[PATCH] docs/devel: Explain in more detail the TB chaining mechanisms

Luis Pires posted 1 patch 2 years, 11 months ago
Patches applied successfully (tree, apply log)
git fetch https://github.com/patchew-project/next-importer-push tags/patchew/20210528123029.143847-1-luis.pires@eldorado.org.br
There is a newer version of this series
docs/devel/tcg.rst | 96 ++++++++++++++++++++++++++++++++++++++++------
1 file changed, 85 insertions(+), 11 deletions(-)
[PATCH] docs/devel: Explain in more detail the TB chaining mechanisms
Posted by Luis Pires 2 years, 11 months ago
Signed-off-by: Luis Pires <luis.pires@eldorado.org.br>
---

Being new to QEMU, I went through the code to try to understand how
lookup_and_goto_ptr, goto_tb and exit_tb work, and when each should be used.
Thought I'd share what I learned by documenting it, as it might be
useful to other people starting to work on TCG, and will also allow
others to comment on any parts I misunderstood.

 docs/devel/tcg.rst | 96 ++++++++++++++++++++++++++++++++++++++++------
 1 file changed, 85 insertions(+), 11 deletions(-)

diff --git a/docs/devel/tcg.rst b/docs/devel/tcg.rst
index 4ebde44b9d..d3354b8dcb 100644
--- a/docs/devel/tcg.rst
+++ b/docs/devel/tcg.rst
@@ -11,13 +11,14 @@ performances.
 QEMU's dynamic translation backend is called TCG, for "Tiny Code
 Generator". For more information, please take a look at ``tcg/README``.
 
-Some notable features of QEMU's dynamic translator are:
+The following sections outline some notable features and implementation
+details of QEMU's dynamic translator.
 
 CPU state optimisations
 -----------------------
 
-The target CPUs have many internal states which change the way it
-evaluates instructions. In order to achieve a good speed, the
+The target CPUs have many internal states which change the way they
+evaluate instructions. In order to achieve a good speed, the
 translation phase considers that some state information of the virtual
 CPU cannot change in it. The state is recorded in the Translation
 Block (TB). If the state changes (e.g. privilege level), a new TB will
@@ -31,18 +32,91 @@ Direct block chaining
 ---------------------
 
 After each translated basic block is executed, QEMU uses the simulated
