Dynamic reads without locking.
Harti Brandt
brandt at fokus.fraunhofer.de
Fri Oct 10 00:18:10 PDT 2003
On Thu, 9 Oct 2003, Jeffrey Hsu wrote:
JH> > I'm wondering...
JH> > Jeffrey Hsu was talking about this at BSDCon03.
JH> > There is no need to lock data when we just made simple read, for example:
JH> >
JH> > mtx_lock(&foo_mtx);
JH> > foo = 5;
JH> > mtx_unlock(&foo_mtx);
JH> > but only:
JH> > bar = foo;
JH> >
JH> > IMHO this is quite dangerous.
JH> > Let's see:
JH> >
JH> > thread1 thread2
JH> > mtx_lock(&foo_mtx);
JH> > foo = data_from_user;
JH> > bar = foo;
JH> > foo &= MASK;
JH> > mtx_unlock(&foo_mtx);
JH> >
JH> > In this case we have really dangerous race if data from user are
JH> > safe only when we made 'and' operation on them.
JH> > OR of course we can just store wrong value in 'bar' and this could
JH> > be case of different problems.
JH>
JH>This case (along with some other cases where locks of atomic reads
JH>are required) is covered in the paper as
JH>
JH> But, one case where locks would be required is if the field
JH> temporarily holds a value that no one else is supposed to see and
JH> the writer, operating with the lock held, will store a valid value
JH> before releasing his lock. In this case, both the writer and
JH> reader need to hold the lock before accessing this field.
Yes. When I read the C standard
foo = data & mask;
wouldn't also help, because there is no sequence point in this statement
except at the ;. So the compiler is free to compile this as
foo = data,
foo &= mask;
unless foo is declared as volatile (in this case the write to foo is
supposed to have a side effect so that the compiler cannot write twice to
foo when only one write is specified). So I suppose that a lockless read
is (in MI code) only allowed if the object is 32-bit and is written too
with a simple assigment or is declared volatile.
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