Skip to contentSkip to conversation

fix for #285

PATCH Applied Emilio Cota 4 participants 9 messages Feb 5, 2023 – Mar 21, 2023 Arm/Amlogic Meson SoC support

lore
Share & tools
lore
#0 lore raw

v2 cover fix for #285

Changes since v1:

- Add configure check to only use QTree if Glib still implements gslice. If Glib doesn't, then we call Glib directly with inline functions.
- Add TODO's so that in the future (i.e. when the minimum version of Glib that we use doesn't implement gslice) we remove QTree.
- Add comment to the top of qtree.h.
- Make qtree-bench results more robust by running longer or more times.
- Drop deprecated API calls (they're unused in QEMU).
- Drop API calls that are too recent (they're unused in QEMU).
- Drop macro benchmark results from the TCG patch since they're too noisy.
- Add test program to the commit log so that we don't lose it in the future even if the bug tracker goes away.

Thanks,
Emilio

#1 lore raw

PATCH v2 1/2 util: import GTree as QTree

The only reason to add this implementation is to control the memory allocator used. Some users (e.g. TCG) cannot work reliably in multi-threaded environments (e.g. forking in user-mode) with GTree's allocator, GSlice. See https://gitlab.com/qemu-project/qemu/-/issues/285 for details.

Importing GTree is a temporary workaround until GTree migrates away from GSlice.

This implementation is identical to that in glib v2.75.0, except that we don't import recent additions to the API nor deprecated API calls, none of which are used in QEMU.

I've imported tests from glib and added a benchmark just to make sure that performance is similar. Note: it cannot be identical because (1) we are not using GSlice, (2) we use different compilation flags (e.g. -fPIC) and (3) we're linking statically.

$ cat /proc/cpuinfo| grep 'model name' | head -1
model name      : AMD Ryzen 7 PRO 5850U with Radeon Graphics
$ echo '0' | sudo tee /sys/devices/system/cpu/cpufreq/boost
$ tests/bench/qtree-bench

Tree Op 32 1024 4096 131072 1048576
------------------------------------------------------------------------------------------------

GTree     Lookup   83.23           43.08           25.31           19.40           16.22
QTree     Lookup  113.42 (1.36x)   53.83 (1.25x)   28.38 (1.12x)   17.64 (0.91x)   13.04 (0.80x)
GTree     Insert   44.23           29.37           25.83           19.49           17.03
QTree     Insert   46.87 (1.06x)   25.62 (0.87x)   24.29 (0.94x)   16.83 (0.86x)   12.97 (0.76x)
GTree     Remove   53.27           35.15           31.43           24.64           16.70
QTree     Remove   57.32 (1.08x)   41.76 (1.19x)   38.37 (1.22x)   29.30 (1.19x)   15.07 (0.90x)
GTree  RemoveAll  135.44          127.52          126.72          120.11           64.34
QTree  RemoveAll  127.15 (0.94x)  110.37 (0.87x)  107.97 (0.85x)   97.13 (0.81x)   55.10 (0.86x)
GTree   Traverse  277.71          276.09          272.78          246.72           98.47
QTree   Traverse  370.33 (1.33x)  411.97 (1.49x)  400.23 (1.47x)  262.82 (1.07x)   78.52 (0.80x)

------------------------------------------------------------------------------------------------

As a sanity check, the same benchmark when Glib's version is >= $glib_dropped_gslice_version (i.e. QTree == GTree):

Tree Op 32 1024 4096 131072 1048576
------------------------------------------------------------------------------------------------

GTree     Lookup   82.72           43.09           24.18           19.73           16.09
QTree     Lookup   81.82 (0.99x)   43.10 (1.00x)   24.20 (1.00x)   19.76 (1.00x)   16.26 (1.01x)
GTree     Insert   45.07           29.62           26.34           19.90           17.18
QTree     Insert   45.72 (1.01x)   29.60 (1.00x)   26.38 (1.00x)   19.71 (0.99x)   17.20 (1.00x)
GTree     Remove   54.48           35.36           31.77           24.97           16.95
QTree     Remove   54.46 (1.00x)   35.32 (1.00x)   31.77 (1.00x)   24.91 (1.00x)   17.15 (1.01x)
GTree  RemoveAll  140.68          127.36          125.43          121.45           68.20
QTree  RemoveAll  140.65 (1.00x)  127.64 (1.00x)  125.01 (1.00x)  121.73 (1.00x)   67.06 (0.98x)
GTree   Traverse  278.68          276.05          266.75          251.65          104.93
QTree   Traverse  278.31 (1.00x)  275.78 (1.00x)  266.42 (1.00x)  247.89 (0.99x)  104.58 (1.00x)

------------------------------------------------------------------------------------------------

Related: #285

---
 configure                 |   15 +
 include/qemu/qtree.h      |  201 ++++++
 meson.build               |    4 +
 tests/bench/meson.build   |    4 +
 tests/bench/qtree-bench.c |  286 ++++++++
 tests/unit/meson.build    |    1 +
 tests/unit/test-qtree.c   |  333 +++++++++
 util/meson.build          |    1 +
 util/qtree.c              | 1390 +++++++++++++++++++++++++++++++++++++
 9 files changed, 2235 insertions(+)
 create mode 100644 include/qemu/qtree.h
 create mode 100644 tests/bench/qtree-bench.c
 create mode 100644 tests/unit/test-qtree.c
 create mode 100644 util/qtree.c
configure +15 -0
index 64960c6000..8fe3d643c8 100755
@@ -226,6 +226,7 @@ stack_protector=""
 safe_stack=""
 use_containers="yes"
 gdb_bin=$(command -v "gdb-multiarch" || command -v "gdb")
+glib_has_gslice="no"
 
 if test -e "$source_path/.git"
 then
@@ -1456,6 +1457,17 @@ for i in $glib_modules; do
     fi
 done
 
+# Check whether glib has gslice, which we have to avoid for correctness.
+# TODO: remove this check and the corresponding workaround (qtree) when
+# the minimum supported glib is >= $glib_dropped_gslice_version.
+glib_dropped_gslice_version=2.75.3
+for i in $glib_modules; do
+    if ! $pkg_config --atleast-version=$glib_dropped_gslice_version $i; then
+        glib_has_gslice="yes"
+	break
+    fi
+done
+
 glib_bindir="$($pkg_config --variable=bindir glib-2.0)"
 if test -z "$glib_bindir" ; then
 	glib_bindir="$($pkg_config --variable=prefix glib-2.0)"/bin
@@ -2377,6 +2389,9 @@ echo "GLIB_CFLAGS=$glib_cflags" >> $config_host_mak
 echo "GLIB_LIBS=$glib_libs" >> $config_host_mak
 echo "GLIB_BINDIR=$glib_bindir" >> $config_host_mak
 echo "GLIB_VERSION=$($pkg_config --modversion glib-2.0)" >> $config_host_mak
+if test "$glib_has_gslice" = "yes" ; then
+    echo "HAVE_GLIB_WITH_SLICE_ALLOCATOR=y" >> $config_host_mak
+fi
 echo "QEMU_LDFLAGS=$QEMU_LDFLAGS" >> $config_host_mak
 echo "EXESUF=$EXESUF" >> $config_host_mak
 
include/qemu/qtree.h new file +201 -0

201 lines not on this page · raw message

meson.build +4 -0
index 4ba3bf3431..60676271dd 100644
@@ -512,6 +512,10 @@ glib = declare_dependency(compile_args: config_host['GLIB_CFLAGS'].split(),
                           })
 # override glib dep with the configure results (for subprojects)
 meson.override_dependency('glib-2.0', glib)
+# pass down whether Glib has the slice allocator
+if config_host.has_key('HAVE_GLIB_WITH_SLICE_ALLOCATOR')
+  config_host_data.set('HAVE_GLIB_WITH_SLICE_ALLOCATOR', true)
+endif
 
 gio = not_found
 gdbus_codegen = not_found
tests/bench/meson.build +4 -0
index 279a8fcc33..3c799dbd98 100644
@@ -3,6 +3,10 @@ qht_bench = executable('qht-bench',
                        sources: 'qht-bench.c',
                        dependencies: [qemuutil])
 
+qtree_bench = executable('qtree-bench',
+                         sources: 'qtree-bench.c',
+                         dependencies: [qemuutil])
+
 executable('atomic_add-bench',
            sources: files('atomic_add-bench.c'),
            dependencies: [qemuutil],
tests/bench/qtree-bench.c new file +286 -0

286 lines not on this page · raw message

tests/unit/meson.build +1 -0
index ffa444f432..a723ab757e 100644
@@ -35,6 +35,7 @@ tests = {
   'test-rcu-slist': [],
   'test-qdist': [],
   'test-qht': [],
+  'test-qtree': [],
   'test-bitops': [],
   'test-bitcnt': [],
   'test-qgraph': ['../qtest/libqos/qgraph.c'],
tests/unit/test-qtree.c new file +333 -0

333 lines not on this page · raw message

util/meson.build +1 -0
index 26c73e586b..3c2cfc6ede 100644
@@ -26,6 +26,7 @@ util_ss.add(when: 'CONFIG_WIN32', if_true: files('oslib-win32.c'))
 util_ss.add(when: 'CONFIG_WIN32', if_true: files('qemu-thread-win32.c'))
 util_ss.add(when: 'CONFIG_WIN32', if_true: winmm)
 util_ss.add(when: 'CONFIG_WIN32', if_true: pathcch)
+util_ss.add(when: 'HAVE_GLIB_WITH_SLICE_ALLOCATOR', if_true: files('qtree.c'))
 util_ss.add(files('envlist.c', 'path.c', 'module.c'))
 util_ss.add(files('host-utils.c'))
 util_ss.add(files('bitmap.c', 'bitops.c'))
util/qtree.c new file +1390 -0

1,390 lines not on this page · raw message

Signature · 1 line
2.34.1
#2 lore raw

PATCH v2 2/2 tcg: use QTree instead of GTree

In reply to Emilio Cota

qemu-user can hang in a multi-threaded fork. One common reason is that when creating a TB, between fork and exec we manipulate a GTree whose memory allocator (GSlice) is not fork-safe.

Although POSIX does not mandate it, the system's allocator (e.g. tcmalloc, libc malloc) is probably fork-safe.

Fix some of these hangs by using QTree, which uses the system's allocator regardless of the Glib version that we used at configuration time.

Tested with the test program in the original bug report, i.e.:

```

void garble() {
  int pid = fork();
  if (pid == 0) {
    exit(0);
  } else {
    int wstatus;
    waitpid(pid, &wstatus, 0);
  }
}

void supragarble(unsigned depth) {
  if (depth == 0)
    return ;

  std::thread a(supragarble, depth-1);
  std::thread b(supragarble, depth-1);
  garble();
  a.join();
  b.join();
}

int main() {
  supragarble(10);
}
```
Fixes #285
---
 accel/tcg/tb-maint.c | 17 +++++++++--------
 tcg/region.c         | 19 ++++++++++---------
 2 files changed, 19 insertions(+), 17 deletions(-)
accel/tcg/tb-maint.c +9 -8
index b3d6529ae2..e6370ddc71 100644
@@ -19,6 +19,7 @@
 
 #include "qemu/osdep.h"
 #include "qemu/interval-tree.h"
+#include "qemu/qtree.h"
 #include "exec/cputlb.h"
 #include "exec/log.h"
 #include "exec/exec-all.h"
@@ -313,7 +314,7 @@ struct page_entry {
  * See also: page_collection_lock().
  */
 struct page_collection {
-    GTree *tree;
+    QTree *tree;
     struct page_entry *max;
 };
 
@@ -466,7 +467,7 @@ static bool page_trylock_add(struct page_collection *set, tb_page_addr_t addr)
     struct page_entry *pe;
     PageDesc *pd;
 
-    pe = g_tree_lookup(set->tree, &index);
+    pe = q_tree_lookup(set->tree, &index);
     if (pe) {
         return false;
     }
@@ -477,7 +478,7 @@ static bool page_trylock_add(struct page_collection *set, tb_page_addr_t addr)
     }
 
     pe = page_entry_new(pd, index);
-    g_tree_insert(set->tree, &pe->index, pe);
+    q_tree_insert(set->tree, &pe->index, pe);
 
     /*
      * If this is either (1) the first insertion or (2) a page whose index
@@ -524,13 +525,13 @@ static struct page_collection *page_collection_lock(tb_page_addr_t start,
     end   >>= TARGET_PAGE_BITS;
     g_assert(start <= end);
 
-    set->tree = g_tree_new_full(tb_page_addr_cmp, NULL, NULL,
+    set->tree = q_tree_new_full(tb_page_addr_cmp, NULL, NULL,
                                 page_entry_destroy);
     set->max = NULL;
     assert_no_pages_locked();
 
  retry:
-    g_tree_foreach(set->tree, page_entry_lock, NULL);
+    q_tree_foreach(set->tree, page_entry_lock, NULL);
 
     for (index = start; index <= end; index++) {
         TranslationBlock *tb;
@@ -541,7 +542,7 @@ static struct page_collection *page_collection_lock(tb_page_addr_t start,
             continue;
         }
         if (page_trylock_add(set, index << TARGET_PAGE_BITS)) {
-            g_tree_foreach(set->tree, page_entry_unlock, NULL);
+            q_tree_foreach(set->tree, page_entry_unlock, NULL);
             goto retry;
         }
         assert_page_locked(pd);
@@ -550,7 +551,7 @@ static struct page_collection *page_collection_lock(tb_page_addr_t start,
                 (tb_page_addr1(tb) != -1 &&
                  page_trylock_add(set, tb_page_addr1(tb)))) {
                 /* drop all locks, and reacquire in order */
-                g_tree_foreach(set->tree, page_entry_unlock, NULL);
+                q_tree_foreach(set->tree, page_entry_unlock, NULL);
                 goto retry;
             }
         }
@@ -561,7 +562,7 @@ static struct page_collection *page_collection_lock(tb_page_addr_t start,
 static void page_collection_unlock(struct page_collection *set)
 {
     /* entries are unlocked and freed via page_entry_destroy */
-    g_tree_destroy(set->tree);
+    q_tree_destroy(set->tree);
     g_free(set);
 }
 
tcg/region.c +10 -9
index 88d6bb273f..bef4c4756f 100644
@@ -28,6 +28,7 @@
 #include "qemu/mprotect.h"
 #include "qemu/memalign.h"
 #include "qemu/cacheinfo.h"
+#include "qemu/qtree.h"
 #include "qapi/error.h"
 #include "exec/exec-all.h"
 #include "tcg/tcg.h"
@@ -36,7 +37,7 @@
 
 struct tcg_region_tree {
     QemuMutex lock;
-    GTree *tree;
+    QTree *tree;
     /* padding to avoid false sharing is computed at run-time */
 };
 
@@ -163,7 +164,7 @@ static void tcg_region_trees_init(void)
         struct tcg_region_tree *rt = region_trees + i * tree_size;
 
         qemu_mutex_init(&rt->lock);
-        rt->tree = g_tree_new_full(tb_tc_cmp, NULL, NULL, tb_destroy);
+        rt->tree = q_tree_new_full(tb_tc_cmp, NULL, NULL, tb_destroy);
     }
 }
 
