Skip to contentSkip to conversation

tb hash improvements

GIT PULL Applied Richard Henderson 6 participants 31 messages Jun 10, 2016 – Aug 11, 2016

lore
Share & tools
lore
#0 lore raw

We're all good to go with v7.

r~

The following changes since commit 0c33682d5f29b0a4ae53bdec4c8e52e4fae37b34:

target-i386: Move user-mode exception actions out of user-exec.c (2016-06-09 15:55:02 +0100)

are available in the git repository at:

git://github.com/rth7680/qemu.git tags/pull-tcg-20160610

for you to fetch changes up to 9b1b8e78a5a8c849f5ca800d71497dc88a338483:

translate-all: add tb hash bucket info to 'info jit' dump (2016-06-10 07:21:54 -0700)

----------------------------------------------------------------
TB hashing improvements

----------------------------------------------------------------
Emilio G. Cota (14):
compiler.h: add QEMU_ALIGNED() to enforce struct alignment
seqlock: remove optional mutex
seqlock: rename write_lock/unlock to write_begin/end include/processor.h: define cpu_relax()
exec: add tb_hash_func5, derived from xxhash
tb hash: hash phys_pc, pc, and flags with xxhash
qdist: add module to represent frequency distributions of data
qdist: add test program
qht: QEMU's fast, resizable and scalable Hash Table
qht: add test program
qht: add qht-bench, a performance benchmark
qht: add test-qht-par to invoke qht-bench from 'check' target tb hash: track translated blocks with qht
translate-all: add tb hash bucket info to 'info jit' dump

Guillaume Delbergue (1):
qemu-thread: add simple test-and-set spinlock

 cpu-exec.c                |  92 ++---
 cpus.c                    |  30 +-
 include/exec/exec-all.h   |   2 -
 include/exec/tb-context.h |   7 +-
 include/exec/tb-hash-xx.h |  94 ++++++
 include/exec/tb-hash.h    |   7 +-
 include/qemu/compiler.h   |   2 +
 include/qemu/processor.h  |  30 ++
 include/qemu/qdist.h      |  63 ++++
 include/qemu/qht.h        | 183 ++++++++++
 include/qemu/seqlock.h    |  14 +-
 include/qemu/thread.h     |  35 ++
 tests/.gitignore          |   4 +
 tests/Makefile.include    |  14 +-
 tests/qht-bench.c         | 488 +++++++++++++++++++++++++++
 tests/test-qdist.c        | 384 +++++++++++++++++++++
 tests/test-qht-par.c      |  56 ++++
 tests/test-qht.c          | 159 +++++++++
 translate-all.c           | 131 +++++---
 util/Makefile.objs        |   2 +
 util/qdist.c              | 395 ++++++++++++++++++++++
 util/qht.c                | 833 ++++++++++++++++++++++++++++++++++++++++++++++
 22 files changed, 2893 insertions(+), 132 deletions(-)
 create mode 100644 include/exec/tb-hash-xx.h
 create mode 100644 include/qemu/processor.h
 create mode 100644 include/qemu/qdist.h
 create mode 100644 include/qemu/qht.h
 create mode 100644 tests/qht-bench.c
 create mode 100644 tests/test-qdist.c
 create mode 100644 tests/test-qht-par.c
 create mode 100644 tests/test-qht.c
 create mode 100644 util/qdist.c
 create mode 100644 util/qht.c
#1 lore raw

[Qemu-devel] [PULL 02/15] seqlock: remove optional mutex

From: "Emilio G. Cota" <[email protected]>

This option is unused; besides, it bloats the struct when not needed. Let's just let writers define their own locks elsewhere.

Message-Id: <[email protected]>

---
 cpus.c                 |  2 +-
 include/qemu/seqlock.h | 10 +---------
 2 files changed, 2 insertions(+), 10 deletions(-)
cpus.c +1 -1
index 326742f..1c92362 100644
@@ -621,7 +621,7 @@ int cpu_throttle_get_percentage(void)
 
 void cpu_ticks_init(void)
 {
-    seqlock_init(&timers_state.vm_clock_seqlock, NULL);
+    seqlock_init(&timers_state.vm_clock_seqlock);
     vmstate_register(NULL, 0, &vmstate_timers, &timers_state);
     throttle_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL_RT,
                                            cpu_throttle_timer_tick, NULL);
include/qemu/seqlock.h +1 -9
index 70b01fd..e673482 100644
@@ -19,22 +19,17 @@
 typedef struct QemuSeqLock QemuSeqLock;
 
 struct QemuSeqLock {
-    QemuMutex *mutex;
     unsigned sequence;
 };
 
-static inline void seqlock_init(QemuSeqLock *sl, QemuMutex *mutex)
+static inline void seqlock_init(QemuSeqLock *sl)
 {
-    sl->mutex = mutex;
     sl->sequence = 0;
 }
 
 /* Lock out other writers and update the count.  */
 static inline void seqlock_write_lock(QemuSeqLock *sl)
 {
-    if (sl->mutex) {
-        qemu_mutex_lock(sl->mutex);
-    }
     ++sl->sequence;
 
     /* Write sequence before updating other fields.  */
@@ -47,9 +42,6 @@ static inline void seqlock_write_unlock(QemuSeqLock *sl)
     smp_wmb();
 
     ++sl->sequence;
-    if (sl->mutex) {
-        qemu_mutex_unlock(sl->mutex);
-    }
 }
 
 static inline unsigned seqlock_read_begin(QemuSeqLock *sl)
Signature · 1 line
2.5.5
#2 lore raw

[Qemu-devel] [PULL 03/15] seqlock: rename write_lock/unlock to write_begin/end

In reply to Richard Henderson

From: "Emilio G. Cota" <[email protected]>

It is a more appropriate name, now that the mutex embedded in the seqlock is gone.

Message-Id: <[email protected]>

---
 cpus.c                 | 28 ++++++++++++++--------------
 include/qemu/seqlock.h |  4 ++--
 2 files changed, 16 insertions(+), 16 deletions(-)
cpus.c +14 -14
index 1c92362..84c3520 100644
@@ -249,13 +249,13 @@ int64_t cpu_get_clock(void)
 void cpu_enable_ticks(void)
 {
     /* Here, the really thing protected by seqlock is cpu_clock_offset. */
-    seqlock_write_lock(&timers_state.vm_clock_seqlock);
+    seqlock_write_begin(&timers_state.vm_clock_seqlock);
     if (!timers_state.cpu_ticks_enabled) {
         timers_state.cpu_ticks_offset -= cpu_get_host_ticks();
         timers_state.cpu_clock_offset -= get_clock();
         timers_state.cpu_ticks_enabled = 1;
     }
-    seqlock_write_unlock(&timers_state.vm_clock_seqlock);
+    seqlock_write_end(&timers_state.vm_clock_seqlock);
 }
 
 /* disable cpu_get_ticks() : the clock is stopped. You must not call
@@ -265,13 +265,13 @@ void cpu_enable_ticks(void)
 void cpu_disable_ticks(void)
 {
     /* Here, the really thing protected by seqlock is cpu_clock_offset. */
-    seqlock_write_lock(&timers_state.vm_clock_seqlock);
+    seqlock_write_begin(&timers_state.vm_clock_seqlock);
     if (timers_state.cpu_ticks_enabled) {
         timers_state.cpu_ticks_offset += cpu_get_host_ticks();
         timers_state.cpu_clock_offset = cpu_get_clock_locked();
         timers_state.cpu_ticks_enabled = 0;
     }
-    seqlock_write_unlock(&timers_state.vm_clock_seqlock);
+    seqlock_write_end(&timers_state.vm_clock_seqlock);
 }
 
 /* Correlation between real and virtual time is always going to be
@@ -294,7 +294,7 @@ static void icount_adjust(void)
         return;
     }
 
-    seqlock_write_lock(&timers_state.vm_clock_seqlock);
+    seqlock_write_begin(&timers_state.vm_clock_seqlock);
     cur_time = cpu_get_clock_locked();
     cur_icount = cpu_get_icount_locked();
 
@@ -315,7 +315,7 @@ static void icount_adjust(void)
     last_delta = delta;
     timers_state.qemu_icount_bias = cur_icount
                               - (timers_state.qemu_icount << icount_time_shift);
-    seqlock_write_unlock(&timers_state.vm_clock_seqlock);
+    seqlock_write_end(&timers_state.vm_clock_seqlock);
 }
 
 static void icount_adjust_rt(void *opaque)
@@ -355,7 +355,7 @@ static void icount_warp_rt(void)
         return;
     }
 
-    seqlock_write_lock(&timers_state.vm_clock_seqlock);
+    seqlock_write_begin(&timers_state.vm_clock_seqlock);
     if (runstate_is_running()) {
         int64_t clock = REPLAY_CLOCK(REPLAY_CLOCK_VIRTUAL_RT,
                                      cpu_get_clock_locked());
@@ -374,7 +374,7 @@ static void icount_warp_rt(void)
         timers_state.qemu_icount_bias += warp_delta;
     }
     vm_clock_warp_start = -1;
-    seqlock_write_unlock(&timers_state.vm_clock_seqlock);
+    seqlock_write_end(&timers_state.vm_clock_seqlock);
 
     if (qemu_clock_expired(QEMU_CLOCK_VIRTUAL)) {
         qemu_clock_notify(QEMU_CLOCK_VIRTUAL);
@@ -399,9 +399,9 @@ void qtest_clock_warp(int64_t dest)
         int64_t deadline = qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL);
         int64_t warp = qemu_soonest_timeout(dest - clock, deadline);
 
-        seqlock_write_lock(&timers_state.vm_clock_seqlock);
+        seqlock_write_begin(&timers_state.vm_clock_seqlock);
         timers_state.qemu_icount_bias += warp;
-        seqlock_write_unlock(&timers_state.vm_clock_seqlock);
+        seqlock_write_end(&timers_state.vm_clock_seqlock);
 
         qemu_clock_run_timers(QEMU_CLOCK_VIRTUAL);
         timerlist_run_timers(aio_context->tlg.tl[QEMU_CLOCK_VIRTUAL]);
@@ -468,9 +468,9 @@ void qemu_start_warp_timer(void)
              * It is useful when we want a deterministic execution time,
              * isolated from host latencies.
              */
-            seqlock_write_lock(&timers_state.vm_clock_seqlock);
+            seqlock_write_begin(&timers_state.vm_clock_seqlock);
             timers_state.qemu_icount_bias += deadline;
-            seqlock_write_unlock(&timers_state.vm_clock_seqlock);
+            seqlock_write_end(&timers_state.vm_clock_seqlock);
             qemu_clock_notify(QEMU_CLOCK_VIRTUAL);
         } else {
             /*
@@ -481,11 +481,11 @@ void qemu_start_warp_timer(void)
              * you will not be sending network packets continuously instead of
              * every 100ms.
              */
-            seqlock_write_lock(&timers_state.vm_clock_seqlock);
+            seqlock_write_begin(&timers_state.vm_clock_seqlock);
             if (vm_clock_warp_start == -1 || vm_clock_warp_start > clock) {
                 vm_clock_warp_start = clock;
             }
-            seqlock_write_unlock(&timers_state.vm_clock_seqlock);
+            seqlock_write_end(&timers_state.vm_clock_seqlock);
             timer_mod_anticipate(icount_warp_timer, clock + deadline);
         }
     } else if (deadline == 0) {
include/qemu/seqlock.h +2 -2
index e673482..4dfc055 100644
@@ -28,7 +28,7 @@ static inline void seqlock_init(QemuSeqLock *sl)
 }
 
 /* Lock out other writers and update the count.  */
-static inline void seqlock_write_lock(QemuSeqLock *sl)
+static inline void seqlock_write_begin(QemuSeqLock *sl)
 {
     ++sl->sequence;
 
@@ -36,7 +36,7 @@ static inline void seqlock_write_lock(QemuSeqLock *sl)
     smp_wmb();
 }
 
-static inline void seqlock_write_unlock(QemuSeqLock *sl)
+static inline void seqlock_write_end(QemuSeqLock *sl)
 {
     /* Write other fields before finalizing sequence.  */
     smp_wmb();
Signature · 1 line
2.5.5
#3 lore raw

[Qemu-devel] [PULL 04/15] include/processor.h: define cpu_relax()

In reply to Richard Henderson

From: "Emilio G. Cota" <[email protected]>

Taken from the linux kernel.

Message-Id: <[email protected]>

---
 include/qemu/processor.h | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)
 create mode 100644 include/qemu/processor.h
include/qemu/processor.h new file +30 -0
new file mode 100644
index 0000000..42bcc99
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2016, Emilio G. Cota <[email protected]>
+ *
+ * License: GNU GPL, version 2.
+ *   See the COPYING file in the top-level directory.
+ */
+#ifndef QEMU_PROCESSOR_H
+#define QEMU_PROCESSOR_H
+
+#include "qemu/atomic.h"
+
+#if defined(__i386__) || defined(__x86_64__)
+# define cpu_relax() asm volatile("rep; nop" ::: "memory")
+
+#elif defined(__ia64__)
+# define cpu_relax() asm volatile("hint @pause" ::: "memory")
+
+#elif defined(__aarch64__)
+# define cpu_relax() asm volatile("yield" ::: "memory")
+
+#elif defined(__powerpc64__)
+/* set Hardware Multi-Threading (HMT) priority to low; then back to medium */
+# define cpu_relax() asm volatile("or 1, 1, 1;"
+                                  "or 2, 2, 2;" ::: "memory")
+
+#else
+# define cpu_relax() barrier()
+#endif
+
+#endif /* QEMU_PROCESSOR_H */
Signature · 1 line
2.5.5
#4 lore raw

[Qemu-devel] [PULL 05/15] qemu-thread: add simple test-and-set spinlock

In reply to Richard Henderson

From: Guillaume Delbergue <[email protected]>

[Emilio's additions: use TAS instead of atomic_xchg; emit acquire/release
barriers; return bool from trylock; call cpu_relax() while spinning; optimize for uncontended locks by acquiring the lock with TAS instead of TATAS; add qemu_spin_locked().]

Message-Id: <[email protected]>

---
 include/qemu/thread.h | 35 +++++++++++++++++++++++++++++++++++
 1 file changed, 35 insertions(+)
include/qemu/thread.h +35 -0
index bdae6df..c5d71cf 100644
@@ -1,6 +1,8 @@
 #ifndef __QEMU_THREAD_H
 #define __QEMU_THREAD_H 1
 
+#include "qemu/processor.h"
+#include "qemu/atomic.h"
 
 typedef struct QemuMutex QemuMutex;
 typedef struct QemuCond QemuCond;
@@ -60,4 +62,37 @@ struct Notifier;
 void qemu_thread_atexit_add(struct Notifier *notifier);
 void qemu_thread_atexit_remove(struct Notifier *notifier);
 
+typedef struct QemuSpin {
+    int value;
+} QemuSpin;
+
+static inline void qemu_spin_init(QemuSpin *spin)
+{
+    __sync_lock_release(&spin->value);
+}
+
+static inline void qemu_spin_lock(QemuSpin *spin)
+{
+    while (unlikely(__sync_lock_test_and_set(&spin->value, true))) {
+        while (atomic_read(&spin->value)) {
+            cpu_relax();
+        }
+    }
+}
+
+static inline bool qemu_spin_trylock(QemuSpin *spin)
+{
+    return __sync_lock_test_and_set(&spin->value, true);
+}
+
+static inline bool qemu_spin_locked(QemuSpin *spin)
+{
+    return atomic_read(&spin->value);
+}
+
+static inline void qemu_spin_unlock(QemuSpin *spin)
+{
+    __sync_lock_release(&spin->value);
+}
+
 #endif
Signature · 1 line
2.5.5
#5 lore raw

[Qemu-devel] [PULL 06/15] exec: add tb_hash_func5, derived from xxhash

In reply to Richard Henderson

From: "Emilio G. Cota" <[email protected]>

This will be used by upcoming changes for hashing the tb hash.

Add this into a separate file to include the copyright notice from xxhash.

Message-Id: <[email protected]>

---
 include/exec/tb-hash-xx.h | 94 +++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 94 insertions(+)
 create mode 100644 include/exec/tb-hash-xx.h
