Esempio n. 1
0
int main(void)
{
  RT_TASK *task;
  RTIME now;
  int cnt=0;

  // make main thread LXRT soft realtime
  task = rt_task_init_schmod(nam2num("MYTASK"), 9, 0, 0, SCHED_FIFO, 0xF);
  mlockall(MCL_CURRENT | MCL_FUTURE);

  // start realtime timer and scheduler
  //rt_set_oneshot_mode();
  rt_set_periodic_mode();
  start_rt_timer(0);

  now = rt_get_time() + 10*PERIOD;
  rt_task_make_periodic(task, now, PERIOD);

  printf("Init mutex and cond.\n");
  mutex = rt_sem_init(nam2num("MUTEX"), 1);

  if (mutex==0)
    printf("Error init mutex\n");

  cond = rt_cond_init(nam2num("CONDITION"));

  if (cond==0)
    printf("Error init cond\n");

  thread0 = rt_thread_create(fun0, NULL, 10000);
  //thread1 = rt_thread_create(fun1, NULL, 20000);

  //rt_sleep(PERIOD);

  while (cnt < THRESHOLD) {
    rt_task_wait_period();
    rt_printk("main: Hello World %d!\n",cnt);
    rt_sem_wait(mutex); //now the mutex should have value 0

    if (instance_cnt==0) {
      rt_sem_signal(mutex); //now the mutex should have vaule 1
      rt_printk("worker thread busy!\n");
    } else {
      instance_cnt++;
      rt_cond_signal(cond);
      rt_sem_signal(mutex); //now the mutex should have vaule 1
      rt_printk("signaling worker thread to start!\n");
    }

    cnt++;
  }

  // wait for end of program
  printf("TYPE <ENTER> TO TERMINATE\n");
  getchar();

  // cleanup
  stop_rt_timer();
  return 0;
}
Esempio n. 2
0
void _rtapi_clock_set_period_hook(long int nsecs, RTIME *counts, 
				 RTIME *got_counts) {
    rt_set_periodic_mode();
    *counts = nano2count((RTIME) nsecs);
    if(count2nano(*counts) > nsecs) (*counts)--;
    *got_counts = start_rt_timer(*counts);
    rtapi_data->timer_period = count2nano(*got_counts);
}
Esempio n. 3
0
static int
__latency_init(void)
{

	/* XXX check option ranges here */

	/* register a proc entry */
#ifdef CONFIG_PROC_FS
	create_proc_read_entry("rtai/latency_calibrate", /* name             */
	                       0,			 /* default mode     */
	                       NULL, 			 /* parent dir       */
			       proc_read, 		 /* function         */
			       NULL			 /* client data      */
	);
#endif

	rtf_create(DEBUG_FIFO, 16000);	/* create a fifo length: 16000 bytes */
	rt_linux_use_fpu(use_fpu);	/* declare if we use the FPU         */

	rt_task_init(			/* create our measuring task         */
			    &thread,	/* poiter to our RT_TASK             */
			    fun,	/* implementation of the task        */
			    0,		/* we could transfer data -> task    */
			    3000,	/* stack size                        */
			    0,		/* priority                          */
			    use_fpu,	/* do we use the FPU?                */
			    0		/* signal? XXX                       */
	);

	rt_set_runnable_on_cpus(	/* select on which CPUs the task is  */
		&thread,		/* allowed to run                    */
		RUN_ON_CPUS
	);

	/* Test if we have to start the timer                                */
	if (start_timer || (start_timer = !rt_is_hard_timer_running())) {
		if (timer_mode) {
			rt_set_periodic_mode();
		} else {
			rt_set_oneshot_mode();
		}
		rt_assign_irq_to_cpu(TIMER_8254_IRQ, TIMER_TO_CPU);
		period_counts = start_rt_timer(nano2count(period));
	} else {
		period_counts = nano2count(period);
	}

	loops = (1000000000*avrgtime)/period;

	/* Calculate the start time for the task. */
	/* We set this to "now plus 10 periods"   */
	expected = rt_get_time() + 10 * period_counts;
	rt_task_make_periodic(&thread, expected, period_counts);
	return 0;
}
int create_tasks(void)
{
	int i;
	struct thread_param *arrayThreadParams[NTASKS];

	rt_set_periodic_mode();

	rt_hard_timer_tick_cpuid(CPU_ALLOWED);

	printf("************** Iniciando escalonamento **************\n");

	for (i = 0; i < NTASKS; i++)
	{
		arrayThreads[i] = (pthread_t *) malloc(sizeof(pthread_t));
		if (!arrayThreads[i])
		{
			printf("[ERRO] Não foi possivel criar a Thread da tarefa %d.\n\n", i);
			return(0);
		}
	}

	tick_period = start_rt_timer(nano2count(TICK_PERIOD));
	printf("TICK_PERIOD =======> %llu\n", tick_period);

	delay_timeline_sched = tick_period * 10;
	timeline_sched = rt_get_time() + delay_timeline_sched;

	for (i = 0; i < NTASKS; i++) {
		if((arrayThreadParams[i] = malloc(sizeof(*arrayThreadParams[i]))) == NULL)
		{
			printf("[ERRO] Não foi possivel criar os parametros da tarefa %d.\n\n", i);
			return (-1);
		}
		arrayThreadParams[i]->idTask = i;

		// Inicializando as tarefas...
		if(pthread_create(arrayThreads[i], 0, init_task, (void *)arrayThreadParams[i]))
		{
			printf("[ERRO] Não foi possível inicializar a Thread da tarefa %d.\n", i);
			return(0);
		}
	}

	while(!getchar()); // Aguardo o usuario apertar alguma tecla para finalizar o escalonamento...

	for (i = 0; i < NTASKS; i++) {
		pthread_cancel((pthread_t) *arrayThreads[i]);
		free(arrayThreadParams[i]);
	}

	return 0;
}
int main(void)
{
    long signal_a;
    long signal_b;
    t_info a = {
        .id = 'A',
    };
    t_info b = {
        .id = 'B',
    };

    finish = 0;

    rt_set_periodic_mode();
    start_rt_timer(nano2count(TICK_TIME));
    rt_make_hard_real_time();

    a.delay = 0;
    a.period = nano2count(TICK_TIME);
    signal_a = rt_thread_create(&signal_func, &a, 500);
    if (!signal_a) {
        printf("Can not initialize signal A\n");
        return -ENODEV;
    }

    b.delay = nano2count(DELAY_TIME);
    b.period = nano2count(TICK_TIME);
    signal_b = rt_thread_create(&signal_func, &b, 500);
    if (!signal_b) {
        printf("Can not initialize signal B\n");
        return -ENODEV;
    }
    scanf("%d", &finish);
    finish = 1;

    rt_thread_join(signal_a);
    rt_thread_join(signal_b);
    pthread_exit(NULL);
    return 0;
}
int manager_tasks(void)
{
	int contIdTask = 0;

	rt_set_periodic_mode();
	rt_make_hard_real_time();

	printf("************** Iniciando escalonamento **************\n");

	//rt_set_oneshot_mode();
	start_rt_timer(0);
	tick_period = nano2count(TICK_PERIOD); // 0.05 segundos...
	delay_start_timeline = tick_period * 20; // Delay: 2 segundo(s)
	start_timeline = rt_get_time() + delay_start_timeline;

	printf("TICK_PERIOD ================> %llu\n", tick_period);

	/**
	 * TASK(S)
	 */
	contIdTask = 0;//TASK:0
	arrayThreadParams[contIdTask].idTask = contIdTask;
	arrayThreadParams[contIdTask].periodo = tick_period * 320; // ~= 16 segundos
//	arrayThreadParams[contIdTask].deadline = 0.0013;
	arrayThreadParams[contIdTask].deadline = arrayThreadParams[contIdTask].periodo;
	arrayThreadParams[contIdTask].prioridade = 4;
//	arrayThreadParams[contIdTask].cpuFrequencyMin = VALOR_DEFAULT_FREQ_MIN_DESABILITADA; // KHz
	arrayThreadParams[contIdTask].cpuFrequencyMin = 3000000; // KHz
	arrayThreadParams[contIdTask].cpuFrequencyInicial = 3000000; // KHz
	arrayThreadParams[contIdTask].cpuVoltageInicial = AMD_ATHLON_II_X2_250_TENSAO_FREQ_1800000_KHZ; // Volts
	Thread_Task = rt_thread_create(init_task, &arrayThreadParams[contIdTask], 0);

	// Aguarda interrupcao do usuario... ou a conclusao dos periodos de todas as tarefas criadas...
	while(!getchar());

	stop_rt_timer();
	return 0;
}
Esempio n. 7
0
        INTERNAL_QUAL int rtos_task_create_main(RTOS_TASK* main_task)
        {
            if ( geteuid() != 0 ) {
                std::cerr << "You are not root. This program requires that you are root." << std::endl;
                exit(1);
            }

#ifdef OROSEM_OS_LOCK_MEMORY
            int locktype = MCL_CURRENT;
#ifdef OROSEM_OS_LOCK_MEMORY_FUTURE
            locktype |= MCL_FUTURE;
#endif
            // locking of all memory for this process
            int rv = mlockall(locktype);
            if ( rv != 0 ) {
                perror( "rtos_task_create_main: Could not lock memory using mlockall" ); // Logger unavailable.
            }
#endif

            /* check to see if rtai_lxrt module is loaded */
            //         struct module_info modInfo;
            //         size_t retSize;
            //         if ( query_module("rtai_lxrt", QM_INFO, &modInfo,
            //                           sizeof(modInfo), &retSize) != 0 ) {
            //             std::cerr <<"It appears the rtai_lxrt module is not loaded !"<<std::endl;
            //             exit();
            //         }
            unsigned long name = nam2num("main");
            while ( rt_get_adr( name ) != 0 ) // check for existing 'MAINTHREAD'
                ++name;


            const char* tname = "main";
            main_task->name = strcpy( (char*)malloc( (strlen(tname) + 1) * sizeof(char)), tname);

            if( !(main_task->rtaitask = rt_task_init(name, 10,0,0)) ) // priority, stack, msg_size
                {
                    std::cerr << "Cannot rt_task_init() MainThread." << std::endl;
                    exit(1);
                }

            struct sched_param param;

            param.sched_priority = sched_get_priority_max(SCHED_OTHER);
            if (param.sched_priority != -1 )
                sched_setscheduler( 0, SCHED_OTHER, &param);

            // Avoid the LXRT CHANGED MODE (TRAP), PID = 4088, VEC = 14, SIGNO = 11. warning
            rt_task_use_fpu(main_task->rtaitask, 1);

#ifdef OROSEM_OS_LXRT_PERIODIC
            rt_set_periodic_mode();
            start_rt_timer( nano2count( NANO_TIME(ORODAT_OS_LXRT_PERIODIC_TICK*1000*1000*1000) ) );
            Logger::log() << Logger::Info << "RTAI Periodic Timer ticks at "<<ORODAT_OS_LXRT_PERIODIC_TICK<<" seconds." << Logger::endl;
#else
            // BE SURE TO SET rt_preempt_always(1) when using one shot mode
            rt_set_oneshot_mode();
            // only call this function for RTAI 3.0 or older
#if defined(CONFIG_RTAI_VERSION_MINOR) && defined(CONFIG_RTAI_VERSION_MAJOR)
#  if CONFIG_RTAI_VERSION_MAJOR == 3 && CONFIG_RTAI_VERSION_MINOR == 0
            rt_preempt_always(1);
#  endif
#else
            rt_preempt_always(1);
#endif
            start_rt_timer(0);
            Logger::log() << Logger::Info << "RTAI Periodic Timer runs in preemptive 'one-shot' mode." << Logger::endl;
#endif
            Logger::log() << Logger::Debug << "RTAI Task Created" << Logger::endl;
            return 0;
        }
