SMP question w.r.t. reading kernel variables

Attilio Rao attilio at freebsd.org
Sun Apr 17 20:52:10 UTC 2011


2011/4/17 Rick Macklem <rmacklem at uoguelph.ca>:
> Hi,
>
> I should know the answer to this, but... When reading a global kernel
> variable, where its modifications are protected by a mutex, is it
> necessary to get the mutex lock to just read its value?
>
> For example:
> A    if ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0)
>          return (EPERM);
> versus
> B    MNT_ILOCK(mp);
>     if ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0) {
>          MNT_IUNLOCK(mp);
>          return (EPERM);
>     }
>     MNT_IUNLOCK(mp);
>
> My hunch is that B is necessary if you need an up-to-date value
> for the variable (mp->mnt_kern_flag in this case).
>
> Is that correct?
>
> Thanks in advance for help with this, rick

In general, FreeBSD kernel assumes that read and writes of the word
boundry and of the int types are always atomic.

Considering this, if a kernel variable is of int type or word boundry
size you don't strictly need a lock there.
Anyway, locking also bring some side effect, like usage of memory and
compiler barriers... while it is true that bounded read/writes should
be seq points, it is not too obvious to predict if the barrier is
necessary or not, is implied or not in every architecture we support.

Said that, for a matter of consistency and of better semantic, I
prefer to also lock "simple" read/writes when the objects are
explicitly equipped to do that.

Attilio


-- 
Peace can only be achieved by understanding - A. Einstein


More information about the freebsd-hackers mailing list