Linux Kernel Internal APIs
Memory, locking, data structures, work deferral, device model, and logging
Kernel Internal API Map │ ├── Memory → kmalloc, vmalloc, alloc_pages, GFP flags, devm_ ├── Locking → spinlock, mutex, rwsem, seqlock, RCU, atomic ├── Data Structs → list_head, hlist, XArray, rbtree ├── Deferral → workqueue, tasklet, timer_list, hrtimer ├── Ref Counting → kref, refcount_t ├── Device Model → kobject, struct device, platform_driver └── Logging → printk, pr_*, dev_*, rate-limited variants
Memory kmalloc / kzalloc

Slab allocator for small, physically contiguous allocations. The workhorse of kernel memory allocation — fast, cache-friendly, and bounded to ~4 MB per call.

When to use

Small objects (< 4 MB) Physically contiguous needed DMA buffers Per-object allocation

Core API

C
/* allocate uninitialized memory */
void *ptr = kmalloc(size, GFP_KERNEL);

/* allocate zero-initialized memory (preferred) */
struct my_obj *obj = kzalloc(sizeof(*obj), GFP_KERNEL);

/* allocate array, zero-initialized */
void *arr = kcalloc(count, elem_size, GFP_KERNEL);

/* reallocate */
ptr = krealloc(ptr, new_size, GFP_KERNEL);

/* duplicate a string into kernel memory */
char *s = kstrdup(str, GFP_KERNEL);

/* free — safe to call with NULL */
kfree(ptr);

Atomic context

C
/* interrupt handler or spinlock held — must use GFP_ATOMIC */
void *buf = kmalloc(64, GFP_ATOMIC); /* cannot sleep, may fail */
if (!buf)
    return -ENOMEM;
Gotcha: GFP_KERNEL in atomic context Using GFP_KERNEL while holding a spinlock or in interrupt context will deadlock or BUG. Use GFP_ATOMIC instead — it never sleeps but has a higher failure rate.
Tip: always use kzalloc over kmalloc Zero-initialization prevents info leaks and catches uninitialized-read bugs. The overhead is negligible for small allocations.

Size limits

AllocatorMax sizePhysically contiguous?Sleeps?
kmalloc~4 MB (KMALLOC_MAX_SIZE)YesDepends on GFP flag
vmallocVirtually unlimitedNo (virtually only)Yes (always)
alloc_pages2^MAX_ORDER pagesYesDepends on GFP flag
Memory vmalloc

Virtually-contiguous allocator for large buffers. Pages may be physically scattered — do not use for DMA. Slower than kmalloc due to TLB setup overhead.

Core API

C
/* allocate large virtually-contiguous buffer */
void *buf = vmalloc(size);         /* uninitialized */
void *buf = vzalloc(size);         /* zero-initialized */

/* map physically-contiguous memory into vmalloc space */
void *va = vmap(pages, count, VM_MAP, PAGE_KERNEL);
vunmap(va);

vfree(buf);                         /* free vmalloc'd memory */
Never use vmalloc for DMA Pages are not guaranteed to be physically contiguous. Use dma_alloc_coherent() for DMA buffers instead.
Cannot use in atomic context vmalloc() always sleeps to set up page tables. It will BUG in interrupt context or while holding a spinlock.
Memory Page Allocator

The lowest-level allocator — allocates physically contiguous power-of-two page blocks. Used directly when you need page-aligned or order-specific allocations.

Core API

C
/* allocate 2^order contiguous pages */
struct page *page = alloc_pages(GFP_KERNEL, order);
void *va = page_address(page);     /* get kernel virtual address */

/* single page shorthand */
unsigned long addr = __get_free_page(GFP_KERNEL);
unsigned long addr = get_zeroed_page(GFP_KERNEL);

/* free pages */
__free_pages(page, order);
free_page(addr);                    /* for single-page __get_free_page() */

Order reference

