Spin Locks in Linux Kernel
π Spin Locks in Linux Kernel
✅ Why spin locks are needed
-
removes data from one structure
-
processes it
-
inserts it into another structure
This whole sequence must run without interruption.
✅ What is a spin lock?
A spin lock is a synchronization mechanism where:
-
Only one thread can hold the lock at a time.
-
If another thread tries to acquire it while locked:
-
it busy-waits (spins) in a loop
-
repeatedly checks until the lock becomes free.
-
π§ Simple analogy
Like waiting outside a locked room holding a key:
-
If the room is free → enter immediately
-
If occupied → stand outside checking continuously
✅ Key characteristics
1️⃣ Mutual exclusion
-
Guarantees only one execution thread enters the critical region.
-
Prevents race conditions on shared data.
2️⃣ Busy waiting behavior
Instead of sleeping:
-
thread continuously uses CPU while waiting
-
wastes processor time
π Therefore:
✔ Spin locks should be held for very short durations
✔ Long waits → use semaphores instead
3️⃣ Lightweight and fast
Spin locks:
-
avoid costly context switches
-
ideal when waiting time < context-switch cost
4️⃣ Non-recursive (important!)
Linux spin locks are not recursive.
If a thread:
-
tries to acquire a lock it already holds
→ it waits forever
→ deadlock occurs
✅ Basic usage in kernel code
Declare lock
Acquire lock
Critical section
Release lock
✅ Spin locks and interrupts
⚠ Problem
If:
-
kernel code holds a spin lock
-
interrupt occurs
-
interrupt handler tries to acquire same lock
→ deadlock happens
because:
-
interrupt waits for lock
-
lock holder cannot resume
✔ Solution: disable interrupts while locking
This:
-
saves interrupt state
-
disables interrupts locally
-
restores state on unlock
✅ Other useful spin lock functions
Try lock without waiting
-
returns immediately if lock unavailable
Check if locked
Initialize dynamic lock
✅ What should locks protect?
Important kernel rule:
π Protect DATA, not code
Meaning:
-
associate each shared structure with a specific lock
-
always lock before accessing shared data
Example:
✅ Spin locks in different kernel contexts
✔ Interrupt handlers
-
spin locks allowed
-
semaphores NOT allowed (they sleep)
✔ Bottom halves / softirqs
Special variants exist:
Used when data shared between:
-
bottom halves
-
process context
-
interrupts
π Reader-Writer Spin Locks
Used when:
-
many threads only read
-
few threads write
Behavior:
✔ Multiple readers allowed simultaneously
❌ Only one writer allowed
❌ Writer cannot run if readers exist
Usage
Initialize:
Reader:
Writer:
⚠ Important rules
❌ Cannot upgrade read lock → write lock
→ causes deadlock
⚠ Readers are favored over writers
→ too many readers may starve writers
⭐ When to use spin locks
Use spin locks when:
✔ critical section is very short
✔ code cannot sleep (interrupt context)
✔ need fast, lightweight synchronization
Do NOT use when:
❌ operation may take long
❌ thread might need to sleep
→ use semaphore/mutex instead
Comments
Post a Comment