Merge branch 'qemu-cvs'
[qemu-kvm/fedora.git] / vl.c
blob710c41091d87a50b65fd582858cb1cd37d1759b2
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.h"
32 #include "hw/bt.h"
33 #include "net.h"
34 #include "console.h"
35 #include "sysemu.h"
36 #include "gdbstub.h"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
39 #include "cache-utils.h"
40 #include "block.h"
41 #include "audio/audio.h"
42 #include "hw/device-assignment.h"
43 #include "migration.h"
44 #include "kvm.h"
45 #include "balloon.h"
46 #include "qemu-kvm.h"
48 #include <unistd.h>
49 #include <fcntl.h>
50 #include <signal.h>
51 #include <time.h>
52 #include <errno.h>
53 #include <sys/time.h>
54 #include <zlib.h>
56 #ifndef _WIN32
57 #include <sys/times.h>
58 #include <sys/wait.h>
59 #include <termios.h>
60 #include <sys/mman.h>
61 #include <sys/ioctl.h>
62 #include <sys/resource.h>
63 #include <sys/socket.h>
64 #include <netinet/in.h>
65 #include <net/if.h>
66 #if defined(__NetBSD__)
67 #include <net/if_tap.h>
68 #endif
69 #ifdef __linux__
70 #include <linux/if_tun.h>
71 #endif
72 #include <arpa/inet.h>
73 #include <dirent.h>
74 #include <netdb.h>
75 #include <sys/select.h>
76 #ifdef _BSD
77 #include <sys/stat.h>
78 #ifdef __FreeBSD__
79 #include <libutil.h>
80 #else
81 #include <util.h>
82 #endif
83 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
84 #include <freebsd/stdlib.h>
85 #else
86 #ifdef __linux__
87 #include <pty.h>
88 #include <malloc.h>
89 #include <linux/rtc.h>
91 /* For the benefit of older linux systems which don't supply it,
92 we use a local copy of hpet.h. */
93 /* #include <linux/hpet.h> */
94 #include "hpet.h"
96 #include <linux/ppdev.h>
97 #include <linux/parport.h>
98 #endif
99 #ifdef __sun__
100 #include <sys/stat.h>
101 #include <sys/ethernet.h>
102 #include <sys/sockio.h>
103 #include <netinet/arp.h>
104 #include <netinet/in.h>
105 #include <netinet/in_systm.h>
106 #include <netinet/ip.h>
107 #include <netinet/ip_icmp.h> // must come after ip.h
108 #include <netinet/udp.h>
109 #include <netinet/tcp.h>
110 #include <net/if.h>
111 #include <syslog.h>
112 #include <stropts.h>
113 #endif
114 #endif
115 #endif
117 #include "qemu_socket.h"
119 #if defined(CONFIG_SLIRP)
120 #include "libslirp.h"
121 #endif
123 #if defined(__OpenBSD__)
124 #include <util.h>
125 #endif
127 #if defined(CONFIG_VDE)
128 #include <libvdeplug.h>
129 #endif
131 #ifdef _WIN32
132 #include <malloc.h>
133 #include <sys/timeb.h>
134 #include <mmsystem.h>
135 #define getopt_long_only getopt_long
136 #define memalign(align, size) malloc(size)
137 #endif
139 #ifdef CONFIG_SDL
140 #ifdef __APPLE__
141 #include <SDL/SDL.h>
142 #endif
143 #endif /* CONFIG_SDL */
145 #ifdef CONFIG_COCOA
146 #undef main
147 #define main qemu_main
148 #endif /* CONFIG_COCOA */
150 #include "disas.h"
152 #include "exec-all.h"
154 #include "qemu-kvm.h"
156 //#define DEBUG_UNUSED_IOPORT
157 //#define DEBUG_IOPORT
158 //#define DEBUG_NET
159 //#define DEBUG_SLIRP
162 #ifdef DEBUG_IOPORT
163 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
164 #else
165 # define LOG_IOPORT(...) do { } while (0)
166 #endif
168 #define DEFAULT_RAM_SIZE 128
170 /* Max number of USB devices that can be specified on the commandline. */
171 #define MAX_USB_CMDLINE 8
173 /* Max number of bluetooth switches on the commandline. */
174 #define MAX_BT_CMDLINE 10
176 /* XXX: use a two level table to limit memory usage */
177 #define MAX_IOPORTS 65536
179 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
180 const char *bios_name = NULL;
181 static void *ioport_opaque[MAX_IOPORTS];
182 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
183 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
184 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
185 to store the VM snapshots */
186 DriveInfo drives_table[MAX_DRIVES+1];
187 int nb_drives;
188 int extboot_drive = -1;
189 static int vga_ram_size;
190 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
191 static DisplayState *display_state;
192 int nographic;
193 static int curses;
194 static int sdl;
195 const char* keyboard_layout = NULL;
196 int64_t ticks_per_sec;
197 ram_addr_t ram_size;
198 int nb_nics;
199 NICInfo nd_table[MAX_NICS];
200 int vm_running;
201 static int rtc_utc = 1;
202 static int rtc_date_offset = -1; /* -1 means no change */
203 int cirrus_vga_enabled = 1;
204 int std_vga_enabled = 0;
205 int vmsvga_enabled = 0;
206 #ifdef TARGET_SPARC
207 int graphic_width = 1024;
208 int graphic_height = 768;
209 int graphic_depth = 8;
210 #else
211 int graphic_width = 800;
212 int graphic_height = 600;
213 int graphic_depth = 15;
214 #endif
215 static int full_screen = 0;
216 #ifdef CONFIG_SDL
217 static int no_frame = 0;
218 #endif
219 int no_quit = 0;
220 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
221 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
222 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
223 #ifdef TARGET_I386
224 int win2k_install_hack = 0;
225 int rtc_td_hack = 0;
226 #endif
227 int usb_enabled = 0;
228 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
229 int assigned_devices_index;
230 int smp_cpus = 1;
231 const char *vnc_display;
232 int acpi_enabled = 1;
233 int no_hpet = 0;
234 int fd_bootchk = 1;
235 int no_reboot = 0;
236 int no_shutdown = 0;
237 int cursor_hide = 1;
238 int graphic_rotate = 0;
239 int daemonize = 0;
240 const char *incoming;
241 const char *option_rom[MAX_OPTION_ROMS];
242 int nb_option_roms;
243 int semihosting_enabled = 0;
244 int time_drift_fix = 0;
245 unsigned int kvm_shadow_memory = 0;
246 const char *mem_path = NULL;
247 int hpagesize = 0;
248 const char *cpu_vendor_string;
249 #ifdef TARGET_ARM
250 int old_param = 0;
251 #endif
252 const char *qemu_name;
253 int alt_grab = 0;
254 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
255 unsigned int nb_prom_envs = 0;
256 const char *prom_envs[MAX_PROM_ENVS];
257 #endif
258 int nb_drives_opt;
259 const char *nvram = NULL;
260 struct drive_opt drives_opt[MAX_DRIVES];
262 static CPUState *cur_cpu;
263 static CPUState *next_cpu;
264 static int event_pending = 1;
265 /* Conversion factor from emulated instructions to virtual clock ticks. */
266 static int icount_time_shift;
267 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
268 #define MAX_ICOUNT_SHIFT 10
269 /* Compensate for varying guest execution speed. */
270 static int64_t qemu_icount_bias;
271 static QEMUTimer *icount_rt_timer;
272 static QEMUTimer *icount_vm_timer;
273 static QEMUTimer *nographic_timer;
275 uint8_t qemu_uuid[16];
277 /* KVM runs the main loop in a separate thread. If we update one of the lists
278 * that are polled before or after select(), we need to make sure to break out
279 * of the select() to ensure the new item is serviced.
281 static void main_loop_break(void)
283 if (kvm_enabled())
284 qemu_kvm_notify_work();
287 /***********************************************************/
288 /* x86 ISA bus support */
290 target_phys_addr_t isa_mem_base = 0;
291 PicState2 *isa_pic;
293 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
294 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
296 static uint32_t ioport_read(int index, uint32_t address)
298 static IOPortReadFunc *default_func[3] = {
299 default_ioport_readb,
300 default_ioport_readw,
301 default_ioport_readl
303 IOPortReadFunc *func = ioport_read_table[index][address];
304 if (!func)
305 func = default_func[index];
306 return func(ioport_opaque[address], address);
309 static void ioport_write(int index, uint32_t address, uint32_t data)
311 static IOPortWriteFunc *default_func[3] = {
312 default_ioport_writeb,
313 default_ioport_writew,
314 default_ioport_writel
316 IOPortWriteFunc *func = ioport_write_table[index][address];
317 if (!func)
318 func = default_func[index];
319 func(ioport_opaque[address], address, data);
322 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
324 #ifdef DEBUG_UNUSED_IOPORT
325 fprintf(stderr, "unused inb: port=0x%04x\n", address);
326 #endif
327 return 0xff;
330 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
332 #ifdef DEBUG_UNUSED_IOPORT
333 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
334 #endif
337 /* default is to make two byte accesses */
338 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
340 uint32_t data;
341 data = ioport_read(0, address);
342 address = (address + 1) & (MAX_IOPORTS - 1);
343 data |= ioport_read(0, address) << 8;
344 return data;
347 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
349 ioport_write(0, address, data & 0xff);
350 address = (address + 1) & (MAX_IOPORTS - 1);
351 ioport_write(0, address, (data >> 8) & 0xff);
354 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
356 #ifdef DEBUG_UNUSED_IOPORT
357 fprintf(stderr, "unused inl: port=0x%04x\n", address);
358 #endif
359 return 0xffffffff;
362 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
364 #ifdef DEBUG_UNUSED_IOPORT
365 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
366 #endif
369 /* size is the word size in byte */
370 int register_ioport_read(int start, int length, int size,
371 IOPortReadFunc *func, void *opaque)
373 int i, bsize;
375 if (size == 1) {
376 bsize = 0;
377 } else if (size == 2) {
378 bsize = 1;
379 } else if (size == 4) {
380 bsize = 2;
381 } else {
382 hw_error("register_ioport_read: invalid size");
383 return -1;
385 for(i = start; i < start + length; i += size) {
386 ioport_read_table[bsize][i] = func;
387 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
388 hw_error("register_ioport_read: invalid opaque");
389 ioport_opaque[i] = opaque;
391 return 0;
394 /* size is the word size in byte */
395 int register_ioport_write(int start, int length, int size,
396 IOPortWriteFunc *func, void *opaque)
398 int i, bsize;
400 if (size == 1) {
401 bsize = 0;
402 } else if (size == 2) {
403 bsize = 1;
404 } else if (size == 4) {
405 bsize = 2;
406 } else {
407 hw_error("register_ioport_write: invalid size");
408 return -1;
410 for(i = start; i < start + length; i += size) {
411 ioport_write_table[bsize][i] = func;
412 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
413 hw_error("register_ioport_write: invalid opaque");
414 ioport_opaque[i] = opaque;
416 return 0;
419 void isa_unassign_ioport(int start, int length)
421 int i;
423 for(i = start; i < start + length; i++) {
424 ioport_read_table[0][i] = default_ioport_readb;
425 ioport_read_table[1][i] = default_ioport_readw;
426 ioport_read_table[2][i] = default_ioport_readl;
428 ioport_write_table[0][i] = default_ioport_writeb;
429 ioport_write_table[1][i] = default_ioport_writew;
430 ioport_write_table[2][i] = default_ioport_writel;
432 ioport_opaque[i] = NULL;
436 /***********************************************************/
438 void cpu_outb(CPUState *env, int addr, int val)
440 LOG_IOPORT("outb: %04x %02x\n", addr, val);
441 ioport_write(0, addr, val);
442 #ifdef USE_KQEMU
443 if (env)
444 env->last_io_time = cpu_get_time_fast();
445 #endif
448 void cpu_outw(CPUState *env, int addr, int val)
450 LOG_IOPORT("outw: %04x %04x\n", addr, val);
451 ioport_write(1, addr, val);
452 #ifdef USE_KQEMU
453 if (env)
454 env->last_io_time = cpu_get_time_fast();
455 #endif
458 void cpu_outl(CPUState *env, int addr, int val)
460 LOG_IOPORT("outl: %04x %08x\n", addr, val);
461 ioport_write(2, addr, val);
462 #ifdef USE_KQEMU
463 if (env)
464 env->last_io_time = cpu_get_time_fast();
465 #endif
468 int cpu_inb(CPUState *env, int addr)
470 int val;
471 val = ioport_read(0, addr);
472 LOG_IOPORT("inb : %04x %02x\n", addr, val);
473 #ifdef USE_KQEMU
474 if (env)
475 env->last_io_time = cpu_get_time_fast();
476 #endif
477 return val;
480 int cpu_inw(CPUState *env, int addr)
482 int val;
483 val = ioport_read(1, addr);
484 LOG_IOPORT("inw : %04x %04x\n", addr, val);
485 #ifdef USE_KQEMU
486 if (env)
487 env->last_io_time = cpu_get_time_fast();
488 #endif
489 return val;
492 int cpu_inl(CPUState *env, int addr)
494 int val;
495 val = ioport_read(2, addr);
496 LOG_IOPORT("inl : %04x %08x\n", addr, val);
497 #ifdef USE_KQEMU
498 if (env)
499 env->last_io_time = cpu_get_time_fast();
500 #endif
501 return val;
504 /***********************************************************/
505 void hw_error(const char *fmt, ...)
507 va_list ap;
508 CPUState *env;
510 va_start(ap, fmt);
511 fprintf(stderr, "qemu: hardware error: ");
512 vfprintf(stderr, fmt, ap);
513 fprintf(stderr, "\n");
514 for(env = first_cpu; env != NULL; env = env->next_cpu) {
515 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
516 #ifdef TARGET_I386
517 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
518 #else
519 cpu_dump_state(env, stderr, fprintf, 0);
520 #endif
522 va_end(ap);
523 abort();
526 /***************/
527 /* ballooning */
529 static QEMUBalloonEvent *qemu_balloon_event;
530 void *qemu_balloon_event_opaque;
532 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
534 qemu_balloon_event = func;
535 qemu_balloon_event_opaque = opaque;
538 void qemu_balloon(ram_addr_t target)
540 if (qemu_balloon_event)
541 qemu_balloon_event(qemu_balloon_event_opaque, target);
544 ram_addr_t qemu_balloon_status(void)
546 if (qemu_balloon_event)
547 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
548 return 0;
551 /***********************************************************/
552 /* keyboard/mouse */
554 static QEMUPutKBDEvent *qemu_put_kbd_event;
555 static void *qemu_put_kbd_event_opaque;
556 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
557 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
559 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
561 qemu_put_kbd_event_opaque = opaque;
562 qemu_put_kbd_event = func;
565 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
566 void *opaque, int absolute,
567 const char *name)
569 QEMUPutMouseEntry *s, *cursor;
571 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
572 if (!s)
573 return NULL;
575 s->qemu_put_mouse_event = func;
576 s->qemu_put_mouse_event_opaque = opaque;
577 s->qemu_put_mouse_event_absolute = absolute;
578 s->qemu_put_mouse_event_name = qemu_strdup(name);
579 s->next = NULL;
581 if (!qemu_put_mouse_event_head) {
582 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
583 return s;
586 cursor = qemu_put_mouse_event_head;
587 while (cursor->next != NULL)
588 cursor = cursor->next;
590 cursor->next = s;
591 qemu_put_mouse_event_current = s;
593 return s;
596 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
598 QEMUPutMouseEntry *prev = NULL, *cursor;
600 if (!qemu_put_mouse_event_head || entry == NULL)
601 return;
603 cursor = qemu_put_mouse_event_head;
604 while (cursor != NULL && cursor != entry) {
605 prev = cursor;
606 cursor = cursor->next;
609 if (cursor == NULL) // does not exist or list empty
610 return;
611 else if (prev == NULL) { // entry is head
612 qemu_put_mouse_event_head = cursor->next;
613 if (qemu_put_mouse_event_current == entry)
614 qemu_put_mouse_event_current = cursor->next;
615 qemu_free(entry->qemu_put_mouse_event_name);
616 qemu_free(entry);
617 return;
620 prev->next = entry->next;
622 if (qemu_put_mouse_event_current == entry)
623 qemu_put_mouse_event_current = prev;
625 qemu_free(entry->qemu_put_mouse_event_name);
626 qemu_free(entry);
629 void kbd_put_keycode(int keycode)
631 if (qemu_put_kbd_event) {
632 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
636 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
638 QEMUPutMouseEvent *mouse_event;
639 void *mouse_event_opaque;
640 int width;
642 if (!qemu_put_mouse_event_current) {
643 return;
646 mouse_event =
647 qemu_put_mouse_event_current->qemu_put_mouse_event;
648 mouse_event_opaque =
649 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
651 if (mouse_event) {
652 if (graphic_rotate) {
653 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
654 width = 0x7fff;
655 else
656 width = graphic_width - 1;
657 mouse_event(mouse_event_opaque,
658 width - dy, dx, dz, buttons_state);
659 } else
660 mouse_event(mouse_event_opaque,
661 dx, dy, dz, buttons_state);
665 int kbd_mouse_is_absolute(void)
667 if (!qemu_put_mouse_event_current)
668 return 0;
670 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
673 void do_info_mice(void)
675 QEMUPutMouseEntry *cursor;
676 int index = 0;
678 if (!qemu_put_mouse_event_head) {
679 term_printf("No mouse devices connected\n");
680 return;
683 term_printf("Mouse devices available:\n");
684 cursor = qemu_put_mouse_event_head;
685 while (cursor != NULL) {
686 term_printf("%c Mouse #%d: %s\n",
687 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
688 index, cursor->qemu_put_mouse_event_name);
689 index++;
690 cursor = cursor->next;
694 void do_mouse_set(int index)
696 QEMUPutMouseEntry *cursor;
697 int i = 0;
699 if (!qemu_put_mouse_event_head) {
700 term_printf("No mouse devices connected\n");
701 return;
704 cursor = qemu_put_mouse_event_head;
705 while (cursor != NULL && index != i) {
706 i++;
707 cursor = cursor->next;
710 if (cursor != NULL)
711 qemu_put_mouse_event_current = cursor;
712 else
713 term_printf("Mouse at given index not found\n");
716 /* compute with 96 bit intermediate result: (a*b)/c */
717 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
719 union {
720 uint64_t ll;
721 struct {
722 #ifdef WORDS_BIGENDIAN
723 uint32_t high, low;
724 #else
725 uint32_t low, high;
726 #endif
727 } l;
728 } u, res;
729 uint64_t rl, rh;
731 u.ll = a;
732 rl = (uint64_t)u.l.low * (uint64_t)b;
733 rh = (uint64_t)u.l.high * (uint64_t)b;
734 rh += (rl >> 32);
735 res.l.high = rh / c;
736 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
737 return res.ll;
740 /***********************************************************/
741 /* real time host monotonic timer */
743 #define QEMU_TIMER_BASE 1000000000LL
745 #ifdef WIN32
747 static int64_t clock_freq;
749 static void init_get_clock(void)
751 LARGE_INTEGER freq;
752 int ret;
753 ret = QueryPerformanceFrequency(&freq);
754 if (ret == 0) {
755 fprintf(stderr, "Could not calibrate ticks\n");
756 exit(1);
758 clock_freq = freq.QuadPart;
761 static int64_t get_clock(void)
763 LARGE_INTEGER ti;
764 QueryPerformanceCounter(&ti);
765 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
768 #else
770 static int use_rt_clock;
772 static void init_get_clock(void)
774 use_rt_clock = 0;
775 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
777 struct timespec ts;
778 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
779 use_rt_clock = 1;
782 #endif
785 static int64_t get_clock(void)
787 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
788 if (use_rt_clock) {
789 struct timespec ts;
790 clock_gettime(CLOCK_MONOTONIC, &ts);
791 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
792 } else
793 #endif
795 /* XXX: using gettimeofday leads to problems if the date
796 changes, so it should be avoided. */
797 struct timeval tv;
798 gettimeofday(&tv, NULL);
799 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
802 #endif
804 /* Return the virtual CPU time, based on the instruction counter. */
805 static int64_t cpu_get_icount(void)
807 int64_t icount;
808 CPUState *env = cpu_single_env;;
809 icount = qemu_icount;
810 if (env) {
811 if (!can_do_io(env))
812 fprintf(stderr, "Bad clock read\n");
813 icount -= (env->icount_decr.u16.low + env->icount_extra);
815 return qemu_icount_bias + (icount << icount_time_shift);
818 /***********************************************************/
819 /* guest cycle counter */
821 static int64_t cpu_ticks_prev;
822 static int64_t cpu_ticks_offset;
823 static int64_t cpu_clock_offset;
824 static int cpu_ticks_enabled;
826 /* return the host CPU cycle counter and handle stop/restart */
827 int64_t cpu_get_ticks(void)
829 if (use_icount) {
830 return cpu_get_icount();
832 if (!cpu_ticks_enabled) {
833 return cpu_ticks_offset;
834 } else {
835 int64_t ticks;
836 ticks = cpu_get_real_ticks();
837 if (cpu_ticks_prev > ticks) {
838 /* Note: non increasing ticks may happen if the host uses
839 software suspend */
840 cpu_ticks_offset += cpu_ticks_prev - ticks;
842 cpu_ticks_prev = ticks;
843 return ticks + cpu_ticks_offset;
847 /* return the host CPU monotonic timer and handle stop/restart */
848 static int64_t cpu_get_clock(void)
850 int64_t ti;
851 if (!cpu_ticks_enabled) {
852 return cpu_clock_offset;
853 } else {
854 ti = get_clock();
855 return ti + cpu_clock_offset;
859 /* enable cpu_get_ticks() */
860 void cpu_enable_ticks(void)
862 if (!cpu_ticks_enabled) {
863 cpu_ticks_offset -= cpu_get_real_ticks();
864 cpu_clock_offset -= get_clock();
865 cpu_ticks_enabled = 1;
869 /* disable cpu_get_ticks() : the clock is stopped. You must not call
870 cpu_get_ticks() after that. */
871 void cpu_disable_ticks(void)
873 if (cpu_ticks_enabled) {
874 cpu_ticks_offset = cpu_get_ticks();
875 cpu_clock_offset = cpu_get_clock();
876 cpu_ticks_enabled = 0;
880 /***********************************************************/
881 /* timers */
883 #define QEMU_TIMER_REALTIME 0
884 #define QEMU_TIMER_VIRTUAL 1
886 struct QEMUClock {
887 int type;
888 /* XXX: add frequency */
891 struct QEMUTimer {
892 QEMUClock *clock;
893 int64_t expire_time;
894 QEMUTimerCB *cb;
895 void *opaque;
896 struct QEMUTimer *next;
899 struct qemu_alarm_timer {
900 char const *name;
901 unsigned int flags;
903 int (*start)(struct qemu_alarm_timer *t);
904 void (*stop)(struct qemu_alarm_timer *t);
905 void (*rearm)(struct qemu_alarm_timer *t);
906 void *priv;
909 #define ALARM_FLAG_DYNTICKS 0x1
910 #define ALARM_FLAG_EXPIRED 0x2
912 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
914 return t->flags & ALARM_FLAG_DYNTICKS;
917 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
919 if (!alarm_has_dynticks(t))
920 return;
922 t->rearm(t);
925 /* TODO: MIN_TIMER_REARM_US should be optimized */
926 #define MIN_TIMER_REARM_US 250
928 static struct qemu_alarm_timer *alarm_timer;
929 #ifndef _WIN32
930 static int alarm_timer_rfd, alarm_timer_wfd;
931 #endif
933 #ifdef _WIN32
935 struct qemu_alarm_win32 {
936 MMRESULT timerId;
937 HANDLE host_alarm;
938 unsigned int period;
939 } alarm_win32_data = {0, NULL, -1};
941 static int win32_start_timer(struct qemu_alarm_timer *t);
942 static void win32_stop_timer(struct qemu_alarm_timer *t);
943 static void win32_rearm_timer(struct qemu_alarm_timer *t);
945 #else
947 static int unix_start_timer(struct qemu_alarm_timer *t);
948 static void unix_stop_timer(struct qemu_alarm_timer *t);
950 #ifdef __linux__
952 static int dynticks_start_timer(struct qemu_alarm_timer *t);
953 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
954 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
956 static int hpet_start_timer(struct qemu_alarm_timer *t);
957 static void hpet_stop_timer(struct qemu_alarm_timer *t);
959 static int rtc_start_timer(struct qemu_alarm_timer *t);
960 static void rtc_stop_timer(struct qemu_alarm_timer *t);
962 #endif /* __linux__ */
964 #endif /* _WIN32 */
966 /* Correlation between real and virtual time is always going to be
967 fairly approximate, so ignore small variation.
968 When the guest is idle real and virtual time will be aligned in
969 the IO wait loop. */
970 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
972 static void icount_adjust(void)
974 int64_t cur_time;
975 int64_t cur_icount;
976 int64_t delta;
977 static int64_t last_delta;
978 /* If the VM is not running, then do nothing. */
979 if (!vm_running)
980 return;
982 cur_time = cpu_get_clock();
983 cur_icount = qemu_get_clock(vm_clock);
984 delta = cur_icount - cur_time;
985 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
986 if (delta > 0
987 && last_delta + ICOUNT_WOBBLE < delta * 2
988 && icount_time_shift > 0) {
989 /* The guest is getting too far ahead. Slow time down. */
990 icount_time_shift--;
992 if (delta < 0
993 && last_delta - ICOUNT_WOBBLE > delta * 2
994 && icount_time_shift < MAX_ICOUNT_SHIFT) {
995 /* The guest is getting too far behind. Speed time up. */
996 icount_time_shift++;
998 last_delta = delta;
999 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1002 static void icount_adjust_rt(void * opaque)
1004 qemu_mod_timer(icount_rt_timer,
1005 qemu_get_clock(rt_clock) + 1000);
1006 icount_adjust();
1009 static void icount_adjust_vm(void * opaque)
1011 qemu_mod_timer(icount_vm_timer,
1012 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1013 icount_adjust();
1016 static void init_icount_adjust(void)
1018 /* Have both realtime and virtual time triggers for speed adjustment.
1019 The realtime trigger catches emulated time passing too slowly,
1020 the virtual time trigger catches emulated time passing too fast.
1021 Realtime triggers occur even when idle, so use them less frequently
1022 than VM triggers. */
1023 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1024 qemu_mod_timer(icount_rt_timer,
1025 qemu_get_clock(rt_clock) + 1000);
1026 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1027 qemu_mod_timer(icount_vm_timer,
1028 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1031 static struct qemu_alarm_timer alarm_timers[] = {
1032 #ifndef _WIN32
1033 #ifdef __linux__
1034 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1035 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1036 /* HPET - if available - is preferred */
1037 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1038 /* ...otherwise try RTC */
1039 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1040 #endif
1041 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1042 #else
1043 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1044 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1045 {"win32", 0, win32_start_timer,
1046 win32_stop_timer, NULL, &alarm_win32_data},
1047 #endif
1048 {NULL, }
1051 static void show_available_alarms(void)
1053 int i;
1055 printf("Available alarm timers, in order of precedence:\n");
1056 for (i = 0; alarm_timers[i].name; i++)
1057 printf("%s\n", alarm_timers[i].name);
1060 static void configure_alarms(char const *opt)
1062 int i;
1063 int cur = 0;
1064 int count = ARRAY_SIZE(alarm_timers) - 1;
1065 char *arg;
1066 char *name;
1067 struct qemu_alarm_timer tmp;
1069 if (!strcmp(opt, "?")) {
1070 show_available_alarms();
1071 exit(0);
1074 arg = strdup(opt);
1076 /* Reorder the array */
1077 name = strtok(arg, ",");
1078 while (name) {
1079 for (i = 0; i < count && alarm_timers[i].name; i++) {
1080 if (!strcmp(alarm_timers[i].name, name))
1081 break;
1084 if (i == count) {
1085 fprintf(stderr, "Unknown clock %s\n", name);
1086 goto next;
1089 if (i < cur)
1090 /* Ignore */
1091 goto next;
1093 /* Swap */
1094 tmp = alarm_timers[i];
1095 alarm_timers[i] = alarm_timers[cur];
1096 alarm_timers[cur] = tmp;
1098 cur++;
1099 next:
1100 name = strtok(NULL, ",");
1103 free(arg);
1105 if (cur) {
1106 /* Disable remaining timers */
1107 for (i = cur; i < count; i++)
1108 alarm_timers[i].name = NULL;
1109 } else {
1110 show_available_alarms();
1111 exit(1);
1115 QEMUClock *rt_clock;
1116 QEMUClock *vm_clock;
1118 static QEMUTimer *active_timers[2];
1120 static QEMUClock *qemu_new_clock(int type)
1122 QEMUClock *clock;
1123 clock = qemu_mallocz(sizeof(QEMUClock));
1124 if (!clock)
1125 return NULL;
1126 clock->type = type;
1127 return clock;
1130 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1132 QEMUTimer *ts;
1134 ts = qemu_mallocz(sizeof(QEMUTimer));
1135 ts->clock = clock;
1136 ts->cb = cb;
1137 ts->opaque = opaque;
1138 return ts;
1141 void qemu_free_timer(QEMUTimer *ts)
1143 qemu_free(ts);
1146 /* stop a timer, but do not dealloc it */
1147 void qemu_del_timer(QEMUTimer *ts)
1149 QEMUTimer **pt, *t;
1151 /* NOTE: this code must be signal safe because
1152 qemu_timer_expired() can be called from a signal. */
1153 pt = &active_timers[ts->clock->type];
1154 for(;;) {
1155 t = *pt;
1156 if (!t)
1157 break;
1158 if (t == ts) {
1159 *pt = t->next;
1160 break;
1162 pt = &t->next;
1166 /* modify the current timer so that it will be fired when current_time
1167 >= expire_time. The corresponding callback will be called. */
1168 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1170 QEMUTimer **pt, *t;
1172 qemu_del_timer(ts);
1174 /* add the timer in the sorted list */
1175 /* NOTE: this code must be signal safe because
1176 qemu_timer_expired() can be called from a signal. */
1177 pt = &active_timers[ts->clock->type];
1178 for(;;) {
1179 t = *pt;
1180 if (!t)
1181 break;
1182 if (t->expire_time > expire_time)
1183 break;
1184 pt = &t->next;
1186 ts->expire_time = expire_time;
1187 ts->next = *pt;
1188 *pt = ts;
1190 /* Rearm if necessary */
1191 if (pt == &active_timers[ts->clock->type]) {
1192 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1193 qemu_rearm_alarm_timer(alarm_timer);
1195 /* Interrupt execution to force deadline recalculation. */
1196 if (use_icount && cpu_single_env) {
1197 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1202 int qemu_timer_pending(QEMUTimer *ts)
1204 QEMUTimer *t;
1205 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1206 if (t == ts)
1207 return 1;
1209 return 0;
1212 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1214 if (!timer_head)
1215 return 0;
1216 return (timer_head->expire_time <= current_time);
1219 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1221 QEMUTimer *ts;
1223 for(;;) {
1224 ts = *ptimer_head;
1225 if (!ts || ts->expire_time > current_time)
1226 break;
1227 /* remove timer from the list before calling the callback */
1228 *ptimer_head = ts->next;
1229 ts->next = NULL;
1231 /* run the callback (the timer list can be modified) */
1232 ts->cb(ts->opaque);
1236 int64_t qemu_get_clock(QEMUClock *clock)
1238 switch(clock->type) {
1239 case QEMU_TIMER_REALTIME:
1240 return get_clock() / 1000000;
1241 default:
1242 case QEMU_TIMER_VIRTUAL:
1243 if (use_icount) {
1244 return cpu_get_icount();
1245 } else {
1246 return cpu_get_clock();
1251 static void init_timers(void)
1253 init_get_clock();
1254 ticks_per_sec = QEMU_TIMER_BASE;
1255 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1256 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1259 /* save a timer */
1260 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1262 uint64_t expire_time;
1264 if (qemu_timer_pending(ts)) {
1265 expire_time = ts->expire_time;
1266 } else {
1267 expire_time = -1;
1269 qemu_put_be64(f, expire_time);
1272 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1274 uint64_t expire_time;
1276 expire_time = qemu_get_be64(f);
1277 if (expire_time != -1) {
1278 qemu_mod_timer(ts, expire_time);
1279 } else {
1280 qemu_del_timer(ts);
1284 static void timer_save(QEMUFile *f, void *opaque)
1286 if (cpu_ticks_enabled) {
1287 hw_error("cannot save state if virtual timers are running");
1289 qemu_put_be64(f, cpu_ticks_offset);
1290 qemu_put_be64(f, ticks_per_sec);
1291 qemu_put_be64(f, cpu_clock_offset);
1294 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1296 if (version_id != 1 && version_id != 2)
1297 return -EINVAL;
1298 if (cpu_ticks_enabled) {
1299 return -EINVAL;
1301 cpu_ticks_offset=qemu_get_be64(f);
1302 ticks_per_sec=qemu_get_be64(f);
1303 if (version_id == 2) {
1304 cpu_clock_offset=qemu_get_be64(f);
1306 return 0;
1309 #ifdef _WIN32
1310 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1311 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1312 #else
1313 static void host_alarm_handler(int host_signum)
1314 #endif
1316 #if 0
1317 #define DISP_FREQ 1000
1319 static int64_t delta_min = INT64_MAX;
1320 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1321 static int count;
1322 ti = qemu_get_clock(vm_clock);
1323 if (last_clock != 0) {
1324 delta = ti - last_clock;
1325 if (delta < delta_min)
1326 delta_min = delta;
1327 if (delta > delta_max)
1328 delta_max = delta;
1329 delta_cum += delta;
1330 if (++count == DISP_FREQ) {
1331 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1332 muldiv64(delta_min, 1000000, ticks_per_sec),
1333 muldiv64(delta_max, 1000000, ticks_per_sec),
1334 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1335 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1336 count = 0;
1337 delta_min = INT64_MAX;
1338 delta_max = 0;
1339 delta_cum = 0;
1342 last_clock = ti;
1344 #endif
1345 if (1 ||
1346 alarm_has_dynticks(alarm_timer) ||
1347 (!use_icount &&
1348 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1349 qemu_get_clock(vm_clock))) ||
1350 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1351 qemu_get_clock(rt_clock))) {
1352 CPUState *env = next_cpu;
1354 #ifdef _WIN32
1355 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1356 SetEvent(data->host_alarm);
1357 #else
1358 static const char byte = 0;
1359 write(alarm_timer_wfd, &byte, sizeof(byte));
1360 #endif
1361 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1363 if (env) {
1364 /* stop the currently executing cpu because a timer occured */
1365 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1366 #ifdef USE_KQEMU
1367 if (env->kqemu_enabled) {
1368 kqemu_cpu_interrupt(env);
1370 #endif
1372 event_pending = 1;
1376 static int64_t qemu_next_deadline(void)
1378 int64_t delta;
1380 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1381 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1382 qemu_get_clock(vm_clock);
1383 } else {
1384 /* To avoid problems with overflow limit this to 2^32. */
1385 delta = INT32_MAX;
1388 if (delta < 0)
1389 delta = 0;
1391 return delta;
1394 #if defined(__linux__) || defined(_WIN32)
1395 static uint64_t qemu_next_deadline_dyntick(void)
1397 int64_t delta;
1398 int64_t rtdelta;
1400 if (use_icount)
1401 delta = INT32_MAX;
1402 else
1403 delta = (qemu_next_deadline() + 999) / 1000;
1405 if (active_timers[QEMU_TIMER_REALTIME]) {
1406 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1407 qemu_get_clock(rt_clock))*1000;
1408 if (rtdelta < delta)
1409 delta = rtdelta;
1412 if (delta < MIN_TIMER_REARM_US)
1413 delta = MIN_TIMER_REARM_US;
1415 return delta;
1417 #endif
1419 #ifndef _WIN32
1421 /* Sets a specific flag */
1422 static int fcntl_setfl(int fd, int flag)
1424 int flags;
1426 flags = fcntl(fd, F_GETFL);
1427 if (flags == -1)
1428 return -errno;
1430 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1431 return -errno;
1433 return 0;
1436 #if defined(__linux__)
1438 #define RTC_FREQ 1024
1440 static void enable_sigio_timer(int fd)
1442 struct sigaction act;
1444 /* timer signal */
1445 sigfillset(&act.sa_mask);
1446 act.sa_flags = 0;
1447 act.sa_handler = host_alarm_handler;
1449 sigaction(SIGIO, &act, NULL);
1450 fcntl_setfl(fd, O_ASYNC);
1451 fcntl(fd, F_SETOWN, getpid());
1454 static int hpet_start_timer(struct qemu_alarm_timer *t)
1456 struct hpet_info info;
1457 int r, fd;
1459 fd = open("/dev/hpet", O_RDONLY);
1460 if (fd < 0)
1461 return -1;
1463 /* Set frequency */
1464 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1465 if (r < 0) {
1466 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1467 "error, but for better emulation accuracy type:\n"
1468 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1469 goto fail;
1472 /* Check capabilities */
1473 r = ioctl(fd, HPET_INFO, &info);
1474 if (r < 0)
1475 goto fail;
1477 /* Enable periodic mode */
1478 r = ioctl(fd, HPET_EPI, 0);
1479 if (info.hi_flags && (r < 0))
1480 goto fail;
1482 /* Enable interrupt */
1483 r = ioctl(fd, HPET_IE_ON, 0);
1484 if (r < 0)
1485 goto fail;
1487 enable_sigio_timer(fd);
1488 t->priv = (void *)(long)fd;
1490 return 0;
1491 fail:
1492 close(fd);
1493 return -1;
1496 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1498 int fd = (long)t->priv;
1500 close(fd);
1503 static int rtc_start_timer(struct qemu_alarm_timer *t)
1505 int rtc_fd;
1506 unsigned long current_rtc_freq = 0;
1508 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1509 if (rtc_fd < 0)
1510 return -1;
1511 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1512 if (current_rtc_freq != RTC_FREQ &&
1513 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1514 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1515 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1516 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1517 goto fail;
1519 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1520 fail:
1521 close(rtc_fd);
1522 return -1;
1525 enable_sigio_timer(rtc_fd);
1527 t->priv = (void *)(long)rtc_fd;
1529 return 0;
1532 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1534 int rtc_fd = (long)t->priv;
1536 close(rtc_fd);
1539 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1541 struct sigevent ev;
1542 timer_t host_timer;
1543 struct sigaction act;
1545 sigfillset(&act.sa_mask);
1546 act.sa_flags = 0;
1547 act.sa_handler = host_alarm_handler;
1549 sigaction(SIGALRM, &act, NULL);
1551 ev.sigev_value.sival_int = 0;
1552 ev.sigev_notify = SIGEV_SIGNAL;
1553 ev.sigev_signo = SIGALRM;
1555 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1556 perror("timer_create");
1558 /* disable dynticks */
1559 fprintf(stderr, "Dynamic Ticks disabled\n");
1561 return -1;
1564 t->priv = (void *)(long)host_timer;
1566 return 0;
1569 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1571 timer_t host_timer = (timer_t)(long)t->priv;
1573 timer_delete(host_timer);
1576 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1578 timer_t host_timer = (timer_t)(long)t->priv;
1579 struct itimerspec timeout;
1580 int64_t nearest_delta_us = INT64_MAX;
1581 int64_t current_us;
1583 if (!active_timers[QEMU_TIMER_REALTIME] &&
1584 !active_timers[QEMU_TIMER_VIRTUAL])
1585 return;
1587 nearest_delta_us = qemu_next_deadline_dyntick();
1589 /* check whether a timer is already running */
1590 if (timer_gettime(host_timer, &timeout)) {
1591 perror("gettime");
1592 fprintf(stderr, "Internal timer error: aborting\n");
1593 exit(1);
1595 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1596 if (current_us && current_us <= nearest_delta_us)
1597 return;
1599 timeout.it_interval.tv_sec = 0;
1600 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1601 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1602 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1603 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1604 perror("settime");
1605 fprintf(stderr, "Internal timer error: aborting\n");
1606 exit(1);
1610 #endif /* defined(__linux__) */
1612 static int unix_start_timer(struct qemu_alarm_timer *t)
1614 struct sigaction act;
1615 struct itimerval itv;
1616 int err;
1618 /* timer signal */
1619 sigfillset(&act.sa_mask);
1620 act.sa_flags = 0;
1621 act.sa_handler = host_alarm_handler;
1623 sigaction(SIGALRM, &act, NULL);
1625 itv.it_interval.tv_sec = 0;
1626 /* for i386 kernel 2.6 to get 1 ms */
1627 itv.it_interval.tv_usec = 999;
1628 itv.it_value.tv_sec = 0;
1629 itv.it_value.tv_usec = 10 * 1000;
1631 err = setitimer(ITIMER_REAL, &itv, NULL);
1632 if (err)
1633 return -1;
1635 return 0;
1638 static void unix_stop_timer(struct qemu_alarm_timer *t)
1640 struct itimerval itv;
1642 memset(&itv, 0, sizeof(itv));
1643 setitimer(ITIMER_REAL, &itv, NULL);
1646 #endif /* !defined(_WIN32) */
1648 static void try_to_rearm_timer(void *opaque)
1650 struct qemu_alarm_timer *t = opaque;
1651 #ifndef _WIN32
1652 ssize_t len;
1654 /* Drain the notify pipe */
1655 do {
1656 char buffer[512];
1657 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1658 } while ((len == -1 && errno == EINTR) || len > 0);
1659 #endif
1661 if (t->flags & ALARM_FLAG_EXPIRED) {
1662 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1663 qemu_rearm_alarm_timer(alarm_timer);
1667 #ifdef _WIN32
1669 static int win32_start_timer(struct qemu_alarm_timer *t)
1671 TIMECAPS tc;
1672 struct qemu_alarm_win32 *data = t->priv;
1673 UINT flags;
1675 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1676 if (!data->host_alarm) {
1677 perror("Failed CreateEvent");
1678 return -1;
1681 memset(&tc, 0, sizeof(tc));
1682 timeGetDevCaps(&tc, sizeof(tc));
1684 if (data->period < tc.wPeriodMin)
1685 data->period = tc.wPeriodMin;
1687 timeBeginPeriod(data->period);
1689 flags = TIME_CALLBACK_FUNCTION;
1690 if (alarm_has_dynticks(t))
1691 flags |= TIME_ONESHOT;
1692 else
1693 flags |= TIME_PERIODIC;
1695 data->timerId = timeSetEvent(1, // interval (ms)
1696 data->period, // resolution
1697 host_alarm_handler, // function
1698 (DWORD)t, // parameter
1699 flags);
1701 if (!data->timerId) {
1702 perror("Failed to initialize win32 alarm timer");
1704 timeEndPeriod(data->period);
1705 CloseHandle(data->host_alarm);
1706 return -1;
1709 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1711 return 0;
1714 static void win32_stop_timer(struct qemu_alarm_timer *t)
1716 struct qemu_alarm_win32 *data = t->priv;
1718 timeKillEvent(data->timerId);
1719 timeEndPeriod(data->period);
1721 CloseHandle(data->host_alarm);
1724 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1726 struct qemu_alarm_win32 *data = t->priv;
1727 uint64_t nearest_delta_us;
1729 if (!active_timers[QEMU_TIMER_REALTIME] &&
1730 !active_timers[QEMU_TIMER_VIRTUAL])
1731 return;
1733 nearest_delta_us = qemu_next_deadline_dyntick();
1734 nearest_delta_us /= 1000;
1736 timeKillEvent(data->timerId);
1738 data->timerId = timeSetEvent(1,
1739 data->period,
1740 host_alarm_handler,
1741 (DWORD)t,
1742 TIME_ONESHOT | TIME_PERIODIC);
1744 if (!data->timerId) {
1745 perror("Failed to re-arm win32 alarm timer");
1747 timeEndPeriod(data->period);
1748 CloseHandle(data->host_alarm);
1749 exit(1);
1753 #endif /* _WIN32 */
1755 static int init_timer_alarm(void)
1757 struct qemu_alarm_timer *t = NULL;
1758 int i, err = -1;
1760 #ifndef _WIN32
1761 int fds[2];
1763 err = pipe(fds);
1764 if (err == -1)
1765 return -errno;
1767 err = fcntl_setfl(fds[0], O_NONBLOCK);
1768 if (err < 0)
1769 goto fail;
1771 err = fcntl_setfl(fds[1], O_NONBLOCK);
1772 if (err < 0)
1773 goto fail;
1775 alarm_timer_rfd = fds[0];
1776 alarm_timer_wfd = fds[1];
1777 #endif
1779 for (i = 0; alarm_timers[i].name; i++) {
1780 t = &alarm_timers[i];
1782 err = t->start(t);
1783 if (!err)
1784 break;
1787 if (err) {
1788 err = -ENOENT;
1789 goto fail;
1792 #ifndef _WIN32
1793 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1794 try_to_rearm_timer, NULL, t);
1795 #endif
1797 alarm_timer = t;
1799 return 0;
1801 fail:
1802 #ifndef _WIN32
1803 close(fds[0]);
1804 close(fds[1]);
1805 #endif
1806 return err;
1809 static void quit_timers(void)
1811 alarm_timer->stop(alarm_timer);
1812 alarm_timer = NULL;
1815 /***********************************************************/
1816 /* host time/date access */
1817 void qemu_get_timedate(struct tm *tm, int offset)
1819 time_t ti;
1820 struct tm *ret;
1822 time(&ti);
1823 ti += offset;
1824 if (rtc_date_offset == -1) {
1825 if (rtc_utc)
1826 ret = gmtime(&ti);
1827 else
1828 ret = localtime(&ti);
1829 } else {
1830 ti -= rtc_date_offset;
1831 ret = gmtime(&ti);
1834 memcpy(tm, ret, sizeof(struct tm));
1837 int qemu_timedate_diff(struct tm *tm)
1839 time_t seconds;
1841 if (rtc_date_offset == -1)
1842 if (rtc_utc)
1843 seconds = mktimegm(tm);
1844 else
1845 seconds = mktime(tm);
1846 else
1847 seconds = mktimegm(tm) + rtc_date_offset;
1849 return seconds - time(NULL);
1852 #ifdef _WIN32
1853 static void socket_cleanup(void)
1855 WSACleanup();
1858 static int socket_init(void)
1860 WSADATA Data;
1861 int ret, err;
1863 ret = WSAStartup(MAKEWORD(2,2), &Data);
1864 if (ret != 0) {
1865 err = WSAGetLastError();
1866 fprintf(stderr, "WSAStartup: %d\n", err);
1867 return -1;
1869 atexit(socket_cleanup);
1870 return 0;
1872 #endif
1874 const char *get_opt_name(char *buf, int buf_size, const char *p)
1876 char *q;
1878 q = buf;
1879 while (*p != '\0' && *p != '=') {
1880 if (q && (q - buf) < buf_size - 1)
1881 *q++ = *p;
1882 p++;
1884 if (q)
1885 *q = '\0';
1887 return p;
1890 const char *get_opt_value(char *buf, int buf_size, const char *p)
1892 char *q;
1894 q = buf;
1895 while (*p != '\0') {
1896 if (*p == ',') {
1897 if (*(p + 1) != ',')
1898 break;
1899 p++;
1901 if (q && (q - buf) < buf_size - 1)
1902 *q++ = *p;
1903 p++;
1905 if (q)
1906 *q = '\0';
1908 return p;
1911 int get_param_value(char *buf, int buf_size,
1912 const char *tag, const char *str)
1914 const char *p;
1915 char option[128];
1917 p = str;
1918 for(;;) {
1919 p = get_opt_name(option, sizeof(option), p);
1920 if (*p != '=')
1921 break;
1922 p++;
1923 if (!strcmp(tag, option)) {
1924 (void)get_opt_value(buf, buf_size, p);
1925 return strlen(buf);
1926 } else {
1927 p = get_opt_value(NULL, 0, p);
1929 if (*p != ',')
1930 break;
1931 p++;
1933 return 0;
1936 int check_params(char *buf, int buf_size,
1937 const char * const *params, const char *str)
1939 const char *p;
1940 int i;
1942 p = str;
1943 for(;;) {
1944 p = get_opt_name(buf, buf_size, p);
1945 if (*p != '=')
1946 return -1;
1947 p++;
1948 for(i = 0; params[i] != NULL; i++)
1949 if (!strcmp(params[i], buf))
1950 break;
1951 if (params[i] == NULL)
1952 return -1;
1953 p = get_opt_value(NULL, 0, p);
1954 if (*p != ',')
1955 break;
1956 p++;
1958 return 0;
1961 /***********************************************************/
1962 /* Bluetooth support */
1963 static int nb_hcis;
1964 static int cur_hci;
1965 static struct HCIInfo *hci_table[MAX_NICS];
1967 static struct bt_vlan_s {
1968 struct bt_scatternet_s net;
1969 int id;
1970 struct bt_vlan_s *next;
1971 } *first_bt_vlan;
1973 /* find or alloc a new bluetooth "VLAN" */
1974 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1976 struct bt_vlan_s **pvlan, *vlan;
1977 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1978 if (vlan->id == id)
1979 return &vlan->net;
1981 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1982 vlan->id = id;
1983 pvlan = &first_bt_vlan;
1984 while (*pvlan != NULL)
1985 pvlan = &(*pvlan)->next;
1986 *pvlan = vlan;
1987 return &vlan->net;
1990 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1994 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1996 return -ENOTSUP;
1999 static struct HCIInfo null_hci = {
2000 .cmd_send = null_hci_send,
2001 .sco_send = null_hci_send,
2002 .acl_send = null_hci_send,
2003 .bdaddr_set = null_hci_addr_set,
2006 struct HCIInfo *qemu_next_hci(void)
2008 if (cur_hci == nb_hcis)
2009 return &null_hci;
2011 return hci_table[cur_hci++];
2014 static struct HCIInfo *hci_init(const char *str)
2016 char *endp;
2017 struct bt_scatternet_s *vlan = 0;
2019 if (!strcmp(str, "null"))
2020 /* null */
2021 return &null_hci;
2022 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2023 /* host[:hciN] */
2024 return bt_host_hci(str[4] ? str + 5 : "hci0");
2025 else if (!strncmp(str, "hci", 3)) {
2026 /* hci[,vlan=n] */
2027 if (str[3]) {
2028 if (!strncmp(str + 3, ",vlan=", 6)) {
2029 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2030 if (*endp)
2031 vlan = 0;
2033 } else
2034 vlan = qemu_find_bt_vlan(0);
2035 if (vlan)
2036 return bt_new_hci(vlan);
2039 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2041 return 0;
2044 static int bt_hci_parse(const char *str)
2046 struct HCIInfo *hci;
2047 bdaddr_t bdaddr;
2049 if (nb_hcis >= MAX_NICS) {
2050 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2051 return -1;
2054 hci = hci_init(str);
2055 if (!hci)
2056 return -1;
2058 bdaddr.b[0] = 0x52;
2059 bdaddr.b[1] = 0x54;
2060 bdaddr.b[2] = 0x00;
2061 bdaddr.b[3] = 0x12;
2062 bdaddr.b[4] = 0x34;
2063 bdaddr.b[5] = 0x56 + nb_hcis;
2064 hci->bdaddr_set(hci, bdaddr.b);
2066 hci_table[nb_hcis++] = hci;
2068 return 0;
2071 static void bt_vhci_add(int vlan_id)
2073 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2075 if (!vlan->slave)
2076 fprintf(stderr, "qemu: warning: adding a VHCI to "
2077 "an empty scatternet %i\n", vlan_id);
2079 bt_vhci_init(bt_new_hci(vlan));
2082 static struct bt_device_s *bt_device_add(const char *opt)
2084 struct bt_scatternet_s *vlan;
2085 int vlan_id = 0;
2086 char *endp = strstr(opt, ",vlan=");
2087 int len = (endp ? endp - opt : strlen(opt)) + 1;
2088 char devname[10];
2090 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2092 if (endp) {
2093 vlan_id = strtol(endp + 6, &endp, 0);
2094 if (*endp) {
2095 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2096 return 0;
2100 vlan = qemu_find_bt_vlan(vlan_id);
2102 if (!vlan->slave)
2103 fprintf(stderr, "qemu: warning: adding a slave device to "
2104 "an empty scatternet %i\n", vlan_id);
2106 if (!strcmp(devname, "keyboard"))
2107 return bt_keyboard_init(vlan);
2109 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2110 return 0;
2113 static int bt_parse(const char *opt)
2115 const char *endp, *p;
2116 int vlan;
2118 if (strstart(opt, "hci", &endp)) {
2119 if (!*endp || *endp == ',') {
2120 if (*endp)
2121 if (!strstart(endp, ",vlan=", 0))
2122 opt = endp + 1;
2124 return bt_hci_parse(opt);
2126 } else if (strstart(opt, "vhci", &endp)) {
2127 if (!*endp || *endp == ',') {
2128 if (*endp) {
2129 if (strstart(endp, ",vlan=", &p)) {
2130 vlan = strtol(p, (char **) &endp, 0);
2131 if (*endp) {
2132 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2133 return 1;
2135 } else {
2136 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2137 return 1;
2139 } else
2140 vlan = 0;
2142 bt_vhci_add(vlan);
2143 return 0;
2145 } else if (strstart(opt, "device:", &endp))
2146 return !bt_device_add(endp);
2148 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2149 return 1;
2152 /***********************************************************/
2153 /* QEMU Block devices */
2155 #define HD_ALIAS "index=%d,media=disk"
2156 #ifdef TARGET_PPC
2157 #define CDROM_ALIAS "index=1,media=cdrom"
2158 #else
2159 #define CDROM_ALIAS "index=2,media=cdrom"
2160 #endif
2161 #define FD_ALIAS "index=%d,if=floppy"
2162 #define PFLASH_ALIAS "if=pflash"
2163 #define MTD_ALIAS "if=mtd"
2164 #define SD_ALIAS "index=0,if=sd"
2166 static int drive_opt_get_free_idx(void)
2168 int index;
2170 for (index = 0; index < MAX_DRIVES; index++)
2171 if (!drives_opt[index].used) {
2172 drives_opt[index].used = 1;
2173 return index;
2176 return -1;
2179 static int drive_get_free_idx(void)
2181 int index;
2183 for (index = 0; index < MAX_DRIVES; index++)
2184 if (!drives_table[index].used) {
2185 drives_table[index].used = 1;
2186 return index;
2189 return -1;
2192 int drive_add(const char *file, const char *fmt, ...)
2194 va_list ap;
2195 int index = drive_opt_get_free_idx();
2197 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2198 fprintf(stderr, "qemu: too many drives\n");
2199 return -1;
2202 drives_opt[index].file = file;
2203 va_start(ap, fmt);
2204 vsnprintf(drives_opt[index].opt,
2205 sizeof(drives_opt[0].opt), fmt, ap);
2206 va_end(ap);
2208 nb_drives_opt++;
2209 return index;
2212 void drive_remove(int index)
2214 drives_opt[index].used = 0;
2215 nb_drives_opt--;
2218 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2220 int index;
2222 /* seek interface, bus and unit */
2224 for (index = 0; index < MAX_DRIVES; index++)
2225 if (drives_table[index].type == type &&
2226 drives_table[index].bus == bus &&
2227 drives_table[index].unit == unit &&
2228 drives_table[index].used)
2229 return index;
2231 return -1;
2234 int drive_get_max_bus(BlockInterfaceType type)
2236 int max_bus;
2237 int index;
2239 max_bus = -1;
2240 for (index = 0; index < nb_drives; index++) {
2241 if(drives_table[index].type == type &&
2242 drives_table[index].bus > max_bus)
2243 max_bus = drives_table[index].bus;
2245 return max_bus;
2248 const char *drive_get_serial(BlockDriverState *bdrv)
2250 int index;
2252 for (index = 0; index < nb_drives; index++)
2253 if (drives_table[index].bdrv == bdrv)
2254 return drives_table[index].serial;
2256 return "\0";
2259 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2261 int index;
2263 for (index = 0; index < nb_drives; index++)
2264 if (drives_table[index].bdrv == bdrv)
2265 return drives_table[index].onerror;
2267 return BLOCK_ERR_REPORT;
2270 static void bdrv_format_print(void *opaque, const char *name)
2272 fprintf(stderr, " %s", name);
2275 void drive_uninit(BlockDriverState *bdrv)
2277 int i;
2279 for (i = 0; i < MAX_DRIVES; i++)
2280 if (drives_table[i].bdrv == bdrv) {
2281 drives_table[i].bdrv = NULL;
2282 drives_table[i].used = 0;
2283 drive_remove(drives_table[i].drive_opt_idx);
2284 nb_drives--;
2285 break;
2289 int drive_init(struct drive_opt *arg, int snapshot,
2290 QEMUMachine *machine)
2292 char buf[128];
2293 char file[1024];
2294 char devname[128];
2295 char serial[21];
2296 const char *mediastr = "";
2297 BlockInterfaceType type;
2298 enum { MEDIA_DISK, MEDIA_CDROM } media;
2299 int bus_id, unit_id;
2300 int cyls, heads, secs, translation;
2301 BlockDriverState *bdrv;
2302 BlockDriver *drv = NULL;
2303 int max_devs;
2304 int index;
2305 int cache;
2306 int bdrv_flags, onerror;
2307 int drives_table_idx;
2308 char *str = arg->opt;
2309 static const char * const params[] = { "bus", "unit", "if", "index",
2310 "cyls", "heads", "secs", "trans",
2311 "media", "snapshot", "file",
2312 "cache", "format", "serial", "werror",
2313 "boot", NULL };
2315 if (check_params(buf, sizeof(buf), params, str) < 0) {
2316 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2317 buf, str);
2318 return -1;
2321 file[0] = 0;
2322 cyls = heads = secs = 0;
2323 bus_id = 0;
2324 unit_id = -1;
2325 translation = BIOS_ATA_TRANSLATION_AUTO;
2326 index = -1;
2327 cache = 3;
2329 if (machine->use_scsi) {
2330 type = IF_SCSI;
2331 max_devs = MAX_SCSI_DEVS;
2332 pstrcpy(devname, sizeof(devname), "scsi");
2333 } else {
2334 type = IF_IDE;
2335 max_devs = MAX_IDE_DEVS;
2336 pstrcpy(devname, sizeof(devname), "ide");
2338 media = MEDIA_DISK;
2340 /* extract parameters */
2342 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2343 bus_id = strtol(buf, NULL, 0);
2344 if (bus_id < 0) {
2345 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2346 return -1;
2350 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2351 unit_id = strtol(buf, NULL, 0);
2352 if (unit_id < 0) {
2353 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2354 return -1;
2358 if (get_param_value(buf, sizeof(buf), "if", str)) {
2359 pstrcpy(devname, sizeof(devname), buf);
2360 if (!strcmp(buf, "ide")) {
2361 type = IF_IDE;
2362 max_devs = MAX_IDE_DEVS;
2363 } else if (!strcmp(buf, "scsi")) {
2364 type = IF_SCSI;
2365 max_devs = MAX_SCSI_DEVS;
2366 } else if (!strcmp(buf, "floppy")) {
2367 type = IF_FLOPPY;
2368 max_devs = 0;
2369 } else if (!strcmp(buf, "pflash")) {
2370 type = IF_PFLASH;
2371 max_devs = 0;
2372 } else if (!strcmp(buf, "mtd")) {
2373 type = IF_MTD;
2374 max_devs = 0;
2375 } else if (!strcmp(buf, "sd")) {
2376 type = IF_SD;
2377 max_devs = 0;
2378 } else if (!strcmp(buf, "virtio")) {
2379 type = IF_VIRTIO;
2380 max_devs = 0;
2381 } else {
2382 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2383 return -1;
2387 if (get_param_value(buf, sizeof(buf), "index", str)) {
2388 index = strtol(buf, NULL, 0);
2389 if (index < 0) {
2390 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2391 return -1;
2395 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2396 cyls = strtol(buf, NULL, 0);
2399 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2400 heads = strtol(buf, NULL, 0);
2403 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2404 secs = strtol(buf, NULL, 0);
2407 if (cyls || heads || secs) {
2408 if (cyls < 1 || cyls > 16383) {
2409 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2410 return -1;
2412 if (heads < 1 || heads > 16) {
2413 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2414 return -1;
2416 if (secs < 1 || secs > 63) {
2417 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2418 return -1;
2422 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2423 if (!cyls) {
2424 fprintf(stderr,
2425 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2426 str);
2427 return -1;
2429 if (!strcmp(buf, "none"))
2430 translation = BIOS_ATA_TRANSLATION_NONE;
2431 else if (!strcmp(buf, "lba"))
2432 translation = BIOS_ATA_TRANSLATION_LBA;
2433 else if (!strcmp(buf, "auto"))
2434 translation = BIOS_ATA_TRANSLATION_AUTO;
2435 else {
2436 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2437 return -1;
2441 if (get_param_value(buf, sizeof(buf), "media", str)) {
2442 if (!strcmp(buf, "disk")) {
2443 media = MEDIA_DISK;
2444 } else if (!strcmp(buf, "cdrom")) {
2445 if (cyls || secs || heads) {
2446 fprintf(stderr,
2447 "qemu: '%s' invalid physical CHS format\n", str);
2448 return -1;
2450 media = MEDIA_CDROM;
2451 } else {
2452 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2453 return -1;
2457 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2458 if (!strcmp(buf, "on"))
2459 snapshot = 1;
2460 else if (!strcmp(buf, "off"))
2461 snapshot = 0;
2462 else {
2463 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2464 return -1;
2468 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2469 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2470 cache = 0;
2471 else if (!strcmp(buf, "writethrough"))
2472 cache = 1;
2473 else if (!strcmp(buf, "writeback"))
2474 cache = 2;
2475 else {
2476 fprintf(stderr, "qemu: invalid cache option\n");
2477 return -1;
2481 if (get_param_value(buf, sizeof(buf), "format", str)) {
2482 if (strcmp(buf, "?") == 0) {
2483 fprintf(stderr, "qemu: Supported formats:");
2484 bdrv_iterate_format(bdrv_format_print, NULL);
2485 fprintf(stderr, "\n");
2486 return -1;
2488 drv = bdrv_find_format(buf);
2489 if (!drv) {
2490 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2491 return -1;
2495 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2496 if (!strcmp(buf, "on")) {
2497 if (extboot_drive != -1) {
2498 fprintf(stderr, "qemu: two bootable drives specified\n");
2499 return -1;
2501 extboot_drive = nb_drives;
2502 } else if (strcmp(buf, "off")) {
2503 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2504 return -1;
2508 if (arg->file == NULL)
2509 get_param_value(file, sizeof(file), "file", str);
2510 else
2511 pstrcpy(file, sizeof(file), arg->file);
2513 if (!get_param_value(serial, sizeof(serial), "serial", str))
2514 memset(serial, 0, sizeof(serial));
2516 onerror = BLOCK_ERR_REPORT;
2517 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2518 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2519 fprintf(stderr, "werror is no supported by this format\n");
2520 return -1;
2522 if (!strcmp(buf, "ignore"))
2523 onerror = BLOCK_ERR_IGNORE;
2524 else if (!strcmp(buf, "enospc"))
2525 onerror = BLOCK_ERR_STOP_ENOSPC;
2526 else if (!strcmp(buf, "stop"))
2527 onerror = BLOCK_ERR_STOP_ANY;
2528 else if (!strcmp(buf, "report"))
2529 onerror = BLOCK_ERR_REPORT;
2530 else {
2531 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2532 return -1;
2536 /* compute bus and unit according index */
2538 if (index != -1) {
2539 if (bus_id != 0 || unit_id != -1) {
2540 fprintf(stderr,
2541 "qemu: '%s' index cannot be used with bus and unit\n", str);
2542 return -1;
2544 if (max_devs == 0)
2546 unit_id = index;
2547 bus_id = 0;
2548 } else {
2549 unit_id = index % max_devs;
2550 bus_id = index / max_devs;
2554 /* if user doesn't specify a unit_id,
2555 * try to find the first free
2558 if (unit_id == -1) {
2559 unit_id = 0;
2560 while (drive_get_index(type, bus_id, unit_id) != -1) {
2561 unit_id++;
2562 if (max_devs && unit_id >= max_devs) {
2563 unit_id -= max_devs;
2564 bus_id++;
2569 /* check unit id */
2571 if (max_devs && unit_id >= max_devs) {
2572 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2573 str, unit_id, max_devs - 1);
2574 return -1;
2578 * ignore multiple definitions
2581 if (drive_get_index(type, bus_id, unit_id) != -1)
2582 return -2;
2584 /* init */
2586 if (type == IF_IDE || type == IF_SCSI)
2587 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2588 if (max_devs)
2589 snprintf(buf, sizeof(buf), "%s%i%s%i",
2590 devname, bus_id, mediastr, unit_id);
2591 else
2592 snprintf(buf, sizeof(buf), "%s%s%i",
2593 devname, mediastr, unit_id);
2594 bdrv = bdrv_new(buf);
2595 drives_table_idx = drive_get_free_idx();
2596 drives_table[drives_table_idx].bdrv = bdrv;
2597 drives_table[drives_table_idx].type = type;
2598 drives_table[drives_table_idx].bus = bus_id;
2599 drives_table[drives_table_idx].unit = unit_id;
2600 drives_table[drives_table_idx].onerror = onerror;
2601 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2602 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2603 nb_drives++;
2605 switch(type) {
2606 case IF_IDE:
2607 case IF_SCSI:
2608 switch(media) {
2609 case MEDIA_DISK:
2610 if (cyls != 0) {
2611 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2612 bdrv_set_translation_hint(bdrv, translation);
2614 break;
2615 case MEDIA_CDROM:
2616 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2617 break;
2619 break;
2620 case IF_SD:
2621 /* FIXME: This isn't really a floppy, but it's a reasonable
2622 approximation. */
2623 case IF_FLOPPY:
2624 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2625 break;
2626 case IF_PFLASH:
2627 case IF_MTD:
2628 case IF_VIRTIO:
2629 break;
2631 if (!file[0])
2632 return -2;
2633 bdrv_flags = 0;
2634 if (snapshot) {
2635 bdrv_flags |= BDRV_O_SNAPSHOT;
2636 cache = 2; /* always use write-back with snapshot */
2638 if (cache == 0) /* no caching */
2639 bdrv_flags |= BDRV_O_NOCACHE;
2640 else if (cache == 2) /* write-back */
2641 bdrv_flags |= BDRV_O_CACHE_WB;
2642 else if (cache == 3) /* not specified */
2643 bdrv_flags |= BDRV_O_CACHE_DEF;
2644 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2645 fprintf(stderr, "qemu: could not open disk image %s\n",
2646 file);
2647 return -1;
2649 return drives_table_idx;
2652 /***********************************************************/
2653 /* USB devices */
2655 static USBPort *used_usb_ports;
2656 static USBPort *free_usb_ports;
2658 /* ??? Maybe change this to register a hub to keep track of the topology. */
2659 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2660 usb_attachfn attach)
2662 port->opaque = opaque;
2663 port->index = index;
2664 port->attach = attach;
2665 port->next = free_usb_ports;
2666 free_usb_ports = port;
2669 int usb_device_add_dev(USBDevice *dev)
2671 USBPort *port;
2673 /* Find a USB port to add the device to. */
2674 port = free_usb_ports;
2675 if (!port->next) {
2676 USBDevice *hub;
2678 /* Create a new hub and chain it on. */
2679 free_usb_ports = NULL;
2680 port->next = used_usb_ports;
2681 used_usb_ports = port;
2683 hub = usb_hub_init(VM_USB_HUB_SIZE);
2684 usb_attach(port, hub);
2685 port = free_usb_ports;
2688 free_usb_ports = port->next;
2689 port->next = used_usb_ports;
2690 used_usb_ports = port;
2691 usb_attach(port, dev);
2692 return 0;
2695 static int usb_device_add(const char *devname)
2697 const char *p;
2698 USBDevice *dev;
2700 if (!free_usb_ports)
2701 return -1;
2703 if (strstart(devname, "host:", &p)) {
2704 dev = usb_host_device_open(p);
2705 } else if (!strcmp(devname, "mouse")) {
2706 dev = usb_mouse_init();
2707 } else if (!strcmp(devname, "tablet")) {
2708 dev = usb_tablet_init();
2709 } else if (!strcmp(devname, "keyboard")) {
2710 dev = usb_keyboard_init();
2711 } else if (strstart(devname, "disk:", &p)) {
2712 dev = usb_msd_init(p);
2713 } else if (!strcmp(devname, "wacom-tablet")) {
2714 dev = usb_wacom_init();
2715 } else if (strstart(devname, "serial:", &p)) {
2716 dev = usb_serial_init(p);
2717 #ifdef CONFIG_BRLAPI
2718 } else if (!strcmp(devname, "braille")) {
2719 dev = usb_baum_init();
2720 #endif
2721 } else if (strstart(devname, "net:", &p)) {
2722 int nic = nb_nics;
2724 if (net_client_init("nic", p) < 0)
2725 return -1;
2726 nd_table[nic].model = "usb";
2727 dev = usb_net_init(&nd_table[nic]);
2728 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2729 dev = usb_bt_init(devname[2] ? hci_init(p) :
2730 bt_new_hci(qemu_find_bt_vlan(0)));
2731 } else {
2732 return -1;
2734 if (!dev)
2735 return -1;
2737 return usb_device_add_dev(dev);
2740 int usb_device_del_addr(int bus_num, int addr)
2742 USBPort *port;
2743 USBPort **lastp;
2744 USBDevice *dev;
2746 if (!used_usb_ports)
2747 return -1;
2749 if (bus_num != 0)
2750 return -1;
2752 lastp = &used_usb_ports;
2753 port = used_usb_ports;
2754 while (port && port->dev->addr != addr) {
2755 lastp = &port->next;
2756 port = port->next;
2759 if (!port)
2760 return -1;
2762 dev = port->dev;
2763 *lastp = port->next;
2764 usb_attach(port, NULL);
2765 dev->handle_destroy(dev);
2766 port->next = free_usb_ports;
2767 free_usb_ports = port;
2768 return 0;
2771 static int usb_device_del(const char *devname)
2773 int bus_num, addr;
2774 const char *p;
2776 if (strstart(devname, "host:", &p))
2777 return usb_host_device_close(p);
2779 if (!used_usb_ports)
2780 return -1;
2782 p = strchr(devname, '.');
2783 if (!p)
2784 return -1;
2785 bus_num = strtoul(devname, NULL, 0);
2786 addr = strtoul(p + 1, NULL, 0);
2788 return usb_device_del_addr(bus_num, addr);
2791 void do_usb_add(const char *devname)
2793 usb_device_add(devname);
2796 void do_usb_del(const char *devname)
2798 usb_device_del(devname);
2801 void usb_info(void)
2803 USBDevice *dev;
2804 USBPort *port;
2805 const char *speed_str;
2807 if (!usb_enabled) {
2808 term_printf("USB support not enabled\n");
2809 return;
2812 for (port = used_usb_ports; port; port = port->next) {
2813 dev = port->dev;
2814 if (!dev)
2815 continue;
2816 switch(dev->speed) {
2817 case USB_SPEED_LOW:
2818 speed_str = "1.5";
2819 break;
2820 case USB_SPEED_FULL:
2821 speed_str = "12";
2822 break;
2823 case USB_SPEED_HIGH:
2824 speed_str = "480";
2825 break;
2826 default:
2827 speed_str = "?";
2828 break;
2830 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2831 0, dev->addr, speed_str, dev->devname);
2835 /***********************************************************/
2836 /* PCMCIA/Cardbus */
2838 static struct pcmcia_socket_entry_s {
2839 struct pcmcia_socket_s *socket;
2840 struct pcmcia_socket_entry_s *next;
2841 } *pcmcia_sockets = 0;
2843 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2845 struct pcmcia_socket_entry_s *entry;
2847 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2848 entry->socket = socket;
2849 entry->next = pcmcia_sockets;
2850 pcmcia_sockets = entry;
2853 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2855 struct pcmcia_socket_entry_s *entry, **ptr;
2857 ptr = &pcmcia_sockets;
2858 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2859 if (entry->socket == socket) {
2860 *ptr = entry->next;
2861 qemu_free(entry);
2865 void pcmcia_info(void)
2867 struct pcmcia_socket_entry_s *iter;
2868 if (!pcmcia_sockets)
2869 term_printf("No PCMCIA sockets\n");
2871 for (iter = pcmcia_sockets; iter; iter = iter->next)
2872 term_printf("%s: %s\n", iter->socket->slot_string,
2873 iter->socket->attached ? iter->socket->card_string :
2874 "Empty");
2877 /***********************************************************/
2878 /* register display */
2880 void register_displaystate(DisplayState *ds)
2882 DisplayState **s;
2883 s = &display_state;
2884 while (*s != NULL)
2885 s = &(*s)->next;
2886 ds->next = NULL;
2887 *s = ds;
2890 DisplayState *get_displaystate(void)
2892 return display_state;
2895 /* dumb display */
2897 static void dumb_display_init(void)
2899 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2900 if (ds == NULL) {
2901 fprintf(stderr, "dumb_display_init: DisplayState allocation failed\n");
2902 exit(1);
2904 ds->surface = qemu_create_displaysurface(640, 480, 32, 640 * 4);
2905 register_displaystate(ds);
2908 /***********************************************************/
2909 /* I/O handling */
2911 #define MAX_IO_HANDLERS 64
2913 typedef struct IOHandlerRecord {
2914 int fd;
2915 IOCanRWHandler *fd_read_poll;
2916 IOHandler *fd_read;
2917 IOHandler *fd_write;
2918 int deleted;
2919 void *opaque;
2920 /* temporary data */
2921 struct pollfd *ufd;
2922 struct IOHandlerRecord *next;
2923 } IOHandlerRecord;
2925 static IOHandlerRecord *first_io_handler;
2927 /* XXX: fd_read_poll should be suppressed, but an API change is
2928 necessary in the character devices to suppress fd_can_read(). */
2929 int qemu_set_fd_handler2(int fd,
2930 IOCanRWHandler *fd_read_poll,
2931 IOHandler *fd_read,
2932 IOHandler *fd_write,
2933 void *opaque)
2935 IOHandlerRecord **pioh, *ioh;
2937 if (!fd_read && !fd_write) {
2938 pioh = &first_io_handler;
2939 for(;;) {
2940 ioh = *pioh;
2941 if (ioh == NULL)
2942 break;
2943 if (ioh->fd == fd) {
2944 ioh->deleted = 1;
2945 break;
2947 pioh = &ioh->next;
2949 } else {
2950 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2951 if (ioh->fd == fd)
2952 goto found;
2954 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2955 if (!ioh)
2956 return -1;
2957 ioh->next = first_io_handler;
2958 first_io_handler = ioh;
2959 found:
2960 ioh->fd = fd;
2961 ioh->fd_read_poll = fd_read_poll;
2962 ioh->fd_read = fd_read;
2963 ioh->fd_write = fd_write;
2964 ioh->opaque = opaque;
2965 ioh->deleted = 0;
2967 main_loop_break();
2968 return 0;
2971 int qemu_set_fd_handler(int fd,
2972 IOHandler *fd_read,
2973 IOHandler *fd_write,
2974 void *opaque)
2976 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2979 #ifdef _WIN32
2980 /***********************************************************/
2981 /* Polling handling */
2983 typedef struct PollingEntry {
2984 PollingFunc *func;
2985 void *opaque;
2986 struct PollingEntry *next;
2987 } PollingEntry;
2989 static PollingEntry *first_polling_entry;
2991 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2993 PollingEntry **ppe, *pe;
2994 pe = qemu_mallocz(sizeof(PollingEntry));
2995 if (!pe)
2996 return -1;
2997 pe->func = func;
2998 pe->opaque = opaque;
2999 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3000 *ppe = pe;
3001 return 0;
3004 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3006 PollingEntry **ppe, *pe;
3007 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3008 pe = *ppe;
3009 if (pe->func == func && pe->opaque == opaque) {
3010 *ppe = pe->next;
3011 qemu_free(pe);
3012 break;
3017 /***********************************************************/
3018 /* Wait objects support */
3019 typedef struct WaitObjects {
3020 int num;
3021 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3022 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3023 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3024 } WaitObjects;
3026 static WaitObjects wait_objects = {0};
3028 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3030 WaitObjects *w = &wait_objects;
3032 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3033 return -1;
3034 w->events[w->num] = handle;
3035 w->func[w->num] = func;
3036 w->opaque[w->num] = opaque;
3037 w->num++;
3038 return 0;
3041 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3043 int i, found;
3044 WaitObjects *w = &wait_objects;
3046 found = 0;
3047 for (i = 0; i < w->num; i++) {
3048 if (w->events[i] == handle)
3049 found = 1;
3050 if (found) {
3051 w->events[i] = w->events[i + 1];
3052 w->func[i] = w->func[i + 1];
3053 w->opaque[i] = w->opaque[i + 1];
3056 if (found)
3057 w->num--;
3059 #endif
3061 /***********************************************************/
3062 /* ram save/restore */
3064 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3066 int v;
3068 v = qemu_get_byte(f);
3069 switch(v) {
3070 case 0:
3071 if (qemu_get_buffer(f, buf, len) != len)
3072 return -EIO;
3073 break;
3074 case 1:
3075 v = qemu_get_byte(f);
3076 memset(buf, v, len);
3077 break;
3078 default:
3079 return -EINVAL;
3082 if (qemu_file_has_error(f))
3083 return -EIO;
3085 return 0;
3088 static int ram_load_v1(QEMUFile *f, void *opaque)
3090 int ret;
3091 ram_addr_t i;
3093 if (qemu_get_be32(f) != phys_ram_size)
3094 return -EINVAL;
3095 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3096 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3097 continue;
3098 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3099 if (ret)
3100 return ret;
3102 return 0;
3105 #define BDRV_HASH_BLOCK_SIZE 1024
3106 #define IOBUF_SIZE 4096
3107 #define RAM_CBLOCK_MAGIC 0xfabe
3109 typedef struct RamDecompressState {
3110 z_stream zstream;
3111 QEMUFile *f;
3112 uint8_t buf[IOBUF_SIZE];
3113 } RamDecompressState;
3115 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3117 int ret;
3118 memset(s, 0, sizeof(*s));
3119 s->f = f;
3120 ret = inflateInit(&s->zstream);
3121 if (ret != Z_OK)
3122 return -1;
3123 return 0;
3126 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3128 int ret, clen;
3130 s->zstream.avail_out = len;
3131 s->zstream.next_out = buf;
3132 while (s->zstream.avail_out > 0) {
3133 if (s->zstream.avail_in == 0) {
3134 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3135 return -1;
3136 clen = qemu_get_be16(s->f);
3137 if (clen > IOBUF_SIZE)
3138 return -1;
3139 qemu_get_buffer(s->f, s->buf, clen);
3140 s->zstream.avail_in = clen;
3141 s->zstream.next_in = s->buf;
3143 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3144 if (ret != Z_OK && ret != Z_STREAM_END) {
3145 return -1;
3148 return 0;
3151 static void ram_decompress_close(RamDecompressState *s)
3153 inflateEnd(&s->zstream);
3156 #define RAM_SAVE_FLAG_FULL 0x01
3157 #define RAM_SAVE_FLAG_COMPRESS 0x02
3158 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3159 #define RAM_SAVE_FLAG_PAGE 0x08
3160 #define RAM_SAVE_FLAG_EOS 0x10
3162 static int is_dup_page(uint8_t *page, uint8_t ch)
3164 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3165 uint32_t *array = (uint32_t *)page;
3166 int i;
3168 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3169 if (array[i] != val)
3170 return 0;
3173 return 1;
3176 static int ram_save_block(QEMUFile *f)
3178 static ram_addr_t current_addr = 0;
3179 ram_addr_t saved_addr = current_addr;
3180 ram_addr_t addr = 0;
3181 int found = 0;
3183 while (addr < phys_ram_size) {
3184 if (kvm_enabled() && current_addr == 0)
3185 kvm_update_dirty_pages_log(); /* FIXME: propagate errors */
3186 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3187 uint8_t ch;
3189 cpu_physical_memory_reset_dirty(current_addr,
3190 current_addr + TARGET_PAGE_SIZE,
3191 MIGRATION_DIRTY_FLAG);
3193 ch = *(phys_ram_base + current_addr);
3195 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3196 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3197 qemu_put_byte(f, ch);
3198 } else {
3199 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3200 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3203 found = 1;
3204 break;
3206 addr += TARGET_PAGE_SIZE;
3207 current_addr = (saved_addr + addr) % phys_ram_size;
3210 return found;
3213 static ram_addr_t ram_save_threshold = 10;
3215 static ram_addr_t ram_save_remaining(void)
3217 ram_addr_t addr;
3218 ram_addr_t count = 0;
3220 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3221 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3222 count++;
3225 return count;
3228 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3230 ram_addr_t addr;
3232 if (stage == 1) {
3233 /* Make sure all dirty bits are set */
3234 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3235 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3236 cpu_physical_memory_set_dirty(addr);
3239 /* Enable dirty memory tracking */
3240 cpu_physical_memory_set_dirty_tracking(1);
3242 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3245 while (!qemu_file_rate_limit(f)) {
3246 int ret;
3248 ret = ram_save_block(f);
3249 if (ret == 0) /* no more blocks */
3250 break;
3253 /* try transferring iterative blocks of memory */
3255 if (stage == 3) {
3256 cpu_physical_memory_set_dirty_tracking(0);
3258 /* flush all remaining blocks regardless of rate limiting */
3259 while (ram_save_block(f) != 0);
3262 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3264 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3267 static int ram_load_dead(QEMUFile *f, void *opaque)
3269 RamDecompressState s1, *s = &s1;
3270 uint8_t buf[10];
3271 ram_addr_t i;
3273 if (ram_decompress_open(s, f) < 0)
3274 return -EINVAL;
3275 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3276 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3277 continue;
3278 if (ram_decompress_buf(s, buf, 1) < 0) {
3279 fprintf(stderr, "Error while reading ram block header\n");
3280 goto error;
3282 if (buf[0] == 0) {
3283 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3284 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3285 goto error;
3287 } else {
3288 error:
3289 printf("Error block header\n");
3290 return -EINVAL;
3293 ram_decompress_close(s);
3295 return 0;
3298 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3300 ram_addr_t addr;
3301 int flags;
3303 if (version_id == 1)
3304 return ram_load_v1(f, opaque);
3306 if (version_id == 2) {
3307 if (qemu_get_be32(f) != phys_ram_size)
3308 return -EINVAL;
3309 return ram_load_dead(f, opaque);
3312 if (version_id != 3)
3313 return -EINVAL;
3315 do {
3316 addr = qemu_get_be64(f);
3318 flags = addr & ~TARGET_PAGE_MASK;
3319 addr &= TARGET_PAGE_MASK;
3321 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3322 if (addr != phys_ram_size)
3323 return -EINVAL;
3326 if (flags & RAM_SAVE_FLAG_FULL) {
3327 if (ram_load_dead(f, opaque) < 0)
3328 return -EINVAL;
3331 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3332 uint8_t ch = qemu_get_byte(f);
3333 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3334 } else if (flags & RAM_SAVE_FLAG_PAGE)
3335 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3336 } while (!(flags & RAM_SAVE_FLAG_EOS));
3338 return 0;
3341 /***********************************************************/
3342 /* bottom halves (can be seen as timers which expire ASAP) */
3344 struct QEMUBH {
3345 QEMUBHFunc *cb;
3346 void *opaque;
3347 int scheduled;
3348 int idle;
3349 int deleted;
3350 QEMUBH *next;
3353 static QEMUBH *first_bh = NULL;
3355 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3357 QEMUBH *bh;
3358 bh = qemu_mallocz(sizeof(QEMUBH));
3359 if (!bh)
3360 return NULL;
3361 bh->cb = cb;
3362 bh->opaque = opaque;
3363 bh->next = first_bh;
3364 first_bh = bh;
3365 return bh;
3368 int qemu_bh_poll(void)
3370 QEMUBH *bh, **bhp;
3371 int ret;
3373 ret = 0;
3374 for (bh = first_bh; bh; bh = bh->next) {
3375 if (!bh->deleted && bh->scheduled) {
3376 bh->scheduled = 0;
3377 if (!bh->idle)
3378 ret = 1;
3379 bh->idle = 0;
3380 bh->cb(bh->opaque);
3384 /* remove deleted bhs */
3385 bhp = &first_bh;
3386 while (*bhp) {
3387 bh = *bhp;
3388 if (bh->deleted) {
3389 *bhp = bh->next;
3390 qemu_free(bh);
3391 } else
3392 bhp = &bh->next;
3395 return ret;
3398 void qemu_bh_schedule_idle(QEMUBH *bh)
3400 if (bh->scheduled)
3401 return;
3402 bh->scheduled = 1;
3403 bh->idle = 1;
3406 void qemu_bh_schedule(QEMUBH *bh)
3408 CPUState *env = cpu_single_env;
3409 if (bh->scheduled)
3410 return;
3411 bh->scheduled = 1;
3412 bh->idle = 0;
3413 /* stop the currently executing CPU to execute the BH ASAP */
3414 if (env) {
3415 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3417 main_loop_break();
3420 void qemu_bh_cancel(QEMUBH *bh)
3422 bh->scheduled = 0;
3425 void qemu_bh_delete(QEMUBH *bh)
3427 bh->scheduled = 0;
3428 bh->deleted = 1;
3431 static void qemu_bh_update_timeout(int *timeout)
3433 QEMUBH *bh;
3435 for (bh = first_bh; bh; bh = bh->next) {
3436 if (!bh->deleted && bh->scheduled) {
3437 if (bh->idle) {
3438 /* idle bottom halves will be polled at least
3439 * every 10ms */
3440 *timeout = MIN(10, *timeout);
3441 } else {
3442 /* non-idle bottom halves will be executed
3443 * immediately */
3444 *timeout = 0;
3445 break;
3451 /***********************************************************/
3452 /* machine registration */
3454 static QEMUMachine *first_machine = NULL;
3455 QEMUMachine *current_machine = NULL;
3457 int qemu_register_machine(QEMUMachine *m)
3459 QEMUMachine **pm;
3460 pm = &first_machine;
3461 while (*pm != NULL)
3462 pm = &(*pm)->next;
3463 m->next = NULL;
3464 *pm = m;
3465 return 0;
3468 static QEMUMachine *find_machine(const char *name)
3470 QEMUMachine *m;
3472 for(m = first_machine; m != NULL; m = m->next) {
3473 if (!strcmp(m->name, name))
3474 return m;
3476 return NULL;
3479 /***********************************************************/
3480 /* main execution loop */
3482 static void gui_update(void *opaque)
3484 uint64_t interval = GUI_REFRESH_INTERVAL;
3485 DisplayState *ds = opaque;
3486 DisplayChangeListener *dcl = ds->listeners;
3488 dpy_refresh(ds);
3490 while (dcl != NULL) {
3491 if (dcl->gui_timer_interval &&
3492 dcl->gui_timer_interval < interval)
3493 interval = dcl->gui_timer_interval;
3494 dcl = dcl->next;
3496 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3499 static void nographic_update(void *opaque)
3501 uint64_t interval = GUI_REFRESH_INTERVAL;
3503 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3506 struct vm_change_state_entry {
3507 VMChangeStateHandler *cb;
3508 void *opaque;
3509 LIST_ENTRY (vm_change_state_entry) entries;
3512 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3514 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3515 void *opaque)
3517 VMChangeStateEntry *e;
3519 e = qemu_mallocz(sizeof (*e));
3520 if (!e)
3521 return NULL;
3523 e->cb = cb;
3524 e->opaque = opaque;
3525 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3526 return e;
3529 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3531 LIST_REMOVE (e, entries);
3532 qemu_free (e);
3535 static void vm_state_notify(int running, int reason)
3537 VMChangeStateEntry *e;
3539 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3540 e->cb(e->opaque, running, reason);
3544 void vm_start(void)
3546 if (!vm_running) {
3547 cpu_enable_ticks();
3548 vm_running = 1;
3549 vm_state_notify(1, 0);
3550 qemu_rearm_alarm_timer(alarm_timer);
3554 void vm_stop(int reason)
3556 if (vm_running) {
3557 cpu_disable_ticks();
3558 vm_running = 0;
3559 vm_state_notify(0, reason);
3563 /* reset/shutdown handler */
3565 typedef struct QEMUResetEntry {
3566 QEMUResetHandler *func;
3567 void *opaque;
3568 struct QEMUResetEntry *next;
3569 } QEMUResetEntry;
3571 static QEMUResetEntry *first_reset_entry;
3572 static int reset_requested;
3573 static int shutdown_requested;
3574 static int powerdown_requested;
3576 int qemu_shutdown_requested(void)
3578 int r = shutdown_requested;
3579 shutdown_requested = 0;
3580 return r;
3583 int qemu_reset_requested(void)
3585 int r = reset_requested;
3586 reset_requested = 0;
3587 return r;
3590 int qemu_powerdown_requested(void)
3592 int r = powerdown_requested;
3593 powerdown_requested = 0;
3594 return r;
3597 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3599 QEMUResetEntry **pre, *re;
3601 pre = &first_reset_entry;
3602 while (*pre != NULL)
3603 pre = &(*pre)->next;
3604 re = qemu_mallocz(sizeof(QEMUResetEntry));
3605 re->func = func;
3606 re->opaque = opaque;
3607 re->next = NULL;
3608 *pre = re;
3611 void qemu_system_reset(void)
3613 QEMUResetEntry *re;
3615 /* reset all devices */
3616 for(re = first_reset_entry; re != NULL; re = re->next) {
3617 re->func(re->opaque);
3621 void qemu_system_reset_request(void)
3623 if (no_reboot) {
3624 shutdown_requested = 1;
3625 } else {
3626 reset_requested = 1;
3629 if (cpu_single_env) {
3630 qemu_kvm_cpu_stop(cpu_single_env);
3631 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3633 main_loop_break();
3636 void qemu_system_shutdown_request(void)
3638 shutdown_requested = 1;
3639 if (cpu_single_env)
3640 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3643 void qemu_system_powerdown_request(void)
3645 powerdown_requested = 1;
3646 if (cpu_single_env)
3647 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3650 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
3651 struct timeval *tv)
3653 int ret;
3655 /* KVM holds a mutex while QEMU code is running, we need hooks to
3656 release the mutex whenever QEMU code sleeps. */
3658 kvm_sleep_begin();
3660 ret = select(max_fd, rfds, wfds, xfds, tv);
3662 kvm_sleep_end();
3664 return ret;
3667 #ifdef _WIN32
3668 static void host_main_loop_wait(int *timeout)
3670 int ret, ret2, i;
3671 PollingEntry *pe;
3674 /* XXX: need to suppress polling by better using win32 events */
3675 ret = 0;
3676 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3677 ret |= pe->func(pe->opaque);
3679 if (ret == 0) {
3680 int err;
3681 WaitObjects *w = &wait_objects;
3683 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3684 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3685 if (w->func[ret - WAIT_OBJECT_0])
3686 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3688 /* Check for additional signaled events */
3689 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3691 /* Check if event is signaled */
3692 ret2 = WaitForSingleObject(w->events[i], 0);
3693 if(ret2 == WAIT_OBJECT_0) {
3694 if (w->func[i])
3695 w->func[i](w->opaque[i]);
3696 } else if (ret2 == WAIT_TIMEOUT) {
3697 } else {
3698 err = GetLastError();
3699 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3702 } else if (ret == WAIT_TIMEOUT) {
3703 } else {
3704 err = GetLastError();
3705 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3709 *timeout = 0;
3711 #else
3712 static void host_main_loop_wait(int *timeout)
3715 #endif
3717 void main_loop_wait(int timeout)
3719 IOHandlerRecord *ioh;
3720 fd_set rfds, wfds, xfds;
3721 int ret, nfds;
3722 struct timeval tv;
3724 qemu_bh_update_timeout(&timeout);
3726 host_main_loop_wait(&timeout);
3728 /* poll any events */
3729 /* XXX: separate device handlers from system ones */
3730 nfds = -1;
3731 FD_ZERO(&rfds);
3732 FD_ZERO(&wfds);
3733 FD_ZERO(&xfds);
3734 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3735 if (ioh->deleted)
3736 continue;
3737 if (ioh->fd_read &&
3738 (!ioh->fd_read_poll ||
3739 ioh->fd_read_poll(ioh->opaque) != 0)) {
3740 FD_SET(ioh->fd, &rfds);
3741 if (ioh->fd > nfds)
3742 nfds = ioh->fd;
3744 if (ioh->fd_write) {
3745 FD_SET(ioh->fd, &wfds);
3746 if (ioh->fd > nfds)
3747 nfds = ioh->fd;
3751 tv.tv_sec = timeout / 1000;
3752 tv.tv_usec = (timeout % 1000) * 1000;
3754 #if defined(CONFIG_SLIRP)
3755 if (slirp_is_inited()) {
3756 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3758 #endif
3759 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3760 if (ret > 0) {
3761 IOHandlerRecord **pioh;
3763 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3764 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3765 ioh->fd_read(ioh->opaque);
3766 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3767 FD_CLR(ioh->fd, &rfds);
3769 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3770 ioh->fd_write(ioh->opaque);
3774 /* remove deleted IO handlers */
3775 pioh = &first_io_handler;
3776 while (*pioh) {
3777 ioh = *pioh;
3778 if (ioh->deleted) {
3779 *pioh = ioh->next;
3780 qemu_free(ioh);
3781 } else
3782 pioh = &ioh->next;
3785 #if defined(CONFIG_SLIRP)
3786 if (slirp_is_inited()) {
3787 if (ret < 0) {
3788 FD_ZERO(&rfds);
3789 FD_ZERO(&wfds);
3790 FD_ZERO(&xfds);
3792 slirp_select_poll(&rfds, &wfds, &xfds);
3794 #endif
3796 /* vm time timers */
3797 if (vm_running && (!cur_cpu
3798 || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER))))
3799 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3800 qemu_get_clock(vm_clock));
3802 /* real time timers */
3803 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3804 qemu_get_clock(rt_clock));
3806 /* Check bottom-halves last in case any of the earlier events triggered
3807 them. */
3808 qemu_bh_poll();
3812 static int main_loop(void)
3814 int ret, timeout;
3815 #ifdef CONFIG_PROFILER
3816 int64_t ti;
3817 #endif
3818 CPUState *env;
3821 if (kvm_enabled()) {
3822 kvm_main_loop();
3823 cpu_disable_ticks();
3824 return 0;
3827 cur_cpu = first_cpu;
3828 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3829 for(;;) {
3830 if (vm_running) {
3832 for(;;) {
3833 /* get next cpu */
3834 env = next_cpu;
3835 #ifdef CONFIG_PROFILER
3836 ti = profile_getclock();
3837 #endif
3838 if (use_icount) {
3839 int64_t count;
3840 int decr;
3841 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3842 env->icount_decr.u16.low = 0;
3843 env->icount_extra = 0;
3844 count = qemu_next_deadline();
3845 count = (count + (1 << icount_time_shift) - 1)
3846 >> icount_time_shift;
3847 qemu_icount += count;
3848 decr = (count > 0xffff) ? 0xffff : count;
3849 count -= decr;
3850 env->icount_decr.u16.low = decr;
3851 env->icount_extra = count;
3853 ret = cpu_exec(env);
3854 #ifdef CONFIG_PROFILER
3855 qemu_time += profile_getclock() - ti;
3856 #endif
3857 if (use_icount) {
3858 /* Fold pending instructions back into the
3859 instruction counter, and clear the interrupt flag. */
3860 qemu_icount -= (env->icount_decr.u16.low
3861 + env->icount_extra);
3862 env->icount_decr.u32 = 0;
3863 env->icount_extra = 0;
3865 next_cpu = env->next_cpu ?: first_cpu;
3866 if (event_pending && likely(ret != EXCP_DEBUG)) {
3867 ret = EXCP_INTERRUPT;
3868 event_pending = 0;
3869 break;
3871 if (ret == EXCP_HLT) {
3872 /* Give the next CPU a chance to run. */
3873 cur_cpu = env;
3874 continue;
3876 if (ret != EXCP_HALTED)
3877 break;
3878 /* all CPUs are halted ? */
3879 if (env == cur_cpu)
3880 break;
3882 cur_cpu = env;
3884 if (shutdown_requested) {
3885 ret = EXCP_INTERRUPT;
3886 if (no_shutdown) {
3887 vm_stop(0);
3888 no_shutdown = 0;
3890 else
3891 break;
3893 if (reset_requested) {
3894 reset_requested = 0;
3895 qemu_system_reset();
3896 if (kvm_enabled())
3897 kvm_load_registers(env);
3898 ret = EXCP_INTERRUPT;
3900 if (powerdown_requested) {
3901 powerdown_requested = 0;
3902 qemu_system_powerdown();
3903 ret = EXCP_INTERRUPT;
3905 #ifdef CONFIG_GDBSTUB
3906 if (unlikely(ret == EXCP_DEBUG)) {
3907 gdb_set_stop_cpu(cur_cpu);
3908 vm_stop(EXCP_DEBUG);
3910 #endif
3911 /* If all cpus are halted then wait until the next IRQ */
3912 /* XXX: use timeout computed from timers */
3913 if (ret == EXCP_HALTED) {
3914 if (use_icount) {
3915 int64_t add;
3916 int64_t delta;
3917 /* Advance virtual time to the next event. */
3918 if (use_icount == 1) {
3919 /* When not using an adaptive execution frequency
3920 we tend to get badly out of sync with real time,
3921 so just delay for a reasonable amount of time. */
3922 delta = 0;
3923 } else {
3924 delta = cpu_get_icount() - cpu_get_clock();
3926 if (delta > 0) {
3927 /* If virtual time is ahead of real time then just
3928 wait for IO. */
3929 timeout = (delta / 1000000) + 1;
3930 } else {
3931 /* Wait for either IO to occur or the next
3932 timer event. */
3933 add = qemu_next_deadline();
3934 /* We advance the timer before checking for IO.
3935 Limit the amount we advance so that early IO
3936 activity won't get the guest too far ahead. */
3937 if (add > 10000000)
3938 add = 10000000;
3939 delta += add;
3940 add = (add + (1 << icount_time_shift) - 1)
3941 >> icount_time_shift;
3942 qemu_icount += add;
3943 timeout = delta / 1000000;
3944 if (timeout < 0)
3945 timeout = 0;
3947 } else {
3948 timeout = 5000;
3950 } else {
3951 timeout = 0;
3953 } else {
3954 if (shutdown_requested) {
3955 ret = EXCP_INTERRUPT;
3956 break;
3958 timeout = 5000;
3960 #ifdef CONFIG_PROFILER
3961 ti = profile_getclock();
3962 #endif
3963 main_loop_wait(timeout);
3964 #ifdef CONFIG_PROFILER
3965 dev_time += profile_getclock() - ti;
3966 #endif
3968 cpu_disable_ticks();
3969 return ret;
3972 static void help(int exitcode)
3974 /* Please keep in synch with QEMU_OPTION_ enums, qemu_options[]
3975 and qemu-doc.texi */
3976 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
3977 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3978 "usage: %s [options] [disk_image]\n"
3979 "\n"
3980 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3981 "\n"
3982 "Standard options:\n"
3983 "-h or -help display this help and exit\n"
3984 "-M machine select emulated machine (-M ? for list)\n"
3985 "-cpu cpu select CPU (-cpu ? for list)\n"
3986 "-smp n set the number of CPUs to 'n' [default=1]\n"
3987 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3988 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3989 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3990 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3991 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3992 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3993 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
3994 " [,boot=on|off]\n"
3995 " use 'file' as a drive image\n"
3996 "-mtdblock file use 'file' as on-board Flash memory image\n"
3997 "-sd file use 'file' as SecureDigital card image\n"
3998 "-pflash file use 'file' as a parallel flash image\n"
3999 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
4000 "-snapshot write to temporary files instead of disk image files\n"
4001 "-m megs set virtual RAM size to megs MB [default=%d]\n"
4002 #ifndef _WIN32
4003 "-k language use keyboard layout (for example \"fr\" for French)\n"
4004 #endif
4005 #ifdef HAS_AUDIO
4006 "-audio-help print list of audio drivers and their options\n"
4007 "-soundhw c1,... enable audio support\n"
4008 " and only specified sound cards (comma separated list)\n"
4009 " use -soundhw ? to get the list of supported cards\n"
4010 " use -soundhw all to enable all of them\n"
4011 #endif
4012 "-usb enable the USB driver (will be the default soon)\n"
4013 "-usbdevice name add the host or guest USB device 'name'\n"
4014 "-name string set the name of the guest\n"
4015 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x\n"
4016 " specify machine UUID\n"
4017 "\n"
4018 "Display options:\n"
4019 "-nographic disable graphical output and redirect serial I/Os to console\n"
4020 #ifdef CONFIG_CURSES
4021 "-curses use a curses/ncurses interface instead of SDL\n"
4022 #endif
4023 #ifdef CONFIG_SDL
4024 "-no-frame open SDL window without a frame and window decorations\n"
4025 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
4026 "-no-quit disable SDL window close capability\n"
4027 "-sdl enable SDL\n"
4028 #endif
4029 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
4030 "-vga [std|cirrus|vmware|none]\n"
4031 " select video card type\n"
4032 "-full-screen start in full screen\n"
4033 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4034 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4035 #endif
4036 "-vnc display start a VNC server on display\n"
4037 #ifdef TARGET_IA64
4038 "-nvram file use 'file' to save or load nvram image\n"
4039 #endif
4040 "-name string set the name of the guest\n"
4041 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
4042 "\n"
4043 "Network options:\n"
4044 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
4045 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4046 #ifdef CONFIG_SLIRP
4047 "-net user[,vlan=n][,name=str][,hostname=host]\n"
4048 " connect the user mode network stack to VLAN 'n' and send\n"
4049 " hostname 'host' to DHCP clients\n"
4050 #endif
4051 #ifdef _WIN32
4052 "-net tap[,vlan=n][,name=str],ifname=name\n"
4053 " connect the host TAP network interface to VLAN 'n'\n"
4054 #else
4055 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4056 " connect the host TAP network interface to VLAN 'n' and use the\n"
4057 " network scripts 'file' (default=%s)\n"
4058 " and 'dfile' (default=%s);\n"
4059 " use '[down]script=no' to disable script execution;\n"
4060 " use 'fd=h' to connect to an already opened TAP interface\n"
4061 #endif
4062 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4063 " connect the vlan 'n' to another VLAN using a socket connection\n"
4064 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
4065 " connect the vlan 'n' to multicast maddr and port\n"
4066 #ifdef CONFIG_VDE
4067 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4068 " connect the vlan 'n' to port 'n' of a vde switch running\n"
4069 " on host and listening for incoming connections on 'socketpath'.\n"
4070 " Use group 'groupname' and mode 'octalmode' to change default\n"
4071 " ownership and permissions for communication port.\n"
4072 #endif
4073 "-net none use it alone to have zero network devices; if no -net option\n"
4074 " is provided, the default is '-net nic -net user'\n"
4075 #ifdef CONFIG_SLIRP
4076 "-tftp dir allow tftp access to files in dir [-net user]\n"
4077 "-bootp file advertise file in BOOTP replies\n"
4078 #ifndef _WIN32
4079 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4080 #endif
4081 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4082 " redirect TCP or UDP connections from host to guest [-net user]\n"
4083 #endif
4084 "\n"
4085 "-bt hci,null dumb bluetooth HCI - doesn't respond to commands\n"
4086 "-bt hci,host[:id]\n"
4087 " use host's HCI with the given name\n"
4088 "-bt hci[,vlan=n]\n"
4089 " emulate a standard HCI in virtual scatternet 'n'\n"
4090 "-bt vhci[,vlan=n]\n"
4091 " add host computer to virtual scatternet 'n' using VHCI\n"
4092 "-bt device:dev[,vlan=n]\n"
4093 " emulate a bluetooth device 'dev' in scatternet 'n'\n"
4094 "\n"
4095 #ifdef TARGET_I386
4096 "\n"
4097 "i386 target only:\n"
4098 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4099 "-rtc-td-hack use it to fix time drift in Windows ACPI HAL\n"
4100 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4101 "-no-acpi disable ACPI\n"
4102 "-no-hpet disable HPET\n"
4103 #endif
4104 "Linux boot specific:\n"
4105 "-kernel bzImage use 'bzImage' as kernel image\n"
4106 "-append cmdline use 'cmdline' as kernel command line\n"
4107 "-initrd file use 'file' as initial ram disk\n"
4108 "\n"
4109 "Debug/Expert options:\n"
4110 "-serial dev redirect the serial port to char device 'dev'\n"
4111 "-parallel dev redirect the parallel port to char device 'dev'\n"
4112 "-monitor dev redirect the monitor to char device 'dev'\n"
4113 "-pidfile file write PID to 'file'\n"
4114 "-S freeze CPU at startup (use 'c' to start execution)\n"
4115 "-s wait gdb connection to port\n"
4116 "-p port set gdb connection port [default=%s]\n"
4117 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4118 "-hdachs c,h,s[,t]\n"
4119 " force hard disk 0 physical geometry and the optional BIOS\n"
4120 " translation (t=none or lba) (usually qemu can guess them)\n"
4121 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4122 "-bios file set the filename for the BIOS\n"
4123 #ifdef USE_KQEMU
4124 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4125 "-no-kqemu disable KQEMU kernel module usage\n"
4126 #endif
4127 #ifdef CONFIG_KVM
4128 "-enable-kvm enable KVM full virtualization support\n"
4129 #endif
4130 #ifdef USE_KVM
4131 #ifndef NO_CPU_EMULATION
4132 "-no-kvm disable KVM hardware virtualization\n"
4133 #endif
4134 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
4135 "-no-kvm-pit disable KVM kernel mode PIT\n"
4136 "-no-kvm-pit-reinjection disable KVM kernel mode PIT interrupt reinjection\n"
4137 "-enable-nesting enable support for running a VM inside the VM (AMD only)\n"
4138 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4139 "-pcidevice host=bus:dev.func[,dma=none][,name=string]\n"
4140 " expose a PCI device to the guest OS.\n"
4141 " dma=none: don't perform any dma translations (default is to use an iommu)\n"
4142 " 'string' is used in log output.\n"
4143 #endif
4144 #endif
4145 "-no-reboot exit instead of rebooting\n"
4146 "-no-shutdown stop before shutdown\n"
4147 "-loadvm [tag|id]\n"
4148 " start right away with a saved state (loadvm in monitor)\n"
4149 #ifndef _WIN32
4150 "-daemonize daemonize QEMU after initializing\n"
4151 #endif
4152 "-tdf inject timer interrupts that got lost\n"
4153 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
4154 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
4155 "-option-rom rom load a file, rom, into the option ROM space\n"
4156 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4157 "-prom-env variable=value\n"
4158 " set OpenBIOS nvram variables\n"
4159 #endif
4160 "-clock force the use of the given methods for timer alarm.\n"
4161 " To see what timers are available use -clock ?\n"
4162 "-localtime set the real time clock to local time [default=utc]\n"
4163 "-startdate select initial date of the clock\n"
4164 "-icount [N|auto]\n"
4165 " enable virtual instruction counter with 2^N clock ticks per instruction\n"
4166 "-echr chr set terminal escape character instead of ctrl-a\n"
4167 "-virtioconsole c\n"
4168 " set virtio console\n"
4169 "-show-cursor show cursor\n"
4170 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4171 "-semihosting semihosting mode\n"
4172 #endif
4173 #if defined(TARGET_ARM)
4174 "-old-param old param mode\n"
4175 #endif
4176 "-tb-size n set TB size\n"
4177 "-incoming p prepare for incoming migration, listen on port p\n"
4178 "\n"
4179 "During emulation, the following keys are useful:\n"
4180 "ctrl-alt-f toggle full screen\n"
4181 "ctrl-alt-n switch to virtual console 'n'\n"
4182 "ctrl-alt toggle mouse and keyboard grab\n"
4183 "\n"
4184 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4186 "qemu",
4187 DEFAULT_RAM_SIZE,
4188 #ifndef _WIN32
4189 DEFAULT_NETWORK_SCRIPT,
4190 DEFAULT_NETWORK_DOWN_SCRIPT,
4191 #endif
4192 DEFAULT_GDBSTUB_PORT,
4193 "/tmp/qemu.log");
4194 exit(exitcode);
4197 #define HAS_ARG 0x0001
4199 enum {
4200 /* Please keep in synch with help, qemu_options[] and
4201 qemu-doc.texi */
4202 /* Standard options: */
4203 QEMU_OPTION_h,
4204 QEMU_OPTION_M,
4205 QEMU_OPTION_cpu,
4206 QEMU_OPTION_smp,
4207 QEMU_OPTION_fda,
4208 QEMU_OPTION_fdb,
4209 QEMU_OPTION_hda,
4210 QEMU_OPTION_hdb,
4211 QEMU_OPTION_hdc,
4212 QEMU_OPTION_hdd,
4213 QEMU_OPTION_cdrom,
4214 QEMU_OPTION_drive,
4215 QEMU_OPTION_mtdblock,
4216 QEMU_OPTION_sd,
4217 QEMU_OPTION_pflash,
4218 QEMU_OPTION_boot,
4219 QEMU_OPTION_snapshot,
4220 QEMU_OPTION_m,
4221 QEMU_OPTION_k,
4222 QEMU_OPTION_audio_help,
4223 QEMU_OPTION_soundhw,
4224 QEMU_OPTION_usb,
4225 QEMU_OPTION_usbdevice,
4226 QEMU_OPTION_name,
4227 QEMU_OPTION_uuid,
4229 /* Display options: */
4230 QEMU_OPTION_nographic,
4231 QEMU_OPTION_curses,
4232 QEMU_OPTION_no_frame,
4233 QEMU_OPTION_alt_grab,
4234 QEMU_OPTION_no_quit,
4235 QEMU_OPTION_sdl,
4236 QEMU_OPTION_portrait,
4237 QEMU_OPTION_vga,
4238 QEMU_OPTION_full_screen,
4239 QEMU_OPTION_g,
4240 QEMU_OPTION_vnc,
4242 /* Network options: */
4243 QEMU_OPTION_net,
4244 QEMU_OPTION_tftp,
4245 QEMU_OPTION_bootp,
4246 QEMU_OPTION_smb,
4247 QEMU_OPTION_redir,
4248 QEMU_OPTION_bt,
4250 /* i386 target only: */
4251 QEMU_OPTION_win2k_hack,
4252 QEMU_OPTION_rtc_td_hack,
4253 QEMU_OPTION_no_fd_bootchk,
4254 QEMU_OPTION_no_acpi,
4255 QEMU_OPTION_no_hpet,
4257 /* Linux boot specific: */
4258 QEMU_OPTION_kernel,
4259 QEMU_OPTION_append,
4260 QEMU_OPTION_initrd,
4262 /* Debug/Expert options: */
4263 QEMU_OPTION_serial,
4264 QEMU_OPTION_parallel,
4265 QEMU_OPTION_monitor,
4266 QEMU_OPTION_pidfile,
4267 QEMU_OPTION_S,
4268 QEMU_OPTION_s,
4269 QEMU_OPTION_p,
4270 QEMU_OPTION_d,
4271 QEMU_OPTION_hdachs,
4272 QEMU_OPTION_L,
4273 QEMU_OPTION_bios,
4274 QEMU_OPTION_kernel_kqemu,
4275 QEMU_OPTION_no_kqemu,
4276 QEMU_OPTION_enable_kvm,
4277 QEMU_OPTION_enable_nesting,
4278 QEMU_OPTION_no_kvm,
4279 QEMU_OPTION_no_kvm_irqchip,
4280 QEMU_OPTION_no_kvm_pit,
4281 QEMU_OPTION_no_kvm_pit_reinjection,
4282 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4283 QEMU_OPTION_pcidevice,
4284 #endif
4285 QEMU_OPTION_no_reboot,
4286 QEMU_OPTION_no_shutdown,
4287 QEMU_OPTION_loadvm,
4288 QEMU_OPTION_daemonize,
4289 QEMU_OPTION_option_rom,
4290 QEMU_OPTION_cpu_vendor,
4291 QEMU_OPTION_nvram,
4292 QEMU_OPTION_prom_env,
4293 QEMU_OPTION_clock,
4294 QEMU_OPTION_localtime,
4295 QEMU_OPTION_startdate,
4296 QEMU_OPTION_icount,
4297 QEMU_OPTION_echr,
4298 QEMU_OPTION_virtiocon,
4299 QEMU_OPTION_show_cursor,
4300 QEMU_OPTION_semihosting,
4301 QEMU_OPTION_old_param,
4302 QEMU_OPTION_tb_size,
4303 QEMU_OPTION_incoming,
4304 QEMU_OPTION_tdf,
4305 QEMU_OPTION_kvm_shadow_memory,
4306 QEMU_OPTION_mempath,
4309 typedef struct QEMUOption {
4310 const char *name;
4311 int flags;
4312 int index;
4313 } QEMUOption;
4315 static const QEMUOption qemu_options[] = {
4316 /* Please keep in synch with help, QEMU_OPTION_ enums, and
4317 qemu-doc.texi */
4318 /* Standard options: */
4319 { "h", 0, QEMU_OPTION_h },
4320 { "help", 0, QEMU_OPTION_h },
4321 { "M", HAS_ARG, QEMU_OPTION_M },
4322 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4323 { "smp", HAS_ARG, QEMU_OPTION_smp },
4324 { "fda", HAS_ARG, QEMU_OPTION_fda },
4325 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4326 { "hda", HAS_ARG, QEMU_OPTION_hda },
4327 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4328 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4329 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4330 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4331 { "drive", HAS_ARG, QEMU_OPTION_drive },
4332 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4333 { "sd", HAS_ARG, QEMU_OPTION_sd },
4334 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4335 { "boot", HAS_ARG, QEMU_OPTION_boot },
4336 { "snapshot", 0, QEMU_OPTION_snapshot },
4337 { "m", HAS_ARG, QEMU_OPTION_m },
4338 #ifndef _WIN32
4339 { "k", HAS_ARG, QEMU_OPTION_k },
4340 #endif
4341 #ifdef HAS_AUDIO
4342 { "audio-help", 0, QEMU_OPTION_audio_help },
4343 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4344 #endif
4345 { "usb", 0, QEMU_OPTION_usb },
4346 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4347 { "name", HAS_ARG, QEMU_OPTION_name },
4348 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4350 /* Display options: */
4351 { "nographic", 0, QEMU_OPTION_nographic },
4352 #ifdef CONFIG_CURSES
4353 { "curses", 0, QEMU_OPTION_curses },
4354 #endif
4355 #ifdef CONFIG_SDL
4356 { "no-frame", 0, QEMU_OPTION_no_frame },
4357 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4358 { "no-quit", 0, QEMU_OPTION_no_quit },
4359 { "sdl", 0, QEMU_OPTION_sdl },
4360 #endif
4361 { "portrait", 0, QEMU_OPTION_portrait },
4362 { "vga", HAS_ARG, QEMU_OPTION_vga },
4363 { "full-screen", 0, QEMU_OPTION_full_screen },
4364 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4365 { "g", 1, QEMU_OPTION_g },
4366 #endif
4367 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4369 /* Network options: */
4370 { "net", HAS_ARG, QEMU_OPTION_net},
4371 #ifdef CONFIG_SLIRP
4372 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4373 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4374 #ifndef _WIN32
4375 { "smb", HAS_ARG, QEMU_OPTION_smb },
4376 #endif
4377 { "redir", HAS_ARG, QEMU_OPTION_redir },
4378 #endif
4379 { "bt", HAS_ARG, QEMU_OPTION_bt },
4380 #ifdef TARGET_I386
4381 /* i386 target only: */
4382 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4383 { "rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack },
4384 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4385 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4386 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4387 #endif
4389 /* Linux boot specific: */
4390 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4391 { "append", HAS_ARG, QEMU_OPTION_append },
4392 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4394 /* Debug/Expert options: */
4395 { "serial", HAS_ARG, QEMU_OPTION_serial },
4396 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4397 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4398 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4399 { "S", 0, QEMU_OPTION_S },
4400 { "s", 0, QEMU_OPTION_s },
4401 { "p", HAS_ARG, QEMU_OPTION_p },
4402 { "d", HAS_ARG, QEMU_OPTION_d },
4403 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4404 { "L", HAS_ARG, QEMU_OPTION_L },
4405 { "bios", HAS_ARG, QEMU_OPTION_bios },
4406 #ifdef USE_KQEMU
4407 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4408 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4409 #endif
4410 #ifdef CONFIG_KVM
4411 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4412 #endif
4413 #ifdef USE_KVM
4414 #ifndef NO_CPU_EMULATION
4415 { "no-kvm", 0, QEMU_OPTION_no_kvm },
4416 #endif
4417 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
4418 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
4419 { "no-kvm-pit-reinjection", 0, QEMU_OPTION_no_kvm_pit_reinjection },
4420 { "enable-nesting", 0, QEMU_OPTION_enable_nesting },
4421 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4422 { "pcidevice", HAS_ARG, QEMU_OPTION_pcidevice },
4423 #endif
4424 #endif
4425 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4426 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4427 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4428 { "daemonize", 0, QEMU_OPTION_daemonize },
4429 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4430 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4431 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4432 #endif
4433 { "clock", HAS_ARG, QEMU_OPTION_clock },
4434 { "localtime", 0, QEMU_OPTION_localtime },
4435 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4436 { "icount", HAS_ARG, QEMU_OPTION_icount },
4437 { "echr", HAS_ARG, QEMU_OPTION_echr },
4438 { "virtioconsole", HAS_ARG, QEMU_OPTION_virtiocon },
4439 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4440 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4441 { "semihosting", 0, QEMU_OPTION_semihosting },
4442 #endif
4443 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
4444 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
4445 { "nvram", HAS_ARG, QEMU_OPTION_nvram },
4446 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
4447 #if defined(TARGET_ARM)
4448 { "old-param", 0, QEMU_OPTION_old_param },
4449 #endif
4450 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4451 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4452 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
4453 { NULL },
4456 /* password input */
4458 int qemu_key_check(BlockDriverState *bs, const char *name)
4460 char password[256];
4461 int i;
4463 if (!bdrv_is_encrypted(bs))
4464 return 0;
4466 term_printf("%s is encrypted.\n", name);
4467 for(i = 0; i < 3; i++) {
4468 monitor_readline("Password: ", 1, password, sizeof(password));
4469 if (bdrv_set_key(bs, password) == 0)
4470 return 0;
4471 term_printf("invalid password\n");
4473 return -EPERM;
4476 static BlockDriverState *get_bdrv(int index)
4478 if (index > nb_drives)
4479 return NULL;
4480 return drives_table[index].bdrv;
4483 static void read_passwords(void)
4485 BlockDriverState *bs;
4486 int i;
4488 for(i = 0; i < 6; i++) {
4489 bs = get_bdrv(i);
4490 if (bs)
4491 qemu_key_check(bs, bdrv_get_device_name(bs));
4495 #ifdef HAS_AUDIO
4496 struct soundhw soundhw[] = {
4497 #ifdef HAS_AUDIO_CHOICE
4498 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4500 "pcspk",
4501 "PC speaker",
4504 { .init_isa = pcspk_audio_init }
4506 #endif
4508 #ifdef CONFIG_SB16
4510 "sb16",
4511 "Creative Sound Blaster 16",
4514 { .init_isa = SB16_init }
4516 #endif
4518 #ifdef CONFIG_CS4231A
4520 "cs4231a",
4521 "CS4231A",
4524 { .init_isa = cs4231a_init }
4526 #endif
4528 #ifdef CONFIG_ADLIB
4530 "adlib",
4531 #ifdef HAS_YMF262
4532 "Yamaha YMF262 (OPL3)",
4533 #else
4534 "Yamaha YM3812 (OPL2)",
4535 #endif
4538 { .init_isa = Adlib_init }
4540 #endif
4542 #ifdef CONFIG_GUS
4544 "gus",
4545 "Gravis Ultrasound GF1",
4548 { .init_isa = GUS_init }
4550 #endif
4552 #ifdef CONFIG_AC97
4554 "ac97",
4555 "Intel 82801AA AC97 Audio",
4558 { .init_pci = ac97_init }
4560 #endif
4562 #ifdef CONFIG_ES1370
4564 "es1370",
4565 "ENSONIQ AudioPCI ES1370",
4568 { .init_pci = es1370_init }
4570 #endif
4572 #endif /* HAS_AUDIO_CHOICE */
4574 { NULL, NULL, 0, 0, { NULL } }
4577 static void select_soundhw (const char *optarg)
4579 struct soundhw *c;
4581 if (*optarg == '?') {
4582 show_valid_cards:
4584 printf ("Valid sound card names (comma separated):\n");
4585 for (c = soundhw; c->name; ++c) {
4586 printf ("%-11s %s\n", c->name, c->descr);
4588 printf ("\n-soundhw all will enable all of the above\n");
4589 exit (*optarg != '?');
4591 else {
4592 size_t l;
4593 const char *p;
4594 char *e;
4595 int bad_card = 0;
4597 if (!strcmp (optarg, "all")) {
4598 for (c = soundhw; c->name; ++c) {
4599 c->enabled = 1;
4601 return;
4604 p = optarg;
4605 while (*p) {
4606 e = strchr (p, ',');
4607 l = !e ? strlen (p) : (size_t) (e - p);
4609 for (c = soundhw; c->name; ++c) {
4610 if (!strncmp (c->name, p, l)) {
4611 c->enabled = 1;
4612 break;
4616 if (!c->name) {
4617 if (l > 80) {
4618 fprintf (stderr,
4619 "Unknown sound card name (too big to show)\n");
4621 else {
4622 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4623 (int) l, p);
4625 bad_card = 1;
4627 p += l + (e != NULL);
4630 if (bad_card)
4631 goto show_valid_cards;
4634 #endif
4636 static void select_vgahw (const char *p)
4638 const char *opts;
4640 if (strstart(p, "std", &opts)) {
4641 std_vga_enabled = 1;
4642 cirrus_vga_enabled = 0;
4643 vmsvga_enabled = 0;
4644 } else if (strstart(p, "cirrus", &opts)) {
4645 cirrus_vga_enabled = 1;
4646 std_vga_enabled = 0;
4647 vmsvga_enabled = 0;
4648 } else if (strstart(p, "vmware", &opts)) {
4649 cirrus_vga_enabled = 0;
4650 std_vga_enabled = 0;
4651 vmsvga_enabled = 1;
4652 } else if (strstart(p, "none", &opts)) {
4653 cirrus_vga_enabled = 0;
4654 std_vga_enabled = 0;
4655 vmsvga_enabled = 0;
4656 } else {
4657 invalid_vga:
4658 fprintf(stderr, "Unknown vga type: %s\n", p);
4659 exit(1);
4661 while (*opts) {
4662 const char *nextopt;
4664 if (strstart(opts, ",retrace=", &nextopt)) {
4665 opts = nextopt;
4666 if (strstart(opts, "dumb", &nextopt))
4667 vga_retrace_method = VGA_RETRACE_DUMB;
4668 else if (strstart(opts, "precise", &nextopt))
4669 vga_retrace_method = VGA_RETRACE_PRECISE;
4670 else goto invalid_vga;
4671 } else goto invalid_vga;
4672 opts = nextopt;
4676 #ifdef _WIN32
4677 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4679 exit(STATUS_CONTROL_C_EXIT);
4680 return TRUE;
4682 #endif
4684 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4686 int ret;
4688 if(strlen(str) != 36)
4689 return -1;
4691 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4692 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4693 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4695 if(ret != 16)
4696 return -1;
4698 return 0;
4701 #define MAX_NET_CLIENTS 32
4703 static int saved_argc;
4704 static char **saved_argv;
4706 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
4708 *argc = saved_argc;
4709 *argv = saved_argv;
4710 *opt_daemonize = daemonize;
4711 *opt_incoming = incoming;
4715 static int gethugepagesize(void)
4717 int ret, fd;
4718 char buf[4096];
4719 const char *needle = "Hugepagesize:";
4720 char *size;
4721 unsigned long hugepagesize;
4723 fd = open("/proc/meminfo", O_RDONLY);
4724 if (fd < 0) {
4725 perror("open");
4726 exit(0);
4729 ret = read(fd, buf, sizeof(buf));
4730 if (ret < 0) {
4731 perror("read");
4732 exit(0);
4735 size = strstr(buf, needle);
4736 if (!size)
4737 return 0;
4738 size += strlen(needle);
4739 hugepagesize = strtol(size, NULL, 0);
4740 return hugepagesize;
4743 static void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4745 char *filename;
4746 void *area;
4747 int fd;
4749 if (!kvm_has_sync_mmu()) {
4750 fprintf(stderr, "host lacks mmu notifiers, disabling --mem-path\n");
4751 return NULL;
4754 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4755 return NULL;
4757 hpagesize = gethugepagesize() * 1024;
4758 if (!hpagesize)
4759 return NULL;
4761 fd = mkstemp(filename);
4762 if (fd < 0) {
4763 perror("mkstemp");
4764 free(filename);
4765 return NULL;
4767 unlink(filename);
4768 free(filename);
4770 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4773 * ftruncate is not supported by hugetlbfs in older
4774 * hosts, so don't bother checking for errors.
4775 * If anything goes wrong with it under other filesystems,
4776 * mmap will fail.
4778 ftruncate(fd, memory);
4780 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4781 if (area == MAP_FAILED) {
4782 perror("mmap");
4783 close(fd);
4784 return NULL;
4787 *len = memory;
4788 return area;
4791 static void *qemu_alloc_physram(unsigned long memory)
4793 void *area = NULL;
4794 unsigned long map_len = memory;
4796 #ifdef USE_KVM
4797 if (mem_path)
4798 area = alloc_mem_area(memory, &map_len, mem_path);
4799 #endif
4800 if (!area)
4801 area = qemu_vmalloc(memory);
4802 #ifdef USE_KVM
4803 if (kvm_setup_guest_memory(area, map_len))
4804 area = NULL;
4805 #endif
4806 return area;
4809 #ifndef _WIN32
4811 static void termsig_handler(int signal)
4813 qemu_system_shutdown_request();
4816 static void termsig_setup(void)
4818 struct sigaction act;
4820 memset(&act, 0, sizeof(act));
4821 act.sa_handler = termsig_handler;
4822 sigaction(SIGINT, &act, NULL);
4823 sigaction(SIGHUP, &act, NULL);
4824 sigaction(SIGTERM, &act, NULL);
4827 #endif
4829 int main(int argc, char **argv, char **envp)
4831 #ifdef CONFIG_GDBSTUB
4832 int use_gdbstub;
4833 const char *gdbstub_port;
4834 #endif
4835 uint32_t boot_devices_bitmap = 0;
4836 int i;
4837 int snapshot, linux_boot, net_boot;
4838 const char *initrd_filename;
4839 const char *kernel_filename, *kernel_cmdline;
4840 const char *boot_devices = "";
4841 DisplayState *ds;
4842 DisplayChangeListener *dcl;
4843 int cyls, heads, secs, translation;
4844 const char *net_clients[MAX_NET_CLIENTS];
4845 int nb_net_clients;
4846 const char *bt_opts[MAX_BT_CMDLINE];
4847 int nb_bt_opts;
4848 int hda_index;
4849 int optind;
4850 const char *r, *optarg;
4851 CharDriverState *monitor_hd = NULL;
4852 const char *monitor_device;
4853 const char *serial_devices[MAX_SERIAL_PORTS];
4854 int serial_device_index;
4855 const char *parallel_devices[MAX_PARALLEL_PORTS];
4856 int parallel_device_index;
4857 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4858 int virtio_console_index;
4859 const char *loadvm = NULL;
4860 QEMUMachine *machine;
4861 const char *cpu_model;
4862 const char *usb_devices[MAX_USB_CMDLINE];
4863 int usb_devices_index;
4864 int fds[2];
4865 int tb_size;
4866 const char *pid_file = NULL;
4867 int autostart;
4868 const char *incoming = NULL;
4870 qemu_cache_utils_init(envp);
4872 LIST_INIT (&vm_change_state_head);
4873 #ifndef _WIN32
4875 struct sigaction act;
4876 sigfillset(&act.sa_mask);
4877 act.sa_flags = 0;
4878 act.sa_handler = SIG_IGN;
4879 sigaction(SIGPIPE, &act, NULL);
4881 #else
4882 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4883 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4884 QEMU to run on a single CPU */
4886 HANDLE h;
4887 DWORD mask, smask;
4888 int i;
4889 h = GetCurrentProcess();
4890 if (GetProcessAffinityMask(h, &mask, &smask)) {
4891 for(i = 0; i < 32; i++) {
4892 if (mask & (1 << i))
4893 break;
4895 if (i != 32) {
4896 mask = 1 << i;
4897 SetProcessAffinityMask(h, mask);
4901 #endif
4903 register_machines();
4904 machine = first_machine;
4905 cpu_model = NULL;
4906 initrd_filename = NULL;
4907 ram_size = 0;
4908 vga_ram_size = VGA_RAM_SIZE;
4909 #ifdef CONFIG_GDBSTUB
4910 use_gdbstub = 0;
4911 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4912 #endif
4913 snapshot = 0;
4914 nographic = 0;
4915 curses = 0;
4916 kernel_filename = NULL;
4917 kernel_cmdline = "";
4918 cyls = heads = secs = 0;
4919 translation = BIOS_ATA_TRANSLATION_AUTO;
4920 monitor_device = "vc";
4922 serial_devices[0] = "vc:80Cx24C";
4923 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4924 serial_devices[i] = NULL;
4925 serial_device_index = 0;
4927 parallel_devices[0] = "vc:640x480";
4928 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4929 parallel_devices[i] = NULL;
4930 parallel_device_index = 0;
4932 virtio_consoles[0] = "vc:80Cx24C";
4933 for(i = 1; i < MAX_VIRTIO_CONSOLES; i++)
4934 virtio_consoles[i] = NULL;
4935 virtio_console_index = 0;
4937 usb_devices_index = 0;
4938 assigned_devices_index = 0;
4940 nb_net_clients = 0;
4941 nb_bt_opts = 0;
4942 nb_drives = 0;
4943 nb_drives_opt = 0;
4944 hda_index = -1;
4946 nb_nics = 0;
4948 tb_size = 0;
4949 autostart= 1;
4951 optind = 1;
4952 for(;;) {
4953 if (optind >= argc)
4954 break;
4955 r = argv[optind];
4956 if (r[0] != '-') {
4957 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4958 } else {
4959 const QEMUOption *popt;
4961 optind++;
4962 /* Treat --foo the same as -foo. */
4963 if (r[1] == '-')
4964 r++;
4965 popt = qemu_options;
4966 for(;;) {
4967 if (!popt->name) {
4968 fprintf(stderr, "%s: invalid option -- '%s'\n",
4969 argv[0], r);
4970 exit(1);
4972 if (!strcmp(popt->name, r + 1))
4973 break;
4974 popt++;
4976 if (popt->flags & HAS_ARG) {
4977 if (optind >= argc) {
4978 fprintf(stderr, "%s: option '%s' requires an argument\n",
4979 argv[0], r);
4980 exit(1);
4982 optarg = argv[optind++];
4983 } else {
4984 optarg = NULL;
4987 switch(popt->index) {
4988 case QEMU_OPTION_M:
4989 machine = find_machine(optarg);
4990 if (!machine) {
4991 QEMUMachine *m;
4992 printf("Supported machines are:\n");
4993 for(m = first_machine; m != NULL; m = m->next) {
4994 printf("%-10s %s%s\n",
4995 m->name, m->desc,
4996 m == first_machine ? " (default)" : "");
4998 exit(*optarg != '?');
5000 break;
5001 case QEMU_OPTION_cpu:
5002 /* hw initialization will check this */
5003 if (*optarg == '?') {
5004 /* XXX: implement xxx_cpu_list for targets that still miss it */
5005 #if defined(cpu_list)
5006 cpu_list(stdout, &fprintf);
5007 #endif
5008 exit(0);
5009 } else {
5010 cpu_model = optarg;
5012 break;
5013 case QEMU_OPTION_initrd:
5014 initrd_filename = optarg;
5015 break;
5016 case QEMU_OPTION_hda:
5017 if (cyls == 0)
5018 hda_index = drive_add(optarg, HD_ALIAS, 0);
5019 else
5020 hda_index = drive_add(optarg, HD_ALIAS
5021 ",cyls=%d,heads=%d,secs=%d%s",
5022 0, cyls, heads, secs,
5023 translation == BIOS_ATA_TRANSLATION_LBA ?
5024 ",trans=lba" :
5025 translation == BIOS_ATA_TRANSLATION_NONE ?
5026 ",trans=none" : "");
5027 break;
5028 case QEMU_OPTION_hdb:
5029 case QEMU_OPTION_hdc:
5030 case QEMU_OPTION_hdd:
5031 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5032 break;
5033 case QEMU_OPTION_drive:
5034 drive_add(NULL, "%s", optarg);
5035 break;
5036 case QEMU_OPTION_mtdblock:
5037 drive_add(optarg, MTD_ALIAS);
5038 break;
5039 case QEMU_OPTION_sd:
5040 drive_add(optarg, SD_ALIAS);
5041 break;
5042 case QEMU_OPTION_pflash:
5043 drive_add(optarg, PFLASH_ALIAS);
5044 break;
5045 case QEMU_OPTION_snapshot:
5046 snapshot = 1;
5047 break;
5048 case QEMU_OPTION_hdachs:
5050 const char *p;
5051 p = optarg;
5052 cyls = strtol(p, (char **)&p, 0);
5053 if (cyls < 1 || cyls > 16383)
5054 goto chs_fail;
5055 if (*p != ',')
5056 goto chs_fail;
5057 p++;
5058 heads = strtol(p, (char **)&p, 0);
5059 if (heads < 1 || heads > 16)
5060 goto chs_fail;
5061 if (*p != ',')
5062 goto chs_fail;
5063 p++;
5064 secs = strtol(p, (char **)&p, 0);
5065 if (secs < 1 || secs > 63)
5066 goto chs_fail;
5067 if (*p == ',') {
5068 p++;
5069 if (!strcmp(p, "none"))
5070 translation = BIOS_ATA_TRANSLATION_NONE;
5071 else if (!strcmp(p, "lba"))
5072 translation = BIOS_ATA_TRANSLATION_LBA;
5073 else if (!strcmp(p, "auto"))
5074 translation = BIOS_ATA_TRANSLATION_AUTO;
5075 else
5076 goto chs_fail;
5077 } else if (*p != '\0') {
5078 chs_fail:
5079 fprintf(stderr, "qemu: invalid physical CHS format\n");
5080 exit(1);
5082 if (hda_index != -1)
5083 snprintf(drives_opt[hda_index].opt,
5084 sizeof(drives_opt[hda_index].opt),
5085 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5086 0, cyls, heads, secs,
5087 translation == BIOS_ATA_TRANSLATION_LBA ?
5088 ",trans=lba" :
5089 translation == BIOS_ATA_TRANSLATION_NONE ?
5090 ",trans=none" : "");
5092 break;
5093 case QEMU_OPTION_nographic:
5094 nographic = 1;
5095 break;
5096 #ifdef CONFIG_CURSES
5097 case QEMU_OPTION_curses:
5098 curses = 1;
5099 break;
5100 #endif
5101 case QEMU_OPTION_portrait:
5102 graphic_rotate = 1;
5103 break;
5104 case QEMU_OPTION_kernel:
5105 kernel_filename = optarg;
5106 break;
5107 case QEMU_OPTION_append:
5108 kernel_cmdline = optarg;
5109 break;
5110 case QEMU_OPTION_cdrom:
5111 drive_add(optarg, CDROM_ALIAS);
5112 break;
5113 case QEMU_OPTION_boot:
5114 boot_devices = optarg;
5115 /* We just do some generic consistency checks */
5117 /* Could easily be extended to 64 devices if needed */
5118 const char *p;
5120 boot_devices_bitmap = 0;
5121 for (p = boot_devices; *p != '\0'; p++) {
5122 /* Allowed boot devices are:
5123 * a b : floppy disk drives
5124 * c ... f : IDE disk drives
5125 * g ... m : machine implementation dependant drives
5126 * n ... p : network devices
5127 * It's up to each machine implementation to check
5128 * if the given boot devices match the actual hardware
5129 * implementation and firmware features.
5131 if (*p < 'a' || *p > 'q') {
5132 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5133 exit(1);
5135 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5136 fprintf(stderr,
5137 "Boot device '%c' was given twice\n",*p);
5138 exit(1);
5140 boot_devices_bitmap |= 1 << (*p - 'a');
5143 break;
5144 case QEMU_OPTION_fda:
5145 case QEMU_OPTION_fdb:
5146 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5147 break;
5148 #ifdef TARGET_I386
5149 case QEMU_OPTION_no_fd_bootchk:
5150 fd_bootchk = 0;
5151 break;
5152 #endif
5153 case QEMU_OPTION_net:
5154 if (nb_net_clients >= MAX_NET_CLIENTS) {
5155 fprintf(stderr, "qemu: too many network clients\n");
5156 exit(1);
5158 net_clients[nb_net_clients] = optarg;
5159 nb_net_clients++;
5160 break;
5161 #ifdef CONFIG_SLIRP
5162 case QEMU_OPTION_tftp:
5163 tftp_prefix = optarg;
5164 break;
5165 case QEMU_OPTION_bootp:
5166 bootp_filename = optarg;
5167 break;
5168 #ifndef _WIN32
5169 case QEMU_OPTION_smb:
5170 net_slirp_smb(optarg);
5171 break;
5172 #endif
5173 case QEMU_OPTION_redir:
5174 net_slirp_redir(optarg);
5175 break;
5176 #endif
5177 case QEMU_OPTION_bt:
5178 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5179 fprintf(stderr, "qemu: too many bluetooth options\n");
5180 exit(1);
5182 bt_opts[nb_bt_opts++] = optarg;
5183 break;
5184 #ifdef HAS_AUDIO
5185 case QEMU_OPTION_audio_help:
5186 AUD_help ();
5187 exit (0);
5188 break;
5189 case QEMU_OPTION_soundhw:
5190 select_soundhw (optarg);
5191 break;
5192 #endif
5193 case QEMU_OPTION_h:
5194 help(0);
5195 break;
5196 case QEMU_OPTION_m: {
5197 uint64_t value;
5198 char *ptr;
5200 value = strtoul(optarg, &ptr, 10);
5201 switch (*ptr) {
5202 case 0: case 'M': case 'm':
5203 value <<= 20;
5204 break;
5205 case 'G': case 'g':
5206 value <<= 30;
5207 break;
5208 default:
5209 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5210 exit(1);
5213 /* On 32-bit hosts, QEMU is limited by virtual address space */
5214 if (value > (2047 << 20)
5215 #ifndef USE_KQEMU
5216 && HOST_LONG_BITS == 32
5217 #endif
5219 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5220 exit(1);
5222 if (value != (uint64_t)(ram_addr_t)value) {
5223 fprintf(stderr, "qemu: ram size too large\n");
5224 exit(1);
5226 ram_size = value;
5227 break;
5229 case QEMU_OPTION_d:
5231 int mask;
5232 const CPULogItem *item;
5234 mask = cpu_str_to_log_mask(optarg);
5235 if (!mask) {
5236 printf("Log items (comma separated):\n");
5237 for(item = cpu_log_items; item->mask != 0; item++) {
5238 printf("%-10s %s\n", item->name, item->help);
5240 exit(1);
5242 cpu_set_log(mask);
5244 break;
5245 #ifdef CONFIG_GDBSTUB
5246 case QEMU_OPTION_s:
5247 use_gdbstub = 1;
5248 break;
5249 case QEMU_OPTION_p:
5250 gdbstub_port = optarg;
5251 break;
5252 #endif
5253 case QEMU_OPTION_L:
5254 bios_dir = optarg;
5255 break;
5256 case QEMU_OPTION_bios:
5257 bios_name = optarg;
5258 break;
5259 case QEMU_OPTION_S:
5260 autostart = 0;
5261 break;
5262 case QEMU_OPTION_k:
5263 keyboard_layout = optarg;
5264 break;
5265 case QEMU_OPTION_localtime:
5266 rtc_utc = 0;
5267 break;
5268 case QEMU_OPTION_vga:
5269 select_vgahw (optarg);
5270 break;
5271 case QEMU_OPTION_g:
5273 const char *p;
5274 int w, h, depth;
5275 p = optarg;
5276 w = strtol(p, (char **)&p, 10);
5277 if (w <= 0) {
5278 graphic_error:
5279 fprintf(stderr, "qemu: invalid resolution or depth\n");
5280 exit(1);
5282 if (*p != 'x')
5283 goto graphic_error;
5284 p++;
5285 h = strtol(p, (char **)&p, 10);
5286 if (h <= 0)
5287 goto graphic_error;
5288 if (*p == 'x') {
5289 p++;
5290 depth = strtol(p, (char **)&p, 10);
5291 if (depth != 8 && depth != 15 && depth != 16 &&
5292 depth != 24 && depth != 32)
5293 goto graphic_error;
5294 } else if (*p == '\0') {
5295 depth = graphic_depth;
5296 } else {
5297 goto graphic_error;
5300 graphic_width = w;
5301 graphic_height = h;
5302 graphic_depth = depth;
5304 break;
5305 case QEMU_OPTION_echr:
5307 char *r;
5308 term_escape_char = strtol(optarg, &r, 0);
5309 if (r == optarg)
5310 printf("Bad argument to echr\n");
5311 break;
5313 case QEMU_OPTION_monitor:
5314 monitor_device = optarg;
5315 break;
5316 case QEMU_OPTION_serial:
5317 if (serial_device_index >= MAX_SERIAL_PORTS) {
5318 fprintf(stderr, "qemu: too many serial ports\n");
5319 exit(1);
5321 serial_devices[serial_device_index] = optarg;
5322 serial_device_index++;
5323 break;
5324 case QEMU_OPTION_virtiocon:
5325 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5326 fprintf(stderr, "qemu: too many virtio consoles\n");
5327 exit(1);
5329 virtio_consoles[virtio_console_index] = optarg;
5330 virtio_console_index++;
5331 break;
5332 case QEMU_OPTION_parallel:
5333 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5334 fprintf(stderr, "qemu: too many parallel ports\n");
5335 exit(1);
5337 parallel_devices[parallel_device_index] = optarg;
5338 parallel_device_index++;
5339 break;
5340 case QEMU_OPTION_loadvm:
5341 loadvm = optarg;
5342 break;
5343 case QEMU_OPTION_full_screen:
5344 full_screen = 1;
5345 break;
5346 #ifdef CONFIG_SDL
5347 case QEMU_OPTION_no_frame:
5348 no_frame = 1;
5349 break;
5350 case QEMU_OPTION_alt_grab:
5351 alt_grab = 1;
5352 break;
5353 case QEMU_OPTION_no_quit:
5354 no_quit = 1;
5355 break;
5356 case QEMU_OPTION_sdl:
5357 sdl = 1;
5358 break;
5359 #endif
5360 case QEMU_OPTION_pidfile:
5361 pid_file = optarg;
5362 break;
5363 #ifdef TARGET_I386
5364 case QEMU_OPTION_win2k_hack:
5365 win2k_install_hack = 1;
5366 break;
5367 case QEMU_OPTION_rtc_td_hack:
5368 rtc_td_hack = 1;
5369 break;
5370 #endif
5371 #ifdef USE_KQEMU
5372 case QEMU_OPTION_no_kqemu:
5373 kqemu_allowed = 0;
5374 break;
5375 case QEMU_OPTION_kernel_kqemu:
5376 kqemu_allowed = 2;
5377 break;
5378 #endif
5379 #ifdef CONFIG_KVM
5380 case QEMU_OPTION_enable_kvm:
5381 kvm_allowed = 1;
5382 #ifdef USE_KQEMU
5383 kqemu_allowed = 0;
5384 #endif
5385 break;
5386 #endif
5387 #ifdef USE_KVM
5388 case QEMU_OPTION_no_kvm:
5389 kvm_allowed = 0;
5390 break;
5391 case QEMU_OPTION_no_kvm_irqchip: {
5392 kvm_irqchip = 0;
5393 kvm_pit = 0;
5394 break;
5396 case QEMU_OPTION_no_kvm_pit: {
5397 kvm_pit = 0;
5398 break;
5400 case QEMU_OPTION_no_kvm_pit_reinjection: {
5401 kvm_pit_reinject = 0;
5402 break;
5404 case QEMU_OPTION_enable_nesting: {
5405 kvm_nested = 1;
5406 break;
5408 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5409 case QEMU_OPTION_pcidevice:
5410 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5411 fprintf(stderr, "Too many assigned devices\n");
5412 exit(1);
5414 assigned_devices[assigned_devices_index] = optarg;
5415 assigned_devices_index++;
5416 break;
5417 #endif
5418 #endif
5419 case QEMU_OPTION_usb:
5420 usb_enabled = 1;
5421 break;
5422 case QEMU_OPTION_usbdevice:
5423 usb_enabled = 1;
5424 if (usb_devices_index >= MAX_USB_CMDLINE) {
5425 fprintf(stderr, "Too many USB devices\n");
5426 exit(1);
5428 usb_devices[usb_devices_index] = optarg;
5429 usb_devices_index++;
5430 break;
5431 case QEMU_OPTION_smp:
5432 smp_cpus = atoi(optarg);
5433 if (smp_cpus < 1) {
5434 fprintf(stderr, "Invalid number of CPUs\n");
5435 exit(1);
5437 break;
5438 case QEMU_OPTION_vnc:
5439 vnc_display = optarg;
5440 break;
5441 case QEMU_OPTION_no_acpi:
5442 acpi_enabled = 0;
5443 break;
5444 case QEMU_OPTION_no_hpet:
5445 no_hpet = 1;
5446 break;
5447 case QEMU_OPTION_no_reboot:
5448 no_reboot = 1;
5449 break;
5450 case QEMU_OPTION_no_shutdown:
5451 no_shutdown = 1;
5452 break;
5453 case QEMU_OPTION_show_cursor:
5454 cursor_hide = 0;
5455 break;
5456 case QEMU_OPTION_uuid:
5457 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5458 fprintf(stderr, "Fail to parse UUID string."
5459 " Wrong format.\n");
5460 exit(1);
5462 break;
5463 case QEMU_OPTION_daemonize:
5464 daemonize = 1;
5465 break;
5466 case QEMU_OPTION_option_rom:
5467 if (nb_option_roms >= MAX_OPTION_ROMS) {
5468 fprintf(stderr, "Too many option ROMs\n");
5469 exit(1);
5471 option_rom[nb_option_roms] = optarg;
5472 nb_option_roms++;
5473 break;
5474 case QEMU_OPTION_semihosting:
5475 semihosting_enabled = 1;
5476 break;
5477 case QEMU_OPTION_tdf:
5478 time_drift_fix = 1;
5479 break;
5480 case QEMU_OPTION_kvm_shadow_memory:
5481 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5482 break;
5483 case QEMU_OPTION_mempath:
5484 mem_path = optarg;
5485 break;
5486 case QEMU_OPTION_name:
5487 qemu_name = optarg;
5488 break;
5489 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5490 case QEMU_OPTION_prom_env:
5491 if (nb_prom_envs >= MAX_PROM_ENVS) {
5492 fprintf(stderr, "Too many prom variables\n");
5493 exit(1);
5495 prom_envs[nb_prom_envs] = optarg;
5496 nb_prom_envs++;
5497 break;
5498 #endif
5499 case QEMU_OPTION_cpu_vendor:
5500 cpu_vendor_string = optarg;
5501 break;
5502 #ifdef TARGET_ARM
5503 case QEMU_OPTION_old_param:
5504 old_param = 1;
5505 break;
5506 #endif
5507 case QEMU_OPTION_clock:
5508 configure_alarms(optarg);
5509 break;
5510 case QEMU_OPTION_startdate:
5512 struct tm tm;
5513 time_t rtc_start_date;
5514 if (!strcmp(optarg, "now")) {
5515 rtc_date_offset = -1;
5516 } else {
5517 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5518 &tm.tm_year,
5519 &tm.tm_mon,
5520 &tm.tm_mday,
5521 &tm.tm_hour,
5522 &tm.tm_min,
5523 &tm.tm_sec) == 6) {
5524 /* OK */
5525 } else if (sscanf(optarg, "%d-%d-%d",
5526 &tm.tm_year,
5527 &tm.tm_mon,
5528 &tm.tm_mday) == 3) {
5529 tm.tm_hour = 0;
5530 tm.tm_min = 0;
5531 tm.tm_sec = 0;
5532 } else {
5533 goto date_fail;
5535 tm.tm_year -= 1900;
5536 tm.tm_mon--;
5537 rtc_start_date = mktimegm(&tm);
5538 if (rtc_start_date == -1) {
5539 date_fail:
5540 fprintf(stderr, "Invalid date format. Valid format are:\n"
5541 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5542 exit(1);
5544 rtc_date_offset = time(NULL) - rtc_start_date;
5547 break;
5548 case QEMU_OPTION_tb_size:
5549 tb_size = strtol(optarg, NULL, 0);
5550 if (tb_size < 0)
5551 tb_size = 0;
5552 break;
5553 case QEMU_OPTION_icount:
5554 use_icount = 1;
5555 if (strcmp(optarg, "auto") == 0) {
5556 icount_time_shift = -1;
5557 } else {
5558 icount_time_shift = strtol(optarg, NULL, 0);
5560 break;
5561 case QEMU_OPTION_incoming:
5562 incoming = optarg;
5563 break;
5564 case QEMU_OPTION_nvram:
5565 nvram = optarg;
5566 break;
5571 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5572 if (kvm_allowed && kqemu_allowed) {
5573 fprintf(stderr,
5574 "You can not enable both KVM and kqemu at the same time\n");
5575 exit(1);
5577 #endif
5579 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5580 if (smp_cpus > machine->max_cpus) {
5581 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5582 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5583 machine->max_cpus);
5584 exit(1);
5587 if (nographic) {
5588 if (serial_device_index == 0)
5589 serial_devices[0] = "stdio";
5590 if (parallel_device_index == 0)
5591 parallel_devices[0] = "null";
5592 if (strncmp(monitor_device, "vc", 2) == 0)
5593 monitor_device = "stdio";
5594 if (virtio_console_index == 0)
5595 virtio_consoles[0] = "null";
5598 #ifndef _WIN32
5599 if (daemonize) {
5600 pid_t pid;
5602 if (pipe(fds) == -1)
5603 exit(1);
5605 pid = fork();
5606 if (pid > 0) {
5607 uint8_t status;
5608 ssize_t len;
5610 close(fds[1]);
5612 again:
5613 len = read(fds[0], &status, 1);
5614 if (len == -1 && (errno == EINTR))
5615 goto again;
5617 if (len != 1)
5618 exit(1);
5619 else if (status == 1) {
5620 fprintf(stderr, "Could not acquire pidfile\n");
5621 exit(1);
5622 } else
5623 exit(0);
5624 } else if (pid < 0)
5625 exit(1);
5627 setsid();
5629 pid = fork();
5630 if (pid > 0)
5631 exit(0);
5632 else if (pid < 0)
5633 exit(1);
5635 umask(027);
5637 signal(SIGTSTP, SIG_IGN);
5638 signal(SIGTTOU, SIG_IGN);
5639 signal(SIGTTIN, SIG_IGN);
5641 #endif
5643 #if USE_KVM
5644 if (kvm_enabled()) {
5645 if (kvm_qemu_init() < 0) {
5646 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5647 #ifdef NO_CPU_EMULATION
5648 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5649 exit(1);
5650 #endif
5651 kvm_allowed = 0;
5654 #endif
5656 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5657 if (daemonize) {
5658 uint8_t status = 1;
5659 write(fds[1], &status, 1);
5660 } else
5661 fprintf(stderr, "Could not acquire pid file\n");
5662 exit(1);
5665 #ifdef USE_KQEMU
5666 if (smp_cpus > 1)
5667 kqemu_allowed = 0;
5668 #endif
5669 linux_boot = (kernel_filename != NULL);
5670 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5672 if (!linux_boot && net_boot == 0 &&
5673 !machine->nodisk_ok && nb_drives_opt == 0)
5674 help(1);
5676 if (!linux_boot && *kernel_cmdline != '\0') {
5677 fprintf(stderr, "-append only allowed with -kernel option\n");
5678 exit(1);
5681 if (!linux_boot && initrd_filename != NULL) {
5682 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5683 exit(1);
5686 /* boot to floppy or the default cd if no hard disk defined yet */
5687 if (!boot_devices[0]) {
5688 boot_devices = "cad";
5690 setvbuf(stdout, NULL, _IOLBF, 0);
5692 init_timers();
5693 if (init_timer_alarm() < 0) {
5694 fprintf(stderr, "could not initialize alarm timer\n");
5695 exit(1);
5697 if (use_icount && icount_time_shift < 0) {
5698 use_icount = 2;
5699 /* 125MIPS seems a reasonable initial guess at the guest speed.
5700 It will be corrected fairly quickly anyway. */
5701 icount_time_shift = 3;
5702 init_icount_adjust();
5705 #ifdef _WIN32
5706 socket_init();
5707 #endif
5709 /* init network clients */
5710 if (nb_net_clients == 0) {
5711 /* if no clients, we use a default config */
5712 net_clients[nb_net_clients++] = "nic";
5713 #ifdef CONFIG_SLIRP
5714 net_clients[nb_net_clients++] = "user";
5715 #endif
5718 for(i = 0;i < nb_net_clients; i++) {
5719 if (net_client_parse(net_clients[i]) < 0)
5720 exit(1);
5722 net_client_check();
5724 #ifdef TARGET_I386
5725 /* XXX: this should be moved in the PC machine instantiation code */
5726 if (net_boot != 0) {
5727 int netroms = 0;
5728 for (i = 0; i < nb_nics && i < 4; i++) {
5729 const char *model = nd_table[i].model;
5730 char buf[1024];
5731 if (net_boot & (1 << i)) {
5732 if (model == NULL)
5733 model = "rtl8139";
5734 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5735 if (get_image_size(buf) > 0) {
5736 if (nb_option_roms >= MAX_OPTION_ROMS) {
5737 fprintf(stderr, "Too many option ROMs\n");
5738 exit(1);
5740 option_rom[nb_option_roms] = strdup(buf);
5741 nb_option_roms++;
5742 netroms++;
5746 if (netroms == 0) {
5747 fprintf(stderr, "No valid PXE rom found for network device\n");
5748 exit(1);
5751 #endif
5753 /* init the bluetooth world */
5754 for (i = 0; i < nb_bt_opts; i++)
5755 if (bt_parse(bt_opts[i]))
5756 exit(1);
5758 /* init the memory */
5759 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5761 if (machine->ram_require & RAMSIZE_FIXED) {
5762 if (ram_size > 0) {
5763 if (ram_size < phys_ram_size) {
5764 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5765 machine->name, (unsigned long long) phys_ram_size);
5766 exit(-1);
5769 phys_ram_size = ram_size;
5770 } else
5771 ram_size = phys_ram_size;
5772 } else {
5773 if (ram_size == 0)
5774 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5776 phys_ram_size += ram_size;
5779 /* Initialize kvm */
5780 #if defined(TARGET_I386) || defined(TARGET_X86_64)
5781 #define KVM_EXTRA_PAGES 3
5782 #else
5783 #define KVM_EXTRA_PAGES 0
5784 #endif
5785 if (kvm_enabled()) {
5786 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
5787 if (kvm_qemu_create_context() < 0) {
5788 fprintf(stderr, "Could not create KVM context\n");
5789 exit(1);
5793 phys_ram_base = qemu_alloc_physram(phys_ram_size);
5794 if (!phys_ram_base) {
5795 fprintf(stderr, "Could not allocate physical memory\n");
5796 exit(1);
5799 /* init the dynamic translator */
5800 cpu_exec_init_all(tb_size * 1024 * 1024);
5802 bdrv_init();
5804 /* we always create the cdrom drive, even if no disk is there */
5806 if (nb_drives_opt < MAX_DRIVES)
5807 drive_add(NULL, CDROM_ALIAS);
5809 /* we always create at least one floppy */
5811 if (nb_drives_opt < MAX_DRIVES)
5812 drive_add(NULL, FD_ALIAS, 0);
5814 /* we always create one sd slot, even if no card is in it */
5816 if (nb_drives_opt < MAX_DRIVES)
5817 drive_add(NULL, SD_ALIAS);
5819 /* open the virtual block devices
5820 * note that migration with device
5821 * hot add/remove is broken.
5823 for(i = 0; i < nb_drives_opt; i++)
5824 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5825 exit(1);
5827 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5828 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5830 #ifndef _WIN32
5831 /* must be after terminal init, SDL library changes signal handlers */
5832 termsig_setup();
5833 #endif
5835 /* Maintain compatibility with multiple stdio monitors */
5836 if (!strcmp(monitor_device,"stdio")) {
5837 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5838 const char *devname = serial_devices[i];
5839 if (devname && !strcmp(devname,"mon:stdio")) {
5840 monitor_device = NULL;
5841 break;
5842 } else if (devname && !strcmp(devname,"stdio")) {
5843 monitor_device = NULL;
5844 serial_devices[i] = "mon:stdio";
5845 break;
5850 #ifdef KVM_UPSTREAM
5851 if (kvm_enabled()) {
5852 int ret;
5854 ret = kvm_init(smp_cpus);
5855 if (ret < 0) {
5856 fprintf(stderr, "failed to initialize KVM\n");
5857 exit(1);
5860 #endif
5862 if (monitor_device) {
5863 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5864 if (!monitor_hd) {
5865 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5866 exit(1);
5870 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5871 const char *devname = serial_devices[i];
5872 if (devname && strcmp(devname, "none")) {
5873 char label[32];
5874 snprintf(label, sizeof(label), "serial%d", i);
5875 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5876 if (!serial_hds[i]) {
5877 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5878 devname);
5879 exit(1);
5884 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5885 const char *devname = parallel_devices[i];
5886 if (devname && strcmp(devname, "none")) {
5887 char label[32];
5888 snprintf(label, sizeof(label), "parallel%d", i);
5889 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5890 if (!parallel_hds[i]) {
5891 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5892 devname);
5893 exit(1);
5898 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5899 const char *devname = virtio_consoles[i];
5900 if (devname && strcmp(devname, "none")) {
5901 char label[32];
5902 snprintf(label, sizeof(label), "virtcon%d", i);
5903 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5904 if (!virtcon_hds[i]) {
5905 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5906 devname);
5907 exit(1);
5912 if (kvm_enabled())
5913 kvm_init_ap();
5915 machine->init(ram_size, vga_ram_size, boot_devices,
5916 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5918 current_machine = machine;
5920 /* Set KVM's vcpu state to qemu's initial CPUState. */
5921 if (kvm_enabled()) {
5922 int ret;
5924 ret = kvm_sync_vcpus();
5925 if (ret < 0) {
5926 fprintf(stderr, "failed to initialize vcpus\n");
5927 exit(1);
5931 /* init USB devices */
5932 if (usb_enabled) {
5933 for(i = 0; i < usb_devices_index; i++) {
5934 if (usb_device_add(usb_devices[i]) < 0) {
5935 fprintf(stderr, "Warning: could not add USB device %s\n",
5936 usb_devices[i]);
5941 if (!display_state)
5942 dumb_display_init();
5943 /* just use the first displaystate for the moment */
5944 ds = display_state;
5945 /* terminal init */
5946 if (nographic) {
5947 if (curses) {
5948 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5949 exit(1);
5951 } else {
5952 #if defined(CONFIG_CURSES)
5953 if (curses) {
5954 /* At the moment curses cannot be used with other displays */
5955 curses_display_init(ds, full_screen);
5956 } else
5957 #endif
5959 if (vnc_display != NULL) {
5960 vnc_display_init(ds);
5961 if (vnc_display_open(ds, vnc_display) < 0)
5962 exit(1);
5964 #if defined(CONFIG_SDL)
5965 if (sdl || !vnc_display)
5966 sdl_display_init(ds, full_screen, no_frame);
5967 #elif defined(CONFIG_COCOA)
5968 if (sdl || !vnc_display)
5969 cocoa_display_init(ds, full_screen);
5970 #endif
5973 dpy_resize(ds);
5975 dcl = ds->listeners;
5976 while (dcl != NULL) {
5977 if (dcl->dpy_refresh != NULL) {
5978 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5979 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5981 dcl = dcl->next;
5984 if (nographic || (vnc_display && !sdl)) {
5985 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5986 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5989 text_consoles_set_display(display_state);
5991 if (monitor_device && monitor_hd)
5992 monitor_init(monitor_hd, !nographic);
5994 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5995 const char *devname = serial_devices[i];
5996 if (devname && strcmp(devname, "none")) {
5997 char label[32];
5998 snprintf(label, sizeof(label), "serial%d", i);
5999 if (strstart(devname, "vc", 0))
6000 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6004 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6005 const char *devname = parallel_devices[i];
6006 if (devname && strcmp(devname, "none")) {
6007 char label[32];
6008 snprintf(label, sizeof(label), "parallel%d", i);
6009 if (strstart(devname, "vc", 0))
6010 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6014 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6015 const char *devname = virtio_consoles[i];
6016 if (virtcon_hds[i] && devname) {
6017 char label[32];
6018 snprintf(label, sizeof(label), "virtcon%d", i);
6019 if (strstart(devname, "vc", 0))
6020 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6024 #ifdef CONFIG_GDBSTUB
6025 if (use_gdbstub) {
6026 /* XXX: use standard host:port notation and modify options
6027 accordingly. */
6028 if (gdbserver_start(gdbstub_port) < 0) {
6029 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
6030 gdbstub_port);
6031 exit(1);
6034 #endif
6036 if (loadvm)
6037 do_loadvm(loadvm);
6039 if (incoming) {
6040 autostart = 0; /* fixme how to deal with -daemonize */
6041 qemu_start_incoming_migration(incoming);
6045 /* XXX: simplify init */
6046 read_passwords();
6047 if (autostart) {
6048 vm_start();
6052 if (daemonize) {
6053 uint8_t status = 0;
6054 ssize_t len;
6055 int fd;
6057 again1:
6058 len = write(fds[1], &status, 1);
6059 if (len == -1 && (errno == EINTR))
6060 goto again1;
6062 if (len != 1)
6063 exit(1);
6065 chdir("/");
6066 TFR(fd = open("/dev/null", O_RDWR));
6067 if (fd == -1)
6068 exit(1);
6070 dup2(fd, 0);
6071 dup2(fd, 1);
6072 dup2(fd, 2);
6074 close(fd);
6077 main_loop();
6078 quit_timers();
6079 net_cleanup();
6081 return 0;