/*
 * linux/atari/atakeyb.c
 *
 * Atari Keyboard driver for 680x0 Linux
 *
 * This file is subject to the terms and conditions of the GNU General Public
 * License.  See the file README.legal in the main directory of this archive
 * for more details.
 */

/*
 * Atari support by Robert de Vries
 * enhanced by Bjoern Brauel and Roman Hodek
 */

#include <linux/config.h>
#include <linux/sched.h>
#include <linux/keyboard.h>
#include <linux/delay.h>
#include <linux/timer.h>
#include <linux/interrupt.h>

#include <linux/ataritypes.h>
#include <linux/atariints.h>
#include <linux/atarihw.h>
#include <linux/atarikb.h>
#include <linux/atari_mouse.h>
#include <linux/atari_joystick.h>

extern void process_scancode (int);
static void atakeyb_rep( unsigned long ignore );

#define ATAKEY_CAPS	(58)
#define BREAK_MASK	(0x80)

typedef enum kb_state_t
{
    KEYBOARD, AMOUSE, RMOUSE, JOYSTICK, CLOCK
} KB_STATE_T;

typedef struct keyboard_state
{
    unsigned char  buf[6];
    int 	   len;
    KB_STATE_T	   state;
} KEYBOARD_STATE;

KEYBOARD_STATE kb_state;

#define	DEFAULT_KEYB_REP_DELAY	(HZ/4)
#define	DEFAULT_KEYB_REP_RATE	(HZ/25)

unsigned int key_repeat_delay = DEFAULT_KEYB_REP_DELAY;
unsigned int key_repeat_rate  = DEFAULT_KEYB_REP_RATE;


#if 0

/*
 * This table maps the Atari keyboard scan codes to
 * the Linux "virtual" scan codes.  These "virtual" scan
 * codes mostly conform to the scan codes given by an IBM
 * keyboard, except that the E0 xx codes are given unique
 * codes.  These are the codes > 96.  See linux/keyboard.h
 */

static unsigned char atari_kmap[] =
{
/* 00-03 */    KB_NONE,       KB_ESCAPE,    KB_1,	  KB_2,
/* 04-07 */    KB_3,	      KB_4,	    KB_5,	  KB_6,
/* 08-0B */    KB_7,	      KB_8,	    KB_9,	  KB_0,
/* 0C-0F */    KB_DASH,       KB_EQUAL,     KB_BACKSPACE, KB_TAB,
/* 10-13 */    KB_Q,	      KB_W,	    KB_E,	  KB_R,
/* 14-17 */    KB_T,	      KB_Y,	    KB_U,	  KB_I,
/* 18-1B */    KB_O,	      KB_P,	    KB_LSQUARE,   KB_RSQUARE,
/* 1C-1F */    KB_ENTER,      KB_LCTRL,	    KB_A,	  KB_S,
/* 20-23 */    KB_D,	      KB_F,	    KB_G,	  KB_H,
/* 24-27 */    KB_J,	      KB_K,	    KB_L,	  KB_SEMICOLON,
/* 28-2B */    KB_APOSTROPHE, KB_BACKQUOTE, KB_LSHIFT,    KB_BACKSLASH,
/* 2C-2F */    KB_Z,          KB_X,	    KB_C,	  KB_V,
/* 30-33 */    KB_B,          KB_N,	    KB_M,         KB_COMMA,
/* 34-37 */    KB_PERIOD,     KB_SLASH,     KB_RSHIFT,    KB_NONE,
/* 38-3B */    KB_LALT,       KB_SPACE,     KB_CAPS,      KB_F1,
/* 3C-3F */    KB_F2,         KB_F3,	    KB_F4,	  KB_F5,
/* 40-43 */    KB_F6,         KB_F7,        KB_F8,	  KB_F9,
/* 44-47 */    KB_F10,        KB_NONE,      KB_NONE,      KB_FIND,
/* 48-4B */    KB_UP,         KB_NONE,	    KB_KPMINUS,   KB_LEFT,
/* 4C-4F */    KB_NONE,       KB_RIGHT,     KB_KPPLUS,    KB_NONE,
/* 50-53 */    KB_DOWN,       KB_NONE,	    KB_INSERT,	  KB_DELETE,
/* 54-57 */    KB_NONE,	      KB_NONE,	    KB_NONE,	  KB_NONE,
/* 58-5B */    KB_NONE,	      KB_NONE,	    KB_NONE,      KB_NONE,
/* 5B-5F */    KB_NONE,       KB_NONE,      KB_NONE,	  KB_NONE,
/* 60-63 */    KB_LESS,       KB_UNDO,      KB_HELP,      KB_KPLPAR,
/* 64-67 */    KB_KPRPAR,     KB_KPDIVIDE,  KB_KPMULTIPLY,KB_KP7,
/* 68-6B */    KB_KP8,        KB_KP9,	    KB_KP4,	  KB_KP5,
/* 6C-6F */    KB_KP6,        KB_KP1,	    KB_KP2,	  KB_KP3,
/* 70-73 */    KB_KP0,        KB_KPDECIMAL, KB_KPENTER,	  KB_NONE,
/* 74-77 */    KB_NONE,       KB_NONE,	    KB_NONE,	  KB_NONE,
/* 78-7B */    KB_NONE,       KB_NONE,	    KB_NONE,	  KB_NONE,
/* 7C-7F */    KB_NONE,       KB_NONE,	    KB_NONE,	  KB_NONE
};

