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