OrderPagesSize (4K pages)
014 KB
128 KB
2416 KB
41664 KB
82561 MB
1010244 MB (MAX_ORDER)
Memory GFP Flags

Get Free Pages flags control allocator behavior — whether it can sleep, reclaim, use emergency reserves, or restrict to DMA zones.

Common flag combinations

FlagSleeps?Use when
GFP_KERNELYesNormal kernel allocation in process context
GFP_ATOMICNoInterrupt handlers, spinlock held
GFP_NOWAITNoNon-blocking, but no emergency reserves
GFP_NOIOYesReclaim allowed but no I/O (block layer use)
GFP_NOFSYesReclaim allowed but no filesystem calls
GFP_USERYesUserspace allocations via kernel
GFP_DMAYesMust be in DMA-capable zone (<16 MB on x86)
GFP_DMA32YesMust be below 4 GB physical (32-bit DMA)
GFP_HIGHUSERYesUserspace pages, can use highmem

Modifier flags

ModifierEffect
__GFP_ZEROZero-initialize returned memory
__GFP_NOWARNSuppress allocation failure warnings
__GFP_RETRY_MAYFAILRetry hard, but may still fail
__GFP_NOFAILLoop forever until success — use sparingly
__GFP_HIGHUse emergency memory reserves
__GFP_COMPReturn compound page (huge page support)
Never use __GFP_NOFAIL lightly It loops indefinitely and can wedge the system under memory pressure. Only justified for core infrastructure with no error-handling path.
Memory devm_ helpers

Device-managed resource helpers that auto-release when the device is unbound. Eliminates manual cleanup in remove() and error paths.

Common devm_ functions

C
/* memory */
void *p   = devm_kzalloc(dev, size, GFP_KERNEL);
char *str = devm_kstrdup(dev, s, GFP_KERNEL);

/* I/O memory — maps and tracks a resource */
void __iomem *base = devm_ioremap_resource(dev, res);

/* IRQ */
int ret = devm_request_irq(dev, irq, handler, flags, name, data);

/* clocks, regulators, GPIOs */
struct clk *clk = devm_clk_get(dev, "core");
struct regulator *reg = devm_regulator_get(dev, "vdd");
int gpio = devm_gpiod_get(dev, "reset", GPIOD_OUT_LOW);

/* custom cleanup action */
devm_add_action_or_reset(dev, my_cleanup_fn, data);
Prefer devm_ in drivers Error-path cleanup and remove() become trivial — just return the error. Less code, fewer leaks.
Don't mix devm_ and manual free If you allocate with devm_kzalloc(), do not call kfree() on it. The devres framework will free it on device unbind — double-free will follow.
Locking Spinlocks

Busy-wait locks for protecting short critical sections. Safe in any context including interrupt handlers — but the caller must not sleep while holding one.

Variants

VariantUse when
spin_lock / spin_unlockProcess context, no interrupt concern
spin_lock_irq / spin_unlock_irqDisable local IRQs while holding
spin_lock_irqsave / spin_unlock_irqrestoreSave/restore IRQ state — use across function boundaries
spin_lock_bh / spin_unlock_bhDisable bottom halves (softirqs/tasklets)
spin_trylockNon-blocking attempt

Usage

C
struct my_dev {
    spinlock_t  lock;
    struct list_head queue;
};

/* initialise (static) */
DEFINE_SPINLOCK(my_lock);

/* initialise (dynamic) */
spin_lock_init(&dev->lock);

/* process context — shared with interrupt handler */
unsigned long flags;
spin_lock_irqsave(&dev->lock, flags);
/* ... critical section ... */
spin_unlock_irqrestore(&dev->lock, flags);

