コード例 #1
0
ファイル: init.c プロジェクト: chch1028/rtems
/* Task01 starts with priority 36 */
rtems_task Task01(rtems_task_argument ignored)
{
  rtems_status_code status;
  printf("TA01: started with priority %d\n", getprio());

  status = rtems_semaphore_obtain( sem_id[0], RTEMS_WAIT, 0 );
  directive_failed( status, "rtems_semaphore_obtain of S0\n");
  printf("TA01: priority %d, holding S0\n", getprio());

  status = rtems_semaphore_obtain( sem_id[1], RTEMS_WAIT, 0 );
  directive_failed( status, "rtems_semaphore_obtain of S1");
  printf("TA01: priority %d, holding S0, S1\n", getprio());

  /* Start Task 2 (TA02) with priority 34. It will run immediately. */
  status = rtems_task_start( Task_id[1], Task02, 0);
  directive_failed( status, "rtems_task_start of TA02\n");

  status = rtems_semaphore_release(sem_id[1]);
  directive_failed( status, "rtems_semaphore_release of S1\n");
  printf("TA01: priority %d, holding S0\n", getprio());

  status = rtems_semaphore_release(sem_id[0]);
  directive_failed( status, "rtems_semaphore_release of S0\n");
  printf("TA01: priority %d\n", getprio());

  printf("TA01: exiting\n");
  printf("*** END OF SEM01 ***\n");
  status = rtems_task_delete( RTEMS_SELF);
  directive_failed( status, "rtems_task_delete TA01");
}
コード例 #2
0
ファイル: ex1.c プロジェクト: piotrplaneta/RTS
int main() {
    int i;
    int id1, id2;
    struct _pulse pulse;

    // Request I/O privileges
    ThreadCtl( _NTO_TCTL_IO, 0 );

    chid = ChannelCreate( 0 );
	coid = ConnectAttach( 0, 0, chid, _NTO_SIDE_CHANNEL, 0 );

	SIGEV_PULSE_INIT( &event1, coid, getprio(0), MY_PULSE_CODE1, 0 );
    id1=InterruptAttach( SYSPAGE_ENTRY(qtime)->intr, &handler1,
                        NULL, 0, 0 );

	SIGEV_PULSE_INIT( &event2, coid, getprio(0), MY_PULSE_CODE2, 0 );
    id2=InterruptAttach( SYSPAGE_ENTRY(qtime)->intr, &handler2,
                        NULL, 0, 0 );

    for( i = 0; i < 10; ++i ) {
        // Wait for ISR to wake us up
    	MsgReceivePulse( chid, &pulse, sizeof( pulse ), NULL );
    	if(pulse.code == MY_PULSE_CODE1) {
            printf( "1000 events\n" );
    	} else if(pulse.code == MY_PULSE_CODE2) {
    		printf( "2500 events\n" );
    	}
    }

    // Disconnect the ISR handler
    InterruptDetach(id1);
    InterruptDetach(id2);
    return 0;
}
コード例 #3
0
ファイル: user_t.c プロジェクト: solb/sysprogos
int main( void ) {
	prio_t prio1, prio2;
	int i, j;
	pid_t pid;

	pid = getpid();
	prio1 = getprio();
	c_printf( "User T (%d) running, initial prio %d\n", pid, prio1 );
	
	writech( 'T' );
	for( i = 0; i < 20; ++i ) {
		for( j = 0; j < DELAY_STD; ++j )
			continue;
		writech( 'T' );
	}

	prio2 = setprio( PRIO_HIGH );
	prio1 = getprio();
	c_printf( "User T, set prio #1 old %d new %d\n", prio2, prio1 );
	
	writech( 'T' );
	for( i = 0; i < 20; ++i ) {
		for( j = 0; j < DELAY_STD; ++j )
			continue;
		writech( 'T' );
	}

	prio2 = setprio( PRIO_LOW );
	prio1 = getprio();
	c_printf( "User T, set prio #2 old %d new %d\n", prio2, prio1 );

	writech( 'T' );
	for( i = 0; i < 20; ++i ) {
		for( j = 0; j < DELAY_STD; ++j )
			continue;
		writech( 'T' );
	}

	prio2 = setprio( PRIO_STD );
	prio1 = getprio();
	c_printf( "User T, set prio #3 old %d new %d\n", prio2, prio1 );
	
	writech( 'T' );
	for( i = 0; i < 30; ++i ) {
		for( j = 0; j < DELAY_STD; ++j )
			continue;
		writech( 'T' );
	}

	c_puts( "User T exiting\n" );
	exit();
}
コード例 #4
0
ファイル: client2.c プロジェクト: ptomulik/ztmir-texfactory
int main(int argc, char *argv[])
{
	int server_pid;   // PID serwera
	int server_chid;  // CHID serwera
	int coid;	// COID
	int value1;	// wysylana liczba1
	int value2 = 38; // wyslana liczba2
	int status; // status z funkcji MsgSend()

	if(argc != 4) {
		printf("K: Program musi byc wywolany z 3 argumentami, np:\n\n");
		printf("K: client 482834 1 abcdefghi    \n\n");
		printf("K: - pierwszy arg(482834): pid serwera\n");
		printf("K: - drugi arg(1): chid serwera\n");
		printf("K: - trzeci arg(5): int wysylany do serwera\n");
		exit(EXIT_FAILURE);
	}
	server_pid = atoi(argv[1]);
	server_chid = atoi(argv[2]);

	printf("K: Probuje nawiazac polaczenie z serwerem pid: %d, chid %d\n", server_pid, server_chid);
	/* Tworzenie polaczenia */
	coid = ConnectAttach(ND_LOCAL_NODE, server_pid, server_chid,_NTO_SIDE_CHANNEL,0);
	if (coid == -1)
	{
		printf("K: Nie moge utworzyc polaczenia: %s\n", strerror(errno));
		exit(EXIT_FAILURE);
	}

	value1 = atoi(argv[3]);
	printf("K: Wysylam wiadomosc: %d\n", value1);
	//	getprio(0) pobiera priorytet biezacego procesu.
	status = MsgSendPulse(coid, getprio(0),_PULSE_CODE_MINAVAIL,value1);

	if (status == -1)
	{
		printf("K: Nie moge wyslac impulsu 1: %s\n", strerror(errno));
		exit(EXIT_FAILURE);
	}
	printf("K: Wysylam wiadomosc: %d\n", value2);
	status = MsgSendPulse(coid, getprio(0), _PULSE_CODE_MINAVAIL+5, value2);
	if (status == -1)
	{
		printf("K: Nie moge wyslac impulsu 2: %s\n", strerror(errno));
		exit(EXIT_FAILURE);
	}

	return EXIT_SUCCESS;
}
コード例 #5
0
ファイル: init.c プロジェクト: gedare/rtems
/* TA02 starts at Task02 with priority 34 */
rtems_task Task02(rtems_task_argument ignored)
{
  rtems_status_code status;

  printf("TA02: started with priority %d\n", getprio());

  /* Obtain S1, which should be held by TA01 by now */
  status = rtems_semaphore_obtain( sem_id[1], RTEMS_WAIT, 0 );
  directive_failed( status, " rtems_semaphore_obtain S1");
  printf("TA02: priority %d, holding S1\n", getprio());

  printf("TA02: suspending\n");
  status = rtems_task_suspend( RTEMS_SELF);
  directive_failed( status, "rtems_task_suspend TA02");
}
コード例 #6
0
ファイル: test6.c プロジェクト: Leymariv/Operating-System
int main(void *arg)
{
        int pid1, pid2, pid3;
        int ret;

        (void)arg;

        assert(getprio(getpid()) == 128);
        pid1 = start("proc6_1", 0, 64, 0);
        assert(pid1 > 0);
        pid2 = start("proc6_2", 4, 66, (void*)4);
        assert(pid2 > 0);
        pid3 = start("proc6_3", 0xffffffff, 65, (void*)5);
	assert(pid3 < 0);
        pid3 = start("proc6_3", 8, 65, (void*)5);
        assert(pid3 > 0);
        assert(waitpid(-1, &ret) == pid2);
        assert(ret == 4);
        assert(waitpid(-1, &ret) == pid3);
        assert(ret == 5);
        assert(waitpid(-1, &ret) == pid1);
        assert(ret == 3);
        assert(waitpid(pid1, 0) < 0);
        assert(waitpid(-1, 0) < 0);
        assert(waitpid(getpid(), 0) < 0);
        printf("ok.\n");
}
コード例 #7
0
std::string IDSEXT::RegisterProvider(const std::string& providerName)
{
    Json::FastWriter writer;
    Json::Value resultJSON;

    ids_provider_mapping *registeredItem = reinterpret_cast<ids_provider_mapping *>(malloc(sizeof(ids_provider_mapping)));
    if (!registeredItem) {
        fprintf(stderr, "Unable to register IDS provider - malloc error\n");
        return "";
    }

    registeredItem->providerName = strdup(providerName.c_str());
    resultJSON["result"] = ids_register_provider(registeredItem->providerName, &registeredItem->provider, &registeredItem->providerFd);
    if ( (ids_result_t) resultJSON["result"].asInt() == IDS_SUCCESS ) {
        registeredItem->next = providers;
        providers = registeredItem;

        registeredItem->sigEvent = new sigevent;
        registeredItem->sigEvent->sigev_notify = SIGEV_PULSE;
        registeredItem->sigEvent->sigev_coid = ConnectAttach(ND_LOCAL_NODE, 0, eventCHID, _NTO_SIDE_CHANNEL, 0);
        registeredItem->sigEvent->sigev_priority = getprio(0);
        registeredItem->sigEvent->sigev_code = registeredItem->providerFd;
        registeredItem->sigEvent->sigev_value.sival_int = registeredItem->providerFd;

        if (ionotify(registeredItem->providerFd, _NOTIFY_ACTION_POLLARM, _NOTIFY_COND_INPUT, registeredItem->sigEvent) & _NOTIFY_COND_INPUT) {
            MsgDeliverEvent(0, registeredItem->sigEvent);
        }
    } else {
        resultJSON["errno"] = strerror(errno);
    }

    std::string resultStr = writer.write(resultJSON);
    return( resultStr.c_str() );
}
コード例 #8
0
ファイル: renice.c プロジェクト: sebras/util-linux
static int donice(const int which, const int who, const int prio)
{
	int oldprio, newprio;

	if (getprio(which, who, &oldprio) != 0)
		return 1;
	if (setpriority(which, who, prio) < 0) {
		warn(_("failed to set priority for %d (%s)"), who, idtype[which]);
		return 1;
	}
	if (getprio(which, who, &newprio) != 0)
		return 1;
	printf(_("%d (%s) old priority %d, new priority %d\n"),
	       who, idtype[which], oldprio, newprio);
	return 0;
}
コード例 #9
0
ファイル: main.c プロジェクト: Leymariv/Operating-System
int main(int argc, char *argv[])
{
	printf("*****************************\nTest shm\n"
	       "*****************************\n");
	(void)argc;
	(void)argv;
	
	const char *c="page_test_shm";
	int fid=pcreate(1);
	int ret;
	int pid=start("test_shm1",10000,getprio(getpid()),(void *)fid);
	void *pagep = shm_create(c);
	assert(pagep!=NULL);
	*((int*)pagep+4)=23;
	psend(fid, 1);
	preceive(fid,&ret);
	printf("[process %i] : %i\n",getpid(),*((int*)pagep+4));
	pdelete(fid);
	shm_release(c);
	waitpid(pid,&ret);
	assert(shm_acquire(c)==NULL);
	printf("\n*****************************\nTest fini\n"
	       "*****************************\n");
	return 0;
}
コード例 #10
0
ファイル: test4.c プロジェクト: Leymariv/Operating-System
int main(void *args)
{
        int pid1, pid2;
        int r;
        int arg = 0;

        (void)args;
        assert(getprio(getpid()) == 128);
        pid1 = start("busy1", 4000, 64, (void *) arg);
        assert(pid1 > 0);
        pid2 = start("busy2", 4000, 64, (void *) pid1);
        assert(pid2 > 0);
        printf("1 -");
        r = chprio(getpid(), 32);
        assert(r == 128);
        printf(" - 2");
        r = kill(pid1);
        assert(r == 0);
        assert(waitpid(pid1, 0) == pid1);
        r = kill(pid2);
        assert(r < 0); /* kill d'un processus zombie */
        assert(waitpid(pid2, 0) == pid2);
        printf(" 3");
        r = chprio(getpid(), 128);
        assert(r == 32);
        printf(" 4.\n");

        return 0;
}
コード例 #11
0
int main(void *arg)
{
        int fid = (int)arg;
        int c = cons_read();
        assert(psend(fid, 1) == 0);
        printf(" %d (%c)", 134 - getprio(getpid()), c);
        return 0;
}
コード例 #12
0
ファイル: init.c プロジェクト: gedare/rtems
/* Task03 starts with priority 32 */
rtems_task Task03(rtems_task_argument ignored)
{
  rtems_status_code status;
  printf("TA03: started with priority %d\n", getprio());

  status = rtems_semaphore_obtain( sem_id[0], RTEMS_WAIT, 0 );
  directive_failed( status, "rtems_semaphore_obtain of S0\n");
  printf("TA03: priority %d, holding S0\n", getprio());

  status = rtems_semaphore_release(sem_id[0]);
  directive_failed( status, "rtems_semaphore_release of S0\n");
  printf("TA03: priority %d\n", getprio());

  printf("TA03: exiting\n");
  status = rtems_task_delete( RTEMS_SELF);
  directive_failed( status, "rtems_task_delete TA03");
}
コード例 #13
0
ファイル: ex3.c プロジェクト: piotrplaneta/RTS
int main3(int argc, char **argv) {
	struct sigevent event_frame;
	struct itimerspec itime_frame;
	timer_t frame_timer_id;
	int chid;
	int rcvid;
	int srv_coid;
	my_message_t msg;

	if(argc != 3) {
		printf("proper usage: ./lab5 hyperperiod_duration_in_sec frames_count\n");
		return 0;
	}

	int duration = atoi(argv[1]);
	int frames_count = atoi(argv[2]);

	float frame_duration = (float)duration / (float)frames_count;

	int frame_duration_seconds = (int) frame_duration;
	int frame_duration_ns = (int) ((frame_duration - frame_duration_seconds) * 1000000000);

	chid = ChannelCreate(0);
	srv_coid = ConnectAttach(ND_LOCAL_NODE, 0, chid, _NTO_SIDE_CHANNEL, 0);


	event_frame.sigev_notify = SIGEV_PULSE;
	event_frame.sigev_coid = srv_coid;
	event_frame.sigev_priority = getprio(0);
	event_frame.sigev_code = FRAME_PULSE_CODE;
	timer_create(CLOCK_REALTIME, &event_frame, &frame_timer_id);
	itime_frame.it_value.tv_sec = frame_duration_seconds;
	itime_frame.it_value.tv_nsec = frame_duration_ns;
	itime_frame.it_interval.tv_sec = frame_duration_seconds;
	itime_frame.it_interval.tv_nsec = frame_duration_ns;
	timer_settime(frame_timer_id, 0, &itime_frame, NULL);


	int tid;
	int i = 0;
	pthread_create(&tid, NULL, print_functions, (void *)i);
	for (;;) {
		rcvid = MsgReceivePulse(chid, &msg, sizeof(msg), NULL);
		if (rcvid == 0) {
			if (msg.pulse.code == FRAME_PULSE_CODE) {
				i++;
				pthread_cancel(tid);
				pthread_create(&tid, NULL, print_functions, (void *)i);
				printf("\n\n\tKoniec ramki %d\n\n", i);
				if(i == frames_count) {
					printf("\n\n\t\tKoniec hiper-okresu\n\n");
					i = -1;
				}
			}
		}
	}
}
コード例 #14
0
ファイル: app3.c プロジェクト: gowthamk/xinu
int app3() {
    int res = 101 * 555;
    int my_pid = getpid();
    int my_prio = getprio(my_pid);
    kprintf("app3: 101*555=%d.\n",res);
    kprintf("app3: my pid is %d and my priority is %d.\n",my_pid,my_prio);
    int parent_pid = getppid();
    kprintf("app3: my parent pid is %d.\n",parent_pid);
    return 0;
}
コード例 #15
0
ファイル: app3.c プロジェクト: Ninja91/Operating-Systems-Hw
void app3(){
    kprintf(" 101x555 Result -- %d\n", 101*555);
    kprintf("app 3 PID -- %d\n", getpid());
    kprintf("app 3 Process Priority -- %d\n", getprio(getpid()));    

    kprintf("\n\nParent PID:");
    kprintf("Parent PID -- %d\n", getppid());
    kprintf("\n\nBonus Question:");
    prtprstate(getpid());
}
コード例 #16
0
ファイル: init.c プロジェクト: gedare/rtems
/* Task01 starts with priority 36 */
rtems_task Task01(rtems_task_argument ignored)
{
  rtems_status_code status;
  printf("TA01: started with priority %d\n", getprio());

  status = rtems_semaphore_obtain( sem_id[0], RTEMS_WAIT, 0 );
  directive_failed( status, "rtems_semaphore_obtain of S0\n");
  printf("TA01: priority %d, holding S0\n", getprio());

  status = rtems_semaphore_obtain( sem_id[1], RTEMS_WAIT, 0 );
  directive_failed( status, "rtems_semaphore_obtain of S1");
  printf("TA01: priority %d, holding S0, S1\n", getprio());

  /* Start Task 2 (TA02) with priority 34. It will run immediately. */
  status = rtems_task_start( Task_id[1], Task02, 0);
  directive_failed( status, "rtems_task_start of TA02\n");

  /* Start Task 3 (TA03) with priority 32. It will run immediately. */
  status = rtems_task_start( Task_id[2], Task03, 0);
  directive_failed( status, "rtems_task_start of TA03\n");
  printf("TA01: priority %d, holding S0, S1\n", getprio());

  status = rtems_semaphore_release(sem_id[1]);
  directive_failed( status, "rtems_semaphore_release of S1\n");
  printf("TA01: priority %d, holding S0\n", getprio());

  status = rtems_semaphore_release(sem_id[0]);
  directive_failed( status, "rtems_semaphore_release of S0\n");
  printf("TA01: priority %d\n", getprio());

  printf("TA01: exiting\n");
  TEST_END();

  rtems_test_exit(0);
}
コード例 #17
0
ファイル: kill.c プロジェクト: michalt25/Courses
void inversion(int pid)
{
	int waiting_lock_id,max=-1,i;
	waiting_lock_id = proctab[pid].waiting_lock.lock_id;
	if(lockarr[waiting_lock_id].maxprio == getprio(pid))
	{
		int head=lockarr[waiting_lock_id].lqhead;
		int next = next = q[head].qnext;
		while(next<NPROC)
		{
			if(getprio(next) && (next!=pid))
				max = getprio(next);
			next = q[next].qnext;
		}
		lockarr[waiting_lock_id].maxprio = max;
		for(i=0;i<NPROC;i++)
		{
			if(lockarr[waiting_lock_id].process_lock[i]==1)
				proctab[i].pinh = max;
		}
	}
}
コード例 #18
0
int main(void *arg)
{
    int i, count, fid, pid;
    struct tst16 *p = NULL;
    int pids[2 * NB_PROCS];

    (void)arg;
    p = (struct tst16*) shm_create("test16_shm");
    assert(p != NULL);

    assert(getprio(getpid()) == 128);
    for (count = 1; count <= 100; count++) {
        fid = pcreate(count);
        assert(fid >= 0);
        p->count = count;
        p->fid = fid;
        pid = start("proc16_1", 2000, 128, 0);
        assert(pid > 0);
        for (i=0; i<=count; i++) {
            assert(psend(fid, i) == 0);
            test_it();
        }
        assert(waitpid(pid, 0) == pid);
        assert(pdelete(fid) == 0);
    }

    p->count = 20000;
    fid = pcreate(50);
    assert(fid >= 0);
    p->fid = fid;
    for (i = 0; i< NB_PROCS; i++) {
        pid = start("proc16_2", 2000, 127, 0);
        assert(pid > 0);
        pids[i] = pid;
    }
    for (i=0; i < NB_PROCS; i++) {
        pid = start("proc16_3", 2000, 127, 0);
        assert(pid > 0);
        pids[NB_PROCS + i] = pid;
    }
    for (i=0; i < 2 * NB_PROCS; i++) {
        assert(waitpid(pids[i], 0) == pids[i]);
    }
    assert(pcount(fid, &count) == 0);
    assert(count == 0);
    assert(pdelete(fid) == 0);

    shm_release("test16_shm");
    printf("ok.\n");
    return 0;
}
コード例 #19
0
void CreateInterrupt(Interrupt *ret, long periodMicros, long sec)
{
	//declare variables
	struct sigevent event;
	struct itimerspec timer;
	struct _clockperiod clkper;
	struct sched_param param;
	timer_t timer_id;

	/* Give this thread root permissions to access the hardware */
	ThreadCtl( _NTO_TCTL_IO, NULL );

	int chid = ChannelCreate( 0 ); //create event channel

	/* Set our priority to the maximum, so we won’t get disrupted by anything other than interrupts. */
	param.sched_priority = sched_get_priority_max( SCHED_RR );

	//set the clock from 10ns to 1microsecond ticks
	clkper.nsec = 100000;
	clkper.fract = 0;
	ClockPeriod ( CLOCK_REALTIME, &clkper, NULL, 0 ); // 1ms

	//Set up the pulse width modulation event
	event.sigev_notify = SIGEV_PULSE;		// most basic message we can send -- just a pulse number
	event.sigev_coid = ConnectAttach ( ND_LOCAL_NODE, 0, chid, 0, 0 );  // Get ID that allows me to communicate on the channel
	assert ( event.sigev_coid != -1 );		// stop with error if cannot attach to channel
	event.sigev_priority = getprio(0);
	event.sigev_code = 1023;				// arbitrary number assigned to this pulse
	event.sigev_value.sival_ptr = (void*)0;		// ?? TBD

	// Now create the timer and get back the timer_id value for the timer we created.
	if ( timer_create( CLOCK_REALTIME, &event, &timer_id ) == -1)
	{
		perror ( "can’t create timer" );
		exit( EXIT_FAILURE );
	}

	/* Change the timer request to alter the behavior. */
	timer.it_value.tv_sec = sec;
	timer.it_value.tv_nsec = periodMicros * 1000;
	timer.it_interval.tv_sec = sec;
	timer.it_interval.tv_nsec = periodMicros * 1000;


	//ret = (Interrupt){timer_id, timer, chid, periodMicros};
	ret->timer_id = timer_id;
	ret->timer = timer;
	ret->chid = chid;
	ret->period = periodMicros;
}
コード例 #20
0
ファイル: task1.c プロジェクト: riturajsacademic/XinuPA2
void test3 ()
{
        
        int     rd1, rd2;
        int     wr1;

        kprintf("\nTest 3: test the basic priority inheritence\n");
        lck  = lcreate();
        lck2 = lcreate();
		kprintf("lck1: %d    \t  lck2: %d",lck,lck2);
        rd1 = create(reader3, 2000, 25, "reader3", 2, "reader A", lck);
        rd2 = create(reader3, 2000, 30, "reader3", 2, "reader B", lck2);
        wr1 = create(writer3, 2000, 40, "writer3", 2, "writer C", lck);
		 kprintf("-start reader B, then sleep 1s. reader B(prio 30) blocked on the lock\n");
        resume (rd2);
		sleep (1);
        kprintf("-start writer, then sleep 1s. lock granted to write (prio 20)\n");
        resume(wr1);
        sleep (1);

        kprintf("-start reader A, then sleep 1s. reader A(prio 25) blocked on the lock\n");
        resume(rd1);
		assert(getprio(rd2)==40);
		assert(getprio(rd1)==25);
		assert(getprio(wr1)==40);
	   
	    sleep (8);
        kprintf ("Test 3 OK\n");
		/*semaphore*/
		
       
		kprintf("\n\nSEMAPHORE	\n\n");
        kprintf("\nTest 3: test the basic priority inheritence\n");
        sem  = screate(2);
        sem2 = screate(1);
		kprintf("lck1: %d    \t  lck2: %d",lck,lck2);
        rd1 = create(readersem3, 2000, 25, "readersem3", 2, "reader A", sem);
        rd2 = create(readersem3, 2000, 30, "readersem3", 2, "reader B", sem2);
        wr1 = create(writersem3, 2000, 40, "writersem3", 2, "writer C", sem);
		 kprintf("-start reader B, then sleep 1s. reader B(prio 30) blocked on the lock\n");
        resume (rd2);
		sleep (1);
        kprintf("-start writer, then sleep 1s. lock granted to write (prio 20)\n");
        resume(wr1);
        sleep (1);

        kprintf("-start reader A, then sleep 1s. reader A(prio 25) blocked on the lock\n");
        resume(rd1);
		assert(getprio(rd2)==40);
		assert(getprio(rd1)==25);
		assert(getprio(wr1)==40);
	   
	    sleep (8);
        kprintf ("Test 3 OK\n");
		
		
}
コード例 #21
0
/*
 * Function     - __pwm_setup()
 *
 * Arguments    - None
 *
 * Return Value - None
 */
