livepatch: hybrid consistency model
Subsystems (11)
v5 cover livepatch: hybrid consistency model
Here's v5 of the consistency model, targeted for 4.12. Only a few minor changes this time.
I would very much appreciate reviews/acks from the following:
- Michael Ellerman for the powerpc changes in patch 5.
- Heiko Carstens for the s390 changes in patches 6 & 7.
- Peter Zijlstra/Ingo Molnar for the use of task_rq_lock() and the modification of do_idle() in patch 13.
Thanks!
Based on linux-next/master (20170213).
v5:
- return -EINVAL in __save_stack_trace_reliable()
- only call show_stack() once
- add save_stack_trace_tsk_reliable() define for !CONFIG_STACKTRACE
- update kernel version and date in ABI doc
- make suggested improvements to livepatch.txt
- update barrier comments
- remove klp_try_complete_transition() call from klp_start_transition()
- move end of klp_try_complete_transition() into klp_complete_transition()
- fix __klp_enable_patch() error path
- check for transition in klp_module_going()
v4:
- add warnings for "impossible" scenarios in __save_stack_trace_reliable()
- sort _TIF_ALLWORK_MASK flags
- move klp_transition_work to transition.c. This resulted in the following related changes:
- klp_mutex is now visible to transition.c
- klp_start_transition() now calls klp_try_complete_transition()
- klp_try_complete_transition() now sets up the work
- rearrange code in transition.c accordingly
- klp_reverse_transition(): clear TIF flags and call synchronize_rcu()
- klp_try_complete_transition(): do synchronize_rcu() only when unpatching
- klp_start_transition(): only set TIF flags when necessary
- klp_complete_transition(): add synchronize_rcu() when patching
- klp_ftrace_handler(): put WARN_ON_ONCE back in and add comment
- use for_each_possible_cpu() to patch offline idle tasks
- add warnings to sample module when setting patch.immediate
- don't use pr_debug() with the task rq lock
- add documentation about porting consistency model to other arches
- move klp_patch_pending() to patch 13
- improve several comments and commit messages
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: create temporary klp_update_patch_state() stub 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 | 214 +++++++-- 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 | 13 +- arch/x86/include/asm/unwind.h | 6 + arch/x86/kernel/stacktrace.c | 96 +++- arch/x86/kernel/unwind_frame.c | 2 + fs/proc/base.c | 15 + include/linux/init_task.h | 9 + include/linux/livepatch.h | 68 ++- include/linux/sched.h | 3 + include/linux/stacktrace.h | 9 +- kernel/fork.c | 3 + kernel/livepatch/Makefile | 2 +- kernel/livepatch/core.c | 436 +++++++----------- kernel/livepatch/patch.c | 272 +++++++++++ kernel/livepatch/patch.h | 33 ++ kernel/livepatch/transition.c | 551 +++++++++++++++++++++++ kernel/livepatch/transition.h | 14 + kernel/sched/idle.c | 4 + kernel/stacktrace.c | 12 +- samples/livepatch/livepatch-sample.c | 18 +- 29 files changed, 1531 insertions(+), 354 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
PATCH v5 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.
Note that if the target task isn't the current task, and the target task is allowed to run, then it could be writing the stack while the unwinder is reading it, resulting in possible corruption. So the caller of save_stack_trace_tsk_reliable() must ensure that the task is either 'current' or inactive.
save_stack_trace_tsk_reliable() relies on the x86 unwinder's detection of pt_regs on the stack. If the pt_regs are not user-mode registers from a syscall, then they indicate an in-kernel interrupt or exception (e.g. preemption or a page fault), in which case the stack is considered unreliable due to the nature of frame pointers.
It also relies on the x86 unwinder's detection of other issues, such as:
- corrupted stack data
- stack grows the wrong way
- stack walk doesn't reach the bottom
- user didn't provide a large enough entries array
Such issues are reported by checking unwind_error() and !unwind_done().
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 | 96 +++++++++++++++++++++++++++++++++++++++++- arch/x86/kernel/unwind_frame.c | 2 + include/linux/stacktrace.h | 9 ++-- kernel/stacktrace.c | 12 +++++- 7 files changed, 126 insertions(+), 6 deletions(-)
arch/Kconfig +6 -0
@@ -749,6 +749,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
@@ -160,6 +160,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
@@ -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, *orig_sp;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 +95 -1
105 lines not on this page · raw message
arch/x86/kernel/unwind_frame.c +2 -0
@@ -223,6 +223,8 @@ bool unwind_next_frame(struct unwind_state *state)return true; bad_address: + state->error = true; +/* * When unwinding a non-current task, the task might actually be * running on another CPU, in which case it could be modifying its
include/linux/stacktrace.h +6 -3
@@ -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,13 @@ 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 +# define save_stack_trace_tsk_reliable (tsk, trace) ({ -ENOSYS; }) +#endif /* CONFIG_STACKTRACE */ -#endif +#endif /* __LINUX_STACKTRACE_H */
kernel/stacktrace.c +10 -2
@@ -54,8 +54,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
@@ -69,3 +69,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
Re: [PATCH v5 01/15] stacktrace/x86: add function for detecting reliable stack traces
Quoted 23 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.Note that if the target task isn't the current task, and the target task is allowed to run, then it could be writing the stack while the unwinder is reading it, resulting in possible corruption. So the caller of
save_stack_trace_tsk_reliable()must ensure that the task is either 'current' or inactive.
save_stack_trace_tsk_reliable()relies on the x86 unwinder's detection ofpt_regson the stack. If thept_regsare not user-mode registers from a syscall, then they indicate an in-kernel interrupt or exception (e.g. preemption or a page fault), in which case the stack is considered unreliable due to the nature of frame pointers.It also relies on the x86 unwinder's detection of other issues, such as:
- corrupted stack data
- stack grows the wrong way
- stack walk doesn't reach the bottom
- user didn't provide a large enough entries array
Quoted 6 lines
Such issues are reported by checking
unwind_error()and !unwind_done().Also add
CONFIG_HAVE_RELIABLE_STACKTRACEso arch-independent code can determine at build time whether the function is implemented.Signed-off-by Josh Poimboeuf <[email protected]>
I do not see any difference from 4.1 version, so my
stays.
Regards,
Miroslav
Re: [PATCH v5 01/15] stacktrace/x86: add function for detecting reliable stack traces
Quoted 27 lines · Miroslav Benes
Quoted 25 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.Note that if the target task isn't the current task, and the target task is allowed to run, then it could be writing the stack while the unwinder is reading it, resulting in possible corruption. So the caller of
save_stack_trace_tsk_reliable()must ensure that the task is either 'current' or inactive.
save_stack_trace_tsk_reliable()relies on the x86 unwinder's detection ofpt_regson the stack. If thept_regsare not user-mode registers from a syscall, then they indicate an in-kernel interrupt or exception (e.g. preemption or a page fault), in which case the stack is considered unreliable due to the nature of frame pointers.It also relies on the x86 unwinder's detection of other issues, such as:
- corrupted stack data
- stack grows the wrong way
- stack walk doesn't reach the bottom
- user didn't provide a large enough entries arraySuch issues are reported by checking
unwind_error()and !unwind_done().
Quoted 8 lines
Quoted 4 lines
Also add
CONFIG_HAVE_RELIABLE_STACKTRACEso arch-independent code can determine at build time whether the function is implemented.Signed-off-by Josh Poimboeuf <[email protected]>I do not see any difference from 4.1 version, so my
Reviewed-by Miroslav Benes <[email protected]>
Sorry, forgot to add your Reviewed-by from last time. The patch is indeed the same. Thanks!
Signature · 1 line
Josh
Re: [PATCH v5 01/15] stacktrace/x86: add function for detecting reliable stack traces
In reply to Josh PoimboeufQuoted 23 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.Note that if the target task isn't the current task, and the target task is allowed to run, then it could be writing the stack while the unwinder is reading it, resulting in possible corruption. So the caller of
save_stack_trace_tsk_reliable()must ensure that the task is either 'current' or inactive.
save_stack_trace_tsk_reliable()relies on the x86 unwinder's detection ofpt_regson the stack. If thept_regsare not user-mode registers from a syscall, then they indicate an in-kernel interrupt or exception (e.g. preemption or a page fault), in which case the stack is considered unreliable due to the nature of frame pointers.It also relies on the x86 unwinder's detection of other issues, such as:
- corrupted stack data
- stack grows the wrong way
- stack walk doesn't reach the bottom
- user didn't provide a large enough entries array
Quoted 7 lines
Such issues are reported by checking
unwind_error()and !unwind_done().Also add
CONFIG_HAVE_RELIABLE_STACKTRACEso arch-independent code can determine at build time whether the function is implemented.Signed-off-by Josh Poimboeuf <[email protected]>---
Could you comment on why we need a reliable trace for live-patching? Are we in any way reliant on the stack trace to patch something broken?
Thanks,
Balbir Singh.
Re: [PATCH v5 01/15] stacktrace/x86: add function for detecting reliable stack traces
Quoted 26 lines · Balbir Singh
Quoted 25 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.Note that if the target task isn't the current task, and the target task is allowed to run, then it could be writing the stack while the unwinder is reading it, resulting in possible corruption. So the caller of
save_stack_trace_tsk_reliable()must ensure that the task is either 'current' or inactive.
save_stack_trace_tsk_reliable()relies on the x86 unwinder's detection ofpt_regson the stack. If thept_regsare not user-mode registers from a syscall, then they indicate an in-kernel interrupt or exception (e.g. preemption or a page fault), in which case the stack is considered unreliable due to the nature of frame pointers.It also relies on the x86 unwinder's detection of other issues, such as:
- corrupted stack data
- stack grows the wrong way
- stack walk doesn't reach the bottom
- user didn't provide a large enough entries arraySuch issues are reported by checking
unwind_error()and !unwind_done().
Quoted 8 lines
Quoted 5 lines
Also add
CONFIG_HAVE_RELIABLE_STACKTRACEso arch-independent code can determine at build time whether the function is implemented.Signed-off-by Josh Poimboeuf <[email protected]>---
Could you comment on why we need a reliable trace for live-patching? Are we in any way reliant on the stack trace to patch something broken?
I tried to cover this comprehensively in patch 13/15 in Documentation/livepatch/livepatch.txt. Does that answer your questions?
Signature · 1 line
Josh
Re: [PATCH v5 01/15] stacktrace/x86: add function for detecting reliable stack traces
Quoted 32 lines · Josh Poimboeuf
Quoted 31 lines · Balbir Singh
Quoted 30 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.
Note that if the target task isn't the current task, and the target task is allowed to run, then it could be writing the stack while the unwinder is reading it, resulting in possible corruption. So the caller ofsave_stack_trace_tsk_reliable()must ensure that the task is either 'current' or inactive.save_stack_trace_tsk_reliable()relies on the x86 unwinder's detection ofpt_regson the stack. If thept_regsare not user-mode registers from a syscall, then they indicate an in-kernel interrupt or exception (e.g. preemption or a page fault), in which case the stack is considered unreliable due to the nature of frame pointers.
It also relies on the x86 unwinder's detection of other issues, such as:
- corrupted stack data
- stack grows the wrong way
- stack walk doesn't reach the bottom
- user didn't provide a large enough entries array
Such issues are reported by checkingunwind_error()and !unwind_done().
Also addCONFIG_HAVE_RELIABLE_STACKTRACEso arch-independent code can determine at build time whether the function is implemented.Signed-off-by Josh Poimboeuf <[email protected]>---
Quoted 7 lines
Quoted 3 lines
Could you comment on why we need a reliable trace for live-patching? Are we in any way reliant on the stack trace to patch something broken?
I tried to cover this comprehensively in patch 13/15 in Documentation/livepatch/livepatch.txt. Does that answer your questions?
Yes, it answers my questions
Thanks,
Balbir Singh.
Re: [PATCH v5 01/15] stacktrace/x86: add function for detecting reliable stack traces
In reply to Josh PoimboeufQuoted 23 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.Note that if the target task isn't the current task, and the target task is allowed to run, then it could be writing the stack while the unwinder is reading it, resulting in possible corruption. So the caller of
save_stack_trace_tsk_reliable()must ensure that the task is either 'current' or inactive.
save_stack_trace_tsk_reliable()relies on the x86 unwinder's detection ofpt_regson the stack. If thept_regsare not user-mode registers from a syscall, then they indicate an in-kernel interrupt or exception (e.g. preemption or a page fault), in which case the stack is considered unreliable due to the nature of frame pointers.It also relies on the x86 unwinder's detection of other issues, such as:
- corrupted stack data
- stack grows the wrong way
- stack walk doesn't reach the bottom
- user didn't provide a large enough entries array
Quoted 6 lines
Such issues are reported by checking
unwind_error()and !unwind_done().Also add
CONFIG_HAVE_RELIABLE_STACKTRACEso arch-independent code can determine at build time whether the function is implemented.Signed-off-by Josh Poimboeuf <[email protected]>
Just for record, this version looks fine to me:
Best Regards,
Petr
PS: I was on the sick leave longer then expected. The patch set has been pushed into the for-4.12 branch in jikos/livepatching.git in the meantime. I check it there just for completeness. You do not need to add my Reviewed-by tags.
PATCH v5 2/15 x86/entry: define _TIF_ALLWORK_MASK flags explicitly
In reply to Josh PoimboeufThe _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 | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-)
arch/x86/include/asm/thread_info.h +5 -6
@@ -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 */
@@ -103,8 +100,8 @@ struct thread_info {#define _TIF_SYSCALL_TRACE (1 << TIF_SYSCALL_TRACE)#define _TIF_NOTIFY_RESUME (1 << TIF_NOTIFY_RESUME)#define _TIF_SIGPENDING (1 << TIF_SIGPENDING) -#define _TIF_SINGLESTEP (1 << TIF_SINGLESTEP)#define _TIF_NEED_RESCHED (1 << TIF_NEED_RESCHED) +#define _TIF_SINGLESTEP (1 << TIF_SINGLESTEP)#define _TIF_SYSCALL_EMU (1 << TIF_SYSCALL_EMU)#define _TIF_SYSCALL_AUDIT (1 << TIF_SYSCALL_AUDIT)#define _TIF_SECCOMP (1 << TIF_SECCOMP)
@@ -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_NEED_RESCHED | _TIF_SINGLESTEP | _TIF_SYSCALL_EMU | \ + _TIF_SYSCALL_AUDIT | _TIF_USER_RETURN_NOTIFY | _TIF_UPROBE | \ + _TIF_NOHZ | _TIF_SYSCALL_TRACEPOINT)/* flags to check in __switch_to() */ #define _TIF_WORK_CTXSW \
Signature · 1 line
2.7.4
PATCH v5 3/15 livepatch: create temporary klp_update_patch_state() stub
In reply to Josh PoimboeufCreate temporary stubs for 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 | 5 ++++- kernel/livepatch/core.c | 3 +++ 2 files changed, 7 insertions(+), 1 deletion(-)
include/linux/livepatch.h +4 -1
@@ -123,10 +123,13 @@ void arch_klp_init_object_loaded(struct klp_patch *patch,int klp_module_coming (struct module *mod);void klp_module_going (struct module *mod); +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 void klp_update_patch_state (struct task_struct *task) {}#endif /* CONFIG_LIVEPATCH */
kernel/livepatch/core.c +3 -0
@@ -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
PATCH v5 4/15 livepatch/x86: add TIF_PATCH_PENDING thread flag
In reply to Josh PoimboeufAdd 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
@@ -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
@@ -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_NEED_RESCHED | _TIF_SINGLESTEP | _TIF_SYSCALL_EMU | \ _TIF_SYSCALL_AUDIT | _TIF_USER_RETURN_NOTIFY | _TIF_UPROBE | \ - _TIF_NOHZ | _TIF_SYSCALL_TRACEPOINT) + _TIF_PATCH_PENDING | _TIF_NOHZ | _TIF_SYSCALL_TRACEPOINT) /* flags to check in __switch_to() */#define _TIF_WORK_CTXSW \
Signature · 1 line
2.7.4
PATCH v5 5/15 livepatch/powerpc: add TIF_PATCH_PENDING thread flag
In reply to Josh PoimboeufAdd 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
@@ -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
@@ -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 <linux/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
Re: [PATCH v5 05/15] livepatch/powerpc: add TIF_PATCH_PENDING thread flag
Quoted 9 lines · Josh Poimboeuf
Add the
TIF_PATCH_PENDINGthread 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_MASKmacro so thatdo_notify_resume()andklp_update_patch_state()get called when the bit is set.
Quoted 5 lines
Signed-off-by Josh Poimboeuf <[email protected]>Reviewed-by Petr Mladek <[email protected]>Reviewed-by Miroslav Benes <[email protected]>Reviewed-by Kamalesh Babulal <[email protected]>---
Re: [PATCH v5 05/15] livepatch/powerpc: add TIF_PATCH_PENDING thread flag
In reply to Josh PoimboeufQuoted 9 lines · Josh Poimboeuf
Add the
TIF_PATCH_PENDINGthread 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_MASKmacro so thatdo_notify_resume()andklp_update_patch_state()get called when the bit is set.
Quoted 8 lines
Signed-off-by Josh Poimboeuf <[email protected]>Reviewed-by Petr Mladek <[email protected]>Reviewed-by Miroslav Benes <[email protected]>Reviewed-by Kamalesh Babulal <[email protected]>--- arch/powerpc/include/asm/thread_info.h | 4 +++- arch/powerpc/kernel/signal.c | 4 ++++ 2 files changed, 7 insertions(+), 1 deletion(-)
The arch changes here seem fine. I haven't tested the whole series though.
cheers
PATCH v5 6/15 livepatch/s390: reorganize TIF thread flag bits
In reply to Josh PoimboeufFrom: 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
@@ -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
PATCH v5 7/15 livepatch/s390: add TIF_PATCH_PENDING thread flag
In reply to Josh PoimboeufFrom: 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
@@ -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
@@ -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)
@@ -333,6 +333,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
@@ -405,6 +410,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:
@@ -654,6 +669,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
@@ -700,6 +719,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
PATCH v5 8/15 livepatch: separate enabled and patched states
In reply to Josh PoimboeufOnce 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
@@ -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
PATCH v5 9/15 livepatch: remove unnecessary object loaded check
In reply to Josh Poimboeufklp_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
@@ -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
PATCH v5 10/15 livepatch: move patching functions into patch.c
In reply to Josh PoimboeufMove 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
@@ -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
@@ -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
PATCH v5 11/15 livepatch: use kstrtobool() in enabled_store()
In reply to Josh PoimboeufThe 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 | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-)
kernel/livepatch/core.c +5 -8
@@ -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 ; +return ret; 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
PATCH v5 12/15 livepatch: store function sizes
In reply to Josh PoimboeufFor 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
@@ -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
@@ -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
PATCH v5 13/15 livepatch: change to a per-task consistency model
In reply to Josh PoimboeufChange 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 | 186 +++++++- include/linux/init_task.h | 9 + include/linux/livepatch.h | 42 +- include/linux/sched.h | 3 + kernel/fork.c | 3 + kernel/livepatch/Makefile | 2 +- kernel/livepatch/core.c | 105 ++++- kernel/livepatch/patch.c | 59 +++ kernel/livepatch/patch.h | 1 + kernel/livepatch/transition.c | 543 +++++++++++++++++++++++ kernel/livepatch/transition.h | 14 + kernel/sched/idle.c | 4 + samples/livepatch/livepatch-sample.c | 17 + 14 files changed, 947 insertions(+), 49 deletions(-) create mode 100644 kernel/livepatch/transition.c create mode 100644 kernel/livepatch/transition.h
Documentation/ABI/testing/sysfs-kernel-livepatch +8 -0
@@ -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: Feb 2017 +KernelVersion: 4.12.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 +163 -23
228 lines not on this page · raw message
include/linux/init_task.h +9 -0
@@ -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>
@@ -202,6 +203,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), \
@@ -288,6 +296,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 +41 -1
103 lines not on this page · raw message
include/linux/sched.h +3 -0
@@ -1980,6 +1980,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
@@ -77,6 +77,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>
@@ -1772,6 +1773,8 @@ static __latent_entropy struct task_struct *copy_process( p->parent_exec_id = current->self_exec_id; } +klp_copy_process (p); +spin_lock (¤t->sighand->siglock);/*
kernel/livepatch/Makefile +1 -1
@@ -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 +81 -24
206 lines not on this page · raw message
kernel/livepatch/patch.c +59 -0
83 lines not on this page · raw message
kernel/livepatch/patch.h +1 -0
@@ -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 +543 -0
543 lines not on this page · raw message
kernel/livepatch/transition.h new file +14 -0
@@ -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_cancel_transition (void ); +void klp_start_transition (void ); +void klp_try_complete_transition (void ); +void klp_reverse_transition (void ); + +#endif /* _LIVEPATCH_TRANSITION_H */
kernel/sched/idle.c +4 -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)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 +17 -0
@@ -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,21 @@ static int livepatch_init(void) {int ret; +if (!klp_have_reliable_stack () && !patch.immediate) { +/* +* WARNING: Be very careful when using 'patch.immediate' in +* your patches. It's ok to use it for simple patches like +* this, but for more complex patches which change function +* semantics, locking semantics, or data structures, it may not +* be safe. Use of this option will also prevent removal of +* the patch. +* +* See Documentation/livepatch/livepatch.txt for more details. +*/ + patch.immediate = true; +pr_notice ("The consistency model isn't supported for your architecture. Bypassing safety mechanisms and applying the patch immediately.\n" ); + } + ret =klp_register_patch (&patch);if (ret)return ret;
Signature · 1 line
2.7.4
Miroslav Benes
maintainerRe: [PATCH v5 13/15] livepatch: change to a per-task consistency model
Quoted 30 lines
kernel/livepatch/core.c +18
-2@@ -347,22 +356,36 @@ static int __klp_enable_patch(struct klp_patch *patch)pr_notice ("enabling patch '%s'\n" , patch->mod->name); +klp_init_transition (patch,KLP_PATCHED ); + +/* +* Enforce the order of the func->transition writes in +* klp_init_transition() and the ops->func_stack writes in +* klp_patch_object(), so that klp_ftrace_handler() will see the +* func->transition updates before the handler is registered and the +* new funcs become visible to the handler. +*/ +smp_wmb (); +klp_for_each_object (patch, obj) {if (!klp_is_object_loaded (obj))continue ; ret =klp_patch_object (obj); -if (ret) - goto unregister; +if (ret) { +pr_warn ("failed to enable patch '%s'\n" , + patch->mod->name); + +klp_cancel_transition (); +return ret; + }
[...]
Quoted 53 lines
kernel/livepatch/transition.c new file +53
-0+static void klp_complete_transition (void ) +{ +struct klp_object *obj; +struct klp_func *func; +struct task_struct *g, *task; +unsigned int cpu; + +if (klp_target_state ==KLP_UNPATCHED ) { +/* +* All tasks have transitioned to KLP_UNPATCHED so we can now +* remove the new functions from the func_stack. +*/ +klp_unpatch_objects (klp_transition_patch); + +/* +* Make sure klp_ftrace_handler() can no longer see functions +* from this patch on the ops->func_stack. Otherwise, after +* func->transition gets cleared, the handler may choose a +* removed function. +*/ +synchronize_rcu (); + } + +if (klp_transition_patch->immediate) + goto done; + +klp_for_each_object (klp_transition_patch, obj) +klp_for_each_func (obj, func) + func->transition = false; + +/* Prevent klp_ftrace_handler() from seeing KLP_UNDEFINED state */ +if (klp_target_state ==KLP_PATCHED ) +synchronize_rcu (); + +read_lock (&tasklist_lock); +for_each_process_thread (g, task) { +WARN_ON_ONCE (test_tsk_thread_flag (task,TIF_PATCH_PENDING )); + task->patch_state =KLP_UNDEFINED ; + } +read_unlock (&tasklist_lock); + +for_each_possible_cpu (cpu) { + task =idle_task (cpu); +WARN_ON_ONCE (test_tsk_thread_flag (task,TIF_PATCH_PENDING )); + task->patch_state =KLP_UNDEFINED ; + } + +done: + klp_target_state =KLP_UNDEFINED ; + klp_transition_patch =NULL ; +} + +/*
kernel/livepatch/transition.c line 118
Quoted 10 lines
kernel/livepatch/transition.c new file +10
-0+* This is called in the error path, to cancel a transition before it has +* started, i.e. klp_init_transition() has been called but +* klp_start_transition() hasn't. If the transition *has* been started, +* klp_reverse_transition() should be used instead. +*/ +void klp_cancel_transition (void ) +{ + klp_target_state = !klp_target_state; +klp_complete_transition (); +}
If we fail to enable patch in __klp_enable_patch(), we call klp_cancel_transition() and get to klp_complete_transition(). If the patch has immediate set to true, the module would not be allowed to go (the changes are in the last patch unfortunately, but my remark is closely related to klp_cancel_transition() and __klp_enable_patch()). This could annoy a user if it was due to a trivial reason. So we could call module_put() in this case. It should be safe as no task could be in a new function thanks to klp_ftrace_handler() logic.
Pity I have not spotted this earlier.
Putting module_put(patch->mod) right after klp_cancel_transition() call in __klp_enable_patch() would be the simplest fix (as a part of 15/15 patch). Maybe with a comment that it is safe to do it there.
What do you think?
Miroslav
Re: [PATCH v5 13/15] livepatch: change to a per-task consistency model
Quoted 106 lines · Miroslav Benes
Quoted 30 lines
(quoted diff) +18
-2@@ -347,22 +356,36 @@ static int __klp_enable_patch(struct klp_patch *patch) pr_notice("enabling patch '%s'\n", patch->mod->name); + klp_init_transition(patch, KLP_PATCHED); + + /* + * Enforce the order of the func->transition writes in + * klp_init_transition() and the ops->func_stack writes in + * klp_patch_object(), so that klp_ftrace_handler() will see the + * func->transition updates before the handler is registered and the + * new funcs become visible to the handler. + */ + smp_wmb(); + klp_for_each_object(patch, obj) { if (!klp_is_object_loaded(obj)) continue; ret = klp_patch_object(obj); - if (ret) - goto unregister; + if (ret) { + pr_warn("failed to enable patch '%s'\n", + patch->mod->name); + + klp_cancel_transition(); + return ret; + }[...]
Quoted 53 lines
(quoted diff) +53
-0+static void klp_complete_transition(void) +{ + struct klp_object *obj; + struct klp_func *func; + struct task_struct *g, *task; + unsigned int cpu; + + if (klp_target_state == KLP_UNPATCHED) { + /* + * All tasks have transitioned to KLP_UNPATCHED so we can now + * remove the new functions from the func_stack. + */ + klp_unpatch_objects(klp_transition_patch); + + /* + * Make sure klp_ftrace_handler() can no longer see functions + * from this patch on the ops->func_stack. Otherwise, after + * func->transition gets cleared, the handler may choose a + * removed function. + */ + synchronize_rcu(); + } + + if (klp_transition_patch->immediate) + goto done; + + klp_for_each_object(klp_transition_patch, obj) + klp_for_each_func(obj, func) + func->transition = false; + + /* Prevent klp_ftrace_handler() from seeing KLP_UNDEFINED state */ + if (klp_target_state == KLP_PATCHED) + synchronize_rcu(); + + read_lock(&tasklist_lock); + for_each_process_thread(g, task) { + WARN_ON_ONCE(test_tsk_thread_flag(task, TIF_PATCH_PENDING)); + task->patch_state = KLP_UNDEFINED; + } + read_unlock(&tasklist_lock); + + for_each_possible_cpu(cpu) { + task = idle_task(cpu); + WARN_ON_ONCE(test_tsk_thread_flag(task, TIF_PATCH_PENDING)); + task->patch_state = KLP_UNDEFINED; + } + +done: + klp_target_state = KLP_UNDEFINED; + klp_transition_patch = NULL; +} + +/*Review
Quoted 10 lines
(quoted diff) +10
-0+ * This is called in the error path, to cancel a transition before it has + * started, i.e. klp_init_transition() has been called but + * klp_start_transition() hasn't. If the transition *has* been started, + * klp_reverse_transition() should be used instead. + */ +void klp_cancel_transition(void) +{ + klp_target_state = !klp_target_state; + klp_complete_transition(); +}If we fail to enable patch in
__klp_enable_patch(), we callklp_cancel_transition()and get toklp_complete_transition(). If the patch has immediate set to true, the module would not be allowed to go (the changes are in the last patch unfortunately, but my remark is closely related toklp_cancel_transition()and__klp_enable_patch()). This could annoy a user if it was due to a trivial reason. So we could callmodule_put()in this case. It should be safe as no task could be in a new function thanks toklp_ftrace_handler()logic.
Quoted 7 lines
Pity I have not spotted this earlier.
Putting
module_put(patch->mod)right afterklp_cancel_transition()call in__klp_enable_patch()would be the simplest fix (as a part of 15/15 patch). Maybe with a comment that it is safe to do it there.What do you think?
Good catch. I agree that 15/15 should have something like that.
Also, the module_put() will be needed for non-immediate patches which have a func->immediate set.
What do you think about the following? I tried to put the logic in klp_complete_transition(), so the module_put()'s would be in one place. But it was too messy, so I put it in klp_cancel_transition() instead.
kernel/livepatch/transition.c +20 -0
@@ -121,8 +121,28 @@ static void klp_complete_transition(void)*/ void klp_cancel_transition (void ) { +bool immediate_func = false; + klp_target_state = !klp_target_state;klp_complete_transition (); + +if (klp_target_state ==KLP_PATCHED ) +return ; + +/* +* In the enable error path, even immediate patches can be safely +* removed because the transition hasn't been started yet. +* +* klp_complete_transition() doesn't have a module_put() for immediate +* patches, so do it here. +*/ +klp_for_each_object (klp_transition_patch, obj) +klp_for_each_func (obj, func) +if (func->immediate) + immediate_func = true; + +if (klp_transition_patch->immediate || immediate_func) +module_put (klp_transition_patch->mod); }/*
Miroslav Benes
maintainerRe: [PATCH v5 13/15] livepatch: change to a per-task consistency model
Quoted 113 lines · Josh Poimboeuf
Quoted 112 lines · Miroslav Benes
Quoted 30 lines
(quoted diff) +18
-2@@ -347,22 +356,36 @@ static int __klp_enable_patch(struct klp_patch *patch) pr_notice("enabling patch '%s'\n", patch->mod->name); + klp_init_transition(patch, KLP_PATCHED); + + /* + * Enforce the order of the func->transition writes in + * klp_init_transition() and the ops->func_stack writes in + * klp_patch_object(), so that klp_ftrace_handler() will see the + * func->transition updates before the handler is registered and the + * new funcs become visible to the handler. + */ + smp_wmb(); + klp_for_each_object(patch, obj) { if (!klp_is_object_loaded(obj)) continue; ret = klp_patch_object(obj); - if (ret) - goto unregister; + if (ret) { + pr_warn("failed to enable patch '%s'\n", + patch->mod->name); + + klp_cancel_transition(); + return ret; + }[...]
Quoted 53 lines
(quoted diff) +53
-0+static void klp_complete_transition(void) +{ + struct klp_object *obj; + struct klp_func *func; + struct task_struct *g, *task; + unsigned int cpu; + + if (klp_target_state == KLP_UNPATCHED) { + /* + * All tasks have transitioned to KLP_UNPATCHED so we can now + * remove the new functions from the func_stack. + */ + klp_unpatch_objects(klp_transition_patch); + + /* + * Make sure klp_ftrace_handler() can no longer see functions + * from this patch on the ops->func_stack. Otherwise, after + * func->transition gets cleared, the handler may choose a + * removed function. + */ + synchronize_rcu(); + } + + if (klp_transition_patch->immediate) + goto done; + + klp_for_each_object(klp_transition_patch, obj) + klp_for_each_func(obj, func) + func->transition = false; + + /* Prevent klp_ftrace_handler() from seeing KLP_UNDEFINED state */ + if (klp_target_state == KLP_PATCHED) + synchronize_rcu(); + + read_lock(&tasklist_lock); + for_each_process_thread(g, task) { + WARN_ON_ONCE(test_tsk_thread_flag(task, TIF_PATCH_PENDING)); + task->patch_state = KLP_UNDEFINED; + } + read_unlock(&tasklist_lock); + + for_each_possible_cpu(cpu) { + task = idle_task(cpu); + WARN_ON_ONCE(test_tsk_thread_flag(task, TIF_PATCH_PENDING)); + task->patch_state = KLP_UNDEFINED; + } + +done: + klp_target_state = KLP_UNDEFINED; + klp_transition_patch = NULL; +} + +/*Review
Quoted 10 lines
(quoted diff) +10
-0+ * This is called in the error path, to cancel a transition before it has + * started, i.e. klp_init_transition() has been called but + * klp_start_transition() hasn't. If the transition *has* been started, + * klp_reverse_transition() should be used instead. + */ +void klp_cancel_transition(void) +{ + klp_target_state = !klp_target_state; + klp_complete_transition(); +}If we fail to enable patch in
__klp_enable_patch(), we callklp_cancel_transition()and get toklp_complete_transition(). If the patch has immediate set to true, the module would not be allowed to go (the changes are in the last patch unfortunately, but my remark is closely related toklp_cancel_transition()and__klp_enable_patch()). This could annoy a user if it was due to a trivial reason. So we could callmodule_put()in this case. It should be safe as no task could be in a new function thanks toklp_ftrace_handler()logic.Pity I have not spotted this earlier.
Putting
module_put(patch->mod)right afterklp_cancel_transition()call in__klp_enable_patch()would be the simplest fix (as a part of 15/15 patch). Maybe with a comment that it is safe to do it there.
Quoted 6 lines
Quoted 1 line
What do you think?
Good catch. I agree that 15/15 should have something like that.
Also, the
module_put()will be needed for non-immediate patches which have afunc->immediateset.
Right. This further complicates it.
Quoted 9 lines
What do you think about the following? I tried to put the logic in
klp_complete_transition(), so the module_put()'s would be in one place. But it was too messy, so I put it inklp_cancel_transition()instead.kernel/livepatch/transition.c +0
-0
kernel/livepatch/transition.c static void klp_complete_transition(void) · line 130
Quoted 10 lines
kernel/livepatch/transition.c +5
-0@@ -121,8 +121,28 @@ static void klp_complete_transition(void)*/ void klp_cancel_transition (void ) { +bool immediate_func = false; + klp_target_state = !klp_target_state;klp_complete_transition (); + +if (klp_target_state ==KLP_PATCHED ) +return ;
This is not needed, I think. We call klp_cancel_transition() in __klp_enable_patch() only. klp_target_state is set to KLP_PATCHED there (through klp_init_transition()) and negated here. We know it must be KLP_UNPATCHED.
Moreover, due to klp_complete_transition() klp_target_state is always KLP_UNDEFINED after it.
Quoted 5 lines
kernel/livepatch/transition.c +5
-0+ +/* +* In the enable error path, even immediate patches can be safely +* removed because the transition hasn't been started yet. +*
kernel/livepatch/transition.c static void klp_complete_transition(void) · line 145
Quoted 10 lines
kernel/livepatch/transition.c +10
-0+* klp_complete_transition() doesn't have a module_put() for immediate +* patches, so do it here. +*/ +klp_for_each_object (klp_transition_patch, obj) +klp_for_each_func (obj, func) +if (func->immediate) + immediate_func = true; + +if (klp_transition_patch->immediate || immediate_func) +module_put (klp_transition_patch->mod);
Almost correct. The only problem is that klp_transition_patch is NULL at this point. klp_complete_transition() does that and it should stay there in my opinion to keep it simple.
So we could either move all this to __klp_enable_patch(), where patch variable is defined, or we could store klp_transition_patch to a local variable here in klp_cancel_transition() before klp_complete_transition() is called. That should be safe. I like the latter more, because it keeps the code in klp_cancel_transition() where it belongs.
Miroslav
Re: [PATCH v5 13/15] livepatch: change to a per-task consistency model
Quoted 17 lines · Miroslav Benes
Quoted 16 lines · Josh Poimboeuf
What do you think about the following? I tried to put the logic in
klp_complete_transition(), so the module_put()'s would be in one place. But it was too messy, so I put it inklp_cancel_transition()instead.kernel/livepatch/transition.c +2
-0@@ -121,8 +121,28 @@ static void klp_complete_transition(void)*/ void klp_cancel_transition (void ) { +bool immediate_func = false; + klp_target_state = !klp_target_state;klp_complete_transition ();
Quoted 8 lines
kernel/livepatch/transition.c static void klp_complete_transition(void) · line 130
Quoted 3 lines
kernel/livepatch/transition.c +3
-0+ +if (klp_target_state ==KLP_PATCHED ) +return ;This is not needed, I think. We call
klp_cancel_transition()in__klp_enable_patch()only.klp_target_stateis set toKLP_PATCHEDthere (throughklp_init_transition()) and negated here. We know it must beKLP_UNPATCHED.
Yeah, I was trying to hedge against the possibility of future code calling this function in the disable path. But that probably won't happen and it would probably be cleaner to just add a warning if klp_target_state isn't KLP_PATCHED.
Quoted 23 lines
Moreover, due to
klp_complete_transition()klp_target_stateis alwaysKLP_UNDEFINEDafter it.Quoted 5 lines
kernel/livepatch/transition.c +5
-0+ +/* +* In the enable error path, even immediate patches can be safely +* removed because the transition hasn't been started yet. +* kernel/livepatch/transition.c static void klp_complete_transition(void) · line 145
Quoted 10 lines
kernel/livepatch/transition.c +10
-0+* klp_complete_transition() doesn't have a module_put() for immediate +* patches, so do it here. +*/ +klp_for_each_object (klp_transition_patch, obj) +klp_for_each_func (obj, func) +if (func->immediate) + immediate_func = true; + +if (klp_transition_patch->immediate || immediate_func) +module_put (klp_transition_patch->mod);Almost correct. The only problem is that
klp_transition_patchis NULL at this point.klp_complete_transition()does that and it should stay there in my opinion to keep it simple.
Quoted 5 lines
So we could either move all this to
__klp_enable_patch(), where patch variable is defined, or we could storeklp_transition_patchto a local variable here inklp_cancel_transition()beforeklp_complete_transition()is called. That should be safe. I like the latter more, because it keeps the code inklp_cancel_transition()where it belongs.
Good points. Here's another try:
kernel/livepatch/transition.c +24 -1
@@ -121,8 +121,31 @@ static void klp_complete_transition(void)*/ void klp_cancel_transition (void ) { - klp_target_state = !klp_target_state; +struct klp_patch *patch = klp_transition_patch; +struct klp_object *obj; +struct klp_func *func; +bool immediate_func = false; + +if (WARN_ON_ONCE (klp_target_state !=KLP_PATCHED )) +return ; + + klp_target_state =KLP_UNPATCHED ;klp_complete_transition (); + +/* +* In the enable error path, even immediate patches can be safely +* removed because the transition hasn't been started yet. +* +* klp_complete_transition() doesn't have a module_put() for immediate +* patches, so do it here. +*/ +klp_for_each_object (patch, obj) +klp_for_each_func (obj, func) +if (func->immediate) + immediate_func = true; + +if (patch->immediate || immediate_func) +module_put (patch->mod); }/*
Miroslav Benes
maintainerRe: [PATCH v5 13/15] livepatch: change to a per-task consistency model
Quoted 88 lines · Josh Poimboeuf
Quoted 17 lines · Miroslav Benes
Quoted 16 lines · Josh Poimboeuf
What do you think about the following? I tried to put the logic in
klp_complete_transition(), so the module_put()'s would be in one place. But it was too messy, so I put it inklp_cancel_transition()instead.kernel/livepatch/transition.c +2
-0@@ -121,8 +121,28 @@ static void klp_complete_transition(void)*/ void klp_cancel_transition (void ) { +bool immediate_func = false; + klp_target_state = !klp_target_state;klp_complete_transition ();Quoted 8 lines
kernel/livepatch/transition.c static void klp_complete_transition(void) · line 130
Quoted 3 lines
kernel/livepatch/transition.c +3
-0+ +if (klp_target_state ==KLP_PATCHED ) +return ;This is not needed, I think. We call
klp_cancel_transition()in__klp_enable_patch()only.klp_target_stateis set toKLP_PATCHEDthere (throughklp_init_transition()) and negated here. We know it must beKLP_UNPATCHED.Yeah, I was trying to hedge against the possibility of future code calling this function in the disable path. But that probably won't happen and it would probably be cleaner to just add a warning if
klp_target_stateisn'tKLP_PATCHED.Quoted 23 lines
Moreover, due to
klp_complete_transition()klp_target_stateis alwaysKLP_UNDEFINEDafter it.Quoted 5 lines
kernel/livepatch/transition.c +5
-0+ +/* +* In the enable error path, even immediate patches can be safely +* removed because the transition hasn't been started yet. +* kernel/livepatch/transition.c static void klp_complete_transition(void)
Quoted 10 lines
kernel/livepatch/transition.c +10
-0+* klp_complete_transition() doesn't have a module_put() for immediate +* patches, so do it here. +*/ +klp_for_each_object (klp_transition_patch, obj) +klp_for_each_func (obj, func) +if (func->immediate) + immediate_func = true; + +if (klp_transition_patch->immediate || immediate_func) +module_put (klp_transition_patch->mod);Almost correct. The only problem is that
klp_transition_patchis NULL at this point.klp_complete_transition()does that and it should stay there in my opinion to keep it simple.Quoted 5 lines
So we could either move all this to
__klp_enable_patch(), where patch variable is defined, or we could storeklp_transition_patchto a local variable here inklp_cancel_transition()beforeklp_complete_transition()is called. That should be safe. I like the latter more, because it keeps the code inklp_cancel_transition()where it belongs.Good points. Here's another try:
kernel/livepatch/transition.c +15
-1@@ -121,8 +121,31 @@ static void klp_complete_transition(void)*/ void klp_cancel_transition (void ) { - klp_target_state = !klp_target_state; +struct klp_patch *patch = klp_transition_patch; +struct klp_object *obj; +struct klp_func *func; +bool immediate_func = false; + +if (WARN_ON_ONCE (klp_target_state !=KLP_PATCHED )) +return ; + + klp_target_state =KLP_UNPATCHED ;klp_complete_transition (); + +/* +* In the enable error path, even immediate patches can be safely +* removed because the transition hasn't been started yet. +* +* klp_complete_transition() doesn't have a module_put() for immediate
kernel/livepatch/transition.c static void klp_complete_transition(void) · line 149
Quoted 10 lines
kernel/livepatch/transition.c +9
-0+* patches, so do it here. +*/ +klp_for_each_object (patch, obj) +klp_for_each_func (obj, func) +if (func->immediate) + immediate_func = true; + +if (patch->immediate || immediate_func) +module_put (patch->mod); }
Looks ok.
Thanks,
Miroslav
Re: [PATCH v5 13/15] livepatch: change to a per-task consistency model
In reply to Josh PoimboeufQuoted 82 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.
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 haveHAVE_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 withoutHAVE_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 likeschedule(), 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 setpatch->immediatewhich 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_STACKTRACEmay 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.
Quoted 8 lines
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]
Signed-off-by Josh Poimboeuf <[email protected]>
I looked at the patch again and could not see any problem with it. I tested it with a couple of live patches too and it worked as expected. Good job.
Thanks,
Miroslav
Re: [PATCH v5 13/15] livepatch: change to a per-task consistency model
In reply to Josh PoimboeufQuoted 7 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.
Signed-off-by Josh Poimboeuf <[email protected]>
Just for record, this last version looks fine to me. I do not see problems any longer. Everything looks consistent now ;-) It is a great work. Feel free to use:
Thanks a lot for patience.
Best Regards,
Petr
Peter Zijlstra
maintainerRe: [PATCH v5 13/15] livepatch: change to a per-task consistency model
In reply to Josh PoimboeufQuoted 13 lines · Josh Poimboeuf
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); }
Can someone explain this one? This is a very weird place to add things. What was the expectation?
Petr Mladek
maintainerRe: [PATCH v5 13/15] livepatch: change to a per-task consistency model
Quoted 15 lines · Peter Zijlstra
Quoted 14 lines · Josh Poimboeuf
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 9 lines
kernel/sched/idle.c static void do_idle(void) · line 271
Quoted 6 lines
kernel/sched/idle.c +3
-0sched_ttwu_pending ();schedule_preempt_disabled (); + +if (unlikely (klp_patch_pending (current))) +klp_update_patch_state (current); }Can someone explain this one? This is a very weird place to add things. What was the expectation?
AFAIK, it was the least ugly and minimalist solution that we came with.
The tasks are migrated to the new patch when neither of the patched functions is on the stack. The stack can be checked safely only when the task is not running. It might be very hard to catch the idle task on a such a place if we patch something that is used there.
If the idle task is scheduled, you would need to create some fake load on the system, try to migrate the idle task, stop the fake load on the CPU.
The above code makes the idle task to migrate itself on a sane place. You just need to schedule some minimalist job on the CPU. The idle task will do one loop, gets migrated, and might be scheduled again immediately.
Best Regards,
Petr
Peter Zijlstra
maintainerRe: [PATCH v5 13/15] livepatch: change to a per-task consistency model
Quoted 33 lines · Petr Mladek
Quoted 15 lines · Peter Zijlstra
Quoted 14 lines · Josh Poimboeuf
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 9 lines
kernel/sched/idle.c static void do_idle(void) · line 271
Quoted 6 lines
kernel/sched/idle.c +3
-0sched_ttwu_pending ();schedule_preempt_disabled (); + +if (unlikely (klp_patch_pending (current))) +klp_update_patch_state (current); }Can someone explain this one? This is a very weird place to add things. What was the expectation?
AFAIK, it was the least ugly and minimalist solution that we came with.
The tasks are migrated to the new patch when neither of the patched functions is on the stack. The stack can be checked safely only when the task is not running. It might be very hard to catch the idle task on a such a place if we patch something that is used there.
Quoted 8 lines
If the idle task is scheduled, you would need to create some fake load on the system, try to migrate the idle task, stop the fake load on the CPU.
The above code makes the idle task to migrate itself on a sane place. You just need to schedule some minimalist job on the CPU. The idle task will do one loop, gets migrated, and might be scheduled again immediately.
What I was getting at, the klp stuff is the very first thing we run when we schedule the idle task, but its placed at the very end of the function. This is confusing.
The above still doesn't help with solving that. Do you want to run something before we go idle, or before we leave idle, in neither cases would I place it where it is.
Petr Mladek
maintainerRe: [PATCH v5 13/15] livepatch: change to a per-task consistency model
Quoted 38 lines · Peter Zijlstra
Quoted 37 lines · Petr Mladek
Quoted 15 lines · Peter Zijlstra
Quoted 14 lines · Josh Poimboeuf
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 9 lines
kernel/sched/idle.c static void do_idle(void) · line 271
Quoted 6 lines
kernel/sched/idle.c +3
-0sched_ttwu_pending ();schedule_preempt_disabled (); + +if (unlikely (klp_patch_pending (current))) +klp_update_patch_state (current); }Can someone explain this one? This is a very weird place to add things. What was the expectation?
AFAIK, it was the least ugly and minimalist solution that we came with.
The tasks are migrated to the new patch when neither of the patched functions is on the stack. The stack can be checked safely only when the task is not running. It might be very hard to catch the idle task on a such a place if we patch something that is used there.
If the idle task is scheduled, you would need to create some fake load on the system, try to migrate the idle task, stop the fake load on the CPU.
Quoted 8 lines
Quoted 4 lines
The above code makes the idle task to migrate itself on a sane place. You just need to schedule some minimalist job on the CPU. The idle task will do one loop, gets migrated, and might be scheduled again immediately.
What I was getting at, the klp stuff is the very first thing we run when we schedule the idle task, but its placed at the very end of the function. This is confusing.
I see.
Quoted 3 lines
The above still doesn't help with solving that. Do you want to run something before we go idle, or before we leave idle, in neither cases would I place it where it is.
In fact, both ways are fine. We require going the idle task through the entire cycle anyway. It is because both situations, too long idling or non-idling, would block finishing the patch transition.
Feel free to move it right before schedule_idle() or __current_set_polling().
Or should I send a patch?
Best Regards,
Petr
Peter Zijlstra
maintainerRe: [PATCH v5 13/15] livepatch: change to a per-task consistency model
Quoted 11 lines · Petr Mladek
Quoted 3 lines
What I was getting at, the klp stuff is the very first thing we run when we schedule the idle task, but its placed at the very end of the function. This is confusing.
I see.
Quoted 3 lines
The above still doesn't help with solving that. Do you want to run something before we go idle, or before we leave idle, in neither cases would I place it where it is.
Quoted 7 lines
In fact, both ways are fine. We require going the idle task through the entire cycle anyway. It is because both situations, too long idling or non-idling, would block finishing the patch transition.
Feel free to move it right before
schedule_idle()or__current_set_polling().
OK, I'll move it. Thanks!
PATCH v5 14/15 livepatch: add /proc/<pid>/patch_state
In reply to Josh PoimboeufExpose 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
@@ -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
@@ -1887,6 +1888,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
@@ -2828,6 +2828,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 */
@@ -2927,6 +2936,9 @@ static const struct pid_entry tgid_base_stuff[] = {REG ("timers" ,S_IRUGO , proc_timers_operations), #endifREG ("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)
@@ -3309,6 +3321,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
PATCH v5 15/15 livepatch: allow removal of a disabled patch
In reply to Josh PoimboeufFrom: 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.
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 neither 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]
[Thanks to Petr Mladek for improving the commit message.]
--- Documentation/livepatch/livepatch.txt | 28 ++++-------- 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(+), 52 deletions(-)
Documentation/livepatch/livepatch.txt +9 -19
@@ -316,8 +316,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 =======================
@@ -469,23 +476,6 @@ The current Livepatch implementation has several limitations: by "notrace". - + 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
@@ -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
@@ -59,6 +59,7 @@ static void klp_complete_transition(void)struct klp_func *func;struct task_struct *g, *task;unsigned int cpu; +bool is_immediate = false;if (klp_target_state ==KLP_UNPATCHED ) {/*
@@ -79,9 +80,16 @@ static void klp_complete_transition(void)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);/* Prevent klp_ftrace_handler() from seeing KLP_UNDEFINED state */ if (klp_target_state ==KLP_PATCHED )
samples/livepatch/livepatch-sample.c +0 -1
@@ -99,7 +99,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
PATCH v5 15/15 livepatch: allow removal of a disabled patch
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.
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 neither 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]
[Thanks to Petr Mladek for improving the commit message.]
---
v5.1: improve error handling in enable path -- call module_put() in
klp_cancel_transition()
Documentation/livepatch/livepatch.txt | 28 ++++-------- include/linux/livepatch.h | 3 ++ kernel/livepatch/core.c | 80 ++++++++++++++++++++++------------- kernel/livepatch/transition.c | 37 ++++++++++++++-- samples/livepatch/livepatch-sample.c | 1 - 5 files changed, 96 insertions(+), 53 deletions(-)
Documentation/livepatch/livepatch.txt +9 -19
@@ -316,8 +316,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 =======================
@@ -469,23 +476,6 @@ The current Livepatch implementation has several limitations: by "notrace". - + 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
@@ -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 +34 -3
@@ -59,6 +59,7 @@ static void klp_complete_transition(void)struct klp_func *func;struct task_struct *g, *task;unsigned int cpu; +bool immediate_func = false;if (klp_target_state ==KLP_UNPATCHED ) {/*
@@ -79,9 +80,16 @@ static void klp_complete_transition(void)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) + immediate_func = true; + } + } + +if (klp_target_state ==KLP_UNPATCHED && !immediate_func) +module_put (klp_transition_patch->mod);/* Prevent klp_ftrace_handler() from seeing KLP_UNDEFINED state */ if (klp_target_state ==KLP_PATCHED )
@@ -113,8 +121,31 @@ static void klp_complete_transition(void)*/ void klp_cancel_transition (void ) { - klp_target_state = !klp_target_state; +struct klp_patch *patch = klp_transition_patch; +struct klp_object *obj; +struct klp_func *func; +bool immediate_func = false; + +if (WARN_ON_ONCE (klp_target_state !=KLP_PATCHED )) +return ; + + klp_target_state =KLP_UNPATCHED ;klp_complete_transition (); + +/* +* In the enable error path, even immediate patches can be safely +* removed because the transition hasn't been started yet. +* +* klp_complete_transition() doesn't have a module_put() for immediate +* patches, so do it here. +*/ +klp_for_each_object (patch, obj) +klp_for_each_func (obj, func) +if (func->immediate) + immediate_func = true; + +if (patch->immediate || immediate_func) +module_put (patch->mod); }/*
samples/livepatch/livepatch-sample.c +0 -1
@@ -99,7 +99,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
Re: [PATCH v5.1 15/15] livepatch: allow removal of a disabled patch
Quoted 44 lines · Josh Poimboeuf
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: Fixmod->mkobj.kobjpotentially 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_patchfromklp_register_patchto 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.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 withoutklp_mutex. Otherwise, it might be blocked byenabled_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 neither 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 8 lines
[Thanks to Petr Mladek for improving the commit message.]
Signed-off-by Miroslav Benes <[email protected]>Signed-off-by Josh Poimboeuf <[email protected]>Reviewed-by Petr Mladek <[email protected]>---
v5.1: improve error handling in enable path -- callmodule_put()in
klp_cancel_transition()
Looks good.
if it is needed for Josh's code.
Regards,
Miroslav
Miroslav Benes
maintainerQuoted 14 lines · Josh Poimboeuf
Here's v5 of the consistency model, targeted for 4.12. Only a few minor changes this time.
v5:
- return-EINVALin__save_stack_trace_reliable()
- only callshow_stack()once
- addsave_stack_trace_tsk_reliable()define for !CONFIG_STACKTRACE
- update kernel version and date in ABI doc
- make suggested improvements to livepatch.txt
- update barrier comments
- removeklp_try_complete_transition()call fromklp_start_transition()
- move end ofklp_try_complete_transition()intoklp_complete_transition()
- fix__klp_enable_patch()error path
- check for transition inklp_module_going()
All the changes since v4 look good to me (except for module_put() in __klp_enable_patch() mentioned elsewhere).
Thanks,
Miroslav
Quoted 11 lines · Josh Poimboeuf
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 | 13 +- arch/x86/include/asm/unwind.h | 6 + arch/x86/kernel/stacktrace.c | 96 +++- arch/x86/kernel/unwind_frame.c | 2 +
for the x86 and scheduler changes:
Thanks,
Ingo
Quoted 1 line · Josh Poimboeuf
Here's v5 of the consistency model
I have ammended the patches with all the received ACKs and applied to 'for-4.12/klp-hybrid-consistency-model' branch of livepatching.git.
Thanks,
Signature · 2 lines
Jiri Kosina SUSE Labs