/*
 * obmouse.c, revision 0.3, 26 november 1999, grundler@cup.hp.com
 *
 *   removed ifdefs for EMULATE_SERIAL_MOUSE  and EMULATE_NCR_PEN.
 *   Only support "basic serial mouse protocol (gpm -t pnp)" which
 *   is also supported directly by Xfree.
 *
 *   Moved delta(x,y) calculations into ob_interrupt.
 *   If we only get interrupts when the mouse moves,
 *   then only need to update delta(x,y) then too.
 *
 *
 * obmouse.c, revision 0.2, 22 november 1999, grundler@cup.hp.com
 *
 *   "man mouse" explains really well how PNP mouse works. Read it.
 *
 *   Fixed algorithm which generated delta(x,y) from current-last
 *   position reported. Now handles "roll-over" properly and
 *   speed scales _inversely_ (ie bigger number is slower).
 *   "speed" parameter can be set with "insmod obmouse speed=5" (default).
 *
 *   added FIXME's to places things need to be enhanced.
 *
 *
 * obmouse.c, revision 0.1a, 16 november 1999, charles_slivkoff@hp.com
 *
 * Modifications by Chuck Slivkoff
 *    File did not compile as received
 *    Modified ob_write,ob_read parameters to match 2.2.x kernel
 *    Added uaccess.h
 *    Tried to fix ob_interrupt
 *
 * obmouse.c, revision 0.1, 17 february 1999, olivier_florent@hp.com
 *
 * This is an attempt to build a mouse driver for the proprietary pop-up
 * mouse found on HP omnibooks 600C and 600CT.  Pop-up mouse on later
 * omnibook * (i.e > 600) are covered by the standard ps/2 mouse driver.
 *
 * OB600C/CT mouse can be compared to a tablet, as absolute coordinates
 * are given by the hardware. I try to emulate a known mouse protocol to
 * be able to use this driver with common packages (gpm, xfree86, ...).
 *
 * The first one is the NCR tablet understood by gpm. It works clean with
 * gpm itself, but very badly with the repeater mode (-R option of gpm)
 * so it is not usable for X11.
 *
 * The second one is a basic serial mouse protocol. This works with
 * gpm -t pnp and Xfree86 as a standard Micro$oft mouse. But I have
 * to translate absolute coordinates to relative moves. This need to 
 * be improved a lot I think.
 *
 *
 * FIXME:
 * o This driver lacks a detection routine. i.e you must know that
 *   you have a 600C/CT before using it.
 *
 * o when you switch off the omnibook with the on/off button, and then
 *   switch back on, X11 loses contact with the driver. I do not know why.
 */

#include <linux/module.h>
#include <linux/kmod.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/signal.h>
#include <linux/errno.h>
#include <linux/mm.h>
#include <linux/random.h>
#include <linux/delay.h>	/* only used by OBMOUSE_DEBUG */
#include <linux/ioport.h>
#include <linux/wrapper.h>

#include <asm/io.h>
#include <asm/segment.h>
#include <asm/system.h>
#include <asm/irq.h>
#include <asm/uaccess.h>

#undef OBMOUSE_DEBUG		/* define to enable lots of printf */

/* name of the device */
#define OBMOUSE_DEV_NAME "obmouse"
#define OBMOUSE_REV "v0.3"


/*
** "speed" of the mouse. Determines how "fast" the mouse "moves".
** Similar (but not the same) as acceleration. Using slower acceleration
** together with lower speed value might result in better mouse control.
** I've only used the default acceleration.
*/
int speed = 4;	/* my personal preference */
MODULE_PARM(speed, "i");

/*
** OB 600 mouse doesn't completely act like a tablet.
** The xy-coordinates do in fact roll over which would
** not happen on a tablet.
*/
#define OB_ROLL_LIMIT 0xd00

/*
** The default '0' value lets insmod dynamically assign the next
** available MAJOR number. Use "speed" as an example of how to 
** make a parameter visible via insmod.
*/
static int  ob_major = 0 ; 

/*
** obmouse HW specific data
*/
#define OBMOUSE_BASE           (0x238)  /* base address of the hardware */
#define OBMOUSE_EXTENT         (3)      /* from 0x238 to 0x23b          */
#define OBMOUSE_IRQ            (12)     /* irq 12                       */

/* The 4 high bits of OBMOUSE_INTR_CTL */
#define OBMOUSE_BTN_IRQ_MASK   (0x10)    /* WR: enable/disable button irq   */
#define OBMOUSE_MOV_IRQ_MASK   (0x20)    /* WR: enable/disable movement irq */
#define OBMOUSE_BUTTON1_MASK   (0x40)    /* RD: status of button 1 */
#define OBMOUSE_BUTTON2_MASK   (0x80)    /* RD: status of button 2 */