#endif


static unsigned char rep_scancode;
static struct timer_list atakeyb_rep_timer = { NULL, 0, 0, atakeyb_rep };


static void atakeyb_rep( unsigned long ignore )

{
	atakeyb_rep_timer.expires = key_repeat_rate;
	add_timer( &atakeyb_rep_timer );
	process_scancode( rep_scancode );
}


static void keyboard_interrupt(struct  intframe *fp, void *data)
{
  u_char acia_stat;
  int scancode;
  int break_flag;

  acia_stat = acia.key_ctrl;
  /* check out if the interrupt came from this ACIA */
  if (!(acia_stat & ACIA_IRQ))
	return;

    if (acia_stat & ACIA_RDRF)	/* received a character */
    {
	scancode = acia.key_data;	/* get it or reset the ACIA, I'll get it! */
	switch (kb_state.state)
	{
	  case KEYBOARD:
	    switch (scancode)
	    {
	      case 0xF7:
		kb_state.state = AMOUSE;
		kb_state.len = 0;
		break;

	      case 0xF8:
	      case 0xF9:
     	      case 0xFA:
	      case 0xFB:
		kb_state.state = RMOUSE;
	    	kb_state.len = 1;
		kb_state.buf[0] = scancode;
		break;

	      case 0xFC:
		kb_state.state = CLOCK;
		kb_state.len = 0;
		break;

	      case 0xFE:
	      case 0xFF:
		kb_state.state = JOYSTICK;
		kb_state.len = 1;
		kb_state.buf[0] = scancode;
		break;

	      default:
		break_flag = scancode & BREAK_MASK;
		scancode &= ~BREAK_MASK;

		if (break_flag) {
		    del_timer( &atakeyb_rep_timer );
		    rep_scancode = 0;
		}
		else {
		    del_timer( &atakeyb_rep_timer );
		    rep_scancode = scancode;
		    atakeyb_rep_timer.expires = key_repeat_delay;
		    add_timer( &atakeyb_rep_timer );
		}

		process_scancode( break_flag | scancode );
		break;
	    }
	    break;

	  case AMOUSE:
	    kb_state.buf[kb_state.len++] = scancode;
	    if (kb_state.len == 5)
	    {
		kb_state.state = KEYBOARD;
		/* not yet used */
		/* wake up someone waiting for this */
	    }
	    break;	

	  case RMOUSE:
	    kb_state.buf[kb_state.len++] = scancode;
	    if (kb_state.len == 3)
	    {
		kb_state.state = KEYBOARD;
		mouse_interrupt(kb_state.buf);
	    }
	    break;

	  case JOYSTICK:
	    kb_state.buf[1] = scancode;
	    kb_state.state = KEYBOARD;
	    joystick_interrupt(kb_state.buf);
	    break;

	  case CLOCK:
	    kb_state.buf[kb_state.len++] = scancode;
	    if (kb_state.len == 6)
	    {
		kb_state.state = KEYBOARD;
		/* wake up someone waiting for this.
		   But will this ever be used, as Linux keeps its own time.
		   Perhaps for synchronization purposes? */
		/* wake_up_interruptible(&clock_wait); */
	    }
	    break;
	}
    }

#ifdef KEYB_WRITE_INTERRUPT
    if (acia_stat & ACIA_TDRE)	/* transmit of character is finished */
    {
	if (kb_state.buf)
	{
	    acia.key_data = *kb_state.buf++;
	    kb_state.len--;
	    if (kb_state.len == 0)
	    {
		kb_state.buf = NULL;
		if (!kb_state.kernel_mode)
			/* unblock something */;
	    }
	}
    }
#endif

#if 0
    if (acia_stat & ACIA_CTS)
	/* cannot happen */;
#endif

    if (acia_stat & (ACIA_FE | ACIA_PE))
    {
	panic("Error in keyboard communication");
    }

    if (acia_stat & ACIA_OVRN)
    {
	/* a very fast typist or a slow system, give a warning */	
    }
}

