Dynamic reads without locking.

Harti Brandt brandt at fokus.fraunhofer.de
Wed Oct 8 02:51:12 PDT 2003


On Wed, 8 Oct 2003, Pawel Jakub Dawidek wrote:

PJD>Hello hackers...
PJD>
PJD>I'm wondering...
PJD>Jeffrey Hsu was talking about this at BSDCon03.
PJD>There is no need to lock data when we just made simple read, for example:
PJD>
PJD>	mtx_lock(&foo_mtx);
PJD>	foo = 5;
PJD>	mtx_unlock(&foo_mtx);
PJD>but only:
PJD>	bar = foo;
PJD>
PJD>IMHO this is quite dangerous.
PJD>Let's see:
PJD>
PJD>	thread1			thread2
PJD>	mtx_lock(&foo_mtx);
PJD>	foo = data_from_user;
PJD>				bar = foo;
PJD>	foo &= MASK;
PJD>	mtx_unlock(&foo_mtx);
PJD>
PJD>In this case we have really dangerous race if data from user are
PJD>safe only when we made 'and' operation on them.
PJD>OR of course we can just store wrong value in 'bar' and this could
PJD>be case of different problems.
PJD>
PJD>So I'm not sure now if I understand everything well. We can't just say
PJD>'We never split such writes. We always do: foo = (data_from_user & MASK)',
PJD>because author of some 3rd party kernel module will be sure that when
PJD>he locks writes to some variable this operation is safe and he could
PJD>split such writes and in kernel could be dynamic read without lock.
PJD>
PJD>Does this make any sense?

You need to lock when reading if you insist on consistent data. Even a
simple read may be non-atomic (this should be the case for 64bit
operations on all our platforms). So you need to do

mtx_lock(&foo_mtx);
bar = foo;
mtx_unlock(&foo_mtx);

if foo is a datatype that is not guaranteed to be red atomically. For
8-bit data you should be safe without the lock on any architecture. I'm
not sure for 16 and 32 bit, but for 64-bit you need the look for all
our architectures, I think.

If you don't care about occasionally reading false data (for statistics or
such stuff) you can go without the lock.

harti
-- 
harti brandt,
http://www.fokus.fraunhofer.de/research/cc/cats/employees/hartmut.brandt/private
brandt at fokus.fraunhofer.de, harti at freebsd.org


More information about the freebsd-hackers mailing list