I’m currently trying to program my first Linux kernel module for a school project. Unfortunately, we haven’t really learned much about this topic at school, which is why I’ve tried a lot with ChatGPT and google, but haven’t quite figured it out yet.
I am doing this on a Virtual Machine with the Linux-Kernel-Version 6.8.0.
Please be kind, few hours ago I did not even know what workqueues are :c
Now I wanted to ask you what you do think about my code. You should be able to call the module with the parameter delay_ms, which states after how many milliseconds statistics should be output again by the work handler.
Here is my code, please give me some tips, improvements or tell me where I did something wrong/unnecessary complex 🙂
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/workqueue.h>
#include <linux/sched.h>
static struct delayed_work stat_work;
static int delay_ms = 1000; // Default delay
//Function receives pointer to struct work_struct
static void stat_work_handler(struct work_struct *work)
{
int i;
unsigned long flags;
//current points to the ongoing process
struct task_struct *task = current;
printk(KERN_INFO "mod_stat_scheduler: current process statistics:n");
printk(KERN_INFO "latency_record:n");
//Save and pause local interrupt
raw_local_irq_save(flags);
//Print out latency of the current process
for (i = 0; i < task->latency_record_count; i++) {
printk(KERN_INFO "%lu ", task->latency_record[i]);
}
printk(KERN_INFO "n");
//Restore saved interrupt
raw_local_irq_restore(flags);
//plan execution of delayed work
schedule_delayed_work(&stat_work, msecs_to_jiffies(delay_ms));
}
static int __init mod_init(void)
{
printk(KERN_INFO "mod_stat_scheduler: module loaded.n");
// initialize work handler
INIT_DELAYED_WORK(&stat_work, stat_work_handler);
// plan first work handler
schedule_delayed_work(&stat_work, msecs_to_jiffies(delay_ms));
return 0;
}
static void __exit mod_exit(void)
{
cancel_delayed_work_sync(&stat_work);
printk(KERN_INFO "mod_stat_scheduler: module unloaded.n");
}
module_init(mod_init);
module_exit(mod_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("darquis");
MODULE_DESCRIPTION("A kernel module to periodically output the latency_record of the current process");
module_param(delay_ms, int, 0644);
MODULE_PARM_DESC(delay_ms, "Time interval in milliseconds for the periodic output of the latency_record");
I just tried to code it with ChatGPT in Visual Studio Code and wanted to ask here, before I actually load the module into the kernel, because I do not want to break something.
darquis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.