Skip to contentSkip to conversation

KVM: arm64: EL2 synchronisation and pKVM stage-2 error propagation fixes

PATCH Superseded Fuad Tabba 4 participants 19 messages Apr 28 – Apr 30

Subsystems (3)

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore

Fuad Tabba

author
#0 lore raw

cover KVM: arm64: EL2 synchronisation and pKVM stage-2 error propagation fixes

Hi folks,

This is yet another series of fixes I'd like to land before posting a follow-up to Will's pKVM infrastructure series [1].

I found these while developing KVM and arm64 system guides for review-prompts [2], an open-source set of AI-assisted review prompts used by sashiko [3]. While writing the guides I tried to find cases that would be easy to miss or trip up an LLM, and stumbled on these bugs. A local run with the updated guides flagged all of them correctly (some of the commit messages incorporate feedback from that run, e.g., the impact of WARN_ON() in hyp). I plan to upstream the guides once they are complete.

The patches fall into three groups:

EL2 context-synchronisation (patches 1-2):

Patch 1 sets SCTLR_EL2.EIS and SCTLR_EL2.EOS in INIT_SCTLR_EL2_MMU_ON. On FEAT_ExS hardware these bits are UNKNOWN at reset; without them EL2 exception entry and exit are not architecturally guaranteed to be Context Synchronisation Events. KVM/arm64 hot paths rely on that guarantee implicitly to elide explicit ISBs after MSRs to context-switching sysregs.

Patch 2 adds an explicit ISB after write_sysreg_hcr() on the __deactivate_traps() path. The activate path is covered by the ERET that follows (a CSE, guaranteed by patch 1); on the deactivate path, subsequent EL2 sysreg accesses run before any natural CSE.

Minor fixes (patches 3-4):

Patch 3 fixes a parameter-name typo in __deactivate_fgt() that causes it to silently capture a variable from the enclosing scope rather than use its declared parameter.

Patch 4 guards the VHE hyp panic path against a NULL vcpu pointer; the nVHE counterpart already has this guard.

pKVM stage-2 error propagation (patches 5-8):

At EL2 in nVHE/pKVM, WARN_ON() is not warn-and-continue: it expands to a BRK that enters the invalid-host-el2 vector and branches to hyp_panic(), which is __noreturn.

Four pKVM memory-transition functions wrapped the return value of kvm_pgtable_stage2_map() in WARN_ON() and discarded it. For the share and donation paths the map can fail via -ENOMEM when the vcpu memcache is exhausted, converting a recoverable hypercall error into a fatal hyp panic. The four patches capture and propagate the return value, with appropriate stage-2 unmap and host-side rollback for the reachable failure cases.

Cheers,
/fuad

[1] https://lore.kernel.org/all/[email protected]/
[2] https://github.com/masoncl/review-prompts
[3] https://sashiko.dev/

Fuad Tabba (8):
KVM: arm64: Make EL2 exception entry and exit context-synchronization
events
KVM: arm64: Synchronise HCR_EL2 writes on the guest exit path
KVM: arm64: Guard against NULL vcpu on VHE hyp panic path
KVM: arm64: Fix __deactivate_fgt macro parameter typo
KVM: arm64: Propagate stage-2 map failure on host->guest share
KVM: arm64: Propagate stage-2 map failure on host->guest donation
KVM: arm64: Propagate stage-2 map failure on guest->host share
KVM: arm64: Propagate stage-2 map failure on guest->host unshare

 arch/arm64/include/asm/sysreg.h         |  2 +-
 arch/arm64/kvm/hyp/include/hyp/switch.h |  2 +-
 arch/arm64/kvm/hyp/nvhe/mem_protect.c   | 99 +++++++++++++++++++++----
 arch/arm64/kvm/hyp/nvhe/switch.c        | 11 +++
 arch/arm64/kvm/hyp/vhe/switch.c         | 14 +++-
 5 files changed, 111 insertions(+), 17 deletions(-)
Signature · 1 line
2.54.0.545.g6539524ca2-goog
author
#1 lore raw

PATCH 1/8 KVM: arm64: Make EL2 exception entry and exit context-synchronization events

SCTLR_EL2.EIS and SCTLR_EL2.EOS control whether exception entry and exit at EL2 are Context Synchronisation Events (CSEs). Per ARM DDI 0487 M.b, EIS is governed by D1.4.2 rule RBBSRF (p. D1-7205) and EOS by D1.4.4.1 rule RBWCFK (p. D1-7209). D24.2.175 (p. D24-9754):

- !FEAT_ExS: the bit is RES1, so the entry/exit is unconditionally a CSE.
- FEAT_ExS: the reset value is architecturally UNKNOWN; software must set the bit to make the entry/exit a CSE.

INIT_SCTLR_EL2_MMU_ON in arch/arm64/include/asm/sysreg.h sets neither bit. KVM/arm64 hot paths rely on ERET from EL2 being a CSE, and on synchronous EL1->EL2 entry being a CSE, to elide explicit ISBs after MSRs to context-switching system registers (HCR_EL2, HFGxTR_EL2, HCRX_EL2, ZCR_EL2, CPACR_EL1, CPTR_EL2, SCTLR_EL1, ptrauth keys, etc.); examples include the activate-traps path, ptrauth_switch_to_guest, and the FPSIMD trap re-enable in kvm_hyp_handle_fpsimd. On FEAT_ExS hardware those reliances are not architecturally backed unless EOS=1 (and, for entry, EIS=1), and whether they hold today depends on firmware initialisation outside the kernel's control.

Make the guarantee explicit: include SCTLR_ELx_EIS | SCTLR_ELx_EOS in INIT_SCTLR_EL2_MMU_ON so that EL2 exception entry and exit are unconditionally CSEs regardless of whether FEAT_ExS is implemented. This matches the pairing in arch/arm64/kvm/config.c which treats EIS and EOS together as RES1 under !FEAT_ExS.

INIT_SCTLR_EL2_MMU_OFF is left unchanged: that path is used during very early EL2 init and the EL2 MMU-off transition, neither of which relies on these bits in the same way.

Fixes fe2c8d19189e ("KVM: arm64: Turn SCTLR_ELx_FLAGS into INIT_SCTLR_EL2_MMU_ON")
---
 arch/arm64/include/asm/sysreg.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/arm64/include/asm/sysreg.h +1 -1
index 736561480f36..7aa08d59d494 100644
@@ -844,7 +844,7 @@
 #define INIT_SCTLR_EL2_MMU_ON						\
 	(SCTLR_ELx_M  | SCTLR_ELx_C | SCTLR_ELx_SA | SCTLR_ELx_I |	\
 	 SCTLR_ELx_IESB | SCTLR_ELx_WXN | ENDIAN_SET_EL2 |		\
-	 SCTLR_ELx_ITFSB | SCTLR_EL2_RES1)
+	 SCTLR_ELx_ITFSB | SCTLR_ELx_EIS | SCTLR_ELx_EOS | SCTLR_EL2_RES1)
 
 #define INIT_SCTLR_EL2_MMU_OFF \
 	(SCTLR_EL2_RES1 | ENDIAN_SET_EL2)
Signature · 1 line
2.54.0.545.g6539524ca2-goog
Reviewed-by on v1 1/8
#2 lore raw

Re: [PATCH 1/8] KVM: arm64: Make EL2 exception entry and exit context-synchronization events

Quoted 43 lines · Fuad Tabba

SCTLR_EL2.EIS and SCTLR_EL2.EOS control whether exception entry and exit at EL2 are Context Synchronisation Events (CSEs). Per ARM DDI 0487 M.b, EIS is governed by D1.4.2 rule RBBSRF (p. D1-7205) and EOS by D1.4.4.1 rule RBWCFK (p. D1-7209). D24.2.175 (p. D24-9754):

- !FEAT_ExS: the bit is RES1, so the entry/exit is unconditionally a CSE.
- FEAT_ExS: the reset value is architecturally UNKNOWN; software must set the bit to make the entry/exit a CSE.

INIT_SCTLR_EL2_MMU_ON in arch/arm64/include/asm/sysreg.h sets neither bit. KVM/arm64 hot paths rely on ERET from EL2 being a CSE, and on synchronous EL1->EL2 entry being a CSE, to elide explicit ISBs after MSRs to context-switching system registers (HCR_EL2, HFGxTR_EL2, HCRX_EL2, ZCR_EL2, CPACR_EL1, CPTR_EL2, SCTLR_EL1, ptrauth keys, etc.); examples include the activate-traps path, ptrauth_switch_to_guest, and the FPSIMD trap re-enable in kvm_hyp_handle_fpsimd. On FEAT_ExS hardware those reliances are not architecturally backed unless EOS=1 (and, for entry, EIS=1), and whether they hold today depends on firmware initialisation outside the kernel's control.

Make the guarantee explicit: include SCTLR_ELx_EIS | SCTLR_ELx_EOS in INIT_SCTLR_EL2_MMU_ON so that EL2 exception entry and exit are unconditionally CSEs regardless of whether FEAT_ExS is implemented. This matches the pairing in arch/arm64/kvm/config.c which treats EIS and EOS together as RES1 under !FEAT_ExS.

