Blame doc/patch-author-guide.md

Packit c71e3f
kpatch Patch Author Guide
Packit c71e3f
=========================
Packit c71e3f
Packit c71e3f
Because kpatch-build is relatively easy to use, it can be easy to assume that a
Packit c71e3f
successful patch module build means that the patch is safe to apply.  But in
Packit c71e3f
fact that's a very dangerous assumption.
Packit c71e3f
Packit c71e3f
There are many pitfalls that can be encountered when creating a live patch.
Packit c71e3f
This document attempts to guide the patch creation process.  It's a work in
Packit c71e3f
progress.  If you find it useful, please contribute!
Packit c71e3f
Packit c71e3f
Patch Analysis
Packit c71e3f
--------------
Packit c71e3f
Packit c71e3f
kpatch provides _some_ guarantees, but it does not guarantee that all patches
Packit c71e3f
are safe to apply.  Every patch must also be analyzed in-depth by a human.
Packit c71e3f
Packit c71e3f
The most important point here cannot be stressed enough.  Here comes the bold:
Packit c71e3f
Packit c71e3f
**Do not blindly apply patches.  There is no substitute for human analysis and
Packit c71e3f
reasoning on a per-patch basis.  All patches must be thoroughly analyzed by a
Packit c71e3f
human kernel expert who completely understands the patch and the affected code
Packit c71e3f
and how they relate to the live patching environment.**
Packit c71e3f
Packit c71e3f
kpatch vs livepatch vs kGraft
Packit c71e3f
-----------------------------
Packit c71e3f
Packit c71e3f
This document assumes that the kpatch core module is being used.  Other live
Packit c71e3f
patching systems (e.g., livepatch and kGraft) have different consistency
Packit c71e3f
models.  Each comes with its own guarantees, and there are some subtle
Packit c71e3f
differences.  The guidance in this document applies **only** to kpatch.
Packit c71e3f
Packit c71e3f
Patch upgrades
Packit c71e3f
--------------
Packit c71e3f
Packit c71e3f
Due to potential unexpected interactions between patches, it's highly
Packit c71e3f
recommended that when patching a system which has already been patched, the
Packit c71e3f
second patch should be a cumulative upgrade which is a superset of the first
Packit c71e3f
patch.
Packit c71e3f
Packit c71e3f
Data structure changes
Packit c71e3f
----------------------
Packit c71e3f
Packit c71e3f
kpatch patches functions, not data.  If the original patch involves a change to
Packit c71e3f
a data structure, the patch will require some rework, as changes to data
Packit c71e3f
structures are not allowed by default.
Packit c71e3f
Packit c71e3f
Usually you have to get creative.  There are several possible ways to handle
Packit c71e3f
this:
Packit c71e3f
Packit c71e3f
### Change the code which uses the data structure
Packit c71e3f
Packit c71e3f
Sometimes, instead of changing the data structure itself, you can change the
Packit c71e3f
code which uses it.
Packit c71e3f
Packit c71e3f
For example, consider this
Packit c71e3f
[patch](http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=54a20552e1eae07aa240fa370a0293e006b5faed).
Packit c71e3f
which has the following hunk:
Packit c71e3f
Packit c71e3f
```
Packit c71e3f
@@ -3270,6 +3277,7 @@ static int (*const svm_exit_handlers[])(struct vcpu_svm *svm) = {
Packit c71e3f
 	[SVM_EXIT_EXCP_BASE + PF_VECTOR]	= pf_interception,
Packit c71e3f
 	[SVM_EXIT_EXCP_BASE + NM_VECTOR]	= nm_interception,
Packit c71e3f
 	[SVM_EXIT_EXCP_BASE + MC_VECTOR]	= mc_interception,
Packit c71e3f
+	[SVM_EXIT_EXCP_BASE + AC_VECTOR]	= ac_interception,
Packit c71e3f
 	[SVM_EXIT_INTR]				= intr_interception,
Packit c71e3f
 	[SVM_EXIT_NMI]				= nmi_interception,
Packit c71e3f
 	[SVM_EXIT_SMI]				= nop_on_interception,
Packit c71e3f
```
Packit c71e3f
Packit c71e3f
`svm_exit_handlers[]` is an array of function pointers.  The patch adds a
Packit c71e3f
`ac_interception` function pointer to the array at index `[SVM_EXIT_EXCP_BASE +
Packit c71e3f
AC_VECTOR]`.  That change is incompatible with kpatch.
Packit c71e3f
Packit c71e3f
Looking at the source file, we can see that this function pointer is only
Packit c71e3f
accessed by a single function, `handle_exit()`:
Packit c71e3f
Packit c71e3f
```
Packit c71e3f
        if (exit_code >= ARRAY_SIZE(svm_exit_handlers)
Packit c71e3f
            || !svm_exit_handlers[exit_code]) {
Packit c71e3f
                WARN_ONCE(1, "svm: unexpected exit reason 0x%x\n", exit_code);
Packit c71e3f
                kvm_queue_exception(vcpu, UD_VECTOR);
Packit c71e3f
                return 1;
Packit c71e3f
        }
Packit c71e3f
Packit c71e3f
        return svm_exit_handlers[exit_code](svm);
Packit c71e3f
```
Packit c71e3f
Packit c71e3f
So an easy solution here is to just change the code to manually check for the
Packit c71e3f
new case before looking in the data structure:
Packit c71e3f
Packit c71e3f
```
Packit c71e3f
@@ -3580,6 +3580,9 @@ static int handle_exit(struct kvm_vcpu *vcpu)
Packit c71e3f
                return 1;
Packit c71e3f
        }
Packit c71e3f
Packit c71e3f
+       if (exit_code == SVM_EXIT_EXCP_BASE + AC_VECTOR)
Packit c71e3f
+               return ac_interception(svm);
Packit c71e3f
+
Packit c71e3f
        return svm_exit_handlers[exit_code](svm);
Packit c71e3f
 }
Packit c71e3f
```
Packit c71e3f
Packit c71e3f
Not only is this an easy solution, it's also safer than touching data since
Packit c71e3f
kpatch creates a barrier between the calling of old functions and new
Packit c71e3f
functions.
Packit c71e3f
Packit c71e3f
### Use a kpatch callback macro
Packit c71e3f
Packit c71e3f
Kpatch supports livepatch style callbacks, as described by the kernel's
Packit c71e3f
[Documentation/livepatch/callbacks.txt](https://github.com/torvalds/linux/blob/master/Documentation/livepatch/callbacks.txt).
Packit c71e3f
Packit c71e3f
`kpatch-macros.h` defines the following macros that can be used to
Packit c71e3f
register such callbacks:
Packit c71e3f
Packit c71e3f
* `KPATCH_PRE_PATCH_CALLBACK` - executed before patching
Packit c71e3f
* `KPATCH_POST_PATCH_CALLBACK` - executed after patching
Packit c71e3f
* `KPATCH_PRE_UNPATCH_CALLBACK` - executed before unpatching, complements the
Packit c71e3f
                                  post-patch callback.
Packit c71e3f
* `KPATCH_POST_UNPATCH_CALLBACK` - executed after unpatching, complements the
Packit c71e3f
                                   pre-patch callback.
Packit c71e3f
Packit c71e3f
A pre-patch callback routine has the following signature:
Packit c71e3f
Packit c71e3f
```
Packit c71e3f
static int callback(patch_object *obj) { }
Packit c71e3f
```
Packit c71e3f
Packit c71e3f
and any non-zero return status indicates failure to the kpatch core.  For more
Packit c71e3f
information on pre-patch callback failure, see the **Pre-patch return status**
Packit c71e3f
section below.
Packit c71e3f
Packit c71e3f
Post-patch, pre-unpatch, and post-unpatch callback routines all share the
Packit c71e3f
following signature:
Packit c71e3f
Packit c71e3f
```
Packit c71e3f
static void callback(patch_object *obj) { }
Packit c71e3f
```
Packit c71e3f
Packit c71e3f
Generally pre-patch callbacks are paired with post-unpatch callbacks, meaning
Packit c71e3f
that anything the former allocates or sets up should be torn down by the former
Packit c71e3f
callback.  Likewise for post-patch and pre-unpatch callbacks.
Packit c71e3f
Packit c71e3f
#### Pre-patch return status
Packit c71e3f
Packit c71e3f
If kpatch is currently patching already-loaded objects (vmlinux always by
Packit c71e3f
definition as well as any currently loaded kernel modules), a non-zero pre-patch
Packit c71e3f
callback status results in the kpatch core reverting the current
Packit c71e3f
patch-in-progress.  The kpatch-module is rejected, completely reverted, and
Packit c71e3f
unloaded.
Packit c71e3f
Packit c71e3f
If kpatch is patching a newly loaded kernel module, then a failing pre-patch
Packit c71e3f
callback will only result in a WARN message.  This is non-intuitive and a
Packit c71e3f
deviation from livepatch callback behavior, but the result of a limitation of
Packit c71e3f
kpatch and linux module notifiers.
Packit c71e3f
Packit c71e3f
In both cases, if a pre-patch callback fails, none of its other callbacks will
Packit c71e3f
be executed.
Packit c71e3f
Packit c71e3f
#### Callback context
Packit c71e3f
Packit c71e3f
* For patches to vmlinux or already loaded kernel modules, callback functions
Packit c71e3f
will be run by `stop_machine` as part of applying or removing a patch.
Packit c71e3f
(Therefore the callbacks must not block or sleep.)
Packit c71e3f
Packit c71e3f
* For patches to kernel modules which haven't been loaded yet, a
Packit c71e3f
module-notifier will execute callbacks when the associated module is loaded
Packit c71e3f
into the `MODULE_STATE_COMING` state.  The pre and post-patch callbacks
Packit c71e3f
are called before any module_init code.
Packit c71e3f
Packit c71e3f
Example: a kpatch fix for CVE-2016-5389 could utilize the
Packit c71e3f
`KPATCH_PRE_PATCH_CALLBACK` and `KPATCH_POST_UNPATCH_CALLBACK` macros to modify
Packit c71e3f
variable `sysctl_tcp_challenge_ack_limit` in-place:
Packit c71e3f
Packit c71e3f
```
Packit c71e3f
+#include "kpatch-macros.h"
Packit c71e3f
+
Packit c71e3f
+static bool kpatch_write = false;
Packit c71e3f
+static int kpatch_pre_patch_tcp_send_challenge_ack(patch_object *obj)
Packit c71e3f
+{
Packit c71e3f
+	if (sysctl_tcp_challenge_ack_limit == 100) {
Packit c71e3f
+		sysctl_tcp_challenge_ack_limit = 1000;
Packit c71e3f
+		kpatch_write = true;
Packit c71e3f
+	}
Packit c71e3f
+	return 0;
Packit c71e3f
+}
Packit c71e3f
static void kpatch_post_unpatch_tcp_send_challenge_ack(patch_object *obj)
Packit c71e3f
+{
Packit c71e3f
+	if (kpatch_write && sysctl_tcp_challenge_ack_limit == 1000)
Packit c71e3f
+		sysctl_tcp_challenge_ack_limit = 100;
Packit c71e3f
+}
Packit c71e3f
+KPATCH_PRE_PATCH_CALLBACK(kpatch_pre_patch_tcp_send_challenge_ack);
Packit c71e3f
+KPATCH_POST_UNPATCH_CALLBACK(kpatch_post_unpatch_tcp_send_challenge_ack);
Packit c71e3f
```
Packit c71e3f
Packit c71e3f
Don't forget to protect access to the data as needed. Please note that
Packit c71e3f
spinlocks and mutexes / sleeping locks can't be used from stop_machine
Packit c71e3f
context. Also note the pre-patch callback return code will be ignored by the
Packit c71e3f
kernel's module notifier, so it does not affect the target module or livepatch
Packit c71e3f
module status. This means:
Packit c71e3f
Packit c71e3f
* Pre-patch callbacks to loaded objects (vmlinux, loaded kernel modules) are
Packit c71e3f
  run from stop_machine(), so they may only inspect lock state (i.e.
Packit c71e3f
  spin_is_locked(), mutex_is_locked()) and optionally return -EBUSY to prevent
Packit c71e3f
  patching.
Packit c71e3f
Packit c71e3f
* Post-patch, pre-unpatch, and post-unpatch callbacks to loaded objects are
Packit c71e3f
  also run from stop_machine(), so the same locking context applies.  No
Packit c71e3f
  return status is supported.
Packit c71e3f
Packit c71e3f
* Deferred pre-patch callbacks to newly loading objects do not run from
Packit c71e3f
  stop_machine(), so they may spin or schedule, i.e. spin_lock(),
Packit c71e3f
  mutex_lock()).  Return status is ignored.
