/*
 * (C) Copyright 2003
 * Gerry Hamel, geh@ti.com, Texas Instruments
 *
 * (C) Copyright 2006
 * Bryan O'Donoghue, bodonoghue@codehermit.ie
 *
 * SPDX-License-Identifier:	GPL-2.0+
 */

#include <common.h>
#include <config.h>
#include <circbuf.h>
#include <stdio_dev.h>
#include <asm/unaligned.h>
#include <linux/usb/ch9.h>
#include <linux/usb/gadget.h>
#include <linux/usb/cdc.h>
#include <usb_cdc_acm.h>
#include "serial.h"
#include "gadget_chips.h"

#ifdef DEBUG
#define TTYDBG(fmt,args...)\
	serial_printf(fmt,##args)
#else
#define TTYDBG(fmt,args...) do{}while(0)
#endif

#if 1
#define TTYERR(fmt,args...)\
	serial_printf("ERROR![%s] %s %d: "fmt, __FILE__,__FUNCTION__,\
	__LINE__,##args)
#else
#define TTYERR(fmt,args...) do{}while(0)
#endif

unsigned packet_received, packet_sent;
int connected;

#define GFP_ATOMIC ((gfp_t) 0)
#define GFP_KERNEL ((gfp_t) 0)

/*
 * Defines
 */
#define NUM_CONFIGS    1
#define MAX_INTERFACES 2
#define NUM_ENDPOINTS  3
#define ACM_TX_ENDPOINT 3
#define ACM_RX_ENDPOINT 2
#define GSERIAL_TX_ENDPOINT 2
#define GSERIAL_RX_ENDPOINT 1
#define NUM_ACM_INTERFACES 2
#define NUM_GSERIAL_INTERFACES 1
#define CONFIG_USBD_DATA_INTERFACE_STR "Bulk Data Interface"
#define CONFIG_USBD_CTRL_INTERFACE_STR "Control Interface"
#define USB_CONNECT_TIMEOUT (10 * CONFIG_SYS_HZ)
#define DEFAULT_QLEN	2	/* double buffering by default */
#define DRIVER_DESC		"Serial Gadget"
#define USB_BUFSIZ 256

/* peak bulk transfer bits-per-second */
#define	HS_BPS		(13 * 512 * 8 * 1000 * 8)
#define	FS_BPS		(19 *  64 * 1 * 1000 * 8)

static inline int BITRATE(struct usb_gadget *g)
{
	return (g->speed == USB_SPEED_HIGH) ? HS_BPS : FS_BPS;
}

#ifdef CONFIG_USB_GADGET_DUALSPEED
#define	DEVSPEED	USB_SPEED_HIGH

#ifdef CONFIG_USB_TTY_QMULT
#define qmult CONFIG_USB_TTY_QMULT
#else
#define qmult 5
#endif

/* for dual-speed hardware, use deeper queues at highspeed */
#define qlen(gadget) \
	(DEFAULT_QLEN*((gadget->speed == USB_SPEED_HIGH) ? qmult : 1))

static inline int BITRATE(struct usb_gadget *g)
{
	return (g->speed == USB_SPEED_HIGH) ? HS_BPS : FS_BPS;
}

#else	/* full speed (low speed doesn't do bulk) */

#define qmult		1

#define	DEVSPEED	USB_SPEED_FULL

#define qlen(gadget) DEFAULT_QLEN
#endif

#define cdc_active(dev) (dev->cdc)

#define STRING_MANUFACTURER		1
#define STRING_PRODUCT			2
#define STRING_SERIAL			3
#define STRING_DATA			4
#define STRING_CONTROL			5
#define STRING_CDC			6
#define STRING_GSERIAL			7

#define CDC_VENDOR_NUM			0x0525

/*
 * Buffers to hold input and output data
 */
#define USBTTY_BUFFER_SIZE 2048
static circbuf_t usbtty_input;
static circbuf_t usbtty_output;


struct usb_tty_dev {
	struct usb_gadget	*gadget;
	struct usb_request	*req;		/* for control responses */
	struct usb_request	*stat_req;	/* for cdc*/

	u8			config;
	struct usb_ep		*in_ep, *out_ep, *status_ep;
	const struct usb_endpoint_descriptor
				*in, *out, *status;

	struct usb_request	*tx_req, *rx_req;

	unsigned int		tx_qlen;

	unsigned		cdc:1;
	unsigned		suspended:1;
	unsigned		tty_started:1;
};

static struct usb_tty_dev ttydev;
static char RxBuffer[64];

/*
 * Descriptors, Strings, Local variables.
 */

#define DEV_CONFIG_VALUE	1	/* cdc or subset */

/* Standard USB Data Structures */
static struct usb_device_descriptor device_desc = {
	.bLength = sizeof(struct usb_device_descriptor),
	.bDescriptorType =	USB_DT_DEVICE,
	.bcdUSB =		cpu_to_le16(0x0200),
	.bDeviceSubClass =	0x00,
	.bDeviceProtocol =	0x00,
	.bMaxPacketSize0 =	64,
	.idVendor =		0x0000,
	.bcdDevice =		0x0001,
	.iManufacturer =	STR_MANUFACTURER,
	.iProduct =		STR_PRODUCT,
	.iSerialNumber =	STR_SERIAL,
	.bNumConfigurations =	NUM_CONFIGS
};

#if defined(CONFIG_USBD_HS)
static struct usb_qualifier_descriptor qualifier_descriptor = {
	.bLength = sizeof(struct usb_qualifier_descriptor),
	.bDescriptorType =	USB_DT_QUAL,
	.bcdUSB =		cpu_to_le16(0x0200),
	.bDeviceClass =		COMMUNICATIONS_DEVICE_CLASS,
	.bDeviceSubClass =	0x00,
	.bDeviceProtocol =	0x00,
	.bMaxPacketSize0 =	64,
	.bNumConfigurations =	NUM_CONFIGS
};
#endif

static struct usb_otg_descriptor
otg_descriptor = {
	.bLength =		sizeof otg_descriptor,
	.bDescriptorType =	USB_DT_OTG,

	.bmAttributes =		USB_OTG_SRP,
};

static struct usb_config_descriptor
tty_config = {
	.bLength =		sizeof tty_config,
	.bDescriptorType =	USB_DT_CONFIG,

	/* compute wTotalLength on the fly */
	.bNumInterfaces =	2,
	.bConfigurationValue =	DEV_CONFIG_VALUE,
	.iConfiguration =	0,
	.bmAttributes =		USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
	.bMaxPower =		250,
};

/*
 * Static CDC ACM specific descriptors
 */

#ifdef	CONFIG_USB_TTY_CDC
static struct usb_interface_descriptor
control_intf = {
	.bLength =		sizeof control_intf,
	.bDescriptorType =	USB_DT_INTERFACE,

	.bInterfaceNumber =	0,
	/* status endpoint is optional; this may be patched later */
	.bNumEndpoints =	1,
	.bInterfaceClass =	USB_CLASS_COMM,
	.bInterfaceSubClass =	USB_CDC_SUBCLASS_ACM,
	.bInterfaceProtocol =	0,
	.iInterface =		0,
};
#endif

static const struct usb_cdc_header_desc header_desc = {
	.bLength =		sizeof header_desc,
	.bDescriptorType =	USB_DT_CS_INTERFACE,
	.bDescriptorSubType =	USB_CDC_HEADER_TYPE,

	.bcdCDC =		__constant_cpu_to_le16(0x0110),
};

#if defined(CONFIG_USB_TTY_CDC)
static const struct usb_cdc_union_desc union_desc = {
	.bLength =		sizeof union_desc,
	.bDescriptorType =	USB_DT_CS_INTERFACE,
	.bDescriptorSubType =	USB_CDC_UNION_TYPE,

	.bMasterInterface0 =	0,	/* index of control interface */
	.bSlaveInterface0 =	1,	/* index of DATA interface */
};
#endif

static const struct usb_cdc_call_mgmt_descriptor call_mgmt_desc = {
	.bLength =		sizeof call_mgmt_desc,
	.bDescriptorType =	USB_DT_CS_INTERFACE,
	.bDescriptorSubType =	USB_CDC_CALL_MANAGEMENT_TYPE,

	.bmCapabilities =	0x00,
	.bDataInterface =	0x01,
};

static const struct usb_cdc_acm_descriptor acm_desc = {
	.bLength =		sizeof acm_desc,
	.bDescriptorType =	USB_DT_CS_INTERFACE,
	.bDescriptorSubType =	USB_CDC_ACM_TYPE,

	.bmCapabilities =	0x02,
};

#ifndef CONFIG_USB_TTY_CDC

/*
 * "SAFE" loosely follows CDC WMC MDLM, violating the spec in various
 * ways:  data endpoints live in the control interface, there's no data
 * interface, and it's not used to talk to a cell phone radio.
 */

static const struct usb_cdc_mdlm_desc mdlm_desc = {
	.bLength =		sizeof mdlm_desc,
	.bDescriptorType =	USB_DT_CS_INTERFACE,
	.bDescriptorSubType =	USB_CDC_MDLM_TYPE,

	.bcdVersion =		__constant_cpu_to_le16(0x0100),
	.bGUID = {
		0x5d, 0x34, 0xcf, 0x66, 0x11, 0x18, 0x11, 0xd6,
		0xa2, 0x1a, 0x00, 0x01, 0x02, 0xca, 0x9a, 0x7f,
	},
};

/*
 * since "usb_cdc_mdlm_detail_desc" is a variable length structure, we
 * can't really use its struct.  All we do here is say that we're using
 * the submode of "SAFE" which directly matches the CDC Subset.
 */
static const u8 mdlm_detail_desc[] = {
	6,
	USB_DT_CS_INTERFACE,
	USB_CDC_MDLM_DETAIL_TYPE,

	0,	/* "SAFE" */
	0,	/* network control capabilities (none) */
	0,	/* network data capabilities ("raw" encapsulation) */
};

#endif

#if defined(CONFIG_USB_TTY_CDC)

/*
 * include the status endpoint if we can, even where it's optional.
 * use wMaxPacketSize big enough to fit CDC_NOTIFY_SPEED_CHANGE in one
 * packet, to simplify cancellation; and a big transfer interval, to
 * waste less bandwidth.
 *
 * some drivers (like Linux 2.4 cdc-ether!) "need" it to exist even
 * if they ignore the connect/disconnect notifications that real aether
 * can provide.  more advanced cdc configurations might want to support
 * encapsulated commands (vendor-specific, using control-OUT).
 *
 * RNDIS requires the status endpoint, since it uses that encapsulation
 * mechanism for its funky RPC scheme.
 */

#define LOG2_STATUS_INTERVAL_MSEC	5	/* 1 << 5 == 32 msec */
#define STATUS_BYTECOUNT		16	/* 8 byte header + data */

static struct usb_endpoint_descriptor
fs_status_desc = {
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,

	.bEndpointAddress =	USB_DIR_IN,
	.bmAttributes =		USB_ENDPOINT_XFER_INT,
	.wMaxPacketSize =	__constant_cpu_to_le16(STATUS_BYTECOUNT),
	.bInterval =		1 << LOG2_STATUS_INTERVAL_MSEC,
};
#endif

/* ... but the "real" data interface has two bulk endpoints */

static const struct usb_interface_descriptor
data_intf = {
	.bLength =		sizeof data_intf,
	.bDescriptorType =	USB_DT_INTERFACE,

	.bInterfaceNumber =	1,
	.bAlternateSetting =	1,
	.bNumEndpoints =	2,
	.bInterfaceClass =	USB_CLASS_CDC_DATA,
	.bInterfaceSubClass =	0,
	.bInterfaceProtocol =	0,
	.iInterface =		STRING_DATA,
};


#ifndef CONFIG_USB_TTY_CDC

/*
 * "Simple" CDC-subset option is a simple vendor-neutral model that most
 * full speed controllers can handle:  one interface, two bulk endpoints.
 *
 * To assist host side drivers, we fancy it up a bit, and add descriptors
 * so some host side drivers will understand it as a "SAFE" variant.
 */

static const struct usb_interface_descriptor
gserial_data_intf = {
	.bLength =		sizeof gserial_data_intf,
	.bDescriptorType =	USB_DT_INTERFACE,

	.bInterfaceNumber =	0,
	.bAlternateSetting =	0,
	.bNumEndpoints =	2,
	.bInterfaceClass =      USB_CLASS_COMM,
	.bInterfaceSubClass =	USB_CDC_SUBCLASS_MDLM,
	.bInterfaceProtocol =	0,
	.iInterface =		STRING_DATA,
};

#endif

static struct usb_endpoint_descriptor
fs_source_desc = {
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,

	.bEndpointAddress =	USB_DIR_IN,
	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
	.wMaxPacketSize =	__constant_cpu_to_le16(64),
};

static struct usb_endpoint_descriptor
fs_sink_desc = {
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,

	.bEndpointAddress =	USB_DIR_OUT,
	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
	.wMaxPacketSize =	__constant_cpu_to_le16(64),
};

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

/* descriptors that are built on-demand */

static char manufacturer[50];
static char product_desc[40] = DRIVER_DESC;
static char serial_number[20] = "12345678";

/* static strings, in UTF-8 */
static struct usb_string		strings[] = {
	{ STRING_MANUFACTURER,	manufacturer, },
	{ STRING_PRODUCT,	product_desc, },
	{ STRING_SERIAL,	serial_number, },
	{ STRING_DATA,		"Bulk Data", },
#ifdef	CONFIG_USB_TTY_CDC
	{ STRING_CDC,		"CDC ACM", },
	{ STRING_CONTROL,	"CDC Communications Control", },
#else
	{ STRING_GSERIAL,	"Generic Serial", },
#endif
	{  }		/* end of list */
};

static struct usb_gadget_strings	stringtab = {
	.language	= 0x0409,	/* en-us */
	.strings	= strings,
};

static struct rs232_emu rs232_desc={
		.dter		=	115200,
		.stop_bits	=	0x00,
		.parity		=	0x00,
		.data_bits	=	0x08
};

DEFINE_CACHE_ALIGN_BUFFER(u8, control_req, 8);

#if defined(CONFIG_USB_TTY_CDC)
DEFINE_CACHE_ALIGN_BUFFER(u8, status_req, STATUS_BYTECOUNT);
#endif

static const struct usb_descriptor_header *fs_tty_function[11] = {
	(struct usb_descriptor_header *) &otg_descriptor,
#ifdef CONFIG_USB_TTY_CDC
	/* "cdc" mode descriptors */
	(struct usb_descriptor_header *) &control_intf,
	(struct usb_descriptor_header *) &header_desc,
	(struct usb_descriptor_header *) &union_desc,
	(struct usb_descriptor_header *) &call_mgmt_desc,
	(struct usb_descriptor_header *) &acm_desc,
	/* NOTE: status endpoint may need to be removed */
	(struct usb_descriptor_header *) &fs_status_desc,
	/* data interface, with altsetting */
	(struct usb_descriptor_header *) &data_intf,
	(struct usb_descriptor_header *) &fs_source_desc,
	(struct usb_descriptor_header *) &fs_sink_desc,
	NULL,
#endif /* CONFIG_USB_TTY_CDC */
};

static inline void fs_gserial_descriptors(void)
{
#ifndef CONFIG_USB_TTY_CDC
	/* behavior is "CDC Subset"; extra descriptors say "SAFE" */
	fs_tty_function[1] = (struct usb_descriptor_header *) &gserial_data_intf;
	fs_tty_function[2] = (struct usb_descriptor_header *) &header_desc;
	fs_tty_function[3] = (struct usb_descriptor_header *) &mdlm_desc;
	fs_tty_function[4] = (struct usb_descriptor_header *) &mdlm_detail_desc;
	fs_tty_function[5] = (struct usb_descriptor_header *) &call_mgmt_desc;
	fs_tty_function[6] = (struct usb_descriptor_header *) &acm_desc;
	fs_tty_function[7] = (struct usb_descriptor_header *) &fs_source_desc;
	fs_tty_function[8] = (struct usb_descriptor_header *) &fs_sink_desc;
	fs_tty_function[9] = NULL;
#else
	fs_tty_function[1] = NULL;
#endif
}

static struct usb_endpoint_descriptor
hs_source_desc = {
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,

	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
	.wMaxPacketSize =	__constant_cpu_to_le16(512),
};

static struct usb_endpoint_descriptor
hs_sink_desc = {
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,

	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
	.wMaxPacketSize =	__constant_cpu_to_le16(512),
};

#ifdef CONFIG_USB_TTY_CDC
static struct usb_endpoint_descriptor
hs_status_desc = {
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,

	.bEndpointAddress =	USB_DIR_IN,
	.bmAttributes =		USB_ENDPOINT_XFER_INT,
	.wMaxPacketSize =	__constant_cpu_to_le16(STATUS_BYTECOUNT),
	.bInterval =		1 << LOG2_STATUS_INTERVAL_MSEC,
};
#endif

static struct usb_qualifier_descriptor
dev_qualifier = {
	.bLength =		sizeof dev_qualifier,
	.bDescriptorType =	USB_DT_DEVICE_QUALIFIER,

	.bcdUSB =		__constant_cpu_to_le16(0x0200),
	.bDeviceClass =		USB_CLASS_COMM,

	.bNumConfigurations =	1,
};

static const struct usb_descriptor_header *hs_tty_function[11] = {
	(struct usb_descriptor_header *) &otg_descriptor,
#ifdef CONFIG_USB_TTY_CDC
	/* "cdc" mode descriptors */
	(struct usb_descriptor_header *) &control_intf,
	(struct usb_descriptor_header *) &header_desc,
	(struct usb_descriptor_header *) &union_desc,
	(struct usb_descriptor_header *) &call_mgmt_desc,
	(struct usb_descriptor_header *) &acm_desc,
	/* NOTE: status endpoint may need to be removed */
	(struct usb_descriptor_header *) &hs_status_desc,
	/* data interface, with altsetting */
	(struct usb_descriptor_header *) &data_intf,
	(struct usb_descriptor_header *) &hs_source_desc,
	(struct usb_descriptor_header *) &hs_sink_desc,
	NULL,
#endif /* CONFIG_USB_TTY_CDC */
};

static inline void hs_gserial_descriptors(void)
{
#ifndef CONFIG_USB_TTY_CDC
	/* behavior is "CDC Subset"; extra descriptors say "SAFE" */
	hs_tty_function[1] = (struct usb_descriptor_header *) &gserial_data_intf;
	hs_tty_function[2] = (struct usb_descriptor_header *) &header_desc;
	hs_tty_function[3] = (struct usb_descriptor_header *) &mdlm_desc;
	hs_tty_function[4] = (struct usb_descriptor_header *) &mdlm_detail_desc;
	hs_tty_function[5] = (struct usb_descriptor_header *) &call_mgmt_desc;
	hs_tty_function[6] = (struct usb_descriptor_header *) &acm_desc;
	hs_tty_function[7] = (struct usb_descriptor_header *) &hs_source_desc;
	hs_tty_function[8] = (struct usb_descriptor_header *) &hs_sink_desc;
	hs_tty_function[9] = NULL;
#else
	hs_tty_function[1] = NULL;
#endif
}

/*
 * Emulating them in eth_bind:
 * static ushort idVendor;
 * static ushort idProduct;
 */

#if defined(CONFIG_USBNET_MANUFACTURER)
static char *iManufacturer = CONFIG_USBTTY_MANUFACTURER;
#else
static char *iManufacturer = "U-boot";
#endif

/* These probably need to be configurable. */
static ushort bcdDevice;
static char *iProduct;
static char *iSerialNumber;

static const char driver_desc[] = DRIVER_DESC;

static inline struct usb_endpoint_descriptor *
ep_desc(struct usb_gadget *g, struct usb_endpoint_descriptor *hs,
		struct usb_endpoint_descriptor *fs)
{
	if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
		return hs;
	return fs;
}

/*
 * Static Function Prototypes
 */

static int usbtty_configured (void);
static int write_buffer (circbuf_t * buf);
static int fill_buffer (circbuf_t * buf);

/*
 * Test whether a character is in the RX buffer
 */

int usbtty_tstc (void)
{
	usb_gadget_handle_interrupts();
	fill_buffer(&usbtty_input);
	return (usbtty_input.size > 0);
}

/*
 * Read a single byte from the usb client port. Returns 1 on success, 0
 * otherwise. When the function is succesfull, the character read is
 * written into its argument c.
 */

int usbtty_getc (void)
{
	char c;

	while (usbtty_input.size <= 0) {
		usb_gadget_handle_interrupts();
		fill_buffer (&usbtty_input);
	}

	buf_pop (&usbtty_input, &c, 1);

	return c;
}

/*
 * Output a single byte to the usb client port.
 */
void usbtty_putc (const char c)
{
	if (!usbtty_configured ())
		return;

	buf_push (&usbtty_output, &c, 1);
	/* If \n, also do \r */
	if (c == '\n')
		buf_push (&usbtty_output, "\r", 1);

	/* Poll at end to handle new data... */
	if ((usbtty_output.size + 2) >= usbtty_output.totalsize) {
		write_buffer(&usbtty_output);
		usb_gadget_handle_interrupts();
	}
}

/* usbtty_puts() helper function for finding the next '\n' in a string */
static int next_nl_pos (const char *s)
{
	int i;

	for (i = 0; s[i] != '\0'; i++) {
		if (s[i] == '\n')
			return i;
	}
	return i;
}

/*
 * Output a string to the usb client port - implementing flow control
 */

static void __usbtty_puts (const char *str, int len)
{
	int maxlen = usbtty_output.totalsize;
	int space, n;

	/* break str into chunks < buffer size, if needed */
	while (len > 0) {

		space = maxlen - usbtty_output.size;
		/* Empty buffer here, if needed, to ensure space... */
		if (space) {
			write_buffer (&usbtty_output);
			usb_gadget_handle_interrupts();

			n = MIN (space, MIN (len, maxlen));
			buf_push (&usbtty_output, str, n);

			str += n;
			len -= n;
		}
	}
}

void usbtty_puts (const char *str)
{
	int n;
	int len;

	if (!usbtty_configured ())
		return;

	len = strlen (str);
	/* add '\r' for each '\n' */
	while (len > 0) {
		n = next_nl_pos (str);

		if (str[n] == '\n') {
			__usbtty_puts (str, n + 1);
			__usbtty_puts ("\r", 1);
			str += (n + 1);
			len -= (n + 1);
		} else {
			/* No \n found.	 All done. */
			__usbtty_puts (str, n);
			break;
		}
	}

	/* Poll at end to handle new data... */
	write_buffer(&usbtty_output);
	usb_gadget_handle_interrupts();
}

static void tx_complete(struct usb_ep *_ep, struct usb_request *req)
{
	packet_sent = 1;
	TTYDBG("%s: status %d\n", __func__, req->status);
}

static int write_buffer (circbuf_t * buf)
{
	if (!usbtty_configured ()) {
		return 0;
	}

	if (buf->size) {
		struct usb_tty_dev *dev = &ttydev;
		char dest[64];

		int popnum, popped;
		int total = 0;
		int retval;
		unsigned long ts;
		unsigned long timeout = USB_CONNECT_TIMEOUT;

		/* Break buffer into urb sized pieces,
		 * and link each to the endpoint
		 */
		while (buf->size > 0) {
			popnum = MIN (sizeof(dest), buf->size);
			if (popnum == 0)
				break;

			popped = buf_pop (buf, dest, popnum);
			if (popped == 0)
				break;
			total += popped;
			packet_sent = 0;

			dev->tx_req->buf = dest;
			dev->tx_req->length = popped;
			dev->tx_req->complete = tx_complete;
			retval = usb_ep_queue(dev->in_ep, dev->tx_req, GFP_ATOMIC);

			if (!retval)
				TTYDBG("%s: packet queued\n", __func__);
			else
				TTYDBG("%s: fail %d\n", __func__, retval);
			ts = get_timer(0);
			while (!packet_sent) {
				if (get_timer(ts) > timeout) {
					serial_printf("timeout sending packets to usb serial\n");
					return -1;
				}
				usb_gadget_handle_interrupts();
			}
		}/* end while */
		return total;
	}

	return 0;
}

static void rx_complete(struct usb_ep *ep, struct usb_request *req)
{
	TTYDBG("%s: status %d\n", __func__, req->status);
	packet_received = 1;
}

static int rx_submit(struct usb_tty_dev *dev, struct usb_request *req,
				gfp_t gfp_flags)
{
	int			retval = -ENOMEM;

	/*
	 * Padding up to RX_EXTRA handles minor disagreements with host.
	 * Normally we use the USB "terminate on short read" convention;
	 * so allow up to (N*maxpacket), since that memory is normally
	 * already allocated.  Some hardware doesn't deal well with short
	 * reads (e.g. DMA must be N*maxpacket), so for now don't trim a
	 * byte off the end (to force hardware errors on overflow).
	 *
	 * RNDIS uses internal framing, and explicitly allows senders to
	 * pad to end-of-packet.  That's potentially nice for speed,
	 * but means receivers can't recover synch on their own.
	 */

	if (!req)
		return -EINVAL;

	/*
	 * Some platforms perform better when IP packets are aligned,
	 * but on at least one, checksumming fails otherwise.  Note:
	 * RNDIS headers involve variable numbers of LE32 values.
	 */

	req->buf = (u8 *)RxBuffer;
	req->length = 1;
	req->complete = rx_complete;

	retval = usb_ep_queue(dev->out_ep, req, gfp_flags);

	if (retval)
		error("rx submit --> %d", retval);

	return retval;
}

static int fill_buffer (circbuf_t * buf)
{
	struct usb_tty_dev *dev = &ttydev;
	int nb = 0;

	if (packet_received) {
		TTYDBG("%s received %d\n", __func__, dev->rx_req->length);
		if(dev->rx_req) {
			nb = dev->rx_req->length;
			buf_push (buf, RxBuffer, nb);
		}
		packet_received = 0;
		rx_submit(dev, dev->rx_req, 0);

		return nb;
	}
	return 0;
}

static int usbtty_configured (void)
{
	return ttydev.tty_started;
}

static int alloc_requests(struct usb_tty_dev *dev, unsigned n, gfp_t gfp_flags)
{

	dev->tx_req = usb_ep_alloc_request(dev->in_ep, 0);
	if (!dev->tx_req)
		goto fail1;

	dev->rx_req = usb_ep_alloc_request(dev->out_ep, 0);

	if (!dev->rx_req)
		goto fail2;

	return 0;

fail2:
	usb_ep_free_request(dev->in_ep, dev->tx_req);
fail1:
	error("can't alloc requests");
	return -1;
}

/*
 * one config, two interfaces:  control, data.
 * complications: class descriptors, and an altsetting.
 */
static int
config_buf(struct usb_gadget *g, u8 *buf, u8 type, unsigned index, int is_otg)
{
	int					len;
	const struct usb_config_descriptor	*config;
	const struct usb_descriptor_header	**function;
	int					hs = 0;

	if (gadget_is_dualspeed(g)) {
		hs = (g->speed == USB_SPEED_HIGH);
		if (type == USB_DT_OTHER_SPEED_CONFIG)
			hs = !hs;
	}
#define which_fn(t)	(hs ? hs_ ## t ## _function : fs_ ## t ## _function)

	if (index >= device_desc.bNumConfigurations)
		return -EINVAL;

	config = &tty_config;
	function = which_fn(tty);

	/* for now, don't advertise srp-only devices */
	if (!is_otg)
		function++;

	len = usb_gadget_config_buf(config, buf, USB_BUFSIZ, function);
	if (len < 0)
		return len;
	((struct usb_config_descriptor *) buf)->bDescriptorType = type;
	return len;
}

static int alloc_requests(struct usb_tty_dev *dev, unsigned n, gfp_t gfp_flags);

static int
set_tty_config(struct usb_tty_dev *dev, gfp_t gfp_flags)
{
	int					result = 0;
	struct usb_gadget			*gadget = dev->gadget;

#if defined(CONFIG_USB_TTY_CDC)
	/* status endpoint used for RNDIS and (optionally) CDC */
	if (dev->status_ep) {
		dev->status = ep_desc(gadget, &hs_status_desc,
						&fs_status_desc);
		dev->status_ep->driver_data = dev;

		result = usb_ep_enable(dev->status_ep, dev->status);
		if (result != 0) {
			TTYDBG("enable %s --> %d\n",
				dev->status_ep->name, result);
			goto done;
		}
	}
#endif

	dev->in = ep_desc(gadget, &hs_source_desc, &fs_source_desc);
	dev->in_ep->driver_data = dev;

	dev->out = ep_desc(gadget, &hs_sink_desc, &fs_sink_desc);
	dev->out_ep->driver_data = dev;

	/*
	 * With CDC,  the host isn't allowed to use these two data
	 * endpoints in the default altsetting for the interface.
	 * so we don't activate them yet.  Reset from SET_INTERFACE.
	 *
	 * Strictly speaking RNDIS should work the same: activation is
	 * a side effect of setting a packet filter.  Deactivation is
	 * from REMOTE_NDIS_HALT_MSG, reset from REMOTE_NDIS_RESET_MSG.
	 */
	if (!dev->cdc) {
		result = usb_ep_enable(dev->in_ep, dev->in);
		if (result != 0) {
			TTYDBG("enable %s --> %d\n",
				dev->in_ep->name, result);
			goto done;
		}

		result = usb_ep_enable(dev->out_ep, dev->out);
		if (result != 0) {
			TTYDBG("enable %s --> %d\n",
				dev->out_ep->name, result);
			goto done;
		}
	}

done:
	if (result == 0)
		result = alloc_requests(dev, qlen(gadget), gfp_flags);

	/* on error, disable any endpoints  */
	if (result < 0) {
		if (cdc_active(dev) && dev->status_ep)
			(void) usb_ep_disable(dev->status_ep);
		dev->status = NULL;
		(void) usb_ep_disable(dev->in_ep);
		(void) usb_ep_disable(dev->out_ep);
		dev->in = NULL;
		dev->out = NULL;
	} else if (!cdc_active(dev)) {
		/*
		 * activate non-CDC configs right away
		 * this isn't strictly according to the RNDIS spec
		 */
	}

	/* caller is responsible for cleanup on error */
	return result;
}

static void tty_reset_config(struct usb_tty_dev *dev)
{
	if (dev->config == 0)
		return;

	TTYDBG("%s\n", __func__);

	/*
	 * disable endpoints, forcing (synchronous) completion of
	 * pending i/o.  then free the requests.
	 */

	if (dev->in) {
		usb_ep_disable(dev->in_ep);
		if (dev->tx_req) {
			usb_ep_free_request(dev->in_ep, dev->tx_req);
			dev->tx_req = NULL;
		}
	}
	if (dev->out) {
		usb_ep_disable(dev->out_ep);
		if (dev->rx_req) {
			usb_ep_free_request(dev->out_ep, dev->rx_req);
			dev->rx_req = NULL;
		}
	}
	if (dev->status)
		usb_ep_disable(dev->status_ep);

	dev->config = 0;
}

/*
 * change our operational config.  must agree with the code
 * that returns config descriptors, and altsetting code.
 */
static int tty_set_config(struct usb_tty_dev *dev, unsigned number,
				gfp_t gfp_flags)
{
	int			result = 0;
	struct usb_gadget	*gadget = dev->gadget;

	if (gadget_is_sa1100(gadget)
			&& dev->config
			&& dev->tx_qlen != 0) {
		/* tx fifo is full, but we can't clear it...*/
		error("can't change configurations");
		return -ESPIPE;
	}
	tty_reset_config(dev);

	switch (number) {
	case DEV_CONFIG_VALUE:
		result = set_tty_config(dev, gfp_flags);
		break;
	default:
		result = -EINVAL;
		/* FALL THROUGH */
	case 0:
		break;
	}

	if (result) {
		if (number)
			tty_reset_config(dev);
		usb_gadget_vbus_draw(dev->gadget,
				gadget_is_otg(dev->gadget) ? 8 : 100);
	} else {
		char *speed;
		unsigned power;

		power = 2 * tty_config.bMaxPower;
		usb_gadget_vbus_draw(dev->gadget, power);

		switch (gadget->speed) {
		case USB_SPEED_FULL:
			speed = "full"; break;
#ifdef CONFIG_USB_GADGET_DUALSPEED
		case USB_SPEED_HIGH:
			speed = "high"; break;
#endif
		default:
			speed = "?"; break;
		}

		dev->config = number;
		printf("%s speed config #%d: %d mA, %s, using %s\n",
		       speed, number, power, driver_desc,
		       (cdc_active(dev)?"CDC ACM": "Generic Serial"));
	}
	return result;
}

static void tty_disconnect(struct usb_gadget *gadget)
{
	ttydev.tty_started = 0;
	tty_reset_config(get_gadget_data(gadget));
}

static void tty_suspend(struct usb_gadget *gadget)
{
	/* Not used */
}

static void tty_resume(struct usb_gadget *gadget)
{
	/* Not used */
}

static void tty_status_complete(struct usb_ep *ep, struct usb_request *req)
{
	struct usb_cdc_notification	*event = req->buf;
	int				value = req->status;
	struct usb_tty_dev			*dev = ep->driver_data;

	/* issue the second notification if host reads the first */
	if (event->bNotificationType == USB_CDC_NOTIFY_NETWORK_CONNECTION
			&& value == 0) {
		__le32	*data = req->buf + sizeof *event;

		event->bmRequestType = 0xA1;
		event->bNotificationType = USB_CDC_NOTIFY_SPEED_CHANGE;
		event->wValue = __constant_cpu_to_le16(0);
		event->wIndex = __constant_cpu_to_le16(1);
		event->wLength = __constant_cpu_to_le16(8);

		/* SPEED_CHANGE data is up/down speeds in bits/sec */
		data[0] = data[1] = cpu_to_le32(BITRATE(dev->gadget));

		req->length = STATUS_BYTECOUNT;
		value = usb_ep_queue(ep, req, GFP_ATOMIC);
		debug("send SPEED_CHANGE --> %d\n", value);
		if (value == 0)
			return;
	} else if (value != -ECONNRESET) {
		debug("event %02x --> %d\n",
			event->bNotificationType, value);
		if (event->bNotificationType ==
				USB_CDC_NOTIFY_SPEED_CHANGE) {
			ttydev.tty_started = 1;
			printf("USB serial connected!\n");
		}
	}
	req->context = NULL;
}

static void issue_start_status(struct usb_tty_dev *dev)
{
	struct usb_request		*req = dev->stat_req;
	struct usb_cdc_notification	*event;
	int				value;

	/*
	 * flush old status
	 *
	 * FIXME ugly idiom, maybe we'd be better with just
	 * a "cancel the whole queue" primitive since any
	 * unlink-one primitive has way too many error modes.
	 * here, we "know" toggle is already clear...
	 *
	 * FIXME iff req->context != null just dequeue it
	 */
	usb_ep_disable(dev->status_ep);
	usb_ep_enable(dev->status_ep, dev->status);

	/*
	 * 3.8.1 says to issue first NETWORK_CONNECTION, then
	 * a SPEED_CHANGE.  could be useful in some configs.
	 */
	event = req->buf;
	event->bmRequestType = 0xA1;
	event->bNotificationType = USB_CDC_NOTIFY_NETWORK_CONNECTION;
	event->wValue = __constant_cpu_to_le16(1);	/* connected */
	event->wIndex = __constant_cpu_to_le16(1);
	event->wLength = 0;

	req->length = sizeof *event;
	req->complete = tty_status_complete;
	req->context = dev;

	value = usb_ep_queue(dev->status_ep, req, GFP_ATOMIC);
	if (value < 0)
		debug("status buf queue --> %d\n", value);
}

static void tty_setup_complete(struct usb_ep *ep, struct usb_request *req)
{
	if (req->status || req->actual != req->length) {
		TTYDBG("setup complete --> %d, %d/%d\n",
				req->status, req->actual, req->length);
		usb_ep_queue(ep, req, GFP_ATOMIC);
	}
	if (connected) {
		req->zero = 1;
		req->length = 0;
		usb_ep_queue(ep, req, GFP_ATOMIC);
		connected = 0;
		ttydev.tty_started = 1;
		printf("USB serial connected!\n");
	}
}

/*
 * The setup() callback implements all the ep0 functionality that's not
 * handled lower down.  CDC has a number of less-common features:
 *
 *  - two interfaces:  control, and ethernet data
 *  - Ethernet data interface has two altsettings:  default, and active
 *  - class-specific descriptors for the control interface
 *  - class-specific control requests
 */
static int
tty_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
{
	struct usb_tty_dev	*dev = get_gadget_data(gadget);
	struct usb_request	*req = dev->req;
	int			value = -EOPNOTSUPP;
	u16			wIndex = le16_to_cpu(ctrl->wIndex);
	u16			wValue = le16_to_cpu(ctrl->wValue);
	u16			wLength = le16_to_cpu(ctrl->wLength);

	/*
	 * descriptors just go into the pre-allocated ep0 buffer,
	 * while config change events may enable network traffic.
	 */

	req->complete = tty_setup_complete;
	switch (ctrl->bRequest) {

	case USB_REQ_GET_DESCRIPTOR:
		if (ctrl->bRequestType != USB_DIR_IN)
			break;
		switch (wValue >> 8) {

		case USB_DT_DEVICE:
			value = min(wLength, (u16) sizeof device_desc);
			memcpy(req->buf, &device_desc, value);
			break;
		case USB_DT_DEVICE_QUALIFIER:
			if (!gadget_is_dualspeed(gadget))
				break;
			value = min(wLength, (u16) sizeof dev_qualifier);
			memcpy(req->buf, &dev_qualifier, value);
			break;

		case USB_DT_OTHER_SPEED_CONFIG:
			if (!gadget_is_dualspeed(gadget))
				break;
			/* FALLTHROUGH */
		case USB_DT_CONFIG:
			value = config_buf(gadget, req->buf,
					wValue >> 8,
					wValue & 0xff,
					gadget_is_otg(gadget));
			if (value >= 0)
				value = min(wLength, (u16) value);
			break;

		case USB_DT_STRING:
			value = usb_gadget_get_string(&stringtab,
					wValue & 0xff, req->buf);

			if (value >= 0)
				value = min(wLength, (u16) value);

			break;
		}
		break;

	case USB_REQ_SET_CONFIGURATION:
		if (ctrl->bRequestType != 0)
			break;
		if (gadget->a_hnp_support)
			TTYDBG("HNP available\n");
		else if (gadget->a_alt_hnp_support)
			TTYDBG("HNP needs a different root port\n");
		value = tty_set_config(dev, wValue, GFP_ATOMIC);
		break;
	case USB_REQ_GET_CONFIGURATION:
		if (ctrl->bRequestType != USB_DIR_IN)
			break;
		*(u8 *)req->buf = dev->config;
		value = min(wLength, (u16) 1);
		break;

	case USB_REQ_SET_INTERFACE:
		if (ctrl->bRequestType != USB_RECIP_INTERFACE
				|| !dev->config
				|| wIndex > 1)
			break;
		if (!cdc_active(dev) && wIndex != 0)
			break;

		/*
		 * PXA hardware partially handles SET_INTERFACE;
		 * we need to kluge around that interference.
		 */
		if (gadget_is_pxa(gadget)) {
			value = tty_set_config(dev, DEV_CONFIG_VALUE,
					       GFP_ATOMIC);
			/*
			 * PXA25x driver use non-CDC ethernet gadget.
			 * But only _CDC and _RNDIS code can signalize
			 * that network is working. So we signalize it
			 * here.
			 */
			ttydev.tty_started = 1;
			TTYDBG("USB connected!\n");
			goto done_set_intf;
		}
#ifdef CONFIG_USB_TTY_CDC
		switch (wIndex) {
		case 0:		/* control/master intf */
			if (wValue != 0)
				break;
			if (dev->status) {
				usb_ep_disable(dev->status_ep);
				usb_ep_enable(dev->status_ep, dev->status);
			}

			value = 0;
			break;
		case 1:		/* data intf */
			if (wValue > 1)
				break;
			usb_ep_disable(dev->in_ep);
			usb_ep_disable(dev->out_ep);

			/*
			 * CDC requires the data transfers not be done from
			 * the default interface setting ... also, setting
			 * the non-default interface resets filters etc.
			 */
			if (wValue == 1) {
				if (!cdc_active(dev))
					break;
				usb_ep_enable(dev->in_ep, dev->in);
				usb_ep_enable(dev->out_ep, dev->out);
				if (dev->status)
					issue_start_status(dev);
			}
			value = 0;
			break;
		}
#else
		/*
		 * FIXME this is wrong, as is the assumption that
		 * all non-PXA hardware talks real CDC ...
		 */
		TTYDBG("set_interface ignored!\n");
#endif /* CONFIG_USB_ETH_CDC */

done_set_intf:
		break;
	case USB_REQ_GET_INTERFACE:
		if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE)
				|| !dev->config
				|| wIndex > 1)
			break;
		if (!cdc_active(dev) && wIndex != 0)
			break;

		/* for CDC, iff carrier is on, data interface is active. */
		if (wIndex != 1)
			*(u8 *)req->buf = 0;
		else {
			/* *(u8 *)req->buf = netif_carrier_ok (dev->net) ? 1 : 0; */
			/* carrier always ok ...*/
			*(u8 *)req->buf = 1 ;
		}
		value = min(wLength, (u16) 1);
		break;
	case ACM_SEND_ENCAPSULATED_COMMAND :	/* Required */
		value = 0;
		break;
	case ACM_SET_CONTROL_LINE_STATE:	/* Implies DTE ready */
		value = wLength;
		break;
	case ACM_SET_LINE_ENCODING :		/* DTE stop/parity bits
						 * per character */
		if (!ttydev.tty_started) {
			usb_ep_enable(dev->in_ep, dev->in);
			usb_ep_enable(dev->out_ep, dev->out);
			if (dev->status)
				issue_start_status(dev);
		}
		value = wLength;
		connected = 1;
		break;
	case ACM_GET_ENCAPSULATED_RESPONSE :	/* request response */
		value = wLength;
		break;
	case ACM_GET_LINE_ENCODING :		/* request DTE rate,
						 * stop/parity bits */
		memcpy (req->buf , &rs232_desc, sizeof(rs232_desc));
		value = sizeof(rs232_desc);
		
		break;
		
	default:
		TTYDBG("unknown control req%02x.%02x v%04x i%04x l%d\n",
			ctrl->bRequestType, ctrl->bRequest,
			wValue, wIndex, wLength);
	}

	/* respond with data transfer before status phase? */
	if (value >= 0) {
		TTYDBG("respond with data transfer before status phase\n");
		req->length = value;
		req->zero = value < wLength
				&& (value % gadget->ep0->maxpacket) == 0;
		value = usb_ep_queue(gadget->ep0, req, GFP_ATOMIC);
		if (value < 0) {
			TTYDBG("ep_queue --> %d\n", value);
			req->status = 0;
			tty_setup_complete(gadget->ep0, req);
		}
	}

	/* host either stalls (value < 0) or reports success */
	return value;
}

