// darts-usb.c
//
// DARTS USB driver 0.0-pre0
//
// The DARTS USB driver recieves data from a radio direction finding unit,
// timestamps each received datum, and makes the data available to use
// user.
//
// Designed for Linux 2.4
// Supports devfs
//
// Copyright (c) 2003 Jeffrey M. Laughlin, n1ywb@arrl.org
// 
// Based upon USB Skeleton driver - 0.7
// Copyright (c) 2001 Greg Kroah-Hartman (greg@kroah.com)
//
// This program is free software; you can redistribute it and/or modify     
// it under the terms of the GNU General Public License as published by     
// the Free Software Foundation; either version 2 of the License, or        
// (at your option) any later version.                                      
//                                                                          
// This program is distributed in the hope that it will be useful,          
// but WITHOUT ANY WARRANTY; without even the implied warranty of           
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            
// GNU General Public License for more details.                             
// 
// You should have received a copy of the GNU General Public License        
// along with this program; if not, write to the Free Software              
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#include <linux/config.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/signal.h>
#include <linux/errno.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/fcntl.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/list.h>
#include <linux/smp_lock.h>
#include <linux/devfs_fs_kernel.h>
#include <linux/usb.h>
#include <linux/time.h>

#define CONFIG_USB_DEBUG

#ifdef CONFIG_USB_DEBUG
	static int debug = 1;
#else
	static int debug;
#endif

/* Use our own dbg macro */
#undef dbg
#define dbg(format, arg...) do { if (debug) printk(KERN_DEBUG __FILE__ ": " format "\n" , ## arg); } while (0)


/* Version Information */
#define DRIVER_VERSION "v0.0pre0"
#define DRIVER_AUTHOR "Jeffrey M. Laughlin, n1ywb@arrl.org"
#define DRIVER_DESC "DARTS USB Interface Driver"

/* Module paramaters */
MODULE_PARM(debug, "i");
MODULE_PARM_DESC(debug, "Debug enabled or not");


/* Define these values to match your device */
#define DARTS_USB_VENDOR_ID	1240 // This is Microchips ID. Technically DARTS
                                     // needs to request a unique ID from the
                                     // USB organization.
#define DARTS_USB_PRODUCT_ID	42   // The ultimate answer.

/* table of devices that work with this driver */
static struct usb_device_id darts_usb_table [] = {
	{ USB_DEVICE(DARTS_USB_VENDOR_ID, DARTS_USB_PRODUCT_ID) },
	{ }					/* Terminating entry */
};

MODULE_DEVICE_TABLE (usb, darts_usb_table);

// Technically, DARTS needs to request an assigned minor number range from the
// USB kernel maintainer. For now we're using the skeleton's minor number.
#define DARTS_USB_MINOR_BASE	192	

/* we can have up to this number of device plugged in at once */
#define MAX_DEVICES		16

/* Structure to hold all of our device specific stuff */
struct darts_usb {
	struct usb_device *	udev;			/* save off the usb device pointer */
	struct usb_interface *	interface;		/* the interface for this device */
	devfs_handle_t		devfs;			/* devfs device node */
	unsigned char		minor;			/* the starting minor number for this device */
	unsigned char		num_ports;		/* the number of ports this device has */
	char			num_interrupt_in;	/* number of interrupt in endpoints we have */

	unsigned char *		interrupt_in_buffer;	/* the buffer to receive data */
	int			interrupt_in_size;	/* the size of the receive buffer */
	__u8			interrupt_in_endpointAddr; /* the address of the interrupt in endpoint */
	struct urb *		read_urb;		/* the urb used to receive data */

	unsigned char *		userland_buffer;	/* file data buffer */
	int			userland_size;		/* the size of the file data buffer */

	int			open_count;		/* number of times this port has been opened */
	struct semaphore	sem;			/* locks this structure */
        
        wait_queue_head_t       read_queue;             // Queue for processes blocked on read

        struct timeval          tv;                     // Hold the timestamp
};


/* the global usb devfs handle */
extern devfs_handle_t usb_devfs_handle;


