]> git.proxmox.com Git - qemu.git/blob - qemu-tech.texi
added -numa cmdline parameter parser (Andre Przywara)
[qemu.git] / qemu-tech.texi
1 \input texinfo @c -*- texinfo -*-
2 @c %**start of header
3 @setfilename qemu-tech.info
4 @settitle QEMU Internals
5 @exampleindent 0
6 @paragraphindent 0
7 @c %**end of header
8
9 @iftex
10 @titlepage
11 @sp 7
12 @center @titlefont{QEMU Internals}
13 @sp 3
14 @end titlepage
15 @end iftex
16
17 @ifnottex
18 @node Top
19 @top
20
21 @menu
22 * Introduction::
23 * QEMU Internals::
24 * Regression Tests::
25 * Index::
26 @end menu
27 @end ifnottex
28
29 @contents
30
31 @node Introduction
32 @chapter Introduction
33
34 @menu
35 * intro_features:: Features
36 * intro_x86_emulation:: x86 and x86-64 emulation
37 * intro_arm_emulation:: ARM emulation
38 * intro_mips_emulation:: MIPS emulation
39 * intro_ppc_emulation:: PowerPC emulation
40 * intro_sparc_emulation:: Sparc32 and Sparc64 emulation
41 * intro_other_emulation:: Other CPU emulation
42 @end menu
43
44 @node intro_features
45 @section Features
46
47 QEMU is a FAST! processor emulator using a portable dynamic
48 translator.
49
50 QEMU has two operating modes:
51
52 @itemize @minus
53
54 @item
55 Full system emulation. In this mode (full platform virtualization),
56 QEMU emulates a full system (usually a PC), including a processor and
57 various peripherals. It can be used to launch several different
58 Operating Systems at once without rebooting the host machine or to
59 debug system code.
60
61 @item
62 User mode emulation. In this mode (application level virtualization),
63 QEMU can launch processes compiled for one CPU on another CPU, however
64 the Operating Systems must match. This can be used for example to ease
65 cross-compilation and cross-debugging.
66 @end itemize
67
68 As QEMU requires no host kernel driver to run, it is very safe and
69 easy to use.
70
71 QEMU generic features:
72
73 @itemize
74
75 @item User space only or full system emulation.
76
77 @item Using dynamic translation to native code for reasonable speed.
78
79 @item
80 Working on x86, x86_64 and PowerPC32/64 hosts. Being tested on ARM,
81 HPPA, Sparc32 and Sparc64. Previous versions had some support for
82 Alpha and S390 hosts, but TCG (see below) doesn't support those yet.
83
84 @item Self-modifying code support.
85
86 @item Precise exceptions support.
87
88 @item The virtual CPU is a library (@code{libqemu}) which can be used
89 in other projects (look at @file{qemu/tests/qruncom.c} to have an
90 example of user mode @code{libqemu} usage).
91
92 @item
93 Floating point library supporting both full software emulation and
94 native host FPU instructions.
95
96 @end itemize
97
98 QEMU user mode emulation features:
99 @itemize
100 @item Generic Linux system call converter, including most ioctls.
101
102 @item clone() emulation using native CPU clone() to use Linux scheduler for threads.
103
104 @item Accurate signal handling by remapping host signals to target signals.
105 @end itemize
106
107 Linux user emulator (Linux host only) can be used to launch the Wine
108 Windows API emulator (@url{http://www.winehq.org}). A Darwin user
109 emulator (Darwin hosts only) exists and a BSD user emulator for BSD
110 hosts is under development. It would also be possible to develop a
111 similar user emulator for Solaris.
112
113 QEMU full system emulation features:
114 @itemize
115 @item
116 QEMU uses a full software MMU for maximum portability.
117
118 @item
119 QEMU can optionally use an in-kernel accelerator, like kqemu and
120 kvm. The accelerators execute some of the guest code natively, while
121 continuing to emulate the rest of the machine.
122
123 @item
124 Various hardware devices can be emulated and in some cases, host
125 devices (e.g. serial and parallel ports, USB, drives) can be used
126 transparently by the guest Operating System. Host device passthrough
127 can be used for talking to external physical peripherals (e.g. a
128 webcam, modem or tape drive).
129
130 @item
131 Symmetric multiprocessing (SMP) even on a host with a single CPU. On a
132 SMP host system, QEMU can use only one CPU fully due to difficulty in
133 implementing atomic memory accesses efficiently.
134
135 @end itemize
136
137 @node intro_x86_emulation
138 @section x86 and x86-64 emulation
139
140 QEMU x86 target features:
141
142 @itemize
143
144 @item The virtual x86 CPU supports 16 bit and 32 bit addressing with segmentation.
145 LDT/GDT and IDT are emulated. VM86 mode is also supported to run
146 DOSEMU. There is some support for MMX/3DNow!, SSE, SSE2, SSE3, SSSE3,
147 and SSE4 as well as x86-64 SVM.
148
149 @item Support of host page sizes bigger than 4KB in user mode emulation.
150
151 @item QEMU can emulate itself on x86.
152
153 @item An extensive Linux x86 CPU test program is included @file{tests/test-i386}.
154 It can be used to test other x86 virtual CPUs.
155
156 @end itemize
157
158 Current QEMU limitations:
159
160 @itemize
161
162 @item Limited x86-64 support.
163
164 @item IPC syscalls are missing.
165
166 @item The x86 segment limits and access rights are not tested at every
167 memory access (yet). Hopefully, very few OSes seem to rely on that for
168 normal use.
169
170 @end itemize
171
172 @node intro_arm_emulation
173 @section ARM emulation
174
175 @itemize
176
177 @item Full ARM 7 user emulation.
178
179 @item NWFPE FPU support included in user Linux emulation.
180
181 @item Can run most ARM Linux binaries.
182
183 @end itemize
184
185 @node intro_mips_emulation
186 @section MIPS emulation
187
188 @itemize
189
190 @item The system emulation allows full MIPS32/MIPS64 Release 2 emulation,
191 including privileged instructions, FPU and MMU, in both little and big
192 endian modes.
193
194 @item The Linux userland emulation can run many 32 bit MIPS Linux binaries.
195
196 @end itemize
197
198 Current QEMU limitations:
199
200 @itemize
201
202 @item Self-modifying code is not always handled correctly.
203
204 @item 64 bit userland emulation is not implemented.
205
206 @item The system emulation is not complete enough to run real firmware.
207
208 @item The watchpoint debug facility is not implemented.
209
210 @end itemize
211
212 @node intro_ppc_emulation
213 @section PowerPC emulation
214
215 @itemize
216
217 @item Full PowerPC 32 bit emulation, including privileged instructions,
218 FPU and MMU.
219
220 @item Can run most PowerPC Linux binaries.
221
222 @end itemize
223
224 @node intro_sparc_emulation
225 @section Sparc32 and Sparc64 emulation
226
227 @itemize
228
229 @item Full SPARC V8 emulation, including privileged
230 instructions, FPU and MMU. SPARC V9 emulation includes most privileged
231 and VIS instructions, FPU and I/D MMU. Alignment is fully enforced.
232
233 @item Can run most 32-bit SPARC Linux binaries, SPARC32PLUS Linux binaries and
234 some 64-bit SPARC Linux binaries.
235
236 @end itemize
237
238 Current QEMU limitations:
239
240 @itemize
241
242 @item IPC syscalls are missing.
243
244 @item Floating point exception support is buggy.
245
246 @item Atomic instructions are not correctly implemented.
247
248 @item There are still some problems with Sparc64 emulators.
249
250 @end itemize
251
252 @node intro_other_emulation
253 @section Other CPU emulation
254
255 In addition to the above, QEMU supports emulation of other CPUs with
256 varying levels of success. These are:
257
258 @itemize
259
260 @item
261 Alpha
262 @item
263 CRIS
264 @item
265 M68k
266 @item
267 SH4
268 @end itemize
269
270 @node QEMU Internals
271 @chapter QEMU Internals
272
273 @menu
274 * QEMU compared to other emulators::
275 * Portable dynamic translation::
276 * Condition code optimisations::
277 * CPU state optimisations::
278 * Translation cache::
279 * Direct block chaining::
280 * Self-modifying code and translated code invalidation::
281 * Exception support::
282 * MMU emulation::
283 * Device emulation::
284 * Hardware interrupts::
285 * User emulation specific details::
286 * Bibliography::
287 @end menu
288
289 @node QEMU compared to other emulators
290 @section QEMU compared to other emulators
291
292 Like bochs [3], QEMU emulates an x86 CPU. But QEMU is much faster than
293 bochs as it uses dynamic compilation. Bochs is closely tied to x86 PC
294 emulation while QEMU can emulate several processors.
295
296 Like Valgrind [2], QEMU does user space emulation and dynamic
297 translation. Valgrind is mainly a memory debugger while QEMU has no
298 support for it (QEMU could be used to detect out of bound memory
299 accesses as Valgrind, but it has no support to track uninitialised data
300 as Valgrind does). The Valgrind dynamic translator generates better code
301 than QEMU (in particular it does register allocation) but it is closely
302 tied to an x86 host and target and has no support for precise exceptions
303 and system emulation.
304
305 EM86 [4] is the closest project to user space QEMU (and QEMU still uses
306 some of its code, in particular the ELF file loader). EM86 was limited
307 to an alpha host and used a proprietary and slow interpreter (the
308 interpreter part of the FX!32 Digital Win32 code translator [5]).
309
310 TWIN [6] is a Windows API emulator like Wine. It is less accurate than
311 Wine but includes a protected mode x86 interpreter to launch x86 Windows
312 executables. Such an approach has greater potential because most of the
313 Windows API is executed natively but it is far more difficult to develop
314 because all the data structures and function parameters exchanged
315 between the API and the x86 code must be converted.
316
317 User mode Linux [7] was the only solution before QEMU to launch a
318 Linux kernel as a process while not needing any host kernel
319 patches. However, user mode Linux requires heavy kernel patches while
320 QEMU accepts unpatched Linux kernels. The price to pay is that QEMU is
321 slower.
322
323 The Plex86 [8] PC virtualizer is done in the same spirit as the now
324 obsolete qemu-fast system emulator. It requires a patched Linux kernel
325 to work (you cannot launch the same kernel on your PC), but the
326 patches are really small. As it is a PC virtualizer (no emulation is
327 done except for some privileged instructions), it has the potential of
328 being faster than QEMU. The downside is that a complicated (and
329 potentially unsafe) host kernel patch is needed.
330
331 The commercial PC Virtualizers (VMWare [9], VirtualPC [10], TwoOStwo
332 [11]) are faster than QEMU, but they all need specific, proprietary
333 and potentially unsafe host drivers. Moreover, they are unable to
334 provide cycle exact simulation as an emulator can.
335
336 VirtualBox [12], Xen [13] and KVM [14] are based on QEMU. QEMU-SystemC
337 [15] uses QEMU to simulate a system where some hardware devices are
338 developed in SystemC.
339
340 @node Portable dynamic translation
341 @section Portable dynamic translation
342
343 QEMU is a dynamic translator. When it first encounters a piece of code,
344 it converts it to the host instruction set. Usually dynamic translators
345 are very complicated and highly CPU dependent. QEMU uses some tricks
346 which make it relatively easily portable and simple while achieving good
347 performances.
348
349 After the release of version 0.9.1, QEMU switched to a new method of
350 generating code, Tiny Code Generator or TCG. TCG relaxes the
351 dependency on the exact version of the compiler used. The basic idea
352 is to split every target instruction into a couple of RISC-like TCG
353 ops (see @code{target-i386/translate.c}). Some optimizations can be
354 performed at this stage, including liveness analysis and trivial
355 constant expression evaluation. TCG ops are then implemented in the
356 host CPU back end, also known as TCG target (see
357 @code{tcg/i386/tcg-target.c}). For more information, please take a
358 look at @code{tcg/README}.
359
360 @node Condition code optimisations
361 @section Condition code optimisations
362
363 Lazy evaluation of CPU condition codes (@code{EFLAGS} register on x86)
364 is important for CPUs where every instruction sets the condition
365 codes. It tends to be less important on conventional RISC systems
366 where condition codes are only updated when explicitly requested.
367
368 Instead of computing the condition codes after each x86 instruction,
369 QEMU just stores one operand (called @code{CC_SRC}), the result
370 (called @code{CC_DST}) and the type of operation (called
371 @code{CC_OP}). When the condition codes are needed, the condition
372 codes can be calculated using this information. In addition, an
373 optimized calculation can be performed for some instruction types like
374 conditional branches.
375
376 @code{CC_OP} is almost never explicitly set in the generated code
377 because it is known at translation time.
378
379 The lazy condition code evaluation is used on x86, m68k and cris. ARM
380 uses a simplified variant for the N and Z flags.
381
382 @node CPU state optimisations
383 @section CPU state optimisations
384
385 The target CPUs have many internal states which change the way it
386 evaluates instructions. In order to achieve a good speed, the
387 translation phase considers that some state information of the virtual
388 CPU cannot change in it. The state is recorded in the Translation
389 Block (TB). If the state changes (e.g. privilege level), a new TB will
390 be generated and the previous TB won't be used anymore until the state
391 matches the state recorded in the previous TB. For example, if the SS,
392 DS and ES segments have a zero base, then the translator does not even
393 generate an addition for the segment base.
394
395 [The FPU stack pointer register is not handled that way yet].
396
397 @node Translation cache
398 @section Translation cache
399
400 A 16 MByte cache holds the most recently used translations. For
401 simplicity, it is completely flushed when it is full. A translation unit
402 contains just a single basic block (a block of x86 instructions
403 terminated by a jump or by a virtual CPU state change which the
404 translator cannot deduce statically).
405
406 @node Direct block chaining
407 @section Direct block chaining
408
409 After each translated basic block is executed, QEMU uses the simulated
410 Program Counter (PC) and other cpu state informations (such as the CS
411 segment base value) to find the next basic block.
412
413 In order to accelerate the most common cases where the new simulated PC
414 is known, QEMU can patch a basic block so that it jumps directly to the
415 next one.
416
417 The most portable code uses an indirect jump. An indirect jump makes
418 it easier to make the jump target modification atomic. On some host
419 architectures (such as x86 or PowerPC), the @code{JUMP} opcode is
420 directly patched so that the block chaining has no overhead.
421
422 @node Self-modifying code and translated code invalidation
423 @section Self-modifying code and translated code invalidation
424
425 Self-modifying code is a special challenge in x86 emulation because no
426 instruction cache invalidation is signaled by the application when code
427 is modified.
428
429 When translated code is generated for a basic block, the corresponding
430 host page is write protected if it is not already read-only. Then, if
431 a write access is done to the page, Linux raises a SEGV signal. QEMU
432 then invalidates all the translated code in the page and enables write
433 accesses to the page.
434
435 Correct translated code invalidation is done efficiently by maintaining
436 a linked list of every translated block contained in a given page. Other
437 linked lists are also maintained to undo direct block chaining.
438
439 On RISC targets, correctly written software uses memory barriers and
440 cache flushes, so some of the protection above would not be
441 necessary. However, QEMU still requires that the generated code always
442 matches the target instructions in memory in order to handle
443 exceptions correctly.
444
445 @node Exception support
446 @section Exception support
447
448 longjmp() is used when an exception such as division by zero is
449 encountered.
450
451 The host SIGSEGV and SIGBUS signal handlers are used to get invalid
452 memory accesses. The simulated program counter is found by
453 retranslating the corresponding basic block and by looking where the
454 host program counter was at the exception point.
455
456 The virtual CPU cannot retrieve the exact @code{EFLAGS} register because
457 in some cases it is not computed because of condition code
458 optimisations. It is not a big concern because the emulated code can
459 still be restarted in any cases.
460
461 @node MMU emulation
462 @section MMU emulation
463
464 For system emulation QEMU supports a soft MMU. In that mode, the MMU
465 virtual to physical address translation is done at every memory
466 access. QEMU uses an address translation cache to speed up the
467 translation.
468
469 In order to avoid flushing the translated code each time the MMU
470 mappings change, QEMU uses a physically indexed translation cache. It
471 means that each basic block is indexed with its physical address.
472
473 When MMU mappings change, only the chaining of the basic blocks is
474 reset (i.e. a basic block can no longer jump directly to another one).
475
476 @node Device emulation
477 @section Device emulation
478
479 Systems emulated by QEMU are organized by boards. At initialization
480 phase, each board instantiates a number of CPUs, devices, RAM and
481 ROM. Each device in turn can assign I/O ports or memory areas (for
482 MMIO) to its handlers. When the emulation starts, an access to the
483 ports or MMIO memory areas assigned to the device causes the
484 corresponding handler to be called.
485
486 RAM and ROM are handled more optimally, only the offset to the host
487 memory needs to be added to the guest address.
488
489 The video RAM of VGA and other display cards is special: it can be
490 read or written directly like RAM, but write accesses cause the memory
491 to be marked with VGA_DIRTY flag as well.
492
493 QEMU supports some device classes like serial and parallel ports, USB,
494 drives and network devices, by providing APIs for easier connection to
495 the generic, higher level implementations. The API hides the
496 implementation details from the devices, like native device use or
497 advanced block device formats like QCOW.
498
499 Usually the devices implement a reset method and register support for
500 saving and loading of the device state. The devices can also use
501 timers, especially together with the use of bottom halves (BHs).
502
503 @node Hardware interrupts
504 @section Hardware interrupts
505
506 In order to be faster, QEMU does not check at every basic block if an
507 hardware interrupt is pending. Instead, the user must asynchrously
508 call a specific function to tell that an interrupt is pending. This
509 function resets the chaining of the currently executing basic
510 block. It ensures that the execution will return soon in the main loop
511 of the CPU emulator. Then the main loop can test if the interrupt is
512 pending and handle it.
513
514 @node User emulation specific details
515 @section User emulation specific details
516
517 @subsection Linux system call translation
518
519 QEMU includes a generic system call translator for Linux. It means that
520 the parameters of the system calls can be converted to fix the
521 endianness and 32/64 bit issues. The IOCTLs are converted with a generic
522 type description system (see @file{ioctls.h} and @file{thunk.c}).
523
524 QEMU supports host CPUs which have pages bigger than 4KB. It records all
525 the mappings the process does and try to emulated the @code{mmap()}
526 system calls in cases where the host @code{mmap()} call would fail
527 because of bad page alignment.
528
529 @subsection Linux signals
530
531 Normal and real-time signals are queued along with their information
532 (@code{siginfo_t}) as it is done in the Linux kernel. Then an interrupt
533 request is done to the virtual CPU. When it is interrupted, one queued
534 signal is handled by generating a stack frame in the virtual CPU as the
535 Linux kernel does. The @code{sigreturn()} system call is emulated to return
536 from the virtual signal handler.
537
538 Some signals (such as SIGALRM) directly come from the host. Other
539 signals are synthetized from the virtual CPU exceptions such as SIGFPE
540 when a division by zero is done (see @code{main.c:cpu_loop()}).
541
542 The blocked signal mask is still handled by the host Linux kernel so
543 that most signal system calls can be redirected directly to the host
544 Linux kernel. Only the @code{sigaction()} and @code{sigreturn()} system
545 calls need to be fully emulated (see @file{signal.c}).
546
547 @subsection clone() system call and threads
548
549 The Linux clone() system call is usually used to create a thread. QEMU
550 uses the host clone() system call so that real host threads are created
551 for each emulated thread. One virtual CPU instance is created for each
552 thread.
553
554 The virtual x86 CPU atomic operations are emulated with a global lock so
555 that their semantic is preserved.
556
557 Note that currently there are still some locking issues in QEMU. In
558 particular, the translated cache flush is not protected yet against
559 reentrancy.
560
561 @subsection Self-virtualization
562
563 QEMU was conceived so that ultimately it can emulate itself. Although
564 it is not very useful, it is an important test to show the power of the
565 emulator.
566
567 Achieving self-virtualization is not easy because there may be address
568 space conflicts. QEMU user emulators solve this problem by being an
569 executable ELF shared object as the ld-linux.so ELF interpreter. That
570 way, it can be relocated at load time.
571
572 @node Bibliography
573 @section Bibliography
574
575 @table @asis
576
577 @item [1]
578 @url{http://citeseer.nj.nec.com/piumarta98optimizing.html}, Optimizing
579 direct threaded code by selective inlining (1998) by Ian Piumarta, Fabio
580 Riccardi.
581
582 @item [2]
583 @url{http://developer.kde.org/~sewardj/}, Valgrind, an open-source
584 memory debugger for x86-GNU/Linux, by Julian Seward.
585
586 @item [3]
587 @url{http://bochs.sourceforge.net/}, the Bochs IA-32 Emulator Project,
588 by Kevin Lawton et al.
589
590 @item [4]
591 @url{http://www.cs.rose-hulman.edu/~donaldlf/em86/index.html}, the EM86
592 x86 emulator on Alpha-Linux.
593
594 @item [5]
595 @url{http://www.usenix.org/publications/library/proceedings/usenix-nt97/@/full_papers/chernoff/chernoff.pdf},
596 DIGITAL FX!32: Running 32-Bit x86 Applications on Alpha NT, by Anton
597 Chernoff and Ray Hookway.
598
599 @item [6]
600 @url{http://www.willows.com/}, Windows API library emulation from
601 Willows Software.
602
603 @item [7]
604 @url{http://user-mode-linux.sourceforge.net/},
605 The User-mode Linux Kernel.
606
607 @item [8]
608 @url{http://www.plex86.org/},
609 The new Plex86 project.
610
611 @item [9]
612 @url{http://www.vmware.com/},
613 The VMWare PC virtualizer.
614
615 @item [10]
616 @url{http://www.microsoft.com/windowsxp/virtualpc/},
617 The VirtualPC PC virtualizer.
618
619 @item [11]
620 @url{http://www.twoostwo.org/},
621 The TwoOStwo PC virtualizer.
622
623 @item [12]
624 @url{http://virtualbox.org/},
625 The VirtualBox PC virtualizer.
626
627 @item [13]
628 @url{http://www.xen.org/},
629 The Xen hypervisor.
630
631 @item [14]
632 @url{http://kvm.qumranet.com/kvmwiki/Front_Page},
633 Kernel Based Virtual Machine (KVM).
634
635 @item [15]
636 @url{http://www.greensocs.com/projects/QEMUSystemC},
637 QEMU-SystemC, a hardware co-simulator.
638
639 @end table
640
641 @node Regression Tests
642 @chapter Regression Tests
643
644 In the directory @file{tests/}, various interesting testing programs
645 are available. They are used for regression testing.
646
647 @menu
648 * test-i386::
649 * linux-test::
650 * qruncom.c::
651 @end menu
652
653 @node test-i386
654 @section @file{test-i386}
655
656 This program executes most of the 16 bit and 32 bit x86 instructions and
657 generates a text output. It can be compared with the output obtained with
658 a real CPU or another emulator. The target @code{make test} runs this
659 program and a @code{diff} on the generated output.
660
661 The Linux system call @code{modify_ldt()} is used to create x86 selectors
662 to test some 16 bit addressing and 32 bit with segmentation cases.
663
664 The Linux system call @code{vm86()} is used to test vm86 emulation.
665
666 Various exceptions are raised to test most of the x86 user space
667 exception reporting.
668
669 @node linux-test
670 @section @file{linux-test}
671
672 This program tests various Linux system calls. It is used to verify
673 that the system call parameters are correctly converted between target
674 and host CPUs.
675
676 @node qruncom.c
677 @section @file{qruncom.c}
678
679 Example of usage of @code{libqemu} to emulate a user mode i386 CPU.
680
681 @node Index
682 @chapter Index
683 @printindex cp
684
685 @bye