timer.c
cd57180a
 /*
  * $Id$
  */
 
 #include "timer.h"
 #include "dprint.h"
 #include "error.h"
 #include "config.h"
dda9dab1
 #include "mem/mem.h"
d4f2d8b0
 #ifdef SHM_MEM
dda9dab1
 #include "mem/shm_mem.h"
d4f2d8b0
 #endif
cd57180a
 
 #include <stdlib.h>
 
 
 struct sr_timer* timer_list=0;
 
d4f2d8b0
 static int* jiffies=0;
cd57180a
 static int timer_id=0;
 
d4f2d8b0
 
 
 /* ret 0 on success, <0 on error*/
 int init_timer()
 {
 #ifdef SHM_MEM
 	jiffies=shm_malloc(sizeof(int));
 #else
 	/* in this case get_ticks won't work! */
 	LOG(L_INFO, "WARNING: no shared memory support compiled in"
 				" get_ticks won't work\n");
 	jiffies=malloc(sizeof(int));
 #endif
 	if (jiffies==0){
 		LOG(L_CRIT, "ERROR: init_timer: could not init jiffies\n");
 		return E_OUT_OF_MEM;
 	}
 	*jiffies=0;
 	return 0;
 }
 
 
 
 	
cd57180a
 /*register a periodic timer;
  * ret: <0 on error*/
 int register_timer(timer_function f, void* param, unsigned int interval)
 {
 	struct sr_timer* t;
 
 	t=malloc(sizeof(struct sr_timer));
 	if (t==0){
 		LOG(L_ERR, "ERROR: register_timer: out of memory\n");
 		goto error;
 	}
 	t->id=timer_id++;
 	t->timer_f=f;
 	t->t_param=param;
 	t->interval=interval;
d4f2d8b0
 	t->expires=*jiffies+interval;
cd57180a
 	/* insert it into the list*/
 	t->next=timer_list;
 	timer_list=t;
 	return t->id;
 
 error:
 	return E_OUT_OF_MEM;
 }
 
 
 
 void timer_ticker()
 {
 	struct sr_timer* t;
 	unsigned int prev_jiffies;
 	
d4f2d8b0
 	prev_jiffies=*jiffies;
 	*jiffies+=TIMER_TICK;
cd57180a
 	/* test for overflow (if tick= 1s =>overflow in 136 years)*/
d4f2d8b0
 	if (*jiffies<prev_jiffies){ 
cd57180a
 		/*force expire & update every timer, a little buggy but it 
 		 * happens once in 136 years :) */
 		for(t=timer_list;t;t=t->next){
d4f2d8b0
 			t->expires=*jiffies+t->interval;
 			t->timer_f(*jiffies, t->t_param);
cd57180a
 		}
 		return;
 	}
 	
 	for (t=timer_list;t; t=t->next){
d4f2d8b0
 		if (*jiffies>=t->expires){
 			t->expires=*jiffies+t->interval;
 			t->timer_f(*jiffies, t->t_param);
cd57180a
 		}
 	}
 }
b902c38b
 
 
 
 unsigned int get_ticks()
 {
d4f2d8b0
 	if (jiffies==0){
 		LOG(L_CRIT, "BUG: get_ticks: jiffies not intialized\n");
 		return 0;
 	}
 #ifndef SHM_MEM
 	LOG(L_CRIT, "WARNING: get_ticks: no shared memory support compiled in"
 			", returning 0 (probably wrong)");
 	return 0;
 #endif
 	return *jiffies;
b902c38b
 }