Please CC me on all replies since I seem to be having issues subscribing to the 
list...

I am working on writing a USB Serial driver roughly based on the Keyspan_pda 
driver, and I am running into real strange issues.  As this is my first serial 
driver (and my first serial firmware) I am not quite sure where I am going 
wrong and I was wondering if someone could look at the driver code and tell me 
if there are any obvious mistakes.  Basicly the issue I am having is I am 
dropping chars for some unknown reason, but only sometimes.  I can set up a 
loop like "cat /dev/ttyUSB0 > /dev/ttyUSB0" and send an ascii file from another 
machine to the device and get back an identical copy, but if I try to do any 
sending from the linux side (like if I use wvdial or something) the data gets 
corrupted and I seem to drop chars randomly.

The basic setup is I have a FX2 USB controller chip in it with some firmware 
that takes the RX data and places it on an interrupt in endpoint to Linux, and 
a bit of code to take chars from a bulk out endpoint from linux and puts it in 
a TX ringbuffer on the chip.  Since TX and RX seem to work ok some of the time 
I am not sure if the firmware is buggy or the driver is buggy.

The driver code is attached.  Sorry if its a mess, I have been hacking at it 
for 3 days now and got a bit frustrated.  I am very new to the Linux USB-Serial 
stuff and I am not quite sure I know how it all works yet.  I have read the 
online LJ articles but they didnt seem to help much.

/*
 * USB FX2 Converter driver, based on the USB Keyspan PDA
 * Xircom / Entregra Converter driver.
 *
 * Copyright (C) 2006 - 2006 Mike Panetta	<[EMAIL PROTECTED]>
 * Copyright (C) 1999 - 2001 Greg Kroah-Hartman	<[EMAIL PROTECTED]>
 * Copyright (C) 1999, 2000 Brian Warner	<[EMAIL PROTECTED]>
 * Copyright (C) 2000 Al Borchers		<[EMAIL PROTECTED]>
 *
 *	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.
 *
 * See Documentation/usb/usb-serial.txt for more information on using this driver
 * 
 * (09/07/2001) gkh
 *	cleaned up the Xircom support.  Added ids for Entregra device which is
 *	the same as the Xircom device.  Enabled the code to be compiled for
 *	either Xircom or Keyspan devices.
 *
 * (08/11/2001) Cristian M. Craciunescu
 *	support for Xircom PGSDB9
 *
 * (05/31/2001) gkh
 *	switched from using spinlock to a semaphore, which fixes lots of problems.
 *
 * (04/08/2001) gb
 *	Identify version on module load.
 * 
 * (11/01/2000) Adam J. Richter
 *	usb_device_id table support
 * 
 * (10/05/2000) gkh
 *	Fixed bug with urb->dev not being set properly, now that the usb
 *	core needs it.
 * 
 * (08/28/2000) gkh
 *	Added locks for SMP safeness.
 *	Fixed MOD_INC and MOD_DEC logic and the ability to open a port more 
 *	than once.
 * 
 * (07/20/2000) borchers
 *	- keyspan_pda_write no longer sleeps if it is called on interrupt time;
 *	  PPP and the line discipline with stty echo on can call write on
 *	  interrupt time and this would cause an oops if write slept
 *	- if keyspan_pda_write is in an interrupt, it will not call
 *	  usb_control_msg (which sleeps) to query the room in the device
 *	  buffer, it simply uses the current room value it has
 *	- if the urb is busy or if it is throttled keyspan_pda_write just
 *	  returns 0, rather than sleeping to wait for this to change; the
 *	  write_chan code in n_tty.c will sleep if needed before calling
 *	  keyspan_pda_write again
 *	- if the device needs to be unthrottled, write now queues up the
 *	  call to usb_control_msg (which sleeps) to unthrottle the device
 *	- the wakeups from keyspan_pda_write_bulk_callback are queued rather
 *	  than done directly from the callback to avoid the race in write_chan
 *	- keyspan_pda_chars_in_buffer also indicates its buffer is full if the
 *	  urb status is -EINPROGRESS, meaning it cannot write at the moment
 *      
 * (07/19/2000) gkh
 *	Added module_init and module_exit functions to handle the fact that this
 *	driver is a loadable module now.
 *
 * (03/26/2000) gkh
 *	Split driver up into device specific pieces.
 * 
 */


#include <linux/config.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/workqueue.h>
#include <asm/uaccess.h>
#include <linux/usb.h>

static int debug;

#include "usb-serial.h"

/*
 * Version Information
 */
#define DRIVER_VERSION "v0.1"
#define DRIVER_AUTHOR "Mike Panetta <[EMAIL PROTECTED]>"
#define DRIVER_DESC "FX2 Serial Driver"

#define FX2_SIO_INT_IN_ENDPOINT 8
#define FX2_SIO_BULK_OUT_ENDPOINT 6

#define RX_SIZ 16
#define TX_SIZ 16

struct fx2_port_private {
	int			tx_room;
	int			tx_throttled;
	int			port_open; // Is this port open?
	struct work_struct	wakeup_work;
	struct work_struct	unthrottle_work;
};

