在编写 Linux 内核模块时,我遇到了一个 kthread 问题,在等待信号量解锁时无法唤醒该 kthread。这会导致线程不可停止并且rmmod
尝试卸载模块时冻结。
请注意:该模块在 3.10 内核上运行,我无法将其更新到较新的版本(客户要求在具有 3.10 内核的现有 CentOS 7 上运行)。
以下是模块源代码中有趣的部分。它代表一个简单的生产者消费者问题,列表的大小不受限制(因此不需要生产者信号量)并由互斥锁保护。从列表中获取某些内容的函数由信号量保护,该信号量由生产者增加并由消费者减少。生产者函数是从未在此代码片段中显示的外部事件(实际上是字符设备)调用的,以保持尽可能小。除了模块卸载之外,该过程运行良好。
导致冻结的部分在代码片段中用注释标记。我知道停止 kthread 的唯一方法是调用kthread_stop
在它上面,在这种情况下会失败,因为它显然无法唤醒休眠线程。因为它等待线程退出,所以调用永远不会返回,模块也不会卸载。
如何唤醒并停止等待信号量成功卸载模块的 kthread?
列表实现:
#include <linux/mutex.h>
#include <linux/list.h>
#include <linux/semaphore.h>
static LIST_HEAD(list);
DEFINE_MUTEX(list_lock);
DEFINE_SEMAPHORE(sem_list_consumer);
void add_to_list(struct *some_struct) {
int rv = mutex_lock_interruptible(&list_lock);
if(rv != 0) {
return;
}
list_add(&some_struct->list, &list);
mutex_unlock(&list_lock);
up(&sem_list_consumer);
}
struct some_struct * take_from_list() {
int rv;
some_struct *entry;
/* this is where the kthread will freeze when module is unloaded */
rv = down_interruptible(&sem_list_consumer);
if(rv != 0) {
return NULL;
}
rv = mutex_lock_interruptible(&list_lock);
if(rv != 0) {
up(&sem_list_consumer);
return NULL;
}
if (list_empty(&list)) {
mutex_unlock(&list_lock);
return NULL;
} else {
entry = list_last_entry(&list, struct some_struct, list);
if (entry) {
list_del(&entry->list);
}
}
mutex_unlock(&list_lock);
return entry;
}
消费者kthread实现:
#include <linux/kthread.h>
#include <linux/sched.h>
int consumer_kthread(void *data) {
struct some_struct *entry;
set_current_state(TASK_INTERRUPTIBLE);
while (!kthread_should_stop()) {
/* Here the function including the semaphore is called */
entry = take_from_list();
if(entry != NULL) {
/* Do something with 'entry' here */
} else {
/* Some handling of returned NULL pointers */
}
set_current_state(TASK_INTERRUPTIBLE);
}
set_current_state(TASK_RUNNING);
return 0;
}
模块实现:
#include <linux/init.h>
#include <linux/kthread.h>
#include <linux/module.h>
#include <linux/sched.h>
static struct task_struct *consumer_task;
static int __init initModule(void) {
consumer_task = kthread_run(consumer_kthread, NULL, "list-consumer");
return 0;
}
static void __exit exitModule(void) {
/* this call will cause rmmod to freeze forever */
kthread_stop(consumer_task);
}
module_init(initModule);
module_exit(exitModule);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("My Module");