JuHyung Son
JuHyung Son

Reputation: 73

What does raw_spinlock mean?

I was studying the raw_spinlock struct, which is in /usr/src/linux/include/linux/spinlock_types.h:

typedef struct raw_spinlock {
        arch_spinlock_t raw_lock;
#ifdef CONFIG_GENERIC_LOCKBREAK
        unsigned int break_lock;
#endif
#ifdef CONFIG_DEBUG_SPINLOCK
        unsigned int magic, owner_cpu;
        void *owner;
#endif
#ifdef CONFIG_DEBUG_LOCK_ALLOC
        struct lockdep_map dep_map;
#endif
} raw_spinlock_t;

I think raw_lock is for a lock which is dependent on an architecture and dep_map is a kind of data structure to avoid deadlocks, but what do break_lock, magic, owner_cpu, and *owner mean?

Upvotes: 4

Views: 4596

Answers (1)

gavv
gavv

Reputation: 4883

spinlock

spinlock is public API for spinlocks in kernel code.

See Documentation/locking/spinlocks.txt.

raw_spinlock

raw_spinlock is actual implementation of normal spinlocks. On not-RT kernels, spinlock is just a wrapper for raw_spinlock. On RT kernels, spinlock doesn't always use raw_spinlock.

See this article on LWN.

arch_spinlock

arch_spinlock is platform-specific part of spinlock implementation. raw_spinlock is generally platform-independent and delegates low-level operations to arch_spinlock.

lockdep_map

lockdep_map is a dependency map for locking correctness validator.

See Documentation/locking/lockdep-design.txt.

break_lock

On SMP kernels, when spin_lock() on one CPU starts looping while the lock is held on another CPU, it sets this flag to 1. Another CPU that holds the lock can periodically check this flag using spin_is_contended() and then call spin_unlock().

This allows to archive two goals at the same time:

  • avoid frequent locking/unlocking;
  • avoid holding lock for a long time, preventing others to acquire the lock.

See also this article.

magic, owner, owner_cpu

These fields are enabled when CONFIG_SPINLOCK_DEBUG is set and help to detect common bugs:

  • magic is set to some randomly choosen constant when spinlock is created (SPINLOCK_MAGIC which is 0xdead4ead)
  • owner is set to current process in spin_lock();
  • owner_cpu is set to current CPU id in spin_lock().

spin_unlock() checks that it is called when current process and CPU are the same as they were when spin_lock() was called.

spin_lock() checks that magic is equal to SPINLOCK_MAGIC to ensure that caller passed a pointer to correctly initialized spinlock and (hopefully) no memory corruption occurred.

See kernel/locking/spinlock_debug.c.

Upvotes: 2

Related Questions