Skip to content

Commit 2fb76f6

Browse files
committed
Clarify usage differences between spinlock functions
Explain the behavior and use cases of spin_lock(), spin_lock_irq(), , spin_lock_irqsave() and spin_lock_bh().
1 parent ef553aa commit 2fb76f6

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

lkmpg.tex

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1708,6 +1708,20 @@ \subsection{Spinlocks}
17081708
Sometimes you may find comments in kernel source code stating that a function ``may sleep'', ``might sleep'', or more explicitly ``the caller should not hold a spinlock''.
17091709
Those comments are hints that a function may implicitly sleep and must not be called in atomic contexts.
17101710

1711+
Now, let's differentiate between a few types of spinlock functions in Linux kernel: \cpp|spin_lock()|, \cpp|spin_lock_irq()|, \cpp|spin_lock_irqsave()|, and \cpp|spin_lock_bh()|.
1712+
1713+
\cpp|spin_lock()| does not allow the CPU to sleep while waiting for the lock, which makes it suitable for most use cases where the critical section is short.
1714+
However, this is problematic for RT Linux because spinlocks in this configuration behave as sleeping locks.
1715+
This can prevent other tasks from running and cause the system to become unresponsive. To address this in RT Linux environments, a \cpp|raw_spin_lock()| is used, which behaves similarly to a spinlock but without causing the system to sleep.
1716+
1717+
On the other hand, \cpp|spin_lock_irq()| disables interrupts while holding the lock, but it does not save the interrupt state.
1718+
This means that if an interrupt occurs while the lock is held, the interrupt state could be lost.
1719+
In contrast, \cpp|spin_lock_irqsave()| disables interrupts and also saves the interrupt state, ensuring that interrupts are restored to their previous state when the lock is released.
1720+
This makes \cpp|spin_lock_irqsave()| a safer option in scenarios where preserving the interrupt state is crucial.
1721+
1722+
Next, \cpp|spin_lock_bh()| disables softirqs (software interrupts) but allows hardware interrupts to continue.
1723+
Unlike \cpp|spin_lock_irq()| and \cpp|spin_lock_irqsave()|, which disable both hardware and software interrupts, \cpp|spin_lock_bh()| is useful when hardware interrupts need to remain active.
1724+
17111725
\subsection{Read and write locks}
17121726
\label{sec:rwlock}
17131727
Read and write locks are specialised kinds of spinlocks so that you can exclusively read from something or write to something.

0 commit comments

Comments
 (0)