struct fx2_sio_private {
	struct urb * interrupt_in_urb;  // We only have one IN urb for both ports.
	struct urb * bulk_out_urb;      // The bulk out URB, we only have one for both ports.
	int	     bulk_out_urb_busy; // Tells us when the URB is in use.
	int	     bulk_out_urb_port;	// Tells us what port is using it.
	int 	     dev_open;		// Open count for the device.
	spinlock_t   lock;		// Lock for the usb tracking.
};


#define FX2_VENDOR_ID		0x1944
#define FX2_SIO_ID		0x0dab

static struct usb_device_id id_table_combined [] = {
	{ USB_DEVICE(FX2_VENDOR_ID, FX2_SIO_ID) },
	{ }						/* Terminating entry */
};

static const 
struct usb_device_id fx2_id_table [] __devinitdata = {
//	{ USB_DEVICE(FX2_VENDOR, FX2_PRODUCT), USB_INTERFACE_INFO(255, 0, 2), 
//       .match_flags = USB_DEVICE_ID_MATCH_INT_INFO | USB_DEVICE_ID_MATCH_DEVICE }, // The first interface is the i2c interface.
	{ USB_DEVICE(FX2_VENDOR_ID, FX2_SIO_ID), USB_INTERFACE_INFO(255, 0, 2), 
        .match_flags = USB_DEVICE_ID_MATCH_INT_INFO | USB_DEVICE_ID_MATCH_DEVICE }, // The first interface is the i2c interface.
	{ 0 },
};

MODULE_DEVICE_TABLE (usb, fx2_id_table);

static struct usb_driver fx2_sio_driver = {
	.owner =	THIS_MODULE,
	.name =		"fx2_sio",
	.probe =	usb_serial_probe,
	.disconnect =	usb_serial_disconnect,
	.id_table =	fx2_id_table,
};

static void fx2_sio_wakeup_write( struct usb_serial_port *port )
{

	struct tty_struct *tty = port->tty;

	printk("%s: called to work. (Port: %p, %d)\n", __FUNCTION__, port, port->number);
	//printk("%s: Doing nothing. (Port: %d)\n", __FUNCTION__, port->number);
	//return ;
	/* wake up port processes */
	wake_up_interruptible( &port->write_wait );

	/* wake up line discipline */
	if (tty != NULL)
		tty_wakeup(tty);
	else
		printk("%s: My TTY is NULL?!?!?!. (Port: %d)\n", __FUNCTION__, port->number);
}

static void fx2_sio_request_unthrottle( struct usb_serial *serial )
{
	int result;

	printk("%s: called to work.\n", __FUNCTION__);
	dbg(" request_unthrottle");
	/* ask the device to tell us when the tx buffer becomes
	   sufficiently empty */
#if 0
	result = usb_control_msg(serial->dev, 
				 usb_sndctrlpipe(serial->dev, 0),
				 7, /* request_unthrottle */
				 USB_TYPE_VENDOR | USB_RECIP_INTERFACE
				 | USB_DIR_OUT,
				 16, /* value: threshold */
				 0, /* index */
				 NULL,
				 0,
				 2000);
	if (result < 0)
		dbg("%s - error %d from usb_control_msg", 
		    __FUNCTION__, result);
#endif
}


static void fx2_sio_rx_interrupt (struct urb *urb, struct pt_regs *regs)
{
	//struct usb_serial_port *port = (struct usb_serial_port *)urb->context;
	struct usb_serial *serial = urb->context;
       	//struct tty_struct *tty = port->tty;
	unsigned char *data = urb->transfer_buffer;
	int i;
	int status;
	struct fx2_port_private *priv;

	//printk("%s: Called to work.\n", __FUNCTION__);

	switch (urb->status) {
	case 0:
		/* success */
		break;
	case -ECONNRESET:
	case -ENOENT:
	case -ESHUTDOWN:
		/* this urb is terminated, clean up */
		dbg("%s - urb shutting down with status: %d", __FUNCTION__, urb->status);
		return;
	default:
		dbg("%s - nonzero urb status received: %d", __FUNCTION__, urb->status);
		goto exit;
	}

 	/* see if the message is data or a status interrupt */
	switch (data[0]) {
	case 0:
		//printk("%s: sio0 rx.\n", __FUNCTION__);
		/* rest of message is rx data */
		priv = usb_get_serial_port_data(serial->port[0]);
		if (urb->actual_length > 2 && priv->port_open) {
			for (i = 2; i < urb->actual_length ; ++i) {
				if (serial->port[0]->tty->flip.count >= TTY_FLIPBUF_SIZE)
					tty_flip_buffer_push(serial->port[0]->tty);
				tty_insert_flip_char(serial->port[0]->tty, data[i], 0);
			}
			tty_flip_buffer_push(serial->port[0]->tty);
		}
		/* Remove this later */
		//printk("%s: sio0 rx. TX room = %d\n", __FUNCTION__, data[1]);
		if (priv->tx_throttled && data[1] > 14) { // If we have space unthrottle
			printk("%s: sio0 Unthrottle TX. TX room = %d\n", __FUNCTION__, data[1]);
			priv->tx_throttled = 0;
			priv->tx_room = data[1];
			/* queue up a wakeup at scheduler time */
			schedule_work(&priv->wakeup_work);
		}
		break;
	case 1:
		//printk("%s: sio1 rx.\n", __FUNCTION__);
		/* rest of message is rx data */
		priv = usb_get_serial_port_data(serial->port[1]);
		if (urb->actual_length > 2 && priv->port_open) {
			for (i = 2; i < urb->actual_length ; ++i) {
				if (serial->port[1]->tty->flip.count >= TTY_FLIPBUF_SIZE)
					tty_flip_buffer_push(serial->port[1]->tty);
				tty_insert_flip_char(serial->port[1]->tty, data[i], 0);
			}
			tty_flip_buffer_push(serial->port[1]->tty);
		}
		/* Remove this later */
		//printk("%s: sio1 rx. TX room = %d\n", __FUNCTION__, data[1]);
		if (priv->tx_throttled && data[1] > 14) { // If we have space unthrottle
			printk("%s: sio1 Unthrottle TX. TX room = %d\n", __FUNCTION__, data[1]);
			priv->tx_throttled = 0;
			priv->tx_room = data[1];
			/* queue up a wakeup at scheduler time */
			schedule_work(&priv->wakeup_work);
		}
		break;
#if 0
	case 9:
		/* status interrupt */
		dbg(" rx int, d1=%d, d2=%d", data[1], data[2]);
		switch (data[1]) {
		case 1: /* modemline change */
			break;
		case 2: /* tx unthrottle interrupt */
			priv->tx_throttled = 0;
			/* queue up a wakeup at scheduler time */
			schedule_work(&priv->wakeup_work);
			break;
		default:
			break;
		}
#endif
		break;
	default:
		break;
	}

exit:
	status = usb_submit_urb (urb, GFP_ATOMIC);
	if (status)
		err ("%s - usb_submit_urb failed with result %d",
		     __FUNCTION__, status);
}

