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:
What's the recommended pattern for combining kref with proper locking mechanisms?
When should I use RCU vs. spinlocks vs. mutexes for reference-counted structures?
How do I ensure all code paths properly increment/decrement references?
Are there kernel debugging tools to detect reference counting issues?
I'm looking for best practices and code examples that demonstrate proper patterns.