git: 9b16d1435123 - stable/13 - amd64: do not enable PKRU if user disabled saving PKRU register in xsave mask

From: Konstantin Belousov <kib_at_FreeBSD.org>
Date: Fri, 03 Feb 2023 00:27:01 UTC
The branch stable/13 has been updated by kib:

URL: https://cgit.FreeBSD.org/src/commit/?id=9b16d143512368ac33988c6ae54e7939db2ed036

commit 9b16d143512368ac33988c6ae54e7939db2ed036
Author:     Konstantin Belousov <kib@FreeBSD.org>
AuthorDate: 2023-01-27 10:45:02 +0000
Commit:     Konstantin Belousov <kib@FreeBSD.org>
CommitDate: 2023-02-03 00:26:12 +0000

    amd64: do not enable PKRU if user disabled saving PKRU register in xsave mask
    
    (cherry picked from commit 153643a5bc8ac3b1d47fc8e4de18d8c8a59817da)
---
 sys/amd64/amd64/fpu.c | 18 +++++++++++++++++-
 1 file changed, 17 insertions(+), 1 deletion(-)

diff --git a/sys/amd64/amd64/fpu.c b/sys/amd64/amd64/fpu.c
index 8be69a347d63..f51c042bf8de 100644
--- a/sys/amd64/amd64/fpu.c
+++ b/sys/amd64/amd64/fpu.c
@@ -394,6 +394,7 @@ void
 fpuinit(void)
 {
 	register_t saveintr;
+	uint64_t cr4;
 	u_int mxcsr;
 	u_short control;
 
@@ -401,7 +402,22 @@ fpuinit(void)
 		fpuinit_bsp1();
 
 	if (use_xsave) {
-		load_cr4(rcr4() | CR4_XSAVE);
+		cr4 = rcr4();
+
+		/*
+		 * Revert enablement of PKRU if user disabled its
+		 * saving on context switches by clearing the bit in
+		 * the xsave mask.  Also redundantly clear the bit in
+		 * cpu_stdext_feature2 to prevent pmap from ever
+		 * trying to set the page table bits.
+		 */
+		if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0 &&
+		    (xsave_mask & XFEATURE_ENABLED_PKRU) == 0) {
+			cr4 &= ~CR4_PKE;
+			cpu_stdext_feature2 &= ~CPUID_STDEXT2_PKU;
+		}
+
+		load_cr4(cr4 | CR4_XSAVE);
 		load_xcr(XCR0, xsave_mask);
 	}