/* 
 * MWP: The next 2 functions are disabled until I deal with
 *      the shared RX URB.
 */
static void fx2_sio_rx_throttle (struct usb_serial_port *port)
{
	struct usb_serial *serial = port->serial;
	struct fx2_sio_private *spriv;
	printk("%s: called to work.\n", __FUNCTION__);
	spriv = usb_get_serial_data(serial);
	/* stop receiving characters. We just turn off the URB request, and
	   let chars pile up in the device. If we're doing hardware
	   flowcontrol, the device will signal the other end when its buffer
	   fills up. If we're doing XON/XOFF, this would be a good time to
	   send an XOFF, although it might make sense to foist that off
	   upon the device too. */

	dbg("fx2_sio_rx_throttle port %d", port->number);
	//usb_kill_urb(port->interrupt_in_urb);
}


static void fx2_sio_rx_unthrottle (struct usb_serial_port *port)
{
	printk("%s: called to work.\n", __FUNCTION__);
	/* just restart the receive interrupt URB */
	dbg("fx2_sio_rx_unthrottle port %d", port->number);
#if 0
	port->interrupt_in_urb->dev = port->serial->dev;
	if (usb_submit_urb(port->interrupt_in_urb, GFP_ATOMIC))
		dbg(" usb_submit_urb(read urb) failed");
#endif
	return;
}


static int fx2_sio_setbaud (struct usb_serial *serial, int baud)
{
	int rc;
	int bindex;

	printk("%s: called to work.\n", __FUNCTION__);
	switch(baud) {
		case 110: bindex = 0; break;
		case 300: bindex = 1; break;
		case 1200: bindex = 2; break;
		case 2400: bindex = 3; break;
		case 4800: bindex = 4; break;
		case 9600: bindex = 5; break;
		case 19200: bindex = 6; break;
		case 38400: bindex = 7; break;
		case 57600: bindex = 8; break;
		case 115200: bindex = 9; break;
		default: return -EINVAL;
	}

	/* rather than figure out how to sleep while waiting for this
	   to complete, I just use the "legacy" API. */
	rc = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
			     0, /* set baud */
			     USB_TYPE_VENDOR 
			     | USB_RECIP_INTERFACE
			     | USB_DIR_OUT, /* type */
			     bindex, /* value */
			     0, /* index */
			     NULL, /* &data */
			     0, /* size */
			     2000); /* timeout */
	return(rc);
}


static void fx2_sio_break_ctl (struct usb_serial_port *port, int break_state)
{
	struct usb_serial *serial = port->serial;
	int value;
	int result;

	printk("%s: called to work.\n", __FUNCTION__);
	if (break_state == -1)
		value = 1; /* start break */
	else
		value = 0; /* clear break */
	result = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
				4, /* set break */
				USB_TYPE_VENDOR | USB_RECIP_INTERFACE | USB_DIR_OUT,
				value, 0, NULL, 0, 2000);
	if (result < 0)
		dbg("%s - error %d from usb_control_msg", 
		    __FUNCTION__, result);
	/* there is something funky about this.. the TCSBRK that 'cu' performs
	   ought to translate into a break_ctl(-1),break_ctl(0) pair HZ/4
	   seconds apart, but it feels like the break sent isn't as long as it
	   is on /dev/ttyS0 */
}


