10 July, 2009

Using Timers in Linux kernel module

Linux kernel timer tutorial
This is a tutorial for using timer in linux kernel module. we all need one function to be called periodically say 500ms,1s to do so some task periodically(like GPIO polling, sending some message to user space etc)

As any system/OS, we need to initialize the timer module before we can use it. We need to give a name for the timer(for us to configure and restart the timer), timer function handler(ie.when timer expires this function will be called). One important thing to be noted is after timer expires it wont restart the timer automatically, it has to be restarted manually to get the next timer expiry.

The timer implementation resides in and kernel/timer.c

The timer study program is as shown below. In the module init we are initializing the timer with the the timer expiry routine(timer1_routine), data to be passed when the routing is called(in my example 1) , the timer expiry in jiffies. these are the minimum initialization we need to do with the timer struct. After calling the add_timer function the timer starts and the expiray routine will be called after the specifies time, in our case 1 second Dont forget to stop the timer del_timer_sync(&timer1); in the module unload. If we want to execute the timer1_routine every 1 second we need to restart the timer with mod_timer(&timer1, jiffies + HZ);

Any feedback welcome ! You can read the below book

Linux Device Drivers, 3rd Edition


also look for more at http://www.embeddedlinuxforum.com

/********************************** timerStudy.c *************************************************
#include
#include
#include

MODULE_LICENSE("Dual BSD/GPL");

struct timer_list timer1;

int i;

void timer1_routine(unsigned long data)
{

printk(KERN_ALERT"Inside Timer Routine count-> %d data passed %ld\n",i++,data);
mod_timer(&timer1, jiffies + HZ); /* restarting timer */
}


static int timer_module_init(void)
{


init_timer(&timer1);

timer1.function = timer1_routine;
timer1.data = 1;
timer1.expires = jiffies + HZ; /* 1 second */
add_timer(&timer1); /* Starting the timer */

printk(KERN_ALERT"Timer Module loaded\n");
return 0;
}

static void timer_module_exit(void)
{
del_timer_sync(&timer1); /* Deleting the timer */

printk(KERN_ALERT "Timer module unloaded \n");
}

module_init(timer_module_init);
module_exit(timer_module_exit);

********************************** timerStudy.c *************************************************/



Make file to compile the above timer module.

/********************************** Makefile *************************************************



obj-m +=timerStudy.o

all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

********************************** Makefile *************************************************/

Dino Joseph Mycle

No comments:

Post a Comment