include/exec/tb-hash-xx.h new file +94 -0
new file mode 100644
index 0000000..9f3fc05
@@ -0,0 +1,94 @@
+/*
+ * xxHash - Fast Hash algorithm
+ * Copyright (C) 2012-2016, Yann Collet
+ *
+ * BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * + Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * + Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * You can contact the author at :
+ * - xxHash source repository : https://github.com/Cyan4973/xxHash
+ */
+#ifndef EXEC_TB_HASH_XX
+#define EXEC_TB_HASH_XX
+
+#include <qemu/bitops.h>
+
+#define PRIME32_1   2654435761U
+#define PRIME32_2   2246822519U
+#define PRIME32_3   3266489917U
+#define PRIME32_4    668265263U
+#define PRIME32_5    374761393U
+
+#define TB_HASH_XX_SEED 1
+
+/*
+ * xxhash32, customized for input variables that are not guaranteed to be
+ * contiguous in memory.
+ */
+static inline
+uint32_t tb_hash_func5(uint64_t a0, uint64_t b0, uint32_t e)
+{
+    uint32_t v1 = TB_HASH_XX_SEED + PRIME32_1 + PRIME32_2;
+    uint32_t v2 = TB_HASH_XX_SEED + PRIME32_2;
+    uint32_t v3 = TB_HASH_XX_SEED + 0;
+    uint32_t v4 = TB_HASH_XX_SEED - PRIME32_1;
+    uint32_t a = a0 >> 32;
+    uint32_t b = a0;
+    uint32_t c = b0 >> 32;
+    uint32_t d = b0;
+    uint32_t h32;
+
+    v1 += a * PRIME32_2;
+    v1 = rol32(v1, 13);
+    v1 *= PRIME32_1;
+
+    v2 += b * PRIME32_2;
+    v2 = rol32(v2, 13);
+    v2 *= PRIME32_1;
+
+    v3 += c * PRIME32_2;
+    v3 = rol32(v3, 13);
+    v3 *= PRIME32_1;
+
+    v4 += d * PRIME32_2;
+    v4 = rol32(v4, 13);
+    v4 *= PRIME32_1;
+
+    h32 = rol32(v1, 1) + rol32(v2, 7) + rol32(v3, 12) + rol32(v4, 18);
+    h32 += 20;
+
+    h32 += e * PRIME32_3;
+    h32  = rol32(h32, 17) * PRIME32_4;
+
+    h32 ^= h32 >> 15;
+    h32 *= PRIME32_2;
+    h32 ^= h32 >> 13;
+    h32 *= PRIME32_3;
+    h32 ^= h32 >> 16;
+
+    return h32;
+}
+
+#endif /* EXEC_TB_HASH_XX */
Signature · 1 line
2.5.5
#6 lore raw

[Qemu-devel] [PULL 07/15] tb hash: hash phys_pc, pc, and flags with xxhash

In reply to Richard Henderson

From: "Emilio G. Cota" <[email protected]>

For some workloads such as arm bootup, tb_phys_hash is performance-critical. The is due to the high frequency of accesses to the hash table, originated by (frequent) TLB flushes that wipe out the cpu-private tb_jmp_cache's. More info:
https://lists.nongnu.org/archive/html/qemu-devel/2016-03/msg05098.html

To dig further into this I modified an arm image booting debian jessie to immediately shut down after boot. Analysis revealed that quite a bit of time is unnecessarily spent in tb_phys_hash: the cause is poor hashing that results in very uneven loading of chains in the hash table's buckets; the longest observed chain had ~550 elements.

The appended addresses this with two changes:

1) Use xxhash as the hash table's hash function. xxhash is a fast, high-quality hashing function.

2) Feed the hashing function with not just tb_phys, but also pc and flags.

This improves performance over using just tb_phys for hashing, since that resulted in some hash buckets having many TB's, while others getting very few; with these changes, the longest observed chain on a single hash bucket is brought down from ~550 to ~40.

Tests show that the other element checked for in tb_find_physical, cs_base, is always a match when tb_phys+pc+flags are a match, so hashing cs_base is wasteful. It could be that this is an ARM-only thing, though. UPDATE:

Quoted 3 lines · Richard Henderson

The cs_base field is only used by i386 (in 16-bit modes), and sparc (for a TB consisting of only a delay slot).
It may well still turn out to be reasonable to ignore cs_base for hashing.

BTW, after this change the hash table should not be called "tb_hash_phys" anymore; this is addressed later in this series.

This change gives consistent bootup time improvements. I tested two host machines:
- Intel Xeon E5-2690: 11.6% less time
- Intel i7-4790K: 19.2% less time

Increasing the number of hash buckets yields further improvements. However, using a larger, fixed number of buckets can degrade performance for other workloads that do not translate as many blocks (600K+ for debian-jessie arm bootup). This is dealt with later in this series.

Message-Id: <[email protected]>

---
 cpu-exec.c             |  4 ++--
 include/exec/tb-hash.h |  8 ++++++--
 translate-all.c        | 10 +++++-----
 3 files changed, 13 insertions(+), 9 deletions(-)
cpu-exec.c +2 -2
index f7c642f..b9e294c 100644
@@ -232,13 +232,13 @@ static TranslationBlock *tb_find_physical(CPUState *cpu,
 {
     CPUArchState *env = (CPUArchState *)cpu->env_ptr;
     TranslationBlock *tb, **tb_hash_head, **ptb1;
-    unsigned int h;
+    uint32_t h;
     tb_page_addr_t phys_pc, phys_page1;
 
     /* find translated block using physical mappings */
     phys_pc = get_page_addr_code(env, pc);
     phys_page1 = phys_pc & TARGET_PAGE_MASK;
-    h = tb_phys_hash_func(phys_pc);
+    h = tb_hash_func(phys_pc, pc, flags);
 
     /* Start at head of the hash entry */
     ptb1 = tb_hash_head = &tcg_ctx.tb_ctx.tb_phys_hash[h];
include/exec/tb-hash.h +6 -2
index 0f4e8a0..88ccfd1 100644
@@ -20,6 +20,9 @@
 #ifndef EXEC_TB_HASH
 #define EXEC_TB_HASH
 
+#include "exec/exec-all.h"
+#include "exec/tb-hash-xx.h"
+
 /* Only the bottom TB_JMP_PAGE_BITS of the jump cache hash bits vary for
    addresses on the same page.  The top bits are the same.  This allows
    TLB invalidation to quickly clear a subset of the hash table.  */
@@ -43,9 +46,10 @@ static inline unsigned int tb_jmp_cache_hash_func(target_ulong pc)
            | (tmp & TB_JMP_ADDR_MASK));
 }
 
-static inline unsigned int tb_phys_hash_func(tb_page_addr_t pc)
+static inline
+uint32_t tb_hash_func(tb_page_addr_t phys_pc, target_ulong pc, uint32_t flags)
 {
-    return (pc >> 2) & (CODE_GEN_PHYS_HASH_SIZE - 1);
+    return tb_hash_func5(phys_pc, pc, flags) & (CODE_GEN_PHYS_HASH_SIZE - 1);
 }
 
 #endif