Packit c71e3f
Packit c71e3f
* Post-patch, pre-unpatch, and post-unpatch callbacks to unloading objects are
Packit c71e3f
  also *not* run from stop_machine(), so they may spin or sleep.  No return
Packit c71e3f
  status is supported.
Packit c71e3f
Packit c71e3f
Unfortunately there is no simple, all-case-inclusive kpatch callback
Packit c71e3f
implementation that handles data structures and mutual exclusion.
Packit c71e3f
Packit c71e3f
A few workarounds:
Packit c71e3f
Packit c71e3f
1. If a given lock/mutex is held and released by the same set of functions
Packit c71e3f
(that is, functions that take a lock/mutex always release it before
Packit c71e3f
returning), a trivial change to those functions can re-purpose kpatch's
Packit c71e3f
activeness safety check to avoid patching when the lock/mutex may be held.
Packit c71e3f
This assumes that all lock/mutex holders can be patched.
Packit c71e3f
Packit c71e3f
2. If it can be assured that all patch targets will be loaded before the
Packit c71e3f
kpatch patch module, pre-patch callbacks may return -EBUSY if the lock/mutex
Packit c71e3f
is held to block the patching.
Packit c71e3f
Packit c71e3f
3. Finally, if a kpatch is disabled or removed and while all patch targets are
Packit c71e3f
still loaded, then all unpatch callbacks will run from stop_machine() -- the
Packit c71e3f
unpatching cannot be stopped at this point and the callbacks cannot spin or
Packit c71e3f
sleep.
Packit c71e3f
Packit c71e3f
    With that in mind, it is probably easiest to omit unpatching callbacks
