cachepc-qemu

Fork of AMDESE/qemu with changes for cachepc side-channel attack
git clone https://git.sinitax.com/sinitax/cachepc-qemu
Log | Files | Refs | Submodules | LICENSE | sfeed.txt

tcg.rst (8711B)


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