translate-all.c +5 -5
index 118e7d3..d75737c 100644
@@ -992,12 +992,12 @@ void tb_phys_invalidate(TranslationBlock *tb, tb_page_addr_t page_addr)
 {
     CPUState *cpu;
     PageDesc *p;
-    unsigned int h;
+    uint32_t h;
     tb_page_addr_t phys_pc;
 
     /* remove the TB from the hash list */
     phys_pc = tb->page_addr[0] + (tb->pc & ~TARGET_PAGE_MASK);
-    h = tb_phys_hash_func(phys_pc);
+    h = tb_hash_func(phys_pc, tb->pc, tb->flags);
     tb_hash_remove(&tcg_ctx.tb_ctx.tb_phys_hash[h], tb);
 
     /* remove the TB from the page list */
@@ -1127,11 +1127,11 @@ static inline void tb_alloc_page(TranslationBlock *tb,
 static void tb_link_page(TranslationBlock *tb, tb_page_addr_t phys_pc,
                          tb_page_addr_t phys_page2)
 {
-    unsigned int h;
+    uint32_t h;
     TranslationBlock **ptb;
 
-    /* add in the physical hash table */
-    h = tb_phys_hash_func(phys_pc);
+    /* add in the hash table */
+    h = tb_hash_func(phys_pc, tb->pc, tb->flags);
     ptb = &tcg_ctx.tb_ctx.tb_phys_hash[h];
     tb->phys_hash_next = *ptb;
     *ptb = tb;
Signature · 1 line
2.5.5
#7 lore raw

[Qemu-devel] [PULL 11/15] qht: add test program

In reply to Richard Henderson

From: "Emilio G. Cota" <[email protected]>

Message-Id: <[email protected]>

---
 tests/.gitignore       |   1 +
 tests/Makefile.include |   6 +-
 tests/test-qht.c       | 159 +++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 165 insertions(+), 1 deletion(-)
 create mode 100644 tests/test-qht.c
tests/.gitignore +1 -0
index 7c0d156..ffde5d2 100644
@@ -50,6 +50,7 @@ test-qdev-global-props
 test-qemu-opts
 test-qdist
 test-qga
+test-qht
 test-qmp-commands
 test-qmp-commands.h
 test-qmp-event
tests/Makefile.include +5 -1
index 2948945..429d384 100644
@@ -72,6 +72,8 @@ check-unit-y += tests/test-rcu-list$(EXESUF)
 gcov-files-test-rcu-list-y = util/rcu.c
 check-unit-y += tests/test-qdist$(EXESUF)
 gcov-files-test-qdist-y = util/qdist.c
+check-unit-y += tests/test-qht$(EXESUF)
+gcov-files-test-qht-y = util/qht.c
 check-unit-y += tests/test-bitops$(EXESUF)
 check-unit-$(CONFIG_HAS_GLIB_SUBPROCESS_TESTS) += tests/test-qdev-global-props$(EXESUF)
 check-unit-y += tests/check-qom-interface$(EXESUF)
@@ -397,7 +399,8 @@ test-obj-y = tests/check-qint.o tests/check-qstring.o tests/check-qdict.o \
 	tests/test-x86-cpuid.o tests/test-mul64.o tests/test-int128.o \
 	tests/test-opts-visitor.o tests/test-qmp-event.o \
 	tests/rcutorture.o tests/test-rcu-list.o \
-	tests/test-qdist.o
+	tests/test-qdist.o \
+	tests/test-qht.o
 
 $(test-obj-y): QEMU_INCLUDES += -Itests
 QEMU_CFLAGS += -I$(SRC_PATH)/tests
@@ -437,6 +440,7 @@ tests/test-int128$(EXESUF): tests/test-int128.o
 tests/rcutorture$(EXESUF): tests/rcutorture.o $(test-util-obj-y)
 tests/test-rcu-list$(EXESUF): tests/test-rcu-list.o $(test-util-obj-y)
 tests/test-qdist$(EXESUF): tests/test-qdist.o $(test-util-obj-y)
+tests/test-qht$(EXESUF): tests/test-qht.o $(test-util-obj-y)
 
 tests/test-qdev-global-props$(EXESUF): tests/test-qdev-global-props.o \
 	hw/core/qdev.o hw/core/qdev-properties.o hw/core/hotplug.o\
tests/test-qht.c new file +159 -0

159 lines not on this page · raw message

Signature · 1 line
2.5.5
#8 lore raw

[Qemu-devel] [PULL 01/15] compiler.h: add QEMU_ALIGNED() to enforce struct alignment

In reply to Richard Henderson

From: "Emilio G. Cota" <[email protected]>

Message-Id: <[email protected]>

---
 include/qemu/compiler.h | 2 ++
 1 file changed, 2 insertions(+)
include/qemu/compiler.h +2 -0
index 8f1cc7b..b64f899 100644
@@ -41,6 +41,8 @@
 # define QEMU_PACKED __attribute__((packed))
 #endif
 
+#define QEMU_ALIGNED(X) __attribute__((aligned(X)))
+
 #ifndef glue
 #define xglue(x, y) x ## y
 #define glue(x, y) xglue(x, y)
Signature · 1 line
2.5.5
#9 lore raw

[Qemu-devel] [PULL 08/15] qdist: add module to represent frequency distributions of data

In reply to Richard Henderson

From: "Emilio G. Cota" <[email protected]>

Sometimes it is useful to have a quick histogram to represent a certain distribution -- for example, when investigating a performance regression in a hash table due to inadequate hashing.

The appended allows us to easily represent a distribution using Unicode characters. Further, the data structure keeping track of the distribution is so simple that obtaining its values for off-line processing is trivial.

Example, taking the last 10 commits to QEMU:

Characters in commit title Count
-----------------------------------

                         39      1
                         48      1
                         53      1
                         54      2
                         57      1
                         61      1
                         67      1
                         78      1
                         80      1

qdist_init(&dist);
qdist_inc(&dist, 39);
[...]
qdist_inc(&dist, 80);

char *str = qdist_pr(&dist, 9, QDIST_PR_LABELS);
// -> [39.0,43.6)▂▂ █▂ ▂ ▄[75.4,80.0]
g_free(str);

char *str = qdist_pr(&dist, 4, QDIST_PR_LABELS);
// -> [39.0,49.2)▁█▁▁[69.8,80.0]
g_free(str);

Message-Id: <[email protected]>

---
 include/qemu/qdist.h |  63 ++++++++
 util/Makefile.objs   |   1 +
 util/qdist.c         | 395 +++++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 459 insertions(+)
 create mode 100644 include/qemu/qdist.h
 create mode 100644 util/qdist.c
include/qemu/qdist.h new file +63 -0
new file mode 100644
index 0000000..f30050c
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2016, Emilio G. Cota <[email protected]>
+ *
+ * License: GNU GPL, version 2 or later.
+ *   See the COPYING file in the top-level directory.
+ */
+#ifndef QEMU_QDIST_H
+#define QEMU_QDIST_H
+
+#include "qemu/osdep.h"
+#include "qemu-common.h"
+#include "qemu/bitops.h"
+
+/*
+ * Samples with the same 'x value' end up in the same qdist_entry,
+ * e.g. inc(0.1) and inc(0.1) end up as {x=0.1, count=2}.
+ *
+ * Binning happens only at print time, so that we retain the flexibility to
+ * choose the binning. This might not be ideal for workloads that do not care
+ * much about precision and insert many samples all with different x values;
+ * in that case, pre-binning (e.g. entering both 0.115 and 0.097 as 0.1)
+ * should be considered.
+ */
+struct qdist_entry {
+    double x;
+    unsigned long count;
+};
+
+struct qdist {
+    struct qdist_entry *entries;
+    size_t n;
+    size_t size;
+};
+
+#define QDIST_PR_BORDER     BIT(0)
+#define QDIST_PR_LABELS     BIT(1)
+/* the remaining options only work if PR_LABELS is set */
+#define QDIST_PR_NODECIMAL  BIT(2)
+#define QDIST_PR_PERCENT    BIT(3)
+#define QDIST_PR_100X       BIT(4)
+#define QDIST_PR_NOBINRANGE BIT(5)
+
+void qdist_init(struct qdist *dist);
+void qdist_destroy(struct qdist *dist);
+
+void qdist_add(struct qdist *dist, double x, long count);
+void qdist_inc(struct qdist *dist, double x);
+double qdist_xmin(const struct qdist *dist);
+double qdist_xmax(const struct qdist *dist);
+double qdist_avg(const struct qdist *dist);
+unsigned long qdist_sample_count(const struct qdist *dist);
+size_t qdist_unique_entries(const struct qdist *dist);
+
+/* callers must free the returned string with g_free() */
+char *qdist_pr_plain(const struct qdist *dist, size_t n_groups);
+
+/* callers must free the returned string with g_free() */
+char *qdist_pr(const struct qdist *dist, size_t n_groups, uint32_t opt);
+
+/* Only qdist code and test code should ever call this function */
+void qdist_bin__internal(struct qdist *to, const struct qdist *from, size_t n);
+
+#endif /* QEMU_QDIST_H */
util/Makefile.objs +1 -0
index a8a777e..702435e 100644
@@ -32,3 +32,4 @@ util-obj-y += buffer.o
 util-obj-y += timed-average.o
 util-obj-y += base64.o
 util-obj-y += log.o
+util-obj-y += qdist.o
util/qdist.c new file +395 -0

395 lines not on this page · raw message

Signature · 1 line
2.5.5
#10 lore raw

[Qemu-devel] [PULL 09/15] qdist: add test program

In reply to Richard Henderson

From: "Emilio G. Cota" <[email protected]>

Message-Id: <[email protected]>

---
 tests/.gitignore       |   1 +
 tests/Makefile.include |   6 +-
 tests/test-qdist.c     | 384 +++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 390 insertions(+), 1 deletion(-)
 create mode 100644 tests/test-qdist.c
tests/.gitignore +1 -0
index a06a8ba..7c0d156 100644
@@ -48,6 +48,7 @@ test-qapi-types.[ch]
 test-qapi-visit.[ch]
 test-qdev-global-props
 test-qemu-opts
+test-qdist
 test-qga
 test-qmp-commands
 test-qmp-commands.h
tests/Makefile.include +5 -1
index a3e20e3..2948945 100644
@@ -70,6 +70,8 @@ check-unit-y += tests/rcutorture$(EXESUF)
 gcov-files-rcutorture-y = util/rcu.c
 check-unit-y += tests/test-rcu-list$(EXESUF)
 gcov-files-test-rcu-list-y = util/rcu.c
+check-unit-y += tests/test-qdist$(EXESUF)
+gcov-files-test-qdist-y = util/qdist.c
 check-unit-y += tests/test-bitops$(EXESUF)
 check-unit-$(CONFIG_HAS_GLIB_SUBPROCESS_TESTS) += tests/test-qdev-global-props$(EXESUF)
 check-unit-y += tests/check-qom-interface$(EXESUF)
@@ -394,7 +396,8 @@ test-obj-y = tests/check-qint.o tests/check-qstring.o tests/check-qdict.o \
 	tests/test-qmp-commands.o tests/test-visitor-serialization.o \
 	tests/test-x86-cpuid.o tests/test-mul64.o tests/test-int128.o \
 	tests/test-opts-visitor.o tests/test-qmp-event.o \
-	tests/rcutorture.o tests/test-rcu-list.o
+	tests/rcutorture.o tests/test-rcu-list.o \
+	tests/test-qdist.o
 
 $(test-obj-y): QEMU_INCLUDES += -Itests
 QEMU_CFLAGS += -I$(SRC_PATH)/tests
@@ -433,6 +436,7 @@ tests/test-cutils$(EXESUF): tests/test-cutils.o util/cutils.o
 tests/test-int128$(EXESUF): tests/test-int128.o
 tests/rcutorture$(EXESUF): tests/rcutorture.o $(test-util-obj-y)
 tests/test-rcu-list$(EXESUF): tests/test-rcu-list.o $(test-util-obj-y)
+tests/test-qdist$(EXESUF): tests/test-qdist.o $(test-util-obj-y)
 
 tests/test-qdev-global-props$(EXESUF): tests/test-qdev-global-props.o \
 	hw/core/qdev.o hw/core/qdev-properties.o hw/core/hotplug.o\
tests/test-qdist.c new file +384 -0

384 lines not on this page · raw message

Signature · 1 line
2.5.5
#11 lore raw

[Qemu-devel] [PULL 13/15] qht: add test-qht-par to invoke qht-bench from 'check' target

In reply to Richard Henderson

From: "Emilio G. Cota" <[email protected]>

Message-Id: <[email protected]>

---
 tests/.gitignore       |  1 +
 tests/Makefile.include |  5 ++++-
 tests/test-qht-par.c   | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 61 insertions(+), 1 deletion(-)
 create mode 100644 tests/test-qht-par.c
tests/.gitignore +1 -0
index d19023e..840ea39 100644
@@ -52,6 +52,7 @@ test-qemu-opts
 test-qdist
 test-qga
 test-qht
+test-qht-par
 test-qmp-commands
 test-qmp-commands.h
 test-qmp-event
tests/Makefile.include +4 -1
index 7b00301..7d63d16 100644
@@ -74,6 +74,8 @@ check-unit-y += tests/test-qdist$(EXESUF)
 gcov-files-test-qdist-y = util/qdist.c
 check-unit-y += tests/test-qht$(EXESUF)
 gcov-files-test-qht-y = util/qht.c
+check-unit-y += tests/test-qht-par$(EXESUF)
+gcov-files-test-qht-par-y = util/qht.c
 check-unit-y += tests/test-bitops$(EXESUF)
 check-unit-$(CONFIG_HAS_GLIB_SUBPROCESS_TESTS) += tests/test-qdev-global-props$(EXESUF)
 check-unit-y += tests/check-qom-interface$(EXESUF)
@@ -400,7 +402,7 @@ test-obj-y = tests/check-qint.o tests/check-qstring.o tests/check-qdict.o \
 	tests/test-opts-visitor.o tests/test-qmp-event.o \
 	tests/rcutorture.o tests/test-rcu-list.o \
 	tests/test-qdist.o \
-	tests/test-qht.o tests/qht-bench.o
+	tests/test-qht.o tests/qht-bench.o tests/test-qht-par.o
 
 $(test-obj-y): QEMU_INCLUDES += -Itests
 QEMU_CFLAGS += -I$(SRC_PATH)/tests
@@ -441,6 +443,7 @@ tests/rcutorture$(EXESUF): tests/rcutorture.o $(test-util-obj-y)
 tests/test-rcu-list$(EXESUF): tests/test-rcu-list.o $(test-util-obj-y)
 tests/test-qdist$(EXESUF): tests/test-qdist.o $(test-util-obj-y)
 tests/test-qht$(EXESUF): tests/test-qht.o $(test-util-obj-y)
+tests/test-qht-par$(EXESUF): tests/test-qht-par.o tests/qht-bench$(EXESUF) $(test-util-obj-y)
 tests/qht-bench$(EXESUF): tests/qht-bench.o $(test-util-obj-y)
 
 tests/test-qdev-global-props$(EXESUF): tests/test-qdev-global-props.o \
tests/test-qht-par.c new file +56 -0

56 lines not on this page · raw message

Signature · 1 line
2.5.5
#12 lore raw

[Qemu-devel] [PULL 15/15] translate-all: add tb hash bucket info to 'info jit' dump

In reply to Richard Henderson

From: "Emilio G. Cota" <[email protected]>

Examples:

- Good hashing, i.e. tb_hash_func5(phys_pc, pc, flags):
TB count 715135/2684354
[...]

TB hash buckets     388775/524288 (74.15% head buckets used)
TB hash occupancy   33.04% avg chain occ. Histogram: [0,10)%|▆ █  ▅▁▃▁▁|[90,100]%
TB hash avg chain   1.017 buckets. Histogram: 1|█▁▁|3

- Not-so-good hashing, i.e. tb_hash_func5(phys_pc, pc, 0):
TB count 712636/2684354
[...]

TB hash buckets     344924/524288 (65.79% head buckets used)
TB hash occupancy   31.64% avg chain occ. Histogram: [0,10)%|█ ▆  ▅▁▃▁▂|[90,100]%
TB hash avg chain   1.047 buckets. Histogram: 1|█▁▁▁|4

- Bad hashing, i.e. tb_hash_func5(phys_pc, 0, 0):
TB count 702818/2684354
[...]

TB hash buckets     112741/524288 (21.50% head buckets used)
TB hash occupancy   10.15% avg chain occ. Histogram: [0,10)%|█ ▁  ▁▁▁▁▁|[90,100]%
TB hash avg chain   2.107 buckets. Histogram: [1.0,10.2)|█▁▁▁▁▁▁▁▁▁|[83.8,93.0]

- Good hashing, but no auto-resize:

TB count            715634/2684354
TB hash buckets     8192/8192 (100.00% head buckets used)
TB hash occupancy   98.30% avg chain occ. Histogram: [95.3,95.8)%|▁▁▃▄▃▄▁▇▁█|[99.5,100.0]%
TB hash avg chain   22.070 buckets. Histogram: [15.0,16.7)|▁▂▅▄█▅▁▁▁▁|[30.3,32.0]

Message-Id: <[email protected]>

---
 translate-all.c | 36 ++++++++++++++++++++++++++++++++++++
 1 file changed, 36 insertions(+)
translate-all.c +36 -0
index b620fcc..e8b88b4 100644
@@ -1668,6 +1668,10 @@ void dump_exec_info(FILE *f, fprintf_function cpu_fprintf)
     int i, target_code_size, max_target_code_size;
     int direct_jmp_count, direct_jmp2_count, cross_page;
     TranslationBlock *tb;
+    struct qht_stats hst;
+    uint32_t hgram_opts;
+    size_t hgram_bins;
+    char *hgram;
 
     target_code_size = 0;
     max_target_code_size = 0;
@@ -1718,6 +1722,38 @@ void dump_exec_info(FILE *f, fprintf_function cpu_fprintf)
                 direct_jmp2_count,
                 tcg_ctx.tb_ctx.nb_tbs ? (direct_jmp2_count * 100) /
                         tcg_ctx.tb_ctx.nb_tbs : 0);
+
+    qht_statistics_init(&tcg_ctx.tb_ctx.htable, &hst);
+
+    cpu_fprintf(f, "TB hash buckets     %zu/%zu (%0.2f%% head buckets used)\n",
+                hst.used_head_buckets, hst.head_buckets,
+                (double)hst.used_head_buckets / hst.head_buckets * 100);
+
+    hgram_opts =  QDIST_PR_BORDER | QDIST_PR_LABELS;
+    hgram_opts |= QDIST_PR_100X   | QDIST_PR_PERCENT;
+    if (qdist_xmax(&hst.occupancy) - qdist_xmin(&hst.occupancy) == 1) {
+        hgram_opts |= QDIST_PR_NODECIMAL;
+    }
+    hgram = qdist_pr(&hst.occupancy, 10, hgram_opts);
+    cpu_fprintf(f, "TB hash occupancy   %0.2f%% avg chain occ. Histogram: %s\n",
+                qdist_avg(&hst.occupancy) * 100, hgram);
+    g_free(hgram);
+
+    hgram_opts = QDIST_PR_BORDER | QDIST_PR_LABELS;
+    hgram_bins = qdist_xmax(&hst.chain) - qdist_xmin(&hst.chain);
+    if (hgram_bins > 10) {
+        hgram_bins = 10;
+    } else {
+        hgram_bins = 0;
+        hgram_opts |= QDIST_PR_NODECIMAL | QDIST_PR_NOBINRANGE;
+    }
+    hgram = qdist_pr(&hst.chain, hgram_bins, hgram_opts);
+    cpu_fprintf(f, "TB hash avg chain   %0.3f buckets. Histogram: %s\n",
+                qdist_avg(&hst.chain), hgram);
+    g_free(hgram);
+
+    qht_statistics_destroy(&hst);
+
     cpu_fprintf(f, "\nStatistics:\n");
     cpu_fprintf(f, "TB flush count      %d\n", tcg_ctx.tb_ctx.tb_flush_count);
     cpu_fprintf(f, "TB invalidate count %d\n",
Signature · 1 line
2.5.5
#13 lore raw

Re: [Qemu-devel] [PULL 15/15] translate-all: add tb hash bucket info to 'info jit' dump

Quoted 57 lines · Richard Henderson

From: "Emilio G. Cota" <[email protected]>

Examples:

- Good hashing, i.e. tb_hash_func5(phys_pc, pc, flags):
TB count 715135/2684354
[...]

TB hash buckets     388775/524288 (74.15% head buckets used)
TB hash occupancy   33.04% avg chain occ. Histogram: [0,10)%|▆ █  ▅▁▃▁▁|[90,100]%
TB hash avg chain   1.017 buckets. Histogram: 1|█▁▁|3

- Not-so-good hashing, i.e. tb_hash_func5(phys_pc, pc, 0):
TB count 712636/2684354
[...]

TB hash buckets     344924/524288 (65.79% head buckets used)
TB hash occupancy   31.64% avg chain occ. Histogram: [0,10)%|█ ▆  ▅▁▃▁▂|[90,100]%
TB hash avg chain   1.047 buckets. Histogram: 1|█▁▁▁|4

- Bad hashing, i.e. tb_hash_func5(phys_pc, 0, 0):
TB count 702818/2684354
[...]

TB hash buckets     112741/524288 (21.50% head buckets used)
TB hash occupancy   10.15% avg chain occ. Histogram: [0,10)%|█ ▁  ▁▁▁▁▁|[90,100]%
TB hash avg chain   2.107 buckets. Histogram: [1.0,10.2)|█▁▁▁▁▁▁▁▁▁|[83.8,93.0]

- Good hashing, but no auto-resize:

TB count            715634/2684354
TB hash buckets     8192/8192 (100.00% head buckets used)
TB hash occupancy   98.30% avg chain occ. Histogram: [95.3,95.8)%|▁▁▃▄▃▄▁▇▁█|[99.5,100.0]%
TB hash avg chain   22.070 buckets. Histogram: [15.0,16.7)|▁▂▅▄█▅▁▁▁▁|[30.3,32.0]

Message-Id: <[email protected]>

---
  translate-all.c | 36 ++++++++++++++++++++++++++++++++++++
  1 file changed, 36 insertions(+)
translate-all.c +4 -0
index b620fcc..e8b88b4 100644
@@ -1668,6 +1668,10 @@ void dump_exec_info(FILE *f, fprintf_function cpu_fprintf)
      int i, target_code_size, max_target_code_size;
      int direct_jmp_count, direct_jmp2_count, cross_page;
      TranslationBlock *tb;
+    struct qht_stats hst;
+    uint32_t hgram_opts;
+    size_t hgram_bins;
+    char *hgram;
 
      target_code_size = 0;
      max_target_code_size = 0;

translate-all.c void dump_exec_info(FILE *f, fprintf_function cpu_fprintf) · line 1726

Quoted 5 lines
translate-all.c +2 -0
@@ -1718,6 +1722,38 @@ void dump_exec_info(FILE *f, fprintf_function cpu_fprintf)
                  direct_jmp2_count,
                  tcg_ctx.tb_ctx.nb_tbs ? (direct_jmp2_count * 100) /
                          tcg_ctx.tb_ctx.nb_tbs : 0);
+
+    qht_statistics_init(&tcg_ctx.tb_ctx.htable, &hst);

Hi Emilio

If we use kvm accelerator, we will encouter segment fault.

slave:~/.xie # gdb --args qemu-colo/x86_64-softmmu/qemu-system-x86_64 --enable-kvm -drive driver=qcow2,file.filename=fd16.qcow2 -monitor stdio -vnc :1

(qemu) info jit
Translation buffer state:

gen code size       0/0
TB count            0/0
TB avg target size  0 max=0 bytes
TB avg host size    0 bytes (expansion ratio: 0.0)

cross page TB count 0 (0%)
direct jump count 0 (0%) (2 jumps=0 0%)

Program received signal SIGSEGV, Segmentation fault.
0x0000555555c0c432 in qht_statistics_init (ht=0x5555561ddfd0 <tcg_ctx+240>, stats=0x7fffffffcab0) at util/qht.c:786
786 stats->head_buckets = map->n_buckets;
Program received signal SIGSEGV, Segmentation fault.
0x0000555555c0c432 in qht_statistics_init (ht=0x5555561ddfd0 <tcg_ctx+240>, stats=0x7fffffffcab0) at util/qht.c:786
786 stats->head_buckets = map->n_buckets;
(gdb) p *ht
$1 = {map = 0x0, lock = {lock = {__data = {__lock = 0, __count = 0, __owner = 0, __nusers = 0, __kind = 0, __spins = 0, __list = {__prev = 0x0, __next = 0x0}}, __size =

    '\000' <repeats 39 times>, __align = 0}}, mode = 0}

(gdb)

Thanks
-Xie

Quoted 34 lines
translate-all.c +30 -0
+
+    cpu_fprintf(f, "TB hash buckets     %zu/%zu (%0.2f%% head buckets used)\n",
+                hst.used_head_buckets, hst.head_buckets,
+                (double)hst.used_head_buckets / hst.head_buckets * 100);
+
+    hgram_opts =  QDIST_PR_BORDER | QDIST_PR_LABELS;
+    hgram_opts |= QDIST_PR_100X   | QDIST_PR_PERCENT;
+    if (qdist_xmax(&hst.occupancy) - qdist_xmin(&hst.occupancy) == 1) {
+        hgram_opts |= QDIST_PR_NODECIMAL;
+    }
+    hgram = qdist_pr(&hst.occupancy, 10, hgram_opts);
+    cpu_fprintf(f, "TB hash occupancy   %0.2f%% avg chain occ. Histogram: %s\n",
+                qdist_avg(&hst.occupancy) * 100, hgram);
+    g_free(hgram);
+
+    hgram_opts = QDIST_PR_BORDER | QDIST_PR_LABELS;
+    hgram_bins = qdist_xmax(&hst.chain) - qdist_xmin(&hst.chain);
+    if (hgram_bins > 10) {
+        hgram_bins = 10;
+    } else {
+        hgram_bins = 0;
+        hgram_opts |= QDIST_PR_NODECIMAL | QDIST_PR_NOBINRANGE;
+    }
+    hgram = qdist_pr(&hst.chain, hgram_bins, hgram_opts);
+    cpu_fprintf(f, "TB hash avg chain   %0.3f buckets. Histogram: %s\n",
+                qdist_avg(&hst.chain), hgram);
+    g_free(hgram);
+
+    qht_statistics_destroy(&hst);
+
      cpu_fprintf(f, "\nStatistics:\n");
      cpu_fprintf(f, "TB flush count      %d\n", tcg_ctx.tb_ctx.tb_flush_count);
      cpu_fprintf(f, "TB invalidate count %d\n",
#14 lore raw

PATCH 1/1 qht: do not segfault when gathering stats from an uninitialized qht

So far, QHT functions assume that the passed qht has previously been initialized--otherwise they segfault.

This patch makes an exception for qht_statistics_init, with the goal of simplifying calling code. For instance, qht_statistics_init is called from the 'info jit' dump, and given that under KVM the TB qht is never initialized, we get a segfault. Thus, instead of complicating the 'info jit' code with additional checks, let's allow passing an uninitialized qht to qht_statistics_init.

While at it, add a test for this to test-qht.

Before the patch (for $ qemu -enable-kvm [...]):
(qemu) info jit
[...]
direct jump count 0 (0%) (2 jumps=0 0%)
Program received signal SIGSEGV, Segmentation fault.

After the patch:
(qemu) info jit
[...]

direct jump count   0 (0%) (2 jumps=0 0%)
TB hash buckets     0/0 (-nan% head buckets used)
TB hash occupancy   nan% avg chain occ. Histogram: (null)
TB hash avg chain   nan buckets. Histogram: (null)

[...]

Reported by: Changlong Xie <[email protected]>

---
 tests/test-qht.c | 4 ++++
 util/qht.c       | 7 ++++++-
 2 files changed, 10 insertions(+), 1 deletion(-)
tests/test-qht.c +4 -0
index c8eb930..e2f9e14 100644
@@ -96,8 +96,12 @@ static void iter_check(unsigned int count)
 
 static void qht_do_test(unsigned int mode, size_t init_entries)
 {
+    /* under KVM we might fetch stats from an uninitialized qht */
+    check_n(0);
+
     qht_init(&ht, 0, mode);
 
+    check_n(0);
     insert(0, N);
     check(0, N, true);
     check_n(N);
util/qht.c +6 -1
index 6f74909..0cb95e2 100644
@@ -783,11 +783,16 @@ void qht_statistics_init(struct qht *ht, struct qht_stats *stats)
 
     map = atomic_rcu_read(&ht->map);
 
-    stats->head_buckets = map->n_buckets;
     stats->used_head_buckets = 0;
     stats->entries = 0;
     qdist_init(&stats->chain);
     qdist_init(&stats->occupancy);
+    /* bail out if the qht has not yet been initialized */
+    if (unlikely(map == NULL)) {
+        stats->head_buckets = 0;
+        return;
+    }
+    stats->head_buckets = map->n_buckets;
 
     for (i = 0; i < map->n_buckets; i++) {
         struct qht_bucket *head = &map->buckets[i];
Signature · 1 line
1.9.1
#15 lore raw

Re: [Qemu-devel] [PATCH] qht: do not segfault when gathering stats from an uninitialized qht

Quoted 64 lines · Emilio G. Cota

So far, QHT functions assume that the passed qht has previously been initialized--otherwise they segfault.

This patch makes an exception for qht_statistics_init, with the goal of simplifying calling code. For instance, qht_statistics_init is called from the 'info jit' dump, and given that under KVM the TB qht is never initialized, we get a segfault. Thus, instead of complicating the 'info jit' code with additional checks, let's allow passing an uninitialized qht to qht_statistics_init.

While at it, add a test for this to test-qht.

Before the patch (for $ qemu -enable-kvm [...]):
(qemu) info jit
[...]
direct jump count 0 (0%) (2 jumps=0 0%)
Program received signal SIGSEGV, Segmentation fault.

After the patch:
(qemu) info jit
[...]

direct jump count   0 (0%) (2 jumps=0 0%)
TB hash buckets     0/0 (-nan% head buckets used)
TB hash occupancy   nan% avg chain occ. Histogram: (null)
TB hash avg chain   nan buckets. Histogram: (null)

[...]

Reported by: Changlong Xie <[email protected]>

---
 tests/test-qht.c | 4 ++++
 util/qht.c       | 7 ++++++-
 2 files changed, 10 insertions(+), 1 deletion(-)
tests/test-qht.c +4 -0
index c8eb930..e2f9e14 100644
@@ -96,8 +96,12 @@ static void iter_check(unsigned int count)
 
 static void qht_do_test(unsigned int mode, size_t init_entries)
 {
+    /* under KVM we might fetch stats from an uninitialized qht */
+    check_n(0);
+
     qht_init(&ht, 0, mode);
 
+    check_n(0);
     insert(0, N);
     check(0, N, true);
     check_n(N);
util/qht.c +0 -1
index 6f74909..0cb95e2 100644
@@ -783,11 +783,16 @@ void qht_statistics_init(struct qht *ht, struct qht_stats *stats)
 
     map = atomic_rcu_read(&ht->map);
 
-    stats->head_buckets = map->n_buckets;
     stats->used_head_buckets = 0;
     stats->entries = 0;
     qdist_init(&stats->chain);

util/qht.c void qht_statistics_init(struct qht *ht, struct qht_stats *stats) · line 798

Quoted 10 lines
util/qht.c +6 -0
     qdist_init(&stats->occupancy);
+    /* bail out if the qht has not yet been initialized */
+    if (unlikely(map == NULL)) {
+        stats->head_buckets = 0;
+        return;
+    }
+    stats->head_buckets = map->n_buckets;
 
     for (i = 0; i < map->n_buckets; i++) {
         struct qht_bucket *head = &map->buckets[i];

Queued, thanks.

Paolo

#16 lore raw

Re: [Qemu-devel] [PATCH] qht: do not segfault when gathering stats from an uninitialized qht

In reply to Emilio G. Cota
Quoted 18 lines · Emilio G. Cota

So far, QHT functions assume that the passed qht has previously been initialized--otherwise they segfault.

This patch makes an exception for qht_statistics_init, with the goal of simplifying calling code. For instance, qht_statistics_init is called from the 'info jit' dump, and given that under KVM the TB qht is never initialized, we get a segfault. Thus, instead of complicating the 'info jit' code with additional checks, let's allow passing an uninitialized qht to qht_statistics_init.

While at it, add a test for this to test-qht.

Before the patch (for $ qemu -enable-kvm [...]):
(qemu) info jit
[...]
direct jump count 0 (0%) (2 jumps=0 0%)
Program received signal SIGSEGV, Segmentation fault.

Quoted 7 lines

After the patch:
(qemu) info jit
[...]

direct jump count   0 (0%) (2 jumps=0 0%)
TB hash buckets     0/0 (-nan% head buckets used)
TB hash occupancy   nan% avg chain occ. Histogram: (null)
TB hash avg chain   nan buckets. Histogram: (null)

This looks like we're passing NULL pointers to printf %s specifiers. This is undefined behaviour at least for POSIX printf, and I can't see anything in the glib printf-alike function documentation that gives an extra guarantee for this, so it's probably a bad idea.

Printing 'nan' also looks a bit odd, though it's not UB.

thanks
-- PMM

#17 lore raw

Re: [Qemu-devel] [PATCH] qht: do not segfault when gathering stats from an uninitialized qht

Quoted 27 lines · Peter Maydell
Quoted 18 lines · Emilio G. Cota

So far, QHT functions assume that the passed qht has previously been initialized--otherwise they segfault.

This patch makes an exception for qht_statistics_init, with the goal of simplifying calling code. For instance, qht_statistics_init is called from the 'info jit' dump, and given that under KVM the TB qht is never initialized, we get a segfault. Thus, instead of complicating the 'info jit' code with additional checks, let's allow passing an uninitialized qht to qht_statistics_init.

While at it, add a test for this to test-qht.

Before the patch (for $ qemu -enable-kvm [...]):
(qemu) info jit
[...]
direct jump count 0 (0%) (2 jumps=0 0%)
Program received signal SIGSEGV, Segmentation fault.

Quoted 7 lines

After the patch:
(qemu) info jit
[...]

direct jump count   0 (0%) (2 jumps=0 0%)
TB hash buckets     0/0 (-nan% head buckets used)
TB hash occupancy   nan% avg chain occ. Histogram: (null)
TB hash avg chain   nan buckets. Histogram: (null)
Quoted 7 lines

This looks like we're passing NULL pointers to printf %s specifiers. This is undefined behaviour at least for POSIX printf, and I can't see anything in the glib printf-alike function documentation that gives an extra guarantee for this, so it's probably a bad idea.

Printing 'nan' also looks a bit odd, though it's not UB.

Let's move everything to a new function, so that it's easy to add a check at the top:

translate-all.c +39 -31
index 0d47c1c..efeba29 100644
@@ -1663,15 +1663,50 @@ void tb_flush_jmp_cache(CPUState *cpu, target_ulong addr)
            TB_JMP_PAGE_SIZE * sizeof(TranslationBlock *));
 }
 
+static void print_qht_statistics(FILE *f, fprintf_function cpu_fprintf,
+                                 struct qht_stats hst)
+{
+    uint32_t hgram_opts;
+    size_t hgram_bins;
+    char *hgram;
+
+    if (!hst.head_buckets) {
+        return;
+    }
+    cpu_fprintf(f, "TB hash buckets     %zu/%zu (%0.2f%% head buckets used)\n",
+                hst.used_head_buckets, hst.head_buckets,
+                (double)hst.used_head_buckets / hst.head_buckets * 100);
+
+    hgram_opts =  QDIST_PR_BORDER | QDIST_PR_LABELS;
+    hgram_opts |= QDIST_PR_100X   | QDIST_PR_PERCENT;
+    if (qdist_xmax(&hst.occupancy) - qdist_xmin(&hst.occupancy) == 1) {
+        hgram_opts |= QDIST_PR_NODECIMAL;
+    }
+    hgram = qdist_pr(&hst.occupancy, 10, hgram_opts);
+    cpu_fprintf(f, "TB hash occupancy   %0.2f%% avg chain occ. Histogram: %s\n",
+                qdist_avg(&hst.occupancy) * 100, hgram);
+    g_free(hgram);
+
+    hgram_opts = QDIST_PR_BORDER | QDIST_PR_LABELS;
+    hgram_bins = qdist_xmax(&hst.chain) - qdist_xmin(&hst.chain);
+    if (hgram_bins > 10) {
+        hgram_bins = 10;
+    } else {
+        hgram_bins = 0;
+        hgram_opts |= QDIST_PR_NODECIMAL | QDIST_PR_NOBINRANGE;
+    }
+    hgram = qdist_pr(&hst.chain, hgram_bins, hgram_opts);
+    cpu_fprintf(f, "TB hash avg chain   %0.3f buckets. Histogram: %s\n",
+                qdist_avg(&hst.chain), hgram);
+    g_free(hgram);
+}
+
 void dump_exec_info(FILE *f, fprintf_function cpu_fprintf)
 {
     int i, target_code_size, max_target_code_size;
     int direct_jmp_count, direct_jmp2_count, cross_page;
     TranslationBlock *tb;
     struct qht_stats hst;
-    uint32_t hgram_opts;
-    size_t hgram_bins;
-    char *hgram;
 
     target_code_size = 0;
     max_target_code_size = 0;
@@ -1724,34 +1759,7 @@ void dump_exec_info(FILE *f, fprintf_function cpu_fprintf)
                         tcg_ctx.tb_ctx.nb_tbs : 0);
 
     qht_statistics_init(&tcg_ctx.tb_ctx.htable, &hst);
-
-    cpu_fprintf(f, "TB hash buckets     %zu/%zu (%0.2f%% head buckets used)\n",
-                hst.used_head_buckets, hst.head_buckets,
-                (double)hst.used_head_buckets / hst.head_buckets * 100);
-
-    hgram_opts =  QDIST_PR_BORDER | QDIST_PR_LABELS;
-    hgram_opts |= QDIST_PR_100X   | QDIST_PR_PERCENT;
-    if (qdist_xmax(&hst.occupancy) - qdist_xmin(&hst.occupancy) == 1) {
-        hgram_opts |= QDIST_PR_NODECIMAL;
-    }
-    hgram = qdist_pr(&hst.occupancy, 10, hgram_opts);
-    cpu_fprintf(f, "TB hash occupancy   %0.2f%% avg chain occ. Histogram: %s\n",
-                qdist_avg(&hst.occupancy) * 100, hgram);
-    g_free(hgram);
-
-    hgram_opts = QDIST_PR_BORDER | QDIST_PR_LABELS;
-    hgram_bins = qdist_xmax(&hst.chain) - qdist_xmin(&hst.chain);
-    if (hgram_bins > 10) {
-        hgram_bins = 10;
-    } else {
-        hgram_bins = 0;
-        hgram_opts |= QDIST_PR_NODECIMAL | QDIST_PR_NOBINRANGE;
-    }
-    hgram = qdist_pr(&hst.chain, hgram_bins, hgram_opts);
-    cpu_fprintf(f, "TB hash avg chain   %0.3f buckets. Histogram: %s\n",
-                qdist_avg(&hst.chain), hgram);
-    g_free(hgram);
-
+    print_qht_statistics(f, cpu_fprintf, hst);
     qht_statistics_destroy(&hst);
 
     cpu_fprintf(f, "\nStatistics:\n");
#18 lore raw

Re: [Qemu-devel] [PATCH] qht: do not segfault when gathering stats from an uninitialized qht

Quoted 8 lines · Paolo Bonzini
Quoted 7 lines · Peter Maydell

On 22 July 2016 at 17:36, Emilio G. Cota <[email protected]> wrote:
This looks like we're passing NULL pointers to
printf %s specifiers. This is undefined behaviour at least for POSIX printf, and I can't see anything in the glib printf-alike function documentation that gives an extra guarantee for this, so it's probably a bad idea.

Quoted 4 lines
Quoted 1 line

Printing 'nan' also looks a bit odd, though it's not UB.

Let's move everything to a new function, so that it's easy to add a check at the top:

I'm OK with this.

Regardless, it's probably a good idea to also add the appended to qdist, since as Peter points out passing NULL to printf is undefined.

[ Note that we need to return a dup'ed
string, since callers are supposed to call g_free() on it when they're done.]

If there's interest, I'll send a proper patch on Monday.

Thanks,

		E.
tests/test-qdist.c +2 -2
index 0298986..0a03635 100644
@@ -360,10 +360,10 @@ static void test_none(void)
     g_assert(isnan(qdist_xmax(&dist)));
 
     pr = qdist_pr_plain(&dist, 0);
-    g_assert(pr == NULL);
+    g_assert_cmpstr(pr, ==, "(empty)");
 
     pr = qdist_pr_plain(&dist, 2);
-    g_assert(pr == NULL);
+    g_assert_cmpstr(pr, ==, "(empty)");
 
     qdist_destroy(&dist);
 }
util/qdist.c +1 -1
index 56f5738..a43f464 100644
@@ -234,7 +234,7 @@ char *qdist_pr_plain(const struct qdist *dist, size_t n)
     char *ret;
 
     if (dist->n == 0) {
-        return NULL;
+        return g_strdup("(empty)");
     }
     qdist_bin__internal(&binned, dist, n);
     ret = qdist_pr_internal(&binned);
#19 lore raw

[Qemu-devel] [PULL 10/15] qht: QEMU's fast, resizable and scalable Hash Table

In reply to Richard Henderson

From: "Emilio G. Cota" <[email protected]>

This is a fast, scalable chained hash table with optional auto-resizing, allowing reads that are concurrent with reads, and reads/writes that are concurrent with writes to separate buckets.

A hash table with these features will be necessary for the scalability of the ongoing MTTCG work; before those changes arrive we can already benefit from the single-threaded speedup that qht also provides.

Message-Id: <[email protected]>

---
 include/qemu/qht.h | 183 ++++++++++++
 util/Makefile.objs |   1 +
 util/qht.c         | 833 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 1017 insertions(+)
 create mode 100644 include/qemu/qht.h
 create mode 100644 util/qht.c
include/qemu/qht.h new file +183 -0
new file mode 100644
index 0000000..aec60aa
@@ -0,0 +1,183 @@
+/*
+ * Copyright (C) 2016, Emilio G. Cota <[email protected]>
+ *
+ * License: GNU GPL, version 2 or later.
+ *   See the COPYING file in the top-level directory.
+ */
+#ifndef QEMU_QHT_H
+#define QEMU_QHT_H
+
+#include "qemu/osdep.h"
+#include "qemu/seqlock.h"
+#include "qemu/thread.h"
+#include "qemu/qdist.h"
+
+struct qht {
+    struct qht_map *map;
+    QemuMutex lock; /* serializes setters of ht->map */
+    unsigned int mode;
+};
+
+/**
+ * struct qht_stats - Statistics of a QHT
+ * @head_buckets: number of head buckets
+ * @used_head_buckets: number of non-empty head buckets
+ * @entries: total number of entries
+ * @chain: frequency distribution representing the number of buckets in each
+ *         chain, excluding empty chains.
+ * @occupancy: frequency distribution representing chain occupancy rate.
+ *             Valid range: from 0.0 (empty) to 1.0 (full occupancy).
+ *
+ * An entry is a pointer-hash pair.
+ * Each bucket can host several entries.
+ * Chains are chains of buckets, whose first link is always a head bucket.
+ */
+struct qht_stats {
+    size_t head_buckets;
+    size_t used_head_buckets;
+    size_t entries;
+    struct qdist chain;
+    struct qdist occupancy;
+};
+
+typedef bool (*qht_lookup_func_t)(const void *obj, const void *userp);
+typedef void (*qht_iter_func_t)(struct qht *ht, void *p, uint32_t h, void *up);
+
+#define QHT_MODE_AUTO_RESIZE 0x1 /* auto-resize when heavily loaded */
+
+/**
+ * qht_init - Initialize a QHT
+ * @ht: QHT to be initialized
+ * @n_elems: number of entries the hash table should be optimized for.
+ * @mode: bitmask with OR'ed QHT_MODE_*
+ */
+void qht_init(struct qht *ht, size_t n_elems, unsigned int mode);
+
+/**
+ * qht_destroy - destroy a previously initialized QHT
+ * @ht: QHT to be destroyed
+ *
+ * Call only when there are no readers/writers left.
+ */
+void qht_destroy(struct qht *ht);
+
+/**
+ * qht_insert - Insert a pointer into the hash table
+ * @ht: QHT to insert to
+ * @p: pointer to be inserted
+ * @hash: hash corresponding to @p
+ *
+ * Attempting to insert a NULL @p is a bug.
+ * Inserting the same pointer @p with different @hash values is a bug.
+ *
+ * Returns true on sucess.
+ * Returns false if the @p-@hash pair already exists in the hash table.
+ */
+bool qht_insert(struct qht *ht, void *p, uint32_t hash);
+
+/**
+ * qht_lookup - Look up a pointer in a QHT
+ * @ht: QHT to be looked up
+ * @func: function to compare existing pointers against @userp
+ * @userp: pointer to pass to @func
+ * @hash: hash of the pointer to be looked up
+ *
+ * Needs to be called under an RCU read-critical section.
+ *
+ * The user-provided @func compares pointers in QHT against @userp.
+ * If the function returns true, a match has been found.
+ *
+ * Returns the corresponding pointer when a match is found.
+ * Returns NULL otherwise.
+ */
+void *qht_lookup(struct qht *ht, qht_lookup_func_t func, const void *userp,
+                 uint32_t hash);
+
+/**
+ * qht_remove - remove a pointer from the hash table
+ * @ht: QHT to remove from
+ * @p: pointer to be removed
+ * @hash: hash corresponding to @p
+ *
+ * Attempting to remove a NULL @p is a bug.
+ *
+ * Just-removed @p pointers cannot be immediately freed; they need to remain
+ * valid until the end of the RCU grace period in which qht_remove() is called.
+ * This guarantees that concurrent lookups will always compare against valid
+ * data.
+ *
+ * Returns true on success.
+ * Returns false if the @p-@hash pair was not found.
+ */
+bool qht_remove(struct qht *ht, const void *p, uint32_t hash);
+
+/**
+ * qht_reset - reset a QHT
+ * @ht: QHT to be reset
+ *
+ * All entries in the hash table are reset. No resizing is performed.
+ *
+ * If concurrent readers may exist, the objects pointed to by the hash table
+ * must remain valid for the existing RCU grace period -- see qht_remove().
+ * See also: qht_reset_size()
+ */
+void qht_reset(struct qht *ht);
+
+/**
+ * qht_reset_size - reset and resize a QHT
+ * @ht: QHT to be reset and resized
+ * @n_elems: number of entries the resized hash table should be optimized for.
+ *
+ * Returns true if the resize was necessary and therefore performed.
+ * Returns false otherwise.
+ *
+ * If concurrent readers may exist, the objects pointed to by the hash table
+ * must remain valid for the existing RCU grace period -- see qht_remove().
+ * See also: qht_reset(), qht_resize().
+ */
+bool qht_reset_size(struct qht *ht, size_t n_elems);
+
+/**
+ * qht_resize - resize a QHT
+ * @ht: QHT to be resized
+ * @n_elems: number of entries the resized hash table should be optimized for
+ *
+ * Returns true on success.
+ * Returns false if the resize was not necessary and therefore not performed.
+ * See also: qht_reset_size().
+ */
+bool qht_resize(struct qht *ht, size_t n_elems);
+
+/**
+ * qht_iter - Iterate over a QHT
+ * @ht: QHT to be iterated over
+ * @func: function to be called for each entry in QHT
+ * @userp: additional pointer to be passed to @func
+ *
+ * Each time it is called, user-provided @func is passed a pointer-hash pair,
+ * plus @userp.
+ */
+void qht_iter(struct qht *ht, qht_iter_func_t func, void *userp);
+
+/**
+ * qht_statistics_init - Gather statistics from a QHT
+ * @ht: QHT to gather statistics from
+ * @stats: pointer to a struct qht_stats to be filled in
+ *
+ * Does NOT need to be called under an RCU read-critical section,
+ * since it does not dereference any pointers stored in the hash table.
+ *
+ * When done with @stats, pass the struct to qht_statistics_destroy().
+ * Failing to do this will leak memory.
+ */
+void qht_statistics_init(struct qht *ht, struct qht_stats *stats);
+
+/**
+ * qht_statistics_destroy - Destroy a struct qht_stats
+ * @stats: stuct qht_stats to be destroyed
+ *
+ * See also: qht_statistics_init().
+ */
+void qht_statistics_destroy(struct qht_stats *stats);
+
+#endif /* QEMU_QHT_H */
util/Makefile.objs +1 -0
index 702435e..45f8794 100644
@@ -33,3 +33,4 @@ util-obj-y += timed-average.o
 util-obj-y += base64.o
 util-obj-y += log.o
 util-obj-y += qdist.o
+util-obj-y += qht.o
util/qht.c new file +833 -0

833 lines not on this page · raw message

Signature · 1 line
2.5.5
#20 lore raw

[Qemu-devel] [PULL 14/15] tb hash: track translated blocks with qht

In reply to Richard Henderson

From: "Emilio G. Cota" <[email protected]>

Having a fixed-size hash table for keeping track of all translation blocks is suboptimal: some workloads are just too big or too small to get maximum performance from the hash table. The MRU promotion policy helps improve performance when the hash table is a little undersized, but it cannot make up for severely undersized hash tables.

Furthermore, frequent MRU promotions result in writes that are a scalability bottleneck. For scalability, lookups should only perform reads, not writes. This is not a big deal for now, but it will become one once MTTCG matures.

The appended fixes these issues by using qht as the implementation of the TB hash table. This solution is superior to other alternatives considered, namely:

- master: implementation in QEMU before this patchset
- xxhash: before this patch, i.e. fixed buckets + xxhash hashing + MRU.
- xxhash-rcu: fixed buckets + xxhash + RCU list + MRU.
MRU is implemented here by adding an intermediate struct that contains the u32 hash and a pointer to the TB; this allows us, on an MRU promotion, to copy said struct (that is not at the head), and put this new copy at the head. After a grace period, the original non-head struct can be eliminated, and after another grace period, freed.
- qht-fixed-nomru: fixed buckets + xxhash + qht without auto-resize + no MRU for lookups; MRU for inserts.
The appended solution is the following:
- qht-dyn-nomru: dynamic number of buckets + xxhash + qht w/ auto-resize + no MRU for lookups; MRU for inserts.

The plots below compare the considered solutions. The Y axis shows the boot time (in seconds) of a debian jessie image with arm-softmmu; the X axis sweeps the number of buckets (or initial number of buckets for qht-autoresize). The plots in PNG format (and with errorbars) can be seen here:
http://imgur.com/a/Awgnq

Each test runs 5 times, and the entire QEMU process is pinned to a single core for repeatability of results.

                            Host: Intel Xeon E5-2690

28 ++------------+-------------+-------------+-------------+------------++
A***** + + + master **A*** +
27 ++ * xxhash ##B###++

     |      A******A******                               xxhash-rcu $$C$$$ |
  26 C$$                  A******A******            qht-fixed-nomru*%%D%%%++
     D%%$$                              A******A******A*qht-dyn-mru A*E****A
  25 ++ %%$$                                          qht-dyn-nomru &&F&&&++
     B#####%                                                               |
  24 ++    #C$$$$$                                                        ++
     |      B###  $                                                        |
     |          ## C$$$$$$                                                 |
  23 ++           #       C$$$$$$                                         ++
     |             B######       C$$$$$$                                %%%D
  22 ++                  %B######       C$$$$$$C$$$$$$C$$$$$$C$$$$$$C$$$$$$C
     |                    D%%%%%%B######      @E@@@@@@    %%%D%%%@@@E@@@@@@E

21 E@@@@@@E@@@@@@F&&&@@@E@@@&&&D%%%%%%B######B######B######B######B######B
+ E@@@ F&&& + E@ + F&&& + +
20 ++------------+-------------+-------------+-------------+------------++
14 16 18 20 22 24
log2 number of buckets

Host: Intel i7-4790K

14.5 ++------------+------------+-------------+------------+------------++
A** + + + master **A*** +
14 ++ ** xxhash ##B###++
13.5 ++ ** xxhash-rcu $$C$$$++

       |                                            qht-fixed-nomru %%D%%% |
    13 ++     A******                                   qht-dyn-mru @@E@@@++
       |             A*****A******A******             qht-dyn-nomru &&F&&& |
  12.5 C$$                               A******A******A*****A******    ***A
    12 ++ $$                                                        A***  ++
       D%%% $$                                                             |
  11.5 ++  %%                                                             ++
       B###  %C$$$$$$                                                      |
    11 ++  ## D%%%%% C$$$$$                                               ++
       |     #      %      C$$$$$$                                         |
  10.5 F&&&&&&B######D%%%%%       C$$$$$$C$$$$$$C$$$$$$C$$$$$C$$$$$$    $$$C

10 E@@@@@@E@@@@@@B#####B######B######E@@@@@@E@@@%%%D%%%%%D%%%###B######B
+ F&& D%%%%%%B######B######B#####B###@@@D%%% +
9.5 ++------------+------------+-------------+------------+------------++
14 16 18 20 22 24
log2 number of buckets

Note that the original point before this patch series is X=15 for "master"; the little sensitivity to the increased number of buckets is due to the poor hashing function in master.

xxhash-rcu has significant overhead due to the constant churn of allocating and deallocating intermediate structs for implementing MRU. An alternative would be do consider failed lookups as "maybe not there", and then acquire the external lock (tb_lock in this case) to really confirm that there was indeed a failed lookup. This, however, would not be enough to implement dynamic resizing--this is more complex: see "Resizable, Scalable, Concurrent Hash Tables via Relativistic Programming" by Triplett, McKenney and Walpole. This solution was discarded due to the very coarse RCU read critical sections that we have in MTTCG; resizing requires waiting for readers after every pointer update, and resizes require many pointer updates, so this would quickly become prohibitive.

qht-fixed-nomru shows that MRU promotion is advisable for undersized hash tables.

However, qht-dyn-mru shows that MRU promotion is not important if the hash table is properly sized: there is virtually no difference in performance between qht-dyn-nomru and qht-dyn-mru.

Before this patch, we're at X=15 on "xxhash"; after this patch, we're at X=15 @ qht-dyn-nomru. This patch thus matches the best performance that we can achieve with optimum sizing of the hash table, while keeping the hash table scalable for readers.

The improvement we get before and after this patch for booting debian jessie with arm-softmmu is:

- Intel Xeon E5-2690: 10.5% less time
- Intel i7-4790K: 5.2% less time

We could get this same improvement _for this particular workload_ by statically increasing the size of the hash table. But this would hurt workloads that do not need a large hash table. The dynamic (upward) resizing allows us to start small and enlarge the hash table as needed.

A quick note on downsizing: the table is resized back to 2**15 buckets on every tb_flush; this makes sense because it is not guaranteed that the table will reach the same number of TBs later on (e.g. most bootup code is thrown away after boot); it makes sense to grow the hash table as more code blocks are translated. This also avoids the complication of having to build downsizing hysteresis logic into qht.

Message-Id: <[email protected]>

---
 cpu-exec.c                | 86 +++++++++++++++++++++++------------------------
 include/exec/exec-all.h   |  2 --
 include/exec/tb-context.h |  7 ++--
 include/exec/tb-hash.h    |  3 +-
 translate-all.c           | 85 +++++++++++++++++++++-------------------------
 5 files changed, 86 insertions(+), 97 deletions(-)
cpu-exec.c +43 -43
index b9e294c..b840e1d 100644
@@ -225,57 +225,57 @@ static void cpu_exec_nocache(CPUState *cpu, int max_cycles,
 }
 #endif
 
+struct tb_desc {
+    target_ulong pc;
+    target_ulong cs_base;
+    CPUArchState *env;
+    tb_page_addr_t phys_page1;
+    uint32_t flags;
+};
+
+static bool tb_cmp(const void *p, const void *d)
+{
+    const TranslationBlock *tb = p;
+    const struct tb_desc *desc = d;
+
+    if (tb->pc == desc->pc &&
+        tb->page_addr[0] == desc->phys_page1 &&
+        tb->cs_base == desc->cs_base &&
+        tb->flags == desc->flags) {
+        /* check next page if needed */
+        if (tb->page_addr[1] == -1) {
+            return true;
+        } else {
+            tb_page_addr_t phys_page2;
+            target_ulong virt_page2;
+
+            virt_page2 = (desc->pc & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;
+            phys_page2 = get_page_addr_code(desc->env, virt_page2);
+            if (tb->page_addr[1] == phys_page2) {
+                return true;
+            }
+        }
+    }
+    return false;
+}
+
 static TranslationBlock *tb_find_physical(CPUState *cpu,
                                           target_ulong pc,
                                           target_ulong cs_base,
                                           uint32_t flags)
 {
-    CPUArchState *env = (CPUArchState *)cpu->env_ptr;
-    TranslationBlock *tb, **tb_hash_head, **ptb1;
+    tb_page_addr_t phys_pc;
+    struct tb_desc desc;
     uint32_t h;
-    tb_page_addr_t phys_pc, phys_page1;
 
-    /* find translated block using physical mappings */
-    phys_pc = get_page_addr_code(env, pc);
-    phys_page1 = phys_pc & TARGET_PAGE_MASK;
+    desc.env = (CPUArchState *)cpu->env_ptr;
+    desc.cs_base = cs_base;
+    desc.flags = flags;
+    desc.pc = pc;
+    phys_pc = get_page_addr_code(desc.env, pc);
+    desc.phys_page1 = phys_pc & TARGET_PAGE_MASK;
     h = tb_hash_func(phys_pc, pc, flags);
-
-    /* Start at head of the hash entry */
-    ptb1 = tb_hash_head = &tcg_ctx.tb_ctx.tb_phys_hash[h];
-    tb = *ptb1;
-
-    while (tb) {
-        if (tb->pc == pc &&
-            tb->page_addr[0] == phys_page1 &&
-            tb->cs_base == cs_base &&
-            tb->flags == flags) {
-
-            if (tb->page_addr[1] == -1) {
-                /* done, we have a match */
-                break;
-            } else {
-                /* check next page if needed */
-                target_ulong virt_page2 = (pc & TARGET_PAGE_MASK) +
-                                          TARGET_PAGE_SIZE;
-                tb_page_addr_t phys_page2 = get_page_addr_code(env, virt_page2);
-
-                if (tb->page_addr[1] == phys_page2) {
-                    break;
-                }
-            }
-        }
-
-        ptb1 = &tb->phys_hash_next;
-        tb = *ptb1;
-    }
-
-    if (tb) {
-        /* Move the TB to the head of the list */
-        *ptb1 = tb->phys_hash_next;
-        tb->phys_hash_next = *tb_hash_head;
-        *tb_hash_head = tb;
-    }
-    return tb;
+    return qht_lookup(&tcg_ctx.tb_ctx.htable, tb_cmp, &desc, h);
 }
 
 static TranslationBlock *tb_find_slow(CPUState *cpu,
include/exec/exec-all.h +0 -2
index e076397..c1f59fa 100644
@@ -215,8 +215,6 @@ struct TranslationBlock {
 
     void *tc_ptr;    /* pointer to the translated code */
     uint8_t *tc_search;  /* pointer to search data */
-    /* next matching tb for physical address. */
-    struct TranslationBlock *phys_hash_next;
     /* original tb when cflags has CF_NOCACHE */
     struct TranslationBlock *orig_tb;
     /* first and second physical page containing code. The lower bit
include/exec/tb-context.h +4 -3
index 5efe3d9..e209c1c 100644
@@ -21,9 +21,10 @@
 #define QEMU_TB_CONTEXT_H_
 
 #include "qemu/thread.h"
+#include "qemu/qht.h"
 
-#define CODE_GEN_PHYS_HASH_BITS     15
-#define CODE_GEN_PHYS_HASH_SIZE     (1 << CODE_GEN_PHYS_HASH_BITS)
+#define CODE_GEN_HTABLE_BITS     15
+#define CODE_GEN_HTABLE_SIZE     (1 << CODE_GEN_HTABLE_BITS)
 
 typedef struct TranslationBlock TranslationBlock;
 typedef struct TBContext TBContext;
@@ -31,7 +32,7 @@ typedef struct TBContext TBContext;
 struct TBContext {
 
     TranslationBlock *tbs;
-    TranslationBlock *tb_phys_hash[CODE_GEN_PHYS_HASH_SIZE];
+    struct qht htable;
     int nb_tbs;
     /* any access to the tbs or the page table must use this lock */
     QemuMutex tb_lock;
include/exec/tb-hash.h +1 -2
index 88ccfd1..1d0200b 100644
@@ -20,7 +20,6 @@
 #ifndef EXEC_TB_HASH
 #define EXEC_TB_HASH
 
-#include "exec/exec-all.h"
 #include "exec/tb-hash-xx.h"
 
 /* Only the bottom TB_JMP_PAGE_BITS of the jump cache hash bits vary for
@@ -49,7 +48,7 @@ static inline unsigned int tb_jmp_cache_hash_func(target_ulong pc)
 static inline
 uint32_t tb_hash_func(tb_page_addr_t phys_pc, target_ulong pc, uint32_t flags)
 {
-    return tb_hash_func5(phys_pc, pc, flags) & (CODE_GEN_PHYS_HASH_SIZE - 1);
+    return tb_hash_func5(phys_pc, pc, flags);
 }
 
 #endif
translate-all.c +38 -47

137 lines not on this page · raw message

Signature · 1 line
2.5.5
#21 lore raw

Re: [Qemu-devel] [PULL 14/15] tb hash: track translated blocks with qht

On Fri, 10 Jun 2016 07:26:52 -0700
Richard Henderson <[email protected]> wrote:

This patch make SIGSEGVs QEMU when debugging KVM guest with gdb

Steps to reproduce:

Seabios:
clone and build current master with
defconfig plus CONFIG_RELOCATE_INIT=n on top of it

QEMU:
./configure --enable-debug --target-list=x86_64-softmmu ./x86_64-softmmu/qemu-system-x86_64 -enable-kvm -bios ../seabios/out/bios.bin -s -S

GDB:
gdb ../seabios/out/rom.o
(gdb) b smp_setup
(gdb) target remote localhost:1234
(gdb) c
Continuing.
Remote connection closed

QEMU's backtrace:

Program received signal SIGSEGV, Segmentation fault.
0x0000555555c19c6f in qht_reset_size (ht=0x555556240058 <tcg_ctx+216>, n_elems=0x8000) at util/qht.c:422
422 if (n_buckets != map->n_buckets) {
(gdb) bt

#0  0x0000555555c19c6f in qht_reset_size (ht=0x555556240058 <tcg_ctx+216>, n_elems=0x8000) at util/qht.c:422
#1  0x0000555555754bdd in tb_flush (cpu=0x0) at /home/imammedo/builds/qemu/translate-all.c:855
#2  0x000055555579026e in gdb_vm_state_change (opaque=0x0, running=0x0, state=RUN_STATE_DEBUG) at /home/imammedo/builds/qemu/gdbstub.c:1276
#3  0x00005555558be59f in vm_state_notify (running=0x0, state=RUN_STATE_DEBUG) at vl.c:1585
#4  0x000055555578137e in do_vm_stop (state=RUN_STATE_DEBUG) at /home/imammedo/builds/qemu/cpus.c:743
#5  0x0000555555782b5e in vm_stop (state=RUN_STATE_DEBUG) at /home/imammedo/builds/qemu/cpus.c:1476
#6  0x00005555558bebdf in main_loop_should_exit () at vl.c:1856
#7  0x00005555558bed57 in main_loop () at vl.c:1912
#8  0x00005555558c678a in main (argc=0x6, argv=0x7fffffffe0c8, envp=0x7fffffffe100) at vl.c:4603
Quoted 459 lines

From: "Emilio G. Cota" <[email protected]>

Having a fixed-size hash table for keeping track of all translation blocks is suboptimal: some workloads are just too big or too small to get maximum performance from the hash table. The MRU promotion policy helps improve performance when the hash table is a little undersized, but it cannot make up for severely undersized hash tables.

Furthermore, frequent MRU promotions result in writes that are a scalability bottleneck. For scalability, lookups should only perform reads, not writes. This is not a big deal for now, but it will become one once MTTCG matures.

The appended fixes these issues by using qht as the implementation of the TB hash table. This solution is superior to other alternatives considered, namely:

- master: implementation in QEMU before this patchset
- xxhash: before this patch, i.e. fixed buckets + xxhash hashing + MRU.
- xxhash-rcu: fixed buckets + xxhash + RCU list + MRU.
MRU is implemented here by adding an intermediate struct that contains the u32 hash and a pointer to the TB; this allows us, on an MRU promotion, to copy said struct (that is not at the head), and put this new copy at the head. After a grace period, the original non-head struct can be eliminated, and after another grace period, freed.
- qht-fixed-nomru: fixed buckets + xxhash + qht without auto-resize + no MRU for lookups; MRU for inserts.
The appended solution is the following:
- qht-dyn-nomru: dynamic number of buckets + xxhash + qht w/ auto-resize + no MRU for lookups; MRU for inserts.

The plots below compare the considered solutions. The Y axis shows the boot time (in seconds) of a debian jessie image with arm-softmmu; the X axis sweeps the number of buckets (or initial number of buckets for qht-autoresize). The plots in PNG format (and with errorbars) can be seen here:
http://imgur.com/a/Awgnq

Each test runs 5 times, and the entire QEMU process is pinned to a single core for repeatability of results.

                            Host: Intel Xeon E5-2690

28 ++------------+-------------+-------------+-------------+------------++
A***** + + + master **A*** +
27 ++ * xxhash ##B###++

     |      A******A******                               xxhash-rcu $$C$$$ |
  26 C$$                  A******A******            qht-fixed-nomru*%%D%%%++
     D%%$$                              A******A******A*qht-dyn-mru A*E****A
  25 ++ %%$$                                          qht-dyn-nomru &&F&&&++
     B#####%                                                               |
  24 ++    #C$$$$$                                                        ++
     |      B###  $                                                        |
     |          ## C$$$$$$                                                 |
  23 ++           #       C$$$$$$                                         ++
     |             B######       C$$$$$$                                %%%D
  22 ++                  %B######       C$$$$$$C$$$$$$C$$$$$$C$$$$$$C$$$$$$C
     |                    D%%%%%%B######      @E@@@@@@    %%%D%%%@@@E@@@@@@E

21 E@@@@@@E@@@@@@F&&&@@@E@@@&&&D%%%%%%B######B######B######B######B######B
+ E@@@ F&&& + E@ + F&&& + +
20 ++------------+-------------+-------------+-------------+------------++
14 16 18 20 22 24
log2 number of buckets

Host: Intel i7-4790K

14.5 ++------------+------------+-------------+------------+------------++
A** + + + master **A*** +
14 ++ ** xxhash ##B###++
13.5 ++ ** xxhash-rcu $$C$$$++

       |                                            qht-fixed-nomru %%D%%% |
    13 ++     A******                                   qht-dyn-mru @@E@@@++
       |             A*****A******A******             qht-dyn-nomru &&F&&& |
  12.5 C$$                               A******A******A*****A******    ***A
    12 ++ $$                                                        A***  ++
       D%%% $$                                                             |
  11.5 ++  %%                                                             ++
       B###  %C$$$$$$                                                      |
    11 ++  ## D%%%%% C$$$$$                                               ++
       |     #      %      C$$$$$$                                         |
  10.5 F&&&&&&B######D%%%%%       C$$$$$$C$$$$$$C$$$$$$C$$$$$C$$$$$$    $$$C

10 E@@@@@@E@@@@@@B#####B######B######E@@@@@@E@@@%%%D%%%%%D%%%###B######B
+ F&& D%%%%%%B######B######B#####B###@@@D%%% +
9.5 ++------------+------------+-------------+------------+------------++
14 16 18 20 22 24
log2 number of buckets

Note that the original point before this patch series is X=15 for "master"; the little sensitivity to the increased number of buckets is due to the poor hashing function in master.

xxhash-rcu has significant overhead due to the constant churn of allocating and deallocating intermediate structs for implementing MRU. An alternative would be do consider failed lookups as "maybe not there", and then acquire the external lock (tb_lock in this case) to really confirm that there was indeed a failed lookup. This, however, would not be enough to implement dynamic resizing--this is more complex: see "Resizable, Scalable, Concurrent Hash Tables via Relativistic Programming" by Triplett, McKenney and Walpole. This solution was discarded due to the very coarse RCU read critical sections that we have in MTTCG; resizing requires waiting for readers after every pointer update, and resizes require many pointer updates, so this would quickly become prohibitive.

qht-fixed-nomru shows that MRU promotion is advisable for undersized hash tables.

However, qht-dyn-mru shows that MRU promotion is not important if the hash table is properly sized: there is virtually no difference in performance between qht-dyn-nomru and qht-dyn-mru.

Before this patch, we're at X=15 on "xxhash"; after this patch, we're at X=15 @ qht-dyn-nomru. This patch thus matches the best performance that we can achieve with optimum sizing of the hash table, while keeping the hash table scalable for readers.

The improvement we get before and after this patch for booting debian jessie with arm-softmmu is:

- Intel Xeon E5-2690: 10.5% less time
- Intel i7-4790K: 5.2% less time

We could get this same improvement _for this particular workload_ by statically increasing the size of the hash table. But this would hurt workloads that do not need a large hash table. The dynamic (upward) resizing allows us to start small and enlarge the hash table as needed.

A quick note on downsizing: the table is resized back to 2**15 buckets on every tb_flush; this makes sense because it is not guaranteed that the table will reach the same number of TBs later on (e.g. most bootup code is thrown away after boot); it makes sense to grow the hash table as more code blocks are translated. This also avoids the complication of having to build downsizing hysteresis logic into qht.

Message-Id: <[email protected]>

---
 cpu-exec.c                | 86 +++++++++++++++++++++++------------------------
 include/exec/exec-all.h   |  2 --
 include/exec/tb-context.h |  7 ++--
 include/exec/tb-hash.h    |  3 +-
 translate-all.c           | 85 +++++++++++++++++++++-------------------------
 5 files changed, 86 insertions(+), 97 deletions(-)
cpu-exec.c +43 -43
index b9e294c..b840e1d 100644
@@ -225,57 +225,57 @@ static void cpu_exec_nocache(CPUState *cpu, int max_cycles,
 }
 #endif
 
+struct tb_desc {
+    target_ulong pc;
+    target_ulong cs_base;
+    CPUArchState *env;
+    tb_page_addr_t phys_page1;
+    uint32_t flags;
+};
+
+static bool tb_cmp(const void *p, const void *d)
+{
+    const TranslationBlock *tb = p;
+    const struct tb_desc *desc = d;
+
+    if (tb->pc == desc->pc &&
+        tb->page_addr[0] == desc->phys_page1 &&
+        tb->cs_base == desc->cs_base &&
+        tb->flags == desc->flags) {
+        /* check next page if needed */
+        if (tb->page_addr[1] == -1) {
+            return true;
+        } else {
+            tb_page_addr_t phys_page2;
+            target_ulong virt_page2;
+
+            virt_page2 = (desc->pc & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;
+            phys_page2 = get_page_addr_code(desc->env, virt_page2);
+            if (tb->page_addr[1] == phys_page2) {
+                return true;
+            }
+        }
+    }
+    return false;
+}
+
 static TranslationBlock *tb_find_physical(CPUState *cpu,
                                           target_ulong pc,
                                           target_ulong cs_base,
                                           uint32_t flags)
 {
-    CPUArchState *env = (CPUArchState *)cpu->env_ptr;
-    TranslationBlock *tb, **tb_hash_head, **ptb1;
+    tb_page_addr_t phys_pc;
+    struct tb_desc desc;
     uint32_t h;
-    tb_page_addr_t phys_pc, phys_page1;
 
-    /* find translated block using physical mappings */
-    phys_pc = get_page_addr_code(env, pc);
-    phys_page1 = phys_pc & TARGET_PAGE_MASK;
+    desc.env = (CPUArchState *)cpu->env_ptr;
+    desc.cs_base = cs_base;
+    desc.flags = flags;
+    desc.pc = pc;
+    phys_pc = get_page_addr_code(desc.env, pc);
+    desc.phys_page1 = phys_pc & TARGET_PAGE_MASK;
     h = tb_hash_func(phys_pc, pc, flags);
-
-    /* Start at head of the hash entry */
-    ptb1 = tb_hash_head = &tcg_ctx.tb_ctx.tb_phys_hash[h];
-    tb = *ptb1;
-
-    while (tb) {
-        if (tb->pc == pc &&
-            tb->page_addr[0] == phys_page1 &&
-            tb->cs_base == cs_base &&
-            tb->flags == flags) {
-
-            if (tb->page_addr[1] == -1) {
-                /* done, we have a match */
-                break;
-            } else {
-                /* check next page if needed */
-                target_ulong virt_page2 = (pc & TARGET_PAGE_MASK) +
-                                          TARGET_PAGE_SIZE;
-                tb_page_addr_t phys_page2 = get_page_addr_code(env, virt_page2);
-
-                if (tb->page_addr[1] == phys_page2) {
-                    break;
-                }
-            }
-        }
-
-        ptb1 = &tb->phys_hash_next;
-        tb = *ptb1;
-    }
-
-    if (tb) {
-        /* Move the TB to the head of the list */
-        *ptb1 = tb->phys_hash_next;
-        tb->phys_hash_next = *tb_hash_head;
-        *tb_hash_head = tb;
-    }
-    return tb;
+    return qht_lookup(&tcg_ctx.tb_ctx.htable, tb_cmp, &desc, h);
 }
 
 static TranslationBlock *tb_find_slow(CPUState *cpu,
include/exec/exec-all.h +0 -2
index e076397..c1f59fa 100644
@@ -215,8 +215,6 @@ struct TranslationBlock {
 
     void *tc_ptr;    /* pointer to the translated code */
     uint8_t *tc_search;  /* pointer to search data */
-    /* next matching tb for physical address. */
-    struct TranslationBlock *phys_hash_next;
     /* original tb when cflags has CF_NOCACHE */
     struct TranslationBlock *orig_tb;
     /* first and second physical page containing code. The lower bit
include/exec/tb-context.h +4 -3
index 5efe3d9..e209c1c 100644
@@ -21,9 +21,10 @@
 #define QEMU_TB_CONTEXT_H_
 
 #include "qemu/thread.h"
+#include "qemu/qht.h"
 
-#define CODE_GEN_PHYS_HASH_BITS     15
-#define CODE_GEN_PHYS_HASH_SIZE     (1 << CODE_GEN_PHYS_HASH_BITS)
+#define CODE_GEN_HTABLE_BITS     15
+#define CODE_GEN_HTABLE_SIZE     (1 << CODE_GEN_HTABLE_BITS)
 
 typedef struct TranslationBlock TranslationBlock;
 typedef struct TBContext TBContext;
@@ -31,7 +32,7 @@ typedef struct TBContext TBContext;
 struct TBContext {
 
     TranslationBlock *tbs;
-    TranslationBlock *tb_phys_hash[CODE_GEN_PHYS_HASH_SIZE];
+    struct qht htable;
     int nb_tbs;
     /* any access to the tbs or the page table must use this lock */
     QemuMutex tb_lock;
include/exec/tb-hash.h +1 -2
index 88ccfd1..1d0200b 100644
@@ -20,7 +20,6 @@
 #ifndef EXEC_TB_HASH
 #define EXEC_TB_HASH
 
-#include "exec/exec-all.h"
 #include "exec/tb-hash-xx.h"
 
 /* Only the bottom TB_JMP_PAGE_BITS of the jump cache hash bits vary for
@@ -49,7 +48,7 @@ static inline unsigned int tb_jmp_cache_hash_func(target_ulong pc)
 static inline
 uint32_t tb_hash_func(tb_page_addr_t phys_pc, target_ulong pc, uint32_t flags)
 {
-    return tb_hash_func5(phys_pc, pc, flags) & (CODE_GEN_PHYS_HASH_SIZE - 1);
+    return tb_hash_func5(phys_pc, pc, flags);
 }
 
 #endif
translate-all.c +38 -47
index d75737c..b620fcc 100644
@@ -735,6 +735,13 @@ static inline void code_gen_alloc(size_t tb_size)
     qemu_mutex_init(&tcg_ctx.tb_ctx.tb_lock);
 }
 
+static void tb_htable_init(void)
+{
+    unsigned int mode = QHT_MODE_AUTO_RESIZE;
+
+    qht_init(&tcg_ctx.tb_ctx.htable, CODE_GEN_HTABLE_SIZE, mode);
+}
+
 /* Must be called before using the QEMU cpus. 'tb_size' is the size
    (in bytes) allocated to the translation buffer. Zero means default
    size. */
@@ -742,6 +749,7 @@ void tcg_exec_init(unsigned long tb_size)
 {
     cpu_gen_init();
     page_init();
+    tb_htable_init();
     code_gen_alloc(tb_size);
 #if defined(CONFIG_SOFTMMU)
     /* There's no guest base to take into account, so go ahead and
@@ -846,7 +854,7 @@ void tb_flush(CPUState *cpu)
         cpu->tb_flushed = true;
     }
 
-    memset(tcg_ctx.tb_ctx.tb_phys_hash, 0, sizeof(tcg_ctx.tb_ctx.tb_phys_hash));
+    qht_reset_size(&tcg_ctx.tb_ctx.htable, CODE_GEN_HTABLE_SIZE);
     page_flush_tb();
 
     tcg_ctx.code_gen_ptr = tcg_ctx.code_gen_buffer;
@@ -857,60 +865,46 @@ void tb_flush(CPUState *cpu)
 
 #ifdef DEBUG_TB_CHECK
 
-static void tb_invalidate_check(target_ulong address)
+static void
+do_tb_invalidate_check(struct qht *ht, void *p, uint32_t hash, void *userp)
 {
-    TranslationBlock *tb;
-    int i;
+    TranslationBlock *tb = p;
+    target_ulong addr = *(target_ulong *)userp;
 
-    address &= TARGET_PAGE_MASK;
-    for (i = 0; i < CODE_GEN_PHYS_HASH_SIZE; i++) {
-        for (tb = tcg_ctx.tb_ctx.tb_phys_hash[i]; tb != NULL;
-             tb = tb->phys_hash_next) {
-            if (!(address + TARGET_PAGE_SIZE <= tb->pc ||
-                  address >= tb->pc + tb->size)) {
-                printf("ERROR invalidate: address=" TARGET_FMT_lx
-                       " PC=%08lx size=%04x\n",
-                       address, (long)tb->pc, tb->size);
-            }
-        }
+    if (!(addr + TARGET_PAGE_SIZE <= tb->pc || addr >= tb->pc + tb->size)) {
+        printf("ERROR invalidate: address=" TARGET_FMT_lx
+               " PC=%08lx size=%04x\n", addr, (long)tb->pc, tb->size);
     }
 }
 
-/* verify that all the pages have correct rights for code */
-static void tb_page_check(void)
+static void tb_invalidate_check(target_ulong address)
 {
-    TranslationBlock *tb;
-    int i, flags1, flags2;
-
-    for (i = 0; i < CODE_GEN_PHYS_HASH_SIZE; i++) {
-        for (tb = tcg_ctx.tb_ctx.tb_phys_hash[i]; tb != NULL;
-                tb = tb->phys_hash_next) {
-            flags1 = page_get_flags(tb->pc);
-            flags2 = page_get_flags(tb->pc + tb->size - 1);
-            if ((flags1 & PAGE_WRITE) || (flags2 & PAGE_WRITE)) {
-                printf("ERROR page flags: PC=%08lx size=%04x f1=%x f2=%x\n",
-                       (long)tb->pc, tb->size, flags1, flags2);
-            }
-        }
-    }
+    address &= TARGET_PAGE_MASK;
+    qht_iter(&tcg_ctx.tb_ctx.htable, do_tb_invalidate_check, &address);
 }
 
-#endif
-
-static inline void tb_hash_remove(TranslationBlock **ptb, TranslationBlock *tb)
+static void
+do_tb_page_check(struct qht *ht, void *p, uint32_t hash, void *userp)
 {
-    TranslationBlock *tb1;
+    TranslationBlock *tb = p;
+    int flags1, flags2;
 
-    for (;;) {
-        tb1 = *ptb;
-        if (tb1 == tb) {
-            *ptb = tb1->phys_hash_next;
-            break;
-        }
-        ptb = &tb1->phys_hash_next;
+    flags1 = page_get_flags(tb->pc);
+    flags2 = page_get_flags(tb->pc + tb->size - 1);
+    if ((flags1 & PAGE_WRITE) || (flags2 & PAGE_WRITE)) {
+        printf("ERROR page flags: PC=%08lx size=%04x f1=%x f2=%x\n",
+               (long)tb->pc, tb->size, flags1, flags2);
     }
 }
 
+/* verify that all the pages have correct rights for code */
+static void tb_page_check(void)
+{
+    qht_iter(&tcg_ctx.tb_ctx.htable, do_tb_page_check, NULL);
+}
+
+#endif
+
 static inline void tb_page_remove(TranslationBlock **ptb, TranslationBlock *tb)
 {
     TranslationBlock *tb1;
@@ -998,7 +992,7 @@ void tb_phys_invalidate(TranslationBlock *tb, tb_page_addr_t page_addr)
     /* remove the TB from the hash list */
     phys_pc = tb->page_addr[0] + (tb->pc & ~TARGET_PAGE_MASK);
     h = tb_hash_func(phys_pc, tb->pc, tb->flags);
-    tb_hash_remove(&tcg_ctx.tb_ctx.tb_phys_hash[h], tb);
+    qht_remove(&tcg_ctx.tb_ctx.htable, tb, h);
 
     /* remove the TB from the page list */
     if (tb->page_addr[0] != page_addr) {
@@ -1128,13 +1122,10 @@ static void tb_link_page(TranslationBlock *tb, tb_page_addr_t phys_pc,
                          tb_page_addr_t phys_page2)
 {
     uint32_t h;
-    TranslationBlock **ptb;
 
     /* add in the hash table */
     h = tb_hash_func(phys_pc, tb->pc, tb->flags);
-    ptb = &tcg_ctx.tb_ctx.tb_phys_hash[h];
-    tb->phys_hash_next = *ptb;
-    *ptb = tb;
+    qht_insert(&tcg_ctx.tb_ctx.htable, tb, h);
 
     /* add in the page list */
     tb_alloc_page(tb, 0, phys_pc & TARGET_PAGE_MASK);
#22 lore raw

PATCH 1/1 qht: support resetting an uninitialized qht

tb_flush() is called when debugging the guest (under both KVM and TCG accelerators) with gdb. tb_flush() resets TCG's qht, which segfaults if we're using KVM due to the qht not being initialized.

Fix this adding a magic number field to struct qht to track whether a qht has been initialized with qht_init(). Then, explicitly allow passing uninitialized qht's to qht_reset() and qht_reset_size(), just like we do with qht_statistics_init().

---
 include/qemu/qht.h |  7 +++++++
 tests/test-qht.c   |  3 +++
 util/qht.c         | 20 +++++++++++++++++---
 3 files changed, 27 insertions(+), 3 deletions(-)
include/qemu/qht.h +7 -0
index 311139b..39dd5e8 100644
@@ -15,6 +15,7 @@ struct qht {
     struct qht_map *map;
     QemuMutex lock; /* serializes setters of ht->map */
     unsigned int mode;
+    unsigned int magic;
 };
 
 /**
@@ -124,6 +125,8 @@ bool qht_remove(struct qht *ht, const void *p, uint32_t hash);
  * If concurrent readers may exist, the objects pointed to by the hash table
  * must remain valid for the existing RCU grace period -- see qht_remove().
  * See also: qht_reset_size()
+ *
+ * Note: it is OK to pass an uninitialized @ht.
  */
 void qht_reset(struct qht *ht);
 
@@ -138,6 +141,8 @@ void qht_reset(struct qht *ht);
  * If concurrent readers may exist, the objects pointed to by the hash table
  * must remain valid for the existing RCU grace period -- see qht_remove().
  * See also: qht_reset(), qht_resize().
+ *
+ * Note: it is OK to pass an uninitialized @ht.
  */
 bool qht_reset_size(struct qht *ht, size_t n_elems);
 
@@ -173,6 +178,8 @@ void qht_iter(struct qht *ht, qht_iter_func_t func, void *userp);
  *
  * When done with @stats, pass the struct to qht_statistics_destroy().
  * Failing to do this will leak memory.
+ *
+ * Note: it is OK to pass an uninitialized @ht.
  */
 void qht_statistics_init(struct qht *ht, struct qht_stats *stats);
 
tests/test-qht.c +3 -0
index 46a64b6..a923b2e 100644
@@ -97,6 +97,9 @@ static void qht_do_test(unsigned int mode, size_t init_entries)
 {
     /* under KVM we might fetch stats from an uninitialized qht */
     check_n(0);
+    /* resetting an uninitialized qht can happen as well, e.g. KVM + gdb */
+    qht_reset(&ht);
+    qht_reset_size(&ht, 0);
 
     qht_init(&ht, 0, mode);
 
util/qht.c +17 -3
index 16a8d79..e4c90d6 100644
@@ -89,6 +89,8 @@
 #define QHT_BUCKET_ENTRIES 4
 #endif
 
+#define QHT_MAGIC 0xbebec4fe
+
 /*
  * Note: reading partially-updated pointers in @pointers could lead to
  * segfaults. We thus access them with atomic_read/set; this guarantees
@@ -182,6 +184,11 @@ static inline void qht_map_debug__all_locked(struct qht_map *map)
 { }
 #endif /* QHT_DEBUG */
 
+static inline bool qht_inited(const struct qht *ht)
+{
+    return ht->magic == QHT_MAGIC;
+}
+
 static inline size_t qht_elems_to_buckets(size_t n_elems)
 {
     return pow2ceil(n_elems / QHT_BUCKET_ENTRIES);
@@ -356,6 +363,7 @@ void qht_init(struct qht *ht, size_t n_elems, unsigned int mode)
     size_t n_buckets = qht_elems_to_buckets(n_elems);
 
     ht->mode = mode;
+    ht->magic = QHT_MAGIC;
     qemu_mutex_init(&ht->lock);
     map = qht_map_create(n_buckets);
     atomic_rcu_set(&ht->map, map);
@@ -403,6 +411,10 @@ void qht_reset(struct qht *ht)
 {
     struct qht_map *map;
 
+    if (unlikely(!qht_inited(ht))) {
+        return;
+    }
+
     qht_map_lock_buckets__no_stale(ht, &map);
     qht_map_reset__all_locked(map);
     qht_map_unlock_buckets(map);
@@ -415,6 +427,9 @@ bool qht_reset_size(struct qht *ht, size_t n_elems)
     size_t n_buckets;
     bool resize = false;
 
+    if (unlikely(!qht_inited(ht))) {
+        return false;
+    }
     n_buckets = qht_elems_to_buckets(n_elems);
 
     qemu_mutex_lock(&ht->lock);
@@ -787,17 +802,16 @@ void qht_statistics_init(struct qht *ht, struct qht_stats *stats)
     struct qht_map *map;
     int i;
 
-    map = atomic_rcu_read(&ht->map);
-
     stats->used_head_buckets = 0;
     stats->entries = 0;
     qdist_init(&stats->chain);
     qdist_init(&stats->occupancy);
     /* bail out if the qht has not yet been initialized */
-    if (unlikely(map == NULL)) {
+    if (unlikely(!qht_inited(ht))) {
         stats->head_buckets = 0;
         return;
     }
+    map = atomic_rcu_read(&ht->map);
     stats->head_buckets = map->n_buckets;
 
     for (i = 0; i < map->n_buckets; i++) {
Signature · 1 line
2.5.0
#23 lore raw

Re: [Qemu-devel] [PATCH] qht: support resetting an uninitialized qht

On Wed, 10 Aug 2016 15:25:49 -0400
"Emilio G. Cota" <[email protected]> wrote:

Emilio,

Pls also see
https://www.mail-archive.com/[email protected]/msg391669.html
which fixed issue for me, I've CCed you.

Quoted 145 lines

tb_flush() is called when debugging the guest (under both KVM and TCG accelerators) with gdb. tb_flush() resets TCG's qht, which segfaults if we're using KVM due to the qht not being initialized.

Fix this adding a magic number field to struct qht to track whether a qht has been initialized with qht_init(). Then, explicitly allow passing uninitialized qht's to qht_reset() and qht_reset_size(), just like we do with qht_statistics_init().

---
 include/qemu/qht.h |  7 +++++++
 tests/test-qht.c   |  3 +++
 util/qht.c         | 20 +++++++++++++++++---
 3 files changed, 27 insertions(+), 3 deletions(-)
include/qemu/qht.h +7 -0
index 311139b..39dd5e8 100644
@@ -15,6 +15,7 @@ struct qht {
     struct qht_map *map;
     QemuMutex lock; /* serializes setters of ht->map */
     unsigned int mode;
+    unsigned int magic;
 };
 
 /**
@@ -124,6 +125,8 @@ bool qht_remove(struct qht *ht, const void *p, uint32_t hash);
  * If concurrent readers may exist, the objects pointed to by the hash table
  * must remain valid for the existing RCU grace period -- see qht_remove().
  * See also: qht_reset_size()
+ *
+ * Note: it is OK to pass an uninitialized @ht.
  */
 void qht_reset(struct qht *ht);
 
@@ -138,6 +141,8 @@ void qht_reset(struct qht *ht);
  * If concurrent readers may exist, the objects pointed to by the hash table
  * must remain valid for the existing RCU grace period -- see qht_remove().
  * See also: qht_reset(), qht_resize().
+ *
+ * Note: it is OK to pass an uninitialized @ht.
  */
 bool qht_reset_size(struct qht *ht, size_t n_elems);
 
@@ -173,6 +178,8 @@ void qht_iter(struct qht *ht, qht_iter_func_t func, void *userp);
  *
  * When done with @stats, pass the struct to qht_statistics_destroy().
  * Failing to do this will leak memory.
+ *
+ * Note: it is OK to pass an uninitialized @ht.
  */
 void qht_statistics_init(struct qht *ht, struct qht_stats *stats);
 
tests/test-qht.c +3 -0
index 46a64b6..a923b2e 100644
@@ -97,6 +97,9 @@ static void qht_do_test(unsigned int mode, size_t init_entries)
 {
     /* under KVM we might fetch stats from an uninitialized qht */
     check_n(0);
+    /* resetting an uninitialized qht can happen as well, e.g. KVM + gdb */
+    qht_reset(&ht);
+    qht_reset_size(&ht, 0);
 
     qht_init(&ht, 0, mode);
 
util/qht.c +17 -3
index 16a8d79..e4c90d6 100644
@@ -89,6 +89,8 @@
 #define QHT_BUCKET_ENTRIES 4
 #endif
 
+#define QHT_MAGIC 0xbebec4fe
+
 /*
  * Note: reading partially-updated pointers in @pointers could lead to
  * segfaults. We thus access them with atomic_read/set; this guarantees
@@ -182,6 +184,11 @@ static inline void qht_map_debug__all_locked(struct qht_map *map)
 { }
 #endif /* QHT_DEBUG */
 
+static inline bool qht_inited(const struct qht *ht)
+{
+    return ht->magic == QHT_MAGIC;
+}
+
 static inline size_t qht_elems_to_buckets(size_t n_elems)
 {
     return pow2ceil(n_elems / QHT_BUCKET_ENTRIES);
@@ -356,6 +363,7 @@ void qht_init(struct qht *ht, size_t n_elems, unsigned int mode)
     size_t n_buckets = qht_elems_to_buckets(n_elems);
 
     ht->mode = mode;
+    ht->magic = QHT_MAGIC;
     qemu_mutex_init(&ht->lock);
     map = qht_map_create(n_buckets);
     atomic_rcu_set(&ht->map, map);
@@ -403,6 +411,10 @@ void qht_reset(struct qht *ht)
 {
     struct qht_map *map;
 
+    if (unlikely(!qht_inited(ht))) {
+        return;
+    }
+
     qht_map_lock_buckets__no_stale(ht, &map);
     qht_map_reset__all_locked(map);
     qht_map_unlock_buckets(map);
@@ -415,6 +427,9 @@ bool qht_reset_size(struct qht *ht, size_t n_elems)
     size_t n_buckets;
     bool resize = false;
 
+    if (unlikely(!qht_inited(ht))) {
+        return false;
+    }
     n_buckets = qht_elems_to_buckets(n_elems);
 
     qemu_mutex_lock(&ht->lock);
@@ -787,17 +802,16 @@ void qht_statistics_init(struct qht *ht, struct qht_stats *stats)
     struct qht_map *map;
     int i;
 
-    map = atomic_rcu_read(&ht->map);
-
     stats->used_head_buckets = 0;
     stats->entries = 0;
     qdist_init(&stats->chain);
     qdist_init(&stats->occupancy);
     /* bail out if the qht has not yet been initialized */
-    if (unlikely(map == NULL)) {
+    if (unlikely(!qht_inited(ht))) {
         stats->head_buckets = 0;
         return;
     }
+    map = atomic_rcu_read(&ht->map);
     stats->head_buckets = map->n_buckets;
 
     for (i = 0; i < map->n_buckets; i++) {
#24 lore raw

[Qemu-devel] [PULL 12/15] qht: add qht-bench, a performance benchmark

In reply to Richard Henderson

From: "Emilio G. Cota" <[email protected]>

This serves as a performance benchmark as well as a stress test for QHT. We can tweak quite a number of things, including the number of resize threads and how frequently resizes are triggered.

A performance comparison of QHT vs CLHT[1] and ck_hs[2] using this same benchmark program can be found here:
http://imgur.com/a/0Bms4

The tests are run on a 64-core AMD Opteron 6376, pinning threads to cores favoring same-socket cores. For each run, qht-bench is invoked with:

  $ tests/qht-bench -d $duration -n $n -u $u -g $range
, where $duration is in seconds, $n is the number of threads,
$u is the update rate (0.0 to 100.0), and $range is the number
of keys.

Note that ck_hs's performance drops significantly as writes go up, since it requires an external lock (I used a ck_spinlock) around every write.

Also, note that CLHT instead of using a seqlock, relies on an allocator that does not ever return the same address during the same read-critical section. This gives it a slight performance advantage over QHT on read-heavy workloads, since the seqlock writes aren't there.

[1] CLHT: https://github.com/LPD-EPFL/CLHT

          https://infoscience.epfl.ch/record/207109/files/ascy_asplos15.pdf

[2] ck_hs: http://concurrencykit.org/

           http://backtrace.io/blog/blog/2015/03/13/workload-specialization/

A few of those plots are shown in text here, since that site might not be online forever. Throughput is on Mops/s on the Y axis.

                             200K keys, 0 % updates

450 ++--+------+------+-------+-------+-------+-------+------+-------+--++

      |   +      +      +       +       +       +       +      +      +N+  |
  400 ++                                                           ---+E+ ++
      |                                                       +++----      |
  350 ++          9 ++------+------++                       --+E+    -+H+ ++
      |             |      +H+-     |                 -+N+----   ---- +++  |
  300 ++          8 ++     +E+     ++             -----+E+  --+H+         ++
      |             |      +++      |         -+N+-----+H+--               |
  250 ++          7 ++------+------++  +++-----+E+----                    ++
  200 ++                    1         -+E+-----+H+                        ++
      |                           ----                     qht +-E--+      |
  150 ++                      -+E+                        clht +-H--+     ++
      |                   ----                              ck +-N--+      |
  100 ++               +E+                                                ++
      |            ----                                                    |
   50 ++       -+E+                                                       ++
      |   +E+E+  +      +       +       +       +       +      +       +   |
    0 ++--E------+------+-------+-------+-------+-------+------+-------+--++
          1      8      16      24      32      40      48     56      64
                                Number of threads

                             200K keys, 1 % updates

350 ++--+------+------+-------+-------+-------+-------+------+-------+--++

      |   +      +      +       +       +       +       +      +     -+E+  |
  300 ++                                                         -----+H+ ++
      |                                                       +E+--        |
      |           9 ++------+------++                  +++----             |
  250 ++            |      +E+   -- |                 -+E+                ++
      |           8 ++         --  ++             ----                     |
  200 ++            |      +++-     |  +++  ---+E+                        ++
      |           7 ++------N------++ -+E+--               qht +-E--+      |
      |                     1  +++----                    clht +-H--+      |
  150 ++                      -+E+                          ck +-N--+     ++
      |                   ----                                             |
  100 ++               +E+                                                ++
      |            ----                                                    |
      |        -+E+                                                        |
   50 ++    +H+-+N+----+N+-----+N+------                                  ++
      |   +E+E+  +      +       +      +N+-----+N+-----+N+----+N+-----+N+  |
    0 ++--E------+------+-------+-------+-------+-------+------+-------+--++
          1      8      16      24      32      40      48     56      64
                                Number of threads

                             200K keys, 20 % updates

300 ++--+------+------+-------+-------+-------+-------+------+-------+--++

      |   +      +      +       +       +       +       +      +       +   |
      |                                                              -+H+  |
  250 ++                                                         ----     ++
      |           9 ++------+------++                       --+H+  ---+E+  |
      |           8 ++     +H+--   ++                 -+H+----+E+--        |
  200 ++            |      +E+    --|             -----+E+--  +++         ++
      |           7 ++      + ---- ++       ---+H+---- +++ qht +-E--+      |
  150 ++          6 ++------N------++ -+H+-----+E+        clht +-H--+     ++
      |                     1     -----+E+--                ck +-N--+      |
      |                       -+H+----                                     |
  100 ++                  -----+E+                                        ++
      |                +E+--                                               |
      |            ----+++                                                 |
   50 ++       -+E+                                                       ++
      |     +E+ +++                                                        |
      |   +E+N+-+N+-----+       +       +       +       +      +       +   |
    0 ++--E------+------N-------N-------N-------N-------N------N-------N--++
          1      8      16      24      32      40      48     56      64
                                Number of threads

                            200K keys, 100 % updates       qht +-E--+
                                                          clht +-H--+
  160 ++--+------+------+-------+-------+-------+-------+---ck-+-N-----+--++
      |   +      +      +       +       +       +       +      +   ----H   |
  140 ++                                                      +H+--  -+E+ ++
      |                                                +++----   ----      |
  120 ++          8 ++------+------++                 -+H+    +E+         ++
      |           7 ++     +H+---- ++             ---- +++----             |
  100 ++            |      +E+      |  +++  ---+H+    -+E+                ++
      |           6 ++     +++     ++ -+H+--   +++----                     |
   80 ++          5 ++------N----------+E+-----+E+                        ++
      |                     1 -+H+---- +++                                 |
      |                   -----+E+                                         |
   60 ++               +H+---- +++                                        ++
      |            ----+E+                                                 |
   40 ++        +H+----                                                   ++
      |       --+E+                                                        |
   20 ++    +E+                                                           ++
      |  +EE+    +      +       +       +       +       +      +       +   |
    0 ++--+N-N---N------N-------N-------N-------N-------N------N-------N--++
          1      8      16      24      32      40      48     56      64
                                Number of threads

Message-Id: <[email protected]>

---
 tests/.gitignore       |   1 +
 tests/Makefile.include |   3 +-
 tests/qht-bench.c      | 488 +++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 491 insertions(+), 1 deletion(-)
 create mode 100644 tests/qht-bench.c
tests/.gitignore +1 -0
index ffde5d2..d19023e 100644
@@ -7,6 +7,7 @@ check-qnull
 check-qstring
 check-qom-interface
 check-qom-proplist
+qht-bench
 rcutorture
 test-aio
 test-base64
tests/Makefile.include +2 -1
index 429d384..7b00301 100644
@@ -400,7 +400,7 @@ test-obj-y = tests/check-qint.o tests/check-qstring.o tests/check-qdict.o \
 	tests/test-opts-visitor.o tests/test-qmp-event.o \
 	tests/rcutorture.o tests/test-rcu-list.o \
 	tests/test-qdist.o \
-	tests/test-qht.o
+	tests/test-qht.o tests/qht-bench.o
 
 $(test-obj-y): QEMU_INCLUDES += -Itests
 QEMU_CFLAGS += -I$(SRC_PATH)/tests
@@ -441,6 +441,7 @@ tests/rcutorture$(EXESUF): tests/rcutorture.o $(test-util-obj-y)
 tests/test-rcu-list$(EXESUF): tests/test-rcu-list.o $(test-util-obj-y)
 tests/test-qdist$(EXESUF): tests/test-qdist.o $(test-util-obj-y)
 tests/test-qht$(EXESUF): tests/test-qht.o $(test-util-obj-y)
+tests/qht-bench$(EXESUF): tests/qht-bench.o $(test-util-obj-y)
 
 tests/test-qdev-global-props$(EXESUF): tests/test-qdev-global-props.o \
 	hw/core/qdev.o hw/core/qdev-properties.o hw/core/hotplug.o\
tests/qht-bench.c new file +488 -0

488 lines not on this page · raw message

Signature · 1 line
2.5.5
#25 lore raw
In reply to Richard Henderson
Quoted 12 lines · Richard Henderson

We're all good to go with v7.

r~

The following changes since commit 0c33682d5f29b0a4ae53bdec4c8e52e4fae37b34:

target-i386: Move user-mode exception actions out of user-exec.c (2016-06-09 15:55:02 +0100)

are available in the git repository at:

Quoted 8 lines

git://github.com/rth7680/qemu.git tags/pull-tcg-20160610

for you to fetch changes up to 9b1b8e78a5a8c849f5ca800d71497dc88a338483:

translate-all: add tb hash bucket info to 'info jit' dump (2016-06-10 07:21:54 -0700)

----------------------------------------------------------------
TB hashing improvements

Fails to build on ppc64be :-(

In file included from /home/pm215/qemu/include/qemu/thread.h:4:0,

                 from /home/pm215/qemu/include/block/aio.h:20,
                 from /home/pm215/qemu/include/block/block.h:4,
                 from /home/pm215/qemu/include/monitor/monitor.h:6,
                 from /home/pm215/qemu/trace/control.c:23:
/home/pm215/qemu/include/qemu/processor.h:24:35: error: expected
identifier or ‘(’ before string constant
                                   "or 2, 2, 2;" ::: "memory")
                                   ^
In file included from /home/pm215/qemu/include/block/aio.h:20:0,
                 from /home/pm215/qemu/include/block/block.h:4,
                 from /home/pm215/qemu/include/monitor/monitor.h:6,
                 from /home/pm215/qemu/trace/control.c:23:
/home/pm215/qemu/include/qemu/thread.h:22:22: error: unknown type name
‘QemuMutex’
 void qemu_mutex_init(QemuMutex *mutex);
                      ^
/home/pm215/qemu/include/qemu/thread.h:23:25: error: unknown type name
‘QemuMutex’
 void qemu_mutex_destroy(QemuMutex *mutex);
                         ^
/home/pm215/qemu/include/qemu/thread.h:24:22: error: unknown type name
‘QemuMutex’
 void qemu_mutex_lock(QemuMutex *mutex);
                      ^
/home/pm215/qemu/include/qemu/thread.h:25:24: error: unknown type name
‘QemuMutex’
 int qemu_mutex_trylock(QemuMutex *mutex);
                        ^
/home/pm215/qemu/include/qemu/thread.h:26:24: error: unknown type name
‘QemuMutex’
 void qemu_mutex_unlock(QemuMutex *mutex);
                        ^
/home/pm215/qemu/include/qemu/thread.h:38:37: error: unknown type name
‘QemuMutex’
 void qemu_cond_wait(QemuCond *cond, QemuMutex *mutex);
                                     ^
/home/pm215/qemu/include/qemu/thread.h: In function ‘qemu_spin_lock’:
/home/pm215/qemu/include/qemu/thread.h:78:24: error: expected ‘:’ or
‘)’ before ‘;’ token
             cpu_relax();
                        ^

(and some more errors that I think are just run-on from those).

thanks
-- PMM

#26 lore raw
Quoted 15 lines · Peter Maydell
Quoted 14 lines · Richard Henderson

We're all good to go with v7.

r~

The following changes since commit 0c33682d5f29b0a4ae53bdec4c8e52e4fae37b34:

target-i386: Move user-mode exception actions out of user-exec.c (2016-06-09 15:55:02 +0100)

are available in the git repository at:

git://github.com/rth7680/qemu.git tags/pull-tcg-20160610

Quoted 8 lines
Quoted 6 lines

for you to fetch changes up to 9b1b8e78a5a8c849f5ca800d71497dc88a338483:

translate-all: add tb hash bucket info to 'info jit' dump (2016-06-10 07:21:54 -0700)

----------------------------------------------------------------
TB hashing improvements

Fails to build on ppc64be :-(

Also fails trying to build a test on 32-bit:

/home/petmay01/qemu/tests/qht-bench.c: In function 'pr_params':
/home/petmay01/qemu/tests/qht-bench.c:270:5: error: format '%zu' expects argument of type 'size_t', but argument 2 has type 'long unsigned int' [-Werror=format=]

     printf(" lookup range:      %zu\n", lookup_range);
     ^
/home/petmay01/qemu/tests/qht-bench.c:271:5: error: format '%zu'
expects argument of type 'size_t', but argument 2 has type 'long
unsigned int' [-Werror=format=]
     printf(" update range:      %zu\n", update_range);
     ^

cc1: all warnings being treated as errors

thanks
-- PMM

#27 lore raw
Quoted 10 lines · Peter Maydell

Fails to build on ppc64be :-(

In file included from /home/pm215/qemu/include/qemu/thread.h:4:0,

                 from /home/pm215/qemu/include/block/aio.h:20,
                 from /home/pm215/qemu/include/block/block.h:4,
                 from /home/pm215/qemu/include/monitor/monitor.h:6,
                 from /home/pm215/qemu/trace/control.c:23:
/home/pm215/qemu/include/qemu/processor.h:24:35: error: expected
identifier or ‘(’ before string constant
                                   "or 2, 2, 2;" ::: "memory")
Quoted 7 lines · Peter Maydell

Also fails trying to build a test on 32-bit:

/home/petmay01/qemu/tests/qht-bench.c: In function 'pr_params':
/home/petmay01/qemu/tests/qht-bench.c:270:5: error: format '%zu' expects argument of type 'size_t', but argument 2 has type 'long unsigned int' [-Werror=format=]

     printf(" lookup range:      %zu\n", lookup_range);

Can you please test again after applying the appended delta?

Thanks,

Emilio

include/qemu/processor.h +6 -2
index 42bcc99..c28d7e3 100644
@@ -20,8 +20,12 @@
 
 #elif defined(__powerpc64__)
 /* set Hardware Multi-Threading (HMT) priority to low; then back to medium */
-# define cpu_relax() asm volatile("or 1, 1, 1;"
-                                  "or 2, 2, 2;" ::: "memory")
+# define cpu_relax()                            \
+    do {                                        \
+        asm volatile("or 1,1,1");               \
+        asm volatile("or 2,2,2");               \
+        barrier();                              \
+    } while (0)
 
 #else
 # define cpu_relax() barrier()
tests/qht-bench.c +2 -2
index c7f73b4..ad8efbc 100644
@@ -267,8 +267,8 @@ static void pr_params(void)
     printf(" update rate:       %f%%\n", update_rate * 100.0);
     printf(" offset:            %ld\n", populate_offset);
     printf(" initial key range: %zu\n", init_range);
-    printf(" lookup range:      %zu\n", lookup_range);
-    printf(" update range:      %zu\n", update_range);
+    printf(" lookup range:      %lu\n", lookup_range);
+    printf(" update range:      %lu\n", update_range);
 }
 
 static void do_threshold(double rate, uint64_t *threshold)
#28 lore raw
Quoted 15 lines · Emilio G. Cota
Quoted 10 lines · Peter Maydell

Fails to build on ppc64be :-(

In file included from /home/pm215/qemu/include/qemu/thread.h:4:0,

                 from /home/pm215/qemu/include/block/aio.h:20,
                 from /home/pm215/qemu/include/block/block.h:4,
                 from /home/pm215/qemu/include/monitor/monitor.h:6,
                 from /home/pm215/qemu/trace/control.c:23:
/home/pm215/qemu/include/qemu/processor.h:24:35: error: expected
identifier or ‘(’ before string constant
                                   "or 2, 2, 2;" ::: "memory")
Quoted 2 lines · Peter Maydell

Also fails trying to build a test on 32-bit:

Quoted 7 lines
Quoted 5 lines

/home/petmay01/qemu/tests/qht-bench.c: In function 'pr_params':
/home/petmay01/qemu/tests/qht-bench.c:270:5: error: format '%zu' expects argument of type 'size_t', but argument 2 has type 'long unsigned int' [-Werror=format=]

     printf(" lookup range:      %zu\n", lookup_range);

Can you please test again after applying the appended delta?

I will test.

For the PPC asm, is it not just wanting the "\n" between instructions? Shouldn't be necessary to use two separate asm() lines...

thanks
-- PMM

#29 lore raw
Quoted 22 lines · Peter Maydell
Quoted 21 lines · Emilio G. Cota
Quoted 10 lines · Peter Maydell

Fails to build on ppc64be :-(

In file included from /home/pm215/qemu/include/qemu/thread.h:4:0,

                 from /home/pm215/qemu/include/block/aio.h:20,
                 from /home/pm215/qemu/include/block/block.h:4,
                 from /home/pm215/qemu/include/monitor/monitor.h:6,
                 from /home/pm215/qemu/trace/control.c:23:
/home/pm215/qemu/include/qemu/processor.h:24:35: error: expected
identifier or ‘(’ before string constant
                                   "or 2, 2, 2;" ::: "memory")
Quoted 7 lines · Peter Maydell

Also fails trying to build a test on 32-bit:

/home/petmay01/qemu/tests/qht-bench.c: In function 'pr_params':
/home/petmay01/qemu/tests/qht-bench.c:270:5: error: format '%zu' expects argument of type 'size_t', but argument 2 has type 'long unsigned int' [-Werror=format=]

     printf(" lookup range:      %zu\n", lookup_range);
Quoted 6 lines
Quoted 1 line

Can you please test again after applying the appended delta?

I will test.

For the PPC asm, is it not just wanting the "\n" between instructions? Shouldn't be necessary to use two separate asm() lines...

I can't test on ppc so I was just being paranoid to avoid wasting your time :-)

		E.
#30 lore raw
In reply to Peter Maydell
Quoted 22 lines · Peter Maydell
Quoted 21 lines · Emilio G. Cota
Quoted 10 lines · Peter Maydell

Fails to build on ppc64be :-(

In file included from /home/pm215/qemu/include/qemu/thread.h:4:0,

                 from /home/pm215/qemu/include/block/aio.h:20,
                 from /home/pm215/qemu/include/block/block.h:4,
                 from /home/pm215/qemu/include/monitor/monitor.h:6,
                 from /home/pm215/qemu/trace/control.c:23:
/home/pm215/qemu/include/qemu/processor.h:24:35: error: expected
identifier or ‘(’ before string constant
                                   "or 2, 2, 2;" ::: "memory")
Quoted 7 lines · Peter Maydell

Also fails trying to build a test on 32-bit:

/home/petmay01/qemu/tests/qht-bench.c: In function 'pr_params':
/home/petmay01/qemu/tests/qht-bench.c:270:5: error: format '%zu' expects argument of type 'size_t', but argument 2 has type 'long unsigned int' [-Werror=format=]

     printf(" lookup range:      %zu\n", lookup_range);
Quoted 6 lines
Quoted 1 line

Can you please test again after applying the appended delta?

I will test.

For the PPC asm, is it not just wanting the "\n" between instructions? Shouldn't be necessary to use two separate asm() lines...

It has a ; between instructions. That's not the problem.

What it needs is a \ to continue the macro to the second line.

I've just finished a build on ppc64 with that one character fix.

r~