#include <rtl.h>
#include <time.h>
#include <pthread.h>

#ifndef CONFIG_RTL_CLOCK_GPOS
#error CONFIG_RTL_CLOCK_GPOS required
#endif

static pthread_t thread;
static int my_softirq;

void * start_routine(void *arg)
{
	hrtime_t abstime = clock_gethrtime(CLOCK_REALTIME) + 1000000000;

	struct sched_param p;
	p . sched_priority = 1;
	pthread_setschedparam (pthread_self(), SCHED_FIFO, &p);

	while (1) {
		clock_nanosleep (CLOCK_REALTIME, TIMER_ABSTIME,
			hrt2ts(abstime), NULL);
		rtl_global_pend_irq(my_softirq);
		abstime += 1000000000;
	}
	return 0;
}

static void my_handler(int irq,void *ignore,struct pt_regs *ignoreregs)
{
	struct timeval tv;
	int diff;
	hrtime_t now = clock_gethrtime(CLOCK_GPOS);
	hrtime_t linuxnow;

	do_gettimeofday(&tv);
	linuxnow = tv.tv_sec * (long long) 1000000000 + tv.tv_usec * 1000;

	diff = now - linuxnow;
	rtl_printf("diff = %d\n", diff);
}


int init_module(void)
{
	pthread_create (&thread, NULL, start_routine, 0);
	my_softirq = rtl_get_soft_irq(my_handler,"rtlinux test sofirq");
	return 0;
}

void cleanup_module(void) {
	rtl_free_soft_irq(my_softirq);
	pthread_cancel (thread);
	pthread_join (thread, NULL);
}