Packit c71e3f
at this point.
Packit c71e3f
Packit c71e3f
Also be careful when upgrading.  If patch A has a pre/post-patch callback which
Packit c71e3f
writes to X, and then you load patch B which is a superset of A, in some cases
Packit c71e3f
you may want to prevent patch B from writing to X, if A is already loaded.
Packit c71e3f
Packit c71e3f
Packit c71e3f
### Use a shadow variable
Packit c71e3f
Packit c71e3f
If you need to add a field to an existing data structure, or even many existing
Packit c71e3f
data structures, you can use the `kpatch_shadow_*()` functions:
Packit c71e3f
Packit c71e3f
* `kpatch_shadow_alloc` - allocates a new shadow variable associated with a
Packit c71e3f
  given object
Packit c71e3f
* `kpatch_shadow_get` - find and return a pointer to a shadow variable
Packit c71e3f
* `kpatch_shadow_free` - find and free a shadow variable
Packit c71e3f
Packit c71e3f
Example: The `shadow-newpid.patch` integration test demonstrates the usage of
Packit c71e3f
these functions.
Packit c71e3f
Packit c71e3f
A shadow PID variable is allocated in `do_fork()`: it is associated with the
Packit c71e3f
current `struct task_struct *p` value, given a string lookup key of "newpid",
Packit c71e3f
sized accordingly, and allocated as per `GFP_KERNEL` flag rules.
Packit c71e3f
Packit c71e3f
`kpatch_shadow_alloc` returns a pointer to the shadow variable, so we can
Packit c71e3f
dereference and make assignments as usual.  In this patch chunk, the shadow
Packit c71e3f
`newpid` is allocated then assigned to a rolling `ctr` counter value:
Packit c71e3f
```
Packit c71e3f
+		int *newpid;
Packit c71e3f
+		static int ctr = 0;
Packit c71e3f
+
Packit c71e3f
+		newpid = kpatch_shadow_alloc(p, "newpid", sizeof(*newpid),
Packit c71e3f
+					     GFP_KERNEL);
Packit c71e3f
+		if (newpid)
Packit c71e3f
+			*newpid = ctr++;
Packit c71e3f
```
Packit c71e3f
Packit c71e3f
A shadow variable may also be accessed via `kpatch_shadow_get`.  Here the
Packit c71e3f
patch modifies `task_context_switch_counts()` to fetch the shadow variable
Packit c71e3f
associated with the current `struct task_struct *p` object and a "newpid" tag.
Packit c71e3f
As in the previous patch chunk, the shadow variable pointer may be accessed
Packit c71e3f
as an ordinary pointer type:
Packit c71e3f
```
Packit c71e3f
+	int *newpid;
Packit c71e3f
+
Packit c71e3f
 	seq_put_decimal_ull(m, "voluntary_ctxt_switches:\t", p->nvcsw);
Packit c71e3f
 	seq_put_decimal_ull(m, "\nnonvoluntary_ctxt_switches:\t", p->nivcsw);
Packit c71e3f
 	seq_putc(m, '\n');
Packit c71e3f
+
Packit c71e3f
+	newpid = kpatch_shadow_get(p, "newpid");
Packit c71e3f
+	if (newpid)
Packit c71e3f
+		seq_printf(m, "newpid:\t%d\n", *newpid);
Packit c71e3f
```
Packit c71e3f
Packit c71e3f
A shadow variable is freed by calling `kpatch_shadow_free` and providing
Packit c71e3f
the object / string key combination.  Once freed, the shadow variable is not
Packit c71e3f
safe to access:
Packit c71e3f
```
Packit c71e3f
 	exit_task_work(tsk);
Packit c71e3f
 	exit_thread(tsk);
Packit c71e3f
 
Packit c71e3f
+	kpatch_shadow_free(tsk, "newpid");
Packit c71e3f
+
Packit c71e3f
 	/*
Packit c71e3f
 	 * Flush inherited counters to the parent - before the parent
Packit c71e3f
 	 * gets woken up by child-exit notifications.
Packit c71e3f
```
Packit c71e3f
Notes:
Packit c71e3f
* `kpatch_shadow_alloc` initializes only shadow variable metadata. It
Packit c71e3f
  allocates variable storage via `kmalloc` with the `gfp_t` flags it is
