Skip to contentSkip to conversation

QEMUBH: make AioContext's bh re-entrant

PATCH Superseded Liu Ping Fan 5 participants 15 messages Jun 19, 2013 – Jun 21, 2013 Atomic infrastructure

v3 of 6 Superseded Latest is v6 →

lore
Share & tools
lore
#0 lore raw

v3 cover QEMUBH: make AioContext's bh re-entrant

v2->v3
some small fix for atomic header by Paolo
fine document for bh re-entrant

Liu Ping Fan (1):
QEMUBH: make AioContext's bh re-entrant

Paolo Bonzini (1):
add a header file for atomic operations

 async.c                  |  22 +++
 docs/atomics.txt         | 345 +++++++++++++++++++++++++++++++++++++++++++++++
 hw/display/qxl.c         |   3 +-
 hw/virtio/vhost.c        |   9 +-
 include/block/aio.h      |   5 +
 include/qemu/atomic.h    | 190 +++++++++++++++++++++-----
 migration.c              |   3 +-
 tests/test-thread-pool.c |   8 +-
 8 files changed, 541 insertions(+), 44 deletions(-)
 create mode 100644 docs/atomics.txt
Signature · 1 line
1.8.1.4
#1 lore raw

PATCH v3 1/2 add a header file for atomic operations

From: Paolo Bonzini <[email protected]>

We're already using them in several places, but __sync builtins are just too ugly to type, and do not provide seqcst load/store operations.

Cc Richard Henderson <[email protected]>
Cc Andrew Haley <[email protected]>,
Cc Torvald Riegel <[email protected]>,
Cc Paul E. McKenney <[email protected]>
---
 docs/atomics.txt         | 345 +++++++++++++++++++++++++++++++++++++++++++++++
 hw/display/qxl.c         |   3 +-
 hw/virtio/vhost.c        |   9 +-
 include/qemu/atomic.h    | 190 +++++++++++++++++++++-----
 migration.c              |   3 +-
 tests/test-thread-pool.c |   8 +-
 6 files changed, 514 insertions(+), 44 deletions(-)
 create mode 100644 docs/atomics.txt
