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

#include <rtl_conf.h>
#ifndef CONFIG_RTL_SUSPEND_LINUX
#error CONFIG_RTL_SUSPEND_LINUX not enabled
#endif

pthread_t thread;
#define NUMBER_OF_WAITS 10000
#define NUMBER_OF_OUTER_ITERATIONS 500
#define NUMBER_OF_INNER_ITERATIONS 10000

void * start_routine(void *arg)
{
	int i,j;
	unsigned int starttime,endtime;
	unsigned int maxdiff= 0,mindiff = -1;
	unsigned int diff;
	int count = smp_num_cpus;
	rtl_printf("RTLinux Reserve_cpu thread starts on cpu %d and about to kill linux\n",hw_smp_processor_id());
	pthread_kill(pthread_linux(), RTL_SIG_SUSPEND_LINUX);/* off */
	for(i=0; i < NUMBER_OF_WAITS; i++){
		if(smp_num_cpus < count)break;
		else{ 
			nanosleep(hrt2ts(5000000UL), NULL);
		}
	}
	rtl_printf("RTLinux Reserve_cpu demo: Linux is asleep numcpus=%d\n",smp_num_cpus);

	for(j=0; j < NUMBER_OF_OUTER_ITERATIONS; j++){
		for(i=0; i < NUMBER_OF_INNER_ITERATIONS; i++){
			hrtime_t start = clock_gethrtime(CLOCK_REALTIME);
			starttime =(int) (start&0xffffffff) ;
			clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, hrt2ts(50000 + start), NULL);
			endtime =(int) (clock_gethrtime(CLOCK_REALTIME)&0xffffffff) ;
			if(endtime > starttime) { /* too lazy to worry about the
						     overflow cases every 4 seconds */
				diff = endtime - starttime;
				if(diff > maxdiff) {
					maxdiff=diff;
				}
				if(diff < mindiff) mindiff=diff;
if(hw_smp_processor_id() != smp_num_cpus)
{rtl_printf("RTLinux error running on processor %d\n",hw_smp_processor_id());
	pthread_kill(pthread_linux(), RTL_SIG_RESTART_LINUX);/* on */
break;
}
			}
		}
	rtl_printf("RESERVE Demo: %d: max=%d min=%d\n",j,maxdiff,mindiff);
	maxdiff = 0; mindiff = -1;
	}
	pthread_kill(pthread_linux(), RTL_SIG_RESTART_LINUX);/* on */
	rtl_printf("RTLinux RESERVE DEMO: end numcpus=%d\n",smp_num_cpus);

	return 0;
}

int init_module(void) {
	int last_cpu = smp_num_cpus -1; /* id of last CPU */
	pthread_attr_t attr;
	pthread_attr_init (&attr);
        pthread_attr_setcpu_np(&attr, last_cpu);
	return pthread_create (&thread, &attr, start_routine, 0);
}

void cleanup_module(void) {
	pthread_delete_np (thread);
	pthread_kill(pthread_linux(), RTL_SIG_RESTART_LINUX);/* on */
/* 	printk("RTLinux RESERVE DEMO: cleanup numcpus=%d\n",smp_num_cpus); */
}
