/*
linux/drivers/char/joystick.c
   Copyright (C) 1992, 1993 Arthur C. Smith
   Joystick driver for Linux running on an IBM compatible computer.

VERSION INFO:
01/08/93	ACS	0.1: Works but needs multi-joystick support
01/13/93	ACS	0.2: Added multi-joystick support (minor 0 and 1)
		  	     Added delay between measuring joystick axis
		   	     Added scaling ioctl
02/16/93	ACS	0.3: Modified scaling to use ints to prevent kernel
			     panics 8-)
02/28/93	ACS	0.4: Linux99.6 and fixed race condition in js_read.
			     After looking at a schematic of a joystick card
                             it became apparent that any write to the joystick
			     port started ALL the joystick one shots. If the
			     one that we are reading is short enough and the
			     first one to be read, the second one will return
			     bad data if it's one shot has not expired when
			     the joystick port is written for the second time.
			     Thus solves the mystery delay problem in 0.2!
05/05/93	ACS/Eyal 0.5:Upgraded the driver to the 99.9 kernel, added
			     joystick support to the make config options,
			     updated the driver to return the buttons as
			     positive logic, and read both axis at once
			     (thanks Eyal!), and added some new ioctls.
02/12/94    Jeff Tranter 0.6:Made necessary changes to work with 0.99pl15
                             kernel (and hopefully 1.0). Also did some
			     cleanup: indented code, fixed some typos, wrote
			     man page, etc...
2/12/95    Fork{} & DRW (from linuxnet) : Figured out why this thing 
wasnt compiling with newer 8x or where it stopped working kernels. Very 
easy. Just add #include "linux/mm.h" to it...Anyways it works again.. 
29/2/95	   Alex Hornby <w.a.hornby@dcs.warwick.ac.uk>
		Changed to work on kernels compiled with CONFIG_MODVERSIONS
		Thus fixing the undefined symbol errors it was getting. I will
		bravely call this 0.7.3. Possibly won't work on kernels 
		compiled without CONFIG_MODVERSIONS.
*/

#include "joystick.h"
#include "release.h"

static struct JS_DATA_SAVE_TYPE JS_DATA[JS_MAX];	/* misc data */
static int JS_EXIST;		/* which joysticks' axis exist? */
static int JS_READ_SEMAPHORE;	/* to prevent two processes
				 from trying to read different
				 joysticks at the same time */

/* get_timer0():
   returns the current value of timer 0. This is a 16 bit counter that starts
   at LATCH and counts down to 0 */
inline int get_timer0 (void)
{
	int t0, t1;
	outb (0, PIT_MODE);
	t0 = (int) inb (PIT_COUNTER_0);
	t1 = ((int) inb (PIT_COUNTER_0) << 8) + t0;
	return (t1);
}

static int js_ioctl (struct inode *inode,
		     struct file *file,
		     unsigned int cmd,
		     unsigned long arg)
{
	unsigned int minor, i, save_busy;
	char *c;
	minor = MINOR (inode->i_rdev);
	if (MAJOR (inode->i_rdev) != JOYSTICK_MAJOR)
		return -EINVAL;
	if (minor >= JS_MAX)
		return -ENODEV;
	if ((((inb (JS_PORT) & 0x0f) >> (minor << 1)) & 0x03) != 0)	/*js minor exists?*/
		return -ENODEV;
	switch (cmd) {
	case JS_SET_CAL:	/*from struct *arg to JS_DATA[minor]*/
		verify_area(VERIFY_READ, (void *) arg,
			     sizeof (struct JS_DATA_TYPE));
		c = (char *) &JS_DATA[minor].JS_CORR;
		for (i = 0; i < sizeof (struct JS_DATA_TYPE); i++)
			*c++ = get_fs_byte ((char *) arg++);
		break;
	case JS_GET_CAL:	/*to struct *arg from JS_DATA[minor]*/
		verify_area (VERIFY_WRITE, (void *) arg,
			     sizeof (struct JS_DATA_TYPE));
		c = (char *) &JS_DATA[minor].JS_CORR;
		for (i = 0; i < sizeof (struct JS_DATA_TYPE); i++)
			put_fs_byte (*c++, (char *) arg++);
		break;
	case JS_SET_TIMEOUT:
		verify_area (VERIFY_READ, (void *) arg,
			     sizeof (JS_DATA[0].JS_TIMEOUT));
		c = (char *) &JS_DATA[minor].JS_TIMEOUT;
		for (i = 0; i < sizeof (JS_DATA[0].JS_TIMEOUT); i++)
			*c++ = get_fs_byte ((char *) arg++);
		break;
	case JS_GET_TIMEOUT:
		verify_area (VERIFY_WRITE, (void *) arg,
			     sizeof (JS_DATA[0].JS_TIMEOUT));
		c = (char *) &JS_DATA[minor].JS_TIMEOUT;
		for (i = 0; i < sizeof (JS_DATA[0].JS_TIMEOUT); i++)
			put_fs_byte (*c++, (char *) arg++);
		break;
	case JS_SET_TIMELIMIT:
		verify_area (VERIFY_READ, (void *) arg,
			     sizeof (JS_DATA[0].JS_TIMELIMIT));
		c = (char *) &JS_DATA[minor].JS_TIMELIMIT;
		for (i = 0; i < sizeof (JS_DATA[0].JS_TIMELIMIT); i++)
			*c++ = get_fs_byte ((char *) arg++);
		break;
	case JS_GET_TIMELIMIT:
		verify_area (VERIFY_WRITE, (void *) arg,
			     sizeof (JS_DATA[0].JS_TIMELIMIT));
		c = (char *) &JS_DATA[minor].JS_TIMELIMIT;
		for (i = 0; i < sizeof (JS_DATA[0].JS_TIMELIMIT); i++)
			put_fs_byte (*c++, (char *) arg++);
		break;
	case JS_GET_ALL:
		verify_area (VERIFY_WRITE, (void *) arg,
			     sizeof (struct JS_DATA_SAVE_TYPE));
		c = (char *) &JS_DATA[minor];
		for (i = 0; i < sizeof (struct JS_DATA_SAVE_TYPE); i++)
			put_fs_byte (*c++, (char *) arg++);
		break;
	case JS_SET_ALL:
		verify_area (VERIFY_READ, (void *) arg,
			     sizeof (struct JS_DATA_SAVE_TYPE));
		save_busy = JS_DATA[minor].BUSY;
		c = (char *) &JS_DATA[minor];
		for (i = 0; i < sizeof (struct JS_DATA_SAVE_TYPE); i++)
			*c++ = get_fs_byte ((char *) arg++);
		JS_DATA[minor].BUSY = save_busy;
		break;
	default:
		return -EINVAL;
	}
	return 0;
}