Esempio n. 8
0
int main(void)
{
	time_t aclock;
	struct tm *newtime;

	i = 0;

	printf("\n\nBeginning the Deadline Monotonic Scheduler\n\n");

	/* Dados de controle da Thread */
	pthread_t *threadControle_11;
	pthread_t *threadControle_12;
	pthread_t *threadControle_13;
	pthread_t *threadControle_21;
	pthread_t *threadControle_22;
	pthread_t *threadControle_31;
	pthread_t *threadControle_32;
	pthread_t *threadControle_33;

	rMutex = rt_sem_init(nam2num("MySEM"), 1);

	rt_set_periodic_mode();

	sampling = start_rt_timer(nano2count(TICK));

	printf("\nInit module function\n");

	threadControle_11 = (pthread_t *) malloc(sizeof(pthread_t));
	if (threadControle_11 == NULL)
	{
		printf("Não foi possivel criar a Thread deste PWM.\n\n");
		return(NULL);
	}

	if(pthread_create(threadControle_11, NULL, signalIchi, NULL))
	{
		printf("Não escalonar a Thread deste PWM.\n");
		return(NULL);
	}
	threadControle_12 = (pthread_t *) malloc(sizeof(pthread_t));
	if (threadControle_12 == NULL)
	{
		printf("Não foi possivel criar a Thread deste PWM.\n\n");
		return(NULL);
	}

	if(pthread_create(threadControle_12, NULL, signalIchi, NULL))
	{
		printf("Não escalonar a Thread deste PWM.\n");
		return(NULL);
	}
	threadControle_13 = (pthread_t *) malloc(sizeof(pthread_t));
	if (threadControle_13 == NULL)
	{
		printf("Não foi possivel criar a Thread deste PWM.\n\n");
		return(NULL);
	}

	if(pthread_create(threadControle_13, NULL, signalIchi, NULL))
	{
		printf("Não escalonar a Thread deste PWM.\n");
		return(NULL);
	}

	threadControle_21 = (pthread_t *) malloc(sizeof(pthread_t));
	if (threadControle_21 == NULL)
	{
		printf("Não foi possivel criar a Thread deste PWM.\n");
		return(NULL);
	}

	if(pthread_create(threadControle_21, NULL, signalNi, NULL))
	{
		printf("Não escalonar a Thread deste PWM.\n\n");
		return(NULL);
	}
	threadControle_22 = (pthread_t *) malloc(sizeof(pthread_t));
	if (threadControle_22 == NULL)
	{
		printf("Não foi possivel criar a Thread deste PWM.\n");
		return(NULL);
	}

	if(pthread_create(threadControle_22, NULL, signalNi, NULL))
	{
		printf("Não escalonar a Thread deste PWM.\n\n");
		return(NULL);
	}


	threadControle_31 = (pthread_t *) malloc(sizeof(pthread_t));
	if (threadControle_31 == NULL)
	{
		printf("Não foi possivel criar a Thread deste PWM.\n");
		return(NULL);
	}

	if(pthread_create(threadControle_31, NULL, signalSan, NULL))
	{
		printf("Não escalonar a Thread deste PWM.\n\n");
		return(NULL);
	}
	threadControle_32 = (pthread_t *) malloc(sizeof(pthread_t));
	if (threadControle_32 == NULL)
	{
		printf("Não foi possivel criar a Thread deste PWM.\n");
		return(NULL);
	}

	if(pthread_create(threadControle_32, NULL, signalSan, NULL))
	{
		printf("Não escalonar a Thread deste PWM.\n\n");
		return(NULL);
	}
	threadControle_33 = (pthread_t *) malloc(sizeof(pthread_t));
	if (threadControle_33 == NULL)
	{
		printf("Não foi possivel criar a Thread deste PWM.\n");
		return(NULL);
	}

	if(pthread_create(threadControle_33, NULL, signalSan, NULL))
	{
		printf("Não escalonar a Thread deste PWM.\n\n");
		return(NULL);
	}

	time(&aclock); // Pega tempo em segundos.
	newtime = localtime(&aclock);
	printf(" Inicio  =======> %s", asctime(newtime));

	begin = 3600 * newtime->tm_hour + 60 * newtime->tm_min + newtime->tm_sec;

	while(!getchar());


	rt_sem_wait(rMutex);
	rt_sem_delete(rMutex);

	pthread_cancel((pthread_t) *threadControle_11);
	pthread_cancel((pthread_t) *threadControle_12);
	pthread_cancel((pthread_t) *threadControle_13);
	pthread_cancel((pthread_t) *threadControle_21);
	pthread_cancel((pthread_t) *threadControle_22);
	pthread_cancel((pthread_t) *threadControle_31);
	pthread_cancel((pthread_t) *threadControle_32);
	pthread_cancel((pthread_t) *threadControle_33);

	printf("\nFim do Escalonamento\n");


	return 0;
}
Esempio n. 9
0
int main(int argc, char *argv[])
{
	int diff;
	int sample;
	long average;
	int min_diff;
	int max_diff;
	int period;
	int i;
	RTIME t, svt;
	RTIME expected, exectime[3];
	MBX *mbx;
	RT_TASK *task, *latchk;
	struct sample { long long min; long long max; int index, ovrn; } samp;
	double s = 0.0, sref;
	long long max = -1000000000, min = 1000000000;

	signal(SIGINT, endme);
	signal(SIGKILL, endme);
	signal(SIGTERM, endme);

 	if (!(mbx = rt_mbx_init(nam2num("LATMBX"), 20*sizeof(samp)))) {
		printf("CANNOT CREATE MAILBOX\n");
		exit(1);
	}

 	if (!(task = rt_task_init_schmod(nam2num("LATCAL"), 0, 0, 0, SCHED_FIFO, 0xF))) {
		printf("CANNOT INIT MASTER LATENCY TASK\n");
		exit(1);
	}

	printf("\n## RTAI latency calibration tool ##\n");
	printf("# period = %i (ns) \n", PERIOD);
	printf("# average time = %i (s)\n", (int)AVRGTIME);
	printf("# use the FPU\n");
	printf("#%sstart the timer\n", argc == 1 ? " " : " do not ");
	printf("# timer_mode is %s\n", TIMER_MODE ? "periodic" : "oneshot");
	printf("\n");

	if (!(hard_timer_running = rt_is_hard_timer_running())) {
		if (TIMER_MODE) {
			rt_set_periodic_mode();
		} else {
			rt_set_oneshot_mode();
		}
		period = start_rt_timer(nano2count(PERIOD));
	} else {
		period = nano2count(PERIOD);
	}

	for(i = 0; i < MAXDIM; i++) {
		a[i] = b[i] = 3.141592;
	}
	sref = dot(a, b, MAXDIM);

	mlockall(MCL_CURRENT | MCL_FUTURE);

	rt_make_hard_real_time();
	expected = rt_get_time() + 200*period;
	rt_task_make_periodic(task, expected, period);
	svt = rt_get_cpu_time_ns();
	i = 0;
	samp.ovrn = 0;
	while (!end) {
		min_diff = 1000000000;
		max_diff = -1000000000;
		average = 0;

		for (sample = 0; sample < SMPLSXAVRG && !end; sample++) {
			expected += period;
			if (!rt_task_wait_period()) {
				if (TIMER_MODE) {
					diff = (int) ((t = rt_get_cpu_time_ns()) - svt - PERIOD);
					svt = t;
				} else {
					diff = (int) count2nano(rt_get_time() - expected);
				}
			} else {
				samp.ovrn++;
				diff = 0;
				if (TIMER_MODE) {
					svt = rt_get_cpu_time_ns();
				}
			}
			outb(i = 1 - i, 0x378);

			if (diff < min_diff) {
				min_diff = diff;
			}
			if (diff > max_diff) {
				max_diff = diff;
			}
			average += diff;
			s = dot(a, b, MAXDIM);
			if (fabs((s - sref)/sref) > 1.0e-15) {
				printf("\nDOT PRODUCT RESULT = %20.16e %20.16e %20.16e\n", s, sref, fabs((s - sref)/sref));
				return 0;
			}
		}
		samp.min = min_diff;
		samp.max = max_diff;
		samp.index = average/SMPLSXAVRG;
#if SOLO
		if (max < samp.max) max = samp.max;
		if (min > samp.min) min = samp.min;
		rt_printk("SOLO * min: %lld/%lld, max: %lld/%lld average: %d (%d) <Hit [RETURN] to stop> *\n", samp.min, min, samp.max, max, samp.index, samp.ovrn);
#else
		rt_mbx_send_if(mbx, &samp, sizeof(samp));
		if ((latchk = rt_get_adr(nam2num("LATCHK"))) && (rt_receive_if(latchk, &average) || end)) {
			rt_return(latchk, average);
			break;
		}
#endif
	}

	while (rt_get_adr(nam2num("LATCHK"))) {
		rt_sleep(nano2count(1000000));
	}
	rt_make_soft_real_time();
	if (!hard_timer_running) {
		stop_rt_timer();
	}
	rt_get_exectime(task, exectime);
	if (exectime[1] && exectime[2]) {
		printf("\n>>> S = %g, EXECTIME = %G\n", s, (double)exectime[0]/(double)(exectime[2] - exectime[1]));
	}
	rt_task_delete(task);
	rt_mbx_delete(mbx);

	return 0;
}
Esempio n. 10
0
int main(int argc, char *argv[])
{
	int sock;
	struct sockaddr_in SPRT_ADDR;
	char buf[200];
	int fd;

	int diff;
	int sample;
	int average;
	int min_diff;
	int max_diff;
	int period;
	int i;
	int cnt;
	RTIME t, svt;
	RTIME expected, exectime[3];
	RT_TASK *task;
	long long max = -1000000000, min = 1000000000;
	struct sample { long long min; long long max; int index, ovrn; } samp;
	double s, sref;

 	if (!(task = rt_task_init_schmod(nam2num("LATCAL"), 0, 0, 0, SCHED_FIFO, 0xF))) {
		printf("CANNOT INIT MASTER LATENCY TASK\n");
		exit(1);
	}

	sock = socket(AF_INET, SOCK_DGRAM, 0);
	bzero(&SPRT_ADDR, sizeof(struct sockaddr_in));
	SPRT_ADDR.sin_family = AF_INET;
	SPRT_ADDR.sin_port = htons(5000);
	SPRT_ADDR.sin_addr.s_addr = inet_addr("127.0.0.1");

	fd = open("echo", O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);

	printf("\n## RTAI latency calibration tool ##\n");
	printf("# period = %i (ns) \n", PERIOD);
	printf("# average time = %i (s)\n", (int)AVRGTIME);
	printf("# use the FPU\n");
	printf("#%sstart the timer\n", argc == 1 ? " " : " do not ");
	printf("# timer_mode is %s\n", TIMER_MODE ? "periodic" : "oneshot");
	printf("\n");

	rt_sync_async_linux_syscall_server_create(NULL, ASYNC_LINUX_SYSCALL, async_callback, 120);

	if (!(hard_timer_running = rt_is_hard_timer_running())) {
		if (TIMER_MODE) {
			rt_set_periodic_mode();
		} else {
			rt_set_oneshot_mode();
		}
		period = start_rt_timer(nano2count(PERIOD));
	} else {
		period = nano2count(PERIOD);
	}

        for(i = 0; i < MAXDIM; i++) {
                a[i] = b[i] = 3.141592;
        }
	sref = dot(a, b, MAXDIM);
	s = 0.0;

	mlockall(MCL_CURRENT | MCL_FUTURE);

	rt_make_hard_real_time();
	expected = rt_get_time() + 200*period;
	rt_task_make_periodic(task, expected, period);
	svt = rt_get_cpu_time_ns();
	cnt = 0;
	i = 0;
	samp.ovrn = 0;
	while (!end) {
		min_diff = 1000000000;
		max_diff = -1000000000;
		average = 0;

		for (sample = 0; sample < SMPLSXAVRG && !end; sample++) {
			expected += period;
			if (!rt_task_wait_period()) {
				if (TIMER_MODE) {
					diff = (int) ((t = rt_get_cpu_time_ns()) - svt - PERIOD);
					svt = t;
				} else {
					diff = (int) count2nano(rt_get_time() - expected);
				}
			} else {
				samp.ovrn++;
				diff = 0;
				if (TIMER_MODE) {
					svt = rt_get_cpu_time_ns();
				}
			}

			if (diff < min_diff) {
				min_diff = diff;
			}
			if (diff > max_diff) {
				max_diff = diff;
			}
			average += diff;
			s = dot(a, b, MAXDIM);
			if (fabs(s/sref - 1.0) > 1.0e-16) {
				printf("\nDOT PRODUCT RESULT = %lf %lf %lf\n", s, sref, sref - s);
				return 0;
			}
		}
		samp.min = min_diff;
		samp.max = max_diff;
		samp.index = average/SMPLSXAVRG;
		if (max < samp.max) max = samp.max;
		if (min > samp.min) min = samp.min;
		++cnt;
//		printf("* %d - min: %lld/%lld, max: %lld/%lld average: %d <RET to stop> %d *\n", cnt, samp.min, min, samp.max, max, samp.index, samp.ovrn);
		sprintf(buf, "* %d - min: %lld/%lld, max: %lld/%lld average: %d <RET to stop> %d *\n", cnt, samp.min, min, samp.max, max, samp.index, samp.ovrn);
		i = write(STDOUT_FILENO, buf, strlen(buf));
		fdatasync(STDOUT_FILENO);
		i = write(fd, buf, strlen(buf));
		fsync(fd);
		sendto(sock, buf, strlen(buf), 0, (struct sockaddr *)&SPRT_ADDR, sizeof(struct sockaddr_in));
	}

	close(sock);
	close(fd);
	rt_make_soft_real_time();
	if (!hard_timer_running) {
		stop_rt_timer();
	}
	rt_get_exectime(task, exectime);
	if (exectime[1] && exectime[2]) {
		printf("\n>>> S = %g, EXECTIME = %G\n", s, (double)exectime[0]/(double)(exectime[2] - exectime[1]));
	}
	rt_task_delete(task);

	return 0;
}
Esempio n. 11
0
int main(int argc, char *argv[])
{
	int diff;
	int skip;
	long average;
	int min_diff;
	int max_diff;
	int period;
	int i;
	RTIME t, svt;
	RTIME expected, exectime[3];
	MBX *mbx;
	RT_TASK *task, *latchk;
	struct sample { long long min; long long max; int index, ovrn; } samp;
	double s;

	signal(SIGHUP,  endme);
	signal(SIGKILL, endme);
	signal(SIGTERM, endme);
	signal(SIGALRM, endme);

 	if (!(mbx = rt_mbx_init(nam2num("LATMBX"), 20*sizeof(samp)))) {
		printf("CANNOT CREATE MAILBOX\n");
		exit(1);
	}

 	if (!(task = rt_task_init_schmod(nam2num("LATCAL"), 0, 0, 0, SCHED_FIFO, 0xF))) {
		printf("CANNOT INIT MASTER TASK\n");
		exit(1);
	}

	printf("\n## RTAI latency calibration tool ##\n");
	printf("# period = %i (ns) \n", PERIOD);
	printf("# average time = %i (s)\n", (int)AVRGTIME);
	printf("# use the FPU\n");
	printf("#%sstart the timer\n", argc == 1 ? " " : " do not ");
	printf("# timer_mode is %s\n", TIMER_MODE ? "periodic" : "oneshot");
	printf("\n");

	if (argc == 1) {
		if (TIMER_MODE) {
			rt_set_periodic_mode();
		} else {
			rt_set_oneshot_mode();
		}
		period = start_rt_timer(nano2count(PERIOD));
	} else {
		period = nano2count(PERIOD);
	}

        for(i = 0; i < MAXDIM; i++) {
                a[i] = b[i] = 3.141592;
        }
	s = dot(a, b, MAXDIM);

	mlockall(MCL_CURRENT | MCL_FUTURE);

	rt_make_hard_real_time();
	rt_task_make_periodic(task, expected = rt_get_tscnt() + 10*period, period);

	svt = rt_get_cpu_time_ns();
	samp.ovrn = i = 0;
	while (!end) {
		min_diff = 1000000000;
		max_diff = -1000000000;
		average = 0;

		for (skip = 0; skip < SKIP && !end; skip++) {
			expected += period;

			if (!rt_task_wait_period()) {
				if (TIMER_MODE) {
					diff = (int) ((t = rt_get_cpu_time_ns()) - svt - PERIOD);
					svt = t;
				} else {
					diff = (int) count2nano(rt_get_tscnt() - expected);
				}
			} else {
				samp.ovrn++;
				diff = 0;
				if (TIMER_MODE) {
					svt = rt_get_cpu_time_ns();
				}
			}
			if (diff < min_diff) {
				min_diff = diff;
			}
			if (diff > max_diff) {
				max_diff = diff;
			}
			average += diff;
			s = dot(a, b, MAXDIM);
		}
		samp.min = min_diff;
		samp.max = max_diff;
		samp.index = average/SKIP;
		rt_mbx_send_if(mbx, &samp, sizeof(samp));
		if ((latchk = rt_get_adr(nam2num("LATCHK"))) && (rt_receive_if(latchk, (unsigned long *)&average) || end)) {
			rt_return(latchk, (unsigned long)average);
			break;
		}
	}

	while (rt_get_adr(nam2num("LATCHK"))) {
		rt_sleep(nano2count(1000000));
	}
	rt_make_soft_real_time();
	if (argc == 1) {
		stop_rt_timer();	
	}
	rt_get_exectime(task, exectime);
	if (exectime[1] && exectime[2]) {
		printf("\n>>> S = %g, EXECTIME = %G\n", s, (double)exectime[0]/(double)(exectime[2] - exectime[1]));
	}
	rt_task_delete(task);
	rt_mbx_delete(mbx);

	return 0;
}
int create_tasks(void)
{
	/* Dados de controle da Thread */
	pthread_t *threadControle_Task_1;
	pthread_t *threadControle_Task_3;
	pthread_t *threadControle_Task_2;
	pthread_t *threadControle_Task_4;

	rt_set_periodic_mode();

	rt_hard_timer_tick_cpuid(CPU_ALLOWED);

	sampling = start_rt_timer(nano2count(TICK));

	printf("\nInit module function\n");

	threadControle_Task_1 = (pthread_t *) malloc(sizeof(pthread_t));
	threadControle_Task_3 = (pthread_t *) malloc(sizeof(pthread_t));
	threadControle_Task_2 = (pthread_t *) malloc(sizeof(pthread_t));
	threadControle_Task_4 = (pthread_t *) malloc(sizeof(pthread_t));

	if (threadControle_Task_1 == 0)
	{
		printf("[ERRO] Não foi possivel criar a Thread da tarefa 1.\n\n");
		return(0);
	}
	if (threadControle_Task_2 == 0)
	{
		printf("[ERRO] Não foi possivel criar a Thread da tarefa 2.\n");
		return(0);
	}
	if (threadControle_Task_3 == 0)
	{
		printf("[ERRO] Não foi possivel criar a Thread da tarefa 3.\n");
		return(0);
	}
	if (threadControle_Task_4 == 0)
	{
		printf("[ERRO] Não foi possivel criar a Thread da tarefa 4.\n");
		return(0);
	}

	// Inicializando as tarefas...
	if(pthread_create(threadControle_Task_1, 0, init_task_1, 0))
	{
		printf("[ERRO] Não foi possível inicializar a Thread da tarefa 1.\n");
		return(0);
	}
	if(pthread_create(threadControle_Task_3, 0, init_task_2, 0))
	{
		printf("[ERRO] Não foi possível inicializar a Thread da tarefa 2.\n\n");
		return(0);
	}
	if(pthread_create(threadControle_Task_2, 0, init_task_3, 0))
	{
		printf("[ERRO] Não foi possível inicializar a Thread da tarefa 3.\n\n");
		return(0);
	}
	if(pthread_create(threadControle_Task_4, 0, init_task_4, 0))
	{
		printf("[ERRO] Não foi possível inicializar a Thread da tarefa 4.\n\n");
		return(0);
	}

	while(!getchar()); // Aguardo o usuario apertar alguma tecla para finalizar o escalonamento...

	pthread_cancel((pthread_t) *threadControle_Task_1);
	pthread_cancel((pthread_t) *threadControle_Task_3);
	pthread_cancel((pthread_t) *threadControle_Task_2);
	pthread_cancel((pthread_t) *threadControle_Task_4);

	return 0;
}
Esempio n. 13
0
File: rtmain.c Progetto: ArcEye/RTAI
static int rt_Main(int priority)
{
	SEM *hard_timers_cnt;
	char name[7];
	RTIME rt_BaseTaskPeriod;
	struct timespec err_timeout;
	int i;


	rt_allow_nonroot_hrt();

	for (i = 0; i < MAX_NTARGETS; i++) {
		sprintf(name,"MNT%d",i);
		if (!rt_get_adr(nam2num(name))) break;
	}

	if (!(rt_MainTask = rt_task_init_schmod(nam2num(name), rt_MainTaskPriority, 0, 0, SCHED_RR, 0xFF))) {
		fprintf(stderr,"Cannot init rt_MainTask.\n");
		return 1;
	}
	sem_init(&err_sem, 0, 0);

	printf("TARGET STARTS.\n");
	pthread_create(&rt_HostInterfaceThread, NULL, rt_HostInterface, NULL);
	err_timeout.tv_sec = (long int)(time(NULL)) + 1;
	err_timeout.tv_nsec = 0;
	if ((sem_timedwait(&err_sem, &err_timeout)) != 0) {
		fprintf(stderr, "Target is terminated.\n");
		goto finish;
	}

	pthread_create(&rt_BaseRateThread, NULL, rt_BaseRate, &priority);
	err_timeout.tv_sec = (long int)(time(NULL)) + 1;
	err_timeout.tv_nsec = 0;
	if ((sem_timedwait(&err_sem, &err_timeout)) != 0) {
		endInterface = 1;
		rt_send(rt_HostInterfaceTask, 0);
		pthread_join(rt_HostInterfaceThread, NULL);
		fprintf(stderr, "Target is terminated.\n");
		goto finish;
	}

	rt_BaseTaskPeriod = (RTIME) (1e9*get_tsamp());
	if (InternTimer) {
		WaitTimingEvent = (void *)rt_task_wait_period;
		if (!(hard_timers_cnt = rt_get_adr(nam2num("HTMRCN")))) {
			if (!ClockTick) {
				rt_set_oneshot_mode();
				start_rt_timer(0);
				rt_BaseRateTick = nano2count(rt_BaseTaskPeriod);
			}
			else {
				rt_set_periodic_mode();
				rt_BaseRateTick = start_rt_timer(nano2count(rt_BaseTaskPeriod));
			}
			hard_timers_cnt = rt_sem_init(nam2num("HTMRCN"), 0);
		}
		else {
			rt_BaseRateTick = nano2count(rt_BaseTaskPeriod);
			rt_sem_signal(hard_timers_cnt);
		}
	}
	else {
		WaitTimingEvent = (void *)DummyWait;
		SendTimingEvent = (void *)DummySend;
	}

	if (verbose) {
		printf("Model : %s .\n", modelname);
		printf("Executes on CPU map : %x.\n", CpuMap);
		printf("Sampling time : %e (s).\n", get_tsamp());
	}
	{
	int msg;

	rt_receive(0, &msg);
	}

	if (WaitToStart) {
		if (verbose) {
			printf("Target is waiting to start ... ");
			fflush(stdout);
		}
		rt_task_suspend(rt_MainTask);
	}


	if (verbose) {
		printf("Target is running.\n");
	}
	rt_return(rt_BaseRateTask, 0);
	isRunning = 1;

	while (!endex && (!FinalTime || SIM_TIME < FinalTime)) {
		msleep(POLL_PERIOD);
	}
	endBaseRate = 1;
	if (!InternTimer) {
		SendTimingEvent(TimingEventArg);
	}
	pthread_join(rt_BaseRateThread, NULL);
	isRunning = 0;
	endInterface = 1;
	rt_send(rt_HostInterfaceTask, 0);
	if (verbose) {
		printf("Target has been stopped.\n");
	}
	pthread_join(rt_HostInterfaceThread, NULL);
	if (InternTimer) {
		if (!rt_sem_wait_if(hard_timers_cnt)) {
			rt_sem_delete(hard_timers_cnt);
		}
	}

	finish:
    		for (i=0 ; i<NSCOPE ; i++)
				RT_named_mbx_delete(0, 0, rtaiScope[i].mbx);
    		for (i=0 ; i<NLOGS ; i++)
				RT_named_mbx_delete(0, 0, rtaiLogData[i].mbx);
    		for (i=0 ; i<NLEDS ; i++)
				RT_named_mbx_delete(0, 0, rtaiLed[i].mbx);
    		for (i=0 ; i<NMETERS ; i++)
				RT_named_mbx_delete(0, 0, rtaiMeter[i].mbx);

			for ( i=0 ; i<MAX_COMEDI_DEVICES ; i++ ){
				if ( ComediDev[i] != NULL ){
					comedi_close(ComediDev[i]);
				}
			}

			for ( i=0 ; i<N_DATAIN ; i++){
				free( ComediDataIn[i].comdev );
			}
			for ( i=0 ; i<N_DATAOUT ; i++){
				free( ComediDataOut[i].comdev );
			}
			for ( i=0 ; i<N_DIOIN ; i++){
				free( ComediDioIn[i].comdev );
			}
			for ( i=0 ; i<N_DIOOUT ; i++){
				free( ComediDioOut[i].comdev );
			}

			SA_Output_To_File();
			rt_task_delete(rt_MainTask);
			printf("TARGET ENDS.\n");

	return 0;

}
Esempio n. 14
0
int main(int argc, char **argv) {

#ifdef RTAI
  RT_TASK *task;
  RTIME period;
#endif
  int i,j,aa;
  void *status;

  /*
  uint32_t rf_mode_max[4]     = {55759,55759,55759,55759};
  uint32_t rf_mode_med[4]     = {39375,39375,39375,39375};
  uint32_t rf_mode_byp[4]     = {22991,22991,22991,22991};
  */
  uint32_t my_rf_mode = RXEN + TXEN + TXLPFNORM + TXLPFEN + TXLPF25 + RXLPFNORM + RXLPFEN + RXLPF25 + LNA1ON +LNAMax + RFBBNORM + DMAMODE_RX + DMAMODE_TX;
  uint32_t rf_mode_base = TXLPFNORM + TXLPFEN + TXLPF25 + RXLPFNORM + RXLPFEN + RXLPF25 + LNA1ON +LNAMax + RFBBNORM;
  uint32_t rf_mode[4]     = {my_rf_mode,0,0,0};
  uint32_t rf_local[4]    = {8255000,8255000,8255000,8255000}; // UE zepto
    //{8254617, 8254617, 8254617, 8254617}; //eNB khalifa
    //{8255067,8254810,8257340,8257340}; // eNB PETRONAS

  uint32_t rf_vcocal[4]   = {910,910,910,910};
  uint32_t rf_vcocal_850[4] = {2015, 2015, 2015, 2015};
  uint32_t rf_rxdc[4]     = {32896,32896,32896,32896};
  uint32_t rxgain[4]      = {20,20,20,20};
  uint32_t txgain[4]      = {20,20,20,20};

  uint16_t Nid_cell = 0;
  uint8_t  cooperation_flag=0, transmission_mode=1, abstraction_flag=0;
  uint8_t beta_ACK=0,beta_RI=0,beta_CQI=2;

  int c;
  char do_forms=0;
  unsigned int fd;
  unsigned int tcxo = 114;

  int amp;
  uint8_t prach_fmt;
  int N_ZC;

  char rxg_fname[100];
  char txg_fname[100];
  char rflo_fname[100];
  char rfdc_fname[100];
  FILE *rxg_fd=NULL;
  FILE *txg_fd=NULL;
  FILE *rflo_fd=NULL;
  FILE *rfdc_fd=NULL;
  unsigned int rxg_max[4]={133,133,133,133}, rxg_med[4]={127,127,127,127}, rxg_byp[4]={120,120,120,120};
  int tx_max_power=0;

  char line[1000];
  int l;
  int ret, ant;
  int ant_offset=0;

  int error_code;
  char *itti_dump_file = NULL;

  const struct option long_options[] = {
    {"calib-ue-rx", required_argument, NULL, 256},
    {"calib-ue-rx-med", required_argument, NULL, 257},
    {"calib-ue-rx-byp", required_argument, NULL, 258},
    {"debug-ue-prach", no_argument, NULL, 259},
    {"no-L2-connect", no_argument, NULL, 260},
    {NULL, 0, NULL, 0}};

  //mode = normal_txrx;


  while ((c = getopt_long (argc, argv, "C:K:O:ST:UdF:V",long_options,NULL)) != -1)
    {
      switch (c)
        {
	case 'V':
          ouput_vcd = 1;
	  break;
        case 'd':
          do_forms=1;
          break;
        case 'U':
          UE_flag = 1;
          break;
        case 'C':
          carrier_freq[0] = atoi(optarg);
          carrier_freq[1] = atoi(optarg);
          carrier_freq[2] = atoi(optarg);
          carrier_freq[3] = atoi(optarg);
          break;
        case 'S':
          fs4_test=1;
          break;
        case 'T':
          tcxo=atoi(optarg);
          break;
        case 'K':
#if defined(ENABLE_ITTI)
          itti_dump_file = strdup(optarg);
#else
          printf("-K option is disabled when ENABLE_ITTI is not defined\n");
#endif
          break;
        case 'O':
#if defined(ENABLE_USE_MME)
          EPC_MODE_ENABLED = 1;
          if (optarg == NULL) /* No IP address provided: use localhost */
          {
            memcpy(&EPC_MODE_MME_ADDRESS[0], "127.0.0.1", 10);
          } else {
            uint8_t ip_length = strlen(optarg) + 1;
            memcpy(&EPC_MODE_MME_ADDRESS[0], optarg,
            ip_length > 16 ? 16 : ip_length);
          }
#else
          printf("You enabled mme mode without s1ap compiled...\n");
#endif
          break;
	case 'F':
	  sprintf(rxg_fname,"%srxg.lime",optarg);
	  rxg_fd = fopen(rxg_fname,"r");
	  if (rxg_fd) {
	    printf("Loading RX Gain parameters from %s\n",rxg_fname);
	    l=0;
	    while (fgets(line, sizeof(line), rxg_fd)) {
	      if ((strlen(line)==0) || (*line == '#')) continue; //ignore empty or comment lines
	      else {
		if (l==0) sscanf(line,"%d %d %d %d",&rxg_max[0],&rxg_max[1],&rxg_max[2],&rxg_max[3]);
		if (l==1) sscanf(line,"%d %d %d %d",&rxg_med[0],&rxg_med[1],&rxg_med[2],&rxg_med[3]);
		if (l==2) sscanf(line,"%d %d %d %d",&rxg_byp[0],&rxg_byp[1],&rxg_byp[2],&rxg_byp[3]);
		l++;
	      }
	    }
	  }
	  else 
	    printf("%s not found, running with defaults\n",rxg_fname);

	  sprintf(txg_fname,"%stxg.lime",optarg);
	  txg_fd = fopen(txg_fname,"r");
	  if (txg_fd) {
	    printf("Loading TX Gain parameters from %s\n",txg_fname);
	    l=0;
	    while (fgets(line, sizeof(line), txg_fd)) {
	      if ((strlen(line)==0) || (*line == '#')) {
		continue; //ignore empty or comment lines
	      }
	      else {
		if (l==0) sscanf(line,"%d %d %d %d",&txgain[0],&txgain[1],&txgain[2],&txgain[3]);
		if (l==1) sscanf(line,"%d",&tx_max_power);
		l++;
	      }
	    }
	  }
	  else 
	    printf("%s not found, running with defaults\n",txg_fname);

	  sprintf(rflo_fname,"%srflo.lime",optarg);
	  rflo_fd = fopen(rflo_fname,"r");
	  if (rflo_fd) {
	    printf("Loading RF LO parameters from %s\n",rflo_fname);
	    fscanf(rflo_fd,"%d %d %d %d",&rf_local[0],&rf_local[1],&rf_local[2],&rf_local[3]);
	  }
	  else 
	    printf("%s not found, running with defaults\n",rflo_fname);

	  sprintf(rfdc_fname,"%srfdc.lime",optarg);
	  rfdc_fd = fopen(rfdc_fname,"r");
	  if (rfdc_fd) {
	    printf("Loading RF DC parameters from %s\n",rfdc_fname);
	    fscanf(rfdc_fd,"%d %d %d %d",&rf_rxdc[0],&rf_rxdc[1],&rf_rxdc[2],&rf_rxdc[3]);
	  }
	  else 
	    printf("%s not found, running with defaults\n",rfdc_fname);

	  break;
	  /*
	case 256:
	  mode = rx_calib_ue;
	  rx_input_level_dBm = atoi(optarg);
	  printf("Running with UE calibration on (LNA max), input level %d dBm\n",rx_input_level_dBm);
	  break;
	case 257:
	  mode = rx_calib_ue_med;
	  rx_input_level_dBm = atoi(optarg);
	  printf("Running with UE calibration on (LNA med), input level %d dBm\n",rx_input_level_dBm);
	  break;
	case 258:
	  mode = rx_calib_ue_byp;
	  rx_input_level_dBm = atoi(optarg);
	  printf("Running with UE calibration on (LNA byp), input level %d dBm\n",rx_input_level_dBm);
	  break;
	case 259:
	  mode = debug_prach;
	  break;
	case 260:
	  mode = no_L2_connect;
	  break;
	  */
        default:
          break;
        }
    }

  if (UE_flag==1)
    printf("configuring for UE\n");
  else
    printf("configuring for eNB\n");

  //randominit (0);
  //set_taus_seed (0);

  // initialize the log (see log.h for details)
  logInit();

#if defined(ENABLE_ITTI)
  itti_init(TASK_MAX, THREAD_MAX, MESSAGES_ID_MAX, tasks_info, messages_info, messages_definition_xml, itti_dump_file);

# if defined(ENABLE_USE_MME)
  if (itti_create_task(TASK_SCTP, sctp_eNB_task, NULL) < 0) {
    LOG_E(EMU, "Create task failed");
    LOG_D(EMU, "Initializing SCTP task interface: FAILED\n");
    return -1;
  }
  if (itti_create_task(TASK_S1AP, s1ap_eNB_task, NULL) < 0) {
    LOG_E(EMU, "Create task failed");
    LOG_D(EMU, "Initializing S1AP task interface: FAILED\n");
    return -1;
  }
# endif

  if (itti_create_task(TASK_L2L1, l2l1_task, NULL) < 0) {
      LOG_E(EMU, "Create task failed");
      LOG_D(EMU, "Initializing L2L1 task interface: FAILED\n");
      return -1;
  }

  // Handle signals until all tasks are terminated
//   itti_wait_tasks_end();
#endif

  if (ouput_vcd) {
    if (UE_flag==1)
      vcd_signal_dumper_init("/tmp/openair_dump_UE.vcd");
    else
      vcd_signal_dumper_init("/tmp/openair_dump_eNB.vcd");
  }

#ifdef NAS_NETLINK
  netlink_init();
#endif

  // to make a graceful exit when ctrl-c is pressed
  signal(SIGSEGV, signal_handler);
  signal(SIGINT, signal_handler);

#ifndef RTAI
  check_clock();
#endif

    g_log->log_component[HW].level = LOG_DEBUG;
    g_log->log_component[HW].flag  = LOG_HIGH;
#ifdef OPENAIR2
    g_log->log_component[PHY].level = LOG_INFO;
#else
    g_log->log_component[PHY].level = LOG_INFO;
#endif
    g_log->log_component[PHY].flag  = LOG_HIGH;
    g_log->log_component[MAC].level = LOG_INFO;
    g_log->log_component[MAC].flag  = LOG_HIGH;
    g_log->log_component[RLC].level = LOG_INFO;
    g_log->log_component[RLC].flag  = LOG_HIGH;
    g_log->log_component[PDCP].level = LOG_INFO;
    g_log->log_component[PDCP].flag  = LOG_HIGH;
    g_log->log_component[OTG].level = LOG_INFO;
    g_log->log_component[OTG].flag  = LOG_HIGH;
    g_log->log_component[RRC].level = LOG_INFO;
    g_log->log_component[RRC].flag  = LOG_HIGH;


  // Initialize card
  ret = openair0_open();
  if ( ret != 0 ) {
          if (ret == -1)
              printf("Error opening /dev/openair0");
          if (ret == -2)
              printf("Error mapping bigshm");
          if (ret == -3)
              printf("Error mapping RX or TX buffer");
          return(ret);
     }

  printf ("Detected %d number of cards, %d number of antennas.\n", openair0_num_detected_cards, openair0_num_antennas[card]);
  
  p_exmimo_config = openair0_exmimo_pci[card].exmimo_config_ptr;
  p_exmimo_id     = openair0_exmimo_pci[card].exmimo_id_ptr;
  
  printf("Card %d: ExpressMIMO %d, HW Rev %d, SW Rev 0x%d\n", card, p_exmimo_id->board_exmimoversion, p_exmimo_id->board_hwrev, p_exmimo_id->board_swrev);

  if (p_exmimo_id->board_swrev>=BOARD_SWREV_CNTL2)
    p_exmimo_config->framing.eNB_flag   = 0; 
  else 
    p_exmimo_config->framing.eNB_flag   = !UE_flag;

  p_exmimo_config->framing.tdd_config = DUPLEXMODE_FDD + TXRXSWITCH_LSB;
  for (ant=0; ant<4; ant++) 
    p_exmimo_config->framing.resampling_factor[ant] = RESAMPLING_FACTOR;
 
  /*
  for (ant=0;ant<max(frame_parms->nb_antennas_tx,frame_parms->nb_antennas_rx);ant++) 
    p_exmimo_config->rf.rf_mode[ant] = rf_mode_base;
  for (ant=0;ant<frame_parms->nb_antennas_tx;ant++)
    p_exmimo_config->rf.rf_mode[ant] += (TXEN + DMAMODE_TX);
  for (ant=0;ant<frame_parms->nb_antennas_rx;ant++)
    p_exmimo_config->rf.rf_mode[ant] += (RXEN + DMAMODE_RX);
  for (ant=max(frame_parms->nb_antennas_tx,frame_parms->nb_antennas_rx);ant<4;ant++) {
    p_exmimo_config->rf.rf_mode[ant] = 0;
    carrier_freq[ant] = 0; //this turns off all other LIMEs
  }
  */

  ant_offset = 0;
  for (ant=0; ant<4; ant++) {
    if (ant==ant_offset) {
      //if (1) {
      p_exmimo_config->rf.rf_mode[ant] = rf_mode_base;
      //p_exmimo_config->rf.rf_mode[ant] += (TXEN + DMAMODE_TX);
      p_exmimo_config->rf.rf_mode[ant] += (RXEN + DMAMODE_RX);
    }
    else {
      p_exmimo_config->rf.rf_mode[ant] = 0;
      carrier_freq[ant] = 0; //this turns off all other LIMEs
    }
  }

  for (ant = 0; ant<4; ant++) { 
    p_exmimo_config->rf.do_autocal[ant] = 1;
    p_exmimo_config->rf.rf_freq_rx[ant] = carrier_freq[ant];
    p_exmimo_config->rf.rf_freq_tx[ant] = carrier_freq[ant];
    p_exmimo_config->rf.rx_gain[ant][0] = rxgain[ant];
    p_exmimo_config->rf.tx_gain[ant][0] = txgain[ant];
    
    p_exmimo_config->rf.rf_local[ant]   = rf_local[ant];
    p_exmimo_config->rf.rf_rxdc[ant]    = rf_rxdc[ant];

    if ((carrier_freq[ant] >= 850000000) && (carrier_freq[ant] <= 865000000)) {
      p_exmimo_config->rf.rf_vcocal[ant]  = rf_vcocal_850[ant];
      p_exmimo_config->rf.rffe_band_mode[ant] = DD_TDD;	    
    }
    else if ((carrier_freq[ant] >= 1900000000) && (carrier_freq[ant] <= 2000000000)) {
      p_exmimo_config->rf.rf_vcocal[ant]  = rf_vcocal[ant];
      p_exmimo_config->rf.rffe_band_mode[ant] = B19G_TDD;	    
    }
    else {
      p_exmimo_config->rf.rf_vcocal[ant]  = rf_vcocal[ant];
      p_exmimo_config->rf.rffe_band_mode[ant] = 0;	    
    }

    p_exmimo_config->rf.rffe_gain_txlow[ant] = 31;
    p_exmimo_config->rf.rffe_gain_txhigh[ant] = 31;
    p_exmimo_config->rf.rffe_gain_rxfinal[ant] = 52;
    p_exmimo_config->rf.rffe_gain_rxlow[ant] = 31;
  }


    number_of_cards = openair0_num_detected_cards;
    /*
    if (p_exmimo_id->board_exmimoversion==1) //ExpressMIMO1
      openair_daq_vars.timing_advance = 138;
    else //ExpressMIMO2
      openair_daq_vars.timing_advance = 0;
    */

  openair0_dump_config(card);

  printf("EXMIMO_CONFIG: rf_mode 0x %x %x %x %x, [0]: TXRXEn %d, TXLPFEn %d, TXLPF %d, RXLPFEn %d, RXLPF %d, RFBB %d, LNA %d, LNAGain %d, RXLPFMode %d, SWITCH %d, rf_rxdc %d, rf_local %d, rf_vcocal %d\n",  
	 p_exmimo_config->rf.rf_mode[0],
	 p_exmimo_config->rf.rf_mode[1],
	 p_exmimo_config->rf.rf_mode[2],
	 p_exmimo_config->rf.rf_mode[3],
	 (p_exmimo_config->rf.rf_mode[0]&3),  // RXen+TXen
	 (p_exmimo_config->rf.rf_mode[0]&4)>>2,         //TXLPFen
	 (p_exmimo_config->rf.rf_mode[0]&TXLPFMASK)>>3, //TXLPF
	 (p_exmimo_config->rf.rf_mode[0]&128)>>7,      //RXLPFen
	 (p_exmimo_config->rf.rf_mode[0]&RXLPFMASK)>>8, //TXLPF
	 (p_exmimo_config->rf.rf_mode[0]&RFBBMASK)>>16, // RFBB mode
	 (p_exmimo_config->rf.rf_mode[0]&LNAMASK)>>12, // RFBB mode
	 (p_exmimo_config->rf.rf_mode[0]&LNAGAINMASK)>>14, // RFBB mode
	 (p_exmimo_config->rf.rf_mode[0]&RXLPFMODEMASK)>>19, // RXLPF mode
	 (p_exmimo_config->framing.tdd_config&TXRXSWITCH_MASK)>>1, // Switch mode
	 p_exmimo_config->rf.rf_rxdc[0],
	 p_exmimo_config->rf.rf_local[0],
	 p_exmimo_config->rf.rf_vcocal[0]);
  
  for (ant=0;ant<4;ant++)
    p_exmimo_config->rf.do_autocal[ant] = 0;

#ifdef EMOS
  error_code = rtf_create(CHANSOUNDER_FIFO_MINOR,CHANSOUNDER_FIFO_SIZE);
  if (error_code==0)
    printf("[OPENAIR][SCHED][INIT] Created EMOS FIFO %d\n",CHANSOUNDER_FIFO_MINOR);
  else if (error_code==ENODEV)
    printf("[OPENAIR][SCHED][INIT] Problem: EMOS FIFO %d is greater than or equal to RTF_NO\n",CHANSOUNDER_FIFO_MINOR);
  else if (error_code==ENOMEM)
    printf("[OPENAIR][SCHED][INIT] Problem: cannot allocate memory for EMOS FIFO %d\n",CHANSOUNDER_FIFO_MINOR);
  else 
    printf("[OPENAIR][SCHED][INIT] Problem creating EMOS FIFO %d, error_code %d\n",CHANSOUNDER_FIFO_MINOR,error_code);
#endif

  mlockall(MCL_CURRENT | MCL_FUTURE);

#ifdef RTAI
  // make main thread LXRT soft realtime
  task = rt_task_init_schmod(nam2num("MYTASK"), 9, 0, 0, SCHED_FIFO, 0xF);

  // start realtime timer and scheduler
#ifdef TIMER_ONESHOT_MODE
  rt_set_oneshot_mode();
  start_rt_timer(0);
  printf("started RTAI timer inoneshot mode\n");
#else
  rt_set_periodic_mode();
  period = start_rt_timer(nano2count(500000));
  printf("started RTAI timer with period %llu ns\n",count2nano(period));
#endif

  printf("Init mutex\n");
  //mutex = rt_get_adr(nam2num("MUTEX"));
  mutex = rt_sem_init(nam2num("MUTEX"), 1);
  if (mutex==0)
    {
      printf("Error init mutex\n");
      exit(-1);
    }
  else
    printf("mutex=%p\n",mutex);
#endif

  DAQ_MBOX = (volatile unsigned int *) openair0_exmimo_pci[card].rxcnt_ptr[0];

  // this starts the DMA transfers
  if (UE_flag!=1)
      openair0_start_rt_acquisition(card);


#ifdef XFORMS
  if (do_forms==1) {
      fl_initialize (&argc, argv, NULL, 0, 0);
      form_stats = create_form_stats_form();
      if (UE_flag==1) {
          form_ue[UE_id] = create_lte_phy_scope_ue();
          sprintf (title, "LTE DL SCOPE UE");
          fl_show_form (form_ue[UE_id]->lte_phy_scope_ue, FL_PLACE_HOTSPOT, FL_FULLBORDER, title);
      } else {
            for(UE_id=0;UE_id<scope_enb_num_ue;UE_id++) {
                form_enb[UE_id] = create_lte_phy_scope_enb();
                sprintf (title, "UE%d LTE UL SCOPE eNB",UE_id+1);
                fl_show_form (form_enb[UE_id]->lte_phy_scope_enb, FL_PLACE_HOTSPOT, FL_FULLBORDER, title);
            }
      }
      fl_show_form (form_stats->stats_form, FL_PLACE_HOTSPOT, FL_FULLBORDER, "stats");
      if (UE_flag==0) {
          for (UE_id=0;UE_id<scope_enb_num_ue;UE_id++) {
              if (otg_enabled) {
                  fl_set_button(form_enb[UE_id]->button_0,1);
                  fl_set_object_label(form_enb[UE_id]->button_0,"DL Traffic ON");
              }
              else {
                  fl_set_button(form_enb[UE_id]->button_0,0);
                  fl_set_object_label(form_enb[UE_id]->button_0,"DL Traffic OFF");
              }
          }
      }
      else {
          if (openair_daq_vars.use_ia_receiver) {
              fl_set_button(form_ue[UE_id]->button_0,1);
              fl_set_object_label(form_ue[UE_id]->button_0, "IA Receiver ON");
          }
          else {
              fl_set_button(form_ue[UE_id]->button_0,0);
              fl_set_object_label(form_ue[UE_id]->button_0, "IA Receiver OFF");
          }
      }

      ret = pthread_create(&thread2, NULL, scope_thread, NULL);
      printf("Scope thread created, ret=%d\n",ret);
    }
#endif

#ifdef EMOS
  ret = pthread_create(&thread3, NULL, emos_thread, NULL);
  printf("EMOS thread created, ret=%d\n",ret);
#endif

  rt_sleep_ns(10*FRAME_PERIOD);

#ifndef RTAI
  pthread_attr_init (&attr_dlsch_threads);
  pthread_attr_setstacksize(&attr_dlsch_threads,OPENAIR_THREAD_STACK_SIZE);
  //attr_dlsch_threads.priority = 1;
  sched_param_dlsch.sched_priority = sched_get_priority_max(SCHED_FIFO); //OPENAIR_THREAD_PRIORITY;
  pthread_attr_setschedparam  (&attr_dlsch_threads, &sched_param_dlsch);
  pthread_attr_setschedpolicy (&attr_dlsch_threads, SCHED_FIFO);
#endif

  // start the main thread
  if (UE_flag == 1) {
    /*
#ifdef RTAI
    thread1 = rt_thread_create(UE_thread, NULL, 100000000);
#else
    error_code = pthread_create(&thread1, &attr_dlsch_threads, UE_thread, NULL);
    if (error_code!= 0) {
      LOG_D(HW,"[lte-softmodem.c] Could not allocate UE_thread, error %d\n",error_code);
      return(error_code);
    }
    else {
      LOG_D(HW,"[lte-softmodem.c] Allocate UE_thread successful\n");
    }
#endif
#ifdef DLSCH_THREAD
    init_rx_pdsch_thread();
    rt_sleep_ns(FRAME_PERIOD/10);
    init_dlsch_threads();
#endif
    printf("UE threads created\n");
    */
  }
  else {
#ifdef RTAI
    thread0 = rt_thread_create(eNB_thread, NULL, 100000000);
#else
    error_code = pthread_create(&thread0, &attr_dlsch_threads, eNB_thread, NULL);
    if (error_code!= 0) {
      LOG_D(HW,"[lte-softmodem.c] Could not allocate eNB_thread, error %d\n",error_code);
      return(error_code);
    }
    else {
      LOG_D(HW,"[lte-softmodem.c] Allocate eNB_thread successful\n");
    }
#endif
#ifdef ULSCH_THREAD
    init_ulsch_threads();
#endif
    printf("eNB threads created\n");
  }


  // wait for end of program
  printf("TYPE <CTRL-C> TO TERMINATE\n");
  //getchar();
  while (oai_exit==0)
    rt_sleep_ns(FRAME_PERIOD);

  // stop threads
#ifdef XFORMS
  printf("waiting for XFORMS thread\n");
  if (do_forms==1)
    {
      pthread_join(thread2,&status);
        fl_hide_form(form_stats->stats_form);
        fl_free_form(form_stats->stats_form);
        if (UE_flag==1) {
            fl_hide_form(form_ue[UE_id]->lte_phy_scope_ue);
            fl_free_form(form_ue[UE_id]->lte_phy_scope_ue);
        } else {
            for(UE_id=0;UE_id<scope_enb_num_ue;UE_id++) {
                fl_hide_form(form_enb[UE_id]->lte_phy_scope_enb);
                fl_free_form(form_enb[UE_id]->lte_phy_scope_enb);
            }
        }
    }
#endif

  printf("stopping MODEM threads\n");
  // cleanup
  if (UE_flag == 1) {
    /*
#ifdef RTAI
    rt_thread_join(thread1); 
#else
    pthread_join(thread1,&status); 
#endif
#ifdef DLSCH_THREAD
    cleanup_dlsch_threads();
    cleanup_rx_pdsch_thread();
#endif
    */
  }
  else {
#ifdef RTAI
    rt_thread_join(thread0); 
#else
    pthread_join(thread0,&status); 
#endif
#ifdef ULSCH_THREAD
    cleanup_ulsch_threads();
#endif
  }

#ifdef OPENAIR2
  //cleanup_pdcp_thread();
#endif

#ifdef RTAI
  stop_rt_timer();
#endif

  printf("stopping card\n");
  openair0_stop(card);
  printf("closing openair0_lib\n");
  openair0_close();

#ifdef EMOS
  printf("waiting for EMOS thread\n");
  pthread_cancel(thread3);
  pthread_join(thread3,&status);
#endif

#ifdef EMOS
  error_code = rtf_destroy(CHANSOUNDER_FIFO_MINOR);
  printf("[OPENAIR][SCHED][CLEANUP] EMOS FIFO closed, error_code %d\n", error_code);
#endif

  if (ouput_vcd)
    vcd_signal_dumper_close();

  logClean();

  return 0;
}
Esempio n. 15
0
static int _init(void)
{
	int broadcast = 1;
	int64_t timeout = -1;

	rt_printk("RtnetTest: Module initialisation started\n");

	memset(buffer_in, 0, sizeof(buffer_in));
	memset(&loc_addr, 0, sizeof (struct sockaddr_in));

	memset(buffer_out, 0, sizeof(buffer_out));
	memset(&tx_addr, 0, sizeof (struct sockaddr_in));

	loc_addr.sin_family      = AF_INET;
	loc_addr.sin_port        = htons(UDPPORT);
	loc_addr.sin_addr.s_addr = INADDR_ANY;

	tx_addr.sin_family       = AF_INET;
	tx_addr.sin_port         = htons(UDPPORT);
	tx_addr.sin_addr.s_addr  = rt_inet_aton("127.0.0.1");

	if (((mbx = rt_typed_named_mbx_init("MYMBX", 2000*sizeof(struct sample), FIFO_Q))) == NULL) {
		rt_printk("RtnetTest: Cannot create the mailbox\n");
		return -1;
	}

	if (((sock = rt_dev_socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))) < 0) {
		rt_printk("RtnetTest: Error opening UDP/IP socket: %d\n", sock);
		return -1;
	}
	if (rt_dev_setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast)) == -1) {
		rt_printk("RtnetTest: Can't set broadcast options\n");
		goto close_socks;
	}

	rt_dev_ioctl(sock, RTNET_RTIOC_TIMEOUT, &timeout);

	if (rt_dev_bind(sock, (struct sockaddr *) &loc_addr, sizeof(struct sockaddr_in)) < 0) {
		rt_printk("RtnetTest: Can't bind the network socket");
		goto close_socks;
	}

	rt_set_periodic_mode();
	period = start_rt_timer(nano2count(WORKCYCLE));

	if (rt_task_init_cpuid(&rx_task, receiver, 0, STKSIZ, 0, 0, 0, CPU) < 0) {
		rt_printk("RtnetTest: Can't initialise the receiver task");
		goto close_socks;
	}

	if (rt_task_init_cpuid(&tx_task, sender, 0, STKSIZ, 0, 0, 0, CPU) < 0) {
		rt_printk("RtnetTest: Can't initialise the transmitter task");
		goto close_socks;
	}

	if (0 != rt_task_make_periodic(&tx_task, rt_get_time() + 20*period, period)) {
		rt_printk("RtnetTest: Make sender periodic failed\n");
		goto close_socks;
	}

	if (rt_task_resume(&rx_task) < 0) {
		rt_printk("RtnetTest: Can't start the receiver task");
		goto close_socks;
	}

	rt_printk("RtnetTest: Module initialisation completed\n");
	return 0;

close_socks:

	rt_dev_close(sock);
	rt_dev_shutdown(sock, SHUT_RDWR);
	return -1;
}