/*****************************************************************************
 *
 * Filename:      irda-usb.c
 * Version:       0.1
 * Description:   IrDA-USB Driver
 * Status:        Experimental 
 * Author:        Dag Brattli <dag@brattli.net>
 *
 *	Copyright (C) 2000, Roman Weissgaerber <weissg@vienna.at>
 *      Copyright (C) 2000, Dag Brattli <dag@brattli.net>
 *          
 *	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., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *****************************************************************************/

#include <linux/module.h>

#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/malloc.h>
#include <linux/rtnetlink.h>
#include <linux/usb.h>

#include <net/irda/irda.h>
#include <net/irda/irlap.h>
#include <net/irda/irda_device.h>
#include <net/irda/wrapper.h>

#include "irda-usb.h"

__u32 min_turn_times[]  = { 10000, 5000, 1000, 500, 100, 50, 10, 0 }; /* us */

static void irda_usb_dump_class_desc(struct irda_class_desc *desc);
static struct irda_class_desc *irda_usb_find_class_desc(struct usb_device *dev, unsigned int ifnum);
static void irda_usb_change_speed(struct irda_usb_cb *self, __u32 speed);
static int irda_usb_hard_xmit(struct sk_buff *skb, struct net_device *dev);
static int irda_usb_open(struct irda_usb_cb *self);
static int irda_usb_close(struct irda_usb_cb *self);
static void write_bulk_callback(purb_t purb);
static void irda_usb_receive(purb_t purb);
static int irda_usb_net_init(struct net_device *dev);
static int irda_usb_net_open(struct net_device *dev);
static int irda_usb_net_close(struct net_device *dev);
static int irda_usb_net_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
static void irda_usb_net_timeout(struct net_device *dev);
static struct net_device_stats *irda_usb_net_get_stats(struct net_device *dev);

/* Master instance */
static struct irda_usb_cb irda_instance;

/* These are the currently known IrDA USB dongles. Add new dongles here */
struct irda_usb_dongle dongles[] = {
	/* idVendor, idProduct */
	{ 0x9c4, 0x011 },    /* ACTiSYS Corp,  ACT-IR2000U FIR-USB Adapter */
	{ 0x50f, 0x180 },    /* KC Technology Inc., ?? */
     /* { 0x8e9, 0x??? },*/  /* Extended Systems, Inc., ?? */
	{ 0, 0 }, /* The end */
};

