This document outlines basic information about kernel livepatching.
1. Motivation¶
There are many situations where users are reluctant to reboot a system. It maybe because their system is performing complex scientific computations or underheavy load during peak usage. In addition to keeping systems up and running,users want to also have a stable and secure system. Livepatching gives usersboth by allowing for function calls to be redirected; thus, fixing criticalfunctions without a system reboot.
2. Kprobes, Ftrace, Livepatching¶
There are multiple mechanisms in the Linux kernel that are directly relatedto redirection of code execution; namely: kernel probes, function tracing,and livepatching:
The kernel probes are the most generic. The code can be redirected byputting a breakpoint instruction instead of any instruction.
The function tracer calls the code from a predefined location that isclose to the function entry point. This location is generated by thecompiler using the ‘-pg’ gcc option.
Livepatching typically needs to redirect the code at the very beginningof the function entry before the function parameters or the stackare in any way modified.
All three approaches need to modify the existing code at runtime. Thereforethey need to be aware of each other and not step over each other’s toes.Most of these problems are solved by using the dynamic ftrace framework asa base. A Kprobe is registered as a ftrace handler when the function entryis probed, see CONFIG_KPROBES_ON_FTRACE. Also an alternative function froma live patch is called with the help of a custom ftrace handler. But there aresome limitations, see below.
3. Consistency model¶
Functions are there for a reason. They take some input parameters, acquire orrelease locks, read, process, and even write some data in a defined way,have return values. In other words, each function has a defined semantic.
Many fixes do not change the semantic of the modified functions. Forexample, they add a NULL pointer or a boundary check, fix a race by addinga missing memory barrier, or add some locking around a critical section.Most of these changes are self contained and the function presents itselfthe same way to the rest of the system. In this case, the functions mightbe updated independently one by one.
But there are more complex fixes. For example, a patch might changeordering of locking in multiple functions at the same time. Or a patchmight exchange meaning of some temporary structures and updateall the relevant functions. In this case, the affected unit(thread, whole kernel) need to start using all new versions ofthe functions at the same time. Also the switch must happen onlywhen it is safe to do so, e.g. when the affected locks are releasedor no data are stored in the modified structures at the moment.
The theory about how to apply functions a safe way is rather complex.The aim is to define a so-called consistency model. It attempts to defineconditions when the new implementation could be used so that the systemstays consistent.
Livepatch has a consistency model which is a hybrid of kGraft andkpatch: it uses kGraft’s per-task consistency and syscall barrierswitching combined with kpatch’s stack trace switching. There are alsoa number of fallback options which make it quite flexible.
Patches are applied on a per-task basis, when the task is deemed safe toswitch over. When a patch is enabled, livepatch enters into atransition state where tasks are converging to the patched state.Usually this transition state can complete in a few seconds. The samesequence occurs when a patch is disabled, except the tasks converge fromthe patched state to the unpatched state.
An interrupt handler inherits the patched state of the task itinterrupts. The same is true for forked tasks: the child inherits thepatched state of the parent.
Livepatch uses several complementary approaches to determine when it’ssafe to patch tasks:
The first and most effective approach is stack checking of sleepingtasks. If no affected functions are on the stack of a given task,the task is patched. In most cases this will patch most or all ofthe tasks on the first try. Otherwise it’ll keep tryingperiodically. This option is only available if the architecture hasreliable stacks (HAVE_RELIABLE_STACKTRACE).
The second approach, if needed, is kernel exit switching. Atask is switched when it returns to user space from a system call, auser space IRQ, or a signal. It’s useful in the following cases:
Patching I/O-bound user tasks which are sleeping on an affectedfunction. In this case you have to send SIGSTOP and SIGCONT toforce it to exit the kernel and be patched.
Patching CPU-bound user tasks. If the task is highly CPU-boundthen it will get patched the next time it gets interrupted by anIRQ.
For idle “swapper” tasks, since they don’t ever exit the kernel, theyinstead have a klp_update_patch_state() call in the idle loop whichallows them to be patched before the CPU enters the idle state.
(Note there’s not yet such an approach for kthreads.)
Architectures which don’t have HAVE_RELIABLE_STACKTRACE solely rely onthe second approach. It’s highly likely that some tasks may still berunning with an old version of the function, until that functionreturns. In this case you would have to signal the tasks. Thisespecially applies to kthreads. They may not be woken up and would needto be forced. See below for more information.
Unless we can come up with another way to patch kthreads, architectureswithout HAVE_RELIABLE_STACKTRACE are not considered fully supported bythe kernel livepatching.
The /sys/kernel/livepatch/<patch>/transition file shows whether a patchis in transition. Only a single patch can be in transition at a giventime. A patch can remain in transition indefinitely, if any of the tasksare stuck in the initial patch state.
A transition can be reversed and effectively canceled by writing theopposite value to the /sys/kernel/livepatch/<patch>/enabled file whilethe transition is in progress. Then all the tasks will attempt toconverge back to the original patch state.
There’s also a /proc/<pid>/patch_state file which can be used todetermine which tasks are blocking completion of a patching operation.If a patch is in transition, this file shows 0 to indicate the task isunpatched and 1 to indicate it’s patched. Otherwise, if no patch is intransition, it shows -1. Any tasks which are blocking the transitioncan be signaled with SIGSTOP and SIGCONT to force them to change theirpatched state. This may be harmful to the system though. Sending a fake signalto all remaining blocking tasks is a better alternative. No proper signal isactually delivered (there is no data in signal pending structures). Tasks areinterrupted or woken up, and forced to change their patched state. The fakesignal is automatically sent every 15 seconds.
Administrator can also affect a transition through/sys/kernel/livepatch/<patch>/force attribute. Writing 1 there clearsTIF_PATCH_PENDING flag of all tasks and thus forces the tasks to the patchedstate. Important note! The force attribute is intended for cases when thetransition gets stuck for a long time because of a blocking task. Administratoris expected to collect all necessary data (namely stack traces of such blockingtasks) and request a clearance from a patch distributor to force the transition.Unauthorized usage may cause harm to the system. It depends on the nature of thepatch, which functions are (un)patched, and which functions the blocking tasksare sleeping in (/proc/<pid>/stack may help here). Removal (rmmod) of patchmodules is permanently disabled when the force feature is used. It cannot beguaranteed there is no task sleeping in such module. It implies unboundedreference count if a patch module is disabled and enabled in a loop.
Moreover, the usage of force may also affect future applications of livepatches and cause even more harm to the system. Administrator should firstconsider to simply cancel a transition (see above). If force is used, rebootshould be planned and no more live patches applied.
3.1 Adding consistency model support to new architectures¶
For adding consistency model support to new architectures, there are afew options:
Add CONFIG_HAVE_RELIABLE_STACKTRACE. This means porting objtool, andfor non-DWARF unwinders, also making sure there’s a way for the stacktracing code to detect interrupts on the stack.
Alternatively, ensure that every kthread has a call toklp_update_patch_state() in a safe location. Kthreads are typicallyin an infinite loop which does some action repeatedly. The safelocation to switch the kthread’s patch state would be at a designatedpoint in the loop where there are no locks taken and all datastructures are in a well-defined state.
The location is clear when using workqueues or the kthread workerAPI. These kthreads process independent actions in a generic loop.
It’s much more complicated with kthreads which have a custom loop.There the safe location must be carefully selected on a case-by-casebasis.
In that case, arches without HAVE_RELIABLE_STACKTRACE would still beable to use the non-stack-checking parts of the consistency model:
patching user tasks when they cross the kernel/user spaceboundary; and
patching kthreads and idle tasks at their designated patch points.
This option isn’t as good as option 1 because it requires signalinguser tasks and waking kthreads to patch them. But it could still bea good backup option for those architectures which don’t havereliable stack traces yet.
4. Livepatch module¶
Livepatches are distributed using kernel modules, seesamples/livepatch/livepatch-sample.c.
The module includes a new implementation of functions that we wantto replace. In addition, it defines some structures describing therelation between the original and the new implementation. Then thereis code that makes the kernel start using the new code when the livepatchmodule is loaded. Also there is code that cleans up before thelivepatch module is removed. All this is explained in more details inthe next sections.
4.1. New functions¶
New versions of functions are typically just copied from the originalsources. A good practice is to add a prefix to the names so that theycan be distinguished from the original ones, e.g. in a backtrace. Alsothey can be declared as static because they are not called directlyand do not need the global visibility.
The patch contains only functions that are really modified. But theymight want to access functions or data from the original source filethat may only be locally accessible. This can be solved by a specialrelocation section in the generated livepatch module, seeLivepatch module ELF format for more details.
4.2. Metadata¶
The patch is described by several structures that split the informationinto three levels:
struct klp_func is defined for each patched function. It describesthe relation between the original and the new implementation of aparticular function.
The structure includes the name, as a string, of the original function.The function address is found via kallsyms at runtime.
Then it includes the address of the new function. It is defineddirectly by assigning the function pointer. Note that the newfunction is typically defined in the same source file.
As an optional parameter, the symbol position in the kallsyms database canbe used to disambiguate functions of the same name. This is not theabsolute position in the database, but rather the order it has been foundonly for a particular object ( vmlinux or a kernel module ). Note thatkallsyms allows for searching symbols according to the object name.
struct klp_object defines an array of patched functions (structklp_func) in the same object. Where the object is either vmlinux(NULL) or a module name.
The structure helps to group and handle functions for each objecttogether. Note that patched modules might be loaded later thanthe patch itself and the relevant functions might be patchedonly when they are available.
struct klp_patch defines an array of patched objects (structklp_object).
This structure handles all patched functions consistently and eventually,synchronously. The whole patch is applied only when all patchedsymbols are found. The only exception are symbols from objects(kernel modules) that have not been loaded yet.
For more details on how the patch is applied on a per-task basis,see the “Consistency model” section.
5. Livepatch life-cycle¶
Livepatching can be described by five basic operations:loading, enabling, replacing, disabling, removing.
Where the replacing and the disabling operations are mutuallyexclusive. They have the same result for the given patch butnot for the system.
5.1. Loading¶
The only reasonable way is to enable the patch when the livepatch kernelmodule is being loaded. For this, klp_enable_patch() has to be calledin the module_init() callback. There are two main reasons:
First, only the module has an easy access to the related struct klp_patch.
Second, the error code might be used to refuse loading the module whenthe patch cannot get enabled.
5.2. Enabling¶
The livepatch gets enabled by calling klp_enable_patch() fromthe module_init() callback. The system will start using the newimplementation of the patched functions at this stage.
First, the addresses of the patched functions are found according to theirnames. The special relocations, mentioned in the section “New functions”,are applied. The relevant entries are created under/sys/kernel/livepatch/<name>. The patch is rejected when any aboveoperation fails.
Second, livepatch enters into a transition state where tasks are convergingto the patched state. If an original function is patched for the firsttime, a function specific struct klp_ops is created and an universalftrace handler is registered[1]. This stage is indicated by a value of ‘1’in /sys/kernel/livepatch/<name>/transition. For more information aboutthis process, see the “Consistency model” section.
Finally, once all tasks have been patched, the ‘transition’ value changesto ‘0’.
5.3. Replacing¶
All enabled patches might get replaced by a cumulative patch thathas the .replace flag set.
Once the new patch is enabled and the ‘transition’ finishes thenall the functions (struct klp_func) associated with the replacedpatches are removed from the corresponding struct klp_ops. Alsothe ftrace handler is unregistered and the struct klp_ops isfreed when the related function is not modified by the new patchand func_stack list becomes empty.
See for more details.
5.4. Disabling¶
Enabled patches might get disabled by writing ‘0’ to/sys/kernel/livepatch/<name>/enabled.
First, livepatch enters into a transition state where tasks are convergingto the unpatched state. The system starts using either the code fromthe previously enabled patch or even the original one. This stage isindicated by a value of ‘1’ in /sys/kernel/livepatch/<name>/transition.For more information about this process, see the “Consistency model”section.
Second, once all tasks have been unpatched, the ‘transition’ value changesto ‘0’. All the functions (struct klp_func) associated with the to-be-disabledpatch are removed from the corresponding struct klp_ops. The ftrace handleris unregistered and the struct klp_ops is freed when the func_stack listbecomes empty.
Third, the sysfs interface is destroyed.
5.5. Removing¶
Module removal is only safe when there are no users of functions providedby the module. This is the reason why the force feature permanentlydisables the removal. Only when the system is successfully transitionedto a new patch state (patched/unpatched) without being forced it isguaranteed that no task sleeps or runs in the old code.
6. Sysfs¶
Information about the registered patches can be found under/sys/kernel/livepatch. The patches could be enabled and disabledby writing there.
/sys/kernel/livepatch/<patch>/force attributes allow administrator to affect apatching operation.
See Documentation/ABI/testing/sysfs-kernel-livepatch for more details.
7. Limitations¶
The current Livepatch implementation has several limitations:
Only functions that can be traced could be patched.
Livepatch is based on the dynamic ftrace. In particular, functionsimplementing ftrace or the livepatch ftrace handler could not bepatched. Otherwise, the code would end up in an infinite loop. Apotential mistake is prevented by marking the problematic functionsby “notrace”.
Livepatch works reliably only when the dynamic ftrace is located atthe very beginning of the function.
The function need to be redirected before the stack or the functionparameters are modified in any way. For example, livepatch requiresusing -fentry gcc compiler option on x86_64.
One exception is the PPC port. It uses relative addressing and TOC.Each function has to handle TOC and save LR before it could callthe ftrace handler. This operation has to be reverted on return.Fortunately, the generic ftrace code has the same problem and allthis is handled on the ftrace level.
Kretprobes using the ftrace framework conflict with the patchedfunctions.
Both kretprobes and livepatches use a ftrace handler that modifiesthe return address. The first user wins. Either the probe or the patchis rejected when the handler is already in use by the other.
Kprobes in the original function are ignored when the code isredirected to the new implementation.
There is a work in progress to add warnings about this situation.