static __inline void __pwm_setup(void)
{
   timer_t  timer_id;
   struct sigevent event;
   struct itimerspec interval_time;

   // Set-up signal handler for handling __SIG_SETUP_OP
   action.sa_handler = __pwm_signal_handler;
   action.sa_flags = SA_SIGINFO;
   sigaction(__SIG_SETUP_OP, &action, NULL);

#if defined (__ARM__)
   // Map GPIO address into virtual memory
   gpio_base = (sint32_t)mmap_device_memory(0,
                                            GPIO_MEM_SIZE,
                                            (PROT_READ | PROT_WRITE | PROT_NOCACHE),
                                            0,
                                            (uint32_t)GPIO_BASE_ADDR);

   if(gpio_base == MAP_DEVICE_FAILED)
   {
      perror("Mapping GPIO base address\n");
      exit(0);
   }
#endif   // #if defined (__ARM__)

   // Create channel for timer pulses
   channel_id = ChannelCreate(0);

   // Setup timer pulse event
   event.sigev_notify = SIGEV_PULSE;
   event.sigev_priority = getprio(0);
   event.sigev_code = __TIMER_PULSE_CODE;
   event.sigev_coid = ConnectAttach(ND_LOCAL_NODE, 0, channel_id, _NTO_SIDE_CHANNEL, 0);

   // Create the timer
   timer_create(CLOCK_REALTIME, &event, &timer_id);

   // Set timer interval
   interval_time.it_value.tv_sec = 0;
   interval_time.it_value.tv_nsec = __TIMER_TICK_NS;
   interval_time.it_interval.tv_sec = 0;
   interval_time.it_interval.tv_nsec = __TIMER_TICK_NS;

   // Timer will start after this call
   timer_settime(timer_id, 0, &interval_time, NULL);
}
コード例 #22
0
void dolog(int prio, const char *fmt, ...)
{
	char *p;
	va_list ap;
	char	logprio[20];

	if(nosysl && prio <= gLogLevel) {
		getprio(prio,logprio,sizeof(logprio));
		fprintf(stderr,"%s ",logprio);
		va_start(ap, fmt);
		(void) vfprintf(stderr, fmt, ap);
		va_end(ap);
		fprintf(stderr,"\n");
	}
	else {
		va_start(ap, fmt);
		vsyslog(prio, fmt, ap);
		va_end(ap);
	}
}
コード例 #23
0
void *time_update( void *ptr )
{
	 struct sigevent         event;
	 struct itimerspec       itime;
	 timer_t                 timer_id;
	 int                     chid, rcvid;
	 my_message_t            msg;

	 chid = ChannelCreate(0);

	 event.sigev_notify = SIGEV_PULSE;
	 event.sigev_coid = ConnectAttach(ND_LOCAL_NODE, 0,
	                                    chid,
	                                    _NTO_SIDE_CHANNEL, 0);
	 event.sigev_priority = getprio(0);
	 event.sigev_code = MY_PULSE_CODE;
	 timer_create(CLOCK_REALTIME, &event, &timer_id);

	 itime.it_value.tv_sec = 0;
	 /* 100 ms = .1 secs */
	 itime.it_value.tv_nsec = 100000000;
	 itime.it_interval.tv_sec = 0;
	 /* 100 ms = .1 secs */
	 itime.it_interval.tv_nsec = 100000000;
	 timer_settime(timer_id, 0, &itime, NULL);
	 // This for loop will update the global_time for every 100 ms which is 1 minute in simulation time.
	 for (;;) {
	     rcvid = MsgReceive(chid, &msg, sizeof(msg), NULL);
	     if (rcvid == 0) { /* we got a pulse */
	          if (msg.pulse.code == MY_PULSE_CODE) {
	          	if (global_time > 0)
	        	  global_time--;
	          	else
	          		break;
	            //printf("we got a pulse from our timer and time = %d\n", global_time);
	          } /* else other pulses ... */
	     } /* else other messages ... */
    }
}
コード例 #24
0
ファイル: test_semaphore5.c プロジェクト: disrvptor/xinu
process test_semaphore5(bool8 verbose)
{
    pid32 atid;
    bool8 passed = TRUE;
    sid32 s;
    byte testResult = 0;
    char msg[50];

    testPrint(verbose, "Semaphore creation: ");
    s = semcreate(0);
    if (isbadsem(s))
    {
        passed = FALSE;
        sprintf(msg, "%d", s);
        testFail(verbose, msg);
    }
    else if (test_checkSemCount(s, 0))
    {
        testPass(verbose, "");
    }
    else
    {
        passed = FALSE;
    }

    ready(atid =
          create((void *)test_semWaiter, INITSTK, getprio(getpid()) + 10,
                 "SEMAPHORE-A", 3, s, 1, &testResult), RESCHED_YES);

    testPrint(verbose, "Wait on semaphore: ");
    if (test_checkProcState(atid, PR_WAIT)
        && test_checkSemCount(s, -1) && test_checkResult(testResult, 0))
    {
        testPass(verbose, "");
    }
    else
    {
        passed = FALSE;
    }

    testPrint(verbose, "Reset semaphore: ");
    if ((OK == semreset(s, 0))
	&& test_checkProcState(atid, PR_FREE)
        && test_checkSemCount(s, 0) && test_checkResult(testResult, 1))
    {
        testPass(verbose, "");
    }
    else
    {
        passed = FALSE;
    }

    testPrint(verbose, "Reset semaphore (invalid count): ");
    if (SYSERR == semreset(s, -5))
    {
        testPass(verbose, "");
    }
    else
    {
        passed = FALSE;
    }

    testPrint(verbose, "Reset invalid semaphore: ");
    if (SYSERR == semreset(-1, 0))
    {   
        testPass(verbose, "");
    }
    else
    {
        passed = FALSE;
    }

    semdelete(s);

    testPrint(verbose, "Reset free semaphore: ");
    if (SYSERR == semreset(s, 0))
    {   
        testPass(verbose, "");
    }
    else
    {
        passed = FALSE;
    }

    if (TRUE == passed)
    {
        testPass(TRUE, "");
    }
    else
    {
        testFail(TRUE, "");
    }

    return OK;
}
コード例 #25
0
ファイル: event_client.c プロジェクト: ejoonie/mutex
int main(int argc, char *argv[]) {
    int server_coid, self_coid, chid, rcvid;
    struct reg_msg msg;

    setvbuf (stdout, NULL, _IOLBF, 0);

    /* look for server */
    server_coid = name_open( RECV_NAME, 0 );
    while( server_coid == -1 )
    {  
      sleep(1);
      server_coid = name_open( RECV_NAME, 0 );
    }

    chid = ChannelCreate(0);
    if( -1 == chid)
    {
        perror( PROGNAME "ChannelCreate");
        exit( EXIT_FAILURE );
    }
    self_coid = ConnectAttach( 0, 0, chid, _NTO_SIDE_CHANNEL, 0 );
    if( -1 == self_coid )
    {
        perror( PROGNAME "ConnectAttach");
        exit( EXIT_FAILURE );
    }
    
    msg.type = REG_MSG;
    
    /* class: Initialize the sigevent structure (msg.ev) in the message 
     * to be sent to the server.
     */
    SIGEV_PULSE_INIT( &msg.ev, self_coid, getprio(0), MY_PULSE_CODE, 0 );

    if (MsgSend( server_coid, &msg, sizeof( msg ), NULL, 0 ))
    {
        perror(PROGNAME "MsgSend");
        exit( EXIT_FAILURE );
    }
    
    while( 1 )
    {
        rcvid = MsgReceive( chid, &recv_buf, sizeof(recv_buf), NULL );
        if( -1 == rcvid )
        {
            perror(PROGNAME "MsgReceive");
            continue;
        }
        if ( 0 == rcvid )
        {
            if (MY_PULSE_CODE == recv_buf.pulse.code )
            {
                printf(PROGNAME "got my pulse, value is %d\n", recv_buf.pulse.value.sival_int);
            } else
            {
                printf(PROGNAME "got unexpected pulse with code %d, value %d\n", 
                        recv_buf.pulse.code, recv_buf.pulse.value.sival_int );
            }
            continue;
        }
        printf(PROGNAME "got unexpected message, type: %d\n", recv_buf.type );
        MsgError( rcvid, ENOSYS );
    }
 }
