From owner-freebsd-hackers@FreeBSD.ORG Thu Sep 24 23:46:14 2009 Return-Path: Delivered-To: hackers@freebsd.org Received: from mx1.freebsd.org (mx1.freebsd.org [IPv6:2001:4f8:fff6::34]) by hub.freebsd.org (Postfix) with ESMTP id 2AE90106568D; Thu, 24 Sep 2009 23:46:14 +0000 (UTC) (envelope-from fabio@freebsd.org) Received: from sssup.it (ms01.sssup.it [193.205.80.99]) by mx1.freebsd.org (Postfix) with ESMTP id 43A4F8FC14; Thu, 24 Sep 2009 23:46:13 +0000 (UTC) Received: from [193.205.82.7] (HELO gandalf.sssup.it) by sssup.it (CommuniGate Pro SMTP 4.1.8) with ESMTP-TLS id 53895175; Fri, 25 Sep 2009 00:30:29 +0200 Received: from smaug.retis (smaug.retis [10.30.3.72]) by gandalf.sssup.it (8.12.10/8.12.10) with ESMTP id n8OMkCU0031573; Fri, 25 Sep 2009 00:46:12 +0200 Received: by smaug.retis (Postfix, from userid 1000) id A3659538C2; Fri, 25 Sep 2009 00:49:35 +0200 (CEST) Date: Fri, 25 Sep 2009 00:49:35 +0200 From: Fabio Checconi To: hackers@freebsd.org Message-ID: <20090924224935.GW473@gandalf.sssup.it> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline User-Agent: Mutt/1.4.2.3i Cc: attilio@freebsd.org Subject: sx locks and memory barriers X-BeenThere: freebsd-hackers@freebsd.org X-Mailman-Version: 2.1.5 Precedence: list List-Id: Technical Discussions relating to FreeBSD List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Thu, 24 Sep 2009 23:46:14 -0000 Hi all, looking at sys/sx.h I have some troubles understanding this comment: * A note about memory barriers. Exclusive locks need to use the same * memory barriers as mutexes: _acq when acquiring an exclusive lock * and _rel when releasing an exclusive lock. On the other side, * shared lock needs to use an _acq barrier when acquiring the lock * but, since they don't update any locked data, no memory barrier is * needed when releasing a shared lock. In particular, I'm not understanding what prevents the following sequence from happening: CPU A CPU B sx_slock(&data->lock); sx_sunlock(&data->lock); /* reordered after the unlock by the cpu */ if (data->buffer) sx_xlock(&data->lock); free(data->buffer); data->buffer = NULL; sx_xunlock(&data->lock); a = *data->buffer; IOW, even if readers do not modify the data protected by the lock, without a release barrier a memory access may leak past the unlock (as the cpu won't notice any dependency between the unlock and the fetch, feeling free to reorder them), thus potentially racing with an exclusive writer accessing the data. On architectures where atomic ops serialize memory accesses this would never happen, otherwise the sequence above seems possible; am I missing something?