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
Core API
/* 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
/* interrupt handler or spinlock held — must use GFP_ATOMIC */ void *buf = kmalloc(64, GFP_ATOMIC); /* cannot sleep, may fail */ if (!buf) return -ENOMEM;
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.
Size limits
| Allocator | Max size | Physically contiguous? | Sleeps? |
|---|---|---|---|
kmalloc | ~4 MB (KMALLOC_MAX_SIZE) | Yes | Depends on GFP flag |
vmalloc | Virtually unlimited | No (virtually only) | Yes (always) |
alloc_pages | 2^MAX_ORDER pages | Yes | Depends on GFP flag |
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
/* 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 */
dma_alloc_coherent() for DMA buffers instead.
vmalloc() always sleeps to set up page tables. It will BUG in interrupt context or while holding a spinlock.
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
/* 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
| Order | Pages | Size (4K pages) |
|---|---|---|
0 | 1 | 4 KB |
1 | 2 | 8 KB |
2 | 4 | 16 KB |
4 | 16 | 64 KB |
8 | 256 | 1 MB |
10 | 1024 | 4 MB (MAX_ORDER) |
Get Free Pages flags control allocator behavior — whether it can sleep, reclaim, use emergency reserves, or restrict to DMA zones.
Common flag combinations
| Flag | Sleeps? | Use when |
|---|---|---|
GFP_KERNEL | Yes | Normal kernel allocation in process context |
GFP_ATOMIC | No | Interrupt handlers, spinlock held |
GFP_NOWAIT | No | Non-blocking, but no emergency reserves |
GFP_NOIO | Yes | Reclaim allowed but no I/O (block layer use) |
GFP_NOFS | Yes | Reclaim allowed but no filesystem calls |
GFP_USER | Yes | Userspace allocations via kernel |
GFP_DMA | Yes | Must be in DMA-capable zone (<16 MB on x86) |
GFP_DMA32 | Yes | Must be below 4 GB physical (32-bit DMA) |
GFP_HIGHUSER | Yes | Userspace pages, can use highmem |
Modifier flags
| Modifier | Effect |
|---|---|
__GFP_ZERO | Zero-initialize returned memory |
__GFP_NOWARN | Suppress allocation failure warnings |
__GFP_RETRY_MAYFAIL | Retry hard, but may still fail |
__GFP_NOFAIL | Loop forever until success — use sparingly |
__GFP_HIGH | Use emergency memory reserves |
__GFP_COMP | Return compound page (huge page support) |
Device-managed resource helpers that auto-release when the device is unbound. Eliminates manual cleanup in remove() and error paths.
Common devm_ functions
/* 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);
remove() become trivial — just return the error. Less code, fewer leaks.
devm_kzalloc(), do not call kfree() on it. The devres framework will free it on device unbind — double-free will follow.
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
| Variant | Use when |
|---|---|
spin_lock / spin_unlock | Process context, no interrupt concern |
spin_lock_irq / spin_unlock_irq | Disable local IRQs while holding |
spin_lock_irqsave / spin_unlock_irqrestore | Save/restore IRQ state — use across function boundaries |
spin_lock_bh / spin_unlock_bh | Disable bottom halves (softirqs/tasklets) |
spin_trylock | Non-blocking attempt |
Usage
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);
kmalloc(GFP_KERNEL), mutex_lock(), msleep(), etc.) while a spinlock is held will deadlock on RT kernels and cause subtle bugs on non-RT.
spin_lock() in process context while an IRQ handler also calls spin_lock() on the same lock is a deadlock waiting to happen.
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
/* 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);
Allows multiple concurrent readers or one exclusive writer. Sleeping lock — process context only. Use when reads vastly outnumber writes.
Core API
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);
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
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));
read_seqretry() returns 0.
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
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
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);
srcu_read_lock() / srcu_read_unlock() allow sleeping readers at the cost of per-CPU data structures.
RCU vs other locks
| Primitive | Read cost | Write cost | Readers sleep? |
|---|---|---|---|
spinlock | Cache line bounce | Low | No |
rwsem | Atomic op | Sleeps | Yes |
RCU | Near-zero | Grace period wait | No (SRCU: yes) |
seqlock | Retry loop | Low | No |
Lock-free integer operations using hardware atomic instructions. Use for counters, flags, and simple state machines shared between contexts.
Core API (atomic_t)
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
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);
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
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); }
list_for_each_entry_safe() when you need to delete the current entry. The safe variant keeps a next pointer before processing each entry.
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
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) { ... } }
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
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 */
idr is now a thin wrapper around XArray; the old struct radix_tree_root API is deprecated.
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
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); }
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)
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
/* 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);
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
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() */ }
schedule_work() / schedule_delayed_work() instead.
Jiffies-resolution kernel timers. Callbacks run in softirq (atomic) context — no sleeping allowed. For sub-jiffie or nanosecond resolution, use hrtimers.
Core API
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)); }
High-resolution timers with nanosecond precision. Used internally for nanosleep(), itimers, and real-time tasks. Callback runs in hardirq or softirq context.
Core API
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 */ }
Simple reference counter with a release callback. The canonical way to manage object lifetime when multiple subsystems share ownership.
Core API
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);
kref_put(), treat the pointer as potentially invalid.
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
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 */
refcount_t saturates at INT_MAX and warns on increment-from-zero, preventing integer wrap-around use-after-free vulnerabilities.
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
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);
kobject_put(). The release callback in kobj_type is the only safe place to free the containing object.
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
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);
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
| Macro | Level | Value | Use when |
|---|---|---|---|
pr_emerg() | KERN_EMERG | 0 | System is unusable |
pr_alert() | KERN_ALERT | 1 | Action must be taken immediately |
pr_crit() | KERN_CRIT | 2 | Critical conditions |
pr_err() | KERN_ERR | 3 | Error conditions |
pr_warn() | KERN_WARNING | 4 | Warning conditions |
pr_notice() | KERN_NOTICE | 5 | Normal but significant condition |
pr_info() | KERN_INFO | 6 | Informational |
pr_debug() | KERN_DEBUG | 7 | Debug messages (compiled out by default) |
Usage
/* 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);
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
/* 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 */
-EPROBE_DEFER (which is not a real failure, just deferred probing).
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
/* 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");
printk() will saturate the console and can render the system unresponsive.
Dynamic debug
# 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 ☕