Adding delayed work to kthread worker

Topics in this section,

#

Version

Ubuntu

Ubuntu 22.10

Kernel

6.7.9

  • In this program, you are going to learn

  • How to create the delayed kthread work ?

  • How to add delayed kthread work to kthread worker?

  • How to destroy the kthread worker ?

#include <linux/kthread.h>

struct kthread_worker *kthread_create_worker(unsigned int flags, const char namefmt[], ...);
  • where

    • kthread_create_worker: creates a kthread worker.

    • return type:

      • returns a pointer (i.e struct kthread_worker*) to the allocated worker on success

      • ERR_PTR(-ENOMEM) when the needed structures could not get allocated

      • ERR_PTR(-EINTR) when the caller was killed by a fatal signal.

    • flags: flags modifying the default behaviour of the kthread worker.

    • namefmt: printf-style name for the kthread worker.

  • Here is an example of how to use the API,

kthread_create_worker(0,"sample kthread worker");
  • Here is the function prototype of the API: kthread_run

#include <linux/kthread.h>

#define kthread_run(threadfn, data, namefmt, ...)
  • where

    • kthread_run : is used to create and wake a kthread

    • return type: struct task_struct* (i.e) address of the kthread

    • threadfn: function to executed by kthread

    • data: data pointer for threadfn which can be used to send any possible arguments required for threadfn.

    • namefmt: printf-style format for the thread name which will be displayed on ps output when the thread is in execution.

  • Here is an example of how to use the API,

kthread_run(mythread,NULL,"sample kthread");
#include <linux/kthread.h>

#define kthread_init_delayed_work(dwork, fn)            \
    do {                                                \
        kthread_init_work(&(dwork)->work, (fn));        \
        timer_setup(&(dwork)->timer,                    \
            kthread_delayed_work_timer_fn,              \
            TIMER_IRQSAFE);                             \
    } while (0)
  • where

    • kthread_init_delayed_work : used to initialize a delayed work.

    • work: kthread work which needs to be initialized

    • fn: function which is needs to be executed once kthread work is created.

  • Here is an example of how to use the API,

kthread_init_delayed_work(mydelayedwork,mydelayedworkfn);
#include <linux/kthread.h>

bool kthread_queue_delayed_work(struct kthread_worker *worker,struct kthread_delayed_work *dwork,unsigned long delay);
  • where

    • kthread_queue_delayed_work : queue the associated kthread work after delay

    • worker: target kthread_worker

    • dwork: kthread_delayed_work to queue

    • delay: number of jiffies to wait before queuing.

    • return type: returns type if it is successfully queue to kthread_worker, false if its already pending

  • Here is an example of how to use the API,

kthread_queue_delayed_work(myworker,mywork);
#include <linux/kthread.h>

bool kthread_cancel_delayed_work_sync(struct kthread_delayed_work *work);
  • where

    • kthread_cancel_delayed_work_sync : cancel a kthread_delayed_work and wait for it to finish

    • work: the kthread_delayed_work to cancel.

    • return type: true if work is pending , false otherwise.

  • Here is an example of how to use the API,

kthread_cancel_delayed_work_sync(mywork);
# include <linux/kthread.h>

bool kthread_mod_delayed_work(struct kthread_worker *worker, struct kthread_delayed_work *dwork, unsigned long delay);
  • where

    • kthread_mod_delayed_work : modify delay of kthread delayed work

    • worker: kthread worker to use

    • dwork: delayed work to queue

    • delay: number of jiffies to wait before queuing

    • return type: return false if dwork is queued or idle, true otherwise.

  • Here is an example of how to use the API,

kthread_mod_delayed_work(myworker,mywork,msecs_to_jiffies(10));
#include <linux/kthread.h>

void kthread_destroy_worker(struct kthread_worker *worker);
  • where

#include <linux/kthread.h>

bool kthread_should_stop(void);
  • where

    • kthread_should_stop: this is used to determine whether the thread should return now Whenever the kthread_stop() is called it will be woken and returns true.

    • return type: returns true when the thread is stopped, false when the thread is still in execution

  • Here is an example of how to use the API,

while (!kthread_should_stop())
{
    //add the instructions to be performed during thread execution.
}
  • Here is the prototype of module paramter APIs

#include <linux/module.h>

#define MODULE_LICENSE(_license) MODULE_FILE MODULE_INFO(license, _license)
#define MODULE_AUTHOR(_author) MODULE_INFO(author, _author)
#define MODULE_DESCRIPTION(_description) MODULE_INFO(description, _description)
  • where

    • MODULE_LICENSE: tells the kernel what license is used by our module.

    • MODULE_AUTHOR: denotes the author of this kernel module.

    • MODULE_DESCRIPTION: gives a basic idea about what the kernel module does.

    • These information can be found when modinfo command is used which lists out all these above mentioned information.

  • Here is the example of how to use the Module parameter APIs,

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Linux Usr");
MODULE_DESCRIPTION("Sample kernel module");
  • Here is the prototype of the API: IS_ERR

#include <linux/err.h>

static inline bool __must_check IS_ERR(__force const void *ptr);
  • where

    • IS_ERR: Detects an error pointer

    • return type: return true if it’s an error pointer else return false.

    • ptr: pointer which needs to detected.

  • Here is an example of how to use the API,

if(IS_ERR(sample_ptr)) {
    //instructions to be executed when error ptr is detected
} else {
    //instructions to be executed when error ptr is not detected
}
#include <linux/kernel.h>

#define container_of(ptr, type, member) ({                  \
    const typeof(((type *)0)->member) * __mptr = (ptr);     \
    (type *)((char *)__mptr - offsetof(type, member)); })
#endif
  • where

    • container_of : cast a member of the structure to the containing structure.

    • ptr: the pointer to the member

    • type: the type of container struct this is embedded in

    • member: the name of the member within the struct

  • Here is an example of how to use the API,

container_of(myptr,struct mysamplestruct,samplemember);
  • Here is the prototype of the API: kmalloc

#include <linux/slab.h>

void *kmalloc(size_t size, gfp_t gfp);
  • where

    • kmalloc: allocate kernel memory

    • size: how many bytes of memory is required

    • flags: describle the allocation context

  • Here is an example of how to use the API,

kmalloc(sizeof(struct mystruct),GFP_KERNEL);
  • Here is the prototype of the API: pr_info

#include <linux/printk.h>

