removed test code
[qemu/qemu_0_9_1_stable.git] / qemu-doc.texi
blobc0a5bd048c29f13b38c9425004c49555af319580
1 \input texinfo @c -*- texinfo -*-
3 @iftex
4 @settitle QEMU CPU Emulator Reference Documentation
5 @titlepage
6 @sp 7
7 @center @titlefont{QEMU CPU Emulator Reference Documentation}
8 @sp 3
9 @end titlepage
10 @end iftex
12 @chapter Introduction
14 @section Features
16 QEMU is a FAST! processor emulator. By using dynamic translation it
17 achieves a reasonnable speed while being easy to port on new host
18 CPUs.
20 QEMU has two operating modes:
22 @itemize @minus
24 @item 
25 User mode emulation. In this mode, QEMU can launch Linux processes
26 compiled for one CPU on another CPU. Linux system calls are converted
27 because of endianness and 32/64 bit mismatches. The Wine Windows API
28 emulator (@url{http://www.winehq.org}) and the DOSEMU DOS emulator
29 (@url{www.dosemu.org}) are the main targets for QEMU.
31 @item 
32 Full system emulation. In this mode, QEMU emulates a full
33 system, including a processor and various peripherials. Currently, it
34 is only used to launch an x86 Linux kernel on an x86 Linux system. It
35 enables easier testing and debugging of system code. It can also be
36 used to provide virtual hosting of several virtual PCs on a single
37 server.
39 @end itemize
41 As QEMU requires no host kernel patches to run, it is very safe and
42 easy to use.
44 QEMU generic features:
46 @itemize 
48 @item User space only or full system emulation.
50 @item Using dynamic translation to native code for reasonnable speed.
52 @item Working on x86 and PowerPC hosts. Being tested on ARM, Sparc32, Alpha and S390.
54 @item Self-modifying code support.
56 @item Precise exceptions support.
58 @item The virtual CPU is a library (@code{libqemu}) which can be used 
59 in other projects.
61 @end itemize
63 QEMU user mode emulation features:
64 @itemize 
65 @item Generic Linux system call converter, including most ioctls.
67 @item clone() emulation using native CPU clone() to use Linux scheduler for threads.
69 @item Accurate signal handling by remapping host signals to target signals. 
70 @end itemize
71 @end itemize
73 QEMU full system emulation features:
74 @itemize 
75 @item QEMU can either use a full software MMU for maximum portability or use the host system call mmap() to simulate the target MMU.
76 @end itemize
78 @section x86 emulation
80 QEMU x86 target features:
82 @itemize 
84 @item The virtual x86 CPU supports 16 bit and 32 bit addressing with segmentation. 
85 LDT/GDT and IDT are emulated. VM86 mode is also supported to run DOSEMU.
87 @item Support of host page sizes bigger than 4KB in user mode emulation.
89 @item QEMU can emulate itself on x86.
91 @item An extensive Linux x86 CPU test program is included @file{tests/test-i386}. 
92 It can be used to test other x86 virtual CPUs.
94 @end itemize
96 Current QEMU limitations:
98 @itemize 
100 @item No SSE/MMX support (yet).
102 @item No x86-64 support.
104 @item IPC syscalls are missing.
106 @item The x86 segment limits and access rights are not tested at every 
107 memory access.
109 @item On non x86 host CPUs, @code{double}s are used instead of the non standard 
110 10 byte @code{long double}s of x86 for floating point emulation to get
111 maximum performances.
113 @item Some priviledged instructions or behaviors are missing, especially for segment protection testing (yet). 
115 @end itemize
117 @section ARM emulation
119 @itemize
121 @item ARM emulation can currently launch small programs while using the
122 generic dynamic code generation architecture of QEMU.
124 @item No FPU support (yet).
126 @item No automatic regression testing (yet).
128 @end itemize
130 @section SPARC emulation
132 The SPARC emulation is currently in development.
134 @chapter Installation
136 If you want to compile QEMU, please read the @file{README} which gives
137 the related information. Otherwise just download the binary
138 distribution (@file{qemu-XXX-i386.tar.gz}) and untar it as root in
139 @file{/}:
141 @example
143 cd /
144 tar zxvf /tmp/qemu-XXX-i386.tar.gz
145 @end example
147 @chapter QEMU User space emulator invocation
149 @section Quick Start
151 In order to launch a Linux process, QEMU needs the process executable
152 itself and all the target (x86) dynamic libraries used by it. 
154 @itemize
156 @item On x86, you can just try to launch any process by using the native
157 libraries:
159 @example 
160 qemu-i386 -L / /bin/ls
161 @end example
163 @code{-L /} tells that the x86 dynamic linker must be searched with a
164 @file{/} prefix.
166 @item Since QEMU is also a linux process, you can launch qemu with qemu (NOTE: you can only do that if you compiled QEMU from the sources):
168 @example 
169 qemu-i386 -L / qemu-i386 -L / /bin/ls
170 @end example
172 @item On non x86 CPUs, you need first to download at least an x86 glibc
173 (@file{qemu-runtime-i386-XXX-.tar.gz} on the QEMU web page). Ensure that
174 @code{LD_LIBRARY_PATH} is not set:
176 @example
177 unset LD_LIBRARY_PATH 
178 @end example
180 Then you can launch the precompiled @file{ls} x86 executable:
182 @example
183 qemu-i386 tests/i386/ls
184 @end example
185 You can look at @file{qemu-binfmt-conf.sh} so that
186 QEMU is automatically launched by the Linux kernel when you try to
187 launch x86 executables. It requires the @code{binfmt_misc} module in the
188 Linux kernel.
190 @item The x86 version of QEMU is also included. You can try weird things such as:
191 @example
192 qemu-i386 /usr/local/qemu-i386/bin/qemu-i386 /usr/local/qemu-i386/bin/ls-i386
193 @end example
195 @end itemize
197 @section Wine launch
199 @itemize
201 @item Ensure that you have a working QEMU with the x86 glibc
202 distribution (see previous section). In order to verify it, you must be
203 able to do:
205 @example
206 qemu-i386 /usr/local/qemu-i386/bin/ls-i386
207 @end example
209 @item Download the binary x86 Wine install
210 (@file{qemu-XXX-i386-wine.tar.gz} on the QEMU web page). 
212 @item Configure Wine on your account. Look at the provided script
213 @file{/usr/local/qemu-i386/bin/wine-conf.sh}. Your previous
214 @code{$@{HOME@}/.wine} directory is saved to @code{$@{HOME@}/.wine.org}.
216 @item Then you can try the example @file{putty.exe}:
218 @example
219 qemu-i386 /usr/local/qemu-i386/wine/bin/wine /usr/local/qemu-i386/wine/c/Program\ Files/putty.exe
220 @end example
222 @end itemize
224 @section Command line options
226 @example
227 usage: qemu-i386 [-h] [-d] [-L path] [-s size] program [arguments...]
228 @end example
230 @table @option
231 @item -h
232 Print the help
233 @item -L path   
234 Set the x86 elf interpreter prefix (default=/usr/local/qemu-i386)
235 @item -s size
236 Set the x86 stack size in bytes (default=524288)
237 @end table
239 Debug options:
241 @table @option
242 @item -d
243 Activate log (logfile=/tmp/qemu.log)
244 @item -p pagesize
245 Act as if the host page size was 'pagesize' bytes
246 @end table
248 @chapter QEMU System emulator invocation
250 @section Introduction
252 @c man begin DESCRIPTION
254 The QEMU System emulator simulates a complete PC. It can either boot
255 directly a Linux kernel (without any BIOS or boot loader) or boot like a
256 real PC with the included BIOS.
258 In order to meet specific user needs, two versions of QEMU are
259 available:
261 @enumerate
263 @item 
264 @code{qemu-fast} uses the host Memory Management Unit (MMU) to simulate 
265 the x86 MMU. It is @emph{fast} but has limitations because the whole 4 GB
266 address space cannot be used and some memory mapped peripherials
267 cannot be emulated accurately yet. Therefore, a specific Linux kernel
268 must be used (@xref{linux_compile}).
270 @item 
271 @code{qemu} uses a software MMU. It is about @emph{two times 
272 slower} but gives a more accurate emulation. 
274 @end enumerate
276 QEMU emulates the following PC peripherials:
278 @itemize @minus
279 @item
280 VGA (hardware level, including all non standard modes)
281 @item
282 PS/2 mouse and keyboard
283 @item 
284 2 IDE interfaces with hard disk and CD-ROM support
285 @item 
286 NE2000 network adapter (port=0x300, irq=9)
287 @item
288 Serial port
289 @item 
290 Soundblaster 16 card
291 @item
292 PIC (interrupt controler)
293 @item
294 PIT (timers)
295 @item 
296 CMOS memory
297 @end itemize
299 @c man end
301 @section Quick Start
303 Download and uncompress the linux image (@file{linux.img}) and type:
305 @example
306 qemu linux.img
307 @end example
309 Linux should boot and give you a prompt.
311 @section Direct Linux Boot and Network emulation
313 This section explains how to launch a Linux kernel inside QEMU without
314 having to make a full bootable image. It is very useful for fast Linux
315 kernel testing. The QEMU network configuration is also explained.
317 @enumerate
318 @item
319 Download the archive @file{linux-test-xxx.tar.gz} containing a Linux
320 kernel and a disk image. 
322 @item Optional: If you want network support (for example to launch X11 examples), you
323 must copy the script @file{qemu-ifup} in @file{/etc} and configure
324 properly @code{sudo} so that the command @code{ifconfig} contained in
325 @file{qemu-ifup} can be executed as root. You must verify that your host
326 kernel supports the TUN/TAP network interfaces: the device
327 @file{/dev/net/tun} must be present.
329 When network is enabled, there is a virtual network connection between
330 the host kernel and the emulated kernel. The emulated kernel is seen
331 from the host kernel at IP address 172.20.0.2 and the host kernel is
332 seen from the emulated kernel at IP address 172.20.0.1.
334 @item Launch @code{qemu.sh}. You should have the following output:
336 @example
337 > ./qemu.sh 
338 Connected to host network interface: tun0
339 Linux version 2.4.21 (bellard@voyager.localdomain) (gcc version 3.2.2 20030222 (Red Hat Linux 3.2.2-5)) #5 Tue Nov 11 18:18:53 CET 2003
340 BIOS-provided physical RAM map:
341  BIOS-e801: 0000000000000000 - 000000000009f000 (usable)
342  BIOS-e801: 0000000000100000 - 0000000002000000 (usable)
343 32MB LOWMEM available.
344 On node 0 totalpages: 8192
345 zone(0): 4096 pages.
346 zone(1): 4096 pages.
347 zone(2): 0 pages.
348 Kernel command line: root=/dev/hda sb=0x220,5,1,5 ide2=noprobe ide3=noprobe ide4=noprobe ide5=noprobe console=ttyS0
349 ide_setup: ide2=noprobe
350 ide_setup: ide3=noprobe
351 ide_setup: ide4=noprobe
352 ide_setup: ide5=noprobe
353 Initializing CPU#0
354 Detected 2399.621 MHz processor.
355 Console: colour EGA 80x25
356 Calibrating delay loop... 4744.80 BogoMIPS
357 Memory: 28872k/32768k available (1210k kernel code, 3508k reserved, 266k data, 64k init, 0k highmem)
358 Dentry cache hash table entries: 4096 (order: 3, 32768 bytes)
359 Inode cache hash table entries: 2048 (order: 2, 16384 bytes)
360 Mount cache hash table entries: 512 (order: 0, 4096 bytes)
361 Buffer-cache hash table entries: 1024 (order: 0, 4096 bytes)
362 Page-cache hash table entries: 8192 (order: 3, 32768 bytes)
363 CPU: Intel Pentium Pro stepping 03
364 Checking 'hlt' instruction... OK.
365 POSIX conformance testing by UNIFIX
366 Linux NET4.0 for Linux 2.4
367 Based upon Swansea University Computer Society NET3.039
368 Initializing RT netlink socket
369 apm: BIOS not found.
370 Starting kswapd
371 Journalled Block Device driver loaded
372 Detected PS/2 Mouse Port.
373 pty: 256 Unix98 ptys configured
374 Serial driver version 5.05c (2001-07-08) with no serial options enabled
375 ttyS00 at 0x03f8 (irq = 4) is a 16450
376 ne.c:v1.10 9/23/94 Donald Becker (becker@scyld.com)
377 Last modified Nov 1, 2000 by Paul Gortmaker
378 NE*000 ethercard probe at 0x300: 52 54 00 12 34 56
379 eth0: NE2000 found at 0x300, using IRQ 9.
380 RAMDISK driver initialized: 16 RAM disks of 4096K size 1024 blocksize
381 Uniform Multi-Platform E-IDE driver Revision: 7.00beta4-2.4
382 ide: Assuming 50MHz system bus speed for PIO modes; override with idebus=xx
383 hda: QEMU HARDDISK, ATA DISK drive
384 ide0 at 0x1f0-0x1f7,0x3f6 on irq 14
385 hda: attached ide-disk driver.
386 hda: 20480 sectors (10 MB) w/256KiB Cache, CHS=20/16/63
387 Partition check:
388  hda:
389 Soundblaster audio driver Copyright (C) by Hannu Savolainen 1993-1996
390 NET4: Linux TCP/IP 1.0 for NET4.0
391 IP Protocols: ICMP, UDP, TCP, IGMP
392 IP: routing cache hash table of 512 buckets, 4Kbytes
393 TCP: Hash tables configured (established 2048 bind 4096)
394 NET4: Unix domain sockets 1.0/SMP for Linux NET4.0.
395 EXT2-fs warning: mounting unchecked fs, running e2fsck is recommended
396 VFS: Mounted root (ext2 filesystem).
397 Freeing unused kernel memory: 64k freed
399 Linux version 2.4.21 (bellard@voyager.localdomain) (gcc version 3.2.2 20030222 (Red Hat Linux 3.2.2-5)) #5 Tue Nov 11 18:18:53 CET 2003
401 QEMU Linux test distribution (based on Redhat 9)
403 Type 'exit' to halt the system
405 sh-2.05b# 
406 @end example
408 @item
409 Then you can play with the kernel inside the virtual serial console. You
410 can launch @code{ls} for example. Type @key{Ctrl-a h} to have an help
411 about the keys you can type inside the virtual serial console. In
412 particular, use @key{Ctrl-a x} to exit QEMU and use @key{Ctrl-a b} as
413 the Magic SysRq key.
415 @item 
416 If the network is enabled, launch the script @file{/etc/linuxrc} in the
417 emulator (don't forget the leading dot):
418 @example
419 . /etc/linuxrc
420 @end example
422 Then enable X11 connections on your PC from the emulated Linux: 
423 @example
424 xhost +172.20.0.2
425 @end example
427 You can now launch @file{xterm} or @file{xlogo} and verify that you have
428 a real Virtual Linux system !
430 @end enumerate
432 NOTES:
433 @enumerate
434 @item 
435 A 2.5.74 kernel is also included in the archive. Just
436 replace the bzImage in qemu.sh to try it.
438 @item 
439 qemu creates a temporary file in @var{$QEMU_TMPDIR} (@file{/tmp} is the
440 default) containing all the simulated PC memory. If possible, try to use
441 a temporary directory using the tmpfs filesystem to avoid too many
442 unnecessary disk accesses.
444 @item 
445 In order to exit cleanly from qemu, you can do a @emph{shutdown} inside
446 qemu. qemu will automatically exit when the Linux shutdown is done.
448 @item 
449 You can boot slightly faster by disabling the probe of non present IDE
450 interfaces. To do so, add the following options on the kernel command
451 line:
452 @example
453 ide1=noprobe ide2=noprobe ide3=noprobe ide4=noprobe ide5=noprobe
454 @end example
456 @item 
457 The example disk image is a modified version of the one made by Kevin
458 Lawton for the plex86 Project (@url{www.plex86.org}).
460 @end enumerate
462 @section Invocation
464 @example
465 @c man begin SYNOPSIS
466 usage: qemu [options] [disk_image]
467 @c man end
468 @end example
470 @c man begin OPTIONS
471 @var{disk_image} is a raw hard disk image for IDE hard disk 0.
473 General options:
474 @table @option
475 @item -hda file
476 @item -hdb file
477 @item -hdc file
478 @item -hdd file
479 Use @var{file} as hard disk 0, 1, 2 or 3 image (@xref{disk_images}). 
481 @item -cdrom file
482 Use @var{file} as CD-ROM image (you cannot use @option{-hdc} and and
483 @option{-cdrom} at the same time).
485 @item -boot [c|d]
486 Boot on hard disk (c) or CD-ROM (d). Hard disk boot is the default.
488 @item -snapshot
489 Write to temporary files instead of disk image files. In this case,
490 the raw disk image you use is not written back. You can however force
491 the write back by pressing @key{C-a s} (@xref{disk_images}). 
493 @item -m megs
494 Set virtual RAM size to @var{megs} megabytes.
496 @item -n script      
497 Set network init script [default=/etc/qemu-ifup]. This script is
498 launched to configure the host network interface (usually tun0)
499 corresponding to the virtual NE2000 card.
501 @item -initrd file
502 Use @var{file} as initial ram disk.
504 @item -tun-fd fd      
505 Assumes @var{fd} talks to tap/tun and use it. Read
506 @url{http://bellard.org/qemu/tetrinet.html} to have an example of its
507 use.
509 @item -nographic
511 Normally, QEMU uses SDL to display the VGA output. With this option,
512 you can totally disable graphical output so that QEMU is a simple
513 command line application. The emulated serial port is redirected on
514 the console. Therefore, you can still use QEMU to debug a Linux kernel
515 with a serial console.
517 @end table
519 Linux boot specific (does not require a full PC boot with a BIOS):
520 @table @option
522 @item -kernel bzImage 
523 Use @var{bzImage} as kernel image.
525 @item -append cmdline 
526 Use @var{cmdline} as kernel command line
528 @item -initrd file
529 Use @var{file} as initial ram disk.
531 @end table
533 Debug options:
534 @table @option
535 @item -s
536 Wait gdb connection to port 1234 (@xref{gdb_usage}). 
537 @item -p port
538 Change gdb connection port.
539 @item -d             
540 Output log in /tmp/qemu.log
541 @end table
543 During emulation, use @key{C-a h} to get terminal commands:
545 @table @key
546 @item C-a h
547 Print this help
548 @item C-a x    
549 Exit emulatior
550 @item C-a s    
551 Save disk data back to file (if -snapshot)
552 @item C-a b
553 Send break (magic sysrq)
554 @item C-a C-a
555 Send C-a
556 @end table
557 @c man end
559 @ignore
561 @setfilename qemu 
562 @settitle QEMU System Emulator
564 @c man begin SEEALSO
565 The HTML documentation of QEMU for more precise information and Linux
566 user mode emulator invocation.
567 @c man end
569 @c man begin AUTHOR
570 Fabrice Bellard
571 @c man end
573 @end ignore
575 @end ignore
576 @node disk_images
577 @section Disk Images
579 @subsection Raw disk images
581 The disk images can simply be raw images of the hard disk. You can
582 create them with the command:
583 @example
584 dd if=/dev/zero of=myimage bs=1024 count=mysize
585 @end example
586 where @var{myimage} is the image filename and @var{mysize} is its size
587 in kilobytes.
589 @subsection Snapshot mode
591 If you use the option @option{-snapshot}, all disk images are
592 considered as read only. When sectors in written, they are written in
593 a temporary file created in @file{/tmp}. You can however force the
594 write back to the raw disk images by pressing @key{C-a s}.
596 NOTE: The snapshot mode only works with raw disk images.
598 @subsection Copy On Write disk images
600 QEMU also supports user mode Linux
601 (@url{http://user-mode-linux.sourceforge.net/}) Copy On Write (COW)
602 disk images. The COW disk images are much smaller than normal images
603 as they store only modified sectors. They also permit the use of the
604 same disk image template for many users.
606 To create a COW disk images, use the command:
608 @example
609 qemu-mkcow -f myrawimage.bin mycowimage.cow
610 @end example
612 @file{myrawimage.bin} is a raw image you want to use as original disk
613 image. It will never be written to.
615 @file{mycowimage.cow} is the COW disk image which is created by
616 @code{qemu-mkcow}. You can use it directly with the @option{-hdx}
617 options. You must not modify the original raw disk image if you use
618 COW images, as COW images only store the modified sectors from the raw
619 disk image. QEMU stores the original raw disk image name and its
620 modified time in the COW disk image so that chances of mistakes are
621 reduced.
623 If the raw disk image is not read-only, by pressing @key{C-a s} you
624 can flush the COW disk image back into the raw disk image, as in
625 snapshot mode.
627 COW disk images can also be created without a corresponding raw disk
628 image. It is useful to have a big initial virtual disk image without
629 using much disk space. Use:
631 @example
632 qemu-mkcow mycowimage.cow 1024
633 @end example
635 to create a 1 gigabyte empty COW disk image.
637 NOTES: 
638 @enumerate
639 @item
640 COW disk images must be created on file systems supporting
641 @emph{holes} such as ext2 or ext3.
642 @item 
643 Since holes are used, the displayed size of the COW disk image is not
644 the real one. To know it, use the @code{ls -ls} command.
645 @end enumerate
647 @node linux_compile
648 @section Linux Kernel Compilation
650 You can use any linux kernel with QEMU. However, if you want to use
651 @code{qemu-fast} to get maximum performances, you should make the
652 following changes to the Linux kernel (only 2.4.x and 2.5.x were
653 tested):
655 @enumerate
656 @item
657 The kernel must be mapped at 0x90000000 (the default is
658 0xc0000000). You must modify only two lines in the kernel source:
660 In @file{include/asm/page.h}, replace
661 @example
662 #define __PAGE_OFFSET           (0xc0000000)
663 @end example
665 @example
666 #define __PAGE_OFFSET           (0x90000000)
667 @end example
669 And in @file{arch/i386/vmlinux.lds}, replace
670 @example
671   . = 0xc0000000 + 0x100000;
672 @end example
673 by 
674 @example
675   . = 0x90000000 + 0x100000;
676 @end example
678 @item
679 If you want to enable SMP (Symmetric Multi-Processing) support, you
680 must make the following change in @file{include/asm/fixmap.h}. Replace
681 @example
682 #define FIXADDR_TOP     (0xffffX000UL)
683 @end example
684 by 
685 @example
686 #define FIXADDR_TOP     (0xa7ffX000UL)
687 @end example
688 (X is 'e' or 'f' depending on the kernel version). Although you can
689 use an SMP kernel with QEMU, it only supports one CPU.
691 @item
692 If you are not using a 2.5 kernel as host kernel but if you use a target
693 2.5 kernel, you must also ensure that the 'HZ' define is set to 100
694 (1000 is the default) as QEMU cannot currently emulate timers at
695 frequencies greater than 100 Hz on host Linux systems < 2.5. In
696 @file{include/asm/param.h}, replace:
698 @example
699 # define HZ             1000            /* Internal kernel timer frequency */
700 @end example
702 @example
703 # define HZ             100             /* Internal kernel timer frequency */
704 @end example
706 @end enumerate
708 The file config-2.x.x gives the configuration of the example kernels.
710 Just type
711 @example
712 make bzImage
713 @end example
715 As you would do to make a real kernel. Then you can use with QEMU
716 exactly the same kernel as you would boot on your PC (in
717 @file{arch/i386/boot/bzImage}).
719 @node gdb_usage
720 @section GDB usage
722 QEMU has a primitive support to work with gdb, so that you can do
723 'Ctrl-C' while the virtual machine is running and inspect its state.
725 In order to use gdb, launch qemu with the '-s' option. It will wait for a
726 gdb connection:
727 @example
728 > qemu -s arch/i386/boot/bzImage -hda root-2.4.20.img root=/dev/hda
729 Connected to host network interface: tun0
730 Waiting gdb connection on port 1234
731 @end example
733 Then launch gdb on the 'vmlinux' executable:
734 @example
735 > gdb vmlinux
736 @end example
738 In gdb, connect to QEMU:
739 @example
740 (gdb) target remote locahost:1234
741 @end example
743 Then you can use gdb normally. For example, type 'c' to launch the kernel:
744 @example
745 (gdb) c
746 @end example
748 Here are some useful tips in order to use gdb on system code:
750 @enumerate
751 @item
752 Use @code{info reg} to display all the CPU registers.
753 @item
754 Use @code{x/10i $eip} to display the code at the PC position.
755 @item
756 Use @code{set architecture i8086} to dump 16 bit code. Then use
757 @code{x/10i $cs*16+*eip} to dump the code at the PC position.
758 @end enumerate
760 @chapter QEMU Internals
762 @section QEMU compared to other emulators
764 Like bochs [3], QEMU emulates an x86 CPU. But QEMU is much faster than
765 bochs as it uses dynamic compilation and because it uses the host MMU to
766 simulate the x86 MMU. The downside is that currently the emulation is
767 not as accurate as bochs (for example, you cannot currently run Windows
768 inside QEMU).
770 Like Valgrind [2], QEMU does user space emulation and dynamic
771 translation. Valgrind is mainly a memory debugger while QEMU has no
772 support for it (QEMU could be used to detect out of bound memory
773 accesses as Valgrind, but it has no support to track uninitialised data
774 as Valgrind does). The Valgrind dynamic translator generates better code
775 than QEMU (in particular it does register allocation) but it is closely
776 tied to an x86 host and target and has no support for precise exceptions
777 and system emulation.
779 EM86 [4] is the closest project to user space QEMU (and QEMU still uses
780 some of its code, in particular the ELF file loader). EM86 was limited
781 to an alpha host and used a proprietary and slow interpreter (the
782 interpreter part of the FX!32 Digital Win32 code translator [5]).
784 TWIN [6] is a Windows API emulator like Wine. It is less accurate than
785 Wine but includes a protected mode x86 interpreter to launch x86 Windows
786 executables. Such an approach as greater potential because most of the
787 Windows API is executed natively but it is far more difficult to develop
788 because all the data structures and function parameters exchanged
789 between the API and the x86 code must be converted.
791 User mode Linux [7] was the only solution before QEMU to launch a Linux
792 kernel as a process while not needing any host kernel patches. However,
793 user mode Linux requires heavy kernel patches while QEMU accepts
794 unpatched Linux kernels. It would be interesting to compare the
795 performance of the two approaches.
797 The new Plex86 [8] PC virtualizer is done in the same spirit as the QEMU
798 system emulator. It requires a patched Linux kernel to work (you cannot
799 launch the same kernel on your PC), but the patches are really small. As
800 it is a PC virtualizer (no emulation is done except for some priveledged
801 instructions), it has the potential of being faster than QEMU. The
802 downside is that a complicated (and potentially unsafe) host kernel
803 patch is needed.
805 @section Portable dynamic translation
807 QEMU is a dynamic translator. When it first encounters a piece of code,
808 it converts it to the host instruction set. Usually dynamic translators
809 are very complicated and highly CPU dependent. QEMU uses some tricks
810 which make it relatively easily portable and simple while achieving good
811 performances.
813 The basic idea is to split every x86 instruction into fewer simpler
814 instructions. Each simple instruction is implemented by a piece of C
815 code (see @file{op-i386.c}). Then a compile time tool (@file{dyngen})
816 takes the corresponding object file (@file{op-i386.o}) to generate a
817 dynamic code generator which concatenates the simple instructions to
818 build a function (see @file{op-i386.h:dyngen_code()}).
820 In essence, the process is similar to [1], but more work is done at
821 compile time. 
823 A key idea to get optimal performances is that constant parameters can
824 be passed to the simple operations. For that purpose, dummy ELF
825 relocations are generated with gcc for each constant parameter. Then,
826 the tool (@file{dyngen}) can locate the relocations and generate the
827 appriopriate C code to resolve them when building the dynamic code.
829 That way, QEMU is no more difficult to port than a dynamic linker.
831 To go even faster, GCC static register variables are used to keep the
832 state of the virtual CPU.
834 @section Register allocation
836 Since QEMU uses fixed simple instructions, no efficient register
837 allocation can be done. However, because RISC CPUs have a lot of
838 register, most of the virtual CPU state can be put in registers without
839 doing complicated register allocation.
841 @section Condition code optimisations
843 Good CPU condition codes emulation (@code{EFLAGS} register on x86) is a
844 critical point to get good performances. QEMU uses lazy condition code
845 evaluation: instead of computing the condition codes after each x86
846 instruction, it just stores one operand (called @code{CC_SRC}), the
847 result (called @code{CC_DST}) and the type of operation (called
848 @code{CC_OP}).
850 @code{CC_OP} is almost never explicitely set in the generated code
851 because it is known at translation time.
853 In order to increase performances, a backward pass is performed on the
854 generated simple instructions (see
855 @code{translate-i386.c:optimize_flags()}). When it can be proved that
856 the condition codes are not needed by the next instructions, no
857 condition codes are computed at all.
859 @section CPU state optimisations
861 The x86 CPU has many internal states which change the way it evaluates
862 instructions. In order to achieve a good speed, the translation phase
863 considers that some state information of the virtual x86 CPU cannot
864 change in it. For example, if the SS, DS and ES segments have a zero
865 base, then the translator does not even generate an addition for the
866 segment base.
868 [The FPU stack pointer register is not handled that way yet].
870 @section Translation cache
872 A 2MByte cache holds the most recently used translations. For
873 simplicity, it is completely flushed when it is full. A translation unit
874 contains just a single basic block (a block of x86 instructions
875 terminated by a jump or by a virtual CPU state change which the
876 translator cannot deduce statically).
878 @section Direct block chaining
880 After each translated basic block is executed, QEMU uses the simulated
881 Program Counter (PC) and other cpu state informations (such as the CS
882 segment base value) to find the next basic block.
884 In order to accelerate the most common cases where the new simulated PC
885 is known, QEMU can patch a basic block so that it jumps directly to the
886 next one.
888 The most portable code uses an indirect jump. An indirect jump makes it
889 easier to make the jump target modification atomic. On some
890 architectures (such as PowerPC), the @code{JUMP} opcode is directly
891 patched so that the block chaining has no overhead.
893 @section Self-modifying code and translated code invalidation
895 Self-modifying code is a special challenge in x86 emulation because no
896 instruction cache invalidation is signaled by the application when code
897 is modified.
899 When translated code is generated for a basic block, the corresponding
900 host page is write protected if it is not already read-only (with the
901 system call @code{mprotect()}). Then, if a write access is done to the
902 page, Linux raises a SEGV signal. QEMU then invalidates all the
903 translated code in the page and enables write accesses to the page.
905 Correct translated code invalidation is done efficiently by maintaining
906 a linked list of every translated block contained in a given page. Other
907 linked lists are also maintained to undo direct block chaining. 
909 Although the overhead of doing @code{mprotect()} calls is important,
910 most MSDOS programs can be emulated at reasonnable speed with QEMU and
911 DOSEMU.
913 Note that QEMU also invalidates pages of translated code when it detects
914 that memory mappings are modified with @code{mmap()} or @code{munmap()}.
916 @section Exception support
918 longjmp() is used when an exception such as division by zero is
919 encountered. 
921 The host SIGSEGV and SIGBUS signal handlers are used to get invalid
922 memory accesses. The exact CPU state can be retrieved because all the
923 x86 registers are stored in fixed host registers. The simulated program
924 counter is found by retranslating the corresponding basic block and by
925 looking where the host program counter was at the exception point.
927 The virtual CPU cannot retrieve the exact @code{EFLAGS} register because
928 in some cases it is not computed because of condition code
929 optimisations. It is not a big concern because the emulated code can
930 still be restarted in any cases.
932 @section Linux system call translation
934 QEMU includes a generic system call translator for Linux. It means that
935 the parameters of the system calls can be converted to fix the
936 endianness and 32/64 bit issues. The IOCTLs are converted with a generic
937 type description system (see @file{ioctls.h} and @file{thunk.c}).
939 QEMU supports host CPUs which have pages bigger than 4KB. It records all
940 the mappings the process does and try to emulated the @code{mmap()}
941 system calls in cases where the host @code{mmap()} call would fail
942 because of bad page alignment.
944 @section Linux signals
946 Normal and real-time signals are queued along with their information
947 (@code{siginfo_t}) as it is done in the Linux kernel. Then an interrupt
948 request is done to the virtual CPU. When it is interrupted, one queued
949 signal is handled by generating a stack frame in the virtual CPU as the
950 Linux kernel does. The @code{sigreturn()} system call is emulated to return
951 from the virtual signal handler.
953 Some signals (such as SIGALRM) directly come from the host. Other
954 signals are synthetized from the virtual CPU exceptions such as SIGFPE
955 when a division by zero is done (see @code{main.c:cpu_loop()}).
957 The blocked signal mask is still handled by the host Linux kernel so
958 that most signal system calls can be redirected directly to the host
959 Linux kernel. Only the @code{sigaction()} and @code{sigreturn()} system
960 calls need to be fully emulated (see @file{signal.c}).
962 @section clone() system call and threads
964 The Linux clone() system call is usually used to create a thread. QEMU
965 uses the host clone() system call so that real host threads are created
966 for each emulated thread. One virtual CPU instance is created for each
967 thread.
969 The virtual x86 CPU atomic operations are emulated with a global lock so
970 that their semantic is preserved.
972 Note that currently there are still some locking issues in QEMU. In
973 particular, the translated cache flush is not protected yet against
974 reentrancy.
976 @section Self-virtualization
978 QEMU was conceived so that ultimately it can emulate itself. Although
979 it is not very useful, it is an important test to show the power of the
980 emulator.
982 Achieving self-virtualization is not easy because there may be address
983 space conflicts. QEMU solves this problem by being an executable ELF
984 shared object as the ld-linux.so ELF interpreter. That way, it can be
985 relocated at load time.
987 @section MMU emulation
989 For system emulation, QEMU uses the mmap() system call to emulate the
990 target CPU MMU. It works as long the emulated OS does not use an area
991 reserved by the host OS (such as the area above 0xc0000000 on x86
992 Linux).
994 It is planned to add a slower but more precise MMU emulation
995 with a software MMU.
997 @section Bibliography
999 @table @asis
1001 @item [1] 
1002 @url{http://citeseer.nj.nec.com/piumarta98optimizing.html}, Optimizing
1003 direct threaded code by selective inlining (1998) by Ian Piumarta, Fabio
1004 Riccardi.
1006 @item [2]
1007 @url{http://developer.kde.org/~sewardj/}, Valgrind, an open-source
1008 memory debugger for x86-GNU/Linux, by Julian Seward.
1010 @item [3]
1011 @url{http://bochs.sourceforge.net/}, the Bochs IA-32 Emulator Project,
1012 by Kevin Lawton et al.
1014 @item [4]
1015 @url{http://www.cs.rose-hulman.edu/~donaldlf/em86/index.html}, the EM86
1016 x86 emulator on Alpha-Linux.
1018 @item [5]
1019 @url{http://www.usenix.org/publications/library/proceedings/usenix-nt97/full_papers/chernoff/chernoff.pdf},
1020 DIGITAL FX!32: Running 32-Bit x86 Applications on Alpha NT, by Anton
1021 Chernoff and Ray Hookway.
1023 @item [6]
1024 @url{http://www.willows.com/}, Windows API library emulation from
1025 Willows Software.
1027 @item [7]
1028 @url{http://user-mode-linux.sourceforge.net/}, 
1029 The User-mode Linux Kernel.
1031 @item [8]
1032 @url{http://www.plex86.org/}, 
1033 The new Plex86 project.
1035 @end table
1037 @chapter Regression Tests
1039 In the directory @file{tests/}, various interesting testing programs
1040 are available. There are used for regression testing.
1042 @section @file{test-i386}
1044 This program executes most of the 16 bit and 32 bit x86 instructions and
1045 generates a text output. It can be compared with the output obtained with
1046 a real CPU or another emulator. The target @code{make test} runs this
1047 program and a @code{diff} on the generated output.
1049 The Linux system call @code{modify_ldt()} is used to create x86 selectors
1050 to test some 16 bit addressing and 32 bit with segmentation cases.
1052 The Linux system call @code{vm86()} is used to test vm86 emulation.
1054 Various exceptions are raised to test most of the x86 user space
1055 exception reporting.
1057 @section @file{linux-test}
1059 This program tests various Linux system calls. It is used to verify
1060 that the system call parameters are correctly converted between target
1061 and host CPUs.
1063 @section @file{hello-i386}
1065 Very simple statically linked x86 program, just to test QEMU during a
1066 port to a new host CPU.
1068 @section @file{hello-arm}
1070 Very simple statically linked ARM program, just to test QEMU during a
1071 port to a new host CPU.
1073 @section @file{sha1}
1075 It is a simple benchmark. Care must be taken to interpret the results
1076 because it mostly tests the ability of the virtual CPU to optimize the
1077 @code{rol} x86 instruction and the condition code computations.