From fb2f04adb246cdc4b5812596b13cfccd812fef23 Mon Sep 17 00:00:00 2001 From: "leon.bohnwagner" <leon.bohnwagner@informatik.hs-fulda.de> Date: Wed, 12 Feb 2025 20:16:52 +0100 Subject: [PATCH] feat: add timed kernel thread --- kernel/kmod.c | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/kernel/kmod.c b/kernel/kmod.c index e29d238..d8dd08c 100644 --- a/kernel/kmod.c +++ b/kernel/kmod.c @@ -5,11 +5,13 @@ #include <linux/vmalloc.h> #include <linux/uaccess.h> #include <linux/hrtimer.h> +#include <linux/kthread.h> #include "../common/include/message.h" #define DEVICE_NAME "amogus" #define CLASS_NAME "amogus_class" +#define SLOTS 4 #define SLOT_INTERVAL_NS 250000 static int major_number; @@ -21,6 +23,13 @@ static message_t* message; static struct hrtimer timer; static ktime_t interval; +static struct task_struct *timed_thread; + +static DECLARE_WAIT_QUEUE_HEAD(wq); +static atomic_t wake_counter = ATOMIC_INIT(0); + +static int slot = 0; + static int device_open(struct inode *inode, struct file *file) { return 0; @@ -55,10 +64,26 @@ static const struct file_operations fops = { }; static enum hrtimer_restart timer_callback(struct hrtimer *timer) { + atomic_inc(&wake_counter); + wake_up_interruptible(&wq); + hrtimer_forward_now(timer, interval); return HRTIMER_RESTART; } +static int timed_thread_fn(void *args) { + while (!kthread_should_stop()) { + wait_event_interruptible(wq, atomic_read(&wake_counter) > 0); + atomic_dec(&wake_counter); + + if (slot == 0) {} + + slot = (slot + 1) % SLOTS; + } + + return 0; +} + static int __init lkm_init(void) { dev_t dev; @@ -110,6 +135,20 @@ static int __init lkm_init(void) timer.function = timer_callback; hrtimer_start(&timer, interval, HRTIMER_MODE_REL); + timed_thread = kthread_run(timed_thread_fn, NULL, "timed_thread"); + if (IS_ERR(timed_thread)) { + vfree(message); + cdev_del(&mycdev); + device_destroy(class, MKDEV(major_number, 0)); + class_destroy(class); + unregister_chrdev_region(MKDEV(major_number, 0), 1); + + hrtimer_cancel(&timer); + + printk(KERN_ALERT "Failed to create timed thread\n"); + return -1; + } + return 0; } -- GitLab