Re: [PATCH] only irq-safe atomic ops

yodaiken
2002-02-23T11:39:48Z

On Fri, Feb 22, 2002 at 11:54:48PM -0800, Andrew Morton wrote:
> Robert Love wrote:
> > Thinking about it, you are probably going to be doing this:
> >
> > ++counter[smp_processor_id()];
> >
> > and that is not preempt-safe since the whole operation certainly is not
> > atomic. The current CPU could change between calculating it and
> > referencing the array.
>
> yup. It'd probably work - the compiler should calculate the address and
> do a non-buslocked but IRQ-atomic increment on it. But no way can we
> rely on that happening.
>
> > But, that wouldn't matter as long as you only
> > cared about the sum of the counters.
>
> If the compiler produced code equivalent to
>
> counter[smp_processor_id()] = counter[smp_processor_id()] + 1;
>
> then the counter would get trashed - a context switch could cause CPUB
> to write CPUA's counter (+1) onto CPUB's counter. It's quite possibly
> illegal for the compiler to evaluate the array subscript twice in this
> manner. Dunno.
>
> If the compiler produced code equivalent to:
>
> const int cpu = smp_processor_id();
> counter[cpu] = counter[cpu] + 1;
>
> (which is much more likely) then a context switch would result
> in CPUB writing CPUA's updated counter onto CPUA's counter. Which
> will work a lot more often, until CPUA happens to be updating its
> counter at the same time.

So without preemption in the kernel
maybe 4 instructions: calculate cpuid, inc; all local no cache ping
code is easy to read and understand.

with preemption in the kernel
a design problem. a slippery synchronization issue that
involves the characteristic preemption error - code that works
most of the time.

--
---------------------------------------------------------
Victor Yodaiken
Finite State Machine Labs: The RTLinux Company.
www.fsmlabs.com www.rtlinux.com