static int js_open (struct inode *inode, struct file *file)
{
	unsigned int minor = MINOR (inode->i_rdev);
	int j;

	if (minor >= JS_MAX)
		return -ENODEV;	/*check for joysticks*/
	for (j = JS_DEF_TIMEOUT; (JS_EXIST & inb (JS_PORT)) && j; j--);
	cli ();			/*block js_read while JS_EXIST is being modified*/
	/*js minor exists?*/
	if ((((JS_EXIST = inb (JS_PORT)) >> (minor << 1)) & 0x03) != 0) {
		JS_EXIST = (~JS_EXIST) & 0x0f;
		sti ();
		return -ENODEV;
	}
	JS_EXIST = (~JS_EXIST) & 0x0f;
	sti ();
	if (JS_DATA[minor].BUSY)
		return -EBUSY;
	JS_DATA[minor].BUSY = JS_TRUE;
	JS_DATA[minor].JS_CORR.x = JS_DEF_CORR;	/*default scale*/
	JS_DATA[minor].JS_CORR.y = JS_DEF_CORR;
	JS_DATA[minor].JS_TIMEOUT = JS_DEF_TIMEOUT;
	JS_DATA[minor].JS_TIMELIMIT = JS_DEF_TIMELIMIT;
	JS_DATA[minor].JS_EXPIRETIME = CURRENT_JIFFIES;
	MOD_INC_USE_COUNT;
	return 0;
}

static void js_release (struct inode *inode, struct file *file)
{
	unsigned int minor = MINOR (inode->i_rdev);
	inode->i_atime = CURRENT_TIME;
	JS_DATA[minor].BUSY = JS_FALSE;
	MOD_DEC_USE_COUNT;
}

/* js_read() reads the buttons x, and y axis from both joysticks if a
 * given interval has expired since the last read or is equal to
 * -1l. The buttons are in port 0x201 in the high nibble. The axis are
 * read by writing to 0x201 and then measuring the time it takes the
 * one shots to clear.
 */

