docs/devel/qapi-code-gen: Belatedly document feature documentation
[qemu/armbru.git] / docs / devel / tcg.rst
bloba65fb7b1c44275cc62ccef9e49edf5055d552dfa
1 ====================
2 Translator Internals
3 ====================
5 QEMU is a dynamic translator. When it first encounters a piece of code,
6 it converts it to the host instruction set. Usually dynamic translators
7 are very complicated and highly CPU dependent. QEMU uses some tricks
8 which make it relatively easily portable and simple while achieving good
9 performances.
11 QEMU's dynamic translation backend is called TCG, for "Tiny Code
12 Generator". For more information, please take a look at ``tcg/README``.
14 The following sections outline some notable features and implementation
15 details of QEMU's dynamic translator.
17 CPU state optimisations
18 -----------------------
20 The target CPUs have many internal states which change the way they
21 evaluate instructions. In order to achieve a good speed, the
22 translation phase considers that some state information of the virtual
23 CPU cannot change in it. The state is recorded in the Translation
24 Block (TB). If the state changes (e.g. privilege level), a new TB will
25 be generated and the previous TB won't be used anymore until the state
26 matches the state recorded in the previous TB. The same idea can be applied
27 to other aspects of the CPU state.  For example, on x86, if the SS,
28 DS and ES segments have a zero base, then the translator does not even
29 generate an addition for the segment base.
31 Direct block chaining
32 ---------------------
34 After each translated basic block is executed, QEMU uses the simulated
35 Program Counter (PC) and other CPU state information (such as the CS
36 segment base value) to find the next basic block.
38 In its simplest, less optimized form, this is done by exiting from the
39 current TB, going through the TB epilogue, and then back to the
40 main loop. That’s where QEMU looks for the next TB to execute,
41 translating it from the guest architecture if it isn’t already available
42 in memory. Then QEMU proceeds to execute this next TB, starting at the
43 prologue and then moving on to the translated instructions.
45 Exiting from the TB this way will cause the ``cpu_exec_interrupt()``
46 callback to be re-evaluated before executing additional instructions.
47 It is mandatory to exit this way after any CPU state changes that may
48 unmask interrupts.
50 In order to accelerate the cases where the TB for the new
51 simulated PC is already available, QEMU has mechanisms that allow
52 multiple TBs to be chained directly, without having to go back to the
53 main loop as described above. These mechanisms are:
55 ``lookup_and_goto_ptr``
56 ^^^^^^^^^^^^^^^^^^^^^^^
58 Calling ``tcg_gen_lookup_and_goto_ptr()`` will emit a call to
59 ``helper_lookup_tb_ptr``. This helper will look for an existing TB that
60 matches the current CPU state. If the destination TB is available its
61 code address is returned, otherwise the address of the JIT epilogue is
62 returned. The call to the helper is always followed by the tcg ``goto_ptr``
63 opcode, which branches to the returned address. In this way, we either
64 branch to the next TB or return to the main loop.
66 ``goto_tb + exit_tb``
67 ^^^^^^^^^^^^^^^^^^^^^
69 The translation code usually implements branching by performing the
70 following steps:
72 1. Call ``tcg_gen_goto_tb()`` passing a jump slot index (either 0 or 1)
73    as a parameter.
75 2. Emit TCG instructions to update the CPU state with any information
76    that has been assumed constant and is required by the main loop to
77    correctly locate and execute the next TB. For most guests, this is
78    just the PC of the branch destination, but others may store additional
79    data. The information updated in this step must be inferable from both
80    ``cpu_get_tb_cpu_state()`` and ``cpu_restore_state()``.
82 3. Call ``tcg_gen_exit_tb()`` passing the address of the current TB and
83    the jump slot index again.
85 Step 1, ``tcg_gen_goto_tb()``, will emit a ``goto_tb`` TCG
86 instruction that later on gets translated to a jump to an address
87 associated with the specified jump slot. Initially, this is the address
88 of step 2's instructions, which update the CPU state information. Step 3,
89 ``tcg_gen_exit_tb()``, exits from the current TB returning a tagged
90 pointer composed of the last executed TB’s address and the jump slot
91 index.
93 The first time this whole sequence is executed, step 1 simply jumps
94 to step 2. Then the CPU state information gets updated and we exit from
95 the current TB. As a result, the behavior is very similar to the less
96 optimized form described earlier in this section.
98 Next, the main loop looks for the next TB to execute using the
99 current CPU state information (creating the TB if it wasn’t already
100 available) and, before starting to execute the new TB’s instructions,
101 patches the previously executed TB by associating one of its jump
102 slots (the one specified in the call to ``tcg_gen_exit_tb()``) with the
103 address of the new TB.
105 The next time this previous TB is executed and we get to that same
106 ``goto_tb`` step, it will already be patched (assuming the destination TB
107 is still in memory) and will jump directly to the first instruction of
108 the destination TB, without going back to the main loop.
110 For the ``goto_tb + exit_tb`` mechanism to be used, the following
111 conditions need to be satisfied:
113 * The change in CPU state must be constant, e.g., a direct branch and
114   not an indirect branch.
116 * The direct branch cannot cross a page boundary. Memory mappings
117   may change, causing the code at the destination address to change.
119 Note that, on step 3 (``tcg_gen_exit_tb()``), in addition to the
120 jump slot index, the address of the TB just executed is also returned.
121 This address corresponds to the TB that will be patched; it may be
122 different than the one that was directly executed from the main loop
123 if the latter had already been chained to other TBs.
125 Self-modifying code and translated code invalidation
126 ----------------------------------------------------
128 Self-modifying code is a special challenge in x86 emulation because no
129 instruction cache invalidation is signaled by the application when code
130 is modified.
132 User-mode emulation marks a host page as write-protected (if it is
133 not already read-only) every time translated code is generated for a
134 basic block.  Then, if a write access is done to the page, Linux raises
135 a SEGV signal. QEMU then invalidates all the translated code in the page
136 and enables write accesses to the page.  For system emulation, write
137 protection is achieved through the software MMU.
139 Correct translated code invalidation is done efficiently by maintaining
140 a linked list of every translated block contained in a given page. Other
141 linked lists are also maintained to undo direct block chaining.
143 On RISC targets, correctly written software uses memory barriers and
144 cache flushes, so some of the protection above would not be
145 necessary. However, QEMU still requires that the generated code always
146 matches the target instructions in memory in order to handle
147 exceptions correctly.
149 Exception support
150 -----------------
152 longjmp() is used when an exception such as division by zero is
153 encountered.
155 The host SIGSEGV and SIGBUS signal handlers are used to get invalid
156 memory accesses.  QEMU keeps a map from host program counter to
157 target program counter, and looks up where the exception happened
158 based on the host program counter at the exception point.
160 On some targets, some bits of the virtual CPU's state are not flushed to the
161 memory until the end of the translation block.  This is done for internal
162 emulation state that is rarely accessed directly by the program and/or changes
163 very often throughout the execution of a translation block---this includes
164 condition codes on x86, delay slots on SPARC, conditional execution on
165 Arm, and so on.  This state is stored for each target instruction, and
166 looked up on exceptions.
168 MMU emulation
169 -------------
171 For system emulation QEMU uses a software MMU. In that mode, the MMU
172 virtual to physical address translation is done at every memory
173 access.
175 QEMU uses an address translation cache (TLB) to speed up the translation.
176 In order to avoid flushing the translated code each time the MMU
177 mappings change, all caches in QEMU are physically indexed.  This
178 means that each basic block is indexed with its physical address.
180 In order to avoid invalidating the basic block chain when MMU mappings
181 change, chaining is only performed when the destination of the jump
182 shares a page with the basic block that is performing the jump.
184 The MMU can also distinguish RAM and ROM memory areas from MMIO memory
185 areas.  Access is faster for RAM and ROM because the translation cache also
186 hosts the offset between guest address and host memory.  Accessing MMIO
187 memory areas instead calls out to C code for device emulation.
188 Finally, the MMU helps tracking dirty pages and pages pointed to by
189 translation blocks.