static void fx2_sio_set_termios (struct usb_serial_port *port, 
				     struct termios *old_termios)
{
	struct usb_serial *serial = port->serial;
	unsigned int cflag = port->tty->termios->c_cflag;

	printk("%s: called to work.\n", __FUNCTION__);
	/* cflag specifies lots of stuff: number of stop bits, parity, number
	   of data bits, baud. What can the device actually handle?:
	   CSTOPB (1 stop bit or 2)
	   PARENB (parity)
	   CSIZE (5bit .. 8bit)
	   There is minimal hw support for parity (a PSW bit seems to hold the
	   parity of whatever is in the accumulator). The UART either deals
	   with 10 bits (start, 8 data, stop) or 11 bits (start, 8 data,
	   1 special, stop). So, with firmware changes, we could do:
	   8N1: 10 bit
	   8N2: 11 bit, extra bit always (mark?)
	   8[EOMS]1: 11 bit, extra bit is parity
	   7[EOMS]1: 10 bit, b0/b7 is parity
	   7[EOMS]2: 11 bit, b0/b7 is parity, extra bit always (mark?)

	   HW flow control is dictated by the tty->termios->c_cflags & CRTSCTS
	   bit.

	   For now, just do baud. */

	switch (cflag & CBAUD) {
		/* we could support more values here, just need to calculate
		   the necessary divisors in the firmware. <asm/termbits.h>
		   has the Bnnn constants. */
		case B110: fx2_sio_setbaud(serial, 110); break;
		case B300: fx2_sio_setbaud(serial, 300); break;
		case B1200: fx2_sio_setbaud(serial, 1200); break;
		case B2400: fx2_sio_setbaud(serial, 2400); break;
		case B4800: fx2_sio_setbaud(serial, 4800); break;
		case B9600: fx2_sio_setbaud(serial, 9600); break;
		case B19200: fx2_sio_setbaud(serial, 19200); break;
		case B38400: fx2_sio_setbaud(serial, 38400); break;
		case B57600: fx2_sio_setbaud(serial, 57600); break;
		case B115200: fx2_sio_setbaud(serial, 115200); break;
		default: dbg("can't handle requested baud rate"); break;
	}
}


/* modem control pins: DTR and RTS are outputs and can be controlled.
   DCD, RI, DSR, CTS are inputs and can be read. All outputs can also be
   read. The byte passed is: DTR(b7) DCD RI DSR CTS RTS(b2) unused unused */

static int fx2_sio_get_modem_info(struct usb_serial *serial,
				      unsigned char *value)
{
	int rc;
	unsigned char data;
	printk("%s: called to work.\n", __FUNCTION__);
	return 0;
	rc = usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0),
			     3, /* get pins */
			     USB_TYPE_VENDOR|USB_RECIP_INTERFACE|USB_DIR_IN,
			     0, 0, &data, 1, 2000);
	if (rc > 0)
		*value = data;
	return rc;
}


static int fx2_sio_set_modem_info(struct usb_serial *serial,
				      unsigned char value)
{
	int rc;
	printk("%s: called to work.\n", __FUNCTION__);
	return 0;
	rc = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
			     3, /* set pins */
			     USB_TYPE_VENDOR|USB_RECIP_INTERFACE|USB_DIR_OUT,
			     value, 0, NULL, 0, 2000);
	return rc;
}

static int fx2_sio_tiocmget(struct usb_serial_port *port, struct file *file)
{
	struct usb_serial *serial = port->serial;
	int rc;
	unsigned char status;
	int value;

	printk("%s: called to work.\n", __FUNCTION__);
	rc = fx2_sio_get_modem_info(serial, &status);
	if (rc < 0)
		return rc;
	value =
		((status & (1<<7)) ? TIOCM_DTR : 0) |
		((status & (1<<6)) ? TIOCM_CAR : 0) |
		((status & (1<<5)) ? TIOCM_RNG : 0) |
		((status & (1<<4)) ? TIOCM_DSR : 0) |
		((status & (1<<3)) ? TIOCM_CTS : 0) |
		((status & (1<<2)) ? TIOCM_RTS : 0);
	return value;
}

static int fx2_sio_tiocmset(struct usb_serial_port *port, struct file *file,
				unsigned int set, unsigned int clear)
{
	struct usb_serial *serial = port->serial;
	int rc;
	unsigned char status;

	printk("%s: called to work.\n", __FUNCTION__);
	rc = fx2_sio_get_modem_info(serial, &status);
	if (rc < 0)
		return rc;

	if (set & TIOCM_RTS)
		status |= (1<<2);
	if (set & TIOCM_DTR)
		status |= (1<<7);

	if (clear & TIOCM_RTS)
		status &= ~(1<<2);
	if (clear & TIOCM_DTR)
		status &= ~(1<<7);
	rc = fx2_sio_set_modem_info(serial, status);
	return rc;
}

static int fx2_sio_ioctl(struct usb_serial_port *port, struct file *file,
			     unsigned int cmd, unsigned long arg)
{
	printk("%s: called to work.\n", __FUNCTION__);
	switch (cmd) {
	case TIOCMIWAIT:
		/* wait for any of the 4 modem inputs (DCD,RI,DSR,CTS)*/
		/* TODO */
	case TIOCGICOUNT:
		/* return count of modemline transitions */
		return 0; /* TODO */
	}
	
	return -ENOIOCTLCMD;
}