INIT_SCTLR_EL2_MMU_OFF is left unchanged: that path is used during very early EL2 init and the EL2 MMU-off transition, neither of which relies on these bits in the same way.

Fixes fe2c8d19189e ("KVM: arm64: Turn SCTLR_ELx_FLAGS into INIT_SCTLR_EL2_MMU_ON")
---
 arch/arm64/include/asm/sysreg.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/arm64/include/asm/sysreg.h +0 -0
index 736561480f36..7aa08d59d494 100644

arch/arm64/include/asm/sysreg.h line 846

Quoted 3 lines
arch/arm64/include/asm/sysreg.h +0 -0
@@ -844,7 +844,7 @@
 #define INIT_SCTLR_EL2_MMU_ON						\
 	(SCTLR_ELx_M  | SCTLR_ELx_C | SCTLR_ELx_SA | SCTLR_ELx_I |	\
 	 SCTLR_ELx_IESB | SCTLR_ELx_WXN | ENDIAN_SET_EL2 |		\

Hi Fuad,

arch/arm64/include/asm/sysreg.h line 847

Quoted 2 lines
arch/arm64/include/asm/sysreg.h +1 -1
-	 SCTLR_ELx_ITFSB | SCTLR_EL2_RES1)
+	 SCTLR_ELx_ITFSB | SCTLR_ELx_EIS | SCTLR_ELx_EOS | SCTLR_EL2_RES1)

LGTM.

Quoted 6 lines
arch/arm64/include/asm/sysreg.h +0 -1
 #define INIT_SCTLR_EL2_MMU_OFF \
 	(SCTLR_EL2_RES1 | ENDIAN_SET_EL2)
--

2.54.0.545.g6539524ca2-goog

maintainer
#3 lore raw

Re: [PATCH 1/8] KVM: arm64: Make EL2 exception entry and exit context-synchronization events

In reply to Fuad Tabba
Quoted 28 lines · Fuad Tabba

SCTLR_EL2.EIS and SCTLR_EL2.EOS control whether exception entry and exit at EL2 are Context Synchronisation Events (CSEs). Per ARM DDI 0487 M.b, EIS is governed by D1.4.2 rule RBBSRF (p. D1-7205) and EOS by D1.4.4.1 rule RBWCFK (p. D1-7209). D24.2.175 (p. D24-9754):

- !FEAT_ExS: the bit is RES1, so the entry/exit is unconditionally a CSE.
- FEAT_ExS: the reset value is architecturally UNKNOWN; software must set the bit to make the entry/exit a CSE.

INIT_SCTLR_EL2_MMU_ON in arch/arm64/include/asm/sysreg.h sets neither bit. KVM/arm64 hot paths rely on ERET from EL2 being a CSE, and on synchronous EL1->EL2 entry being a CSE, to elide explicit ISBs after MSRs to context-switching system registers (HCR_EL2, HFGxTR_EL2, HCRX_EL2, ZCR_EL2, CPACR_EL1, CPTR_EL2, SCTLR_EL1, ptrauth keys, etc.); examples include the activate-traps path, ptrauth_switch_to_guest, and the FPSIMD trap re-enable in kvm_hyp_handle_fpsimd. On FEAT_ExS hardware those reliances are not architecturally backed unless EOS=1 (and, for entry, EIS=1), and whether they hold today depends on firmware initialisation outside the kernel's control.

Make the guarantee explicit: include SCTLR_ELx_EIS | SCTLR_ELx_EOS in INIT_SCTLR_EL2_MMU_ON so that EL2 exception entry and exit are unconditionally CSEs regardless of whether FEAT_ExS is implemented. This matches the pairing in arch/arm64/kvm/config.c which treats EIS and EOS together as RES1 under !FEAT_ExS.

Quoted 5 lines

INIT_SCTLR_EL2_MMU_OFF is left unchanged: that path is used during very early EL2 init and the EL2 MMU-off transition, neither of which relies on these bits in the same way.

Fixes fe2c8d19189e ("KVM: arm64: Turn SCTLR_ELx_FLAGS into INIT_SCTLR_EL2_MMU_ON")

I don't think this Fixes: tag is accurate:

1. That commit doesn't do anything with EIS/EOS afaict.
2. Back in 5.12 (when that thing landed), SCTLR_EL2_RES1 did actually include EIS and EOS

so I think the issue here might be that the auto-generated sysreg file quietly changes the RES1 definitions as bits get allocated, but the macros using the RES1 definition don't get updated. That's a pretty horrible pit that it feels like we might keep falling into :/

Looking at 0a35bd285f43 ("arm64: Convert SCTLR_EL2 to sysreg infrastructure"), I think we ended up dropping a whole bunch of fields from the RES1 mask (which became 0!). Have you checked all of those?

Will

author
#4 lore raw

Re: [PATCH 1/8] KVM: arm64: Make EL2 exception entry and exit context-synchronization events

Hi Will,

Quoted 42 lines · Will Deacon
Quoted 28 lines · Fuad Tabba

SCTLR_EL2.EIS and SCTLR_EL2.EOS control whether exception entry and exit at EL2 are Context Synchronisation Events (CSEs). Per ARM DDI 0487 M.b, EIS is governed by D1.4.2 rule RBBSRF (p. D1-7205) and EOS by D1.4.4.1 rule RBWCFK (p. D1-7209). D24.2.175 (p. D24-9754):

- !FEAT_ExS: the bit is RES1, so the entry/exit is unconditionally a CSE.
- FEAT_ExS: the reset value is architecturally UNKNOWN; software must set the bit to make the entry/exit a CSE.

INIT_SCTLR_EL2_MMU_ON in arch/arm64/include/asm/sysreg.h sets neither bit. KVM/arm64 hot paths rely on ERET from EL2 being a CSE, and on synchronous EL1->EL2 entry being a CSE, to elide explicit ISBs after MSRs to context-switching system registers (HCR_EL2, HFGxTR_EL2, HCRX_EL2, ZCR_EL2, CPACR_EL1, CPTR_EL2, SCTLR_EL1, ptrauth keys, etc.); examples include the activate-traps path, ptrauth_switch_to_guest, and the FPSIMD trap re-enable in kvm_hyp_handle_fpsimd. On FEAT_ExS hardware those reliances are not architecturally backed unless EOS=1 (and, for entry, EIS=1), and whether they hold today depends on firmware initialisation outside the kernel's control.

Make the guarantee explicit: include SCTLR_ELx_EIS | SCTLR_ELx_EOS in INIT_SCTLR_EL2_MMU_ON so that EL2 exception entry and exit are unconditionally CSEs regardless of whether FEAT_ExS is implemented. This matches the pairing in arch/arm64/kvm/config.c which treats EIS and EOS together as RES1 under !FEAT_ExS.

Quoted 5 lines

INIT_SCTLR_EL2_MMU_OFF is left unchanged: that path is used during very early EL2 init and the EL2 MMU-off transition, neither of which relies on these bits in the same way.

Fixes fe2c8d19189e ("KVM: arm64: Turn SCTLR_ELx_FLAGS into INIT_SCTLR_EL2_MMU_ON")

I don't think this Fixes: tag is accurate:

1. That commit doesn't do anything with EIS/EOS afaict.
2. Back in 5.12 (when that thing landed), SCTLR_EL2_RES1 did actually include EIS and EOS

Quoted 8 lines

so I think the issue here might be that the auto-generated sysreg file quietly changes the RES1 definitions as bits get allocated, but the macros using the RES1 definition don't get updated. That's a pretty horrible pit that it feels like we might keep falling into :/

Looking at 0a35bd285f43 ("arm64: Convert SCTLR_EL2 to sysreg infrastructure"), I think we ended up dropping a whole bunch of fields from the RES1 mask (which became 0!). Have you checked all of those?

You're right, fe2c8d19189e didn't touch EIS/EOS: the SCTLR_EL2_RES1 mask it pulled into INIT_SCTLR_EL2_MMU_ON already contained BIT(11)/BIT(22). Looking at it, I _think_ it's this one:

0a35bd285f43 ("arm64: Convert SCTLR_EL2 to sysreg infrastructure")

After that commit SCTLR_EL2_RES1 is auto-generated. Because the sysreg tooling can only model unconditional RES1, and EIS/EOS are RES1 only when !FEAT_ExS, the generated mask is UL(0). I'll fix the
Fixes: tag in v2.

On the wider question of the other bits dropped from the old mask, I went through them against DDI 0487 M.b §D24.2.175. The summary (SCTLR_EL2 with E2H=0):

bit field E2H=0 status kernel cares?
-------------------------------------------------------------

   4   SA0      RES1 unconditionally          no
   5   CP15BEN  RES1 unconditionally          no
  11   EOS      RES1 iff !FEAT_ExS, else RW   yes (this fix)
  16   nTWI     RES1 unconditionally          no
  18   nTWE     RES1 unconditionally          no
  22   EIS      RES1 iff !FEAT_ExS, else RW   yes (this fix)
  23   SPAN     RES1 unconditionally          no
  28   nTLSMD   RES1 unconditionally          no
  29   LSMAOE   RES1 unconditionally          no

