How to properly implement reference counting in Linux kernel modules to prevent use-after-free vulnerabilities?
11:41 21 Nov 2025

I'm developing a custom Linux kernel module for managing device resources, and I need to implement proper reference counting to prevent use-after-free (UAF) vulnerabilities.

My module maintains pointers to shared device structures that can be accessed from multiple contexts (interrupt handlers, work queues, and system calls). Without proper reference counting, there's a risk that a structure could be freed while another component is still using it.

I've tried:

  • Using atomic counters with kref_get() and kref_put()

  • Implementing cleanup with kref_release_callback()

  • Adding RCU (Read-Copy-Update) synchronization

Specific questions:

  1. What's the recommended pattern for combining kref with proper locking mechanisms?

  2. When should I use RCU vs. spinlocks vs. mutexes for reference-counted structures?

  3. How do I ensure all code paths properly increment/decrement references?

  4. Are there kernel debugging tools to detect reference counting issues?

I'm looking for best practices and code examples that demonstrate proper patterns.

c memory-management linux-kernel synchronization