#include <sys/types.h>
#include <stdlib.h>
#include "timer.h"
#include "iperf_time.h"
static Timer* timers = NULL;
static Timer* free_timers = NULL;
TimerClientData JunkClientData;
static void
getnow( struct iperf_time* nowP, struct iperf_time* nowP2 )
{
if ( nowP != NULL )
*nowP2 = *nowP;
else
iperf_time_now(nowP2);
}
static void
list_add( Timer* t )
{
Timer* t2;
Timer* t2prev;
if ( timers == NULL ) {
timers = t;
t->prev = t->next = NULL;
} else {
if (iperf_time_compare(&t->time, &timers->time) < 0) {
t->prev = NULL;
t->next = timers;
timers->prev = t;
timers = t;
} else {
for ( t2prev = timers, t2 = timers->next; t2 != NULL;
t2prev = t2, t2 = t2->next ) {
if (iperf_time_compare(&t->time, &t2->time) < 0) {
t2prev->next = t;
t->prev = t2prev;
t->next = t2;
t2->prev = t;
return;
}
}
t2prev->next = t;
t->prev = t2prev;
t->next = NULL;
}
}
}
static void
list_remove( Timer* t )
{
if ( t->prev == NULL )
timers = t->next;
else
t->prev->next = t->next;
if ( t->next != NULL )
t->next->prev = t->prev;
}
static void
list_resort( Timer* t )
{
list_remove( t );
list_add( t );
}
Timer*
tmr_create(
struct iperf_time* nowP, TimerProc* timer_proc, TimerClientData client_data,
int64_t usecs, int periodic )
{
struct iperf_time now;
Timer* t;
getnow( nowP, &now );
if ( free_timers != NULL ) {
t = free_timers;
free_timers = t->next;
} else {
t = (Timer*) malloc( sizeof(Timer) );
if ( t == NULL )
return NULL;
}
t->timer_proc = timer_proc;
t->client_data = client_data;
t->usecs = usecs;
t->periodic = periodic;
t->time = now;
iperf_time_add_usecs(&t->time, usecs);
list_add( t );
return t;
}
struct timeval*
tmr_timeout( struct iperf_time* nowP )
{
struct iperf_time now, diff;
int64_t usecs;
int past;
static struct timeval timeout;
getnow( nowP, &now );
if ( timers == NULL )
return NULL;
past = iperf_time_diff(&timers->time, &now, &diff);
if (past)
usecs = 0;
else
usecs = iperf_time_in_usecs(&diff);
timeout.tv_sec = usecs / 1000000LL;
timeout.tv_usec = usecs % 1000000LL;
return &timeout;
}
void
tmr_run( struct iperf_time* nowP )
{
struct iperf_time now;
Timer* t;
Timer* next;
getnow( nowP, &now );
for ( t = timers; t != NULL; t = next ) {
next = t->next;
if (iperf_time_compare(&t->time, &now) > 0)
break;
(t->timer_proc)( t->client_data, &now );
if ( t->periodic ) {
iperf_time_add_usecs(&t->time, t->usecs);
list_resort( t );
} else
tmr_cancel( t );
}
}
void
tmr_reset( struct iperf_time* nowP, Timer* t )
{
struct iperf_time now;
getnow( nowP, &now );
t->time = now;
iperf_time_add_usecs( &t->time, t->usecs );
list_resort( t );
}
void
tmr_cancel( Timer* t )
{
list_remove( t );
t->next = free_timers;
free_timers = t;
t->prev = NULL;
}
void
tmr_cleanup( void )
{
Timer* t;
while ( free_timers != NULL ) {
t = free_timers;
free_timers = t->next;
free( (void*) t );
}
}
void
tmr_destroy( void )
{
while ( timers != NULL )
tmr_cancel( timers );
tmr_cleanup();
}