How can I pass a custom argument to a linux timer function?
Under some conditions, I want to schedule a timer ( struct timer_list
) that runs on user data. The field of function
this structure contains the actual function that will be run and is defined as below:
void (*function)(unsigned long);
The thing is, I want to pass a pointer instead of unsigned long
. I know that depending on the architecture, the int-ptr conversion may or may not be safe, but I couldn't find if all architectures align long
integers with pointers, so here's my question (actually, one):
Is it safe to cast long
to void*
? If not, how should I handle the argument unsigned long
to get the data pointer I want in the timer function?
source to share
In the case of timer functions and in some other situations, it is possible to simply cast a pointer to a data structure to unsigned long
, store it in a field, data
struct timer_list
and return the argument of the timer function back to a pointer to your data structure. This appears to be common practice.
Linux Driver Development, 3rd. ed. states the following in this matter in chapter 7:
If you need to pass multiple elements as an argument, you can bind them as a single data structure and pass pointer casting to unsigned long, safe practice on all supported architectures, and fairly frequent memory management (as described in Chapter 15).
There are many examples in the kernel, see for example s_err_report
timer in the ext4 filesystem module. A pointer to struct super_block
is passed to the timer function with clicks on unsigned long
and back, as described above.
source to share