Skip to content

Commit c2162ec

Browse files
authored
Merge pull request #294 from eleanorLYJ/spinlock-add-desc
Clarify usage differences between spinlock functions
2 parents ef553aa + 11e1064 commit c2162ec

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

lkmpg.tex

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1708,6 +1708,27 @@ \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 real-time 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.
1716+
To address this in real-time Linux environments, a \cpp|raw_spin_lock()| is used, which behaves similarly to a \cpp|spin_lock()| but without causing the system to sleep.
1717+
1718+
On the other hand, \cpp|spin_lock_irq()| disables interrupts while holding the lock, but it does not save the interrupt state.
1719+
This means that if an interrupt occurs while the lock is held, the interrupt state could be lost.
1720+
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.
1721+
This makes \cpp|spin_lock_irqsave()| a safer option in scenarios where preserving the interrupt state is crucial.
1722+
1723+
Next, \cpp|spin_lock_bh()| disables softirqs (software interrupts) but allows hardware interrupts to continue.
1724+
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.
1725+
1726+
For more information about spinlock usage and lock types, see the following resources:
1727+
\begin{itemize}
1728+
\item \href{https://www.kernel.org/doc/Documentation/locking/spinlocks.txt}{Lesson 1: Spin locks}
1729+
\item\href{https://docs.kernel.org/locking/locktypes.html}{Lock types and their rules}
1730+
\end{itemize}
1731+
17111732
\subsection{Read and write locks}
17121733
\label{sec:rwlock}
17131734
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)