Packit c71e3f
  given, but otherwise leaves the area untouched. Initialization of a shadow
Packit c71e3f
  variable is the responsibility of the caller.
Packit c71e3f
* As soon as `kpatch_shadow_alloc` creates a shadow variable, its presence
Packit c71e3f
  will be reported by `kpatch_shadow_get`. Care should be taken to avoid any
Packit c71e3f
  potential race conditions between a kernel thread that allocates a shadow
Packit c71e3f
  variable and concurrent threads that may attempt to use it.
Packit c71e3f
Packit c71e3f
Data semantic changes
Packit c71e3f
---------------------
Packit c71e3f
Packit c71e3f
Part of the stable-tree [backport](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git/commit/fs/aio.c?h=linux-3.10.y&id=6745cb91b5ec93a1b34221279863926fba43d0d7)
Packit c71e3f
to fix CVE-2014-0206 changed the reference count semantic of `struct
Packit c71e3f
kioctx.reqs_active`. Associating a shadow variable to new instances of this
Packit c71e3f
structure can be used by patched code to handle both new (post-patch) and
Packit c71e3f
existing (pre-patch) instances.
Packit c71e3f
Packit c71e3f
(This example is trimmed to highlight this use-case. Boilerplate code is also
Packit c71e3f
required to allocate/free a shadow variable called "reqs_active_v2" whenever a
Packit c71e3f
new `struct kioctx` is created/released. No values are ever assigned to the
Packit c71e3f
shadow variable.)
Packit c71e3f
Packit c71e3f
Shadow variable existence can be verified before applying the new data
Packit c71e3f
semantic of the associated object:
Packit c71e3f
```
Packit c71e3f
@@ -678,6 +688,9 @@ void aio_complete(struct kiocb *iocb, lo
Packit c71e3f
 put_rq:
Packit c71e3f
 	/* everything turned out well, dispose of the aiocb. */
Packit c71e3f
 	aio_put_req(iocb);
Packit c71e3f
+	reqs_active_v2 = kpatch_shadow_get(ctx, "reqs_active_v2");
Packit c71e3f
+	if (reqs_active_v2)
Packit c71e3f
+		atomic_dec(&ctx->reqs_active);
Packit c71e3f
 
Packit c71e3f
 	/*
Packit c71e3f
 	 * We have to order our ring_info tail store above and test
Packit c71e3f
```
Packit c71e3f
Packit c71e3f
Likewise, shadow variable non-existence can be tested to continue applying the
Packit c71e3f
old data semantic:
Packit c71e3f
```
Packit c71e3f
@@ -705,6 +718,7 @@ static long aio_read_events_ring(struct
Packit c71e3f
 	unsigned head, pos;
Packit c71e3f
 	long ret = 0;
Packit c71e3f
 	int copy_ret;
Packit c71e3f
+	int *reqs_active_v2;
Packit c71e3f
 
Packit c71e3f
 	mutex_lock(&ctx->ring_lock);
Packit c71e3f
 
Packit c71e3f
@@ -756,7 +770,9 @@ static long aio_read_events_ring(struct
Packit c71e3f
 
Packit c71e3f
 	pr_debug("%li  h%u t%u\n", ret, head, ctx->tail);
Packit c71e3f
 
Packit c71e3f
-	atomic_sub(ret, &ctx->reqs_active);
Packit c71e3f
+	reqs_active_v2 = kpatch_shadow_get(ctx, "reqs_active_v2");
Packit c71e3f
+	if (!reqs_active_v2)
Packit c71e3f
+		atomic_sub(ret, &ctx->reqs_active);
Packit c71e3f
 out:
Packit c71e3f
 	mutex_unlock(&ctx->ring_lock);
Packit c71e3f
```
Packit c71e3f
 