#ifdef KEYB_WRITE_INTERRUPT
void ikbd_write(char *str, int len)
{
    u_char acia_stat;

    if (kb_stat.buf)
	/* wait */;
    acia_stat = acia.key_ctrl;
    if (acia_stat & ACIA_TDRE)
    {
	if (len != 1)
	{
	    kb_stat.buf = str 1;
	    kb_stat.len = len - 1;
	}
	acia.key_data = *str;
	/* poll */
    }
}
#else
/*
 * I write to the keyboard without using interrupts, I poll instead.
 * This takes for the maximum length string allowed (7) at 7812.5 baud
 * 8 data 1 start 1 stop bit: 9.0 ms
 * If this takes too long for normal operation, interrupt driven writing
 * is the solution. (I made a feeble attempt in that direction but I
 * kept it simple for now.)
 */
void ikbd_write(char *str, int len)
{
    u_char acia_stat;

    if ((len < 1) || (len > 7))
	panic("ikbd: maximum string length exceeded");
    while (len)
    {
	acia_stat = acia.key_ctrl;
	if (acia_stat & ACIA_TDRE)
	{
	    acia.key_data = *str++;
	    len--;
	}
    }
}
#endif

/* Reset (without touching the clock) */
void ikbd_reset(void)
{
    static char cmd[2] = { 0x80, 0x01 };
    
    ikbd_write(cmd, 2);

    /* if allswell code 0xF1 is returned, else the break codes of
       all keys making contact */
}

/* Set mouse button action */
void ikbd_mouse_button_action(int mode)
{
    char cmd[2] = { 0x07, mode };

    ikbd_write(cmd, 2);
}

/* Set relative mouse position reporting */
void ikbd_mouse_rel_pos(void)
{
    static char cmd[1] = { 0x08 };

    ikbd_write(cmd, 1);
}

/* Set absolute mouse position reporting */
void ikbd_mouse_abs_pos(int xmax, int ymax)
{
    char cmd[5] = { 0x09, xmax>>8, xmax&0xFF, ymax>>8, ymax&0xFF };

    ikbd_write(cmd, 5);
}

/* Set mouse keycode mode */
void ikbd_mouse_kbd_mode(int dx, int dy)
{
    char cmd[3] = { 0x0A, dx, dy };

    ikbd_write(cmd, 3);
}

/* Set mouse threshold */
void ikbd_mouse_thresh(int x, int y)
{
    char cmd[3] = { 0x0B, x, y };

    ikbd_write(cmd, 3);
}

/* Set mouse scale */
void ikbd_mouse_scale(int x, int y)
{
    char cmd[3] = { 0x0C, x, y };

    ikbd_write(cmd, 3);
}

/* Interrogate mouse position */
void ikbd_mouse_pos_get(int *x, int *y)
{
    static char cmd[1] = { 0x0D };

    ikbd_write(cmd, 1);

    /* wait for returning bytes */
}

/* Load mouse position */
void ikbd_mouse_pos_set(int x, int y)
{
    char cmd[6] = { 0x0E, 0x00, x>>8, x&0xFF, y>>8, y&0xFF };

    ikbd_write(cmd, 6);
}

