Define cpu_has_work() for ia64
[qemu-kvm/fedora.git] / vl.c
blob6b4b7d29e952c9659c9ecaabc3086c0314db7c5a
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
32 /* Needed early for HOST_BSD etc. */
33 #include "config-host.h"
35 #ifndef _WIN32
36 #include <pwd.h>
37 #include <sys/times.h>
38 #include <sys/wait.h>
39 #include <termios.h>
40 #include <sys/mman.h>
41 #include <sys/ioctl.h>
42 #include <sys/resource.h>
43 #include <sys/socket.h>
44 #include <sys/vfs.h>
45 #include <netinet/in.h>
46 #include <net/if.h>
47 #if defined(__NetBSD__)
48 #include <net/if_tap.h>
49 #endif
50 #ifdef __linux__
51 #include <linux/if_tun.h>
52 #endif
53 #include <arpa/inet.h>
54 #include <dirent.h>
55 #include <netdb.h>
56 #include <sys/select.h>
57 #ifdef HOST_BSD
58 #include <sys/stat.h>
59 #if defined(__FreeBSD__) || defined(__DragonFly__)
60 #include <libutil.h>
61 #else
62 #include <util.h>
63 #endif
64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65 #include <freebsd/stdlib.h>
66 #else
67 #ifdef __linux__
68 #include <pty.h>
69 #include <malloc.h>
70 #include <linux/rtc.h>
72 /* For the benefit of older linux systems which don't supply it,
73 we use a local copy of hpet.h. */
74 /* #include <linux/hpet.h> */
75 #include "hpet.h"
77 #include <linux/ppdev.h>
78 #include <linux/parport.h>
79 #endif
80 #ifdef __sun__
81 #include <sys/stat.h>
82 #include <sys/ethernet.h>
83 #include <sys/sockio.h>
84 #include <netinet/arp.h>
85 #include <netinet/in.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip_icmp.h> // must come after ip.h
89 #include <netinet/udp.h>
90 #include <netinet/tcp.h>
91 #include <net/if.h>
92 #include <syslog.h>
93 #include <stropts.h>
94 #endif
95 #endif
96 #endif
98 #if defined(__OpenBSD__)
99 #include <util.h>
100 #endif
102 #if defined(CONFIG_VDE)
103 #include <libvdeplug.h>
104 #endif
106 #ifdef _WIN32
107 #include <windows.h>
108 #include <malloc.h>
109 #include <sys/timeb.h>
110 #include <mmsystem.h>
111 #define getopt_long_only getopt_long
112 #define memalign(align, size) malloc(size)
113 #endif
115 #ifdef CONFIG_SDL
116 #ifdef __APPLE__
117 #include <SDL/SDL.h>
118 int qemu_main(int argc, char **argv, char **envp);
119 int main(int argc, char **argv)
121 qemu_main(argc, argv, NULL);
123 #undef main
124 #define main qemu_main
125 #endif
126 #endif /* CONFIG_SDL */
128 #ifdef CONFIG_COCOA
129 #undef main
130 #define main qemu_main
131 #endif /* CONFIG_COCOA */
133 #include "hw/hw.h"
134 #include "hw/boards.h"
135 #include "hw/usb.h"
136 #include "hw/pcmcia.h"
137 #include "hw/pc.h"
138 #include "hw/audiodev.h"
139 #include "hw/isa.h"
140 #include "hw/baum.h"
141 #include "hw/bt.h"
142 #include "hw/watchdog.h"
143 #include "hw/smbios.h"
144 #include "hw/xen.h"
145 #include "bt-host.h"
146 #include "net.h"
147 #include "monitor.h"
148 #include "console.h"
149 #include "sysemu.h"
150 #include "gdbstub.h"
151 #include "qemu-timer.h"
152 #include "qemu-char.h"
153 #include "cache-utils.h"
154 #include "block.h"
155 #include "dma.h"
156 #include "audio/audio.h"
157 #include "migration.h"
158 #include "kvm.h"
159 #include "balloon.h"
160 #include "qemu-kvm.h"
161 #include "hw/device-assignment.h"
163 #include "disas.h"
165 #include "exec-all.h"
167 #include "qemu_socket.h"
169 #if defined(CONFIG_SLIRP)
170 #include "libslirp.h"
171 #endif
173 //#define DEBUG_UNUSED_IOPORT
174 //#define DEBUG_IOPORT
175 //#define DEBUG_NET
176 //#define DEBUG_SLIRP
179 #ifdef DEBUG_IOPORT
180 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
181 #else
182 # define LOG_IOPORT(...) do { } while (0)
183 #endif
185 #define DEFAULT_RAM_SIZE 128
187 /* Max number of USB devices that can be specified on the commandline. */
188 #define MAX_USB_CMDLINE 8
190 /* Max number of bluetooth switches on the commandline. */
191 #define MAX_BT_CMDLINE 10
193 /* XXX: use a two level table to limit memory usage */
194 #define MAX_IOPORTS 65536
196 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
197 const char *bios_name = NULL;
198 static void *ioport_opaque[MAX_IOPORTS];
199 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
200 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
201 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
202 to store the VM snapshots */
203 DriveInfo drives_table[MAX_DRIVES+1];
204 int nb_drives;
205 int extboot_drive = -1;
206 static int vga_ram_size;
207 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
208 static DisplayState *display_state;
209 int nographic;
210 static int curses;
211 static int sdl;
212 const char* keyboard_layout = NULL;
213 int64_t ticks_per_sec;
214 ram_addr_t ram_size;
215 int nb_nics;
216 NICInfo nd_table[MAX_NICS];
217 int vm_running;
218 static int autostart;
219 static int rtc_utc = 1;
220 static int rtc_date_offset = -1; /* -1 means no change */
221 int cirrus_vga_enabled = 1;
222 int std_vga_enabled = 0;
223 int vmsvga_enabled = 0;
224 int xenfb_enabled = 0;
225 #ifdef TARGET_SPARC
226 int graphic_width = 1024;
227 int graphic_height = 768;
228 int graphic_depth = 8;
229 #else
230 int graphic_width = 800;
231 int graphic_height = 600;
232 int graphic_depth = 15;
233 #endif
234 static int full_screen = 0;
235 #ifdef CONFIG_SDL
236 static int no_frame = 0;
237 #endif
238 int no_quit = 0;
239 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
240 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
241 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
242 #ifdef TARGET_I386
243 int win2k_install_hack = 0;
244 int rtc_td_hack = 0;
245 #endif
246 int usb_enabled = 0;
247 int singlestep = 0;
248 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
249 int assigned_devices_index;
250 int smp_cpus = 1;
251 const char *vnc_display;
252 int acpi_enabled = 1;
253 int no_hpet = 0;
254 int fd_bootchk = 1;
255 int no_reboot = 0;
256 int no_shutdown = 0;
257 int cursor_hide = 1;
258 int graphic_rotate = 0;
259 #ifndef _WIN32
260 int daemonize = 0;
261 #endif
262 WatchdogTimerModel *watchdog = NULL;
263 int watchdog_action = WDT_RESET;
264 const char *option_rom[MAX_OPTION_ROMS];
265 int nb_option_roms;
266 int semihosting_enabled = 0;
267 int time_drift_fix = 0;
268 unsigned int kvm_shadow_memory = 0;
269 const char *mem_path = NULL;
270 #ifdef MAP_POPULATE
271 int mem_prealloc = 1; /* force preallocation of physical target memory */
272 #endif
273 long hpagesize = 0;
274 #ifdef TARGET_ARM
275 int old_param = 0;
276 #endif
277 const char *qemu_name;
278 int alt_grab = 0;
279 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
280 unsigned int nb_prom_envs = 0;
281 const char *prom_envs[MAX_PROM_ENVS];
282 #endif
283 int nb_drives_opt;
284 const char *nvram = NULL;
285 struct drive_opt drives_opt[MAX_DRIVES];
287 int nb_numa_nodes;
288 uint64_t node_mem[MAX_NODES];
289 uint64_t node_cpumask[MAX_NODES];
291 static CPUState *cur_cpu;
292 static CPUState *next_cpu;
293 static int timer_alarm_pending = 1;
294 /* Conversion factor from emulated instructions to virtual clock ticks. */
295 static int icount_time_shift;
296 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
297 #define MAX_ICOUNT_SHIFT 10
298 /* Compensate for varying guest execution speed. */
299 static int64_t qemu_icount_bias;
300 static QEMUTimer *icount_rt_timer;
301 static QEMUTimer *icount_vm_timer;
302 static QEMUTimer *nographic_timer;
304 uint8_t qemu_uuid[16];
306 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
307 struct timeval *tv)
309 int ret;
311 /* KVM holds a mutex while QEMU code is running, we need hooks to
312 release the mutex whenever QEMU code sleeps. */
314 kvm_sleep_begin();
316 ret = select(max_fd, rfds, wfds, xfds, tv);
318 kvm_sleep_end();
320 return ret;
324 /***********************************************************/
325 /* x86 ISA bus support */
327 target_phys_addr_t isa_mem_base = 0;
328 PicState2 *isa_pic;
330 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
331 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
333 static uint32_t ioport_read(int index, uint32_t address)
335 static IOPortReadFunc *default_func[3] = {
336 default_ioport_readb,
337 default_ioport_readw,
338 default_ioport_readl
340 IOPortReadFunc *func = ioport_read_table[index][address];
341 if (!func)
342 func = default_func[index];
343 return func(ioport_opaque[address], address);
346 static void ioport_write(int index, uint32_t address, uint32_t data)
348 static IOPortWriteFunc *default_func[3] = {
349 default_ioport_writeb,
350 default_ioport_writew,
351 default_ioport_writel
353 IOPortWriteFunc *func = ioport_write_table[index][address];
354 if (!func)
355 func = default_func[index];
356 func(ioport_opaque[address], address, data);
359 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
361 #ifdef DEBUG_UNUSED_IOPORT
362 fprintf(stderr, "unused inb: port=0x%04x\n", address);
363 #endif
364 return 0xff;
367 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
369 #ifdef DEBUG_UNUSED_IOPORT
370 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
371 #endif
374 /* default is to make two byte accesses */
375 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
377 uint32_t data;
378 data = ioport_read(0, address);
379 address = (address + 1) & (MAX_IOPORTS - 1);
380 data |= ioport_read(0, address) << 8;
381 return data;
384 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
386 ioport_write(0, address, data & 0xff);
387 address = (address + 1) & (MAX_IOPORTS - 1);
388 ioport_write(0, address, (data >> 8) & 0xff);
391 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
393 #ifdef DEBUG_UNUSED_IOPORT
394 fprintf(stderr, "unused inl: port=0x%04x\n", address);
395 #endif
396 return 0xffffffff;
399 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
401 #ifdef DEBUG_UNUSED_IOPORT
402 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
403 #endif
406 /* size is the word size in byte */
407 int register_ioport_read(int start, int length, int size,
408 IOPortReadFunc *func, void *opaque)
410 int i, bsize;
412 if (size == 1) {
413 bsize = 0;
414 } else if (size == 2) {
415 bsize = 1;
416 } else if (size == 4) {
417 bsize = 2;
418 } else {
419 hw_error("register_ioport_read: invalid size");
420 return -1;
422 for(i = start; i < start + length; i += size) {
423 ioport_read_table[bsize][i] = func;
424 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
425 hw_error("register_ioport_read: invalid opaque");
426 ioport_opaque[i] = opaque;
428 return 0;
431 /* size is the word size in byte */
432 int register_ioport_write(int start, int length, int size,
433 IOPortWriteFunc *func, void *opaque)
435 int i, bsize;
437 if (size == 1) {
438 bsize = 0;
439 } else if (size == 2) {
440 bsize = 1;
441 } else if (size == 4) {
442 bsize = 2;
443 } else {
444 hw_error("register_ioport_write: invalid size");
445 return -1;
447 for(i = start; i < start + length; i += size) {
448 ioport_write_table[bsize][i] = func;
449 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
450 hw_error("register_ioport_write: invalid opaque");
451 ioport_opaque[i] = opaque;
453 return 0;
456 void isa_unassign_ioport(int start, int length)
458 int i;
460 for(i = start; i < start + length; i++) {
461 ioport_read_table[0][i] = default_ioport_readb;
462 ioport_read_table[1][i] = default_ioport_readw;
463 ioport_read_table[2][i] = default_ioport_readl;
465 ioport_write_table[0][i] = default_ioport_writeb;
466 ioport_write_table[1][i] = default_ioport_writew;
467 ioport_write_table[2][i] = default_ioport_writel;
469 ioport_opaque[i] = NULL;
473 /***********************************************************/
475 void cpu_outb(CPUState *env, int addr, int val)
477 LOG_IOPORT("outb: %04x %02x\n", addr, val);
478 ioport_write(0, addr, val);
479 #ifdef CONFIG_KQEMU
480 if (env)
481 env->last_io_time = cpu_get_time_fast();
482 #endif
485 void cpu_outw(CPUState *env, int addr, int val)
487 LOG_IOPORT("outw: %04x %04x\n", addr, val);
488 ioport_write(1, addr, val);
489 #ifdef CONFIG_KQEMU
490 if (env)
491 env->last_io_time = cpu_get_time_fast();
492 #endif
495 void cpu_outl(CPUState *env, int addr, int val)
497 LOG_IOPORT("outl: %04x %08x\n", addr, val);
498 ioport_write(2, addr, val);
499 #ifdef CONFIG_KQEMU
500 if (env)
501 env->last_io_time = cpu_get_time_fast();
502 #endif
505 int cpu_inb(CPUState *env, int addr)
507 int val;
508 val = ioport_read(0, addr);
509 LOG_IOPORT("inb : %04x %02x\n", addr, val);
510 #ifdef CONFIG_KQEMU
511 if (env)
512 env->last_io_time = cpu_get_time_fast();
513 #endif
514 return val;
517 int cpu_inw(CPUState *env, int addr)
519 int val;
520 val = ioport_read(1, addr);
521 LOG_IOPORT("inw : %04x %04x\n", addr, val);
522 #ifdef CONFIG_KQEMU
523 if (env)
524 env->last_io_time = cpu_get_time_fast();
525 #endif
526 return val;
529 int cpu_inl(CPUState *env, int addr)
531 int val;
532 val = ioport_read(2, addr);
533 LOG_IOPORT("inl : %04x %08x\n", addr, val);
534 #ifdef CONFIG_KQEMU
535 if (env)
536 env->last_io_time = cpu_get_time_fast();
537 #endif
538 return val;
541 /***********************************************************/
542 void hw_error(const char *fmt, ...)
544 va_list ap;
545 CPUState *env;
547 va_start(ap, fmt);
548 fprintf(stderr, "qemu: hardware error: ");
549 vfprintf(stderr, fmt, ap);
550 fprintf(stderr, "\n");
551 for(env = first_cpu; env != NULL; env = env->next_cpu) {
552 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
553 #ifdef TARGET_I386
554 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
555 #else
556 cpu_dump_state(env, stderr, fprintf, 0);
557 #endif
559 va_end(ap);
560 abort();
563 /***************/
564 /* ballooning */
566 static QEMUBalloonEvent *qemu_balloon_event;
567 void *qemu_balloon_event_opaque;
569 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
571 qemu_balloon_event = func;
572 qemu_balloon_event_opaque = opaque;
575 void qemu_balloon(ram_addr_t target)
577 if (qemu_balloon_event)
578 qemu_balloon_event(qemu_balloon_event_opaque, target);
581 ram_addr_t qemu_balloon_status(void)
583 if (qemu_balloon_event)
584 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
585 return 0;
588 /***********************************************************/
589 /* keyboard/mouse */
591 static QEMUPutKBDEvent *qemu_put_kbd_event;
592 static void *qemu_put_kbd_event_opaque;
593 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
594 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
596 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
598 qemu_put_kbd_event_opaque = opaque;
599 qemu_put_kbd_event = func;
602 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
603 void *opaque, int absolute,
604 const char *name)
606 QEMUPutMouseEntry *s, *cursor;
608 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
610 s->qemu_put_mouse_event = func;
611 s->qemu_put_mouse_event_opaque = opaque;
612 s->qemu_put_mouse_event_absolute = absolute;
613 s->qemu_put_mouse_event_name = qemu_strdup(name);
614 s->next = NULL;
616 if (!qemu_put_mouse_event_head) {
617 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
618 return s;
621 cursor = qemu_put_mouse_event_head;
622 while (cursor->next != NULL)
623 cursor = cursor->next;
625 cursor->next = s;
626 qemu_put_mouse_event_current = s;
628 return s;
631 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
633 QEMUPutMouseEntry *prev = NULL, *cursor;
635 if (!qemu_put_mouse_event_head || entry == NULL)
636 return;
638 cursor = qemu_put_mouse_event_head;
639 while (cursor != NULL && cursor != entry) {
640 prev = cursor;
641 cursor = cursor->next;
644 if (cursor == NULL) // does not exist or list empty
645 return;
646 else if (prev == NULL) { // entry is head
647 qemu_put_mouse_event_head = cursor->next;
648 if (qemu_put_mouse_event_current == entry)
649 qemu_put_mouse_event_current = cursor->next;
650 qemu_free(entry->qemu_put_mouse_event_name);
651 qemu_free(entry);
652 return;
655 prev->next = entry->next;
657 if (qemu_put_mouse_event_current == entry)
658 qemu_put_mouse_event_current = prev;
660 qemu_free(entry->qemu_put_mouse_event_name);
661 qemu_free(entry);
664 void kbd_put_keycode(int keycode)
666 if (qemu_put_kbd_event) {
667 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
671 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
673 QEMUPutMouseEvent *mouse_event;
674 void *mouse_event_opaque;
675 int width;
677 if (!qemu_put_mouse_event_current) {
678 return;
681 mouse_event =
682 qemu_put_mouse_event_current->qemu_put_mouse_event;
683 mouse_event_opaque =
684 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
686 if (mouse_event) {
687 if (graphic_rotate) {
688 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
689 width = 0x7fff;
690 else
691 width = graphic_width - 1;
692 mouse_event(mouse_event_opaque,
693 width - dy, dx, dz, buttons_state);
694 } else
695 mouse_event(mouse_event_opaque,
696 dx, dy, dz, buttons_state);
700 int kbd_mouse_is_absolute(void)
702 if (!qemu_put_mouse_event_current)
703 return 0;
705 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
708 void do_info_mice(Monitor *mon)
710 QEMUPutMouseEntry *cursor;
711 int index = 0;
713 if (!qemu_put_mouse_event_head) {
714 monitor_printf(mon, "No mouse devices connected\n");
715 return;
718 monitor_printf(mon, "Mouse devices available:\n");
719 cursor = qemu_put_mouse_event_head;
720 while (cursor != NULL) {
721 monitor_printf(mon, "%c Mouse #%d: %s\n",
722 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
723 index, cursor->qemu_put_mouse_event_name);
724 index++;
725 cursor = cursor->next;
729 void do_mouse_set(Monitor *mon, int index)
731 QEMUPutMouseEntry *cursor;
732 int i = 0;
734 if (!qemu_put_mouse_event_head) {
735 monitor_printf(mon, "No mouse devices connected\n");
736 return;
739 cursor = qemu_put_mouse_event_head;
740 while (cursor != NULL && index != i) {
741 i++;
742 cursor = cursor->next;
745 if (cursor != NULL)
746 qemu_put_mouse_event_current = cursor;
747 else
748 monitor_printf(mon, "Mouse at given index not found\n");
751 /* compute with 96 bit intermediate result: (a*b)/c */
752 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
754 union {
755 uint64_t ll;
756 struct {
757 #ifdef WORDS_BIGENDIAN
758 uint32_t high, low;
759 #else
760 uint32_t low, high;
761 #endif
762 } l;
763 } u, res;
764 uint64_t rl, rh;
766 u.ll = a;
767 rl = (uint64_t)u.l.low * (uint64_t)b;
768 rh = (uint64_t)u.l.high * (uint64_t)b;
769 rh += (rl >> 32);
770 res.l.high = rh / c;
771 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
772 return res.ll;
775 /***********************************************************/
776 /* real time host monotonic timer */
778 #define QEMU_TIMER_BASE 1000000000LL
780 #ifdef WIN32
782 static int64_t clock_freq;
784 static void init_get_clock(void)
786 LARGE_INTEGER freq;
787 int ret;
788 ret = QueryPerformanceFrequency(&freq);
789 if (ret == 0) {
790 fprintf(stderr, "Could not calibrate ticks\n");
791 exit(1);
793 clock_freq = freq.QuadPart;
796 static int64_t get_clock(void)
798 LARGE_INTEGER ti;
799 QueryPerformanceCounter(&ti);
800 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
803 #else
805 static int use_rt_clock;
807 static void init_get_clock(void)
809 use_rt_clock = 0;
810 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
811 || defined(__DragonFly__)
813 struct timespec ts;
814 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
815 use_rt_clock = 1;
818 #endif
821 static int64_t get_clock(void)
823 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
824 || defined(__DragonFly__)
825 if (use_rt_clock) {
826 struct timespec ts;
827 clock_gettime(CLOCK_MONOTONIC, &ts);
828 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
829 } else
830 #endif
832 /* XXX: using gettimeofday leads to problems if the date
833 changes, so it should be avoided. */
834 struct timeval tv;
835 gettimeofday(&tv, NULL);
836 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
839 #endif
841 /* Return the virtual CPU time, based on the instruction counter. */
842 static int64_t cpu_get_icount(void)
844 int64_t icount;
845 CPUState *env = cpu_single_env;;
846 icount = qemu_icount;
847 if (env) {
848 if (!can_do_io(env))
849 fprintf(stderr, "Bad clock read\n");
850 icount -= (env->icount_decr.u16.low + env->icount_extra);
852 return qemu_icount_bias + (icount << icount_time_shift);
855 /***********************************************************/
856 /* guest cycle counter */
858 static int64_t cpu_ticks_prev;
859 static int64_t cpu_ticks_offset;
860 static int64_t cpu_clock_offset;
861 static int cpu_ticks_enabled;
863 /* return the host CPU cycle counter and handle stop/restart */
864 int64_t cpu_get_ticks(void)
866 if (use_icount) {
867 return cpu_get_icount();
869 if (!cpu_ticks_enabled) {
870 return cpu_ticks_offset;
871 } else {
872 int64_t ticks;
873 ticks = cpu_get_real_ticks();
874 if (cpu_ticks_prev > ticks) {
875 /* Note: non increasing ticks may happen if the host uses
876 software suspend */
877 cpu_ticks_offset += cpu_ticks_prev - ticks;
879 cpu_ticks_prev = ticks;
880 return ticks + cpu_ticks_offset;
884 /* return the host CPU monotonic timer and handle stop/restart */
885 static int64_t cpu_get_clock(void)
887 int64_t ti;
888 if (!cpu_ticks_enabled) {
889 return cpu_clock_offset;
890 } else {
891 ti = get_clock();
892 return ti + cpu_clock_offset;
896 /* enable cpu_get_ticks() */
897 void cpu_enable_ticks(void)
899 if (!cpu_ticks_enabled) {
900 cpu_ticks_offset -= cpu_get_real_ticks();
901 cpu_clock_offset -= get_clock();
902 cpu_ticks_enabled = 1;
906 /* disable cpu_get_ticks() : the clock is stopped. You must not call
907 cpu_get_ticks() after that. */
908 void cpu_disable_ticks(void)
910 if (cpu_ticks_enabled) {
911 cpu_ticks_offset = cpu_get_ticks();
912 cpu_clock_offset = cpu_get_clock();
913 cpu_ticks_enabled = 0;
917 /***********************************************************/
918 /* timers */
920 #define QEMU_TIMER_REALTIME 0
921 #define QEMU_TIMER_VIRTUAL 1
923 struct QEMUClock {
924 int type;
925 /* XXX: add frequency */
928 struct QEMUTimer {
929 QEMUClock *clock;
930 int64_t expire_time;
931 QEMUTimerCB *cb;
932 void *opaque;
933 struct QEMUTimer *next;
936 struct qemu_alarm_timer {
937 char const *name;
938 unsigned int flags;
940 int (*start)(struct qemu_alarm_timer *t);
941 void (*stop)(struct qemu_alarm_timer *t);
942 void (*rearm)(struct qemu_alarm_timer *t);
943 void *priv;
946 #define ALARM_FLAG_DYNTICKS 0x1
947 #define ALARM_FLAG_EXPIRED 0x2
949 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
951 return t->flags & ALARM_FLAG_DYNTICKS;
954 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
956 if (!alarm_has_dynticks(t))
957 return;
959 t->rearm(t);
962 /* TODO: MIN_TIMER_REARM_US should be optimized */
963 #define MIN_TIMER_REARM_US 250
965 static struct qemu_alarm_timer *alarm_timer;
967 #ifdef _WIN32
969 struct qemu_alarm_win32 {
970 MMRESULT timerId;
971 unsigned int period;
972 } alarm_win32_data = {0, -1};
974 static int win32_start_timer(struct qemu_alarm_timer *t);
975 static void win32_stop_timer(struct qemu_alarm_timer *t);
976 static void win32_rearm_timer(struct qemu_alarm_timer *t);
978 #else
980 static int unix_start_timer(struct qemu_alarm_timer *t);
981 static void unix_stop_timer(struct qemu_alarm_timer *t);
983 #ifdef __linux__
985 static int dynticks_start_timer(struct qemu_alarm_timer *t);
986 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
987 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
989 static int hpet_start_timer(struct qemu_alarm_timer *t);
990 static void hpet_stop_timer(struct qemu_alarm_timer *t);
992 static int rtc_start_timer(struct qemu_alarm_timer *t);
993 static void rtc_stop_timer(struct qemu_alarm_timer *t);
995 #endif /* __linux__ */
997 #endif /* _WIN32 */
999 /* Correlation between real and virtual time is always going to be
1000 fairly approximate, so ignore small variation.
1001 When the guest is idle real and virtual time will be aligned in
1002 the IO wait loop. */
1003 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
1005 static void icount_adjust(void)
1007 int64_t cur_time;
1008 int64_t cur_icount;
1009 int64_t delta;
1010 static int64_t last_delta;
1011 /* If the VM is not running, then do nothing. */
1012 if (!vm_running)
1013 return;
1015 cur_time = cpu_get_clock();
1016 cur_icount = qemu_get_clock(vm_clock);
1017 delta = cur_icount - cur_time;
1018 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1019 if (delta > 0
1020 && last_delta + ICOUNT_WOBBLE < delta * 2
1021 && icount_time_shift > 0) {
1022 /* The guest is getting too far ahead. Slow time down. */
1023 icount_time_shift--;
1025 if (delta < 0
1026 && last_delta - ICOUNT_WOBBLE > delta * 2
1027 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1028 /* The guest is getting too far behind. Speed time up. */
1029 icount_time_shift++;
1031 last_delta = delta;
1032 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1035 static void icount_adjust_rt(void * opaque)
1037 qemu_mod_timer(icount_rt_timer,
1038 qemu_get_clock(rt_clock) + 1000);
1039 icount_adjust();
1042 static void icount_adjust_vm(void * opaque)
1044 qemu_mod_timer(icount_vm_timer,
1045 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1046 icount_adjust();
1049 static void init_icount_adjust(void)
1051 /* Have both realtime and virtual time triggers for speed adjustment.
1052 The realtime trigger catches emulated time passing too slowly,
1053 the virtual time trigger catches emulated time passing too fast.
1054 Realtime triggers occur even when idle, so use them less frequently
1055 than VM triggers. */
1056 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1057 qemu_mod_timer(icount_rt_timer,
1058 qemu_get_clock(rt_clock) + 1000);
1059 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1060 qemu_mod_timer(icount_vm_timer,
1061 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1064 static struct qemu_alarm_timer alarm_timers[] = {
1065 #ifndef _WIN32
1066 #ifdef __linux__
1067 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1068 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1069 /* HPET - if available - is preferred */
1070 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1071 /* ...otherwise try RTC */
1072 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1073 #endif
1074 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1075 #else
1076 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1077 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1078 {"win32", 0, win32_start_timer,
1079 win32_stop_timer, NULL, &alarm_win32_data},
1080 #endif
1081 {NULL, }
1084 static void show_available_alarms(void)
1086 int i;
1088 printf("Available alarm timers, in order of precedence:\n");
1089 for (i = 0; alarm_timers[i].name; i++)
1090 printf("%s\n", alarm_timers[i].name);
1093 static void configure_alarms(char const *opt)
1095 int i;
1096 int cur = 0;
1097 int count = ARRAY_SIZE(alarm_timers) - 1;
1098 char *arg;
1099 char *name;
1100 struct qemu_alarm_timer tmp;
1102 if (!strcmp(opt, "?")) {
1103 show_available_alarms();
1104 exit(0);
1107 arg = strdup(opt);
1109 /* Reorder the array */
1110 name = strtok(arg, ",");
1111 while (name) {
1112 for (i = 0; i < count && alarm_timers[i].name; i++) {
1113 if (!strcmp(alarm_timers[i].name, name))
1114 break;
1117 if (i == count) {
1118 fprintf(stderr, "Unknown clock %s\n", name);
1119 goto next;
1122 if (i < cur)
1123 /* Ignore */
1124 goto next;
1126 /* Swap */
1127 tmp = alarm_timers[i];
1128 alarm_timers[i] = alarm_timers[cur];
1129 alarm_timers[cur] = tmp;
1131 cur++;
1132 next:
1133 name = strtok(NULL, ",");
1136 free(arg);
1138 if (cur) {
1139 /* Disable remaining timers */
1140 for (i = cur; i < count; i++)
1141 alarm_timers[i].name = NULL;
1142 } else {
1143 show_available_alarms();
1144 exit(1);
1148 QEMUClock *rt_clock;
1149 QEMUClock *vm_clock;
1151 static QEMUTimer *active_timers[2];
1153 static QEMUClock *qemu_new_clock(int type)
1155 QEMUClock *clock;
1156 clock = qemu_mallocz(sizeof(QEMUClock));
1157 clock->type = type;
1158 return clock;
1161 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1163 QEMUTimer *ts;
1165 ts = qemu_mallocz(sizeof(QEMUTimer));
1166 ts->clock = clock;
1167 ts->cb = cb;
1168 ts->opaque = opaque;
1169 return ts;
1172 void qemu_free_timer(QEMUTimer *ts)
1174 qemu_free(ts);
1177 /* stop a timer, but do not dealloc it */
1178 void qemu_del_timer(QEMUTimer *ts)
1180 QEMUTimer **pt, *t;
1182 /* NOTE: this code must be signal safe because
1183 qemu_timer_expired() can be called from a signal. */
1184 pt = &active_timers[ts->clock->type];
1185 for(;;) {
1186 t = *pt;
1187 if (!t)
1188 break;
1189 if (t == ts) {
1190 *pt = t->next;
1191 break;
1193 pt = &t->next;
1197 /* modify the current timer so that it will be fired when current_time
1198 >= expire_time. The corresponding callback will be called. */
1199 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1201 QEMUTimer **pt, *t;
1203 qemu_del_timer(ts);
1205 /* add the timer in the sorted list */
1206 /* NOTE: this code must be signal safe because
1207 qemu_timer_expired() can be called from a signal. */
1208 pt = &active_timers[ts->clock->type];
1209 for(;;) {
1210 t = *pt;
1211 if (!t)
1212 break;
1213 if (t->expire_time > expire_time)
1214 break;
1215 pt = &t->next;
1217 ts->expire_time = expire_time;
1218 ts->next = *pt;
1219 *pt = ts;
1221 /* Rearm if necessary */
1222 if (pt == &active_timers[ts->clock->type]) {
1223 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1224 qemu_rearm_alarm_timer(alarm_timer);
1226 /* Interrupt execution to force deadline recalculation. */
1227 if (use_icount)
1228 qemu_notify_event();
1232 int qemu_timer_pending(QEMUTimer *ts)
1234 QEMUTimer *t;
1235 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1236 if (t == ts)
1237 return 1;
1239 return 0;
1242 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1244 if (!timer_head)
1245 return 0;
1246 return (timer_head->expire_time <= current_time);
1249 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1251 QEMUTimer *ts;
1253 for(;;) {
1254 ts = *ptimer_head;
1255 if (!ts || ts->expire_time > current_time)
1256 break;
1257 /* remove timer from the list before calling the callback */
1258 *ptimer_head = ts->next;
1259 ts->next = NULL;
1261 /* run the callback (the timer list can be modified) */
1262 ts->cb(ts->opaque);
1266 int64_t qemu_get_clock(QEMUClock *clock)
1268 switch(clock->type) {
1269 case QEMU_TIMER_REALTIME:
1270 return get_clock() / 1000000;
1271 default:
1272 case QEMU_TIMER_VIRTUAL:
1273 if (use_icount) {
1274 return cpu_get_icount();
1275 } else {
1276 return cpu_get_clock();
1281 static void init_timers(void)
1283 init_get_clock();
1284 ticks_per_sec = QEMU_TIMER_BASE;
1285 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1286 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1289 /* save a timer */
1290 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1292 uint64_t expire_time;
1294 if (qemu_timer_pending(ts)) {
1295 expire_time = ts->expire_time;
1296 } else {
1297 expire_time = -1;
1299 qemu_put_be64(f, expire_time);
1302 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1304 uint64_t expire_time;
1306 expire_time = qemu_get_be64(f);
1307 if (expire_time != -1) {
1308 qemu_mod_timer(ts, expire_time);
1309 } else {
1310 qemu_del_timer(ts);
1314 static void timer_save(QEMUFile *f, void *opaque)
1316 if (cpu_ticks_enabled) {
1317 hw_error("cannot save state if virtual timers are running");
1319 qemu_put_be64(f, cpu_ticks_offset);
1320 qemu_put_be64(f, ticks_per_sec);
1321 qemu_put_be64(f, cpu_clock_offset);
1324 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1326 if (version_id != 1 && version_id != 2)
1327 return -EINVAL;
1328 if (cpu_ticks_enabled) {
1329 return -EINVAL;
1331 cpu_ticks_offset=qemu_get_be64(f);
1332 ticks_per_sec=qemu_get_be64(f);
1333 if (version_id == 2) {
1334 cpu_clock_offset=qemu_get_be64(f);
1336 return 0;
1339 static void qemu_event_increment(void);
1341 #ifdef _WIN32
1342 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1343 DWORD_PTR dwUser, DWORD_PTR dw1,
1344 DWORD_PTR dw2)
1345 #else
1346 static void host_alarm_handler(int host_signum)
1347 #endif
1349 #if 0
1350 #define DISP_FREQ 1000
1352 static int64_t delta_min = INT64_MAX;
1353 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1354 static int count;
1355 ti = qemu_get_clock(vm_clock);
1356 if (last_clock != 0) {
1357 delta = ti - last_clock;
1358 if (delta < delta_min)
1359 delta_min = delta;
1360 if (delta > delta_max)
1361 delta_max = delta;
1362 delta_cum += delta;
1363 if (++count == DISP_FREQ) {
1364 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1365 muldiv64(delta_min, 1000000, ticks_per_sec),
1366 muldiv64(delta_max, 1000000, ticks_per_sec),
1367 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1368 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1369 count = 0;
1370 delta_min = INT64_MAX;
1371 delta_max = 0;
1372 delta_cum = 0;
1375 last_clock = ti;
1377 #endif
1378 if (alarm_has_dynticks(alarm_timer) ||
1379 (!use_icount &&
1380 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1381 qemu_get_clock(vm_clock))) ||
1382 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1383 qemu_get_clock(rt_clock))) {
1384 qemu_event_increment();
1385 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1387 #ifndef CONFIG_IOTHREAD
1388 if (next_cpu) {
1389 /* stop the currently executing cpu because a timer occured */
1390 cpu_exit(next_cpu);
1391 #ifdef CONFIG_KQEMU
1392 if (next_cpu->kqemu_enabled) {
1393 kqemu_cpu_interrupt(next_cpu);
1395 #endif
1397 #endif
1398 timer_alarm_pending = 1;
1399 qemu_notify_event();
1403 static int64_t qemu_next_deadline(void)
1405 int64_t delta;
1407 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1408 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1409 qemu_get_clock(vm_clock);
1410 } else {
1411 /* To avoid problems with overflow limit this to 2^32. */
1412 delta = INT32_MAX;
1415 if (delta < 0)
1416 delta = 0;
1418 return delta;
1421 #if defined(__linux__) || defined(_WIN32)
1422 static uint64_t qemu_next_deadline_dyntick(void)
1424 int64_t delta;
1425 int64_t rtdelta;
1427 if (use_icount)
1428 delta = INT32_MAX;
1429 else
1430 delta = (qemu_next_deadline() + 999) / 1000;
1432 if (active_timers[QEMU_TIMER_REALTIME]) {
1433 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1434 qemu_get_clock(rt_clock))*1000;
1435 if (rtdelta < delta)
1436 delta = rtdelta;
1439 if (delta < MIN_TIMER_REARM_US)
1440 delta = MIN_TIMER_REARM_US;
1442 return delta;
1444 #endif
1446 #ifndef _WIN32
1448 /* Sets a specific flag */
1449 static int fcntl_setfl(int fd, int flag)
1451 int flags;
1453 flags = fcntl(fd, F_GETFL);
1454 if (flags == -1)
1455 return -errno;
1457 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1458 return -errno;
1460 return 0;
1463 #if defined(__linux__)
1465 #define RTC_FREQ 1024
1467 static void enable_sigio_timer(int fd)
1469 struct sigaction act;
1471 /* timer signal */
1472 sigfillset(&act.sa_mask);
1473 act.sa_flags = 0;
1474 act.sa_handler = host_alarm_handler;
1476 sigaction(SIGIO, &act, NULL);
1477 fcntl_setfl(fd, O_ASYNC);
1478 fcntl(fd, F_SETOWN, getpid());
1481 static int hpet_start_timer(struct qemu_alarm_timer *t)
1483 struct hpet_info info;
1484 int r, fd;
1486 fd = open("/dev/hpet", O_RDONLY);
1487 if (fd < 0)
1488 return -1;
1490 /* Set frequency */
1491 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1492 if (r < 0) {
1493 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1494 "error, but for better emulation accuracy type:\n"
1495 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1496 goto fail;
1499 /* Check capabilities */
1500 r = ioctl(fd, HPET_INFO, &info);
1501 if (r < 0)
1502 goto fail;
1504 /* Enable periodic mode */
1505 r = ioctl(fd, HPET_EPI, 0);
1506 if (info.hi_flags && (r < 0))
1507 goto fail;
1509 /* Enable interrupt */
1510 r = ioctl(fd, HPET_IE_ON, 0);
1511 if (r < 0)
1512 goto fail;
1514 enable_sigio_timer(fd);
1515 t->priv = (void *)(long)fd;
1517 return 0;
1518 fail:
1519 close(fd);
1520 return -1;
1523 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1525 int fd = (long)t->priv;
1527 close(fd);
1530 static int rtc_start_timer(struct qemu_alarm_timer *t)
1532 int rtc_fd;
1533 unsigned long current_rtc_freq = 0;
1535 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1536 if (rtc_fd < 0)
1537 return -1;
1538 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1539 if (current_rtc_freq != RTC_FREQ &&
1540 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1541 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1542 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1543 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1544 goto fail;
1546 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1547 fail:
1548 close(rtc_fd);
1549 return -1;
1552 enable_sigio_timer(rtc_fd);
1554 t->priv = (void *)(long)rtc_fd;
1556 return 0;
1559 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1561 int rtc_fd = (long)t->priv;
1563 close(rtc_fd);
1566 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1568 struct sigevent ev;
1569 timer_t host_timer;
1570 struct sigaction act;
1572 sigfillset(&act.sa_mask);
1573 act.sa_flags = 0;
1574 act.sa_handler = host_alarm_handler;
1576 sigaction(SIGALRM, &act, NULL);
1578 ev.sigev_value.sival_int = 0;
1579 ev.sigev_notify = SIGEV_SIGNAL;
1580 ev.sigev_signo = SIGALRM;
1582 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1583 perror("timer_create");
1585 /* disable dynticks */
1586 fprintf(stderr, "Dynamic Ticks disabled\n");
1588 return -1;
1591 t->priv = (void *)(long)host_timer;
1593 return 0;
1596 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1598 timer_t host_timer = (timer_t)(long)t->priv;
1600 timer_delete(host_timer);
1603 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1605 timer_t host_timer = (timer_t)(long)t->priv;
1606 struct itimerspec timeout;
1607 int64_t nearest_delta_us = INT64_MAX;
1608 int64_t current_us;
1610 if (!active_timers[QEMU_TIMER_REALTIME] &&
1611 !active_timers[QEMU_TIMER_VIRTUAL])
1612 return;
1614 nearest_delta_us = qemu_next_deadline_dyntick();
1616 /* check whether a timer is already running */
1617 if (timer_gettime(host_timer, &timeout)) {
1618 perror("gettime");
1619 fprintf(stderr, "Internal timer error: aborting\n");
1620 exit(1);
1622 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1623 if (current_us && current_us <= nearest_delta_us)
1624 return;
1626 timeout.it_interval.tv_sec = 0;
1627 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1628 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1629 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1630 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1631 perror("settime");
1632 fprintf(stderr, "Internal timer error: aborting\n");
1633 exit(1);
1637 #endif /* defined(__linux__) */
1639 static int unix_start_timer(struct qemu_alarm_timer *t)
1641 struct sigaction act;
1642 struct itimerval itv;
1643 int err;
1645 /* timer signal */
1646 sigfillset(&act.sa_mask);
1647 act.sa_flags = 0;
1648 act.sa_handler = host_alarm_handler;
1650 sigaction(SIGALRM, &act, NULL);
1652 itv.it_interval.tv_sec = 0;
1653 /* for i386 kernel 2.6 to get 1 ms */
1654 itv.it_interval.tv_usec = 999;
1655 itv.it_value.tv_sec = 0;
1656 itv.it_value.tv_usec = 10 * 1000;
1658 err = setitimer(ITIMER_REAL, &itv, NULL);
1659 if (err)
1660 return -1;
1662 return 0;
1665 static void unix_stop_timer(struct qemu_alarm_timer *t)
1667 struct itimerval itv;
1669 memset(&itv, 0, sizeof(itv));
1670 setitimer(ITIMER_REAL, &itv, NULL);
1673 #endif /* !defined(_WIN32) */
1676 #ifdef _WIN32
1678 static int win32_start_timer(struct qemu_alarm_timer *t)
1680 TIMECAPS tc;
1681 struct qemu_alarm_win32 *data = t->priv;
1682 UINT flags;
1684 memset(&tc, 0, sizeof(tc));
1685 timeGetDevCaps(&tc, sizeof(tc));
1687 if (data->period < tc.wPeriodMin)
1688 data->period = tc.wPeriodMin;
1690 timeBeginPeriod(data->period);
1692 flags = TIME_CALLBACK_FUNCTION;
1693 if (alarm_has_dynticks(t))
1694 flags |= TIME_ONESHOT;
1695 else
1696 flags |= TIME_PERIODIC;
1698 data->timerId = timeSetEvent(1, // interval (ms)
1699 data->period, // resolution
1700 host_alarm_handler, // function
1701 (DWORD)t, // parameter
1702 flags);
1704 if (!data->timerId) {
1705 perror("Failed to initialize win32 alarm timer");
1706 timeEndPeriod(data->period);
1707 return -1;
1710 return 0;
1713 static void win32_stop_timer(struct qemu_alarm_timer *t)
1715 struct qemu_alarm_win32 *data = t->priv;
1717 timeKillEvent(data->timerId);
1718 timeEndPeriod(data->period);
1721 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1723 struct qemu_alarm_win32 *data = t->priv;
1724 uint64_t nearest_delta_us;
1726 if (!active_timers[QEMU_TIMER_REALTIME] &&
1727 !active_timers[QEMU_TIMER_VIRTUAL])
1728 return;
1730 nearest_delta_us = qemu_next_deadline_dyntick();
1731 nearest_delta_us /= 1000;
1733 timeKillEvent(data->timerId);
1735 data->timerId = timeSetEvent(1,
1736 data->period,
1737 host_alarm_handler,
1738 (DWORD)t,
1739 TIME_ONESHOT | TIME_PERIODIC);
1741 if (!data->timerId) {
1742 perror("Failed to re-arm win32 alarm timer");
1744 timeEndPeriod(data->period);
1745 exit(1);
1749 #endif /* _WIN32 */
1751 static int init_timer_alarm(void)
1753 struct qemu_alarm_timer *t = NULL;
1754 int i, err = -1;
1756 for (i = 0; alarm_timers[i].name; i++) {
1757 t = &alarm_timers[i];
1759 err = t->start(t);
1760 if (!err)
1761 break;
1764 if (err) {
1765 err = -ENOENT;
1766 goto fail;
1769 alarm_timer = t;
1771 return 0;
1773 fail:
1774 return err;
1777 static void quit_timers(void)
1779 alarm_timer->stop(alarm_timer);
1780 alarm_timer = NULL;
1783 /***********************************************************/
1784 /* host time/date access */
1785 void qemu_get_timedate(struct tm *tm, int offset)
1787 time_t ti;
1788 struct tm *ret;
1790 time(&ti);
1791 ti += offset;
1792 if (rtc_date_offset == -1) {
1793 if (rtc_utc)
1794 ret = gmtime(&ti);
1795 else
1796 ret = localtime(&ti);
1797 } else {
1798 ti -= rtc_date_offset;
1799 ret = gmtime(&ti);
1802 memcpy(tm, ret, sizeof(struct tm));
1805 int qemu_timedate_diff(struct tm *tm)
1807 time_t seconds;
1809 if (rtc_date_offset == -1)
1810 if (rtc_utc)
1811 seconds = mktimegm(tm);
1812 else
1813 seconds = mktime(tm);
1814 else
1815 seconds = mktimegm(tm) + rtc_date_offset;
1817 return seconds - time(NULL);
1820 #ifdef _WIN32
1821 static void socket_cleanup(void)
1823 WSACleanup();
1826 static int socket_init(void)
1828 WSADATA Data;
1829 int ret, err;
1831 ret = WSAStartup(MAKEWORD(2,2), &Data);
1832 if (ret != 0) {
1833 err = WSAGetLastError();
1834 fprintf(stderr, "WSAStartup: %d\n", err);
1835 return -1;
1837 atexit(socket_cleanup);
1838 return 0;
1840 #endif
1842 const char *get_opt_name(char *buf, int buf_size, const char *p, char delim)
1844 char *q;
1846 q = buf;
1847 while (*p != '\0' && *p != delim) {
1848 if (q && (q - buf) < buf_size - 1)
1849 *q++ = *p;
1850 p++;
1852 if (q)
1853 *q = '\0';
1855 return p;
1858 const char *get_opt_value(char *buf, int buf_size, const char *p)
1860 char *q;
1862 q = buf;
1863 while (*p != '\0') {
1864 if (*p == ',') {
1865 if (*(p + 1) != ',')
1866 break;
1867 p++;
1869 if (q && (q - buf) < buf_size - 1)
1870 *q++ = *p;
1871 p++;
1873 if (q)
1874 *q = '\0';
1876 return p;
1879 int get_param_value(char *buf, int buf_size,
1880 const char *tag, const char *str)
1882 const char *p;
1883 char option[128];
1885 p = str;
1886 for(;;) {
1887 p = get_opt_name(option, sizeof(option), p, '=');
1888 if (*p != '=')
1889 break;
1890 p++;
1891 if (!strcmp(tag, option)) {
1892 (void)get_opt_value(buf, buf_size, p);
1893 return strlen(buf);
1894 } else {
1895 p = get_opt_value(NULL, 0, p);
1897 if (*p != ',')
1898 break;
1899 p++;
1901 return 0;
1904 int check_params(const char * const *params, const char *str)
1906 int name_buf_size = 1;
1907 const char *p;
1908 char *name_buf;
1909 int i, len;
1910 int ret = 0;
1912 for (i = 0; params[i] != NULL; i++) {
1913 len = strlen(params[i]) + 1;
1914 if (len > name_buf_size) {
1915 name_buf_size = len;
1918 name_buf = qemu_malloc(name_buf_size);
1920 p = str;
1921 while (*p != '\0') {
1922 p = get_opt_name(name_buf, name_buf_size, p, '=');
1923 if (*p != '=') {
1924 ret = -1;
1925 break;
1927 p++;
1928 for(i = 0; params[i] != NULL; i++)
1929 if (!strcmp(params[i], name_buf))
1930 break;
1931 if (params[i] == NULL) {
1932 ret = -1;
1933 break;
1935 p = get_opt_value(NULL, 0, p);
1936 if (*p != ',')
1937 break;
1938 p++;
1941 qemu_free(name_buf);
1942 return ret;
1945 /***********************************************************/
1946 /* Bluetooth support */
1947 static int nb_hcis;
1948 static int cur_hci;
1949 static struct HCIInfo *hci_table[MAX_NICS];
1951 static struct bt_vlan_s {
1952 struct bt_scatternet_s net;
1953 int id;
1954 struct bt_vlan_s *next;
1955 } *first_bt_vlan;
1957 /* find or alloc a new bluetooth "VLAN" */
1958 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1960 struct bt_vlan_s **pvlan, *vlan;
1961 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1962 if (vlan->id == id)
1963 return &vlan->net;
1965 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1966 vlan->id = id;
1967 pvlan = &first_bt_vlan;
1968 while (*pvlan != NULL)
1969 pvlan = &(*pvlan)->next;
1970 *pvlan = vlan;
1971 return &vlan->net;
1974 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1978 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1980 return -ENOTSUP;
1983 static struct HCIInfo null_hci = {
1984 .cmd_send = null_hci_send,
1985 .sco_send = null_hci_send,
1986 .acl_send = null_hci_send,
1987 .bdaddr_set = null_hci_addr_set,
1990 struct HCIInfo *qemu_next_hci(void)
1992 if (cur_hci == nb_hcis)
1993 return &null_hci;
1995 return hci_table[cur_hci++];
1998 static struct HCIInfo *hci_init(const char *str)
2000 char *endp;
2001 struct bt_scatternet_s *vlan = 0;
2003 if (!strcmp(str, "null"))
2004 /* null */
2005 return &null_hci;
2006 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2007 /* host[:hciN] */
2008 return bt_host_hci(str[4] ? str + 5 : "hci0");
2009 else if (!strncmp(str, "hci", 3)) {
2010 /* hci[,vlan=n] */
2011 if (str[3]) {
2012 if (!strncmp(str + 3, ",vlan=", 6)) {
2013 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2014 if (*endp)
2015 vlan = 0;
2017 } else
2018 vlan = qemu_find_bt_vlan(0);
2019 if (vlan)
2020 return bt_new_hci(vlan);
2023 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2025 return 0;
2028 static int bt_hci_parse(const char *str)
2030 struct HCIInfo *hci;
2031 bdaddr_t bdaddr;
2033 if (nb_hcis >= MAX_NICS) {
2034 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2035 return -1;
2038 hci = hci_init(str);
2039 if (!hci)
2040 return -1;
2042 bdaddr.b[0] = 0x52;
2043 bdaddr.b[1] = 0x54;
2044 bdaddr.b[2] = 0x00;
2045 bdaddr.b[3] = 0x12;
2046 bdaddr.b[4] = 0x34;
2047 bdaddr.b[5] = 0x56 + nb_hcis;
2048 hci->bdaddr_set(hci, bdaddr.b);
2050 hci_table[nb_hcis++] = hci;
2052 return 0;
2055 static void bt_vhci_add(int vlan_id)
2057 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2059 if (!vlan->slave)
2060 fprintf(stderr, "qemu: warning: adding a VHCI to "
2061 "an empty scatternet %i\n", vlan_id);
2063 bt_vhci_init(bt_new_hci(vlan));
2066 static struct bt_device_s *bt_device_add(const char *opt)
2068 struct bt_scatternet_s *vlan;
2069 int vlan_id = 0;
2070 char *endp = strstr(opt, ",vlan=");
2071 int len = (endp ? endp - opt : strlen(opt)) + 1;
2072 char devname[10];
2074 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2076 if (endp) {
2077 vlan_id = strtol(endp + 6, &endp, 0);
2078 if (*endp) {
2079 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2080 return 0;
2084 vlan = qemu_find_bt_vlan(vlan_id);
2086 if (!vlan->slave)
2087 fprintf(stderr, "qemu: warning: adding a slave device to "
2088 "an empty scatternet %i\n", vlan_id);
2090 if (!strcmp(devname, "keyboard"))
2091 return bt_keyboard_init(vlan);
2093 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2094 return 0;
2097 static int bt_parse(const char *opt)
2099 const char *endp, *p;
2100 int vlan;
2102 if (strstart(opt, "hci", &endp)) {
2103 if (!*endp || *endp == ',') {
2104 if (*endp)
2105 if (!strstart(endp, ",vlan=", 0))
2106 opt = endp + 1;
2108 return bt_hci_parse(opt);
2110 } else if (strstart(opt, "vhci", &endp)) {
2111 if (!*endp || *endp == ',') {
2112 if (*endp) {
2113 if (strstart(endp, ",vlan=", &p)) {
2114 vlan = strtol(p, (char **) &endp, 0);
2115 if (*endp) {
2116 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2117 return 1;
2119 } else {
2120 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2121 return 1;
2123 } else
2124 vlan = 0;
2126 bt_vhci_add(vlan);
2127 return 0;
2129 } else if (strstart(opt, "device:", &endp))
2130 return !bt_device_add(endp);
2132 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2133 return 1;
2136 /***********************************************************/
2137 /* QEMU Block devices */
2139 #define HD_ALIAS "index=%d,media=disk"
2140 #define CDROM_ALIAS "index=2,media=cdrom"
2141 #define FD_ALIAS "index=%d,if=floppy"
2142 #define PFLASH_ALIAS "if=pflash"
2143 #define MTD_ALIAS "if=mtd"
2144 #define SD_ALIAS "index=0,if=sd"
2146 static int drive_opt_get_free_idx(void)
2148 int index;
2150 for (index = 0; index < MAX_DRIVES; index++)
2151 if (!drives_opt[index].used) {
2152 drives_opt[index].used = 1;
2153 return index;
2156 return -1;
2159 static int drive_get_free_idx(void)
2161 int index;
2163 for (index = 0; index < MAX_DRIVES; index++)
2164 if (!drives_table[index].used) {
2165 drives_table[index].used = 1;
2166 return index;
2169 return -1;
2172 int drive_add(const char *file, const char *fmt, ...)
2174 va_list ap;
2175 int index = drive_opt_get_free_idx();
2177 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2178 fprintf(stderr, "qemu: too many drives\n");
2179 return -1;
2182 drives_opt[index].file = file;
2183 va_start(ap, fmt);
2184 vsnprintf(drives_opt[index].opt,
2185 sizeof(drives_opt[0].opt), fmt, ap);
2186 va_end(ap);
2188 nb_drives_opt++;
2189 return index;
2192 void drive_remove(int index)
2194 drives_opt[index].used = 0;
2195 nb_drives_opt--;
2198 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2200 int index;
2202 /* seek interface, bus and unit */
2204 for (index = 0; index < MAX_DRIVES; index++)
2205 if (drives_table[index].type == type &&
2206 drives_table[index].bus == bus &&
2207 drives_table[index].unit == unit &&
2208 drives_table[index].used)
2209 return index;
2211 return -1;
2214 int drive_get_max_bus(BlockInterfaceType type)
2216 int max_bus;
2217 int index;
2219 max_bus = -1;
2220 for (index = 0; index < nb_drives; index++) {
2221 if(drives_table[index].type == type &&
2222 drives_table[index].bus > max_bus)
2223 max_bus = drives_table[index].bus;
2225 return max_bus;
2228 const char *drive_get_serial(BlockDriverState *bdrv)
2230 int index;
2232 for (index = 0; index < nb_drives; index++)
2233 if (drives_table[index].bdrv == bdrv)
2234 return drives_table[index].serial;
2236 return "\0";
2239 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2241 int index;
2243 for (index = 0; index < nb_drives; index++)
2244 if (drives_table[index].bdrv == bdrv)
2245 return drives_table[index].onerror;
2247 return BLOCK_ERR_STOP_ENOSPC;
2250 static void bdrv_format_print(void *opaque, const char *name)
2252 fprintf(stderr, " %s", name);
2255 void drive_uninit(BlockDriverState *bdrv)
2257 int i;
2259 for (i = 0; i < MAX_DRIVES; i++)
2260 if (drives_table[i].bdrv == bdrv) {
2261 drives_table[i].bdrv = NULL;
2262 drives_table[i].used = 0;
2263 drive_remove(drives_table[i].drive_opt_idx);
2264 nb_drives--;
2265 break;
2269 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2271 char buf[128];
2272 char file[1024];
2273 char devname[128];
2274 char serial[21];
2275 const char *mediastr = "";
2276 BlockInterfaceType type;
2277 enum { MEDIA_DISK, MEDIA_CDROM } media;
2278 int bus_id, unit_id;
2279 int cyls, heads, secs, translation;
2280 BlockDriverState *bdrv;
2281 BlockDriver *drv = NULL;
2282 QEMUMachine *machine = opaque;
2283 int max_devs;
2284 int index;
2285 int cache;
2286 int bdrv_flags, onerror;
2287 int drives_table_idx;
2288 char *str = arg->opt;
2289 static const char * const params[] = { "bus", "unit", "if", "index",
2290 "cyls", "heads", "secs", "trans",
2291 "media", "snapshot", "file",
2292 "cache", "format", "serial", "werror",
2293 "boot", NULL };
2295 if (check_params(params, str) < 0) {
2296 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2297 buf, str);
2298 return -1;
2301 file[0] = 0;
2302 cyls = heads = secs = 0;
2303 bus_id = 0;
2304 unit_id = -1;
2305 translation = BIOS_ATA_TRANSLATION_AUTO;
2306 index = -1;
2307 cache = 3;
2309 if (machine->use_scsi) {
2310 type = IF_SCSI;
2311 max_devs = MAX_SCSI_DEVS;
2312 pstrcpy(devname, sizeof(devname), "scsi");
2313 } else {
2314 type = IF_IDE;
2315 max_devs = MAX_IDE_DEVS;
2316 pstrcpy(devname, sizeof(devname), "ide");
2318 media = MEDIA_DISK;
2320 /* extract parameters */
2322 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2323 bus_id = strtol(buf, NULL, 0);
2324 if (bus_id < 0) {
2325 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2326 return -1;
2330 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2331 unit_id = strtol(buf, NULL, 0);
2332 if (unit_id < 0) {
2333 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2334 return -1;
2338 if (get_param_value(buf, sizeof(buf), "if", str)) {
2339 pstrcpy(devname, sizeof(devname), buf);
2340 if (!strcmp(buf, "ide")) {
2341 type = IF_IDE;
2342 max_devs = MAX_IDE_DEVS;
2343 } else if (!strcmp(buf, "scsi")) {
2344 type = IF_SCSI;
2345 max_devs = MAX_SCSI_DEVS;
2346 } else if (!strcmp(buf, "floppy")) {
2347 type = IF_FLOPPY;
2348 max_devs = 0;
2349 } else if (!strcmp(buf, "pflash")) {
2350 type = IF_PFLASH;
2351 max_devs = 0;
2352 } else if (!strcmp(buf, "mtd")) {
2353 type = IF_MTD;
2354 max_devs = 0;
2355 } else if (!strcmp(buf, "sd")) {
2356 type = IF_SD;
2357 max_devs = 0;
2358 } else if (!strcmp(buf, "virtio")) {
2359 type = IF_VIRTIO;
2360 max_devs = 0;
2361 } else if (!strcmp(buf, "xen")) {
2362 type = IF_XEN;
2363 max_devs = 0;
2364 } else {
2365 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2366 return -1;
2370 if (get_param_value(buf, sizeof(buf), "index", str)) {
2371 index = strtol(buf, NULL, 0);
2372 if (index < 0) {
2373 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2374 return -1;
2378 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2379 cyls = strtol(buf, NULL, 0);
2382 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2383 heads = strtol(buf, NULL, 0);
2386 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2387 secs = strtol(buf, NULL, 0);
2390 if (cyls || heads || secs) {
2391 if (cyls < 1 || cyls > 16383) {
2392 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2393 return -1;
2395 if (heads < 1 || heads > 16) {
2396 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2397 return -1;
2399 if (secs < 1 || secs > 63) {
2400 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2401 return -1;
2405 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2406 if (!cyls) {
2407 fprintf(stderr,
2408 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2409 str);
2410 return -1;
2412 if (!strcmp(buf, "none"))
2413 translation = BIOS_ATA_TRANSLATION_NONE;
2414 else if (!strcmp(buf, "lba"))
2415 translation = BIOS_ATA_TRANSLATION_LBA;
2416 else if (!strcmp(buf, "auto"))
2417 translation = BIOS_ATA_TRANSLATION_AUTO;
2418 else {
2419 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2420 return -1;
2424 if (get_param_value(buf, sizeof(buf), "media", str)) {
2425 if (!strcmp(buf, "disk")) {
2426 media = MEDIA_DISK;
2427 } else if (!strcmp(buf, "cdrom")) {
2428 if (cyls || secs || heads) {
2429 fprintf(stderr,
2430 "qemu: '%s' invalid physical CHS format\n", str);
2431 return -1;
2433 media = MEDIA_CDROM;
2434 } else {
2435 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2436 return -1;
2440 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2441 if (!strcmp(buf, "on"))
2442 snapshot = 1;
2443 else if (!strcmp(buf, "off"))
2444 snapshot = 0;
2445 else {
2446 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2447 return -1;
2451 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2452 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2453 cache = 0;
2454 else if (!strcmp(buf, "writethrough"))
2455 cache = 1;
2456 else if (!strcmp(buf, "writeback"))
2457 cache = 2;
2458 else {
2459 fprintf(stderr, "qemu: invalid cache option\n");
2460 return -1;
2464 if (get_param_value(buf, sizeof(buf), "format", str)) {
2465 if (strcmp(buf, "?") == 0) {
2466 fprintf(stderr, "qemu: Supported formats:");
2467 bdrv_iterate_format(bdrv_format_print, NULL);
2468 fprintf(stderr, "\n");
2469 return -1;
2471 drv = bdrv_find_format(buf);
2472 if (!drv) {
2473 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2474 return -1;
2478 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2479 if (!strcmp(buf, "on")) {
2480 if (extboot_drive != -1) {
2481 fprintf(stderr, "qemu: two bootable drives specified\n");
2482 return -1;
2484 extboot_drive = nb_drives;
2485 } else if (strcmp(buf, "off")) {
2486 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2487 return -1;
2491 if (arg->file == NULL)
2492 get_param_value(file, sizeof(file), "file", str);
2493 else
2494 pstrcpy(file, sizeof(file), arg->file);
2496 if (!get_param_value(serial, sizeof(serial), "serial", str))
2497 memset(serial, 0, sizeof(serial));
2499 onerror = BLOCK_ERR_STOP_ENOSPC;
2500 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2501 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2502 fprintf(stderr, "werror is no supported by this format\n");
2503 return -1;
2505 if (!strcmp(buf, "ignore"))
2506 onerror = BLOCK_ERR_IGNORE;
2507 else if (!strcmp(buf, "enospc"))
2508 onerror = BLOCK_ERR_STOP_ENOSPC;
2509 else if (!strcmp(buf, "stop"))
2510 onerror = BLOCK_ERR_STOP_ANY;
2511 else if (!strcmp(buf, "report"))
2512 onerror = BLOCK_ERR_REPORT;
2513 else {
2514 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2515 return -1;
2519 /* compute bus and unit according index */
2521 if (index != -1) {
2522 if (bus_id != 0 || unit_id != -1) {
2523 fprintf(stderr,
2524 "qemu: '%s' index cannot be used with bus and unit\n", str);
2525 return -1;
2527 if (max_devs == 0)
2529 unit_id = index;
2530 bus_id = 0;
2531 } else {
2532 unit_id = index % max_devs;
2533 bus_id = index / max_devs;
2537 /* if user doesn't specify a unit_id,
2538 * try to find the first free
2541 if (unit_id == -1) {
2542 unit_id = 0;
2543 while (drive_get_index(type, bus_id, unit_id) != -1) {
2544 unit_id++;
2545 if (max_devs && unit_id >= max_devs) {
2546 unit_id -= max_devs;
2547 bus_id++;
2552 /* check unit id */
2554 if (max_devs && unit_id >= max_devs) {
2555 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2556 str, unit_id, max_devs - 1);
2557 return -1;
2561 * ignore multiple definitions
2564 if (drive_get_index(type, bus_id, unit_id) != -1)
2565 return -2;
2567 /* init */
2569 if (type == IF_IDE || type == IF_SCSI)
2570 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2571 if (max_devs)
2572 snprintf(buf, sizeof(buf), "%s%i%s%i",
2573 devname, bus_id, mediastr, unit_id);
2574 else
2575 snprintf(buf, sizeof(buf), "%s%s%i",
2576 devname, mediastr, unit_id);
2577 bdrv = bdrv_new(buf);
2578 drives_table_idx = drive_get_free_idx();
2579 drives_table[drives_table_idx].bdrv = bdrv;
2580 drives_table[drives_table_idx].type = type;
2581 drives_table[drives_table_idx].bus = bus_id;
2582 drives_table[drives_table_idx].unit = unit_id;
2583 drives_table[drives_table_idx].onerror = onerror;
2584 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2585 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2586 nb_drives++;
2588 switch(type) {
2589 case IF_IDE:
2590 case IF_SCSI:
2591 case IF_XEN:
2592 switch(media) {
2593 case MEDIA_DISK:
2594 if (cyls != 0) {
2595 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2596 bdrv_set_translation_hint(bdrv, translation);
2598 break;
2599 case MEDIA_CDROM:
2600 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2601 break;
2603 break;
2604 case IF_SD:
2605 /* FIXME: This isn't really a floppy, but it's a reasonable
2606 approximation. */
2607 case IF_FLOPPY:
2608 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2609 break;
2610 case IF_PFLASH:
2611 case IF_MTD:
2612 case IF_VIRTIO:
2613 break;
2615 if (!file[0])
2616 return -2;
2617 bdrv_flags = 0;
2618 if (snapshot) {
2619 bdrv_flags |= BDRV_O_SNAPSHOT;
2620 cache = 2; /* always use write-back with snapshot */
2622 if (cache == 0) /* no caching */
2623 bdrv_flags |= BDRV_O_NOCACHE;
2624 else if (cache == 2) /* write-back */
2625 bdrv_flags |= BDRV_O_CACHE_WB;
2626 else if (cache == 3) /* not specified */
2627 bdrv_flags |= BDRV_O_CACHE_DEF;
2628 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2629 fprintf(stderr, "qemu: could not open disk image %s\n",
2630 file);
2631 return -1;
2633 if (bdrv_key_required(bdrv))
2634 autostart = 0;
2635 return drives_table_idx;
2638 static void numa_add(const char *optarg)
2640 char option[128];
2641 char *endptr;
2642 unsigned long long value, endvalue;
2643 int nodenr;
2645 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2646 if (!strcmp(option, "node")) {
2647 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2648 nodenr = nb_numa_nodes;
2649 } else {
2650 nodenr = strtoull(option, NULL, 10);
2653 if (get_param_value(option, 128, "mem", optarg) == 0) {
2654 node_mem[nodenr] = 0;
2655 } else {
2656 value = strtoull(option, &endptr, 0);
2657 switch (*endptr) {
2658 case 0: case 'M': case 'm':
2659 value <<= 20;
2660 break;
2661 case 'G': case 'g':
2662 value <<= 30;
2663 break;
2665 node_mem[nodenr] = value;
2667 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2668 node_cpumask[nodenr] = 0;
2669 } else {
2670 value = strtoull(option, &endptr, 10);
2671 if (value >= 64) {
2672 value = 63;
2673 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2674 } else {
2675 if (*endptr == '-') {
2676 endvalue = strtoull(endptr+1, &endptr, 10);
2677 if (endvalue >= 63) {
2678 endvalue = 62;
2679 fprintf(stderr,
2680 "only 63 CPUs in NUMA mode supported.\n");
2682 value = (1 << (endvalue + 1)) - (1 << value);
2683 } else {
2684 value = 1 << value;
2687 node_cpumask[nodenr] = value;
2689 nb_numa_nodes++;
2691 return;
2694 /***********************************************************/
2695 /* USB devices */
2697 static USBPort *used_usb_ports;
2698 static USBPort *free_usb_ports;
2700 /* ??? Maybe change this to register a hub to keep track of the topology. */
2701 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2702 usb_attachfn attach)
2704 port->opaque = opaque;
2705 port->index = index;
2706 port->attach = attach;
2707 port->next = free_usb_ports;
2708 free_usb_ports = port;
2711 int usb_device_add_dev(USBDevice *dev)
2713 USBPort *port;
2715 /* Find a USB port to add the device to. */
2716 port = free_usb_ports;
2717 if (!port->next) {
2718 USBDevice *hub;
2720 /* Create a new hub and chain it on. */
2721 free_usb_ports = NULL;
2722 port->next = used_usb_ports;
2723 used_usb_ports = port;
2725 hub = usb_hub_init(VM_USB_HUB_SIZE);
2726 usb_attach(port, hub);
2727 port = free_usb_ports;
2730 free_usb_ports = port->next;
2731 port->next = used_usb_ports;
2732 used_usb_ports = port;
2733 usb_attach(port, dev);
2734 return 0;
2737 static void usb_msd_password_cb(void *opaque, int err)
2739 USBDevice *dev = opaque;
2741 if (!err)
2742 usb_device_add_dev(dev);
2743 else
2744 dev->handle_destroy(dev);
2747 static int usb_device_add(const char *devname, int is_hotplug)
2749 const char *p;
2750 USBDevice *dev;
2752 if (!free_usb_ports)
2753 return -1;
2755 if (strstart(devname, "host:", &p)) {
2756 dev = usb_host_device_open(p);
2757 } else if (!strcmp(devname, "mouse")) {
2758 dev = usb_mouse_init();
2759 } else if (!strcmp(devname, "tablet")) {
2760 dev = usb_tablet_init();
2761 } else if (!strcmp(devname, "keyboard")) {
2762 dev = usb_keyboard_init();
2763 } else if (strstart(devname, "disk:", &p)) {
2764 BlockDriverState *bs;
2766 dev = usb_msd_init(p);
2767 if (!dev)
2768 return -1;
2769 bs = usb_msd_get_bdrv(dev);
2770 if (bdrv_key_required(bs)) {
2771 autostart = 0;
2772 if (is_hotplug) {
2773 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2774 dev);
2775 return 0;
2778 } else if (!strcmp(devname, "wacom-tablet")) {
2779 dev = usb_wacom_init();
2780 } else if (strstart(devname, "serial:", &p)) {
2781 dev = usb_serial_init(p);
2782 #ifdef CONFIG_BRLAPI
2783 } else if (!strcmp(devname, "braille")) {
2784 dev = usb_baum_init();
2785 #endif
2786 } else if (strstart(devname, "net:", &p)) {
2787 int nic = nb_nics;
2789 if (net_client_init("nic", p) < 0)
2790 return -1;
2791 nd_table[nic].model = "usb";
2792 dev = usb_net_init(&nd_table[nic]);
2793 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2794 dev = usb_bt_init(devname[2] ? hci_init(p) :
2795 bt_new_hci(qemu_find_bt_vlan(0)));
2796 } else {
2797 return -1;
2799 if (!dev)
2800 return -1;
2802 return usb_device_add_dev(dev);
2805 int usb_device_del_addr(int bus_num, int addr)
2807 USBPort *port;
2808 USBPort **lastp;
2809 USBDevice *dev;
2811 if (!used_usb_ports)
2812 return -1;
2814 if (bus_num != 0)
2815 return -1;
2817 lastp = &used_usb_ports;
2818 port = used_usb_ports;
2819 while (port && port->dev->addr != addr) {
2820 lastp = &port->next;
2821 port = port->next;
2824 if (!port)
2825 return -1;
2827 dev = port->dev;
2828 *lastp = port->next;
2829 usb_attach(port, NULL);
2830 dev->handle_destroy(dev);
2831 port->next = free_usb_ports;
2832 free_usb_ports = port;
2833 return 0;
2836 static int usb_device_del(const char *devname)
2838 int bus_num, addr;
2839 const char *p;
2841 if (strstart(devname, "host:", &p))
2842 return usb_host_device_close(p);
2844 if (!used_usb_ports)
2845 return -1;
2847 p = strchr(devname, '.');
2848 if (!p)
2849 return -1;
2850 bus_num = strtoul(devname, NULL, 0);
2851 addr = strtoul(p + 1, NULL, 0);
2853 return usb_device_del_addr(bus_num, addr);
2856 void do_usb_add(Monitor *mon, const char *devname)
2858 usb_device_add(devname, 1);
2861 void do_usb_del(Monitor *mon, const char *devname)
2863 usb_device_del(devname);
2866 void usb_info(Monitor *mon)
2868 USBDevice *dev;
2869 USBPort *port;
2870 const char *speed_str;
2872 if (!usb_enabled) {
2873 monitor_printf(mon, "USB support not enabled\n");
2874 return;
2877 for (port = used_usb_ports; port; port = port->next) {
2878 dev = port->dev;
2879 if (!dev)
2880 continue;
2881 switch(dev->speed) {
2882 case USB_SPEED_LOW:
2883 speed_str = "1.5";
2884 break;
2885 case USB_SPEED_FULL:
2886 speed_str = "12";
2887 break;
2888 case USB_SPEED_HIGH:
2889 speed_str = "480";
2890 break;
2891 default:
2892 speed_str = "?";
2893 break;
2895 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2896 0, dev->addr, speed_str, dev->devname);
2900 /***********************************************************/
2901 /* PCMCIA/Cardbus */
2903 static struct pcmcia_socket_entry_s {
2904 struct pcmcia_socket_s *socket;
2905 struct pcmcia_socket_entry_s *next;
2906 } *pcmcia_sockets = 0;
2908 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2910 struct pcmcia_socket_entry_s *entry;
2912 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2913 entry->socket = socket;
2914 entry->next = pcmcia_sockets;
2915 pcmcia_sockets = entry;
2918 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2920 struct pcmcia_socket_entry_s *entry, **ptr;
2922 ptr = &pcmcia_sockets;
2923 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2924 if (entry->socket == socket) {
2925 *ptr = entry->next;
2926 qemu_free(entry);
2930 void pcmcia_info(Monitor *mon)
2932 struct pcmcia_socket_entry_s *iter;
2934 if (!pcmcia_sockets)
2935 monitor_printf(mon, "No PCMCIA sockets\n");
2937 for (iter = pcmcia_sockets; iter; iter = iter->next)
2938 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2939 iter->socket->attached ? iter->socket->card_string :
2940 "Empty");
2943 /***********************************************************/
2944 /* register display */
2946 struct DisplayAllocator default_allocator = {
2947 defaultallocator_create_displaysurface,
2948 defaultallocator_resize_displaysurface,
2949 defaultallocator_free_displaysurface
2952 void register_displaystate(DisplayState *ds)
2954 DisplayState **s;
2955 s = &display_state;
2956 while (*s != NULL)
2957 s = &(*s)->next;
2958 ds->next = NULL;
2959 *s = ds;
2962 DisplayState *get_displaystate(void)
2964 return display_state;
2967 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2969 if(ds->allocator == &default_allocator) ds->allocator = da;
2970 return ds->allocator;
2973 /* dumb display */
2975 static void dumb_display_init(void)
2977 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2978 ds->allocator = &default_allocator;
2979 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2980 register_displaystate(ds);
2983 /***********************************************************/
2984 /* I/O handling */
2986 typedef struct IOHandlerRecord {
2987 int fd;
2988 IOCanRWHandler *fd_read_poll;
2989 IOHandler *fd_read;
2990 IOHandler *fd_write;
2991 int deleted;
2992 void *opaque;
2993 /* temporary data */
2994 struct pollfd *ufd;
2995 struct IOHandlerRecord *next;
2996 } IOHandlerRecord;
2998 static IOHandlerRecord *first_io_handler;
3000 /* XXX: fd_read_poll should be suppressed, but an API change is
3001 necessary in the character devices to suppress fd_can_read(). */
3002 int qemu_set_fd_handler2(int fd,
3003 IOCanRWHandler *fd_read_poll,
3004 IOHandler *fd_read,
3005 IOHandler *fd_write,
3006 void *opaque)
3008 IOHandlerRecord **pioh, *ioh;
3010 if (!fd_read && !fd_write) {
3011 pioh = &first_io_handler;
3012 for(;;) {
3013 ioh = *pioh;
3014 if (ioh == NULL)
3015 break;
3016 if (ioh->fd == fd) {
3017 ioh->deleted = 1;
3018 break;
3020 pioh = &ioh->next;
3022 } else {
3023 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3024 if (ioh->fd == fd)
3025 goto found;
3027 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3028 ioh->next = first_io_handler;
3029 first_io_handler = ioh;
3030 found:
3031 ioh->fd = fd;
3032 ioh->fd_read_poll = fd_read_poll;
3033 ioh->fd_read = fd_read;
3034 ioh->fd_write = fd_write;
3035 ioh->opaque = opaque;
3036 ioh->deleted = 0;
3038 qemu_notify_event();
3039 return 0;
3042 int qemu_set_fd_handler(int fd,
3043 IOHandler *fd_read,
3044 IOHandler *fd_write,
3045 void *opaque)
3047 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3050 #ifdef _WIN32
3051 /***********************************************************/
3052 /* Polling handling */
3054 typedef struct PollingEntry {
3055 PollingFunc *func;
3056 void *opaque;
3057 struct PollingEntry *next;
3058 } PollingEntry;
3060 static PollingEntry *first_polling_entry;
3062 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3064 PollingEntry **ppe, *pe;
3065 pe = qemu_mallocz(sizeof(PollingEntry));
3066 pe->func = func;
3067 pe->opaque = opaque;
3068 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3069 *ppe = pe;
3070 return 0;
3073 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3075 PollingEntry **ppe, *pe;
3076 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3077 pe = *ppe;
3078 if (pe->func == func && pe->opaque == opaque) {
3079 *ppe = pe->next;
3080 qemu_free(pe);
3081 break;
3086 /***********************************************************/
3087 /* Wait objects support */
3088 typedef struct WaitObjects {
3089 int num;
3090 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3091 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3092 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3093 } WaitObjects;
3095 static WaitObjects wait_objects = {0};
3097 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3099 WaitObjects *w = &wait_objects;
3101 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3102 return -1;
3103 w->events[w->num] = handle;
3104 w->func[w->num] = func;
3105 w->opaque[w->num] = opaque;
3106 w->num++;
3107 return 0;
3110 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3112 int i, found;
3113 WaitObjects *w = &wait_objects;
3115 found = 0;
3116 for (i = 0; i < w->num; i++) {
3117 if (w->events[i] == handle)
3118 found = 1;
3119 if (found) {
3120 w->events[i] = w->events[i + 1];
3121 w->func[i] = w->func[i + 1];
3122 w->opaque[i] = w->opaque[i + 1];
3125 if (found)
3126 w->num--;
3128 #endif
3130 /***********************************************************/
3131 /* ram save/restore */
3133 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3135 int v;
3137 v = qemu_get_byte(f);
3138 switch(v) {
3139 case 0:
3140 if (qemu_get_buffer(f, buf, len) != len)
3141 return -EIO;
3142 break;
3143 case 1:
3144 v = qemu_get_byte(f);
3145 memset(buf, v, len);
3146 break;
3147 default:
3148 return -EINVAL;
3151 if (qemu_file_has_error(f))
3152 return -EIO;
3154 return 0;
3157 static int ram_load_v1(QEMUFile *f, void *opaque)
3159 int ret;
3160 ram_addr_t i;
3162 if (qemu_get_be32(f) != last_ram_offset)
3163 return -EINVAL;
3164 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
3165 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3166 continue;
3167 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
3168 if (ret)
3169 return ret;
3171 return 0;
3174 #define BDRV_HASH_BLOCK_SIZE 1024
3175 #define IOBUF_SIZE 4096
3176 #define RAM_CBLOCK_MAGIC 0xfabe
3178 typedef struct RamDecompressState {
3179 z_stream zstream;
3180 QEMUFile *f;
3181 uint8_t buf[IOBUF_SIZE];
3182 } RamDecompressState;
3184 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3186 int ret;
3187 memset(s, 0, sizeof(*s));
3188 s->f = f;
3189 ret = inflateInit(&s->zstream);
3190 if (ret != Z_OK)
3191 return -1;
3192 return 0;
3195 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3197 int ret, clen;
3199 s->zstream.avail_out = len;
3200 s->zstream.next_out = buf;
3201 while (s->zstream.avail_out > 0) {
3202 if (s->zstream.avail_in == 0) {
3203 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3204 return -1;
3205 clen = qemu_get_be16(s->f);
3206 if (clen > IOBUF_SIZE)
3207 return -1;
3208 qemu_get_buffer(s->f, s->buf, clen);
3209 s->zstream.avail_in = clen;
3210 s->zstream.next_in = s->buf;
3212 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3213 if (ret != Z_OK && ret != Z_STREAM_END) {
3214 return -1;
3217 return 0;
3220 static void ram_decompress_close(RamDecompressState *s)
3222 inflateEnd(&s->zstream);
3225 #define RAM_SAVE_FLAG_FULL 0x01
3226 #define RAM_SAVE_FLAG_COMPRESS 0x02
3227 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3228 #define RAM_SAVE_FLAG_PAGE 0x08
3229 #define RAM_SAVE_FLAG_EOS 0x10
3231 static int is_dup_page(uint8_t *page, uint8_t ch)
3233 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3234 uint32_t *array = (uint32_t *)page;
3235 int i;
3237 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3238 if (array[i] != val)
3239 return 0;
3242 return 1;
3245 static int ram_save_block(QEMUFile *f)
3247 static ram_addr_t current_addr = 0;
3248 ram_addr_t saved_addr = current_addr;
3249 ram_addr_t addr = 0;
3250 int found = 0;
3252 while (addr < last_ram_offset) {
3253 if (kvm_enabled() && current_addr == 0) {
3254 int r;
3255 r = kvm_update_dirty_pages_log();
3256 if (r) {
3257 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3258 qemu_file_set_error(f);
3259 return 0;
3262 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3263 uint8_t *p;
3265 cpu_physical_memory_reset_dirty(current_addr,
3266 current_addr + TARGET_PAGE_SIZE,
3267 MIGRATION_DIRTY_FLAG);
3269 p = qemu_get_ram_ptr(current_addr);
3271 if (is_dup_page(p, *p)) {
3272 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3273 qemu_put_byte(f, *p);
3274 } else {
3275 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3276 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3279 found = 1;
3280 break;
3282 addr += TARGET_PAGE_SIZE;
3283 current_addr = (saved_addr + addr) % last_ram_offset;
3286 return found;
3289 static ram_addr_t ram_save_threshold = 10;
3291 static ram_addr_t ram_save_remaining(void)
3293 ram_addr_t addr;
3294 ram_addr_t count = 0;
3296 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3297 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3298 count++;
3301 return count;
3304 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3306 ram_addr_t addr;
3308 if (stage == 1) {
3309 /* Make sure all dirty bits are set */
3310 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3311 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3312 cpu_physical_memory_set_dirty(addr);
3315 /* Enable dirty memory tracking */
3316 cpu_physical_memory_set_dirty_tracking(1);
3318 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3321 while (!qemu_file_rate_limit(f)) {
3322 int ret;
3324 ret = ram_save_block(f);
3325 if (ret == 0) /* no more blocks */
3326 break;
3329 /* try transferring iterative blocks of memory */
3331 if (stage == 3) {
3333 /* flush all remaining blocks regardless of rate limiting */
3334 while (ram_save_block(f) != 0);
3335 cpu_physical_memory_set_dirty_tracking(0);
3338 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3340 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3343 static int ram_load_dead(QEMUFile *f, void *opaque)
3345 RamDecompressState s1, *s = &s1;
3346 uint8_t buf[10];
3347 ram_addr_t i;
3349 if (ram_decompress_open(s, f) < 0)
3350 return -EINVAL;
3351 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3352 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3353 continue;
3354 if (ram_decompress_buf(s, buf, 1) < 0) {
3355 fprintf(stderr, "Error while reading ram block header\n");
3356 goto error;
3358 if (buf[0] == 0) {
3359 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3360 BDRV_HASH_BLOCK_SIZE) < 0) {
3361 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3362 goto error;
3364 } else {
3365 error:
3366 printf("Error block header\n");
3367 return -EINVAL;
3370 ram_decompress_close(s);
3372 return 0;
3375 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3377 ram_addr_t addr;
3378 int flags;
3380 if (version_id == 1)
3381 return ram_load_v1(f, opaque);
3383 if (version_id == 2) {
3384 if (qemu_get_be32(f) != last_ram_offset)
3385 return -EINVAL;
3386 return ram_load_dead(f, opaque);
3389 if (version_id != 3)
3390 return -EINVAL;
3392 do {
3393 addr = qemu_get_be64(f);
3395 flags = addr & ~TARGET_PAGE_MASK;
3396 addr &= TARGET_PAGE_MASK;
3398 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3399 if (addr != last_ram_offset)
3400 return -EINVAL;
3403 if (flags & RAM_SAVE_FLAG_FULL) {
3404 if (ram_load_dead(f, opaque) < 0)
3405 return -EINVAL;
3408 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3409 uint8_t ch = qemu_get_byte(f);
3410 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3411 } else if (flags & RAM_SAVE_FLAG_PAGE)
3412 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3413 } while (!(flags & RAM_SAVE_FLAG_EOS));
3415 return 0;
3418 void qemu_service_io(void)
3420 qemu_notify_event();
3423 /***********************************************************/
3424 /* bottom halves (can be seen as timers which expire ASAP) */
3426 struct QEMUBH {
3427 QEMUBHFunc *cb;
3428 void *opaque;
3429 int scheduled;
3430 int idle;
3431 int deleted;
3432 QEMUBH *next;
3435 static QEMUBH *first_bh = NULL;
3437 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3439 QEMUBH *bh;
3440 bh = qemu_mallocz(sizeof(QEMUBH));
3441 bh->cb = cb;
3442 bh->opaque = opaque;
3443 bh->next = first_bh;
3444 first_bh = bh;
3445 return bh;
3448 int qemu_bh_poll(void)
3450 QEMUBH *bh, **bhp;
3451 int ret;
3453 ret = 0;
3454 for (bh = first_bh; bh; bh = bh->next) {
3455 if (!bh->deleted && bh->scheduled) {
3456 bh->scheduled = 0;
3457 if (!bh->idle)
3458 ret = 1;
3459 bh->idle = 0;
3460 bh->cb(bh->opaque);
3464 /* remove deleted bhs */
3465 bhp = &first_bh;
3466 while (*bhp) {
3467 bh = *bhp;
3468 if (bh->deleted) {
3469 *bhp = bh->next;
3470 qemu_free(bh);
3471 } else
3472 bhp = &bh->next;
3475 return ret;
3478 void qemu_bh_schedule_idle(QEMUBH *bh)
3480 if (bh->scheduled)
3481 return;
3482 bh->scheduled = 1;
3483 bh->idle = 1;
3486 void qemu_bh_schedule(QEMUBH *bh)
3488 if (bh->scheduled)
3489 return;
3490 bh->scheduled = 1;
3491 bh->idle = 0;
3492 /* stop the currently executing CPU to execute the BH ASAP */
3493 qemu_notify_event();
3496 void qemu_bh_cancel(QEMUBH *bh)
3498 bh->scheduled = 0;
3501 void qemu_bh_delete(QEMUBH *bh)
3503 bh->scheduled = 0;
3504 bh->deleted = 1;
3507 static void qemu_bh_update_timeout(int *timeout)
3509 QEMUBH *bh;
3511 for (bh = first_bh; bh; bh = bh->next) {
3512 if (!bh->deleted && bh->scheduled) {
3513 if (bh->idle) {
3514 /* idle bottom halves will be polled at least
3515 * every 10ms */
3516 *timeout = MIN(10, *timeout);
3517 } else {
3518 /* non-idle bottom halves will be executed
3519 * immediately */
3520 *timeout = 0;
3521 break;
3527 /***********************************************************/
3528 /* machine registration */
3530 static QEMUMachine *first_machine = NULL;
3531 QEMUMachine *current_machine = NULL;
3533 int qemu_register_machine(QEMUMachine *m)
3535 QEMUMachine **pm;
3536 pm = &first_machine;
3537 while (*pm != NULL)
3538 pm = &(*pm)->next;
3539 m->next = NULL;
3540 *pm = m;
3541 return 0;
3544 static QEMUMachine *find_machine(const char *name)
3546 QEMUMachine *m;
3548 for(m = first_machine; m != NULL; m = m->next) {
3549 if (!strcmp(m->name, name))
3550 return m;
3552 return NULL;
3555 /***********************************************************/
3556 /* main execution loop */
3558 static void gui_update(void *opaque)
3560 uint64_t interval = GUI_REFRESH_INTERVAL;
3561 DisplayState *ds = opaque;
3562 DisplayChangeListener *dcl = ds->listeners;
3564 dpy_refresh(ds);
3566 while (dcl != NULL) {
3567 if (dcl->gui_timer_interval &&
3568 dcl->gui_timer_interval < interval)
3569 interval = dcl->gui_timer_interval;
3570 dcl = dcl->next;
3572 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3575 static void nographic_update(void *opaque)
3577 uint64_t interval = GUI_REFRESH_INTERVAL;
3579 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3582 struct vm_change_state_entry {
3583 VMChangeStateHandler *cb;
3584 void *opaque;
3585 LIST_ENTRY (vm_change_state_entry) entries;
3588 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3590 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3591 void *opaque)
3593 VMChangeStateEntry *e;
3595 e = qemu_mallocz(sizeof (*e));
3597 e->cb = cb;
3598 e->opaque = opaque;
3599 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3600 return e;
3603 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3605 LIST_REMOVE (e, entries);
3606 qemu_free (e);
3609 static void vm_state_notify(int running, int reason)
3611 VMChangeStateEntry *e;
3613 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3614 e->cb(e->opaque, running, reason);
3618 static void resume_all_vcpus(void);
3619 static void pause_all_vcpus(void);
3621 void vm_start(void)
3623 if (!vm_running) {
3624 cpu_enable_ticks();
3625 vm_running = 1;
3626 vm_state_notify(1, 0);
3627 qemu_rearm_alarm_timer(alarm_timer);
3628 resume_all_vcpus();
3632 /* reset/shutdown handler */
3634 typedef struct QEMUResetEntry {
3635 QEMUResetHandler *func;
3636 void *opaque;
3637 struct QEMUResetEntry *next;
3638 } QEMUResetEntry;
3640 static QEMUResetEntry *first_reset_entry;
3641 static int reset_requested;
3642 static int shutdown_requested;
3643 static int powerdown_requested;
3644 static int debug_requested;
3645 static int vmstop_requested;
3647 int qemu_shutdown_requested(void)
3649 int r = shutdown_requested;
3650 shutdown_requested = 0;
3651 return r;
3654 int qemu_reset_requested(void)
3656 int r = reset_requested;
3657 reset_requested = 0;
3658 return r;
3661 int qemu_powerdown_requested(void)
3663 int r = powerdown_requested;
3664 powerdown_requested = 0;
3665 return r;
3668 static int qemu_debug_requested(void)
3670 int r = debug_requested;
3671 debug_requested = 0;
3672 return r;
3675 static int qemu_vmstop_requested(void)
3677 int r = vmstop_requested;
3678 vmstop_requested = 0;
3679 return r;
3682 static void do_vm_stop(int reason)
3684 if (vm_running) {
3685 cpu_disable_ticks();
3686 vm_running = 0;
3687 pause_all_vcpus();
3688 vm_state_notify(0, reason);
3692 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3694 QEMUResetEntry **pre, *re;
3696 pre = &first_reset_entry;
3697 while (*pre != NULL)
3698 pre = &(*pre)->next;
3699 re = qemu_mallocz(sizeof(QEMUResetEntry));
3700 re->func = func;
3701 re->opaque = opaque;
3702 re->next = NULL;
3703 *pre = re;
3706 void qemu_system_reset(void)
3708 QEMUResetEntry *re;
3710 /* reset all devices */
3711 for(re = first_reset_entry; re != NULL; re = re->next) {
3712 re->func(re->opaque);
3714 if (kvm_enabled())
3715 kvm_sync_vcpus();
3718 void qemu_system_reset_request(void)
3720 if (no_reboot) {
3721 shutdown_requested = 1;
3722 } else {
3723 reset_requested = 1;
3725 if (cpu_single_env) {
3726 qemu_kvm_cpu_stop(cpu_single_env);
3727 cpu_exit(cpu_single_env);
3729 qemu_notify_event();
3732 void qemu_system_shutdown_request(void)
3734 shutdown_requested = 1;
3735 qemu_notify_event();
3738 void qemu_system_powerdown_request(void)
3740 powerdown_requested = 1;
3741 qemu_notify_event();
3744 #ifdef CONFIG_IOTHREAD
3745 static void qemu_system_vmstop_request(int reason)
3747 vmstop_requested = reason;
3748 qemu_notify_event();
3750 #endif
3752 #ifndef _WIN32
3753 static int io_thread_fd = -1;
3755 static void qemu_event_increment(void)
3757 static const char byte = 0;
3759 if (io_thread_fd == -1)
3760 return;
3762 write(io_thread_fd, &byte, sizeof(byte));
3765 static void qemu_event_read(void *opaque)
3767 int fd = (unsigned long)opaque;
3768 ssize_t len;
3770 /* Drain the notify pipe */
3771 do {
3772 char buffer[512];
3773 len = read(fd, buffer, sizeof(buffer));
3774 } while ((len == -1 && errno == EINTR) || len > 0);
3777 static int qemu_event_init(void)
3779 int err;
3780 int fds[2];
3782 err = pipe(fds);
3783 if (err == -1)
3784 return -errno;
3786 err = fcntl_setfl(fds[0], O_NONBLOCK);
3787 if (err < 0)
3788 goto fail;
3790 err = fcntl_setfl(fds[1], O_NONBLOCK);
3791 if (err < 0)
3792 goto fail;
3794 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3795 (void *)(unsigned long)fds[0]);
3797 io_thread_fd = fds[1];
3798 return 0;
3800 fail:
3801 close(fds[0]);
3802 close(fds[1]);
3803 return err;
3805 #else
3806 HANDLE qemu_event_handle;
3808 static void dummy_event_handler(void *opaque)
3812 static int qemu_event_init(void)
3814 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3815 if (!qemu_event_handle) {
3816 perror("Failed CreateEvent");
3817 return -1;
3819 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3820 return 0;
3823 static void qemu_event_increment(void)
3825 SetEvent(qemu_event_handle);
3827 #endif
3829 static int cpu_can_run(CPUState *env)
3831 if (env->stop)
3832 return 0;
3833 if (env->stopped)
3834 return 0;
3835 return 1;
3838 #ifndef CONFIG_IOTHREAD
3839 static int qemu_init_main_loop(void)
3841 return qemu_event_init();
3844 void qemu_init_vcpu(void *_env)
3846 CPUState *env = _env;
3848 if (kvm_enabled())
3849 kvm_init_vcpu(env);
3850 return;
3853 int qemu_cpu_self(void *env)
3855 return 1;
3858 static void resume_all_vcpus(void)
3862 static void pause_all_vcpus(void)
3866 void qemu_cpu_kick(void *env)
3868 return;
3871 void qemu_notify_event(void)
3873 CPUState *env = cpu_single_env;
3875 if (kvm_enabled()) {
3876 qemu_kvm_notify_work();
3877 return;
3879 if (env) {
3880 cpu_exit(env);
3881 #ifdef USE_KQEMU
3882 if (env->kqemu_enabled)
3883 kqemu_cpu_interrupt(env);
3884 #endif
3888 #define qemu_mutex_lock_iothread() do { } while (0)
3889 #define qemu_mutex_unlock_iothread() do { } while (0)
3891 void vm_stop(int reason)
3893 do_vm_stop(reason);
3896 #else /* CONFIG_IOTHREAD */
3898 #include "qemu-thread.h"
3900 QemuMutex qemu_global_mutex;
3901 static QemuMutex qemu_fair_mutex;
3903 static QemuThread io_thread;
3905 static QemuThread *tcg_cpu_thread;
3906 static QemuCond *tcg_halt_cond;
3908 static int qemu_system_ready;
3909 /* cpu creation */
3910 static QemuCond qemu_cpu_cond;
3911 /* system init */
3912 static QemuCond qemu_system_cond;
3913 static QemuCond qemu_pause_cond;
3915 static void block_io_signals(void);
3916 static void unblock_io_signals(void);
3917 static int tcg_has_work(void);
3919 static int qemu_init_main_loop(void)
3921 int ret;
3923 ret = qemu_event_init();
3924 if (ret)
3925 return ret;
3927 qemu_cond_init(&qemu_pause_cond);
3928 qemu_mutex_init(&qemu_fair_mutex);
3929 qemu_mutex_init(&qemu_global_mutex);
3930 qemu_mutex_lock(&qemu_global_mutex);
3932 unblock_io_signals();
3933 qemu_thread_self(&io_thread);
3935 return 0;
3938 static void qemu_wait_io_event(CPUState *env)
3940 while (!tcg_has_work())
3941 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3943 qemu_mutex_unlock(&qemu_global_mutex);
3946 * Users of qemu_global_mutex can be starved, having no chance
3947 * to acquire it since this path will get to it first.
3948 * So use another lock to provide fairness.
3950 qemu_mutex_lock(&qemu_fair_mutex);
3951 qemu_mutex_unlock(&qemu_fair_mutex);
3953 qemu_mutex_lock(&qemu_global_mutex);
3954 if (env->stop) {
3955 env->stop = 0;
3956 env->stopped = 1;
3957 qemu_cond_signal(&qemu_pause_cond);
3961 static int qemu_cpu_exec(CPUState *env);
3963 static void *kvm_cpu_thread_fn(void *arg)
3965 CPUState *env = arg;
3967 block_io_signals();
3968 qemu_thread_self(env->thread);
3970 /* signal CPU creation */
3971 qemu_mutex_lock(&qemu_global_mutex);
3972 env->created = 1;
3973 qemu_cond_signal(&qemu_cpu_cond);
3975 /* and wait for machine initialization */
3976 while (!qemu_system_ready)
3977 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3979 while (1) {
3980 if (cpu_can_run(env))
3981 qemu_cpu_exec(env);
3982 qemu_wait_io_event(env);
3985 return NULL;
3988 static void tcg_cpu_exec(void);
3990 static void *tcg_cpu_thread_fn(void *arg)
3992 CPUState *env = arg;
3994 block_io_signals();
3995 qemu_thread_self(env->thread);
3997 /* signal CPU creation */
3998 qemu_mutex_lock(&qemu_global_mutex);
3999 for (env = first_cpu; env != NULL; env = env->next_cpu)
4000 env->created = 1;
4001 qemu_cond_signal(&qemu_cpu_cond);
4003 /* and wait for machine initialization */
4004 while (!qemu_system_ready)
4005 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
4007 while (1) {
4008 tcg_cpu_exec();
4009 qemu_wait_io_event(cur_cpu);
4012 return NULL;
4015 void qemu_cpu_kick(void *_env)
4017 CPUState *env = _env;
4018 qemu_cond_broadcast(env->halt_cond);
4019 if (kvm_enabled())
4020 qemu_thread_signal(env->thread, SIGUSR1);
4023 int qemu_cpu_self(void *env)
4025 return (cpu_single_env != NULL);
4028 static void cpu_signal(int sig)
4030 if (cpu_single_env)
4031 cpu_exit(cpu_single_env);
4034 static void block_io_signals(void)
4036 sigset_t set;
4037 struct sigaction sigact;
4039 sigemptyset(&set);
4040 sigaddset(&set, SIGUSR2);
4041 sigaddset(&set, SIGIO);
4042 sigaddset(&set, SIGALRM);
4043 pthread_sigmask(SIG_BLOCK, &set, NULL);
4045 sigemptyset(&set);
4046 sigaddset(&set, SIGUSR1);
4047 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4049 memset(&sigact, 0, sizeof(sigact));
4050 sigact.sa_handler = cpu_signal;
4051 sigaction(SIGUSR1, &sigact, NULL);
4054 static void unblock_io_signals(void)
4056 sigset_t set;
4058 sigemptyset(&set);
4059 sigaddset(&set, SIGUSR2);
4060 sigaddset(&set, SIGIO);
4061 sigaddset(&set, SIGALRM);
4062 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4064 sigemptyset(&set);
4065 sigaddset(&set, SIGUSR1);
4066 pthread_sigmask(SIG_BLOCK, &set, NULL);
4069 static void qemu_signal_lock(unsigned int msecs)
4071 qemu_mutex_lock(&qemu_fair_mutex);
4073 while (qemu_mutex_trylock(&qemu_global_mutex)) {
4074 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
4075 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
4076 break;
4078 qemu_mutex_unlock(&qemu_fair_mutex);
4081 static void qemu_mutex_lock_iothread(void)
4083 if (kvm_enabled()) {
4084 qemu_mutex_lock(&qemu_fair_mutex);
4085 qemu_mutex_lock(&qemu_global_mutex);
4086 qemu_mutex_unlock(&qemu_fair_mutex);
4087 } else
4088 qemu_signal_lock(100);
4091 static void qemu_mutex_unlock_iothread(void)
4093 qemu_mutex_unlock(&qemu_global_mutex);
4096 static int all_vcpus_paused(void)
4098 CPUState *penv = first_cpu;
4100 while (penv) {
4101 if (!penv->stopped)
4102 return 0;
4103 penv = (CPUState *)penv->next_cpu;
4106 return 1;
4109 static void pause_all_vcpus(void)
4111 CPUState *penv = first_cpu;
4113 while (penv) {
4114 penv->stop = 1;
4115 qemu_thread_signal(penv->thread, SIGUSR1);
4116 qemu_cpu_kick(penv);
4117 penv = (CPUState *)penv->next_cpu;
4120 while (!all_vcpus_paused()) {
4121 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
4122 penv = first_cpu;
4123 while (penv) {
4124 qemu_thread_signal(penv->thread, SIGUSR1);
4125 penv = (CPUState *)penv->next_cpu;
4130 static void resume_all_vcpus(void)
4132 CPUState *penv = first_cpu;
4134 while (penv) {
4135 penv->stop = 0;
4136 penv->stopped = 0;
4137 qemu_thread_signal(penv->thread, SIGUSR1);
4138 qemu_cpu_kick(penv);
4139 penv = (CPUState *)penv->next_cpu;
4143 static void tcg_init_vcpu(void *_env)
4145 CPUState *env = _env;
4146 /* share a single thread for all cpus with TCG */
4147 if (!tcg_cpu_thread) {
4148 env->thread = qemu_mallocz(sizeof(QemuThread));
4149 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4150 qemu_cond_init(env->halt_cond);
4151 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
4152 while (env->created == 0)
4153 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4154 tcg_cpu_thread = env->thread;
4155 tcg_halt_cond = env->halt_cond;
4156 } else {
4157 env->thread = tcg_cpu_thread;
4158 env->halt_cond = tcg_halt_cond;
4162 static void kvm_start_vcpu(CPUState *env)
4164 kvm_init_vcpu(env);
4165 env->thread = qemu_mallocz(sizeof(QemuThread));
4166 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4167 qemu_cond_init(env->halt_cond);
4168 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
4169 while (env->created == 0)
4170 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4173 void qemu_init_vcpu(void *_env)
4175 CPUState *env = _env;
4177 if (kvm_enabled())
4178 kvm_start_vcpu(env);
4179 else
4180 tcg_init_vcpu(env);
4183 void qemu_notify_event(void)
4185 qemu_event_increment();
4188 void vm_stop(int reason)
4190 QemuThread me;
4191 qemu_thread_self(&me);
4193 if (!qemu_thread_equal(&me, &io_thread)) {
4194 qemu_system_vmstop_request(reason);
4196 * FIXME: should not return to device code in case
4197 * vm_stop() has been requested.
4199 if (cpu_single_env) {
4200 cpu_exit(cpu_single_env);
4201 cpu_single_env->stop = 1;
4203 return;
4205 do_vm_stop(reason);
4208 #endif
4211 #ifdef _WIN32
4212 static void host_main_loop_wait(int *timeout)
4214 int ret, ret2, i;
4215 PollingEntry *pe;
4218 /* XXX: need to suppress polling by better using win32 events */
4219 ret = 0;
4220 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4221 ret |= pe->func(pe->opaque);
4223 if (ret == 0) {
4224 int err;
4225 WaitObjects *w = &wait_objects;
4227 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4228 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4229 if (w->func[ret - WAIT_OBJECT_0])
4230 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4232 /* Check for additional signaled events */
4233 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4235 /* Check if event is signaled */
4236 ret2 = WaitForSingleObject(w->events[i], 0);
4237 if(ret2 == WAIT_OBJECT_0) {
4238 if (w->func[i])
4239 w->func[i](w->opaque[i]);
4240 } else if (ret2 == WAIT_TIMEOUT) {
4241 } else {
4242 err = GetLastError();
4243 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4246 } else if (ret == WAIT_TIMEOUT) {
4247 } else {
4248 err = GetLastError();
4249 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4253 *timeout = 0;
4255 #else
4256 static void host_main_loop_wait(int *timeout)
4259 #endif
4261 void main_loop_wait(int timeout)
4263 IOHandlerRecord *ioh;
4264 fd_set rfds, wfds, xfds;
4265 int ret, nfds;
4266 struct timeval tv;
4268 qemu_bh_update_timeout(&timeout);
4270 host_main_loop_wait(&timeout);
4272 /* poll any events */
4273 /* XXX: separate device handlers from system ones */
4274 nfds = -1;
4275 FD_ZERO(&rfds);
4276 FD_ZERO(&wfds);
4277 FD_ZERO(&xfds);
4278 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4279 if (ioh->deleted)
4280 continue;
4281 if (ioh->fd_read &&
4282 (!ioh->fd_read_poll ||
4283 ioh->fd_read_poll(ioh->opaque) != 0)) {
4284 FD_SET(ioh->fd, &rfds);
4285 if (ioh->fd > nfds)
4286 nfds = ioh->fd;
4288 if (ioh->fd_write) {
4289 FD_SET(ioh->fd, &wfds);
4290 if (ioh->fd > nfds)
4291 nfds = ioh->fd;
4295 tv.tv_sec = timeout / 1000;
4296 tv.tv_usec = (timeout % 1000) * 1000;
4298 #if defined(CONFIG_SLIRP)
4299 if (slirp_is_inited()) {
4300 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4302 #endif
4303 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4304 if (ret > 0) {
4305 IOHandlerRecord **pioh;
4307 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4308 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4309 ioh->fd_read(ioh->opaque);
4310 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
4311 FD_CLR(ioh->fd, &rfds);
4313 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4314 ioh->fd_write(ioh->opaque);
4318 /* remove deleted IO handlers */
4319 pioh = &first_io_handler;
4320 while (*pioh) {
4321 ioh = *pioh;
4322 if (ioh->deleted) {
4323 *pioh = ioh->next;
4324 qemu_free(ioh);
4325 } else
4326 pioh = &ioh->next;
4329 #if defined(CONFIG_SLIRP)
4330 if (slirp_is_inited()) {
4331 if (ret < 0) {
4332 FD_ZERO(&rfds);
4333 FD_ZERO(&wfds);
4334 FD_ZERO(&xfds);
4336 slirp_select_poll(&rfds, &wfds, &xfds);
4338 #endif
4340 /* rearm timer, if not periodic */
4341 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4342 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4343 qemu_rearm_alarm_timer(alarm_timer);
4346 /* vm time timers */
4347 if (vm_running) {
4348 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4349 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4350 qemu_get_clock(vm_clock));
4353 /* real time timers */
4354 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4355 qemu_get_clock(rt_clock));
4357 /* Check bottom-halves last in case any of the earlier events triggered
4358 them. */
4359 qemu_bh_poll();
4363 static int qemu_cpu_exec(CPUState *env)
4365 int ret;
4366 #ifdef CONFIG_PROFILER
4367 int64_t ti;
4368 #endif
4370 #ifdef CONFIG_PROFILER
4371 ti = profile_getclock();
4372 #endif
4373 if (use_icount) {
4374 int64_t count;
4375 int decr;
4376 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4377 env->icount_decr.u16.low = 0;
4378 env->icount_extra = 0;
4379 count = qemu_next_deadline();
4380 count = (count + (1 << icount_time_shift) - 1)
4381 >> icount_time_shift;
4382 qemu_icount += count;
4383 decr = (count > 0xffff) ? 0xffff : count;
4384 count -= decr;
4385 env->icount_decr.u16.low = decr;
4386 env->icount_extra = count;
4388 ret = cpu_exec(env);
4389 #ifdef CONFIG_PROFILER
4390 qemu_time += profile_getclock() - ti;
4391 #endif
4392 if (use_icount) {
4393 /* Fold pending instructions back into the
4394 instruction counter, and clear the interrupt flag. */
4395 qemu_icount -= (env->icount_decr.u16.low
4396 + env->icount_extra);
4397 env->icount_decr.u32 = 0;
4398 env->icount_extra = 0;
4400 return ret;
4403 static void tcg_cpu_exec(void)
4405 int ret = 0;
4407 if (next_cpu == NULL)
4408 next_cpu = first_cpu;
4409 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4410 CPUState *env = cur_cpu = next_cpu;
4412 if (!vm_running)
4413 break;
4414 if (timer_alarm_pending) {
4415 timer_alarm_pending = 0;
4416 break;
4418 if (cpu_can_run(env))
4419 ret = qemu_cpu_exec(env);
4420 #ifndef CONFIG_GDBSTUB
4421 if (ret == EXCP_DEBUG) {
4422 gdb_set_stop_cpu(env);
4423 debug_requested = 1;
4424 break;
4426 #endif
4430 static int cpu_has_work(CPUState *env)
4432 if (env->stop)
4433 return 1;
4434 if (env->stopped)
4435 return 0;
4436 if (!env->halted)
4437 return 1;
4438 if (qemu_cpu_has_work(env))
4439 return 1;
4440 return 0;
4443 static int tcg_has_work(void)
4445 CPUState *env;
4447 for (env = first_cpu; env != NULL; env = env->next_cpu)
4448 if (cpu_has_work(env))
4449 return 1;
4450 return 0;
4453 static int qemu_calculate_timeout(void)
4455 int timeout;
4457 if (!vm_running)
4458 timeout = 5000;
4459 else if (tcg_has_work())
4460 timeout = 0;
4461 else if (!use_icount)
4462 timeout = 5000;
4463 else {
4464 /* XXX: use timeout computed from timers */
4465 int64_t add;
4466 int64_t delta;
4467 /* Advance virtual time to the next event. */
4468 if (use_icount == 1) {
4469 /* When not using an adaptive execution frequency
4470 we tend to get badly out of sync with real time,
4471 so just delay for a reasonable amount of time. */
4472 delta = 0;
4473 } else {
4474 delta = cpu_get_icount() - cpu_get_clock();
4476 if (delta > 0) {
4477 /* If virtual time is ahead of real time then just
4478 wait for IO. */
4479 timeout = (delta / 1000000) + 1;
4480 } else {
4481 /* Wait for either IO to occur or the next
4482 timer event. */
4483 add = qemu_next_deadline();
4484 /* We advance the timer before checking for IO.
4485 Limit the amount we advance so that early IO
4486 activity won't get the guest too far ahead. */
4487 if (add > 10000000)
4488 add = 10000000;
4489 delta += add;
4490 add = (add + (1 << icount_time_shift) - 1)
4491 >> icount_time_shift;
4492 qemu_icount += add;
4493 timeout = delta / 1000000;
4494 if (timeout < 0)
4495 timeout = 0;
4499 return timeout;
4502 static int vm_can_run(void)
4504 if (powerdown_requested)
4505 return 0;
4506 if (reset_requested)
4507 return 0;
4508 if (shutdown_requested)
4509 return 0;
4510 if (debug_requested)
4511 return 0;
4512 return 1;
4515 static void main_loop(void)
4517 int r;
4519 if (kvm_enabled()) {
4520 kvm_main_loop();
4521 cpu_disable_ticks();
4522 return;
4525 #ifdef CONFIG_IOTHREAD
4526 qemu_system_ready = 1;
4527 qemu_cond_broadcast(&qemu_system_cond);
4528 #endif
4530 for (;;) {
4531 do {
4532 #ifdef CONFIG_PROFILER
4533 int64_t ti;
4534 #endif
4535 #ifndef CONFIG_IOTHREAD
4536 tcg_cpu_exec();
4537 #endif
4538 #ifdef CONFIG_PROFILER
4539 ti = profile_getclock();
4540 #endif
4541 #ifdef CONFIG_IOTHREAD
4542 main_loop_wait(1000);
4543 #else
4544 main_loop_wait(qemu_calculate_timeout());
4545 #endif
4546 #ifdef CONFIG_PROFILER
4547 dev_time += profile_getclock() - ti;
4548 #endif
4549 } while (vm_can_run());
4551 if (qemu_debug_requested())
4552 vm_stop(EXCP_DEBUG);
4553 if (qemu_shutdown_requested()) {
4554 if (no_shutdown) {
4555 vm_stop(0);
4556 no_shutdown = 0;
4557 } else
4558 break;
4560 if (qemu_reset_requested()) {
4561 pause_all_vcpus();
4562 qemu_system_reset();
4563 resume_all_vcpus();
4565 if (qemu_powerdown_requested())
4566 qemu_system_powerdown();
4567 if ((r = qemu_vmstop_requested()))
4568 vm_stop(r);
4570 pause_all_vcpus();
4573 static void version(void)
4575 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4578 static void help(int exitcode)
4580 version();
4581 printf("usage: %s [options] [disk_image]\n"
4582 "\n"
4583 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4584 "\n"
4585 #define DEF(option, opt_arg, opt_enum, opt_help) \
4586 opt_help
4587 #define DEFHEADING(text) stringify(text) "\n"
4588 #include "qemu-options.h"
4589 #undef DEF
4590 #undef DEFHEADING
4591 #undef GEN_DOCS
4592 "\n"
4593 "During emulation, the following keys are useful:\n"
4594 "ctrl-alt-f toggle full screen\n"
4595 "ctrl-alt-n switch to virtual console 'n'\n"
4596 "ctrl-alt toggle mouse and keyboard grab\n"
4597 "\n"
4598 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4600 "qemu",
4601 DEFAULT_RAM_SIZE,
4602 #ifndef _WIN32
4603 DEFAULT_NETWORK_SCRIPT,
4604 DEFAULT_NETWORK_DOWN_SCRIPT,
4605 #endif
4606 DEFAULT_GDBSTUB_PORT,
4607 "/tmp/qemu.log");
4608 exit(exitcode);
4611 #define HAS_ARG 0x0001
4613 enum {
4614 #define DEF(option, opt_arg, opt_enum, opt_help) \
4615 opt_enum,
4616 #define DEFHEADING(text)
4617 #include "qemu-options.h"
4618 #undef DEF
4619 #undef DEFHEADING
4620 #undef GEN_DOCS
4623 typedef struct QEMUOption {
4624 const char *name;
4625 int flags;
4626 int index;
4627 } QEMUOption;
4629 static const QEMUOption qemu_options[] = {
4630 { "h", 0, QEMU_OPTION_h },
4631 #define DEF(option, opt_arg, opt_enum, opt_help) \
4632 { option, opt_arg, opt_enum },
4633 #define DEFHEADING(text)
4634 #include "qemu-options.h"
4635 #undef DEF
4636 #undef DEFHEADING
4637 #undef GEN_DOCS
4638 { NULL },
4641 #ifdef HAS_AUDIO
4642 struct soundhw soundhw[] = {
4643 #ifdef HAS_AUDIO_CHOICE
4644 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4646 "pcspk",
4647 "PC speaker",
4650 { .init_isa = pcspk_audio_init }
4652 #endif
4654 #ifdef CONFIG_SB16
4656 "sb16",
4657 "Creative Sound Blaster 16",
4660 { .init_isa = SB16_init }
4662 #endif
4664 #ifdef CONFIG_CS4231A
4666 "cs4231a",
4667 "CS4231A",
4670 { .init_isa = cs4231a_init }
4672 #endif
4674 #ifdef CONFIG_ADLIB
4676 "adlib",
4677 #ifdef HAS_YMF262
4678 "Yamaha YMF262 (OPL3)",
4679 #else
4680 "Yamaha YM3812 (OPL2)",
4681 #endif
4684 { .init_isa = Adlib_init }
4686 #endif
4688 #ifdef CONFIG_GUS
4690 "gus",
4691 "Gravis Ultrasound GF1",
4694 { .init_isa = GUS_init }
4696 #endif
4698 #ifdef CONFIG_AC97
4700 "ac97",
4701 "Intel 82801AA AC97 Audio",
4704 { .init_pci = ac97_init }
4706 #endif
4708 #ifdef CONFIG_ES1370
4710 "es1370",
4711 "ENSONIQ AudioPCI ES1370",
4714 { .init_pci = es1370_init }
4716 #endif
4718 #endif /* HAS_AUDIO_CHOICE */
4720 { NULL, NULL, 0, 0, { NULL } }
4723 static void select_soundhw (const char *optarg)
4725 struct soundhw *c;
4727 if (*optarg == '?') {
4728 show_valid_cards:
4730 printf ("Valid sound card names (comma separated):\n");
4731 for (c = soundhw; c->name; ++c) {
4732 printf ("%-11s %s\n", c->name, c->descr);
4734 printf ("\n-soundhw all will enable all of the above\n");
4735 exit (*optarg != '?');
4737 else {
4738 size_t l;
4739 const char *p;
4740 char *e;
4741 int bad_card = 0;
4743 if (!strcmp (optarg, "all")) {
4744 for (c = soundhw; c->name; ++c) {
4745 c->enabled = 1;
4747 return;
4750 p = optarg;
4751 while (*p) {
4752 e = strchr (p, ',');
4753 l = !e ? strlen (p) : (size_t) (e - p);
4755 for (c = soundhw; c->name; ++c) {
4756 if (!strncmp (c->name, p, l)) {
4757 c->enabled = 1;
4758 break;
4762 if (!c->name) {
4763 if (l > 80) {
4764 fprintf (stderr,
4765 "Unknown sound card name (too big to show)\n");
4767 else {
4768 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4769 (int) l, p);
4771 bad_card = 1;
4773 p += l + (e != NULL);
4776 if (bad_card)
4777 goto show_valid_cards;
4780 #endif
4782 static void select_vgahw (const char *p)
4784 const char *opts;
4786 cirrus_vga_enabled = 0;
4787 std_vga_enabled = 0;
4788 vmsvga_enabled = 0;
4789 xenfb_enabled = 0;
4790 if (strstart(p, "std", &opts)) {
4791 std_vga_enabled = 1;
4792 } else if (strstart(p, "cirrus", &opts)) {
4793 cirrus_vga_enabled = 1;
4794 } else if (strstart(p, "vmware", &opts)) {
4795 vmsvga_enabled = 1;
4796 } else if (strstart(p, "xenfb", &opts)) {
4797 xenfb_enabled = 1;
4798 } else if (!strstart(p, "none", &opts)) {
4799 invalid_vga:
4800 fprintf(stderr, "Unknown vga type: %s\n", p);
4801 exit(1);
4803 while (*opts) {
4804 const char *nextopt;
4806 if (strstart(opts, ",retrace=", &nextopt)) {
4807 opts = nextopt;
4808 if (strstart(opts, "dumb", &nextopt))
4809 vga_retrace_method = VGA_RETRACE_DUMB;
4810 else if (strstart(opts, "precise", &nextopt))
4811 vga_retrace_method = VGA_RETRACE_PRECISE;
4812 else goto invalid_vga;
4813 } else goto invalid_vga;
4814 opts = nextopt;
4818 #ifdef _WIN32
4819 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4821 exit(STATUS_CONTROL_C_EXIT);
4822 return TRUE;
4824 #endif
4826 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4828 int ret;
4830 if(strlen(str) != 36)
4831 return -1;
4833 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4834 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4835 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4837 if(ret != 16)
4838 return -1;
4840 #ifdef TARGET_I386
4841 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4842 #endif
4844 return 0;
4847 #define MAX_NET_CLIENTS 32
4849 #ifdef USE_KVM
4851 #define HUGETLBFS_MAGIC 0x958458f6
4853 static long gethugepagesize(const char *path)
4855 struct statfs fs;
4856 int ret;
4858 do {
4859 ret = statfs(path, &fs);
4860 } while (ret != 0 && errno == EINTR);
4862 if (ret != 0) {
4863 perror("statfs");
4864 return 0;
4867 if (fs.f_type != HUGETLBFS_MAGIC)
4868 fprintf(stderr, "Warning: path not on HugeTLBFS: %s\n", path);
4870 return fs.f_bsize;
4873 static void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4875 char *filename;
4876 void *area;
4877 int fd;
4878 #ifdef MAP_POPULATE
4879 int flags;
4880 #endif
4882 if (!kvm_has_sync_mmu()) {
4883 fprintf(stderr, "host lacks mmu notifiers, disabling --mem-path\n");
4884 return NULL;
4887 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4888 return NULL;
4890 hpagesize = gethugepagesize(path);
4891 if (!hpagesize)
4892 return NULL;
4894 fd = mkstemp(filename);
4895 if (fd < 0) {
4896 perror("mkstemp");
4897 free(filename);
4898 return NULL;
4900 unlink(filename);
4901 free(filename);
4903 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4906 * ftruncate is not supported by hugetlbfs in older
4907 * hosts, so don't bother checking for errors.
4908 * If anything goes wrong with it under other filesystems,
4909 * mmap will fail.
4911 ftruncate(fd, memory);
4913 #ifdef MAP_POPULATE
4914 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4915 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4916 * to sidestep this quirk.
4918 flags = mem_prealloc ? MAP_POPULATE|MAP_SHARED : MAP_PRIVATE;
4919 area = mmap(0, memory, PROT_READ|PROT_WRITE, flags, fd, 0);
4920 #else
4921 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4922 #endif
4923 if (area == MAP_FAILED) {
4924 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4925 close(fd);
4926 return (NULL);
4928 *len = memory;
4929 return area;
4931 #endif
4933 #ifndef _WIN32
4935 static void termsig_handler(int signal)
4937 qemu_system_shutdown_request();
4940 static void termsig_setup(void)
4942 struct sigaction act;
4944 memset(&act, 0, sizeof(act));
4945 act.sa_handler = termsig_handler;
4946 sigaction(SIGINT, &act, NULL);
4947 sigaction(SIGHUP, &act, NULL);
4948 sigaction(SIGTERM, &act, NULL);
4951 #endif
4953 int main(int argc, char **argv, char **envp)
4955 #ifdef CONFIG_GDBSTUB
4956 const char *gdbstub_dev = NULL;
4957 #endif
4958 uint32_t boot_devices_bitmap = 0;
4959 int i;
4960 int snapshot, linux_boot, net_boot;
4961 const char *initrd_filename;
4962 const char *kernel_filename, *kernel_cmdline;
4963 const char *boot_devices = "";
4964 DisplayState *ds;
4965 DisplayChangeListener *dcl;
4966 int cyls, heads, secs, translation;
4967 const char *net_clients[MAX_NET_CLIENTS];
4968 int nb_net_clients;
4969 const char *bt_opts[MAX_BT_CMDLINE];
4970 int nb_bt_opts;
4971 int hda_index;
4972 int optind;
4973 const char *r, *optarg;
4974 CharDriverState *monitor_hd = NULL;
4975 const char *monitor_device;
4976 const char *serial_devices[MAX_SERIAL_PORTS];
4977 int serial_device_index;
4978 const char *parallel_devices[MAX_PARALLEL_PORTS];
4979 int parallel_device_index;
4980 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4981 int virtio_console_index;
4982 const char *loadvm = NULL;
4983 QEMUMachine *machine;
4984 const char *cpu_model;
4985 const char *usb_devices[MAX_USB_CMDLINE];
4986 int usb_devices_index;
4987 #ifndef _WIN32
4988 int fds[2];
4989 #endif
4990 int tb_size;
4991 const char *pid_file = NULL;
4992 const char *incoming = NULL;
4993 #ifndef _WIN32
4994 int fd = 0;
4995 struct passwd *pwd = NULL;
4996 const char *chroot_dir = NULL;
4997 const char *run_as = NULL;
4998 #endif
4999 CPUState *env;
5001 qemu_cache_utils_init(envp);
5003 LIST_INIT (&vm_change_state_head);
5004 #ifndef _WIN32
5006 struct sigaction act;
5007 sigfillset(&act.sa_mask);
5008 act.sa_flags = 0;
5009 act.sa_handler = SIG_IGN;
5010 sigaction(SIGPIPE, &act, NULL);
5012 #else
5013 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5014 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5015 QEMU to run on a single CPU */
5017 HANDLE h;
5018 DWORD mask, smask;
5019 int i;
5020 h = GetCurrentProcess();
5021 if (GetProcessAffinityMask(h, &mask, &smask)) {
5022 for(i = 0; i < 32; i++) {
5023 if (mask & (1 << i))
5024 break;
5026 if (i != 32) {
5027 mask = 1 << i;
5028 SetProcessAffinityMask(h, mask);
5032 #endif
5034 register_machines();
5035 machine = first_machine;
5036 cpu_model = NULL;
5037 initrd_filename = NULL;
5038 ram_size = 0;
5039 vga_ram_size = VGA_RAM_SIZE;
5040 snapshot = 0;
5041 nographic = 0;
5042 curses = 0;
5043 kernel_filename = NULL;
5044 kernel_cmdline = "";
5045 cyls = heads = secs = 0;
5046 translation = BIOS_ATA_TRANSLATION_AUTO;
5047 monitor_device = "vc:80Cx24C";
5049 serial_devices[0] = "vc:80Cx24C";
5050 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5051 serial_devices[i] = NULL;
5052 serial_device_index = 0;
5054 parallel_devices[0] = "vc:80Cx24C";
5055 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5056 parallel_devices[i] = NULL;
5057 parallel_device_index = 0;
5059 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
5060 virtio_consoles[i] = NULL;
5061 virtio_console_index = 0;
5063 for (i = 0; i < MAX_NODES; i++) {
5064 node_mem[i] = 0;
5065 node_cpumask[i] = 0;
5068 usb_devices_index = 0;
5069 assigned_devices_index = 0;
5071 nb_net_clients = 0;
5072 nb_bt_opts = 0;
5073 nb_drives = 0;
5074 nb_drives_opt = 0;
5075 nb_numa_nodes = 0;
5076 hda_index = -1;
5078 nb_nics = 0;
5080 tb_size = 0;
5081 autostart= 1;
5083 register_watchdogs();
5085 optind = 1;
5086 for(;;) {
5087 if (optind >= argc)
5088 break;
5089 r = argv[optind];
5090 if (r[0] != '-') {
5091 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5092 } else {
5093 const QEMUOption *popt;
5095 optind++;
5096 /* Treat --foo the same as -foo. */
5097 if (r[1] == '-')
5098 r++;
5099 popt = qemu_options;
5100 for(;;) {
5101 if (!popt->name) {
5102 fprintf(stderr, "%s: invalid option -- '%s'\n",
5103 argv[0], r);
5104 exit(1);
5106 if (!strcmp(popt->name, r + 1))
5107 break;
5108 popt++;
5110 if (popt->flags & HAS_ARG) {
5111 if (optind >= argc) {
5112 fprintf(stderr, "%s: option '%s' requires an argument\n",
5113 argv[0], r);
5114 exit(1);
5116 optarg = argv[optind++];
5117 } else {
5118 optarg = NULL;
5121 switch(popt->index) {
5122 case QEMU_OPTION_M:
5123 machine = find_machine(optarg);
5124 if (!machine) {
5125 QEMUMachine *m;
5126 printf("Supported machines are:\n");
5127 for(m = first_machine; m != NULL; m = m->next) {
5128 printf("%-10s %s%s\n",
5129 m->name, m->desc,
5130 m == first_machine ? " (default)" : "");
5132 exit(*optarg != '?');
5134 break;
5135 case QEMU_OPTION_cpu:
5136 /* hw initialization will check this */
5137 if (*optarg == '?') {
5138 /* XXX: implement xxx_cpu_list for targets that still miss it */
5139 #if defined(cpu_list)
5140 cpu_list(stdout, &fprintf);
5141 #endif
5142 exit(0);
5143 } else {
5144 cpu_model = optarg;
5146 break;
5147 case QEMU_OPTION_initrd:
5148 initrd_filename = optarg;
5149 break;
5150 case QEMU_OPTION_hda:
5151 if (cyls == 0)
5152 hda_index = drive_add(optarg, HD_ALIAS, 0);
5153 else
5154 hda_index = drive_add(optarg, HD_ALIAS
5155 ",cyls=%d,heads=%d,secs=%d%s",
5156 0, cyls, heads, secs,
5157 translation == BIOS_ATA_TRANSLATION_LBA ?
5158 ",trans=lba" :
5159 translation == BIOS_ATA_TRANSLATION_NONE ?
5160 ",trans=none" : "");
5161 break;
5162 case QEMU_OPTION_hdb:
5163 case QEMU_OPTION_hdc:
5164 case QEMU_OPTION_hdd:
5165 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5166 break;
5167 case QEMU_OPTION_drive:
5168 drive_add(NULL, "%s", optarg);
5169 break;
5170 case QEMU_OPTION_mtdblock:
5171 drive_add(optarg, MTD_ALIAS);
5172 break;
5173 case QEMU_OPTION_sd:
5174 drive_add(optarg, SD_ALIAS);
5175 break;
5176 case QEMU_OPTION_pflash:
5177 drive_add(optarg, PFLASH_ALIAS);
5178 break;
5179 case QEMU_OPTION_snapshot:
5180 snapshot = 1;
5181 break;
5182 case QEMU_OPTION_hdachs:
5184 const char *p;
5185 p = optarg;
5186 cyls = strtol(p, (char **)&p, 0);
5187 if (cyls < 1 || cyls > 16383)
5188 goto chs_fail;
5189 if (*p != ',')
5190 goto chs_fail;
5191 p++;
5192 heads = strtol(p, (char **)&p, 0);
5193 if (heads < 1 || heads > 16)
5194 goto chs_fail;
5195 if (*p != ',')
5196 goto chs_fail;
5197 p++;
5198 secs = strtol(p, (char **)&p, 0);
5199 if (secs < 1 || secs > 63)
5200 goto chs_fail;
5201 if (*p == ',') {
5202 p++;
5203 if (!strcmp(p, "none"))
5204 translation = BIOS_ATA_TRANSLATION_NONE;
5205 else if (!strcmp(p, "lba"))
5206 translation = BIOS_ATA_TRANSLATION_LBA;
5207 else if (!strcmp(p, "auto"))
5208 translation = BIOS_ATA_TRANSLATION_AUTO;
5209 else
5210 goto chs_fail;
5211 } else if (*p != '\0') {
5212 chs_fail:
5213 fprintf(stderr, "qemu: invalid physical CHS format\n");
5214 exit(1);
5216 if (hda_index != -1)
5217 snprintf(drives_opt[hda_index].opt,
5218 sizeof(drives_opt[hda_index].opt),
5219 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5220 0, cyls, heads, secs,
5221 translation == BIOS_ATA_TRANSLATION_LBA ?
5222 ",trans=lba" :
5223 translation == BIOS_ATA_TRANSLATION_NONE ?
5224 ",trans=none" : "");
5226 break;
5227 case QEMU_OPTION_numa:
5228 if (nb_numa_nodes >= MAX_NODES) {
5229 fprintf(stderr, "qemu: too many NUMA nodes\n");
5230 exit(1);
5232 numa_add(optarg);
5233 break;
5234 case QEMU_OPTION_nographic:
5235 nographic = 1;
5236 break;
5237 #ifdef CONFIG_CURSES
5238 case QEMU_OPTION_curses:
5239 curses = 1;
5240 break;
5241 #endif
5242 case QEMU_OPTION_portrait:
5243 graphic_rotate = 1;
5244 break;
5245 case QEMU_OPTION_kernel:
5246 kernel_filename = optarg;
5247 break;
5248 case QEMU_OPTION_append:
5249 kernel_cmdline = optarg;
5250 break;
5251 case QEMU_OPTION_cdrom:
5252 drive_add(optarg, CDROM_ALIAS);
5253 break;
5254 case QEMU_OPTION_boot:
5255 boot_devices = optarg;
5256 /* We just do some generic consistency checks */
5258 /* Could easily be extended to 64 devices if needed */
5259 const char *p;
5261 boot_devices_bitmap = 0;
5262 for (p = boot_devices; *p != '\0'; p++) {
5263 /* Allowed boot devices are:
5264 * a b : floppy disk drives
5265 * c ... f : IDE disk drives
5266 * g ... m : machine implementation dependant drives
5267 * n ... p : network devices
5268 * It's up to each machine implementation to check
5269 * if the given boot devices match the actual hardware
5270 * implementation and firmware features.
5272 if (*p < 'a' || *p > 'q') {
5273 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5274 exit(1);
5276 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5277 fprintf(stderr,
5278 "Boot device '%c' was given twice\n",*p);
5279 exit(1);
5281 boot_devices_bitmap |= 1 << (*p - 'a');
5284 break;
5285 case QEMU_OPTION_fda:
5286 case QEMU_OPTION_fdb:
5287 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5288 break;
5289 #ifdef TARGET_I386
5290 case QEMU_OPTION_no_fd_bootchk:
5291 fd_bootchk = 0;
5292 break;
5293 #endif
5294 case QEMU_OPTION_net:
5295 if (nb_net_clients >= MAX_NET_CLIENTS) {
5296 fprintf(stderr, "qemu: too many network clients\n");
5297 exit(1);
5299 net_clients[nb_net_clients] = optarg;
5300 nb_net_clients++;
5301 break;
5302 #ifdef CONFIG_SLIRP
5303 case QEMU_OPTION_tftp:
5304 tftp_prefix = optarg;
5305 break;
5306 case QEMU_OPTION_bootp:
5307 bootp_filename = optarg;
5308 break;
5309 #ifndef _WIN32
5310 case QEMU_OPTION_smb:
5311 net_slirp_smb(optarg);
5312 break;
5313 #endif
5314 case QEMU_OPTION_redir:
5315 net_slirp_redir(NULL, optarg);
5316 break;
5317 #endif
5318 case QEMU_OPTION_bt:
5319 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5320 fprintf(stderr, "qemu: too many bluetooth options\n");
5321 exit(1);
5323 bt_opts[nb_bt_opts++] = optarg;
5324 break;
5325 #ifdef HAS_AUDIO
5326 case QEMU_OPTION_audio_help:
5327 AUD_help ();
5328 exit (0);
5329 break;
5330 case QEMU_OPTION_soundhw:
5331 select_soundhw (optarg);
5332 break;
5333 #endif
5334 case QEMU_OPTION_h:
5335 help(0);
5336 break;
5337 case QEMU_OPTION_version:
5338 version();
5339 exit(0);
5340 break;
5341 case QEMU_OPTION_m: {
5342 uint64_t value;
5343 char *ptr;
5345 value = strtoul(optarg, &ptr, 10);
5346 switch (*ptr) {
5347 case 0: case 'M': case 'm':
5348 value <<= 20;
5349 break;
5350 case 'G': case 'g':
5351 value <<= 30;
5352 break;
5353 default:
5354 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5355 exit(1);
5358 /* On 32-bit hosts, QEMU is limited by virtual address space */
5359 if (value > (2047 << 20)
5360 #ifndef CONFIG_KQEMU
5361 && HOST_LONG_BITS == 32
5362 #endif
5364 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5365 exit(1);
5367 if (value != (uint64_t)(ram_addr_t)value) {
5368 fprintf(stderr, "qemu: ram size too large\n");
5369 exit(1);
5371 ram_size = value;
5372 break;
5374 case QEMU_OPTION_d:
5376 int mask;
5377 const CPULogItem *item;
5379 mask = cpu_str_to_log_mask(optarg);
5380 if (!mask) {
5381 printf("Log items (comma separated):\n");
5382 for(item = cpu_log_items; item->mask != 0; item++) {
5383 printf("%-10s %s\n", item->name, item->help);
5385 exit(1);
5387 cpu_set_log(mask);
5389 break;
5390 #ifdef CONFIG_GDBSTUB
5391 case QEMU_OPTION_s:
5392 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5393 break;
5394 case QEMU_OPTION_gdb:
5395 gdbstub_dev = optarg;
5396 break;
5397 #endif
5398 case QEMU_OPTION_L:
5399 bios_dir = optarg;
5400 break;
5401 case QEMU_OPTION_bios:
5402 bios_name = optarg;
5403 break;
5404 case QEMU_OPTION_singlestep:
5405 singlestep = 1;
5406 break;
5407 case QEMU_OPTION_S:
5408 autostart = 0;
5409 break;
5410 #ifndef _WIN32
5411 case QEMU_OPTION_k:
5412 keyboard_layout = optarg;
5413 break;
5414 #endif
5415 case QEMU_OPTION_localtime:
5416 rtc_utc = 0;
5417 break;
5418 case QEMU_OPTION_vga:
5419 select_vgahw (optarg);
5420 break;
5421 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5422 case QEMU_OPTION_g:
5424 const char *p;
5425 int w, h, depth;
5426 p = optarg;
5427 w = strtol(p, (char **)&p, 10);
5428 if (w <= 0) {
5429 graphic_error:
5430 fprintf(stderr, "qemu: invalid resolution or depth\n");
5431 exit(1);
5433 if (*p != 'x')
5434 goto graphic_error;
5435 p++;
5436 h = strtol(p, (char **)&p, 10);
5437 if (h <= 0)
5438 goto graphic_error;
5439 if (*p == 'x') {
5440 p++;
5441 depth = strtol(p, (char **)&p, 10);
5442 if (depth != 8 && depth != 15 && depth != 16 &&
5443 depth != 24 && depth != 32)
5444 goto graphic_error;
5445 } else if (*p == '\0') {
5446 depth = graphic_depth;
5447 } else {
5448 goto graphic_error;
5451 graphic_width = w;
5452 graphic_height = h;
5453 graphic_depth = depth;
5455 break;
5456 #endif
5457 case QEMU_OPTION_echr:
5459 char *r;
5460 term_escape_char = strtol(optarg, &r, 0);
5461 if (r == optarg)
5462 printf("Bad argument to echr\n");
5463 break;
5465 case QEMU_OPTION_monitor:
5466 monitor_device = optarg;
5467 break;
5468 case QEMU_OPTION_serial:
5469 if (serial_device_index >= MAX_SERIAL_PORTS) {
5470 fprintf(stderr, "qemu: too many serial ports\n");
5471 exit(1);
5473 serial_devices[serial_device_index] = optarg;
5474 serial_device_index++;
5475 break;
5476 case QEMU_OPTION_watchdog:
5477 i = select_watchdog(optarg);
5478 if (i > 0)
5479 exit (i == 1 ? 1 : 0);
5480 break;
5481 case QEMU_OPTION_watchdog_action:
5482 if (select_watchdog_action(optarg) == -1) {
5483 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5484 exit(1);
5486 break;
5487 case QEMU_OPTION_virtiocon:
5488 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5489 fprintf(stderr, "qemu: too many virtio consoles\n");
5490 exit(1);
5492 virtio_consoles[virtio_console_index] = optarg;
5493 virtio_console_index++;
5494 break;
5495 case QEMU_OPTION_parallel:
5496 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5497 fprintf(stderr, "qemu: too many parallel ports\n");
5498 exit(1);
5500 parallel_devices[parallel_device_index] = optarg;
5501 parallel_device_index++;
5502 break;
5503 case QEMU_OPTION_loadvm:
5504 loadvm = optarg;
5505 break;
5506 case QEMU_OPTION_full_screen:
5507 full_screen = 1;
5508 break;
5509 #ifdef CONFIG_SDL
5510 case QEMU_OPTION_no_frame:
5511 no_frame = 1;
5512 break;
5513 case QEMU_OPTION_alt_grab:
5514 alt_grab = 1;
5515 break;
5516 case QEMU_OPTION_no_quit:
5517 no_quit = 1;
5518 break;
5519 case QEMU_OPTION_sdl:
5520 sdl = 1;
5521 break;
5522 #endif
5523 case QEMU_OPTION_pidfile:
5524 pid_file = optarg;
5525 break;
5526 #ifdef TARGET_I386
5527 case QEMU_OPTION_win2k_hack:
5528 win2k_install_hack = 1;
5529 break;
5530 case QEMU_OPTION_rtc_td_hack:
5531 rtc_td_hack = 1;
5532 break;
5533 case QEMU_OPTION_acpitable:
5534 if(acpi_table_add(optarg) < 0) {
5535 fprintf(stderr, "Wrong acpi table provided\n");
5536 exit(1);
5538 break;
5539 case QEMU_OPTION_smbios:
5540 if(smbios_entry_add(optarg) < 0) {
5541 fprintf(stderr, "Wrong smbios provided\n");
5542 exit(1);
5544 break;
5545 #endif
5546 #ifdef CONFIG_KQEMU
5547 case QEMU_OPTION_no_kqemu:
5548 kqemu_allowed = 0;
5549 break;
5550 case QEMU_OPTION_kernel_kqemu:
5551 kqemu_allowed = 2;
5552 break;
5553 #endif
5554 #ifdef CONFIG_KVM
5555 case QEMU_OPTION_enable_kvm:
5556 kvm_allowed = 1;
5557 #ifdef CONFIG_KQEMU
5558 kqemu_allowed = 0;
5559 #endif
5560 break;
5561 #endif
5562 #ifdef USE_KVM
5563 case QEMU_OPTION_no_kvm:
5564 kvm_allowed = 0;
5565 break;
5566 case QEMU_OPTION_no_kvm_irqchip: {
5567 kvm_irqchip = 0;
5568 kvm_pit = 0;
5569 break;
5571 case QEMU_OPTION_no_kvm_pit: {
5572 kvm_pit = 0;
5573 break;
5575 case QEMU_OPTION_no_kvm_pit_reinjection: {
5576 kvm_pit_reinject = 0;
5577 break;
5579 case QEMU_OPTION_enable_nesting: {
5580 kvm_nested = 1;
5581 break;
5583 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5584 case QEMU_OPTION_pcidevice:
5585 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5586 fprintf(stderr, "Too many assigned devices\n");
5587 exit(1);
5589 assigned_devices[assigned_devices_index] = optarg;
5590 assigned_devices_index++;
5591 break;
5592 #endif
5593 #endif
5594 case QEMU_OPTION_usb:
5595 usb_enabled = 1;
5596 break;
5597 case QEMU_OPTION_usbdevice:
5598 usb_enabled = 1;
5599 if (usb_devices_index >= MAX_USB_CMDLINE) {
5600 fprintf(stderr, "Too many USB devices\n");
5601 exit(1);
5603 usb_devices[usb_devices_index] = optarg;
5604 usb_devices_index++;
5605 break;
5606 case QEMU_OPTION_smp:
5607 smp_cpus = atoi(optarg);
5608 if (smp_cpus < 1) {
5609 fprintf(stderr, "Invalid number of CPUs\n");
5610 exit(1);
5612 break;
5613 case QEMU_OPTION_vnc:
5614 vnc_display = optarg;
5615 break;
5616 #ifdef TARGET_I386
5617 case QEMU_OPTION_no_acpi:
5618 acpi_enabled = 0;
5619 break;
5620 case QEMU_OPTION_no_hpet:
5621 no_hpet = 1;
5622 break;
5623 #endif
5624 case QEMU_OPTION_no_reboot:
5625 no_reboot = 1;
5626 break;
5627 case QEMU_OPTION_no_shutdown:
5628 no_shutdown = 1;
5629 break;
5630 case QEMU_OPTION_show_cursor:
5631 cursor_hide = 0;
5632 break;
5633 case QEMU_OPTION_uuid:
5634 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5635 fprintf(stderr, "Fail to parse UUID string."
5636 " Wrong format.\n");
5637 exit(1);
5639 break;
5640 #ifndef _WIN32
5641 case QEMU_OPTION_daemonize:
5642 daemonize = 1;
5643 break;
5644 #endif
5645 case QEMU_OPTION_option_rom:
5646 if (nb_option_roms >= MAX_OPTION_ROMS) {
5647 fprintf(stderr, "Too many option ROMs\n");
5648 exit(1);
5650 option_rom[nb_option_roms] = optarg;
5651 nb_option_roms++;
5652 break;
5653 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5654 case QEMU_OPTION_semihosting:
5655 semihosting_enabled = 1;
5656 break;
5657 #endif
5658 case QEMU_OPTION_tdf:
5659 time_drift_fix = 1;
5660 break;
5661 case QEMU_OPTION_kvm_shadow_memory:
5662 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5663 break;
5664 case QEMU_OPTION_mempath:
5665 mem_path = optarg;
5666 break;
5667 #ifdef MAP_POPULATE
5668 case QEMU_OPTION_mem_prealloc:
5669 mem_prealloc = !mem_prealloc;
5670 break;
5671 #endif
5672 case QEMU_OPTION_name:
5673 qemu_name = optarg;
5674 break;
5675 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5676 case QEMU_OPTION_prom_env:
5677 if (nb_prom_envs >= MAX_PROM_ENVS) {
5678 fprintf(stderr, "Too many prom variables\n");
5679 exit(1);
5681 prom_envs[nb_prom_envs] = optarg;
5682 nb_prom_envs++;
5683 break;
5684 #endif
5685 #ifdef TARGET_ARM
5686 case QEMU_OPTION_old_param:
5687 old_param = 1;
5688 break;
5689 #endif
5690 case QEMU_OPTION_clock:
5691 configure_alarms(optarg);
5692 break;
5693 case QEMU_OPTION_startdate:
5695 struct tm tm;
5696 time_t rtc_start_date;
5697 if (!strcmp(optarg, "now")) {
5698 rtc_date_offset = -1;
5699 } else {
5700 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5701 &tm.tm_year,
5702 &tm.tm_mon,
5703 &tm.tm_mday,
5704 &tm.tm_hour,
5705 &tm.tm_min,
5706 &tm.tm_sec) == 6) {
5707 /* OK */
5708 } else if (sscanf(optarg, "%d-%d-%d",
5709 &tm.tm_year,
5710 &tm.tm_mon,
5711 &tm.tm_mday) == 3) {
5712 tm.tm_hour = 0;
5713 tm.tm_min = 0;
5714 tm.tm_sec = 0;
5715 } else {
5716 goto date_fail;
5718 tm.tm_year -= 1900;
5719 tm.tm_mon--;
5720 rtc_start_date = mktimegm(&tm);
5721 if (rtc_start_date == -1) {
5722 date_fail:
5723 fprintf(stderr, "Invalid date format. Valid format are:\n"
5724 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5725 exit(1);
5727 rtc_date_offset = time(NULL) - rtc_start_date;
5730 break;
5731 case QEMU_OPTION_tb_size:
5732 tb_size = strtol(optarg, NULL, 0);
5733 if (tb_size < 0)
5734 tb_size = 0;
5735 break;
5736 case QEMU_OPTION_icount:
5737 use_icount = 1;
5738 if (strcmp(optarg, "auto") == 0) {
5739 icount_time_shift = -1;
5740 } else {
5741 icount_time_shift = strtol(optarg, NULL, 0);
5743 break;
5744 case QEMU_OPTION_incoming:
5745 incoming = optarg;
5746 break;
5747 #ifndef _WIN32
5748 case QEMU_OPTION_chroot:
5749 chroot_dir = optarg;
5750 break;
5751 case QEMU_OPTION_runas:
5752 run_as = optarg;
5753 break;
5754 case QEMU_OPTION_nvram:
5755 nvram = optarg;
5756 break;
5757 #endif
5758 #ifdef CONFIG_XEN
5759 case QEMU_OPTION_xen_domid:
5760 xen_domid = atoi(optarg);
5761 break;
5762 case QEMU_OPTION_xen_create:
5763 xen_mode = XEN_CREATE;
5764 break;
5765 case QEMU_OPTION_xen_attach:
5766 xen_mode = XEN_ATTACH;
5767 break;
5768 #endif
5773 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5774 if (kvm_allowed && kqemu_allowed) {
5775 fprintf(stderr,
5776 "You can not enable both KVM and kqemu at the same time\n");
5777 exit(1);
5779 #endif
5781 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5782 if (smp_cpus > machine->max_cpus) {
5783 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5784 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5785 machine->max_cpus);
5786 exit(1);
5789 if (nographic) {
5790 if (serial_device_index == 0)
5791 serial_devices[0] = "stdio";
5792 if (parallel_device_index == 0)
5793 parallel_devices[0] = "null";
5794 if (strncmp(monitor_device, "vc", 2) == 0)
5795 monitor_device = "stdio";
5798 #ifndef _WIN32
5799 if (daemonize) {
5800 pid_t pid;
5802 if (pipe(fds) == -1)
5803 exit(1);
5805 pid = fork();
5806 if (pid > 0) {
5807 uint8_t status;
5808 ssize_t len;
5810 close(fds[1]);
5812 again:
5813 len = read(fds[0], &status, 1);
5814 if (len == -1 && (errno == EINTR))
5815 goto again;
5817 if (len != 1)
5818 exit(1);
5819 else if (status == 1) {
5820 fprintf(stderr, "Could not acquire pidfile\n");
5821 exit(1);
5822 } else
5823 exit(0);
5824 } else if (pid < 0)
5825 exit(1);
5827 setsid();
5829 pid = fork();
5830 if (pid > 0)
5831 exit(0);
5832 else if (pid < 0)
5833 exit(1);
5835 umask(027);
5837 signal(SIGTSTP, SIG_IGN);
5838 signal(SIGTTOU, SIG_IGN);
5839 signal(SIGTTIN, SIG_IGN);
5842 #ifdef USE_KVM
5843 if (kvm_enabled()) {
5844 if (kvm_qemu_init() < 0) {
5845 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5846 #ifdef NO_CPU_EMULATION
5847 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5848 exit(1);
5849 #endif
5850 kvm_allowed = 0;
5853 #endif
5855 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5856 if (daemonize) {
5857 uint8_t status = 1;
5858 write(fds[1], &status, 1);
5859 } else
5860 fprintf(stderr, "Could not acquire pid file\n");
5861 exit(1);
5863 #endif
5865 #ifdef CONFIG_KQEMU
5866 if (smp_cpus > 1)
5867 kqemu_allowed = 0;
5868 #endif
5869 if (qemu_init_main_loop()) {
5870 fprintf(stderr, "qemu_init_main_loop failed\n");
5871 exit(1);
5873 linux_boot = (kernel_filename != NULL);
5874 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5876 if (!linux_boot && *kernel_cmdline != '\0') {
5877 fprintf(stderr, "-append only allowed with -kernel option\n");
5878 exit(1);
5881 if (!linux_boot && initrd_filename != NULL) {
5882 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5883 exit(1);
5886 /* boot to floppy or the default cd if no hard disk defined yet */
5887 if (!boot_devices[0]) {
5888 boot_devices = "cad";
5890 setvbuf(stdout, NULL, _IOLBF, 0);
5892 init_timers();
5893 if (init_timer_alarm() < 0) {
5894 fprintf(stderr, "could not initialize alarm timer\n");
5895 exit(1);
5897 if (use_icount && icount_time_shift < 0) {
5898 use_icount = 2;
5899 /* 125MIPS seems a reasonable initial guess at the guest speed.
5900 It will be corrected fairly quickly anyway. */
5901 icount_time_shift = 3;
5902 init_icount_adjust();
5905 #ifdef _WIN32
5906 socket_init();
5907 #endif
5909 /* init network clients */
5910 if (nb_net_clients == 0) {
5911 /* if no clients, we use a default config */
5912 net_clients[nb_net_clients++] = "nic";
5913 #ifdef CONFIG_SLIRP
5914 net_clients[nb_net_clients++] = "user";
5915 #endif
5918 for(i = 0;i < nb_net_clients; i++) {
5919 if (net_client_parse(net_clients[i]) < 0)
5920 exit(1);
5922 net_client_check();
5924 #ifdef TARGET_I386
5925 /* XXX: this should be moved in the PC machine instantiation code */
5926 if (net_boot != 0) {
5927 int netroms = 0;
5928 for (i = 0; i < nb_nics && i < 4; i++) {
5929 const char *model = nd_table[i].model;
5930 char buf[1024];
5931 if (net_boot & (1 << i)) {
5932 if (model == NULL)
5933 model = "rtl8139";
5934 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5935 if (get_image_size(buf) > 0) {
5936 if (nb_option_roms >= MAX_OPTION_ROMS) {
5937 fprintf(stderr, "Too many option ROMs\n");
5938 exit(1);
5940 option_rom[nb_option_roms] = strdup(buf);
5941 nb_option_roms++;
5942 netroms++;
5946 if (netroms == 0) {
5947 fprintf(stderr, "No valid PXE rom found for network device\n");
5948 exit(1);
5951 #endif
5953 /* init the bluetooth world */
5954 for (i = 0; i < nb_bt_opts; i++)
5955 if (bt_parse(bt_opts[i]))
5956 exit(1);
5958 /* init the memory */
5959 if (ram_size == 0)
5960 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5962 if (kvm_enabled()) {
5963 if (kvm_qemu_create_context() < 0) {
5964 fprintf(stderr, "Could not create KVM context\n");
5965 exit(1);
5969 #ifdef CONFIG_KQEMU
5970 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5971 guest ram allocation. It needs to go away. */
5972 if (kqemu_allowed) {
5973 kqemu_phys_ram_size = ram_size + VGA_RAM_SIZE + 4 * 1024 * 1024;
5974 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5975 if (!kqemu_phys_ram_base) {
5976 fprintf(stderr, "Could not allocate physical memory\n");
5977 exit(1);
5980 #endif
5982 /* init the dynamic translator */
5983 cpu_exec_init_all(tb_size * 1024 * 1024);
5985 bdrv_init();
5986 dma_helper_init();
5988 /* we always create the cdrom drive, even if no disk is there */
5990 if (nb_drives_opt < MAX_DRIVES)
5991 drive_add(NULL, CDROM_ALIAS);
5993 /* we always create at least one floppy */
5995 if (nb_drives_opt < MAX_DRIVES)
5996 drive_add(NULL, FD_ALIAS, 0);
5998 /* we always create one sd slot, even if no card is in it */
6000 if (nb_drives_opt < MAX_DRIVES)
6001 drive_add(NULL, SD_ALIAS);
6003 /* open the virtual block devices
6004 * note that migration with device
6005 * hot add/remove is broken.
6007 for(i = 0; i < nb_drives_opt; i++)
6008 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
6009 exit(1);
6011 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6012 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
6014 #ifndef _WIN32
6015 /* must be after terminal init, SDL library changes signal handlers */
6016 termsig_setup();
6017 #endif
6019 /* Maintain compatibility with multiple stdio monitors */
6020 if (!strcmp(monitor_device,"stdio")) {
6021 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
6022 const char *devname = serial_devices[i];
6023 if (devname && !strcmp(devname,"mon:stdio")) {
6024 monitor_device = NULL;
6025 break;
6026 } else if (devname && !strcmp(devname,"stdio")) {
6027 monitor_device = NULL;
6028 serial_devices[i] = "mon:stdio";
6029 break;
6034 if (nb_numa_nodes > 0) {
6035 int i;
6037 if (nb_numa_nodes > smp_cpus) {
6038 nb_numa_nodes = smp_cpus;
6041 /* If no memory size if given for any node, assume the default case
6042 * and distribute the available memory equally across all nodes
6044 for (i = 0; i < nb_numa_nodes; i++) {
6045 if (node_mem[i] != 0)
6046 break;
6048 if (i == nb_numa_nodes) {
6049 uint64_t usedmem = 0;
6051 /* On Linux, the each node's border has to be 8MB aligned,
6052 * the final node gets the rest.
6054 for (i = 0; i < nb_numa_nodes - 1; i++) {
6055 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
6056 usedmem += node_mem[i];
6058 node_mem[i] = ram_size - usedmem;
6061 for (i = 0; i < nb_numa_nodes; i++) {
6062 if (node_cpumask[i] != 0)
6063 break;
6065 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6066 * must cope with this anyway, because there are BIOSes out there in
6067 * real machines which also use this scheme.
6069 if (i == nb_numa_nodes) {
6070 for (i = 0; i < smp_cpus; i++) {
6071 node_cpumask[i % nb_numa_nodes] |= 1 << i;
6076 #ifdef KVM_UPSTREAM
6077 if (kvm_enabled()) {
6078 int ret;
6080 ret = kvm_init(smp_cpus);
6081 if (ret < 0) {
6082 fprintf(stderr, "failed to initialize KVM\n");
6083 exit(1);
6086 #endif
6088 if (monitor_device) {
6089 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
6090 if (!monitor_hd) {
6091 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6092 exit(1);
6096 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6097 const char *devname = serial_devices[i];
6098 if (devname && strcmp(devname, "none")) {
6099 char label[32];
6100 snprintf(label, sizeof(label), "serial%d", i);
6101 serial_hds[i] = qemu_chr_open(label, devname, NULL);
6102 if (!serial_hds[i]) {
6103 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6104 devname);
6105 exit(1);
6110 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6111 const char *devname = parallel_devices[i];
6112 if (devname && strcmp(devname, "none")) {
6113 char label[32];
6114 snprintf(label, sizeof(label), "parallel%d", i);
6115 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
6116 if (!parallel_hds[i]) {
6117 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6118 devname);
6119 exit(1);
6124 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6125 const char *devname = virtio_consoles[i];
6126 if (devname && strcmp(devname, "none")) {
6127 char label[32];
6128 snprintf(label, sizeof(label), "virtcon%d", i);
6129 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
6130 if (!virtcon_hds[i]) {
6131 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
6132 devname);
6133 exit(1);
6138 if (kvm_enabled())
6139 kvm_init_ap();
6141 machine->init(ram_size, vga_ram_size, boot_devices,
6142 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6145 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6146 for (i = 0; i < nb_numa_nodes; i++) {
6147 if (node_cpumask[i] & (1 << env->cpu_index)) {
6148 env->numa_node = i;
6153 current_machine = machine;
6155 /* Set KVM's vcpu state to qemu's initial CPUState. */
6156 if (kvm_enabled()) {
6157 int ret;
6159 ret = kvm_sync_vcpus();
6160 if (ret < 0) {
6161 fprintf(stderr, "failed to initialize vcpus\n");
6162 exit(1);
6166 /* init USB devices */
6167 if (usb_enabled) {
6168 for(i = 0; i < usb_devices_index; i++) {
6169 if (usb_device_add(usb_devices[i], 0) < 0) {
6170 fprintf(stderr, "Warning: could not add USB device %s\n",
6171 usb_devices[i]);
6176 if (!display_state)
6177 dumb_display_init();
6178 /* just use the first displaystate for the moment */
6179 ds = display_state;
6180 /* terminal init */
6181 if (nographic) {
6182 if (curses) {
6183 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
6184 exit(1);
6186 } else {
6187 #if defined(CONFIG_CURSES)
6188 if (curses) {
6189 /* At the moment curses cannot be used with other displays */
6190 curses_display_init(ds, full_screen);
6191 } else
6192 #endif
6194 if (vnc_display != NULL) {
6195 vnc_display_init(ds);
6196 if (vnc_display_open(ds, vnc_display) < 0)
6197 exit(1);
6199 #if defined(CONFIG_SDL)
6200 if (sdl || !vnc_display)
6201 sdl_display_init(ds, full_screen, no_frame);
6202 #elif defined(CONFIG_COCOA)
6203 if (sdl || !vnc_display)
6204 cocoa_display_init(ds, full_screen);
6205 #endif
6208 dpy_resize(ds);
6210 dcl = ds->listeners;
6211 while (dcl != NULL) {
6212 if (dcl->dpy_refresh != NULL) {
6213 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6214 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6216 dcl = dcl->next;
6219 if (nographic || (vnc_display && !sdl)) {
6220 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6221 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6224 text_consoles_set_display(display_state);
6225 qemu_chr_initial_reset();
6227 if (monitor_device && monitor_hd)
6228 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6230 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6231 const char *devname = serial_devices[i];
6232 if (devname && strcmp(devname, "none")) {
6233 char label[32];
6234 snprintf(label, sizeof(label), "serial%d", i);
6235 if (strstart(devname, "vc", 0))
6236 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6240 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6241 const char *devname = parallel_devices[i];
6242 if (devname && strcmp(devname, "none")) {
6243 char label[32];
6244 snprintf(label, sizeof(label), "parallel%d", i);
6245 if (strstart(devname, "vc", 0))
6246 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6250 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6251 const char *devname = virtio_consoles[i];
6252 if (virtcon_hds[i] && devname) {
6253 char label[32];
6254 snprintf(label, sizeof(label), "virtcon%d", i);
6255 if (strstart(devname, "vc", 0))
6256 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6260 #ifdef CONFIG_GDBSTUB
6261 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6262 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6263 gdbstub_dev);
6264 exit(1);
6266 #endif
6268 if (loadvm)
6269 do_loadvm(cur_mon, loadvm);
6271 if (incoming) {
6272 autostart = 0; /* fixme how to deal with -daemonize */
6273 qemu_start_incoming_migration(incoming);
6276 if (autostart)
6277 vm_start();
6279 #ifndef _WIN32
6280 if (daemonize) {
6281 uint8_t status = 0;
6282 ssize_t len;
6284 again1:
6285 len = write(fds[1], &status, 1);
6286 if (len == -1 && (errno == EINTR))
6287 goto again1;
6289 if (len != 1)
6290 exit(1);
6292 chdir("/");
6293 TFR(fd = open("/dev/null", O_RDWR));
6294 if (fd == -1)
6295 exit(1);
6298 if (run_as) {
6299 pwd = getpwnam(run_as);
6300 if (!pwd) {
6301 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6302 exit(1);
6306 if (chroot_dir) {
6307 if (chroot(chroot_dir) < 0) {
6308 fprintf(stderr, "chroot failed\n");
6309 exit(1);
6311 chdir("/");
6314 if (run_as) {
6315 if (setgid(pwd->pw_gid) < 0) {
6316 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6317 exit(1);
6319 if (setuid(pwd->pw_uid) < 0) {
6320 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6321 exit(1);
6323 if (setuid(0) != -1) {
6324 fprintf(stderr, "Dropping privileges failed\n");
6325 exit(1);
6329 if (daemonize) {
6330 dup2(fd, 0);
6331 dup2(fd, 1);
6332 dup2(fd, 2);
6334 close(fd);
6336 #endif
6338 main_loop();
6339 quit_timers();
6340 net_cleanup();
6342 return 0;