/* interrupt handler */
spin_lock(&dev->lock);
/* ... critical section ... */
spin_unlock(&dev->lock);
Never sleep while holding a spinlock Calling any sleeping function (kmalloc(GFP_KERNEL), mutex_lock(), msleep(), etc.) while a spinlock is held will deadlock on RT kernels and cause subtle bugs on non-RT.
Always use irqsave if an IRQ handler touches the same lock Using plain spin_lock() in process context while an IRQ handler also calls spin_lock() on the same lock is a deadlock waiting to happen.
Locking Mutexes

Sleeping lock for process context. Cheaper than spinlocks under contention — the waiter sleeps instead of busy-waiting. Cannot be used in interrupt or atomic context.

Core API

C
/* static initialisation */
DEFINE_MUTEX(my_mutex);

/* dynamic initialisation */
mutex_init(&dev->lock);

/* lock — sleeps until acquired */
mutex_lock(&dev->lock);

/* lock — returns -EINTR if signal received */
if (mutex_lock_interruptible(&dev->lock))
    return -EINTR;

/* try-lock — returns 1 on success, 0 on failure */
if (!mutex_trylock(&dev->lock))
    return -EBUSY;

mutex_unlock(&dev->lock);

/* ownership check (DEBUG_MUTEXES) */
lockdep_assert_held(&dev->lock);
mutex vs spinlock decision rule Use a mutex when the critical section may sleep, calls kernel APIs, or runs for more than a few microseconds. Use a spinlock in interrupt context or for sub-microsecond critical sections.
Locking RW Semaphores

Allows multiple concurrent readers or one exclusive writer. Sleeping lock — process context only. Use when reads vastly outnumber writes.

Core API

C
DECLARE_RWSEM(my_rwsem);     /* static */
init_rwsem(&dev->sem);        /* dynamic */

/* read side — multiple concurrent readers allowed */
down_read(&dev->sem);
/* ... read-only access ... */
up_read(&dev->sem);

/* write side — exclusive */
down_write(&dev->sem);
/* ... modify shared data ... */
up_write(&dev->sem);

/* downgrade write lock to read lock without releasing */
downgrade_write(&dev->sem);

/* interruptible variants */
down_read_interruptible(&dev->sem);
down_write_interruptible(&dev->sem);
Locking Seqlocks

Lightweight synchronisation for frequently-read, rarely-written small data (e.g. timestamps). Readers never block writers; readers retry if they observe a write in progress.

Core API

C
DEFINE_SEQLOCK(my_seqlock);

/* writer */
write_seqlock(&my_seqlock);
/* update shared_data */
write_sequnlock(&my_seqlock);

/* reader — retry loop */
unsigned int seq;
do {
    seq = read_seqbegin(&my_seqlock);
    /* read shared_data */
} while (read_seqretry(&my_seqlock, seq));
Ideal for: jiffies, wall-clock time, xtime The kernel itself uses seqlocks for timekeeping. Best when data fits in a few words, writes are rare, and readers greatly outnumber writers.
Readers must not use pointers from the read section If a writer runs concurrently, the data is torn. Only safe to use values after read_seqretry() returns 0.
Locking RCU

Read-Copy-Update — lock-free reads with deferred reclamation. Readers are extremely cheap (no locking, no cache line bouncing). Writers copy, update, then wait for all pre-existing readers to finish before freeing the old version.

Read side

C
rcu_read_lock();               /* begin RCU read-side critical section */
struct my_obj *obj = rcu_dereference(global_ptr);
if (obj)
    use(obj->field);           /* safe — obj cannot be freed yet */
rcu_read_unlock();             /* end critical section */

Write / update side

C
struct my_obj *new_obj = kzalloc(sizeof(*new_obj), GFP_KERNEL);
struct my_obj *old_obj;

spin_lock(&update_lock);
old_obj = rcu_dereference_protected(global_ptr,
                                   lockdep_is_held(&update_lock));
/* ... populate new_obj ... */
rcu_assign_pointer(global_ptr, new_obj);
spin_unlock(&update_lock);

/* wait for all readers of old_obj to finish */
synchronize_rcu();             /* synchronous — sleeps */
kfree(old_obj);