@@ -202,7 +203,7 @@ void tcg_tb_insert(TranslationBlock *tb)
 
     g_assert(rt != NULL);
     qemu_mutex_lock(&rt->lock);
-    g_tree_insert(rt->tree, &tb->tc, tb);
+    q_tree_insert(rt->tree, &tb->tc, tb);
     qemu_mutex_unlock(&rt->lock);
 }
 
@@ -212,7 +213,7 @@ void tcg_tb_remove(TranslationBlock *tb)
 
     g_assert(rt != NULL);
     qemu_mutex_lock(&rt->lock);
-    g_tree_remove(rt->tree, &tb->tc);
+    q_tree_remove(rt->tree, &tb->tc);
     qemu_mutex_unlock(&rt->lock);
 }
 
@@ -232,7 +233,7 @@ TranslationBlock *tcg_tb_lookup(uintptr_t tc_ptr)
     }
 
     qemu_mutex_lock(&rt->lock);
-    tb = g_tree_lookup(rt->tree, &s);
+    tb = q_tree_lookup(rt->tree, &s);
     qemu_mutex_unlock(&rt->lock);
     return tb;
 }
@@ -267,7 +268,7 @@ void tcg_tb_foreach(GTraverseFunc func, gpointer user_data)
     for (i = 0; i < region.n; i++) {
         struct tcg_region_tree *rt = region_trees + i * tree_size;
 
-        g_tree_foreach(rt->tree, func, user_data);
+        q_tree_foreach(rt->tree, func, user_data);
     }
     tcg_region_tree_unlock_all();
 }
