Exemplo n.º 1
0
/*!
 * Registered 'arch' handler for timer interrupts;
 * update system time and forward interrupt to kernel if its timer is expired
 */
static void arch_timer_handler ()
{
	void (*k_handler) ();

	time_add ( &clock, &last_load );

	time_sub ( &delay, &last_load );
	last_load = timer->max_interval;

	if ( time_cmp ( &delay, &threshold ) <= 0 )
	{
		delay = timer->max_interval;
		timer->set_interval ( &last_load );

		k_handler = alarm_handler;
		alarm_handler = NULL; /* reset kernel callback function */

		if ( k_handler )
			k_handler (); /* forward interrupt to kernel */
	}
	else {
		if ( time_cmp ( &delay, &last_load ) < 0 )
			last_load = delay;

		timer->set_interval ( &last_load );
	}
}
Exemplo n.º 2
0
void handle_recv_event(pings_params *pings)
{
    struct timeval current_time =  {0};
    int is_recv_packet;

    is_recv_packet = recv_packets(pings);

    if(pings->recv_error){
        return;
    }

    if(PINGS_TRUE == is_recv_packet){
        gettimeofday(&(pings->recv_last_packet_time), NULL);
        pings->recv_interval = 0.0;
    }
    else{
        gettimeofday(&current_time, NULL);
        pings->recv_interval = time_sub(&current_time, &(pings->recv_last_packet_time));
    }

    if(pings->resend_num < PINGS_RESEND_NUMBER){
        pings->event.events = EPOLLOUT | EPOLLET;
        epoll_ctl(pings->epoll_fd, EPOLL_CTL_MOD, pings->sock_fd, &(pings->event));
    }
    else{
        pings->event.events = EPOLLIN | EPOLLET;
        epoll_ctl(pings->epoll_fd, EPOLL_CTL_MOD, pings->sock_fd, &(pings->event));
    }
}
Exemplo n.º 3
0
/*! Cancel sleep
 *  - handle return values and errno;
 *  - thread must be handled elsewhere - with source of interrupt (signal?)
 */
static void kclock_interrupt_sleep ( kthread_t *kthread, void *param )
{
	ktimer_t *ktimer;
	timespec_t *remain;
	itimerspec_t irem;

	ASSERT ( kthread && param );
	ASSERT ( kthread_check_kthread ( kthread ) ); /* is this valid thread */
	ASSERT ( kthread_is_suspended ( kthread, NULL, NULL ) );

	ktimer = param;
	remain = ktimer->param;

	if ( remain )
	{
		/* save remaining time */
		timespec_t now;
		kclock_gettime ( CLOCK_REALTIME, &now );
		ktimer_gettime ( ktimer, &irem );
		*remain = irem.it_value;
		time_sub ( remain, &now );
	}

	ktimer_delete (ktimer);

	kthread_set_syscall_retval ( kthread, EXIT_FAILURE );
	kthread_set_errno ( kthread, EINTR );
}
Exemplo n.º 4
0
/*!
 * Deactivate thread because:
 * 1. higher priority thread becomes active
 * 2. this thread time slice is expired
 * 3. this thread blocks on some queue
 */
static int rr_thread_deactivate ( kthread_t *kthread )
{
	/* Get current time and recalculate remainder */
	time_t t;
	kthread_sched_data_t *tsched = kthread_get_sched_param ( kthread );
	ksched_t *gsched = ksched_get ( tsched->sched_policy );

	if (tsched->params.rr.remainder.sec + tsched->params.rr.remainder.nsec)
	{
		/*
		 * "slice interrupted"
		 * recalculate remainder
		 */
		k_get_time ( &t );
		time_sub ( &tsched->params.rr.slice_end, &t );
		tsched->params.rr.remainder = tsched->params.rr.slice_end;

		if ( kthread_is_ready ( kthread ) )
		{
			/* is remainder too small or not? */
			if ( time_cmp ( &tsched->params.rr.remainder,
				&gsched->params.rr.threshold ) <= 0 )
			{
				kthread_move_to_ready ( kthread, LAST );
			}
			else {
				kthread_move_to_ready ( kthread, FIRST );
			}
		}
	}
	/* else = remainder is zero, thread is already enqueued in ready queue*/

	return 0;
}
Exemplo n.º 5
0
int unpack(char *buf, int len, float *rtt, pid_t pid)
{
    int iphdrlen;
    struct ip *ip;
    struct icmp *icmp;
    struct timeval *time_sent;
    struct timeval time_recv;

    ip = (struct ip *)buf;
    iphdrlen = ip->ip_hl << 2;
    icmp = (struct icmp *)(buf + iphdrlen);
    len -= iphdrlen;

    if(len < PINGS_ICMP_HEADER_SIZE){
        return PINGS_FAILED;
    }

    if((icmp->icmp_type == ICMP_ECHOREPLY) && (ntohs(icmp->icmp_id) == pid)){

        gettimeofday(&time_recv, NULL);
        time_sent = (struct timeval *)icmp->icmp_data;
        *rtt = time_sub(&time_recv,time_sent);

        return PINGS_SUCCESS;
    }

    return PINGS_FAILED;
}
Exemplo n.º 6
0
int main(int argc, char *argv[])
{
    struct timespec start, curr;
    struct timers timers;
    struct list_head expired;
    struct timer t[PER_CONN_TIME];
    unsigned int i, num;
    bool check = false;

    opt_register_noarg("-c|--check", opt_set_bool, &check,
                       "Check timer structure during progress");

    opt_parse(&argc, argv, opt_log_stderr_exit);

    num = argv[1] ? atoi(argv[1]) : (check ? 100000 : 100000000);

    list_head_init(&expired);
    curr = start = time_now();
    timers_init(&timers, start);

    for (i = 0; i < num; i++) {
        curr = time_add(curr, time_from_msec(1));
        if (check)
            timers_check(&timers, NULL);
        timers_expire(&timers, curr, &expired);
        if (check)
            timers_check(&timers, NULL);
        assert(list_empty(&expired));

        if (i >= PER_CONN_TIME) {
            timer_del(&timers, &t[i%PER_CONN_TIME]);
            if (check)
                timers_check(&timers, NULL);
        }
        timer_add(&timers, &t[i%PER_CONN_TIME],
                  time_add(curr, time_from_msec(CONN_TIMEOUT_MS)));
        if (check)
            timers_check(&timers, NULL);
    }
    if (num > PER_CONN_TIME) {
        for (i = 0; i < PER_CONN_TIME; i++)
            timer_del(&timers, &t[i]);
    }

    curr = time_sub(time_now(), start);
    if (check)
        timers_check(&timers, NULL);
    timers_cleanup(&timers);
    opt_free_table();

    for (i = 0; i < ARRAY_SIZE(timers.level); i++)
        if (!timers.level[i])
            break;

    printf("%u in %lu.%09lu (%u levels / %zu)\n",
           num, (long)curr.tv_sec, curr.tv_nsec,
           i, ARRAY_SIZE(timers.level));
    return 0;
}
Exemplo n.º 7
0
static void alarm ()
{
	timespec_t t;

	clock_gettime ( CLOCK_REALTIME, &t );
	time_sub ( &t, &t0 );

	printf ( "[%d:%d] Alarm! \n", t.tv_sec, t.tv_nsec/100000000 );
}
Exemplo n.º 8
0
/*!
 * Get 'current' system time
 * \param time Store address for current time
 */
void arch_get_time ( time_t *time )
{
	time_t remainder;

	timer->get_interval_remainder ( &remainder );

	*time = last_load;
	time_sub ( time, &remainder );
	time_add ( time, &clock );
}
Exemplo n.º 9
0
/* time t is wall clock time, convert to time compatible
 * with our clock_gettime clock */
