x86: Quiesce text_poke() IPIs
Subsystems (9)
Valentin Schneider
reviewerv10 cover x86: Quiesce text_poke() IPIs
Christmas comes early this year, here's v10!
Context
=======
We've observed within Red Hat that isolated, NOHZ_FULL CPUs running a pure-userspace application get regularly interrupted by IPIs sent from housekeeping CPUs. Those IPIs are caused by activity on the housekeeping CPUs leading to various on_each_cpu() calls; this series is tackling the ones coming from
smp_text_poke_*()
`\
smp_text_poke_sync_each_cpu()In the wild we mostly see these from static key updates and BPF JIT'ing. All sorts of kernel text updates can trigger them:
$ global -v --result=grep --color=always --path-style=shorter --from-here=3136:arch/x86/kernel/alternative.c -- smp_text_poke_single arch/x86/include/asm/text-patching.h:47:extern void smp_text_poke_single(void *addr, const void *opcode, size_t len, const void *emulate); arch/x86/kernel/ftrace.c:194: smp_text_poke_single((void *)ip, new, MCOUNT_INSN_SIZE, NULL); arch/x86/kernel/ftrace.c:198: smp_text_poke_single((void *)ip, new, MCOUNT_INSN_SIZE, NULL); arch/x86/kernel/ftrace.c:507: smp_text_poke_single((void *)ip, new, MCOUNT_INSN_SIZE, NULL); arch/x86/kernel/ftrace.c:601: smp_text_poke_single((void *)ip, new, MCOUNT_INSN_SIZE, NULL); arch/x86/kernel/jump_label.c:105: smp_text_poke_single((void *)jump_entry_code(entry), jlp.code, jlp.size, NULL); arch/x86/kernel/kprobes/opt.c:486: smp_text_poke_single(op->kp.addr, insn_buff, JMP32_INSN_SIZE, NULL); arch/x86/kernel/static_call.c:142: smp_text_poke_single(insn, code, size, emulate); arch/x86/net/bpf_jit_comp.c:657: smp_text_poke_single(ip, new_insn, X86_PATCH_SIZE, NULL);
global -v --result=grep --color=always --path-style=shorter --from-here=2846:arch/x86/kernel/alternative.c -- smp_text_poke_batch_finish arch/x86/include/asm/text-patching.h:50:extern void smp_text_poke_batch_finish(void); arch/x86/kernel/alternative.c:3120: smp_text_poke_batch_finish(); arch/x86/kernel/alternative.c:3139: smp_text_poke_batch_finish(); arch/x86/kernel/ftrace.c:61: smp_text_poke_batch_finish(); arch/x86/kernel/ftrace.c:258: smp_text_poke_batch_finish(); arch/x86/kernel/jump_label.c:146: smp_text_poke_batch_finish();
Approach
========
The heart of this series is the thought that while we cannot remove NOHZ_FULL CPUs from the list of CPUs targeted by these IPIs, they may not have to execute the callbacks immediately. Anything that only affects kernelspace can wait until the next user->kernel transition, providing it can be executed "early enough" in the entry code as a postponed operation.
The original implementation is from Peter [1]. Nicolas then added kernel TLB invalidation deferral to that [2], and I picked it up from there.
Previous submissions included mitigations for both text_poke() and vmalloc()/vfree(), this time around it's just text_poke() - I have updated code for vmalloc()/vfree() but it's really fugly, and the text_poke() stuff is more pressing. Also, that's enough assembly faff for one patchset.
text_poke() requires executing a serializing instruction on all CPUs, thus its postponed operation must be a serializing instruction. Turns out we're in luck, as the kPTI CR3 RMW is just that:
SDM vol2 chapter 4.3 - Move to/from control registers:
``` MOV CR* instructions, except for MOV CR8, are serializing instructions. ```
That means we don't need to do anything extra on kernel entry to handle quiesced sync_core() IPIs coming from text_poke() (other than leverage kPTI).
Kernel entry vs execution of the postponed operation
====================================================
This is what I've referred to as the "Danger Zone" during my LPC24 talk [4].
There is a non-zero length of code that is executed upon kernel entry before the postponed operation can be itself executed (before we switch to the kernel CR3), i.e.:
idtentry
idtentry_body
error_entry
SWITCH_TO_KERNEL_CR3
This danger zone used to be much wider in v7 and earlier (from kernel entry all the way down to ct_kernel_enter_state()). The objtool instrumentation thus now targets .entry.text rather than .noinstr as a whole.
kPTI woes
=========
I only learned today that even with kPTI enabled in the Kconfig, a lot of hardware does not actually require PTI and disables it at boot. You can imagine my reaction to this if you look at the amount of faffing I've done in the kPTI SITCH_TO_*_CR3 code.
Buuut there may still be some value to it - I'm using the text_poke() stuff as a foundation for the tlb_flush quiescing, and that *does* require *at least* a CR3 RMW. Again for that I was relying on kPTI limiting the global pages to not have to add a pure ASM CR4 sequence. So I should be able to reuse a lot of that code, but that puts me in a bad spot where I'm submitting quite intrusive code for a feature that isn't even in the patchset...
So yeah, thoughts welcome here!
Testing
=======
(May require pti=on depending on your hardware setup)
QEMU
++++
Tested with GDB single-stepping to check the ASM static key behaviour. Used the 'nmi' command to trigger the NMI entry paths, although I couldn't get NMI nesting to happen.
Real hardware
+++++++++++++
Tested on a dual-socket Intel(R) Xeon(R) CPU E5-2699 system with SMToff, NOHZ_FULL, 26 isolated CPUs. RHEL10 userspace.
BPF kselftests, the fentry one:
```
cleanup () { kill $(jobs -p); echo on > /sys/devices/system/cpu/smt/control; }
trap "cleanup" INT
echo off > /sys/devices/system/cpu/smt/control
ISOL_CPUS=5-17,23-35
ISOL_CPUS_ARRAY=(5 6 7 8 9 10 11 12 13 14 15 16 17 23 24 25 26 27 28 29 30 31 32 33 34 35)
for cpu in ${ISOL_CPUS_ARRAY[@]}; do
echo $cpu
taskset -c $cpu bash -c "while true; do continue; done" &
chrt -f -p 1 $!
done
trace-cmd record -e "csd_queue_cpu" -f "cpu & CPUS{$ISOL_CPUS}" \
-e "ipi_send_cpumask" -f "cpumask & CPUS{$ISOL_CPUS}" \
-e "ipi_send_cpu" -f "cpu & CPUS{$ISOL_CPUS}" \
./test_progs -t fentry_test
cleanup
wait
```*Most* of the smp_text_poke_batch_finish() IPIs are gone with the patches, the one or two that remain are due to other, preceding IPIs forcing the isolated CPUs out of userspace, making the quiescing condition fail.
Running rteval I mostly get flooded with =flush_tlb_kernel_range()= IPIs, which season 2 of this should take care of.
Patches
=======
o Patches 1-4 are standalone objtool cleanups.
o Patches 5-6 add infrastructure for annotating static keys that may be used in entry code (courtesy of Josh).
o Patch 7 adds ASM support for static keys
o Patches 8-10 add the deferral mechanism.
Patches are also available at:
https://gitlab.com/vschneid/linux.git -b redhat/isolirq/defer/v10
Acknowledgements
================
Special thanks to:
o Clark Williams for listening to my ramblings about this and throwing ideas my way
o Josh Poimboeuf for all his help with everything objtool-related
o Dave Hansen for patiently educating me about mm
o All of the folks who attended various (too many?) talks about this and provided precious feedback.
Links
=====
[1]: https://lore.kernel.org/all/[email protected]/
[2]: https://github.com/vianpl/linux.git -b ct-work-defer-wip [3]: https://lpc.events/event/19/contributions/2219/
[4]: https://lpc.events/event/18/contributions/1889/
Revisions
=========
v9 -> v10
+++++++++
o Rebased onto v7.3-rc4
o Overall renaming of "IPI deferral" to "IPI quiescing" (nikbor)
o Now handles NMI entry!
o Ditched the flush_tlb_kernel_range() stuff this time again, for now
v8 -> v9
++++++++
o Rebased onto v7.1-rc1-ish (507bd4b66c85)
o Caught up to housekeeping_overridden now being dynamic; revived alternative.c code that deals with static keys in early entry code (Shrikanth)
o Messed about ordering of @kernel_cr3_loaded accesses (Frederic)
v7 -> v8
++++++++
o Rebased onto v6.19
o Fixed objtool --uaccess validation preventing --noinstr validation of unwind hints
o Added more objtool --noinstr warning fixes
o Reduced objtool noinstr static key validation to just .entry.text
o I've kept the "simple" __ro_after_init conversions
o Moved the kernel_cr3_loaded signal update to before writing to CR3
o Ditched context_tracking based deferral
o Ditched the (additionnal) unconditionnal TLB flush upon kernel entry
v6 -> v7
++++++++
o Rebased onto latest v6.18-rc5 (6fa9041b7177f)
o Collected Acks (Sean, Frederic)
o Fixed <asm/context_tracking_work.h> include (Shrikanth)
o Fixed ct_set_cpu_work() CT_RCU_WATCHING logic (Frederic)
o Wrote more verbose comments about NOINSTR static keys and calls (Petr)
o [NEW PATCH] Instrumented one more static key: cpu_bf_vm_clear
o [NEW PATCH] added ASM-accessible static key helpers to gate NO_HZ_FULL logic in early entry code (Frederic)
v5 -> v6
++++++++
o Rebased onto v6.17
o Small conflict fixes with cpu_buf_idle_clear smp_text_poke() renaming
o Added the TLB flush craziness
v4 -> v5
++++++++
o Rebased onto v6.15-rc3
o Collected Reviewed-by
o Annotated a few more static keys
o Added proper checking of noinstr sections that are in loadable code such as KVM early entry (Sean Christopherson)
o Switched to checking for CT_RCU_WATCHING instead of CT_STATE_KERNEL or CT_STATE_IDLE, which means deferral is now behaving sanely for IRQ/NMI entry from idle (thanks to Frederic!)
o Ditched the vmap TLB flush deferral (for now)
RFCv3 -> v4
+++++++++++
o Rebased onto v6.13-rc6
o New objtool patches from Josh
o More .noinstr static key/call patches
o Static calls now handled as well (again thanks to Josh)
o Fixed clearing the work bits on kernel exit
o Messed with IRQ hitting an idle CPU vs context tracking
o Various comment and naming cleanups
o Made RCU_DYNTICKS_TORTURE depend on !COMPILE_TEST (PeterZ)
o Fixed the CT_STATE_KERNEL check when setting a deferred work (Frederic)
o Cleaned up the __flush_tlb_all() mess thanks to PeterZ
RFCv2 -> RFCv3
++++++++++++++
o Rebased onto v6.12-rc6
o Added objtool documentation for the new warning (Josh)
o Added low-size RCU watching counter to TREE04 torture scenario (Paul)
o Added FORCEFUL jump label and static key types
o Added noinstr-compliant helpers for tlb flush deferral
RFCv1 -> RFCv2
++++++++++++++
o Rebased onto v6.5-rc1
o Updated the trace filter patches (Steven)
o Fixed __ro_after_init keys used in modules (Peter)
o Dropped the extra context_tracking atomic, squashed the new bits in the existing .state field (Peter, Frederic)
o Added an RCU_EXPERT config for the RCU dynticks counter size, and added an rcutorture case for a low-size counter (Paul)
o Fixed flush_tlb_kernel_range_deferrable() definition
Josh Poimboeuf (2):
jump_label: Add annotations for validating .entry.text key usage
objtool: Add .entry.text validation for static branches
Valentin Schneider (8):
objtool: Make validate_call() recognize indirect calls to pv_ops[]
objtool: Flesh out warning related to pv_ops[] calls
objtool: Always pass a section to validate_unwind_hints() x86/retpoline: Make warn_thunk_thunk .noinstr x86/jump_label: Add ASM support for static_branch_likely() x86/mm/pti: Introduce kernel_cr3_loaded
x86/mm/pti: Drive kernel_cr3_loaded
context_tracking,x86: Quiesce kernel text patching IPIs when tracking
CR3 switches
arch/x86/Kconfig | 14 +++ arch/x86/entry/calling.h | 71 +++++++++++++ arch/x86/entry/entry.S | 3 +- arch/x86/include/asm/cpu_entry_area.h | 4 + arch/x86/include/asm/jump_label.h | 34 +++++- arch/x86/include/asm/pti.h | 11 ++ arch/x86/include/asm/text-patching.h | 5 + arch/x86/include/uapi/asm/processor-flags.h | 3 + arch/x86/kernel/alternative.c | 59 +++++++++-- arch/x86/kernel/asm-offsets.c | 3 + arch/x86/kernel/cpu/bugs.c | 2 +- arch/x86/kernel/kprobes/core.c | 4 +- arch/x86/kernel/kprobes/opt.c | 4 +- arch/x86/kernel/module.c | 2 +- arch/x86/mm/cpu_entry_area.c | 5 + arch/x86/mm/pti.c | 40 ++++--- include/asm-generic/sections.h | 14 +++ include/linux/jump_label.h | 27 ++++- include/linux/objtool.h | 16 +++ kernel/sched/isolation.c | 9 +- tools/objtool/Documentation/objtool.txt | 15 +++ tools/objtool/check.c | 111 +++++++++++++++++--- tools/objtool/include/objtool/check.h | 2 + tools/objtool/include/objtool/elf.h | 3 +- tools/objtool/include/objtool/special.h | 1 + tools/objtool/special.c | 15 ++- 26 files changed, 428 insertions(+), 49 deletions(-)
--
2.56.1
Valentin Schneider
reviewerPATCH v10 1/10 objtool: Make validate_call() recognize indirect calls to pv_ops[]
call_dest_name() does not get passed the file pointer of validate_call(), which means its invocation of insn_reloc() will always return NULL. Make it take a file pointer.
While at it, make sure call_dest_name() uses arch_dest_reloc_offset(), otherwise it gets the pv_ops[] offset wrong.
Fabricating an intentional warning shows the change; previously:
vmlinux.o: warning: objtool: __flush_tlb_all_noinstr+0x4: call to {dynamic}() leaves .noinstr.text section
now:
vmlinux.o: warning: objtool: __flush_tlb_all_noinstr+0x4: call to pv_ops[1]() leaves .noinstr.text section
--- tools/objtool/check.c | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-)
tools/objtool/check.c +8 -6
@@ -3423,7 +3423,7 @@ static inline bool func_uaccess_safe(struct symbol *func)return false; } -static inline const char *call_dest_name (struct instruction *insn) +static inline const char *call_dest_name (struct objtool_file *file,struct instruction *insn) {static char pvname[19 ];struct reloc *reloc;
@@ -3432,9 +3432,9 @@ static inline const char *call_dest_name(struct instruction *insn)if (insn_call_dest (insn))return insn_call_dest (insn)->name; - reloc =insn_reloc (NULL , insn); + reloc =insn_reloc (file, insn);if (reloc && !strcmp (reloc->sym->name,"pv_ops" )) { - idx = (reloc_addend (reloc) /sizeof (void *)); + idx =arch_insn_adjusted_addend (insn, reloc) /sizeof (void *);snprintf (pvname,sizeof (pvname),"pv_ops[%d]" , idx);return pvname; }
@@ -3513,17 +3513,19 @@ static int validate_call(struct objtool_file *file, {if (state->noinstr && state->instr <=0 && !noinstr_call_dest (file, insn,insn_call_dest (insn))) { -WARN_INSN (insn,"call to %s() leaves .noinstr.text section" ,call_dest_name (insn)); +WARN_INSN (insn,"call to %s() leaves .noinstr.text section" ,call_dest_name (file, insn));return 1 ; }if (state->uaccess && !func_uaccess_safe (insn_call_dest (insn))) { -WARN_INSN (insn,"call to %s() with UACCESS enabled" ,call_dest_name (insn)); +WARN_INSN (insn,"call to %s() with UACCESS enabled" , +call_dest_name (file, insn));return 1 ; }if (state->df) { -WARN_INSN (insn,"call to %s() with DF set" ,call_dest_name (insn)); +WARN_INSN (insn,"call to %s() with DF set" , +call_dest_name (file, insn));return 1 ; }
Signature · 1 line
2.56.1
Valentin Schneider
reviewerPATCH v10 2/10 objtool: Flesh out warning related to pv_ops[] calls
In reply to Valentin SchneiderI had to look into objtool itself to understand what this warning was about; make it more explicit.
--- tools/objtool/check.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
tools/objtool/check.c +1 -1
@@ -3461,7 +3461,7 @@ static bool pv_call_dest(struct objtool_file *file, struct instruction *insn)list_for_each_entry (target, &file->pv_ops[idx].targets, pv_target) {if (!target->sec->noinstr) { -WARN ("pv_ops[%d]: %s" , idx, target->name); +WARN ("pv_ops[%d]: indirect call to %s() leaves .noinstr.text section" , idx, target->name); file->pv_ops[idx].clean = false; } }
Signature · 1 line
2.56.1
Valentin Schneider
reviewerPATCH v10 3/10 objtool: Always pass a section to validate_unwind_hints()
In reply to Valentin SchneiderWhen passing a NULL @sec to validate_unwind_hints(), it is unable to properly initialize the insn_state->noinstr passed down during validation. This means we lose noinstr validation of the hints.
That validation currently happens when 'opts.noinstr' is true but 'validate_branch_enabled()' isn't.
In other words, this will run noinstr validation of hints:
$ objtool --noinstr --link [...] but this won't: $ objtool --noinstr --link --uaccess [...]
Always pass a valid section to validate_unwind_hints(), so that noinstr validation of hints happens regardless of the value of validate_branch_enabled().
--- tools/objtool/check.c | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-)
tools/objtool/check.c +19 -8
@@ -4011,13 +4011,8 @@ static int validate_unwind_hints(struct objtool_file *file, struct section *sec)init_insn_state (file, &state, sec); -if (sec) { -sec_for_each_insn (file, sec, insn) - warnings +=validate_unwind_hint (file, insn, &state); - }else { -for_each_insn (file, insn) - warnings +=validate_unwind_hint (file, insn, &state); - } +sec_for_each_insn (file, sec, insn) + warnings +=validate_unwind_hint (file, insn, &state);return warnings; }
@@ -4460,6 +4455,21 @@ static int validate_functions(struct objtool_file *file)return warnings; } +static int validate_file_unwind_hints (struct objtool_file *file) +{ +struct section *sec; +int warnings =0 ; + +for_each_sec (file->elf, sec) { +if (!is_text_sec (sec)) +continue ; + + warnings +=validate_unwind_hints (file, sec); + } + +return warnings; +} +static void mark_endbr_used (struct instruction *insn) {if (!list_empty (&insn->call_node))
@@ -4849,7 +4859,8 @@ int check(struct objtool_file *file)int w =0 ; w +=validate_functions (file); - w +=validate_unwind_hints (file,NULL ); + w +=validate_file_unwind_hints (file); +if (!w) w +=validate_reachable_instructions (file);
Signature · 1 line
2.56.1
Valentin Schneider
reviewerPATCH v10 4/10 x86/retpoline: Make warn_thunk_thunk .noinstr
In reply to Valentin SchneiderObjtool now warns about it:
vmlinux.o: warning: objtool: .altinstr_replacement+0x28e1: call to warn_thunk_thunk() leaves .noinstr.text section
Mark it noinstr.
--- arch/x86/entry/entry.S | 3 ++- arch/x86/kernel/cpu/bugs.c | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-)
arch/x86/entry/entry.S +2 -1
@@ -40,6 +40,8 @@ SYM_FUNC_START(__WARN_trap) SYM_FUNC_END(__WARN_trap) EXPORT_SYMBOL(__WARN_trap) +THUNK warn_thunk_thunk, __warn_thunk + .popsection /*
@@ -60,7 +62,6 @@ EXPORT_SYMBOL_FOR_KVM(x86_verw_sel); .popsection -THUNK warn_thunk_thunk, __warn_thunk /* * Clang's implementation of TLS stack cookies requires the variable in
arch/x86/kernel/cpu/bugs.c +1 -1
@@ -3771,7 +3771,7 @@ ssize_t cpu_show_vmscape(struct device *dev, struct device_attribute *attr, char }#endif -void __warn_thunk (void ) +void noinstr __warn_thunk(void) {WARN_ONCE (1 ,"Unpatched return thunk in use. This should not happen!\n" ); }
Signature · 1 line
2.56.1
Valentin Schneider
reviewerPATCH v10 5/10 jump_label: Add annotations for validating .entry.text key usage
In reply to Valentin SchneiderFrom: Josh Poimboeuf <[email protected]>
Adding static keys to entry text needs to be done with care, as they may be executed before a context serialization operation has been run. Add DEFINE_STATIC_KEY_*_ENTRY() variants for those. They don't do anything special yet; that will come later.
--- include/linux/jump_label.h | 14 ++++++++++++++ 1 file changed, 14 insertions(+)
include/linux/jump_label.h +14 -0
@@ -374,6 +374,20 @@ struct static_key_false {#define DEFINE_STATIC_KEY_FALSE_RO (name) \ struct static_key_false name __ro_after_init = STATIC_KEY_FALSE_INIT +/* +* Objtool will warn about static keys used in early entry code, as they may +* be unsafe if executed before any serializing operation. +* +* The _ENTRY variants are used to tell objtool the static key is safe to be +* used. If using one of these _ENTRY variants, please add a comment above the +* definition with the rationale. +*/ +#define DEFINE_STATIC_KEY_TRUE_ENTRY (name) \ + DEFINE_STATIC_KEY_TRUE(name) + +#define DEFINE_STATIC_KEY_FALSE_ENTRY (name) \ + DEFINE_STATIC_KEY_FALSE(name) +#define DECLARE_STATIC_KEY_FALSE (name) \ extern struct static_key_false name
Signature · 1 line
2.56.1
Valentin Schneider
reviewerPATCH v10 6/10 objtool: Add .entry.text validation for static branches
In reply to Valentin SchneiderFrom: Josh Poimboeuf <[email protected]>
Warn about static branches in entry text, unless the corresponding key is RO-after-init.
--- include/linux/jump_label.h | 17 ++++--- include/linux/objtool.h | 16 ++++++ tools/objtool/Documentation/objtool.txt | 15 ++++++ tools/objtool/check.c | 68 ++++++++++++++++++++++++- tools/objtool/include/objtool/check.h | 2 + tools/objtool/include/objtool/elf.h | 3 +- tools/objtool/include/objtool/special.h | 1 + tools/objtool/special.c | 15 +++++- 8 files changed, 128 insertions(+), 9 deletions(-)
include/linux/jump_label.h +11 -6
@@ -76,6 +76,7 @@#include <linux/types.h> #include <linux/compiler.h> #include <linux/cleanup.h> +#include <linux/objtool.h> extern bool static_key_initialized;
@@ -362,8 +363,9 @@ struct static_key_false {#define DEFINE_STATIC_KEY_TRUE (name) \ struct static_key_true name = STATIC_KEY_TRUE_INIT -#define DEFINE_STATIC_KEY_TRUE_RO (name) \ - struct static_key_true name __ro_after_init = STATIC_KEY_TRUE_INIT +#define DEFINE_STATIC_KEY_TRUE_RO (name) \ + struct static_key_true name __ro_after_init = STATIC_KEY_TRUE_INIT; \ + ANNOTATE_ENTRY_ALLOWED(name)#define DECLARE_STATIC_KEY_TRUE (name) \ extern struct static_key_true name
@@ -371,8 +373,9 @@ struct static_key_false {#define DEFINE_STATIC_KEY_FALSE (name) \ struct static_key_false name = STATIC_KEY_FALSE_INIT -#define DEFINE_STATIC_KEY_FALSE_RO (name) \ - struct static_key_false name __ro_after_init = STATIC_KEY_FALSE_INIT +#define DEFINE_STATIC_KEY_FALSE_RO (name) \ + struct static_key_false name __ro_after_init = STATIC_KEY_FALSE_INIT; \ + ANNOTATE_ENTRY_ALLOWED(name)/* * Objtool will warn about static keys used in early entry code, as they may
@@ -383,10 +386,12 @@ struct static_key_false {* definition with the rationale. */ #define DEFINE_STATIC_KEY_TRUE_ENTRY (name) \ - DEFINE_STATIC_KEY_TRUE(name) + DEFINE_STATIC_KEY_TRUE(name); \ + ANNOTATE_ENTRY_ALLOWED(name)#define DEFINE_STATIC_KEY_FALSE_ENTRY (name) \ - DEFINE_STATIC_KEY_FALSE(name) + DEFINE_STATIC_KEY_FALSE(name); \ + ANNOTATE_ENTRY_ALLOWED(name)#define DECLARE_STATIC_KEY_FALSE (name) \ extern struct static_key_false name
include/linux/objtool.h +16 -0
@@ -34,6 +34,19 @@ static void __used __section(".discard.func_stack_frame_non_standard") \ *__func_stack_frame_non_standard_##func = func +#define __ANNOTATE_ENTRY_ALLOWED (key) \ + static void __used __section(".discard.entry_allowed") \ + *__annotate_entry_allowed_##key = &key + +/* +* This is used to tell objtool that a given static key is safe to be used +* within .noinstr code, and it doesn't need to generate a warning about it. +* +* For more information, see tools/objtool/Documentation/objtool.txt, +* "non-RO static key usage in entry code" +*/ +#define ANNOTATE_ENTRY_ALLOWED (key) __ANNOTATE_ENTRY_ALLOWED(key) +/* * STACK_FRAME_NON_STANDARD_FP() is a frame-pointer-specific function ignore * for the case where a function is intentionally missing frame pointer setup,
@@ -111,6 +124,9 @@#define UNWIND_HINT (type, sp_reg, sp_offset, signal) "\n\t"#define STACK_FRAME_NON_STANDARD (func)#define STACK_FRAME_NON_STANDARD_FP (func) +#define __ASM_ANNOTATE (label, type) "" +#define ASM_ANNOTATE (type) +#define ANNOTATE_ENTRY_ALLOWED (key)#else .macro UNWIND_HINT type:req sp_reg=0 sp_offset=0 signal=0 .endm
tools/objtool/Documentation/objtool.txt +15 -0
@@ -456,6 +456,21 @@ the objtool maintainers. these special names and does not use module_init() / module_exit() macros to create them. +vmlinux.o: warning: objtool: entry_SYSCALL_64+0x108: housekeeping_overridden: non-RO static key usage in entry code + +13. file.o: warning: func()+0x2a: key: non-RO static key usage in entry code + + This means that .entry.text function func() uses a static key named 'key' + which can be modified at runtime. This is discouraged because the jump + location may be accessed before a serializing operation has been + executed. + + Check whether the static key in question is only modified during init. If so, + define it as read-only-after-init with DEFINE_STATIC_KEY_*_RO(). + + Alternatively, if observing a stale/wrong value of the key isn't critical + (i.e. the system is in a transient state as lots of things are being updated), + you can mark it as safe with DEFINE_STATIC_KEY_*_ENTRY(). If the error doesn't seem to make sense, it could be a bug in objtool. Feel free to ask objtool maintainers for help.
tools/objtool/check.c +67 -1
111 lines not on this page · raw message
tools/objtool/include/objtool/check.h +2 -0
@@ -16,6 +16,7 @@ struct insn_state {bool uaccess;bool df;bool noinstr; +bool entry;s8 instr; };
@@ -98,6 +99,7 @@ struct instruction {struct symbol *_sym;struct stack_op *stack_ops;struct cfi_state *cfi; +struct symbol *key; };/*
tools/objtool/include/objtool/elf.h +2 -1
@@ -58,7 +58,7 @@ struct section {Elf_Data *data;const char *name;int idx; -bool _changed, text, rodata, noinstr, init, truncate; +bool _changed, text, rodata, noinstr, init, truncate, entry;struct reloc *relocs;unsigned long nr_alloc_relocs;struct section *twin;
@@ -98,6 +98,7 @@ struct symbol { u8 klp : 1; u8 dont_correlate : 1; u8 fake : 1; + u8 entry_allowed : 1;struct list_head pv_target;struct reloc *relocs;struct section *group_sec;
tools/objtool/include/objtool/special.h +1 -0
@@ -18,6 +18,7 @@ struct special_alt {bool group;bool jump_or_nop;u8 key_addend; +struct symbol *key;struct section *orig_sec;unsigned long orig_off;
tools/objtool/special.c +14 -1
@@ -111,13 +111,26 @@ static int get_alt_entry(struct elf *elf, const struct special_entry *entry,if (entry->key) {struct reloc *key_reloc; +struct symbol *key; +s64 key_addend; key_reloc =find_reloc_by_dest (elf, sec, offset + entry->key);if (!key_reloc) {ERROR_FUNC (sec, offset + entry->key,"can't find key reloc" );return -1 ; } - alt->key_addend =reloc_addend (key_reloc); + + key = key_reloc->sym; + key_addend =reloc_addend (key_reloc); + +if (key->type ==STT_SECTION ) + key =find_symbol_by_offset (key->sec, key_addend & ~3 ); + +/* embedded keys not supported */ +if (key) { + alt->key = key; + alt->key_addend = key_addend; + } }return 0 ;
Signature · 1 line
2.56.1
Valentin Schneider
reviewerPATCH v10 7/10 x86/jump_label: Add ASM support for static_branch_likely()
In reply to Valentin SchneiderA later commit will add some early entry code that only needs to be executed if nohz_full is present on the cmdline, not just if CONFIG_NO_HZ_FULL is compiled in. Add an ASM-callable static branch macro.
Note that I haven't found a way to express unlikely (i.e. out-of-line) static branches in ASM macros without using extra jumps, which kind of defeats the purpose. Consider:
.macro FOOBAR
// Key enabled: JMP .Ldostuff_\@ // Key disabled: NOP STATIC_BRANCH_UNLIKELY key, .Ldostuff_\@ // Patched to JMP if enabled jmp .Lend_\@
.Ldostuff_\@:
<dostuff>
.Lend_\@:
.endm
Instead, this should be expressed as a likely (i.e. in-line) static key:
.macro FOOBAR
// Key enabled: NOP // Key disabled: JMP .Lend_\@ STATIC_BRANCH_LIKELY key, .Lend\@ // Patched to NOP if enabled <dostuff>
.Lend_\@:
.endm
--- arch/x86/include/asm/jump_label.h | 34 ++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-)
arch/x86/include/asm/jump_label.h +33 -1
@@ -7,7 +7,39 @@#include <asm/asm.h> #include <asm/nops.h> -#ifndef __ASSEMBLER__ +#ifdef __ASSEMBLER__ + +/* +* There isn't a neat way to craft unlikely static branches in ASM, so they +* all have to be expressed as likely (inline) static branches. This macro +* thus assumes a "likely" usage. +*/ +.macro ARCH_STATIC_BRANCH_LIKELY_ASM key, label, jump, hack +.Lentry_code_\@: +.if \jump || \hack + jmp \label +.else + .byte BYTES_NOP5 +.endif + .pushsection __jump_table, "aw" + _ASM_ALIGN +ANNOTATE_DATA_SPECIAL + .long .Lentry_code_\@ - . + .long \label - . +/* LIKELY so bit0=1, bit1=hack */ + _ASM_PTR \key + 1 + (\hack << 1) - . + .popsection +.endm + +.macro STATIC_BRANCH_TRUE_LIKELY key, label + ARCH_STATIC_BRANCH_LIKELY_ASM \key, \label, 0, IS_ENABLED(CONFIG_HAVE_JUMP_LABEL_HACK) +.endm + +.macro STATIC_BRANCH_FALSE_LIKELY key, label + ARCH_STATIC_BRANCH_LIKELY_ASM \key, \label, 1, 0 +.endm + +#else /* !__ASSEMBLER__ */ #include <linux/stringify.h> #include <linux/types.h>
Signature · 1 line
2.56.1
Valentin Schneider
reviewerPATCH v10 8/10 x86/mm/pti: Introduce kernel_cr3_loaded
In reply to Valentin SchneiderLater commits will rely on being able to check whether a remote CPU is using the kernel or the user CR3.
Add a per-cpu variable that will be updated right before switching to the kernel CR3.
Note that this only adds the backing data, a later commit will drive the updates.
pcpu access in early entry
==========================
The variable is accessed through two different ways:
1) The general case where swapgs has already been executed, and the usual gs-based per-cpu offset is usable. This requires mapping the variable in the userspace visible pages, since CR3 hasn't been switched to the kernel CR3 yet.
2) The paranoid case where swapgs has *not* be executed, in which case a CEA alias is used.
security concerns
=================
That variable does not contain any exploitable data, and being in the .data..percpu..aligned section it occupies a whole page - that is, as long as it is not the last variable in that section. AFAICT the last one is always @entry_stack_storage (which by itself is a whole page), although I'm not sure if that's a happy accident or if it is actually enforced somehow?
--- arch/x86/include/asm/cpu_entry_area.h | 4 +++ arch/x86/include/asm/pti.h | 11 ++++++++ arch/x86/kernel/asm-offsets.c | 3 ++ arch/x86/mm/cpu_entry_area.c | 5 ++++ arch/x86/mm/pti.c | 40 +++++++++++++++++++-------- 5 files changed, 51 insertions(+), 12 deletions(-)
arch/x86/include/asm/cpu_entry_area.h +4 -0
@@ -127,6 +127,10 @@ struct cpu_entry_area {* Reserve enough fixmap PTEs. */ struct debug_store_buffers cpu_debug_buffers; + +#ifdef CONFIG_TRACK_CR3 +atomic_t kernel_cr3_loaded__aligned(PAGE_SIZE) ; +#endif };#define CPU_ENTRY_AREA_SIZE (sizeof(struct cpu_entry_area))
arch/x86/include/asm/pti.h +11 -0
@@ -1,12 +1,23 @@/* SPDX-License-Identifier: GPL-2.0 */ #ifndef _ASM_X86_PTI_H#define _ASM_X86_PTI_H + +#ifdef CONFIG_TRACK_CR3 +#define KERNEL_CR3_IN_USER 0 +#define KERNEL_CR3_IN_KERNEL 1 +#endif +#ifndef __ASSEMBLER__#ifdef CONFIG_MITIGATION_PAGE_TABLE_ISOLATION extern void pti_init (void );extern void pti_check_boottime_disable (void );extern void pti_finalize (void ); + +#ifdef CONFIG_TRACK_CR3 +DECLARE_PER_CPU_PAGE_ALIGNED (atomic_t, kernel_cr3_loaded); +#endif +#else static inline void pti_check_boottime_disable (void ) { }#endif
arch/x86/kernel/asm-offsets.c +3 -0
@@ -117,6 +117,9 @@ static void __used common(void)OFFSET (CPU_ENTRY_AREA_entry_stack, cpu_entry_area, entry_stack_page);DEFINE (SIZEOF_entry_stack,sizeof (struct entry_stack ));DEFINE (MASK_entry_stack, (~(sizeof (struct entry_stack ) -1 ))); +#ifdef CONFIG_TRACK_CR3 +OFFSET (CPU_ENTRY_AREA_kernel_cr3, cpu_entry_area, kernel_cr3_loaded); +#endif /* Offset for fields in tss_struct */ OFFSET (TSS_sp0, tss_struct, x86_tss.sp0);
arch/x86/mm/cpu_entry_area.c +5 -0
@@ -202,6 +202,11 @@ static void __init setup_cpu_entry_area(unsigned int cpu)per_cpu_ptr (&entry_stack_storage, cpu),1 , PAGE_KERNEL); +#ifdef CONFIG_TRACK_CR3 +cea_map_percpu_pages (&cea->kernel_cr3_loaded, +per_cpu_ptr (&kernel_cr3_loaded, cpu),1 , +PAGE_KERNEL ); +#endif /* * The Intel SDM says (Volume 3, 7.2.1): *
arch/x86/mm/pti.c +28 -12
@@ -446,6 +446,22 @@ static void __init pti_clone_p4d(unsigned long addr) *user_p4d = *kernel_p4d; } +static void __init pti_clone_percpu (unsigned long va) +{ +phys_addr_t pa =per_cpu_ptr_to_phys ((void *)va); +pte_t *target_pte; + + target_pte =pti_user_pagetable_walk_pte (va, false); +if (WARN_ON (!target_pte)) +return ; + + *target_pte =pfn_pte (pa >>PAGE_SHIFT ,PAGE_KERNEL ); +} + +#ifdef CONFIG_TRACK_CR3 +DEFINE_PER_CPU_PAGE_ALIGNED (atomic_t, kernel_cr3_loaded) =ATOMIC_INIT (KERNEL_CR3_IN_KERNEL ); +#endif +/* * Clone the CPU_ENTRY_AREA and associated data into the user space visible * page table.
@@ -456,25 +472,25 @@ static void __init pti_clone_user_shared(void)pti_clone_p4d (CPU_ENTRY_AREA_BASE ); +/* +* This is done for all possible CPUs during boot to ensure that it's +* propagated to all mms. +*/ for_each_possible_cpu (cpu) {/* * The SYSCALL64 entry code needs one word of scratch space * in which to spill a register. It lives in the sp2 slot * of the CPU's TSS. -* -* This is done for all possible CPUs during boot to ensure -* that it's propagated to all mms. */ +pti_clone_percpu ((unsigned long )&per_cpu (cpu_tss_rw, cpu)); -unsigned long va = (unsigned long )&per_cpu (cpu_tss_rw, cpu); -phys_addr_t pa =per_cpu_ptr_to_phys ((void *)va); -pte_t *target_pte; - - target_pte =pti_user_pagetable_walk_pte (va, false); -if (WARN_ON (!target_pte)) -return ; - - *target_pte =pfn_pte (pa >>PAGE_SHIFT ,PAGE_KERNEL ); +#ifdef CONFIG_TRACK_CR3 +/* +* The entry code needs access to the @kernel_cr3_loaded percpu +* variable before the kernel CR3 is loaded. +*/ +pti_clone_percpu ((unsigned long )&per_cpu (kernel_cr3_loaded, cpu)); +#endif } }
Signature · 1 line
2.56.1
Valentin Schneider
reviewerPATCH v10 9/10 x86/mm/pti: Drive kernel_cr3_loaded
In reply to Valentin SchneiderLater commits will rely on being able to check whether a remote CPU is using the kernel or the user CR3.
This per-CPU variable needs to be updated before the actual CR3 write, IOW it always immediately precedes it:
KERNEL_CR3_LOADED := 1
SWITCH_TO_KERNEL_CR3
[...]
KERNEL_CR3_LOADED := 0
SWITCH_TO_USER_CR3
NMI reentry considerations
==========================
NMIs are cheeky and can occur e.g. after @kernel_cr3_loaded has been updated but before the actual CR3 has been switched. This requires some extra care when exiting the NMI to *not* restore @kernel_cr3_loaded to its userland value.
That part is implemented by abusing bit #60 of the CR3 which is reserved; it itself is never written to in the actual CR3, but is fiddled in its register copy.
Per the Intel SDM:
```Volume 3, Chapter 5.1.4 Enumeration of Paging Features by CPUID This width is referred to as MAXPHYADDR. MAXPHYADDR is at most 52. ```
```Volume 3, Chapter 5.5.2 Use of CR3 with Ordinary 4-Level Paging and 5-Level Paging | Bit position | Contents | |--------------+----------------------------------------------------------------------------------------| | 11:0 | PCID | | M-1:12 | Physical address of the 4-KByte aligned PML4 table used for linear-address translation | | 60:M | Reserved (must be 0) | | 61 | Enables LAM57 for user pointers; Section 4.4.3 | | 62 | Enables LAM48 for user pointers; ignored if bit 61 is set | | 63 | Reserved (must be 0) | ```
unconditional update
=====================
This will only be really useful for NOHZ_FULL CPUs, but it should be cheaper to unconditionally update a never-used per-CPU variable living in its own cacheline than to check a shared cpumask such as
housekeeping_cpumask(HK_TYPE_KERNEL_NOISE)
at every entry.
--- arch/x86/Kconfig | 14 ++++ arch/x86/entry/calling.h | 71 +++++++++++++++++++++ arch/x86/include/uapi/asm/processor-flags.h | 3 + kernel/sched/isolation.c | 9 ++- 4 files changed, 96 insertions(+), 1 deletion(-)
arch/x86/Kconfig +14 -0
@@ -2163,6 +2163,20 @@ config ADDRESS_MASKING The capability can be used for efficient address sanitizers (ASAN) implementation and for optimizations in JITs. +config TRACK_CR3 + def_bool n + prompt "Track which CR3 is in use" + depends on X86_64 && MITIGATION_PAGE_TABLE_ISOLATION && NO_HZ_FULL + help + This option adds a software signal that allows checking remotely + whether a CPU is using the user or the kernel page table. + + This allows further optimizations for NOHZ_FULL CPUs. + + This obviously makes the user<->kernel transition overhead even worse. + + If unsure, say N. + config HOTPLUG_CPU def_bool y depends on SMP
arch/x86/entry/calling.h +71 -0
104 lines not on this page · raw message
arch/x86/include/uapi/asm/processor-flags.h +3 -0
@@ -82,6 +82,9 @@#define X86_CR3_PCID_BITS 12#define X86_CR3_PCID_MASK (_AC((1UL << X86_CR3_PCID_BITS) - 1, UL)) +#define X86_CR3_REENTRY_BIT 60/* NOT a CPU flag, but a pure software abuse of the CR3 layout */ +#define X86_CR3_REENTRY _BITULL(X86_CR3_REENTRY_BIT) +#define X86_CR3_LAM_U57_BIT 61/* Activate LAM for userspace, 62:57 bits masked */ #define X86_CR3_LAM_U57 _BITULL(X86_CR3_LAM_U57_BIT)#define X86_CR3_LAM_U48_BIT 62/* Activate LAM for userspace, 62:48 bits masked */
kernel/sched/isolation.c +8 -1
@@ -19,7 +19,14 @@ enum hk_flags { HK_FLAG_KERNEL_NOISE = BIT(HK_TYPE_KERNEL_NOISE), }; -DEFINE_STATIC_KEY_FALSE (housekeeping_overridden); +/* +* This key is accessed in early entry code to drive the CPU isolation IPI +* quiescing mechanism. This happens before a serializing instruction has been +* executed in the entry path. This is acceptable as a stale value will only be +* observed during transient CPU isolation states, and the updated value will be +* acted upon at the next kernel exit. +*/ +DEFINE_STATIC_KEY_FALSE_ENTRY (housekeeping_overridden);EXPORT_SYMBOL_GPL (housekeeping_overridden);struct housekeeping {
Signature · 1 line
2.56.1
Valentin Schneider
reviewerPATCH v10 10/10 context_tracking,x86: Quiesce kernel text patching IPIs when tracking CR3 switches
In reply to Valentin Schneidertext_poke_bp_batch() sends IPIs to all online CPUs to synchronize them vs the newly patched instruction. CPUs that are executing in userspace do not need this synchronization to happen immediately, and this is actually harmful interference for NOHZ_FULL CPUs.
As the synchronization IPIs are sent using a blocking call, returning from text_poke_bp_batch() implies all CPUs will observe the patched instruction(s), and this should be preserved even if the IPI is quiesced. In other words, to safely postpone this synchronization, any kernel instruction leading to the execution of the postponed instruction sync must *not* be mutable (patchable) at runtime.
This means we must pay attention to mutable instructions in the early entry code:
- alternatives
- static keys
- static calls
- all sorts of probes (kprobes/ftrace/bpf/???)
The early entry code is noinstr, which gets rid of the probes.
Alternatives are safe, because it's boot-time patching (before SMP is even brought up) which is before any IPI quiescing can happen.
This leaves us with static keys and static calls. Any static key used in early entry code should be only forever-enabled at boot time, IOW __ro_after_init (pretty much like alternatives). Exceptions to that will now be caught by objtool.
The postponed instruction sync is the CR3 RMW done as part of kPTI when switching to the kernel page table:
SDM vol2 chapter 4.3 - Move to/from control registers:
``` MOV CR* instructions, except for MOV CR8, are serializing instructions. ```
Leverage the new kernel_cr3_loaded signal and the kPTI CR3 RMW to quiesce sync_core() IPIs targeting NOHZ_FULL CPUs.
--- arch/x86/include/asm/text-patching.h | 5 +++ arch/x86/kernel/alternative.c | 59 +++++++++++++++++++++++++--- arch/x86/kernel/kprobes/core.c | 4 +- arch/x86/kernel/kprobes/opt.c | 4 +- arch/x86/kernel/module.c | 2 +- include/asm-generic/sections.h | 14 +++++++ 6 files changed, 77 insertions(+), 11 deletions(-)
arch/x86/include/asm/text-patching.h +5 -0
@@ -33,6 +33,11 @@ extern void text_poke_apply_relocation(u8 *buf, const u8 * const instr, size_t i*/ extern void *text_poke (void *addr,const void *opcode,size_t len);extern void smp_text_poke_sync_each_cpu (void ); +#ifdef CONFIG_TRACK_CR3 +extern void smp_text_poke_sync_each_cpu_quiescable (void ); +#else +#define smp_text_poke_sync_each_cpu_quiescable smp_text_poke_sync_each_cpu +#endif extern void *text_poke_kgdb (void *addr,const void *opcode,size_t len);extern void *text_poke_copy (void *addr,const void *opcode,size_t len);#define text_poke_copy text_poke_copy
arch/x86/kernel/alternative.c +53 -6
107 lines not on this page · raw message
arch/x86/kernel/kprobes/core.c +2 -2
@@ -785,7 +785,7 @@ void arch_arm_kprobe(struct kprobe *p)u8 int3 =INT3_INSN_OPCODE ;text_poke (p->addr, &int3,1 ); -smp_text_poke_sync_each_cpu (); +smp_text_poke_sync_each_cpu_quiescable ();perf_event_text_poke (p->addr, &p->opcode,1 , &int3,1 ); }
@@ -795,7 +795,7 @@ void arch_disarm_kprobe(struct kprobe *p)perf_event_text_poke (p->addr, &int3,1 , &p->opcode,1 );text_poke (p->addr, &p->opcode,1 ); -smp_text_poke_sync_each_cpu (); +smp_text_poke_sync_each_cpu_quiescable (); }void arch_remove_kprobe (struct kprobe *p)
arch/x86/kernel/kprobes/opt.c +2 -2
@@ -508,11 +508,11 @@ void arch_unoptimize_kprobe(struct optimized_kprobe *op) JMP32_INSN_SIZE - INT3_INSN_SIZE);text_poke (addr, new,INT3_INSN_SIZE ); -smp_text_poke_sync_each_cpu (); +smp_text_poke_sync_each_cpu_quiescable ();text_poke (addr +INT3_INSN_SIZE , new +INT3_INSN_SIZE ,JMP32_INSN_SIZE -INT3_INSN_SIZE ); -smp_text_poke_sync_each_cpu (); +smp_text_poke_sync_each_cpu_quiescable ();perf_event_text_poke (op->kp.addr, old,JMP32_INSN_SIZE , new,JMP32_INSN_SIZE ); }
arch/x86/kernel/module.c +1 -1
@@ -194,7 +194,7 @@ static int write_relocate_add(Elf64_Shdr *sechdrs, write, apply);if (!early) { -smp_text_poke_sync_each_cpu (); +smp_text_poke_sync_each_cpu_quiescable ();mutex_unlock (&text_mutex); }
include/asm-generic/sections.h +14 -0
@@ -199,6 +199,20 @@ static inline bool is_kernel_inittext(unsigned long addr) addr < (unsigned long )_einittext; } +/** +* is_kernel_entrytext - checks if the pointer address is located in the +* .entry.text section +* +* @addr: address to check +* +* Returns: true if the address is located in .entry.text, false otherwise. +*/ +static inline bool is_kernel_entrytext (unsigned long addr) +{ +return addr >= (unsigned long )__entry_text_start && + addr < (unsigned long )__entry_text_end; +} +/** * __is_kernel_text - checks if the pointer address is located in the * .text section
Signature · 1 line
2.56.1