git: 27b4bb447eab - main - powerpc: fix the VSCR save and restore on little endian

From: Piotr Kubaj <pkubaj_at_FreeBSD.org>
Date: Sat, 14 Nov 2026 12:12:11 UTC
The branch main has been updated by pkubaj:

URL: https://cgit.FreeBSD.org/src/commit/?id=27b4bb447eababd60da777065a813d2379050850

commit 27b4bb447eababd60da777065a813d2379050850
Author:     Piotr Kubaj <pkubaj@FreeBSD.org>
AuthorDate: 2026-10-18 10:41:39 +0000
Commit:     Piotr Kubaj <pkubaj@FreeBSD.org>
CommitDate: 2026-11-14 12:06:34 +0000

    powerpc: fix the VSCR save and restore on little endian
    
    VSCR was saved and restored through stvewx/lvewx at byte 12 of a
    16 byte slot. Which element those instructions move at a given address
    depends on the byte order, so on little-endian kernels they touched VR
    bits 0-31 instead of the 96-127 where mfvscr/mtvscr keep VSCR: every
    context switch and signal reset VSCR to 0, losing NJ and SAT.
    Replicate the word into all four elements first so that the element
    choice no longer matters.
    
    VSCR[NJ] set with mtvscr read back as 0 after a usleep on a
    little-endian kernel; it is preserved now.
    
    Reviewed by:    adrian, jhibbits
    MFC after:      1 week
    Differential Revision:  https://reviews.freebsd.org/D61525
---
 sys/powerpc/powerpc/altivec.c | 22 ++++++++++++++++++++--
 1 file changed, 20 insertions(+), 2 deletions(-)

diff --git a/sys/powerpc/powerpc/altivec.c b/sys/powerpc/powerpc/altivec.c
index c4f356875af0..928e5cf2f0eb 100644
--- a/sys/powerpc/powerpc/altivec.c
+++ b/sys/powerpc/powerpc/altivec.c
@@ -71,7 +71,15 @@ save_vec_int(struct thread *td)
 	STVX(28);	STVX(29);	STVX(30);	STVX(31);
 #undef STVX
 
-	__asm __volatile("mfvscr 0; stvewx 0,0,%0" :: "b"(&pcb->pcb_vec.vscr));
+	/*
+	 * mfvscr places VSCR in bits 96-127 of the vector register, but
+	 * which word stvewx stores at a given address depends on the byte
+	 * order (in little-endian mode element positions are reversed).
+	 * Replicate VSCR into all four words first, so the store is right
+	 * either way.
+	 */
+	__asm __volatile("mfvscr 0; vspltw 0,0,3; stvewx 0,0,%0"
+	    :: "b"(&pcb->pcb_vec.vscr));
 
 	/*
 	 * Disable vector unit again
@@ -123,8 +131,18 @@ enable_vec(struct thread *td)
 	 * (this needs to done before loading the user's vector registers
 	 * since we need to use a scratch vector register)
 	 */
-	__asm __volatile("vxor 0,0,0; lvewx 0,0,%0; mtvscr 0" \
+	/*
+	 * lvewx loads the word into whichever element the byte order maps
+	 * that address to; replicate it into all words so that mtvscr finds
+	 * it in bits 96-127 either way.
+	 */
+#if _BYTE_ORDER == _BIG_ENDIAN
+	__asm __volatile("lvewx 0,0,%0; vspltw 0,0,3; mtvscr 0" \
+			  :: "b"(&pcb->pcb_vec.vscr));
+#else
+	__asm __volatile("lvewx 0,0,%0; vspltw 0,0,0; mtvscr 0" \
 			  :: "b"(&pcb->pcb_vec.vscr));
+#endif
 
 #define LVX(n)   __asm ("lvx " #n ",0,%0" \
 		:: "b"(&pcb->pcb_vec.vr[n]));