The seven non-EIS/EOS bits all fall under the "Otherwise: Reserved, RES1" clause for the E2H=0 layout, with no feature guard. Writing 0 to them is a no-op, so dropping them from the mask should be harmless I think. EIS and EOS are the only positions where the bit becomes RW (with UNKNOWN reset) on FEAT_ExS hardware and the kernel actively relies on the value being 1, which is what this patch addresses.

I agree the auto-generator silently zeroing previously hand-rolled RES1 masks is a real problem. Happy to look at either teaching the sysreg infrastructure to express conditional RES1 (so config.c's AS_RES1/FEAT_X facts can flow back into the header masks), or at least adding a build-time check that flags any auto-generated <REG>_RES1 that shrinks. After this series, though. Let me know if you'd like me to take a stab.

What plan to changechange in v2:

1. Fixes: 0a35bd285f43 ("arm64: Convert SCTLR_EL2 to sysreg infrastructure").
2. Add one paragraph in the commit message explaining that the bug landed when SCTLR_EL2_RES1 was auto-generated to UL(0), with a one-line justification that the other seven dropped bits are unconditionally RES1 at E2H=0 and so harmless.
3. Code diff unchanged (still just adding SCTLR_ELx_EIS | SCTLR_ELx_EOS to INIT_SCTLR_EL2_MMU_ON).

What do you think?

Cheers,
/fuad

Quoted 1 line

Will

reviewer
#5 lore raw

Re: [PATCH 1/8] KVM: arm64: Make EL2 exception entry and exit context-synchronization events

Quoted 6 lines · Fuad Tabba
Quoted 5 lines · Will Deacon
Quoted 1 line · Fuad Tabba
Fixes fe2c8d19189e ("KVM: arm64: Turn SCTLR_ELx_FLAGS into INIT_SCTLR_EL2_MMU_ON")

I don't think this Fixes: tag is accurate:

Quoted 8 lines
Quoted 8 lines

1. That commit doesn't do anything with EIS/EOS afaict.
2. Back in 5.12 (when that thing landed), SCTLR_EL2_RES1 did actually include EIS and EOS

so I think the issue here might be that the auto-generated sysreg file quietly changes the RES1 definitions as bits get allocated, but the macros using the RES1 definition don't get updated. That's a pretty horrible pit that it feels like we might keep falling into :/

I think that's a review failure, and people need to be careful when updating the sysreg file (e.g. looking at whether any new bits were previously RESx, and considering the impact). Regardless of tooling, we need people to conciosuly review that.

Quoted 28 lines
Quoted 3 lines

Looking at 0a35bd285f43 ("arm64: Convert SCTLR_EL2 to sysreg infrastructure"), I think we ended up dropping a whole bunch of fields from the RES1 mask (which became 0!). Have you checked all of those?

On the wider question of the other bits dropped from the old mask, I went through them against DDI 0487 M.b §D24.2.175. The summary (SCTLR_EL2 with E2H=0):

bit field E2H=0 status kernel cares?
-------------------------------------------------------------

   4   SA0      RES1 unconditionally          no
   5   CP15BEN  RES1 unconditionally          no
  11   EOS      RES1 iff !FEAT_ExS, else RW   yes (this fix)
  16   nTWI     RES1 unconditionally          no
  18   nTWE     RES1 unconditionally          no
  22   EIS      RES1 iff !FEAT_ExS, else RW   yes (this fix)
  23   SPAN     RES1 unconditionally          no
  28   nTLSMD   RES1 unconditionally          no
  29   LSMAOE   RES1 unconditionally          no

The seven non-EIS/EOS bits all fall under the "Otherwise: Reserved, RES1" clause for the E2H=0 layout, with no feature guard. Writing 0 to them is a no-op, so dropping them from the mask should be harmless I think. EIS and EOS are the only positions where the bit becomes RW (with UNKNOWN reset) on FEAT_ExS hardware and the kernel actively relies on the value being 1, which is what this patch addresses.

Quoted 4 lines

I agree the auto-generator silently zeroing previously hand-rolled RES1 masks is a real problem. Happy to look at either teaching the sysreg infrastructure to express conditional RES1 (so config.c's AS_RES1/FEAT_X facts can flow back into the header masks),

Please don't add that to the syreg code; that's deliberately *only* the architectural definitions, and overloading that is going to make things even more confusing, because "I want to treat this as RESx in this piece of code" isn't a global property.

Quoted 3 lines

or at least adding a build-time check that flags any auto-generated <REG>_RES1 that shrinks. After this series, though. Let me know if you'd like me to take a stab.

FWIW, having tooling to compare before/after would be useful, but I don't think that can be a standard build-time check, given that this would depend on having the old and new sysreg files available for comparison.

Mark.

author
#6 lore raw

PATCH 2/8 KVM: arm64: Synchronise HCR_EL2 writes on the guest exit path

In reply to Fuad Tabba

MSR HCR_EL2 is not self-synchronising. Per ARM DDI 0487 M.b K1.2.4 (p.K1-16823) and B2.6.1 (p.B2-297), a Context Synchronisation Event is required between an HCR_EL2 write and any subsequent direct register access at the same EL that depends on the new value being in effect.

On the entry path, the HCR_EL2 write in __activate_traps is followed by further EL2 sysreg work (MDCR_EL2, CPTR_EL2, VBAR_EL2, and on the speculative-AT errata path SCTLR_EL1/TCR_EL1) before ERET into the guest. None of those intervening accesses depend on the new HCR_EL2 value, and ERET is a CSE per ARM DDI 0487 M.b D1.4.4.1 rule RBWCFK (p. D1-7209) conditional on SCTLR_EL2.EOS=1, which is set unconditionally by INIT_SCTLR_EL2_MMU_ON (see the prerequisite patch in this series). The requirement is therefore satisfied implicitly on the activate path.

The deactivate path is different: after write_sysreg_hcr() in __deactivate_traps() further EL2 sysreg work runs before any natural CSE - on nVHE, __deactivate_cptr_traps and the VBAR_EL2 write; on VHE, the timer context save which reads CNTP_CVAL_EL0 under the new TGE/E2H, and the EL1 sysreg restore. Add an explicit isb() at each of the two deactivate sites.

The practical impact today is bounded: HCR_EL2.E2H does not toggle in either path, and the trap bits being changed primarily affect EL1&0 behaviour. But the architectural rule should be honoured. Note that write_sysreg_hcr() itself already issues isb() on the Ampere errata path (sysreg.h), confirming the architectural expectation; the fast path optimises that away.

The fix is at the call sites rather than inside write_sysreg_hcr() because the macro has many users (e.g. the activate path, at.c, hardirq.h, ptrauth alternatives) where the immediately-following code either reaches ERET or has another CSE; making the macro emit an unconditional ISB would impose unnecessary cost on those well-formed users.

Fixes 9404673293b0 ("KVM: arm64: timers: Correctly handle TGE flip with CNTPOFF_EL2")
---
 arch/arm64/kvm/hyp/nvhe/switch.c | 11 +++++++++++
 arch/arm64/kvm/hyp/vhe/switch.c  | 11 +++++++++++
 2 files changed, 22 insertions(+)
arch/arm64/kvm/hyp/nvhe/switch.c +11 -0
index 8d1df3d33595..9d7ead5a5503 100644
@@ -105,6 +105,17 @@ static void __deactivate_traps(struct kvm_vcpu *vcpu)
 	__deactivate_traps_common(vcpu);
 
 	write_sysreg_hcr(this_cpu_ptr(&kvm_init_params)->hcr_el2);
+	/*
+	 * MSR HCR_EL2 is not self-synchronising. Per ARM ARM K1.2.4 p.K1-16823
+	 * and B2.6.1 p.B2-297, a Context Synchronisation Event is required
+	 * between an HCR_EL2 write and any subsequent direct register access at
+	 * the same EL that depends on the new value being in effect.
+	 * The activate_traps path falls through to ERET (a CSE), but the
+	 * deactivate path still executes further EL2 sysreg work (CPTR/VBAR
+	 * writes below) before any natural CSE, so make the synchronisation
+	 * explicit.
+	 */
+	isb();
 
 	__deactivate_cptr_traps(vcpu);
 	write_sysreg(__kvm_hyp_host_vector, vbar_el2);
arch/arm64/kvm/hyp/vhe/switch.c +11 -0
index 9db3f11a4754..140d3bcb5651 100644
@@ -149,6 +149,17 @@ static void __deactivate_traps(struct kvm_vcpu *vcpu)
 	___deactivate_traps(vcpu);
 
 	write_sysreg_hcr(HCR_HOST_VHE_FLAGS);
+	/*
+	 * MSR HCR_EL2 is not self-synchronising. Per ARM ARM K1.2.4 p.K1-16823
+	 * and B2.6.1 p.B2-297, a Context Synchronisation Event is required
+	 * between an HCR_EL2 write and any subsequent direct register access at
+	 * the same EL that depends on the new value being in effect.
+	 * The activate_traps path falls through to ERET (a CSE), but the
+	 * deactivate path still executes further EL2 sysreg work (CPTR/VBAR
+	 * writes below) before any natural CSE, so make the synchronisation
+	 * explicit.
+	 */
+	isb();
 
 	if (has_cntpoff()) {
 		struct timer_map map;
Signature · 1 line
2.54.0.545.g6539524ca2-goog
maintainer
#7 lore raw

Re: [PATCH 2/8] KVM: arm64: Synchronise HCR_EL2 writes on the guest exit path

Quoted 53 lines · Fuad Tabba

MSR HCR_EL2 is not self-synchronising. Per ARM DDI 0487 M.b K1.2.4 (p.K1-16823) and B2.6.1 (p.B2-297), a Context Synchronisation Event is required between an HCR_EL2 write and any subsequent direct register access at the same EL that depends on the new value being in effect.

On the entry path, the HCR_EL2 write in __activate_traps is followed by further EL2 sysreg work (MDCR_EL2, CPTR_EL2, VBAR_EL2, and on the speculative-AT errata path SCTLR_EL1/TCR_EL1) before ERET into the guest. None of those intervening accesses depend on the new HCR_EL2 value, and ERET is a CSE per ARM DDI 0487 M.b D1.4.4.1 rule RBWCFK (p. D1-7209) conditional on SCTLR_EL2.EOS=1, which is set unconditionally by INIT_SCTLR_EL2_MMU_ON (see the prerequisite patch in this series). The requirement is therefore satisfied implicitly on the activate path.

The deactivate path is different: after write_sysreg_hcr() in __deactivate_traps() further EL2 sysreg work runs before any natural CSE - on nVHE, __deactivate_cptr_traps and the VBAR_EL2 write; on VHE, the timer context save which reads CNTP_CVAL_EL0 under the new TGE/E2H, and the EL1 sysreg restore. Add an explicit isb() at each of the two deactivate sites.

The practical impact today is bounded: HCR_EL2.E2H does not toggle in either path, and the trap bits being changed primarily affect EL1&0 behaviour. But the architectural rule should be honoured. Note that write_sysreg_hcr() itself already issues isb() on the Ampere errata path (sysreg.h), confirming the architectural expectation; the fast path optimises that away.

The fix is at the call sites rather than inside write_sysreg_hcr() because the macro has many users (e.g. the activate path, at.c, hardirq.h, ptrauth alternatives) where the immediately-following code either reaches ERET or has another CSE; making the macro emit an unconditional ISB would impose unnecessary cost on those well-formed users.

Fixes 9404673293b0 ("KVM: arm64: timers: Correctly handle TGE flip with CNTPOFF_EL2")
---
 arch/arm64/kvm/hyp/nvhe/switch.c | 11 +++++++++++
 arch/arm64/kvm/hyp/vhe/switch.c  | 11 +++++++++++
 2 files changed, 22 insertions(+)
arch/arm64/kvm/hyp/nvhe/switch.c +1 -0
index 8d1df3d33595..9d7ead5a5503 100644
@@ -105,6 +105,17 @@ static void __deactivate_traps(struct kvm_vcpu *vcpu)
 	__deactivate_traps_common(vcpu);
 
 	write_sysreg_hcr(this_cpu_ptr(&kvm_init_params)->hcr_el2);
+	/*

arch/arm64/kvm/hyp/nvhe/switch.c static void __deactivate_traps(struct kvm_vcpu *vcpu) · line 118

Quoted 10 lines
arch/arm64/kvm/hyp/nvhe/switch.c +10 -0
+	 * MSR HCR_EL2 is not self-synchronising. Per ARM ARM K1.2.4 p.K1-16823
+	 * and B2.6.1 p.B2-297, a Context Synchronisation Event is required
+	 * between an HCR_EL2 write and any subsequent direct register access at
+	 * the same EL that depends on the new value being in effect.
+	 * The activate_traps path falls through to ERET (a CSE), but the
+	 * deactivate path still executes further EL2 sysreg work (CPTR/VBAR
+	 * writes below) before any natural CSE, so make the synchronisation
+	 * explicit.
+	 */
+	isb();

Sorry, but I don't understand this. Please can you explain why you think that CPTR and VBAR have an ordering dependency on HCR_EL2? Preferably, the comment would talk about the specific fields that are relevant.

Will

author
#8 lore raw

Re: [PATCH 2/8] KVM: arm64: Synchronise HCR_EL2 writes on the guest exit path

Hi Will,

Quoted 53 lines · Will Deacon
Quoted 51 lines · Fuad Tabba

MSR HCR_EL2 is not self-synchronising. Per ARM DDI 0487 M.b K1.2.4 (p.K1-16823) and B2.6.1 (p.B2-297), a Context Synchronisation Event is required between an HCR_EL2 write and any subsequent direct register access at the same EL that depends on the new value being in effect.

On the entry path, the HCR_EL2 write in __activate_traps is followed by further EL2 sysreg work (MDCR_EL2, CPTR_EL2, VBAR_EL2, and on the speculative-AT errata path SCTLR_EL1/TCR_EL1) before ERET into the guest. None of those intervening accesses depend on the new HCR_EL2 value, and ERET is a CSE per ARM DDI 0487 M.b D1.4.4.1 rule RBWCFK (p. D1-7209) conditional on SCTLR_EL2.EOS=1, which is set unconditionally by INIT_SCTLR_EL2_MMU_ON (see the prerequisite patch in this series). The requirement is therefore satisfied implicitly on the activate path.

The deactivate path is different: after write_sysreg_hcr() in __deactivate_traps() further EL2 sysreg work runs before any natural CSE - on nVHE, __deactivate_cptr_traps and the VBAR_EL2 write; on VHE, the timer context save which reads CNTP_CVAL_EL0 under the new TGE/E2H, and the EL1 sysreg restore. Add an explicit isb() at each of the two deactivate sites.

The practical impact today is bounded: HCR_EL2.E2H does not toggle in either path, and the trap bits being changed primarily affect EL1&0 behaviour. But the architectural rule should be honoured. Note that write_sysreg_hcr() itself already issues isb() on the Ampere errata path (sysreg.h), confirming the architectural expectation; the fast path optimises that away.

The fix is at the call sites rather than inside write_sysreg_hcr() because the macro has many users (e.g. the activate path, at.c, hardirq.h, ptrauth alternatives) where the immediately-following code either reaches ERET or has another CSE; making the macro emit an unconditional ISB would impose unnecessary cost on those well-formed users.

Fixes 9404673293b0 ("KVM: arm64: timers: Correctly handle TGE flip with CNTPOFF_EL2")
---
 arch/arm64/kvm/hyp/nvhe/switch.c | 11 +++++++++++
 arch/arm64/kvm/hyp/vhe/switch.c  | 11 +++++++++++
 2 files changed, 22 insertions(+)
arch/arm64/kvm/hyp/nvhe/switch.c +0 -0
index 8d1df3d33595..9d7ead5a5503 100644
@@ -105,6 +105,17 @@ static void __deactivate_traps(struct kvm_vcpu *vcpu)
      __deactivate_traps_common(vcpu);
 
Quoted 16 lines

arch/arm64/kvm/hyp/nvhe/switch.c static void __deactivate_traps(struct kvm_vcpu *vcpu) · line 118

Quoted 12 lines
arch/arm64/kvm/hyp/nvhe/switch.c +11 -0
      write_sysreg_hcr(this_cpu_ptr(&kvm_init_params)->hcr_el2);
+     /*
+      * MSR HCR_EL2 is not self-synchronising. Per ARM ARM K1.2.4 p.K1-16823
+      * and B2.6.1 p.B2-297, a Context Synchronisation Event is required
+      * between an HCR_EL2 write and any subsequent direct register access at
+      * the same EL that depends on the new value being in effect.
+      * The activate_traps path falls through to ERET (a CSE), but the
+      * deactivate path still executes further EL2 sysreg work (CPTR/VBAR
+      * writes below) before any natural CSE, so make the synchronisation
+      * explicit.
+      */
+     isb();

Sorry, but I don't understand this. Please can you explain why you think that CPTR and VBAR have an ordering dependency on HCR_EL2? Preferably, the comment would talk about the specific fields that are relevant.

You're right, I misread the spec in my excitement to fix an issue raised by my new and improved prompts. I went back to the access pseudocode for the registers being written after write_sysreg_hcr():

- CPTR_EL2/VBAR_EL2 (nVHE) are direct EL2-only registers; their write semantics at EL2 don't consult HCR_EL2.
- CPACR_EL1/VBAR_EL1/CNTP_CVAL_EL0 (VHE) redirect to their EL2 counterparts on ELIsInHost(EL2) — i.e., HCR_EL2.E2H — and E2H doesn't toggle here. TGE isn't a condition for these EL2-level accesses.

So the whole "depends on the new value being in effect" doesn't actually bite for any of the accesses I cited. I'll drop this patch. The natural CSEs cover whatever real synchronisation is needed.

Cheers,
/fuad

Quoted 2 lines

Will

author
#9 lore raw

PATCH 3/8 KVM: arm64: Guard against NULL vcpu on VHE hyp panic path

In reply to Fuad Tabba

On VHE, __hyp_call_panic() unconditionally calls __deactivate_traps(vcpu) on the vcpu pointer read from host_ctxt->__hyp_running_vcpu. That pointer is cleared after every guest exit (and is never set when no guest is running), so an unexpected EL2 exception landing in _guest_exit_panic, e.g. via the el2t*_invalid / el2h_irq_invalid vectors - reaches this function with vcpu == NULL. __deactivate_traps() then dereferences vcpu via ___deactivate_traps() -> vserror_state_is_nested() -> vcpu_has_nv() -> vcpu->arch.features, faulting inside the panic handler and obscuring the original failure.

The nVHE counterpart (hyp_panic() in arch/arm64/kvm/hyp/nvhe/switch.c) already guards its vcpu-using cleanup with "if (vcpu)"; mirror that here. sysreg_restore_host_state_vhe() and __hyp_do_panic() do not depend on vcpu and continue to run unconditionally, preserving panic forensics. The trailing panic("...VCPU:%p", vcpu) prints "(null)" safely via printk's %p handling.

Fixes 6a0259ed29bb ("KVM: arm64: Remove hyp_panic arguments")
---
 arch/arm64/kvm/hyp/vhe/switch.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
arch/arm64/kvm/hyp/vhe/switch.c +2 -1
index 140d3bcb5651..8912863cc238 100644
@@ -674,7 +674,8 @@ static void __noreturn __hyp_call_panic(u64 spsr, u64 elr, u64 par)
 	host_ctxt = host_data_ptr(host_ctxt);
 	vcpu = host_ctxt->__hyp_running_vcpu;
 
-	__deactivate_traps(vcpu);
+	if (vcpu)
+		__deactivate_traps(vcpu);
 	sysreg_restore_host_state_vhe(host_ctxt);
 
 	panic("HYP panic:\nPS:%08llx PC:%016llx ESR:%08llx\nFAR:%016llx HPFAR:%016llx PAR:%016llx\nVCPU:%p\n",
Signature · 1 line
2.54.0.545.g6539524ca2-goog
author
#10 lore raw

PATCH 4/8 KVM: arm64: Fix __deactivate_fgt macro parameter typo

In reply to Fuad Tabba

__deactivate_fgt() declares its first parameter as "htcxt" but the body references "hctxt". The parameter is unused; the macro silently captures "hctxt" from the enclosing scope. Both existing callers (__deactivate_traps_hfgxtr() and __deactivate_traps_ich_hfgxtr()) happen to define a local "struct kvm_cpu_context *hctxt", so the macro works by coincidence.

A future caller without an "hctxt" local in scope, or naming it differently, would compile but bind to the wrong context. Align the parameter name with the sibling __activate_fgt() macro.

The "vcpu" parameter remains unused in the body, kept for API symmetry with __activate_fgt() (which uses it).

Fixes f5a5a406b4b8 ("KVM: arm64: Propagate and handle Fine-Grained UNDEF bits")
---
 arch/arm64/kvm/hyp/include/hyp/switch.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/arm64/kvm/hyp/include/hyp/switch.h +1 -1
index 98b2976837b1..bf0eb5e43427 100644
@@ -245,7 +245,7 @@ static inline void __activate_traps_ich_hfgxtr(struct kvm_vcpu *vcpu)
 	__activate_fgt(hctxt, vcpu, ICH_HFGITR_EL2);
 }
 
-#define __deactivate_fgt(htcxt, vcpu, reg)				\
+#define __deactivate_fgt(hctxt, vcpu, reg)				\
 	do {								\
 		write_sysreg_s(ctxt_sys_reg(hctxt, reg),		\
 			       SYS_ ## reg);				\
Signature · 1 line
2.54.0.545.g6539524ca2-goog
author
#11 lore raw

PATCH 5/8 KVM: arm64: Propagate stage-2 map failure on host->guest share

In reply to Fuad Tabba

__pkvm_host_share_guest() mutates the host vmemmap for every page in the range (sets PKVM_PAGE_SHARED_OWNED and increments host_share_guest_count) and then calls kvm_pgtable_stage2_map() to install the guest stage-2 mapping. The stage-2 map's return value was wrapped in WARN_ON() and otherwise discarded.

At EL2 in nVHE/pKVM, WARN_ON() is not warn-and-continue: it expands to a BRK that enters the invalid-host-el2 vector and branches to hyp_panic(), declared __noreturn. WARN_ON of a reachable failure at EL2 is a panic primitive, not a debug aid.

kvm_pgtable_stage2_map() can fail in reachable ways: the stage-2 walker requests fresh pages from the caller's memcache and returns -ENOMEM when the memcache is exhausted mid-walk. The host controls the vcpu memcache via the topup interface, so an under-provisioned share request converts a recoverable error into a fatal hyp panic.

Capture the stage-2 map return value and propagate it. The walker may have installed leaf entries for some pages in the IPA range before failing, so unmap the range to clear any partial mappings; otherwise the guest would retain stage-2 access to pages the host is about to reclaim. Then roll back the host vmemmap mutations from the forward pass: the forward pass increments the count by 1 on every page, and the only forward state transition is OWNED -> SHARED_OWNED (the count 0 -> 1 transition). The reverse pass decrements the count and, if it drops back to zero, restores PKVM_PAGE_OWNED. Pages already SHARED_OWNED with other sharers (count > 1 after the forward pass) only need the count decremented.

Fixes d0bd3e6570ae ("KVM: arm64: Introduce __pkvm_host_share_guest()")
---
 arch/arm64/kvm/hyp/nvhe/mem_protect.c | 30 ++++++++++++++++++++++++---
 1 file changed, 27 insertions(+), 3 deletions(-)
arch/arm64/kvm/hyp/nvhe/mem_protect.c +27 -3
index 28a471d1927c..7044913a0758 100644
@@ -1458,9 +1458,33 @@ int __pkvm_host_share_guest(u64 pfn, u64 gfn, u64 nr_pages, struct pkvm_hyp_vcpu
 		page->host_share_guest_count++;
 	}
 
-	WARN_ON(kvm_pgtable_stage2_map(&vm->pgt, ipa, size, phys,
-				       pkvm_mkstate(prot, PKVM_PAGE_SHARED_BORROWED),
-				       &vcpu->vcpu.arch.pkvm_memcache, 0));
+	ret = kvm_pgtable_stage2_map(&vm->pgt, ipa, size, phys,
+				     pkvm_mkstate(prot, PKVM_PAGE_SHARED_BORROWED),
+				     &vcpu->vcpu.arch.pkvm_memcache, 0);
+	if (ret) {
+		/*
+		 * Stage-2 map can fail mid-walk (e.g. -ENOMEM from the
+		 * memcache), leaving partial leaf entries installed in the
+		 * guest stage-2. Tear them down before rolling back host
+		 * bookkeeping; otherwise the guest would retain access to
+		 * pages the host is about to reclaim as PKVM_PAGE_OWNED.
+		 */
+		kvm_pgtable_stage2_unmap(&vm->pgt, ipa, size);
+
+		/*
+		 * Roll back the host vmemmap mutations applied above. A page
+		 * whose host_share_guest_count is now 1 was PKVM_PAGE_OWNED
+		 * before this call (count 0->1, state OWNED->SHARED_OWNED);
+		 * undo both. A page with count > 1 was already
+		 * PKVM_PAGE_SHARED_OWNED with other sharers; only the count
+		 * needs to be decremented.
+		 */
+		for_each_hyp_page(page, phys, size) {
+			page->host_share_guest_count--;
+			if (!page->host_share_guest_count)
+				set_host_state(page, PKVM_PAGE_OWNED);
+		}
+	}
 
 unlock:
 	guest_unlock_component(vm);
Signature · 1 line
2.54.0.545.g6539524ca2-goog
author
#12 lore raw

PATCH 6/8 KVM: arm64: Propagate stage-2 map failure on host->guest donation

In reply to Fuad Tabba

__pkvm_host_donate_guest() flips the host stage-2 PTE for the donated page to a non-valid annotation (KVM_HOST_INVALID_PTE_TYPE_DONATION, owner = PKVM_ID_GUEST) via host_stage2_set_owner_metadata_locked() and then calls kvm_pgtable_stage2_map() to install the matching guest stage-2 mapping. The map's return value was wrapped in WARN_ON() and otherwise discarded.

At EL2 in nVHE/pKVM, WARN_ON() is not warn-and-continue: it expands to a BRK that enters the invalid-host-el2 vector and branches to hyp_panic(), declared __noreturn. WARN_ON of a reachable failure at EL2 is a panic primitive, not a debug aid.

kvm_pgtable_stage2_map() can fail in reachable ways even at PAGE_SIZE
granularity: __pkvm_host_donate_guest() verifies PKVM_NOPAGE for the guest IPA before the map, meaning no valid stage-2 entry exists. The walker must allocate new page-table pages from the vcpu memcache to install the mapping, returning -ENOMEM if exhausted. The host controls the vcpu memcache via the topup interface, so an under-provisioned donation request converts a recoverable error into a fatal hyp panic.

Capture the stage-2 map return value and propagate it. The walker may have installed partial leaf entries for the IPA before failing, so unmap the range to clear them; otherwise the guest would retain stage-2 access to a page the host is about to reclaim as PKVM_PAGE_OWNED. Then roll back the host stage-2 mutation: the only forward mutation is host_stage2_set_owner_metadata_locked() flipping the host vmemmap from PKVM_PAGE_OWNED to PKVM_NOPAGE and the host stage-2 PTE from idmap to invalid+annotation. host_stage2_set_owner_locked(_, _, PKVM_ID_HOST) restores both.

The rollback calls host_stage2_set_owner_locked() under WARN_ON. This is the correct use: host_stage2_set_owner_metadata_locked() just wrote the host leaf PTE as an invalid+annotation entry, so the reverse idmap rewrite cannot require new page-table allocation — it rewrites the leaf in-place. The WARN_ON asserts an impossible state under correct EL2 execution, semantically distinct from the misuse being fixed.

Fixes 1e579adca177 ("KVM: arm64: Introduce __pkvm_host_donate_guest()")
---
 arch/arm64/kvm/hyp/nvhe/mem_protect.c | 27 ++++++++++++++++++++++++---
 1 file changed, 24 insertions(+), 3 deletions(-)
arch/arm64/kvm/hyp/nvhe/mem_protect.c +24 -3
index 7044913a0758..b8c57a95e9bf 100644
@@ -1391,9 +1391,30 @@ int __pkvm_host_donate_guest(u64 pfn, u64 gfn, struct pkvm_hyp_vcpu *vcpu)
 	meta = host_stage2_encode_gfn_meta(vm, gfn);
 	WARN_ON(host_stage2_set_owner_metadata_locked(phys, PAGE_SIZE,
 						      PKVM_ID_GUEST, meta));
-	WARN_ON(kvm_pgtable_stage2_map(&vm->pgt, ipa, PAGE_SIZE, phys,
-				       pkvm_mkstate(KVM_PGTABLE_PROT_RWX, PKVM_PAGE_OWNED),
-				       &vcpu->vcpu.arch.pkvm_memcache, 0));
+	ret = kvm_pgtable_stage2_map(&vm->pgt, ipa, PAGE_SIZE, phys,
+				     pkvm_mkstate(KVM_PGTABLE_PROT_RWX, PKVM_PAGE_OWNED),
+				     &vcpu->vcpu.arch.pkvm_memcache, 0);
+	if (ret) {
+		/*
+		 * Stage-2 map can fail mid-walk (e.g. -ENOMEM from the
+		 * memcache), leaving partial leaf entries installed in the
+		 * guest stage-2. Tear them down before rolling back the host
+		 * stage-2; otherwise the guest would retain access to a page
+		 * the host is about to reclaim as PKVM_PAGE_OWNED.
+		 */
+		kvm_pgtable_stage2_unmap(&vm->pgt, ipa, PAGE_SIZE);
+
+		/*
+		 * Roll back the donation annotation applied above by
+		 * host_stage2_set_owner_metadata_locked() (host vmemmap
+		 * PKVM_NOPAGE -> PKVM_PAGE_OWNED, host stage-2 PTE
+		 * invalid+annotation -> idmap). The leaf PTE was just
+		 * installed by the forward call, so reinstating the idmap
+		 * rewrites it without needing fresh page-table pages from
+		 * host_s2_pool.
+		 */
+		WARN_ON(host_stage2_set_owner_locked(phys, PAGE_SIZE, PKVM_ID_HOST));
+	}
 
 unlock:
 	guest_unlock_component(vm);
Signature · 1 line
2.54.0.545.g6539524ca2-goog
maintainer
#13 lore raw

Re: [PATCH 6/8] KVM: arm64: Propagate stage-2 map failure on host->guest donation

Quoted 58 lines · Fuad Tabba

__pkvm_host_donate_guest() flips the host stage-2 PTE for the donated page to a non-valid annotation (KVM_HOST_INVALID_PTE_TYPE_DONATION, owner = PKVM_ID_GUEST) via host_stage2_set_owner_metadata_locked() and then calls kvm_pgtable_stage2_map() to install the matching guest stage-2 mapping. The map's return value was wrapped in WARN_ON() and otherwise discarded.

At EL2 in nVHE/pKVM, WARN_ON() is not warn-and-continue: it expands to a BRK that enters the invalid-host-el2 vector and branches to hyp_panic(), declared __noreturn. WARN_ON of a reachable failure at EL2 is a panic primitive, not a debug aid.

kvm_pgtable_stage2_map() can fail in reachable ways even at PAGE_SIZE
granularity: __pkvm_host_donate_guest() verifies PKVM_NOPAGE for the guest IPA before the map, meaning no valid stage-2 entry exists. The walker must allocate new page-table pages from the vcpu memcache to install the mapping, returning -ENOMEM if exhausted. The host controls the vcpu memcache via the topup interface, so an under-provisioned donation request converts a recoverable error into a fatal hyp panic.

Capture the stage-2 map return value and propagate it. The walker may have installed partial leaf entries for the IPA before failing, so unmap the range to clear them; otherwise the guest would retain stage-2 access to a page the host is about to reclaim as PKVM_PAGE_OWNED. Then roll back the host stage-2 mutation: the only forward mutation is host_stage2_set_owner_metadata_locked() flipping the host vmemmap from PKVM_PAGE_OWNED to PKVM_NOPAGE and the host stage-2 PTE from idmap to invalid+annotation. host_stage2_set_owner_locked(_, _, PKVM_ID_HOST) restores both.

The rollback calls host_stage2_set_owner_locked() under WARN_ON. This is the correct use: host_stage2_set_owner_metadata_locked() just wrote the host leaf PTE as an invalid+annotation entry, so the reverse idmap rewrite cannot require new page-table allocation — it rewrites the leaf in-place. The WARN_ON asserts an impossible state under correct EL2 execution, semantically distinct from the misuse being fixed.

Fixes 1e579adca177 ("KVM: arm64: Introduce __pkvm_host_donate_guest()")
---
 arch/arm64/kvm/hyp/nvhe/mem_protect.c | 27 ++++++++++++++++++++++++---
 1 file changed, 24 insertions(+), 3 deletions(-)
arch/arm64/kvm/hyp/nvhe/mem_protect.c +2 -3
index 7044913a0758..b8c57a95e9bf 100644
@@ -1391,9 +1391,30 @@ int __pkvm_host_donate_guest(u64 pfn, u64 gfn, struct pkvm_hyp_vcpu *vcpu)
 	meta = host_stage2_encode_gfn_meta(vm, gfn);
 	WARN_ON(host_stage2_set_owner_metadata_locked(phys, PAGE_SIZE,
 						      PKVM_ID_GUEST, meta));
-	WARN_ON(kvm_pgtable_stage2_map(&vm->pgt, ipa, PAGE_SIZE, phys,
-				       pkvm_mkstate(KVM_PGTABLE_PROT_RWX, PKVM_PAGE_OWNED),
-				       &vcpu->vcpu.arch.pkvm_memcache, 0));
+	ret = kvm_pgtable_stage2_map(&vm->pgt, ipa, PAGE_SIZE, phys,
+				     pkvm_mkstate(KVM_PGTABLE_PROT_RWX, PKVM_PAGE_OWNED),

arch/arm64/kvm/hyp/nvhe/mem_protect.c int __pkvm_host_donate_guest(u64 pfn, u64 gfn, struct pkvm_hyp_vcpu *vcpu) · line 1405

Quoted 10 lines
arch/arm64/kvm/hyp/nvhe/mem_protect.c +10 -0
+				     &vcpu->vcpu.arch.pkvm_memcache, 0);
+	if (ret) {
+		/*
+		 * Stage-2 map can fail mid-walk (e.g. -ENOMEM from the
+		 * memcache), leaving partial leaf entries installed in the
+		 * guest stage-2. Tear them down before rolling back the host
+		 * stage-2; otherwise the guest would retain access to a page
+		 * the host is about to reclaim as PKVM_PAGE_OWNED.
+		 */
+		kvm_pgtable_stage2_unmap(&vm->pgt, ipa, PAGE_SIZE);

Whoa, whoa, whoa.

First of all, this is mapping a single page, so the comment talking about "leaf entries" (plural) is bogus. If an operation to map a single page fails, then it makes no sense to try unmapping the mapping which we failed to create. What do you expect it to do?

On the other hand, if we extend this to handle ranges in future (which presumably we'll want as part of the THP support) then wouldn't this mean that a concurrent vCPU could have transiently written to the pages that _did_ get mapped, and now we're going to give those back to the host? That's really not ok! We're relying on these WARN_ON()s being fatal and they shouldn't fail because we perform all the permission checks first, in a separate pass.

If you want to improve this, then I think the options are either:

1. Check that the the memcache is topped up first
2. Poison the page (similar to the forced-reclaim path)
3. Tell the host about the pages it's lost and maybe it can leak them

(I vote for (1))

But we absolutely cannot do the simple rollback for the ownership changes; that's why the code is written to do the checks up-front. Your other patches at the end of this series have different flavours of the same issue.

If it's just about keeping the LLM happy, then either fix the LLM or make these BUG_ON() (in conjunction with (1) above).

Will

author
#14 lore raw

Re: [PATCH 6/8] KVM: arm64: Propagate stage-2 map failure on host->guest donation

Hi Will,

Quoted 94 lines · Will Deacon
Quoted 58 lines · Fuad Tabba

__pkvm_host_donate_guest() flips the host stage-2 PTE for the donated page to a non-valid annotation (KVM_HOST_INVALID_PTE_TYPE_DONATION, owner = PKVM_ID_GUEST) via host_stage2_set_owner_metadata_locked() and then calls kvm_pgtable_stage2_map() to install the matching guest stage-2 mapping. The map's return value was wrapped in WARN_ON() and otherwise discarded.

At EL2 in nVHE/pKVM, WARN_ON() is not warn-and-continue: it expands to a BRK that enters the invalid-host-el2 vector and branches to hyp_panic(), declared __noreturn. WARN_ON of a reachable failure at EL2 is a panic primitive, not a debug aid.

kvm_pgtable_stage2_map() can fail in reachable ways even at PAGE_SIZE
granularity: __pkvm_host_donate_guest() verifies PKVM_NOPAGE for the guest IPA before the map, meaning no valid stage-2 entry exists. The walker must allocate new page-table pages from the vcpu memcache to install the mapping, returning -ENOMEM if exhausted. The host controls the vcpu memcache via the topup interface, so an under-provisioned donation request converts a recoverable error into a fatal hyp panic.

Capture the stage-2 map return value and propagate it. The walker may have installed partial leaf entries for the IPA before failing, so unmap the range to clear them; otherwise the guest would retain stage-2 access to a page the host is about to reclaim as PKVM_PAGE_OWNED. Then roll back the host stage-2 mutation: the only forward mutation is host_stage2_set_owner_metadata_locked() flipping the host vmemmap from PKVM_PAGE_OWNED to PKVM_NOPAGE and the host stage-2 PTE from idmap to invalid+annotation. host_stage2_set_owner_locked(_, _, PKVM_ID_HOST) restores both.

The rollback calls host_stage2_set_owner_locked() under WARN_ON. This is the correct use: host_stage2_set_owner_metadata_locked() just wrote the host leaf PTE as an invalid+annotation entry, so the reverse idmap rewrite cannot require new page-table allocation — it rewrites the leaf in-place. The WARN_ON asserts an impossible state under correct EL2 execution, semantically distinct from the misuse being fixed.

Fixes 1e579adca177 ("KVM: arm64: Introduce __pkvm_host_donate_guest()")
---
 arch/arm64/kvm/hyp/nvhe/mem_protect.c | 27 ++++++++++++++++++++++++---
 1 file changed, 24 insertions(+), 3 deletions(-)
arch/arm64/kvm/hyp/nvhe/mem_protect.c +2 -3
index 7044913a0758..b8c57a95e9bf 100644
@@ -1391,9 +1391,30 @@ int __pkvm_host_donate_guest(u64 pfn, u64 gfn, struct pkvm_hyp_vcpu *vcpu)
      meta = host_stage2_encode_gfn_meta(vm, gfn);
      WARN_ON(host_stage2_set_owner_metadata_locked(phys, PAGE_SIZE,
                                                    PKVM_ID_GUEST, meta));
-     WARN_ON(kvm_pgtable_stage2_map(&vm->pgt, ipa, PAGE_SIZE, phys,
-                                    pkvm_mkstate(KVM_PGTABLE_PROT_RWX, PKVM_PAGE_OWNED),
-                                    &vcpu->vcpu.arch.pkvm_memcache, 0));
+     ret = kvm_pgtable_stage2_map(&vm->pgt, ipa, PAGE_SIZE, phys,
+                                  pkvm_mkstate(KVM_PGTABLE_PROT_RWX, PKVM_PAGE_OWNED),

arch/arm64/kvm/hyp/nvhe/mem_protect.c int __pkvm_host_donate_guest(u64 pfn, u64 gfn, struct pkvm_hyp_vcpu *vcpu) · line 1405

Quoted 10 lines
arch/arm64/kvm/hyp/nvhe/mem_protect.c +10 -0
+                                  &vcpu->vcpu.arch.pkvm_memcache, 0);
+     if (ret) {
+             /*
+              * Stage-2 map can fail mid-walk (e.g. -ENOMEM from the
+              * memcache), leaving partial leaf entries installed in the
+              * guest stage-2. Tear them down before rolling back the host
+              * stage-2; otherwise the guest would retain access to a page
+              * the host is about to reclaim as PKVM_PAGE_OWNED.
+              */
+             kvm_pgtable_stage2_unmap(&vm->pgt, ipa, PAGE_SIZE);

Whoa, whoa, whoa.

First of all, this is mapping a single page, so the comment talking about "leaf entries" (plural) is bogus. If an operation to map a single page fails, then it makes no sense to try unmapping the mapping which we failed to create. What do you expect it to do?

On the other hand, if we extend this to handle ranges in future (which presumably we'll want as part of the THP support) then wouldn't this mean that a concurrent vCPU could have transiently written to the pages that _did_ get mapped, and now we're going to give those back to the host? That's really not ok! We're relying on these WARN_ON()s being fatal and they shouldn't fail because we perform all the permission checks first, in a separate pass.

If you want to improve this, then I think the options are either:

1. Check that the the memcache is topped up first
2. Poison the page (similar to the forced-reclaim path)
3. Tell the host about the pages it's lost and maybe it can leak them

(I vote for (1))

Quoted 7 lines

But we absolutely cannot do the simple rollback for the ownership changes; that's why the code is written to do the checks up-front. Your other patches at the end of this series have different flavours of the same issue.

If it's just about keeping the LLM happy, then either fix the LLM or make these BUG_ON() (in conjunction with (1) above).

You're right, and no, it's not just about keeping em happy :D

The "leaf entries" comment on the single-page donate path is wrong, and more importantly the rollback model is unsound. The right fix is to tighten the precondition, not to handle a failure that shouldn't be reachable.

V2 will drop two patches (in addition to the HCR_EL2 one), and will be as follows:

1. host->guest share and host->guest donate (kept, rewritten): add a memcache-sufficiency check during the existing pre-check pass (option 1) and return -ENOMEM cleanly without touching any state. Restore the WARN_ON() on the subsequent kvm_pgtable_stage2_map() — with the topup precheck it asserts an established invariant rather than ignoring a reachable error.

For the single-page donate, "topped up" is KVM_PGTABLE_LAST_LEVEL - vm->pgt.start_level (mirroring host EL1's kvm_mmu_cache_min_pages). For multi-page share I plan to use the conservative nr_pages * (LAST_LEVEL - start_level) bound and flag it as conservative in the commit message; happy to compute a tighter alignment-aware bound if you'd prefer.

2. guest->host share and guest->host unshare (dropped): on reflection these shouldn't have been in V1 at all. As I did note in the commit message, failure path is not reachable. Again, too eager to make use of the new prompts.

I'll repost this as V2 if you agree.

Cheers,
/fuad

Quoted 2 lines

Will

maintainer
#15 lore raw

Re: [PATCH 6/8] KVM: arm64: Propagate stage-2 map failure on host->guest donation

Quoted 11 lines · Fuad Tabba

On Tue, 28 Apr 2026 at 14:45, Will Deacon <[email protected]> wrote:
V2 will drop two patches (in addition to the HCR_EL2 one), and will be as follows:

1. host->guest share and host->guest donate (kept, rewritten): add a memcache-sufficiency check during the existing pre-check pass (option 1) and return -ENOMEM cleanly without touching any state. Restore the WARN_ON() on the subsequent kvm_pgtable_stage2_map() — with the topup precheck it asserts an established invariant rather than ignoring a reachable error.

Quoted 6 lines

For the single-page donate, "topped up" is KVM_PGTABLE_LAST_LEVEL - vm->pgt.start_level (mirroring host EL1's kvm_mmu_cache_min_pages). For multi-page share I plan to use the conservative nr_pages * (LAST_LEVEL - start_level) bound and flag it as conservative in the commit message; happy to compute a tighter alignment-aware bound if you'd prefer.

For now, I think we should just check against kvm_mmu_cache_min_pages() because that's what the host is using.

Cheers,

Will

author
#16 lore raw

Re: [PATCH 6/8] KVM: arm64: Propagate stage-2 map failure on host->guest donation

Quoted 20 lines · Will Deacon
Quoted 11 lines · Fuad Tabba

On Tue, 28 Apr 2026 at 14:45, Will Deacon <[email protected]> wrote:
V2 will drop two patches (in addition to the HCR_EL2 one), and will be as follows:

1. host->guest share and host->guest donate (kept, rewritten): add a memcache-sufficiency check during the existing pre-check pass (option 1) and return -ENOMEM cleanly without touching any state. Restore the WARN_ON() on the subsequent kvm_pgtable_stage2_map() — with the topup precheck it asserts an established invariant rather than ignoring a reachable error.

Quoted 6 lines

For the single-page donate, "topped up" is KVM_PGTABLE_LAST_LEVEL - vm->pgt.start_level (mirroring host EL1's kvm_mmu_cache_min_pages). For multi-page share I plan to use the conservative nr_pages * (LAST_LEVEL - start_level) bound and flag it as conservative in the commit message; happy to compute a tighter alignment-aware bound if you'd prefer.

Quoted 2 lines

For now, I think we should just check against kvm_mmu_cache_min_pages() because that's what the host is using.

Ack,
/fuad

Quoted 4 lines

Cheers,

Will

author
#17 lore raw

PATCH 7/8 KVM: arm64: Propagate stage-2 map failure on guest->host share

In reply to Fuad Tabba

__pkvm_guest_share_host() updates the guest stage-2 PTE for a guest-OWNED page to PKVM_PAGE_SHARED_OWNED via kvm_pgtable_stage2_map() and then transitions the host vmemmap and stage-2 PTE to PKVM_PAGE_SHARED_BORROWED. The map's return value was wrapped in WARN_ON() and otherwise discarded.

At EL2 in nVHE/pKVM, WARN_ON() is not warn-and-continue: it expands to a BRK that enters the invalid-host-el2 vector and branches to hyp_panic(), declared __noreturn.

__pkvm_guest_share_host() calls get_valid_guest_pte() before the map, which verifies that a valid last-level (PAGE_SIZE) leaf PTE already exists for the IPA. Because the leaf and all intermediate tables are in place, the subsequent kvm_pgtable_stage2_map() replacing it cannot fail via -ENOMEM: no block to split, no new tables to install. The failure path is not currently reachable.

Nevertheless, WARN_ON() on any fallible call is the wrong pattern at
EL2: if the get_valid_guest_pte() precondition were ever relaxed, or the walker gained a new failure mode, the WARN_ON would convert a recoverable error into a fatal hyp panic. Capture the return value and propagate it. The unmap() is kept as a defensive guard for the currently unreachable failure path; no host-side unwinding is needed since the host vmemmap and stage-2 update is the next step and is correctly skipped on error.

Fixes 03313efed5e2 ("KVM: arm64: Implement the MEM_SHARE hypercall for protected VMs")
---
 arch/arm64/kvm/hyp/nvhe/mem_protect.c | 21 +++++++++++++++++----
 1 file changed, 17 insertions(+), 4 deletions(-)
arch/arm64/kvm/hyp/nvhe/mem_protect.c +17 -4
index b8c57a95e9bf..6fb546af699f 100644
@@ -979,10 +979,23 @@ int __pkvm_guest_share_host(struct pkvm_hyp_vcpu *vcpu, u64 gfn)
 	if (__host_check_page_state_range(phys, PAGE_SIZE, PKVM_NOPAGE))
 		goto unlock;
 
-	ret = 0;
-	WARN_ON(kvm_pgtable_stage2_map(&vm->pgt, ipa, PAGE_SIZE, phys,
-				       pkvm_mkstate(KVM_PGTABLE_PROT_RWX, PKVM_PAGE_SHARED_OWNED),
-				       &vcpu->vcpu.arch.pkvm_memcache, 0));
+	ret = kvm_pgtable_stage2_map(&vm->pgt, ipa, PAGE_SIZE, phys,
+				     pkvm_mkstate(KVM_PGTABLE_PROT_RWX, PKVM_PAGE_SHARED_OWNED),
+				     &vcpu->vcpu.arch.pkvm_memcache, 0);
+	if (ret) {
+		/*
+		 * Stage-2 map can fail mid-walk (e.g. -ENOMEM from the
+		 * memcache), leaving partial leaf entries in the guest
+		 * stage-2 transitioned to PKVM_PAGE_SHARED_OWNED. Tear
+		 * them down so the host does not see a partially-shared
+		 * mapping it has not yet acknowledged via the host
+		 * stage-2 update below. No host bookkeeping needs
+		 * unwinding here: the only mutation prior to the failed
+		 * map is the (now-discarded) guest stage-2 update itself.
+		 */
+		kvm_pgtable_stage2_unmap(&vm->pgt, ipa, PAGE_SIZE);
+		goto unlock;
+	}
 	WARN_ON(__host_set_page_state_range(phys, PAGE_SIZE, PKVM_PAGE_SHARED_BORROWED));
 unlock:
 	guest_unlock_component(vm);
Signature · 1 line
2.54.0.545.g6539524ca2-goog
author
#18 lore raw

PATCH 8/8 KVM: arm64: Propagate stage-2 map failure on guest->host unshare

In reply to Fuad Tabba

__pkvm_guest_unshare_host() re-acquires exclusive guest ownership of a page by (i) annotating the host stage-2 PTE via host_stage2_set_owner_metadata_locked(), (ii) mapping the page in the guest stage-2 as PKVM_PAGE_OWNED via kvm_pgtable_stage2_map(), and (iii) restoring host ownership via host_stage2_set_owner_locked(). The map's return value was wrapped in WARN_ON() and otherwise discarded.

At EL2 in nVHE/pKVM, WARN_ON() is not warn-and-continue: it expands to a BRK that enters the invalid-host-el2 vector and branches to hyp_panic(), declared __noreturn.

__pkvm_guest_unshare_host() calls get_valid_guest_pte() before the map, which verifies that a valid last-level (PAGE_SIZE) leaf PTE already exists for the IPA. Because the leaf and all intermediate tables are in place, the subsequent kvm_pgtable_stage2_map() replacing it cannot fail via -ENOMEM: no block to split, no new tables to install. The failure path is not currently reachable.

Nevertheless, WARN_ON() on any fallible call is the wrong pattern at EL2. Capture the return value and propagate it. The unmap() and host-side rollback are kept as defensive guards for the currently unreachable failure path. The rollback's WARN_ON(__host_set_page_state_range()) asserts an impossible state:
the host leaf PTE was just written by host_stage2_set_owner_metadata_locked(), so the reverse idmap rewrite cannot require new page-table allocation from host_s2_pool. This is the correct use of WARN_ON at EL2 — an impossible-state assertion, not a reachable error being ignored.

Fixes 246c976c370d ("KVM: arm64: Implement the MEM_UNSHARE hypercall for protected VMs")
---
 arch/arm64/kvm/hyp/nvhe/mem_protect.c | 37 ++++++++++++++++++---------
 1 file changed, 25 insertions(+), 12 deletions(-)
arch/arm64/kvm/hyp/nvhe/mem_protect.c +25 -12
index 6fb546af699f..12f3ea7a2d75 100644
@@ -984,14 +984,10 @@ int __pkvm_guest_share_host(struct pkvm_hyp_vcpu *vcpu, u64 gfn)
 				     &vcpu->vcpu.arch.pkvm_memcache, 0);
 	if (ret) {
 		/*
-		 * Stage-2 map can fail mid-walk (e.g. -ENOMEM from the
-		 * memcache), leaving partial leaf entries in the guest
-		 * stage-2 transitioned to PKVM_PAGE_SHARED_OWNED. Tear
-		 * them down so the host does not see a partially-shared
-		 * mapping it has not yet acknowledged via the host
-		 * stage-2 update below. No host bookkeeping needs
-		 * unwinding here: the only mutation prior to the failed
-		 * map is the (now-discarded) guest stage-2 update itself.
+		 * Defensive: get_valid_guest_pte() guarantees a last-level
+		 * leaf PTE already exists, so stage-2 map() cannot currently
+		 * fail here. The unmap() restores the IPA to a clean state as
+		 * a guard should the precondition ever change.
 		 */
 		kvm_pgtable_stage2_unmap(&vm->pgt, ipa, PAGE_SIZE);
 		goto unlock;
@@ -1024,13 +1020,30 @@ int __pkvm_guest_unshare_host(struct pkvm_hyp_vcpu *vcpu, u64 gfn)
 	if (__host_check_page_state_range(phys, PAGE_SIZE, PKVM_PAGE_SHARED_BORROWED))
 		goto unlock;
 
-	ret = 0;
 	meta = host_stage2_encode_gfn_meta(vm, gfn);
 	WARN_ON(host_stage2_set_owner_metadata_locked(phys, PAGE_SIZE,
 						      PKVM_ID_GUEST, meta));
-	WARN_ON(kvm_pgtable_stage2_map(&vm->pgt, ipa, PAGE_SIZE, phys,
-				       pkvm_mkstate(KVM_PGTABLE_PROT_RWX, PKVM_PAGE_OWNED),
-				       &vcpu->vcpu.arch.pkvm_memcache, 0));
+	ret = kvm_pgtable_stage2_map(&vm->pgt, ipa, PAGE_SIZE, phys,
+				     pkvm_mkstate(KVM_PGTABLE_PROT_RWX, PKVM_PAGE_OWNED),
+				     &vcpu->vcpu.arch.pkvm_memcache, 0);
+	if (ret) {
+		/*
+		 * Defensive: get_valid_guest_pte() guarantees a last-level
+		 * leaf PTE already exists, so stage-2 map() cannot currently
+		 * fail here. The unmap() and host-side rollback below are
+		 * kept as guards should the precondition ever change.
+		 */
+		kvm_pgtable_stage2_unmap(&vm->pgt, ipa, PAGE_SIZE);
+
+		/*
+		 * Roll back the host stage-2 mutation above: the host leaf
+		 * PTE was just written by host_stage2_set_owner_metadata_locked(),
+		 * so __host_set_page_state_range() rewrites it in-place
+		 * without needing fresh page-table pages from host_s2_pool.
+		 */
+		WARN_ON(__host_set_page_state_range(phys, PAGE_SIZE,
+						    PKVM_PAGE_SHARED_BORROWED));
+	}
 unlock:
 	guest_unlock_component(vm);
 	host_unlock_component();
Signature · 1 line
2.54.0.545.g6539524ca2-goog