docs/atomics.txt new file +345 -0
new file mode 100644
index 0000000..e2ce04b
@@ -0,0 +1,345 @@
+CPUs perform independent memory operations effectively in random order.
+but this can be a problem for CPU-CPU interaction (including interactions
+between QEMU and the guest).  Multi-threaded programs use various tools
+to instruct the compiler and the CPU to restrict the order to something
+that is consistent with the expectations of the programmer.
+
+The most basic tool is locking.  Mutexes, condition variables and
+semaphores are used in QEMU, and should be the default approach to
+synchronization.  Anything else is considerably harder, but it's
+also justified more often than one would like.  The two tools that
+are provided by qemu/atomic.h are memory barriers and atomic operations.
+
+Macros defined by qemu/atomic.h fall in three camps:
+
+- compiler barriers: barrier();
+
+- weak atomic access and manual memory barriers: atomic_read(),
+  atomic_set(), smp_rmb(), smp_wmb(), smp_mb(), smp_read_barrier_depends();
+
+- sequentially consistent atomic access: everything else.
+
+
+COMPILER MEMORY BARRIER
+=======================
+
+barrier() prevents the compiler from moving the memory accesses either
+side of it to the other side.  The compiler barrier has no direct effect
+on the CPU, which may then reorder things however it wishes.
+
+barrier() is mostly used within qemu/atomic.h itself.  On some
+architectures, CPU guarantees are strong enough that blocking compiler
+optimizations already ensures the correct order of execution.  In this
+case, qemu/atomic.h will reduce stronger memory barriers to simple
+compiler barriers.
+
+Still, barrier() can be useful when writing code that can be interrupted
+by signal handlers.
+
+
+SEQUENTIALLY CONSISTENT ATOMIC ACCESS
+=====================================
+
+Most of the operations in the qemu/atomic.h header ensure *sequential
+consistency*, where "the result of any execution is the same as if the
+operations of all the processors were executed in some sequential order,
+and the operations of each individual processor appear in this sequence
+in the order specified by its program".
+
+qemu/atomic.h provides the following set of atomic read-modify-write
+operations:
+
+    typeof(*ptr) atomic_inc(ptr)
+    typeof(*ptr) atomic_dec(ptr)
+    typeof(*ptr) atomic_add(ptr, val)
+    typeof(*ptr) atomic_sub(ptr, val)
+    typeof(*ptr) atomic_and(ptr, val)
+    typeof(*ptr) atomic_or(ptr, val)
+    typeof(*ptr) atomic_xchg(ptr, val
+    typeof(*ptr) atomic_cmpxchg(ptr, old, new)
+
+all of which return the old value of *ptr.  These operations are
+polymorphic; they operate on any type that is as wide as an int.
+
+Sequentially consistent loads and stores can be done using:
+
+    atomic_add(ptr, 0) for loads
+    atomic_xchg(ptr, val) for stores
+
+However, they are quite expensive on some platforms, notably POWER and
+ARM.  Therefore, qemu/atomic.h provides two primitives with slightly
+weaker constraints:
+
+    typeof(*ptr) atomic_mb_read(ptr)
+    void         atomic_mb_set(ptr, val)
+
+The semantics of these primitives map to Java volatile variables,
+and are strongly related to memory barriers as used in the Linux
+kernel (see below).
+
+As long as you use atomic_mb_read and atomic_mb_set, accesses cannot
+be reordered with each other, and it is also not possible to reorder
+"normal" accesses around them.
+
+However, and this is the important difference between
+atomic_mb_read/atomic_mb_set and sequential consistency, it is important
+for both threads to access the same volatile variable.  It is not the
+case that everything visible to thread A when it writes volatile field f
+becomes visible to thread B after it reads volatile field g. The store
+and load have to "match" (i.e., be performed on the same volatile
+field) to achieve the right semantics.
+
+
+These operations operate on any type that is as wide as an int or smaller.
+
+
+WEAK ATOMIC ACCESS AND MANUAL MEMORY BARRIERS
+=============================================
+
+Compared to sequentially consistent atomic access, programming with
+weaker consistency models can be considerably more complicated.
+In general, if the algorithm you are writing includes both writes
+and reads on the same side, it is generally simpler to use sequentially
+consistent primitives.
+
+When using this model, variables are accessed with atomic_read() and
+atomic_set(), and restrictions to the ordering of accesses is enforced
+using the smp_rmb(), smp_wmb(), smp_mb() and smp_read_barrier_depends()
+memory barriers.
+
+atomic_read() and atomic_set() prevents the compiler from using
+optimizations that might otherwise optimize accesses out of existence
+on the one hand, or that might create unsolicited accesses on the other.
+In general this should not have any effect, because the same compiler
+barriers are already implied by memory barriers.  However, it is useful
+to do so, because it tells readers which variables are shared with
+other threads, and which are local to the current thread or protected
+by other, more mundane means.
+
+Memory barriers control the order of references to shared memory.
+They come in four kinds:
+
+- smp_rmb() guarantees that all the LOAD operations specified before
+  the barrier will appear to happen before all the LOAD operations
+  specified after the barrier with respect to the other components of
+  the system.
+
+  In other words, smp_rmb() puts a partial ordering on loads, but is not
+  required to have any effect on stores.
+
+- smp_wmb() guarantees that all the STORE operations specified before
+  the barrier will appear to happen before all the STORE operations
+  specified after the barrier with respect to the other components of
+  the system.
+
+  In other words, smp_wmb() puts a partial ordering on stores, but is not
+  required to have any effect on loads.
+
+- smp_mb() guarantees that all the LOAD and STORE operations specified
+  before the barrier will appear to happen before all the LOAD and
+  STORE operations specified after the barrier with respect to the other
+  components of the system.
+
+  smp_mb() puts a partial ordering on both loads and stores.  It is
+  stronger than both a read and a write memory barrier; it implies both
+  smp_rmb() and smp_wmb(), but it also prevents STOREs coming before the
+  barrier from overtaking LOADs coming after the barrier and vice versa.
+
+- smp_read_barrier_depends() is a weaker kind of read barrier.  On
+  most processors, whenever two loads are performed such that the
+  second depends on the result of the first (e.g., the first load
+  retrieves the address to which the second load will be directed),
+  the processor will guarantee that the first LOAD will appear to happen
+  before the second with respect to the other components of the system.
+  However, this is not always true---for example, it was not true on
+  Alpha processors.  Whenever this kind of access happens to shared
+  memory (that is not protected by a lock), a read barrier is needed,
+  and smp_read_barrier_depends() can be used instead of smp_rmb().
+
+  Note that the first load really has to have a _data_ dependency and not
+  a control dependency.  If the address for the second load is dependent
+  on the first load, but the dependency is through a conditional rather
+  than actually loading the address itself, then it's a _control_
+  dependency and a full read barrier or better is required.
+
+
+This is the set of barriers that is required *between* two atomic_read()
+and atomic_set() operations to achieve sequential consistency:
+
+                    |               2nd operation             |
+                    |-----------------------------------------|
+     1st operation  | (after last) | atomic_read | atomic_set |
+     ---------------+--------------+-------------+------------|
+     (before first) |              | none        | smp_wmb()  |
+     ---------------+--------------+-------------+------------|
+     atomic_read    | smp_rmb()    | smp_rmb()*  | **         |
+     ---------------+--------------+-------------+------------|
+     atomic_set     | none         | smp_mb()*** | smp_wmb()  |
+     ---------------+--------------+-------------+------------|
+
+       * Or smp_read_barrier_depends().
+
+      ** This requires a load-store barrier.  How to achieve this varies
+         depending on the machine, but in practice smp_rmb()+smp_wmb()
+         should have the desired effect.  For example, on PowerPC the
+         lwsync instruction is a combined load-load, load-store and
+         store-store barrier.
+
+     *** This requires a store-load barrier.  On most machines, the only
+         way to achieve this is a full barrier.
+
+
+You can see that the two possible definitions of atomic_mb_read()
+and atomic_mb_set() are the following:
+
+    1) atomic_mb_read(p)   = atomic_read(p); smp_rmb()
+       atomic_mb_set(p, v) = smp_wmb(); atomic_set(p, v); smp_mb()
+
+    2) atomic_mb_read(p)   = smp_mb() atomic_read(p); smp_rmb()
+       atomic_mb_set(p, v) = smp_wmb(); atomic_set(p, v);
+
+Usually the former is used, because smp_mb() is expensive and a program
+normally has more reads than writes.  Therefore it makes more sense to
+make atomic_mb_set() the more expensive operation.
+
+There are two common cases in which atomic_mb_read and atomic_mb_set
+generate too many memory barriers, and thus it can be useful to manually
+place barriers instead:
+
+- when a data structure has one thread that is always a writer
+  and one thread that is always a reader, manual placement of
+  memory barriers makes the write side faster.  Furthermore,
+  correctness is easy to check for in this case using the "pairing"
+  trick that is explained below:
+
+     thread 1                                thread 1
+     -------------------------               ------------------------
+     (other writes)
+                                             smp_wmb()
+     atomic_mb_set(&a, x)                    atomic_set(&a, x)
+                                             smp_wmb()
+     atomic_mb_set(&b, y)                    atomic_set(&b, y)
+
+                                       =>
+     thread 2                                thread 2
+     -------------------------               ------------------------
+     y = atomic_mb_read(&b)                  y = atomic_read(&b)
+                                             smp_rmb()
+     x = atomic_mb_read(&a)                  x = atomic_read(&a)
+                                             smp_rmb()
+
+- sometimes, a thread is accessing many variables that are otherwise
+  unrelated to each other (for example because, apart from the current
+  thread, exactly one other thread will read or write each of these
+  variables).  In this case, it is possible to "hoist" the implicit
+  barriers provided by atomic_mb_read() and atomic_mb_set() outside
+  a loop.  For example, the above definition atomic_mb_read() gives
+  the following transformation:
+
+     n = 0;                                  n = 0;
+     for (i = 0; i < 10; i++)          =>    for (i = 0; i < 10; i++)
+       n += atomic_mb_read(&a[i]);             n += atomic_read(&a[i]);
+                                             smp_rmb();
+
+  Similarly, atomic_mb_set() can be transformed as follows:
+  smp_mb():
+
+                                             smp_wmb();
+     for (i = 0; i < 10; i++)          =>    for (i = 0; i < 10; i++)
+       atomic_mb_set(&a[i], false);            atomic_set(&a[i], false);
+                                             smp_mb();
+
+
+The two tricks can be combined.  In this case, splitting a loop in
+two lets you hoist the barriers out of the loops _and_ eliminate the
+expensive smp_mb():
+
+                                             smp_wmb();
+     for (i = 0; i < 10; i++) {        =>    for (i = 0; i < 10; i++)
+       atomic_mb_set(&a[i], false);            atomic_set(&a[i], false);
+       atomic_mb_set(&b[i], false);          smb_wmb();
+     }                                       for (i = 0; i < 10; i++)
+                                               atomic_set(&a[i], false);
+                                             smp_mb();
+
+  The other thread can still use atomic_mb_read()/atomic_mb_set()
+
+
+Memory barrier pairing
+----------------------
+
+A useful rule of thumb is that memory barriers should always, or almost
+always, be paired with another barrier.  In the case of QEMU, however,
+note that the other barrier may actually be in a driver that runs in
+the guest!
+
+For the purposes of pairing, smp_read_barrier_depends() and smp_rmb()
+both count as read barriers.  A read barriers shall pair with a write
+barrier or a full barrier; a write barrier shall pair with a read
+barrier or a full barrier.  A full barrier can pair with anything.
+For example:
+
+        thread 1             thread 2
+        ===============      ===============
+        a = 1;
+        smp_wmb();
+        b = 2;               x = b;
+                             smp_rmb();
+                             y = a;
+
+Note that the "writing" thread are accessing the variables in the
+opposite order as the "reading" thread.  This is expected: stores
+before the write barrier will normally match the loads after the
+read barrier, and vice versa.  The same is true for more than 2
+access and for data dependency barriers:
+
+        thread 1             thread 2
+        ===============      ===============
+        b[2] = 1;
+        smp_wmb();
+        x->i = 2;
+        smp_wmb();
+        a = x;               x = a;
+                             smp_read_barrier_depends();
+                             y = x->i;
+                             smp_read_barrier_depends();
+                             z = b[y];
+
+smp_wmb() also pairs with atomic_mb_read(), and smp_rmb() also pairs
+with atomic_mb_set().
+
+
+COMPARISON WITH LINUX KERNEL MEMORY BARRIERS
+============================================
+
+Here is a list of differences between Linux kernel atomic operations
+and memory barriers, and the equivalents in QEMU:
+
+- atomic operations in Linux are always on a 32-bit int type and
+  use a boxed atomic_t type; atomic operations in QEMU are polymorphic
+  and use normal C types.
+
+- atomic_read and atomic_set in Linux give no guarantee at all;
+  atomic_read and atomic_set in QEMU include a compiler barrier
+  (similar to the ACCESS_ONCE macro in Linux).
+
+- most atomic read-modify-write operations in Linux return void;
+  in QEMU, all of them return the old value of the variable.
+
+- different atomic read-modify-write operations in Linux imply
+  a different set of memory barriers; in QEMU, all of them enforce
+  sequential consistency, which means they imply full memory barriers
+  before and after the operation.
+
+- Linux does not have an equivalent of atomic_mb_read() and
+  atomic_mb_set().  In particular, note that set_mb() is a little
+  weaker than atomic_mb_set().
+
+
+SOURCES
+=======
+
+* Documentation/memory-barriers.txt from the Linux kernel
+
+* "The JSR-133 Cookbook for Compiler Writers", available at
+  http://g.oswego.edu/dl/jmm/cookbook.html
hw/display/qxl.c +2 -1
index c475cb1..2b10d3d 100644
@@ -23,6 +23,7 @@
 #include "qemu-common.h"
 #include "qemu/timer.h"
 #include "qemu/queue.h"
