Skip to contentSkip to conversation

TCG code quality tracking

PATCH Superseded Fei Wu 2 participants 17 messages Jun 7, 2023 – Jun 16, 2023 Arm/Amlogic Meson SoC support

v15 of 16 Superseded Latest is v16 →

lore
Share & tools
lore

Fei Wu

author
#0 lore raw

v15 cover TCG code quality tracking

v15
---
This is a large change:
* remove all time related stuffs, including cmd 'info profile'
* remove the per-TB flag, use global flag instead
* remove tb_stats pause/filter, but add status
* remove qemu_log changes, and use monitor_printf
* use array instead of list for sorting
* remove async_safe_run_on_cpu for cmd info tb-list & tb
* use monitor_disas instead of regenerate TB, but **doesn't work yet**
* other cleanups

Alex Bennée (1):
tb-stats: reset the tracked TBs on a tb_flush

Fei Wu (5):
accel/tcg: remove CONFIG_PROFILER accel/tcg: add jit stats to TBStatistics
debug: add -d tb_stats to control TBStatistics
tb-stats: dump hot TBs at the end of the execution
docs: add tb-stats how to

Vanderson M. do Rosario (4):
accel/tcg: introduce TBStatistics structure
accel: collecting TB execution count
monitor: adding tb_stats hmp command
tb-stats: Adding info [tb-list|tb] commands to HMP (WIP)

 MAINTAINERS                   |   1 +
 accel/tcg/cpu-exec.c          |   6 +
 accel/tcg/meson.build         |   1 +
 accel/tcg/monitor.c           | 184 +++++++++++++++--
 accel/tcg/tb-context.h        |   1 +
 accel/tcg/tb-hash.h           |   7 +
 accel/tcg/tb-maint.c          |  20 ++
 accel/tcg/tb-stats.c          | 365 ++++++++++++++++++++++++++++++++++
 accel/tcg/tcg-accel-ops.c     |  10 -
 accel/tcg/tcg-runtime.c       |   1 +
 accel/tcg/translate-all.c     | 110 ++++++----
 accel/tcg/translator.c        |  30 +++
 disas/disas.c                 |   2 +
 docs/devel/tcg-tbstats.rst    |  97 +++++++++
 hmp-commands-info.hx          |  31 +--
 hmp-commands.hx               |  16 ++
 include/exec/exec-all.h       |   3 +
 include/exec/gen-icount.h     |   1 +
 include/exec/tb-stats-dump.h  |  21 ++
 include/exec/tb-stats-flags.h |  29 +++
 include/exec/tb-stats.h       | 130 ++++++++++++
 include/monitor/hmp.h         |   3 +
 include/qemu/log.h            |   1 +
 include/qemu/timer.h          |   9 -
 include/tcg/tcg.h             |  26 +--
 linux-user/exit.c             |   2 +
 meson.build                   |   2 -
 meson_options.txt             |   2 -
 qapi/machine.json             |  18 --
 scripts/meson-buildoptions.sh |   3 -
 softmmu/runstate.c            |  11 +-
 stubs/meson.build             |   1 +
 stubs/tb-stats.c              |  36 ++++
 tcg/tcg.c                     | 237 +++-------------------
 tests/qtest/qmp-cmd-test.c    |   3 -
 util/log.c                    |  26 +++
 36 files changed, 1093 insertions(+), 353 deletions(-)
 create mode 100644 accel/tcg/tb-stats.c
 create mode 100644 docs/devel/tcg-tbstats.rst
 create mode 100644 include/exec/tb-stats-dump.h
 create mode 100644 include/exec/tb-stats-flags.h
 create mode 100644 include/exec/tb-stats.h
 create mode 100644 stubs/tb-stats.c
Signature · 1 line
2.25.1
author
#1 lore raw

PATCH v15 1/10 accel/tcg: remove CONFIG_PROFILER

TBStats will be introduced to replace CONFIG_PROFILER totally, here remove all CONFIG_PROFILER related stuffs first.

---
 accel/tcg/monitor.c           |  31 -----
 accel/tcg/tcg-accel-ops.c     |  10 --
 accel/tcg/translate-all.c     |  33 ------
 hmp-commands-info.hx          |  15 ---
 include/qemu/timer.h          |   9 --
 include/tcg/tcg.h             |  26 -----
 meson.build                   |   2 -
 meson_options.txt             |   2 -
 qapi/machine.json             |  18 ---
 scripts/meson-buildoptions.sh |   3 -
 softmmu/runstate.c            |   9 --
 tcg/tcg.c                     | 214 ----------------------------------
 tests/qtest/qmp-cmd-test.c    |   3 -
 13 files changed, 375 deletions(-)
accel/tcg/monitor.c +0 -31
index 92fce580f1..39d8260428 100644
@@ -80,37 +80,6 @@ HumanReadableText *qmp_x_query_opcount(Error **errp)
     return human_readable_text_from_str(buf);
 }
 
-#ifdef CONFIG_PROFILER
-
-int64_t dev_time;
-
-HumanReadableText *qmp_x_query_profile(Error **errp)
-{
-    g_autoptr(GString) buf = g_string_new("");
-    static int64_t last_cpu_exec_time;
-    int64_t cpu_exec_time;
-    int64_t delta;
-
-    cpu_exec_time = tcg_cpu_exec_time();
-    delta = cpu_exec_time - last_cpu_exec_time;
-
-    g_string_append_printf(buf, "async time  %" PRId64 " (%0.3f)\n",
-                           dev_time, dev_time / (double)NANOSECONDS_PER_SECOND);
-    g_string_append_printf(buf, "qemu time   %" PRId64 " (%0.3f)\n",
-                           delta, delta / (double)NANOSECONDS_PER_SECOND);
-    last_cpu_exec_time = cpu_exec_time;
-    dev_time = 0;
-
-    return human_readable_text_from_str(buf);
-}
-#else
-HumanReadableText *qmp_x_query_profile(Error **errp)
-{
-    error_setg(errp, "Internal profiler not compiled");
-    return NULL;
-}
-#endif
-
 static void hmp_tcg_register(void)
 {
     monitor_register_hmp_info_hrt("jit", qmp_x_query_jit);
accel/tcg/tcg-accel-ops.c +0 -10
index 58c8e64096..3973591508 100644
@@ -70,20 +70,10 @@ void tcg_cpus_destroy(CPUState *cpu)
 int tcg_cpus_exec(CPUState *cpu)
 {
     int ret;
-#ifdef CONFIG_PROFILER
-    int64_t ti;
-#endif
     assert(tcg_enabled());
-#ifdef CONFIG_PROFILER
-    ti = profile_getclock();
-#endif
     cpu_exec_start(cpu);
     ret = cpu_exec(cpu);
     cpu_exec_end(cpu);
-#ifdef CONFIG_PROFILER
-    qatomic_set(&tcg_ctx->prof.cpu_exec_time,
-                tcg_ctx->prof.cpu_exec_time + profile_getclock() - ti);
-#endif
     return ret;
 }
 
accel/tcg/translate-all.c +0 -33
index c87648b99e..4e035e0f79 100644
@@ -203,10 +203,6 @@ void cpu_restore_state_from_tb(CPUState *cpu, TranslationBlock *tb,
                                uintptr_t host_pc)
 {
     uint64_t data[TARGET_INSN_START_WORDS];
-#ifdef CONFIG_PROFILER
-    TCGProfile *prof = &tcg_ctx->prof;
-    int64_t ti = profile_getclock();
-#endif
     int insns_left = cpu_unwind_data_from_tb(tb, host_pc, data);
 
     if (insns_left < 0) {
@@ -223,12 +219,6 @@ void cpu_restore_state_from_tb(CPUState *cpu, TranslationBlock *tb,
     }
 
     cpu->cc->tcg_ops->restore_state_to_opc(cpu, tb, data);
-
-#ifdef CONFIG_PROFILER
-    qatomic_set(&prof->restore_time,
-                prof->restore_time + profile_getclock() - ti);
-    qatomic_set(&prof->restore_count, prof->restore_count + 1);
-#endif
 }
 
 bool cpu_restore_state(CPUState *cpu, uintptr_t host_pc)
@@ -291,13 +281,6 @@ static int setjmp_gen_code(CPUArchState *env, TranslationBlock *tb,
     tcg_ctx->cpu = NULL;
     *max_insns = tb->icount;
 
-#ifdef CONFIG_PROFILER
-    qatomic_set(&tcg_ctx->prof.tb_count, tcg_ctx->prof.tb_count + 1);
-    qatomic_set(&tcg_ctx->prof.interm_time,
-                tcg_ctx->prof.interm_time + profile_getclock() - *ti);
-    *ti = profile_getclock();
-#endif
-
     return tcg_gen_code(tcg_ctx, tb, pc);
 }
 
@@ -311,9 +294,6 @@ TranslationBlock *tb_gen_code(CPUState *cpu,
     tb_page_addr_t phys_pc;
     tcg_insn_unit *gen_code_buf;
     int gen_code_size, search_size, max_insns;
-#ifdef CONFIG_PROFILER
-    TCGProfile *prof = &tcg_ctx->prof;
-#endif
     int64_t ti;
     void *host_pc;
 
@@ -365,12 +345,6 @@ TranslationBlock *tb_gen_code(CPUState *cpu,
 
  tb_overflow:
 
-#ifdef CONFIG_PROFILER
-    /* includes aborted translations because of exceptions */
-    qatomic_set(&prof->tb_count1, prof->tb_count1 + 1);
-    ti = profile_getclock();
-#endif
-
     trace_translate_block(tb, pc, tb->tc.ptr);
 
     gen_code_size = setjmp_gen_code(env, tb, pc, host_pc, &max_insns, &ti);
@@ -425,13 +399,6 @@ TranslationBlock *tb_gen_code(CPUState *cpu,
      */
     perf_report_code(pc, tb, tcg_splitwx_to_rx(gen_code_buf));
 
-#ifdef CONFIG_PROFILER
-    qatomic_set(&prof->code_time, prof->code_time + profile_getclock() - ti);
-    qatomic_set(&prof->code_in_len, prof->code_in_len + tb->size);
-    qatomic_set(&prof->code_out_len, prof->code_out_len + gen_code_size);
-    qatomic_set(&prof->search_out_len, prof->search_out_len + search_size);
-#endif
-
     if (qemu_loglevel_mask(CPU_LOG_TB_OUT_ASM) &&
         qemu_log_in_addr_range(pc)) {
         FILE *logfile = qemu_log_trylock();
hmp-commands-info.hx +0 -15
index 47d63d26db..f5b37eb74a 100644
@@ -360,21 +360,6 @@ SRST
     Show host USB devices.
 ERST
 
-#if defined(CONFIG_TCG)
-    {
-        .name       = "profile",
-        .args_type  = "",
-        .params     = "",
-        .help       = "show profiling information",
-        .cmd_info_hrt = qmp_x_query_profile,
-    },
-#endif
-
-SRST
-  ``info profile``
-    Show profiling information.
-ERST
-
     {
         .name       = "capture",
         .args_type  = "",
include/qemu/timer.h +0 -9
index ee071e07d1..9a91cb1248 100644
@@ -989,13 +989,4 @@ static inline int64_t cpu_get_host_ticks(void)
 }
 #endif
 
-#ifdef CONFIG_PROFILER
-static inline int64_t profile_getclock(void)
-{
-    return get_clock();
-}
-
-extern int64_t dev_time;
-#endif
-
 #endif
include/tcg/tcg.h +0 -26
index 072c35f7f5..da1c8fa3b5 100644
@@ -522,27 +522,6 @@ static inline TCGRegSet output_pref(const TCGOp *op, unsigned i)
     return i < ARRAY_SIZE(op->output_pref) ? op->output_pref[i] : 0;
 }
 
-typedef struct TCGProfile {
-    int64_t cpu_exec_time;
-    int64_t tb_count1;
-    int64_t tb_count;
-    int64_t op_count; /* total insn count */
-    int op_count_max; /* max insn per TB */
-    int temp_count_max;
-    int64_t temp_count;
-    int64_t del_op_count;
-    int64_t code_in_len;
-    int64_t code_out_len;
-    int64_t search_out_len;
-    int64_t interm_time;
-    int64_t code_time;
-    int64_t la_time;
-    int64_t opt_time;
-    int64_t restore_count;
-    int64_t restore_time;
-    int64_t table_op_count[NB_OPS];
-} TCGProfile;
-
 struct TCGContext {
     uint8_t *pool_cur, *pool_end;
     TCGPool *pool_first, *pool_current, *pool_first_large;
@@ -569,10 +548,6 @@ struct TCGContext {
     tcg_insn_unit *code_buf;      /* pointer for start of tb */
     tcg_insn_unit *code_ptr;      /* pointer for running end of tb */
 
-#ifdef CONFIG_PROFILER
-    TCGProfile prof;
-#endif
-
 #ifdef CONFIG_DEBUG_TCG
     int goto_tb_issue_mask;
     const TCGOpcode *vecop_list;
@@ -910,7 +885,6 @@ static inline TCGv_ptr tcg_temp_new_ptr(void)
     return temp_tcgv_ptr(t);
 }
 
-int64_t tcg_cpu_exec_time(void);
 void tcg_dump_info(GString *buf);
 void tcg_dump_op_count(GString *buf);
 
meson.build +0 -2
index ef181ff2df..7da252cc81 100644
@@ -2134,7 +2134,6 @@ if numa.found()
                                        dependencies: numa))
 endif
 config_host_data.set('CONFIG_OPENGL', opengl.found())
-config_host_data.set('CONFIG_PROFILER', get_option('profiler'))
 config_host_data.set('CONFIG_RBD', rbd.found())
 config_host_data.set('CONFIG_RDMA', rdma.found())
 config_host_data.set('CONFIG_SAFESTACK', get_option('safe_stack'))
@@ -4117,7 +4116,6 @@ if 'objc' in all_languages
   summary_info += {'QEMU_OBJCFLAGS':    ' '.join(qemu_common_flags)}
 endif
 summary_info += {'QEMU_LDFLAGS':      ' '.join(qemu_ldflags)}
-summary_info += {'profiler':          get_option('profiler')}
 summary_info += {'link-time optimization (LTO)': get_option('b_lto')}
 summary_info += {'PIE':               get_option('b_pie')}
 summary_info += {'static build':      config_host.has_key('CONFIG_STATIC')}
meson_options.txt +0 -2
index 90237389e2..bbb5c7e886 100644
@@ -345,8 +345,6 @@ option('qom_cast_debug', type: 'boolean', value: true,
 option('gprof', type: 'boolean', value: false,
        description: 'QEMU profiling with gprof',
        deprecated: true)
-option('profiler', type: 'boolean', value: false,
-       description: 'profiler support')
 option('slirp_smbd', type : 'feature', value : 'auto',
        description: 'use smbd (at path --smbd=*) in slirp networking')
 
qapi/machine.json +0 -18
index 37660d8f2a..a08b6576ca 100644
@@ -1575,24 +1575,6 @@
   'if': 'CONFIG_TCG',
   'features': [ 'unstable' ] }
 
-##
-# @x-query-profile:
-#
-# Query TCG profiling information
-#
-# Features:
-#
-# @unstable: This command is meant for debugging.
-#
-# Returns: profile information
-#
-# Since: 6.2
-##
-{ 'command': 'x-query-profile',
-  'returns': 'HumanReadableText',
-  'if': 'CONFIG_TCG',
-  'features': [ 'unstable' ] }
-
 ##
 # @x-query-ramblock:
 #
scripts/meson-buildoptions.sh +0 -3
index 5714fd93d9..7dd5709ef4 100644
@@ -39,7 +39,6 @@ meson_options_help() {
   printf "%s\n" '                           jemalloc/system/tcmalloc)'
   printf "%s\n" '  --enable-module-upgrades try to load modules from alternate paths for'
   printf "%s\n" '                           upgrades'
-  printf "%s\n" '  --enable-profiler        profiler support'
   printf "%s\n" '  --enable-rng-none        dummy RNG, avoid using /dev/(u)random and'
   printf "%s\n" '                           getrandom()'
   printf "%s\n" '  --enable-safe-stack      SafeStack Stack Smash Protection (requires'
@@ -401,8 +400,6 @@ _meson_option_parse() {
     --with-pkgversion=*) quote_sh "-Dpkgversion=$2" ;;
     --enable-png) printf "%s" -Dpng=enabled ;;
     --disable-png) printf "%s" -Dpng=disabled ;;
-    --enable-profiler) printf "%s" -Dprofiler=true ;;
-    --disable-profiler) printf "%s" -Dprofiler=false ;;
     --enable-pvrdma) printf "%s" -Dpvrdma=enabled ;;
     --disable-pvrdma) printf "%s" -Dpvrdma=disabled ;;
     --enable-qcow1) printf "%s" -Dqcow1=enabled ;;
