Re: [PATCH v2 -tip] x86/percpu: Use C for arch_raw_cpu_ptr()
From: Uros Bizjak
Date: Wed Oct 18 2023 - 14:08:38 EST
On Wed, Oct 18, 2023 at 6:26 PM Linus Torvalds
<torvalds@xxxxxxxxxxxxxxxxxxxx> wrote:
>
> On Wed, 18 Oct 2023 at 09:03, Nadav Amit <namit@xxxxxxxxxx> wrote:
> >
> > Having said that, I am not sure what other usages you have in mind.
> > “current” is a pretty obvious straight forward case with considerable
> > impact on code generation. There may be additional variables, but it is
> > likely that there would be more functions/TU in which they would not be
> > constant and would require more refined techniques to avoid mistakes
> > such as the use of stale cached values.
>
> Yeah, I don't think there really are other cases.
>
> We do have things that could be considered stable (like
> "smp_processor_id()" which is stable as long as preemption or
> migration is disabled (or it's in an irq-off section).
>
> And it might be lovely to optimize those too, *BUT* that would require
> that there be a barrier against that optimization that works.
But loads from non-const memory work like the above.
Please consider:
--cut here--
extern __seg_gs int m;
int foo (void)
{
int r;
r = m;
r += m;
asm volatile ("" ::: "memory");
r += m;
return r;
}
int bar (void)
{
int r;
r = m;
r += m;
r += m;
return r;
}
--cut here--
gcc -O2:
foo:
movl %gs:m(%rip), %eax
addl %eax, %eax
addl %gs:m(%rip), %eax
ret
bar:
movl %gs:m(%rip), %eax
leal (%rax,%rax,2), %eax
ret
Please note the __barrier(), implemented with asm volatile.
> And if there is anything that this thread has made clear, it's that
> the whole 'load from a constant section' doesn't seem to have any sane
> barriers.
>
> So while the CSE for inline asm statements is a bit too weak with that
> whole "only CSE within a basic block" thing, the CSE of "load a
> constant value from memory" is too *strong*, in that we don't seem to
> have _any_ sane way to say "now you need to reload".
We can use alias to __seg_gs non-const memory, so the value can be
accessed without asm. __barrier() will then force reload. Please note
that any memory clobber, hidden inside asm will also force reload.
> The traditional way we've done that is with our "barrier()" macro,
> which does the whole inline asm with a memory clobber, but even that
> doesn't act as a barrier for gcc optimizing the constant load.
>
> Which means that while we'd probably love for the compiere to optimize
> smp_processor_id() a bit more, we can't use the 'stable memory
> location' trick for it.
We should get rid of asm statements, and as shown above, __barrier()
will do the trick.
> Because I can't think of anything but 'current' that would be _that_
> stable as far as C code is concerned.
Uros.