* [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support
@ 2026-11-29 22:29 K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 01/27] x86/entry: Parameterize kernel shadow stack handling at FRED entry K Prateek Nayak
` (27 more replies)
0 siblings, 28 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
Disclaimer: A large part of my understanding of shadow stack and some
parts of this series are from interactions with AI agents. Please
forgive any slop.
Introduction
============
A query on supervisor shadow stacks brought Dave's series [1] to my
attention and getting it to boot on a zEn6 machine revealed a couple
early problems.
1. AMD processors supporting FRED don't have SERIALIZE and sync_core()
defaults to IRET-to-self which tries to pop a { CS, LIP, SS } frame
that doesn't exist on shadow stack.
2. The kernel text patching requires emulating RET and CALL
instructions. RET is simple enough and follows similar footsteps as
regs_set_return_ip() but emulating CALL is more challenging since,
unlike the regular stack that has FRED REDZONE, the shadow stack has
no gaps to push a return frame.
The code that got to prompt was horrible so over the past couple of
weeks I tried to understand shadow stacks better and hopefully have
turned the essence of initial slop that booted to prompt into a
reviewable series.
This is a more principled approach to enabling a bunch of features to
work with shadow stacks on FRED enabled systems and beyond. Ugly is
reserved for the end.
Write-to-CR2 for serialization
==============================
CPUs that don't have SERIALIZE and have X86_FEATURE_KERN_SHSTK will
default to using write-to-CR2 as serializing step. write-to-CR2 is
available widely and although the comment in sync_core() suggests XEN
may have some issues here, CONFIG_X86_KERE_SHADOW_STACK cannot be
compiled with XEN yet so we'll consider write-to-CR2 as a temporary
measure.
Making IRET-to-self work needs 3 dummy CALLs + 3 WRSS to setup the
shadow stack which might be too heavy handed for sync_core().
Enabling shaddow stack at early boot
====================================
The idle tasks are given their own shadow stack and are switched in with
restorprevss at early boot just after enabling shadow stacks in S_CET.
This avoids complicated handling in context switch path.
Note: Enable, disable kernel shadow stack helpers are ugly since they
have to be __always_inline so they can be called from spots with a
shallow stack to enable shadow stack with a single return entry.
start_kernel() and start_secondary() both are noreturn and a shallow
call location in their chain is a good point to enable shadow stacks
with just a single return slot whose corresponding RET jumps into the
noreturn function.
CALL emulation
==============
Call emulation requires a RET frame to be inserted below the FRED entry
frame. FRED frame is a { CS, LIP, SSP } pushed onto the shadow stack.
To make our lives easy, we push a corresponding metadata frame onto the
regula stack on top of pt_regs to make the following container:
struct {
u64 metadata; /* Context */
u64 ssp; /* SSP at FRED_ENTRY */
pt_rega *regs;
}
For CALL emulation, regs_emulate_call() helper will use the SSP from
this context to overwrite the CS in the FRED frame with the return IP.
The original CS and LIP are moved one slot up to make:
... ...
+-----+ +-----+
| CS | | RET |
| LIP | -> +-----+
| SSP | | CS |
+-----+ | LIP | <- Jump to CALL site
+-----+ <- Top of stack
Text patching events always occur at same FRED level and SSP always
points to address 3 slots down. regs_emulate_call() will then notify
FRED_EXIT of the patching by setting a flag in the metadata.
FRED_EXIT will see this flag and do a dummy call, fixup stack, and
overwrite the top of shadow stack with a SSP of three slots down to
complete the FRED frame which matches for ERETS. After an ERETS, the
fist RET will mismatch but rest of the RETs are balanced in RSB.
This is also the same method of doing a direct call via ORIG_RAX in
ftrace_regs_caller and has been adopted here.
Ftrace, Kprobe, Rethooks
========================
Tracing can occur in three context - int3, fentry call, or a fentry
trampoline like:
caller
traced function
int3
asm_fred_entrypoint_kernel
exec_int3()
rethook_hook()
caller
call traced_function
call ftrace_caller
call ftrace_handlers
rethook_hook()
caller
call traced_function
jmp optprobe_template_entry
call probe_handlers
rethook_hook()
In each of these context, regs->ip modification, and regs->sp[0] changes
need to target a specific shadow stack frame to ensure the shadow stack
is consistent with the actual redirection.
Each context builds a copy of pt_regs and the same metadata frame can be
constructed here with the SSP at the time of pt_regs snapshot. The
metadata advertises if it came from a FRED entrypoint, ftrace caller, or
optprobe.
Based on the context, either FRED frame is modified, or corresponding
slot on shadows tack is modified to either hijack the return from
function, or return from ftrac caller.
Note: To keep any exploit surface minimal, the ftrace_.*caller do not
correct the shadow stack. The ftrace / kprobe handlers are expected to
use the CET aware regs_* helper to steer regs->ip or add a return
trampoline.
The return trampolines are also made context aware to set regs->ip back
to the original caller.
Note: This may break a bunch of modules but for everyone's safety, they
must adapt. It is easy to sync the shadow stack at ftrace_.*caller but
is that the right thing to do?
BPF JIT
=======
BPF JIT only unwinds the stack (incsspq), skip's ftrace_caller's return
from the direct trampoline (incsspq) or can override return with a
trampoline (error injection).
All three are covered with the addition of context information. BPF JIT
only has to emit an incsspq in the unwinder and tasmpoline return.
Retpolines, SRSO, CALL Thunks
=============================
All three can fix their shadow stack by either doing a WRSS of the
correct return address for retpoline, or do an incsspq for SRSO and CALL
depth stuffing.
Fill RSB loop also uses incsspq to dispose the frames injected by the
stuffing.
As a consequence, all the thunks are much bigger since registers cannot
be clobbered and rdsspq, incsspq both need a register operand. SRSO
loses the handle_interrupted_saferet() fixup since it emulates a CALL,
LEA, RET sequence and an incsspq between that is complicated thus making
those systems slower and unsafe to interrupts during Safe-RET :-(
A possible way to solve this is to push a stack canary before pushing
additional data to restore and use the canary position + whether
regs->ip is past incsspq to emulate the RET while restoring register
state and stack.
When this started out, I didn't realize we may get to IDT systems so
interrupted SRSO is still unhandled in the series.
Since shadow stacks can be disabled during offline, suspend, kexec, and
during early start_secondary, patched retpoline, SRSO thunk cannot
assume wrss / incsspq is available else it will fault. All thunks need
to first do a rdsspq to see if shadow stack is enabled or not and then
continue which adds to the thunk size.
KEXEC, Suspend-Resume, Hibernation
==================================
All have to save SSP and disable shadow stack on the way out. On the way
back in, read the saved data to enable shadow stacks again and restore
the SSP at the same nesting level.
All are adapted to fit the existing save restore pattern in their path
except KDUMP.
Path to IDT
===========
At this point, the handling of patching was very modular and just
pushing the metadata frame around the pt_regs at IDT entry just worked
since the same { CS, LIP, SSP } is pushed for kernel events.
There are additional setssbsy, clrssbsy handling to assert the SSP0
token in the syscall path and there is a need for supervisor token at
base for INT_SSP_TAB but apart from that, things are simple.
Nested NMI is as complicated as stack management and the NMI from kernel
has to clear the IST gate 1 shadow stack (which makes SSP0), switch back
to the same shadow stack past the hardware populated frames, write two
copies (inner and outer) on top and continue.
The structure of shadow stack is as follows:
+-------------------------------+
| supervisor token |
+-------------------------------+
| Original CS |
| Original LIP | Hardware overwrites this slot
| Original SSP |
+-------------------------------+
| Inner CS |
| Inner LIP | Copied from first NMI
| Inner SSP |
+-------------------------------+
| Outer CS |
| Outer LIP | For the IRET from first NMI
| Outer SSP |
+-------------------------------+
A nested NMI will use the same shadow stack, the hardware overxrwrites
the lower frames, sees it is nested, and will modify the outer shadow
stack frame to make the first NMI return back to repeat_nmi.
If there are no nested NMIs, the outer frame is used for IRET which is
same as th original frame. This has been tested on a DEBUG_ENTRY kernel
with sysrq trigger, kprobe on NMI, and perf record going at it but did
not #CP/#GP/#DF do I'm assuming it works.
Testing
=======
Changes have been tested on a Zen6 (1024 CPUs; FRED), Zen4 (512 CPUs;
IDT, SRSO), and a Granite Rapids (256 CPUs; IDT) server with Ftrace
selftest, BPF selftest, and NMI stress test on a DEBUG_ENTRY kernel.
Credits
=======
All the credits for the effort goes to Dave. Without the strong
foundations from his series, this iteration would not have been
possible.
How to apply
============
These patches cleany apply on top of Dave's series from [1] which in
turn in applied on top of v7.3-rc6. For convenience a tree is present
at:
https://github.com/kudureranganath/linux.git x86/shstk_rfc_v1
Tree also contains a reference build config that I have been testing
with. Your mileage may vary.
References
==========
[1] https://lore.kernel.org/all/20261021195120.E61EC737@davehans-spike.ostc.intel.com/
---
Andrew Cooper (1):
x86/entry: Parameterize kernel shadow stack handling at FRED entry
K Prateek Nayak (26):
x86/perf_regs: Rename pt_regs_offset array to prevent build failure
x86/cet: Fix build for KERN_SHADOW_STACK and !USER_SHADOW_STACK
x86/cet: Make kernel shadow stack #CP fatal instead of livelocking
x86/sync_core: Don't use IRET-to-self with kernel shadow stacks
x86/process: Initialize and enable kernel shadow stack at boot
x86/entry: Handle int3 text patching with kernel shadow stack
x86/retpoline: Handle retpolies and thunks with kernel shadow stack
x86/ftrace: Prepare ftrace trampolines to handle shadow stack
x86/kprobes: Prepare optprobe trampoline to handle shadow stacks
x86/rethook: Prepare the rethook trampoline to handle shadow stack
x86/cet: Make regs_set_return_ip() helpers context aware
x86/cet: Introduce regs_set_return_trampoline() for rethook trampoline
x86/ftrace,livepatch: Use CET helpers for ftrace regs->ip and
trampoline redirection
x86/rethook: Make the trampoline insert and return shadow stack aware
x86/error_inject: Use CET helpers to insert just_return_func
trampoline
x86/kprobes: Use CET helpers in kprobe core to modify regs->ip
x86/bpf: Make BPF JIT aware of CET handling
x86/shstk: Remove profiling related dependencies for KERN_SHADOW_STACK
x86/shstk: Disable kenrel shadow stack when CPU is offlined
x86/shstsk: Allow suspend-resume and hibernation with kernel shadow
stack
x86/shstk: Save and restore shadow stack pointer during kexec
x86/idt: Map MCE shadow stack and populate the INT_SPP table
x86/process: Initialize shadow stack for IDT systems
x86/entry: Prepare IDT entry for shadow stacks
x86/syscall: Toggle shadow stack busy on entry and exit from syscall
x86/entry: Handle shadow stack on nested NMI
arch/x86/Kconfig | 51 ----
arch/x86/entry/calling.h | 99 ++++++++
arch/x86/entry/entry_64.S | 350 ++++++++++++++++++++------
arch/x86/entry/entry_64_compat.S | 10 +
arch/x86/entry/entry_64_fred.S | 39 +--
arch/x86/include/asm/alternative.h | 3 +-
arch/x86/include/asm/cpu.h | 106 ++++++++
arch/x86/include/asm/cpu_entry_area.h | 2 +
arch/x86/include/asm/entry-common.h | 19 +-
arch/x86/include/asm/fred.h | 7 -
arch/x86/include/asm/ftrace.h | 7 +-
arch/x86/include/asm/insn-eval.h | 27 +-
arch/x86/include/asm/nospec-branch.h | 82 +++++-
arch/x86/include/asm/suspend.h | 2 +
arch/x86/include/asm/sync_core.h | 11 +
arch/x86/include/asm/text-patching.h | 7 +-
arch/x86/include/asm/traps.h | 1 +
arch/x86/kernel/Makefile | 3 +-
arch/x86/kernel/acpi/wakeup_64.S | 6 +
arch/x86/kernel/alternative.c | 4 +-
arch/x86/kernel/asm-offsets.c | 3 +
arch/x86/kernel/cet.c | 348 +++++++++++++++++++++++--
arch/x86/kernel/cpu/common.c | 2 +
arch/x86/kernel/ftrace.c | 20 +-
arch/x86/kernel/ftrace_64.S | 121 +++++++--
arch/x86/kernel/idt.c | 30 +++
arch/x86/kernel/kprobes/core.c | 14 +-
arch/x86/kernel/kprobes/ftrace.c | 2 +
arch/x86/kernel/kprobes/opt.c | 28 ++-
arch/x86/kernel/machine_kexec_64.c | 4 +
arch/x86/kernel/perf_regs.c | 6 +-
arch/x86/kernel/process.c | 68 ++++-
arch/x86/kernel/rethook.c | 42 +++-
arch/x86/kernel/shstk.c | 8 +-
arch/x86/kernel/smpboot.c | 3 +
arch/x86/kernel/traps.c | 4 +-
arch/x86/kernel/vmlinux.lds.S | 8 +
arch/x86/lib/error-inject.c | 2 +-
arch/x86/lib/retpoline.S | 92 ++++++-
arch/x86/mm/cpu_entry_area.c | 27 ++
arch/x86/mm/pat/set_memory.c | 17 ++
arch/x86/net/bpf_jit_comp.c | 18 +-
arch/x86/power/hibernate.c | 2 +
arch/x86/power/hibernate_32.c | 16 +-
arch/x86/power/hibernate_asm_64.S | 7 +
kernel/bpf/helpers.c | 3 +-
kernel/trace/fgraph.c | 1 +
47 files changed, 1471 insertions(+), 261 deletions(-)
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 01/27] x86/entry: Parameterize kernel shadow stack handling at FRED entry
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 02/27] x86/perf_regs: Rename pt_regs_offset array to prevent build failure K Prateek Nayak
` (26 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
From: Andrew Cooper <andrew.cooper3@citrix.com>
Picked from feedback on Dave's RFC.
Link: https://lore.kernel.org/lkml/47f352d9-1ad8-44c9-bcf2-af1dbf14b626@citrix.com/
(Not-yet-)Signed-off-by: Andrew Cooper <andrew.cooper3@citrix.com>
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/entry/entry_64_fred.S | 42 +++++++++++++---------------------
1 file changed, 16 insertions(+), 26 deletions(-)
diff --git a/arch/x86/entry/entry_64_fred.S b/arch/x86/entry/entry_64_fred.S
index 1a2b39d9f7d3..9ff32e2a9103 100644
--- a/arch/x86/entry/entry_64_fred.S
+++ b/arch/x86/entry/entry_64_fred.S
@@ -16,35 +16,27 @@
.code64
.section .noinstr.text, "ax"
-/*
- * Kernel-mode events: save the SSP of the shadow stack frame FRED
- * pushed (old SSP, LIP, CS) just below pt_regs. See struct
- * fred_kernel_frame.
- */
-.macro PUSH_KERNEL_EVENT_SSP
-#ifdef CONFIG_X86_USER_SHADOW_STACK
- xorl %eax, %eax
- rdsspq %rax /* nop if shadow stacks are off */
- pushq %rax
- UNWIND_HINT_REGS offset=8
-#endif
-.endm
-
-.macro POP_KERNEL_EVENT_SSP
-#ifdef CONFIG_X86_USER_SHADOW_STACK
- addq $8, %rsp
-#endif
-.endm
-
-.macro FRED_ENTER
+.macro FRED_ENTER ssp=0
UNWIND_HINT_END_OF_STACK
ANNOTATE_NOENDBR
PUSH_AND_CLEAR_REGS
ENCODE_FRAME_POINTER
movq %rsp, %rdi /* %rdi -> pt_regs */
+
+#ifdef CONFIG_X86_KERN_SHADOW_STACK
+ .if \ssp
+ rdsspq %rax /* NOP if SHSTK is off. Pre-zeroed. */
+ push %rax
+ .endif
+#endif
.endm
-.macro FRED_EXIT
+.macro FRED_EXIT ssp=0
+#ifdef CONFIG_X86_KERN_SHADOW_STACK
+ .if \ssp
+ pop %rax /* Any dead register */
+ .endif
+#endif
UNWIND_HINT_REGS
POP_REGS
.endm
@@ -73,11 +65,9 @@ SYM_CODE_END(asm_fred_entrypoint_user)
*/
.org asm_fred_entrypoint_user + 256, 0xcc
SYM_CODE_START_NOALIGN(asm_fred_entrypoint_kernel)
- FRED_ENTER
- PUSH_KERNEL_EVENT_SSP
+ FRED_ENTER ssp=1
call fred_entry_from_kernel
- POP_KERNEL_EVENT_SSP
- FRED_EXIT
+ FRED_EXIT ssp=1
ERETS
SYM_CODE_END(asm_fred_entrypoint_kernel)
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 02/27] x86/perf_regs: Rename pt_regs_offset array to prevent build failure
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 01/27] x86/entry: Parameterize kernel shadow stack handling at FRED entry K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 03/27] x86/cet: Fix build for KERN_SHADOW_STACK and !USER_SHADOW_STACK K Prateek Nayak
` (25 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
Subsequent patches will add header dependency that will conflict with
"pt_regs_offset" naming. Since "pt_regs_offset" is a static array used
only by perf_regs, rename it to "__pt_regs_offset" to prevent build
conflicts with asm/insn-eval.h version.
No functional changes intended.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/kernel/perf_regs.c | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/arch/x86/kernel/perf_regs.c b/arch/x86/kernel/perf_regs.c
index 624703af80a1..444f41a8fa72 100644
--- a/arch/x86/kernel/perf_regs.c
+++ b/arch/x86/kernel/perf_regs.c
@@ -17,7 +17,7 @@
#define PT_REGS_OFFSET(id, r) [id] = offsetof(struct pt_regs, r)
-static unsigned int pt_regs_offset[PERF_REG_X86_MAX] = {
+static unsigned int __pt_regs_offset[PERF_REG_X86_MAX] = {
PT_REGS_OFFSET(PERF_REG_X86_AX, ax),
PT_REGS_OFFSET(PERF_REG_X86_BX, bx),
PT_REGS_OFFSET(PERF_REG_X86_CX, cx),
@@ -68,10 +68,10 @@ u64 perf_reg_value(struct pt_regs *regs, int idx)
return perf_regs->xmm_regs[idx - PERF_REG_X86_XMM0];
}
- if (WARN_ON_ONCE(idx >= ARRAY_SIZE(pt_regs_offset)))
+ if (WARN_ON_ONCE(idx >= ARRAY_SIZE(__pt_regs_offset)))
return 0;
- return regs_get_register(regs, pt_regs_offset[idx]);
+ return regs_get_register(regs, __pt_regs_offset[idx]);
}
#define PERF_REG_X86_RESERVED (((1ULL << PERF_REG_X86_XMM0) - 1) & \
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 03/27] x86/cet: Fix build for KERN_SHADOW_STACK and !USER_SHADOW_STACK
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 01/27] x86/entry: Parameterize kernel shadow stack handling at FRED entry K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 02/27] x86/perf_regs: Rename pt_regs_offset array to prevent build failure K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 04/27] x86/cet: Make kernel shadow stack #CP fatal instead of livelocking K Prateek Nayak
` (24 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
Since shstk.c is only compiled when X86_USER_SHADOW_STACK in enabled, a
build that only enables X86_KERN_SHADOW_STACK fails to link since
arch_init_thread_stacks() is not compiled in.
Add a defbool X86_SHADOW_STACK option that gets toggled when either
user, or kernel shadow stack support is toggled and use that to build
shstk.o.
No functional changes intended.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/kernel/Makefile | 3 +--
arch/x86/kernel/shstk.c | 8 +++++++-
2 files changed, 8 insertions(+), 3 deletions(-)
diff --git a/arch/x86/kernel/Makefile b/arch/x86/kernel/Makefile
index 31f46fd00527..31c5f61a2756 100644
--- a/arch/x86/kernel/Makefile
+++ b/arch/x86/kernel/Makefile
@@ -167,8 +167,7 @@ obj-$(CONFIG_CFI) += cfi.o
obj-$(CONFIG_CALL_THUNKS) += callthunks.o
obj-$(CONFIG_X86_CET) += cet.o
-
-obj-$(CONFIG_X86_USER_SHADOW_STACK) += shstk.o
+obj-$(CONFIG_X86_CET) += shstk.o
###
# 64 bit specific files
diff --git a/arch/x86/kernel/shstk.c b/arch/x86/kernel/shstk.c
index c89891b2ff55..ec3073ce2b89 100644
--- a/arch/x86/kernel/shstk.c
+++ b/arch/x86/kernel/shstk.c
@@ -26,6 +26,8 @@
#include <asm/fpu/api.h>
#include <asm/prctl.h>
+#ifdef CONFIG_X86_USER_SHADOW_STACK
+
#define SS_FRAME_SIZE 8
static bool features_enabled(unsigned long features)
@@ -631,7 +633,10 @@ bool shstk_is_enabled(void)
return features_enabled(ARCH_SHSTK_SHSTK);
}
+#endif /* CONFIG_X86_USER_SHADOW_STACK */
+
#ifdef CONFIG_X86_KERN_SHADOW_STACK
+
static inline int set_shstk_pte(pte_t *ptep, unsigned long addr, void *data)
{
set_pte(ptep, pte_mkwrite_shstk(pte_wrprotect(ptep_get(ptep))));
@@ -650,4 +655,5 @@ void arch_init_thread_stacks(struct thread_stacks *ts)
set_shstk_pte, NULL);
flush_tlb_kernel_range(shstk_vaddr, shstk_vaddr + shstk_size);
}
-#endif
+
+#endif /* CONFIG_X86_KERN_SHADOW_STACK */
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 04/27] x86/cet: Make kernel shadow stack #CP fatal instead of livelocking
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (2 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 03/27] x86/cet: Fix build for KERN_SHADOW_STACK and !USER_SHADOW_STACK K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 05/27] x86/sync_core: Don't use IRET-to-self with kernel shadow stacks K Prateek Nayak
` (23 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
A kernel-mode shadow stack #CP (NEAR-RET or FAR-RET/IRET) ends up in
do_unexpected_cp(), which does WARN_ONCE() and returns to a shadow stack
with mismatch. Returning executes that instruction again and faults
again. After the first WARN this repeats silently forever. For example,
IRET-to-self in sync_core() on a CPU without SERIALIZE just hangs the
machine.
Nothing can be fixed up at that point. Handle kernel-mode shadow stack
regular stack top vs the shadow stack top for RET, and the RIP in the
IRET/ERETS frame vs the shadow stack LIP for FAR-RET/IRET. Then die().
A code path that returns somewhere the shadow stack doesn't expect now
shows up as a one-line oops naming both targets, instead of a hang or a
WARN storm.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/kernel/cet.c | 101 ++++++++++++++++++++++++++++++++----------
1 file changed, 77 insertions(+), 24 deletions(-)
diff --git a/arch/x86/kernel/cet.c b/arch/x86/kernel/cet.c
index 4033775a922c..97375a8335c8 100644
--- a/arch/x86/kernel/cet.c
+++ b/arch/x86/kernel/cet.c
@@ -1,7 +1,9 @@
// SPDX-License-Identifier: GPL-2.0
#include <linux/ptrace.h>
+#include <linux/uaccess.h>
#include <asm/bugs.h>
+#include <asm/kdebug.h>
#include <asm/msr.h>
#include <asm/traps.h>
#include <asm/insn-eval.h>
@@ -112,6 +114,77 @@ static void ibt_clear_fred_wfe(struct pt_regs *regs)
regs->fred_cs.wfe = 0;
}
+/*
+ * FRED hardware pushes this frame on to the shadow stack for
+ * kernel=>kernel entry. First (lowest address) in this struct
+ * is the last entry pushed by the hardware.
+ */
+struct fred_shstk_entry_frame {
+ u64 ssef_ssp;
+ u64 ssef_lip;
+ u64 ssef_cs;
+};
+
+/*
+ * The kernel=>kernel entry code pushes SSP on to the entry stack.
+ * This only occurs for kernel=>kernel entry. Not userspace.
+ *
+ * SSP is pushed on to the frame below pt_regs. At the point it is
+ * pushed, it points to a special FRED entry frame.
+ */
+struct fred_kernel_frame {
+ struct fred_shstk_entry_frame *ssef;
+ struct pt_regs regs;
+};
+
+static unsigned long cp_peek(unsigned long addr)
+{
+ unsigned long val = 0;
+
+ copy_from_kernel_nofault(&val, (void *)addr, sizeof(val));
+ return val;
+}
+
+/*
+ * Shadow stack #CPs are faults: regs->ip is the RET/IRET/ERETS that found
+ * the mismatch and returning from here would just execute it again. There
+ * is no way to recover, so say which two return addresses disagreed and
+ * die.
+ */
+static void do_kernel_shstk_cp(struct pt_regs *regs, unsigned long error_code)
+{
+ struct fred_shstk_entry_frame *ssef;
+ static const u8 erets[] = { 0xf2, 0x0f, 0x01, 0xca };
+ unsigned long ssp, ip, shstk_ip, sp_off = 0;
+ u8 insn[sizeof(erets)] = { };
+
+ ssef = container_of(regs, struct fred_kernel_frame, regs)->ssef;
+ ssp = cp_peek((unsigned long)&ssef->ssef_ssp);
+
+ switch (error_code & CP_EC) {
+ case CP_RET:
+ ip = cp_peek(regs->sp);
+ shstk_ip = cp_peek(ssp);
+ break;
+ case CP_IRET:
+ /* ERETS skips the error code slot, IRET does not. */
+ copy_from_kernel_nofault(insn, (void *)regs->ip, sizeof(insn));
+ if (!memcmp(insn, erets, sizeof(erets)))
+ sp_off = 8;
+ ip = cp_peek(regs->sp + sp_off);
+ shstk_ip = cp_peek(ssp + 8);
+ break;
+ default:
+ ip = shstk_ip = 0;
+ break;
+ }
+
+ pr_emerg("Kernel shadow stack violation (%s) at %pS: stack: %pS shadow stack: %pS (ssp=%lx)\n",
+ cp_err_string(error_code), (void *)regs->ip, (void *)ip,
+ (void *)shstk_ip, ssp);
+ die("control protection fault", regs, error_code);
+}
+
static void do_kernel_cp_fault(struct pt_regs *regs, unsigned long error_code)
{
if ((error_code & CP_EC) != CP_ENDBR) {
@@ -156,36 +229,16 @@ DEFINE_IDTENTRY_ERRORCODE(exc_control_protection)
else
do_unexpected_cp(regs, error_code);
} else {
- if (cpu_feature_enabled(X86_FEATURE_IBT))
+ if (cpu_feature_enabled(X86_FEATURE_KERN_SHSTK) &&
+ (error_code & CP_EC) != CP_ENDBR)
+ do_kernel_shstk_cp(regs, error_code);
+ else if (cpu_feature_enabled(X86_FEATURE_IBT))
do_kernel_cp_fault(regs, error_code);
else
do_unexpected_cp(regs, error_code);
}
}
-/*
- * FRED hardware pushes this frame on to the shadow stack for
- * kernel=>kernel entry. First (lowest address) in this struct
- * is the last entry pushed by the hardware.
- */
-struct fred_shstk_entry_frame {
- u64 ssef_ssp;
- u64 ssef_lip;
- u64 ssef_cs;
-};
-
-/*
- * The kernel=>kernel entry code pushes SSP on to the entry stack.
- * This only occurs for kernel=>kernel entry. Not userspace.
- *
- * SSP is pushed on to the frame below pt_regs. At the point it is
- * pushed, it points to a special FRED entry frame.
- */
-struct fred_kernel_frame {
- struct fred_shstk_entry_frame *ssef;
- struct pt_regs regs;
-};
-
/*
* Change the return IP of an event. Use this instead of directly
* manipulating regs->ip.
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 05/27] x86/sync_core: Don't use IRET-to-self with kernel shadow stacks
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (3 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 04/27] x86/cet: Make kernel shadow stack #CP fatal instead of livelocking K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 06/27] x86/process: Initialize and enable kernel shadow stack at boot K Prateek Nayak
` (22 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
On CPUs without SERIALIZE (Zen6), sync_core() serializes with
IRET-to-self. With kernel shadow stacks enabled, IRET at CPL0 also pops
a {SSP, LIP, CS} frame from the shadow stack and checks it against the
RIP and CS it returns to.
IRET-to-self only builds the frame on the regular stack, so the IRET
raises:
Unexpected kernel mode #CP, error_code: far/iret
WARNING: arch/x86/kernel/cet.c:42 at exc_control_protection+0xe2/0x3b0
RIP: 0010:do_sync_core+0x24/0x30
smp_call_function_many_cond+0x3e7/0x5f0
smp_text_poke_batch_finish+0x12f/0x590
arch_jump_label_transform_apply+0x1a/0x30
static_key_disable_cpuslocked+0x90/0xa0
LFENCE is not enough for cross-modifying code and making IRET-to-self
shadow stack compatible would need three CALLs plus three WRSSs to fake
the frame.
Use write-to-cr2 as the serializing operation for systems that have
X86_FEATURE_KERN_SHSTK but don't support SERIALIZE instruction.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/include/asm/sync_core.h | 11 +++++++++++
1 file changed, 11 insertions(+)
diff --git a/arch/x86/include/asm/sync_core.h b/arch/x86/include/asm/sync_core.h
index df22113db9cd..b056444407b5 100644
--- a/arch/x86/include/asm/sync_core.h
+++ b/arch/x86/include/asm/sync_core.h
@@ -66,6 +66,17 @@ static __always_inline void sync_core(void)
return;
}
+ /*
+ * IRET-to-self fabricates a frame on the regular stack only. With
+ * supervisor shadow stacks enabled, IRET (and ERETS) also pop and
+ * verify a {SSP, LIP, CS} frame from the shadow stack, which isn't
+ * there -> #CP(FAR-RET/IRET). Use MOV-to-CR2 to serialize.
+ */
+ if (cpu_feature_enabled(X86_FEATURE_KERN_SHSTK)) {
+ native_write_cr2(native_read_cr2());
+ return;
+ }
+
/*
* For all other processors, there are quite a few ways to do this.
* IRET-to-self is nice because it works on every CPU, at any CPL
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 06/27] x86/process: Initialize and enable kernel shadow stack at boot
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (4 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 05/27] x86/sync_core: Don't use IRET-to-self with kernel shadow stacks K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 07/27] x86/entry: Handle int3 text patching with kernel shadow stack K Prateek Nayak
` (21 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
Current scheme of dynamically toggling shadow stacks at context-switch
is heavy handed and unnecessary if all tasks start off with kernel
shadow stack initialized before the CPU can context-switch.
Initialize forked task with a restore token and enable shadow stacks
early into the boot after the CPU has been identified and feature flags
are patched.
This gets us the simple pattern for SSP handling at context-switch of:
rstorssp -8(%rax)
saveprevssp
The init_task has its shadow stack data mapped into the kernel image
and needs the CPA helper to change it to RO mapping unlike AP which goes
via copy_process() and has its shadow stack area vmalloced.
The first context switch is only possible after BSP has patched
alternatives and it is safe to patch out the shadow stack handling in
the switch path.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/entry/entry_64.S | 88 ++++-------------------------------
arch/x86/include/asm/cpu.h | 62 ++++++++++++++++++++++++
arch/x86/kernel/cpu/common.c | 2 +
arch/x86/kernel/process.c | 54 ++++++++++++++++-----
arch/x86/kernel/smpboot.c | 2 +
arch/x86/kernel/vmlinux.lds.S | 8 ++++
arch/x86/mm/pat/set_memory.c | 17 +++++++
7 files changed, 141 insertions(+), 92 deletions(-)
diff --git a/arch/x86/entry/entry_64.S b/arch/x86/entry/entry_64.S
index 6d5c09cb9680..c255722cd66d 100644
--- a/arch/x86/entry/entry_64.S
+++ b/arch/x86/entry/entry_64.S
@@ -170,83 +170,14 @@ SYM_INNER_LABEL(entry_SYSRETQ_end, SYM_L_GLOBAL)
int3
SYM_CODE_END(entry_SYSCALL_64)
-.macro SAVE_KERNEL_SHADOW_STACK
+.macro SWITCH_KERNEL_SHADOW_STACK
#ifdef CONFIG_X86_KERN_SHADOW_STACK
- /* kshstk_ssp==0 means no kernel shadow stack, skip handling */
- cmpq $0, TASK_thread_kshstk_ssp(%rdi)
- je .Lprev_no_shstk\@
- rdsspq %rax
- movq %rax, TASK_thread_kshstk_ssp(%rdi)
-.Lprev_no_shstk\@:
-#endif
-.endm
-
-.macro ENABLE_KERNEL_SHADOW_STACK
- movl $MSR_IA32_S_CET, %ecx
- rdmsr
- orl $(CET_SHSTK_EN | CET_WRSS_EN), %eax
- wrmsr
-.endm
-
-.macro DISABLE_KERNEL_SHADOW_STACK
- movl $MSR_IA32_S_CET, %ecx
- rdmsr
- andl $~(CET_SHSTK_EN | CET_WRSS_EN), %eax
- wrmsr
-.endm
-
-/*
- * Clobbers rax, rcx, rdx, r8, r9. rdi/rsi must survive for the rest
- * of __switch_to_asm.
- *
- * Dumb and slow. Always does WRMSR, regardless of if changes need to
- * be made.
- */
-.macro LOAD_KERNEL_SHADOW_STACK
-#ifdef CONFIG_X86_KERN_SHADOW_STACK
- movq TASK_thread_kshstk_ssp(%rsi), %r8
- testq %r8, %r8
- jz .Lnext_no_shstk\@
-
- ENABLE_KERNEL_SHADOW_STACK
-
- /*
- * This should be just a:
- *
- * rstorssp
- * saveprevssp
- *
- * sequence. But, currently, the previous task might not
- * have a valid SSP, like the init_task. This needs fixing.
- * But, for now, just hack a Prev-SSP token in.
- *
- * The right fix is to give all tasks a valid SSP universally
- * and then initialize the token once at task creation time,
- * probably near the spot that ret_from_fork_asm is also
- * written to the shadow stack.
- */
- leaq -8(%r8), %r9
- movq %r8, %rax
- /*
- * Set type=0. Indicates a "Restore token" to satisfy RSTORSSP:
- * Set mode=1. Indicates 64-bit mode.
- * */
- orq $SHSTK_TOKEN_MODE64, %rax
- wrssq %rax, (%r9)
-
- rstorssp (%r9)
-
- /*
- * Discard the Previous-SSP token left by RSTORSSP.
- *
- * This will go away once SAVEPREVSSP is being used properly.
- */
- movl $1, %eax
- incsspq %rax
- jmp .Lshstk_done\@
-
-.Lnext_no_shstk\@:
- DISABLE_KERNEL_SHADOW_STACK
+ ALTERNATIVE "jmp .Lshstk_done\@", "", X86_FEATURE_KERN_SHSTK
+ rdsspq %rbx
+ movq %rbx, TASK_thread_kshstk_ssp(%rdi)
+ movq TASK_thread_kshstk_ssp(%rsi), %rbx
+ rstorssp -8(%rbx)
+ saveprevssp
.Lshstk_done\@:
#endif
.endm
@@ -273,7 +204,7 @@ SYM_FUNC_START(__switch_to_asm)
movq %rsp, TASK_threadsp(%rdi)
movq TASK_threadsp(%rsi), %rsp
- SAVE_KERNEL_SHADOW_STACK
+ SWITCH_KERNEL_SHADOW_STACK
#ifdef CONFIG_STACKPROTECTOR
movq TASK_stack_canary(%rsi), %rbx
@@ -289,9 +220,6 @@ SYM_FUNC_START(__switch_to_asm)
*/
FILL_RETURN_BUFFER %r12, RSB_CLEAR_LOOPS, X86_FEATURE_RSB_CTXSW
- /* Note that this clobbers tons of stuff: */
- LOAD_KERNEL_SHADOW_STACK
-
/* restore callee-saved registers */
popq %r15
popq %r14
diff --git a/arch/x86/include/asm/cpu.h b/arch/x86/include/asm/cpu.h
index 01313070b2da..5f2e5b150b61 100644
--- a/arch/x86/include/asm/cpu.h
+++ b/arch/x86/include/asm/cpu.h
@@ -9,6 +9,9 @@
#include <linux/percpu.h>
#include <asm/ibt.h>
+#include <asm/msr-index.h>
+#include <asm/thread_info.h>
+#include <asm/special_insns.h>
#include <asm/cpuid/leaf_types.h>
#ifndef CONFIG_SMP
@@ -62,6 +65,65 @@ static inline void init_ia32_feat_ctl(struct cpuinfo_x86 *c) {}
extern __noendbr void cet_disable(void);
+#ifdef CONFIG_X86_KERN_SHADOW_STACK
+
+extern int set_init_task_shstk_attr(struct task_struct *tsk);
+extern void prep_kernel_shadow_stack(struct task_struct *tsk,
+ unsigned long ret_addr,
+ bool base_configured);
+
+/*
+ * This function should always be inlined. cpu_setup_kernel_shstk()
+ * soes not unwind the full stack and the shadow stack is only capable
+ * of handling a single unbalanced ret to _RET_IP_ of setup.
+ */
+static __always_inline void enable_kernel_shstk(unsigned long shstk_top)
+{
+ asm volatile ("rdmsr\n"
+ "orl %1, %%eax\n"
+ "wrmsr\n"
+ "rstorssp -8(%2)\n"
+ "incsspq %3\n"
+ :
+ : "c" (MSR_IA32_S_CET),
+ "i" ((u32)(CET_SHSTK_EN | CET_WRSS_EN)),
+ "r" (shstk_top),
+ "r" (1ULL)
+ : "eax", "edx", "cc", "memory");
+}
+
+/*
+ * Setup the shadow stack for this CPU.
+ *
+ * Note: The shadow stack is setup in a way that it can handle at
+ * most one retun to _RET_IP_. The expectations is that the caller
+ * returns to an noreturn function that sets up the idle task.
+ */
+static __always_inline void cpu_setup_kernel_shstk(bool boot_cpu)
+{
+ struct task_struct *tsk = current;
+ unsigned long shstk_top;
+
+ if (!cpu_feature_enabled(X86_FEATURE_KERN_SHSTK))
+ return;
+
+ prep_kernel_shadow_stack(tsk, _RET_IP_, !boot_cpu);
+ if (boot_cpu)
+ BUG_ON(set_init_task_shstk_attr(tsk));
+
+ /* All taks must have a valid shadow stack. */
+ BUG_ON(!tsk->thread.kshstk_ssp);
+ shstk_top = (unsigned long)tsk->thread.kshstk_ssp;
+
+ wrmsrq(MSR_IA32_FRED_SSP0, shstk_top);
+ enable_kernel_shstk(shstk_top);
+}
+
+#else /* !CONFIG_X86_KERN_SHADOW_STACK */
+
+static inline void cpu_setup_kernel_shstk(bool boot_cpu) { }
+
+#endif /* CONFIG_X86_KERN_SHADOW_STACK */
struct cpu_signature;
void intel_collect_cpu_info(struct cpu_signature *sig);
diff --git a/arch/x86/kernel/cpu/common.c b/arch/x86/kernel/cpu/common.c
index b8b9364754e7..370a4301c55d 100644
--- a/arch/x86/kernel/cpu/common.c
+++ b/arch/x86/kernel/cpu/common.c
@@ -2648,6 +2648,8 @@ void __init arch_cpu_finalize_init(void)
alternative_instructions();
+ cpu_setup_kernel_shstk(true);
+
if (IS_ENABLED(CONFIG_X86_64)) {
USER_PTR_MAX = TASK_SIZE_MAX;
diff --git a/arch/x86/kernel/process.c b/arch/x86/kernel/process.c
index b5dd664c78c9..7b3a9f112451 100644
--- a/arch/x86/kernel/process.c
+++ b/arch/x86/kernel/process.c
@@ -167,13 +167,16 @@ __visible void ret_from_fork(struct task_struct *prev, struct pt_regs *regs,
syscall_exit_to_user_mode(regs);
}
+#ifdef CONFIG_X86_KERN_SHADOW_STACK
+
/*
* The goal here is to build a shadow stack for the new thread. It
* just needs to survive the first RET from ret_from_fork_asm().
*/
-static void prep_kernel_shadow_stack(struct task_struct *tsk)
+void prep_kernel_shadow_stack(struct task_struct *tsk,
+ unsigned long ret_addr,
+ bool base_configured)
{
-#ifdef CONFIG_X86_KERN_SHADOW_STACK
unsigned long *ss_top_slot;
u8 *shstk_base_writable;
u8 *shstk_base_vmap;
@@ -183,24 +186,49 @@ static void prep_kernel_shadow_stack(struct task_struct *tsk)
return;
/* Start with the shadow stack permission mapping: */
- shstk_base_vmap = &task_thread_union(tsk)->stacks.shadow_stack[0];
+ shstk_base_vmap = task_thread_union(tsk)->stacks.shadow_stack;
- /* Walk the page tables and find the direct map alias of the sshstk */
- shstk_base_writable = page_address(vmalloc_to_page(shstk_base_vmap));
+ /*
+ * Walk the page tables and find the direct map alias of the sshstk
+ * if permissions are already configured. Otherwise, use the
+ * base vmap as is since it is writable as is the case of init_task.
+ */
+ shstk_base_writable = (base_configured) ?
+ page_address(vmalloc_to_page(shstk_base_vmap)) :
+ shstk_base_vmap;
/* Point at the end of the shadow stack: */
ss_top = shstk_base_writable + TASK_SHADOW_STACK_SIZE;
/* Back up one ulong from the end to write the first return pointer: */
ss_top_slot = (unsigned long *)ss_top - 1;
- /* Write the return address for the first RET: */
- *ss_top_slot = (unsigned long)ret_from_fork_asm;
+ /*
+ * Write the return address for the first RET: and point the task's
+ * kshstk_ssp to the top slot.
+ */
+ *ss_top_slot = (unsigned long)ret_addr;
+ tsk->thread.kshstk_ssp = task_shstk_top(tsk) - sizeof(unsigned long);
- // Needs helper?
- tsk->thread.kshstk_ssp = shstk_base_vmap + TASK_SHADOW_STACK_SIZE - sizeof(unsigned long);
-#endif
+ /*
+ * Back up one more frame and write the token for rstorssp when this
+ * shadow stack switches in. this token will be consumed when this
+ * shadow stack is toggled busy.
+ */
+ ss_top_slot -= 1;
+ *ss_top_slot = (unsigned long)tsk->thread.kshstk_ssp | SHSTK_TOKEN_MODE64;
+}
+
+#else /* !CONFIG_X86_KERN_SHADOW_STACK */
+
+static void prep_kernel_shadow_stack(struct task_struct *tsk,
+ unsigned long ret_addr,
+ bool base_configured)
+{
}
+#endif /* CONFIG_X86_KERN_SHADOW_STACK */
+
+
int copy_thread(struct task_struct *p, const struct kernel_clone_args *args)
{
u64 clone_flags = args->flags;
@@ -209,6 +237,7 @@ int copy_thread(struct task_struct *p, const struct kernel_clone_args *args)
struct inactive_task_frame *frame;
struct fork_frame *fork_frame;
struct pt_regs *childregs;
+ unsigned long ret_addr;
unsigned long new_ssp;
int ret = 0;
@@ -216,10 +245,11 @@ int copy_thread(struct task_struct *p, const struct kernel_clone_args *args)
fork_frame = container_of(childregs, struct fork_frame, regs);
frame = &fork_frame->frame;
+ ret_addr = (unsigned long) ret_from_fork_asm;
frame->bp = encode_frame_pointer(childregs);
- frame->ret_addr = (unsigned long) ret_from_fork_asm;
+ frame->ret_addr = ret_addr;
p->thread.sp = (unsigned long) fork_frame;
- prep_kernel_shadow_stack(p);
+ prep_kernel_shadow_stack(p, ret_addr, true);
p->thread.io_bitmap = NULL;
clear_tsk_thread_flag(p, TIF_IO_BITMAP);
p->thread.iopl_warn = 0;
diff --git a/arch/x86/kernel/smpboot.c b/arch/x86/kernel/smpboot.c
index ba01a9e919b7..6ff2730a39c0 100644
--- a/arch/x86/kernel/smpboot.c
+++ b/arch/x86/kernel/smpboot.c
@@ -189,6 +189,8 @@ static void ap_starting(void)
/* Save the processor parameters. */
identify_secondary_cpu(cpuid);
+ cpu_setup_kernel_shstk(false);
+
/*
* The topology information must be up to date before
* notify_cpu_starting().
diff --git a/arch/x86/kernel/vmlinux.lds.S b/arch/x86/kernel/vmlinux.lds.S
index 2438b89a4620..3aff2d25ba98 100644
--- a/arch/x86/kernel/vmlinux.lds.S
+++ b/arch/x86/kernel/vmlinux.lds.S
@@ -185,6 +185,14 @@ SECTIONS
/* init_task */
INIT_TASK_DATA(THREAD_SIZE)
+#ifdef CONFIG_X86_KERN_SHADOW_STACK
+ /*
+ * The rest of init_thread_union: init_task's shadow stack,
+ * i.e. thread_union.stacks.shadow_stack[].
+ */
+ . += TASK_SHADOW_STACK_SIZE;
+#endif
+
/* equivalent to task_pt_regs(&init_task) */
__top_init_kernel_stack = __end_init_stack - TOP_OF_KERNEL_STACK_PADDING - PTREGS_SIZE;
diff --git a/arch/x86/mm/pat/set_memory.c b/arch/x86/mm/pat/set_memory.c
index 4652487b5572..7258514ec414 100644
--- a/arch/x86/mm/pat/set_memory.c
+++ b/arch/x86/mm/pat/set_memory.c
@@ -24,6 +24,7 @@
#include <linux/memregion.h>
#include <linux/cleanup.h>
+#include <asm/cpu.h>
#include <asm/e820/api.h>
#include <asm/processor.h>
#include <asm/tlbflush.h>
@@ -2823,6 +2824,22 @@ int __init kernel_unmap_pages_in_pgd(pgd_t *pgd, unsigned long address,
return retval;
}
+#ifdef CONFIG_X86_KERN_SHADOW_STACK
+
+int set_init_task_shstk_attr(struct task_struct *tsk)
+{
+ int numpages = TASK_SHADOW_STACK_SIZE >> PAGE_SHIFT;
+ unsigned long addr;
+
+ addr = (unsigned long)task_thread_union(tsk)->stacks.shadow_stack;
+ return change_page_attr_set_clr(&addr, numpages,
+ __pgprot(_PAGE_DIRTY),
+ __pgprot(_PAGE_RW),
+ 0, 0, NULL);
+}
+
+#endif
+
/*
* The testcases use internal knowledge of the implementation that shouldn't
* be exposed to the rest of the kernel. Include these directly here.
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 07/27] x86/entry: Handle int3 text patching with kernel shadow stack
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (5 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 06/27] x86/process: Initialize and enable kernel shadow stack at boot K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 08/27] x86/retpoline: Handle retpolies and thunks " K Prateek Nayak
` (20 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
Kernel running with shadow stacks enabled explode early into the boot
during text-poke like:
RIP: 0010:asm_fred_entrypoint_kernel+0x5f/0x70 <- ERETS, #CP
RIP: 0010:native_send_call_func_ipi+0x11/0xf0 <- after emulated NOP5
smp_call_function_many_cond+0x2c0/0x5f0
smp_text_poke_batch_finish+0x12f/0x590
static_key_enable+0x1f/0x30
_cpu_up+0x11a/0x260
With kernel shadow stacks, a same-level FRED event pushes {CS, LIP, SSP}
onto the shadow stack. ERETS raises #CP unless LIP and CS match the RIP
and CS on the regular stack. The extable code already updates the frame
through regs_set_return_ip() but this has not been extended to generic
int3 based text patching.
Emulating JMP and RET are simple enough - jmp sets the ret->ip like
extables and ret too does this with an addition of an emulated stack pop
to direct to the return IP which has to adjust the SSP accordingly by
moving it one slot lower.
Emulating a CALL is slightly more complicated - CALL pushes the return
address onto the stack and jumps to the function as if it was called
from LIP.
FRED stacks add a redzone on the stack that can be used for the call
emulation but there is no gap in shadow stack for the same.
There are two ways to solve this:
o Inspired by IDT handling, add a dummy shadow stack slot on shadow
stack for X86_TRAP_BP. This slot can then be used for CALL emulation
to push a ret frame below the FRED shadow stack frame and then steer
the FRED shadow stack frame to return to the caller.
In practice it looks like:
.macro PUSH_KERN_SHSTK_FRAME
xor %eax, %eax
pushq %rax
rdsspq %rax
cmpb $X86_TRAP_BP, PTREGS_fred_vector(%rdi)
jne .Lpush_shstk_done\@
ANNOTATE_INTRA_FUNCTION_CALL
call 1f
int3
1:
/* Indicate one extra slot is available on frame */
add $8, %rsp
incq (%rsp)
.Lpush_shstk_done\@:
push %rax
.endm
.macro POP_KERN_SHSTK_FRAME
pop %rax
pop %rax
/* Spare slots are recalimed here. */
incsspq %rax
.endm
The CALL emulation moves the FRED frame up by one slot to occupy the
spare slot, sets 8(%rsp) to 0 to indicate that spare slot has
been consumed
This has one key disadvantage that the INTRA_FUNCTION_CALL for every
#BP will unbalance the RSB and CPU will mis-speculate every return
after the handler has finished. Not ideal.
o (Implemented here) Use the same spare frame flags at 8(%rsp) to insert
a tail call at POP_KERN_SHSTK_FRAME during FRED_EXIT. This adds a
matching RSB to call entry much like the orig_rax path in the
ftrace_regs_call.
The call emulation would have adjusted the SS frame to insert the ret
frame, CS, and LIP. POP_KERN_SHSTK_FRAME adds the missing SSP to slot
by pointing it to SPP + 32 after the INTRA_FUNCTION_CALL.
The emulation functions are marked noisntr since subsequent patches
enable Ftrace caller hooks which can recurse if the patching function
can be probed.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/entry/entry_64_fred.S | 92 ++++++++++++++---
arch/x86/include/asm/insn-eval.h | 22 ++++-
arch/x86/include/asm/text-patching.h | 7 +-
arch/x86/kernel/alternative.c | 4 +-
arch/x86/kernel/asm-offsets.c | 3 +
arch/x86/kernel/cet.c | 142 +++++++++++++++++++++++++--
arch/x86/kernel/traps.c | 4 +-
7 files changed, 247 insertions(+), 27 deletions(-)
diff --git a/arch/x86/entry/entry_64_fred.S b/arch/x86/entry/entry_64_fred.S
index 9ff32e2a9103..284976114c70 100644
--- a/arch/x86/entry/entry_64_fred.S
+++ b/arch/x86/entry/entry_64_fred.S
@@ -3,6 +3,7 @@
* The actual FRED entry points.
*/
+#include <linux/annotate.h>
#include <linux/export.h>
#include <linux/kvm_types.h>
@@ -16,6 +17,79 @@
.code64
.section .noinstr.text, "ax"
+#ifdef CONFIG_X86_KERN_SHADOW_STACK
+
+/*
+ * A INT3 breakpoint can emulate a CALL which requires pushing the
+ * return frame below this FRED event. Allow the handlers to communicate
+ * if it emulated a CALL by setting a flag on the stack.
+ *
+ * FRED event pushes { SSP, LIP, CS } onto the shadow stack and SSP
+ * points to record three slots for top here and it should stay that
+ * way.
+ *
+ * CALL emulation will consume the SSP, push a return frame below, and
+ * set a flag on stack. If the flag is set, FRED_EXIT will add an
+ * shadow stack frame on top by doing an INTRA_FUNCTION_CALL and
+ * populate the top with a pointer to three slots below, thus recreating
+ * the correct FRED frame.
+ */
+.macro PUSH_KERN_SHSTK_FRAME
+ xor %eax, %eax
+ rdsspq %rax /* NOP if SHSTK is off. */
+ pushq %rax
+ /*
+ * Frame metadata:
+ *
+ * [15:8] Context (FRED_EVENT)
+ * [ 7:0] fred_exit_work_flags
+ *
+ * Context data is used by CET helpers to interpret
+ * SSP frame. fred_exit_work_flags is used to fixup
+ * shadow stack for CALL emulation.
+ */
+ pushq $0x100
+.endm
+
+/* Clobbers RAX, RCX; Both will be restored later. */
+.macro POP_KERN_SHSTK_FRAME
+ popq %rax /* fred_exit_work_flags */
+
+ /* Only one action is supported currently. */
+ test %al, %al
+ jz .Lpop_shstk_done\@
+
+ /*
+ * CALL Emulation has overwritten the shadow-stack frame and
+ * SSP is lost. Point it back to 3 slots down where the real
+ * return has to go.
+ *
+ * Doing a CALL here will add a RSB which the next RET will
+ * mispredict on but all RETs after that are balanced.
+ */
+ ANNOTATE_INTRA_FUNCTION_CALL
+ call 1f
+ int3
+1:
+ /* Synthesize the corrct SSP to fix the FRED Frame. */
+ addq $8, %rsp
+ rdsspq %rax
+ leaq 24(%rax), %rcx
+ wrssq %rcx, (%rax)
+
+.Lpop_shstk_done\@:
+ popq %rax
+.endm
+
+#else /* !CONFIG_X86_KERN_SHADOW_STACK */
+
+.macro PUSH_KERN_SHSTK_FRAME
+.endm
+.macro POP_KERN_SHSTK_FRAME
+.endm
+
+#endif /* CONFIG_X86_KERN_SHADOW_STACK */
+
.macro FRED_ENTER ssp=0
UNWIND_HINT_END_OF_STACK
ANNOTATE_NOENDBR
@@ -23,20 +97,16 @@
ENCODE_FRAME_POINTER
movq %rsp, %rdi /* %rdi -> pt_regs */
-#ifdef CONFIG_X86_KERN_SHADOW_STACK
- .if \ssp
- rdsspq %rax /* NOP if SHSTK is off. Pre-zeroed. */
- push %rax
- .endif
-#endif
+.if \ssp
+ PUSH_KERN_SHSTK_FRAME
+.endif
.endm
.macro FRED_EXIT ssp=0
-#ifdef CONFIG_X86_KERN_SHADOW_STACK
- .if \ssp
- pop %rax /* Any dead register */
- .endif
-#endif
+.if \ssp
+ POP_KERN_SHSTK_FRAME
+.endif
+
UNWIND_HINT_REGS
POP_REGS
.endm
diff --git a/arch/x86/include/asm/insn-eval.h b/arch/x86/include/asm/insn-eval.h
index 2f4c4d3d3f9b..75d40a399ace 100644
--- a/arch/x86/include/asm/insn-eval.h
+++ b/arch/x86/include/asm/insn-eval.h
@@ -83,8 +83,13 @@ static inline void insn_assign_reg(unsigned long *reg, u64 val, int bytes)
}
#ifdef CONFIG_X86_CET
+
void regs_set_return_ip(struct pt_regs *regs, unsigned long ip);
-#else
+void regs_emulate_call(struct pt_regs *regs, unsigned long ret, unsigned long func);
+void regs_emulate_ret(struct pt_regs *regs, unsigned long ret_ip);
+
+#else /* !CONFIG_X86_CET */
+
static inline void regs_set_return_ip(struct pt_regs *regs, unsigned long ip)
{
/* This is only for changing kernel return addresses: */
@@ -92,6 +97,19 @@ static inline void regs_set_return_ip(struct pt_regs *regs, unsigned long ip)
regs->ip = ip;
}
-#endif
+
+static inline void regs_emulate_call(struct pt_regs *regs,
+ unsigned long ret,
+ unsigned long func)
+{
+ regs_set_return_ip(regs, func);
+}
+
+static inline void regs_emulate_ret(struct pt_regs *regs, unsigned long ret_ip)
+{
+ regs_set_return_ip(regs, ret_ip);
+}
+
+#endif /* CONFIG_X86_CET */
#endif /* _ASM_X86_INSN_EVAL_H */
diff --git a/arch/x86/include/asm/text-patching.h b/arch/x86/include/asm/text-patching.h
index ea09381070e8..2c0c736fb62a 100644
--- a/arch/x86/include/asm/text-patching.h
+++ b/arch/x86/include/asm/text-patching.h
@@ -5,6 +5,7 @@
#include <linux/types.h>
#include <linux/stddef.h>
#include <asm/ptrace.h>
+#include <asm/insn-eval.h>
/*
* Currently, the max observed size in the kernel code is
@@ -135,7 +136,7 @@ extern __ro_after_init unsigned long text_poke_mm_addr;
static __always_inline
void int3_emulate_jmp(struct pt_regs *regs, unsigned long ip)
{
- regs->ip = ip;
+ regs_set_return_ip(regs, ip);
}
static __always_inline
@@ -167,14 +168,14 @@ static __always_inline
void int3_emulate_call(struct pt_regs *regs, unsigned long ip, unsigned long func)
{
int3_emulate_push(regs, ip);
- int3_emulate_jmp(regs, func);
+ regs_emulate_call(regs, ip, func);
}
static __always_inline
void int3_emulate_ret(struct pt_regs *regs)
{
unsigned long ip = int3_emulate_pop(regs);
- int3_emulate_jmp(regs, ip);
+ regs_emulate_ret(regs, ip);
}
static __always_inline
diff --git a/arch/x86/kernel/alternative.c b/arch/x86/kernel/alternative.c
index 582c6d8307d1..20880945a1fa 100644
--- a/arch/x86/kernel/alternative.c
+++ b/arch/x86/kernel/alternative.c
@@ -1981,7 +1981,7 @@ static bool decode_fineibt_preamble(struct pt_regs *regs, unsigned long *target,
* Since regs->ip points to the middle of an instruction; it cannot
* continue with the normal fixup.
*/
- regs->ip = *target;
+ regs_set_return_ip(regs, *target);
return true;
@@ -2085,7 +2085,7 @@ static bool decode_fineibt_paranoid(struct pt_regs *regs, unsigned long *target,
*target = regs->r11 + fineibt_prefix_size;
*type = regs->ax;
- regs->ip = *target;
+ regs_set_return_ip(regs, *target);
return true;
}
diff --git a/arch/x86/kernel/asm-offsets.c b/arch/x86/kernel/asm-offsets.c
index acbd0c1fb2ad..fc1cbee2f9e9 100644
--- a/arch/x86/kernel/asm-offsets.c
+++ b/arch/x86/kernel/asm-offsets.c
@@ -112,6 +112,9 @@ static void __used common(void)
BLANK();
DEFINE(PTREGS_SIZE, sizeof(struct pt_regs));
OFFSET(C_PTREGS_SIZE, pt_regs, orig_ax);
+#ifdef CONFIG_X86_KERN_SHADOW_STACK
+ DEFINE(PTREGS_fred_vector, offsetof(struct pt_regs, fred_ss) + 4);
+#endif
/* TLB state for the entry code */
OFFSET(TLB_STATE_user_pcid_flush_mask, tlb_state, user_pcid_flush_mask);
diff --git a/arch/x86/kernel/cet.c b/arch/x86/kernel/cet.c
index 97375a8335c8..bab8ff1c64c5 100644
--- a/arch/x86/kernel/cet.c
+++ b/arch/x86/kernel/cet.c
@@ -114,6 +114,14 @@ static void ibt_clear_fred_wfe(struct pt_regs *regs)
regs->fred_cs.wfe = 0;
}
+enum fred_exit_work {
+ FRED_EXIT_EMULATE_CALL = 1
+};
+
+enum frame_context {
+ FRED_ENTRY = 1
+};
+
/*
* FRED hardware pushes this frame on to the shadow stack for
* kernel=>kernel entry. First (lowest address) in this struct
@@ -129,11 +137,23 @@ struct fred_shstk_entry_frame {
* The kernel=>kernel entry code pushes SSP on to the entry stack.
* This only occurs for kernel=>kernel entry. Not userspace.
*
- * SSP is pushed on to the frame below pt_regs. At the point it is
- * pushed, it points to a special FRED entry frame.
+ * Number of spare frames available on shadow stack is pushed onto
+ * the frame below pt_regs followed by the SSP before the spare
+ * frames were populated (if any). At the point it is pushed, it
+ * points to a special FRED entry frame.
*/
-struct fred_kernel_frame {
- struct fred_shstk_entry_frame *ssef;
+struct kernel_event_frame {
+ union {
+ struct {
+ u8 fred_exit_work_flags;
+ u8 context;
+ };
+ u64 metadata;
+ };
+ union {
+ struct fred_shstk_entry_frame *ssef;
+ u64 *ssp;
+ };
struct pt_regs regs;
};
@@ -158,7 +178,7 @@ static void do_kernel_shstk_cp(struct pt_regs *regs, unsigned long error_code)
unsigned long ssp, ip, shstk_ip, sp_off = 0;
u8 insn[sizeof(erets)] = { };
- ssef = container_of(regs, struct fred_kernel_frame, regs)->ssef;
+ ssef = container_of(regs, struct kernel_event_frame, regs)->ssef;
ssp = cp_peek((unsigned long)&ssef->ssef_ssp);
switch (error_code & CP_EC) {
@@ -249,7 +269,7 @@ DEFINE_IDTENTRY_ERRORCODE(exc_control_protection)
*
* Update the FRED entry frame in addition to regs->ip.
*/
-void regs_set_return_ip(struct pt_regs *regs, unsigned long ip)
+noinstr void regs_set_return_ip(struct pt_regs *regs, unsigned long ip)
{
struct fred_shstk_entry_frame *ssef;
@@ -261,9 +281,117 @@ void regs_set_return_ip(struct pt_regs *regs, unsigned long ip)
/* Only kernel-mode events save the 'ssef' pointer. */
WARN_ON_ONCE(user_mode(regs));
- ssef = container_of(regs, struct fred_kernel_frame, regs)->ssef;
+ ssef = container_of(regs, struct kernel_event_frame, regs)->ssef;
+ if (!ssef)
+ return;
+
+ wrss(ip, &ssef->ssef_lip);
+}
+
+/*
+ * Make the event return to @func as if it executed a CALL that returns to
+ * @ret. The caller has already pushed @ret on the regular stack.
+ * If int3 does not emulate a CALL, the dummy shadow stack frame is popped
+ * at FRED_EXIT \ssp=1 before ERETS.
+ */
+noinstr void regs_emulate_call(struct pt_regs *regs, unsigned long ret, unsigned long func)
+{
+ struct fred_shstk_entry_frame *ssef;
+ struct kernel_event_frame *frame;
+ int frame_size;
+ u64 *raw_frame;
+
+ regs->ip = func;
+
+ if (!cpu_feature_enabled(X86_FEATURE_KERN_SHSTK))
+ return;
+
+ WARN_ON_ONCE(user_mode(regs));
+
+ frame = container_of(regs, struct kernel_event_frame, regs);
+
+ ssef = frame->ssef;
+ if (!ssef)
+ return;
+
+ /* Someone else emulated a CALL for same frame? */
+ if (WARN_ON_ONCE(frame->fred_exit_work_flags))
+ return;
+
+ /*
+ * Return frame must be right below the FRED frame
+ * else FRED_EXIT will not be able to recreate the
+ * SSP correctly. Leave breadcrumbs if we #CP.
+ */
+ raw_frame = (u64 *)ssef;
+ frame_size = sizeof(*ssef) / sizeof(u64);
+ WARN_ON_ONCE((u64 *)ssef->ssef_ssp != raw_frame + frame_size);
+
+ frame->fred_exit_work_flags |= FRED_EXIT_EMULATE_CALL;
+ wrss(func, &ssef->ssef_lip);
+
+ /*
+ * Consume the SSP and move the rest of the FRED frame aka
+ * { LIP, CS } up by one slot. This is how the shadow stack
+ * looks at the end:
+ *
+ * +-----+ +-----+ <--- Top of Shadow Stack
+ * | SSP | | LIP |
+ * | LIP | -> | CS |
+ * | CS | +-----+
+ * +-----+ <- SSP points | RET |
+ * | ... | here +-----+
+ * +-----+ | ... |
+ *
+ * Since SSP should always point 3 slots below, a new frame is
+ * synthesized at FRED exit to reconstruct the SSP making the
+ * FRED frame whole again before ERETS.
+ *
+ * XXX: One wrss() call can be reduced by doing "ssef_lip"
+ * overwrite during the movement but keep it simple for now.
+ */
+ for (int i = 0; i < frame_size - 1; ++i)
+ wrss(raw_frame[i + 1], &raw_frame[i]);
+
+ /*
+ * Populate the ret frame and consme the FRED frame
+ * pointer so no other emulation is possible.
+ */
+ wrss(ret, &raw_frame[frame_size - 1]);
+ frame->ssef = NULL;
+}
+
+/*
+ * Make the event return to @ip as if it executed a RET. The caller
+ * has already popped @ip off the regular stack.
+ */
+noinstr void regs_emulate_ret(struct pt_regs *regs, unsigned long ip)
+{
+ struct fred_shstk_entry_frame *ssef;
+
+ regs->ip = ip;
+
+ if (!cpu_feature_enabled(X86_FEATURE_KERN_SHSTK))
+ return;
+
+ WARN_ON_ONCE(user_mode(regs));
+
+ ssef = container_of(regs, struct kernel_event_frame, regs)->ssef;
if (!ssef)
return;
+ /*
+ * Return target should point to the old SP on top of the shadow
+ * stack that was popped from the regular stack.
+ */
+ if (*((u64 *)ssef->ssef_ssp) != ip)
+ return;
+
+ /* Point the SP on the frame to the new SP one frame below. */
+ wrss(ssef->ssef_ssp + sizeof(unsigned long), &ssef->ssef_ssp);
+ /*
+ * Set return ip on frame to the new return target such that
+ * return from FRED frame jumps to the target.
+ */
wrss(ip, &ssef->ssef_lip);
}
diff --git a/arch/x86/kernel/traps.c b/arch/x86/kernel/traps.c
index 30aa8369957e..01b16dcd0d8c 100644
--- a/arch/x86/kernel/traps.c
+++ b/arch/x86/kernel/traps.c
@@ -466,9 +466,9 @@ noinstr bool handle_bug(struct pt_regs *regs)
*/
if (handled) {
if (regs->ip == addr)
- regs->ip += ud_len;
+ regs_set_return_ip(regs, addr + ud_len);
} else {
- regs->ip = addr;
+ regs_set_return_ip(regs, addr);
}
if (regs->flags & X86_EFLAGS_IF)
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 08/27] x86/retpoline: Handle retpolies and thunks with kernel shadow stack
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (6 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 07/27] x86/entry: Handle int3 text patching with kernel shadow stack K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 09/27] x86/ftrace: Prepare ftrace trampolines to handle " K Prateek Nayak
` (19 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
Retpolines need to correct the return address on the shadow stack to
match that of the indirect call target such that the return doesn't lead
to a #CP. Direct jump to an out of line trampoline that handles shadow
stack and does the final RET which allows keeping the retpoline thunk
size below 32-bytes.
SRSO adds a CALL, LEA, RET pattern which needs to pop an intermediate
shadow stack slot since the correct return address exists right below.
The handle_interrupted_saferet() handling with shadow stack is hard and
there are no processors that need Safe-RET sequence to mitigate SRSO and
support FRED (touch wood!).
Make any CPUs that toggle Safe-RET with X86_FEATURE_KERN_SHSTK call an
alternalte Safe-RET thunk that handle_interrupted_saferet() is unaware
of. If FRED enabled systems ever need Safe-RET (hopefully never),
handle_interrupted_saferet() has to spot if the control is past
incsspq or not (perhaps using another global symbol):
o If control is past incsspq, emulate a POP + RET like normal.
o If incsspq has not yet executed, use the FRED shadow stack frame's SSP
to redirect the SSP at return to one slot above (similar to how
int3_emulate_ret() does) in addition to handling the rest of the LEA +
RET sequence.
Call depth thunk only needs to pop 16 entries when the RSB is stuffed
which is also copied for the RSB_FILL_LOOP.
Retpolines cannot clobber registers and need to handle it on stack :-(
Saferet sequences are longer :-(
Survives a spectre_v2=retpolines,generic :-)
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/Kconfig | 12 ----
arch/x86/include/asm/alternative.h | 3 +-
arch/x86/include/asm/nospec-branch.h | 27 +++++++-
arch/x86/lib/retpoline.S | 92 +++++++++++++++++++++++++++-
4 files changed, 116 insertions(+), 18 deletions(-)
diff --git a/arch/x86/Kconfig b/arch/x86/Kconfig
index a5bad1fd3010..559b9bc95c38 100644
--- a/arch/x86/Kconfig
+++ b/arch/x86/Kconfig
@@ -1907,18 +1907,6 @@ config X86_KERN_SHADOW_STACK
depends on VMAP_STACK
depends on AS_WRUSS
select X86_CET
- # The retpoline sequence is "call; mov %reg,(%rsp); ret": the
- # CALL pushes a shadow stack entry and the RET then uses a
- # rewritten return address. Mismatch every time.
- depends on !MITIGATION_RETPOLINE
- # The indirect call thunks are retpoline-based (see above) and
- # call_depth_return_thunk() refills the RSB with 16 CALLs, then
- # does "add $128,%rsp; ret", leaving 16 stale shadow stack entries.
- depends on !MITIGATION_CALL_DEPTH_TRACKING
- # Safe-RET is "call srso_safe_ret" followed by
- # "lea 8(%rsp),%rsp; ret": the RET consumes the caller's return
- # address while the shadow stack top holds the CALL's.
- depends on !MITIGATION_SRSO
# Replaces return addresses on the stack with return_to_handler,
# and return_to_handler itself returns with a retpoline-style
# "call; mov %rdi,(%rsp); ret".
diff --git a/arch/x86/include/asm/alternative.h b/arch/x86/include/asm/alternative.h
index 08af86ef090a..83ee5527ed4a 100644
--- a/arch/x86/include/asm/alternative.h
+++ b/arch/x86/include/asm/alternative.h
@@ -329,7 +329,8 @@ void nop_func(void);
.endm
.macro ALTERNATIVE_3 oldinstr, newinstr1, ft_flags1, newinstr2, ft_flags2, newinstr3, ft_flags3
- __ALTERNATIVE(ALTERNATIVE_2(\oldinstr, \newinstr1, \ft_flags1, \newinstr2, \ft_flags2),
+ __ALTERNATIVE(__ALTERNATIVE(__ALTERNATIVE(\oldinstr, \newinstr1, \ft_flags1),
+ \newinstr2, \ft_flags2),
\newinstr3, \ft_flags3)
.endm
diff --git a/arch/x86/include/asm/nospec-branch.h b/arch/x86/include/asm/nospec-branch.h
index 1abeb9af000b..0872dceb3819 100644
--- a/arch/x86/include/asm/nospec-branch.h
+++ b/arch/x86/include/asm/nospec-branch.h
@@ -121,6 +121,7 @@
*/
#define RETPOLINE_THUNK_SIZE 32
+
#define RSB_CLEAR_LOOPS 32 /* To forcibly overwrite all entries */
/*
@@ -132,6 +133,24 @@
int3; \
772:
+#ifdef CONFIG_X86_KERN_SHADOW_STACK
+
+/* INCSSP #UDs when the supervisor shadow stack is not enabled. */
+#define __FIXUP_SHSTK_SLOTS(reg, nr) \
+ xor reg, reg; \
+ rdsspq reg; \
+ test reg, reg; \
+ jz 773f; \
+ mov $nr, reg; \
+ incsspq reg; \
+773:
+
+#else /* !CONFIG_X86_KERN_SHADOW_STACK */
+
+#define __FIXUP_SHSTK_SLOTS(reg, nr)
+
+#endif /* CONFIG_X86_KERN_SHADOW_STACK */
+
/*
* Stuff the entire RSB.
*
@@ -149,6 +168,7 @@
dec reg; \
jnz 771b; \
/* barrier for jnz misprediction */ \
+ __FIXUP_SHSTK_SLOTS(reg, nr); \
lfence; \
CREDIT_CALL_DEPTH \
CALL_THUNKS_DEBUG_INC_CTXSW
@@ -173,10 +193,11 @@
* On PBRSB-vulnerable CPUs, it is not safe for a RET to be executed
* before this point.
*/
-#define __FILL_ONE_RETURN \
+#define __FILL_ONE_RETURN(reg) \
__FILL_RETURN_SLOT \
add $(BITS_PER_LONG/8), %_ASM_SP; \
- lfence;
+ lfence; \
+ __FIXUP_SHSTK_SLOTS(reg, 1);
/*
* Helper for detecting if an interrupt occurred at an unsafe location within
@@ -289,7 +310,7 @@
.macro FILL_RETURN_BUFFER reg:req nr:req ftr:req ftr2=ALT_NOT(X86_FEATURE_ALWAYS)
ALTERNATIVE_2 "jmp .Lskip_rsb_\@", \
__stringify(__FILL_RETURN_BUFFER(\reg,\nr)), \ftr, \
- __stringify(nop;nop;__FILL_ONE_RETURN), \ftr2
+ __stringify(nop;nop;__FILL_ONE_RETURN(\reg)), \ftr2
.Lskip_rsb_\@:
.endm
diff --git a/arch/x86/lib/retpoline.S b/arch/x86/lib/retpoline.S
index f9ca1d8eabca..d4a8c2b434a1 100644
--- a/arch/x86/lib/retpoline.S
+++ b/arch/x86/lib/retpoline.S
@@ -29,6 +29,37 @@
RET
.endm
+#ifdef CONFIG_X86_KERN_SHADOW_STACK
+
+SYM_CODE_START(__x86_shstk_poline_ret)
+ UNWIND_HINT_FUNC
+ ANNOTATE_NOENDBR
+ push %rax
+ xorl %eax, %eax
+ rdsspq %rax
+ testq %rax, %rax
+ jz 1f
+ push %rcx
+ movq 16(%rsp), %rcx
+ wrssq %rcx, (%rax)
+ pop %rcx
+1: pop %rax
+ RET
+SYM_CODE_END(__x86_shstk_poline_ret)
+
+.macro RETPOLINE_SHSTK reg
+ POLINE \reg
+ jmp __x86_shstk_poline_ret
+.endm
+
+#else /* CONFIG_X86_KERN_SHADOW_STACK */
+
+.macro RETPOLINE_SHSTK reg
+ RETPOLINE \reg
+.endm
+
+#endif
+
.macro THUNK reg
.align RETPOLINE_THUNK_SIZE
@@ -36,9 +67,11 @@ SYM_INNER_LABEL(__x86_indirect_thunk_\reg, SYM_L_GLOBAL)
UNWIND_HINT_UNDEFINED
ANNOTATE_NOENDBR
- ALTERNATIVE_2 __stringify(RETPOLINE \reg), \
+ ALTERNATIVE_3 __stringify(RETPOLINE \reg), \
__stringify(lfence; ANNOTATE_RETPOLINE_SAFE; jmp *%\reg; int3), X86_FEATURE_RETPOLINE_LFENCE, \
+ __stringify(RETPOLINE_SHSTK \reg), X86_FEATURE_KERN_SHSTK, \
__stringify(ANNOTATE_RETPOLINE_SAFE; jmp *%\reg), ALT_NOT(X86_FEATURE_RETPOLINE)
+
SYM_PIC_ALIAS(__x86_indirect_thunk_\reg)
.endm
@@ -228,10 +261,50 @@ SYM_CODE_START_NOALIGN(srso_alias_safe_ret)
int3
SYM_FUNC_END(srso_alias_safe_ret)
+/*
+ * Safe-RET sequence system with X86_FEATURE_KERN_SHSTK.
+ *
+ * This does not need to adhere to constraints of
+ * handle_interrupted_saferet() since none of the FRED enabled systems
+ * need Safe-RET mitigation. It only exists as a precaution for systems
+ * that enable kernel shadow stack and somehow lands here.
+ *
+ * If this ever needs a handle_interrupted_saferet() like handling,
+ * check if incsspq has been handled or not, and if it hasn't been
+ * handled, use the FRED event frame to pop the shadow stack by
+ * redirecting the SSP on top of the frame and continue as usual.
+ */
+SYM_CODE_START_NOALIGN(srso_alias_safe_ret_shstk)
+#ifdef CONFIG_X86_KERN_SHADOW_STACK
+ movq %rcx, (%_ASM_SP)
+ movq $0, %rcx
+ rdsspq %rcx
+ jrcxz 1f
+ movl $1, %ecx
+ incsspq %rcx
+1:
+ movq (%_ASM_SP), %rcx
+#endif
+ lea 8(%_ASM_SP), %_ASM_SP
+ UNWIND_HINT_FUNC
+ ANNOTATE_UNRET_SAFE
+ ret
+ /* End of Safe-RET sequence */
+ int3
+SYM_FUNC_END(srso_alias_safe_ret_shstk)
+
SYM_CODE_START_NOALIGN(srso_alias_return_thunk)
UNWIND_HINT_FUNC
ANNOTATE_NOENDBR
- call srso_alias_safe_ret
+
+ /*
+ * Switch to kernel shadow stack handling before
+ * it is toggled on.
+ */
+ ALTERNATIVE "call srso_alias_safe_ret_shstk", \
+ "call srso_alias_safe_ret", \
+ ALT_NOT(X86_FEATURE_KERN_SHSTK)
+
ud2
SYM_CODE_END(srso_alias_return_thunk)
.popsection
@@ -394,6 +467,20 @@ __EXPORT_THUNK(entry_untrain_ret)
#ifdef CONFIG_MITIGATION_CALL_DEPTH_TRACKING
+.macro FIXUP_CALL_DEPTH_SHSTK
+#ifdef CONFIG_X86_KERN_SHADOW_STACK
+ push %rax
+ xor %eax, %eax
+ rdsspq %rax
+ test %rax, %rax
+ jz .Lshstk_skip\@
+ movl $16, %eax
+ incsspq %rax
+.Lshstk_skip\@:
+ pop %rax
+#endif
+.endm
+
.align 64
SYM_FUNC_START(call_depth_return_thunk)
ANNOTATE_NOENDBR
@@ -417,6 +504,7 @@ SYM_FUNC_START(call_depth_return_thunk)
.endr
add $(8*16), %rsp
+ FIXUP_CALL_DEPTH_SHSTK
CREDIT_CALL_DEPTH
ANNOTATE_UNRET_SAFE
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 09/27] x86/ftrace: Prepare ftrace trampolines to handle shadow stack
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (7 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 08/27] x86/retpoline: Handle retpolies and thunks " K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 10/27] x86/kprobes: Prepare optprobe trampoline to handle shadow stacks K Prateek Nayak
` (18 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
Kprobes can hook onto function entry via optprobes, int3 kprobes, or via
ftrace_regs_caller and hijack the return. From a shadow stack
perspective, the ftrace_caller's stack looks like:
caller
call traced_function
call ftrace_regs_caller
Rethooks and return_to_handler can hijack the return address from
traced_function; IPMODIFY and direct caller ftrace handlers can steer
the return from traced function.
To be aware of the shadow stack context that needs correction, the CET
helpers need to know the context from where pt_regs came from.
Similar to the FRED frame handling, push the SSP at ftrace_regs_caller
and a context metadata flag onto the stack that can be inspected from
the handler.
Based on the event type, the CET helpers can be made aware if the slot
that needs modifying is at SSP, or just below. return_to_handler() now
does the INTRA_FUNCTION_CALL early which allows using the stack slot
pushed for the pt_regs container. !X86_KERN_SHADOW_STACK build will now
do an extra pop.
Note: The return_to_handler now sets regs->cs to 0 to prevent false
positives of !user_mode_regs() in CET helpers. Since a full pt_regs is
not present, it also blocks the ftrace helper from returning the
incomplete pt_regs pointer.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/kernel/cet.c | 4 +-
arch/x86/kernel/ftrace_64.S | 121 +++++++++++++++++++++++++++++++-----
2 files changed, 108 insertions(+), 17 deletions(-)
diff --git a/arch/x86/kernel/cet.c b/arch/x86/kernel/cet.c
index bab8ff1c64c5..66c9ce531249 100644
--- a/arch/x86/kernel/cet.c
+++ b/arch/x86/kernel/cet.c
@@ -119,7 +119,9 @@ enum fred_exit_work {
};
enum frame_context {
- FRED_ENTRY = 1
+ FRED_ENTRY = 1,
+ FTRACE_CALLER,
+ RETURN_TRAMPOLINE
};
/*
diff --git a/arch/x86/kernel/ftrace_64.S b/arch/x86/kernel/ftrace_64.S
index 62c1c93aa1c6..a6211070d6e5 100644
--- a/arch/x86/kernel/ftrace_64.S
+++ b/arch/x86/kernel/ftrace_64.S
@@ -131,6 +131,62 @@
.endm
+#ifdef CONFIG_X86_KERN_SHADOW_STACK
+
+/*
+ * The ftrace handler might use regs_set_return_ip() to steer the return
+ * from ftrace_caller which also tries to do shadow stack handling
+ * assuming pt_regs is part of the standared FRED entry frame.
+ *
+ * Avoid any shadow stack manipulations by setting the two slots above
+ * pt_regs to zeros. regs_set_return_ip() et al. will see shadow stack
+ * pointer to be NULL and skip any shadow stack handling.
+ *
+ * Ftrace caller will correct the shadow stack if the handler has
+ * hijacked any of the return or has decided to do a tail call.
+ */
+.macro FTRACE_PUSH_SHSTK_FRAME
+ xor %eax, %eax
+ rdsspq %rax
+ pushq %rax
+ pushq $0x200
+ .endm
+
+.macro FTRACE_POP_SHSTK_FRAME
+ addq $16, %rsp
+ .endm
+
+.macro FTRACE_FIX_DIRECT_CALL_SHSTK
+ xor %ecx, %ecx
+ rdsspq %rcx
+ testq %rcx, %rcx
+ jz .Lshstk_done\@
+ wrssq %rax, (%rcx)
+.Lshstk_done\@:
+ .endm
+
+.macro FTRACE_PUSH_RETURN_HANDLER_SHSTK_FRAME
+ xor %eax, %eax
+ rdsspq %rax
+ movq %rax, (%rsp) /* Pushed by intra function call. */
+ pushq $0x300
+ .endm
+
+#else /* !CONFIG_X86_KERN_SHADOW_STACK */
+
+.macro FTRACE_PUSH_SHSTK_FRAME
+ .endm
+.macro FTRACE_POP_SHSTK_FRAME
+ .endm
+.macro FTRACE_FIX_DIRECT_CALL_SHSTK
+ .endm
+
+.macro FTRACE_PUSH_RETURN_HANDLER_SHSTK_FRAME
+ addq $8, %rsp
+ .endm
+
+#endif /* CONFIG_X86_KERN_SHADOW_STACK */
+
SYM_TYPED_FUNC_START(ftrace_stub)
CALL_DEPTH_ACCOUNT
RET
@@ -177,10 +233,18 @@ SYM_INNER_LABEL(ftrace_caller_op_ptr, SYM_L_GLOBAL)
/* Account for the function call below */
CALL_DEPTH_ACCOUNT
+ /*
+ * Push a blank frame above pt_regs as to not confuse
+ * the shadow stack handlers.
+ */
+ FTRACE_PUSH_SHSTK_FRAME
+
SYM_INNER_LABEL(ftrace_call, SYM_L_GLOBAL)
ANNOTATE_NOENDBR
call ftrace_stub
+ FTRACE_POP_SHSTK_FRAME
+
/* Handlers can change the RIP */
movq RIP(%rsp), %rax
movq %rax, MCOUNT_REG_SIZE(%rsp)
@@ -242,10 +306,15 @@ SYM_INNER_LABEL(ftrace_regs_caller_op_ptr, SYM_L_GLOBAL)
/* Account for the function call below */
CALL_DEPTH_ACCOUNT
+ /* See comment in ftrace_caller above. */
+ FTRACE_PUSH_SHSTK_FRAME
+
SYM_INNER_LABEL(ftrace_regs_call, SYM_L_GLOBAL)
ANNOTATE_NOENDBR
call ftrace_stub
+ FTRACE_POP_SHSTK_FRAME
+
/* Copy flags back to SS, to restore them */
movq EFLAGS(%rsp), %rax
movq %rax, MCOUNT_REG_SIZE(%rsp)
@@ -290,6 +359,9 @@ SYM_INNER_LABEL(ftrace_regs_caller_end, SYM_L_GLOBAL)
jz 2f
andq $0xfffffffffffffffe, %rax
movq %rax, MCOUNT_REG_SIZE+8(%rsp)
+
+ FTRACE_FIX_DIRECT_CALL_SHSTK
+
restore_mcount_regs
/* Restore flags */
popfq
@@ -300,21 +372,26 @@ SYM_INNER_LABEL(ftrace_regs_caller_end, SYM_L_GLOBAL)
movq %rdi, MCOUNT_REG_SIZE-8(%rsp)
movq %rax, MCOUNT_REG_SIZE(%rsp)
- restore_mcount_regs 8
- /* Restore flags */
- popfq
- UNWIND_HINT_FUNC
-
/*
- * The above left an extra return value on the stack; effectively
- * doing a tail-call without using a register. This PUSH;RET
- * pattern unbalances the RSB, inject a pointless CALL to rebalance.
+ * Restore below will leve an extra return value on the stack;
+ * effectively doing a tail-call without using a register.
+ * This PUSH;RET pattern unbalances the RSB, inject a pointless
+ * CALL to rebalance.
*/
ANNOTATE_INTRA_FUNCTION_CALL
CALL .Ldo_rebalance
int3
.Ldo_rebalance:
add $8, %rsp
+
+ /* Populate the return into the frame from above. */
+ FTRACE_FIX_DIRECT_CALL_SHSTK
+
+ restore_mcount_regs 8
+ /* Restore flags */
+ popfq
+ UNWIND_HINT_FUNC
+
ALTERNATIVE __stringify(RET), \
__stringify(ANNOTATE_UNRET_SAFE; ret; int3), \
X86_FEATURE_CALL_DEPTH
@@ -378,26 +455,38 @@ SYM_CODE_START(return_to_handler)
movq %rdx, RDX(%rsp)
movq %rbp, RBP(%rsp)
movq %rdi, RSP(%rsp)
+ movq $0, CS(%rsp)
movq %rsp, %rdi
+ /*
+ * Final RET will jump back to the old return address. Since, the return
+ * frame was hijacked, use a retpoline here to keep the RSB balanced.
+ *
+ * For shadow stack, this adds the frame to stuff the return address into.
+ */
+ ANNOTATE_INTRA_FUNCTION_CALL
+ call .Ldo_rop
+ int3
+.Ldo_rop:
+ FTRACE_PUSH_RETURN_HANDLER_SHSTK_FRAME
+
call ftrace_return_to_handler
+ FTRACE_POP_SHSTK_FRAME
+
movq %rax, %rdi
movq RDX(%rsp), %rdx
movq RAX(%rsp), %rax
- addq $(FRAME_SIZE) + 8, %rsp
+ addq $(FRAME_SIZE), %rsp
/*
- * Jump back to the old return address. This cannot be JMP_NOSPEC rdi
- * since IBT would demand that contain ENDBR, which simply isn't so for
- * return addresses. Use a retpoline here to keep the RSB balanced.
+ * This cannot be JMP_NOSPEC rdi since IBT would demand that contain ENDBR,
+ * which simply isn't so for return addresses. This is the second part of
+ * the repoline sequence; CALL has already been balanced above.
*/
- ANNOTATE_INTRA_FUNCTION_CALL
- call .Ldo_rop
- int3
-.Ldo_rop:
mov %rdi, (%rsp)
+
ALTERNATIVE __stringify(RET), \
__stringify(ANNOTATE_UNRET_SAFE; ret; int3), \
X86_FEATURE_CALL_DEPTH
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 10/27] x86/kprobes: Prepare optprobe trampoline to handle shadow stacks
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (8 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 09/27] x86/ftrace: Prepare ftrace trampolines to handle " K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 11/27] x86/rethook: Prepare the rethook trampoline to handle shadow stack K Prateek Nayak
` (17 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
Optimized probes can be executed from a trampoline where, although it
cannot hijack the regs->ip to steer return from the caller, it can still
be used to attach a retprobe trampoline.
The path into the optprobe trampoline looks like:
caller
call traced_function
jmp optprobe_template_entry
Similar to FRED frame, extend a container outside pt_regs to notify this
is an optprobe frame the handler is on using frame metadata.
The return trampoline will be populated at the top of SSP such that
traced function's return jumps to the return trampoline and the
trampoline can direct the return from within in case there are multiple
trampolines chained on the same function.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/kernel/cet.c | 3 ++-
arch/x86/kernel/ftrace_64.S | 2 +-
arch/x86/kernel/kprobes/opt.c | 26 ++++++++++++++++++++++++++
3 files changed, 29 insertions(+), 2 deletions(-)
diff --git a/arch/x86/kernel/cet.c b/arch/x86/kernel/cet.c
index 66c9ce531249..b037508215c9 100644
--- a/arch/x86/kernel/cet.c
+++ b/arch/x86/kernel/cet.c
@@ -121,7 +121,8 @@ enum fred_exit_work {
enum frame_context {
FRED_ENTRY = 1,
FTRACE_CALLER,
- RETURN_TRAMPOLINE
+ RETURN_TRAMPOLINE,
+ OPTPORBE_TRAMPOLINE
};
/*
diff --git a/arch/x86/kernel/ftrace_64.S b/arch/x86/kernel/ftrace_64.S
index a6211070d6e5..9060c16d34b3 100644
--- a/arch/x86/kernel/ftrace_64.S
+++ b/arch/x86/kernel/ftrace_64.S
@@ -459,7 +459,7 @@ SYM_CODE_START(return_to_handler)
movq %rsp, %rdi
/*
- * Final RET will jump back to the old return address. Since, the return
+ * Final RET will jump back to the old return address. Since the return
* frame was hijacked, use a retpoline here to keep the RSB balanced.
*
* For shadow stack, this adds the frame to stuff the return address into.
diff --git a/arch/x86/kernel/kprobes/opt.c b/arch/x86/kernel/kprobes/opt.c
index 3f8fea52619f..5694cf566022 100644
--- a/arch/x86/kernel/kprobes/opt.c
+++ b/arch/x86/kernel/kprobes/opt.c
@@ -34,6 +34,30 @@
#include "common.h"
+#ifdef CONFIG_X86_KERN_SHADOW_STACK
+
+/*
+ * Push a NULL on the stack to such that CET helpers will
+ * see Shadow stack pointer as NULL and skip shadow stack
+ * corrects internally.
+ */
+#define OPTPROBE_PUSH_SHSTK_FRAME \
+ " xor %eax, %eax\n" \
+ " rdsspq %rax\n" \
+ " pushq %rax\n" \
+ " pushq $0x400\n"
+
+/* RAX is dead and will be restored after. */
+#define OPTPROBE_POP_SHSTK_FRAME \
+ " addq $16, %rsp\n"
+
+#else /* !CONFIG_X86_KERN_SHADOW_STACK */
+
+#define OPTPROBE_PUSH_SHSTK_FRAME
+#define OPTPROBE_POP_SHSTK_FRAME
+
+#endif /* CONFIG_X86_KERN_SHADOW_STACK */
+
unsigned long __recover_optprobed_insn(kprobe_opcode_t *buf, unsigned long addr)
{
struct optimized_kprobe *op;
@@ -115,6 +139,7 @@ asm (
ASM_NOP3
SAVE_REGS_STRING
" movq %rsp, %rsi\n"
+ OPTPROBE_PUSH_SHSTK_FRAME
".global optprobe_template_val\n"
"optprobe_template_val:\n"
ASM_NOP5
@@ -122,6 +147,7 @@ asm (
".global optprobe_template_call\n"
"optprobe_template_call:\n"
ASM_NOP5
+ OPTPROBE_POP_SHSTK_FRAME
/* Copy 'regs->flags' into 'regs->ss'. */
" movq 18*8(%rsp), %rdx\n"
" movq %rdx, 20*8(%rsp)\n"
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 11/27] x86/rethook: Prepare the rethook trampoline to handle shadow stack
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (9 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 10/27] x86/kprobes: Prepare optprobe trampoline to handle shadow stacks K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 12/27] x86/cet: Make regs_set_return_ip() helpers context aware K Prateek Nayak
` (16 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
Rethook prepare caches the original return IP from the regs->sp state it
was presented and insert the trampoline that later returns back to the
cached IP.
It is possible for multiple handlers to install multiple return
trampolines such that the return from one jumps to another, and
eventually landing to traced functions' caller's frame.
Since return trampoline has hijacked a genuine return, it must balance
the call, not only from the RSB perspective but also from shadow stack
perspective.
Similar to the return_to_handler, populate a dummy slot before
triggering the rethook handlers. The rethook handler must populate the
correct return IP in the slot using regs_set_return_ip() or expect a #CP
for missing redirection.
Since the return trampolines (although limited to two) can be chained in
weird manner to jump between each other based on the order of
pre-handler's running, the tail call technique to populate the return from
the ftrace handler turn complicated.
Instead, use a retpoline to return into the next trampoline until
the execution finds its way back to the correct caller.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/kernel/rethook.c | 34 ++++++++++++++++++++++++++++++++++
1 file changed, 34 insertions(+)
diff --git a/arch/x86/kernel/rethook.c b/arch/x86/kernel/rethook.c
index 85e2f2d16a90..974ef400b1b3 100644
--- a/arch/x86/kernel/rethook.c
+++ b/arch/x86/kernel/rethook.c
@@ -6,6 +6,9 @@
#include <linux/rethook.h>
#include <linux/kprobes.h>
#include <linux/objtool.h>
+#include <linux/annotate.h>
+
+#include <asm/insn-eval.h>
#include "kprobes/common.h"
@@ -15,6 +18,35 @@ __visible void arch_rethook_trampoline_callback(struct pt_regs *regs);
#define ANNOTATE_NOENDBR
#endif
+#ifdef CONFIG_X86_KERN_SHADOW_STACK
+
+/*
+ * The return to caller of traced function was hijacked by the trampoline and
+ * the trampoline now corrects the return address. Add a spare slot at SSP that
+ * the fixup function can use to syncing the return IP on stack from
+ * arch_rethook_trampoline_callback().
+ *
+ * Clobbers RAX which is dead in both context.
+ */
+#define RETHOOK_PUSH_SHSTK_FRAME \
+ ANNOTATE_INTRA_FUNCTION_CALL "\n" \
+ " call 1f\n" \
+ " int3\n" \
+ "1:\n" \
+ " xor %eax, %eax\n" \
+ " rdsspq %rax\n" \
+ " movq %rax, (%rsp)\n" \
+ " pushq $0x300\n"
+
+#define RETHOOK_POP_SHSTK_FRAME \
+ " addq $16, %rsp\n"
+
+#else /* !CONFIG_X86_KERN_SHADOW_STACK */
+
+#define RETHOOK_PUSH_SHSTK_FRAME
+#define RETHOOK_POP_SHSTK_FRAME
+
+#endif /* CONFIG_X86_KERN_SHADOW_STACK */
/*
* When a target function returns, this code saves registers and calls
* arch_rethook_trampoline_callback(), which calls the rethook handler.
@@ -35,7 +67,9 @@ asm(
" pushfq\n"
SAVE_REGS_STRING
" movq %rsp, %rdi\n"
+ RETHOOK_PUSH_SHSTK_FRAME
" call arch_rethook_trampoline_callback\n"
+ RETHOOK_POP_SHSTK_FRAME
RESTORE_REGS_STRING
/* In the callback function, 'regs->flags' is copied to 'regs->ss'. */
" addq $16, %rsp\n"
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 12/27] x86/cet: Make regs_set_return_ip() helpers context aware
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (10 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 11/27] x86/rethook: Prepare the rethook trampoline to handle shadow stack K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 13/27] x86/cet: Introduce regs_set_return_trampoline() for rethook trampoline K Prateek Nayak
` (15 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
All the known locations that can genuinely change the control flow have
been instrumented to advertise their context. Use the context
information to set the return IP to the correct shadow stack slot from
regs_set_return_ip().
All the emulation helpers are still expected to be called from a #BP
that inserts a FRED frame and any violations from other contexts are
warned about to help debugs and any shadow stack adjustments for these
contexts are skipped.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/kernel/cet.c | 41 ++++++++++++++++++++++++++++++++++++++---
1 file changed, 38 insertions(+), 3 deletions(-)
diff --git a/arch/x86/kernel/cet.c b/arch/x86/kernel/cet.c
index b037508215c9..fb80c841bbfb 100644
--- a/arch/x86/kernel/cet.c
+++ b/arch/x86/kernel/cet.c
@@ -275,6 +275,7 @@ DEFINE_IDTENTRY_ERRORCODE(exc_control_protection)
noinstr void regs_set_return_ip(struct pt_regs *regs, unsigned long ip)
{
struct fred_shstk_entry_frame *ssef;
+ struct kernel_event_frame *frame;
regs->ip = ip;
@@ -284,11 +285,34 @@ noinstr void regs_set_return_ip(struct pt_regs *regs, unsigned long ip)
/* Only kernel-mode events save the 'ssef' pointer. */
WARN_ON_ONCE(user_mode(regs));
- ssef = container_of(regs, struct kernel_event_frame, regs)->ssef;
+ frame = container_of(regs, struct kernel_event_frame, regs);
+
+ ssef = frame->ssef;
if (!ssef)
return;
- wrss(ip, &ssef->ssef_lip);
+ switch (frame->context) {
+ case FRED_ENTRY:
+ wrss(ip, &ssef->ssef_lip);
+ break;
+ case FTRACE_CALLER:
+ fallthrough;
+ case RETURN_TRAMPOLINE:
+ /*
+ * In case of both RETURN_TRAMPOLINE and FTRACE_CALLER,
+ * regs_set_return_ip() is used to hijack the return
+ * from the current frame. Just set the location at SSP.
+ */
+ wrss(ip, frame->ssp);
+ break;
+ case OPTPORBE_TRAMPOLINE:
+ /* regs->ip changes from optprobes are ignored. */
+ break;
+ default:
+ WARN_ONCE(1, "Unknown calling context %d! Expect #CP\n",
+ frame->context);
+ break;
+ }
}
/*
@@ -317,6 +341,10 @@ noinstr void regs_emulate_call(struct pt_regs *regs, unsigned long ret, unsigned
if (!ssef)
return;
+ /* A CALL emulation for !INT3 events are ignored. */
+ if (WARN_ON_ONCE(frame->context != FRED_ENTRY))
+ return;
+
/* Someone else emulated a CALL for same frame? */
if (WARN_ON_ONCE(frame->fred_exit_work_flags))
return;
@@ -371,6 +399,7 @@ noinstr void regs_emulate_call(struct pt_regs *regs, unsigned long ret, unsigned
noinstr void regs_emulate_ret(struct pt_regs *regs, unsigned long ip)
{
struct fred_shstk_entry_frame *ssef;
+ struct kernel_event_frame *frame;
regs->ip = ip;
@@ -379,10 +408,16 @@ noinstr void regs_emulate_ret(struct pt_regs *regs, unsigned long ip)
WARN_ON_ONCE(user_mode(regs));
- ssef = container_of(regs, struct kernel_event_frame, regs)->ssef;
+ frame = container_of(regs, struct kernel_event_frame, regs);
+
+ ssef = frame->ssef;
if (!ssef)
return;
+ /* A RET emulation for !INT3 events are ignored. */
+ if (WARN_ON_ONCE(frame->context != FRED_ENTRY))
+ return;
+
/*
* Return target should point to the old SP on top of the shadow
* stack that was popped from the regular stack.
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 13/27] x86/cet: Introduce regs_set_return_trampoline() for rethook trampoline
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (11 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 12/27] x86/cet: Make regs_set_return_ip() helpers context aware K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 14/27] x86/ftrace,livepatch: Use CET helpers for ftrace regs->ip and trampoline redirection K Prateek Nayak
` (14 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
Rethooks hijack the function return to jump to a return trampoline and
then to the actual caller. Rethooks can be added from three contexts:
caller
traced function
int3
asm_fred_entrypoint_kernel
exec_int3()
rethook_hook()
caller
call traced_function
call ftrace_caller
call ftrace_handlers
rethook_hook()
caller
call traced_function
jmp optprobe_template_entry
call probe_handlers
rethook_hook()
In each case, the return trampoline frame needs to be handled distinctly
relative to the frame where pt_regs are created and SSP is stashed.
Provide a regs_set_return_trampoline() that will be used in subsequent
commits to hijacks the shadow stack entry of return from traced function
correctly using the context saved in the entry metadata.
The trampolines will use a retpoline to insert a shadow stack slot
corresponding to correct return address and return to the caller
correctly.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/include/asm/insn-eval.h | 5 +++
arch/x86/kernel/cet.c | 77 ++++++++++++++++++++++++++++++++
2 files changed, 82 insertions(+)
diff --git a/arch/x86/include/asm/insn-eval.h b/arch/x86/include/asm/insn-eval.h
index 75d40a399ace..2cc5562c7d29 100644
--- a/arch/x86/include/asm/insn-eval.h
+++ b/arch/x86/include/asm/insn-eval.h
@@ -87,6 +87,7 @@ static inline void insn_assign_reg(unsigned long *reg, u64 val, int bytes)
void regs_set_return_ip(struct pt_regs *regs, unsigned long ip);
void regs_emulate_call(struct pt_regs *regs, unsigned long ret, unsigned long func);
void regs_emulate_ret(struct pt_regs *regs, unsigned long ret_ip);
+void regs_set_ret_trampoline(struct pt_regs *regs, unsigned long ret);
#else /* !CONFIG_X86_CET */
@@ -110,6 +111,10 @@ static inline void regs_emulate_ret(struct pt_regs *regs, unsigned long ret_ip)
regs_set_return_ip(regs, ret_ip);
}
+static inline void regs_set_ret_trampoline(struct pt_regs *regs, unsigned long ret)
+{
+}
+
#endif /* CONFIG_X86_CET */
#endif /* _ASM_X86_INSN_EVAL_H */
diff --git a/arch/x86/kernel/cet.c b/arch/x86/kernel/cet.c
index fb80c841bbfb..da80c6822242 100644
--- a/arch/x86/kernel/cet.c
+++ b/arch/x86/kernel/cet.c
@@ -433,3 +433,80 @@ noinstr void regs_emulate_ret(struct pt_regs *regs, unsigned long ip)
*/
wrss(ip, &ssef->ssef_lip);
}
+
+/*
+ * Hijack the return to jump to @ret. This is called from the int3
+ * handler and a spare frame is available. Use it to stuff the return
+ * trampoline between the actual return and fred_kernel_frame such that
+ * return from caller is gouted to @ret.
+ *
+ * Caller has already pointed the top of regular stack to @ret.
+ */
+noinstr void regs_set_ret_trampoline(struct pt_regs *regs, unsigned long ret)
+{
+ struct fred_shstk_entry_frame *ssef;
+ struct kernel_event_frame *frame;
+ unsigned int offset = 0;
+
+ if (!cpu_feature_enabled(X86_FEATURE_KERN_SHSTK))
+ return;
+
+ WARN_ON_ONCE(user_mode(regs));
+
+ frame = container_of(regs, struct kernel_event_frame, regs);
+
+ ssef = frame->ssef;
+ if (!ssef)
+ return;
+
+ switch (frame->context) {
+ case FRED_ENTRY:
+ /*
+ * Re-direct the ret below the FRED frame to the new return
+ * address such that the traced function's RET will jump to
+ * the trampoline.
+ */
+ wrss(ret, (u64 *)ssef->ssef_ssp);
+ break;
+ case FTRACE_CALLER:
+ /*
+ * The stack at ftrace_.*caller is:
+ *
+ * caller_function
+ * call traced_function
+ * call ftrace_caller
+ * frame->ssp = rdsspq();
+ *
+ * To redirect return of traced traced_function, the
+ * shadow stack entry below the frame->ssp should be
+ * modified.
+ */
+ offset = 1;
+ fallthrough;
+ case OPTPORBE_TRAMPOLINE:
+ /*
+ * Optprobes are eecuted from a jmp to trampoline:
+ *
+ * caller_function
+ * call traced_function
+ * jmp optprobe_template_entry
+ * frame->ssp = rdsspq();
+ *
+ * In this case, the return from traced_function is at
+ * the top of shadow stack at frame->ssp.
+ */
+ wrss(ret, frame->ssp + offset);
+ break;
+ case RETURN_TRAMPOLINE:
+ /*
+ * Trampolines should only be set at fentry. For
+ * chaining tampoline calls, use regs_set_return_ip().
+ */
+ WARN_ONCE(1, "Setting trampoline from return trampoline!\n");
+ break;
+ default:
+ WARN_ONCE(1, "Unknown calling context %d! Expect #CP\n",
+ frame->context);
+ break;
+ }
+}
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 14/27] x86/ftrace,livepatch: Use CET helpers for ftrace regs->ip and trampoline redirection
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (12 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 13/27] x86/cet: Introduce regs_set_return_trampoline() for rethook trampoline K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 15/27] x86/rethook: Make the trampoline insert and return shadow stack aware K Prateek Nayak
` (13 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
Ftrace core uses ftrace_regs_set_instruction_pointer() to redirect
regs->ip both from ftrace_caller and from ftrace_return_to_handler
return trampoline. Use regs_set_return_ip() to redirect function
execution while correcting the shadow stack.
Livepatch too uses ftrace_regs_set_instruction_pointer() to redirect the
execution to the livepatched function. As a consequence, using CET
helper for the regs->ip redirection also enables livepatching.
Use regs_set_ret_trampoline() to insert the return_to_handler
trampoline.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/include/asm/ftrace.h | 7 +++++--
arch/x86/kernel/ftrace.c | 20 ++++++++++++++++++--
kernel/trace/fgraph.c | 1 +
3 files changed, 24 insertions(+), 4 deletions(-)
diff --git a/arch/x86/include/asm/ftrace.h b/arch/x86/include/asm/ftrace.h
index c56e1e63b893..de4f71566a36 100644
--- a/arch/x86/include/asm/ftrace.h
+++ b/arch/x86/include/asm/ftrace.h
@@ -68,9 +68,12 @@ arch_ftrace_get_regs(struct ftrace_regs *fregs)
(_regs)->flags = 0; \
} while (0)
-#define ftrace_regs_set_instruction_pointer(fregs, _ip) \
- do { arch_ftrace_regs(fregs)->regs.ip = (_ip); } while (0)
+void ftrace_regs_set_instruction_pointer(struct ftrace_regs *fregs,
+ unsigned long ip);
+
+#define ftrace_regs_set_instruction_pointer \
+ ftrace_regs_set_instruction_pointer
static __always_inline unsigned long
ftrace_regs_get_return_address(struct ftrace_regs *fregs)
diff --git a/arch/x86/kernel/ftrace.c b/arch/x86/kernel/ftrace.c
index 17d6edfcb7e0..245deb44075f 100644
--- a/arch/x86/kernel/ftrace.c
+++ b/arch/x86/kernel/ftrace.c
@@ -651,11 +651,16 @@ void prepare_ftrace_return(unsigned long ip, unsigned long *parent,
if (unlikely(skip_ftrace_return()))
return;
+ /*
+ * This is only used for !CONFIG_HAVE_DYNAMIC_FTRACE_WITH_ARGS
+ * (implying !X86_64) and does not need shadow stack handling.
+ */
if (!function_graph_enter(*parent, ip, frame_pointer, parent))
*parent = return_hooker;
}
#ifdef CONFIG_HAVE_DYNAMIC_FTRACE_WITH_ARGS
+
void ftrace_graph_func(unsigned long ip, unsigned long parent_ip,
struct ftrace_ops *op, struct ftrace_regs *fregs)
{
@@ -668,9 +673,20 @@ void ftrace_graph_func(unsigned long ip, unsigned long parent_ip,
return;
- if (!function_graph_enter_regs(*parent, ip, 0, parent, fregs))
+ if (!function_graph_enter_regs(*parent, ip, 0, parent, fregs)) {
+ regs_set_ret_trampoline(regs, return_hooker);
*parent = return_hooker;
+ }
}
-#endif
+
+void ftrace_regs_set_instruction_pointer(struct ftrace_regs *fregs,
+ unsigned long ip)
+{
+ struct pt_regs *regs = &arch_ftrace_regs(fregs)->regs;
+
+ regs_set_return_ip(regs, ip);
+}
+
+#endif /* CONFIG_HAVE_DYNAMIC_FTRACE_WITH_ARGS */
#endif /* CONFIG_FUNCTION_GRAPH_TRACER */
diff --git a/kernel/trace/fgraph.c b/kernel/trace/fgraph.c
index ed455b53513b..2ec8140e5c33 100644
--- a/kernel/trace/fgraph.c
+++ b/kernel/trace/fgraph.c
@@ -822,6 +822,7 @@ __ftrace_return_to_handler(struct ftrace_regs *fregs, unsigned long frame_pointe
ftrace_graph_stop();
WARN_ON(1);
/* Might as well panic. What else to do? */
+ ftrace_regs_set_instruction_pointer(fregs, (unsigned long)panic);
return (unsigned long)panic;
}
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 15/27] x86/rethook: Make the trampoline insert and return shadow stack aware
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (13 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 14/27] x86/ftrace,livepatch: Use CET helpers for ftrace regs->ip and trampoline redirection K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 16/27] x86/error_inject: Use CET helpers to insert just_return_func trampoline K Prateek Nayak
` (12 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
Use the CET helper regs_set_ret_trampoline() to insert the rethook
trampoline and regs_set_return_ip() to correct the return address to the
caller from the return trampoline's handler.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/kernel/rethook.c | 8 +++++++-
1 file changed, 7 insertions(+), 1 deletion(-)
diff --git a/arch/x86/kernel/rethook.c b/arch/x86/kernel/rethook.c
index 974ef400b1b3..a5f92c3feedd 100644
--- a/arch/x86/kernel/rethook.c
+++ b/arch/x86/kernel/rethook.c
@@ -145,17 +145,23 @@ void arch_rethook_fixup_return(struct pt_regs *regs,
/* Replace fake return address with real one. */
*frame_pointer = correct_ret_addr;
+ regs_set_return_ip(regs, correct_ret_addr);
}
NOKPROBE_SYMBOL(arch_rethook_fixup_return);
void arch_rethook_prepare(struct rethook_node *rh, struct pt_regs *regs, bool mcount)
{
+ unsigned long ip = (unsigned long)arch_rethook_trampoline;
unsigned long *stack = (unsigned long *)regs->sp;
rh->ret_addr = stack[0];
rh->frame = regs->sp;
/* Replace the return addr with trampoline addr */
- stack[0] = (unsigned long) arch_rethook_trampoline;
+ stack[0] = ip;
+
+ /* First return trampoline; Override shadow stack. */
+ if (rh->ret_addr != ip)
+ regs_set_ret_trampoline(regs, ip);
}
NOKPROBE_SYMBOL(arch_rethook_prepare);
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 16/27] x86/error_inject: Use CET helpers to insert just_return_func trampoline
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (14 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 15/27] x86/rethook: Make the trampoline insert and return shadow stack aware K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 17/27] x86/kprobes: Use CET helpers in kprobe core to modify regs->ip K Prateek Nayak
` (11 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
Use regs_set_return_ip() to insert the retun to just_return_func. Unlike
a return trampoline, the just_return_func hijacks the return from
ftrace_regs_caller / int3 breakpoint (much like the direct hump path
from ftrace_regs_caller) to jump to execute just_return_func which
directly returns to the caller's slot.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/lib/error-inject.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/arch/x86/lib/error-inject.c b/arch/x86/lib/error-inject.c
index 512a2538596f..f64469d350f2 100644
--- a/arch/x86/lib/error-inject.c
+++ b/arch/x86/lib/error-inject.c
@@ -20,6 +20,6 @@ asm(
void override_function_with_return(struct pt_regs *regs)
{
- regs->ip = (unsigned long)&just_return_func;
+ regs_set_return_ip(regs, (unsigned long)&just_return_func);
}
NOKPROBE_SYMBOL(override_function_with_return);
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 17/27] x86/kprobes: Use CET helpers in kprobe core to modify regs->ip
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (15 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 16/27] x86/error_inject: Use CET helpers to insert just_return_func trampoline K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 18/27] x86/bpf: Make BPF JIT aware of CET handling K Prateek Nayak
` (10 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
Use regs_set_return_ip() in kprobe core to that modifies regs->ip.
Open-coded kprobe_emulate_call_indirect() has been converted to use
int3_emulate_call() to the indirect call target.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/kernel/kprobes/core.c | 14 +++++++-------
arch/x86/kernel/kprobes/ftrace.c | 2 ++
arch/x86/kernel/kprobes/opt.c | 2 +-
3 files changed, 10 insertions(+), 8 deletions(-)
diff --git a/arch/x86/kernel/kprobes/core.c b/arch/x86/kernel/kprobes/core.c
index 133ff20caccd..a365bd6cb56c 100644
--- a/arch/x86/kernel/kprobes/core.c
+++ b/arch/x86/kernel/kprobes/core.c
@@ -498,7 +498,7 @@ static void kprobe_emulate_ifmodifiers(struct kprobe *p, struct pt_regs *regs)
regs->flags = int3_emulate_pop(regs);
break;
}
- regs->ip = regs->ip - INT3_INSN_SIZE + p->ainsn.size;
+ regs_set_return_ip(regs, regs->ip - INT3_INSN_SIZE + p->ainsn.size);
}
NOKPROBE_SYMBOL(kprobe_emulate_ifmodifiers);
@@ -593,9 +593,9 @@ static const int addrmode_regoffs[] = {
static void kprobe_emulate_call_indirect(struct kprobe *p, struct pt_regs *regs)
{
unsigned long offs = addrmode_regoffs[p->ainsn.indirect.reg];
+ unsigned long ret = regs->ip - INT3_INSN_SIZE + p->ainsn.size;
- int3_emulate_push(regs, regs->ip - INT3_INSN_SIZE + p->ainsn.size);
- int3_emulate_jmp(regs, regs_get_register(regs, offs));
+ int3_emulate_call(regs, ret, regs_get_register(regs, offs));
}
NOKPROBE_SYMBOL(kprobe_emulate_call_indirect);
@@ -872,7 +872,7 @@ static void setup_singlestep(struct kprobe *p, struct pt_regs *regs,
* nor set current_kprobe, because it doesn't use single
* stepping.
*/
- regs->ip = (unsigned long)p->ainsn.insn;
+ regs_set_return_ip(regs, (unsigned long)p->ainsn.insn);
return;
}
#endif
@@ -891,7 +891,7 @@ static void setup_singlestep(struct kprobe *p, struct pt_regs *regs,
/* Disable interrupt, and set ip register on trampoline */
regs->flags &= ~X86_EFLAGS_IF;
- regs->ip = (unsigned long)p->ainsn.insn;
+ regs_set_return_ip(regs, (unsigned long)p->ainsn.insn);
}
NOKPROBE_SYMBOL(setup_singlestep);
@@ -922,7 +922,7 @@ static void resume_singlestep(struct kprobe *p, struct pt_regs *regs,
/* Restore saved interrupt flag and ip register */
regs->flags |= kcb->kprobe_saved_flags;
/* Note that regs->ip is executed int3 so must be a step back */
- regs->ip += (orig_ip - copy_ip) - INT3_INSN_SIZE;
+ regs_set_return_ip(regs, regs->ip + (orig_ip - copy_ip) - INT3_INSN_SIZE);
}
NOKPROBE_SYMBOL(resume_singlestep);
@@ -1042,7 +1042,7 @@ int kprobe_fault_handler(struct pt_regs *regs, int trapnr)
* and allow the page fault handler to continue as a
* normal page fault.
*/
- regs->ip = (unsigned long)cur->addr;
+ regs_set_return_ip(regs, (unsigned long)cur->addr);
/*
* If the IF flag was set before the kprobe hit,
diff --git a/arch/x86/kernel/kprobes/ftrace.c b/arch/x86/kernel/kprobes/ftrace.c
index 2be55ec3f392..d28473960f0b 100644
--- a/arch/x86/kernel/kprobes/ftrace.c
+++ b/arch/x86/kernel/kprobes/ftrace.c
@@ -56,6 +56,8 @@ void kprobe_ftrace_handler(unsigned long ip, unsigned long parent_ip,
}
/* Recover IP address */
instruction_pointer_set(regs, orig_ip);
+ /* Recover the shadow stack too. */
+ regs_set_return_ip(regs, orig_ip);
}
/*
* If pre_handler returns !0, it changes regs->ip. We have to
diff --git a/arch/x86/kernel/kprobes/opt.c b/arch/x86/kernel/kprobes/opt.c
index 5694cf566022..b77663d22f97 100644
--- a/arch/x86/kernel/kprobes/opt.c
+++ b/arch/x86/kernel/kprobes/opt.c
@@ -566,7 +566,7 @@ int setup_detour_execution(struct kprobe *p, struct pt_regs *regs, int reenter)
/* This kprobe is really able to run optimized path. */
op = container_of(p, struct optimized_kprobe, kp);
/* Detour through copied instructions */
- regs->ip = (unsigned long)op->optinsn.insn + TMPL_END_IDX;
+ regs_set_return_ip(regs, (unsigned long)op->optinsn.insn + TMPL_END_IDX);
if (!reenter)
reset_current_kprobe();
return 1;
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 18/27] x86/bpf: Make BPF JIT aware of CET handling
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (16 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 17/27] x86/kprobes: Use CET helpers in kprobe core to modify regs->ip K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 19/27] x86/shstk: Remove profiling related dependencies for KERN_SHADOW_STACK K Prateek Nayak
` (9 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
The retpolies that BPF JIT uses are already aware of shadow stack
handling.
Emit a incsspq %ecx for the trampoline that return to parent directly
when a function return hook is active and BPF runs the function body as
part of the trampoline.
For the unwinding case, use incsspq %rcx again with %rcx set to
(unwinding depth + 1) when transferring the control back to a
caller in chain for do_exception callback. The "+ 1" is for the extra
frame that call to "bpf_exception_cb" adds.
Since unwinding and call to bpf_exception_cb is done from the bpf
core, use the 4th argument to pass the unwinding depth.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/net/bpf_jit_comp.c | 18 +++++++++++++++++-
kernel/bpf/helpers.c | 3 ++-
2 files changed, 19 insertions(+), 2 deletions(-)
diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c
index 6bca87457e87..9d6be7de7521 100644
--- a/arch/x86/net/bpf_jit_comp.c
+++ b/arch/x86/net/bpf_jit_comp.c
@@ -560,6 +560,12 @@ static void emit_prologue(u8 **pprog, u8 *ip, u32 stack_depth, bool ebpf_from_cb
}
/* Exception callback receives FP as third parameter */
if (is_exception_cb) {
+ /*
+ * The number of slots to unwind to reach the
+ * return address is in the fourth parameter.
+ */
+ if (cpu_feature_enabled(X86_FEATURE_KERN_SHSTK))
+ EMIT5(0xF3, 0x48, 0x0F, 0xAE, 0xE9); /* incsspq rcx */
EMIT3(0x48, 0x89, 0xF4); /* mov rsp, rsi */
EMIT3(0x48, 0x89, 0xD5); /* mov rbp, rdx */
/* The main frame must have exception_boundary as true, so we
@@ -1530,7 +1536,7 @@ bool ex_handler_bpf(const struct exception_table_entry *x, struct pt_regs *regs)
/* jump over faulting load and clear dest register */
if (reg != DONT_CLEAR)
*(unsigned long *)((void *)regs + reg) = 0;
- regs->ip += insn_len;
+ regs_set_return_ip(regs, regs->ip + insn_len);
return true;
}
@@ -3756,6 +3762,16 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_im
if (flags & BPF_TRAMP_F_SKIP_FRAME) {
/* skip our return address and return to parent */
EMIT4(0x48, 0x83, 0xC4, 8); /* add rsp, 8 */
+
+ /*
+ * Drop the same return address from the shadow stack. The
+ * traced function is returning here, so every caller-saved
+ * register except RAX is dead.
+ */
+ if (cpu_feature_enabled(X86_FEATURE_KERN_SHSTK)) {
+ EMIT1_off32(0xB9, 1); /* mov ecx, 1 */
+ EMIT5(0xF3, 0x48, 0x0F, 0xAE, 0xE9); /* incsspq rcx */
+ }
}
emit_return(&prog, image + (prog - (u8 *)rw_image));
/* Make sure the trampoline generation logic doesn't overflow */
diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c
index 712dca5a2c5b..4d1cdd507563 100644
--- a/kernel/bpf/helpers.c
+++ b/kernel/bpf/helpers.c
@@ -3402,7 +3402,8 @@ __bpf_kfunc void bpf_throw(u64 cookie)
* architectures cannot recover sp while unwinding, so fall back to bp.
*/
kasan_unpoison_task_stack_below((void *)(long)(ctx.sp ?: ctx.bp));
- ctx.aux->bpf_exception_cb(cookie, ctx.sp + ctx.aux->stack_arg_sp_adjust, ctx.bp, 0, 0);
+ ctx.aux->bpf_exception_cb(cookie, ctx.sp + ctx.aux->stack_arg_sp_adjust,
+ ctx.bp, ctx.cnt + 1, 0);
WARN(1, "A call to BPF exception callback should never return\n");
}
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 19/27] x86/shstk: Remove profiling related dependencies for KERN_SHADOW_STACK
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (17 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 18/27] x86/bpf: Make BPF JIT aware of CET handling K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 20/27] x86/shstk: Disable kenrel shadow stack when CPU is offlined K Prateek Nayak
` (8 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
Ftrace, optprobes, kprobes, rethooks, livepatch (ftrace direct call),
error injection, and BPF JIT have now been adjusted to handle shadow
stacks for control-flow changes.
Remove the config dependencies to allow building
CONFIG_KERN_SHADOW_STACK with the above configs enabled.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/Kconfig | 28 ----------------------------
1 file changed, 28 deletions(-)
diff --git a/arch/x86/Kconfig b/arch/x86/Kconfig
index 559b9bc95c38..21f2b41043f4 100644
--- a/arch/x86/Kconfig
+++ b/arch/x86/Kconfig
@@ -1907,34 +1907,6 @@ config X86_KERN_SHADOW_STACK
depends on VMAP_STACK
depends on AS_WRUSS
select X86_CET
- # Replaces return addresses on the stack with return_to_handler,
- # and return_to_handler itself returns with a retpoline-style
- # "call; mov %rdi,(%rsp); ret".
- depends on !FUNCTION_GRAPH_TRACER
- # kprobe_emulate_call(), kprobe_emulate_ret() and
- # kprobe_emulate_call_indirect() emulate CALL and RET by moving
- # the return address on the regular stack only. KRETPROBES and
- # OPTPROBES hang off this symbol as well.
- depends on !KPROBES
- # arch_rethook_trampoline() is a return address hijack: the
- # probed function RETs to the trampoline instead of its caller.
- # FPROBE selects RETHOOK.
- depends on !RETHOOK
- depends on !FPROBE
- # klp_ftrace_handler() redirects execution by changing the
- # ftrace_regs IP. ftrace_regs_caller writes that IP into the
- # return slot and RETs to it, but the shadow stack still holds
- # the original address.
- depends on !LIVEPATCH
- # override_function_with_return() points regs->ip at
- # just_return_func, a bare RET that pops the probed function's
- # return address without the function's own RET ever running.
- depends on !FUNCTION_ERROR_INJECTION
- # BPF trampolines with BPF_TRAMP_F_SKIP_FRAME do "add $8,%rsp; ret"
- # to return to the grandparent. bpf_throw() unwinds BPF frames by
- # walking the stack and resuming at the exception callback with
- # the unwound RSP, skipping the intervening RETs.
- depends on !BPF_JIT
# relocate_kernel() switches CR3 and CR4 with a shadow stack live
# and uses "pushq $0 ... ret" as the handoff into purgatory. It
# needs S_CET.SH_STK_EN cleared first, which nothing does yet.
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 20/27] x86/shstk: Disable kenrel shadow stack when CPU is offlined
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (18 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 19/27] x86/shstk: Remove profiling related dependencies for KERN_SHADOW_STACK K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 21/27] x86/shstsk: Allow suspend-resume and hibernation with kernel shadow stack K Prateek Nayak
` (7 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
Once the CPU is marked dead, disable kernel shadow stacks just before
the play_dead() noreturn function.
A subsequent online will setup the shadow stack again from
start_secondary. This prepares the hotplug path for subsequent suspend
resume / hibernation handling.
disable_kernel_shstk() is proactively made to push a restore token on
top of the shadow stack and return the pointer just below to allow for
error handling on the hibernation restore path if the switching to saved
image fails.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/include/asm/cpu.h | 40 ++++++++++++++++++++++++++++++++++++++
arch/x86/kernel/smpboot.c | 1 +
2 files changed, 41 insertions(+)
diff --git a/arch/x86/include/asm/cpu.h b/arch/x86/include/asm/cpu.h
index 5f2e5b150b61..e9b0907b1a2b 100644
--- a/arch/x86/include/asm/cpu.h
+++ b/arch/x86/include/asm/cpu.h
@@ -79,6 +79,9 @@ extern void prep_kernel_shadow_stack(struct task_struct *tsk,
*/
static __always_inline void enable_kernel_shstk(unsigned long shstk_top)
{
+ if (!cpu_feature_enabled(X86_FEATURE_KERN_SHSTK))
+ return;
+
asm volatile ("rdmsr\n"
"orl %1, %%eax\n"
"wrmsr\n"
@@ -92,6 +95,38 @@ static __always_inline void enable_kernel_shstk(unsigned long shstk_top)
: "eax", "edx", "cc", "memory");
}
+/*
+ * This function should always be inlined. disable_kernel_shstk()
+ * returns the token to shstk_top that can be supplied later to
+ * enable_kernel_shstk() for error handling such that shadow stack
+ * can be re-enabled in the same function. Used for hotplug and
+ * and suspend-resume / hibernation.
+ */
+static __always_inline unsigned long disable_kernel_shstk(void)
+{
+ unsigned long ssp = 0, tok;
+
+ if (!cpu_feature_enabled(X86_FEATURE_KERN_SHSTK))
+ return ssp;
+
+ asm volatile ("rdsspq %0\n"
+ "test %0, %0\n"
+ "jz 1f\n"
+ "lea 1(%0), %1\n"
+ "wrssq %1, -8(%0)\n"
+ "rdmsr\n"
+ "andl %3, %%eax\n"
+ "wrmsr\n"
+ "1:"
+ : "+r" (ssp),
+ "=&r" (tok)
+ : "c" (MSR_IA32_S_CET),
+ "i" (~(u32)(CET_SHSTK_EN | CET_WRSS_EN))
+ : "eax", "edx", "cc", "memory");
+
+ return ssp;
+}
+
/*
* Setup the shadow stack for this CPU.
*
@@ -121,6 +156,11 @@ static __always_inline void cpu_setup_kernel_shstk(bool boot_cpu)
#else /* !CONFIG_X86_KERN_SHADOW_STACK */
+static inline void enable_kernel_shstk(unsigned long shstk_top) { }
+static inline unsigned long disable_kernel_shstk(void)
+{
+ return 0;
+}
static inline void cpu_setup_kernel_shstk(bool boot_cpu) { }
#endif /* CONFIG_X86_KERN_SHADOW_STACK */
diff --git a/arch/x86/kernel/smpboot.c b/arch/x86/kernel/smpboot.c
index 6ff2730a39c0..afd7c6740ed8 100644
--- a/arch/x86/kernel/smpboot.c
+++ b/arch/x86/kernel/smpboot.c
@@ -1510,6 +1510,7 @@ void __noreturn native_play_dead(void)
play_dead_common();
tboot_shutdown(TB_SHUTDOWN_WFS);
+ disable_kernel_shstk();
/* Below returns only on error. */
cpuidle_play_dead();
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 21/27] x86/shstsk: Allow suspend-resume and hibernation with kernel shadow stack
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (19 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 20/27] x86/shstk: Disable kenrel shadow stack when CPU is offlined K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 22/27] x86/shstk: Save and restore shadow stack pointer during kexec K Prateek Nayak
` (6 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
Save and restore the shadow stack pointers from the CPUs driving the
suspend-resume / hibernation while disabling kernel shadow stack just
before the system is suspended.
Since APs are taken down, they would have disabled shadow stack before
hitting the idle routine and only the BSP (CPU doing the final bits of
suspend-resume) needs to cache its SSP with restore token, disable
kernel shadow stack and execute the suspend routine.
The caches SSP is restored on resume such that it finds the matching ret
on the way out.
For hibernation, the CPU restoring the image disables shadow stacks, and
the restored kernel then enables and restores the SSP it had cached
before the hibernation.
Tested with:
rtcwake -m mem -s 20
rtcwake -m freeze -s 30
rtcwake -m disk -s 100
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/Kconfig | 7 ----
arch/x86/include/asm/nospec-branch.h | 55 ++++++++++++++++++++++++++++
arch/x86/include/asm/suspend.h | 2 +
arch/x86/kernel/acpi/wakeup_64.S | 6 +++
arch/x86/power/hibernate.c | 2 +
arch/x86/power/hibernate_32.c | 16 +++++---
arch/x86/power/hibernate_asm_64.S | 7 ++++
7 files changed, 83 insertions(+), 12 deletions(-)
diff --git a/arch/x86/Kconfig b/arch/x86/Kconfig
index 21f2b41043f4..4f5097fdd365 100644
--- a/arch/x86/Kconfig
+++ b/arch/x86/Kconfig
@@ -1911,13 +1911,6 @@ config X86_KERN_SHADOW_STACK
# and uses "pushq $0 ... ret" as the handoff into purgatory. It
# needs S_CET.SH_STK_EN cleared first, which nothing does yet.
depends on !KEXEC_CORE
- # restore_registers() RETs on a stack reloaded from the image
- # with S_CET, the PLx/FRED_SSPx MSRs and SSP itself never saved or
- # restored. Same problem for do_suspend_lowlevel()/wakeup_long64(),
- # which resume with "jmp *%rax" into the middle of the function
- # and then RET.
- depends on !HIBERNATION
- depends on !SUSPEND
# __efi64_thunk() drops into 32-bit firmware with LRETQ and comes
# back with LRET. Far returns are shadow stack checked and expect
# a far CALL frame that was never pushed.
diff --git a/arch/x86/include/asm/nospec-branch.h b/arch/x86/include/asm/nospec-branch.h
index 0872dceb3819..ff9449921106 100644
--- a/arch/x86/include/asm/nospec-branch.h
+++ b/arch/x86/include/asm/nospec-branch.h
@@ -417,6 +417,61 @@
#define CLEAR_BRANCH_HISTORY_VMEXIT
#endif
+#ifdef CONFIG_X86_KERN_SHADOW_STACK
+
+.macro SUSPEND_KERNEL_SHSTK ssp_offset cet_offset
+ xorl %eax, %eax
+ rdsspq %rax
+ movq %rax, \ssp_offset(%rip)
+ testq %rax, %rax
+ jz .Lsusp_no_shstk\@
+
+ /* Write the restore token = saved_ssp | MODE64 */
+ leaq 1(%rax), %rcx
+ wrssq %rcx, -8(%rax)
+
+ /* Disable Shadow Stack */
+ movl $MSR_IA32_S_CET, %ecx
+ rdmsr
+ movl %eax, \cet_offset(%rip)
+ movl %edx, \cet_offset+4(%rip)
+ andl $~(CET_SHSTK_EN | CET_WRSS_EN), %eax
+ wrmsr
+.Lsusp_no_shstk\@:
+.endm
+
+/*
+ * Call at .Lresume_point after CR4/CR3/CR0 and the GPRs are restored,
+ * before jmp restore_processor_state. Clobbers rax, rcx, rdx and flags.
+ */
+.macro RESUME_KERNEL_SHSTK ssp_offset cet_offset
+ cmpq $0, \ssp_offset(%rip)
+ je .Lres_no_shstk\@
+
+ movl $MSR_IA32_S_CET, %ecx
+ movl \cet_offset(%rip), %eax
+ movl \cet_offset+4(%rip), %edx
+ wrmsr
+
+ movq \ssp_offset(%rip), %rax
+
+ /* Consume and drop the token. */
+ rstorssp -8(%rax)
+ movl $1, %ecx
+ incsspq %rcx
+.Lres_no_shstk\@:
+.endm
+
+#else /* !CONFIG_X86_KERN_SHADOW_STACK */
+
+.macro SUSPEND_KERNEL_SHSTK ssp_offset cet_offset
+.endm
+.macro RESUME_KERNEL_SHSTK ssp_offset cet_offset
+.endm
+
+#endif /* CONFIG_X86_KERN_SHADOW_STACK */
+
+
#else /* __ASSEMBLER__ */
#define ITS_THUNK_SIZE 64
diff --git a/arch/x86/include/asm/suspend.h b/arch/x86/include/asm/suspend.h
index a892494ca5e4..7ea62a6624a0 100644
--- a/arch/x86/include/asm/suspend.h
+++ b/arch/x86/include/asm/suspend.h
@@ -9,6 +9,8 @@ extern unsigned long jump_address_phys;
extern unsigned long restore_cr3 __visible;
extern unsigned long temp_pgt __visible;
extern unsigned long relocated_restore_code __visible;
+extern unsigned long restore_ssp __visible;
+extern unsigned long restore_s_cet __visible;
extern int relocate_restore_code(void);
/* Defined in hibernate_asm_32/64.S */
extern asmlinkage __visible int restore_image(void);
diff --git a/arch/x86/kernel/acpi/wakeup_64.S b/arch/x86/kernel/acpi/wakeup_64.S
index 04f561f75e99..dc4ba38c4e40 100644
--- a/arch/x86/kernel/acpi/wakeup_64.S
+++ b/arch/x86/kernel/acpi/wakeup_64.S
@@ -79,6 +79,8 @@ SYM_FUNC_START(do_suspend_lowlevel)
movq %rdi, saved_rdi(%rip)
movq %rsi, saved_rsi(%rip)
+ SUSPEND_KERNEL_SHSTK saved_ssp, saved_s_cet
+
addq $8, %rsp
movl $3, %edi
xorl %eax, %eax
@@ -126,6 +128,8 @@ SYM_FUNC_START(do_suspend_lowlevel)
call kasan_unpoison_task_stack_below
#endif
+ RESUME_KERNEL_SHSTK saved_ssp, saved_s_cet
+
xorl %eax, %eax
addq $8, %rsp
FRAME_END
@@ -141,5 +145,7 @@ saved_rbx: .quad 0
saved_rip: .quad 0
saved_rsp: .quad 0
+saved_ssp: .quad 0
+saved_s_cet: .quad 0
SYM_DATA(saved_magic, .quad 0)
diff --git a/arch/x86/power/hibernate.c b/arch/x86/power/hibernate.c
index a2294c1649f6..940f8c6bfebc 100644
--- a/arch/x86/power/hibernate.c
+++ b/arch/x86/power/hibernate.c
@@ -39,6 +39,8 @@ unsigned long jump_address_phys;
unsigned long restore_cr3 __visible;
unsigned long temp_pgt __visible;
unsigned long relocated_restore_code __visible;
+unsigned long restore_ssp __visible;
+unsigned long restore_s_cet __visible;
/**
* pfn_is_nosave - check if given pfn is in the 'nosave' section
diff --git a/arch/x86/power/hibernate_32.c b/arch/x86/power/hibernate_32.c
index 223d5bca29b8..0b5498585c25 100644
--- a/arch/x86/power/hibernate_32.c
+++ b/arch/x86/power/hibernate_32.c
@@ -170,29 +170,35 @@ static int set_up_temporary_text_mapping(pgd_t *pgd_base)
asmlinkage int swsusp_arch_resume(void)
{
+ unsigned long ssp = disable_kernel_shstk();
int error;
resume_pg_dir = (pgd_t *)get_safe_page(GFP_ATOMIC);
- if (!resume_pg_dir)
- return -ENOMEM;
+ if (!resume_pg_dir) {
+ error = -ENOMEM;
+ goto out_error;
+ }
resume_init_first_level_page_table(resume_pg_dir);
error = set_up_temporary_text_mapping(resume_pg_dir);
if (error)
- return error;
+ goto out_error;
error = resume_physical_mapping_init(resume_pg_dir);
if (error)
- return error;
+ goto out_error;
temp_pgt = __pa(resume_pg_dir);
error = relocate_restore_code();
if (error)
- return error;
+ goto out_error;
/* We have got enough memory and from now on we cannot recover */
restore_image();
return 0;
+out_error:
+ disable_kernel_shstk(ssp);
+ return err;
}
diff --git a/arch/x86/power/hibernate_asm_64.S b/arch/x86/power/hibernate_asm_64.S
index c73be0a02a6c..e41dadac5045 100644
--- a/arch/x86/power/hibernate_asm_64.S
+++ b/arch/x86/power/hibernate_asm_64.S
@@ -62,6 +62,8 @@ SYM_FUNC_START(restore_registers)
/* Saved in save_processor_state. */
lgdt saved_context_gdt_desc(%rax)
+ RESUME_KERNEL_SHSTK restore_ssp, restore_s_cet
+
xorl %eax, %eax
/* tell the hibernation core that we've just restored the memory */
@@ -94,9 +96,14 @@ SYM_FUNC_START(swsusp_arch_suspend)
movq %cr3, %rax
movq %rax, restore_cr3(%rip)
+ SUSPEND_KERNEL_SHSTK restore_ssp, restore_s_cet
+
FRAME_BEGIN
call swsusp_save
FRAME_END
+
+ RESUME_KERNEL_SHSTK restore_ssp, restore_s_cet
+
RET
SYM_FUNC_END(swsusp_arch_suspend)
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 22/27] x86/shstk: Save and restore shadow stack pointer during kexec
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (20 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 21/27] x86/shstsk: Allow suspend-resume and hibernation with kernel shadow stack K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 23/27] x86/idt: Map MCE shadow stack and populate the INT_SPP table K Prateek Nayak
` (5 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
To support KEXEC and KEXEC_JUMP, save and restore shadow stack token on
either side of relocate_kernel_ptr(). On regual kexec path,
disable_kernel_shstk() from stop_this_cpu() will disable shadow stack on
APs after the APIC is turned off. KEXEC_JUMP would disable the shadow
stack from the offline callback.
restore_processor_state() populates the CR4 and FRED exceptions, RSPs
and SSPs on the way back - restore the shadow stack token on the way
back in machine_kexec() after the necessary FRED bits have been
initialized.
APs re-enable shadow stack when coming online in start_secondary.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/Kconfig | 4 ----
arch/x86/kernel/machine_kexec_64.c | 4 ++++
arch/x86/kernel/process.c | 1 +
3 files changed, 5 insertions(+), 4 deletions(-)
diff --git a/arch/x86/Kconfig b/arch/x86/Kconfig
index 4f5097fdd365..c101f7b23644 100644
--- a/arch/x86/Kconfig
+++ b/arch/x86/Kconfig
@@ -1907,10 +1907,6 @@ config X86_KERN_SHADOW_STACK
depends on VMAP_STACK
depends on AS_WRUSS
select X86_CET
- # relocate_kernel() switches CR3 and CR4 with a shadow stack live
- # and uses "pushq $0 ... ret" as the handoff into purgatory. It
- # needs S_CET.SH_STK_EN cleared first, which nothing does yet.
- depends on !KEXEC_CORE
# __efi64_thunk() drops into 32-bit firmware with LRETQ and comes
# back with LRET. Far returns are shadow stack checked and expect
# a far CALL frame that was never pushed.
diff --git a/arch/x86/kernel/machine_kexec_64.c b/arch/x86/kernel/machine_kexec_64.c
index c3f4a389992d..e18f7d292d62 100644
--- a/arch/x86/kernel/machine_kexec_64.c
+++ b/arch/x86/kernel/machine_kexec_64.c
@@ -386,6 +386,7 @@ void __nocfi machine_kexec(struct kimage *image)
unsigned long reloc_start = (unsigned long)__relocate_kernel_start;
relocate_kernel_fn *relocate_kernel_ptr;
unsigned int relocate_kernel_flags;
+ unsigned long shstk_token;
int save_ftrace_enabled;
void *control_page;
@@ -399,6 +400,8 @@ void __nocfi machine_kexec(struct kimage *image)
/* Interrupts aren't acceptable while we reboot */
local_irq_disable();
hw_breakpoint_disable();
+
+ shstk_token = disable_kernel_shstk();
cet_disable();
if (image->preserve_context) {
@@ -461,6 +464,7 @@ void __nocfi machine_kexec(struct kimage *image)
restore_processor_state();
#endif
+ enable_kernel_shstk(shstk_token);
__ftrace_enabled_restore(save_ftrace_enabled);
}
/*
diff --git a/arch/x86/kernel/process.c b/arch/x86/kernel/process.c
index 7b3a9f112451..357c815d4522 100644
--- a/arch/x86/kernel/process.c
+++ b/arch/x86/kernel/process.c
@@ -902,6 +902,7 @@ void __noreturn stop_this_cpu(void *dummy)
set_cpu_online(cpu, false);
disable_local_APIC();
mcheck_cpu_clear(c);
+ disable_kernel_shstk();
if (this_cpu_read(cache_state_incoherent))
wbinvd();
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 23/27] x86/idt: Map MCE shadow stack and populate the INT_SPP table
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (21 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 22/27] x86/shstk: Save and restore shadow stack pointer during kexec K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 24/27] x86/process: Initialize shadow stack for IDT systems K Prateek Nayak
` (4 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
In preparation for IDT handling of shadow stacks, allocate the MCE
shadow stack too and map it similar to other shadow stack areas on IDT
init path.
IDT systems need a supervisor token to mark shadow stack busy at the top
entry. Use the R/W estacks alias to populate the entry corresponding to
the linear address of the top slot.
IDT systems additionally require populating the INT_SSP table that maps
the shadow stacks to IST gates. Initialize the SSP table in
MSR_IA32_INT_SSP_TAB before enabling shadow stacks.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/include/asm/cpu.h | 2 ++
arch/x86/include/asm/cpu_entry_area.h | 2 ++
arch/x86/include/asm/traps.h | 1 +
arch/x86/kernel/idt.c | 30 +++++++++++++++++++++++++++
arch/x86/mm/cpu_entry_area.c | 27 ++++++++++++++++++++++++
5 files changed, 62 insertions(+)
diff --git a/arch/x86/include/asm/cpu.h b/arch/x86/include/asm/cpu.h
index e9b0907b1a2b..e8227cc1336b 100644
--- a/arch/x86/include/asm/cpu.h
+++ b/arch/x86/include/asm/cpu.h
@@ -9,6 +9,7 @@
#include <linux/percpu.h>
#include <asm/ibt.h>
+#include <asm/traps.h>
#include <asm/msr-index.h>
#include <asm/thread_info.h>
#include <asm/special_insns.h>
@@ -150,6 +151,7 @@ static __always_inline void cpu_setup_kernel_shstk(bool boot_cpu)
BUG_ON(!tsk->thread.kshstk_ssp);
shstk_top = (unsigned long)tsk->thread.kshstk_ssp;
+ load_ssp_table();
wrmsrq(MSR_IA32_FRED_SSP0, shstk_top);
enable_kernel_shstk(shstk_top);
}
diff --git a/arch/x86/include/asm/cpu_entry_area.h b/arch/x86/include/asm/cpu_entry_area.h
index 676feba17d27..014212159fe5 100644
--- a/arch/x86/include/asm/cpu_entry_area.h
+++ b/arch/x86/include/asm/cpu_entry_area.h
@@ -34,6 +34,7 @@
char DB_shadow_stack[EXCEPTION_SHADOW_STKSZ]; \
char DB_stack[EXCEPTION_STKSZ]; \
char MCE_stack_guard[guardsize]; \
+ char MCE_shadow_stack[EXCEPTION_SHADOW_STKSZ]; \
char MCE_stack[EXCEPTION_STKSZ]; \
char VC_stack_guard[guardsize]; \
char VC_stack[optional_stack_size]; \
@@ -145,6 +146,7 @@ DECLARE_PER_CPU(struct cpu_entry_area *, cpu_entry_area);
DECLARE_PER_CPU(struct cea_exception_stacks *, cea_exception_stacks);
extern void setup_cpu_entry_areas(void);
+extern void init_idt_shadows_stacks(unsigned int cpu);
extern void cea_set_pte(void *cea_vaddr, phys_addr_t pa, pgprot_t flags);
extern struct cpu_entry_area *get_cpu_entry_area(int cpu);
diff --git a/arch/x86/include/asm/traps.h b/arch/x86/include/asm/traps.h
index 3f24cc472ce9..0f99535fe31f 100644
--- a/arch/x86/include/asm/traps.h
+++ b/arch/x86/include/asm/traps.h
@@ -19,6 +19,7 @@ asmlinkage __visible noinstr struct pt_regs *vc_switch_off_ist(struct pt_regs *e
extern int ibt_selftest(void);
extern int ibt_selftest_noendbr(void);
+extern void load_ssp_table(void);
#ifdef CONFIG_X86_F00F_BUG
/* For handling the FOOF bug */
diff --git a/arch/x86/kernel/idt.c b/arch/x86/kernel/idt.c
index 90a22e24a9eb..85aaf841f813 100644
--- a/arch/x86/kernel/idt.c
+++ b/arch/x86/kernel/idt.c
@@ -180,10 +180,40 @@ static struct desc_ptr idt_descr __ro_after_init = {
.address = (unsigned long) idt_table,
};
+#define INT_SSP_TABLE_SIZE 8
+
+struct int_ssp_table {
+ unsigned long *int_ssp[INT_SSP_TABLE_SIZE];
+};
+
+static DEFINE_PER_CPU(struct int_ssp_table, ssp_table);
+
+#define load_int_ssp_table(_vec) \
+ do { \
+ unsigned long *__shstk = (unsigned long *)__this_cpu_shadow_top_va(_vec); \
+ table->int_ssp[IST_INDEX_ ##_vec + 1] = __shstk - 1; \
+ } while(0)
+
+void load_ssp_table(void)
+{
+ struct int_ssp_table *table = this_cpu_ptr(&ssp_table);
+
+ if (cpu_feature_enabled(X86_FEATURE_FRED))
+ return;
+
+ load_int_ssp_table(DB);
+ load_int_ssp_table(NMI);
+ load_int_ssp_table(DF);
+ load_int_ssp_table(MCE);
+
+ wrmsrq(MSR_IA32_INT_SSP_TAB, (u64)table->int_ssp);
+}
+
void load_current_idt(void)
{
lockdep_assert_irqs_disabled();
load_idt(&idt_descr);
+ init_idt_shadows_stacks(smp_processor_id());
}
#ifdef CONFIG_X86_F00F_BUG
diff --git a/arch/x86/mm/cpu_entry_area.c b/arch/x86/mm/cpu_entry_area.c
index 7c1f04e7651a..f182e2f82f12 100644
--- a/arch/x86/mm/cpu_entry_area.c
+++ b/arch/x86/mm/cpu_entry_area.c
@@ -167,6 +167,29 @@ static void __init percpu_setup_exception_stacks(unsigned int cpu)
cea_map_stack(DB, shadow_stack, PAGE_KERNEL_SHSTK);
cea_map_stack(NMI, shadow_stack, PAGE_KERNEL_SHSTK);
cea_map_stack(DF, shadow_stack, PAGE_KERNEL_SHSTK);
+ cea_map_stack(MCE, shadow_stack, PAGE_KERNEL_SHSTK);
+}
+
+#define shstk_get_top_slot(ptr, stack) \
+ (unsigned long *)((u8*)(ptr)->stack## _shadow_stack + \
+ EXCEPTION_SHADOW_STKSZ) - 1
+
+#define cea_init_shadow_stack(name) do { \
+ unsigned long *estacks_alias = shstk_get_top_slot(estacks, name); \
+ unsigned long *cae_alias = shstk_get_top_slot(&cea->estacks, name); \
+ *estacks_alias = (unsigned long)cae_alias; \
+ } while (0)
+
+void init_idt_shadows_stacks(unsigned int cpu)
+{
+ struct exception_stacks *estacks = per_cpu_ptr(&exception_stacks, cpu);
+ struct cpu_entry_area *cea = get_cpu_entry_area(cpu);
+
+ /* Map the per-CPU exception shadow stacks: */
+ cea_init_shadow_stack(DB);
+ cea_init_shadow_stack(NMI);
+ cea_init_shadow_stack(DF);
+ cea_init_shadow_stack(MCE);
}
#else
static void __init percpu_setup_exception_stacks(unsigned int cpu)
@@ -176,6 +199,10 @@ static void __init percpu_setup_exception_stacks(unsigned int cpu)
cea_map_percpu_pages(&cea->doublefault_stack,
&per_cpu(doublefault_stack, cpu), 1, PAGE_KERNEL);
}
+
+void init_idt_shadows_stacks(unsigned int cpu)
+{
+}
#endif
/* Setup the fixmap mappings only once per-processor */
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 24/27] x86/process: Initialize shadow stack for IDT systems
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (22 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 23/27] x86/idt: Map MCE shadow stack and populate the INT_SPP table K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 25/27] x86/entry: Prepare IDT entry for shadow stacks K Prateek Nayak
` (3 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
On IDT systems, the bottom of the stack should always have a supervisor
token that can be marked busy by the hardware. Populate the supervisor
token in the fist slot and, like FRED path, populate the first return
address and the restore token below.
Since SSP0 should point to the supervisor slot, set SSP0 to one slot
below task_shstk_top() that contains the supervisor token.
The SSP0 reset is no longer limited to FRED enabled systems. Use
MSR_IA32_PL0_SSP to reference the MSR instead of the FRED alias.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/include/asm/cpu.h | 4 +++-
arch/x86/include/asm/entry-common.h | 19 ++++++++++++++++++-
arch/x86/include/asm/fred.h | 7 -------
arch/x86/kernel/process.c | 17 +++++++++++++++--
4 files changed, 36 insertions(+), 11 deletions(-)
diff --git a/arch/x86/include/asm/cpu.h b/arch/x86/include/asm/cpu.h
index e8227cc1336b..8c91a3ee59d8 100644
--- a/arch/x86/include/asm/cpu.h
+++ b/arch/x86/include/asm/cpu.h
@@ -138,8 +138,10 @@ static __always_inline unsigned long disable_kernel_shstk(void)
static __always_inline void cpu_setup_kernel_shstk(bool boot_cpu)
{
struct task_struct *tsk = current;
+ u64 ssp0 = (u64)task_shstk_top(tsk) - sizeof(unsigned long);
unsigned long shstk_top;
+
if (!cpu_feature_enabled(X86_FEATURE_KERN_SHSTK))
return;
@@ -152,7 +154,7 @@ static __always_inline void cpu_setup_kernel_shstk(bool boot_cpu)
shstk_top = (unsigned long)tsk->thread.kshstk_ssp;
load_ssp_table();
- wrmsrq(MSR_IA32_FRED_SSP0, shstk_top);
+ wrmsrq(MSR_IA32_PL0_SSP, ssp0);
enable_kernel_shstk(shstk_top);
}
diff --git a/arch/x86/include/asm/entry-common.h b/arch/x86/include/asm/entry-common.h
index 470ac946afba..10960d8237c9 100644
--- a/arch/x86/include/asm/entry-common.h
+++ b/arch/x86/include/asm/entry-common.h
@@ -56,6 +56,23 @@ static inline void arch_exit_work(unsigned long ti_work)
switch_fpu_return();
}
+#ifdef CONFIG_X86_KERN_SHADOW_STACK
+static inline void update_ssp0(void)
+{
+ if (current->thread.kshstk_ssp) {
+ u64 top = (u64)task_shstk_top(current);
+
+ /* On IDT systems, restore past the token. */
+ if (!cpu_feature_enabled(X86_FEATURE_FRED))
+ top -= sizeof(unsigned long);
+
+ wrmsrns(MSR_IA32_PL0_SSP, top);
+ }
+}
+#else /* !CONFIG_X86_KERN_SHADOW_STACK */
+static inline void update_ssp0(void) { }
+#endif /* CONFIG_X86_KERN_SHADOW_STACK */
+
static inline void arch_exit_to_user_mode_prepare(struct pt_regs *regs,
unsigned long ti_work)
{
@@ -65,7 +82,7 @@ static inline void arch_exit_to_user_mode_prepare(struct pt_regs *regs,
arch_exit_work(ti_work);
fred_update_rsp0();
- fred_update_ssp0();
+ update_ssp0();
#ifdef CONFIG_COMPAT
/*
* Compat syscalls set TS_COMPAT. Make sure we clear it before
diff --git a/arch/x86/include/asm/fred.h b/arch/x86/include/asm/fred.h
index 57c7e78c787a..477b0b2605a7 100644
--- a/arch/x86/include/asm/fred.h
+++ b/arch/x86/include/asm/fred.h
@@ -105,13 +105,6 @@ static __always_inline void fred_update_rsp0(void)
__this_cpu_write(fred_rsp0, rsp0);
}
}
-static __always_inline void fred_update_ssp0(void)
-{
-#ifdef CONFIG_X86_KERN_SHADOW_STACK
- if (current->thread.kshstk_ssp)
- wrmsrns(MSR_IA32_FRED_SSP0, (u64)task_shstk_top(current));
-#endif
-}
#else /* CONFIG_X86_FRED */
static __always_inline unsigned long fred_event_data(struct pt_regs *regs) { return 0; }
static inline void cpu_init_fred_exceptions(void) { }
diff --git a/arch/x86/kernel/process.c b/arch/x86/kernel/process.c
index 357c815d4522..661932d894cb 100644
--- a/arch/x86/kernel/process.c
+++ b/arch/x86/kernel/process.c
@@ -206,8 +206,21 @@ void prep_kernel_shadow_stack(struct task_struct *tsk,
* Write the return address for the first RET: and point the task's
* kshstk_ssp to the top slot.
*/
- *ss_top_slot = (unsigned long)ret_addr;
- tsk->thread.kshstk_ssp = task_shstk_top(tsk) - sizeof(unsigned long);
+ if (cpu_feature_enabled(X86_FEATURE_FRED)) {
+ *ss_top_slot = (unsigned long)ret_addr;
+ tsk->thread.kshstk_ssp = task_shstk_top(tsk) - sizeof(unsigned long);
+
+ } else {
+ unsigned long *shstk_top = task_shstk_top(tsk);
+
+ /* Supervisor token for PL0_SSP */
+ *ss_top_slot = (unsigned long)(shstk_top - 1);
+
+ ss_top_slot -= 1;
+ /* Token for first return. */
+ *ss_top_slot = (unsigned long)ret_addr;
+ tsk->thread.kshstk_ssp = shstk_top - 2;
+ }
/*
* Back up one more frame and write the token for rstorssp when this
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 25/27] x86/entry: Prepare IDT entry for shadow stacks
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (23 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 24/27] x86/process: Initialize shadow stack for IDT systems K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 26/27] x86/syscall: Toggle shadow stack busy on entry and exit from syscall K Prateek Nayak
` (2 subsequent siblings)
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
Similar to FRED entry, IDT entry must populate a metadata frame around
the pt_regs. Unlike FRED entry point which clearly distinguishes entry
form kernel vs entry from user, IDT entry has a common entry point.
The POP_KERN_SHSTK_FRAME needs a consistent stack state to locate CS and
pop accordingly which makes the handling complicated. Always push two
slots - two blank ones for user entry and the correct FRED frame for
entry from kernel such that POP_KERN_SHSTK_FRAME can always see a
consistent state.
Once the CET helpers see a non-NULL shadow stack pointer, it can operate
on the shadow stack frames for kernel events.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/entry/calling.h | 85 ++++++++++++++++++++++++++++++++++
arch/x86/entry/entry_64.S | 24 ++++++++++
arch/x86/entry/entry_64_fred.S | 73 -----------------------------
3 files changed, 109 insertions(+), 73 deletions(-)
diff --git a/arch/x86/entry/calling.h b/arch/x86/entry/calling.h
index 77e2d920a640..402c08bac5b5 100644
--- a/arch/x86/entry/calling.h
+++ b/arch/x86/entry/calling.h
@@ -381,6 +381,91 @@ For 32-bit we have the following conventions - kernel is built with
wrgsbase \scratch_reg
.endm
+#ifdef CONFIG_X86_KERN_SHADOW_STACK
+
+/*
+ * A INT3 breakpoint can emulate a CALL which requires pushing the
+ * return frame below this FRED event. Allow the handlers to communicate
+ * if it emulated a CALL by setting a flag on the stack.
+ *
+ * FRED event pushes { SSP, LIP, CS } onto the shadow stack and SSP
+ * points to record three slots for top here and it should stay that
+ * way.
+ *
+ * CALL emulation will consume the SSP, push a return frame below, and
+ * set a flag on stack. If the flag is set, FRED_EXIT will add an
+ * shadow stack frame on top by doing an INTRA_FUNCTION_CALL and
+ * populate the top with a pointer to three slots below, thus recreating
+ * the correct FRED frame.
+ */
+.macro PUSH_KERN_SHSTK_FRAME
+ xor %eax, %eax
+ rdsspq %rax
+ pushq %rax
+ /*
+ * Frame metadata:
+ *
+ * [15:8] Context (FRED_EVENT)
+ * [ 7:0] fred_exit_work_flags
+ *
+ * Context data is used by CET helpers to interpret
+ * SSP frame. fred_exit_work_flags is used to fixup
+ * shadow stack for CALL emulation.
+ */
+ pushq $0x100
+.endm
+
+/* Clobbers RAX, RCX; Both will be restored later. */
+.macro POP_KERN_SHSTK_FRAME
+ popq %rax /* fred_exit_work_flags */
+
+ /* Only one action is supported currently. */
+ test %al, %al
+ jz .Lpop_shstk_done\@
+
+ /*
+ * CALL Emulation has overwritten the shadow-stack frame and
+ * SSP is lost. Point it back to 3 slots down where the real
+ * return has to go.
+ *
+ * Doing a CALL here will add a RSB which the next RET will
+ * mispredict on but all RETs after that are balanced.
+ */
+ ANNOTATE_INTRA_FUNCTION_CALL
+ call 1f
+ int3
+1:
+ /* Synthesize the corrct SSP to fix the FRED Frame. */
+ addq $8, %rsp
+ rdsspq %rax
+ leaq 24(%rax), %rcx
+ wrssq %rcx, (%rax)
+
+.Lpop_shstk_done\@:
+ popq %rax
+.endm
+
+.macro PUSH_USER_SHSTK_FRAME
+ subq $16, %rsp
+.endm
+
+.macro POP_USER_SHSTK_FRAME
+ addq $16, %rsp
+.endm
+
+#else /* !CONFIG_X86_KERN_SHADOW_STACK */
+
+.macro PUSH_KERN_SHSTK_FRAME
+.endm
+.macro POP_KERN_SHSTK_FRAME
+.endm
+.macro PUSH_USER_SHSTK_FRAME
+.endm
+.macro POP_USER_SHSTK_FRAME
+.endm
+
+#endif /* CONFIG_X86_KERN_SHADOW_STACK */
+
#else /* CONFIG_X86_64 */
# undef UNWIND_HINT_IRET_REGS
# define UNWIND_HINT_IRET_REGS
diff --git a/arch/x86/entry/entry_64.S b/arch/x86/entry/entry_64.S
index c255722cd66d..6ce8c523b2d6 100644
--- a/arch/x86/entry/entry_64.S
+++ b/arch/x86/entry/entry_64.S
@@ -296,6 +296,26 @@ SYM_CODE_START(xen_error_entry)
RET
SYM_CODE_END(xen_error_entry)
+.macro PUSH_IDT_SHSTK_FRAME
+ testb $3, CS(%rsp)
+ jnz .Lpush_from_usermode\@
+ PUSH_KERN_SHSTK_FRAME
+ jmp .Lpush_shstk_done\@
+.Lpush_from_usermode\@:
+ PUSH_USER_SHSTK_FRAME
+.Lpush_shstk_done\@:
+.endm
+
+.macro POP_IDT_SHSTK_FRAME
+ testb $3, CS+16(%rsp)
+ jnz .Lpop_from_usermode\@
+ POP_KERN_SHSTK_FRAME
+ jmp .Lpush_shstk_done\@
+.Lpop_from_usermode\@:
+ POP_USER_SHSTK_FRAME
+.Lpush_shstk_done\@:
+.endm
+
/**
* idtentry_body - Macro to emit code calling the C function
* @cfunc: C function to be called
@@ -324,10 +344,14 @@ SYM_CODE_END(xen_error_entry)
movq $-1, ORIG_RAX(%rsp) /* no syscall to restart */
.endif
+ PUSH_IDT_SHSTK_FRAME
+
/* For some configurations \cfunc ends up being a noreturn. */
ANNOTATE_REACHABLE
call \cfunc
+ POP_IDT_SHSTK_FRAME
+
jmp error_return
.endm
diff --git a/arch/x86/entry/entry_64_fred.S b/arch/x86/entry/entry_64_fred.S
index 284976114c70..2119d0da50b4 100644
--- a/arch/x86/entry/entry_64_fred.S
+++ b/arch/x86/entry/entry_64_fred.S
@@ -17,79 +17,6 @@
.code64
.section .noinstr.text, "ax"
-#ifdef CONFIG_X86_KERN_SHADOW_STACK
-
-/*
- * A INT3 breakpoint can emulate a CALL which requires pushing the
- * return frame below this FRED event. Allow the handlers to communicate
- * if it emulated a CALL by setting a flag on the stack.
- *
- * FRED event pushes { SSP, LIP, CS } onto the shadow stack and SSP
- * points to record three slots for top here and it should stay that
- * way.
- *
- * CALL emulation will consume the SSP, push a return frame below, and
- * set a flag on stack. If the flag is set, FRED_EXIT will add an
- * shadow stack frame on top by doing an INTRA_FUNCTION_CALL and
- * populate the top with a pointer to three slots below, thus recreating
- * the correct FRED frame.
- */
-.macro PUSH_KERN_SHSTK_FRAME
- xor %eax, %eax
- rdsspq %rax /* NOP if SHSTK is off. */
- pushq %rax
- /*
- * Frame metadata:
- *
- * [15:8] Context (FRED_EVENT)
- * [ 7:0] fred_exit_work_flags
- *
- * Context data is used by CET helpers to interpret
- * SSP frame. fred_exit_work_flags is used to fixup
- * shadow stack for CALL emulation.
- */
- pushq $0x100
-.endm
-
-/* Clobbers RAX, RCX; Both will be restored later. */
-.macro POP_KERN_SHSTK_FRAME
- popq %rax /* fred_exit_work_flags */
-
- /* Only one action is supported currently. */
- test %al, %al
- jz .Lpop_shstk_done\@
-
- /*
- * CALL Emulation has overwritten the shadow-stack frame and
- * SSP is lost. Point it back to 3 slots down where the real
- * return has to go.
- *
- * Doing a CALL here will add a RSB which the next RET will
- * mispredict on but all RETs after that are balanced.
- */
- ANNOTATE_INTRA_FUNCTION_CALL
- call 1f
- int3
-1:
- /* Synthesize the corrct SSP to fix the FRED Frame. */
- addq $8, %rsp
- rdsspq %rax
- leaq 24(%rax), %rcx
- wrssq %rcx, (%rax)
-
-.Lpop_shstk_done\@:
- popq %rax
-.endm
-
-#else /* !CONFIG_X86_KERN_SHADOW_STACK */
-
-.macro PUSH_KERN_SHSTK_FRAME
-.endm
-.macro POP_KERN_SHSTK_FRAME
-.endm
-
-#endif /* CONFIG_X86_KERN_SHADOW_STACK */
-
.macro FRED_ENTER ssp=0
UNWIND_HINT_END_OF_STACK
ANNOTATE_NOENDBR
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 26/27] x86/syscall: Toggle shadow stack busy on entry and exit from syscall
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (24 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 25/27] x86/entry: Prepare IDT entry for shadow stacks K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 27/27] x86/entry: Handle shadow stack on nested NMI K Prateek Nayak
2026-11-29 23:00 ` [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support Andrew Cooper
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
On IDT systems, a syscall to Ring-0 will set SSP to 0. Intel SDM for
"SYSENTER - Fast System Call" reads:
When shadow stacks are enabled at privilege level where SYSENTER
instruction is invoked, the SSP is saved to the IA32_PL3_SSP MSR.
If shadow stacks are enabled at privilege level 0, the SSP is
loaded with 0.
Before IRQs are enable, execute a setssbsy to load the SSP0 shadow stack
and clear the busy status before SYSRET to allow IST Gate 0 events from
userspace to mark it busy.
Kernel events at level 0 will not inspect the busy bit.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/entry/calling.h | 14 ++++++++++++++
arch/x86/entry/entry_64.S | 6 ++++++
arch/x86/entry/entry_64_compat.S | 10 ++++++++++
3 files changed, 30 insertions(+)
diff --git a/arch/x86/entry/calling.h b/arch/x86/entry/calling.h
index 402c08bac5b5..2d471ec9d8e8 100644
--- a/arch/x86/entry/calling.h
+++ b/arch/x86/entry/calling.h
@@ -453,6 +453,16 @@ For 32-bit we have the following conventions - kernel is built with
addq $16, %rsp
.endm
+.macro SET_SHSTK_BUSY
+ ALTERNATIVE "", "setssbsy", X86_FEATURE_KERN_SHSTK
+.endm
+
+.macro CLEAR_SHSTK_BUSY scratch_reg
+ ALTERNATIVE "", \
+ __stringify(rdsspq \scratch_reg; clrssbsy (\scratch_reg)), \
+ X86_FEATURE_KERN_SHSTK
+.endm
+
#else /* !CONFIG_X86_KERN_SHADOW_STACK */
.macro PUSH_KERN_SHSTK_FRAME
@@ -463,6 +473,10 @@ For 32-bit we have the following conventions - kernel is built with
.endm
.macro POP_USER_SHSTK_FRAME
.endm
+.macro SET_SHSTK_BUSY
+.endm
+.macro CLEAR_SHSTK_BUSY scratch_reg
+.endm
#endif /* CONFIG_X86_KERN_SHADOW_STACK */
diff --git a/arch/x86/entry/entry_64.S b/arch/x86/entry/entry_64.S
index 6ce8c523b2d6..53ea96470f15 100644
--- a/arch/x86/entry/entry_64.S
+++ b/arch/x86/entry/entry_64.S
@@ -109,6 +109,9 @@ SYM_INNER_LABEL(entry_SYSCALL_64_after_hwframe, SYM_L_GLOBAL)
PUSH_AND_CLEAR_REGS rax=$-ENOSYS
+ /* SYSCALL zeroed SSP; claim the task's supervisor token before any CALL. */
+ SET_SHSTK_BUSY
+
/* IRQs are off. */
movq %rsp, %rdi
/* Sign extend the lower 32bit as syscall numbers are treated as int */
@@ -156,6 +159,9 @@ syscall_return_via_sysret:
*/
STACKLEAK_ERASE_NOCLOBBER
+ /* SYSRET does not free the token; SSP is back on it here. */
+ CLEAR_SHSTK_BUSY scratch_reg=%rdi
+
SWITCH_TO_USER_CR3_STACK scratch_reg=%rdi
popq %rdi
diff --git a/arch/x86/entry/entry_64_compat.S b/arch/x86/entry/entry_64_compat.S
index a45e1125fc6c..59998d70c800 100644
--- a/arch/x86/entry/entry_64_compat.S
+++ b/arch/x86/entry/entry_64_compat.S
@@ -87,6 +87,9 @@ SYM_INNER_LABEL(entry_SYSENTER_compat_after_hwframe, SYM_L_GLOBAL)
PUSH_AND_CLEAR_REGS rax=$-ENOSYS
UNWIND_HINT_REGS
+ /* SYSENTER zeroed SSP; claim the task's supervisor token before any CALL. */
+ SET_SHSTK_BUSY
+
cld
/*
@@ -210,6 +213,9 @@ SYM_INNER_LABEL(entry_SYSCALL_compat_after_hwframe, SYM_L_GLOBAL)
PUSH_AND_CLEAR_REGS rcx=%rbp rax=$-ENOSYS
UNWIND_HINT_REGS
+ /* SYSCALL zeroed SSP; claim the task's supervisor token before any CALL. */
+ SET_SHSTK_BUSY
+
IBRS_ENTER
UNTRAIN_RET
CLEAR_BRANCH_HISTORY
@@ -271,6 +277,10 @@ SYM_INNER_LABEL(entry_SYSRETL_compat_unsafe_stack, SYM_L_GLOBAL)
*
* %r8/%r9 are zeroed before the sysret, thus safe to clobber.
*/
+
+ /* SYSRET does not free the token; SSP is back on it here. */
+ CLEAR_SHSTK_BUSY scratch_reg=%r8
+
SWITCH_TO_USER_CR3_NOSTACK scratch_reg=%r8 scratch_reg2=%r9
xorl %r8d, %r8d
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* [RFC PATCH 27/27] x86/entry: Handle shadow stack on nested NMI
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (25 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 26/27] x86/syscall: Toggle shadow stack busy on entry and exit from syscall K Prateek Nayak
@ 2026-11-29 22:29 ` K Prateek Nayak
2026-11-29 23:00 ` [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support Andrew Cooper
27 siblings, 0 replies; 29+ messages in thread
From: K Prateek Nayak @ 2026-11-29 22:29 UTC (permalink / raw)
To: Dave Hansen, Thomas Gleixner, Ingo Molnar, Borislav Petkov,
the arch/x86 maintainers, linux-kernel
Cc: Andy Lutomirski, Peter Zijlstra, Rick Edgecombe, Andrew Cooper,
Kees Cook, Pawan Gupta, K Prateek Nayak
IDT sets NMI on IST gate 1 and teh corresponding shadow shadows from
INT_SSP_TAB is asserted and marked busy.
On userspace NMIs that use the task's stack, clear the busy bit from the
NMI shadow stack to allow nesting and switch to PL0_SSP stack. Since it
is an NMI from userspace, the PL0SSP stack is empty and the stack can be
used safely from the top.
NMI from kernel needs special handling. Similar to the NMI from
userspace handling, clear the busy bit on the IST gate token, and switch
back to the same shadow stack at Gate 1 via restorssp.
Once back, the shadow stack establishes the same pattern as the regular
stack by duplicating { CS, LIP, SS } on top as the inner frame. The NMI
entry in "repeat NMI" will replicate the entries a second time to
stablish the outer frame.
The structure of shadow stack is as follows:
+-------------------------------+
| supervisor token |
+-------------------------------+
| Original CS |
| Original LIP | Hardware overwrites this slot
| Original SSP |
+-------------------------------+
| Inner CS |
| Inner LIP | Copied from first NMI
| Inner SSP |
+-------------------------------+
| Outer CS |
| Outer LIP | For the IRET from first NMI
| Outer SSP | (BUILD_NMI_REPEAT_SHSTK_FRAME)
+-------------------------------+
At the beginning, all three copies are same when it is established by
the first NMI. A nested NMI, will point outer SSP to Inner SSP's slot,
sets CS to, __KERNEL_CS and modify the LIP to jump to repeat_nmi just
like it populates the outer IRET frame on the stack.
Since the replication is consistent, the address of the outer frame is
known beforehand. IRET of first NMI is supposed to consume the outer
frame.
If there was nesting, repeat_nmi will rebuild the outer frame it
consumed during IRET in BUILD_NMI_REPEAT_SHSTK_FRAME and continue. Any
nested NMI at this point will simply take the nested_nmi_out path
without modifying anything on the shadow stack.
If there is no nested NMI, the outer frame, which is a replica of the
hardware populated frame, will transfer the control back into the
kernel.
This is super convoluted like the stack handling and severely unbalances
the RSB.
Signed-off-by: K Prateek Nayak <kprateek.nayak@amd.com>
---
arch/x86/entry/entry_64.S | 232 ++++++++++++++++++++++++++++++++++++++
1 file changed, 232 insertions(+)
diff --git a/arch/x86/entry/entry_64.S b/arch/x86/entry/entry_64.S
index 53ea96470f15..5a25c629a4d2 100644
--- a/arch/x86/entry/entry_64.S
+++ b/arch/x86/entry/entry_64.S
@@ -1145,6 +1145,214 @@ SYM_CODE_START_LOCAL(error_return)
jmp swapgs_restore_regs_and_return_to_usermode
SYM_CODE_END(error_return)
+#ifdef CONFIG_X86_KERN_SHADOW_STACK
+
+/*
+ * This allocates three dummy slots on the shadow stack frame
+ * and copies the previous top 3 slots on to the newly
+ * created dummy slots.
+ */
+.macro BUILD_NMI_REPEAT_SHSTK_FRAME needs_scratch=1
+ /* Save the scratch that will be clobbered. */
+ .if \needs_scratch
+ pushq %rax /* Extra scratch. */
+ pushq %rdx
+ .endif
+
+ xor %rdx, %rdx
+ rdsspq %rdx
+ testq %rdx, %rdx
+ jz .Lskip_shstk\@
+
+ /* Replicate top 3 frames below. */
+ .rept 3
+ ANNOTATE_INTRA_FUNCTION_CALL
+ call 7771f
+ int3
+7771:
+ movq 16(%rdx), %rax
+ wrssq %rax, -8(%rdx)
+ leaq -8(%rdx), %rdx
+ .endr
+ addq $24, %rsp
+.Lskip_shstk\@:
+
+ /* Restore scratch. */
+ .if \needs_scratch
+ popq %rdx
+ popq %rax
+ .endif
+.endm
+
+/*
+ * Nested NMI Shadow Stack handling
+ *
+ * On IDT systems, the hardware asserts the IST Gate-1 token and pushes
+ * a { CS, LIP, SS } package onto the shadow stack. Until the token is
+ * occupied, a nested NMI will #GP.
+ *
+ * We mark the shadow stack non-busy and use rstorssp to switch back to
+ * the same shadow stack. Then, like NMI handler does on regular stack,
+ * we construct a similar inner frame, outer frame structure, on the
+ * shadow stack:
+ *
+ * +-------------------------------+
+ * | supervisor token |
+ * +-------------------------------+
+ * | Original CS |
+ * | Original LIP | Hardware overwrites this slot
+ * | Original SSP |
+ * +-------------------------------+
+ * | Inner CS |
+ * | Inner LIP | Copied from first NMI
+ * | Inner SSP |
+ * +-------------------------------+
+ * | Outer CS |
+ * | Outer LIP | For the IRET from first NMI
+ * | Outer SSP | (BUILD_NMI_REPEAT_SHSTK_FRAME)
+ * +-------------------------------+
+ *
+ * At the beginning, all three copies are same when first NMI arrives.
+ * A nested NMI, will point outer SSP to Inner SSP's slot, set CS to,
+ * __KERNEL_CS and modify the LIP to jump to repeat_nmi just like it
+ * populates the stack frame.
+ *
+ * repeat_nmi will rebuild the outer frame it consumed in
+ * BUILD_NMI_REPEAT_SHSTK_FRAME and continue. Any nested NMI at this
+ * point will simply take the nested_nmi_out path to jump out.
+ *
+ * If there is no other NMI in-between, the outer frame is same as
+ * hardware populated one and the transfer jumps back at IRET.
+ *
+ * Note: RSB is severely unbalanced by the time we exit here.
+ */
+.macro INIT_NMI_SHSTK_STATE
+ xor %rdx, %rdx
+ rdsspq %rdx
+ testq %rdx, %rdx
+ jz .Lskip_shstk_init\@
+
+ /* Write a restore token. */
+ pushq %rax /* Extra scratch. */
+ movq %rdx, %rax
+ orq $1, %rax
+ wrssq %rax, -8(%rdx)
+
+ /*
+ * Supervisor token is 3 slots up, at the IST SSP.
+ * Clear the busy bit to allow nesting.
+ * NMIs are still disabled.
+ */
+ clrssbsy 24(%rdx)
+
+ /* Switch back to the same shadow stack */
+ rstorssp -8(%rdx)
+ movq $1, %rdx
+ incsspq %rdx
+
+ /*
+ * Build the original copy. first_nmi falls through into
+ * repeat_nmi, which builds the outer copy from it.
+ */
+ BUILD_NMI_REPEAT_SHSTK_FRAME needs_scratch=0
+
+ popq %rax /* Restore scratch. */
+
+.Lskip_shstk_init\@:
+.endm
+
+/*
+ * For CONFIG_DEBUG_ENTRY build a shadow stack frame that
+ * IRET-to-self can pop out.
+ */
+.macro BUILD_NMI_DEBUG_SHSTK_FRAME
+ pushq %rax /* Extra scratch. */
+ pushq %rdx
+
+ xor %eax, %eax
+ rdsspq %rax
+ testq %rax, %rax
+ jz .Lskip_shstk_debug\@
+
+ .rept 3
+ ANNOTATE_INTRA_FUNCTION_CALL
+ call 7772f
+ int3
+7772:
+ .endr
+ addq $24, %rsp
+
+ rdsspq %rdx
+ wrssq %rax, (%rdx) /* SSP */
+ movq 16(%rsp), %rax
+ wrssq %rax, 8(%rdx) /* LIP */
+ movq 24(%rsp), %rax
+ wrssq %rax, 16(%rdx) /* CS */
+
+.Lskip_shstk_debug\@:
+ popq %rdx
+ popq %rax
+.endm
+
+/*
+ * Fixup the outer frame to jump to "repeat_nmi" and point the
+ * CS, SSP to correct location to jump back to the inner copy
+ * 3 slots down the same shadow stack.
+ */
+.macro FIX_NESTED_NMI_SHSTK_FRAME
+ xor %rdx, %rdx
+ rdsspq %rdx
+ testq %rdx, %rdx
+ jz .Lskip_shstk_fix\@
+
+ pushq %rax
+
+ /*
+ * %rdx is S0-24. Redirect the outer copy (S0-56..S0-72) to
+ * repeat_nmi, resuming on top of the original copy (S0-48).
+ */
+ movq $__KERNEL_CS, %rax
+ wrssq %rax, -32(%rdx) /* CS */
+
+ movabsq $repeat_nmi, %rax
+ wrssq %rax, -40(%rdx) /* LIP */
+
+ leaq -24(%rdx), %rax
+ wrssq %rax, -48(%rdx) /* SSP */
+
+ popq %rax
+.Lskip_shstk_fix\@:
+.endm
+
+/*
+ * NMI from userspace uses the thread's stack.
+ *
+ * Set NMI shadow stack as non-busy to accommodate nested NMIs and
+ * switch to PL0_SSP stack. Simce this comes from userspace, the
+ * SSP0 stack is currently unused.
+ */
+.macro SWITCH_TO_TASK_SHSTK
+ rdsspq %rdx
+ clrssbsy (%rdx)
+ setssbsy
+.endm
+
+#else
+
+.macro BUILD_NMI_REPEAT_SHSTK_FRAME
+.endm
+.macro INIT_NMI_SHSTK_STATE
+.endm
+.macro BUILD_NMI_DEBUG_SHSTK_FRAME
+.endm
+.macro FIX_NESTED_NMI_SHSTK_FRAME
+.endm
+.macro SWITCH_TO_TASK_SHSTK
+.endm
+
+#endif
+
+
/*
* Runs on exception stack. Xen PV does not go through this path at all,
* so we can use real assembly here.
@@ -1231,6 +1439,13 @@ SYM_CODE_START(asm_exc_nmi)
PUSH_AND_CLEAR_REGS rdx=(%rdx)
ENCODE_FRAME_POINTER
+ /*
+ * Like the data stack, leave the NMI IST shadow stack so a nested
+ * NMI can claim its token, and run on the task's shadow stack.
+ * The IRET to user frees the task token again.
+ */
+ ALTERNATIVE "", __stringify(SWITCH_TO_TASK_SHSTK), X86_FEATURE_KERN_SHSTK
+
IBRS_ENTER
UNTRAIN_RET
@@ -1354,6 +1569,14 @@ nested_nmi:
* iteration of NMI handling.
*/
subq $8, %rsp
+
+ /*
+ * Fix needs to be done here since we have
+ * 5 spare stack frame we can use that gets
+ * overwritten by the later push.
+ */
+ FIX_NESTED_NMI_SHSTK_FRAME
+
leaq -10*8(%rsp), %rdx
pushq $__KERNEL_DS
pushq %rdx
@@ -1371,6 +1594,9 @@ nested_nmi_out:
iretq
first_nmi:
+
+ INIT_NMI_SHSTK_STATE
+
/* Restore rdx. */
movq (%rsp), %rdx
@@ -1399,6 +1625,9 @@ first_nmi:
pushfq /* RFLAGS */
pushq $__KERNEL_CS /* CS */
pushq $1f /* RIP */
+
+ BUILD_NMI_DEBUG_SHSTK_FRAME
+
iretq /* continues at repeat_nmi below */
UNWIND_HINT_IRET_REGS
1:
@@ -1433,6 +1662,9 @@ repeat_nmi:
pushq -6*8(%rsp)
.endr
subq $(5*8), %rsp
+
+ BUILD_NMI_REPEAT_SHSTK_FRAME
+
end_repeat_nmi:
ANNOTATE_NOENDBR // this code
--
2.43.0
^ permalink raw reply [flat|nested] 29+ messages in thread
* Re: [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
` (26 preceding siblings ...)
2026-11-29 22:29 ` [RFC PATCH 27/27] x86/entry: Handle shadow stack on nested NMI K Prateek Nayak
@ 2026-11-29 23:00 ` Andrew Cooper
27 siblings, 0 replies; 29+ messages in thread
From: Andrew Cooper @ 2026-11-29 23:00 UTC (permalink / raw)
To: K Prateek Nayak, Dave Hansen, Thomas Gleixner, Ingo Molnar,
Borislav Petkov, the arch/x86 maintainers, linux-kernel
Cc: Andrew Cooper, Andy Lutomirski, Peter Zijlstra, Rick Edgecombe,
Kees Cook, Pawan Gupta
On 29/11/2026 10:29 pm, K Prateek Nayak wrote:
> Write-to-CR2 for serialization
> ==============================
>
> CPUs that don't have SERIALIZE and have X86_FEATURE_KERN_SHSTK will
> default to using write-to-CR2 as serializing step. write-to-CR2 is
> available widely and although the comment in sync_core() suggests XEN
> may have some issues here, CONFIG_X86_KERE_SHADOW_STACK cannot be
> compiled with XEN yet so we'll consider write-to-CR2 as a temporary
> measure.
There is no legitimate dependency CONFIG_X86_KERNEL_SHADOW_STACK and
XEN; it's bogus and needs dropping.
Xen PV guests will never see CET (SS or IBT) and never enter the
CONFIG_X86_KERNEL_SHADOW_STACK paths. Xen HVM guests will, and they
will work as per native, just like KVM guests/etc.
The change you've made in sync core is fine. IRET is used because for
both XenPV and for UML, it will serialise without trapping; it's a
performance concern only.
> CALL emulation
> ==============
>
> Call emulation requires a RET frame to be inserted below the FRED entry
> frame. FRED frame is a { CS, LIP, SSP } pushed onto the shadow stack.
>
> To make our lives easy, we push a corresponding metadata frame onto the
> regula stack on top of pt_regs to make the following container:
>
> struct {
> u64 metadata; /* Context */
> u64 ssp; /* SSP at FRED_ENTRY */
> pt_rega *regs;
> }
>
> For CALL emulation, regs_emulate_call() helper will use the SSP from
> this context to overwrite the CS in the FRED frame with the return IP.
> The original CS and LIP are moved one slot up to make:
>
> ... ...
> +-----+ +-----+
> | CS | | RET |
> | LIP | -> +-----+
> | SSP | | CS |
> +-----+ | LIP | <- Jump to CALL site
> +-----+ <- Top of stack
>
> Text patching events always occur at same FRED level and SSP always
> points to address 3 slots down. regs_emulate_call() will then notify
> FRED_EXIT of the patching by setting a flag in the metadata.
>
> FRED_EXIT will see this flag and do a dummy call, fixup stack, and
> overwrite the top of shadow stack with a SSP of three slots down to
> complete the FRED frame which matches for ERETS. After an ERETS, the
> fist RET will mismatch but rest of the RETs are balanced in RSB.
>
> This is also the same method of doing a direct call via ORIG_RAX in
> ftrace_regs_caller and has been adopted here.
MSR_FRED_CONFIG.SSP (bit 3) exists exclusively for this purpose.
There was a reasonable amount of spirited debate required to get that
into the FRED spec. It would be a shame not to use it.
~Andrew
^ permalink raw reply [flat|nested] 29+ messages in thread
end of thread, other threads:[~2026-11-29 23:00 UTC | newest]
Thread overview: 29+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-29 22:29 [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 01/27] x86/entry: Parameterize kernel shadow stack handling at FRED entry K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 02/27] x86/perf_regs: Rename pt_regs_offset array to prevent build failure K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 03/27] x86/cet: Fix build for KERN_SHADOW_STACK and !USER_SHADOW_STACK K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 04/27] x86/cet: Make kernel shadow stack #CP fatal instead of livelocking K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 05/27] x86/sync_core: Don't use IRET-to-self with kernel shadow stacks K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 06/27] x86/process: Initialize and enable kernel shadow stack at boot K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 07/27] x86/entry: Handle int3 text patching with kernel shadow stack K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 08/27] x86/retpoline: Handle retpolies and thunks " K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 09/27] x86/ftrace: Prepare ftrace trampolines to handle " K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 10/27] x86/kprobes: Prepare optprobe trampoline to handle shadow stacks K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 11/27] x86/rethook: Prepare the rethook trampoline to handle shadow stack K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 12/27] x86/cet: Make regs_set_return_ip() helpers context aware K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 13/27] x86/cet: Introduce regs_set_return_trampoline() for rethook trampoline K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 14/27] x86/ftrace,livepatch: Use CET helpers for ftrace regs->ip and trampoline redirection K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 15/27] x86/rethook: Make the trampoline insert and return shadow stack aware K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 16/27] x86/error_inject: Use CET helpers to insert just_return_func trampoline K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 17/27] x86/kprobes: Use CET helpers in kprobe core to modify regs->ip K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 18/27] x86/bpf: Make BPF JIT aware of CET handling K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 19/27] x86/shstk: Remove profiling related dependencies for KERN_SHADOW_STACK K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 20/27] x86/shstk: Disable kenrel shadow stack when CPU is offlined K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 21/27] x86/shstsk: Allow suspend-resume and hibernation with kernel shadow stack K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 22/27] x86/shstk: Save and restore shadow stack pointer during kexec K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 23/27] x86/idt: Map MCE shadow stack and populate the INT_SPP table K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 24/27] x86/process: Initialize shadow stack for IDT systems K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 25/27] x86/entry: Prepare IDT entry for shadow stacks K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 26/27] x86/syscall: Toggle shadow stack busy on entry and exit from syscall K Prateek Nayak
2026-11-29 22:29 ` [RFC PATCH 27/27] x86/entry: Handle shadow stack on nested NMI K Prateek Nayak
2026-11-29 23:00 ` [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support Andrew Cooper
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
all inboxes | Powered by JetHome®