qemu-tech: document lazy condition code evaluation in cpu.h
[sdk/emulator/qemu.git] / qemu-tech.texi
1 \input texinfo @c -*- texinfo -*-
2 @c %**start of header
3 @setfilename qemu-tech.info
4
5 @documentlanguage en
6 @documentencoding UTF-8
7
8 @settitle QEMU Internals
9 @exampleindent 0
10 @paragraphindent 0
11 @c %**end of header
12
13 @ifinfo
14 @direntry
15 * QEMU Internals: (qemu-tech).   The QEMU Emulator Internals.
16 @end direntry
17 @end ifinfo
18
19 @iftex
20 @titlepage
21 @sp 7
22 @center @titlefont{QEMU Internals}
23 @sp 3
24 @end titlepage
25 @end iftex
26
27 @ifnottex
28 @node Top
29 @top
30
31 @menu
32 * Introduction::
33 * QEMU Internals::
34 * Regression Tests::
35 @end menu
36 @end ifnottex
37
38 @contents
39
40 @node Introduction
41 @chapter Introduction
42
43 @menu
44 * intro_x86_emulation::    x86 and x86-64 emulation
45 * intro_arm_emulation::    ARM emulation
46 * intro_mips_emulation::   MIPS emulation
47 * intro_ppc_emulation::    PowerPC emulation
48 * intro_sparc_emulation::  Sparc32 and Sparc64 emulation
49 * intro_xtensa_emulation:: Xtensa emulation
50 * intro_other_emulation::  Other CPU emulation
51 @end menu
52
53 @node intro_x86_emulation
54 @section x86 and x86-64 emulation
55
56 QEMU x86 target features:
57
58 @itemize
59
60 @item The virtual x86 CPU supports 16 bit and 32 bit addressing with segmentation.
61 LDT/GDT and IDT are emulated. VM86 mode is also supported to run
62 DOSEMU. There is some support for MMX/3DNow!, SSE, SSE2, SSE3, SSSE3,
63 and SSE4 as well as x86-64 SVM.
64
65 @item Support of host page sizes bigger than 4KB in user mode emulation.
66
67 @item QEMU can emulate itself on x86.
68
69 @item An extensive Linux x86 CPU test program is included @file{tests/test-i386}.
70 It can be used to test other x86 virtual CPUs.
71
72 @end itemize
73
74 Current QEMU limitations:
75
76 @itemize
77
78 @item Limited x86-64 support.
79
80 @item IPC syscalls are missing.
81
82 @item The x86 segment limits and access rights are not tested at every
83 memory access (yet). Hopefully, very few OSes seem to rely on that for
84 normal use.
85
86 @end itemize
87
88 @node intro_arm_emulation
89 @section ARM emulation
90
91 @itemize
92
93 @item Full ARM 7 user emulation.
94
95 @item NWFPE FPU support included in user Linux emulation.
96
97 @item Can run most ARM Linux binaries.
98
99 @end itemize
100
101 @node intro_mips_emulation
102 @section MIPS emulation
103
104 @itemize
105
106 @item The system emulation allows full MIPS32/MIPS64 Release 2 emulation,
107 including privileged instructions, FPU and MMU, in both little and big
108 endian modes.
109
110 @item The Linux userland emulation can run many 32 bit MIPS Linux binaries.
111
112 @end itemize
113
114 Current QEMU limitations:
115
116 @itemize
117
118 @item Self-modifying code is not always handled correctly.
119
120 @item 64 bit userland emulation is not implemented.
121
122 @item The system emulation is not complete enough to run real firmware.
123
124 @item The watchpoint debug facility is not implemented.
125
126 @end itemize
127
128 @node intro_ppc_emulation
129 @section PowerPC emulation
130
131 @itemize
132
133 @item Full PowerPC 32 bit emulation, including privileged instructions,
134 FPU and MMU.
135
136 @item Can run most PowerPC Linux binaries.
137
138 @end itemize
139
140 @node intro_sparc_emulation
141 @section Sparc32 and Sparc64 emulation
142
143 @itemize
144
145 @item Full SPARC V8 emulation, including privileged
146 instructions, FPU and MMU. SPARC V9 emulation includes most privileged
147 and VIS instructions, FPU and I/D MMU. Alignment is fully enforced.
148
149 @item Can run most 32-bit SPARC Linux binaries, SPARC32PLUS Linux binaries and
150 some 64-bit SPARC Linux binaries.
151
152 @end itemize
153
154 Current QEMU limitations:
155
156 @itemize
157
158 @item IPC syscalls are missing.
159
160 @item Floating point exception support is buggy.
161
162 @item Atomic instructions are not correctly implemented.
163
164 @item There are still some problems with Sparc64 emulators.
165
166 @end itemize
167
168 @node intro_xtensa_emulation
169 @section Xtensa emulation
170
171 @itemize
172
173 @item Core Xtensa ISA emulation, including most options: code density,
174 loop, extended L32R, 16- and 32-bit multiplication, 32-bit division,
175 MAC16, miscellaneous operations, boolean, FP coprocessor, coprocessor
176 context, debug, multiprocessor synchronization,
177 conditional store, exceptions, relocatable vectors, unaligned exception,
178 interrupts (including high priority and timer), hardware alignment,
179 region protection, region translation, MMU, windowed registers, thread
180 pointer, processor ID.
181
182 @item Not implemented options: data/instruction cache (including cache
183 prefetch and locking), XLMI, processor interface. Also options not
184 covered by the core ISA (e.g. FLIX, wide branches) are not implemented.
185
186 @item Can run most Xtensa Linux binaries.
187
188 @item New core configuration that requires no additional instructions
189 may be created from overlay with minimal amount of hand-written code.
190
191 @end itemize
192
193 @node intro_other_emulation
194 @section Other CPU emulation
195
196 In addition to the above, QEMU supports emulation of other CPUs with
197 varying levels of success. These are:
198
199 @itemize
200
201 @item
202 Alpha
203 @item
204 CRIS
205 @item
206 M68k
207 @item
208 SH4
209 @end itemize
210
211 @node QEMU Internals
212 @chapter QEMU Internals
213
214 @menu
215 * QEMU compared to other emulators::
216 * Portable dynamic translation::
217 * CPU state optimisations::
218 * Translation cache::
219 * Direct block chaining::
220 * Self-modifying code and translated code invalidation::
221 * Exception support::
222 * MMU emulation::
223 * Device emulation::
224 * Hardware interrupts::
225 * User emulation specific details::
226 * Bibliography::
227 @end menu
228
229 @node QEMU compared to other emulators
230 @section QEMU compared to other emulators
231
232 Like bochs [1], QEMU emulates an x86 CPU. But QEMU is much faster than
233 bochs as it uses dynamic compilation. Bochs is closely tied to x86 PC
234 emulation while QEMU can emulate several processors.
235
236 Like Valgrind [2], QEMU does user space emulation and dynamic
237 translation. Valgrind is mainly a memory debugger while QEMU has no
238 support for it (QEMU could be used to detect out of bound memory
239 accesses as Valgrind, but it has no support to track uninitialised data
240 as Valgrind does). The Valgrind dynamic translator generates better code
241 than QEMU (in particular it does register allocation) but it is closely
242 tied to an x86 host and target and has no support for precise exceptions
243 and system emulation.
244
245 EM86 [3] is the closest project to user space QEMU (and QEMU still uses
246 some of its code, in particular the ELF file loader). EM86 was limited
247 to an alpha host and used a proprietary and slow interpreter (the
248 interpreter part of the FX!32 Digital Win32 code translator [4]).
249
250 TWIN from Willows Software was a Windows API emulator like Wine. It is less
251 accurate than Wine but includes a protected mode x86 interpreter to launch
252 x86 Windows executables. Such an approach has greater potential because most
253 of the Windows API is executed natively but it is far more difficult to
254 develop because all the data structures and function parameters exchanged
255 between the API and the x86 code must be converted.
256
257 User mode Linux [5] was the only solution before QEMU to launch a
258 Linux kernel as a process while not needing any host kernel
259 patches. However, user mode Linux requires heavy kernel patches while
260 QEMU accepts unpatched Linux kernels. The price to pay is that QEMU is
261 slower.
262
263 The Plex86 [6] PC virtualizer is done in the same spirit as the now
264 obsolete qemu-fast system emulator. It requires a patched Linux kernel
265 to work (you cannot launch the same kernel on your PC), but the
266 patches are really small. As it is a PC virtualizer (no emulation is
267 done except for some privileged instructions), it has the potential of
268 being faster than QEMU. The downside is that a complicated (and
269 potentially unsafe) host kernel patch is needed.
270
271 The commercial PC Virtualizers (VMWare [7], VirtualPC [8]) are faster
272 than QEMU (without virtualization), but they all need specific, proprietary
273 and potentially unsafe host drivers. Moreover, they are unable to
274 provide cycle exact simulation as an emulator can.
275
276 VirtualBox [9], Xen [10] and KVM [11] are based on QEMU. QEMU-SystemC
277 [12] uses QEMU to simulate a system where some hardware devices are
278 developed in SystemC.
279
280 @node Portable dynamic translation
281 @section Portable dynamic translation
282
283 QEMU is a dynamic translator. When it first encounters a piece of code,
284 it converts it to the host instruction set. Usually dynamic translators
285 are very complicated and highly CPU dependent. QEMU uses some tricks
286 which make it relatively easily portable and simple while achieving good
287 performances.
288
289 QEMU's dynamic translation backend is called TCG, for "Tiny Code
290 Generator". For more information, please take a look at @code{tcg/README}.
291
292 @node CPU state optimisations
293 @section CPU state optimisations
294
295 The target CPUs have many internal states which change the way it
296 evaluates instructions. In order to achieve a good speed, the
297 translation phase considers that some state information of the virtual
298 CPU cannot change in it. The state is recorded in the Translation
299 Block (TB). If the state changes (e.g. privilege level), a new TB will
300 be generated and the previous TB won't be used anymore until the state
301 matches the state recorded in the previous TB. For example, if the SS,
302 DS and ES segments have a zero base, then the translator does not even
303 generate an addition for the segment base.
304
305 [The FPU stack pointer register is not handled that way yet].
306
307 @node Translation cache
308 @section Translation cache
309
310 A 32 MByte cache holds the most recently used translations. For
311 simplicity, it is completely flushed when it is full. A translation unit
312 contains just a single basic block (a block of x86 instructions
313 terminated by a jump or by a virtual CPU state change which the
314 translator cannot deduce statically).
315
316 @node Direct block chaining
317 @section Direct block chaining
318
319 After each translated basic block is executed, QEMU uses the simulated
320 Program Counter (PC) and other cpu state information (such as the CS
321 segment base value) to find the next basic block.
322
323 In order to accelerate the most common cases where the new simulated PC
324 is known, QEMU can patch a basic block so that it jumps directly to the
325 next one.
326
327 The most portable code uses an indirect jump. An indirect jump makes
328 it easier to make the jump target modification atomic. On some host
329 architectures (such as x86 or PowerPC), the @code{JUMP} opcode is
330 directly patched so that the block chaining has no overhead.
331
332 @node Self-modifying code and translated code invalidation
333 @section Self-modifying code and translated code invalidation
334
335 Self-modifying code is a special challenge in x86 emulation because no
336 instruction cache invalidation is signaled by the application when code
337 is modified.
338
339 When translated code is generated for a basic block, the corresponding
340 host page is write protected if it is not already read-only. Then, if
341 a write access is done to the page, Linux raises a SEGV signal. QEMU
342 then invalidates all the translated code in the page and enables write
343 accesses to the page.
344
345 Correct translated code invalidation is done efficiently by maintaining
346 a linked list of every translated block contained in a given page. Other
347 linked lists are also maintained to undo direct block chaining.
348
349 On RISC targets, correctly written software uses memory barriers and
350 cache flushes, so some of the protection above would not be
351 necessary. However, QEMU still requires that the generated code always
352 matches the target instructions in memory in order to handle
353 exceptions correctly.
354
355 @node Exception support
356 @section Exception support
357
358 longjmp() is used when an exception such as division by zero is
359 encountered.
360
361 The host SIGSEGV and SIGBUS signal handlers are used to get invalid
362 memory accesses. The simulated program counter is found by
363 retranslating the corresponding basic block and by looking where the
364 host program counter was at the exception point.
365
366 The virtual CPU cannot retrieve the exact @code{EFLAGS} register because
367 in some cases it is not computed because of condition code
368 optimisations. It is not a big concern because the emulated code can
369 still be restarted in any cases.
370
371 @node MMU emulation
372 @section MMU emulation
373
374 For system emulation QEMU supports a soft MMU. In that mode, the MMU
375 virtual to physical address translation is done at every memory
376 access. QEMU uses an address translation cache to speed up the
377 translation.
378
379 In order to avoid flushing the translated code each time the MMU
380 mappings change, QEMU uses a physically indexed translation cache. It
381 means that each basic block is indexed with its physical address.
382
383 When MMU mappings change, only the chaining of the basic blocks is
384 reset (i.e. a basic block can no longer jump directly to another one).
385
386 @node Device emulation
387 @section Device emulation
388
389 Systems emulated by QEMU are organized by boards. At initialization
390 phase, each board instantiates a number of CPUs, devices, RAM and
391 ROM. Each device in turn can assign I/O ports or memory areas (for
392 MMIO) to its handlers. When the emulation starts, an access to the
393 ports or MMIO memory areas assigned to the device causes the
394 corresponding handler to be called.
395
396 RAM and ROM are handled more optimally, only the offset to the host
397 memory needs to be added to the guest address.
398
399 The video RAM of VGA and other display cards is special: it can be
400 read or written directly like RAM, but write accesses cause the memory
401 to be marked with VGA_DIRTY flag as well.
402
403 QEMU supports some device classes like serial and parallel ports, USB,
404 drives and network devices, by providing APIs for easier connection to
405 the generic, higher level implementations. The API hides the
406 implementation details from the devices, like native device use or
407 advanced block device formats like QCOW.
408
409 Usually the devices implement a reset method and register support for
410 saving and loading of the device state. The devices can also use
411 timers, especially together with the use of bottom halves (BHs).
412
413 @node Hardware interrupts
414 @section Hardware interrupts
415
416 In order to be faster, QEMU does not check at every basic block if a
417 hardware interrupt is pending. Instead, the user must asynchronously
418 call a specific function to tell that an interrupt is pending. This
419 function resets the chaining of the currently executing basic
420 block. It ensures that the execution will return soon in the main loop
421 of the CPU emulator. Then the main loop can test if the interrupt is
422 pending and handle it.
423
424 @node User emulation specific details
425 @section User emulation specific details
426
427 @subsection Linux system call translation
428
429 QEMU includes a generic system call translator for Linux. It means that
430 the parameters of the system calls can be converted to fix the
431 endianness and 32/64 bit issues. The IOCTLs are converted with a generic
432 type description system (see @file{ioctls.h} and @file{thunk.c}).
433
434 QEMU supports host CPUs which have pages bigger than 4KB. It records all
435 the mappings the process does and try to emulated the @code{mmap()}
436 system calls in cases where the host @code{mmap()} call would fail
437 because of bad page alignment.
438
439 @subsection Linux signals
440
441 Normal and real-time signals are queued along with their information
442 (@code{siginfo_t}) as it is done in the Linux kernel. Then an interrupt
443 request is done to the virtual CPU. When it is interrupted, one queued
444 signal is handled by generating a stack frame in the virtual CPU as the
445 Linux kernel does. The @code{sigreturn()} system call is emulated to return
446 from the virtual signal handler.
447
448 Some signals (such as SIGALRM) directly come from the host. Other
449 signals are synthesized from the virtual CPU exceptions such as SIGFPE
450 when a division by zero is done (see @code{main.c:cpu_loop()}).
451
452 The blocked signal mask is still handled by the host Linux kernel so
453 that most signal system calls can be redirected directly to the host
454 Linux kernel. Only the @code{sigaction()} and @code{sigreturn()} system
455 calls need to be fully emulated (see @file{signal.c}).
456
457 @subsection clone() system call and threads
458
459 The Linux clone() system call is usually used to create a thread. QEMU
460 uses the host clone() system call so that real host threads are created
461 for each emulated thread. One virtual CPU instance is created for each
462 thread.
463
464 The virtual x86 CPU atomic operations are emulated with a global lock so
465 that their semantic is preserved.
466
467 Note that currently there are still some locking issues in QEMU. In
468 particular, the translated cache flush is not protected yet against
469 reentrancy.
470
471 @subsection Self-virtualization
472
473 QEMU was conceived so that ultimately it can emulate itself. Although
474 it is not very useful, it is an important test to show the power of the
475 emulator.
476
477 Achieving self-virtualization is not easy because there may be address
478 space conflicts. QEMU user emulators solve this problem by being an
479 executable ELF shared object as the ld-linux.so ELF interpreter. That
480 way, it can be relocated at load time.
481
482 @node Bibliography
483 @section Bibliography
484
485 @table @asis
486
487 @item [1]
488 @url{http://bochs.sourceforge.net/}, the Bochs IA-32 Emulator Project,
489 by Kevin Lawton et al.
490
491 @item [2]
492 @url{http://www.valgrind.org/}, Valgrind, an open-source memory debugger
493 for GNU/Linux.
494
495 @item [3]
496 @url{http://ftp.dreamtime.org/pub/linux/Linux-Alpha/em86/v0.2/docs/em86.html},
497 the EM86 x86 emulator on Alpha-Linux.
498
499 @item [4]
500 @url{http://www.usenix.org/publications/library/proceedings/usenix-nt97/@/full_papers/chernoff/chernoff.pdf},
501 DIGITAL FX!32: Running 32-Bit x86 Applications on Alpha NT, by Anton
502 Chernoff and Ray Hookway.
503
504 @item [5]
505 @url{http://user-mode-linux.sourceforge.net/},
506 The User-mode Linux Kernel.
507
508 @item [6]
509 @url{http://www.plex86.org/},
510 The new Plex86 project.
511
512 @item [7]
513 @url{http://www.vmware.com/},
514 The VMWare PC virtualizer.
515
516 @item [8]
517 @url{https://www.microsoft.com/download/details.aspx?id=3702},
518 The VirtualPC PC virtualizer.
519
520 @item [9]
521 @url{http://virtualbox.org/},
522 The VirtualBox PC virtualizer.
523
524 @item [10]
525 @url{http://www.xen.org/},
526 The Xen hypervisor.
527
528 @item [11]
529 @url{http://www.linux-kvm.org/},
530 Kernel Based Virtual Machine (KVM).
531
532 @item [12]
533 @url{http://www.greensocs.com/projects/QEMUSystemC},
534 QEMU-SystemC, a hardware co-simulator.
535
536 @end table
537
538 @node Regression Tests
539 @chapter Regression Tests
540
541 In the directory @file{tests/}, various interesting testing programs
542 are available. They are used for regression testing.
543
544 @menu
545 * test-i386::
546 * linux-test::
547 @end menu
548
549 @node test-i386
550 @section @file{test-i386}
551
552 This program executes most of the 16 bit and 32 bit x86 instructions and
553 generates a text output. It can be compared with the output obtained with
554 a real CPU or another emulator. The target @code{make test} runs this
555 program and a @code{diff} on the generated output.
556
557 The Linux system call @code{modify_ldt()} is used to create x86 selectors
558 to test some 16 bit addressing and 32 bit with segmentation cases.
559
560 The Linux system call @code{vm86()} is used to test vm86 emulation.
561
562 Various exceptions are raised to test most of the x86 user space
563 exception reporting.
564
565 @node linux-test
566 @section @file{linux-test}
567
568 This program tests various Linux system calls. It is used to verify
569 that the system call parameters are correctly converted between target
570 and host CPUs.
571
572 @bye