/* $Id: fasttimer.c,v 1.1 2000/10/26 15:49:16 johana Exp $
 * linux/arch/etrax100/kernel/fasttimer.c
 * 
 * Fast timers for ETRAX100
 * This may be useful in other OS than Linux so use 2 space indentation...
 *
 * $Log: fasttimer.c,v $
 * Revision 1.1  2000/10/26 15:49:16  johana
 * Added fasttimer, highresolution timers.
 * 
 *
 * Copyright (C) 2000, Axis Communications AB, Lund, Sweden
 */

#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/param.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/time.h>
#include <linux/delay.h>

#include <asm/segment.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/delay.h>
#include <asm/rtc.h>

#include <linux/timex.h>
#include <linux/config.h>

#include <asm/svinto.h>
#include <asm/fasttimer.h>
#include <linux/proc_fs.h>

#define TIMER1_IRQ_NBR 3

//#define FAST_TIMER_TEST

#define D1(x)
#define D2(x)
#define DP(x)

/* The timer0 values gives 52us resolution (1/19200) but interrupts at HZ */
/* We use timer1 to generate interrupts at desired times. */

#define TIMER0_FREQ (19200)
#define TIMER0_CLKSEL c19k2Hz
#define __INLINE__ inline

static int fast_timer_running = 0;
static int fast_timer_started = 0;
static int fast_timer_is_init = 0;
static int fast_timer_ints = 0;


static struct fast_timer *fast_timer_list = NULL;


/* The frequencies for index = clkselx number in R_TIMER_CTRL */
#define NUM_TIMER_FREQ 15
#define MAX_USABLE_TIMER_FREQ 7
#define MAX_DELAY_US  853333L
const unsigned long timer_freq_100[NUM_TIMER_FREQ] = 
{
  3,   /* 0 3333 - 853333 us */ 
  6,   /* 1 1666 - 426666 us */
  12,  /* 2  833 - 213333 us */
  24,  /* 3  416 - 106666 us */
  48,  /* 4  208 -  53333 us */
  96,  /* 5  104 -  26666 us */
  192, /* 6   52 -  13333 us */
  384, /* 7   26 -   6666 us */
  576,
  1152,
  2304,
  4608,
  9216,
  18432,
  62500,
  /* 15 = cascade */
};
#define NUM_TIMER_STATS 32
int timer_div_settings[NUM_TIMER_STATS];
int timer_freq_settings[NUM_TIMER_STATS];
int timer_delay_settings[NUM_TIMER_STATS];




int __INLINE__ timeval_cmp(struct timeval *t0, struct timeval *t1)
{
  if (t0->tv_sec < t1->tv_sec)
  {
    return -1;
  }
  else if (t0->tv_sec > t1->tv_sec)
  {
    return 1;
  }
  if (t0->tv_usec < t1->tv_usec)
  {
    return -1;
  }
  else if (t0->tv_usec > t1->tv_usec)
  {
    return 1;
  }
  return 0;
}

