Skip to contentSkip to conversation

livepatch: hybrid consistency model

PATCH Superseded Josh Poimboeuf 6 participants 78 messages Dec 8, 2016 – Jan 11, 2017

Subsystems (11)
Documentation x86 PowerPC MM core +7 more subsystems

v3 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

v3 cover livepatch: hybrid consistency model

Dusting the cobwebs off the consistency model again. This is based on linux-next/master.

v1 was posted on 2015-02-09:

https://lkml.kernel.org/r/[email protected]

v2 was posted on 2016-04-28:

https://lkml.kernel.org/r/[email protected]

The biggest issue from v2 was finding a decent way to detect preemption and page faults on the stack of a sleeping task. That problem was solved by rewriting the x86 stack unwinder. The new unwinder helps detect such cases by finding all pt_regs on the stack. When preemption/page faults are detected, the stack is considered unreliable and the patching of the task is deferred.

For more details about the consistency model, see patch 13/15.

---

v3:
- rebase on new x86 unwinder
- force !HAVE_RELIABLE_STACKTRACE arches to use patch->immediate for now, because we don't have a way to transition kthreads otherwise
- rebase s390 TIF_PATCH_PENDING patch onto latest entry code
- update barrier comments and move barrier from the end of klp_init_transition() to its callers
- "klp_work" -> "klp_transition_work"
- "klp_patch_task()" -> "klp_update_patch_state()"
- explicit _TIF_ALLWORK_MASK
- change klp_reverse_transition() to not try to complete transition. instead modify the work queue delay to zero.
- get rid of klp_schedule_work() in favor of calling schedule_delayed_work() directly with a KLP_TRANSITION_DELAY
- initialize klp_target_state to KLP_UNDEFINED
- move klp_target_state assignment to before patch->immediate check in klp_init_transition()
- rcu_read_lock() in klp_update_patch_state(), test the thread flag in patch task, synchronize_rcu() in klp_complete_transition()
- use kstrtobool() in enabled_store()
- change task_rq_lock() argument type to struct rq_flags
- add several WARN_ON_ONCE assertions for klp_target_state and task->patch_state

v2:
- "universe" -> "patch state"
- rename klp_update_task_universe() -> klp_patch_task()
- add preempt IRQ tracking (TF_PREEMPT_IRQ)
- fix print_context_stack_reliable() bug
- improve print_context_stack_reliable() comments
- klp_ftrace_handler comment fixes
- add "patch_state" proc file to tid_base_stuff
- schedule work even for !RELIABLE_STACKTRACE
- forked child inherits patch state from parent
- add detailed comment to livepatch.h klp_func definition about the klp_func patched/transition state transitions
- update exit_to_usermode_loop() comment
- clear all TIF_KLP_NEED_UPDATE flags in klp_complete_transition()
- remove unnecessary function externs
- add livepatch documentation, sysfs documentation, /proc documentation
- /proc/pid/patch_state: -1 means no patch is currently being applied/reverted
- "TIF_KLP_NEED_UPDATE" -> "TIF_PATCH_PENDING"
- support for s390 and powerpc-le
- don't assume stacks with dynamic ftrace trampolines are reliable
- add _TIF_ALLWORK_MASK info to commit log

v1.9:
- revive from the dead and rebased
- reliable stacks!
- add support for immediate consistency model
- add a ton of comments
- fix up memory barriers
- remove "allow patch modules to be removed" patch for now, it still needs more discussion and thought - it can be done with something
- "proc/pid/universe" -> "proc/pid/patch_status"
- remove WARN_ON_ONCE from !func condition in ftrace handler -- can happen because of RCU
- keep klp_mutex private by putting the work_fn in core.c
- convert states from int to boolean
- remove obsolete '@state' comments
- several header file and include improvements suggested by Jiri S
- change kallsyms_lookup_size_offset() errors from EINVAL -> ENOENT
- change proc file permissions S_IRUGO -> USR
- use klp_for_each_object/func helpers

---

Jiri Slaby (1):
livepatch/s390: reorganize TIF thread flag bits

Josh Poimboeuf (12):
stacktrace/x86: add function for detecting reliable stack traces x86/entry: define _TIF_ALLWORK_MASK flags explicitly
livepatch: temporary stubs for klp_patch_pending() and
klp_update_patch_state()
livepatch/x86: add TIF_PATCH_PENDING thread flag livepatch/powerpc: add TIF_PATCH_PENDING thread flag
livepatch: separate enabled and patched states
livepatch: remove unnecessary object loaded check
livepatch: move patching functions into patch.c
livepatch: use kstrtobool() in enabled_store()
livepatch: store function sizes
livepatch: change to a per-task consistency model
livepatch: add /proc/<pid>/patch_state

Miroslav Benes (2):
livepatch/s390: add TIF_PATCH_PENDING thread flag
livepatch: allow removal of a disabled patch

 Documentation/ABI/testing/sysfs-kernel-livepatch |   8 +
 Documentation/filesystems/proc.txt               |  18 +
 Documentation/livepatch/livepatch.txt            | 156 ++++++--
 arch/Kconfig                                     |   6 +
 arch/powerpc/include/asm/thread_info.h           |   4 +-
 arch/powerpc/kernel/signal.c                     |   4 +
 arch/s390/include/asm/thread_info.h              |  24 +-
 arch/s390/kernel/entry.S                         |  31 +-
 arch/x86/Kconfig                                 |   1 +
 arch/x86/entry/common.c                          |   9 +-
 arch/x86/include/asm/thread_info.h               |  11 +-
 arch/x86/include/asm/unwind.h                    |   6 +
 arch/x86/kernel/stacktrace.c                     |  59 ++-
 arch/x86/kernel/unwind_frame.c                   |   1 +
 fs/proc/base.c                                   |  15 +
 include/linux/init_task.h                        |   9 +
 include/linux/livepatch.h                        |  66 ++-
 include/linux/sched.h                            |   3 +
 include/linux/stacktrace.h                       |   8 +-
 kernel/fork.c                                    |   3 +
 kernel/livepatch/Makefile                        |   2 +-
 kernel/livepatch/core.c                          | 446 +++++++++------------
 kernel/livepatch/patch.c                         | 261 ++++++++++++
 kernel/livepatch/patch.h                         |  33 ++
 kernel/livepatch/transition.c                    | 487 +++++++++++++++++++++++
 kernel/livepatch/transition.h                    |  14 +
 kernel/sched/idle.c                              |   4 +
 kernel/stacktrace.c                              |  12 +-
 samples/livepatch/livepatch-sample.c             |   8 +-
 29 files changed, 1367 insertions(+), 342 deletions(-)
 create mode 100644 kernel/livepatch/patch.c
 create mode 100644 kernel/livepatch/patch.h
 create mode 100644 kernel/livepatch/transition.c
 create mode 100644 kernel/livepatch/transition.h
Signature · 1 line
2.7.4
#1 lore raw

PATCH v3 1/15 stacktrace/x86: add function for detecting reliable stack traces

For live patching and possibly other use cases, a stack trace is only useful if it can be assured that it's completely reliable. Add a new save_stack_trace_tsk_reliable() function to achieve that.

Scenarios which indicate that a stack trace may be unreliable:

- running task
- interrupt stack
- preemption
- corrupted stack data
- stack grows the wrong way
- stack walk doesn't reach the bottom
- user didn't provide a large enough entries array

Also add CONFIG_HAVE_RELIABLE_STACKTRACE so arch-independent code can determine at build time whether the function is implemented.

---
 arch/Kconfig                   |  6 +++++
 arch/x86/Kconfig               |  1 +
 arch/x86/include/asm/unwind.h  |  6 +++++
 arch/x86/kernel/stacktrace.c   | 59 +++++++++++++++++++++++++++++++++++++++++-
 arch/x86/kernel/unwind_frame.c |  1 +
 include/linux/stacktrace.h     |  8 +++---
 kernel/stacktrace.c            | 12 +++++++--
 7 files changed, 87 insertions(+), 6 deletions(-)
arch/Kconfig +6 -0
index 13f27c1..d61a133 100644
@@ -678,6 +678,12 @@ config HAVE_STACK_VALIDATION
 	  Architecture supports the 'objtool check' host tool command, which
 	  performs compile-time stack metadata validation.
 
+config HAVE_RELIABLE_STACKTRACE
+	bool
+	help
+	  Architecture has a save_stack_trace_tsk_reliable() function which
+	  only returns a stack trace if it can guarantee the trace is reliable.
+
 config HAVE_ARCH_HASH
 	bool
 	default n
arch/x86/Kconfig +1 -0
index 215612c..b4a6663 100644
@@ -155,6 +155,7 @@ config X86
 	select HAVE_PERF_REGS
 	select HAVE_PERF_USER_STACK_DUMP
 	select HAVE_REGS_AND_STACK_ACCESS_API
+	select HAVE_RELIABLE_STACKTRACE		if X86_64 && FRAME_POINTER && STACK_VALIDATION
 	select HAVE_STACK_VALIDATION		if X86_64
 	select HAVE_SYSCALL_TRACEPOINTS
 	select HAVE_UNSTABLE_SCHED_CLOCK
arch/x86/include/asm/unwind.h +6 -0
index c5a7f3a..44f86dc 100644
@@ -11,6 +11,7 @@ struct unwind_state {
 	unsigned long stack_mask;
 	struct task_struct *task;
 	int graph_idx;
+	bool error;
 #ifdef CONFIG_FRAME_POINTER
 	unsigned long *bp;
 	struct pt_regs *regs;
@@ -40,6 +41,11 @@ void unwind_start(struct unwind_state *state, struct task_struct *task,
 	__unwind_start(state, task, regs, first_frame);
 }
 
+static inline bool unwind_error(struct unwind_state *state)
+{
+	return state->error;
+}
+
 #ifdef CONFIG_FRAME_POINTER
 
 static inline
arch/x86/kernel/stacktrace.c +58 -1

68 lines not on this page · raw message

arch/x86/kernel/unwind_frame.c +1 -0
index ea7b7f9..f82525a 100644
@@ -184,6 +184,7 @@ bool unwind_next_frame(struct unwind_state *state)
 			state->bp, state->task->comm,
 			state->task->pid, next_frame);
 	}
+	state->error = true;
 the_end:
 	state->stack_info.type = STACK_TYPE_UNKNOWN;
 	return false;
include/linux/stacktrace.h +5 -3
index 0a34489..8e8b67b 100644
@@ -18,6 +18,8 @@ extern void save_stack_trace_regs(struct pt_regs *regs,
 				  struct stack_trace *trace);
 extern void save_stack_trace_tsk(struct task_struct *tsk,
 				struct stack_trace *trace);