static int fx2_sio_write(struct usb_serial_port *port, 
			     const unsigned char *buf, int count)
{
	struct usb_serial *serial = port->serial;
	int request_unthrottle = 0;
	int rc = 0;
	struct fx2_port_private *priv;
	struct fx2_sio_private *spriv;
	unsigned long flags;

	printk("%s: called to work.\n", __FUNCTION__);

	spriv = usb_get_serial_data(serial);
	priv = usb_get_serial_port_data(port);
	/* guess how much room is left in the device's ring buffer, and if we
	   want to send more than that, check first, updating our notion of
	   what is left. If our write will result in no room left, ask the
	   device to give us an interrupt when the room available rises above
	   a threshold, and hold off all writers (eventually, those using
	   select() or poll() too) until we receive that unthrottle interrupt.
	   Block if we can't write anything at all, otherwise write as much as
	   we can. */

	dbg("fx2_sio_write(%d)",count);
	if (count == 0) {
		dbg(" write request of 0 bytes");
		return (0);
	}

	/* we might block because of:
	   the TX urb is in-flight (wait until it completes)
	   the device is full (wait until it says there is room)
	*/
	
	spin_lock(&port->lock);
	if (priv->tx_throttled) {
		spin_unlock(&port->lock);
		dbg("%s: TX Throttled.\n", __FUNCTION__);
		return 0;
	}
	spin_unlock(&port->lock);
	dbg("%s: TX NOT Throttled.\n", __FUNCTION__);

	//printk("%s: About to aquire lock %p, %d.\n", __FUNCTION__, &spriv->lock, spriv->lock.magic);
	spin_lock_irqsave(&spriv->lock, flags);
	if (spriv->bulk_out_urb_busy) {
		spin_unlock_irqrestore(&spriv->lock, flags);
		dbg("%s: write URB busy.\n", __FUNCTION__);
		return 0;
	}
	spriv->bulk_out_urb_busy = 1;
	spriv->bulk_out_urb_port = port->number;
	spin_unlock_irqrestore(&spriv->lock, flags);
	dbg("%s: Write URB free.\n", __FUNCTION__);

	/* At this point the URB is in our control, nobody else can submit it
	   again (the only sudden transition was the one from EINPROGRESS to
	   finished).  Also, the tx process is not throttled. So we are
	   ready to write. */

	count = (count > TX_SIZ) ? TX_SIZ : count;
	dbg("%s: count = %d.\n", __FUNCTION__, count);

#if 1
	/* Check if we might overrun the Tx buffer.   If so, ask the
	   device how much room it really has.  This is done only on
	   scheduler time, since usb_control_msg() sleeps. */
	if (count > priv->tx_room && !in_interrupt()) {
		unsigned char room[4];
		rc = usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0),
				     16, /* write_room */
				     USB_TYPE_VENDOR | USB_DIR_IN,
				     0, /* value */
				     0, /* index */
				     room,
				     4,
				     2000);
		printk("%s: Sent ctrl msg.\n", __FUNCTION__);
		if (rc < 0) {
			dbg(" roomquery failed");
			goto exit;
		}
		if (rc == 0) {
			dbg(" roomquery returned 0 bytes");
			rc = -EIO; /* device didn't return any data */
			goto exit;
		}
		dbg(" roomquery says %d", TX_SIZ - room[port->number * 2]);
		priv->tx_room = TX_SIZ - room[port->number * 2];
	}
#endif
	if (count > priv->tx_room) {
		/* we're about to completely fill the Tx buffer, so
		   we'll be throttled afterwards. */
		count = priv->tx_room;
		request_unthrottle = 1;
	}
	dbg("%s: count = %d.\n", __FUNCTION__, count);

	if (count) {
		/* now transfer data */
		((char *)spriv->bulk_out_urb->transfer_buffer)[0] = port->number;
		memcpy (spriv->bulk_out_urb->transfer_buffer+1, buf, count);
		/* send the data out the bulk port */
		spriv->bulk_out_urb->transfer_buffer_length = count + 1;

		priv->tx_room -= count;

		spriv->bulk_out_urb->dev = port->serial->dev;
		rc = usb_submit_urb(spriv->bulk_out_urb, GFP_ATOMIC);
		if (rc) {
			dbg(" usb_submit_urb(write bulk) failed");
			goto exit;
		}
	}
	else {
		/* There wasn't any room left, so we are throttled until
		   the buffer empties a bit */
		request_unthrottle = 1;
	}

#if 1
	if (request_unthrottle || (priv->tx_room == 0)) {
		priv->tx_throttled = 1; /* block writers */
		//schedule_work(&priv->unthrottle_work);
	}
#endif
	rc = count;
exit:
	if (rc < 0)
		spriv->bulk_out_urb_busy = 0;
	dbg("%s: Done rc = %d. '%s'\n", __FUNCTION__, rc, priv->tx_throttled ? "TX Throttled." : "TX NOT Throttled.");
	return rc;
}