コード例 #26
0
/*-----------------------------------------------------------------------------

 PUBLIC ROUTINE

  NTP_PollingThrdFunc

 DESCRIPTION

  This routine will manage NTP polling session. The client will extract
  timing information from the packet which is t1, t2, t3, and t4. Compute
  the delay and offset. The client will update RTC if offset is exceeding
  the defined spurious threshold, and thereby update the clock to the
  BIOS system.

  Timestamp Name ID When Generated
  --------------------------------
  t1: Originate Timestamp, time request sent by client
  t2: Receive Timestamp, time request received by server
  t3: Transmit Timestamp, time reply sent by server
  t4: Destination Timestamp, time reply received by client

  The roundtrip delay d and local clock offset t are defined as
  d = (t4 - t1) - (t2 - t3)
  t = ((t2 - t1) + (t3 - t4)) / 2.

 CALLED BY

  SYS_Initialization

 CALLS

  None

 PARAMETER

  None

 RETURN

   E_ERR_Success      the routine executed successfully

 AUTHOR

  Bryan KW Chong


 HISTORY

    NAME            DATE                    REMARKS

   Bryan Chong    25-Jan-2009      Created initial revision

-----------------------------------------------------------------------------*/
VOID *NTP_PollingThrdFunc(VOID *pThreadParameter)
{
  INT32             chid;
  struct sigevent   event;
  struct itimerspec itime;
  timer_t           timer_id;
  INT32             rcvid;
  NTP_CH_MSG_T      msg;
  E_ERR_T            rstatus;
  #if((defined CFG_DEBUG_MSG) && CFG_DEBUG_NTP_POLL)
  struct tm         *pbdtime;
  #endif // ((defined CFG_DEBUG_MSG) && CFG_DEBUG_NTP_POLL)
  struct timespec   tspec;
  #if((defined CFG_DEBUG_MSG) || (CFG_DEBUG_NTP))
  struct tm         *tFormatTime;
  #endif // ((defined CFG_DEBUG_MSG) || (CFG_DEBUG_NTP))

  NTP_PACKET_T      tx_ntppack;
  NTP_PACKET_T      rx_ntppack;
  UINT8             ucntp_packet_sz;
  INT32             rlen;

  FP64              t1, t2, t3, t4;
  FP64              tdelay, toffset;
  FP64              tadjust;
  FP64              integer_part;
  timespec          ctspec;

  #ifdef CFG_PRN_WARN
  CHAR              errBuff[100] = {0};
  #endif // CFG_PRN_WARN

  if ((chid = ChannelCreate (0)) == TYP_ERROR)
  {
    #ifdef CFG_PRN_ERR
    printf("ERR  [NTP] NTP_PollingThrdFunc, fail to create channel, %s\n",
            strerror(errno));
    #endif // CFG_PRN_ERR
    return TYP_NULL;
  }

  pNTP_CB->npolling_channelID = chid;

  // set up the pulse
  event.sigev_notify = SIGEV_PULSE;
  event.sigev_coid =
    ConnectAttach(ND_LOCAL_NODE, 0, chid, _NTO_SIDE_CHANNEL, 0);
  event.sigev_priority = getprio(0);
  event.sigev_code = E_SYS_PULSE_NTP_Polling;
  timer_create(CLOCK_REALTIME, &event, &timer_id);

  pNTP_CB->polling_timer_id = timer_id;

  while(1)
  {
    rcvid = MsgReceive (chid, &msg, sizeof (msg), NULL);

    if (rcvid < 0)
    {
       //gotAMessage (rcvid, &msg.msg);
       #ifdef CFG_PRN_ERR
       printf("ERR  [NTP] NTP_PollingThrdFunc, error, %s\n",
               strerror(errno));
       #endif //CFG_PRN_ERR
    }

    if (rcvid > 0)
    {
       //gotAMessage (rcvid, &msg.msg);
       #if((defined CFG_DEBUG_MSG) || (CFG_DEBUG_NTP))
       printf("[NTP] NTP_LinkManagementThrdFunc, currently not support message"
              "handling\n");
       #endif //((defined CFG_DEBUG_MSG) || (CFG_DEBUG_NTP))
    }

    // determine where the message came from
    if (msg.pulse.code != E_SYS_PULSE_NTP_Polling)
    {
      #ifdef CFG_PRN_WARN
      printf("WARN [NTP] NTP_PollingThrdFunc, unidentified pulse code"
             "%d\n", msg.pulse.code);
      #endif // CFG_PRN_WARN
      continue;
    }

    #if((defined CFG_DEBUG_MSG) && CFG_DEBUG_NTP_POLL)
    rstatus = SYS_GetCurrentTimeInString(&pbdtime, &tspec, E_SYS_TIME_Local);
    if(rstatus != E_ERR_Success)
    {
      #ifdef CFG_PRN_WARN
      printf("WARN [NTP] NTP_PollingThrdFunc, get current time fail, %d\n",
              rstatus);
      #endif // CFG_PRN_WARN
      continue;
    }

    printf("[NTP] %d.%02d.%02d %02d:%02d:%02d.%03d NTP_PollingThrdFunc\n",
           (pbdtime->tm_year + 1900), (pbdtime->tm_mon + 1),
           pbdtime->tm_mday, pbdtime->tm_hour, pbdtime->tm_min,
           pbdtime->tm_sec, tspec.tv_nsec/1000000);
    #endif //((defined CFG_DEBUG_MSG) || (CFG_DEBUG_NTP))

    // construct the ntp request packet
    tx_ntppack.flags.allbits = 0xe3;
    tx_ntppack.peerClkStranum = TYP_NULL;
    tx_ntppack.peerPollingInterval = 0x4;
    tx_ntppack.peerClockPrecision = -6;
    tx_ntppack.rootDelay = NTP_Fp64ToFpst32(1.0000);
    tx_ntppack.rootDispersion = NTP_Fp64ToFpst32(1.0000);
    tx_ntppack.referenceClockID = TYP_NULL;
    tx_ntppack.referenceClockUpdateTime = NTP_Fp64ToFpst64(0.0000);
    tx_ntppack.originateTimeStamp = NTP_Fp64ToFpst64(0.0000);
    tx_ntppack.receiveTimeStamp = NTP_Fp64ToFpst64(0.0000);

    // get current time
    clock_gettime(CLOCK_REALTIME, &tspec);
    tx_ntppack.transmitTimeStamp =
      NTP_Fp64ToFpst64(tspec.tv_sec + NTP_JAN_1970 + 1.0e-9 * tspec.tv_nsec);
    ucntp_packet_sz = sizeof(NTP_PACKET_T);

    if(pNTP_CB->pactiveserver == TYP_NULL)
      continue;

    // transmit and receive ntp reply packet
    rstatus = LNC_SendWithReply(
          pNTP_CB->pactiveserver->nfd,
          (const CHAR *)&tx_ntppack,
          ucntp_packet_sz,
          (VOID *)&rx_ntppack,
          ucntp_packet_sz, &rlen, 2000);
    if (rstatus != E_ERR_Success)
    {
      #ifdef CFG_PRN_WARN
      ERR_GetMsgString(rstatus, errBuff);
      printf("ERR  [NTP] NTP_PollingThrdFunc, LNC_SendWithReply error "
             "%s\n", errBuff);
      #endif // CFG_PRN_WARN
      if(rstatus == E_ERR_LNC_SelectReadTimeOut)
      {
        #ifdef CFG_PRN_WARN
        printf("WARN [NTP] NTP_PollingThrdFunc, server %s is down.\n",
                pNTP_CB->pactiveserver->ipaddr);
        #endif // ((defined CFG_DEBUG_MSG) && (CFG_DEBUG_NTP))
      }
      pNTP_CB->pactiveserver->isConnectionGood = E_TYPE_No;
      pNTP_CB->pactiveserver = TYP_NULL;
      rlen = 0;

      // disarm timer
      itime.it_value.tv_sec = 0;
      itime.it_value.tv_nsec = 0;
      timer_settime(timer_id, 0, &itime, NULL);
      continue;
    }

    // Get t4, destination timestamp, time reply received by client
    clock_gettime(CLOCK_REALTIME, &tspec);
    t4 = tspec.tv_sec + NTP_JAN_1970 + 1.0e-9 * tspec.tv_nsec;

    // Get t1, originate timestamp, time request sent by client
    t1 = NTP_Fpst64ToFp64(rx_ntppack.originateTimeStamp);

    // Get t2, receive timestamp, time request received by server
    t2 = NTP_Fpst64ToFp64(rx_ntppack.receiveTimeStamp);

    // Get t3, transmit timestamp, time reply sent by server
    t3 = NTP_Fpst64ToFp64(rx_ntppack.transmitTimeStamp);

    // compute the delay and offset in seconds
    tdelay = (t4 - t1) - (t2 - t3);
    toffset = ((t2 - t1) + (t3 - t4))/2;

    // check if delay and offset is within the defined tolerance if not
    // update RTC
    clock_gettime(CLOCK_REALTIME, &tspec);
    tadjust = tspec.tv_sec + NTP_JAN_1970 + 1.0e-9 * tspec.tv_nsec;
    tadjust += toffset;

    #if((defined CFG_DEBUG_MSG) && CFG_DEBUG_NTP_POLL)
    tFormatTime = localtime(&tspec.tv_sec);
    printf("[NTP] NTP_PollingThrdFunc, %s:%d fd %d, "
           "%04d-%02d-%02d %02d:%02d:%02d\n"
           "  t1 = %.09f, t2 = %.09f,\n"
           "  t3 = %.09f, t4 = %.09f\n"
           "  delay = %.09f, offset = %.09f tadjust = %.09f\n",
           pNTP_CB->pactiveserver->ipaddr, NTP_SERVER_PORT,
           pNTP_CB->pactiveserver->nfd,
           (tFormatTime->tm_year + 1900), (tFormatTime->tm_mon + 1),
           tFormatTime->tm_mday, tFormatTime->tm_hour, tFormatTime->tm_min,
           tFormatTime->tm_sec, t1, t2, t3, t4, tdelay, toffset, tadjust);
    #endif // ((defined CFG_DEBUG_MSG) || (CFG_DEBUG_NTP))

    // Check if exceed spurious threshold in milliseconds
    if((abs(toffset) * 1e3) < pNTP_CB->threshold)
      continue;

    ctspec.tv_nsec = modf(tadjust, &integer_part) * 1e9;
    ctspec.tv_sec = integer_part - NTP_JAN_1970;

    #if((defined CFG_DEBUG_MSG) || CFG_DEBUG_NTP)
    tFormatTime = localtime(&ctspec.tv_sec);
    printf("[NTP] NTP_PollingThrdFunc, update current time = \n"
           "  sec = %d, nsec = %d\n  %04d-%02d-%02d %02d:%02d:%02d\n",
           ctspec.tv_sec, ctspec.tv_nsec,
           (tFormatTime->tm_year + 1900), (tFormatTime->tm_mon + 1),
           tFormatTime->tm_mday, tFormatTime->tm_hour, tFormatTime->tm_min,
           tFormatTime->tm_sec);
    #endif // ((defined CFG_DEBUG_MSG) || (CFG_DEBUG_NTP))
    if(clock_settime(CLOCK_REALTIME, &ctspec) == TYP_ERROR)
    {
      #ifdef CFG_PRN_ERR
      printf("[NTP] NTP_PollingThrdFunc, set RTC clock fail, error %s\n",
             strerror(errno));
      #endif // CFG_PRN_ERR
    }

    // update current time to hardware BIOS system
    rstatus = SYS_UpdateHardwareRTC();
    if(rstatus != E_ERR_Success)
    {
      #if ((defined CFG_PRN_WARN) && (CFG_PRN_WARN_NTP))
      printf("WARN [NTP] NTP_PollingThrdFunc, update hardware bios RTC fail\n");
      #endif // ((defined CFG_PRN_WARN) && (CFG_PRN_WARN_NTP)
    }

  } // while(1)
  return TYP_NULL;
} // NTP_PollingThrdFunc
コード例 #27
0
// ****************************************************************
// TimerThreadMain()
//
void* FastResearchInterface::TimerThreadMain(void *ObjectPointer)
{
	int								OurChannelID	=	0
								,	ReceptionID		=	0;

	timer_t 						TimerID;

	struct sigevent 				Event;

	struct itimerspec 				Timer;

	struct _pulse  					PulseMsg;

	FastResearchInterface			*ThisObjectPtr		=	(FastResearchInterface*)ObjectPointer;

	OurChannelID				=	ChannelCreate(0); //create communication channel

	// Initialize event data structure
	// attach the timer to the channel OurChannelID
	Event.sigev_notify			=	SIGEV_PULSE;
	Event.sigev_coid			=	ConnectAttach(0, 0, OurChannelID, _NTO_SIDE_CHANNEL, 0);
	Event.sigev_priority		=	getprio(0);
	Event.sigev_code			=	TIMER_PULSE;

	timer_create(CLOCK_REALTIME, &Event, &TimerID);

	// Configure the timer
	Timer.it_value.tv_sec		=	0L;
	Timer.it_value.tv_nsec		=	(long int)(1000000000.0 * ThisObjectPtr->CycleTime);	// wait one cycle time interval before start
	Timer.it_interval.tv_sec	=	0L;
	Timer.it_interval.tv_nsec	=	(long int)(1000000000.0 * ThisObjectPtr->CycleTime);

	pthread_mutex_lock(&(ThisObjectPtr->MutexForThreadCreation));
	ThisObjectPtr->ThreadCreated	=	true;
	pthread_mutex_unlock(&(ThisObjectPtr->MutexForThreadCreation));

	pthread_cond_signal(&(ThisObjectPtr->CondVarForThreadCreation));

	// Start the timer
	timer_settime(TimerID, 0, &Timer, NULL);

	pthread_mutex_lock(&(ThisObjectPtr->MutexForCondVarForTimer));

	while(!(ThisObjectPtr->TerminateTimerThread))
	{
		pthread_mutex_unlock(&(ThisObjectPtr->MutexForCondVarForTimer));

		ReceptionID	= MsgReceive(OurChannelID, &PulseMsg, sizeof(PulseMsg), NULL);

		pthread_mutex_lock(&(ThisObjectPtr->MutexForCondVarForTimer));
		if (ReceptionID == 0)
		{
			ThisObjectPtr->TimerFlag = true;
			pthread_cond_signal(&(ThisObjectPtr->CondVarForTimer));
		}
	}
	pthread_mutex_unlock(&(ThisObjectPtr->MutexForCondVarForTimer));

	if (timer_delete(TimerID) != 0)
    {
		ThisObjectPtr->OutputConsole->printf("FastResearchInterface::TimerThreadMain(): ERROR, cannot delete timer...\n");
    }

	pthread_exit(NULL);
}
コード例 #28
0
//#define CFG_DEBUG_MSG
VOID *NTP_LinkManagementThrdFunc(VOID *pThreadParameter)
{
  E_ERR_T            rstatus = E_ERR_Success;
  INT32             chid;
  struct sigevent   event;
  struct itimerspec itime;
  timer_t           timer_id;
  INT32             rcvid;
  NTP_CH_MSG_T      msg;
  struct timespec   tspec;
  UINT8             uccnt;
  UINT8             ucservercnt;
  BOOL_T            isServerActive = E_TYPE_No;
  NTP_PACKET_T      tx_ntppack;
  NTP_PACKET_T      rx_ntppack;
  UINT8             ucntp_packet_sz;
  UINT8             unretrycnt;
  INT32             rlen;             // receive length


  struct mq_attr    mqstat;
  INT32             msglen;
  SYS_MSGQ_MCPR     msgq;
  struct msq_ctrl_st *pcb;
  NTP_MSGQ_MCP_STATUS ntpcstatus;

  #if ((defined CFG_PRN_WARN) && CFG_PRN_WARN_NTP)
  CHAR thrdnamebuff[SYS_THRD_NAME_LEN] = {0};
  CHAR acErrMsg[100] = {0};
  #endif // ((defined CFG_PRN_WARN) && CFG_PRN_WARN_NTP)

  #if (((defined CFG_PRN_WARN) && CFG_PRN_WARN_NTP) || (defined CFG_PRN_ERR))
  CHAR              errBuff[100] = {0};
  #endif // ((defined CFG_PRN_WARN) && CFG_PRN_WARN_NTP) ||
         //  (defined CFG_PRN_ERR))
  #if((defined CFG_DEBUG_MSG) && CFG_DEBUG_NTP)
  struct tm         *pbdtime;
  #endif // ((defined CFG_DEBUG_MSG) && CFG_DEBUG_NTP)

  if ((chid = ChannelCreate (0)) == TYP_ERROR)
  {
    #ifdef CFG_PRN_ERR
    printf("ERR  [NTP] NTP_LinkManagementThrdFunc, fail to create channel, %s\n",
            strerror(errno));
    #endif // CFG_PRN_ERR
    return (VOID *)E_ERR_InvalidNullPointer;
  }

  // set up the pulse
  event.sigev_notify = SIGEV_PULSE;
  event.sigev_coid =
    ConnectAttach(ND_LOCAL_NODE, 0, chid, _NTO_SIDE_CHANNEL, 0);
  event.sigev_priority = getprio(0);
  event.sigev_code = E_SYS_PULSE_NTPC_LinkMgmt;
  timer_create(CLOCK_REALTIME, &event, &timer_id);

  // set timer value
  // First trigger begin after 10 seconds, subsequent after 60 seconds
  itime.it_value.tv_sec = 15;
  itime.it_value.tv_nsec = 0;
  itime.it_interval.tv_sec = pNTP_CB->poll_frequency;
  itime.it_interval.tv_nsec = 0;
  timer_settime(timer_id, 0, &itime, NULL);

  // construct NTP request packet
  tx_ntppack.flags.allbits = 0xe3;
  tx_ntppack.peerClkStranum = TYP_NULL;
  tx_ntppack.peerPollingInterval = 0x4;
  tx_ntppack.peerClockPrecision = -6;
  tx_ntppack.rootDelay = NTP_Fp64ToFpst32(1.0000);
  tx_ntppack.rootDispersion = NTP_Fp64ToFpst32(1.0000);
  tx_ntppack.referenceClockID = TYP_NULL;
  tx_ntppack.referenceClockUpdateTime = NTP_Fp64ToFpst64(0.0000);
  tx_ntppack.originateTimeStamp = NTP_Fp64ToFpst64(0.0000);
  tx_ntppack.receiveTimeStamp = NTP_Fp64ToFpst64(0.0000);

  ucntp_packet_sz = sizeof(NTP_PACKET_T);

  // set all connection to false
  for(ucservercnt = 0; ucservercnt < CGF_NTP_TOTAL_SERVER; ucservercnt++)
  {
    pNTP_CB->server[ucservercnt].isConnectionGood = E_TYPE_No;
  }

  pcb = &pSYS_CB->msq_ctrl[E_SYS_MSQL_NTPC_TxExternalSystemMsg];

  if(pcb == TYP_NULL)
  {
    #ifdef CFG_PRN_WARN
    printf("ERR  [NTP] NTP_LinkManagementThrdFunc, pcb in null pointer\n");
    #endif // CFG_PRN_WARN
    return TYP_NULL;
  }

  // get message queue attribute
  mq_getattr(pcb->msq_id, &mqstat);
  msgq.msgtype = E_SYS_MCP_NTPClientToSWC;

	  while(1)

  {
    rcvid = MsgReceive (chid, &msg, sizeof (msg), NULL);
    if (rcvid < 0)
    {
      //gotAMessage (rcvid, &msg.msg);
      #ifdef CFG_PRN_ERR
      printf("ERR  [NTP] NTP_LinkManagementThrdFunc, error, %s\n",
             strerror(errno));
      #endif //CFG_PRN_ERR
    }

    if (rcvid > 0)
    {
      //gotAMessage (rcvid, &msg.msg);
      #if((defined CFG_DEBUG_MSG) && CFG_DEBUG_NTP)
      printf("[NTP] NTP_LinkManagementThrdFunc, currently not support message"
             "handling\n");
      #endif //((defined CFG_DEBUG_MSG) || (CFG_DEBUG_NTP))
    }

    if (msg.pulse.code != E_SYS_PULSE_NTPC_LinkMgmt)
    {
      #ifdef CFG_PRN_WARN
      printf("WARN [NTP] NTP_LinkManagementThrdFunc, unidentified pulse code"
             "%d\n", msg.pulse.code);
      #endif // CFG_PRN_WARN
      continue;
    }

    isServerActive = E_TYPE_No;
    for(uccnt = 0; uccnt < CGF_NTP_TOTAL_SERVER; uccnt++)
    {
      unretrycnt = 0;
      do{
        if(pNTP_CB->server[uccnt].nfd == TYP_ERROR)
        {
          rstatus = LNC_GetConnectFileDescriptor(
            (const CHAR *)pNTP_CB->server[uccnt].ipaddr,
            (const UINT16) NTP_SERVER_PORT, (const INT32) SOCK_DGRAM,
            NTP_GETFILEDESC_TIMEOUT,
            (INT32 *) &pNTP_CB->server[uccnt].nfd);

          if(rstatus != E_ERR_Success)
          {
            unretrycnt++;
            #if ((defined CFG_PRN_WARN) && CFG_PRN_WARN_NTP)
            ERR_GetMsgString(rstatus, acErrMsg);
            printf("WARN [NTP] NTP_LinkManagementThrdFunc, server %s is down\n"
                   "  retry %d/%d, error %s\n",
               pNTP_CB->server[uccnt].ipaddr, unretrycnt, pNTP_CB->connectRetry,
               acErrMsg);
            #endif // ((defined CFG_PRN_WARN) && CFG_PRN_WARN_NTP)
            continue;
          }

          pLNC_CB->endPointConfig[uccnt].nfd = pNTP_CB->server[uccnt].nfd;
        }


        unretrycnt++;

        #if ((defined CFG_DEBUG_MSG) && CFG_DEBUG_NTP)
        rstatus = SYS_GetCurrentTimeInString(&pbdtime, &tspec,
                                             E_SYS_TIME_Local);
        printf("[NTP] %d.%02d.%02d %02d:%02d:%02d.%03d "
               "NTP_LinkManagementThrdFunc,\n"
               "  server %s, fd %d, retry %d/%d\n",
               (pbdtime->tm_year + 1900), (pbdtime->tm_mon + 1),
               pbdtime->tm_mday, pbdtime->tm_hour, pbdtime->tm_min,
               pbdtime->tm_sec, tspec.tv_nsec/1000000,
               pLNC_CB->endPointConfig[uccnt].pipaddr,
               pNTP_CB->server[uccnt].nfd,
               unretrycnt, pNTP_CB->connectRetry);
        //SYS_PrnDataBlock((const UINT8 *) pbuff,const UINT32 prnsz,const UINT8 byteperrow)
        #endif // ((defined CFG_DEBUG_MSG) && (CFG_DEBUG_NTP))

        clock_gettime(CLOCK_REALTIME, &tspec);
        tx_ntppack.transmitTimeStamp =
         NTP_Fp64ToFpst64(tspec.tv_sec + NTP_JAN_1970 + 1.0e-9 * tspec.tv_nsec);

        rstatus = LNC_SendWithReply(pNTP_CB->server[uccnt].nfd,
                                    (const CHAR *)&tx_ntppack,
                                    ucntp_packet_sz,
                                    (VOID *)&rx_ntppack,
                                    ucntp_packet_sz, &rlen, 500);
        switch(rstatus)
        {
          case E_ERR_Success:
            break;

          case E_ERR_LNC_InvalidFileDescriptor:
          case E_ERR_LNC_SelectReadTimeOut:
          case E_ERR_LNC_FailToWriteSocket:
          case E_ERR_LNC_FailToConnectDatagramSocket:
            #if ((defined CFG_PRN_WARN) && CFG_PRN_WARN_NTP)
            ERR_GetMsgString(rstatus, acErrMsg);
            printf("WARN [NTP] NTP_LinkManagementThrdFunc, server %s is down\n"
                   "  fd %d, error %s\n",
               pNTP_CB->server[uccnt].ipaddr, pNTP_CB->server[uccnt].nfd,
               acErrMsg);
            #endif // ((defined CFG_PRN_WARN) && CFG_PRN_WARN_NTP)
            pNTP_CB->server[uccnt].isConnectionGood = E_TYPE_No;
            close(pNTP_CB->server[uccnt].nfd);
            pNTP_CB->server[uccnt].nfd = TYP_ERROR;
            rlen = 0;
            continue; // E_ERR_LNC_SelectReadTimeOut

          default:
            #if ((defined CFG_PRN_WARN) && CFG_PRN_WARN_NTP)
            ERR_GetMsgString(rstatus, errBuff);
            printf("WARN [NTP] NTP_LinkManagementThrdFunc, %s\n"
                   "  unhandled rstatus error %s\n",
                   SYS_GetDefaultThrdName(thrdnamebuff, sizeof(thrdnamebuff)),
                   errBuff);
            #endif // ((defined CFG_PRN_WARN) && CFG_PRN_WARN_NTP)
            continue;

        }

        if(rlen == ucntp_packet_sz)
        {
          pNTP_CB->server[uccnt].isConnectionGood = E_TYPE_Yes;
          #if ((defined CFG_DEBUG_MSG) && CFG_DEBUG_NTP)
          printf("[NTP] NTP_LinkManagementThrdFunc, fd %d server %s is good\n",
                 pNTP_CB->server[uccnt].nfd,
                 pNTP_CB->server[uccnt].ipaddr);
          #endif // ((defined CFG_DEBUG_MSG) && (CFG_DEBUG_NTP))

          // 20100928 BC
          // set active server according to priority
          for(ucservercnt = 0; ucservercnt < CGF_NTP_TOTAL_SERVER;
              ucservercnt++)
          {
            if(pNTP_CB->server[ucservercnt].isConnectionGood == E_TYPE_No)
              continue;

            if(pNTP_CB->pactiveserver == &pNTP_CB->server[ucservercnt])
            {
              isServerActive = E_TYPE_Yes;
              break;
            }

            pNTP_CB->pactiveserver = &pNTP_CB->server[ucservercnt];
            #if ((defined CFG_DEBUG_MSG) && CFG_DEBUG_NTP)
            printf("[NTP] NTP_LinkManagementThrdFunc, fd %d server %s is set "
                   "to active\n",
                   pNTP_CB->server[uccnt].nfd,
                   pNTP_CB->pactiveserver->ipaddr);
            #endif // ((defined CFG_DEBUG_MSG) && (CFG_DEBUG_NTP))
            isServerActive = E_TYPE_Yes;
            break;
          }

          // set timer value to start NTP polling thread
          itime.it_value.tv_sec = 1;
          itime.it_value.tv_nsec = 0;
          itime.it_interval.tv_sec = pNTP_CB->poll_frequency;
          itime.it_interval.tv_nsec = 0;
          timer_settime(pNTP_CB->polling_timer_id, 0, &itime, NULL);
          rlen = 0;
          break;
        }else{
          #if ((defined CFG_DEBUG_MSG) && CFG_DEBUG_NTP)
          printf("WARN [NTP] NTP_LinkManagementThrdFunc, invalid rx length, "
               "%d from server %s\n",
               rlen, pNTP_CB->server[uccnt].ipaddr);
          #endif // CFG_PRN_WARN_NTP
          continue;
        }
      }while(unretrycnt < pNTP_CB->connectRetry);

      if(unretrycnt >= pNTP_CB->connectRetry)
      {
        if((pNTP_CB->server[uccnt].ipaddr[0] != 0) &&
           (pNTP_CB->server[uccnt].nfd > 0))
        {
          close(pNTP_CB->server[uccnt].nfd);
          pNTP_CB->server[uccnt].nfd = TYP_ERROR;
          #if ((defined CFG_DEBUG_MSG) && CFG_DEBUG_NTP)
          printf("[NTP] NTP_LinkManagementThrdFunc, reset fd[%d] to TYP_ERROR\n",
                 uccnt);
          #endif // ((defined CFG_DEBUG_MSG) && (CFG_DEBUG_NTP))
        }
      }
    } // for(uncnt = 0; uncnt < NTP_TOTAL_SERVER; uncnt++)

    // active server status
    if(isServerActive == E_TYPE_No)
    {
      #if ((defined CFG_DEBUG_MSG) && CFG_DEBUG_NTP)
      printf("[NTP] NTP_LinkManagementThrdFunc, set active server to "
             "TYP_NULL\n");
      #endif // ((defined CFG_DEBUG_MSG) && CFG_DEBUG_NTP))
      pNTP_CB->pactiveserver = TYP_NULL;
    }

    // pack NTP client status information
    rstatus = ntp_McpGetStatus(&ntpcstatus, sizeof(NTP_MSGQ_MCP_STATUS));
    if(rstatus != E_ERR_Success)
    {
      #ifdef CFG_PRN_ERR
      ERR_GetMsgString(rstatus, errBuff);
      printf("ERR  [NTP] NTP_LinkManagementThrdFunc, ntp_McpGetStatus "
             "error, %s\n", errBuff);
      #endif // CFG_PRN_ERR
      #if (((defined CFG_PRN_WARN) && CFG_PRN_WARN_NTP) || \
            (defined CFG_PRN_ERR))
      memset(errBuff, 0, sizeof(errBuff));
      #endif  // (((defined CFG_PRN_WARN) && CFG_PRN_WARN_NTP) ||
              //  (defined CFG_PRN_ERR))
    }

    memcpy(msgq.msgbuff, &ntpcstatus, sizeof(NTP_MSGQ_MCP_STATUS));
    msgq.msgsz = sizeof(NTP_MSGQ_MCP_STATUS);

    #if ((defined CFG_DEBUG_MSG) && CFG_DEBUG_NTP_TXRESP)
    printf("[NTP] NTP_LinkManagementThrdFunc, send message queue %d "
           "bytes:\n", sizeof(SYS_MSGQ_MCPR));
    SYS_PrnDataBlock((const UINT8 *) &msgq, sizeof(SYS_MSGQ_MCPR), 20);
    #endif // ((defined CFG_DEBUG_MSG) && CFG_DEBUG_NTP))

    // Send result to serial link using message queue
    msglen = mq_send(
      pSYS_CB->msq_ctrl[E_SYS_MSQL_NTPC_TxExternalSystemMsg].msq_id,
      (CHAR *)&msgq, sizeof(SYS_MSGQ_MCPR), SYS_MSQ_PRIOR_NORMAL);

    #if ((defined CFG_DEBUG_MSG) && (CFG_DEBUG_NTP))
    printf("[NTP] NTP_LinkManagementThrdFunc, tx message queue %s\n",
           (msglen == 0 ? "OK" : "ERROR"));
    #endif // ((defined CFG_DEBUG_MSG) && CFG_DEBUG_NTP))
    memset(&msgq, 0, sizeof(SYS_MSGQ_MCPR));

    if(pNTP_CB->pactiveserver == TYP_NULL)
    {
      #if ((defined CFG_DEBUG_MSG) && CFG_DEBUG_NTP)
      printf("[NTP] NTP_LinkManagementThrdFunc, set polling time to %d secs\n",
             pCGF_CB->ntp.linkDownRetryFreq);
      #endif // ((defined CFG_DEBUG_MSG) && CFG_DEBUG_NTP))
      itime.it_value.tv_sec = pCGF_CB->ntp.linkDownRetryFreq;
      itime.it_value.tv_nsec = 0;
      itime.it_interval.tv_sec = pCGF_CB->ntp.linkDownRetryFreq;
      itime.it_interval.tv_nsec = 0;
    }else{
      #if ((defined CFG_DEBUG_MSG) && CFG_DEBUG_NTP)
      printf("[NTP] NTP_LinkManagementThrdFunc, set polling time to %d secs\n",
             pNTP_CB->poll_frequency);
      #endif // ((defined CFG_DEBUG_MSG) && CFG_DEBUG_NTP))
      itime.it_value.tv_sec = pNTP_CB->poll_frequency;
      itime.it_value.tv_nsec = 1;
      itime.it_interval.tv_sec = pNTP_CB->poll_frequency;
      itime.it_interval.tv_nsec = 0;
    }
    timer_settime(timer_id, 0, &itime, NULL);

  }// while(1)

} // NTP_LinkManagementThrdFunc