/* local function prototypes */
static ssize_t darts_usb_read	(struct file *file, char *buffer, size_t count, loff_t *ppos);
static int darts_usb_ioctl		(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg);
static int darts_usb_open		(struct inode *inode, struct file *file);
static int darts_usb_release		(struct inode *inode, struct file *file);
	
static void * darts_usb_probe	(struct usb_device *dev, unsigned int ifnum, const struct usb_device_id *id);
static void darts_usb_disconnect	(struct usb_device *dev, void *ptr);
static void darts_usb_irq       (struct urb *urb);


/* array of pointers to our devices that are currently connected */
static struct darts_usb		*minor_table[MAX_DEVICES];

/* lock to protect the minor_table structure */
static DECLARE_MUTEX (minor_table_mutex);

/*
 * File operations needed when we register this driver.
 * This assumes that this driver NEEDS file operations,
 * of course, which means that the driver is expected
 * to have a node in the /dev directory. If the USB
 * device were for a network interface then the driver
 * would use "struct net_driver" instead, and a serial
 * device would use "struct tty_driver". 
 */
static struct file_operations darts_usb_fops = {
	/*
	 * The owner field is part of the module-locking
	 * mechanism. The idea is that the kernel knows
	 * which module to increment the use-counter of
	 * BEFORE it calls the device's open() function.
	 * This also means that the kernel can decrement
	 * the use-counter again before calling release()
	 * or should the open() function fail.
	 *
	 * Not all device structures have an "owner" field
	 * yet. "struct file_operations" and "struct net_device"
	 * do, while "struct tty_driver" does not. If the struct
	 * has an "owner" field, then initialize it to the value
	 * THIS_MODULE and the kernel will handle all module
	 * locking for you automatically. Otherwise, you must
	 * increment the use-counter in the open() function
	 * and decrement it again in the release() function
	 * yourself.
	 */
	owner:		THIS_MODULE,

	read:		darts_usb_read,
	ioctl:		darts_usb_ioctl,
	open:		darts_usb_open,
	release:	darts_usb_release,
};      


/* usb specific object needed to register this driver with the usb subsystem */
static struct usb_driver darts_usb_driver = {
	name:		"darts-usb",
	probe:		darts_usb_probe,
	disconnect:	darts_usb_disconnect,
	fops:		&darts_usb_fops,
	minor:		DARTS_USB_MINOR_BASE,
	id_table:	darts_usb_table,
};



static inline void darts_usb_delete (struct darts_usb *dev)
{
	dbg(__FUNCTION__);
	minor_table[dev->minor] = NULL;
	dbg(__FUNCTION__ " - if (dev->interrupt_in_buffer != NULL)");
	if (dev->interrupt_in_buffer != NULL)
        {
                dbg(__FUNCTION__ " - kfree (dev->interrupt_in_buffer);");
		kfree (dev->interrupt_in_buffer);
        }
	dbg(__FUNCTION__ " - if (dev->read_urb != NULL)");
	if (dev->read_urb != NULL)
        {
            dbg(__FUNCTION__ " - usb_free_urb (dev->read_urb);");
            usb_free_urb (dev->read_urb);
        }
	if (dev->userland_buffer != NULL)
        {
                dbg(__FUNCTION__ " - kfree (dev->userland_buffer);");
		kfree (dev->userland_buffer);
        }
	dbg(__FUNCTION__ " - if (dev->read_urb != NULL)");
	dbg(__FUNCTION__ " - kfree (dev);");
	kfree (dev);
}


static int darts_usb_open (struct inode *inode, struct file *file)
{
	struct darts_usb *dev = NULL;
	int subminor;
	int retval = 0;
	
	dbg(__FUNCTION__);

	subminor = MINOR (inode->i_rdev) - DARTS_USB_MINOR_BASE;
	if ((subminor < 0) ||
	    (subminor >= MAX_DEVICES)) {
		return -ENODEV;
	}

	/* Increment our usage count for the module.
	 * This is redundant here, because "struct file_operations"
	 * has an "owner" field. This line is included here soley as
	 * a reference for drivers using lesser structures... ;-)
	 */
	MOD_INC_USE_COUNT;

	/* lock our minor table and get our local data for this minor */
	down (&minor_table_mutex);
	dev = minor_table[subminor];
	if (dev == NULL) {
		up (&minor_table_mutex);
		MOD_DEC_USE_COUNT;
		return -ENODEV;
	}

	/* lock this device */
	down (&dev->sem);

	/* unlock the minor table */
	up (&minor_table_mutex);

	/* increment our usage count for the driver */
	++dev->open_count;

	/* save our object in the file's private structure */
	file->private_data = dev;

	/* unlock this device */
	up (&dev->sem);

	return retval;
}


