Date: Wed, 8 Oct 2003 11:51:06 +0200 (CEST) From: Harti Brandt <brandt@fokus.fraunhofer.de> To: Pawel Jakub Dawidek <nick@garage.freebsd.pl> Cc: rwatson@freebsd.org Subject: Re: Dynamic reads without locking. Message-ID: <20031008114506.I63940@beagle.fokus.fraunhofer.de> In-Reply-To: <20031008083059.GA520@garage.freebsd.pl> References: <20031008083059.GA520@garage.freebsd.pl>
next in thread | previous in thread | raw e-mail | index | archive | help
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@fokus.fraunhofer.de, harti@freebsd.org
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20031008114506.I63940>