Skip to content
systemcoding.dev
Kernels

The Complete Guide to Linux Kernel Development for Beginners

A beginner guide to Linux kernel development: how the kernel works, a safe lab, reading source, kernel C, a first module, debugging and a first patch.

27 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the Linux, C and FreeBSD logos.

Who this guide is for

Linux kernel development has a reputation for being closed off, and most of that reputation is wrong. The kernel is a very large C program with an unusually open process, and almost everything about it is documented, searchable and learnable by someone who can already write C. The difficulty is not secret knowledge. It is that the kernel is built on different assumptions from the programs you have written before, and no one tells you which assumptions changed.

This guide is the hub for beginners in this series. It assumes you can write and compile small C programs and use a Linux command line. It does not assume you have read any kernel code. It covers the mental model of what a kernel is and how Linux is organized, how to set up a lab where mistakes are cheap, how to read the source without drowning, how kernel C differs from the C you know, how to write and load a first module, how to see what your code is doing, how the development process works and how to send a first patch. Each section points at the deeper posts in the series. The examples target Linux 6.12 LTS on x86-64 with GCC 14, and facts about interfaces can be checked in the kernel documentation and the source.

You do not need special hardware. Everything here works in a virtual machine, and most of it works on any Linux laptop. What you need is patience for a large codebase and willingness to read the primary sources, because the kernel documents itself better than any article can.

What a kernel is and what it does

A kernel is the one program on a computer that the processor allows to touch the hardware directly. Every other program asks it for what it needs. Four jobs cover almost everything it does.

Process management gives many programs the illusion of having a processor each. The scheduler decides which runnable task gets a core and for how long, and the kernel records every task in a structure called task_struct.

Memory management gives each process a private virtual address space and decides which physical pages back it. The kernel builds page tables the processor walks on every access, allocates and reclaims pages, and keeps one program from reading another's memory.

Device access hides the differences between thousands of kinds of hardware behind a few abstractions: files, block devices, network interfaces. A program calls read and does not care whether the bytes come from flash, a network mount or RAM.

System calls are the controlled door through which programs ask for all of the above. A program loads a number and arguments into registers and executes a special instruction, and the processor switches to a higher privilege level at an entry point the kernel chose.

You can see the door with a program that skips the C library's wrappers and makes the calls itself:

whoami.cc
#define _GNU_SOURCE
#include <string.h>
#include <sys/syscall.h>
#include <unistd.h>

int main(void)
{
    long pid = syscall(SYS_getpid);

    char msg[] = "hello from the user side of the boundary\n";
    syscall(SYS_write, 1, msg, strlen(msg));

    return pid > 0 ? 0 : 1;
}
Shell
gcc -Wall -o whoami whoami.c
./whoami
Text
hello from the user side of the boundary

Two system calls ran: getpid and write. Everything the kernel did for this program happened between the syscall instruction and its return. Running it under strace shows the calls as they happen, and that tool is worth keeping at hand while you learn, since it shows the boundary from the user side.

User space and kernel space

The processor enforces the line between the two. Ordinary code runs at the lowest privilege level, where privileged instructions fault. The kernel runs at the highest, where nothing is forbidden. On x86-64 these are rings 3 and 0, and on ARM64 exception levels 0 and 1. The two also differ in address ranges: user space gets the lower half of the 48-bit canonical address space and the kernel the upper half, so a user program cannot even name a kernel address without a fault.

There are exactly three ways to cross from user to kernel: a system call the program requests, an exception such as a page fault, and an interrupt from a device or timer. All three arrive at addresses the kernel configured at boot. This matters to you as a developer because it explains the strict rules about passing data across the line: the kernel cannot trust a pointer from user space, so it uses checked copy functions rather than dereferencing it.

Kernel design in one paragraph

