Skip to contentSkip to conversation

x86: memcpy() / memset() (non-)ERMS flavors plus fallout

PATCH Superseded Jan Beulich 3 participants 21 messages Jun 16, 2025 – Jun 30, 2025 RISC-V

v6 of 7 Superseded Latest is v7 →

lore
Share & tools
lore
#0 lore raw

v6 cover x86: memcpy() / memset() (non-)ERMS flavors plus fallout

While the performance varies quite a bit on older (pre-ERMS) and newer (ERMS) hardware, so far we've been going with just a single flavor of these two functions, and oddly enough with ones not consistent with one another. Using plain memcpy() / memset() on MMIO (video frame buffer) is generally okay, but the ERMS variant of memcpy() turned out to regress (boot) performance in a way easily visible to the human eye (meanwhile addressed by using ioremap_wc() there).

1: x86: suppress ERMS for internal use when MISC_ENABLE.FAST_STRING is clear 2: x86/alternatives: serialize after (self-)modifying code
3: x86: re-work memset()
4: x86: re-work memcpy()
5: x86: control memset() and memcpy() inlining
6: x86: introduce "hot" and "cold" page clearing functions
7: mm: allow page scrubbing routine(s) to be arch controlled

Jan

#1 lore raw

PATCH v6 1/7 x86: suppress ERMS for internal use when MISC_ENABLE.FAST_STRING is clear

Before we start actually adjusting behavior when ERMS is available, follow Linux commit 161ec53c702c ("x86, mem, intel: Initialize Enhanced REP MOVSB/STOSB") and zap the CPUID-derived feature flag when the MSR bit is clear. Don't extend the artificial clearing to guest view,
though: Guests can take their own decision in this regard, as they can read (most of) MISC_ENABLE.

---
TBD: Would be nice if "cpuid=no-erms" propagated to guest view (for
"cpuid=" generally meaning to affect guests as well as Xen), but since both disabling paths use setup_clear_cpu_cap() they're indistinguishable in guest_common_feature_adjustments(). A separate boolean could take care of this, but would look clumsy to me.
---
v5: Correct guest_common_max_feature_adjustments() addition.
v4: Also adjust guest_common_max_feature_adjustments().
v3: New.

xen/arch/x86/cpu/intel.c +10 -0
@@ -366,8 +366,18 @@ static void cf_check early_init_intel(st
 		paddr_bits = 36;
 
 	if (c == &boot_cpu_data) {
+		uint64_t misc_enable;
+
 		check_memory_type_self_snoop_errata();
 
+		/*
+		 * If fast string is not enabled in IA32_MISC_ENABLE for any reason,
+		 * clear the enhanced fast string CPU capability.
+		 */
+		rdmsrl(MSR_IA32_MISC_ENABLE, misc_enable);
+		if (!(misc_enable & MSR_IA32_MISC_ENABLE_FAST_STRING))
+			setup_clear_cpu_cap(X86_FEATURE_ERMS);
+
 		intel_init_levelling();
 	}
 
xen/arch/x86/cpu-policy.c +16 -0
@@ -487,6 +487,12 @@ static void __init guest_common_max_feat
      */
     if ( test_bit(X86_FEATURE_RTM, fs) )
         __set_bit(X86_FEATURE_RTM_ALWAYS_ABORT, fs);
+
+    /*
+     * We expose MISC_ENABLE to guests, so our internal clearing of ERMS when
+     * FAST_STRING is not set should not affect the view of migrating-in guests.
+     */
+    __set_bit(X86_FEATURE_ERMS, fs);
 }
 
 static void __init guest_common_default_feature_adjustments(uint32_t *fs)
@@ -567,6 +573,16 @@ static void __init guest_common_default_
         __clear_bit(X86_FEATURE_RTM, fs);
         __set_bit(X86_FEATURE_RTM_ALWAYS_ABORT, fs);
     }
+
+    /*
+     * We expose MISC_ENABLE to guests, so our internal clearing of ERMS when
+     * FAST_STRING is not set should not propagate to guest view.  Guests can
+     * judge on their own whether to ignore the CPUID bit when the MSR bit is
+     * clear.  The bit being uniformly set in the max policies, we only need
+     * to clear it here (if hardware doesn't have it).
+     */
+    if ( !raw_cpu_policy.feat.erms )
+        __clear_bit(X86_FEATURE_ERMS, fs);
 }
 
 static void __init guest_common_feature_adjustments(uint32_t *fs)
xen/arch/x86/include/asm/msr-index.h +1 -0
@@ -493,6 +493,7 @@
 #define MSR_IA32_THERM_INTERRUPT	0x0000019b
 #define MSR_IA32_THERM_STATUS		0x0000019c
 #define MSR_IA32_MISC_ENABLE		0x000001a0
+#define MSR_IA32_MISC_ENABLE_FAST_STRING  (1<<0)
 #define MSR_IA32_MISC_ENABLE_PERF_AVAIL   (1<<7)
 #define MSR_IA32_MISC_ENABLE_BTS_UNAVAIL  (1<<11)
 #define MSR_IA32_MISC_ENABLE_PEBS_UNAVAIL (1<<12)
Reviewed-by on v6 1/7
#2 lore raw

Re: [PATCH v6 1/7] x86: suppress ERMS for internal use when MISC_ENABLE.FAST_STRING is clear

Quoted 8 lines · Jan Beulich

Before we start actually adjusting behavior when ERMS is available, follow Linux commit 161ec53c702c ("x86, mem, intel: Initialize Enhanced REP MOVSB/STOSB") and zap the CPUID-derived feature flag when the MSR bit is clear. Don't extend the artificial clearing to guest view,
though: Guests can take their own decision in this regard, as they can read (most of) MISC_ENABLE.

#3 lore raw

Re: [PATCH v6 1/7] x86: suppress ERMS for internal use when MISC_ENABLE.FAST_STRING is clear

In reply to Jan Beulich

