Re: Why Semaphore Hardware-Dependent?

Paul Mackerras
2006-08-28T00:18:44Z

Dong Feng writes:

> Why can't we have a hardware-independent semaphore definition while we
> have already had hardware-dependent spinlock, rwlock, and rcu lock? It
> seems the semaphore definitions classified into two major categories.
> The main deference is whether there is a member variable _sleeper_.
> Does this (optional) member indicate any hardware family gene?

It indicates the presence of instructions that let you implement a
flexible atomic update, that is, either load-locked and
store-conditional instructions, or a compare-and-exchange instruction.

The original x86 implementation had the `count' and `sleepers' fields
in the semaphore structure. For PowerPC, I redesigned the semaphores
to have only the `count' field, which I was able to do because PowerPC
has `load with reservation' and `store conditional' instructions,
which one can use to construct code to do atomic updates where the
resulting value can be just about any function of the initial value.

For semaphores, I made a __sem_update_count function which atomically
updates the count field to (MAX(count, 0) + inc). That implementation
was subsequently picked up by other architectures with equivalent
instructions (alpha, mips, s390, sparc64, etc.). Have a look at
arch/powerpc/kernel/semaphore.c for the details.

I believe the reason for not doing something like this on x86 was the
fact that we still support i386 processors, which don't have the
cmpxchg instruction. That's fair enough, but I would be opposed to
making semaphores bigger and slower on PowerPC because of that. Hence
the two different styles of implementation.

Paul.