@@ -281,7 +282,7 @@ size_t tcg_nb_tbs(void)
     for (i = 0; i < region.n; i++) {
         struct tcg_region_tree *rt = region_trees + i * tree_size;
 
-        nb_tbs += g_tree_nnodes(rt->tree);
+        nb_tbs += q_tree_nnodes(rt->tree);
     }
     tcg_region_tree_unlock_all();
     return nb_tbs;
@@ -296,8 +297,8 @@ static void tcg_region_tree_reset_all(void)
         struct tcg_region_tree *rt = region_trees + i * tree_size;
 
         /* Increment the refcount first so that destroy acts as a reset */
-        g_tree_ref(rt->tree);
-        g_tree_destroy(rt->tree);
+        q_tree_ref(rt->tree);
+        q_tree_destroy(rt->tree);
     }
     tcg_region_tree_unlock_all();
 }
Signature · 1 line
2.34.1
Reviewed-by on v2 2/2
#3 lore raw

Re: [PATCH v2 2/2] tcg: use QTree instead of GTree

Quoted 41 lines · Emilio Cota

qemu-user can hang in a multi-threaded fork. One common reason is that when creating a TB, between fork and exec we manipulate a GTree whose memory allocator (GSlice) is not fork-safe.

Although POSIX does not mandate it, the system's allocator (e.g. tcmalloc, libc malloc) is probably fork-safe.

