mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
From: K Prateek Nayak <kprateek.nayak@amd.com>
To: Dave Hansen <dave.hansen@linux.intel.com>,
	Thomas Gleixner <tglx@kernel.org>, Ingo Molnar <mingo@redhat.com>,
	Borislav Petkov <bp@alien8.de>,
	the arch/x86 maintainers <x86@kernel.org>,
	<linux-kernel@vger.kernel.org>
Cc: Andy Lutomirski <luto@kernel.org>,
	Peter Zijlstra <peterz@infradead.org>,
	Rick Edgecombe <rick.p.edgecombe@intel.com>,
	Andrew Cooper <andrew.cooper3@citrix.com>,
	Kees Cook <kees@kernel.org>,
	Pawan Gupta <pawan.kumar.gupta@linux.intel.com>,
	K Prateek Nayak <kprateek.nayak@amd.com>
Subject: [RFC PATCH 00/27] x86/shstk: More shadow stack enablement and path to IDT support
Date: Sun, 29 Nov 2026 22:29:25 +0000	[thread overview]
Message-ID: <20261129222953.9124-1-kprateek.nayak@amd.com> (raw)

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


             reply	other threads:[~2026-11-29 22:30 UTC|newest]

Thread overview: 29+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-29 22:29 K Prateek Nayak [this message]
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

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261129222953.9124-1-kprateek.nayak@amd.com \
    --to=kprateek.nayak@amd.com \
    --cc=andrew.cooper3@citrix.com \
    --cc=bp@alien8.de \
    --cc=dave.hansen@linux.intel.com \
    --cc=kees@kernel.org \
    --cc=linux-kernel@vger.kernel.org \
    --cc=luto@kernel.org \
    --cc=mingo@redhat.com \
    --cc=pawan.kumar.gupta@linux.intel.com \
    --cc=peterz@infradead.org \
    --cc=rick.p.edgecombe@intel.com \
    --cc=tglx@kernel.org \
    --cc=x86@kernel.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
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®