Packit c71e3f
The previous example can be extended to use shadow variable storage to handle
Packit c71e3f
locking semantic changes.  Consider the [upstream fix](https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=1d147bfa64293b2723c4fec50922168658e613ba)
Packit c71e3f
for CVE-2014-2706, which added a `ps_lock` to `struct sta_info` to protect
Packit c71e3f
critical sections throughout `net/mac80211/sta_info.c`.
Packit c71e3f
Packit c71e3f
When allocating a new `struct sta_info`, allocate a corresponding "ps_lock"
Packit c71e3f
shadow variable large enough to hold a `spinlock_t` instance, then initialize
Packit c71e3f
the spinlock:
Packit c71e3f
```
Packit c71e3f
@@ -333,12 +336,16 @@ struct sta_info *sta_info_alloc(struct ieee80211_sub_if_data *sdata,
Packit c71e3f
 	struct sta_info *sta;
Packit c71e3f
 	struct timespec uptime;
Packit c71e3f
 	int i;
Packit c71e3f
+	spinlock_t *ps_lock;
Packit c71e3f
 
Packit c71e3f
 	sta = kzalloc(sizeof(*sta) + local->hw.sta_data_size, gfp);
Packit c71e3f
 	if (!sta)
Packit c71e3f
 		return NULL;
Packit c71e3f
 
Packit c71e3f
 	spin_lock_init(&sta->lock);
Packit c71e3f
+	ps_lock = kpatch_shadow_alloc(sta, "ps_lock", sizeof(*ps_lock), gfp);
Packit c71e3f
+	if (ps_lock)
Packit c71e3f
+		spin_lock_init(ps_lock);
Packit c71e3f
 	INIT_WORK(&sta->drv_unblock_wk, sta_unblock);
Packit c71e3f
 	INIT_WORK(&sta->ampdu_mlme.work, ieee80211_ba_session_work);
Packit c71e3f
 	mutex_init(&sta->ampdu_mlme.mtx);
Packit c71e3f
```
Packit c71e3f
Packit c71e3f
Patched code can reference the "ps_lock" shadow variable associated with a
Packit c71e3f
given `struct sta_info` to determine and apply the correct locking semantic
Packit c71e3f
for that instance:
Packit c71e3f
```
Packit c71e3f
@@ -471,6 +475,23 @@ ieee80211_tx_h_unicast_ps_buf(struct ieee80211_tx_data *tx)
Packit c71e3f
 		       sta->sta.addr, sta->sta.aid, ac);
Packit c71e3f
 		if (tx->local->total_ps_buffered >= TOTAL_MAX_TX_BUFFER)
Packit c71e3f
 			purge_old_ps_buffers(tx->local);
Packit c71e3f
+
Packit c71e3f
+		/* sync with ieee80211_sta_ps_deliver_wakeup */
Packit c71e3f
+		ps_lock = kpatch_shadow_get(sta, "ps_lock");
Packit c71e3f
+		if (ps_lock) {
Packit c71e3f
+			spin_lock(ps_lock);
Packit c71e3f
+			/*
Packit c71e3f
+			 * STA woke up the meantime and all the frames on ps_tx_buf have
Packit c71e3f
+			 * been queued to pending queue. No reordering can happen, go
Packit c71e3f
+			 * ahead and Tx the packet.
Packit c71e3f
+			 */
Packit c71e3f
+			if (!test_sta_flag(sta, WLAN_STA_PS_STA) &&
Packit c71e3f
+			    !test_sta_flag(sta, WLAN_STA_PS_DRIVER)) {
Packit c71e3f
+				spin_unlock(ps_lock);
Packit c71e3f
+				return TX_CONTINUE;
Packit c71e3f
+			}
Packit c71e3f
+		}
Packit c71e3f
+
Packit c71e3f
 		if (skb_queue_len(&sta->ps_tx_buf[ac]) >= STA_MAX_TX_BUFFER) {
Packit c71e3f
 			struct sk_buff *old = skb_dequeue(&sta->ps_tx_buf[ac]);
Packit c71e3f
 			ps_dbg(tx->sdata,
Packit c71e3f
```
Packit c71e3f
Packit c71e3f
Init code changes
Packit c71e3f
-----------------
Packit c71e3f
Packit c71e3f
Any code which runs in an `__init` function or during module or device
Packit c71e3f
initialization is problematic, as it may have already run before the patch was
Packit c71e3f
applied.  The patch may require a pre-patch callback which detects whether such
Packit c71e3f
init code has run, and which rewrites or changes the original initialization to
Packit c71e3f
force it into the desired state.  Some changes involving hardware init are
Packit c71e3f
inherently incompatible with live patching.
Packit c71e3f
Packit c71e3f
Header file changes
Packit c71e3f
-------------------
Packit c71e3f
Packit c71e3f
When changing header files, be extra careful.  If data is being changed, you
Packit c71e3f
probably need to modify the patch.  See "Data struct changes" above.
Packit c71e3f
Packit c71e3f
If a function prototype is being changed, make sure it's not an exported
Packit c71e3f
function.  Otherwise it could break out-of-tree modules.  One way to
Packit c71e3f
workaround this is to define an entirely new copy of the function (with
Packit c71e3f
updated code) and patch in-tree callers to invoke it rather than the
Packit c71e3f
deprecated version.
Packit c71e3f
Packit c71e3f
Many header file changes result in a complete rebuild of the kernel tree, which
Packit c71e3f
makes kpatch-build have to compare every .o file in the kernel.  It slows the
Packit c71e3f
build down a lot, and can even fail to build if kpatch-build has any bugs
Packit c71e3f
lurking.  If it's a trivial header file change, like adding a macro, it's
Packit c71e3f
advisable to just move that macro into the .c file where it's needed to avoid
Packit c71e3f
changing the header file at all.
Packit c71e3f
Packit c71e3f
Dealing with unexpected changed functions
Packit c71e3f
-----------------------------------------
Packit c71e3f
Packit c71e3f
In general, it's best to patch as minimally as possible.  If kpatch-build is
Packit c71e3f
reporting some unexpected function changes, it's always a good idea to try to
Packit c71e3f
figure out why it thinks they changed.  In many cases you can change the source
Packit c71e3f
patch so that they no longer change.
Packit c71e3f
Packit c71e3f
Some examples:
Packit c71e3f
Packit c71e3f
* If a changed function was inlined, then the callers which inlined the
Packit c71e3f
  function will also change.  In this case there's nothing you can do to