static void fx2_sio_write_bulk_callback (struct urb *urb, struct pt_regs *regs)
{
	//struct usb_serial_port *port = (struct usb_serial_port *)urb->context;
	struct usb_serial *serial = urb->context;
	struct fx2_port_private *priv;
	struct fx2_sio_private *spriv;


	spriv = usb_get_serial_data(serial);
	printk("%s: called to work. (Status: %d, Port: %d)\n", __FUNCTION__, urb->status, spriv->bulk_out_urb_port);

	spriv->bulk_out_urb_busy = 0;

	priv = usb_get_serial_port_data(serial->port[spriv->bulk_out_urb_port]);

	/* queue up a wakeup at scheduler time */
	schedule_work(&priv->wakeup_work);
}


static int fx2_sio_write_room (struct usb_serial_port *port)
{
	struct usb_serial *serial = port->serial;
	unsigned char room[4];
	int rc = 0;
	unsigned long flags;

	struct fx2_port_private *priv;
	struct fx2_sio_private  *spriv;

	printk("%s: called to work. (Port: %d)\n", __FUNCTION__, port->number);

	priv = usb_get_serial_port_data(port);
	spriv = usb_get_serial_data(serial);

	spin_lock_irqsave(&spriv->lock, flags);
	if (spriv->bulk_out_urb_busy) {
		spin_unlock_irqrestore(&spriv->lock, flags);
		dbg("%s: write URB busy.\n", __FUNCTION__);
		return 0;
	}
	spin_unlock_irqrestore(&spriv->lock, flags);

#if 1
	if (priv->tx_room < 2) { //get an updated value.  Seems broken otherwise?

		rc = usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0),
				     16, /* write_room */
				     USB_TYPE_VENDOR | USB_DIR_IN,
				     0, /* value */
				     0, /* index */
				     room,
				     4,
				     2000);
		printk("%s: Sent ctrl msg.\n", __FUNCTION__);
		if (rc < 0) {
			dbg("%s - roomquery failed", __FUNCTION__);
			return rc;
		}
		if (rc == 0) {
			dbg("%s - roomquery returned 0 bytes", __FUNCTION__);
			return -EIO;
		}


		priv->tx_room = TX_SIZ - room[port->number * 2];
	}
#endif
	/* used by n_tty.c for processing of tabs and such. Giving it our
	   conservative guess is probably good enough, but needs testing by
	   running a console through the device. */

	printk("%s: Returning room = %d\n", __FUNCTION__, priv->tx_room);
	return (priv->tx_room);
}


static int fx2_sio_chars_in_buffer (struct usb_serial_port *port)
{
	struct fx2_port_private *priv;
	struct fx2_sio_private *spriv;

	unsigned long flags;

	printk("%s: called to work.\n", __FUNCTION__);

	spriv = usb_get_serial_data(port->serial);
	priv = usb_get_serial_port_data(port);

	/* when throttled, return at least WAKEUP_CHARS to tell select() (via
	   n_tty.c:normal_poll() ) that we're not writeable. */
	spin_lock_irqsave(&spriv->lock, flags);
	if (spriv->bulk_out_urb_busy) {
		spin_unlock_irqrestore(&spriv->lock, flags);
		dbg("%s: write URB busy.\n", __FUNCTION__);
		return 256;
	}
	spin_unlock_irqrestore(&spriv->lock, flags);
	if (priv->tx_throttled)
		return 256;
	return 0;
}


static int fx2_sio_open (struct usb_serial_port *port, struct file *filp)
{
	struct usb_serial *serial = port->serial;
	unsigned char room[4];
	int rc = 0;
	struct fx2_port_private *priv;
	struct fx2_sio_private *spriv;

	printk("%s: called to work for port: %d\n", __FUNCTION__, port->number);

	priv = usb_get_serial_port_data(port);
	spriv = usb_get_serial_data(serial);
	printk("%s: Got priv data (%p).\n", __FUNCTION__, priv);
#if 1
	/* find out how much room is in the Tx ring */
	//usb_control_msg(myhandle, USB_TYPE_VENDOR | USB_ENDPOINT_IN, GET_ROOM, 0, 0, tmp, 4, 10);
	rc = usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0),
			     16, /* write_room */
			     USB_TYPE_VENDOR | USB_DIR_IN,
			     0, /* value */
			     0, /* index */
			     room,
			     4,
			     2000);
	printk("%s: Sent ctrl msg.\n", __FUNCTION__);
	if (rc < 0) {
		dbg("%s - roomquery failed", __FUNCTION__);
		return rc;
	}
	if (rc == 0) {
		dbg("%s - roomquery returned 0 bytes", __FUNCTION__);
		rc = -EIO;
		return rc;
	}
#endif
	priv->tx_room = TX_SIZ - (room[port->number * 2]);
	priv->tx_throttled = (TX_SIZ - (room[port->number * 2])) ? 0 : 1;
	priv->port_open = 1;
	printk("%s: setup room (%d).\n", __FUNCTION__, priv->tx_room);

	/* the normal serial device seems to always turn on DTR and RTS here,
	   so do the same */
