Unreliable Guide To Hacking The Linux Kernel¶
| Author: | Rusty Russell |
|---|
Introduction¶
Welcome, gentle reader, to Rusty’s Remarkably Unreliable Guide to LinuxKernel Hacking. This document describes the common routines and generalrequirements for kernel code: its goal is to serve as a primer for Linuxkernel development for experienced C programmers. I avoid implementationdetails: that’s what the code is for, and I ignore whole tracts ofuseful routines.
Before you read this, please understand that I never wanted to writethis document, being grossly under-qualified, but I always wanted toread it, and this was the only way. I hope it will grow into acompendium of best practice, common starting points and randominformation.
The Players¶
At any time each of the CPUs in a system can be:
- not associated with any process, serving a hardware interrupt;
- not associated with any process, serving a softirq or tasklet;
- running in kernel space, associated with a process (user context);
- running a process in user space.
There is an ordering between these. The bottom two can preempt eachother, but above that is a strict hierarchy: each can only be preemptedby the ones above it. For example, while a softirq is running on a CPU,no other softirq will preempt it, but a hardware interrupt can. However,any other CPUs in the system execute independently.
We’ll see a number of ways that the user context can block interrupts,to become truly non-preemptable.
User Context¶
User context is when you are coming in from a system call or other trap:like userspace, you can be preempted by more important tasks and byinterrupts. You can sleep, by callingschedule().
Note
You are always in user context on module load and unload, and onoperations on the block device layer.
In user context, thecurrent pointer (indicating the task we arecurrently executing) is valid, andin_interrupt()(include/linux/preempt.h) is false.
Warning
Beware that if you have preemption or softirqs disabled (see below),in_interrupt() will return a false positive.
Hardware Interrupts (Hard IRQs)¶
Timer ticks, network cards and keyboard are examples of real hardwarewhich produce interrupts at any time. The kernel runs interrupthandlers, which services the hardware. The kernel guarantees that thishandler is never re-entered: if the same interrupt arrives, it is queued(or dropped). Because it disables interrupts, this handler has to befast: frequently it simply acknowledges the interrupt, marks a ‘softwareinterrupt’ for execution and exits.
You can tell you are in a hardware interrupt, becausein_irq() returns true.
Warning
Beware that this will return a false positive if interrupts aredisabled (see below).
Software Interrupt Context: Softirqs and Tasklets¶
Whenever a system call is about to return to userspace, or a hardwareinterrupt handler exits, any ‘software interrupts’ which are markedpending (usually by hardware interrupts) are run (kernel/softirq.c).
Much of the real interrupt handling work is done here. Early in thetransition to SMP, there were only ‘bottom halves’ (BHs), which didn’ttake advantage of multiple CPUs. Shortly after we switched from wind-upcomputers made of match-sticks and snot, we abandoned this limitationand switched to ‘softirqs’.
include/linux/interrupt.h lists the different softirqs. A veryimportant softirq is the timer softirq (include/linux/timer.h): youcan register to have it call functions for you in a given length oftime.
Softirqs are often a pain to deal with, since the same softirq will runsimultaneously on more than one CPU. For this reason, tasklets(include/linux/interrupt.h) are more often used: they aredynamically-registrable (meaning you can have as many as you want), andthey also guarantee that any tasklet will only run on one CPU at anytime, although different tasklets can run simultaneously.
Warning
The name ‘tasklet’ is misleading: they have nothing to do with‘tasks’, and probably more to do with some bad vodka AlexeyKuznetsov had at the time.
You can tell you are in a softirq (or tasklet) using thein_softirq() macro (include/linux/preempt.h).
Warning
Beware that this will return a false positive if abotton half lock is held.
Some Basic Rules¶
- No memory protection
- If you corrupt memory, whether in user context or interrupt context,the whole machine will crash. Are you sure you can’t do what youwant in userspace?
- No floating point or MMX
- The FPU context is not saved; even in user context the FPU stateprobably won’t correspond with the current process: you would messwith some user process’ FPU state. If you really want to do this,you would have to explicitly save/restore the full FPU state (andavoid context switches). It is generally a bad idea; use fixed pointarithmetic first.
- A rigid stack limit
- Depending on configuration options the kernel stack is about 3K to6K for most 32-bit architectures: it’s about 14K on most 64-bitarchs, and often shared with interrupts so you can’t use it all.Avoid deep recursion and huge local arrays on the stack (allocatethem dynamically instead).
- The Linux kernel is portable
- Let’s keep it that way. Your code should be 64-bit clean, andendian-independent. You should also minimize CPU specific stuff,e.g. inline assembly should be cleanly encapsulated and minimized toease porting. Generally it should be restricted to thearchitecture-dependent part of the kernel tree.
ioctls: Not writing a new system call¶
A system call generally looks like this:
asmlinkage long sys_mycall(int arg){ return 0;}First, in most cases you don’t want to create a new system call. Youcreate a character device and implement an appropriate ioctl for it.This is much more flexible than system calls, doesn’t have to be enteredin every architecture’sinclude/asm/unistd.h andarch/kernel/entry.S file, and is much more likely to be accepted byLinus.
If all your routine does is read or write some parameter, considerimplementing asysfs() interface instead.
Inside the ioctl you’re in user context to a process. When a erroroccurs you return a negated errno (seeinclude/uapi/asm-generic/errno-base.h,include/uapi/asm-generic/errno.h andinclude/linux/errno.h),otherwise you return 0.
After you slept you should check if a signal occurred: the Unix/Linuxway of handling signals is to temporarily exit the system call with the-ERESTARTSYS error. The system call entry code will switch back touser context, process the signal handler and then your system call willbe restarted (unless the user disabled that). So you should be preparedto process the restart, e.g. if you’re in the middle of manipulatingsome data structure.
if (signal_pending(current)) return -ERESTARTSYS;
If you’re doing longer computations: first think userspace. If youreally want to do it in kernel you should regularly check if you needto give up the CPU (remember there is cooperative multitasking per CPU).Idiom:
cond_resched(); /* Will sleep */
A short note on interface design: the UNIX system call motto is “Providemechanism not policy”.
Recipes for Deadlock¶
You cannot call any routines which may sleep, unless:
- You are in user context.
- You do not own any spinlocks.
- You have interrupts enabled (actually, Andi Kleen says that thescheduling code will enable them for you, but that’s probably notwhat you wanted).
Note that some functions may sleep implicitly: common ones are the userspace access functions (*_user) and memory allocation functionswithoutGFP_ATOMIC.
You should always compile your kernelCONFIG_DEBUG_ATOMIC_SLEEP on,and it will warn you if you break these rules. If youdo break therules, you will eventually lock up your box.
Really.
Common Routines¶
printk()¶
Defined ininclude/linux/printk.h
printk() feeds kernel messages to the console, dmesg, andthe syslog daemon. It is useful for debugging and reporting errors, andcan be used inside interrupt context, but use with caution: a machinewhich has its console flooded with printk messages is unusable. It usesa format string mostly compatible with ANSI C printf, and C stringconcatenation to give it a first “priority” argument:
printk(KERN_INFO "i = %u\n", i);
Seeinclude/linux/kern_levels.h; for otherKERN_ values; these areinterpreted by syslog as the level. Special case: for printing an IPaddress use:
__be32 ipaddress;printk(KERN_INFO "my ip: %pI4\n", &ipaddress);
printk() internally uses a 1K buffer and does not catchoverruns. Make sure that will be enough.
Note
You will know when you are a real kernel hacker when you starttypoing printf as printk in your user programs :)
Note
Another sidenote: the original Unix Version 6 sources had a commenton top of its printf function: “Printf should not be used forchit-chat”. You should follow that advice.
copy_to_user() /copy_from_user() /get_user() /put_user()¶
Defined ininclude/linux/uaccess.h /asm/uaccess.h
[SLEEPS]
put_user() andget_user() are used to getand put single values (such as an int, char, or long) from and touserspace. A pointer into userspace should never be simply dereferenced:data should be copied using these routines. Both return-EFAULT or0.
copy_to_user() andcopy_from_user() aremore general: they copy an arbitrary amount of data to and fromuserspace.
Warning
Unlikeput_user() andget_user(), theyreturn the amount of uncopied data (ie. 0 still means success).
[Yes, this moronic interface makes me cringe. The flamewar comes upevery year or so. –RR.]
The functions may sleep implicitly. This should never be called outsideuser context (it makes no sense), with interrupts disabled, or aspinlock held.
kmalloc()/kfree()¶
Defined ininclude/linux/slab.h
[MAY SLEEP: SEE BELOW]
These routines are used to dynamically request pointer-aligned chunks ofmemory, like malloc and free do in userspace, butkmalloc() takes an extra flag word. Important values:
GFP_KERNEL- May sleep and swap to free memory. Only allowed in user context, butis the most reliable way to allocate memory.
GFP_ATOMIC- Don’t sleep. Less reliable than
GFP_KERNEL, but may be calledfrom interrupt context. You shouldreally have a goodout-of-memory error-handling strategy. GFP_DMA- Allocate ISA DMA lower than 16MB. If you don’t know what that is youdon’t need it. Very unreliable.
If you see a sleeping function called from invalid context warningmessage, then maybe you called a sleeping allocation function frominterrupt context withoutGFP_ATOMIC. You should really fix that.Run, don’t walk.
If you are allocating at leastPAGE_SIZE (asm/page.h orasm/page_types.h) bytes, consider using__get_free_pages()(include/linux/gfp.h). It takes an order argument (0 for page sized,1 for double page, 2 for four pages etc.) and the same memory priorityflag word as above.
If you are allocating more than a page worth of bytes you can usevmalloc(). It’ll allocate virtual memory in the kernelmap. This block is not contiguous in physical memory, but the MMU makesit look like it is for you (so it’ll only look contiguous to the CPUs,not to external device drivers). If you really need large physicallycontiguous memory for some weird device, you have a problem: it ispoorly supported in Linux because after some time memory fragmentationin a running kernel makes it hard. The best way is to allocate the blockearly in the boot process via thealloc_bootmem()routine.
Before inventing your own cache of often-used objects consider using aslab cache ininclude/linux/slab.h
current()¶
Defined ininclude/asm/current.h
This global variable (really a macro) contains a pointer to the currenttask structure, so is only valid in user context. For example, when aprocess makes a system call, this will point to the task structure ofthe calling process. It isnot NULL in interrupt context.
mdelay()/udelay()¶
Defined ininclude/asm/delay.h /include/linux/delay.h
Theudelay() andndelay() functions can beused for small pauses. Do not use large values with them as you riskoverflow - the helper functionmdelay() is useful here, orconsidermsleep().
cpu_to_be32()/be32_to_cpu()/cpu_to_le32()/le32_to_cpu()¶
Defined ininclude/asm/byteorder.h
Thecpu_to_be32() family (where the “32” can be replacedby 64 or 16, and the “be” can be replaced by “le”) are the general wayto do endian conversions in the kernel: they return the converted value.All variations supply the reverse as well:be32_to_cpu(), etc.
There are two major variations of these functions: the pointervariation, such ascpu_to_be32p(), which take a pointerto the given type, and return the converted value. The other variationis the “in-situ” family, such ascpu_to_be32s(), whichconvert value referred to by the pointer, and return void.
local_irq_save()/local_irq_restore()¶
Defined ininclude/linux/irqflags.h
These routines disable hard interrupts on the local CPU, and restorethem. They are reentrant; saving the previous state in their oneunsignedlongflags argument. If you know that interrupts areenabled, you can simply uselocal_irq_disable() andlocal_irq_enable().
local_bh_disable()/local_bh_enable()¶
Defined ininclude/linux/bottom_half.h
These routines disable soft interrupts on the local CPU, and restorethem. They are reentrant; if soft interrupts were disabled before, theywill still be disabled after this pair of functions has been called.They prevent softirqs and tasklets from running on the current CPU.
smp_processor_id()¶
Defined ininclude/linux/smp.h
get_cpu() disables preemption (so you won’t suddenly getmoved to another CPU) and returns the current processor number, between0 andNR_CPUS. Note that the CPU numbers are not necessarilycontinuous. You return it again withput_cpu() when youare done.
If you know you cannot be preempted by another task (ie. you are ininterrupt context, or have preemption disabled) you can usesmp_processor_id().
__init/__exit/__initdata¶
Defined ininclude/linux/init.h
After boot, the kernel frees up a special section; functions marked with__init and data structures marked with__initdata are droppedafter boot is complete: similarly modules discard this memory afterinitialization.__exit is used to declare a function which is onlyrequired on exit: the function will be dropped if this file is notcompiled as a module. See the header file for use. Note that it makes nosense for a function marked with__init to be exported to moduleswithEXPORT_SYMBOL() orEXPORT_SYMBOL_GPL()- thiswill break.
__initcall()/module_init()¶
Defined ininclude/linux/init.h /include/linux/module.h
Many parts of the kernel are well served as a module(dynamically-loadable parts of the kernel). Using themodule_init() andmodule_exit() macros itis easy to write code without #ifdefs which can operate both as a moduleor built into the kernel.
Themodule_init() macro defines which function is to becalled at module insertion time (if the file is compiled as a module),or at boot time: if the file is not compiled as a module themodule_init() macro becomes equivalent to__initcall(), which through linker magic ensures thatthe function is called on boot.
The function can return a negative error number to cause module loadingto fail (unfortunately, this has no effect if the module is compiledinto the kernel). This function is called in user context withinterrupts enabled, so it can sleep.
module_exit()¶
Defined ininclude/linux/module.h
This macro defines the function to be called at module removal time (ornever, in the case of the file compiled into the kernel). It will onlybe called if the module usage count has reached zero. This function canalso sleep, but cannot fail: everything must be cleaned up by the timeit returns.
Note that this macro is optional: if it is not present, your module willnot be removable (except for ‘rmmod -f’).
try_module_get()/module_put()¶
Defined ininclude/linux/module.h
These manipulate the module usage count, to protect against removal (amodule also can’t be removed if another module uses one of its exportedsymbols: see below). Before calling into module code, you should calltry_module_get() on that module: if it fails, then themodule is being removed and you should act as if it wasn’t there.Otherwise, you can safely enter the module, and callmodule_put() when you’re finished.
Most registerable structures have an owner field, such as in thestructfile_operations structure.Set this field to the macroTHIS_MODULE.
Wait Queuesinclude/linux/wait.h¶
[SLEEPS]
A wait queue is used to wait for someone to wake you up when a certaincondition is true. They must be used carefully to ensure there is norace condition. You declare await_queue_head_t, and then processeswhich want to wait for that condition declare await_queue_entry_treferring to themselves, and place that in the queue.
Declaring¶
You declare await_queue_head_t using theDECLARE_WAIT_QUEUE_HEAD() macro, or using theinit_waitqueue_head() routine in your initializationcode.
Queuing¶
Placing yourself in the waitqueue is fairly complex, because you mustput yourself in the queue before checking the condition. There is amacro to do this:wait_event_interruptible()(include/linux/wait.h) The first argument is the wait queue head, andthe second is an expression which is evaluated; the macro returns 0 whenthis expression is true, or-ERESTARTSYS if a signal is received. Thewait_event() version ignores signals.
Waking Up Queued Tasks¶
Callwake_up() (include/linux/wait.h), which will wakeup every process in the queue. The exception is if one hasTASK_EXCLUSIVE set, in which case the remainder of the queue willnot be woken. There are other variants of this basic function availablein the same header.
Atomic Operations¶
Certain operations are guaranteed atomic on all platforms. The firstclass of operations work onatomic_t (include/asm/atomic.h);this contains a signed integer (at least 32 bits long), and you must usethese functions to manipulate or readatomic_t variables.atomic_read() andatomic_set() get and setthe counter,atomic_add(),atomic_sub(),atomic_inc(),atomic_dec(), andatomic_dec_and_test() (returns true if it wasdecremented to zero).
Yes. It returns true (i.e. != 0) if the atomic variable is zero.
Note that these functions are slower than normal arithmetic, and soshould not be used unnecessarily.
The second class of atomic operations is atomic bit operations on anunsignedlong, defined ininclude/linux/bitops.h. Theseoperations generally take a pointer to the bit pattern, and a bitnumber: 0 is the least significant bit.set_bit(),clear_bit() andchange_bit() set, clear,and flip the given bit.test_and_set_bit(),test_and_clear_bit() andtest_and_change_bit() do the same thing, except returntrue if the bit was previously set; these are particularly useful foratomically setting flags.
It is possible to call these operations with bit indices greater thanBITS_PER_LONG. The resulting behavior is strange on big-endianplatforms though so it is a good idea not to do this.
Symbols¶
Within the kernel proper, the normal linking rules apply (ie. unless asymbol is declared to be file scope with thestatic keyword, it canbe used anywhere in the kernel). However, for modules, a specialexported symbol table is kept which limits the entry points to thekernel proper. Modules can also export symbols.
EXPORT_SYMBOL()¶
Defined ininclude/linux/export.h
This is the classic method of exporting a symbol: dynamically loadedmodules will be able to use the symbol as normal.
EXPORT_SYMBOL_GPL()¶
Defined ininclude/linux/export.h
Similar toEXPORT_SYMBOL() except that the symbolsexported byEXPORT_SYMBOL_GPL() can only be seen bymodules with aMODULE_LICENSE() that specifies a GPLcompatible license. It implies that the function is considered aninternal implementation issue, and not really an interface. Somemaintainers and developers may however require EXPORT_SYMBOL_GPL()when adding any new APIs or functionality.
EXPORT_SYMBOL_NS()¶
Defined ininclude/linux/export.h
This is the variant ofEXPORT_SYMBOL() that allows specifying a symbolnamespace. Symbol Namespaces are documented inSymbol Namespaces
EXPORT_SYMBOL_NS_GPL()¶
Defined ininclude/linux/export.h
This is the variant ofEXPORT_SYMBOL_GPL() that allows specifying a symbolnamespace. Symbol Namespaces are documented inSymbol Namespaces
Routines and Conventions¶
Double-linked listsinclude/linux/list.h¶
There used to be three sets of linked-list routines in the kernelheaders, but this one is the winner. If you don’t have some particularpressing need for a single list, it’s a good choice.
In particular,list_for_each_entry() is useful.
Return Conventions¶
For code called in user context, it’s very common to defy C convention,and return 0 for success, and a negative error number (eg.-EFAULT) forfailure. This can be unintuitive at first, but it’s fairly widespread inthe kernel.
UsingERR_PTR() (include/linux/err.h) to encode anegative error number into a pointer, andIS_ERR() andPTR_ERR() to get it back out again: avoids a separatepointer parameter for the error number. Icky, but in a good way.
Breaking Compilation¶
Linus and the other developers sometimes change function or structurenames in development kernels; this is not done just to keep everyone ontheir toes: it reflects a fundamental change (eg. can no longer becalled with interrupts on, or does extra checks, or doesn’t do checkswhich were caught before). Usually this is accompanied by a fairlycomplete note to the linux-kernel mailing list; search the archive.Simply doing a global replace on the file usually makes thingsworse.
Initializing structure members¶
The preferred method of initializing structures is to use designatedinitialisers, as defined by ISO C99, eg:
static struct block_device_operations opt_fops = { .open = opt_open, .release = opt_release, .ioctl = opt_ioctl, .check_media_change = opt_media_change,};This makes it easy to grep for, and makes it clear which structurefields are set. You should do this because it looks cool.
GNU Extensions¶
GNU Extensions are explicitly allowed in the Linux kernel. Note thatsome of the more complex ones are not very well supported, due to lackof general use, but the following are considered standard (see the GCCinfo page section “C Extensions” for more details - Yes, really the infopage, the man page is only a short summary of the stuff in info).
- Inline functions
- Statement expressions (ie. the ({ and }) constructs).
- Declaring attributes of a function / variable / type(__attribute__)
- typeof
- Zero length arrays
- Macro varargs
- Arithmetic on void pointers
- Non-Constant initializers
- Assembler Instructions (not outside arch/ and include/asm/)
- Function names as strings (__func__).
- __builtin_constant_p()
Be wary when using long long in the kernel, the code gcc generates forit is horrible and worse: division and multiplication does not work oni386 because the GCC runtime functions for it are missing from thekernel environment.
C++¶
Using C++ in the kernel is usually a bad idea, because the kernel doesnot provide the necessary runtime environment and the include files arenot tested for it. It is still possible, but not recommended. If youreally want to do this, forget about exceptions at least.
#if¶
It is generally considered cleaner to use macros in header files (or atthe top of .c files) to abstract away functions rather than using `#if’pre-processor statements throughout the source code.
Putting Your Stuff in the Kernel¶
In order to get your stuff into shape for official inclusion, or even tomake a neat patch, there’s administrative work to be done:
Figure out whose pond you’ve been pissing in. Look at the top of thesource files, inside the
MAINTAINERSfile, and last of all in theCREDITSfile. You should coordinate with this person to make sureyou’re not duplicating effort, or trying something that’s alreadybeen rejected.Make sure you put your name and EMail address at the top of any filesyou create or mangle significantly. This is the first place peoplewill look when they find a bug, or whenthey want to make a change.
Usually you want a configuration option for your kernel hack. Edit
Kconfigin the appropriate directory. The Config language issimple to use by cut and paste, and there’s complete documentation inDocumentation/kbuild/kconfig-language.rst.In your description of the option, make sure you address both theexpert user and the user who knows nothing about your feature.Mention incompatibilities and issues here.Definitely end yourdescription with “if in doubt, say N” (or, occasionally, `Y’); thisis for people who have no idea what you are talking about.
Edit the
Makefile: the CONFIG variables are exported here so youcan usually just add a “obj-$(CONFIG_xxx) += xxx.o” line. The syntaxis documented inDocumentation/kbuild/makefiles.rst.Put yourself in
CREDITSif you’ve done something noteworthy,usually beyond a single file (your name should be at the top of thesource files anyway).MAINTAINERSmeans you want to be consultedwhen changes are made to a subsystem, and hear about bugs; it impliesa more-than-passing commitment to some part of the code.Finally, don’t forget to read
Documentation/process/submitting-patches.rstand possiblyDocumentation/process/submitting-drivers.rst.
Kernel Cantrips¶
Some favorites from browsing the source. Feel free to add to this list.
arch/x86/include/asm/delay.h:
#define ndelay(n) (__builtin_constant_p(n) ? \ ((n) > 20000 ? __bad_ndelay() : __const_udelay((n) * 5ul)) : \ __ndelay(n))
include/linux/fs.h:
/* * Kernel pointers have redundant information, so we can use a * scheme where we can return either an error code or a dentry * pointer with the same return value. * * This should be a per-architecture thing, to allow different * error and pointer decisions. */ #define ERR_PTR(err) ((void *)((long)(err))) #define PTR_ERR(ptr) ((long)(ptr)) #define IS_ERR(ptr) ((unsigned long)(ptr) > (unsigned long)(-1000))
arch/x86/include/asm/uaccess_32.h::
#define copy_to_user(to,from,n) \ (__builtin_constant_p(n) ? \ __constant_copy_to_user((to),(from),(n)) : \ __generic_copy_to_user((to),(from),(n)))
arch/sparc/kernel/head.S::
/* * Sun people can't spell worth damn. "compatability" indeed. * At least we *know* we can't spell, and use a spell-checker. *//* Uh, actually Linus it is I who cannot spell. Too much murky * Sparc assembly will do this to ya. */C_LABEL(cputypvar): .asciz "compatibility"/* Tested on SS-5, SS-10. Probably someone at Sun applied a spell-checker. */ .align 4C_LABEL(cputypvar_sun4m): .asciz "compatible"
arch/sparc/lib/checksum.S::
/* Sun, you just can't beat me, you just can't. Stop trying, * give up. I'm serious, I am going to kick the living shit * out of you, game over, lights out. */
Thanks¶
Thanks to Andi Kleen for the idea, answering my questions, fixing mymistakes, filling content, etc. Philipp Rumpf for more spelling andclarity fixes, and some excellent non-obvious points. Werner Almesbergerfor giving me a great summary ofdisable_irq(), and JesSorensen and Andrea Arcangeli added caveats. Michael Elizabeth Chastainfor checking and adding to the Configure section. Telsa Gwynne forteaching me DocBook.