xen/arch/x86/cpu-policy.c static void __init guest_common_max_feat · line 494

Quoted 11 lines · Jan Beulich
xen/arch/x86/cpu-policy.c +5 -0
@@ -487,6 +487,12 @@ static void __init guest_common_max_feat
      */
     if ( test_bit(X86_FEATURE_RTM, fs) )
         __set_bit(X86_FEATURE_RTM_ALWAYS_ABORT, fs);
+
+    /*
+     * We expose MISC_ENABLE to guests, so our internal clearing of ERMS when
+     * FAST_STRING is not set should not affect the view of migrating-in guests.
+     */

The logic is ok, but the justification wants to be different.

"ERMS is a performance hint.  A VM which previously saw ERMS will function correctly when migrated here, even if ERMS isn't available."

What Xen chooses to do with the bit isn't relevant to why we unconditionally set it in the max featureset.

Quoted 6 lines
xen/arch/x86/cpu-policy.c +1 -0
+    __set_bit(X86_FEATURE_ERMS, fs);
 }
 
 static void __init guest_common_default_feature_adjustments(uint32_t *fs)
@@ -567,6 +573,16 @@ static void __init guest_common_default_
         __clear_bit(X86_FEATURE_RTM, fs);

xen/arch/x86/cpu-policy.c static void __init guest_common_default_ · line 583

Quoted 10 lines
xen/arch/x86/cpu-policy.c +8 -0
         __set_bit(X86_FEATURE_RTM_ALWAYS_ABORT, fs);
     }
+
+    /*
+     * We expose MISC_ENABLE to guests, so our internal clearing of ERMS when
+     * FAST_STRING is not set should not propagate to guest view.  Guests can
+     * judge on their own whether to ignore the CPUID bit when the MSR bit is
+     * clear.  The bit being uniformly set in the max policies, we only need
+     * to clear it here (if hardware doesn't have it).
+     */

"ERMS is a performance hint, so is set unconditionally in the max policy.  However, the guest should default to the host setting."

xen/arch/x86/cpu-policy.c static void __init guest_common_default_ · line 584

Quoted 1 line
xen/arch/x86/cpu-policy.c +1 -0
+    if ( !raw_cpu_policy.feat.erms )

This wants to be the host policy, not the raw policy.  That's why cpuid=no-erms isn't working in the way you'd expect.

cpuid=no-$foo means "Xen should behave as if $foo wasn't reported by hardware", and that includes not giving it to guests by default.

xen/arch/x86/cpu-policy.c static void __init guest_common_default_ · line 587

Quoted 3 lines
xen/arch/x86/cpu-policy.c +1 -0
+        __clear_bit(X86_FEATURE_ERMS, fs);
 }
 

It occurs to me that there are quite a few examples of clear/cond-set which could be converted to cond-clear like this

I'll do a prep patch to make things consistent.  It shouldn't conflict with this, but I'd prefer to keep the function logic consistent; it's hard enough to follow already.

~Andrew

P.S. I don't have time right now, but this is yet another example that could be eliminated with an annotation meaning "set in max, host in default".  I'll try to find some time to make this happen, because there's clearly a pattern now.

#4 lore raw

Re: [PATCH v6 1/7] x86: suppress ERMS for internal use when MISC_ENABLE.FAST_STRING is clear

Quoted 15 lines · Andrew Cooper

xen/arch/x86/cpu-policy.c static void __init guest_common_max_feat · line 494

Quoted 11 lines · Jan Beulich
xen/arch/x86/cpu-policy.c +5 -0
@@ -487,6 +487,12 @@ static void __init guest_common_max_feat
      */
     if ( test_bit(X86_FEATURE_RTM, fs) )
         __set_bit(X86_FEATURE_RTM_ALWAYS_ABORT, fs);
+
+    /*
+     * We expose MISC_ENABLE to guests, so our internal clearing of ERMS when
+     * FAST_STRING is not set should not affect the view of migrating-in guests.
+     */

The logic is ok, but the justification wants to be different.

Quoted 5 lines

"ERMS is a performance hint.  A VM which previously saw ERMS will function correctly when migrated here, even if ERMS isn't available."

What Xen chooses to do with the bit isn't relevant to why we unconditionally set it in the max featureset.

It's different words for effectively the same thing, to me at least. I can certainly use your wording, ...

Quoted 7 lines
Quoted 7 lines
xen/arch/x86/cpu-policy.c +3 -0
@@ -567,6 +573,16 @@ static void __init guest_common_default_
         __clear_bit(X86_FEATURE_RTM, fs);
         __set_bit(X86_FEATURE_RTM_ALWAYS_ABORT, fs);
     }
+
+    /*
+     * We expose MISC_ENABLE to guests, so our internal clearing of ERMS when
Quoted 8 lines

xen/arch/x86/cpu-policy.c static void __init guest_common_default_ · line 583

Quoted 5 lines
xen/arch/x86/cpu-policy.c +5 -0
+     * FAST_STRING is not set should not propagate to guest view.  Guests can
+     * judge on their own whether to ignore the CPUID bit when the MSR bit is
+     * clear.  The bit being uniformly set in the max policies, we only need
+     * to clear it here (if hardware doesn't have it).
+     */

"ERMS is a performance hint, so is set unconditionally in the max policy.  However, the guest should default to the host setting."

... also here.

Quoted 7 lines

xen/arch/x86/cpu-policy.c static void __init guest_common_default_ · line 584

Quoted 1 line
xen/arch/x86/cpu-policy.c +1 -0
+    if ( !raw_cpu_policy.feat.erms )

This wants to be the host policy, not the raw policy.  That's why cpuid=no-erms isn't working in the way you'd expect.

cpuid=no-$foo means "Xen should behave as if $foo wasn't reported by hardware", and that includes not giving it to guests by default.