/* async variant — callback fires after grace period */
call_rcu(&old_obj->rcu_head, free_my_obj_rcu);
Never sleep inside rcu_read_lock() The RCU read-side critical section must not sleep (on non-SRCU). This prevents the grace period from ending and starves writers.
Use SRCU when you need to sleep in the read side srcu_read_lock() / srcu_read_unlock() allow sleeping readers at the cost of per-CPU data structures.

RCU vs other locks

PrimitiveRead costWrite costReaders sleep?
spinlockCache line bounceLowNo
rwsemAtomic opSleepsYes
RCUNear-zeroGrace period waitNo (SRCU: yes)
seqlockRetry loopLowNo
Locking Atomic Operations

Lock-free integer operations using hardware atomic instructions. Use for counters, flags, and simple state machines shared between contexts.

Core API (atomic_t)

C
ATOMIC_INIT(0)                       /* static initialiser */
atomic_set(&a, 0)                   /* set value */
atomic_read(&a)                      /* read value */
atomic_inc(&a)                       /* increment */
atomic_dec(&a)                       /* decrement */
atomic_add(5, &a)                    /* add */
atomic_sub(3, &a)                    /* subtract */

/* returns new value */
int new = atomic_inc_return(&a);
int new = atomic_dec_return(&a);
int new = atomic_add_return(5, &a);

/* test-and-set patterns */
if (atomic_dec_and_test(&a))      /* true if result is 0 */
    cleanup();
if (atomic_inc_and_test(&a))      /* true if result is 0 */
    signal_done();

/* compare-and-exchange */
int old = atomic_cmpxchg(&a, expected, new_val);

/* 64-bit variant */
atomic64_t a64;
atomic64_set(&a64, 0);
atomic64_inc(&a64);

Bitwise atomic ops

C
unsigned long flags = 0;

set_bit(BIT_NUM, &flags);
clear_bit(BIT_NUM, &flags);
change_bit(BIT_NUM, &flags);
test_bit(BIT_NUM, &flags);          /* returns 0 or 1 */
test_and_set_bit(BIT_NUM, &flags);  /* returns old value */
test_and_clear_bit(BIT_NUM, &flags);
Data Structures list_head

Intrusive doubly-linked circular list. The most used data structure in the kernel. Embed struct list_head inside your struct and use container_of() to get back to the containing object.

Core API

C
struct my_item {
    int              val;
    struct list_head node;   /* embed the list node */
};

/* declare and initialise a list head */
LIST_HEAD(my_list);                  /* static */
INIT_LIST_HEAD(&dev->list);          /* dynamic */

/* add items */
list_add(&item->node, &my_list);     /* prepend (stack-like) */
list_add_tail(&item->node, &my_list);/* append (queue-like) */

/* remove */
list_del(&item->node);
list_del_init(&item->node);          /* del + reinitialise */

/* move between lists */
list_move(&item->node, &other_list);
list_move_tail(&item->node, &other_list);

/* check */
list_empty(&my_list);               /* returns bool */

/* iterate — safe to delete current entry */
struct my_item *pos, *tmp;
list_for_each_entry_safe(pos, tmp, &my_list, node) {
    if (pos->val < 0)
        list_del(&pos->node);
}

/* iterate read-only */
list_for_each_entry(pos, &my_list, node) {
    process(pos->val);
}
Do not delete entries during list_for_each_entry() Use list_for_each_entry_safe() when you need to delete the current entry. The safe variant keeps a next pointer before processing each entry.
Data Structures hlist

Singly-linked list optimised for hash table buckets. The head is only one pointer (not two), halving the memory cost for large hash tables with many empty buckets.

Core API

C
struct hlist_head buckets[HASH_SIZE];  /* hash table */

struct my_item {
    int               key;
    struct hlist_node node;
};

/* initialise */
INIT_HLIST_HEAD(&buckets[i]);