/* Set Y=0 at bottom */
void ikbd_mouse_y0_bot(void)
{
    static char cmd[1] = { 0x0F };

    ikbd_write(cmd, 1);
}

/* Set Y=0 at top */
void ikbd_mouse_y0_top(void)
{
    static char cmd[1] = { 0x10 };

    ikbd_write(cmd, 1);
}

/* Resume */
void ikbd_resume(void)
{
    static char cmd[1] = { 0x11 };

    ikbd_write(cmd, 1);
}

/* Disable mouse */
void ikbd_mouse_disable(void)
{
    static char cmd[1] = { 0x12 };

    ikbd_write(cmd, 1);
}

/* Pause output */
void ikbd_pause(void)
{
    static char cmd[1] = { 0x13 };

    ikbd_write(cmd, 1);
}

/* Set joystick event reporting */
void ikbd_joystick_event_on(void)
{
    static char cmd[1] = { 0x14 };

    ikbd_write(cmd, 1);
}

/* Set joystick interrogation mode */
void ikbd_joystick_event_off(void)
{
    static char cmd[1] = { 0x15 };

    ikbd_write(cmd, 1);
}

/* Joystick interrogation */
void ikbd_joystick_get_state(void)
{
    static char cmd[1] = { 0x16 };

    ikbd_write(cmd, 1);
}

#if 0
/* This disables all other ikbd activities !!!! */
/* Set joystick monitoring */
void ikbd_joystick_monitor(int rate)
{
    static char cmd[2] = { 0x17, rate };

    ikbd_write(cmd, 2);

    kb_state.state = JOYSTICK_MONITOR;
}
#endif

/* some joystick routines not in yet (0x18-0x19) */

/* Disable joysticks */
void ikbd_joystick_disable(void)
{
    static char cmd[1] = { 0x1A };

    ikbd_write(cmd, 1);
}

/* Time-of-day clock set */
void ikbd_clock_set(int year, int month, int day, int hour, int minute, int second)
{
    char cmd[7] = { 0x1B, year, month, day, hour, minute, second };

    ikbd_write(cmd, 7);
}

/* Interrogate time-of-day clock */
void ikbd_clock_get(int *year, int *month, int *day, int *hour, int *minute, int second)
{
    static char cmd[1] = { 0x1C };

    ikbd_write(cmd, 1);
}

/* Memory load */
void ikbd_mem_write(int address, int size, char *data)
{
    panic("Attempt to write data into keyboard memory");
}

/* Memory read */
void ikbd_mem_read(int address, char data[6])
{
    char cmd[3] = { 0x21, address>>8, address&0xFF };

    ikbd_write(cmd, 3);

    /* receive data and put it in data */
}

/* Controller execute */
void ikbd_exec(int address)
{
    char cmd[3] = { 0x22, address>>8, address&0xFF };

    ikbd_write(cmd, 3);
}

/* Status inquiries (0x87-0x9A) not yet implemented */

unsigned long atari_keyb_init(unsigned long kmem_start)
{

  acia.key_ctrl = ACIA_RESET;		/* reset ACIA */

  /* divide 500kHz by 64 gives 7812.5 baud */
  /* 8 data no parity 1 start 1 stop bit */
  /* receive interrupt enabled */
#ifdef KEYB_WRITE_INTERRUPT
  /* RTS low, transmit interrupt enabled */
  acia.key_ctrl = (ACIA_DIV64|ACIA_D8N1S|ACIA_RLTIE|ACIA_RIE);
#else
  /* RTS low, transmit interrupt disabled */
  acia.key_ctrl = (ACIA_DIV64|ACIA_D8N1S|ACIA_RLTID|ACIA_RIE);
#endif

    add_isr(IRQ_MFP_ACIA, keyboard_interrupt, 0, NULL);

    ikbd_reset();
    ikbd_mouse_disable();
    ikbd_joystick_disable();

    kb_state.state = KEYBOARD;
    kb_state.len = 0;

	/* enable ACIA Interrupts */ 
	mfp.int_en_b |= 0x40;

  return kmem_start;
}
