</>EmbeddedInterview

What are atomic_t, RCU and seqlocks?

HardLinux Kernel & Device Drivers

Short answer: atomic_t/atomic64_t provide lock-free integer operations (atomic_inc, atomic_dec_and_test, atomic_cmpxchg), and refcount_t is the safe type for reference counts (it saturates and warns instead of wrapping). RCU (read-copy-update) lets readers access shared data with almost no overhead and no locks: writers publish a new version with rcu_assign_pointer and free the old version only after a grace period, when all pre-existing readers have finished. Seqlocks let readers proceed without locks and retry if a writer changed the data during the read; they suit small, frequently read, rarely written data like timekeeping.

RCU example: read-mostly configuration

struct cfg { int rate; int gain; struct rcu_head rcu; };
static struct cfg __rcu *cur_cfg;
static DEFINE_MUTEX(cfg_lock);

int read_rate(void)                               /* readers: fast, never block */
{
    int r;
    rcu_read_lock();
    r = rcu_dereference(cur_cfg)->rate;
    rcu_read_unlock();
    return r;
}

int update_cfg(int rate, int gain)                /* writers: copy, publish, free later */
{
    struct cfg *new = kmalloc(sizeof(*new), GFP_KERNEL), *old;
    if (!new) return -ENOMEM;
    new->rate = rate; new->gain = gain;
    mutex_lock(&cfg_lock);
    old = rcu_dereference_protected(cur_cfg, lockdep_is_held(&cfg_lock));
    rcu_assign_pointer(cur_cfg, new);
    mutex_unlock(&cfg_lock);
    if (old) kfree_rcu(old, rcu);                 /* freed after all current readers finish */
    return 0;
}

Seqlock pattern

unsigned int seq;
do {
    seq = read_seqbegin(&tk_lock);
    t = timekeeper_time;                          /* copy the data */
} while (read_seqretry(&tk_lock, seq));           /* writer was active: retry */

Comparison

Readers Writers Good for
spinlock / mutex take the lock take the lock general use
rwlock shared lock (still cache-line bouncing) exclusive rarely the best choice today
RCU nearly free, never block copy + publish + deferred free read-mostly lists, tables, configs (routing, module lists)
seqlock lock-free, may retry exclusive, never wait for readers small data, frequent reads, readers can retry (no pointers to chase)
atomics – – counters, flags, refcounts

Memory ordering: atomic_inc alone has no ordering guarantees; use smp_mb__after_atomic() or ordered variants (atomic_inc_return, _acquire/_release) when ordering matters.