time_t unwall_ts(time_t t)
{
	struct timespec booth_clk_now, now_tv, res;
	struct timeval now;

	get_time(&booth_clk_now);
	gettimeofday(&now, NULL);
	TIMEVAL_TO_TIMESPEC(&now, &now_tv);
	time_sub(&now_tv, &booth_clk_now, &res);
	return t - res.tv_sec;
}
Exemplo n.º 10
0
/*! Iterate through active alarms and activate newly expired ones */
static void k_schedule_alarms ()
{
	kalarm_t *first;
	time_t time, ref_time;

	arch_get_time ( &time );
	ref_time = time;
	time_add ( &ref_time, &threshold );

	/* should any alarm be activated? */
	first = list_get ( &kalarms, FIRST );
	while ( first != NULL )
	{
		if ( time_cmp ( &first->alarm.exp_time, &ref_time ) <= 0 )
		{
			/* 'activate' alarm */

			/* but first remove alarm from list */
			first = list_remove ( &kalarms, FIRST, NULL );

			if ( first->alarm.flags & ALARM_PERIODIC )
			{
				/* calculate next activation time */
				time_add ( &first->alarm.exp_time,
					   &first->alarm.period );
				/* put back into list */
				list_sort_add ( &kalarms, first, &first->list,
						alarm_cmp );
			}
			else {
				first->active = 0;
			}

			if ( first->alarm.action ) /* activate alarm */
				first->alarm.action ( first->alarm.param );

			first = list_get ( &kalarms, FIRST );
		}
		else {
			break;
		}
	}

	first = list_get ( &kalarms, FIRST );
	if ( first )
	{
		ref_time = first->alarm.exp_time;
		time_sub ( &ref_time, &time );
		arch_timer_set ( &ref_time, k_timer_interrupt );
	}
}
Exemplo n.º 11
0
static void profile_end(const char *f, int line)
{
	struct timeval profile_time_end;
	long d;

	gettimeofday(&profile_time_end, NULL);
	d = time_sub(&profile_time_end, &profile_time_start);

	if (profile_tty)
		fprintf(stderr, "\33[01;31mRESULT %s \33[35m%ld\33[0m (%d)\n", f, d,
			line);
	fprintf(fd, "%s %ld\n", f, d);
	fflush(fd);
} /* profile_end */
Exemplo n.º 12
0
/*!
 * Get timer expiration time
 * \param ktimer	Timer
 * \param value		Where to store time to next timer expiration (+period)
 * \return status	0 for success
 */
int ktimer_gettime ( ktimer_t *ktimer, itimerspec_t *value )
{
	ASSERT( ktimer && value );
	timespec_t now;

	kclock_gettime ( ktimer->clockid, &now );

	*value = ktimer->itimer;

	/* return relative time to timer expiration */
	if ( TIME_IS_SET ( &value->it_value ) )
		time_sub ( &value->it_value, &now );

	return EXIT_SUCCESS;
}
Exemplo n.º 13
0
/*
 * update the packet (num and size) counters
 * and get the time diff to calculate the 
 * rate
 */
void stats_half_end(struct half_stats *hs, u_int len)
{
   struct timeval diff;
   float ttime;
   float ptime;

   /* get the time */
   gettimeofday(&hs->te, 0);

   time_sub(&hs->te, &hs->ts, &diff);
   time_add(&hs->ttot, &diff, &hs->ttot);
   time_add(&hs->tpar, &diff, &hs->tpar);

   /* calculate the rate (packet/time) */
   ttime = hs->ttot.tv_sec + hs->ttot.tv_usec/1.0e6;
   ptime = hs->tpar.tv_sec + hs->tpar.tv_usec/1.0e6;

   /* update the packet count */
   hs->pck_recv++;
   hs->pck_size += len;
   hs->tmp_size += len;
   
   if ( (hs->pck_recv % GBL_CONF->sampling_rate) == 0 ) {
      /* save the average and the worst sampling */
      hs->rate_adv = hs->pck_recv/ttime;
      if (hs->rate_worst > GBL_CONF->sampling_rate/ptime || hs->rate_worst == 0)
         hs->rate_worst = GBL_CONF->sampling_rate/ptime;
      
      hs->thru_adv = hs->pck_size/ttime;
      if (hs->thru_worst > hs->tmp_size/ptime || hs->thru_worst == 0)
         hs->thru_worst = hs->tmp_size/ptime;

#if 0
      DEBUG_MSG("PACKET RATE: %llu [%d] [%d] -- [%d] [%d]\n", hs->pck_recv,
         hs->rate_worst, hs->rate_adv,
         hs->thru_worst, hs->thru_adv);
#endif
            
      /* reset the partial */
      memset(&hs->tpar, 0, sizeof(struct timeval));
      hs->tmp_size = 0;
   }

}
Exemplo n.º 14
0
/*!
 * Set next timer activation
 * \param time Time of next activation
 * \param alarm_func Function to call upon timer expiration
 */
void arch_timer_set ( time_t *time, void *alarm_func )
{
	time_t remainder;

	timer->get_interval_remainder ( &remainder );
	time_sub ( &last_load, &remainder );
	time_add ( &clock, &last_load );

	delay = *time;
	if ( time_cmp ( &delay, &timer->min_interval ) < 0 )
		delay = timer->min_interval;

	alarm_handler = alarm_func;

	if ( time_cmp ( &delay, &timer->max_interval ) > 0 )
		last_load = timer->max_interval;
	else
		last_load = delay;

	timer->set_interval ( &last_load );
}
Exemplo n.º 15
0
/*!
 * Arm/disarm timer
 * \param ktimer	Timer
 * \param flags		Various flags
 * \param value		Set timer values (it_value+it_period)
 * \param ovalue	Where to store time to next timer expiration (+period)
 * \return status	0 for success
 */
int ktimer_settime ( ktimer_t *ktimer, int flags, itimerspec_t *value,
		     itimerspec_t *ovalue )
{
	timespec_t now;

	ASSERT ( ktimer );

	kclock_gettime ( ktimer->clockid, &now );

	if ( ovalue )
	{
		*ovalue = ktimer->itimer;

		/* return relative time to timer expiration */
		if ( TIME_IS_SET ( &ovalue->it_value ) )
			time_sub ( &ovalue->it_value, &now );
	}

	/* first disarm timer, if it was armed */
	if ( TIMER_IS_ARMED ( ktimer ) )
	{
		TIMER_DISARM ( ktimer );
		list_remove ( &ktimers, 0, &ktimer->list );
	}

	if ( value && TIME_IS_SET ( &value->it_value ) )
	{
		/* arm timer */
		ktimer->itimer = *value;
		if ( !(flags & TIMER_ABSTIME) ) /* convert to absolute time */
			time_add ( &ktimer->itimer.it_value, &now );

		list_sort_add ( &ktimers, ktimer, &ktimer->list, ktimer_cmp );
	}

	ktimer_schedule ();

	return EXIT_SUCCESS;
}
Exemplo n.º 16
0
// returns 1 if child exited, else 0
static int wait_for_child_gone() {
  struct timeval beg_time = time_now();
  struct timeval sleep_time = {0, 1000};
  int status;
  int timeout = 0;
  while(!timeout) {
    pid_t pid = gdb_pid();
    pid_t wpid = waitpid(pid, &status, WNOHANG);
    if(wpid == pid) // child done
      break;

    // wait a little
    time_sleep(&sleep_time);
    struct timeval now_time = time_now();
    struct timeval wait_time = time_sub(&now_time, &beg_time);
    if(time_greater(&wait_time, &wait_timeout))
      timeout = 1;
  }
  if(timeout)
    return 0;
  return 1;
}
Exemplo n.º 17
0
/* ********************************************************************   */
int sntp_process_result(int socket_no, PNTP_TIME_FORMAT current_timestamp,
                        int version, dword ticks_when_sent,
                        PEBSTIME res_ebs_tod)