#if 0
	if (port->tty->termios->c_cflag & CBAUD)
		fx2_sio_set_modem_info(serial, (1<<7) | (1<<2) );
	else
		fx2_sio_set_modem_info(serial, 0);
#endif
	/*Start reading from the device*/
	if (serial->num_bulk_in) {
		printk("%s: have %d bulk in endpoints.\n", __FUNCTION__, serial->num_bulk_in);
	}

	if (serial->num_bulk_out) {
		printk("%s: have %d bulk out endpoints.\n", __FUNCTION__, serial->num_bulk_out);
	}

	if (serial->num_interrupt_in) {
		printk("%s: have %d int in endpoints.\n", __FUNCTION__, serial->num_interrupt_in);
	}

	if (spriv->dev_open == 0) { 
                spriv->interrupt_in_urb->dev = serial->dev;
                printk("%s: Setup URB (%p).\n", __FUNCTION__, priv);

		rc = usb_submit_urb(spriv->interrupt_in_urb, GFP_KERNEL);
		printk("%s: Submit URB (%p).\n", __FUNCTION__, priv);
		if (rc) {
			dbg("%s - usb_submit_urb(read int) failed", __FUNCTION__);
			return rc;
		}
		spriv->dev_open++;
	} else {
		spriv->dev_open++;
	}

error:
	printk("%s: Done (%p).\n", __FUNCTION__, priv);

	return 0;
}


static void fx2_sio_close(struct usb_serial_port *port, struct file *filp)
{
	struct usb_serial *serial = port->serial;
	struct fx2_port_private *priv;
	struct fx2_sio_private *spriv;

	printk("%s: called to work for port: %d\n", __FUNCTION__, port->number);
	priv = usb_get_serial_port_data(port);
	spriv = usb_get_serial_data(serial);
	if (serial->dev) {
#if 0
		/* the normal serial device seems to always shut off DTR and RTS now */
		if (port->tty->termios->c_cflag & HUPCL)
			fx2_sio_set_modem_info(serial, 0);
#endif
		priv->port_open = 0;
		spriv->dev_open--;

		/* shutdown our bulk reads and writes */
		if (spriv->dev_open == 0) {
			usb_kill_urb(spriv->bulk_out_urb);
			usb_kill_urb(spriv->interrupt_in_urb);
			spriv->bulk_out_urb_busy = 0;
		}
	}
}

static struct urb * 
fx2_setup_bulk_urb(struct usb_serial * serial, int endpoint, int dir,
		   char * buf, int buflen,
		   void (* callback)(struct urb *, struct pt_regs *),
		   void * context)
{

	struct urb * urb;

	if (endpoint == -1)
		return NULL; /* Endpoint not needed */

	urb = usb_alloc_urb(0, GFP_KERNEL);
	if (urb == NULL) {
		dbg("%s - alloc for endpoint %d failed.", __FUNCTION__, endpoint);
		return NULL;
	}

	usb_fill_bulk_urb(urb, serial->dev, 
			  usb_sndbulkpipe(serial->dev, endpoint) | dir,
			  buf, buflen, callback, context);

	return urb;
}

static struct urb * 
fx2_setup_int_urb(struct usb_serial * serial, int endpoint, int dir,
		   char * buf, int buflen,
		   void (* callback)(struct urb *, struct pt_regs *),
		   void * context, int interval)
{

	struct urb * urb;

	if (endpoint == -1)
		return NULL; /* Endpoint not needed */

	urb = usb_alloc_urb(0, GFP_KERNEL);
	if (urb == NULL) {
		dbg("%s - alloc for endpoint %d failed.", __FUNCTION__, endpoint);
		return NULL;
	}

	usb_fill_int_urb(urb, serial->dev, 
			  usb_sndintpipe(serial->dev, endpoint) | dir,
			  buf, buflen, callback, context, interval);

	return urb;
}

static int fx2_sio_urb_init(struct fx2_sio_private * s_priv, struct usb_serial * serial)
{
	struct urb * rx_urb;
	struct urb * tx_urb;
	char       * rx_buf;
	char       * tx_buf;

	rx_buf = kmalloc(RX_SIZ + 2, GFP_KERNEL); // Allocate space for the chars + 2 bytes ctrl
	if (rx_buf == NULL)
		goto rx_alloc_fail;

	rx_urb  = fx2_setup_int_urb(serial, 
			      FX2_SIO_INT_IN_ENDPOINT, USB_DIR_IN,
			      rx_buf, RX_SIZ + 2,
			      fx2_sio_rx_interrupt, serial, 1);
	if (rx_urb == NULL)
		goto rx_urb_fail;

 	s_priv->interrupt_in_urb = rx_urb;

	tx_buf = kmalloc(TX_SIZ + 2, GFP_KERNEL); // Allocate space for the chars + 1 bytes ctrl
	if (tx_buf == NULL)
		goto tx_alloc_fail;

	tx_urb  = fx2_setup_bulk_urb(serial, 
			      FX2_SIO_BULK_OUT_ENDPOINT, USB_DIR_OUT,
			      tx_buf, TX_SIZ + 1,
			      fx2_sio_write_bulk_callback, serial);
			      
	if (tx_urb == NULL)
		goto tx_urb_fail;
	s_priv->bulk_out_urb      = tx_urb;

	s_priv->bulk_out_urb_busy = 0;

	
	return 0;
	
tx_urb_fail:
	kfree(tx_buf);
tx_alloc_fail:
	usb_free_urb(rx_urb);
rx_urb_fail:
	kfree(rx_buf);
rx_alloc_fail:
	return -ENOMEM;
}