#define OBMOUSE_COORD_ONLY(v)  ((v) & 0xfff)  /* ignore high 4 bits */

/* Convert BUTTON bits to byte 0 of serial output protocol */
#define OBMOUSE_BTN_SHIFT	10
#define OBMOUSE_BTN_MASK	0x30
#define OBMOUSE_BTN_MASK	0x30

#define OBMOUSE_INTR_CTL   (OBMOUSE_BASE+3)
#define OBMOUSE_INTR_BITS  (OBMOUSE_BTN_IRQ_MASK | OBMOUSE_MOV_IRQ_MASK)

/* Enable/disable both button and movement interrupt */
#define OBMOUSE_ENABLE_INTR()  outb(OBMOUSE_INTR_BITS,  OBMOUSE_INTR_CTL)
#define OBMOUSE_DISABLE_INTR() outb(~OBMOUSE_INTR_BITS, OBMOUSE_INTR_CTL)

/* Amount mouse has to move before the hardware launchs a new
** interrupt (I think). 0x08 is the standard value.
** Write value to OBMOUSE_BASE each time an interrupt is handled to
** enable the next one.
*/
#define OBMOUSE_SENSITIVITY    (0x08)

/* reset the sensitivity to enable next interrupt */
#define OBMOUSE_ENABLE_SENSE() outb(OBMOUSE_SENSITIVITY,OBMOUSE_BASE) 
#define OBMOUSE_DISABLE_SENSE() outb(0,OBMOUSE_BASE) 

/* obmouse must be on the 12 IRQ. Remove 'static' to enable */
/* ob_irq to become an exported ksym, an to be able to set  */
/* its value at module loading : "insmod obmouse ob_irq=5 for example */
static int ob_irq = OBMOUSE_IRQ;

/* The struct where I put the data while reading the hardware */
struct obmouse_data {
	char          found  ; /* 0=notfound, 1=found  */
	char          opened ; /* 0=closed, 1=opened  */

	char serial_byte_id;
	char pad;

	/* ob_interrupt updates delta(x,y) */
	/* simple difference between raw(x,y) - last(x,y) */
	short deltax;
	short deltay;

	/* ob_interrupt updates raw(x,y) */
	unsigned short rawx;	/* unprocessed values read by the interrupt */
	unsigned short rawy;	/* y contains button status! */

	/* ob_read updates last(x,y) and read_d(x,y) */
	unsigned short lastx;
	unsigned short lasty;

	/* tmp storage for ob_read routine */
	short read_dx;
	short read_dy;
};
static struct obmouse_data ob ;



/*
** Omnibook 600 mouse ISR.
** Read the HW state and resets "SENSITIVITY" in order to re-arm
** the interrupt.
*/
static void
ob_interrupt(int irq, void *dev_id, struct pt_regs *regs)
{
	ob.rawx = inb(OBMOUSE_BASE+0) + (inb(OBMOUSE_BASE+1) << 8);
	ob.rawy = inb(OBMOUSE_BASE+2) + (inb(OBMOUSE_BASE+3) << 8);

#ifdef OBMOUSE_DEBUG
/* This printk is really useful for learning how the mouse
** actually behaves. Not as good as docs (which I don't have) though.
** - ggg
*/
printk("ob_intr: %4x,%4x\n", ob.rawx, ob.rawy);
#endif

	/* reset the sensitivity */
	OBMOUSE_ENABLE_SENSE();

	/* ------------------------------------
	**  update delta(x,y) values.
	** ------------------------------------
	*/

	ob.deltax = (short) ob.rawx - (short) ob.lastx ;
	ob.deltay = (short) OBMOUSE_COORD_ONLY(ob.rawy) - (short) ob.lasty ;

	/*
	** If only a button was pushed, one could return here.
	** But I suspect the mouse is too sensitive.
	** When a button is pushed, we'll *probably* get a measurable
	** movement and thus never end up exercising this optimization.
	*/

	/*
	** determine if the reading "rolled" over.
	** Not fool-proof but should be good enough.
	*/
	if (ob.deltax > OB_ROLL_LIMIT) {
		/*
		** 0xf80 - 0x80 = 0xf00 (and we want 0x100)
		*/
		ob.deltax = 0x1000 - ob.deltax;
	} else if (-ob.deltax > OB_ROLL_LIMIT) {
		/*
		** 0x80 - 0xf80 = -0xf00 (and we want -0x100)
		** -0x1000 - (-0xf00) = -0x1000 + 0xf00 = -0x100
		*/
		ob.deltax = -0x1000 - ob.deltax;
	}

	/* Same story with the Y-coordinate */	
	if (ob.deltay > OB_ROLL_LIMIT) {
		ob.deltay = 0x1000 - ob.deltay;
	} else if (-ob.deltay > OB_ROLL_LIMIT) {
		ob.deltay = -0x1000 - ob.deltay;
	}

	ob.deltax /= speed;	/* scale */
	ob.deltay /= speed;

	ob.deltax = -ob.deltax;	/* remap to same coord system */
}