void __INLINE__ start_timer1(unsigned long delay_us)
{
  int freq_index = 0; /* This is the lowest resolution */
  unsigned long upper_limit = MAX_DELAY_US;
  
  unsigned long div;
  /* Start/Restart the timer to the new shorter value */
  /* t = 1/freq = 1/19200 = 53us
   * T=div*t,  div = T/t = delay_us*freq/1000000
   */
#if 1 /* Adaptive timer settings */
  while (delay_us < upper_limit && freq_index < MAX_USABLE_TIMER_FREQ)
  {
    freq_index++;
    upper_limit >>= 1; /* Divide by 2 using shift */
  }
  if (freq_index > 0)
  {
    freq_index--;
  }
#else
  freq_index = 6;
#endif    
  div = delay_us*timer_freq_100[freq_index]/10000;
  if (div < 2)
  {
    /* Maybe increase timer freq? */
    div = 2;
  }
  if (div > 255)
  {
    div = 0; /* This means 256, the max the timer takes */
    /* Longer timeout then the timer can handle,
     *  we must restart it when it goes off.
     */
  }

  timer_div_settings[fast_timer_started % NUM_TIMER_STATS] = div;
  timer_freq_settings[fast_timer_started % NUM_TIMER_STATS] = freq_index;
  timer_delay_settings[fast_timer_started % NUM_TIMER_STATS] = delay_us;
  

  D1(printk("start_timer1 : %d us freq: %i div: %i\n", 
            delay_us, freq_index, div));
  *R_TIMER_CTRL = r_timer_ctrl_shadow = 
    (r_timer_ctrl_shadow &
     ~IO_MASK(R_TIMER_CTRL, timerdiv1) &
     ~IO_MASK(R_TIMER_CTRL, tm1) &
     ~IO_MASK(R_TIMER_CTRL, clksel1)) | 
    IO_FIELD(R_TIMER_CTRL, timerdiv1, div) |
    IO_STATE(R_TIMER_CTRL, tm1, stop_ld) | 
    IO_FIELD(R_TIMER_CTRL, clksel1, freq_index ); /* 6=c19k2Hz */
  
  *R_TIMER_CTRL = r_timer_ctrl_shadow = 
    (r_timer_ctrl_shadow & ~IO_MASK(R_TIMER_CTRL, tm1)) |
    IO_STATE(R_TIMER_CTRL, tm1, run);
  
  /* enable timer1 irq */

  *R_IRQ_MASK0_SET = IO_STATE(R_IRQ_MASK0_SET, timer1, set);
  fast_timer_started++;
  fast_timer_running = 1;
}


void start_one_shot_timer(struct fast_timer *t,
                          fast_timer_function_type *function,
                          unsigned long data,
                          unsigned long delay_us,
                          const char *name)
{
	unsigned long flags;
  struct fast_timer *tmp;
  D1(printk("sft %s %d us\n", name, delay_us));
	save_flags(flags);
	cli();  
  do_gettimeofday(&t->tv_set); /* This take like 100us to run!? */
  tmp = fast_timer_list;
  t->function = function;
  t->data = data;
  t->name = name;
  
  t->tv_expires.tv_usec = t->tv_set.tv_usec + delay_us%1000000;
  t->tv_expires.tv_sec  = t->tv_set.tv_sec + delay_us/1000000;
  /* Check if this should timeout before anything else */
  if (tmp == NULL || timeval_cmp(&t->tv_expires, &tmp->tv_expires) < 0)
  {
     /* Put first in list and modify the timer value */
    t->prev = NULL;
    t->next = fast_timer_list;
    fast_timer_list = t;
    start_timer1(delay_us);
  }else{
  /* Put in correct place in list */
    while (tmp->next && 
           timeval_cmp(&t->tv_expires, &tmp->next->tv_expires) > 0)
    {
      tmp = tmp->next;
    }
    /* Insert t after tmp */
    t->prev = tmp;
    t->next = tmp->next;
    tmp->next->prev = t;
    tmp->next = t;
  }
  D2(printk("start_one_shot_timer: %d us done\n", delay_us));
	restore_flags(flags);
}

/* Interrupt routines or functions called in interrupt context */

/* Timer 1 interrupt handler */

static void
timer1_handler(int irq, void *dev_id, struct pt_regs *regs)
{
  struct fast_timer *t = fast_timer_list;

  /* Ack interrupt */
	*R_TIMER_CTRL = r_timer_ctrl_shadow | 
		IO_STATE(R_TIMER_CTRL, i1, clr);

  /* Stop timer */
  *R_TIMER_CTRL = r_timer_ctrl_shadow = 
    (r_timer_ctrl_shadow & ~IO_MASK(R_TIMER_CTRL, tm1)) |
    IO_STATE(R_TIMER_CTRL, tm1, stop_ld);
  
  *R_IRQ_MASK0_CLR = IO_STATE(R_IRQ_MASK0_CLR, timer1, clr);
  fast_timer_ints++;
 
  while (t)
  {
    struct timeval tv;
    /* Has it really expired? */
    do_gettimeofday(&tv);
    D1(printk("t: %is %06ius\n", tv.tv_sec, tv.tv_usec));
    
    if (timeval_cmp(&t->tv_expires, &tv) <= 0)
    {
      /* Yes it has expired */
      /* remove this timer before call, since it can reuse the timer */
      fast_timer_list = t->next;
      if (t->function != NULL && fast_timer_running){
        t->function(t->data);
      }
      else
      {
        printk("t?!\n");
      }

      /* Go to next */
      t = t->next;
    }
    else
    {
      /* Timer is to early, let's set it again using the normal routines */
      D1(printk(".\n"));
    }
    
    
    if (t != NULL)
    {
      /* Start next timer.. */
      long us;
      struct timeval tv;
      t->prev = NULL;
      do_gettimeofday(&tv);
      us = ((t->tv_expires.tv_sec - tv.tv_sec) * 1000000 +
            t->tv_expires.tv_usec - tv.tv_usec);
      if (us > 0)
      {
        start_timer1(us);
        return;
      }
      else
      {
        /* Timer already expired, let's handle it better late then never.
         * The normal loop handles it 
         */
        D1(printk("e! %d\n", us));
      }
    }
  }
  D1(printk("t1 stop!\n"));
}

