Poojan
Poojan

Reputation: 3332

What is the best way to implment multiple timers in Kernel module

I am trying to build e kernel module which will be used by userspace program to setup timers. I am implementing it as a character device. What is the best way to implement multiple timers in the kernel module?

Currently I have one 'timer_list*', sat 'timer'. I am assigning memory from the heap everytime I get a new request for timer and then use setup_timer() and mod_timer() to set the timer everytime I assign memory. But I am only using one pointer to the timer_list struct. But my concern here is that how to free the memory assigned to 'timer' once the callback function is called because the current value of 'timer' might not be pointing to the structure whose callback function is called.

So, I thought about passing the address of the structure in as an argument to the callback function and then call kfree() on that address.

struct timer_list *timer;
timer = kmalloc(sizeof(struct timer_list), GFP_KERNEL);
setup_timer(timer, my_callback, (unsigend long)timer);

My callback function looks like this:

void my_callback (unsigned long data)
{
      struct timer_list *timer = (struct timer_list*)data;
      printk("%d\n", timer->data);
      kfree(timer);
}

In this case I am getting a segmentation fault when I try to print timer->data saying there is no page for that particular address. So, is the the memoery allocated to timer_list freed when the callback function is called. In that case I dont need to worry about freeing the memory.

Also, is there a better way to implement this thing. Also, to keep a track of all the timers (like checking like existence of a timer), is it adivasable to maintain something like a linked-list or there is some kernel function to check this?

Upvotes: 0

Views: 380

Answers (1)

Federico
Federico

Reputation: 3892

In some way you have to take track of all your timers. You can use, for example, a list (see list.h) of your pending timers. Then, you can loop on your list to check if any timer already expired and release its memory (and remove from the list). You can do this before allocate a new timer.

timer_list is not freed automatically because you can re-program it with mod_timer()

Upvotes: 1

Related Questions