Re: [PATCH 2/2] x86/percpu: Use raw_cpu_try_cmpxchg in preempt_count_set

From: Ingo Molnar
Date: Fri Sep 15 2023 - 07:23:00 EST



* Ingo Molnar <mingo@xxxxxxxxxx> wrote:

>
> * Ingo Molnar <mingo@xxxxxxxxxx> wrote:
>
> >
> > * Uros Bizjak <ubizjak@xxxxxxxxx> wrote:
> >
> > > Use raw_cpu_try_cmpxchg instead of raw_cpu_cmpxchg (*ptr, old, new) == old.
> > > x86 CMPXCHG instruction returns success in ZF flag, so this change saves a
> > > compare after cmpxchg (and related move instruction in front of cmpxchg).
> > >
> > > Also, raw_cpu_try_cmpxchg implicitly assigns old *ptr value to "old" when
> > > cmpxchg fails. There is no need to re-read the value in the loop.
> > >
> > > No functional change intended.
> > >
> > > Cc: Peter Zijlstra <peterz@xxxxxxxxxxxxx>
> > > Cc: Thomas Gleixner <tglx@xxxxxxxxxxxxx>
> > > Cc: Ingo Molnar <mingo@xxxxxxxxxx>
> > > Cc: Borislav Petkov <bp@xxxxxxxxx>
> > > Cc: Dave Hansen <dave.hansen@xxxxxxxxxxxxxxx>
> > > Cc: "H. Peter Anvin" <hpa@xxxxxxxxx>
> > > Signed-off-by: Uros Bizjak <ubizjak@xxxxxxxxx>
> > > ---
> > > arch/x86/include/asm/preempt.h | 4 ++--
> > > 1 file changed, 2 insertions(+), 2 deletions(-)
> > >
> > > diff --git a/arch/x86/include/asm/preempt.h b/arch/x86/include/asm/preempt.h
> > > index 2d13f25b1bd8..4527e1430c6d 100644
> > > --- a/arch/x86/include/asm/preempt.h
> > > +++ b/arch/x86/include/asm/preempt.h
> > > @@ -31,11 +31,11 @@ static __always_inline void preempt_count_set(int pc)
> > > {
> > > int old, new;
> > >
> > > + old = raw_cpu_read_4(pcpu_hot.preempt_count);
> > > do {
> > > - old = raw_cpu_read_4(pcpu_hot.preempt_count);
> > > new = (old & PREEMPT_NEED_RESCHED) |
> > > (pc & ~PREEMPT_NEED_RESCHED);
> > > - } while (raw_cpu_cmpxchg_4(pcpu_hot.preempt_count, old, new) != old);
> > > + } while (!raw_cpu_try_cmpxchg_4(pcpu_hot.preempt_count, &old, new));
> >
> > It would be really nice to have a before/after comparison of generated
> > assembly code in the changelog, to demonstrate the effectiveness of this
> > optimization.
>
> Never mind, you did exactly that in the September 6 variation of these
> changes. I'll apply those.

I mean, this third patch of yours:

[PATCH] x86/percpu: Define {raw,this}_cpu_try_cmpxchg{64,128}

Had a proper disassembly comparison - so I've applied all 3 optimization
patches to tip:x86/asm as:

b8e3dfa16ec5 ("x86/percpu: Use raw_cpu_try_cmpxchg() in preempt_count_set()")
5f863897d964 ("x86/percpu: Define raw_cpu_try_cmpxchg and this_cpu_try_cmpxchg()")
54cd971c6f44 ("x86/percpu: Define {raw,this}_cpu_try_cmpxchg{64,128}")

Thanks,

Ingo