Learn how to use Linux Kernel Timer (linux/timer.h)

Introduction: –

Linux Kernel provides its own sets of timers which can be used by the device drivers to provide delays. They are declared in linux/timer.h file. Check out the post to learn more about the Linux Kernel Timer.

There is one structure of timer defined in the header file named as timer_list. The definition of the structure is stated below.

struct timer_list {
   * All fields that change during normal runtime grouped to the
   * same cacheline
  struct hlist_node	entry;
  unsigned long		expires;
  void			(*function)(unsigned long);
  unsigned long		data;
  u32			flags;
  int			slack;

  int			start_pid;
  void			*start_site;
  char			start_comm[16];
  struct lockdep_map	lockdep_map;

referred from: –https://elixir.bootlin.com/linux/v4.6/source/include/linux/timer.h

Initialization: –

To initialize the timer we are required to populate the timer_list structure and add the timer into the kernel. The variable expires defines timeout in jiffies. Once the value of the timer is equal to the expires it calls the callback function which is provided in the function inside the structure.

struct timer_list mytimer;
static void timer_init(void)
  mytimer.function = myfunc;
  mytimer.data = 0;
  mytimer.expires = (unsigned long)(jiffies + HZ/2);
  printk("Timer Started\r\n");

The above function provides initialization of the timer. mytimer is the object defined for the timer_list structure. mytimer.data provides parameter to the callback function. Note down the mytimer.expires in the initialization where you provide the delay in jiffies. HZ corresponds to 1 second delay. Hence, HZ/2 provides 500 ms delay. For above initialization, the timer expires after 500 ms and calls myfunc.

Working: –

When timer expires it calls myfunc. Check out the function myfunc which prints name and reinitialize the timer. Also, it keeps count about how many times the function has been called. We are not using parameter unsigned long s but the inbuilt timer passes the parameter to the callback function of data type unsigned long.

void myfunc(unsigned long s)
  printk("My name is %s and count is %d\n", n, count);
  mytimer.expires = (unsigned long)(jiffies + HZ/2);

We are required to delete the timer once we are about to exit from the program or we are completed with the timer use. Use the below function to delete the timer.

add_timer function adds the timer into the global list of timers.


There are other functions which we can use to modify the timer or initialize it.

int mod_timer(struct timer_list *timer, unsigned long expires);

The mod_timer can be used to modify the expires value.

Checkout the full code:- https://github.com/satya45/Advanced_Embedded_Software_Development/blob/master/HW-3/P3/satya_module.c



Please enter your comment!
Please enter your name here