+#include "qemu/atomic.h"
 #include "monitor/monitor.h"
 #include "sysemu/sysemu.h"
 #include "trace.h"
@@ -1725,7 +1726,7 @@ static void qxl_send_events(PCIQXLDevice *d, uint32_t events)
         trace_qxl_send_events_vm_stopped(d->id, events);
         return;
     }
-    old_pending = __sync_fetch_and_or(&d->ram->int_pending, le_events);
+    old_pending = atomic_or(&d->ram->int_pending, le_events);
     if ((old_pending & le_events) == le_events) {
         return;
     }
hw/virtio/vhost.c +4 -5
index fbabf99..28abe1e 100644
@@ -16,6 +16,7 @@
 #include <sys/ioctl.h>
 #include "hw/virtio/vhost.h"
 #include "hw/hw.h"
+#include "qemu/atomic.h"
 #include "qemu/range.h"
 #include <linux/vhost.h>
 #include "exec/address-spaces.h"
@@ -47,11 +48,9 @@ static void vhost_dev_sync_region(struct vhost_dev *dev,
             addr += VHOST_LOG_CHUNK;
             continue;
         }
-        /* Data must be read atomically. We don't really
-         * need the barrier semantics of __sync
-         * builtins, but it's easier to use them than
-         * roll our own. */
-        log = __sync_fetch_and_and(from, 0);
+        /* Data must be read atomically. We don't really need barrier semantics
+         * but it's easier to use atomic_* than roll our own. */
+        log = atomic_xchg(from, 0);
         while ((bit = sizeof(log) > sizeof(int) ?
                 ffsll(log) : ffs(log))) {
             hwaddr page_addr;
include/qemu/atomic.h +158 -32

226 lines not on this page · raw message

migration.c +1 -2
index bfbc345..a513970 100644
@@ -290,8 +290,7 @@ static void migrate_fd_cleanup(void *opaque)
 
 static void migrate_finish_set_state(MigrationState *s, int new_state)
 {
-    if (__sync_val_compare_and_swap(&s->state, MIG_STATE_ACTIVE,
-                                    new_state) == new_state) {
+    if (atomic_cmpxchg(&s->state, MIG_STATE_ACTIVE, new_state) == new_state) {
         trace_migrate_set_state(new_state);
     }
 }
tests/test-thread-pool.c +4 -4
index 22915aa..dbf2fc8 100644
@@ -17,15 +17,15 @@ typedef struct {
 static int worker_cb(void *opaque)
 {
     WorkerTestData *data = opaque;
-    return __sync_fetch_and_add(&data->n, 1);
+    return atomic_inc(&data->n);
 }
 
 static int long_cb(void *opaque)
 {
     WorkerTestData *data = opaque;
-    __sync_fetch_and_add(&data->n, 1);
+    atomic_inc(&data->n);
     g_usleep(2000000);
-    __sync_fetch_and_add(&data->n, 1);
+    atomic_inc(&data->n);
     return 0;
 }
 
@@ -169,7 +169,7 @@ static void test_cancel(void)
     /* Cancel the jobs that haven't been started yet.  */
     num_canceled = 0;
     for (i = 0; i < 100; i++) {
-        if (__sync_val_compare_and_swap(&data[i].n, 0, 3) == 0) {
+        if (atomic_cmpxchg(&data[i].n, 0, 3) == 0) {
             data[i].ret = -ECANCELED;
             bdrv_aio_cancel(data[i].aiocb);
             active--;
Signature · 1 line
1.8.1.4
Reviewed-by on v3 1/2
#2 lore raw

Re: [Qemu-devel] [PATCH v3 1/2] add a header file for atomic operations

include/qemu/atomic.h line 130

Quoted 7 lines · Liu Ping Fan
include/qemu/atomic.h +5 -0
+#ifndef atomic_read
+#define atomic_read(ptr)       (*(__typeof__(*ptr) *volatile) (ptr))
 #endif
 
+#ifndef atomic_set
+#define atomic_set(ptr, i)     ((*(__typeof__(*ptr) *volatile) (ptr)) = (i))
+#endif

I still think these should be enhanced to reject operations larger than word-size, so that we don't accidentally introduce bugs for our 32-bit hosts. But that can be done as a follow-up.

Otherwise, everything looks consistent now.

r~

#3 lore raw

Re: [Qemu-devel] [PATCH v3 1/2] add a header file for atomic operations

Il 19/06/2013 18:37, Richard Henderson ha scritto:

Quoted 10 lines
Quoted 7 lines

include/qemu/atomic.h line 130

Quoted 7 lines
include/qemu/atomic.h +5 -0
+#ifndef atomic_read
+#define atomic_read(ptr)       (*(__typeof__(*ptr) *volatile) (ptr))
 #endif
 
+#ifndef atomic_set
+#define atomic_set(ptr, i)     ((*(__typeof__(*ptr) *volatile) (ptr)) = (i))
+#endif

I still think these should be enhanced to reject operations larger than word-size, so that we don't accidentally introduce bugs for our 32-bit hosts. But that can be done as a follow-up.

Oops, forgot about that (and also using relaxed instead of volatile).

Will do as a follow-up. Thanks!

Paolo

Quoted 3 lines

Otherwise, everything looks consistent now.

#4 lore raw

Re: [Qemu-devel] [PATCH v3 1/2] add a header file for atomic operations

In reply to Liu Ping Fan
Quoted 14 lines · Liu Ping Fan
hw/virtio/vhost.c +1 -0
index fbabf99..28abe1e 100644
@@ -16,6 +16,7 @@
 #include <sys/ioctl.h>
 #include "hw/virtio/vhost.h"
 #include "hw/hw.h"
+#include "qemu/atomic.h"
 #include "qemu/range.h"
 #include <linux/vhost.h>
 #include "exec/address-spaces.h"
@@ -47,11 +48,9 @@ static void vhost_dev_sync_region(struct vhost_dev *dev,
             addr += VHOST_LOG_CHUNK;

hw/virtio/vhost.c static void vhost_dev_sync_region(struct vhost_dev *dev, · line 53

Quoted 10 lines
hw/virtio/vhost.c +3 -5
             continue;
         }
-        /* Data must be read atomically. We don't really
-         * need the barrier semantics of __sync
-         * builtins, but it's easier to use them than
-         * roll our own. */
-        log = __sync_fetch_and_and(from, 0);
+        /* Data must be read atomically. We don't really need barrier semantics
+         * but it's easier to use atomic_* than roll our own. */
+        log = atomic_xchg(from, 0);

If you really don't need any ordering guarantees / barriers here, then using a relaxed load should be fine. But my gut feeling tells me you probably do need some barriers; either you are "re-using" another barrier (and then the comment should probably point out which), or it must be a case where it's either fine to read any value someone (else) wrote or there's no concurrent store after all.

#5 lore raw

Re: [Qemu-devel] [PATCH v3 1/2] add a header file for atomic operations

Quoted 24 lines · Torvald Riegel
Quoted 23 lines · Liu Ping Fan
hw/virtio/vhost.c +3 -5
index fbabf99..28abe1e 100644
@@ -16,6 +16,7 @@
 #include <sys/ioctl.h>
 #include "hw/virtio/vhost.h"
 #include "hw/hw.h"
+#include "qemu/atomic.h"
 #include "qemu/range.h"
 #include <linux/vhost.h>
 #include "exec/address-spaces.h"
@@ -47,11 +48,9 @@ static void vhost_dev_sync_region(struct vhost_dev *dev,
             addr += VHOST_LOG_CHUNK;
             continue;
         }
-        /* Data must be read atomically. We don't really
-         * need the barrier semantics of __sync
-         * builtins, but it's easier to use them than
-         * roll our own. */
-        log = __sync_fetch_and_and(from, 0);
+        /* Data must be read atomically. We don't really need barrier semantics
+         * but it's easier to use atomic_* than roll our own. */
Quoted 9 lines

hw/virtio/vhost.c static void vhost_dev_sync_region(struct vhost_dev *dev, · line 53

Quoted 1 line
hw/virtio/vhost.c +1 -0
+        log = atomic_xchg(from, 0);

If you really don't need any ordering guarantees / barriers here, then using a relaxed load should be fine. But my gut feeling tells me you probably do need some barriers; either you are "re-using" another barrier (and then the comment should probably point out which), or it must be a case where it's either fine to read any value someone (else) wrote or there's no concurrent store after all.

There is a store here, before and after. Read the value, store zero.

I suppose what the comment is saying is that the atomic operation doesn't need to be ordered with respect to the rest of the surrounding code, as the object being synchronized is just that one integer.

r~

#6 lore raw

Re: [Qemu-devel] [PATCH v3 1/2] add a header file for atomic operations

Il 19/06/2013 22:44, Richard Henderson ha scritto:

Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
Quoted 3 lines

hw/virtio/vhost.c static void vhost_dev_sync_region(struct vhost_dev *dev, · line 53

Quoted 3 lines
hw/virtio/vhost.c +3 -0
+        /* Data must be read atomically. We don't really need barrier semantics
+         * but it's easier to use atomic_* than roll our own. */
+        log = atomic_xchg(from, 0);

If you really don't need any ordering guarantees / barriers here, then using a relaxed load should be fine. But my gut feeling tells me you probably do need some barriers; either you are "re-using" another barrier (and then the comment should probably point out which), or it must be a case where it's either fine to read any value someone (else) wrote or there's no concurrent store after all.

Quoted 5 lines

There is a store here, before and after. Read the value, store zero.

I suppose what the comment is saying is that the atomic operation doesn't need to be ordered with respect to the rest of the surrounding code, as the object being synchronized is just that one integer.

Exactly. The items of the array can be read independently.

Paolo

#7 lore raw

PATCH v3 2/2 QEMUBH: make AioContext's bh re-entrant

In reply to Liu Ping Fan

BH will be used outside big lock, so introduce lock to protect between the writers, ie, bh's adders and deleter. The lock only affects the writers and bh's callback does not take this extra lock. Note that for the same AioContext, aio_bh_poll() can not run in parallel yet.

---
 async.c             | 22 ++++++++++++++++++++++
 include/block/aio.h |  5 +++++
 2 files changed, 27 insertions(+)
async.c +22 -0
index 90fe906..4b17eb7 100644
@@ -47,11 +47,16 @@ QEMUBH *aio_bh_new(AioContext *ctx, QEMUBHFunc *cb, void *opaque)
     bh->ctx = ctx;
     bh->cb = cb;
     bh->opaque = opaque;
+    qemu_mutex_lock(&ctx->bh_lock);
     bh->next = ctx->first_bh;
+    /* Make sure the members ready before putting bh into list */
+    smp_wmb();
     ctx->first_bh = bh;
+    qemu_mutex_unlock(&ctx->bh_lock);
     return bh;
 }
 
+/* Multiple occurrences of aio_bh_poll cannot be called concurrently */
 int aio_bh_poll(AioContext *ctx)
 {
     QEMUBH *bh, **bhp, *next;
@@ -61,12 +66,18 @@ int aio_bh_poll(AioContext *ctx)
 
     ret = 0;
     for (bh = ctx->first_bh; bh; bh = next) {
+        /* Make sure fetching bh before accessing its members */
+        smp_read_barrier_depends();
         next = bh->next;
         if (!bh->deleted && bh->scheduled) {
             bh->scheduled = 0;
             if (!bh->idle)
                 ret = 1;
             bh->idle = 0;
+            /* Paired with write barrier in bh schedule to ensure reading for
+             *  callbacks coming after bh's scheduling.
+             */
+            smp_rmb();
             bh->cb(bh->opaque);
         }
     }
@@ -75,6 +86,7 @@ int aio_bh_poll(AioContext *ctx)
 
     /* remove deleted bhs */
     if (!ctx->walking_bh) {
+        qemu_mutex_lock(&ctx->bh_lock);
         bhp = &ctx->first_bh;
         while (*bhp) {
             bh = *bhp;
@@ -85,6 +97,7 @@ int aio_bh_poll(AioContext *ctx)
                 bhp = &bh->next;
             }
         }
+        qemu_mutex_unlock(&ctx->bh_lock);
     }
 
     return ret;
@@ -94,6 +107,10 @@ void qemu_bh_schedule_idle(QEMUBH *bh)
 {
     if (bh->scheduled)
         return;
+    /* Make sure any writes that are needed by the callback are done
+     * before the locations are read in the aio_bh_poll.
+     */
+    smp_wmb();
     bh->scheduled = 1;
     bh->idle = 1;
 }
@@ -102,6 +119,10 @@ void qemu_bh_schedule(QEMUBH *bh)
 {
     if (bh->scheduled)
         return;
+    /* Make sure any writes that are needed by the callback are done
+     * before the locations are read in the aio_bh_poll.
+     */
+    smp_wmb();
     bh->scheduled = 1;
     bh->idle = 0;
     aio_notify(bh->ctx);
@@ -211,6 +232,7 @@ AioContext *aio_context_new(void)
     ctx = (AioContext *) g_source_new(&aio_source_funcs, sizeof(AioContext));
     ctx->pollfds = g_array_new(FALSE, FALSE, sizeof(GPollFD));
     ctx->thread_pool = NULL;
+    qemu_mutex_init(&ctx->bh_lock);
     event_notifier_init(&ctx->notifier, false);
     aio_set_event_notifier(ctx, &ctx->notifier, 
                            (EventNotifierHandler *)
include/block/aio.h +5 -0
index 1836793..686b10f 100644
@@ -17,6 +17,7 @@
 #include "qemu-common.h"
 #include "qemu/queue.h"
 #include "qemu/event_notifier.h"
+#include "qemu/thread.h"
 
 typedef struct BlockDriverAIOCB BlockDriverAIOCB;
 typedef void BlockDriverCompletionFunc(void *opaque, int ret);
@@ -53,6 +54,8 @@ typedef struct AioContext {
      */
     int walking_handlers;
 
+    /* lock to protect between bh's adders and deleter */
+    QemuMutex bh_lock;
     /* Anchor of the list of Bottom Halves belonging to the context */
     struct QEMUBH *first_bh;
 
@@ -127,6 +130,8 @@ void aio_notify(AioContext *ctx);
  * aio_bh_poll: Poll bottom halves for an AioContext.
  *
  * These are internal functions used by the QEMU main loop.
+ * And notice that multiple occurrences of aio_bh_poll cannot
+ * be called concurrently
  */
 int aio_bh_poll(AioContext *ctx);
 
Signature · 1 line
1.8.1.4
#8 lore raw
Quoted 11 lines · Liu Ping Fan

BH will be used outside big lock, so introduce lock to protect between the writers, ie, bh's adders and deleter. The lock only affects the writers and bh's callback does not take this extra lock. Note that for the same AioContext, aio_bh_poll() can not run in parallel yet.

---
 async.c             | 22 ++++++++++++++++++++++
 include/block/aio.h |  5 +++++
 2 files changed, 27 insertions(+)

qemu_bh_cancel() and qemu_bh_delete() are not modified by this patch.

It seems that calling them from a thread is a little risky because there is no guarantee that the BH is no longer invoked after a thread calls these functions.

I think that's worth a comment or do you want them to take the lock so they become safe?

The other thing I'm unclear on is the ->idle assignment followed immediately by a ->scheduled assignment. Without memory barriers aio_bh_poll() isn't guaranteed to get an ordered view of these updates:
it may see an idle BH as a regular scheduled BH because ->idle is still 0.

Stefan

#9 lore raw

Il 20/06/2013 09:39, Stefan Hajnoczi ha scritto:

Quoted 8 lines

qemu_bh_cancel() and qemu_bh_delete() are not modified by this patch.

It seems that calling them from a thread is a little risky because there is no guarantee that the BH is no longer invoked after a thread calls these functions.

I think that's worth a comment or do you want them to take the lock so they become safe?

Taking the lock wouldn't help. The invoking loop of aio_bh_poll runs lockless. I think a comment is better.

qemu_bh_cancel is inherently not thread-safe, there's not much you can do about it.

qemu_bh_delete is safe as long as you wait for the bottom half to stop before deleting the containing object. Once we have RCU, deletion of QOM objects will be RCU-protected. Hence, a simple way could be to put the first part of aio_bh_poll() within rcu_read_lock/unlock.

Quoted 5 lines

The other thing I'm unclear on is the ->idle assignment followed immediately by a ->scheduled assignment. Without memory barriers aio_bh_poll() isn't guaranteed to get an ordered view of these updates:
it may see an idle BH as a regular scheduled BH because ->idle is still 0.

Right. You need to order ->idle writes before ->scheduled writes, and add memory barriers, or alternatively use two bits in ->scheduled so that you can assign both atomically.

Paolo

#10 lore raw
Quoted 7 lines · Paolo Bonzini

Il 20/06/2013 09:39, Stefan Hajnoczi ha scritto:

Quoted 6 lines

qemu_bh_cancel() and qemu_bh_delete() are not modified by this patch.

It seems that calling them from a thread is a little risky because there is no guarantee that the BH is no longer invoked after a thread calls these functions.

Quoted 6 lines
Quoted 2 lines

I think that's worth a comment or do you want them to take the lock so they become safe?

Taking the lock wouldn't help. The invoking loop of aio_bh_poll runs lockless. I think a comment is better.

Yes, will document it.

Quoted 14 lines

qemu_bh_cancel is inherently not thread-safe, there's not much you can do about it.

qemu_bh_delete is safe as long as you wait for the bottom half to stop before deleting the containing object. Once we have RCU, deletion of QOM objects will be RCU-protected. Hence, a simple way could be to put the first part of aio_bh_poll() within rcu_read_lock/unlock.

Quoted 5 lines

The other thing I'm unclear on is the ->idle assignment followed immediately by a ->scheduled assignment. Without memory barriers aio_bh_poll() isn't guaranteed to get an ordered view of these updates:
it may see an idle BH as a regular scheduled BH because ->idle is still 0.

Quoted 4 lines

Right. You need to order ->idle writes before ->scheduled writes, and add memory barriers, or alternatively use two bits in ->scheduled so that you can assign both atomically.

I think just shift the position of smp_rmb/wmb in _schedule and _poll, we can acheive this (callbacks will not refer to ->idle)

Regards,
Pingfan

Quoted 1 line

Paolo

#11 lore raw

Il 20/06/2013 11:12, liu ping fan ha scritto:

Quoted 6 lines
Quoted 4 lines

Right. You need to order ->idle writes before ->scheduled writes, and add memory barriers, or alternatively use two bits in ->scheduled so that you can assign both atomically.

I think just shift the position of smp_rmb/wmb in _schedule and _poll, we can acheive this (callbacks will not refer to ->idle)

Yes, but you also need to swap ->idle and ->scheduled assignments (aio_bh_poll reads scheduled before idle; qemu_bh_schedule* must write idle before scheduled).

Paolo

#12 lore raw
In reply to Paolo Bonzini
Quoted 13 lines · Paolo Bonzini

Il 20/06/2013 09:39, Stefan Hajnoczi ha scritto:

Quoted 8 lines

qemu_bh_cancel() and qemu_bh_delete() are not modified by this patch.

It seems that calling them from a thread is a little risky because there is no guarantee that the BH is no longer invoked after a thread calls these functions.

I think that's worth a comment or do you want them to take the lock so they become safe?

Taking the lock wouldn't help. The invoking loop of aio_bh_poll runs lockless. I think a comment is better.

Quoted 8 lines

qemu_bh_cancel is inherently not thread-safe, there's not much you can do about it.

qemu_bh_delete is safe as long as you wait for the bottom half to stop before deleting the containing object. Once we have RCU, deletion of QOM objects will be RCU-protected. Hence, a simple way could be to put the first part of aio_bh_poll() within rcu_read_lock/unlock.

In fact, I have some idea about this, introduce another member - Object for QEMUBH which will be refereed in cb, then we leave anything to refcnt mechanism.
For qemu_bh_cancel(), I do not figure out whether it is important or not to sync with caller.

async.c +1 -0
index 4b17eb7..60c35a1 100644
@@ -61,6 +61,7 @@ int aio_bh_poll(AioContext *ctx)
 {
     QEMUBH *bh, **bhp, *next;
     int ret;
+    int sched;
 
 {
     QEMUBH *bh, **bhp, *next;
     int ret;

+ int sched;

     ctx->walking_bh++;

@@ -69,8 +70,10 @@ int aio_bh_poll(AioContext *ctx)

         /* Make sure fetching bh before accessing its members */
         smp_read_barrier_depends();
         next = bh->next;
-        if (!bh->deleted && bh->scheduled) {
-            bh->scheduled = 0;
+        sched = 0;
+        atomic_xchg(&bh->scheduled, sched);
+        if (!bh->deleted && sched) {
+            //bh->scheduled = 0;
             if (!bh->idle)
                 ret = 1;
             bh->idle = 0;
@@ -79,6 +82,9 @@ int aio_bh_poll(AioContext *ctx)
              */
             smp_rmb();
             bh->cb(bh->opaque);
+            if (bh->obj) {
+                object_unref(bh->obj);
+            }
         }
     }

@@ -105,8 +111,12 @@ int aio_bh_poll(AioContext *ctx)

void qemu_bh_schedule_idle(QEMUBH *bh)
{
- if (bh->scheduled)
+ int sched = 1;
+
+ atomic_xchg( &bh->scheduled, sched);

+    if (sched) {
         return;
+    }
     /* Make sure any writes that are needed by the callback are done
      * before the locations are read in the aio_bh_poll.
      */

@@ -117,25 +127,46 @@ void qemu_bh_schedule_idle(QEMUBH *bh)

void qemu_bh_schedule(QEMUBH *bh)
{
- if (bh->scheduled)
+ int sched = 1;
+
+ atomic_xchg( &bh->scheduled, sched);

+    if (sched) {
         return;
+    }
     /* Make sure any writes that are needed by the callback are done
      * before the locations are read in the aio_bh_poll.
      */
     smp_wmb();
     bh->scheduled = 1;
+    if (bh->obj) {
+        object_ref(bh->obj);
+    }
     bh->idle = 0;
     aio_notify(bh->ctx);

}

void qemu_bh_cancel(QEMUBH *bh)
{
- bh->scheduled = 0;
+ int sched = 0;
+
+ atomic_xchg( &bh->scheduled, sched);
+ if (sched) {
+ if (bh->obj) {
+ object_ref(bh->obj);
+ }
+ }
}

void qemu_bh_delete(QEMUBH *bh)
{
- bh->scheduled = 0;
+ int sched = 0;
+
+ atomic_xchg( &bh->scheduled, sched);
+ if (sched) {
+ if (bh->obj) {
+ object_ref(bh->obj);
+ }
+ }

     bh->deleted = 1;

}

Regards,
Pingfan

Quoted 11 lines
Quoted 5 lines

The other thing I'm unclear on is the ->idle assignment followed immediately by a ->scheduled assignment. Without memory barriers aio_bh_poll() isn't guaranteed to get an ordered view of these updates:
it may see an idle BH as a regular scheduled BH because ->idle is still 0.

Right. You need to order ->idle writes before ->scheduled writes, and add memory barriers, or alternatively use two bits in ->scheduled so that you can assign both atomically.

Paolo

#13 lore raw

Il 20/06/2013 11:41, liu ping fan ha scritto:

Quoted 22 lines · Paolo Bonzini
Quoted 13 lines

Il 20/06/2013 09:39, Stefan Hajnoczi ha scritto:

Quoted 8 lines

qemu_bh_cancel() and qemu_bh_delete() are not modified by this patch.

It seems that calling them from a thread is a little risky because there is no guarantee that the BH is no longer invoked after a thread calls these functions.

I think that's worth a comment or do you want them to take the lock so they become safe?

Taking the lock wouldn't help. The invoking loop of aio_bh_poll runs lockless. I think a comment is better.

Quoted 8 lines

qemu_bh_cancel is inherently not thread-safe, there's not much you can do about it.

qemu_bh_delete is safe as long as you wait for the bottom half to stop before deleting the containing object. Once we have RCU, deletion of QOM objects will be RCU-protected. Hence, a simple way could be to put the first part of aio_bh_poll() within rcu_read_lock/unlock.

Quoted 5 lines

In fact, I have some idea about this, introduce another member - Object for QEMUBH which will be refereed in cb, then we leave anything to refcnt mechanism.
For qemu_bh_cancel(), I do not figure out whether it is important or not to sync with caller.

This is a separate patch anyway... and a long discussion to have before too. :)

Let's concentrate on one thing at a time.

Paolo

Quoted 18 lines
async.c +1 -0
index 4b17eb7..60c35a1 100644
@@ -61,6 +61,7 @@ int aio_bh_poll(AioContext *ctx)
 {
     QEMUBH *bh, **bhp, *next;
     int ret;
+    int sched;
 
 {
     QEMUBH *bh, **bhp, *next;
     int ret;
async.c +1 -0
+    int sched;
 
     ctx->walking_bh++;

async.c int aio_bh_poll(AioContext *ctx) · line 74

Quoted 7 lines
async.c +2 -2
@@ -69,8 +70,10 @@ int aio_bh_poll(AioContext *ctx)
         /* Make sure fetching bh before accessing its members */
         smp_read_barrier_depends();
         next = bh->next;
-        if (!bh->deleted && bh->scheduled) {
-            bh->scheduled = 0;
+        sched = 0;
+        atomic_xchg(&bh->scheduled, sched);

This is expensive.

Quoted 92 lines
async.c +34 -4
+        if (!bh->deleted && sched) {
+            //bh->scheduled = 0;
             if (!bh->idle)
                 ret = 1;
             bh->idle = 0;
@@ -79,6 +82,9 @@ int aio_bh_poll(AioContext *ctx)
              */
             smp_rmb();
             bh->cb(bh->opaque);
+            if (bh->obj) {
+                object_unref(bh->obj);
+            }
         }
     }
 
@@ -105,8 +111,12 @@ int aio_bh_poll(AioContext *ctx)
 
 void qemu_bh_schedule_idle(QEMUBH *bh)
 {
-    if (bh->scheduled)
+    int sched = 1;
+
+    atomic_xchg( &bh->scheduled, sched);
+    if (sched) {
         return;
+    }
     /* Make sure any writes that are needed by the callback are done
      * before the locations are read in the aio_bh_poll.
      */
@@ -117,25 +127,46 @@ void qemu_bh_schedule_idle(QEMUBH *bh)
 
 void qemu_bh_schedule(QEMUBH *bh)
 {
-    if (bh->scheduled)
+    int sched = 1;
+
+    atomic_xchg( &bh->scheduled, sched);
+    if (sched) {
         return;
+    }
     /* Make sure any writes that are needed by the callback are done
      * before the locations are read in the aio_bh_poll.
      */
     smp_wmb();
     bh->scheduled = 1;
+    if (bh->obj) {
+        object_ref(bh->obj);
+    }
     bh->idle = 0;
     aio_notify(bh->ctx);
 }
 
 void qemu_bh_cancel(QEMUBH *bh)
 {
-    bh->scheduled = 0;
+    int sched = 0;
+
+    atomic_xchg( &bh->scheduled, sched);
+    if (sched) {
+        if (bh->obj) {
+            object_ref(bh->obj);
+        }
+    }
 }
 
 void qemu_bh_delete(QEMUBH *bh)
 {
-    bh->scheduled = 0;
+    int sched = 0;
+
+    atomic_xchg( &bh->scheduled, sched);
+    if (sched) {
+        if (bh->obj) {
+            object_ref(bh->obj);
+        }
+    }
     bh->deleted = 1;
 }
 

Regards,
Pingfan

Quoted 11 lines
Quoted 5 lines

The other thing I'm unclear on is the ->idle assignment followed immediately by a ->scheduled assignment. Without memory barriers aio_bh_poll() isn't guaranteed to get an ordered view of these updates:
it may see an idle BH as a regular scheduled BH because ->idle is still 0.

Right. You need to order ->idle writes before ->scheduled writes, and add memory barriers, or alternatively use two bits in ->scheduled so that you can assign both atomically.

Paolo

#14 lore raw

[...]

Quoted 12 lines
Quoted 11 lines
Quoted 6 lines

qemu_bh_delete is safe as long as you wait for the bottom half to stop before deleting the containing object. Once we have RCU, deletion of QOM objects will be RCU-protected. Hence, a simple way could be to put the first part of aio_bh_poll() within rcu_read_lock/unlock.

In fact, I have some idea about this, introduce another member - Object for QEMUBH which will be refereed in cb, then we leave anything to refcnt mechanism.
For qemu_bh_cancel(), I do not figure out whether it is important or not to sync with caller.

Quoted 5 lines

This is a separate patch anyway... and a long discussion to have before too. :)

Let's concentrate on one thing at a time.

Yes, will do like this.

Regards,
Pingfan

Quoted 123 lines

Paolo

Quoted 18 lines
async.c +1 -0
index 4b17eb7..60c35a1 100644
@@ -61,6 +61,7 @@ int aio_bh_poll(AioContext *ctx)
 {
     QEMUBH *bh, **bhp, *next;
     int ret;
+    int sched;
 
 {
     QEMUBH *bh, **bhp, *next;
     int ret;
async.c +1 -0
+    int sched;
 
     ctx->walking_bh++;

async.c int aio_bh_poll(AioContext *ctx) · line 74

Quoted 7 lines
async.c +2 -2
@@ -69,8 +70,10 @@ int aio_bh_poll(AioContext *ctx)
         /* Make sure fetching bh before accessing its members */
         smp_read_barrier_depends();
         next = bh->next;
-        if (!bh->deleted && bh->scheduled) {
-            bh->scheduled = 0;
+        sched = 0;
+        atomic_xchg(&bh->scheduled, sched);

This is expensive.

Quoted 92 lines
async.c +34 -4
+        if (!bh->deleted && sched) {
+            //bh->scheduled = 0;
             if (!bh->idle)
                 ret = 1;
             bh->idle = 0;
@@ -79,6 +82,9 @@ int aio_bh_poll(AioContext *ctx)
              */
             smp_rmb();
             bh->cb(bh->opaque);
+            if (bh->obj) {
+                object_unref(bh->obj);
+            }
         }
     }
 
@@ -105,8 +111,12 @@ int aio_bh_poll(AioContext *ctx)
 
 void qemu_bh_schedule_idle(QEMUBH *bh)
 {
-    if (bh->scheduled)
+    int sched = 1;
+
+    atomic_xchg( &bh->scheduled, sched);
+    if (sched) {
         return;
+    }
     /* Make sure any writes that are needed by the callback are done
      * before the locations are read in the aio_bh_poll.
      */
@@ -117,25 +127,46 @@ void qemu_bh_schedule_idle(QEMUBH *bh)
 
 void qemu_bh_schedule(QEMUBH *bh)
 {
-    if (bh->scheduled)
+    int sched = 1;
+
+    atomic_xchg( &bh->scheduled, sched);
+    if (sched) {
         return;
+    }
     /* Make sure any writes that are needed by the callback are done
      * before the locations are read in the aio_bh_poll.
      */
     smp_wmb();
     bh->scheduled = 1;
+    if (bh->obj) {
+        object_ref(bh->obj);
+    }
     bh->idle = 0;
     aio_notify(bh->ctx);
 }
 
 void qemu_bh_cancel(QEMUBH *bh)
 {
-    bh->scheduled = 0;
+    int sched = 0;
+
+    atomic_xchg( &bh->scheduled, sched);
+    if (sched) {
+        if (bh->obj) {
+            object_ref(bh->obj);
+        }
+    }
 }
 
 void qemu_bh_delete(QEMUBH *bh)
 {
-    bh->scheduled = 0;
+    int sched = 0;
+
+    atomic_xchg( &bh->scheduled, sched);
+    if (sched) {
+        if (bh->obj) {
+            object_ref(bh->obj);
+        }
+    }
     bh->deleted = 1;
 }
 

Regards,
Pingfan

Quoted 11 lines
Quoted 5 lines

The other thing I'm unclear on is the ->idle assignment followed immediately by a ->scheduled assignment. Without memory barriers aio_bh_poll() isn't guaranteed to get an ordered view of these updates:
it may see an idle BH as a regular scheduled BH because ->idle is still 0.

Right. You need to order ->idle writes before ->scheduled writes, and add memory barriers, or alternatively use two bits in ->scheduled so that you can assign both atomically.

Paolo