[PATCH v6 22/26] x86/fpu/xstate: Skip writing zeros to signal frame for dynamic user states if in INIT-state

From: Chang S. Bae
Date: Wed Jun 30 2021 - 02:09:38 EST


By default, for XSTATE features in the INIT-state, XSAVE writes zeros to
the uncompressed destination buffer.

E.g., if you are not using AVX-512, you will still get a bunch of zeros on
the signal stack where live AVX-512 data would go.

For 'dynamic user state' (currently only XTILEDATA), explicitly skip this
data transfer. The result is that the user buffer for the AMX region will
not be touched by XSAVE.

[ Reading XINUSE takes about 20-30 cycles, but writing zeros consumes about
5-times or more, e.g., for XTILEDATA. ]

Signed-off-by: Chang S. Bae <chang.seok.bae@xxxxxxxxx>
Reviewed-by: Len Brown <len.brown@xxxxxxxxx>
Cc: x86@xxxxxxxxxx
Cc: linux-kernel@xxxxxxxxxxxxxxx
---
Changes from v5:
* Mentioned the optimization trade-offs in the changelog. (Dave Hansen)
* Added code comment.

Changes from v4:
* Added as a new patch.
---
arch/x86/include/asm/fpu/internal.h | 35 ++++++++++++++++++++++-------
1 file changed, 27 insertions(+), 8 deletions(-)

diff --git a/arch/x86/include/asm/fpu/internal.h b/arch/x86/include/asm/fpu/internal.h
index 4f1652784088..a7541d0e5057 100644
--- a/arch/x86/include/asm/fpu/internal.h
+++ b/arch/x86/include/asm/fpu/internal.h
@@ -338,7 +338,7 @@ static inline void os_xrstor(struct xregs_state *xstate, u64 mask)
static inline int xsave_to_user_sigframe(struct xregs_state __user *buf)
{
u32 lmask, hmask;
- u64 mask;
+ u64 state_mask;
int err;

/*
@@ -346,20 +346,39 @@ static inline int xsave_to_user_sigframe(struct xregs_state __user *buf)
* internally, e.g. PKRU. That's user space ABI and also required
* to allow the signal handler to modify PKRU.
*/
- mask = xfeatures_mask_uabi();
+ state_mask = xfeatures_mask_uabi();
+
+ if (!xfeatures_mask_user_dynamic)
+ goto mask_ready;

/*
* When any dynamic user state is enabled, exclude dynamic user
* states for non-opt-in threads.
*/
- if (xfeatures_mask_user_dynamic) {
- mask &= test_thread_flag(TIF_XSTATE_PERM) ?
- current->thread.fpu.state_mask :
- ~xfeatures_mask_user_dynamic;
+ if (!test_thread_flag(TIF_XSTATE_PERM)) {
+ state_mask &= ~xfeatures_mask_user_dynamic;
+ } else {
+ u64 dynamic_state_mask;
+
+ state_mask &= current->thread.fpu.state_mask;
+
+ dynamic_state_mask = state_mask & xfeatures_mask_user_dynamic;
+ if (dynamic_state_mask && boot_cpu_has(X86_FEATURE_XGETBV1)) {
+ u64 dynamic_xinuse, dynamic_init;
+ u64 xinuse = xgetbv(1);
+
+ dynamic_xinuse = xinuse & dynamic_state_mask;
+ dynamic_init = ~xinuse & dynamic_state_mask;
+ if (dynamic_init) {
+ state_mask &= ~xfeatures_mask_user_dynamic;
+ state_mask |= dynamic_xinuse;
+ }
+ }
}

- lmask = mask;
- hmask = mask >> 32;
+mask_ready:
+ lmask = state_mask;
+ hmask = state_mask >> 32;

/*
* Clear the xsave header first, so that reserved fields are
--
2.17.1