Linux is a monolithic kernel: the scheduler, memory manager, file systems, network stack and drivers all run in one privileged address space and call each other as ordinary functions. That makes calls cheap and gives every driver full privilege, which is why a driver bug can crash the whole machine. Microkernels such as MINIX 3 and seL4 move most services into separate user-space processes and pay for the isolation with message passing. Neither is better in the abstract; they trade speed for isolation. Linux gets much of its flexibility from loadable modules, pieces of kernel code that can be linked into a running kernel and removed again.

Set up a lab where mistakes are cheap

A mistake in kernel code does not end one process. It can freeze the machine, corrupt a file system or both. So the first step is not installing a compiler, it is deciding where your experiments run. There are three sensible choices, in order of safety.

A virtual machine is the best for beginners. A snapshot lets you roll back after a crash, and a kernel panic in the guest does not touch the host. Any hypervisor works. A QEMU session with your own kernel and a tiny initramfs is even better for learning how the pieces fit, and boots in seconds with no disk at all. A spare physical machine is the last choice, for hardware you must test on real devices. Do not experiment on the computer that holds your work.

Tools

On Debian or Ubuntu, one command installs what you need for the rest of the guide:

Shell
sudo apt install build-essential bc bison flex libssl-dev libelf-dev \
  libncurses-dev dwarves rsync cpio kmod git qemu-system-x86 \
  linux-headers-"$(uname -r)"

The first group builds a kernel, git fetches the source, qemu-system-x86 runs it in an emulator and the headers package lets you build modules for the kernel you are running. A later post in the series lists the packages for Fedora and Arch and explains what each one does, which is useful the first time a build stops with a missing-file error.

Getting the source

Clone a shallow copy of the stable tree at the version you will study:

Shell
git clone --depth 1 --branch v6.12 \
  https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git
cd linux
git describe
Text
v6.12

Pick one version and stay with it while you learn, because function names and file locations change between releases. Version 6.12 is a longterm branch, which makes it a stable target. Know the cycle you are entering: a new mainline version arrives about every ten weeks after a two-week merge window and weekly release candidates, and one release a year becomes a longterm branch that is maintained for years.

A first kernel that boots in an emulator

Before you write any kernel code, build and boot the kernel once. The point is not to learn the whole build system yet; it is to prove that the loop works end to end and to see what a boot looks like.

Shell
make defconfig
make -j"$(nproc)" bzImage
Text
  BUILD   arch/x86/boot/bzImage