{
int             n_received;
NTP_PKT         ntp_response;
NTP_TIME_FORMAT temp_time1;
NTP_TIME_FORMAT temp_time2;
NTP_TIME_FORMAT t1;
NTP_TIME_FORMAT t2;
NTP_TIME_FORMAT t3;
NTP_TIME_FORMAT t4;
NTP_TIME_FORMAT local_offset;
NTP_TIME_FORMAT delay_time;         /* round trip delay */
#if (DELAY_TICKS)
dword           delay_ticks;
dword           curr_ticks;
#endif
RTIP_BOOLEAN    gmt_neg;

#if (DELAY_TICKS)
    curr_ticks = ks_get_ticks();
    if (CHECK_GREATER(curr_ticks, ticks_when_sent))
        delay_ticks = curr_ticks - ticks_when_sent;
    else
        delay_ticks = (int)( (long)((long)curr_ticks - 
                             (long)ticks_when_sent) );

#if (DEBUG_DELAY_TICKS)
    DEBUG_ERROR("ks_get_ticks, ticks_when_sent: ", DINT2,
        curr_ticks, ticks_when_sent);
#endif
#endif

    /* Get a packet   */
    n_received = recv(socket_no, (PFCHAR)&ntp_response, 
                      sizeof(ntp_response), 0);
    if (n_received < 0)
    {
        DEBUG_ERROR("sntp_process_result: recv failed", EBS_INT1, 
            xn_getlasterror(), 0);
    }

    closesocket(socket_no);

    /* verify response - mode   */
    if ( ((ntp_response.li_vn_mode & NTP_MODE_MASK) != NTP_SYM_PASSIVE) &&
         ((ntp_response.li_vn_mode & NTP_MODE_MASK) != NTP_RESPONSE) )
    {
        DEBUG_ERROR("sntp_process_result: response invalid: exp, act", 
            EBS_INT2, 
            NTP_SYM_PASSIVE, ntp_response.li_vn_mode & NTP_MODE_MASK);
        return(-1);
    }

    /* verify response - stratum   */
    if ( (ntp_response.stratum < 1) || (ntp_response.stratum > 14) )
    {
        DEBUG_ERROR("sntp_process_result: stratum invalid: ", EBS_INT1,
            ntp_response.stratum, 0);
        return(-1);
    }

    /* verify response - version   */
    if ( (ntp_response.li_vn_mode & NTP_VERSION_MASK) != version )
    {
        DEBUG_ERROR("sntp_process_result: response invalid - version : exp, act", 
            EBS_INT2, version, 
            ntp_response.li_vn_mode & NTP_VERSION_MASK);
        return(-1);
    }

    ntp_response.rcv_timestamp.seconds = 
        net2hl(ntp_response.rcv_timestamp.seconds);

    ntp_response.ref_timestamp.seconds = 
        net2hl(ntp_response.ref_timestamp.seconds);

    ntp_response.transmit_timestamp.seconds = 
        net2hl(ntp_response.transmit_timestamp.seconds);

    /* seconds since Jan 1, 1970                  */
/*  DEBUG_ERROR("TIME SECONDS: seconds: ", DINT2, */
/*      ntp_response.rcv_timestamp.seconds,       */
/*      ntp_response.rcv_timestamp.frac_sec);     */

#if (DISPLAY_RCV_TIME)
    DEBUG_ERROR("\n***** RCV TIME *****", NOVAR, 0, 0);
    display_sntp_time(ntp_response.rcv_timestamp.seconds);
#endif

#if (DISPLAY_INT_TIMES)
/*  DEBUG_ERROR("***** REF TIME *****", NOVAR, 0, 0);      */
/*  display_sntp_time(ntp_response.ref_timestamp.seconds); */


/*  DEBUG_ERROR("***** TRANSMIT TIME *****", NOVAR, 0, 0);      */
/*  display_sntp_time(ntp_response.transmit_timestamp.seconds); */
#endif

#if (DELAY_TICKS)
    t4.seconds = delay_ticks / ks_ticks_p_sec();
    t4.frac_sec = 0;    /* tbd */
    DEBUG_ERROR("delay_ticks, t4.sec", DINT2, delay_ticks, t4.seconds);
#endif

    /* set the following                    */
    /* t2 = time request received by server */
    /* t3 = time reply sent by server       */
    /* t4 = time reply received by client   */
    STRUCT_COPY(t1, *current_timestamp); 
    STRUCT_COPY(t2, ntp_response.rcv_timestamp);
    STRUCT_COPY(t3, ntp_response.transmit_timestamp);
#if (!DELAY_TICKS)
    STRUCT_COPY(t4, *current_timestamp);
#endif

    /* set time response took to arrive from time sent   */
    /* delay_time = (t4-t1) - (t2-t3)                    */
    time_sub(&temp_time1, &t4, &t1);
    time_sub(&temp_time2, &t2, &t3);
    time_sub(&delay_time, &temp_time1, &temp_time2);

    /* calculate local time offset   */
    /* local clock offset            */
    time_sub(&temp_time1, &t2, &t1);
    time_sub(&temp_time2, &t3, &t4);
    time_add(&local_offset, &temp_time1, &temp_time2);
    time_div_2(&local_offset);

#if (DISPLAY_DELAY_OFFSET)
    display_total_time("\nDELAY TIME: ", delay_time.seconds);
    display_total_time("OFFSET TIME: ",  local_offset.seconds);
#endif

    gmt_neg = FALSE;
#if (!ADD_OFFSET)
    if (CFG_GMT_DIFF < 0)
    {
        gmt_neg = TRUE;
        /* convert hours to seconds, hence multiply by 3600;   */
        /* make it positive and it will be subtracted below    */
        local_offset.seconds = -(CFG_GMT_DIFF * SEC_PER_HOUR);
    }
    else
    {
        /* CFG_GMT_DIFF is positive so seconds is always positive   */
        local_offset.seconds = (dword)(CFG_GMT_DIFF * SEC_PER_HOUR);
    }
#endif
    local_offset.frac_sec = 0;

    /* update time with delay   */
    time_add(&temp_time1, &t3, &delay_time);

    /* save current time for next request   */
    STRUCT_COPY(*current_timestamp, temp_time1); 

    /* update time with time zone   */
    if (gmt_neg)
        time_sub(&temp_time2, &temp_time1, &local_offset);
    else
        time_add(&temp_time2, &temp_time1, &local_offset);


/*  display_total_time("BEFORE CONVERSION TO ebs_tod ", temp_time2.seconds);   */
/*  display_total_time("FINAL TIME ", temp_time2.seconds);                     */

    /* convert time returned by SNTP server to RTIP internal format   */
    convert_time_to_ebs_time(temp_time2.seconds, res_ebs_tod);

    return(0);
}
Exemplo n.º 18
0
/*! Activate timers and reschedule threads if required */
static void ktimer_schedule ()
{
	ktimer_t *first;
	timespec_t time, ref_time;
	int resched = 0;

	kclock_gettime ( CLOCK_REALTIME, &time );
	/* should have separate "scheduler" for each clock */

	ref_time = time;
	time_add ( &ref_time, &threshold );
	/* use "ref_time" instead of "time" when looking timers to activate */

	/* should any timer be activated? */
	first = list_get ( &ktimers, FIRST );
	while ( first != NULL )
	{
		/* timers have absolute values in 'it_value' */
		if ( time_cmp ( &first->itimer.it_value, &ref_time ) <= 0 )
		{
			/* 'activate' timer */

			/* but first remove timer from list */
			first = list_remove ( &ktimers, FIRST, NULL );

			/* and add to list if period is given */
			if ( TIME_IS_SET ( &first->itimer.it_interval) )
			{
				/* calculate next activation time */
				time_add ( &first->itimer.it_value,
					   &first->itimer.it_interval );
				/* put back into list */
				list_sort_add ( &ktimers, first,
						&first->list, ktimer_cmp );
			}
			else {
				TIMER_DISARM ( first );
			}

			if ( first->owner == NULL )
			{
				/* timer set by kernel - call now, directly */
				if ( first->evp.sigev_notify_function )
					first->evp.sigev_notify_function (
						first->evp.sigev_value
					);
			}
			else {
				/* timer set by thread */
				if ( !ksignal_process_event (
					&first->evp, first->owner, SI_TIMER ) )
				{
					resched++;
				}
			}

			first = list_get ( &ktimers, FIRST );
		}
		else {
			break;
		}
	}

	first = list_get ( &ktimers, FIRST );
	if ( first )
	{
		ref_time = first->itimer.it_value;
		time_sub ( &ref_time, &time );
		arch_timer_set ( &ref_time, ktimer_schedule );
	}

	if ( resched )
		kthreads_schedule ();
}
Exemplo n.º 19
0
void mainloop_run (void) {
	
	fd_set *rfds, *wfds, *efds;
	int res;
	struct timeval _tv;
	struct os_time tv, now;

	rfds = malloc(sizeof(*rfds));
	wfds = malloc(sizeof(*wfds));
	efds = malloc(sizeof(*efds));


	if (verbose) printf("running main loop\n");

	if (rfds == NULL || wfds == NULL || efds == NULL) {
		printf("mainloop_run - malloc failed\n");
		goto out;
	}

	while (!mainloop.terminate &&
	       (mainloop.timeout || mainloop.readers.count > 0 ||
		mainloop.writers.count > 0 || mainloop.exceptions.count > 0)) {
		if (mainloop.timeout) {
			os_get_time(&now);
			if (time_before(&now, &mainloop.timeout->time))
				time_sub(&mainloop.timeout->time, &now, &tv);
			else
				tv.sec = tv.usec = 0;
#if 0
			printf("next timeout in %lu.%06lu sec\n",
			       tv.sec, tv.usec);
#endif
			_tv.tv_sec = tv.sec;
			_tv.tv_usec = tv.usec;
		}

		mainloop_sock_table_set_fds(&mainloop.readers, rfds);
		mainloop_sock_table_set_fds(&mainloop.writers, wfds);
		mainloop_sock_table_set_fds(&mainloop.exceptions, efds);
		res = select(mainloop.max_sock + 1, rfds, wfds, efds,
			     mainloop.timeout ? &_tv : NULL);
		if (res < 0 && errno != EINTR && errno != 0) {
			perror("select");
			goto out;
		}
		mainloop_process_pending_signals();

		/* check if some registered timeouts have occurred */
		if (mainloop.timeout) {
			struct mainloop_timeout *tmp;

			os_get_time(&now);
			if (!time_before(&now, &mainloop.timeout->time)) {
				tmp = mainloop.timeout;
				mainloop.timeout = mainloop.timeout->next;
				tmp->handler(tmp->mainloop_data,
					     tmp->user_data);
				free(tmp);
			}

		}

		if (res <= 0)
			continue;

		mainloop_sock_table_dispatch(&mainloop.readers, rfds);
		mainloop_sock_table_dispatch(&mainloop.writers, wfds);
		mainloop_sock_table_dispatch(&mainloop.exceptions, efds);
	}

out:
	free(rfds);
	free(wfds);
	free(efds);
}
/**
 * @brief Called by the Client to get the reponse from the server or vice-versa.
 *
 * Reads the message from the file \c filedes.
 *
 * @param[in] command one of the \ref pcsc_msg_commands commands
 * @param[out] buffer_void Message read.
 * @param[in] buffer_size Size to read
 * @param[in] filedes Socket handle.
 * @param[in] timeOut Timeout in milliseconds.
 *
 * @retval SCARD_S_SUCCESS Success.
 * @retval SCARD_E_TIMEOUT Timeout.
 * @retval SCARD_F_COMM_ERROR Socket is closed.
 * @retval SCARD_F_COMM_ERROR A signal was received.
 */