Hmm, interesting. That's definitely not the meaning I give this. To me it means merely Xen shouldn't use the feature (with an impact on guests only when the feature in hardware is required to surface it to guests). I don't think we have the precise meaning of this option written down anywhere?

Quoted 10 lines

xen/arch/x86/cpu-policy.c static void __init guest_common_default_ · line 587

Quoted 3 lines
xen/arch/x86/cpu-policy.c +1 -0
+        __clear_bit(X86_FEATURE_ERMS, fs);
 }
 

It occurs to me that there are quite a few examples of clear/cond-set which could be converted to cond-clear like this

I'll do a prep patch to make things consistent.  It shouldn't conflict with this, but I'd prefer to keep the function logic consistent; it's hard enough to follow already.

Right, I too noticed that there are others which could be swapped over. I actually had it the other way around in early versions of the series, and it was only in the course of some re-work where I noticed it might be a little tidier this way. But I first wanted to see whether perhaps I have some thinko there, so didn't want to convert anything pre-existing.

Jan

#5 lore raw

Re: [PATCH v6 1/7] x86: suppress ERMS for internal use when MISC_ENABLE.FAST_STRING is clear

Quoted 7 lines · Jan Beulich
Quoted 6 lines · Andrew Cooper
Quoted 1 line · Jan Beulich

+ if ( !raw_cpu_policy.feat.erms )

This wants to be the host policy, not the raw policy.  That's why cpuid=no-erms isn't working in the way you'd expect.

Quoted 8 lines
Quoted 2 lines

cpuid=no-$foo means "Xen should behave as if $foo wasn't reported by hardware", and that includes not giving it to guests by default.

Hmm, interesting. That's definitely not the meaning I give this. To me it means merely Xen shouldn't use the feature (with an impact on guests only when the feature in hardware is required to surface it to guests). I don't think we have the precise meaning of this option written down anywhere?

Then again I notice what you ask for is in line with uses of cpu_has_* (where available) elsewhere (e.g. in your "x86/cpu-policy: Simplify logic in guest_common_default_feature_adjustments()"), with calculate_host_policy() simply copying boot_cpu_data.x86_capability into the host policy. So yes, I guess I'll need to adjust.

Ftaod, this still leaves open what exact meaning "cpuid=no-..." ought to have. While kind of an example in the opposite direction, consider e.g. "cpuid=no-lm": This cannot sensibly have any effect on Xen itself. It could plausibly mean to permit only 32-bit guests.

Jan

#6 lore raw

PATCH v6 2/7 x86/alternatives: serialize after (self-)modifying code

In reply to Jan Beulich

While supposedly safe via enforcing a control flow change when modifying already prefetched code, it may not really be. Afaik a request is pending to drop the first of the two options in the SDM's "Handling Self- and Cross-Modifying Code" section (still present there as of version 087). Insert a serializing instruction there, and remove the "noinline" in exchange.

---
Strictly speaking with LIVEPATCH=n the if() (but not its body) is dead code. Adding IS_ENABLED(CONFIG_LIVEPATCH) would feel quite a bit like extra clutter, though. Plus Misra rule 2.2 is globally deviated anyway.
---
v6: Split off. Extend commentary. Load deterministic value into CR2.
Drop "noinline".

xen/arch/x86/alternative.c +8 -3
@@ -194,13 +194,18 @@ void *place_ret(void *ptr)
  * You should run this with interrupts disabled or on code that is not
  * executing.
  *
- * "noinline" to cause control flow change and thus invalidate I$ and
- * cause refetch after modification.
+ * While the SDM continues to suggest using "noinline" would be sufficient, it
+ * may not be, e.g. due to errata.  Issue a serializing insn afterwards, unless
+ * this is for live-patching, where we modify code before it goes live.  Issue
+ * a serializing insn which is unlikely to be intercepted by a hypervisor, in
+ * case we run virtualized ourselves.
  */
-static void init_or_livepatch noinline
+static void init_or_livepatch
 text_poke(void *addr, const void *opcode, size_t len)
 {
     memcpy(addr, opcode, len);
+    if ( system_state < SYS_STATE_active )
+        asm volatile ( "mov %0, %%cr2" :: "r" (0L) : "memory" );
 }
 
 extern void *const __initdata_cf_clobber_start[];
Reviewed-by on v6 2/7
#7 lore raw

Re: [PATCH v6 2/7] x86/alternatives: serialize after (self-)modifying code

Quoted 8 lines · Jan Beulich

While supposedly safe via enforcing a control flow change when modifying already prefetched code, it may not really be. Afaik a request is pending to drop the first of the two options in the SDM's "Handling Self- and Cross-Modifying Code" section (still present there as of version 087). Insert a serializing instruction there, and remove the "noinline" in exchange.

#8 lore raw

PATCH v6 3/7 x86: re-work memset()

In reply to Jan Beulich

Move the function to its own assembly file. Having it in C just for the entire body to be an asm() isn't really helpful. Then have two flavors:
A "basic" version using qword steps for the bulk of the operation, and an ERMS version for modern hardware, to be substituted in via alternatives patching.

For RET to be usable in an alternative's replacement code, extend the CALL/JMP patching to cover the case of "JMP __x86_return_thunk" coming last in replacement code.

---
We may want to consider branching over the REP STOSQ as well, if the number of qwords turns out to be zero.
We may also want to consider using non-REP STOS{L,W,B} for the tail.
---
v5: Re-base.
v4: Use %r8 instead of %rsi in a few places.
v3: Re-base.

xen/arch/x86/Makefile +1 -0
@@ -47,6 +47,7 @@ obj-$(CONFIG_RETURN_THUNK) += indirect-t
 obj-$(CONFIG_PV) += ioport_emulate.o
 obj-y += irq.o
 obj-$(CONFIG_KEXEC) += machine_kexec.o
+obj-y += memset.o
 obj-y += mm.o x86_64/mm.o
 obj-$(CONFIG_VM_EVENT) += monitor.o
 obj-y += mpparse.o
