Skip to main content
The Linux kernel has a well-defined coding style described in Documentation/process/coding-style.rst. Adhering to it is not optional — patches that violate these conventions are routinely rejected by maintainers before any functional review takes place.
Run scripts/checkpatch.pl on your patch before submitting. It catches the majority of style violations automatically.

Indentation

Tabs are 8 characters. Indentation is also 8 characters. There are no exceptions outside of Kconfig files.
// Correct — 8-character tab indentation
switch (suffix) {
case 'G':
case 'g':
	mem <<= 30;
	break;
case 'M':
case 'm':
	mem <<= 20;
	break;
case 'K':
case 'k':
	mem <<= 10;
	fallthrough;
default:
	break;
}
switch and its case labels align in the same column. Do not double-indent case labels. If you need more than 3 levels of indentation, your code needs restructuring — the 8-character tab makes deep nesting visually painful by design.
Spaces are never used for indentation in .c and .h files. Editors that insert spaces instead of tabs will get your patch rejected.

Line length

The preferred limit is 80 columns. Statements longer than 80 columns should be broken into sensible chunks. The modern trend in the kernel allows up to 100 columns when it significantly improves readability without hiding information.
// Break long argument lists to align with the opening parenthesis
static int my_function(struct device *dev,
		       const char *name,
		       unsigned int flags)
{
	...
}
Never break user-visible strings such as printk messages — doing so breaks the ability to grep for them in dmesg output.

Placing braces and spaces

The kernel follows K&R style. Opening braces go at the end of the line for all non-function statement blocks (if, switch, for, while, do):
if (x == y) {
	...
} else if (x > y) {
	...
} else {
	...
}
Functions are the only exception — their opening brace goes on the next line:
int function(int x)
{
	body of function
}
Do not use braces where a single statement suffices:
// Correct
if (condition)
	action();

// Also correct
if (condition)
	do_this();
else
	do_that();
If one branch of a conditional is multi-line, use braces in both branches:
if (condition) {
	do_this();
	do_that();
} else {
	otherwise();
}

Spaces

Use a space after these keywords: if, switch, case, for, do, while. Do not use a space after sizeof, typeof, alignof, or __attribute__:
s = sizeof(struct file);    /* correct */
s = sizeof( struct file );  /* wrong */
Pointer * is adjacent to the name, not the type:
char *linux_banner;
unsigned long long memparse(char *ptr, char **retptr);
One space around binary and ternary operators (=, +, -, <, >, *, /, %, |, &, ^, <=, >=, ==, !=, ?, :). No space after unary operators (&, *, +, -, ~, !).

Naming conventions

Global functions and variables

Descriptive names using snake_case. count_active_users(), not cntusr(). Global functions named foo are a shooting offense.

Local variables

Short and to the point. A loop counter is i, not loop_counter. Temporary values are tmp. If you fear confusion, your function is too large.

Macros and enum constants

UPPERCASE. For example, #define CONSTANT 0x12345 and enum members like KOBJ_ADD, KOBJ_REMOVE.

Inclusive terminology

Avoid master/slave and blacklist/whitelist. Use primary/secondary, controller/device, allowlist/denylist instead.
Hungarian notation (encoding the type into the name) is explicitly prohibited. The compiler knows the types.

Functions

Functions should be short and do one thing well. They should fit on one or two screenfuls of text (80×24). The maximum length is inversely proportional to the function’s complexity and indentation level. Keep local variables to 5–10 at most. If you need more, split the function. When a function is exported, the EXPORT_SYMBOL macro follows immediately after the closing brace:
int system_is_up(void)
{
	return system_state == SYSTEM_RUNNING;
}
EXPORT_SYMBOL(system_is_up);

Function prototypes

Include parameter names in function prototypes. Do not use the extern keyword with function declarations. The preferred order of elements:
  1. Storage class (static __always_inline)
  2. Storage class attributes (__init, __cold)
  3. Return type (void *)
  4. Return type attributes (__must_check)
  5. Function name
  6. Parameters (always include names)
  7. Function parameter attributes (__printf(4, 5))
  8. Function behavior attributes (__malloc)

Centralized exit using goto

The goto statement is idiomatic in the kernel for centralized cleanup on multiple exit paths:
int fun(int a)
{
	int result = 0;
	char *buffer;

	buffer = kmalloc(SIZE, GFP_KERNEL);
	if (!buffer)
		return -ENOMEM;

	if (condition1) {
		while (loop1) {
			...
		}
		result = 1;
		goto out_free_buffer;
	}
	...
out_free_buffer:
	kfree(buffer);
	return result;
}
Label names must describe what the goto does. Use out_free_buffer: not err1:. Use separate labels for separate cleanup steps to avoid null-pointer bugs.

Comments

Comments should say what code does, not how it works. If you need to explain how, your code is too complex. Do not put comments inside a function body unless noting something particularly clever or ugly. Put the comment at the function’s head, explaining what it does and why. The preferred multi-line comment style:
/*
 * This is the preferred style for multi-line
 * comments in the Linux kernel source code.
 * Please use it consistently.
 *
 * Description: A column of asterisks on the left side,
 * with beginning and ending almost-blank lines.
 */