Packit c71e3f
  prevent the extra changes.
Packit c71e3f
Packit c71e3f
* If a changed function was originally inlined, but turned into a callable
Packit c71e3f
  function after patching, consider adding `__always_inline` to the function
Packit c71e3f
  definition.  Likewise, if a function is only inlined after patching,
Packit c71e3f
  consider using `noinline` to prevent the compiler from doing so.
Packit c71e3f
Packit c71e3f
* If your patch adds a call to a function where the original version of the
Packit c71e3f
  function's ELF symbol has a .constprop or .isra suffix, and the corresponding
Packit c71e3f
  patched function doesn't, that means the patch caused gcc to no longer
Packit c71e3f
  perform an interprocedural optimization, which affects the function and all
Packit c71e3f
  its callers.  If you want to prevent this from happening, copy/paste the
Packit c71e3f
  function with a new name and call the new function from your patch.
Packit c71e3f
Packit c71e3f
* Moving around source code lines can introduce unique instructions if any
Packit c71e3f
  `__LINE__` preprocessor macros are in use. This can be mitigated by adding
Packit c71e3f
  any new functions to the bottom of source files, using newline whitespace to
Packit c71e3f
  maintain original line counts, etc. A more exact fix can be employed by
Packit c71e3f
  modifying the source code that invokes `__LINE__` and hard-coding the