static void tty_unbind(struct usb_gadget *gadget)
{
	struct usb_tty_dev	*dev = get_gadget_data(gadget);

	TTYDBG("%s...\n", __func__);

	/* we've already been disconnected ... no i/o is active */
	if (dev->req) {
		usb_ep_free_request(gadget->ep0, dev->req);
		dev->req = NULL;
	}
	if (dev->stat_req) {
		usb_ep_free_request(dev->status_ep, dev->stat_req);
		dev->stat_req = NULL;
	}

	if (dev->tx_req) {
		usb_ep_free_request(dev->in_ep, dev->tx_req);
		dev->tx_req = NULL;
	}

	if (dev->rx_req) {
		usb_ep_free_request(dev->out_ep, dev->rx_req);
		dev->rx_req = NULL;
	}

/*	unregister_netdev (dev->net);*/
/*	free_netdev(dev->net);*/

	dev->gadget = NULL;
	set_gadget_data(gadget, NULL);
}

static int tty_bind(struct usb_gadget *gadget)
{
	struct usb_tty_dev	*dev = &ttydev;
	u8			cdc = 1;
	struct usb_ep		*in_ep, *out_ep, *status_ep = NULL;
	int			gcnum;
	int			status = -ENOMEM;

	/* these flags are only ever cleared; compiler take note */
#ifndef	CONFIG_USB_TTY_CDC
	cdc = 0;
#endif
	/*
	 * Because most host side USB stacks handle CDC Ethernet, that
	 * standard protocol is _strongly_ preferred for interop purposes.
	 * (By everyone except Microsoft.)
	 */
	if (gadget_is_pxa(gadget)) {
		/* pxa doesn't support altsettings */
		cdc = 0;
	} else if (gadget_is_sh(gadget)) {
		/* sh doesn't support multiple interfaces or configs */
		cdc = 0;
	} else if (gadget_is_sa1100(gadget)) {
		/*
		 * sa1100 CAN do CDC, without status endpoint ... we use
		 * non-CDC to be compatible with ARM Linux-2.4 "usb-eth".
		 */
		cdc = 0;
	}

	gcnum = usb_gadget_controller_number(gadget);
	if (gcnum < 0) {
		/*
		 * can't assume CDC works.  don't want to default to
		 * anything less functional on CDC-capable hardware,
		 * so we fail in this case.
		 */
		error("controller '%s' not recognized",
			gadget->name);
		return -ENODEV;
	}

	/*
	 * If there's an RNDIS configuration, that's what Windows wants to
	 * be using ... so use these product IDs here and in the "linux.inf"
	 * needed to install MSFT drivers.  Current Linux kernels will use
	 * the second configuration if it's CDC Ethernet, and need some help
	 * to choose the right configuration otherwise.
	 */
	if (cdc == 0) {
#if defined(CONFIG_USB_GS_VENDOR_ID) && defined(CONFIG_USB_GS_PRODUCT_ID)
		device_desc.idVendor =
			__constant_cpu_to_le16(CONFIG_USB_GS_VENDOR_ID);
		device_desc.idProduct =
			__constant_cpu_to_le16(CONFIG_USB_GS_PRODUCT_ID);
#else
		device_desc.idVendor =
			__constant_cpu_to_le16(CONFIG_USBD_VENDORID);
		device_desc.idProduct =
			__constant_cpu_to_le16(CONFIG_USBD_PRODUCTID_GSERIAL);
#endif
		sprintf(product_desc, "GenericSerial/%s", driver_desc);

	/*
	 * CDC subset ... recognized by Linux since 2.4.10, but Windows
	 * drivers aren't widely available.  (That may be improved by
	 * supporting one submode of the "SAFE" variant of MDLM.)
	 */
	} else {
#if defined(CONFIG_USB_CDC_VENDOR_ID) && defined(CONFIG_USB_CDC_PRODUCT_ID)
		device_desc.idVendor = cpu_to_le16(CONFIG_USB_CDC_VENDOR_ID);
		device_desc.idProduct = cpu_to_le16(CONFIG_USB_CDC_PRODUCT_ID);
#else
		device_desc.idVendor =
				__constant_cpu_to_le16(CONFIG_USBD_VENDORID);
		device_desc.idProduct =
				__constant_cpu_to_le16(CONFIG_USBD_PRODUCTID_CDCACM);
#endif
	}
	/* support optional vendor/distro customization */
	if (bcdDevice)
		device_desc.bcdDevice = cpu_to_le16(bcdDevice);
	if (iManufacturer)
		strcpy(manufacturer, iManufacturer);
	if (iProduct)
		strcpy(product_desc, iProduct);
	if (iSerialNumber) {
		device_desc.iSerialNumber = STRING_SERIAL,
		strcpy(serial_number, iSerialNumber);
	}

	/* all we really need is bulk IN/OUT */
	usb_ep_autoconfig_reset(gadget);
	in_ep = usb_ep_autoconfig(gadget, &fs_source_desc);
	if (!in_ep) {
autoconf_fail:
		error("can't autoconfigure on %s\n",
			gadget->name);
		return -ENODEV;
	}
	in_ep->driver_data = in_ep;	/* claim */

	out_ep = usb_ep_autoconfig(gadget, &fs_sink_desc);
	if (!out_ep)
		goto autoconf_fail;
	out_ep->driver_data = out_ep;	/* claim */

#if defined(CONFIG_USB_TTY_CDC)
	/*
	 * CDC Ethernet control interface doesn't require a status endpoint.
	 * Since some hosts expect one, try to allocate one anyway.
	 */
	if (cdc) {
		status_ep = usb_ep_autoconfig(gadget, &fs_status_desc);
		if (status_ep) {
			status_ep->driver_data = status_ep;	/* claim */
#ifdef CONFIG_USB_TTY_CDC
		} else if (cdc) {
			control_intf.bNumEndpoints = 0;
			/* FIXME remove endpoint from descriptor list */
#endif
		}
	}
#endif

	/* one config:  cdc, else minimal subset */
	if (!cdc) {
		tty_config.bNumInterfaces = 1;
		tty_config.iConfiguration = STRING_GSERIAL;

		/*
		 * use functions to set these up, in case we're built to work
		 * with multiple controllers and must override CDC Ethernet.
		 */
		fs_gserial_descriptors();
		hs_gserial_descriptors();
	}

	device_desc.bMaxPacketSize0 = gadget->ep0->maxpacket;
	usb_gadget_set_selfpowered(gadget);

	if (gadget_is_dualspeed(gadget)) {
		if (!cdc)
			dev_qualifier.bDeviceClass = USB_CLASS_VENDOR_SPEC;

		/* assumes ep0 uses the same value for both speeds ... */
		dev_qualifier.bMaxPacketSize0 = device_desc.bMaxPacketSize0;

		/* and that all endpoints are dual-speed */
		hs_source_desc.bEndpointAddress =
				fs_source_desc.bEndpointAddress;
		hs_sink_desc.bEndpointAddress =
				fs_sink_desc.bEndpointAddress;
#if defined(CONFIG_USB_TTY_CDC)
		if (status_ep)
			hs_status_desc.bEndpointAddress =
					fs_status_desc.bEndpointAddress;
#endif
	}

	if (gadget_is_otg(gadget)) {
		otg_descriptor.bmAttributes |= USB_OTG_HNP,
		tty_config.bmAttributes |= USB_CONFIG_ATT_WAKEUP;
		tty_config.bMaxPower = 4;
	}


	dev->cdc = cdc;

	dev->in_ep = in_ep;
	dev->out_ep = out_ep;
	dev->status_ep = status_ep;

	/* preallocate control message data and buffer */
	dev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
	if (!dev->req)
		goto fail;
	dev->req->buf = control_req;
	dev->req->complete = tty_setup_complete;

	/* ... and maybe likewise for status transfer */
#if defined(CONFIG_USB_TTY_CDC)
	if (dev->status_ep) {
		dev->stat_req = usb_ep_alloc_request(dev->status_ep,
							GFP_KERNEL);
		if (!dev->stat_req) {
			usb_ep_free_request(dev->status_ep, dev->req);

			goto fail;
		}
		dev->stat_req->buf = status_req;
		dev->stat_req->context = NULL;
	}
#endif

	/* finish hookup to lower layer ... */
	dev->gadget = gadget;
	set_gadget_data(gadget, dev);
	gadget->ep0->driver_data = dev;

	/*
	 * two kinds of host-initiated state changes:
	 *  - iff DATA transfer is active, carrier is "on"
	 *  - tx queueing enabled if open *and* carrier is "on"
	 */

	printf("using %s, OUT %s IN %s%s%s\n", gadget->name,
		out_ep->name, in_ep->name,
		status_ep ? " STATUS " : "",
		status_ep ? status_ep->name : ""
		);
	if (gadget_is_mb9bfxxx(gadget)) {
		dev->in = ep_desc(gadget, &hs_source_desc, &fs_source_desc);
		dev->in_ep->driver_data = dev;
		usb_ep_enable(dev->in_ep, dev->in);

		dev->out = ep_desc(gadget, &hs_sink_desc, &fs_sink_desc);
		dev->out_ep->driver_data = dev;
		usb_ep_enable(dev->out_ep, dev->out);
		if (cdc) {
			dev->status = ep_desc(gadget, &hs_status_desc,
					      &fs_status_desc);
			dev->status_ep->driver_data = dev;
			usb_ep_enable(dev->status_ep, dev->status);
		}
	}
	return 0;

fail:
	error("%s failed, status = %d", __func__, status);
	tty_unbind(gadget);
	return status;
}

