qemu 原理

qemu

2003 年由 Fabrice Bellard 创建。
Just-in-time compilation support to achieve high performance

http://archives.cse.iitd.ernet.in/~sbansal/csl862-virt/2010/readings/bellard.pdf
https://www.slideshare.net/RampantJeff/qemu-binary-translation

Execution flow

qemu 原理_第1张图片

qemu 原理_第2张图片

User mode emulation

Run a Linux process compiled for one target CPU on another CPU. (Same OS)
Ex. execute arm/linux program on x86/linux

Full system emulation

Run an OS.

Usage

For cross-compilation development environments
Virtualization, device emulation, for kvm
Android Emulator

Portable dynamic translation

The first step is to split each target CPU instruction into fewer simpler instructions called micro operations.
Each micro operation is implemented by a small piece of C code.
This small C source code is compiled by GCC to an object file.
The translation from target CPU instructions to micro operations is done entirely with hand coded code.

A compile time tool called dyngen uses the object file containing the micro operations as input to generate a dynamic code generator. This dynamic code generator is invoked at runtime to generate a complete host function which concatenates several micro operations.

Translation Blocks

When QEMU first encounters a piece of target code, it translates it to host code up to the next jump or instruction modifying the static CPU state in a way that cannot be deduced at translation time. We call these basic blocks Translated Blocks (TBs).

Self-modifying code and translated code invalidation

When translated code is generated for a TB, the corresponding host page is write protected if it is not already read-only. If a write access is made to the page, then QEMU invalidates all the translated code in it and reenables write accesses to it.

Hardware interrupts

In order to be faster, QEMU does not check at every TB if an hardware interrupt is pending. Instead, the user must asynchronously call a specific function to tell that an interrupt is pending. This function resets the chaining of the currently executing TB. It ensures that the execution will return soon in the main loop of the CPU emulator. Then the main loop tests if an interrupt is pending and handles it.

Tiny Code Generator (TCG)

TCG 的前端与后端, 前端将目标平台的指令翻译成 TCG 的 micro-ops,后端将 micro-ops 翻译成 host 平台的指令。
qemu 原理_第3张图片

qemu 原理_第4张图片
TCG 前端提供了 API 接口,复杂的操作还可以定义 helper 函数。
qemu 原理_第5张图片

TCG backend

qemu 原理_第6张图片

TCG internal

由操作码和操作参数组成,操作数由 gen_opc_ptr 指向,参数由 gen_opparam_ptr 指向。
qemu 原理_第7张图片
复杂的操作则由简单操作组成。
qemu 原理_第8张图片

例子

一个加法操作,r0 = r1 + r2
被翻译成4条微操作,微操作是事先定义好的,已经生成了二进制码。

这里
T0被映射到r15
T1被映射到r12
T2被映射到r13

micro-ops 二进制码

qemu 原理_第9张图片

根据操作码复制 micro-ops

qemu 原理_第10张图片
qemu 原理_第11张图片

Optimization

  • Use basic block as execution unit (space locality)
  • Chain basic block
  • Cache translated basic block (temporal locality)

TCG 对应的源码树

qemu 原理_第12张图片

Road map

qemu 原理_第13张图片

你可能感兴趣的:(虚拟机)