Re: [PATCH 2/2] x86/kstack_erase: Use REP STOSQ for large stack fills

From: David Laight

Date: Fri Nov 20 2026 - 11:19:01 EST


On Fri, 20 Nov 2026 16:35:39 +0100
Peter Zijlstra <peterz@xxxxxxxxxxxxx> wrote:

> On Fri, Nov 20, 2026 at 02:02:00PM +0000, David Laight wrote:
> > On Fri, 20 Nov 2026 11:45:34 +0100
> > Peter Zijlstra <peterz@xxxxxxxxxxxxx> wrote:
> >
> > > On Thu, Nov 19, 2026 at 01:31:08PM -0800, Usama Arif wrote:
> > > > +#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"
> > > > + : "+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.
> >
> > 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