Re: [PATCH -tip 1/3] x86/fsgsbase: Remove unnecessary "memory" clobbers from FS/GS base accessors

From: Uros Bizjak

Date: Tue Mar 10 2026 - 11:31:08 EST


On Tue, Mar 10, 2026 at 3:11 PM David Laight
<david.laight.linux@xxxxxxxxx> wrote:
>
> On Tue, 10 Mar 2026 11:27:42 +0100
> Peter Zijlstra <peterz@xxxxxxxxxxxxx> wrote:
>
> > On Tue, Mar 10, 2026 at 09:21:22AM +0100, Uros Bizjak wrote:
> > > The rdfsbase() and rdgsbase() helpers currently include a "memory" clobber
> > > in their inline assembly definitions. However, the RDFSBASE and RDGSBASE
> > > instructions only read the FS/GS base MSRs into a general-purpose register
> > > and do not access memory. As such, the "memory" clobber is unnecessary.
> >
> > The point isn't that this accesses memory, but that prior or later
> > accesses would end up at different memory locations (as would happen
> > when setting the per-cpu segment.
>
> Don't they need a "memory" clobber to stop them being moved the other
> side of a request to set the relevant register?

Only if the register setting instruction also uses "memory" clobber,
otherwise "asm" can be scheduled around "asm volatile".

> In effect the [fg]sbase register has to be treated like a memory location.

Yes, but only segment register setting instructions should have
"memory" clobber. They do in fact affect memory, when e.g. a follow up
insn uses memory in __seg_gs named address space. Although it is a
"big hammer" approach, "memory" clobber prevents the compiler from
scheduling these instructions before register setting insn (there is
no separate notation of memory in non-generic address spaces).

When reading the register, "asm volatile" prevents the compiler from
scheduling register reading insn before register setting instruction
(so, both should be marked "asm volatile"). There is no memory
involved, so "asm volatile" is the instrument that tells the compiler
what it can do with the insn.

> Given that a memory clobber often makes little (or no) difference to
> the generated code it is probably better to be safe and leave the clobber
> in place.

asm with the "memory" clobber is the biggest hammer approach here. It
blocks scheduling of *all* memory related instructions and should
really be used as the last resort. Merely reading the segment register
doesn't justify its usage.

> If the memory clobber does make a significant difference (unlikely here)
> it can often be mitigated by changing the source code to not rely on CSE.

There is a trade-off when using "asm volatile". It prevents the
compiler from scheduling insn with other "asm volatile" insns, but it
also prevents the compiler from moving insns out of loops or omitting
them on the assumption that the result from a previous call is still
valid. But this can easily be solved in the source code.

Uros.