static int darts_usb_release (struct inode *inode, struct file *file)
{
	struct darts_usb *dev;
	int retval = 0;

	dbg(__FUNCTION__);
	dev = (struct darts_usb *)file->private_data;
	if (dev == NULL) {
		dbg (__FUNCTION__ " - object is NULL");
		return -ENODEV;
	}

	dbg(__FUNCTION__ " - minor %d", dev->minor);

	/* lock our minor table */
	down (&minor_table_mutex);

	/* lock our device */
	down (&dev->sem);

	if (dev->open_count <= 0) {
		dbg (__FUNCTION__ " - device not opened");
		retval = -ENODEV;
		goto exit_not_opened;
	}

	if (dev->udev == NULL) {
		/* the device was unplugged before the file was released */
		up (&dev->sem);
		darts_usb_delete (dev);
		up (&minor_table_mutex);
		MOD_DEC_USE_COUNT;
		return 0;
	}

	/* decrement our usage count for the device */
	--dev->open_count;
	if (dev->open_count <= 0) {
		dev->open_count = 0;
	}

	/* decrement our usage count for the module */
	MOD_DEC_USE_COUNT;

exit_not_opened:
	up (&dev->sem);
	up (&minor_table_mutex);

	return retval;
}


// darts_usb_read always returns a fixed size data structure containing the
// current bearing, and the timestamp of when the bearing was received. All
// calls to read should request the exact number of bytes.
static ssize_t darts_usb_read (struct file *file, char *buffer, size_t count, loff_t *ppos)
{
	struct darts_usb *dev;

//	dbg(__FUNCTION__);
	dev = (struct darts_usb *)file->private_data;
	
//	dbg(__FUNCTION__ " - minor %d, count = %d", dev->minor, count);

        // Go to sleep untill next datum is ready
        interruptible_sleep_on(&dev->read_queue);

        if (count < sizeof(long) * 2 + sizeof(unsigned char))
            return -EINVAL;

	/* lock this object */
        if (down_interruptible(&dev->sem))
            return -ERESTARTSYS;

	/* verify that the device wasn't unplugged */
	if (dev->udev == NULL) {
		up (&dev->sem);
		return -ENODEV;
	}
	
        // Get datum out of userland buffer and get it to the user somehow
        if (dev->interrupt_in_buffer == NULL) {
            up (&dev->sem);
            return -ENODEV;
        }

        if (copy_to_user (buffer, dev->interrupt_in_buffer, sizeof(unsigned char)))
                return -EFAULT;
        if (copy_to_user (buffer + sizeof(unsigned char), &dev->tv.tv_sec, sizeof(long)))
                return -EFAULT;
        if (copy_to_user (buffer + sizeof(unsigned char) + sizeof(long), &dev->tv.tv_usec, sizeof(long)))
                return -EFAULT;

	/* unlock the device */
	up (&dev->sem);
	return (sizeof(unsigned char) + sizeof(long) * 2);
}