static struct usb_gadget_driver tty_driver = {
	.speed		= DEVSPEED,

	.bind		= tty_bind,
	.unbind		= tty_unbind,

	.setup		= tty_setup,
	.disconnect	= tty_disconnect,

	.suspend	= tty_suspend,
	.resume		= tty_resume,
};

static int usbtty_start(void)
{
	struct usb_gadget *gadget;
	unsigned long ts;
	unsigned long timeout = USB_CONNECT_TIMEOUT;

	if (usb_gadget_register_driver(&tty_driver) < 0)
		return 0;

	ttydev.tty_started = 0;
	buf_init (&usbtty_input, USBTTY_BUFFER_SIZE);
	buf_init (&usbtty_output, USBTTY_BUFFER_SIZE);

	gadget = ttydev.gadget;
	usb_gadget_connect(gadget);

	if (getenv("cdc_connect_timeout"))
		timeout = simple_strtoul(getenv("cdc_connect_timeout"),
						NULL, 10) * CONFIG_SYS_HZ;
	ts = get_timer(0);
	while (!ttydev.tty_started) {
		/* Handle control-c and timeouts */
		if (ctrlc() || (get_timer(ts) > timeout)) {
			error("The remote end did not respond in time.");
			return -1;
		}
		usb_gadget_handle_interrupts();
	}
	packet_received = 0;
	rx_submit(&ttydev, ttydev.rx_req, 0);
	TTYDBG("%s complete\n", __func__);

	return 0;
}

int usbtty_stop(void)
{
	return 0;
}

int drv_usb_gadget_tty_init(void)
{
	struct stdio_dev dev;
	int rc;

	memset(&dev, 0, sizeof(dev));
	strcpy(dev.name, "usbtty");
	dev.flags = DEV_FLAGS_OUTPUT | DEV_FLAGS_INPUT | DEV_FLAGS_SYSTEM;
	dev.start = usbtty_start;
	dev.stop = usbtty_stop;
	dev.putc = usbtty_putc;
	dev.puts = usbtty_puts;
	dev.getc = usbtty_getc;
	dev.tstc = usbtty_tstc;

	rc = stdio_register(&dev);
	return rc?rc:1;
}
