[Linux Kernel] Mutex (1) - Overview
What is mutex
A mutex is a common synchronization method used in Linux kernel programming, especially in device drivers. When you read Linux kernel code, you will often see the mutex_lock() function. This post outlines how mutex works in the Linux kernel.
Important Rules for Mutex
Mutex is widely used in the Linux kernel. However, there are some important rules to follow when using it.
Key Signature of Mutex
The following is the key signature of a mutex:
(struct mutex)0xD1491980 = (
(atomic_t) count = ((int) counter = 0xFFFFFFFF),
(spinlock_t) wait_lock = ((struct raw_spinlock) rlock = ((arch_spinlock_t) r
(struct list_head) wait_list = (
(struct list_head *) next = 0xEBB3BD34 // <<-- mutex: 0xEBB3BD2C, kworker/u16:8
(struct list_head *) next = 0xC18472E4 // <<-- mutex: 0xC18472DC, kworker/u16:8
(struct list_head *) next = 0xEBB3BD34,
(struct list_head *) prev = 0xEBB3BD34),
(struct list_head *) prev = 0xC18472E4),
(struct list_head *) prev = 0xEBB3BD34),
(struct task_struct *) owner = 0xDCB78B00, //<<--kworker/u16:8, pid: 1521 cpu: 4
Explanation of Key Fields
Recommended by LinkedIn
Call Stack When Waiting for a Mutex
When a process tries to acquire a mutex but must wait, the following call stack occurs:
-000|context_switch(inline)
-000|__schedule()
-001|schedule_preempt_disabled()
-002|__mutex_lock_common(inline)
-002|__mutex_lock_slowpath(lock_count = 0xC1327164)
-003|current_thread_info(inline)
-003|mutex_set_owner(inline)
-003|mutex_lock(lock = 0xD1327184)
-004|cpu_hotplug_disable()
-005|migrate_to_reboot_cpu()
-006|kernel_restart(cmd = 0x0)
-007|sys_reboot(magic1 = -18751827, ?, cmd = 19088743, arg = 0)
-008|ret_fast_syscall(asm)
Understanding the Call Stack
__schedule(): The scheduler selects the next task to run.
This explanation helps in understanding how a mutex works and how processes behave when waiting for a mutex in a Linux system.
Helpful overview of mutex in Linux. Looking forward to more kernel programming insights!
Good info. I do recommend reading chap 12-13 from Kaiwan Linux Kernel Programming book, there are also sample codes to try on github, the best way to grasp kernel synchronization is to try it.
Very informative for the good 😊