/* insert at head of bucket */
hlist_add_head(&item->node, &buckets[hash(key)]);

/* delete */
hlist_del(&item->node);

/* iterate */
struct my_item *pos;
hlist_for_each_entry(pos, &buckets[h], node) {
    if (pos->key == target_key) { ... }
}
Data Structures XArray

Resizable array of pointers, indexed by unsigned long. Replaces the old radix tree API. Built-in locking, sparse-friendly, and supports marks and multi-index entries.

Core API

C
struct xarray xa;

/* initialise */
xa_init(&xa);                              /* not locked */
xa_init_flags(&xa, XA_FLAGS_ALLOC);       /* for ID allocation */

/* store */
void *old = xa_store(&xa, index, ptr, GFP_KERNEL);
int ret   = xa_err(old);                  /* check for -ENOMEM */

/* store only if slot is empty */
ret = xa_insert(&xa, index, ptr, GFP_KERNEL);

/* load */
void *p = xa_load(&xa, index);

/* erase */
xa_erase(&xa, index);

/* ID allocation — finds and stores at next free index */
u32 id;
ret = xa_alloc(&xa, &id, ptr, XA_LIMIT(0, 1023), GFP_KERNEL);

/* iterate all populated entries */
unsigned long idx;
void *entry;
xa_for_each(&xa, idx, entry) {
    process(entry);
}

xa_destroy(&xa);                           /* free internal nodes */
XArray replaces idr and radix_tree New code should use XArray. idr is now a thin wrapper around XArray; the old struct radix_tree_root API is deprecated.
Data Structures Red-Black Tree

Self-balancing BST providing O(log n) search, insert, and delete. Used for the CFS scheduler run queue, VM area structures, and interval trees.

Core API

C
struct my_node {
    struct rb_node rb;
    int            key;
};

struct rb_root root = RB_ROOT;

/* insert */
static void insert(struct rb_root *root, struct my_node *new)
{
    struct rb_node **link = &root->rb_node, *parent = NULL;
    while (*link) {
        struct my_node *cur = rb_entry(*link, struct my_node, rb);
        parent = *link;
        if (new->key < cur->key) link = &(*link)->rb_left;
        else if (new->key > cur->key) link = &(*link)->rb_right;
        else return;                 /* duplicate */
    }
    rb_link_node(&new->rb, parent, link);
    rb_insert_color(&new->rb, root); /* rebalance */
}

/* erase */
rb_erase(&node->rb, &root);

/* iterate in-order */
struct rb_node *n;
for (n = rb_first(&root); n; n = rb_next(n)) {
    struct my_node *cur = rb_entry(n, struct my_node, rb);
    use(cur->key);
}
Work Deferral Workqueues

Defer work to a kernel thread (process context). The handler can sleep, allocate memory with GFP_KERNEL, and acquire mutexes. The recommended way to defer work from interrupt context.

Simple work (system workqueue)

C
struct my_dev {
    struct work_struct  work;
    struct delayed_work dwork;
};

/* static initialisation */
INIT_WORK(&dev->work, my_work_handler);
INIT_DELAYED_WORK(&dev->dwork, my_delayed_handler);

/* schedule (uses system_wq) */
schedule_work(&dev->work);
schedule_delayed_work(&dev->dwork, msecs_to_jiffies(100));

/* wait for completion */
flush_work(&dev->work);
cancel_work_sync(&dev->work);
cancel_delayed_work_sync(&dev->dwork);

/* the handler — runs in process context */
static void my_work_handler(struct work_struct *work)
{
    struct my_dev *dev = container_of(work, struct my_dev, work);
    /* can sleep, kmalloc(GFP_KERNEL), mutex_lock(), etc. */
}

Custom workqueue

C
/* create a dedicated ordered workqueue (single-threaded) */
struct workqueue_struct *wq =
    alloc_ordered_workqueue("my_wq", 0);