softmmu/runstate.c +0 -9
index 2f2396c819..bd50062ed0 100644
@@ -728,18 +728,9 @@ static bool main_loop_should_exit(int *status)
 int qemu_main_loop(void)
 {
     int status = EXIT_SUCCESS;
-#ifdef CONFIG_PROFILER
-    int64_t ti;
-#endif
 
     while (!main_loop_should_exit(&status)) {
-#ifdef CONFIG_PROFILER
-        ti = profile_getclock();
-#endif
         main_loop_wait(false);
-#ifdef CONFIG_PROFILER
-        dev_time += profile_getclock() - ti;
-#endif
     }
 
     return status;
tcg/tcg.c +0 -214

266 lines not on this page · raw message

tests/qtest/qmp-cmd-test.c +0 -3
index a58de48d2a..73a670e8fa 100644
@@ -46,9 +46,6 @@ static int query_error_class(const char *cmd)
         { "query-balloon", ERROR_CLASS_DEVICE_NOT_ACTIVE },
         { "query-hotpluggable-cpus", ERROR_CLASS_GENERIC_ERROR },
         { "query-vm-generation-id", ERROR_CLASS_GENERIC_ERROR },
-#ifndef CONFIG_PROFILER
-        { "x-query-profile", ERROR_CLASS_GENERIC_ERROR },
-#endif
         /* Only valid with a USB bus added */
         { "x-query-usb", ERROR_CLASS_GENERIC_ERROR },
         /* Only valid with accel=tcg */
Signature · 1 line
2.25.1
author
#2 lore raw

PATCH v15 2/10 accel/tcg: introduce TBStatistics structure

In reply to Fei Wu

From: "Vanderson M. do Rosario" <[email protected]>

To store statistics for each TB, we created a TBStatistics structure which is linked with the TBs. TBStatistics can stay alive after tb_flush and be relinked to a regenerated TB. So the statistics can be accumulated even through flushes.

The goal is to have all present and future qemu/tcg statistics and meta-data stored in this new structure.

Message-Id: <[email protected]>

[AJB: fix git author, review comments]
---
 MAINTAINERS                   |  1 +
 accel/tcg/meson.build         |  1 +
 accel/tcg/tb-context.h        |  1 +
 accel/tcg/tb-hash.h           |  7 +++++
 accel/tcg/tb-maint.c          | 19 ++++++++++++
 accel/tcg/tb-stats.c          | 46 ++++++++++++++++++++++++++++
 accel/tcg/translate-all.c     | 44 +++++++++++++++++++++++++++
 include/exec/exec-all.h       |  3 ++
 include/exec/tb-stats-flags.h | 19 ++++++++++++
 include/exec/tb-stats.h       | 56 +++++++++++++++++++++++++++++++++++
 10 files changed, 197 insertions(+)
 create mode 100644 accel/tcg/tb-stats.c
 create mode 100644 include/exec/tb-stats-flags.h
 create mode 100644 include/exec/tb-stats.h
MAINTAINERS +1 -0
index 1c93ab0ee5..2077889efd 100644
@@ -153,6 +153,7 @@ F: include/exec/cpu*.h
 F: include/exec/exec-all.h
 F: include/exec/tb-flush.h
 F: include/exec/target_long.h
+F: include/exec/tb-stats*.h
 F: include/exec/helper*.h
 F: include/sysemu/cpus.h
 F: include/sysemu/tcg.h
accel/tcg/meson.build +1 -0
index aeb20a6ef0..9263bdde11 100644
@@ -4,6 +4,7 @@ tcg_ss.add(files(
   'cpu-exec-common.c',
   'cpu-exec.c',
   'tb-maint.c',
+  'tb-stats.c',
   'tcg-runtime-gvec.c',
   'tcg-runtime.c',
   'translate-all.c',
accel/tcg/tb-context.h +1 -0
index cac62d9749..d7910d586b 100644
@@ -35,6 +35,7 @@ struct TBContext {
     /* statistics */
     unsigned tb_flush_count;
     unsigned tb_phys_invalidate_count;
+    struct qht tb_stats;
 };
 
 extern TBContext tb_ctx;
accel/tcg/tb-hash.h +7 -0
index 83dc610e4c..87d657a1c6 100644
@@ -67,4 +67,11 @@ uint32_t tb_hash_func(tb_page_addr_t phys_pc, target_ulong pc, uint32_t flags,
     return qemu_xxhash7(phys_pc, pc, flags, cf_mask, trace_vcpu_dstate);
 }
 
+static inline
+uint32_t tb_stats_hash_func(tb_page_addr_t phys_pc, target_ulong pc,
+                            uint32_t flags)
+{
+    return qemu_xxhash5(phys_pc, pc, flags);
+}
+
 #endif
accel/tcg/tb-maint.c +19 -0
index 991746f80f..0980fca358 100644
@@ -24,6 +24,7 @@
 #include "exec/log.h"
 #include "exec/exec-all.h"
 #include "exec/tb-flush.h"
+#include "exec/tb-stats.h"
 #include "exec/translate-all.h"
 #include "sysemu/tcg.h"
 #include "tcg/tcg.h"
@@ -41,6 +42,23 @@
 #define TB_FOR_EACH_JMP(head_tb, tb, n)                                 \
     TB_FOR_EACH_TAGGED((head_tb)->jmp_list_head, tb, n, jmp_list_next)
 
+/*
+ * This is the more or less the same compare as tb_cmp(), but the
+ * data persists over tb_flush. We also aggregate the various
+ * variations of cflags under one record and ignore the details of
+ * page overlap (although we can count it).
+ */
+bool tb_stats_cmp(const void *ap, const void *bp)
+{
+    const TBStatistics *a = ap;
+    const TBStatistics *b = bp;
+
+    return a->phys_pc == b->phys_pc &&
+        a->pc == b->pc &&
+        a->cs_base == b->cs_base &&
+        a->flags == b->flags;
+}
+
 static bool tb_cmp(const void *ap, const void *bp)
 {
     const TranslationBlock *a = ap;
@@ -60,6 +78,7 @@ void tb_htable_init(void)
     unsigned int mode = QHT_MODE_AUTO_RESIZE;
 
     qht_init(&tb_ctx.htable, tb_cmp, CODE_GEN_HTABLE_SIZE, mode);
+    init_tb_stats_htable();
 }
 
 typedef struct PageDesc PageDesc;
accel/tcg/tb-stats.c new file +46 -0

46 lines not on this page · raw message

accel/tcg/translate-all.c +44 -0

62 lines not on this page · raw message

include/exec/exec-all.h +3 -0
index 4d2b151986..f8a80f63d3 100644
@@ -608,6 +608,9 @@ struct TranslationBlock {
     uintptr_t jmp_list_head;
     uintptr_t jmp_list_next[2];
     uintptr_t jmp_dest[2];
+
+    /* Pointer to a struct where statistics from the TB is stored */
+    struct TBStatistics *tb_stats;
 };
 
 /* Hide the qatomic_read to make code a little easier on the eyes */
include/exec/tb-stats-flags.h new file +19 -0
new file mode 100644
index 0000000000..c994cf3b9d
@@ -0,0 +1,19 @@
+/*
+ * QEMU System Emulator, Code Quality Monitor System
+ *
+ * We define the flags and control bits here to avoid complications of
+ * including TCG/CPU information in common code.
+ *
+ * Copyright (c) 2019 Vanderson M. do Rosario <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+#ifndef TB_STATS_FLAGS
+#define TB_STATS_FLAGS
+
+/* TBStatistic collection controls */
+void enable_collect_tb_stats(void);
+void disable_collect_tb_stats(void);
+bool tb_stats_collection_enabled(void);
+
+#endif
include/exec/tb-stats.h new file +56 -0

56 lines not on this page · raw message

Signature · 1 line
2.25.1
author
#3 lore raw

PATCH v15 3/10 accel: collecting TB execution count

In reply to Fei Wu

From: "Vanderson M. do Rosario" <[email protected]>

If a TB has a TBS (TBStatistics) with the TB_EXEC_STATS enabled, then we instrument the start code of this TB to atomically count the number of times it is executed. We count both the number of "normal" executions and atomic executions of a TB.

The execution count of the TB is stored in its respective TBS.

All TBStatistics are created by default with the flags from default_tbstats_flag.

[Richard Henderson created the inline gen_tb_exec_count]

Message-Id: <[email protected]>

[AJB: Fix author]
---
 accel/tcg/cpu-exec.c          |  6 ++++++
 accel/tcg/tb-stats.c          | 18 ++++++++++++++++++
 accel/tcg/tcg-runtime.c       |  1 +
 accel/tcg/translate-all.c     |  6 ++++--
 accel/tcg/translator.c        | 25 +++++++++++++++++++++++++
 include/exec/gen-icount.h     |  1 +
 include/exec/tb-stats-flags.h |  6 ++++++
 include/exec/tb-stats.h       |  8 ++++++++
 8 files changed, 69 insertions(+), 2 deletions(-)
accel/tcg/cpu-exec.c +6 -0
index 0e741960da..c0d8f26237 100644
@@ -25,6 +25,7 @@
 #include "trace.h"
 #include "disas/disas.h"
 #include "exec/exec-all.h"
+#include "exec/tb-stats.h"
 #include "tcg/tcg.h"
 #include "qemu/atomic.h"
 #include "qemu/rcu.h"
@@ -562,7 +563,12 @@ void cpu_exec_step_atomic(CPUState *cpu)
             mmap_unlock();
         }
 
+        if (tb_stats_enabled(tb, TB_EXEC_STATS)) {
+            tb->tb_stats->executions.atomic++;
+        }
+
         cpu_exec_enter(cpu);
+
         /* execute the generated code */
         trace_exec_tb(tb, pc);
         cpu_tb_exec(cpu, tb, &tb_exit);
accel/tcg/tb-stats.c +18 -0
index 2b6be943ef..2b7321b548 100644
@@ -20,6 +20,7 @@ enum TBStatsStatus {
 };
 
 static enum TBStatsStatus tcg_collect_tb_stats;
+static uint32_t tbstats_flag;
 
 void init_tb_stats_htable(void)
 {
@@ -44,3 +45,20 @@ bool tb_stats_collection_enabled(void)
 {
     return tcg_collect_tb_stats == TB_STATS_RUNNING;
 }
+
+uint32_t get_tbstats_flag(void)
+{
+    return tbstats_flag;
+}
+
+void set_tbstats_flag(uint32_t flag)
+{
+    tbstats_flag = flag;
+}
+
+bool tb_stats_enabled(TranslationBlock *tb, uint32_t flag)
+{
+    return tb_stats_collection_enabled() &&
+           tb->tb_stats &&
+           (tbstats_flag & flag);
+}
accel/tcg/tcg-runtime.c +1 -0
index e4e030043f..11c6192064 100644
@@ -27,6 +27,7 @@
 #include "exec/helper-proto.h"
 #include "exec/cpu_ldst.h"
 #include "exec/exec-all.h"
+#include "exec/tb-stats.h"
 #include "disas/disas.h"
 #include "exec/log.h"
 #include "tcg/tcg.h"
accel/tcg/translate-all.c +4 -2
index 4fc41a63b5..5963cd6fe4 100644
@@ -382,9 +382,11 @@ TranslationBlock *tb_gen_code(CPUState *cpu,
     /*
      * We want to fetch the stats structure before we start code
      * generation so we can count interesting things about this
-     * generation.
+     * generation. If dfilter is in effect we will only collect stats
+     * for the specified range.
      */
-    if (tb_stats_collection_enabled()) {
+    if (tb_stats_collection_enabled() &&
+        qemu_log_in_addr_range(tb->pc)) {
         tb->tb_stats = tb_get_stats(phys_pc, cflags & CF_PCREL ? 0 : pc,
                                     cs_base, flags);
     } else {
accel/tcg/translator.c +25 -0
index 6120ef2a92..80ffbfb455 100644
@@ -11,6 +11,7 @@
 #include "qemu/error-report.h"
 #include "tcg/tcg.h"
 #include "tcg/tcg-op.h"
+#include "tcg/tcg-temp-internal.h"
 #include "exec/exec-all.h"
 #include "exec/gen-icount.h"
 #include "exec/log.h"
@@ -18,6 +19,29 @@
 #include "exec/plugin-gen.h"
 #include "exec/replay-core.h"
 
+static void gen_tb_exec_count(TranslationBlock *tb)
+{
+    if (tb_stats_enabled(tb, TB_EXEC_STATS)) {
+        TCGv_ptr ptr = tcg_temp_ebb_new_ptr();
+
+        tcg_gen_movi_ptr(ptr, (intptr_t)&tb->tb_stats->executions.normal);
+        if (sizeof(tb->tb_stats->executions.normal) == 4) {
+            TCGv_i32 t = tcg_temp_ebb_new_i32();
+            tcg_gen_ld_i32(t, ptr, 0);
+            tcg_gen_addi_i32(t, t, 1);
+            tcg_gen_st_i32(t, ptr, 0);
+            tcg_temp_free_i32(t);
+        } else {
+            TCGv_i64 t = tcg_temp_ebb_new_i64();
+            tcg_gen_ld_i64(t, ptr, 0);
+            tcg_gen_addi_i64(t, t, 1);
+            tcg_gen_st_i64(t, ptr, 0);
+            tcg_temp_free_i64(t);
+        }
+        tcg_temp_free_ptr(ptr);
+    }
+}
+
 bool translator_use_goto_tb(DisasContextBase *db, target_ulong dest)
 {
     /* Suppress goto_tb if requested. */
@@ -56,6 +80,7 @@ void translator_loop(CPUState *cpu, TranslationBlock *tb, int *max_insns,
 
     /* Start translating.  */
     gen_tb_start(db->tb);
+    gen_tb_exec_count(tb);
     ops->tb_start(db, cpu);
     tcg_debug_assert(db->is_jmp == DISAS_NEXT);  /* no early exit */
 
include/exec/gen-icount.h +1 -0
index f6de79a6b4..20e7835ff0 100644
@@ -2,6 +2,7 @@
 #define GEN_ICOUNT_H
 
 #include "exec/exec-all.h"
+#include "exec/tb-stats.h"
 
 /* Helpers for instruction counting code generation.  */
 
include/exec/tb-stats-flags.h +6 -0
index c994cf3b9d..c0e63408e2 100644
@@ -11,9 +11,15 @@
 #ifndef TB_STATS_FLAGS
 #define TB_STATS_FLAGS
 
+#define TB_NONE_STATS (0)  /* no stats */
+#define TB_EXEC_STATS (1 << 0)
+
 /* TBStatistic collection controls */
 void enable_collect_tb_stats(void);
 void disable_collect_tb_stats(void);
 bool tb_stats_collection_enabled(void);
 
+uint32_t get_tbstats_flag(void);
+void set_tbstats_flag(uint32_t flag);
+
 #endif
include/exec/tb-stats.h +8 -0
index b519465665..b935c3235a 100644
@@ -47,10 +47,18 @@ struct TBStatistics {
     uint32_t     flags;
     /* cs_base isn't included in the hash but we do check for matches */
     target_ulong cs_base;
+
+    /* Execution stats */
+    struct {
+        unsigned long normal;
+        unsigned long atomic;
+    } executions;
+
 };
 
 bool tb_stats_cmp(const void *ap, const void *bp);
 
 void init_tb_stats_htable(void);
+bool tb_stats_enabled(TranslationBlock *tb, uint32_t flag);
 
 #endif
Signature · 1 line
2.25.1
author
#4 lore raw

PATCH v15 4/10 accel/tcg: add jit stats to TBStatistics

In reply to Fei Wu

This collects all the statistics for TBStatistics, not only for the whole emulation but for each TB.

---
 accel/tcg/monitor.c           |  6 +++
 accel/tcg/tb-stats.c          | 69 +++++++++++++++++++++++++++++++++++
 accel/tcg/translate-all.c     | 31 ++++++++++++++--
 accel/tcg/translator.c        |  5 +++
 include/exec/tb-stats-flags.h |  1 +
 include/exec/tb-stats.h       | 29 +++++++++++++++
 include/tcg/tcg.h             | 10 +++++
 tcg/tcg.c                     | 47 ++++++++++++++++++++++--
 8 files changed, 192 insertions(+), 6 deletions(-)
accel/tcg/monitor.c +6 -0
index 39d8260428..111ccbc4da 100644
@@ -15,6 +15,7 @@
 #include "sysemu/cpus.h"
 #include "sysemu/cpu-timers.h"
 #include "sysemu/tcg.h"
+#include "exec/tb-stats.h"
 #include "internal.h"
 
 
@@ -69,6 +70,11 @@ HumanReadableText *qmp_x_query_opcount(Error **errp)
 {
     g_autoptr(GString) buf = g_string_new("");
 
+    if (!tb_stats_collection_enabled()) {
+        error_setg(errp, "TB information not being recorded");
+        return NULL;
+    }
+
     if (!tcg_enabled()) {
         error_setg(errp,
                    "Opcode count information is only available with accel=tcg");
accel/tcg/tb-stats.c +69 -0

81 lines not on this page · raw message

accel/tcg/translate-all.c +28 -3
index 5963cd6fe4..f795385aac 100644
@@ -267,7 +267,7 @@ void page_init(void)
  */
 static int setjmp_gen_code(CPUArchState *env, TranslationBlock *tb,
                            target_ulong pc, void *host_pc,
-                           int *max_insns, int64_t *ti)
+                           int *max_insns)
 {
     int ret = sigsetjmp(tcg_ctx->jmp_trans, 0);
     if (unlikely(ret != 0)) {
@@ -295,6 +295,8 @@ static TBStatistics *tb_get_stats(tb_page_addr_t phys_pc, target_ulong pc,
     new_stats->pc = pc;
     new_stats->cs_base = cs_base;
     new_stats->flags = flags;
+    new_stats->tbs = g_ptr_array_new();
+    qemu_mutex_init(&new_stats->jit_stats_lock);
 
     /*
      * All initialisation must be complete before we insert into qht
@@ -308,6 +310,7 @@ static TBStatistics *tb_get_stats(tb_page_addr_t phys_pc, target_ulong pc,
          * If there is already a TBStatistic for this TB from a previous flush
          * then just make the new TB point to the older TBStatistic
          */
+        g_ptr_array_free(new_stats->tbs, true);
         g_free(new_stats);
         return existing_stats;
     } else {
@@ -326,7 +329,6 @@ TranslationBlock *tb_gen_code(CPUState *cpu,
     tb_page_addr_t phys_pc;
     tcg_insn_unit *gen_code_buf;
     int gen_code_size, search_size, max_insns;
-    int64_t ti;
     void *host_pc;
 
     assert_memory_lock();
@@ -393,7 +395,7 @@ TranslationBlock *tb_gen_code(CPUState *cpu,
         tb->tb_stats = NULL;
     }
 
-    gen_code_size = setjmp_gen_code(env, tb, pc, host_pc, &max_insns, &ti);
+    gen_code_size = setjmp_gen_code(env, tb, pc, host_pc, &max_insns);
     if (unlikely(gen_code_size < 0)) {
         switch (gen_code_size) {
         case -1:
@@ -547,6 +549,29 @@ TranslationBlock *tb_gen_code(CPUState *cpu,
         return tb;
     }
 
+    /*
+     * Collect JIT stats when enabled. We batch them all up here to
+     * avoid spamming the cache with atomic accesses
+     */
+    if (tb_stats_enabled(tb, TB_JIT_STATS)) {
+        TBStatistics *ts = tb->tb_stats;
+        qemu_mutex_lock(&ts->jit_stats_lock);
+
+        ts->code.num_tcg_ops_opt += tcg_ctx->nb_ops;
+        ts->code.in_len += tb->size;
+        ts->code.out_len += tb->tc.size;
+        ts->code.search_out_len += search_size;
+
+        ts->translations.total++;
+        if (tb_page_addr1(tb) != -1) {
+            ts->translations.spanning++;
+        }
+
+        g_ptr_array_add(ts->tbs, tb);
+
+        qemu_mutex_unlock(&ts->jit_stats_lock);
+    }
+
     /*
      * Insert TB into the corresponding region tree before publishing it
      * through QHT. Otherwise rewinding happened in the TB might fail to
accel/tcg/translator.c +5 -0
index 80ffbfb455..2fcd8bba35 100644
@@ -147,6 +147,11 @@ void translator_loop(CPUState *cpu, TranslationBlock *tb, int *max_insns,
     tb->size = db->pc_next - db->pc_first;
     tb->icount = db->num_insns;
 
+    /* Save number of guest instructions for TB_JIT_STATS */
+    if (tb_stats_enabled(tb, TB_JIT_STATS)) {
+        tb->tb_stats->code.num_guest_inst += db->num_insns;
+    }
+
     if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)
         && qemu_log_in_addr_range(db->pc_first)) {
         FILE *logfile = qemu_log_trylock();
include/exec/tb-stats-flags.h +1 -0
index c0e63408e2..286ca93bcc 100644
@@ -13,6 +13,7 @@
 
 #define TB_NONE_STATS (0)  /* no stats */
 #define TB_EXEC_STATS (1 << 0)
+#define TB_JIT_STATS  (1 << 1)
 
 /* TBStatistic collection controls */
 void enable_collect_tb_stats(void);
include/exec/tb-stats.h +29 -0
index b935c3235a..6ed767f490 100644
@@ -54,6 +54,33 @@ struct TBStatistics {
         unsigned long atomic;
     } executions;
 
+    /* JIT Stats - protected by lock */
+    QemuMutex jit_stats_lock;
+
+    /* Sum of all operations for all translations */
+    struct {
+        unsigned num_guest_inst;
+        unsigned num_tcg_ops;
+        unsigned num_tcg_ops_opt;
+        unsigned spills;
+
+        unsigned temps;
+        unsigned deleted_ops;
+        unsigned in_len;
+        unsigned out_len;
+        unsigned search_out_len;
+    } code;
+
+    struct {
+        unsigned long total;
+        unsigned long spanning;
+    } translations;
+
+    /*
+     * All persistent (cached) TranslationBlocks using
+     * this TBStats structure. Has to be reset on a tb_flush.
+     */
+    GPtrArray *tbs;
 };
 
 bool tb_stats_cmp(const void *ap, const void *bp);
@@ -61,4 +88,6 @@ bool tb_stats_cmp(const void *ap, const void *bp);
 void init_tb_stats_htable(void);
 bool tb_stats_enabled(TranslationBlock *tb, uint32_t flag);
 
+void dump_jit_profile_info(GString *buf);
+
 #endif
include/tcg/tcg.h +10 -0
index da1c8fa3b5..276a4b60ad 100644
@@ -522,6 +522,14 @@ static inline TCGRegSet output_pref(const TCGOp *op, unsigned i)
     return i < ARRAY_SIZE(op->output_pref) ? op->output_pref[i] : 0;
 }
 
+/*
+ * The TCGProfile structure holds data for the lifetime of the translator.
+ */
+typedef struct TCGProfile {
+    /* Lifetime count of TCGOps per TCGContext when tb_stats enabled */
+    size_t table_op_count[NB_OPS];
+} TCGProfile;
+
 struct TCGContext {
     uint8_t *pool_cur, *pool_end;
     TCGPool *pool_first, *pool_current, *pool_first_large;
@@ -548,6 +556,8 @@ struct TCGContext {
     tcg_insn_unit *code_buf;      /* pointer for start of tb */
     tcg_insn_unit *code_ptr;      /* pointer for running end of tb */
 
+    TCGProfile prof;
+
 #ifdef CONFIG_DEBUG_TCG
     int goto_tb_issue_mask;
     const TCGOpcode *vecop_list;
tcg/tcg.c +44 -3

92 lines not on this page · raw message

Signature · 1 line
2.25.1
author
#5 lore raw

PATCH v15 5/10 monitor: adding tb_stats hmp command

In reply to Fei Wu

From: "Vanderson M. do Rosario" <[email protected]>

Adding tb_stats [start|stop|status] command to hmp. This allows controlling the collection of statistics. It is also possible to set the flag of collection:
all, jit, or exec.

The goal of this command is to allow the dynamic exploration of the TCG behavior and quality. Therefore, for now, a corresponding QMP command is not worthwhile.

Message-Id: <[email protected]>
Message-Id: <[email protected]>

[AJB: fix authorship]
---
 accel/tcg/monitor.c           | 100 ++++++++++++++++++++++++++++++++++
 accel/tcg/tb-stats.c          |  17 ++++++
 hmp-commands.hx               |  16 ++++++
 include/exec/tb-stats-flags.h |   1 +
 include/exec/tb-stats.h       |   4 ++
 include/monitor/hmp.h         |   1 +
 6 files changed, 139 insertions(+)
accel/tcg/monitor.c +100 -0
index 111ccbc4da..094150e4af 100644
@@ -11,13 +11,18 @@
 #include "qapi/error.h"
 #include "qapi/type-helpers.h"
 #include "qapi/qapi-commands-machine.h"
+#include "qapi/qmp/qdict.h"
 #include "monitor/monitor.h"
+#include "monitor/hmp.h"
 #include "sysemu/cpus.h"
 #include "sysemu/cpu-timers.h"
 #include "sysemu/tcg.h"
 #include "exec/tb-stats.h"
+#include "exec/tb-flush.h"
 #include "internal.h"
+#include "tb-context.h"
 
+enum TbstatsCmd { TBS_CMD_START, TBS_CMD_STOP, TBS_CMD_STATUS };
 
 static void dump_drift_info(GString *buf)
 {
@@ -86,6 +91,101 @@ HumanReadableText *qmp_x_query_opcount(Error **errp)
     return human_readable_text_from_str(buf);
 }
 
+struct TbstatsCommand {
+    enum TbstatsCmd cmd;
+    uint32_t flag;
+    Monitor *mon;
+};
+
+static void do_hmp_tbstats_safe(CPUState *cpu, run_on_cpu_data icmd)
+{
+    struct TbstatsCommand *cmdinfo = icmd.host_ptr;
+    int cmd = cmdinfo->cmd;
+    uint32_t flag = cmdinfo->flag;
+    Monitor *mon = cmdinfo->mon;
+
+    switch (cmd) {
+    case TBS_CMD_START:
+        if (tb_stats_collection_enabled()) {
+            monitor_printf(mon, "TB information already being recorded\n");
+            return;
+        }
+
+        qht_init(&tb_ctx.tb_stats, tb_stats_cmp, CODE_GEN_HTABLE_SIZE,
+                 QHT_MODE_AUTO_RESIZE);
+        set_tbstats_flag(flag);
+        enable_collect_tb_stats();
+        tb_flush(cpu);
+        break;
+    case TBS_CMD_STOP:
+        if (tb_stats_collection_disabled()) {
+            monitor_printf(mon, "TB information not being recorded\n");
+            return;
+        }
+
+        /* Dissalloc all TBStatistics structures and stop creating new ones */
+        disable_collect_tb_stats();
+        clean_tbstats();
+        tb_flush(cpu);
+        break;
+    case TBS_CMD_STATUS:
+        if (tb_stats_collection_enabled()) {
+            uint32_t flag = get_tbstats_flag();
+            monitor_printf(mon, "tb_stats is enabled with flag:\n");
+            monitor_printf(mon, "    EXEC: %d\n", !!(flag & TB_EXEC_STATS));
+            monitor_printf(mon, "     JIT: %d\n", !!(flag & TB_JIT_STATS));
+        } else {
+            monitor_printf(mon, "tb_stats is disabled\n");
+        }
+        break;
+    default: /* INVALID */
+        g_assert_not_reached();
+        break;
+    }
+
+    g_free(cmdinfo);
+}
+
+void hmp_tbstats(Monitor *mon, const QDict *qdict)
+{
+    if (!tcg_enabled()) {
+        monitor_printf(mon, "Only available with accel=tcg\n");
+        return;
+    }
+
+    char *cmd = (char *) qdict_get_try_str(qdict, "command");
+    enum TbstatsCmd icmd = -1;
+
+    if (strcmp(cmd, "start") == 0) {
+        icmd = TBS_CMD_START;
+    } else if (strcmp(cmd, "stop") == 0) {
+        icmd = TBS_CMD_STOP;
+    } else if (strcmp(cmd, "status") == 0) {
+        icmd = TBS_CMD_STATUS;
+    } else {
+        monitor_printf(mon, "Invalid command\n");
+        return;
+    }
+
+    char *sflag = (char *) qdict_get_try_str(qdict, "flag");
+    uint32_t flag = TB_EXEC_STATS | TB_JIT_STATS;
+    if (sflag) {
+        if (strcmp(sflag, "jit") == 0) {
+            flag = TB_JIT_STATS;
+        } else if (strcmp(sflag, "exec") == 0) {
+            flag = TB_EXEC_STATS;
+        }
+    }
+
+    struct TbstatsCommand *tbscommand = g_new0(struct TbstatsCommand, 1);
+    tbscommand->cmd = icmd;
+    tbscommand->flag = flag;
+    tbscommand->mon = mon;
+    async_safe_run_on_cpu(first_cpu, do_hmp_tbstats_safe,
+                          RUN_ON_CPU_HOST_PTR(tbscommand));
+
+}
+
 static void hmp_tcg_register(void)
 {
     monitor_register_hmp_info_hrt("jit", qmp_x_query_jit);
accel/tcg/tb-stats.c +17 -0
index 11322359c7..c90dde37d0 100644
@@ -91,6 +91,18 @@ void dump_jit_profile_info(GString *buf)
     g_free(jpi);
 }
 
+static void free_tbstats(void *p, uint32_t hash, void *userp)
+{
+    g_free(p);
+}
+
+void clean_tbstats(void)
+{
+    /* remove all tb_stats */
+    qht_iter(&tb_ctx.tb_stats, free_tbstats, NULL);
+    qht_destroy(&tb_ctx.tb_stats);
+}
+
 void init_tb_stats_htable(void)
 {
     if (!tb_ctx.tb_stats.map && tb_stats_collection_enabled()) {
@@ -115,6 +127,11 @@ bool tb_stats_collection_enabled(void)
     return tcg_collect_tb_stats == TB_STATS_RUNNING;
 }
 
+bool tb_stats_collection_disabled(void)
+{
+    return tcg_collect_tb_stats == TB_STATS_STOPPED;
+}
+
 uint32_t get_tbstats_flag(void)
 {
     return tbstats_flag;
hmp-commands.hx +16 -0
index 2cbd0f77a0..639e9d9e53 100644
@@ -1670,6 +1670,22 @@ SRST
   Executes a qemu-io command on the given block device.
 ERST
 
+#if defined(CONFIG_TCG)
+    {
+        .name       = "tb_stats",
+        .args_type  = "command:s,flag:s?",
+        .params     = "command [flag]",
+        .help       = "Control tb statistics collection:"
+                        "tb_stats (start|stop|status) [all|jit|exec]",
+        .cmd        = hmp_tbstats,
+    },
+#endif
+
+SRST
+``tb_stats`` *command* *flag*
+  Control recording tb statistics
+ERST
+
     {
         .name       = "qom-list",
         .args_type  = "path:s?",
include/exec/tb-stats-flags.h +1 -0
index 286ca93bcc..d8b844be99 100644
@@ -19,6 +19,7 @@
 void enable_collect_tb_stats(void);
 void disable_collect_tb_stats(void);
 bool tb_stats_collection_enabled(void);
+bool tb_stats_collection_disabled(void);
 
 uint32_t get_tbstats_flag(void);
 void set_tbstats_flag(uint32_t flag);
include/exec/tb-stats.h +4 -0
index 6ed767f490..e16f947410 100644
@@ -31,6 +31,8 @@
 #include "exec/tb-stats-flags.h"
 #include "tcg/tcg.h"
 
+enum SortBy { SORT_BY_HOTNESS, SORT_BY_HG /* Host/Guest */, SORT_BY_SPILLS };
+
 typedef struct TBStatistics TBStatistics;
 
 /*
@@ -90,4 +92,6 @@ bool tb_stats_enabled(TranslationBlock *tb, uint32_t flag);
 
 void dump_jit_profile_info(GString *buf);
 
+void clean_tbstats(void);
+
 #endif
include/monitor/hmp.h +1 -0
index 13f9a2dedb..2e7f141754 100644
@@ -181,5 +181,6 @@ void hmp_ioport_write(Monitor *mon, const QDict *qdict);
 void hmp_boot_set(Monitor *mon, const QDict *qdict);
 void hmp_info_mtree(Monitor *mon, const QDict *qdict);
 void hmp_info_cryptodev(Monitor *mon, const QDict *qdict);
+void hmp_tbstats(Monitor *mon, const QDict *qdict);
 
 #endif
Signature · 1 line
2.25.1
author
#6 lore raw

PATCH v15 6/10 tb-stats: reset the tracked TBs on a tb_flush

In reply to Fei Wu

From: Alex Bennée <[email protected]>

We keep track of translations but can only do so up until the translation cache is flushed. At that point we really have no idea if we can re-create a translation because all the active tracking information has been reset.

---
 accel/tcg/tb-maint.c    |  1 +
 accel/tcg/tb-stats.c    | 18 ++++++++++++++++++
 include/exec/tb-stats.h |  8 ++++++++
 3 files changed, 27 insertions(+)
accel/tcg/tb-maint.c +1 -0
index 0980fca358..11ff0ddd90 100644
@@ -763,6 +763,7 @@ static void do_tb_flush(CPUState *cpu, run_on_cpu_data tb_flush_count)
     qht_reset_size(&tb_ctx.htable, CODE_GEN_HTABLE_SIZE);
     tb_remove_all();
 
+    tbstats_reset_tbs();
     tcg_region_reset_all();
     /* XXX: flush processor icache at this point if cache flush is expensive */
     qatomic_inc(&tb_ctx.tb_flush_count);
accel/tcg/tb-stats.c +18 -0
index c90dde37d0..7c7f700c89 100644
@@ -103,6 +103,24 @@ void clean_tbstats(void)
     qht_destroy(&tb_ctx.tb_stats);
 }
 
+/*
+ * We have to reset the tbs array on a tb_flush as those
+ * TranslationBlocks no longer exist.
+ */
+
+static void reset_tbs_array(void *p, uint32_t hash, void *userp)
+{
+    TBStatistics *tbs = p;
+    g_ptr_array_set_size(tbs->tbs, 0);
+}
+
+void tbstats_reset_tbs(void)
+{
+    if (tb_ctx.tb_stats.map) {
+        qht_iter(&tb_ctx.tb_stats, reset_tbs_array, NULL);
+    }
+}
+
 void init_tb_stats_htable(void)
 {
     if (!tb_ctx.tb_stats.map && tb_stats_collection_enabled()) {
include/exec/tb-stats.h +8 -0
index e16f947410..77974b4b7f 100644
@@ -94,4 +94,12 @@ void dump_jit_profile_info(GString *buf);
 
 void clean_tbstats(void);
 
+/**
+ * tbstats_reset_tbs: reset the linked array of TBs
+ *
+ * Reset the list of tbs for a given array. Should be called from
+ * safe work during tb_flush.
+ */
+void tbstats_reset_tbs(void);
+
 #endif
Signature · 1 line
2.25.1
author
#7 lore raw

PATCH v15 7/10 tb-stats: Adding info [tb-list|tb] commands to HMP (WIP)

In reply to Fei Wu

From: "Vanderson M. do Rosario" <[email protected]>

These commands allow the exploration of TBs generated by the TCG. Understand which one hotter, with more guest/host instructions... and examine their guest, host and IR code.

The goal of this command is to allow the dynamic exploration of TCG behavior and code quality. Therefore, for now, a corresponding QMP command is not worthwhile.

[AJB: WIP - we still can't be safely sure a translation will succeed]

Example of output:

TB id:0 | phys:0x34d54 virt:0x0000000000034d54 flags:0x0000f0

	| exec:4828932/0 guest inst cov:16.38%
	| trans:1 ints: g:3 op:82 op_opt:34 spills:3
	| h/g (host bytes / guest insts): 90.666664

TB id:1 | phys:0x34d0d virt:0x0000000000034d0d flags:0x0000f0

	| exec:4825842/0 guest inst cov:21.82%
	| trans:1 ints: g:4 op:80 op_opt:38 spills:2
	| h/g (host bytes / guest insts): 84.000000

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

0x00034d0d:  89 de                    movl     %ebx, %esi
0x00034d0f:  26 8b 0e                 movl     %es:(%esi), %ecx
0x00034d12:  26 f6 46 08 80           testb    $0x80, %es:8(%esi)
0x00034d17:  75 3b                    jne      0x34d54

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

Message-Id: <[email protected]>

[AJB: fix authorship, dropped coverset]
---
 accel/tcg/monitor.c     |  69 ++++++++++++++++
 accel/tcg/tb-stats.c    | 176 ++++++++++++++++++++++++++++++++++++++++
 disas/disas.c           |   2 +
 hmp-commands-info.hx    |  16 ++++
 include/exec/tb-stats.h |  25 ++++++
 include/monitor/hmp.h   |   2 +
 6 files changed, 290 insertions(+)
accel/tcg/monitor.c +69 -0
index 094150e4af..d43c62b248 100644
@@ -8,17 +8,21 @@
 
 #include "qemu/osdep.h"
 #include "qemu/accel.h"
+#include "qemu/log.h"
 #include "qapi/error.h"
 #include "qapi/type-helpers.h"
 #include "qapi/qapi-commands-machine.h"
 #include "qapi/qmp/qdict.h"
 #include "monitor/monitor.h"
 #include "monitor/hmp.h"
+#include "monitor/hmp-target.h"
 #include "sysemu/cpus.h"
 #include "sysemu/cpu-timers.h"
 #include "sysemu/tcg.h"
 #include "exec/tb-stats.h"
 #include "exec/tb-flush.h"
+#include "disas/disas.h"
+#include "tb-context.h"
 #include "internal.h"
 #include "tb-context.h"
 
@@ -186,6 +190,71 @@ void hmp_tbstats(Monitor *mon, const QDict *qdict)
 
 }
 
+void hmp_info_tblist(Monitor *mon, const QDict *qdict)
+{
+    int number_int;
+    const char *sortedby_str = NULL;
+    g_autoptr(GString) buf = g_string_new("");
+
+    if (!tcg_enabled()) {
+        monitor_printf(mon, "Only available with accel=tcg\n");
+        return;
+    }
+    if (!tb_ctx.tb_stats.map) {
+        monitor_printf(mon, "no TB information recorded\n");
+        return;
+    }
+
+    number_int = qdict_get_try_int(qdict, "number", 10);
+    sortedby_str = qdict_get_try_str(qdict, "sortedby");
+
+    int sortedby = SORT_BY_HOTNESS;
+    if (sortedby_str == NULL || strcmp(sortedby_str, "hotness") == 0) {
+        sortedby = SORT_BY_HOTNESS;
+    } else if (strcmp(sortedby_str, "hg") == 0) {
+        sortedby = SORT_BY_HG;
+    } else if (strcmp(sortedby_str, "spills") == 0) {
+        sortedby = SORT_BY_SPILLS;
+    } else {
+        monitor_printf(mon, "valid sort options are: hotness hg spills\n");
+        return;
+    }
+
+    dump_tblist_info(buf, number_int, sortedby);
+    monitor_printf(mon, "%s", buf->str);
+}
+
+void hmp_info_tb(Monitor *mon, const QDict *qdict)
+{
+    const int id = qdict_get_int(qdict, "id");
+    g_autoptr(GString) buf = g_string_new("");
+
+    if (!tcg_enabled()) {
+        monitor_printf(mon, "Only available with accel=tcg\n");
+        return;
+    }
+
+    TBStatistics *tbs = get_tbstats_by_id(id);
+    if (tbs == NULL) {
+        monitor_printf(mon, "TB %d information is not recorded\n", id);
+        return;
+    }
+
+    monitor_printf(mon, "\n------------------------------\n\n");
+
+    int valid_tb_num = dump_tb_info(buf, tbs, id);
+    monitor_printf(mon, "%s", buf->str);
+
+    if (valid_tb_num > 0) {
+        unsigned num_inst = tbs->code.num_guest_inst / tbs->translations.total;
+
+        monitor_printf(mon, "\n----------------n\n");
+        // FIXME: cannot disas
+        monitor_disas(mon, mon_get_cpu(mon), tbs->phys_pc, num_inst, true);
+        monitor_printf(mon, "\n------------------------------\n\n");
+    }
+}
+
 static void hmp_tcg_register(void)
 {
     monitor_register_hmp_info_hrt("jit", qmp_x_query_jit);
accel/tcg/tb-stats.c +176 -0

215 lines not on this page · raw message

disas/disas.c +2 -0
index 0d2d06c2ec..3b19b51fca 100644
@@ -8,6 +8,8 @@
 #include "hw/core/cpu.h"
 #include "exec/memory.h"
 
+#include "qemu/log-for-trace.h"
+
 /* Filled in by elfload.c.  Simplistic, but will do for now. */
 struct syminfo *syminfos = NULL;
 
hmp-commands-info.hx +16 -0
index f5b37eb74a..ace1ecc3c5 100644
@@ -262,6 +262,22 @@ ERST
         .params     = "",
         .help       = "show dynamic compiler info",
     },
+    {
+        .name       = "tb-list",
+        .args_type  = "number:i?,sortedby:s?",
+        .params     = "[number sortedby]",
+        .help       = "show a [number] translated blocks sorted by [sortedby]"
+                      "sortedby opts: hotness hg spills",
+        .cmd        = hmp_info_tblist,
+    },
+    {
+        .name       = "tb",
+        .args_type  = "id:i,flags:s?",
+        .params     = "id [flag1,flag2,...]",
+        .help       = "show information about one translated block by id."
+                      "dump flags can be used to set dump code level: out_asm in_asm op",
+        .cmd        = hmp_info_tb,
+    },
 #endif
 
 SRST
include/exec/tb-stats.h +25 -0
index 77974b4b7f..4cdf41af6c 100644
@@ -54,6 +54,8 @@ struct TBStatistics {
     struct {
         unsigned long normal;
         unsigned long atomic;
+        /* filled only when dumping x% cover set */
+        uint16_t coverage;
     } executions;
 
     /* JIT Stats - protected by lock */
@@ -89,6 +91,7 @@ bool tb_stats_cmp(const void *ap, const void *bp);
 
 void init_tb_stats_htable(void);
 bool tb_stats_enabled(TranslationBlock *tb, uint32_t flag);
+bool tbs_stats_enabled(struct TBStatistics *tbs, uint32_t flag);
 
 void dump_jit_profile_info(GString *buf);
 
@@ -102,4 +105,26 @@ void clean_tbstats(void);
  */
 void tbstats_reset_tbs(void);
 
+/**
+ * dump_tbs_info: report the hottest blocks
+ *
+ * @buf: output buffer
+ * @total: the limit of hotblocks
+ * @sort_by: property in which the dump will be sorted
+ *
+ * Report the hottest blocks to either the log or monitor
+ */
+void dump_tblist_info(GString *buf, int total, int sort_by);
+
+/**
+ * dump_tb_info: dump information about one TB
+ *
+ * @buf: output buffer
+ * @tbs: the tbs to dump
+ * @id: the display id of the block (from previous search)
+ */
+int dump_tb_info(GString *buf, TBStatistics *tbs, int id);
+
+TBStatistics *get_tbstats_by_id(int id);
+
 #endif
include/monitor/hmp.h +2 -0
index 2e7f141754..acdd6f1561 100644
@@ -182,5 +182,7 @@ void hmp_boot_set(Monitor *mon, const QDict *qdict);
 void hmp_info_mtree(Monitor *mon, const QDict *qdict);
 void hmp_info_cryptodev(Monitor *mon, const QDict *qdict);
 void hmp_tbstats(Monitor *mon, const QDict *qdict);
+void hmp_info_tblist(Monitor *mon, const QDict *qdict);
+void hmp_info_tb(Monitor *mon, const QDict *qdict);
 
 #endif
Signature · 1 line
2.25.1
author
#8 lore raw

Re: [PATCH v15 07/10] tb-stats: Adding info [tb-list|tb] commands to HMP (WIP)

Quoted 21 lines · Fei Wu
accel/tcg/monitor.c +21 -0
+void hmp_info_tb(Monitor *mon, const QDict *qdict)
+{
+    const int id = qdict_get_int(qdict, "id");
+    g_autoptr(GString) buf = g_string_new("");
+
+    if (!tcg_enabled()) {
+        monitor_printf(mon, "Only available with accel=tcg\n");
+        return;
+    }
+
+    TBStatistics *tbs = get_tbstats_by_id(id);
+    if (tbs == NULL) {
+        monitor_printf(mon, "TB %d information is not recorded\n", id);
+        return;
+    }
+
+    monitor_printf(mon, "\n------------------------------\n\n");
+
+    int valid_tb_num = dump_tb_info(buf, tbs, id);
+    monitor_printf(mon, "%s", buf->str);
+

accel/tcg/monitor.c void hmp_tbstats(Monitor *mon, const QDict *qdict) · line 257

Quoted 10 lines
accel/tcg/monitor.c +10 -0
+    if (valid_tb_num > 0) {
+        unsigned num_inst = tbs->code.num_guest_inst / tbs->translations.total;
+
+        monitor_printf(mon, "\n----------------n\n");
+        // FIXME: cannot disas
+        monitor_disas(mon, mon_get_cpu(mon), tbs->phys_pc, num_inst, true);
+        monitor_printf(mon, "\n------------------------------\n\n");
+    }
+}
+

So far the following methods are candidates for monitor_disas:

1. still use ram_addr_t for tbs->phys_pc, and extend monitor_disas to support disassemble ram_addr_t by using qemu_map_ram_ptr(NULL, ram_addr) to convert it to hva first

2. use gpa for tbs->phys_pc, there is no need to change monitor_disas, but add another parameter for get_page_addr_code_hostp() to return extra gpa, probe_access_internal() has already returned CPUTLBEntryFull, so it's plain to get gpa here.

3. record gpa in another field of tbs, and keep tbs->phys_pc as it is, this is just a variation of #2.

I'm inclined to use method #2. I think gpa carries more information for debugging than ram_addr_t, guest can map gpa to the executable file etc., but it has little knowledge of ram_addr_t.

What do you suggest?

Thanks,
Fei.

#9 lore raw

Re: [PATCH v15 07/10] tb-stats: Adding info [tb-list|tb] commands to HMP (WIP)

Quoted 34 lines · Fei
Quoted 21 lines · Fei Wu
accel/tcg/monitor.c +21 -0
+void hmp_info_tb(Monitor *mon, const QDict *qdict)
+{
+    const int id = qdict_get_int(qdict, "id");
+    g_autoptr(GString) buf = g_string_new("");
+
+    if (!tcg_enabled()) {
+        monitor_printf(mon, "Only available with accel=tcg\n");
+        return;
+    }
+
+    TBStatistics *tbs = get_tbstats_by_id(id);
+    if (tbs == NULL) {
+        monitor_printf(mon, "TB %d information is not recorded\n", id);
+        return;
+    }
+
+    monitor_printf(mon, "\n------------------------------\n\n");
+
+    int valid_tb_num = dump_tb_info(buf, tbs, id);
+    monitor_printf(mon, "%s", buf->str);
+

accel/tcg/monitor.c void hmp_tbstats(Monitor *mon, const QDict *qdict) · line 257

Quoted 10 lines
accel/tcg/monitor.c +10 -0
+    if (valid_tb_num > 0) {
+        unsigned num_inst = tbs->code.num_guest_inst / tbs->translations.total;
+
+        monitor_printf(mon, "\n----------------n\n");
+        // FIXME: cannot disas
+        monitor_disas(mon, mon_get_cpu(mon), tbs->phys_pc, num_inst, true);
+        monitor_printf(mon, "\n------------------------------\n\n");
+    }
+}
+

So far the following methods are candidates for monitor_disas:

Quoted 8 lines

1. still use ram_addr_t for tbs->phys_pc, and extend monitor_disas to support disassemble ram_addr_t by using qemu_map_ram_ptr(NULL, ram_addr) to convert it to hva first

2. use gpa for tbs->phys_pc, there is no need to change monitor_disas, but add another parameter for get_page_addr_code_hostp() to return extra gpa, probe_access_internal() has already returned CPUTLBEntryFull, so it's plain to get gpa here.

No, we need the ram_addr_t for dirty-page handling in order to detect self-modifying code.
Leave tb->phys_pc alone.

r~

Quoted 13 lines

3. record gpa in another field of tbs, and keep tbs->phys_pc as it is, this is just a variation of #2.

I'm inclined to use method #2. I think gpa carries more information for debugging than ram_addr_t, guest can map gpa to the executable file etc., but it has little knowledge of ram_addr_t.

What do you suggest?

Thanks,
Fei.

author
#10 lore raw

Re: [PATCH v15 07/10] tb-stats: Adding info [tb-list|tb] commands to HMP (WIP)

Quoted 41 lines · Richard Henderson
Quoted 40 lines · Fei
Quoted 31 lines · Fei Wu
accel/tcg/monitor.c +23 -0
+void hmp_info_tb(Monitor *mon, const QDict *qdict)
+{
+    const int id = qdict_get_int(qdict, "id");
+    g_autoptr(GString) buf = g_string_new("");
+
+    if (!tcg_enabled()) {
+        monitor_printf(mon, "Only available with accel=tcg\n");
+        return;
+    }
+
+    TBStatistics *tbs = get_tbstats_by_id(id);
+    if (tbs == NULL) {
+        monitor_printf(mon, "TB %d information is not recorded\n", id);
+        return;
+    }
+
+    monitor_printf(mon, "\n------------------------------\n\n");
+
+    int valid_tb_num = dump_tb_info(buf, tbs, id);
+    monitor_printf(mon, "%s", buf->str);
+
+    if (valid_tb_num > 0) {
+        unsigned num_inst = tbs->code.num_guest_inst /

tbs->translations.total;
+
+        monitor_printf(mon, "\n----------------n\n");
+        // FIXME: cannot disas
+        monitor_disas(mon, mon_get_cpu(mon), tbs->phys_pc, num_inst, true);
+        monitor_printf(mon, "\n------------------------------\n\n"); +    }

Review

Quoted 2 lines
(quoted diff) +2 -0
+}
+

So far the following methods are candidates for monitor_disas:

1. still use ram_addr_t for tbs->phys_pc, and extend monitor_disas to support disassemble ram_addr_t by using qemu_map_ram_ptr(NULL, ram_addr) to convert it to hva first

Quoted 8 lines
Quoted 4 lines

2. use gpa for tbs->phys_pc, there is no need to change monitor_disas, but add another parameter for get_page_addr_code_hostp() to return extra gpa, probe_access_internal() has already returned CPUTLBEntryFull, so it's plain to get gpa here.

No, we need the ram_addr_t for dirty-page handling in order to detect self-modifying code.  Leave tb->phys_pc alone.

I mean return both ram_addr_t and gpa from get_page_addr_code_hostp(), tb->phys_pc will not be changed, I'm not going to change tbs->phys_pc either (like #3), the extra gpa will be saved in tbs for 'info tb' purpose.

In short, no change on phys_pc, but add gpa to tbs, sounds good?

Thanks,
Fei.

Quoted 17 lines

r~

Quoted 13 lines

3. record gpa in another field of tbs, and keep tbs->phys_pc as it is, this is just a variation of #2.

I'm inclined to use method #2. I think gpa carries more information for debugging than ram_addr_t, guest can map gpa to the executable file etc., but it has little knowledge of ram_addr_t.

What do you suggest?

Thanks,
Fei.

author
#11 lore raw

PATCH v15 8/10 debug: add -d tb_stats to control TBStatistics

In reply to Fei Wu

Capture TBS at startup instead of an explicit 'tb_stats start' command.

---
 include/exec/tb-stats-flags.h |  1 +
 include/qemu/log.h            |  1 +
 stubs/meson.build             |  1 +
 stubs/tb-stats.c              | 32 ++++++++++++++++++++++++++++++++
 util/log.c                    | 18 ++++++++++++++++++
 5 files changed, 53 insertions(+)
 create mode 100644 stubs/tb-stats.c
include/exec/tb-stats-flags.h +1 -0
index d8b844be99..936bd35707 100644
@@ -14,6 +14,7 @@
 #define TB_NONE_STATS (0)  /* no stats */
 #define TB_EXEC_STATS (1 << 0)
 #define TB_JIT_STATS  (1 << 1)
+#define TB_ALL_STATS  (TB_EXEC_STATS | TB_JIT_STATS)
 
 /* TBStatistic collection controls */
 void enable_collect_tb_stats(void);
include/qemu/log.h +1 -0
index c5643d8dd5..6f3b8091cd 100644
@@ -35,6 +35,7 @@ bool qemu_log_separate(void);
 /* LOG_STRACE is used for user-mode strace logging. */
 #define LOG_STRACE         (1 << 19)
 #define LOG_PER_THREAD     (1 << 20)
+#define CPU_LOG_TB_STATS   (1 << 21)
 
 /* Lock/unlock output. */
 
stubs/meson.build +1 -0
index a56645e2f7..e926649d40 100644
@@ -65,3 +65,4 @@ else
 endif
 stub_ss.add(files('semihost-all.c'))
 stub_ss.add(when: 'CONFIG_VFIO_USER_SERVER', if_false: files('vfio-user-obj.c'))
+stub_ss.add(files('tb-stats.c'))
stubs/tb-stats.c new file +32 -0
new file mode 100644
index 0000000000..38ee12313e
@@ -0,0 +1,32 @@
+/*
+ * TB Stats Stubs
+ *
+ * Copyright (c) 2019
+ * Written by Alex Bennée <[email protected]>
+ *
+ * This code is licensed under the GNU GPL v2, or later.
+ */
+
+
+#include "qemu/osdep.h"
+#include "exec/tb-stats-flags.h"
+
+void enable_collect_tb_stats(void)
+{
+    return;
+}
+
+void disable_collect_tb_stats(void)
+{
+    return;
+}
+
+bool tb_stats_collection_enabled(void)
+{
+    return false;
+}
+
+void set_tbstats_flag(uint32_t flag)
+{
+    return;
+}
util/log.c +18 -0
index 53b4f6c58e..419f02c380 100644
@@ -27,6 +27,7 @@
 #include "qemu/thread.h"
 #include "qemu/lockable.h"
 #include "qemu/rcu.h"
+#include "exec/tb-stats-flags.h"
 #ifdef CONFIG_LINUX
 #include <sys/syscall.h>
 #endif
@@ -495,6 +496,8 @@ const QEMULogItem qemu_log_items[] = {
       "log every user-mode syscall, its input, and its result" },
     { LOG_PER_THREAD, "tid",
       "open a separate log file per thread; filename must contain '%d'" },
+    { CPU_LOG_TB_STATS, "tb_stats_{all,jit,exec}",
+      "enable collection of TBs statistics at startup" },
     { 0, NULL, NULL },
 };
 
@@ -516,6 +519,21 @@ int qemu_str_to_log_mask(const char *str)
             trace_enable_events((*tmp) + 6);
             mask |= LOG_TRACE;
 #endif
+        } else if (g_str_has_prefix(*tmp, "tb_stats_")) {
+            char *p = *tmp + 9;
+            uint32_t flag = TB_NONE_STATS;
+            if (g_str_has_prefix(p, "all")) {
+                flag = TB_ALL_STATS;
+            } else if (g_str_has_prefix(p, "jit")) {
+                flag = TB_JIT_STATS;
+            } else if (g_str_has_prefix(p, "exec")) {
+                flag = TB_EXEC_STATS;
+            }
+            if (flag != TB_NONE_STATS) {
+                mask |= CPU_LOG_TB_STATS;
+                set_tbstats_flag(flag);
+                enable_collect_tb_stats();
+            }
         } else {
             for (item = qemu_log_items; item->mask != 0; item++) {
                 if (g_str_equal(*tmp, item->name)) {
Signature · 1 line
2.25.1
author
#12 lore raw

PATCH v15 9/10 tb-stats: dump hot TBs at the end of the execution

In reply to Fei Wu

Dump the hottest TBs if -d tb_stats_{all,jit,exec}[:dump_num_at_exit]

---
 accel/tcg/tb-stats.c          | 21 +++++++++++++++++++++
 include/exec/tb-stats-dump.h  | 21 +++++++++++++++++++++
 include/exec/tb-stats-flags.h |  1 +
 linux-user/exit.c             |  2 ++
 softmmu/runstate.c            |  2 ++
 stubs/tb-stats.c              |  4 ++++
 util/log.c                    | 12 ++++++++++--
 7 files changed, 61 insertions(+), 2 deletions(-)
 create mode 100644 include/exec/tb-stats-dump.h
accel/tcg/tb-stats.c +21 -0
index 53a4f448dc..a5fc3c1c74 100644
@@ -17,6 +17,7 @@
 #include "qemu/log.h"
 
 #include "exec/tb-stats.h"
+#include "exec/tb-stats-dump.h"
 #include "tb-context.h"
 
 #include "internal.h"
@@ -29,6 +30,7 @@ enum TBStatsStatus {
 
 static enum TBStatsStatus tcg_collect_tb_stats;
 static uint32_t tbstats_flag;
+static int max_dump_tbs;
 
 static GPtrArray *last_search;
 
@@ -299,6 +301,20 @@ void dump_tblist_info(GString *buf, int total, int sort_by)
     }
 }
 
+/*
+ * Dump the final stats
+ */
+void tb_stats_dump(void)
+{
+    if (!tb_stats_collection_enabled()) {
+        return;
+    }
+
+    g_autoptr(GString) buf = g_string_new("");
+    dump_tblist_info(buf, max_dump_tbs, SORT_BY_HOTNESS);
+    qemu_printf("%s", buf->str);
+}
+
 void enable_collect_tb_stats(void)
 {
     tcg_collect_tb_stats = TB_STATS_RUNNING;
@@ -342,3 +358,8 @@ bool tbs_stats_enabled(struct TBStatistics *tbs, uint32_t flag)
     return tb_stats_collection_enabled() &&
            (tbstats_flag & flag);
 }
+
+void set_tbstats_max_tbs(int max)
+{
+    max_dump_tbs = max;
+}
include/exec/tb-stats-dump.h new file +21 -0
new file mode 100644
index 0000000000..197c6148e9
@@ -0,0 +1,21 @@
+/*
+ * TB Stats common dump functions across sysemu/linux-user
+ *
+ * Copyright (c) 2019 Linaro
+ *
+ * SPDX-License-Identifier: GPL-3.0-or-later
+ */
+
+#ifndef _TB_STATS_DUMP_H_
+#define _TB_STATS_DUMP_H_
+
+/**
+ * tb_stats_dump: dump final tb_stats at end of execution
+ */
+#ifdef CONFIG_TCG
+void tb_stats_dump(void);
+#else
+static inline void tb_stats_dump(void) { /* do nothing */ };
+#endif
+
+#endif /* _TB_STATS_DUMP_H_ */
include/exec/tb-stats-flags.h +1 -0
index 936bd35707..52d0429eeb 100644
@@ -24,5 +24,6 @@ bool tb_stats_collection_disabled(void);
 
 uint32_t get_tbstats_flag(void);
 void set_tbstats_flag(uint32_t flag);
+void set_tbstats_max_tbs(int max);
 
 #endif
linux-user/exit.c +2 -0
index 3017d28a3c..4fd23bcf60 100644
@@ -25,6 +25,7 @@
 #ifdef CONFIG_GPROF
 #include <sys/gmon.h>
 #endif
+#include "exec/tb-stats-dump.h"
 
 #ifdef CONFIG_GCOV
 extern void __gcov_dump(void);
@@ -41,4 +42,5 @@ void preexit_cleanup(CPUArchState *env, int code)
         gdb_exit(code);
         qemu_plugin_user_exit();
         perf_exit();
+        tb_stats_dump();
 }
softmmu/runstate.c +2 -0
index bd50062ed0..156156815b 100644
@@ -30,6 +30,7 @@
 #include "crypto/cipher.h"
 #include "crypto/init.h"
 #include "exec/cpu-common.h"
+#include "exec/tb-stats-dump.h"
 #include "gdbstub/syscalls.h"
 #include "hw/boards.h"
 #include "migration/misc.h"
@@ -818,6 +819,7 @@ void qemu_cleanup(void)
     vm_shutdown();
     replay_finish();
 
+    tb_stats_dump();
     job_cancel_sync_all();
     bdrv_close_all();
 
stubs/tb-stats.c +4 -0
index 38ee12313e..78ae1aa217 100644
@@ -30,3 +30,7 @@ void set_tbstats_flag(uint32_t flag)
 {
     return;
 }
+
+void set_tbstats_max_tbs(int max) {
+    return;
+}
util/log.c +10 -2
index 419f02c380..ae5398fb69 100644
@@ -496,8 +496,9 @@ const QEMULogItem qemu_log_items[] = {
       "log every user-mode syscall, its input, and its result" },
     { LOG_PER_THREAD, "tid",
       "open a separate log file per thread; filename must contain '%d'" },
-    { CPU_LOG_TB_STATS, "tb_stats_{all,jit,exec}",
-      "enable collection of TBs statistics at startup" },
+    { CPU_LOG_TB_STATS, "tb_stats_{all,jit,exec}[:dump_num_at_exit]",
+      "enable collection of TBs statistics at startup "
+      "and dump at exit until given a limit" },
     { 0, NULL, NULL },
 };
 
@@ -524,16 +525,23 @@ int qemu_str_to_log_mask(const char *str)
             uint32_t flag = TB_NONE_STATS;
             if (g_str_has_prefix(p, "all")) {
                 flag = TB_ALL_STATS;
+                p += 3;
             } else if (g_str_has_prefix(p, "jit")) {
                 flag = TB_JIT_STATS;
+                p += 3;
             } else if (g_str_has_prefix(p, "exec")) {
                 flag = TB_EXEC_STATS;
+                p += 4;
             }
             if (flag != TB_NONE_STATS) {
                 mask |= CPU_LOG_TB_STATS;
                 set_tbstats_flag(flag);
                 enable_collect_tb_stats();
             }
+            if (p[0] == ':') {
+                int max_to_dump = atoi(p + 1);
+                set_tbstats_max_tbs(max_to_dump);
+            }
         } else {
             for (item = qemu_log_items; item->mask != 0; item++) {
                 if (g_str_equal(*tmp, item->name)) {
Signature · 1 line
2.25.1
author
#13 lore raw

PATCH v15 10/10 docs: add tb-stats how to

In reply to Fei Wu
---
 docs/devel/tcg-tbstats.rst | 97 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 97 insertions(+)
 create mode 100644 docs/devel/tcg-tbstats.rst
docs/devel/tcg-tbstats.rst new file +97 -0
new file mode 100644
index 0000000000..dd611e41f3
@@ -0,0 +1,97 @@
+============
+TBStatistics
+============
+
+What is TBStatistics
+====================
+
+TBStatistics (tb_stats) is a tool to gather various internal information of TCG
+during binary translation, this allows us to identify such as hottest TBs,
+guest to host instruction translation ratio, number of spills during register
+allocation and more.
+
+
+How to use TBStatistics
+=======================
+
+1. HMP interface
+----------------
+
+TBStatistics provides HMP interface, you can try the following examples after
+connecting to the monitor.
+
+* First check the help info::
+
+    (qemu) help tb_stats
+    tb_stats command [flag] -- Control tb statistics collection:tb_stats (start|stop|status) [all|jit|exec]
+
+    (qemu) help info tb-list
+    info tb-list [number sortedby] -- show a [number] translated blocks sorted by [sortedby]sortedby opts: hotness hg spills
+
+    (qemu) help info tb
+    info tb id [flag1,flag2,...] -- show information about one translated block by id.dump flags can be used to set dump code level: out_asm in_asm op
+
+* Enable TBStatistics::
+
+    (qemu) tb_stats start all
+    (qemu)
+
+* Get interested TB list::
+
+    (qemu) info tb-list 2
+    TB id:0 | phys:0x79bca0 virt:0xffffffff8059bca0 flags:0x01024001 0 inv/1
+            | exec:1464084/0 guest inst cov:0.15%
+            | trans:1 ints: g:3 op:16 op_opt:15 spills:0
+            | h/g (host bytes / guest insts): 64.000000
+
+    TB id:1 | phys:0x2adf0c virt:0xffffffff800adf0c flags:0x01024001 0 inv/1
+            | exec:1033298/0 guest inst cov:0.28%
+            | trans:1 ints: g:8 op:35 op_opt:33 spills:0
+            | h/g (host bytes / guest insts): 86.000000
+
+* Dive into the specific TB::
+
+    (qemu) info tb 1
+    ------------------------------
+
+    TB id:0 | phys:0x79bca0 virt:0xffffffff8059bca0 flags:0x01024001 7 inv/19
+            | exec:2038349/0 guest inst cov:0.15%
+            | trans:19 ints: g:3 op:16 op_opt:15 spills:0
+            | h/g (host bytes / guest insts): 64.000000
+
+    ------------------------------
+
+* Stop TBStatistics after investigation, this will disable TBStatistics completely.::
+
+    (qemu) tb_stats stop
+    (qemu)
+
+* Definitely, TBStatistics can be restarted for another round of investigation.::
+
+    (qemu) tb_stats start all
+    (qemu)
+
+
+2. Dump at exit
+---------------
+
+New command line options have been added to enable dump TB information at exit:::
+
+    -d tb_stats_{all,jit,exec}[:dump_num_at_exit]
+
+e.g. starting qemu like this:::
+
+    -d tb_stats_all:2
+
+Qemu prints the following at exit:::
+
+    QEMU: Terminated
+    TB id:1 | phys:0x61be02 virt:0xffffffff8041be02 flags:0x01024001 0 inv/1
+            | exec:72739176/0 guest inst cov:20.22%
+            | trans:1 ints: g:9 op:35 op_opt:33 spills:0
+            | h/g (host bytes / guest insts): 51.555557
+
+    TB id:2 | phys:0x61bc66 virt:0xffffffff8041bc66 flags:0x01024001 0 inv/1
+            | exec:25069507/0 guest inst cov:0.77%
+            | trans:1 ints: g:1 op:15 op_opt:14 spills:0
+            | h/g (host bytes / guest insts): 128.000000
Signature · 1 line
2.25.1
author
#14 lore raw
In reply to Fei Wu
Quoted 9 lines · Fei Wu

v15
---
This is a large change:
* remove all time related stuffs, including cmd 'info profile'
* remove the per-TB flag, use global flag instead
* remove tb_stats pause/filter, but add status
* remove qemu_log changes, and use monitor_printf
* use array instead of list for sorting
* remove async_safe_run_on_cpu for cmd info tb-list & tb

I didn't realize async_safe_run_on_cpu has such a strong semantics, I will add it back if it's necessary.

Thanks,
Fei.

Quoted 64 lines

* use monitor_disas instead of regenerate TB, but **doesn't work yet**
* other cleanups

Alex Bennée (1):
tb-stats: reset the tracked TBs on a tb_flush

Fei Wu (5):
accel/tcg: remove CONFIG_PROFILER accel/tcg: add jit stats to TBStatistics
debug: add -d tb_stats to control TBStatistics
tb-stats: dump hot TBs at the end of the execution
docs: add tb-stats how to

Vanderson M. do Rosario (4):
accel/tcg: introduce TBStatistics structure
accel: collecting TB execution count
monitor: adding tb_stats hmp command
tb-stats: Adding info [tb-list|tb] commands to HMP (WIP)

 MAINTAINERS                   |   1 +
 accel/tcg/cpu-exec.c          |   6 +
 accel/tcg/meson.build         |   1 +
 accel/tcg/monitor.c           | 184 +++++++++++++++--
 accel/tcg/tb-context.h        |   1 +
 accel/tcg/tb-hash.h           |   7 +
 accel/tcg/tb-maint.c          |  20 ++
 accel/tcg/tb-stats.c          | 365 ++++++++++++++++++++++++++++++++++
 accel/tcg/tcg-accel-ops.c     |  10 -
 accel/tcg/tcg-runtime.c       |   1 +
 accel/tcg/translate-all.c     | 110 ++++++----
 accel/tcg/translator.c        |  30 +++
 disas/disas.c                 |   2 +
 docs/devel/tcg-tbstats.rst    |  97 +++++++++
 hmp-commands-info.hx          |  31 +--
 hmp-commands.hx               |  16 ++
 include/exec/exec-all.h       |   3 +
 include/exec/gen-icount.h     |   1 +
 include/exec/tb-stats-dump.h  |  21 ++
 include/exec/tb-stats-flags.h |  29 +++
 include/exec/tb-stats.h       | 130 ++++++++++++
 include/monitor/hmp.h         |   3 +
 include/qemu/log.h            |   1 +
 include/qemu/timer.h          |   9 -
 include/tcg/tcg.h             |  26 +--
 linux-user/exit.c             |   2 +
 meson.build                   |   2 -
 meson_options.txt             |   2 -
 qapi/machine.json             |  18 --
 scripts/meson-buildoptions.sh |   3 -
 softmmu/runstate.c            |  11 +-
 stubs/meson.build             |   1 +
 stubs/tb-stats.c              |  36 ++++
 tcg/tcg.c                     | 237 +++-------------------
 tests/qtest/qmp-cmd-test.c    |   3 -
 util/log.c                    |  26 +++
 36 files changed, 1093 insertions(+), 353 deletions(-)
 create mode 100644 accel/tcg/tb-stats.c
 create mode 100644 docs/devel/tcg-tbstats.rst
 create mode 100644 include/exec/tb-stats-dump.h
 create mode 100644 include/exec/tb-stats-flags.h
 create mode 100644 include/exec/tb-stats.h
 create mode 100644 stubs/tb-stats.c
author
#15 lore raw
In reply to Fei Wu
Quoted 12 lines · Fei Wu

v15
---
This is a large change:
* remove all time related stuffs, including cmd 'info profile'
* remove the per-TB flag, use global flag instead
* remove tb_stats pause/filter, but add status
* remove qemu_log changes, and use monitor_printf
* use array instead of list for sorting
* remove async_safe_run_on_cpu for cmd info tb-list & tb
* use monitor_disas instead of regenerate TB, but **doesn't work yet**
* other cleanups

Hi Richard,

Could you please take a look at this series? I hope most of the comments on v14 have been addressed.

Next revision I will change:
* add async_safe_run_on_cpu back in case of any concurrency issue
* add tbs->gpa_pc for monitor_disas, which requires get_page_addr_code_hostp() return both ram_addr_t and gpa
* finalize the commit logs and documents

Thanks,
Fei.

Quoted 61 lines

Alex Bennée (1):
tb-stats: reset the tracked TBs on a tb_flush

Fei Wu (5):
accel/tcg: remove CONFIG_PROFILER accel/tcg: add jit stats to TBStatistics
debug: add -d tb_stats to control TBStatistics
tb-stats: dump hot TBs at the end of the execution
docs: add tb-stats how to

Vanderson M. do Rosario (4):
accel/tcg: introduce TBStatistics structure
accel: collecting TB execution count
monitor: adding tb_stats hmp command
tb-stats: Adding info [tb-list|tb] commands to HMP (WIP)

 MAINTAINERS                   |   1 +
 accel/tcg/cpu-exec.c          |   6 +
 accel/tcg/meson.build         |   1 +
 accel/tcg/monitor.c           | 184 +++++++++++++++--
 accel/tcg/tb-context.h        |   1 +
 accel/tcg/tb-hash.h           |   7 +
 accel/tcg/tb-maint.c          |  20 ++
 accel/tcg/tb-stats.c          | 365 ++++++++++++++++++++++++++++++++++
 accel/tcg/tcg-accel-ops.c     |  10 -
 accel/tcg/tcg-runtime.c       |   1 +
 accel/tcg/translate-all.c     | 110 ++++++----
 accel/tcg/translator.c        |  30 +++
 disas/disas.c                 |   2 +
 docs/devel/tcg-tbstats.rst    |  97 +++++++++
 hmp-commands-info.hx          |  31 +--
 hmp-commands.hx               |  16 ++
 include/exec/exec-all.h       |   3 +
 include/exec/gen-icount.h     |   1 +
 include/exec/tb-stats-dump.h  |  21 ++
 include/exec/tb-stats-flags.h |  29 +++
 include/exec/tb-stats.h       | 130 ++++++++++++
 include/monitor/hmp.h         |   3 +
 include/qemu/log.h            |   1 +
 include/qemu/timer.h          |   9 -
 include/tcg/tcg.h             |  26 +--
 linux-user/exit.c             |   2 +
 meson.build                   |   2 -
 meson_options.txt             |   2 -
 qapi/machine.json             |  18 --
 scripts/meson-buildoptions.sh |   3 -
 softmmu/runstate.c            |  11 +-
 stubs/meson.build             |   1 +
 stubs/tb-stats.c              |  36 ++++
 tcg/tcg.c                     | 237 +++-------------------
 tests/qtest/qmp-cmd-test.c    |   3 -
 util/log.c                    |  26 +++
 36 files changed, 1093 insertions(+), 353 deletions(-)
 create mode 100644 accel/tcg/tb-stats.c
 create mode 100644 docs/devel/tcg-tbstats.rst
 create mode 100644 include/exec/tb-stats-dump.h
 create mode 100644 include/exec/tb-stats-flags.h
 create mode 100644 include/exec/tb-stats.h
 create mode 100644 stubs/tb-stats.c
author
#16 lore raw
Quoted 15 lines · Fei
Quoted 12 lines · Fei Wu

v15
---
This is a large change:
* remove all time related stuffs, including cmd 'info profile'
* remove the per-TB flag, use global flag instead
* remove tb_stats pause/filter, but add status
* remove qemu_log changes, and use monitor_printf
* use array instead of list for sorting
* remove async_safe_run_on_cpu for cmd info tb-list & tb
* use monitor_disas instead of regenerate TB, but **doesn't work yet**
* other cleanups

Hi Richard,

Quoted 9 lines

Could you please take a look at this series? I hope most of the comments on v14 have been addressed.

Next revision I will change:
* add async_safe_run_on_cpu back in case of any concurrency issue
* add tbs->gpa_pc for monitor_disas, which requires get_page_addr_code_hostp() return both ram_addr_t and gpa
* finalize the commit logs and documents

Should I send the new revision with these changes, or you take a look first then I address all of them together?

Thanks,
Fei.

Quoted 65 lines

Thanks,
Fei.

Quoted 61 lines

Alex Bennée (1):
tb-stats: reset the tracked TBs on a tb_flush

Fei Wu (5):
accel/tcg: remove CONFIG_PROFILER accel/tcg: add jit stats to TBStatistics
debug: add -d tb_stats to control TBStatistics
tb-stats: dump hot TBs at the end of the execution
docs: add tb-stats how to

Vanderson M. do Rosario (4):
accel/tcg: introduce TBStatistics structure
accel: collecting TB execution count
monitor: adding tb_stats hmp command
tb-stats: Adding info [tb-list|tb] commands to HMP (WIP)

 MAINTAINERS                   |   1 +
 accel/tcg/cpu-exec.c          |   6 +
 accel/tcg/meson.build         |   1 +
 accel/tcg/monitor.c           | 184 +++++++++++++++--
 accel/tcg/tb-context.h        |   1 +
 accel/tcg/tb-hash.h           |   7 +
 accel/tcg/tb-maint.c          |  20 ++
 accel/tcg/tb-stats.c          | 365 ++++++++++++++++++++++++++++++++++
 accel/tcg/tcg-accel-ops.c     |  10 -
 accel/tcg/tcg-runtime.c       |   1 +
 accel/tcg/translate-all.c     | 110 ++++++----
 accel/tcg/translator.c        |  30 +++
 disas/disas.c                 |   2 +
 docs/devel/tcg-tbstats.rst    |  97 +++++++++
 hmp-commands-info.hx          |  31 +--
 hmp-commands.hx               |  16 ++
 include/exec/exec-all.h       |   3 +
 include/exec/gen-icount.h     |   1 +
 include/exec/tb-stats-dump.h  |  21 ++
 include/exec/tb-stats-flags.h |  29 +++
 include/exec/tb-stats.h       | 130 ++++++++++++
 include/monitor/hmp.h         |   3 +
 include/qemu/log.h            |   1 +
 include/qemu/timer.h          |   9 -
 include/tcg/tcg.h             |  26 +--
 linux-user/exit.c             |   2 +
 meson.build                   |   2 -
 meson_options.txt             |   2 -
 qapi/machine.json             |  18 --
 scripts/meson-buildoptions.sh |   3 -
 softmmu/runstate.c            |  11 +-
 stubs/meson.build             |   1 +
 stubs/tb-stats.c              |  36 ++++
 tcg/tcg.c                     | 237 +++-------------------
 tests/qtest/qmp-cmd-test.c    |   3 -
 util/log.c                    |  26 +++
 36 files changed, 1093 insertions(+), 353 deletions(-)
 create mode 100644 accel/tcg/tb-stats.c
 create mode 100644 docs/devel/tcg-tbstats.rst
 create mode 100644 include/exec/tb-stats-dump.h
 create mode 100644 include/exec/tb-stats-flags.h
 create mode 100644 include/exec/tb-stats.h
 create mode 100644 stubs/tb-stats.c