Skip to content

Commit

Permalink
Describe atomic context in spinlock section (#254)
Browse files Browse the repository at this point in the history
Aquiring a spinlock makes the holder enter atomic context. Extra
attention is needed in atomic context. In particular, functions
that may sleep must not be used. Add this detail to the spinlock
section.
  • Loading branch information
0xff07 authored Apr 16, 2024
1 parent e1b4457 commit 3e472c8
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lkmpg.tex
Original file line number Diff line number Diff line change
Expand Up @@ -1689,6 +1689,21 @@ \subsection{Spinlocks}

\samplec{examples/example_spinlock.c}

Taking 100\% of a CPU's resources comes with greater responsibility.
Situations where the kernel code monopolizes a CPU are called \textbf{atomic contexts}.
Holding a spinlock is one of those situations.
Sleeping in atomic contexts may leave the system hanging, as the occupied CPU devotes 100\% of its resources doing nothing but sleeping.
In some worse cases the system may crash.
Thus, sleeping in atomic contexts is considered a bug in the kernel.
They are sometimes called ``sleep-in-atomic-context'' in some materials.

Note that sleeping here is not limited to calling the sleep functions explicitly.
If subsequent function calls eventually invoke a function that sleeps, it is also considered sleeping.
Thus, it is important to pay attention to functions being used in atomic context.
There's no documentation recording all such functions, but code comments may help.
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''.
Those comments are hints that a function may implicitly sleep and must not be called in atomic contexts.

\subsection{Read and write locks}
\label{sec:rwlock}
Read and write locks are specialised kinds of spinlocks so that you can exclusively read from something or write to something.
Expand Down

0 comments on commit 3e472c8

Please sign in to comment.