Received: from eggs.gnu.org ([208.118.235.92]:56713) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1TEK8i-0006x0-FX for qemu-devel@nongnu.org; Wed, 19 Sep 2012 09:16:29 -0400 Received: from Debian-exim by eggs.gnu.org with spam-scanned (Exim 4.71) (envelope-from ) id 1TEK8c-0002qp-LY for qemu-devel@nongnu.org; Wed, 19 Sep 2012 09:16:28 -0400 Received: from mail2.shareable.org ([80.68.89.115]:50506) by eggs.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1TEK8c-0002gr-FK for qemu-devel@nongnu.org; Wed, 19 Sep 2012 09:16:22 -0400 Date: Wed, 19 Sep 2012 14:16:14 +0100 From: Jamie Lokier Message-ID: <20120919131614.GD17137@jl-vm1.vm.bytemark.co.uk> References: <1347349912-15611-1-git-send-email-qemulist@gmail.com> <1347349912-15611-2-git-send-email-qemulist@gmail.com> <504EF077.9080107@redhat.com> <505195CF.8040002@redhat.com> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <505195CF.8040002@redhat.com> Subject: Re: [Qemu-devel] [PATCH V3 01/11] atomic: introduce atomic operations List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , To: Avi Kivity Cc: Jan Kiszka , Marcelo Tosatti , liu ping fan , qemu-devel@nongnu.org, Anthony Liguori , Paolo Bonzini Avi Kivity wrote: > On 09/13/2012 09:54 AM, liu ping fan wrote: > > >>> +typedef struct Atomic { > >>> + int counter; > >>> +} Atomic; > >> > >> Best to mark counter 'volatile'. > >> > >>> + > >>> +static inline void atomic_set(Atomic *v, int i) > >>> +{ > >>> + v->counter = i; > >>> +} > >>> + > >>> +static inline int atomic_read(Atomic *v) > >>> +{ > >>> + return v->counter; > >>> +} > >>> > >> > >> So these two operations don't get mangled by the optimizer. > >> > > Browsing linux code and reading lkml, find some similar material. But > > they have moved volatile from ->counter to function - atomic_read(). > > As to atomic_read(), I think it need to prevent optimizer from > > refetching issue, but as to atomic_set(), do we need ? > > I think so, to prevent reordering. Hi, I don't think volatile makes any difference to reordering here. The compiler is not going to move the atomic_set() store before or after another instruction on the same atomic variable anyway, just like it wouldn't do that for an ordinary assignment. If you're concerned about ordering with respect to other memory, then volatile wouldn't make much difference. barrier() before and after would. If you're copying Linux's semantics, Linux's atomic_set() doesn't include any barriers, nor imply any. atomic_read() uses volatile to ensure that each call re-reads the value, for example in a loop. (Same as ACCESS_ONCE()). If there was a call to atomic_set() in a loop, it doesn't guarantee that will be written each time. -- Jamie