Refactor persistent CPU state
[qemu-kvm/fedora.git] / vl.c
blobdb8265baff43dafa97f952f34290438e8ae307b9
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-option.h"
161 #include "qemu-kvm.h"
162 #include "hw/device-assignment.h"
164 #include "disas.h"
166 #include "exec-all.h"
168 #include "qemu_socket.h"
170 #if defined(CONFIG_SLIRP)
171 #include "libslirp.h"
172 #endif
174 //#define DEBUG_UNUSED_IOPORT
175 //#define DEBUG_IOPORT
176 //#define DEBUG_NET
177 //#define DEBUG_SLIRP
180 #ifdef DEBUG_IOPORT
181 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
182 #else
183 # define LOG_IOPORT(...) do { } while (0)
184 #endif
186 #define DEFAULT_RAM_SIZE 128
188 /* Max number of USB devices that can be specified on the commandline. */
189 #define MAX_USB_CMDLINE 8
191 /* Max number of bluetooth switches on the commandline. */
192 #define MAX_BT_CMDLINE 10
194 /* XXX: use a two level table to limit memory usage */
195 #define MAX_IOPORTS 65536
197 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
198 const char *bios_name = NULL;
199 static void *ioport_opaque[MAX_IOPORTS];
200 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
201 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
202 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
203 to store the VM snapshots */
204 DriveInfo drives_table[MAX_DRIVES+1];
205 int nb_drives;
206 int extboot_drive = -1;
207 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
208 static DisplayState *display_state;
209 DisplayType display_type = DT_DEFAULT;
210 const char* keyboard_layout = NULL;
211 int64_t ticks_per_sec;
212 ram_addr_t ram_size;
213 int nb_nics;
214 NICInfo nd_table[MAX_NICS];
215 int vm_running;
216 static int autostart;
217 static int rtc_utc = 1;
218 static int rtc_date_offset = -1; /* -1 means no change */
219 int cirrus_vga_enabled = 1;
220 int std_vga_enabled = 0;
221 int vmsvga_enabled = 0;
222 int xenfb_enabled = 0;
223 #ifdef TARGET_SPARC
224 int graphic_width = 1024;
225 int graphic_height = 768;
226 int graphic_depth = 8;
227 #else
228 int graphic_width = 800;
229 int graphic_height = 600;
230 int graphic_depth = 15;
231 #endif
232 static int full_screen = 0;
233 #ifdef CONFIG_SDL
234 static int no_frame = 0;
235 #endif
236 int no_quit = 0;
237 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
238 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
239 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
240 #ifdef TARGET_I386
241 int win2k_install_hack = 0;
242 int rtc_td_hack = 0;
243 #endif
244 int usb_enabled = 0;
245 int singlestep = 0;
246 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
247 int assigned_devices_index;
248 int smp_cpus = 1;
249 const char *vnc_display;
250 int acpi_enabled = 1;
251 int no_hpet = 0;
252 int fd_bootchk = 1;
253 int no_reboot = 0;
254 int no_shutdown = 0;
255 int cursor_hide = 1;
256 int graphic_rotate = 0;
257 #ifndef _WIN32
258 int daemonize = 0;
259 #endif
260 WatchdogTimerModel *watchdog = NULL;
261 int watchdog_action = WDT_RESET;
262 const char *option_rom[MAX_OPTION_ROMS];
263 int nb_option_roms;
264 int semihosting_enabled = 0;
265 int time_drift_fix = 0;
266 unsigned int kvm_shadow_memory = 0;
267 const char *mem_path = NULL;
268 #ifdef MAP_POPULATE
269 int mem_prealloc = 1; /* force preallocation of physical target memory */
270 #endif
271 long hpagesize = 0;
272 #ifdef TARGET_ARM
273 int old_param = 0;
274 #endif
275 const char *qemu_name;
276 int alt_grab = 0;
277 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
278 unsigned int nb_prom_envs = 0;
279 const char *prom_envs[MAX_PROM_ENVS];
280 #endif
281 int nb_drives_opt;
282 const char *nvram = NULL;
283 struct drive_opt drives_opt[MAX_DRIVES];
285 int nb_numa_nodes;
286 uint64_t node_mem[MAX_NODES];
287 uint64_t node_cpumask[MAX_NODES];
289 static CPUState *cur_cpu;
290 static CPUState *next_cpu;
291 static int timer_alarm_pending = 1;
292 /* Conversion factor from emulated instructions to virtual clock ticks. */
293 static int icount_time_shift;
294 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
295 #define MAX_ICOUNT_SHIFT 10
296 /* Compensate for varying guest execution speed. */
297 static int64_t qemu_icount_bias;
298 static QEMUTimer *icount_rt_timer;
299 static QEMUTimer *icount_vm_timer;
300 static QEMUTimer *nographic_timer;
302 uint8_t qemu_uuid[16];
304 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
305 struct timeval *tv)
307 int ret;
309 /* KVM holds a mutex while QEMU code is running, we need hooks to
310 release the mutex whenever QEMU code sleeps. */
312 kvm_sleep_begin();
314 ret = select(max_fd, rfds, wfds, xfds, tv);
316 kvm_sleep_end();
318 return ret;
322 /***********************************************************/
323 /* x86 ISA bus support */
325 target_phys_addr_t isa_mem_base = 0;
326 PicState2 *isa_pic;
328 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
329 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
331 static uint32_t ioport_read(int index, uint32_t address)
333 static IOPortReadFunc *default_func[3] = {
334 default_ioport_readb,
335 default_ioport_readw,
336 default_ioport_readl
338 IOPortReadFunc *func = ioport_read_table[index][address];
339 if (!func)
340 func = default_func[index];
341 return func(ioport_opaque[address], address);
344 static void ioport_write(int index, uint32_t address, uint32_t data)
346 static IOPortWriteFunc *default_func[3] = {
347 default_ioport_writeb,
348 default_ioport_writew,
349 default_ioport_writel
351 IOPortWriteFunc *func = ioport_write_table[index][address];
352 if (!func)
353 func = default_func[index];
354 func(ioport_opaque[address], address, data);
357 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
359 #ifdef DEBUG_UNUSED_IOPORT
360 fprintf(stderr, "unused inb: port=0x%04x\n", address);
361 #endif
362 return 0xff;
365 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
367 #ifdef DEBUG_UNUSED_IOPORT
368 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
369 #endif
372 /* default is to make two byte accesses */
373 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
375 uint32_t data;
376 data = ioport_read(0, address);
377 address = (address + 1) & (MAX_IOPORTS - 1);
378 data |= ioport_read(0, address) << 8;
379 return data;
382 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
384 ioport_write(0, address, data & 0xff);
385 address = (address + 1) & (MAX_IOPORTS - 1);
386 ioport_write(0, address, (data >> 8) & 0xff);
389 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
391 #ifdef DEBUG_UNUSED_IOPORT
392 fprintf(stderr, "unused inl: port=0x%04x\n", address);
393 #endif
394 return 0xffffffff;
397 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
399 #ifdef DEBUG_UNUSED_IOPORT
400 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
401 #endif
404 /* size is the word size in byte */
405 int register_ioport_read(int start, int length, int size,
406 IOPortReadFunc *func, void *opaque)
408 int i, bsize;
410 if (size == 1) {
411 bsize = 0;
412 } else if (size == 2) {
413 bsize = 1;
414 } else if (size == 4) {
415 bsize = 2;
416 } else {
417 hw_error("register_ioport_read: invalid size");
418 return -1;
420 for(i = start; i < start + length; i += size) {
421 ioport_read_table[bsize][i] = func;
422 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
423 hw_error("register_ioport_read: invalid opaque");
424 ioport_opaque[i] = opaque;
426 return 0;
429 /* size is the word size in byte */
430 int register_ioport_write(int start, int length, int size,
431 IOPortWriteFunc *func, void *opaque)
433 int i, bsize;
435 if (size == 1) {
436 bsize = 0;
437 } else if (size == 2) {
438 bsize = 1;
439 } else if (size == 4) {
440 bsize = 2;
441 } else {
442 hw_error("register_ioport_write: invalid size");
443 return -1;
445 for(i = start; i < start + length; i += size) {
446 ioport_write_table[bsize][i] = func;
447 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
448 hw_error("register_ioport_write: invalid opaque");
449 ioport_opaque[i] = opaque;
451 return 0;
454 void isa_unassign_ioport(int start, int length)
456 int i;
458 for(i = start; i < start + length; i++) {
459 ioport_read_table[0][i] = default_ioport_readb;
460 ioport_read_table[1][i] = default_ioport_readw;
461 ioport_read_table[2][i] = default_ioport_readl;
463 ioport_write_table[0][i] = default_ioport_writeb;
464 ioport_write_table[1][i] = default_ioport_writew;
465 ioport_write_table[2][i] = default_ioport_writel;
467 ioport_opaque[i] = NULL;
471 /***********************************************************/
473 void cpu_outb(CPUState *env, int addr, int val)
475 LOG_IOPORT("outb: %04x %02x\n", addr, val);
476 ioport_write(0, addr, val);
477 #ifdef CONFIG_KQEMU
478 if (env)
479 env->last_io_time = cpu_get_time_fast();
480 #endif
483 void cpu_outw(CPUState *env, int addr, int val)
485 LOG_IOPORT("outw: %04x %04x\n", addr, val);
486 ioport_write(1, addr, val);
487 #ifdef CONFIG_KQEMU
488 if (env)
489 env->last_io_time = cpu_get_time_fast();
490 #endif
493 void cpu_outl(CPUState *env, int addr, int val)
495 LOG_IOPORT("outl: %04x %08x\n", addr, val);
496 ioport_write(2, addr, val);
497 #ifdef CONFIG_KQEMU
498 if (env)
499 env->last_io_time = cpu_get_time_fast();
500 #endif
503 int cpu_inb(CPUState *env, int addr)
505 int val;
506 val = ioport_read(0, addr);
507 LOG_IOPORT("inb : %04x %02x\n", addr, val);
508 #ifdef CONFIG_KQEMU
509 if (env)
510 env->last_io_time = cpu_get_time_fast();
511 #endif
512 return val;
515 int cpu_inw(CPUState *env, int addr)
517 int val;
518 val = ioport_read(1, addr);
519 LOG_IOPORT("inw : %04x %04x\n", addr, val);
520 #ifdef CONFIG_KQEMU
521 if (env)
522 env->last_io_time = cpu_get_time_fast();
523 #endif
524 return val;
527 int cpu_inl(CPUState *env, int addr)
529 int val;
530 val = ioport_read(2, addr);
531 LOG_IOPORT("inl : %04x %08x\n", addr, val);
532 #ifdef CONFIG_KQEMU
533 if (env)
534 env->last_io_time = cpu_get_time_fast();
535 #endif
536 return val;
539 /***********************************************************/
540 void hw_error(const char *fmt, ...)
542 va_list ap;
543 CPUState *env;
545 va_start(ap, fmt);
546 fprintf(stderr, "qemu: hardware error: ");
547 vfprintf(stderr, fmt, ap);
548 fprintf(stderr, "\n");
549 for(env = first_cpu; env != NULL; env = env->next_cpu) {
550 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
551 #ifdef TARGET_I386
552 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
553 #else
554 cpu_dump_state(env, stderr, fprintf, 0);
555 #endif
557 va_end(ap);
558 abort();
561 /***************/
562 /* ballooning */
564 static QEMUBalloonEvent *qemu_balloon_event;
565 void *qemu_balloon_event_opaque;
567 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
569 qemu_balloon_event = func;
570 qemu_balloon_event_opaque = opaque;
573 void qemu_balloon(ram_addr_t target)
575 if (qemu_balloon_event)
576 qemu_balloon_event(qemu_balloon_event_opaque, target);
579 ram_addr_t qemu_balloon_status(void)
581 if (qemu_balloon_event)
582 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
583 return 0;
586 /***********************************************************/
587 /* keyboard/mouse */
589 static QEMUPutKBDEvent *qemu_put_kbd_event;
590 static void *qemu_put_kbd_event_opaque;
591 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
592 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
594 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
596 qemu_put_kbd_event_opaque = opaque;
597 qemu_put_kbd_event = func;
600 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
601 void *opaque, int absolute,
602 const char *name)
604 QEMUPutMouseEntry *s, *cursor;
606 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
608 s->qemu_put_mouse_event = func;
609 s->qemu_put_mouse_event_opaque = opaque;
610 s->qemu_put_mouse_event_absolute = absolute;
611 s->qemu_put_mouse_event_name = qemu_strdup(name);
612 s->next = NULL;
614 if (!qemu_put_mouse_event_head) {
615 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
616 return s;
619 cursor = qemu_put_mouse_event_head;
620 while (cursor->next != NULL)
621 cursor = cursor->next;
623 cursor->next = s;
624 qemu_put_mouse_event_current = s;
626 return s;
629 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
631 QEMUPutMouseEntry *prev = NULL, *cursor;
633 if (!qemu_put_mouse_event_head || entry == NULL)
634 return;
636 cursor = qemu_put_mouse_event_head;
637 while (cursor != NULL && cursor != entry) {
638 prev = cursor;
639 cursor = cursor->next;
642 if (cursor == NULL) // does not exist or list empty
643 return;
644 else if (prev == NULL) { // entry is head
645 qemu_put_mouse_event_head = cursor->next;
646 if (qemu_put_mouse_event_current == entry)
647 qemu_put_mouse_event_current = cursor->next;
648 qemu_free(entry->qemu_put_mouse_event_name);
649 qemu_free(entry);
650 return;
653 prev->next = entry->next;
655 if (qemu_put_mouse_event_current == entry)
656 qemu_put_mouse_event_current = prev;
658 qemu_free(entry->qemu_put_mouse_event_name);
659 qemu_free(entry);
662 void kbd_put_keycode(int keycode)
664 if (qemu_put_kbd_event) {
665 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
669 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
671 QEMUPutMouseEvent *mouse_event;
672 void *mouse_event_opaque;
673 int width;
675 if (!qemu_put_mouse_event_current) {
676 return;
679 mouse_event =
680 qemu_put_mouse_event_current->qemu_put_mouse_event;
681 mouse_event_opaque =
682 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
684 if (mouse_event) {
685 if (graphic_rotate) {
686 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
687 width = 0x7fff;
688 else
689 width = graphic_width - 1;
690 mouse_event(mouse_event_opaque,
691 width - dy, dx, dz, buttons_state);
692 } else
693 mouse_event(mouse_event_opaque,
694 dx, dy, dz, buttons_state);
698 int kbd_mouse_is_absolute(void)
700 if (!qemu_put_mouse_event_current)
701 return 0;
703 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
706 void do_info_mice(Monitor *mon)
708 QEMUPutMouseEntry *cursor;
709 int index = 0;
711 if (!qemu_put_mouse_event_head) {
712 monitor_printf(mon, "No mouse devices connected\n");
713 return;
716 monitor_printf(mon, "Mouse devices available:\n");
717 cursor = qemu_put_mouse_event_head;
718 while (cursor != NULL) {
719 monitor_printf(mon, "%c Mouse #%d: %s\n",
720 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
721 index, cursor->qemu_put_mouse_event_name);
722 index++;
723 cursor = cursor->next;
727 void do_mouse_set(Monitor *mon, int index)
729 QEMUPutMouseEntry *cursor;
730 int i = 0;
732 if (!qemu_put_mouse_event_head) {
733 monitor_printf(mon, "No mouse devices connected\n");
734 return;
737 cursor = qemu_put_mouse_event_head;
738 while (cursor != NULL && index != i) {
739 i++;
740 cursor = cursor->next;
743 if (cursor != NULL)
744 qemu_put_mouse_event_current = cursor;
745 else
746 monitor_printf(mon, "Mouse at given index not found\n");
749 /* compute with 96 bit intermediate result: (a*b)/c */
750 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
752 union {
753 uint64_t ll;
754 struct {
755 #ifdef WORDS_BIGENDIAN
756 uint32_t high, low;
757 #else
758 uint32_t low, high;
759 #endif
760 } l;
761 } u, res;
762 uint64_t rl, rh;
764 u.ll = a;
765 rl = (uint64_t)u.l.low * (uint64_t)b;
766 rh = (uint64_t)u.l.high * (uint64_t)b;
767 rh += (rl >> 32);
768 res.l.high = rh / c;
769 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
770 return res.ll;
773 /***********************************************************/
774 /* real time host monotonic timer */
776 #define QEMU_TIMER_BASE 1000000000LL
778 #ifdef WIN32
780 static int64_t clock_freq;
782 static void init_get_clock(void)
784 LARGE_INTEGER freq;
785 int ret;
786 ret = QueryPerformanceFrequency(&freq);
787 if (ret == 0) {
788 fprintf(stderr, "Could not calibrate ticks\n");
789 exit(1);
791 clock_freq = freq.QuadPart;
794 static int64_t get_clock(void)
796 LARGE_INTEGER ti;
797 QueryPerformanceCounter(&ti);
798 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
801 #else
803 static int use_rt_clock;
805 static void init_get_clock(void)
807 use_rt_clock = 0;
808 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
809 || defined(__DragonFly__)
811 struct timespec ts;
812 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
813 use_rt_clock = 1;
816 #endif
819 static int64_t get_clock(void)
821 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
822 || defined(__DragonFly__)
823 if (use_rt_clock) {
824 struct timespec ts;
825 clock_gettime(CLOCK_MONOTONIC, &ts);
826 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
827 } else
828 #endif
830 /* XXX: using gettimeofday leads to problems if the date
831 changes, so it should be avoided. */
832 struct timeval tv;
833 gettimeofday(&tv, NULL);
834 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
837 #endif
839 /* Return the virtual CPU time, based on the instruction counter. */
840 static int64_t cpu_get_icount(void)
842 int64_t icount;
843 CPUState *env = cpu_single_env;;
844 icount = qemu_icount;
845 if (env) {
846 if (!can_do_io(env))
847 fprintf(stderr, "Bad clock read\n");
848 icount -= (env->icount_decr.u16.low + env->icount_extra);
850 return qemu_icount_bias + (icount << icount_time_shift);
853 /***********************************************************/
854 /* guest cycle counter */
856 static int64_t cpu_ticks_prev;
857 static int64_t cpu_ticks_offset;
858 static int64_t cpu_clock_offset;
859 static int cpu_ticks_enabled;
861 /* return the host CPU cycle counter and handle stop/restart */
862 int64_t cpu_get_ticks(void)
864 if (use_icount) {
865 return cpu_get_icount();
867 if (!cpu_ticks_enabled) {
868 return cpu_ticks_offset;
869 } else {
870 int64_t ticks;
871 ticks = cpu_get_real_ticks();
872 if (cpu_ticks_prev > ticks) {
873 /* Note: non increasing ticks may happen if the host uses
874 software suspend */
875 cpu_ticks_offset += cpu_ticks_prev - ticks;
877 cpu_ticks_prev = ticks;
878 return ticks + cpu_ticks_offset;
882 /* return the host CPU monotonic timer and handle stop/restart */
883 static int64_t cpu_get_clock(void)
885 int64_t ti;
886 if (!cpu_ticks_enabled) {
887 return cpu_clock_offset;
888 } else {
889 ti = get_clock();
890 return ti + cpu_clock_offset;
894 /* enable cpu_get_ticks() */
895 void cpu_enable_ticks(void)
897 if (!cpu_ticks_enabled) {
898 cpu_ticks_offset -= cpu_get_real_ticks();
899 cpu_clock_offset -= get_clock();
900 cpu_ticks_enabled = 1;
904 /* disable cpu_get_ticks() : the clock is stopped. You must not call
905 cpu_get_ticks() after that. */
906 void cpu_disable_ticks(void)
908 if (cpu_ticks_enabled) {
909 cpu_ticks_offset = cpu_get_ticks();
910 cpu_clock_offset = cpu_get_clock();
911 cpu_ticks_enabled = 0;
915 /***********************************************************/
916 /* timers */
918 #define QEMU_TIMER_REALTIME 0
919 #define QEMU_TIMER_VIRTUAL 1
921 struct QEMUClock {
922 int type;
923 /* XXX: add frequency */
926 struct QEMUTimer {
927 QEMUClock *clock;
928 int64_t expire_time;
929 QEMUTimerCB *cb;
930 void *opaque;
931 struct QEMUTimer *next;
934 struct qemu_alarm_timer {
935 char const *name;
936 unsigned int flags;
938 int (*start)(struct qemu_alarm_timer *t);
939 void (*stop)(struct qemu_alarm_timer *t);
940 void (*rearm)(struct qemu_alarm_timer *t);
941 void *priv;
944 #define ALARM_FLAG_DYNTICKS 0x1
945 #define ALARM_FLAG_EXPIRED 0x2
947 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
949 return t && (t->flags & ALARM_FLAG_DYNTICKS);
952 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
954 if (!alarm_has_dynticks(t))
955 return;
957 t->rearm(t);
960 /* TODO: MIN_TIMER_REARM_US should be optimized */
961 #define MIN_TIMER_REARM_US 250
963 static struct qemu_alarm_timer *alarm_timer;
965 #ifdef _WIN32
967 struct qemu_alarm_win32 {
968 MMRESULT timerId;
969 unsigned int period;
970 } alarm_win32_data = {0, -1};
972 static int win32_start_timer(struct qemu_alarm_timer *t);
973 static void win32_stop_timer(struct qemu_alarm_timer *t);
974 static void win32_rearm_timer(struct qemu_alarm_timer *t);
976 #else
978 static int unix_start_timer(struct qemu_alarm_timer *t);
979 static void unix_stop_timer(struct qemu_alarm_timer *t);
981 #ifdef __linux__
983 static int dynticks_start_timer(struct qemu_alarm_timer *t);
984 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
985 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
987 static int hpet_start_timer(struct qemu_alarm_timer *t);
988 static void hpet_stop_timer(struct qemu_alarm_timer *t);
990 static int rtc_start_timer(struct qemu_alarm_timer *t);
991 static void rtc_stop_timer(struct qemu_alarm_timer *t);
993 #endif /* __linux__ */
995 #endif /* _WIN32 */
997 /* Correlation between real and virtual time is always going to be
998 fairly approximate, so ignore small variation.
999 When the guest is idle real and virtual time will be aligned in
1000 the IO wait loop. */
1001 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
1003 static void icount_adjust(void)
1005 int64_t cur_time;
1006 int64_t cur_icount;
1007 int64_t delta;
1008 static int64_t last_delta;
1009 /* If the VM is not running, then do nothing. */
1010 if (!vm_running)
1011 return;
1013 cur_time = cpu_get_clock();
1014 cur_icount = qemu_get_clock(vm_clock);
1015 delta = cur_icount - cur_time;
1016 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1017 if (delta > 0
1018 && last_delta + ICOUNT_WOBBLE < delta * 2
1019 && icount_time_shift > 0) {
1020 /* The guest is getting too far ahead. Slow time down. */
1021 icount_time_shift--;
1023 if (delta < 0
1024 && last_delta - ICOUNT_WOBBLE > delta * 2
1025 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1026 /* The guest is getting too far behind. Speed time up. */
1027 icount_time_shift++;
1029 last_delta = delta;
1030 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1033 static void icount_adjust_rt(void * opaque)
1035 qemu_mod_timer(icount_rt_timer,
1036 qemu_get_clock(rt_clock) + 1000);
1037 icount_adjust();
1040 static void icount_adjust_vm(void * opaque)
1042 qemu_mod_timer(icount_vm_timer,
1043 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1044 icount_adjust();
1047 static void init_icount_adjust(void)
1049 /* Have both realtime and virtual time triggers for speed adjustment.
1050 The realtime trigger catches emulated time passing too slowly,
1051 the virtual time trigger catches emulated time passing too fast.
1052 Realtime triggers occur even when idle, so use them less frequently
1053 than VM triggers. */
1054 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1055 qemu_mod_timer(icount_rt_timer,
1056 qemu_get_clock(rt_clock) + 1000);
1057 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1058 qemu_mod_timer(icount_vm_timer,
1059 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1062 static struct qemu_alarm_timer alarm_timers[] = {
1063 #ifndef _WIN32
1064 #ifdef __linux__
1065 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1066 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1067 /* HPET - if available - is preferred */
1068 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1069 /* ...otherwise try RTC */
1070 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1071 #endif
1072 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1073 #else
1074 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1075 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1076 {"win32", 0, win32_start_timer,
1077 win32_stop_timer, NULL, &alarm_win32_data},
1078 #endif
1079 {NULL, }
1082 static void show_available_alarms(void)
1084 int i;
1086 printf("Available alarm timers, in order of precedence:\n");
1087 for (i = 0; alarm_timers[i].name; i++)
1088 printf("%s\n", alarm_timers[i].name);
1091 static void configure_alarms(char const *opt)
1093 int i;
1094 int cur = 0;
1095 int count = ARRAY_SIZE(alarm_timers) - 1;
1096 char *arg;
1097 char *name;
1098 struct qemu_alarm_timer tmp;
1100 if (!strcmp(opt, "?")) {
1101 show_available_alarms();
1102 exit(0);
1105 arg = strdup(opt);
1107 /* Reorder the array */
1108 name = strtok(arg, ",");
1109 while (name) {
1110 for (i = 0; i < count && alarm_timers[i].name; i++) {
1111 if (!strcmp(alarm_timers[i].name, name))
1112 break;
1115 if (i == count) {
1116 fprintf(stderr, "Unknown clock %s\n", name);
1117 goto next;
1120 if (i < cur)
1121 /* Ignore */
1122 goto next;
1124 /* Swap */
1125 tmp = alarm_timers[i];
1126 alarm_timers[i] = alarm_timers[cur];
1127 alarm_timers[cur] = tmp;
1129 cur++;
1130 next:
1131 name = strtok(NULL, ",");
1134 free(arg);
1136 if (cur) {
1137 /* Disable remaining timers */
1138 for (i = cur; i < count; i++)
1139 alarm_timers[i].name = NULL;
1140 } else {
1141 show_available_alarms();
1142 exit(1);
1146 QEMUClock *rt_clock;
1147 QEMUClock *vm_clock;
1149 static QEMUTimer *active_timers[2];
1151 static QEMUClock *qemu_new_clock(int type)
1153 QEMUClock *clock;
1154 clock = qemu_mallocz(sizeof(QEMUClock));
1155 clock->type = type;
1156 return clock;
1159 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1161 QEMUTimer *ts;
1163 ts = qemu_mallocz(sizeof(QEMUTimer));
1164 ts->clock = clock;
1165 ts->cb = cb;
1166 ts->opaque = opaque;
1167 return ts;
1170 void qemu_free_timer(QEMUTimer *ts)
1172 qemu_free(ts);
1175 /* stop a timer, but do not dealloc it */
1176 void qemu_del_timer(QEMUTimer *ts)
1178 QEMUTimer **pt, *t;
1180 /* NOTE: this code must be signal safe because
1181 qemu_timer_expired() can be called from a signal. */
1182 pt = &active_timers[ts->clock->type];
1183 for(;;) {
1184 t = *pt;
1185 if (!t)
1186 break;
1187 if (t == ts) {
1188 *pt = t->next;
1189 break;
1191 pt = &t->next;
1195 /* modify the current timer so that it will be fired when current_time
1196 >= expire_time. The corresponding callback will be called. */
1197 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1199 QEMUTimer **pt, *t;
1201 qemu_del_timer(ts);
1203 /* add the timer in the sorted list */
1204 /* NOTE: this code must be signal safe because
1205 qemu_timer_expired() can be called from a signal. */
1206 pt = &active_timers[ts->clock->type];
1207 for(;;) {
1208 t = *pt;
1209 if (!t)
1210 break;
1211 if (t->expire_time > expire_time)
1212 break;
1213 pt = &t->next;
1215 ts->expire_time = expire_time;
1216 ts->next = *pt;
1217 *pt = ts;
1219 /* Rearm if necessary */
1220 if (pt == &active_timers[ts->clock->type]) {
1221 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1222 qemu_rearm_alarm_timer(alarm_timer);
1224 /* Interrupt execution to force deadline recalculation. */
1225 if (use_icount)
1226 qemu_notify_event();
1230 int qemu_timer_pending(QEMUTimer *ts)
1232 QEMUTimer *t;
1233 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1234 if (t == ts)
1235 return 1;
1237 return 0;
1240 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1242 if (!timer_head)
1243 return 0;
1244 return (timer_head->expire_time <= current_time);
1247 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1249 QEMUTimer *ts;
1251 for(;;) {
1252 ts = *ptimer_head;
1253 if (!ts || ts->expire_time > current_time)
1254 break;
1255 /* remove timer from the list before calling the callback */
1256 *ptimer_head = ts->next;
1257 ts->next = NULL;
1259 /* run the callback (the timer list can be modified) */
1260 ts->cb(ts->opaque);
1264 int64_t qemu_get_clock(QEMUClock *clock)
1266 switch(clock->type) {
1267 case QEMU_TIMER_REALTIME:
1268 return get_clock() / 1000000;
1269 default:
1270 case QEMU_TIMER_VIRTUAL:
1271 if (use_icount) {
1272 return cpu_get_icount();
1273 } else {
1274 return cpu_get_clock();
1279 static void init_timers(void)
1281 init_get_clock();
1282 ticks_per_sec = QEMU_TIMER_BASE;
1283 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1284 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1287 /* save a timer */
1288 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1290 uint64_t expire_time;
1292 if (qemu_timer_pending(ts)) {
1293 expire_time = ts->expire_time;
1294 } else {
1295 expire_time = -1;
1297 qemu_put_be64(f, expire_time);
1300 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1302 uint64_t expire_time;
1304 expire_time = qemu_get_be64(f);
1305 if (expire_time != -1) {
1306 qemu_mod_timer(ts, expire_time);
1307 } else {
1308 qemu_del_timer(ts);
1312 static void timer_save(QEMUFile *f, void *opaque)
1314 if (cpu_ticks_enabled) {
1315 hw_error("cannot save state if virtual timers are running");
1317 qemu_put_be64(f, cpu_ticks_offset);
1318 qemu_put_be64(f, ticks_per_sec);
1319 qemu_put_be64(f, cpu_clock_offset);
1322 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1324 if (version_id != 1 && version_id != 2)
1325 return -EINVAL;
1326 if (cpu_ticks_enabled) {
1327 return -EINVAL;
1329 cpu_ticks_offset=qemu_get_be64(f);
1330 ticks_per_sec=qemu_get_be64(f);
1331 if (version_id == 2) {
1332 cpu_clock_offset=qemu_get_be64(f);
1334 return 0;
1337 static void qemu_event_increment(void);
1339 #ifdef _WIN32
1340 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1341 DWORD_PTR dwUser, DWORD_PTR dw1,
1342 DWORD_PTR dw2)
1343 #else
1344 static void host_alarm_handler(int host_signum)
1345 #endif
1347 #if 0
1348 #define DISP_FREQ 1000
1350 static int64_t delta_min = INT64_MAX;
1351 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1352 static int count;
1353 ti = qemu_get_clock(vm_clock);
1354 if (last_clock != 0) {
1355 delta = ti - last_clock;
1356 if (delta < delta_min)
1357 delta_min = delta;
1358 if (delta > delta_max)
1359 delta_max = delta;
1360 delta_cum += delta;
1361 if (++count == DISP_FREQ) {
1362 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1363 muldiv64(delta_min, 1000000, ticks_per_sec),
1364 muldiv64(delta_max, 1000000, ticks_per_sec),
1365 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1366 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1367 count = 0;
1368 delta_min = INT64_MAX;
1369 delta_max = 0;
1370 delta_cum = 0;
1373 last_clock = ti;
1375 #endif
1376 if (alarm_has_dynticks(alarm_timer) ||
1377 (!use_icount &&
1378 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1379 qemu_get_clock(vm_clock))) ||
1380 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1381 qemu_get_clock(rt_clock))) {
1382 qemu_event_increment();
1383 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1385 #ifndef CONFIG_IOTHREAD
1386 if (next_cpu) {
1387 /* stop the currently executing cpu because a timer occured */
1388 cpu_exit(next_cpu);
1389 #ifdef CONFIG_KQEMU
1390 if (next_cpu->kqemu_enabled) {
1391 kqemu_cpu_interrupt(next_cpu);
1393 #endif
1395 #endif
1396 timer_alarm_pending = 1;
1397 qemu_notify_event();
1401 static int64_t qemu_next_deadline(void)
1403 int64_t delta;
1405 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1406 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1407 qemu_get_clock(vm_clock);
1408 } else {
1409 /* To avoid problems with overflow limit this to 2^32. */
1410 delta = INT32_MAX;
1413 if (delta < 0)
1414 delta = 0;
1416 return delta;
1419 #if defined(__linux__) || defined(_WIN32)
1420 static uint64_t qemu_next_deadline_dyntick(void)
1422 int64_t delta;
1423 int64_t rtdelta;
1425 if (use_icount)
1426 delta = INT32_MAX;
1427 else
1428 delta = (qemu_next_deadline() + 999) / 1000;
1430 if (active_timers[QEMU_TIMER_REALTIME]) {
1431 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1432 qemu_get_clock(rt_clock))*1000;
1433 if (rtdelta < delta)
1434 delta = rtdelta;
1437 if (delta < MIN_TIMER_REARM_US)
1438 delta = MIN_TIMER_REARM_US;
1440 return delta;
1442 #endif
1444 #ifndef _WIN32
1446 /* Sets a specific flag */
1447 static int fcntl_setfl(int fd, int flag)
1449 int flags;
1451 flags = fcntl(fd, F_GETFL);
1452 if (flags == -1)
1453 return -errno;
1455 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1456 return -errno;
1458 return 0;
1461 #if defined(__linux__)
1463 #define RTC_FREQ 1024
1465 static void enable_sigio_timer(int fd)
1467 struct sigaction act;
1469 /* timer signal */
1470 sigfillset(&act.sa_mask);
1471 act.sa_flags = 0;
1472 act.sa_handler = host_alarm_handler;
1474 sigaction(SIGIO, &act, NULL);
1475 fcntl_setfl(fd, O_ASYNC);
1476 fcntl(fd, F_SETOWN, getpid());
1479 static int hpet_start_timer(struct qemu_alarm_timer *t)
1481 struct hpet_info info;
1482 int r, fd;
1484 fd = open("/dev/hpet", O_RDONLY);
1485 if (fd < 0)
1486 return -1;
1488 /* Set frequency */
1489 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1490 if (r < 0) {
1491 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1492 "error, but for better emulation accuracy type:\n"
1493 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1494 goto fail;
1497 /* Check capabilities */
1498 r = ioctl(fd, HPET_INFO, &info);
1499 if (r < 0)
1500 goto fail;
1502 /* Enable periodic mode */
1503 r = ioctl(fd, HPET_EPI, 0);
1504 if (info.hi_flags && (r < 0))
1505 goto fail;
1507 /* Enable interrupt */
1508 r = ioctl(fd, HPET_IE_ON, 0);
1509 if (r < 0)
1510 goto fail;
1512 enable_sigio_timer(fd);
1513 t->priv = (void *)(long)fd;
1515 return 0;
1516 fail:
1517 close(fd);
1518 return -1;
1521 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1523 int fd = (long)t->priv;
1525 close(fd);
1528 static int rtc_start_timer(struct qemu_alarm_timer *t)
1530 int rtc_fd;
1531 unsigned long current_rtc_freq = 0;
1533 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1534 if (rtc_fd < 0)
1535 return -1;
1536 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1537 if (current_rtc_freq != RTC_FREQ &&
1538 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1539 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1540 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1541 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1542 goto fail;
1544 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1545 fail:
1546 close(rtc_fd);
1547 return -1;
1550 enable_sigio_timer(rtc_fd);
1552 t->priv = (void *)(long)rtc_fd;
1554 return 0;
1557 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1559 int rtc_fd = (long)t->priv;
1561 close(rtc_fd);
1564 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1566 struct sigevent ev;
1567 timer_t host_timer;
1568 struct sigaction act;
1570 sigfillset(&act.sa_mask);
1571 act.sa_flags = 0;
1572 act.sa_handler = host_alarm_handler;
1574 sigaction(SIGALRM, &act, NULL);
1577 * Initialize ev struct to 0 to avoid valgrind complaining
1578 * about uninitialized data in timer_create call
1580 memset(&ev, 0, sizeof(ev));
1581 ev.sigev_value.sival_int = 0;
1582 ev.sigev_notify = SIGEV_SIGNAL;
1583 ev.sigev_signo = SIGALRM;
1585 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1586 perror("timer_create");
1588 /* disable dynticks */
1589 fprintf(stderr, "Dynamic Ticks disabled\n");
1591 return -1;
1594 t->priv = (void *)(long)host_timer;
1596 return 0;
1599 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1601 timer_t host_timer = (timer_t)(long)t->priv;
1603 timer_delete(host_timer);
1606 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1608 timer_t host_timer = (timer_t)(long)t->priv;
1609 struct itimerspec timeout;
1610 int64_t nearest_delta_us = INT64_MAX;
1611 int64_t current_us;
1613 if (!active_timers[QEMU_TIMER_REALTIME] &&
1614 !active_timers[QEMU_TIMER_VIRTUAL])
1615 return;
1617 nearest_delta_us = qemu_next_deadline_dyntick();
1619 /* check whether a timer is already running */
1620 if (timer_gettime(host_timer, &timeout)) {
1621 perror("gettime");
1622 fprintf(stderr, "Internal timer error: aborting\n");
1623 exit(1);
1625 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1626 if (current_us && current_us <= nearest_delta_us)
1627 return;
1629 timeout.it_interval.tv_sec = 0;
1630 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1631 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1632 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1633 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1634 perror("settime");
1635 fprintf(stderr, "Internal timer error: aborting\n");
1636 exit(1);
1640 #endif /* defined(__linux__) */
1642 static int unix_start_timer(struct qemu_alarm_timer *t)
1644 struct sigaction act;
1645 struct itimerval itv;
1646 int err;
1648 /* timer signal */
1649 sigfillset(&act.sa_mask);
1650 act.sa_flags = 0;
1651 act.sa_handler = host_alarm_handler;
1653 sigaction(SIGALRM, &act, NULL);
1655 itv.it_interval.tv_sec = 0;
1656 /* for i386 kernel 2.6 to get 1 ms */
1657 itv.it_interval.tv_usec = 999;
1658 itv.it_value.tv_sec = 0;
1659 itv.it_value.tv_usec = 10 * 1000;
1661 err = setitimer(ITIMER_REAL, &itv, NULL);
1662 if (err)
1663 return -1;
1665 return 0;
1668 static void unix_stop_timer(struct qemu_alarm_timer *t)
1670 struct itimerval itv;
1672 memset(&itv, 0, sizeof(itv));
1673 setitimer(ITIMER_REAL, &itv, NULL);
1676 #endif /* !defined(_WIN32) */
1679 #ifdef _WIN32
1681 static int win32_start_timer(struct qemu_alarm_timer *t)
1683 TIMECAPS tc;
1684 struct qemu_alarm_win32 *data = t->priv;
1685 UINT flags;
1687 memset(&tc, 0, sizeof(tc));
1688 timeGetDevCaps(&tc, sizeof(tc));
1690 if (data->period < tc.wPeriodMin)
1691 data->period = tc.wPeriodMin;
1693 timeBeginPeriod(data->period);
1695 flags = TIME_CALLBACK_FUNCTION;
1696 if (alarm_has_dynticks(t))
1697 flags |= TIME_ONESHOT;
1698 else
1699 flags |= TIME_PERIODIC;
1701 data->timerId = timeSetEvent(1, // interval (ms)
1702 data->period, // resolution
1703 host_alarm_handler, // function
1704 (DWORD)t, // parameter
1705 flags);
1707 if (!data->timerId) {
1708 perror("Failed to initialize win32 alarm timer");
1709 timeEndPeriod(data->period);
1710 return -1;
1713 return 0;
1716 static void win32_stop_timer(struct qemu_alarm_timer *t)
1718 struct qemu_alarm_win32 *data = t->priv;
1720 timeKillEvent(data->timerId);
1721 timeEndPeriod(data->period);
1724 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1726 struct qemu_alarm_win32 *data = t->priv;
1727 uint64_t nearest_delta_us;
1729 if (!active_timers[QEMU_TIMER_REALTIME] &&
1730 !active_timers[QEMU_TIMER_VIRTUAL])
1731 return;
1733 nearest_delta_us = qemu_next_deadline_dyntick();
1734 nearest_delta_us /= 1000;
1736 timeKillEvent(data->timerId);
1738 data->timerId = timeSetEvent(1,
1739 data->period,
1740 host_alarm_handler,
1741 (DWORD)t,
1742 TIME_ONESHOT | TIME_PERIODIC);
1744 if (!data->timerId) {
1745 perror("Failed to re-arm win32 alarm timer");
1747 timeEndPeriod(data->period);
1748 exit(1);
1752 #endif /* _WIN32 */
1754 static int init_timer_alarm(void)
1756 struct qemu_alarm_timer *t = NULL;
1757 int i, err = -1;
1759 for (i = 0; alarm_timers[i].name; i++) {
1760 t = &alarm_timers[i];
1762 err = t->start(t);
1763 if (!err)
1764 break;
1767 if (err) {
1768 err = -ENOENT;
1769 goto fail;
1772 alarm_timer = t;
1774 return 0;
1776 fail:
1777 return err;
1780 static void quit_timers(void)
1782 alarm_timer->stop(alarm_timer);
1783 alarm_timer = NULL;
1786 /***********************************************************/
1787 /* host time/date access */
1788 void qemu_get_timedate(struct tm *tm, int offset)
1790 time_t ti;
1791 struct tm *ret;
1793 time(&ti);
1794 ti += offset;
1795 if (rtc_date_offset == -1) {
1796 if (rtc_utc)
1797 ret = gmtime(&ti);
1798 else
1799 ret = localtime(&ti);
1800 } else {
1801 ti -= rtc_date_offset;
1802 ret = gmtime(&ti);
1805 memcpy(tm, ret, sizeof(struct tm));
1808 int qemu_timedate_diff(struct tm *tm)
1810 time_t seconds;
1812 if (rtc_date_offset == -1)
1813 if (rtc_utc)
1814 seconds = mktimegm(tm);
1815 else
1816 seconds = mktime(tm);
1817 else
1818 seconds = mktimegm(tm) + rtc_date_offset;
1820 return seconds - time(NULL);
1823 #ifdef _WIN32
1824 static void socket_cleanup(void)
1826 WSACleanup();
1829 static int socket_init(void)
1831 WSADATA Data;
1832 int ret, err;
1834 ret = WSAStartup(MAKEWORD(2,2), &Data);
1835 if (ret != 0) {
1836 err = WSAGetLastError();
1837 fprintf(stderr, "WSAStartup: %d\n", err);
1838 return -1;
1840 atexit(socket_cleanup);
1841 return 0;
1843 #endif
1845 int get_param_value(char *buf, int buf_size,
1846 const char *tag, const char *str)
1848 const char *p;
1849 char option[128];
1851 p = str;
1852 for(;;) {
1853 p = get_opt_name(option, sizeof(option), p, '=');
1854 if (*p != '=')
1855 break;
1856 p++;
1857 if (!strcmp(tag, option)) {
1858 (void)get_opt_value(buf, buf_size, p);
1859 return strlen(buf);
1860 } else {
1861 p = get_opt_value(NULL, 0, p);
1863 if (*p != ',')
1864 break;
1865 p++;
1867 return 0;
1870 int check_params(const char * const *params, const char *str)
1872 int name_buf_size = 1;
1873 const char *p;
1874 char *name_buf;
1875 int i, len;
1876 int ret = 0;
1878 for (i = 0; params[i] != NULL; i++) {
1879 len = strlen(params[i]) + 1;
1880 if (len > name_buf_size) {
1881 name_buf_size = len;
1884 name_buf = qemu_malloc(name_buf_size);
1886 p = str;
1887 while (*p != '\0') {
1888 p = get_opt_name(name_buf, name_buf_size, p, '=');
1889 if (*p != '=') {
1890 ret = -1;
1891 break;
1893 p++;
1894 for(i = 0; params[i] != NULL; i++)
1895 if (!strcmp(params[i], name_buf))
1896 break;
1897 if (params[i] == NULL) {
1898 ret = -1;
1899 break;
1901 p = get_opt_value(NULL, 0, p);
1902 if (*p != ',')
1903 break;
1904 p++;
1907 qemu_free(name_buf);
1908 return ret;
1911 /***********************************************************/
1912 /* Bluetooth support */
1913 static int nb_hcis;
1914 static int cur_hci;
1915 static struct HCIInfo *hci_table[MAX_NICS];
1917 static struct bt_vlan_s {
1918 struct bt_scatternet_s net;
1919 int id;
1920 struct bt_vlan_s *next;
1921 } *first_bt_vlan;
1923 /* find or alloc a new bluetooth "VLAN" */
1924 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1926 struct bt_vlan_s **pvlan, *vlan;
1927 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1928 if (vlan->id == id)
1929 return &vlan->net;
1931 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1932 vlan->id = id;
1933 pvlan = &first_bt_vlan;
1934 while (*pvlan != NULL)
1935 pvlan = &(*pvlan)->next;
1936 *pvlan = vlan;
1937 return &vlan->net;
1940 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1944 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1946 return -ENOTSUP;
1949 static struct HCIInfo null_hci = {
1950 .cmd_send = null_hci_send,
1951 .sco_send = null_hci_send,
1952 .acl_send = null_hci_send,
1953 .bdaddr_set = null_hci_addr_set,
1956 struct HCIInfo *qemu_next_hci(void)
1958 if (cur_hci == nb_hcis)
1959 return &null_hci;
1961 return hci_table[cur_hci++];
1964 static struct HCIInfo *hci_init(const char *str)
1966 char *endp;
1967 struct bt_scatternet_s *vlan = 0;
1969 if (!strcmp(str, "null"))
1970 /* null */
1971 return &null_hci;
1972 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1973 /* host[:hciN] */
1974 return bt_host_hci(str[4] ? str + 5 : "hci0");
1975 else if (!strncmp(str, "hci", 3)) {
1976 /* hci[,vlan=n] */
1977 if (str[3]) {
1978 if (!strncmp(str + 3, ",vlan=", 6)) {
1979 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1980 if (*endp)
1981 vlan = 0;
1983 } else
1984 vlan = qemu_find_bt_vlan(0);
1985 if (vlan)
1986 return bt_new_hci(vlan);
1989 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1991 return 0;
1994 static int bt_hci_parse(const char *str)
1996 struct HCIInfo *hci;
1997 bdaddr_t bdaddr;
1999 if (nb_hcis >= MAX_NICS) {
2000 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2001 return -1;
2004 hci = hci_init(str);
2005 if (!hci)
2006 return -1;
2008 bdaddr.b[0] = 0x52;
2009 bdaddr.b[1] = 0x54;
2010 bdaddr.b[2] = 0x00;
2011 bdaddr.b[3] = 0x12;
2012 bdaddr.b[4] = 0x34;
2013 bdaddr.b[5] = 0x56 + nb_hcis;
2014 hci->bdaddr_set(hci, bdaddr.b);
2016 hci_table[nb_hcis++] = hci;
2018 return 0;
2021 static void bt_vhci_add(int vlan_id)
2023 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2025 if (!vlan->slave)
2026 fprintf(stderr, "qemu: warning: adding a VHCI to "
2027 "an empty scatternet %i\n", vlan_id);
2029 bt_vhci_init(bt_new_hci(vlan));
2032 static struct bt_device_s *bt_device_add(const char *opt)
2034 struct bt_scatternet_s *vlan;
2035 int vlan_id = 0;
2036 char *endp = strstr(opt, ",vlan=");
2037 int len = (endp ? endp - opt : strlen(opt)) + 1;
2038 char devname[10];
2040 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2042 if (endp) {
2043 vlan_id = strtol(endp + 6, &endp, 0);
2044 if (*endp) {
2045 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2046 return 0;
2050 vlan = qemu_find_bt_vlan(vlan_id);
2052 if (!vlan->slave)
2053 fprintf(stderr, "qemu: warning: adding a slave device to "
2054 "an empty scatternet %i\n", vlan_id);
2056 if (!strcmp(devname, "keyboard"))
2057 return bt_keyboard_init(vlan);
2059 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2060 return 0;
2063 static int bt_parse(const char *opt)
2065 const char *endp, *p;
2066 int vlan;
2068 if (strstart(opt, "hci", &endp)) {
2069 if (!*endp || *endp == ',') {
2070 if (*endp)
2071 if (!strstart(endp, ",vlan=", 0))
2072 opt = endp + 1;
2074 return bt_hci_parse(opt);
2076 } else if (strstart(opt, "vhci", &endp)) {
2077 if (!*endp || *endp == ',') {
2078 if (*endp) {
2079 if (strstart(endp, ",vlan=", &p)) {
2080 vlan = strtol(p, (char **) &endp, 0);
2081 if (*endp) {
2082 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2083 return 1;
2085 } else {
2086 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2087 return 1;
2089 } else
2090 vlan = 0;
2092 bt_vhci_add(vlan);
2093 return 0;
2095 } else if (strstart(opt, "device:", &endp))
2096 return !bt_device_add(endp);
2098 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2099 return 1;
2102 /***********************************************************/
2103 /* QEMU Block devices */
2105 #define HD_ALIAS "index=%d,media=disk"
2106 #define CDROM_ALIAS "index=2,media=cdrom"
2107 #define FD_ALIAS "index=%d,if=floppy"
2108 #define PFLASH_ALIAS "if=pflash"
2109 #define MTD_ALIAS "if=mtd"
2110 #define SD_ALIAS "index=0,if=sd"
2112 static int drive_opt_get_free_idx(void)
2114 int index;
2116 for (index = 0; index < MAX_DRIVES; index++)
2117 if (!drives_opt[index].used) {
2118 drives_opt[index].used = 1;
2119 return index;
2122 return -1;
2125 static int drive_get_free_idx(void)
2127 int index;
2129 for (index = 0; index < MAX_DRIVES; index++)
2130 if (!drives_table[index].used) {
2131 drives_table[index].used = 1;
2132 return index;
2135 return -1;
2138 int drive_add(const char *file, const char *fmt, ...)
2140 va_list ap;
2141 int index = drive_opt_get_free_idx();
2143 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2144 fprintf(stderr, "qemu: too many drives\n");
2145 return -1;
2148 drives_opt[index].file = file;
2149 va_start(ap, fmt);
2150 vsnprintf(drives_opt[index].opt,
2151 sizeof(drives_opt[0].opt), fmt, ap);
2152 va_end(ap);
2154 nb_drives_opt++;
2155 return index;
2158 void drive_remove(int index)
2160 drives_opt[index].used = 0;
2161 nb_drives_opt--;
2164 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2166 int index;
2168 /* seek interface, bus and unit */
2170 for (index = 0; index < MAX_DRIVES; index++)
2171 if (drives_table[index].type == type &&
2172 drives_table[index].bus == bus &&
2173 drives_table[index].unit == unit &&
2174 drives_table[index].used)
2175 return index;
2177 return -1;
2180 int drive_get_max_bus(BlockInterfaceType type)
2182 int max_bus;
2183 int index;
2185 max_bus = -1;
2186 for (index = 0; index < nb_drives; index++) {
2187 if(drives_table[index].type == type &&
2188 drives_table[index].bus > max_bus)
2189 max_bus = drives_table[index].bus;
2191 return max_bus;
2194 const char *drive_get_serial(BlockDriverState *bdrv)
2196 int index;
2198 for (index = 0; index < nb_drives; index++)
2199 if (drives_table[index].bdrv == bdrv)
2200 return drives_table[index].serial;
2202 return "\0";
2205 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2207 int index;
2209 for (index = 0; index < nb_drives; index++)
2210 if (drives_table[index].bdrv == bdrv)
2211 return drives_table[index].onerror;
2213 return BLOCK_ERR_STOP_ENOSPC;
2216 static void bdrv_format_print(void *opaque, const char *name)
2218 fprintf(stderr, " %s", name);
2221 void drive_uninit(BlockDriverState *bdrv)
2223 int i;
2225 for (i = 0; i < MAX_DRIVES; i++)
2226 if (drives_table[i].bdrv == bdrv) {
2227 drives_table[i].bdrv = NULL;
2228 drives_table[i].used = 0;
2229 drive_remove(drives_table[i].drive_opt_idx);
2230 nb_drives--;
2231 break;
2235 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2237 char buf[128];
2238 char file[1024];
2239 char devname[128];
2240 char serial[21];
2241 const char *mediastr = "";
2242 BlockInterfaceType type;
2243 enum { MEDIA_DISK, MEDIA_CDROM } media;
2244 int bus_id, unit_id;
2245 int cyls, heads, secs, translation;
2246 BlockDriverState *bdrv;
2247 BlockDriver *drv = NULL;
2248 QEMUMachine *machine = opaque;
2249 int max_devs;
2250 int index;
2251 int cache;
2252 int bdrv_flags, onerror;
2253 int drives_table_idx;
2254 char *str = arg->opt;
2255 static const char * const params[] = { "bus", "unit", "if", "index",
2256 "cyls", "heads", "secs", "trans",
2257 "media", "snapshot", "file",
2258 "cache", "format", "serial", "werror",
2259 "boot", NULL };
2261 if (check_params(params, str) < 0) {
2262 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2263 buf, str);
2264 return -1;
2267 file[0] = 0;
2268 cyls = heads = secs = 0;
2269 bus_id = 0;
2270 unit_id = -1;
2271 translation = BIOS_ATA_TRANSLATION_AUTO;
2272 index = -1;
2273 cache = 3;
2275 if (machine->use_scsi) {
2276 type = IF_SCSI;
2277 max_devs = MAX_SCSI_DEVS;
2278 pstrcpy(devname, sizeof(devname), "scsi");
2279 } else {
2280 type = IF_IDE;
2281 max_devs = MAX_IDE_DEVS;
2282 pstrcpy(devname, sizeof(devname), "ide");
2284 media = MEDIA_DISK;
2286 /* extract parameters */
2288 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2289 bus_id = strtol(buf, NULL, 0);
2290 if (bus_id < 0) {
2291 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2292 return -1;
2296 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2297 unit_id = strtol(buf, NULL, 0);
2298 if (unit_id < 0) {
2299 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2300 return -1;
2304 if (get_param_value(buf, sizeof(buf), "if", str)) {
2305 pstrcpy(devname, sizeof(devname), buf);
2306 if (!strcmp(buf, "ide")) {
2307 type = IF_IDE;
2308 max_devs = MAX_IDE_DEVS;
2309 } else if (!strcmp(buf, "scsi")) {
2310 type = IF_SCSI;
2311 max_devs = MAX_SCSI_DEVS;
2312 } else if (!strcmp(buf, "floppy")) {
2313 type = IF_FLOPPY;
2314 max_devs = 0;
2315 } else if (!strcmp(buf, "pflash")) {
2316 type = IF_PFLASH;
2317 max_devs = 0;
2318 } else if (!strcmp(buf, "mtd")) {
2319 type = IF_MTD;
2320 max_devs = 0;
2321 } else if (!strcmp(buf, "sd")) {
2322 type = IF_SD;
2323 max_devs = 0;
2324 } else if (!strcmp(buf, "virtio")) {
2325 type = IF_VIRTIO;
2326 max_devs = 0;
2327 } else if (!strcmp(buf, "xen")) {
2328 type = IF_XEN;
2329 max_devs = 0;
2330 } else {
2331 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2332 return -1;
2336 if (get_param_value(buf, sizeof(buf), "index", str)) {
2337 index = strtol(buf, NULL, 0);
2338 if (index < 0) {
2339 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2340 return -1;
2344 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2345 cyls = strtol(buf, NULL, 0);
2348 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2349 heads = strtol(buf, NULL, 0);
2352 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2353 secs = strtol(buf, NULL, 0);
2356 if (cyls || heads || secs) {
2357 if (cyls < 1 || cyls > 16383) {
2358 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2359 return -1;
2361 if (heads < 1 || heads > 16) {
2362 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2363 return -1;
2365 if (secs < 1 || secs > 63) {
2366 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2367 return -1;
2371 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2372 if (!cyls) {
2373 fprintf(stderr,
2374 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2375 str);
2376 return -1;
2378 if (!strcmp(buf, "none"))
2379 translation = BIOS_ATA_TRANSLATION_NONE;
2380 else if (!strcmp(buf, "lba"))
2381 translation = BIOS_ATA_TRANSLATION_LBA;
2382 else if (!strcmp(buf, "auto"))
2383 translation = BIOS_ATA_TRANSLATION_AUTO;
2384 else {
2385 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2386 return -1;
2390 if (get_param_value(buf, sizeof(buf), "media", str)) {
2391 if (!strcmp(buf, "disk")) {
2392 media = MEDIA_DISK;
2393 } else if (!strcmp(buf, "cdrom")) {
2394 if (cyls || secs || heads) {
2395 fprintf(stderr,
2396 "qemu: '%s' invalid physical CHS format\n", str);
2397 return -1;
2399 media = MEDIA_CDROM;
2400 } else {
2401 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2402 return -1;
2406 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2407 if (!strcmp(buf, "on"))
2408 snapshot = 1;
2409 else if (!strcmp(buf, "off"))
2410 snapshot = 0;
2411 else {
2412 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2413 return -1;
2417 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2418 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2419 cache = 0;
2420 else if (!strcmp(buf, "writethrough"))
2421 cache = 1;
2422 else if (!strcmp(buf, "writeback"))
2423 cache = 2;
2424 else {
2425 fprintf(stderr, "qemu: invalid cache option\n");
2426 return -1;
2430 if (get_param_value(buf, sizeof(buf), "format", str)) {
2431 if (strcmp(buf, "?") == 0) {
2432 fprintf(stderr, "qemu: Supported formats:");
2433 bdrv_iterate_format(bdrv_format_print, NULL);
2434 fprintf(stderr, "\n");
2435 return -1;
2437 drv = bdrv_find_format(buf);
2438 if (!drv) {
2439 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2440 return -1;
2444 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2445 if (!strcmp(buf, "on")) {
2446 if (extboot_drive != -1) {
2447 fprintf(stderr, "qemu: two bootable drives specified\n");
2448 return -1;
2450 extboot_drive = nb_drives;
2451 } else if (strcmp(buf, "off")) {
2452 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2453 return -1;
2457 if (arg->file == NULL)
2458 get_param_value(file, sizeof(file), "file", str);
2459 else
2460 pstrcpy(file, sizeof(file), arg->file);
2462 if (!get_param_value(serial, sizeof(serial), "serial", str))
2463 memset(serial, 0, sizeof(serial));
2465 onerror = BLOCK_ERR_STOP_ENOSPC;
2466 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2467 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2468 fprintf(stderr, "werror is no supported by this format\n");
2469 return -1;
2471 if (!strcmp(buf, "ignore"))
2472 onerror = BLOCK_ERR_IGNORE;
2473 else if (!strcmp(buf, "enospc"))
2474 onerror = BLOCK_ERR_STOP_ENOSPC;
2475 else if (!strcmp(buf, "stop"))
2476 onerror = BLOCK_ERR_STOP_ANY;
2477 else if (!strcmp(buf, "report"))
2478 onerror = BLOCK_ERR_REPORT;
2479 else {
2480 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2481 return -1;
2485 /* compute bus and unit according index */
2487 if (index != -1) {
2488 if (bus_id != 0 || unit_id != -1) {
2489 fprintf(stderr,
2490 "qemu: '%s' index cannot be used with bus and unit\n", str);
2491 return -1;
2493 if (max_devs == 0)
2495 unit_id = index;
2496 bus_id = 0;
2497 } else {
2498 unit_id = index % max_devs;
2499 bus_id = index / max_devs;
2503 /* if user doesn't specify a unit_id,
2504 * try to find the first free
2507 if (unit_id == -1) {
2508 unit_id = 0;
2509 while (drive_get_index(type, bus_id, unit_id) != -1) {
2510 unit_id++;
2511 if (max_devs && unit_id >= max_devs) {
2512 unit_id -= max_devs;
2513 bus_id++;
2518 /* check unit id */
2520 if (max_devs && unit_id >= max_devs) {
2521 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2522 str, unit_id, max_devs - 1);
2523 return -1;
2527 * ignore multiple definitions
2530 if (drive_get_index(type, bus_id, unit_id) != -1)
2531 return -2;
2533 /* init */
2535 if (type == IF_IDE || type == IF_SCSI)
2536 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2537 if (max_devs)
2538 snprintf(buf, sizeof(buf), "%s%i%s%i",
2539 devname, bus_id, mediastr, unit_id);
2540 else
2541 snprintf(buf, sizeof(buf), "%s%s%i",
2542 devname, mediastr, unit_id);
2543 bdrv = bdrv_new(buf);
2544 drives_table_idx = drive_get_free_idx();
2545 drives_table[drives_table_idx].bdrv = bdrv;
2546 drives_table[drives_table_idx].type = type;
2547 drives_table[drives_table_idx].bus = bus_id;
2548 drives_table[drives_table_idx].unit = unit_id;
2549 drives_table[drives_table_idx].onerror = onerror;
2550 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2551 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2552 nb_drives++;
2554 switch(type) {
2555 case IF_IDE:
2556 case IF_SCSI:
2557 case IF_XEN:
2558 switch(media) {
2559 case MEDIA_DISK:
2560 if (cyls != 0) {
2561 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2562 bdrv_set_translation_hint(bdrv, translation);
2564 break;
2565 case MEDIA_CDROM:
2566 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2567 break;
2569 break;
2570 case IF_SD:
2571 /* FIXME: This isn't really a floppy, but it's a reasonable
2572 approximation. */
2573 case IF_FLOPPY:
2574 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2575 break;
2576 case IF_PFLASH:
2577 case IF_MTD:
2578 case IF_VIRTIO:
2579 break;
2580 case IF_COUNT:
2581 abort();
2583 if (!file[0])
2584 return -2;
2585 bdrv_flags = 0;
2586 if (snapshot) {
2587 bdrv_flags |= BDRV_O_SNAPSHOT;
2588 cache = 2; /* always use write-back with snapshot */
2590 if (cache == 0) /* no caching */
2591 bdrv_flags |= BDRV_O_NOCACHE;
2592 else if (cache == 2) /* write-back */
2593 bdrv_flags |= BDRV_O_CACHE_WB;
2594 else if (cache == 3) /* not specified */
2595 bdrv_flags |= BDRV_O_CACHE_DEF;
2596 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2597 fprintf(stderr, "qemu: could not open disk image %s\n",
2598 file);
2599 return -1;
2601 if (bdrv_key_required(bdrv))
2602 autostart = 0;
2603 return drives_table_idx;
2606 static void numa_add(const char *optarg)
2608 char option[128];
2609 char *endptr;
2610 unsigned long long value, endvalue;
2611 int nodenr;
2613 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2614 if (!strcmp(option, "node")) {
2615 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2616 nodenr = nb_numa_nodes;
2617 } else {
2618 nodenr = strtoull(option, NULL, 10);
2621 if (get_param_value(option, 128, "mem", optarg) == 0) {
2622 node_mem[nodenr] = 0;
2623 } else {
2624 value = strtoull(option, &endptr, 0);
2625 switch (*endptr) {
2626 case 0: case 'M': case 'm':
2627 value <<= 20;
2628 break;
2629 case 'G': case 'g':
2630 value <<= 30;
2631 break;
2633 node_mem[nodenr] = value;
2635 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2636 node_cpumask[nodenr] = 0;
2637 } else {
2638 value = strtoull(option, &endptr, 10);
2639 if (value >= 64) {
2640 value = 63;
2641 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2642 } else {
2643 if (*endptr == '-') {
2644 endvalue = strtoull(endptr+1, &endptr, 10);
2645 if (endvalue >= 63) {
2646 endvalue = 62;
2647 fprintf(stderr,
2648 "only 63 CPUs in NUMA mode supported.\n");
2650 value = (1 << (endvalue + 1)) - (1 << value);
2651 } else {
2652 value = 1 << value;
2655 node_cpumask[nodenr] = value;
2657 nb_numa_nodes++;
2659 return;
2662 /***********************************************************/
2663 /* USB devices */
2665 static USBPort *used_usb_ports;
2666 static USBPort *free_usb_ports;
2668 /* ??? Maybe change this to register a hub to keep track of the topology. */
2669 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2670 usb_attachfn attach)
2672 port->opaque = opaque;
2673 port->index = index;
2674 port->attach = attach;
2675 port->next = free_usb_ports;
2676 free_usb_ports = port;
2679 int usb_device_add_dev(USBDevice *dev)
2681 USBPort *port;
2683 /* Find a USB port to add the device to. */
2684 port = free_usb_ports;
2685 if (!port->next) {
2686 USBDevice *hub;
2688 /* Create a new hub and chain it on. */
2689 free_usb_ports = NULL;
2690 port->next = used_usb_ports;
2691 used_usb_ports = port;
2693 hub = usb_hub_init(VM_USB_HUB_SIZE);
2694 usb_attach(port, hub);
2695 port = free_usb_ports;
2698 free_usb_ports = port->next;
2699 port->next = used_usb_ports;
2700 used_usb_ports = port;
2701 usb_attach(port, dev);
2702 return 0;
2705 static void usb_msd_password_cb(void *opaque, int err)
2707 USBDevice *dev = opaque;
2709 if (!err)
2710 usb_device_add_dev(dev);
2711 else
2712 dev->handle_destroy(dev);
2715 static int usb_device_add(const char *devname, int is_hotplug)
2717 const char *p;
2718 USBDevice *dev;
2720 if (!free_usb_ports)
2721 return -1;
2723 if (strstart(devname, "host:", &p)) {
2724 dev = usb_host_device_open(p);
2725 } else if (!strcmp(devname, "mouse")) {
2726 dev = usb_mouse_init();
2727 } else if (!strcmp(devname, "tablet")) {
2728 dev = usb_tablet_init();
2729 } else if (!strcmp(devname, "keyboard")) {
2730 dev = usb_keyboard_init();
2731 } else if (strstart(devname, "disk:", &p)) {
2732 BlockDriverState *bs;
2734 dev = usb_msd_init(p);
2735 if (!dev)
2736 return -1;
2737 bs = usb_msd_get_bdrv(dev);
2738 if (bdrv_key_required(bs)) {
2739 autostart = 0;
2740 if (is_hotplug) {
2741 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2742 dev);
2743 return 0;
2746 } else if (!strcmp(devname, "wacom-tablet")) {
2747 dev = usb_wacom_init();
2748 } else if (strstart(devname, "serial:", &p)) {
2749 dev = usb_serial_init(p);
2750 #ifdef CONFIG_BRLAPI
2751 } else if (!strcmp(devname, "braille")) {
2752 dev = usb_baum_init();
2753 #endif
2754 } else if (strstart(devname, "net:", &p)) {
2755 int nic = nb_nics;
2757 if (net_client_init("nic", p) < 0)
2758 return -1;
2759 nd_table[nic].model = "usb";
2760 dev = usb_net_init(&nd_table[nic]);
2761 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2762 dev = usb_bt_init(devname[2] ? hci_init(p) :
2763 bt_new_hci(qemu_find_bt_vlan(0)));
2764 } else {
2765 return -1;
2767 if (!dev)
2768 return -1;
2770 return usb_device_add_dev(dev);
2773 int usb_device_del_addr(int bus_num, int addr)
2775 USBPort *port;
2776 USBPort **lastp;
2777 USBDevice *dev;
2779 if (!used_usb_ports)
2780 return -1;
2782 if (bus_num != 0)
2783 return -1;
2785 lastp = &used_usb_ports;
2786 port = used_usb_ports;
2787 while (port && port->dev->addr != addr) {
2788 lastp = &port->next;
2789 port = port->next;
2792 if (!port)
2793 return -1;
2795 dev = port->dev;
2796 *lastp = port->next;
2797 usb_attach(port, NULL);
2798 dev->handle_destroy(dev);
2799 port->next = free_usb_ports;
2800 free_usb_ports = port;
2801 return 0;
2804 static int usb_device_del(const char *devname)
2806 int bus_num, addr;
2807 const char *p;
2809 if (strstart(devname, "host:", &p))
2810 return usb_host_device_close(p);
2812 if (!used_usb_ports)
2813 return -1;
2815 p = strchr(devname, '.');
2816 if (!p)
2817 return -1;
2818 bus_num = strtoul(devname, NULL, 0);
2819 addr = strtoul(p + 1, NULL, 0);
2821 return usb_device_del_addr(bus_num, addr);
2824 void do_usb_add(Monitor *mon, const char *devname)
2826 usb_device_add(devname, 1);
2829 void do_usb_del(Monitor *mon, const char *devname)
2831 usb_device_del(devname);
2834 void usb_info(Monitor *mon)
2836 USBDevice *dev;
2837 USBPort *port;
2838 const char *speed_str;
2840 if (!usb_enabled) {
2841 monitor_printf(mon, "USB support not enabled\n");
2842 return;
2845 for (port = used_usb_ports; port; port = port->next) {
2846 dev = port->dev;
2847 if (!dev)
2848 continue;
2849 switch(dev->speed) {
2850 case USB_SPEED_LOW:
2851 speed_str = "1.5";
2852 break;
2853 case USB_SPEED_FULL:
2854 speed_str = "12";
2855 break;
2856 case USB_SPEED_HIGH:
2857 speed_str = "480";
2858 break;
2859 default:
2860 speed_str = "?";
2861 break;
2863 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2864 0, dev->addr, speed_str, dev->devname);
2868 /***********************************************************/
2869 /* PCMCIA/Cardbus */
2871 static struct pcmcia_socket_entry_s {
2872 PCMCIASocket *socket;
2873 struct pcmcia_socket_entry_s *next;
2874 } *pcmcia_sockets = 0;
2876 void pcmcia_socket_register(PCMCIASocket *socket)
2878 struct pcmcia_socket_entry_s *entry;
2880 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2881 entry->socket = socket;
2882 entry->next = pcmcia_sockets;
2883 pcmcia_sockets = entry;
2886 void pcmcia_socket_unregister(PCMCIASocket *socket)
2888 struct pcmcia_socket_entry_s *entry, **ptr;
2890 ptr = &pcmcia_sockets;
2891 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2892 if (entry->socket == socket) {
2893 *ptr = entry->next;
2894 qemu_free(entry);
2898 void pcmcia_info(Monitor *mon)
2900 struct pcmcia_socket_entry_s *iter;
2902 if (!pcmcia_sockets)
2903 monitor_printf(mon, "No PCMCIA sockets\n");
2905 for (iter = pcmcia_sockets; iter; iter = iter->next)
2906 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2907 iter->socket->attached ? iter->socket->card_string :
2908 "Empty");
2911 /***********************************************************/
2912 /* register display */
2914 struct DisplayAllocator default_allocator = {
2915 defaultallocator_create_displaysurface,
2916 defaultallocator_resize_displaysurface,
2917 defaultallocator_free_displaysurface
2920 void register_displaystate(DisplayState *ds)
2922 DisplayState **s;
2923 s = &display_state;
2924 while (*s != NULL)
2925 s = &(*s)->next;
2926 ds->next = NULL;
2927 *s = ds;
2930 DisplayState *get_displaystate(void)
2932 return display_state;
2935 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2937 if(ds->allocator == &default_allocator) ds->allocator = da;
2938 return ds->allocator;
2941 /* dumb display */
2943 static void dumb_display_init(void)
2945 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2946 ds->allocator = &default_allocator;
2947 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2948 register_displaystate(ds);
2951 /***********************************************************/
2952 /* I/O handling */
2954 typedef struct IOHandlerRecord {
2955 int fd;
2956 IOCanRWHandler *fd_read_poll;
2957 IOHandler *fd_read;
2958 IOHandler *fd_write;
2959 int deleted;
2960 void *opaque;
2961 /* temporary data */
2962 struct pollfd *ufd;
2963 struct IOHandlerRecord *next;
2964 } IOHandlerRecord;
2966 static IOHandlerRecord *first_io_handler;
2968 /* XXX: fd_read_poll should be suppressed, but an API change is
2969 necessary in the character devices to suppress fd_can_read(). */
2970 int qemu_set_fd_handler2(int fd,
2971 IOCanRWHandler *fd_read_poll,
2972 IOHandler *fd_read,
2973 IOHandler *fd_write,
2974 void *opaque)
2976 IOHandlerRecord **pioh, *ioh;
2978 if (!fd_read && !fd_write) {
2979 pioh = &first_io_handler;
2980 for(;;) {
2981 ioh = *pioh;
2982 if (ioh == NULL)
2983 break;
2984 if (ioh->fd == fd) {
2985 ioh->deleted = 1;
2986 break;
2988 pioh = &ioh->next;
2990 } else {
2991 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2992 if (ioh->fd == fd)
2993 goto found;
2995 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2996 ioh->next = first_io_handler;
2997 first_io_handler = ioh;
2998 found:
2999 ioh->fd = fd;
3000 ioh->fd_read_poll = fd_read_poll;
3001 ioh->fd_read = fd_read;
3002 ioh->fd_write = fd_write;
3003 ioh->opaque = opaque;
3004 ioh->deleted = 0;
3006 qemu_notify_event();
3007 return 0;
3010 int qemu_set_fd_handler(int fd,
3011 IOHandler *fd_read,
3012 IOHandler *fd_write,
3013 void *opaque)
3015 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3018 #ifdef _WIN32
3019 /***********************************************************/
3020 /* Polling handling */
3022 typedef struct PollingEntry {
3023 PollingFunc *func;
3024 void *opaque;
3025 struct PollingEntry *next;
3026 } PollingEntry;
3028 static PollingEntry *first_polling_entry;
3030 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3032 PollingEntry **ppe, *pe;
3033 pe = qemu_mallocz(sizeof(PollingEntry));
3034 pe->func = func;
3035 pe->opaque = opaque;
3036 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3037 *ppe = pe;
3038 return 0;
3041 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3043 PollingEntry **ppe, *pe;
3044 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3045 pe = *ppe;
3046 if (pe->func == func && pe->opaque == opaque) {
3047 *ppe = pe->next;
3048 qemu_free(pe);
3049 break;
3054 /***********************************************************/
3055 /* Wait objects support */
3056 typedef struct WaitObjects {
3057 int num;
3058 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3059 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3060 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3061 } WaitObjects;
3063 static WaitObjects wait_objects = {0};
3065 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3067 WaitObjects *w = &wait_objects;
3069 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3070 return -1;
3071 w->events[w->num] = handle;
3072 w->func[w->num] = func;
3073 w->opaque[w->num] = opaque;
3074 w->num++;
3075 return 0;
3078 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3080 int i, found;
3081 WaitObjects *w = &wait_objects;
3083 found = 0;
3084 for (i = 0; i < w->num; i++) {
3085 if (w->events[i] == handle)
3086 found = 1;
3087 if (found) {
3088 w->events[i] = w->events[i + 1];
3089 w->func[i] = w->func[i + 1];
3090 w->opaque[i] = w->opaque[i + 1];
3093 if (found)
3094 w->num--;
3096 #endif
3098 /***********************************************************/
3099 /* ram save/restore */
3101 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3103 int v;
3105 v = qemu_get_byte(f);
3106 switch(v) {
3107 case 0:
3108 if (qemu_get_buffer(f, buf, len) != len)
3109 return -EIO;
3110 break;
3111 case 1:
3112 v = qemu_get_byte(f);
3113 memset(buf, v, len);
3114 break;
3115 default:
3116 return -EINVAL;
3119 if (qemu_file_has_error(f))
3120 return -EIO;
3122 return 0;
3125 static int ram_load_v1(QEMUFile *f, void *opaque)
3127 int ret;
3128 ram_addr_t i;
3130 if (qemu_get_be32(f) != last_ram_offset)
3131 return -EINVAL;
3132 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
3133 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3134 continue;
3135 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
3136 if (ret)
3137 return ret;
3139 return 0;
3142 #define BDRV_HASH_BLOCK_SIZE 1024
3143 #define IOBUF_SIZE 4096
3144 #define RAM_CBLOCK_MAGIC 0xfabe
3146 typedef struct RamDecompressState {
3147 z_stream zstream;
3148 QEMUFile *f;
3149 uint8_t buf[IOBUF_SIZE];
3150 } RamDecompressState;
3152 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3154 int ret;
3155 memset(s, 0, sizeof(*s));
3156 s->f = f;
3157 ret = inflateInit(&s->zstream);
3158 if (ret != Z_OK)
3159 return -1;
3160 return 0;
3163 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3165 int ret, clen;
3167 s->zstream.avail_out = len;
3168 s->zstream.next_out = buf;
3169 while (s->zstream.avail_out > 0) {
3170 if (s->zstream.avail_in == 0) {
3171 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3172 return -1;
3173 clen = qemu_get_be16(s->f);
3174 if (clen > IOBUF_SIZE)
3175 return -1;
3176 qemu_get_buffer(s->f, s->buf, clen);
3177 s->zstream.avail_in = clen;
3178 s->zstream.next_in = s->buf;
3180 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3181 if (ret != Z_OK && ret != Z_STREAM_END) {
3182 return -1;
3185 return 0;
3188 static void ram_decompress_close(RamDecompressState *s)
3190 inflateEnd(&s->zstream);
3193 #define RAM_SAVE_FLAG_FULL 0x01
3194 #define RAM_SAVE_FLAG_COMPRESS 0x02
3195 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3196 #define RAM_SAVE_FLAG_PAGE 0x08
3197 #define RAM_SAVE_FLAG_EOS 0x10
3199 static int is_dup_page(uint8_t *page, uint8_t ch)
3201 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3202 uint32_t *array = (uint32_t *)page;
3203 int i;
3205 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3206 if (array[i] != val)
3207 return 0;
3210 return 1;
3213 static int ram_save_block(QEMUFile *f)
3215 static ram_addr_t current_addr = 0;
3216 ram_addr_t saved_addr = current_addr;
3217 ram_addr_t addr = 0;
3218 int found = 0;
3220 while (addr < last_ram_offset) {
3221 if (kvm_enabled() && current_addr == 0) {
3222 int r;
3223 r = kvm_update_dirty_pages_log();
3224 if (r) {
3225 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3226 qemu_file_set_error(f);
3227 return 0;
3230 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3231 uint8_t *p;
3233 cpu_physical_memory_reset_dirty(current_addr,
3234 current_addr + TARGET_PAGE_SIZE,
3235 MIGRATION_DIRTY_FLAG);
3237 p = qemu_get_ram_ptr(current_addr);
3239 if (is_dup_page(p, *p)) {
3240 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3241 qemu_put_byte(f, *p);
3242 } else {
3243 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3244 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3247 found = 1;
3248 break;
3250 addr += TARGET_PAGE_SIZE;
3251 current_addr = (saved_addr + addr) % last_ram_offset;
3254 return found;
3257 static ram_addr_t ram_save_threshold = 10;
3258 static uint64_t bytes_transferred = 0;
3260 static ram_addr_t ram_save_remaining(void)
3262 ram_addr_t addr;
3263 ram_addr_t count = 0;
3265 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3266 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3267 count++;
3270 return count;
3273 uint64_t ram_bytes_remaining(void)
3275 return ram_save_remaining() * TARGET_PAGE_SIZE;
3278 uint64_t ram_bytes_transferred(void)
3280 return bytes_transferred;
3283 uint64_t ram_bytes_total(void)
3285 return last_ram_offset;
3288 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3290 ram_addr_t addr;
3292 if (cpu_physical_sync_dirty_bitmap(0, last_ram_offset) != 0) {
3293 qemu_file_set_error(f);
3294 return 0;
3297 if (stage == 1) {
3298 /* Make sure all dirty bits are set */
3299 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3300 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3301 cpu_physical_memory_set_dirty(addr);
3304 /* Enable dirty memory tracking */
3305 cpu_physical_memory_set_dirty_tracking(1);
3307 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3310 while (!qemu_file_rate_limit(f)) {
3311 int ret;
3313 ret = ram_save_block(f);
3314 bytes_transferred += ret * TARGET_PAGE_SIZE;
3315 if (ret == 0) /* no more blocks */
3316 break;
3319 /* try transferring iterative blocks of memory */
3321 if (stage == 3) {
3323 /* flush all remaining blocks regardless of rate limiting */
3324 while (ram_save_block(f) != 0) {
3325 bytes_transferred += TARGET_PAGE_SIZE;
3327 cpu_physical_memory_set_dirty_tracking(0);
3330 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3332 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3335 static int ram_load_dead(QEMUFile *f, void *opaque)
3337 RamDecompressState s1, *s = &s1;
3338 uint8_t buf[10];
3339 ram_addr_t i;
3341 if (ram_decompress_open(s, f) < 0)
3342 return -EINVAL;
3343 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3344 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3345 continue;
3346 if (ram_decompress_buf(s, buf, 1) < 0) {
3347 fprintf(stderr, "Error while reading ram block header\n");
3348 goto error;
3350 if (buf[0] == 0) {
3351 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3352 BDRV_HASH_BLOCK_SIZE) < 0) {
3353 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3354 goto error;
3356 } else {
3357 error:
3358 printf("Error block header\n");
3359 return -EINVAL;
3362 ram_decompress_close(s);
3364 return 0;
3367 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3369 ram_addr_t addr;
3370 int flags;
3372 if (version_id == 1)
3373 return ram_load_v1(f, opaque);
3375 if (version_id == 2) {
3376 if (qemu_get_be32(f) != last_ram_offset)
3377 return -EINVAL;
3378 return ram_load_dead(f, opaque);
3381 if (version_id != 3)
3382 return -EINVAL;
3384 do {
3385 addr = qemu_get_be64(f);
3387 flags = addr & ~TARGET_PAGE_MASK;
3388 addr &= TARGET_PAGE_MASK;
3390 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3391 if (addr != last_ram_offset)
3392 return -EINVAL;
3395 if (flags & RAM_SAVE_FLAG_FULL) {
3396 if (ram_load_dead(f, opaque) < 0)
3397 return -EINVAL;
3400 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3401 uint8_t ch = qemu_get_byte(f);
3402 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3403 } else if (flags & RAM_SAVE_FLAG_PAGE)
3404 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3405 } while (!(flags & RAM_SAVE_FLAG_EOS));
3407 return 0;
3410 void qemu_service_io(void)
3412 qemu_notify_event();
3415 /***********************************************************/
3416 /* bottom halves (can be seen as timers which expire ASAP) */
3418 struct QEMUBH {
3419 QEMUBHFunc *cb;
3420 void *opaque;
3421 int scheduled;
3422 int idle;
3423 int deleted;
3424 QEMUBH *next;
3427 static QEMUBH *first_bh = NULL;
3429 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3431 QEMUBH *bh;
3432 bh = qemu_mallocz(sizeof(QEMUBH));
3433 bh->cb = cb;
3434 bh->opaque = opaque;
3435 bh->next = first_bh;
3436 first_bh = bh;
3437 return bh;
3440 int qemu_bh_poll(void)
3442 QEMUBH *bh, **bhp;
3443 int ret;
3445 ret = 0;
3446 for (bh = first_bh; bh; bh = bh->next) {
3447 if (!bh->deleted && bh->scheduled) {
3448 bh->scheduled = 0;
3449 if (!bh->idle)
3450 ret = 1;
3451 bh->idle = 0;
3452 bh->cb(bh->opaque);
3456 /* remove deleted bhs */
3457 bhp = &first_bh;
3458 while (*bhp) {
3459 bh = *bhp;
3460 if (bh->deleted) {
3461 *bhp = bh->next;
3462 qemu_free(bh);
3463 } else
3464 bhp = &bh->next;
3467 return ret;
3470 void qemu_bh_schedule_idle(QEMUBH *bh)
3472 if (bh->scheduled)
3473 return;
3474 bh->scheduled = 1;
3475 bh->idle = 1;
3478 void qemu_bh_schedule(QEMUBH *bh)
3480 if (bh->scheduled)
3481 return;
3482 bh->scheduled = 1;
3483 bh->idle = 0;
3484 /* stop the currently executing CPU to execute the BH ASAP */
3485 qemu_notify_event();
3488 void qemu_bh_cancel(QEMUBH *bh)
3490 bh->scheduled = 0;
3493 void qemu_bh_delete(QEMUBH *bh)
3495 bh->scheduled = 0;
3496 bh->deleted = 1;
3499 static void qemu_bh_update_timeout(int *timeout)
3501 QEMUBH *bh;
3503 for (bh = first_bh; bh; bh = bh->next) {
3504 if (!bh->deleted && bh->scheduled) {
3505 if (bh->idle) {
3506 /* idle bottom halves will be polled at least
3507 * every 10ms */
3508 *timeout = MIN(10, *timeout);
3509 } else {
3510 /* non-idle bottom halves will be executed
3511 * immediately */
3512 *timeout = 0;
3513 break;
3519 /***********************************************************/
3520 /* machine registration */
3522 static QEMUMachine *first_machine = NULL;
3523 QEMUMachine *current_machine = NULL;
3525 int qemu_register_machine(QEMUMachine *m)
3527 QEMUMachine **pm;
3528 pm = &first_machine;
3529 while (*pm != NULL)
3530 pm = &(*pm)->next;
3531 m->next = NULL;
3532 *pm = m;
3533 return 0;
3536 static QEMUMachine *find_machine(const char *name)
3538 QEMUMachine *m;
3540 for(m = first_machine; m != NULL; m = m->next) {
3541 if (!strcmp(m->name, name))
3542 return m;
3544 return NULL;
3547 static QEMUMachine *find_default_machine(void)
3549 QEMUMachine *m;
3551 for(m = first_machine; m != NULL; m = m->next) {
3552 if (m->is_default) {
3553 return m;
3556 return NULL;
3559 /***********************************************************/
3560 /* main execution loop */
3562 static void gui_update(void *opaque)
3564 uint64_t interval = GUI_REFRESH_INTERVAL;
3565 DisplayState *ds = opaque;
3566 DisplayChangeListener *dcl = ds->listeners;
3568 dpy_refresh(ds);
3570 while (dcl != NULL) {
3571 if (dcl->gui_timer_interval &&
3572 dcl->gui_timer_interval < interval)
3573 interval = dcl->gui_timer_interval;
3574 dcl = dcl->next;
3576 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3579 static void nographic_update(void *opaque)
3581 uint64_t interval = GUI_REFRESH_INTERVAL;
3583 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3586 struct vm_change_state_entry {
3587 VMChangeStateHandler *cb;
3588 void *opaque;
3589 LIST_ENTRY (vm_change_state_entry) entries;
3592 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3594 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3595 void *opaque)
3597 VMChangeStateEntry *e;
3599 e = qemu_mallocz(sizeof (*e));
3601 e->cb = cb;
3602 e->opaque = opaque;
3603 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3604 return e;
3607 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3609 LIST_REMOVE (e, entries);
3610 qemu_free (e);
3613 static void vm_state_notify(int running, int reason)
3615 VMChangeStateEntry *e;
3617 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3618 e->cb(e->opaque, running, reason);
3622 static void resume_all_vcpus(void);
3623 static void pause_all_vcpus(void);
3625 void vm_start(void)
3627 if (!vm_running) {
3628 cpu_enable_ticks();
3629 vm_running = 1;
3630 vm_state_notify(1, 0);
3631 qemu_rearm_alarm_timer(alarm_timer);
3632 resume_all_vcpus();
3636 /* reset/shutdown handler */
3638 typedef struct QEMUResetEntry {
3639 QEMUResetHandler *func;
3640 void *opaque;
3641 int order;
3642 struct QEMUResetEntry *next;
3643 } QEMUResetEntry;
3645 static QEMUResetEntry *first_reset_entry;
3646 static int reset_requested;
3647 static int shutdown_requested;
3648 static int powerdown_requested;
3649 static int debug_requested;
3650 static int vmstop_requested;
3652 int qemu_no_shutdown(void)
3654 int r = no_shutdown;
3655 no_shutdown = 0;
3656 return r;
3659 int qemu_shutdown_requested(void)
3661 int r = shutdown_requested;
3662 shutdown_requested = 0;
3663 return r;
3666 int qemu_reset_requested(void)
3668 int r = reset_requested;
3669 reset_requested = 0;
3670 return r;
3673 int qemu_powerdown_requested(void)
3675 int r = powerdown_requested;
3676 powerdown_requested = 0;
3677 return r;
3680 static int qemu_debug_requested(void)
3682 int r = debug_requested;
3683 debug_requested = 0;
3684 return r;
3687 static int qemu_vmstop_requested(void)
3689 int r = vmstop_requested;
3690 vmstop_requested = 0;
3691 return r;
3694 static void do_vm_stop(int reason)
3696 if (vm_running) {
3697 cpu_disable_ticks();
3698 vm_running = 0;
3699 pause_all_vcpus();
3700 vm_state_notify(0, reason);
3704 void qemu_register_reset(QEMUResetHandler *func, int order, void *opaque)
3706 QEMUResetEntry **pre, *re;
3708 pre = &first_reset_entry;
3709 while (*pre != NULL && (*pre)->order >= order) {
3710 pre = &(*pre)->next;
3712 re = qemu_mallocz(sizeof(QEMUResetEntry));
3713 re->func = func;
3714 re->opaque = opaque;
3715 re->order = order;
3716 re->next = NULL;
3717 *pre = re;
3720 void qemu_system_reset(void)
3722 QEMUResetEntry *re;
3724 /* reset all devices */
3725 for(re = first_reset_entry; re != NULL; re = re->next) {
3726 re->func(re->opaque);
3730 void qemu_system_reset_request(void)
3732 if (no_reboot) {
3733 shutdown_requested = 1;
3734 } else {
3735 reset_requested = 1;
3737 if (cpu_single_env) {
3738 qemu_kvm_cpu_stop(cpu_single_env);
3739 cpu_exit(cpu_single_env);
3741 qemu_notify_event();
3744 void qemu_system_shutdown_request(void)
3746 shutdown_requested = 1;
3747 qemu_notify_event();
3750 void qemu_system_powerdown_request(void)
3752 powerdown_requested = 1;
3753 qemu_notify_event();
3756 #ifdef CONFIG_IOTHREAD
3757 static void qemu_system_vmstop_request(int reason)
3759 vmstop_requested = reason;
3760 qemu_notify_event();
3762 #endif
3764 #ifndef _WIN32
3765 static int io_thread_fd = -1;
3767 static void qemu_event_increment(void)
3769 static const char byte = 0;
3771 if (io_thread_fd == -1)
3772 return;
3774 write(io_thread_fd, &byte, sizeof(byte));
3777 static void qemu_event_read(void *opaque)
3779 int fd = (unsigned long)opaque;
3780 ssize_t len;
3782 /* Drain the notify pipe */
3783 do {
3784 char buffer[512];
3785 len = read(fd, buffer, sizeof(buffer));
3786 } while ((len == -1 && errno == EINTR) || len > 0);
3789 static int qemu_event_init(void)
3791 int err;
3792 int fds[2];
3794 err = pipe(fds);
3795 if (err == -1)
3796 return -errno;
3798 err = fcntl_setfl(fds[0], O_NONBLOCK);
3799 if (err < 0)
3800 goto fail;
3802 err = fcntl_setfl(fds[1], O_NONBLOCK);
3803 if (err < 0)
3804 goto fail;
3806 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3807 (void *)(unsigned long)fds[0]);
3809 io_thread_fd = fds[1];
3810 return 0;
3812 fail:
3813 close(fds[0]);
3814 close(fds[1]);
3815 return err;
3817 #else
3818 HANDLE qemu_event_handle;
3820 static void dummy_event_handler(void *opaque)
3824 static int qemu_event_init(void)
3826 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3827 if (!qemu_event_handle) {
3828 perror("Failed CreateEvent");
3829 return -1;
3831 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3832 return 0;
3835 static void qemu_event_increment(void)
3837 SetEvent(qemu_event_handle);
3839 #endif
3841 static int cpu_can_run(CPUState *env)
3843 if (env->stop)
3844 return 0;
3845 if (env->stopped)
3846 return 0;
3847 return 1;
3850 #ifndef CONFIG_IOTHREAD
3851 static int qemu_init_main_loop(void)
3853 return qemu_event_init();
3856 void qemu_init_vcpu(void *_env)
3858 CPUState *env = _env;
3860 if (kvm_enabled())
3861 kvm_init_vcpu(env);
3862 return;
3865 int qemu_cpu_self(void *env)
3867 return 1;
3870 static void resume_all_vcpus(void)
3874 static void pause_all_vcpus(void)
3878 void qemu_cpu_kick(void *env)
3880 return;
3883 void qemu_notify_event(void)
3885 CPUState *env = cpu_single_env;
3887 if (kvm_enabled()) {
3888 qemu_kvm_notify_work();
3889 return;
3891 if (env) {
3892 cpu_exit(env);
3893 #ifdef USE_KQEMU
3894 if (env->kqemu_enabled)
3895 kqemu_cpu_interrupt(env);
3896 #endif
3900 #define qemu_mutex_lock_iothread() do { } while (0)
3901 #define qemu_mutex_unlock_iothread() do { } while (0)
3903 void vm_stop(int reason)
3905 do_vm_stop(reason);
3908 #else /* CONFIG_IOTHREAD */
3910 #include "qemu-thread.h"
3912 QemuMutex qemu_global_mutex;
3913 static QemuMutex qemu_fair_mutex;
3915 static QemuThread io_thread;
3917 static QemuThread *tcg_cpu_thread;
3918 static QemuCond *tcg_halt_cond;
3920 static int qemu_system_ready;
3921 /* cpu creation */
3922 static QemuCond qemu_cpu_cond;
3923 /* system init */
3924 static QemuCond qemu_system_cond;
3925 static QemuCond qemu_pause_cond;
3927 static void block_io_signals(void);
3928 static void unblock_io_signals(void);
3929 static int tcg_has_work(void);
3931 static int qemu_init_main_loop(void)
3933 int ret;
3935 ret = qemu_event_init();
3936 if (ret)
3937 return ret;
3939 qemu_cond_init(&qemu_pause_cond);
3940 qemu_mutex_init(&qemu_fair_mutex);
3941 qemu_mutex_init(&qemu_global_mutex);
3942 qemu_mutex_lock(&qemu_global_mutex);
3944 unblock_io_signals();
3945 qemu_thread_self(&io_thread);
3947 return 0;
3950 static void qemu_wait_io_event(CPUState *env)
3952 while (!tcg_has_work())
3953 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3955 qemu_mutex_unlock(&qemu_global_mutex);
3958 * Users of qemu_global_mutex can be starved, having no chance
3959 * to acquire it since this path will get to it first.
3960 * So use another lock to provide fairness.
3962 qemu_mutex_lock(&qemu_fair_mutex);
3963 qemu_mutex_unlock(&qemu_fair_mutex);
3965 qemu_mutex_lock(&qemu_global_mutex);
3966 if (env->stop) {
3967 env->stop = 0;
3968 env->stopped = 1;
3969 qemu_cond_signal(&qemu_pause_cond);
3973 static int qemu_cpu_exec(CPUState *env);
3975 static void *kvm_cpu_thread_fn(void *arg)
3977 CPUState *env = arg;
3979 block_io_signals();
3980 qemu_thread_self(env->thread);
3982 /* signal CPU creation */
3983 qemu_mutex_lock(&qemu_global_mutex);
3984 env->created = 1;
3985 qemu_cond_signal(&qemu_cpu_cond);
3987 /* and wait for machine initialization */
3988 while (!qemu_system_ready)
3989 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3991 while (1) {
3992 if (cpu_can_run(env))
3993 qemu_cpu_exec(env);
3994 qemu_wait_io_event(env);
3997 return NULL;
4000 static void tcg_cpu_exec(void);
4002 static void *tcg_cpu_thread_fn(void *arg)
4004 CPUState *env = arg;
4006 block_io_signals();
4007 qemu_thread_self(env->thread);
4009 /* signal CPU creation */
4010 qemu_mutex_lock(&qemu_global_mutex);
4011 for (env = first_cpu; env != NULL; env = env->next_cpu)
4012 env->created = 1;
4013 qemu_cond_signal(&qemu_cpu_cond);
4015 /* and wait for machine initialization */
4016 while (!qemu_system_ready)
4017 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
4019 while (1) {
4020 tcg_cpu_exec();
4021 qemu_wait_io_event(cur_cpu);
4024 return NULL;
4027 void qemu_cpu_kick(void *_env)
4029 CPUState *env = _env;
4030 qemu_cond_broadcast(env->halt_cond);
4031 if (kvm_enabled())
4032 qemu_thread_signal(env->thread, SIGUSR1);
4035 int qemu_cpu_self(void *env)
4037 return (cpu_single_env != NULL);
4040 static void cpu_signal(int sig)
4042 if (cpu_single_env)
4043 cpu_exit(cpu_single_env);
4046 static void block_io_signals(void)
4048 sigset_t set;
4049 struct sigaction sigact;
4051 sigemptyset(&set);
4052 sigaddset(&set, SIGUSR2);
4053 sigaddset(&set, SIGIO);
4054 sigaddset(&set, SIGALRM);
4055 pthread_sigmask(SIG_BLOCK, &set, NULL);
4057 sigemptyset(&set);
4058 sigaddset(&set, SIGUSR1);
4059 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4061 memset(&sigact, 0, sizeof(sigact));
4062 sigact.sa_handler = cpu_signal;
4063 sigaction(SIGUSR1, &sigact, NULL);
4066 static void unblock_io_signals(void)
4068 sigset_t set;
4070 sigemptyset(&set);
4071 sigaddset(&set, SIGUSR2);
4072 sigaddset(&set, SIGIO);
4073 sigaddset(&set, SIGALRM);
4074 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4076 sigemptyset(&set);
4077 sigaddset(&set, SIGUSR1);
4078 pthread_sigmask(SIG_BLOCK, &set, NULL);
4081 static void qemu_signal_lock(unsigned int msecs)
4083 qemu_mutex_lock(&qemu_fair_mutex);
4085 while (qemu_mutex_trylock(&qemu_global_mutex)) {
4086 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
4087 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
4088 break;
4090 qemu_mutex_unlock(&qemu_fair_mutex);
4093 static void qemu_mutex_lock_iothread(void)
4095 if (kvm_enabled()) {
4096 qemu_mutex_lock(&qemu_fair_mutex);
4097 qemu_mutex_lock(&qemu_global_mutex);
4098 qemu_mutex_unlock(&qemu_fair_mutex);
4099 } else
4100 qemu_signal_lock(100);
4103 static void qemu_mutex_unlock_iothread(void)
4105 qemu_mutex_unlock(&qemu_global_mutex);
4108 static int all_vcpus_paused(void)
4110 CPUState *penv = first_cpu;
4112 while (penv) {
4113 if (!penv->stopped)
4114 return 0;
4115 penv = (CPUState *)penv->next_cpu;
4118 return 1;
4121 static void pause_all_vcpus(void)
4123 CPUState *penv = first_cpu;
4125 while (penv) {
4126 penv->stop = 1;
4127 qemu_thread_signal(penv->thread, SIGUSR1);
4128 qemu_cpu_kick(penv);
4129 penv = (CPUState *)penv->next_cpu;
4132 while (!all_vcpus_paused()) {
4133 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
4134 penv = first_cpu;
4135 while (penv) {
4136 qemu_thread_signal(penv->thread, SIGUSR1);
4137 penv = (CPUState *)penv->next_cpu;
4142 static void resume_all_vcpus(void)
4144 CPUState *penv = first_cpu;
4146 while (penv) {
4147 penv->stop = 0;
4148 penv->stopped = 0;
4149 qemu_thread_signal(penv->thread, SIGUSR1);
4150 qemu_cpu_kick(penv);
4151 penv = (CPUState *)penv->next_cpu;
4155 static void tcg_init_vcpu(void *_env)
4157 CPUState *env = _env;
4158 /* share a single thread for all cpus with TCG */
4159 if (!tcg_cpu_thread) {
4160 env->thread = qemu_mallocz(sizeof(QemuThread));
4161 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4162 qemu_cond_init(env->halt_cond);
4163 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
4164 while (env->created == 0)
4165 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4166 tcg_cpu_thread = env->thread;
4167 tcg_halt_cond = env->halt_cond;
4168 } else {
4169 env->thread = tcg_cpu_thread;
4170 env->halt_cond = tcg_halt_cond;
4174 static void kvm_start_vcpu(CPUState *env)
4176 kvm_init_vcpu(env);
4177 env->thread = qemu_mallocz(sizeof(QemuThread));
4178 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4179 qemu_cond_init(env->halt_cond);
4180 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
4181 while (env->created == 0)
4182 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4185 void qemu_init_vcpu(void *_env)
4187 CPUState *env = _env;
4189 if (kvm_enabled())
4190 kvm_start_vcpu(env);
4191 else
4192 tcg_init_vcpu(env);
4195 void qemu_notify_event(void)
4197 qemu_event_increment();
4200 void vm_stop(int reason)
4202 QemuThread me;
4203 qemu_thread_self(&me);
4205 if (!qemu_thread_equal(&me, &io_thread)) {
4206 qemu_system_vmstop_request(reason);
4208 * FIXME: should not return to device code in case
4209 * vm_stop() has been requested.
4211 if (cpu_single_env) {
4212 cpu_exit(cpu_single_env);
4213 cpu_single_env->stop = 1;
4215 return;
4217 do_vm_stop(reason);
4220 #endif
4223 #ifdef _WIN32
4224 static void host_main_loop_wait(int *timeout)
4226 int ret, ret2, i;
4227 PollingEntry *pe;
4230 /* XXX: need to suppress polling by better using win32 events */
4231 ret = 0;
4232 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4233 ret |= pe->func(pe->opaque);
4235 if (ret == 0) {
4236 int err;
4237 WaitObjects *w = &wait_objects;
4239 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4240 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4241 if (w->func[ret - WAIT_OBJECT_0])
4242 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4244 /* Check for additional signaled events */
4245 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4247 /* Check if event is signaled */
4248 ret2 = WaitForSingleObject(w->events[i], 0);
4249 if(ret2 == WAIT_OBJECT_0) {
4250 if (w->func[i])
4251 w->func[i](w->opaque[i]);
4252 } else if (ret2 == WAIT_TIMEOUT) {
4253 } else {
4254 err = GetLastError();
4255 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4258 } else if (ret == WAIT_TIMEOUT) {
4259 } else {
4260 err = GetLastError();
4261 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4265 *timeout = 0;
4267 #else
4268 static void host_main_loop_wait(int *timeout)
4271 #endif
4273 void main_loop_wait(int timeout)
4275 IOHandlerRecord *ioh;
4276 fd_set rfds, wfds, xfds;
4277 int ret, nfds;
4278 struct timeval tv;
4280 qemu_bh_update_timeout(&timeout);
4282 host_main_loop_wait(&timeout);
4284 /* poll any events */
4285 /* XXX: separate device handlers from system ones */
4286 nfds = -1;
4287 FD_ZERO(&rfds);
4288 FD_ZERO(&wfds);
4289 FD_ZERO(&xfds);
4290 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4291 if (ioh->deleted)
4292 continue;
4293 if (ioh->fd_read &&
4294 (!ioh->fd_read_poll ||
4295 ioh->fd_read_poll(ioh->opaque) != 0)) {
4296 FD_SET(ioh->fd, &rfds);
4297 if (ioh->fd > nfds)
4298 nfds = ioh->fd;
4300 if (ioh->fd_write) {
4301 FD_SET(ioh->fd, &wfds);
4302 if (ioh->fd > nfds)
4303 nfds = ioh->fd;
4307 tv.tv_sec = timeout / 1000;
4308 tv.tv_usec = (timeout % 1000) * 1000;
4310 #if defined(CONFIG_SLIRP)
4311 if (slirp_is_inited()) {
4312 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4314 #endif
4315 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4316 if (ret > 0) {
4317 IOHandlerRecord **pioh;
4319 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4320 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4321 ioh->fd_read(ioh->opaque);
4322 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
4323 FD_CLR(ioh->fd, &rfds);
4325 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4326 ioh->fd_write(ioh->opaque);
4330 /* remove deleted IO handlers */
4331 pioh = &first_io_handler;
4332 while (*pioh) {
4333 ioh = *pioh;
4334 if (ioh->deleted) {
4335 *pioh = ioh->next;
4336 qemu_free(ioh);
4337 } else
4338 pioh = &ioh->next;
4341 #if defined(CONFIG_SLIRP)
4342 if (slirp_is_inited()) {
4343 if (ret < 0) {
4344 FD_ZERO(&rfds);
4345 FD_ZERO(&wfds);
4346 FD_ZERO(&xfds);
4348 slirp_select_poll(&rfds, &wfds, &xfds);
4350 #endif
4352 /* rearm timer, if not periodic */
4353 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4354 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4355 qemu_rearm_alarm_timer(alarm_timer);
4358 /* vm time timers */
4359 if (vm_running) {
4360 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4361 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4362 qemu_get_clock(vm_clock));
4365 /* real time timers */
4366 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4367 qemu_get_clock(rt_clock));
4369 /* Check bottom-halves last in case any of the earlier events triggered
4370 them. */
4371 qemu_bh_poll();
4375 static int qemu_cpu_exec(CPUState *env)
4377 int ret;
4378 #ifdef CONFIG_PROFILER
4379 int64_t ti;
4380 #endif
4382 #ifdef CONFIG_PROFILER
4383 ti = profile_getclock();
4384 #endif
4385 if (use_icount) {
4386 int64_t count;
4387 int decr;
4388 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4389 env->icount_decr.u16.low = 0;
4390 env->icount_extra = 0;
4391 count = qemu_next_deadline();
4392 count = (count + (1 << icount_time_shift) - 1)
4393 >> icount_time_shift;
4394 qemu_icount += count;
4395 decr = (count > 0xffff) ? 0xffff : count;
4396 count -= decr;
4397 env->icount_decr.u16.low = decr;
4398 env->icount_extra = count;
4400 ret = cpu_exec(env);
4401 #ifdef CONFIG_PROFILER
4402 qemu_time += profile_getclock() - ti;
4403 #endif
4404 if (use_icount) {
4405 /* Fold pending instructions back into the
4406 instruction counter, and clear the interrupt flag. */
4407 qemu_icount -= (env->icount_decr.u16.low
4408 + env->icount_extra);
4409 env->icount_decr.u32 = 0;
4410 env->icount_extra = 0;
4412 return ret;
4415 static void tcg_cpu_exec(void)
4417 int ret = 0;
4419 if (next_cpu == NULL)
4420 next_cpu = first_cpu;
4421 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4422 CPUState *env = cur_cpu = next_cpu;
4424 if (!vm_running)
4425 break;
4426 if (timer_alarm_pending) {
4427 timer_alarm_pending = 0;
4428 break;
4430 if (cpu_can_run(env))
4431 ret = qemu_cpu_exec(env);
4432 if (ret == EXCP_DEBUG) {
4433 gdb_set_stop_cpu(env);
4434 debug_requested = 1;
4435 break;
4440 static int cpu_has_work(CPUState *env)
4442 if (env->stop)
4443 return 1;
4444 if (env->stopped)
4445 return 0;
4446 if (!env->halted)
4447 return 1;
4448 if (qemu_cpu_has_work(env))
4449 return 1;
4450 return 0;
4453 static int tcg_has_work(void)
4455 CPUState *env;
4457 for (env = first_cpu; env != NULL; env = env->next_cpu)
4458 if (cpu_has_work(env))
4459 return 1;
4460 return 0;
4463 static int qemu_calculate_timeout(void)
4465 int timeout;
4467 if (!vm_running)
4468 timeout = 5000;
4469 else if (tcg_has_work())
4470 timeout = 0;
4471 else if (!use_icount)
4472 timeout = 5000;
4473 else {
4474 /* XXX: use timeout computed from timers */
4475 int64_t add;
4476 int64_t delta;
4477 /* Advance virtual time to the next event. */
4478 if (use_icount == 1) {
4479 /* When not using an adaptive execution frequency
4480 we tend to get badly out of sync with real time,
4481 so just delay for a reasonable amount of time. */
4482 delta = 0;
4483 } else {
4484 delta = cpu_get_icount() - cpu_get_clock();
4486 if (delta > 0) {
4487 /* If virtual time is ahead of real time then just
4488 wait for IO. */
4489 timeout = (delta / 1000000) + 1;
4490 } else {
4491 /* Wait for either IO to occur or the next
4492 timer event. */
4493 add = qemu_next_deadline();
4494 /* We advance the timer before checking for IO.
4495 Limit the amount we advance so that early IO
4496 activity won't get the guest too far ahead. */
4497 if (add > 10000000)
4498 add = 10000000;
4499 delta += add;
4500 add = (add + (1 << icount_time_shift) - 1)
4501 >> icount_time_shift;
4502 qemu_icount += add;
4503 timeout = delta / 1000000;
4504 if (timeout < 0)
4505 timeout = 0;
4509 return timeout;
4512 static int vm_can_run(void)
4514 if (powerdown_requested)
4515 return 0;
4516 if (reset_requested)
4517 return 0;
4518 if (shutdown_requested)
4519 return 0;
4520 if (debug_requested)
4521 return 0;
4522 return 1;
4525 static void main_loop(void)
4527 int r;
4529 if (kvm_enabled()) {
4530 kvm_main_loop();
4531 cpu_disable_ticks();
4532 return;
4535 #ifdef CONFIG_IOTHREAD
4536 qemu_system_ready = 1;
4537 qemu_cond_broadcast(&qemu_system_cond);
4538 #endif
4540 for (;;) {
4541 do {
4542 #ifdef CONFIG_PROFILER
4543 int64_t ti;
4544 #endif
4545 #ifndef CONFIG_IOTHREAD
4546 tcg_cpu_exec();
4547 #endif
4548 #ifdef CONFIG_PROFILER
4549 ti = profile_getclock();
4550 #endif
4551 #ifdef CONFIG_IOTHREAD
4552 main_loop_wait(1000);
4553 #else
4554 main_loop_wait(qemu_calculate_timeout());
4555 #endif
4556 #ifdef CONFIG_PROFILER
4557 dev_time += profile_getclock() - ti;
4558 #endif
4559 } while (vm_can_run());
4561 if (qemu_debug_requested())
4562 vm_stop(EXCP_DEBUG);
4563 if (qemu_shutdown_requested()) {
4564 if (no_shutdown) {
4565 vm_stop(0);
4566 no_shutdown = 0;
4567 } else
4568 break;
4570 if (qemu_reset_requested()) {
4571 pause_all_vcpus();
4572 qemu_system_reset();
4573 resume_all_vcpus();
4575 if (qemu_powerdown_requested())
4576 qemu_system_powerdown();
4577 if ((r = qemu_vmstop_requested()))
4578 vm_stop(r);
4580 pause_all_vcpus();
4583 static void version(void)
4585 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4588 static void help(int exitcode)
4590 version();
4591 printf("usage: %s [options] [disk_image]\n"
4592 "\n"
4593 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4594 "\n"
4595 #define DEF(option, opt_arg, opt_enum, opt_help) \
4596 opt_help
4597 #define DEFHEADING(text) stringify(text) "\n"
4598 #include "qemu-options.h"
4599 #undef DEF
4600 #undef DEFHEADING
4601 #undef GEN_DOCS
4602 "\n"
4603 "During emulation, the following keys are useful:\n"
4604 "ctrl-alt-f toggle full screen\n"
4605 "ctrl-alt-n switch to virtual console 'n'\n"
4606 "ctrl-alt toggle mouse and keyboard grab\n"
4607 "\n"
4608 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4610 "qemu",
4611 DEFAULT_RAM_SIZE,
4612 #ifndef _WIN32
4613 DEFAULT_NETWORK_SCRIPT,
4614 DEFAULT_NETWORK_DOWN_SCRIPT,
4615 #endif
4616 DEFAULT_GDBSTUB_PORT,
4617 "/tmp/qemu.log");
4618 exit(exitcode);
4621 #define HAS_ARG 0x0001
4623 enum {
4624 #define DEF(option, opt_arg, opt_enum, opt_help) \
4625 opt_enum,
4626 #define DEFHEADING(text)
4627 #include "qemu-options.h"
4628 #undef DEF
4629 #undef DEFHEADING
4630 #undef GEN_DOCS
4633 typedef struct QEMUOption {
4634 const char *name;
4635 int flags;
4636 int index;
4637 } QEMUOption;
4639 static const QEMUOption qemu_options[] = {
4640 { "h", 0, QEMU_OPTION_h },
4641 #define DEF(option, opt_arg, opt_enum, opt_help) \
4642 { option, opt_arg, opt_enum },
4643 #define DEFHEADING(text)
4644 #include "qemu-options.h"
4645 #undef DEF
4646 #undef DEFHEADING
4647 #undef GEN_DOCS
4648 { NULL },
4651 #ifdef HAS_AUDIO
4652 struct soundhw soundhw[] = {
4653 #ifdef HAS_AUDIO_CHOICE
4654 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4656 "pcspk",
4657 "PC speaker",
4660 { .init_isa = pcspk_audio_init }
4662 #endif
4664 #ifdef CONFIG_SB16
4666 "sb16",
4667 "Creative Sound Blaster 16",
4670 { .init_isa = SB16_init }
4672 #endif
4674 #ifdef CONFIG_CS4231A
4676 "cs4231a",
4677 "CS4231A",
4680 { .init_isa = cs4231a_init }
4682 #endif
4684 #ifdef CONFIG_ADLIB
4686 "adlib",
4687 #ifdef HAS_YMF262
4688 "Yamaha YMF262 (OPL3)",
4689 #else
4690 "Yamaha YM3812 (OPL2)",
4691 #endif
4694 { .init_isa = Adlib_init }
4696 #endif
4698 #ifdef CONFIG_GUS
4700 "gus",
4701 "Gravis Ultrasound GF1",
4704 { .init_isa = GUS_init }
4706 #endif
4708 #ifdef CONFIG_AC97
4710 "ac97",
4711 "Intel 82801AA AC97 Audio",
4714 { .init_pci = ac97_init }
4716 #endif
4718 #ifdef CONFIG_ES1370
4720 "es1370",
4721 "ENSONIQ AudioPCI ES1370",
4724 { .init_pci = es1370_init }
4726 #endif
4728 #endif /* HAS_AUDIO_CHOICE */
4730 { NULL, NULL, 0, 0, { NULL } }
4733 static void select_soundhw (const char *optarg)
4735 struct soundhw *c;
4737 if (*optarg == '?') {
4738 show_valid_cards:
4740 printf ("Valid sound card names (comma separated):\n");
4741 for (c = soundhw; c->name; ++c) {
4742 printf ("%-11s %s\n", c->name, c->descr);
4744 printf ("\n-soundhw all will enable all of the above\n");
4745 exit (*optarg != '?');
4747 else {
4748 size_t l;
4749 const char *p;
4750 char *e;
4751 int bad_card = 0;
4753 if (!strcmp (optarg, "all")) {
4754 for (c = soundhw; c->name; ++c) {
4755 c->enabled = 1;
4757 return;
4760 p = optarg;
4761 while (*p) {
4762 e = strchr (p, ',');
4763 l = !e ? strlen (p) : (size_t) (e - p);
4765 for (c = soundhw; c->name; ++c) {
4766 if (!strncmp (c->name, p, l)) {
4767 c->enabled = 1;
4768 break;
4772 if (!c->name) {
4773 if (l > 80) {
4774 fprintf (stderr,
4775 "Unknown sound card name (too big to show)\n");
4777 else {
4778 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4779 (int) l, p);
4781 bad_card = 1;
4783 p += l + (e != NULL);
4786 if (bad_card)
4787 goto show_valid_cards;
4790 #endif
4792 static void select_vgahw (const char *p)
4794 const char *opts;
4796 cirrus_vga_enabled = 0;
4797 std_vga_enabled = 0;
4798 vmsvga_enabled = 0;
4799 xenfb_enabled = 0;
4800 if (strstart(p, "std", &opts)) {
4801 std_vga_enabled = 1;
4802 } else if (strstart(p, "cirrus", &opts)) {
4803 cirrus_vga_enabled = 1;
4804 } else if (strstart(p, "vmware", &opts)) {
4805 vmsvga_enabled = 1;
4806 } else if (strstart(p, "xenfb", &opts)) {
4807 xenfb_enabled = 1;
4808 } else if (!strstart(p, "none", &opts)) {
4809 invalid_vga:
4810 fprintf(stderr, "Unknown vga type: %s\n", p);
4811 exit(1);
4813 while (*opts) {
4814 const char *nextopt;
4816 if (strstart(opts, ",retrace=", &nextopt)) {
4817 opts = nextopt;
4818 if (strstart(opts, "dumb", &nextopt))
4819 vga_retrace_method = VGA_RETRACE_DUMB;
4820 else if (strstart(opts, "precise", &nextopt))
4821 vga_retrace_method = VGA_RETRACE_PRECISE;
4822 else goto invalid_vga;
4823 } else goto invalid_vga;
4824 opts = nextopt;
4828 #ifdef _WIN32
4829 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4831 exit(STATUS_CONTROL_C_EXIT);
4832 return TRUE;
4834 #endif
4836 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4838 int ret;
4840 if(strlen(str) != 36)
4841 return -1;
4843 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4844 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4845 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4847 if(ret != 16)
4848 return -1;
4850 #ifdef TARGET_I386
4851 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4852 #endif
4854 return 0;
4857 #define MAX_NET_CLIENTS 32
4859 #ifdef USE_KVM
4861 #define HUGETLBFS_MAGIC 0x958458f6
4863 static long gethugepagesize(const char *path)
4865 struct statfs fs;
4866 int ret;
4868 do {
4869 ret = statfs(path, &fs);
4870 } while (ret != 0 && errno == EINTR);
4872 if (ret != 0) {
4873 perror("statfs");
4874 return 0;
4877 if (fs.f_type != HUGETLBFS_MAGIC)
4878 fprintf(stderr, "Warning: path not on HugeTLBFS: %s\n", path);
4880 return fs.f_bsize;
4883 static void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4885 char *filename;
4886 void *area;
4887 int fd;
4888 #ifdef MAP_POPULATE
4889 int flags;
4890 #endif
4892 if (!kvm_has_sync_mmu()) {
4893 fprintf(stderr, "host lacks mmu notifiers, disabling --mem-path\n");
4894 return NULL;
4897 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4898 return NULL;
4900 hpagesize = gethugepagesize(path);
4901 if (!hpagesize)
4902 return NULL;
4904 fd = mkstemp(filename);
4905 if (fd < 0) {
4906 perror("mkstemp");
4907 free(filename);
4908 return NULL;
4910 unlink(filename);
4911 free(filename);
4913 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4916 * ftruncate is not supported by hugetlbfs in older
4917 * hosts, so don't bother checking for errors.
4918 * If anything goes wrong with it under other filesystems,
4919 * mmap will fail.
4921 ftruncate(fd, memory);
4923 #ifdef MAP_POPULATE
4924 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4925 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4926 * to sidestep this quirk.
4928 flags = mem_prealloc ? MAP_POPULATE|MAP_SHARED : MAP_PRIVATE;
4929 area = mmap(0, memory, PROT_READ|PROT_WRITE, flags, fd, 0);
4930 #else
4931 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4932 #endif
4933 if (area == MAP_FAILED) {
4934 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4935 close(fd);
4936 return (NULL);
4938 *len = memory;
4939 return area;
4941 #endif
4943 #ifndef _WIN32
4945 static void termsig_handler(int signal)
4947 qemu_system_shutdown_request();
4950 static void termsig_setup(void)
4952 struct sigaction act;
4954 memset(&act, 0, sizeof(act));
4955 act.sa_handler = termsig_handler;
4956 sigaction(SIGINT, &act, NULL);
4957 sigaction(SIGHUP, &act, NULL);
4958 sigaction(SIGTERM, &act, NULL);
4961 #endif
4963 int main(int argc, char **argv, char **envp)
4965 const char *gdbstub_dev = NULL;
4966 uint32_t boot_devices_bitmap = 0;
4967 int i;
4968 int snapshot, linux_boot, net_boot;
4969 const char *initrd_filename;
4970 const char *kernel_filename, *kernel_cmdline;
4971 const char *boot_devices = "";
4972 DisplayState *ds;
4973 DisplayChangeListener *dcl;
4974 int cyls, heads, secs, translation;
4975 const char *net_clients[MAX_NET_CLIENTS];
4976 int nb_net_clients;
4977 const char *bt_opts[MAX_BT_CMDLINE];
4978 int nb_bt_opts;
4979 int hda_index;
4980 int optind;
4981 const char *r, *optarg;
4982 CharDriverState *monitor_hd = NULL;
4983 const char *monitor_device;
4984 const char *serial_devices[MAX_SERIAL_PORTS];
4985 int serial_device_index;
4986 const char *parallel_devices[MAX_PARALLEL_PORTS];
4987 int parallel_device_index;
4988 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4989 int virtio_console_index;
4990 const char *loadvm = NULL;
4991 QEMUMachine *machine;
4992 const char *cpu_model;
4993 const char *usb_devices[MAX_USB_CMDLINE];
4994 int usb_devices_index;
4995 #ifndef _WIN32
4996 int fds[2];
4997 #endif
4998 int tb_size;
4999 const char *pid_file = NULL;
5000 const char *incoming = NULL;
5001 #ifndef _WIN32
5002 int fd = 0;
5003 struct passwd *pwd = NULL;
5004 const char *chroot_dir = NULL;
5005 const char *run_as = NULL;
5006 #endif
5007 CPUState *env;
5008 int show_vnc_port = 0;
5010 qemu_cache_utils_init(envp);
5012 LIST_INIT (&vm_change_state_head);
5013 #ifndef _WIN32
5015 struct sigaction act;
5016 sigfillset(&act.sa_mask);
5017 act.sa_flags = 0;
5018 act.sa_handler = SIG_IGN;
5019 sigaction(SIGPIPE, &act, NULL);
5021 #else
5022 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5023 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5024 QEMU to run on a single CPU */
5026 HANDLE h;
5027 DWORD mask, smask;
5028 int i;
5029 h = GetCurrentProcess();
5030 if (GetProcessAffinityMask(h, &mask, &smask)) {
5031 for(i = 0; i < 32; i++) {
5032 if (mask & (1 << i))
5033 break;
5035 if (i != 32) {
5036 mask = 1 << i;
5037 SetProcessAffinityMask(h, mask);
5041 #endif
5043 module_call_init(MODULE_INIT_MACHINE);
5044 machine = find_default_machine();
5045 cpu_model = NULL;
5046 initrd_filename = NULL;
5047 ram_size = 0;
5048 snapshot = 0;
5049 kernel_filename = NULL;
5050 kernel_cmdline = "";
5051 cyls = heads = secs = 0;
5052 translation = BIOS_ATA_TRANSLATION_AUTO;
5053 monitor_device = "vc:80Cx24C";
5055 serial_devices[0] = "vc:80Cx24C";
5056 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5057 serial_devices[i] = NULL;
5058 serial_device_index = 0;
5060 parallel_devices[0] = "vc:80Cx24C";
5061 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5062 parallel_devices[i] = NULL;
5063 parallel_device_index = 0;
5065 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
5066 virtio_consoles[i] = NULL;
5067 virtio_console_index = 0;
5069 for (i = 0; i < MAX_NODES; i++) {
5070 node_mem[i] = 0;
5071 node_cpumask[i] = 0;
5074 usb_devices_index = 0;
5075 assigned_devices_index = 0;
5077 nb_net_clients = 0;
5078 nb_bt_opts = 0;
5079 nb_drives = 0;
5080 nb_drives_opt = 0;
5081 nb_numa_nodes = 0;
5082 hda_index = -1;
5084 nb_nics = 0;
5086 tb_size = 0;
5087 autostart= 1;
5089 register_watchdogs();
5091 optind = 1;
5092 for(;;) {
5093 if (optind >= argc)
5094 break;
5095 r = argv[optind];
5096 if (r[0] != '-') {
5097 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5098 } else {
5099 const QEMUOption *popt;
5101 optind++;
5102 /* Treat --foo the same as -foo. */
5103 if (r[1] == '-')
5104 r++;
5105 popt = qemu_options;
5106 for(;;) {
5107 if (!popt->name) {
5108 fprintf(stderr, "%s: invalid option -- '%s'\n",
5109 argv[0], r);
5110 exit(1);
5112 if (!strcmp(popt->name, r + 1))
5113 break;
5114 popt++;
5116 if (popt->flags & HAS_ARG) {
5117 if (optind >= argc) {
5118 fprintf(stderr, "%s: option '%s' requires an argument\n",
5119 argv[0], r);
5120 exit(1);
5122 optarg = argv[optind++];
5123 } else {
5124 optarg = NULL;
5127 switch(popt->index) {
5128 case QEMU_OPTION_M:
5129 machine = find_machine(optarg);
5130 if (!machine) {
5131 QEMUMachine *m;
5132 printf("Supported machines are:\n");
5133 for(m = first_machine; m != NULL; m = m->next) {
5134 printf("%-10s %s%s\n",
5135 m->name, m->desc,
5136 m->is_default ? " (default)" : "");
5138 exit(*optarg != '?');
5140 break;
5141 case QEMU_OPTION_cpu:
5142 /* hw initialization will check this */
5143 if (*optarg == '?') {
5144 /* XXX: implement xxx_cpu_list for targets that still miss it */
5145 #if defined(cpu_list)
5146 cpu_list(stdout, &fprintf);
5147 #endif
5148 exit(0);
5149 } else {
5150 cpu_model = optarg;
5152 break;
5153 case QEMU_OPTION_initrd:
5154 initrd_filename = optarg;
5155 break;
5156 case QEMU_OPTION_hda:
5157 if (cyls == 0)
5158 hda_index = drive_add(optarg, HD_ALIAS, 0);
5159 else
5160 hda_index = drive_add(optarg, HD_ALIAS
5161 ",cyls=%d,heads=%d,secs=%d%s",
5162 0, cyls, heads, secs,
5163 translation == BIOS_ATA_TRANSLATION_LBA ?
5164 ",trans=lba" :
5165 translation == BIOS_ATA_TRANSLATION_NONE ?
5166 ",trans=none" : "");
5167 break;
5168 case QEMU_OPTION_hdb:
5169 case QEMU_OPTION_hdc:
5170 case QEMU_OPTION_hdd:
5171 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5172 break;
5173 case QEMU_OPTION_drive:
5174 drive_add(NULL, "%s", optarg);
5175 break;
5176 case QEMU_OPTION_mtdblock:
5177 drive_add(optarg, MTD_ALIAS);
5178 break;
5179 case QEMU_OPTION_sd:
5180 drive_add(optarg, SD_ALIAS);
5181 break;
5182 case QEMU_OPTION_pflash:
5183 drive_add(optarg, PFLASH_ALIAS);
5184 break;
5185 case QEMU_OPTION_snapshot:
5186 snapshot = 1;
5187 break;
5188 case QEMU_OPTION_hdachs:
5190 const char *p;
5191 p = optarg;
5192 cyls = strtol(p, (char **)&p, 0);
5193 if (cyls < 1 || cyls > 16383)
5194 goto chs_fail;
5195 if (*p != ',')
5196 goto chs_fail;
5197 p++;
5198 heads = strtol(p, (char **)&p, 0);
5199 if (heads < 1 || heads > 16)
5200 goto chs_fail;
5201 if (*p != ',')
5202 goto chs_fail;
5203 p++;
5204 secs = strtol(p, (char **)&p, 0);
5205 if (secs < 1 || secs > 63)
5206 goto chs_fail;
5207 if (*p == ',') {
5208 p++;
5209 if (!strcmp(p, "none"))
5210 translation = BIOS_ATA_TRANSLATION_NONE;
5211 else if (!strcmp(p, "lba"))
5212 translation = BIOS_ATA_TRANSLATION_LBA;
5213 else if (!strcmp(p, "auto"))
5214 translation = BIOS_ATA_TRANSLATION_AUTO;
5215 else
5216 goto chs_fail;
5217 } else if (*p != '\0') {
5218 chs_fail:
5219 fprintf(stderr, "qemu: invalid physical CHS format\n");
5220 exit(1);
5222 if (hda_index != -1)
5223 snprintf(drives_opt[hda_index].opt,
5224 sizeof(drives_opt[hda_index].opt),
5225 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5226 0, cyls, heads, secs,
5227 translation == BIOS_ATA_TRANSLATION_LBA ?
5228 ",trans=lba" :
5229 translation == BIOS_ATA_TRANSLATION_NONE ?
5230 ",trans=none" : "");
5232 break;
5233 case QEMU_OPTION_numa:
5234 if (nb_numa_nodes >= MAX_NODES) {
5235 fprintf(stderr, "qemu: too many NUMA nodes\n");
5236 exit(1);
5238 numa_add(optarg);
5239 break;
5240 case QEMU_OPTION_nographic:
5241 display_type = DT_NOGRAPHIC;
5242 break;
5243 #ifdef CONFIG_CURSES
5244 case QEMU_OPTION_curses:
5245 display_type = DT_CURSES;
5246 break;
5247 #endif
5248 case QEMU_OPTION_portrait:
5249 graphic_rotate = 1;
5250 break;
5251 case QEMU_OPTION_kernel:
5252 kernel_filename = optarg;
5253 break;
5254 case QEMU_OPTION_append:
5255 kernel_cmdline = optarg;
5256 break;
5257 case QEMU_OPTION_cdrom:
5258 drive_add(optarg, CDROM_ALIAS);
5259 break;
5260 case QEMU_OPTION_boot:
5261 boot_devices = optarg;
5262 /* We just do some generic consistency checks */
5264 /* Could easily be extended to 64 devices if needed */
5265 const char *p;
5267 boot_devices_bitmap = 0;
5268 for (p = boot_devices; *p != '\0'; p++) {
5269 /* Allowed boot devices are:
5270 * a b : floppy disk drives
5271 * c ... f : IDE disk drives
5272 * g ... m : machine implementation dependant drives
5273 * n ... p : network devices
5274 * It's up to each machine implementation to check
5275 * if the given boot devices match the actual hardware
5276 * implementation and firmware features.
5278 if (*p < 'a' || *p > 'q') {
5279 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5280 exit(1);
5282 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5283 fprintf(stderr,
5284 "Boot device '%c' was given twice\n",*p);
5285 exit(1);
5287 boot_devices_bitmap |= 1 << (*p - 'a');
5290 break;
5291 case QEMU_OPTION_fda:
5292 case QEMU_OPTION_fdb:
5293 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5294 break;
5295 #ifdef TARGET_I386
5296 case QEMU_OPTION_no_fd_bootchk:
5297 fd_bootchk = 0;
5298 break;
5299 #endif
5300 case QEMU_OPTION_net:
5301 if (nb_net_clients >= MAX_NET_CLIENTS) {
5302 fprintf(stderr, "qemu: too many network clients\n");
5303 exit(1);
5305 net_clients[nb_net_clients] = optarg;
5306 nb_net_clients++;
5307 break;
5308 #ifdef CONFIG_SLIRP
5309 case QEMU_OPTION_tftp:
5310 tftp_prefix = optarg;
5311 break;
5312 case QEMU_OPTION_bootp:
5313 bootp_filename = optarg;
5314 break;
5315 #ifndef _WIN32
5316 case QEMU_OPTION_smb:
5317 net_slirp_smb(optarg);
5318 break;
5319 #endif
5320 case QEMU_OPTION_redir:
5321 net_slirp_redir(NULL, optarg);
5322 break;
5323 #endif
5324 case QEMU_OPTION_bt:
5325 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5326 fprintf(stderr, "qemu: too many bluetooth options\n");
5327 exit(1);
5329 bt_opts[nb_bt_opts++] = optarg;
5330 break;
5331 #ifdef HAS_AUDIO
5332 case QEMU_OPTION_audio_help:
5333 AUD_help ();
5334 exit (0);
5335 break;
5336 case QEMU_OPTION_soundhw:
5337 select_soundhw (optarg);
5338 break;
5339 #endif
5340 case QEMU_OPTION_h:
5341 help(0);
5342 break;
5343 case QEMU_OPTION_version:
5344 version();
5345 exit(0);
5346 break;
5347 case QEMU_OPTION_m: {
5348 uint64_t value;
5349 char *ptr;
5351 value = strtoul(optarg, &ptr, 10);
5352 switch (*ptr) {
5353 case 0: case 'M': case 'm':
5354 value <<= 20;
5355 break;
5356 case 'G': case 'g':
5357 value <<= 30;
5358 break;
5359 default:
5360 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5361 exit(1);
5364 /* On 32-bit hosts, QEMU is limited by virtual address space */
5365 if (value > (2047 << 20)
5366 #ifndef CONFIG_KQEMU
5367 && HOST_LONG_BITS == 32
5368 #endif
5370 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5371 exit(1);
5373 if (value != (uint64_t)(ram_addr_t)value) {
5374 fprintf(stderr, "qemu: ram size too large\n");
5375 exit(1);
5377 ram_size = value;
5378 break;
5380 case QEMU_OPTION_d:
5382 int mask;
5383 const CPULogItem *item;
5385 mask = cpu_str_to_log_mask(optarg);
5386 if (!mask) {
5387 printf("Log items (comma separated):\n");
5388 for(item = cpu_log_items; item->mask != 0; item++) {
5389 printf("%-10s %s\n", item->name, item->help);
5391 exit(1);
5393 cpu_set_log(mask);
5395 break;
5396 case QEMU_OPTION_s:
5397 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5398 break;
5399 case QEMU_OPTION_gdb:
5400 gdbstub_dev = optarg;
5401 break;
5402 case QEMU_OPTION_L:
5403 bios_dir = optarg;
5404 break;
5405 case QEMU_OPTION_bios:
5406 bios_name = optarg;
5407 break;
5408 case QEMU_OPTION_singlestep:
5409 singlestep = 1;
5410 break;
5411 case QEMU_OPTION_S:
5412 autostart = 0;
5413 break;
5414 #ifndef _WIN32
5415 case QEMU_OPTION_k:
5416 keyboard_layout = optarg;
5417 break;
5418 #endif
5419 case QEMU_OPTION_localtime:
5420 rtc_utc = 0;
5421 break;
5422 case QEMU_OPTION_vga:
5423 select_vgahw (optarg);
5424 break;
5425 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5426 case QEMU_OPTION_g:
5428 const char *p;
5429 int w, h, depth;
5430 p = optarg;
5431 w = strtol(p, (char **)&p, 10);
5432 if (w <= 0) {
5433 graphic_error:
5434 fprintf(stderr, "qemu: invalid resolution or depth\n");
5435 exit(1);
5437 if (*p != 'x')
5438 goto graphic_error;
5439 p++;
5440 h = strtol(p, (char **)&p, 10);
5441 if (h <= 0)
5442 goto graphic_error;
5443 if (*p == 'x') {
5444 p++;
5445 depth = strtol(p, (char **)&p, 10);
5446 if (depth != 8 && depth != 15 && depth != 16 &&
5447 depth != 24 && depth != 32)
5448 goto graphic_error;
5449 } else if (*p == '\0') {
5450 depth = graphic_depth;
5451 } else {
5452 goto graphic_error;
5455 graphic_width = w;
5456 graphic_height = h;
5457 graphic_depth = depth;
5459 break;
5460 #endif
5461 case QEMU_OPTION_echr:
5463 char *r;
5464 term_escape_char = strtol(optarg, &r, 0);
5465 if (r == optarg)
5466 printf("Bad argument to echr\n");
5467 break;
5469 case QEMU_OPTION_monitor:
5470 monitor_device = optarg;
5471 break;
5472 case QEMU_OPTION_serial:
5473 if (serial_device_index >= MAX_SERIAL_PORTS) {
5474 fprintf(stderr, "qemu: too many serial ports\n");
5475 exit(1);
5477 serial_devices[serial_device_index] = optarg;
5478 serial_device_index++;
5479 break;
5480 case QEMU_OPTION_watchdog:
5481 i = select_watchdog(optarg);
5482 if (i > 0)
5483 exit (i == 1 ? 1 : 0);
5484 break;
5485 case QEMU_OPTION_watchdog_action:
5486 if (select_watchdog_action(optarg) == -1) {
5487 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5488 exit(1);
5490 break;
5491 case QEMU_OPTION_virtiocon:
5492 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5493 fprintf(stderr, "qemu: too many virtio consoles\n");
5494 exit(1);
5496 virtio_consoles[virtio_console_index] = optarg;
5497 virtio_console_index++;
5498 break;
5499 case QEMU_OPTION_parallel:
5500 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5501 fprintf(stderr, "qemu: too many parallel ports\n");
5502 exit(1);
5504 parallel_devices[parallel_device_index] = optarg;
5505 parallel_device_index++;
5506 break;
5507 case QEMU_OPTION_loadvm:
5508 loadvm = optarg;
5509 break;
5510 case QEMU_OPTION_full_screen:
5511 full_screen = 1;
5512 break;
5513 #ifdef CONFIG_SDL
5514 case QEMU_OPTION_no_frame:
5515 no_frame = 1;
5516 break;
5517 case QEMU_OPTION_alt_grab:
5518 alt_grab = 1;
5519 break;
5520 case QEMU_OPTION_no_quit:
5521 no_quit = 1;
5522 break;
5523 case QEMU_OPTION_sdl:
5524 display_type = DT_SDL;
5525 break;
5526 #endif
5527 case QEMU_OPTION_pidfile:
5528 pid_file = optarg;
5529 break;
5530 #ifdef TARGET_I386
5531 case QEMU_OPTION_win2k_hack:
5532 win2k_install_hack = 1;
5533 break;
5534 case QEMU_OPTION_rtc_td_hack:
5535 rtc_td_hack = 1;
5536 break;
5537 case QEMU_OPTION_acpitable:
5538 if(acpi_table_add(optarg) < 0) {
5539 fprintf(stderr, "Wrong acpi table provided\n");
5540 exit(1);
5542 break;
5543 case QEMU_OPTION_smbios:
5544 if(smbios_entry_add(optarg) < 0) {
5545 fprintf(stderr, "Wrong smbios provided\n");
5546 exit(1);
5548 break;
5549 #endif
5550 #ifdef CONFIG_KQEMU
5551 case QEMU_OPTION_no_kqemu:
5552 kqemu_allowed = 0;
5553 break;
5554 case QEMU_OPTION_kernel_kqemu:
5555 kqemu_allowed = 2;
5556 break;
5557 #endif
5558 #ifdef CONFIG_KVM
5559 case QEMU_OPTION_enable_kvm:
5560 kvm_allowed = 1;
5561 #ifdef CONFIG_KQEMU
5562 kqemu_allowed = 0;
5563 #endif
5564 break;
5565 #endif
5566 #ifdef USE_KVM
5567 case QEMU_OPTION_no_kvm:
5568 kvm_allowed = 0;
5569 break;
5570 case QEMU_OPTION_no_kvm_irqchip: {
5571 kvm_irqchip = 0;
5572 kvm_pit = 0;
5573 break;
5575 case QEMU_OPTION_no_kvm_pit: {
5576 kvm_pit = 0;
5577 break;
5579 case QEMU_OPTION_no_kvm_pit_reinjection: {
5580 kvm_pit_reinject = 0;
5581 break;
5583 case QEMU_OPTION_enable_nesting: {
5584 kvm_nested = 1;
5585 break;
5587 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5588 case QEMU_OPTION_pcidevice:
5589 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5590 fprintf(stderr, "Too many assigned devices\n");
5591 exit(1);
5593 assigned_devices[assigned_devices_index] = optarg;
5594 assigned_devices_index++;
5595 break;
5596 #endif
5597 #endif
5598 case QEMU_OPTION_usb:
5599 usb_enabled = 1;
5600 break;
5601 case QEMU_OPTION_usbdevice:
5602 usb_enabled = 1;
5603 if (usb_devices_index >= MAX_USB_CMDLINE) {
5604 fprintf(stderr, "Too many USB devices\n");
5605 exit(1);
5607 usb_devices[usb_devices_index] = optarg;
5608 usb_devices_index++;
5609 break;
5610 case QEMU_OPTION_smp:
5611 smp_cpus = atoi(optarg);
5612 if (smp_cpus < 1) {
5613 fprintf(stderr, "Invalid number of CPUs\n");
5614 exit(1);
5616 break;
5617 case QEMU_OPTION_vnc:
5618 display_type = DT_VNC;
5619 vnc_display = optarg;
5620 break;
5621 #ifdef TARGET_I386
5622 case QEMU_OPTION_no_acpi:
5623 acpi_enabled = 0;
5624 break;
5625 case QEMU_OPTION_no_hpet:
5626 no_hpet = 1;
5627 break;
5628 #endif
5629 case QEMU_OPTION_no_reboot:
5630 no_reboot = 1;
5631 break;
5632 case QEMU_OPTION_no_shutdown:
5633 no_shutdown = 1;
5634 break;
5635 case QEMU_OPTION_show_cursor:
5636 cursor_hide = 0;
5637 break;
5638 case QEMU_OPTION_uuid:
5639 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5640 fprintf(stderr, "Fail to parse UUID string."
5641 " Wrong format.\n");
5642 exit(1);
5644 break;
5645 #ifndef _WIN32
5646 case QEMU_OPTION_daemonize:
5647 daemonize = 1;
5648 break;
5649 #endif
5650 case QEMU_OPTION_option_rom:
5651 if (nb_option_roms >= MAX_OPTION_ROMS) {
5652 fprintf(stderr, "Too many option ROMs\n");
5653 exit(1);
5655 option_rom[nb_option_roms] = optarg;
5656 nb_option_roms++;
5657 break;
5658 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5659 case QEMU_OPTION_semihosting:
5660 semihosting_enabled = 1;
5661 break;
5662 #endif
5663 case QEMU_OPTION_tdf:
5664 time_drift_fix = 1;
5665 break;
5666 case QEMU_OPTION_kvm_shadow_memory:
5667 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5668 break;
5669 case QEMU_OPTION_mempath:
5670 mem_path = optarg;
5671 break;
5672 #ifdef MAP_POPULATE
5673 case QEMU_OPTION_mem_prealloc:
5674 mem_prealloc = !mem_prealloc;
5675 break;
5676 #endif
5677 case QEMU_OPTION_name:
5678 qemu_name = optarg;
5679 break;
5680 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5681 case QEMU_OPTION_prom_env:
5682 if (nb_prom_envs >= MAX_PROM_ENVS) {
5683 fprintf(stderr, "Too many prom variables\n");
5684 exit(1);
5686 prom_envs[nb_prom_envs] = optarg;
5687 nb_prom_envs++;
5688 break;
5689 #endif
5690 #ifdef TARGET_ARM
5691 case QEMU_OPTION_old_param:
5692 old_param = 1;
5693 break;
5694 #endif
5695 case QEMU_OPTION_clock:
5696 configure_alarms(optarg);
5697 break;
5698 case QEMU_OPTION_startdate:
5700 struct tm tm;
5701 time_t rtc_start_date;
5702 if (!strcmp(optarg, "now")) {
5703 rtc_date_offset = -1;
5704 } else {
5705 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5706 &tm.tm_year,
5707 &tm.tm_mon,
5708 &tm.tm_mday,
5709 &tm.tm_hour,
5710 &tm.tm_min,
5711 &tm.tm_sec) == 6) {
5712 /* OK */
5713 } else if (sscanf(optarg, "%d-%d-%d",
5714 &tm.tm_year,
5715 &tm.tm_mon,
5716 &tm.tm_mday) == 3) {
5717 tm.tm_hour = 0;
5718 tm.tm_min = 0;
5719 tm.tm_sec = 0;
5720 } else {
5721 goto date_fail;
5723 tm.tm_year -= 1900;
5724 tm.tm_mon--;
5725 rtc_start_date = mktimegm(&tm);
5726 if (rtc_start_date == -1) {
5727 date_fail:
5728 fprintf(stderr, "Invalid date format. Valid format are:\n"
5729 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5730 exit(1);
5732 rtc_date_offset = time(NULL) - rtc_start_date;
5735 break;
5736 case QEMU_OPTION_tb_size:
5737 tb_size = strtol(optarg, NULL, 0);
5738 if (tb_size < 0)
5739 tb_size = 0;
5740 break;
5741 case QEMU_OPTION_icount:
5742 use_icount = 1;
5743 if (strcmp(optarg, "auto") == 0) {
5744 icount_time_shift = -1;
5745 } else {
5746 icount_time_shift = strtol(optarg, NULL, 0);
5748 break;
5749 case QEMU_OPTION_incoming:
5750 incoming = optarg;
5751 break;
5752 #ifndef _WIN32
5753 case QEMU_OPTION_chroot:
5754 chroot_dir = optarg;
5755 break;
5756 case QEMU_OPTION_runas:
5757 run_as = optarg;
5758 break;
5759 case QEMU_OPTION_nvram:
5760 nvram = optarg;
5761 break;
5762 #endif
5763 #ifdef CONFIG_XEN
5764 case QEMU_OPTION_xen_domid:
5765 xen_domid = atoi(optarg);
5766 break;
5767 case QEMU_OPTION_xen_create:
5768 xen_mode = XEN_CREATE;
5769 break;
5770 case QEMU_OPTION_xen_attach:
5771 xen_mode = XEN_ATTACH;
5772 break;
5773 #endif
5778 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5779 if (kvm_allowed && kqemu_allowed) {
5780 fprintf(stderr,
5781 "You can not enable both KVM and kqemu at the same time\n");
5782 exit(1);
5784 #endif
5786 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5787 if (smp_cpus > machine->max_cpus) {
5788 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5789 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5790 machine->max_cpus);
5791 exit(1);
5794 if (display_type == DT_NOGRAPHIC) {
5795 if (serial_device_index == 0)
5796 serial_devices[0] = "stdio";
5797 if (parallel_device_index == 0)
5798 parallel_devices[0] = "null";
5799 if (strncmp(monitor_device, "vc", 2) == 0)
5800 monitor_device = "stdio";
5803 #ifndef _WIN32
5804 if (daemonize) {
5805 pid_t pid;
5807 if (pipe(fds) == -1)
5808 exit(1);
5810 pid = fork();
5811 if (pid > 0) {
5812 uint8_t status;
5813 ssize_t len;
5815 close(fds[1]);
5817 again:
5818 len = read(fds[0], &status, 1);
5819 if (len == -1 && (errno == EINTR))
5820 goto again;
5822 if (len != 1)
5823 exit(1);
5824 else if (status == 1) {
5825 fprintf(stderr, "Could not acquire pidfile\n");
5826 exit(1);
5827 } else
5828 exit(0);
5829 } else if (pid < 0)
5830 exit(1);
5832 setsid();
5834 pid = fork();
5835 if (pid > 0)
5836 exit(0);
5837 else if (pid < 0)
5838 exit(1);
5840 umask(027);
5842 signal(SIGTSTP, SIG_IGN);
5843 signal(SIGTTOU, SIG_IGN);
5844 signal(SIGTTIN, SIG_IGN);
5847 #ifdef USE_KVM
5848 if (kvm_enabled()) {
5849 if (kvm_qemu_init() < 0) {
5850 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5851 #ifdef NO_CPU_EMULATION
5852 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5853 exit(1);
5854 #endif
5855 kvm_allowed = 0;
5858 #endif
5860 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5861 if (daemonize) {
5862 uint8_t status = 1;
5863 write(fds[1], &status, 1);
5864 } else
5865 fprintf(stderr, "Could not acquire pid file\n");
5866 exit(1);
5868 #endif
5870 #ifdef CONFIG_KQEMU
5871 if (smp_cpus > 1)
5872 kqemu_allowed = 0;
5873 #endif
5874 if (qemu_init_main_loop()) {
5875 fprintf(stderr, "qemu_init_main_loop failed\n");
5876 exit(1);
5878 linux_boot = (kernel_filename != NULL);
5879 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5881 if (!linux_boot && *kernel_cmdline != '\0') {
5882 fprintf(stderr, "-append only allowed with -kernel option\n");
5883 exit(1);
5886 if (!linux_boot && initrd_filename != NULL) {
5887 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5888 exit(1);
5891 /* boot to floppy or the default cd if no hard disk defined yet */
5892 if (!boot_devices[0]) {
5893 boot_devices = "cad";
5895 setvbuf(stdout, NULL, _IOLBF, 0);
5897 init_timers();
5898 if (init_timer_alarm() < 0) {
5899 fprintf(stderr, "could not initialize alarm timer\n");
5900 exit(1);
5902 if (use_icount && icount_time_shift < 0) {
5903 use_icount = 2;
5904 /* 125MIPS seems a reasonable initial guess at the guest speed.
5905 It will be corrected fairly quickly anyway. */
5906 icount_time_shift = 3;
5907 init_icount_adjust();
5910 #ifdef _WIN32
5911 socket_init();
5912 #endif
5914 /* init network clients */
5915 if (nb_net_clients == 0) {
5916 /* if no clients, we use a default config */
5917 net_clients[nb_net_clients++] = "nic";
5918 #ifdef CONFIG_SLIRP
5919 net_clients[nb_net_clients++] = "user";
5920 #endif
5923 for(i = 0;i < nb_net_clients; i++) {
5924 if (net_client_parse(net_clients[i]) < 0)
5925 exit(1);
5927 net_client_check();
5929 #ifdef TARGET_I386
5930 /* XXX: this should be moved in the PC machine instantiation code */
5931 if (net_boot != 0) {
5932 int netroms = 0;
5933 for (i = 0; i < nb_nics && i < 4; i++) {
5934 const char *model = nd_table[i].model;
5935 char buf[1024];
5936 if (net_boot & (1 << i)) {
5937 if (model == NULL)
5938 model = "rtl8139";
5939 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5940 if (get_image_size(buf) > 0) {
5941 if (nb_option_roms >= MAX_OPTION_ROMS) {
5942 fprintf(stderr, "Too many option ROMs\n");
5943 exit(1);
5945 option_rom[nb_option_roms] = strdup(buf);
5946 nb_option_roms++;
5947 netroms++;
5951 if (netroms == 0) {
5952 fprintf(stderr, "No valid PXE rom found for network device\n");
5953 exit(1);
5956 #endif
5958 /* init the bluetooth world */
5959 for (i = 0; i < nb_bt_opts; i++)
5960 if (bt_parse(bt_opts[i]))
5961 exit(1);
5963 /* init the memory */
5964 if (ram_size == 0)
5965 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5967 if (kvm_enabled()) {
5968 if (kvm_qemu_create_context() < 0) {
5969 fprintf(stderr, "Could not create KVM context\n");
5970 exit(1);
5974 #ifdef CONFIG_KQEMU
5975 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5976 guest ram allocation. It needs to go away. */
5977 if (kqemu_allowed) {
5978 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
5979 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5980 if (!kqemu_phys_ram_base) {
5981 fprintf(stderr, "Could not allocate physical memory\n");
5982 exit(1);
5985 #endif
5987 /* init the dynamic translator */
5988 cpu_exec_init_all(tb_size * 1024 * 1024);
5990 bdrv_init();
5991 dma_helper_init();
5993 /* we always create the cdrom drive, even if no disk is there */
5995 if (nb_drives_opt < MAX_DRIVES)
5996 drive_add(NULL, CDROM_ALIAS);
5998 /* we always create at least one floppy */
6000 if (nb_drives_opt < MAX_DRIVES)
6001 drive_add(NULL, FD_ALIAS, 0);
6003 /* we always create one sd slot, even if no card is in it */
6005 if (nb_drives_opt < MAX_DRIVES)
6006 drive_add(NULL, SD_ALIAS);
6008 /* open the virtual block devices
6009 * note that migration with device
6010 * hot add/remove is broken.
6012 for(i = 0; i < nb_drives_opt; i++)
6013 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
6014 exit(1);
6016 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6017 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
6019 #ifndef _WIN32
6020 /* must be after terminal init, SDL library changes signal handlers */
6021 termsig_setup();
6022 #endif
6024 /* Maintain compatibility with multiple stdio monitors */
6025 if (!strcmp(monitor_device,"stdio")) {
6026 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
6027 const char *devname = serial_devices[i];
6028 if (devname && !strcmp(devname,"mon:stdio")) {
6029 monitor_device = NULL;
6030 break;
6031 } else if (devname && !strcmp(devname,"stdio")) {
6032 monitor_device = NULL;
6033 serial_devices[i] = "mon:stdio";
6034 break;
6039 if (nb_numa_nodes > 0) {
6040 int i;
6042 if (nb_numa_nodes > smp_cpus) {
6043 nb_numa_nodes = smp_cpus;
6046 /* If no memory size if given for any node, assume the default case
6047 * and distribute the available memory equally across all nodes
6049 for (i = 0; i < nb_numa_nodes; i++) {
6050 if (node_mem[i] != 0)
6051 break;
6053 if (i == nb_numa_nodes) {
6054 uint64_t usedmem = 0;
6056 /* On Linux, the each node's border has to be 8MB aligned,
6057 * the final node gets the rest.
6059 for (i = 0; i < nb_numa_nodes - 1; i++) {
6060 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
6061 usedmem += node_mem[i];
6063 node_mem[i] = ram_size - usedmem;
6066 for (i = 0; i < nb_numa_nodes; i++) {
6067 if (node_cpumask[i] != 0)
6068 break;
6070 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6071 * must cope with this anyway, because there are BIOSes out there in
6072 * real machines which also use this scheme.
6074 if (i == nb_numa_nodes) {
6075 for (i = 0; i < smp_cpus; i++) {
6076 node_cpumask[i % nb_numa_nodes] |= 1 << i;
6081 #ifdef KVM_UPSTREAM
6082 if (kvm_enabled()) {
6083 int ret;
6085 ret = kvm_init(smp_cpus);
6086 if (ret < 0) {
6087 fprintf(stderr, "failed to initialize KVM\n");
6088 exit(1);
6091 #endif
6093 if (monitor_device) {
6094 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
6095 if (!monitor_hd) {
6096 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6097 exit(1);
6101 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6102 const char *devname = serial_devices[i];
6103 if (devname && strcmp(devname, "none")) {
6104 char label[32];
6105 snprintf(label, sizeof(label), "serial%d", i);
6106 serial_hds[i] = qemu_chr_open(label, devname, NULL);
6107 if (!serial_hds[i]) {
6108 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6109 devname);
6110 exit(1);
6115 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6116 const char *devname = parallel_devices[i];
6117 if (devname && strcmp(devname, "none")) {
6118 char label[32];
6119 snprintf(label, sizeof(label), "parallel%d", i);
6120 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
6121 if (!parallel_hds[i]) {
6122 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6123 devname);
6124 exit(1);
6129 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6130 const char *devname = virtio_consoles[i];
6131 if (devname && strcmp(devname, "none")) {
6132 char label[32];
6133 snprintf(label, sizeof(label), "virtcon%d", i);
6134 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
6135 if (!virtcon_hds[i]) {
6136 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
6137 devname);
6138 exit(1);
6143 module_call_init(MODULE_INIT_DEVICE);
6145 if (kvm_enabled())
6146 kvm_init_ap();
6148 machine->init(ram_size, boot_devices,
6149 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6152 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6153 for (i = 0; i < nb_numa_nodes; i++) {
6154 if (node_cpumask[i] & (1 << env->cpu_index)) {
6155 env->numa_node = i;
6160 current_machine = machine;
6162 /* Set KVM's vcpu state to qemu's initial CPUState. */
6163 if (kvm_enabled()) {
6164 int ret;
6166 ret = kvm_sync_vcpus();
6167 if (ret < 0) {
6168 fprintf(stderr, "failed to initialize vcpus\n");
6169 exit(1);
6173 /* init USB devices */
6174 if (usb_enabled) {
6175 for(i = 0; i < usb_devices_index; i++) {
6176 if (usb_device_add(usb_devices[i], 0) < 0) {
6177 fprintf(stderr, "Warning: could not add USB device %s\n",
6178 usb_devices[i]);
6183 if (!display_state)
6184 dumb_display_init();
6185 /* just use the first displaystate for the moment */
6186 ds = display_state;
6188 if (display_type == DT_DEFAULT) {
6189 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6190 display_type = DT_SDL;
6191 #else
6192 display_type = DT_VNC;
6193 vnc_display = "localhost:0,to=99";
6194 show_vnc_port = 1;
6195 #endif
6199 switch (display_type) {
6200 case DT_NOGRAPHIC:
6201 break;
6202 #if defined(CONFIG_CURSES)
6203 case DT_CURSES:
6204 curses_display_init(ds, full_screen);
6205 break;
6206 #endif
6207 #if defined(CONFIG_SDL)
6208 case DT_SDL:
6209 sdl_display_init(ds, full_screen, no_frame);
6210 break;
6211 #elif defined(CONFIG_COCOA)
6212 case DT_SDL:
6213 cocoa_display_init(ds, full_screen);
6214 break;
6215 #endif
6216 case DT_VNC:
6217 vnc_display_init(ds);
6218 if (vnc_display_open(ds, vnc_display) < 0)
6219 exit(1);
6221 if (show_vnc_port) {
6222 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6224 break;
6225 default:
6226 break;
6228 dpy_resize(ds);
6230 dcl = ds->listeners;
6231 while (dcl != NULL) {
6232 if (dcl->dpy_refresh != NULL) {
6233 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6234 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6236 dcl = dcl->next;
6239 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6240 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6241 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6244 text_consoles_set_display(display_state);
6245 qemu_chr_initial_reset();
6247 if (monitor_device && monitor_hd)
6248 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6250 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6251 const char *devname = serial_devices[i];
6252 if (devname && strcmp(devname, "none")) {
6253 char label[32];
6254 snprintf(label, sizeof(label), "serial%d", i);
6255 if (strstart(devname, "vc", 0))
6256 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6260 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6261 const char *devname = parallel_devices[i];
6262 if (devname && strcmp(devname, "none")) {
6263 char label[32];
6264 snprintf(label, sizeof(label), "parallel%d", i);
6265 if (strstart(devname, "vc", 0))
6266 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6270 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6271 const char *devname = virtio_consoles[i];
6272 if (virtcon_hds[i] && devname) {
6273 char label[32];
6274 snprintf(label, sizeof(label), "virtcon%d", i);
6275 if (strstart(devname, "vc", 0))
6276 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6280 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6281 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6282 gdbstub_dev);
6283 exit(1);
6286 if (loadvm)
6287 do_loadvm(cur_mon, loadvm);
6289 if (incoming) {
6290 autostart = 0; /* fixme how to deal with -daemonize */
6291 qemu_start_incoming_migration(incoming);
6294 if (autostart)
6295 vm_start();
6297 #ifndef _WIN32
6298 if (daemonize) {
6299 uint8_t status = 0;
6300 ssize_t len;
6302 again1:
6303 len = write(fds[1], &status, 1);
6304 if (len == -1 && (errno == EINTR))
6305 goto again1;
6307 if (len != 1)
6308 exit(1);
6310 chdir("/");
6311 TFR(fd = open("/dev/null", O_RDWR));
6312 if (fd == -1)
6313 exit(1);
6316 if (run_as) {
6317 pwd = getpwnam(run_as);
6318 if (!pwd) {
6319 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6320 exit(1);
6324 if (chroot_dir) {
6325 if (chroot(chroot_dir) < 0) {
6326 fprintf(stderr, "chroot failed\n");
6327 exit(1);
6329 chdir("/");
6332 if (run_as) {
6333 if (setgid(pwd->pw_gid) < 0) {
6334 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6335 exit(1);
6337 if (setuid(pwd->pw_uid) < 0) {
6338 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6339 exit(1);
6341 if (setuid(0) != -1) {
6342 fprintf(stderr, "Dropping privileges failed\n");
6343 exit(1);
6347 if (daemonize) {
6348 dup2(fd, 0);
6349 dup2(fd, 1);
6350 dup2(fd, 2);
6352 close(fd);
6354 #endif
6356 main_loop();
6357 quit_timers();
6358 net_cleanup();
6360 return 0;