static void *irda_usb_probe(struct usb_device *dev, unsigned int ifnum)
{
	struct irda_usb_cb *self = &irda_instance;
	struct usb_interface_descriptor *interface;
	struct usb_endpoint_descriptor *endpoint;
	struct irda_class_desc *irda_desc;
	struct irda_usb_dongle *dongle;
	int class, subclass;
	int found;
	int ret;
	int ep;

	IRDA_DEBUG(0, "Vendor: %x, Product: %x\n", dev->descriptor.idVendor, dev->descriptor.idProduct);
	
	/* Check for all known IrDA-USB dongles */
	found = 0;
	for (dongle=dongles;dongle->idVendor;dongle++) {
		if ((dev->descriptor.idVendor == dongle->idVendor) && 
		    (dev->descriptor.idProduct == dongle->idProduct)) 
		{
			    found = TRUE;
			    break;
		}
	}
	if (!found) {
		/* Accept all dongles with IrDA-USB class/subclass */
		class = dev->actconfig->interface[ifnum].altsetting[0].bInterfaceClass;
		subclass = dev->actconfig->interface[ifnum].altsetting[0].bInterfaceSubClass;
		IRDA_DEBUG(0, "Class: %x, Subclass: %x\n", class, subclass);
		
		if ((class != USB_CLASS_APP_SPEC) || (subclass != USB_CLASS_IRDA))
			return NULL;
	}
	
	MESSAGE("USB IRDA found at address %d\n", dev->devnum);
#if 0   /* Is this really necessary? */
	ret = usb_set_interface(dev, ifnum, 0);
	IRDA_DEBUG(0, "usb-irda: set interface result %d\n", ret);
	switch (ret) {
	case 0:
		break;
	case USB_ST_STALL:
		usb_clear_halt(dev, usb_sndctrlpipe(dev, 0));
		IRDA_DEBUG(0, __FUNCTION__ "(), Clearing stall on control interface\n" );
		break;
	default:
		IRDA_DEBUG(0, __FUNCTION__ "(), Unknown error %d\n", ret);
		return NULL;
		break;
	}
#endif
	/* Find our endpoints */
	interface = &dev->actconfig->interface[ifnum].altsetting[0];
	endpoint = interface->endpoint;
	ep = endpoint[0].bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
	if ((endpoint[0].bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN)
		self->bulk_in_ep = ep;
	else
		self->bulk_out_ep = ep;

	ep = endpoint[1].bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
	if ((endpoint[1].bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN)
		self->bulk_in_ep = ep;
	else
	    self->bulk_out_ep = ep;

	if (self->bulk_out_ep == 0 || self->bulk_in_ep == 0 ||
		endpoint [0].bmAttributes != USB_ENDPOINT_XFER_BULK ||
		endpoint [1].bmAttributes != USB_ENDPOINT_XFER_BULK) 
	{
		IRDA_DEBUG(0, __FUNCTION__ "(), Bogus endpoints");
		return NULL;
	}
	IRDA_DEBUG(0, __FUNCTION__ "(), bulk_in_ep=%d, bulk_out_ep=%d\n", self->bulk_in_ep, self->bulk_out_ep);

	/* Find IrDA class descriptor */
	irda_desc = irda_usb_find_class_desc(dev, ifnum);
	if (irda_desc == NULL)
		return NULL;
	
	self->irda_desc =  irda_desc;	
	self->present = 1;
	self->usbdev = dev;
	ret = irda_usb_open(self);
	if (ret)
		return NULL;

	return self;
}

/*
 * Function irda_usb_find_class_desc(dev, ifnum)
 *
 *    Returns instance of IrDA class descriptor, or NULL if not found
 *
 */
static struct irda_class_desc *irda_usb_find_class_desc(struct usb_device *dev, unsigned int ifnum)
{
	struct usb_interface_descriptor *interface;
	struct irda_class_desc *desc, *ptr;
	int ret;
		
	desc = kmalloc(sizeof (struct irda_class_desc), GFP_KERNEL);
	if (desc == NULL) 
		return NULL;
	memset(desc, 0, sizeof(struct irda_class_desc));
	
	ret = usb_get_class_descriptor(dev, ifnum, USB_DT_IRDA, 0, (void *) desc, sizeof(struct irda_class_desc));
	IRDA_DEBUG(0, __FUNCTION__ "(), ret=%d\n", ret);
	if (ret) {
		WARNING("usb-irda: usb_get_class_descriptor failed (0x%x)\n", ret);  
	}

	/* Check if we found it? */
	if (desc->bDescriptorType == USB_DT_IRDA)
		return desc;

	IRDA_DEBUG(0, __FUNCTION__ "(), parsing extra descriptors ...\n");
	
	/* Check if the class descriptor is interleaved with standard descriptors */
	interface = &dev->actconfig->interface[ifnum].altsetting[0];
	ret = usb_get_extra_descriptor(interface, USB_DT_IRDA, &ptr);
	if (ret) {
		kfree(desc);
		return NULL;
	}
	*desc = *ptr;
	irda_usb_dump_class_desc(desc);
	
	return desc;
}

/*
 * Function usb_irda_dump_class_desc(desc)
 *
 *    Prints out the contents of the IrDA class descriptor
 *
 */
static void irda_usb_dump_class_desc(struct irda_class_desc *desc)
{
	printk("bLength=%x\n", desc->bLength);
	printk("bDescriptorType=%x\n", desc->bDescriptorType);
	printk("bcdSpecRevision=%x\n", desc->bcdSpecRevision); 
	printk("bmDataSize=%x\n", desc->bmDataSize);
	printk("bmWindowSize=%x\n", desc->bmWindowSize);
	printk("bmMinTurnaroundTime=%d\n", desc->bmMinTurnaroundTime);
	printk("wBaudRate=%x\n", desc->wBaudRate);
	printk("bmAdditionalBOFs=%x\n", desc->bmAdditionalBOFs);
	printk("bIrdaRateSniff=%x\n", desc->bIrdaRateSniff);
	printk("bMaxUnicastList=%x\n", desc->bMaxUnicastList);
}												
	
static void irda_usb_disconnect(struct usb_device *dev, void *ptr)
{
	struct irda_usb_cb *self = (struct irda_usb_cb *) ptr;

	IRDA_DEBUG(0, __FUNCTION__ "()\n");

	if (self->isopen) {
		self->isopen = 0;
		/* better let it finish - the release will do whats needed */
		self->usbdev = NULL;
		return;
	}
	irda_usb_close(self);
	IRDA_DEBUG(0, __FUNCTION__ "(), USB IrDA Disconnected\n");

	self->present = 0;
}

#if 0
static void ctrl_callback(urb_t *urb)
{
	IRDA_DEBUG(0, __FUNCTION__ "()\n");
	switch (urb->status) {
	case USB_ST_NOERROR:
		break;
	case USB_ST_URB_PENDING:
		break;
	case USB_ST_URB_KILLED:
		break;
	default:
		break;
        }
}
#endif

static struct usb_driver irda_driver = {
	"irda-usb",
	irda_usb_probe,
	irda_usb_disconnect,
	{ NULL, NULL },
	NULL,
};

static void irda_usb_init_qos(struct irda_usb_cb *self)
{
	struct irda_class_desc *desc;

	IRDA_DEBUG(0, __FUNCTION__ "()\n");
	
	desc = self->irda_desc;
	
	/* Initialize QoS for this device */
	irda_init_max_qos_capabilies(&self->qos);

	self->qos.baud_rate.bits       = desc->wBaudRate;
	self->qos.min_turn_time.bits   = desc->bmMinTurnaroundTime;
	self->qos.additional_bofs.bits = desc->bmAdditionalBOFs;
	self->qos.window_size.bits     = desc->bmWindowSize;
	self->qos.data_size.bits       = desc->bmDataSize;

	/* Limit to SIR for now */
	self->qos.baud_rate.bits       &= 0xff;
	self->qos.data_size.bits       =  0x07;
	
	irda_qos_bits_to_value(&self->qos);

	self->flags |= IFF_SIR;
	if (self->qos.baud_rate.value > 115200)
		self->flags |= IFF_MIR;
	if (self->qos.baud_rate.value > 1152000)
		self->flags |= IFF_FIR;
}

static int irda_usb_open(struct irda_usb_cb *self)
{
	struct net_device *netdev;
	int err;

	IRDA_DEBUG(0, __FUNCTION__ "()\n");

	spin_lock_init(&self->lock);

	irda_usb_init_qos(self);
	
	/* Specify how much memory we want */
	self->tx_buff.truesize = IRDA_USB_MAX_MTU;
	
	/* Allocate memory if needed */
	if (self->tx_buff.truesize > 0) {
		self->tx_buff.head = (__u8 *) kmalloc(self->tx_buff.truesize, 
						      GFP_KERNEL);
		if (self->tx_buff.head == NULL) 
			return -1;
		memset(self->tx_buff.head, 0, self->tx_buff.truesize);
	}	
	self->tx_buff.data = self->tx_buff.head;

	if (!(netdev = dev_alloc("irda%d", &err))) {
		ERROR(__FUNCTION__ "(), dev_alloc() failed!\n");
		return -1;
	}
	self->netdev = netdev;
 	netdev->priv = (void *) self;

	/* Override the network functions we need to use */
	netdev->init            = irda_usb_net_init;
	netdev->hard_start_xmit = irda_usb_hard_xmit;
	netdev->tx_timeout	= irda_usb_net_timeout;
	netdev->watchdog_timeo  = HZ/20;
	netdev->open            = irda_usb_net_open;
	netdev->stop            = irda_usb_net_close;
	netdev->get_stats	= irda_usb_net_get_stats;
	netdev->do_ioctl        = irda_usb_net_ioctl;

	rtnl_lock();
	err = register_netdevice(netdev);
	rtnl_unlock();
	if (err) {
		ERROR(__FUNCTION__ "(), register_netdev() failed!\n");
		return -1;
	}
	MESSAGE("IrDA: Registered device %s\n", netdev->name);

	return 0;
}

static int irda_usb_close(struct irda_usb_cb *self)
{
	IRDA_DEBUG(0, __FUNCTION__ "()\n");

	ASSERT(self != NULL, return -1;);

	/* Remove netdevice */
	if (self->netdev) {
		rtnl_lock();
		unregister_netdevice(self->netdev);
		rtnl_unlock();
	}
	if (self->tx_buff.head)
		kfree(self->tx_buff.head);
	
	return 0;
}

#if 0
static int irda_usb_send_cmd(void)
{
	devrequest request;

	
}
#endif

/*
 * Function irda_usb_build_header(self, skb, header)
 *
 *   Builds USB-IrDA outbound header
 *
 */
static void irda_usb_build_header(struct irda_usb_cb *self, struct sk_buff *skb,  __u8 *header)
{
	int xbofs;
	
	if (self->new_speed) {
		IRDA_DEBUG(0, __FUNCTION__ "(), changing speed to %d\n", self->new_speed);
		self->speed = self->new_speed;
		self->new_speed = 0;

		switch (self->speed) {
		case 2400:
		        *header = SPEED_2400;
			break;
		default:
		case 9600:
			*header = SPEED_9600;
			break;
		case 19200:
			*header = SPEED_19200;
			break;
		case 38400:
			*header = SPEED_38400;
			break;
		case 57600:
		        *header = SPEED_57600;
			break;
		case 115200:
		        *header = SPEED_115200;
			break;
		case 576000:
		        *header = SPEED_576000;
			break;
		case 1152000:
		        *header = SPEED_1152000;
			break;
		case 4000000:
		        *header = SPEED_4000000;
			break;
		}
	} else
		/* No change */
		*header = 0;
	
	if (!skb)
		return;
	
	/* Set the negotiated additional XBOFS */
	if (((struct irda_skb_cb *)(skb->cb))->magic != LAP_MAGIC) {
	        /* 
		 * This will happen for all frames sent from user-space.
		 * Nothing to worry about, but we set the default number of 
		 * BOF's
		 */
		IRDA_DEBUG(1, __FUNCTION__ "(), wrong magic in skb!\n");
		xbofs = 12;
	} else
		xbofs = ((struct irda_skb_cb *)(skb->cb))->xbofs;
    
	if (xbofs == self->xbofs)
		return;

	IRDA_DEBUG(0, __FUNCTION__ "(), changing xbofs to %d\n", xbofs);
	self->xbofs = xbofs;
	
	switch (xbofs) {
	case 48:
		*header |= 0x10;
		break;
	case 28:
		*header |= 0x20;
		break;
	case 12:
		*header |= 0x30;
		break;
	case 5: /* Bug in IrLAP spec? (should be 6) */
	case 6:
		*header |= 0x40;
		break;
	case 3:
		*header |= 0x50;
		break;
	case 2:
		*header |= 0x60;
		break;
	case 1:
		*header |= 0x70;
		break;
	case 0:
		*header |= 0x80;
		break;
	default:
		WARNING(__FUNCTION__ "(), unsupported number of xbofs=%d!\n", xbofs);
		break;
	}
}

static void irda_usb_change_speed(struct irda_usb_cb *self, __u32 speed)
{
	struct sk_buff *skb;
	unsigned long flags;
	__u8 *frame;
	purb_t purb;
	int ret;

	IRDA_DEBUG(0, __FUNCTION__ "(), speed=%d\n", speed);
    
	skb = dev_alloc_skb(USB_IRDA_HEADER);
	if (!skb)
		return;
	purb = usb_alloc_urb(0);
	if (!purb)
		return;
	
	frame = skb_put(skb, USB_IRDA_HEADER);
	irda_usb_build_header(self, skb, frame);

	spin_lock_irqsave(&self->lock, flags);
	
	/* Submit 0 length IrDA frame to trigger new speed settings */
        FILL_BULK_URB(purb, self->usbdev, 
		      usb_sndbulkpipe(self->usbdev, self->bulk_out_ep),
                      frame, IRDA_USB_MAX_MTU,
                      write_bulk_callback, NULL);
	purb->transfer_buffer_length = 1;
	//purb->transfer_flags |= USB_ASYNC_UNLINK;
	purb->transfer_flags |= USB_QUEUE_BULK;
	
	if ((ret = usb_submit_urb(purb))) {
		IRDA_DEBUG(0, __FUNCTION__ "(), failed Tx URB\n");
	} 
	spin_unlock_irqrestore(&self->lock, flags);
}

static int irda_usb_hard_xmit(struct sk_buff *skb, struct net_device *netdev)
{
	struct irda_usb_cb *self = netdev->priv;
	purb_t purb;
	unsigned long flags;
	__u32 speed;
	int res, mtt;
	    
	IRDA_DEBUG(2, __FUNCTION__ "()\n");

	netif_stop_queue(netdev);

        /* Check if we need to change the speed */
        if ((speed = irda_get_speed(skb)) != self->speed)
                self->new_speed = speed;
	
	purb = &self->tx_urb;
	if (purb->status) {
		WARNING(__FUNCTION__ "(), URB still in use!\n");
		return 0;
	}
	spin_lock_irqsave(&self->lock, flags);
	
	/* Copy packet and make room for USB-IrDA header */
	memcpy(self->tx_buff.head+USB_IRDA_HEADER, skb->data, skb->len);
	self->tx_buff.len = skb->len+USB_IRDA_HEADER;

	irda_usb_build_header(self, skb, self->tx_buff.head);

	/* Generate min turn time. FIXME: can we do better than this? */
	mtt = irda_get_mtt(skb);
	if (mtt) {
		udelay(mtt);			
	}	
	
        FILL_BULK_URB(purb, self->usbdev, 
		      usb_sndbulkpipe(self->usbdev, self->bulk_out_ep),
                      self->tx_buff.head, IRDA_USB_MAX_MTU,
                      write_bulk_callback, self);
	self->tx_urb.transfer_buffer_length = self->tx_buff.len;
	//self->tx_urb.transfer_flags |= USB_ASYNC_UNLINK;
	self->tx_urb.transfer_flags |= USB_QUEUE_BULK;
	self->tx_urb.timeout = MSECS_TO_JIFFIES(100);
		    
	if ((res = usb_submit_urb(purb))) {
		IRDA_DEBUG(0, __FUNCTION__ "(), failed Tx URB\n");
		self->stats.tx_errors++;
		netif_start_queue(netdev);
	} else {
		self->stats.tx_packets++;
                self->stats.tx_bytes += skb->len;
		
		netdev->trans_start = jiffies;
	}
	spin_unlock_irqrestore(&self->lock, flags);
	dev_kfree_skb(skb);
	
	return 0;
}

static void write_bulk_callback(purb_t purb)
{
	struct irda_usb_cb *self = purb->context;
	
	IRDA_DEBUG(2, __FUNCTION__ "()\n");

	/* Change speed doesn't set context */
	if (self == NULL) {
		usb_free_urb(purb);
		return;
	}
	purb->status = 0;
	netif_wake_queue(self->netdev);
}

static void irda_usb_submit(struct irda_usb_cb *self, struct sk_buff *skb, purb_t purb)
{
	struct irda_skb_cb *cb;
	int ret;

	IRDA_DEBUG(2, __FUNCTION__ "()\n");
	
	/* Allocate new skb if it has not been recycled */
	if (!skb) {
		skb = dev_alloc_skb(IRDA_USB_MAX_MTU+1);
		if (!skb) {
			if (purb)
				usb_free_urb(purb);
			return;
		}
	} else  {
		/* Reset recycled skb */
		skb->data = skb->tail = skb->head;
		skb->len = 0;
	}
	/* Make sure IP header get aligned (IrDA header is 5 bytes ) */
	skb_reserve(skb, 1);

	/* Allocate new urb if it has not been recycled */
	if (!purb) {
		purb = usb_alloc_urb(0);
		if (!purb) {
			dev_kfree_skb(skb);
			return;
		}
	}

	/* Save ourselves */
	cb = (struct irda_skb_cb *) skb->cb;
	cb->context = self;

	/* Reinitialize URB */
	FILL_BULK_URB(purb, self->usbdev, 
		      usb_rcvbulkpipe(self->usbdev, self->bulk_in_ep), 
		      skb->data, skb->truesize,
                      irda_usb_receive, skb);
	//purb->transfer_flags |= USB_ASYNC_UNLINK;
	purb->transfer_flags |= USB_QUEUE_BULK;
	purb->status = 0;
	
	ret = usb_submit_urb(purb);
	if (ret) {
		IRDA_DEBUG(0, __FUNCTION__ "(), Failed to submit Rx URB %d\n", ret);
	}
}

/*
 * Function irda_usb_receive(purb)
 *
 *     Called by the USB subsystem when a frame has been received
 *
 */
static void irda_usb_receive(purb_t purb) 
{
	struct sk_buff *skb = (struct sk_buff *) purb->context;
	struct irda_usb_cb *self; 
	struct irda_skb_cb *cb;
	struct sk_buff *new;
	
	IRDA_DEBUG(2, __FUNCTION__ "(), len=%d\n", purb->actual_length);
	
	/* Find ourselves */
	cb = (struct irda_skb_cb *) skb->cb;
	self = (struct irda_usb_cb *) cb->context;

	ASSERT(self != NULL, return;);
	ASSERT(cb != NULL, return;);
	
	if (!self->irlap) {
		WARNING(__FUNCTION__ "(), IrLAP is gone!\n");
		usb_free_urb(purb);
		return;
	}
	
	if (purb->status) {
		switch (purb->status) {
		case USB_ST_CRC:
			self->stats.rx_errors++;
			self->stats.rx_crc_errors++;	
			break;
		default:
			WARNING(__FUNCTION__ "(), RX status %d\n", purb->status);
			break;
		}
		goto done;
	}
	
	if (purb->actual_length <= USB_IRDA_HEADER) {
		WARNING(__FUNCTION__ "(), empty frame!\n");
		goto done;
	}
		
	/* Fix skb, and remove USB-IrDA header */
	skb_put(skb, purb->actual_length);
	skb_pull(skb, USB_IRDA_HEADER);
	
	/* Don't waste a lot of memory on small IrDA frames */
	if (skb->len > RX_COPY_THRESHOLD) {
		new = dev_alloc_skb(skb->len+1);
		if (!new) {
			self->stats.rx_dropped++;
			goto done;  
		}

		/* Make sure IP header get aligned (IrDA header is 5 bytes) */
		skb_reserve(new, 1);
		
		/* Copy packet, so we can recycle the original */
		memcpy(skb_put(new, skb->len), skb->data, skb->len);
	} else {
		/* Deliver the original skb */
		new = skb;
		skb = NULL;
	}
	
	self->stats.rx_bytes += new->len;
	self->stats.rx_packets++;

        new->dev = self->netdev;
        new->mac.raw  = new->data;
        new->protocol = htons(ETH_P_IRDA);
        netif_rx(new);
done:
	/* Recycle Rx URB (and possible the skb as well) */
	irda_usb_submit(self, skb, purb);
}

static int irda_usb_net_init(struct net_device *dev)
{
	IRDA_DEBUG(0, __FUNCTION__ "()\n");
	
	/* Set up to be a normal IrDA network device driver */
	irda_device_setup(dev);

	/* Insert overrides below this line! */

	return 0;
}

/*
 * Function irda_usb_net_open (dev)
 *
 *    Network device is taken up. Usually this is done by "ifconfig irda0 up" 
 *   
 */
static int irda_usb_net_open(struct net_device *netdev)
{
	struct irda_usb_cb *self;
	int win, i;
	
	IRDA_DEBUG(0, __FUNCTION__ "()\n");

	ASSERT(netdev != NULL, return -1;);
	self = (struct irda_usb_cb *) netdev->priv;
	ASSERT(self != NULL, return -1;);
	
	/* The peer device may in some cases send one more frame */
	win = self->qos.window_size.value+1;
	IRDA_DEBUG(0, __FUNCTION__ "(), rx window size=%d\n", win);
	
	/* Some some reason other values makes the system unstable */	
	win=1;
	self->qos.window_size.bits = 0x01;
	self->qos.window_size.value = 1;
	
	/* Submit Rx window URBs */
	for (i=0;i<win;i++)
		irda_usb_submit(self, NULL, NULL);
	/* 
	 * Open new IrLAP layer instance, now that everything should be
	 * initialized properly 
	 */
	self->irlap = irlap_open(netdev, &self->qos);

	/* Ready to play! */
	netif_start_queue(netdev);
	
	MOD_INC_USE_COUNT;

	return 0;
}

/*
 * Function irda_usb_net_close (self)
 *
 *    Network device is taken down. Usually this is done by 
 *    "ifconfig irda0 down" 
 */
static int irda_usb_net_close(struct net_device *netdev)
{
	struct irda_usb_cb *self;

	IRDA_DEBUG(0, __FUNCTION__ "()\n");

	ASSERT(netdev != NULL, return -1;);
	self = (struct irda_usb_cb *) netdev->priv;
	ASSERT(self != NULL, return -1;);

	/* Stop device */
	netif_stop_queue(netdev);

#if 0   /* For some reason this crashes the machine :-( */
	usb_unlink_urb(&self->rx_urb);
	usb_unlink_urb(&self->tx_urb);
#endif	
	/* Stop and remove instance of IrLAP */
	if (self->irlap)
		irlap_close(self->irlap);
	self->irlap = NULL;

	/*irda_usb_stop(self);*/
	MOD_DEC_USE_COUNT;

	return 0;
}

static void irda_usb_net_timeout(struct net_device *netdev)
{
	struct irda_usb_cb *self = netdev->priv;
	
	IRDA_DEBUG(0, __FUNCTION__ "(), Network layer thinks we timed out!\n");
	if (!self)
		return;
	
	WARNING("%s: Tx timed out, usb->status=%d\n", netdev->name, self->tx_urb.status);
	self->stats.tx_errors++;

	switch (self->tx_urb.status) {
	case -ECONNABORTED:
		netif_wake_queue(self->netdev);
		break;
	case -EINPROGRESS:
		usb_unlink_urb(&self->tx_urb);
		break;
	default:
		break;
	}
	/* Maybe we need a reset */
}

static int irda_usb_is_receiving(struct irda_usb_cb *self)
{
	return 0; /* For now */
}

static int irda_usb_net_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
{
	struct if_irda_req *irq = (struct if_irda_req *) rq;
	struct irda_usb_cb *self;
	unsigned long flags;
	int ret = 0;

	ASSERT(dev != NULL, return -1;);
	self = dev->priv;
	ASSERT(self != NULL, return -1;);

	IRDA_DEBUG(2, __FUNCTION__ "(), %s, (cmd=0x%X)\n", dev->name, cmd);
	
	/* Disable interrupts & save flags */
	save_flags(flags);
	cli();
	
	switch (cmd) {
	case SIOCSBANDWIDTH: /* Set bandwidth */
		/*
		 * This function will also be used by IrLAP to change the
		 * speed, so we still must allow for speed change within
		 * interrupt context.
		 */
		if (!in_interrupt() && !capable(CAP_NET_ADMIN))
			return -EPERM;
		irda_usb_change_speed(self, irq->ifr_baudrate);
		break;
	case SIOCSMEDIABUSY: /* Set media busy */
		if (!capable(CAP_NET_ADMIN))
			return -EPERM;
		irda_device_set_media_busy(self->netdev, TRUE);
		break;
	case SIOCGRECEIVING: /* Check if we are receiving right now */
		irq->ifr_receiving = irda_usb_is_receiving(self);
		break;
	default:
		ret = -EOPNOTSUPP;
	}
	
	restore_flags(flags);
	
	return ret;
}

static struct net_device_stats *irda_usb_net_get_stats(struct net_device *dev)
{
	struct irda_usb_cb *self = dev->priv;
	return &self->stats;
}

int __init usb_irda_init(void)
{
	if (usb_register(&irda_driver) < 0)
		return -1;

	MESSAGE("USB IrDA support registered\n");
	return 0;
}
module_init(usb_irda_init);

void __exit usb_irda_cleanup(void)
{
	struct irda_usb_cb *irda = &irda_instance;

	irda->present = 0;
	usb_deregister(&irda_driver);
}
module_exit(usb_irda_cleanup);

MODULE_AUTHOR("Roman Weissgaerber <weissg@vienna.at>, Dag Brattli <dag@brattli.net>");
MODULE_DESCRIPTION("IrDA-USB Dongle Driver"); 


