Hello,
Sometime back i had asked a question regarding kernel timers.
Thanks i could implement them.I am posting my code so that others new to this stuff may also benefit from it.
#include<linux/init.h>
#include<linux/sched.h>
#include<linux/timer.h>
#include<linux/slab.h>
#include<linux/list.h>
struct struct_timer{
int timer_id;
struct timer_list timer;
struct list_head list;
};
struct struct_timer timer_head;
void stop_timer(int id)
{
struct list_head *pos,*q;
struct struct_timer*tmp;
printk("\n the id is %d",id);
list_for_each_safe(pos,q,&timer_head.list){
tmp=list_entry(pos,struct struct_timer,list);
if(tmp->timer_id==id)
{
printk("\n timer_id%d",tmp->timer_id);
del_timer(&(tmp->timer));
//list_del(pos);
kfree(tmp);
break;
}
}
}
void timer_timeout(int c)
{
struct timeval timecount;
struct list_head*pos,*q;
struct struct_timer*tmp;
do_gettimeofday(&timecount);
printk(KERN_INFO "\ntimer%d expired at :%ld seconds %ld microseconds",c,timecount.tv_sec,timecount.tv_usec);
list_for_each_safe(pos,q,&timer_head.list){
tmp=list_entry(pos,struct struct_timer,list);
if(tmp->timer_id==c)
{
del_timer(&(tmp->timer));
list_del(pos);
kfree(tmp);
}
}
}
int set_timer(int delay)
{
static int i=0,id;
struct timeval timecount;
struct struct_timer*temp;
temp=kmalloc(sizeof(struct struct_timer),GFP_ATOMIC);
init_timer(&(temp->timer));
temp->timer.expires=jiffies+delay*HZ;
id=i;
temp->timer.data="">
temp->timer.function=(void*)timer_timeout;
add_timer(&(temp->timer));
temp->timer_id=i;
list_add(&(temp->list),&(timer_head.list));
do_gettimeofday(&timecount);
printk(KERN_INFO "\ntimer%d started at :%ld seconds %ld microseconds",i++,timecount.tv_sec,timecount.tv_usec);
return id;
}
int time_init(void)
{
int i,id[5],delay,timerid;
struct list_head*pos;
struct struct_timer*tmp;
INIT_LIST_HEAD(&(timer_head.list));
for(i=0;i<3;i++)
{
delay=10*(i+1);
id[i]=set_timer(delay);
}
list_for_each(pos,&timer_head.list){
tmp=list_entry(pos,struct struct_timer,list);
if((tmp->timer_id==id[2])&&(timer_pending(&tmp->timer)))
stop_timer(tmp->timer_id);
}
return 0;
}
void time_cleanup(void)
{
struct list_head*pos,*q;
struct struct_timer*tmp;
list_for_each_safe(pos,q,&timer_head.list){
tmp=list_entry(pos,struct struct_timer,list);
printk("\n freeing the timer%d",tmp->timer_id);
del_timer(&(tmp->timer));
list_del(pos);
kfree(tmp);
}
printk(KERN_INFO "\ntimer unloaded\n");
}
module_init(time_init);
module_exit(time_cleanup);
MODULE_LICENSE("GPL");
the time_init is just a test function that sets up three timers with different times of expiry.And then tries to stop the third timer before expiry by passing the timerid of third timer to stop_timer.
The code works fine except for the commented line "list_del(pos)" in stop_timer.The same thing works just fine in timeout function.But if I uncomment this line the code gives fault and i have to reboot the system.
I have been wondering over this over 4 days.Any suggestions to this are most welcome.
Regards
vaishali