static int js_read (struct inode *inode, struct file *file, char *buf, int count)
{
	int j, chk;
	int t0, t_x0, t_y0, t_x1, t_y1;
	char *c;
	unsigned int minor, minor2;
	int buttons;

	if (count != JS_RETURN)
		return -EOVERFLOW;
	verify_area (VERIFY_WRITE, (void *) buf, sizeof (struct JS_DATA_TYPE));
	minor = MINOR (inode->i_rdev);
	inode->i_atime = CURRENT_TIME;
	if (CURRENT_JIFFIES > JS_DATA[minor].JS_EXPIRETIME) {
		minor2 = minor << 1;
		j = JS_DATA[minor].JS_TIMEOUT;
		for (; (JS_EXIST & inb (JS_PORT)) && j; j--);
		if (j == 0)
			return -ENODEV;	/*no joystick here*/
		while (1) {	/*Make sure no other proc is using port*/
			cli ();
			if (!JS_READ_SEMAPHORE) {
				JS_READ_SEMAPHORE++;
				sti ();
				break;
			}
			sti ();
		}
		buttons = ~(inb (JS_PORT) >> 4);
		JS_DATA[0].JS_SAVE.buttons = buttons & 0x03;
		JS_DATA[1].JS_SAVE.buttons = (buttons >> 2) & 0x03;
		j = JS_DATA[minor].JS_TIMEOUT;
		cli ();		/*no interupts!*/
		outb (0xff, JS_PORT);	/*trigger one-shots*/
		/*get init timestamp*/
		t_x0 = t_y0 = t_x1 = t_y1 = t0 = get_timer0 ();
		/*wait for an axis' bit to clear or timeout*/
		while (j-- && (chk = inb (JS_PORT) & JS_EXIST)) {
			if (chk & JS_X_0)
				t_x0 = get_timer0 ();
			if (chk & JS_Y_0)
				t_y0 = get_timer0 ();
			if (chk & JS_X_1)
				t_x1 = get_timer0 ();
			if (chk & JS_Y_1)
				t_y1 = get_timer0 ();
		}
		sti ();		/*allow interupts*/
		JS_READ_SEMAPHORE = 0;	/*allow other reads to progress*/
		if (j == 0)
			return -ENODEV;	/*read timed out*/
		JS_DATA[0].JS_EXPIRETIME = CURRENT_JIFFIES +
			JS_DATA[0].JS_TIMELIMIT;	/*update data*/
		JS_DATA[1].JS_EXPIRETIME = CURRENT_JIFFIES +
			JS_DATA[1].JS_TIMELIMIT;
		JS_DATA[0].JS_SAVE.x = DELTA_TIME (t0, t_x0) >>
			JS_DATA[0].JS_CORR.x;
		JS_DATA[0].JS_SAVE.y = DELTA_TIME (t0, t_y0) >>
			JS_DATA[0].JS_CORR.y;
		JS_DATA[1].JS_SAVE.x = DELTA_TIME (t0, t_x1) >>
			JS_DATA[1].JS_CORR.x;
		JS_DATA[1].JS_SAVE.y = DELTA_TIME (t0, t_y1) >>
			JS_DATA[1].JS_CORR.y;
	}
	for (c = (char *) &JS_DATA[minor].JS_SAVE, j = 0; j < JS_RETURN; j++)
		put_fs_byte (*c++, buf++);	/*copy to user space*/
	return JS_RETURN;
}


static struct file_operations js_fops =
{
	NULL,			/* js_lseek*/
	js_read,		/* js_read */
	NULL,			/* js_write*/
	NULL,			/* js_readaddr*/
	NULL,			/* js_select */
	js_ioctl,		/* js_ioctl*/
	NULL,			/* js_mmap */
	js_open,		/* js_open*/
	js_release,		/* js_release*/
	NULL			/* js_sync */
};

#ifdef __cplusplus
extern "C" {
#endif

int init_module (void) {
	unsigned char js_num;
	int j;
	  outb (0xff, JS_PORT);	/*trigger oneshots*/
	/*and see what happens*/
	for (j = JS_DEF_TIMEOUT; (0x0f & inb (JS_PORT)) && j; j--);
	  JS_EXIST = inb (JS_PORT) & 0x0f;	/*get joystick status byte*/
	switch (JS_EXIST) {
	case 0x00:
		js_num = 2;	/*Both joysticks are connected*/
		break;
		case 0x03:	/*Joystick 1 is connected*/
		case 0x0c:
		js_num = 1;	/*Joystick 0 is connected*/
		break;
		default:
		js_num = 0;	/*No joysticks*/
	}
	JS_EXIST = (~JS_EXIST) & 0x0f;
	  printk ("js_init: found %d joystick%c\n", js_num,
		    (js_num == 1) ? ' ' : 's');
	if (register_chrdev (JOYSTICK_MAJOR, "Joystick", &js_fops))
		  printk ("Unable to get major=%d for Joystick\n",
					JOYSTICK_MAJOR);
	for (js_num = 0; js_num < JS_MAX; js_num++)
		  JS_DATA[js_num].BUSY = JS_FALSE;
	  JS_READ_SEMAPHORE = 0;
	  return 0;
}

void cleanup_module (void)
{
	if (MOD_IN_USE)
		printk ("Joystick: device busy, remove delayed.\n");

	if (unregister_chrdev (JOYSTICK_MAJOR, "Joystick") != 0) {
		printk ("cleanup_module failed.\n");
	}
	else {
		printk ("cleanup_module succeeded.\n");
	}
}

#ifdef __cplusplus
}
#endif