static int fx2_sio_startup (struct usb_serial *serial)
{

	struct fx2_port_private * p_priv;
	struct fx2_sio_private  * s_priv;
	struct usb_serial_port  * port;

	int i;

	s_priv = kmalloc(sizeof(struct fx2_sio_private), GFP_KERNEL);
	if (!s_priv)
		return (1);


	/*
         * Set up the device private data.  We only have one in urb 
	 * and one out urb for both ports, so we get it here and store it in 
	 * the device private data structure.
	 */
	memset(s_priv, 0, sizeof(struct fx2_sio_private));
	if (fx2_sio_urb_init(s_priv, serial) < 0)
		return (1);
	s_priv->dev_open          = 0;
	spin_lock_init(&s_priv->lock);
	//printk("Setting up serial private data. (%p, %d)\n", &s_priv->lock, s_priv->lock.magic);
	usb_set_serial_data(serial, s_priv);

        /* Now setup per port private data */
        for (i = 0; i < serial->num_ports; i++) {
		//printk("Setting up port %d private data.\n", i);
                port = serial->port[i];
                p_priv = kmalloc(sizeof(struct fx2_port_private), GFP_KERNEL);
                if (!p_priv) {
                        dbg("%s - kmalloc for fx2_port_private (%d) failed!.", __FUNCTION__, i);
                        return (1);
                }
		//printk("Setting up port %d private data at %p.\n", i, p_priv);
                memset(p_priv, 0, sizeof(struct fx2_port_private));
                //p_priv->device_details = d_details;
		init_waitqueue_head(&port->write_wait);
		INIT_WORK(&p_priv->wakeup_work, (void *)fx2_sio_wakeup_write,
				(void *)(port));
		INIT_WORK(&p_priv->unthrottle_work,
				(void *)fx2_sio_request_unthrottle,
				(void *)(serial));
                usb_set_serial_port_data(port, p_priv);
        }

	return (0);
}

static void fx2_sio_shutdown (struct usb_serial *serial)
{
	struct fx2_sio_private  * s_priv = usb_get_serial_data(serial);
	struct fx2_port_private * p_priv;

	dbg("%s", __FUNCTION__);

	kfree(s_priv->interrupt_in_urb->transfer_buffer);
	kfree(s_priv->bulk_out_urb->transfer_buffer);
	
	usb_free_urb(s_priv->interrupt_in_urb);
	usb_free_urb(s_priv->bulk_out_urb);

	kfree(usb_get_serial_port_data(serial->port[0]));
	kfree(usb_get_serial_port_data(serial->port[1]));
}


static struct usb_serial_driver fx2_sio_device = {
	.driver = {
		.owner =	THIS_MODULE,
		.name =		"fx2_sio",
	},
	.description =		"FX2 SIO",
	.id_table =		fx2_id_table,
	.num_interrupt_in =	NUM_DONT_CARE,
	.num_bulk_in =		NUM_DONT_CARE,
	.num_bulk_out =		NUM_DONT_CARE,
	.num_ports =		2,
	.open =			fx2_sio_open,
	.close =		fx2_sio_close,
	.write =		fx2_sio_write,
	.write_room =		fx2_sio_write_room,
	//.write_bulk_callback = 	fx2_sio_write_bulk_callback,
	//.read_int_callback =	fx2_sio_rx_interrupt,
	.chars_in_buffer =	fx2_sio_chars_in_buffer,
	.throttle =		fx2_sio_rx_throttle,
	.unthrottle =		fx2_sio_rx_unthrottle,
	.ioctl =		fx2_sio_ioctl,
	.set_termios =		fx2_sio_set_termios,
	.break_ctl =		fx2_sio_break_ctl,
	.tiocmget =		fx2_sio_tiocmget,
	.tiocmset =		fx2_sio_tiocmset,
	.attach =		fx2_sio_startup,
	.shutdown =		fx2_sio_shutdown,
};


static int __init fx2_sio_init (void)
{
	int retval;
	retval = usb_serial_register(&fx2_sio_device);
	if (retval)
		goto failed_pda_register;
	retval = usb_register(&fx2_sio_driver);
	if (retval)
		goto failed_usb_register;
	info(DRIVER_DESC " " DRIVER_VERSION);
	return 0;
failed_usb_register:	
	usb_serial_deregister(&fx2_sio_device);
failed_pda_register:
	return retval;
}


static void __exit fx2_sio_exit (void)
{
	usb_deregister (&fx2_sio_driver);
	usb_serial_deregister (&fx2_sio_device);
}


module_init(fx2_sio_init);
module_exit(fx2_sio_exit);

MODULE_AUTHOR( DRIVER_AUTHOR );
MODULE_DESCRIPTION( DRIVER_DESC );
MODULE_LICENSE("GPL");

module_param(debug, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Debug enabled or not");

Reply via email to