Propagate errors on failed migration.
[qemu-kvm/fedora.git] / vl.c
blob2e4ceb840ed6a5d292e5d87286171310a4c24fff
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 int r;
3231 r = kvm_update_dirty_pages_log();
3232 if (r) {
3233 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3234 qemu_file_set_error(f);
3235 return 0;
3238 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3239 uint8_t ch;
3241 cpu_physical_memory_reset_dirty(current_addr,
3242 current_addr + TARGET_PAGE_SIZE,
3243 MIGRATION_DIRTY_FLAG);
3245 ch = *(phys_ram_base + current_addr);
3247 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3248 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3249 qemu_put_byte(f, ch);
3250 } else {
3251 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3252 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3255 found = 1;
3256 break;
3258 addr += TARGET_PAGE_SIZE;
3259 current_addr = (saved_addr + addr) % phys_ram_size;
3262 return found;
3265 static ram_addr_t ram_save_threshold = 10;
3267 static ram_addr_t ram_save_remaining(void)
3269 ram_addr_t addr;
3270 ram_addr_t count = 0;
3272 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3273 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3274 count++;
3277 return count;
3280 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3282 ram_addr_t addr;
3284 if (stage == 1) {
3285 /* Make sure all dirty bits are set */
3286 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3287 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3288 cpu_physical_memory_set_dirty(addr);
3291 /* Enable dirty memory tracking */
3292 cpu_physical_memory_set_dirty_tracking(1);
3294 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3297 while (!qemu_file_rate_limit(f)) {
3298 int ret;
3300 ret = ram_save_block(f);
3301 if (ret == 0) /* no more blocks */
3302 break;
3305 /* try transferring iterative blocks of memory */
3307 if (stage == 3) {
3309 /* flush all remaining blocks regardless of rate limiting */
3310 while (ram_save_block(f) != 0);
3311 cpu_physical_memory_set_dirty_tracking(0);
3314 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3316 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3319 static int ram_load_dead(QEMUFile *f, void *opaque)
3321 RamDecompressState s1, *s = &s1;
3322 uint8_t buf[10];
3323 ram_addr_t i;
3325 if (ram_decompress_open(s, f) < 0)
3326 return -EINVAL;
3327 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3328 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3329 continue;
3330 if (ram_decompress_buf(s, buf, 1) < 0) {
3331 fprintf(stderr, "Error while reading ram block header\n");
3332 goto error;
3334 if (buf[0] == 0) {
3335 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3336 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3337 goto error;
3339 } else {
3340 error:
3341 printf("Error block header\n");
3342 return -EINVAL;
3345 ram_decompress_close(s);
3347 return 0;
3350 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3352 ram_addr_t addr;
3353 int flags;
3355 if (version_id == 1)
3356 return ram_load_v1(f, opaque);
3358 if (version_id == 2) {
3359 if (qemu_get_be32(f) != phys_ram_size)
3360 return -EINVAL;
3361 return ram_load_dead(f, opaque);
3364 if (version_id != 3)
3365 return -EINVAL;
3367 do {
3368 addr = qemu_get_be64(f);
3370 flags = addr & ~TARGET_PAGE_MASK;
3371 addr &= TARGET_PAGE_MASK;
3373 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3374 if (addr != phys_ram_size)
3375 return -EINVAL;
3378 if (flags & RAM_SAVE_FLAG_FULL) {
3379 if (ram_load_dead(f, opaque) < 0)
3380 return -EINVAL;
3383 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3384 uint8_t ch = qemu_get_byte(f);
3385 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3386 } else if (flags & RAM_SAVE_FLAG_PAGE)
3387 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3388 } while (!(flags & RAM_SAVE_FLAG_EOS));
3390 return 0;
3393 void qemu_service_io(void)
3395 CPUState *env = cpu_single_env;
3396 if (env) {
3397 cpu_exit(env);
3398 #ifdef USE_KQEMU
3399 if (env->kqemu_enabled) {
3400 kqemu_cpu_interrupt(env);
3402 #endif
3406 /***********************************************************/
3407 /* bottom halves (can be seen as timers which expire ASAP) */
3409 struct QEMUBH {
3410 QEMUBHFunc *cb;
3411 void *opaque;
3412 int scheduled;
3413 int idle;
3414 int deleted;
3415 QEMUBH *next;
3418 static QEMUBH *first_bh = NULL;
3420 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3422 QEMUBH *bh;
3423 bh = qemu_mallocz(sizeof(QEMUBH));
3424 bh->cb = cb;
3425 bh->opaque = opaque;
3426 bh->next = first_bh;
3427 first_bh = bh;
3428 return bh;
3431 int qemu_bh_poll(void)
3433 QEMUBH *bh, **bhp;
3434 int ret;
3436 ret = 0;
3437 for (bh = first_bh; bh; bh = bh->next) {
3438 if (!bh->deleted && bh->scheduled) {
3439 bh->scheduled = 0;
3440 if (!bh->idle)
3441 ret = 1;
3442 bh->idle = 0;
3443 bh->cb(bh->opaque);
3447 /* remove deleted bhs */
3448 bhp = &first_bh;
3449 while (*bhp) {
3450 bh = *bhp;
3451 if (bh->deleted) {
3452 *bhp = bh->next;
3453 qemu_free(bh);
3454 } else
3455 bhp = &bh->next;
3458 return ret;
3461 void qemu_bh_schedule_idle(QEMUBH *bh)
3463 if (bh->scheduled)
3464 return;
3465 bh->scheduled = 1;
3466 bh->idle = 1;
3469 void qemu_bh_schedule(QEMUBH *bh)
3471 CPUState *env = cpu_single_env;
3472 if (bh->scheduled)
3473 return;
3474 bh->scheduled = 1;
3475 bh->idle = 0;
3476 /* stop the currently executing CPU to execute the BH ASAP */
3477 if (env) {
3478 cpu_exit(env);
3480 main_loop_break();
3483 void qemu_bh_cancel(QEMUBH *bh)
3485 bh->scheduled = 0;
3488 void qemu_bh_delete(QEMUBH *bh)
3490 bh->scheduled = 0;
3491 bh->deleted = 1;
3494 static void qemu_bh_update_timeout(int *timeout)
3496 QEMUBH *bh;
3498 for (bh = first_bh; bh; bh = bh->next) {
3499 if (!bh->deleted && bh->scheduled) {
3500 if (bh->idle) {
3501 /* idle bottom halves will be polled at least
3502 * every 10ms */
3503 *timeout = MIN(10, *timeout);
3504 } else {
3505 /* non-idle bottom halves will be executed
3506 * immediately */
3507 *timeout = 0;
3508 break;
3514 /***********************************************************/
3515 /* machine registration */
3517 static QEMUMachine *first_machine = NULL;
3518 QEMUMachine *current_machine = NULL;
3520 int qemu_register_machine(QEMUMachine *m)
3522 QEMUMachine **pm;
3523 pm = &first_machine;
3524 while (*pm != NULL)
3525 pm = &(*pm)->next;
3526 m->next = NULL;
3527 *pm = m;
3528 return 0;
3531 static QEMUMachine *find_machine(const char *name)
3533 QEMUMachine *m;
3535 for(m = first_machine; m != NULL; m = m->next) {
3536 if (!strcmp(m->name, name))
3537 return m;
3539 return NULL;
3542 /***********************************************************/
3543 /* main execution loop */
3545 static void gui_update(void *opaque)
3547 uint64_t interval = GUI_REFRESH_INTERVAL;
3548 DisplayState *ds = opaque;
3549 DisplayChangeListener *dcl = ds->listeners;
3551 dpy_refresh(ds);
3553 while (dcl != NULL) {
3554 if (dcl->gui_timer_interval &&
3555 dcl->gui_timer_interval < interval)
3556 interval = dcl->gui_timer_interval;
3557 dcl = dcl->next;
3559 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3562 static void nographic_update(void *opaque)
3564 uint64_t interval = GUI_REFRESH_INTERVAL;
3566 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3569 struct vm_change_state_entry {
3570 VMChangeStateHandler *cb;
3571 void *opaque;
3572 LIST_ENTRY (vm_change_state_entry) entries;
3575 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3577 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3578 void *opaque)
3580 VMChangeStateEntry *e;
3582 e = qemu_mallocz(sizeof (*e));
3584 e->cb = cb;
3585 e->opaque = opaque;
3586 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3587 return e;
3590 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3592 LIST_REMOVE (e, entries);
3593 qemu_free (e);
3596 static void vm_state_notify(int running, int reason)
3598 VMChangeStateEntry *e;
3600 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3601 e->cb(e->opaque, running, reason);
3605 void vm_start(void)
3607 if (!vm_running) {
3608 cpu_enable_ticks();
3609 vm_running = 1;
3610 vm_state_notify(1, 0);
3611 if (kvm_enabled())
3612 qemu_kvm_resume_all_threads();
3613 qemu_rearm_alarm_timer(alarm_timer);
3617 void vm_stop(int reason)
3619 if (vm_running) {
3620 cpu_disable_ticks();
3621 vm_running = 0;
3622 if (kvm_enabled())
3623 qemu_kvm_pause_all_threads();
3624 vm_state_notify(0, reason);
3628 /* reset/shutdown handler */
3630 typedef struct QEMUResetEntry {
3631 QEMUResetHandler *func;
3632 void *opaque;
3633 struct QEMUResetEntry *next;
3634 } QEMUResetEntry;
3636 static QEMUResetEntry *first_reset_entry;
3637 static int reset_requested;
3638 static int shutdown_requested;
3639 static int powerdown_requested;
3641 int qemu_shutdown_requested(void)
3643 int r = shutdown_requested;
3644 shutdown_requested = 0;
3645 return r;
3648 int qemu_reset_requested(void)
3650 int r = reset_requested;
3651 reset_requested = 0;
3652 return r;
3655 int qemu_powerdown_requested(void)
3657 int r = powerdown_requested;
3658 powerdown_requested = 0;
3659 return r;
3662 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3664 QEMUResetEntry **pre, *re;
3666 pre = &first_reset_entry;
3667 while (*pre != NULL)
3668 pre = &(*pre)->next;
3669 re = qemu_mallocz(sizeof(QEMUResetEntry));
3670 re->func = func;
3671 re->opaque = opaque;
3672 re->next = NULL;
3673 *pre = re;
3676 void qemu_system_reset(void)
3678 QEMUResetEntry *re;
3680 /* reset all devices */
3681 for(re = first_reset_entry; re != NULL; re = re->next) {
3682 re->func(re->opaque);
3686 void qemu_system_reset_request(void)
3688 if (no_reboot) {
3689 shutdown_requested = 1;
3690 } else {
3691 reset_requested = 1;
3693 if (cpu_single_env) {
3694 qemu_kvm_cpu_stop(cpu_single_env);
3695 cpu_exit(cpu_single_env);
3699 void qemu_system_shutdown_request(void)
3701 shutdown_requested = 1;
3702 if (cpu_single_env)
3703 cpu_exit(cpu_single_env);
3706 void qemu_system_powerdown_request(void)
3708 powerdown_requested = 1;
3709 if (cpu_single_env)
3710 cpu_exit(cpu_single_env);
3713 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
3714 struct timeval *tv)
3716 int ret;
3718 /* KVM holds a mutex while QEMU code is running, we need hooks to
3719 release the mutex whenever QEMU code sleeps. */
3721 kvm_sleep_begin();
3723 ret = select(max_fd, rfds, wfds, xfds, tv);
3725 kvm_sleep_end();
3727 return ret;
3730 #ifdef _WIN32
3731 static void host_main_loop_wait(int *timeout)
3733 int ret, ret2, i;
3734 PollingEntry *pe;
3737 /* XXX: need to suppress polling by better using win32 events */
3738 ret = 0;
3739 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3740 ret |= pe->func(pe->opaque);
3742 if (ret == 0) {
3743 int err;
3744 WaitObjects *w = &wait_objects;
3746 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3747 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3748 if (w->func[ret - WAIT_OBJECT_0])
3749 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3751 /* Check for additional signaled events */
3752 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3754 /* Check if event is signaled */
3755 ret2 = WaitForSingleObject(w->events[i], 0);
3756 if(ret2 == WAIT_OBJECT_0) {
3757 if (w->func[i])
3758 w->func[i](w->opaque[i]);
3759 } else if (ret2 == WAIT_TIMEOUT) {
3760 } else {
3761 err = GetLastError();
3762 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3765 } else if (ret == WAIT_TIMEOUT) {
3766 } else {
3767 err = GetLastError();
3768 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3772 *timeout = 0;
3774 #else
3775 static void host_main_loop_wait(int *timeout)
3778 #endif
3780 void main_loop_wait(int timeout)
3782 IOHandlerRecord *ioh;
3783 fd_set rfds, wfds, xfds;
3784 int ret, nfds;
3785 struct timeval tv;
3787 qemu_bh_update_timeout(&timeout);
3789 host_main_loop_wait(&timeout);
3791 /* poll any events */
3792 /* XXX: separate device handlers from system ones */
3793 nfds = -1;
3794 FD_ZERO(&rfds);
3795 FD_ZERO(&wfds);
3796 FD_ZERO(&xfds);
3797 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3798 if (ioh->deleted)
3799 continue;
3800 if (ioh->fd_read &&
3801 (!ioh->fd_read_poll ||
3802 ioh->fd_read_poll(ioh->opaque) != 0)) {
3803 FD_SET(ioh->fd, &rfds);
3804 if (ioh->fd > nfds)
3805 nfds = ioh->fd;
3807 if (ioh->fd_write) {
3808 FD_SET(ioh->fd, &wfds);
3809 if (ioh->fd > nfds)
3810 nfds = ioh->fd;
3814 tv.tv_sec = timeout / 1000;
3815 tv.tv_usec = (timeout % 1000) * 1000;
3817 #if defined(CONFIG_SLIRP)
3818 if (slirp_is_inited()) {
3819 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3821 #endif
3822 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3823 if (ret > 0) {
3824 IOHandlerRecord **pioh;
3826 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3827 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3828 ioh->fd_read(ioh->opaque);
3829 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3830 FD_CLR(ioh->fd, &rfds);
3832 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3833 ioh->fd_write(ioh->opaque);
3837 /* remove deleted IO handlers */
3838 pioh = &first_io_handler;
3839 while (*pioh) {
3840 ioh = *pioh;
3841 if (ioh->deleted) {
3842 *pioh = ioh->next;
3843 qemu_free(ioh);
3844 } else
3845 pioh = &ioh->next;
3848 #if defined(CONFIG_SLIRP)
3849 if (slirp_is_inited()) {
3850 if (ret < 0) {
3851 FD_ZERO(&rfds);
3852 FD_ZERO(&wfds);
3853 FD_ZERO(&xfds);
3855 slirp_select_poll(&rfds, &wfds, &xfds);
3857 #endif
3859 /* vm time timers */
3860 if (vm_running && (!cur_cpu
3861 || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER))))
3862 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3863 qemu_get_clock(vm_clock));
3865 /* real time timers */
3866 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3867 qemu_get_clock(rt_clock));
3869 /* Check bottom-halves last in case any of the earlier events triggered
3870 them. */
3871 qemu_bh_poll();
3875 static int main_loop(void)
3877 int ret, timeout;
3878 #ifdef CONFIG_PROFILER
3879 int64_t ti;
3880 #endif
3881 CPUState *env;
3884 if (kvm_enabled()) {
3885 kvm_main_loop();
3886 cpu_disable_ticks();
3887 return 0;
3890 cur_cpu = first_cpu;
3891 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3892 for(;;) {
3893 if (vm_running) {
3895 for(;;) {
3896 /* get next cpu */
3897 env = next_cpu;
3898 #ifdef CONFIG_PROFILER
3899 ti = profile_getclock();
3900 #endif
3901 if (use_icount) {
3902 int64_t count;
3903 int decr;
3904 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3905 env->icount_decr.u16.low = 0;
3906 env->icount_extra = 0;
3907 count = qemu_next_deadline();
3908 count = (count + (1 << icount_time_shift) - 1)
3909 >> icount_time_shift;
3910 qemu_icount += count;
3911 decr = (count > 0xffff) ? 0xffff : count;
3912 count -= decr;
3913 env->icount_decr.u16.low = decr;
3914 env->icount_extra = count;
3916 ret = cpu_exec(env);
3917 #ifdef CONFIG_PROFILER
3918 qemu_time += profile_getclock() - ti;
3919 #endif
3920 if (use_icount) {
3921 /* Fold pending instructions back into the
3922 instruction counter, and clear the interrupt flag. */
3923 qemu_icount -= (env->icount_decr.u16.low
3924 + env->icount_extra);
3925 env->icount_decr.u32 = 0;
3926 env->icount_extra = 0;
3928 next_cpu = env->next_cpu ?: first_cpu;
3929 if (event_pending && likely(ret != EXCP_DEBUG)) {
3930 ret = EXCP_INTERRUPT;
3931 event_pending = 0;
3932 break;
3934 if (ret == EXCP_HLT) {
3935 /* Give the next CPU a chance to run. */
3936 cur_cpu = env;
3937 continue;
3939 if (ret != EXCP_HALTED)
3940 break;
3941 /* all CPUs are halted ? */
3942 if (env == cur_cpu)
3943 break;
3945 cur_cpu = env;
3947 if (shutdown_requested) {
3948 ret = EXCP_INTERRUPT;
3949 if (no_shutdown) {
3950 vm_stop(0);
3951 no_shutdown = 0;
3953 else
3954 break;
3956 if (reset_requested) {
3957 reset_requested = 0;
3958 qemu_system_reset();
3959 ret = EXCP_INTERRUPT;
3961 if (powerdown_requested) {
3962 powerdown_requested = 0;
3963 qemu_system_powerdown();
3964 ret = EXCP_INTERRUPT;
3966 #ifdef CONFIG_GDBSTUB
3967 if (unlikely(ret == EXCP_DEBUG)) {
3968 gdb_set_stop_cpu(cur_cpu);
3969 vm_stop(EXCP_DEBUG);
3971 #endif
3972 /* If all cpus are halted then wait until the next IRQ */
3973 /* XXX: use timeout computed from timers */
3974 if (ret == EXCP_HALTED) {
3975 if (use_icount) {
3976 int64_t add;
3977 int64_t delta;
3978 /* Advance virtual time to the next event. */
3979 if (use_icount == 1) {
3980 /* When not using an adaptive execution frequency
3981 we tend to get badly out of sync with real time,
3982 so just delay for a reasonable amount of time. */
3983 delta = 0;
3984 } else {
3985 delta = cpu_get_icount() - cpu_get_clock();
3987 if (delta > 0) {
3988 /* If virtual time is ahead of real time then just
3989 wait for IO. */
3990 timeout = (delta / 1000000) + 1;
3991 } else {
3992 /* Wait for either IO to occur or the next
3993 timer event. */
3994 add = qemu_next_deadline();
3995 /* We advance the timer before checking for IO.
3996 Limit the amount we advance so that early IO
3997 activity won't get the guest too far ahead. */
3998 if (add > 10000000)
3999 add = 10000000;
4000 delta += add;
4001 add = (add + (1 << icount_time_shift) - 1)
4002 >> icount_time_shift;
4003 qemu_icount += add;
4004 timeout = delta / 1000000;
4005 if (timeout < 0)
4006 timeout = 0;
4008 } else {
4009 timeout = 5000;
4011 } else {
4012 timeout = 0;
4014 } else {
4015 if (shutdown_requested) {
4016 ret = EXCP_INTERRUPT;
4017 break;
4019 timeout = 5000;
4021 #ifdef CONFIG_PROFILER
4022 ti = profile_getclock();
4023 #endif
4024 main_loop_wait(timeout);
4025 #ifdef CONFIG_PROFILER
4026 dev_time += profile_getclock() - ti;
4027 #endif
4029 cpu_disable_ticks();
4030 return ret;
4033 static void help(int exitcode)
4035 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
4036 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
4037 "usage: %s [options] [disk_image]\n"
4038 "\n"
4039 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4040 "\n"
4041 #define DEF(option, opt_arg, opt_enum, opt_help) \
4042 opt_help
4043 #define DEFHEADING(text) stringify(text) "\n"
4044 #include "qemu-options.h"
4045 #undef DEF
4046 #undef DEFHEADING
4047 #undef GEN_DOCS
4048 "\n"
4049 "During emulation, the following keys are useful:\n"
4050 "ctrl-alt-f toggle full screen\n"
4051 "ctrl-alt-n switch to virtual console 'n'\n"
4052 "ctrl-alt toggle mouse and keyboard grab\n"
4053 "\n"
4054 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4056 "qemu",
4057 DEFAULT_RAM_SIZE,
4058 #ifndef _WIN32
4059 DEFAULT_NETWORK_SCRIPT,
4060 DEFAULT_NETWORK_DOWN_SCRIPT,
4061 #endif
4062 DEFAULT_GDBSTUB_PORT,
4063 "/tmp/qemu.log");
4064 exit(exitcode);
4067 #define HAS_ARG 0x0001
4069 enum {
4070 #define DEF(option, opt_arg, opt_enum, opt_help) \
4071 opt_enum,
4072 #define DEFHEADING(text)
4073 #include "qemu-options.h"
4074 #undef DEF
4075 #undef DEFHEADING
4076 #undef GEN_DOCS
4079 typedef struct QEMUOption {
4080 const char *name;
4081 int flags;
4082 int index;
4083 } QEMUOption;
4085 static const QEMUOption qemu_options[] = {
4086 { "h", 0, QEMU_OPTION_h },
4087 #define DEF(option, opt_arg, opt_enum, opt_help) \
4088 { option, opt_arg, opt_enum },
4089 #define DEFHEADING(text)
4090 #include "qemu-options.h"
4091 #undef DEF
4092 #undef DEFHEADING
4093 #undef GEN_DOCS
4094 { NULL },
4097 #ifdef HAS_AUDIO
4098 struct soundhw soundhw[] = {
4099 #ifdef HAS_AUDIO_CHOICE
4100 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4102 "pcspk",
4103 "PC speaker",
4106 { .init_isa = pcspk_audio_init }
4108 #endif
4110 #ifdef CONFIG_SB16
4112 "sb16",
4113 "Creative Sound Blaster 16",
4116 { .init_isa = SB16_init }
4118 #endif
4120 #ifdef CONFIG_CS4231A
4122 "cs4231a",
4123 "CS4231A",
4126 { .init_isa = cs4231a_init }
4128 #endif
4130 #ifdef CONFIG_ADLIB
4132 "adlib",
4133 #ifdef HAS_YMF262
4134 "Yamaha YMF262 (OPL3)",
4135 #else
4136 "Yamaha YM3812 (OPL2)",
4137 #endif
4140 { .init_isa = Adlib_init }
4142 #endif
4144 #ifdef CONFIG_GUS
4146 "gus",
4147 "Gravis Ultrasound GF1",
4150 { .init_isa = GUS_init }
4152 #endif
4154 #ifdef CONFIG_AC97
4156 "ac97",
4157 "Intel 82801AA AC97 Audio",
4160 { .init_pci = ac97_init }
4162 #endif
4164 #ifdef CONFIG_ES1370
4166 "es1370",
4167 "ENSONIQ AudioPCI ES1370",
4170 { .init_pci = es1370_init }
4172 #endif
4174 #endif /* HAS_AUDIO_CHOICE */
4176 { NULL, NULL, 0, 0, { NULL } }
4179 static void select_soundhw (const char *optarg)
4181 struct soundhw *c;
4183 if (*optarg == '?') {
4184 show_valid_cards:
4186 printf ("Valid sound card names (comma separated):\n");
4187 for (c = soundhw; c->name; ++c) {
4188 printf ("%-11s %s\n", c->name, c->descr);
4190 printf ("\n-soundhw all will enable all of the above\n");
4191 exit (*optarg != '?');
4193 else {
4194 size_t l;
4195 const char *p;
4196 char *e;
4197 int bad_card = 0;
4199 if (!strcmp (optarg, "all")) {
4200 for (c = soundhw; c->name; ++c) {
4201 c->enabled = 1;
4203 return;
4206 p = optarg;
4207 while (*p) {
4208 e = strchr (p, ',');
4209 l = !e ? strlen (p) : (size_t) (e - p);
4211 for (c = soundhw; c->name; ++c) {
4212 if (!strncmp (c->name, p, l)) {
4213 c->enabled = 1;
4214 break;
4218 if (!c->name) {
4219 if (l > 80) {
4220 fprintf (stderr,
4221 "Unknown sound card name (too big to show)\n");
4223 else {
4224 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4225 (int) l, p);
4227 bad_card = 1;
4229 p += l + (e != NULL);
4232 if (bad_card)
4233 goto show_valid_cards;
4236 #endif
4238 static void select_vgahw (const char *p)
4240 const char *opts;
4242 if (strstart(p, "std", &opts)) {
4243 std_vga_enabled = 1;
4244 cirrus_vga_enabled = 0;
4245 vmsvga_enabled = 0;
4246 } else if (strstart(p, "cirrus", &opts)) {
4247 cirrus_vga_enabled = 1;
4248 std_vga_enabled = 0;
4249 vmsvga_enabled = 0;
4250 } else if (strstart(p, "vmware", &opts)) {
4251 cirrus_vga_enabled = 0;
4252 std_vga_enabled = 0;
4253 vmsvga_enabled = 1;
4254 } else if (strstart(p, "none", &opts)) {
4255 cirrus_vga_enabled = 0;
4256 std_vga_enabled = 0;
4257 vmsvga_enabled = 0;
4258 } else {
4259 invalid_vga:
4260 fprintf(stderr, "Unknown vga type: %s\n", p);
4261 exit(1);
4263 while (*opts) {
4264 const char *nextopt;
4266 if (strstart(opts, ",retrace=", &nextopt)) {
4267 opts = nextopt;
4268 if (strstart(opts, "dumb", &nextopt))
4269 vga_retrace_method = VGA_RETRACE_DUMB;
4270 else if (strstart(opts, "precise", &nextopt))
4271 vga_retrace_method = VGA_RETRACE_PRECISE;
4272 else goto invalid_vga;
4273 } else goto invalid_vga;
4274 opts = nextopt;
4278 #ifdef _WIN32
4279 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4281 exit(STATUS_CONTROL_C_EXIT);
4282 return TRUE;
4284 #endif
4286 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4288 int ret;
4290 if(strlen(str) != 36)
4291 return -1;
4293 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4294 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4295 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4297 if(ret != 16)
4298 return -1;
4300 return 0;
4303 #define MAX_NET_CLIENTS 32
4305 static int saved_argc;
4306 static char **saved_argv;
4307 static const char *saved_incoming;
4309 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
4311 *argc = saved_argc;
4312 *argv = saved_argv;
4313 *opt_daemonize = daemonize;
4314 *opt_incoming = saved_incoming;
4317 #ifdef USE_KVM
4319 #define HUGETLBFS_MAGIC 0x958458f6
4321 static long gethugepagesize(const char *path)
4323 struct statfs fs;
4324 int ret;
4326 do {
4327 ret = statfs(path, &fs);
4328 } while (ret != 0 && errno == EINTR);
4330 if (ret != 0) {
4331 perror("statfs");
4332 return 0;
4335 if (fs.f_type != HUGETLBFS_MAGIC)
4336 fprintf(stderr, "Warning: path not on HugeTLBFS: %s\n", path);
4338 return fs.f_bsize;
4341 static void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4343 char *filename;
4344 void *area;
4345 int fd;
4346 #ifdef MAP_POPULATE
4347 int flags;
4348 #endif
4350 if (!kvm_has_sync_mmu()) {
4351 fprintf(stderr, "host lacks mmu notifiers, disabling --mem-path\n");
4352 return NULL;
4355 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4356 return NULL;
4358 hpagesize = gethugepagesize(path);
4359 if (!hpagesize)
4360 return NULL;
4362 fd = mkstemp(filename);
4363 if (fd < 0) {
4364 perror("mkstemp");
4365 free(filename);
4366 return NULL;
4368 unlink(filename);
4369 free(filename);
4371 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4374 * ftruncate is not supported by hugetlbfs in older
4375 * hosts, so don't bother checking for errors.
4376 * If anything goes wrong with it under other filesystems,
4377 * mmap will fail.
4379 ftruncate(fd, memory);
4381 #ifdef MAP_POPULATE
4382 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4383 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4384 * to sidestep this quirk.
4386 flags = mem_prealloc ? MAP_POPULATE|MAP_SHARED : MAP_PRIVATE;
4387 area = mmap(0, memory, PROT_READ|PROT_WRITE, flags, fd, 0);
4388 #else
4389 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4390 #endif
4391 if (area == MAP_FAILED) {
4392 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4393 close(fd);
4394 return (NULL);
4396 *len = memory;
4397 return area;
4399 #endif
4401 static void *qemu_alloc_physram(unsigned long memory)
4403 void *area = NULL;
4404 #ifdef USE_KVM
4405 unsigned long map_len = memory;
4407 if (mem_path)
4408 area = alloc_mem_area(memory, &map_len, mem_path);
4409 #endif
4410 if (!area)
4411 area = qemu_vmalloc(memory);
4412 #ifdef USE_KVM
4413 if (kvm_setup_guest_memory(area, map_len))
4414 area = NULL;
4415 #endif
4416 return area;
4419 #ifndef _WIN32
4421 static void termsig_handler(int signal)
4423 qemu_system_shutdown_request();
4426 static void termsig_setup(void)
4428 struct sigaction act;
4430 memset(&act, 0, sizeof(act));
4431 act.sa_handler = termsig_handler;
4432 sigaction(SIGINT, &act, NULL);
4433 sigaction(SIGHUP, &act, NULL);
4434 sigaction(SIGTERM, &act, NULL);
4437 #endif
4439 int main(int argc, char **argv, char **envp)
4441 #ifdef CONFIG_GDBSTUB
4442 const char *gdbstub_dev = NULL;
4443 #endif
4444 uint32_t boot_devices_bitmap = 0;
4445 int i;
4446 int snapshot, linux_boot, net_boot;
4447 const char *initrd_filename;
4448 const char *kernel_filename, *kernel_cmdline;
4449 const char *boot_devices = "";
4450 DisplayState *ds;
4451 DisplayChangeListener *dcl;
4452 int cyls, heads, secs, translation;
4453 const char *net_clients[MAX_NET_CLIENTS];
4454 int nb_net_clients;
4455 const char *bt_opts[MAX_BT_CMDLINE];
4456 int nb_bt_opts;
4457 int hda_index;
4458 int optind;
4459 const char *r, *optarg;
4460 CharDriverState *monitor_hd = NULL;
4461 const char *monitor_device;
4462 const char *serial_devices[MAX_SERIAL_PORTS];
4463 int serial_device_index;
4464 const char *parallel_devices[MAX_PARALLEL_PORTS];
4465 int parallel_device_index;
4466 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4467 int virtio_console_index;
4468 const char *loadvm = NULL;
4469 QEMUMachine *machine;
4470 const char *cpu_model;
4471 const char *usb_devices[MAX_USB_CMDLINE];
4472 int usb_devices_index;
4473 #ifndef _WIN32
4474 int fds[2];
4475 #endif
4476 int tb_size;
4477 const char *pid_file = NULL;
4478 const char *incoming = NULL;
4479 #ifndef _WIN32
4480 int fd = 0;
4481 struct passwd *pwd = NULL;
4482 const char *chroot_dir = NULL;
4483 const char *run_as = NULL;
4484 #endif
4486 qemu_cache_utils_init(envp);
4488 LIST_INIT (&vm_change_state_head);
4489 #ifndef _WIN32
4491 struct sigaction act;
4492 sigfillset(&act.sa_mask);
4493 act.sa_flags = 0;
4494 act.sa_handler = SIG_IGN;
4495 sigaction(SIGPIPE, &act, NULL);
4497 #else
4498 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4499 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4500 QEMU to run on a single CPU */
4502 HANDLE h;
4503 DWORD mask, smask;
4504 int i;
4505 h = GetCurrentProcess();
4506 if (GetProcessAffinityMask(h, &mask, &smask)) {
4507 for(i = 0; i < 32; i++) {
4508 if (mask & (1 << i))
4509 break;
4511 if (i != 32) {
4512 mask = 1 << i;
4513 SetProcessAffinityMask(h, mask);
4517 #endif
4519 register_machines();
4520 machine = first_machine;
4521 cpu_model = NULL;
4522 initrd_filename = NULL;
4523 ram_size = 0;
4524 vga_ram_size = VGA_RAM_SIZE;
4525 snapshot = 0;
4526 nographic = 0;
4527 curses = 0;
4528 kernel_filename = NULL;
4529 kernel_cmdline = "";
4530 cyls = heads = secs = 0;
4531 translation = BIOS_ATA_TRANSLATION_AUTO;
4532 monitor_device = "vc:80Cx24C";
4534 serial_devices[0] = "vc:80Cx24C";
4535 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4536 serial_devices[i] = NULL;
4537 serial_device_index = 0;
4539 parallel_devices[0] = "vc:80Cx24C";
4540 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4541 parallel_devices[i] = NULL;
4542 parallel_device_index = 0;
4544 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4545 virtio_consoles[i] = NULL;
4546 virtio_console_index = 0;
4548 usb_devices_index = 0;
4549 assigned_devices_index = 0;
4551 nb_net_clients = 0;
4552 nb_bt_opts = 0;
4553 nb_drives = 0;
4554 nb_drives_opt = 0;
4555 hda_index = -1;
4557 nb_nics = 0;
4559 tb_size = 0;
4560 autostart= 1;
4562 optind = 1;
4563 for(;;) {
4564 if (optind >= argc)
4565 break;
4566 r = argv[optind];
4567 if (r[0] != '-') {
4568 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4569 } else {
4570 const QEMUOption *popt;
4572 optind++;
4573 /* Treat --foo the same as -foo. */
4574 if (r[1] == '-')
4575 r++;
4576 popt = qemu_options;
4577 for(;;) {
4578 if (!popt->name) {
4579 fprintf(stderr, "%s: invalid option -- '%s'\n",
4580 argv[0], r);
4581 exit(1);
4583 if (!strcmp(popt->name, r + 1))
4584 break;
4585 popt++;
4587 if (popt->flags & HAS_ARG) {
4588 if (optind >= argc) {
4589 fprintf(stderr, "%s: option '%s' requires an argument\n",
4590 argv[0], r);
4591 exit(1);
4593 optarg = argv[optind++];
4594 } else {
4595 optarg = NULL;
4598 switch(popt->index) {
4599 case QEMU_OPTION_M:
4600 machine = find_machine(optarg);
4601 if (!machine) {
4602 QEMUMachine *m;
4603 printf("Supported machines are:\n");
4604 for(m = first_machine; m != NULL; m = m->next) {
4605 printf("%-10s %s%s\n",
4606 m->name, m->desc,
4607 m == first_machine ? " (default)" : "");
4609 exit(*optarg != '?');
4611 break;
4612 case QEMU_OPTION_cpu:
4613 /* hw initialization will check this */
4614 if (*optarg == '?') {
4615 /* XXX: implement xxx_cpu_list for targets that still miss it */
4616 #if defined(cpu_list)
4617 cpu_list(stdout, &fprintf);
4618 #endif
4619 exit(0);
4620 } else {
4621 cpu_model = optarg;
4623 break;
4624 case QEMU_OPTION_initrd:
4625 initrd_filename = optarg;
4626 break;
4627 case QEMU_OPTION_hda:
4628 if (cyls == 0)
4629 hda_index = drive_add(optarg, HD_ALIAS, 0);
4630 else
4631 hda_index = drive_add(optarg, HD_ALIAS
4632 ",cyls=%d,heads=%d,secs=%d%s",
4633 0, cyls, heads, secs,
4634 translation == BIOS_ATA_TRANSLATION_LBA ?
4635 ",trans=lba" :
4636 translation == BIOS_ATA_TRANSLATION_NONE ?
4637 ",trans=none" : "");
4638 break;
4639 case QEMU_OPTION_hdb:
4640 case QEMU_OPTION_hdc:
4641 case QEMU_OPTION_hdd:
4642 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4643 break;
4644 case QEMU_OPTION_drive:
4645 drive_add(NULL, "%s", optarg);
4646 break;
4647 case QEMU_OPTION_mtdblock:
4648 drive_add(optarg, MTD_ALIAS);
4649 break;
4650 case QEMU_OPTION_sd:
4651 drive_add(optarg, SD_ALIAS);
4652 break;
4653 case QEMU_OPTION_pflash:
4654 drive_add(optarg, PFLASH_ALIAS);
4655 break;
4656 case QEMU_OPTION_snapshot:
4657 snapshot = 1;
4658 break;
4659 case QEMU_OPTION_hdachs:
4661 const char *p;
4662 p = optarg;
4663 cyls = strtol(p, (char **)&p, 0);
4664 if (cyls < 1 || cyls > 16383)
4665 goto chs_fail;
4666 if (*p != ',')
4667 goto chs_fail;
4668 p++;
4669 heads = strtol(p, (char **)&p, 0);
4670 if (heads < 1 || heads > 16)
4671 goto chs_fail;
4672 if (*p != ',')
4673 goto chs_fail;
4674 p++;
4675 secs = strtol(p, (char **)&p, 0);
4676 if (secs < 1 || secs > 63)
4677 goto chs_fail;
4678 if (*p == ',') {
4679 p++;
4680 if (!strcmp(p, "none"))
4681 translation = BIOS_ATA_TRANSLATION_NONE;
4682 else if (!strcmp(p, "lba"))
4683 translation = BIOS_ATA_TRANSLATION_LBA;
4684 else if (!strcmp(p, "auto"))
4685 translation = BIOS_ATA_TRANSLATION_AUTO;
4686 else
4687 goto chs_fail;
4688 } else if (*p != '\0') {
4689 chs_fail:
4690 fprintf(stderr, "qemu: invalid physical CHS format\n");
4691 exit(1);
4693 if (hda_index != -1)
4694 snprintf(drives_opt[hda_index].opt,
4695 sizeof(drives_opt[hda_index].opt),
4696 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4697 0, cyls, heads, secs,
4698 translation == BIOS_ATA_TRANSLATION_LBA ?
4699 ",trans=lba" :
4700 translation == BIOS_ATA_TRANSLATION_NONE ?
4701 ",trans=none" : "");
4703 break;
4704 case QEMU_OPTION_nographic:
4705 nographic = 1;
4706 break;
4707 #ifdef CONFIG_CURSES
4708 case QEMU_OPTION_curses:
4709 curses = 1;
4710 break;
4711 #endif
4712 case QEMU_OPTION_portrait:
4713 graphic_rotate = 1;
4714 break;
4715 case QEMU_OPTION_kernel:
4716 kernel_filename = optarg;
4717 break;
4718 case QEMU_OPTION_append:
4719 kernel_cmdline = optarg;
4720 break;
4721 case QEMU_OPTION_cdrom:
4722 drive_add(optarg, CDROM_ALIAS);
4723 break;
4724 case QEMU_OPTION_boot:
4725 boot_devices = optarg;
4726 /* We just do some generic consistency checks */
4728 /* Could easily be extended to 64 devices if needed */
4729 const char *p;
4731 boot_devices_bitmap = 0;
4732 for (p = boot_devices; *p != '\0'; p++) {
4733 /* Allowed boot devices are:
4734 * a b : floppy disk drives
4735 * c ... f : IDE disk drives
4736 * g ... m : machine implementation dependant drives
4737 * n ... p : network devices
4738 * It's up to each machine implementation to check
4739 * if the given boot devices match the actual hardware
4740 * implementation and firmware features.
4742 if (*p < 'a' || *p > 'q') {
4743 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4744 exit(1);
4746 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4747 fprintf(stderr,
4748 "Boot device '%c' was given twice\n",*p);
4749 exit(1);
4751 boot_devices_bitmap |= 1 << (*p - 'a');
4754 break;
4755 case QEMU_OPTION_fda:
4756 case QEMU_OPTION_fdb:
4757 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4758 break;
4759 #ifdef TARGET_I386
4760 case QEMU_OPTION_no_fd_bootchk:
4761 fd_bootchk = 0;
4762 break;
4763 #endif
4764 case QEMU_OPTION_net:
4765 if (nb_net_clients >= MAX_NET_CLIENTS) {
4766 fprintf(stderr, "qemu: too many network clients\n");
4767 exit(1);
4769 net_clients[nb_net_clients] = optarg;
4770 nb_net_clients++;
4771 break;
4772 #ifdef CONFIG_SLIRP
4773 case QEMU_OPTION_tftp:
4774 tftp_prefix = optarg;
4775 break;
4776 case QEMU_OPTION_bootp:
4777 bootp_filename = optarg;
4778 break;
4779 #ifndef _WIN32
4780 case QEMU_OPTION_smb:
4781 net_slirp_smb(optarg);
4782 break;
4783 #endif
4784 case QEMU_OPTION_redir:
4785 net_slirp_redir(optarg);
4786 break;
4787 #endif
4788 case QEMU_OPTION_bt:
4789 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4790 fprintf(stderr, "qemu: too many bluetooth options\n");
4791 exit(1);
4793 bt_opts[nb_bt_opts++] = optarg;
4794 break;
4795 #ifdef HAS_AUDIO
4796 case QEMU_OPTION_audio_help:
4797 AUD_help ();
4798 exit (0);
4799 break;
4800 case QEMU_OPTION_soundhw:
4801 select_soundhw (optarg);
4802 break;
4803 #endif
4804 case QEMU_OPTION_h:
4805 help(0);
4806 break;
4807 case QEMU_OPTION_m: {
4808 uint64_t value;
4809 char *ptr;
4811 value = strtoul(optarg, &ptr, 10);
4812 switch (*ptr) {
4813 case 0: case 'M': case 'm':
4814 value <<= 20;
4815 break;
4816 case 'G': case 'g':
4817 value <<= 30;
4818 break;
4819 default:
4820 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4821 exit(1);
4824 /* On 32-bit hosts, QEMU is limited by virtual address space */
4825 if (value > (2047 << 20)
4826 #ifndef USE_KQEMU
4827 && HOST_LONG_BITS == 32
4828 #endif
4830 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4831 exit(1);
4833 if (value != (uint64_t)(ram_addr_t)value) {
4834 fprintf(stderr, "qemu: ram size too large\n");
4835 exit(1);
4837 ram_size = value;
4838 break;
4840 case QEMU_OPTION_d:
4842 int mask;
4843 const CPULogItem *item;
4845 mask = cpu_str_to_log_mask(optarg);
4846 if (!mask) {
4847 printf("Log items (comma separated):\n");
4848 for(item = cpu_log_items; item->mask != 0; item++) {
4849 printf("%-10s %s\n", item->name, item->help);
4851 exit(1);
4853 cpu_set_log(mask);
4855 break;
4856 #ifdef CONFIG_GDBSTUB
4857 case QEMU_OPTION_s:
4858 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
4859 break;
4860 case QEMU_OPTION_gdb:
4861 gdbstub_dev = optarg;
4862 break;
4863 #endif
4864 case QEMU_OPTION_L:
4865 bios_dir = optarg;
4866 break;
4867 case QEMU_OPTION_bios:
4868 bios_name = optarg;
4869 break;
4870 case QEMU_OPTION_singlestep:
4871 singlestep = 1;
4872 break;
4873 case QEMU_OPTION_S:
4874 autostart = 0;
4875 break;
4876 #ifndef _WIN32
4877 case QEMU_OPTION_k:
4878 keyboard_layout = optarg;
4879 break;
4880 #endif
4881 case QEMU_OPTION_localtime:
4882 rtc_utc = 0;
4883 break;
4884 case QEMU_OPTION_vga:
4885 select_vgahw (optarg);
4886 break;
4887 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4888 case QEMU_OPTION_g:
4890 const char *p;
4891 int w, h, depth;
4892 p = optarg;
4893 w = strtol(p, (char **)&p, 10);
4894 if (w <= 0) {
4895 graphic_error:
4896 fprintf(stderr, "qemu: invalid resolution or depth\n");
4897 exit(1);
4899 if (*p != 'x')
4900 goto graphic_error;
4901 p++;
4902 h = strtol(p, (char **)&p, 10);
4903 if (h <= 0)
4904 goto graphic_error;
4905 if (*p == 'x') {
4906 p++;
4907 depth = strtol(p, (char **)&p, 10);
4908 if (depth != 8 && depth != 15 && depth != 16 &&
4909 depth != 24 && depth != 32)
4910 goto graphic_error;
4911 } else if (*p == '\0') {
4912 depth = graphic_depth;
4913 } else {
4914 goto graphic_error;
4917 graphic_width = w;
4918 graphic_height = h;
4919 graphic_depth = depth;
4921 break;
4922 #endif
4923 case QEMU_OPTION_echr:
4925 char *r;
4926 term_escape_char = strtol(optarg, &r, 0);
4927 if (r == optarg)
4928 printf("Bad argument to echr\n");
4929 break;
4931 case QEMU_OPTION_monitor:
4932 monitor_device = optarg;
4933 break;
4934 case QEMU_OPTION_serial:
4935 if (serial_device_index >= MAX_SERIAL_PORTS) {
4936 fprintf(stderr, "qemu: too many serial ports\n");
4937 exit(1);
4939 serial_devices[serial_device_index] = optarg;
4940 serial_device_index++;
4941 break;
4942 case QEMU_OPTION_virtiocon:
4943 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
4944 fprintf(stderr, "qemu: too many virtio consoles\n");
4945 exit(1);
4947 virtio_consoles[virtio_console_index] = optarg;
4948 virtio_console_index++;
4949 break;
4950 case QEMU_OPTION_parallel:
4951 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4952 fprintf(stderr, "qemu: too many parallel ports\n");
4953 exit(1);
4955 parallel_devices[parallel_device_index] = optarg;
4956 parallel_device_index++;
4957 break;
4958 case QEMU_OPTION_loadvm:
4959 loadvm = optarg;
4960 break;
4961 case QEMU_OPTION_full_screen:
4962 full_screen = 1;
4963 break;
4964 #ifdef CONFIG_SDL
4965 case QEMU_OPTION_no_frame:
4966 no_frame = 1;
4967 break;
4968 case QEMU_OPTION_alt_grab:
4969 alt_grab = 1;
4970 break;
4971 case QEMU_OPTION_no_quit:
4972 no_quit = 1;
4973 break;
4974 case QEMU_OPTION_sdl:
4975 sdl = 1;
4976 break;
4977 #endif
4978 case QEMU_OPTION_pidfile:
4979 pid_file = optarg;
4980 break;
4981 #ifdef TARGET_I386
4982 case QEMU_OPTION_win2k_hack:
4983 win2k_install_hack = 1;
4984 break;
4985 case QEMU_OPTION_rtc_td_hack:
4986 rtc_td_hack = 1;
4987 break;
4988 case QEMU_OPTION_acpitable:
4989 if(acpi_table_add(optarg) < 0) {
4990 fprintf(stderr, "Wrong acpi table provided\n");
4991 exit(1);
4993 break;
4994 #endif
4995 #ifdef USE_KQEMU
4996 case QEMU_OPTION_no_kqemu:
4997 kqemu_allowed = 0;
4998 break;
4999 case QEMU_OPTION_kernel_kqemu:
5000 kqemu_allowed = 2;
5001 break;
5002 #endif
5003 #ifdef CONFIG_KVM
5004 case QEMU_OPTION_enable_kvm:
5005 kvm_allowed = 1;
5006 #ifdef USE_KQEMU
5007 kqemu_allowed = 0;
5008 #endif
5009 break;
5010 #endif
5011 #ifdef USE_KVM
5012 case QEMU_OPTION_no_kvm:
5013 kvm_allowed = 0;
5014 break;
5015 case QEMU_OPTION_no_kvm_irqchip: {
5016 kvm_irqchip = 0;
5017 kvm_pit = 0;
5018 break;
5020 case QEMU_OPTION_no_kvm_pit: {
5021 kvm_pit = 0;
5022 break;
5024 case QEMU_OPTION_no_kvm_pit_reinjection: {
5025 kvm_pit_reinject = 0;
5026 break;
5028 case QEMU_OPTION_enable_nesting: {
5029 kvm_nested = 1;
5030 break;
5032 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5033 case QEMU_OPTION_pcidevice:
5034 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5035 fprintf(stderr, "Too many assigned devices\n");
5036 exit(1);
5038 assigned_devices[assigned_devices_index] = optarg;
5039 assigned_devices_index++;
5040 break;
5041 #endif
5042 #endif
5043 case QEMU_OPTION_usb:
5044 usb_enabled = 1;
5045 break;
5046 case QEMU_OPTION_usbdevice:
5047 usb_enabled = 1;
5048 if (usb_devices_index >= MAX_USB_CMDLINE) {
5049 fprintf(stderr, "Too many USB devices\n");
5050 exit(1);
5052 usb_devices[usb_devices_index] = optarg;
5053 usb_devices_index++;
5054 break;
5055 case QEMU_OPTION_smp:
5056 smp_cpus = atoi(optarg);
5057 if (smp_cpus < 1) {
5058 fprintf(stderr, "Invalid number of CPUs\n");
5059 exit(1);
5061 break;
5062 case QEMU_OPTION_vnc:
5063 vnc_display = optarg;
5064 break;
5065 #ifdef TARGET_I386
5066 case QEMU_OPTION_no_acpi:
5067 acpi_enabled = 0;
5068 break;
5069 case QEMU_OPTION_no_hpet:
5070 no_hpet = 1;
5071 break;
5072 #endif
5073 case QEMU_OPTION_no_reboot:
5074 no_reboot = 1;
5075 break;
5076 case QEMU_OPTION_no_shutdown:
5077 no_shutdown = 1;
5078 break;
5079 case QEMU_OPTION_show_cursor:
5080 cursor_hide = 0;
5081 break;
5082 case QEMU_OPTION_uuid:
5083 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5084 fprintf(stderr, "Fail to parse UUID string."
5085 " Wrong format.\n");
5086 exit(1);
5088 break;
5089 #ifndef _WIN32
5090 case QEMU_OPTION_daemonize:
5091 daemonize = 1;
5092 break;
5093 #endif
5094 case QEMU_OPTION_option_rom:
5095 if (nb_option_roms >= MAX_OPTION_ROMS) {
5096 fprintf(stderr, "Too many option ROMs\n");
5097 exit(1);
5099 option_rom[nb_option_roms] = optarg;
5100 nb_option_roms++;
5101 break;
5102 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5103 case QEMU_OPTION_semihosting:
5104 semihosting_enabled = 1;
5105 break;
5106 #endif
5107 case QEMU_OPTION_tdf:
5108 time_drift_fix = 1;
5109 break;
5110 case QEMU_OPTION_kvm_shadow_memory:
5111 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5112 break;
5113 case QEMU_OPTION_mempath:
5114 mem_path = optarg;
5115 break;
5116 #ifdef MAP_POPULATE
5117 case QEMU_OPTION_mem_prealloc:
5118 mem_prealloc = !mem_prealloc;
5119 break;
5120 #endif
5121 case QEMU_OPTION_name:
5122 qemu_name = optarg;
5123 break;
5124 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5125 case QEMU_OPTION_prom_env:
5126 if (nb_prom_envs >= MAX_PROM_ENVS) {
5127 fprintf(stderr, "Too many prom variables\n");
5128 exit(1);
5130 prom_envs[nb_prom_envs] = optarg;
5131 nb_prom_envs++;
5132 break;
5133 #endif
5134 case QEMU_OPTION_cpu_vendor:
5135 cpu_vendor_string = optarg;
5136 break;
5137 #ifdef TARGET_ARM
5138 case QEMU_OPTION_old_param:
5139 old_param = 1;
5140 break;
5141 #endif
5142 case QEMU_OPTION_clock:
5143 configure_alarms(optarg);
5144 break;
5145 case QEMU_OPTION_startdate:
5147 struct tm tm;
5148 time_t rtc_start_date;
5149 if (!strcmp(optarg, "now")) {
5150 rtc_date_offset = -1;
5151 } else {
5152 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5153 &tm.tm_year,
5154 &tm.tm_mon,
5155 &tm.tm_mday,
5156 &tm.tm_hour,
5157 &tm.tm_min,
5158 &tm.tm_sec) == 6) {
5159 /* OK */
5160 } else if (sscanf(optarg, "%d-%d-%d",
5161 &tm.tm_year,
5162 &tm.tm_mon,
5163 &tm.tm_mday) == 3) {
5164 tm.tm_hour = 0;
5165 tm.tm_min = 0;
5166 tm.tm_sec = 0;
5167 } else {
5168 goto date_fail;
5170 tm.tm_year -= 1900;
5171 tm.tm_mon--;
5172 rtc_start_date = mktimegm(&tm);
5173 if (rtc_start_date == -1) {
5174 date_fail:
5175 fprintf(stderr, "Invalid date format. Valid format are:\n"
5176 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5177 exit(1);
5179 rtc_date_offset = time(NULL) - rtc_start_date;
5182 break;
5183 case QEMU_OPTION_tb_size:
5184 tb_size = strtol(optarg, NULL, 0);
5185 if (tb_size < 0)
5186 tb_size = 0;
5187 break;
5188 case QEMU_OPTION_icount:
5189 use_icount = 1;
5190 if (strcmp(optarg, "auto") == 0) {
5191 icount_time_shift = -1;
5192 } else {
5193 icount_time_shift = strtol(optarg, NULL, 0);
5195 break;
5196 case QEMU_OPTION_incoming:
5197 incoming = optarg;
5198 saved_incoming = incoming;
5199 break;
5200 #ifndef _WIN32
5201 case QEMU_OPTION_chroot:
5202 chroot_dir = optarg;
5203 break;
5204 case QEMU_OPTION_runas:
5205 run_as = optarg;
5206 break;
5207 case QEMU_OPTION_nvram:
5208 nvram = optarg;
5209 break;
5210 #endif
5215 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5216 if (kvm_allowed && kqemu_allowed) {
5217 fprintf(stderr,
5218 "You can not enable both KVM and kqemu at the same time\n");
5219 exit(1);
5221 #endif
5223 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5224 if (smp_cpus > machine->max_cpus) {
5225 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5226 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5227 machine->max_cpus);
5228 exit(1);
5231 if (nographic) {
5232 if (serial_device_index == 0)
5233 serial_devices[0] = "stdio";
5234 if (parallel_device_index == 0)
5235 parallel_devices[0] = "null";
5236 if (strncmp(monitor_device, "vc", 2) == 0)
5237 monitor_device = "stdio";
5240 #ifndef _WIN32
5241 if (daemonize) {
5242 pid_t pid;
5244 if (pipe(fds) == -1)
5245 exit(1);
5247 pid = fork();
5248 if (pid > 0) {
5249 uint8_t status;
5250 ssize_t len;
5252 close(fds[1]);
5254 again:
5255 len = read(fds[0], &status, 1);
5256 if (len == -1 && (errno == EINTR))
5257 goto again;
5259 if (len != 1)
5260 exit(1);
5261 else if (status == 1) {
5262 fprintf(stderr, "Could not acquire pidfile\n");
5263 exit(1);
5264 } else
5265 exit(0);
5266 } else if (pid < 0)
5267 exit(1);
5269 setsid();
5271 pid = fork();
5272 if (pid > 0)
5273 exit(0);
5274 else if (pid < 0)
5275 exit(1);
5277 umask(027);
5279 signal(SIGTSTP, SIG_IGN);
5280 signal(SIGTTOU, SIG_IGN);
5281 signal(SIGTTIN, SIG_IGN);
5284 #ifdef USE_KVM
5285 if (kvm_enabled()) {
5286 if (kvm_qemu_init() < 0) {
5287 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5288 #ifdef NO_CPU_EMULATION
5289 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5290 exit(1);
5291 #endif
5292 kvm_allowed = 0;
5295 #endif
5297 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5298 if (daemonize) {
5299 uint8_t status = 1;
5300 write(fds[1], &status, 1);
5301 } else
5302 fprintf(stderr, "Could not acquire pid file\n");
5303 exit(1);
5305 #endif
5307 #ifdef USE_KQEMU
5308 if (smp_cpus > 1)
5309 kqemu_allowed = 0;
5310 #endif
5311 linux_boot = (kernel_filename != NULL);
5312 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5314 if (!linux_boot && *kernel_cmdline != '\0') {
5315 fprintf(stderr, "-append only allowed with -kernel option\n");
5316 exit(1);
5319 if (!linux_boot && initrd_filename != NULL) {
5320 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5321 exit(1);
5324 /* boot to floppy or the default cd if no hard disk defined yet */
5325 if (!boot_devices[0]) {
5326 boot_devices = "cad";
5328 setvbuf(stdout, NULL, _IOLBF, 0);
5330 init_timers();
5331 if (init_timer_alarm() < 0) {
5332 fprintf(stderr, "could not initialize alarm timer\n");
5333 exit(1);
5335 if (use_icount && icount_time_shift < 0) {
5336 use_icount = 2;
5337 /* 125MIPS seems a reasonable initial guess at the guest speed.
5338 It will be corrected fairly quickly anyway. */
5339 icount_time_shift = 3;
5340 init_icount_adjust();
5343 #ifdef _WIN32
5344 socket_init();
5345 #endif
5347 /* init network clients */
5348 if (nb_net_clients == 0) {
5349 /* if no clients, we use a default config */
5350 net_clients[nb_net_clients++] = "nic";
5351 #ifdef CONFIG_SLIRP
5352 net_clients[nb_net_clients++] = "user";
5353 #endif
5356 for(i = 0;i < nb_net_clients; i++) {
5357 if (net_client_parse(net_clients[i]) < 0)
5358 exit(1);
5360 net_client_check();
5362 #ifdef TARGET_I386
5363 /* XXX: this should be moved in the PC machine instantiation code */
5364 if (net_boot != 0) {
5365 int netroms = 0;
5366 for (i = 0; i < nb_nics && i < 4; i++) {
5367 const char *model = nd_table[i].model;
5368 char buf[1024];
5369 if (net_boot & (1 << i)) {
5370 if (model == NULL)
5371 model = "rtl8139";
5372 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5373 if (get_image_size(buf) > 0) {
5374 if (nb_option_roms >= MAX_OPTION_ROMS) {
5375 fprintf(stderr, "Too many option ROMs\n");
5376 exit(1);
5378 option_rom[nb_option_roms] = strdup(buf);
5379 nb_option_roms++;
5380 netroms++;
5384 if (netroms == 0) {
5385 fprintf(stderr, "No valid PXE rom found for network device\n");
5386 exit(1);
5389 #endif
5391 /* init the bluetooth world */
5392 for (i = 0; i < nb_bt_opts; i++)
5393 if (bt_parse(bt_opts[i]))
5394 exit(1);
5396 /* init the memory */
5397 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5399 if (machine->ram_require & RAMSIZE_FIXED) {
5400 if (ram_size > 0) {
5401 if (ram_size < phys_ram_size) {
5402 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5403 machine->name, (unsigned long long) phys_ram_size);
5404 exit(-1);
5407 phys_ram_size = ram_size;
5408 } else
5409 ram_size = phys_ram_size;
5410 } else {
5411 if (ram_size == 0)
5412 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5414 phys_ram_size += ram_size;
5417 /* Initialize kvm */
5418 #if defined(TARGET_I386) || defined(TARGET_X86_64)
5419 #define KVM_EXTRA_PAGES 3
5420 #else
5421 #define KVM_EXTRA_PAGES 0
5422 #endif
5423 if (kvm_enabled()) {
5424 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
5425 if (kvm_qemu_create_context() < 0) {
5426 fprintf(stderr, "Could not create KVM context\n");
5427 exit(1);
5431 phys_ram_base = qemu_alloc_physram(phys_ram_size);
5432 if (!phys_ram_base) {
5433 fprintf(stderr, "Could not allocate physical memory\n");
5434 exit(1);
5437 /* init the dynamic translator */
5438 cpu_exec_init_all(tb_size * 1024 * 1024);
5440 bdrv_init();
5441 dma_helper_init();
5443 /* we always create the cdrom drive, even if no disk is there */
5445 if (nb_drives_opt < MAX_DRIVES)
5446 drive_add(NULL, CDROM_ALIAS);
5448 /* we always create at least one floppy */
5450 if (nb_drives_opt < MAX_DRIVES)
5451 drive_add(NULL, FD_ALIAS, 0);
5453 /* we always create one sd slot, even if no card is in it */
5455 if (nb_drives_opt < MAX_DRIVES)
5456 drive_add(NULL, SD_ALIAS);
5458 /* open the virtual block devices
5459 * note that migration with device
5460 * hot add/remove is broken.
5462 for(i = 0; i < nb_drives_opt; i++)
5463 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5464 exit(1);
5466 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5467 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5469 #ifndef _WIN32
5470 /* must be after terminal init, SDL library changes signal handlers */
5471 termsig_setup();
5472 #endif
5474 /* Maintain compatibility with multiple stdio monitors */
5475 if (!strcmp(monitor_device,"stdio")) {
5476 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5477 const char *devname = serial_devices[i];
5478 if (devname && !strcmp(devname,"mon:stdio")) {
5479 monitor_device = NULL;
5480 break;
5481 } else if (devname && !strcmp(devname,"stdio")) {
5482 monitor_device = NULL;
5483 serial_devices[i] = "mon:stdio";
5484 break;
5489 #ifdef KVM_UPSTREAM
5490 if (kvm_enabled()) {
5491 int ret;
5493 ret = kvm_init(smp_cpus);
5494 if (ret < 0) {
5495 fprintf(stderr, "failed to initialize KVM\n");
5496 exit(1);
5499 #endif
5501 if (monitor_device) {
5502 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5503 if (!monitor_hd) {
5504 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5505 exit(1);
5509 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5510 const char *devname = serial_devices[i];
5511 if (devname && strcmp(devname, "none")) {
5512 char label[32];
5513 snprintf(label, sizeof(label), "serial%d", i);
5514 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5515 if (!serial_hds[i]) {
5516 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5517 devname);
5518 exit(1);
5523 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5524 const char *devname = parallel_devices[i];
5525 if (devname && strcmp(devname, "none")) {
5526 char label[32];
5527 snprintf(label, sizeof(label), "parallel%d", i);
5528 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5529 if (!parallel_hds[i]) {
5530 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5531 devname);
5532 exit(1);
5537 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5538 const char *devname = virtio_consoles[i];
5539 if (devname && strcmp(devname, "none")) {
5540 char label[32];
5541 snprintf(label, sizeof(label), "virtcon%d", i);
5542 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5543 if (!virtcon_hds[i]) {
5544 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5545 devname);
5546 exit(1);
5551 if (kvm_enabled())
5552 kvm_init_ap();
5554 machine->init(ram_size, vga_ram_size, boot_devices,
5555 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5557 current_machine = machine;
5559 /* Set KVM's vcpu state to qemu's initial CPUState. */
5560 if (kvm_enabled()) {
5561 int ret;
5563 ret = kvm_sync_vcpus();
5564 if (ret < 0) {
5565 fprintf(stderr, "failed to initialize vcpus\n");
5566 exit(1);
5570 /* init USB devices */
5571 if (usb_enabled) {
5572 for(i = 0; i < usb_devices_index; i++) {
5573 if (usb_device_add(usb_devices[i], 0) < 0) {
5574 fprintf(stderr, "Warning: could not add USB device %s\n",
5575 usb_devices[i]);
5580 if (!display_state)
5581 dumb_display_init();
5582 /* just use the first displaystate for the moment */
5583 ds = display_state;
5584 /* terminal init */
5585 if (nographic) {
5586 if (curses) {
5587 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5588 exit(1);
5590 } else {
5591 #if defined(CONFIG_CURSES)
5592 if (curses) {
5593 /* At the moment curses cannot be used with other displays */
5594 curses_display_init(ds, full_screen);
5595 } else
5596 #endif
5598 if (vnc_display != NULL) {
5599 vnc_display_init(ds);
5600 if (vnc_display_open(ds, vnc_display) < 0)
5601 exit(1);
5603 #if defined(CONFIG_SDL)
5604 if (sdl || !vnc_display)
5605 sdl_display_init(ds, full_screen, no_frame);
5606 #elif defined(CONFIG_COCOA)
5607 if (sdl || !vnc_display)
5608 cocoa_display_init(ds, full_screen);
5609 #endif
5612 dpy_resize(ds);
5614 dcl = ds->listeners;
5615 while (dcl != NULL) {
5616 if (dcl->dpy_refresh != NULL) {
5617 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5618 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5620 dcl = dcl->next;
5623 if (nographic || (vnc_display && !sdl)) {
5624 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5625 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5628 text_consoles_set_display(display_state);
5629 qemu_chr_initial_reset();
5631 if (monitor_device && monitor_hd)
5632 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
5634 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5635 const char *devname = serial_devices[i];
5636 if (devname && strcmp(devname, "none")) {
5637 char label[32];
5638 snprintf(label, sizeof(label), "serial%d", i);
5639 if (strstart(devname, "vc", 0))
5640 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5644 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5645 const char *devname = parallel_devices[i];
5646 if (devname && strcmp(devname, "none")) {
5647 char label[32];
5648 snprintf(label, sizeof(label), "parallel%d", i);
5649 if (strstart(devname, "vc", 0))
5650 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5654 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5655 const char *devname = virtio_consoles[i];
5656 if (virtcon_hds[i] && devname) {
5657 char label[32];
5658 snprintf(label, sizeof(label), "virtcon%d", i);
5659 if (strstart(devname, "vc", 0))
5660 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5664 #ifdef CONFIG_GDBSTUB
5665 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5666 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5667 gdbstub_dev);
5668 exit(1);
5670 #endif
5672 if (loadvm)
5673 do_loadvm(cur_mon, loadvm);
5675 if (incoming) {
5676 autostart = 0; /* fixme how to deal with -daemonize */
5677 qemu_start_incoming_migration(incoming);
5680 if (autostart)
5681 vm_start();
5683 #ifndef _WIN32
5684 if (daemonize) {
5685 uint8_t status = 0;
5686 ssize_t len;
5688 again1:
5689 len = write(fds[1], &status, 1);
5690 if (len == -1 && (errno == EINTR))
5691 goto again1;
5693 if (len != 1)
5694 exit(1);
5696 chdir("/");
5697 TFR(fd = open("/dev/null", O_RDWR));
5698 if (fd == -1)
5699 exit(1);
5702 if (run_as) {
5703 pwd = getpwnam(run_as);
5704 if (!pwd) {
5705 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5706 exit(1);
5710 if (chroot_dir) {
5711 if (chroot(chroot_dir) < 0) {
5712 fprintf(stderr, "chroot failed\n");
5713 exit(1);
5715 chdir("/");
5718 if (run_as) {
5719 if (setgid(pwd->pw_gid) < 0) {
5720 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5721 exit(1);
5723 if (setuid(pwd->pw_uid) < 0) {
5724 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5725 exit(1);
5727 if (setuid(0) != -1) {
5728 fprintf(stderr, "Dropping privileges failed\n");
5729 exit(1);
5733 if (daemonize) {
5734 dup2(fd, 0);
5735 dup2(fd, 1);
5736 dup2(fd, 2);
5738 close(fd);
5740 #endif
5742 main_loop();
5743 quit_timers();
5744 net_cleanup();
5746 return 0;