Skip to contentSkip to conversation

Helper-based Atomic Instruction Emulation (AIE)

RFC In review Emilio G. Cota 3 participants 13 messages May 8, 2015 – May 11, 2015 Kbuild

lore
Share & tools
lore
#0 lore raw

cover Helper-based Atomic Instruction Emulation (AIE)

Hi all,

These are patches I've been working on for some time now. Since emulation of atomic instructions is recently getting attention([1], [2]), I'm submitting them for comment.

[1] http://thread.gmane.org/gmane.comp.emulators.qemu/314406
[2] http://thread.gmane.org/gmane.comp.emulators.qemu/334561

Main features of this design:

- Performance and scalability are the main design goal: guest code should scale as much as it would scale running natively on the host.

For this, a host lock is (if necessary) assigned to each 16-byte aligned chunk of the physical address space.
The assignment (i.e. lock allocation + registration) only happens after an atomic operation on a particular physical address is performed. To keep track of this sparse set of locks, a lockless radix tree is used, so lookups are fast and scalable.

- Translation helpers are employed to call the 'aie' module, which is the common code that accesses the radix tree, locking the appropriate entry depending on the access' physical address.

- No special host atomic instructions (e.g. cmpxchg16b) are required; mutexes and include/qemu/atomic.h is all that's needed.

- Usermode and full-system are supported with the same code. Note that the newly-added tiny_set module is necessary to properly emulate LL/SC, since the number of "cpus" (i.e. threads) is unbounded in usermode-- for full-system mode a bitmap would have been sufficient.

- ARM: Stores concurrent with LL/SC primitives are initially not dealt with.
This is my choice, since I'm assuming most sane code will only handle data atomically using LL/SC primitives. However, SWP can be used, so whenevery a SWP instruction is issued, stores start checking that stores do not clash with concurrent SWP instructions. This is implemented via pre/post-store helpers. I've stress-tested this with a heavily contended guest lock (64 cores), and it works fine. Executing non-trivial pre/post-store helpers adds a 5% perf overhead to linux bootup, and is negligible on regular programs. Anyway most sane code doesn't use SWP (linux bootup certainly doesn't.), so this overhead is rarely seen.

- x86: Instead of acquiring the same host lock every time LOCK is found, the acquisition of an AIE lock (via the radix tree) is done when the address of the ensuing load/store is known.
Loads perform this check at compile-time.
Stores are emulated using the same trick as in ARM; non-atomic stores are executed as atomic stores iff there's a prior atomic operation that has been executed on their target address. This for instance ensures that a regular store cannot race with a cmpxchg.
This has very small overhead (negligible with OpenSSL's bntest in user-only), and scales as native code.

- Barriers: not emulated yet. They're needed to correctly run non-trivial lockless code (I'm using concurrencykit's testbenches).
The strongly-ordered-guest-on-weakly-ordered-host problem remains; my guess is that we'll have to sacrifice single-threaded performance to make it work (e.g. using pre-post ld/st helpers).

- 64-bit guest on 32-bit host: Not supported yet. Note that 64-bit loads/stores on a 32-bit guest are not atomic, yet 64-bit code might have been written assuming that they are. Checks for this will be needed.

- Other ISAs: not done yet, but they should be like either ARM or x86.

- License of new files: is there a preferred license for new code?

- Please tolerate the lack of comments in code and commit logs, when preparing this RFC I thought it's better to put all the info here. If this wasn't an RFC I'd have done it differently.

Thanks for reading this far, comments welcome!

Emilio

#1 lore raw

RFC 1/8 cputlb: add physical address to CPUTLBEntry

Having the physical address in the TLB entry will allow us to portably obtain the physical address of a memory access, which will prove useful when implementing a scalable emulation of atomic instructions.

---
 cputlb.c                |  1 +
 include/exec/cpu-defs.h | 11 ++++++-----
 2 files changed, 7 insertions(+), 5 deletions(-)
cputlb.c +1 -0
index 7606548..2cd5912 100644
@@ -330,6 +330,7 @@ void tlb_set_page_with_attrs(CPUState *cpu, target_ulong vaddr,
     } else {
         te->addr_write = -1;
     }
+    te->addr_phys = paddr;
 }
 
 /* Add a new TLB entry, but without specifying the memory
include/exec/cpu-defs.h +6 -5
index 3f56546..67aa0a0 100644
@@ -75,10 +75,10 @@ typedef uint64_t target_ulong;
 /* use a fully associative victim tlb of 8 entries */
 #define CPU_VTLB_SIZE 8
 
-#if HOST_LONG_BITS == 32 && TARGET_LONG_BITS == 32
-#define CPU_TLB_ENTRY_BITS 4
-#else
+#if TARGET_LONG_BITS == 32
 #define CPU_TLB_ENTRY_BITS 5