/* create a high-priority concurrent workqueue */
struct workqueue_struct *wq =
    alloc_workqueue("my_wq", WQ_HIGHPRI | WQ_CPU_INTENSIVE, 0);

queue_work(wq, &dev->work);
flush_workqueue(wq);
destroy_workqueue(wq);
Use system_wq for normal work Avoid creating custom workqueues unless you need strict ordering, high priority, or isolation. The system workqueue pool is shared and well-tuned.
Work Deferral Tasklets

Softirq-based deferred work that runs in atomic context (no sleeping). Guaranteed to run on one CPU at a time. Deprecated since 5.10 — prefer workqueues for new code.

Core API

C
struct tasklet_struct my_tasklet;

/* initialise */
tasklet_init(&my_tasklet, my_tasklet_fn, (unsigned long)dev);

/* schedule from interrupt handler */
tasklet_schedule(&my_tasklet);
tasklet_hi_schedule(&my_tasklet);     /* high-priority softirq */

/* disable/enable */
tasklet_disable(&my_tasklet);         /* waits for running instance */
tasklet_enable(&my_tasklet);

tasklet_kill(&my_tasklet);            /* wait for completion, prevent re-schedule */

/* handler — atomic context, cannot sleep */
static void my_tasklet_fn(unsigned long data)
{
    struct my_dev *dev = (struct my_dev *)data;
    /* no sleeping, no GFP_KERNEL, no mutex_lock() */
}
Prefer workqueues for new drivers Tasklets are deprecated and will eventually be removed. Use schedule_work() / schedule_delayed_work() instead.
Work Deferral Timers (timer_list)

Jiffies-resolution kernel timers. Callbacks run in softirq (atomic) context — no sleeping allowed. For sub-jiffie or nanosecond resolution, use hrtimers.

Core API

C
struct timer_list my_timer;

/* initialise with callback */
timer_setup(&my_timer, my_timer_fn, 0);

/* start / reschedule — fires in 'delay' jiffies */
mod_timer(&my_timer, jiffies + msecs_to_jiffies(500));

/* stop */
del_timer(&my_timer);           /* non-blocking */
del_timer_sync(&my_timer);     /* waits for running callback */

/* check if pending */
timer_pending(&my_timer);

/* callback — atomic context */
static void my_timer_fn(struct timer_list *t)
{
    struct my_dev *dev = from_timer(dev, t, my_timer);
    /* reschedule if needed */
    mod_timer(t, jiffies + msecs_to_jiffies(500));
}
Work Deferral Hrtimers

High-resolution timers with nanosecond precision. Used internally for nanosleep(), itimers, and real-time tasks. Callback runs in hardirq or softirq context.

Core API

C
struct hrtimer my_hrtimer;