static int
ob_read(struct file *file, char *buffer, size_t count, loff_t *poss)
{
	/*
	** For the serial mouse, 3 bytes are sent.
	** Bit 7 is always 0 (ignored).
	** Bit 6 in the first byte is set and clear in the 2cd and 3rd bytes.
	** Caller uses bit 6 to "sync" with the input data stream.
	**
	** first_data_byte = 0  1  L   R  dy7 dy6 dx7 dx6
	** 2nd_data_byte   = 0  0 dx5 dx4 dx3 dx2 dx1 dx0
	** 3rd_data_byte   = 0  0 dy5 dy4 dy3 dy2 dy1 dy0
	*/
     
	if (count < 1) { 
		printk("ob_read(%d bytes) : must read at least 1 byte (serial mouse protocol\n",count);
		return -EINVAL ;
	}

	switch (ob.serial_byte_id) {
		unsigned char buttons;

	case 0:
		/*
		** Writing the obmouse controller to disable/enable
		** IRQs has a nice side effect: the controller is
		** re-armed to generate interrupts again after a
		** on/off (button label, a form of suspend/resume)
		** power cycle. disable_irq()/enable_irq() do the
		** same thing and cost just as much (in terms
		** of I/O port accesses).
		*/
		OBMOUSE_DISABLE_INTR();	/* data may NOT change */

		/* save delta in case more intrs come in. */
		ob.read_dx = ob.deltax;
		ob.read_dy = ob.deltay;

		ob.deltax = ob.deltay = 0;

		/*
		** update last(x,y) intr handler calculates delta based on
		** most recent thing that ob_read has digested.
		*/
		ob.lastx = ob.rawx;
		ob.lasty = OBMOUSE_COORD_ONLY(ob.rawy);

		/* copy button status bits to PNP byte 0 */
		buttons = ((unsigned char) (ob.rawy >> OBMOUSE_BTN_SHIFT));

		OBMOUSE_ENABLE_INTR();	/* data may now change again */


		buttons &= OBMOUSE_BTN_MASK;	/* clear everything else */
		buttons ^= OBMOUSE_BTN_MASK;	/* invert logic */

		/* serial mouse protocol wants d(x,y) in the range -127/+127 */
		if (ob.read_dx >  127) ob.read_dx =  127;
		if (ob.read_dx < -127) ob.read_dx = -127;
		if (ob.read_dy >  127) ob.read_dy =  127;
		if (ob.read_dy < -127) ob.read_dy = -127;

		/* first_data_byte = 0  1  L   R  dy7 dy6 dx7 dx6  */
		put_user(0x40 | buttons | 
			(((char)ob.read_dy >> 4) & 0x0c) | 
			(((char)ob.read_dx >> 6) & 0x03)
			,buffer);

		/* serial_byte_id is 0, 1, 2, 0, 1, 2, 0, ... */
		ob.serial_byte_id++;
		break;

	case 1:		/* 2nd_data_byte   = 0  0 dx5 dx4 dx3 dx2 dx1 dx0  */
		put_user((char)ob.read_dx & 0x3f,buffer) ;
		ob.serial_byte_id++;
		break;

	case 2:		/* 3rd_data_byte   = 0  0 dy5 dy4 dy3 dy2 dy1 dy0  */
		put_user((char)ob.read_dy & 0x3f,buffer) ;
		ob.serial_byte_id = 0;
		break;

#ifdef OBMOUSE_DEBUG
	default:
		panic(OBMOUSE_DEV_NAME ": serial_byte_id is bogus");
#endif /* OBMOUSE_DEBUG */
	}
	return 1 ; /* return one byte at a time */
}


static ssize_t
ob_write(struct file *file, const char *buffer, size_t count, loff_t *ppos )
{
#ifdef OBMOUSE_DEBUG
	int i; 
	printk("ob_write(");

	for (i = 0 ; i < count ; i ++) {
		unsigned int tmp;
		int j = get_user(tmp, (buffer + i));
		printk("%d:%d ",j,tmp);
	}
	printk(")\n");
#endif
	return -EINVAL;
}


