Spin Locks in Linux Kernel

 

πŸ” Spin Locks in Linux Kernel 

✅ Why spin locks are needed

Simple atomic operations work only for very small actions (like incrementing a counter).
Real kernel code often:

  • removes data from one structure

  • processes it

  • inserts it into another structure

This whole sequence must run without interruption.

To protect such larger critical sections, the kernel uses locks, and the most common is the spin lock.


✅ 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

DEFINE_SPINLOCK(mr_lock);

Acquire lock

spin_lock(&mr_lock);

Critical section

/* protected code */

Release lock

spin_unlock(&mr_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

spin_lock_irqsave(&mr_lock, flags); /* critical region */ spin_unlock_irqrestore(&mr_lock, flags);

This:

  • saves interrupt state

  • disables interrupts locally

  • restores state on unlock


✅ Other useful spin lock functions

Try lock without waiting

spin_trylock()
  • returns immediately if lock unavailable


Check if locked

spin_is_locked()

Initialize dynamic lock

spin_lock_init()

✅ 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:

struct foo protected by foo_lock

✅ Spin locks in different kernel contexts

✔ Interrupt handlers

  • spin locks allowed

  • semaphores NOT allowed (they sleep)


✔ Bottom halves / softirqs

Special variants exist:

spin_lock_bh() spin_unlock_bh()

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:

DEFINE_RWLOCK(mr_rwlock);

Reader:

read_lock(&mr_rwlock); /* read-only code */ read_unlock(&mr_rwlock);

Writer:

write_lock(&mr_rwlock); /* read/write code */ write_unlock(&mr_rwlock);

⚠ 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

Popular posts from this blog

Operating Systems OS PCCST403 Semester 4 BTech KTU CS 2024 Scheme

Introduction to Operating System -Virtualization, Concurrency, and Persistence

Differences Between Linux and Classic UNIX Kernels