hrtimer_init(&my_hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
my_hrtimer.function = my_hrtimer_fn;

/* start — fires after 1 ms */
hrtimer_start(&my_hrtimer, ms_to_ktime(1), HRTIMER_MODE_REL);

hrtimer_cancel(&my_hrtimer);     /* stop and wait */
hrtimer_active(&my_hrtimer);     /* is it queued? */

/* callback */
static enum hrtimer_restart my_hrtimer_fn(struct hrtimer *t)
{
    /* do work */
    hrtimer_forward_now(t, ms_to_ktime(1)); /* reschedule */
    return HRTIMER_RESTART;
    /* or return HRTIMER_NORESTART to stop */
}
Ref Counting kref

Simple reference counter with a release callback. The canonical way to manage object lifetime when multiple subsystems share ownership.

Core API

C
struct my_obj {
    struct kref ref;
    /* ... other fields ... */
};

static void my_obj_release(struct kref *ref)
{
    struct my_obj *obj = container_of(ref, struct my_obj, ref);
    kfree(obj);
}

/* initialise to refcount = 1 */
kref_init(&obj->ref);

/* increment */
kref_get(&obj->ref);

/* decrement — calls release if count hits 0 */
kref_put(&obj->ref, my_obj_release);

/* conditional get (only if count > 0) — needs external lock */
kref_get_unless_zero(&obj->ref);
Never access an object after kref_put drops to zero The release callback may free the object synchronously. After calling kref_put(), treat the pointer as potentially invalid.
Ref Counting refcount_t

Saturating reference counter with overflow and use-after-free protection. Prefer over bare atomic_t for reference counting — it prevents counter wrap-around exploits.

Core API

C
struct my_obj {
    refcount_t refs;
};

refcount_set(&obj->refs, 1);        /* initialise */
refcount_inc(&obj->refs);            /* increment (WARN if 0) */

/* decrement and test — true if the count dropped to 0 */
if (refcount_dec_and_test(&obj->refs))
    kfree(obj);

refcount_read(&obj->refs);           /* current value */
refcount_inc_not_zero(&obj->refs);   /* conditional get */
Use refcount_t instead of atomic_t for reference counts refcount_t saturates at INT_MAX and warns on increment-from-zero, preventing integer wrap-around use-after-free vulnerabilities.
Device Model kobject

The base object in the Linux device model — provides reference counting, sysfs representation, and parent/child hierarchy. Embedded in struct device, struct module, and most subsystem objects.

Core API

C
struct my_obj {
    struct kobject kobj;
    /* ... */
};

static struct kobj_type my_ktype = {
    .release   = my_obj_release,
    .sysfs_ops = &kobj_sysfs_ops,
};

/* initialise and add (creates sysfs dir) */
kobject_init(&obj->kobj, &my_ktype);
ret = kobject_add(&obj->kobj, parent_kobj, "%s", name);

/* or combined */
ret = kobject_init_and_add(&obj->kobj, &my_ktype, parent, "%s", name);

/* reference counting */
kobject_get(&obj->kobj);
kobject_put(&obj->kobj);    /* calls release when count hits 0 */

/* send uevent (e.g. for udev) */
kobject_uevent(&obj->kobj, KOBJ_ADD);
kobject_uevent(&obj->kobj, KOBJ_REMOVE);
Never kfree() a kobject directly Always use kobject_put(). The release callback in kobj_type is the only safe place to free the containing object.
Device Model Platform Driver

The standard driver model for SoC peripherals described in device tree or ACPI. Handles resource discovery, IRQ, and memory-mapped I/O setup.

Driver skeleton

C
struct my_priv {
    void __iomem    *base;
    int              irq;
    struct clk      *clk;
};

static int my_probe(struct platform_device *pdev)
{
    struct my_priv *priv;
    struct resource *res;

    priv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL);
    if (!priv)
        return -ENOMEM;

    /* map MMIO from device tree "reg" property */
    priv->base = devm_platform_ioremap_resource(pdev, 0);
    if (IS_ERR(priv->base))
        return PTR_ERR(priv->base);

    /* get IRQ */
    priv->irq = platform_get_irq(pdev, 0);
    if (priv->irq < 0)
        return priv->irq;

    devm_request_irq(&pdev->dev, priv->irq, my_isr,
                     0, "my_dev", priv);

    /* get and enable clock */
    priv->clk = devm_clk_get(&pdev->dev, "core");
    if (IS_ERR(priv->clk))
        return PTR_ERR(priv->clk);

    platform_set_drvdata(pdev, priv);
    return 0;                  /* devm_ handles cleanup on error unwind */
}

static int my_remove(struct platform_device *pdev)
{
    /* devm_ resources freed automatically */
    return 0;
}

static const struct of_device_id my_of_match[] = {
    { .compatible = "vendor,my-device" },
    { }
};
MODULE_DEVICE_TABLE(of, my_of_match);

static struct platform_driver my_driver = {
    .probe  = my_probe,
    .remove = my_remove,
    .driver = {
        .name           = "my_dev",
        .of_match_table = my_of_match,
    },
};
module_platform_driver(my_driver);
Logging printk / pr_* macros