Packit c71e3f
  original line number in place.
Packit c71e3f
Packit c71e3f
Removing references to static local variables
Packit c71e3f
---------------------------------------------
Packit c71e3f
Packit c71e3f
Removing references to static locals will fail to patch unless extra steps are taken.
Packit c71e3f
Static locals are basically global variables because they outlive the function's
Packit c71e3f
scope. They need to be correlated so that the new function will use the old static
Packit c71e3f
local. That way patching the function doesn't inadvertently reset the variable
Packit c71e3f
to zero; instead the variable keeps its old value.
Packit c71e3f
Packit c71e3f
To work around this limitation one needs to retain the reference to the static local.
Packit c71e3f
This might be as simple as adding the variable back in the patched function in a 
Packit c71e3f
non-functional way and ensuring the compiler doesn't optimize it away.
Packit c71e3f
Packit c71e3f
Code removal
Packit c71e3f
------------
Packit c71e3f
Packit c71e3f
Some fixes may replace or completely remove functions and references
Packit c71e3f
to them. Remember that kpatch modules can only add new functions and
Packit c71e3f
redirect existing functions, so "removed" functions will continue to exist in
Packit c71e3f
kernel address space as effectively dead code.
Packit c71e3f
Packit c71e3f
That means this patch (source code removal of `cmdline_proc_show`):
Packit c71e3f
```
Packit c71e3f
diff -Nupr src.orig/fs/proc/cmdline.c src/fs/proc/cmdline.c
Packit c71e3f
--- src.orig/fs/proc/cmdline.c	2016-11-30 19:39:49.317737234 +0000
Packit c71e3f
+++ src/fs/proc/cmdline.c	2016-11-30 19:39:52.696737234 +0000
Packit c71e3f
@@ -3,15 +3,15 @@
Packit c71e3f
 #include <linux/proc_fs.h>
Packit c71e3f
 #include <linux/seq_file.h>
Packit c71e3f
 
Packit c71e3f
-static int cmdline_proc_show(struct seq_file *m, void *v)
Packit c71e3f
-{
Packit c71e3f
-	seq_printf(m, "%s\n", saved_command_line);
Packit c71e3f
-	return 0;
Packit c71e3f
-}
Packit c71e3f
+static int cmdline_proc_show_v2(struct seq_file *m, void *v)
Packit c71e3f
+{
Packit c71e3f
+	seq_printf(m, "%s kpatch\n", saved_command_line);
Packit c71e3f
+	return 0;
Packit c71e3f
+}
Packit c71e3f
 
Packit c71e3f
 static int cmdline_proc_open(struct inode *inode, struct file *file)
Packit c71e3f
 {
Packit c71e3f
-	return single_open(file, cmdline_proc_show, NULL);
Packit c71e3f
+	return single_open(file, cmdline_proc_show_v2, NULL);
Packit c71e3f
 }
Packit c71e3f
 
Packit c71e3f
 static const struct file_operations cmdline_proc_fops = {
Packit c71e3f
```
Packit c71e3f
will generate an equivalent kpatch module to this patch (dead
Packit c71e3f
`cmdline_proc_show` left in source):
Packit c71e3f
```
Packit c71e3f
diff -Nupr src.orig/fs/proc/cmdline.c src/fs/proc/cmdline.c
Packit c71e3f
--- src.orig/fs/proc/cmdline.c	2016-11-30 19:39:49.317737234 +0000
Packit c71e3f
+++ src/fs/proc/cmdline.c	2016-11-30 19:39:52.696737234 +0000
Packit c71e3f
@@ -9,9 +9,15 @@ static int cmdline_proc_show(struct seq_
Packit c71e3f
 	return 0;
Packit c71e3f
 }
Packit c71e3f
 
Packit c71e3f
+static int cmdline_proc_show_v2(struct seq_file *m, void *v)
Packit c71e3f
+{
Packit c71e3f
+	seq_printf(m, "%s kpatch\n", saved_command_line);
Packit c71e3f
+	return 0;
Packit c71e3f
+}
Packit c71e3f
+
Packit c71e3f
 static int cmdline_proc_open(struct inode *inode, struct file *file)
Packit c71e3f
 {
Packit c71e3f
-	return single_open(file, cmdline_proc_show, NULL);
Packit c71e3f
+	return single_open(file, cmdline_proc_show_v2, NULL);
Packit c71e3f
 }
Packit c71e3f
 
Packit c71e3f
 static const struct file_operations cmdline_proc_fops = {
Packit c71e3f
```
Packit c71e3f
In both versions, `kpatch-build` will determine that only
Packit c71e3f
`cmdline_proc_open` has changed and that `cmdline_proc_show_v2` is a
Packit c71e3f
new function.
Packit c71e3f
Packit c71e3f
In some patching cases it might be necessary to completely remove the original
Packit c71e3f
function to avoid the compiler complaining about a defined, but unused
Packit c71e3f
function.  This will depend on symbol scope and kernel build options.
Packit c71e3f
Packit c71e3f
Other issues
Packit c71e3f
------------
Packit c71e3f
Packit c71e3f
When adding a call to `printk_once()`, `pr_warn_once()`, or any other "once"
Packit c71e3f
variation of `printk()`, you'll get the following eror:
Packit c71e3f
Packit c71e3f
```
Packit c71e3f
ERROR: vmx.o: 1 unsupported section change(s)
Packit c71e3f
vmx.o: WARNING: unable to correlate static local variable __print_once.60588 used by vmx_update_pi_irte, assuming variable is new
Packit c71e3f
vmx.o: changed function: vmx_update_pi_irte
Packit c71e3f
vmx.o: data section .data..read_mostly selected for inclusion
Packit c71e3f
/usr/lib/kpatch/create-diff-object: unreconcilable difference
Packit c71e3f
```
Packit c71e3f
This error occurs because the `printk_once()` adds a static local variable to
Packit c71e3f
the `.data..read_mostly` section.  kpatch-build strict disallows any changes to
Packit c71e3f
that section, because in some cases a change to this section indicates a bug.
Packit c71e3f
Packit c71e3f
To work around this issue, you'll need to manually implement your own "once"
Packit c71e3f
logic which doesn't store the static variable in the `.data..read_mostly`
Packit c71e3f
section.
Packit c71e3f
Packit c71e3f
For example, a `pr_warn_once()` can be replaced with:
Packit c71e3f
```
Packit c71e3f
	static bool print_once;
Packit c71e3f
	...
Packit c71e3f
	if (!print_once) {
Packit c71e3f
		print_once = true;
Packit c71e3f
		pr_warn("...");
Packit c71e3f
	}
Packit c71e3f
```