static void wake_up_func(unsigned long data)
{
  wake_up((struct wait_queue **)data);
}


/* Useful API */


void schedule_usleep(unsigned long us)
{
  struct fast_timer t;
  struct wait_queue *sleep_wait = NULL;
  struct wait_queue wait = { current, NULL };
  printk("schedule_usleep(%d)\n", us);
  add_wait_queue(&sleep_wait, &wait);
  current->state = TASK_INTERRUPTIBLE;
  start_one_shot_timer(&t, wake_up_func, (unsigned long)&sleep_wait, us, 
                       "usleep");
  schedule();
  current->state = TASK_RUNNING;
  remove_wait_queue(&sleep_wait, &wait);
  printk("done schedule_usleep(%d)\n", us);
}

#ifdef CONFIG_PROC_FS
static int proc_fasttimer_read(char *buf, char **start, off_t offset, 
                                 int len, int unused);
static struct proc_dir_entry fasttimer_proc_entry =  
{
	0, 9, "fasttimer",
	S_IFREG | S_IRUGO, 1, 0, 0,
	0, NULL /* ops -- default to array */,
	&proc_fasttimer_read /* get_info */,
};
#endif /* CONFIG_PROC_FS */

#ifdef CONFIG_PROC_FS
static int proc_fasttimer_read(char *buf, char **start, off_t offset, 
                               int len, int unused)
{
	unsigned long flags;
	int i = 0;
  int num_to_show;
  struct timeval tv;
  struct fast_timer *t, *nextt;
  do_gettimeofday(&tv);  
	len = 0;
  len += sprintf(buf +len, "fast_timer_ints: %i\n", 
                 fast_timer_ints);
  len += sprintf(buf +len, "fast_timer_started: %i\n", 
                 fast_timer_started);
  len += sprintf(buf +len, "fast_timer_running: %i\n", 
                 fast_timer_running);
  len += sprintf(buf +len, "current time: %is %06ius\n", 
                 tv.tv_sec,
                 tv.tv_usec);
  num_to_show = (fast_timer_started < NUM_TIMER_STATS ? fast_timer_started: 
                 NUM_TIMER_STATS);
  
  for (i=0; i < num_to_show; i++)
  {
    len += sprintf(buf +len, "div: %i freq: %i delay: %i\n", 
                   timer_div_settings[i],
                   timer_freq_settings[i],
                   timer_delay_settings[i]);
  }

	save_flags(flags);
	cli();    
  t = fast_timer_list;
	while (t != NULL)
  {
    nextt = t->next;
    restore_flags(flags);
    len += sprintf(buf +len, "%-10s set: %is %06ius exp: %is %06ius "
                   "data: 0x%08X"
/*                     " func: 0x%08X"*/
                   "\n", 
                   t->name,
                   t->tv_set.tv_sec,
                   t->tv_set.tv_usec,
                   t->tv_expires.tv_sec,
                   t->tv_expires.tv_usec,
                   t->data
/*                     ,t->function*/
                   );
    cli();    
    if (t->next != nextt)
    {
      printk("timer removed!\n");
    }
    t = nextt;
	}
  restore_flags(flags);
	return len;
}

#endif /* PROC_FS */

#ifdef FAST_TIMER_TEST
static volatile unsigned long i = 0;
static volatile int num_test_timeout = 0;
struct fast_timer tr[10];
int exp_num[10];