static int darts_usb_ioctl (struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
{
	struct darts_usb *dev;

	dbg(__FUNCTION__);
	dev = (struct darts_usb *)file->private_data;

	/* lock this object */
	down (&dev->sem);

	/* verify that the device wasn't unplugged */
	if (dev->udev == NULL) {
		up (&dev->sem);
		return -ENODEV;
	}

	dbg(__FUNCTION__ " - minor %d, cmd 0x%.4x, arg %ld", 
	    dev->minor, cmd, arg);

	/* fill in your device specific stuff here */
	
	/* unlock the device */
	up (&dev->sem);
	
	/* return that we did not understand this ioctl call */
	return -ENOTTY;
}


// The USB host controller periodically polls the DARTS device for data. When
// data arrives the USB host issues an interrupt, puts the datum in the buffer,
// and calls this function in interrupt context to let us know it happened. So
// we take the opportunity to precisely timestamp the datum.
static void darts_usb_irq(struct urb *urb)
{
    struct darts_usb *dev = urb->context;
//    dbg(__FUNCTION__);


    // Check to make sure buffer still exists
    if (urb->status != USB_ST_NOERROR) {
        return;
    }

    do_gettimeofday(&dev->tv); // Update the timestamp

//    printk(KERN_DEBUG "darts-usb output: %d\n", *data );   
    wake_up_interruptible(&dev->read_queue); // Send wake up event to any processees sleeping on read
}


// The USB core driver calls this function when our device is plugged in. This
// is where most of the initialization happens.
static void * darts_usb_probe(struct usb_device *udev, unsigned int ifnum, const struct usb_device_id *id)
{
	struct darts_usb *dev = NULL;
	struct usb_interface *interface;
	struct usb_interface_descriptor *iface_desc;
	struct usb_endpoint_descriptor *endpoint;
	int minor;
	int buffer_size;
	char name[10];
        int pipe;
	
	dbg(__FUNCTION__);
	/* See if the device offered us matches what we can accept */
	dbg(__FUNCTION__ " - See if the device offered us matches what we can accept");
	if ((udev->descriptor.idVendor != DARTS_USB_VENDOR_ID) ||
	    (udev->descriptor.idProduct != DARTS_USB_PRODUCT_ID)) {
		return NULL;
	}

	/* select a "subminor" number (part of a minor number) */
        dbg(__FUNCTION__ " - select a \"subminor\" number (part of a minor number) ");
	down (&minor_table_mutex);
	for (minor = 0; minor < MAX_DEVICES; ++minor) {
		if (minor_table[minor] == NULL)
			break;
	}
	if (minor >= MAX_DEVICES) {
		info ("Too many devices plugged in, can not handle this device.");
		goto exit;
	}

	/* allocate memory for our device state and intialize it */
        dbg(__FUNCTION__ " - allocate memory for our device state and intialize it ");
	dev = kmalloc (sizeof(struct darts_usb), GFP_KERNEL);
	if (dev == NULL) {
		err ("Out of memory");
		goto exit;
	}
	memset (dev, 0x00, sizeof (*dev));
	minor_table[minor] = dev;

	interface = &udev->actconfig->interface[ifnum];

	init_MUTEX (&dev->sem);
	dev->udev = udev;
	dev->interface = interface;
	dev->minor = minor;

	/* set up the endpoint information */
        dbg(__FUNCTION__ " - set up the endpoint information");
	iface_desc = &interface->altsetting[0];
        endpoint = &iface_desc->endpoint[0]; // DARTS only has one endpoint.
        if (!(endpoint->bEndpointAddress & 0x80)) goto error; // See if this is an IN endpoint
        if ((endpoint->bmAttributes & 3) != 3) goto error; // See if this is an interrupt endpoint
        
        dbg(__FUNCTION__ " - dev->read_urb = usb_alloc_urb(0);");
        dev->read_urb = usb_alloc_urb(0);
        if (!dev->read_urb) {
            err("No free URBs");
            goto error;
        }

        // Set up some additional device parameters
        dbg(__FUNCTION__ " -  fill the URB data structure using the FILL_INT_URB macro");
            buffer_size = endpoint->wMaxPacketSize;
        dbg(__FUNCTION__ " - dev->interrupt_in_size = buffer_size;");
            dev->interrupt_in_size = buffer_size;
        dbg(__FUNCTION__ " - dev->interrupt_in_endpointAddr = endpoint->bEndpointAddress;");
            dev->interrupt_in_endpointAddr = endpoint->bEndpointAddress;
        dbg(__FUNCTION__ " - dev->interrupt_in_buffer = kmalloc (buffer_size, GFP_KERNEL);");
            dev->interrupt_in_buffer = kmalloc (buffer_size, GFP_KERNEL);
        dbg(__FUNCTION__ " - if (!dev->interrupt_in_buffer)");
            if (!dev->interrupt_in_buffer) {
                    err("Couldn't allocate interrupt_in_buffer");
                    goto error;
            }
                
      
        // Create a buffer for users reading from our device 
        dev->userland_size = buffer_size;
        dev->userland_buffer = kmalloc (buffer_size, GFP_KERNEL);
        if (!dev->userland_buffer) {
                err("Couldn't allocate userland_buffer");
                goto error;
        }
 
	/* initialize the devfs node for this device and register it */
        dbg(__FUNCTION__ " - initialize the devfs node for this device and register it");
	sprintf(name, "darts-usb%d", dev->minor);
	
	dev->devfs = devfs_register (usb_devfs_handle, name,
				     DEVFS_FL_DEFAULT, USB_MAJOR,
				     DARTS_USB_MINOR_BASE + dev->minor,
				     S_IFCHR | S_IRUSR | S_IWUSR | 
				     S_IRGRP | S_IWGRP | S_IROTH, 
				     &darts_usb_fops, NULL);

       
        // Create a wait queue to allow reading process to block until the next datum is available
        init_waitqueue_head( &dev->read_queue );
 
        /* fill the URB data structure using the usb_fill_int_urb function in usb.h */
        dbg(__FUNCTION__ " - pipe = usb_rcvintpipe(udev, endpoint->bEndpointAddress);");
            pipe = usb_rcvintpipe(udev, endpoint->bEndpointAddress);
        dbg(__FUNCTION__ " - FILL_INT_URB");
        usb_fill_int_urb(dev->read_urb, udev, pipe, dev->interrupt_in_buffer,
                buffer_size, darts_usb_irq, dev, endpoint->bInterval);
        dbg(__FUNCTION__ " - if (usb_submit_urb(dev->read_urb))");

        // The second we submit the URB, the device may start to receive data.
        // It would be bad if darts_usb_irq were called before we were ready,
        // so call usb_submit_urb LAST after all buffers are allocated and all
        // parameters are set up.
       if (usb_submit_urb(dev->read_urb))
       {dbg(__FUNCTION__ " - goto error");
           goto error;
       }

        /* let the user know what node this device is now attached to */
	info ("DARTS USB device now attached to usb/darts-usb%d", dev->minor);
	goto exit;
	
error:
	darts_usb_delete (dev);
	dev = NULL;

exit:
	up (&minor_table_mutex);
	return dev;
}


 //	The opposite of probe, this function is called by the usb core when
 //	the device is removed from the system.
static void darts_usb_disconnect(struct usb_device *udev, void *ptr)
{
	struct darts_usb *dev;
	int minor;
	dbg(__FUNCTION__);

	dev = (struct darts_usb *)ptr;
	
	down (&minor_table_mutex);
	down (&dev->sem);
		
	minor = dev->minor;

	/* remove our devfs node */
	devfs_unregister(dev->devfs);

	dbg(__FUNCTION__ "usb_unlink_urb(dev->read_urb);" );
        usb_unlink_urb(dev->read_urb);

	/* if the device is not opened, then we clean up right now */
        if (!dev->open_count) {
		up (&dev->sem);
		darts_usb_delete (dev);
	} else {
		dev->udev = NULL;
		up (&dev->sem);
	}

	info("DARTS USB #%d now disconnected", minor);
	up (&minor_table_mutex);
        dbg(__FUNCTION__ " - returning");           
}


static int __init darts_usb_init(void)
{
	int result;
	dbg(__FUNCTION__);

	/* register this driver with the USB subsystem */
	result = usb_register(&darts_usb_driver);
	if (result < 0) {
		err("usb_register failed for the "__FILE__" driver. Error number %d",
		    result);
		return -1;
	}

	info(DRIVER_DESC " " DRIVER_VERSION);
	return 0;
}


static void __exit darts_usb_exit(void)
{
	dbg(__FUNCTION__);
	/* deregister this driver with the USB subsystem */
	usb_deregister(&darts_usb_driver);
}


module_init (darts_usb_init);
module_exit (darts_usb_exit);

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