-Program Counter (PC) and other cpu state information (such as the CS
+Program Counter (PC) and other CPU state information (such as the CS
 segment base value) to find the next basic block.
 
-In order to accelerate the most common cases where the new simulated PC
-is known, QEMU can patch a basic block so that it jumps directly to the
-next one.
-
-The most portable code uses an indirect jump. An indirect jump makes
-it easier to make the jump target modification atomic. On some host
-architectures (such as x86 or PowerPC), the ``JUMP`` opcode is
+In its simplest, less optimized form, this is done by exiting from the
+current TB, going through the TB epilogue, and then back to the outer
+execution loop. That’s where QEMU looks for the next TB to execute,
+translating it from the guest architecture if it isn’t already available
+in memory. Then QEMU proceeds to execute this next TB, starting at the
+prologue and then moving on to the translated instructions.
+
+In order to accelerate the most common cases where the TB for the new
+simulated PC is already available, QEMU has mechanisms that allow
+multiple TBs to be chained directly, without having to go back to the
+outer execution loop as described above. These mechanisms are:
+
+``lookup_and_goto_ptr``
+^^^^^^^^^^^^^^^^^^^^^^^
+
+On platforms that support the ``lookup_and_goto_ptr`` mechanism, calling
+``tcg_gen_lookup_and_goto_ptr()`` will emit TCG instructions that call
+a helper function to look for the destination TB, based on
+the CPU state information. If the destination TB is available, a
+``goto_ptr`` TCG instruction is emitted to jump directly to its first
+instruction, skipping the epilogue - execution loop - prologue path.
+If the destination TB is not available, the ``goto_ptr`` instruction
+jumps to the epilogue, effectively exiting from the current TB and
+going back to the execution loop.
+
+On platforms that do not support this mechanism, the
+``tcg_gen_lookup_and_goto_ptr()`` function will just use
+``tcg_gen_exit_tb()`` to exit from the current TB.
+
+``goto_tb + exit_tb``
+^^^^^^^^^^^^^^^^^^^^^
+
+On platforms that support this mechanism, the translation code usually
+implements branching by performing the following steps:
+
+1. Call ``tcg_gen_goto_tb()`` passing a jump slot index (either 0 or 1)
+   as a parameter
+
+2. Emit TCG instructions to update the CPU state information with the
+   address of the next instruction to execute
+
+3. Call ``tcg_gen_exit_tb()`` passing the address of the current TB and
+   the jump slot index again
+
+Step 1, ``tcg_gen_goto_tb()``, will emit a ``goto_tb`` TCG
+instruction that later on gets translated to a jump to an address
+associated with the specified jump slot. Initially, this is the address
+of step 2's instructions, which update the CPU state information. Step 3,
+``tcg_gen_exit_tb()``, exits from the current TB returning a tagged
+pointer composed of the last executed TB’s address and the jump slot
+index.
+
+The first time this whole sequence is translated to target instructions
+and executed, step 1 doesn’t do anything really useful, as it just jumps
+to step 2. Then the CPU state information gets updated and we exit from
+the current TB. As a result, the behavior is very similar to the less
+optimized form described earlier in this section.
+
+Next, the execution loop looks for the next TB to execute using the
+current CPU state information (creating the TB if it wasn’t already
+available) and, before starting to execute the new TB’s instructions,
+tries to patch the previously executed TB by associating one of its jump
+slots (the one specified in the call to ``tcg_gen_exit_tb()``) with the
+address of the new TB.
+
+The next time this previous TB is executed and we get to that same
+``goto_tb`` step, it will already be patched (assuming the destination TB
+is still in memory) and will jump directly to the first instruction of
+the destination TB, without going back to the outer execution loop.
+The most portable code patches TBs using indirect jumps. An indirect
+jump makes it easier to make the jump target modification atomic. On some
+host architectures (such as x86 and PowerPC), the ``JUMP`` opcode is
 directly patched so that the block chaining has no overhead.
 
+Note that, on step 3 (``tcg_gen_exit_tb()``), in addition to the
+jump slot index, the address of the TB just executed is also returned.
+This is important because that's the TB that will have to be patched
+by the execution loop, and not necessarily the one that was directly
+executed from it. This is due to the fact that the original TB might
+have already been chained to additional TBs, which ended up being
+executed without the execution loop's knowledge.
+
 Self-modifying code and translated code invalidation
 ----------------------------------------------------
 
-- 
2.25.1


Re: [PATCH] docs/devel: Explain in more detail the TB chaining mechanisms
Posted by Richard Henderson 2 years, 11 months ago
On 5/28/21 5:30 AM, Luis Pires wrote:
> +In its simplest, less optimized form, this is done by exiting from the
> +current TB, going through the TB epilogue, and then back to the outer
> +execution loop. That’s where QEMU looks for the next TB to execute,
> +translating it from the guest architecture if it isn’t already available
> +in memory. Then QEMU proceeds to execute this next TB, starting at the
> +prologue and then moving on to the translated instructions.

It is important to mention that by exiting this way, we immediately re-evaluate 
cc->cpu_exec_interrupt().  It is mandatory to exit this way after any cpu state 
change that may unmask interrupts.

This is often referred to as "exit to the main loop" in the translators.  In my 
recent changes to the ppc translator, I introduced DISAS_EXIT* for the purpose.


> +In order to accelerate the most common cases where the TB for the new
> +simulated PC is already available, QEMU has mechanisms that allow
> +multiple TBs to be chained directly, without having to go back to the
> +outer execution loop as described above. These mechanisms are:
> +
> +``lookup_and_goto_ptr``
> +^^^^^^^^^^^^^^^^^^^^^^^
> +
> +On platforms that support the ``lookup_and_goto_ptr`` mechanism, calling
> +``tcg_gen_lookup_and_goto_ptr()`` will emit TCG instructions that call
> +a helper function to look for the destination TB, based on
> +the CPU state information. If the destination TB is available, a
> +``goto_ptr`` TCG instruction is emitted to jump directly to its first
> +instruction, skipping the epilogue - execution loop - prologue path.
> +If the destination TB is not available, the ``goto_ptr`` instruction
> +jumps to the epilogue, effectively exiting from the current TB and
> +going back to the execution loop.

I'm one step shy of making TCG_TARGET_HAS_goto_ptr mandatory, and I don't think 
it's useful to focus on what the fallback mechanisms are.  In particular, 
lookup_and_goto_ptr will exit to the main loop with '-d nochain'.

The timeline is off here as well.  The goto_ptr tcg opcode is not conditionally 
emitted -- it is always emitted.  Better phrasing:

   ... will emit a call to ``helper_lookup_tb_ptr``.  This helper
   will look for an existing TB that matches the current CPU state.
   If the destination TB is available its code address is returned,
   otherwise the address of the JIT epilogue is returned.  The call
   to the helper is always followed by the tcg ``goto_ptr`` opcode,
   which branches to the returned address.  In this way, we either
   branch to the next TB or return to the main loop.


> +On platforms that do not support this mechanism, the
> +``tcg_gen_lookup_and_goto_ptr()`` function will just use
> +``tcg_gen_exit_tb()`` to exit from the current TB.

Just drop this bit.

> +``goto_tb + exit_tb``
> +^^^^^^^^^^^^^^^^^^^^^
> +
> +On platforms that support this mechanism, the translation code usually
> +implements branching by performing the following steps:

Again drop "on platforms that support", because they all do -- it's mandatory.

It's also very important to note when this cannot be used: the change in cpu 
state must be constant.  E.g. a direct branch not an indirect branch.  A 
surprising edge case here in the past has been a direct branch with a 
conditional delay slot nullification.

Moreover, even the direct branch cannot cross a page boundary, because memory 
mappings may change causing the code at the destination address to change.

> +
> +1. Call ``tcg_gen_goto_tb()`` passing a jump slot index (either 0 or 1)
> +   as a parameter
> +
> +2. Emit TCG instructions to update the CPU state information with the
> +   address of the next instruction to execute

More completely, update the CPU state with any information that has been 
assumed constant.  For most guests, this is just the PC.  But e.g. for hppa 
this is both iaoq.f (cip) and iaoq.b (nip).

It is very much up to the guest to determine the set of data that is present in 
cpu_get_tb_cpu_state, and what can be assumed across the break.

> +The first time this whole sequence is translated to target instructions
> +and executed, step 1 doesn’t do anything really useful, as it just jumps
> +to step 2.

Timing problem.  When the whole sequence is translated is immaterial.  You mean 
the first time this sequence is executed.  Drop the "doesn't do anything 
useful" phrase.


> Then the CPU state information gets updated and we exit from
> +the current TB. As a result, the behavior is very similar to the less
> +optimized form described earlier in this section.
> +
> +Next, the execution loop looks for the next TB to execute using the
> +current CPU state information (creating the TB if it wasn’t already
> +available) and, before starting to execute the new TB’s instructions,
> +tries to patch the previously executed TB by associating one of its jump

s/tries to patch/patches/.  There's no failure possible.

> +The most portable code patches TBs using indirect jumps. An indirect
> +jump makes it easier to make the jump target modification atomic. On some
> +host architectures (such as x86 and PowerPC), the ``JUMP`` opcode is

This detail should be elsewhere. This is an internal choice of the tcg backend, 
depending on the host architecture.


r~

RE: [PATCH] docs/devel: Explain in more detail the TB chaining mechanisms
Posted by Luis Fernando Fujita Pires 2 years, 11 months ago
From: Richard Henderson <richard.henderson@linaro.org>
> More completely, update the CPU state with any information that has been
> assumed constant.  For most guests, this is just the PC.  But e.g. for hppa
> this is both iaoq.f (cip) and iaoq.b (nip).
> 
> It is very much up to the guest to determine the set of data that is present in
> cpu_get_tb_cpu_state, and what can be assumed across the break.

I’m not sure I understand what “assumed constant” means in this context. Would
it be fair to say that step 2 should update any CPU state information that is
required by the main loop to correctly locate and execute the next TB, but not
anything that would be needed if we were to jump directly from step 1 to the first
instruction in the next TB without going through the main loop?

Thanks,

--
Luis Pires
Instituto de Pesquisas ELDORADO 
Aviso Legal - Disclaimer <https://www.eldorado.org.br/disclaimer.html>
Re: [PATCH] docs/devel: Explain in more detail the TB chaining mechanisms
Posted by Richard Henderson 2 years, 11 months ago
On 5/28/21 1:15 PM, Luis Fernando Fujita Pires wrote:
> From: Richard Henderson <richard.henderson@linaro.org>
>> More completely, update the CPU state with any information that has been
>> assumed constant.  For most guests, this is just the PC.  But e.g. for hppa
>> this is both iaoq.f (cip) and iaoq.b (nip).
>>
>> It is very much up to the guest to determine the set of data that is present in
>> cpu_get_tb_cpu_state, and what can be assumed across the break.
> 
> I’m not sure I understand what “assumed constant” means in this context.

The pc of the branch destination is a constant, for instance.
As would be the enabled instruction set (consider arm's blx, which toggles 
between arm and thumb isa).


> Would
> it be fair to say that step 2 should update any CPU state information that is
> required by the main loop to correctly locate and execute the next TB, but not
> anything that would be needed if we were to jump directly from step 1 to the first
> instruction in the next TB without going through the main loop?

The information written in step 2, omitted by step 1, must be inferable from 
cpu_get_tb_cpu_state (via tcg_ops->synchronize_from_tb) and from cpu_restore_state.

One of the two forms is how we return to the main loop after escaping from the 
chain of TB via interrupt or exception, respectively.


r~