kvm: testsuite: fix warning in msr.c
[qemu-kvm/fedora.git] / vl.c
blob9e02a43f1e2be4b20e4c5fa71a8f51fee10780d8
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.
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <signal.h>
28 #include <time.h>
29 #include <errno.h>
30 #include <sys/time.h>
31 #include <zlib.h>
33 /* Needed early for HOST_BSD etc. */
34 #include "config-host.h"
36 #ifndef _WIN32
37 #include <pwd.h>
38 #include <sys/times.h>
39 #include <sys/wait.h>
40 #include <termios.h>
41 #include <sys/mman.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <sys/vfs.h>
46 #include <netinet/in.h>
47 #include <net/if.h>
48 #if defined(__NetBSD__)
49 #include <net/if_tap.h>
50 #endif
51 #ifdef __linux__
52 #include <linux/if_tun.h>
53 #endif
54 #include <arpa/inet.h>
55 #include <dirent.h>
56 #include <netdb.h>
57 #include <sys/select.h>
58 #ifdef HOST_BSD
59 #include <sys/stat.h>
60 #if defined(__FreeBSD__) || defined(__DragonFly__)
61 #include <libutil.h>
62 #else
63 #include <util.h>
64 #endif
65 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
66 #include <freebsd/stdlib.h>
67 #else
68 #ifdef __linux__
69 #include <pty.h>
70 #include <malloc.h>
71 #include <linux/rtc.h>
73 /* For the benefit of older linux systems which don't supply it,
74 we use a local copy of hpet.h. */
75 /* #include <linux/hpet.h> */
76 #include "hpet.h"
78 #include <linux/ppdev.h>
79 #include <linux/parport.h>
80 #endif
81 #ifdef __sun__
82 #include <sys/stat.h>
83 #include <sys/ethernet.h>
84 #include <sys/sockio.h>
85 #include <netinet/arp.h>
86 #include <netinet/in.h>
87 #include <netinet/in_systm.h>
88 #include <netinet/ip.h>
89 #include <netinet/ip_icmp.h> // must come after ip.h
90 #include <netinet/udp.h>
91 #include <netinet/tcp.h>
92 #include <net/if.h>
93 #include <syslog.h>
94 #include <stropts.h>
95 #endif
96 #endif
97 #endif
99 #if defined(__OpenBSD__)
100 #include <util.h>
101 #endif
103 #if defined(CONFIG_VDE)
104 #include <libvdeplug.h>
105 #endif
107 #ifdef _WIN32
108 #include <windows.h>
109 #include <malloc.h>
110 #include <sys/timeb.h>
111 #include <mmsystem.h>
112 #define getopt_long_only getopt_long
113 #define memalign(align, size) malloc(size)
114 #endif
116 #ifdef CONFIG_SDL
117 #ifdef __APPLE__
118 #include <SDL/SDL.h>
119 int qemu_main(int argc, char **argv, char **envp);
120 int main(int argc, char **argv)
122 qemu_main(argc, argv, NULL);
124 #undef main
125 #define main qemu_main
126 #endif
127 #endif /* CONFIG_SDL */
129 #ifdef CONFIG_COCOA
130 #undef main
131 #define main qemu_main
132 #endif /* CONFIG_COCOA */
134 #include "hw/hw.h"
135 #include "hw/boards.h"
136 #include "hw/usb.h"
137 #include "hw/pcmcia.h"
138 #include "hw/pc.h"
139 #include "hw/audiodev.h"
140 #include "hw/isa.h"
141 #include "hw/baum.h"
142 #include "hw/bt.h"
143 #include "bt-host.h"
144 #include "net.h"
145 #include "monitor.h"
146 #include "console.h"
147 #include "sysemu.h"
148 #include "gdbstub.h"
149 #include "qemu-timer.h"
150 #include "qemu-char.h"
151 #include "cache-utils.h"
152 #include "block.h"
153 #include "dma.h"
154 #include "audio/audio.h"
155 #include "migration.h"
156 #include "kvm.h"
157 #include "balloon.h"
158 #include "qemu-kvm.h"
159 #include "hw/device-assignment.h"
161 #include "disas.h"
163 #include "exec-all.h"
165 #include "qemu_socket.h"
167 #if defined(CONFIG_SLIRP)
168 #include "libslirp.h"
169 #endif
171 //#define DEBUG_UNUSED_IOPORT
172 //#define DEBUG_IOPORT
173 //#define DEBUG_NET
174 //#define DEBUG_SLIRP
177 #ifdef DEBUG_IOPORT
178 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
179 #else
180 # define LOG_IOPORT(...) do { } while (0)
181 #endif
183 #define DEFAULT_RAM_SIZE 128
185 /* Max number of USB devices that can be specified on the commandline. */
186 #define MAX_USB_CMDLINE 8
188 /* Max number of bluetooth switches on the commandline. */
189 #define MAX_BT_CMDLINE 10
191 /* XXX: use a two level table to limit memory usage */
192 #define MAX_IOPORTS 65536
194 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
195 const char *bios_name = NULL;
196 static void *ioport_opaque[MAX_IOPORTS];
197 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
198 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
199 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
200 to store the VM snapshots */
201 DriveInfo drives_table[MAX_DRIVES+1];
202 int nb_drives;
203 int extboot_drive = -1;
204 static int vga_ram_size;
205 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
206 static DisplayState *display_state;
207 int nographic;
208 static int curses;
209 static int sdl;
210 const char* keyboard_layout = NULL;
211 int64_t ticks_per_sec;
212 ram_addr_t ram_size;
213 int nb_nics;
214 NICInfo nd_table[MAX_NICS];
215 int vm_running;
216 static int autostart;
217 static int rtc_utc = 1;
218 static int rtc_date_offset = -1; /* -1 means no change */
219 int cirrus_vga_enabled = 1;
220 int std_vga_enabled = 0;
221 int vmsvga_enabled = 0;
222 #ifdef TARGET_SPARC
223 int graphic_width = 1024;
224 int graphic_height = 768;
225 int graphic_depth = 8;
226 #else
227 int graphic_width = 800;
228 int graphic_height = 600;
229 int graphic_depth = 15;
230 #endif
231 static int full_screen = 0;
232 #ifdef CONFIG_SDL
233 static int no_frame = 0;
234 #endif
235 int no_quit = 0;
236 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
237 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
238 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
239 #ifdef TARGET_I386
240 int win2k_install_hack = 0;
241 int rtc_td_hack = 0;
242 #endif
243 int usb_enabled = 0;
244 int singlestep = 0;
245 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
246 int assigned_devices_index;
247 int smp_cpus = 1;
248 const char *vnc_display;
249 int acpi_enabled = 1;
250 int no_hpet = 0;
251 int fd_bootchk = 1;
252 int no_reboot = 0;
253 int no_shutdown = 0;
254 int cursor_hide = 1;
255 int graphic_rotate = 0;
256 #ifndef _WIN32
257 int daemonize = 0;
258 #endif
259 const char *option_rom[MAX_OPTION_ROMS];
260 int nb_option_roms;
261 int semihosting_enabled = 0;
262 int time_drift_fix = 0;
263 unsigned int kvm_shadow_memory = 0;
264 const char *mem_path = NULL;
265 #ifdef MAP_POPULATE
266 int mem_prealloc = 1; /* force preallocation of physical target memory */
267 #endif
268 long hpagesize = 0;
269 const char *cpu_vendor_string;
270 #ifdef TARGET_ARM
271 int old_param = 0;
272 #endif
273 const char *qemu_name;
274 int alt_grab = 0;
275 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
276 unsigned int nb_prom_envs = 0;
277 const char *prom_envs[MAX_PROM_ENVS];
278 #endif
279 int nb_drives_opt;
280 const char *nvram = NULL;
281 struct drive_opt drives_opt[MAX_DRIVES];
283 static CPUState *cur_cpu;
284 static CPUState *next_cpu;
285 static int event_pending = 1;
286 /* Conversion factor from emulated instructions to virtual clock ticks. */
287 static int icount_time_shift;
288 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
289 #define MAX_ICOUNT_SHIFT 10
290 /* Compensate for varying guest execution speed. */
291 static int64_t qemu_icount_bias;
292 static QEMUTimer *icount_rt_timer;
293 static QEMUTimer *icount_vm_timer;
294 static QEMUTimer *nographic_timer;
296 uint8_t qemu_uuid[16];
298 /* KVM runs the main loop in a separate thread. If we update one of the lists
299 * that are polled before or after select(), we need to make sure to break out
300 * of the select() to ensure the new item is serviced.
302 static void main_loop_break(void)
304 if (kvm_enabled())
305 qemu_kvm_notify_work();
308 /***********************************************************/
309 /* x86 ISA bus support */
311 target_phys_addr_t isa_mem_base = 0;
312 PicState2 *isa_pic;
314 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
315 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
317 static uint32_t ioport_read(int index, uint32_t address)
319 static IOPortReadFunc *default_func[3] = {
320 default_ioport_readb,
321 default_ioport_readw,
322 default_ioport_readl
324 IOPortReadFunc *func = ioport_read_table[index][address];
325 if (!func)
326 func = default_func[index];
327 return func(ioport_opaque[address], address);
330 static void ioport_write(int index, uint32_t address, uint32_t data)
332 static IOPortWriteFunc *default_func[3] = {
333 default_ioport_writeb,
334 default_ioport_writew,
335 default_ioport_writel
337 IOPortWriteFunc *func = ioport_write_table[index][address];
338 if (!func)
339 func = default_func[index];
340 func(ioport_opaque[address], address, data);
343 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
345 #ifdef DEBUG_UNUSED_IOPORT
346 fprintf(stderr, "unused inb: port=0x%04x\n", address);
347 #endif
348 return 0xff;
351 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
353 #ifdef DEBUG_UNUSED_IOPORT
354 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
355 #endif
358 /* default is to make two byte accesses */
359 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
361 uint32_t data;
362 data = ioport_read(0, address);
363 address = (address + 1) & (MAX_IOPORTS - 1);
364 data |= ioport_read(0, address) << 8;
365 return data;
368 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
370 ioport_write(0, address, data & 0xff);
371 address = (address + 1) & (MAX_IOPORTS - 1);
372 ioport_write(0, address, (data >> 8) & 0xff);
375 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
377 #ifdef DEBUG_UNUSED_IOPORT
378 fprintf(stderr, "unused inl: port=0x%04x\n", address);
379 #endif
380 return 0xffffffff;
383 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
385 #ifdef DEBUG_UNUSED_IOPORT
386 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
387 #endif
390 /* size is the word size in byte */
391 int register_ioport_read(int start, int length, int size,
392 IOPortReadFunc *func, void *opaque)
394 int i, bsize;
396 if (size == 1) {
397 bsize = 0;
398 } else if (size == 2) {
399 bsize = 1;
400 } else if (size == 4) {
401 bsize = 2;
402 } else {
403 hw_error("register_ioport_read: invalid size");
404 return -1;
406 for(i = start; i < start + length; i += size) {
407 ioport_read_table[bsize][i] = func;
408 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
409 hw_error("register_ioport_read: invalid opaque");
410 ioport_opaque[i] = opaque;
412 return 0;
415 /* size is the word size in byte */
416 int register_ioport_write(int start, int length, int size,
417 IOPortWriteFunc *func, void *opaque)
419 int i, bsize;
421 if (size == 1) {
422 bsize = 0;
423 } else if (size == 2) {
424 bsize = 1;
425 } else if (size == 4) {
426 bsize = 2;
427 } else {
428 hw_error("register_ioport_write: invalid size");
429 return -1;
431 for(i = start; i < start + length; i += size) {
432 ioport_write_table[bsize][i] = func;
433 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
434 hw_error("register_ioport_write: invalid opaque");
435 ioport_opaque[i] = opaque;
437 return 0;
440 void isa_unassign_ioport(int start, int length)
442 int i;
444 for(i = start; i < start + length; i++) {
445 ioport_read_table[0][i] = default_ioport_readb;
446 ioport_read_table[1][i] = default_ioport_readw;
447 ioport_read_table[2][i] = default_ioport_readl;
449 ioport_write_table[0][i] = default_ioport_writeb;
450 ioport_write_table[1][i] = default_ioport_writew;
451 ioport_write_table[2][i] = default_ioport_writel;
453 ioport_opaque[i] = NULL;
457 /***********************************************************/
459 void cpu_outb(CPUState *env, int addr, int val)
461 LOG_IOPORT("outb: %04x %02x\n", addr, val);
462 ioport_write(0, addr, val);
463 #ifdef USE_KQEMU
464 if (env)
465 env->last_io_time = cpu_get_time_fast();
466 #endif
469 void cpu_outw(CPUState *env, int addr, int val)
471 LOG_IOPORT("outw: %04x %04x\n", addr, val);
472 ioport_write(1, addr, val);
473 #ifdef USE_KQEMU
474 if (env)
475 env->last_io_time = cpu_get_time_fast();
476 #endif
479 void cpu_outl(CPUState *env, int addr, int val)
481 LOG_IOPORT("outl: %04x %08x\n", addr, val);
482 ioport_write(2, addr, val);
483 #ifdef USE_KQEMU
484 if (env)
485 env->last_io_time = cpu_get_time_fast();
486 #endif
489 int cpu_inb(CPUState *env, int addr)
491 int val;
492 val = ioport_read(0, addr);
493 LOG_IOPORT("inb : %04x %02x\n", addr, val);
494 #ifdef USE_KQEMU
495 if (env)
496 env->last_io_time = cpu_get_time_fast();
497 #endif
498 return val;
501 int cpu_inw(CPUState *env, int addr)
503 int val;
504 val = ioport_read(1, addr);
505 LOG_IOPORT("inw : %04x %04x\n", addr, val);
506 #ifdef USE_KQEMU
507 if (env)
508 env->last_io_time = cpu_get_time_fast();
509 #endif
510 return val;
513 int cpu_inl(CPUState *env, int addr)
515 int val;
516 val = ioport_read(2, addr);
517 LOG_IOPORT("inl : %04x %08x\n", addr, val);
518 #ifdef USE_KQEMU
519 if (env)
520 env->last_io_time = cpu_get_time_fast();
521 #endif
522 return val;
525 /***********************************************************/
526 void hw_error(const char *fmt, ...)
528 va_list ap;
529 CPUState *env;
531 va_start(ap, fmt);
532 fprintf(stderr, "qemu: hardware error: ");
533 vfprintf(stderr, fmt, ap);
534 fprintf(stderr, "\n");
535 for(env = first_cpu; env != NULL; env = env->next_cpu) {
536 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
537 #ifdef TARGET_I386
538 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
539 #else
540 cpu_dump_state(env, stderr, fprintf, 0);
541 #endif
543 va_end(ap);
544 abort();
547 /***************/
548 /* ballooning */
550 static QEMUBalloonEvent *qemu_balloon_event;
551 void *qemu_balloon_event_opaque;
553 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
555 qemu_balloon_event = func;
556 qemu_balloon_event_opaque = opaque;
559 void qemu_balloon(ram_addr_t target)
561 if (qemu_balloon_event)
562 qemu_balloon_event(qemu_balloon_event_opaque, target);
565 ram_addr_t qemu_balloon_status(void)
567 if (qemu_balloon_event)
568 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
569 return 0;
572 /***********************************************************/
573 /* keyboard/mouse */
575 static QEMUPutKBDEvent *qemu_put_kbd_event;
576 static void *qemu_put_kbd_event_opaque;
577 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
578 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
580 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
582 qemu_put_kbd_event_opaque = opaque;
583 qemu_put_kbd_event = func;
586 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
587 void *opaque, int absolute,
588 const char *name)
590 QEMUPutMouseEntry *s, *cursor;
592 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
594 s->qemu_put_mouse_event = func;
595 s->qemu_put_mouse_event_opaque = opaque;
596 s->qemu_put_mouse_event_absolute = absolute;
597 s->qemu_put_mouse_event_name = qemu_strdup(name);
598 s->next = NULL;
600 if (!qemu_put_mouse_event_head) {
601 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
602 return s;
605 cursor = qemu_put_mouse_event_head;
606 while (cursor->next != NULL)
607 cursor = cursor->next;
609 cursor->next = s;
610 qemu_put_mouse_event_current = s;
612 return s;
615 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
617 QEMUPutMouseEntry *prev = NULL, *cursor;
619 if (!qemu_put_mouse_event_head || entry == NULL)
620 return;
622 cursor = qemu_put_mouse_event_head;
623 while (cursor != NULL && cursor != entry) {
624 prev = cursor;
625 cursor = cursor->next;
628 if (cursor == NULL) // does not exist or list empty
629 return;
630 else if (prev == NULL) { // entry is head
631 qemu_put_mouse_event_head = cursor->next;
632 if (qemu_put_mouse_event_current == entry)
633 qemu_put_mouse_event_current = cursor->next;
634 qemu_free(entry->qemu_put_mouse_event_name);
635 qemu_free(entry);
636 return;
639 prev->next = entry->next;
641 if (qemu_put_mouse_event_current == entry)
642 qemu_put_mouse_event_current = prev;
644 qemu_free(entry->qemu_put_mouse_event_name);
645 qemu_free(entry);
648 void kbd_put_keycode(int keycode)
650 if (qemu_put_kbd_event) {
651 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
655 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
657 QEMUPutMouseEvent *mouse_event;
658 void *mouse_event_opaque;
659 int width;
661 if (!qemu_put_mouse_event_current) {
662 return;
665 mouse_event =
666 qemu_put_mouse_event_current->qemu_put_mouse_event;
667 mouse_event_opaque =
668 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
670 if (mouse_event) {
671 if (graphic_rotate) {
672 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
673 width = 0x7fff;
674 else
675 width = graphic_width - 1;
676 mouse_event(mouse_event_opaque,
677 width - dy, dx, dz, buttons_state);
678 } else
679 mouse_event(mouse_event_opaque,
680 dx, dy, dz, buttons_state);
684 int kbd_mouse_is_absolute(void)
686 if (!qemu_put_mouse_event_current)
687 return 0;
689 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
692 void do_info_mice(Monitor *mon)
694 QEMUPutMouseEntry *cursor;
695 int index = 0;
697 if (!qemu_put_mouse_event_head) {
698 monitor_printf(mon, "No mouse devices connected\n");
699 return;
702 monitor_printf(mon, "Mouse devices available:\n");
703 cursor = qemu_put_mouse_event_head;
704 while (cursor != NULL) {
705 monitor_printf(mon, "%c Mouse #%d: %s\n",
706 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
707 index, cursor->qemu_put_mouse_event_name);
708 index++;
709 cursor = cursor->next;
713 void do_mouse_set(Monitor *mon, int index)
715 QEMUPutMouseEntry *cursor;
716 int i = 0;
718 if (!qemu_put_mouse_event_head) {
719 monitor_printf(mon, "No mouse devices connected\n");
720 return;
723 cursor = qemu_put_mouse_event_head;
724 while (cursor != NULL && index != i) {
725 i++;
726 cursor = cursor->next;
729 if (cursor != NULL)
730 qemu_put_mouse_event_current = cursor;
731 else
732 monitor_printf(mon, "Mouse at given index not found\n");
735 /* compute with 96 bit intermediate result: (a*b)/c */
736 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
738 union {
739 uint64_t ll;
740 struct {
741 #ifdef WORDS_BIGENDIAN
742 uint32_t high, low;
743 #else
744 uint32_t low, high;
745 #endif
746 } l;
747 } u, res;
748 uint64_t rl, rh;
750 u.ll = a;
751 rl = (uint64_t)u.l.low * (uint64_t)b;
752 rh = (uint64_t)u.l.high * (uint64_t)b;
753 rh += (rl >> 32);
754 res.l.high = rh / c;
755 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
756 return res.ll;
759 /***********************************************************/
760 /* real time host monotonic timer */
762 #define QEMU_TIMER_BASE 1000000000LL
764 #ifdef WIN32
766 static int64_t clock_freq;
768 static void init_get_clock(void)
770 LARGE_INTEGER freq;
771 int ret;
772 ret = QueryPerformanceFrequency(&freq);
773 if (ret == 0) {
774 fprintf(stderr, "Could not calibrate ticks\n");
775 exit(1);
777 clock_freq = freq.QuadPart;
780 static int64_t get_clock(void)
782 LARGE_INTEGER ti;
783 QueryPerformanceCounter(&ti);
784 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
787 #else
789 static int use_rt_clock;
791 static void init_get_clock(void)
793 use_rt_clock = 0;
794 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
795 || defined(__DragonFly__)
797 struct timespec ts;
798 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
799 use_rt_clock = 1;
802 #endif
805 static int64_t get_clock(void)
807 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
808 || defined(__DragonFly__)
809 if (use_rt_clock) {
810 struct timespec ts;
811 clock_gettime(CLOCK_MONOTONIC, &ts);
812 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
813 } else
814 #endif
816 /* XXX: using gettimeofday leads to problems if the date
817 changes, so it should be avoided. */
818 struct timeval tv;
819 gettimeofday(&tv, NULL);
820 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
823 #endif
825 /* Return the virtual CPU time, based on the instruction counter. */
826 static int64_t cpu_get_icount(void)
828 int64_t icount;
829 CPUState *env = cpu_single_env;;
830 icount = qemu_icount;
831 if (env) {
832 if (!can_do_io(env))
833 fprintf(stderr, "Bad clock read\n");
834 icount -= (env->icount_decr.u16.low + env->icount_extra);
836 return qemu_icount_bias + (icount << icount_time_shift);
839 /***********************************************************/
840 /* guest cycle counter */
842 static int64_t cpu_ticks_prev;
843 static int64_t cpu_ticks_offset;
844 static int64_t cpu_clock_offset;
845 static int cpu_ticks_enabled;
847 /* return the host CPU cycle counter and handle stop/restart */
848 int64_t cpu_get_ticks(void)
850 if (use_icount) {
851 return cpu_get_icount();
853 if (!cpu_ticks_enabled) {
854 return cpu_ticks_offset;
855 } else {
856 int64_t ticks;
857 ticks = cpu_get_real_ticks();
858 if (cpu_ticks_prev > ticks) {
859 /* Note: non increasing ticks may happen if the host uses
860 software suspend */
861 cpu_ticks_offset += cpu_ticks_prev - ticks;
863 cpu_ticks_prev = ticks;
864 return ticks + cpu_ticks_offset;
868 /* return the host CPU monotonic timer and handle stop/restart */
869 static int64_t cpu_get_clock(void)
871 int64_t ti;
872 if (!cpu_ticks_enabled) {
873 return cpu_clock_offset;
874 } else {
875 ti = get_clock();
876 return ti + cpu_clock_offset;
880 /* enable cpu_get_ticks() */
881 void cpu_enable_ticks(void)
883 if (!cpu_ticks_enabled) {
884 cpu_ticks_offset -= cpu_get_real_ticks();
885 cpu_clock_offset -= get_clock();
886 cpu_ticks_enabled = 1;
890 /* disable cpu_get_ticks() : the clock is stopped. You must not call
891 cpu_get_ticks() after that. */
892 void cpu_disable_ticks(void)
894 if (cpu_ticks_enabled) {
895 cpu_ticks_offset = cpu_get_ticks();
896 cpu_clock_offset = cpu_get_clock();
897 cpu_ticks_enabled = 0;
901 /***********************************************************/
902 /* timers */
904 #define QEMU_TIMER_REALTIME 0
905 #define QEMU_TIMER_VIRTUAL 1
907 struct QEMUClock {
908 int type;
909 /* XXX: add frequency */
912 struct QEMUTimer {
913 QEMUClock *clock;
914 int64_t expire_time;
915 QEMUTimerCB *cb;
916 void *opaque;
917 struct QEMUTimer *next;
920 struct qemu_alarm_timer {
921 char const *name;
922 unsigned int flags;
924 int (*start)(struct qemu_alarm_timer *t);
925 void (*stop)(struct qemu_alarm_timer *t);
926 void (*rearm)(struct qemu_alarm_timer *t);
927 void *priv;
930 #define ALARM_FLAG_DYNTICKS 0x1
931 #define ALARM_FLAG_EXPIRED 0x2
933 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
935 return t->flags & ALARM_FLAG_DYNTICKS;
938 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
940 if (!alarm_has_dynticks(t))
941 return;
943 t->rearm(t);
946 /* TODO: MIN_TIMER_REARM_US should be optimized */
947 #define MIN_TIMER_REARM_US 250
949 static struct qemu_alarm_timer *alarm_timer;
950 #ifndef _WIN32
951 static int alarm_timer_rfd, alarm_timer_wfd;
952 #endif
954 #ifdef _WIN32
956 struct qemu_alarm_win32 {
957 MMRESULT timerId;
958 HANDLE host_alarm;
959 unsigned int period;
960 } alarm_win32_data = {0, NULL, -1};
962 static int win32_start_timer(struct qemu_alarm_timer *t);
963 static void win32_stop_timer(struct qemu_alarm_timer *t);
964 static void win32_rearm_timer(struct qemu_alarm_timer *t);
966 #else
968 static int unix_start_timer(struct qemu_alarm_timer *t);
969 static void unix_stop_timer(struct qemu_alarm_timer *t);
971 #ifdef __linux__
973 static int dynticks_start_timer(struct qemu_alarm_timer *t);
974 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
975 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
977 static int hpet_start_timer(struct qemu_alarm_timer *t);
978 static void hpet_stop_timer(struct qemu_alarm_timer *t);
980 static int rtc_start_timer(struct qemu_alarm_timer *t);
981 static void rtc_stop_timer(struct qemu_alarm_timer *t);
983 #endif /* __linux__ */
985 #endif /* _WIN32 */
987 /* Correlation between real and virtual time is always going to be
988 fairly approximate, so ignore small variation.
989 When the guest is idle real and virtual time will be aligned in
990 the IO wait loop. */
991 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
993 static void icount_adjust(void)
995 int64_t cur_time;
996 int64_t cur_icount;
997 int64_t delta;
998 static int64_t last_delta;
999 /* If the VM is not running, then do nothing. */
1000 if (!vm_running)
1001 return;
1003 cur_time = cpu_get_clock();
1004 cur_icount = qemu_get_clock(vm_clock);
1005 delta = cur_icount - cur_time;
1006 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1007 if (delta > 0
1008 && last_delta + ICOUNT_WOBBLE < delta * 2
1009 && icount_time_shift > 0) {
1010 /* The guest is getting too far ahead. Slow time down. */
1011 icount_time_shift--;
1013 if (delta < 0
1014 && last_delta - ICOUNT_WOBBLE > delta * 2
1015 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1016 /* The guest is getting too far behind. Speed time up. */
1017 icount_time_shift++;
1019 last_delta = delta;
1020 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1023 static void icount_adjust_rt(void * opaque)
1025 qemu_mod_timer(icount_rt_timer,
1026 qemu_get_clock(rt_clock) + 1000);
1027 icount_adjust();
1030 static void icount_adjust_vm(void * opaque)
1032 qemu_mod_timer(icount_vm_timer,
1033 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1034 icount_adjust();
1037 static void init_icount_adjust(void)
1039 /* Have both realtime and virtual time triggers for speed adjustment.
1040 The realtime trigger catches emulated time passing too slowly,
1041 the virtual time trigger catches emulated time passing too fast.
1042 Realtime triggers occur even when idle, so use them less frequently
1043 than VM triggers. */
1044 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1045 qemu_mod_timer(icount_rt_timer,
1046 qemu_get_clock(rt_clock) + 1000);
1047 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1048 qemu_mod_timer(icount_vm_timer,
1049 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1052 static struct qemu_alarm_timer alarm_timers[] = {
1053 #ifndef _WIN32
1054 #ifdef __linux__
1055 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1056 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1057 /* HPET - if available - is preferred */
1058 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1059 /* ...otherwise try RTC */
1060 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1061 #endif
1062 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1063 #else
1064 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1065 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1066 {"win32", 0, win32_start_timer,
1067 win32_stop_timer, NULL, &alarm_win32_data},
1068 #endif
1069 {NULL, }
1072 static void show_available_alarms(void)
1074 int i;
1076 printf("Available alarm timers, in order of precedence:\n");
1077 for (i = 0; alarm_timers[i].name; i++)
1078 printf("%s\n", alarm_timers[i].name);
1081 static void configure_alarms(char const *opt)
1083 int i;
1084 int cur = 0;
1085 int count = ARRAY_SIZE(alarm_timers) - 1;
1086 char *arg;
1087 char *name;
1088 struct qemu_alarm_timer tmp;
1090 if (!strcmp(opt, "?")) {
1091 show_available_alarms();
1092 exit(0);
1095 arg = strdup(opt);
1097 /* Reorder the array */
1098 name = strtok(arg, ",");
1099 while (name) {
1100 for (i = 0; i < count && alarm_timers[i].name; i++) {
1101 if (!strcmp(alarm_timers[i].name, name))
1102 break;
1105 if (i == count) {
1106 fprintf(stderr, "Unknown clock %s\n", name);
1107 goto next;
1110 if (i < cur)
1111 /* Ignore */
1112 goto next;
1114 /* Swap */
1115 tmp = alarm_timers[i];
1116 alarm_timers[i] = alarm_timers[cur];
1117 alarm_timers[cur] = tmp;
1119 cur++;
1120 next:
1121 name = strtok(NULL, ",");
1124 free(arg);
1126 if (cur) {
1127 /* Disable remaining timers */
1128 for (i = cur; i < count; i++)
1129 alarm_timers[i].name = NULL;
1130 } else {
1131 show_available_alarms();
1132 exit(1);
1136 QEMUClock *rt_clock;
1137 QEMUClock *vm_clock;
1139 static QEMUTimer *active_timers[2];
1141 static QEMUClock *qemu_new_clock(int type)
1143 QEMUClock *clock;
1144 clock = qemu_mallocz(sizeof(QEMUClock));
1145 clock->type = type;
1146 return clock;
1149 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1151 QEMUTimer *ts;
1153 ts = qemu_mallocz(sizeof(QEMUTimer));
1154 ts->clock = clock;
1155 ts->cb = cb;
1156 ts->opaque = opaque;
1157 return ts;
1160 void qemu_free_timer(QEMUTimer *ts)
1162 qemu_free(ts);
1165 /* stop a timer, but do not dealloc it */
1166 void qemu_del_timer(QEMUTimer *ts)
1168 QEMUTimer **pt, *t;
1170 /* NOTE: this code must be signal safe because
1171 qemu_timer_expired() can be called from a signal. */
1172 pt = &active_timers[ts->clock->type];
1173 for(;;) {
1174 t = *pt;
1175 if (!t)
1176 break;
1177 if (t == ts) {
1178 *pt = t->next;
1179 break;
1181 pt = &t->next;
1185 /* modify the current timer so that it will be fired when current_time
1186 >= expire_time. The corresponding callback will be called. */
1187 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1189 QEMUTimer **pt, *t;
1191 qemu_del_timer(ts);
1193 /* add the timer in the sorted list */
1194 /* NOTE: this code must be signal safe because
1195 qemu_timer_expired() can be called from a signal. */
1196 pt = &active_timers[ts->clock->type];
1197 for(;;) {
1198 t = *pt;
1199 if (!t)
1200 break;
1201 if (t->expire_time > expire_time)
1202 break;
1203 pt = &t->next;
1205 ts->expire_time = expire_time;
1206 ts->next = *pt;
1207 *pt = ts;
1209 /* Rearm if necessary */
1210 if (pt == &active_timers[ts->clock->type]) {
1211 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1212 qemu_rearm_alarm_timer(alarm_timer);
1214 /* Interrupt execution to force deadline recalculation. */
1215 if (use_icount && cpu_single_env) {
1216 cpu_exit(cpu_single_env);
1221 int qemu_timer_pending(QEMUTimer *ts)
1223 QEMUTimer *t;
1224 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1225 if (t == ts)
1226 return 1;
1228 return 0;
1231 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1233 if (!timer_head)
1234 return 0;
1235 return (timer_head->expire_time <= current_time);
1238 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1240 QEMUTimer *ts;
1242 for(;;) {
1243 ts = *ptimer_head;
1244 if (!ts || ts->expire_time > current_time)
1245 break;
1246 /* remove timer from the list before calling the callback */
1247 *ptimer_head = ts->next;
1248 ts->next = NULL;
1250 /* run the callback (the timer list can be modified) */
1251 ts->cb(ts->opaque);
1255 int64_t qemu_get_clock(QEMUClock *clock)
1257 switch(clock->type) {
1258 case QEMU_TIMER_REALTIME:
1259 return get_clock() / 1000000;
1260 default:
1261 case QEMU_TIMER_VIRTUAL:
1262 if (use_icount) {
1263 return cpu_get_icount();
1264 } else {
1265 return cpu_get_clock();
1270 static void init_timers(void)
1272 init_get_clock();
1273 ticks_per_sec = QEMU_TIMER_BASE;
1274 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1275 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1278 /* save a timer */
1279 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1281 uint64_t expire_time;
1283 if (qemu_timer_pending(ts)) {
1284 expire_time = ts->expire_time;
1285 } else {
1286 expire_time = -1;
1288 qemu_put_be64(f, expire_time);
1291 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1293 uint64_t expire_time;
1295 expire_time = qemu_get_be64(f);
1296 if (expire_time != -1) {
1297 qemu_mod_timer(ts, expire_time);
1298 } else {
1299 qemu_del_timer(ts);
1303 static void timer_save(QEMUFile *f, void *opaque)
1305 if (cpu_ticks_enabled) {
1306 hw_error("cannot save state if virtual timers are running");
1308 qemu_put_be64(f, cpu_ticks_offset);
1309 qemu_put_be64(f, ticks_per_sec);
1310 qemu_put_be64(f, cpu_clock_offset);
1313 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1315 if (version_id != 1 && version_id != 2)
1316 return -EINVAL;
1317 if (cpu_ticks_enabled) {
1318 return -EINVAL;
1320 cpu_ticks_offset=qemu_get_be64(f);
1321 ticks_per_sec=qemu_get_be64(f);
1322 if (version_id == 2) {
1323 cpu_clock_offset=qemu_get_be64(f);
1325 return 0;
1328 #ifdef _WIN32
1329 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1330 DWORD_PTR dwUser, DWORD_PTR dw1,
1331 DWORD_PTR dw2)
1332 #else
1333 static void host_alarm_handler(int host_signum)
1334 #endif
1336 #if 0
1337 #define DISP_FREQ 1000
1339 static int64_t delta_min = INT64_MAX;
1340 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1341 static int count;
1342 ti = qemu_get_clock(vm_clock);
1343 if (last_clock != 0) {
1344 delta = ti - last_clock;
1345 if (delta < delta_min)
1346 delta_min = delta;
1347 if (delta > delta_max)
1348 delta_max = delta;
1349 delta_cum += delta;
1350 if (++count == DISP_FREQ) {
1351 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1352 muldiv64(delta_min, 1000000, ticks_per_sec),
1353 muldiv64(delta_max, 1000000, ticks_per_sec),
1354 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1355 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1356 count = 0;
1357 delta_min = INT64_MAX;
1358 delta_max = 0;
1359 delta_cum = 0;
1362 last_clock = ti;
1364 #endif
1365 if (1 ||
1366 alarm_has_dynticks(alarm_timer) ||
1367 (!use_icount &&
1368 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1369 qemu_get_clock(vm_clock))) ||
1370 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1371 qemu_get_clock(rt_clock))) {
1372 CPUState *env = next_cpu;
1374 #ifdef _WIN32
1375 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1376 SetEvent(data->host_alarm);
1377 #else
1378 static const char byte = 0;
1379 write(alarm_timer_wfd, &byte, sizeof(byte));
1380 #endif
1381 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1383 if (env) {
1384 /* stop the currently executing cpu because a timer occured */
1385 cpu_exit(env);
1386 #ifdef USE_KQEMU
1387 if (env->kqemu_enabled) {
1388 kqemu_cpu_interrupt(env);
1390 #endif
1392 event_pending = 1;
1396 static int64_t qemu_next_deadline(void)
1398 int64_t delta;
1400 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1401 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1402 qemu_get_clock(vm_clock);
1403 } else {
1404 /* To avoid problems with overflow limit this to 2^32. */
1405 delta = INT32_MAX;
1408 if (delta < 0)
1409 delta = 0;
1411 return delta;
1414 #if defined(__linux__) || defined(_WIN32)
1415 static uint64_t qemu_next_deadline_dyntick(void)
1417 int64_t delta;
1418 int64_t rtdelta;
1420 if (use_icount)
1421 delta = INT32_MAX;
1422 else
1423 delta = (qemu_next_deadline() + 999) / 1000;
1425 if (active_timers[QEMU_TIMER_REALTIME]) {
1426 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1427 qemu_get_clock(rt_clock))*1000;
1428 if (rtdelta < delta)
1429 delta = rtdelta;
1432 if (delta < MIN_TIMER_REARM_US)
1433 delta = MIN_TIMER_REARM_US;
1435 return delta;
1437 #endif
1439 #ifndef _WIN32
1441 /* Sets a specific flag */
1442 static int fcntl_setfl(int fd, int flag)
1444 int flags;
1446 flags = fcntl(fd, F_GETFL);
1447 if (flags == -1)
1448 return -errno;
1450 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1451 return -errno;
1453 return 0;
1456 #if defined(__linux__)
1458 #define RTC_FREQ 1024
1460 static void enable_sigio_timer(int fd)
1462 struct sigaction act;
1464 /* timer signal */
1465 sigfillset(&act.sa_mask);
1466 act.sa_flags = 0;
1467 act.sa_handler = host_alarm_handler;
1469 sigaction(SIGIO, &act, NULL);
1470 fcntl_setfl(fd, O_ASYNC);
1471 fcntl(fd, F_SETOWN, getpid());
1474 static int hpet_start_timer(struct qemu_alarm_timer *t)
1476 struct hpet_info info;
1477 int r, fd;
1479 fd = open("/dev/hpet", O_RDONLY);
1480 if (fd < 0)
1481 return -1;
1483 /* Set frequency */
1484 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1485 if (r < 0) {
1486 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1487 "error, but for better emulation accuracy type:\n"
1488 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1489 goto fail;
1492 /* Check capabilities */
1493 r = ioctl(fd, HPET_INFO, &info);
1494 if (r < 0)
1495 goto fail;
1497 /* Enable periodic mode */
1498 r = ioctl(fd, HPET_EPI, 0);
1499 if (info.hi_flags && (r < 0))
1500 goto fail;
1502 /* Enable interrupt */
1503 r = ioctl(fd, HPET_IE_ON, 0);
1504 if (r < 0)
1505 goto fail;
1507 enable_sigio_timer(fd);
1508 t->priv = (void *)(long)fd;
1510 return 0;
1511 fail:
1512 close(fd);
1513 return -1;
1516 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1518 int fd = (long)t->priv;
1520 close(fd);
1523 static int rtc_start_timer(struct qemu_alarm_timer *t)
1525 int rtc_fd;
1526 unsigned long current_rtc_freq = 0;
1528 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1529 if (rtc_fd < 0)
1530 return -1;
1531 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1532 if (current_rtc_freq != RTC_FREQ &&
1533 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1534 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1535 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1536 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1537 goto fail;
1539 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1540 fail:
1541 close(rtc_fd);
1542 return -1;
1545 enable_sigio_timer(rtc_fd);
1547 t->priv = (void *)(long)rtc_fd;
1549 return 0;
1552 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1554 int rtc_fd = (long)t->priv;
1556 close(rtc_fd);
1559 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1561 struct sigevent ev;
1562 timer_t host_timer;
1563 struct sigaction act;
1565 sigfillset(&act.sa_mask);
1566 act.sa_flags = 0;
1567 act.sa_handler = host_alarm_handler;
1569 sigaction(SIGALRM, &act, NULL);
1571 ev.sigev_value.sival_int = 0;
1572 ev.sigev_notify = SIGEV_SIGNAL;
1573 ev.sigev_signo = SIGALRM;
1575 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1576 perror("timer_create");
1578 /* disable dynticks */
1579 fprintf(stderr, "Dynamic Ticks disabled\n");
1581 return -1;
1584 t->priv = (void *)(long)host_timer;
1586 return 0;
1589 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1591 timer_t host_timer = (timer_t)(long)t->priv;
1593 timer_delete(host_timer);
1596 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1598 timer_t host_timer = (timer_t)(long)t->priv;
1599 struct itimerspec timeout;
1600 int64_t nearest_delta_us = INT64_MAX;
1601 int64_t current_us;
1603 if (!active_timers[QEMU_TIMER_REALTIME] &&
1604 !active_timers[QEMU_TIMER_VIRTUAL])
1605 return;
1607 nearest_delta_us = qemu_next_deadline_dyntick();
1609 /* check whether a timer is already running */
1610 if (timer_gettime(host_timer, &timeout)) {
1611 perror("gettime");
1612 fprintf(stderr, "Internal timer error: aborting\n");
1613 exit(1);
1615 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1616 if (current_us && current_us <= nearest_delta_us)
1617 return;
1619 timeout.it_interval.tv_sec = 0;
1620 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1621 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1622 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1623 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1624 perror("settime");
1625 fprintf(stderr, "Internal timer error: aborting\n");
1626 exit(1);
1630 #endif /* defined(__linux__) */
1632 static int unix_start_timer(struct qemu_alarm_timer *t)
1634 struct sigaction act;
1635 struct itimerval itv;
1636 int err;
1638 /* timer signal */
1639 sigfillset(&act.sa_mask);
1640 act.sa_flags = 0;
1641 act.sa_handler = host_alarm_handler;
1643 sigaction(SIGALRM, &act, NULL);
1645 itv.it_interval.tv_sec = 0;
1646 /* for i386 kernel 2.6 to get 1 ms */
1647 itv.it_interval.tv_usec = 999;
1648 itv.it_value.tv_sec = 0;
1649 itv.it_value.tv_usec = 10 * 1000;
1651 err = setitimer(ITIMER_REAL, &itv, NULL);
1652 if (err)
1653 return -1;
1655 return 0;
1658 static void unix_stop_timer(struct qemu_alarm_timer *t)
1660 struct itimerval itv;
1662 memset(&itv, 0, sizeof(itv));
1663 setitimer(ITIMER_REAL, &itv, NULL);
1666 #endif /* !defined(_WIN32) */
1668 static void try_to_rearm_timer(void *opaque)
1670 struct qemu_alarm_timer *t = opaque;
1671 #ifndef _WIN32
1672 ssize_t len;
1674 /* Drain the notify pipe */
1675 do {
1676 char buffer[512];
1677 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1678 } while ((len == -1 && errno == EINTR) || len > 0);
1679 #endif
1681 if (t->flags & ALARM_FLAG_EXPIRED) {
1682 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1683 qemu_rearm_alarm_timer(alarm_timer);
1687 #ifdef _WIN32
1689 static int win32_start_timer(struct qemu_alarm_timer *t)
1691 TIMECAPS tc;
1692 struct qemu_alarm_win32 *data = t->priv;
1693 UINT flags;
1695 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1696 if (!data->host_alarm) {
1697 perror("Failed CreateEvent");
1698 return -1;
1701 memset(&tc, 0, sizeof(tc));
1702 timeGetDevCaps(&tc, sizeof(tc));
1704 if (data->period < tc.wPeriodMin)
1705 data->period = tc.wPeriodMin;
1707 timeBeginPeriod(data->period);
1709 flags = TIME_CALLBACK_FUNCTION;
1710 if (alarm_has_dynticks(t))
1711 flags |= TIME_ONESHOT;
1712 else
1713 flags |= TIME_PERIODIC;
1715 data->timerId = timeSetEvent(1, // interval (ms)
1716 data->period, // resolution
1717 host_alarm_handler, // function
1718 (DWORD)t, // parameter
1719 flags);
1721 if (!data->timerId) {
1722 perror("Failed to initialize win32 alarm timer");
1724 timeEndPeriod(data->period);
1725 CloseHandle(data->host_alarm);
1726 return -1;
1729 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1731 return 0;
1734 static void win32_stop_timer(struct qemu_alarm_timer *t)
1736 struct qemu_alarm_win32 *data = t->priv;
1738 timeKillEvent(data->timerId);
1739 timeEndPeriod(data->period);
1741 CloseHandle(data->host_alarm);
1744 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1746 struct qemu_alarm_win32 *data = t->priv;
1747 uint64_t nearest_delta_us;
1749 if (!active_timers[QEMU_TIMER_REALTIME] &&
1750 !active_timers[QEMU_TIMER_VIRTUAL])
1751 return;
1753 nearest_delta_us = qemu_next_deadline_dyntick();
1754 nearest_delta_us /= 1000;
1756 timeKillEvent(data->timerId);
1758 data->timerId = timeSetEvent(1,
1759 data->period,
1760 host_alarm_handler,
1761 (DWORD)t,
1762 TIME_ONESHOT | TIME_PERIODIC);
1764 if (!data->timerId) {
1765 perror("Failed to re-arm win32 alarm timer");
1767 timeEndPeriod(data->period);
1768 CloseHandle(data->host_alarm);
1769 exit(1);
1773 #endif /* _WIN32 */
1775 static int init_timer_alarm(void)
1777 struct qemu_alarm_timer *t = NULL;
1778 int i, err = -1;
1780 #ifndef _WIN32
1781 int fds[2];
1783 err = pipe(fds);
1784 if (err == -1)
1785 return -errno;
1787 err = fcntl_setfl(fds[0], O_NONBLOCK);
1788 if (err < 0)
1789 goto fail;
1791 err = fcntl_setfl(fds[1], O_NONBLOCK);
1792 if (err < 0)
1793 goto fail;
1795 alarm_timer_rfd = fds[0];
1796 alarm_timer_wfd = fds[1];
1797 #endif
1799 for (i = 0; alarm_timers[i].name; i++) {
1800 t = &alarm_timers[i];
1802 err = t->start(t);
1803 if (!err)
1804 break;
1807 if (err) {
1808 err = -ENOENT;
1809 goto fail;
1812 #ifndef _WIN32
1813 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1814 try_to_rearm_timer, NULL, t);
1815 #endif
1817 alarm_timer = t;
1819 return 0;
1821 fail:
1822 #ifndef _WIN32
1823 close(fds[0]);
1824 close(fds[1]);
1825 #endif
1826 return err;
1829 static void quit_timers(void)
1831 alarm_timer->stop(alarm_timer);
1832 alarm_timer = NULL;
1835 /***********************************************************/
1836 /* host time/date access */
1837 void qemu_get_timedate(struct tm *tm, int offset)
1839 time_t ti;
1840 struct tm *ret;
1842 time(&ti);
1843 ti += offset;
1844 if (rtc_date_offset == -1) {
1845 if (rtc_utc)
1846 ret = gmtime(&ti);
1847 else
1848 ret = localtime(&ti);
1849 } else {
1850 ti -= rtc_date_offset;
1851 ret = gmtime(&ti);
1854 memcpy(tm, ret, sizeof(struct tm));
1857 int qemu_timedate_diff(struct tm *tm)
1859 time_t seconds;
1861 if (rtc_date_offset == -1)
1862 if (rtc_utc)
1863 seconds = mktimegm(tm);
1864 else
1865 seconds = mktime(tm);
1866 else
1867 seconds = mktimegm(tm) + rtc_date_offset;
1869 return seconds - time(NULL);
1872 #ifdef _WIN32
1873 static void socket_cleanup(void)
1875 WSACleanup();
1878 static int socket_init(void)
1880 WSADATA Data;
1881 int ret, err;
1883 ret = WSAStartup(MAKEWORD(2,2), &Data);
1884 if (ret != 0) {
1885 err = WSAGetLastError();
1886 fprintf(stderr, "WSAStartup: %d\n", err);
1887 return -1;
1889 atexit(socket_cleanup);
1890 return 0;
1892 #endif
1894 const char *get_opt_name(char *buf, int buf_size, const char *p)
1896 char *q;
1898 q = buf;
1899 while (*p != '\0' && *p != '=') {
1900 if (q && (q - buf) < buf_size - 1)
1901 *q++ = *p;
1902 p++;
1904 if (q)
1905 *q = '\0';
1907 return p;
1910 const char *get_opt_value(char *buf, int buf_size, const char *p)
1912 char *q;
1914 q = buf;
1915 while (*p != '\0') {
1916 if (*p == ',') {
1917 if (*(p + 1) != ',')
1918 break;
1919 p++;
1921 if (q && (q - buf) < buf_size - 1)
1922 *q++ = *p;
1923 p++;
1925 if (q)
1926 *q = '\0';
1928 return p;
1931 int get_param_value(char *buf, int buf_size,
1932 const char *tag, const char *str)
1934 const char *p;
1935 char option[128];
1937 p = str;
1938 for(;;) {
1939 p = get_opt_name(option, sizeof(option), p);
1940 if (*p != '=')
1941 break;
1942 p++;
1943 if (!strcmp(tag, option)) {
1944 (void)get_opt_value(buf, buf_size, p);
1945 return strlen(buf);
1946 } else {
1947 p = get_opt_value(NULL, 0, p);
1949 if (*p != ',')
1950 break;
1951 p++;
1953 return 0;
1956 int check_params(char *buf, int buf_size,
1957 const char * const *params, const char *str)
1959 const char *p;
1960 int i;
1962 p = str;
1963 for(;;) {
1964 p = get_opt_name(buf, buf_size, p);
1965 if (*p != '=')
1966 return -1;
1967 p++;
1968 for(i = 0; params[i] != NULL; i++)
1969 if (!strcmp(params[i], buf))
1970 break;
1971 if (params[i] == NULL)
1972 return -1;
1973 p = get_opt_value(NULL, 0, p);
1974 if (*p != ',')
1975 break;
1976 p++;
1978 return 0;
1981 /***********************************************************/
1982 /* Bluetooth support */
1983 static int nb_hcis;
1984 static int cur_hci;
1985 static struct HCIInfo *hci_table[MAX_NICS];
1987 static struct bt_vlan_s {
1988 struct bt_scatternet_s net;
1989 int id;
1990 struct bt_vlan_s *next;
1991 } *first_bt_vlan;
1993 /* find or alloc a new bluetooth "VLAN" */
1994 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1996 struct bt_vlan_s **pvlan, *vlan;
1997 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1998 if (vlan->id == id)
1999 return &vlan->net;
2001 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
2002 vlan->id = id;
2003 pvlan = &first_bt_vlan;
2004 while (*pvlan != NULL)
2005 pvlan = &(*pvlan)->next;
2006 *pvlan = vlan;
2007 return &vlan->net;
2010 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
2014 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
2016 return -ENOTSUP;
2019 static struct HCIInfo null_hci = {
2020 .cmd_send = null_hci_send,
2021 .sco_send = null_hci_send,
2022 .acl_send = null_hci_send,
2023 .bdaddr_set = null_hci_addr_set,
2026 struct HCIInfo *qemu_next_hci(void)
2028 if (cur_hci == nb_hcis)
2029 return &null_hci;
2031 return hci_table[cur_hci++];
2034 static struct HCIInfo *hci_init(const char *str)
2036 char *endp;
2037 struct bt_scatternet_s *vlan = 0;
2039 if (!strcmp(str, "null"))
2040 /* null */
2041 return &null_hci;
2042 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2043 /* host[:hciN] */
2044 return bt_host_hci(str[4] ? str + 5 : "hci0");
2045 else if (!strncmp(str, "hci", 3)) {
2046 /* hci[,vlan=n] */
2047 if (str[3]) {
2048 if (!strncmp(str + 3, ",vlan=", 6)) {
2049 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2050 if (*endp)
2051 vlan = 0;
2053 } else
2054 vlan = qemu_find_bt_vlan(0);
2055 if (vlan)
2056 return bt_new_hci(vlan);
2059 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2061 return 0;
2064 static int bt_hci_parse(const char *str)
2066 struct HCIInfo *hci;
2067 bdaddr_t bdaddr;
2069 if (nb_hcis >= MAX_NICS) {
2070 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2071 return -1;
2074 hci = hci_init(str);
2075 if (!hci)
2076 return -1;
2078 bdaddr.b[0] = 0x52;
2079 bdaddr.b[1] = 0x54;
2080 bdaddr.b[2] = 0x00;
2081 bdaddr.b[3] = 0x12;
2082 bdaddr.b[4] = 0x34;
2083 bdaddr.b[5] = 0x56 + nb_hcis;
2084 hci->bdaddr_set(hci, bdaddr.b);
2086 hci_table[nb_hcis++] = hci;
2088 return 0;
2091 static void bt_vhci_add(int vlan_id)
2093 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2095 if (!vlan->slave)
2096 fprintf(stderr, "qemu: warning: adding a VHCI to "
2097 "an empty scatternet %i\n", vlan_id);
2099 bt_vhci_init(bt_new_hci(vlan));
2102 static struct bt_device_s *bt_device_add(const char *opt)
2104 struct bt_scatternet_s *vlan;
2105 int vlan_id = 0;
2106 char *endp = strstr(opt, ",vlan=");
2107 int len = (endp ? endp - opt : strlen(opt)) + 1;
2108 char devname[10];
2110 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2112 if (endp) {
2113 vlan_id = strtol(endp + 6, &endp, 0);
2114 if (*endp) {
2115 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2116 return 0;
2120 vlan = qemu_find_bt_vlan(vlan_id);
2122 if (!vlan->slave)
2123 fprintf(stderr, "qemu: warning: adding a slave device to "
2124 "an empty scatternet %i\n", vlan_id);
2126 if (!strcmp(devname, "keyboard"))
2127 return bt_keyboard_init(vlan);
2129 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2130 return 0;
2133 static int bt_parse(const char *opt)
2135 const char *endp, *p;
2136 int vlan;
2138 if (strstart(opt, "hci", &endp)) {
2139 if (!*endp || *endp == ',') {
2140 if (*endp)
2141 if (!strstart(endp, ",vlan=", 0))
2142 opt = endp + 1;
2144 return bt_hci_parse(opt);
2146 } else if (strstart(opt, "vhci", &endp)) {
2147 if (!*endp || *endp == ',') {
2148 if (*endp) {
2149 if (strstart(endp, ",vlan=", &p)) {
2150 vlan = strtol(p, (char **) &endp, 0);
2151 if (*endp) {
2152 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2153 return 1;
2155 } else {
2156 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2157 return 1;
2159 } else
2160 vlan = 0;
2162 bt_vhci_add(vlan);
2163 return 0;
2165 } else if (strstart(opt, "device:", &endp))
2166 return !bt_device_add(endp);
2168 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2169 return 1;
2172 /***********************************************************/
2173 /* QEMU Block devices */
2175 #define HD_ALIAS "index=%d,media=disk"
2176 #define CDROM_ALIAS "index=2,media=cdrom"
2177 #define FD_ALIAS "index=%d,if=floppy"
2178 #define PFLASH_ALIAS "if=pflash"
2179 #define MTD_ALIAS "if=mtd"
2180 #define SD_ALIAS "index=0,if=sd"
2182 static int drive_opt_get_free_idx(void)
2184 int index;
2186 for (index = 0; index < MAX_DRIVES; index++)
2187 if (!drives_opt[index].used) {
2188 drives_opt[index].used = 1;
2189 return index;
2192 return -1;
2195 static int drive_get_free_idx(void)
2197 int index;
2199 for (index = 0; index < MAX_DRIVES; index++)
2200 if (!drives_table[index].used) {
2201 drives_table[index].used = 1;
2202 return index;
2205 return -1;
2208 int drive_add(const char *file, const char *fmt, ...)
2210 va_list ap;
2211 int index = drive_opt_get_free_idx();
2213 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2214 fprintf(stderr, "qemu: too many drives\n");
2215 return -1;
2218 drives_opt[index].file = file;
2219 va_start(ap, fmt);
2220 vsnprintf(drives_opt[index].opt,
2221 sizeof(drives_opt[0].opt), fmt, ap);
2222 va_end(ap);
2224 nb_drives_opt++;
2225 return index;
2228 void drive_remove(int index)
2230 drives_opt[index].used = 0;
2231 nb_drives_opt--;
2234 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2236 int index;
2238 /* seek interface, bus and unit */
2240 for (index = 0; index < MAX_DRIVES; index++)
2241 if (drives_table[index].type == type &&
2242 drives_table[index].bus == bus &&
2243 drives_table[index].unit == unit &&
2244 drives_table[index].used)
2245 return index;
2247 return -1;
2250 int drive_get_max_bus(BlockInterfaceType type)
2252 int max_bus;
2253 int index;
2255 max_bus = -1;
2256 for (index = 0; index < nb_drives; index++) {
2257 if(drives_table[index].type == type &&
2258 drives_table[index].bus > max_bus)
2259 max_bus = drives_table[index].bus;
2261 return max_bus;
2264 const char *drive_get_serial(BlockDriverState *bdrv)
2266 int index;
2268 for (index = 0; index < nb_drives; index++)
2269 if (drives_table[index].bdrv == bdrv)
2270 return drives_table[index].serial;
2272 return "\0";
2275 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2277 int index;
2279 for (index = 0; index < nb_drives; index++)
2280 if (drives_table[index].bdrv == bdrv)
2281 return drives_table[index].onerror;
2283 return BLOCK_ERR_STOP_ENOSPC;
2286 static void bdrv_format_print(void *opaque, const char *name)
2288 fprintf(stderr, " %s", name);
2291 void drive_uninit(BlockDriverState *bdrv)
2293 int i;
2295 for (i = 0; i < MAX_DRIVES; i++)
2296 if (drives_table[i].bdrv == bdrv) {
2297 drives_table[i].bdrv = NULL;
2298 drives_table[i].used = 0;
2299 drive_remove(drives_table[i].drive_opt_idx);
2300 nb_drives--;
2301 break;
2305 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2307 char buf[128];
2308 char file[1024];
2309 char devname[128];
2310 char serial[21];
2311 const char *mediastr = "";
2312 BlockInterfaceType type;
2313 enum { MEDIA_DISK, MEDIA_CDROM } media;
2314 int bus_id, unit_id;
2315 int cyls, heads, secs, translation;
2316 BlockDriverState *bdrv;
2317 BlockDriver *drv = NULL;
2318 QEMUMachine *machine = opaque;
2319 int max_devs;
2320 int index;
2321 int cache;
2322 int bdrv_flags, onerror;
2323 int drives_table_idx;
2324 char *str = arg->opt;
2325 static const char * const params[] = { "bus", "unit", "if", "index",
2326 "cyls", "heads", "secs", "trans",
2327 "media", "snapshot", "file",
2328 "cache", "format", "serial", "werror",
2329 "boot", NULL };
2331 if (check_params(buf, sizeof(buf), params, str) < 0) {
2332 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2333 buf, str);
2334 return -1;
2337 file[0] = 0;
2338 cyls = heads = secs = 0;
2339 bus_id = 0;
2340 unit_id = -1;
2341 translation = BIOS_ATA_TRANSLATION_AUTO;
2342 index = -1;
2343 cache = 3;
2345 if (machine->use_scsi) {
2346 type = IF_SCSI;
2347 max_devs = MAX_SCSI_DEVS;
2348 pstrcpy(devname, sizeof(devname), "scsi");
2349 } else {
2350 type = IF_IDE;
2351 max_devs = MAX_IDE_DEVS;
2352 pstrcpy(devname, sizeof(devname), "ide");
2354 media = MEDIA_DISK;
2356 /* extract parameters */
2358 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2359 bus_id = strtol(buf, NULL, 0);
2360 if (bus_id < 0) {
2361 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2362 return -1;
2366 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2367 unit_id = strtol(buf, NULL, 0);
2368 if (unit_id < 0) {
2369 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2370 return -1;
2374 if (get_param_value(buf, sizeof(buf), "if", str)) {
2375 pstrcpy(devname, sizeof(devname), buf);
2376 if (!strcmp(buf, "ide")) {
2377 type = IF_IDE;
2378 max_devs = MAX_IDE_DEVS;
2379 } else if (!strcmp(buf, "scsi")) {
2380 type = IF_SCSI;
2381 max_devs = MAX_SCSI_DEVS;
2382 } else if (!strcmp(buf, "floppy")) {
2383 type = IF_FLOPPY;
2384 max_devs = 0;
2385 } else if (!strcmp(buf, "pflash")) {
2386 type = IF_PFLASH;
2387 max_devs = 0;
2388 } else if (!strcmp(buf, "mtd")) {
2389 type = IF_MTD;
2390 max_devs = 0;
2391 } else if (!strcmp(buf, "sd")) {
2392 type = IF_SD;
2393 max_devs = 0;
2394 } else if (!strcmp(buf, "virtio")) {
2395 type = IF_VIRTIO;
2396 max_devs = 0;
2397 } else {
2398 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2399 return -1;
2403 if (get_param_value(buf, sizeof(buf), "index", str)) {
2404 index = strtol(buf, NULL, 0);
2405 if (index < 0) {
2406 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2407 return -1;
2411 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2412 cyls = strtol(buf, NULL, 0);
2415 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2416 heads = strtol(buf, NULL, 0);
2419 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2420 secs = strtol(buf, NULL, 0);
2423 if (cyls || heads || secs) {
2424 if (cyls < 1 || cyls > 16383) {
2425 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2426 return -1;
2428 if (heads < 1 || heads > 16) {
2429 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2430 return -1;
2432 if (secs < 1 || secs > 63) {
2433 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2434 return -1;
2438 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2439 if (!cyls) {
2440 fprintf(stderr,
2441 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2442 str);
2443 return -1;
2445 if (!strcmp(buf, "none"))
2446 translation = BIOS_ATA_TRANSLATION_NONE;
2447 else if (!strcmp(buf, "lba"))
2448 translation = BIOS_ATA_TRANSLATION_LBA;
2449 else if (!strcmp(buf, "auto"))
2450 translation = BIOS_ATA_TRANSLATION_AUTO;
2451 else {
2452 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2453 return -1;
2457 if (get_param_value(buf, sizeof(buf), "media", str)) {
2458 if (!strcmp(buf, "disk")) {
2459 media = MEDIA_DISK;
2460 } else if (!strcmp(buf, "cdrom")) {
2461 if (cyls || secs || heads) {
2462 fprintf(stderr,
2463 "qemu: '%s' invalid physical CHS format\n", str);
2464 return -1;
2466 media = MEDIA_CDROM;
2467 } else {
2468 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2469 return -1;
2473 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2474 if (!strcmp(buf, "on"))
2475 snapshot = 1;
2476 else if (!strcmp(buf, "off"))
2477 snapshot = 0;
2478 else {
2479 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2480 return -1;
2484 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2485 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2486 cache = 0;
2487 else if (!strcmp(buf, "writethrough"))
2488 cache = 1;
2489 else if (!strcmp(buf, "writeback"))
2490 cache = 2;
2491 else {
2492 fprintf(stderr, "qemu: invalid cache option\n");
2493 return -1;
2497 if (get_param_value(buf, sizeof(buf), "format", str)) {
2498 if (strcmp(buf, "?") == 0) {
2499 fprintf(stderr, "qemu: Supported formats:");
2500 bdrv_iterate_format(bdrv_format_print, NULL);
2501 fprintf(stderr, "\n");
2502 return -1;
2504 drv = bdrv_find_format(buf);
2505 if (!drv) {
2506 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2507 return -1;
2511 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2512 if (!strcmp(buf, "on")) {
2513 if (extboot_drive != -1) {
2514 fprintf(stderr, "qemu: two bootable drives specified\n");
2515 return -1;
2517 extboot_drive = nb_drives;
2518 } else if (strcmp(buf, "off")) {
2519 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2520 return -1;
2524 if (arg->file == NULL)
2525 get_param_value(file, sizeof(file), "file", str);
2526 else
2527 pstrcpy(file, sizeof(file), arg->file);
2529 if (!get_param_value(serial, sizeof(serial), "serial", str))
2530 memset(serial, 0, sizeof(serial));
2532 onerror = BLOCK_ERR_STOP_ENOSPC;
2533 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2534 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2535 fprintf(stderr, "werror is no supported by this format\n");
2536 return -1;
2538 if (!strcmp(buf, "ignore"))
2539 onerror = BLOCK_ERR_IGNORE;
2540 else if (!strcmp(buf, "enospc"))
2541 onerror = BLOCK_ERR_STOP_ENOSPC;
2542 else if (!strcmp(buf, "stop"))
2543 onerror = BLOCK_ERR_STOP_ANY;
2544 else if (!strcmp(buf, "report"))
2545 onerror = BLOCK_ERR_REPORT;
2546 else {
2547 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2548 return -1;
2552 /* compute bus and unit according index */
2554 if (index != -1) {
2555 if (bus_id != 0 || unit_id != -1) {
2556 fprintf(stderr,
2557 "qemu: '%s' index cannot be used with bus and unit\n", str);
2558 return -1;
2560 if (max_devs == 0)
2562 unit_id = index;
2563 bus_id = 0;
2564 } else {
2565 unit_id = index % max_devs;
2566 bus_id = index / max_devs;
2570 /* if user doesn't specify a unit_id,
2571 * try to find the first free
2574 if (unit_id == -1) {
2575 unit_id = 0;
2576 while (drive_get_index(type, bus_id, unit_id) != -1) {
2577 unit_id++;
2578 if (max_devs && unit_id >= max_devs) {
2579 unit_id -= max_devs;
2580 bus_id++;
2585 /* check unit id */
2587 if (max_devs && unit_id >= max_devs) {
2588 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2589 str, unit_id, max_devs - 1);
2590 return -1;
2594 * ignore multiple definitions
2597 if (drive_get_index(type, bus_id, unit_id) != -1)
2598 return -2;
2600 /* init */
2602 if (type == IF_IDE || type == IF_SCSI)
2603 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2604 if (max_devs)
2605 snprintf(buf, sizeof(buf), "%s%i%s%i",
2606 devname, bus_id, mediastr, unit_id);
2607 else
2608 snprintf(buf, sizeof(buf), "%s%s%i",
2609 devname, mediastr, unit_id);
2610 bdrv = bdrv_new(buf);
2611 drives_table_idx = drive_get_free_idx();
2612 drives_table[drives_table_idx].bdrv = bdrv;
2613 drives_table[drives_table_idx].type = type;
2614 drives_table[drives_table_idx].bus = bus_id;
2615 drives_table[drives_table_idx].unit = unit_id;
2616 drives_table[drives_table_idx].onerror = onerror;
2617 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2618 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2619 nb_drives++;
2621 switch(type) {
2622 case IF_IDE:
2623 case IF_SCSI:
2624 switch(media) {
2625 case MEDIA_DISK:
2626 if (cyls != 0) {
2627 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2628 bdrv_set_translation_hint(bdrv, translation);
2630 break;
2631 case MEDIA_CDROM:
2632 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2633 break;
2635 break;
2636 case IF_SD:
2637 /* FIXME: This isn't really a floppy, but it's a reasonable
2638 approximation. */
2639 case IF_FLOPPY:
2640 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2641 break;
2642 case IF_PFLASH:
2643 case IF_MTD:
2644 case IF_VIRTIO:
2645 break;
2647 if (!file[0])
2648 return -2;
2649 bdrv_flags = 0;
2650 if (snapshot) {
2651 bdrv_flags |= BDRV_O_SNAPSHOT;
2652 cache = 2; /* always use write-back with snapshot */
2654 if (cache == 0) /* no caching */
2655 bdrv_flags |= BDRV_O_NOCACHE;
2656 else if (cache == 2) /* write-back */
2657 bdrv_flags |= BDRV_O_CACHE_WB;
2658 else if (cache == 3) /* not specified */
2659 bdrv_flags |= BDRV_O_CACHE_DEF;
2660 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2661 fprintf(stderr, "qemu: could not open disk image %s\n",
2662 file);
2663 return -1;
2665 if (bdrv_key_required(bdrv))
2666 autostart = 0;
2667 return drives_table_idx;
2670 /***********************************************************/
2671 /* USB devices */
2673 static USBPort *used_usb_ports;
2674 static USBPort *free_usb_ports;
2676 /* ??? Maybe change this to register a hub to keep track of the topology. */
2677 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2678 usb_attachfn attach)
2680 port->opaque = opaque;
2681 port->index = index;
2682 port->attach = attach;
2683 port->next = free_usb_ports;
2684 free_usb_ports = port;
2687 int usb_device_add_dev(USBDevice *dev)
2689 USBPort *port;
2691 /* Find a USB port to add the device to. */
2692 port = free_usb_ports;
2693 if (!port->next) {
2694 USBDevice *hub;
2696 /* Create a new hub and chain it on. */
2697 free_usb_ports = NULL;
2698 port->next = used_usb_ports;
2699 used_usb_ports = port;
2701 hub = usb_hub_init(VM_USB_HUB_SIZE);
2702 usb_attach(port, hub);
2703 port = free_usb_ports;
2706 free_usb_ports = port->next;
2707 port->next = used_usb_ports;
2708 used_usb_ports = port;
2709 usb_attach(port, dev);
2710 return 0;
2713 static void usb_msd_password_cb(void *opaque, int err)
2715 USBDevice *dev = opaque;
2717 if (!err)
2718 usb_device_add_dev(dev);
2719 else
2720 dev->handle_destroy(dev);
2723 static int usb_device_add(const char *devname, int is_hotplug)
2725 const char *p;
2726 USBDevice *dev;
2728 if (!free_usb_ports)
2729 return -1;
2731 if (strstart(devname, "host:", &p)) {
2732 dev = usb_host_device_open(p);
2733 } else if (!strcmp(devname, "mouse")) {
2734 dev = usb_mouse_init();
2735 } else if (!strcmp(devname, "tablet")) {
2736 dev = usb_tablet_init();
2737 } else if (!strcmp(devname, "keyboard")) {
2738 dev = usb_keyboard_init();
2739 } else if (strstart(devname, "disk:", &p)) {
2740 BlockDriverState *bs;
2742 dev = usb_msd_init(p);
2743 if (!dev)
2744 return -1;
2745 bs = usb_msd_get_bdrv(dev);
2746 if (bdrv_key_required(bs)) {
2747 autostart = 0;
2748 if (is_hotplug) {
2749 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2750 dev);
2751 return 0;
2754 } else if (!strcmp(devname, "wacom-tablet")) {
2755 dev = usb_wacom_init();
2756 } else if (strstart(devname, "serial:", &p)) {
2757 dev = usb_serial_init(p);
2758 #ifdef CONFIG_BRLAPI
2759 } else if (!strcmp(devname, "braille")) {
2760 dev = usb_baum_init();
2761 #endif
2762 } else if (strstart(devname, "net:", &p)) {
2763 int nic = nb_nics;
2765 if (net_client_init("nic", p) < 0)
2766 return -1;
2767 nd_table[nic].model = "usb";
2768 dev = usb_net_init(&nd_table[nic]);
2769 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2770 dev = usb_bt_init(devname[2] ? hci_init(p) :
2771 bt_new_hci(qemu_find_bt_vlan(0)));
2772 } else {
2773 return -1;
2775 if (!dev)
2776 return -1;
2778 return usb_device_add_dev(dev);
2781 int usb_device_del_addr(int bus_num, int addr)
2783 USBPort *port;
2784 USBPort **lastp;
2785 USBDevice *dev;
2787 if (!used_usb_ports)
2788 return -1;
2790 if (bus_num != 0)
2791 return -1;
2793 lastp = &used_usb_ports;
2794 port = used_usb_ports;
2795 while (port && port->dev->addr != addr) {
2796 lastp = &port->next;
2797 port = port->next;
2800 if (!port)
2801 return -1;
2803 dev = port->dev;
2804 *lastp = port->next;
2805 usb_attach(port, NULL);
2806 dev->handle_destroy(dev);
2807 port->next = free_usb_ports;
2808 free_usb_ports = port;
2809 return 0;
2812 static int usb_device_del(const char *devname)
2814 int bus_num, addr;
2815 const char *p;
2817 if (strstart(devname, "host:", &p))
2818 return usb_host_device_close(p);
2820 if (!used_usb_ports)
2821 return -1;
2823 p = strchr(devname, '.');
2824 if (!p)
2825 return -1;
2826 bus_num = strtoul(devname, NULL, 0);
2827 addr = strtoul(p + 1, NULL, 0);
2829 return usb_device_del_addr(bus_num, addr);
2832 void do_usb_add(Monitor *mon, const char *devname)
2834 usb_device_add(devname, 1);
2837 void do_usb_del(Monitor *mon, const char *devname)
2839 usb_device_del(devname);
2842 void usb_info(Monitor *mon)
2844 USBDevice *dev;
2845 USBPort *port;
2846 const char *speed_str;
2848 if (!usb_enabled) {
2849 monitor_printf(mon, "USB support not enabled\n");
2850 return;
2853 for (port = used_usb_ports; port; port = port->next) {
2854 dev = port->dev;
2855 if (!dev)
2856 continue;
2857 switch(dev->speed) {
2858 case USB_SPEED_LOW:
2859 speed_str = "1.5";
2860 break;
2861 case USB_SPEED_FULL:
2862 speed_str = "12";
2863 break;
2864 case USB_SPEED_HIGH:
2865 speed_str = "480";
2866 break;
2867 default:
2868 speed_str = "?";
2869 break;
2871 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2872 0, dev->addr, speed_str, dev->devname);
2876 /***********************************************************/
2877 /* PCMCIA/Cardbus */
2879 static struct pcmcia_socket_entry_s {
2880 struct pcmcia_socket_s *socket;
2881 struct pcmcia_socket_entry_s *next;
2882 } *pcmcia_sockets = 0;
2884 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2886 struct pcmcia_socket_entry_s *entry;
2888 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2889 entry->socket = socket;
2890 entry->next = pcmcia_sockets;
2891 pcmcia_sockets = entry;
2894 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2896 struct pcmcia_socket_entry_s *entry, **ptr;
2898 ptr = &pcmcia_sockets;
2899 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2900 if (entry->socket == socket) {
2901 *ptr = entry->next;
2902 qemu_free(entry);
2906 void pcmcia_info(Monitor *mon)
2908 struct pcmcia_socket_entry_s *iter;
2910 if (!pcmcia_sockets)
2911 monitor_printf(mon, "No PCMCIA sockets\n");
2913 for (iter = pcmcia_sockets; iter; iter = iter->next)
2914 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2915 iter->socket->attached ? iter->socket->card_string :
2916 "Empty");
2919 /***********************************************************/
2920 /* register display */
2922 struct DisplayAllocator default_allocator = {
2923 defaultallocator_create_displaysurface,
2924 defaultallocator_resize_displaysurface,
2925 defaultallocator_free_displaysurface
2928 void register_displaystate(DisplayState *ds)
2930 DisplayState **s;
2931 s = &display_state;
2932 while (*s != NULL)
2933 s = &(*s)->next;
2934 ds->next = NULL;
2935 *s = ds;
2938 DisplayState *get_displaystate(void)
2940 return display_state;
2943 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2945 if(ds->allocator == &default_allocator) ds->allocator = da;
2946 return ds->allocator;
2949 /* dumb display */
2951 static void dumb_display_init(void)
2953 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2954 ds->allocator = &default_allocator;
2955 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2956 register_displaystate(ds);
2959 /***********************************************************/
2960 /* I/O handling */
2962 typedef struct IOHandlerRecord {
2963 int fd;
2964 IOCanRWHandler *fd_read_poll;
2965 IOHandler *fd_read;
2966 IOHandler *fd_write;
2967 int deleted;
2968 void *opaque;
2969 /* temporary data */
2970 struct pollfd *ufd;
2971 struct IOHandlerRecord *next;
2972 } IOHandlerRecord;
2974 static IOHandlerRecord *first_io_handler;
2976 /* XXX: fd_read_poll should be suppressed, but an API change is
2977 necessary in the character devices to suppress fd_can_read(). */
2978 int qemu_set_fd_handler2(int fd,
2979 IOCanRWHandler *fd_read_poll,
2980 IOHandler *fd_read,
2981 IOHandler *fd_write,
2982 void *opaque)
2984 IOHandlerRecord **pioh, *ioh;
2986 if (!fd_read && !fd_write) {
2987 pioh = &first_io_handler;
2988 for(;;) {
2989 ioh = *pioh;
2990 if (ioh == NULL)
2991 break;
2992 if (ioh->fd == fd) {
2993 ioh->deleted = 1;
2994 break;
2996 pioh = &ioh->next;
2998 } else {
2999 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3000 if (ioh->fd == fd)
3001 goto found;
3003 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3004 ioh->next = first_io_handler;
3005 first_io_handler = ioh;
3006 found:
3007 ioh->fd = fd;
3008 ioh->fd_read_poll = fd_read_poll;
3009 ioh->fd_read = fd_read;
3010 ioh->fd_write = fd_write;
3011 ioh->opaque = opaque;
3012 ioh->deleted = 0;
3014 main_loop_break();
3015 return 0;
3018 int qemu_set_fd_handler(int fd,
3019 IOHandler *fd_read,
3020 IOHandler *fd_write,
3021 void *opaque)
3023 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3026 #ifdef _WIN32
3027 /***********************************************************/
3028 /* Polling handling */
3030 typedef struct PollingEntry {
3031 PollingFunc *func;
3032 void *opaque;
3033 struct PollingEntry *next;
3034 } PollingEntry;
3036 static PollingEntry *first_polling_entry;
3038 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3040 PollingEntry **ppe, *pe;
3041 pe = qemu_mallocz(sizeof(PollingEntry));
3042 pe->func = func;
3043 pe->opaque = opaque;
3044 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3045 *ppe = pe;
3046 return 0;
3049 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3051 PollingEntry **ppe, *pe;
3052 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3053 pe = *ppe;
3054 if (pe->func == func && pe->opaque == opaque) {
3055 *ppe = pe->next;
3056 qemu_free(pe);
3057 break;
3062 /***********************************************************/
3063 /* Wait objects support */
3064 typedef struct WaitObjects {
3065 int num;
3066 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3067 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3068 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3069 } WaitObjects;
3071 static WaitObjects wait_objects = {0};
3073 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3075 WaitObjects *w = &wait_objects;
3077 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3078 return -1;
3079 w->events[w->num] = handle;
3080 w->func[w->num] = func;
3081 w->opaque[w->num] = opaque;
3082 w->num++;
3083 return 0;
3086 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3088 int i, found;
3089 WaitObjects *w = &wait_objects;
3091 found = 0;
3092 for (i = 0; i < w->num; i++) {
3093 if (w->events[i] == handle)
3094 found = 1;
3095 if (found) {
3096 w->events[i] = w->events[i + 1];
3097 w->func[i] = w->func[i + 1];
3098 w->opaque[i] = w->opaque[i + 1];
3101 if (found)
3102 w->num--;
3104 #endif
3106 /***********************************************************/
3107 /* ram save/restore */
3109 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3111 int v;
3113 v = qemu_get_byte(f);
3114 switch(v) {
3115 case 0:
3116 if (qemu_get_buffer(f, buf, len) != len)
3117 return -EIO;
3118 break;
3119 case 1:
3120 v = qemu_get_byte(f);
3121 memset(buf, v, len);
3122 break;
3123 default:
3124 return -EINVAL;
3127 if (qemu_file_has_error(f))
3128 return -EIO;
3130 return 0;
3133 static int ram_load_v1(QEMUFile *f, void *opaque)
3135 int ret;
3136 ram_addr_t i;
3138 if (qemu_get_be32(f) != phys_ram_size)
3139 return -EINVAL;
3140 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3141 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3142 continue;
3143 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3144 if (ret)
3145 return ret;
3147 return 0;
3150 #define BDRV_HASH_BLOCK_SIZE 1024
3151 #define IOBUF_SIZE 4096
3152 #define RAM_CBLOCK_MAGIC 0xfabe
3154 typedef struct RamDecompressState {
3155 z_stream zstream;
3156 QEMUFile *f;
3157 uint8_t buf[IOBUF_SIZE];
3158 } RamDecompressState;
3160 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3162 int ret;
3163 memset(s, 0, sizeof(*s));
3164 s->f = f;
3165 ret = inflateInit(&s->zstream);
3166 if (ret != Z_OK)
3167 return -1;
3168 return 0;
3171 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3173 int ret, clen;
3175 s->zstream.avail_out = len;
3176 s->zstream.next_out = buf;
3177 while (s->zstream.avail_out > 0) {
3178 if (s->zstream.avail_in == 0) {
3179 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3180 return -1;
3181 clen = qemu_get_be16(s->f);
3182 if (clen > IOBUF_SIZE)
3183 return -1;
3184 qemu_get_buffer(s->f, s->buf, clen);
3185 s->zstream.avail_in = clen;
3186 s->zstream.next_in = s->buf;
3188 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3189 if (ret != Z_OK && ret != Z_STREAM_END) {
3190 return -1;
3193 return 0;
3196 static void ram_decompress_close(RamDecompressState *s)
3198 inflateEnd(&s->zstream);
3201 #define RAM_SAVE_FLAG_FULL 0x01
3202 #define RAM_SAVE_FLAG_COMPRESS 0x02
3203 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3204 #define RAM_SAVE_FLAG_PAGE 0x08
3205 #define RAM_SAVE_FLAG_EOS 0x10
3207 static int is_dup_page(uint8_t *page, uint8_t ch)
3209 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3210 uint32_t *array = (uint32_t *)page;
3211 int i;
3213 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3214 if (array[i] != val)
3215 return 0;
3218 return 1;
3221 static int ram_save_block(QEMUFile *f)
3223 static ram_addr_t current_addr = 0;
3224 ram_addr_t saved_addr = current_addr;
3225 ram_addr_t addr = 0;
3226 int found = 0;
3228 while (addr < phys_ram_size) {
3229 if (kvm_enabled() && current_addr == 0)
3230 kvm_update_dirty_pages_log(); /* FIXME: propagate errors */
3231 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3232 uint8_t ch;
3234 cpu_physical_memory_reset_dirty(current_addr,
3235 current_addr + TARGET_PAGE_SIZE,
3236 MIGRATION_DIRTY_FLAG);
3238 ch = *(phys_ram_base + current_addr);
3240 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3241 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3242 qemu_put_byte(f, ch);
3243 } else {
3244 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3245 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3248 found = 1;
3249 break;
3251 addr += TARGET_PAGE_SIZE;
3252 current_addr = (saved_addr + addr) % phys_ram_size;
3255 return found;
3258 static ram_addr_t ram_save_threshold = 10;
3260 static ram_addr_t ram_save_remaining(void)
3262 ram_addr_t addr;
3263 ram_addr_t count = 0;
3265 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3266 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3267 count++;
3270 return count;
3273 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3275 ram_addr_t addr;
3277 if (stage == 1) {
3278 /* Make sure all dirty bits are set */
3279 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3280 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3281 cpu_physical_memory_set_dirty(addr);
3284 /* Enable dirty memory tracking */
3285 cpu_physical_memory_set_dirty_tracking(1);
3287 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3290 while (!qemu_file_rate_limit(f)) {
3291 int ret;
3293 ret = ram_save_block(f);
3294 if (ret == 0) /* no more blocks */
3295 break;
3298 /* try transferring iterative blocks of memory */
3300 if (stage == 3) {
3302 /* flush all remaining blocks regardless of rate limiting */
3303 while (ram_save_block(f) != 0);
3304 cpu_physical_memory_set_dirty_tracking(0);
3307 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3309 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3312 static int ram_load_dead(QEMUFile *f, void *opaque)
3314 RamDecompressState s1, *s = &s1;
3315 uint8_t buf[10];
3316 ram_addr_t i;
3318 if (ram_decompress_open(s, f) < 0)
3319 return -EINVAL;
3320 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3321 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3322 continue;
3323 if (ram_decompress_buf(s, buf, 1) < 0) {
3324 fprintf(stderr, "Error while reading ram block header\n");
3325 goto error;
3327 if (buf[0] == 0) {
3328 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3329 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3330 goto error;
3332 } else {
3333 error:
3334 printf("Error block header\n");
3335 return -EINVAL;
3338 ram_decompress_close(s);
3340 return 0;
3343 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3345 ram_addr_t addr;
3346 int flags;
3348 if (version_id == 1)
3349 return ram_load_v1(f, opaque);
3351 if (version_id == 2) {
3352 if (qemu_get_be32(f) != phys_ram_size)
3353 return -EINVAL;
3354 return ram_load_dead(f, opaque);
3357 if (version_id != 3)
3358 return -EINVAL;
3360 do {
3361 addr = qemu_get_be64(f);
3363 flags = addr & ~TARGET_PAGE_MASK;
3364 addr &= TARGET_PAGE_MASK;
3366 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3367 if (addr != phys_ram_size)
3368 return -EINVAL;
3371 if (flags & RAM_SAVE_FLAG_FULL) {
3372 if (ram_load_dead(f, opaque) < 0)
3373 return -EINVAL;
3376 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3377 uint8_t ch = qemu_get_byte(f);
3378 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3379 } else if (flags & RAM_SAVE_FLAG_PAGE)
3380 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3381 } while (!(flags & RAM_SAVE_FLAG_EOS));
3383 return 0;
3386 void qemu_service_io(void)
3388 CPUState *env = cpu_single_env;
3389 if (env) {
3390 cpu_exit(env);
3391 #ifdef USE_KQEMU
3392 if (env->kqemu_enabled) {
3393 kqemu_cpu_interrupt(env);
3395 #endif
3399 /***********************************************************/
3400 /* bottom halves (can be seen as timers which expire ASAP) */
3402 struct QEMUBH {
3403 QEMUBHFunc *cb;
3404 void *opaque;
3405 int scheduled;
3406 int idle;
3407 int deleted;
3408 QEMUBH *next;
3411 static QEMUBH *first_bh = NULL;
3413 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3415 QEMUBH *bh;
3416 bh = qemu_mallocz(sizeof(QEMUBH));
3417 bh->cb = cb;
3418 bh->opaque = opaque;
3419 bh->next = first_bh;
3420 first_bh = bh;
3421 return bh;
3424 int qemu_bh_poll(void)
3426 QEMUBH *bh, **bhp;
3427 int ret;
3429 ret = 0;
3430 for (bh = first_bh; bh; bh = bh->next) {
3431 if (!bh->deleted && bh->scheduled) {
3432 bh->scheduled = 0;
3433 if (!bh->idle)
3434 ret = 1;
3435 bh->idle = 0;
3436 bh->cb(bh->opaque);
3440 /* remove deleted bhs */
3441 bhp = &first_bh;
3442 while (*bhp) {
3443 bh = *bhp;
3444 if (bh->deleted) {
3445 *bhp = bh->next;
3446 qemu_free(bh);
3447 } else
3448 bhp = &bh->next;
3451 return ret;
3454 void qemu_bh_schedule_idle(QEMUBH *bh)
3456 if (bh->scheduled)
3457 return;
3458 bh->scheduled = 1;
3459 bh->idle = 1;
3462 void qemu_bh_schedule(QEMUBH *bh)
3464 CPUState *env = cpu_single_env;
3465 if (bh->scheduled)
3466 return;
3467 bh->scheduled = 1;
3468 bh->idle = 0;
3469 /* stop the currently executing CPU to execute the BH ASAP */
3470 if (env) {
3471 cpu_exit(env);
3473 main_loop_break();
3476 void qemu_bh_cancel(QEMUBH *bh)
3478 bh->scheduled = 0;
3481 void qemu_bh_delete(QEMUBH *bh)
3483 bh->scheduled = 0;
3484 bh->deleted = 1;
3487 static void qemu_bh_update_timeout(int *timeout)
3489 QEMUBH *bh;
3491 for (bh = first_bh; bh; bh = bh->next) {
3492 if (!bh->deleted && bh->scheduled) {
3493 if (bh->idle) {
3494 /* idle bottom halves will be polled at least
3495 * every 10ms */
3496 *timeout = MIN(10, *timeout);
3497 } else {
3498 /* non-idle bottom halves will be executed
3499 * immediately */
3500 *timeout = 0;
3501 break;
3507 /***********************************************************/
3508 /* machine registration */
3510 static QEMUMachine *first_machine = NULL;
3511 QEMUMachine *current_machine = NULL;
3513 int qemu_register_machine(QEMUMachine *m)
3515 QEMUMachine **pm;
3516 pm = &first_machine;
3517 while (*pm != NULL)
3518 pm = &(*pm)->next;
3519 m->next = NULL;
3520 *pm = m;
3521 return 0;
3524 static QEMUMachine *find_machine(const char *name)
3526 QEMUMachine *m;
3528 for(m = first_machine; m != NULL; m = m->next) {
3529 if (!strcmp(m->name, name))
3530 return m;
3532 return NULL;
3535 /***********************************************************/
3536 /* main execution loop */
3538 static void gui_update(void *opaque)
3540 uint64_t interval = GUI_REFRESH_INTERVAL;
3541 DisplayState *ds = opaque;
3542 DisplayChangeListener *dcl = ds->listeners;
3544 dpy_refresh(ds);
3546 while (dcl != NULL) {
3547 if (dcl->gui_timer_interval &&
3548 dcl->gui_timer_interval < interval)
3549 interval = dcl->gui_timer_interval;
3550 dcl = dcl->next;
3552 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3555 static void nographic_update(void *opaque)
3557 uint64_t interval = GUI_REFRESH_INTERVAL;
3559 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3562 struct vm_change_state_entry {
3563 VMChangeStateHandler *cb;
3564 void *opaque;
3565 LIST_ENTRY (vm_change_state_entry) entries;
3568 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3570 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3571 void *opaque)
3573 VMChangeStateEntry *e;
3575 e = qemu_mallocz(sizeof (*e));
3577 e->cb = cb;
3578 e->opaque = opaque;
3579 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3580 return e;
3583 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3585 LIST_REMOVE (e, entries);
3586 qemu_free (e);
3589 static void vm_state_notify(int running, int reason)
3591 VMChangeStateEntry *e;
3593 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3594 e->cb(e->opaque, running, reason);
3598 void vm_start(void)
3600 if (!vm_running) {
3601 cpu_enable_ticks();
3602 vm_running = 1;
3603 vm_state_notify(1, 0);
3604 if (kvm_enabled())
3605 qemu_kvm_resume_all_threads();
3606 qemu_rearm_alarm_timer(alarm_timer);
3610 void vm_stop(int reason)
3612 if (vm_running) {
3613 cpu_disable_ticks();
3614 vm_running = 0;
3615 if (kvm_enabled())
3616 qemu_kvm_pause_all_threads();
3617 vm_state_notify(0, reason);
3621 /* reset/shutdown handler */
3623 typedef struct QEMUResetEntry {
3624 QEMUResetHandler *func;
3625 void *opaque;
3626 struct QEMUResetEntry *next;
3627 } QEMUResetEntry;
3629 static QEMUResetEntry *first_reset_entry;
3630 static int reset_requested;
3631 static int shutdown_requested;
3632 static int powerdown_requested;
3634 int qemu_shutdown_requested(void)
3636 int r = shutdown_requested;
3637 shutdown_requested = 0;
3638 return r;
3641 int qemu_reset_requested(void)
3643 int r = reset_requested;
3644 reset_requested = 0;
3645 return r;
3648 int qemu_powerdown_requested(void)
3650 int r = powerdown_requested;
3651 powerdown_requested = 0;
3652 return r;
3655 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3657 QEMUResetEntry **pre, *re;
3659 pre = &first_reset_entry;
3660 while (*pre != NULL)
3661 pre = &(*pre)->next;
3662 re = qemu_mallocz(sizeof(QEMUResetEntry));
3663 re->func = func;
3664 re->opaque = opaque;
3665 re->next = NULL;
3666 *pre = re;
3669 void qemu_system_reset(void)
3671 QEMUResetEntry *re;
3673 /* reset all devices */
3674 for(re = first_reset_entry; re != NULL; re = re->next) {
3675 re->func(re->opaque);
3679 void qemu_system_reset_request(void)
3681 if (no_reboot) {
3682 shutdown_requested = 1;
3683 } else {
3684 reset_requested = 1;
3686 if (cpu_single_env) {
3687 qemu_kvm_cpu_stop(cpu_single_env);
3688 cpu_exit(cpu_single_env);
3692 void qemu_system_shutdown_request(void)
3694 shutdown_requested = 1;
3695 if (cpu_single_env)
3696 cpu_exit(cpu_single_env);
3699 void qemu_system_powerdown_request(void)
3701 powerdown_requested = 1;
3702 if (cpu_single_env)
3703 cpu_exit(cpu_single_env);
3706 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
3707 struct timeval *tv)
3709 int ret;
3711 /* KVM holds a mutex while QEMU code is running, we need hooks to
3712 release the mutex whenever QEMU code sleeps. */
3714 kvm_sleep_begin();
3716 ret = select(max_fd, rfds, wfds, xfds, tv);
3718 kvm_sleep_end();
3720 return ret;
3723 #ifdef _WIN32
3724 static void host_main_loop_wait(int *timeout)
3726 int ret, ret2, i;
3727 PollingEntry *pe;
3730 /* XXX: need to suppress polling by better using win32 events */
3731 ret = 0;
3732 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3733 ret |= pe->func(pe->opaque);
3735 if (ret == 0) {
3736 int err;
3737 WaitObjects *w = &wait_objects;
3739 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3740 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3741 if (w->func[ret - WAIT_OBJECT_0])
3742 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3744 /* Check for additional signaled events */
3745 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3747 /* Check if event is signaled */
3748 ret2 = WaitForSingleObject(w->events[i], 0);
3749 if(ret2 == WAIT_OBJECT_0) {
3750 if (w->func[i])
3751 w->func[i](w->opaque[i]);
3752 } else if (ret2 == WAIT_TIMEOUT) {
3753 } else {
3754 err = GetLastError();
3755 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3758 } else if (ret == WAIT_TIMEOUT) {
3759 } else {
3760 err = GetLastError();
3761 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3765 *timeout = 0;
3767 #else
3768 static void host_main_loop_wait(int *timeout)
3771 #endif
3773 void main_loop_wait(int timeout)
3775 IOHandlerRecord *ioh;
3776 fd_set rfds, wfds, xfds;
3777 int ret, nfds;
3778 struct timeval tv;
3780 qemu_bh_update_timeout(&timeout);
3782 host_main_loop_wait(&timeout);
3784 /* poll any events */
3785 /* XXX: separate device handlers from system ones */
3786 nfds = -1;
3787 FD_ZERO(&rfds);
3788 FD_ZERO(&wfds);
3789 FD_ZERO(&xfds);
3790 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3791 if (ioh->deleted)
3792 continue;
3793 if (ioh->fd_read &&
3794 (!ioh->fd_read_poll ||
3795 ioh->fd_read_poll(ioh->opaque) != 0)) {
3796 FD_SET(ioh->fd, &rfds);
3797 if (ioh->fd > nfds)
3798 nfds = ioh->fd;
3800 if (ioh->fd_write) {
3801 FD_SET(ioh->fd, &wfds);
3802 if (ioh->fd > nfds)
3803 nfds = ioh->fd;
3807 tv.tv_sec = timeout / 1000;
3808 tv.tv_usec = (timeout % 1000) * 1000;
3810 #if defined(CONFIG_SLIRP)
3811 if (slirp_is_inited()) {
3812 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3814 #endif
3815 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3816 if (ret > 0) {
3817 IOHandlerRecord **pioh;
3819 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3820 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3821 ioh->fd_read(ioh->opaque);
3822 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3823 FD_CLR(ioh->fd, &rfds);
3825 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3826 ioh->fd_write(ioh->opaque);
3830 /* remove deleted IO handlers */
3831 pioh = &first_io_handler;
3832 while (*pioh) {
3833 ioh = *pioh;
3834 if (ioh->deleted) {
3835 *pioh = ioh->next;
3836 qemu_free(ioh);
3837 } else
3838 pioh = &ioh->next;
3841 #if defined(CONFIG_SLIRP)
3842 if (slirp_is_inited()) {
3843 if (ret < 0) {
3844 FD_ZERO(&rfds);
3845 FD_ZERO(&wfds);
3846 FD_ZERO(&xfds);
3848 slirp_select_poll(&rfds, &wfds, &xfds);
3850 #endif
3852 /* vm time timers */
3853 if (vm_running && (!cur_cpu
3854 || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER))))
3855 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3856 qemu_get_clock(vm_clock));
3858 /* real time timers */
3859 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3860 qemu_get_clock(rt_clock));
3862 /* Check bottom-halves last in case any of the earlier events triggered
3863 them. */
3864 qemu_bh_poll();
3868 static int main_loop(void)
3870 int ret, timeout;
3871 #ifdef CONFIG_PROFILER
3872 int64_t ti;
3873 #endif
3874 CPUState *env;
3877 if (kvm_enabled()) {
3878 kvm_main_loop();
3879 cpu_disable_ticks();
3880 return 0;
3883 cur_cpu = first_cpu;
3884 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3885 for(;;) {
3886 if (vm_running) {
3888 for(;;) {
3889 /* get next cpu */
3890 env = next_cpu;
3891 #ifdef CONFIG_PROFILER
3892 ti = profile_getclock();
3893 #endif
3894 if (use_icount) {
3895 int64_t count;
3896 int decr;
3897 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3898 env->icount_decr.u16.low = 0;
3899 env->icount_extra = 0;
3900 count = qemu_next_deadline();
3901 count = (count + (1 << icount_time_shift) - 1)
3902 >> icount_time_shift;
3903 qemu_icount += count;
3904 decr = (count > 0xffff) ? 0xffff : count;
3905 count -= decr;
3906 env->icount_decr.u16.low = decr;
3907 env->icount_extra = count;
3909 ret = cpu_exec(env);
3910 #ifdef CONFIG_PROFILER
3911 qemu_time += profile_getclock() - ti;
3912 #endif
3913 if (use_icount) {
3914 /* Fold pending instructions back into the
3915 instruction counter, and clear the interrupt flag. */
3916 qemu_icount -= (env->icount_decr.u16.low
3917 + env->icount_extra);
3918 env->icount_decr.u32 = 0;
3919 env->icount_extra = 0;
3921 next_cpu = env->next_cpu ?: first_cpu;
3922 if (event_pending && likely(ret != EXCP_DEBUG)) {
3923 ret = EXCP_INTERRUPT;
3924 event_pending = 0;
3925 break;
3927 if (ret == EXCP_HLT) {
3928 /* Give the next CPU a chance to run. */
3929 cur_cpu = env;
3930 continue;
3932 if (ret != EXCP_HALTED)
3933 break;
3934 /* all CPUs are halted ? */
3935 if (env == cur_cpu)
3936 break;
3938 cur_cpu = env;
3940 if (shutdown_requested) {
3941 ret = EXCP_INTERRUPT;
3942 if (no_shutdown) {
3943 vm_stop(0);
3944 no_shutdown = 0;
3946 else
3947 break;
3949 if (reset_requested) {
3950 reset_requested = 0;
3951 qemu_system_reset();
3952 ret = EXCP_INTERRUPT;
3954 if (powerdown_requested) {
3955 powerdown_requested = 0;
3956 qemu_system_powerdown();
3957 ret = EXCP_INTERRUPT;
3959 #ifdef CONFIG_GDBSTUB
3960 if (unlikely(ret == EXCP_DEBUG)) {
3961 gdb_set_stop_cpu(cur_cpu);
3962 vm_stop(EXCP_DEBUG);
3964 #endif
3965 /* If all cpus are halted then wait until the next IRQ */
3966 /* XXX: use timeout computed from timers */
3967 if (ret == EXCP_HALTED) {
3968 if (use_icount) {
3969 int64_t add;
3970 int64_t delta;
3971 /* Advance virtual time to the next event. */
3972 if (use_icount == 1) {
3973 /* When not using an adaptive execution frequency
3974 we tend to get badly out of sync with real time,
3975 so just delay for a reasonable amount of time. */
3976 delta = 0;
3977 } else {
3978 delta = cpu_get_icount() - cpu_get_clock();
3980 if (delta > 0) {
3981 /* If virtual time is ahead of real time then just
3982 wait for IO. */
3983 timeout = (delta / 1000000) + 1;
3984 } else {
3985 /* Wait for either IO to occur or the next
3986 timer event. */
3987 add = qemu_next_deadline();
3988 /* We advance the timer before checking for IO.
3989 Limit the amount we advance so that early IO
3990 activity won't get the guest too far ahead. */
3991 if (add > 10000000)
3992 add = 10000000;
3993 delta += add;
3994 add = (add + (1 << icount_time_shift) - 1)
3995 >> icount_time_shift;
3996 qemu_icount += add;
3997 timeout = delta / 1000000;
3998 if (timeout < 0)
3999 timeout = 0;
4001 } else {
4002 timeout = 5000;
4004 } else {
4005 timeout = 0;
4007 } else {
4008 if (shutdown_requested) {
4009 ret = EXCP_INTERRUPT;
4010 break;
4012 timeout = 5000;
4014 #ifdef CONFIG_PROFILER
4015 ti = profile_getclock();
4016 #endif
4017 main_loop_wait(timeout);
4018 #ifdef CONFIG_PROFILER
4019 dev_time += profile_getclock() - ti;
4020 #endif
4022 cpu_disable_ticks();
4023 return ret;
4026 static void help(int exitcode)
4028 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
4029 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
4030 "usage: %s [options] [disk_image]\n"
4031 "\n"
4032 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4033 "\n"
4034 #define DEF(option, opt_arg, opt_enum, opt_help) \
4035 opt_help
4036 #define DEFHEADING(text) stringify(text) "\n"
4037 #include "qemu-options.h"
4038 #undef DEF
4039 #undef DEFHEADING
4040 #undef GEN_DOCS
4041 "\n"
4042 "During emulation, the following keys are useful:\n"
4043 "ctrl-alt-f toggle full screen\n"
4044 "ctrl-alt-n switch to virtual console 'n'\n"
4045 "ctrl-alt toggle mouse and keyboard grab\n"
4046 "\n"
4047 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4049 "qemu",
4050 DEFAULT_RAM_SIZE,
4051 #ifndef _WIN32
4052 DEFAULT_NETWORK_SCRIPT,
4053 DEFAULT_NETWORK_DOWN_SCRIPT,
4054 #endif
4055 DEFAULT_GDBSTUB_PORT,
4056 "/tmp/qemu.log");
4057 exit(exitcode);
4060 #define HAS_ARG 0x0001
4062 enum {
4063 #define DEF(option, opt_arg, opt_enum, opt_help) \
4064 opt_enum,
4065 #define DEFHEADING(text)
4066 #include "qemu-options.h"
4067 #undef DEF
4068 #undef DEFHEADING
4069 #undef GEN_DOCS
4072 typedef struct QEMUOption {
4073 const char *name;
4074 int flags;
4075 int index;
4076 } QEMUOption;
4078 static const QEMUOption qemu_options[] = {
4079 { "h", 0, QEMU_OPTION_h },
4080 #define DEF(option, opt_arg, opt_enum, opt_help) \
4081 { option, opt_arg, opt_enum },
4082 #define DEFHEADING(text)
4083 #include "qemu-options.h"
4084 #undef DEF
4085 #undef DEFHEADING
4086 #undef GEN_DOCS
4087 { NULL },
4090 #ifdef HAS_AUDIO
4091 struct soundhw soundhw[] = {
4092 #ifdef HAS_AUDIO_CHOICE
4093 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4095 "pcspk",
4096 "PC speaker",
4099 { .init_isa = pcspk_audio_init }
4101 #endif
4103 #ifdef CONFIG_SB16
4105 "sb16",
4106 "Creative Sound Blaster 16",
4109 { .init_isa = SB16_init }
4111 #endif
4113 #ifdef CONFIG_CS4231A
4115 "cs4231a",
4116 "CS4231A",
4119 { .init_isa = cs4231a_init }
4121 #endif
4123 #ifdef CONFIG_ADLIB
4125 "adlib",
4126 #ifdef HAS_YMF262
4127 "Yamaha YMF262 (OPL3)",
4128 #else
4129 "Yamaha YM3812 (OPL2)",
4130 #endif
4133 { .init_isa = Adlib_init }
4135 #endif
4137 #ifdef CONFIG_GUS
4139 "gus",
4140 "Gravis Ultrasound GF1",
4143 { .init_isa = GUS_init }
4145 #endif
4147 #ifdef CONFIG_AC97
4149 "ac97",
4150 "Intel 82801AA AC97 Audio",
4153 { .init_pci = ac97_init }
4155 #endif
4157 #ifdef CONFIG_ES1370
4159 "es1370",
4160 "ENSONIQ AudioPCI ES1370",
4163 { .init_pci = es1370_init }
4165 #endif
4167 #endif /* HAS_AUDIO_CHOICE */
4169 { NULL, NULL, 0, 0, { NULL } }
4172 static void select_soundhw (const char *optarg)
4174 struct soundhw *c;
4176 if (*optarg == '?') {
4177 show_valid_cards:
4179 printf ("Valid sound card names (comma separated):\n");
4180 for (c = soundhw; c->name; ++c) {
4181 printf ("%-11s %s\n", c->name, c->descr);
4183 printf ("\n-soundhw all will enable all of the above\n");
4184 exit (*optarg != '?');
4186 else {
4187 size_t l;
4188 const char *p;
4189 char *e;
4190 int bad_card = 0;
4192 if (!strcmp (optarg, "all")) {
4193 for (c = soundhw; c->name; ++c) {
4194 c->enabled = 1;
4196 return;
4199 p = optarg;
4200 while (*p) {
4201 e = strchr (p, ',');
4202 l = !e ? strlen (p) : (size_t) (e - p);
4204 for (c = soundhw; c->name; ++c) {
4205 if (!strncmp (c->name, p, l)) {
4206 c->enabled = 1;
4207 break;
4211 if (!c->name) {
4212 if (l > 80) {
4213 fprintf (stderr,
4214 "Unknown sound card name (too big to show)\n");
4216 else {
4217 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4218 (int) l, p);
4220 bad_card = 1;
4222 p += l + (e != NULL);
4225 if (bad_card)
4226 goto show_valid_cards;
4229 #endif
4231 static void select_vgahw (const char *p)
4233 const char *opts;
4235 if (strstart(p, "std", &opts)) {
4236 std_vga_enabled = 1;
4237 cirrus_vga_enabled = 0;
4238 vmsvga_enabled = 0;
4239 } else if (strstart(p, "cirrus", &opts)) {
4240 cirrus_vga_enabled = 1;
4241 std_vga_enabled = 0;
4242 vmsvga_enabled = 0;
4243 } else if (strstart(p, "vmware", &opts)) {
4244 cirrus_vga_enabled = 0;
4245 std_vga_enabled = 0;
4246 vmsvga_enabled = 1;
4247 } else if (strstart(p, "none", &opts)) {
4248 cirrus_vga_enabled = 0;
4249 std_vga_enabled = 0;
4250 vmsvga_enabled = 0;
4251 } else {
4252 invalid_vga:
4253 fprintf(stderr, "Unknown vga type: %s\n", p);
4254 exit(1);
4256 while (*opts) {
4257 const char *nextopt;
4259 if (strstart(opts, ",retrace=", &nextopt)) {
4260 opts = nextopt;
4261 if (strstart(opts, "dumb", &nextopt))
4262 vga_retrace_method = VGA_RETRACE_DUMB;
4263 else if (strstart(opts, "precise", &nextopt))
4264 vga_retrace_method = VGA_RETRACE_PRECISE;
4265 else goto invalid_vga;
4266 } else goto invalid_vga;
4267 opts = nextopt;
4271 #ifdef _WIN32
4272 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4274 exit(STATUS_CONTROL_C_EXIT);
4275 return TRUE;
4277 #endif
4279 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4281 int ret;
4283 if(strlen(str) != 36)
4284 return -1;
4286 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4287 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4288 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4290 if(ret != 16)
4291 return -1;
4293 return 0;
4296 #define MAX_NET_CLIENTS 32
4298 static int saved_argc;
4299 static char **saved_argv;
4300 static const char *saved_incoming;
4302 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
4304 *argc = saved_argc;
4305 *argv = saved_argv;
4306 *opt_daemonize = daemonize;
4307 *opt_incoming = saved_incoming;
4310 #ifdef USE_KVM
4312 #define HUGETLBFS_MAGIC 0x958458f6
4314 static long gethugepagesize(const char *path)
4316 struct statfs fs;
4317 int ret;
4319 do {
4320 ret = statfs(path, &fs);
4321 } while (ret != 0 && errno == EINTR);
4323 if (ret != 0) {
4324 perror("statfs");
4325 return 0;
4328 if (fs.f_type != HUGETLBFS_MAGIC)
4329 fprintf(stderr, "Warning: path not on HugeTLBFS: %s\n", path);
4331 return fs.f_bsize;
4334 static void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4336 char *filename;
4337 void *area;
4338 int fd;
4339 #ifdef MAP_POPULATE
4340 int flags;
4341 #endif
4343 if (!kvm_has_sync_mmu()) {
4344 fprintf(stderr, "host lacks mmu notifiers, disabling --mem-path\n");
4345 return NULL;
4348 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4349 return NULL;
4351 hpagesize = gethugepagesize(path);
4352 if (!hpagesize)
4353 return NULL;
4355 fd = mkstemp(filename);
4356 if (fd < 0) {
4357 perror("mkstemp");
4358 free(filename);
4359 return NULL;
4361 unlink(filename);
4362 free(filename);
4364 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4367 * ftruncate is not supported by hugetlbfs in older
4368 * hosts, so don't bother checking for errors.
4369 * If anything goes wrong with it under other filesystems,
4370 * mmap will fail.
4372 ftruncate(fd, memory);
4374 #ifdef MAP_POPULATE
4375 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4376 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4377 * to sidestep this quirk.
4379 flags = mem_prealloc ? MAP_POPULATE|MAP_SHARED : MAP_PRIVATE;
4380 area = mmap(0, memory, PROT_READ|PROT_WRITE, flags, fd, 0);
4381 #else
4382 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4383 #endif
4384 if (area == MAP_FAILED) {
4385 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4386 close(fd);
4387 return (NULL);
4389 *len = memory;
4390 return area;
4392 #endif
4394 static void *qemu_alloc_physram(unsigned long memory)
4396 void *area = NULL;
4397 #ifdef USE_KVM
4398 unsigned long map_len = memory;
4400 if (mem_path)
4401 area = alloc_mem_area(memory, &map_len, mem_path);
4402 #endif
4403 if (!area)
4404 area = qemu_vmalloc(memory);
4405 #ifdef USE_KVM
4406 if (kvm_setup_guest_memory(area, map_len))
4407 area = NULL;
4408 #endif
4409 return area;
4412 #ifndef _WIN32
4414 static void termsig_handler(int signal)
4416 qemu_system_shutdown_request();
4419 static void termsig_setup(void)
4421 struct sigaction act;
4423 memset(&act, 0, sizeof(act));
4424 act.sa_handler = termsig_handler;
4425 sigaction(SIGINT, &act, NULL);
4426 sigaction(SIGHUP, &act, NULL);
4427 sigaction(SIGTERM, &act, NULL);
4430 #endif
4432 int main(int argc, char **argv, char **envp)
4434 #ifdef CONFIG_GDBSTUB
4435 const char *gdbstub_dev = NULL;
4436 #endif
4437 uint32_t boot_devices_bitmap = 0;
4438 int i;
4439 int snapshot, linux_boot, net_boot;
4440 const char *initrd_filename;
4441 const char *kernel_filename, *kernel_cmdline;
4442 const char *boot_devices = "";
4443 DisplayState *ds;
4444 DisplayChangeListener *dcl;
4445 int cyls, heads, secs, translation;
4446 const char *net_clients[MAX_NET_CLIENTS];
4447 int nb_net_clients;
4448 const char *bt_opts[MAX_BT_CMDLINE];
4449 int nb_bt_opts;
4450 int hda_index;
4451 int optind;
4452 const char *r, *optarg;
4453 CharDriverState *monitor_hd = NULL;
4454 const char *monitor_device;
4455 const char *serial_devices[MAX_SERIAL_PORTS];
4456 int serial_device_index;
4457 const char *parallel_devices[MAX_PARALLEL_PORTS];
4458 int parallel_device_index;
4459 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4460 int virtio_console_index;
4461 const char *loadvm = NULL;
4462 QEMUMachine *machine;
4463 const char *cpu_model;
4464 const char *usb_devices[MAX_USB_CMDLINE];
4465 int usb_devices_index;
4466 #ifndef _WIN32
4467 int fds[2];
4468 #endif
4469 int tb_size;
4470 const char *pid_file = NULL;
4471 const char *incoming = NULL;
4472 #ifndef _WIN32
4473 int fd = 0;
4474 struct passwd *pwd = NULL;
4475 const char *chroot_dir = NULL;
4476 const char *run_as = NULL;
4477 #endif
4479 qemu_cache_utils_init(envp);
4481 LIST_INIT (&vm_change_state_head);
4482 #ifndef _WIN32
4484 struct sigaction act;
4485 sigfillset(&act.sa_mask);
4486 act.sa_flags = 0;
4487 act.sa_handler = SIG_IGN;
4488 sigaction(SIGPIPE, &act, NULL);
4490 #else
4491 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4492 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4493 QEMU to run on a single CPU */
4495 HANDLE h;
4496 DWORD mask, smask;
4497 int i;
4498 h = GetCurrentProcess();
4499 if (GetProcessAffinityMask(h, &mask, &smask)) {
4500 for(i = 0; i < 32; i++) {
4501 if (mask & (1 << i))
4502 break;
4504 if (i != 32) {
4505 mask = 1 << i;
4506 SetProcessAffinityMask(h, mask);
4510 #endif
4512 register_machines();
4513 machine = first_machine;
4514 cpu_model = NULL;
4515 initrd_filename = NULL;
4516 ram_size = 0;
4517 vga_ram_size = VGA_RAM_SIZE;
4518 snapshot = 0;
4519 nographic = 0;
4520 curses = 0;
4521 kernel_filename = NULL;
4522 kernel_cmdline = "";
4523 cyls = heads = secs = 0;
4524 translation = BIOS_ATA_TRANSLATION_AUTO;
4525 monitor_device = "vc:80Cx24C";
4527 serial_devices[0] = "vc:80Cx24C";
4528 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4529 serial_devices[i] = NULL;
4530 serial_device_index = 0;
4532 parallel_devices[0] = "vc:80Cx24C";
4533 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4534 parallel_devices[i] = NULL;
4535 parallel_device_index = 0;
4537 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4538 virtio_consoles[i] = NULL;
4539 virtio_console_index = 0;
4541 usb_devices_index = 0;
4542 assigned_devices_index = 0;
4544 nb_net_clients = 0;
4545 nb_bt_opts = 0;
4546 nb_drives = 0;
4547 nb_drives_opt = 0;
4548 hda_index = -1;
4550 nb_nics = 0;
4552 tb_size = 0;
4553 autostart= 1;
4555 optind = 1;
4556 for(;;) {
4557 if (optind >= argc)
4558 break;
4559 r = argv[optind];
4560 if (r[0] != '-') {
4561 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4562 } else {
4563 const QEMUOption *popt;
4565 optind++;
4566 /* Treat --foo the same as -foo. */
4567 if (r[1] == '-')
4568 r++;
4569 popt = qemu_options;
4570 for(;;) {
4571 if (!popt->name) {
4572 fprintf(stderr, "%s: invalid option -- '%s'\n",
4573 argv[0], r);
4574 exit(1);
4576 if (!strcmp(popt->name, r + 1))
4577 break;
4578 popt++;
4580 if (popt->flags & HAS_ARG) {
4581 if (optind >= argc) {
4582 fprintf(stderr, "%s: option '%s' requires an argument\n",
4583 argv[0], r);
4584 exit(1);
4586 optarg = argv[optind++];
4587 } else {
4588 optarg = NULL;
4591 switch(popt->index) {
4592 case QEMU_OPTION_M:
4593 machine = find_machine(optarg);
4594 if (!machine) {
4595 QEMUMachine *m;
4596 printf("Supported machines are:\n");
4597 for(m = first_machine; m != NULL; m = m->next) {
4598 printf("%-10s %s%s\n",
4599 m->name, m->desc,
4600 m == first_machine ? " (default)" : "");
4602 exit(*optarg != '?');
4604 break;
4605 case QEMU_OPTION_cpu:
4606 /* hw initialization will check this */
4607 if (*optarg == '?') {
4608 /* XXX: implement xxx_cpu_list for targets that still miss it */
4609 #if defined(cpu_list)
4610 cpu_list(stdout, &fprintf);
4611 #endif
4612 exit(0);
4613 } else {
4614 cpu_model = optarg;
4616 break;
4617 case QEMU_OPTION_initrd:
4618 initrd_filename = optarg;
4619 break;
4620 case QEMU_OPTION_hda:
4621 if (cyls == 0)
4622 hda_index = drive_add(optarg, HD_ALIAS, 0);
4623 else
4624 hda_index = drive_add(optarg, HD_ALIAS
4625 ",cyls=%d,heads=%d,secs=%d%s",
4626 0, cyls, heads, secs,
4627 translation == BIOS_ATA_TRANSLATION_LBA ?
4628 ",trans=lba" :
4629 translation == BIOS_ATA_TRANSLATION_NONE ?
4630 ",trans=none" : "");
4631 break;
4632 case QEMU_OPTION_hdb:
4633 case QEMU_OPTION_hdc:
4634 case QEMU_OPTION_hdd:
4635 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4636 break;
4637 case QEMU_OPTION_drive:
4638 drive_add(NULL, "%s", optarg);
4639 break;
4640 case QEMU_OPTION_mtdblock:
4641 drive_add(optarg, MTD_ALIAS);
4642 break;
4643 case QEMU_OPTION_sd:
4644 drive_add(optarg, SD_ALIAS);
4645 break;
4646 case QEMU_OPTION_pflash:
4647 drive_add(optarg, PFLASH_ALIAS);
4648 break;
4649 case QEMU_OPTION_snapshot:
4650 snapshot = 1;
4651 break;
4652 case QEMU_OPTION_hdachs:
4654 const char *p;
4655 p = optarg;
4656 cyls = strtol(p, (char **)&p, 0);
4657 if (cyls < 1 || cyls > 16383)
4658 goto chs_fail;
4659 if (*p != ',')
4660 goto chs_fail;
4661 p++;
4662 heads = strtol(p, (char **)&p, 0);
4663 if (heads < 1 || heads > 16)
4664 goto chs_fail;
4665 if (*p != ',')
4666 goto chs_fail;
4667 p++;
4668 secs = strtol(p, (char **)&p, 0);
4669 if (secs < 1 || secs > 63)
4670 goto chs_fail;
4671 if (*p == ',') {
4672 p++;
4673 if (!strcmp(p, "none"))
4674 translation = BIOS_ATA_TRANSLATION_NONE;
4675 else if (!strcmp(p, "lba"))
4676 translation = BIOS_ATA_TRANSLATION_LBA;
4677 else if (!strcmp(p, "auto"))
4678 translation = BIOS_ATA_TRANSLATION_AUTO;
4679 else
4680 goto chs_fail;
4681 } else if (*p != '\0') {
4682 chs_fail:
4683 fprintf(stderr, "qemu: invalid physical CHS format\n");
4684 exit(1);
4686 if (hda_index != -1)
4687 snprintf(drives_opt[hda_index].opt,
4688 sizeof(drives_opt[hda_index].opt),
4689 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4690 0, cyls, heads, secs,
4691 translation == BIOS_ATA_TRANSLATION_LBA ?
4692 ",trans=lba" :
4693 translation == BIOS_ATA_TRANSLATION_NONE ?
4694 ",trans=none" : "");
4696 break;
4697 case QEMU_OPTION_nographic:
4698 nographic = 1;
4699 break;
4700 #ifdef CONFIG_CURSES
4701 case QEMU_OPTION_curses:
4702 curses = 1;
4703 break;
4704 #endif
4705 case QEMU_OPTION_portrait:
4706 graphic_rotate = 1;
4707 break;
4708 case QEMU_OPTION_kernel:
4709 kernel_filename = optarg;
4710 break;
4711 case QEMU_OPTION_append:
4712 kernel_cmdline = optarg;
4713 break;
4714 case QEMU_OPTION_cdrom:
4715 drive_add(optarg, CDROM_ALIAS);
4716 break;
4717 case QEMU_OPTION_boot:
4718 boot_devices = optarg;
4719 /* We just do some generic consistency checks */
4721 /* Could easily be extended to 64 devices if needed */
4722 const char *p;
4724 boot_devices_bitmap = 0;
4725 for (p = boot_devices; *p != '\0'; p++) {
4726 /* Allowed boot devices are:
4727 * a b : floppy disk drives
4728 * c ... f : IDE disk drives
4729 * g ... m : machine implementation dependant drives
4730 * n ... p : network devices
4731 * It's up to each machine implementation to check
4732 * if the given boot devices match the actual hardware
4733 * implementation and firmware features.
4735 if (*p < 'a' || *p > 'q') {
4736 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4737 exit(1);
4739 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4740 fprintf(stderr,
4741 "Boot device '%c' was given twice\n",*p);
4742 exit(1);
4744 boot_devices_bitmap |= 1 << (*p - 'a');
4747 break;
4748 case QEMU_OPTION_fda:
4749 case QEMU_OPTION_fdb:
4750 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4751 break;
4752 #ifdef TARGET_I386
4753 case QEMU_OPTION_no_fd_bootchk:
4754 fd_bootchk = 0;
4755 break;
4756 #endif
4757 case QEMU_OPTION_net:
4758 if (nb_net_clients >= MAX_NET_CLIENTS) {
4759 fprintf(stderr, "qemu: too many network clients\n");
4760 exit(1);
4762 net_clients[nb_net_clients] = optarg;
4763 nb_net_clients++;
4764 break;
4765 #ifdef CONFIG_SLIRP
4766 case QEMU_OPTION_tftp:
4767 tftp_prefix = optarg;
4768 break;
4769 case QEMU_OPTION_bootp:
4770 bootp_filename = optarg;
4771 break;
4772 #ifndef _WIN32
4773 case QEMU_OPTION_smb:
4774 net_slirp_smb(optarg);
4775 break;
4776 #endif
4777 case QEMU_OPTION_redir:
4778 net_slirp_redir(optarg);
4779 break;
4780 #endif
4781 case QEMU_OPTION_bt:
4782 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4783 fprintf(stderr, "qemu: too many bluetooth options\n");
4784 exit(1);
4786 bt_opts[nb_bt_opts++] = optarg;
4787 break;
4788 #ifdef HAS_AUDIO
4789 case QEMU_OPTION_audio_help:
4790 AUD_help ();
4791 exit (0);
4792 break;
4793 case QEMU_OPTION_soundhw:
4794 select_soundhw (optarg);
4795 break;
4796 #endif
4797 case QEMU_OPTION_h:
4798 help(0);
4799 break;
4800 case QEMU_OPTION_m: {
4801 uint64_t value;
4802 char *ptr;
4804 value = strtoul(optarg, &ptr, 10);
4805 switch (*ptr) {
4806 case 0: case 'M': case 'm':
4807 value <<= 20;
4808 break;
4809 case 'G': case 'g':
4810 value <<= 30;
4811 break;
4812 default:
4813 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4814 exit(1);
4817 /* On 32-bit hosts, QEMU is limited by virtual address space */
4818 if (value > (2047 << 20)
4819 #ifndef USE_KQEMU
4820 && HOST_LONG_BITS == 32
4821 #endif
4823 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4824 exit(1);
4826 if (value != (uint64_t)(ram_addr_t)value) {
4827 fprintf(stderr, "qemu: ram size too large\n");
4828 exit(1);
4830 ram_size = value;
4831 break;
4833 case QEMU_OPTION_d:
4835 int mask;
4836 const CPULogItem *item;
4838 mask = cpu_str_to_log_mask(optarg);
4839 if (!mask) {
4840 printf("Log items (comma separated):\n");
4841 for(item = cpu_log_items; item->mask != 0; item++) {
4842 printf("%-10s %s\n", item->name, item->help);
4844 exit(1);
4846 cpu_set_log(mask);
4848 break;
4849 #ifdef CONFIG_GDBSTUB
4850 case QEMU_OPTION_s:
4851 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
4852 break;
4853 case QEMU_OPTION_gdb:
4854 gdbstub_dev = optarg;
4855 break;
4856 #endif
4857 case QEMU_OPTION_L:
4858 bios_dir = optarg;
4859 break;
4860 case QEMU_OPTION_bios:
4861 bios_name = optarg;
4862 break;
4863 case QEMU_OPTION_singlestep:
4864 singlestep = 1;
4865 break;
4866 case QEMU_OPTION_S:
4867 autostart = 0;
4868 break;
4869 #ifndef _WIN32
4870 case QEMU_OPTION_k:
4871 keyboard_layout = optarg;
4872 break;
4873 #endif
4874 case QEMU_OPTION_localtime:
4875 rtc_utc = 0;
4876 break;
4877 case QEMU_OPTION_vga:
4878 select_vgahw (optarg);
4879 break;
4880 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4881 case QEMU_OPTION_g:
4883 const char *p;
4884 int w, h, depth;
4885 p = optarg;
4886 w = strtol(p, (char **)&p, 10);
4887 if (w <= 0) {
4888 graphic_error:
4889 fprintf(stderr, "qemu: invalid resolution or depth\n");
4890 exit(1);
4892 if (*p != 'x')
4893 goto graphic_error;
4894 p++;
4895 h = strtol(p, (char **)&p, 10);
4896 if (h <= 0)
4897 goto graphic_error;
4898 if (*p == 'x') {
4899 p++;
4900 depth = strtol(p, (char **)&p, 10);
4901 if (depth != 8 && depth != 15 && depth != 16 &&
4902 depth != 24 && depth != 32)
4903 goto graphic_error;
4904 } else if (*p == '\0') {
4905 depth = graphic_depth;
4906 } else {
4907 goto graphic_error;
4910 graphic_width = w;
4911 graphic_height = h;
4912 graphic_depth = depth;
4914 break;
4915 #endif
4916 case QEMU_OPTION_echr:
4918 char *r;
4919 term_escape_char = strtol(optarg, &r, 0);
4920 if (r == optarg)
4921 printf("Bad argument to echr\n");
4922 break;
4924 case QEMU_OPTION_monitor:
4925 monitor_device = optarg;
4926 break;
4927 case QEMU_OPTION_serial:
4928 if (serial_device_index >= MAX_SERIAL_PORTS) {
4929 fprintf(stderr, "qemu: too many serial ports\n");
4930 exit(1);
4932 serial_devices[serial_device_index] = optarg;
4933 serial_device_index++;
4934 break;
4935 case QEMU_OPTION_virtiocon:
4936 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
4937 fprintf(stderr, "qemu: too many virtio consoles\n");
4938 exit(1);
4940 virtio_consoles[virtio_console_index] = optarg;
4941 virtio_console_index++;
4942 break;
4943 case QEMU_OPTION_parallel:
4944 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4945 fprintf(stderr, "qemu: too many parallel ports\n");
4946 exit(1);
4948 parallel_devices[parallel_device_index] = optarg;
4949 parallel_device_index++;
4950 break;
4951 case QEMU_OPTION_loadvm:
4952 loadvm = optarg;
4953 break;
4954 case QEMU_OPTION_full_screen:
4955 full_screen = 1;
4956 break;
4957 #ifdef CONFIG_SDL
4958 case QEMU_OPTION_no_frame:
4959 no_frame = 1;
4960 break;
4961 case QEMU_OPTION_alt_grab:
4962 alt_grab = 1;
4963 break;
4964 case QEMU_OPTION_no_quit:
4965 no_quit = 1;
4966 break;
4967 case QEMU_OPTION_sdl:
4968 sdl = 1;
4969 break;
4970 #endif
4971 case QEMU_OPTION_pidfile:
4972 pid_file = optarg;
4973 break;
4974 #ifdef TARGET_I386
4975 case QEMU_OPTION_win2k_hack:
4976 win2k_install_hack = 1;
4977 break;
4978 case QEMU_OPTION_rtc_td_hack:
4979 rtc_td_hack = 1;
4980 break;
4981 case QEMU_OPTION_acpitable:
4982 if(acpi_table_add(optarg) < 0) {
4983 fprintf(stderr, "Wrong acpi table provided\n");
4984 exit(1);
4986 break;
4987 #endif
4988 #ifdef USE_KQEMU
4989 case QEMU_OPTION_no_kqemu:
4990 kqemu_allowed = 0;
4991 break;
4992 case QEMU_OPTION_kernel_kqemu:
4993 kqemu_allowed = 2;
4994 break;
4995 #endif
4996 #ifdef CONFIG_KVM
4997 case QEMU_OPTION_enable_kvm:
4998 kvm_allowed = 1;
4999 #ifdef USE_KQEMU
5000 kqemu_allowed = 0;
5001 #endif
5002 break;
5003 #endif
5004 #ifdef USE_KVM
5005 case QEMU_OPTION_no_kvm:
5006 kvm_allowed = 0;
5007 break;
5008 case QEMU_OPTION_no_kvm_irqchip: {
5009 kvm_irqchip = 0;
5010 kvm_pit = 0;
5011 break;
5013 case QEMU_OPTION_no_kvm_pit: {
5014 kvm_pit = 0;
5015 break;
5017 case QEMU_OPTION_no_kvm_pit_reinjection: {
5018 kvm_pit_reinject = 0;
5019 break;
5021 case QEMU_OPTION_enable_nesting: {
5022 kvm_nested = 1;
5023 break;
5025 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5026 case QEMU_OPTION_pcidevice:
5027 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5028 fprintf(stderr, "Too many assigned devices\n");
5029 exit(1);
5031 assigned_devices[assigned_devices_index] = optarg;
5032 assigned_devices_index++;
5033 break;
5034 #endif
5035 #endif
5036 case QEMU_OPTION_usb:
5037 usb_enabled = 1;
5038 break;
5039 case QEMU_OPTION_usbdevice:
5040 usb_enabled = 1;
5041 if (usb_devices_index >= MAX_USB_CMDLINE) {
5042 fprintf(stderr, "Too many USB devices\n");
5043 exit(1);
5045 usb_devices[usb_devices_index] = optarg;
5046 usb_devices_index++;
5047 break;
5048 case QEMU_OPTION_smp:
5049 smp_cpus = atoi(optarg);
5050 if (smp_cpus < 1) {
5051 fprintf(stderr, "Invalid number of CPUs\n");
5052 exit(1);
5054 break;
5055 case QEMU_OPTION_vnc:
5056 vnc_display = optarg;
5057 break;
5058 #ifdef TARGET_I386
5059 case QEMU_OPTION_no_acpi:
5060 acpi_enabled = 0;
5061 break;
5062 case QEMU_OPTION_no_hpet:
5063 no_hpet = 1;
5064 break;
5065 #endif
5066 case QEMU_OPTION_no_reboot:
5067 no_reboot = 1;
5068 break;
5069 case QEMU_OPTION_no_shutdown:
5070 no_shutdown = 1;
5071 break;
5072 case QEMU_OPTION_show_cursor:
5073 cursor_hide = 0;
5074 break;
5075 case QEMU_OPTION_uuid:
5076 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5077 fprintf(stderr, "Fail to parse UUID string."
5078 " Wrong format.\n");
5079 exit(1);
5081 break;
5082 #ifndef _WIN32
5083 case QEMU_OPTION_daemonize:
5084 daemonize = 1;
5085 break;
5086 #endif
5087 case QEMU_OPTION_option_rom:
5088 if (nb_option_roms >= MAX_OPTION_ROMS) {
5089 fprintf(stderr, "Too many option ROMs\n");
5090 exit(1);
5092 option_rom[nb_option_roms] = optarg;
5093 nb_option_roms++;
5094 break;
5095 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5096 case QEMU_OPTION_semihosting:
5097 semihosting_enabled = 1;
5098 break;
5099 #endif
5100 case QEMU_OPTION_tdf:
5101 time_drift_fix = 1;
5102 break;
5103 case QEMU_OPTION_kvm_shadow_memory:
5104 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5105 break;
5106 case QEMU_OPTION_mempath:
5107 mem_path = optarg;
5108 break;
5109 #ifdef MAP_POPULATE
5110 case QEMU_OPTION_mem_prealloc:
5111 mem_prealloc = !mem_prealloc;
5112 break;
5113 #endif
5114 case QEMU_OPTION_name:
5115 qemu_name = optarg;
5116 break;
5117 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5118 case QEMU_OPTION_prom_env:
5119 if (nb_prom_envs >= MAX_PROM_ENVS) {
5120 fprintf(stderr, "Too many prom variables\n");
5121 exit(1);
5123 prom_envs[nb_prom_envs] = optarg;
5124 nb_prom_envs++;
5125 break;
5126 #endif
5127 case QEMU_OPTION_cpu_vendor:
5128 cpu_vendor_string = optarg;
5129 break;
5130 #ifdef TARGET_ARM
5131 case QEMU_OPTION_old_param:
5132 old_param = 1;
5133 break;
5134 #endif
5135 case QEMU_OPTION_clock:
5136 configure_alarms(optarg);
5137 break;
5138 case QEMU_OPTION_startdate:
5140 struct tm tm;
5141 time_t rtc_start_date;
5142 if (!strcmp(optarg, "now")) {
5143 rtc_date_offset = -1;
5144 } else {
5145 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5146 &tm.tm_year,
5147 &tm.tm_mon,
5148 &tm.tm_mday,
5149 &tm.tm_hour,
5150 &tm.tm_min,
5151 &tm.tm_sec) == 6) {
5152 /* OK */
5153 } else if (sscanf(optarg, "%d-%d-%d",
5154 &tm.tm_year,
5155 &tm.tm_mon,
5156 &tm.tm_mday) == 3) {
5157 tm.tm_hour = 0;
5158 tm.tm_min = 0;
5159 tm.tm_sec = 0;
5160 } else {
5161 goto date_fail;
5163 tm.tm_year -= 1900;
5164 tm.tm_mon--;
5165 rtc_start_date = mktimegm(&tm);
5166 if (rtc_start_date == -1) {
5167 date_fail:
5168 fprintf(stderr, "Invalid date format. Valid format are:\n"
5169 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5170 exit(1);
5172 rtc_date_offset = time(NULL) - rtc_start_date;
5175 break;
5176 case QEMU_OPTION_tb_size:
5177 tb_size = strtol(optarg, NULL, 0);
5178 if (tb_size < 0)
5179 tb_size = 0;
5180 break;
5181 case QEMU_OPTION_icount:
5182 use_icount = 1;
5183 if (strcmp(optarg, "auto") == 0) {
5184 icount_time_shift = -1;
5185 } else {
5186 icount_time_shift = strtol(optarg, NULL, 0);
5188 break;
5189 case QEMU_OPTION_incoming:
5190 incoming = optarg;
5191 saved_incoming = incoming;
5192 break;
5193 #ifndef _WIN32
5194 case QEMU_OPTION_chroot:
5195 chroot_dir = optarg;
5196 break;
5197 case QEMU_OPTION_runas:
5198 run_as = optarg;
5199 break;
5200 case QEMU_OPTION_nvram:
5201 nvram = optarg;
5202 break;
5203 #endif
5208 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5209 if (kvm_allowed && kqemu_allowed) {
5210 fprintf(stderr,
5211 "You can not enable both KVM and kqemu at the same time\n");
5212 exit(1);
5214 #endif
5216 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5217 if (smp_cpus > machine->max_cpus) {
5218 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5219 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5220 machine->max_cpus);
5221 exit(1);
5224 if (nographic) {
5225 if (serial_device_index == 0)
5226 serial_devices[0] = "stdio";
5227 if (parallel_device_index == 0)
5228 parallel_devices[0] = "null";
5229 if (strncmp(monitor_device, "vc", 2) == 0)
5230 monitor_device = "stdio";
5233 #ifndef _WIN32
5234 if (daemonize) {
5235 pid_t pid;
5237 if (pipe(fds) == -1)
5238 exit(1);
5240 pid = fork();
5241 if (pid > 0) {
5242 uint8_t status;
5243 ssize_t len;
5245 close(fds[1]);
5247 again:
5248 len = read(fds[0], &status, 1);
5249 if (len == -1 && (errno == EINTR))
5250 goto again;
5252 if (len != 1)
5253 exit(1);
5254 else if (status == 1) {
5255 fprintf(stderr, "Could not acquire pidfile\n");
5256 exit(1);
5257 } else
5258 exit(0);
5259 } else if (pid < 0)
5260 exit(1);
5262 setsid();
5264 pid = fork();
5265 if (pid > 0)
5266 exit(0);
5267 else if (pid < 0)
5268 exit(1);
5270 umask(027);
5272 signal(SIGTSTP, SIG_IGN);
5273 signal(SIGTTOU, SIG_IGN);
5274 signal(SIGTTIN, SIG_IGN);
5277 #ifdef USE_KVM
5278 if (kvm_enabled()) {
5279 if (kvm_qemu_init() < 0) {
5280 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5281 #ifdef NO_CPU_EMULATION
5282 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5283 exit(1);
5284 #endif
5285 kvm_allowed = 0;
5288 #endif
5290 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5291 if (daemonize) {
5292 uint8_t status = 1;
5293 write(fds[1], &status, 1);
5294 } else
5295 fprintf(stderr, "Could not acquire pid file\n");
5296 exit(1);
5298 #endif
5300 #ifdef USE_KQEMU
5301 if (smp_cpus > 1)
5302 kqemu_allowed = 0;
5303 #endif
5304 linux_boot = (kernel_filename != NULL);
5305 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5307 if (!linux_boot && *kernel_cmdline != '\0') {
5308 fprintf(stderr, "-append only allowed with -kernel option\n");
5309 exit(1);
5312 if (!linux_boot && initrd_filename != NULL) {
5313 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5314 exit(1);
5317 /* boot to floppy or the default cd if no hard disk defined yet */
5318 if (!boot_devices[0]) {
5319 boot_devices = "cad";
5321 setvbuf(stdout, NULL, _IOLBF, 0);
5323 init_timers();
5324 if (init_timer_alarm() < 0) {
5325 fprintf(stderr, "could not initialize alarm timer\n");
5326 exit(1);
5328 if (use_icount && icount_time_shift < 0) {
5329 use_icount = 2;
5330 /* 125MIPS seems a reasonable initial guess at the guest speed.
5331 It will be corrected fairly quickly anyway. */
5332 icount_time_shift = 3;
5333 init_icount_adjust();
5336 #ifdef _WIN32
5337 socket_init();
5338 #endif
5340 /* init network clients */
5341 if (nb_net_clients == 0) {
5342 /* if no clients, we use a default config */
5343 net_clients[nb_net_clients++] = "nic";
5344 #ifdef CONFIG_SLIRP
5345 net_clients[nb_net_clients++] = "user";
5346 #endif
5349 for(i = 0;i < nb_net_clients; i++) {
5350 if (net_client_parse(net_clients[i]) < 0)
5351 exit(1);
5353 net_client_check();
5355 #ifdef TARGET_I386
5356 /* XXX: this should be moved in the PC machine instantiation code */
5357 if (net_boot != 0) {
5358 int netroms = 0;
5359 for (i = 0; i < nb_nics && i < 4; i++) {
5360 const char *model = nd_table[i].model;
5361 char buf[1024];
5362 if (net_boot & (1 << i)) {
5363 if (model == NULL)
5364 model = "rtl8139";
5365 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5366 if (get_image_size(buf) > 0) {
5367 if (nb_option_roms >= MAX_OPTION_ROMS) {
5368 fprintf(stderr, "Too many option ROMs\n");
5369 exit(1);
5371 option_rom[nb_option_roms] = strdup(buf);
5372 nb_option_roms++;
5373 netroms++;
5377 if (netroms == 0) {
5378 fprintf(stderr, "No valid PXE rom found for network device\n");
5379 exit(1);
5382 #endif
5384 /* init the bluetooth world */
5385 for (i = 0; i < nb_bt_opts; i++)
5386 if (bt_parse(bt_opts[i]))
5387 exit(1);
5389 /* init the memory */
5390 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5392 if (machine->ram_require & RAMSIZE_FIXED) {
5393 if (ram_size > 0) {
5394 if (ram_size < phys_ram_size) {
5395 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5396 machine->name, (unsigned long long) phys_ram_size);
5397 exit(-1);
5400 phys_ram_size = ram_size;
5401 } else
5402 ram_size = phys_ram_size;
5403 } else {
5404 if (ram_size == 0)
5405 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5407 phys_ram_size += ram_size;
5410 /* Initialize kvm */
5411 #if defined(TARGET_I386) || defined(TARGET_X86_64)
5412 #define KVM_EXTRA_PAGES 3
5413 #else
5414 #define KVM_EXTRA_PAGES 0
5415 #endif
5416 if (kvm_enabled()) {
5417 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
5418 if (kvm_qemu_create_context() < 0) {
5419 fprintf(stderr, "Could not create KVM context\n");
5420 exit(1);
5424 phys_ram_base = qemu_alloc_physram(phys_ram_size);
5425 if (!phys_ram_base) {
5426 fprintf(stderr, "Could not allocate physical memory\n");
5427 exit(1);
5430 /* init the dynamic translator */
5431 cpu_exec_init_all(tb_size * 1024 * 1024);
5433 bdrv_init();
5434 dma_helper_init();
5436 /* we always create the cdrom drive, even if no disk is there */
5438 if (nb_drives_opt < MAX_DRIVES)
5439 drive_add(NULL, CDROM_ALIAS);
5441 /* we always create at least one floppy */
5443 if (nb_drives_opt < MAX_DRIVES)
5444 drive_add(NULL, FD_ALIAS, 0);
5446 /* we always create one sd slot, even if no card is in it */
5448 if (nb_drives_opt < MAX_DRIVES)
5449 drive_add(NULL, SD_ALIAS);
5451 /* open the virtual block devices
5452 * note that migration with device
5453 * hot add/remove is broken.
5455 for(i = 0; i < nb_drives_opt; i++)
5456 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5457 exit(1);
5459 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5460 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5462 #ifndef _WIN32
5463 /* must be after terminal init, SDL library changes signal handlers */
5464 termsig_setup();
5465 #endif
5467 /* Maintain compatibility with multiple stdio monitors */
5468 if (!strcmp(monitor_device,"stdio")) {
5469 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5470 const char *devname = serial_devices[i];
5471 if (devname && !strcmp(devname,"mon:stdio")) {
5472 monitor_device = NULL;
5473 break;
5474 } else if (devname && !strcmp(devname,"stdio")) {
5475 monitor_device = NULL;
5476 serial_devices[i] = "mon:stdio";
5477 break;
5482 #ifdef KVM_UPSTREAM
5483 if (kvm_enabled()) {
5484 int ret;
5486 ret = kvm_init(smp_cpus);
5487 if (ret < 0) {
5488 fprintf(stderr, "failed to initialize KVM\n");
5489 exit(1);
5492 #endif
5494 if (monitor_device) {
5495 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5496 if (!monitor_hd) {
5497 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5498 exit(1);
5502 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5503 const char *devname = serial_devices[i];
5504 if (devname && strcmp(devname, "none")) {
5505 char label[32];
5506 snprintf(label, sizeof(label), "serial%d", i);
5507 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5508 if (!serial_hds[i]) {
5509 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5510 devname);
5511 exit(1);
5516 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5517 const char *devname = parallel_devices[i];
5518 if (devname && strcmp(devname, "none")) {
5519 char label[32];
5520 snprintf(label, sizeof(label), "parallel%d", i);
5521 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5522 if (!parallel_hds[i]) {
5523 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5524 devname);
5525 exit(1);
5530 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5531 const char *devname = virtio_consoles[i];
5532 if (devname && strcmp(devname, "none")) {
5533 char label[32];
5534 snprintf(label, sizeof(label), "virtcon%d", i);
5535 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5536 if (!virtcon_hds[i]) {
5537 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5538 devname);
5539 exit(1);
5544 if (kvm_enabled())
5545 kvm_init_ap();
5547 machine->init(ram_size, vga_ram_size, boot_devices,
5548 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5550 current_machine = machine;
5552 /* Set KVM's vcpu state to qemu's initial CPUState. */
5553 if (kvm_enabled()) {
5554 int ret;
5556 ret = kvm_sync_vcpus();
5557 if (ret < 0) {
5558 fprintf(stderr, "failed to initialize vcpus\n");
5559 exit(1);
5563 /* init USB devices */
5564 if (usb_enabled) {
5565 for(i = 0; i < usb_devices_index; i++) {
5566 if (usb_device_add(usb_devices[i], 0) < 0) {
5567 fprintf(stderr, "Warning: could not add USB device %s\n",
5568 usb_devices[i]);
5573 if (!display_state)
5574 dumb_display_init();
5575 /* just use the first displaystate for the moment */
5576 ds = display_state;
5577 /* terminal init */
5578 if (nographic) {
5579 if (curses) {
5580 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5581 exit(1);
5583 } else {
5584 #if defined(CONFIG_CURSES)
5585 if (curses) {
5586 /* At the moment curses cannot be used with other displays */
5587 curses_display_init(ds, full_screen);
5588 } else
5589 #endif
5591 if (vnc_display != NULL) {
5592 vnc_display_init(ds);
5593 if (vnc_display_open(ds, vnc_display) < 0)
5594 exit(1);
5596 #if defined(CONFIG_SDL)
5597 if (sdl || !vnc_display)
5598 sdl_display_init(ds, full_screen, no_frame);
5599 #elif defined(CONFIG_COCOA)
5600 if (sdl || !vnc_display)
5601 cocoa_display_init(ds, full_screen);
5602 #endif
5605 dpy_resize(ds);
5607 dcl = ds->listeners;
5608 while (dcl != NULL) {
5609 if (dcl->dpy_refresh != NULL) {
5610 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5611 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5613 dcl = dcl->next;
5616 if (nographic || (vnc_display && !sdl)) {
5617 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5618 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5621 text_consoles_set_display(display_state);
5622 qemu_chr_initial_reset();
5624 if (monitor_device && monitor_hd)
5625 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
5627 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5628 const char *devname = serial_devices[i];
5629 if (devname && strcmp(devname, "none")) {
5630 char label[32];
5631 snprintf(label, sizeof(label), "serial%d", i);
5632 if (strstart(devname, "vc", 0))
5633 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5637 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5638 const char *devname = parallel_devices[i];
5639 if (devname && strcmp(devname, "none")) {
5640 char label[32];
5641 snprintf(label, sizeof(label), "parallel%d", i);
5642 if (strstart(devname, "vc", 0))
5643 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5647 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5648 const char *devname = virtio_consoles[i];
5649 if (virtcon_hds[i] && devname) {
5650 char label[32];
5651 snprintf(label, sizeof(label), "virtcon%d", i);
5652 if (strstart(devname, "vc", 0))
5653 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5657 #ifdef CONFIG_GDBSTUB
5658 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5659 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5660 gdbstub_dev);
5661 exit(1);
5663 #endif
5665 if (loadvm)
5666 do_loadvm(cur_mon, loadvm);
5668 if (incoming) {
5669 autostart = 0; /* fixme how to deal with -daemonize */
5670 qemu_start_incoming_migration(incoming);
5673 if (autostart)
5674 vm_start();
5676 #ifndef _WIN32
5677 if (daemonize) {
5678 uint8_t status = 0;
5679 ssize_t len;
5681 again1:
5682 len = write(fds[1], &status, 1);
5683 if (len == -1 && (errno == EINTR))
5684 goto again1;
5686 if (len != 1)
5687 exit(1);
5689 chdir("/");
5690 TFR(fd = open("/dev/null", O_RDWR));
5691 if (fd == -1)
5692 exit(1);
5695 if (run_as) {
5696 pwd = getpwnam(run_as);
5697 if (!pwd) {
5698 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5699 exit(1);
5703 if (chroot_dir) {
5704 if (chroot(chroot_dir) < 0) {
5705 fprintf(stderr, "chroot failed\n");
5706 exit(1);
5708 chdir("/");
5711 if (run_as) {
5712 if (setgid(pwd->pw_gid) < 0) {
5713 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5714 exit(1);
5716 if (setuid(pwd->pw_uid) < 0) {
5717 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5718 exit(1);
5720 if (setuid(0) != -1) {
5721 fprintf(stderr, "Dropping privileges failed\n");
5722 exit(1);
5726 if (daemonize) {
5727 dup2(fd, 0);
5728 dup2(fd, 1);
5729 dup2(fd, 2);
5731 close(fd);
5733 #endif
5735 main_loop();
5736 quit_timers();
5737 net_cleanup();
5739 return 0;