struct timeval tv_exp[10];

void test_timeout(unsigned long data)
{
  do_gettimeofday(&tv_exp[data]);
  exp_num[data] = num_test_timeout;
  
  num_test_timeout++;
}
void test_timeout1(unsigned long data)
{
  struct test_struct *ts = &tr[data];
  do_gettimeofday(&tv_exp[data]);
  exp_num[data] = num_test_timeout;
  if (data < 7)
  {
     start_one_shot_timer(&tr[i], test_timeout1, i,
                      1000, "timeout1"); 
     i++;
  }
  num_test_timeout++;
}

void fast_timer_test(void)
{
  char buf0[2000];
  char buf1[2000];
  char buf2[2000];
  char buf3[2000];
  char buf4[2000];
  char buf5[2000];
  char buf6[2000];
  int prev_num;
  int j;
  struct timeval tv;
  
  do_gettimeofday(&tv);
  
  printk("fast_timer_test() %is %08i\n", tv.tv_sec, tv.tv_usec);
  
  start_one_shot_timer(&tr[i], test_timeout, i,
                       50000, "test0");
  DP(proc_fasttimer_read(buf0, NULL, 0, 0, 0));
  i++;
  start_one_shot_timer(&tr[i], test_timeout, i,
                       70000, "test1");
  DP(proc_fasttimer_read(buf1, NULL, 0, 0, 0));
  i++;
  start_one_shot_timer(&tr[i], test_timeout, i,
                       40000, "test2");
  DP(proc_fasttimer_read(buf2, NULL, 0, 0, 0));
  i++;
  start_one_shot_timer(&tr[i], test_timeout, i,
                       60000, "test3");
  DP(proc_fasttimer_read(buf3, NULL, 0, 0, 0));
  i++;
  start_one_shot_timer(&tr[i], test_timeout1, i,
                       55000, "test4xx");
  DP(proc_fasttimer_read(buf4, NULL, 0, 0, 0));
  i++;
  do_gettimeofday(&tv);
  printk("Timers started    %is %08i\n", tv.tv_sec, tv.tv_usec);
  proc_fasttimer_read(buf5, NULL, 0, 0, 0);

  prev_num = num_test_timeout;
  while (num_test_timeout < i)
  {
    if (num_test_timeout != prev_num)
    {
      prev_num = num_test_timeout;

    }
  }
  do_gettimeofday(&tv);
  printk("Timers done       %is %08i\n", tv.tv_sec, tv.tv_usec);
  DP(printk("buf0:\n");
     printk(buf0);
     printk("buf1:\n");
     printk(buf1);
     printk("buf2:\n");
     printk(buf2);
     printk("buf3:\n");
     printk(buf3);
     printk("buf4:\n");
     printk(buf4);
  );
  printk("buf5:\n");
  printk(buf5);
   
  printk("timers set:\n");
  for(j = 0; j<i; j++)
  {
    struct fast_timer *t = &tr[j];
    printk("%-10s set: %is %06ius exp: %is %06ius "
           "data: 0x%08X func: 0x%08X\n", 
           t->name,
           t->tv_set.tv_sec,
           t->tv_set.tv_usec,
           t->tv_expires.tv_sec,
           t->tv_expires.tv_usec,
           t->data,
           t->function
           );

    printk("                                did exp: %is %06ius as #%i\n", 
           tv_exp[j].tv_sec,
           tv_exp[j].tv_usec,
           exp_num[j]);
    
  }
  proc_fasttimer_read(buf5, NULL, 0, 0, 0);
  printk("buf5 after all done:\n");
  printk(buf5);
  
}
#endif


void fast_timer_init(void)
{
  if (!fast_timer_is_init)
  {
    printk("fast_timer_init()\n");
#ifdef CONFIG_PROC_FS
    proc_register_dynamic(&proc_root, &fasttimer_proc_entry);	
#endif /* PROC_FS */
    if(request_irq(TIMER1_IRQ_NBR, timer1_handler, SA_SHIRQ,
                   "fast timer int", NULL)) {
      printk("err: timer1 irq\n");
    }
    fast_timer_is_init = 1;
#ifdef FAST_TIMER_TEST
    fast_timer_test();
#endif
  }
}
