Timer Example

Table of Contents

1 Timer API

A timer is represented in the kernel as an instance of timer_list:

#include <linux/timer.h>

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

#ifdef CONFIG_LOCKDEP
	struct lockdep_map	lockdep_map;
#endif
};

expires is an absolute value in jiffies. entry is a doubley linked list, and a callback function.

2 Timer setup initialization

The following are steps to initialize timers:

  • Setting up the timer: Set up the timer, feeding the user-defined callback function.
/**
 * timer_setup - prepare a timer for first use
 * @timer: the timer in question
 * @callback: the function to call when timer expires
 * @flags: any TIMER_* flags
 *
 * Regular timer initialization should use either DEFINE_TIMER() above,
 * or timer_setup(). For timers on the stack, timer_setup_on_stack() must
 * be used and must be balanced with a call to destroy_timer_on_stack().
 */
#define timer_setup(timer, callback, flags)			\
	__init_timer((timer), (callback), (flags))
  • Setting the expiration time: When the timer is initialized, we need to set its expiration before the callback gets fired:
int mod_timer(struct timer_list *timer, unsigned long expires);
  • Releasing the timer: When you are done with the timer, it needs to be released:
int del_timer(struct timer_list * timer);
int del_timer_sync(struct timer_list *timer);

del_timer() return 0 on an inactive timer, and return 1 on an active timer, del_timer_sync waits for the handler to finish its execution, even those that may happen on another CPU. You should not hold a lock preventing the handler's completion, otherwise it will result in a dead lock. You should release the timer in the module cleanup routine. You can independently check whether the timer is running or not:

int timer_pending(const struct timer_list * timer);

3 Example Code

Author: Yanqing.Li

Created: 2019-04-20 六 18:22

Validate