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