1

The mutex must later on be released by the same task that acquired it.

The above line is present in kernel/locking/mutex.c in the definition of mutex_lock.

I am unable to see the same behavior with the sample code. Am I making any mistake. Please check my code below and dmesg.

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/kthread.h>

MODULE_LICENSE("GPL");
DEFINE_MUTEX(my_lock);
struct task_struct *mythread;

static int threadfn(void *data)
{
    pr_info("Kernel thread running on processor:%d\n", smp_processor_id());
    pr_info("Kernel thread unlocking without calling lock on processor:%d\n", smp_processor_id());
    mutex_unlock(&my_lock);
    pr_info("Kernel thread unlocked without calling lock on processor:%d\n", smp_processor_id());
    return 0;
}

static int __init test_hello_init(void)
{
    mutex_init(&my_lock);
    pr_info("Init function running on processor:%d\n", smp_processor_id());
    mutex_lock(&my_lock);
    pr_info("Init function locked on processor:%d\n", smp_processor_id());
    mythread = kthread_run(threadfn, NULL, "mythread");
    msleep(8000);
    pr_info("Init function completed on processor:%d\n", smp_processor_id());
    return -1;
}

static void __exit test_hello_exit(void)
{
}

module_init(test_hello_init);
module_exit(test_hello_exit);

dmesg:

[27389.146151] Init function running on processor:5
[27389.146152] Init function locked on processor:5
[27389.146351] Kernel thread running on processor:2
[27389.146352] Kernel thread unlocking without calling lock on processor:2
[27389.146352] Kernel thread unlocked without calling lock on processor:2
[27397.385479] Init function completed on processor:5
insmod: ERROR: could not insert module ./hello.ko: Operation not permitted
red0ct
  • 4,840
  • 3
  • 17
  • 44
md.jamal
  • 4,067
  • 8
  • 45
  • 108
  • 3
    I can only repeat [my comment](https://stackoverflow.com/questions/58177762/spin-unlock-successful-without-spin-lock-in-kernel-module#comment102742603_58177762) from your previous question. The verb "must" means that using the function in other way is prohibited and any guarantee is cleared. You could treat this as **undefined behavior**, which meaning is described in that question: https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior. – Tsyvarev Oct 02 '19 at 08:02
  • You don't know if your code works or not - your code never checks for any error. – Andrew Henle Oct 02 '19 at 09:36
  • The functions do not return anything – md.jamal Oct 02 '19 at 09:59
  • 1
    If you want to know why the functions do not do a lot of checking by default, it is because that would slow the system down. – Ian Abbott Oct 02 '19 at 14:48

0 Answers0