]> git.proxmox.com Git - qemu.git/blame_incremental - qemu-tech.texi
pc: add machine type for 0.12
[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 kvm. The accelerators
120execute 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. On
367Sparc64, costly update of both 32 and 64 bit condition codes can be
368avoided with lazy evaluation.
369
370Instead of computing the condition codes after each x86 instruction,
371QEMU just stores one operand (called @code{CC_SRC}), the result
372(called @code{CC_DST}) and the type of operation (called
373@code{CC_OP}). When the condition codes are needed, the condition
374codes can be calculated using this information. In addition, an
375optimized calculation can be performed for some instruction types like
376conditional branches.
377
378@code{CC_OP} is almost never explicitly set in the generated code
379because it is known at translation time.
380
381The lazy condition code evaluation is used on x86, m68k, cris and
382Sparc. ARM uses a simplified variant for the N and Z flags.
383
384@node CPU state optimisations
385@section CPU state optimisations
386
387The target CPUs have many internal states which change the way it
388evaluates instructions. In order to achieve a good speed, the
389translation phase considers that some state information of the virtual
390CPU cannot change in it. The state is recorded in the Translation
391Block (TB). If the state changes (e.g. privilege level), a new TB will
392be generated and the previous TB won't be used anymore until the state
393matches the state recorded in the previous TB. For example, if the SS,
394DS and ES segments have a zero base, then the translator does not even
395generate an addition for the segment base.
396
397[The FPU stack pointer register is not handled that way yet].
398
399@node Translation cache
400@section Translation cache
401
402A 16 MByte cache holds the most recently used translations. For
403simplicity, it is completely flushed when it is full. A translation unit
404contains just a single basic block (a block of x86 instructions
405terminated by a jump or by a virtual CPU state change which the
406translator cannot deduce statically).
407
408@node Direct block chaining
409@section Direct block chaining
410
411After each translated basic block is executed, QEMU uses the simulated
412Program Counter (PC) and other cpu state informations (such as the CS
413segment base value) to find the next basic block.
414
415In order to accelerate the most common cases where the new simulated PC
416is known, QEMU can patch a basic block so that it jumps directly to the
417next one.
418
419The most portable code uses an indirect jump. An indirect jump makes
420it easier to make the jump target modification atomic. On some host
421architectures (such as x86 or PowerPC), the @code{JUMP} opcode is
422directly patched so that the block chaining has no overhead.
423
424@node Self-modifying code and translated code invalidation
425@section Self-modifying code and translated code invalidation
426
427Self-modifying code is a special challenge in x86 emulation because no
428instruction cache invalidation is signaled by the application when code
429is modified.
430
431When translated code is generated for a basic block, the corresponding
432host page is write protected if it is not already read-only. Then, if
433a write access is done to the page, Linux raises a SEGV signal. QEMU
434then invalidates all the translated code in the page and enables write
435accesses to the page.
436
437Correct translated code invalidation is done efficiently by maintaining
438a linked list of every translated block contained in a given page. Other
439linked lists are also maintained to undo direct block chaining.
440
441On RISC targets, correctly written software uses memory barriers and
442cache flushes, so some of the protection above would not be
443necessary. However, QEMU still requires that the generated code always
444matches the target instructions in memory in order to handle
445exceptions correctly.
446
447@node Exception support
448@section Exception support
449
450longjmp() is used when an exception such as division by zero is
451encountered.
452
453The host SIGSEGV and SIGBUS signal handlers are used to get invalid
454memory accesses. The simulated program counter is found by
455retranslating the corresponding basic block and by looking where the
456host program counter was at the exception point.
457
458The virtual CPU cannot retrieve the exact @code{EFLAGS} register because
459in some cases it is not computed because of condition code
460optimisations. It is not a big concern because the emulated code can
461still be restarted in any cases.
462
463@node MMU emulation
464@section MMU emulation
465
466For system emulation QEMU supports a soft MMU. In that mode, the MMU
467virtual to physical address translation is done at every memory
468access. QEMU uses an address translation cache to speed up the
469translation.
470
471In order to avoid flushing the translated code each time the MMU
472mappings change, QEMU uses a physically indexed translation cache. It
473means that each basic block is indexed with its physical address.
474
475When MMU mappings change, only the chaining of the basic blocks is
476reset (i.e. a basic block can no longer jump directly to another one).
477
478@node Device emulation
479@section Device emulation
480
481Systems emulated by QEMU are organized by boards. At initialization
482phase, each board instantiates a number of CPUs, devices, RAM and
483ROM. Each device in turn can assign I/O ports or memory areas (for
484MMIO) to its handlers. When the emulation starts, an access to the
485ports or MMIO memory areas assigned to the device causes the
486corresponding handler to be called.
487
488RAM and ROM are handled more optimally, only the offset to the host
489memory needs to be added to the guest address.
490
491The video RAM of VGA and other display cards is special: it can be
492read or written directly like RAM, but write accesses cause the memory
493to be marked with VGA_DIRTY flag as well.
494
495QEMU supports some device classes like serial and parallel ports, USB,
496drives and network devices, by providing APIs for easier connection to
497the generic, higher level implementations. The API hides the
498implementation details from the devices, like native device use or
499advanced block device formats like QCOW.
500
501Usually the devices implement a reset method and register support for
502saving and loading of the device state. The devices can also use
503timers, especially together with the use of bottom halves (BHs).
504
505@node Hardware interrupts
506@section Hardware interrupts
507
508In order to be faster, QEMU does not check at every basic block if an
509hardware interrupt is pending. Instead, the user must asynchrously
510call a specific function to tell that an interrupt is pending. This
511function resets the chaining of the currently executing basic
512block. It ensures that the execution will return soon in the main loop
513of the CPU emulator. Then the main loop can test if the interrupt is
514pending and handle it.
515
516@node User emulation specific details
517@section User emulation specific details
518
519@subsection Linux system call translation
520
521QEMU includes a generic system call translator for Linux. It means that
522the parameters of the system calls can be converted to fix the
523endianness and 32/64 bit issues. The IOCTLs are converted with a generic
524type description system (see @file{ioctls.h} and @file{thunk.c}).
525
526QEMU supports host CPUs which have pages bigger than 4KB. It records all
527the mappings the process does and try to emulated the @code{mmap()}
528system calls in cases where the host @code{mmap()} call would fail
529because of bad page alignment.
530
531@subsection Linux signals
532
533Normal and real-time signals are queued along with their information
534(@code{siginfo_t}) as it is done in the Linux kernel. Then an interrupt
535request is done to the virtual CPU. When it is interrupted, one queued
536signal is handled by generating a stack frame in the virtual CPU as the
537Linux kernel does. The @code{sigreturn()} system call is emulated to return
538from the virtual signal handler.
539
540Some signals (such as SIGALRM) directly come from the host. Other
541signals are synthetized from the virtual CPU exceptions such as SIGFPE
542when a division by zero is done (see @code{main.c:cpu_loop()}).
543
544The blocked signal mask is still handled by the host Linux kernel so
545that most signal system calls can be redirected directly to the host
546Linux kernel. Only the @code{sigaction()} and @code{sigreturn()} system
547calls need to be fully emulated (see @file{signal.c}).
548
549@subsection clone() system call and threads
550
551The Linux clone() system call is usually used to create a thread. QEMU
552uses the host clone() system call so that real host threads are created
553for each emulated thread. One virtual CPU instance is created for each
554thread.
555
556The virtual x86 CPU atomic operations are emulated with a global lock so
557that their semantic is preserved.
558
559Note that currently there are still some locking issues in QEMU. In
560particular, the translated cache flush is not protected yet against
561reentrancy.
562
563@subsection Self-virtualization
564
565QEMU was conceived so that ultimately it can emulate itself. Although
566it is not very useful, it is an important test to show the power of the
567emulator.
568
569Achieving self-virtualization is not easy because there may be address
570space conflicts. QEMU user emulators solve this problem by being an
571executable ELF shared object as the ld-linux.so ELF interpreter. That
572way, it can be relocated at load time.
573
574@node Bibliography
575@section Bibliography
576
577@table @asis
578
579@item [1]
580@url{http://citeseer.nj.nec.com/piumarta98optimizing.html}, Optimizing
581direct threaded code by selective inlining (1998) by Ian Piumarta, Fabio
582Riccardi.
583
584@item [2]
585@url{http://developer.kde.org/~sewardj/}, Valgrind, an open-source
586memory debugger for x86-GNU/Linux, by Julian Seward.
587
588@item [3]
589@url{http://bochs.sourceforge.net/}, the Bochs IA-32 Emulator Project,
590by Kevin Lawton et al.
591
592@item [4]
593@url{http://www.cs.rose-hulman.edu/~donaldlf/em86/index.html}, the EM86
594x86 emulator on Alpha-Linux.
595
596@item [5]
597@url{http://www.usenix.org/publications/library/proceedings/usenix-nt97/@/full_papers/chernoff/chernoff.pdf},
598DIGITAL FX!32: Running 32-Bit x86 Applications on Alpha NT, by Anton
599Chernoff and Ray Hookway.
600
601@item [6]
602@url{http://www.willows.com/}, Windows API library emulation from
603Willows Software.
604
605@item [7]
606@url{http://user-mode-linux.sourceforge.net/},
607The User-mode Linux Kernel.
608
609@item [8]
610@url{http://www.plex86.org/},
611The new Plex86 project.
612
613@item [9]
614@url{http://www.vmware.com/},
615The VMWare PC virtualizer.
616
617@item [10]
618@url{http://www.microsoft.com/windowsxp/virtualpc/},
619The VirtualPC PC virtualizer.
620
621@item [11]
622@url{http://www.twoostwo.org/},
623The TwoOStwo PC virtualizer.
624
625@item [12]
626@url{http://virtualbox.org/},
627The VirtualBox PC virtualizer.
628
629@item [13]
630@url{http://www.xen.org/},
631The Xen hypervisor.
632
633@item [14]
634@url{http://kvm.qumranet.com/kvmwiki/Front_Page},
635Kernel Based Virtual Machine (KVM).
636
637@item [15]
638@url{http://www.greensocs.com/projects/QEMUSystemC},
639QEMU-SystemC, a hardware co-simulator.
640
641@end table
642
643@node Regression Tests
644@chapter Regression Tests
645
646In the directory @file{tests/}, various interesting testing programs
647are available. They are used for regression testing.
648
649@menu
650* test-i386::
651* linux-test::
652* qruncom.c::
653@end menu
654
655@node test-i386
656@section @file{test-i386}
657
658This program executes most of the 16 bit and 32 bit x86 instructions and
659generates a text output. It can be compared with the output obtained with
660a real CPU or another emulator. The target @code{make test} runs this
661program and a @code{diff} on the generated output.
662
663The Linux system call @code{modify_ldt()} is used to create x86 selectors
664to test some 16 bit addressing and 32 bit with segmentation cases.
665
666The Linux system call @code{vm86()} is used to test vm86 emulation.
667
668Various exceptions are raised to test most of the x86 user space
669exception reporting.
670
671@node linux-test
672@section @file{linux-test}
673
674This program tests various Linux system calls. It is used to verify
675that the system call parameters are correctly converted between target
676and host CPUs.
677
678@node qruncom.c
679@section @file{qruncom.c}
680
681Example of usage of @code{libqemu} to emulate a user mode i386 CPU.
682
683@node Index
684@chapter Index
685@printindex cp
686
687@bye