+#else
+#define CPU_TLB_ENTRY_BITS 6
 #endif
 
 typedef struct CPUTLBEntry {
@@ -91,13 +91,14 @@ typedef struct CPUTLBEntry {
     target_ulong addr_read;
     target_ulong addr_write;
     target_ulong addr_code;
+    target_ulong addr_phys;
     /* Addend to virtual address to get host address.  IO accesses
        use the corresponding iotlb value.  */
     uintptr_t addend;
     /* padding to get a power of two size */
     uint8_t dummy[(1 << CPU_TLB_ENTRY_BITS) -
-                  (sizeof(target_ulong) * 3 +
-                   ((-sizeof(target_ulong) * 3) & (sizeof(uintptr_t) - 1)) +
+                  (sizeof(target_ulong) * 4 +
+                   ((-sizeof(target_ulong) * 4) & (sizeof(uintptr_t) - 1)) +
                    sizeof(uintptr_t))];
 } CPUTLBEntry;
 
Signature · 1 line
1.8.3
#2 lore raw

Re: [Qemu-devel] [RFC 1/8] cputlb: add physical address to CPUTLBEntry

include/exec/cpu-defs.h typedef uint64_t target_ulong; · line 82

Quoted 8 lines · Emilio G. Cota
include/exec/cpu-defs.h +3 -3
-#if HOST_LONG_BITS == 32 && TARGET_LONG_BITS == 32
-#define CPU_TLB_ENTRY_BITS 4
-#else
+#if TARGET_LONG_BITS == 32
 #define CPU_TLB_ENTRY_BITS 5
+#else
+#define CPU_TLB_ENTRY_BITS 6
 #endif

Ouch. 24 of 64 wasted bytes for 64-bit?

I wonder if there's a better way we can encode this to avoid 3 copies of the virtual address for read/write/code. Or if we're better off using more than one insn to multiply by a non-power-of-two. Or if the hardware multiplier is fast enough just multiply by the proper constant.

r~

#3 lore raw

Re: [Qemu-devel] [RFC 1/8] cputlb: add physical address to CPUTLBEntry

Quoted 5 lines · Richard Henderson

Ouch. 24 of 64 wasted bytes for 64-bit?

I wonder if there's a better way we can encode this to avoid 3 copies of the virtual address for read/write/code. Or if we're better off using more than one insn to multiply by a non-power-of-two.

Adding one more instruction works well. Perf tests (# time ./selftest.sh for [1]) show no appreciable difference.

Patch (i386-only) appended.

[1] http://wiki.qemu.org/download/ppc-virtexml507-linux-2_6_34.tgz

Quoted 2 lines

Or if the hardware multiplier is
fast enough just multiply by the proper constant.

This option should be slower (3-cycle latency for IMUL on Ivy Bridge/Haswell, probably slower on others), but would make the code very simple. Unfortunately I couldn't write a patch to do it due to my poor grasp of TCG backend code. If someone provides a patch I'd be glad to test it.

If the appended ends up being the preferred option I can extend it to support all the TCG targets. I cannot however test all of them--only have access to x86 and ppc hardware at the moment.

Thanks,

Emilio

[PATCH] i386-only: remove sizeof(CPUTLBEntry)=pow2 constraint

Breaks all non-i386 TCG backends! Do not apply.

---
 include/exec/cpu-defs.h | 23 +++++++++++++++++------
 tcg/i386/tcg-target.c   | 12 +++++++-----
 2 files changed, 24 insertions(+), 11 deletions(-)
include/exec/cpu-defs.h +17 -6
index 8891f16..716052a 100644
@@ -96,14 +96,25 @@ typedef struct CPUTLBEntry {
     /* Addend to virtual address to get host address.  IO accesses
        use the corresponding iotlb value.  */
     uintptr_t addend;
-    /* padding to get a power of two size */
-    uint8_t dummy[(1 << CPU_TLB_ENTRY_BITS) -
-                  (sizeof(target_ulong) * 4 +
-                   ((-sizeof(target_ulong) * 4) & (sizeof(uintptr_t) - 1)) +
-                   sizeof(uintptr_t))];
 } CPUTLBEntry;
 
-QEMU_BUILD_BUG_ON(sizeof(CPUTLBEntry) != (1 << CPU_TLB_ENTRY_BITS));
+/*
+ * Fast TLB hits are essential for softmmu performance. Since we hand-code in
+ * assembly the TCG check for TLB hits, we define here a pair of constants that
+ * allow us to use only shifts to obtain a TLBEntry address given its index.
+ * NOTE: The constants below should thus be updated every time changes are
+ * made to the CPUTLBEntry struct. See the compile-time consistency check below.
+ */
+#if TARGET_LONG_BITS == 64
+#define CPU_TLB_ENTRY_OUT_SHIFT 3
+#define CPU_TLB_ENTRY_IN_SHIFT  2
+#else
+#define CPU_TLB_ENTRY_OUT_SHIFT (HOST_LONG_BITS == 32 ? 2 : 3)
+#define CPU_TLB_ENTRY_IN_SHIFT  (HOST_LONG_BITS == 32 ? 2 : 1)
+#endif
+
+QEMU_BUILD_BUG_ON(sizeof(CPUTLBEntry) != \
+                (1 + BIT(CPU_TLB_ENTRY_IN_SHIFT)) << CPU_TLB_ENTRY_OUT_SHIFT);
 
 /* The IOTLB is not accessed directly inline by generated TCG code,
  * so the CPUIOTLBEntry layout is not as critical as that of the
tcg/i386/tcg-target.c +7 -5
index ab63823..54250f5 100644
@@ -1195,15 +1195,17 @@ static inline void tcg_out_tlb_load(TCGContext *s, TCGReg addrlo, TCGReg addrhi,
     tcg_out_mov(s, htype, r0, addrlo);
     tcg_out_mov(s, ttype, r1, addrlo);
 
-    tcg_out_shifti(s, SHIFT_SHR + hrexw, r0,
-                   TARGET_PAGE_BITS - CPU_TLB_ENTRY_BITS);
+    tcg_out_shifti(s, SHIFT_SHR + hrexw, r0, TARGET_PAGE_BITS);
 
     tgen_arithi(s, ARITH_AND + trexw, r1,
                 TARGET_PAGE_MASK | ((1 << s_bits) - 1), 0);
-    tgen_arithi(s, ARITH_AND + hrexw, r0,
-                (CPU_TLB_SIZE - 1) << CPU_TLB_ENTRY_BITS, 0);
+    tgen_arithi(s, ARITH_AND + hrexw, r0, CPU_TLB_SIZE - 1, 0);
 
-    tcg_out_modrm_sib_offset(s, OPC_LEA + hrexw, r0, TCG_AREG0, r0, 0,
+    tcg_out_modrm_sib_offset(s, OPC_LEA + hrexw, r0, r0, r0,
+                             CPU_TLB_ENTRY_IN_SHIFT, 0);
+
+    tcg_out_modrm_sib_offset(s, OPC_LEA + hrexw, r0, TCG_AREG0, r0,
+                             CPU_TLB_ENTRY_OUT_SHIFT,
                              offsetof(CPUArchState, tlb_table[mem_index][0])
                              + which);
 
Signature · 1 line
1.8.3
#4 lore raw

RFC 2/8 softmmu: add helpers to get ld/st physical addresses

In reply to Emilio G. Cota

This will be used by the atomic instruction emulation code.

---
 softmmu_template.h | 48 ++++++++++++++++++++++++++++++++++++++++++++++++
 tcg/tcg.h          |  5 +++++
 2 files changed, 53 insertions(+)
softmmu_template.h +48 -0
index 16b0852..cf33d77 100644
@@ -465,6 +465,54 @@ void helper_le_st_name(CPUArchState *env, target_ulong addr, DATA_TYPE val,
 #endif
 }
 
+#if DATA_SIZE == 1
+
+/* get a load's physical address */
+hwaddr helper_ret_get_ld_phys(CPUArchState *env, target_ulong addr,
+                              int mmu_idx, uintptr_t retaddr)
+{
+    int index = (addr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1);
+    CPUTLBEntry *te = &env->tlb_table[mmu_idx][index];
+    target_ulong taddr;
+    target_ulong phys_addr;
+
+    retaddr -= GETPC_ADJ;
+    taddr = te->addr_read & (TARGET_PAGE_MASK | TLB_INVALID_MASK);
+    if (taddr != (addr & TARGET_PAGE_MASK)) {
+        if (!VICTIM_TLB_HIT(addr_read)) {
+            CPUState *cs = ENV_GET_CPU(env);
+
+            tlb_fill(cs, addr, MMU_DATA_LOAD, mmu_idx, retaddr);
+        }
+    }
+    phys_addr = te->addr_phys;
+    return phys_addr | (addr & ~TARGET_PAGE_MASK);
+}
+
+/* get a store's physical address */
+hwaddr helper_ret_get_st_phys(CPUArchState *env, target_ulong addr,
+                              int mmu_idx, uintptr_t retaddr)
+{
+    int index = (addr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1);
+    CPUTLBEntry *te = &env->tlb_table[mmu_idx][index];
+    target_ulong taddr;
+    target_ulong phys_addr;
+
+    retaddr -= GETPC_ADJ;
+    taddr = te->addr_write & (TARGET_PAGE_MASK | TLB_INVALID_MASK);
+    if (taddr != (addr & TARGET_PAGE_MASK)) {
+        if (!VICTIM_TLB_HIT(addr_write)) {
+            CPUState *cs = ENV_GET_CPU(env);
+
+            tlb_fill(cs, addr, MMU_DATA_STORE, mmu_idx, retaddr);
+        }
+    }
+    phys_addr = te->addr_phys;
+    return phys_addr | (addr & ~TARGET_PAGE_MASK);
+}
+
+#endif /* DATA_SIZE == 1 */
+
 #if DATA_SIZE > 1
 void helper_be_st_name(CPUArchState *env, target_ulong addr, DATA_TYPE val,
                        int mmu_idx, uintptr_t retaddr)
tcg/tcg.h +5 -0
index fbb3daf..e84cf45 100644
@@ -930,6 +930,11 @@ void helper_be_stl_mmu(CPUArchState *env, target_ulong addr, uint32_t val,
 void helper_be_stq_mmu(CPUArchState *env, target_ulong addr, uint64_t val,
                        int mmu_idx, uintptr_t retaddr);
 
+hwaddr helper_ret_get_ld_phys(CPUArchState *env, target_ulong addr,
+                              int mmu_idx, uintptr_t retaddr);
+hwaddr helper_ret_get_st_phys(CPUArchState *env, target_ulong addr,
+                              int mmu_idx, uintptr_t retaddr);
+
 /* Temporary aliases until backends are converted.  */
 #ifdef TARGET_WORDS_BIGENDIAN
 # define helper_ret_ldsw_mmu  helper_be_ldsw_mmu
Signature · 1 line
1.8.3
#5 lore raw

RFC 3/8 tiny_set: add module to test for membership in a tiny set of pointers

In reply to Emilio G. Cota

This will be used by the atomic instruction emulation code.

---
 include/qemu/tiny_set.h | 90 +++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 90 insertions(+)
 create mode 100644 include/qemu/tiny_set.h
include/qemu/tiny_set.h new file +90 -0
new file mode 100644
index 0000000..b9aa049
@@ -0,0 +1,90 @@
+/*
+ * tiny_set - simple data structure for fast lookups on tiny sets
+ *
+ * Assumptions:
+ * - Sets are tiny, i.e. of up to a few dozen items
+ * - All operations are serialised by some external lock
+ * - Only non-NULL pointers are supported
+ * - No values stored! This is a set, and thus key-only
+ * - No check for duplicates on insert
+ *
+ * Alternatives:
+ * - bitmap: if the number of items in the set is small and bounded
+ * - hash table: if the set is not tiny
+ *
+ * Complexity:
+ * - O(n) lookup/removal, O(1) insert
+ */
+#ifndef TINY_SET_H
+#define TINY_SET_H
+
+#include <stdbool.h>
+#include <assert.h>
+
+#include <glib.h>
+
+#include "qemu/osdep.h"
+#include "qemu/queue.h"
+
+typedef struct tiny_set TinySet;
+
+struct tiny_set {
+    const void **items;
+    int max_items;
+    int n_items;
+};
+
+static inline void tiny_set_init(TinySet *ts)
+{
+    memset(ts, 0, sizeof(*ts));
+}
+
+static inline void tiny_set_insert(TinySet *ts, const void *key)
+{
+    assert(key);
+
+    if (unlikely(ts->n_items == ts->max_items)) {
+        ts->max_items = ts->max_items ? ts->max_items * 2 : 1;
+        ts->items = g_realloc_n(ts->items, ts->max_items, sizeof(*ts->items));
+    }
+    ts->items[ts->n_items] = key;
+    ts->n_items++;
+}
+
+/* returns true if key was removed, false if it wasn't found */
+static inline bool tiny_set_remove(TinySet *ts, const void *key)
+{
+    bool ret = false;
+    int i;
+
+    assert(key);
+
+    for (i = 0; i < ts->n_items; i++) {
+        if (ts->items[i] == key) {
+            ts->items[i] = NULL;
+            ret = true;
+        }
+    }
+    return ret;
+}
+
+static inline void tiny_set_remove_all(TinySet *ts)
+{
+    ts->n_items = 0;
+}
+
+static inline bool tiny_set_contains(TinySet *ts, const void *key)
+{
+    int i;
+
+    assert(key);
+
+    for (i = 0; i < ts->n_items; i++) {
+        if (ts->items[i] == key) {
+            return true;
+        }
+    }
+    return false;
+}
+
+#endif /* TINY_SET_H */
Signature · 1 line
1.8.3
#6 lore raw

RFC 4/8 radix-tree: add generic lockless radix tree module

In reply to Emilio G. Cota

This will be used by atomic instruction emulation code.

---
 include/qemu/radix-tree.h | 29 ++++++++++++++++++
 util/Makefile.objs        |  2 +-
 util/radix-tree.c         | 77 +++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 107 insertions(+), 1 deletion(-)
 create mode 100644 include/qemu/radix-tree.h
 create mode 100644 util/radix-tree.c
include/qemu/radix-tree.h new file +29 -0
new file mode 100644
index 0000000..a4e1f97
@@ -0,0 +1,29 @@
+#ifndef RADIX_TREE_H
+#define RADIX_TREE_H
+
+#include <stddef.h>
+
+typedef struct QemuRadixNode QemuRadixNode;
+typedef struct QemuRadixTree QemuRadixTree;
+
+struct QemuRadixNode {
+    void *slots[0];
+};
+
+struct QemuRadixTree {
+    QemuRadixNode *root;
+    int radix;
+    int max_height;
+};
+
+void qemu_radix_tree_init(QemuRadixTree *tree, int bits, int radix);
+void *qemu_radix_tree_find_alloc(QemuRadixTree *tree, unsigned long index,
+                                 void *(*create)(unsigned long),
+                                 void (*delete)(void *));
+
+static inline void *qemu_radix_tree_find(QemuRadixTree *t, unsigned long index)
+{
+    return qemu_radix_tree_find_alloc(t, index, NULL, NULL);
+}
+
+#endif /* RADIX_TREE_H */
util/Makefile.objs +1 -1
index ceaba30..253f91e 100644
@@ -1,4 +1,4 @@
-util-obj-y = osdep.o cutils.o unicode.o qemu-timer-common.o
+util-obj-y = osdep.o cutils.o unicode.o qemu-timer-common.o radix-tree.o
 util-obj-$(CONFIG_WIN32) += oslib-win32.o qemu-thread-win32.o event_notifier-win32.o
 util-obj-$(CONFIG_POSIX) += oslib-posix.o qemu-thread-posix.o event_notifier-posix.o qemu-openpty.o
 util-obj-y += envlist.o path.o module.o
util/radix-tree.c new file +77 -0

77 lines not on this page · raw message

Signature · 1 line
1.8.3
#7 lore raw

RFC 5/8 aie: add module for Atomic Instruction Emulation

In reply to Emilio G. Cota
---
 Makefile.target    |  1 +
 aie.c              | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 include/qemu/aie.h | 48 ++++++++++++++++++++++++++++++++++++++++++++++++
 translate-all.c    |  2 ++
 4 files changed, 103 insertions(+)
 create mode 100644 aie.c
 create mode 100644 include/qemu/aie.h
Makefile.target +1 -0
index 1083377..ab2fe6c 100644
@@ -83,6 +83,7 @@ all: $(PROGS) stap
 #########################################################
 # cpu emulator library
 obj-y = exec.o translate-all.o cpu-exec.o
+obj-y += aie.o
 obj-y += tcg/tcg.o tcg/tcg-op.o tcg/optimize.o
 obj-$(CONFIG_TCG_INTERPRETER) += tci.o
 obj-$(CONFIG_TCG_INTERPRETER) += disas/tci.o
aie.c new file +52 -0

52 lines not on this page · raw message

include/qemu/aie.h new file +48 -0

48 lines not on this page · raw message

translate-all.c +2 -0
index 65a76c5..c12f333 100644
@@ -61,6 +61,7 @@
 #include "translate-all.h"
 #include "qemu/bitmap.h"
 #include "qemu/timer.h"
+#include "qemu/aie.h"
 
 //#define DEBUG_TB_INVALIDATE
 //#define DEBUG_FLUSH
@@ -684,6 +685,7 @@ void tcg_exec_init(unsigned long tb_size)
     tcg_ctx.code_gen_ptr = tcg_ctx.code_gen_buffer;
     tcg_register_jit(tcg_ctx.code_gen_buffer, tcg_ctx.code_gen_buffer_size);
     page_init();
+    aie_init();
 #if !defined(CONFIG_USER_ONLY) || !defined(CONFIG_USE_GUEST_BASE)
     /* There's no guest base to take into account, so go ahead and
        initialize the prologue now.  */
Signature · 1 line
1.8.3
#8 lore raw

Re: [Qemu-devel] [RFC 5/8] aie: add module for Atomic Instruction Emulation

Quoted 1 line · Emilio G. Cota

+++ b/aie.c

(snip)

Quoted 6 lines
aie.c new file +6 -0
+static inline void *aie_entry_init(unsigned long index)
+{
+    AIEEntry *entry;
+
+    entry = qemu_memalign(64, sizeof(*entry));
+    tiny_set_init(&entry->ts);

aie.c line 44

Quoted 10 lines
aie.c new file +10 -0
+    qemu_mutex_init(&entry->lock);
+    return entry;
+}
+
+AIEEntry *aie_entry_get_lock(hwaddr addr)
+{
+    aie_addr_t laddr = to_aie(addr);
+    AIEEntry *e;
+
+    e = qemu_radix_tree_find_alloc(&aie_rtree, laddr, aie_entry_init, g_free);

s/g_free/qemu_vfree/, since the allocation is done (above) with qemu_memalign.

The tree doesn't support deletions, but still..

Emilio

#9 lore raw

RFC 6/8 aie: add target helpers

In reply to Emilio G. Cota
---
 aie-helper.c              | 179 ++++++++++++++++++++++++++++++++++++++++++++++
 include/exec/cpu-defs.h   |   5 ++
 include/qemu/aie-helper.h |  21 ++++++
 3 files changed, 205 insertions(+)
 create mode 100644 aie-helper.c
 create mode 100644 include/qemu/aie-helper.h
aie-helper.c new file +179 -0
new file mode 100644
index 0000000..8bc8955
@@ -0,0 +1,179 @@
+/*
+ * To be included directly from the target's helper.c
+ */
+#include "qemu/aie.h"
+
+#ifdef CONFIG_USER_ONLY
+static inline hwaddr h_get_ld_phys(CPUArchState *env, target_ulong vaddr)
+{
+    return vaddr;
+}
+
+static inline hwaddr h_get_st_phys(CPUArchState *env, target_ulong vaddr)
+{
+    return vaddr;
+}
+#else
+/* these need to be macros due to GETRA() */
+#define h_get_ld_phys(env, vaddr)                                       \
+    helper_ret_get_ld_phys(env, vaddr, cpu_mmu_index(env), GETRA())
+#define h_get_st_phys(env, vaddr)                                       \
+    helper_ret_get_st_phys(env, vaddr, cpu_mmu_index(env), GETRA())
+#endif /* CONFIG_USER_ONLY */
+
+static inline void h_aie_lock(CPUArchState *env, hwaddr paddr)
+{
+    AIEEntry *entry = aie_entry_get_lock(paddr);
+
+    env->aie_entry = entry;
+    env->aie_locked = true;
+}
+
+static inline void h_aie_unlock(CPUArchState *env)
+{
+    assert(env->aie_entry && env->aie_locked);
+    qemu_mutex_unlock(&env->aie_entry->lock);
+    env->aie_locked = false;
+}
+
+static inline void h_aie_unlock__done(CPUArchState *env)
+{
+    h_aie_unlock(env);
+    env->aie_entry = NULL;
+}
+
+void HELPER(aie_llsc_st_tracking_enable)(CPUArchState *env)
+{
+    CPUState *other_cs;
+
+    if (likely(atomic_read(&env->aie_llsc_st_tracking))) {
+        return;
+    }
+    CPU_FOREACH(other_cs) {
+        CPUArchState *other_env = other_cs->env_ptr;
+
+        atomic_set(&other_env->aie_llsc_st_tracking, true);
+    }
+}
+
+void HELPER(aie_ld_lock)(CPUArchState *env, target_ulong vaddr)
+{
+    hwaddr paddr;
+
+    assert(!env->aie_locked);
+    paddr = h_get_ld_phys(env, vaddr);
+    h_aie_lock(env, paddr);
+}
+
+void HELPER(aie_st_lock)(CPUArchState *env, target_ulong vaddr)
+{
+    hwaddr paddr;
+
+    assert(!env->aie_locked);
+    paddr = h_get_st_phys(env, vaddr);
+    h_aie_lock(env, paddr);
+}
+
+void HELPER(aie_insert_lock)(CPUArchState *env, target_ulong vaddr)
+{
+    AIEEntry *entry;
+    hwaddr paddr;
+
+    assert(!env->aie_locked);
+    paddr = h_get_ld_phys(env, vaddr);
+    entry = aie_entry_get_lock(paddr);
+
+    tiny_set_insert(&entry->ts, current_cpu);
+    env->aie_entry = entry;
+    env->aie_locked = true;
+}
+
+uint32_t HELPER(aie_contains_lock)(CPUArchState *env)
+{
+    AIEEntry *entry = env->aie_entry;
+
+    /* clrex could arrive between ldrex and strex due to preemption */
+    if (unlikely(entry == NULL)) {
+        return -1;
+    }
+    qemu_mutex_lock(&entry->lock);
+    env->aie_locked = true;
+    if (tiny_set_contains(&entry->ts, current_cpu)) {
+        tiny_set_remove_all(&entry->ts);
+        return 0;
+    }
+    qemu_mutex_unlock(&entry->lock);
+    env->aie_locked = false;
+    env->aie_entry = NULL;
+    return -1;
+}
+
+void HELPER(aie_unlock)(CPUArchState *env)
+{
+    h_aie_unlock(env);
+}
+
+void HELPER(aie_unlock__done)(CPUArchState *env)
+{
+    h_aie_unlock__done(env);
+}
+
+void HELPER(aie_clear)(CPUArchState *env)
+{
+    AIEEntry *entry = env->aie_entry;
+
+    assert(!env->aie_locked);
+    if (!entry) {
+        return;
+    }
+
+    qemu_mutex_lock(&env->aie_entry->lock);
+    tiny_set_remove(&entry->ts, current_cpu);
+    qemu_mutex_unlock(&env->aie_entry->lock);
+    env->aie_entry = NULL;
+}
+
+void HELPER(aie_ld_pre)(CPUArchState *env, target_ulong vaddr)
+{
+    if (likely(!env->aie_lock_enabled) || env->aie_locked) {
+        return;
+    }
+    helper_aie_ld_lock(env, vaddr);
+}
+
+void HELPER(aie_st_pre)(CPUArchState *env, target_ulong vaddr)
+{
+    if (unlikely(env->aie_lock_enabled)) {
+        if (env->aie_locked) {
+            return;
+        }
+        helper_aie_st_lock(env, vaddr);
+    } else {
+        hwaddr paddr = h_get_st_phys(env, vaddr);
+
+        if (unlikely(aie_entry_exists(paddr))) {
+            h_aie_lock(env, paddr);
+        }
+    }
+}
+
+void HELPER(aie_llsc_st_pre)(CPUArchState *env, target_ulong vaddr)
+{
+    hwaddr paddr;
+
+    assert(!env->aie_locked);
+    if (!env->aie_llsc_st_tracking) {
+        return;
+    }
+    paddr = h_get_st_phys(env, vaddr);
+    if (unlikely(aie_entry_exists(paddr))) {
+        h_aie_lock(env, paddr);
+    }
+}
+
+void HELPER(aie_llsc_st_post)(CPUArchState *env)
+{
+    if (unlikely(env->aie_locked)) {
+        h_aie_unlock__done(env);
+    }
+}
include/exec/cpu-defs.h +5 -0
index 67aa0a0..8891f16 100644
@@ -27,6 +27,7 @@
 #include <inttypes.h>
 #include "qemu/osdep.h"
 #include "qemu/queue.h"
+#include "qemu/aie.h"
 #ifndef CONFIG_USER_ONLY
 #include "exec/hwaddr.h"
 #endif
@@ -135,5 +136,9 @@ typedef struct CPUIOTLBEntry {
 #define CPU_COMMON                                                      \
     /* soft mmu support */                                              \
     CPU_COMMON_TLB                                                      \
+    AIEEntry *aie_entry;                                                \
+    bool aie_locked;                                                    \
+    bool aie_lock_enabled;                                              \
+    bool aie_llsc_st_tracking;                                          \
 
 #endif
include/qemu/aie-helper.h new file +21 -0
new file mode 100644
index 0000000..7605e07
@@ -0,0 +1,21 @@
+#ifdef TARGET_ARM
+#define AIE_VADDR_TCG_TYPE glue(i, TARGET_VIRT_ADDR_SPACE_BITS)
+#else
+#define AIE_VADDR_TCG_TYPE tl
+#endif /* TARGET_ARM */
+
+DEF_HELPER_2(aie_ld_pre, void, env, AIE_VADDR_TCG_TYPE)
+DEF_HELPER_2(aie_st_pre, void, env, AIE_VADDR_TCG_TYPE)
+DEF_HELPER_2(aie_llsc_st_pre, void, env, AIE_VADDR_TCG_TYPE)
+DEF_HELPER_1(aie_llsc_st_post, void, env)
+DEF_HELPER_1(aie_llsc_st_tracking_enable, void, env)
+
+DEF_HELPER_2(aie_ld_lock, void, env, AIE_VADDR_TCG_TYPE)
+DEF_HELPER_2(aie_st_lock, void, env, AIE_VADDR_TCG_TYPE)
+DEF_HELPER_2(aie_insert_lock, void, env, AIE_VADDR_TCG_TYPE)
+DEF_HELPER_1(aie_contains_lock, i32, env)
+DEF_HELPER_1(aie_unlock, void, env)
+DEF_HELPER_1(aie_unlock__done, void, env)
+DEF_HELPER_1(aie_clear, void, env)
+
+#undef AIE_VADDR_TCG_TYPE
Signature · 1 line
1.8.3
#10 lore raw

RFC 7/8 target-arm: emulate atomic instructions using AIE

In reply to Emilio G. Cota
---
 linux-user/main.c      |  89 -------------------------
 target-arm/helper.c    |   2 +
 target-arm/helper.h    |   2 +
 target-arm/op_helper.c |   5 ++
 target-arm/translate.c | 172 ++++++++++++++++++++++---------------------------
 5 files changed, 86 insertions(+), 184 deletions(-)
linux-user/main.c +0 -89
index 3f32db0..b6f21b4 100644
@@ -584,90 +584,6 @@ do_kernel_trap(CPUARMState *env)
     return 0;
 }
 
-/* Store exclusive handling for AArch32 */
-static int do_strex(CPUARMState *env)
-{
-    uint64_t val;
-    int size;
-    int rc = 1;
-    int segv = 0;
-    uint32_t addr;
-    start_exclusive();
-    if (env->exclusive_addr != env->exclusive_test) {
-        goto fail;
-    }
-    /* We know we're always AArch32 so the address is in uint32_t range
-     * unless it was the -1 exclusive-monitor-lost value (which won't
-     * match exclusive_test above).
-     */
-    assert(extract64(env->exclusive_addr, 32, 32) == 0);
-    addr = env->exclusive_addr;
-    size = env->exclusive_info & 0xf;
-    switch (size) {
-    case 0:
-        segv = get_user_u8(val, addr);
-        break;
-    case 1:
-        segv = get_user_u16(val, addr);
-        break;
-    case 2:
-    case 3:
-        segv = get_user_u32(val, addr);
-        break;
-    default:
-        abort();
-    }
-    if (segv) {
-        env->exception.vaddress = addr;
-        goto done;
-    }
-    if (size == 3) {
-        uint32_t valhi;
-        segv = get_user_u32(valhi, addr + 4);
-        if (segv) {
-            env->exception.vaddress = addr + 4;
-            goto done;
-        }
-        val = deposit64(val, 32, 32, valhi);
-    }
-    if (val != env->exclusive_val) {
-        goto fail;
-    }
-
-    val = env->regs[(env->exclusive_info >> 8) & 0xf];
-    switch (size) {
-    case 0:
-        segv = put_user_u8(val, addr);
-        break;
-    case 1:
-        segv = put_user_u16(val, addr);
-        break;
-    case 2:
-    case 3:
-        segv = put_user_u32(val, addr);
-        break;
-    }
-    if (segv) {
-        env->exception.vaddress = addr;
-        goto done;
-    }
-    if (size == 3) {
-        val = env->regs[(env->exclusive_info >> 12) & 0xf];
-        segv = put_user_u32(val, addr + 4);
-        if (segv) {
-            env->exception.vaddress = addr + 4;
-            goto done;
-        }
-    }
-    rc = 0;
-fail:
-    env->regs[15] += 4;
-    env->regs[(env->exclusive_info >> 4) & 0xf] = rc;
-done:
-    end_exclusive();
-    return segv;
-}
-
 void cpu_loop(CPUARMState *env)
 {
     CPUState *cs = CPU(arm_env_get_cpu(env));
@@ -833,11 +749,6 @@ void cpu_loop(CPUARMState *env)
         case EXCP_INTERRUPT:
             /* just indicate that signals should be handled asap */
             break;
-        case EXCP_STREX:
-            if (!do_strex(env)) {
-                break;
-            }
-            /* fall through for segv */
         case EXCP_PREFETCH_ABORT:
         case EXCP_DATA_ABORT:
             addr = env->exception.vaddress;
target-arm/helper.c +2 -0
index f8f8d76..742e5be 100644
@@ -11,6 +11,8 @@
 #include "arm_ldst.h"
 #include <zlib.h> /* For crc32 */
 
+#include "aie-helper.c"
+
 #ifndef CONFIG_USER_ONLY
 static inline int get_phys_addr(CPUARMState *env, target_ulong address,
                                 int access_type, ARMMMUIdx mmu_idx,
target-arm/helper.h +2 -0
index dec3728..3c797d1 100644
@@ -529,6 +529,8 @@ DEF_HELPER_2(dc_zva, void, env, i64)
 DEF_HELPER_FLAGS_2(neon_pmull_64_lo, TCG_CALL_NO_RWG_SE, i64, i64, i64)
 DEF_HELPER_FLAGS_2(neon_pmull_64_hi, TCG_CALL_NO_RWG_SE, i64, i64, i64)
 
+#include "qemu/aie-helper.h"
+
 #ifdef TARGET_AARCH64
 #include "helper-a64.h"
 #endif
target-arm/op_helper.c +5 -0
index 3df9c57..ef48180 100644
@@ -29,6 +29,11 @@ static void raise_exception(CPUARMState *env, int tt)
     ARMCPU *cpu = arm_env_get_cpu(env);
     CPUState *cs = CPU(cpu);
 
+    if (unlikely(env->aie_locked)) {
+        assert(env->aie_entry);
+        qemu_mutex_unlock(&env->aie_entry->lock);
+        env->aie_locked = false;
+    }
     cs->exception_index = tt;
     cpu_loop_exit(cs);
 }
target-arm/translate.c +77 -95

298 lines not on this page · raw message

Signature · 1 line
1.8.3
#11 lore raw

RFC 8/8 target-i386: emulate atomic instructions using AIE

In reply to Emilio G. Cota
---
 target-i386/helper.h     |   6 +-
 target-i386/mem_helper.c |  19 +++--
 target-i386/translate.c  | 176 ++++++++++++++++++++++++++++-------------------
 3 files changed, 122 insertions(+), 79 deletions(-)
target-i386/helper.h +4 -2
index 8eb0145..d3335b0 100644
@@ -1,8 +1,8 @@
 DEF_HELPER_FLAGS_4(cc_compute_all, TCG_CALL_NO_RWG_SE, tl, tl, tl, tl, int)
 DEF_HELPER_FLAGS_4(cc_compute_c, TCG_CALL_NO_RWG_SE, tl, tl, tl, tl, int)
 
-DEF_HELPER_0(lock, void)
-DEF_HELPER_0(unlock, void)
+DEF_HELPER_1(lock_enable, void, env)
+DEF_HELPER_1(lock_disable, void, env)
 DEF_HELPER_3(write_eflags, void, env, tl, i32)
 DEF_HELPER_1(read_eflags, tl, env)
 DEF_HELPER_2(divb_AL, void, env, tl)
@@ -217,3 +217,5 @@ DEF_HELPER_3(rcrl, tl, env, tl, tl)
 DEF_HELPER_3(rclq, tl, env, tl, tl)
 DEF_HELPER_3(rcrq, tl, env, tl, tl)
 #endif
+
+#include "qemu/aie-helper.h"
target-i386/mem_helper.c +12 -7
index 1aec8a5..b3d4cf7 100644
@@ -21,18 +21,19 @@
 #include "exec/helper-proto.h"
 #include "exec/cpu_ldst.h"
 
-/* broken thread support */
+#include "aie-helper.c"
 
-static spinlock_t global_cpu_lock = SPIN_LOCK_UNLOCKED;
-
-void helper_lock(void)
+void helper_lock_enable(CPUX86State *env)
 {
-    spin_lock(&global_cpu_lock);
+    env->aie_lock_enabled = true;
 }
 
-void helper_unlock(void)
+void helper_lock_disable(CPUX86State *env)
 {
-    spin_unlock(&global_cpu_lock);
+    if (env->aie_entry) {
+        helper_aie_unlock__done(env);
+    }
+    env->aie_lock_enabled = false;
 }
 
 void helper_cmpxchg8b(CPUX86State *env, target_ulong a0)
@@ -41,6 +42,7 @@ void helper_cmpxchg8b(CPUX86State *env, target_ulong a0)
     int eflags;
 
     eflags = cpu_cc_compute_all(env, CC_OP);
+    helper_aie_ld_lock(env, a0);
     d = cpu_ldq_data(env, a0);
     if (d == (((uint64_t)env->regs[R_EDX] << 32) | (uint32_t)env->regs[R_EAX])) {
         cpu_stq_data(env, a0, ((uint64_t)env->regs[R_ECX] << 32) | (uint32_t)env->regs[R_EBX]);
@@ -52,6 +54,7 @@ void helper_cmpxchg8b(CPUX86State *env, target_ulong a0)
         env->regs[R_EAX] = (uint32_t)d;
         eflags &= ~CC_Z;
     }
+    helper_aie_unlock__done(env);
     CC_SRC = eflags;
 }
 
@@ -65,6 +68,7 @@ void helper_cmpxchg16b(CPUX86State *env, target_ulong a0)
         raise_exception(env, EXCP0D_GPF);
     }
     eflags = cpu_cc_compute_all(env, CC_OP);
+    helper_aie_ld_lock(env, a0);
     d0 = cpu_ldq_data(env, a0);
     d1 = cpu_ldq_data(env, a0 + 8);
     if (d0 == env->regs[R_EAX] && d1 == env->regs[R_EDX]) {
@@ -79,6 +83,7 @@ void helper_cmpxchg16b(CPUX86State *env, target_ulong a0)
         env->regs[R_EAX] = d0;
         eflags &= ~CC_Z;
     }
+    helper_aie_unlock__done(env);
     CC_SRC = eflags;
 }
 #endif
target-i386/translate.c +106 -70

386 lines not on this page · raw message

Signature · 1 line
1.8.3
#12 lore raw
In reply to Emilio G. Cota
Quoted 63 lines · Emilio G. Cota

Hi all,

These are patches I've been working on for some time now. Since emulation of atomic instructions is recently getting attention([1], [2]), I'm submitting them for comment.

[1] http://thread.gmane.org/gmane.comp.emulators.qemu/314406
[2] http://thread.gmane.org/gmane.comp.emulators.qemu/334561

Main features of this design:

- Performance and scalability are the main design goal: guest code should scale as much as it would scale running natively on the host.

For this, a host lock is (if necessary) assigned to each 16-byte aligned chunk of the physical address space.
The assignment (i.e. lock allocation + registration) only happens after an atomic operation on a particular physical address is performed. To keep track of this sparse set of locks, a lockless radix tree is used, so lookups are fast and scalable.

- Translation helpers are employed to call the 'aie' module, which is the common code that accesses the radix tree, locking the appropriate entry depending on the access' physical address.

- No special host atomic instructions (e.g. cmpxchg16b) are required; mutexes and include/qemu/atomic.h is all that's needed.

- Usermode and full-system are supported with the same code. Note that the newly-added tiny_set module is necessary to properly emulate LL/SC, since the number of "cpus" (i.e. threads) is unbounded in usermode-- for full-system mode a bitmap would have been sufficient.

- ARM: Stores concurrent with LL/SC primitives are initially not dealt with.
This is my choice, since I'm assuming most sane code will only handle data atomically using LL/SC primitives. However, SWP can be used, so whenevery a SWP instruction is issued, stores start checking that stores do not clash with concurrent SWP instructions. This is implemented via pre/post-store helpers. I've stress-tested this with a heavily contended guest lock (64 cores), and it works fine. Executing non-trivial pre/post-store helpers adds a 5% perf overhead to linux bootup, and is negligible on regular programs. Anyway most sane code doesn't use SWP (linux bootup certainly doesn't.), so this overhead is rarely seen.

- x86: Instead of acquiring the same host lock every time LOCK is found, the acquisition of an AIE lock (via the radix tree) is done when the address of the ensuing load/store is known.
Loads perform this check at compile-time.
Stores are emulated using the same trick as in ARM; non-atomic stores are executed as atomic stores iff there's a prior atomic operation that has been executed on their target address. This for instance ensures that a regular store cannot race with a cmpxchg.
This has very small overhead (negligible with OpenSSL's bntest in user-only), and scales as native code.

- Barriers: not emulated yet. They're needed to correctly run non-trivial lockless code (I'm using concurrencykit's testbenches). The strongly-ordered-guest-on-weakly-ordered-host problem remains; my guess is that we'll have to sacrifice single-threaded performance to make it work (e.g. using pre-post ld/st helpers).

Quoted 7 lines

- 64-bit guest on 32-bit host: Not supported yet. Note that 64-bit loads/stores on a 32-bit guest are not atomic, yet 64-bit code might have been written assuming that they are. Checks for this will be needed.

- Other ISAs: not done yet, but they should be like either ARM or x86.

- License of new files: is there a preferred license for new code?

I think it's GPL V2 or later.

Fred

Quoted 8 lines

- Please tolerate the lack of comments in code and commit logs, when preparing this RFC I thought it's better to put all the info here. If this wasn't an RFC I'd have done it differently.

Thanks for reading this far, comments welcome!

Emilio