#define pr_info(fmt, ...) \
    printk(KERN_INFO pr_fmt(fmt), ##__VA_ARGS__)
  • where

    • pr_info: Prints an info-level messages

    • fmt: format string

  • Here is an example of how to use the API,

pr_info("//sample print statement");
#include <linux/sched.h>

extern int wake_up_process(struct task_struct *tsk);
  • where

    • wake_up_process: wake up a specific process

    • return type: returns 1 if the process is woken up, 0 if the process is in running state.

    • tsk: process to be woken up.

  • Here is the example of how to use the API,

wake_up_process(mythread);
#include <linux/jiffies.h>

static __always_inline unsigned long msecs_to_jiffies(const unsigned int m);
  • where

    • msecs_to_jiffies : convert milliseconds to jiffies

    • m: time in milliseconds

    • return type: returns jiffies values

  • Here is the example of the API: msleep

#include <linux/delay.h>

void msleep(unsigned int msecs);
  • where

    • msleep: will put it in sleep for a certain amount of msecs time.

    • msecs: time in milliseconds to sleep for

  • Here is the example of how to use the API,

msleep(1000);
  • Here is the prototype of the Driver entry point API’s

#include <linux/module.h>

#define module_init(x)      __initcall(x);
#define module_exit(x)      __exitcall(x);
  • where

    • module_init: driver initialization entry point which will be called at module insertion time.

    • module_exit: driver exit entry point which will be called during the removal of module.

    • x:
      • function to be run at module insertion for module_init function.

      • function to be run when driver is removed for module_exit function.

  • Here is an example of how to use the driver entry point API’s

module_init(myinitmodule);
module_exit(myexitmodule);
  • In this example let’s see how to create kthread delayed work using kthread_init_delayed_work and execute it.

  • Include the follow header files(.h) to refer the API being used for the execution.

#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/kthread.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/jiffies.h>
  • Add the following module macros to display information about the license, author and description about the module.

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Linux Usr");
MODULE_DESCRIPTION("Example of kthread_init_delayed_work");
  • Declare the thread variables which we are going to create and use in this example

bool ret_val;
static struct task_struct *my_thread;
static struct kthread_worker *worker;
struct my_work {
    struct kthread_delayed_work my_kthread_delayed_work;
    int i;
};
  • Add the module init function which will be executed once we load the kernel module using insmod command.

static int __init kthread_init_delayed_work_init(void)
{
    pr_info("Inside kthread init function\n");
    thread_start();
    return 0;
}
  • Add the thread start function which creates kthread, on success creation it starts executing the task.

void thread_start(void)
{
    my_thread = kthread_run(def_thread_fun,NULL,"kthread_init_delayed_work_init thread example");
    if(IS_ERR(my_thread))
        pr_info("Error creating thread\n");
    else
        pr_info("Created kthread\n");
}
  • Add the module exit function which will be executed once we unload the kernel module using rmmod command.

static void __exit kthread_init_delayed_work_exit(void)
{
    pr_info("Inside kthread exit function\n");
    thread_stop();
}
  • Add the thread stop function which destroys the thread and stops the execution.

void thread_stop(void)
{
    if(my_thread) {
        kthread_stop(my_thread);
        kthread_destroy_worker(worker);
        pr_info("Destroyed kthread and worker");
    }
}
  • Add the thread function API which will be called as soon as the kthread is created and is in running state.

int def_thread_fun(void *data)
{
    struct my_work my_def_work;
    kthread_init_delayed_work(&my_def_work.my_kthread_delayed_work,def_delayed_work_function);
    pr_info("Initializing kthread work\n");
    worker = kthread_create_worker(0,"kthread_init_delayed_work_init worker example");
    if (IS_ERR(worker))
        pr_info("Error creating worker\n");
    else
        pr_info("Created kthread worker\n");
    ret_val = kthread_queue_delayed_work(worker,&my_def_work.my_kthread_delayed_work,msecs_to_jiffies(10));
    if (ret_val)
        pr_info("Queue the work to worker\n");
    else
        pr_info("queue is pending\n");
    while (!kthread_should_stop()) {
        pr_info("thread_execution\n");
        msleep(100);
    }
    return 0;
}
  • Add the work function which is executed once the work is queued to kthread_worker.

void def_delayed_work_function(struct kthread_work *work)
{
    struct my_work *my_data;
    my_data = kmalloc(sizeof(struct my_work*),GFP_KERNEL);
    pr_info("Inside work function\n");
    my_data->i = 0;
    while (my_data->i <= 10) {
        pr_info("my_data->i = %d\n",my_data->i);
        my_data->i++;
    }
}
  • Add the driver entry points which will be executed once the module is inserted or removed from the kernel.

module_init(kthread_init_delayed_work_init);
module_exit(kthread_init_delayed_work_exit);
  1#include <linux/init.h>
  2#include <linux/kernel.h>
  3#include <linux/module.h>
  4#include <linux/kthread.h>
  5#include <linux/slab.h>
  6#include <linux/delay.h>
  7#include <linux/jiffies.h>
  8
  9MODULE_LICENSE("GPL");
 10MODULE_AUTHOR("Linux usr");
 11MODULE_DESCRIPTION("Kthread test case 8");
 12
 13bool ret_val;
 14static struct task_struct *my_thread;
 15static struct kthread_worker *worker;
 16struct my_work {
 17	struct kthread_delayed_work my_kthread_delayed_work;
 18	int i;
 19};
 20
 21/* def_delayed_work_function - executes when delayed_work is added to worker queue,
 22 * prints a message and sleeps for 100ms,
 23 * stops its execution when my_data->i reaches 10*/
 24
 25void def_delayed_work_function(struct kthread_work *work)
 26{
 27	struct my_work *my_data; 
 28	my_data = kmalloc(sizeof(struct my_work*),GFP_KERNEL);
 29    pr_info("Inside work function\n");
 30	my_data->i = 0;
 31	while (my_data->i <= 10) {
 32		pr_info("my_data->i = %d\n",my_data->i);
 33		my_data->i++;
 34        msleep(100);
 35	}
 36}
 37
 38/* def_thread_fun - executes when thread is created,
 39 * creates worker,delayed work and adds the work to worker queue,
 40 * prints a message and sleeps for 100ms,
 41 * stops when kthread_stop is called */
 42
 43int def_thread_fun(void *data)
 44{
 45	struct my_work my_def_work;
 46	kthread_init_delayed_work(&my_def_work.my_kthread_delayed_work,def_delayed_work_function);
 47	pr_info("Initializing kthread work\n");
 48	worker = kthread_create_worker(0,"kthread_init_delayed_work_init worker example");
 49	if (IS_ERR(worker))
 50		pr_info("Error creating worker\n");
 51    else
 52	    pr_info("Created kthread worker\n");
 53	ret_val = kthread_queue_delayed_work(worker,&my_def_work.my_kthread_delayed_work,msecs_to_jiffies(10));
 54    if (ret_val)
 55        pr_info("Queue the work to worker\n");
 56    else
 57        pr_info("queue is pending\n");
 58    while (!kthread_should_stop()) {
 59        pr_info("thread_execution\n");
 60        msleep(100);
 61    }
 62	return 0;
 63}
 64
 65/* thread_start - creates thread and starts execution */
 66
 67void thread_start(void)
 68{
 69    my_thread = kthread_run(def_thread_fun,NULL,"kthread_init_delayed_work_init thread example");
 70    if(IS_ERR(my_thread))
 71        pr_info("Error creating thread\n");
 72    else
 73        pr_info("Created kthread\n");
 74}
 75
 76/* kthread_init_delayed_work - calls thread_start function,
 77 * executes when module is loaded */
 78
 79static int __init kthread_init_delayed_work_init(void)
 80{
 81	pr_info("Inside kthread_init function\n");	
 82	thread_start();
 83    return 0;
 84}
 85
 86/* thread_stop - destroys thread,worker and stops execution */
 87
 88void thread_stop(void)
 89{
 90    if(my_thread) {
 91        kthread_stop(my_thread);
 92        kthread_destroy_worker(worker);
 93        pr_info("Destroyed kthread and worker");
 94    }
 95}
 96
 97/* kthread_init_delayed_work_exit - calls thread_stop,
 98 * executes when the module is unloaded */
 99
100static void __exit kthread_init_delayed_work_exit(void)
101{
102	pr_info("Inside kthread exit function\n");
103    thread_stop();
104}
105
106module_init(kthread_init_delayed_work_init);
107module_exit(kthread_init_delayed_work_exit);
1obj-m += kthread.o
2
3all:
4	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
5
6clean:
7	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
  • Run make to compile the kernel source and generate the .ko image.

make -C /lib/modules/6.7.9/build M=$HOME/kthread_examples/
make[1]: Entering directory '/usr/src/linux-headers-6.7.9'
warning: the compiler differs from the one used to build the kernel
The kernel was built by: x86_64-linux-gnu-gcc (Ubuntu 12.2.0-3ubuntu1) 12.2.0
You are using:           gcc (Ubuntu 12.2.0-3ubuntu1) 12.2.0
CC [M]  $HOME/kthread_examples/kthread.o
MODPOST $HOME/kthread_examples/Module.symvers
CC [M]  $HOME/kthread_examples/kthread.mod.o
LD [M]  $HOME/kthread_examples/kthread.ko
BTF [M] $HOME/kthread_examples/kthread.ko
Skipping BTF generation for $HOME/kthread_examples/kthread.ko due to unavailability of vmlinux
make[1]: Leaving directory '/usr/src/linux-headers-6.7.9'
  • Check if the .ko is generated or not using ls command.

test@test-V520-15IKL:~$ ls -l
total 360
-rw-rw-r-- 1 test test    713 Mar 18 16:06 kthread.c
-rw-rw-r-- 1 test test 169784 Mar 18 16:08 kthread.ko
-rw-rw-r-- 1 test test     58 Mar 18 16:08 kthread.mod
-rw-rw-r-- 1 test test   1047 Mar 18 16:08 kthread.mod.c
-rw-rw-r-- 1 test test  96512 Mar 18 16:08 kthread.mod.o
-rw-rw-r-- 1 test test  74696 Mar 18 16:08 kthread.o
-rw-rw-r-- 1 test test    161 Mar 18 16:00 Makefile
-rw-rw-r-- 1 test test     58 Mar 18 16:08 modules.order
-rw-rw-r-- 1 test test      0 Mar 18 16:08 Module.symvers
  • Run modinfo command to get the information about the kernel module.

test@test-V520-15IKL:~/.../tc_1$ modinfo kthread.ko
filename:       $HOME/kthread_examples/kthread.ko
description:    Example of kthread_init_delayed_work
author:         Linux Usr
license:        GPL
srcversion:     8D2147F67AB01CF0E482DAC
depends:
retpoline:      Y
name:           kthread
vermagic:       6.7.9 SMP preempt mod_unload modversions
  • insert the module using insmod command.

test@test-V520-15IKL:~$ sudo insmod ./kthread.ko
  • check if the module is loaded or not using lsmod command.

test@test-V520-15IKL:~$ sudo lsmod | grep kthread
kthread                16384  0
  • check if the thread is created or not using ps command.

test@test-V520-15IKL:~$ ps -N | grep kthread_init_delayed_work
11404 ?        00:00:00 kthread_init_delayed_work_init thread example
11405 ?        00:00:00 kthread_init_delayed_work_init worker example
  • check for the kernel messages from init function and thread function once the module is loaded and thread is created.

test@test-V520-15IKL:~$ sudo dmesg
[11715.486700] Inside kthread_init function
[11715.486727] Created kthread
[11715.486728] Initializing kthread work
[11715.486743] Created kthread worker
[11715.486744] Queue the work to worker
[11715.486744] thread_execution
[11715.499090] Inside work function
[11715.499091] my_data->i = 0
[11715.591078] thread_execution
[11715.607082] my_data->i = 1
[11715.698965] thread_execution
[11715.715088] my_data->i = 2
  • remove the module from kernel using rmmod command.

test@test-V520-15IKL:~$ sudo rmmod kthread
  • check if the module is still loaded after removing the kernel module using lsmod if it is not displayed in lsmod output it is verified that the module is removed successfully.

test@test-V520-15IKL:~$ sudo lsmod | grep kthread
test@test-V520-15IKL:~$
  • check if the thread is destroyed using ps command if it is not displayed in ps output we can confirm that the thread is destroyed successfully.

test@test-V520-15IKL:~$ ps -N | grep kthread_init_work
test@test-V520-15IKL:~$
  • Check for kernel messages from exit function using dmesg command.

test@test-V520-15IKL:~$ sudo dmesg
[11723.785020] Inside kthread exit function
[11723.811440] Destroyed kthread and worker
  • In this example let’s see how to cancel kthread_delayed_work using kthread_cancel_delayed_work_sync.

  • Include the follow header files(.h) to refer the API being used for the execution.

#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/kthread.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/jiffies.h>
  • Add the following module macros to display information about the license, author and description about the module.

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Linux Usr");
MODULE_DESCRIPTION("Example of kthread_cancel_delayed_work_sync");
  • Declare the thread variables which we are going to create and use in this example

bool ret_val;
static struct task_struct *my_thread;
static struct kthread_worker *worker;
struct my_work {
    struct kthread_delayed_work my_kthread_delayed_work;
    int i;
};
  • Add the module init function which will be executed once we load the kernel module using insmod command.

static int __init kthread_cancel_delayed_work_sync_init(void)
{
    pr_info("Inside kthread init function\n");
    thread_start();
    return 0;
}
  • Add the thread start function in which the worker and thread is created and starts its execution.

void thread_start(void)
{
    my_thread = kthread_run(def_thread_fun,NULL,"kthread_cancel_work_sync thread example");
    if(IS_ERR(my_thread))
        pr_info("Error creating kthread\n");
    else
        pr_info("Created kthread\n");
}
  • Add the module exit function which will be executed once we unload the kernel module using rmmod command.

static void __exit kthread_cancel_delayed_work_sync_exit(void)
{
    pr_info("Inside kthread exit function\n");
    thread_stop();
}
  • Add the thread stop function in which worker is destroyed and the thread stops its execution.

void thread_stop(void)
{
    if(my_thread) {
        kthread_stop(my_thread);
        kthread_destroy_worker(worker);
        pr_info("Destroyed kthread and worker");
    }
}
  • Add the thread function API which will be called as soon as the kthread is created and is in running state.

int def_thread_fun(void *data)
{
    struct my_work my_def_work;
    kthread_init_work(&my_def_work.my_kthread_work,def_work_function);
    pr_info("Initializing kthread work\n");
    worker = kthread_create_worker(0,"kthread_cancel_work_sync worker example");
    if (IS_ERR(worker))
        pr_info("Error creating worker\n");
    else
        pr_info("Created kthread worker\n");
    ret_val = kthread_queue_delayed_work(worker,&my_def_work.my_kthread_delayed_work,msecs_to_jiffies(10));
    if (ret_val)
        pr_info("Queue the work to worker\n");
    else
        pr_info("Work is in pending state");
    while (!kthread_should_stop()) {
        pr_info("thread execution\n");
        msleep(1000);
        kthread_cancel_delayed_work_sync(&my_def_work.my_kthread_delayed_work);
        msleep(100);
    }
    pr_info("Cancel the kthread delayed work\n");
    return 0;
}
  • Add the work function which will be executed once kthread_work is queued to kthread_worker.

void def_work_function(struct kthread_work *work)
{
    struct my_work *my_data;
    my_data = kmalloc(sizeof(struct my_work*),GFP_KERNEL);
    pr_info("Inside work function\n");
    my_data->i = 0;
    while (my_data->i <= 10) {
        pr_info("my_data->i = %d\n",my_data->i);
        my_data->i++;
        msleep(100);
    }
}
  • Add the driver entry points which will be executed once the module is inserted or removed from the kernel.

module_init(kthread_cancel_delayed_work_sync_init);
module_exit(kthread_cancel_delayed_work_sync_exit);
  1#include <linux/init.h>
  2#include <linux/kernel.h>
  3#include <linux/module.h>
  4#include <linux/kthread.h>
  5#include <linux/slab.h>
  6#include <linux/delay.h>
  7#include <linux/jiffies.h>
  8
  9MODULE_LICENSE("GPL");
 10MODULE_AUTHOR("Linux usr");
 11MODULE_DESCRIPTION("Example of kthread_cancel_delayed_work_sync");
 12
 13bool ret_val;
 14static struct task_struct *my_thread;
 15static struct kthread_worker *worker;
 16struct my_work {
 17	struct kthread_delayed_work my_kthread_delayed_work;
 18	int i;
 19};
 20
 21/* def_delayed_work - executes when delayed work is queued to worker,
 22 * prints a message and sleeps for 100ms,
 23 * stops when my_data->i reaches 10*/
 24
 25void def_delayed_work_function(struct kthread_work *work)
 26{
 27	struct my_work *my_data; 
 28	my_data = kmalloc(sizeof(struct my_work*),GFP_KERNEL);
 29    pr_info("Inside work function\n");
 30	my_data->i = 0;
 31	while (my_data->i <= 10) {
 32		pr_info("my_data->i = %d\n",my_data->i);
 33		my_data->i++;
 34        msleep(100);
 35	}
 36}
 37
 38/* def_thread_fun - executes when thread is created,
 39 * creates thread,worker,delayed_work and queues the work to worker,
 40 * prints a message and sleeps for 100ms,
 41 * stops when kthread_stop is called*/
 42
 43int def_thread_fun(void *data)
 44{
 45	struct my_work my_def_work;
 46	kthread_init_delayed_work(&my_def_work.my_kthread_delayed_work,def_delayed_work_function);
 47	pr_info("Initializing kthread work\n");
 48	worker = kthread_create_worker(0,"kthread_cancel_delayed_work_sync worker example");
 49	if (IS_ERR(worker))
 50		pr_info("Error creating worker\n");
 51    else
 52	    pr_info("Creating kthread worker\n");
 53	ret_val = kthread_queue_delayed_work(worker,&my_def_work.my_kthread_delayed_work,msecs_to_jiffies(10));
 54    if (ret_val)
 55        pr_info("Queue the work to worker\n");
 56    else
 57        pr_info("work is pending\n");
 58    while(!kthread_should_stop()) {
 59        pr_info("thread execution\n");
 60        msleep(1000);
 61	    kthread_cancel_delayed_work_sync(&my_def_work.my_kthread_delayed_work);
 62        msleep(100);
 63    }
 64	pr_info("Cancel the kthread delayed work\n");
 65	return 0;
 66}
 67
 68/* thread_start - creates thread and starts execution*/
 69
 70void thread_start(void)
 71{
 72    my_thread = kthread_run(def_thread_fun,NULL,"kthread_cancel_delayed_work_sync thread example");
 73    if(IS_ERR(my_thread))
 74        pr_info("Error creating thread\n");
 75    else
 76        pr_info("Created kthread\n");
 77}
 78
 79/* kthread_cancel_delayed_work_sync_init - calls thread_start function,
 80 * executes when module is loaded */
 81
 82static int __init kthread_cancel_delayed_work_sync_init(void)
 83{
 84	pr_info("Inside kthread_init function\n");	
 85	thread_start();
 86    return 0;
 87}
 88
 89/* thread_stop - destroys thread,worker and stops execution*/
 90
 91void thread_stop(void)
 92{
 93    if(my_thread) {
 94        kthread_stop(my_thread);
 95        kthread_destroy_worker(worker);
 96        pr_info("Destroyed kthread and worker");
 97    }
 98}
 99
100/* kthread_cancel_delayed_work_sync_exit - calls thread_stop function,
101 * executes when module is unloaded */
102
103static void __exit kthread_cancel_delayed_work_sync_exit(void)
104{
105	pr_info("Destroying kthread\n");
106    thread_stop();
107}
108
109module_init(kthread_cancel_delayed_work_sync_init);
110module_exit(kthread_cancel_delayed_work_sync_exit);
1obj-m += kthread.o
2
3all:
4	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
5
6clean:
7	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
  • Run make to compile the kernel source and generate the .ko image.

make -C /lib/modules/6.7.9/build M=$HOME/kthread_examples/
make[1]: Entering directory '/usr/src/linux-headers-6.7.9'
warning: the compiler differs from the one used to build the kernel
The kernel was built by: x86_64-linux-gnu-gcc (Ubuntu 12.2.0-3ubuntu1) 12.2.0
You are using:           gcc (Ubuntu 12.2.0-3ubuntu1) 12.2.0
CC [M]  $HOME/kthread_examples/kthread.o
MODPOST $HOME/kthread_examples/Module.symvers
CC [M]  $HOME/kthread_examples/kthread.mod.o
LD [M]  $HOME/kthread_examples/kthread.ko
BTF [M] $HOME/kthread_examples/kthread.ko
Skipping BTF generation for $HOME/kthread_examples/kthread.ko due to unavailability of vmlinux
make[1]: Leaving directory '/usr/src/linux-headers-6.7.9'
  • Check if the .ko is generated or not using ls command.

test@test-V520-15IKL:~$ ls -l
total 360
-rw-rw-r-- 1 test test    713 Mar 18 16:06 kthread.c
-rw-rw-r-- 1 test test 169784 Mar 18 16:08 kthread.ko
-rw-rw-r-- 1 test test     58 Mar 18 16:08 kthread.mod
-rw-rw-r-- 1 test test   1047 Mar 18 16:08 kthread.mod.c
-rw-rw-r-- 1 test test  96512 Mar 18 16:08 kthread.mod.o
-rw-rw-r-- 1 test test  74696 Mar 18 16:08 kthread.o
-rw-rw-r-- 1 test test    161 Mar 18 16:00 Makefile
-rw-rw-r-- 1 test test     58 Mar 18 16:08 modules.order
-rw-rw-r-- 1 test test      0 Mar 18 16:08 Module.symvers
  • Run modinfo command to get the information about the kernel module.

test@test-V520-15IKL:~/.../tc_1$ modinfo kthread.ko
filename:       $HOME/kthread_examples/kthread.ko
description:    Example of kthread_cancel_delayed_work_sync
author:         Linux Usr
license:        GPL
srcversion:     8D2147F67AB01CF0E482DAC
depends:
retpoline:      Y
name:           kthread
vermagic:       6.7.9 SMP preempt mod_unload modversions
  • insert the module using insmod command.

test@test-V520-15IKL:~$ sudo insmod ./kthread.ko
  • check if the module is loaded or not using lsmod command.

test@test-V520-15IKL:~$ sudo lsmod | grep kthread
kthread                16384  0
  • check if the thread is created or not using ps command.

test@test-V520-15IKL:~$ ps -N | grep kthread_cancel_delayed_work_sync
14117 ?        00:00:00 kthread_cancel_delayed_work_sync thread example
14118 ?        00:00:00 kthread_cancel_delayed_work_sync worker example
  • check for the kernel messages from init function and thread function once the module is loaded and thread is created.

test@test-V520-15IKL:~$ sudo dmesg
[14116.036297] Inside kthread_init function
[14116.036322] Created kthread
[14116.036324] Initializing kthread work
[14116.036371] Creating kthread worker
[14116.036373] Queue the work to worker
[14116.036373] thread execution
[14116.051054] Inside work function
[14116.051060] my_data->i = 0
[14116.159099] my_data->i = 1
[14116.267063] my_data->i = 2
  • remove the module from kernel using rmmod command.

test@test-V520-15IKL:~$ sudo rmmod kthread
  • check if the module is still loaded after removing the kernel module using lsmod if it is not displayed in lsmod output it is verified that the module is removed successfully.

test@test-V520-15IKL:~$ sudo lsmod | grep kthread
test@test-V520-15IKL:~$
  • check if the thread is destroyed using ps command if it is not displayed in ps output we can confirm that the thread is destroyed successfully.

test@test-V520-15IKL:~$ ps -N | grep kthread_cancel_work_sync
test@test-V520-15IKL:~$
  • Check for kernel messages from exit function using dmesg command.

test@test-V520-15IKL:~$ sudo dmesg
[14118.693977] Destroying kthread
[14119.599136] Cancel the kthread delayed work
[14119.599537] Destroyed kthread and worker
  • In this example let’s see how to modify delay of work using kthread_mod_delayed_work

  • Include the follow header files(.h) to refer the API being used for the execution.

#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/kthread.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/jiffies.h>
  • Add the following module macros to display information about the license, author and description about the module.

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Linux Usr");
MODULE_DESCRIPTION("example of kthread_mod_delayed_work");
  • Declare the thread variables which we are going to create and use in this example

bool ret_val;
static struct task_struct *my_thread;
static struct kthread_worker *my_worker;
struct my_work {
    struct kthread_work my_kthread_delayed_work;
    int i;
};
  • Add the module init function which will be executed once we load the kernel module using insmod command.

static int __init kthread_mod_delayed_work_init(void)
{
    pr_info("Inside kthread init function\n");
    thread_start();
    return 0;
}
  • Add the thread start function in which the thread is created and starts its execution.

void thread_start(void)
{
    my_thread = kthread_run(my_thread_fun,NULL,"kthread_mod_delayed_work thread example");
    if (IS_ERR(my_thread))
        pr_info("Error in creating thread\n");
    else
        pr_info("Created Thread\n");
}
  • Add the module exit function which will be executed once we unload the kernel module using rmmod command.

static void __exit kthread_mod_delayed_work_exit(void)
{
    pr_info("Inside kthread exit function\n");
    thread_stop();
}
  • Add the thread stop function which destroys worker,thread and stops the execution.

void thread_stop(void)
{
    if (my_thread) {
        kthread_stop(my_thread);
        kthread_destroy_worker(my_worker);
        pr_info("Destroyed threads and worker\n");
    }
}
  • Add the thread function API which will be called as soon as the kthread is created and is in running state.

int def_thread_fun(void *data)
{
    struct my_work my_def_work;
    kthread_init_delayed_work(&my_def_work.my_kthread_delayed_work,def_delayed_work_function);
    pr_info("Initializing kthread work\n");
    worker = kthread_create_worker(0,"kthread_mod_delayed_work worker example");
    if (IS_ERR(worker))
        pr_info("Error creating worker\n");
    else
        pr_info("Created kthread worker\n");
    ret_val  = kthread_queue_delayed_work(worker,&my_def_work.my_kthread_delayed_work,msecs_to_jiffies(5000));
    if (ret_val)
        pr_info("Queue the work to worker\n");
    else
        pr_info("Work is pending\n");
    while (!kthread_should_stop()) {
        pr_info("thread execution\n");
        ret_val = kthread_cancel_delayed_work_sync(&my_def_work.my_kthread_delayed_work);
        if (!ret_val) {
            kthread_mod_delayed_work(worker,&my_def_work.my_kthread_delayed_work,msecs_to_jiffies(10));
            pr_info("Modified the time delay for the queued work\n");
            msleep(1000);
            kthread_stop(my_thread);
        }
    }
    return 0;
}
  • Add the work function API which is executed once the work is queued to worker.

void def_delayed_work_function(struct kthread_work *work)
{
    struct my_work *my_data;
    my_data = kmalloc(sizeof(struct my_work*),GFP_KERNEL);
    pr_info("Inside work function\n");
    my_data->i = 0;
    while (my_data->i <= 10) {
        pr_info("my_data->i = %d\n",my_data->i);
        my_data->i++;
    }
}
  • Add the driver entry points which will be executed once the module is inserted or removed from the kernel.

module_init(kthread_mod_delayed_work_init);
module_exit(kthread_mod_delayed_work_exit);
  1#include <linux/init.h>
  2#include <linux/kernel.h>
  3#include <linux/module.h>
  4#include <linux/kthread.h>
  5#include <linux/slab.h>
  6#include <linux/delay.h>
  7#include <linux/jiffies.h>
  8
  9MODULE_LICENSE("GPL");
 10MODULE_AUTHOR("Linux usr");
 11MODULE_DESCRIPTION("Example of kthread_mod_delayed_work");
 12
 13bool ret_val;
 14static struct task_struct *my_thread;
 15static struct kthread_worker *worker;
 16struct my_work {
 17	struct kthread_delayed_work my_kthread_delayed_work;
 18	int i;
 19};
 20
 21/* def_delayed_work_function - executes when work is queued to worker,
 22 * prints a messages and increments my_data->i value,
 23 * stops when my_data->i value reaches 10 */
 24
 25void def_delayed_work_function(struct kthread_work *work)
 26{
 27	struct my_work *my_data; 
 28	my_data = kmalloc(sizeof(struct my_work*),GFP_KERNEL);
 29    pr_info("Inside work function\n");
 30	my_data->i = 0;
 31	while (my_data->i <= 10) {
 32		pr_info("my_data->i = %d\n",my_data->i);
 33		my_data->i++;
 34	}
 35}
 36
 37/*def_thread_fun - executes when thread is created,
 38 * creates worker,work and queue the work to worker,
 39 * cancel the work and wait for its completion,
 40 * try modifying the delay timer using kthread_mod_delayed_work,
 41 * once the timer is modifier thread execution stops */
 42
 43int def_thread_fun(void *data)
 44{
 45	struct my_work my_def_work;
 46	kthread_init_delayed_work(&my_def_work.my_kthread_delayed_work,def_delayed_work_function);
 47	pr_info("Initializing kthread work\n");
 48	worker = kthread_create_worker(0,"kthread_mod_delayed_work worker example");
 49	if (IS_ERR(worker))
 50		pr_info("Error creating worker\n");
 51    else
 52	    pr_info("Created kthread worker\n");
 53	ret_val  = kthread_queue_delayed_work(worker,&my_def_work.my_kthread_delayed_work,msecs_to_jiffies(5000));
 54	if (ret_val)
 55        pr_info("Queue the work to worker\n");
 56    else
 57        pr_info("Work is pending\n");
 58    while (!kthread_should_stop()) {
 59        pr_info("thread execution\n");
 60        ret_val = kthread_cancel_delayed_work_sync(&my_def_work.my_kthread_delayed_work);
 61        if (!ret_val) {
 62	        kthread_mod_delayed_work(worker,&my_def_work.my_kthread_delayed_work,msecs_to_jiffies(10));
 63	        pr_info("Modified the time delay for the queued work\n");
 64            msleep(1000);
 65            kthread_stop(my_thread);
 66        }
 67    }
 68	return 0;
 69}
 70
 71/* thread_start - creates thread and starts execution */
 72
 73void thread_start(void)
 74{
 75    my_thread = kthread_run(def_thread_fun,NULL,"kthread_mod_delayed_work thread example");
 76    if(IS_ERR(my_thread))
 77        pr_info("Error creating thread\n");
 78    else
 79        pr_info("Created kthread\n");
 80}
 81
 82/* kthread_mod_delayed_work_init - calls thread_start function,
 83 * executes when module is loaded */
 84
 85static int __init kthread_mod_delayed_work_init(void)
 86{
 87	pr_info("Inside kthread_init function\n");	
 88	thread_start();
 89    return 0;
 90}
 91
 92/* thread_stop - destroys worker and stops execution */
 93
 94void thread_stop(void)
 95{
 96    if(my_thread) {
 97        kthread_destroy_worker(worker);
 98        pr_info("Destroyed kthread and worker");
 99    }
100}
101
102/* kthread_mod_delayed_work_exit - calls thread_stop,
103 * executes when module is unloaded */
104
105static void __exit kthread_mod_delayed_work_exit(void)
106{
107	pr_info("Inside kthread_exit function\n");
108    thread_stop();
109}
110
111module_init(kthread_mod_delayed_work_init);
112module_exit(kthread_mod_delayed_work_exit);
1obj-m += kthread.o
2
3all:
4	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
5
6clean:
7	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
  • Run make to compile the kernel source and generate the .ko image.

make -C /lib/modules/6.7.9/build M=$HOME/kthread_examples/
make[1]: Entering directory '/usr/src/linux-headers-6.7.9'
warning: the compiler differs from the one used to build the kernel
The kernel was built by: x86_64-linux-gnu-gcc (Ubuntu 12.2.0-3ubuntu1) 12.2.0
You are using:           gcc (Ubuntu 12.2.0-3ubuntu1) 12.2.0
CC [M]  $HOME/kthread_examples/kthread.o
MODPOST $HOME/kthread_examples/Module.symvers
CC [M]  $HOME/kthread_examples/kthread.mod.o
LD [M]  $HOME/kthread_examples/kthread.ko
BTF [M] $HOME/kthread_examples/kthread.ko
Skipping BTF generation for $HOME/kthread_examples/kthread.ko due to unavailability of vmlinux
make[1]: Leaving directory '/usr/src/linux-headers-6.7.9'
  • Check if the .ko is generated or not using ls command.

test@test-V520-15IKL:~$ ls -l
total 360
-rw-rw-r-- 1 test test    713 Mar 18 16:06 kthread.c
-rw-rw-r-- 1 test test 169784 Mar 18 16:08 kthread.ko
-rw-rw-r-- 1 test test     58 Mar 18 16:08 kthread.mod
-rw-rw-r-- 1 test test   1047 Mar 18 16:08 kthread.mod.c
-rw-rw-r-- 1 test test  96512 Mar 18 16:08 kthread.mod.o
-rw-rw-r-- 1 test test  74696 Mar 18 16:08 kthread.o
-rw-rw-r-- 1 test test    161 Mar 18 16:00 Makefile
-rw-rw-r-- 1 test test     58 Mar 18 16:08 modules.order
-rw-rw-r-- 1 test test      0 Mar 18 16:08 Module.symvers
  • Run modinfo command to get the information about the kernel module.

test@test-V520-15IKL:~/.../tc_1$ modinfo kthread.ko
filename:       $HOME/kthread_examples/kthread.ko
description:    Example of kthread_mod_delayed_work
author:         Linux Usr
license:        GPL
srcversion:     8D2147F67AB01CF0E482DAC
depends:
retpoline:      Y
name:           kthread
vermagic:       6.7.9 SMP preempt mod_unload modversions
  • insert the module using insmod command.

test@test-V520-15IKL:~$ sudo insmod ./kthread.ko
  • check if the module is loaded or not using lsmod command.

test@test-V520-15IKL:~$ sudo lsmod | grep kthread
kthread                16384  0
  • check if the thread is created or not using ps command.

test@test-V520-15IKL:~$ ps -N | grep kthread_mod_delayed_work
5207 ?        00:00:00 kthread_mod_delayed_work thread example
5208 ?        00:00:00 kthread_mod_delayed_work worker example
  • check for the kernel messages from init function and thread function once the module is loaded and thread is created.

test@test-V520-15IKL:~$ sudo dmesg
[  665.913373] Inside kthread_init function
[  665.913463] Created kthread
[  665.913469] Initializing kthread work
[  665.913518] Created kthread worker
[  665.913521] Queue the work to worker
[  665.913526] thread execution
[  665.913529] thread execution
[  665.913530] Modified the time delay for the queued work
[  665.930962] Inside work function
[  665.930967] my_data->i = 0
[  665.930970] my_data->i = 1
[  665.930972] my_data->i = 2
  • remove the module from kernel using rmmod command.

test@test-V520-15IKL:~$ sudo rmmod kthread
  • check if the module is still loaded after removing the kernel module using lsmod if it is not displayed in lsmod output it is verified that the module is removed successfully.

test@test-V520-15IKL:~$ sudo lsmod | grep kthread
test@test-V520-15IKL:~$
  • check if the thread is destroyed using ps command if it is not displayed in ps output we can confirm that the thread is destroyed successfully.

test@test-V520-15IKL:~$ ps -N | grep kthread_mod_delayed_work
test@test-V520-15IKL:~$
  • Check for kernel messages from exit function using dmesg command.

test@test-V520-15IKL:~$ sudo dmesg
[  676.799621] Inside kthread_exit function
[  676.799898] Destroyed kthread and worker
  • In this example let’s see how to queue multiple delayed works using kthread_queue_delayed_work

  • Include the follow header files(.h) to refer the API being used for the execution.

#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
  • Add the following module macros to display information about the license, author and description about the module.

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Linux Usr");
MODULE_DESCRIPTION("example of kthread_queue_delayed_work");
  • Declare the thread variables which we are going to create and use in this example

bool ret_val;
static struct task_struct *my_thread;
static struct kthread_worker *my_worker;
struct my_work {
    struct kthread_work my_kthread_delayed_work;
    int i;
};
  • Add the module init function which will be executed once we load the kernel module using insmod command.

static int __init kthread_queue_delayed_work_init(void)
{
    pr_info("Inside kthread init function\n");
    thread_start();
    return 0;
}
  • Add the thread start function in which the thread is created and starts its execution.

void thread_start(void)
{
    my_thread = kthread_run(my_thread_fun,NULL,"kthread_queue_delayed_work thread example");
    if (IS_ERR(my_thread))
        pr_info("Error in creating thread\n");
    else
        pr_info("Thread created successfully\n");
}
  • Add the module exit function which will be executed once we unload the kernel module using rmmod command.

static void __exit kthread_queue_delayed_work_exit(void)
{
    pr_info("Inside kthread exit function\n");
    thread_stop();
}
  • Add the thread stop function which destroys worker,thread and stops the execution.

void thread_stop(void)
{
    if (my_thread) {
        kthread_stop(my_thread);
        kthread_destroy_worker(my_worker);
        pr_info("Destroyed threads and worker\n");
    }
}
  • Add the thread function API which will be called as soon as the kthread is created and is in running state.

int my_thread_fun(void *data)
{
    struct my_work my_def_work_1;
    struct my_work my_def_work_2;
    kthread_init_delayed_work(&my_def_work_1.my_kthread_delayed_work,def_work_fn_1);
    pr_info("kthread work 1 intialized\n");
    my_worker = kthread_create_worker(0,"kthread_queue_delayed_work worker example");
    if (IS_ERR(my_worker))
        pr_info("error in creating kthread_worker\n");
    else
        pr_info("kthread worker created\n");
    ret_val = kthread_queue_delayed_work(my_worker,&my_def_work_1.my_kthread_delayed_work,msecs_to_jiffies(1000));
    if (ret_val)
        pr_info("kthread work 1 is queued to worker\n");
    else
        pr_info("work is in pending state\n");
    kthread_init_delayed_work(&my_def_work_2.my_kthread_delayed_work,def_work_fn_2);
    pr_info("kthread_work_2_initialized\n");
    ret_val = kthread_queue_delayed_work(my_worker,&my_def_work_2.my_kthread_delayed_work,msecs_to_jiffies(10));
    if (ret_val)
        pr_info("kthread work 2 is queued to worker\n");
    else
        pr_info("work is in pending state\n");
    while(!kthread_should_stop()) {
        pr_info("thread execution\n");
        msleep(5000);
    }
    return 0;
}
  • Add the work function API which is executed once the work is queued to worker.

void def_work_fn_1(struct kthread_work *work)
{
    struct my_work *my_work_fn_1;
    my_work_fn_1 = kmalloc(sizeof(struct my_work*),GFP_KERNEL);
    pr_info("Inside work function 1\n");
    my_work_fn_1->i = 0;
    while (my_work_fn_1->i <= 3) {
        pr_info("my_work_fn_1 = %d\n",my_work_fn_1->i);
        my_work_fn_1->i++;
        msleep(100);
    }
}

void def_work_fn_2(struct kthread_work *work)
{
    struct my_work *my_work_fn_2;
    my_work_fn_2 = kmalloc(sizeof(struct my_work*),GFP_KERNEL);
    pr_info("Inside work function 2\n");
    my_work_fn_2->i=3;
    while (my_work_fn_2->i >= 0) {
        pr_info("my_work_fn_2 = %d\n",my_work_fn_2->i);
        my_work_fn_2->i--;
        msleep(100);
    }
}
  • Add the driver entry points which will be executed once the module is inserted or removed from the kernel.

module_init(kthread_queue_delayed_work_init);
module_exit(kthread_queue_delayed_work_exit);
  1#include <linux/init.h>
  2#include <linux/kernel.h>
  3#include <linux/module.h>
  4#include <linux/kthread.h>
  5#include <linux/delay.h>
  6#include <linux/jiffies.h>
  7#include <linux/slab.h>
  8
  9MODULE_LICENSE("GPL");
 10MODULE_AUTHOR("Linux Usr");
 11MODULE_DESCRIPTION("Kthread test case 12");
 12
 13bool ret_val;
 14static struct task_struct *my_thread;
 15static struct kthread_worker *my_worker;
 16struct my_work {
 17	struct kthread_delayed_work my_kthread_delayed_work;
 18	int i;
 19};
 20
 21/* def_work_fn_1 - executes when work 1 is queued to worker,
 22 * prints a message and increments my_work_fn_1->i value,
 23 * stops when the value reaches 3 */
 24
 25void def_work_fn_1(struct kthread_work *work)
 26{
 27	struct my_work *my_work_fn_1;
 28	my_work_fn_1 = kmalloc(sizeof(struct my_work*),GFP_KERNEL);
 29    pr_info("Inside work function 1\n");
 30	my_work_fn_1->i = 0;
 31	while (my_work_fn_1->i <= 3) {
 32		pr_info("my_work_fn_1 = %d\n",my_work_fn_1->i);
 33		my_work_fn_1->i++;
 34	}
 35}
 36
 37/* def_work_fn_2 - executes when work 2 is queued to worker,
 38 * prints a message and decrements my_work_fn_2->i value,
 39 * stops when value reaches 0 */
 40
 41void def_work_fn_2(struct kthread_work *work)
 42{
 43	struct my_work *my_work_fn_2;
 44	my_work_fn_2 = kmalloc(sizeof(struct my_work*),GFP_KERNEL);
 45    pr_info("Inside work function 2\n");
 46	my_work_fn_2->i=3;
 47	while (my_work_fn_2->i >= 0) {
 48		pr_info("my_work_fn_2 = %d\n",my_work_fn_2->i);
 49		my_work_fn_2->i--;
 50	}
 51}
 52
 53/* my_thread_fun - executes when thread is created,
 54 * creates worker,delayed work and queues delayed_work to worker,
 55 * prints a message and sleeps for 5000 ms,
 56 * stops when kthread_stop is called */
 57
 58int my_thread_fun(void *data)
 59{
 60	struct my_work my_def_work_1;
 61	struct my_work my_def_work_2;
 62	my_worker = kthread_create_worker(0,"kthread_queue_delayed_work worker example");
 63	if (IS_ERR(my_worker))
 64		pr_info("error in creating kthread_worker\n");
 65    else
 66	    pr_info("kthread worker created\n");
 67	kthread_init_delayed_work(&my_def_work_1.my_kthread_delayed_work,def_work_fn_1);
 68	pr_info("kthread work 1 intialized\n");
 69	ret_val = kthread_queue_delayed_work(my_worker,&my_def_work_1.my_kthread_delayed_work,msecs_to_jiffies(1000));
 70	if (ret_val)
 71        pr_info("kthread work 1 is queued to worker\n");
 72    else
 73        pr_info("work is in pending state\n");
 74	
 75    kthread_init_delayed_work(&my_def_work_2.my_kthread_delayed_work,def_work_fn_2);
 76    pr_info("kthread_work_2_initialized\n");
 77	ret_val = kthread_queue_delayed_work(my_worker,&my_def_work_2.my_kthread_delayed_work,msecs_to_jiffies(10));
 78	if (ret_val)
 79	    pr_info("kthread work 2 is queued to worker\n");
 80    else
 81        pr_info("work is in pending state\n");
 82    while(!kthread_should_stop()) {
 83        pr_info("thread execution\n");
 84        msleep(5000);
 85    }
 86	return 0;
 87}
 88
 89/* thread_start - creates thread and starts execution */
 90
 91void thread_start(void)
 92{
 93    my_thread = kthread_run(my_thread_fun,NULL,"kthread_queue_delayed_work thread example");
 94    if (IS_ERR(my_thread))
 95        pr_info("Error in creating thread\n");
 96    else
 97        pr_info("Thread created successfully\n");
 98}
 99
100/* kthread_queue_delayed_work_init - calls thread_start function,
101 * executes when module is loaded */
102
103static int __init kthread_queue_delayed_work_init(void)
104{
105	pr_info("Inside kthread init function\n");
106	thread_start();
107    return 0;
108}
109
110/* thread_stop - destroys thread and stops execution */
111
112void thread_stop(void)
113{
114    if (my_thread) {
115        kthread_stop(my_thread);
116        kthread_destroy_worker(my_worker);
117        pr_info("Destroyed threads and worker\n");
118    }
119}
120
121/* kthread_queue_delayed_work_exit - calls thread_stop,
122 * executes when module is unloaded */
123
124static void __exit kthread_queue_delayed_work_exit(void)
125{
126	pr_info("Destroying threads\n");
127    thread_stop();
128}
129
130module_init(kthread_queue_delayed_work_init);
131module_exit(kthread_queue_delayed_work_exit);
1obj-m += kthread.o
2
3all:
4	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
5
6clean:
7	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
  • Run make to compile the kernel source and generate the .ko image.

make -C /lib/modules/6.7.9/build M=$HOME/kthread_examples/
make[1]: Entering directory '/usr/src/linux-headers-6.7.9'
warning: the compiler differs from the one used to build the kernel
The kernel was built by: x86_64-linux-gnu-gcc (Ubuntu 12.2.0-3ubuntu1) 12.2.0
You are using:           gcc (Ubuntu 12.2.0-3ubuntu1) 12.2.0
CC [M]  $HOME/kthread_examples/kthread.o
MODPOST $HOME/kthread_examples/Module.symvers
CC [M]  $HOME/kthread_examples/kthread.mod.o
LD [M]  $HOME/kthread_examples/kthread.ko
BTF [M] $HOME/kthread_examples/kthread.ko
Skipping BTF generation for $HOME/kthread_examples/kthread.ko due to unavailability of vmlinux
make[1]: Leaving directory '/usr/src/linux-headers-6.7.9'
  • Check if the .ko is generated or not using ls command.

test@test-V520-15IKL:~$ ls -l
total 360
-rw-rw-r-- 1 test test    713 Mar 18 16:06 kthread.c
-rw-rw-r-- 1 test test 169784 Mar 18 16:08 kthread.ko
-rw-rw-r-- 1 test test     58 Mar 18 16:08 kthread.mod
-rw-rw-r-- 1 test test   1047 Mar 18 16:08 kthread.mod.c
-rw-rw-r-- 1 test test  96512 Mar 18 16:08 kthread.mod.o
-rw-rw-r-- 1 test test  74696 Mar 18 16:08 kthread.o
-rw-rw-r-- 1 test test    161 Mar 18 16:00 Makefile
-rw-rw-r-- 1 test test     58 Mar 18 16:08 modules.order
-rw-rw-r-- 1 test test      0 Mar 18 16:08 Module.symvers
  • Run modinfo command to get the information about the kernel module.

test@test-V520-15IKL:~/.../tc_1$ modinfo kthread.ko
filename:       $HOME/kthread_examples/kthread.ko
description:    Example of kthread_queue_delayed_work
author:         Linux Usr
license:        GPL
srcversion:     8D2147F67AB01CF0E482DAC
depends:
retpoline:      Y
name:           kthread
vermagic:       6.7.9 SMP preempt mod_unload modversions
  • insert the module using insmod command.

test@test-V520-15IKL:~$ sudo insmod ./kthread.ko
  • check if the module is loaded or not using lsmod command.

test@test-V520-15IKL:~$ sudo lsmod | grep kthread
kthread                16384  0
  • check if the thread is created or not using ps command.

test@test-V520-15IKL:~$ ps -N | grep kthread_queue_delayed_work
6108 ?        00:00:00 kthread_queue_delayed_work thread example
6109 ?        00:00:00 kthread_queue_delayed_work worker example
  • check for the kernel messages from init function and thread function once the module is loaded and thread is created.

test@test-V520-15IKL:~$ sudo dmesg
[ 1196.526494] Inside kthread init function
[ 1196.526552] Thread created successfully
[ 1196.526556] kthread work 1 intialized
[ 1196.526596] kthread worker created
[ 1196.526602] kthread work 1 is queued to worker
[ 1196.526603] kthread_work_2_initialized
[ 1196.526605] kthread work 2 is queued to worker
[ 1196.526606] thread execution
[ 1196.539529] Inside work function 2
[ 1196.539534] my_work_fn_2 = 3
[ 1196.539537] my_work_fn_2 = 2
[ 1196.539539] my_work_fn_2 = 1
[ 1196.539541] my_work_fn_2 = 0
[ 1197.555661] Inside work function 1
[ 1197.555666] my_work_fn_1 = 0
[ 1197.555668] my_work_fn_1 = 1
[ 1197.555669] my_work_fn_1 = 2
[ 1197.555671] my_work_fn_1 = 3
  • remove the module from kernel using rmmod command.

test@test-V520-15IKL:~$ sudo rmmod kthread
  • check if the module is still loaded after removing the kernel module using lsmod if it is not displayed in lsmod output it is verified that the module is removed successfully.

test@test-V520-15IKL:~$ sudo lsmod | grep kthread
test@test-V520-15IKL:~$
  • check if the thread is destroyed using ps command if it is not displayed in ps output we can confirm that the thread is destroyed successfully.

test@test-V520-15IKL:~$ ps -N | grep kthread_queue_delayed_work
test@test-V520-15IKL:~$
  • Check for kernel messages from exit function using dmesg command.

test@test-V520-15IKL:~$ sudo dmesg
[ 1198.643574] Destroying threads
[ 1201.647894] Destroyed threads and worker

kthread API

Learning

kthread_create_worker

Create kthread worker

kthread_init_delayed_work

Create kthread delayed work

kthread_queue_delayed_work

Queue work to worker

kthread_cancel_delayed_work_sync

Cancel the kthread work and wait for it to finish

kthread_run

Create and wake a thread

kthread_destroy_worker

Destroy kthread worker

API

Learning

MODULE_LICENSE

Used to denote the license used in the kernel module

MODULE_AUTHOR

Used to mention the author of the kernel module

MODULE_DESCRIPTION

Used to describe what the module does

IS_ERR

Detects an error pointer

container_of

cast a member of the structure to the containing structure

kmalloc

Allocate kernel memory

wake_up_process

wake up a specific process

msleep

will put in sleep for a certain amount of msecs time.

msecs_to_jiffies

convert milliseconds to jiffies

module_init

Driver initialization entry point

module_exit

Driver exit entry point

pr_info

Print an info-level message