static int
ob_open(struct inode *inode, struct file *file)
{
	/* init_module must have failed */
	if (!ob.found) 
		return -EINVAL;

	/* device is already opened */
	if (ob.opened)
		return -EBUSY;

#ifdef OBMOUSE_DEBUG
printk(OBMOUSE_DEV_NAE ": attempt request irq %d\n",ob_irq);
#endif

	/* Try to get the interrupt */
	if (request_irq(ob_irq,ob_interrupt,0,OBMOUSE_DEV_NAME,NULL)) {
		printk (OBMOUSE_DEV_NAME ": request_irq failed for %d\n",ob_irq);
		return -EBUSY;
	}

#ifdef OBMOUSE_DEBUG
printk(OBMOUSE_DEV_NAME ": irq %d registered\n",ob_irq);
#endif

	ob.rawx = inb(OBMOUSE_BASE+0) + (inb(OBMOUSE_BASE+1) << 8);
	ob.rawy = inb(OBMOUSE_BASE+2) + (inb(OBMOUSE_BASE+3) << 8);

	ob.lastx = ob.rawx;
	ob.lasty = OBMOUSE_COORD_ONLY(ob.rawy);

	/* start with no movement */
	ob.deltax = 0;
	ob.deltay = 0;

	OBMOUSE_ENABLE_INTR() ;
	OBMOUSE_ENABLE_SENSE() ;

	MOD_INC_USE_COUNT;
	ob.opened = 1 ;
	return 0;
}


/*
 * obmouse closing function
 */
static int
ob_close(struct inode *inode, struct file *file)
{
  /* init_module must have failed */
  if (!ob.found) 
	return ENXIO;

  /* device has never been opened */
  if (!ob.opened)
	return ENODEV;

  OBMOUSE_DISABLE_INTR() ;

  /* release the irq */
  free_irq(ob_irq,NULL);

  MOD_DEC_USE_COUNT;
  ob.opened = 0 ;

  return 0;
}



/*
 * fops structure for obmouse
 */
struct file_operations ob_fops = {
	NULL,		/* seek() */
	ob_read,	/* read() */
	ob_write,	/* write() */
	NULL,		/* readdr() */
	NULL,		/* select() */
	NULL,		/* ioctl() FIXME: is this just for real serial mice? */
	NULL,		/* mmap() */
	ob_open,	/* open() */
        NULL,           /* flush() */
	ob_close,	/* release() */
};


int init_module(void)
{
	int ret ;

	ob.found  = 0 ; /* until we found it ... */
	ob.opened = 0 ;

	printk(OBMOUSE_DEV_NAME ": " OBMOUSE_REV \
		" HP omnibook 600C/CT pop-up mouse (base 0x%x irq %d speed %d)\n",
		OBMOUSE_BASE, ob_irq, speed);

	/* try to acess obmouse ioport region */
	if (check_region(OBMOUSE_BASE,OBMOUSE_EXTENT)) {
		printk(OBMOUSE_DEV_NAME ": Region starting at %x through %x is already occuped\n",
			OBMOUSE_BASE,OBMOUSE_BASE + OBMOUSE_EXTENT);
		return -EIO ; 
	}

	/* Get the region now */
	request_region(OBMOUSE_BASE,OBMOUSE_EXTENT,OBMOUSE_DEV_NAME);

	ret = module_register_chrdev(ob_major,OBMOUSE_DEV_NAME,&ob_fops);

	if (ret < 0) {
		printk(OBMOUSE_DEV_NAME ": register_chrdev failed! major %d return %d\n",
			ob_major, ret);
		return ret;
	}

	ob_major = ret ;

	printk( OBMOUSE_DEV_NAME ": create special file with 'mknod /dev/obmouse c %d 0'\n",ob_major);

	OBMOUSE_DISABLE_INTR() ;
	OBMOUSE_DISABLE_SENSE() ;

	ob.found = 1;
	return 0;
}

void cleanup_module(void)
{
	int ret ;

	OBMOUSE_DISABLE_INTR() ;
	OBMOUSE_DISABLE_SENSE() ;

	release_region(OBMOUSE_BASE,OBMOUSE_EXTENT);
	ret = module_unregister_chrdev(ob_major,OBMOUSE_DEV_NAME);
	if (ret < 0) {
		printk(OBMOUSE_DEV_NAME ": unregister_chrdev failed! ret %d\n",
			ret);
	} else {
		printk(OBMOUSE_DEV_NAME ": HP omnibook 600C/CT pop-up mouse driver closed\n");
	}
}

