Re: Fix for binfmt_misc / Question about locking [PATCH]

Linus Torvalds (torvalds@transmeta.com)
8 Aug 1997 18:40:24 GMT


In article <Pine.HPP.3.91.970808135729.23970D-100000@hp08.zdv.uni-tuebingen.de>,
Richard Guenther <richard.guenther@student.uni-tuebingen.de> wrote:
>
>Well, I noticed, that my locking approach in binfmt_misc is the wrong
>thing (I used a spinlock to protect a resource, which is useless in
>the uniprocessor case and not nice in the SMP case).
>I now (temporarily?) switched to a semaphore. (Patch for this is
>attached below)

No, the spinlock looks fine, and I actually prefer spinlocks to
semaphores if at all possible.

Spinlocks have these advantages:
- it is a no-op on UP, so it's really fast (infinitely faster than a
semaphore ;)
- it's much faster than a semaphore on SMP too. Especially if there is
any contention at all (unless locks are held so long that blocking
starts to become an issue, but that is generally _way_ too long to
hold a lock anyway unless we're talking IO).
- read-write spinlocks work really well, there is currently no support
for read-write "semaphores" (well, call it a "blocking read-write
lock" instead, it's no longer a semaphore).
- it can be made interrupt-safe (semaphores are interrupt-safe too, but
when using semaphores you can never aquire a lock from within an
interrupt - you can only free a lock. In contrast, you can actually
aquire a spinlock from within an interrupt).

There is only one thing you have to look out for with spinlocks: you
must never lock anything that can block. So you have to do all your
allocations etc _before_ getting the spinlock, and then just lock the
small critical region where you actually do the real work.

But that is generally a good idea anyway, as it minimizes the area that
is locked (so you'd really like to do that with semaphores too if at all
possible).

So this all boils down to the fact that I personally would use
semaphores _only_ when protecting large regions that might do IO.
Anything that you have complete control over generally does not need a
semaphore, because you are better off with a spinlock and some basic
ordering constraints (ie do allocations and user level accesses outside
the lock rather than inside the lock).

>My question now is: Is it ok to do no locking at all, if we can sure,
>that only root could trigger a race condition (which could cause an
>oops, of cause)?? Or do we have to avoid every race condition we know
>of, regardless what cost it has?

You do want to have locking, but with spinlocks you can make the cost of
locking very low indeed (zero, in the case of UP).

Linus