accel/tcg: cut per-block dispatch overhead
Subsystems (2)
v3 cover accel/tcg: cut per-block dispatch overhead
For guests running large amounts of code, most of what TCG executes is not translated guest work but the fixed overhead around it. Blocks are short and there are a great many of them, so the constant cost at each end of a block (the interrupt poll and the can_do_io stores on entry, the dispatch on exit) ends up dominating everything else.
The workload throughout is qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host, in a --static --enable-lto --target-list=alpha-linux-user build. It executes 34.2 billion TBs at 6.04 guest instructions each, and 24.6% of its TB exits cannot use goto_tb. That is a representative shape for any guest whose text is much larger than a page: indirect calls and returns everywhere, plus direct branches that merely crossed a page boundary.
The first three patches are ordinary cleanups that stand on their own; patch 3 picked up review tags in v2. The remaining four are marked RFC individually and are where the interesting questions are.
1 accel/tcg: fold the dynamic cflags into CPUState::tcg_cflags
curr_cflags() recomputed three unlikely tests on every one of the run's 8.4 billion dispatches, from state that changes only when gdb enables single-step, when one-insn-per-tb is toggled, or when the log mask
moves. Fold each into tcg_cflags where it changes. -5.15%
2 accel/tcg: enlarge the TB jump cache to 64K entries
4096 entries is too small for a guest running a large program; tb_htable_lookup() is 6.10% of samples. 16 bits is the knee of the
sizing curve, at 1 MiB per vCPU. -5.92%, -8.71% wall
3 accel/tcg: skip the can_do_io stores in user-only builds
Two stores per TB that nothing in a user-only build reads: 68 billion
of them over the run. -4.57%, -4.53% wall
4 RFC: tcg: probe the TB jump cache inline instead of calling a helper
95.8% of those 8.4 billion helper_lookup_tb_ptr() calls hit the jump cache. Emit the probe inline (hash, four guarded loads, goto_ptr) and
call the helper only on a miss. -34.67%, -25.94% wall
5 RFC: accel/tcg: allow cross-page goto_tb chaining in user-only builds
translator_use_goto_tb() refuses to chain across a page. In user-only builds the invalidation path already covers what that was protecting
against: every mmap/mprotect/munmap reaches page_set_flags(), which invalidates and unlinks. Lift it there for runs that can never acquire
a breakpoint, keep it for system mode. -2.75%, -4.84% wall
6 RFC: accel/tcg: poison the jump cache instead of polling for indirect
exits
A block only needs the icount_decr poll if it can leave by goto_tb; every other exit already passes through a dispatch. Give the inline probe its own jump cache base pointer and point it at zeroes when an exit is requested, so every dispatch misses into the helper, which returns the epilogue. Emit the poll only in blocks that emitted a
goto_tb. -2.52%, -1.96% wall
7 RFC: tcg: fold a guest displacement into the host addressing mode
tcg_gen_qemu_ld/st cannot express a based access, so a target with a displacement in its encodings materializes the address with an lea that the host addressing mode would have done for free. Fold a preceding constant add into a new argument on the op, opt-in per
backend, wired up for x86_64 user-only. -5.70%, -3.20% wall
Each percentage is against the patch before it. Every stage was measured in one session on the same host, so end to end, from an unmodified LTO build of the same base to the full series:
instructions retired: 1,646,994,254,249 -> 819,262,147,022 -50.26%
wall clock: 133.19s -> 77.30s -41.96%The two figures do not track each other, and that is the interesting part:
what the series removes is cheap, well-predicted, highly pipelined work, so it retires far more instructions than it saves time. Patch 4 also cuts L1 icache load misses by 39.0%, because a dispatch no longer jumps into qemu's .text and evicts translated code; qemu's own .text falls from 38.8% to 5.3% of profile samples.
Every revision was built and measured separately, so the series bisects, and the emulated compiler produces byte-identical assembly output at every step, which is the correctness check these patches most need. Three new alpha tests cover the hazards the series creates: tests/tcg/alpha/test-xpage-chain.c and tests/tcg/alpha/gdbstub/xpage-bp.py (patch 5) and test-indirect-irq.c (patch 6). Each fails or hangs if the mechanism it covers is removed, which is what makes them tests of the new behavior rather than of the old.
Changes since v2
================
The biggest change is that "RFC: accel/tcg: only poll for interrupts in blocks that can close a cycle" is dropped. Richard pointed out that it let a straight-line run of arbitrary length go unchecked, since a block with no backward edge polled nowhere. Patch 6 now keeps the poll where a block can leave by goto_tb and relies on the dispatch everywhere else, which holds the one-block bound without any analysis of the guest's control flow graph. All of v2's measurements for that patch were taken with the dropped patch underneath and have been replaced by a fresh measurement of the series as it now stands.
1 Rewritten as folding the dynamic bits into CPUState::tcg_cflags where
they change, rather than caching curr_cflags() in a second field. Monitor-side updates ('one-insn-per-tb on', 'log nochain') are queued with async_safe_run_on_cpu() so each CPU writes its own cflags.
2 Sizing curve re-measured on top of the new patch 1, now with wall clock
alongside instructions retired.
3 Back to #ifndef CONFIG_USER_ONLY. QEMU's IS_ENABLED() is IS_EMPTY(),
true only for a symbol Meson defines empty, and CONFIG_USER_ONLY is defined as 1, so v2's test was always false and the stores were emitted after all. Review tags carried over; the numbers are from the working form.
4 Folded into tcg_gen_lookup_and_goto_ptr() instead of adding a second
entry point beside it (Richard), which changed all 38 call sites. cs_base is compared too, which is what lets the probe be enabled generically rather than per target. Audited which targets may pass a real PC: five do, the rest pass NULL and keep the helper call. The breakpoint poison now happens in cpu_breakpoint_insert() rather than only from the poisoned CPU's own main loop, since a thread dispatching indirectly need never reach that loop.
5 Only take the shortcut when no gdbstub was requested: the same-page rule
also forces a breakpoint check on entry to every page, and without that a chain established earlier runs past a breakpoint set later. Reported by Richard. Changed translator_use_goto_tb() rather than translator_is_same_page(), which i386, riscv and s390x use for something else and which v2 perturbed as a side effect. Added the gdbstub half of the test.
6 Rebased onto the removal described above, with the deferred-emission
machinery moved here from the dropped patch, and re-measured.
7 Unchanged in substance, re-measured on the new baseline.
What I would most like reviewed
===============================
- Patch 5 reverses a deliberate decision made in d3a2a1d803 on the strength of an argument about the user-only invalidation paths, plus a gate on whether gdb can ever attach.
- Patch 6's un-poison in the main loop races a concurrent poison from another thread. I believe the existing barrier around icount_decr.u16.high covers it, but my testing was single-threaded user mode.
- Patch 4 treats cpu flags, cflags and cs_base as translation-time constants in its guards, reads a jump cache entry without qatomic_read(), and leaves one_insn_per_tb and -d nochain toggles visible only at the next non-inline exit.
- Patch 7 only examines the immediately preceding op, refuses any access with a slow path (so user-only, and no alignment check), and leaves the i128 pairs alone.
- Patch 2's 1 MiB per vCPU is easy to justify for a single-vCPU linux-user process and less obvious for system emulation with many vCPUs. It may want to be sized per target or made tunable rather than raised unconditionally.
Patches 4 and 7 are wired up for alpha and x86_64 respectively; everything else is target-independent, and no other backend changes behavior or needs touching.
v2: https://lore.kernel.org/qemu-devel/[email protected]/
Matt Turner (7):
accel/tcg: fold the dynamic cflags into CPUState::tcg_cflags accel/tcg: enlarge the TB jump cache to 64K entries accel/tcg: skip the can_do_io stores in user-only builds
RFC: tcg: probe the TB jump cache inline instead of calling a helper
RFC: accel/tcg: allow cross-page goto_tb chaining in user-only builds
RFC: accel/tcg: poison the jump cache instead of polling for indirect
exits
RFC: tcg: fold a guest displacement into the host addressing mode
accel/tcg/cpu-exec-common.c | 33 +++- accel/tcg/cpu-exec.c | 122 +++++++++++++++ accel/tcg/internal-common.h | 13 +- accel/tcg/tb-jmp-cache.h | 2 +- accel/tcg/tcg-accel-ops.c | 1 + accel/tcg/tcg-all.c | 1 + accel/tcg/translator.c | 94 +++++++++++- cpu-common.c | 11 ++ cpu-target.c | 3 + gdbstub/user.c | 14 ++ include/gdbstub/user.h | 11 ++ include/hw/core/cpu.h | 11 ++ include/system/tcg.h | 21 +++ include/tcg/tcg-op-common.h | 16 +- include/tcg/tcg-op.h | 12 ++ include/tcg/tcg-opc.h | 9 +- include/tcg/tcg.h | 2 + stubs/meson.build | 1 + stubs/tcg-cflags.c | 20 +++ target/alpha/translate.c | 4 +- target/arm/tcg/translate-a64.c | 4 +- target/arm/tcg/translate.c | 10 +- target/avr/translate.c | 4 +- target/hexagon/translate.c | 4 +- target/hppa/translate.c | 6 +- target/i386/tcg/translate.c | 2 +- .../tcg/insn_trans/trans_branch.c.inc | 2 +- target/loongarch/tcg/translate.c | 4 +- target/m68k/translate.c | 2 +- target/microblaze/translate.c | 4 +- target/mips/tcg/nanomips_translate.c.inc | 2 +- target/mips/tcg/translate.c | 6 +- target/or1k/translate.c | 4 +- target/ppc/translate.c | 4 +- target/riscv/tcg/insn_trans/trans_rvzce.c.inc | 4 +- target/riscv/tcg/translate.c | 2 +- target/rx/translate.c | 4 +- target/s390x/tcg/translate.c | 5 +- target/sh4/translate.c | 4 +- target/sparc/translate.c | 4 +- target/tricore/translate.c | 4 +- tcg/tcg-op-ldst.c | 3 +- tcg/tcg-op.c | 101 +++++++++++- tcg/tcg.c | 86 ++++++++++- tcg/x86_64/tcg-target.c.inc | 61 ++++++++ tcg/x86_64/tcg-target.h | 3 + tests/tcg/alpha/Makefile.target | 18 ++- tests/tcg/alpha/gdbstub/xpage-bp.py | 34 +++++ tests/tcg/alpha/test-indirect-irq.c | 55 +++++++ tests/tcg/alpha/test-xpage-chain.c | 144 ++++++++++++++++++ util/log.c | 4 + 51 files changed, 932 insertions(+), 63 deletions(-) create mode 100644 stubs/tcg-cflags.c create mode 100644 tests/tcg/alpha/gdbstub/xpage-bp.py create mode 100644 tests/tcg/alpha/test-indirect-irq.c create mode 100644 tests/tcg/alpha/test-xpage-chain.c
Signature · 1 line
2.54.0
PATCH v3 1/7 accel/tcg: fold the dynamic cflags into CPUState::tcg_cflags
curr_cflags() is called once per TB dispatch, from helper_lookup_tb_ptr() and from the cpu_exec() loop. It recomputes the same value every time:
uint32_t cflags = cpu->tcg_cflags;
if (unlikely(cpu_single_stepping(cpu))) { ... }
else if (qatomic_read(&one_insn_per_tb)) { ... }
else if (qemu_loglevel_mask(CPU_LOG_TB_NOCHAIN)) { ... }That is three loads and three branches on the hottest path in the interpreter, for state that changes only when gdb enables single-step, when one-insn-per-tb is toggled, or when the log mask changes.
None of the three has to be sampled at dispatch time. Fold each into CPUState::tcg_cflags where it changes and curr_cflags() becomes a single load of a field that TB lookup has to read anyway.
The derived bits -- CF_COUNT_MASK, CF_NO_GOTO_TB, CF_NO_GOTO_PTR and CF_SINGLE_STEP -- are never set by tcg_cflags_set(), so tcg_update_cflags() can recompute them in place without disturbing the rest, and conversely tcg_cflags_set() ORs in its bits without disturbing them.
There are three places to call it:
- tcg_exec_realizefn(), so that a CPU created after the command line has been parsed starts out with the right value. This covers user-only, where tcg_cpu_init_cflags() is not reached. linux-user's cpu_copy() copies tcg_cflags wholesale, so a cloned thread inherits it.
- cpu_single_step(), which changes one CPU and runs either on that CPU's thread or with it stopped.
- tcg_set_one_insn_per_tb() and qemu_set_log_internal(), which change every CPU. Both can be reached from the monitor while the vCPUs are running -- 'one-insn-per-tb on' and 'log nochain' -- so the update is queued with async_safe_run_on_cpu() and each CPU writes its own cflags with the others halted.
Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host, in a build configured with --enable-lto:
before: 1,646,994,254,249 instructions
after: 1,562,204,796,597 instructions -5.15%That workload issues 8.4 billion dispatches, so the per-call saving is small but the aggregate is not. The emulated compiler produces byte-identical output before and after.
Wall clock does not move: 133.19s to 132.58s, a 0.46% difference against a run-to-run spread larger than that. The removed work is a few predictable loads and branches that the host executes largely in parallel with the surrounding dispatch, so this patch is worth taking for the instruction count and for what it enables, not for a time saving that can be measured on its own.
--- accel/tcg/cpu-exec-common.c | 33 ++++++++++++++++++++++++++++++--- accel/tcg/cpu-exec.c | 3 +++ accel/tcg/internal-common.h | 11 +++++++++-- accel/tcg/tcg-all.c | 1 + cpu-target.c | 3 +++ include/system/tcg.h | 12 ++++++++++++ stubs/meson.build | 1 + stubs/tcg-cflags.c | 16 ++++++++++++++++ util/log.c | 4 ++++ 9 files changed, 79 insertions(+), 5 deletions(-) create mode 100644 stubs/tcg-cflags.c
accel/tcg/cpu-exec-common.c +30 -3
@@ -36,9 +36,16 @@ void tcg_cflags_set(CPUState *cpu, uint32_t flags) cpu->tcg_cflags |= flags; } -uint32_t curr_cflags (CPUState *cpu) +/* +* The bits of CPUState::tcg_cflags that tcg_cflags_set() never sets, because +* they are derived from gdb single-step, one-insn-per-tb and -d nochain. +*/ +#define CF_DERIVED (CF_COUNT_MASK | CF_NO_GOTO_TB | CF_NO_GOTO_PTR | \ + CF_SINGLE_STEP) + +void tcg_update_cflags (CPUState *cpu) { -uint32_t cflags = cpu->tcg_cflags; +uint32_t cflags = cpu->tcg_cflags & ~CF_DERIVED ;/* * Record gdb single-step. We should be exiting the TB by raising
@@ -55,7 +62,27 @@ uint32_t curr_cflags(CPUState *cpu) cflags |=CF_NO_GOTO_TB ; } -return cflags; + cpu->tcg_cflags = cflags; +} + +static void tcg_update_cflags_work (CPUState *cpu,run_on_cpu_data data) +{ +tcg_update_cflags (cpu); +} + +void tcg_update_all_cflags (void ) +{ +CPUState *cpu; + +/* +* one-insn-per-tb and -d nochain can both be changed from the monitor +* while the vCPUs are running. Have each CPU update its own cflags +* with the others halted, so that no dispatch can read a value that +* another thread is in the middle of writing. +*/ +CPU_FOREACH (cpu) { +async_safe_run_on_cpu (cpu, tcg_update_cflags_work,RUN_ON_CPU_NULL ); + } }/* exit the current TB, but without causing any exception to be raised */
accel/tcg/cpu-exec.c +3 -0
@@ -1068,6 +1068,9 @@ bool tcg_exec_realizefn(CPUState *cpu, Error **errp) tcg_target_initialized = true; } +/* Pick up one-insn-per-tb and -d nochain from the command line. */ +tcg_update_cflags (cpu); + cpu->tb_jmp_cache =g_new0 (CPUJumpCache,1 );tlb_init (cpu);#ifndef CONFIG_USER_ONLY
accel/tcg/internal-common.h +9 -2
@@ -69,8 +69,15 @@ void tlb_destroy(CPUState *cpu);bool tcg_exec_realizefn (CPUState *cpu,Error **errp);void tcg_exec_unrealizefn (CPUState *cpu); -/* current cflags for hashing/comparison */ -uint32_t curr_cflags (CPUState *cpu); +/* +* Current cflags for hashing/comparison. Everything that feeds into the +* value is folded into CPUState::tcg_cflags when it changes, by +* tcg_update_cflags(), so that TB dispatch only has to load it. +*/ +static inline uint32_t curr_cflags (CPUState *cpu) +{ +return cpu->tcg_cflags; +}void tb_check_watchpoint (CPUState *cpu,uintptr_t retaddr);
accel/tcg/tcg-all.c +1 -0
@@ -254,6 +254,7 @@ static void tcg_set_one_insn_per_tb(Object *obj, bool value, Error **errp) s->one_insn_per_tb = value;/* Set the global also: this changes the behaviour */ qatomic_set (&one_insn_per_tb, value); +tcg_update_all_cflags (); }static void tcg_accel_class_init (ObjectClass *oc,const void *data)
cpu-target.c +3 -0
@@ -24,6 +24,7 @@#include "exec/replay-core.h" #include "exec/log.h" #include "hw/core/cpu.h" +#include "system/tcg.h" #include "trace/trace-root.h" /* enable or disable single step mode. EXCP_DEBUG is returned by the
@@ -35,6 +36,8 @@ void cpu_single_step(CPUState *cpu, unsigned flags) cpu->singlestep_flags, flags); cpu->singlestep_flags = flags; +tcg_update_cflags (cpu); +#if !defined(CONFIG_USER_ONLY )const AccelOpsClass *ops =cpus_get_accel ();if (ops->update_guest_debug) {
include/system/tcg.h +12 -0
@@ -17,6 +17,18 @@ extern bool tcg_allowed;#define tcg_enabled () 0#endif +/* +* Recompute the parts of CPUState::tcg_cflags that TB dispatch consumes but +* tcg_cflags_set() does not provide: gdb single-step, one-insn-per-tb and +* the CPU_LOG_TB_NOCHAIN log flag. Call whenever one of those changes. +* +* tcg_update_cflags() updates one CPU and must be called from that CPU's +* thread, or with it stopped. tcg_update_all_cflags() updates every CPU +* and is safe to call from the monitor while the vCPUs run. +*/ +void tcg_update_cflags (CPUState *cpu); +void tcg_update_all_cflags (void ); +/** * qemu_tcg_mttcg_enabled: * Check whether we are running MultiThread TCG or not.
stubs/meson.build +1 -0
@@ -3,6 +3,7 @@ # below, so that it is clear who needs the stubbed functionality. stub_ss.add(files('cpu-get-clock.c')) +stub_ss.add(files('tcg-cflags.c')) stub_ss.add(files('fdset.c')) stub_ss.add(files('iothread-lock.c')) stub_ss.add(files('is-daemonized.c'))
stubs/tcg-cflags.c new file +16 -0
@@ -0,0 +1,16 @@ +/* +* Stub for tcg_update_all_cflags(), for binaries that link util/log.c +* or cpu-target.c but not TCG. +* +* SPDX-License-Identifier: GPL-2.0-or-later +*/ +#include "qemu/osdep.h" +#include "system/tcg.h" + +void tcg_update_cflags (CPUState *cpu) +{ +} + +void tcg_update_all_cflags (void ) +{ +}
util/log.c +4 -0
@@ -27,6 +27,7 @@#include "qemu/thread.h" #include "qemu/lockable.h" #include "qemu/rcu.h" +#include "system/tcg.h" #ifdef CONFIG_LINUX #include <sys/syscall.h> #endif
@@ -301,6 +302,9 @@ static bool qemu_set_log_internal(const char *filename, bool changed_name,#endif qemu_loglevel = log_flags; +/* CPU_LOG_TB_NOCHAIN feeds into the per-CPU cflags. */ +tcg_update_all_cflags (); + daemonized =is_daemonized (); need_to_open_file = false;if (!daemonized) {
Signature · 1 line
2.54.0
Re: [PATCH v3 1/7] accel/tcg: fold the dynamic cflags into CPUState::tcg_cflags
Quoted 10 lines · Matt Turner
accel/tcg/tcg-all.c +1
-0@@ -254,6 +254,7 @@ static void tcg_set_one_insn_per_tb(Object *obj, bool value, Error **errp) s->one_insn_per_tb = value;/* Set the global also: this changes the behaviour */ qatomic_set (&one_insn_per_tb, value); +tcg_update_all_cflags (); }
...
Quoted 13 lines
util/log.c +1
-0@@ -27,6 +27,7 @@#include "qemu/thread.h" #include "qemu/lockable.h" #include "qemu/rcu.h" +#include "system/tcg.h" #ifdef CONFIG_LINUX #include <sys/syscall.h> #endif
util/log.c static bool qemu_set_log_internal(const char *filename, bool changed_name, · line 306
Quoted 5 lines
util/log.c +2
-0@@ -301,6 +302,9 @@ static bool qemu_set_log_internal(const char *filename, bool changed_name,#endif qemu_loglevel = log_flags; +/* CPU_LOG_TB_NOCHAIN feeds into the per-CPU cflags. */ +tcg_update_all_cflags ();
I'm not keen on these placements. I know they're needed for HMP, but I'd rather have these calls in HMP, after updating state.
util/log.c static bool qemu_set_log_internal(const char *filename, bool changed_name, · line 310
Quoted 4 lines
util/log.c +4
-0+void tcg_update_cflags (CPUState *cpu) +{ +} +
Where does this get used outside of tcg itself? I think only tcg_update_all_cflags() should be stubbed, and indeed the only one visible outside of accel/tcg/.
Phil, is the stub itself better placed in accel/stubs/ or accel/tcg/? I'm unsure what organization you're working toward.
r~
Re: [PATCH v3 1/7] accel/tcg: fold the dynamic cflags into CPUState::tcg_cflags
Quoted 36 lines · Richard Henderson
Quoted 10 lines · Matt Turner
accel/tcg/tcg-all.c +1
-0@@ -254,6 +254,7 @@ static void tcg_set_one_insn_per_tb(Object *obj, bool value, Error **errp) s->one_insn_per_tb = value;/* Set the global also: this changes the behaviour */ qatomic_set (&one_insn_per_tb, value); +tcg_update_all_cflags (); }...
Quoted 13 lines
util/log.c +1
-0@@ -27,6 +27,7 @@#include "qemu/thread.h" #include "qemu/lockable.h" #include "qemu/rcu.h" +#include "system/tcg.h" #ifdef CONFIG_LINUX #include <sys/syscall.h> #endif util/log.c static bool qemu_set_log_internal(const char *filename, bool changed_name, · line 306
Quoted 5 lines
util/log.c +2
-0@@ -301,6 +302,9 @@ static bool qemu_set_log_internal(const char *filename, bool changed_name,#endif qemu_loglevel = log_flags; +/* CPU_LOG_TB_NOCHAIN feeds into the per-CPU cflags. */ +tcg_update_all_cflags ();I'm not keen on these placements. I know they're needed for HMP, but I'd rather have these calls in HMP, after updating state.
Quoted 7 lines
util/log.c static bool qemu_set_log_internal(const char *filename, bool changed_name, · line 310
Quoted 4 lines
util/log.c +4
-0+void tcg_update_cflags (CPUState *cpu) +{ +} +Where does this get used outside of tcg itself? I think only
tcg_update_all_cflags()should be stubbed, and indeed the only one visible outside of accel/tcg/.
cpu_single_step(), in cpu-target.c, which is in both user_ss and system_ss and always linked. So both entry points need stubbing.
Quoted 2 lines
Phil, is the stub itself better placed in accel/stubs/ or accel/tcg/? I'm unsure what organization you're working toward.
v4 moves it to accel/stubs/tcg-stub.c, alongside the other accelerator stubs. Verified --disable-tcg links. Easy to move again if Phil prefers elsewhere.
Re: [PATCH v3 1/7] accel/tcg: fold the dynamic cflags into CPUState::tcg_cflags
In reply to Matt TurnerQuoted 108 lines · Matt Turner
curr_cflags()is called once per TB dispatch, fromhelper_lookup_tb_ptr()and from thecpu_exec()loop. It recomputes the same value every time:uint32_t cflags = cpu->tcg_cflags; if (unlikely(cpu_single_stepping(cpu))) { ... } else if (qatomic_read(&one_insn_per_tb)) { ... } else if (qemu_loglevel_mask(CPU_LOG_TB_NOCHAIN)) { ... }That is three loads and three branches on the hottest path in the interpreter, for state that changes only when gdb enables single-step, when one-insn-per-tb is toggled, or when the log mask changes.
None of the three has to be sampled at dispatch time. Fold each into
CPUState::tcg_cflagswhere it changes andcurr_cflags()becomes a single load of a field that TB lookup has to read anyway.The derived bits --
CF_COUNT_MASK,CF_NO_GOTO_TB,CF_NO_GOTO_PTRandCF_SINGLE_STEP-- are never set bytcg_cflags_set(), sotcg_update_cflags()can recompute them in place without disturbing the rest, and converselytcg_cflags_set()ORs in its bits without disturbing them.There are three places to call it:
-
tcg_exec_realizefn(), so that a CPU created after the command line has been parsed starts out with the right value. This covers user-only, wheretcg_cpu_init_cflags()is not reached. linux-user'scpu_copy()copiestcg_cflagswholesale, so a cloned thread inherits it.-
cpu_single_step(), which changes one CPU and runs either on that CPU's thread or with it stopped.-
tcg_set_one_insn_per_tb()andqemu_set_log_internal(), which change every CPU. Both can be reached from the monitor while the vCPUs are running -- 'one-insn-per-tb on' and 'log nochain' -- so the update is queued withasync_safe_run_on_cpu()and each CPU writes its own cflags with the others halted.Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host, in a build configured with --enable-lto:
before: 1,646,994,254,249 instructions after: 1,562,204,796,597 instructions -5.15%That workload issues 8.4 billion dispatches, so the per-call saving is small but the aggregate is not. The emulated compiler produces byte-identical output before and after.
Wall clock does not move: 133.19s to 132.58s, a 0.46% difference against a run-to-run spread larger than that. The removed work is a few predictable loads and branches that the host executes largely in parallel with the surrounding dispatch, so this patch is worth taking for the instruction count and for what it enables, not for a time saving that can be measured on its own.
Signed-off-by Matt Turner <[email protected]>--- accel/tcg/cpu-exec-common.c | 33 ++++++++++++++++++++++++++++++--- accel/tcg/cpu-exec.c | 3 +++ accel/tcg/internal-common.h | 11 +++++++++-- accel/tcg/tcg-all.c | 1 + cpu-target.c | 3 +++ include/system/tcg.h | 12 ++++++++++++ stubs/meson.build | 1 + stubs/tcg-cflags.c | 16 ++++++++++++++++ util/log.c | 4 ++++ 9 files changed, 79 insertions(+), 5 deletions(-) create mode 100644 stubs/tcg-cflags.caccel/tcg/cpu-exec-common.c +20
-3@@ -36,9 +36,16 @@ void tcg_cflags_set(CPUState *cpu, uint32_t flags) cpu->tcg_cflags |= flags; } -uint32_t curr_cflags (CPUState *cpu) +/* +* The bits of CPUState::tcg_cflags that tcg_cflags_set() never sets, because +* they are derived from gdb single-step, one-insn-per-tb and -d nochain. +*/ +#define CF_DERIVED (CF_COUNT_MASK | CF_NO_GOTO_TB | CF_NO_GOTO_PTR | \ + CF_SINGLE_STEP) + +void tcg_update_cflags (CPUState *cpu) { -uint32_t cflags = cpu->tcg_cflags; +uint32_t cflags = cpu->tcg_cflags & ~CF_DERIVED ;/* * Record gdb single-step. We should be exiting the TB by raising @@ -55,7 +62,27 @@ uint32_t curr_cflags(CPUState *cpu) cflags |=CF_NO_GOTO_TB ; } -return cflags; + cpu->tcg_cflags = cflags; +} + +static void tcg_update_cflags_work (CPUState *cpu,run_on_cpu_data data) +{ +tcg_update_cflags (cpu); +} + +void tcg_update_all_cflags (void ) +{ +CPUState *cpu;
accel/tcg/cpu-exec-common.c uint32_t curr_cflags(CPUState *cpu) · line 85
Quoted 10 lines
accel/tcg/cpu-exec-common.c +9
-0+ +/* +* one-insn-per-tb and -d nochain can both be changed from the monitor +* while the vCPUs are running. Have each CPU update its own cflags +* with the others halted, so that no dispatch can read a value that +* another thread is in the middle of writing. +*/ +CPU_FOREACH (cpu) { +async_safe_run_on_cpu (cpu, tcg_update_cflags_work,RUN_ON_CPU_NULL );
I don't think this is wrong but are we really seeing cross-vCPU updates of cpu->cflags? I suspect async_run_on_cpu would be enough to trigger an update from a non-vCPU thread to the vCPU.
You could even pass the sub-set of flags down in the user data and maybe avoid having to use global atomics for those flags.
Quoted 152 lines
accel/tcg/cpu-exec-common.c +1
-0+ } }/* exit the current TB, but without causing any exception to be raised */
accel/tcg/cpu-exec.c +3
-0@@ -1068,6 +1068,9 @@ bool tcg_exec_realizefn(CPUState *cpu, Error **errp) tcg_target_initialized = true; } +/* Pick up one-insn-per-tb and -d nochain from the command line. */ +tcg_update_cflags (cpu); + cpu->tb_jmp_cache =g_new0 (CPUJumpCache,1 );tlb_init (cpu);#ifndef CONFIG_USER_ONLY accel/tcg/internal-common.h +9
-2@@ -69,8 +69,15 @@ void tlb_destroy(CPUState *cpu);bool tcg_exec_realizefn (CPUState *cpu,Error **errp);void tcg_exec_unrealizefn (CPUState *cpu); -/* current cflags for hashing/comparison */ -uint32_t curr_cflags (CPUState *cpu); +/* +* Current cflags for hashing/comparison. Everything that feeds into the +* value is folded into CPUState::tcg_cflags when it changes, by +* tcg_update_cflags(), so that TB dispatch only has to load it. +*/ +static inline uint32_t curr_cflags (CPUState *cpu) +{ +return cpu->tcg_cflags; +}void tb_check_watchpoint (CPUState *cpu,uintptr_t retaddr);accel/tcg/tcg-all.c +1
-0@@ -254,6 +254,7 @@ static void tcg_set_one_insn_per_tb(Object *obj, bool value, Error **errp) s->one_insn_per_tb = value;/* Set the global also: this changes the behaviour */ qatomic_set (&one_insn_per_tb, value); +tcg_update_all_cflags (); }static void tcg_accel_class_init (ObjectClass *oc,const void *data)cpu-target.c +3
-0@@ -24,6 +24,7 @@#include "exec/replay-core.h" #include "exec/log.h" #include "hw/core/cpu.h" +#include "system/tcg.h" #include "trace/trace-root.h" /* enable or disable single step mode. EXCP_DEBUG is returned by the @@ -35,6 +36,8 @@ void cpu_single_step(CPUState *cpu, unsigned flags) cpu->singlestep_flags, flags); cpu->singlestep_flags = flags; +tcg_update_cflags (cpu); +#if !defined(CONFIG_USER_ONLY )const AccelOpsClass *ops =cpus_get_accel ();if (ops->update_guest_debug) {include/system/tcg.h +12
-0@@ -17,6 +17,18 @@ extern bool tcg_allowed;#define tcg_enabled () 0#endif +/* +* Recompute the parts of CPUState::tcg_cflags that TB dispatch consumes but +* tcg_cflags_set() does not provide: gdb single-step, one-insn-per-tb and +* the CPU_LOG_TB_NOCHAIN log flag. Call whenever one of those changes. +* +* tcg_update_cflags() updates one CPU and must be called from that CPU's +* thread, or with it stopped. tcg_update_all_cflags() updates every CPU +* and is safe to call from the monitor while the vCPUs run. +*/ +void tcg_update_cflags (CPUState *cpu); +void tcg_update_all_cflags (void ); +/** * qemu_tcg_mttcg_enabled: * Check whether we are running MultiThread TCG or not. stubs/meson.build +1
-0@@ -3,6 +3,7 @@ # below, so that it is clear who needs the stubbed functionality. stub_ss.add(files('cpu-get-clock.c')) +stub_ss.add(files('tcg-cflags.c')) stub_ss.add(files('fdset.c')) stub_ss.add(files('iothread-lock.c')) stub_ss.add(files('is-daemonized.c'))stubs/tcg-cflags.c new file +16
-0@@ -0,0 +1,16 @@ +/* +* Stub for tcg_update_all_cflags(), for binaries that link util/log.c +* or cpu-target.c but not TCG. +* +* SPDX-License-Identifier: GPL-2.0-or-later +*/ +#include "qemu/osdep.h" +#include "system/tcg.h" + +void tcg_update_cflags (CPUState *cpu) +{ +} + +void tcg_update_all_cflags (void ) +{ +}util/log.c +4
-0@@ -27,6 +27,7 @@#include "qemu/thread.h" #include "qemu/lockable.h" #include "qemu/rcu.h" +#include "system/tcg.h" #ifdef CONFIG_LINUX #include <sys/syscall.h> #endif @@ -301,6 +302,9 @@ static bool qemu_set_log_internal(const char *filename, bool changed_name,#endif qemu_loglevel = log_flags; +/* CPU_LOG_TB_NOCHAIN feeds into the per-CPU cflags. */ +tcg_update_all_cflags (); + daemonized =is_daemonized (); need_to_open_file = false;if (!daemonized) {
Signature · 2 lines
Alex Bennée Virtualisation Tech Lead @ Linaro
Re: [PATCH v3 1/7] accel/tcg: fold the dynamic cflags into CPUState::tcg_cflags
Quoted 116 lines · Alex Bennée
Quoted 113 lines · Matt Turner
curr_cflags()is called once per TB dispatch, fromhelper_lookup_tb_ptr()and from thecpu_exec()loop. It recomputes the same value every time:uint32_t cflags = cpu->tcg_cflags; if (unlikely(cpu_single_stepping(cpu))) { ... } else if (qatomic_read(&one_insn_per_tb)) { ... } else if (qemu_loglevel_mask(CPU_LOG_TB_NOCHAIN)) { ... }That is three loads and three branches on the hottest path in the interpreter, for state that changes only when gdb enables single-step, when one-insn-per-tb is toggled, or when the log mask changes.
None of the three has to be sampled at dispatch time. Fold each into
CPUState::tcg_cflagswhere it changes andcurr_cflags()becomes a single load of a field that TB lookup has to read anyway.The derived bits --
CF_COUNT_MASK,CF_NO_GOTO_TB,CF_NO_GOTO_PTRandCF_SINGLE_STEP-- are never set bytcg_cflags_set(), sotcg_update_cflags()can recompute them in place without disturbing the rest, and converselytcg_cflags_set()ORs in its bits without disturbing them.There are three places to call it:
-
tcg_exec_realizefn(), so that a CPU created after the command line has been parsed starts out with the right value. This covers user-only, wheretcg_cpu_init_cflags()is not reached. linux-user'scpu_copy()copiestcg_cflagswholesale, so a cloned thread inherits it.-
cpu_single_step(), which changes one CPU and runs either on that CPU's thread or with it stopped.-
tcg_set_one_insn_per_tb()andqemu_set_log_internal(), which change every CPU. Both can be reached from the monitor while the vCPUs are running -- 'one-insn-per-tb on' and 'log nochain' -- so the update is queued withasync_safe_run_on_cpu()and each CPU writes its own cflags with the others halted.Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host, in a build configured with --enable-lto:
before: 1,646,994,254,249 instructions after: 1,562,204,796,597 instructions -5.15%That workload issues 8.4 billion dispatches, so the per-call saving is small but the aggregate is not. The emulated compiler produces byte-identical output before and after.
Wall clock does not move: 133.19s to 132.58s, a 0.46% difference against a run-to-run spread larger than that. The removed work is a few predictable loads and branches that the host executes largely in parallel with the surrounding dispatch, so this patch is worth taking for the instruction count and for what it enables, not for a time saving that can be measured on its own.
Signed-off-by Matt Turner <[email protected]>--- accel/tcg/cpu-exec-common.c | 33 ++++++++++++++++++++++++++++++--- accel/tcg/cpu-exec.c | 3 +++ accel/tcg/internal-common.h | 11 +++++++++-- accel/tcg/tcg-all.c | 1 + cpu-target.c | 3 +++ include/system/tcg.h | 12 ++++++++++++ stubs/meson.build | 1 + stubs/tcg-cflags.c | 16 ++++++++++++++++ util/log.c | 4 ++++ 9 files changed, 79 insertions(+), 5 deletions(-) create mode 100644 stubs/tcg-cflags.caccel/tcg/cpu-exec-common.c +25
-3@@ -36,9 +36,16 @@ void tcg_cflags_set(CPUState *cpu, uint32_t flags) cpu->tcg_cflags |= flags; } -uint32_t curr_cflags (CPUState *cpu) +/* +* The bits of CPUState::tcg_cflags that tcg_cflags_set() never sets, because +* they are derived from gdb single-step, one-insn-per-tb and -d nochain. +*/ +#define CF_DERIVED (CF_COUNT_MASK | CF_NO_GOTO_TB | CF_NO_GOTO_PTR | \ + CF_SINGLE_STEP) + +void tcg_update_cflags (CPUState *cpu) { -uint32_t cflags = cpu->tcg_cflags; +uint32_t cflags = cpu->tcg_cflags & ~CF_DERIVED ;/* * Record gdb single-step. We should be exiting the TB by raising @@ -55,7 +62,27 @@ uint32_t curr_cflags(CPUState *cpu) cflags |=CF_NO_GOTO_TB ; } -return cflags; + cpu->tcg_cflags = cflags; +} + +static void tcg_update_cflags_work (CPUState *cpu,run_on_cpu_data data) +{ +tcg_update_cflags (cpu); +} + +void tcg_update_all_cflags (void ) +{ +CPUState *cpu; + +/* +* one-insn-per-tb and -d nochain can both be changed from the monitor +* while the vCPUs are running. Have each CPU update its own cflags +* with the others halted, so that no dispatch can read a value that
Quoted 8 lines
accel/tcg/cpu-exec-common.c uint32_t curr_cflags(CPUState *cpu)
Quoted 5 lines
accel/tcg/cpu-exec-common.c +4
-0+* another thread is in the middle of writing. +*/ +CPU_FOREACH (cpu) { +async_safe_run_on_cpu (cpu, tcg_update_cflags_work,RUN_ON_CPU_NULL );I don't think this is wrong but are we really seeing cross-vCPU updates of
cpu->cflags?
Fixed in v4. The monitor path was the cross-vCPU one -- v3 had the monitor thread storing into every cpu->tcg_cflags -- and v4 queues the update instead, so each vCPU writes its own field from its own thread.
The one foreign writer left is cpu_single_step(), and it's the same one that was already there. gdb_continue_partial() in gdbstub/user.c walks CPU_FOREACH and can hit a thread that's still running, since gdb_handlesig() only parks the thread that trapped. But before this patch, curr_cflags() on CPU X read X->singlestep_flags and cpu_single_step() stored to it from whichever thread gdb was on. Now the store lands in X->tcg_cflags. Same width, same plain accesses, same writer, same reader -- the patch changes which field carries the state, not how it's synchronized. Nothing here wants atomics that didn't want them before.
I did fix the commit message, which claimed cpu_single_step() always runs on the owning thread or with the CPU stopped. True in system mode, not in the user-mode gdb_continue_partial() case.
Quoted 2 lines
I suspect
async_run_on_cpuwould be enough to trigger an update from a non-vCPU thread to the vCPU.
Agreed, fixed in v4. async_safe_run_on_cpu() was overkill.
Quoted 2 lines
You could even pass the sub-set of flags down in the user data and maybe avoid having to use global atomics for those flags.
I left this, but tell me if you'd rather have it. The only atomic is qatomic_read(&one_insn_per_tb), and the patch already takes it off the hot path -- it ran on every dispatch, now it runs at realize, at a gdb step change, or on an HMP command. Passing a snapshot would remove that last read, but one_insn_per_tb and qemu_loglevel are read by other code too, so the queued CPU would be working from a snapshot while everyone else sees the live global. For a path this cold that seemed like the worse trade.
PATCH v3 2/7 accel/tcg: enlarge the TB jump cache to 64K entries
In reply to Matt TurnerThe per-CPU TB jump cache has held 4096 entries since it was introduced. That is too small for guests running large programs: an emulated compiler misses often enough that the fallback qht lookup shows up prominently in a profile.
Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host. The compile performs 34.2 billion TB executions, of which 8.4 billion take the indirect dispatch path.
Sizing curve, on top of the preceding patch, instructions retired and wall clock:
12 bits ( 64 KiB): 1,562,204,796,597 132.58s
14 bits ( 256 KiB): 1,493,318,515,396 -4.41% 124.67s -5.97%
16 bits ( 1 MiB): 1,469,772,951,575 -5.92% 121.04s -8.71%
18 bits ( 4 MiB): 1,462,309,832,762 -6.39% 119.82s -9.62%16 bits is the knee. 18 buys another 0.47% of instructions for four times the memory. It does show a further 1.01% of wall clock, which is outside the 0.70% run-to-run spread at 16 bits, so the effect is probably real -- but paying four times the memory for it is a poor trade, and instructions retired does not account for the data cache pressure of a 4 MiB table.
In a perf profile the mechanism is visible directly: tb_htable_lookup(), which is where qht_lookup_custom() lands once it is inlined in an LTO build, falls from 6.10% of samples to 1.66%.
The cost is memory: the cache grows from 64 KiB to 1 MiB per vCPU. That is easy to justify for a single-vCPU linux-user process and less obvious for system emulation with many vCPUs, so this may want to be sized by target or made tunable rather than raised unconditionally.
--- accel/tcg/tb-jmp-cache.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
accel/tcg/tb-jmp-cache.h +1 -1
@@ -12,7 +12,7 @@#include "qemu/rcu.h" #include "exec/cpu-common.h" -#define TB_JMP_CACHE_BITS 12 +#define TB_JMP_CACHE_BITS 16#define TB_JMP_CACHE_SIZE (1 << TB_JMP_CACHE_BITS)/*
Signature · 1 line
2.54.0
Re: [PATCH v3 2/7] accel/tcg: enlarge the TB jump cache to 64K entries
Quoted 4 lines · Matt Turner
The cost is memory: the cache grows from 64 KiB to 1 MiB per vCPU. That is easy to justify for a single-vCPU linux-user process and less obvious for system emulation with many vCPUs, so this may want to be sized by target or made tunable rather than raised unconditionally.
Why do you believe linux-user processes are single-threaded? I suppose when emulating /bin a fair few of them are, but...
r~
Re: [PATCH v3 2/7] accel/tcg: enlarge the TB jump cache to 64K entries
Quoted 9 lines · Richard Henderson
Quoted 4 lines · Matt Turner
The cost is memory: the cache grows from 64 KiB to 1 MiB per vCPU. That is easy to justify for a single-vCPU linux-user process and less obvious for system emulation with many vCPUs, so this may want to be sized by target or made tunable rather than raised unconditionally.
Why do you believe linux-user processes are single-threaded? I suppose when emulating /bin a fair few of them are, but...
I don't -- I'd conflated "one process" with "one CPUState". linux-user creates a CPUState per guest thread, so a threaded guest pays the megabyte per thread, just as system emulation pays it per vCPU. Commit message fixed.
The sizing question stays open, which is why the patch says so. I don't have a threaded workload where 64 KiB is the better trade and would welcome one.
PATCH v3 3/7 accel/tcg: skip the can_do_io stores in user-only builds
In reply to Matt TurnerEvery translation block stores to cpu->neg.can_do_io twice: false before the first instruction, true before the last one. Nothing reads it in a user-only build. There is no memory-mapped I/O in linux-user, and every reader is in system_ss: cputlb.c, watchpoint.c, icount-common.c and tcg-accel-ops-icount.c.
Two stores per TB is not much on its own, but TBs are short. An emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) executes 34.2 billion TBs at 6.04 guest instructions each, so this is 68 billion stores for nothing.
Measured on an x86-64 host, LTO build, on top of the preceding two patches:
before: 1,469,772,951,575 instructions
after: 1,402,667,803,616 instructions -4.57%
before: 121.04s wall clock
after: 115.56s wall clock -4.53%The emulated compiler produces byte-identical output.
v3: Use #ifndef CONFIG_USER_ONLY again rather than
if (IS_ENABLED(CONFIG_USER_ONLY)). QEMU's IS_ENABLED() is IS_EMPTY(), which is only true for a symbol Meson defines empty; CONFIG_USER_ONLY is defined as 1, so the test was always false and v2 emitted the two stores after all. The measurements above are from the working form.
--- accel/tcg/translator.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
accel/tcg/translator.c +10 -0
@@ -21,12 +21,14 @@#include "disas/disas.h" #include "tb-internal.h" +#ifndef CONFIG_USER_ONLY static void set_can_do_io (DisasContextBase *db,bool val) {QEMU_BUILD_BUG_ON (sizeof_field (CPUState, neg.can_do_io) !=1 );tcg_gen_st8_i32 (tcg_constant_i32 (val), tcg_env, offsetof(CPUState, neg.can_do_io) - sizeof(CPUState)); } +#endif bool translator_io_start (DisasContextBase *db) {
@@ -210,17 +212,25 @@ void translator_loop(CPUState *cpu, TranslationBlock *tb, int *max_insns,/* * Manage can_do_io for the translation block: set to false before * the first insn and set to true before the last insn. +* +* Nothing reads can_do_io in user-only builds. There is no MMIO +* there, and every reader (cputlb.c, watchpoint.c, icount) is in +* system_ss, so skip the two stores per TB entirely. */ if (db->num_insns ==1 ) {tcg_debug_assert (first_insn_start == db->insn_start); }else {tcg_debug_assert (first_insn_start != db->insn_start); +#ifndef CONFIG_USER_ONLY tcg_ctx->emit_before_op = first_insn_start;set_can_do_io (db, false); +#endif } +#ifndef CONFIG_USER_ONLY tcg_ctx->emit_before_op = db->insn_start;set_can_do_io (db, true); tcg_ctx->emit_before_op =NULL ; +#endif /* May be used by disas_log or plugin callbacks. */ tb->size = db->pc_next - db->pc_first;
Signature · 1 line
2.54.0
PATCH v3 4/7 RFC: tcg: probe the TB jump cache inline instead of calling a helper
In reply to Matt TurnerEvery indirect branch that cannot use goto_tb ends in tcg_gen_lookup_and_goto_ptr(), which calls helper_lookup_tb_ptr(). For an emulated compiler that is 8.4 billion helper calls in a single translation
unit: 24.6% of all TB exits take this path, because jsr/ret/jmp have a register destination and because goto_tb is restricted to same-page targets.
The helper itself is already tight, but each call pays for a call frame, the can_do_io store, the get_tb_cpu_state() indirect call through TCGCPUOps, curr_cflags(), and a breakpoint check, before it gets to the jump cache probe that almost always hits (95.8% for this workload).
Emit the probe inline instead. The destination PC is already in a TCG temp, and the flags, cflags and cs_base the destination must match are constants at translation time, so the fast path is a hash, four guarded loads and a goto_ptr. Only a miss calls the helper, which still owns filling the cache.
tcg_gen_lookup_and_goto_ptr() therefore takes the destination PC and the TB being generated, and decides for itself whether to emit the probe or the old helper call; there is no second entry point for targets that opt in. A target that cannot name its destination in a single temp passes NULL and gets the helper. Since the probe hashes and compares the PC as one 64-bit value, a 32-bit guest PC also falls back.
The PC a target passes must be exactly what get_tb_cpu_state() reports for the destination, which is the whole of the contract. alpha, loongarch, mips, ppc and s390x pass their PC register, whose value is that pc by construction. The rest pass NULL for now: avr's TB pc is the word address doubled, i386's is eip before segmentation, riscv masks it to 32 bits when xl is MXL_RV32, hppa derives it from the IAQ, hexagon adjusts it inside a hardware loop, and sparc puts npc in cs_base so the guard could not hit anyway. Each of those is a one-line change for whoever wants to measure it.
Two details matter for the generated code. The flags and cflags guards are folded into a single aligned 64-bit load and compare, since the fields are adjacent. And each path emits its own goto_ptr rather than branching to a shared one: a temp live across the label is spilled and reloaded on every dispatch, which cost 6.3% on its own.
The probe cannot check everything the helper checks, and the one that matters is breakpoints. check_for_breakpoints() raises EXCP_DEBUG on an exact pc match and selects CF_BP_PAGE cflags for the rest of the page, and setting a breakpoint deliberately invalidates no TB, so a block translated before the breakpoint was set is still sitting in the jump cache. Rather than pay for a breakpoint test on the fast path, give the probe its own base pointer, tb_jmp_cache_probe, that nothing else reads, and point it at a page of zeroes while any breakpoint is set. Every entry the probe finds then has a NULL tb, so every dispatch misses into the helper and the old behaviour is restored exactly. cpu_breakpoint_insert() poisons the pointer, so the poison takes effect at the next dispatch rather than whenever that vCPU next reaches its main loop, which matters because a vCPU chaining indirectly need never reach it. The main loop puts the pointer back once the last breakpoint is gone; that is a load and a compare per block dispatched from the main loop, and nothing at all in generated code.
The flags and cflags constants are safe against the other things that can change them. CF_PARALLEL is only ever set by begin_parallel_context(), which flushes first, so no block predating it survives to dispatch. gdb single-step is only turned on with the CPU stopped, and a block translated without CF_SINGLE_STEP can only be re-entered through tb_lookup(), which from then on demands the new cflags -- so a stale-cflags block is never the one running. What is left is one_insn_per_tb and -d nochain, which the monitor can toggle under a running vCPU without a flush; see below.
Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host, LTO build, on top of the preceding three patches:
before: 1,402,667,803,616 instructions
after: 916,415,123,244 instructions -34.67%
before: 115.56s wall clock
after: 85.59s wall clock -25.94%The gap between the two is the point at which this stops being a straight-line win: the helper call was highly predictable work that the host pipelined well, so removing it retires far fewer instructions than it saves time. IPC falls from 2.48 to 2.17 across this patch for that reason.
Despite emitting more code, this also reduces instruction cache pressure, because a dispatch no longer jumps into qemu's .text and evicts translated code:
before: 11,735,141,703 L1-icache-load-misses
after: 7,154,863,292 L1-icache-load-misses -39.0%The mechanism is visible directly in a profile: helper_lookup_tb_ptr() falls from 31.01% of samples to 0.35%, and qemu's own .text falls from 38.8% to 5.3%, with the balance moving into generated code.
Combined with the three preceding patches, against an unmodified LTO build, 1,646,994,254,249 instructions fall to 916,415,123,244, or -44.36%. The emulated compiler produces byte-identical output throughout.
Open issues, hence RFC:
- one_insn_per_tb and CPU_LOG_TB_NOCHAIN can be toggled from the monitor while a vCPU is inside a block that was translated without them. The block keeps dispatching inline with the old cflags until it exits for some other reason. Poisoning the probe from tcg_update_all_curr_cflags() would close it.
- The jump cache entry is read without qatomic_read(); entries are invalidated concurrently by setting tb to NULL.
- Only alpha has been measured. The other four targets that pass a PC are built and boot-tested only.
v3: Fold the fast path into tcg_gen_lookup_and_goto_ptr() instead of
adding tcg_gen_lookup_and_goto_ptr_inline() beside it (Richard). It now takes the destination PC and the TB unconditionally, from all 38 call sites, and picks the probe or the helper itself. Translators built for both values of TARGET_LONG_BITS -- arm, s390x, microblaze -- cannot include tcg-op.h, so the common entry point takes a TCGTemp and reads the width from it, and tcg-op.h wraps that for everyone else; this is the same split as tcg_gen_qemu_ld_*_chk().
Compare cs_base too. v2 listed this as an open issue, and closing it is what lets the choice be made generically rather than per target: a target that uses cs_base would otherwise have been enabled silently by a decision keyed on PC width alone. It costs a load and a compare on the fast path, and the numbers above were measured with it in place.
Audited which targets may pass a real PC, the contract being that it is exactly what get_tb_cpu_state() reports for the destination. Five do; the rest pass NULL and keep the helper call, sparc among them because it puts npc in cs_base and so could essentially never hit.
Poison the probe from cpu_breakpoint_insert() rather than only from the poisoned CPU's own main loop. gdb inserts a breakpoint into every CPU (tcg_insert_gdbstub_breakpoint()), and a thread already inside generated code, dispatching indirectly, need never return to the main loop -- so it would keep dispatching inline and run past a breakpoint another thread had just set. Upstream has no such window: its helper_lookup_tb_ptr() sees the new breakpoint at the next indirect branch. The un-poison in tcg_cpu_sync_jmp_cache() now re-checks after its store, with a barrier, so that it loses the race with a concurrent insert in the safe direction.
--- accel/tcg/cpu-exec.c | 102 ++++++++++++++++++ accel/tcg/internal-common.h | 2 + cpu-common.c | 11 ++ include/hw/core/cpu.h | 9 ++ include/system/tcg.h | 9 ++ include/tcg/tcg-op-common.h | 16 ++- include/tcg/tcg-op.h | 12 +++ stubs/tcg-cflags.c | 8 +- target/alpha/translate.c | 4 +- target/arm/tcg/translate-a64.c | 4 +- target/arm/tcg/translate.c | 10 +- target/avr/translate.c | 4 +- target/hexagon/translate.c | 4 +- target/hppa/translate.c | 6 +- target/i386/tcg/translate.c | 2 +- .../tcg/insn_trans/trans_branch.c.inc | 2 +- target/loongarch/tcg/translate.c | 4 +- target/m68k/translate.c | 2 +- target/microblaze/translate.c | 4 +- target/mips/tcg/nanomips_translate.c.inc | 2 +- target/mips/tcg/translate.c | 6 +- target/or1k/translate.c | 4 +- target/ppc/translate.c | 4 +- target/riscv/tcg/insn_trans/trans_rvzce.c.inc | 4 +- target/riscv/tcg/translate.c | 2 +- target/rx/translate.c | 4 +- target/s390x/tcg/translate.c | 5 +- target/sh4/translate.c | 4 +- target/sparc/translate.c | 4 +- target/tricore/translate.c | 4 +- tcg/tcg-op.c | 92 +++++++++++++++- 31 files changed, 300 insertions(+), 50 deletions(-)
accel/tcg/cpu-exec.c +102 -0
@@ -752,6 +752,99 @@ static inline bool cpu_handle_exception(CPUState *cpu, int *ret)return false; } +/* +* The inline jump cache probe reads cpu->tb_jmp_cache_probe and takes the +* slow path when the entry it finds has a NULL tb. Pointing the probe at a +* region that is all zeroes therefore forces every indirect dispatch into +* helper_lookup_tb_ptr(), which does the full lookup the inline probe only +* approximates. The real jump cache is untouched, so no contents are lost +* and recovery is a single store. +* +* Only ever read from, and only the tb field of one entry per dispatch, so +* one shared zero-filled cache is enough for every CPU. +*/ +static const CPUJumpCache *tb_jmp_cache_poison (void ) +{ +static CPUJumpCache *poison; + +if (unlikely (poison ==NULL )) { +/* Raced allocations are harmless: both are all zeroes. */ +qatomic_cmpxchg (&poison,NULL ,g_new0 (CPUJumpCache,1 )); + } +return poison; +} + +/* +* Whether the generated code may dispatch to the next block by itself. +* +* The inline probe matches on the destination pc and on the flags and +* cflags the dispatching block was translated with. It does not consult +* cpu->breakpoints, so it must not run while one is set: setting a +* breakpoint deliberately invalidates nothing, and check_for_breakpoints() +* both raises EXCP_DEBUG on an exact match and picks CF_BP_PAGE cflags for +* the rest of the page. A block translated before the breakpoint was set is +* therefore still in the jump cache, and dispatching to it inline would step +* straight over the breakpoint. +*/ +static bool tcg_cpu_may_dispatch (CPUState *cpu) +{ +return QTAILQ_EMPTY (&cpu->breakpoints); +} + +/* +* Poison @cpu's probe, from any thread. Called when a breakpoint is +* inserted, which is what makes the poison take effect at the dispatch +* after the insert rather than whenever @cpu next reaches its main loop: +* a vCPU chaining indirectly need never reach it, and would run past a +* breakpoint another thread had just set. +* +* A plain store is enough. The value only ever costs a slow path that is +* correct on its own, and the generated code re-reads the base on every +* dispatch. Un-poisoning is tcg_cpu_sync_jmp_cache()'s job. +*/ +void tcg_cpu_poison_jmp_cache (CPUState *cpu) +{ +if (qatomic_read (&cpu->tb_jmp_cache_probe) !=NULL ) { +qatomic_set (&cpu->tb_jmp_cache_probe, + (CPUJumpCache *)tb_jmp_cache_poison ()); + } +} + +/* +* Called from the main loop, which is the only context that can establish +* that no reason to be poisoned is left. Cheap enough to call every time +* round: the common case is a load, a compare and no store at all. +*/ +void tcg_cpu_sync_jmp_cache (CPUState *cpu) +{ +CPUJumpCache *want; + +if (qatomic_read (&cpu->tb_jmp_cache_probe) ==NULL ) { +return ;/* not realized, or already unrealized */ + } + + want =tcg_cpu_may_dispatch (cpu) + ? cpu->tb_jmp_cache + : (CPUJumpCache *)tb_jmp_cache_poison (); + +if (qatomic_read (&cpu->tb_jmp_cache_probe) != want) { +qatomic_set (&cpu->tb_jmp_cache_probe, want); + +/* +* Un-poisoning races a concurrent tcg_cpu_poison_jmp_cache(): the +* reason may have appeared after tcg_cpu_may_dispatch() read it and +* the poison may have landed before the store above. Order the +* store against a re-read, and lose the race in the safe direction. +*/ +if (want == cpu->tb_jmp_cache) { +smp_mb (); +if (!tcg_cpu_may_dispatch (cpu)) { +tcg_cpu_poison_jmp_cache (cpu); + } + } + } +} +void tcg_kick_vcpu_thread (CPUState *cpu) {/*
@@ -964,6 +1057,13 @@ cpu_exec_loop(CPUState *cpu, SyncClocks *sc)break ; } +/* +* Reaching here means the main loop has just re-evaluated +* everything the inline probe assumes, so this is where the +* probe is allowed to come back after a poison. +*/ +tcg_cpu_sync_jmp_cache (cpu); + tb =tb_lookup (cpu, s);if (tb ==NULL ) {CPUJumpCache *jc;
@@ -1072,6 +1172,7 @@ bool tcg_exec_realizefn(CPUState *cpu, Error **errp)tcg_update_cflags (cpu); cpu->tb_jmp_cache =g_new0 (CPUJumpCache,1 ); +qatomic_set (&cpu->tb_jmp_cache_probe, cpu->tb_jmp_cache);tlb_init (cpu);#ifndef CONFIG_USER_ONLY tcg_iommu_init_notifier_list (cpu);
@@ -1089,5 +1190,6 @@ void tcg_exec_unrealizefn(CPUState *cpu)#endif /* !CONFIG_USER_ONLY */ tlb_destroy (cpu); +qatomic_set (&cpu->tb_jmp_cache_probe,NULL );g_free_rcu (cpu->tb_jmp_cache, rcu); }
accel/tcg/internal-common.h +2 -0
@@ -144,6 +144,8 @@ void page_table_config_init(void); G_NORETURN void cpu_io_recompile(CPUState *cpu, uintptr_t retaddr);#endif /* CONFIG_USER_ONLY */ +void tcg_cpu_sync_jmp_cache (CPUState *cpu); +void tb_phys_invalidate (TranslationBlock *tb,tb_page_addr_t page_addr);void tb_set_jmp_target (TranslationBlock *tb,int n,uintptr_t addr);
cpu-common.c +11 -0
@@ -22,6 +22,7 @@#include "exec/cpu-common.h" #include "hw/core/cpu.h" #include "qemu/lockable.h" +#include "system/tcg.h" #include "trace/trace-root.h" QemuMutex qemu_cpu_list_lock;
@@ -429,6 +430,16 @@ int cpu_breakpoint_insert(CPUState *cpu, vaddr pc, int flags, *breakpoint = bp; } +/* +* Nothing is invalidated here, so blocks translated before this point +* are still live and still dispatch to each other without consulting +* cpu->breakpoints. Stop the ones that can: a TCG vCPU dispatching +* inline reads a base pointer that this poisons, so the next dispatch +* takes the slow path and sees the new breakpoint. @cpu may be another +* thread, and may be running. +*/ +tcg_cpu_poison_jmp_cache (cpu); +trace_breakpoint_insert (cpu->cpu_index, pc, flags);return 0 ; }
include/hw/core/cpu.h +9 -0
@@ -519,6 +519,15 @@ struct CPUState {MemoryRegion *memory;struct CPUJumpCache *tb_jmp_cache; +/* +* @tb_jmp_cache_probe: base the inline jump cache probe reads. +* +* Normally @tb_jmp_cache. Pointed at a shared page of zeroes to force +* every inline dispatch to miss and fall back to helper_lookup_tb_ptr(); +* see tcg_cpu_sync_jmp_cache(). NULL before tcg_exec_realizefn() and +* after tcg_exec_unrealizefn(). +*/ +struct CPUJumpCache *tb_jmp_cache_probe;GArray *gdb_regs;int gdb_num_regs;
include/system/tcg.h +9 -0
@@ -29,6 +29,15 @@ extern bool tcg_allowed;void tcg_update_cflags (CPUState *cpu);void tcg_update_all_cflags (void ); +/* +* Force @cpu's generated code back into the slow dispatch path, which +* re-checks everything the inline jump cache probe assumes. Safe to call +* from any thread, and a no-op for a CPU that is not running TCG. Call +* whenever something the probe cannot see changes under a running vCPU; +* the main loop undoes it once the reason is gone. +*/ +void tcg_cpu_poison_jmp_cache (CPUState *cpu); +/** * qemu_tcg_mttcg_enabled: * Check whether we are running MultiThread TCG or not.
include/tcg/tcg-op-common.h +13 -3
@@ -75,15 +75,25 @@ void tcg_gen_exit_tb(const TranslationBlock *tb, unsigned idx);void tcg_gen_goto_tb (unsigned idx);/** -* tcg_gen_lookup_and_goto_ptr() - look up the current TB, jump to it if valid -* @addr: Guest address of the target TB +* tcg_gen_lookup_and_goto_ptr() - look up the destination TB, jump to it +* @pc: temp holding the destination guest PC, or NULL +* @tb: the translation block being generated * * If the TB is not valid, jump to the epilogue. * +* The lookup is normally a call to helper_lookup_tb_ptr(). If @pc is +* non-NULL and the destination can be keyed on it directly, the jump cache +* is probed inline instead and only a miss reaches the helper. @pc must +* then hold exactly the value get_tb_cpu_state() reports as the pc for the +* destination; a target whose pc is derived (avr's word address, i386's +* eip before segmentation) must pass NULL. The destination is required to +* match @tb's flags, cflags and cs_base, which is what makes them +* constants in the probe. +* * This operation is optional. If the TCG backend does not implement goto_ptr, * this op is equivalent to calling tcg_gen_exit_tb() with 0 as the argument. */ -void tcg_gen_lookup_and_goto_ptr (void ); +void tcg_gen_lookup_and_goto_ptr_tmp (TCGTemp *pc,const TranslationBlock *tb);void tcg_gen_plugin_cb (unsigned from);void tcg_gen_plugin_mem_cb (TCGv_i64 addr,unsigned meminfo);
include/tcg/tcg-op.h +12 -0
@@ -49,6 +49,18 @@ typedef TCGv_i64 TCGv;#error Unhandled TARGET_LONG_BITS value#endif +/* +* See tcg_gen_lookup_and_goto_ptr_tmp(). @pc may be NULL, for a target +* whose guest PC is not directly the key the jump cache is indexed by. +* A translator that is built for more than one value of TARGET_LONG_BITS, +* and so cannot include this header, calls the _tmp() form directly. +*/ +static inline void +tcg_gen_lookup_and_goto_ptr (TCGv pc,const TranslationBlock *tb) +{ +tcg_gen_lookup_and_goto_ptr_tmp (pc ?tcgv_tl_temp (pc) :NULL , tb); +} +#if TARGET_LONG_BITS ==64 #define tcg_gen_movi_tl tcg_gen_movi_i64#define tcg_gen_mov_tl tcg_gen_mov_i64
stubs/tcg-cflags.c +6 -2
@@ -1,6 +1,6 @@/* -* Stub for tcg_update_all_cflags(), for binaries that link util/log.c -* or cpu-target.c but not TCG. +* Stubs for the TCG entry points in system/tcg.h, for binaries that link +* util/log.c, cpu-target.c or cpu-common.c but not TCG. * * SPDX-License-Identifier: GPL-2.0-or-later */
@@ -14,3 +14,7 @@ void tcg_update_cflags(CPUState *cpu)void tcg_update_all_cflags (void ) { } + +void tcg_cpu_poison_jmp_cache (CPUState *cpu) +{ +}
target/alpha/translate.c +2 -2
@@ -449,7 +449,7 @@ static void gen_goto_tb(DisasContext *ctx, unsigned tb_slot_idx, int32_t disp)tcg_gen_exit_tb (ctx->base.tb, tb_slot_idx); }else {gen_pc_disp (ctx, cpu_pc, disp); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (cpu_pc, ctx->base.tb); } }
@@ -2917,7 +2917,7 @@ static void alpha_tr_tb_stop(DisasContextBase *dcbase, CPUState *cpu)gen_pc_disp (ctx, cpu_pc,0 );/* FALLTHRU */ case DISAS_PC_UPDATED : -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (cpu_pc, ctx->base.tb);break ;case DISAS_PC_UPDATED_NOCHAIN :tcg_gen_exit_tb (NULL ,0 );
target/arm/tcg/translate-a64.c +2 -2
@@ -562,7 +562,7 @@ static void gen_goto_tb(DisasContext *s, unsigned tb_slot_idx, int64_t diff)if (s->ss_active) {gen_step_complete_exception (s); }else { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , s->base.tb); s->base.is_jmp =DISAS_NORETURN ; } }
@@ -11250,7 +11250,7 @@ static void aarch64_tr_tb_stop(DisasContextBase *dcbase, CPUState *cpu)gen_a64_update_pc (dc,4 );/* fall through */ case DISAS_JUMP : -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , dc->base.tb);break ;case DISAS_NORETURN :case DISAS_SWI :
target/arm/tcg/translate.c +5 -5
@@ -1306,9 +1306,9 @@ void write_neon_element64(TCGv_i64 src, int reg, int ele, MemOp memop) } } -static void gen_goto_ptr (void ) +static void gen_goto_ptr (DisasContext *s) { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr_tmp (NULL , s->base.tb); }/* This will end the TB but doesn't guarantee we'll return to
@@ -1336,7 +1336,7 @@ static void gen_goto_tb(DisasContext *s, unsigned tb_slot_idx, int64_t diff)tcg_gen_exit_tb (s->base.tb, tb_slot_idx); }else {gen_update_pc (s, diff); -gen_goto_ptr (); +gen_goto_ptr (s); } s->base.is_jmp =DISAS_NORETURN ; }
@@ -1373,7 +1373,7 @@ static void gen_jmp_tb(DisasContext *s, int64_t diff, int tbno)* and don't chain to another TB. */ gen_update_pc (s, diff); -gen_goto_ptr (); +gen_goto_ptr (s); s->base.is_jmp =DISAS_NORETURN ;break ;default :
@@ -6858,7 +6858,7 @@ static void arm_tr_tb_stop(DisasContextBase *dcbase, CPUState *cpu)gen_update_pc (dc,curr_insn_len (dc));/* fall through */ case DISAS_JUMP : -gen_goto_ptr (); +gen_goto_ptr (dc);break ;case DISAS_UPDATE_EXIT :gen_update_pc (dc,curr_insn_len (dc));
target/avr/translate.c +2 -2
@@ -992,7 +992,7 @@ static void gen_goto_tb(DisasContext *ctx, unsigned tb_slot_idx,tcg_gen_exit_tb (tb, tb_slot_idx); }else {tcg_gen_movi_i32 (cpu_pc, dest); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb); } ctx->base.is_jmp =DISAS_NORETURN ; }
@@ -2778,7 +2778,7 @@ static void avr_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)/* fall through */ case DISAS_LOOKUP :if (!force_exit) { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb);break ; }/* fall through */
target/hexagon/translate.c +2 -2
@@ -181,7 +181,7 @@ static void gen_goto_tb(DisasContext *ctx, unsigned tb_slot_idx,if (move_to_pc) {tcg_gen_movi_tl (hex_gpr[HEX_REG_PC ], dest); } -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb); } }
@@ -218,7 +218,7 @@ static void gen_end_tb(DisasContext *ctx)gen_set_label (skip);gen_goto_tb (ctx,1 , ctx->next_PC, false); }else { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb); } ctx->base.is_jmp =DISAS_NORETURN ;
target/hppa/translate.c +3 -3
@@ -816,7 +816,7 @@ static void gen_goto_tb(DisasContext *ctx, int which,tcg_gen_goto_tb (which);tcg_gen_exit_tb (ctx->base.tb, which); }else { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb); } }
@@ -2027,7 +2027,7 @@ static bool do_ibranch(DisasContext *ctx, unsigned link,store_psw_xb (ctx,PSW_B ); } -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb); ctx->base.is_jmp =DISAS_NORETURN ;return nullify_end (ctx); }
@@ -4838,7 +4838,7 @@ static void hppa_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs) }/* FALLTHRU */ case DISAS_IAQ_N_UPDATED : -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb);break ;case DISAS_EXIT :tcg_gen_exit_tb (NULL ,0 );
target/i386/tcg/translate.c +1 -1
@@ -2005,7 +2005,7 @@ gen_eob(DisasContext *s, int mode) }else if (mode ==DISAS_JUMP &&/* give irqs a chance to happen */ !inhibit_reset) { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , s->base.tb); }else {tcg_gen_exit_tb (NULL ,0 ); }
target/loongarch/tcg/insn_trans/trans_branch.c.inc +1 -1
@@ -27,7 +27,7 @@ static bool trans_jirl(DisasContext *ctx, arg_jirl *a) tcg_gen_mov_tl(cpu_pc, addr); tcg_gen_movi_tl(dest, make_address_pc(ctx, ctx->base.pc_next + 4)); gen_set_gpr(a->rd, dest, EXT_NONE); - tcg_gen_lookup_and_goto_ptr(); + tcg_gen_lookup_and_goto_ptr(cpu_pc, ctx->base.tb); ctx->base.is_jmp = DISAS_NORETURN; return true; }
target/loongarch/tcg/translate.c +2 -2
@@ -111,7 +111,7 @@ static void gen_goto_tb(DisasContext *ctx, unsigned tb_slot_idx, vaddr dest)tcg_gen_exit_tb (ctx->base.tb, tb_slot_idx); }else {tcg_gen_movi_tl (cpu_pc, dest); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (cpu_pc, ctx->base.tb); } }
@@ -311,7 +311,7 @@ static void loongarch_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)switch (ctx->base.is_jmp) {case DISAS_STOP :tcg_gen_movi_tl (cpu_pc, ctx->base.pc_next); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (cpu_pc, ctx->base.tb);break ;case DISAS_TOO_MANY :gen_goto_tb (ctx,0 , ctx->base.pc_next);
target/m68k/translate.c +1 -1
@@ -6095,7 +6095,7 @@ static void m68k_tr_tb_stop(DisasContextBase *dcbase, CPUState *cpu)if (dc->ss_active) {gen_raise_exception_format2 (dc,EXCP_TRACE , dc->pc_prev); }else { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , dc->base.tb); }break ;case DISAS_EXIT :
target/microblaze/translate.c +2 -2
@@ -127,7 +127,7 @@ static void gen_goto_tb(DisasContext *dc, unsigned tb_slot_idx, vaddr dest)tcg_gen_exit_tb (dc->base.tb, tb_slot_idx); }else {tcg_gen_movi_i32 (cpu_pc, dest); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr_tmp (NULL , dc->base.tb); } dc->base.is_jmp =DISAS_NORETURN ; }
@@ -1764,7 +1764,7 @@ static void mb_tr_tb_stop(DisasContextBase *dcb, CPUState *cs)/* Indirect jump (or direct jump w/ goto_tb disabled) */ tcg_gen_mov_i32 (cpu_pc, cpu_btarget);tcg_gen_discard_i32 (cpu_btarget); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr_tmp (NULL , dc->base.tb);return ;default :
target/mips/tcg/nanomips_translate.c.inc +1 -1
@@ -2406,7 +2406,7 @@ static void gen_compute_nanomips_pbalrsc_branch(DisasContext *ctx, int rs, /* unconditional branch to register */ tcg_gen_mov_tl(cpu_PC, btarget); - tcg_gen_lookup_and_goto_ptr(); + tcg_gen_lookup_and_goto_ptr(cpu_PC, ctx->base.tb); } /* nanoMIPS Branches */
target/mips/tcg/translate.c +3 -3
@@ -4374,7 +4374,7 @@ static void gen_goto_tb(DisasContext *ctx, unsigned tb_slot_idx,tcg_gen_exit_tb (ctx->base.tb, tb_slot_idx); }else {gen_save_pc (dest); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (cpu_PC, ctx->base.tb); } }
@@ -11014,7 +11014,7 @@ static void gen_branch(DisasContext *ctx, int insn_bytes) }else {tcg_gen_mov_tl (cpu_PC, btarget); } -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (cpu_PC, ctx->base.tb);break ;default :LOG_DISAS ("unknown branch 0x%x\n" , proc_hflags);
@@ -15244,7 +15244,7 @@ static void mips_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)switch (ctx->base.is_jmp) {case DISAS_STOP :gen_save_pc (ctx->base.pc_next); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (cpu_PC, ctx->base.tb);break ;case DISAS_NEXT :case DISAS_TOO_MANY :
target/or1k/translate.c +2 -2
@@ -1605,7 +1605,7 @@ static void openrisc_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)/* The jump destination is indirect/computed; use jmp_pc. */ tcg_gen_mov_i32 (cpu_pc, jmp_pc);tcg_gen_discard_i32 (jmp_pc); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , dc->base.tb);break ; }/* The jump destination is direct; use jmp_pc_imm.
@@ -1622,7 +1622,7 @@ static void openrisc_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)break ; }tcg_gen_movi_i32 (cpu_pc, jmp_dest); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , dc->base.tb);break ;case DISAS_EXIT :
target/ppc/translate.c +2 -2
@@ -3664,7 +3664,7 @@ static void gen_lookup_and_goto_ptr(DisasContext *ctx)pmu_count_insns (ctx); } -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (cpu_nip, ctx->base.tb); } }
@@ -6690,7 +6690,7 @@ static void ppc_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)pmu_count_insns (ctx); } -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (cpu_nip, ctx->base.tb);break ;case DISAS_EXIT_UPDATE :
target/riscv/tcg/insn_trans/trans_rvzce.c.inc +2 -2
@@ -213,7 +213,7 @@ static bool gen_pop(DisasContext *ctx, arg_cmpp *a, bool ret, bool ret_val) } #endif tcg_gen_mov_tl(cpu_pc, ret_addr); - tcg_gen_lookup_and_goto_ptr(); + tcg_gen_lookup_and_goto_ptr(NULL, ctx->base.tb); ctx->base.is_jmp = DISAS_NORETURN; }
@@ -334,7 +334,7 @@ static bool trans_cm_jalt(DisasContext *ctx, arg_cm_jalt *a) tcg_gen_mov_tl(cpu_pc, addr); - tcg_gen_lookup_and_goto_ptr(); + tcg_gen_lookup_and_goto_ptr(NULL, ctx->base.tb); ctx->base.is_jmp = DISAS_NORETURN; return true; }
target/riscv/tcg/translate.c +1 -1
@@ -287,7 +287,7 @@ static void lookup_and_goto_ptr(DisasContext *ctx) gen_helper_itrigger_match(tcg_env); }#endif -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb); }static void exit_tb (DisasContext *ctx)
target/rx/translate.c +2 -2
@@ -161,7 +161,7 @@ static void gen_goto_tb(DisasContext *dc, unsigned tb_slot_idx, vaddr dest)tcg_gen_exit_tb (dc->base.tb, tb_slot_idx); }else {tcg_gen_movi_i32 (cpu_pc, dest); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , dc->base.tb); } dc->base.is_jmp =DISAS_NORETURN ; }
@@ -2242,7 +2242,7 @@ static void rx_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)gen_goto_tb (ctx,0 , dcbase->pc_next);break ;case DISAS_JUMP : -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb);break ;case DISAS_UPDATE :tcg_gen_movi_i32 (cpu_pc, ctx->base.pc_next);
target/s390x/tcg/translate.c +3 -2
@@ -1162,7 +1162,7 @@ static DisasJumpType help_branch(DisasContext *s, DisasCompare *c,tcg_gen_goto_tb (0 );tcg_gen_exit_tb (s->base.tb,0 ); }else { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr_tmp (tcgv_i64_temp (psw_addr), s->base.tb); }gen_set_label (lab);
@@ -6477,7 +6477,8 @@ static void s390x_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)if (dc->exit_to_mainloop) {tcg_gen_exit_tb (NULL ,0 ); }else { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr_tmp (tcgv_i64_temp (psw_addr), + dc->base.tb); }break ;default :
target/sh4/translate.c +2 -2
@@ -242,7 +242,7 @@ static void gen_goto_tb(DisasContext *ctx, unsigned tb_slot_idx, vaddr dest)if (use_exit_tb (ctx)) {tcg_gen_exit_tb (NULL ,0 ); }else { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb); } } ctx->base.is_jmp =DISAS_NORETURN ;
@@ -258,7 +258,7 @@ static void gen_jump(DisasContext * ctx)if (use_exit_tb (ctx)) {tcg_gen_exit_tb (NULL ,0 ); }else { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb); } ctx->base.is_jmp =DISAS_NORETURN ; }else {
target/sparc/translate.c +2 -2
@@ -376,7 +376,7 @@ static void gen_goto_tb(DisasContext *s, unsigned tb_slot_idx,/* jump to another page: we can use an indirect jump */ tcg_gen_movi_tl (cpu_pc, pc);tcg_gen_movi_tl (cpu_npc, npc); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , s->base.tb); } }
@@ -5807,7 +5807,7 @@ static void sparc_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)tcg_gen_movi_tl (cpu_npc, dc->npc); }if (may_lookup) { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , dc->base.tb); }else {tcg_gen_exit_tb (NULL ,0 ); }
target/tricore/translate.c +2 -2
@@ -2857,7 +2857,7 @@ static void gen_goto_tb(DisasContext *ctx, unsigned tb_slot_index, vaddr dest)tcg_gen_exit_tb (ctx->base.tb, tb_slot_index); }else {gen_save_pc (dest); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb); } ctx->base.is_jmp =DISAS_NORETURN ; }
@@ -8478,7 +8478,7 @@ static void tricore_tr_tb_stop(DisasContextBase *dcbase, CPUState *cpu)tcg_gen_exit_tb (NULL ,0 );break ;case DISAS_JUMP : -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb);break ;case DISAS_NORETURN :break ;
tcg/tcg-op.c +91 -1
111 lines not on this page · raw message
Signature · 1 line
2.54.0
Re: [PATCH v3 4/7] RFC: tcg: probe the TB jump cache inline instead of calling a helper
Quoted 192 lines · Matt Turner
Every indirect branch that cannot use
goto_tbends intcg_gen_lookup_and_goto_ptr(), which callshelper_lookup_tb_ptr(). For an emulated compiler that is 8.4 billion helper calls in a single translation
unit: 24.6% of all TB exits take this path, because jsr/ret/jmp have a register destination and becausegoto_tbis restricted to same-page targets.The helper itself is already tight, but each call pays for a call frame, the
can_do_iostore, theget_tb_cpu_state()indirect call through TCGCPUOps,curr_cflags(), and a breakpoint check, before it gets to the jump cache probe that almost always hits (95.8% for this workload).Emit the probe inline instead. The destination PC is already in a TCG temp, and the flags, cflags and
cs_basethe destination must match are constants at translation time, so the fast path is a hash, four guarded loads and agoto_ptr. Only a miss calls the helper, which still owns filling the cache.
tcg_gen_lookup_and_goto_ptr()therefore takes the destination PC and the TB being generated, and decides for itself whether to emit the probe or the old helper call; there is no second entry point for targets that opt in. A target that cannot name its destination in a single temp passes NULL and gets the helper. Since the probe hashes and compares the PC as one 64-bit value, a 32-bit guest PC also falls back.The PC a target passes must be exactly what
get_tb_cpu_state()reports for the destination, which is the whole of the contract. alpha, loongarch, mips, ppc and s390x pass their PC register, whose value is that pc by construction. The rest pass NULL for now: avr's TB pc is the word address doubled, i386's is eip before segmentation, riscv masks it to 32 bits when xl isMXL_RV32, hppa derives it from the IAQ, hexagon adjusts it inside a hardware loop, and sparc puts npc incs_baseso the guard could not hit anyway. Each of those is a one-line change for whoever wants to measure it.Two details matter for the generated code. The flags and cflags guards are folded into a single aligned 64-bit load and compare, since the fields are adjacent. And each path emits its own
goto_ptrrather than branching to a shared one: a temp live across the label is spilled and reloaded on every dispatch, which cost 6.3% on its own.The probe cannot check everything the helper checks, and the one that matters is breakpoints.
check_for_breakpoints()raisesEXCP_DEBUGon an exact pc match and selectsCF_BP_PAGEcflags for the rest of the page, and setting a breakpoint deliberately invalidates no TB, so a block translated before the breakpoint was set is still sitting in the jump cache. Rather than pay for a breakpoint test on the fast path, give the probe its own base pointer,tb_jmp_cache_probe, that nothing else reads, and point it at a page of zeroes while any breakpoint is set. Every entry the probe finds then has a NULL tb, so every dispatch misses into the helper and the old behaviour is restored exactly.cpu_breakpoint_insert()poisons the pointer, so the poison takes effect at the next dispatch rather than whenever that vCPU next reaches its main loop, which matters because a vCPU chaining indirectly need never reach it. The main loop puts the pointer back once the last breakpoint is gone; that is a load and a compare per block dispatched from the main loop, and nothing at all in generated code.The flags and cflags constants are safe against the other things that can change them.
CF_PARALLELis only ever set bybegin_parallel_context(), which flushes first, so no block predating it survives to dispatch. gdb single-step is only turned on with the CPU stopped, and a block translated withoutCF_SINGLE_STEPcan only be re-entered throughtb_lookup(), which from then on demands the new cflags -- so a stale-cflags block is never the one running. What is left isone_insn_per_tband -d nochain, which the monitor can toggle under a running vCPU without a flush; see below.Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host, LTO build, on top of the preceding three patches:
before: 1,402,667,803,616 instructions after: 916,415,123,244 instructions -34.67% before: 115.56s wall clock after: 85.59s wall clock -25.94%The gap between the two is the point at which this stops being a straight-line win: the helper call was highly predictable work that the host pipelined well, so removing it retires far fewer instructions than it saves time. IPC falls from 2.48 to 2.17 across this patch for that reason.
Despite emitting more code, this also reduces instruction cache pressure, because a dispatch no longer jumps into qemu's .text and evicts translated code:
before: 11,735,141,703 L1-icache-load-misses after: 7,154,863,292 L1-icache-load-misses -39.0%The mechanism is visible directly in a profile:
helper_lookup_tb_ptr()falls from 31.01% of samples to 0.35%, and qemu's own .text falls from 38.8% to 5.3%, with the balance moving into generated code.Combined with the three preceding patches, against an unmodified LTO build, 1,646,994,254,249 instructions fall to 916,415,123,244, or -44.36%. The emulated compiler produces byte-identical output throughout.
Open issues, hence RFC:
-
one_insn_per_tbandCPU_LOG_TB_NOCHAINcan be toggled from the monitor while a vCPU is inside a block that was translated without them. The block keeps dispatching inline with the old cflags until it exits for some other reason. Poisoning the probe fromtcg_update_all_curr_cflags()would close it.
- The jump cache entry is read withoutqatomic_read(); entries are invalidated concurrently by setting tb to NULL.
- Only alpha has been measured. The other four targets that pass a PC are built and boot-tested only.v3: Fold the fast path into
tcg_gen_lookup_and_goto_ptr()instead of
addingtcg_gen_lookup_and_goto_ptr_inline()beside it (Richard). It now takes the destination PC and the TB unconditionally, from all 38 call sites, and picks the probe or the helper itself. Translators built for both values ofTARGET_LONG_BITS-- arm, s390x, microblaze -- cannot includetcg-op.h, so the common entry point takes a TCGTemp and reads the width from it, andtcg-op.hwraps that for everyone else; this is the same split as tcg_gen_qemu_ld_*_chk().Compare
cs_basetoo. v2 listed this as an open issue, and closing it is what lets the choice be made generically rather than per target: a target that usescs_basewould otherwise have been enabled silently by a decision keyed on PC width alone. It costs a load and a compare on the fast path, and the numbers above were measured with it in place.Audited which targets may pass a real PC, the contract being that it is exactly what
get_tb_cpu_state()reports for the destination. Five do; the rest pass NULL and keep the helper call, sparc among them because it puts npc incs_baseand so could essentially never hit.Poison the probe from
cpu_breakpoint_insert()rather than only from the poisoned CPU's own main loop. gdb inserts a breakpoint into every CPU (tcg_insert_gdbstub_breakpoint()), and a thread already inside generated code, dispatching indirectly, need never return to the main loop -- so it would keep dispatching inline and run past a breakpoint another thread had just set. Upstream has no such window: itshelper_lookup_tb_ptr()sees the new breakpoint at the next indirect branch. The un-poison intcg_cpu_sync_jmp_cache()now re-checks after its store, with a barrier, so that it loses the race with a concurrent insert in the safe direction.Signed-off-by Matt Turner <[email protected]>--- accel/tcg/cpu-exec.c | 102 ++++++++++++++++++ accel/tcg/internal-common.h | 2 + cpu-common.c | 11 ++ include/hw/core/cpu.h | 9 ++ include/system/tcg.h | 9 ++ include/tcg/tcg-op-common.h | 16 ++- include/tcg/tcg-op.h | 12 +++ stubs/tcg-cflags.c | 8 +- target/alpha/translate.c | 4 +- target/arm/tcg/translate-a64.c | 4 +- target/arm/tcg/translate.c | 10 +- target/avr/translate.c | 4 +- target/hexagon/translate.c | 4 +- target/hppa/translate.c | 6 +- target/i386/tcg/translate.c | 2 +- .../tcg/insn_trans/trans_branch.c.inc | 2 +- target/loongarch/tcg/translate.c | 4 +- target/m68k/translate.c | 2 +- target/microblaze/translate.c | 4 +- target/mips/tcg/nanomips_translate.c.inc | 2 +- target/mips/tcg/translate.c | 6 +- target/or1k/translate.c | 4 +- target/ppc/translate.c | 4 +- target/riscv/tcg/insn_trans/trans_rvzce.c.inc | 4 +- target/riscv/tcg/translate.c | 2 +- target/rx/translate.c | 4 +- target/s390x/tcg/translate.c | 5 +- target/sh4/translate.c | 4 +- target/sparc/translate.c | 4 +- target/tricore/translate.c | 4 +- tcg/tcg-op.c | 92 +++++++++++++++- 31 files changed, 300 insertions(+), 50 deletions(-)accel/tcg/cpu-exec.c +11
-0@@ -752,6 +752,99 @@ static inline bool cpu_handle_exception(CPUState *cpu, int *ret)return false; } +/* +* The inline jump cache probe reads cpu->tb_jmp_cache_probe and takes the +* slow path when the entry it finds has a NULL tb. Pointing the probe at a +* region that is all zeroes therefore forces every indirect dispatch into +* helper_lookup_tb_ptr(), which does the full lookup the inline probe only +* approximates. The real jump cache is untouched, so no contents are lost +* and recovery is a single store. +* +* Only ever read from, and only the tb field of one entry per dispatch, so +* one shared zero-filled cache is enough for every CPU. +*/
accel/tcg/cpu-exec.c static inline bool cpu_handle_exception(CPUState *cpu, int *ret) · line 775
Quoted 10 lines
accel/tcg/cpu-exec.c +10
-0+static const CPUJumpCache *tb_jmp_cache_poison (void ) +{ +static CPUJumpCache *poison; + +if (unlikely (poison ==NULL )) { +/* Raced allocations are harmless: both are all zeroes. */ +qatomic_cmpxchg (&poison,NULL ,g_new0 (CPUJumpCache,1 )); + } +return poison; +}
Why allocate a jump cache at runtime? Surely this would simply be a block of 0's in .rodata with
static const CPUJumpCache poison;
I think this needs to be split into many pieces. In particular:
(1) API change for tcg_gen_lookup_and_goto_ptr.
(2) Introduce tb_jmp_cache_probe, and the poisoning.
(3) Implementation of gen_jmp_cache_probe.
Quoted 28 lines
accel/tcg/cpu-exec.c +16
-1@@ -28,6 +28,8 @@#include "tcg/tcg-op-common.h" #include "exec/translation-block.h" #include "exec/plugin-gen.h" +#include "hw/core/cpu.h" +#include "../accel/tcg/tb-jmp-cache.h" #include "tcg-internal.h" #include "tcg-has.h" @@ -2715,7 +2717,81 @@ void tcg_gen_goto_tb(unsigned idx)tcg_gen_op1i (INDEX_op_goto_tb,0 , idx); } -void tcg_gen_lookup_and_goto_ptr (void ) +static void gen_jmp_cache_probe (TCGv_i64 pc,const TranslationBlock *tb) +{ +TCGv_ptr jc, ent, tbp, ptr; +TCGv_i64 h, tmp; +TCGLabel *slow; +uint64_t fpair; + +QEMU_BUILD_BUG_ON (sizeof (((CPUJumpCache *)0 )->array[0 ]) !=16 ); +QEMU_BUILD_BUG_ON (offsetof(TranslationBlock , cflags) != + offsetof(TranslationBlock , flags) +4 ); + + jc =tcg_temp_ebb_new_ptr (); + ent =tcg_temp_ebb_new_ptr (); + tbp =tcg_temp_ebb_new_ptr ();
accel/tcg/cpu-exec.c void tcg_gen_goto_tb(unsigned idx) · line 2743
Quoted 10 lines
accel/tcg/cpu-exec.c +10
-0+ ptr =tcg_temp_ebb_new_ptr (); + h =tcg_temp_ebb_new_i64 (); + tmp =tcg_temp_ebb_new_i64 (); + slow =gen_new_label (); + +/* h = tb_jmp_cache_hash_func(pc) * sizeof(array[0]) */ +tcg_gen_shri_i64 (h, pc,TB_JMP_CACHE_BITS ); +tcg_gen_xor_i64 (h, h, pc); +tcg_gen_andi_i64 (h, h,TB_JMP_CACHE_SIZE -1 ); +tcg_gen_shli_i64 (h, h,4 );
This hash function varies between system and user mode.
Quoted 7 lines
accel/tcg/cpu-exec.c +7
-0+ +/* +* Not cpu->tb_jmp_cache: the probe reads its own base so that the main +* loop can poison it, which is how conditions the probe cannot test for +* itself force every dispatch back into the helper. See +* tcg_cpu_sync_jmp_cache(). +*/
accel/tcg/cpu-exec.c void tcg_gen_goto_tb(unsigned idx) · line 2760
Quoted 10 lines
accel/tcg/cpu-exec.c +10
-0+tcg_gen_ld_ptr (jc, tcg_env, + offsetof(CPUState , tb_jmp_cache_probe) -sizeof (CPUState)); +tcg_gen_trunc_i64_ptr (ent, h); +tcg_gen_add_ptr (ent, jc, ent); + + tcg_gen_ld_ptr(tbp, ent, offsetof(CPUJumpCache, array[0].tb)); +tcg_gen_brcondi_ptr (TCG_COND_EQ , tbp,0 , slow); + + tcg_gen_ld_i64(tmp, ent, offsetof(CPUJumpCache, array[0].pc)); +tcg_gen_brcond_i64 (TCG_COND_NE , tmp, pc, slow);
I think you can test pc first as on hash miss, that's most likely to differ.
accel/tcg/cpu-exec.c void tcg_gen_goto_tb(unsigned idx) · line 2772
Quoted 12 lines
accel/tcg/cpu-exec.c +12
-0+ +/* +* flags and cflags are adjacent uint32_t, so one aligned 64-bit load +* and compare covers both. +*/ +#if HOST_BIG_ENDIAN + fpair = ((uint64_t )tb->flags <<32 ) | tb->cflags; +#else + fpair = ((uint64_t )tb->cflags <<32 ) | tb->flags; +#endif +tcg_gen_ld_i64 (tmp, tbp, offsetof(TranslationBlock , flags)); +tcg_gen_brcondi_i64 (TCG_COND_NE , tmp, fpair, slow);
I'm not keen on this without an additional _Static_assert that the offset is aligned. It happens to be right now, but we're not currently relying on that. :-)
accel/tcg/cpu-exec.c void tcg_gen_goto_tb(unsigned idx) · line 2779
Quoted 7 lines
accel/tcg/cpu-exec.c +7
-0+ +/* +* The destination must have been translated with the same cs_base, which +* the pc alone does not imply on a target that uses it. +*/ +tcg_gen_ld_i64 (tmp, tbp, offsetof(TranslationBlock , cs_base)); +tcg_gen_brcondi_i64 (TCG_COND_NE , tmp, tb->cs_base, slow);
The comment here should be more generic. Despite the cs_base name, consider this target-specific tb->flags2.
Quoted 8 lines
accel/tcg/cpu-exec.c +4
-0@@ -2724,7 +2800,21 @@ void tcg_gen_lookup_and_goto_ptr(void)return ; } +/* +* No icount_decr poll is needed for this exit: the helper is called on +* every dispatch and returns to the main loop while an exit is pending. +*/
accel/tcg/cpu-exec.c void tcg_gen_lookup_and_goto_ptr(void) · line 2816
Quoted 10 lines
accel/tcg/cpu-exec.c +9
-0plugin_gen_disable_mem_helpers (); + +/* +* The inline probe hashes and compares the pc as a single 64-bit value. +* A target with a 32-bit guest PC keeps the helper call. +*/ +if (pc && pc->type ==TCG_TYPE_I64 ) { +gen_jmp_cache_probe (temp_tcgv_i64 (pc), tb); +return ; + }
Just extend, clearly.
r~
Re: [PATCH v3 4/7] RFC: tcg: probe the TB jump cache inline instead of calling a helper
Quoted 208 lines · Richard Henderson
Quoted 192 lines · Matt Turner
Every indirect branch that cannot use
goto_tbends intcg_gen_lookup_and_goto_ptr(), which callshelper_lookup_tb_ptr(). For an emulated compiler that is 8.4 billion helper calls in a single translation
unit: 24.6% of all TB exits take this path, because jsr/ret/jmp have a register destination and becausegoto_tbis restricted to same-page targets.The helper itself is already tight, but each call pays for a call frame, the
can_do_iostore, theget_tb_cpu_state()indirect call through TCGCPUOps,curr_cflags(), and a breakpoint check, before it gets to the jump cache probe that almost always hits (95.8% for this workload).Emit the probe inline instead. The destination PC is already in a TCG temp, and the flags, cflags and
cs_basethe destination must match are constants at translation time, so the fast path is a hash, four guarded loads and agoto_ptr. Only a miss calls the helper, which still owns filling the cache.
tcg_gen_lookup_and_goto_ptr()therefore takes the destination PC and the TB being generated, and decides for itself whether to emit the probe or the old helper call; there is no second entry point for targets that opt in. A target that cannot name its destination in a single temp passes NULL and gets the helper. Since the probe hashes and compares the PC as one 64-bit value, a 32-bit guest PC also falls back.The PC a target passes must be exactly what
get_tb_cpu_state()reports for the destination, which is the whole of the contract. alpha, loongarch, mips, ppc and s390x pass their PC register, whose value is that pc by construction. The rest pass NULL for now: avr's TB pc is the word address doubled, i386's is eip before segmentation, riscv masks it to 32 bits when xl isMXL_RV32, hppa derives it from the IAQ, hexagon adjusts it inside a hardware loop, and sparc puts npc incs_baseso the guard could not hit anyway. Each of those is a one-line change for whoever wants to measure it.Two details matter for the generated code. The flags and cflags guards are folded into a single aligned 64-bit load and compare, since the fields are adjacent. And each path emits its own
goto_ptrrather than branching to a shared one: a temp live across the label is spilled and reloaded on every dispatch, which cost 6.3% on its own.The probe cannot check everything the helper checks, and the one that matters is breakpoints.
check_for_breakpoints()raisesEXCP_DEBUGon an exact pc match and selectsCF_BP_PAGEcflags for the rest of the page, and setting a breakpoint deliberately invalidates no TB, so a block translated before the breakpoint was set is still sitting in the jump cache. Rather than pay for a breakpoint test on the fast path, give the probe its own base pointer,tb_jmp_cache_probe, that nothing else reads, and point it at a page of zeroes while any breakpoint is set. Every entry the probe finds then has a NULL tb, so every dispatch misses into the helper and the old behaviour is restored exactly.cpu_breakpoint_insert()poisons the pointer, so the poison takes effect at the next dispatch rather than whenever that vCPU next reaches its main loop, which matters because a vCPU chaining indirectly need never reach it. The main loop puts the pointer back once the last breakpoint is gone; that is a load and a compare per block dispatched from the main loop, and nothing at all in generated code.The flags and cflags constants are safe against the other things that can change them.
CF_PARALLELis only ever set bybegin_parallel_context(), which flushes first, so no block predating it survives to dispatch. gdb single-step is only turned on with the CPU stopped, and a block translated withoutCF_SINGLE_STEPcan only be re-entered throughtb_lookup(), which from then on demands the new cflags -- so a stale-cflags block is never the one running. What is left isone_insn_per_tband -d nochain, which the monitor can toggle under a running vCPU without a flush; see below.Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host, LTO build, on top of the preceding three patches:
before: 1,402,667,803,616 instructions after: 916,415,123,244 instructions -34.67% before: 115.56s wall clock after: 85.59s wall clock -25.94%The gap between the two is the point at which this stops being a straight-line win: the helper call was highly predictable work that the host pipelined well, so removing it retires far fewer instructions than it saves time. IPC falls from 2.48 to 2.17 across this patch for that reason.
Despite emitting more code, this also reduces instruction cache pressure, because a dispatch no longer jumps into qemu's .text and evicts translated code:
before: 11,735,141,703 L1-icache-load-misses after: 7,154,863,292 L1-icache-load-misses -39.0%The mechanism is visible directly in a profile:
helper_lookup_tb_ptr()falls from 31.01% of samples to 0.35%, and qemu's own .text falls from 38.8% to 5.3%, with the balance moving into generated code.Combined with the three preceding patches, against an unmodified LTO build, 1,646,994,254,249 instructions fall to 916,415,123,244, or -44.36%. The emulated compiler produces byte-identical output throughout.
Open issues, hence RFC:
-
one_insn_per_tbandCPU_LOG_TB_NOCHAINcan be toggled from the monitor while a vCPU is inside a block that was translated without them. The block keeps dispatching inline with the old cflags until it exits for some other reason. Poisoning the probe fromtcg_update_all_curr_cflags()would close it.
- The jump cache entry is read withoutqatomic_read(); entries are invalidated concurrently by setting tb to NULL.
- Only alpha has been measured. The other four targets that pass a PC are built and boot-tested only.v3: Fold the fast path into
tcg_gen_lookup_and_goto_ptr()instead of
addingtcg_gen_lookup_and_goto_ptr_inline()beside it (Richard). It now takes the destination PC and the TB unconditionally, from all 38 call sites, and picks the probe or the helper itself. Translators built for both values ofTARGET_LONG_BITS-- arm, s390x, microblaze -- cannot includetcg-op.h, so the common entry point takes a TCGTemp and reads the width from it, andtcg-op.hwraps that for everyone else; this is the same split as tcg_gen_qemu_ld_*_chk().Compare
cs_basetoo. v2 listed this as an open issue, and closing it is what lets the choice be made generically rather than per target: a target that usescs_basewould otherwise have been enabled silently by a decision keyed on PC width alone. It costs a load and a compare on the fast path, and the numbers above were measured with it in place.Audited which targets may pass a real PC, the contract being that it is exactly what
get_tb_cpu_state()reports for the destination. Five do; the rest pass NULL and keep the helper call, sparc among them because it puts npc incs_baseand so could essentially never hit.Poison the probe from
cpu_breakpoint_insert()rather than only from the poisoned CPU's own main loop. gdb inserts a breakpoint into every CPU (tcg_insert_gdbstub_breakpoint()), and a thread already inside generated code, dispatching indirectly, need never return to the main loop -- so it would keep dispatching inline and run past a breakpoint another thread had just set. Upstream has no such window: itshelper_lookup_tb_ptr()sees the new breakpoint at the next indirect branch. The un-poison intcg_cpu_sync_jmp_cache()now re-checks after its store, with a barrier, so that it loses the race with a concurrent insert in the safe direction.Signed-off-by Matt Turner <[email protected]>--- accel/tcg/cpu-exec.c | 102 ++++++++++++++++++ accel/tcg/internal-common.h | 2 + cpu-common.c | 11 ++ include/hw/core/cpu.h | 9 ++ include/system/tcg.h | 9 ++ include/tcg/tcg-op-common.h | 16 ++- include/tcg/tcg-op.h | 12 +++ stubs/tcg-cflags.c | 8 +- target/alpha/translate.c | 4 +- target/arm/tcg/translate-a64.c | 4 +- target/arm/tcg/translate.c | 10 +- target/avr/translate.c | 4 +- target/hexagon/translate.c | 4 +- target/hppa/translate.c | 6 +- target/i386/tcg/translate.c | 2 +- .../tcg/insn_trans/trans_branch.c.inc | 2 +- target/loongarch/tcg/translate.c | 4 +- target/m68k/translate.c | 2 +- target/microblaze/translate.c | 4 +- target/mips/tcg/nanomips_translate.c.inc | 2 +- target/mips/tcg/translate.c | 6 +- target/or1k/translate.c | 4 +- target/ppc/translate.c | 4 +- target/riscv/tcg/insn_trans/trans_rvzce.c.inc | 4 +- target/riscv/tcg/translate.c | 2 +- target/rx/translate.c | 4 +- target/s390x/tcg/translate.c | 5 +- target/sh4/translate.c | 4 +- target/sparc/translate.c | 4 +- target/tricore/translate.c | 4 +- tcg/tcg-op.c | 92 +++++++++++++++- 31 files changed, 300 insertions(+), 50 deletions(-)accel/tcg/cpu-exec.c +11
-0@@ -752,6 +752,99 @@ static inline bool cpu_handle_exception(CPUState *cpu, int *ret)return false; } +/* +* The inline jump cache probe reads cpu->tb_jmp_cache_probe and takes the +* slow path when the entry it finds has a NULL tb. Pointing the probe at a +* region that is all zeroes therefore forces every indirect dispatch into +* helper_lookup_tb_ptr(), which does the full lookup the inline probe only +* approximates. The real jump cache is untouched, so no contents are lost +* and recovery is a single store. +* +* Only ever read from, and only the tb field of one entry per dispatch, so +* one shared zero-filled cache is enough for every CPU. +*/ accel/tcg/cpu-exec.c static inline bool cpu_handle_exception(CPUState *cpu, int *ret) · line 775
Quoted 10 lines
accel/tcg/cpu-exec.c +10
-0+static const CPUJumpCache *tb_jmp_cache_poison (void ) +{ +static CPUJumpCache *poison; + +if (unlikely (poison ==NULL )) { +/* Raced allocations are harmless: both are all zeroes. */ +qatomic_cmpxchg (&poison,NULL ,g_new0 (CPUJumpCache,1 )); + } +return poison; +}Why allocate a jump cache at runtime? Surely this would simply be a block of 0's in .rodata with
Quoted 1 line
static const CPUJumpCache poison;
Changed to be a static object now, but not const. A zero-initialized const aggregate goes in .rodata -- a megabyte of real zeroes in every emulator binary. Without const it lands in .bss, costs nothing on disk, and faults in only the pages a poisoned run touches. Nothing writes to it; there's a comment saying why.
Quoted 7 lines
I think this needs to be split into many pieces. In particular:
(1) API change for
tcg_gen_lookup_and_goto_ptr.(2) Introduce
tb_jmp_cache_probe, and the poisoning.(3) Implementation of
gen_jmp_cache_probe.
Done, in the order you gave.
Quoted 32 lines
Quoted 32 lines
accel/tcg/cpu-exec.c +20
-1@@ -28,6 +28,8 @@#include "tcg/tcg-op-common.h" #include "exec/translation-block.h" #include "exec/plugin-gen.h" +#include "hw/core/cpu.h" +#include "../accel/tcg/tb-jmp-cache.h" #include "tcg-internal.h" #include "tcg-has.h" @@ -2715,7 +2717,81 @@ void tcg_gen_goto_tb(unsigned idx)tcg_gen_op1i (INDEX_op_goto_tb,0 , idx); } -void tcg_gen_lookup_and_goto_ptr (void ) +static void gen_jmp_cache_probe (TCGv_i64 pc,const TranslationBlock *tb) +{ +TCGv_ptr jc, ent, tbp, ptr; +TCGv_i64 h, tmp; +TCGLabel *slow; +uint64_t fpair; + +QEMU_BUILD_BUG_ON (sizeof (((CPUJumpCache *)0 )->array[0 ]) !=16 ); +QEMU_BUILD_BUG_ON (offsetof(TranslationBlock , cflags) != + offsetof(TranslationBlock , flags) +4 ); + + jc =tcg_temp_ebb_new_ptr (); + ent =tcg_temp_ebb_new_ptr (); + tbp =tcg_temp_ebb_new_ptr (); + ptr =tcg_temp_ebb_new_ptr (); + h =tcg_temp_ebb_new_i64 (); + tmp =tcg_temp_ebb_new_i64 (); + slow =gen_new_label ();
Quoted 8 lines
accel/tcg/cpu-exec.c void tcg_gen_goto_tb(unsigned idx) · line 2743
Quoted 6 lines
accel/tcg/cpu-exec.c +6
-0+ +/* h = tb_jmp_cache_hash_func(pc) * sizeof(array[0]) */ +tcg_gen_shri_i64 (h, pc,TB_JMP_CACHE_BITS ); +tcg_gen_xor_i64 (h, h, pc); +tcg_gen_andi_i64 (h, h,TB_JMP_CACHE_SIZE -1 ); +tcg_gen_shli_i64 (h, h,4 );This hash function varies between system and user mode.
Fixed.
Quoted 11 lines
Quoted 11 lines
accel/tcg/cpu-exec.c +11
-0+ +/* +* Not cpu->tb_jmp_cache: the probe reads its own base so that the main +* loop can poison it, which is how conditions the probe cannot test for +* itself force every dispatch back into the helper. See +* tcg_cpu_sync_jmp_cache(). +*/ +tcg_gen_ld_ptr (jc, tcg_env, + offsetof(CPUState , tb_jmp_cache_probe) -sizeof (CPUState)); +tcg_gen_trunc_i64_ptr (ent, h); +tcg_gen_add_ptr (ent, jc, ent);
Quoted 8 lines
accel/tcg/cpu-exec.c void tcg_gen_goto_tb(unsigned idx) · line 2760
Quoted 6 lines
accel/tcg/cpu-exec.c +6
-0+ + tcg_gen_ld_ptr(tbp, ent, offsetof(CPUJumpCache, array[0].tb)); +tcg_gen_brcondi_ptr (TCG_COND_EQ , tbp,0 , slow); + + tcg_gen_ld_i64(tmp, ent, offsetof(CPUJumpCache, array[0].pc)); +tcg_gen_brcond_i64 (TCG_COND_NE , tmp, pc, slow);I think you can test pc first as on hash miss, that's most likely to differ.
Smart! Fixed.
Quoted 17 lines
accel/tcg/cpu-exec.c void tcg_gen_goto_tb(unsigned idx) · line 2772
Quoted 13 lines
accel/tcg/cpu-exec.c +12
-0+ +/* +* flags and cflags are adjacent uint32_t, so one aligned 64-bit load +* and compare covers both. +*/ +#if HOST_BIG_ENDIAN + fpair = ((uint64_t )tb->flags <<32 ) | tb->cflags; +#else + fpair = ((uint64_t )tb->cflags <<32 ) | tb->flags; +#endif +tcg_gen_ld_i64 (tmp, tbp, offsetof(TranslationBlock , flags)); +tcg_gen_brcondi_i64 (TCG_COND_NE , tmp, fpair, slow);I'm not keen on this without an additional
_Static_assertthat the offset is aligned. It happens to be right now, but we're not currently relying on that. :-)
Added, next to the adjacency assert.
Quoted 10 lines
accel/tcg/cpu-exec.c void tcg_gen_goto_tb(unsigned idx) · line 2779
Quoted 7 lines
accel/tcg/cpu-exec.c +7
-0+ +/* +* The destination must have been translated with the same cs_base, which +* the pc alone does not imply on a target that uses it. +*/ +tcg_gen_ld_i64 (tmp, tbp, offsetof(TranslationBlock , cs_base)); +tcg_gen_brcondi_i64 (TCG_COND_NE , tmp, tb->cs_base, slow);The comment here should be more generic. Despite the
cs_basename, consider this target-specifictb->flags2.
Done.
Quoted 4 lines
Quoted 4 lines
accel/tcg/cpu-exec.c +0
-0@@ -2724,7 +2800,21 @@ void tcg_gen_lookup_and_goto_ptr(void)return ; }
Quoted 16 lines
Quoted 4 lines
accel/tcg/cpu-exec.c +4
-0+/* +* No icount_decr poll is needed for this exit: the helper is called on +* every dispatch and returns to the main loop while an exit is pending. +*/ accel/tcg/cpu-exec.c void tcg_gen_lookup_and_goto_ptr(void) · line 2816
Quoted 10 lines
accel/tcg/cpu-exec.c +9
-0plugin_gen_disable_mem_helpers (); + +/* +* The inline probe hashes and compares the pc as a single 64-bit value. +* A target with a 32-bit guest PC keeps the helper call. +*/ +if (pc && pc->type ==TCG_TYPE_I64 ) { +gen_jmp_cache_probe (temp_tcgv_i64 (pc), tb); +return ; + }Just extend, clearly.
Done. Nice, the high half folds to a compare against zero.
PATCH v3 5/7 RFC: accel/tcg: allow cross-page goto_tb chaining in user-only builds
In reply to Matt Turnertranslator_use_goto_tb() refuses to chain unless the destination is on the same page as the start of the TB. For guests whose text is much larger than a page this is expensive: an emulated alpha gcc compiling a 255k line translation unit takes the indirect dispatch path for 8.4 billion of its 34.2 billion TB exits, and a large share of those are ordinary direct branches that simply crossed an 8 KiB page boundary.
The restriction was made unconditional by d3a2a1d803 ("accel/tcg:
Introduce translator_use_goto_tb"), whose rationale was:
Various targets avoid the page crossing test for CONFIG_USER_ONLY, but that is wrong: mmap and mprotect can change page permissions.
That is true, but in user-only builds the invalidation path already covers it. There are no page tables: every mmap, mprotect and munmap reaches page_set_flags(), which calls tb_invalidate_phys_range() whenever the flags actually change, and tb_phys_invalidate() calls tb_jmp_unlink() to reset incoming jumps. A chained cross-page jump is therefore broken whenever the destination page's permissions change. This is not true in system mode, where TBs are keyed by physical address and a page table change invalidates nothing, so the restriction is kept there.
The rule protects one more thing, which the original rationale does not
mention: it guarantees that execution cannot enter a page without a TB lookup, and so without check_for_breakpoints(). That is what makes a breakpoint set after a block was translated take effect, since insertion deliberately invalidates nothing. A link established before the breakpoint was set would jump straight over it.
So the chaining is only enabled for a run that can never acquire a breakpoint. In user-only mode every breakpoint comes from gdb -- BP_CPU is g_assert_not_reached() there, and the guest cannot ask for one -- and gdb has to be requested with -g before the first block is translated, even though with suspend=n it may connect later. gdb_may_set_breakpoints() reports whether it was, and is fixed for the lifetime of the process.
Add tests/tcg/alpha/test-xpage-chain.c to cover both hazards directly. It places a direct branch near the end of one page targeting the next page, runs it 200000 times so the chain is established, then checks that mprotect(PROT_NONE) makes the next call fault, and that remapping the page with different code runs the new code rather than a stale translation.
The test detects the hazard it is meant to detect: with the tb_invalidate_phys_range() call in page_set_flags() commented out, it fails both phases, executing page B after PROT_NONE and returning the stale result.
Run with -b, the same binary stops once the chain is established and lets tests/tcg/alpha/gdbstub/xpage-bp.py set a breakpoint on the far side of it, which the next call has to stop on. With gdb_may_set_breakpoints() forced to false so that the chaining stays on under gdb, that breakpoint is missed and the test fails, which is what makes it a test of the gate rather than of gdb.
Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation on an x86-64 host, LTO build, on top of the preceding patches:
before: 916,415,123,244 instructions
after: 891,254,240,071 instructions -2.75%
before: 85.59s wall clock
after: 81.45s wall clock -4.84%Note that this is worth more in time than in instructions, the reverse of the preceding patch: a chained jump replaces a cache probe whose loads can miss, so the instructions it removes are more expensive than average.
Measured before the inline jump cache probe, when a missed chain cost a helper call rather than an inline probe, the same change was worth -7.9%.
RFC because this reverses a deliberate decision and the reasoning above wants review from someone who knows the invalidation paths better than I do.
v3: Only take the shortcut when no gdbstub was requested. The same-page
rule also forces a lookup, and so a breakpoint check, on entry to every page; without that, a chain established before a breakpoint was set runs past it. Reported by Richard Henderson.
v3: Change translator_use_goto_tb() rather than translator_is_same_page().
i386, riscv and s390x call translator_is_same_page() for something else -- enforcing that only a single-insn TB may cross a page -- and v2 changed their TB boundaries in user-only mode as a side effect. alpha does not call it, so the numbers above are unaffected.
v3: Add the gdbstub half of the test.
--- accel/tcg/translator.c | 33 ++++++- gdbstub/user.c | 14 +++ include/gdbstub/user.h | 11 +++ tests/tcg/alpha/Makefile.target | 17 +++- tests/tcg/alpha/gdbstub/xpage-bp.py | 34 +++++++ tests/tcg/alpha/test-xpage-chain.c | 144 ++++++++++++++++++++++++++++ 6 files changed, 251 insertions(+), 2 deletions(-) create mode 100644 tests/tcg/alpha/gdbstub/xpage-bp.py create mode 100644 tests/tcg/alpha/test-xpage-chain.c
accel/tcg/translator.c +32 -1
@@ -15,6 +15,9 @@#include "accel/tcg/cpu-mmu-index.h" #include "exec/target_page.h" #include "exec/translator.h" +#ifdef CONFIG_USER_ONLY +#include "gdbstub/user.h" +#endif #include "exec/plugin-gen.h" #include "tcg/tcg-op-common.h" #include "internal-common.h"
@@ -110,6 +113,34 @@ bool translator_is_same_page(const DisasContextBase *db, vaddr addr)return ((addr ^ db->pc_first) &TARGET_PAGE_MASK ) ==0 ; } +/* +* Whether a direct jump may be chained to a destination outside the page +* the TB started in. +* +* In user-only mode there are no page tables. Every mmap, mprotect and +* munmap goes through page_set_flags(), which calls tb_invalidate_phys_range() +* whenever the flags actually change, and tb_phys_invalidate() unlinks +* incoming jumps. A cross-page link is therefore broken whenever the +* destination page's permissions change. +* +* What the same-page rule also provides is that execution cannot enter a page +* without a TB lookup, and so without check_for_breakpoints(), which is what +* makes a breakpoint set after a block was translated take effect. Nothing +* invalidates on breakpoint insertion, so a link established beforehand would +* jump straight over it. In user-only mode breakpoints only ever come from +* gdb -- BP_CPU is g_assert_not_reached() there and the guest has no way to +* ask for one -- and gdb has to be requested with -g before the first block +* is translated, so a run that has no gdbstub can never acquire a breakpoint. +*/ +static bool use_cross_page_goto_tb (void ) +{ +#ifdef CONFIG_USER_ONLY +return !gdb_may_set_breakpoints (); +#else +return false; +#endif +} +bool translator_use_goto_tb (DisasContextBase *db,vaddr dest) {/* Suppress goto_tb if requested. */
@@ -118,7 +149,7 @@ bool translator_use_goto_tb(DisasContextBase *db, vaddr dest) }/* Check for the dest on the same page as the start of the TB. */ -return translator_is_same_page (db, dest); +return use_cross_page_goto_tb () ||translator_is_same_page (db, dest); } void translator_loop(CPUState *cpu, TranslationBlock *tb, int *max_insns,
gdbstub/user.c +14 -0
@@ -470,6 +470,18 @@ static void *gdbserver_accept_thread(void *arg)#define USAGE "\nUsage: -g {port|path}[,suspend={y|n}]" +/* +* Set before the guest runs and never cleared, so that code translated at +* any point can rely on it: with suspend=n gdb may connect long after +* startup, and once connected it can insert a breakpoint at any time. +*/ +static bool gdbserver_requested; + +bool gdb_may_set_breakpoints (void ) +{ +return gdbserver_requested; +} +bool gdbserver_start (const char *args,Error **errp) {g_auto (GStrv) argv =g_strsplit (args,"," ,0 );
@@ -513,6 +525,8 @@ bool gdbserver_start(const char *args, Error **errp)return false; } + gdbserver_requested = true; +if (suspend) {if (gdbserver_accept (port, gdb_fd, port_or_path)) {gdb_handlesig (first_cpu,0 ,NULL ,NULL ,0 );
include/gdbstub/user.h +11 -0
@@ -11,6 +11,17 @@#define MAX_SIGINFO_LENGTH 128 +/** +* gdb_may_set_breakpoints() - whether a breakpoint can ever be inserted +* +* In user-only mode every breakpoint comes from gdb, and gdb is only ever +* reachable if -g was given at startup, before the guest ran a single +* instruction. A run that has no gdbstub can therefore never acquire a +* breakpoint, which lets translation take shortcuts that a breakpoint +* would invalidate. Stays true once true, even if gdb detaches. +*/ +bool gdb_may_set_breakpoints (void ); +/** * gdb_handlesig() - yield control to gdb * @cpu: CPU
tests/tcg/alpha/Makefile.target +16 -1
@@ -5,7 +5,7 @@ ALPHA_SRC=$(SRC_PATH)/tests/tcg/alpha VPATH+=$(ALPHA_SRC) -ALPHA_TESTS=hello-alpha test-cond test-cmov test-ovf test-cvttq +ALPHA_TESTS=hello-alpha test-cond test-cmov test-ovf test-cvttq test-xpage-chain TESTS+=$(ALPHA_TESTS) test-cmov: EXTRA_CFLAGS=-DTEST_CMOV
@@ -16,3 +16,18 @@ test-cmov: test-cond.c test-plugin-mem-access: CFLAGS+=-mbwx run-test-cmov: test-cmov + +ifneq ($(GDB),) +GDB_SCRIPT=$(SRC_PATH)/tests/guest-debug/run-test.py + +# The chaining this exercises is only enabled when no gdbstub was requested, +# so what is under test here is that requesting one turns it back off. +run-gdbstub-xpage-bp: test-xpage-chain + $(call run-test, $@, $(GDB_SCRIPT) \ + --gdb $(GDB) \ + --qemu $(QEMU) --qargs "$(QEMU_OPTS)" \ + --bin "$< -b" --test $(ALPHA_SRC)/gdbstub/xpage-bp.py, \ + breakpoint behind an established cross-page chain) + +EXTRA_RUNS += run-gdbstub-xpage-bp +endif
tests/tcg/alpha/gdbstub/xpage-bp.py new file +34 -0
@@ -0,0 +1,34 @@ +"""Test that a breakpoint set after a cross-page chain is established is hit. + +translator_use_goto_tb() lets a direct branch chain to another page in +user-only builds, which is only safe because a run with no gdbstub can never +acquire a breakpoint. This runs with one, so the chaining must be off and +the breakpoint must still be reached. + +This runs as a sourced script (via -x, via run-test.py). + +SPDX-License-Identifier: GPL-2.0-or-later +""" +from test_gdbstub import main, report + + +def run_test(): + """Run through the tests one by one""" + gdb.Breakpoint("break_here") + gdb.execute("continue") + + # The chain exists by now; put a breakpoint on the far side of it. + target = int(gdb.parse_and_eval("(unsigned long)page_b_entry")) + gdb.execute("break *{}".format(target)) + gdb.execute("continue") + + pc = int(gdb.parse_and_eval("(unsigned long)$pc")) + report(pc == target, "stopped at {:#x}, expected {:#x}".format(pc, target)) + + gdb.execute("delete") + gdb.execute("continue") + exitcode = int(gdb.parse_and_eval("$_exitcode")) + report(exitcode == 0, "{} == 0".format(exitcode)) + + +main(run_test)
tests/tcg/alpha/test-xpage-chain.c new file +144 -0
144 lines not on this page · raw message
Signature · 1 line
2.54.0
Re: [PATCH v3 5/7] RFC: accel/tcg: allow cross-page goto_tb chaining in user-only builds
Quoted 21 lines · Matt Turner
translator_use_goto_tb()refuses to chain unless the destination is on the same page as the start of the TB. For guests whose text is much larger than a page this is expensive: an emulated alpha gcc compiling a 255k line translation unit takes the indirect dispatch path for 8.4 billion of its 34.2 billion TB exits, and a large share of those are ordinary direct branches that simply crossed an 8 KiB page boundary.The restriction was made unconditional by
d3a2a1d803("accel/tcg:
Introducetranslator_use_goto_tb"), whose rationale was:Various targets avoid the page crossing test for
CONFIG_USER_ONLY, but that is wrong: mmap and mprotect can change page permissions.That is true, but in user-only builds the invalidation path already covers it. There are no page tables: every mmap, mprotect and munmap reaches
page_set_flags(), which callstb_invalidate_phys_range()whenever the flags actually change, andtb_phys_invalidate()callstb_jmp_unlink()to reset incoming jumps. A chained cross-page jump is therefore broken whenever the destination page's permissions change. This is not true in system mode, where TBs are keyed by physical address and a page table change invalidates nothing, so the restriction is kept there.
Quoted 3 lines
tests/tcg/alpha/Makefile.target | 17 +++- tests/tcg/alpha/gdbstub/xpage-bp.py | 34 +++++++ tests/tcg/alpha/test-xpage-chain.c | 144 ++++++++++++++++++++++++++++
<snip>
Given alpha linux-user isn't widely built or used it would be better if we could make the xpage chaining tests multiarch so they are exercised on all *-user targets.
Signature · 2 lines
Alex Bennée Virtualisation Tech Lead @ Linaro
Re: [PATCH v3 5/7] RFC: accel/tcg: allow cross-page goto_tb chaining in user-only builds
Quoted 27 lines · Alex Bennée
Quoted 21 lines · Matt Turner
translator_use_goto_tb()refuses to chain unless the destination is on the same page as the start of the TB. For guests whose text is much larger than a page this is expensive: an emulated alpha gcc compiling a 255k line translation unit takes the indirect dispatch path for 8.4 billion of its 34.2 billion TB exits, and a large share of those are ordinary direct branches that simply crossed an 8 KiB page boundary.The restriction was made unconditional by
d3a2a1d803("accel/tcg:
Introducetranslator_use_goto_tb"), whose rationale was:Various targets avoid the page crossing test for
CONFIG_USER_ONLY, but that is wrong: mmap and mprotect can change page permissions.That is true, but in user-only builds the invalidation path already covers it. There are no page tables: every mmap, mprotect and munmap reaches
page_set_flags(), which callstb_invalidate_phys_range()whenever the flags actually change, andtb_phys_invalidate()callstb_jmp_unlink()to reset incoming jumps. A chained cross-page jump is therefore broken whenever the destination page's permissions change. This is not true in system mode, where TBs are keyed by physical address and a page table change invalidates nothing, so the restriction is kept there.Quoted 3 lines
tests/tcg/alpha/Makefile.target | 17 +++- tests/tcg/alpha/gdbstub/xpage-bp.py | 34 +++++++ tests/tcg/alpha/test-xpage-chain.c | 144 ++++++++++++++++++++++++++++
Quoted 5 lines
<snip>
Given alpha linux-user isn't widely built or used it would be better if we could make the xpage chaining tests multiarch so they are exercised on all *-user targets.
Done. The explicit branch is gone with the move: a fall-through off the end of a page is a cross-page goto_tb just the same, so the test writes the last instruction of page A and the first of page B, and needs no per-arch branch encoding or displacement arithmetic -- just "set the return value" and "return".
13 architectures supply those two, and the rest skip. I checked each encoding against the cross assembler and ran the test under qemu-user on aarch64, alpha, arm, hppa, loongarch64, m68k, mips, ppc, ppc64le, riscv64, s390x, sh4, sparc64 and x86_64 (ppc64 ELFv1 skips). The gdbstub half moved with it.
PATCH v3 6/7 RFC: accel/tcg: poison the jump cache instead of polling for indirect exits
In reply to Matt TurnerEvery translation block begins by loading cpu->neg.icount_decr.u32, testing it and branching to the exit path. That is three host instructions at the top of every TB, and blocks are short: an emulated alpha gcc 16.2.0 compiling a 255k line translation unit executes 34.2 billion of them at 6.04 guest instructions each.
A block does not need to poll if every way out of it already reaches a check. A goto_tb does not: it chains straight into its destination, with nothing in between that looks at icount_decr, so the destination has to poll on entry. An indirect exit does. The out-of-line path calls helper_lookup_tb_ptr() every time, so it only needs the helper to return the epilogue while an exit is pending. The inline probe is already covered by the machinery the breakpoint patch added: it reads its base pointer from cpu->tb_jmp_cache_probe and takes the slow path when the entry it finds has a NULL tb, so pointing that base at a page of zeroes turns every indirect dispatch into a miss, and a miss lands in the same helper.
So a pending exit becomes one more reason for tcg_cpu_may_dispatch() to say no. The two places that set icount_decr.u16.high poison the probe; the main loop puts it back once the flag is clear, on the same pass that already re-evaluates the breakpoint state. The real tb_jmp_cache is untouched throughout, so no cache contents are lost, and the fast path pays nothing:
the base was a load from CPUState either way.
The poll is therefore emitted only in blocks that emit a goto_tb. Whether a block does is not known until its last exit has been generated, so the decision is deferred and the load and branch are emitted retroactively at the head of the block in gen_tb_end(), using the same emit_before_op mechanism the can_do_io stores use. icount opts out and keeps the counter unconditionally.
Interrupt latency is bounded at one block, as before. It does not depend on the shape of the guest's control flow graph: a block either polls on entry or is checked on the way out, and no run of blocks can avoid both. What changes is where the check sits, not how often one happens.
tests/tcg/alpha/test-indirect-irq.c is added for this: a loop whose only back edge is an indirect branch, under alarm(1). That loop's block emits no goto_tb, so it no longer polls, and the test passes only because the dispatch notices instead -- it hangs if the poison is removed, which is what makes it a test of the new mechanism rather than of the old poll. The other alpha tests still pass and the emulated compiler still produces byte-identical output.
Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host, LTO build, on top of the preceding patches:
before: 891,254,240,071 instructions
after: 868,811,832,620 instructions -2.52%
before: 81.45s wall clock
after: 79.85s wall clock -1.96%The emulated compiler produces byte-identical output.
RFC because:
- The un-poison in the main loop races a concurrent poison from another thread. The existing barrier around icount_decr.u16.high covers it -- a poison that lands after the sync also re-set the flag, and exit_request was stored before it -- but this deserves more eyes than the single-threaded user-mode testing I have given it.
- Only the inline probe needs the poison, and only alpha uses the inline probe today. Targets on the out-of-line path are covered by the helper check alone, but that has not been measured.
- The shared zero-filled CPUJumpCache is a 1MB allocation that is never written. A read-only mapping would express that better.
v3: Rebased onto the removal of "only poll for interrupts in blocks that can
close a cycle", which v2 sat on top of and which is dropped: it let a straight-line run of arbitrary length go unchecked, since a block with no backward edge polled nowhere (Richard).
The rule is now that a block polls iff it emits a goto_tb, rather than iff it can close a control flow cycle. That keeps the bound at one block without any analysis of the guest's control flow graph, so the objection to the dropped patch does not carry over. The deferred-emission machinery it needs moves here from that patch; DisasContextBase::needs_exit_check and the hook in translator_use_goto_tb() are gone with it, and the flag is now set by tcg_gen_goto_tb() rather than by goto_ptr emission.
All of v2's measurements were dropped: they were taken with the cycle-analysis patch underneath, which changes both the baseline and what is left to remove, so none of them described this patch. The numbers above are a fresh measurement of the series as it now stands.
--- accel/tcg/cpu-exec.c | 23 ++++++++++-- accel/tcg/tcg-accel-ops.c | 1 + accel/tcg/translator.c | 51 ++++++++++++++++++++++++-- include/hw/core/cpu.h | 8 +++-- include/tcg/tcg.h | 2 ++ tcg/tcg-op.c | 13 +++++-- tests/tcg/alpha/Makefile.target | 3 +- tests/tcg/alpha/test-indirect-irq.c | 55 +++++++++++++++++++++++++++++ 8 files changed, 144 insertions(+), 12 deletions(-) create mode 100644 tests/tcg/alpha/test-indirect-irq.c
accel/tcg/cpu-exec.c +20 -3
@@ -388,6 +388,16 @@ const void *HELPER(lookup_tb_ptr)(CPUArchState *env)*/ cpu->neg.can_do_io = true; +/* +* A block that dispatches indirectly does not emit the icount_decr poll, +* so this is where a pending exit is noticed for that path: either the +* probe was poisoned and every dispatch arrives here, or the target uses +* the out-of-line lookup and always did. +*/ +if (unlikely (cpu_loop_exit_requested (cpu))) { +return tcg_code_gen_epilogue; + } +TCGTBCPUState s = cpu->cc->tcg_ops->get_tb_cpu_state (cpu); s.cflags =curr_cflags (cpu);
@@ -757,8 +767,9 @@ static inline bool cpu_handle_exception(CPUState *cpu, int *ret)* slow path when the entry it finds has a NULL tb. Pointing the probe at a * region that is all zeroes therefore forces every indirect dispatch into * helper_lookup_tb_ptr(), which does the full lookup the inline probe only -* approximates. The real jump cache is untouched, so no contents are lost -* and recovery is a single store. +* approximates and returns to the main loop while an exit is pending. The +* real jump cache is untouched, so no contents are lost and recovery is a +* single store. * * Only ever read from, and only the tb field of one entry per dispatch, so * one shared zero-filled cache is enough for every CPU.
@@ -785,10 +796,13 @@ static const CPUJumpCache *tb_jmp_cache_poison(void)* the rest of the page. A block translated before the breakpoint was set is * therefore still in the jump cache, and dispatching to it inline would step * straight over the breakpoint. +* +* A block that dispatches indirectly also does not emit the icount_decr +* poll, so the dispatch is where a pending exit has to be noticed. */ static bool tcg_cpu_may_dispatch (CPUState *cpu) { -return QTAILQ_EMPTY (&cpu->breakpoints); +return QTAILQ_EMPTY (&cpu->breakpoints) && !cpu_loop_exit_requested (cpu); }/*
@@ -857,6 +871,9 @@ void tcg_kick_vcpu_thread(CPUState *cpu)/* Ensure cpu_exec will see the exit request after TCG has exited. */ qatomic_store_release (&cpu->neg.icount_decr.u16.high,-1 ); + +/* Blocks that only dispatch indirectly do not poll; stop them chaining. */ +tcg_cpu_poison_jmp_cache (cpu); }static inline bool icount_exit_request (CPUState *cpu)
accel/tcg/tcg-accel-ops.c +1 -0
@@ -106,6 +106,7 @@ void tcg_handle_interrupt(CPUState *cpu, int mask)qemu_cpu_kick (cpu); }else {qatomic_set (&cpu->neg.icount_decr.u16.high,-1 ); +tcg_cpu_poison_jmp_cache (cpu); } }
accel/tcg/translator.c +48 -3
86 lines not on this page · raw message
include/hw/core/cpu.h +5 -3
@@ -523,9 +523,11 @@ struct CPUState {* @tb_jmp_cache_probe: base the inline jump cache probe reads. * * Normally @tb_jmp_cache. Pointed at a shared page of zeroes to force -* every inline dispatch to miss and fall back to helper_lookup_tb_ptr(); -* see tcg_cpu_sync_jmp_cache(). NULL before tcg_exec_realizefn() and -* after tcg_exec_unrealizefn(). +* every inline dispatch to miss and fall back to helper_lookup_tb_ptr(), +* either because a breakpoint is set or because an exit is pending; see +* tcg_cpu_sync_jmp_cache(). Only generated code and the accessors in +* cpu-exec.c may touch it. NULL before tcg_exec_realizefn() and after +* tcg_exec_unrealizefn(). */ struct CPUJumpCache *tb_jmp_cache_probe;
include/tcg/tcg.h +2 -0
@@ -389,6 +389,8 @@ struct TCGContext {struct TCGLabelPoolData *pool_labels;TCGLabel *exitreq_label; +/* Set by goto_tb emission: this TB chains without reaching a check. */ +bool exit_check_needed;#ifdef CONFIG_PLUGIN /*
tcg/tcg-op.c +11 -2
@@ -2713,6 +2713,13 @@ void tcg_gen_goto_tb(unsigned idx)tcg_debug_assert ((tcg_ctx->goto_tb_issue_mask & (1 << idx)) ==0 ); tcg_ctx->goto_tb_issue_mask |=1 << idx;#endif +/* +* A goto_tb chains straight into the destination, with nothing in between +* that looks at icount_decr, so this TB has to poll on entry. See +* defer_exit_check(). +*/ + tcg_ctx->exit_check_needed = true; +plugin_gen_disable_mem_helpers ();tcg_gen_op1i (INDEX_op_goto_tb,0 , idx); }
@@ -2801,8 +2808,10 @@ void tcg_gen_lookup_and_goto_ptr_tmp(TCGTemp *pc, const TranslationBlock *tb) }/* -* No icount_decr poll is needed for this exit: the helper is called on -* every dispatch and returns to the main loop while an exit is pending. +* No icount_decr poll is needed for this exit. The helper returns to the +* main loop while an exit is pending, and a pending exit poisons +* tb_jmp_cache_probe, so the inline path below finds a NULL tb and falls +* into that same helper. */ plugin_gen_disable_mem_helpers ();
tests/tcg/alpha/Makefile.target +2 -1
@@ -5,7 +5,8 @@ ALPHA_SRC=$(SRC_PATH)/tests/tcg/alpha VPATH+=$(ALPHA_SRC) -ALPHA_TESTS=hello-alpha test-cond test-cmov test-ovf test-cvttq test-xpage-chain +ALPHA_TESTS=hello-alpha test-cond test-cmov test-ovf test-cvttq test-xpage-chain \ + test-indirect-irq TESTS+=$(ALPHA_TESTS) test-cmov: EXTRA_CFLAGS=-DTEST_CMOV
tests/tcg/alpha/test-indirect-irq.c new file +55 -0
55 lines not on this page · raw message
Signature · 1 line
2.54.0
PATCH v3 7/7 RFC: tcg: fold a guest displacement into the host addressing mode
In reply to Matt TurnerNothing in the TCG frontend interface can express a based memory access. tcg_gen_qemu_ld/st take an address and nothing else, so a target with a displacement in its load and store encodings -- which is most of them -- has to materialise the address first:
ldq a1,8(a0) -> mov 0x80(%rbp),%rbx reload a0
lea 0x8(%rbx),%r12 address
mov (%r12),%r12 the load
mov %r12,0x88(%rbp) spill a1The lea is pure loss on a host whose addressing mode has a displacement field sitting empty. It also needs a register, at the point in a block where pressure is highest.
Fold it. After optimisation, look for an add of a constant immediately before a guest access, defining that access's address operand, and move the constant into a new second constant argument on the op. The add is left for liveness to remove, so nothing breaks if its result has another use. Only the immediately preceding op is examined: that is what the frontends emit, and a window of one op means the pass does not have to reason about what could have happened in between. The one thing it does check is that the add did not clobber the base it read, since the access now reads that base directly.
Targets opt in with TCG_TARGET_HAS_ldst_disp and an out_disp member on TCGOutOpQemuLdSt. Without it the pass does not run, the displacement stays zero and the existing out member is called exactly as before, so no other backend changes behaviour or needs touching.
For x86_64 the displacement goes in the disp32 that prepare_host_addr() already fills in for guest_base. The fold is refused unless there is no slow path at all, which means user-only -- softmmu compares the unadjusted address against the TLB -- and an access needing no alignment test, since the slow path hands addr_reg to the helper and that register no longer holds the full guest address. It is also refused if guest_base plus the displacement leaves disp32.
Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host, LTO build, on top of the preceding patches, against a control measured in the same session:
before: 868,811,832,620 instructions, 79.85s
after: 819,262,147,022 instructions, 77.30s
-5.70% instructions, -3.20% wallEmitted code shrinks from 50.55MB to 48.80MB over the run, 167.4 to 161.6 bytes per block. Per Alpha opcode, the host bytes emitted for an access fall as expected and nothing else moves:
ldq 18.3 -> 15.4 ldah 20.9 -> 20.9
ldl 16.6 -> 14.1 lda 12.9 -> 12.9
stq 12.8 -> 9.7 mov 9.8 -> 9.8The emulated compiler produces byte-identical output and the alpha tests still pass, including with a non-zero guest_base forced via -B.
RFC because:
- Only wired up for x86_64, and only for qemu_ld and qemu_st; the i128 qemu_ld2 and qemu_st2 pairs are left alone.
- Requiring that no slow path exists is stricter than necessary. Recording the displacement in TCGLabelQemuLdst and emitting one lea on the slow path would cover alignment-checked accesses too, at no fast path cost.
- Softmmu wants the displacement folded into the TLB comparison as well, which is a bigger change than this one.
- A one op window catches everything the frontends emit today but is trivially defeated by anything scheduled in between.
--- include/tcg/tcg-opc.h | 9 +++- tcg/tcg-op-ldst.c | 3 +- tcg/tcg.c | 86 ++++++++++++++++++++++++++++++++++++- tcg/x86_64/tcg-target.c.inc | 61 ++++++++++++++++++++++++++ tcg/x86_64/tcg-target.h | 3 ++ 5 files changed, 158 insertions(+), 4 deletions(-)
include/tcg/tcg-opc.h +7 -2
@@ -125,8 +125,13 @@ DEF(goto_ptr, 0, 1, 0, TCG_OPF_BB_EXIT | TCG_OPF_BB_END) DEF(plugin_cb, 0, 0, 1, TCG_OPF_NOT_PRESENT)DEF (plugin_mem_cb,0 ,1 ,1 ,TCG_OPF_NOT_PRESENT ) -DEF(qemu_ld, 1, 1, 1, TCG_OPF_CALL_CLOBBER | TCG_OPF_SIDE_EFFECTS | TCG_OPF_INT) -DEF(qemu_st, 0, 2, 1, TCG_OPF_CALL_CLOBBER | TCG_OPF_SIDE_EFFECTS | TCG_OPF_INT) +/* +* The second constant argument is a displacement to add to the address, +* zero unless a target advertises TCG_TARGET_HAS_ldst_disp and the fold in +* fold_ldst_disp() applied. + */ +DEF(qemu_ld, 1, 1, 2, TCG_OPF_CALL_CLOBBER | TCG_OPF_SIDE_EFFECTS | TCG_OPF_INT) +DEF(qemu_st, 0, 2, 2, TCG_OPF_CALL_CLOBBER | TCG_OPF_SIDE_EFFECTS | TCG_OPF_INT) DEF(qemu_ld2, 2, 1, 1, TCG_OPF_CALL_CLOBBER | TCG_OPF_SIDE_EFFECTS | TCG_OPF_INT)DEF (qemu_st2,0 ,3 ,1 ,TCG_OPF_CALL_CLOBBER |TCG_OPF_SIDE_EFFECTS |TCG_OPF_INT )
tcg/tcg-op-ldst.c +2 -1
@@ -92,7 +92,8 @@ static MemOp tcg_canonicalize_memop(MemOp op, bool is64, bool st)static void gen_ldst1 (TCGOpcode opc,TCGType type,TCGTemp *v,TCGTemp *addr,MemOpIdx oi) { -TCGOp *op =tcg_gen_op3 (opc, type,temp_arg (v),temp_arg (addr), oi); +/* The trailing zero is the address displacement; see fold_ldst_disp(). */ +TCGOp *op =tcg_gen_op4 (opc, type,temp_arg (v),temp_arg (addr), oi,0 );TCGOP_FLAGS (op) =get_memop (oi) &MO_SIZE ; }
tcg/tcg.c +85 -1
110 lines not on this page · raw message
tcg/x86_64/tcg-target.c.inc +61 -0
85 lines not on this page · raw message
tcg/x86_64/tcg-target.h +3 -0
@@ -30,6 +30,9 @@#define TCG_TARGET_NB_REGS 32#define MAX_CODE_GEN_BUFFER_SIZE (2 * GiB) +/* A guest displacement can go in the disp32 of the addressing mode. */ +#define TCG_TARGET_HAS_ldst_disp 1 + typedef enum { TCG_REG_EAX = 0, TCG_REG_ECX,
Signature · 1 line
2.54.0
Re: [PATCH v3 7/7] RFC: tcg: fold a guest displacement into the host addressing mode
Quoted 11 lines · Matt Turner
RFC because:
- Only wired up for
x86_64, and only forqemu_ldandqemu_st; the i128qemu_ld2andqemu_st2pairs are left alone.
- Requiring that no slow path exists is stricter than necessary. Recording the displacement in TCGLabelQemuLdst and emitting one lea on the slow path would cover alignment-checked accesses too, at no fast path cost.
- Softmmu wants the displacement folded into the TLB comparison as well, which is a bigger change than this one.
- A one op window catches everything the frontends emit today but is trivially defeated by anything scheduled in between.
Plausible. Several times I've considered exposing complex addressing modes to the translators so that things that do LEA are kept intact for awhile. There are plenty of host-specific code sequences for x << s + y + c, even before we fold that into the memory access. Then expose the host memory path to tcg ops, somehow, and finally implement a simple CSE pass. But yeah, hand waving is as far as I've ever gone.
On the second point, I guess you also assuming the offset is also aligned? I.e. for X + 8*N, you can test X for 8-byte alignment without constructing the complete address.
Quoted 11 lines
tcg/x86_64/tcg-target.c.inc +11
-0+static bool tcg_target_ldst_disp_ok(TCGContext *s, MemOpIdx oi, int64_t disp) +{ +#ifdef CONFIG_USER_ONLY + MemOp opc = get_memop(oi); + TCGAtomAlign aa; + int64_t ofs; + + if (tcg_use_softmmu || s->addr_type != TCG_TYPE_I64) { + return false; + } + aa = atom_and_align_for_opc(s, opc, MO_ATOM_WITHIN16,
tcg/x86_64/tcg-target.c.inc static TCGLabelQemuLdst *prepare_host_addr(TCGContext *s, HostAddress *h, · line 2061
Quoted 10 lines
tcg/x86_64/tcg-target.c.inc +10
-0+ (opc & MO_SIZE) == MO_128); + if (aa.align) { + return false; + } + ofs = (int64_t)x86_guest_base.ofs + disp; + return ofs == (int32_t)ofs; +#else + return false; +#endif +}
These compilation mode tests belong...
tcg/tcg.c static void move_label_uses(TCGLabel *to, TCGLabel *from) · line 3611
Quoted 8 lines
tcg/tcg.c +8
-0+static void __attribute__((noinline)) +fold_ldst_disp (TCGContext *s) +{ +TCGOp *op; + +if (!TCG_TARGET_HAS_ldst_disp) { +return ; + }
... here, before we step over the loop. You might as well pass MemOp to the target function and not MemOpIdx -- nothing about the mmu_idx is relevant.
Ideally, the atom_and_align test would also be done generically, not requiring each target to replicate that boilerplate.
r~
Re: [PATCH v3 7/7] RFC: tcg: fold a guest displacement into the host addressing mode
Quoted 14 lines · Richard Henderson
Quoted 11 lines · Matt Turner
RFC because:
- Only wired up for
x86_64, and only forqemu_ldandqemu_st; the i128qemu_ld2andqemu_st2pairs are left alone.
- Requiring that no slow path exists is stricter than necessary. Recording the displacement in TCGLabelQemuLdst and emitting one lea on the slow path would cover alignment-checked accesses too, at no fast path cost.
- Softmmu wants the displacement folded into the TLB comparison as well, which is a bigger change than this one.
- A one op window catches everything the frontends emit today but is trivially defeated by anything scheduled in between.
Quoted 6 lines
Plausible. Several times I've considered exposing complex addressing modes to the translators so that things that do LEA are kept intact for awhile. There are plenty of host-specific code sequences for x << s + y
+ c, even before we fold that into the memory access. Then expose the host memory path to tcg ops, somehow, and finally implement a simple CSE pass. But yeah, hand waving is as far as I've ever gone.
That's the shape I kept wanting. A one-op peephole is a poor substitute, and it loses the moment anything is scheduled between the add and the access. I went this way because it needed no frontend changes; happy to look at the op instead if you'd rather.
Quoted 3 lines
On the second point, I guess you also assuming the offset is also aligned? I.e. for X + 8*N, you can test X for 8-byte alignment without constructing the complete address.
Right, and that's what makes the second bullet worth doing. If disp is a multiple of the required alignment, X + disp is aligned exactly when X is, so the fast path test can stay on the base and never needs the full address. That covers every displacement a frontend emits for a struct or stack access.
What's left is the slow path, which hands addr_reg to the helper -- and addr_reg is now the base. Recording the displacement in TCGLabelQemuLdst and emitting one lea there fixes it at no fast path cost. v4 spells that out in the bullet but still refuses any access needing a test.
Quoted 35 lines
Quoted 11 lines
tcg/x86_64/tcg-target.c.inc +11
-0+static bool tcg_target_ldst_disp_ok(TCGContext *s, MemOpIdx oi, int64_t disp) +{ +#ifdef CONFIG_USER_ONLY + MemOp opc = get_memop(oi); + TCGAtomAlign aa; + int64_t ofs; + + if (tcg_use_softmmu || s->addr_type != TCG_TYPE_I64) { + return false; + } + aa = atom_and_align_for_opc(s, opc, MO_ATOM_WITHIN16,tcg/x86_64/tcg-target.c.inc static TCGLabelQemuLdst *prepare_host_addr(TCGContext *s, HostAddress *h, · line 2061
Quoted 10 lines
tcg/x86_64/tcg-target.c.inc +10
-0+ (opc & MO_SIZE) == MO_128); + if (aa.align) { + return false; + } + ofs = (int64_t)x86_guest_base.ofs + disp; + return ofs == (int32_t)ofs; +#else + return false; +#endif +}These compilation mode tests belong...
tcg/tcg.c static void move_label_uses(TCGLabel *to, TCGLabel *from) · line 3611
Quoted 8 lines
tcg/tcg.c +8
-0+static void __attribute__((noinline)) +fold_ldst_disp (TCGContext *s) +{ +TCGOp *op; + +if (!TCG_TARGET_HAS_ldst_disp) { +return ; + }... here, before we step over the loop. You might as well pass MemOp to the target function and not MemOpIdx -- nothing about the
mmu_idxis relevant.
Quoted 2 lines
Ideally, the
atom_and_aligntest would also be done generically, not requiring each target to replicate that boilerplate.
All three done. x86_64 is now just:
ofs = (int64_t)x86_guest_base.ofs + disp;
return ofs == (int32_t)ofs;The alignment one needed a compromise. atom_and_align_for_opc() takes host_atom and allow_two_ops and both feed aa.align, so a generic caller either gets them from the target -- the same boilerplate, moved to tcg-target.h -- or answers without them. I answered without them: a small ldst_disp_needs_align() that gives the answer for the most restrictive
host.
Exact for MO_ATOM_NONE and the IFALIGN cases, i.e. everything frontends emit by default, so the alpha numbers don't move. Conservative for MO_ATOM_WITHIN16 and MO_ATOM_SUBALIGN: x86 could take those folds and no longer does. One #define of the host atomicity next to TCG_TARGET_HAS_ldst_disp gets that back if you'd rather have it exact.
PATCH v4 1/9 accel/tcg: fold the dynamic cflags into CPUState::tcg_cflags
In reply to Matt Turnercurr_cflags() is called once per TB dispatch, from helper_lookup_tb_ptr() and from the cpu_exec() loop. It recomputes the same value every time:
uint32_t cflags = cpu->tcg_cflags;
if (unlikely(cpu_single_stepping(cpu))) { ... }
else if (qatomic_read(&one_insn_per_tb)) { ... }
else if (qemu_loglevel_mask(CPU_LOG_TB_NOCHAIN)) { ... }That is three loads and three branches on the hottest path in the interpreter, for state that changes only when gdb enables single-step, when one-insn-per-tb is toggled, or when the log mask changes.
None of the three has to be sampled at dispatch time. Fold each into CPUState::tcg_cflags where it changes and curr_cflags() becomes a single load of a field that TB lookup has to read anyway.
The derived bits -- CF_COUNT_MASK, CF_NO_GOTO_TB, CF_NO_GOTO_PTR and CF_SINGLE_STEP -- are never set by tcg_cflags_set(), so tcg_update_cflags() can recompute them in place without disturbing the rest, and conversely tcg_cflags_set() ORs in its bits without disturbing them.
There are three places to call it:
- tcg_exec_realizefn(), so that a CPU created after the command line has been parsed starts out with the right value. This covers user-only, where tcg_cpu_init_cflags() is not reached. linux-user's cpu_copy() copies tcg_cflags wholesale, so a cloned thread inherits it.
- cpu_single_step(), which changes one CPU. gdb is the only caller that matters; in system mode it runs with the vCPUs stopped, and in user mode gdb_continue_partial() can reach a thread that is still running, because gdb_handlesig() stops only the thread that trapped. That is exactly the plain cross-thread store to another CPU's CPUState that cpu->singlestep_flags already was, read back by that CPU through cpu_single_stepping() in curr_cflags(). This patch changes which field carries it, not who writes it or how.
- hmp_one_insn_per_tb() and hmp_log(), which change every CPU while the vCPUs are running, so the update is queued with async_run_on_cpu() and each CPU writes its own cflags from its own thread. The command line spellings of those two settings need nothing: they are parsed before any CPU is realized, so tcg_exec_realizefn() picks them up.
Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host, in a build configured with --enable-lto:
before: 1,646,994,254,249 instructions
after: 1,562,204,796,597 instructions -5.15%That workload issues 8.4 billion dispatches, so the per-call saving is small but the aggregate is not. The emulated compiler produces byte-identical output before and after.
Wall clock does not move: 133.19s to 132.58s, a 0.46% difference against a run-to-run spread larger than that. The removed work is a few predictable loads and branches that the host executes largely in parallel with the surrounding dispatch, so this patch is worth taking for the instruction count and for what it enables, not for a time saving that can be measured on its own.
v4: Update the cflags from the HMP handlers for 'log' and 'one-insn-per-tb'
rather than from qemu_set_log_internal() and the accelerator property setter. Those are the paths that reach a running vCPU, and the monitor is the only thing that does. Suggested by Richard Henderson.
v4: Queue the per-CPU update with async_run_on_cpu() rather than
async_safe_run_on_cpu(). Halting the other vCPUs buys nothing: the queued work already runs on the owning CPU's own thread. Suggested by Alex Bennee, who also asked whether there are cross-vCPU updates of tcg_cflags at all. With this change the monitor path has none: the only remaining writer from another thread is cpu_single_step(), above, which is neither new nor made worse here.
v4: Move the stub to accel/stubs/, which is where the other accelerator
stubs live.
--- accel/stubs/meson.build | 1 + accel/stubs/tcg-stub.c | 16 ++++++++++++++++ accel/tcg/cpu-exec-common.c | 33 ++++++++++++++++++++++++++++++--- accel/tcg/cpu-exec.c | 3 +++ accel/tcg/internal-common.h | 11 +++++++++-- cpu-target.c | 3 +++ include/system/tcg.h | 12 ++++++++++++ monitor/hmp-cmds.c | 5 +++++ system/runstate-hmp-cmds.c | 4 ++++ 9 files changed, 83 insertions(+), 5 deletions(-) create mode 100644 accel/stubs/tcg-stub.c
accel/stubs/meson.build +1 -0
@@ -4,6 +4,7 @@ stub_ss.add(files( 'nitro-stub.c', 'mshv-stub.c', 'nvmm-stub.c', + 'tcg-stub.c', 'whpx-stub.c', 'xen-stub.c', ))
accel/stubs/tcg-stub.c new file +16 -0
@@ -0,0 +1,16 @@ +/* +* Stubs for the TCG entry points in system/tcg.h, for binaries that link +* cpu-target.c or the HMP command handlers but not TCG. +* +* SPDX-License-Identifier: GPL-2.0-or-later +*/ +#include "qemu/osdep.h" +#include "system/tcg.h" + +void tcg_update_cflags (CPUState *cpu) +{ +} + +void tcg_update_all_cflags (void ) +{ +}
accel/tcg/cpu-exec-common.c +30 -3
@@ -36,9 +36,16 @@ void tcg_cflags_set(CPUState *cpu, uint32_t flags) cpu->tcg_cflags |= flags; } -uint32_t curr_cflags (CPUState *cpu) +/* +* The bits of CPUState::tcg_cflags that tcg_cflags_set() never sets, because +* they are derived from gdb single-step, one-insn-per-tb and -d nochain. +*/ +#define CF_DERIVED (CF_COUNT_MASK | CF_NO_GOTO_TB | CF_NO_GOTO_PTR | \ + CF_SINGLE_STEP) + +void tcg_update_cflags (CPUState *cpu) { -uint32_t cflags = cpu->tcg_cflags; +uint32_t cflags = cpu->tcg_cflags & ~CF_DERIVED ;/* * Record gdb single-step. We should be exiting the TB by raising
@@ -55,7 +62,27 @@ uint32_t curr_cflags(CPUState *cpu) cflags |=CF_NO_GOTO_TB ; } -return cflags; + cpu->tcg_cflags = cflags; +} + +static void tcg_update_cflags_work (CPUState *cpu,run_on_cpu_data data) +{ +tcg_update_cflags (cpu); +} + +void tcg_update_all_cflags (void ) +{ +CPUState *cpu; + +/* +* one-insn-per-tb and -d nochain can both be changed from the monitor +* while the vCPUs are running. Queue the update onto each CPU rather +* than writing tcg_cflags from here, so that the field is only ever +* written by the CPU that owns it. +*/ +CPU_FOREACH (cpu) { +async_run_on_cpu (cpu, tcg_update_cflags_work,RUN_ON_CPU_NULL ); + } }/* exit the current TB, but without causing any exception to be raised */
accel/tcg/cpu-exec.c +3 -0
@@ -1068,6 +1068,9 @@ bool tcg_exec_realizefn(CPUState *cpu, Error **errp) tcg_target_initialized = true; } +/* Pick up one-insn-per-tb and -d nochain from the command line. */ +tcg_update_cflags (cpu); + cpu->tb_jmp_cache =g_new0 (CPUJumpCache,1 );tlb_init (cpu);#ifndef CONFIG_USER_ONLY
accel/tcg/internal-common.h +9 -2
@@ -69,8 +69,15 @@ void tlb_destroy(CPUState *cpu);bool tcg_exec_realizefn (CPUState *cpu,Error **errp);void tcg_exec_unrealizefn (CPUState *cpu); -/* current cflags for hashing/comparison */ -uint32_t curr_cflags (CPUState *cpu); +/* +* Current cflags for hashing/comparison. Everything that feeds into the +* value is folded into CPUState::tcg_cflags when it changes, by +* tcg_update_cflags(), so that TB dispatch only has to load it. +*/ +static inline uint32_t curr_cflags (CPUState *cpu) +{ +return cpu->tcg_cflags; +}void tb_check_watchpoint (CPUState *cpu,uintptr_t retaddr);
cpu-target.c +3 -0
@@ -24,6 +24,7 @@#include "exec/replay-core.h" #include "exec/log.h" #include "hw/core/cpu.h" +#include "system/tcg.h" #include "trace/trace-root.h" /* enable or disable single step mode. EXCP_DEBUG is returned by the
@@ -35,6 +36,8 @@ void cpu_single_step(CPUState *cpu, unsigned flags) cpu->singlestep_flags, flags); cpu->singlestep_flags = flags; +tcg_update_cflags (cpu); +#if !defined(CONFIG_USER_ONLY )const AccelOpsClass *ops =cpus_get_accel ();if (ops->update_guest_debug) {
include/system/tcg.h +12 -0
@@ -17,6 +17,18 @@ extern bool tcg_allowed;#define tcg_enabled () 0#endif +/* +* Recompute the parts of CPUState::tcg_cflags that TB dispatch consumes but +* tcg_cflags_set() does not provide: gdb single-step, one-insn-per-tb and +* the CPU_LOG_TB_NOCHAIN log flag. Call whenever one of those changes. +* +* tcg_update_cflags() updates one CPU and must be called from that CPU's +* thread, or with it stopped. tcg_update_all_cflags() updates every CPU +* and is safe to call from the monitor while the vCPUs run. +*/ +void tcg_update_cflags (CPUState *cpu); +void tcg_update_all_cflags (void ); +/** * qemu_tcg_mttcg_enabled: * Check whether we are running MultiThread TCG or not.
monitor/hmp-cmds.c +5 -0
@@ -39,6 +39,7 @@#include "system/hw_accel.h" #include "system/memory.h" #include "system/system.h" +#include "system/tcg.h" #include "disas/disas.h" /* Please update hmp-commands.hx when adding or changing commands */
@@ -335,7 +336,11 @@ void hmp_log(Monitor *mon, const QDict *qdict)if (!qemu_set_log (mask, &err)) {error_report_err (err); +return ; } + +/* CPU_LOG_TB_NOCHAIN feeds into the per-CPU cflags. */ +tcg_update_all_cflags (); }void hmp_gdbserver (Monitor *mon,const QDict *qdict)
system/runstate-hmp-cmds.c +4 -0
@@ -22,6 +22,7 @@#include "qapi/qapi-commands-run-state.h" #include "qobject/qdict.h" #include "qemu/accel.h" +#include "system/tcg.h" void hmp_info_status (Monitor *mon,const QDict *qdict) {
@@ -64,6 +65,9 @@ void hmp_one_insn_per_tb(Monitor *mon, const QDict *qdict)/* If the property exists then setting it can never fail */ object_property_set_bool (OBJECT (accel),"one-insn-per-tb" , newval, &error_abort); + +/* one-insn-per-tb feeds into the per-CPU cflags. */ +tcg_update_all_cflags (); }void hmp_watchdog_action (Monitor *mon,const QDict *qdict)
Signature · 1 line
2.54.0
Re: [PATCH v4 1/9] accel/tcg: fold the dynamic cflags into CPUState::tcg_cflags
Quoted 89 lines · Matt Turner
curr_cflags()is called once per TB dispatch, fromhelper_lookup_tb_ptr()and from thecpu_exec()loop. It recomputes the same value every time:uint32_t cflags = cpu->tcg_cflags; if (unlikely(cpu_single_stepping(cpu))) { ... } else if (qatomic_read(&one_insn_per_tb)) { ... } else if (qemu_loglevel_mask(CPU_LOG_TB_NOCHAIN)) { ... }That is three loads and three branches on the hottest path in the interpreter, for state that changes only when gdb enables single-step, when one-insn-per-tb is toggled, or when the log mask changes.
None of the three has to be sampled at dispatch time. Fold each into
CPUState::tcg_cflagswhere it changes andcurr_cflags()becomes a single load of a field that TB lookup has to read anyway.The derived bits --
CF_COUNT_MASK,CF_NO_GOTO_TB,CF_NO_GOTO_PTRandCF_SINGLE_STEP-- are never set bytcg_cflags_set(), sotcg_update_cflags()can recompute them in place without disturbing the rest, and converselytcg_cflags_set()ORs in its bits without disturbing them.There are three places to call it:
-
tcg_exec_realizefn(), so that a CPU created after the command line has been parsed starts out with the right value. This covers user-only, wheretcg_cpu_init_cflags()is not reached. linux-user'scpu_copy()copiestcg_cflagswholesale, so a cloned thread inherits it.-
cpu_single_step(), which changes one CPU. gdb is the only caller that matters; in system mode it runs with the vCPUs stopped, and in user modegdb_continue_partial()can reach a thread that is still running, becausegdb_handlesig()stops only the thread that trapped. That is exactly the plain cross-thread store to another CPU's CPUState thatcpu->singlestep_flagsalready was, read back by that CPU throughcpu_single_stepping()incurr_cflags(). This patch changes which field carries it, not who writes it or how.-
hmp_one_insn_per_tb()andhmp_log(), which change every CPU while the vCPUs are running, so the update is queued withasync_run_on_cpu()and each CPU writes its own cflags from its own thread. The command line spellings of those two settings need nothing: they are parsed before any CPU is realized, sotcg_exec_realizefn()picks them up.Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host, in a build configured with --enable-lto:
before: 1,646,994,254,249 instructions after: 1,562,204,796,597 instructions -5.15%That workload issues 8.4 billion dispatches, so the per-call saving is small but the aggregate is not. The emulated compiler produces byte-identical output before and after.
Wall clock does not move: 133.19s to 132.58s, a 0.46% difference against a run-to-run spread larger than that. The removed work is a few predictable loads and branches that the host executes largely in parallel with the surrounding dispatch, so this patch is worth taking for the instruction count and for what it enables, not for a time saving that can be measured on its own.
v4: Update the cflags from the HMP handlers for 'log' and 'one-insn-per-tb'
rather than fromqemu_set_log_internal()and the accelerator property setter. Those are the paths that reach a running vCPU, and the monitor is the only thing that does. Suggested by Richard Henderson.v4: Queue the per-CPU update with
async_run_on_cpu()rather than
async_safe_run_on_cpu(). Halting the other vCPUs buys nothing: the queued work already runs on the owning CPU's own thread. Suggested by Alex Bennee, who also asked whether there are cross-vCPU updates oftcg_cflagsat all. With this change the monitor path has none: the only remaining writer from another thread iscpu_single_step(), above, which is neither new nor made worse here.v4: Move the stub to accel/stubs/, which is where the other accelerator
stubs live.Signed-off-by Matt Turner<[email protected]>--- accel/stubs/meson.build | 1 + accel/stubs/tcg-stub.c | 16 ++++++++++++++++ accel/tcg/cpu-exec-common.c | 33 ++++++++++++++++++++++++++++++--- accel/tcg/cpu-exec.c | 3 +++ accel/tcg/internal-common.h | 11 +++++++++-- cpu-target.c | 3 +++ include/system/tcg.h | 12 ++++++++++++ monitor/hmp-cmds.c | 5 +++++ system/runstate-hmp-cmds.c | 4 ++++ 9 files changed, 83 insertions(+), 5 deletions(-)
Quoted 1 line
create mode 100644
accel/stubs/tcg-stub.c
r~
v4 cover accel/tcg: cut per-block dispatch overhead
In reply to Matt TurnerFor guests running large amounts of code, most of what TCG executes is not translated guest work but the fixed overhead around it. Blocks are short and there are a great many of them, so the constant cost at each end of a block (the interrupt poll and the can_do_io stores on entry, the dispatch on exit) ends up dominating everything else.
The workload throughout is qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host, in a --static --enable-lto --target-list=alpha-linux-user build. It executes 34.2 billion TBs at 6.04 guest instructions each, and 24.6% of its TB exits cannot use goto_tb. That is a representative shape for any guest whose text is much larger than a page: indirect calls and returns everywhere, plus direct branches that merely crossed a page boundary.
The first three patches are ordinary cleanups that stand on their own; patch 3 picked up review tags in v2. Patches 4 and 5 are preparation split out of v3's patch 4 at Richard's request and move nothing on their own. The remaining four are marked RFC individually and are where the interesting questions are.
1 accel/tcg: fold the dynamic cflags into CPUState::tcg_cflags
curr_cflags() recomputed three unlikely tests on every one of the run's 8.4 billion dispatches, from state that changes only when gdb enables single-step, when one-insn-per-tb is toggled, or when the log mask
moves. Fold each into tcg_cflags where it changes. -5.15%
2 accel/tcg: enlarge the TB jump cache to 64K entries
4096 entries is too small for a guest running a large program; tb_htable_lookup() is 6.10% of samples. 16 bits is the knee of the
sizing curve, at 1 MiB per CPUState. -5.92%, -8.71% wall
3 accel/tcg: skip the can_do_io stores in user-only builds
Two stores per TB that nothing in a user-only build reads: 68 billion
of them over the run. -4.57%, -4.53% wall
4 tcg: pass the destination to tcg_gen_lookup_and_goto_ptr()
Preparation. The destination PC is already in a TCG temp at every one of the 38 call sites; give the helper wrapper the option of taking it rather than discarding it. Five targets pass it; the rest pass NULL and keep today's behavior.
5 accel/tcg: give the TB jump cache a second base pointer for generated
code
Preparation. CPUState::tb_jmp_cache_probe is a base pointer only generated code reads. Pointing it at a shared zero-filled cache makes every lookup through it miss, which is how the conditions an inline probe cannot check force it back into the helper. Nothing reads it yet.
6 RFC: tcg: probe the TB jump cache inline instead of calling a helper
95.8% of those 8.4 billion helper_lookup_tb_ptr() calls hit the jump cache. Emit the probe inline (hash, four guarded loads, goto_ptr) and
call the helper only on a miss. -34.67%, -25.94% wall
7 RFC: accel/tcg: allow cross-page goto_tb chaining in user-only builds
translator_use_goto_tb() refuses to chain across a page. In user-only builds the invalidation path already covers what that was protecting
against: every mmap/mprotect/munmap reaches page_set_flags(), which invalidates and unlinks. Lift it there for runs that can never acquire
a breakpoint, keep it for system mode. -2.75%, -4.84% wall
8 RFC: accel/tcg: poison the jump cache instead of polling for indirect
exits
A block only needs the icount_decr poll if it can leave by goto_tb; every other exit already passes through a dispatch. Poison the probe pointer from patch 5 when an exit is requested, so every dispatch misses into the helper, which returns the epilogue. Emit the poll only
in blocks that emitted a goto_tb. -2.52%, -1.96% wall
9 RFC: tcg: fold a guest displacement into the host addressing mode
tcg_gen_qemu_ld/st cannot express a based access, so a target with a displacement in its encodings materializes the address with an lea that the host addressing mode would have done for free. Fold a preceding constant add into a new argument on the op, opt-in per
backend, wired up for x86_64 user-only. -5.70%, -3.20% wall
Each percentage is against the patch before it. Every stage was measured in one session on the same host, so end to end, from an unmodified LTO build of the same base to the full series:
instructions retired: 1,646,994,254,249 -> 819,262,147,022 -50.26%
wall clock: 133.19s -> 77.30s -41.96%Those are the v3 measurements. The machine they were taken on is busy, so v4 has not been re-measured. Nothing in the v4 changes is expected to move them -- the splits are pure reorganization, the new alignment test in patch 9 reaches the same answer for everything the alpha frontend emits, and the emulated compiler's output is unchanged -- but they are not a measurement of this posting and should not be read as one.
The two figures do not track each other, and that is the interesting part:
what the series removes is cheap, well-predicted, highly pipelined work, so it retires far more instructions than it saves time. Patch 6 also cuts L1 icache load misses by 39.0%, because a dispatch no longer jumps into qemu's .text and evicts translated code; qemu's own .text falls from 38.8% to 5.3% of profile samples.
Every step builds and runs on its own, so the series bisects, and the emulated compiler produces byte-identical assembly output at every step, which is the correctness check these patches most need. Three new tests cover the hazards the series creates, all under tests/tcg/multiarch as of this revision: test-xpage-chain.c and gdbstub/xpage-bp.py (patch 7) and test-indirect-irq.c (patch 8). Each fails or hangs if the mechanism it covers is removed, which is what makes them tests of the new behavior rather than of the old.
Changes since v3
================
The biggest change is that v3's patch 4 is split three ways, as Richard
asked: the tcg_gen_lookup_and_goto_ptr() API change is now patch 4, the tb_jmp_cache_probe base pointer and its poison are patch 5, and the inline probe itself is patch 6. The other structural change is that both guest tests move from tests/tcg/alpha to tests/tcg/multiarch, as Alex asked, so every *-user target runs them. tests/tcg/alpha is now byte-identical to master again.
1 Update the cflags from the HMP handlers for 'log' and
'one-insn-per-tb' rather than from qemu_set_log_internal() and the accelerator property setter; those are the paths that reach a running vCPU, and the monitor is the only thing that does (Richard). Queue the per-CPU update with async_run_on_cpu() rather than async_safe_run_on_cpu(): halting the other vCPUs buys nothing, since the queued work already runs on the owning CPU's own thread (Alex). Alex also asked whether there are cross-vCPU updates of tcg_cflags at all; with this change the monitor path has none, and the only remaining writer from another thread is cpu_single_step(), which is neither new nor made worse here. Stub moved to accel/stubs/, where the other accelerator stubs live (Philippe).
2 Commit message only: a linux-user process is not a single vCPU. The
cache is per CPUState and linux-user creates one per guest thread, so a threaded guest pays the 1 MiB per thread, exactly as system emulation pays it per vCPU (Richard).
3 Unchanged.
4 New, split out of v3's patch 4. No functional change from v3. Its
commit message no longer claims most targets can simply pass a PC:
five do, six cannot because their TB pc is derived (avr doubles it, i386's is pre-segmentation, riscv masks it, hppa derives it from the IAQ, hexagon adjusts it in hardware loops, sparc puts npc in cs_base), and seven look like they could but are untested.
5 Also new, split out of v3's patch 4. The poison cache is a static
object rather than one allocated on first use (Richard, who asked for const; the commit message says why it is plain static and lands in .bss).
6 What remains of v3's patch 4. Emit the softmmu form of
tb_jmp_cache_hash_func() under CONFIG_SOFTMMU rather than the user-only form everywhere: v3 was wrong for system mode, and only not a correctness bug because a wrong index simply misses (Richard). Compare the pc before testing tb for NULL, assert that TranslationBlock::flags is 8-byte aligned since folding the two guards into one 64-bit load relies on it, zero-extend a 32-bit guest PC instead of falling back to the helper, and describe cs_base in the probe as a second word of target-specific flags rather than by name (all Richard).
7 Test moved to tests/tcg/multiarch (Alex). The hand-written branch went
with it: falling off the end of a page is a cross-page goto_tb just the same, and needs no per-architecture branch encoding or displacement arithmetic, only "set the return value" and "return". Built and run under qemu-user on aarch64, alpha, arm, hppa, loongarch64, m68k, mips, ppc, ppc64le, riscv64, s390x, sh4, sparc64 and x86_64; ppc64 ELFv1 skips, because a function pointer there is a descriptor rather than a code address.
8 Test likewise moved to tests/tcg/multiarch (Alex). Nothing in it is
architecture specific: the loop is a computed goto, which every target's compiler supports, so it covers whichever targets go on to use the inline probe.
9 Hoist the compilation mode tests -- tcg_use_softmmu and the 64-bit
address type -- out of the backend hook into fold_ldst_disp(), so the loop is not entered at all when the mode rules the fold out. Pass MemOp rather than MemOpIdx to the hook; nothing about the mmu_idx is relevant to it. Move the alignment test into generic code as ldst_disp_needs_align(), so a backend need not repeat the atom_and_align_for_opc() call; the exact answer depends on the host's atomicity capabilities, which the generic pass does not know, so it answers for the most restrictive host. That is the same answer for everything the frontends actually emit, and conservative for the handful of MO_ATOM_WITHIN16 and MO_ATOM_SUBALIGN accesses. (All Richard.) What is left of the x86_64 hook is the guest_base test, so it now lives beside x86_guest_base under the CONFIG_USER_ONLY that declares it. Also refuse a displacement that does not fit the int32_t out_disp() takes, which is unreachable with any real guest_base but which the interface could not have carried.
What I would most like reviewed
===============================
- Patch 7 reverses a deliberate decision made in d3a2a1d803 on the strength of an argument about the user-only invalidation paths, plus a gate on whether gdb can ever attach.
- Patch 8's un-poison in the main loop races a concurrent poison from another thread. I believe the existing barrier around icount_decr.u16.high covers it, but my testing was single-threaded user mode.
- Patch 6 treats cpu flags, cflags and cs_base as translation-time constants in its guards, reads a jump cache entry without qatomic_read(), and leaves one_insn_per_tb and -d nochain toggles visible only at the next non-inline exit.
- Patch 9 only examines the immediately preceding op, refuses any access with a slow path (so user-only, and no alignment check), and leaves the i128 pairs alone. Richard asked whether the alignment test could stay on the base register when the displacement is itself aligned; it can, and the reason the fold is still refused there is the slow path handing addr_reg to the helper. Recording the displacement in TCGLabelQemuLdst and emitting one lea on the slow path would cover alignment-checked accesses too, at no fast path cost. Not attempted here.
- Patch 2's 1 MiB per CPUState is easy to justify for a single-threaded linux-user process and less obvious for system emulation with many vCPUs, or for a heavily threaded guest. It may want to be sized per target or made tunable rather than raised unconditionally.
Patches 6 and 9 are wired up for alpha and x86_64 respectively; everything else is target-independent, and no other backend changes behavior or needs touching.
v3: https://lore.kernel.org/qemu-devel/[email protected]/
v2: https://lore.kernel.org/qemu-devel/[email protected]/
Matt Turner (9):
accel/tcg: fold the dynamic cflags into CPUState::tcg_cflags accel/tcg: enlarge the TB jump cache to 64K entries accel/tcg: skip the can_do_io stores in user-only builds
tcg: pass the destination to tcg_gen_lookup_and_goto_ptr() accel/tcg: give the TB jump cache a second base pointer for generated
code
RFC: tcg: probe the TB jump cache inline instead of calling a helper
RFC: accel/tcg: allow cross-page goto_tb chaining in user-only builds
RFC: accel/tcg: poison the jump cache instead of polling for indirect
exits
RFC: tcg: fold a guest displacement into the host addressing mode
accel/stubs/meson.build | 1 + accel/stubs/tcg-stub.c | 20 ++ accel/tcg/cpu-exec-common.c | 33 +- accel/tcg/cpu-exec.c | 116 ++++++ accel/tcg/internal-common.h | 13 +- accel/tcg/tb-jmp-cache.h | 2 +- accel/tcg/tcg-accel-ops.c | 1 + accel/tcg/translator.c | 94 ++++- cpu-common.c | 11 + cpu-target.c | 3 + gdbstub/user.c | 14 + include/gdbstub/user.h | 11 + include/hw/core/cpu.h | 11 + include/system/tcg.h | 21 ++ include/tcg/tcg-op-common.h | 15 +- include/tcg/tcg-op.h | 12 + include/tcg/tcg-opc.h | 9 +- include/tcg/tcg.h | 2 + monitor/hmp-cmds.c | 5 + system/runstate-hmp-cmds.c | 4 + target/alpha/translate.c | 4 +- target/arm/tcg/translate-a64.c | 4 +- target/arm/tcg/translate.c | 10 +- target/avr/translate.c | 4 +- target/hexagon/translate.c | 4 +- target/hppa/translate.c | 6 +- target/i386/tcg/translate.c | 2 +- .../tcg/insn_trans/trans_branch.c.inc | 2 +- target/loongarch/tcg/translate.c | 4 +- target/m68k/translate.c | 2 +- target/microblaze/translate.c | 4 +- target/mips/tcg/nanomips_translate.c.inc | 2 +- target/mips/tcg/translate.c | 6 +- target/or1k/translate.c | 4 +- target/ppc/translate.c | 4 +- target/riscv/tcg/insn_trans/trans_rvzce.c.inc | 4 +- target/riscv/tcg/translate.c | 2 +- target/rx/translate.c | 4 +- target/s390x/tcg/translate.c | 5 +- target/sh4/translate.c | 4 +- target/sparc/translate.c | 4 +- target/tricore/translate.c | 4 +- tcg/tcg-op-ldst.c | 3 +- tcg/tcg-op.c | 142 +++++++- tcg/tcg.c | 132 ++++++- tcg/x86_64/tcg-target.c.inc | 41 +++ tcg/x86_64/tcg-target.h | 3 + tests/tcg/multiarch/Makefile.target | 12 +- tests/tcg/multiarch/gdbstub/xpage-bp.py | 37 ++ tests/tcg/multiarch/test-indirect-irq.c | 62 ++++ tests/tcg/multiarch/test-xpage-chain.c | 336 ++++++++++++++++++ 51 files changed, 1192 insertions(+), 63 deletions(-) create mode 100644 accel/stubs/tcg-stub.c create mode 100644 tests/tcg/multiarch/gdbstub/xpage-bp.py create mode 100644 tests/tcg/multiarch/test-indirect-irq.c create mode 100644 tests/tcg/multiarch/test-xpage-chain.c
base-commit: eea8fe61b8be8f3016e522e6af24924a0266ca95
Signature · 1 line
2.54.0
v5 cover accel/tcg: cut per-block dispatch overhead
For guests running large amounts of code, most of what TCG executes is not translated guest work but the fixed overhead around it. Blocks are short and there are a great many of them, so the constant cost at each end of a block (the interrupt poll and the can_do_io stores on entry, the dispatch on exit) ends up dominating everything else.
The workload throughout is qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host, in a --static --enable-lto --target-list=alpha-linux-user build. It executes 34.2 billion TBs at 6.04 guest instructions each, and 24.6% of its TB exits cannot use goto_tb. That is a representative shape for any guest whose text is much larger than a page: indirect calls and returns everywhere, plus direct branches that merely crossed a page boundary.
The first three patches are ordinary cleanups that stand on their own; patch 1 picked up a review tag in v4 and patch 3 in v2. Patches 4 and 5 are preparation and move nothing on their own. The remaining four are marked RFC individually and are where the interesting questions are.
1 accel/tcg: fold the dynamic cflags into CPUState::tcg_cflags
curr_cflags() recomputed three unlikely tests on every one of the run's 8.4 billion dispatches, from state that changes only when gdb enables single-step, when one-insn-per-tb is toggled, or when the log mask
moves. Fold each into tcg_cflags where it changes. -5.15%
2 accel/tcg: enlarge the TB jump cache to 64K entries
4096 entries is too small for a guest running a large program; tb_htable_lookup() is 6.10% of samples. 16 bits is the knee of the
sizing curve, at 1 MiB per CPUState. -5.92%, -8.71% wall
3 accel/tcg: skip the can_do_io stores in user-only builds
Two stores per TB that nothing in a user-only build reads: 68 billion
of them over the run. -4.57%, -4.53% wall
4 tcg: add tcg_gen_goto_jc_{i32,i64,tl}()
Preparation. A second dispatch interface alongside tcg_gen_lookup_and_goto_ptr(), which is unchanged. The caller passes the destination PC and thereby states that the CPU state is already the destination's, which is what an inline lookup needs and what the existing interface cannot promise. --enable-debug-tcg checks that claim at runtime. Five targets are migrated; every other target and every unmigrated call site is untouched.
5 accel/tcg: add CF_NO_GOTO_JC, set while a breakpoint is present
Preparation. The one thing an inline jump cache probe cannot check is breakpoints, and it does not have to: the probe compares cflags, so a cflag set while cpu->breakpoints is non-empty keeps such blocks both from dispatching inline and from being reached by a block that does. Nothing reads it yet.
6 RFC: tcg: probe the TB jump cache inline instead of calling a helper
95.8% of those 8.4 billion helper_lookup_tb_ptr() calls hit the jump cache. Emit the probe inline (hash, four guarded loads, goto_ptr) and
call the helper only on a miss. -34.67%, -25.94% wall
7 RFC: accel/tcg: allow cross-page goto_tb chaining in user-only builds
translator_use_goto_tb() refuses to chain across a page. In user-only builds the invalidation path already covers what that was protecting
against: every mmap/mprotect/munmap reaches page_set_flags(), which invalidates and unlinks. Lift it there for runs that can never acquire
a breakpoint, keep it for system mode. -2.75%, -4.84% wall
8 RFC: accel/tcg: poison the jump cache instead of polling for indirect
exits
A block only needs the icount_decr poll if it can leave by goto_tb; every other exit already passes through a dispatch. Give generated code its own jump cache base pointer and point it at a read-only page of zeroes when an exit is requested, so every dispatch misses into the helper, which returns the epilogue. Emit the poll only in blocks that
emitted a goto_tb. -2.52%, -1.96% wall
9 RFC: tcg: fold a guest displacement into the host addressing mode
tcg_gen_qemu_ld/st cannot express a based access, so a target with a displacement in its encodings materializes the address with an lea that the host addressing mode would have done for free. Fold a preceding constant add into a new argument on the op, opt-in per
backend, wired up for x86_64 user-only. -5.70%, -3.20% wall
Each percentage is against the patch before it. Every stage was measured in one session on the same host, so end to end, from an unmodified LTO build of the same base to the full series:
instructions retired: 1,646,994,254,249 -> 819,262,147,022 -50.26%
wall clock: 133.19s -> 77.30s -41.96%Those are still the v3 measurements, unchanged and not re-run; the machine they were taken on is busy. Nothing in v4 or v5 is expected to move them -- both revisions are reorganization, and the emulated compiler's output is still byte-identical -- but they are not a measurement of this posting and should not be read as one.
The two figures do not track each other, and that is the interesting part:
what the series removes is cheap, well-predicted, highly pipelined work, so it retires far more instructions than it saves time. Patch 6 also cuts L1 icache load misses by 39.0%, because a dispatch no longer jumps into qemu's .text and evicts translated code; qemu's own .text falls from 38.8% to 5.3% of profile samples.
Every step builds and runs on its own, so the series bisects, and the emulated compiler produces byte-identical assembly output at every step, which is the correctness check these patches most need. Three tests under tests/tcg/multiarch cover the hazards the series creates: test-xpage-chain.c and gdbstub/xpage-bp.py (patch 7) and test-indirect-irq.c (patch 8). Each fails or hangs if the mechanism it covers is removed, which is what makes them tests of the new behavior rather than of the old.
Changes since v4
================
The structural change is that v4's patches 4 and 5 are gone, replaced by different patches with the same job.
v4's patch 4 added an argument to tcg_gen_lookup_and_goto_ptr() and made every caller pass NULL. Richard's example is target/arm, where DISAS_UPDATE_NOCHAIN needs the helper because the state has changed while DISAS_JUMP does not; that subtlety, he pointed out, means the existing interface should not be adjusted at all, and that targets should migrate to a new one instead. So v5 leaves tcg_gen_lookup_and_goto_ptr(void) as it was and adds tcg_gen_goto_jc_{i32,i64,tl}() beside it. Only the five migrated targets are touched, rather than all twenty; the diffstat is a good summary of the difference.
v4's patch 5 gave generated code a second jump cache base pointer and poisoned it when a breakpoint was inserted, which needed a cross-thread poison, an un-poison, and a double check of the breakpoint list. Richard suggested a cflag instead, which is both simpler and sufficient: the probe already compares cflags, so CF_NO_GOTO_JC alone keeps both the block itself and anything chaining to it off the inline path. The whole poison mechanism leaves this patch. The base pointer moves down to patch 8, where a pending exit is the only reason left to want one, that being a per-execution condition no cflag can express.
1 Reviewed-by: Richard Henderson.
2 Unchanged.
3 Unchanged.
4 Replaces "tcg: pass the destination to tcg_gen_lookup_and_goto_ptr()".
New interface rather than a changed one; _i32 and _i64 entry points with a _tl alias in tcg-op.h rather than one entry point taking a TCGTemp, since single-binary targets build once and stop relying on TARGET_LONG_BITS; and a new helper_goto_jc_check() that asserts pc, flags and cs_base against get_tb_cpu_state() under CONFIG_DEBUG_TCG. (All Richard.) The contract is now written on the declaration rather than left to be inferred.
5 Replaces "accel/tcg: give the TB jump cache a second base pointer for
generated code" (Richard, as above). That leaves a residual window, in which blocks translated before the insert keep chaining on their old cflags until the vCPU reaches its main loop. It is the same window goto_tb chaining already has, and in system mode gdb inserts breakpoints with the vCPUs stopped, so there is none. The commit message says so rather than leaving it implicit.
6 Build the folded flags/cflags constant with deposit64() rather than
under #if HOST_BIG_ENDIAN, so both arms compile on every host (Richard). Read cpu->tb_jmp_cache directly and honor CF_NO_GOTO_JC, following patch 5. Commit message notes the backend expansion this wants as a follow-up, which is Richard's list: x86_64 and s390x can compare against a memory operand, and aarch64 has shift-add for the entry address, ldp to load (tb, pc) and (cs_base, flags), and ccmp to halve the branches. Not attempted here: the probe as posted is correct on every backend, and the expansions are strictly additive and deserve their own numbers, particularly the aarch64 one, which changes the shape enough that it should be measured on aarch64 hardware.
7 Unchanged.
8 Gains CPUState::tb_jmp_cache_probe from v4's patch 5. With breakpoints
handled by a cflag, a pending exit is the only reason left to poison, so there is one condition rather than two, no cross-thread poison from cpu_breakpoint_insert(), and no unrealized or NULL state for either helper to consider: the probe is initialized alongside tb_jmp_cache and unrealize leaves it pointing at the poison (Richard). The poison is now a page-aligned allocation mapped read-only at startup rather than a writable .bss object (Richard); qemu_mprotect_ro() is added for it beside the existing _rw, _rwx and _none forms. That also settles v4's own note about a 1 MiB object that is never written.
9 Unchanged.
Testing
=======
alpha, loongarch64, mips, mipsel, mips64, ppc, ppc64 and s390x all build and run an indirect-dispatch exerciser (computed-goto back edges, function pointer calls, returns and a longjmp out of a SIGALRM handler) to completion under --enable-debug-tcg, so helper_goto_jc_check()'s assertions have actually been exercised on every migrated target rather than only on alpha. The gdbstub path (insert, hit, backtrace, delete, continue) and test-indirect-irq still pass, and the emulated compiler's output is still byte-identical.
What I would most like reviewed
===============================
- Patch 7 reverses a deliberate decision made in d3a2a1d803 on the strength of an argument about the user-only invalidation paths, plus a gate on whether gdb can ever attach.
- Patch 8's un-poison in the main loop races a concurrent poison from another thread. I believe the existing barrier around icount_decr.u16.high covers it, but my testing was single-threaded user mode.
- Patch 5's argument that a cflag is sufficient rests on the probe comparing cflags and on the residual window being one goto_tb chaining already accepts. Both seem clearly true to me, which is why they are worth a second reader.
- Patch 6 treats cpu flags, cflags and cs_base as translation-time constants in its guards, reads a jump cache entry without qatomic_read(), and leaves one_insn_per_tb and -d nochain toggles visible only at the next non-inline exit.
- Patch 9 only examines the immediately preceding op, refuses any access with a slow path (so user-only, and no alignment check), and leaves the i128 pairs alone. Richard asked whether the alignment test could stay on the base register when the displacement is itself aligned; it can, and the reason the fold is still refused there is the slow path handing addr_reg to the helper. Recording the displacement in TCGLabelQemuLdst and emitting one lea on the slow path would cover alignment-checked accesses too, at no fast path cost. Not attempted here.
- Patch 2's 1 MiB per CPUState is easy to justify for a single-threaded linux-user process and less obvious for system emulation with many vCPUs, or for a heavily threaded guest. It may want to be sized per target or made tunable rather than raised unconditionally.
Patches 6 and 9 are wired up for alpha and x86_64 respectively; everything else is target-independent, and no other backend changes behavior or needs touching.
v4: https://lore.kernel.org/qemu-devel/[email protected]/
v3: https://lore.kernel.org/qemu-devel/[email protected]/
v2: https://lore.kernel.org/qemu-devel/[email protected]/
Matt Turner (9):
accel/tcg: fold the dynamic cflags into CPUState::tcg_cflags accel/tcg: enlarge the TB jump cache to 64K entries accel/tcg: skip the can_do_io stores in user-only builds
tcg: add tcg_gen_goto_jc_{i32,i64,tl}()
accel/tcg: add CF_NO_GOTO_JC, set while a breakpoint is present
RFC: tcg: probe the TB jump cache inline instead of calling a helper
RFC: accel/tcg: allow cross-page goto_tb chaining in user-only builds
RFC: accel/tcg: poison the jump cache instead of polling for indirect
exits
RFC: tcg: fold a guest displacement into the host addressing mode
accel/stubs/meson.build | 1 + accel/stubs/tcg-stub.c | 16 + accel/tcg/cpu-exec-common.c | 44 ++- accel/tcg/cpu-exec.c | 121 +++++++ accel/tcg/internal-common.h | 20 +- accel/tcg/tb-jmp-cache.h | 2 +- accel/tcg/tcg-accel-ops.c | 2 + accel/tcg/tcg-runtime.h | 4 + accel/tcg/translator.c | 94 ++++- cpu-common.c | 7 + cpu-target.c | 3 + gdbstub/user.c | 14 + include/exec/translation-block.h | 1 + include/gdbstub/user.h | 11 + include/hw/core/cpu.h | 9 + include/qemu/mprotect.h | 1 + include/system/tcg.h | 12 + include/tcg/tcg-op-common.h | 21 ++ include/tcg/tcg-op.h | 2 + include/tcg/tcg-opc.h | 9 +- include/tcg/tcg.h | 2 + monitor/hmp-cmds.c | 5 + system/runstate-hmp-cmds.c | 4 + target/alpha/translate.c | 4 +- .../tcg/insn_trans/trans_branch.c.inc | 2 +- target/loongarch/tcg/translate.c | 4 +- target/mips/tcg/nanomips_translate.c.inc | 2 +- target/mips/tcg/translate.c | 6 +- target/ppc/translate.c | 4 +- target/s390x/tcg/translate.c | 4 +- tcg/tcg-op-ldst.c | 3 +- tcg/tcg-op.c | 182 +++++++++- tcg/tcg.c | 132 ++++++- tcg/x86_64/tcg-target.c.inc | 41 +++ tcg/x86_64/tcg-target.h | 3 + tests/tcg/multiarch/Makefile.target | 12 +- tests/tcg/multiarch/gdbstub/xpage-bp.py | 37 ++ tests/tcg/multiarch/test-indirect-irq.c | 62 ++++ tests/tcg/multiarch/test-xpage-chain.c | 336 ++++++++++++++++++ util/osdep.c | 9 + 40 files changed, 1216 insertions(+), 32 deletions(-) create mode 100644 accel/stubs/tcg-stub.c create mode 100644 tests/tcg/multiarch/gdbstub/xpage-bp.py create mode 100644 tests/tcg/multiarch/test-indirect-irq.c create mode 100644 tests/tcg/multiarch/test-xpage-chain.c
base-commit: eea8fe61b8be8f3016e522e6af24924a0266ca95
Signature · 1 line
2.54.0
PATCH v5 1/9 accel/tcg: fold the dynamic cflags into CPUState::tcg_cflags
curr_cflags() is called once per TB dispatch, from helper_lookup_tb_ptr() and from the cpu_exec() loop. It recomputes the same value every time:
uint32_t cflags = cpu->tcg_cflags;
if (unlikely(cpu_single_stepping(cpu))) { ... }
else if (qatomic_read(&one_insn_per_tb)) { ... }
else if (qemu_loglevel_mask(CPU_LOG_TB_NOCHAIN)) { ... }That is three loads and three branches on the hottest path in the interpreter, for state that changes only when gdb enables single-step, when one-insn-per-tb is toggled, or when the log mask changes.
None of the three has to be sampled at dispatch time. Fold each into CPUState::tcg_cflags where it changes and curr_cflags() becomes a single load of a field that TB lookup has to read anyway.
The derived bits -- CF_COUNT_MASK, CF_NO_GOTO_TB, CF_NO_GOTO_PTR and CF_SINGLE_STEP -- are never set by tcg_cflags_set(), so tcg_update_cflags() can recompute them in place without disturbing the rest, and conversely tcg_cflags_set() ORs in its bits without disturbing them.
There are three places to call it:
- tcg_exec_realizefn(), so that a CPU created after the command line has been parsed starts out with the right value. This covers user-only, where tcg_cpu_init_cflags() is not reached. linux-user's cpu_copy() copies tcg_cflags wholesale, so a cloned thread inherits it.
- cpu_single_step(), which changes one CPU. gdb is the only caller that matters; in system mode it runs with the vCPUs stopped, and in user mode gdb_continue_partial() can reach a thread that is still running, because gdb_handlesig() stops only the thread that trapped. That is exactly the plain cross-thread store to another CPU's CPUState that cpu->singlestep_flags already was, read back by that CPU through cpu_single_stepping() in curr_cflags(). This patch changes which field carries it, not who writes it or how.
- hmp_one_insn_per_tb() and hmp_log(), which change every CPU while the vCPUs are running, so the update is queued with async_run_on_cpu() and each CPU writes its own cflags from its own thread. The command line spellings of those two settings need nothing: they are parsed before any CPU is realized, so tcg_exec_realizefn() picks them up.
Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host, in a build configured with --enable-lto:
before: 1,646,994,254,249 instructions
after: 1,562,204,796,597 instructions -5.15%That workload issues 8.4 billion dispatches, so the per-call saving is small but the aggregate is not. The emulated compiler produces byte-identical output before and after.
Wall clock does not move: 133.19s to 132.58s, a 0.46% difference against a run-to-run spread larger than that. The removed work is a few predictable loads and branches that the host executes largely in parallel with the surrounding dispatch, so this patch is worth taking for the instruction count and for what it enables, not for a time saving that can be measured on its own.
v4: Update the cflags from the HMP handlers for 'log' and 'one-insn-per-tb'
rather than from qemu_set_log_internal() and the accelerator property setter. Those are the paths that reach a running vCPU, and the monitor is the only thing that does. Suggested by Richard Henderson.
v4: Queue the per-CPU update with async_run_on_cpu() rather than
async_safe_run_on_cpu(). Halting the other vCPUs buys nothing: the queued work already runs on the owning CPU's own thread. Suggested by Alex Bennee, who also asked whether there are cross-vCPU updates of tcg_cflags at all. With this change the monitor path has none: the only remaining writer from another thread is cpu_single_step(), above, which is neither new nor made worse here.
v4: Move the stub to accel/stubs/, which is where the other accelerator
stubs live.
--- accel/stubs/meson.build | 1 + accel/stubs/tcg-stub.c | 16 ++++++++++++++++ accel/tcg/cpu-exec-common.c | 33 ++++++++++++++++++++++++++++++--- accel/tcg/cpu-exec.c | 3 +++ accel/tcg/internal-common.h | 11 +++++++++-- cpu-target.c | 3 +++ include/system/tcg.h | 12 ++++++++++++ monitor/hmp-cmds.c | 5 +++++ system/runstate-hmp-cmds.c | 4 ++++ 9 files changed, 83 insertions(+), 5 deletions(-) create mode 100644 accel/stubs/tcg-stub.c
accel/stubs/meson.build +1 -0
@@ -4,6 +4,7 @@ stub_ss.add(files( 'nitro-stub.c', 'mshv-stub.c', 'nvmm-stub.c', + 'tcg-stub.c', 'whpx-stub.c', 'xen-stub.c', ))
accel/stubs/tcg-stub.c new file +16 -0
@@ -0,0 +1,16 @@ +/* +* Stubs for the TCG entry points in system/tcg.h, for binaries that link +* cpu-target.c or the HMP command handlers but not TCG. +* +* SPDX-License-Identifier: GPL-2.0-or-later +*/ +#include "qemu/osdep.h" +#include "system/tcg.h" + +void tcg_update_cflags (CPUState *cpu) +{ +} + +void tcg_update_all_cflags (void ) +{ +}
accel/tcg/cpu-exec-common.c +30 -3
@@ -36,9 +36,16 @@ void tcg_cflags_set(CPUState *cpu, uint32_t flags) cpu->tcg_cflags |= flags; } -uint32_t curr_cflags (CPUState *cpu) +/* +* The bits of CPUState::tcg_cflags that tcg_cflags_set() never sets, because +* they are derived from gdb single-step, one-insn-per-tb and -d nochain. +*/ +#define CF_DERIVED (CF_COUNT_MASK | CF_NO_GOTO_TB | CF_NO_GOTO_PTR | \ + CF_SINGLE_STEP) + +void tcg_update_cflags (CPUState *cpu) { -uint32_t cflags = cpu->tcg_cflags; +uint32_t cflags = cpu->tcg_cflags & ~CF_DERIVED ;/* * Record gdb single-step. We should be exiting the TB by raising
@@ -55,7 +62,27 @@ uint32_t curr_cflags(CPUState *cpu) cflags |=CF_NO_GOTO_TB ; } -return cflags; + cpu->tcg_cflags = cflags; +} + +static void tcg_update_cflags_work (CPUState *cpu,run_on_cpu_data data) +{ +tcg_update_cflags (cpu); +} + +void tcg_update_all_cflags (void ) +{ +CPUState *cpu; + +/* +* one-insn-per-tb and -d nochain can both be changed from the monitor +* while the vCPUs are running. Queue the update onto each CPU rather +* than writing tcg_cflags from here, so that the field is only ever +* written by the CPU that owns it. +*/ +CPU_FOREACH (cpu) { +async_run_on_cpu (cpu, tcg_update_cflags_work,RUN_ON_CPU_NULL ); + } }/* exit the current TB, but without causing any exception to be raised */
accel/tcg/cpu-exec.c +3 -0
@@ -1068,6 +1068,9 @@ bool tcg_exec_realizefn(CPUState *cpu, Error **errp) tcg_target_initialized = true; } +/* Pick up one-insn-per-tb and -d nochain from the command line. */ +tcg_update_cflags (cpu); + cpu->tb_jmp_cache =g_new0 (CPUJumpCache,1 );tlb_init (cpu);#ifndef CONFIG_USER_ONLY
accel/tcg/internal-common.h +9 -2
@@ -69,8 +69,15 @@ void tlb_destroy(CPUState *cpu);bool tcg_exec_realizefn (CPUState *cpu,Error **errp);void tcg_exec_unrealizefn (CPUState *cpu); -/* current cflags for hashing/comparison */ -uint32_t curr_cflags (CPUState *cpu); +/* +* Current cflags for hashing/comparison. Everything that feeds into the +* value is folded into CPUState::tcg_cflags when it changes, by +* tcg_update_cflags(), so that TB dispatch only has to load it. +*/ +static inline uint32_t curr_cflags (CPUState *cpu) +{ +return cpu->tcg_cflags; +}void tb_check_watchpoint (CPUState *cpu,uintptr_t retaddr);
cpu-target.c +3 -0
@@ -24,6 +24,7 @@#include "exec/replay-core.h" #include "exec/log.h" #include "hw/core/cpu.h" +#include "system/tcg.h" #include "trace/trace-root.h" /* enable or disable single step mode. EXCP_DEBUG is returned by the
@@ -35,6 +36,8 @@ void cpu_single_step(CPUState *cpu, unsigned flags) cpu->singlestep_flags, flags); cpu->singlestep_flags = flags; +tcg_update_cflags (cpu); +#if !defined(CONFIG_USER_ONLY )const AccelOpsClass *ops =cpus_get_accel ();if (ops->update_guest_debug) {
include/system/tcg.h +12 -0
@@ -17,6 +17,18 @@ extern bool tcg_allowed;#define tcg_enabled () 0#endif +/* +* Recompute the parts of CPUState::tcg_cflags that TB dispatch consumes but +* tcg_cflags_set() does not provide: gdb single-step, one-insn-per-tb and +* the CPU_LOG_TB_NOCHAIN log flag. Call whenever one of those changes. +* +* tcg_update_cflags() updates one CPU and must be called from that CPU's +* thread, or with it stopped. tcg_update_all_cflags() updates every CPU +* and is safe to call from the monitor while the vCPUs run. +*/ +void tcg_update_cflags (CPUState *cpu); +void tcg_update_all_cflags (void ); +/** * qemu_tcg_mttcg_enabled: * Check whether we are running MultiThread TCG or not.
monitor/hmp-cmds.c +5 -0
@@ -39,6 +39,7 @@#include "system/hw_accel.h" #include "system/memory.h" #include "system/system.h" +#include "system/tcg.h" #include "disas/disas.h" /* Please update hmp-commands.hx when adding or changing commands */
@@ -335,7 +336,11 @@ void hmp_log(Monitor *mon, const QDict *qdict)if (!qemu_set_log (mask, &err)) {error_report_err (err); +return ; } + +/* CPU_LOG_TB_NOCHAIN feeds into the per-CPU cflags. */ +tcg_update_all_cflags (); }void hmp_gdbserver (Monitor *mon,const QDict *qdict)
system/runstate-hmp-cmds.c +4 -0
@@ -22,6 +22,7 @@#include "qapi/qapi-commands-run-state.h" #include "qobject/qdict.h" #include "qemu/accel.h" +#include "system/tcg.h" void hmp_info_status (Monitor *mon,const QDict *qdict) {
@@ -64,6 +65,9 @@ void hmp_one_insn_per_tb(Monitor *mon, const QDict *qdict)/* If the property exists then setting it can never fail */ object_property_set_bool (OBJECT (accel),"one-insn-per-tb" , newval, &error_abort); + +/* one-insn-per-tb feeds into the per-CPU cflags. */ +tcg_update_all_cflags (); }void hmp_watchdog_action (Monitor *mon,const QDict *qdict)
Signature · 1 line
2.54.0
PATCH v5 2/9 accel/tcg: enlarge the TB jump cache to 64K entries
In reply to Matt TurnerThe per-CPU TB jump cache has held 4096 entries since it was introduced. That is too small for guests running large programs: an emulated compiler misses often enough that the fallback qht lookup shows up prominently in a profile.
Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host. The compile performs 34.2 billion TB executions, of which 8.4 billion take the indirect dispatch path.
Sizing curve, on top of the preceding patch, instructions retired and wall clock:
12 bits ( 64 KiB): 1,562,204,796,597 132.58s
14 bits ( 256 KiB): 1,493,318,515,396 -4.41% 124.67s -5.97%
16 bits ( 1 MiB): 1,469,772,951,575 -5.92% 121.04s -8.71%
18 bits ( 4 MiB): 1,462,309,832,762 -6.39% 119.82s -9.62%16 bits is the knee. 18 buys another 0.47% of instructions for four times the memory. It does show a further 1.01% of wall clock, which is outside the 0.70% run-to-run spread at 16 bits, so the effect is probably real -- but paying four times the memory for it is a poor trade, and instructions retired does not account for the data cache pressure of a 4 MiB table.
In a perf profile the mechanism is visible directly: tb_htable_lookup(), which is where qht_lookup_custom() lands once it is inlined in an LTO build, falls from 6.10% of samples to 1.66%.
The cost is memory: the cache grows from 64 KiB to 1 MiB, once per CPUState. In linux-user that is per guest thread rather than per process, so a threaded guest pays it as many times as it has threads, exactly as system emulation pays it per vCPU. The allocation is g_new0(), so the pages are faulted in as the cache is touched and a thread that runs a small amount of code touches a small part of it, but the address space is committed either way.
So this may still want to be tunable, or scaled from the number of CPUs, rather than raised unconditionally. I do not have a threaded workload where the smaller cache is the better trade, and would welcome one.
v4: Fix the claim that a linux-user process is a single vCPU. The cache is
per CPUState, and linux-user creates one per guest thread. Pointed out by Richard Henderson.
--- accel/tcg/tb-jmp-cache.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
accel/tcg/tb-jmp-cache.h +1 -1
@@ -12,7 +12,7 @@#include "qemu/rcu.h" #include "exec/cpu-common.h" -#define TB_JMP_CACHE_BITS 12 +#define TB_JMP_CACHE_BITS 16#define TB_JMP_CACHE_SIZE (1 << TB_JMP_CACHE_BITS)/*
Signature · 1 line
2.54.0
PATCH v5 3/9 accel/tcg: skip the can_do_io stores in user-only builds
In reply to Matt TurnerEvery translation block stores to cpu->neg.can_do_io twice: false before the first instruction, true before the last one. Nothing reads it in a user-only build. There is no memory-mapped I/O in linux-user, and every reader is in system_ss: cputlb.c, watchpoint.c, icount-common.c and tcg-accel-ops-icount.c.
Two stores per TB is not much on its own, but TBs are short. An emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) executes 34.2 billion TBs at 6.04 guest instructions each, so this is 68 billion stores for nothing.
Measured on an x86-64 host, LTO build, on top of the preceding two patches:
before: 1,469,772,951,575 instructions
after: 1,402,667,803,616 instructions -4.57%
before: 121.04s wall clock
after: 115.56s wall clock -4.53%The emulated compiler produces byte-identical output.
v3: Use #ifndef CONFIG_USER_ONLY again rather than
if (IS_ENABLED(CONFIG_USER_ONLY)). QEMU's IS_ENABLED() is IS_EMPTY(), which is only true for a symbol Meson defines empty; CONFIG_USER_ONLY is defined as 1, so the test was always false and v2 emitted the two stores after all. The measurements above are from the working form.
--- accel/tcg/translator.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
accel/tcg/translator.c +10 -0
@@ -21,12 +21,14 @@#include "disas/disas.h" #include "tb-internal.h" +#ifndef CONFIG_USER_ONLY static void set_can_do_io (DisasContextBase *db,bool val) {QEMU_BUILD_BUG_ON (sizeof_field (CPUState, neg.can_do_io) !=1 );tcg_gen_st8_i32 (tcg_constant_i32 (val), tcg_env, offsetof(CPUState, neg.can_do_io) - sizeof(CPUState)); } +#endif bool translator_io_start (DisasContextBase *db) {
@@ -210,17 +212,25 @@ void translator_loop(CPUState *cpu, TranslationBlock *tb, int *max_insns,/* * Manage can_do_io for the translation block: set to false before * the first insn and set to true before the last insn. +* +* Nothing reads can_do_io in user-only builds. There is no MMIO +* there, and every reader (cputlb.c, watchpoint.c, icount) is in +* system_ss, so skip the two stores per TB entirely. */ if (db->num_insns ==1 ) {tcg_debug_assert (first_insn_start == db->insn_start); }else {tcg_debug_assert (first_insn_start != db->insn_start); +#ifndef CONFIG_USER_ONLY tcg_ctx->emit_before_op = first_insn_start;set_can_do_io (db, false); +#endif } +#ifndef CONFIG_USER_ONLY tcg_ctx->emit_before_op = db->insn_start;set_can_do_io (db, true); tcg_ctx->emit_before_op =NULL ; +#endif /* May be used by disas_log or plugin callbacks. */ tb->size = db->pc_next - db->pc_first;
Signature · 1 line
2.54.0
Re: [PATCH v5 3/9] accel/tcg: skip the can_do_io stores in user-only builds
Quoted 28 lines · Matt Turner
Every translation block stores to
cpu->neg.can_do_iotwice: false before the first instruction, true before the last one. Nothing reads it in a user-only build. There is no memory-mapped I/O in linux-user, and every reader is insystem_ss:cputlb.c,watchpoint.c,icount-common.candtcg-accel-ops-icount.c.Two stores per TB is not much on its own, but TBs are short. An emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) executes 34.2 billion TBs at 6.04 guest instructions each, so this is 68 billion stores for nothing.
Measured on an x86-64 host, LTO build, on top of the preceding two patches:
before: 1,469,772,951,575 instructions after: 1,402,667,803,616 instructions -4.57% before: 121.04s wall clock after: 115.56s wall clock -4.53%The emulated compiler produces byte-identical output.
v3: Use #ifndef
CONFIG_USER_ONLYagain rather than
if (IS_ENABLED(CONFIG_USER_ONLY)). QEMU'sIS_ENABLED()isIS_EMPTY(), which is only true for a symbol Meson defines empty;CONFIG_USER_ONLYis defined as 1, so the test was always false and v2 emitted the two stores after all. The measurements above are from the working form.
Quoted 6 lines
Reviewed-by Richard Henderson<[email protected]>Reviewed-by Philippe Mathieu-Daudé<[email protected]>Signed-off-by Matt Turner<[email protected]>--- accel/tcg/translator.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
Cherry-picked this to tcg-next.
r~
PATCH v5 4/9 tcg: add tcg_gen_goto_jc_{i32,i64,tl}()
In reply to Matt Turnertcg_gen_lookup_and_goto_ptr() takes no arguments and emits a call to helper_lookup_tb_ptr(), which recovers the destination PC from env by calling back into the target through TCGCPUOps::get_tb_cpu_state(). At translation time the caller often already has the destination PC in a temp, and knows the flags, cflags and cs_base any destination it may reach has to match, because they are the ones the block being generated was translated with. A later patch uses that to look the destination up inline.
But it is not something every caller of tcg_gen_lookup_and_goto_ptr() can promise, and the promise is subtle. target/arm has
case DISAS_UPDATE_NOCHAIN:
gen_update_pc(dc, curr_insn_len(dc));
/* fall through */
case DISAS_JUMP:
gen_goto_ptr();
break;where DISAS_JUMP could make the promise and DISAS_UPDATE_NOCHAIN could not, because it is there precisely because the state changed. Two call sites, one line apart, on opposite sides of the contract.
So add a second entry point rather than growing an argument on the first. tcg_gen_lookup_and_goto_ptr() keeps today's meaning and today's signature:
dispatch, and let the helper work out where. tcg_gen_goto_jc_*() means dispatch to the destination that env already describes, and takes the pc as proof that the caller knows which one that is. Targets migrate one call site at a time, and a call site that cannot promise simply does not move.
The contract is:
- @pc holds exactly what get_tb_cpu_state() reports as the destination pc.
- The flags and cs_base it reports are the ones this block was translated with, which is what lets them be constants in the generated code.
--enable-debug-tcg checks all three against get_tb_cpu_state() at run time, via a new helper_goto_jc_check(). That turns a mistake into an assertion at the offending call site instead of a block that runs with someone else's flags.
Five targets have a call site whose pc temp is that key by construction, and are migrated here: alpha, loongarch, mips, ppc and s390x. Nothing else changes; the generated code does not change either, since goto_jc still emits the same helper call for now.
For six targets the TB pc is derived and passing the pc temp would be wrong:
avr's TB pc is the word address doubled, i386's is eip before segmentation, riscv masks it to 32 bits when xl is MXL_RV32, hppa derives it from the IAQ, hexagon adjusts it inside a hardware loop, and sparc puts npc in cs_base. The remaining seven -- arm, m68k, microblaze, or1k, rx, sh4 and tricore -- have call sites that look like they could move, but I have not convinced myself of the contract for them and have nothing to test them with. Each is a one-line change for whoever wants it, and debug-tcg will say if it is wrong.
The i32 and i64 forms are separate functions, with a _tl alias in tcg-op.h, as for most everything else. A translator built for more than one value of TARGET_LONG_BITS cannot include tcg-op.h and calls the sized form directly, which is what s390x does here.
Neither form takes the TranslationBlock: tcg_ctx->gen_tb is the block being generated, the same one tcg_gen_goto_tb() and tcg_gen_lookup_and_goto_ptr() already read, so there is no way for a caller to pass the wrong one.
v4: Split out of "tcg: probe the TB jump cache inline instead of calling a
helper", which did the API change and the inline probe in one patch. Requested by Richard Henderson.
v5: Add a new interface rather than growing an argument on
tcg_gen_lookup_and_goto_ptr(), and check the contract under --enable-debug-tcg. Requested by Richard Henderson, who named it tcg_gen_goto_jc_*(); the DISAS_UPDATE_NOCHAIN example above is his.
v5: Define _i32 and _i64 entry points with a _tl alias in tcg-op.h, rather
than one entry point taking a TCGTemp. Requested by Richard Henderson:
as targets migrate to single-binary, code is built once and stops relying on TARGET_LONG_BITS, so the TCGTemp split was the wrong shape.
--- accel/tcg/cpu-exec.c | 27 +++++++++ accel/tcg/tcg-runtime.h | 4 ++ include/tcg/tcg-op-common.h | 20 +++++++ include/tcg/tcg-op.h | 2 + target/alpha/translate.c | 4 +- .../tcg/insn_trans/trans_branch.c.inc | 2 +- target/loongarch/tcg/translate.c | 4 +- target/mips/tcg/nanomips_translate.c.inc | 2 +- target/mips/tcg/translate.c | 6 +- target/ppc/translate.c | 4 +- target/s390x/tcg/translate.c | 4 +- tcg/tcg-op.c | 59 +++++++++++++++++-- 12 files changed, 119 insertions(+), 19 deletions(-)
accel/tcg/cpu-exec.c +27 -0
@@ -407,6 +407,33 @@ const void *HELPER(lookup_tb_ptr)(CPUArchState *env)return tb->tc.ptr; } +#ifdef CONFIG_DEBUG_TCG +/** +* helper_goto_jc_check: check the contract of tcg_gen_goto_jc_*() +* @env: current cpu state +* @pc: the destination pc the caller passed at translation time +* @flags: the flags the dispatching block was translated with +* @cs_base: the cs_base the dispatching block was translated with +* +* A goto_jc looks the destination up on the caller's @pc with the flags and +* cs_base of the block doing the dispatching, so all three have to be what +* get_tb_cpu_state() reports by the time the dispatch runs. That is a +* property of the translator, not of the generated code, so check it here +* rather than leaving a target that gets it wrong to be debugged as a block +* running with someone else's flags. +*/ +void HELPER (goto_jc_check )(CPUArchState *env,uint64_t pc,uint64_t flags, +uint64_t cs_base) +{ +CPUState *cpu =env_cpu (env); +TCGTBCPUState s = cpu->cc->tcg_ops->get_tb_cpu_state (cpu); + +assert (s.pc == pc); +assert (s.flags == flags); +assert (s.cs_base == cs_base); +} +#endif +/* Return the current PC from CPU, which may be cached in TB. */ static vaddr log_pc (CPUState *cpu,const TranslationBlock *tb) {
accel/tcg/tcg-runtime.h +4 -0
@@ -22,6 +22,10 @@ DEF_HELPER_FLAGS_1(ctpop_i64, TCG_CALL_NO_RWG_SE, i64, i64) DEF_HELPER_FLAGS_1(lookup_tb_ptr, TCG_CALL_NO_WG_SE, cptr, env) +#ifdef CONFIG_DEBUG_TCG +DEF_HELPER_FLAGS_4(goto_jc_check, TCG_CALL_NO_WG_SE, void, env, i64, i64, i64) +#endif + DEF_HELPER_FLAGS_1(exit_atomic, TCG_CALL_NO_WG, noreturn, env)#ifndef IN_HELPER_PROTO
include/tcg/tcg-op-common.h +20 -0
@@ -85,6 +85,26 @@ void tcg_gen_goto_tb(unsigned idx);*/ void tcg_gen_lookup_and_goto_ptr (void ); +/** +* tcg_gen_goto_jc_i32() - dispatch to the destination TB via the jump cache +* tcg_gen_goto_jc_i64() - dispatch to the destination TB via the jump cache +* @pc: temp holding the destination guest PC +* +* As tcg_gen_lookup_and_goto_ptr(), but the caller states where the +* dispatch is going, which allows the lookup to be done inline. +* +* The contract is that when this runs, the CPU state must already be +* exactly the destination's: @pc must hold what get_tb_cpu_state() would +* report as the destination pc, and the flags and cs_base it would report +* must be the ones the block being generated was translated with. A +* translator that has not finished updating the state, or whose pc is +* derived rather than being the lookup key -- avr's word address, i386's +* eip before segmentation -- must use tcg_gen_lookup_and_goto_ptr() +* instead. --enable-debug-tcg checks the contract at runtime. +*/ +void tcg_gen_goto_jc_i32 (TCGv_i32 pc); +void tcg_gen_goto_jc_i64 (TCGv_i64 pc); +void tcg_gen_plugin_cb (unsigned from);void tcg_gen_plugin_mem_cb (TCGv_i64 addr,unsigned meminfo);
include/tcg/tcg-op.h +2 -0
@@ -38,6 +38,7 @@ typedef TCGv_i32 TCGv;#define tcgv_tl_temp tcgv_i32_temp#define tcg_gen_qemu_ld_tl tcg_gen_qemu_ld_i32#define tcg_gen_qemu_st_tl tcg_gen_qemu_st_i32 +#define tcg_gen_goto_jc_tl tcg_gen_goto_jc_i32#elif TARGET_LONG_BITS ==64 typedef TCGv_i64 TCGv ;#define tcg_temp_new () tcg_temp_new_i64()
@@ -45,6 +46,7 @@ typedef TCGv_i64 TCGv;#define tcgv_tl_temp tcgv_i64_temp#define tcg_gen_qemu_ld_tl tcg_gen_qemu_ld_i64#define tcg_gen_qemu_st_tl tcg_gen_qemu_st_i64 +#define tcg_gen_goto_jc_tl tcg_gen_goto_jc_i64#else #error Unhandled TARGET_LONG_BITS value#endif
target/alpha/translate.c +2 -2
@@ -449,7 +449,7 @@ static void gen_goto_tb(DisasContext *ctx, unsigned tb_slot_idx, int32_t disp)tcg_gen_exit_tb (ctx->base.tb, tb_slot_idx); }else {gen_pc_disp (ctx, cpu_pc, disp); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_goto_jc_tl (cpu_pc); } }
@@ -2917,7 +2917,7 @@ static void alpha_tr_tb_stop(DisasContextBase *dcbase, CPUState *cpu)gen_pc_disp (ctx, cpu_pc,0 );/* FALLTHRU */ case DISAS_PC_UPDATED : -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_goto_jc_tl (cpu_pc);break ;case DISAS_PC_UPDATED_NOCHAIN :tcg_gen_exit_tb (NULL ,0 );
target/loongarch/tcg/insn_trans/trans_branch.c.inc +1 -1
@@ -27,7 +27,7 @@ static bool trans_jirl(DisasContext *ctx, arg_jirl *a) tcg_gen_mov_tl(cpu_pc, addr); tcg_gen_movi_tl(dest, make_address_pc(ctx, ctx->base.pc_next + 4)); gen_set_gpr(a->rd, dest, EXT_NONE); - tcg_gen_lookup_and_goto_ptr(); + tcg_gen_goto_jc_tl(cpu_pc); ctx->base.is_jmp = DISAS_NORETURN; return true; }
target/loongarch/tcg/translate.c +2 -2
@@ -111,7 +111,7 @@ static void gen_goto_tb(DisasContext *ctx, unsigned tb_slot_idx, vaddr dest)tcg_gen_exit_tb (ctx->base.tb, tb_slot_idx); }else {tcg_gen_movi_tl (cpu_pc, dest); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_goto_jc_tl (cpu_pc); } }
@@ -311,7 +311,7 @@ static void loongarch_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)switch (ctx->base.is_jmp) {case DISAS_STOP :tcg_gen_movi_tl (cpu_pc, ctx->base.pc_next); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_goto_jc_tl (cpu_pc);break ;case DISAS_TOO_MANY :gen_goto_tb (ctx,0 , ctx->base.pc_next);
target/mips/tcg/nanomips_translate.c.inc +1 -1
@@ -2406,7 +2406,7 @@ static void gen_compute_nanomips_pbalrsc_branch(DisasContext *ctx, int rs, /* unconditional branch to register */ tcg_gen_mov_tl(cpu_PC, btarget); - tcg_gen_lookup_and_goto_ptr(); + tcg_gen_goto_jc_tl(cpu_PC); } /* nanoMIPS Branches */
target/mips/tcg/translate.c +3 -3
@@ -4374,7 +4374,7 @@ static void gen_goto_tb(DisasContext *ctx, unsigned tb_slot_idx,tcg_gen_exit_tb (ctx->base.tb, tb_slot_idx); }else {gen_save_pc (dest); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_goto_jc_tl (cpu_PC); } }
@@ -11014,7 +11014,7 @@ static void gen_branch(DisasContext *ctx, int insn_bytes) }else {tcg_gen_mov_tl (cpu_PC, btarget); } -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_goto_jc_tl (cpu_PC);break ;default :LOG_DISAS ("unknown branch 0x%x\n" , proc_hflags);
@@ -15244,7 +15244,7 @@ static void mips_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)switch (ctx->base.is_jmp) {case DISAS_STOP :gen_save_pc (ctx->base.pc_next); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_goto_jc_tl (cpu_PC);break ;case DISAS_NEXT :case DISAS_TOO_MANY :
target/ppc/translate.c +2 -2
@@ -3664,7 +3664,7 @@ static void gen_lookup_and_goto_ptr(DisasContext *ctx)pmu_count_insns (ctx); } -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_goto_jc_tl (cpu_nip); } }
@@ -6690,7 +6690,7 @@ static void ppc_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)pmu_count_insns (ctx); } -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_goto_jc_tl (cpu_nip);break ;case DISAS_EXIT_UPDATE :
target/s390x/tcg/translate.c +2 -2
@@ -1162,7 +1162,7 @@ static DisasJumpType help_branch(DisasContext *s, DisasCompare *c,tcg_gen_goto_tb (0 );tcg_gen_exit_tb (s->base.tb,0 ); }else { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_goto_jc_i64 (psw_addr); }gen_set_label (lab);
@@ -6477,7 +6477,7 @@ static void s390x_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)if (dc->exit_to_mainloop) {tcg_gen_exit_tb (NULL ,0 ); }else { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_goto_jc_i64 (psw_addr); }break ;default :
tcg/tcg-op.c +53 -6
71 lines not on this page · raw message
Signature · 1 line
2.54.0
PATCH v5 5/9 accel/tcg: add CF_NO_GOTO_JC, set while a breakpoint is present
In reply to Matt TurnerThe next patch dispatches a goto_jc by probing the TB jump cache from generated code. That probe cannot check everything helper_lookup_tb_ptr() checks, and the one that matters is breakpoints: check_for_breakpoints() raises EXCP_DEBUG on an exact pc match and selects CF_BP_PAGE cflags for the rest of the page, and inserting a breakpoint deliberately invalidates no TB.
The probe does compare the destination's cflags against the cflags of the block doing the dispatching, and only takes the destination when they are equal. So a cflag is all that is needed. Add CF_NO_GOTO_JC, set it in CPUState::tcg_cflags while cpu->breakpoints is non-empty, and blocks translated from then on both decline to dispatch inline themselves -- the next patch makes them emit the plain helper call -- and are unreachable from blocks that do, because their cflags no longer match.
The two ends of the flag are cpu_breakpoint_insert() and cpu_breakpoint_remove_by_ref(), which are the only places the list changes. Both already run either on the CPU's own thread or with it stopped, or reach another CPU exactly as cpu_single_step() does, which is where the previous patch put the same kind of update.
That leaves blocks translated before the breakpoint was inserted, which are still live and still chain to each other. They do so on the old cflags, so inline dispatch among them keeps working until the vCPU reaches its main loop, which then looks up with the new cflags and translates afresh. In system mode gdb inserts breakpoints with the vCPUs stopped, so there is no window at all. In user mode the window is the one goto_tb chaining already
has: a chained direct jump consults nothing either, and is not broken by inserting a breakpoint.
Nothing reads CF_NO_GOTO_JC yet; the next patch does.
v5: New patch, replacing "accel/tcg: give the TB jump cache a second base
pointer for generated code", which forced the same fallback by pointing generated code at a zero-filled jump cache when a breakpoint was inserted, and needed a cross-thread poison and an un-poison race to do it. Richard Henderson suggested a cflag instead, and pointed out that the previous patch had already shown how to update tcg_cflags from gdbstub. The base pointer comes back later in the series, for pending exits, which a cflag cannot express.
--- accel/tcg/cpu-exec-common.c | 13 ++++++++++++- cpu-common.c | 7 +++++++ include/exec/translation-block.h | 1 + 3 files changed, 20 insertions(+), 1 deletion(-)
accel/tcg/cpu-exec-common.c +12 -1
@@ -41,7 +41,7 @@ void tcg_cflags_set(CPUState *cpu, uint32_t flags)* they are derived from gdb single-step, one-insn-per-tb and -d nochain. */ #define CF_DERIVED (CF_COUNT_MASK | CF_NO_GOTO_TB | CF_NO_GOTO_PTR | \ - CF_SINGLE_STEP) + CF_SINGLE_STEP | CF_NO_GOTO_JC)void tcg_update_cflags (CPUState *cpu) {
@@ -62,6 +62,17 @@ void tcg_update_cflags(CPUState *cpu) cflags |=CF_NO_GOTO_TB ; } +/* +* A block that dispatches through the jump cache inline does not consult +* cpu->breakpoints, and inserting a breakpoint deliberately invalidates +* nothing. Give blocks translated while one is set a distinct cflags, so +* that they neither dispatch inline themselves nor are reached by a block +* that does, and check_for_breakpoints() gets to run on every dispatch. +*/ +if (unlikely (!QTAILQ_EMPTY (&cpu->breakpoints))) { + cflags |=CF_NO_GOTO_JC ; + } + cpu->tcg_cflags = cflags; }
cpu-common.c +7 -0
@@ -22,6 +22,7 @@#include "exec/cpu-common.h" #include "hw/core/cpu.h" #include "qemu/lockable.h" +#include "system/tcg.h" #include "trace/trace-root.h" QemuMutex qemu_cpu_list_lock;
@@ -429,6 +430,9 @@ int cpu_breakpoint_insert(CPUState *cpu, vaddr pc, int flags, *breakpoint = bp; } +/* The first breakpoint takes the CPU off the inline dispatch path. */ +tcg_update_cflags (cpu); +trace_breakpoint_insert (cpu->cpu_index, pc, flags);return 0 ; }
@@ -456,6 +460,9 @@ void cpu_breakpoint_remove_by_ref(CPUState *cpu, CPUBreakpoint *bp) {QTAILQ_REMOVE (&cpu->breakpoints, bp, entry); +/* The last breakpoint puts the CPU back on it. */ +tcg_update_cflags (cpu); +trace_breakpoint_remove (cpu->cpu_index, bp->pc, bp->flags);g_free (bp); }
include/exec/translation-block.h +1 -0
@@ -84,6 +84,7 @@ struct TranslationBlock {#define CF_NOIRQ 0x00010000/* Generate an uninterruptible TB */ #define CF_PCREL 0x00020000/* Opcodes in TB are PC-relative */ #define CF_BP_PAGE 0x00040000/* Breakpoint present in code page */ +#define CF_NO_GOTO_JC 0x00080000/* Do not dispatch via the inline probe */ #define CF_CLUSTER_MASK 0xff000000/* Top 8 bits are cluster ID */ #define CF_CLUSTER_SHIFT 24
Signature · 1 line
2.54.0
PATCH v5 6/9 RFC: tcg: probe the TB jump cache inline instead of calling a helper
In reply to Matt TurnerEvery indirect branch that cannot use goto_tb ends in a dispatch that calls helper_lookup_tb_ptr(). For an emulated compiler that is 8.4 billion helper calls in a single translation unit: 24.6% of all TB exits take this path, because jsr/ret/jmp have a register destination and because goto_tb is restricted to same-page targets.
The helper itself is already tight, but each call pays for a call frame, the can_do_io store, the get_tb_cpu_state() indirect call through TCGCPUOps, curr_cflags(), and a breakpoint check, before it gets to the jump cache probe that almost always hits (95.8% for this workload).
Emit the probe inline instead, for the callers that have migrated to tcg_gen_goto_jc_*(). Those supply what it needs: the destination PC is in a TCG temp, and the flags, cflags and cs_base the destination must match are constants at translation time. The fast path is therefore a hash, four guarded loads and a goto_ptr. Only a miss calls the helper, which still owns filling the cache.
Two details matter for the generated code. The flags and cflags guards are folded into a single aligned 64-bit load and compare, since the fields are adjacent. And each path emits its own goto_ptr rather than branching to a shared one: a temp live across the label is spilled and reloaded on every dispatch, which cost 6.3% on its own.
The flags and cflags constants are safe against the other things that can change them. CF_PARALLEL is only ever set by begin_parallel_context(), which flushes first, so no block predating it survives to dispatch. gdb single-step is only turned on with the CPU stopped, and a block translated without CF_SINGLE_STEP can only be re-entered through tb_lookup(), which from then on demands the new cflags -- so a stale-cflags block is never the one running. Breakpoints are handled by CF_NO_GOTO_JC, added by the previous
patch: while one is set, blocks are translated with a cflags that both keeps them off the inline path and keeps them unreachable from blocks already on it. What is left is one_insn_per_tb and -d nochain; see below.
Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host, LTO build, on top of the preceding patches:
before: 1,402,667,803,616 instructions
after: 916,415,123,244 instructions -34.67%
before: 115.56s wall clock
after: 85.59s wall clock -25.94%The gap between the two is the point at which this stops being a straight-line win: the helper call was highly predictable work that the host pipelined well, so removing it retires far fewer instructions than it saves time. IPC falls from 2.48 to 2.17 across this patch for that reason.
Despite emitting more code, this also reduces instruction cache pressure, because a dispatch no longer jumps into qemu's .text and evicts translated code:
before: 11,735,141,703 L1-icache-load-misses
after: 7,154,863,292 L1-icache-load-misses -39.0%The mechanism is visible directly in a profile: helper_lookup_tb_ptr() falls from 31.01% of samples to 0.35%, and qemu's own .text falls from 38.8% to 5.3%, with the balance moving into generated code.
Combined with the preceding patches, against an unmodified LTO build, 1,646,994,254,249 instructions fall to 916,415,123,244, or -44.36%. The emulated compiler produces byte-identical output throughout.
A follow-up worth having: the probe is emitted entirely out of generic TCG ops, and several backends can do much better than the result. x86_64 and s390x have memory-operand comparisons; aarch64 can form env + off + h * 16 with a shift-add, load (tb, pc) and (cs_base, flags) with two ldp, and halve the branches with ccmp. That wants a backend expansion of a dedicated opcode, which is a separate series.
Open issues, hence RFC:
- one_insn_per_tb and CPU_LOG_TB_NOCHAIN can be toggled from the monitor while a vCPU is inside a block that was translated without them. The block keeps dispatching inline on the old cflags until it exits for some other reason. This is the same window goto_tb chaining already has, since a chained direct jump consults nothing either, but it is worth saying out loud.
- The jump cache entry is read without qatomic_read(); entries are invalidated concurrently by setting tb to NULL.
- Only alpha has been measured. The other four targets that use goto_jc are built and boot-tested only.
v4: Split out of the patch that also changed the
tcg_gen_lookup_and_goto_ptr() API and introduced tb_jmp_cache_probe, which are now the two preceding patches. Requested by Richard Henderson.
v4: Emit the softmmu form of tb_jmp_cache_hash_func() under
CONFIG_SOFTMMU rather than the user-only form everywhere. v3 emitted the user-only hash unconditionally, which was wrong for system mode and was only not a correctness bug because a wrong index simply misses. Caught by Richard Henderson. tcg-op.c is compiled once per build rather than once per target, but CONFIG_SOFTMMU is set for it, and TARGET_PAGE_BITS -- a load from target_page here -- is fixed long before any translation happens.
v4: Compare the pc before testing tb for NULL. On a hash miss the pc is
the field most likely to differ, and an unused entry has a zero pc that only pc 0 can match, so the tb test buys nothing ahead of it. Suggested by Richard Henderson.
v4: Assert that offsetof(TranslationBlock, flags) is 8-byte aligned, since
folding the flags and cflags guards into one 64-bit load relies on it and nothing else does. Requested by Richard Henderson.
v4: Zero-extend a 32-bit guest PC instead of falling back to the helper.
Suggested by Richard Henderson. The high half then folds to a compare against zero.
v4: Describe cs_base in the probe as a second word of target-specific
flags rather than by name. Suggested by Richard Henderson.
v5: Build the folded flags/cflags constant with deposit64() rather than
under #if HOST_BIG_ENDIAN, so both arms compile on every host. Requested by Richard Henderson.
v5: Read cpu->tb_jmp_cache directly, and honor CF_NO_GOTO_JC rather than a
poisoned base pointer, which is no longer how breakpoints are handled. A separate base pointer comes back later in the series for pending exits.
v5: Note the backend expansion this wants as a follow-up. Suggested by
Richard Henderson, whose list it is.
--- include/tcg/tcg-op-common.h | 3 +- tcg/tcg-op.c | 110 +++++++++++++++++++++++++++++++++++- 2 files changed, 111 insertions(+), 2 deletions(-)
include/tcg/tcg-op-common.h +2 -1
@@ -91,7 +91,8 @@ void tcg_gen_lookup_and_goto_ptr(void);* @pc: temp holding the destination guest PC * * As tcg_gen_lookup_and_goto_ptr(), but the caller states where the -* dispatch is going, which allows the lookup to be done inline. +* dispatch is going, so the TB jump cache is probed inline and only a miss +* reaches helper_lookup_tb_ptr(). * * The contract is that when this runs, the CPU state must already be * exactly the destination's: @pc must hold what get_tb_cpu_state() would
tcg/tcg-op.c +109 -1
128 lines not on this page · raw message
Signature · 1 line
2.54.0
PATCH v5 7/9 RFC: accel/tcg: allow cross-page goto_tb chaining in user-only builds
In reply to Matt Turnertranslator_use_goto_tb() refuses to chain unless the destination is on the same page as the start of the TB. For guests whose text is much larger than a page this is expensive: an emulated alpha gcc compiling a 255k line translation unit takes the indirect dispatch path for 8.4 billion of its 34.2 billion TB exits, and a large share of those are ordinary direct branches that simply crossed an 8 KiB page boundary.
The restriction was made unconditional by d3a2a1d803 ("accel/tcg:
Introduce translator_use_goto_tb"), whose rationale was:
Various targets avoid the page crossing test for CONFIG_USER_ONLY, but that is wrong: mmap and mprotect can change page permissions.
That is true, but in user-only builds the invalidation path already covers it. There are no page tables: every mmap, mprotect and munmap reaches page_set_flags(), which calls tb_invalidate_phys_range() whenever the flags actually change, and tb_phys_invalidate() calls tb_jmp_unlink() to reset incoming jumps. A chained cross-page jump is therefore broken whenever the destination page's permissions change. This is not true in system mode, where TBs are keyed by physical address and a page table change invalidates nothing, so the restriction is kept there.
The rule protects one more thing, which the original rationale does not
mention: it guarantees that execution cannot enter a page without a TB lookup, and so without check_for_breakpoints(). That is what makes a breakpoint set after a block was translated take effect, since insertion deliberately invalidates nothing. A link established before the breakpoint was set would jump straight over it.
So the chaining is only enabled for a run that can never acquire a breakpoint. In user-only mode every breakpoint comes from gdb -- BP_CPU is g_assert_not_reached() there, and the guest cannot ask for one -- and gdb has to be requested with -g before the first block is translated, even though with suspend=n it may connect later. gdb_may_set_breakpoints() reports whether it was, and is fixed for the lifetime of the process.
Add tests/tcg/multiarch/test-xpage-chain.c to cover both hazards directly. It writes the last instruction of one page and the first of the next, so that the fall-through between them is a cross-page goto_tb, runs it 200000 times so the chain is established, then checks that mprotect(PROT_NONE) makes the next call fault, and that different code written into the page once it is mapped back runs rather than a stale translation.
The two instructions -- set the return value register, and return -- are all the architecture specific code there is; thirteen architectures supply them and the rest skip.
The test detects the hazard it is meant to detect: with the tb_invalidate_phys_range() call in page_set_flags() commented out, it fails both phases, executing page B after PROT_NONE and returning the stale result.
Run with -b, the same binary stops once the chain is established and lets tests/tcg/multiarch/gdbstub/xpage-bp.py set a breakpoint on the far side of it, which the next call has to stop on. With gdb_may_set_breakpoints() forced to false so that the chaining stays on under gdb, that breakpoint is missed and the test fails, which is what makes it a test of the gate rather than of gdb.
Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation on an x86-64 host, LTO build, on top of the preceding patches:
before: 916,415,123,244 instructions
after: 891,254,240,071 instructions -2.75%
before: 85.59s wall clock
after: 81.45s wall clock -4.84%Note that this is worth more in time than in instructions, the reverse of the preceding patch: a chained jump replaces a cache probe whose loads can miss, so the instructions it removes are more expensive than average.
Measured before the inline jump cache probe, when a missed chain cost a helper call rather than an inline probe, the same change was worth -7.9%.
RFC because this reverses a deliberate decision and the reasoning above wants review from someone who knows the invalidation paths better than I do.
v3: Only take the shortcut when no gdbstub was requested. The same-page
rule also forces a lookup, and so a breakpoint check, on entry to every page; without that, a chain established before a breakpoint was set runs past it. Reported by Richard Henderson.
v3: Change translator_use_goto_tb() rather than translator_is_same_page().
i386, riscv and s390x call translator_is_same_page() for something else -- enforcing that only a single-insn TB may cross a page -- and v2 changed their TB boundaries in user-only mode as a side effect. alpha does not call it, so the numbers above are unaffected.
v3: Add the gdbstub half of the test.
v4: Move the test to tests/tcg/multiarch so that every *-user target runs
it, rather than only alpha. Requested by Alex Bennee. The direct branch is gone with it: a fall-through off the end of a page is a cross-page goto_tb just the same, and needs no per-architecture branch encoding or displacement arithmetic, only "set the return value" and "return". Built and run under qemu-user on aarch64, alpha, arm, hppa, loongarch64, m68k, mips, ppc, ppc64le, riscv64, s390x, sh4, sparc64 and x86_64; ppc64 ELFv1 skips, because a function pointer there is a descriptor rather than a code address.
--- accel/tcg/translator.c | 33 ++- gdbstub/user.c | 14 + include/gdbstub/user.h | 11 + tests/tcg/multiarch/Makefile.target | 12 +- tests/tcg/multiarch/gdbstub/xpage-bp.py | 37 +++ tests/tcg/multiarch/test-xpage-chain.c | 336 ++++++++++++++++++++++++ 6 files changed, 441 insertions(+), 2 deletions(-) create mode 100644 tests/tcg/multiarch/gdbstub/xpage-bp.py create mode 100644 tests/tcg/multiarch/test-xpage-chain.c
accel/tcg/translator.c +32 -1
@@ -15,6 +15,9 @@#include "accel/tcg/cpu-mmu-index.h" #include "exec/target_page.h" #include "exec/translator.h" +#ifdef CONFIG_USER_ONLY +#include "gdbstub/user.h" +#endif #include "exec/plugin-gen.h" #include "tcg/tcg-op-common.h" #include "internal-common.h"
@@ -110,6 +113,34 @@ bool translator_is_same_page(const DisasContextBase *db, vaddr addr)return ((addr ^ db->pc_first) &TARGET_PAGE_MASK ) ==0 ; } +/* +* Whether a direct jump may be chained to a destination outside the page +* the TB started in. +* +* In user-only mode there are no page tables. Every mmap, mprotect and +* munmap goes through page_set_flags(), which calls tb_invalidate_phys_range() +* whenever the flags actually change, and tb_phys_invalidate() unlinks +* incoming jumps. A cross-page link is therefore broken whenever the +* destination page's permissions change. +* +* What the same-page rule also provides is that execution cannot enter a page +* without a TB lookup, and so without check_for_breakpoints(), which is what +* makes a breakpoint set after a block was translated take effect. Nothing +* invalidates on breakpoint insertion, so a link established beforehand would +* jump straight over it. In user-only mode breakpoints only ever come from +* gdb -- BP_CPU is g_assert_not_reached() there and the guest has no way to +* ask for one -- and gdb has to be requested with -g before the first block +* is translated, so a run that has no gdbstub can never acquire a breakpoint. +*/ +static bool use_cross_page_goto_tb (void ) +{ +#ifdef CONFIG_USER_ONLY +return !gdb_may_set_breakpoints (); +#else +return false; +#endif +} +bool translator_use_goto_tb (DisasContextBase *db,vaddr dest) {/* Suppress goto_tb if requested. */
@@ -118,7 +149,7 @@ bool translator_use_goto_tb(DisasContextBase *db, vaddr dest) }/* Check for the dest on the same page as the start of the TB. */ -return translator_is_same_page (db, dest); +return use_cross_page_goto_tb () ||translator_is_same_page (db, dest); } void translator_loop(CPUState *cpu, TranslationBlock *tb, int *max_insns,
gdbstub/user.c +14 -0
@@ -470,6 +470,18 @@ static void *gdbserver_accept_thread(void *arg)#define USAGE "\nUsage: -g {port|path}[,suspend={y|n}]" +/* +* Set before the guest runs and never cleared, so that code translated at +* any point can rely on it: with suspend=n gdb may connect long after +* startup, and once connected it can insert a breakpoint at any time. +*/ +static bool gdbserver_requested; + +bool gdb_may_set_breakpoints (void ) +{ +return gdbserver_requested; +} +bool gdbserver_start (const char *args,Error **errp) {g_auto (GStrv) argv =g_strsplit (args,"," ,0 );
@@ -513,6 +525,8 @@ bool gdbserver_start(const char *args, Error **errp)return false; } + gdbserver_requested = true; +if (suspend) {if (gdbserver_accept (port, gdb_fd, port_or_path)) {gdb_handlesig (first_cpu,0 ,NULL ,NULL ,0 );
include/gdbstub/user.h +11 -0
@@ -11,6 +11,17 @@#define MAX_SIGINFO_LENGTH 128 +/** +* gdb_may_set_breakpoints() - whether a breakpoint can ever be inserted +* +* In user-only mode every breakpoint comes from gdb, and gdb is only ever +* reachable if -g was given at startup, before the guest ran a single +* instruction. A run that has no gdbstub can therefore never acquire a +* breakpoint, which lets translation take shortcuts that a breakpoint +* would invalidate. Stays true once true, even if gdb detaches. +*/ +bool gdb_may_set_breakpoints (void ); +/** * gdb_handlesig() - yield control to gdb * @cpu: CPU
tests/tcg/multiarch/Makefile.target +11 -1
@@ -143,6 +143,15 @@ run-gdbstub-follow-fork-mode-parent: follow-fork-mode --bin $< --test $(MULTIARCH_SRC)/gdbstub/follow-fork-mode-parent.py, \ following parents on fork) +# The chaining this exercises is only enabled when no gdbstub was requested, +# so what is under test here is that requesting one turns it back off. +run-gdbstub-xpage-bp: test-xpage-chain + $(call run-test, $@, $(GDB_SCRIPT) \ + --gdb $(GDB) \ + --qemu $(QEMU) --qargs "$(QEMU_OPTS)" \ + --bin "$< -b" --test $(MULTIARCH_SRC)/gdbstub/xpage-bp.py, \ + breakpoint behind an established cross-page chain) + run-gdbstub-late-attach: late-attach $(call run-test, $@, env LATE_ATTACH_PY=1 $(GDB_SCRIPT) \ --gdb $(GDB) \
@@ -159,7 +168,8 @@ EXTRA_RUNS += run-gdbstub-sha1 run-gdbstub-qxfer-auxv-read \ run-gdbstub-registers run-gdbstub-prot-none \ run-gdbstub-catch-syscalls run-gdbstub-follow-fork-mode-child \ run-gdbstub-follow-fork-mode-parent \ - run-gdbstub-qxfer-siginfo-read run-gdbstub-late-attach + run-gdbstub-qxfer-siginfo-read run-gdbstub-late-attach \ + run-gdbstub-xpage-bp # ARM Compatible Semi Hosting Tests #
tests/tcg/multiarch/gdbstub/xpage-bp.py new file +37 -0
@@ -0,0 +1,37 @@ +"""Test that a breakpoint set after a cross-page chain is established is hit. + +translator_use_goto_tb() lets a direct branch chain to another page in +user-only builds, which is only safe because a run with no gdbstub can never +acquire a breakpoint. This runs with one, so the chaining must be off and +the breakpoint must still be reached. + +This runs as a sourced script (via -x, via run-test.py). + +SPDX-License-Identifier: GPL-2.0-or-later +""" +from test_gdbstub import main, report + + +def run_test(): + """Run through the tests one by one""" + gdb.Breakpoint("break_here") + gdb.execute("continue") + + # The chain exists by now; put a breakpoint on the far side of it. + target = int(gdb.parse_and_eval("(unsigned long)page_b_entry")) + if target == 0: + report(True, "no code emitters for this architecture, skipped") + return + gdb.execute("break *{}".format(target)) + gdb.execute("continue") + + pc = int(gdb.parse_and_eval("(unsigned long)$pc")) + report(pc == target, "stopped at {:#x}, expected {:#x}".format(pc, target)) + + gdb.execute("delete") + gdb.execute("continue") + exitcode = int(gdb.parse_and_eval("$_exitcode")) + report(exitcode == 0, "{} == 0".format(exitcode)) + + +main(run_test)
tests/tcg/multiarch/test-xpage-chain.c new file +336 -0
336 lines not on this page · raw message
Signature · 1 line
2.54.0
Re: [PATCH v5 7/9] RFC: accel/tcg: allow cross-page goto_tb chaining in user-only builds
Quoted 69 lines · Matt Turner
translator_use_goto_tb()refuses to chain unless the destination is on the same page as the start of the TB. For guests whose text is much larger than a page this is expensive: an emulated alpha gcc compiling a 255k line translation unit takes the indirect dispatch path for 8.4 billion of its 34.2 billion TB exits, and a large share of those are ordinary direct branches that simply crossed an 8 KiB page boundary.The restriction was made unconditional by
d3a2a1d803("accel/tcg:
Introducetranslator_use_goto_tb"), whose rationale was:Various targets avoid the page crossing test for
CONFIG_USER_ONLY, but that is wrong: mmap and mprotect can change page permissions.That is true, but in user-only builds the invalidation path already covers it. There are no page tables: every mmap, mprotect and munmap reaches
page_set_flags(), which callstb_invalidate_phys_range()whenever the flags actually change, andtb_phys_invalidate()callstb_jmp_unlink()to reset incoming jumps. A chained cross-page jump is therefore broken whenever the destination page's permissions change. This is not true in system mode, where TBs are keyed by physical address and a page table change invalidates nothing, so the restriction is kept there.The rule protects one more thing, which the original rationale does not
mention: it guarantees that execution cannot enter a page without a TB lookup, and so withoutcheck_for_breakpoints(). That is what makes a breakpoint set after a block was translated take effect, since insertion deliberately invalidates nothing. A link established before the breakpoint was set would jump straight over it.So the chaining is only enabled for a run that can never acquire a breakpoint. In user-only mode every breakpoint comes from gdb --
BP_CPUisg_assert_not_reached()there, and the guest cannot ask for one -- and gdb has to be requested with -g before the first block is translated, even though with suspend=n it may connect later.gdb_may_set_breakpoints()reports whether it was, and is fixed for the lifetime of the process.Add
tests/tcg/multiarch/test-xpage-chain.cto cover both hazards directly. It writes the last instruction of one page and the first of the next, so that the fall-through between them is a cross-pagegoto_tb, runs it 200000 times so the chain is established, then checks thatmprotect(PROT_NONE)makes the next call fault, and that different code written into the page once it is mapped back runs rather than a stale translation.The two instructions -- set the return value register, and return -- are all the architecture specific code there is; thirteen architectures supply them and the rest skip.
The test detects the hazard it is meant to detect: with the
tb_invalidate_phys_range()call inpage_set_flags()commented out, it fails both phases, executing page B afterPROT_NONEand returning the stale result.Run with -b, the same binary stops once the chain is established and lets
tests/tcg/multiarch/gdbstub/xpage-bp.pyset a breakpoint on the far side of it, which the next call has to stop on. Withgdb_may_set_breakpoints()forced to false so that the chaining stays on under gdb, that breakpoint is missed and the test fails, which is what makes it a test of the gate rather than of gdb.Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation on an x86-64 host, LTO build, on top of the preceding patches:
before: 916,415,123,244 instructions after: 891,254,240,071 instructions -2.75% before: 85.59s wall clock after: 81.45s wall clock -4.84%
Quoted 6 lines
Note that this is worth more in time than in instructions, the reverse of the preceding patch: a chained jump replaces a cache probe whose loads can miss, so the instructions it removes are more expensive than average.
Measured before the inline jump cache probe, when a missed chain cost a helper call rather than an inline probe, the same change was worth -7.9%.
Cherry-picked this to tcg-next.
r~
PATCH v5 8/9 RFC: accel/tcg: poison the jump cache instead of polling for indirect exits
In reply to Matt TurnerEvery translation block begins by loading cpu->neg.icount_decr.u32, testing it and branching to the exit path. That is three host instructions at the top of every TB, and blocks are short: an emulated alpha gcc 16.2.0 compiling a 255k line translation unit executes 34.2 billion of them at 6.04 guest instructions each.
A block does not need to poll if every way out of it already reaches a check. A goto_tb does not: it chains straight into its destination, with nothing in between that looks at icount_decr, so the destination has to poll on entry. An indirect exit does. The out-of-line path calls helper_lookup_tb_ptr() every time, so it only needs the helper to return the epilogue while an exit is pending. The inline probe needs a way to be told, so give it one:CPUState::tb_jmp_cache_probe, the base pointer it reads. Normally that is cpu->tb_jmp_cache; pointed at a shared page of zeroes instead, every entry the probe finds has a NULL tb, every dispatch misses, and a miss lands in the same helper. The real jump cache is untouched, so no cache contents are lost, and the fast path pays nothing: the base was a load from CPUState either way.
The two places that set icount_decr.u16.high poison the probe; the main loop puts it back once cpu_handle_interrupt() has cleared the reason. The poison is a single read-only mapping shared by every CPU, because nothing may ever write to it and a stray store into a page every vCPU dispatches through is worth trapping rather than debugging.
The poll is therefore emitted only in blocks that emit a goto_tb. Whether a block does is not known until its last exit has been generated, so the decision is deferred and the load and branch are emitted retroactively at the head of the block in gen_tb_end(), using the same emit_before_op mechanism the can_do_io stores use. icount opts out and keeps the counter unconditionally.
Interrupt latency is bounded at one block, as before. It does not depend on the shape of the guest's control flow graph: a block either polls on entry or is checked on the way out, and no run of blocks can avoid both. What changes is where the check sits, not how often one happens.
tests/tcg/multiarch/test-indirect-irq.c is added for this: a loop whose only back edge is an indirect branch, under alarm(1). That loop's block emits no goto_tb, so it no longer polls, and the test passes only because the dispatch notices instead -- it hangs if the poison is removed, which is what makes it a test of the new mechanism rather than of the old poll. Nothing in it is architecture specific: the loop is a computed goto, which every target's compiler supports, so it covers whichever targets go on to use the inline probe. The other alpha tests still pass and the emulated compiler still produces byte-identical output.
Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host, LTO build, on top of the preceding patches:
before: 891,254,240,071 instructions
after: 868,811,832,620 instructions -2.52%
before: 81.45s wall clock
after: 79.85s wall clock -1.96%The emulated compiler produces byte-identical output.
RFC because:
- The un-poison in the main loop races a concurrent poison from another thread. The existing barrier around icount_decr.u16.high covers it -- a poison that lands after the sync also re-set the flag, and exit_request was stored before it -- but this deserves more eyes than the single-threaded user-mode testing I have given it.
- Only the inline probe needs the poison, and only alpha uses the inline probe today. Targets on the out-of-line path are covered by the helper check alone, but that has not been measured.
v3: Rebased onto the removal of "only poll for interrupts in blocks that can
close a cycle", which v2 sat on top of and which is dropped: it let a straight-line run of arbitrary length go unchecked, since a block with no backward edge polled nowhere (Richard).
The rule is now that a block polls iff it emits a goto_tb, rather than iff it can close a control flow cycle. That keeps the bound at one block without any analysis of the guest's control flow graph, so the objection to the dropped patch does not carry over. The deferred-emission machinery it needs moves here from that patch; DisasContextBase::needs_exit_check and the hook in translator_use_goto_tb() are gone with it, and the flag is now set by tcg_gen_goto_tb() rather than by goto_ptr emission.
All of v2's measurements were dropped: they were taken with the cycle-analysis patch underneath, which changes both the baseline and what is left to remove, so none of them described this patch. The numbers above are a fresh measurement of the series as it now stands.
v4: Moved the test from tests/tcg/alpha/ to tests/tcg/multiarch/: the
mechanism is generic and nothing in the test is alpha specific (Alex).
The performance numbers above are the v3 measurements, not re-run: the machine they were taken on is busy.
v5: CPUState::tb_jmp_cache_probe moves here from what was patch 5, which
used it for breakpoints too. Breakpoints are now a cflag, so a pending exit is the only reason left to poison, and the machinery shrinks to
match: no NULL states to handle, no cross-thread poison from cpu_breakpoint_insert(), and one condition rather than two.
v5: Map the poison read-only rather than leaving it a writable .bss object.
Requested by Richard Henderson. It costs a page-aligned 1MB allocation at startup instead of nothing on disk, which the enforcement is worth. qemu_mprotect_ro() is added for it, alongside the _rw, _rwx and _none forms already there.
v5: Drop the NULL checks in the poison and sync helpers. Requested by
Richard Henderson: the sync is only ever called by the main loop, so it cannot see an unrealized CPU, and unrealize now leaves the probe pointing at the poison rather than at NULL, so neither has an unrealized state to consider.
--- accel/tcg/cpu-exec.c | 91 +++++++++++++++++++++++++ accel/tcg/internal-common.h | 9 +++ accel/tcg/tcg-accel-ops.c | 2 + accel/tcg/translator.c | 51 +++++++++++++- include/hw/core/cpu.h | 9 +++ include/qemu/mprotect.h | 1 + include/tcg/tcg.h | 2 + tcg/tcg-op.c | 21 +++++- tests/tcg/multiarch/test-indirect-irq.c | 62 +++++++++++++++++ util/osdep.c | 9 +++ 10 files changed, 253 insertions(+), 4 deletions(-) create mode 100644 tests/tcg/multiarch/test-indirect-irq.c
accel/tcg/cpu-exec.c +91 -0
@@ -19,6 +19,9 @@#include "qemu/osdep.h" #include "qemu/qemu-print.h" +#include "qemu/error-report.h" +#include "qemu/memalign.h" +#include "qemu/mprotect.h" #include "qapi/error.h" #include "qapi/type-helpers.h" #include "hw/core/cpu.h"
@@ -388,6 +391,16 @@ const void *HELPER(lookup_tb_ptr)(CPUArchState *env)*/ cpu->neg.can_do_io = true; +/* +* A block that dispatches indirectly does not emit the icount_decr poll, +* so this is where a pending exit is noticed for that path: either the +* probe was poisoned and every dispatch arrives here, or the target uses +* the out-of-line lookup and always did. +*/ +if (unlikely (cpu_loop_exit_requested (cpu))) { +return tcg_code_gen_epilogue; + } +TCGTBCPUState s = cpu->cc->tcg_ops->get_tb_cpu_state (cpu); s.cflags =curr_cflags (cpu);
@@ -779,6 +792,70 @@ static inline bool cpu_handle_exception(CPUState *cpu, int *ret)return false; } +/* +* The inline jump cache probe reads cpu->tb_jmp_cache_probe and takes the +* slow path when the entry it finds has a NULL tb. Pointing the probe at a +* region that is all zeroes therefore forces every indirect dispatch into +* helper_lookup_tb_ptr(), which returns the epilogue while an exit is +* pending. The real jump cache is untouched, so no contents are lost and +* recovery is a single store. +* +* Only ever read from, and only one entry per dispatch, so one shared +* zero-filled cache is enough for every CPU. Mapped read-only, since +* nothing may write to it and a stray store into a shared page every vCPU +* dispatches through is worth trapping rather than debugging. +*/ +static CPUJumpCache *tb_jmp_cache_poison; + +static void tb_jmp_cache_poison_init (void ) +{ +size_t align =qemu_real_host_page_size (); +size_t size =ROUND_UP (sizeof (CPUJumpCache), align); +void *p =qemu_memalign (align, size); + +memset (p,0 , size); +if (qemu_mprotect_ro (p, size) <0 ) { +/* Only the enforcement is lost; the zeroes are what matter. */ +warn_report ("could not write-protect the jump cache poison" ); + } + tb_jmp_cache_poison = p; +} + +/* +* Poison @cpu's probe, from any thread. A plain store is enough: the value +* only ever costs a slow path that is correct on its own, and the generated +* code re-reads the base on every dispatch. +*/ +void tcg_cpu_poison_jmp_cache (CPUState *cpu) +{ +qatomic_set (&cpu->tb_jmp_cache_probe, tb_jmp_cache_poison); +} + +/* +* Called from @cpu's own main loop, which is the only context that can +* establish that no reason to be poisoned is left. +*/ +void tcg_cpu_sync_jmp_cache (CPUState *cpu) +{ +if (qatomic_read (&cpu->tb_jmp_cache_probe) == cpu->tb_jmp_cache) { +return ; + } + +qatomic_set (&cpu->tb_jmp_cache_probe, cpu->tb_jmp_cache); + +/* +* Another thread may have set icount_decr.u16.high after the caller +* decided no exit was pending, and its poison may have landed before +* the store above. Order that store against the re-read, so the race +* is lost in the safe direction: an exit that is still pending here +* poisons again, and the dispatch after it returns to the main loop. +*/ +smp_mb (); +if (unlikely (cpu_loop_exit_requested (cpu))) { +tcg_cpu_poison_jmp_cache (cpu); + } +} +void tcg_kick_vcpu_thread (CPUState *cpu) {/*
@@ -791,6 +868,9 @@ void tcg_kick_vcpu_thread(CPUState *cpu)/* Ensure cpu_exec will see the exit request after TCG has exited. */ qatomic_store_release (&cpu->neg.icount_decr.u16.high,-1 ); + +/* Blocks that only dispatch indirectly do not poll; stop them chaining. */ +tcg_cpu_poison_jmp_cache (cpu); }static inline bool icount_exit_request (CPUState *cpu)
@@ -991,6 +1071,13 @@ cpu_exec_loop(CPUState *cpu, SyncClocks *sc)break ; } +/* +* cpu_handle_interrupt() has just cleared everything that would +* make a dispatch have to come back here, so this is where the +* probe is allowed to return after a poison. +*/ +tcg_cpu_sync_jmp_cache (cpu); + tb =tb_lookup (cpu, s);if (tb ==NULL ) {CPUJumpCache *jc;
@@ -1092,6 +1179,7 @@ bool tcg_exec_realizefn(CPUState *cpu, Error **errp)assert (tcg_ops->get_tb_cpu_state);assert (tcg_ops->mmu_index); tcg_ops->initialize (); +tb_jmp_cache_poison_init (); tcg_target_initialized = true; }
@@ -1099,6 +1187,7 @@ bool tcg_exec_realizefn(CPUState *cpu, Error **errp)tcg_update_cflags (cpu); cpu->tb_jmp_cache =g_new0 (CPUJumpCache,1 ); +qatomic_set (&cpu->tb_jmp_cache_probe, cpu->tb_jmp_cache);tlb_init (cpu);#ifndef CONFIG_USER_ONLY tcg_iommu_init_notifier_list (cpu);
@@ -1116,5 +1205,7 @@ void tcg_exec_unrealizefn(CPUState *cpu)#endif /* !CONFIG_USER_ONLY */ tlb_destroy (cpu); +/* Not NULL: nothing then has to special-case an unrealized CPU. */ +tcg_cpu_poison_jmp_cache (cpu);g_free_rcu (cpu->tb_jmp_cache, rcu); }
accel/tcg/internal-common.h +9 -0
@@ -144,6 +144,15 @@ void page_table_config_init(void); G_NORETURN void cpu_io_recompile(CPUState *cpu, uintptr_t retaddr);#endif /* CONFIG_USER_ONLY */ +/* +* Force @cpu's generated code back into helper_lookup_tb_ptr(), which +* re-checks everything the inline jump cache probe cannot. Safe to call +* from any thread. tcg_cpu_sync_jmp_cache() undoes it, and is for the +* owning CPU's main loop only. +*/ +void tcg_cpu_poison_jmp_cache (CPUState *cpu); +void tcg_cpu_sync_jmp_cache (CPUState *cpu); +void tb_phys_invalidate (TranslationBlock *tb,tb_page_addr_t page_addr);void tb_set_jmp_target (TranslationBlock *tb,int n,uintptr_t addr);
accel/tcg/tcg-accel-ops.c +2 -0
@@ -38,6 +38,7 @@#include "exec/cputlb.h" #include "exec/hwaddr.h" #include "exec/tb-flush.h" +#include "internal-common.h" #include "exec/translation-block.h" #include "exec/watchpoint.h" #include "gdbstub/enums.h"
@@ -106,6 +107,7 @@ void tcg_handle_interrupt(CPUState *cpu, int mask)qemu_cpu_kick (cpu); }else {qatomic_set (&cpu->neg.icount_decr.u16.high,-1 ); +tcg_cpu_poison_jmp_cache (cpu); } }
accel/tcg/translator.c +48 -3
86 lines not on this page · raw message
include/hw/core/cpu.h +9 -0
@@ -519,6 +519,15 @@ struct CPUState {MemoryRegion *memory;struct CPUJumpCache *tb_jmp_cache; +/* +* @tb_jmp_cache_probe: the base the inline jump cache probe reads. +* +* Normally @tb_jmp_cache. Pointed at a shared read-only page of zeroes +* while an exit is pending, so that every inline dispatch misses and +* falls back to helper_lookup_tb_ptr(), which returns to the main loop. +* Only generated code and the accessors in cpu-exec.c may touch it. +*/ +struct CPUJumpCache *tb_jmp_cache_probe;GArray *gdb_regs;int gdb_num_regs;
include/qemu/mprotect.h +1 -0
@@ -8,6 +8,7 @@#define QEMU_MPROTECT_H int qemu_mprotect_rw (void *addr,size_t size); +int qemu_mprotect_ro (void *addr,size_t size);int qemu_mprotect_rwx (void *addr,size_t size);int qemu_mprotect_none (void *addr,size_t size);
include/tcg/tcg.h +2 -0
@@ -389,6 +389,8 @@ struct TCGContext {struct TCGLabelPoolData *pool_labels;TCGLabel *exitreq_label; +/* Set by goto_tb emission: this TB chains without reaching a check. */ +bool exit_check_needed;#ifdef CONFIG_PLUGIN /*
tcg/tcg-op.c +20 -1
@@ -2713,6 +2713,13 @@ void tcg_gen_goto_tb(unsigned idx)tcg_debug_assert ((tcg_ctx->goto_tb_issue_mask & (1 << idx)) ==0 ); tcg_ctx->goto_tb_issue_mask |=1 << idx;#endif +/* +* A goto_tb chains straight into the destination, with nothing in between +* that looks at icount_decr, so this TB has to poll on entry. See +* defer_exit_check(). +*/ + tcg_ctx->exit_check_needed = true; +plugin_gen_disable_mem_helpers ();tcg_gen_op1i (INDEX_op_goto_tb,0 , idx); }
@@ -2790,8 +2797,13 @@ static void gen_jmp_cache_probe(TCGv_i64 pc, const TranslationBlock *tb)gen_jmp_cache_hash (h, pc);tcg_gen_shli_i64 (h, h,4 ); +/* +* Not cpu->tb_jmp_cache: the probe reads its own base so that the main +* loop can poison it, which is how a pending exit forces every dispatch +* back into the helper. See tcg_cpu_sync_jmp_cache(). +*/ tcg_gen_ld_ptr (jc, tcg_env, - offsetof(CPUState , tb_jmp_cache) -sizeof (CPUState)); + offsetof(CPUState , tb_jmp_cache_probe) -sizeof (CPUState));tcg_gen_trunc_i64_ptr (ent, h);tcg_gen_add_ptr (ent, jc, ent);
@@ -2849,6 +2861,13 @@ static void gen_goto_jc(TCGv_i64 pc)plugin_gen_disable_mem_helpers (); +/* +* Neither path below needs an icount_decr poll. The helper returns to +* the main loop while an exit is pending, and a pending exit poisons +* tb_jmp_cache_probe, so the inline probe finds a NULL tb and falls into +* that same helper. +*/ +#ifdef CONFIG_DEBUG_TCG /* * The caller has asserted that env already describes the destination.
tests/tcg/multiarch/test-indirect-irq.c new file +62 -0
62 lines not on this page · raw message
util/osdep.c +9 -0
@@ -99,6 +99,15 @@ int qemu_mprotect_rw(void *addr, size_t size)#endif } +int qemu_mprotect_ro (void *addr,size_t size) +{ +#ifdef _WIN32 +return qemu_mprotect__osdep (addr, size,PAGE_READONLY ); +#else +return qemu_mprotect__osdep (addr, size,PROT_READ ); +#endif +} +int qemu_mprotect_rwx (void *addr,size_t size) {#ifdef _WIN32
Signature · 1 line
2.54.0
PATCH v5 9/9 RFC: tcg: fold a guest displacement into the host addressing mode
In reply to Matt TurnerNothing in the TCG frontend interface can express a based memory access. tcg_gen_qemu_ld/st take an address and nothing else, so a target with a displacement in its load and store encodings -- which is most of them -- has to materialize the address first:
ldq a1,8(a0) -> mov 0x80(%rbp),%rbx reload a0
lea 0x8(%rbx),%r12 address
mov (%r12),%r12 the load
mov %r12,0x88(%rbp) spill a1The lea is pure loss on a host whose addressing mode has a displacement field sitting empty. It also needs a register, at the point in a block where pressure is highest.
Fold it. After optimization, look for an add of a constant immediately before a guest access, defining that access's address operand, and move the constant into a new second constant argument on the op. The add is left for liveness to remove, so nothing breaks if its result has another use. Only the immediately preceding op is examined: that is what the frontends emit, and a window of one op means the pass does not have to reason about what could have happened in between. The one thing it does check is that the add did not clobber the base it read, since the access now reads that base directly.
Targets opt in with TCG_TARGET_HAS_ldst_disp and an out_disp member on TCGOutOpQemuLdSt. Without it the pass does not run, the displacement stays zero and the existing out member is called exactly as before, so no other backend changes behavior or needs touching.
The fold is refused unless the access has no slow path at all, since the slow path hands addr_reg to the helper and that register no longer holds the full guest address. That is decided generically: user-only, because softmmu compares the unadjusted address against the TLB; a 64-bit address type, because a 32-bit one wraps where a host displacement would not; and no alignment test on the access. For x86_64 the displacement goes in the disp32 that prepare_host_addr() already fills in for guest_base, so all the backend has left to check is that guest_base plus the displacement still fits there.
Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host, LTO build, on top of the preceding patches, against a control measured in the same session:
before: 868,811,832,620 instructions, 79.85s
after: 819,262,147,022 instructions, 77.30s
-5.70% instructions, -3.20% wallEmitted code shrinks from 50.55MB to 48.80MB over the run, 167.4 to 161.6 bytes per block. Per Alpha opcode, the host bytes emitted for an access fall as expected and nothing else moves:
ldq 18.3 -> 15.4 ldah 20.9 -> 20.9
ldl 16.6 -> 14.1 lda 12.9 -> 12.9
stq 12.8 -> 9.7 mov 9.8 -> 9.8The emulated compiler produces byte-identical output and the alpha tests still pass, including with a non-zero guest_base forced via -B.
RFC because:
- Only wired up for x86_64, and only for qemu_ld and qemu_st; the i128 qemu_ld2 and qemu_st2 pairs are left alone.
- Requiring that no slow path exists is stricter than necessary. The fast path test can stay on the base register as long as the displacement is itself a multiple of the required alignment, which it is for anything a frontend emits for a struct or stack access. Recording the displacement in TCGLabelQemuLdst and emitting one lea on the slow path would then cover alignment-checked accesses too, at no fast path cost.
- Softmmu wants the displacement folded into the TLB comparison as well, which is a bigger change than this one.
- A one op window catches everything the frontends emit today but is trivially defeated by anything scheduled in between.
v4:
- Hoisted the compilation mode tests -- tcg_use_softmmu and the 64-bit address type -- out of the backend hook and into fold_ldst_disp(), next to the TCG_TARGET_HAS_ldst_disp test, so the loop is not entered at all when the mode rules the fold out.
- Pass MemOp rather than MemOpIdx to the backend hook; nothing about the mmu_idx is relevant to it.
- Moved the alignment test into generic code as ldst_disp_needs_align(), so a backend does not have to repeat the atom_and_align_for_opc() call. The exact answer depends on the host's atomicity capabilities, which the generic pass does not know, so it answers for the most restrictive host. That is the same answer for everything the frontends actually emit -- MO_ATOM_IFALIGN is the default -- and conservative for the handful of MO_ATOM_WITHIN16 and MO_ATOM_SUBALIGN accesses, which lose the fold on a host that could have taken it.
- What is left of the x86_64 hook is the guest_base test, so it now lives beside x86_guest_base under the CONFIG_USER_ONLY that declares it.
- Refuse a displacement that does not fit in an int32_t, which is what out_disp() takes. Not reachable with any real guest_base, but the pass should not offer the backend something the interface cannot carry.
- The numbers above are unchanged from v3: they have not been re-measured on the restructured patch, which is not expected to move them since the accesses in this workload are all MO_ATOM_IFALIGN.
--- include/tcg/tcg-opc.h | 9 ++- tcg/tcg-op-ldst.c | 3 +- tcg/tcg.c | 132 +++++++++++++++++++++++++++++++++++- tcg/x86_64/tcg-target.c.inc | 41 +++++++++++ tcg/x86_64/tcg-target.h | 3 + 5 files changed, 184 insertions(+), 4 deletions(-)
include/tcg/tcg-opc.h +7 -2
@@ -125,8 +125,13 @@ DEF(goto_ptr, 0, 1, 0, TCG_OPF_BB_EXIT | TCG_OPF_BB_END) DEF(plugin_cb, 0, 0, 1, TCG_OPF_NOT_PRESENT)DEF (plugin_mem_cb,0 ,1 ,1 ,TCG_OPF_NOT_PRESENT ) -DEF(qemu_ld, 1, 1, 1, TCG_OPF_CALL_CLOBBER | TCG_OPF_SIDE_EFFECTS | TCG_OPF_INT) -DEF(qemu_st, 0, 2, 1, TCG_OPF_CALL_CLOBBER | TCG_OPF_SIDE_EFFECTS | TCG_OPF_INT) +/* +* The second constant argument is a displacement to add to the address, +* zero unless a target advertises TCG_TARGET_HAS_ldst_disp and the fold in +* fold_ldst_disp() applied. + */ +DEF(qemu_ld, 1, 1, 2, TCG_OPF_CALL_CLOBBER | TCG_OPF_SIDE_EFFECTS | TCG_OPF_INT) +DEF(qemu_st, 0, 2, 2, TCG_OPF_CALL_CLOBBER | TCG_OPF_SIDE_EFFECTS | TCG_OPF_INT) DEF(qemu_ld2, 2, 1, 1, TCG_OPF_CALL_CLOBBER | TCG_OPF_SIDE_EFFECTS | TCG_OPF_INT)DEF (qemu_st2,0 ,3 ,1 ,TCG_OPF_CALL_CLOBBER |TCG_OPF_SIDE_EFFECTS |TCG_OPF_INT )
tcg/tcg-op-ldst.c +2 -1
@@ -92,7 +92,8 @@ static MemOp tcg_canonicalize_memop(MemOp op, bool is64, bool st)static void gen_ldst1 (TCGOpcode opc,TCGType type,TCGTemp *v,TCGTemp *addr,MemOpIdx oi) { -TCGOp *op =tcg_gen_op3 (opc, type,temp_arg (v),temp_arg (addr), oi); +/* The trailing zero is the address displacement; see fold_ldst_disp(). */ +TCGOp *op =tcg_gen_op4 (opc, type,temp_arg (v),temp_arg (addr), oi,0 );TCGOP_FLAGS (op) =get_memop (oi) &MO_SIZE ; }
tcg/tcg.c +131 -1
156 lines not on this page · raw message
tcg/x86_64/tcg-target.c.inc +41 -0
71 lines not on this page · raw message
tcg/x86_64/tcg-target.h +3 -0
@@ -30,6 +30,9 @@#define TCG_TARGET_NB_REGS 32#define MAX_CODE_GEN_BUFFER_SIZE (2 * GiB) +/* A guest displacement can go in the disp32 of the addressing mode. */ +#define TCG_TARGET_HAS_ldst_disp 1 + typedef enum { TCG_REG_EAX = 0, TCG_REG_ECX,
Signature · 1 line
2.54.0
PATCH v4 2/9 accel/tcg: enlarge the TB jump cache to 64K entries
In reply to Matt TurnerThe per-CPU TB jump cache has held 4096 entries since it was introduced. That is too small for guests running large programs: an emulated compiler misses often enough that the fallback qht lookup shows up prominently in a profile.
Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host. The compile performs 34.2 billion TB executions, of which 8.4 billion take the indirect dispatch path.
Sizing curve, on top of the preceding patch, instructions retired and wall clock:
12 bits ( 64 KiB): 1,562,204,796,597 132.58s
14 bits ( 256 KiB): 1,493,318,515,396 -4.41% 124.67s -5.97%
16 bits ( 1 MiB): 1,469,772,951,575 -5.92% 121.04s -8.71%
18 bits ( 4 MiB): 1,462,309,832,762 -6.39% 119.82s -9.62%16 bits is the knee. 18 buys another 0.47% of instructions for four times the memory. It does show a further 1.01% of wall clock, which is outside the 0.70% run-to-run spread at 16 bits, so the effect is probably real -- but paying four times the memory for it is a poor trade, and instructions retired does not account for the data cache pressure of a 4 MiB table.
In a perf profile the mechanism is visible directly: tb_htable_lookup(), which is where qht_lookup_custom() lands once it is inlined in an LTO build, falls from 6.10% of samples to 1.66%.
The cost is memory: the cache grows from 64 KiB to 1 MiB, once per CPUState. In linux-user that is per guest thread rather than per process, so a threaded guest pays it as many times as it has threads, exactly as system emulation pays it per vCPU. The allocation is g_new0(), so the pages are faulted in as the cache is touched and a thread that runs a small amount of code touches a small part of it, but the address space is committed either way.
So this may still want to be tunable, or scaled from the number of CPUs, rather than raised unconditionally. I do not have a threaded workload where the smaller cache is the better trade, and would welcome one.
v4: Fix the claim that a linux-user process is a single vCPU. The cache is
per CPUState, and linux-user creates one per guest thread. Pointed out by Richard Henderson.
--- accel/tcg/tb-jmp-cache.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
accel/tcg/tb-jmp-cache.h +1 -1
@@ -12,7 +12,7 @@#include "qemu/rcu.h" #include "exec/cpu-common.h" -#define TB_JMP_CACHE_BITS 12 +#define TB_JMP_CACHE_BITS 16#define TB_JMP_CACHE_SIZE (1 << TB_JMP_CACHE_BITS)/*
Signature · 1 line
2.54.0
PATCH v4 3/9 accel/tcg: skip the can_do_io stores in user-only builds
In reply to Matt TurnerEvery translation block stores to cpu->neg.can_do_io twice: false before the first instruction, true before the last one. Nothing reads it in a user-only build. There is no memory-mapped I/O in linux-user, and every reader is in system_ss: cputlb.c, watchpoint.c, icount-common.c and tcg-accel-ops-icount.c.
Two stores per TB is not much on its own, but TBs are short. An emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) executes 34.2 billion TBs at 6.04 guest instructions each, so this is 68 billion stores for nothing.
Measured on an x86-64 host, LTO build, on top of the preceding two patches:
before: 1,469,772,951,575 instructions
after: 1,402,667,803,616 instructions -4.57%
before: 121.04s wall clock
after: 115.56s wall clock -4.53%The emulated compiler produces byte-identical output.
v3: Use #ifndef CONFIG_USER_ONLY again rather than
if (IS_ENABLED(CONFIG_USER_ONLY)). QEMU's IS_ENABLED() is IS_EMPTY(), which is only true for a symbol Meson defines empty; CONFIG_USER_ONLY is defined as 1, so the test was always false and v2 emitted the two stores after all. The measurements above are from the working form.
--- accel/tcg/translator.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
accel/tcg/translator.c +10 -0
@@ -21,12 +21,14 @@#include "disas/disas.h" #include "tb-internal.h" +#ifndef CONFIG_USER_ONLY static void set_can_do_io (DisasContextBase *db,bool val) {QEMU_BUILD_BUG_ON (sizeof_field (CPUState, neg.can_do_io) !=1 );tcg_gen_st8_i32 (tcg_constant_i32 (val), tcg_env, offsetof(CPUState, neg.can_do_io) - sizeof(CPUState)); } +#endif bool translator_io_start (DisasContextBase *db) {
@@ -210,17 +212,25 @@ void translator_loop(CPUState *cpu, TranslationBlock *tb, int *max_insns,/* * Manage can_do_io for the translation block: set to false before * the first insn and set to true before the last insn. +* +* Nothing reads can_do_io in user-only builds. There is no MMIO +* there, and every reader (cputlb.c, watchpoint.c, icount) is in +* system_ss, so skip the two stores per TB entirely. */ if (db->num_insns ==1 ) {tcg_debug_assert (first_insn_start == db->insn_start); }else {tcg_debug_assert (first_insn_start != db->insn_start); +#ifndef CONFIG_USER_ONLY tcg_ctx->emit_before_op = first_insn_start;set_can_do_io (db, false); +#endif } +#ifndef CONFIG_USER_ONLY tcg_ctx->emit_before_op = db->insn_start;set_can_do_io (db, true); tcg_ctx->emit_before_op =NULL ; +#endif /* May be used by disas_log or plugin callbacks. */ tb->size = db->pc_next - db->pc_first;
Signature · 1 line
2.54.0
PATCH v4 4/9 tcg: pass the destination to tcg_gen_lookup_and_goto_ptr()
In reply to Matt Turnertcg_gen_lookup_and_goto_ptr() takes no arguments and emits a call to helper_lookup_tb_ptr(), which recovers the destination PC from env by calling back into the target through TCGCPUOps::get_tb_cpu_state(). At translation time the caller already has the destination PC in a temp, and knows the flags, cflags and cs_base any destination it may reach has to match, because they are the ones the block being generated was translated with.
Pass both, so that a later patch can use them to look the destination up inline. Nothing reads them yet and the generated code does not change.
The contract on @pc is the whole of the interface: it must hold exactly what get_tb_cpu_state() reports as the pc for the destination block. Five targets keep their PC in a temp whose value is that pc by construction and so can pass it: alpha, loongarch, mips, ppc and s390x. Everything else passes NULL and keeps today's behavior.
For six of those the TB pc is derived and passing the PC temp would be
wrong: avr's TB pc is the word address doubled, i386's is eip before segmentation, riscv masks it to 32 bits when xl is MXL_RV32, hppa derives it from the IAQ, hexagon adjusts it inside a hardware loop, and sparc puts npc in cs_base. The remaining seven -- arm, m68k, microblaze, or1k, rx, sh4 and tricore -- look like they could pass it, but I have not convinced myself of the contract for them and have nothing to test them with. Each is a one-line change for whoever wants it.
The common entry point takes a TCGTemp rather than a TCGv and reads the width from it, because the translators that are built for both values of TARGET_LONG_BITS -- arm, s390x, microblaze -- cannot include tcg-op.h. tcg-op.h wraps it for everyone else. This is the same split as tcg_gen_qemu_ld_*_chk().
v4: Split out of "tcg: probe the TB jump cache inline instead of calling a
helper", which did the API change and the inline probe in one patch. Requested by Richard Henderson.
--- include/tcg/tcg-op-common.h | 15 ++++++++++++--- include/tcg/tcg-op.h | 12 ++++++++++++ target/alpha/translate.c | 4 ++-- target/arm/tcg/translate-a64.c | 4 ++-- target/arm/tcg/translate.c | 10 +++++----- target/avr/translate.c | 4 ++-- target/hexagon/translate.c | 4 ++-- target/hppa/translate.c | 6 +++--- target/i386/tcg/translate.c | 2 +- .../loongarch/tcg/insn_trans/trans_branch.c.inc | 2 +- target/loongarch/tcg/translate.c | 4 ++-- target/m68k/translate.c | 2 +- target/microblaze/translate.c | 4 ++-- target/mips/tcg/nanomips_translate.c.inc | 2 +- target/mips/tcg/translate.c | 6 +++--- target/or1k/translate.c | 4 ++-- target/ppc/translate.c | 4 ++-- target/riscv/tcg/insn_trans/trans_rvzce.c.inc | 4 ++-- target/riscv/tcg/translate.c | 2 +- target/rx/translate.c | 4 ++-- target/s390x/tcg/translate.c | 5 +++-- target/sh4/translate.c | 4 ++-- target/sparc/translate.c | 4 ++-- target/tricore/translate.c | 4 ++-- tcg/tcg-op.c | 3 ++- 25 files changed, 71 insertions(+), 48 deletions(-)
include/tcg/tcg-op-common.h +12 -3
@@ -75,15 +75,24 @@ void tcg_gen_exit_tb(const TranslationBlock *tb, unsigned idx);void tcg_gen_goto_tb (unsigned idx);/** -* tcg_gen_lookup_and_goto_ptr() - look up the current TB, jump to it if valid -* @addr: Guest address of the target TB +* tcg_gen_lookup_and_goto_ptr() - look up the destination TB, jump to it +* @pc: temp holding the destination guest PC, or NULL +* @tb: the translation block being generated * * If the TB is not valid, jump to the epilogue. * +* The lookup is a call to helper_lookup_tb_ptr(). @pc and @tb describe the +* destination for a faster lookup that a later patch adds, and neither is +* used yet. When @pc is non-NULL it must hold exactly the value +* get_tb_cpu_state() reports as the pc for the destination, and the +* destination must match @tb's flags, cflags and cs_base. A target whose +* pc is derived rather than being that key -- avr's word address, i386's +* eip before segmentation -- must pass NULL. +* * This operation is optional. If the TCG backend does not implement goto_ptr, * this op is equivalent to calling tcg_gen_exit_tb() with 0 as the argument. */ -void tcg_gen_lookup_and_goto_ptr (void ); +void tcg_gen_lookup_and_goto_ptr_tmp (TCGTemp *pc,const TranslationBlock *tb);void tcg_gen_plugin_cb (unsigned from);void tcg_gen_plugin_mem_cb (TCGv_i64 addr,unsigned meminfo);
include/tcg/tcg-op.h +12 -0
@@ -49,6 +49,18 @@ typedef TCGv_i64 TCGv;#error Unhandled TARGET_LONG_BITS value#endif +/* +* See tcg_gen_lookup_and_goto_ptr_tmp(). @pc may be NULL, for a target +* whose guest PC is not directly the key a destination block is found by. +* A translator that is built for more than one value of TARGET_LONG_BITS, +* and so cannot include this header, calls the _tmp() form directly. +*/ +static inline void +tcg_gen_lookup_and_goto_ptr (TCGv pc,const TranslationBlock *tb) +{ +tcg_gen_lookup_and_goto_ptr_tmp (pc ?tcgv_tl_temp (pc) :NULL , tb); +} +#if TARGET_LONG_BITS ==64 #define tcg_gen_movi_tl tcg_gen_movi_i64#define tcg_gen_mov_tl tcg_gen_mov_i64
target/alpha/translate.c +2 -2
@@ -449,7 +449,7 @@ static void gen_goto_tb(DisasContext *ctx, unsigned tb_slot_idx, int32_t disp)tcg_gen_exit_tb (ctx->base.tb, tb_slot_idx); }else {gen_pc_disp (ctx, cpu_pc, disp); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (cpu_pc, ctx->base.tb); } }
@@ -2917,7 +2917,7 @@ static void alpha_tr_tb_stop(DisasContextBase *dcbase, CPUState *cpu)gen_pc_disp (ctx, cpu_pc,0 );/* FALLTHRU */ case DISAS_PC_UPDATED : -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (cpu_pc, ctx->base.tb);break ;case DISAS_PC_UPDATED_NOCHAIN :tcg_gen_exit_tb (NULL ,0 );
target/arm/tcg/translate-a64.c +2 -2
@@ -562,7 +562,7 @@ static void gen_goto_tb(DisasContext *s, unsigned tb_slot_idx, int64_t diff)if (s->ss_active) {gen_step_complete_exception (s); }else { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , s->base.tb); s->base.is_jmp =DISAS_NORETURN ; } }
@@ -11250,7 +11250,7 @@ static void aarch64_tr_tb_stop(DisasContextBase *dcbase, CPUState *cpu)gen_a64_update_pc (dc,4 );/* fall through */ case DISAS_JUMP : -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , dc->base.tb);break ;case DISAS_NORETURN :case DISAS_SWI :
target/arm/tcg/translate.c +5 -5
@@ -1306,9 +1306,9 @@ void write_neon_element64(TCGv_i64 src, int reg, int ele, MemOp memop) } } -static void gen_goto_ptr (void ) +static void gen_goto_ptr (DisasContext *s) { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr_tmp (NULL , s->base.tb); }/* This will end the TB but doesn't guarantee we'll return to
@@ -1336,7 +1336,7 @@ static void gen_goto_tb(DisasContext *s, unsigned tb_slot_idx, int64_t diff)tcg_gen_exit_tb (s->base.tb, tb_slot_idx); }else {gen_update_pc (s, diff); -gen_goto_ptr (); +gen_goto_ptr (s); } s->base.is_jmp =DISAS_NORETURN ; }
@@ -1373,7 +1373,7 @@ static void gen_jmp_tb(DisasContext *s, int64_t diff, int tbno)* and don't chain to another TB. */ gen_update_pc (s, diff); -gen_goto_ptr (); +gen_goto_ptr (s); s->base.is_jmp =DISAS_NORETURN ;break ;default :
@@ -6858,7 +6858,7 @@ static void arm_tr_tb_stop(DisasContextBase *dcbase, CPUState *cpu)gen_update_pc (dc,curr_insn_len (dc));/* fall through */ case DISAS_JUMP : -gen_goto_ptr (); +gen_goto_ptr (dc);break ;case DISAS_UPDATE_EXIT :gen_update_pc (dc,curr_insn_len (dc));
target/avr/translate.c +2 -2
@@ -992,7 +992,7 @@ static void gen_goto_tb(DisasContext *ctx, unsigned tb_slot_idx,tcg_gen_exit_tb (tb, tb_slot_idx); }else {tcg_gen_movi_i32 (cpu_pc, dest); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb); } ctx->base.is_jmp =DISAS_NORETURN ; }
@@ -2778,7 +2778,7 @@ static void avr_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)/* fall through */ case DISAS_LOOKUP :if (!force_exit) { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb);break ; }/* fall through */
target/hexagon/translate.c +2 -2
@@ -181,7 +181,7 @@ static void gen_goto_tb(DisasContext *ctx, unsigned tb_slot_idx,if (move_to_pc) {tcg_gen_movi_tl (hex_gpr[HEX_REG_PC ], dest); } -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb); } }
@@ -218,7 +218,7 @@ static void gen_end_tb(DisasContext *ctx)gen_set_label (skip);gen_goto_tb (ctx,1 , ctx->next_PC, false); }else { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb); } ctx->base.is_jmp =DISAS_NORETURN ;
target/hppa/translate.c +3 -3
@@ -816,7 +816,7 @@ static void gen_goto_tb(DisasContext *ctx, int which,tcg_gen_goto_tb (which);tcg_gen_exit_tb (ctx->base.tb, which); }else { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb); } }
@@ -2027,7 +2027,7 @@ static bool do_ibranch(DisasContext *ctx, unsigned link,store_psw_xb (ctx,PSW_B ); } -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb); ctx->base.is_jmp =DISAS_NORETURN ;return nullify_end (ctx); }
@@ -4838,7 +4838,7 @@ static void hppa_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs) }/* FALLTHRU */ case DISAS_IAQ_N_UPDATED : -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb);break ;case DISAS_EXIT :tcg_gen_exit_tb (NULL ,0 );
target/i386/tcg/translate.c +1 -1
@@ -2005,7 +2005,7 @@ gen_eob(DisasContext *s, int mode) }else if (mode ==DISAS_JUMP &&/* give irqs a chance to happen */ !inhibit_reset) { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , s->base.tb); }else {tcg_gen_exit_tb (NULL ,0 ); }
target/loongarch/tcg/insn_trans/trans_branch.c.inc +1 -1
@@ -27,7 +27,7 @@ static bool trans_jirl(DisasContext *ctx, arg_jirl *a) tcg_gen_mov_tl(cpu_pc, addr); tcg_gen_movi_tl(dest, make_address_pc(ctx, ctx->base.pc_next + 4)); gen_set_gpr(a->rd, dest, EXT_NONE); - tcg_gen_lookup_and_goto_ptr(); + tcg_gen_lookup_and_goto_ptr(cpu_pc, ctx->base.tb); ctx->base.is_jmp = DISAS_NORETURN; return true; }
target/loongarch/tcg/translate.c +2 -2
@@ -111,7 +111,7 @@ static void gen_goto_tb(DisasContext *ctx, unsigned tb_slot_idx, vaddr dest)tcg_gen_exit_tb (ctx->base.tb, tb_slot_idx); }else {tcg_gen_movi_tl (cpu_pc, dest); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (cpu_pc, ctx->base.tb); } }
@@ -311,7 +311,7 @@ static void loongarch_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)switch (ctx->base.is_jmp) {case DISAS_STOP :tcg_gen_movi_tl (cpu_pc, ctx->base.pc_next); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (cpu_pc, ctx->base.tb);break ;case DISAS_TOO_MANY :gen_goto_tb (ctx,0 , ctx->base.pc_next);
target/m68k/translate.c +1 -1
@@ -6095,7 +6095,7 @@ static void m68k_tr_tb_stop(DisasContextBase *dcbase, CPUState *cpu)if (dc->ss_active) {gen_raise_exception_format2 (dc,EXCP_TRACE , dc->pc_prev); }else { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , dc->base.tb); }break ;case DISAS_EXIT :
target/microblaze/translate.c +2 -2
@@ -127,7 +127,7 @@ static void gen_goto_tb(DisasContext *dc, unsigned tb_slot_idx, vaddr dest)tcg_gen_exit_tb (dc->base.tb, tb_slot_idx); }else {tcg_gen_movi_i32 (cpu_pc, dest); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr_tmp (NULL , dc->base.tb); } dc->base.is_jmp =DISAS_NORETURN ; }
@@ -1764,7 +1764,7 @@ static void mb_tr_tb_stop(DisasContextBase *dcb, CPUState *cs)/* Indirect jump (or direct jump w/ goto_tb disabled) */ tcg_gen_mov_i32 (cpu_pc, cpu_btarget);tcg_gen_discard_i32 (cpu_btarget); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr_tmp (NULL , dc->base.tb);return ;default :
target/mips/tcg/nanomips_translate.c.inc +1 -1
@@ -2406,7 +2406,7 @@ static void gen_compute_nanomips_pbalrsc_branch(DisasContext *ctx, int rs, /* unconditional branch to register */ tcg_gen_mov_tl(cpu_PC, btarget); - tcg_gen_lookup_and_goto_ptr(); + tcg_gen_lookup_and_goto_ptr(cpu_PC, ctx->base.tb); } /* nanoMIPS Branches */
target/mips/tcg/translate.c +3 -3
@@ -4374,7 +4374,7 @@ static void gen_goto_tb(DisasContext *ctx, unsigned tb_slot_idx,tcg_gen_exit_tb (ctx->base.tb, tb_slot_idx); }else {gen_save_pc (dest); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (cpu_PC, ctx->base.tb); } }
@@ -11014,7 +11014,7 @@ static void gen_branch(DisasContext *ctx, int insn_bytes) }else {tcg_gen_mov_tl (cpu_PC, btarget); } -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (cpu_PC, ctx->base.tb);break ;default :LOG_DISAS ("unknown branch 0x%x\n" , proc_hflags);
@@ -15244,7 +15244,7 @@ static void mips_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)switch (ctx->base.is_jmp) {case DISAS_STOP :gen_save_pc (ctx->base.pc_next); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (cpu_PC, ctx->base.tb);break ;case DISAS_NEXT :case DISAS_TOO_MANY :
target/or1k/translate.c +2 -2
@@ -1605,7 +1605,7 @@ static void openrisc_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)/* The jump destination is indirect/computed; use jmp_pc. */ tcg_gen_mov_i32 (cpu_pc, jmp_pc);tcg_gen_discard_i32 (jmp_pc); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , dc->base.tb);break ; }/* The jump destination is direct; use jmp_pc_imm.
@@ -1622,7 +1622,7 @@ static void openrisc_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)break ; }tcg_gen_movi_i32 (cpu_pc, jmp_dest); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , dc->base.tb);break ;case DISAS_EXIT :
target/ppc/translate.c +2 -2
@@ -3664,7 +3664,7 @@ static void gen_lookup_and_goto_ptr(DisasContext *ctx)pmu_count_insns (ctx); } -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (cpu_nip, ctx->base.tb); } }
@@ -6690,7 +6690,7 @@ static void ppc_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)pmu_count_insns (ctx); } -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (cpu_nip, ctx->base.tb);break ;case DISAS_EXIT_UPDATE :
target/riscv/tcg/insn_trans/trans_rvzce.c.inc +2 -2
@@ -213,7 +213,7 @@ static bool gen_pop(DisasContext *ctx, arg_cmpp *a, bool ret, bool ret_val) } #endif tcg_gen_mov_tl(cpu_pc, ret_addr); - tcg_gen_lookup_and_goto_ptr(); + tcg_gen_lookup_and_goto_ptr(NULL, ctx->base.tb); ctx->base.is_jmp = DISAS_NORETURN; }
@@ -334,7 +334,7 @@ static bool trans_cm_jalt(DisasContext *ctx, arg_cm_jalt *a) tcg_gen_mov_tl(cpu_pc, addr); - tcg_gen_lookup_and_goto_ptr(); + tcg_gen_lookup_and_goto_ptr(NULL, ctx->base.tb); ctx->base.is_jmp = DISAS_NORETURN; return true; }
target/riscv/tcg/translate.c +1 -1
@@ -287,7 +287,7 @@ static void lookup_and_goto_ptr(DisasContext *ctx) gen_helper_itrigger_match(tcg_env); }#endif -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb); }static void exit_tb (DisasContext *ctx)
target/rx/translate.c +2 -2
@@ -161,7 +161,7 @@ static void gen_goto_tb(DisasContext *dc, unsigned tb_slot_idx, vaddr dest)tcg_gen_exit_tb (dc->base.tb, tb_slot_idx); }else {tcg_gen_movi_i32 (cpu_pc, dest); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , dc->base.tb); } dc->base.is_jmp =DISAS_NORETURN ; }
@@ -2242,7 +2242,7 @@ static void rx_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)gen_goto_tb (ctx,0 , dcbase->pc_next);break ;case DISAS_JUMP : -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb);break ;case DISAS_UPDATE :tcg_gen_movi_i32 (cpu_pc, ctx->base.pc_next);
target/s390x/tcg/translate.c +3 -2
@@ -1162,7 +1162,7 @@ static DisasJumpType help_branch(DisasContext *s, DisasCompare *c,tcg_gen_goto_tb (0 );tcg_gen_exit_tb (s->base.tb,0 ); }else { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr_tmp (tcgv_i64_temp (psw_addr), s->base.tb); }gen_set_label (lab);
@@ -6477,7 +6477,8 @@ static void s390x_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)if (dc->exit_to_mainloop) {tcg_gen_exit_tb (NULL ,0 ); }else { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr_tmp (tcgv_i64_temp (psw_addr), + dc->base.tb); }break ;default :
target/sh4/translate.c +2 -2
@@ -242,7 +242,7 @@ static void gen_goto_tb(DisasContext *ctx, unsigned tb_slot_idx, vaddr dest)if (use_exit_tb (ctx)) {tcg_gen_exit_tb (NULL ,0 ); }else { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb); } } ctx->base.is_jmp =DISAS_NORETURN ;
@@ -258,7 +258,7 @@ static void gen_jump(DisasContext * ctx)if (use_exit_tb (ctx)) {tcg_gen_exit_tb (NULL ,0 ); }else { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb); } ctx->base.is_jmp =DISAS_NORETURN ; }else {
target/sparc/translate.c +2 -2
@@ -376,7 +376,7 @@ static void gen_goto_tb(DisasContext *s, unsigned tb_slot_idx,/* jump to another page: we can use an indirect jump */ tcg_gen_movi_tl (cpu_pc, pc);tcg_gen_movi_tl (cpu_npc, npc); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , s->base.tb); } }
@@ -5807,7 +5807,7 @@ static void sparc_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs)tcg_gen_movi_tl (cpu_npc, dc->npc); }if (may_lookup) { -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , dc->base.tb); }else {tcg_gen_exit_tb (NULL ,0 ); }
target/tricore/translate.c +2 -2
@@ -2857,7 +2857,7 @@ static void gen_goto_tb(DisasContext *ctx, unsigned tb_slot_index, vaddr dest)tcg_gen_exit_tb (ctx->base.tb, tb_slot_index); }else {gen_save_pc (dest); -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb); } ctx->base.is_jmp =DISAS_NORETURN ; }
@@ -8478,7 +8478,7 @@ static void tricore_tr_tb_stop(DisasContextBase *dcbase, CPUState *cpu)tcg_gen_exit_tb (NULL ,0 );break ;case DISAS_JUMP : -tcg_gen_lookup_and_goto_ptr (); +tcg_gen_lookup_and_goto_ptr (NULL , ctx->base.tb);break ;case DISAS_NORETURN :break ;
tcg/tcg-op.c +2 -1
@@ -2715,7 +2715,7 @@ void tcg_gen_goto_tb(unsigned idx)tcg_gen_op1i (INDEX_op_goto_tb,0 , idx); } -void tcg_gen_lookup_and_goto_ptr (void ) +void tcg_gen_lookup_and_goto_ptr_tmp (TCGTemp *pc,const TranslationBlock *tb) {TCGv_ptr ptr;
@@ -2725,6 +2725,7 @@ void tcg_gen_lookup_and_goto_ptr(void) }plugin_gen_disable_mem_helpers (); + ptr =tcg_temp_ebb_new_ptr ();gen_helper_lookup_tb_ptr (ptr, tcg_env);tcg_gen_op1i (INDEX_op_goto_ptr,TCG_TYPE_PTR ,tcgv_ptr_arg (ptr));
Signature · 1 line
2.54.0
Re: [PATCH v4 4/9] tcg: pass the destination to tcg_gen_lookup_and_goto_ptr()
Quoted 32 lines · Matt Turner
tcg_gen_lookup_and_goto_ptr()takes no arguments and emits a call tohelper_lookup_tb_ptr(), which recovers the destination PC from env by calling back into the target throughTCGCPUOps::get_tb_cpu_state(). At translation time the caller already has the destination PC in a temp, and knows the flags, cflags andcs_baseany destination it may reach has to match, because they are the ones the block being generated was translated with.Pass both, so that a later patch can use them to look the destination up inline. Nothing reads them yet and the generated code does not change.
The contract on @pc is the whole of the interface: it must hold exactly what
get_tb_cpu_state()reports as the pc for the destination block. Five targets keep their PC in a temp whose value is that pc by construction and so can pass it: alpha, loongarch, mips, ppc and s390x. Everything else passes NULL and keeps today's behavior.For six of those the TB pc is derived and passing the PC temp would be
wrong: avr's TB pc is the word address doubled, i386's is eip before segmentation, riscv masks it to 32 bits when xl isMXL_RV32, hppa derives it from the IAQ, hexagon adjusts it inside a hardware loop, and sparc puts npc incs_base. The remaining seven -- arm, m68k, microblaze, or1k, rx, sh4 and tricore -- look like they could pass it, but I have not convinced myself of the contract for them and have nothing to test them with. Each is a one-line change for whoever wants it.The common entry point takes a TCGTemp rather than a TCGv and reads the width from it, because the translators that are built for both values of
TARGET_LONG_BITS-- arm, s390x, microblaze -- cannot includetcg-op.h.tcg-op.hwraps it for everyone else. This is the same split as tcg_gen_qemu_ld_*_chk().
Quoted 6 lines
v4: Split out of "tcg: probe the TB jump cache inline instead of calling a
helper", which did the API change and the inline probe in one patch. Requested by Richard Henderson.Signed-off-by Matt Turner<[email protected]>---
Ok, I was a bit surprised at your claim that only 5 targets qualify, as there are plenty that have a simple PC.
However! The subtlety of the interface, that we are asserting that the current TranslationBlock flags are still valid, now leads me to think that it's a mistake to adjust the current interface.
We need to introduce a new interface to which targets may be migrated. This won't be difficult, but it's not entirely trivial.
For instance, target/arm/ has
case DISAS_UPDATE_NOCHAIN:
gen_update_pc(dc, curr_insn_len(dc));
/* fall through */
case DISAS_JUMP:
gen_goto_ptr();
break;where DISAS_UPDATE_NOCHAIN requires the helper because of state change and DISAS_JUMP does not.
This is subtle enough that we probably want to verify that the flags are unchanged with --enable-debug-tcg.
Perhaps tcg_gen_goto_jc_{i32,i64,tl)?
BTW:
Quoted 8 lines
include/tcg/tcg-op.h +2
-0@@ -49,6 +49,18 @@ typedef TCGv_i64 TCGv;#error Unhandled TARGET_LONG_BITS value#endif +/* +* See tcg_gen_lookup_and_goto_ptr_tmp(). @pc may be NULL, for a target
include/tcg/tcg-op.h typedef TCGv_i64 TCGv; · line 63
Quoted 10 lines
include/tcg/tcg-op.h +10
-0+* whose guest PC is not directly the key a destination block is found by. +* A translator that is built for more than one value of TARGET_LONG_BITS, +* and so cannot include this header, calls the _tmp() form directly. +*/ +static inline void +tcg_gen_lookup_and_goto_ptr (TCGv pc,const TranslationBlock *tb) +{ +tcg_gen_lookup_and_goto_ptr_tmp (pc ?tcgv_tl_temp (pc) :NULL , tb); +} +
This needs adjustment. As we migrate binaries to single-binary, we start building bits of code once and stop relying on TARGET_LONG_BITS. Notice where we include "tcg-op-common.h" instead of "tcg-op.h".
The simplest solution, IMO is to define functions for _i32 and _i64, as for most everything else, and to have a _tl alias in tcg-op.h.
r~
Re: [PATCH v4 4/9] tcg: pass the destination to tcg_gen_lookup_and_goto_ptr()
Quoted 60 lines · Richard Henderson
Quoted 32 lines · Matt Turner
tcg_gen_lookup_and_goto_ptr()takes no arguments and emits a call tohelper_lookup_tb_ptr(), which recovers the destination PC from env by calling back into the target throughTCGCPUOps::get_tb_cpu_state(). At translation time the caller already has the destination PC in a temp, and knows the flags, cflags andcs_baseany destination it may reach has to match, because they are the ones the block being generated was translated with.Pass both, so that a later patch can use them to look the destination up inline. Nothing reads them yet and the generated code does not change.
The contract on @pc is the whole of the interface: it must hold exactly what
get_tb_cpu_state()reports as the pc for the destination block. Five targets keep their PC in a temp whose value is that pc by construction and so can pass it: alpha, loongarch, mips, ppc and s390x. Everything else passes NULL and keeps today's behavior.For six of those the TB pc is derived and passing the PC temp would be
wrong: avr's TB pc is the word address doubled, i386's is eip before segmentation, riscv masks it to 32 bits when xl isMXL_RV32, hppa derives it from the IAQ, hexagon adjusts it inside a hardware loop, and sparc puts npc incs_base. The remaining seven -- arm, m68k, microblaze, or1k, rx, sh4 and tricore -- look like they could pass it, but I have not convinced myself of the contract for them and have nothing to test them with. Each is a one-line change for whoever wants it.The common entry point takes a TCGTemp rather than a TCGv and reads the width from it, because the translators that are built for both values of
TARGET_LONG_BITS-- arm, s390x, microblaze -- cannot includetcg-op.h.tcg-op.hwraps it for everyone else. This is the same split as tcg_gen_qemu_ld_*_chk().Quoted 6 lines
v4: Split out of "tcg: probe the TB jump cache inline instead of calling a
helper", which did the API change and the inline probe in one patch. Requested by Richard Henderson.Signed-off-by Matt Turner<[email protected]>---
Ok, I was a bit surprised at your claim that only 5 targets qualify, as there are plenty that have a simple PC.
However! The subtlety of the interface, that we are asserting that the current TranslationBlock flags are still valid, now leads me to think that it's a mistake to adjust the current interface.
We need to introduce a new interface to which targets may be migrated. This won't be difficult, but it's not entirely trivial.
For instance, target/arm/ has
case DISAS_UPDATE_NOCHAIN: gen_update_pc(dc, curr_insn_len(dc)); /* fall through */ case DISAS_JUMP: gen_goto_ptr(); break;
Quoted 5 lines
where
DISAS_UPDATE_NOCHAINrequires the helper because of state change andDISAS_JUMPdoes not.This is subtle enough that we probably want to verify that the flags are unchanged with --enable-debug-tcg.
Agreed, and done. tcg_gen_lookup_and_goto_ptr(void) is unchanged in v5. Nothing that isn't migrated sees any difference.
Quoted 1 line
Perhaps tcg_gen_goto_jc_{i32,i64,tl)?
Sounds good. Done.
Replying to bits out of order:
Quoted 2 lines
The simplest solution, IMO is to define functions for
_i32and_i64, as for most everything else, and to have a_tlalias intcg-op.h.
Also done -- the _tmp()/TCGTemp form is gone. tcg_gen_goto_jc_i32() and tcg_gen_goto_jc_i64() are declared in tcg-op-common.h, and tcg-op.h has the _tl alias in each TARGET_LONG_BITS arm alongside the qemu_ld/st ones. The _i32 entry point zero-extends into a temp and shares the body, so there is one implementation.
s390x is the one migrated target that cannot include tcg-op.h, so it calls tcg_gen_goto_jc_i64(psw_addr) directly; that reads fine.
Quoted 3 lines
the subtlety is asserting that the current TB flags are still valid ... target/arm:
DISAS_UPDATE_NOCHAINrequires the helper because of the state change,DISAS_JUMPdoes not.
Right, and that distinction is exactly what the new interface makes the caller state. The contract is now written dow the goto_jc runs, the CPU state must already be the destination's -- @pc must be what get_tb_cpu_state() would report, it would report must be the ones this block was translated with. A translator that hasn't finished updating state lookup key (avr's word address, i386's eip before segmentation), keeps using tcg_gen_lookup_and_goto_ptr().
Quoted 2 lines
we probably want to verify that the flags ar
--enable-debug-tcg
Done. Under CONFIG_DEBUG_TCG the goto_jc emits a call to a new helper_goto_jc_check(env, pc, flags, cs_base), get_tb_cpu_state() and asserts all three against what the block was translated with. It costs nothing in a normal contract being stated rather than assumed while I migrated the targets.
Five targets are migrated in v5: alpha, loongarch, mips, ppc and s390x -- the ones whose lookup_and_goto_ptr sites are u already the destination's, and the pc register is the key". arm, i386 and the rest are untouched and can be migrated point of it being a separate interface.
All five build and run their indirect-dispatch paths (computed goto, function pointers, returns, and a longjmp out completion under --enable-debug-tcg, so the assert has actually been exercised on each.
PATCH v4 5/9 accel/tcg: give the TB jump cache a second base pointer for generated code
In reply to Matt TurnerAdd CPUState::tb_jmp_cache_probe, a base pointer that only generated code will read. Normally it is cpu->tb_jmp_cache. Pointing it instead at a shared, permanently zero-filled CPUJumpCache makes every entry generated code finds have a NULL tb, so every lookup done through it misses. The real jump cache is not touched, so nothing is lost and recovery is a single store.
Nothing reads it yet. The next patch probes the jump cache from generated code, and that probe cannot check everything helper_lookup_tb_ptr() checks; poisoning this pointer is how the conditions it cannot check force it back into the helper. The one that matters here is breakpoints. check_for_breakpoints() raises EXCP_DEBUG on an exact pc match and selects CF_BP_PAGE cflags for the rest of the page, and inserting a breakpoint deliberately invalidates no TB, so a block translated before the breakpoint was set is still sitting in the jump cache and would be dispatched to directly.
cpu_breakpoint_insert() poisons the target CPU, rather than leaving it to that CPU's own main loop, because gdb inserts a breakpoint into every CPU (tcg_insert_gdbstub_breakpoint()) and a thread already inside generated code dispatching to itself need never return to its main loop. The main loop puts the pointer back once the last breakpoint is gone, re-checking after the store so that it loses a race with a concurrent insert in the safe direction.
The poison cache is a plain static rather than a const one so that it lands in .bss: a megabyte of const zeroes would be a megabyte of .rodata in every emulator binary, whereas .bss costs nothing on disk and faults in only the handful of pages a poisoned run happens to probe.
v4: Split out of "tcg: probe the TB jump cache inline instead of calling a
helper". Requested by Richard Henderson.
v4: Make the poison a static object rather than allocating one on first
use. Suggested by Richard Henderson, who asked for const; see above for why it is not.
--- accel/stubs/tcg-stub.c | 6 ++- accel/tcg/cpu-exec.c | 96 +++++++++++++++++++++++++++++++++++++ accel/tcg/internal-common.h | 2 + cpu-common.c | 11 +++++ include/hw/core/cpu.h | 9 ++++ include/system/tcg.h | 9 ++++ 6 files changed, 132 insertions(+), 1 deletion(-)
accel/stubs/tcg-stub.c +5 -1
@@ -1,6 +1,6 @@/* * Stubs for the TCG entry points in system/tcg.h, for binaries that link -* cpu-target.c or the HMP command handlers but not TCG. +* cpu-target.c, cpu-common.c or the HMP command handlers but not TCG. * * SPDX-License-Identifier: GPL-2.0-or-later */
@@ -14,3 +14,7 @@ void tcg_update_cflags(CPUState *cpu)void tcg_update_all_cflags (void ) { } + +void tcg_cpu_poison_jmp_cache (CPUState *cpu) +{ +}
accel/tcg/cpu-exec.c +96 -0
119 lines not on this page · raw message
accel/tcg/internal-common.h +2 -0
@@ -144,6 +144,8 @@ void page_table_config_init(void); G_NORETURN void cpu_io_recompile(CPUState *cpu, uintptr_t retaddr);#endif /* CONFIG_USER_ONLY */ +void tcg_cpu_sync_jmp_cache (CPUState *cpu); +void tb_phys_invalidate (TranslationBlock *tb,tb_page_addr_t page_addr);void tb_set_jmp_target (TranslationBlock *tb,int n,uintptr_t addr);
cpu-common.c +11 -0
@@ -22,6 +22,7 @@#include "exec/cpu-common.h" #include "hw/core/cpu.h" #include "qemu/lockable.h" +#include "system/tcg.h" #include "trace/trace-root.h" QemuMutex qemu_cpu_list_lock;
@@ -429,6 +430,16 @@ int cpu_breakpoint_insert(CPUState *cpu, vaddr pc, int flags, *breakpoint = bp; } +/* +* Nothing is invalidated here, so blocks translated before this point +* are still live and still dispatch to each other without consulting +* cpu->breakpoints. Stop the ones that can: a TCG vCPU dispatching +* inline reads a base pointer that this poisons, so the next dispatch +* takes the slow path and sees the new breakpoint. @cpu may be another +* thread, and may be running. +*/ +tcg_cpu_poison_jmp_cache (cpu); +trace_breakpoint_insert (cpu->cpu_index, pc, flags);return 0 ; }
include/hw/core/cpu.h +9 -0
@@ -519,6 +519,15 @@ struct CPUState {MemoryRegion *memory;struct CPUJumpCache *tb_jmp_cache; +/* +* @tb_jmp_cache_probe: base the inline jump cache probe reads. +* +* Normally @tb_jmp_cache. Pointed at a shared page of zeroes to force +* every inline dispatch to miss and fall back to helper_lookup_tb_ptr(); +* see tcg_cpu_sync_jmp_cache(). NULL before tcg_exec_realizefn() and +* after tcg_exec_unrealizefn(). +*/ +struct CPUJumpCache *tb_jmp_cache_probe;GArray *gdb_regs;int gdb_num_regs;
include/system/tcg.h +9 -0
@@ -29,6 +29,15 @@ extern bool tcg_allowed;void tcg_update_cflags (CPUState *cpu);void tcg_update_all_cflags (void ); +/* +* Force @cpu's generated code back into the slow dispatch path, which +* re-checks everything the inline jump cache probe assumes. Safe to call +* from any thread, and a no-op for a CPU that is not running TCG. Call +* whenever something the probe cannot see changes under a running vCPU; +* the main loop undoes it once the reason is gone. +*/ +void tcg_cpu_poison_jmp_cache (CPUState *cpu); +/** * qemu_tcg_mttcg_enabled: * Check whether we are running MultiThread TCG or not.
Signature · 1 line
2.54.0
Re: [PATCH v4 5/9] accel/tcg: give the TB jump cache a second base pointer for generated code
Quoted 5 lines · Matt Turner
accel/tcg/cpu-exec.c +5
-0+/* +* The inline jump cache probe reads cpu->tb_jmp_cache_probe and takes the +* slow path when the entry it finds has a NULL tb. Pointing the probe at a +* region that is all zeroes therefore forces every indirect dispatch into +* helper_lookup_tb_ptr(), which does the full lookup the inline probe only
accel/tcg/cpu-exec.c static inline bool cpu_handle_exception(CPUState *cpu, int *ret) · line 769
Quoted 10 lines
accel/tcg/cpu-exec.c +10
-0+* approximates. The real jump cache is untouched, so no contents are lost +* and recovery is a single store. +* +* Only ever read from, and only one entry per dispatch, so one shared +* zero-filled cache is enough for every CPU. Not const: that would put a +* megabyte of zeroes in .rodata and so in the binary, where .bss costs +* nothing on disk and only faults in the handful of pages a poisoned run +* happens to probe. +*/ +static CPUJumpCache tb_jmp_cache_poison;
Hmm. Maybe we should mmap it at startup then, because while we're not supposed to be writing into this, it would be nice to enforce that.
Quoted 7 lines
accel/tcg/cpu-exec.c +7
-0+/* +* Poison @cpu's probe, from any thread. Called when a breakpoint is +* inserted, which is what makes the poison take effect at the dispatch +* after the insert rather than whenever @cpu next reaches its main loop: +* a vCPU chaining indirectly need never reach it, and would run past a +* breakpoint another thread had just set. +*
accel/tcg/cpu-exec.c static inline bool cpu_handle_exception(CPUState *cpu, int *ret) · line 804
Quoted 10 lines
accel/tcg/cpu-exec.c +10
-0+* A plain store is enough. The value only ever costs a slow path that is +* correct on its own, and the generated code re-reads the base on every +* dispatch. Un-poisoning is tcg_cpu_sync_jmp_cache()'s job. +*/ +void tcg_cpu_poison_jmp_cache (CPUState *cpu) +{ +if (qatomic_read (&cpu->tb_jmp_cache_probe) !=NULL ) { +qatomic_set (&cpu->tb_jmp_cache_probe, &tb_jmp_cache_poison); + } +}
Why do we need to check for NULL?
accel/tcg/cpu-exec.c static inline bool cpu_handle_exception(CPUState *cpu, int *ret) · line 817
Quoted 13 lines
accel/tcg/cpu-exec.c +13
-0+ +/* +* Called from the main loop, which is the only context that can establish +* that no reason to be poisoned is left. Cheap enough to call every time +* round: the common case is a load, a compare and no store at all. +*/ +void tcg_cpu_sync_jmp_cache (CPUState *cpu) +{ +CPUJumpCache *want; + +if (qatomic_read (&cpu->tb_jmp_cache_probe) ==NULL ) { +return ;/* not realized, or already unrealized */ + }
If this function is only called by the main loop, we shouldn't have to deal with either unrealized state.
Quoted 9 lines
accel/tcg/cpu-exec.c +9
-0+ + want =tcg_cpu_may_dispatch (cpu) + ? cpu->tb_jmp_cache + : &tb_jmp_cache_poison; + +if (qatomic_read (&cpu->tb_jmp_cache_probe) != want) { +qatomic_set (&cpu->tb_jmp_cache_probe, want); + +if (want == cpu->tb_jmp_cache) {
accel/tcg/cpu-exec.c static inline bool cpu_handle_exception(CPUState *cpu, int *ret) · line 836
Quoted 10 lines
accel/tcg/cpu-exec.c +10
-0+/* +* Un-poisoning races a concurrent tcg_cpu_poison_jmp_cache(): +* the reason may have appeared after tcg_cpu_may_dispatch() read +* it, and the poison may have landed before the store above. +* Order that store against the re-read below, so that the race +* is lost in the safe direction. +*/ +smp_mb (); +if (!tcg_cpu_may_dispatch (cpu)) { +tcg_cpu_poison_jmp_cache (cpu);
Why do we need to check for breakpoints twice?
I don't think I understand this race.
I'm not familiar with how gdbstub interacts with user threads, but this feels overly complicated. Up to and including needing to poison the jump cache just for adding a breakpoint.
I suspect what we need is to add a CF_NO_GOTO_JC flag that suppresses the inline jump cache, which is set whenever any breakpoint exists, which falls back to the helper, which checks for breakpoints.
Conveniently, you've already shown how to adjust tcg_cflags from gdbstub. :-)
r~
Re: [PATCH v4 5/9] accel/tcg: give the TB jump cache a second base pointer for generated code
Quoted 12 lines · Richard Henderson
Quoted 10 lines · Matt Turner
+/*
+ * The inline jump cache probe readscpu->tb_jmp_cache_probeand takes the
+ * slow path when the entry it finds has a NULL tb. Pointing the probe at a
+ * region that is all zeroes therefore forces every indirect dispatch into
+ *helper_lookup_tb_ptr(), which does the full lookup the inline probe only
+ * approximates. The real jump cache is untouched, so no contents are lost
+ * and recovery is a single store.
+ *
+ * Only ever read from, and only one entry per dispatch, so one shared
+ * zero-filled cache is enough for every CPU. Not const: that would put a
Quoted 8 lines
Quoted 5 lines
+ * megabyte of zeroes in .rodata and so in the binary, where .bss costs
+ * nothing on disk and only faults in the handful of pages a poisoned run
+ * happens to probe.
+ */
+static CPUJumpCachetb_jmp_cache_poison;Hmm. Maybe we should mmap it at startup then, because while we're not supposed to be writing into this, it would be nice to enforce that.
Done, also in 8/9. It's a page-aligned qemu_memalign() + mprotect at startup instead of a .bss object, which also removes the "1MB never written" note from that patch's RFC list. I added qemu_mprotect_ro() next to the existing _rw/_rwx/_none forms for it. A stray store into a page every vCPU dispatches through is worth trapping rather than debugging.
Quoted 11 lines
Quoted 11 lines
+/*
+ * Poison @cpu's probe, from any thread. Called when a breakpoint is
+ * inserted, which is what makes the poison take effect at the dispatch
+ * after the insert rather than whenever @cpu next reaches its main loop:
+ * a vCPU chaining indirectly need never reach it, and would run past a
+ * breakpoint another thread had just set.
+ *
+ * A plain store is enough. The value only ever costs a slow path that is
+ * correct on its own, and the generated code re-reads the base on every
+ * dispatch. Un-poisoning is tcg_cpu_sync_jmp_cache()'s job.
+ */
Quoted 8 lines
accel/tcg/cpu-exec.c static inline bool cpu_handle_exception(CPUState *cpu, int *ret) · line 804
Quoted 6 lines
accel/tcg/cpu-exec.c +6
-0+void tcg_cpu_poison_jmp_cache (CPUState *cpu) +{ +if (qatomic_read (&cpu->tb_jmp_cache_probe) !=NULL ) { +qatomic_set (&cpu->tb_jmp_cache_probe, &tb_jmp_cache_poison); + } +}Why do we need to check for NULL?
Fixed, see below.
Quoted 31 lines
accel/tcg/cpu-exec.c static inline bool cpu_handle_exception(CPUState *cpu, int *ret) · line 817
Quoted 13 lines
accel/tcg/cpu-exec.c +13
-0+ +/* +* Called from the main loop, which is the only context that can establish +* that no reason to be poisoned is left. Cheap enough to call every time +* round: the common case is a load, a compare and no store at all. +*/ +void tcg_cpu_sync_jmp_cache (CPUState *cpu) +{ +CPUJumpCache *want; + +if (qatomic_read (&cpu->tb_jmp_cache_probe) ==NULL ) { +return ;/* not realized, or already unrealized */ + }If this function is only called by the main loop, we shouldn't have to deal with either unrealized state.
Quoted 14 lines
accel/tcg/cpu-exec.c +14
-0+ + want =tcg_cpu_may_dispatch (cpu) + ? cpu->tb_jmp_cache + : &tb_jmp_cache_poison; + +if (qatomic_read (&cpu->tb_jmp_cache_probe) != want) { +qatomic_set (&cpu->tb_jmp_cache_probe, want); + +if (want == cpu->tb_jmp_cache) { +/* +* Un-poisoning races a concurrent tcg_cpu_poison_jmp_cache(): +* the reason may have appeared after tcg_cpu_may_dispatch() read +* it, and the poison may have landed before the store above. +* Order that store against the re-read below, so that the race
Quoted 8 lines
accel/tcg/cpu-exec.c static inline bool cpu_handle_exception(CPUState *cpu, int *ret) · line 836
Quoted 5 lines
accel/tcg/cpu-exec.c +5
-0+* is lost in the safe direction. +*/ +smp_mb (); +if (!tcg_cpu_may_dispatch (cpu)) { +tcg_cpu_poison_jmp_cache (cpu);Why do we need to check for breakpoints twice?
I don't think I understand this race.
Fixed, see below.
Quoted 7 lines
I'm not familiar with how gdbstub interacts with user threads, but this feels overly complicated. Up to and including needing to poison the jump cache just for adding a breakpoint.
I suspect what we need is to add a
CF_NO_GOTO_JCflag that suppresses the inline jump cache, which is set whenever any breakpoint exists, which falls back to the helper, which checks for breakpoints.
You're right, and this is much better. v5 replaces this patch with "accel/tcg: add CF_NO_GOTO_JC, set while a breakpoint is present".
What makes the cflag sufficient rather than merely convenient: the inline probe already compares the destination TB's cflags against the constant cflags of the block doing the dispatching, and only takes the destination when they're equal. So a block translated while a breakpoint exists neither dispatches inline itself nor can be reached by a block that does. tcg_update_cflags() sets the flag while cpu->breakpoints is non-empty, and cpu_breakpoint_insert()/cpu_breakpoint_remove_by_ref() call it -- the only two places the list changes, both of which already run on the CPU's own thread or with it stopped, or reach another CPU exactly the way cpu_single_step() does.
That deletes the entire mechanism you were objecting to. The cross-thread poison from breakpoint insertion, the un-poison, and the double breakpoint check are all gone, so the questions above mostly answer themselves.
PATCH v4 6/9 RFC: tcg: probe the TB jump cache inline instead of calling a helper
In reply to Matt TurnerEvery indirect branch that cannot use goto_tb ends in tcg_gen_lookup_and_goto_ptr(), which calls helper_lookup_tb_ptr(). For an emulated compiler that is 8.4 billion helper calls in a single translation
unit: 24.6% of all TB exits take this path, because jsr/ret/jmp have a register destination and because goto_tb is restricted to same-page targets.
The helper itself is already tight, but each call pays for a call frame, the can_do_io store, the get_tb_cpu_state() indirect call through TCGCPUOps, curr_cflags(), and a breakpoint check, before it gets to the jump cache probe that almost always hits (95.8% for this workload).
Emit the probe inline instead. The two preceding patches supply what it
needs: the destination PC is in a TCG temp, the flags, cflags and cs_base the destination must match are constants at translation time, and tb_jmp_cache_probe is a base pointer the main loop can poison. The fast path is therefore a hash, four guarded loads and a goto_ptr. Only a miss calls the helper, which still owns filling the cache.
Two details matter for the generated code. The flags and cflags guards are folded into a single aligned 64-bit load and compare, since the fields are adjacent. And each path emits its own goto_ptr rather than branching to a shared one: a temp live across the label is spilled and reloaded on every dispatch, which cost 6.3% on its own.
The flags and cflags constants are safe against the other things that can change them. CF_PARALLEL is only ever set by begin_parallel_context(), which flushes first, so no block predating it survives to dispatch. gdb single-step is only turned on with the CPU stopped, and a block translated without CF_SINGLE_STEP can only be re-entered through tb_lookup(), which from then on demands the new cflags -- so a stale-cflags block is never the one running. What is left is one_insn_per_tb and -d nochain, which the monitor can toggle under a running vCPU without a flush; see below.
Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host, LTO build, on top of the preceding patches:
before: 1,402,667,803,616 instructions
after: 916,415,123,244 instructions -34.67%
before: 115.56s wall clock
after: 85.59s wall clock -25.94%The gap between the two is the point at which this stops being a straight-line win: the helper call was highly predictable work that the host pipelined well, so removing it retires far fewer instructions than it saves time. IPC falls from 2.48 to 2.17 across this patch for that reason.
Despite emitting more code, this also reduces instruction cache pressure, because a dispatch no longer jumps into qemu's .text and evicts translated code:
before: 11,735,141,703 L1-icache-load-misses
after: 7,154,863,292 L1-icache-load-misses -39.0%The mechanism is visible directly in a profile: helper_lookup_tb_ptr() falls from 31.01% of samples to 0.35%, and qemu's own .text falls from 38.8% to 5.3%, with the balance moving into generated code.
Combined with the preceding patches, against an unmodified LTO build, 1,646,994,254,249 instructions fall to 916,415,123,244, or -44.36%. The emulated compiler produces byte-identical output throughout.
Open issues, hence RFC:
- one_insn_per_tb and CPU_LOG_TB_NOCHAIN can be toggled from the monitor while a vCPU is inside a block that was translated without them. The block keeps dispatching inline with the old cflags until it exits for some other reason. Poisoning the probe from tcg_update_all_cflags() would close it.
- The jump cache entry is read without qatomic_read(); entries are invalidated concurrently by setting tb to NULL.
- Only alpha has been measured. The other four targets that pass a PC are built and boot-tested only.
v4: Split out of the patch that also changed the
tcg_gen_lookup_and_goto_ptr() API and introduced tb_jmp_cache_probe, which are now the two preceding patches. Requested by Richard Henderson.
v4: Emit the softmmu form of tb_jmp_cache_hash_func() under
CONFIG_SOFTMMU rather than the user-only form everywhere. v3 emitted the user-only hash unconditionally, which was wrong for system mode and was only not a correctness bug because a wrong index simply misses. Caught by Richard Henderson. tcg-op.c is compiled once per build rather than once per target, but CONFIG_SOFTMMU is set for it, and TARGET_PAGE_BITS -- a load from target_page here -- is fixed long before any translation happens.
v4: Compare the pc before testing tb for NULL. On a hash miss the pc is
the field most likely to differ, and an unused entry has a zero pc that only pc 0 can match, so the tb test buys nothing ahead of it. Suggested by Richard Henderson.
v4: Assert that offsetof(TranslationBlock, flags) is 8-byte aligned, since
folding the flags and cflags guards into one 64-bit load relies on it and nothing else does. Requested by Richard Henderson.
v4: Zero-extend a 32-bit guest PC instead of falling back to the helper.
Suggested by Richard Henderson. The high half then folds to a compare against zero.
v4: Describe cs_base in the probe as a second word of target-specific
flags rather than by name. Suggested by Richard Henderson.
--- include/tcg/tcg-op-common.h | 14 ++-- tcg/tcg-op.c | 126 ++++++++++++++++++++++++++++++++++++ 2 files changed, 133 insertions(+), 7 deletions(-)
include/tcg/tcg-op-common.h +7 -7
@@ -81,13 +81,13 @@ void tcg_gen_goto_tb(unsigned idx);* * If the TB is not valid, jump to the epilogue. * -* The lookup is a call to helper_lookup_tb_ptr(). @pc and @tb describe the -* destination for a faster lookup that a later patch adds, and neither is -* used yet. When @pc is non-NULL it must hold exactly the value -* get_tb_cpu_state() reports as the pc for the destination, and the -* destination must match @tb's flags, cflags and cs_base. A target whose -* pc is derived rather than being that key -- avr's word address, i386's -* eip before segmentation -- must pass NULL. +* The lookup is normally a call to helper_lookup_tb_ptr(). If @pc is +* non-NULL the jump cache is probed inline instead, and only a miss reaches +* the helper. @pc must then hold exactly the value get_tb_cpu_state() +* reports as the pc for the destination; a target whose pc is derived +* (avr's word address, i386's eip before segmentation) must pass NULL. The +* destination is required to match @tb's flags, cflags and cs_base, which +* is what makes them constants in the probe. * * This operation is optional. If the TCG backend does not implement goto_ptr, * this op is equivalent to calling tcg_gen_exit_tb() with 0 as the argument.
tcg/tcg-op.c +126 -0
144 lines not on this page · raw message
Signature · 1 line
2.54.0
Re: [PATCH v4 6/9] RFC: tcg: probe the TB jump cache inline instead of calling a helper
Quoted 47 lines · Matt Turner
tcg/tcg-op.c +47
-0+static void gen_jmp_cache_probe (TCGv_i64 pc,const TranslationBlock *tb) +{ +TCGv_ptr jc, ent, tbp, ptr; +TCGv_i64 h, tmp; +TCGLabel *slow; +uint64_t fpair; + +QEMU_BUILD_BUG_ON (sizeof (((CPUJumpCache *)0 )->array[0 ]) !=16 ); + QEMU_BUILD_BUG_ON(offsetof(CPUJumpCache, array[0].pc) % 8 != 0); +/* One 64-bit load has to cover both, so they must be adjacent... */ +QEMU_BUILD_BUG_ON (offsetof(TranslationBlock , cflags) != + offsetof(TranslationBlock , flags) +4 ); +/* ...and aligned, which nothing else currently relies on. */ +QEMU_BUILD_BUG_ON (offsetof(TranslationBlock , flags) %8 !=0 ); + + jc =tcg_temp_ebb_new_ptr (); + ent =tcg_temp_ebb_new_ptr (); + tbp =tcg_temp_ebb_new_ptr (); + ptr =tcg_temp_ebb_new_ptr (); + h =tcg_temp_ebb_new_i64 (); + tmp =tcg_temp_ebb_new_i64 (); + slow =gen_new_label (); + +/* ent = &jc->array[tb_jmp_cache_hash_func(pc)] */ +gen_jmp_cache_hash (h, pc); +tcg_gen_shli_i64 (h, h,4 ); + +/* +* Not cpu->tb_jmp_cache: the probe reads its own base so that the main +* loop can poison it, which is how conditions the probe cannot test for +* itself force every dispatch back into the helper. See +* tcg_cpu_sync_jmp_cache(). +*/ +tcg_gen_ld_ptr (jc, tcg_env, + offsetof(CPUState , tb_jmp_cache_probe) -sizeof (CPUState)); +tcg_gen_trunc_i64_ptr (ent, h); +tcg_gen_add_ptr (ent, jc, ent); + +/* +* The pc first: on a hash miss it is the field most likely to differ, +* and an entry whose tb is NULL has a zero pc that only pc 0 matches. +*/ + tcg_gen_ld_i64(tmp, ent, offsetof(CPUJumpCache, array[0].pc)); +tcg_gen_brcond_i64 (TCG_COND_NE , tmp, pc, slow); + + tcg_gen_ld_ptr(tbp, ent, offsetof(CPUJumpCache, array[0].tb)); +tcg_gen_brcondi_ptr (TCG_COND_EQ , tbp,0 , slow);
tcg/tcg-op.c void tcg_gen_goto_tb(unsigned idx) · line 2802
Quoted 10 lines
tcg/tcg-op.c +10
-0+ +/* +* flags and cflags are adjacent uint32_t, so one aligned 64-bit load +* and compare covers both. +*/ +#if HOST_BIG_ENDIAN + fpair = ((uint64_t )tb->flags <<32 ) | tb->cflags; +#else + fpair = ((uint64_t )tb->cflags <<32 ) | tb->flags; +#endif
I'd use
fpair = (HOST_BIG_ENDIAN
? deposit64(tb->cflags, 32, 32, tb->flags)
: deposit64(tb->flags, 32, 32, tb->cflags));Whenever possible, avoid ifdefs to make sure all paths compile on every host.
Quoted 12 lines
tcg/tcg-op.c +12
-0+tcg_gen_ld_i64 (tmp, tbp, offsetof(TranslationBlock , flags)); +tcg_gen_brcondi_i64 (TCG_COND_NE , tmp, fpair, slow); + +/* +* cs_base is a second word of target-specific flags despite the name, +* and the pc alone does not imply it on a target that uses it. +*/ +tcg_gen_ld_i64 (tmp, tbp, offsetof(TranslationBlock , cs_base)); +tcg_gen_brcondi_i64 (TCG_COND_NE , tmp, tb->cs_base, slow); + + tcg_gen_ld_ptr(ptr, tbp, offsetof(TranslationBlock, tc.ptr)); +tcg_gen_op1i (INDEX_op_goto_ptr,TCG_TYPE_PTR ,tcgv_ptr_arg (ptr));
tcg/tcg-op.c void tcg_gen_goto_tb(unsigned idx) · line 2824
Quoted 10 lines
tcg/tcg-op.c +10
-0+ +/* +* Emit a second goto_ptr rather than branching to a shared one: a temp +* live across the label would be spilled and reloaded on every dispatch. +*/ +gen_set_label (slow); + ptr =tcg_temp_ebb_new_ptr (); +gen_helper_lookup_tb_ptr (ptr, tcg_env); +tcg_gen_op1i (INDEX_op_goto_ptr,TCG_TYPE_PTR ,tcgv_ptr_arg (ptr)); +}
This is pretty good. As a follow-up I suspect we'll want a tcg backend expansion of this. For instance:
- x86_64 and s390x can use memory-operand comparisons.
- aarch64
- use shift-add insn for env_plus_off + h * 16.
- use ldp to load (tb, pc) and (cs_base, flags) in one insn.
- use ccmp to halve the number of branches.
etc.
r~
Re: [PATCH v4 6/9] RFC: tcg: probe the TB jump cache inline instead of calling a helper
Quoted 62 lines · Richard Henderson
Quoted 47 lines · Matt Turner
tcg/tcg-op.c +47
-0+static void gen_jmp_cache_probe (TCGv_i64 pc,const TranslationBlock *tb) +{ +TCGv_ptr jc, ent, tbp, ptr; +TCGv_i64 h, tmp; +TCGLabel *slow; +uint64_t fpair; + +QEMU_BUILD_BUG_ON (sizeof (((CPUJumpCache *)0 )->array[0 ]) !=16 ); + QEMU_BUILD_BUG_ON(offsetof(CPUJumpCache, array[0].pc) % 8 != 0); +/* One 64-bit load has to cover both, so they must be adjacent... */ +QEMU_BUILD_BUG_ON (offsetof(TranslationBlock , cflags) != + offsetof(TranslationBlock , flags) +4 ); +/* ...and aligned, which nothing else currently relies on. */ +QEMU_BUILD_BUG_ON (offsetof(TranslationBlock , flags) %8 !=0 ); + + jc =tcg_temp_ebb_new_ptr (); + ent =tcg_temp_ebb_new_ptr (); + tbp =tcg_temp_ebb_new_ptr (); + ptr =tcg_temp_ebb_new_ptr (); + h =tcg_temp_ebb_new_i64 (); + tmp =tcg_temp_ebb_new_i64 (); + slow =gen_new_label (); + +/* ent = &jc->array[tb_jmp_cache_hash_func(pc)] */ +gen_jmp_cache_hash (h, pc); +tcg_gen_shli_i64 (h, h,4 ); + +/* +* Not cpu->tb_jmp_cache: the probe reads its own base so that the main +* loop can poison it, which is how conditions the probe cannot test for +* itself force every dispatch back into the helper. See +* tcg_cpu_sync_jmp_cache(). +*/ +tcg_gen_ld_ptr (jc, tcg_env, + offsetof(CPUState , tb_jmp_cache_probe) -sizeof (CPUState)); +tcg_gen_trunc_i64_ptr (ent, h); +tcg_gen_add_ptr (ent, jc, ent); + +/* +* The pc first: on a hash miss it is the field most likely to differ, +* and an entry whose tb is NULL has a zero pc that only pc 0 matches. +*/ + tcg_gen_ld_i64(tmp, ent, offsetof(CPUJumpCache, array[0].pc)); +tcg_gen_brcond_i64 (TCG_COND_NE , tmp, pc, slow); + + tcg_gen_ld_ptr(tbp, ent, offsetof(CPUJumpCache, array[0].tb)); +tcg_gen_brcondi_ptr (TCG_COND_EQ , tbp,0 , slow);tcg/tcg-op.c void tcg_gen_goto_tb(unsigned idx) · line 2802
Quoted 10 lines
tcg/tcg-op.c +10
-0+ +/* +* flags and cflags are adjacent uint32_t, so one aligned 64-bit load +* and compare covers both. +*/ +#if HOST_BIG_ENDIAN + fpair = ((uint64_t )tb->flags <<32 ) | tb->cflags; +#else + fpair = ((uint64_t )tb->cflags <<32 ) | tb->flags; +#endif I'd use
Quoted 6 lines
fpair = (HOST_BIG_ENDIAN ? deposit64(tb->cflags, 32, 32, tb->flags) : deposit64(tb->flags, 32, 32, tb->cflags));Whenever possible, avoid ifdefs to make sure all paths compile on every host.
Good call. Fixed.
Quoted 25 lines
Quoted 12 lines
tcg/tcg-op.c +12
-0+tcg_gen_ld_i64 (tmp, tbp, offsetof(TranslationBlock , flags)); +tcg_gen_brcondi_i64 (TCG_COND_NE , tmp, fpair, slow); + +/* +* cs_base is a second word of target-specific flags despite the name, +* and the pc alone does not imply it on a target that uses it. +*/ +tcg_gen_ld_i64 (tmp, tbp, offsetof(TranslationBlock , cs_base)); +tcg_gen_brcondi_i64 (TCG_COND_NE , tmp, tb->cs_base, slow); + + tcg_gen_ld_ptr(ptr, tbp, offsetof(TranslationBlock, tc.ptr)); +tcg_gen_op1i (INDEX_op_goto_ptr,TCG_TYPE_PTR ,tcgv_ptr_arg (ptr));tcg/tcg-op.c void tcg_gen_goto_tb(unsigned idx) · line 2824
Quoted 10 lines
tcg/tcg-op.c +10
-0+ +/* +* Emit a second goto_ptr rather than branching to a shared one: a temp +* live across the label would be spilled and reloaded on every dispatch. +*/ +gen_set_label (slow); + ptr =tcg_temp_ebb_new_ptr (); +gen_helper_lookup_tb_ptr (ptr, tcg_env); +tcg_gen_op1i (INDEX_op_goto_ptr,TCG_TYPE_PTR ,tcgv_ptr_arg (ptr)); +}This is pretty good. As a follow-up I suspect we'll want a tcg backend expansion of this. For instance:
Quoted 8 lines
-
x86_64and s390x can use memory-operand comparisons.- aarch64
- use shift-add insn forenv_plus_off+ h * 16.
- use ldp to load (tb, pc) and (cs_base, flags) in one insn.
- use ccmp to halve the number of branches.etc.
Yeah, that sounds good. I'd like to look into that.
PATCH v4 7/9 RFC: accel/tcg: allow cross-page goto_tb chaining in user-only builds
In reply to Matt Turnertranslator_use_goto_tb() refuses to chain unless the destination is on the same page as the start of the TB. For guests whose text is much larger than a page this is expensive: an emulated alpha gcc compiling a 255k line translation unit takes the indirect dispatch path for 8.4 billion of its 34.2 billion TB exits, and a large share of those are ordinary direct branches that simply crossed an 8 KiB page boundary.
The restriction was made unconditional by d3a2a1d803 ("accel/tcg:
Introduce translator_use_goto_tb"), whose rationale was:
Various targets avoid the page crossing test for CONFIG_USER_ONLY, but that is wrong: mmap and mprotect can change page permissions.
That is true, but in user-only builds the invalidation path already covers it. There are no page tables: every mmap, mprotect and munmap reaches page_set_flags(), which calls tb_invalidate_phys_range() whenever the flags actually change, and tb_phys_invalidate() calls tb_jmp_unlink() to reset incoming jumps. A chained cross-page jump is therefore broken whenever the destination page's permissions change. This is not true in system mode, where TBs are keyed by physical address and a page table change invalidates nothing, so the restriction is kept there.
The rule protects one more thing, which the original rationale does not
mention: it guarantees that execution cannot enter a page without a TB lookup, and so without check_for_breakpoints(). That is what makes a breakpoint set after a block was translated take effect, since insertion deliberately invalidates nothing. A link established before the breakpoint was set would jump straight over it.
So the chaining is only enabled for a run that can never acquire a breakpoint. In user-only mode every breakpoint comes from gdb -- BP_CPU is g_assert_not_reached() there, and the guest cannot ask for one -- and gdb has to be requested with -g before the first block is translated, even though with suspend=n it may connect later. gdb_may_set_breakpoints() reports whether it was, and is fixed for the lifetime of the process.
Add tests/tcg/multiarch/test-xpage-chain.c to cover both hazards directly. It writes the last instruction of one page and the first of the next, so that the fall-through between them is a cross-page goto_tb, runs it 200000 times so the chain is established, then checks that mprotect(PROT_NONE) makes the next call fault, and that different code written into the page once it is mapped back runs rather than a stale translation.
The two instructions -- set the return value register, and return -- are all the architecture specific code there is; thirteen architectures supply them and the rest skip.
The test detects the hazard it is meant to detect: with the tb_invalidate_phys_range() call in page_set_flags() commented out, it fails both phases, executing page B after PROT_NONE and returning the stale result.
Run with -b, the same binary stops once the chain is established and lets tests/tcg/multiarch/gdbstub/xpage-bp.py set a breakpoint on the far side of it, which the next call has to stop on. With gdb_may_set_breakpoints() forced to false so that the chaining stays on under gdb, that breakpoint is missed and the test fails, which is what makes it a test of the gate rather than of gdb.
Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation on an x86-64 host, LTO build, on top of the preceding patches:
before: 916,415,123,244 instructions
after: 891,254,240,071 instructions -2.75%
before: 85.59s wall clock
after: 81.45s wall clock -4.84%Note that this is worth more in time than in instructions, the reverse of the preceding patch: a chained jump replaces a cache probe whose loads can miss, so the instructions it removes are more expensive than average.
Measured before the inline jump cache probe, when a missed chain cost a helper call rather than an inline probe, the same change was worth -7.9%.
RFC because this reverses a deliberate decision and the reasoning above wants review from someone who knows the invalidation paths better than I do.
v3: Only take the shortcut when no gdbstub was requested. The same-page
rule also forces a lookup, and so a breakpoint check, on entry to every page; without that, a chain established before a breakpoint was set runs past it. Reported by Richard Henderson.
v3: Change translator_use_goto_tb() rather than translator_is_same_page().
i386, riscv and s390x call translator_is_same_page() for something else -- enforcing that only a single-insn TB may cross a page -- and v2 changed their TB boundaries in user-only mode as a side effect. alpha does not call it, so the numbers above are unaffected.
v3: Add the gdbstub half of the test.
v4: Move the test to tests/tcg/multiarch so that every *-user target runs
it, rather than only alpha. Requested by Alex Bennee. The direct branch is gone with it: a fall-through off the end of a page is a cross-page goto_tb just the same, and needs no per-architecture branch encoding or displacement arithmetic, only "set the return value" and "return". Built and run under qemu-user on aarch64, alpha, arm, hppa, loongarch64, m68k, mips, ppc, ppc64le, riscv64, s390x, sh4, sparc64 and x86_64; ppc64 ELFv1 skips, because a function pointer there is a descriptor rather than a code address.
--- accel/tcg/translator.c | 33 ++- gdbstub/user.c | 14 + include/gdbstub/user.h | 11 + tests/tcg/multiarch/Makefile.target | 12 +- tests/tcg/multiarch/gdbstub/xpage-bp.py | 37 +++ tests/tcg/multiarch/test-xpage-chain.c | 336 ++++++++++++++++++++++++ 6 files changed, 441 insertions(+), 2 deletions(-) create mode 100644 tests/tcg/multiarch/gdbstub/xpage-bp.py create mode 100644 tests/tcg/multiarch/test-xpage-chain.c
accel/tcg/translator.c +32 -1
@@ -15,6 +15,9 @@#include "accel/tcg/cpu-mmu-index.h" #include "exec/target_page.h" #include "exec/translator.h" +#ifdef CONFIG_USER_ONLY +#include "gdbstub/user.h" +#endif #include "exec/plugin-gen.h" #include "tcg/tcg-op-common.h" #include "internal-common.h"
@@ -110,6 +113,34 @@ bool translator_is_same_page(const DisasContextBase *db, vaddr addr)return ((addr ^ db->pc_first) &TARGET_PAGE_MASK ) ==0 ; } +/* +* Whether a direct jump may be chained to a destination outside the page +* the TB started in. +* +* In user-only mode there are no page tables. Every mmap, mprotect and +* munmap goes through page_set_flags(), which calls tb_invalidate_phys_range() +* whenever the flags actually change, and tb_phys_invalidate() unlinks +* incoming jumps. A cross-page link is therefore broken whenever the +* destination page's permissions change. +* +* What the same-page rule also provides is that execution cannot enter a page +* without a TB lookup, and so without check_for_breakpoints(), which is what +* makes a breakpoint set after a block was translated take effect. Nothing +* invalidates on breakpoint insertion, so a link established beforehand would +* jump straight over it. In user-only mode breakpoints only ever come from +* gdb -- BP_CPU is g_assert_not_reached() there and the guest has no way to +* ask for one -- and gdb has to be requested with -g before the first block +* is translated, so a run that has no gdbstub can never acquire a breakpoint. +*/ +static bool use_cross_page_goto_tb (void ) +{ +#ifdef CONFIG_USER_ONLY +return !gdb_may_set_breakpoints (); +#else +return false; +#endif +} +bool translator_use_goto_tb (DisasContextBase *db,vaddr dest) {/* Suppress goto_tb if requested. */
@@ -118,7 +149,7 @@ bool translator_use_goto_tb(DisasContextBase *db, vaddr dest) }/* Check for the dest on the same page as the start of the TB. */ -return translator_is_same_page (db, dest); +return use_cross_page_goto_tb () ||translator_is_same_page (db, dest); } void translator_loop(CPUState *cpu, TranslationBlock *tb, int *max_insns,
gdbstub/user.c +14 -0
@@ -470,6 +470,18 @@ static void *gdbserver_accept_thread(void *arg)#define USAGE "\nUsage: -g {port|path}[,suspend={y|n}]" +/* +* Set before the guest runs and never cleared, so that code translated at +* any point can rely on it: with suspend=n gdb may connect long after +* startup, and once connected it can insert a breakpoint at any time. +*/ +static bool gdbserver_requested; + +bool gdb_may_set_breakpoints (void ) +{ +return gdbserver_requested; +} +bool gdbserver_start (const char *args,Error **errp) {g_auto (GStrv) argv =g_strsplit (args,"," ,0 );
@@ -513,6 +525,8 @@ bool gdbserver_start(const char *args, Error **errp)return false; } + gdbserver_requested = true; +if (suspend) {if (gdbserver_accept (port, gdb_fd, port_or_path)) {gdb_handlesig (first_cpu,0 ,NULL ,NULL ,0 );
include/gdbstub/user.h +11 -0
@@ -11,6 +11,17 @@#define MAX_SIGINFO_LENGTH 128 +/** +* gdb_may_set_breakpoints() - whether a breakpoint can ever be inserted +* +* In user-only mode every breakpoint comes from gdb, and gdb is only ever +* reachable if -g was given at startup, before the guest ran a single +* instruction. A run that has no gdbstub can therefore never acquire a +* breakpoint, which lets translation take shortcuts that a breakpoint +* would invalidate. Stays true once true, even if gdb detaches. +*/ +bool gdb_may_set_breakpoints (void ); +/** * gdb_handlesig() - yield control to gdb * @cpu: CPU
tests/tcg/multiarch/Makefile.target +11 -1
@@ -143,6 +143,15 @@ run-gdbstub-follow-fork-mode-parent: follow-fork-mode --bin $< --test $(MULTIARCH_SRC)/gdbstub/follow-fork-mode-parent.py, \ following parents on fork) +# The chaining this exercises is only enabled when no gdbstub was requested, +# so what is under test here is that requesting one turns it back off. +run-gdbstub-xpage-bp: test-xpage-chain + $(call run-test, $@, $(GDB_SCRIPT) \ + --gdb $(GDB) \ + --qemu $(QEMU) --qargs "$(QEMU_OPTS)" \ + --bin "$< -b" --test $(MULTIARCH_SRC)/gdbstub/xpage-bp.py, \ + breakpoint behind an established cross-page chain) + run-gdbstub-late-attach: late-attach $(call run-test, $@, env LATE_ATTACH_PY=1 $(GDB_SCRIPT) \ --gdb $(GDB) \
@@ -159,7 +168,8 @@ EXTRA_RUNS += run-gdbstub-sha1 run-gdbstub-qxfer-auxv-read \ run-gdbstub-registers run-gdbstub-prot-none \ run-gdbstub-catch-syscalls run-gdbstub-follow-fork-mode-child \ run-gdbstub-follow-fork-mode-parent \ - run-gdbstub-qxfer-siginfo-read run-gdbstub-late-attach + run-gdbstub-qxfer-siginfo-read run-gdbstub-late-attach \ + run-gdbstub-xpage-bp # ARM Compatible Semi Hosting Tests #
tests/tcg/multiarch/gdbstub/xpage-bp.py new file +37 -0
@@ -0,0 +1,37 @@ +"""Test that a breakpoint set after a cross-page chain is established is hit. + +translator_use_goto_tb() lets a direct branch chain to another page in +user-only builds, which is only safe because a run with no gdbstub can never +acquire a breakpoint. This runs with one, so the chaining must be off and +the breakpoint must still be reached. + +This runs as a sourced script (via -x, via run-test.py). + +SPDX-License-Identifier: GPL-2.0-or-later +""" +from test_gdbstub import main, report + + +def run_test(): + """Run through the tests one by one""" + gdb.Breakpoint("break_here") + gdb.execute("continue") + + # The chain exists by now; put a breakpoint on the far side of it. + target = int(gdb.parse_and_eval("(unsigned long)page_b_entry")) + if target == 0: + report(True, "no code emitters for this architecture, skipped") + return + gdb.execute("break *{}".format(target)) + gdb.execute("continue") + + pc = int(gdb.parse_and_eval("(unsigned long)$pc")) + report(pc == target, "stopped at {:#x}, expected {:#x}".format(pc, target)) + + gdb.execute("delete") + gdb.execute("continue") + exitcode = int(gdb.parse_and_eval("$_exitcode")) + report(exitcode == 0, "{} == 0".format(exitcode)) + + +main(run_test)
tests/tcg/multiarch/test-xpage-chain.c new file +336 -0
336 lines not on this page · raw message
Signature · 1 line
2.54.0
PATCH v4 8/9 RFC: accel/tcg: poison the jump cache instead of polling for indirect exits
In reply to Matt TurnerEvery translation block begins by loading cpu->neg.icount_decr.u32, testing it and branching to the exit path. That is three host instructions at the top of every TB, and blocks are short: an emulated alpha gcc 16.2.0 compiling a 255k line translation unit executes 34.2 billion of them at 6.04 guest instructions each.
A block does not need to poll if every way out of it already reaches a check. A goto_tb does not: it chains straight into its destination, with nothing in between that looks at icount_decr, so the destination has to poll on entry. An indirect exit does. The out-of-line path calls helper_lookup_tb_ptr() every time, so it only needs the helper to return the epilogue while an exit is pending. The inline probe is already covered by the machinery the breakpoint patch added: it reads its base pointer from cpu->tb_jmp_cache_probe and takes the slow path when the entry it finds has a NULL tb, so pointing that base at a page of zeroes turns every indirect dispatch into a miss, and a miss lands in the same helper.
So a pending exit becomes one more reason for tcg_cpu_may_dispatch() to say no. The two places that set icount_decr.u16.high poison the probe; the main loop puts it back once the flag is clear, on the same pass that already re-evaluates the breakpoint state. The real tb_jmp_cache is untouched throughout, so no cache contents are lost, and the fast path pays nothing:
the base was a load from CPUState either way.
The poll is therefore emitted only in blocks that emit a goto_tb. Whether a block does is not known until its last exit has been generated, so the decision is deferred and the load and branch are emitted retroactively at the head of the block in gen_tb_end(), using the same emit_before_op mechanism the can_do_io stores use. icount opts out and keeps the counter unconditionally.
Interrupt latency is bounded at one block, as before. It does not depend on the shape of the guest's control flow graph: a block either polls on entry or is checked on the way out, and no run of blocks can avoid both. What changes is where the check sits, not how often one happens.
tests/tcg/multiarch/test-indirect-irq.c is added for this: a loop whose only back edge is an indirect branch, under alarm(1). That loop's block emits no goto_tb, so it no longer polls, and the test passes only because the dispatch notices instead -- it hangs if the poison is removed, which is what makes it a test of the new mechanism rather than of the old poll. Nothing in it is architecture specific: the loop is a computed goto, which every target's compiler supports, so it covers whichever targets go on to use the inline probe. The other alpha tests still pass and the emulated compiler still produces byte-identical output.
Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host, LTO build, on top of the preceding patches:
before: 891,254,240,071 instructions
after: 868,811,832,620 instructions -2.52%
before: 81.45s wall clock
after: 79.85s wall clock -1.96%The emulated compiler produces byte-identical output.
RFC because:
- The un-poison in the main loop races a concurrent poison from another thread. The existing barrier around icount_decr.u16.high covers it -- a poison that lands after the sync also re-set the flag, and exit_request was stored before it -- but this deserves more eyes than the single-threaded user-mode testing I have given it.
- Only the inline probe needs the poison, and only alpha uses the inline probe today. Targets on the out-of-line path are covered by the helper check alone, but that has not been measured.
- The shared zero-filled CPUJumpCache is a 1MB allocation that is never written. A read-only mapping would express that better.
v3: Rebased onto the removal of "only poll for interrupts in blocks that can
close a cycle", which v2 sat on top of and which is dropped: it let a straight-line run of arbitrary length go unchecked, since a block with no backward edge polled nowhere (Richard).
The rule is now that a block polls iff it emits a goto_tb, rather than iff it can close a control flow cycle. That keeps the bound at one block without any analysis of the guest's control flow graph, so the objection to the dropped patch does not carry over. The deferred-emission machinery it needs moves here from that patch; DisasContextBase::needs_exit_check and the hook in translator_use_goto_tb() are gone with it, and the flag is now set by tcg_gen_goto_tb() rather than by goto_ptr emission.
All of v2's measurements were dropped: they were taken with the cycle-analysis patch underneath, which changes both the baseline and what is left to remove, so none of them described this patch. The numbers above are a fresh measurement of the series as it now stands.
v4: Moved the test from tests/tcg/alpha/ to tests/tcg/multiarch/: the
mechanism is generic and nothing in the test is alpha specific (Alex).
The performance numbers above are the v3 measurements, not re-run: the machine they were taken on is busy.
--- accel/tcg/cpu-exec.c | 23 +++++++-- accel/tcg/tcg-accel-ops.c | 1 + accel/tcg/translator.c | 51 ++++++++++++++++++-- include/hw/core/cpu.h | 8 ++-- include/tcg/tcg.h | 2 + tcg/tcg-op.c | 13 ++++++ tests/tcg/multiarch/test-indirect-irq.c | 62 +++++++++++++++++++++++++ 7 files changed, 151 insertions(+), 9 deletions(-) create mode 100644 tests/tcg/multiarch/test-indirect-irq.c
accel/tcg/cpu-exec.c +20 -3
@@ -388,6 +388,16 @@ const void *HELPER(lookup_tb_ptr)(CPUArchState *env)*/ cpu->neg.can_do_io = true; +/* +* A block that dispatches indirectly does not emit the icount_decr poll, +* so this is where a pending exit is noticed for that path: either the +* probe was poisoned and every dispatch arrives here, or the target uses +* the out-of-line lookup and always did. +*/ +if (unlikely (cpu_loop_exit_requested (cpu))) { +return tcg_code_gen_epilogue; + } +TCGTBCPUState s = cpu->cc->tcg_ops->get_tb_cpu_state (cpu); s.cflags =curr_cflags (cpu);
@@ -757,8 +767,9 @@ static inline bool cpu_handle_exception(CPUState *cpu, int *ret)* slow path when the entry it finds has a NULL tb. Pointing the probe at a * region that is all zeroes therefore forces every indirect dispatch into * helper_lookup_tb_ptr(), which does the full lookup the inline probe only -* approximates. The real jump cache is untouched, so no contents are lost -* and recovery is a single store. +* approximates and returns to the main loop while an exit is pending. The +* real jump cache is untouched, so no contents are lost and recovery is a +* single store. * * Only ever read from, and only one entry per dispatch, so one shared * zero-filled cache is enough for every CPU. Not const: that would put a
@@ -779,10 +790,13 @@ static CPUJumpCache tb_jmp_cache_poison;* the rest of the page. A block translated before the breakpoint was set is * therefore still in the jump cache, and dispatching to it inline would step * straight over the breakpoint. +* +* A block that dispatches indirectly also does not emit the icount_decr +* poll, so the dispatch is where a pending exit has to be noticed. */ static bool tcg_cpu_may_dispatch (CPUState *cpu) { -return QTAILQ_EMPTY (&cpu->breakpoints); +return QTAILQ_EMPTY (&cpu->breakpoints) && !cpu_loop_exit_requested (cpu); }/*
@@ -851,6 +865,9 @@ void tcg_kick_vcpu_thread(CPUState *cpu)/* Ensure cpu_exec will see the exit request after TCG has exited. */ qatomic_store_release (&cpu->neg.icount_decr.u16.high,-1 ); + +/* Blocks that only dispatch indirectly do not poll; stop them chaining. */ +tcg_cpu_poison_jmp_cache (cpu); }static inline bool icount_exit_request (CPUState *cpu)
accel/tcg/tcg-accel-ops.c +1 -0
@@ -106,6 +106,7 @@ void tcg_handle_interrupt(CPUState *cpu, int mask)qemu_cpu_kick (cpu); }else {qatomic_set (&cpu->neg.icount_decr.u16.high,-1 ); +tcg_cpu_poison_jmp_cache (cpu); } }
accel/tcg/translator.c +48 -3
86 lines not on this page · raw message
include/hw/core/cpu.h +5 -3
@@ -523,9 +523,11 @@ struct CPUState {* @tb_jmp_cache_probe: base the inline jump cache probe reads. * * Normally @tb_jmp_cache. Pointed at a shared page of zeroes to force -* every inline dispatch to miss and fall back to helper_lookup_tb_ptr(); -* see tcg_cpu_sync_jmp_cache(). NULL before tcg_exec_realizefn() and -* after tcg_exec_unrealizefn(). +* every inline dispatch to miss and fall back to helper_lookup_tb_ptr(), +* either because a breakpoint is set or because an exit is pending; see +* tcg_cpu_sync_jmp_cache(). Only generated code and the accessors in +* cpu-exec.c may touch it. NULL before tcg_exec_realizefn() and after +* tcg_exec_unrealizefn(). */ struct CPUJumpCache *tb_jmp_cache_probe;
include/tcg/tcg.h +2 -0
@@ -389,6 +389,8 @@ struct TCGContext {struct TCGLabelPoolData *pool_labels;TCGLabel *exitreq_label; +/* Set by goto_tb emission: this TB chains without reaching a check. */ +bool exit_check_needed;#ifdef CONFIG_PLUGIN /*
tcg/tcg-op.c +13 -0
@@ -2713,6 +2713,13 @@ void tcg_gen_goto_tb(unsigned idx)tcg_debug_assert ((tcg_ctx->goto_tb_issue_mask & (1 << idx)) ==0 ); tcg_ctx->goto_tb_issue_mask |=1 << idx;#endif +/* +* A goto_tb chains straight into the destination, with nothing in between +* that looks at icount_decr, so this TB has to poll on entry. See +* defer_exit_check(). +*/ + tcg_ctx->exit_check_needed = true; +plugin_gen_disable_mem_helpers ();tcg_gen_op1i (INDEX_op_goto_tb,0 , idx); }
@@ -2834,6 +2841,12 @@ void tcg_gen_lookup_and_goto_ptr_tmp(TCGTemp *pc, const TranslationBlock *tb)plugin_gen_disable_mem_helpers (); +/* +* Neither path below needs an icount_decr poll. The helper returns to +* the main loop while an exit is pending, and a pending exit poisons +* tb_jmp_cache_probe, so the inline probe finds a NULL tb and falls into +* that same helper. +*/ if (pc) {TCGv_i64 pc64;
tests/tcg/multiarch/test-indirect-irq.c new file +62 -0
62 lines not on this page · raw message
Signature · 1 line
2.54.0
PATCH v4 9/9 RFC: tcg: fold a guest displacement into the host addressing mode
In reply to Matt TurnerNothing in the TCG frontend interface can express a based memory access. tcg_gen_qemu_ld/st take an address and nothing else, so a target with a displacement in its load and store encodings -- which is most of them -- has to materialize the address first:
ldq a1,8(a0) -> mov 0x80(%rbp),%rbx reload a0
lea 0x8(%rbx),%r12 address
mov (%r12),%r12 the load
mov %r12,0x88(%rbp) spill a1The lea is pure loss on a host whose addressing mode has a displacement field sitting empty. It also needs a register, at the point in a block where pressure is highest.
Fold it. After optimization, look for an add of a constant immediately before a guest access, defining that access's address operand, and move the constant into a new second constant argument on the op. The add is left for liveness to remove, so nothing breaks if its result has another use. Only the immediately preceding op is examined: that is what the frontends emit, and a window of one op means the pass does not have to reason about what could have happened in between. The one thing it does check is that the add did not clobber the base it read, since the access now reads that base directly.
Targets opt in with TCG_TARGET_HAS_ldst_disp and an out_disp member on TCGOutOpQemuLdSt. Without it the pass does not run, the displacement stays zero and the existing out member is called exactly as before, so no other backend changes behavior or needs touching.
The fold is refused unless the access has no slow path at all, since the slow path hands addr_reg to the helper and that register no longer holds the full guest address. That is decided generically: user-only, because softmmu compares the unadjusted address against the TLB; a 64-bit address type, because a 32-bit one wraps where a host displacement would not; and no alignment test on the access. For x86_64 the displacement goes in the disp32 that prepare_host_addr() already fills in for guest_base, so all the backend has left to check is that guest_base plus the displacement still fits there.
Measured with qemu-alpha running an emulated alpha gcc 16.2.0 compiling the SQLite 3.45.1 amalgamation (255k lines, -O2) on an x86-64 host, LTO build, on top of the preceding patches, against a control measured in the same session:
before: 868,811,832,620 instructions, 79.85s
after: 819,262,147,022 instructions, 77.30s
-5.70% instructions, -3.20% wallEmitted code shrinks from 50.55MB to 48.80MB over the run, 167.4 to 161.6 bytes per block. Per Alpha opcode, the host bytes emitted for an access fall as expected and nothing else moves:
ldq 18.3 -> 15.4 ldah 20.9 -> 20.9
ldl 16.6 -> 14.1 lda 12.9 -> 12.9
stq 12.8 -> 9.7 mov 9.8 -> 9.8The emulated compiler produces byte-identical output and the alpha tests still pass, including with a non-zero guest_base forced via -B.
RFC because:
- Only wired up for x86_64, and only for qemu_ld and qemu_st; the i128 qemu_ld2 and qemu_st2 pairs are left alone.
- Requiring that no slow path exists is stricter than necessary. The fast path test can stay on the base register as long as the displacement is itself a multiple of the required alignment, which it is for anything a frontend emits for a struct or stack access. Recording the displacement in TCGLabelQemuLdst and emitting one lea on the slow path would then cover alignment-checked accesses too, at no fast path cost.
- Softmmu wants the displacement folded into the TLB comparison as well, which is a bigger change than this one.
- A one op window catches everything the frontends emit today but is trivially defeated by anything scheduled in between.
v4:
- Hoisted the compilation mode tests -- tcg_use_softmmu and the 64-bit address type -- out of the backend hook and into fold_ldst_disp(), next to the TCG_TARGET_HAS_ldst_disp test, so the loop is not entered at all when the mode rules the fold out.
- Pass MemOp rather than MemOpIdx to the backend hook; nothing about the mmu_idx is relevant to it.
- Moved the alignment test into generic code as ldst_disp_needs_align(), so a backend does not have to repeat the atom_and_align_for_opc() call. The exact answer depends on the host's atomicity capabilities, which the generic pass does not know, so it answers for the most restrictive host. That is the same answer for everything the frontends actually emit -- MO_ATOM_IFALIGN is the default -- and conservative for the handful of MO_ATOM_WITHIN16 and MO_ATOM_SUBALIGN accesses, which lose the fold on a host that could have taken it.
- What is left of the x86_64 hook is the guest_base test, so it now lives beside x86_guest_base under the CONFIG_USER_ONLY that declares it.
- Refuse a displacement that does not fit in an int32_t, which is what out_disp() takes. Not reachable with any real guest_base, but the pass should not offer the backend something the interface cannot carry.
- The numbers above are unchanged from v3: they have not been re-measured on the restructured patch, which is not expected to move them since the accesses in this workload are all MO_ATOM_IFALIGN.
--- include/tcg/tcg-opc.h | 9 ++- tcg/tcg-op-ldst.c | 3 +- tcg/tcg.c | 132 +++++++++++++++++++++++++++++++++++- tcg/x86_64/tcg-target.c.inc | 41 +++++++++++ tcg/x86_64/tcg-target.h | 3 + 5 files changed, 184 insertions(+), 4 deletions(-)
include/tcg/tcg-opc.h +7 -2
@@ -125,8 +125,13 @@ DEF(goto_ptr, 0, 1, 0, TCG_OPF_BB_EXIT | TCG_OPF_BB_END) DEF(plugin_cb, 0, 0, 1, TCG_OPF_NOT_PRESENT)DEF (plugin_mem_cb,0 ,1 ,1 ,TCG_OPF_NOT_PRESENT ) -DEF(qemu_ld, 1, 1, 1, TCG_OPF_CALL_CLOBBER | TCG_OPF_SIDE_EFFECTS | TCG_OPF_INT) -DEF(qemu_st, 0, 2, 1, TCG_OPF_CALL_CLOBBER | TCG_OPF_SIDE_EFFECTS | TCG_OPF_INT) +/* +* The second constant argument is a displacement to add to the address, +* zero unless a target advertises TCG_TARGET_HAS_ldst_disp and the fold in +* fold_ldst_disp() applied. + */ +DEF(qemu_ld, 1, 1, 2, TCG_OPF_CALL_CLOBBER | TCG_OPF_SIDE_EFFECTS | TCG_OPF_INT) +DEF(qemu_st, 0, 2, 2, TCG_OPF_CALL_CLOBBER | TCG_OPF_SIDE_EFFECTS | TCG_OPF_INT) DEF(qemu_ld2, 2, 1, 1, TCG_OPF_CALL_CLOBBER | TCG_OPF_SIDE_EFFECTS | TCG_OPF_INT)DEF (qemu_st2,0 ,3 ,1 ,TCG_OPF_CALL_CLOBBER |TCG_OPF_SIDE_EFFECTS |TCG_OPF_INT )
tcg/tcg-op-ldst.c +2 -1
@@ -92,7 +92,8 @@ static MemOp tcg_canonicalize_memop(MemOp op, bool is64, bool st)static void gen_ldst1 (TCGOpcode opc,TCGType type,TCGTemp *v,TCGTemp *addr,MemOpIdx oi) { -TCGOp *op =tcg_gen_op3 (opc, type,temp_arg (v),temp_arg (addr), oi); +/* The trailing zero is the address displacement; see fold_ldst_disp(). */ +TCGOp *op =tcg_gen_op4 (opc, type,temp_arg (v),temp_arg (addr), oi,0 );TCGOP_FLAGS (op) =get_memop (oi) &MO_SIZE ; }
tcg/tcg.c +131 -1
156 lines not on this page · raw message
tcg/x86_64/tcg-target.c.inc +41 -0
71 lines not on this page · raw message
tcg/x86_64/tcg-target.h +3 -0
@@ -30,6 +30,9 @@#define TCG_TARGET_NB_REGS 32#define MAX_CODE_GEN_BUFFER_SIZE (2 * GiB) +/* A guest displacement can go in the disp32 of the addressing mode. */ +#define TCG_TARGET_HAS_ldst_disp 1 + typedef enum { TCG_REG_EAX = 0, TCG_REG_ECX,
Signature · 1 line
2.54.0