The kernel's logging system. Messages go to the ring buffer (accessible via dmesg) and optionally to the console. Always prefer the pr_* shorthand macros over bare printk().

Log levels

MacroLevelValueUse when
pr_emerg()KERN_EMERG0System is unusable
pr_alert()KERN_ALERT1Action must be taken immediately
pr_crit()KERN_CRIT2Critical conditions
pr_err()KERN_ERR3Error conditions
pr_warn()KERN_WARNING4Warning conditions
pr_notice()KERN_NOTICE5Normal but significant condition
pr_info()KERN_INFO6Informational
pr_debug()KERN_DEBUG7Debug messages (compiled out by default)

Usage

C
/* define a per-module prefix */
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

pr_info("device at 0x%llx irq %d\n", addr, irq);
pr_err("failed to allocate buffer: %d\n", ret);
pr_warn("unexpected state %d\n", state);

/* print once — useful for deprecation warnings */
pr_warn_once("legacy interface used\n");

/* conditional debug (enabled via dynamic_debug) */
pr_debug("rx_len=%d, flags=0x%x\n", len, flags);

/* dump hex buffer to dmesg */
print_hex_dump_bytes("buf: ", DUMP_PREFIX_OFFSET, buf, len);
Logging dev_* macros

Device-aware logging — automatically prepends the device name to each message. Always prefer these over pr_*() inside driver code that has a struct device *.

Core macros

C
/* output: "my_driver my-device: message\n" */
dev_err(dev,  "probe failed: %d\n", ret);
dev_warn(dev, "unexpected interrupt\n");
dev_info(dev, "firmware version %s\n", ver);
dev_dbg(dev,  "rx pkt len=%d\n", len);    /* dynamic debug */

/* print once per device */
dev_warn_once(dev, "deprecated ioctl used\n");

/* return error and log in one call */
return dev_err_probe(dev, -ENODEV, "firmware not found\n");

/* print pointer safely (hashed, not raw address) */
dev_dbg(dev, "ptr=%p\n", ptr);              /* use %p, never %lx */
dev_err_probe() simplifies probe error paths It logs the error, returns the error code, and — crucially — suppresses the message if the error is -EPROBE_DEFER (which is not a real failure, just deferred probing).
Logging Rate Limiting

Prevent log flooding from hot paths — interrupt handlers, packet processing, error loops. The rate-limited variants suppress repeated messages and print a summary count.

Rate-limited variants

C
/* pr_* rate-limited (default: 10 messages / 5 seconds) */
pr_err_ratelimited("DMA error: %d\n", err);
pr_warn_ratelimited("packet dropped\n");

/* dev_* rate-limited */
dev_err_ratelimited(dev, "rx overrun\n");
dev_warn_ratelimited(dev, "underrun: %d\n", count);

/* custom rate limit state */
static DEFINE_RATELIMIT_STATE(rs, HZ/10, 5); /* 5 msgs / 0.1s */
if (__ratelimit(&rs))
    pr_err("hot path error\n");

/* net_ratelimit — for networking drivers */
if (net_ratelimit())
    pr_warn("drop\n");
Always rate-limit messages from interrupt handlers An interrupt firing at 10 kHz with an unguarded printk() will saturate the console and can render the system unresponsive.

Dynamic debug

Shell
# enable all pr_debug() in a module at runtime
echo "module my_module +p" > /sys/kernel/debug/dynamic_debug/control

# enable for a specific file
echo "file drivers/my/my_dev.c +p" > /sys/kernel/debug/dynamic_debug/control

# enable for a specific function
echo "func my_probe +p" > /sys/kernel/debug/dynamic_debug/control

# show active dynamic debug sites
cat /sys/kernel/debug/dynamic_debug/control | grep my_module

Found this guide useful? Buy me a coffee ☕