INTERNAL LONG MessageReceiveTimeout(uint32_t command, void *buffer_void,
	uint64_t buffer_size, int32_t filedes, long timeOut)
{
	char *buffer = buffer_void;

	/* default is success */
	LONG retval = SCARD_S_SUCCESS;

	/* record the time when we started */
	struct timeval start;

	/* how many bytes we must read */
	size_t remaining = buffer_size;

	gettimeofday(&start, NULL);

	/* repeat until we get the whole message */
	while (remaining > 0)
	{
		fd_set read_fd;
		struct timeval timeout, now;
		int selret;
		long delta;

		gettimeofday(&now, NULL);
		delta = time_sub(&now, &start);

		if (delta > timeOut*1000)
		{
			/* we already timed out */
			retval = SCARD_E_TIMEOUT;
			break;
		}

		/* remaining time to wait */
		delta = timeOut*1000 - delta;

		FD_ZERO(&read_fd);
		FD_SET(filedes, &read_fd);

		timeout.tv_sec = delta/1000000;
		timeout.tv_usec = delta - timeout.tv_sec*1000000;

		selret = select(filedes + 1, &read_fd, NULL, NULL, &timeout);

		/* try to read only when socket is readable */
		if (selret > 0)
		{
			int readed;

			if (!FD_ISSET(filedes, &read_fd))
			{
				/* very strange situation. it should be an assert really */
				retval = SCARD_F_COMM_ERROR;
				break;
			}
			readed = read(filedes, buffer, remaining);

			if (readed > 0)
			{
				/* we got something */
				buffer += readed;
				remaining -= readed;
			} else if (readed == 0)
			{
				/* peer closed the socket */
				retval = SCARD_F_COMM_ERROR;
				break;
			} else
			{
				/* we ignore the signals and empty socket situations, all
				 * other errors are fatal */
				if (errno != EINTR && errno != EAGAIN)
				{
					retval = SCARD_F_COMM_ERROR;
					break;
				}
			}
		} else if (selret == 0)
		{
			/* is the daemon still there? */
			retval  =  SCardCheckDaemonAvailability();
			if (retval != SCARD_S_SUCCESS)
			{
				/* timeout */
				break;
			}

			/* you need to set the env variable PCSCLITE_DEBUG=0 since
			 * this is logged on the client side and not on the pcscd
			 * side*/
#ifdef NO_LOG
			(void)command;
#endif
			Log2(PCSC_LOG_INFO, "Command 0x%X not yet finished", command);
		} else
		{
			/* we ignore signals, all other errors are fatal */
			if (errno != EINTR)
			{
				Log2(PCSC_LOG_ERROR, "select returns with failure: %s",
					strerror(errno));
				retval = SCARD_F_COMM_ERROR;
				break;
			}
		}
	}

	return retval;
}
Exemplo n.º 21
0
Arquivo: run.c Projeto: cantora/ccan
int main(void)
{
	struct timespec t1, t2, t3, zero = { 0, 0 };

	plan_tests(61);

	/* Test time_now */
	t1 = time_now();
	t2 = time_now();

	/* Test time_sub. */
	t3 = time_sub(t2, t1);
	ok1(t3.tv_sec > 0 || t3.tv_nsec >= 0);
	t3 = time_sub(t2, t2);
	ok1(t3.tv_sec == 0 && t3.tv_nsec == 0);
	t3 = time_sub(t1, t1);
	ok1(t3.tv_sec == 0 && t3.tv_nsec == 0);

	/* Test time_eq */
	ok1(time_eq(t1, t1));
	ok1(time_eq(t2, t2));
	ok1(!time_eq(t1, t3));
	ok1(!time_eq(t2, t3));

	/* Make sure t2 > t1. */
	t3.tv_sec = 0;
	t3.tv_nsec = 1;
	t2 = time_add(t2, t3);

	/* Test time_less and time_greater. */
	ok1(!time_eq(t1, t2));
	ok1(!time_greater(t1, t2));
	ok1(time_less(t1, t2));
	ok1(time_greater(t2, t1));
	ok1(!time_less(t2, t1));
	t3.tv_sec = 0;
	t3.tv_nsec = 999999999;
	t2 = time_add(t2, t3);
	ok1(!time_eq(t1, t2));
	ok1(!time_greater(t1, t2));
	ok1(time_less(t1, t2));
	ok1(time_greater(t2, t1));
	ok1(!time_less(t2, t1));

	t3 = time_sub(t2, zero);
	ok1(time_eq(t3, t2));
	t3 = time_sub(t2, t2);
	ok1(time_eq(t3, zero));

	/* time_from_sec / time_to_sec */
	t3 = time_from_sec(500);
	ok1(t3.tv_sec == 500);
	ok1(t3.tv_nsec == 0);
	ok1(time_to_sec(t3) == 500);

	/* time_from_msec / time_to_msec */
	t3 = time_from_msec(500);
	ok1(t3.tv_sec == 0);
	ok1(t3.tv_nsec == 500000000);
	ok1(time_to_msec(t3) == 500);

	t3 = time_from_msec(1000);
	ok1(t3.tv_sec == 1);
	ok1(t3.tv_nsec == 0);
	ok1(time_to_msec(t3) == 1000);

	t3 = time_from_msec(1500);
	ok1(t3.tv_sec == 1);
	ok1(t3.tv_nsec == 500000000);
	ok1(time_to_msec(t3) == 1500);

	/* time_from_usec */
	t3 = time_from_usec(500000);
	ok1(t3.tv_sec == 0);
	ok1(t3.tv_nsec == 500000000);
	ok1(time_to_usec(t3) == 500000);

	t3 = time_from_usec(1000000);
	ok1(t3.tv_sec == 1);
	ok1(t3.tv_nsec == 0);
	ok1(time_to_usec(t3) == 1000000);

	t3 = time_from_usec(1500000);
	ok1(t3.tv_sec == 1);
	ok1(t3.tv_nsec == 500000000);
	ok1(time_to_usec(t3) == 1500000);

	/* time_from_nsec */
	t3 = time_from_nsec(500000000);
	ok1(t3.tv_sec == 0);
	ok1(t3.tv_nsec == 500000000);
	ok1(time_to_nsec(t3) == 500000000);

	t3 = time_from_nsec(1000000000);
	ok1(t3.tv_sec == 1);
	ok1(t3.tv_nsec == 0);
	ok1(time_to_nsec(t3) == 1000000000);

	t3 = time_from_nsec(1500000000);
	ok1(t3.tv_sec == 1);
	ok1(t3.tv_nsec == 500000000);
	ok1(time_to_nsec(t3) == 1500000000);

	/* Test wrapunder */
	t3 = time_sub(time_sub(t2, time_from_msec(500)), time_from_msec(500));
	ok1(t3.tv_sec == t2.tv_sec - 1);
	ok1(t3.tv_nsec == t2.tv_nsec);

	/* time_divide and time_multiply */
	t1.tv_nsec = 100;
	t1.tv_sec = 100;

	t3 = time_divide(t1, 2);
	ok1(t3.tv_sec == 50);
	ok1(t3.tv_nsec == 50);

	t3 = time_divide(t1, 100);
	ok1(t3.tv_sec == 1);
	ok1(t3.tv_nsec == 1);

	t3 = time_multiply(t3, 100);
	ok1(time_eq(t3, t1));

	t3 = time_divide(t1, 200);
	ok1(t3.tv_sec == 0);
	ok1(t3.tv_nsec == 500000000);

	/* Divide by huge number. */
	t1.tv_sec = (1U << 31) - 1;
	t1.tv_nsec = 999999999;
	t2 = time_divide(t1, 1 << 30);
	/* Allow us to round either way. */
	ok1((t2.tv_sec == 2 && t2.tv_nsec == 0)
	    || (t2.tv_sec == 1 && t2.tv_nsec == 999999999));

	/* Multiply by huge number. */
	t1.tv_sec = 0;
	t1.tv_nsec = 1;
	t2 = time_multiply(t1, 1UL << 31);
	ok1(t2.tv_sec == 2);
	ok1(t2.tv_nsec == 147483648);

	return exit_status();
}
Exemplo n.º 22
0
int main(void) //(int argc, char *argv[])
{
    printf("Bingo, enter 1st simulator DSP APP~!\n");
#if 0
    u8 i, _i;
    u32 cnt, next;
    u32 msk, setmsk, clrmsk;
    u32 delta, deltamin, tnext, hi, lo;
    u32 *nextp;
    const u32 *hilop;
    u32 period;
    u32 enmask; /* enable mask */
    u32 stmask; /* state mask */
    static u32 next_hi_lo[MAX_PWMS][3];
#endif
/*
 * init Obj objects of each Chn.
 */

    ChanelObj chnObj[MAX_PWMS];
    u32 i = 0;
    u32 currTime = 0;
    //u32 sartRiseTime = 0;
    //u32 startFallTime = 0;
    for (i = 0; i < MAX_PWMS; i++)
    {
        chnObj[i].chid = i + 1;
        chnObj[i].enmask = 0;
    }

    u32 prevTime = 0;
    time64 currTs64;

    while (1)
    {
        u32 index = 0;

        //step 1 : update current time.
        currTime = read_PIEP_COUNT();
        if(prevTime > currTime)
        {
            // reverse
            currTs64.time_p2++;

        }
        currTs64.time_p1 = currTime;

        prevTime = currTime;

        update_flag();


        //step 2: judge current if it is arrive at rising edge time
        for (index = 0; index < MAX_PWMS; index++)
        {
            //it is time that arriving rising edge........
            if(TIME_GREATER(currTs64, chnObj[index].time_of_hi))
            {
                chnObj[index].enmask = PWM_CMD ->enmask;
                chnObj[index].period_time.time_p1 = PWM_CMD ->periodhi[index][0];


                // update time stamp
                //chnObj[index].time_of_lo.time_p2 = 0;
                //chnObj[index].time_of_lo.time_p1 = PWM_CMD ->periodhi[index][1];

                // chnObj[index].time_of_lo = time_add(chnObj[index].time_of_lo, currTs64);
                TIME_ADD(chnObj[index].time_of_lo, currTs64, PWM_CMD ->periodhi[index][1]);
                //rising_edge_time = current + period
                // chnObj[index].time_of_hi = time_add(chnObj[index].period_time, currTs64);
                TIME_ADD(chnObj[index].time_of_hi, currTs64, PWM_CMD ->periodhi[index][0]);

                if (chnObj[index].enmask & (1U << index))
                {
                   // sartRiseTime = read_PIEP_COUNT();
                    //fall_edge_time = current + hi_duty


                    __R30 |= (1U << index); //pull up

                    printf("<high> chn: %d cur [%08x-%08x]  r30 %x  hi [%08x-%08x]  lo [%08x-%08x]  perid %d(high: %d) \n" ,chnObj[index].chid,
                            currTs64.time_p2, currTs64.time_p1, __R30,
                            chnObj[index].time_of_hi.time_p2, chnObj[index].time_of_hi.time_p1,
                            chnObj[index].time_of_lo.time_p2, chnObj[index].time_of_lo.time_p1,
                            time_sub(currTs64, ts[index][0]), PWM_CMD ->periodhi[index][1]);
                    ts[index][0] = currTs64;

                }


                continue;
            }

            //it is time that arriving falling edge........
            if(TIME_GREATER(currTs64, chnObj[index].time_of_lo))
            {

            	TIME_ADD(chnObj[index].time_of_lo, currTs64, PWM_CMD ->periodhi[index][0]);

                if (chnObj[index].enmask & (1U << index))
                {
                    __R30 &= ~(1U << index); //pull down


                    printf("<low> chn: %d cur [%08x-%08x]  r30 %x  hi [%08x-%08x]  lo [%08x-%08x]  high-len %d \n" ,chnObj[index].chid,
                            currTs64.time_p2, currTs64.time_p1, __R30,
                            chnObj[index].time_of_hi.time_p2, chnObj[index].time_of_hi.time_p1,
                            chnObj[index].time_of_lo.time_p2, chnObj[index].time_of_lo.time_p1,
                            time_sub(currTs64, ts[index][0]));
                    ts[index][1] = currTs64;
                }

            }
        }
    }
#if 0


    //static struct cxt cxt;
#if 0
    /* enable OCP master port */
    PRUCFG_SYSCFG &= ~SYSCFG_STANDBY_INIT;
    PRUCFG_SYSCFG = (PRUCFG_SYSCFG &
            ~(SYSCFG_IDLE_MODE_M | SYSCFG_STANDBY_MODE_M)) |
    SYSCFG_IDLE_MODE_NO | SYSCFG_STANDBY_MODE_NO;

    /* our PRU wins arbitration */
    PRUCFG_SPP |= SPP_PRU1_PAD_HP_EN;
    pwm_setup();

    /* configure timer */
    PIEP_GLOBAL_CFG = GLOBAL_CFG_DEFAULT_INC(1) |
    GLOBAL_CFG_CMP_INC(1);
    PIEP_CMP_STATUS = CMD_STATUS_CMP_HIT(1); /* clear the interrupt */
    PIEP_CMP_CMP1 = 0x0;
    PIEP_CMP_CFG |= CMP_CFG_CMP_EN(1);
    PIEP_GLOBAL_CFG |= GLOBAL_CFG_CNT_ENABLE;
#endif

    /* initialize */
    cnt = read_PIEP_COUNT();

    enmask = cfg.enmask;
    stmask = 0; /* starting all low */

    clrmsk = 0;
    for (i = 0, msk = 1, nextp = &next_hi_lo[0][0], hilop = &cfg.hilo[0][0];
            i < MAX_PWMS; i++, msk <<= 1, nextp += 3, hilop += 2)
    {
        if ((enmask & msk) == 0)
        {
            nextp[1] = PRU_us(100); /* default */
            nextp[2] = PRU_us(100);
            continue;
        }
        nextp[0] = cnt; /* next */
        nextp[1] = 200000; /* hi */
        nextp[2] = 208000; /* lo */
        PWM_CMD ->periodhi[i][0] = 408000;
        PWM_CMD ->periodhi[i][1] = 180000;
    }
    PWM_CMD ->enmask = 0;
    clrmsk = enmask;
    setmsk = 0;
    /* guaranteed to be immediate */
    deltamin = 0;
    next = cnt + deltamin;
    PWM_CMD ->magic = PWM_REPLY_MAGIC;

    while (1)
    {

        update_flag();

        if (PWM_CMD ->magic == PWM_CMD_MAGIC)
        {
            msk = PWM_CMD ->enmask;
            for (i = 0, nextp = &next_hi_lo[0][0]; i < MAX_PWMS;
                    i++, nextp += 3)
            {
                //Enable
                if ((PWM_EN_MASK & (msk & (1U << i)))
                        && (enmask & (msk & (1U << i))) == 0)
                {
                    enmask |= (msk & (1U << i));

                    __R30 |= (msk & (1U << i));

                    // first enable
                    if (enmask == (msk & (1U << i)))
                        cnt = read_PIEP_COUNT();

                    nextp[0] = cnt;	//since we start high, wait this amount

                    deltamin = 0;
                    next = cnt;
                }
                //Disable
                if ((PWM_EN_MASK & (msk & (1U << i)))
                        && ((msk & ~(1U << i)) == 0))
                {
                    enmask &= ~(1U << i);
                    __R30 &= ~(1U << i);
                }

                //get and set pwm_vals
                if (PWM_EN_MASK & (msk & (1U << i)))
                {
                    if (b_true == full_period)
                    {

                        //nextp = &next_hi_lo[i * 3];
                        nextp[1] = PWM_CMD ->periodhi[i][1];
                        period = PWM_CMD ->periodhi[i][0];
                        nextp[2] = period - nextp[1];

                    }
                }
                PWM_CMD ->hilo_read[i][0] = nextp[0];
                PWM_CMD ->hilo_read[i][1] = nextp[1];

            }

            // guaranteed to be immediate
            deltamin = 0;

            PWM_CMD ->magic = PWM_REPLY_MAGIC;
        }
        PWM_CMD ->enmask_read = enmask;
        /* if nothing is enabled just skip it all */
        if (enmask == 0)
            continue;

        setmsk = 0;
        clrmsk = (u32) -1;
        deltamin = PRU_ms(100); /* (1U << 31) - 1; */
        next = cnt + deltamin;

        for (_i = 0; _i < MAX_PWMS; _i++)
        {
            if (enmask & (1U << (_i)))
            { //
                nextp = &next_hi_lo[(_i)][0]; //
                tnext = nextp[0]; //
                hi = nextp[1]; //
                lo = nextp[2]; //
                /* avoid signed arithmetic */ //
                while (((delta = (tnext - cnt)) & (1U << 31)) != 0)
                { //
                    /* toggle the state */ //
                    if (stmask & (1U << (_i)))
                    { //
                        stmask &= ~(1U << (_i)); //
                        clrmsk &= ~(1U << (_i)); //
                        tnext += lo; //

                        printf("CH %d: next hi: %08x\n", _i, tnext);
                        // flag when all motor channel finish full period
                        ch_num_period++;
                        if (!((ch_num_period) %= MAX_PWMS))
                        {
                            full_period = b_true;
                            printf(
                                    "----------------full period--------------\n");
                        }
                    }
                    else
                    { //
                        stmask |= (1U << (_i)); //
                        setmsk |= (1U << (_i)); //
                        tnext += hi; //
                        full_period = b_false;

                        //if(flag == Period_change)

                    } //
                } //
                if (delta <= deltamin)
                { //
                    deltamin = delta; //
                    next = tnext; //
                } //
                nextp[0] = tnext; //
            } //
        }
#if 0
#define SINGLE_PWM(_i) \
	do { \
		if (enmask & (1U << (_i))) { \
			nextp = &next_hi_lo[(_i)][0]; \
			tnext = nextp[0]; \
			hi = nextp[1]; \
			lo = nextp[2]; \
			/* avoid signed arithmetic */ \
			while (((delta = (tnext - cnt)) & (1U << 31)) != 0) { \
				/* toggle the state */ \
				if (stmask & (1U << (_i))) { \
					stmask &= ~(1U << (_i)); \
					clrmsk &= ~(1U << (_i)); \
					tnext += lo; \
				} else { \
					stmask |= (1U << (_i)); \
					setmsk |= (1U << (_i)); \
					tnext += hi; \
				} \
			} \
			if (delta <= deltamin) { \
				deltamin = delta; \
				next = tnext; \
			} \
			nextp[0] = tnext; \
		} \
	} while (0)

#if MAX_PWMS > 0 && (PWM_EN_MASK & BIT(0))
        SINGLE_PWM(0);
#endif
#if MAX_PWMS > 1 && (PWM_EN_MASK & BIT(1))
        SINGLE_PWM(1);
#endif
#if MAX_PWMS > 2 && (PWM_EN_MASK & BIT(2))
        SINGLE_PWM(2);
#endif
#if MAX_PWMS > 3 && (PWM_EN_MASK & BIT(3))
        SINGLE_PWM(3);
#endif
#if MAX_PWMS > 4 && (PWM_EN_MASK & BIT(4))
        SINGLE_PWM(4);
#endif
#if MAX_PWMS > 5 && (PWM_EN_MASK & BIT(5))
        SINGLE_PWM(5);
#endif
#if MAX_PWMS > 6 && (PWM_EN_MASK & BIT(6))
        SINGLE_PWM(6);
#endif
#if MAX_PWMS > 7 && (PWM_EN_MASK & BIT(7))
        SINGLE_PWM(7);
#endif
#if MAX_PWMS > 8 && (PWM_EN_MASK & BIT(8))
        SINGLE_PWM(8);
#endif
#if MAX_PWMS > 9 && (PWM_EN_MASK & BIT(9))
        SINGLE_PWM(9);
#endif
#if MAX_PWMS > 10 && (PWM_EN_MASK & BIT(10))
        SINGLE_PWM(10);
#endif
#if MAX_PWMS > 11 && (PWM_EN_MASK & BIT(11))
        SINGLE_PWM(11);
#endif
#if MAX_PWMS > 12 && (PWM_EN_MASK & BIT(12))
        SINGLE_PWM(12);
#endif
#endif

        /* results in set bits where there are changes */

        __R30 = (__R30 & (clrmsk & 0xfff)) | (setmsk & 0xfff);

        /* loop while nothing changes */
        do
        {
            cnt = read_PIEP_COUNT();
            //if(PWM_CMD->magic == PWM_CMD_MAGIC){
            //	break;
            //}
        } while (((next - cnt) & (1U << 31)) == 0);
    }
#endif
    printf("Bingo, leave 1st simulator DSP APP~!\n");
}
Exemplo n.º 23
0
static int edf_set_thread_sched_parameters (kthread_t *kthread, sched_t *params)
{
	time_t now;
	alarm_t alarm;
	kthread_sched_data_t *tsched = kthread_get_sched_param ( kthread );
	ksched_t *gsched = ksched_get ( SCHED_EDF );


	if ( gsched->params.edf.active == kthread )
		gsched->params.edf.active = NULL;

	k_get_time ( &now );

	if ( params->edf.flags & EDF_SET )
	{
		/*LOG( DEBUG, "%x [SET]", kthread ); */
		tsched->params.edf.period = params->edf.period;
		tsched->params.edf.relative_deadline = params->edf.deadline;
		tsched->params.edf.flags = params->edf.flags;

		/* set periodic alarm */
		tsched->params.edf.next_run = now;
		time_add ( &tsched->params.edf.next_run, &params->edf.period );
		edf_arm_deadline ( kthread );
		edf_arm_period ( kthread );

		/*
		 * adjust "next_run" and "deadline" for "0" period
		 * - first "edf_wait" will set correct values for first period
		 */
		tsched->params.edf.next_run = now;
		time_sub ( &tsched->params.edf.next_run, &params->edf.period );

		tsched->params.edf.active_deadline = now;
		time_add ( &tsched->params.edf.active_deadline,
			   &params->edf.deadline );
	}
	else if ( params->edf.flags & EDF_WAIT )
	{
		if ( edf_check_deadline ( kthread ) )
			return -1;

		/* set times for next period */
		if ( time_cmp ( &now, &tsched->params.edf.next_run ) > 0 )
		{
			time_add ( &tsched->params.edf.next_run,
				   &tsched->params.edf.period );

			tsched->params.edf.active_deadline = tsched->params.edf.next_run;
			time_add ( &tsched->params.edf.active_deadline,
				   &tsched->params.edf.relative_deadline );
		
			if ( kthread == gsched->params.edf.active )
				gsched->params.edf.active = NULL;

			/* set (separate) alarm for deadline */

			alarm.action = edf_deadline_timer;
			alarm.param = kthread;
			alarm.flags = 0;
			alarm.period.sec = alarm.period.nsec = 0;
			alarm.exp_time = tsched->params.edf.active_deadline;

			k_alarm_set ( tsched->params.edf.edf_deadline_alarm, &alarm );

		}

		/* is task ready for execution, or must wait until next period */
		if ( time_cmp ( &tsched->params.edf.next_run, &now ) > 0 )
		{
			/* wait till "next_run" */
			LOG( DEBUG, "%x [EDF WAIT]", kthread );
			kthread_enqueue ( kthread, &gsched->params.edf.wait );
			kthreads_schedule (); /* will call edf_schedule() */
		}
		else {
			/* "next_run" has already come,
			 * activate task => move it to "EDF ready tasks"
			 */
			LOG( DEBUG, "%x [EDF READY]", kthread );
			LOG( DEBUG, "%x [1st READY]", kthreadq_get ( &gsched->params.edf.ready ) );
			kthread_enqueue ( kthread, &gsched->params.edf.ready );
			kthreads_schedule (); /* will call edf_schedule() */
		}
	}
	else if ( params->edf.flags & EDF_EXIT )
	{
		if ( kthread == gsched->params.edf.active )
			gsched->params.edf.active = NULL;

		//LOG( DEBUG, "%x [EXIT]", kthread );
		if ( edf_check_deadline ( kthread ) )
		{
			LOG( DEBUG, "%x [EXIT-error]", kthread );
			return -1;
		}

		LOG( DEBUG, "%x [EXIT-normal]", kthread );
		if ( tsched->params.edf.edf_period_alarm )
			k_alarm_remove ( tsched->params.edf.edf_period_alarm );

		if ( tsched->params.edf.edf_deadline_alarm )
			k_alarm_remove ( tsched->params.edf.edf_deadline_alarm );

		tsched->sched_policy = SCHED_FIFO;

		LOG( DEBUG, "%x [EXIT]", kthread );
		if ( k_edf_schedule () )
		{
			LOG( DEBUG, "%x [EXIT]", kthread );

			kthreads_schedule (); /* will NOT call edf_schedule() */
		}

		LOG( DEBUG, "%x [EXIT]", kthread );
	}

	return 0;
}
/*!
 * Iterate through active alarms and activate newly expired ones
 */