Fix some of these hangs by using QTree, which uses the system's allocator regardless of the Glib version that we used at configuration time.

Tested with the test program in the original bug report, i.e.:

```

void garble() {
   int pid = fork();
   if (pid == 0) {
     exit(0);
   } else {
     int wstatus;
     waitpid(pid, &wstatus, 0);
   }
}

void supragarble(unsigned depth) {
   if (depth == 0)
     return ;

   std::thread a(supragarble, depth-1);
   std::thread b(supragarble, depth-1);
   garble();
   a.join();
   b.join();
}

int main() {
   supragarble(10);
}
```
Quoted 1 line
Fixes #285

Please use: 'Fixes: https://gitlab.com/qemu-project/qemu/-/issues/285'

Also,

Quoted 6 lines
---
  accel/tcg/tb-maint.c | 17 +++++++++--------
  tcg/region.c         | 19 ++++++++++---------
  2 files changed, 19 insertions(+), 17 deletions(-)
#4 lore raw
In reply to Emilio Cota

Ping.

This fixes a bug (admittedly with a big hammer) that affects users with heavily multi-threaded user-mode workloads.

Thanks,
Emilio

Quoted 18 lines · Emilio Cota

Changes since v1:

- Add configure check to only use QTree if Glib still implements gslice. If Glib doesn't, then we call Glib directly with inline functions.
- Add TODO's so that in the future (i.e. when the minimum version of Glib that we use doesn't implement gslice) we remove QTree.
- Add comment to the top of qtree.h.
- Make qtree-bench results more robust by running longer or more times.
- Drop deprecated API calls (they're unused in QEMU).
- Drop API calls that are too recent (they're unused in QEMU).
- Drop macro benchmark results from the TCG patch since they're too noisy.
- Add test program to the commit log so that we don't lose it in the future even if the bug tracker goes away.

Thanks,
Emilio

#5 lore raw

Ping. Any feedback on these two patches?

https://patchew.org/QEMU/[email protected]/
https://lore.kernel.org/qemu-devel/[email protected]/

Happy to resend if needed.

Thanks,
Emilio

Quoted 27 lines · Emilio Cota

Ping.

This fixes a bug (admittedly with a big hammer) that affects users with heavily multi-threaded user-mode workloads.

Thanks,
Emilio

Quoted 18 lines · Emilio Cota

Changes since v1:

- Add configure check to only use QTree if Glib still implements gslice. If Glib doesn't, then we call Glib directly with inline functions.
- Add TODO's so that in the future (i.e. when the minimum version of Glib that we use doesn't implement gslice) we remove QTree.
- Add comment to the top of qtree.h.
- Make qtree-bench results more robust by running longer or more times.
- Drop deprecated API calls (they're unused in QEMU).
- Drop API calls that are too recent (they're unused in QEMU).
- Drop macro benchmark results from the TCG patch since they're too noisy.
- Add test program to the commit log so that we don't lose it in the future even if the bug tracker goes away.

Thanks,
Emilio

#6 lore raw

Hi Emilio,

Quoted 6 lines · Emilio Cota

Ping. Any feedback on these two patches?

https://patchew.org/QEMU/[email protected]/
https://lore.kernel.org/qemu-devel/[email protected]/

Happy to resend if needed.

Since we are past hard-freeze, this series likely missed the v8.0 release IMO. Note that doesn't mean maintainers can't queue it and send the pull request later when the next development window opens.

Quoted 29 lines · Emilio Cota
Quoted 27 lines

Ping.

This fixes a bug (admittedly with a big hammer) that affects users with heavily multi-threaded user-mode workloads.

Thanks,
Emilio

Quoted 18 lines · Emilio Cota

Changes since v1:

- Add configure check to only use QTree if Glib still implements gslice. If Glib doesn't, then we call Glib directly with inline functions.
- Add TODO's so that in the future (i.e. when the minimum version of Glib that we use doesn't implement gslice) we remove QTree.
- Add comment to the top of qtree.h.
- Make qtree-bench results more robust by running longer or more times.
- Drop deprecated API calls (they're unused in QEMU).
- Drop API calls that are too recent (they're unused in QEMU).
- Drop macro benchmark results from the TCG patch since they're too noisy.
- Add test program to the commit log so that we don't lose it in the future even if the bug tracker goes away.

Thanks,
Emilio

#7 lore raw
Quoted 5 lines · Philippe Mathieu-Daudé

Hi Emilio,

Quoted 2 lines · Emilio Cota

Ping. Any feedback on these two patches?

Quoted 8 lines
Quoted 4 lines

https://patchew.org/QEMU/[email protected]/
https://lore.kernel.org/qemu-devel/[email protected]/

Happy to resend if needed.

Since we are past hard-freeze, this series likely missed the v8.0 release IMO. Note that doesn't mean maintainers can't queue it and send the pull request later when the next development window opens.

This series is a bug fix though, the freeze only applies to features. For rc0/1 most bug fixes are still permissible.

I'd really recommend we take this series, as it is a clear bug in linux-user that can be fairly easily reproduced

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#8 lore raw
In reply to Emilio Cota
Quoted 4 lines · Emilio Cota

Ping. Any feedback on these two patches?

https://patchew.org/QEMU/[email protected]/
https://lore.kernel.org/qemu-devel/[email protected]/

Queued to tcg-next.

r~

Quoted 35 lines

Happy to resend if needed.

Thanks,
Emilio

Quoted 27 lines · Emilio Cota

Ping.

This fixes a bug (admittedly with a big hammer) that affects users with heavily multi-threaded user-mode workloads.

Thanks,
Emilio

Quoted 18 lines · Emilio Cota

Changes since v1:

- Add configure check to only use QTree if Glib still implements gslice. If Glib doesn't, then we call Glib directly with inline functions.
- Add TODO's so that in the future (i.e. when the minimum version of Glib that we use doesn't implement gslice) we remove QTree.
- Add comment to the top of qtree.h.
- Make qtree-bench results more robust by running longer or more times.
- Drop deprecated API calls (they're unused in QEMU).
- Drop API calls that are too recent (they're unused in QEMU).
- Drop macro benchmark results from the TCG patch since they're too noisy.
- Add test program to the commit log so that we don't lose it in the future even if the bug tracker goes away.

Thanks,
Emilio