xen/arch/x86/alternative.c +6 -0
@@ -351,6 +351,12 @@ static int init_or_livepatch _apply_alte
         /* 0xe8/0xe9 are relative branches; fix the offset. */
         if ( a->repl_len >= 5 && (*buf & 0xfe) == 0xe8 )
             *(int32_t *)(buf + 1) += repl - orig;
+        else if ( IS_ENABLED(CONFIG_RETURN_THUNK) &&
+                  a->repl_len > 5 && buf[a->repl_len - 5] == 0xe9 &&
+                  ((long)repl + a->repl_len +
+                   *(int32_t *)(buf + a->repl_len - 4) ==
+                   (long)__x86_return_thunk) )
+            *(int32_t *)(buf + a->repl_len - 4) += repl - orig;
 
         a->priv = 1;
 
xen/arch/x86/memset.S new file +30 -0
@@ -0,0 +1,30 @@
+#include <asm/asm_defns.h>
+
+.macro memset
+        and     $7, %edx
+        shr     $3, %rcx
+        movzbl  %sil, %esi
+        mov     $0x0101010101010101, %rax
+        imul    %rsi, %rax
+        mov     %rdi, %r8
+        rep stosq
+        or      %edx, %ecx
+        jz      0f
+        rep stosb
+0:
+        mov     %r8, %rax
+        RET
+.endm
+
+.macro memset_erms
+        mov     %esi, %eax
+        mov     %rdi, %r8
+        rep stosb
+        mov     %r8, %rax
+        RET
+.endm
+
+FUNC(memset)
+        mov     %rdx, %rcx
+        ALTERNATIVE memset, memset_erms, X86_FEATURE_ERMS
+END(memset)
xen/arch/x86/string.c +0 -13
@@ -22,19 +22,6 @@ void *(memcpy)(void *dest, const void *s
     return dest;
 }
 