static int k_schedule_alarms ()
{
	kalarm_t *first;
	time_t time, ref_time;
	int resched_thr = 0;
	kprocess_t *proc;

	arch_get_time ( &time );
	ref_time = time;
	time_add ( &ref_time, &threshold );

	/* should any alarm be activated? */
	first = list_get ( &kalarms, FIRST );
	while ( first != NULL )
	{
		if ( time_cmp ( &first->alarm.exp_time, &ref_time ) <= 0 )
		{
			/* 'activate' alarm */

			/* but first remove alarm from list */
			first = list_remove ( &kalarms, FIRST, NULL );

			if ( first->alarm.flags & ALARM_PERIODIC )
			{
				/* calculate next activation time */
				time_add ( &first->alarm.exp_time,
					   &first->alarm.period );
				/* put back into list */
				list_sort_add ( &kalarms, first, &first->list,
						alarm_cmp );
			}
			else {
				first->active = 0;
			}

			if ( first->alarm.action )
			{
				/* call directly:

				first->alarm.action ( first->alarm.param );

				   or create new thread for that job: */

				if ( first->thread )
				{ /* alarm scheduled by thread */
				proc = k_get_thread_process ( first->thread );
				k_create_thread (
					first->alarm.action,
					first->alarm.param,
					proc->pi->exit,
					k_get_thread_prio ( first->thread ) + 1,
					NULL, 0, 1,
					proc
				);
				resched_thr++;
				}
				else { /* alarm scheduled by kernel */
				first->alarm.action ( first->alarm.param );
				}
			}

			resched_thr += k_release_all_threads ( &first->queue );

			first = list_get ( &kalarms, FIRST );
		}
		else {
			break;
		}
	}

	first = list_get ( &kalarms, FIRST );
	if ( first )
	{
		ref_time = first->alarm.exp_time;
		time_sub ( &ref_time, &time );
		arch_timer_set ( &ref_time, k_timer_interrupt );
	}

	return resched_thr;
}
Exemplo n.º 25
0
static int edf_set_thread_sched_parameters ( ksched_t *ksched,
					     kthread_t *kthread,
					     sched_supp_t *params )
{
	timespec_t now;
	itimerspec_t alarm;
	kthread_sched2_t *tsched = kthread_get_sched2_param ( kthread );

	if ( ksched->params.edf.active == kthread )
		ksched->params.edf.active = NULL;

	kclock_gettime ( CLOCK_REALTIME, &now );

	if ( params->edf.flags & EDF_SET )
	{
		tsched->params.edf.period = params->edf.period;
		tsched->params.edf.relative_deadline = params->edf.deadline;
		tsched->params.edf.flags = params->edf.flags ^ EDF_SET;

		/* create and set periodic alarm */
		edf_create_alarm ( kthread, edf_period_alarm,
				   &tsched->params.edf.period_alarm );
		tsched->params.edf.next_run = now;
		time_add ( &tsched->params.edf.next_run, &params->edf.period );
		alarm.it_interval = tsched->params.edf.period;
		alarm.it_value = tsched->params.edf.next_run;
		ktimer_settime ( tsched->params.edf.period_alarm, TIMER_ABSTIME,
				 &alarm, NULL );

		/* adjust "next_run" and "deadline" for "0" period
		 * first "edf_wait" will set correct values for first period */
		tsched->params.edf.next_run = now;
		time_sub ( &tsched->params.edf.next_run, &params->edf.period );

		/* create and set deadline alarm */
		edf_create_alarm ( kthread, edf_deadline_alarm,
				   &tsched->params.edf.deadline_alarm );
		tsched->params.edf.active_deadline = now;
		time_add ( &tsched->params.edf.active_deadline,
			   &params->edf.deadline );
		TIME_RESET ( &alarm.it_interval );
		alarm.it_value = tsched->params.edf.active_deadline;
		ktimer_settime ( tsched->params.edf.deadline_alarm,
				 TIMER_ABSTIME, &alarm, NULL );

		/* move thread to edf scheduler */
		kthread_enqueue ( kthread, &ksched->params.edf.ready );
		edf_schedule (ksched);
	}
	else if ( params->edf.flags & EDF_WAIT )
	{
		if ( edf_check_deadline ( kthread ) )
			return EXIT_FAILURE;

		/* set times for next period */
		if ( time_cmp ( &now, &tsched->params.edf.next_run ) > 0 )
		{
			time_add ( &tsched->params.edf.next_run,
				   &tsched->params.edf.period );

			tsched->params.edf.active_deadline =
				tsched->params.edf.next_run;
			time_add ( &tsched->params.edf.active_deadline,
				   &tsched->params.edf.relative_deadline );

			if ( kthread == ksched->params.edf.active )
				ksched->params.edf.active = NULL;

			/* set (separate) alarm for deadline
			 * (periodic alarm is set only once as periodic) */

			TIME_RESET ( &alarm.it_interval );
			alarm.it_value = tsched->params.edf.active_deadline;
			ktimer_settime ( tsched->params.edf.deadline_alarm,
					 TIMER_ABSTIME, &alarm, NULL );
		}

		/* is task ready for execution, or must wait until next period*/
		if ( time_cmp ( &tsched->params.edf.next_run, &now ) > 0 )
		{
			/* wait till "next_run" */
			EDF_LOG ( "%x [EDF WAIT]", kthread );
			kthread_enqueue ( kthread, &ksched->params.edf.wait );
			edf_schedule (ksched);
		}
		else {
			/* "next_run" has already come,
			 * activate task => move it to "EDF ready tasks"
			 */
			EDF_LOG ( "%x [EDF READY]", kthread );
			kthread_enqueue ( kthread, &ksched->params.edf.ready );
			edf_schedule (ksched);
		}
	}
	else if ( params->edf.flags & EDF_EXIT )
	{
		if ( kthread == ksched->params.edf.active )
			ksched->params.edf.active = NULL;

		if ( edf_check_deadline ( kthread ) )
		{
			EDF_LOG ( "%x [EXIT-error]", kthread );
			return EXIT_FAILURE;
		}

		EDF_LOG ( "%x [EXIT-normal]", kthread );

		if ( tsched->params.edf.period_alarm )
		{
			/* disarm timer */
			TIME_RESET ( &alarm.it_interval );
			TIME_RESET ( &alarm.it_value );
			ktimer_settime ( tsched->params.edf.period_alarm, 0,
					 &alarm, NULL );
		}

		if ( tsched->params.edf.deadline_alarm )
		{
			/* disarm timer */
			TIME_RESET ( &alarm.it_interval );
			TIME_RESET ( &alarm.it_value );
			ktimer_settime ( tsched->params.edf.deadline_alarm, 0,
					 &alarm, NULL );
		}

		kthread_setschedparam ( kthread, SCHED_FIFO, NULL );
	}

	return 0;
}
Exemplo n.º 26
0
int main(int argc, char *argv[])
{
	struct client client;
	unsigned int i, j;
	struct sockaddr_un addr;
	struct timespec start, end;
	int fd, wake[2];
	char buf;

	addr.sun_family = AF_UNIX;
	sprintf(addr.sun_path, "/tmp/run-different-speed.sock.%u", getpid());

	if (pipe(wake) != 0 || pipe(timeout) != 0)
		err(1, "Creating pipes");

	fd = socket(AF_UNIX, SOCK_STREAM, 0);
	if (fd < 0)
		err(1, "Creating socket");

	if (bind(fd, (void *)&addr, sizeof(addr)) != 0)
		err(1, "Binding to %s", addr.sun_path);

	if (listen(fd, NUM_CONNS) != 0)
		err(1, "Listening on %s", addr.sun_path);

	for (i = 0; i < NUM_CHILDREN; i++) {
		switch (fork()) {
		case -1:
			err(1, "forking");
		case 0:
			close(wake[1]);
			create_clients(&addr, wake[0]);
			break;
		}
		for (j = 0; j < NUM_CONNS; j++) {
			int ret = accept(fd, NULL, 0);
			if (ret < 0)
				err(1, "Accepting fd");
			/* For efficiency, we share client structure */
			io_new_conn(ret,
				    io_read(client.request_buffer, REQUEST_SIZE,
					    write_reply, &client));
		}
	}

	io_new_conn(timeout[0], io_read(&buf, 1, do_timeout, &buf));

	close(wake[0]);
	for (i = 0; i < NUM_CHILDREN; i++)
		write(wake[1], "1", 1);

	signal(SIGALRM, sigalarm);
	alarm(10);
	start = time_now();
	io_loop();
	end = time_now();
	close(fd);

	printf("%u connections complete (%u ns per conn)\n",
	       completed,
	       (int)time_to_nsec(time_divide(time_sub(end, start), completed)));
	return 0;
}
Exemplo n.º 27
0
int main(int argc, char *argv[])
{
	void *ctx;
	unsigned count;
	int i, j;
	struct timespec tv;
	void *p1, *p2[100], *p3[100];
	bool run_talloc = true, run_tal = true, run_malloc = true;

	if (argv[1]) {
		if (strcmp(argv[1], "--talloc") == 0)
			run_tal = run_malloc = false;
		else if (strcmp(argv[1], "--tal") == 0)
			run_talloc = run_malloc = false;
		else if (strcmp(argv[1], "--malloc") == 0)
			run_talloc = run_tal = false;
		else
			errx(1, "Bad flag %s", argv[1]);
	}

	if (!run_talloc)
		goto after_talloc;

	ctx = talloc_new(NULL);
	tv = time_now();
	count = 0;
	do {
		for (i=0;i<LOOPS;i++) {
			p1 = talloc_size(ctx, LOOPS % 128);
			for (j = 0; j < 100; j++) {
				p2[j] = talloc_strdup(p1, "foo bar");
				p3[j] = talloc_size(p1, 300);
			}
			talloc_free(p1);
		}
		count += (1 + 200) * LOOPS;
	} while (time_sub(time_now(), tv).tv_sec < 5);

	fprintf(stderr, "talloc: %.0f ops/sec\n", count/5.0);

	talloc_free(ctx);

after_talloc:
	if (!run_tal)
		goto after_tal;

	ctx = tal(NULL, char);
	tv = time_now();
	count = 0;
	do {
		for (i=0;i<LOOPS;i++) {
			p1 = tal_arr(ctx, char, LOOPS % 128);
			for (j = 0; j < 100; j++) {
				p2[j] = tal_strdup(p1, "foo bar");
				p3[j] = tal_arr(p1, char, 300);
			}
			tal_free(p1);
		}
		count += (1 + 200) * LOOPS;
	} while (time_sub(time_now(), tv).tv_sec < 5);
	fprintf(stderr, "tal:    %.0f ops/sec\n", count/5.0);

	tal_free(ctx);

after_tal:
	if (!run_malloc)
		goto after_malloc;

	tv = time_now();
	count = 0;
	do {
		for (i=0;i<LOOPS;i++) {
			p1 = malloc(LOOPS % 128);
			for (j = 0; j < 100; j++) {
				p2[j] = strdup("foo bar");
				p3[j] = malloc(300);
			}
			for (j = 0; j < 100; j++) {
				free(p2[j]);
				free(p3[j]);
			}
			free(p1);
		}
		count += (1 + 200) * LOOPS;
	} while (time_sub(time_now(), tv).tv_sec < 5);
	fprintf(stderr, "malloc: %.0f ops/sec\n", count/5.0);

after_malloc:
	printf("success: speed\n");

	return 0;
}