Statistics
| Branch: | Revision:

root / qemu-tech.texi @ 4a1418e0

History | View | Annotate | Download (22.1 kB)

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 kvm. The accelerators 
120
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. On
367
Sparc64, costly update of both 32 and 64 bit condition codes can be
368
avoided with lazy evaluation.
369

    
370
Instead of computing the condition codes after each x86 instruction,
371
QEMU 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
374
codes can be calculated using this information. In addition, an
375
optimized calculation can be performed for some instruction types like
376
conditional branches.
377

    
378
@code{CC_OP} is almost never explicitly set in the generated code
379
because it is known at translation time.
380

    
381
The lazy condition code evaluation is used on x86, m68k, cris and
382
Sparc. ARM uses a simplified variant for the N and Z flags.
383

    
384
@node CPU state optimisations
385
@section CPU state optimisations
386

    
387
The target CPUs have many internal states which change the way it
388
evaluates instructions. In order to achieve a good speed, the
389
translation phase considers that some state information of the virtual
390
CPU cannot change in it. The state is recorded in the Translation
391
Block (TB). If the state changes (e.g. privilege level), a new TB will
392
be generated and the previous TB won't be used anymore until the state
393
matches the state recorded in the previous TB. For example, if the SS,
394
DS and ES segments have a zero base, then the translator does not even
395
generate 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

    
402
A 16 MByte cache holds the most recently used translations. For
403
simplicity, it is completely flushed when it is full. A translation unit
404
contains just a single basic block (a block of x86 instructions
405
terminated by a jump or by a virtual CPU state change which the
406
translator cannot deduce statically).
407

    
408
@node Direct block chaining
409
@section Direct block chaining
410

    
411
After each translated basic block is executed, QEMU uses the simulated
412
Program Counter (PC) and other cpu state informations (such as the CS
413
segment base value) to find the next basic block.
414

    
415
In order to accelerate the most common cases where the new simulated PC
416
is known, QEMU can patch a basic block so that it jumps directly to the
417
next one.
418

    
419
The most portable code uses an indirect jump. An indirect jump makes
420
it easier to make the jump target modification atomic. On some host
421
architectures (such as x86 or PowerPC), the @code{JUMP} opcode is
422
directly 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

    
427
Self-modifying code is a special challenge in x86 emulation because no
428
instruction cache invalidation is signaled by the application when code
429
is modified.
430

    
431
When translated code is generated for a basic block, the corresponding
432
host page is write protected if it is not already read-only. Then, if
433
a write access is done to the page, Linux raises a SEGV signal. QEMU
434
then invalidates all the translated code in the page and enables write
435
accesses to the page.
436

    
437
Correct translated code invalidation is done efficiently by maintaining
438
a linked list of every translated block contained in a given page. Other
439
linked lists are also maintained to undo direct block chaining.
440

    
441
On RISC targets, correctly written software uses memory barriers and
442
cache flushes, so some of the protection above would not be
443
necessary. However, QEMU still requires that the generated code always
444
matches the target instructions in memory in order to handle
445
exceptions correctly.
446

    
447
@node Exception support
448
@section Exception support
449

    
450
longjmp() is used when an exception such as division by zero is
451
encountered.
452

    
453
The host SIGSEGV and SIGBUS signal handlers are used to get invalid
454
memory accesses. The simulated program counter is found by
455
retranslating the corresponding basic block and by looking where the
456
host program counter was at the exception point.
457

    
458
The virtual CPU cannot retrieve the exact @code{EFLAGS} register because
459
in some cases it is not computed because of condition code
460
optimisations. It is not a big concern because the emulated code can
461
still be restarted in any cases.
462

    
463
@node MMU emulation
464
@section MMU emulation
465

    
466
For system emulation QEMU supports a soft MMU. In that mode, the MMU
467
virtual to physical address translation is done at every memory
468
access. QEMU uses an address translation cache to speed up the
469
translation.
470

    
471
In order to avoid flushing the translated code each time the MMU
472
mappings change, QEMU uses a physically indexed translation cache. It
473
means that each basic block is indexed with its physical address.
474

    
475
When MMU mappings change, only the chaining of the basic blocks is
476
reset (i.e. a basic block can no longer jump directly to another one).
477

    
478
@node Device emulation
479
@section Device emulation
480

    
481
Systems emulated by QEMU are organized by boards. At initialization
482
phase, each board instantiates a number of CPUs, devices, RAM and
483
ROM. Each device in turn can assign I/O ports or memory areas (for
484
MMIO) to its handlers. When the emulation starts, an access to the
485
ports or MMIO memory areas assigned to the device causes the
486
corresponding handler to be called.
487

    
488
RAM and ROM are handled more optimally, only the offset to the host
489
memory needs to be added to the guest address.
490

    
491
The video RAM of VGA and other display cards is special: it can be
492
read or written directly like RAM, but write accesses cause the memory
493
to be marked with VGA_DIRTY flag as well.
494

    
495
QEMU supports some device classes like serial and parallel ports, USB,
496
drives and network devices, by providing APIs for easier connection to
497
the generic, higher level implementations. The API hides the
498
implementation details from the devices, like native device use or
499
advanced block device formats like QCOW.
500

    
501
Usually the devices implement a reset method and register support for
502
saving and loading of the device state. The devices can also use
503
timers, especially together with the use of bottom halves (BHs).
504

    
505
@node Hardware interrupts
506
@section Hardware interrupts
507

    
508
In order to be faster, QEMU does not check at every basic block if an
509
hardware interrupt is pending. Instead, the user must asynchrously
510
call a specific function to tell that an interrupt is pending. This
511
function resets the chaining of the currently executing basic
512
block. It ensures that the execution will return soon in the main loop
513
of the CPU emulator. Then the main loop can test if the interrupt is
514
pending and handle it.
515

    
516
@node User emulation specific details
517
@section User emulation specific details
518

    
519
@subsection Linux system call translation
520

    
521
QEMU includes a generic system call translator for Linux. It means that
522
the parameters of the system calls can be converted to fix the
523
endianness and 32/64 bit issues. The IOCTLs are converted with a generic
524
type description system (see @file{ioctls.h} and @file{thunk.c}).
525

    
526
QEMU supports host CPUs which have pages bigger than 4KB. It records all
527
the mappings the process does and try to emulated the @code{mmap()}
528
system calls in cases where the host @code{mmap()} call would fail
529
because of bad page alignment.
530

    
531
@subsection Linux signals
532

    
533
Normal 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
535
request is done to the virtual CPU. When it is interrupted, one queued
536
signal is handled by generating a stack frame in the virtual CPU as the
537
Linux kernel does. The @code{sigreturn()} system call is emulated to return
538
from the virtual signal handler.
539

    
540
Some signals (such as SIGALRM) directly come from the host. Other
541
signals are synthetized from the virtual CPU exceptions such as SIGFPE
542
when a division by zero is done (see @code{main.c:cpu_loop()}).
543

    
544
The blocked signal mask is still handled by the host Linux kernel so
545
that most signal system calls can be redirected directly to the host
546
Linux kernel. Only the @code{sigaction()} and @code{sigreturn()} system
547
calls need to be fully emulated (see @file{signal.c}).
548

    
549
@subsection clone() system call and threads
550

    
551
The Linux clone() system call is usually used to create a thread. QEMU
552
uses the host clone() system call so that real host threads are created
553
for each emulated thread. One virtual CPU instance is created for each
554
thread.
555

    
556
The virtual x86 CPU atomic operations are emulated with a global lock so
557
that their semantic is preserved.
558

    
559
Note that currently there are still some locking issues in QEMU. In
560
particular, the translated cache flush is not protected yet against
561
reentrancy.
562

    
563
@subsection Self-virtualization
564

    
565
QEMU was conceived so that ultimately it can emulate itself. Although
566
it is not very useful, it is an important test to show the power of the
567
emulator.
568

    
569
Achieving self-virtualization is not easy because there may be address
570
space conflicts. QEMU user emulators solve this problem by being an
571
executable ELF shared object as the ld-linux.so ELF interpreter. That
572
way, 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
581
direct threaded code by selective inlining (1998) by Ian Piumarta, Fabio
582
Riccardi.
583

    
584
@item [2]
585
@url{http://developer.kde.org/~sewardj/}, Valgrind, an open-source
586
memory debugger for x86-GNU/Linux, by Julian Seward.
587

    
588
@item [3]
589
@url{http://bochs.sourceforge.net/}, the Bochs IA-32 Emulator Project,
590
by Kevin Lawton et al.
591

    
592
@item [4]
593
@url{http://www.cs.rose-hulman.edu/~donaldlf/em86/index.html}, the EM86
594
x86 emulator on Alpha-Linux.
595

    
596
@item [5]
597
@url{http://www.usenix.org/publications/library/proceedings/usenix-nt97/@/full_papers/chernoff/chernoff.pdf},
598
DIGITAL FX!32: Running 32-Bit x86 Applications on Alpha NT, by Anton
599
Chernoff and Ray Hookway.
600

    
601
@item [6]
602
@url{http://www.willows.com/}, Windows API library emulation from
603
Willows Software.
604

    
605
@item [7]
606
@url{http://user-mode-linux.sourceforge.net/},
607
The User-mode Linux Kernel.
608

    
609
@item [8]
610
@url{http://www.plex86.org/},
611
The new Plex86 project.
612

    
613
@item [9]
614
@url{http://www.vmware.com/},
615
The VMWare PC virtualizer.
616

    
617
@item [10]
618
@url{http://www.microsoft.com/windowsxp/virtualpc/},
619
The VirtualPC PC virtualizer.
620

    
621
@item [11]
622
@url{http://www.twoostwo.org/},
623
The TwoOStwo PC virtualizer.
624

    
625
@item [12]
626
@url{http://virtualbox.org/},
627
The VirtualBox PC virtualizer.
628

    
629
@item [13]
630
@url{http://www.xen.org/},
631
The Xen hypervisor.
632

    
633
@item [14]
634
@url{http://kvm.qumranet.com/kvmwiki/Front_Page},
635
Kernel Based Virtual Machine (KVM).
636

    
637
@item [15]
638
@url{http://www.greensocs.com/projects/QEMUSystemC},
639
QEMU-SystemC, a hardware co-simulator.
640

    
641
@end table
642

    
643
@node Regression Tests
644
@chapter Regression Tests
645

    
646
In the directory @file{tests/}, various interesting testing programs
647
are 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

    
658
This program executes most of the 16 bit and 32 bit x86 instructions and
659
generates a text output. It can be compared with the output obtained with
660
a real CPU or another emulator. The target @code{make test} runs this
661
program and a @code{diff} on the generated output.
662

    
663
The Linux system call @code{modify_ldt()} is used to create x86 selectors
664
to test some 16 bit addressing and 32 bit with segmentation cases.
665

    
666
The Linux system call @code{vm86()} is used to test vm86 emulation.
667

    
668
Various exceptions are raised to test most of the x86 user space
669
exception reporting.
670

    
671
@node linux-test
672
@section @file{linux-test}
673

    
674
This program tests various Linux system calls. It is used to verify
675
that the system call parameters are correctly converted between target
676
and host CPUs.
677

    
678
@node qruncom.c
679
@section @file{qruncom.c}
680

    
681
Example 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