Learn to write kernel modules — code that runs with full kernel privileges. This is the ultimate systems programming: no standard library, no user-space protections, direct hardware access.There is no safety net here. In user space, a null pointer dereference gives you a segfault and the OS kills your process — annoying but recoverable. In kernel space, the same bug triggers a kernel panic (the Linux equivalent of a Blue Screen of Death), taking down the entire machine and every process running on it. You cannot call printf, malloc, or any libc function. You use printk instead of printf, kmalloc instead of malloc, and a completely different set of rules for memory management, error handling, and concurrency.
#include <linux/slab.h>#include <linux/gfp.h>#include <linux/vmalloc.h>void memory_examples(void) { void *ptr; struct page *page; // kmalloc - physically contiguous memory, up to ~128KB (varies by system). // Use for small allocations, DMA buffers, or anything that needs a physical // address. Backed by the slab allocator, so it is fast for common sizes. ptr = kmalloc(1024, GFP_KERNEL); if (ptr) { // PITFALL: Unlike user-space malloc, kmalloc returns memory from a // limited pool. Allocating large amounts can fail even when the system // has plenty of RAM, because it needs CONTIGUOUS physical pages. kfree(ptr); } // kzalloc - same as kmalloc but zero-initialized (like calloc). // Always prefer kzalloc over kmalloc for structs -- uninitialized kernel // memory can leak sensitive data to user space (information disclosure vuln). ptr = kzalloc(1024, GFP_KERNEL); if (ptr) { kfree(ptr); } // vmalloc - virtually contiguous but physically scattered pages. // Use for large allocations where you do not need physical contiguity. // Slower than kmalloc (requires page table manipulation) and cannot be // used for DMA. Do not use in interrupt context. ptr = vmalloc(1024 * 1024); // 1MB if (ptr) { vfree(ptr); } // Get free pages - for DMA or large buffers page = alloc_pages(GFP_KERNEL, 2); // 2^2 = 4 pages if (page) { ptr = page_address(page); free_pages((unsigned long)ptr, 2); }}// GFP flags -- choosing the wrong one is a common source of kernel bugs:// GFP_KERNEL - Normal allocation, may sleep. Use in process context (syscalls,// workqueues). NEVER use in interrupt handlers or with spinlocks held.// GFP_ATOMIC - Never sleeps, uses emergency memory reserves. Use in interrupt// context or when holding spinlocks. More likely to fail than GFP_KERNEL.// GFP_DMA - Memory from the DMA zone (first 16MB on x86). Required for// legacy ISA DMA devices. Rarely needed on modern hardware.// Slab cache for frequent allocations of same-size objectsstatic struct kmem_cache *my_cache;struct my_object { int data[16]; struct list_head list;};void slab_example(void) { struct my_object *obj; // Create cache my_cache = kmem_cache_create("my_objects", sizeof(struct my_object), 0, // Alignment 0, // Flags NULL); // Constructor // Allocate object obj = kmem_cache_alloc(my_cache, GFP_KERNEL); // Free object kmem_cache_free(my_cache, obj); // Destroy cache kmem_cache_destroy(my_cache);}
#include <linux/spinlock.h>#include <linux/mutex.h>#include <linux/semaphore.h>#include <linux/rwlock.h>#include <linux/atomic.h>// Spinlock - the CPU literally spins in a tight loop waiting for the lock.// Use ONLY for very short critical sections (a few lines, no function calls// that might sleep). Unlike user-space mutexes, spinlocks disable preemption// and (with irqsave) interrupts -- calling kmalloc(GFP_KERNEL), schedule(),// or copy_from_user() while holding a spinlock will deadlock or crash.static DEFINE_SPINLOCK(my_spinlock);static unsigned long flags;void spinlock_example(void) { spin_lock_irqsave(&my_spinlock, flags); // Save interrupt state + disable IRQs + lock // Critical section - VERY short, no sleeping, no user-space access spin_unlock_irqrestore(&my_spinlock, flags); // Restore original interrupt state}// Mutex - sleepable lock for longer critical sections.// Can ONLY be used in process context (not interrupt handlers, not softirqs).// The calling thread sleeps if the lock is held, freeing the CPU for other work.static DEFINE_MUTEX(my_mutex);void mutex_example(void) { mutex_lock(&my_mutex); // Critical section - can call sleeping functions like kmalloc(GFP_KERNEL), // copy_from_user(), msleep(), etc. mutex_unlock(&my_mutex);}// Read-write lockstatic DEFINE_RWLOCK(my_rwlock);void rwlock_example(void) { // Multiple readers allowed read_lock(&my_rwlock); // Read data read_unlock(&my_rwlock); // Exclusive write access write_lock(&my_rwlock); // Modify data write_unlock(&my_rwlock);}// Atomic operationsstatic atomic_t counter = ATOMIC_INIT(0);void atomic_example(void) { atomic_inc(&counter); atomic_dec(&counter); atomic_add(5, &counter); int val = atomic_read(&counter); // Atomic test-and-set if (atomic_cmpxchg(&counter, 0, 1) == 0) { // Successfully changed from 0 to 1 }}// Completion - waiting for eventsstatic DECLARE_COMPLETION(my_completion);void completion_example(void) { // Waiter thread wait_for_completion(&my_completion); // Signaler thread complete(&my_completion); // Wake one waiter // complete_all(&my_completion); // Wake all waiters}