For kernel API documentation, use the kernel-doc format (see Documentation/doc-guide/).
Single-line // comments are permitted in C files since C99, but the multi-line /* */ style is overwhelmingly more common in the kernel. Use // sparingly.

Typedefs

Do not use typedef for structures and pointers. When you see:
vps_t a;
you cannot tell what a is. But:
struct virtual_container *a;
is immediately clear. Typedefs are acceptable only in these specific situations:
When the typedef actively hides what the object is and you can only access it via accessor functions. Example: pte_t and similar architecture-specific types.
u8, u16, u32, u64 and their signed equivalents are fine. But typedef unsigned long myflags_t; has no justification unless the type might change between unsigned int and unsigned long across configurations.
When you use sparse to create a new type for type-checking purposes.
Linux-specific u8/u16/u32/u64 types are permitted alternatives to uint8_t etc., though not mandatory in new code.
Structures shared with userspace use __u32 and similar __ prefixed types, since userspace cannot use kernel-internal types.
In general: if a struct or pointer has elements that can be directly accessed, it should never be a typedef.

Macros and enums

Constants defined by macros and enum members are CAPITALIZED:
#define CONSTANT 0x12345

#define CONSTEXP (CONSTANT | 3)   /* parenthesize expressions */
Enums are preferred over multiple #define constants for related values. Multi-statement macros must be wrapped in do { ... } while (0):
#define macrofun(a, b, c)			\
	do {					\
		if (a == 5)			\
			do_this(b, c);		\
	} while (0)
Function-like macros with unused parameters should be replaced by static inline functions:
static inline void fun(struct foo *foo)
{
}
Avoid macros that:
  • Affect control flow (contain hidden return or goto)
  • Depend on a local variable with a magic name
  • Have arguments used as l-values
  • Define constants without parenthesizing expressions
  • Introduce namespace collisions with local variable names
Prefer static inline functions over function-like macros — they solve the “expression with side effects evaluated more than once” problem and are properly type-checked by the compiler.

Printing kernel messages

Use the appropriate logging functions for the context:
dev_err(dev, "Failed to allocate buffer\n");
dev_warn(dev, "Unexpected state: %d\n", state);
dev_info(dev, "Driver loaded\n");
dev_dbg(dev, "Processing request %u\n", req_id);
From <linux/dev_printk.h>. These tag messages with the device and driver name, and route them through the correct subsystem.
/* When drivers are working properly, they are quiet */
dev_dbg(dev, "Request processed: id=%u len=%zu\n", id, len);

/* pr_debug() compiled out by default without CONFIG_DYNAMIC_DEBUG */
pr_debug("Entering %s\n", __func__);
Do not print numbers in parentheses. Do not use incorrect contractions like dont. Messages do not need a trailing period. Do not break printk strings across lines — it prevents grepping dmesg.

Memory allocation

Prefer the sizeof(*p) form over naming the type explicitly:
/* Correct — survives pointer type changes */
p = kmalloc(sizeof(*p), GFP_KERNEL);

/* Correct — zero-initialized */
p = kzalloc(sizeof(*p), GFP_KERNEL);

/* Correct — array allocation with overflow check */
p = kmalloc_array(n, sizeof(*p), GFP_KERNEL);

/* Correct — zero-initialized array */
p = kcalloc(n, sizeof(*p), GFP_KERNEL);
Do not cast void * return values — the C standard guarantees the implicit conversion. Do not use kmalloc + memset when kzalloc suffices.

BUG() and WARN() macros

Do not add new code that uses BUG(), BUG_ON(), or VM_BUG_ON(). These halt the kernel unconditionally. Instead:
  • Use WARN_ON_ONCE() (preferred) — fires only once to avoid log flooding
  • Use WARN_ON() — fires on each occurrence
  • Use WARN() — fires with a format string
WARN*() is for unexpected, should-never-happen situations only. Do not use it for conditions expected to trigger during normal operation or in response to user-space actions.
/* Compile-time assertions — zero runtime cost */
BUILD_BUG_ON(sizeof(struct my_struct) != 64);

/* Runtime assertion — prefer over BUG_ON */
WARN_ON_ONCE(refcount < 0);

Editor configuration

The kernel ships an .editorconfig file and a .clang-format file. For clang-format, the key settings reflect kernel style: AfterFunction: true (brace on next line for functions), IndentWidth: 8, UseTab: Always.
# Check style with clang-format
clang-format --style=file drivers/mydriver/myfile.c

# Check with checkpatch before submitting
scripts/checkpatch.pl --strict my.patch

# Reformat with GNU indent (K&R, 8-char indents)
indent -kr -i8 myfile.c
# or
scripts/Lindent myfile.c
For Emacs, add (c-basic-offset . 8) and (indent-tabs-mode . t) to your dir-locals. For Vim, :set tabstop=8 shiftwidth=8 noexpandtab.

Build docs developers (and LLMs) love