+extern int save_stack_trace_tsk_reliable(struct task_struct *tsk,
+					 struct stack_trace *trace);
 
 extern void print_stack_trace(struct stack_trace *trace, int spaces);
 extern int snprint_stack_trace(char *buf, size_t size,
@@ -29,12 +31,12 @@ extern void save_stack_trace_user(struct stack_trace *trace);
 # define save_stack_trace_user(trace)              do { } while (0)
 #endif
 
-#else
+#else /* !CONFIG_STACKTRACE */
 # define save_stack_trace(trace)			do { } while (0)
 # define save_stack_trace_tsk(tsk, trace)		do { } while (0)
 # define save_stack_trace_user(trace)			do { } while (0)
 # define print_stack_trace(trace, spaces)		do { } while (0)
 # define snprint_stack_trace(buf, size, trace, spaces)	do { } while (0)
-#endif
+#endif /* CONFIG_STACKTRACE */
 
-#endif
+#endif /* __LINUX_STACKTRACE_H */
kernel/stacktrace.c +10 -2
index b6e4c16..4ef81dc 100644
@@ -58,8 +58,8 @@ int snprint_stack_trace(char *buf, size_t size,
 EXPORT_SYMBOL_GPL(snprint_stack_trace);
 
 /*
- * Architectures that do not implement save_stack_trace_tsk or
- * save_stack_trace_regs get this weak alias and a once-per-bootup warning
+ * Architectures that do not implement save_stack_trace_*()
+ * get these weak aliases and once-per-bootup warnings
  * (whenever this facility is utilized - for example by procfs):
  */
 __weak void
@@ -73,3 +73,11 @@ save_stack_trace_regs(struct pt_regs *regs, struct stack_trace *trace)
 {
 	WARN_ONCE(1, KERN_INFO "save_stack_trace_regs() not implemented yet.\n");
 }
+
+__weak int
+save_stack_trace_tsk_reliable(struct task_struct *tsk,
+			      struct stack_trace *trace)
+{
+	WARN_ONCE(1, KERN_INFO "save_stack_tsk_reliable() not implemented yet.\n");
+	return -ENOSYS;
+}
Signature · 1 line
2.7.4
#9 lore raw

PATCH v3 2/15 x86/entry: define _TIF_ALLWORK_MASK flags explicitly

In reply to Josh Poimboeuf

The _TIF_ALLWORK_MASK macro automatically includes the least-significant 16 bits of the thread_info flags, which is less than obvious and tends to create confusion and surprises when reading or modifying the code.

Define the flags explicitly.

---
 arch/x86/include/asm/thread_info.h | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)
arch/x86/include/asm/thread_info.h +4 -5
index ad6f5eb0..1fe6043 100644
@@ -73,9 +73,6 @@ struct thread_info {
  * thread information flags
  * - these are process state flags that various assembly files
  *   may need to access
- * - pending work-to-be-done flags are in LSW
- * - other flags in MSW
- * Warning: layout of LSW is hardcoded in entry.S
  */
 #define TIF_SYSCALL_TRACE	0	/* syscall trace active */
 #define TIF_NOTIFY_RESUME	1	/* callback before returning to user */
@@ -133,8 +130,10 @@ struct thread_info {
 
 /* work to do on any return to user space */
 #define _TIF_ALLWORK_MASK						\
-	((0x0000FFFF & ~_TIF_SECCOMP) | _TIF_SYSCALL_TRACEPOINT |	\
-	_TIF_NOHZ)
+	(_TIF_SYSCALL_TRACE | _TIF_NOTIFY_RESUME | _TIF_SIGPENDING |	\
+	 _TIF_SINGLESTEP | _TIF_NEED_RESCHED | _TIF_SYSCALL_EMU |	\
+	 _TIF_SYSCALL_AUDIT | _TIF_USER_RETURN_NOTIFY | _TIF_UPROBE |	\
+	 _TIF_SYSCALL_TRACEPOINT | _TIF_NOHZ)
 
 /* flags to check in __switch_to() */
 #define _TIF_WORK_CTXSW							\
Signature · 1 line
2.7.4
#14 lore raw

PATCH v3 3/15 livepatch: temporary stubs for klp_patch_pending() and klp_update_patch_state()

In reply to Josh Poimboeuf

Create temporary stubs for klp_patch_pending() and klp_update_patch_state() so we can add TIF_PATCH_PENDING to different architectures in separate patches without breaking build bisectability.

---
 include/linux/livepatch.h | 7 ++++++-
 kernel/livepatch/core.c   | 3 +++
 2 files changed, 9 insertions(+), 1 deletion(-)
include/linux/livepatch.h +6 -1
index 9072f04..60558d8 100644
@@ -123,10 +123,15 @@ void arch_klp_init_object_loaded(struct klp_patch *patch,
 int klp_module_coming(struct module *mod);
 void klp_module_going(struct module *mod);
 
+static inline bool klp_patch_pending(struct task_struct *task) { return false; }
+void klp_update_patch_state(struct task_struct *task);
+
 #else /* !CONFIG_LIVEPATCH */
 
 static inline int klp_module_coming(struct module *mod) { return 0; }
-static inline void klp_module_going(struct module *mod) { }
+static inline void klp_module_going(struct module *mod) {}
+static inline bool klp_patch_pending(struct task_struct *task) { return false; }
+static inline void klp_update_patch_state(struct task_struct *task) {}
 
 #endif /* CONFIG_LIVEPATCH */
 
kernel/livepatch/core.c +3 -0
index af46438..217b39d 100644
@@ -64,6 +64,9 @@ static LIST_HEAD(klp_ops);
 
 static struct kobject *klp_root_kobj;
 
+/* TODO: temporary stub */
+void klp_update_patch_state(struct task_struct *task) {}
+
 static struct klp_ops *klp_find_ops(unsigned long old_addr)
 {
 	struct klp_ops *ops;
Signature · 1 line
2.7.4
#17 lore raw

PATCH v3 4/15 livepatch/x86: add TIF_PATCH_PENDING thread flag

In reply to Josh Poimboeuf

Add the TIF_PATCH_PENDING thread flag to enable the new livepatch per-task consistency model for x86_64. The bit getting set indicates the thread has a pending patch which needs to be applied when the thread exits the kernel.

The bit is placed in the _TIF_ALLWORK_MASK macro, which results in exit_to_usermode_loop() calling klp_update_patch_state() when it's set.

---
 arch/x86/entry/common.c            | 9 ++++++---
 arch/x86/include/asm/thread_info.h | 4 +++-
 2 files changed, 9 insertions(+), 4 deletions(-)
arch/x86/entry/common.c +6 -3
index bdd9cc5..16a51a5 100644
@@ -21,6 +21,7 @@
 #include <linux/context_tracking.h>
 #include <linux/user-return-notifier.h>
 #include <linux/uprobes.h>
+#include <linux/livepatch.h>
 
 #include <asm/desc.h>
 #include <asm/traps.h>
@@ -129,14 +130,13 @@ static long syscall_trace_enter(struct pt_regs *regs)
 
 #define EXIT_TO_USERMODE_LOOP_FLAGS				\
 	(_TIF_SIGPENDING | _TIF_NOTIFY_RESUME | _TIF_UPROBE |	\
-	 _TIF_NEED_RESCHED | _TIF_USER_RETURN_NOTIFY)
+	 _TIF_NEED_RESCHED | _TIF_USER_RETURN_NOTIFY | _TIF_PATCH_PENDING)
 
 static void exit_to_usermode_loop(struct pt_regs *regs, u32 cached_flags)
 {
 	/*
 	 * In order to return to user mode, we need to have IRQs off with
-	 * none of _TIF_SIGPENDING, _TIF_NOTIFY_RESUME, _TIF_USER_RETURN_NOTIFY,
-	 * _TIF_UPROBE, or _TIF_NEED_RESCHED set.  Several of these flags
+	 * none of EXIT_TO_USERMODE_LOOP_FLAGS set.  Several of these flags
 	 * can be set at any time on preemptable kernels if we have IRQs on,
 	 * so we need to loop.  Disabling preemption wouldn't help: doing the
 	 * work to clear some of the flags can sleep.
@@ -163,6 +163,9 @@ static void exit_to_usermode_loop(struct pt_regs *regs, u32 cached_flags)
 		if (cached_flags & _TIF_USER_RETURN_NOTIFY)
 			fire_user_return_notifiers();
 
+		if (cached_flags & _TIF_PATCH_PENDING)
+			klp_update_patch_state(current);
+
 		/* Disable IRQs and retry */
 		local_irq_disable();
 
arch/x86/include/asm/thread_info.h +3 -1
index 1fe6043..79f4d6a 100644
@@ -84,6 +84,7 @@ struct thread_info {
 #define TIF_SECCOMP		8	/* secure computing */
 #define TIF_USER_RETURN_NOTIFY	11	/* notify kernel of userspace return */
 #define TIF_UPROBE		12	/* breakpointed or singlestepping */
+#define TIF_PATCH_PENDING	13	/* pending live patching update */
 #define TIF_NOTSC		16	/* TSC is not accessible in userland */
 #define TIF_IA32		17	/* IA32 compatibility process */
 #define TIF_NOHZ		19	/* in adaptive nohz mode */
@@ -107,6 +108,7 @@ struct thread_info {
 #define _TIF_SECCOMP		(1 << TIF_SECCOMP)
 #define _TIF_USER_RETURN_NOTIFY	(1 << TIF_USER_RETURN_NOTIFY)
 #define _TIF_UPROBE		(1 << TIF_UPROBE)
+#define _TIF_PATCH_PENDING	(1 << TIF_PATCH_PENDING)
 #define _TIF_NOTSC		(1 << TIF_NOTSC)
 #define _TIF_IA32		(1 << TIF_IA32)
 #define _TIF_NOHZ		(1 << TIF_NOHZ)
@@ -133,7 +135,7 @@ struct thread_info {
 	(_TIF_SYSCALL_TRACE | _TIF_NOTIFY_RESUME | _TIF_SIGPENDING |	\
 	 _TIF_SINGLESTEP | _TIF_NEED_RESCHED | _TIF_SYSCALL_EMU |	\
 	 _TIF_SYSCALL_AUDIT | _TIF_USER_RETURN_NOTIFY | _TIF_UPROBE |	\
-	 _TIF_SYSCALL_TRACEPOINT | _TIF_NOHZ)
+	 _TIF_SYSCALL_TRACEPOINT | _TIF_NOHZ | _TIF_PATCH_PENDING)
 
 /* flags to check in __switch_to() */
 #define _TIF_WORK_CTXSW							\
Signature · 1 line
2.7.4
#22 lore raw

PATCH v3 5/15 livepatch/powerpc: add TIF_PATCH_PENDING thread flag

In reply to Josh Poimboeuf

Add the TIF_PATCH_PENDING thread flag to enable the new livepatch per-task consistency model for powerpc. The bit getting set indicates the thread has a pending patch which needs to be applied when the thread exits the kernel.

The bit is included in the _TIF_USER_WORK_MASK macro so that do_notify_resume() and klp_update_patch_state() get called when the bit is set.

---
 arch/powerpc/include/asm/thread_info.h | 4 +++-
 arch/powerpc/kernel/signal.c           | 4 ++++
 2 files changed, 7 insertions(+), 1 deletion(-)
arch/powerpc/include/asm/thread_info.h +3 -1
index 87e4b2d..6fc6464 100644
@@ -92,6 +92,7 @@ static inline struct thread_info *current_thread_info(void)
 					   TIF_NEED_RESCHED */
 #define TIF_32BIT		4	/* 32 bit binary */
 #define TIF_RESTORE_TM		5	/* need to restore TM FP/VEC/VSX */
+#define TIF_PATCH_PENDING	6	/* pending live patching update */
 #define TIF_SYSCALL_AUDIT	7	/* syscall auditing active */
 #define TIF_SINGLESTEP		8	/* singlestepping active */
 #define TIF_NOHZ		9	/* in adaptive nohz mode */
@@ -115,6 +116,7 @@ static inline struct thread_info *current_thread_info(void)
 #define _TIF_POLLING_NRFLAG	(1<<TIF_POLLING_NRFLAG)
 #define _TIF_32BIT		(1<<TIF_32BIT)
 #define _TIF_RESTORE_TM		(1<<TIF_RESTORE_TM)
+#define _TIF_PATCH_PENDING	(1<<TIF_PATCH_PENDING)
 #define _TIF_SYSCALL_AUDIT	(1<<TIF_SYSCALL_AUDIT)
 #define _TIF_SINGLESTEP		(1<<TIF_SINGLESTEP)
 #define _TIF_SECCOMP		(1<<TIF_SECCOMP)
@@ -131,7 +133,7 @@ static inline struct thread_info *current_thread_info(void)
 
 #define _TIF_USER_WORK_MASK	(_TIF_SIGPENDING | _TIF_NEED_RESCHED | \
 				 _TIF_NOTIFY_RESUME | _TIF_UPROBE | \
-				 _TIF_RESTORE_TM)
+				 _TIF_RESTORE_TM | _TIF_PATCH_PENDING)
 #define _TIF_PERSYSCALL_MASK	(_TIF_RESTOREALL|_TIF_NOERROR)
 
 /* Bits in local_flags */
arch/powerpc/kernel/signal.c +4 -0
index bbe77ae..02d78f9 100644
@@ -14,6 +14,7 @@
 #include <linux/uprobes.h>
 #include <linux/key.h>
 #include <linux/context_tracking.h>
+#include <linux/livepatch.h>
 #include <asm/hw_breakpoint.h>
 #include <asm/uaccess.h>
 #include <asm/unistd.h>
@@ -162,6 +163,9 @@ void do_notify_resume(struct pt_regs *regs, unsigned long thread_info_flags)
 		tracehook_notify_resume(regs);
 	}
 
+	if (thread_info_flags & _TIF_PATCH_PENDING)
+		klp_update_patch_state(current);
+
 	user_enter();
 }
 
Signature · 1 line
2.7.4
#26 lore raw

PATCH v3 6/15 livepatch/s390: reorganize TIF thread flag bits

In reply to Josh Poimboeuf

From: Jiri Slaby <[email protected]>

Group the TIF thread flag bits by their inclusion in the _TIF_WORK and _TIF_TRACE macros.

---
 arch/s390/include/asm/thread_info.h | 22 ++++++++++++++--------
 1 file changed, 14 insertions(+), 8 deletions(-)
arch/s390/include/asm/thread_info.h +14 -8
index a5b54a4..4977668 100644
@@ -51,14 +51,12 @@ int arch_dup_task_struct(struct task_struct *dst, struct task_struct *src);
 /*
  * thread information flags bit numbers
  */
+/* _TIF_WORK bits */
 #define TIF_NOTIFY_RESUME	0	/* callback before returning to user */
 #define TIF_SIGPENDING		1	/* signal pending */
 #define TIF_NEED_RESCHED	2	/* rescheduling necessary */
-#define TIF_SYSCALL_TRACE	3	/* syscall trace active */
-#define TIF_SYSCALL_AUDIT	4	/* syscall auditing active */
-#define TIF_SECCOMP		5	/* secure computing */
-#define TIF_SYSCALL_TRACEPOINT	6	/* syscall tracepoint instrumentation */
-#define TIF_UPROBE		7	/* breakpointed or single-stepping */
+#define TIF_UPROBE		3	/* breakpointed or single-stepping */
+
 #define TIF_31BIT		16	/* 32bit process */
 #define TIF_MEMDIE		17	/* is terminating due to OOM killer */
 #define TIF_RESTORE_SIGMASK	18	/* restore signal mask in do_signal() */
@@ -66,15 +64,23 @@ int arch_dup_task_struct(struct task_struct *dst, struct task_struct *src);
 #define TIF_BLOCK_STEP		20	/* This task is block stepped */
 #define TIF_UPROBE_SINGLESTEP	21	/* This task is uprobe single stepped */
 
+/* _TIF_TRACE bits */
+#define TIF_SYSCALL_TRACE	24	/* syscall trace active */
+#define TIF_SYSCALL_AUDIT	25	/* syscall auditing active */
+#define TIF_SECCOMP		26	/* secure computing */
+#define TIF_SYSCALL_TRACEPOINT	27	/* syscall tracepoint instrumentation */
+
 #define _TIF_NOTIFY_RESUME	_BITUL(TIF_NOTIFY_RESUME)
 #define _TIF_SIGPENDING		_BITUL(TIF_SIGPENDING)
 #define _TIF_NEED_RESCHED	_BITUL(TIF_NEED_RESCHED)
+#define _TIF_UPROBE		_BITUL(TIF_UPROBE)
+
+#define _TIF_31BIT		_BITUL(TIF_31BIT)
+#define _TIF_SINGLE_STEP	_BITUL(TIF_SINGLE_STEP)
+
 #define _TIF_SYSCALL_TRACE	_BITUL(TIF_SYSCALL_TRACE)
 #define _TIF_SYSCALL_AUDIT	_BITUL(TIF_SYSCALL_AUDIT)
 #define _TIF_SECCOMP		_BITUL(TIF_SECCOMP)
 #define _TIF_SYSCALL_TRACEPOINT	_BITUL(TIF_SYSCALL_TRACEPOINT)
-#define _TIF_UPROBE		_BITUL(TIF_UPROBE)
-#define _TIF_31BIT		_BITUL(TIF_31BIT)
-#define _TIF_SINGLE_STEP	_BITUL(TIF_SINGLE_STEP)
 
 #endif /* _ASM_THREAD_INFO_H */
Signature · 1 line
2.7.4
#28 lore raw

PATCH v3 7/15 livepatch/s390: add TIF_PATCH_PENDING thread flag

In reply to Josh Poimboeuf

From: Miroslav Benes <[email protected]>

Update a task's patch state when returning from a system call or user space interrupt, or after handling a signal.

This greatly increases the chances of a patch operation succeeding. If a task is I/O bound, it can be patched when returning from a system call. If a task is CPU bound, it can be patched when returning from an interrupt. If a task is sleeping on a to-be-patched function, the user can send SIGSTOP and SIGCONT to force it to switch.

Since there are two ways the syscall can be restarted on return from a signal handling process, it is important to clear the flag before do_signal() is called. Otherwise we could miss the migration if we used SIGSTOP/SIGCONT procedure or fake signal to migrate patching blocking tasks. If we place our hook to sysc_work label in entry before TIF_SIGPENDING is evaluated we kill two birds with one stone. The task is correctly migrated in all return paths from a syscall.

---
 arch/s390/include/asm/thread_info.h |  2 ++
 arch/s390/kernel/entry.S            | 31 ++++++++++++++++++++++++++++++-
 2 files changed, 32 insertions(+), 1 deletion(-)
arch/s390/include/asm/thread_info.h +2 -0
index 4977668..646845e 100644
@@ -56,6 +56,7 @@ int arch_dup_task_struct(struct task_struct *dst, struct task_struct *src);
 #define TIF_SIGPENDING		1	/* signal pending */
 #define TIF_NEED_RESCHED	2	/* rescheduling necessary */
 #define TIF_UPROBE		3	/* breakpointed or single-stepping */
+#define TIF_PATCH_PENDING	4	/* pending live patching update */
 
 #define TIF_31BIT		16	/* 32bit process */
 #define TIF_MEMDIE		17	/* is terminating due to OOM killer */
@@ -74,6 +75,7 @@ int arch_dup_task_struct(struct task_struct *dst, struct task_struct *src);
 #define _TIF_SIGPENDING		_BITUL(TIF_SIGPENDING)
 #define _TIF_NEED_RESCHED	_BITUL(TIF_NEED_RESCHED)
 #define _TIF_UPROBE		_BITUL(TIF_UPROBE)
+#define _TIF_PATCH_PENDING	_BITUL(TIF_PATCH_PENDING)
 
 #define _TIF_31BIT		_BITUL(TIF_31BIT)
 #define _TIF_SINGLE_STEP	_BITUL(TIF_SINGLE_STEP)
arch/s390/kernel/entry.S +30 -1
index 161f4e6..33848a8 100644
@@ -47,7 +47,7 @@ STACK_SIZE  = 1 << STACK_SHIFT
 STACK_INIT = STACK_SIZE - STACK_FRAME_OVERHEAD - __PT_SIZE
 
 _TIF_WORK	= (_TIF_SIGPENDING | _TIF_NOTIFY_RESUME | _TIF_NEED_RESCHED | \
-		   _TIF_UPROBE)
+		   _TIF_UPROBE | _TIF_PATCH_PENDING)
 _TIF_TRACE	= (_TIF_SYSCALL_TRACE | _TIF_SYSCALL_AUDIT | _TIF_SECCOMP | \
 		   _TIF_SYSCALL_TRACEPOINT)
 _CIF_WORK	= (_CIF_MCCK_PENDING | _CIF_ASCE | _CIF_FPU)
@@ -352,6 +352,11 @@ ENTRY(system_call)
 #endif
 	TSTMSK	__PT_FLAGS(%r11),_PIF_PER_TRAP
 	jo	.Lsysc_singlestep
+#ifdef CONFIG_LIVEPATCH
+	TSTMSK	__TI_flags(%r12),_TIF_PATCH_PENDING
+	jo	.Lsysc_patch_pending	# handle live patching just before
+					# signals and possible syscall restart
+#endif
 	TSTMSK	__TI_flags(%r12),_TIF_SIGPENDING
 	jo	.Lsysc_sigpending
 	TSTMSK	__TI_flags(%r12),_TIF_NOTIFY_RESUME
@@ -426,6 +431,16 @@ ENTRY(system_call)
 #endif
 
 #
+# _TIF_PATCH_PENDING is set, call klp_update_patch_state
+#
+#ifdef CONFIG_LIVEPATCH
+.Lsysc_patch_pending:
+	lg	%r2,__LC_CURRENT	# pass pointer to task struct
+	larl	%r14,.Lsysc_return
+	jg	klp_update_patch_state
+#endif
+
+#
 # _PIF_PER_TRAP is set, call do_per_trap
 #
 .Lsysc_singlestep:
@@ -674,6 +689,10 @@ ENTRY(io_int_handler)
 	jo	.Lio_mcck_pending
 	TSTMSK	__TI_flags(%r12),_TIF_NEED_RESCHED
 	jo	.Lio_reschedule
+#ifdef CONFIG_LIVEPATCH
+	TSTMSK	__TI_flags(%r12),_TIF_PATCH_PENDING
+	jo	.Lio_patch_pending
+#endif
 	TSTMSK	__TI_flags(%r12),_TIF_SIGPENDING
 	jo	.Lio_sigpending
 	TSTMSK	__TI_flags(%r12),_TIF_NOTIFY_RESUME
@@ -720,6 +739,16 @@ ENTRY(io_int_handler)
 	j	.Lio_return
 
 #
+# _TIF_PATCH_PENDING is set, call klp_update_patch_state
+#
+#ifdef CONFIG_LIVEPATCH
+.Lio_patch_pending:
+	lg	%r2,__LC_CURRENT	# pass pointer to task struct
+	larl	%r14,.Lio_return
+	jg	klp_update_patch_state
+#endif
+
+#
 # _TIF_SIGPENDING or is set, call do_signal
 #
 .Lio_sigpending:
Signature · 1 line
2.7.4
#29 lore raw

PATCH v3 8/15 livepatch: separate enabled and patched states

In reply to Josh Poimboeuf

Once we have a consistency model, patches and their objects will be enabled and disabled at different times. For example, when a patch is disabled, its loaded objects' funcs can remain registered with ftrace indefinitely until the unpatching operation is complete and they're no longer in use.

It's less confusing if we give them different names: patches can be enabled or disabled; objects (and their funcs) can be patched or unpatched:

- Enabled means that a patch is logically enabled (but not necessarily fully applied).

- Patched means that an object's funcs are registered with ftrace and added to the klp_ops func stack.

Also, since these states are binary, represent them with booleans instead of ints.

---
 include/linux/livepatch.h | 17 ++++-------
 kernel/livepatch/core.c   | 72 +++++++++++++++++++++++------------------------
 2 files changed, 42 insertions(+), 47 deletions(-)
include/linux/livepatch.h +6 -11
index 60558d8..1e2eb91 100644
@@ -28,11 +28,6 @@
 
 #include <asm/livepatch.h>
 
-enum klp_state {
-	KLP_DISABLED,
-	KLP_ENABLED
-};
-
 /**
  * struct klp_func - function structure for live patching
  * @old_name:	name of the function to be patched
@@ -41,8 +36,8 @@ enum klp_state {
  *		can be found (optional)
  * @old_addr:	the address of the function being patched
  * @kobj:	kobject for sysfs resources
- * @state:	tracks function-level patch application state
  * @stack_node:	list node for klp_ops func_stack list
+ * @patched:	the func has been added to the klp_ops list
  */
 struct klp_func {
 	/* external */
@@ -60,8 +55,8 @@ struct klp_func {
 	/* internal */
 	unsigned long old_addr;
 	struct kobject kobj;
-	enum klp_state state;
 	struct list_head stack_node;
+	bool patched;
 };
 
 /**
@@ -71,7 +66,7 @@ struct klp_func {
  * @kobj:	kobject for sysfs resources
  * @mod:	kernel module associated with the patched object
  * 		(NULL for vmlinux)
- * @state:	tracks object-level patch application state
+ * @patched:	the object's funcs have been added to the klp_ops list
  */
 struct klp_object {
 	/* external */
@@ -81,7 +76,7 @@ struct klp_object {
 	/* internal */
 	struct kobject kobj;
 	struct module *mod;
-	enum klp_state state;
+	bool patched;
 };
 
 /**
@@ -90,7 +85,7 @@ struct klp_object {
  * @objs:	object entries for kernel objects to be patched
  * @list:	list node for global list of registered patches
  * @kobj:	kobject for sysfs resources
- * @state:	tracks patch-level application state
+ * @enabled:	the patch is enabled (but operation may be incomplete)
  */
 struct klp_patch {
 	/* external */
@@ -100,7 +95,7 @@ struct klp_patch {
 	/* internal */
 	struct list_head list;
 	struct kobject kobj;
-	enum klp_state state;
+	bool enabled;
 };
 
 #define klp_for_each_object(patch, obj) \
kernel/livepatch/core.c +36 -36

233 lines not on this page · raw message

Signature · 1 line
2.7.4
#33 lore raw

PATCH v3 9/15 livepatch: remove unnecessary object loaded check

In reply to Josh Poimboeuf

klp_patch_object()'s callers already ensure that the object is loaded, so its call to klp_is_object_loaded() is unnecessary.

This will also make it possible to move the patching code into a separate file.

---
 kernel/livepatch/core.c | 3 ---
 1 file changed, 3 deletions(-)
kernel/livepatch/core.c +0 -3
index 2dbd355..47ed643 100644
@@ -467,9 +467,6 @@ static int klp_patch_object(struct klp_object *obj)
 	if (WARN_ON(obj->patched))
 		return -EINVAL;
 
-	if (WARN_ON(!klp_is_object_loaded(obj)))
-		return -EINVAL;
-
 	klp_for_each_func(obj, func) {
 		ret = klp_patch_func(func);
 		if (ret) {
Signature · 1 line
2.7.4
#37 lore raw

PATCH v3 10/15 livepatch: move patching functions into patch.c

In reply to Josh Poimboeuf

Move functions related to the actual patching of functions and objects into a new patch.c file.

---
 kernel/livepatch/Makefile |   2 +-
 kernel/livepatch/core.c   | 202 +------------------------------------------
 kernel/livepatch/patch.c  | 213 ++++++++++++++++++++++++++++++++++++++++++++++
 kernel/livepatch/patch.h  |  32 +++++++
 4 files changed, 247 insertions(+), 202 deletions(-)
 create mode 100644 kernel/livepatch/patch.c
 create mode 100644 kernel/livepatch/patch.h
kernel/livepatch/Makefile +1 -1
index e8780c0..e136dad 100644
@@ -1,3 +1,3 @@
 obj-$(CONFIG_LIVEPATCH) += livepatch.o
 
-livepatch-objs := core.o
+livepatch-objs := core.o patch.o
kernel/livepatch/core.c +1 -201

232 lines not on this page · raw message

kernel/livepatch/patch.c new file +213 -0

213 lines not on this page · raw message

kernel/livepatch/patch.h new file +32 -0
new file mode 100644
index 0000000..2d0cce0
@@ -0,0 +1,32 @@
+#ifndef _LIVEPATCH_PATCH_H
+#define _LIVEPATCH_PATCH_H
+
+#include <linux/livepatch.h>
+#include <linux/list.h>
+#include <linux/ftrace.h>
+
+/**
+ * struct klp_ops - structure for tracking registered ftrace ops structs
+ *
+ * A single ftrace_ops is shared between all enabled replacement functions
+ * (klp_func structs) which have the same old_addr.  This allows the switch
+ * between function versions to happen instantaneously by updating the klp_ops
+ * struct's func_stack list.  The winner is the klp_func at the top of the
+ * func_stack (front of the list).
+ *
+ * @node:	node for the global klp_ops list
+ * @func_stack:	list head for the stack of klp_func's (active func is on top)
+ * @fops:	registered ftrace ops struct
+ */
+struct klp_ops {
+	struct list_head node;
+	struct list_head func_stack;
+	struct ftrace_ops fops;
+};
+
+struct klp_ops *klp_find_ops(unsigned long old_addr);
+
+int klp_patch_object(struct klp_object *obj);
+void klp_unpatch_object(struct klp_object *obj);
+
+#endif /* _LIVEPATCH_PATCH_H */
Signature · 1 line
2.7.4
#41 lore raw

PATCH v3 11/15 livepatch: use kstrtobool() in enabled_store()

In reply to Josh Poimboeuf

The sysfs enabled value is a boolean, so kstrtobool() is a better fit for parsing the input string since it does the range checking for us.

---
 kernel/livepatch/core.c | 11 ++++-------
 1 file changed, 4 insertions(+), 7 deletions(-)
kernel/livepatch/core.c +4 -7
index 6a137e1..8ca8a0e 100644
@@ -408,26 +408,23 @@ static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr,
 {
 	struct klp_patch *patch;
 	int ret;
-	unsigned long val;
+	bool enabled;
 
-	ret = kstrtoul(buf, 10, &val);
+	ret = kstrtobool(buf, &enabled);
 	if (ret)
 		return -EINVAL;
 
-	if (val > 1)
-		return -EINVAL;
-
 	patch = container_of(kobj, struct klp_patch, kobj);
 
 	mutex_lock(&klp_mutex);
 
-	if (patch->enabled == val) {
+	if (patch->enabled == enabled) {
 		/* already in requested state */
 		ret = -EINVAL;
 		goto err;
 	}
 
-	if (val) {
+	if (enabled) {
 		ret = __klp_enable_patch(patch);
 		if (ret)
 			goto err;
Signature · 1 line
2.7.4
#45 lore raw

PATCH v3 12/15 livepatch: store function sizes

In reply to Josh Poimboeuf

For the consistency model we'll need to know the sizes of the old and new functions to determine if they're on the stacks of any tasks.

---
 include/linux/livepatch.h |  3 +++
 kernel/livepatch/core.c   | 16 ++++++++++++++++
 2 files changed, 19 insertions(+)
include/linux/livepatch.h +3 -0
index 1e2eb91..1a5a93c 100644
@@ -37,6 +37,8 @@
  * @old_addr:	the address of the function being patched
  * @kobj:	kobject for sysfs resources
  * @stack_node:	list node for klp_ops func_stack list
+ * @old_size:	size of the old function
+ * @new_size:	size of the new function
  * @patched:	the func has been added to the klp_ops list
  */
 struct klp_func {
@@ -56,6 +58,7 @@ struct klp_func {
 	unsigned long old_addr;
 	struct kobject kobj;
 	struct list_head stack_node;
+	unsigned long old_size, new_size;
 	bool patched;
 };
 
kernel/livepatch/core.c +16 -0
index 8ca8a0e..fc160c6 100644
@@ -584,6 +584,22 @@ static int klp_init_object_loaded(struct klp_patch *patch,
 					     &func->old_addr);
 		if (ret)
 			return ret;
+
+		ret = kallsyms_lookup_size_offset(func->old_addr,
+						  &func->old_size, NULL);
+		if (!ret) {
+			pr_err("kallsyms size lookup failed for '%s'\n",
+			       func->old_name);
+			return -ENOENT;
+		}
+
+		ret = kallsyms_lookup_size_offset((unsigned long)func->new_func,
+						  &func->new_size, NULL);
+		if (!ret) {
+			pr_err("kallsyms size lookup failed for '%s' replacement\n",
+			       func->old_name);
+			return -ENOENT;
+		}
 	}
 
 	return 0;
Signature · 1 line
2.7.4
#49 lore raw

PATCH v3 13/15 livepatch: change to a per-task consistency model

In reply to Josh Poimboeuf

Change livepatch to use a basic per-task consistency model. This is the foundation which will eventually enable us to patch those ~10% of security patches which change function or data semantics. This is the biggest remaining piece needed to make livepatch more generally useful.

This code stems from the design proposal made by Vojtech [1] in November 2014. It's a hybrid of kGraft and kpatch: it uses kGraft's per-task consistency and syscall barrier switching combined with kpatch's stack trace switching. There are also a number of fallback options which make it quite flexible.

Patches are applied on a per-task basis, when the task is deemed safe to switch over. When a patch is enabled, livepatch enters into a transition state where tasks are converging to the patched state. Usually this transition state can complete in a few seconds. The same sequence occurs when a patch is disabled, except the tasks converge from the patched state to the unpatched state.

An interrupt handler inherits the patched state of the task it interrupts. The same is true for forked tasks: the child inherits the patched state of the parent.

Livepatch uses several complementary approaches to determine when it's safe to patch tasks:

1. The first and most effective approach is stack checking of sleeping tasks. 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 of the tasks on the first try. Otherwise it'll keep trying periodically. This option is only available if the architecture has reliable stacks (HAVE_RELIABLE_STACKTRACE).

2. The second approach, if needed, is kernel exit switching. A task is switched when it returns to user space from a system call, a user space IRQ, or a signal. It's useful in the following cases:

a) Patching I/O-bound user tasks which are sleeping on an affected function. In this case you have to send SIGSTOP and SIGCONT to force it to exit the kernel and be patched.
b) Patching CPU-bound user tasks. If the task is highly CPU-bound then it will get patched the next time it gets interrupted by an IRQ.
c) In the future it could be useful for applying patches for architectures which don't yet have HAVE_RELIABLE_STACKTRACE. In this case you would have to signal most of the tasks on the system. However this isn't supported yet because there's currently no way to patch kthreads without HAVE_RELIABLE_STACKTRACE.

3. For idle "swapper" tasks, since they don't ever exit the kernel, they instead have a klp_update_patch_state() call in the idle loop which allows them to be patched before the CPU enters the idle state.

(Note there's not yet such an approach for kthreads.)

All the above approaches may be skipped by setting the 'immediate' flag in the 'klp_patch' struct, which will disable per-task consistency and patch all tasks immediately. This can be useful if the patch doesn't change any function or data semantics. Note that, even with this flag set, it's possible that some tasks may still be running with an old version of the function, until that function returns.

There's also an 'immediate' flag in the 'klp_func' struct which allows you to specify that certain functions in the patch can be applied without per-task consistency. This might be useful if you want to patch a common function like schedule(), and the function change doesn't need consistency but the rest of the patch does.

For architectures which don't have HAVE_RELIABLE_STACKTRACE, the user must set patch->immediate which causes all tasks to be patched immediately. This option should be used with care, only when the patch doesn't change any function or data semantics.

In the future, architectures which don't have HAVE_RELIABLE_STACKTRACE may be allowed to use per-task consistency if we can come up with another way to patch kthreads.

The /sys/kernel/livepatch/<patch>/transition file shows whether a patch is in transition. Only a single patch (the topmost patch on the stack) can be in transition at a given time. A patch can remain in transition indefinitely, if any of the tasks are stuck in the initial patch state.

A transition can be reversed and effectively canceled by writing the opposite value to the /sys/kernel/livepatch/<patch>/enabled file while the transition is in progress. Then all the tasks will attempt to converge back to the original patch state.

[1] https://lkml.kernel.org/r/[email protected]

---
 Documentation/ABI/testing/sysfs-kernel-livepatch |   8 +
 Documentation/livepatch/livepatch.txt            | 127 +++++-
 include/linux/init_task.h                        |   9 +
 include/linux/livepatch.h                        |  40 +-
 include/linux/sched.h                            |   3 +
 kernel/fork.c                                    |   3 +
 kernel/livepatch/Makefile                        |   2 +-
 kernel/livepatch/core.c                          | 123 +++++-
 kernel/livepatch/patch.c                         |  50 ++-
 kernel/livepatch/patch.h                         |   1 +
 kernel/livepatch/transition.c                    | 479 +++++++++++++++++++++++
 kernel/livepatch/transition.h                    |  14 +
 kernel/sched/idle.c                              |   4 +
 samples/livepatch/livepatch-sample.c             |   7 +
 14 files changed, 827 insertions(+), 43 deletions(-)
 create mode 100644 kernel/livepatch/transition.c
 create mode 100644 kernel/livepatch/transition.h
Documentation/ABI/testing/sysfs-kernel-livepatch +8 -0
index da87f43..24b6570 100644
@@ -25,6 +25,14 @@ Description:
 		code is currently applied.  Writing 0 will disable the patch
 		while writing 1 will re-enable the patch.
 
+What:		/sys/kernel/livepatch/<patch>/transition
+Date:		May 2016
+KernelVersion:	4.11.0
+Contact:	[email protected]
+Description:
+		An attribute which indicates whether the patch is currently in
+		transition.
+
 What:		/sys/kernel/livepatch/<patch>/<object>
 Date:		Nov 2014
 KernelVersion:	3.19.0
Documentation/livepatch/livepatch.txt +108 -19

157 lines not on this page · raw message

include/linux/init_task.h +9 -0
index 325f649..25f0360 100644
@@ -14,6 +14,7 @@
 #include <linux/rbtree.h>
 #include <net/net_namespace.h>
 #include <linux/sched/rt.h>
+#include <linux/livepatch.h>
 
 #include <asm/thread_info.h>
 
@@ -185,6 +186,13 @@ extern struct task_group root_task_group;
 # define INIT_KASAN(tsk)
 #endif
 
+#ifdef CONFIG_LIVEPATCH
+# define INIT_LIVEPATCH(tsk)						\
+	.patch_state = KLP_UNDEFINED,
+#else
+# define INIT_LIVEPATCH(tsk)
+#endif
+
 #ifdef CONFIG_THREAD_INFO_IN_TASK
 # define INIT_TASK_TI(tsk)			\
 	.thread_info = INIT_THREAD_INFO(tsk),	\
@@ -271,6 +279,7 @@ extern struct task_group root_task_group;
 	INIT_VTIME(tsk)							\
 	INIT_NUMA_BALANCING(tsk)					\
 	INIT_KASAN(tsk)							\
+	INIT_LIVEPATCH(tsk)						\
 }
 
 
include/linux/livepatch.h +39 -1
index 1a5a93c..8e06fe5 100644
@@ -28,18 +28,40 @@
 
 #include <asm/livepatch.h>
 
+/* task patch states */
+#define KLP_UNDEFINED	-1
+#define KLP_UNPATCHED	 0
+#define KLP_PATCHED	 1
+
 /**
  * struct klp_func - function structure for live patching
  * @old_name:	name of the function to be patched
  * @new_func:	pointer to the patched function code
  * @old_sympos: a hint indicating which symbol position the old function
  *		can be found (optional)
+ * @immediate:  patch the func immediately, bypassing backtrace safety checks
  * @old_addr:	the address of the function being patched
  * @kobj:	kobject for sysfs resources
  * @stack_node:	list node for klp_ops func_stack list
  * @old_size:	size of the old function
  * @new_size:	size of the new function
  * @patched:	the func has been added to the klp_ops list
+ * @transition:	the func is currently being applied or reverted
+ *
+ * The patched and transition variables define the func's patching state.  When
+ * patching, a func is always in one of the following states:
+ *
+ *   patched=0 transition=0: unpatched
+ *   patched=0 transition=1: unpatched, temporary starting state
+ *   patched=1 transition=1: patched, may be visible to some tasks
+ *   patched=1 transition=0: patched, visible to all tasks
+ *
+ * And when unpatching, it goes in the reverse order:
+ *
+ *   patched=1 transition=0: patched, visible to all tasks
+ *   patched=1 transition=1: patched, may be visible to some tasks
+ *   patched=0 transition=1: unpatched, temporary ending state
+ *   patched=0 transition=0: unpatched
  */
 struct klp_func {
 	/* external */
@@ -53,6 +75,7 @@ struct klp_func {
 	 * in kallsyms for the given object is used.
 	 */
 	unsigned long old_sympos;
+	bool immediate;
 
 	/* internal */
 	unsigned long old_addr;
@@ -60,6 +83,7 @@ struct klp_func {
 	struct list_head stack_node;
 	unsigned long old_size, new_size;
 	bool patched;
+	bool transition;
 };
 
 /**
@@ -86,6 +110,7 @@ struct klp_object {
  * struct klp_patch - patch structure for live patching
  * @mod:	reference to the live patch module
  * @objs:	object entries for kernel objects to be patched
+ * @immediate:  patch all funcs immediately, bypassing safety mechanisms
  * @list:	list node for global list of registered patches
  * @kobj:	kobject for sysfs resources
  * @enabled:	the patch is enabled (but operation may be incomplete)
@@ -94,6 +119,7 @@ struct klp_patch {
 	/* external */
 	struct module *mod;
 	struct klp_object *objs;
+	bool immediate;
 
 	/* internal */
 	struct list_head list;
@@ -121,15 +147,27 @@ void arch_klp_init_object_loaded(struct klp_patch *patch,
 int klp_module_coming(struct module *mod);
 void klp_module_going(struct module *mod);
 
-static inline bool klp_patch_pending(struct task_struct *task) { return false; }
+void klp_copy_process(struct task_struct *child);
 void klp_update_patch_state(struct task_struct *task);
 
+static inline bool klp_patch_pending(struct task_struct *task)
+{
+	return test_tsk_thread_flag(task, TIF_PATCH_PENDING);
+}
+
+static inline bool klp_have_reliable_stack(void)
+{
+	return IS_ENABLED(CONFIG_STACKTRACE) &&
+	       IS_ENABLED(CONFIG_HAVE_RELIABLE_STACKTRACE);
+}
+
 #else /* !CONFIG_LIVEPATCH */
 
 static inline int klp_module_coming(struct module *mod) { return 0; }
 static inline void klp_module_going(struct module *mod) {}
 static inline bool klp_patch_pending(struct task_struct *task) { return false; }
 static inline void klp_update_patch_state(struct task_struct *task) {}
+static inline void klp_copy_process(struct task_struct *child) {}
 
 #endif /* CONFIG_LIVEPATCH */
 
include/linux/sched.h +3 -0
index 1531c48..1b2b234 100644
@@ -1988,6 +1988,9 @@ struct task_struct {
 	/* A live task holds one reference. */
 	atomic_t stack_refcount;
 #endif
+#ifdef CONFIG_LIVEPATCH
+	int patch_state;
+#endif
 /* CPU-specific state of this task */
 	struct thread_struct thread;
 /*
kernel/fork.c +3 -0
index 8f63bf9..3fadbbd 100644
@@ -76,6 +76,7 @@
 #include <linux/compiler.h>
 #include <linux/sysctl.h>
 #include <linux/kcov.h>
+#include <linux/livepatch.h>
 
 #include <asm/pgtable.h>
 #include <asm/pgalloc.h>
@@ -1759,6 +1760,8 @@ static __latent_entropy struct task_struct *copy_process(
 		p->parent_exec_id = current->self_exec_id;
 	}
 
+	klp_copy_process(p);
+
 	spin_lock(&current->sighand->siglock);
 
 	/*
kernel/livepatch/Makefile +1 -1
index e136dad..2b8bdb1 100644
@@ -1,3 +1,3 @@
 obj-$(CONFIG_LIVEPATCH) += livepatch.o
 
-livepatch-objs := core.o patch.o
+livepatch-objs := core.o patch.o transition.o
kernel/livepatch/core.c +102 -21

217 lines not on this page · raw message

kernel/livepatch/patch.c +49 -1

73 lines not on this page · raw message

kernel/livepatch/patch.h +1 -0
index 2d0cce0..0db2271 100644
@@ -28,5 +28,6 @@ struct klp_ops *klp_find_ops(unsigned long old_addr);
 
 int klp_patch_object(struct klp_object *obj);
 void klp_unpatch_object(struct klp_object *obj);
+void klp_unpatch_objects(struct klp_patch *patch);
 
 #endif /* _LIVEPATCH_PATCH_H */
kernel/livepatch/transition.c new file +479 -0

479 lines not on this page · raw message

kernel/livepatch/transition.h new file +14 -0
new file mode 100644
index 0000000..5191b96
@@ -0,0 +1,14 @@
+#ifndef _LIVEPATCH_TRANSITION_H
+#define _LIVEPATCH_TRANSITION_H
+
+#include <linux/livepatch.h>
+
+extern struct klp_patch *klp_transition_patch;
+
+void klp_init_transition(struct klp_patch *patch, int state);
+void klp_start_transition(void);
+void klp_reverse_transition(void);
+bool klp_try_complete_transition(void);
+void klp_complete_transition(void);
+
+#endif /* _LIVEPATCH_TRANSITION_H */
kernel/sched/idle.c +4 -0
index 6a4bae0..a8b3f1a 100644
@@ -9,6 +9,7 @@
 #include <linux/mm.h>
 #include <linux/stackprotector.h>
 #include <linux/suspend.h>
+#include <linux/livepatch.h>
 
 #include <asm/tlb.h>
 
@@ -264,6 +265,9 @@ static void do_idle(void)
 
 	sched_ttwu_pending();
 	schedule_preempt_disabled();
+
+	if (unlikely(klp_patch_pending(current)))
+		klp_update_patch_state(current);
 }
 
 bool cpu_in_idle(unsigned long pc)
samples/livepatch/livepatch-sample.c +7 -0
index e34f871..bb61c65 100644
@@ -17,6 +17,8 @@
  * along with this program; if not, see <http://www.gnu.org/licenses/>.
  */
 
+#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+
 #include <linux/module.h>
 #include <linux/kernel.h>
 #include <linux/livepatch.h>
@@ -69,6 +71,11 @@ static int livepatch_init(void)
 {
 	int ret;
 
+	if (!klp_have_reliable_stack() && !patch.immediate) {
+		pr_notice("disabling consistency model!\n");
+		patch.immediate = true;
+	}
+
 	ret = klp_register_patch(&patch);
 	if (ret)
 		return ret;
Signature · 1 line
2.7.4
#67 lore raw

PATCH v3 14/15 livepatch: add /proc/<pid>/patch_state

In reply to Josh Poimboeuf

Expose the per-task patch state value so users can determine which tasks are holding up completion of a patching operation.

---
 Documentation/filesystems/proc.txt | 18 ++++++++++++++++++
 fs/proc/base.c                     | 15 +++++++++++++++
 2 files changed, 33 insertions(+)
Documentation/filesystems/proc.txt +18 -0
index 72624a1..85c501b 100644
@@ -44,6 +44,7 @@ Table of Contents
   3.8   /proc/<pid>/fdinfo/<fd> - Information about opened file
   3.9   /proc/<pid>/map_files - Information about memory mapped files
   3.10  /proc/<pid>/timerslack_ns - Task timerslack value
+  3.11	/proc/<pid>/patch_state - Livepatch patch operation state
 
   4	Configuring procfs
   4.1	Mount options
@@ -1886,6 +1887,23 @@ Valid values are from 0 - ULLONG_MAX
 An application setting the value must have PTRACE_MODE_ATTACH_FSCREDS level
 permissions on the task specified to change its timerslack_ns value.
 
+3.11	/proc/<pid>/patch_state - Livepatch patch operation state
+-----------------------------------------------------------------
+When CONFIG_LIVEPATCH is enabled, this file displays the value of the
+patch state for the task.
+
+A value of '-1' indicates that no patch is in transition.
+
+A value of '0' indicates that a patch is in transition and the task is
+unpatched.  If the patch is being enabled, then the task hasn't been
+patched yet.  If the patch is being disabled, then the task has already
+been unpatched.
+
+A value of '1' indicates that a patch is in transition and the task is
+patched.  If the patch is being enabled, then the task has already been
+patched.  If the patch is being disabled, then the task hasn't been
+unpatched yet.
+
 
 ------------------------------------------------------------------------------
 Configuring procfs
fs/proc/base.c +15 -0
index 5ea8363..2e1e012 100644
@@ -2841,6 +2841,15 @@ static int proc_pid_personality(struct seq_file *m, struct pid_namespace *ns,
 	return err;
 }
 
+#ifdef CONFIG_LIVEPATCH
+static int proc_pid_patch_state(struct seq_file *m, struct pid_namespace *ns,
+				struct pid *pid, struct task_struct *task)
+{
+	seq_printf(m, "%d\n", task->patch_state);
+	return 0;
+}
+#endif /* CONFIG_LIVEPATCH */
+
 /*
  * Thread groups
  */
@@ -2940,6 +2949,9 @@ static const struct pid_entry tgid_base_stuff[] = {
 	REG("timers",	  S_IRUGO, proc_timers_operations),
 #endif
 	REG("timerslack_ns", S_IRUGO|S_IWUGO, proc_pid_set_timerslack_ns_operations),
+#ifdef CONFIG_LIVEPATCH
+	ONE("patch_state",  S_IRUSR, proc_pid_patch_state),
+#endif
 };
 
 static int proc_tgid_base_readdir(struct file *file, struct dir_context *ctx)
@@ -3320,6 +3332,9 @@ static const struct pid_entry tid_base_stuff[] = {
 	REG("projid_map", S_IRUGO|S_IWUSR, proc_projid_map_operations),
 	REG("setgroups",  S_IRUGO|S_IWUSR, proc_setgroups_operations),
 #endif
+#ifdef CONFIG_LIVEPATCH
+	ONE("patch_state",  S_IRUSR, proc_pid_patch_state),
+#endif
 };
 
 static int proc_tid_base_readdir(struct file *file, struct dir_context *ctx)
Signature · 1 line
2.7.4
#70 lore raw

PATCH v3 15/15 livepatch: allow removal of a disabled patch

In reply to Josh Poimboeuf

From: Miroslav Benes <[email protected]>

Currently we do not allow patch module to unload since there is no method to determine if a task is still running in the patched code.

The consistency model gives us the way because when the unpatching finishes we know that all tasks were marked as safe to call an original function. Thus every new call to the function calls the original code and at the same time no task can be somewhere in the patched code, because it had to leave that code to be marked as safe.

We can safely let the patch module go after that.

Completion is used for synchronization between module removal and sysfs infrastructure in a similar way to commit 942e443127e9 ("module: Fix mod->mkobj.kobj potentially freed too early").

Note that we still do not allow the removal for immediate model, that is no consistency model. The module refcount may increase in this case if somebody disables and enables the patch several times. This should not cause any harm.

With this change a call to try_module_get() is moved to __klp_enable_patch from klp_register_patch to make module reference counting symmetric (module_put() is in a patch disable path) and to allow to take a new reference to a disabled module when being enabled.

Also all kobject_put(&patch->kobj) calls are moved outside of klp_mutex lock protection to prevent a deadlock situation when klp_unregister_patch is called and sysfs directories are removed. There is no need to do the same for other kobject_put() callsites as we currently do not have their sysfs counterparts.

---
 Documentation/livepatch/livepatch.txt | 29 ++++---------
 include/linux/livepatch.h             |  3 ++
 kernel/livepatch/core.c               | 80 ++++++++++++++++++++++-------------
 kernel/livepatch/transition.c         | 12 +++++-
 samples/livepatch/livepatch-sample.c  |  1 -
 5 files changed, 72 insertions(+), 53 deletions(-)
Documentation/livepatch/livepatch.txt +9 -20
index f87e742..b0eaaf8 100644
@@ -265,8 +265,15 @@ section "Livepatch life-cycle" below for more details about these
 two operations.
 
 Module removal is only safe when there are no users of the underlying
-functions.  The immediate consistency model is not able to detect this;
-therefore livepatch modules cannot be removed. See "Limitations" below.
+functions. The immediate consistency model is not able to detect this. The
+code just redirects the functions at the very beginning and it does not
+check if the functions are in use. In other words, it knows when the
+functions get called but it does not know when the functions return.
+Therefore it cannot be decided when the livepatch module can be safely
+removed. This is solved by a hybrid consistency model. When the system is
+transitioned to a new patch state (patched/unpatched) it is guaranteed that
+no task sleeps or runs in the old code.
+
 
 5. Livepatch life-cycle
 =======================
@@ -437,24 +444,6 @@ The current Livepatch implementation has several limitations:
     There is work in progress to remove this limitation.
 
 
-  + Livepatch modules can not be removed.
-
-    The current implementation just redirects the functions at the very
-    beginning. It does not check if the functions are in use. In other
-    words, it knows when the functions get called but it does not
-    know when the functions return. Therefore it can not decide when
-    the livepatch module can be safely removed.
-
-    This will get most likely solved once a more complex consistency model
-    is supported. The idea is that a safe state for patching should also
-    mean a safe state for removing the patch.
-
-    Note that the patch itself might get disabled by writing zero
-    to /sys/kernel/livepatch/<patch>/enabled. It causes that the new
-    code will not longer get called. But it does not guarantee
-    that anyone is not sleeping anywhere in the new code.
-
-
   + Livepatch works reliably only when the dynamic ftrace is located at
     the very beginning of the function.
 
include/linux/livepatch.h +3 -0
index 8e06fe5..1959e52 100644
@@ -23,6 +23,7 @@
 
 #include <linux/module.h>
 #include <linux/ftrace.h>
+#include <linux/completion.h>
 
 #if IS_ENABLED(CONFIG_LIVEPATCH)
 
@@ -114,6 +115,7 @@ struct klp_object {
  * @list:	list node for global list of registered patches
  * @kobj:	kobject for sysfs resources
  * @enabled:	the patch is enabled (but operation may be incomplete)
+ * @finish:	for waiting till it is safe to remove the patch module
  */
 struct klp_patch {
 	/* external */
@@ -125,6 +127,7 @@ struct klp_patch {
 	struct list_head list;
 	struct kobject kobj;
 	bool enabled;
+	struct completion finish;
 };
 
 #define klp_for_each_object(patch, obj) \
kernel/livepatch/core.c +50 -30

161 lines not on this page · raw message

kernel/livepatch/transition.c +10 -2
index 4494fe6..dc950d5 100644
@@ -195,13 +195,21 @@ void klp_complete_transition(void)
 	struct klp_func *func;
 	struct task_struct *g, *task;
 	unsigned int cpu;
+	bool is_immediate = false;
 
 	if (klp_transition_patch->immediate)
 		goto done;
 
-	klp_for_each_object(klp_transition_patch, obj)
-		klp_for_each_func(obj, func)
+	klp_for_each_object(klp_transition_patch, obj) {
+		klp_for_each_func(obj, func) {
 			func->transition = false;
+			if (func->immediate)
+				is_immediate = true;
+		}
+	}
+
+	if (klp_target_state == KLP_UNPATCHED && !is_immediate)
+		module_put(klp_transition_patch->mod);
 
 	read_lock(&tasklist_lock);
 	for_each_process_thread(g, task) {
samples/livepatch/livepatch-sample.c +0 -1
index bb61c65..0625f38 100644
@@ -89,7 +89,6 @@ static int livepatch_init(void)
 
 static void livepatch_exit(void)
 {
-	WARN_ON(klp_disable_patch(&patch));
 	WARN_ON(klp_unregister_patch(&patch));
 }
 
Signature · 1 line
2.7.4
Acked-by on v3 4/15
#18 lore raw

Re: [PATCH v3 04/15] livepatch/x86: add TIF_PATCH_PENDING thread flag

In reply to Josh Poimboeuf
Quoted 9 lines · Josh Poimboeuf

Add the TIF_PATCH_PENDING thread flag to enable the new livepatch per-task consistency model for x86_64. The bit getting set indicates the thread has a pending patch which needs to be applied when the thread exits the kernel.

The bit is placed in the _TIF_ALLWORK_MASK macro, which results in exit_to_usermode_loop() calling klp_update_patch_state() when it's set.

#74 lore raw
In reply to Josh Poimboeuf
Quoted 5 lines · Josh Poimboeuf

Dusting the cobwebs off the consistency model again.  This is based on linux-next/master.

v1 was posted on 2015-02-09:

Quoted 8 lines

  https://lkml.kernel.org/r/[email protected]

v2 was posted on 2016-04-28:

  https://lkml.kernel.org/r/[email protected]

The biggest issue from v2 was finding a decent way to detect preemption and page faults on the stack of a sleeping task.

Could you please elaborate on this? Preemption of a sleeping task and faults as in the future (time) preemption and faults?

Balbir Singh.

#75 lore raw
Quoted 15 lines · Balbir Singh
Quoted 5 lines · Josh Poimboeuf

Dusting the cobwebs off the consistency model again.  This is based on linux-next/master.

v1 was posted on 2015-02-09:

Quoted 8 lines

  https://lkml.kernel.org/r/[email protected]

v2 was posted on 2016-04-28:

  https://lkml.kernel.org/r/[email protected]

The biggest issue from v2 was finding a decent way to detect preemption and page faults on the stack of a sleeping task.

Quoted 2 lines

Could you please elaborate on this? Preemption of a sleeping task and faults as in the future (time) preemption and faults?

The normal way for a task to go to sleep is to call schedule(). objtool ensures the stack trace is reliable in that case, by making sure that all functions save the frame pointer on the stack before calling out to another function.

But a task can also go to sleep in a few other ways. One way is by preemption, where an interrupt handler interrupts the task and calls preempt_schedule_irq(). Another way is by a page fault exception. In both cases, there's no guarantee that the interrupted function saved the frame pointer on the stack beforehand. So the stack trace might be unreliable. Fortunately, interrupts and exceptions leave evidence behind on the stack. So when walking the stack of a sleeping task, we can detect when an IRQ or exception occurred, and consider such a stack unreliable.

Signature · 1 line
Josh
#76 lore raw
Quoted 19 lines · Josh Poimboeuf
Quoted 10 lines · Balbir Singh
Quoted 9 lines · Josh Poimboeuf

Dusting the cobwebs off the consistency model again. This is based on linux-next/master.

v1 was posted on 2015-02-09:

https://lkml.kernel.org/r/[email protected]

v2 was posted on 2016-04-28:

Quoted 7 lines
Quoted 4 lines

https://lkml.kernel.org/r/[email protected]

The biggest issue from v2 was finding a decent way to detect preemption and page faults on the stack of a sleeping task.

Could you please elaborate on this? Preemption of a sleeping task and faults as in the future (time) preemption and faults?

Quoted 8 lines

The normal way for a task to go to sleep is to call schedule(). objtool ensures the stack trace is reliable in that case, by making sure that all functions save the frame pointer on the stack before calling out to another function.

But a task can also go to sleep in a few other ways. One way is by preemption, where an interrupt handler interrupts the task and calls preempt_schedule_irq().

It's preempted, not sleeping. It's on_rq but not on_cpu.

Another way is by a page fault exception. In

Quoted 7 lines

both cases, there's no guarantee that the interrupted function saved the frame pointer on the stack beforehand. So the stack trace might be unreliable. Fortunately, interrupts and exceptions leave evidence behind on the stack. So when walking the stack of a sleeping task, we can detect when an IRQ or exception occurred, and consider such a stack unreliable.

Thanks for the explanation. I presume a whole lot of this is arch specific code? I'll look at the patches as well

Balbir

#77 lore raw
Quoted 27 lines · Balbir Singh
Quoted 24 lines · Josh Poimboeuf
Quoted 10 lines · Balbir Singh
Quoted 9 lines · Josh Poimboeuf

Dusting the cobwebs off the consistency model again. This is based on linux-next/master.

v1 was posted on 2015-02-09:

https://lkml.kernel.org/r/[email protected]

v2 was posted on 2016-04-28:

Quoted 7 lines
Quoted 4 lines

https://lkml.kernel.org/r/[email protected]

The biggest issue from v2 was finding a decent way to detect preemption and page faults on the stack of a sleeping task.

Could you please elaborate on this? Preemption of a sleeping task and faults as in the future (time) preemption and faults?

The normal way for a task to go to sleep is to call schedule(). objtool ensures the stack trace is reliable in that case, by making sure that all functions save the frame pointer on the stack before calling out to another function.

Quoted 5 lines
Quoted 3 lines

But a task can also go to sleep in a few other ways. One way is by preemption, where an interrupt handler interrupts the task and calls preempt_schedule_irq().

It's preempted, not sleeping. It's on_rq but not on_cpu.

You're right, I used the word "sleeping" when I meant "not currently executing on a CPU". (Peter Z also pointed that out.)

Quoted 11 lines

Another way is by a page fault exception. In

Quoted 7 lines

both cases, there's no guarantee that the interrupted function saved the frame pointer on the stack beforehand. So the stack trace might be unreliable. Fortunately, interrupts and exceptions leave evidence behind on the stack. So when walking the stack of a sleeping task, we can detect when an IRQ or exception occurred, and consider such a stack unreliable.

Thanks for the explanation. I presume a whole lot of this is arch specific code? I'll look at the patches as well

Most of the new livepatch code is arch-independent, but the consistency model part of it (i.e., !klp_patch.immediate) is currently only supported by x86_64.

For adding support for other architectures, there are a few options:

1) Add CONFIG_HAVE_RELIABLE_STACKTRACE. This means porting objtool, and for non-DWARF unwinders, also making sure there's a way for the stack tracing code to detect interrupts on the stack.

2) Alternatively, figure out a way to patch kthreads without stack checking. If all kthreads sleep in the same place, then we can designate that place as a patching point. I think Petr M has been working on that? In that case, arches without HAVE_RELIABLE_STACKTRACE would still be able to use the non-stack-checking parts of the consistency model:

a) patching user tasks when they cross the kernel/user space boundary; and

b) patching kthreads and idle tasks at their designated patch points.

This option isn't as good as option 1 because it requires signaling most of the tasks to patch them. But it could still be a good backup option for those architectures which don't have reliable stack traces yet.

In the meantime, other architectures can keep today's behavior by setting klp_patch.immediate to true.

Signature · 1 line
Josh
maintainer
#2 lore raw

Re: [PATCH v3 01/15] stacktrace/x86: add function for detecting reliable stack traces

In reply to Josh Poimboeuf
Quoted 7 lines · Josh Poimboeuf

For live patching and possibly other use cases, a stack trace is only useful if it can be assured that it's completely reliable. Add a new save_stack_trace_tsk_reliable() function to achieve that.

Scenarios which indicate that a stack trace may be unreliable:

- running task

It seems that this has to be enforced by save_stack_trace_tsk_reliable() caller. It should be mentioned in the function description.

Quoted 1 line

- interrupt stack

I guess that it is detected by saved regs on the stack. And it covers also dynamic changes like kprobes. Do I get it correctly, please?

What about ftrace? Is ftrace without regs safe and detected?

Quoted 1 line

- preemption

I wonder if some very active kthreads might almost always be preempted using irq in preemptive kernel. Then they block the conversion with the non-reliable stacks. Have you noticed such problems, please?

Quoted 2 lines

- corrupted stack data
- stack grows the wrong way

This is detected in unwind_next_frame() and passed via state->error. Am I right?

Quoted 23 lines

- stack walk doesn't reach the bottom
- user didn't provide a large enough entries array

Also add CONFIG_HAVE_RELIABLE_STACKTRACE so arch-independent code can determine at build time whether the function is implemented.

arch/x86/kernel/stacktrace.c +9 -0
index 0653788..3e0cf5e 100644
@@ -74,6 +74,64 @@ void save_stack_trace_tsk(struct task_struct *tsk, struct stack_trace *trace)
 }
 EXPORT_SYMBOL_GPL(save_stack_trace_tsk);
 
+#ifdef CONFIG_HAVE_RELIABLE_STACKTRACE
+static int __save_stack_trace_reliable(struct stack_trace *trace,
+				       struct task_struct *task)
+{
+	struct unwind_state state;
+	struct pt_regs *regs;
+	unsigned long addr;
+
+	for (unwind_start(&state, task, NULL, NULL); !unwind_done(&state);

arch/x86/kernel/stacktrace.c void save_stack_trace_tsk(struct task_struct *tsk, struct stack_trace *trace) · line 95

Quoted 10 lines
arch/x86/kernel/stacktrace.c +10 -0
+	     unwind_next_frame(&state)) {
+
+		regs = unwind_get_entry_regs(&state);
+		if (regs) {
+			/*
+			 * Preemption and page faults on the stack can make
+			 * frame pointers unreliable.
+			 */
+			if (!user_mode(regs))
+				return -1;

By other words, it we find regs on the stack, it almost always mean a non-reliable stack. The only exception is when we are in the userspace mode. Do I get it correctly, please?

Quoted 12 lines
arch/x86/kernel/stacktrace.c +12 -0
+
+			/*
+			 * This frame contains the (user mode) pt_regs at the
+			 * end of the stack.  Finish the unwind.
+			 */
+			unwind_next_frame(&state);
+			break;
+		}
+
+		addr = unwind_get_return_address(&state);
+		if (!addr || save_stack_address(trace, addr, false))
+			return -1;

arch/x86/kernel/stacktrace.c void save_stack_trace_tsk(struct task_struct *tsk, struct stack_trace *trace) · line 117

Quoted 10 lines
arch/x86/kernel/stacktrace.c +10 -0
+	}
+
+	if (!unwind_done(&state) || unwind_error(&state))
+		return -1;
+
+	if (trace->nr_entries < trace->max_entries)
+		trace->entries[trace->nr_entries++] = ULONG_MAX;
+
+	return 0;
+}

Great work! I am surprised that it looks so straightforward.

I still have to think and investigate it more. But it looks very promissing.

Best Regards,
Petr

maintainer Reviewed-by on v3 2/15
#10 lore raw

Re: [PATCH v3 02/15] x86/entry: define _TIF_ALLWORK_MASK flags explicitly

In reply to Josh Poimboeuf
Quoted 16 lines · Josh Poimboeuf

The _TIF_ALLWORK_MASK macro automatically includes the least-significant 16 bits of the thread_info flags, which is less than obvious and tends to create confusion and surprises when reading or modifying the code.

Define the flags explicitly.

---
 arch/x86/include/asm/thread_info.h | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)
arch/x86/include/asm/thread_info.h +0 -0
index ad6f5eb0..1fe6043 100644

arch/x86/include/asm/thread_info.h struct thread_info { · line 76

Quoted 4 lines
arch/x86/include/asm/thread_info.h +0 -1
@@ -73,9 +73,6 @@ struct thread_info {
  * thread information flags
  * - these are process state flags that various assembly files
  *   may need to access
- * - pending work-to-be-done flags are in LSW

Yup, this is not true because also some flags from the most significant bits are in the _TIF_ALLWORK_MASK.

Quoted 6 lines
arch/x86/include/asm/thread_info.h +0 -2
- * - other flags in MSW
- * Warning: layout of LSW is hardcoded in entry.S
  */
 #define TIF_SYSCALL_TRACE	0	/* syscall trace active */
 #define TIF_NOTIFY_RESUME	1	/* callback before returning to user */

arch/x86/include/asm/thread_info.h struct thread_info { · line 136

Quoted 9 lines
arch/x86/include/asm/thread_info.h +4 -2
@@ -133,8 +130,10 @@ struct thread_info {
 
 /* work to do on any return to user space */
 #define _TIF_ALLWORK_MASK						\
-	((0x0000FFFF & ~_TIF_SECCOMP) | _TIF_SYSCALL_TRACEPOINT |	\
-	_TIF_NOHZ)
+	(_TIF_SYSCALL_TRACE | _TIF_NOTIFY_RESUME | _TIF_SIGPENDING |	\
+	 _TIF_SINGLESTEP | _TIF_NEED_RESCHED | _TIF_SYSCALL_EMU |	\
+	 _TIF_SYSCALL_AUDIT | _TIF_USER_RETURN_NOTIFY | _TIF_UPROBE |	\
+	 _TIF_SYSCALL_TRACEPOINT | _TIF_NOHZ)

All flags are sorted by the number except for
_TIF_SINGLESTEP and _TIF_NEED_RESCHED ;-)

The patch does not change the existing behavior. The same existing flags are listed.

Best Regards,
Petr

maintainer Reviewed-by on v3 3/15
#15 lore raw

Re: [PATCH v3 03/15] livepatch: temporary stubs for klp_patch_pending() and klp_update_patch_state()

In reply to Josh Poimboeuf
Quoted 15 lines · Josh Poimboeuf

Create temporary stubs for klp_patch_pending() and klp_update_patch_state() so we can add TIF_PATCH_PENDING to different architectures in separate patches without breaking build bisectability.

---
 include/linux/livepatch.h | 7 ++++++-
 kernel/livepatch/core.c   | 3 +++
 2 files changed, 9 insertions(+), 1 deletion(-)
include/linux/livepatch.h +0 -0
index 9072f04..60558d8 100644

include/linux/livepatch.h void arch_klp_init_object_loaded(struct klp_patch *patch, · line 126

Quoted 4 lines
include/linux/livepatch.h +1 -0
@@ -123,10 +123,15 @@ void arch_klp_init_object_loaded(struct klp_patch *patch,
 int klp_module_coming(struct module *mod);
 void klp_module_going(struct module *mod);
 
+static inline bool klp_patch_pending(struct task_struct *task) { return false; }

I was curious about this. It is implemented correctly in the 13th patch and it is never used until 13th patch.

include/linux/livepatch.h void arch_klp_init_object_loaded(struct klp_patch *patch, · line 127

Quoted 1 line
include/linux/livepatch.h +1 -0
+void klp_update_patch_state(struct task_struct *task);

It seems that the stub for this function is enough.

Well, the extra function is just a cosmetic problem. If it could be fixed, it would be great. But the patch makes sense:

Best Regards,
Petr

maintainer Reviewed-by on v3 4/15
#19 lore raw

Re: [PATCH v3 04/15] livepatch/x86: add TIF_PATCH_PENDING thread flag

In reply to Josh Poimboeuf
Quoted 9 lines · Josh Poimboeuf

Add the TIF_PATCH_PENDING thread flag to enable the new livepatch per-task consistency model for x86_64. The bit getting set indicates the thread has a pending patch which needs to be applied when the thread exits the kernel.

The bit is placed in the _TIF_ALLWORK_MASK macro, which results in exit_to_usermode_loop() calling klp_update_patch_state() when it's set.

Best Regards,
Petr

maintainer Reviewed-by on v3 5/15
#23 lore raw

Re: [PATCH v3 05/15] livepatch/powerpc: add TIF_PATCH_PENDING thread flag

In reply to Josh Poimboeuf
Quoted 10 lines · Josh Poimboeuf

Add the TIF_PATCH_PENDING thread flag to enable the new livepatch per-task consistency model for powerpc. The bit getting set indicates the thread has a pending patch which needs to be applied when the thread exits the kernel.

The bit is included in the _TIF_USER_WORK_MASK macro so that do_notify_resume() and klp_update_patch_state() get called when the bit is set.

Best Regards,
Petr

maintainer Reviewed-by on v3 8/15
#30 lore raw

Re: [PATCH v3 08/15] livepatch: separate enabled and patched states

In reply to Josh Poimboeuf
Quoted 13 lines · Josh Poimboeuf

Once we have a consistency model, patches and their objects will be enabled and disabled at different times. For example, when a patch is disabled, its loaded objects' funcs can remain registered with ftrace indefinitely until the unpatching operation is complete and they're no longer in use.

It's less confusing if we give them different names: patches can be enabled or disabled; objects (and their funcs) can be patched or unpatched:

- Enabled means that a patch is logically enabled (but not necessarily fully applied).

Quoted 7 lines

- Patched means that an object's funcs are registered with ftrace and added to the klp_ops func stack.

Also, since these states are binary, represent them with booleans instead of ints.

Makes sense. The patch is pretty straightforward.

Best Regards,
Petr

maintainer Reviewed-by on v3 9/15
#34 lore raw

Re: [PATCH v3 09/15] livepatch: remove unnecessary object loaded check

In reply to Josh Poimboeuf
Quoted 5 lines · Josh Poimboeuf

klp_patch_object()'s callers already ensure that the object is loaded, so its call to klp_is_object_loaded() is unnecessary.

This will also make it possible to move the patching code into a separate file.

Fair enough.

Quoted 1 line

Best Regards,
Petr

maintainer Reviewed-by on v3 11/15
#42 lore raw

Re: [PATCH v3 11/15] livepatch: use kstrtobool() in enabled_store()

In reply to Josh Poimboeuf
Quoted 14 lines · Josh Poimboeuf

The sysfs enabled value is a boolean, so kstrtobool() is a better fit for parsing the input string since it does the range checking for us.

---
 kernel/livepatch/core.c | 11 ++++-------
 1 file changed, 4 insertions(+), 7 deletions(-)
kernel/livepatch/core.c +0 -0
index 6a137e1..8ca8a0e 100644

kernel/livepatch/core.c static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr, · line 415

Quoted 10 lines
kernel/livepatch/core.c +2 -2
@@ -408,26 +408,23 @@ static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr,
 {
 	struct klp_patch *patch;
 	int ret;
-	unsigned long val;
+	bool enabled;
 
-	ret = kstrtoul(buf, 10, &val);
+	ret = kstrtobool(buf, &enabled);
 	if (ret)
 		return -EINVAL;

I would return "ret" here. It is -EINVAL as well but... ;-)

Anyway, feel free to use:

Best Regards,
Petr

#3 lore raw

Re: [PATCH v3 01/15] stacktrace/x86: add function for detecting reliable stack traces

In reply to Petr Mladek
Quoted 11 lines · Petr Mladek
Quoted 7 lines · Josh Poimboeuf

For live patching and possibly other use cases, a stack trace is only useful if it can be assured that it's completely reliable. Add a new save_stack_trace_tsk_reliable() function to achieve that.

Scenarios which indicate that a stack trace may be unreliable:

- running task

It seems that this has to be enforced by save_stack_trace_tsk_reliable() caller. It should be mentioned in the function description.

Agreed.

Quoted 4 lines
Quoted 1 line

- interrupt stack

I guess that it is detected by saved regs on the stack. And it covers also dynamic changes like kprobes. Do I get it correctly, please?

Right.

Quoted 1 line

What about ftrace? Is ftrace without regs safe and detected?

Yes, it's safe because the mcount code does the right thing with respect to frame pointers. See save_mcount_regs().

Quoted 6 lines
Quoted 1 line

- preemption

I wonder if some very active kthreads might almost always be preempted using irq in preemptive kernel. Then they block the conversion with the non-reliable stacks. Have you noticed such problems, please?

I haven't seen such a case and I think it would be quite rare for a kthread to be CPU-bound like that.

Quoted 5 lines
Quoted 2 lines

- corrupted stack data
- stack grows the wrong way

This is detected in unwind_next_frame() and passed via state->error. Am I right?

Right. I'll add more details to the commit message for all of these.

Quoted 31 lines
Quoted 31 lines

- stack walk doesn't reach the bottom
- user didn't provide a large enough entries array

Also add CONFIG_HAVE_RELIABLE_STACKTRACE so arch-independent code can determine at build time whether the function is implemented.

arch/x86/kernel/stacktrace.c +15 -0
index 0653788..3e0cf5e 100644
@@ -74,6 +74,64 @@ void save_stack_trace_tsk(struct task_struct *tsk, struct stack_trace *trace)
 }
 EXPORT_SYMBOL_GPL(save_stack_trace_tsk);
 
+#ifdef CONFIG_HAVE_RELIABLE_STACKTRACE
+static int __save_stack_trace_reliable(struct stack_trace *trace,
+				       struct task_struct *task)
+{
+	struct unwind_state state;
+	struct pt_regs *regs;
+	unsigned long addr;
+
+	for (unwind_start(&state, task, NULL, NULL); !unwind_done(&state);
+	     unwind_next_frame(&state)) {
+
+		regs = unwind_get_entry_regs(&state);
+		if (regs) {
+			/*
+			 * Preemption and page faults on the stack can make
Quoted 8 lines

arch/x86/kernel/stacktrace.c void save_stack_trace_tsk(struct task_struct *tsk, struct stack_trace *trace) · line 95

Quoted 4 lines
arch/x86/kernel/stacktrace.c +4 -0
+			 * frame pointers unreliable.
+			 */
+			if (!user_mode(regs))
+				return -1;

By other words, it we find regs on the stack, it almost always mean a non-reliable stack. The only exception is when we are in the userspace mode. Do I get it correctly, please?

Right.

Quoted 30 lines
Quoted 12 lines
arch/x86/kernel/stacktrace.c +12 -0
+
+			/*
+			 * This frame contains the (user mode) pt_regs at the
+			 * end of the stack.  Finish the unwind.
+			 */
+			unwind_next_frame(&state);
+			break;
+		}
+
+		addr = unwind_get_return_address(&state);
+		if (!addr || save_stack_address(trace, addr, false))
+			return -1;

arch/x86/kernel/stacktrace.c void save_stack_trace_tsk(struct task_struct *tsk, struct stack_trace *trace) · line 117

Quoted 10 lines
arch/x86/kernel/stacktrace.c +10 -0
+	}
+
+	if (!unwind_done(&state) || unwind_error(&state))
+		return -1;
+
+	if (trace->nr_entries < trace->max_entries)
+		trace->entries[trace->nr_entries++] = ULONG_MAX;
+
+	return 0;
+}

Great work! I am surprised that it looks so straightforward.

I still have to think and investigate it more. But it looks very promissing.

Best Regards,
Petr

Signature · 1 line
Josh
#11 lore raw

Re: [PATCH v3 02/15] x86/entry: define _TIF_ALLWORK_MASK flags explicitly

In reply to Petr Mladek
Quoted 32 lines · Petr Mladek
Quoted 16 lines · Josh Poimboeuf

The _TIF_ALLWORK_MASK macro automatically includes the least-significant 16 bits of the thread_info flags, which is less than obvious and tends to create confusion and surprises when reading or modifying the code.

Define the flags explicitly.

---
 arch/x86/include/asm/thread_info.h | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)
arch/x86/include/asm/thread_info.h +0 -0
index ad6f5eb0..1fe6043 100644

arch/x86/include/asm/thread_info.h struct thread_info { · line 76

Quoted 4 lines
arch/x86/include/asm/thread_info.h +0 -1
@@ -73,9 +73,6 @@ struct thread_info {
  * thread information flags
  * - these are process state flags that various assembly files
  *   may need to access
- * - pending work-to-be-done flags are in LSW

Yup, this is not true because also some flags from the most significant bits are in the _TIF_ALLWORK_MASK.

Quoted 7 lines
arch/x86/include/asm/thread_info.h +0 -2
- * - other flags in MSW
- * Warning: layout of LSW is hardcoded in entry.S
  */
 #define TIF_SYSCALL_TRACE	0	/* syscall trace active */
 #define TIF_NOTIFY_RESUME	1	/* callback before returning to user */
@@ -133,8 +130,10 @@ struct thread_info {
 
Quoted 11 lines

arch/x86/include/asm/thread_info.h struct thread_info { · line 136

Quoted 8 lines
arch/x86/include/asm/thread_info.h +4 -2
 /* work to do on any return to user space */
 #define _TIF_ALLWORK_MASK						\
-	((0x0000FFFF & ~_TIF_SECCOMP) | _TIF_SYSCALL_TRACEPOINT |	\
-	_TIF_NOHZ)
+	(_TIF_SYSCALL_TRACE | _TIF_NOTIFY_RESUME | _TIF_SIGPENDING |	\
+	 _TIF_SINGLESTEP | _TIF_NEED_RESCHED | _TIF_SYSCALL_EMU |	\
+	 _TIF_SYSCALL_AUDIT | _TIF_USER_RETURN_NOTIFY | _TIF_UPROBE |	\
+	 _TIF_SYSCALL_TRACEPOINT | _TIF_NOHZ)

All flags are sorted by the number except for
_TIF_SINGLESTEP and _TIF_NEED_RESCHED ;-)

You're right, I'll swap them :-)

Quoted 8 lines

The patch does not change the existing behavior. The same existing flags are listed.

Best Regards,
Petr

Signature · 1 line
Josh
#16 lore raw

Re: [PATCH v3 03/15] livepatch: temporary stubs for klp_patch_pending() and klp_update_patch_state()

In reply to Petr Mladek
Quoted 19 lines · Petr Mladek
Quoted 18 lines · Josh Poimboeuf

Create temporary stubs for klp_patch_pending() and klp_update_patch_state() so we can add TIF_PATCH_PENDING to different architectures in separate patches without breaking build bisectability.

---
 include/linux/livepatch.h | 7 ++++++-
 kernel/livepatch/core.c   | 3 +++
 2 files changed, 9 insertions(+), 1 deletion(-)
include/linux/livepatch.h +0 -0
index 9072f04..60558d8 100644
@@ -123,10 +123,15 @@ void arch_klp_init_object_loaded(struct klp_patch *patch,
 int klp_module_coming(struct module *mod);
 void klp_module_going(struct module *mod);
 
Quoted 4 lines

include/linux/livepatch.h void arch_klp_init_object_loaded(struct klp_patch *patch, · line 126

Quoted 1 line
include/linux/livepatch.h +1 -0
+static inline bool klp_patch_pending(struct task_struct *task) { return false; }

I was curious about this. It is implemented correctly in the 13th patch and it is never used until 13th patch.

Yep, I'll move it to patch 13.

Quoted 13 lines

include/linux/livepatch.h void arch_klp_init_object_loaded(struct klp_patch *patch, · line 127

Quoted 2 lines
include/linux/livepatch.h +1 -0
+void klp_update_patch_state(struct task_struct *task);

It seems that the stub for this function is enough.

Well, the extra function is just a cosmetic problem. If it could be fixed, it would be great. But the patch makes sense:

Best Regards,
Petr

Signature · 1 line
Josh
#43 lore raw

Re: [PATCH v3 11/15] livepatch: use kstrtobool() in enabled_store()

In reply to Petr Mladek
Quoted 21 lines · Petr Mladek
Quoted 20 lines · Josh Poimboeuf

The sysfs enabled value is a boolean, so kstrtobool() is a better fit for parsing the input string since it does the range checking for us.

---
 kernel/livepatch/core.c | 11 ++++-------
 1 file changed, 4 insertions(+), 7 deletions(-)
kernel/livepatch/core.c +1 -1
index 6a137e1..8ca8a0e 100644
@@ -408,26 +408,23 @@ static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr,
 {
 	struct klp_patch *patch;
 	int ret;
-	unsigned long val;
+	bool enabled;
 
Quoted 6 lines

kernel/livepatch/core.c static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr, · line 415

Quoted 4 lines
kernel/livepatch/core.c +1 -1
-	ret = kstrtoul(buf, 10, &val);
+	ret = kstrtobool(buf, &enabled);
 	if (ret)
 		return -EINVAL;

I would return "ret" here. It is -EINVAL as well but... ;-)

That was a preexisting issue with the kstrtoul() return code, but I'll sneak your suggested change into this patch if nobody objects.

Quoted 6 lines

Anyway, feel free to use:

Best Regards,
Petr

Signature · 1 line
Josh
maintainer
#4 lore raw

Re: [PATCH v3 01/15] stacktrace/x86: add function for detecting reliable stack traces

In reply to Josh Poimboeuf

arch/x86/Kconfig config X86 · line 158

Quoted 9 lines · Josh Poimboeuf
arch/x86/Kconfig +1 -0
index 215612c..b4a6663 100644
@@ -155,6 +155,7 @@ config X86
 	select HAVE_PERF_REGS
 	select HAVE_PERF_USER_STACK_DUMP
 	select HAVE_REGS_AND_STACK_ACCESS_API
+	select HAVE_RELIABLE_STACKTRACE		if X86_64 && FRAME_POINTER && STACK_VALIDATION

Tests to measure possible performance penalty of frame pointers were done by Mel Gorman. The outcome was quite clear. There IS a measurable impact. The percentage depends on the workflow but I think it is safe to say that FP usually takes 5-10 percents.

If my understanding is correct there is no single culprit. Register pressure is definitely not a problem. We ran simple benchmarks while taking a register away from GCC (RBP or a common one). The impact is a combination of more cacheline pressure, more memory accesses and the fact that the kernel contains a lot of small functions.

Thus, I think that DWARF should be the way to go here.

Other than that the patch looks good to me.

Miroslav

maintainer Reviewed-by on v3 2/15
#12 lore raw

Re: [PATCH v3 02/15] x86/entry: define _TIF_ALLWORK_MASK flags explicitly

In reply to Josh Poimboeuf
Quoted 3 lines · Josh Poimboeuf

The _TIF_ALLWORK_MASK macro automatically includes the least-significant 16 bits of the thread_info flags, which is less than obvious and tends to create confusion and surprises when reading or modifying the code.

Yes.

Quoted 3 lines

Define the flags explicitly.

With _TIF_SINGLESTEP and _TIF_NEED_RESCHED swapped you can add my

Miroslav

Quoted 34 lines
---
 arch/x86/include/asm/thread_info.h | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)
arch/x86/include/asm/thread_info.h +4 -5
index ad6f5eb0..1fe6043 100644
@@ -73,9 +73,6 @@ struct thread_info {
  * thread information flags
  * - these are process state flags that various assembly files
  *   may need to access
- * - pending work-to-be-done flags are in LSW
- * - other flags in MSW
- * Warning: layout of LSW is hardcoded in entry.S
  */
 #define TIF_SYSCALL_TRACE	0	/* syscall trace active */
 #define TIF_NOTIFY_RESUME	1	/* callback before returning to user */
@@ -133,8 +130,10 @@ struct thread_info {
 
 /* work to do on any return to user space */
 #define _TIF_ALLWORK_MASK						\
-	((0x0000FFFF & ~_TIF_SECCOMP) | _TIF_SYSCALL_TRACEPOINT |	\
-	_TIF_NOHZ)
+	(_TIF_SYSCALL_TRACE | _TIF_NOTIFY_RESUME | _TIF_SIGPENDING |	\
+	 _TIF_SINGLESTEP | _TIF_NEED_RESCHED | _TIF_SYSCALL_EMU |	\
+	 _TIF_SYSCALL_AUDIT | _TIF_USER_RETURN_NOTIFY | _TIF_UPROBE |	\
+	 _TIF_SYSCALL_TRACEPOINT | _TIF_NOHZ)
 
 /* flags to check in __switch_to() */
 #define _TIF_WORK_CTXSW							\
Signature · 1 line
2.7.4
#5 lore raw

Re: [PATCH v3 01/15] stacktrace/x86: add function for detecting reliable stack traces

In reply to Miroslav Benes
Quoted 23 lines · Miroslav Benes

arch/x86/Kconfig config X86 · line 158

Quoted 9 lines · Josh Poimboeuf
arch/x86/Kconfig +1 -0
index 215612c..b4a6663 100644
@@ -155,6 +155,7 @@ config X86
 	select HAVE_PERF_REGS
 	select HAVE_PERF_USER_STACK_DUMP
 	select HAVE_REGS_AND_STACK_ACCESS_API
+	select HAVE_RELIABLE_STACKTRACE		if X86_64 && FRAME_POINTER && STACK_VALIDATION

Tests to measure possible performance penalty of frame pointers were done by Mel Gorman. The outcome was quite clear. There IS a measurable impact. The percentage depends on the workflow but I think it is safe to say that FP usually takes 5-10 percents.

If my understanding is correct there is no single culprit. Register pressure is definitely not a problem. We ran simple benchmarks while taking a register away from GCC (RBP or a common one). The impact is a combination of more cacheline pressure, more memory accesses and the fact that the kernel contains a lot of small functions.

Quoted 3 lines

Thus, I think that DWARF should be the way to go here.

Other than that the patch looks good to me.

I agree that DWARF is generally a good idea, and I'm working toward it. However there's still quite a bit of work to get there.

For this consistency model to work with DWARF on x86, we would need:

1) a reliable x86 DWARF unwinder with Linus's blessing
2) objtool DWARF support (I'm working on this at the moment)
3) probably some kind of runtime NMI stack checking feature to complement objtool, along with a lot of burn time to ensure there are no issues, particularly in entry code
4) port save_stack_trace_tsk_reliable() to work with DWARF

DWARF will be nice to have, but it's definitely not required before merging this consistency model.

Also I doubt we'll ever be able to drop frame pointer support completely. Some embedded systems may not want the overhead of the DWARF metadata.

Signature · 1 line
Josh
maintainer
#6 lore raw

Re: [PATCH v3 01/15] stacktrace/x86: add function for detecting reliable stack traces

Quoted 31 lines · Josh Poimboeuf
Quoted 23 lines · Miroslav Benes

arch/x86/Kconfig config X86 · line 158

Quoted 9 lines · Josh Poimboeuf
arch/x86/Kconfig +1 -0
index 215612c..b4a6663 100644
@@ -155,6 +155,7 @@ config X86
 	select HAVE_PERF_REGS
 	select HAVE_PERF_USER_STACK_DUMP
 	select HAVE_REGS_AND_STACK_ACCESS_API
+	select HAVE_RELIABLE_STACKTRACE		if X86_64 && FRAME_POINTER && STACK_VALIDATION

Tests to measure possible performance penalty of frame pointers were done by Mel Gorman. The outcome was quite clear. There IS a measurable impact. The percentage depends on the workflow but I think it is safe to say that FP usually takes 5-10 percents.

If my understanding is correct there is no single culprit. Register pressure is definitely not a problem. We ran simple benchmarks while taking a register away from GCC (RBP or a common one). The impact is a combination of more cacheline pressure, more memory accesses and the fact that the kernel contains a lot of small functions.

Quoted 3 lines

Thus, I think that DWARF should be the way to go here.

Other than that the patch looks good to me.

I agree that DWARF is generally a good idea, and I'm working toward it. However there's still quite a bit of work to get there.

Quoted 8 lines

For this consistency model to work with DWARF on x86, we would need:

1) a reliable x86 DWARF unwinder with Linus's blessing
2) objtool DWARF support (I'm working on this at the moment)
3) probably some kind of runtime NMI stack checking feature to complement objtool, along with a lot of burn time to ensure there are no issues, particularly in entry code
4) port save_stack_trace_tsk_reliable() to work with DWARF

Yes, this is a lot of work to do.

Quoted 2 lines

DWARF will be nice to have, but it's definitely not required before merging this consistency model.

Oh, I didn't mean it to be done before merging this patch set. Sorry for the confusion. The point was that as long as the performance is involved FP does not look that promising and DWARF could be better (but who knows, right?).

Quoted 3 lines

Also I doubt we'll ever be able to drop frame pointer support completely. Some embedded systems may not want the overhead of the DWARF metadata.

True. There should be a choice in this respect.

Regards,
Miroslav

maintainer
#7 lore raw

Re: [PATCH v3 01/15] stacktrace/x86: add function for detecting reliable stack traces

In reply to Josh Poimboeuf
Quoted 31 lines · Josh Poimboeuf
Quoted 23 lines · Miroslav Benes

arch/x86/Kconfig config X86 · line 158

Quoted 9 lines · Josh Poimboeuf
arch/x86/Kconfig +1 -0
index 215612c..b4a6663 100644
@@ -155,6 +155,7 @@ config X86
 	select HAVE_PERF_REGS
 	select HAVE_PERF_USER_STACK_DUMP
 	select HAVE_REGS_AND_STACK_ACCESS_API
+	select HAVE_RELIABLE_STACKTRACE		if X86_64 && FRAME_POINTER && STACK_VALIDATION

Tests to measure possible performance penalty of frame pointers were done by Mel Gorman. The outcome was quite clear. There IS a measurable impact. The percentage depends on the workflow but I think it is safe to say that FP usually takes 5-10 percents.

If my understanding is correct there is no single culprit. Register pressure is definitely not a problem. We ran simple benchmarks while taking a register away from GCC (RBP or a common one). The impact is a combination of more cacheline pressure, more memory accesses and the fact that the kernel contains a lot of small functions.

Quoted 3 lines

Thus, I think that DWARF should be the way to go here.

Other than that the patch looks good to me.

I agree that DWARF is generally a good idea, and I'm working toward it. However there's still quite a bit of work to get there.

Quoted 7 lines

For this consistency model to work with DWARF on x86, we would need:

1) a reliable x86 DWARF unwinder with Linus's blessing
2) objtool DWARF support (I'm working on this at the moment)
3) probably some kind of runtime NMI stack checking feature to complement objtool, along with a lot of burn time to ensure there are no issues, particularly in entry code

Could you please provide more details about this NMI stack checking? What is it supposed to protect that objtool could not? Will it run regularly or will it be just a random check?

The other points are obvious. But I do not know what to think about this NMI thing. And so I am curious :-)

Quoted 1 line

4) port save_stack_trace_tsk_reliable() to work with DWARF

Best Regards,
Petr

maintainer
#50 lore raw

Re: [PATCH v3 13/15] livepatch: change to a per-task consistency model

In reply to Josh Poimboeuf

Documentation/livepatch/livepatch.txt

Quoted 13 lines · Josh Poimboeuf

Change livepatch to use a basic per-task consistency model. This is the foundation which will eventually enable us to patch those ~10% of security patches which change function or data semantics. This is the biggest remaining piece needed to make livepatch more generally useful.

[1] https://lkml.kernel.org/r/[email protected]

---

Documentation/livepatch/livepatch.txt +0 -0
index 6c43f6e..f87e742 100644

I like the description.

Just a note that we will also need to review the section about limitations. But I am not sure that we want to do it in this patch. It might open a long discussion on its own.

Quoted 10 lines
include/linux/livepatch.h +2 -0
index 1a5a93c..8e06fe5 100644
@@ -28,18 +28,40 @@
 
 #include <asm/livepatch.h>
 
+/* task patch states */
+#define KLP_UNDEFINED	-1

include/linux/livepatch.h line 42

Quoted 10 lines
include/linux/livepatch.h +4 -0
+#define KLP_UNPATCHED	 0
+#define KLP_PATCHED	 1
+
 /**
  * struct klp_func - function structure for live patching
  * @old_name:	name of the function to be patched
  * @new_func:	pointer to the patched function code
  * @old_sympos: a hint indicating which symbol position the old function
  *		can be found (optional)
+ * @immediate:  patch the func immediately, bypassing backtrace safety checks

There are more checks possible. I would use the same description as for klp_object.

Quoted 16 lines
include/linux/livepatch.h +3 -0
  * @old_addr:	the address of the function being patched
  * @kobj:	kobject for sysfs resources
  * @stack_node:	list node for klp_ops func_stack list
  * @old_size:	size of the old function
  * @new_size:	size of the new function
  * @patched:	the func has been added to the klp_ops list
+ * @transition:	the func is currently being applied or reverted
+ *
@@ -86,6 +110,7 @@ struct klp_object {
  * struct klp_patch - patch structure for live patching
  * @mod:	reference to the live patch module
  * @objs:	object entries for kernel objects to be patched
+ * @immediate:  patch all funcs immediately, bypassing safety mechanisms
  * @list:	list node for global list of registered patches
  * @kobj:	kobject for sysfs resources
  * @enabled:	the patch is enabled (but operation may be incomplete)

[...]

kernel/livepatch/core.c static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr, · line 482

Quoted 12 lines
kernel/livepatch/core.c +3 -1
index fc160c6..22c0c01 100644
@@ -424,7 +477,10 @@ static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr,
 		goto err;
 	}
 
-	if (enabled) {
+	if (patch == klp_transition_patch) {
+		klp_reverse_transition();
+		mod_delayed_work(system_wq, &klp_transition_work, 0);

I would put this mod_delayed_work() into klp_reverse_transition(). Also I would put that schedule_delayed_work() into klp_try_complete_transition().

If I did not miss anything, it will allow to move the klp_transition_work code to transition.c where it logically belongs.

Quoted 4 lines
kernel/livepatch/core.c +1 -0
+	} else if (enabled) {
 		ret = __klp_enable_patch(patch);
 		if (ret)
 			goto err;

[...]

Quoted 18 lines
kernel/livepatch/patch.c +2 -0
index 5efa262..e79ebb5 100644
@@ -29,6 +29,7 @@
 #include <linux/bug.h>
 #include <linux/printk.h>
 #include "patch.h"
+#include "transition.h"
 
 static LIST_HEAD(klp_ops);
 
@@ -54,15 +55,53 @@ static void notrace klp_ftrace_handler(unsigned long ip,
 {
 	struct klp_ops *ops;
 	struct klp_func *func;
+	int patch_state;
 

kernel/livepatch/patch.c static void notrace klp_ftrace_handler(unsigned long ip, · line 68

Quoted 10 lines
kernel/livepatch/patch.c +3 -1
 	ops = container_of(fops, struct klp_ops, fops);
 
 	rcu_read_lock();
+
 	func = list_first_or_null_rcu(&ops->func_stack, struct klp_func,
 				      stack_node);
-	if (WARN_ON_ONCE(!func))
+
+	if (!func)
 		goto unlock;

Why do you removed the WARN_ON_ONCE(), please?

We still add the function on the stack before registering the ftrace handler. Also we unregister the ftrace handler before removing the the last entry from the stack.

AFAIK, unregister_ftrace_function() calls rcu_synchronize()' to make sure that no-one is inside the handler once finished. Mirek knows more about it.

If this is not true, we have a problem. For example, we call kfree(ops) after unregister_ftrace_function();

BTW: I thought that this change was really needed because of klp_try_complete_transition(). But I think that the WARN could and should stay after all. See below.

Quoted 16 lines
kernel/livepatch/patch.c +16 -0
+	/*
+	 * Enforce the order of the ops->func_stack and func->transition reads.
+	 * The corresponding write barrier is in __klp_enable_patch().
+	 */
+	smp_rmb();
+
+	if (unlikely(func->transition)) {
+
+		/*
+		 * Enforce the order of the func->transition and
+		 * current->patch_state reads.  Otherwise we could read an
+		 * out-of-date task state and pick the wrong function.  The
+		 * corresponding write barriers are in klp_init_transition()
+		 * and __klp_disable_patch().
+		 */
+		smp_rmb();

kernel/livepatch/patch.c static void notrace klp_ftrace_handler(unsigned long ip, · line 95

Quoted 10 lines
kernel/livepatch/patch.c +10 -0
+
+		patch_state = current->patch_state;
+
+		WARN_ON_ONCE(patch_state == KLP_UNDEFINED);
+
+		if (patch_state == KLP_UNPATCHED) {
+			/*
+			 * Use the previously patched version of the function.
+			 * If no previous patches exist, use the original
+			 * function.

s/use the original/continue with the original/ ?

Quoted 44 lines
kernel/livepatch/patch.c +18 -0
+			 */
+			func = list_entry_rcu(func->stack_node.next,
+					      struct klp_func, stack_node);
+
+			if (&func->stack_node == &ops->func_stack)
+				goto unlock;
+		}
+	}
+
 	klp_arch_set_pc(regs, (unsigned long)func->new_func);
 unlock:
 	rcu_read_unlock();
@@ -211,3 +250,12 @@ int klp_patch_object(struct klp_object *obj)
 
 	return 0;
 }
+
+void klp_unpatch_objects(struct klp_patch *patch)
+{
+	struct klp_object *obj;
+
+	klp_for_each_object(patch, obj)
+		if (obj->patched)
+			klp_unpatch_object(obj);
+}
kernel/livepatch/transition.c new file +16 -0
@@ -0,0 +1,479 @@
+/*
+ * transition.c - Kernel Live Patching transition functions
+ *
+ * Copyright (C) 2015-2016 Josh Poimboeuf <[email protected]>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License

kernel/livepatch/transition.c line 26

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+ * along with this program; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+
+#include <linux/cpu.h>
+#include <linux/stacktrace.h>
+#include "patch.h"
+#include "transition.h"
+#include "../sched/sched.h"

Is this acceptable for the scheduler guys?

Quoted 11 lines
kernel/livepatch/transition.c new file +11 -0
+#define MAX_STACK_ENTRIES 100
+
+struct klp_patch *klp_transition_patch;
+
+static int klp_target_state = KLP_UNDEFINED;
+
+/* called from copy_process() during fork */
+void klp_copy_process(struct task_struct *child)
+{
+	child->patch_state = current->patch_state;
+

kernel/livepatch/transition.c line 48

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+	/* TIF_PATCH_PENDING gets copied in setup_thread_stack() */
+}
+
+/*
+ * klp_update_patch_state() - change the patched state of a task
+ * @task:	The task to change
+ *
+ * Switches the patched state of the task to the set of functions in the target
+ * patch state.
+ */

Please, add here some warning. Something like:

* This function must never be called in parallel with
* klp_ftrace_handler(). Otherwise, the handler might do random
* decisions and break the consistency.
*
* By other words, call this function only by the @task itself
* or make sure that it is not running.

Quoted 63 lines
kernel/livepatch/transition.c new file +63 -0
+void klp_update_patch_state(struct task_struct *task)
+{
+	/*
+	 * The synchronize_rcu() call in klp_try_complete_transition() ensures
+	 * this critical section completes before the global patch transition
+	 * is considered complete so we don't have spurious patch_state updates
+	 * afterwards.
+	 */
+	rcu_read_lock();
+
+	/*
+	 * This test_and_clear_tsk_thread_flag() call also serves as a read
+	 * barrier to enforce the order of the TIF_PATCH_PENDING and
+	 * klp_target_state reads.  The corresponding write barriers are in
+	 * __klp_disable_patch() and klp_reverse_transition().
+	 */
+	if (test_and_clear_tsk_thread_flag(task, TIF_PATCH_PENDING))
+		task->patch_state = READ_ONCE(klp_target_state);
+
+	rcu_read_unlock();
+}
+
+/*
+ * Initialize the global target patch state and all tasks to the initial patch
+ * state, and initialize all function transition states to true in preparation
+ * for patching or unpatching.
+ */
+void klp_init_transition(struct klp_patch *patch, int state)
+{
+	struct task_struct *g, *task;
+	unsigned int cpu;
+	struct klp_object *obj;
+	struct klp_func *func;
+	int initial_state = !state;
+
+	WARN_ON_ONCE(klp_target_state != KLP_UNDEFINED);
+
+	klp_transition_patch = patch;
+
+	/*
+	 * Set the global target patch state which tasks will switch to.  This
+	 * has no effect until the TIF_PATCH_PENDING flags get set later.
+	 */
+	klp_target_state = state;
+
+	/*
+	 * If the patch can be applied or reverted immediately, skip the
+	 * per-task transitions.
+	 */
+	if (patch->immediate)
+		return;
+
+	/*
+	 * Initialize all tasks to the initial patch state to prepare them for
+	 * switching to the target state.
+	 */
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, task) {
+		WARN_ON_ONCE(task->patch_state != KLP_UNDEFINED);
+		task->patch_state = initial_state;
+	}
+	read_unlock(&tasklist_lock);
+

kernel/livepatch/transition.c line 121

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+	/*
+	 * Ditto for the idle "swapper" tasks.
+	 */
+	get_online_cpus();
+	for_each_online_cpu(cpu) {
+		task = idle_task(cpu);
+		WARN_ON_ONCE(task->patch_state != KLP_UNDEFINED);
+		task->patch_state = initial_state;
+	}
+	put_online_cpus();

We allow to add/remove CPUs here. I am afraid that we will also need to add a cpu coming/going handler that will set the task->patch_state the right way. We must not set the klp_target_state until all ftrace handlers are ready.

Quoted 43 lines
kernel/livepatch/transition.c new file +43 -0
+	/*
+	 * Enforce the order of the task->patch_state initializations and the
+	 * func->transition updates to ensure that, in the enable path,
+	 * klp_ftrace_handler() doesn't see a func in transition with a
+	 * task->patch_state of KLP_UNDEFINED.
+	 */
+	smp_wmb();
+
+	/*
+	 * Set the func transition states so klp_ftrace_handler() will know to
+	 * switch to the transition logic.
+	 *
+	 * When patching, the funcs aren't yet in the func_stack and will be
+	 * made visible to the ftrace handler shortly by the calls to
+	 * klp_patch_object().
+	 *
+	 * When unpatching, the funcs are already in the func_stack and so are
+	 * already visible to the ftrace handler.
+	 */
+	klp_for_each_object(patch, obj)
+		klp_for_each_func(obj, func)
+			func->transition = true;
+}
+
+/*
+ * Start the transition to the specified target patch state so tasks can begin
+ * switching to it.
+ */
+void klp_start_transition(void)
+{
+	struct task_struct *g, *task;
+	unsigned int cpu;
+
+	WARN_ON_ONCE(klp_target_state == KLP_UNDEFINED);
+
+	pr_notice("'%s': %s...\n", klp_transition_patch->mod->name,
+		  klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
+
+	/*
+	 * If the patch can be applied or reverted immediately, skip the
+	 * per-task transitions.
+	 */
+	if (klp_transition_patch->immediate)

kernel/livepatch/transition.c line 175

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+		return;
+
+	/*
+	 * Mark all normal tasks as needing a patch state update.  As they pass
+	 * through the syscall barrier they'll switch over to the target state
+	 * (unless we switch them in klp_try_complete_transition() first).
+	 */
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, task)
+		set_tsk_thread_flag(task, TIF_PATCH_PENDING);

This is called also from klp_reverse_transition(). We should set it only when the task need migration. Also we should clear it when the task is in the right state already.

It is not only optimization. It actually solves a race between klp_complete_transition() and klp_update_patch_state(), see below.

kernel/livepatch/transition.c line 185

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+	read_unlock(&tasklist_lock);
+
+	/*
+	 * Ditto for the idle "swapper" tasks, though they never cross the
+	 * syscall barrier.  Instead they switch over in cpu_idle_loop().
+	 */
+	get_online_cpus();
+	for_each_online_cpu(cpu)
+		set_tsk_thread_flag(idle_task(cpu), TIF_PATCH_PENDING);
+	put_online_cpus();

Also this stage need to be somehow handled by CPU coming/going handlers.

Quoted 9 lines
kernel/livepatch/transition.c new file +9 -0
+}
+
+/*
+ * The transition to the target patch state is complete.  Clean up the data
+ * structures.
+ */
+void klp_complete_transition(void)
+{
+	struct klp_object *obj;

kernel/livepatch/transition.c line 204

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+	struct klp_func *func;
+	struct task_struct *g, *task;
+	unsigned int cpu;
+
+	if (klp_transition_patch->immediate)
+		goto done;
+
+	klp_for_each_object(klp_transition_patch, obj)
+		klp_for_each_func(obj, func)
+			func->transition = false;

We should call rcu_synchronize() here. Otherwise, there might be a race, see below:

CPU1 CPU2

klp_ftrace_handler()
if (unlikely(func->transition))

	// still true

					klp_complete_transition()
					  func->transition = false;
					  task->patch_state =
					      KLP_UNDEFINED;

     patch_state = current->patch_state;

     WARN_ON(patch_state == KLP_UNDEFINED);

BANG!: We print the warning.

Note that that smp_wmb() is enough in klp_init_transition() but it is not enough here. We need to wait longer once someone might be inside the if (true) code.

kernel/livepatch/transition.c line 216

Quoted 11 lines
kernel/livepatch/transition.c new file +11 -0
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, task) {
+		clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
+		task->patch_state = KLP_UNDEFINED;
+	}
+	read_unlock(&tasklist_lock);
+
+	get_online_cpus();
+	for_each_online_cpu(cpu) {
+		task = idle_task(cpu);
+		clear_tsk_thread_flag(task, TIF_PATCH_PENDING);

If TIF_PATCH_PENDING flag is set here it means that klp_update_patch_state() might get triggered and it might put wrong value into task->patch_state.

We must make sure that all task have this cleared before calling this function. This is another reason why klp_init_transition() should set the flag only when transition is needed.

We should only check the state here.

It still might make sense to clear it when it is set wrongly. But the question is if it is really safe to continue. I am afraid that it is not. It would mean that the consistency model is broken and we are in strange state.

Quoted 8 lines
kernel/livepatch/transition.c new file +8 -0
+		task->patch_state = KLP_UNDEFINED;
+	}
+	put_online_cpus();
+
+done:
+	klp_target_state = KLP_UNDEFINED;
+	klp_transition_patch = NULL;
+}

[...]

Quoted 62 lines
kernel/livepatch/transition.c new file +62 -0
+
+/*
+ * Try to switch all remaining tasks to the target patch state by walking the
+ * stacks of sleeping tasks and looking for any to-be-patched or
+ * to-be-unpatched functions.  If such functions are found, the task can't be
+ * switched yet.
+ *
+ * If any tasks are still stuck in the initial patch state, schedule a retry.
+ */
+bool klp_try_complete_transition(void)
+{
+	unsigned int cpu;
+	struct task_struct *g, *task;
+	bool complete = true;
+
+	WARN_ON_ONCE(klp_target_state == KLP_UNDEFINED);
+
+	/*
+	 * If the patch can be applied or reverted immediately, skip the
+	 * per-task transitions.
+	 */
+	if (klp_transition_patch->immediate)
+		goto success;
+
+	/*
+	 * Try to switch the tasks to the target patch state by walking their
+	 * stacks and looking for any to-be-patched or to-be-unpatched
+	 * functions.  If such functions are found on a stack, or if the stack
+	 * is deemed unreliable, the task can't be switched yet.
+	 *
+	 * Usually this will transition most (or all) of the tasks on a system
+	 * unless the patch includes changes to a very common function.
+	 */
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, task)
+		if (!klp_try_switch_task(task))
+			complete = false;
+	read_unlock(&tasklist_lock);
+
+	/*
+	 * Ditto for the idle "swapper" tasks.
+	 */
+	get_online_cpus();
+	for_each_online_cpu(cpu)
+		if (!klp_try_switch_task(idle_task(cpu)))
+			complete = false;
+	put_online_cpus();
+
+	/*
+	 * Some tasks weren't able to be switched over.  Try again later and/or
+	 * wait for other methods like syscall barrier switching.
+	 */
+	if (!complete)
+		return false;
+
+success:
+
+	/*
+	 * When unpatching, all tasks have transitioned to KLP_UNPATCHED so we
+	 * can now remove the new functions from the func_stack.
+	 */
+	if (klp_target_state == KLP_UNPATCHED)

kernel/livepatch/transition.c line 439

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+		klp_unpatch_objects(klp_transition_patch);
+
+	/*
+	 * Wait for all RCU read-side critical sections to complete.
+	 *
+	 * This has two purposes:
+	 *
+	 * 1) Ensure all existing critical sections in klp_update_patch_state()
+	 *    complete, so task->patch_state won't be unexpectedly updated
+	 *    later.

We should not be here if anyone still might be in klp_update_patch_state().

kernel/livepatch/transition.c line 446

Quoted 7 lines
kernel/livepatch/transition.c new file +7 -0
+	 *
+	 * 2) When unpatching, don't allow any existing instances of
+	 *    klp_ftrace_handler() to access any obsolete funcs before we reset
+	 *    the func transition states to false.  Otherwise the handler may
+	 *    see the deleted "new" func, see that it's not in transition, and
+	 *    wrongly pick the new version of the function.
+	 */

This makes sense but it too me long time to understand. I wonder if this might be better:

/*
* Make sure that the function is removed from ops->func_stack
* before we clear func->transition. Otherwise the handler may
* pick the wrong version.
*/

And I would call this only when the patch is being removed

	if (klp_target_state = KLP_UNPATCHED)
		synchronize_rcu();

I think that this was the reason to remove WARN_ON_ONCE(!func) in klp_ftrace_handler(). But this is not related. If this was the last entry in the list, we removed the ftrace_handler before removing the last entry. And unregister_ftrace_function() calls rcu_synchronize() to prevent calling the handler later.

Quoted 19 lines
kernel/livepatch/transition.c new file +19 -0
+	synchronize_rcu();
+
+	pr_notice("'%s': %s complete\n", klp_transition_patch->mod->name,
+		  klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
+
+	/* we're done, now cleanup the data structures */
+	klp_complete_transition();
+
+	return true;
+}
+
+/*
+ * This function can be called in the middle of an existing transition to
+ * reverse the direction of the target patch state.  This can be done to
+ * effectively cancel an existing enable or disable operation if there are any
+ * tasks which are stuck in the initial patch state.
+ */
+void klp_reverse_transition(void)
+{

kernel/livepatch/transition.c line 475

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+	klp_transition_patch->enabled = !klp_transition_patch->enabled;
+
+	klp_target_state = !klp_target_state;
+
+	/*
+	 * Enforce the order of the write to klp_target_state above and the
+	 * TIF_PATCH_PENDING writes in klp_start_transition() to ensure that
+	 * klp_update_patch_state() doesn't set a wrong task->patch_state.
+	 */
+	smp_wmb();

I would call rcu_synchronize() here to make sure that klp_update_patch_state() calls will not set an outdated task->patch_state.

Note that smp_wmb() is not enough. We do not check TIF_PATCH_PENDING in klp_try_switch_task(). There is a tiny race:

CPU1 CPU2

klp_update_patch_state()

	if (test_and clear(task, TIF)
	     READ_ONCE(klp_target_state);

					mutex_lock(klp_lock);

					klp_reverse_transition()
					  klp_target_state =
					      !klp_target_state;

					  klp_start_transition()

					mutex_unlock(klp_lock);

					 <switch to another process>

					 klp_transition_work_fn()
					   mutex_lock(klp_lock);
					   klp_try_complete_transition()
					     klp_try_switch_task()
					       if (task->patch_state ==
						   klp_target_state)
						  return true;

	    task->patch_state = <outdated_value>;

	 klp_ftrace_handler()

BANG: klp_ftrace_handler() will use wrong implementation according
to the outdated task->patch_state. At the same time, klp_transition() is not blocked by the task because it thinks that it has a correct state.

Quoted 18 lines
kernel/livepatch/transition.c new file +4 -0
+
+	klp_start_transition();
+}
+
samples/livepatch/livepatch-sample.c +2 -0
index e34f871..bb61c65 100644
@@ -17,6 +17,8 @@
  * along with this program; if not, see <http://www.gnu.org/licenses/>.
  */
 
+#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+
 #include <linux/module.h>
 #include <linux/kernel.h>
 #include <linux/livepatch.h>

samples/livepatch/livepatch-sample.c static int livepatch_init(void) · line 77

Quoted 7 lines
samples/livepatch/livepatch-sample.c +4 -0
@@ -69,6 +71,11 @@ static int livepatch_init(void)
 {
 	int ret;
 
+	if (!klp_have_reliable_stack() && !patch.immediate) {
+		pr_notice("disabling consistency model!\n");
+		patch.immediate = true;
+	}

I am scared to have this in the sample module. It makes sense to use the consistency model even for immediate patches because it allows to remove them. But this must not be used for patches that really require the consistency model. We should add a big fat warning at least.

samples/livepatch/livepatch-sample.c static int livepatch_init(void) · line 81

Quoted 4 lines
samples/livepatch/livepatch-sample.c +1 -0
+
 	ret = klp_register_patch(&patch);
 	if (ret)
 		return ret;

I like the patch. All the problems that I found look solvable. I think that we are on the right way.

Best Regards,
Petr

#8 lore raw

Re: [PATCH v3 01/15] stacktrace/x86: add function for detecting reliable stack traces

In reply to Petr Mladek
Quoted 8 lines · Petr Mladek
Quoted 3 lines · Josh Poimboeuf

3) probably some kind of runtime NMI stack checking feature to complement objtool, along with a lot of burn time to ensure there are no issues, particularly in entry code

Could you please provide more details about this NMI stack checking? What is it supposed to protect that objtool could not? Will it run regularly or will it be just a random check?

save_stack_trace_tsk_reliable(current) would be called periodically from an NMI handler, and a warning would be printed if it ever doesn't reach the "end" of the stack (i.e., user-mode pt_regs). Due to the performance impact it would probably only be a debug option.

It would verify the special hand-coded areas which objtool isn't smart enough to understand, like entry code, ftrace, kprobes, bpf. It would also make sure that objtool itself didn't missing anything.

Signature · 1 line
Josh
maintainer Reviewed-by on v3 4/15
#20 lore raw

Re: [PATCH v3 04/15] livepatch/x86: add TIF_PATCH_PENDING thread flag

In reply to Josh Poimboeuf
Quoted 9 lines · Josh Poimboeuf

Add the TIF_PATCH_PENDING thread flag to enable the new livepatch per-task consistency model for x86_64. The bit getting set indicates the thread has a pending patch which needs to be applied when the thread exits the kernel.

The bit is placed in the _TIF_ALLWORK_MASK macro, which results in exit_to_usermode_loop() calling klp_update_patch_state() when it's set.

Miroslav

maintainer Reviewed-by on v3 5/15
#24 lore raw

Re: [PATCH v3 05/15] livepatch/powerpc: add TIF_PATCH_PENDING thread flag

In reply to Josh Poimboeuf
Quoted 10 lines · Josh Poimboeuf

Add the TIF_PATCH_PENDING thread flag to enable the new livepatch per-task consistency model for powerpc. The bit getting set indicates the thread has a pending patch which needs to be applied when the thread exits the kernel.

The bit is included in the _TIF_USER_WORK_MASK macro so that do_notify_resume() and klp_update_patch_state() get called when the bit is set.

Looks good to me. You can add my

Miroslav

maintainer Reviewed-by on v3 15/15
#71 lore raw

Re: [PATCH v3 15/15] livepatch: allow removal of a disabled patch

In reply to Josh Poimboeuf
Quoted 10 lines · Josh Poimboeuf

From: Miroslav Benes <[email protected]>

Currently we do not allow patch module to unload since there is no method to determine if a task is still running in the patched code.

The consistency model gives us the way because when the unpatching finishes we know that all tasks were marked as safe to call an original function. Thus every new call to the function calls the original code and at the same time no task can be somewhere in the patched code, because it had to leave that code to be marked as safe.

[...]

Quoted 5 lines

Also all kobject_put(&patch->kobj) calls are moved outside of klp_mutex lock protection to prevent a deadlock situation when klp_unregister_patch is called and sysfs directories are removed. is no need to do the same for other kobject_put() callsites as we currently do not have their sysfs counterparts.

Heh, we have spent huge amount of time on this. I think that it deserves a more precise description ;-). What about?

Finally, we need to be very careful about possible races between klp_unregister_patch(), kobject_put() functions and operations on the related sysfs files.

kobject_put(&patch->kobj) must be called without klp_mutex. Otherwise, it might be blocked by enabled_store() that needs the mutex as well. In addition, enabled_store() must check if the patch was not unregisted in the meantime.

There is no need to do the same for other kobject_put() callsites at the moment. Their sysfs operations neiter take the lock nor they access any data that might be freed in the meantime.

There was an attempt to use kobjects the right way and prevent these races by design. But it made the patch definition more complicated and opened another can of worms. See
https://lkml.kernel.org/r/[email protected]

Quoted 2 lines

Otherwise, it seems correct. We have already analyzed this to the death. I do not see new problems with a fresh look.

With the above, or comparable, change in the commit message:

Best Regards,
Petr

maintainer Reviewed-by on v3 6/15
#27 lore raw

Re: [PATCH v3 06/15] livepatch/s390: reorganize TIF thread flag bits

In reply to Josh Poimboeuf
Quoted 7 lines · Josh Poimboeuf

From: Jiri Slaby <[email protected]>

Group the TIF thread flag bits by their inclusion in the _TIF_WORK and _TIF_TRACE macros.

I believe there is no harm doing that and we need it for _TIF_PATCH_PENDING later.

Miroslav

#51 lore raw

Re: [PATCH v3 13/15] livepatch: change to a per-task consistency model

In reply to Petr Mladek
Quoted 29 lines · Petr Mladek

Documentation/livepatch/livepatch.txt

Quoted 13 lines · Josh Poimboeuf

Change livepatch to use a basic per-task consistency model. This is the foundation which will eventually enable us to patch those ~10% of security patches which change function or data semantics. This is the biggest remaining piece needed to make livepatch more generally useful.

[1] https://lkml.kernel.org/r/[email protected]

---

Documentation/livepatch/livepatch.txt +0 -0
index 6c43f6e..f87e742 100644

I like the description.

Just a note that we will also need to review the section about limitations. But I am not sure that we want to do it in this patch. It might open a long discussion on its own.

Quoted 8 lines
include/linux/livepatch.h +0 -0
index 1a5a93c..8e06fe5 100644
@@ -28,18 +28,40 @@
 
 #include <asm/livepatch.h>
 
Quoted 15 lines

include/linux/livepatch.h line 42

Quoted 12 lines
include/linux/livepatch.h +6 -0
+/* task patch states */
+#define KLP_UNDEFINED	-1
+#define KLP_UNPATCHED	 0
+#define KLP_PATCHED	 1
+
 /**
  * struct klp_func - function structure for live patching
  * @old_name:	name of the function to be patched
  * @new_func:	pointer to the patched function code
  * @old_sympos: a hint indicating which symbol position the old function
  *		can be found (optional)
+ * @immediate:  patch the func immediately, bypassing backtrace safety checks

There are more checks possible. I would use the same description as for klp_object.

Agreed.

Quoted 36 lines
Quoted 16 lines
include/linux/livepatch.h +3 -0
  * @old_addr:	the address of the function being patched
  * @kobj:	kobject for sysfs resources
  * @stack_node:	list node for klp_ops func_stack list
  * @old_size:	size of the old function
  * @new_size:	size of the new function
  * @patched:	the func has been added to the klp_ops list
+ * @transition:	the func is currently being applied or reverted
+ *
@@ -86,6 +110,7 @@ struct klp_object {
  * struct klp_patch - patch structure for live patching
  * @mod:	reference to the live patch module
  * @objs:	object entries for kernel objects to be patched
+ * @immediate:  patch all funcs immediately, bypassing safety mechanisms
  * @list:	list node for global list of registered patches
  * @kobj:	kobject for sysfs resources
  * @enabled:	the patch is enabled (but operation may be incomplete)

[...]

kernel/livepatch/core.c static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr, · line 482

Quoted 12 lines
kernel/livepatch/core.c +3 -1
index fc160c6..22c0c01 100644
@@ -424,7 +477,10 @@ static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr,
 		goto err;
 	}
 
-	if (enabled) {
+	if (patch == klp_transition_patch) {
+		klp_reverse_transition();
+		mod_delayed_work(system_wq, &klp_transition_work, 0);

I would put this mod_delayed_work() into klp_reverse_transition(). Also I would put that schedule_delayed_work() into klp_try_complete_transition().

Quoted 3 lines

If I did not miss anything, it will allow to move the klp_transition_work code to transition.c where it logically belongs.

Makes sense, I'll see if I can move all the klp_transition_work code to transition.c.

Quoted 38 lines
Quoted 4 lines
kernel/livepatch/core.c +1 -0
+	} else if (enabled) {
 		ret = __klp_enable_patch(patch);
 		if (ret)
 			goto err;

[...]

Quoted 18 lines
kernel/livepatch/patch.c +2 -0
index 5efa262..e79ebb5 100644
@@ -29,6 +29,7 @@
 #include <linux/bug.h>
 #include <linux/printk.h>
 #include "patch.h"
+#include "transition.h"
 
 static LIST_HEAD(klp_ops);
 
@@ -54,15 +55,53 @@ static void notrace klp_ftrace_handler(unsigned long ip,
 {
 	struct klp_ops *ops;
 	struct klp_func *func;
+	int patch_state;
 

kernel/livepatch/patch.c static void notrace klp_ftrace_handler(unsigned long ip, · line 68

Quoted 10 lines
kernel/livepatch/patch.c +3 -1
 	ops = container_of(fops, struct klp_ops, fops);
 
 	rcu_read_lock();
+
 	func = list_first_or_null_rcu(&ops->func_stack, struct klp_func,
 				      stack_node);
-	if (WARN_ON_ONCE(!func))
+
+	if (!func)
 		goto unlock;

Why do you removed the WARN_ON_ONCE(), please?

Quoted 7 lines

We still add the function on the stack before registering the ftrace handler. Also we unregister the ftrace handler before removing the the last entry from the stack.

AFAIK, unregister_ftrace_function() calls rcu_synchronize()' to make sure that no-one is inside the handler once finished. Mirek knows more about it.

Hm, this is news to me. Mirek, please share :-)

Quoted 2 lines

If this is not true, we have a problem. For example, we call kfree(ops) after unregister_ftrace_function();

Agreed.

Quoted 25 lines

BTW: I thought that this change was really needed because of klp_try_complete_transition(). But I think that the WARN could and should stay after all. See below.

Quoted 20 lines
kernel/livepatch/patch.c +20 -0
+	/*
+	 * Enforce the order of the ops->func_stack and func->transition reads.
+	 * The corresponding write barrier is in __klp_enable_patch().
+	 */
+	smp_rmb();
+
+	if (unlikely(func->transition)) {
+
+		/*
+		 * Enforce the order of the func->transition and
+		 * current->patch_state reads.  Otherwise we could read an
+		 * out-of-date task state and pick the wrong function.  The
+		 * corresponding write barriers are in klp_init_transition()
+		 * and __klp_disable_patch().
+		 */
+		smp_rmb();
+
+		patch_state = current->patch_state;
+
+		WARN_ON_ONCE(patch_state == KLP_UNDEFINED);
Quoted 8 lines

kernel/livepatch/patch.c static void notrace klp_ftrace_handler(unsigned long ip, · line 95

Quoted 6 lines
kernel/livepatch/patch.c +6 -0
+
+		if (patch_state == KLP_UNPATCHED) {
+			/*
+			 * Use the previously patched version of the function.
+			 * If no previous patches exist, use the original
+			 * function.

s/use the original/continue with the original/ ?

Ok.

Quoted 48 lines
Quoted 48 lines
kernel/livepatch/patch.c +18 -0
+			 */
+			func = list_entry_rcu(func->stack_node.next,
+					      struct klp_func, stack_node);
+
+			if (&func->stack_node == &ops->func_stack)
+				goto unlock;
+		}
+	}
+
 	klp_arch_set_pc(regs, (unsigned long)func->new_func);
 unlock:
 	rcu_read_unlock();
@@ -211,3 +250,12 @@ int klp_patch_object(struct klp_object *obj)
 
 	return 0;
 }
+
+void klp_unpatch_objects(struct klp_patch *patch)
+{
+	struct klp_object *obj;
+
+	klp_for_each_object(patch, obj)
+		if (obj->patched)
+			klp_unpatch_object(obj);
+}
kernel/livepatch/transition.c new file +20 -0
@@ -0,0 +1,479 @@
+/*
+ * transition.c - Kernel Live Patching transition functions
+ *
+ * Copyright (C) 2015-2016 Josh Poimboeuf <[email protected]>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
Quoted 8 lines

kernel/livepatch/transition.c line 26

Quoted 6 lines
kernel/livepatch/transition.c new file +6 -0
+
+#include <linux/cpu.h>
+#include <linux/stacktrace.h>
+#include "patch.h"
+#include "transition.h"
+#include "../sched/sched.h"

Is this acceptable for the scheduler guys?

I discussed the use of task_rq_lock() with Peter Zijlstra on IRC and he seemed to think it was ok. Peter, please speak up if you disagree :-)

Quoted 24 lines
Quoted 11 lines
kernel/livepatch/transition.c new file +11 -0
+#define MAX_STACK_ENTRIES 100
+
+struct klp_patch *klp_transition_patch;
+
+static int klp_target_state = KLP_UNDEFINED;
+
+/* called from copy_process() during fork */
+void klp_copy_process(struct task_struct *child)
+{
+	child->patch_state = current->patch_state;
+

kernel/livepatch/transition.c line 48

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+	/* TIF_PATCH_PENDING gets copied in setup_thread_stack() */
+}
+
+/*
+ * klp_update_patch_state() - change the patched state of a task
+ * @task:	The task to change
+ *
+ * Switches the patched state of the task to the set of functions in the target
+ * patch state.
+ */

Please, add here some warning. Something like:

Quoted 6 lines

* This function must never be called in parallel with
* klp_ftrace_handler(). Otherwise, the handler might do random
* decisions and break the consistency.
*
* By other words, call this function only by the @task itself
* or make sure that it is not running.

Yeah, I'll add a comment here. This goes back to our discussion from last time:

https://lkml.kernel.org/r/20160504172517.tdatoj2nlkqwyd4g@treble

Quoted 70 lines
Quoted 70 lines
kernel/livepatch/transition.c new file +70 -0
+void klp_update_patch_state(struct task_struct *task)
+{
+	/*
+	 * The synchronize_rcu() call in klp_try_complete_transition() ensures
+	 * this critical section completes before the global patch transition
+	 * is considered complete so we don't have spurious patch_state updates
+	 * afterwards.
+	 */
+	rcu_read_lock();
+
+	/*
+	 * This test_and_clear_tsk_thread_flag() call also serves as a read
+	 * barrier to enforce the order of the TIF_PATCH_PENDING and
+	 * klp_target_state reads.  The corresponding write barriers are in
+	 * __klp_disable_patch() and klp_reverse_transition().
+	 */
+	if (test_and_clear_tsk_thread_flag(task, TIF_PATCH_PENDING))
+		task->patch_state = READ_ONCE(klp_target_state);
+
+	rcu_read_unlock();
+}
+
+/*
+ * Initialize the global target patch state and all tasks to the initial patch
+ * state, and initialize all function transition states to true in preparation
+ * for patching or unpatching.
+ */
+void klp_init_transition(struct klp_patch *patch, int state)
+{
+	struct task_struct *g, *task;
+	unsigned int cpu;
+	struct klp_object *obj;
+	struct klp_func *func;
+	int initial_state = !state;
+
+	WARN_ON_ONCE(klp_target_state != KLP_UNDEFINED);
+
+	klp_transition_patch = patch;
+
+	/*
+	 * Set the global target patch state which tasks will switch to.  This
+	 * has no effect until the TIF_PATCH_PENDING flags get set later.
+	 */
+	klp_target_state = state;
+
+	/*
+	 * If the patch can be applied or reverted immediately, skip the
+	 * per-task transitions.
+	 */
+	if (patch->immediate)
+		return;
+
+	/*
+	 * Initialize all tasks to the initial patch state to prepare them for
+	 * switching to the target state.
+	 */
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, task) {
+		WARN_ON_ONCE(task->patch_state != KLP_UNDEFINED);
+		task->patch_state = initial_state;
+	}
+	read_unlock(&tasklist_lock);
+
+	/*
+	 * Ditto for the idle "swapper" tasks.
+	 */
+	get_online_cpus();
+	for_each_online_cpu(cpu) {
+		task = idle_task(cpu);
+		WARN_ON_ONCE(task->patch_state != KLP_UNDEFINED);
Quoted 8 lines

kernel/livepatch/transition.c line 121

Quoted 3 lines
kernel/livepatch/transition.c new file +3 -0
+		task->patch_state = initial_state;
+	}
+	put_online_cpus();

We allow to add/remove CPUs here. I am afraid that we will also need to add a cpu coming/going handler that will set the task->patch_state the right way. We must not set the klp_target_state until all ftrace handlers are ready.

What if we instead just change the above to use for_each_possible_cpu()? We could do the same in klp_complete_transition().

Quoted 58 lines
Quoted 43 lines
kernel/livepatch/transition.c new file +43 -0
+	/*
+	 * Enforce the order of the task->patch_state initializations and the
+	 * func->transition updates to ensure that, in the enable path,
+	 * klp_ftrace_handler() doesn't see a func in transition with a
+	 * task->patch_state of KLP_UNDEFINED.
+	 */
+	smp_wmb();
+
+	/*
+	 * Set the func transition states so klp_ftrace_handler() will know to
+	 * switch to the transition logic.
+	 *
+	 * When patching, the funcs aren't yet in the func_stack and will be
+	 * made visible to the ftrace handler shortly by the calls to
+	 * klp_patch_object().
+	 *
+	 * When unpatching, the funcs are already in the func_stack and so are
+	 * already visible to the ftrace handler.
+	 */
+	klp_for_each_object(patch, obj)
+		klp_for_each_func(obj, func)
+			func->transition = true;
+}
+
+/*
+ * Start the transition to the specified target patch state so tasks can begin
+ * switching to it.
+ */
+void klp_start_transition(void)
+{
+	struct task_struct *g, *task;
+	unsigned int cpu;
+
+	WARN_ON_ONCE(klp_target_state == KLP_UNDEFINED);
+
+	pr_notice("'%s': %s...\n", klp_transition_patch->mod->name,
+		  klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
+
+	/*
+	 * If the patch can be applied or reverted immediately, skip the
+	 * per-task transitions.
+	 */
+	if (klp_transition_patch->immediate)

kernel/livepatch/transition.c line 175

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+		return;
+
+	/*
+	 * Mark all normal tasks as needing a patch state update.  As they pass
+	 * through the syscall barrier they'll switch over to the target state
+	 * (unless we switch them in klp_try_complete_transition() first).
+	 */
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, task)
+		set_tsk_thread_flag(task, TIF_PATCH_PENDING);

This is called also from klp_reverse_transition(). We should set it only when the task need migration. Also we should clear it when the task is in the right state already.

Quoted 2 lines

It is not only optimization. It actually solves a race between klp_complete_transition() and klp_update_patch_state(), see below.

I agree about the race, but if I did:

	for_each_process_thread(g, task) {
		if (task->patch_state != klp_target_state)
			set_tsk_thread_flag(task, TIF_PATCH_PENDING);
		else
			clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
	}

It would still leave a small window where TIF_PATCH_PENDING gets set for an already patched task, if klp_update_patch_state() is running at the same time.

See below for another solution.

Quoted 5 lines
Quoted 5 lines
kernel/livepatch/transition.c new file +5 -0
+	read_unlock(&tasklist_lock);
+
+	/*
+	 * Ditto for the idle "swapper" tasks, though they never cross the
+	 * syscall barrier.  Instead they switch over in cpu_idle_loop().
Quoted 8 lines

kernel/livepatch/transition.c line 185

Quoted 5 lines
kernel/livepatch/transition.c new file +5 -0
+	 */
+	get_online_cpus();
+	for_each_online_cpu(cpu)
+		set_tsk_thread_flag(idle_task(cpu), TIF_PATCH_PENDING);
+	put_online_cpus();

Also this stage need to be somehow handled by CPU coming/going handlers.

Here I think we could automatically switch any offline CPUs' idle tasks. And something similar in klp_try_complete_transition().

Quoted 38 lines
Quoted 9 lines
kernel/livepatch/transition.c new file +9 -0
+}
+
+/*
+ * The transition to the target patch state is complete.  Clean up the data
+ * structures.
+ */
+void klp_complete_transition(void)
+{
+	struct klp_object *obj;

kernel/livepatch/transition.c line 204

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+	struct klp_func *func;
+	struct task_struct *g, *task;
+	unsigned int cpu;
+
+	if (klp_transition_patch->immediate)
+		goto done;
+
+	klp_for_each_object(klp_transition_patch, obj)
+		klp_for_each_func(obj, func)
+			func->transition = false;

We should call rcu_synchronize() here. Otherwise, there might be a race, see below:

CPU1 CPU2

klp_ftrace_handler()
if (unlikely(func->transition))

	// still true

					klp_complete_transition()
					  func->transition = false;
					  task->patch_state =
					      KLP_UNDEFINED;

     patch_state = current->patch_state;

     WARN_ON(patch_state == KLP_UNDEFINED);
Quoted 1 line

BANG!: We print the warning.

This shouldn't be possible because klp_try_complete_transition() calls rcu_synchronize() before calling klp_complete_transition(). So by the time klp_complete_transition() is called, the ftrace handler can no longer see the affected func. See the comment for rcu_synchronize() in klp_try_complete_transition().

Quoted 25 lines

Note that that smp_wmb() is enough in klp_init_transition() but it is not enough here. We need to wait longer once someone might be inside the if (true) code.

kernel/livepatch/transition.c line 216

Quoted 11 lines
kernel/livepatch/transition.c new file +11 -0
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, task) {
+		clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
+		task->patch_state = KLP_UNDEFINED;
+	}
+	read_unlock(&tasklist_lock);
+
+	get_online_cpus();
+	for_each_online_cpu(cpu) {
+		task = idle_task(cpu);
+		clear_tsk_thread_flag(task, TIF_PATCH_PENDING);

If TIF_PATCH_PENDING flag is set here it means that klp_update_patch_state() might get triggered and it might put wrong value into task->patch_state.

We must make sure that all task have this cleared before calling this function. This is another reason why klp_init_transition() should set the flag only when transition is needed.

Quoted 6 lines

We should only check the state here.

It still might make sense to clear it when it is set wrongly. But the question is if it is really safe to continue. I am afraid that it is not. It would mean that the consistency model is broken and we are in strange state.

As I mentioned above, with your proposal I think there could still be a task with a spurious set TIF_PATCH_PENDING at this point.

Maybe instead we should clear all the TIF_PATCH_PENDING flags before the synchronize_rcu() in klp_try_complete_transition().

Quoted 77 lines
Quoted 8 lines
kernel/livepatch/transition.c new file +8 -0
+		task->patch_state = KLP_UNDEFINED;
+	}
+	put_online_cpus();
+
+done:
+	klp_target_state = KLP_UNDEFINED;
+	klp_transition_patch = NULL;
+}

[...]

Quoted 66 lines
kernel/livepatch/transition.c new file +66 -0
+
+/*
+ * Try to switch all remaining tasks to the target patch state by walking the
+ * stacks of sleeping tasks and looking for any to-be-patched or
+ * to-be-unpatched functions.  If such functions are found, the task can't be
+ * switched yet.
+ *
+ * If any tasks are still stuck in the initial patch state, schedule a retry.
+ */
+bool klp_try_complete_transition(void)
+{
+	unsigned int cpu;
+	struct task_struct *g, *task;
+	bool complete = true;
+
+	WARN_ON_ONCE(klp_target_state == KLP_UNDEFINED);
+
+	/*
+	 * If the patch can be applied or reverted immediately, skip the
+	 * per-task transitions.
+	 */
+	if (klp_transition_patch->immediate)
+		goto success;
+
+	/*
+	 * Try to switch the tasks to the target patch state by walking their
+	 * stacks and looking for any to-be-patched or to-be-unpatched
+	 * functions.  If such functions are found on a stack, or if the stack
+	 * is deemed unreliable, the task can't be switched yet.
+	 *
+	 * Usually this will transition most (or all) of the tasks on a system
+	 * unless the patch includes changes to a very common function.
+	 */
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, task)
+		if (!klp_try_switch_task(task))
+			complete = false;
+	read_unlock(&tasklist_lock);
+
+	/*
+	 * Ditto for the idle "swapper" tasks.
+	 */
+	get_online_cpus();
+	for_each_online_cpu(cpu)
+		if (!klp_try_switch_task(idle_task(cpu)))
+			complete = false;
+	put_online_cpus();
+
+	/*
+	 * Some tasks weren't able to be switched over.  Try again later and/or
+	 * wait for other methods like syscall barrier switching.
+	 */
+	if (!complete)
+		return false;
+
+success:
+
+	/*
+	 * When unpatching, all tasks have transitioned to KLP_UNPATCHED so we
+	 * can now remove the new functions from the func_stack.
+	 */
+	if (klp_target_state == KLP_UNPATCHED)
+		klp_unpatch_objects(klp_transition_patch);
+
+	/*
+	 * Wait for all RCU read-side critical sections to complete.
Quoted 8 lines

kernel/livepatch/transition.c line 439

Quoted 6 lines
kernel/livepatch/transition.c new file +6 -0
+	 *
+	 * This has two purposes:
+	 *
+	 * 1) Ensure all existing critical sections in klp_update_patch_state()
+	 *    complete, so task->patch_state won't be unexpectedly updated
+	 *    later.

We should not be here if anyone still might be in klp_update_patch_state().

Depends on our discussion about conditionally setting TIF_PATCH_PENDING.

Quoted 12 lines

kernel/livepatch/transition.c line 446

Quoted 8 lines
kernel/livepatch/transition.c new file +7 -0
+	 *
+	 * 2) When unpatching, don't allow any existing instances of
+	 *    klp_ftrace_handler() to access any obsolete funcs before we reset
+	 *    the func transition states to false.  Otherwise the handler may
+	 *    see the deleted "new" func, see that it's not in transition, and
+	 *    wrongly pick the new version of the function.
+	 */

This makes sense but it too me long time to understand. I wonder if this might be better:

Quoted 5 lines

/*
* Make sure that the function is removed from ops->func_stack
* before we clear func->transition. Otherwise the handler may
* pick the wrong version.
*/

Sounds good.

Quoted 4 lines

And I would call this only when the patch is being removed

	if (klp_target_state = KLP_UNPATCHED)
		synchronize_rcu();

Depends on our discussion about conditionally setting TIF_PATCH_PENDING.

Quoted 75 lines

I think that this was the reason to remove WARN_ON_ONCE(!func) in klp_ftrace_handler(). But this is not related. If this was the last entry in the list, we removed the ftrace_handler before removing the last entry. And unregister_ftrace_function() calls rcu_synchronize() to prevent calling the handler later.

Quoted 19 lines
kernel/livepatch/transition.c new file +19 -0
+	synchronize_rcu();
+
+	pr_notice("'%s': %s complete\n", klp_transition_patch->mod->name,
+		  klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
+
+	/* we're done, now cleanup the data structures */
+	klp_complete_transition();
+
+	return true;
+}
+
+/*
+ * This function can be called in the middle of an existing transition to
+ * reverse the direction of the target patch state.  This can be done to
+ * effectively cancel an existing enable or disable operation if there are any
+ * tasks which are stuck in the initial patch state.
+ */
+void klp_reverse_transition(void)
+{

kernel/livepatch/transition.c line 475

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+	klp_transition_patch->enabled = !klp_transition_patch->enabled;
+
+	klp_target_state = !klp_target_state;
+
+	/*
+	 * Enforce the order of the write to klp_target_state above and the
+	 * TIF_PATCH_PENDING writes in klp_start_transition() to ensure that
+	 * klp_update_patch_state() doesn't set a wrong task->patch_state.
+	 */
+	smp_wmb();

I would call rcu_synchronize() here to make sure that klp_update_patch_state() calls will not set an outdated task->patch_state.

Note that smp_wmb() is not enough. We do not check TIF_PATCH_PENDING in klp_try_switch_task(). There is a tiny race:

CPU1 CPU2

klp_update_patch_state()

	if (test_and clear(task, TIF)
	     READ_ONCE(klp_target_state);

					mutex_lock(klp_lock);

					klp_reverse_transition()
					  klp_target_state =
					      !klp_target_state;

					  klp_start_transition()

					mutex_unlock(klp_lock);

					 <switch to another process>

					 klp_transition_work_fn()
					   mutex_lock(klp_lock);
					   klp_try_complete_transition()
					     klp_try_switch_task()
					       if (task->patch_state ==
						   klp_target_state)
						  return true;

	    task->patch_state = <outdated_value>;

	 klp_ftrace_handler()
Quoted 4 lines

BANG: klp_ftrace_handler() will use wrong implementation according
to the outdated task->patch_state. At the same time, klp_transition() is not blocked by the task because it thinks that it has a correct state.

Good find!

Quoted 21 lines
Quoted 21 lines
kernel/livepatch/transition.c new file +4 -0
+
+	klp_start_transition();
+}
+
samples/livepatch/livepatch-sample.c +2 -0
index e34f871..bb61c65 100644
@@ -17,6 +17,8 @@
  * along with this program; if not, see <http://www.gnu.org/licenses/>.
  */
 
+#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+
 #include <linux/module.h>
 #include <linux/kernel.h>
 #include <linux/livepatch.h>
@@ -69,6 +71,11 @@ static int livepatch_init(void)
 {
 	int ret;
 
Quoted 10 lines

samples/livepatch/livepatch-sample.c static int livepatch_init(void) · line 77

Quoted 4 lines
samples/livepatch/livepatch-sample.c +4 -0
+	if (!klp_have_reliable_stack() && !patch.immediate) {
+		pr_notice("disabling consistency model!\n");
+		patch.immediate = true;
+	}

I am scared to have this in the sample module. It makes sense to use the consistency model even for immediate patches because it allows to remove them. But this must not be used for patches that really require the consistency model. We should add a big fat warning at least.

I did this so that the sample module would still work for non-x86_64 arches, for which there's currently no way to patch kthreads.

Notice I did add a warning:

  pr_notice("disabling consistency model!\n");

Is the warning not fat enough?

Quoted 7 lines

samples/livepatch/livepatch-sample.c static int livepatch_init(void) · line 81

Quoted 4 lines
samples/livepatch/livepatch-sample.c +1 -0
+
 	ret = klp_register_patch(&patch);
 	if (ret)
 		return ret;

I like the patch. All the problems that I found look solvable. I think that we are on the right way.

Thank you for the excellent review!

Signature · 1 line
Josh
maintainer
#52 lore raw

Re: [PATCH v3 13/15] livepatch: change to a per-task consistency model

Quoted 68 lines · Josh Poimboeuf
Quoted 58 lines · Petr Mladek
Quoted 57 lines · Josh Poimboeuf

Change livepatch to use a basic per-task consistency model. This is the foundation which will eventually enable us to patch those ~10% of security patches which change function or data semantics. This is the biggest remaining piece needed to make livepatch more generally useful.

[1] https://lkml.kernel.org/r/[email protected]

kernel/livepatch/transition.c new file +48 -0
+/*
+ * Initialize the global target patch state and all tasks to the initial patch
+ * state, and initialize all function transition states to true in preparation
+ * for patching or unpatching.
+ */
+void klp_init_transition(struct klp_patch *patch, int state)
+{
+	struct task_struct *g, *task;
+	unsigned int cpu;
+	struct klp_object *obj;
+	struct klp_func *func;
+	int initial_state = !state;
+
+	WARN_ON_ONCE(klp_target_state != KLP_UNDEFINED);
+
+	klp_transition_patch = patch;
+
+	/*
+	 * Set the global target patch state which tasks will switch to.  This
+	 * has no effect until the TIF_PATCH_PENDING flags get set later.
+	 */
+	klp_target_state = state;
+
+	/*
+	 * If the patch can be applied or reverted immediately, skip the
+	 * per-task transitions.
+	 */
+	if (patch->immediate)
+		return;
+
+	/*
+	 * Initialize all tasks to the initial patch state to prepare them for
+	 * switching to the target state.
+	 */
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, task) {
+		WARN_ON_ONCE(task->patch_state != KLP_UNDEFINED);
+		task->patch_state = initial_state;
+	}
+	read_unlock(&tasklist_lock);
+
+	/*
+	 * Ditto for the idle "swapper" tasks.
+	 */
+	get_online_cpus();
+	for_each_online_cpu(cpu) {
+		task = idle_task(cpu);
+		WARN_ON_ONCE(task->patch_state != KLP_UNDEFINED);
Quoted 8 lines

kernel/livepatch/transition.c line 121

Quoted 3 lines
kernel/livepatch/transition.c new file +3 -0
+		task->patch_state = initial_state;
+	}
+	put_online_cpus();

We allow to add/remove CPUs here. I am afraid that we will also need to add a cpu coming/going handler that will set the task->patch_state the right way. We must not set the klp_target_state until all ftrace handlers are ready.

Quoted 2 lines

What if we instead just change the above to use for_each_possible_cpu()? We could do the same in klp_complete_transition().

I like this idea. It seems that there is idle task for each possible cpu, see idle_threads_init().

IMHO, we should do the same everytime we do anything with the idle tasks. I mean in klp_start_transition, klp_try_complete_transition() and also complete_transition().

Then they will be handled like any other processes and we do not need to think of any special races.

Quoted 70 lines
Quoted 58 lines
Quoted 43 lines
kernel/livepatch/transition.c new file +43 -0
+	/*
+	 * Enforce the order of the task->patch_state initializations and the
+	 * func->transition updates to ensure that, in the enable path,
+	 * klp_ftrace_handler() doesn't see a func in transition with a
+	 * task->patch_state of KLP_UNDEFINED.
+	 */
+	smp_wmb();
+
+	/*
+	 * Set the func transition states so klp_ftrace_handler() will know to
+	 * switch to the transition logic.
+	 *
+	 * When patching, the funcs aren't yet in the func_stack and will be
+	 * made visible to the ftrace handler shortly by the calls to
+	 * klp_patch_object().
+	 *
+	 * When unpatching, the funcs are already in the func_stack and so are
+	 * already visible to the ftrace handler.
+	 */
+	klp_for_each_object(patch, obj)
+		klp_for_each_func(obj, func)
+			func->transition = true;
+}
+
+/*
+ * Start the transition to the specified target patch state so tasks can begin
+ * switching to it.
+ */
+void klp_start_transition(void)
+{
+	struct task_struct *g, *task;
+	unsigned int cpu;
+
+	WARN_ON_ONCE(klp_target_state == KLP_UNDEFINED);
+
+	pr_notice("'%s': %s...\n", klp_transition_patch->mod->name,
+		  klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
+
+	/*
+	 * If the patch can be applied or reverted immediately, skip the
+	 * per-task transitions.
+	 */
+	if (klp_transition_patch->immediate)

kernel/livepatch/transition.c line 175

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+		return;
+
+	/*
+	 * Mark all normal tasks as needing a patch state update.  As they pass
+	 * through the syscall barrier they'll switch over to the target state
+	 * (unless we switch them in klp_try_complete_transition() first).
+	 */
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, task)
+		set_tsk_thread_flag(task, TIF_PATCH_PENDING);

This is called also from klp_reverse_transition(). We should set it only when the task need migration. Also we should clear it when the task is in the right state already.

Quoted 2 lines

It is not only optimization. It actually solves a race between klp_complete_transition() and klp_update_patch_state(), see below.

I agree about the race, but if I did:

	for_each_process_thread(g, task) {
		if (task->patch_state != klp_target_state)
			set_tsk_thread_flag(task, TIF_PATCH_PENDING);
		else
			clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
	}
Quoted 3 lines

It would still leave a small window where TIF_PATCH_PENDING gets set for an already patched task, if klp_update_patch_state() is running at the same time.

I see your point. Well, it seems that it is more complicated:

The race would be possible only when this was called from klp_reverse_transition(). But we need to call there rcu_synchronize() to prevent races with klp_update_patch_state() also to prevent prelimitary patch completion.

The result is:

if (task->patch_state != klp_target_state) {
# it means that the task was already migrated before # we reverted klp_target_state. It means that # the TIF flag was already cleared, the related # klp_update_patch_state() already finished (thanks # to rcu_synchronize() and new one will be called # only when we set the flag again
# => it is safe to set it

# we should also check and warn when the TIF flag # was not clear before we set it here

else

# the task was not migrated before we reverted # klp_target_state. klp_update_patch_state() # could run in parallel but it will do the same # what we do, clear TIF flag and keep the patch_state # as is
# => it is safe to clear it

I agree that this is complex like hell. But it also allows use to check that things work as we expect.

If we always set the flag here and always clear it later, we might hide a bug.

If we want to make it slightly more straightforward, we might clear TIF flags in klp_reverse_transaction() before we revert klp_target_state. The later rcu_synchronize() should make sure that all migrations are finished and non-will run in parallel. Then we could set the TIF flag only where needed here.

Quoted 14 lines
Quoted 5 lines
Quoted 5 lines
kernel/livepatch/transition.c new file +5 -0
+	read_unlock(&tasklist_lock);
+
+	/*
+	 * Ditto for the idle "swapper" tasks, though they never cross the
+	 * syscall barrier.  Instead they switch over in cpu_idle_loop().
Quoted 8 lines

kernel/livepatch/transition.c line 185

Quoted 5 lines
kernel/livepatch/transition.c new file +5 -0
+	 */
+	get_online_cpus();
+	for_each_online_cpu(cpu)
+		set_tsk_thread_flag(idle_task(cpu), TIF_PATCH_PENDING);
+	put_online_cpus();

Also this stage need to be somehow handled by CPU coming/going handlers.

Quoted 2 lines

Here I think we could automatically switch any offline CPUs' idle tasks. And something similar in klp_try_complete_transition().

We still need to make sure to do not race with the cpu_up()/cpu_down() calls.

I would use here the trick with for_each_possible_cpu() and let the migration for the stack check.

Quoted 38 lines
Quoted 38 lines
Quoted 9 lines
kernel/livepatch/transition.c new file +9 -0
+}
+
+/*
+ * The transition to the target patch state is complete.  Clean up the data
+ * structures.
+ */
+void klp_complete_transition(void)
+{
+	struct klp_object *obj;

kernel/livepatch/transition.c line 204

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+	struct klp_func *func;
+	struct task_struct *g, *task;
+	unsigned int cpu;
+
+	if (klp_transition_patch->immediate)
+		goto done;
+
+	klp_for_each_object(klp_transition_patch, obj)
+		klp_for_each_func(obj, func)
+			func->transition = false;

We should call rcu_synchronize() here. Otherwise, there might be a race, see below:

CPU1 CPU2

klp_ftrace_handler()
if (unlikely(func->transition))

	// still true

					klp_complete_transition()
					  func->transition = false;
					  task->patch_state =
					      KLP_UNDEFINED;

     patch_state = current->patch_state;

     WARN_ON(patch_state == KLP_UNDEFINED);
Quoted 7 lines
Quoted 1 line

BANG!: We print the warning.

This shouldn't be possible because klp_try_complete_transition() calls rcu_synchronize() before calling klp_complete_transition(). So by the time klp_complete_transition() is called, the ftrace handler can no longer see the affected func. See the comment for rcu_synchronize() in klp_try_complete_transition().

But rcu_synchronize() in klp_try_complete_transition() will help only when the patch is being disabled. The ftrace handler will still see this function and race when the patch is being enabled.

But you are partially right. We need the rcu_synchronize() here only when the patch is being enabled. It actually matches my comments in klp_try_complete_transition() where I suggested to call it only when the patch is being removed.

Quoted 27 lines
Quoted 27 lines

Note that that smp_wmb() is enough in klp_init_transition() but it is not enough here. We need to wait longer once someone might be inside the if (true) code.

kernel/livepatch/transition.c line 216

Quoted 11 lines
kernel/livepatch/transition.c new file +11 -0
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, task) {
+		clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
+		task->patch_state = KLP_UNDEFINED;
+	}
+	read_unlock(&tasklist_lock);
+
+	get_online_cpus();
+	for_each_online_cpu(cpu) {
+		task = idle_task(cpu);
+		clear_tsk_thread_flag(task, TIF_PATCH_PENDING);

If TIF_PATCH_PENDING flag is set here it means that klp_update_patch_state() might get triggered and it might put wrong value into task->patch_state.

We must make sure that all task have this cleared before calling this function. This is another reason why klp_init_transition() should set the flag only when transition is needed.

We should only check the state here.

Quoted 7 lines
Quoted 4 lines

It still might make sense to clear it when it is set wrongly. But the question is if it is really safe to continue. I am afraid that it is not. It would mean that the consistency model is broken and we are in strange state.

As I mentioned above, with your proposal I think there could still be a task with a spurious set TIF_PATCH_PENDING at this point.

I believe that it could not be here if we add that rcu_synchronize() into klp_reverse_transition().

Quoted 2 lines

Maybe instead we should clear all the TIF_PATCH_PENDING flags before the synchronize_rcu() in klp_try_complete_transition().

It might work. But I believe that we do not need this. If we do it, we might hide a bug.

Quoted 86 lines
Quoted 77 lines
Quoted 8 lines
kernel/livepatch/transition.c new file +8 -0
+		task->patch_state = KLP_UNDEFINED;
+	}
+	put_online_cpus();
+
+done:
+	klp_target_state = KLP_UNDEFINED;
+	klp_transition_patch = NULL;
+}

[...]

Quoted 66 lines
kernel/livepatch/transition.c new file +66 -0
+
+/*
+ * Try to switch all remaining tasks to the target patch state by walking the
+ * stacks of sleeping tasks and looking for any to-be-patched or
+ * to-be-unpatched functions.  If such functions are found, the task can't be
+ * switched yet.
+ *
+ * If any tasks are still stuck in the initial patch state, schedule a retry.
+ */
+bool klp_try_complete_transition(void)
+{
+	unsigned int cpu;
+	struct task_struct *g, *task;
+	bool complete = true;
+
+	WARN_ON_ONCE(klp_target_state == KLP_UNDEFINED);
+
+	/*
+	 * If the patch can be applied or reverted immediately, skip the
+	 * per-task transitions.
+	 */
+	if (klp_transition_patch->immediate)
+		goto success;
+
+	/*
+	 * Try to switch the tasks to the target patch state by walking their
+	 * stacks and looking for any to-be-patched or to-be-unpatched
+	 * functions.  If such functions are found on a stack, or if the stack
+	 * is deemed unreliable, the task can't be switched yet.
+	 *
+	 * Usually this will transition most (or all) of the tasks on a system
+	 * unless the patch includes changes to a very common function.
+	 */
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, task)
+		if (!klp_try_switch_task(task))
+			complete = false;
+	read_unlock(&tasklist_lock);
+
+	/*
+	 * Ditto for the idle "swapper" tasks.
+	 */
+	get_online_cpus();
+	for_each_online_cpu(cpu)
+		if (!klp_try_switch_task(idle_task(cpu)))
+			complete = false;
+	put_online_cpus();
+
+	/*
+	 * Some tasks weren't able to be switched over.  Try again later and/or
+	 * wait for other methods like syscall barrier switching.
+	 */
+	if (!complete)
+		return false;
+
+success:
+
+	/*
+	 * When unpatching, all tasks have transitioned to KLP_UNPATCHED so we
+	 * can now remove the new functions from the func_stack.
+	 */
+	if (klp_target_state == KLP_UNPATCHED)
+		klp_unpatch_objects(klp_transition_patch);
+
+	/*
+	 * Wait for all RCU read-side critical sections to complete.
Quoted 8 lines

kernel/livepatch/transition.c line 439

Quoted 6 lines
kernel/livepatch/transition.c new file +6 -0
+	 *
+	 * This has two purposes:
+	 *
+	 * 1) Ensure all existing critical sections in klp_update_patch_state()
+	 *    complete, so task->patch_state won't be unexpectedly updated
+	 *    later.

We should not be here if anyone still might be in klp_update_patch_state().

Quoted 1 line

Depends on our discussion about conditionally setting TIF_PATCH_PENDING.

Yup.

Quoted 17 lines
Quoted 11 lines

kernel/livepatch/transition.c line 446

Quoted 7 lines
kernel/livepatch/transition.c new file +7 -0
+	 *
+	 * 2) When unpatching, don't allow any existing instances of
+	 *    klp_ftrace_handler() to access any obsolete funcs before we reset
+	 *    the func transition states to false.  Otherwise the handler may
+	 *    see the deleted "new" func, see that it's not in transition, and
+	 *    wrongly pick the new version of the function.
+	 */

This makes sense but it too me long time to understand. I wonder if this might be better:

Quoted 5 lines

/*
* Make sure that the function is removed from ops->func_stack
* before we clear func->transition. Otherwise the handler may
* pick the wrong version.
*/

Quoted 8 lines

Sounds good.

Quoted 4 lines

And I would call this only when the patch is being removed

	if (klp_target_state = KLP_UNPATCHED)
		synchronize_rcu();

Depends on our discussion about conditionally setting TIF_PATCH_PENDING.

And yup.

Quoted 73 lines
Quoted 73 lines

I think that this was the reason to remove WARN_ON_ONCE(!func) in klp_ftrace_handler(). But this is not related. If this was the last entry in the list, we removed the ftrace_handler before removing the last entry. And unregister_ftrace_function() calls rcu_synchronize() to prevent calling the handler later.

Quoted 19 lines
kernel/livepatch/transition.c new file +19 -0
+	synchronize_rcu();
+
+	pr_notice("'%s': %s complete\n", klp_transition_patch->mod->name,
+		  klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
+
+	/* we're done, now cleanup the data structures */
+	klp_complete_transition();
+
+	return true;
+}
+
+/*
+ * This function can be called in the middle of an existing transition to
+ * reverse the direction of the target patch state.  This can be done to
+ * effectively cancel an existing enable or disable operation if there are any
+ * tasks which are stuck in the initial patch state.
+ */
+void klp_reverse_transition(void)
+{

kernel/livepatch/transition.c line 475

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+	klp_transition_patch->enabled = !klp_transition_patch->enabled;
+
+	klp_target_state = !klp_target_state;
+
+	/*
+	 * Enforce the order of the write to klp_target_state above and the
+	 * TIF_PATCH_PENDING writes in klp_start_transition() to ensure that
+	 * klp_update_patch_state() doesn't set a wrong task->patch_state.
+	 */
+	smp_wmb();

I would call rcu_synchronize() here to make sure that klp_update_patch_state() calls will not set an outdated task->patch_state.

Note that smp_wmb() is not enough. We do not check TIF_PATCH_PENDING in klp_try_switch_task(). There is a tiny race:

CPU1 CPU2

klp_update_patch_state()

	if (test_and clear(task, TIF)
	     READ_ONCE(klp_target_state);

					mutex_lock(klp_lock);

					klp_reverse_transition()
					  klp_target_state =
					      !klp_target_state;

					  klp_start_transition()

					mutex_unlock(klp_lock);

					 <switch to another process>

					 klp_transition_work_fn()
					   mutex_lock(klp_lock);
					   klp_try_complete_transition()
					     klp_try_switch_task()
					       if (task->patch_state ==
						   klp_target_state)
						  return true;

	    task->patch_state = <outdated_value>;
Quoted 8 lines
Quoted 6 lines

klp_ftrace_handler()

BANG: klp_ftrace_handler() will use wrong implementation according
to the outdated task->patch_state. At the same time, klp_transition() is not blocked by the task because it thinks that it has a correct state.

Good find!

This is important in the puzzle.

Quoted 32 lines
Quoted 21 lines
Quoted 21 lines
kernel/livepatch/transition.c new file +4 -0
+
+	klp_start_transition();
+}
+
samples/livepatch/livepatch-sample.c +2 -0
index e34f871..bb61c65 100644
@@ -17,6 +17,8 @@
  * along with this program; if not, see <http://www.gnu.org/licenses/>.
  */
 
+#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+
 #include <linux/module.h>
 #include <linux/kernel.h>
 #include <linux/livepatch.h>
@@ -69,6 +71,11 @@ static int livepatch_init(void)
 {
 	int ret;
 
Quoted 10 lines

samples/livepatch/livepatch-sample.c static int livepatch_init(void) · line 77

Quoted 4 lines
samples/livepatch/livepatch-sample.c +4 -0
+	if (!klp_have_reliable_stack() && !patch.immediate) {
+		pr_notice("disabling consistency model!\n");
+		patch.immediate = true;
+	}

I am scared to have this in the sample module. It makes sense to use the consistency model even for immediate patches because it allows to remove them. But this must not be used for patches that really require the consistency model. We should add a big fat warning at least.

Quoted 8 lines

I did this so that the sample module would still work for non-x86_64 arches, for which there's currently no way to patch kthreads.

Notice I did add a warning:

  pr_notice("disabling consistency model!\n");

Is the warning not fat enough?

The warning does not explain who did it, why, if it is safe, and when this could be used. I suggest a comment like:

/*
* WARNING: Use this check only when you know what you do!
*
* This sample patch does not change the semantic of the data structures,
* locks, or return adresses. It is safe to be applied immediately.
* But we want to test and use the consistency model on supported
* architectures. It allows to remove the patch module.
*
* See Documentation/livepatch/livepatch.txt for more details, please. */

Also the message might be more explicit.

pr_notice("livepatch-sample: The consistency model is not supported on this architecture. Using the immediate model that is safe enough.\n");

Alternatively, we might allow more values for patch.immediate, e.g.

enum klp_consistency_model {
KLP_CM_IMMEDIATE,
KLP_CM_TASK,
KLP_CM_TASK_OR_IMMEDIATE,
};

Then we could do the decision on the kernel side. But I am not sure if this would be widely used and it it is worth the complication.

Best Regards,
Petr

PS: Merry Christmas and happy new year!

I am not sure if I will be able to do another deep dive into this code until next year.

#53 lore raw

Re: [PATCH v3 13/15] livepatch: change to a per-task consistency model

Quoted 75 lines · Petr Mladek
Quoted 68 lines · Josh Poimboeuf
Quoted 58 lines · Petr Mladek
Quoted 57 lines · Josh Poimboeuf

Change livepatch to use a basic per-task consistency model. This is the foundation which will eventually enable us to patch those ~10% of security patches which change function or data semantics. This is the biggest remaining piece needed to make livepatch more generally useful.

[1] https://lkml.kernel.org/r/[email protected]

kernel/livepatch/transition.c new file +48 -0
+/*
+ * Initialize the global target patch state and all tasks to the initial patch
+ * state, and initialize all function transition states to true in preparation
+ * for patching or unpatching.
+ */
+void klp_init_transition(struct klp_patch *patch, int state)
+{
+	struct task_struct *g, *task;
+	unsigned int cpu;
+	struct klp_object *obj;
+	struct klp_func *func;
+	int initial_state = !state;
+
+	WARN_ON_ONCE(klp_target_state != KLP_UNDEFINED);
+
+	klp_transition_patch = patch;
+
+	/*
+	 * Set the global target patch state which tasks will switch to.  This
+	 * has no effect until the TIF_PATCH_PENDING flags get set later.
+	 */
+	klp_target_state = state;
+
+	/*
+	 * If the patch can be applied or reverted immediately, skip the
+	 * per-task transitions.
+	 */
+	if (patch->immediate)
+		return;
+
+	/*
+	 * Initialize all tasks to the initial patch state to prepare them for
+	 * switching to the target state.
+	 */
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, task) {
+		WARN_ON_ONCE(task->patch_state != KLP_UNDEFINED);
+		task->patch_state = initial_state;
+	}
+	read_unlock(&tasklist_lock);
+
+	/*
+	 * Ditto for the idle "swapper" tasks.
+	 */
+	get_online_cpus();
+	for_each_online_cpu(cpu) {
+		task = idle_task(cpu);
+		WARN_ON_ONCE(task->patch_state != KLP_UNDEFINED);
Quoted 8 lines

kernel/livepatch/transition.c line 121

Quoted 3 lines
kernel/livepatch/transition.c new file +3 -0
+		task->patch_state = initial_state;
+	}
+	put_online_cpus();

We allow to add/remove CPUs here. I am afraid that we will also need to add a cpu coming/going handler that will set the task->patch_state the right way. We must not set the klp_target_state until all ftrace handlers are ready.

Quoted 2 lines

What if we instead just change the above to use for_each_possible_cpu()? We could do the same in klp_complete_transition().

I like this idea. It seems that there is idle task for each possible cpu, see idle_threads_init().

Quoted 6 lines

IMHO, we should do the same everytime we do anything with the idle tasks. I mean in klp_start_transition, klp_try_complete_transition() and also complete_transition().

Then they will be handled like any other processes and we do not need to think of any special races.

More on this below.

Quoted 106 lines
Quoted 70 lines
Quoted 58 lines
Quoted 43 lines
kernel/livepatch/transition.c new file +43 -0
+	/*
+	 * Enforce the order of the task->patch_state initializations and the
+	 * func->transition updates to ensure that, in the enable path,
+	 * klp_ftrace_handler() doesn't see a func in transition with a
+	 * task->patch_state of KLP_UNDEFINED.
+	 */
+	smp_wmb();
+
+	/*
+	 * Set the func transition states so klp_ftrace_handler() will know to
+	 * switch to the transition logic.
+	 *
+	 * When patching, the funcs aren't yet in the func_stack and will be
+	 * made visible to the ftrace handler shortly by the calls to
+	 * klp_patch_object().
+	 *
+	 * When unpatching, the funcs are already in the func_stack and so are
+	 * already visible to the ftrace handler.
+	 */
+	klp_for_each_object(patch, obj)
+		klp_for_each_func(obj, func)
+			func->transition = true;
+}
+
+/*
+ * Start the transition to the specified target patch state so tasks can begin
+ * switching to it.
+ */
+void klp_start_transition(void)
+{
+	struct task_struct *g, *task;
+	unsigned int cpu;
+
+	WARN_ON_ONCE(klp_target_state == KLP_UNDEFINED);
+
+	pr_notice("'%s': %s...\n", klp_transition_patch->mod->name,
+		  klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
+
+	/*
+	 * If the patch can be applied or reverted immediately, skip the
+	 * per-task transitions.
+	 */
+	if (klp_transition_patch->immediate)

kernel/livepatch/transition.c line 175

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+		return;
+
+	/*
+	 * Mark all normal tasks as needing a patch state update.  As they pass
+	 * through the syscall barrier they'll switch over to the target state
+	 * (unless we switch them in klp_try_complete_transition() first).
+	 */
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, task)
+		set_tsk_thread_flag(task, TIF_PATCH_PENDING);

This is called also from klp_reverse_transition(). We should set it only when the task need migration. Also we should clear it when the task is in the right state already.

Quoted 2 lines

It is not only optimization. It actually solves a race between klp_complete_transition() and klp_update_patch_state(), see below.

I agree about the race, but if I did:

	for_each_process_thread(g, task) {
		if (task->patch_state != klp_target_state)
			set_tsk_thread_flag(task, TIF_PATCH_PENDING);
		else
			clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
	}
Quoted 3 lines

It would still leave a small window where TIF_PATCH_PENDING gets set for an already patched task, if klp_update_patch_state() is running at the same time.

I see your point. Well, it seems that it is more complicated:

The race would be possible only when this was called from klp_reverse_transition(). But we need to call there rcu_synchronize() to prevent races with klp_update_patch_state() also to prevent prelimitary patch completion.

The result is:

if (task->patch_state != klp_target_state) {
# it means that the task was already migrated before # we reverted klp_target_state. It means that # the TIF flag was already cleared, the related # klp_update_patch_state() already finished (thanks # to rcu_synchronize() and new one will be called # only when we set the flag again
# => it is safe to set it

# we should also check and warn when the TIF flag # was not clear before we set it here

else

# the task was not migrated before we reverted # klp_target_state. klp_update_patch_state() # could run in parallel but it will do the same # what we do, clear TIF flag and keep the patch_state # as is
# => it is safe to clear it

Quoted 2 lines

I agree that this is complex like hell. But it also allows use to check that things work as we expect.

Ouch. I agree that it seems safe but it's way too hard to reason about. And then it gets worse if you try to think about what happens when adding another reverse operation.

Quoted 9 lines

If we always set the flag here and always clear it later, we might hide a bug.

If we want to make it slightly more straightforward, we might clear TIF flags in klp_reverse_transaction() before we revert klp_target_state. The later rcu_synchronize() should make sure that all migrations are finished and non-will run in parallel. Then we could set the TIF flag only where needed here.

I think this last paragraph is important. It would simplify things greatly and ensure we won't have klp_update_patch_state() changing things in the background.

Quoted 14 lines
Quoted 14 lines
Quoted 13 lines

kernel/livepatch/transition.c line 185

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+	read_unlock(&tasklist_lock);
+
+	/*
+	 * Ditto for the idle "swapper" tasks, though they never cross the
+	 * syscall barrier.  Instead they switch over in cpu_idle_loop().
+	 */
+	get_online_cpus();
+	for_each_online_cpu(cpu)
+		set_tsk_thread_flag(idle_task(cpu), TIF_PATCH_PENDING);
+	put_online_cpus();

Also this stage need to be somehow handled by CPU coming/going handlers.

Quoted 5 lines
Quoted 2 lines

Here I think we could automatically switch any offline CPUs' idle tasks. And something similar in klp_try_complete_transition().

We still need to make sure to do not race with the cpu_up()/cpu_down() calls.

Hm, maybe we'd need to call cpu_hotplug_disable() before switching the offline idle tasks?

Quoted 2 lines

I would use here the trick with for_each_possible_cpu() and let the migration for the stack check.

There are a few issues with that:

1) The idle task of a missing CPU doesn't *have* a stack, so it doesn't make much sense to try to check it.

2) We can't rely *only* on the stack check, because not all arches have it. The other way to migrate idle tasks is from the idle loop switch point. But if the task's CPU is down, its idle loop isn't running so it can't migrate.

(Note this is currently a theoretical point: we currently don't allow such arches to use the consistency model anyway because there's no way for them to migrate kthreads.)

Quoted 46 lines
Quoted 38 lines
Quoted 38 lines
Quoted 9 lines
kernel/livepatch/transition.c new file +9 -0
+}
+
+/*
+ * The transition to the target patch state is complete.  Clean up the data
+ * structures.
+ */
+void klp_complete_transition(void)
+{
+	struct klp_object *obj;

kernel/livepatch/transition.c line 204

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+	struct klp_func *func;
+	struct task_struct *g, *task;
+	unsigned int cpu;
+
+	if (klp_transition_patch->immediate)
+		goto done;
+
+	klp_for_each_object(klp_transition_patch, obj)
+		klp_for_each_func(obj, func)
+			func->transition = false;

We should call rcu_synchronize() here. Otherwise, there might be a race, see below:

CPU1 CPU2

klp_ftrace_handler()
if (unlikely(func->transition))

	// still true

					klp_complete_transition()
					  func->transition = false;
					  task->patch_state =
					      KLP_UNDEFINED;

     patch_state = current->patch_state;

     WARN_ON(patch_state == KLP_UNDEFINED);
Quoted 7 lines
Quoted 1 line

BANG!: We print the warning.

This shouldn't be possible because klp_try_complete_transition() calls rcu_synchronize() before calling klp_complete_transition(). So by the time klp_complete_transition() is called, the ftrace handler can no longer see the affected func. See the comment for rcu_synchronize() in klp_try_complete_transition().

Quoted 8 lines

But rcu_synchronize() in klp_try_complete_transition() will help only when the patch is being disabled. The ftrace handler will still see this function and race when the patch is being enabled.

But you are partially right. We need the rcu_synchronize() here only when the patch is being enabled. It actually matches my comments in klp_try_complete_transition() where I suggested to call it only when the patch is being removed.

Sorry, for some reason I think I saw KLP_UNPATCHED in your example instead of KLP_UNDEFINED. I get it now.

Quoted 303 lines
Quoted 27 lines
Quoted 27 lines

Note that that smp_wmb() is enough in klp_init_transition() but it is not enough here. We need to wait longer once someone might be inside the if (true) code.

kernel/livepatch/transition.c line 216

Quoted 11 lines
kernel/livepatch/transition.c new file +11 -0
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, task) {
+		clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
+		task->patch_state = KLP_UNDEFINED;
+	}
+	read_unlock(&tasklist_lock);
+
+	get_online_cpus();
+	for_each_online_cpu(cpu) {
+		task = idle_task(cpu);
+		clear_tsk_thread_flag(task, TIF_PATCH_PENDING);

If TIF_PATCH_PENDING flag is set here it means that klp_update_patch_state() might get triggered and it might put wrong value into task->patch_state.

We must make sure that all task have this cleared before calling this function. This is another reason why klp_init_transition() should set the flag only when transition is needed.

We should only check the state here.

Quoted 7 lines
Quoted 4 lines

It still might make sense to clear it when it is set wrongly. But the question is if it is really safe to continue. I am afraid that it is not. It would mean that the consistency model is broken and we are in strange state.

As I mentioned above, with your proposal I think there could still be a task with a spurious set TIF_PATCH_PENDING at this point.

I believe that it could not be here if we add that rcu_synchronize() into klp_reverse_transition().

Quoted 2 lines

Maybe instead we should clear all the TIF_PATCH_PENDING flags before the synchronize_rcu() in klp_try_complete_transition().

It might work. But I believe that we do not need this. If we do it, we might hide a bug.

Quoted 86 lines
Quoted 77 lines
Quoted 8 lines
kernel/livepatch/transition.c new file +8 -0
+		task->patch_state = KLP_UNDEFINED;
+	}
+	put_online_cpus();
+
+done:
+	klp_target_state = KLP_UNDEFINED;
+	klp_transition_patch = NULL;
+}

[...]

Quoted 66 lines
kernel/livepatch/transition.c new file +66 -0
+
+/*
+ * Try to switch all remaining tasks to the target patch state by walking the
+ * stacks of sleeping tasks and looking for any to-be-patched or
+ * to-be-unpatched functions.  If such functions are found, the task can't be
+ * switched yet.
+ *
+ * If any tasks are still stuck in the initial patch state, schedule a retry.
+ */
+bool klp_try_complete_transition(void)
+{
+	unsigned int cpu;
+	struct task_struct *g, *task;
+	bool complete = true;
+
+	WARN_ON_ONCE(klp_target_state == KLP_UNDEFINED);
+
+	/*
+	 * If the patch can be applied or reverted immediately, skip the
+	 * per-task transitions.
+	 */
+	if (klp_transition_patch->immediate)
+		goto success;
+
+	/*
+	 * Try to switch the tasks to the target patch state by walking their
+	 * stacks and looking for any to-be-patched or to-be-unpatched
+	 * functions.  If such functions are found on a stack, or if the stack
+	 * is deemed unreliable, the task can't be switched yet.
+	 *
+	 * Usually this will transition most (or all) of the tasks on a system
+	 * unless the patch includes changes to a very common function.
+	 */
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, task)
+		if (!klp_try_switch_task(task))
+			complete = false;
+	read_unlock(&tasklist_lock);
+
+	/*
+	 * Ditto for the idle "swapper" tasks.
+	 */
+	get_online_cpus();
+	for_each_online_cpu(cpu)
+		if (!klp_try_switch_task(idle_task(cpu)))
+			complete = false;
+	put_online_cpus();
+
+	/*
+	 * Some tasks weren't able to be switched over.  Try again later and/or
+	 * wait for other methods like syscall barrier switching.
+	 */
+	if (!complete)
+		return false;
+
+success:
+
+	/*
+	 * When unpatching, all tasks have transitioned to KLP_UNPATCHED so we
+	 * can now remove the new functions from the func_stack.
+	 */
+	if (klp_target_state == KLP_UNPATCHED)
+		klp_unpatch_objects(klp_transition_patch);
+
+	/*
+	 * Wait for all RCU read-side critical sections to complete.
Quoted 8 lines

kernel/livepatch/transition.c line 439

Quoted 6 lines
kernel/livepatch/transition.c new file +6 -0
+	 *
+	 * This has two purposes:
+	 *
+	 * 1) Ensure all existing critical sections in klp_update_patch_state()
+	 *    complete, so task->patch_state won't be unexpectedly updated
+	 *    later.

We should not be here if anyone still might be in klp_update_patch_state().

Quoted 1 line

Depends on our discussion about conditionally setting TIF_PATCH_PENDING.

Yup.

Quoted 17 lines
Quoted 11 lines

kernel/livepatch/transition.c line 446

Quoted 7 lines
kernel/livepatch/transition.c new file +7 -0
+	 *
+	 * 2) When unpatching, don't allow any existing instances of
+	 *    klp_ftrace_handler() to access any obsolete funcs before we reset
+	 *    the func transition states to false.  Otherwise the handler may
+	 *    see the deleted "new" func, see that it's not in transition, and
+	 *    wrongly pick the new version of the function.
+	 */

This makes sense but it too me long time to understand. I wonder if this might be better:

Quoted 5 lines

/*
* Make sure that the function is removed from ops->func_stack
* before we clear func->transition. Otherwise the handler may
* pick the wrong version.
*/

Quoted 8 lines

Sounds good.

Quoted 4 lines

And I would call this only when the patch is being removed

	if (klp_target_state = KLP_UNPATCHED)
		synchronize_rcu();

Depends on our discussion about conditionally setting TIF_PATCH_PENDING.

And yup.

Quoted 73 lines
Quoted 73 lines

I think that this was the reason to remove WARN_ON_ONCE(!func) in klp_ftrace_handler(). But this is not related. If this was the last entry in the list, we removed the ftrace_handler before removing the last entry. And unregister_ftrace_function() calls rcu_synchronize() to prevent calling the handler later.

Quoted 19 lines
kernel/livepatch/transition.c new file +19 -0
+	synchronize_rcu();
+
+	pr_notice("'%s': %s complete\n", klp_transition_patch->mod->name,
+		  klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
+
+	/* we're done, now cleanup the data structures */
+	klp_complete_transition();
+
+	return true;
+}
+
+/*
+ * This function can be called in the middle of an existing transition to
+ * reverse the direction of the target patch state.  This can be done to
+ * effectively cancel an existing enable or disable operation if there are any
+ * tasks which are stuck in the initial patch state.
+ */
+void klp_reverse_transition(void)
+{

kernel/livepatch/transition.c line 475

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+	klp_transition_patch->enabled = !klp_transition_patch->enabled;
+
+	klp_target_state = !klp_target_state;
+
+	/*
+	 * Enforce the order of the write to klp_target_state above and the
+	 * TIF_PATCH_PENDING writes in klp_start_transition() to ensure that
+	 * klp_update_patch_state() doesn't set a wrong task->patch_state.
+	 */
+	smp_wmb();

I would call rcu_synchronize() here to make sure that klp_update_patch_state() calls will not set an outdated task->patch_state.

Note that smp_wmb() is not enough. We do not check TIF_PATCH_PENDING in klp_try_switch_task(). There is a tiny race:

CPU1 CPU2

klp_update_patch_state()

	if (test_and clear(task, TIF)
	     READ_ONCE(klp_target_state);

					mutex_lock(klp_lock);

					klp_reverse_transition()
					  klp_target_state =
					      !klp_target_state;

					  klp_start_transition()

					mutex_unlock(klp_lock);

					 <switch to another process>

					 klp_transition_work_fn()
					   mutex_lock(klp_lock);
					   klp_try_complete_transition()
					     klp_try_switch_task()
					       if (task->patch_state ==
						   klp_target_state)
						  return true;

	    task->patch_state = <outdated_value>;
Quoted 8 lines
Quoted 6 lines

klp_ftrace_handler()

BANG: klp_ftrace_handler() will use wrong implementation according
to the outdated task->patch_state. At the same time, klp_transition() is not blocked by the task because it thinks that it has a correct state.

Good find!

This is important in the puzzle.

Quoted 32 lines
Quoted 21 lines
Quoted 21 lines
kernel/livepatch/transition.c new file +4 -0
+
+	klp_start_transition();
+}
+
samples/livepatch/livepatch-sample.c +2 -0
index e34f871..bb61c65 100644
@@ -17,6 +17,8 @@
  * along with this program; if not, see <http://www.gnu.org/licenses/>.
  */
 
+#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+
 #include <linux/module.h>
 #include <linux/kernel.h>
 #include <linux/livepatch.h>
@@ -69,6 +71,11 @@ static int livepatch_init(void)
 {
 	int ret;
 
Quoted 10 lines

samples/livepatch/livepatch-sample.c static int livepatch_init(void) · line 77

Quoted 4 lines
samples/livepatch/livepatch-sample.c +4 -0
+	if (!klp_have_reliable_stack() && !patch.immediate) {
+		pr_notice("disabling consistency model!\n");
+		patch.immediate = true;
+	}

I am scared to have this in the sample module. It makes sense to use the consistency model even for immediate patches because it allows to remove them. But this must not be used for patches that really require the consistency model. We should add a big fat warning at least.

Quoted 8 lines

I did this so that the sample module would still work for non-x86_64 arches, for which there's currently no way to patch kthreads.

Notice I did add a warning:

  pr_notice("disabling consistency model!\n");

Is the warning not fat enough?

The warning does not explain who did it, why, if it is safe, and when this could be used. I suggest a comment like:

/*
* WARNING: Use this check only when you know what you do!
*
* This sample patch does not change the semantic of the data structures,
* locks, or return adresses. It is safe to be applied immediately.
* But we want to test and use the consistency model on supported
* architectures. It allows to remove the patch module.
*
* See Documentation/livepatch/livepatch.txt for more details, please. */

Quoted 4 lines

Also the message might be more explicit.

pr_notice("livepatch-sample: The consistency model is not supported on this architecture. Using the immediate model that is safe enough.\n");

Ok, will try to do something like that.

Quoted 11 lines

Alternatively, we might allow more values for patch.immediate, e.g.

enum klp_consistency_model {
KLP_CM_IMMEDIATE,
KLP_CM_TASK,
KLP_CM_TASK_OR_IMMEDIATE,
};

Then we could do the decision on the kernel side. But I am not sure if this would be widely used and it it is worth the complication.

I'd rather avoid that :-)

Quoted 4 lines

PS: Merry Christmas and happy new year!

I am not sure if I will be able to do another deep dive into this code until next year.

Same here, I won't be around much until 2017. Cheers!

Signature · 1 line
Josh
maintainer
#58 lore raw

Re: [PATCH v3 13/15] livepatch: change to a per-task consistency model

In reply to Josh Poimboeuf
Quoted 35 lines
Quoted 35 lines
Quoted 18 lines
kernel/livepatch/patch.c +2 -0
index 5efa262..e79ebb5 100644
@@ -29,6 +29,7 @@
 #include <linux/bug.h>
 #include <linux/printk.h>
 #include "patch.h"
+#include "transition.h"
 
 static LIST_HEAD(klp_ops);
 
@@ -54,15 +55,53 @@ static void notrace klp_ftrace_handler(unsigned long ip,
 {
 	struct klp_ops *ops;
 	struct klp_func *func;
+	int patch_state;
 

kernel/livepatch/patch.c static void notrace klp_ftrace_handler(unsigned long ip, · line 68

Quoted 10 lines
kernel/livepatch/patch.c +3 -1
 	ops = container_of(fops, struct klp_ops, fops);
 
 	rcu_read_lock();
+
 	func = list_first_or_null_rcu(&ops->func_stack, struct klp_func,
 				      stack_node);
-	if (WARN_ON_ONCE(!func))
+
+	if (!func)
 		goto unlock;

Why do you removed the WARN_ON_ONCE(), please?

We still add the function on the stack before registering the ftrace handler. Also we unregister the ftrace handler before removing the the last entry from the stack.

Quoted 5 lines
Quoted 3 lines

AFAIK, unregister_ftrace_function() calls rcu_synchronize()' to make sure that no-one is inside the handler once finished. Mirek knows more about it.

Hm, this is news to me. Mirek, please share :-)

Well, I think the whole thing is well described in emails I exchanged with Steven few months ago. See [1].

[1] http://lkml.kernel.org/r/[email protected]

Quoted 4 lines
Quoted 2 lines

If this is not true, we have a problem. For example, we call kfree(ops) after unregister_ftrace_function();

Agreed.

TL;DR - we should be ok as long as we do not do crazy things in the handler, deliberate sleeping for example.

WARN_ON_ONCE() may be crazy too. I think we discussed it long ago and we came to an agreement to remove it.

Miroslav, very slowly going through the patch set

maintainer
#59 lore raw

Re: [PATCH v3 13/15] livepatch: change to a per-task consistency model

Quoted 49 lines · Miroslav Benes
Quoted 35 lines
Quoted 35 lines
Quoted 18 lines
kernel/livepatch/patch.c +2 -0
index 5efa262..e79ebb5 100644
@@ -29,6 +29,7 @@
 #include <linux/bug.h>
 #include <linux/printk.h>
 #include "patch.h"
+#include "transition.h"
 
 static LIST_HEAD(klp_ops);
 
@@ -54,15 +55,53 @@ static void notrace klp_ftrace_handler(unsigned long ip,
 {
 	struct klp_ops *ops;
 	struct klp_func *func;
+	int patch_state;
 

kernel/livepatch/patch.c static void notrace klp_ftrace_handler(unsigned long ip, · line 68

Quoted 10 lines
kernel/livepatch/patch.c +3 -1
 	ops = container_of(fops, struct klp_ops, fops);
 
 	rcu_read_lock();
+
 	func = list_first_or_null_rcu(&ops->func_stack, struct klp_func,
 				      stack_node);
-	if (WARN_ON_ONCE(!func))
+
+	if (!func)
 		goto unlock;

Why do you removed the WARN_ON_ONCE(), please?

We still add the function on the stack before registering the ftrace handler. Also we unregister the ftrace handler before removing the the last entry from the stack.

Quoted 5 lines
Quoted 3 lines

AFAIK, unregister_ftrace_function() calls rcu_synchronize()' to make sure that no-one is inside the handler once finished. Mirek knows more about it.

Hm, this is news to me. Mirek, please share :-)

Well, I think the whole thing is well described in emails I exchanged with Steven few months ago. See [1].

[1] http://lkml.kernel.org/r/[email protected]

Quoted 3 lines
Quoted 2 lines

If this is not true, we have a problem. For example, we call kfree(ops) after unregister_ftrace_function();

Quoted 7 lines
Quoted 1 line

Agreed.

TL;DR - we should be ok as long as we do not do crazy things in the handler, deliberate sleeping for example.

WARN_ON_ONCE() may be crazy too. I think we discussed it long ago and we came to an agreement to remove it.

There are definitely situations where this might hurt. For example, when we redirect a function called under logbuf_lock.

On the other hand, there is a work in progress[1][2] that will mitigate this risk a lot. Also this warning would be printed only when something goes wrong. IMHO, it is worth the risk. It will succeed in 99,999% cases and it might save us some headache when debugging random crashes of the system.

Anyway, if there is a reason to remove the warning, it should be described. And if it is not strictly related to this patch, it should be handled separately.

[1] https://lkml.kernel.org/r/[email protected]
[2] https://lkml.kernel.org/r/[email protected]

Best Regards,
Petr

maintainer Acked-by on v3 8/15
#31 lore raw

Re: [PATCH v3 08/15] livepatch: separate enabled and patched states

In reply to Josh Poimboeuf
Quoted 13 lines · Josh Poimboeuf

Once we have a consistency model, patches and their objects will be enabled and disabled at different times. For example, when a patch is disabled, its loaded objects' funcs can remain registered with ftrace indefinitely until the unpatching operation is complete and they're no longer in use.

It's less confusing if we give them different names: patches can be enabled or disabled; objects (and their funcs) can be patched or unpatched:

- Enabled means that a patch is logically enabled (but not necessarily fully applied).

Quoted 7 lines

- Patched means that an object's funcs are registered with ftrace and added to the klp_ops func stack.

Also, since these states are binary, represent them with booleans instead of ints.

Miroslav

maintainer Acked-by on v3 9/15
#35 lore raw

Re: [PATCH v3 09/15] livepatch: remove unnecessary object loaded check

In reply to Josh Poimboeuf
Quoted 7 lines · Josh Poimboeuf

klp_patch_object()'s callers already ensure that the object is loaded, so its call to klp_is_object_loaded() is unnecessary.

This will also make it possible to move the patching code into a separate file.

Miroslav

maintainer Acked-by
#44 lore raw

Re: [PATCH v3 11/15] livepatch: use kstrtobool() in enabled_store()

In reply to Josh Poimboeuf
Quoted 29 lines · Josh Poimboeuf
Quoted 21 lines · Petr Mladek
Quoted 20 lines · Josh Poimboeuf

The sysfs enabled value is a boolean, so kstrtobool() is a better fit for parsing the input string since it does the range checking for us.

---
 kernel/livepatch/core.c | 11 ++++-------
 1 file changed, 4 insertions(+), 7 deletions(-)
kernel/livepatch/core.c +1 -1
index 6a137e1..8ca8a0e 100644
@@ -408,26 +408,23 @@ static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr,
 {
 	struct klp_patch *patch;
 	int ret;
-	unsigned long val;
+	bool enabled;
 
Quoted 6 lines

kernel/livepatch/core.c static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr, · line 415

Quoted 4 lines
kernel/livepatch/core.c +1 -1
-	ret = kstrtoul(buf, 10, &val);
+	ret = kstrtobool(buf, &enabled);
 	if (ret)
 		return -EINVAL;

I would return "ret" here. It is -EINVAL as well but... ;-)

Quoted 2 lines

That was a preexisting issue with the kstrtoul() return code, but I'll sneak your suggested change into this patch if nobody objects.

Fine with me.

Miroslav

maintainer
#62 lore raw

Re: [PATCH v3 13/15] livepatch: change to a per-task consistency model

In reply to Josh Poimboeuf
Quoted 20 lines · Josh Poimboeuf
kernel/livepatch/transition.c new file +20 -0
+void klp_start_transition(void)
+{
+	struct task_struct *g, *task;
+	unsigned int cpu;
+
+	WARN_ON_ONCE(klp_target_state == KLP_UNDEFINED);
+
+	pr_notice("'%s': %s...\n", klp_transition_patch->mod->name,
+		  klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
+
+	/*
+	 * If the patch can be applied or reverted immediately, skip the
+	 * per-task transitions.
+	 */
+	if (klp_transition_patch->immediate)
+		return;
+
+	/*
+	 * Mark all normal tasks as needing a patch state update.  As they pass
+	 * through the syscall barrier they'll switch over to the target state

kernel/livepatch/transition.c line 180

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+	 * (unless we switch them in klp_try_complete_transition() first).
+	 */
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, task)
+		set_tsk_thread_flag(task, TIF_PATCH_PENDING);
+	read_unlock(&tasklist_lock);
+
+	/*
+	 * Ditto for the idle "swapper" tasks, though they never cross the
+	 * syscall barrier.  Instead they switch over in cpu_idle_loop().

...or we switch them in klp_try_complete_transition() first by looking at their stacks, right? I would add it to the comment.

Quoted 6 lines
kernel/livepatch/transition.c new file +6 -0
+	 */
+	get_online_cpus();
+	for_each_online_cpu(cpu)
+		set_tsk_thread_flag(idle_task(cpu), TIF_PATCH_PENDING);
+	put_online_cpus();
+}

[...]

Quoted 11 lines
kernel/sched/idle.c +1 -0
@@ -9,6 +9,7 @@
 #include <linux/mm.h>
 #include <linux/stackprotector.h>
 #include <linux/suspend.h>
+#include <linux/livepatch.h>
 
 #include <asm/tlb.h>
 

kernel/sched/idle.c static void do_idle(void) · line 271

Quoted 7 lines
kernel/sched/idle.c +3 -0
@@ -264,6 +265,9 @@ static void do_idle(void)
 
 	sched_ttwu_pending();
 	schedule_preempt_disabled();
+
+	if (unlikely(klp_patch_pending(current)))
+		klp_update_patch_state(current);
 }

I think that (theoretically) this is not sufficient, if we patch a function present on an idle task's stack and one of the two following scenarios happen.

1. there is nothing to schedule on a cpu and an idle task does not leave a loop in do_idle() for some time. It may be a nonsense practically and if it is not we could solve with schedule_on_each_cpu() on an empty stub somewhere in our code.

2. there is a cpu-bound process running on one of the cpus. No chance of going to do_idle() there at all and the idle task would block the patching. We ran into it in kGraft and I tried to solve it with this new hunk in pick_next_task()...

+ /*
+ * Patching is in progress, schedule an idle task to migrate it
+ */
+ if (kgr_in_progress_branch()) {
+ if (!test_bit(0, kgr_immutable) &&
+ klp_kgraft_task_in_progress(rq->idle)) {
+ p = idle_sched_class.pick_next_task(rq, prev);
+
+ return p;
+ }
+ }

(kgr_in_progress_branch() is a static key basically. kgr_immutable flag solves something we don't have a problem with in upstream livepatch thanks to a combination of task->patch_state and klp_func->transition. klp_kgraft_task_in_progress() checks the livepatching TIF of a task.)

It is not tested properly and it is a hack as hell so take it as that. Also note that the problem in kGraft is more serious as we don't have a stack checking there. So any livepatch could cause the issue easily.

I can imagine even crazier solutions but nothing nice and pretty (which is probably impossible because the whole idea to deliberately schedule an idle task is not nice and pretty).

Otherwise the patch looks good to me. I don't understand how Petr found those races there.

Regards,
Miroslav

maintainer
#72 lore raw

Re: [PATCH v3 15/15] livepatch: allow removal of a disabled patch

In reply to Josh Poimboeuf

samples/livepatch/livepatch-sample.c static int livepatch_init(void) · line 93

Quoted 12 lines
samples/livepatch/livepatch-sample.c +0 -1
index bb61c65..0625f38 100644
@@ -89,7 +89,6 @@ static int livepatch_init(void)
 
 static void livepatch_exit(void)
 {
-	WARN_ON(klp_disable_patch(&patch));
 	WARN_ON(klp_unregister_patch(&patch));
 }

Btw, we remove the only call to klp_disable_patch() here. Maybe we can remove the function completely. It is not needed anywhere.

Miroslav

maintainer
#65 lore raw

Re: [PATCH v3 13/15] livepatch: change to a per-task consistency model

In reply to Josh Poimboeuf

kernel/livepatch/core.c int klp_register_patch(struct klp_patch *patch) · line 818

Quoted 12 lines
kernel/livepatch/core.c +7 -0
@@ -740,6 +809,14 @@ int klp_register_patch(struct klp_patch *patch)
 		return -ENODEV;
 
 	/*
+	 * Architectures without reliable stack traces have to set
+	 * patch->immediate because there's currently no way to patch kthreads
+	 * with the consistency model.
+	 */
+	if (!klp_have_reliable_stack() && !patch->immediate)
+		return -ENOSYS;
+

I think an error message (pr_err) would be appropriate here.

$ insmod patch_1.ko
insmod: ERROR: could not insert module patch_1.ko: Function not implemented

is not helpful much :)

Miroslav

#60 lore raw

Re: [PATCH v3 13/15] livepatch: change to a per-task consistency model

In reply to Petr Mladek
Quoted 67 lines · Petr Mladek
Quoted 49 lines · Miroslav Benes
Quoted 35 lines
Quoted 35 lines
Quoted 18 lines
kernel/livepatch/patch.c +2 -0
index 5efa262..e79ebb5 100644
@@ -29,6 +29,7 @@
 #include <linux/bug.h>
 #include <linux/printk.h>
 #include "patch.h"
+#include "transition.h"
 
 static LIST_HEAD(klp_ops);
 
@@ -54,15 +55,53 @@ static void notrace klp_ftrace_handler(unsigned long ip,
 {
 	struct klp_ops *ops;
 	struct klp_func *func;
+	int patch_state;
 

kernel/livepatch/patch.c static void notrace klp_ftrace_handler(unsigned long ip, · line 68

Quoted 10 lines
kernel/livepatch/patch.c +3 -1
 	ops = container_of(fops, struct klp_ops, fops);
 
 	rcu_read_lock();
+
 	func = list_first_or_null_rcu(&ops->func_stack, struct klp_func,
 				      stack_node);
-	if (WARN_ON_ONCE(!func))
+
+	if (!func)
 		goto unlock;

Why do you removed the WARN_ON_ONCE(), please?

We still add the function on the stack before registering the ftrace handler. Also we unregister the ftrace handler before removing the the last entry from the stack.

Quoted 5 lines
Quoted 3 lines

AFAIK, unregister_ftrace_function() calls rcu_synchronize()' to make sure that no-one is inside the handler once finished. Mirek knows more about it.

Hm, this is news to me. Mirek, please share :-)

Well, I think the whole thing is well described in emails I exchanged with Steven few months ago. See [1].

[1] http://lkml.kernel.org/r/[email protected]

Quoted 3 lines
Quoted 2 lines

If this is not true, we have a problem. For example, we call kfree(ops) after unregister_ftrace_function();

Quoted 7 lines
Quoted 1 line

Agreed.

TL;DR - we should be ok as long as we do not do crazy things in the handler, deliberate sleeping for example.

WARN_ON_ONCE() may be crazy too. I think we discussed it long ago and we came to an agreement to remove it.

There are definitely situations where this might hurt. For example, when we redirect a function called under logbuf_lock.

On the other hand, there is a work in progress[1][2] that will mitigate this risk a lot. Also this warning would be printed only when something goes wrong. IMHO, it is worth the risk. It will succeed in 99,999% cases and it might save us some headache when debugging random crashes of the system.

Quoted 6 lines

Anyway, if there is a reason to remove the warning, it should be described. And if it is not strictly related to this patch, it should be handled separately.

[1] https://lkml.kernel.org/r/[email protected]
[2] https://lkml.kernel.org/r/[email protected]

Yeah, I'm thinking we should keep the warning to catch any bugs in case any of our ftrace assumptions change. Maybe I should add a comment:

	/*
	 * func can never be NULL because preemption should be disabled
	 * here and unregister_ftrace_function() does the equivalent of
	 * a synchronize_sched() before the func_stack removal.
	 */
	if (WARN_ON_ONCE(!func))
		goto unlock;
Signature · 1 line
Josh
#63 lore raw

Re: [PATCH v3 13/15] livepatch: change to a per-task consistency model

In reply to Miroslav Benes
Quoted 27 lines · Miroslav Benes
Quoted 25 lines · Josh Poimboeuf
kernel/livepatch/transition.c new file +25 -0
+void klp_start_transition(void)
+{
+	struct task_struct *g, *task;
+	unsigned int cpu;
+
+	WARN_ON_ONCE(klp_target_state == KLP_UNDEFINED);
+
+	pr_notice("'%s': %s...\n", klp_transition_patch->mod->name,
+		  klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
+
+	/*
+	 * If the patch can be applied or reverted immediately, skip the
+	 * per-task transitions.
+	 */
+	if (klp_transition_patch->immediate)
+		return;
+
+	/*
+	 * Mark all normal tasks as needing a patch state update.  As they pass
+	 * through the syscall barrier they'll switch over to the target state
+	 * (unless we switch them in klp_try_complete_transition() first).
+	 */
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, task)
+		set_tsk_thread_flag(task, TIF_PATCH_PENDING);
Quoted 8 lines

kernel/livepatch/transition.c line 180

Quoted 5 lines
kernel/livepatch/transition.c new file +5 -0
+	read_unlock(&tasklist_lock);
+
+	/*
+	 * Ditto for the idle "swapper" tasks, though they never cross the
+	 * syscall barrier.  Instead they switch over in cpu_idle_loop().

...or we switch them in klp_try_complete_transition() first by looking at their stacks, right? I would add it to the comment.

Yeah, I guess the "ditto" was intended to include the "unless we switch them in klp_try_complete_transition() first" statement from the previous comment. I'll try to make it clearer.

Quoted 21 lines
Quoted 6 lines
kernel/livepatch/transition.c new file +6 -0
+	 */
+	get_online_cpus();
+	for_each_online_cpu(cpu)
+		set_tsk_thread_flag(idle_task(cpu), TIF_PATCH_PENDING);
+	put_online_cpus();
+}

[...]

Quoted 12 lines
kernel/sched/idle.c +1 -0
@@ -9,6 +9,7 @@
 #include <linux/mm.h>
 #include <linux/stackprotector.h>
 #include <linux/suspend.h>
+#include <linux/livepatch.h>
 
 #include <asm/tlb.h>
 
@@ -264,6 +265,9 @@ static void do_idle(void)
 
Quoted 10 lines

kernel/sched/idle.c static void do_idle(void) · line 271

Quoted 6 lines
kernel/sched/idle.c +3 -0
 	sched_ttwu_pending();
 	schedule_preempt_disabled();
+
+	if (unlikely(klp_patch_pending(current)))
+		klp_update_patch_state(current);
 }

I think that (theoretically) this is not sufficient, if we patch a function present on an idle task's stack and one of the two following scenarios happen.

Agreed, though I'd argue that these are rare edge cases which can probably be refined later, outside the scope of this patch set.

Quoted 4 lines

1. there is nothing to schedule on a cpu and an idle task does not leave a loop in do_idle() for some time. It may be a nonsense practically and if it is not we could solve with schedule_on_each_cpu() on an empty stub somewhere in our code.

This might only be a theoretical issue, as it only happens when patching one of the idle functions themselves.

If we decided that this were a real world problem, we could use something like schedule_on_each_cpu() to flush them out as you suggested. Or it could even be done from user space by briefly running a CPU-intensive program on the affected CPUs.

Quoted 3 lines

2. there is a cpu-bound process running on one of the cpus. No chance of going to do_idle() there at all and the idle task would block the patching.

To clarify I think this would only be an issue when trying to patch idle code or schedule()/__schedule().

Quoted 20 lines

We ran into it in kGraft and I tried to solve it with this new hunk in pick_next_task()...

(quoted diff) +11 -0
+       /*
+        * Patching is in progress, schedule an idle task to migrate it
+        */
+       if (kgr_in_progress_branch()) {
+               if (!test_bit(0, kgr_immutable) &&
+                   klp_kgraft_task_in_progress(rq->idle)) {
+                       p = idle_sched_class.pick_next_task(rq, prev);
+
+                       return p;
+               }
+       }

(kgr_in_progress_branch() is a static key basically. kgr_immutable flag solves something we don't have a problem with in upstream livepatch thanks to a combination of task->patch_state and klp_func->transition. klp_kgraft_task_in_progress() checks the livepatching TIF of a task.)

Quoted 7 lines

It is not tested properly and it is a hack as hell so take it as that. Also note that the problem in kGraft is more serious as we don't have a stack checking there. So any livepatch could cause the issue easily.

I can imagine even crazier solutions but nothing nice and pretty (which is probably impossible because the whole idea to deliberately schedule an idle task is not nice and pretty).

Yeah, that looks hairy...

Since this is such a specialized case (patching the scheduler in an idle task while CPU-intensive tasks are running) this might also be more reasonably accomplished from user space by briefly SIGSTOPing the CPU hog.

Quoted 2 lines

Otherwise the patch looks good to me. I don't understand how Petr found those races there.

Agreed, kudos to Petr :-)

Signature · 1 line
Josh
#73 lore raw

Re: [PATCH v3 15/15] livepatch: allow removal of a disabled patch

In reply to Miroslav Benes
Quoted 7 lines · Miroslav Benes
Quoted 7 lines
samples/livepatch/livepatch-sample.c +0 -0
index bb61c65..0625f38 100644
@@ -89,7 +89,6 @@ static int livepatch_init(void)
 
Quoted 8 lines

samples/livepatch/livepatch-sample.c static int livepatch_init(void) · line 93

Quoted 5 lines
samples/livepatch/livepatch-sample.c +0 -1
 static void livepatch_exit(void)
 {
-	WARN_ON(klp_disable_patch(&patch));
 	WARN_ON(klp_unregister_patch(&patch));
 }

Btw, we remove the only call to klp_disable_patch() here. Maybe we can remove the function completely. It is not needed anywhere.

Maybe so. I haven't heard of anybody needing this interface.

Signature · 1 line
Josh
#66 lore raw

Re: [PATCH v3 13/15] livepatch: change to a per-task consistency model

In reply to Miroslav Benes
Quoted 15 lines · Miroslav Benes

kernel/livepatch/core.c int klp_register_patch(struct klp_patch *patch) · line 818

Quoted 12 lines
kernel/livepatch/core.c +7 -0
@@ -740,6 +809,14 @@ int klp_register_patch(struct klp_patch *patch)
 		return -ENODEV;
 
 	/*
+	 * Architectures without reliable stack traces have to set
+	 * patch->immediate because there's currently no way to patch kthreads
+	 * with the consistency model.
+	 */
+	if (!klp_have_reliable_stack() && !patch->immediate)
+		return -ENOSYS;
+

I think an error message (pr_err) would be appropriate here.

Quoted 4 lines
$ insmod patch_1.ko
insmod: ERROR: could not insert module patch_1.ko: Function not implemented

is not helpful much :)

Ok :-)

Signature · 1 line
Josh
Reviewed-by on v3 5/15
#25 lore raw

Re: [PATCH v3 05/15] livepatch/powerpc: add TIF_PATCH_PENDING thread flag

In reply to Josh Poimboeuf
Quoted 10 lines · Josh Poimboeuf

Add the TIF_PATCH_PENDING thread flag to enable the new livepatch per-task consistency model for powerpc. The bit getting set indicates the thread has a pending patch which needs to be applied when the thread exits the kernel.

The bit is included in the _TIF_USER_WORK_MASK macro so that do_notify_resume() and klp_update_patch_state() get called when the bit is set.

Signature · 2 lines
cheers,
Kamalesh.
Reviewed-by on v3 2/15
#13 lore raw

Re: [PATCH v3 02/15] x86/entry: define _TIF_ALLWORK_MASK flags explicitly

In reply to Josh Poimboeuf
Quoted 7 lines · Josh Poimboeuf

The _TIF_ALLWORK_MASK macro automatically includes the least-significant 16 bits of the thread_info flags, which is less than obvious and tends to create confusion and surprises when reading or modifying the code.

Define the flags explicitly.

For the version with swapped _TIF_SINGLESTEP and _TIF_NEED_RESCHED flags.

Signature · 2 lines
cheers,
Kamalesh.
Reviewed-by on v3 8/15
#32 lore raw

Re: [PATCH v3 08/15] livepatch: separate enabled and patched states

In reply to Josh Poimboeuf
Quoted 13 lines · Josh Poimboeuf

Once we have a consistency model, patches and their objects will be enabled and disabled at different times. For example, when a patch is disabled, its loaded objects' funcs can remain registered with ftrace indefinitely until the unpatching operation is complete and they're no longer in use.

It's less confusing if we give them different names: patches can be enabled or disabled; objects (and their funcs) can be patched or unpatched:

- Enabled means that a patch is logically enabled (but not necessarily fully applied).

Quoted 7 lines

- Patched means that an object's funcs are registered with ftrace and added to the klp_ops func stack.

Also, since these states are binary, represent them with booleans instead of ints.

Signature · 2 lines
cheers,
Kamalesh.
Reviewed-by on v3 9/15
#36 lore raw

Re: [PATCH v3 09/15] livepatch: remove unnecessary object loaded check

In reply to Josh Poimboeuf
Quoted 7 lines · Josh Poimboeuf

klp_patch_object()'s callers already ensure that the object is loaded, so its call to klp_is_object_loaded() is unnecessary.

This will also make it possible to move the patching code into a separate file.

Signature · 2 lines
cheers,
Kamalesh.
maintainer
#61 lore raw

Re: [PATCH v3 13/15] livepatch: change to a per-task consistency model

In reply to Josh Poimboeuf
Quoted 35 lines · Josh Poimboeuf
Quoted 21 lines · Petr Mladek
Quoted 20 lines · Miroslav Benes
Quoted 20 lines
Quoted 20 lines
Quoted 20 lines
kernel/livepatch/patch.c +2 -0
index 5efa262..e79ebb5 100644
@@ -29,6 +29,7 @@
 #include <linux/bug.h>
 #include <linux/printk.h>
 #include "patch.h"
+#include "transition.h"
 
 static LIST_HEAD(klp_ops);
 
@@ -54,15 +55,53 @@ static void notrace klp_ftrace_handler(unsigned long ip,
 {
 	struct klp_ops *ops;
 	struct klp_func *func;
+	int patch_state;
 
 	ops = container_of(fops, struct klp_ops, fops);
 
Quoted 9 lines
Quoted 9 lines
Quoted 9 lines
Quoted 9 lines

kernel/livepatch/patch.c static void notrace klp_ftrace_handler(unsigned long ip, · line 68

Quoted 8 lines
kernel/livepatch/patch.c +3 -1
 	rcu_read_lock();
+
 	func = list_first_or_null_rcu(&ops->func_stack, struct klp_func,
 				      stack_node);
-	if (WARN_ON_ONCE(!func))
+
+	if (!func)
 		goto unlock;

Yeah, I'm thinking we should keep the warning to catch any bugs in case any of our ftrace assumptions change. Maybe I should add a comment:

Quoted 7 lines
	/*
	 * func can never be NULL because preemption should be disabled
	 * here and unregister_ftrace_function() does the equivalent of
	 * a synchronize_sched() before the func_stack removal.
	 */
	if (WARN_ON_ONCE(!func))
		goto unlock;

Sounds reasonable to me.

Best Regards,
Petr

maintainer
#64 lore raw

Re: [PATCH v3 13/15] livepatch: change to a per-task consistency model

In reply to Josh Poimboeuf
Quoted 24 lines
Quoted 13 lines
Quoted 13 lines
kernel/sched/idle.c +1 -0
@@ -9,6 +9,7 @@
 #include <linux/mm.h>
 #include <linux/stackprotector.h>
 #include <linux/suspend.h>
+#include <linux/livepatch.h>
 
 #include <asm/tlb.h>
 
@@ -264,6 +265,9 @@ static void do_idle(void)
 
Quoted 10 lines

kernel/sched/idle.c static void do_idle(void) · line 271

Quoted 6 lines
kernel/sched/idle.c +3 -0
 	sched_ttwu_pending();
 	schedule_preempt_disabled();
+
+	if (unlikely(klp_patch_pending(current)))
+		klp_update_patch_state(current);
 }

I think that (theoretically) this is not sufficient, if we patch a function present on an idle task's stack and one of the two following scenarios happen.

Quoted 2 lines

Agreed, though I'd argue that these are rare edge cases which can probably be refined later, outside the scope of this patch set.

You're right. They should be really rare and we can solve them (if we even want to) later.

Quoted 5 lines
Quoted 4 lines

1. there is nothing to schedule on a cpu and an idle task does not leave a loop in do_idle() for some time. It may be a nonsense practically and if it is not we could solve with schedule_on_each_cpu() on an empty stub somewhere in our code.

Quoted 7 lines

This might only be a theoretical issue, as it only happens when patching one of the idle functions themselves.

If we decided that this were a real world problem, we could use something like schedule_on_each_cpu() to flush them out as you suggested. Or it could even be done from user space by briefly running a CPU-intensive program on the affected CPUs.

Yes.

Quoted 6 lines
Quoted 3 lines

2. there is a cpu-bound process running on one of the cpus. No chance of going to do_idle() there at all and the idle task would block the patching.

To clarify I think this would only be an issue when trying to patch idle code or schedule()/__schedule().

Yes.

Quoted 28 lines
Quoted 20 lines

We ran into it in kGraft and I tried to solve it with this new hunk in pick_next_task()...

(quoted diff) +11 -0
+       /*
+        * Patching is in progress, schedule an idle task to migrate it
+        */
+       if (kgr_in_progress_branch()) {
+               if (!test_bit(0, kgr_immutable) &&
+                   klp_kgraft_task_in_progress(rq->idle)) {
+                       p = idle_sched_class.pick_next_task(rq, prev);
+
+                       return p;
+               }
+       }

(kgr_in_progress_branch() is a static key basically. kgr_immutable flag solves something we don't have a problem with in upstream livepatch thanks to a combination of task->patch_state and klp_func->transition. klp_kgraft_task_in_progress() checks the livepatching TIF of a task.)

Quoted 7 lines

It is not tested properly and it is a hack as hell so take it as that. Also note that the problem in kGraft is more serious as we don't have a stack checking there. So any livepatch could cause the issue easily.

I can imagine even crazier solutions but nothing nice and pretty (which is probably impossible because the whole idea to deliberately schedule an idle task is not nice and pretty).

Quoted 6 lines

Yeah, that looks hairy...

Since this is such a specialized case (patching the scheduler in an idle task while CPU-intensive tasks are running) this might also be more reasonably accomplished from user space by briefly SIGSTOPing the CPU hog.

Yes, that is true. I can imagine there are users who don't want to stop the cpu hog at all. Even for a fraction of time. HPC comes to mind. But it is not worth it to solve it with something like the code above. Let's add it to the very end of our TODO lists :).

Miroslav

maintainer
#54 lore raw

Re: [PATCH v3 13/15] livepatch: change to a per-task consistency model

In reply to Josh Poimboeuf
Quoted 136 lines · Josh Poimboeuf
Quoted 118 lines · Petr Mladek
Quoted 81 lines · Josh Poimboeuf
Quoted 68 lines · Petr Mladek
Quoted 52 lines · Josh Poimboeuf

Change livepatch to use a basic per-task consistency model. This is the foundation which will eventually enable us to patch those ~10% of security patches which change function or data semantics. This is the biggest remaining piece needed to make livepatch more generally useful.

[1] https://lkml.kernel.org/r/[email protected]

kernel/livepatch/transition.c new file +43 -0
+	/*
+	 * Enforce the order of the task->patch_state initializations and the
+	 * func->transition updates to ensure that, in the enable path,
+	 * klp_ftrace_handler() doesn't see a func in transition with a
+	 * task->patch_state of KLP_UNDEFINED.
+	 */
+	smp_wmb();
+
+	/*
+	 * Set the func transition states so klp_ftrace_handler() will know to
+	 * switch to the transition logic.
+	 *
+	 * When patching, the funcs aren't yet in the func_stack and will be
+	 * made visible to the ftrace handler shortly by the calls to
+	 * klp_patch_object().
+	 *
+	 * When unpatching, the funcs are already in the func_stack and so are
+	 * already visible to the ftrace handler.
+	 */
+	klp_for_each_object(patch, obj)
+		klp_for_each_func(obj, func)
+			func->transition = true;
+}
+
+/*
+ * Start the transition to the specified target patch state so tasks can begin
+ * switching to it.
+ */
+void klp_start_transition(void)
+{
+	struct task_struct *g, *task;
+	unsigned int cpu;
+
+	WARN_ON_ONCE(klp_target_state == KLP_UNDEFINED);
+
+	pr_notice("'%s': %s...\n", klp_transition_patch->mod->name,
+		  klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
+
+	/*
+	 * If the patch can be applied or reverted immediately, skip the
+	 * per-task transitions.
+	 */
+	if (klp_transition_patch->immediate)

kernel/livepatch/transition.c line 175

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+		return;
+
+	/*
+	 * Mark all normal tasks as needing a patch state update.  As they pass
+	 * through the syscall barrier they'll switch over to the target state
+	 * (unless we switch them in klp_try_complete_transition() first).
+	 */
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, task)
+		set_tsk_thread_flag(task, TIF_PATCH_PENDING);

This is called also from klp_reverse_transition(). We should set it only when the task need migration. Also we should clear it when the task is in the right state already.

Quoted 2 lines

It is not only optimization. It actually solves a race between klp_complete_transition() and klp_update_patch_state(), see below.

I agree about the race, but if I did:

	for_each_process_thread(g, task) {
		if (task->patch_state != klp_target_state)
			set_tsk_thread_flag(task, TIF_PATCH_PENDING);
		else
			clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
	}
Quoted 3 lines

It would still leave a small window where TIF_PATCH_PENDING gets set for an already patched task, if klp_update_patch_state() is running at the same time.

I see your point. Well, it seems that it is more complicated:

The race would be possible only when this was called from klp_reverse_transition(). But we need to call there rcu_synchronize() to prevent races with klp_update_patch_state() also to prevent prelimitary patch completion.

The result is:

if (task->patch_state != klp_target_state) {
# it means that the task was already migrated before # we reverted klp_target_state. It means that # the TIF flag was already cleared, the related # klp_update_patch_state() already finished (thanks # to rcu_synchronize() and new one will be called # only when we set the flag again
# => it is safe to set it

# we should also check and warn when the TIF flag # was not clear before we set it here

else

# the task was not migrated before we reverted # klp_target_state. klp_update_patch_state() # could run in parallel but it will do the same # what we do, clear TIF flag and keep the patch_state # as is
# => it is safe to clear it

Quoted 2 lines

I agree that this is complex like hell. But it also allows use to check that things work as we expect.

Ouch. I agree that it seems safe but it's way too hard to reason about. And then it gets worse if you try to think about what happens when adding another reverse operation.

Quoted 9 lines

If we always set the flag here and always clear it later, we might hide a bug.

If we want to make it slightly more straightforward, we might clear TIF flags in klp_reverse_transaction() before we revert klp_target_state. The later rcu_synchronize() should make sure that all migrations are finished and non-will run in parallel. Then we could set the TIF flag only where needed here.

Quoted 3 lines

I think this last paragraph is important. It would simplify things greatly and ensure we won't have klp_update_patch_state() changing things in the background.

OK, let's clear all TIF_PATCH_PENDIG flags and call rcu_synchronize() at the beginning of klp_reverse_transition(). It might be slightly suboptimal but it greatly simplifies the situation. I vote for it. We need to prevent our heads from cracking ;-)

Note that I would still set TIF_PATCH_PENDING flag only for tasks that are not in the requested state.

Quoted 31 lines
Quoted 14 lines
Quoted 14 lines
Quoted 13 lines

kernel/livepatch/transition.c line 185

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+	read_unlock(&tasklist_lock);
+
+	/*
+	 * Ditto for the idle "swapper" tasks, though they never cross the
+	 * syscall barrier.  Instead they switch over in cpu_idle_loop().
+	 */
+	get_online_cpus();
+	for_each_online_cpu(cpu)
+		set_tsk_thread_flag(idle_task(cpu), TIF_PATCH_PENDING);
+	put_online_cpus();

Also this stage need to be somehow handled by CPU coming/going handlers.

Quoted 5 lines
Quoted 2 lines

Here I think we could automatically switch any offline CPUs' idle tasks. And something similar in klp_try_complete_transition().

We still need to make sure to do not race with the cpu_up()/cpu_down() calls.

Hm, maybe we'd need to call cpu_hotplug_disable() before switching the offline idle tasks?

Quoted 2 lines

I would use here the trick with for_each_possible_cpu() and let the migration for the stack check.

There are a few issues with that:

1) The idle task of a missing CPU doesn't *have* a stack, so it doesn't make much sense to try to check it.

Quoted 8 lines

2) We can't rely *only* on the stack check, because not all arches have it. The other way to migrate idle tasks is from the idle loop switch point. But if the task's CPU is down, its idle loop isn't running so it can't migrate.

(Note this is currently a theoretical point: we currently don't allow such arches to use the consistency model anyway because there's no way for them to migrate kthreads.)

Good points. My only concern is that the transaction might take a long or even forever. I am not sure if it is wise to disable cpu_hotplug for the entire transaction.

A compromise might be to disable cpu hotplug only when the task state is manipulated a more complex way. Hmm, cpu_hotplug_disable() looks like a rather costly function. We should not call it in klp_try_complete_transition(). But we could do:

1. When the patch is being enabled, disable cpu hotplug, go through each_possible_cpu and setup the transaction only for CPUs that are online. Then we could enable the hotplug again.

2. Check only each_online_cpu in klp_try_complete_transition(). If all tasks are migrated, disable cpu hotplug and re-check idle tasks on online CPUs. If any is not migrated, enable hotplug and return failure. Othewise, continue with completion of the transaction. [*]

3. In klp_complete_transition, update all tasks including the offline CPUs and enable cpu hotplug again.

If the re-check in the 2nd step looks ugly, we could add some hotlug notifiers to make sure that enabled/disabled CPUs are in a reasonable state. We still should disable the hotplug in the 1st and 3rd step.

BTW: There is a new API for the cpu hotplug callbacks. I was involved in one conversion. You might take inspiration in drivers/thermal/intel_powerclamp.c. See cpuhp_setup_state_nocalls() there.

[...]

Quoted 66 lines
Quoted 51 lines
Quoted 28 lines
Quoted 17 lines
Quoted 17 lines
samples/livepatch/livepatch-sample.c +2 -0
index e34f871..bb61c65 100644
@@ -17,6 +17,8 @@
  * along with this program; if not, see <http://www.gnu.org/licenses/>.
  */
 
+#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+
 #include <linux/module.h>
 #include <linux/kernel.h>
 #include <linux/livepatch.h>
@@ -69,6 +71,11 @@ static int livepatch_init(void)
 {
 	int ret;
 
Quoted 10 lines

samples/livepatch/livepatch-sample.c static int livepatch_init(void) · line 77

Quoted 4 lines
samples/livepatch/livepatch-sample.c +4 -0
+	if (!klp_have_reliable_stack() && !patch.immediate) {
+		pr_notice("disabling consistency model!\n");
+		patch.immediate = true;
+	}

I am scared to have this in the sample module. It makes sense to use the consistency model even for immediate patches because it allows to remove them. But this must not be used for patches that really require the consistency model. We should add a big fat warning at least.

Quoted 8 lines

I did this so that the sample module would still work for non-x86_64 arches, for which there's currently no way to patch kthreads.

Notice I did add a warning:

  pr_notice("disabling consistency model!\n");

Is the warning not fat enough?

The warning does not explain who did it, why, if it is safe, and when this could be used. I suggest a comment like:

/*
* WARNING: Use this check only when you know what you do!
*
* This sample patch does not change the semantic of the data structures,
* locks, or return adresses. It is safe to be applied immediately.
* But we want to test and use the consistency model on supported
* architectures. It allows to remove the patch module.
*
* See Documentation/livepatch/livepatch.txt for more details, please. */

Quoted 4 lines

Also the message might be more explicit.

pr_notice("livepatch-sample: The consistency model is not supported on this architecture. Using the immediate model that is safe enough.\n");

Ok, will try to do something like that.

Quoted 8 lines

Alternatively, we might allow more values for patch.immediate, e.g.

enum klp_consistency_model {
KLP_CM_IMMEDIATE,
KLP_CM_TASK,
KLP_CM_TASK_OR_IMMEDIATE,
};

Quoted 5 lines
Quoted 3 lines

Then we could do the decision on the kernel side. But I am not sure if this would be widely used and it it is worth the complication.

I'd rather avoid that :-)

Same here :-)

Best Regards,
Petr

#55 lore raw

Re: [PATCH v3 13/15] livepatch: change to a per-task consistency model

Quoted 141 lines · Petr Mladek
Quoted 136 lines · Josh Poimboeuf
Quoted 118 lines · Petr Mladek
Quoted 81 lines · Josh Poimboeuf
Quoted 68 lines · Petr Mladek
Quoted 52 lines · Josh Poimboeuf

Change livepatch to use a basic per-task consistency model. This is the foundation which will eventually enable us to patch those ~10% of security patches which change function or data semantics. This is the biggest remaining piece needed to make livepatch more generally useful.

[1] https://lkml.kernel.org/r/[email protected]

kernel/livepatch/transition.c new file +43 -0
+	/*
+	 * Enforce the order of the task->patch_state initializations and the
+	 * func->transition updates to ensure that, in the enable path,
+	 * klp_ftrace_handler() doesn't see a func in transition with a
+	 * task->patch_state of KLP_UNDEFINED.
+	 */
+	smp_wmb();
+
+	/*
+	 * Set the func transition states so klp_ftrace_handler() will know to
+	 * switch to the transition logic.
+	 *
+	 * When patching, the funcs aren't yet in the func_stack and will be
+	 * made visible to the ftrace handler shortly by the calls to
+	 * klp_patch_object().
+	 *
+	 * When unpatching, the funcs are already in the func_stack and so are
+	 * already visible to the ftrace handler.
+	 */
+	klp_for_each_object(patch, obj)
+		klp_for_each_func(obj, func)
+			func->transition = true;
+}
+
+/*
+ * Start the transition to the specified target patch state so tasks can begin
+ * switching to it.
+ */
+void klp_start_transition(void)
+{
+	struct task_struct *g, *task;
+	unsigned int cpu;
+
+	WARN_ON_ONCE(klp_target_state == KLP_UNDEFINED);
+
+	pr_notice("'%s': %s...\n", klp_transition_patch->mod->name,
+		  klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
+
+	/*
+	 * If the patch can be applied or reverted immediately, skip the
+	 * per-task transitions.
+	 */
+	if (klp_transition_patch->immediate)

kernel/livepatch/transition.c line 175

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+		return;
+
+	/*
+	 * Mark all normal tasks as needing a patch state update.  As they pass
+	 * through the syscall barrier they'll switch over to the target state
+	 * (unless we switch them in klp_try_complete_transition() first).
+	 */
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, task)
+		set_tsk_thread_flag(task, TIF_PATCH_PENDING);

This is called also from klp_reverse_transition(). We should set it only when the task need migration. Also we should clear it when the task is in the right state already.

Quoted 2 lines

It is not only optimization. It actually solves a race between klp_complete_transition() and klp_update_patch_state(), see below.

I agree about the race, but if I did:

	for_each_process_thread(g, task) {
		if (task->patch_state != klp_target_state)
			set_tsk_thread_flag(task, TIF_PATCH_PENDING);
		else
			clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
	}
Quoted 3 lines

It would still leave a small window where TIF_PATCH_PENDING gets set for an already patched task, if klp_update_patch_state() is running at the same time.

I see your point. Well, it seems that it is more complicated:

The race would be possible only when this was called from klp_reverse_transition(). But we need to call there rcu_synchronize() to prevent races with klp_update_patch_state() also to prevent prelimitary patch completion.

The result is:

if (task->patch_state != klp_target_state) {
# it means that the task was already migrated before # we reverted klp_target_state. It means that # the TIF flag was already cleared, the related # klp_update_patch_state() already finished (thanks # to rcu_synchronize() and new one will be called # only when we set the flag again
# => it is safe to set it

# we should also check and warn when the TIF flag # was not clear before we set it here

else

# the task was not migrated before we reverted # klp_target_state. klp_update_patch_state() # could run in parallel but it will do the same # what we do, clear TIF flag and keep the patch_state # as is
# => it is safe to clear it

Quoted 2 lines

I agree that this is complex like hell. But it also allows use to check that things work as we expect.

Ouch. I agree that it seems safe but it's way too hard to reason about. And then it gets worse if you try to think about what happens when adding another reverse operation.

Quoted 9 lines

If we always set the flag here and always clear it later, we might hide a bug.

If we want to make it slightly more straightforward, we might clear TIF flags in klp_reverse_transaction() before we revert klp_target_state. The later rcu_synchronize() should make sure that all migrations are finished and non-will run in parallel. Then we could set the TIF flag only where needed here.

Quoted 3 lines

I think this last paragraph is important. It would simplify things greatly and ensure we won't have klp_update_patch_state() changing things in the background.

Quoted 7 lines

OK, let's clear all TIF_PATCH_PENDIG flags and call rcu_synchronize() at the beginning of klp_reverse_transition(). It might be slightly suboptimal but it greatly simplifies the situation. I vote for it. We need to prevent our heads from cracking ;-)

Note that I would still set TIF_PATCH_PENDING flag only for tasks that are not in the requested state.

Ok, sounds good.

Quoted 63 lines
Quoted 31 lines
Quoted 14 lines
Quoted 14 lines
Quoted 13 lines

kernel/livepatch/transition.c line 185

Quoted 10 lines
kernel/livepatch/transition.c new file +10 -0
+	read_unlock(&tasklist_lock);
+
+	/*
+	 * Ditto for the idle "swapper" tasks, though they never cross the
+	 * syscall barrier.  Instead they switch over in cpu_idle_loop().
+	 */
+	get_online_cpus();
+	for_each_online_cpu(cpu)
+		set_tsk_thread_flag(idle_task(cpu), TIF_PATCH_PENDING);
+	put_online_cpus();

Also this stage need to be somehow handled by CPU coming/going handlers.

Quoted 5 lines
Quoted 2 lines

Here I think we could automatically switch any offline CPUs' idle tasks. And something similar in klp_try_complete_transition().

We still need to make sure to do not race with the cpu_up()/cpu_down() calls.

Hm, maybe we'd need to call cpu_hotplug_disable() before switching the offline idle tasks?

Quoted 2 lines

I would use here the trick with for_each_possible_cpu() and let the migration for the stack check.

There are a few issues with that:

1) The idle task of a missing CPU doesn't *have* a stack, so it doesn't make much sense to try to check it.

Quoted 8 lines

2) We can't rely *only* on the stack check, because not all arches have it. The other way to migrate idle tasks is from the idle loop switch point. But if the task's CPU is down, its idle loop isn't running so it can't migrate.

(Note this is currently a theoretical point: we currently don't allow such arches to use the consistency model anyway because there's no way for them to migrate kthreads.)

Good points. My only concern is that the transaction might take a long or even forever. I am not sure if it is wise to disable cpu_hotplug for the entire transaction.

A compromise might be to disable cpu hotplug only when the task state is manipulated a more complex way. Hmm, cpu_hotplug_disable() looks like a rather costly function. We should not call it in klp_try_complete_transition(). But we could do:

1. When the patch is being enabled, disable cpu hotplug, go through each_possible_cpu and setup the transaction only for CPUs that are online. Then we could enable the hotplug again.

2. Check only each_online_cpu in klp_try_complete_transition(). If all tasks are migrated, disable cpu hotplug and re-check idle tasks on online CPUs. If any is not migrated, enable hotplug and return failure. Othewise, continue with completion of the transaction. [*]

3. In klp_complete_transition, update all tasks including the offline CPUs and enable cpu hotplug again.

Quoted 8 lines

If the re-check in the 2nd step looks ugly, we could add some hotlug notifiers to make sure that enabled/disabled CPUs are in a reasonable state. We still should disable the hotplug in the 1st and 3rd step.

BTW: There is a new API for the cpu hotplug callbacks. I was involved in one conversion. You might take inspiration in drivers/thermal/intel_powerclamp.c. See cpuhp_setup_state_nocalls() there.

Backing up a bit, although I brought up cpu_hotplug_disable(), I think I misunderstood the race you mentioned. I actually don't think cpu_hotplug_disable() is necessary. What do you think about something like the following:

In klp_start_transition:

	get_online_cpus();
	for_each_possible_cpu(cpu)
		set_tsk_thread_flag(idle_task(cpu), TIF_PATCH_PENDING);
	put_online_cpus();

In klp_try_complete_transition:

	get_online_cpus();
	for_each_possible_cpu(cpu) {
		task = idle_task(cpu);
		if (cpu_online(cpu)) {
			if (!klp_try_switch_task(task))
				complete = false;
		} else if (task->patch_state != klp_target_state) {
			/* offline CPU idle tasks can be switched immediately */
			clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
			task->patch_state = klp_target_state;
		}
	}
	put_online_cpus();
Signature · 1 line
Josh
Reviewed-by on v3 4/15
#21 lore raw

Re: [PATCH v3 04/15] livepatch/x86: add TIF_PATCH_PENDING thread flag

In reply to Josh Poimboeuf
Quoted 9 lines · Josh Poimboeuf

Add the TIF_PATCH_PENDING thread flag to enable the new livepatch per-task consistency model for x86_64. The bit getting set indicates the thread has a pending patch which needs to be applied when the thread exits the kernel.

The bit is placed in the _TIF_ALLWORK_MASK macro, which results in exit_to_usermode_loop() calling klp_update_patch_state() when it's set.

Signature · 2 lines
cheers,
Kamalesh.
maintainer
#56 lore raw

Re: [PATCH v3 13/15] livepatch: change to a per-task consistency model

In reply to Josh Poimboeuf
Quoted 73 lines · Josh Poimboeuf
Quoted 72 lines · Petr Mladek
Quoted 35 lines · Josh Poimboeuf
Quoted 17 lines · Petr Mladek
Quoted 16 lines · Josh Poimboeuf
Quoted 14 lines · Petr Mladek

Review

Quoted 10 lines · Josh Poimboeuf
(quoted diff) +10 -0
+	read_unlock(&tasklist_lock);
+
+	/*
+	 * Ditto for the idle "swapper" tasks, though they never cross the
+	 * syscall barrier.  Instead they switch over in cpu_idle_loop().
+	 */
+	get_online_cpus();
+	for_each_online_cpu(cpu)
+		set_tsk_thread_flag(idle_task(cpu), TIF_PATCH_PENDING);
+	put_online_cpus();

Also this stage need to be somehow handled by CPU coming/going handlers.

Quoted 5 lines
Quoted 2 lines

Here I think we could automatically switch any offline CPUs' idle tasks. And something similar in klp_try_complete_transition().

We still need to make sure to do not race with the cpu_up()/cpu_down() calls.

Hm, maybe we'd need to call cpu_hotplug_disable() before switching the offline idle tasks?

Quoted 2 lines

I would use here the trick with for_each_possible_cpu() and let the migration for the stack check.

There are a few issues with that:

1) The idle task of a missing CPU doesn't *have* a stack, so it doesn't make much sense to try to check it.

Quoted 8 lines

2) We can't rely *only* on the stack check, because not all arches have it. The other way to migrate idle tasks is from the idle loop switch point. But if the task's CPU is down, its idle loop isn't running so it can't migrate.

(Note this is currently a theoretical point: we currently don't allow such arches to use the consistency model anyway because there's no way for them to migrate kthreads.)

Good points. My only concern is that the transaction might take a long or even forever. I am not sure if it is wise to disable cpu_hotplug for the entire transaction.

A compromise might be to disable cpu hotplug only when the task state is manipulated a more complex way. Hmm, cpu_hotplug_disable() looks like a rather costly function. We should not call it in klp_try_complete_transition(). But we could do:

1. When the patch is being enabled, disable cpu hotplug, go through each_possible_cpu and setup the transaction only for CPUs that are online. Then we could enable the hotplug again.

2. Check only each_online_cpu in klp_try_complete_transition(). If all tasks are migrated, disable cpu hotplug and re-check idle tasks on online CPUs. If any is not migrated, enable hotplug and return failure. Othewise, continue with completion of the transaction. [*]

3. In klp_complete_transition, update all tasks including the offline CPUs and enable cpu hotplug again.

If the re-check in the 2nd step looks ugly, we could add some hotlug notifiers to make sure that enabled/disabled CPUs are in a reasonable state. We still should disable the hotplug in the 1st and 3rd step.

Quoted 8 lines
Quoted 4 lines

BTW: There is a new API for the cpu hotplug callbacks. I was involved in one conversion. You might take inspiration in drivers/thermal/intel_powerclamp.c. See cpuhp_setup_state_nocalls() there.

Backing up a bit, although I brought up cpu_hotplug_disable(), I think I misunderstood the race you mentioned. I actually don't think cpu_hotplug_disable() is necessary.

Great backing! You made me to study the difference. If I get it correctly:

+ cpu_hotplug_disable() works like a writer lock. It gets exclusive access via cpu_hotplug_begin(). A side effect is that do_cpu_up() and do_cpu_down() do not wait. They return -EBUSY if hotplug is disabled.

+ get_online_cpus() is kind of reader lock. It makes sure that all the hotplug operations are finished and "softly" blocks other further operation. By "softly" I mean that the operations wait for the exclusive (write) access in cpu_hotplug_begin().

IMHO, we really have to use get_online_cpus() and avoid the the "hard" blocking.

Quoted 11 lines

What do you think about something like the following:

In klp_start_transition:

	get_online_cpus();
	for_each_possible_cpu(cpu)
		set_tsk_thread_flag(idle_task(cpu), TIF_PATCH_PENDING);
	put_online_cpus();

In klp_try_complete_transition:

Quoted 13 lines
	get_online_cpus();
	for_each_possible_cpu(cpu) {
		task = idle_task(cpu);
		if (cpu_online(cpu)) {
			if (!klp_try_switch_task(task))
				complete = false;
		} else if (task->patch_state != klp_target_state) {
			/* offline CPU idle tasks can be switched immediately */
			clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
			task->patch_state = klp_target_state;
		}
	}
	put_online_cpus();

I like the idea. You are right that it is enough to always get/put CPUs only when a state of the per-CPU idle tasks are manipulated. In the meantime, we are safe because of the consistency model (clever ftrace handler).

Note that we have to use for_each_possible_cpu() everywhere, e.g. in klp_init_transition(), klp_complete_transition(). Otherwise, we might see an inconsistent state.

For example, klp_ftrace_handler() might see KLP_UNDEFINED state if we do not set a valid one in klp_init_transition() and a CPU gets online.

Best Regards,
Petr

#57 lore raw

Re: [PATCH v3 13/15] livepatch: change to a per-task consistency model

Quoted 131 lines · Petr Mladek
Quoted 73 lines · Josh Poimboeuf
Quoted 72 lines · Petr Mladek
Quoted 35 lines · Josh Poimboeuf
Quoted 17 lines · Petr Mladek
Quoted 16 lines · Josh Poimboeuf
Quoted 14 lines · Petr Mladek

Review

Quoted 10 lines · Josh Poimboeuf
(quoted diff) +10 -0
+	read_unlock(&tasklist_lock);
+
+	/*
+	 * Ditto for the idle "swapper" tasks, though they never cross the
+	 * syscall barrier.  Instead they switch over in cpu_idle_loop().
+	 */
+	get_online_cpus();
+	for_each_online_cpu(cpu)
+		set_tsk_thread_flag(idle_task(cpu), TIF_PATCH_PENDING);
+	put_online_cpus();

Also this stage need to be somehow handled by CPU coming/going handlers.

Quoted 5 lines
Quoted 2 lines

Here I think we could automatically switch any offline CPUs' idle tasks. And something similar in klp_try_complete_transition().

We still need to make sure to do not race with the cpu_up()/cpu_down() calls.

Hm, maybe we'd need to call cpu_hotplug_disable() before switching the offline idle tasks?

Quoted 2 lines

I would use here the trick with for_each_possible_cpu() and let the migration for the stack check.

There are a few issues with that:

1) The idle task of a missing CPU doesn't *have* a stack, so it doesn't make much sense to try to check it.

Quoted 8 lines

2) We can't rely *only* on the stack check, because not all arches have it. The other way to migrate idle tasks is from the idle loop switch point. But if the task's CPU is down, its idle loop isn't running so it can't migrate.

(Note this is currently a theoretical point: we currently don't allow such arches to use the consistency model anyway because there's no way for them to migrate kthreads.)

Good points. My only concern is that the transaction might take a long or even forever. I am not sure if it is wise to disable cpu_hotplug for the entire transaction.

A compromise might be to disable cpu hotplug only when the task state is manipulated a more complex way. Hmm, cpu_hotplug_disable() looks like a rather costly function. We should not call it in klp_try_complete_transition(). But we could do:

1. When the patch is being enabled, disable cpu hotplug, go through each_possible_cpu and setup the transaction only for CPUs that are online. Then we could enable the hotplug again.

2. Check only each_online_cpu in klp_try_complete_transition(). If all tasks are migrated, disable cpu hotplug and re-check idle tasks on online CPUs. If any is not migrated, enable hotplug and return failure. Othewise, continue with completion of the transaction. [*]

3. In klp_complete_transition, update all tasks including the offline CPUs and enable cpu hotplug again.

If the re-check in the 2nd step looks ugly, we could add some hotlug notifiers to make sure that enabled/disabled CPUs are in a reasonable state. We still should disable the hotplug in the 1st and 3rd step.

Quoted 8 lines
Quoted 4 lines

BTW: There is a new API for the cpu hotplug callbacks. I was involved in one conversion. You might take inspiration in drivers/thermal/intel_powerclamp.c. See cpuhp_setup_state_nocalls() there.

Backing up a bit, although I brought up cpu_hotplug_disable(), I think I misunderstood the race you mentioned. I actually don't think cpu_hotplug_disable() is necessary.

Great backing! You made me to study the difference. If I get it correctly:

+ cpu_hotplug_disable() works like a writer lock. It gets exclusive access via cpu_hotplug_begin(). A side effect is that do_cpu_up() and do_cpu_down() do not wait. They return -EBUSY if hotplug is disabled.

+ get_online_cpus() is kind of reader lock. It makes sure that all the hotplug operations are finished and "softly" blocks other further operation. By "softly" I mean that the operations wait for the exclusive (write) access in cpu_hotplug_begin().

IMHO, we really have to use get_online_cpus() and avoid the the "hard" blocking.

Quoted 11 lines

What do you think about something like the following:

In klp_start_transition:

	get_online_cpus();
	for_each_possible_cpu(cpu)
		set_tsk_thread_flag(idle_task(cpu), TIF_PATCH_PENDING);
	put_online_cpus();

In klp_try_complete_transition:

Quoted 13 lines
	get_online_cpus();
	for_each_possible_cpu(cpu) {
		task = idle_task(cpu);
		if (cpu_online(cpu)) {
			if (!klp_try_switch_task(task))
				complete = false;
		} else if (task->patch_state != klp_target_state) {
			/* offline CPU idle tasks can be switched immediately */
			clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
			task->patch_state = klp_target_state;
		}
	}
	put_online_cpus();

I like the idea. You are right that it is enough to always get/put CPUs only when a state of the per-CPU idle tasks are manipulated. In the meantime, we are safe because of the consistency model (clever ftrace handler).

Quoted 7 lines

Note that we have to use for_each_possible_cpu() everywhere, e.g. in klp_init_transition(), klp_complete_transition(). Otherwise, we might see an inconsistent state.

For example, klp_ftrace_handler() might see KLP_UNDEFINED state if we do not set a valid one in klp_init_transition() and a CPU gets online.

Agreed! I will try to have v4 soon-ish.

Signature · 1 line
Josh