x86/kstack_erase: Faster stack poisoning, plus a startup build fix
cover x86/kstack_erase: Faster stack poisoning, plus a startup build fix
With KSTACK_ERASE, every return to user space poisons the part of the task stack used since the previous return, one 8-byte store at a time. On Meta hosts running many small VMs, that loop costs about 1.5% of non-idle host kernel cycles. Most of it is on the way out of futex, epoll, procfs and socket syscalls that go 1-2 KiB deep.
Patch 2 makes x86-64 use REP STOSQ for spans above 512 bytes, through the arch hook that s390 already uses. Shorter spans keep the loop, and the range and value written do not change.
Patch 1 is an independent build fix I found while testing patch 2 with a small KSTACK_ERASE_TRACK_MIN_SIZE. The startup code still uses the pre-rename DISABLE_STACKLEAK_PLUGIN, so with Clang, AMD memory encryption and a tracking minimum below about 90 bytes, vmlinux fails to link. It can be applied on its own.
Zen 5c KVM guest, one vCPU, before -> after:
stackleak_erase() per return to user 71 ns -> 46 ns futex wake/wait ping-pong 5-7% faster Unix socket sendmsg()/recvmsg() ping-pong 5-8% faster open+read+close of /proc/self/stat 6-8% faster getppid() (spans below 512 bytes) within 2%
Usama Arif (2):
x86/boot/startup: Disable kernel stack depth tracking x86/kstack_erase: Use REP STOSQ for large stack fills
arch/x86/boot/startup/Makefile | 2 +- arch/x86/include/asm/processor.h | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-)
Signature · 1 line
2.53.1-Meta
PATCH 1/2 x86/boot/startup: Disable kernel stack depth tracking
Commit 57fbad15c2ee ("stackleak: Rename STACKLEAK to KSTACK_ERASE") renamed DISABLE_STACKLEAK_PLUGIN to DISABLE_KSTACK_ERASE everywhere except in arch/x86/boot/startup/Makefile. The old name now expands to nothing, so the startup code is built with stack depth tracking enabled.
The startup code is linked with every symbol prefixed by __pi_, so that it cannot call into the rest of the kernel by accident. It has no alias for the tracking callback, and tracking stack depth there is of no use.
At the default KSTACK_ERASE_TRACK_MIN_SIZE of 100 no startup function is large enough to be tracked, so this went unnoticed. With Clang, CONFIG_AMD_MEM_ENCRYPT=y and a minimum below about 90 bytes, pvalidate_4k_page(), snp_cpuid() and do_vc_no_ghcb() get a call to __sanitizer_cov_stack_depth() and vmlinux fails to link:
ld.lld: error: undefined symbol: __pi___sanitizer_cov_stack_depth
Use DISABLE_KSTACK_ERASE, which disables tracking with either compiler.
--- arch/x86/boot/startup/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/x86/boot/startup/Makefile +1 -1
@@ -3,7 +3,7 @@ KBUILD_AFLAGS += -D__DISABLE_EXPORTS KBUILD_CFLAGS += -D__DISABLE_EXPORTS -mcmodel=small -fPIC \ -Os -DDISABLE_BRANCH_PROFILING \ - $(DISABLE_STACKLEAK_PLUGIN) \ + $(DISABLE_KSTACK_ERASE) \ $(DISABLE_LATENT_ENTROPY_PLUGIN) \ -fno-stack-protector -D__NO_FORTIFY \ -fno-jump-tables \
Signature · 1 line
2.53.1-Meta
PATCH 2/2 x86/kstack_erase: Use REP STOSQ for large stack fills
In reply to Usama ArifWith KSTACK_ERASE, every return to user space poisons the part of the task stack that was used since the previous return. The generic __stackleak_poison() does that one word per loop iteration, so a syscall that went 1-2 KiB deep pays for 128-256 separate stores. On Meta hosts running many small VMs, stackleak_erase() accounts for about 1.5% of non-idle host kernel cycles.
Override __stackleak_poison() on x86-64, as s390 already does, through the hook added by commit 491a78663e03 ("stackleak: allow to specify arch specific stackleak poison function"). Fill spans larger than 512 bytes with REP STOSQ and keep the word loop for shorter ones, where the fixed startup cost of REP STOSQ does not pay off. REP STOSQ starts to win at about 300-400 bytes on Zen 5c and Cooper Lake, so on both no span gets slower.
The fill is inline asm, so the noinstr function still makes no calls. memset64() would be the same instruction, but it is only static inline, and with KMSAN it is an out-of-line function.
In a Zen 5c KVM guest, stackleak_erase() got about 35% cheaper per return to user space (71 ns to 46 ns, scan included) over a futex, epoll, procfs and Unix socket syscall mix. Same-vCPU futex wake/wait and Unix socket sendmsg()/recvmsg() ping-pong round trips got 5-8% faster.
--- arch/x86/include/asm/processor.h | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+)
arch/x86/include/asm/processor.h +25 -0
@@ -580,6 +580,31 @@ static __always_inline bool on_thread_stack(void) current_stack_pointer) < THREAD_SIZE; } +#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +unsigned long count; + +/* Short spans do not amortize the startup cost of REP STOSQ. */ +if (erase_high <= erase_low +512 ) { +while (erase_low < erase_high) { + *(unsigned long *)erase_low = poison; + erase_low +=sizeof (unsigned long ); + } +return ; + } + + count = (erase_high - erase_low) /sizeof (unsigned long ); + asmvolatile ("rep stosq" + :"+D" (erase_low),"+c" (count) + :"a" (poison) + :"memory" ); +} +#endif +#ifdef CONFIG_PARAVIRT_XXL #include <asm/paravirt.h> #else
Signature · 1 line
2.53.1-Meta
Re: [PATCH 2/2] x86/kstack_erase: Use REP STOSQ for large stack fills
Quoted 50 lines · Usama Arif
With
KSTACK_ERASE, every return to user space poisons the part of the task stack that was used since the previous return. The generic__stackleak_poison()does that one word per loop iteration, so a syscall that went 1-2 KiB deep pays for 128-256 separate stores. On Meta hosts running many small VMs,stackleak_erase()accounts for about 1.5% of non-idle host kernel cycles.Override
__stackleak_poison()on x86-64, as s390 already does, through the hook added by commit491a78663e03("stackleak: allow to specify arch specific stackleak poison function"). Fill spans larger than 512 bytes with REP STOSQ and keep the word loop for shorter ones, where the fixed startup cost of REP STOSQ does not pay off. REP STOSQ starts to win at about 300-400 bytes on Zen 5c and Cooper Lake, so on both no span gets slower.The fill is inline asm, so the noinstr function still makes no calls.
memset64()would be the same instruction, but it is only static inline, and with KMSAN it is an out-of-line function.In a Zen 5c KVM guest,
stackleak_erase()got about 35% cheaper per return to user space (71 ns to 46 ns, scan included) over a futex, epoll, procfs and Unix socket syscall mix. Same-vCPU futex wake/wait and Unix socket sendmsg()/recvmsg() ping-pong round trips got 5-8% faster.Signed-off-by Usama Arif <[email protected]>--- arch/x86/include/asm/processor.h | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+)arch/x86/include/asm/processor.h +12
-0@@ -580,6 +580,31 @@ static __always_inline bool on_thread_stack(void) current_stack_pointer) < THREAD_SIZE; } +#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +unsigned long count; + +/* Short spans do not amortize the startup cost of REP STOSQ. */ +if (erase_high <= erase_low +512 ) { +while (erase_low < erase_high) { + *(unsigned long *)erase_low = poison;
arch/x86/include/asm/processor.h static __always_inline bool on_thread_stack(void) · line 604
Quoted 10 lines
arch/x86/include/asm/processor.h +10
-0+ erase_low +=sizeof (unsigned long ); + } +return ; + } + + count = (erase_high - erase_low) /sizeof (unsigned long ); + asmvolatile ("rep stosq" + :"+D" (erase_low),"+c" (count) + :"a" (poison) + :"memory" );
Surely this isn't the only place using rep stosq in the tree, right? It's not, see memset64 in arch/x86/include/asm/string_64.h.
Quoted 9 lines
arch/x86/include/asm/processor.h +3
-1+} +#endif +#ifdef CONFIG_PARAVIRT_XXL #include <asm/paravirt.h> #else --2.53.1-Meta
Signature · 2 lines
Thanks, ~Nick Desaulniers
Re: [PATCH 1/2] x86/boot/startup: Disable kernel stack depth tracking
In reply to Usama ArifQuoted 16 lines · Usama Arif
Commit
57fbad15c2ee("stackleak: Rename STACKLEAK toKSTACK_ERASE") renamedDISABLE_STACKLEAK_PLUGINtoDISABLE_KSTACK_ERASEeverywhere except inarch/x86/boot/startup/Makefile. The old name now expands to nothing, so the startup code is built with stack depth tracking enabled.The startup code is linked with every symbol prefixed by
__pi_, so that it cannot call into the rest of the kernel by accident. It has no alias for the tracking callback, and tracking stack depth there is of no use.At the default
KSTACK_ERASE_TRACK_MIN_SIZEof 100 no startup function is large enough to be tracked, so this went unnoticed. With Clang,CONFIG_AMD_MEM_ENCRYPT=yand a minimum below about 90 bytes,pvalidate_4k_page(),snp_cpuid()anddo_vc_no_ghcb()get a call to__sanitizer_cov_stack_depth()and vmlinux fails to link:
Quoted 5 lines
ld.lld: error: undefined symbol:
__pi___sanitizer_cov_stack_depthUse
DISABLE_KSTACK_ERASE, which disables tracking with either compiler.Fixes 57fbad15c2ee ("stackleak: Rename STACKLEAK to KSTACK_ERASE")
tsk tsk, Kees your grep might be borked!
Quoted 21 lines
Signed-off-by Usama Arif <[email protected]>--- arch/x86/boot/startup/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)arch/x86/boot/startup/Makefile +1
-2@@ -3,7 +3,7 @@ KBUILD_AFLAGS += -D__DISABLE_EXPORTS KBUILD_CFLAGS += -D__DISABLE_EXPORTS -mcmodel=small -fPIC \ -Os -DDISABLE_BRANCH_PROFILING \ - $(DISABLE_STACKLEAK_PLUGIN) \ + $(DISABLE_KSTACK_ERASE) \ $(DISABLE_LATENT_ENTROPY_PLUGIN) \ -fno-stack-protector -D__NO_FORTIFY \ -fno-jump-tables \ --2.53.1-Meta
Signature · 2 lines
Thanks, ~Nick Desaulniers
Re: [PATCH 2/2] x86/kstack_erase: Use REP STOSQ for large stack fills
In reply to Usama ArifQuoted 14 lines · Usama Arif
(quoted diff) +14
-0+#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, + unsigned long erase_high, + unsigned long poison) +{ + unsigned long count; + + /* Short spans do not amortize the startup cost of REP STOSQ. */ + if (erase_high <= erase_low + 512) { + while (erase_low < erase_high) { + *(unsigned long *)erase_low = poison; + erase_low += sizeof(unsigned long); + }
Review
Quoted 10 lines
(quoted diff) +10
-0+ return; + } + + count = (erase_high - erase_low) / sizeof(unsigned long); + asm volatile("rep stosq" + : "+D" (erase_low), "+c" (count) + : "a" (poison) + : "memory"); +} +#endif
Gemini seems to suggest 16-32 words would be sufficient to amortize the REP STOS setup. It was also adamant I try and unroll that earlier loop.
How about something like so, does that make sense? Also, I suppose we should make memset64() __always_inline if we use it here. I'm not at all sold on the unroll here, the asm is pretty horrid for what it does.
---
arch/x86/include/asm/processor.h +28 -0
@@ -28,6 +28,7 @@ struct vm86;#include <asm/vmxfeatures.h> #include <asm/vdso/processor.h> #include <asm/shstk.h> +#include <asm/string.h> #include <linux/personality.h> #include <linux/cache.h>
@@ -580,6 +581,33 @@ static __always_inline bool on_thread_st current_stack_pointer) < THREAD_SIZE; } +#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +unsigned long count = (erase_high - erase_low) /sizeof (unsigned long ); + +/* Amortize the startup cost of REP STOSQ. */ +if (count <32 ) { +unsigned long *ptr = (unsigned long *)erase_low; + +while (count) { +switch ((count-1 ) %4 ) { +case 3 : ptr[--count] = poison; fallthrough; +case 2 : ptr[--count] = poison; fallthrough; +case 1 : ptr[--count] = poison; fallthrough; +case 0 : ptr[--count] = poison;break ; + } + } +return ; + } + +memset64 ((void *)erase_low, poison, count); +} +#endif +#ifdef CONFIG_PARAVIRT_XXL #include <asm/paravirt.h> #else
Re: [PATCH 2/2] x86/kstack_erase: Use REP STOSQ for large stack fills
In reply to Nick DesaulniersQuoted 39 lines · On Thu, 19 Nov 2026 14:28:04 -0800 Nick Desaulniers <[email protected]>…
Quoted 38 lines · Usama Arif
With
KSTACK_ERASE, every return to user space poisons the part of the task stack that was used since the previous return. The generic__stackleak_poison()does that one word per loop iteration, so a syscall that went 1-2 KiB deep pays for 128-256 separate stores. On Meta hosts running many small VMs,stackleak_erase()accounts for about 1.5% of non-idle host kernel cycles.Override
__stackleak_poison()on x86-64, as s390 already does, through the hook added by commit491a78663e03("stackleak: allow to specify arch specific stackleak poison function"). Fill spans larger than 512 bytes with REP STOSQ and keep the word loop for shorter ones, where the fixed startup cost of REP STOSQ does not pay off. REP STOSQ starts to win at about 300-400 bytes on Zen 5c and Cooper Lake, so on both no span gets slower.The fill is inline asm, so the noinstr function still makes no calls.
memset64()would be the same instruction, but it is only static inline, and with KMSAN it is an out-of-line function.In a Zen 5c KVM guest,
stackleak_erase()got about 35% cheaper per return to user space (71 ns to 46 ns, scan included) over a futex, epoll, procfs and Unix socket syscall mix. Same-vCPU futex wake/wait and Unix socket sendmsg()/recvmsg() ping-pong round trips got 5-8% faster.Signed-off-by Usama Arif <[email protected]>--- arch/x86/include/asm/processor.h | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+)arch/x86/include/asm/processor.h +0
-0@@ -580,6 +580,31 @@ static __always_inline bool on_thread_stack(void) current_stack_pointer) < THREAD_SIZE; }
Quoted 15 lines
Quoted 5 lines
arch/x86/include/asm/processor.h +5
-0+#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison)arch/x86/include/asm/processor.h static __always_inline bool on_thread_stack(void) · line 597
Quoted 10 lines
arch/x86/include/asm/processor.h +10
-0+{ +unsigned long count; + +/* Short spans do not amortize the startup cost of REP STOSQ. */ +if (erase_high <= erase_low +512 ) { +while (erase_low < erase_high) { + *(unsigned long *)erase_low = poison; + erase_low +=sizeof (unsigned long ); + } +return ;
gcc 13 onwards makes a meal of that - https://godbolt.org/z/KPP4h8xz6
It does manage to unroll the loop once - which is good because the intel cpu (I've got) won't execute a 'one clock loop' (the zen5 will); but the setup code is horrid.
But I also think some of the more recent cpu can execute more than one write per clock.
If you unroll the loop 4 times it may run a lot faster. Perhaps:
long count = (erase_high - erase_low) / sizeof(unsigned long);
if (count <= 64) {
while ((count -= 4) >= 0) {
*(unsigned long *)erase_low = poison;
*(unsigned long *)(erase_low + 8) = poison;
*(unsigned long *)(erase_low + 16) = poison;
*(unsigned long *)(erase_low + 24) = poison;
erase_low += 32;
}
if (count & 2) {
*(unsigned long *)erase_low = poison;
*(unsigned long *)(erase_low + 8) = poison;
erase_low += 16;
}
if (count & 1)
*(unsigned long *)erase_low = poison;
} else {
...
}Except that gcc makes a mess of it again.
I don't think the 'erase_low += 32' is going to execute at the same time as the last (two probably) writes so costs a clock. So it may need to be asm.
Quoted 10 lines
arch/x86/include/asm/processor.h static __always_inline bool on_thread_stack(void) · line 604
Quoted 7 lines
arch/x86/include/asm/processor.h +7
-0+ } + + count = (erase_high - erase_low) /sizeof (unsigned long ); + asmvolatile ("rep stosq" + :"+D" (erase_low),"+c" (count) + :"a" (poison) + :"memory" );Surely this isn't the only place using
rep stosqin the tree, right? It's not, see memset64 inarch/x86/include/asm/string_64.h.
Which seems to have very few users.memset_p() and memset_l() have almost no users.
David
Quoted 12 lines
Quoted 10 lines
arch/x86/include/asm/processor.h +3
-1+} +#endif +#ifdef CONFIG_PARAVIRT_XXL #include <asm/paravirt.h> #else --2.53.1-Meta
Re: [PATCH 2/2] x86/kstack_erase: Use REP STOSQ for large stack fills
In reply to Peter ZijlstraQuoted 29 lines · Peter Zijlstra
Quoted 14 lines · Usama Arif
(quoted diff) +14
-0+#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, + unsigned long erase_high, + unsigned long poison) +{ + unsigned long count; + + /* Short spans do not amortize the startup cost of REP STOSQ. */ + if (erase_high <= erase_low + 512) { + while (erase_low < erase_high) { + *(unsigned long *)erase_low = poison; + erase_low += sizeof(unsigned long); + }Review
Quoted 10 lines
(quoted diff) +10
-0+ return; + } + + count = (erase_high - erase_low) / sizeof(unsigned long); + asm volatile("rep stosq" + : "+D" (erase_low), "+c" (count) + : "a" (poison) + : "memory"); +} +#endifGemini seems to suggest 16-32 words would be sufficient to amortize the REP STOS setup. It was also adamant I try and unroll that earlier loop.
Quoted 3 lines
How about something like so, does that make sense? Also, I suppose we should make
memset64()__always_inlineif we use it here. I'm not at all sold on the unroll here, the asm is pretty horrid for what it does.
This one is much improved:
arch/x86/include/asm/processor.h +30 -0
@@ -28,6 +28,7 @@ struct vm86;#include <asm/vmxfeatures.h> #include <asm/vdso/processor.h> #include <asm/shstk.h> +#include <asm/string.h> #include <linux/personality.h> #include <linux/cache.h>
@@ -580,6 +581,35 @@ static __always_inline bool on_thread_st current_stack_pointer) < THREAD_SIZE; } +#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +unsigned long count = (erase_high - erase_low) /sizeof (unsigned long ); + +/* Amortize the startup cost of REP STOSQ. */ +if (count <32 ) { +unsigned long *ptr = (unsigned long *)erase_low; + +while (count) { +unsigned long mod = (count-1 ) %4 ; + count -= mod+1 ; +switch (mod) { +case 3 : ptr[count+3 ] = poison; fallthrough; +case 2 : ptr[count+2 ] = poison; fallthrough; +case 1 : ptr[count+1 ] = poison; fallthrough; +case 0 : ptr[count+0 ] = poison;break ; + } + } +return ; + } + +memset64 ((void *)erase_low, poison, count); +} +#endif +#ifdef CONFIG_PARAVIRT_XXL #include <asm/paravirt.h> #else
Re: [PATCH 2/2] x86/kstack_erase: Use REP STOSQ for large stack fills
In reply to David LaightQuoted 66 lines · On Fri, 20 Nov 2026 11:38:25 +0000 David Laight <[email protected]>…
Quoted 39 lines · On Thu, 19 Nov 2026 14:28:04 -0800 Nick Desaulniers <[email protected]>…
Quoted 38 lines · Usama Arif
With
KSTACK_ERASE, every return to user space poisons the part of the task stack that was used since the previous return. The generic__stackleak_poison()does that one word per loop iteration, so a syscall that went 1-2 KiB deep pays for 128-256 separate stores. On Meta hosts running many small VMs,stackleak_erase()accounts for about 1.5% of non-idle host kernel cycles.Override
__stackleak_poison()on x86-64, as s390 already does, through the hook added by commit491a78663e03("stackleak: allow to specify arch specific stackleak poison function"). Fill spans larger than 512 bytes with REP STOSQ and keep the word loop for shorter ones, where the fixed startup cost of REP STOSQ does not pay off. REP STOSQ starts to win at about 300-400 bytes on Zen 5c and Cooper Lake, so on both no span gets slower.The fill is inline asm, so the noinstr function still makes no calls.
memset64()would be the same instruction, but it is only static inline, and with KMSAN it is an out-of-line function.In a Zen 5c KVM guest,
stackleak_erase()got about 35% cheaper per return to user space (71 ns to 46 ns, scan included) over a futex, epoll, procfs and Unix socket syscall mix. Same-vCPU futex wake/wait and Unix socket sendmsg()/recvmsg() ping-pong round trips got 5-8% faster.Signed-off-by Usama Arif <[email protected]>--- arch/x86/include/asm/processor.h | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+)arch/x86/include/asm/processor.h +0
-0@@ -580,6 +580,31 @@ static __always_inline bool on_thread_stack(void) current_stack_pointer) < THREAD_SIZE; }Quoted 15 lines
Quoted 5 lines
arch/x86/include/asm/processor.h +5
-0+#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison)arch/x86/include/asm/processor.h static __always_inline bool on_thread_stack(void) · line 597
Quoted 10 lines
arch/x86/include/asm/processor.h +10
-0+{ +unsigned long count; + +/* Short spans do not amortize the startup cost of REP STOSQ. */ +if (erase_high <= erase_low +512 ) { +while (erase_low < erase_high) { + *(unsigned long *)erase_low = poison; + erase_low +=sizeof (unsigned long ); + } +return ;gcc 13 onwards makes a meal of that - https://godbolt.org/z/KPP4h8xz6
It does manage to unroll the loop once - which is good because the intel cpu (I've got) won't execute a 'one clock loop' (the zen5 will); but the setup code is horrid.
But I also think some of the more recent cpu can execute more than one write per clock.
If you unroll the loop 4 times it may run a lot faster. Perhaps:
Quoted 5 lines
long count = (erase_high - erase_low) / sizeof(unsigned long);
if (count <= 64) {
while ((count -= 4) >= 0) {
*(unsigned long *)erase_low = poison;
*(unsigned long *)(erase_low + 8) = poison;The add (probably) needs to be in the middle...
erase_low += 32;
Quoted 14 lines
*(unsigned long *)(erase_low - 32 + 16) = poison;
*(unsigned long *)(erase_low - 32 + 24) = poison;
}
if (count & 2) {
*(unsigned long *)erase_low = poison;
*(unsigned long *)(erase_low + 8) = poison;
erase_low += 16;
}
if (count & 1)
*(unsigned long *)erase_low = poison;
} else {
...
}Quoted 4 lines
Except that gcc makes a mess of it again.
I don't think the 'erase_low+= 32' is going to execute at the same time as the last (two probably) writes so costs a clock. So it may need to be asm.
I threw in enough OPTIMIZER_HIDE_VAR() to stop the optimiser breaking the code. https://godbolt.org/z/nx477T4M1
gcc then generates:
movq %rdx, (%rdi)
movq %rdx, 8(%rdi)
addq $32, %rdi
movq %rdx, -16(%rdi)
movq %rdx, -8(%rdi).L32:
subq $4, %rcx
jns .L22
for the code loop (clang is a bit worse - but should be ok). I think that will be a 'two clock loop' on cpu that can do two writes/clock; zen3 and ice lake).
For 'stack splatting' rounding up to a multiple of 32 bytes will save all the 'remainder' code.
David
Quoted 30 lines
Quoted 11 lines
arch/x86/include/asm/processor.h static __always_inline bool on_thread_stack(void) · line 604
Quoted 8 lines
arch/x86/include/asm/processor.h +7
-0+ } + + count = (erase_high - erase_low) /sizeof (unsigned long ); + asmvolatile ("rep stosq" + :"+D" (erase_low),"+c" (count) + :"a" (poison) + :"memory" );Surely this isn't the only place using
rep stosqin the tree, right? It's not, see memset64 inarch/x86/include/asm/string_64.h.Which seems to have very few users.
memset_p()andmemset_l()have almost no users.David
Quoted 12 lines
Quoted 10 lines
arch/x86/include/asm/processor.h +3
-1+} +#endif +#ifdef CONFIG_PARAVIRT_XXL #include <asm/paravirt.h> #else --2.53.1-Meta
Re: [PATCH 2/2] x86/kstack_erase: Use REP STOSQ for large stack fills
In reply to Peter ZijlstraQuoted 20 lines · On Fri, 20 Nov 2026 11:45:34 +0100 Peter Zijlstra <[email protected]> wrote:
Quoted 19 lines · Usama Arif
arch/x86/include/asm/processor.h +19
-0+#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +unsigned long count; + +/* Short spans do not amortize the startup cost of REP STOSQ. */ +if (erase_high <= erase_low +512 ) { +while (erase_low < erase_high) { + *(unsigned long *)erase_low = poison; + erase_low +=sizeof (unsigned long ); + } +return ; + } + + count = (erase_high - erase_low) /sizeof (unsigned long ); + asm volatile("rep stosq"
Quoted 8 lines
Review
Quoted 5 lines
(quoted diff) +5
-0+ : "+D" (erase_low), "+c" (count) + : "a" (poison) + : "memory"); +} +#endifGemini seems to suggest 16-32 words would be sufficient to amortize the REP STOS setup.
That really does sound like wishful thinking.
Especially if you go back a few generations on the cpu architecture.
Quoted 31 lines
It was also adamant I try and unroll that earlier loop.
How about something like so, does that make sense? Also, I suppose we should make
memset64()__always_inlineif we use it here. I'm not at all sold on the unroll here, the asm is pretty horrid for what it does.---
arch/x86/include/asm/processor.h +11
-0@@ -28,6 +28,7 @@ struct vm86;#include <asm/vmxfeatures.h> #include <asm/vdso/processor.h> #include <asm/shstk.h> +#include <asm/string.h> #include <linux/personality.h> #include <linux/cache.h> @@ -580,6 +581,33 @@ static __always_inline bool on_thread_st current_stack_pointer) < THREAD_SIZE; } +#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +unsigned long count = (erase_high - erase_low) /sizeof (unsigned long ); + +/* Amortize the startup cost of REP STOSQ. */ +if (count <32 ) {
arch/x86/include/asm/processor.h static __always_inline bool on_thread_st · line 603
Quoted 10 lines
arch/x86/include/asm/processor.h +10
-0+unsigned long *ptr = (unsigned long *)erase_low; + +while (count) { +switch ((count-1 ) %4 ) { +case 3 : ptr[--count] = poison; fallthrough; +case 2 : ptr[--count] = poison; fallthrough; +case 1 : ptr[--count] = poison; fallthrough; +case 0 : ptr[--count] = poison;break ; + } + }
That looks horrid to me.
You want as few instructions (especially conditionals) inside the loop as possible.
The Intel cpu will execute a two clock loop and the later ones will do two writes per clock
(zen5 will execute a one clock loop and do two writes/clock). So you want a loop with just 4 writes and the loop control code. The 'pointer add' just needs to execute at the same time as some of the stores - to avoid lengthening the register dependency chain.
For this code, can the length be a multiple of 32?
Also on some cpu the 'rep stos' might be twice as fast (per byte) if the destination in 64 byte aligned - true for 'rep movsb'.
David
Quoted 11 lines
arch/x86/include/asm/processor.h +7
-0+ return; + } + +memset64 ((void *)erase_low, poison, count); +} +#endif +#ifdef CONFIG_PARAVIRT_XXL #include <asm/paravirt.h> #else
Re: [PATCH 2/2] x86/kstack_erase: Use REP STOSQ for large stack fills
Quoted 32 lines · David Laight
Quoted 20 lines · On Fri, 20 Nov 2026 11:45:34 +0100 Peter Zijlstra <[email protected]> wrote:
Quoted 19 lines · Usama Arif
arch/x86/include/asm/processor.h +19
-0+#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +unsigned long count; + +/* Short spans do not amortize the startup cost of REP STOSQ. */ +if (erase_high <= erase_low +512 ) { +while (erase_low < erase_high) { + *(unsigned long *)erase_low = poison; + erase_low +=sizeof (unsigned long ); + } +return ; + } + + count = (erase_high - erase_low) /sizeof (unsigned long ); + asm volatile("rep stosq"Quoted 8 lines
Review
Quoted 5 lines
(quoted diff) +5
-0+ : "+D" (erase_low), "+c" (count) + : "a" (poison) + : "memory"); +} +#endifGemini seems to suggest 16-32 words would be sufficient to amortize the REP STOS setup.
Quoted 2 lines
That really does sound like wishful thinking.
Especially if you go back a few generations on the cpu architecture.
How old? I mean, Interlagos old, sure, but nobody should care about performance there I think.
AFAICT Nehalem and later should be good with the 16-32 words. As would all the various Zen chips.
Re: [PATCH 2/2] x86/kstack_erase: Use REP STOSQ for large stack fills
Quoted 33 lines · On Fri, 20 Nov 2026 16:35:39 +0100 Peter Zijlstra <[email protected]> wrote:
Quoted 32 lines · David Laight
Quoted 28 lines · On Fri, 20 Nov 2026 11:45:34 +0100 Peter Zijlstra <[email protected]> wrote:
Quoted 14 lines · Usama Arif
arch/x86/include/asm/processor.h +14
-0+#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +unsigned long count; + +/* Short spans do not amortize the startup cost of REP STOSQ. */ +if (erase_high <= erase_low +512 ) { +while (erase_low < erase_high) { + *(unsigned long *)erase_low = poison; + erase_low +=sizeof (unsigned long ); + }arch/x86/include/asm/processor.h static __always_inline bool on_thread_st · line 609
Quoted 10 lines
arch/x86/include/asm/processor.h +10
-0+ return; + } + + count = (erase_high - erase_low) /sizeof (unsigned long ); + asmvolatile ("rep stosq" + :"+D" (erase_low),"+c" (count) + :"a" (poison) + :"memory" ); +} +#endif Gemini seems to suggest 16-32 words would be sufficient to amortize the REP STOS setup.
Quoted 8 lines
Quoted 2 lines
That really does sound like wishful thinking.
Especially if you go back a few generations on the cpu architecture.How old? I mean, Interlagos old, sure, but nobody should care about performance there I think.
AFAICT Nehalem and later should be good with the 16-32 words. As would all the various Zen chips.
Have you got an accurate source for the setup costs for 'rep stos/movs' for the various architectures?
I didn't find one last time I looked.
Last time I measured rep movs I was using mfence to synchronise with rdpmc and that takes even longer - so you only get the per-byte costs. (You can use data-dependencies which have minimal overhead unless you go back to to some pre-zen amd cpu.)
You get 16 bytes/clock until Haswell which will do 32 if rdi is aligned. Icelake might increase that to 64 bytes/clock.
Agner has zen2 onwards at 32 bytes/clock.
Agner also has zen3 and Icelake being able to do 2 writes per clock. If that is achievable for the writes being done (the loop isn't a problem) then it also takes a while for the 'rep stos' to catch up. (Then you have the cost of the I-cache misses ...)
David
Re: [PATCH 2/2] x86/kstack_erase: Use REP STOSQ for large stack fills
In reply to Peter ZijlstraQuoted 65 lines · Peter Zijlstra
Quoted 29 lines · Peter Zijlstra
Quoted 14 lines · Usama Arif
(quoted diff) +14
-0+#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, + unsigned long erase_high, + unsigned long poison) +{ + unsigned long count; + + /* Short spans do not amortize the startup cost of REP STOSQ. */ + if (erase_high <= erase_low + 512) { + while (erase_low < erase_high) { + *(unsigned long *)erase_low = poison; + erase_low += sizeof(unsigned long); + }Review
Quoted 10 lines
(quoted diff) +10
-0+ return; + } + + count = (erase_high - erase_low) / sizeof(unsigned long); + asm volatile("rep stosq" + : "+D" (erase_low), "+c" (count) + : "a" (poison) + : "memory"); +} +#endifGemini seems to suggest 16-32 words would be sufficient to amortize the REP STOS setup. It was also adamant I try and unroll that earlier loop.
Quoted 3 lines
How about something like so, does that make sense? Also, I suppose we should make
memset64()__always_inlineif we use it here. I'm not at all sold on the unroll here, the asm is pretty horrid for what it does.This one is much improved:
arch/x86/include/asm/processor.h +16
-0@@ -28,6 +28,7 @@ struct vm86;#include <asm/vmxfeatures.h> #include <asm/vdso/processor.h> #include <asm/shstk.h> +#include <asm/string.h> #include <linux/personality.h> #include <linux/cache.h> @@ -580,6 +581,35 @@ static __always_inline bool on_thread_st current_stack_pointer) < THREAD_SIZE; } +#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +unsigned long count = (erase_high - erase_low) /sizeof (unsigned long ); + +/* Amortize the startup cost of REP STOSQ. */ +if (count <32 ) { +unsigned long *ptr = (unsigned long *)erase_low; + +while (count) { +unsigned long mod = (count-1 ) %4 ; + count -= mod+1 ;
arch/x86/include/asm/processor.h static __always_inline bool on_thread_st · line 608
Quoted 10 lines
arch/x86/include/asm/processor.h +10
-0+switch (mod) { +case 3 : ptr[count+3 ] = poison; fallthrough; +case 2 : ptr[count+2 ] = poison; fallthrough; +case 1 : ptr[count+1 ] = poison; fallthrough; +case 0 : ptr[count+0 ] = poison;break ; + } + } +return ; + } +
Hello Nick, Peter and David,
Thanks for the reviews! I should have used memset64 from the get go :)
I have tested 2 possible revisions now as well as this one from Peter, have added both of them at the end of the reply.
- v2.1 where you loop upto 512B and then memset
- v2.2: 4 stores per loop up to 512 B, then 64-byte aligned memset64()
I timed stackleak_erase() in a Zen 5c guest over a futex/epoll/procfs/unix syscall:
No patch 68.3 ns per erase
v1 (loop up to 512 B, then REP) 46.6 ns v2.1 (loop up to 512 B, memset64()) 46.6 ns this version 46.4 ns v2.2 (4 stores/iteration, aligned REP) 43.7 ns
The switch doesn't seem to help.
Either way I kept 512 bytes: REP STOSQ only wins from ~430 bytes on Zen 5c against the plain loop (~850 against the unrolled one), and from ~320 on Cooper Lake.
My personal preference is v2.1, as its much simpler code and the difference in performance between v2.1 and v2.2 isn't actually that much. But if there is a stronger preference for v2.2, I can send that as it is faster.
v2.1:
arch/x86/include/asm/processor.h +21 -0
@@ -28,6 +28,7 @@ struct vm86;#include <asm/vmxfeatures.h> #include <asm/vdso/processor.h> #include <asm/shstk.h> +#include <asm/string.h> #include <linux/personality.h> #include <linux/cache.h>
@@ -580,6 +581,26 @@ static __always_inline bool on_thread_stack(void) current_stack_pointer) < THREAD_SIZE; } +#if defined(CONFIG_X86_64 ) && !defined(CONFIG_KMSAN ) +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +/* Short spans do not amortize the startup cost of REP STOSQ. */ +if (erase_high <= erase_low +512 ) { +while (erase_low < erase_high) { + *(unsigned long *)erase_low = poison; + erase_low +=sizeof (unsigned long ); + } +return ; + } + +memset64 ((u64 *)erase_low, poison, + (erase_high - erase_low) /sizeof (u64)); +} +#endif +#ifdef CONFIG_PARAVIRT_XXL #include <asm/paravirt.h> #else
arch/x86/include/asm/string_64.h +1 -1
@@ -54,7 +54,7 @@ static inline void *memset32(uint32_t *s, uint32_t v, size_t n) }#define __HAVE_ARCH_MEMSET64 -static inline void *memset64 (uint64_t *s,uint64_t v,size_t n) +static __always_inline void *memset64(uint64_t *s, uint64_t v, size_t n) { const auto s0 = s; asm volatile (
v2.2:
arch/x86/include/asm/processor.h +44 -0
57 lines not on this page · raw message
arch/x86/include/asm/string_64.h +1 -1
@@ -54,7 +54,7 @@ static inline void *memset32(uint32_t *s, uint32_t v, size_t n) }#define __HAVE_ARCH_MEMSET64 -static inline void *memset64 (uint64_t *s,uint64_t v,size_t n) +static __always_inline void *memset64(uint64_t *s, uint64_t v, size_t n) { const auto s0 = s; asm volatile (
Quoted 7 lines
arch/x86/include/asm/processor.h +4
-0+ memset64((void *)erase_low, poison, count); +} +#endif +#ifdef CONFIG_PARAVIRT_XXL #include <asm/paravirt.h> #else
Re: [PATCH 2/2] x86/kstack_erase: Use REP STOSQ for large stack fills
In reply to David LaightQuoted 104 lines · David Laight
Quoted 66 lines · On Fri, 20 Nov 2026 11:38:25 +0000 David Laight <[email protected]>…
Quoted 39 lines · On Thu, 19 Nov 2026 14:28:04 -0800 Nick Desaulniers <[email protected]>…
Quoted 38 lines · Usama Arif
With
KSTACK_ERASE, every return to user space poisons the part of the task stack that was used since the previous return. The generic__stackleak_poison()does that one word per loop iteration, so a syscall that went 1-2 KiB deep pays for 128-256 separate stores. On Meta hosts running many small VMs,stackleak_erase()accounts for about 1.5% of non-idle host kernel cycles.Override
__stackleak_poison()on x86-64, as s390 already does, through the hook added by commit491a78663e03("stackleak: allow to specify arch specific stackleak poison function"). Fill spans larger than 512 bytes with REP STOSQ and keep the word loop for shorter ones, where the fixed startup cost of REP STOSQ does not pay off. REP STOSQ starts to win at about 300-400 bytes on Zen 5c and Cooper Lake, so on both no span gets slower.The fill is inline asm, so the noinstr function still makes no calls.
memset64()would be the same instruction, but it is only static inline, and with KMSAN it is an out-of-line function.In a Zen 5c KVM guest,
stackleak_erase()got about 35% cheaper per return to user space (71 ns to 46 ns, scan included) over a futex, epoll, procfs and Unix socket syscall mix. Same-vCPU futex wake/wait and Unix socket sendmsg()/recvmsg() ping-pong round trips got 5-8% faster.Signed-off-by Usama Arif <[email protected]>--- arch/x86/include/asm/processor.h | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+)arch/x86/include/asm/processor.h +0
-0@@ -580,6 +580,31 @@ static __always_inline bool on_thread_stack(void) current_stack_pointer) < THREAD_SIZE; }Quoted 15 lines
Quoted 5 lines
arch/x86/include/asm/processor.h +5
-0+#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison)arch/x86/include/asm/processor.h static __always_inline bool on_thread_stack(void) · line 597
Quoted 10 lines
arch/x86/include/asm/processor.h +10
-0+{ +unsigned long count; + +/* Short spans do not amortize the startup cost of REP STOSQ. */ +if (erase_high <= erase_low +512 ) { +while (erase_low < erase_high) { + *(unsigned long *)erase_low = poison; + erase_low +=sizeof (unsigned long ); + } +return ;gcc 13 onwards makes a meal of that - https://godbolt.org/z/KPP4h8xz6
It does manage to unroll the loop once - which is good because the intel cpu (I've got) won't execute a 'one clock loop' (the zen5 will); but the setup code is horrid.
But I also think some of the more recent cpu can execute more than one write per clock.
If you unroll the loop 4 times it may run a lot faster. Perhaps:Quoted 5 lines
long count = (erase_high - erase_low) / sizeof(unsigned long); if (count <= 64) { while ((count -= 4) >= 0) { *(unsigned long *)erase_low = poison; *(unsigned long *)(erase_low + 8) = poison;The add (probably) needs to be in the middle...
erase_low+= 32;Quoted 14 lines
*(unsigned long *)(erase_low - 32 + 16) = poison; *(unsigned long *)(erase_low - 32 + 24) = poison; } if (count & 2) { *(unsigned long *)erase_low = poison; *(unsigned long *)(erase_low + 8) = poison; erase_low += 16; } if (count & 1) *(unsigned long *)erase_low = poison; } else { ... }Quoted 4 lines
Except that gcc makes a mess of it again.
I don't think the 'erase_low+= 32' is going to execute at the same time as the last (two probably) writes so costs a clock. So it may need to be asm.I threw in enough
OPTIMIZER_HIDE_VAR()to stop the optimiser breaking the code. https://godbolt.org/z/nx477T4M1
gcc then generates:movq %rdx, (%rdi) movq %rdx, 8(%rdi) addq $32, %rdi movq %rdx, -16(%rdi) movq %rdx, -8(%rdi)
Quoted 8 lines
.L32:
subq $4, %rcx
jns .L22
for the code loop (clang is a bit worse - but should be ok). I think that will be a 'two clock loop' on cpu that can do two writes/clock; zen3 and ice lake).
For 'stack splatting' rounding up to a multiple of 32 bytes will save all the 'remainder' code.
The range can't be rounded: erase_low is wherever the poison search stopped, and erase_high is the stack pointer or the bottom of pt_regs (168 bytes, so only 8-byte aligned). Rounding up writes live stack, rounding down can write STACK_END_MAGIC when the stack was used to the end.
Quoted 34 lines
David
Quoted 30 lines
Quoted 11 lines
arch/x86/include/asm/processor.h static __always_inline bool on_thread_stack(void) · line 604
Quoted 8 lines
arch/x86/include/asm/processor.h +7
-0+ } + + count = (erase_high - erase_low) /sizeof (unsigned long ); + asmvolatile ("rep stosq" + :"+D" (erase_low),"+c" (count) + :"a" (poison) + :"memory" );Surely this isn't the only place using
rep stosqin the tree, right? It's not, see memset64 inarch/x86/include/asm/string_64.h.Which seems to have very few users.
memset_p()andmemset_l()have almost no users.David
Quoted 12 lines
Quoted 10 lines
arch/x86/include/asm/processor.h +3
-1+} +#endif +#ifdef CONFIG_PARAVIRT_XXL #include <asm/paravirt.h> #else --2.53.1-Meta
Re: [PATCH 2/2] x86/kstack_erase: Use REP STOSQ for large stack fills
In reply to Usama ArifQuoted 7 lines · On Thu, 19 Nov 2026 13:31:08 -0800 Usama Arif <[email protected]> wrote:
With
KSTACK_ERASE, every return to user space poisons the part of the task stack that was used since the previous return. The generic__stackleak_poison()does that one word per loop iteration, so a syscall that went 1-2 KiB deep pays for 128-256 separate stores. On Meta hosts running many small VMs,stackleak_erase()accounts for about 1.5% of non-idle host kernel cycles.
Quoted 7 lines
Override
__stackleak_poison()on x86-64, as s390 already does, through the hook added by commit491a78663e03("stackleak: allow to specify arch specific stackleak poison function"). Fill spans larger than 512 bytes with REP STOSQ and keep the word loop for shorter ones, where the fixed startup cost of REP STOSQ does not pay off. REP STOSQ starts to win at about 300-400 bytes on Zen 5c and Cooper Lake, so on both no span gets slower.
As a matter of interest (and separately from the exact code) how did you measure the performance to get the 300-400 byte gain point?
If the count is variable - likely in real life, you'll get a branch misprediction penalty (about 20 clocks on zen5) every time you change between the two choices.
The copy loop will have another mispredict penalty for the loop itself.
So you are likely to get an overall improvement if you use 'rep stos' for all lengths - even the ones for with it is slightly slower. Unless, that is, you know at compile time that most of the length will be short.
David
Quoted 51 lines
The fill is inline asm, so the noinstr function still makes no calls.
memset64()would be the same instruction, but it is only static inline, and with KMSAN it is an out-of-line function.In a Zen 5c KVM guest,
stackleak_erase()got about 35% cheaper per return to user space (71 ns to 46 ns, scan included) over a futex, epoll, procfs and Unix socket syscall mix. Same-vCPU futex wake/wait and Unix socket sendmsg()/recvmsg() ping-pong round trips got 5-8% faster.Signed-off-by Usama Arif <[email protected]>--- arch/x86/include/asm/processor.h | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+)arch/x86/include/asm/processor.h +25
-0@@ -580,6 +580,31 @@ static __always_inline bool on_thread_stack(void) current_stack_pointer) < THREAD_SIZE; } +#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +unsigned long count; + +/* Short spans do not amortize the startup cost of REP STOSQ. */ +if (erase_high <= erase_low +512 ) { +while (erase_low < erase_high) { + *(unsigned long *)erase_low = poison; + erase_low +=sizeof (unsigned long ); + } +return ; + } + + count = (erase_high - erase_low) /sizeof (unsigned long ); + asmvolatile ("rep stosq" + :"+D" (erase_low),"+c" (count) + :"a" (poison) + :"memory" ); +} +#endif +#ifdef CONFIG_PARAVIRT_XXL #include <asm/paravirt.h> #else
Re: [PATCH 2/2] x86/kstack_erase: Use REP STOSQ for large stack fills
In reply to Usama ArifQuoted 115 lines · On Fri, 20 Nov 2026 18:46:01 +0000 Usama Arif <[email protected]> wrote:
Quoted 104 lines · David Laight
Quoted 66 lines · On Fri, 20 Nov 2026 11:38:25 +0000 David Laight <[email protected]>…
Quoted 39 lines · On Thu, 19 Nov 2026 14:28:04 -0800 Nick Desaulniers <[email protected]>…
Quoted 38 lines · Usama Arif
With
KSTACK_ERASE, every return to user space poisons the part of the task stack that was used since the previous return. The generic__stackleak_poison()does that one word per loop iteration, so a syscall that went 1-2 KiB deep pays for 128-256 separate stores. On Meta hosts running many small VMs,stackleak_erase()accounts for about 1.5% of non-idle host kernel cycles.Override
__stackleak_poison()on x86-64, as s390 already does, through the hook added by commit491a78663e03("stackleak: allow to specify arch specific stackleak poison function"). Fill spans larger than 512 bytes with REP STOSQ and keep the word loop for shorter ones, where the fixed startup cost of REP STOSQ does not pay off. REP STOSQ starts to win at about 300-400 bytes on Zen 5c and Cooper Lake, so on both no span gets slower.The fill is inline asm, so the noinstr function still makes no calls.
memset64()would be the same instruction, but it is only static inline, and with KMSAN it is an out-of-line function.In a Zen 5c KVM guest,
stackleak_erase()got about 35% cheaper per return to user space (71 ns to 46 ns, scan included) over a futex, epoll, procfs and Unix socket syscall mix. Same-vCPU futex wake/wait and Unix socket sendmsg()/recvmsg() ping-pong round trips got 5-8% faster.Signed-off-by Usama Arif <[email protected]>--- arch/x86/include/asm/processor.h | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+)arch/x86/include/asm/processor.h +0
-0@@ -580,6 +580,31 @@ static __always_inline bool on_thread_stack(void) current_stack_pointer) < THREAD_SIZE; }Quoted 15 lines
Quoted 5 lines
arch/x86/include/asm/processor.h +5
-0+#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison)arch/x86/include/asm/processor.h static __always_inline bool on_thread_stack(void) · line 597
Quoted 10 lines
arch/x86/include/asm/processor.h +10
-0+{ +unsigned long count; + +/* Short spans do not amortize the startup cost of REP STOSQ. */ +if (erase_high <= erase_low +512 ) { +while (erase_low < erase_high) { + *(unsigned long *)erase_low = poison; + erase_low +=sizeof (unsigned long ); + } +return ;gcc 13 onwards makes a meal of that - https://godbolt.org/z/KPP4h8xz6
It does manage to unroll the loop once - which is good because the intel cpu (I've got) won't execute a 'one clock loop' (the zen5 will); but the setup code is horrid.
But I also think some of the more recent cpu can execute more than one write per clock.
If you unroll the loop 4 times it may run a lot faster. Perhaps:Quoted 5 lines
long count = (erase_high - erase_low) / sizeof(unsigned long); if (count <= 64) { while ((count -= 4) >= 0) { *(unsigned long *)erase_low = poison; *(unsigned long *)(erase_low + 8) = poison;The add (probably) needs to be in the middle...
erase_low+= 32;Quoted 14 lines
*(unsigned long *)(erase_low - 32 + 16) = poison; *(unsigned long *)(erase_low - 32 + 24) = poison; } if (count & 2) { *(unsigned long *)erase_low = poison; *(unsigned long *)(erase_low + 8) = poison; erase_low += 16; } if (count & 1) *(unsigned long *)erase_low = poison; } else { ... }Quoted 4 lines
Except that gcc makes a mess of it again.
I don't think the 'erase_low+= 32' is going to execute at the same time as the last (two probably) writes so costs a clock. So it may need to be asm.I threw in enough
OPTIMIZER_HIDE_VAR()to stop the optimiser breaking the code. https://godbolt.org/z/nx477T4M1
gcc then generates:movq %rdx, (%rdi) movq %rdx, 8(%rdi) addq $32, %rdi movq %rdx, -16(%rdi) movq %rdx, -8(%rdi)Quoted 8 lines
.L32:
subq $4, %rcx
jns .L22
for the code loop (clang is a bit worse - but should be ok). I think that will be a 'two clock loop' on cpu that can do two writes/clock; zen3 and ice lake).
For 'stack splatting' rounding up to a multiple of 32 bytes will save all the 'remainder' code.
Quoted 5 lines
The range can't be rounded:
erase_lowis wherever the poison search stopped, anderase_highis the stack pointer or the bottom ofpt_regs(168 bytes, so only 8-byte aligned). Rounding up writes live stack, rounding down can writeSTACK_END_MAGICwhen the stack was used to the end.
If the stack down by STACK_END_MAGIC has been written you are almost in 'deep do-do land' so task_low_bound() could return an aligned address and that would let you align down the low address.
(So leaving the very last few words alone.)
It also probably doesn't really matter about the top few words. So the length could be rounded down.
Alternatively, do STACK_END_MAGIC and STACK_ERASE_POISON even need to have different values?
(And aren't stacks now allocated with a guard page - so you get a fault on overflow much earlier than any check for STACK_END_MAGIC.)
But does this code even work in a useful manner.
It seems to stop scanning after finding 128 bytes of KSTACK_ERASE_POISON. Isn't that going to stop on a function with a large on-stack buffer (especially since one is likely to be on the deepest part of the stack). I'd have thought you'd jump down the stack in larger lumps than that just looking for an unwritten word before even trying to decide if it was the boundary.
David
Quoted 37 lines
Quoted 36 lines
David
Quoted 30 lines
Quoted 11 lines
arch/x86/include/asm/processor.h static __always_inline bool on_thread_stack(void) · line 604
Quoted 8 lines
arch/x86/include/asm/processor.h +7
-0+ } + + count = (erase_high - erase_low) /sizeof (unsigned long ); + asmvolatile ("rep stosq" + :"+D" (erase_low),"+c" (count) + :"a" (poison) + :"memory" );Surely this isn't the only place using
rep stosqin the tree, right? It's not, see memset64 inarch/x86/include/asm/string_64.h.Which seems to have very few users.
memset_p()andmemset_l()have almost no users.David
Quoted 12 lines
Quoted 10 lines
arch/x86/include/asm/processor.h +3
-1+} +#endif +#ifdef CONFIG_PARAVIRT_XXL #include <asm/paravirt.h> #else --2.53.1-Meta
Re: [PATCH 2/2] x86/kstack_erase: Use REP STOSQ for large stack fills
In reply to Usama ArifQuoted 87 lines · On Fri, 20 Nov 2026 18:43:38 +0000 Usama Arif <[email protected]> wrote:
Quoted 65 lines · Peter Zijlstra
Quoted 29 lines · Peter Zijlstra
Quoted 14 lines · Usama Arif
arch/x86/include/asm/processor.h +14
-0+#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +unsigned long count; + +/* Short spans do not amortize the startup cost of REP STOSQ. */ +if (erase_high <= erase_low +512 ) { +while (erase_low < erase_high) { + *(unsigned long *)erase_low = poison; + erase_low +=sizeof (unsigned long ); + }arch/x86/include/asm/processor.h static __always_inline bool on_thread_stack(void) · line 602
Quoted 10 lines
arch/x86/include/asm/processor.h +10
-0+ return; + } + + count = (erase_high - erase_low) /sizeof (unsigned long ); + asmvolatile ("rep stosq" + :"+D" (erase_low),"+c" (count) + :"a" (poison) + :"memory" ); +} +#endif Gemini seems to suggest 16-32 words would be sufficient to amortize the REP STOS setup. It was also adamant I try and unroll that earlier loop.
Quoted 3 lines
How about something like so, does that make sense? Also, I suppose we should make
memset64()__always_inlineif we use it here. I'm not at all sold on the unroll here, the asm is pretty horrid for what it does.This one is much improved:
arch/x86/include/asm/processor.h +16
-0@@ -28,6 +28,7 @@ struct vm86;#include <asm/vmxfeatures.h> #include <asm/vdso/processor.h> #include <asm/shstk.h> +#include <asm/string.h> #include <linux/personality.h> #include <linux/cache.h> @@ -580,6 +581,35 @@ static __always_inline bool on_thread_st current_stack_pointer) < THREAD_SIZE; } +#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +unsigned long count = (erase_high - erase_low) /sizeof (unsigned long ); + +/* Amortize the startup cost of REP STOSQ. */ +if (count <32 ) { +unsigned long *ptr = (unsigned long *)erase_low; + +while (count) { +unsigned long mod = (count-1 ) %4 ; + count -= mod+1 ;arch/x86/include/asm/processor.h static __always_inline bool on_thread_st · line 608
Quoted 10 lines
arch/x86/include/asm/processor.h +10
-0+switch (mod) { +case 3 : ptr[count+3 ] = poison; fallthrough; +case 2 : ptr[count+2 ] = poison; fallthrough; +case 1 : ptr[count+1 ] = poison; fallthrough; +case 0 : ptr[count+0 ] = poison;break ; + } + } +return ; + } +Hello Nick, Peter and David,
Thanks for the reviews! I should have used memset64 from the get go :)
I have tested 2 possible revisions now as well as this one from Peter, have added both of them at the end of the reply.
- v2.1 where you loop upto 512B and then memset
- v2.2: 4 stores per loop up to 512 B, then 64-byte alignedmemset64()
Quoted 8 lines
I timed
stackleak_erase()in a Zen 5c guest over a futex/epoll/procfs/unix syscall:No patch 68.3 ns per erase
v1 (loop up to 512 B, then REP) 46.6 ns v2.1 (loop up to 512 B, memset64()) 46.6 ns this version 46.4 ns v2.2 (4 stores/iteration, aligned REP) 43.7 ns
What are the lengths of those erases?
(and where does the 46ns come from??)
I'd definitely time 'just the code loop - various loops' and 'just rep stos'.
Quoted 1 line
The switch doesn't seem to help.
To many conditions in the loop.
You could do it this way:
switch (count & 3) {
case 0: do { *ptr++ = poison;
case 3: *ptr++ = poison;
case 2: *ptr++ = poison;
case 1: *ptr++ = poison;
} while ((count -= 4) > 0);
}(give or take some off-by-one here and there). But I suspect that using Duff's device is frowned up.
Quoted 2 lines
Either way I kept 512 bytes: REP STOSQ only wins from ~430 bytes on Zen 5c against the plain loop (~850 against the unrolled one),
For zen5 you should only need to unroll the loop once (two writes per iteration). In my experiments it can execute a loop in one clock.
Unless the compiler unrolled it for you (and got it right!) the original loop would be half the speed
Quoted 1 line
and from ~320 on Cooper Lake.
I'd also try some older Intel cpu.
The setup costs are likely to be higher with FRMS and friends.
David
Quoted 154 lines
My personal preference is v2.1, as its much simpler code and the difference in performance between v2.1 and v2.2 isn't actually that much. But if there is a stronger preference for v2.2, I can send that as it is faster.
v2.1:
arch/x86/include/asm/processor.h +21
-0@@ -28,6 +28,7 @@ struct vm86;#include <asm/vmxfeatures.h> #include <asm/vdso/processor.h> #include <asm/shstk.h> +#include <asm/string.h> #include <linux/personality.h> #include <linux/cache.h> @@ -580,6 +581,26 @@ static __always_inline bool on_thread_stack(void) current_stack_pointer) < THREAD_SIZE; } +#if defined(CONFIG_X86_64 ) && !defined(CONFIG_KMSAN ) +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +/* Short spans do not amortize the startup cost of REP STOSQ. */ +if (erase_high <= erase_low +512 ) { +while (erase_low < erase_high) { + *(unsigned long *)erase_low = poison; + erase_low +=sizeof (unsigned long ); + } +return ; + } + +memset64 ((u64 *)erase_low, poison, + (erase_high - erase_low) /sizeof (u64)); +} +#endif +#ifdef CONFIG_PARAVIRT_XXL #include <asm/paravirt.h> #else arch/x86/include/asm/string_64.h +1
-1@@ -54,7 +54,7 @@ static inline void *memset32(uint32_t *s, uint32_t v, size_t n) }#define __HAVE_ARCH_MEMSET64 -static inline void *memset64 (uint64_t *s,uint64_t v,size_t n) +static __always_inline void *memset64(uint64_t *s, uint64_t v, size_t n) { const auto s0 = s; asm volatile (v2.2:
arch/x86/include/asm/processor.h +44
-0@@ -28,7 +28,9 @@ struct vm86;#include <asm/vmxfeatures.h> #include <asm/vdso/processor.h> #include <asm/shstk.h> +#include <asm/string.h> +#include <linux/align.h> #include <linux/personality.h> #include <linux/cache.h> #include <linux/threads.h> @@ -580,6 +582,48 @@ static __always_inline bool on_thread_stack(void) current_stack_pointer) < THREAD_SIZE; } +#if defined(CONFIG_X86_64 ) && !defined(CONFIG_KMSAN ) +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +unsigned long *p = (unsigned long *)erase_low; +unsigned long *end = (unsigned long *)erase_high; +unsigned long i; + +/* Fewer than four words, or nothing to do. */ +if (erase_high < erase_low +4 *sizeof (*p)) { +while (p < end) + *p++ = poison; +return ; + } + +/* Four stores per iteration; the last four may overlap. */ +if (erase_high - erase_low <=512 ) { + end -=4 ; +while (p < end) { + p[0 ] = poison; + p[1 ] = poison; + p[2 ] = poison; + p[3 ] = poison; + p +=4 ; + } + end[0 ] = poison; + end[1 ] = poison; + end[2 ] = poison; + end[3 ] = poison; +return ; + } + +/* REP STOSQ is faster from a 64-byte aligned destination. */ +for (i =0 ; i <8 ; i++) + p[i] = poison; + p = (unsigned long *)ALIGN (erase_low +1 ,64 ); +memset64 ((u64 *)p, poison, end - p); +} +#endif +#ifdef CONFIG_PARAVIRT_XXL #include <asm/paravirt.h> #else arch/x86/include/asm/string_64.h +1
-1@@ -54,7 +54,7 @@ static inline void *memset32(uint32_t *s, uint32_t v, size_t n) }#define __HAVE_ARCH_MEMSET64 -static inline void *memset64 (uint64_t *s,uint64_t v,size_t n) +static __always_inline void *memset64(uint64_t *s, uint64_t v, size_t n) { const auto s0 = s; asm volatile (Quoted 8 lines
arch/x86/include/asm/processor.h +4
-0+ memset64((void *)erase_low, poison, count); +} +#endif +#ifdef CONFIG_PARAVIRT_XXL #include <asm/paravirt.h> #else
Re: [PATCH 2/2] x86/kstack_erase: Use REP STOSQ for large stack fills
In reply to David LaightQuoted 18 lines · David Laight
Quoted 7 lines · On Thu, 19 Nov 2026 13:31:08 -0800 Usama Arif <[email protected]> wrote:
With
KSTACK_ERASE, every return to user space poisons the part of the task stack that was used since the previous return. The generic__stackleak_poison()does that one word per loop iteration, so a syscall that went 1-2 KiB deep pays for 128-256 separate stores. On Meta hosts running many small VMs,stackleak_erase()accounts for about 1.5% of non-idle host kernel cycles.Quoted 7 lines
Override
__stackleak_poison()on x86-64, as s390 already does, through the hook added by commit491a78663e03("stackleak: allow to specify arch specific stackleak poison function"). Fill spans larger than 512 bytes with REP STOSQ and keep the word loop for shorter ones, where the fixed startup cost of REP STOSQ does not pay off. REP STOSQ starts to win at about 300-400 bytes on Zen 5c and Cooper Lake, so on both no span gets slower.
Quoted 3 lines
As a matter of interest (and separately from the exact code) how did you measure the performance to get the 300-400 byte gain point?
With a userspace benchmark pinned to one CPU. Each sample is one fill of a stack buffer straight after a getppid() syscall, with lfence;rdtsc;lfence around the fill only, an empty call subtracted, and the mean of 15 times taken. The size stayed fixed for a whole run, so the branches were well predicted. The plain loop and REP STOSQ cost the same at about 430 bytes on Zen 5c and 320 bytes on Cooper Lake.
Quoted 9 lines
If the count is variable - likely in real life, you'll get a branch misprediction penalty (about 20 clocks on zen5) every time you change between the two choices.
The copy loop will have another mispredict penalty for the loop itself.So you are likely to get an overall improvement if you use 'rep stos' for all lengths - even the ones for with it is slightly slower. Unless, that is, you know at compile time that most of the length will be short.
I timed every stackleak_erase() in a Zen 5c guest running a futex, epoll, procfs and unix socket mix, with the variants switchable at runtime and alternated over 15 rounds:
Unpatched 68.3 ns per erase REP STOSQ for all lengths 47.3 ns v1 / v2.1 (loop up to 512 B) 46.6 ns v2.2 (4 stores/iteration) 43.7 ns
The spans aren't random. Unix socket and /proc/self/stat exits were over 1 KiB every time, while getppid(), epoll_wait(), read() and write() exits were under 128 bytes almost everytime.
My preference still is v2.1 because of the simplicity.
Quoted 55 lines
David
Quoted 51 lines
The fill is inline asm, so the noinstr function still makes no calls.
memset64()would be the same instruction, but it is only static inline, and with KMSAN it is an out-of-line function.In a Zen 5c KVM guest,
stackleak_erase()got about 35% cheaper per return to user space (71 ns to 46 ns, scan included) over a futex, epoll, procfs and Unix socket syscall mix. Same-vCPU futex wake/wait and Unix socket sendmsg()/recvmsg() ping-pong round trips got 5-8% faster.Signed-off-by Usama Arif <[email protected]>--- arch/x86/include/asm/processor.h | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+)arch/x86/include/asm/processor.h +25
-0@@ -580,6 +580,31 @@ static __always_inline bool on_thread_stack(void) current_stack_pointer) < THREAD_SIZE; } +#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +unsigned long count; + +/* Short spans do not amortize the startup cost of REP STOSQ. */ +if (erase_high <= erase_low +512 ) { +while (erase_low < erase_high) { + *(unsigned long *)erase_low = poison; + erase_low +=sizeof (unsigned long ); + } +return ; + } + + count = (erase_high - erase_low) /sizeof (unsigned long ); + asmvolatile ("rep stosq" + :"+D" (erase_low),"+c" (count) + :"a" (poison) + :"memory" ); +} +#endif +#ifdef CONFIG_PARAVIRT_XXL #include <asm/paravirt.h> #else
Re: [PATCH 2/2] x86/kstack_erase: Use REP STOSQ for large stack fills
In reply to David LaightQuoted 93 lines · David Laight
Quoted 90 lines · On Fri, 20 Nov 2026 18:43:38 +0000 Usama Arif <[email protected]> wrote:
Quoted 65 lines · Peter Zijlstra
Quoted 29 lines · Peter Zijlstra
Quoted 14 lines · Usama Arif
arch/x86/include/asm/processor.h +14
-0+#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +unsigned long count; + +/* Short spans do not amortize the startup cost of REP STOSQ. */ +if (erase_high <= erase_low +512 ) { +while (erase_low < erase_high) { + *(unsigned long *)erase_low = poison; + erase_low +=sizeof (unsigned long ); + }arch/x86/include/asm/processor.h static __always_inline bool on_thread_stack(void) · line 602
Quoted 10 lines
arch/x86/include/asm/processor.h +10
-0+ return; + } + + count = (erase_high - erase_low) /sizeof (unsigned long ); + asmvolatile ("rep stosq" + :"+D" (erase_low),"+c" (count) + :"a" (poison) + :"memory" ); +} +#endif Gemini seems to suggest 16-32 words would be sufficient to amortize the REP STOS setup. It was also adamant I try and unroll that earlier loop.
Quoted 3 lines
How about something like so, does that make sense? Also, I suppose we should make
memset64()__always_inlineif we use it here. I'm not at all sold on the unroll here, the asm is pretty horrid for what it does.This one is much improved:
arch/x86/include/asm/processor.h +16
-0@@ -28,6 +28,7 @@ struct vm86;#include <asm/vmxfeatures.h> #include <asm/vdso/processor.h> #include <asm/shstk.h> +#include <asm/string.h> #include <linux/personality.h> #include <linux/cache.h> @@ -580,6 +581,35 @@ static __always_inline bool on_thread_st current_stack_pointer) < THREAD_SIZE; } +#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +unsigned long count = (erase_high - erase_low) /sizeof (unsigned long ); + +/* Amortize the startup cost of REP STOSQ. */ +if (count <32 ) { +unsigned long *ptr = (unsigned long *)erase_low; + +while (count) { +unsigned long mod = (count-1 ) %4 ; + count -= mod+1 ;arch/x86/include/asm/processor.h static __always_inline bool on_thread_st · line 608
Quoted 10 lines
arch/x86/include/asm/processor.h +10
-0+switch (mod) { +case 3 : ptr[count+3 ] = poison; fallthrough; +case 2 : ptr[count+2 ] = poison; fallthrough; +case 1 : ptr[count+1 ] = poison; fallthrough; +case 0 : ptr[count+0 ] = poison;break ; + } + } +return ; + } +Hello Nick, Peter and David,
Thanks for the reviews! I should have used memset64 from the get go :)
I have tested 2 possible revisions now as well as this one from Peter, have added both of them at the end of the reply.
- v2.1 where you loop upto 512B and then memset
- v2.2: 4 stores per loop up to 512 B, then 64-byte alignedmemset64()I timed
stackleak_erase()in a Zen 5c guest over a futex/epoll/procfs/unix syscall:
Quoted 7 lines
Quoted 5 lines
No patch 68.3 ns per erase
v1 (loop up to 512 B, then REP) 46.6 ns v2.1 (loop up to 512 B, memset64()) 46.6 ns this version 46.4 ns v2.2 (4 stores/iteration, aligned REP) 43.7 nsWhat are the lengths of those erases?
Its a mixture of lengths, coming from getppid(), read(), write(), futex(), unix socket send(), receive(). I asked LLM to come up with a benchmark with a mixture of syscalls that would target a real world usecase and it came up with this which I found to be quite good.
Quoted 1 line
(and where does the 46ns come from??)
It's the whole stackleak_erase(), the search for the poison plus the fill, timed with rdtsc_ordered() in the kernel on every return to user, minus an empty timed region, and averaged over all of the above.
Quoted 25 lines
I'd definitely time 'just the code loop - various loops' and 'just rep stos'.
Quoted 1 line
The switch doesn't seem to help.
To many conditions in the loop.
You could do it this way:switch (count & 3) { case 0: do { *ptr++ = poison; case 3: *ptr++ = poison; case 2: *ptr++ = poison; case 1: *ptr++ = poison; } while ((count -= 4) > 0); }(give or take some off-by-one here and there). But I suspect that using Duff's device is frowned up.
Quoted 2 lines
Either way I kept 512 bytes: REP STOSQ only wins from ~430 bytes on Zen 5c against the plain loop (~850 against the unrolled one),
For zen5 you should only need to unroll the loop once (two writes per iteration). In my experiments it can execute a loop in one clock.
Unless the compiler unrolled it for you (and got it right!) the original loop would be half the speed
Quoted 5 lines
Quoted 1 line
and from ~320 on Cooper Lake.
I'd also try some older Intel cpu.
The setup costs are likely to be higher with FRMS and friends.
It will be difficult for me to get access to CPUs older than Cooper Lake which is 6 years old. I think if we try and profile and fit for every CPU, this patch wont go anywhere. As seen in [1], the differences between the the different optimizations are small, IMHO, we should just go for the most maintainable approach, which I think is you loop upto 512B and then memset.
[1] https://lore.kernel.org/all/[email protected]/
Quoted 157 lines
David
Quoted 154 lines
My personal preference is v2.1, as its much simpler code and the difference in performance between v2.1 and v2.2 isn't actually that much. But if there is a stronger preference for v2.2, I can send that as it is faster.
v2.1:
arch/x86/include/asm/processor.h +21
-0@@ -28,6 +28,7 @@ struct vm86;#include <asm/vmxfeatures.h> #include <asm/vdso/processor.h> #include <asm/shstk.h> +#include <asm/string.h> #include <linux/personality.h> #include <linux/cache.h> @@ -580,6 +581,26 @@ static __always_inline bool on_thread_stack(void) current_stack_pointer) < THREAD_SIZE; } +#if defined(CONFIG_X86_64 ) && !defined(CONFIG_KMSAN ) +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +/* Short spans do not amortize the startup cost of REP STOSQ. */ +if (erase_high <= erase_low +512 ) { +while (erase_low < erase_high) { + *(unsigned long *)erase_low = poison; + erase_low +=sizeof (unsigned long ); + } +return ; + } + +memset64 ((u64 *)erase_low, poison, + (erase_high - erase_low) /sizeof (u64)); +} +#endif +#ifdef CONFIG_PARAVIRT_XXL #include <asm/paravirt.h> #else arch/x86/include/asm/string_64.h +1
-1@@ -54,7 +54,7 @@ static inline void *memset32(uint32_t *s, uint32_t v, size_t n) }#define __HAVE_ARCH_MEMSET64 -static inline void *memset64 (uint64_t *s,uint64_t v,size_t n) +static __always_inline void *memset64(uint64_t *s, uint64_t v, size_t n) { const auto s0 = s; asm volatile (v2.2:
arch/x86/include/asm/processor.h +44
-0@@ -28,7 +28,9 @@ struct vm86;#include <asm/vmxfeatures.h> #include <asm/vdso/processor.h> #include <asm/shstk.h> +#include <asm/string.h> +#include <linux/align.h> #include <linux/personality.h> #include <linux/cache.h> #include <linux/threads.h> @@ -580,6 +582,48 @@ static __always_inline bool on_thread_stack(void) current_stack_pointer) < THREAD_SIZE; } +#if defined(CONFIG_X86_64 ) && !defined(CONFIG_KMSAN ) +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +unsigned long *p = (unsigned long *)erase_low; +unsigned long *end = (unsigned long *)erase_high; +unsigned long i; + +/* Fewer than four words, or nothing to do. */ +if (erase_high < erase_low +4 *sizeof (*p)) { +while (p < end) + *p++ = poison; +return ; + } + +/* Four stores per iteration; the last four may overlap. */ +if (erase_high - erase_low <=512 ) { + end -=4 ; +while (p < end) { + p[0 ] = poison; + p[1 ] = poison; + p[2 ] = poison; + p[3 ] = poison; + p +=4 ; + } + end[0 ] = poison; + end[1 ] = poison; + end[2 ] = poison; + end[3 ] = poison; +return ; + } + +/* REP STOSQ is faster from a 64-byte aligned destination. */ +for (i =0 ; i <8 ; i++) + p[i] = poison; + p = (unsigned long *)ALIGN (erase_low +1 ,64 ); +memset64 ((u64 *)p, poison, end - p); +} +#endif +#ifdef CONFIG_PARAVIRT_XXL #include <asm/paravirt.h> #else arch/x86/include/asm/string_64.h +1
-1@@ -54,7 +54,7 @@ static inline void *memset32(uint32_t *s, uint32_t v, size_t n) }#define __HAVE_ARCH_MEMSET64 -static inline void *memset64 (uint64_t *s,uint64_t v,size_t n) +static __always_inline void *memset64(uint64_t *s, uint64_t v, size_t n) { const auto s0 = s; asm volatile (Quoted 8 lines
arch/x86/include/asm/processor.h +4
-0+ memset64((void *)erase_low, poison, count); +} +#endif +#ifdef CONFIG_PARAVIRT_XXL #include <asm/paravirt.h> #else
Re: [PATCH 2/2] x86/kstack_erase: Use REP STOSQ for large stack fills
In reply to Usama ArifQuoted 23 lines · On Sat, 21 Nov 2026 13:57:39 +0000 Usama Arif <[email protected]> wrote:
Quoted 18 lines · David Laight
Quoted 7 lines · On Thu, 19 Nov 2026 13:31:08 -0800 Usama Arif <[email protected]> wrote:
With
KSTACK_ERASE, every return to user space poisons the part of the task stack that was used since the previous return. The generic__stackleak_poison()does that one word per loop iteration, so a syscall that went 1-2 KiB deep pays for 128-256 separate stores. On Meta hosts running many small VMs,stackleak_erase()accounts for about 1.5% of non-idle host kernel cycles.Quoted 7 lines
Override
__stackleak_poison()on x86-64, as s390 already does, through the hook added by commit491a78663e03("stackleak: allow to specify arch specific stackleak poison function"). Fill spans larger than 512 bytes with REP STOSQ and keep the word loop for shorter ones, where the fixed startup cost of REP STOSQ does not pay off. REP STOSQ starts to win at about 300-400 bytes on Zen 5c and Cooper Lake, so on both no span gets slower.Quoted 3 lines
As a matter of interest (and separately from the exact code) how did you measure the performance to get the 300-400 byte gain point?
Quoted 7 lines
With a userspace benchmark pinned to one CPU. Each sample is one fill of a stack buffer straight after a
getppid()syscall, with lfence;rdtsc;lfence around the fill only, an empty call subtracted, and the mean of 15 times taken. The size stayed fixed for a whole run, so the branches were well predicted. The plain loop and REP STOSQ cost the same at about 430 bytes on Zen 5c and 320 bytes on Cooper Lake.
The lfence (or mfence - which is the one you really need) take long enough that they don't give meaningful timings for anything short. I think they manage to overlap with the setup times for 'rep xxx'. You also get the problem that the tsc doesn't measure clocks and a lot of benchmarks run long enough that the cpu speed changes.
I've updated my benchmark code and run some tests on zen5.
This uses the PERF_COUNT_CPU_CYCLES counter but directly executing rdpmc. I then use data dependencies from the original count to the test code, and from the test result to the second rdpmc (which nicely has a register number) to get a time that includes the test function with little overhead. The clock count for an empty test function is 25, 32 with a memory read.
Each test is run 10 times and the clock count for each shown separately. The first column includes the cost of the I-cache loads and any branches that get mispredicted because (in these cases) the length changes. This is most obvious for the libc calls.
memset() to 4k aligned buffer
0: len 16 ok 445 32 32 32 32 32 32 32 32 32 no_memset 5: len 16 ok 10538 107 52 52 52 52 52 52 52 52 libc 6: len 256 ok 193 101 48 48 51 44 51 44 44 44 libc 7: len 512 ok 120 83 51 51 51 51 51 51 51 51 libc 8: len 1024 ok 111 56 56 55 56 55 56 55 56 56 libc 9: len 2048 ok 117 71 72 72 72 72 72 72 72 72 libc 10: len 16 ok 90 78 74 55 54 55 54 55 54 55 stosb 11: len 256 ok 112 78 78 78 78 78 78 78 78 78 stosb 12: len 512 ok 80 80 80 80 80 80 80 87 80 80 stosb 13: len 1024 ok 90 95 89 95 89 88 89 95 89 95 stosb 14: len 2048 ok 105 111 104 104 104 111 104 111 104 111 stosb 15: len 16 ok 104 88 84 58 58 58 58 58 58 58 stosq 16: len 256 ok 125 80 80 80 80 80 80 80 80 80 stosq 17: len 512 ok 82 83 83 90 82 82 83 83 82 82 stosq 18: len 1024 ok 90 91 91 98 91 98 91 98 91 91 stosq 19: len 2048 ok 106 113 106 113 106 113 106 106 106 113 stosq 20: len 16 ok 133 65 57 33 33 26 26 26 26 26 longs 21: len 256 ok 159 152 80 42 42 42 42 42 42 42 longs 22: len 512 ok 187 115 88 58 56 57 57 57 57 57 longs 23: len 1024 ok 146 211 167 89 88 88 88 88 88 90 longs 24: len 2048 ok 213 213 209 167 153 155 153 153 155 152 longs
memcpy() between 4k aligned buffers
0: len 16 ok 119 63 59 33 33 33 33 33 33 33 no_copy 5: len 16 ok 7333 103 51 51 51 51 51 51 51 51 libc 6: len 256 ok 447 105 51 51 51 51 51 51 51 51 libc 7: len 512 ok 405 56 56 56 56 56 56 56 56 56 libc 8: len 1024 ok 421 96 66 65 64 66 64 70 64 70 libc 9: len 2048 ok 406 139 81 83 81 85 81 83 83 81 libc 10: len 16 ok 91 81 76 56 56 56 56 56 56 56 movsb 11: len 256 ok 115 77 76 77 76 77 76 77 76 77 movsb 12: len 512 ok 80 81 80 81 80 81 81 81 80 81 movsb 13: len 1024 ok 90 89 90 89 90 89 90 89 90 89 movsb 14: len 2048 ok 112 106 105 106 105 106 105 106 105 106 movsb 15: len 16 ok 108 87 85 65 57 65 57 65 57 65 movsq 16: len 256 ok 119 78 78 78 79 78 79 78 79 78 movsq 17: len 512 ok 81 83 82 83 82 82 82 83 82 82 movsq 18: len 1024 ok 91 91 91 91 91 91 91 91 91 91 movsq 19: len 2048 ok 107 107 107 107 107 107 107 107 107 107 movsq 20: len 16 ok 110 62 56 32 32 32 32 32 32 32 longs 21: len 256 ok 203 128 58 57 57 57 57 47 47 47 longs 22: len 512 ok 97 152 190 95 65 63 65 63 65 63 longs 23: len 1024 ok 226 185 155 100 99 98 100 98 99 98 longs 24: len 2048 ok 201 262 260 179 171 166 170 169 171 166 longs
I added enough barrier() and OPTIMIZER_HIDE_VAR() to get the 'longs' loop to be sane - it sets/copies two 64bit locations each iteration. Both tests manage a loop iteration every clock (on zen5).
The cutoff for 'rep stos' is pretty much 1k.
For memcpy() it is a bit lower.
'rep movsq' is slightly slower than 'rep movsb' because of the 'len /= 8'. But it is much slower for counts of 1 (included above) and 0.
I need to boot up one of my other systems to see how older Intel cpu fair.
David
Quoted 83 lines
Quoted 10 lines
If the count is variable - likely in real life, you'll get a branch misprediction penalty (about 20 clocks on zen5) every time you change between the two choices.
The copy loop will have another mispredict penalty for the loop itself.So you are likely to get an overall improvement if you use 'rep stos' for all lengths - even the ones for with it is slightly slower. Unless, that is, you know at compile time that most of the length will be short.
I timed every
stackleak_erase()in a Zen 5c guest running a futex, epoll, procfs and unix socket mix, with the variants switchable at runtime and alternated over 15 rounds:Unpatched 68.3 ns per erase REP STOSQ for all lengths 47.3 ns v1 / v2.1 (loop up to 512 B) 46.6 ns v2.2 (4 stores/iteration) 43.7 nsThe spans aren't random. Unix socket and
/proc/self/statexits were over 1 KiB every time, whilegetppid(),epoll_wait(),read()andwrite()exits were under 128 bytes almost everytime.My preference still is v2.1 because of the simplicity.
Quoted 55 lines
David
Quoted 51 lines
The fill is inline asm, so the noinstr function still makes no calls.
memset64()would be the same instruction, but it is only static inline, and with KMSAN it is an out-of-line function.In a Zen 5c KVM guest,
stackleak_erase()got about 35% cheaper per return to user space (71 ns to 46 ns, scan included) over a futex, epoll, procfs and Unix socket syscall mix. Same-vCPU futex wake/wait and Unix socket sendmsg()/recvmsg() ping-pong round trips got 5-8% faster.Signed-off-by Usama Arif <[email protected]>--- arch/x86/include/asm/processor.h | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+)arch/x86/include/asm/processor.h +25
-0@@ -580,6 +580,31 @@ static __always_inline bool on_thread_stack(void) current_stack_pointer) < THREAD_SIZE; } +#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +unsigned long count; + +/* Short spans do not amortize the startup cost of REP STOSQ. */ +if (erase_high <= erase_low +512 ) { +while (erase_low < erase_high) { + *(unsigned long *)erase_low = poison; + erase_low +=sizeof (unsigned long ); + } +return ; + } + + count = (erase_high - erase_low) /sizeof (unsigned long ); + asmvolatile ("rep stosq" + :"+D" (erase_low),"+c" (count) + :"a" (poison) + :"memory" ); +} +#endif +#ifdef CONFIG_PARAVIRT_XXL #include <asm/paravirt.h> #else
Re: [PATCH 2/2] x86/kstack_erase: Use REP STOSQ for large stack fills
Quoted 34 lines · On Sat, 21 Nov 2026 18:22:08 +0000 David Laight <[email protected]>…
Quoted 23 lines · On Sat, 21 Nov 2026 13:57:39 +0000 Usama Arif <[email protected]> wrote:
Quoted 18 lines · David Laight
Quoted 7 lines · On Thu, 19 Nov 2026 13:31:08 -0800 Usama Arif <[email protected]> wrote:
With
KSTACK_ERASE, every return to user space poisons the part of the task stack that was used since the previous return. The generic__stackleak_poison()does that one word per loop iteration, so a syscall that went 1-2 KiB deep pays for 128-256 separate stores. On Meta hosts running many small VMs,stackleak_erase()accounts for about 1.5% of non-idle host kernel cycles.Quoted 7 lines
Override
__stackleak_poison()on x86-64, as s390 already does, through the hook added by commit491a78663e03("stackleak: allow to specify arch specific stackleak poison function"). Fill spans larger than 512 bytes with REP STOSQ and keep the word loop for shorter ones, where the fixed startup cost of REP STOSQ does not pay off. REP STOSQ starts to win at about 300-400 bytes on Zen 5c and Cooper Lake, so on both no span gets slower.Quoted 3 lines
As a matter of interest (and separately from the exact code) how did you measure the performance to get the 300-400 byte gain point?
Quoted 7 lines
With a userspace benchmark pinned to one CPU. Each sample is one fill of a stack buffer straight after a
getppid()syscall, with lfence;rdtsc;lfence around the fill only, an empty call subtracted, and the mean of 15 times taken. The size stayed fixed for a whole run, so the branches were well predicted. The plain loop and REP STOSQ cost the same at about 430 bytes on Zen 5c and 320 bytes on Cooper Lake.
Quoted 5 lines
The lfence (or mfence - which is the one you really need) take long enough that they don't give meaningful timings for anything short. I think they manage to overlap with the setup times for 'rep xxx'. You also get the problem that the tsc doesn't measure clocks and a lot of benchmarks run long enough that the cpu speed changes.
I redid it your way (user rdpmc on the cycles counter, no fences, data dependencies in and out), and also with lfence and with mfence around the rdpmc. Where REP STOSQ starts to win, in bytes:
plain loop 2 stores per loop
Zen 5c, your method 384 877 Zen 5c, lfence 429 821 Zen 5c, mfence 424 829 Cooper Lake, lfence 277 320 Cooper Lake, mfence 358 358
With fences the loop and REP STOSQ both read a few cycles lower, so the crossovers move by about 50 bytes. The fenced cycle counts match my TSC numbers.
On Cooper Lake your method gives the plain loop the same crossover as the fences, but has the two-store loop filling 512 bytes in 38 cycles on a core that does one store per clock (60 with lfence, 66 with mfence). The second rdpmc only waits for the loop pointer, which is ready while the last stores are still queued.
Quoted 59 lines
I've updated my benchmark code and run some tests on zen5.
This uses thePERF_COUNT_CPU_CYCLEScounter but directly executing rdpmc. I then use data dependencies from the original count to the test code, and from the test result to the second rdpmc (which nicely has a register number) to get a time that includes the test function with little overhead. The clock count for an empty test function is 25, 32 with a memory read.Each test is run 10 times and the clock count for each shown separately. The first column includes the cost of the I-cache loads and any branches that get mispredicted because (in these cases) the length changes. This is most obvious for the libc calls.
memset()to 4k aligned buffer0: len 16 ok 445 32 32 32 32 32 32 32 32 32 no_memset 5: len 16 ok 10538 107 52 52 52 52 52 52 52 52 libc 6: len 256 ok 193 101 48 48 51 44 51 44 44 44 libc 7: len 512 ok 120 83 51 51 51 51 51 51 51 51 libc 8: len 1024 ok 111 56 56 55 56 55 56 55 56 56 libc 9: len 2048 ok 117 71 72 72 72 72 72 72 72 72 libc 10: len 16 ok 90 78 74 55 54 55 54 55 54 55 stosb 11: len 256 ok 112 78 78 78 78 78 78 78 78 78 stosb 12: len 512 ok 80 80 80 80 80 80 80 87 80 80 stosb 13: len 1024 ok 90 95 89 95 89 88 89 95 89 95 stosb 14: len 2048 ok 105 111 104 104 104 111 104 111 104 111 stosb 15: len 16 ok 104 88 84 58 58 58 58 58 58 58 stosq 16: len 256 ok 125 80 80 80 80 80 80 80 80 80 stosq 17: len 512 ok 82 83 83 90 82 82 83 83 82 82 stosq 18: len 1024 ok 90 91 91 98 91 98 91 98 91 91 stosq 19: len 2048 ok 106 113 106 113 106 113 106 106 106 113 stosq 20: len 16 ok 133 65 57 33 33 26 26 26 26 26 longs 21: len 256 ok 159 152 80 42 42 42 42 42 42 42 longs 22: len 512 ok 187 115 88 58 56 57 57 57 57 57 longs 23: len 1024 ok 146 211 167 89 88 88 88 88 88 90 longs 24: len 2048 ok 213 213 209 167 153 155 153 153 155 152 longs
memcpy()between 4k aligned buffers0: len 16 ok 119 63 59 33 33 33 33 33 33 33 no_copy 5: len 16 ok 7333 103 51 51 51 51 51 51 51 51 libc 6: len 256 ok 447 105 51 51 51 51 51 51 51 51 libc 7: len 512 ok 405 56 56 56 56 56 56 56 56 56 libc 8: len 1024 ok 421 96 66 65 64 66 64 70 64 70 libc 9: len 2048 ok 406 139 81 83 81 85 81 83 83 81 libc 10: len 16 ok 91 81 76 56 56 56 56 56 56 56 movsb 11: len 256 ok 115 77 76 77 76 77 76 77 76 77 movsb 12: len 512 ok 80 81 80 81 80 81 81 81 80 81 movsb 13: len 1024 ok 90 89 90 89 90 89 90 89 90 89 movsb 14: len 2048 ok 112 106 105 106 105 106 105 106 105 106 movsb 15: len 16 ok 108 87 85 65 57 65 57 65 57 65 movsq 16: len 256 ok 119 78 78 78 79 78 79 78 79 78 movsq 17: len 512 ok 81 83 82 83 82 82 82 83 82 82 movsq 18: len 1024 ok 91 91 91 91 91 91 91 91 91 91 movsq 19: len 2048 ok 107 107 107 107 107 107 107 107 107 107 movsq 20: len 16 ok 110 62 56 32 32 32 32 32 32 32 longs 21: len 256 ok 203 128 58 57 57 57 57 47 47 47 longs 22: len 512 ok 97 152 190 95 65 63 65 63 65 63 longs 23: len 1024 ok 226 185 155 100 99 98 100 98 99 98 longs 24: len 2048 ok 201 262 260 179 171 166 170 169 171 166 longs
Quoted 5 lines
I added enough
barrier()andOPTIMIZER_HIDE_VAR()to get the 'longs' loop to be sane - it sets/copies two 64bit locations each iteration. Both tests manage a loop iteration every clock (on zen5).The cutoff for 'rep stos' is pretty much 1k.
For a loop with two stores per iteration, yes. But clang emits the v2.1 loop with one store per iteration, which crosses at about 400 bytes on Zen 5c; your numbers give about 450 for a loop doing one store per clock. gcc 15 unrolls it by two, which moves that to about
850. With the fences, Cooper Lake crosses at 280-360 bytes whatever the loop shape, and a 1 KiB cutoff would make 512-1023 byte spans up to 53 cycles slower there. 512 is in between and IMO the best comprimise.
Quoted 7 lines
For
memcpy()it is a bit lower.'rep movsq' is slightly slower than 'rep movsb' because of the 'len /= 8'. But it is much slower for counts of 1 (included above) and 0.
I need to boot up one of my other systems to see how older Intel cpu fair.
The poison is -0xBEEF, so it has to be STOSQ, and memset64() only sees spans over 512 bytes, never a count of 0 or 1.
In the kernel the fill hardly matters any more. Timing stackleak_erase() over the same syscall mix, the fill is 7-8 ns of a 44 ns erase (37 ns with the generic loop), and REP STOSQ for everything, Duff's device, 2x and 4x unrolling and v2.2 all land within 1.2 ns of each other. About 37 ns is the search for the poison.
Over here I am testing on an AMD server less than 2 years old (Zen 5c) and an Intel one that is 6 years old (Cooper Lake). IMO 512 bytes plus memset64() (v2.1) is a good compromise between them.
Quoted 87 lines
David
Quoted 83 lines
Quoted 10 lines
If the count is variable - likely in real life, you'll get a branch misprediction penalty (about 20 clocks on zen5) every time you change between the two choices.
The copy loop will have another mispredict penalty for the loop itself.So you are likely to get an overall improvement if you use 'rep stos' for all lengths - even the ones for with it is slightly slower. Unless, that is, you know at compile time that most of the length will be short.
I timed every
stackleak_erase()in a Zen 5c guest running a futex, epoll, procfs and unix socket mix, with the variants switchable at runtime and alternated over 15 rounds:Unpatched 68.3 ns per erase REP STOSQ for all lengths 47.3 ns v1 / v2.1 (loop up to 512 B) 46.6 ns v2.2 (4 stores/iteration) 43.7 nsThe spans aren't random. Unix socket and
/proc/self/statexits were over 1 KiB every time, whilegetppid(),epoll_wait(),read()andwrite()exits were under 128 bytes almost everytime.My preference still is v2.1 because of the simplicity.
Quoted 55 lines
David
Quoted 51 lines
The fill is inline asm, so the noinstr function still makes no calls.
memset64()would be the same instruction, but it is only static inline, and with KMSAN it is an out-of-line function.In a Zen 5c KVM guest,
stackleak_erase()got about 35% cheaper per return to user space (71 ns to 46 ns, scan included) over a futex, epoll, procfs and Unix socket syscall mix. Same-vCPU futex wake/wait and Unix socket sendmsg()/recvmsg() ping-pong round trips got 5-8% faster.Signed-off-by Usama Arif <[email protected]>--- arch/x86/include/asm/processor.h | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+)arch/x86/include/asm/processor.h +25
-0@@ -580,6 +580,31 @@ static __always_inline bool on_thread_stack(void) current_stack_pointer) < THREAD_SIZE; } +#ifdef CONFIG_X86_64 +#define __stackleak_poison __stackleak_poison +static __always_inline void __stackleak_poison(unsigned long erase_low, +unsigned long erase_high, +unsigned long poison) +{ +unsigned long count; + +/* Short spans do not amortize the startup cost of REP STOSQ. */ +if (erase_high <= erase_low +512 ) { +while (erase_low < erase_high) { + *(unsigned long *)erase_low = poison; + erase_low +=sizeof (unsigned long ); + } +return ; + } + + count = (erase_high - erase_low) /sizeof (unsigned long ); + asmvolatile ("rep stosq" + :"+D" (erase_low),"+c" (count) + :"a" (poison) + :"memory" ); +} +#endif +#ifdef CONFIG_PARAVIRT_XXL #include <asm/paravirt.h> #else