Kernel: arch/x86/boot/bzImage is ready  (#1)

The defconfig target writes the x86-64 default configuration, and bzImage builds the compressed bootable kernel. A kernel needs a first user program to run, so write the smallest one possible, a static C program that prints a line and never exits:

init.cc
#include <stdio.h>
#include <unistd.h>

int main(void)
{
    printf("hello from PID %d\n", getpid());
    fflush(stdout);

    for (;;)
        pause();
}

Pack it as an initramfs, the archive the kernel unpacks into memory and runs /init from, then boot both under QEMU:

Shell
gcc -static -O2 -o init init.c
mkdir -p rootfs && cp init rootfs/init
( cd rootfs && echo init | cpio -o -H newc ) | gzip > initramfs.cpio.gz

qemu-system-x86_64 \
  -kernel arch/x86/boot/bzImage \
  -initrd initramfs.cpio.gz \
  -append "console=ttyS0 panic=-1" \
  -nographic -m 256M -no-reboot
Text
[    0.402118] Run /init as init process
hello from PID 1

Many kernel log lines scroll above those two. Exit with Ctrl-a then x. You have just seen the whole chain: the emulator loaded the kernel and the archive, the kernel set itself up, mounted the archive as its root and executed /init as process 1. If PID 1 exits, the kernel panics with Attempted to kill init, which is a good experiment because it shows why the first process is special.

Read the log you produced. The first lines are architecture setup, then initialization of the subsystems, then the initcalls that start built-in drivers, then the handoff to user space. Knowing where each stage sits will help you place problems later. A post in this series follows the boot path from firmware to PID 1 in detail.

How the source is organized

The kernel source is tens of millions of lines. Nobody reads it top to bottom, and nobody needs to. It is organized by responsibility, so knowing what a directory owns lets you predict where a feature lives.

DirectoryWhat it holds
arch/Code specific to a CPU architecture: boot, entry, page tables
kernel/Core, architecture-independent logic: scheduler, fork, signals, time
mm/Memory management
fs/File systems and the virtual file system layer
net/The network stack
drivers/Device drivers, by far the largest directory
block/The block layer between file systems and storage drivers
include/Headers; include/uapi/ is the stable contract with user space
init/Start-up code, including start_kernel()
lib/Generic helpers: lists, trees, string functions, printk formatting
security/Linux Security Modules such as SELinux and AppArmor
Documentation/The kernel's own documentation
scripts/Build and developer tools, including checkpatch.pl
tools/User-space programs built from the tree, such as perf
samples/Small working examples of kernel features

Finding where a feature lives

Work from the visible interface inward. Start from something you can observe: a system call name, a file under /proc or /sys, a message in the log or a configuration option. A system call leads to a SYSCALL_DEFINEn line. A log message is the most reliable of all, because the exact text is in the source. Search for a distinctive fragment of it, and the print statement leads you to the function that emitted it.

Shell
git grep -n "SYSCALL_DEFINE3(read," -- fs/
git grep -n "static int __ref kernel_init" -- init/
Text
fs/read_write.c:722:SYSCALL_DEFINE3(read, unsigned int, fd, char __user *, buf, size_t, count)
init/main.c:1458:static int __ref kernel_init(void *unused)

Line numbers differ between releases, so treat these as examples. The first shows how a system call is declared with a macro, and the second is the function that eventually runs /init. From a first hit, read upward to the callers and downward to the helpers, staying inside one subsystem until the question is answered.

Two tools make navigation fast. Elixir, the cross-referencer hosted at elixir.bootlin.com, indexes every released version, links every identifier to its definitions and references and requires no setup. cscope indexes your own checkout offline: make ARCH=x86 cscope builds the database and cscope -d opens it, with searches for definitions, callers and assignments. Callers and assignments are the two questions plain grep answers badly. When you reach a function pointer call such as inode->i_op->lookup, search for assignments to the field name, which finds every file system that fills it in, and that list is the real answer to "what happens when this is called".

Read the kernel-doc comment above any function you meet. Exported functions carry a structured comment that states the arguments, the return value and the locking rules, and it is more reliable than a blog post, including this one.

Kernel C is C with different rules

The kernel is written in C, mostly the GNU C11 dialect, and the language is the same. The environment around it is not. These differences cause most beginner mistakes.

There is no C library

You cannot call printf, malloc or strcpy from glibc. The library is built on system calls that the kernel itself provides, and the kernel is compiled freestanding, with the compiler told not to search the system headers. The kernel supplies its own equivalents:

User spaceKernelNotes
printfprintk, pr_info, dev_infoWrites to a log buffer you read with dmesg
malloc, freekmalloc, kfree, vmallocTakes GFP_ flags that say whether it may sleep
strncpystrscpyAlways terminates and reports truncation
errnonegative return values-ENOMEM, -EINVAL
read on a user buffercopy_from_user, copy_to_userChecked copies across the boundary
assertBUG_ON, WARN_ONHalt or warn with a stack trace
Floating pointavoidedThe FPU state is not saved by default

Errors are negative numbers

A kernel function that can fail returns zero for success and a negative errno constant for failure. A function that returns a pointer returns an encoded error with ERR_PTR(-ENOMEM), and the caller tests with IS_ERR(). Returning a bare -1 loses the reason and gets a patch rejected.

Cleanup uses goto

The kernel style uses goto for a single exit path that unwinds resources in reverse order. It looks odd at first, and it is the clearest way to write code with several failure points:

probe.cc
static int demo_probe(struct demo_dev *d)
{
	int ret;

	d->buf = kmalloc(4096, GFP_KERNEL);
	if (!d->buf)
		return -ENOMEM;

	ret = demo_register(d);
	if (ret)
		goto err_free_buf;

	ret = demo_start_irq(d);
	if (ret)
		goto err_unregister;

	return 0;

err_unregister:
	demo_unregister(d);
err_free_buf:
	kfree(d->buf);
	return ret;
}

Each label names what the code after it undoes, and a failure at any step jumps to the label that releases everything acquired so far. Newer code often uses the devm_ helpers, which tie resources to a device's lifetime, but you will read plenty of code written this way.

Linked lists are intrusive

The kernel does not use a generic container library. Its lists embed a struct list_head inside your own structure, and macros recover the containing structure from the embedded node. This is the first idiom worth learning, because it appears in almost every subsystem. Here is a small module that builds and walks a list:

lists.cc
#include <linux/init.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/slab.h>

struct item {
	int id;
	struct list_head node;
};

static LIST_HEAD(items);

static int __init lists_init(void)
{
	struct item *it;
	int i;

	for (i = 1; i <= 3; i++) {
		it = kmalloc(sizeof(*it), GFP_KERNEL);
		if (!it)
			return -ENOMEM;
		it->id = i;
		list_add_tail(&it->node, &items);
	}

	list_for_each_entry(it, &items, node)
		pr_info("lists: item %d\n", it->id);
	return 0;
}

static void __exit lists_exit(void)
{
	struct item *it, *tmp;

	list_for_each_entry_safe(it, tmp, &items, node) {
		list_del(&it->node);
		kfree(it);
	}
	pr_info("lists: freed\n");
}

module_init(lists_init);
module_exit(lists_exit);
MODULE_LICENSE("GPL");
Text
lists: item 1
lists: item 2
lists: item 3
lists: freed

The macro list_for_each_entry walks the list and gives you the struct item for each node, using container_of inside to compute it from the node's address. The _safe variant used on exit keeps the next pointer before the body runs, so it is legal to delete the current entry. There is a small leak in the example's error path: if an allocation fails halfway through, items already added are not freed. Finding and fixing that is a good exercise, and the goto pattern above is the tool.

Contexts decide what you may do

Kernel code runs in different contexts, and each has rules. Process context is code running on behalf of a task, such as a system call. It may sleep, take mutexes and allocate with GFP_KERNEL. Interrupt context, the hardware interrupt and softirq paths, has no task of its own. It must not sleep, may take only spinlocks and must allocate with GFP_ATOMIC. Calling a sleeping function from interrupt context produces the message BUG: sleeping function called from invalid context, and it is one of the first kernel bugs you will meet.

The usual pattern for an interrupt handler is to do the minimum, acknowledge the device and hand the rest to a context that may sleep. A workqueue item or a threaded interrupt handler runs the slow work in process context. A spinlock shared between an interrupt handler and process code must disable local interrupts while process code holds it, with spin_lock_irqsave, or the handler can interrupt the holder on the same CPU and wait forever. The context a function runs in is part of its contract, and the documentation says which it is.

Memory is not free

Kernel allocation always takes a flag. GFP_KERNEL may sleep to reclaim memory and is for process context. GFP_ATOMIC never sleeps and may fail, and it is for contexts that cannot wait. Always check the result for NULL, free exactly once and never touch memory after freeing it. Small objects come from kmalloc, which returns physically contiguous memory, and large ones from vmalloc, which is contiguous only in virtual space. Memory visible to user space comes through copy_to_user and copy_from_user, which return the number of bytes they could not copy, so a nonzero result means a bad user pointer and the function should return -EFAULT.

Your first module

A module is the gentlest way to run your own code in a kernel, because you can build it without the whole tree and load and unload it while the system runs. This is the smallest useful one.

hello.cc
#include <linux/init.h>
#include <linux/module.h>

static int __init hello_init(void)
{
	pr_info("hello: module loaded\n");
	return 0;
}

static void __exit hello_exit(void)
{
	pr_info("hello: module unloaded\n");
}

module_init(hello_init);
module_exit(hello_exit);

MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("A minimal hello-world kernel module");

There is no main. The module registers two callbacks, and the kernel calls the first at load and the second at removal. The init function returns zero for success or a negative errno, and the exit function must undo everything init did. MODULE_LICENSE("GPL") is not decoration: the kernel exports many symbols only to GPL-compatible modules, and a module without the right license taints the kernel.

The build uses the kernel's own build system with a two-line Makefile:

Makefilemakefile
obj-m += hello.o

KDIR ?= /lib/modules/$(shell uname -r)/build

all:
	$(MAKE) -C $(KDIR) M=$(CURDIR) modules

clean:
	$(MAKE) -C $(KDIR) M=$(CURDIR) clean

The recipe lines start with a tab. obj-m += hello.o says "build a module from hello.c", and the make -C line changes into the kernel's build tree and returns to your directory through M=. Build, load, look and unload:

Shell
make
sudo insmod ./hello.ko
sudo rmmod hello
sudo dmesg | tail -n 2
Text
[ 9120.481202] hello: module loaded
[ 9128.003987] hello: module unloaded

The timestamps differ. The messages did not appear on your terminal because pr_info writes to the kernel log buffer, which dmesg prints. If insmod fails with Invalid module format, the module was built against a different kernel than the running one: compare modinfo -F vermagic hello.ko with uname -r. A separate hub guide in this series covers modules in full: parameters, exported symbols, a character device, licensing, signing and packaging.

Run this in a virtual machine, and run it more than once. Add a parameter, print the name of the loading task with current->comm, make the init function fail with -ENOMEM and watch the load fail. Each variation teaches one idea while keeping everything else familiar.

Seeing what your code does

Kernel debugging starts with the log. printk and its wrappers pr_info, pr_warn and pr_err write messages with a severity level. The log level also decides what reaches the console. For messages you want to switch on and off at run time, use pr_debug or dev_dbg with dynamic debug, enabled by CONFIG_DYNAMIC_DEBUG:

Shell
echo 'module hello +p' | sudo tee /sys/kernel/debug/dynamic_debug/control
Text
module hello +p

Every pr_debug in that module then prints, and -p switches them off. Dynamic debug compiles the statements in but disabled, so leaving them in costs almost nothing.

Reading an oops

When kernel code makes a fatal error, such as dereferencing a null pointer, the kernel prints an oops: a report of what failed, the registers and a call trace. A trimmed example looks like this:

Text
BUG: kernel NULL pointer dereference, address: 0000000000000008
#PF: supervisor read access in kernel mode
#PF: error_code(0x0000) - not-present page
RIP: 0010:hello_init+0x12/0x30 [hello]
Call Trace:
 <TASK>
 do_one_initcall+0x5a/0x300
 do_init_module+0x60/0x230
 __do_sys_finit_module+0xb5/0xf0
 do_syscall_64+0x82/0x190
</TASK>

The numbers and symbol offsets vary. Read it from the top. The first line says what happened. RIP is the instruction that failed, here at offset 0x12 inside hello_init of the module hello. The call trace shows how execution got there, from the system call down. Turn the offset into a source line by building the module with debug information and running addr2line or, in the kernel tree, scripts/decode_stacktrace.sh. After an oops the kernel is tainted, so reboot before drawing conclusions from later behavior.

Build a debugging kernel

The cheapest way to learn what is wrong with your code is to let the kernel check it for you. Build a test kernel with the options that turn silent corruption into a precise report: CONFIG_PROVE_LOCKING for locking mistakes, CONFIG_DEBUG_ATOMIC_SLEEP for sleeping in atomic context, CONFIG_KASAN for memory errors such as out-of-bounds accesses and use after free, and CONFIG_DEBUG_KMEMLEAK for leaks. Enable them with scripts/config, resolve dependencies with make olddefconfig, and rebuild. The slowdown is real, which is why you use this kernel for testing and not for daily work.

Locks, with an example

Concurrency is the idea that most separates kernel programming from the programs you have written. Two processes can call into your code at the same moment on two CPUs, and an interrupt can arrive in the middle of either. Shared data needs protection, and the kernel gives you two basic locks. A mutex puts the caller to sleep while it waits, so it can be held across operations that sleep and can be taken only in process context. A spinlock busy-waits, so it can be used where sleeping is forbidden, and it must be held only for a short, non-sleeping critical section.

This small module shares a counter between an increment function and a reader, protected by a mutex, and shows the pattern you will repeat everywhere:

locked.cc
#include <linux/init.h>
#include <linux/module.h>
#include <linux/mutex.h>

static DEFINE_MUTEX(counter_lock);
static unsigned long counter;

static unsigned long counter_bump(void)
{
	unsigned long v;

	mutex_lock(&counter_lock);
	v = ++counter;
	mutex_unlock(&counter_lock);
	return v;
}

static int __init locked_init(void)
{
	pr_info("locked: first=%lu\n", counter_bump());
	pr_info("locked: second=%lu\n", counter_bump());
	return 0;
}

static void __exit locked_exit(void)
{
	pr_info("locked: final=%lu\n", counter);
}

module_init(locked_init);
module_exit(locked_exit);
MODULE_LICENSE("GPL");
Text
locked: first=1
locked: second=2
locked: final=2

The lock is declared with DEFINE_MUTEX, taken before the shared variable is touched and released immediately after. Nothing about the example fails without the lock on a single CPU with one caller, and that is exactly the trap: the bug appears only when two callers overlap, which is rare in testing and common in production. The kernel's lock validator, CONFIG_PROVE_LOCKING, watches every lock operation in a test kernel and reports a potential deadlock, such as two locks taken in opposite orders, before it ever happens. Turn it on while you write locking code.

Choose the lock by the context. If the code can run in an interrupt handler, use a spinlock, and if process code shares the lock with the handler, take it with spin_lock_irqsave. If the critical section can sleep, use a mutex. If the data is read often and written rarely, ask whether read-copy-update fits, which the memory documentation explains. Whatever you pick, keep critical sections short and never call a function that might sleep while holding a spinlock.

Stepping through the kernel with a debugger

Print statements go a long way, but sometimes you want to stop the kernel at a function and look around. QEMU can expose a GDB stub, and the kernel built with debug information gives GDB the symbols. Enable CONFIG_DEBUG_INFO_DWARF_TOOLCHAIN_DEFAULT and disable CONFIG_RANDOMIZE_BASE, which randomizes the kernel's load address and confuses breakpoints. Then start the emulator halted, with the stub listening:

Shell
qemu-system-x86_64 \
  -kernel arch/x86/boot/bzImage \
  -initrd initramfs.cpio.gz \
  -append "console=ttyS0 nokaslr" \
  -nographic -m 256M -s -S

The -s option opens a GDB server on TCP port 1234 and -S stops the virtual CPU at the first instruction until a debugger tells it to continue. In another terminal, attach GDB to the uncompressed kernel and set a breakpoint:

Shell
gdb vmlinux
Text
(gdb) target remote :1234
(gdb) hbreak start_kernel
(gdb) continue
Breakpoint 1, start_kernel () at init/main.c:1085
(gdb) bt
#0  start_kernel () at init/main.c:1085
#1  0xffffffff81000145 in secondary_startup_64 ()

A hardware breakpoint (hbreak) is the right choice this early, because software breakpoints need memory the kernel has not yet mapped for writing. The file and line shown depend on your tree. Once there, next, step, print and list behave as they do for any program, and you can walk through the same boot sequence described earlier. The kernel also ships GDB helper scripts under scripts/gdb/ that add commands to list tasks and modules, which you load with source vmlinux-gdb.py after building with CONFIG_GDB_SCRIPTS. Debugging through the stub is more work than a print, and for tricky ordering problems it is worth the setup.

Memory in practice

Two allocation functions cover most cases, and the difference between them shows what the kernel does with memory. kmalloc returns memory that is contiguous in both virtual and physical address space, taken from slab caches, and is the right choice for objects up to a few pages. vmalloc returns memory that is contiguous only in virtual space, assembled from scattered pages, and is meant for large buffers. Physical contiguity matters when a device does DMA directly, since a device sees physical addresses, and that is why driver buffers come from the DMA API and not from vmalloc.

The GFP flags describe what the allocator may do to satisfy the request. GFP_KERNEL allows sleeping and reclaim, GFP_ATOMIC forbids sleeping and uses an emergency reserve, and a request in a context that cannot sleep must use the second. A quick check of an allocation is to ask three questions: may this code sleep, who frees the memory and on which path, and what happens if the allocation fails. A kernel that runs out of memory kills processes, so a failed allocation in a driver should return an error and not panic.

Habits that pay off for years

Three habits separate people who keep learning the kernel from those who stall. Read code that was merged recently, not only old code: git log -p on a subsystem you care about shows how experienced developers make small, reviewable changes, and the commit messages explain the reasoning in a way no tutorial does. Keep a notebook of every kernel message and oops you decode, with the cause, because the same classes of bug return. And build the habit of reading the documentation for an API before using it, including the locking rules, since the rules for a function are part of its prototype in every way that matters.

A first week plan

A concrete schedule keeps a beginner moving. On the first day, set up the virtual machine, clone the 6.12 source, install the tools and boot the tiny kernel in QEMU. On the second, read the source tree map and trace one system call from its SYSCALL_DEFINE to the function that does the work. On the third, write and load the hello-world module, then add a parameter and a failing init. On the fourth, build a test kernel with the debug options on and write a module with a deliberate locking mistake to see the report it produces. On the fifth, read Documentation/process/coding-style.rst and submitting-patches.rst and run checkpatch.pl against a file in drivers/staging. On the weekend, prepare one small cleanup patch, build it with W=1, and send it.

That plan is not a promise of skill by the end of the week; it is a way of touching every part of the process once, so that none of it is a mystery. After that, the posts in the series go deeper into each area, in the order of the ladder above.

How kernel development works

The kernel project's process is public and documented, and a beginner can take part. The key facts will save you weeks.

The tree is maintained as a hierarchy. Linus Torvalds maintains the mainline tree and merges changes sent by subsystem maintainers, each of whom owns a part of the tree and a mailing list. Patches go to the maintainer of the code they change, who reviews and merges them into a subsystem tree, which later flows up. Changes are tested together in linux-next before the merge window.

Patches are sent as email. There is no pull request button. You create a patch with git format-patch, send it with git send-email to the maintainers and the list the tree names, and respond to review by email. The mailing list is the record of the discussion.

Every file knows who maintains it. The MAINTAINERS file at the root lists every subsystem with its maintainers, lists and files, and scripts/get_maintainer.pl reads it for you:

Shell
scripts/get_maintainer.pl -f drivers/staging/rtl8723bs/os_dep/os_intfs.c
Text
Greg Kroah-Hartman <[email protected]> (maintainer:STAGING SUBSYSTEM)
[email protected] (open list:STAGING SUBSYSTEM)
[email protected] (open list)

The names and lists depend on your tree and the file, and this output is an example of the format.

Style is checked mechanically. The kernel coding style is documented, with tabs of eight columns, an 80-column preference, no typedefs for structs and negative errno returns. scripts/checkpatch.pl checks most of it, and patches that fail it are sent back:

Shell
scripts/checkpatch.pl --strict -g HEAD
Text
total: 0 errors, 0 warnings, 0 checks, 14 lines checked

Your patch has no obvious style problems and is ready for submission.

Anatomy of a patch

A patch is a git commit with a particular shape. The subject line starts with the subsystem and a colon, is written in the imperative and says what changes. The body explains why, and the last lines carry the sign-off, which certifies that you have the right to submit the code under the project's rules, the Developer Certificate of Origin. git commit -s adds the line from your configured name and email.

Text
staging: rtl8723bs: remove unused variable in rtw_init_default_value

The variable "pregistrypriv" is assigned but never used after the
conversion to the new helper. Remove it to silence the compiler
warning reported with W=1.

Signed-off-by: Your Name <[email protected]>

The subsystem prefix, the reason in the body and the sign-off are all required in practice. Then create and send:

Shell
git format-patch -1 HEAD
git send-email [email protected] 0001-staging-rtl8723bs-remove-unused-variable.patch

The first command writes the patch file from your last commit, and the second sends it by email. The Documentation/process/submitting-patches.rst file in the tree describes every convention, and it is the document to read before you send anything.

Good first contributions

Beginners are welcome, and the community keeps places for them. The drivers/staging/ directory holds drivers that are not yet up to standard, and cleaning them up, one small change at a time, is the traditional first step: fix a checkpatch.pl warning, remove an unused variable or fix a typo in a comment. Documentation fixes are valued, and so are reports of reproducible bugs with a clear description. Whichever you choose, keep the change small, build it, run checkpatch.pl, compile it with W=1, and send it to the right people. Expect review comments and respond politely; asking questions is normal, and a first patch that goes through two revisions is typical.

Respect the project's rules. Do not send a change you do not understand. Do not paste output from a code generator into a patch without reading and being able to defend every line, because you are certifying the work with your sign-off. And do not send the same patch to the whole world: send it to the maintainers and lists that get_maintainer.pl prints.

A learning path through this series

The kernel is large, and a path through it prevents the common beginner problem of reading everything and understanding nothing. The ladder in this series climbs in this order.

  1. Fundamentals. What a kernel does, user space versus kernel space, privilege levels, the source tree, kernel style, why there is no libc, the release cycle, how the kernel boots and the two contexts. This guide and the posts around it cover that.

  2. Building and configuring. Compiling from source, menuconfig, Kconfig and Kbuild, cross compiling, ccache, a QEMU test setup. The guide on building and configuring the kernel is the hub.

  3. Loadable modules. Hello world, parameters, loading at boot, DKMS and blacklisting. The guide on modules is the hub.

  4. Character drivers, block drivers and file systems. The first real drivers, device numbers, file_operations, the VFS.

  5. Platform, I2C, SPI, USB and PCI drivers. Hardware buses and device tree.

  6. Core subsystems. System calls, the scheduler, memory management, interrupts and deferred work, synchronization.

  7. Debugging and tracing. procfs, sysfs, debugfs, ftrace, kprobes, eBPF on the kernel side.

  8. Advanced and other kernels. Rust for Linux, hobby operating systems, FreeBSD, XNU and the contribution workflow.

At each rung, write something. Reading alone does not build the skill: the first time a module you wrote locks up a virtual machine, you learn more about contexts than a chapter can teach.

Mistakes beginners make

A short list of mistakes saves a lot of frustration, because the same ones recur.

  • Experimenting on the machine that holds your work. Use a virtual machine with snapshots.

  • Building a module against the wrong headers. The module must match the running kernel, so install linux-headers-$(uname -r) and check vermagic on a load failure.

  • Sleeping in a context that may not sleep. Know whether your function runs in process or interrupt context, and run a kernel with DEBUG_ATOMIC_SLEEP while you develop.

  • Trusting a user pointer. Always use copy_from_user and copy_to_user, and check lengths before you copy.

  • Forgetting error paths. Every register needs an unregister, and every allocation needs a free on every path out.

  • Ignoring concurrency. The kernel is preemptive and runs on many CPUs. Shared state needs a lock, and the code that works with one caller and breaks with two is the commonest bug in new drivers.

  • Reading too much, writing too little. Pick a small goal, read only the code that serves it and write something that runs.

  • Skipping the documentation. The kernel's own documents are accurate, current and free. Read them before blog posts.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.