-void *(memset)(void *s, int c, size_t n)
-{
-    long d0, d1;
-
-    asm volatile (
-        "rep stosb"
-        : "=&c" (d0), "=&D" (d1)
-        : "a" (c), "1" (s), "0" (n)
-        : "memory");
-
-    return s;
-}
-
 void *(memmove)(void *dest, const void *src, size_t n)
 {
     long d0, d1, d2;
Reviewed-by on v6 3/7
#9 lore raw

Re: [PATCH v6 3/7] x86: re-work memset()

Quoted 11 lines · Jan Beulich

Move the function to its own assembly file. Having it in C just for the entire body to be an asm() isn't really helpful. Then have two flavors:
A "basic" version using qword steps for the bulk of the operation, and an ERMS version for modern hardware, to be substituted in via alternatives patching.

For RET to be usable in an alternative's replacement code, extend the CALL/JMP patching to cover the case of "JMP __x86_return_thunk" coming last in replacement code.

#10 lore raw

PATCH v6 4/7 x86: re-work memcpy()

In reply to Jan Beulich

Move the function to its own assembly file. Having it in C just for the entire body to be an asm() isn't really helpful. Then have two flavors:
A "basic" version using qword steps for the bulk of the operation, and an ERMS version for modern hardware, to be substituted in via alternatives patching.

Alternatives patching, however, requires an extra precaution: It uses memcpy() itself, and hence the function may patch itself. Luckily the patched-in code only replaces the prolog of the original function. Make sure this remains this way.

---
We may want to consider branching over the REP MOVSQ as well, if the number of qwords turns out to be zero.
We may also want to consider using non-REP MOVS{L,W,B} for the tail.

TBD: We may further need a workaround similar to Linux'es 8ca97812c3c8
("x86/mce: Work around an erratum on fast string copy instructions").

TBD: Some older AMD CPUs have an issue with REP MOVS when source and
destination are misaligned with one another (modulo 32?), which may require a separate memcpy() flavor.
---
v6: Move alternatives.c change to a separate patch.
v5: Re-base.
v4: Use CR2 write as serializing insn, and limit its use to boot time.
v3: Re-base.

xen/arch/x86/Makefile +1 -0
@@ -47,6 +47,7 @@ obj-$(CONFIG_RETURN_THUNK) += indirect-t
 obj-$(CONFIG_PV) += ioport_emulate.o
 obj-y += irq.o
 obj-$(CONFIG_KEXEC) += machine_kexec.o
+obj-y += memcpy.o
 obj-y += memset.o
 obj-y += mm.o x86_64/mm.o
 obj-$(CONFIG_VM_EVENT) += monitor.o
xen/arch/x86/memcpy.S new file +20 -0
@@ -0,0 +1,20 @@
+#include <asm/asm_defns.h>
+
+FUNC(memcpy)
+        mov     %rdx, %rcx
+        mov     %rdi, %rax
+        /*
+         * We need to be careful here: memcpy() is involved in alternatives
+         * patching, so the code doing the actual copying (i.e. past setting
+         * up registers) may not be subject to patching (unless further
+         * precautions were taken).
+         */
+        ALTERNATIVE "and $7, %edx; shr $3, %rcx", \
+                    STR(rep movsb; RET), X86_FEATURE_ERMS
+        rep movsq
+        or      %edx, %ecx
+        jz      1f
+        rep movsb
+1:
+        RET
+END(memcpy)
xen/arch/x86/string.c +0 -15
@@ -7,21 +7,6 @@
 
 #include <xen/lib.h>
 
-void *(memcpy)(void *dest, const void *src, size_t n)
-{
-    long d0, d1, d2;
-
-    asm volatile (
-        "   rep ; movs"__OS" ; "
-        "   mov %k4,%k3      ; "
-        "   rep ; movsb        "
-        : "=&c" (d0), "=&D" (d1), "=&S" (d2)
-        : "0" (n/BYTES_PER_LONG), "r" (n%BYTES_PER_LONG), "1" (dest), "2" (src)
-        : "memory" );
-
-    return dest;
-}
-
 void *(memmove)(void *dest, const void *src, size_t n)
 {
     long d0, d1, d2;
Reviewed-by on v6 4/7
#11 lore raw

Re: [PATCH v6 4/7] x86: re-work memcpy()

Quoted 18 lines · Jan Beulich

Move the function to its own assembly file. Having it in C just for the entire body to be an asm() isn't really helpful. Then have two flavors:
A "basic" version using qword steps for the bulk of the operation, and an ERMS version for modern hardware, to be substituted in via alternatives patching.

Alternatives patching, however, requires an extra precaution: It uses memcpy() itself, and hence the function may patch itself. Luckily the patched-in code only replaces the prolog of the original function. Make sure this remains this way.

xen/arch/x86/memcpy.S new file +1 -0
@@ -0,0 +1,20 @@
+#include <asm/asm_defns.h>

xen/arch/x86/memcpy.S line 11

Quoted 10 lines
xen/arch/x86/memcpy.S new file +10 -0
+
+FUNC(memcpy)
+        mov     %rdx, %rcx
+        mov     %rdi, %rax
+        /*
+         * We need to be careful here: memcpy() is involved in alternatives
+         * patching, so the code doing the actual copying (i.e. past setting
+         * up registers) may not be subject to patching (unless further
+         * precautions were taken).
+         */

I think this phrasing is a little clearer:

We need to be careful here: memcpy() is involved in alternatives patching. Define the original code as only the register setup. The code doing the actual copying (i.e. past setting up registers) is not subject to patching, which avoids it changing underneath the processor.

Your comment is okay if you prefer not to change it:

Regards,
Jason

Quoted 9 lines
xen/arch/x86/memcpy.S new file +9 -0
+        ALTERNATIVE "and $7, %edx; shr $3, %rcx", \
+                    STR(rep movsb; RET), X86_FEATURE_ERMS
+        rep movsq
+        or      %edx, %ecx
+        jz      1f
+        rep movsb
+1:
+        RET
+END(memcpy)
#12 lore raw

PATCH v6 5/7 x86: control memset() and memcpy() inlining

In reply to Jan Beulich

Stop the compiler from inlining non-trivial memset() and memcpy() (for memset() see e.g. map_vcpu_info() or kimage_load_segments() for examples). This way we even keep the compiler from using REP STOSQ / REP MOVSQ when we'd prefer REP STOSB / REP MOVSB (when ERMS is available).

With gcc10 this yields a modest .text size reduction (release build) of around 2k.

Unfortunately these options aren't understood by the clang versions I have readily available for testing with; I'm unaware of equivalents.

Note also that using cc-option-add is not an option here, or at least I couldn't make things work with it (in case the option was not supported by the compiler): The embedded comma in the option looks to be getting in the way.

---
v3: Re-base.
v2: New.
---
The boundary values are of course up for discussion - I wasn't really certain whether to use 16 or 32; I'd be less certain about using yet larger values. A respective Linux patch [1] uses 256 ...

Similarly whether to permit the compiler to emit REP STOSQ / REP MOVSQ for known size, properly aligned blocks is up for discussion.

[1] https://lore.kernel.org/lkml/[email protected]/T/#u

xen/arch/x86/arch.mk +3 -0
@@ -58,6 +58,9 @@ endif
 $(call cc-option-add,CFLAGS_stack_boundary,CC,-mpreferred-stack-boundary=3)
 export CFLAGS_stack_boundary
 
+CFLAGS += $(call cc-option,$(CC),-mmemcpy-strategy=unrolled_loop:16:noalign$(comma)libcall:-1:noalign)
+CFLAGS += $(call cc-option,$(CC),-mmemset-strategy=unrolled_loop:16:noalign$(comma)libcall:-1:noalign)
+
 ifeq ($(CONFIG_UBSAN),y)
 # Don't enable alignment sanitisation.  x86 has efficient unaligned accesses,
 # and various things (ACPI tables, hypercall pages, stubs, etc) are wont-fix.
Reviewed-by on v6 5/7
#13 lore raw

Re: [PATCH v6 5/7] x86: control memset() and memcpy() inlining

Quoted 12 lines · Jan Beulich

Stop the compiler from inlining non-trivial memset() and memcpy() (for memset() see e.g. map_vcpu_info() or kimage_load_segments() for examples). This way we even keep the compiler from using REP STOSQ / REP MOVSQ when we'd prefer REP STOSB / REP MOVSB (when ERMS is available).

With gcc10 this yields a modest .text size reduction (release build) of around 2k.

Unfortunately these options aren't understood by the clang versions I have readily available for testing with; I'm unaware of equivalents.

Quoted 7 lines

Note also that using cc-option-add is not an option here, or at least I couldn't make things work with it (in case the option was not supported by the compiler): The embedded comma in the option looks to be getting in the way.

#14 lore raw

PATCH v6 6/7 x86: introduce "hot" and "cold" page clearing functions

In reply to Jan Beulich

The present clear_page_sse2() is useful in case a page isn't going to get touched again soon, or if we want to limit churn on the caches. Amend it by alternatively using CLZERO, which has been found to be quite a bit faster on Zen2 hardware at least. Note that to use CLZERO, we need to know the cache line size, and hence a feature dependency on CLFLUSH gets introduced.

For cases where latency is the most important aspect, or when it is expected that sufficiently large parts of a page will get accessed again soon after the clearing, introduce a "hot" alternative. Again use alternatives patching to select between a "legacy" and an ERMS variant.

Don't switch any callers just yet - this will be the subject of subsequent changes.

---
v5: Re-base.
v3: Re-base.
v2: New.
---
Note: Ankur indicates that for ~L3-size or larger regions MOVNT/CLZERO
is better even latency-wise.

xen/arch/x86/clear_page.S +40 -2
@@ -5,7 +5,7 @@
 #include <asm/asm_defns.h>
 #include <asm/page.h>
 
-FUNC(clear_page_sse2)
+        .macro clear_page_sse2
         mov     $PAGE_SIZE/32, %ecx
         xor     %eax,%eax
 
@@ -19,4 +19,42 @@ FUNC(clear_page_sse2)
 
         sfence
         RET
-END(clear_page_sse2)
+        .endm
+
+        .macro clear_page_clzero
+        mov     %rdi, %rax
+        mov     $PAGE_SIZE/64, %ecx
+        .globl clear_page_clzero_post_count
+clear_page_clzero_post_count:
+
+0:      clzero
+        sub     $-64, %rax
+        .globl clear_page_clzero_post_neg_size
+clear_page_clzero_post_neg_size:
+        sub     $1, %ecx
+        jnz     0b
+
+        sfence
+        RET
+        .endm
+
+FUNC(clear_page_cold)
+        ALTERNATIVE clear_page_sse2, clear_page_clzero, X86_FEATURE_CLZERO
+END(clear_page_cold)
+
+        .macro clear_page_stosb
+        mov     $PAGE_SIZE, %ecx
+        xor     %eax,%eax
+        rep stosb
+        .endm
+
+        .macro clear_page_stosq
+        mov     $PAGE_SIZE/8, %ecx
+        xor     %eax, %eax
+        rep stosq
+        .endm
+
+FUNC(clear_page_hot)
+        ALTERNATIVE clear_page_stosq, clear_page_stosb, X86_FEATURE_ERMS
+        RET
+END(clear_page_hot)
xen/arch/x86/cpu/common.c +35 -2
@@ -60,6 +60,9 @@ DEFINE_PER_CPU(bool, full_gdt_loaded);
 
 DEFINE_PER_CPU(uint32_t, pkrs);
 
+extern uint32_t clear_page_clzero_post_count[];
+extern int8_t clear_page_clzero_post_neg_size[];
+
 void __init setup_clear_cpu_cap(unsigned int cap)
 {
 	const uint32_t *dfs;
@@ -357,8 +360,38 @@ void __init early_cpu_init(bool verbose)
 
 	edx &= ~cleared_caps[FEATURESET_1d];
 	ecx &= ~cleared_caps[FEATURESET_1c];
-	if (edx & cpufeat_mask(X86_FEATURE_CLFLUSH))
-		c->x86_cache_alignment = ((ebx >> 8) & 0xff) * 8;
+	if (edx & cpufeat_mask(X86_FEATURE_CLFLUSH)) {
+		unsigned int size = ((ebx >> 8) & 0xff) * 8;
+
+		c->x86_cache_alignment = size;
+
+		/*
+		 * Patch in parameters of clear_page_cold()'s CLZERO
+		 * alternative. Note that for now we cap this at 128 bytes.
+		 * Larger cache line sizes would still be dealt with
+		 * correctly, but would cause redundant work done.
+		 */
+		if (size > 128)
+			size = 128;
+		if (size && !(size & (size - 1))) {
+			/*
+			 * Need to play some games to keep the compiler from
+			 * recognizing the negative array index as being out
+			 * of bounds. The labels in assembler code really are
+			 * _after_ the locations to be patched, so the
+			 * negative index is intentional.
+			 */
+			uint32_t *pcount = clear_page_clzero_post_count;
+			int8_t *neg_size = clear_page_clzero_post_neg_size;
+
+			OPTIMIZER_HIDE_VAR(pcount);
+			OPTIMIZER_HIDE_VAR(neg_size);
+			pcount[-1] = PAGE_SIZE / size;
+			neg_size[-1] = -size;
+		}
+		else
+			setup_clear_cpu_cap(X86_FEATURE_CLZERO);
+	}
 	/* Leaf 0x1 capabilities filled in early for Xen. */
 	c->x86_capability[FEATURESET_1d] = edx;
 	c->x86_capability[FEATURESET_1c] = ecx;
xen/arch/x86/include/asm/asm-defns.h +4 -0
@@ -1,5 +1,9 @@
 #include <asm/page-bits.h>
 
+.macro clzero
+    .byte 0x0f, 0x01, 0xfc
+.endm
+
 /*
  * Call a noreturn function.  This could be JMP, but CALL results in a more
  * helpful backtrace.  BUG is to catch functions which do decide to return...
xen/arch/x86/include/asm/page.h +3 -2
@@ -219,10 +219,11 @@ typedef struct { u64 pfn; } pagetable_t;
 #define pagetable_from_paddr(p) pagetable_from_pfn((p)>>PAGE_SHIFT)
 #define pagetable_null()        pagetable_from_pfn(0)
 
-void clear_page_sse2(void *pg);
+void clear_page_hot(void *pg);
+void clear_page_cold(void *pg);
 void copy_page_sse2(void *to, const void *from);
 
-#define clear_page(_p)      clear_page_sse2(_p)
+#define clear_page(_p)      clear_page_cold(_p)
 #define copy_page(_t, _f)   copy_page_sse2(_t, _f)
 
 /* Convert between Xen-heap virtual addresses and machine addresses. */
xen/tools/gen-cpuid.py +4 -0
@@ -212,6 +212,10 @@ def crunch_numbers(state):
         # the first place.
         APIC: [X2APIC, TSC_DEADLINE, EXTAPIC],
 
+        # The CLZERO insn requires a means to determine the cache line size,
+        # which is tied to the CLFLUSH insn.
+        CLFLUSH: [CLZERO],
+
         # AMD built MMXExtentions and 3DNow as extentions to MMX.
         MMX: [MMXEXT, _3DNOW],
 
Reviewed-by on v6 6/7
#15 lore raw

Re: [PATCH v6 6/7] x86: introduce "hot" and "cold" page clearing functions

Quoted 12 lines · Jan Beulich

The present clear_page_sse2() is useful in case a page isn't going to get touched again soon, or if we want to limit churn on the caches. Amend it by alternatively using CLZERO, which has been found to be quite a bit faster on Zen2 hardware at least. Note that to use CLZERO, we need to know the cache line size, and hence a feature dependency on CLFLUSH gets introduced.

For cases where latency is the most important aspect, or when it is expected that sufficiently large parts of a page will get accessed again soon after the clearing, introduce a "hot" alternative. Again use alternatives patching to select between a "legacy" and an ERMS variant.

Quoted 4 lines

Don't switch any callers just yet - this will be the subject of subsequent changes.

#16 lore raw

PATCH v6 7/7 mm: allow page scrubbing routine(s) to be arch controlled

In reply to Jan Beulich

Especially when dealing with large amounts of memory, memset() may not be very efficient; this can be bad enough that even for debug builds a custom function is warranted. We additionally want to distinguish "hot" and "cold" cases (with, as initial heuristic, "hot" being for any allocations a domain does for itself, assuming that in all other cases the page wouldn't be accessed [again] soon). The goal is for accesses of "cold" pages to not disturb caches (albeit finding a good balance between this and the higher latency looks to be difficult).

Keep the default fallback to clear_page_*() in common code; this may want to be revisited down the road.

---
v6: Re-base.
v4: Re-base.
v3: Re-base.
v2: New.
---
The choice between hot and cold in scrub_one_page()'s callers is certainly up for discussion / improvement.

xen/arch/arm/include/asm/page.h +6 -0
@@ -144,6 +144,12 @@ extern size_t dcache_line_bytes;
 
 #define copy_page(dp, sp) memcpy(dp, sp, PAGE_SIZE)
 
+#define clear_page_hot  clear_page
+#define clear_page_cold clear_page
+
+#define scrub_page_hot(page) memset(page, SCRUB_BYTE_PATTERN, PAGE_SIZE)
+#define scrub_page_cold      scrub_page_hot
+
 static inline size_t read_dcache_line_bytes(void)
 {
     register_t ctr;
xen/arch/ppc/include/asm/page.h +6 -0
@@ -188,6 +188,12 @@ static inline void invalidate_icache(voi
 #define clear_page(page) memset(page, 0, PAGE_SIZE)
 #define copy_page(dp, sp) memcpy(dp, sp, PAGE_SIZE)
 
+#define clear_page_hot  clear_page
+#define clear_page_cold clear_page
+
+#define scrub_page_hot(page) memset(page, SCRUB_BYTE_PATTERN, PAGE_SIZE)
+#define scrub_page_cold      scrub_page_hot
+
 /* TODO: Flush the dcache for an entire page. */
 static inline void flush_page_to_ram(unsigned long mfn, bool sync_icache)
 {
xen/arch/riscv/include/asm/page.h +6 -0
@@ -185,6 +185,12 @@ static inline void invalidate_icache(voi
 #define clear_page(page) memset((void *)(page), 0, PAGE_SIZE)
 #define copy_page(dp, sp) memcpy(dp, sp, PAGE_SIZE)
 
+#define clear_page_hot  clear_page
+#define clear_page_cold clear_page
+
+#define scrub_page_hot(page) memset(page, SCRUB_BYTE_PATTERN, PAGE_SIZE)
+#define scrub_page_cold      scrub_page_hot
+
 void flush_page_to_ram(unsigned long mfn, bool sync_icache);
 
 /* Write a pagetable entry. */
xen/arch/x86/Makefile +1 -0
@@ -58,6 +58,7 @@ obj-y += pci.o
 obj-y += physdev.o
 obj-$(CONFIG_COMPAT) += x86_64/physdev.o
 obj-$(CONFIG_X86_PSR) += psr.o
+obj-bin-$(CONFIG_DEBUG) += scrub_page.o
 obj-y += setup.o
 obj-y += shutdown.o
 obj-y += smp.o
xen/arch/x86/include/asm/page.h +5 -0
@@ -226,6 +226,11 @@ void copy_page_sse2(void *to, const void
 #define clear_page(_p)      clear_page_cold(_p)
 #define copy_page(_t, _f)   copy_page_sse2(_t, _f)
 
+#ifdef CONFIG_DEBUG
+void scrub_page_hot(void *);
+void scrub_page_cold(void *);
+#endif
+
 /* Convert between Xen-heap virtual addresses and machine addresses. */
 #define __pa(x)             (virt_to_maddr(x))
 #define __va(x)             (maddr_to_virt(x))
xen/arch/x86/scrub_page.S new file +39 -0
@@ -0,0 +1,39 @@
+        .file __FILE__
+
+#include <asm/asm_defns.h>
+#include <xen/page-size.h>
+#include <xen/scrub.h>
+
+FUNC(scrub_page_cold)
+        mov     $PAGE_SIZE/32, %ecx
+        mov     $SCRUB_PATTERN, %rax
+
+0:      movnti  %rax,   (%rdi)
+        movnti  %rax,  8(%rdi)
+        movnti  %rax, 16(%rdi)
+        movnti  %rax, 24(%rdi)
+        add     $32, %rdi
+        sub     $1, %ecx
+        jnz     0b
+
+        sfence
+        ret
+END(scrub_page_cold)
+
+        .macro scrub_page_stosb
+        mov     $PAGE_SIZE, %ecx
+        mov     $SCRUB_BYTE_PATTERN, %eax
+        rep stosb
+        ret
+        .endm
+
+        .macro scrub_page_stosq
+        mov     $PAGE_SIZE/8, %ecx
+        mov     $SCRUB_PATTERN, %rax
+        rep stosq
+        ret
+        .endm
+
+FUNC(scrub_page_hot)
+        ALTERNATIVE scrub_page_stosq, scrub_page_stosb, X86_FEATURE_ERMS
+END(scrub_page_hot)
xen/common/page_alloc.c +27 -20

100 lines not on this page · raw message

xen/include/xen/scrub.h new file +24 -0
@@ -0,0 +1,24 @@
+#ifndef __XEN_SCRUB_H__
+#define __XEN_SCRUB_H__
+
+#include <xen/const.h>
+
+/* SCRUB_PATTERN needs to be a repeating series of bytes. */
+#ifdef CONFIG_DEBUG
+# define SCRUB_PATTERN       _AC(0xc2c2c2c2c2c2c2c2,ULL)
+#else
+# define SCRUB_PATTERN       _AC(0,ULL)
+#endif
+#define SCRUB_BYTE_PATTERN   (SCRUB_PATTERN & 0xff)
+
+#endif /* __XEN_SCRUB_H__ */
+
+/*
+ * Local variables:
+ * mode: C
+ * c-file-style: "BSD"
+ * c-basic-offset: 4
+ * tab-width: 4
+ * indent-tabs-mode: nil
+ * End:
+ */
Reviewed-by on v6 7/7
#17 lore raw

Re: [PATCH v6 7/7] mm: allow page scrubbing routine(s) to be arch controlled

Quoted 9 lines · Jan Beulich

Especially when dealing with large amounts of memory, memset() may not be very efficient; this can be bad enough that even for debug builds a custom function is warranted. We additionally want to distinguish "hot" and "cold" cases (with, as initial heuristic, "hot" being for any allocations a domain does for itself, assuming that in all other cases the page wouldn't be accessed [again] soon). The goal is for accesses of "cold" pages to not disturb caches (albeit finding a good balance between this and the higher latency looks to be difficult).

Quoted 6 lines

Keep the default fallback to clear_page_*() in common code; this may want to be revisited down the road.

#18 lore raw

Re: [PATCH v6 7/7] mm: allow page scrubbing routine(s) to be arch controlled

In reply to Jan Beulich
Quoted 32 lines · Jan Beulich
xen/arch/x86/scrub_page.S new file +29 -0
@@ -0,0 +1,39 @@
+        .file __FILE__
+
+#include <asm/asm_defns.h>
+#include <xen/page-size.h>
+#include <xen/scrub.h>
+
+FUNC(scrub_page_cold)
+        mov     $PAGE_SIZE/32, %ecx
+        mov     $SCRUB_PATTERN, %rax
+
+0:      movnti  %rax,   (%rdi)
+        movnti  %rax,  8(%rdi)
+        movnti  %rax, 16(%rdi)
+        movnti  %rax, 24(%rdi)
+        add     $32, %rdi
+        sub     $1, %ecx
+        jnz     0b
+
+        sfence
+        ret
+END(scrub_page_cold)
+
+        .macro scrub_page_stosb
+        mov     $PAGE_SIZE, %ecx
+        mov     $SCRUB_BYTE_PATTERN, %eax
+        rep stosb
+        ret
+        .endm
+

xen/arch/x86/scrub_page.S line 39

Quoted 10 lines
xen/arch/x86/scrub_page.S new file +10 -0
+        .macro scrub_page_stosq
+        mov     $PAGE_SIZE/8, %ecx
+        mov     $SCRUB_PATTERN, %rax
+        rep stosq
+        ret
+        .endm
+
+FUNC(scrub_page_hot)
+        ALTERNATIVE scrub_page_stosq, scrub_page_stosb, X86_FEATURE_ERMS
+END(scrub_page_hot)

Bah, I've noticed only now that I failed to do the ret -> RET conversion here during the most recent re-basing.

Jan

#19 lore raw

Re: [PATCH v6 7/7] mm: allow page scrubbing routine(s) to be arch controlled

Quoted 38 lines · Jan Beulich
Quoted 37 lines · Jan Beulich
xen/arch/x86/scrub_page.S new file +34 -0
@@ -0,0 +1,39 @@
+        .file __FILE__
+
+#include <asm/asm_defns.h>
+#include <xen/page-size.h>
+#include <xen/scrub.h>
+
+FUNC(scrub_page_cold)
+        mov     $PAGE_SIZE/32, %ecx
+        mov     $SCRUB_PATTERN, %rax
+
+0:      movnti  %rax,   (%rdi)
+        movnti  %rax,  8(%rdi)
+        movnti  %rax, 16(%rdi)
+        movnti  %rax, 24(%rdi)
+        add     $32, %rdi
+        sub     $1, %ecx
+        jnz     0b
+
+        sfence
+        ret
+END(scrub_page_cold)
+
+        .macro scrub_page_stosb
+        mov     $PAGE_SIZE, %ecx
+        mov     $SCRUB_BYTE_PATTERN, %eax
+        rep stosb
+        ret
+        .endm
+
+        .macro scrub_page_stosq
+        mov     $PAGE_SIZE/8, %ecx
+        mov     $SCRUB_PATTERN, %rax
+        rep stosq
+        ret
Quoted 8 lines

xen/arch/x86/scrub_page.S line 39

Quoted 5 lines
xen/arch/x86/scrub_page.S new file +5 -0
+        .endm
+
+FUNC(scrub_page_hot)
+        ALTERNATIVE scrub_page_stosq, scrub_page_stosb, X86_FEATURE_ERMS
+END(scrub_page_hot)

Bah, I've noticed only now that I failed to do the ret -> RET conversion here during the most recent re-basing.

Good job catching that. My R-b still applies with the RET fixup.

Regards,
Jason

#20 lore raw

Re: [PATCH v6 7/7] mm: allow page scrubbing routine(s) to be arch controlled

In reply to Jan Beulich

xen/arch/x86/Makefile obj-y += pci.o · line 61

Quoted 7 lines · Jan Beulich
xen/arch/x86/Makefile +1 -0
@@ -58,6 +58,7 @@ obj-y += pci.o
 obj-y += physdev.o
 obj-$(CONFIG_COMPAT) += x86_64/physdev.o
 obj-$(CONFIG_X86_PSR) += psr.o
+obj-bin-$(CONFIG_DEBUG) += scrub_page.o

Spotted yet one more oversight: Wants to be scrub-page.o (obviously along with the source file's name also changed).

Jan