This commit was manufactured by cvs2svn to create tag
[qemu.git] / qemu-tech.texi
blob0df2a0b9660a5165baa61b42b719143ac7025228
1 \input texinfo @c -*- texinfo -*-
3 @iftex
4 @settitle QEMU Internals
5 @titlepage
6 @sp 7
7 @center @titlefont{QEMU Internals}
8 @sp 3
9 @end titlepage
10 @end iftex
12 @chapter Introduction
14 @section Features
16 QEMU is a FAST! processor emulator using a portable dynamic
17 translator.
19 QEMU has two operating modes:
21 @itemize @minus
23 @item 
24 Full system emulation. In this mode, QEMU emulates a full system
25 (usually a PC), including a processor and various peripherials. It can
26 be used to launch an different Operating System without rebooting the
27 PC or to debug system code.
29 @item 
30 User mode emulation (Linux host only). In this mode, QEMU can launch
31 Linux processes compiled for one CPU on another CPU. It can be used to
32 launch the Wine Windows API emulator (@url{http://www.winehq.org}) or
33 to ease cross-compilation and cross-debugging.
35 @end itemize
37 As QEMU requires no host kernel driver to run, it is very safe and
38 easy to use.
40 QEMU generic features:
42 @itemize 
44 @item User space only or full system emulation.
46 @item Using dynamic translation to native code for reasonnable speed.
48 @item Working on x86 and PowerPC hosts. Being tested on ARM, Sparc32, Alpha and S390.
50 @item Self-modifying code support.
52 @item Precise exceptions support.
54 @item The virtual CPU is a library (@code{libqemu}) which can be used 
55 in other projects (look at @file{qemu/tests/qruncom.c} to have an
56 example of user mode @code{libqemu} usage).
58 @end itemize
60 QEMU user mode emulation features:
61 @itemize 
62 @item Generic Linux system call converter, including most ioctls.
64 @item clone() emulation using native CPU clone() to use Linux scheduler for threads.
66 @item Accurate signal handling by remapping host signals to target signals. 
67 @end itemize
68 @end itemize
70 QEMU full system emulation features:
71 @itemize 
72 @item QEMU can either use a full software MMU for maximum portability or use the host system call mmap() to simulate the target MMU.
73 @end itemize
75 @section x86 emulation
77 QEMU x86 target features:
79 @itemize 
81 @item The virtual x86 CPU supports 16 bit and 32 bit addressing with segmentation. 
82 LDT/GDT and IDT are emulated. VM86 mode is also supported to run DOSEMU.
84 @item Support of host page sizes bigger than 4KB in user mode emulation.
86 @item QEMU can emulate itself on x86.
88 @item An extensive Linux x86 CPU test program is included @file{tests/test-i386}. 
89 It can be used to test other x86 virtual CPUs.
91 @end itemize
93 Current QEMU limitations:
95 @itemize 
97 @item No SSE/MMX support (yet).
99 @item No x86-64 support.
101 @item IPC syscalls are missing.
103 @item The x86 segment limits and access rights are not tested at every 
104 memory access (yet). Hopefully, very few OSes seem to rely on that for
105 normal use.
107 @item On non x86 host CPUs, @code{double}s are used instead of the non standard 
108 10 byte @code{long double}s of x86 for floating point emulation to get
109 maximum performances.
111 @end itemize
113 @section ARM emulation
115 @itemize
117 @item Full ARM 7 user emulation.
119 @item NWFPE FPU support included in user Linux emulation.
121 @item Can run most ARM Linux binaries.
123 @end itemize
125 @section PowerPC emulation
127 @itemize
129 @item Full PowerPC 32 bit emulation, including priviledged instructions, 
130 FPU and MMU.
132 @item Can run most PowerPC Linux binaries.
134 @end itemize
136 @section SPARC emulation
138 @itemize
140 @item SPARC V8 user support, except FPU instructions.
142 @item Can run some SPARC Linux binaries.
144 @end itemize
146 @chapter QEMU Internals
148 @section QEMU compared to other emulators
150 Like bochs [3], QEMU emulates an x86 CPU. But QEMU is much faster than
151 bochs as it uses dynamic compilation. Bochs is closely tied to x86 PC
152 emulation while QEMU can emulate several processors.
154 Like Valgrind [2], QEMU does user space emulation and dynamic
155 translation. Valgrind is mainly a memory debugger while QEMU has no
156 support for it (QEMU could be used to detect out of bound memory
157 accesses as Valgrind, but it has no support to track uninitialised data
158 as Valgrind does). The Valgrind dynamic translator generates better code
159 than QEMU (in particular it does register allocation) but it is closely
160 tied to an x86 host and target and has no support for precise exceptions
161 and system emulation.
163 EM86 [4] is the closest project to user space QEMU (and QEMU still uses
164 some of its code, in particular the ELF file loader). EM86 was limited
165 to an alpha host and used a proprietary and slow interpreter (the
166 interpreter part of the FX!32 Digital Win32 code translator [5]).
168 TWIN [6] is a Windows API emulator like Wine. It is less accurate than
169 Wine but includes a protected mode x86 interpreter to launch x86 Windows
170 executables. Such an approach as greater potential because most of the
171 Windows API is executed natively but it is far more difficult to develop
172 because all the data structures and function parameters exchanged
173 between the API and the x86 code must be converted.
175 User mode Linux [7] was the only solution before QEMU to launch a
176 Linux kernel as a process while not needing any host kernel
177 patches. However, user mode Linux requires heavy kernel patches while
178 QEMU accepts unpatched Linux kernels. The price to pay is that QEMU is
179 slower.
181 The new Plex86 [8] PC virtualizer is done in the same spirit as the
182 qemu-fast system emulator. It requires a patched Linux kernel to work
183 (you cannot launch the same kernel on your PC), but the patches are
184 really small. As it is a PC virtualizer (no emulation is done except
185 for some priveledged instructions), it has the potential of being
186 faster than QEMU. The downside is that a complicated (and potentially
187 unsafe) host kernel patch is needed.
189 The commercial PC Virtualizers (VMWare [9], VirtualPC [10], TwoOStwo
190 [11]) are faster than QEMU, but they all need specific, proprietary
191 and potentially unsafe host drivers. Moreover, they are unable to
192 provide cycle exact simulation as an emulator can.
194 @section Portable dynamic translation
196 QEMU is a dynamic translator. When it first encounters a piece of code,
197 it converts it to the host instruction set. Usually dynamic translators
198 are very complicated and highly CPU dependent. QEMU uses some tricks
199 which make it relatively easily portable and simple while achieving good
200 performances.
202 The basic idea is to split every x86 instruction into fewer simpler
203 instructions. Each simple instruction is implemented by a piece of C
204 code (see @file{target-i386/op.c}). Then a compile time tool
205 (@file{dyngen}) takes the corresponding object file (@file{op.o})
206 to generate a dynamic code generator which concatenates the simple
207 instructions to build a function (see @file{op.h:dyngen_code()}).
209 In essence, the process is similar to [1], but more work is done at
210 compile time. 
212 A key idea to get optimal performances is that constant parameters can
213 be passed to the simple operations. For that purpose, dummy ELF
214 relocations are generated with gcc for each constant parameter. Then,
215 the tool (@file{dyngen}) can locate the relocations and generate the
216 appriopriate C code to resolve them when building the dynamic code.
218 That way, QEMU is no more difficult to port than a dynamic linker.
220 To go even faster, GCC static register variables are used to keep the
221 state of the virtual CPU.
223 @section Register allocation
225 Since QEMU uses fixed simple instructions, no efficient register
226 allocation can be done. However, because RISC CPUs have a lot of
227 register, most of the virtual CPU state can be put in registers without
228 doing complicated register allocation.
230 @section Condition code optimisations
232 Good CPU condition codes emulation (@code{EFLAGS} register on x86) is a
233 critical point to get good performances. QEMU uses lazy condition code
234 evaluation: instead of computing the condition codes after each x86
235 instruction, it just stores one operand (called @code{CC_SRC}), the
236 result (called @code{CC_DST}) and the type of operation (called
237 @code{CC_OP}).
239 @code{CC_OP} is almost never explicitely set in the generated code
240 because it is known at translation time.
242 In order to increase performances, a backward pass is performed on the
243 generated simple instructions (see
244 @code{target-i386/translate.c:optimize_flags()}). When it can be proved that
245 the condition codes are not needed by the next instructions, no
246 condition codes are computed at all.
248 @section CPU state optimisations
250 The x86 CPU has many internal states which change the way it evaluates
251 instructions. In order to achieve a good speed, the translation phase
252 considers that some state information of the virtual x86 CPU cannot
253 change in it. For example, if the SS, DS and ES segments have a zero
254 base, then the translator does not even generate an addition for the
255 segment base.
257 [The FPU stack pointer register is not handled that way yet].
259 @section Translation cache
261 A 16 MByte cache holds the most recently used translations. For
262 simplicity, it is completely flushed when it is full. A translation unit
263 contains just a single basic block (a block of x86 instructions
264 terminated by a jump or by a virtual CPU state change which the
265 translator cannot deduce statically).
267 @section Direct block chaining
269 After each translated basic block is executed, QEMU uses the simulated
270 Program Counter (PC) and other cpu state informations (such as the CS
271 segment base value) to find the next basic block.
273 In order to accelerate the most common cases where the new simulated PC
274 is known, QEMU can patch a basic block so that it jumps directly to the
275 next one.
277 The most portable code uses an indirect jump. An indirect jump makes
278 it easier to make the jump target modification atomic. On some host
279 architectures (such as x86 or PowerPC), the @code{JUMP} opcode is
280 directly patched so that the block chaining has no overhead.
282 @section Self-modifying code and translated code invalidation
284 Self-modifying code is a special challenge in x86 emulation because no
285 instruction cache invalidation is signaled by the application when code
286 is modified.
288 When translated code is generated for a basic block, the corresponding
289 host page is write protected if it is not already read-only (with the
290 system call @code{mprotect()}). Then, if a write access is done to the
291 page, Linux raises a SEGV signal. QEMU then invalidates all the
292 translated code in the page and enables write accesses to the page.
294 Correct translated code invalidation is done efficiently by maintaining
295 a linked list of every translated block contained in a given page. Other
296 linked lists are also maintained to undo direct block chaining. 
298 Although the overhead of doing @code{mprotect()} calls is important,
299 most MSDOS programs can be emulated at reasonnable speed with QEMU and
300 DOSEMU.
302 Note that QEMU also invalidates pages of translated code when it detects
303 that memory mappings are modified with @code{mmap()} or @code{munmap()}.
305 When using a software MMU, the code invalidation is more efficient: if
306 a given code page is invalidated too often because of write accesses,
307 then a bitmap representing all the code inside the page is
308 built. Every store into that page checks the bitmap to see if the code
309 really needs to be invalidated. It avoids invalidating the code when
310 only data is modified in the page.
312 @section Exception support
314 longjmp() is used when an exception such as division by zero is
315 encountered. 
317 The host SIGSEGV and SIGBUS signal handlers are used to get invalid
318 memory accesses. The exact CPU state can be retrieved because all the
319 x86 registers are stored in fixed host registers. The simulated program
320 counter is found by retranslating the corresponding basic block and by
321 looking where the host program counter was at the exception point.
323 The virtual CPU cannot retrieve the exact @code{EFLAGS} register because
324 in some cases it is not computed because of condition code
325 optimisations. It is not a big concern because the emulated code can
326 still be restarted in any cases.
328 @section MMU emulation
330 For system emulation, QEMU uses the mmap() system call to emulate the
331 target CPU MMU. It works as long the emulated OS does not use an area
332 reserved by the host OS (such as the area above 0xc0000000 on x86
333 Linux).
335 In order to be able to launch any OS, QEMU also supports a soft
336 MMU. In that mode, the MMU virtual to physical address translation is
337 done at every memory access. QEMU uses an address translation cache to
338 speed up the translation.
340 In order to avoid flushing the translated code each time the MMU
341 mappings change, QEMU uses a physically indexed translation cache. It
342 means that each basic block is indexed with its physical address. 
344 When MMU mappings change, only the chaining of the basic blocks is
345 reset (i.e. a basic block can no longer jump directly to another one).
347 @section Hardware interrupts
349 In order to be faster, QEMU does not check at every basic block if an
350 hardware interrupt is pending. Instead, the user must asynchrously
351 call a specific function to tell that an interrupt is pending. This
352 function resets the chaining of the currently executing basic
353 block. It ensures that the execution will return soon in the main loop
354 of the CPU emulator. Then the main loop can test if the interrupt is
355 pending and handle it.
357 @section User emulation specific details
359 @subsection Linux system call translation
361 QEMU includes a generic system call translator for Linux. It means that
362 the parameters of the system calls can be converted to fix the
363 endianness and 32/64 bit issues. The IOCTLs are converted with a generic
364 type description system (see @file{ioctls.h} and @file{thunk.c}).
366 QEMU supports host CPUs which have pages bigger than 4KB. It records all
367 the mappings the process does and try to emulated the @code{mmap()}
368 system calls in cases where the host @code{mmap()} call would fail
369 because of bad page alignment.
371 @subsection Linux signals
373 Normal and real-time signals are queued along with their information
374 (@code{siginfo_t}) as it is done in the Linux kernel. Then an interrupt
375 request is done to the virtual CPU. When it is interrupted, one queued
376 signal is handled by generating a stack frame in the virtual CPU as the
377 Linux kernel does. The @code{sigreturn()} system call is emulated to return
378 from the virtual signal handler.
380 Some signals (such as SIGALRM) directly come from the host. Other
381 signals are synthetized from the virtual CPU exceptions such as SIGFPE
382 when a division by zero is done (see @code{main.c:cpu_loop()}).
384 The blocked signal mask is still handled by the host Linux kernel so
385 that most signal system calls can be redirected directly to the host
386 Linux kernel. Only the @code{sigaction()} and @code{sigreturn()} system
387 calls need to be fully emulated (see @file{signal.c}).
389 @subsection clone() system call and threads
391 The Linux clone() system call is usually used to create a thread. QEMU
392 uses the host clone() system call so that real host threads are created
393 for each emulated thread. One virtual CPU instance is created for each
394 thread.
396 The virtual x86 CPU atomic operations are emulated with a global lock so
397 that their semantic is preserved.
399 Note that currently there are still some locking issues in QEMU. In
400 particular, the translated cache flush is not protected yet against
401 reentrancy.
403 @subsection Self-virtualization
405 QEMU was conceived so that ultimately it can emulate itself. Although
406 it is not very useful, it is an important test to show the power of the
407 emulator.
409 Achieving self-virtualization is not easy because there may be address
410 space conflicts. QEMU solves this problem by being an executable ELF
411 shared object as the ld-linux.so ELF interpreter. That way, it can be
412 relocated at load time.
414 @section Bibliography
416 @table @asis
418 @item [1] 
419 @url{http://citeseer.nj.nec.com/piumarta98optimizing.html}, Optimizing
420 direct threaded code by selective inlining (1998) by Ian Piumarta, Fabio
421 Riccardi.
423 @item [2]
424 @url{http://developer.kde.org/~sewardj/}, Valgrind, an open-source
425 memory debugger for x86-GNU/Linux, by Julian Seward.
427 @item [3]
428 @url{http://bochs.sourceforge.net/}, the Bochs IA-32 Emulator Project,
429 by Kevin Lawton et al.
431 @item [4]
432 @url{http://www.cs.rose-hulman.edu/~donaldlf/em86/index.html}, the EM86
433 x86 emulator on Alpha-Linux.
435 @item [5]
436 @url{http://www.usenix.org/publications/library/proceedings/usenix-nt97/full_papers/chernoff/chernoff.pdf},
437 DIGITAL FX!32: Running 32-Bit x86 Applications on Alpha NT, by Anton
438 Chernoff and Ray Hookway.
440 @item [6]
441 @url{http://www.willows.com/}, Windows API library emulation from
442 Willows Software.
444 @item [7]
445 @url{http://user-mode-linux.sourceforge.net/}, 
446 The User-mode Linux Kernel.
448 @item [8]
449 @url{http://www.plex86.org/}, 
450 The new Plex86 project.
452 @item [9]
453 @url{http://www.vmware.com/}, 
454 The VMWare PC virtualizer.
456 @item [10]
457 @url{http://www.microsoft.com/windowsxp/virtualpc/}, 
458 The VirtualPC PC virtualizer.
460 @item [11]
461 @url{http://www.twoostwo.org/}, 
462 The TwoOStwo PC virtualizer.
464 @end table
466 @chapter Regression Tests
468 In the directory @file{tests/}, various interesting testing programs
469 are available. There are used for regression testing.
471 @section @file{test-i386}
473 This program executes most of the 16 bit and 32 bit x86 instructions and
474 generates a text output. It can be compared with the output obtained with
475 a real CPU or another emulator. The target @code{make test} runs this
476 program and a @code{diff} on the generated output.
478 The Linux system call @code{modify_ldt()} is used to create x86 selectors
479 to test some 16 bit addressing and 32 bit with segmentation cases.
481 The Linux system call @code{vm86()} is used to test vm86 emulation.
483 Various exceptions are raised to test most of the x86 user space
484 exception reporting.
486 @section @file{linux-test}
488 This program tests various Linux system calls. It is used to verify
489 that the system call parameters are correctly converted between target
490 and host CPUs.
492 @section @file{qruncom.c}
494 Example of usage of @code{libqemu} to emulate a user mode i386 CPU.