Fix ppc-softmmu kvm-disabled build
[qemu-kvm/fedora.git] / vl.c
blobdf583b7311a4fc3da75dc2beb62dfb52b4fc0d03
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 <libgen.h>
37 #include <pwd.h>
38 #include <sys/times.h>
39 #include <sys/wait.h>
40 #include <termios.h>
41 #include <sys/mman.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <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 #if defined(__APPLE__) || defined(main)
117 #include <SDL.h>
118 int qemu_main(int argc, char **argv, char **envp);
119 int main(int argc, char **argv)
121 return qemu_main(argc, argv, NULL);
123 #undef main
124 #define main qemu_main
125 #endif
126 #endif /* CONFIG_SDL */
128 #ifdef CONFIG_COCOA
129 #undef main
130 #define main qemu_main
131 #endif /* CONFIG_COCOA */
133 #include "hw/hw.h"
134 #include "hw/boards.h"
135 #include "hw/usb.h"
136 #include "hw/pcmcia.h"
137 #include "hw/pc.h"
138 #include "hw/audiodev.h"
139 #include "hw/isa.h"
140 #include "hw/baum.h"
141 #include "hw/bt.h"
142 #include "hw/watchdog.h"
143 #include "hw/smbios.h"
144 #include "hw/xen.h"
145 #include "bt-host.h"
146 #include "net.h"
147 #include "monitor.h"
148 #include "console.h"
149 #include "sysemu.h"
150 #include "gdbstub.h"
151 #include "qemu-timer.h"
152 #include "qemu-char.h"
153 #include "cache-utils.h"
154 #include "block.h"
155 #include "dma.h"
156 #include "audio/audio.h"
157 #include "migration.h"
158 #include "kvm.h"
159 #include "balloon.h"
160 #include "qemu-option.h"
161 #include "qemu-kvm.h"
162 #include "hw/device-assignment.h"
164 #include "disas.h"
166 #include "exec-all.h"
168 #include "qemu_socket.h"
170 #if defined(CONFIG_SLIRP)
171 #include "libslirp.h"
172 #endif
174 //#define DEBUG_UNUSED_IOPORT
175 //#define DEBUG_IOPORT
176 //#define DEBUG_NET
177 //#define DEBUG_SLIRP
180 #ifdef DEBUG_IOPORT
181 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
182 #else
183 # define LOG_IOPORT(...) do { } while (0)
184 #endif
186 #define DEFAULT_RAM_SIZE 128
188 /* Max number of USB devices that can be specified on the commandline. */
189 #define MAX_USB_CMDLINE 8
191 /* Max number of bluetooth switches on the commandline. */
192 #define MAX_BT_CMDLINE 10
194 /* XXX: use a two level table to limit memory usage */
195 #define MAX_IOPORTS 65536
197 static const char *data_dir;
198 const char *bios_name = NULL;
199 static void *ioport_opaque[MAX_IOPORTS];
200 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
201 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
202 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
203 to store the VM snapshots */
204 DriveInfo drives_table[MAX_DRIVES+1];
205 int nb_drives;
206 int extboot_drive = -1;
207 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
208 static DisplayState *display_state;
209 DisplayType display_type = DT_DEFAULT;
210 const char* keyboard_layout = NULL;
211 int64_t ticks_per_sec;
212 ram_addr_t ram_size;
213 int nb_nics;
214 NICInfo nd_table[MAX_NICS];
215 int vm_running;
216 static int autostart;
217 static int rtc_utc = 1;
218 static int rtc_date_offset = -1; /* -1 means no change */
219 int cirrus_vga_enabled = 1;
220 int std_vga_enabled = 0;
221 int vmsvga_enabled = 0;
222 int xenfb_enabled = 0;
223 #ifdef TARGET_SPARC
224 int graphic_width = 1024;
225 int graphic_height = 768;
226 int graphic_depth = 8;
227 #else
228 int graphic_width = 800;
229 int graphic_height = 600;
230 int graphic_depth = 15;
231 #endif
232 static int full_screen = 0;
233 #ifdef CONFIG_SDL
234 static int no_frame = 0;
235 #endif
236 int no_quit = 0;
237 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
238 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
239 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
240 #ifdef TARGET_I386
241 int win2k_install_hack = 0;
242 int rtc_td_hack = 0;
243 #endif
244 int usb_enabled = 0;
245 int singlestep = 0;
246 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
247 int assigned_devices_index;
248 int smp_cpus = 1;
249 const char *vnc_display;
250 int acpi_enabled = 1;
251 int no_hpet = 0;
252 int no_virtio_balloon = 0;
253 int fd_bootchk = 1;
254 int no_reboot = 0;
255 int no_shutdown = 0;
256 int cursor_hide = 1;
257 int graphic_rotate = 0;
258 #ifndef _WIN32
259 int daemonize = 0;
260 #endif
261 WatchdogTimerModel *watchdog = NULL;
262 int watchdog_action = WDT_RESET;
263 const char *option_rom[MAX_OPTION_ROMS];
264 int nb_option_roms;
265 int semihosting_enabled = 0;
266 int time_drift_fix = 0;
267 unsigned int kvm_shadow_memory = 0;
268 const char *mem_path = NULL;
269 #ifdef MAP_POPULATE
270 int mem_prealloc = 1; /* force preallocation of physical target memory */
271 #endif
272 #ifdef TARGET_ARM
273 int old_param = 0;
274 #endif
275 const char *qemu_name;
276 int alt_grab = 0;
277 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
278 unsigned int nb_prom_envs = 0;
279 const char *prom_envs[MAX_PROM_ENVS];
280 #endif
281 int nb_drives_opt;
282 const char *nvram = NULL;
283 struct drive_opt drives_opt[MAX_DRIVES];
285 int nb_numa_nodes;
286 uint64_t node_mem[MAX_NODES];
287 uint64_t node_cpumask[MAX_NODES];
289 static CPUState *cur_cpu;
290 static CPUState *next_cpu;
291 static int timer_alarm_pending = 1;
292 /* Conversion factor from emulated instructions to virtual clock ticks. */
293 static int icount_time_shift;
294 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
295 #define MAX_ICOUNT_SHIFT 10
296 /* Compensate for varying guest execution speed. */
297 static int64_t qemu_icount_bias;
298 static QEMUTimer *icount_rt_timer;
299 static QEMUTimer *icount_vm_timer;
300 static QEMUTimer *nographic_timer;
302 uint8_t qemu_uuid[16];
304 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
305 struct timeval *tv)
307 int ret;
309 /* KVM holds a mutex while QEMU code is running, we need hooks to
310 release the mutex whenever QEMU code sleeps. */
312 kvm_sleep_begin();
314 ret = select(max_fd, rfds, wfds, xfds, tv);
316 kvm_sleep_end();
318 return ret;
322 /***********************************************************/
323 /* x86 ISA bus support */
325 target_phys_addr_t isa_mem_base = 0;
326 PicState2 *isa_pic;
328 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
329 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
331 static uint32_t ioport_read(int index, uint32_t address)
333 static IOPortReadFunc *default_func[3] = {
334 default_ioport_readb,
335 default_ioport_readw,
336 default_ioport_readl
338 IOPortReadFunc *func = ioport_read_table[index][address];
339 if (!func)
340 func = default_func[index];
341 return func(ioport_opaque[address], address);
344 static void ioport_write(int index, uint32_t address, uint32_t data)
346 static IOPortWriteFunc *default_func[3] = {
347 default_ioport_writeb,
348 default_ioport_writew,
349 default_ioport_writel
351 IOPortWriteFunc *func = ioport_write_table[index][address];
352 if (!func)
353 func = default_func[index];
354 func(ioport_opaque[address], address, data);
357 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
359 #ifdef DEBUG_UNUSED_IOPORT
360 fprintf(stderr, "unused inb: port=0x%04x\n", address);
361 #endif
362 return 0xff;
365 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
367 #ifdef DEBUG_UNUSED_IOPORT
368 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
369 #endif
372 /* default is to make two byte accesses */
373 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
375 uint32_t data;
376 data = ioport_read(0, address);
377 address = (address + 1) & (MAX_IOPORTS - 1);
378 data |= ioport_read(0, address) << 8;
379 return data;
382 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
384 ioport_write(0, address, data & 0xff);
385 address = (address + 1) & (MAX_IOPORTS - 1);
386 ioport_write(0, address, (data >> 8) & 0xff);
389 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
391 #ifdef DEBUG_UNUSED_IOPORT
392 fprintf(stderr, "unused inl: port=0x%04x\n", address);
393 #endif
394 return 0xffffffff;
397 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
399 #ifdef DEBUG_UNUSED_IOPORT
400 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
401 #endif
404 /* size is the word size in byte */
405 int register_ioport_read(int start, int length, int size,
406 IOPortReadFunc *func, void *opaque)
408 int i, bsize;
410 if (size == 1) {
411 bsize = 0;
412 } else if (size == 2) {
413 bsize = 1;
414 } else if (size == 4) {
415 bsize = 2;
416 } else {
417 hw_error("register_ioport_read: invalid size");
418 return -1;
420 for(i = start; i < start + length; i += size) {
421 ioport_read_table[bsize][i] = func;
422 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
423 hw_error("register_ioport_read: invalid opaque");
424 ioport_opaque[i] = opaque;
426 return 0;
429 /* size is the word size in byte */
430 int register_ioport_write(int start, int length, int size,
431 IOPortWriteFunc *func, void *opaque)
433 int i, bsize;
435 if (size == 1) {
436 bsize = 0;
437 } else if (size == 2) {
438 bsize = 1;
439 } else if (size == 4) {
440 bsize = 2;
441 } else {
442 hw_error("register_ioport_write: invalid size");
443 return -1;
445 for(i = start; i < start + length; i += size) {
446 ioport_write_table[bsize][i] = func;
447 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
448 hw_error("register_ioport_write: invalid opaque");
449 ioport_opaque[i] = opaque;
451 return 0;
454 void isa_unassign_ioport(int start, int length)
456 int i;
458 for(i = start; i < start + length; i++) {
459 ioport_read_table[0][i] = default_ioport_readb;
460 ioport_read_table[1][i] = default_ioport_readw;
461 ioport_read_table[2][i] = default_ioport_readl;
463 ioport_write_table[0][i] = default_ioport_writeb;
464 ioport_write_table[1][i] = default_ioport_writew;
465 ioport_write_table[2][i] = default_ioport_writel;
467 ioport_opaque[i] = NULL;
471 /***********************************************************/
473 void cpu_outb(CPUState *env, int addr, int val)
475 LOG_IOPORT("outb: %04x %02x\n", addr, val);
476 ioport_write(0, addr, val);
477 #ifdef CONFIG_KQEMU
478 if (env)
479 env->last_io_time = cpu_get_time_fast();
480 #endif
483 void cpu_outw(CPUState *env, int addr, int val)
485 LOG_IOPORT("outw: %04x %04x\n", addr, val);
486 ioport_write(1, addr, val);
487 #ifdef CONFIG_KQEMU
488 if (env)
489 env->last_io_time = cpu_get_time_fast();
490 #endif
493 void cpu_outl(CPUState *env, int addr, int val)
495 LOG_IOPORT("outl: %04x %08x\n", addr, val);
496 ioport_write(2, addr, val);
497 #ifdef CONFIG_KQEMU
498 if (env)
499 env->last_io_time = cpu_get_time_fast();
500 #endif
503 int cpu_inb(CPUState *env, int addr)
505 int val;
506 val = ioport_read(0, addr);
507 LOG_IOPORT("inb : %04x %02x\n", addr, val);
508 #ifdef CONFIG_KQEMU
509 if (env)
510 env->last_io_time = cpu_get_time_fast();
511 #endif
512 return val;
515 int cpu_inw(CPUState *env, int addr)
517 int val;
518 val = ioport_read(1, addr);
519 LOG_IOPORT("inw : %04x %04x\n", addr, val);
520 #ifdef CONFIG_KQEMU
521 if (env)
522 env->last_io_time = cpu_get_time_fast();
523 #endif
524 return val;
527 int cpu_inl(CPUState *env, int addr)
529 int val;
530 val = ioport_read(2, addr);
531 LOG_IOPORT("inl : %04x %08x\n", addr, val);
532 #ifdef CONFIG_KQEMU
533 if (env)
534 env->last_io_time = cpu_get_time_fast();
535 #endif
536 return val;
539 /***********************************************************/
540 void hw_error(const char *fmt, ...)
542 va_list ap;
543 CPUState *env;
545 va_start(ap, fmt);
546 fprintf(stderr, "qemu: hardware error: ");
547 vfprintf(stderr, fmt, ap);
548 fprintf(stderr, "\n");
549 for(env = first_cpu; env != NULL; env = env->next_cpu) {
550 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
551 #ifdef TARGET_I386
552 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
553 #else
554 cpu_dump_state(env, stderr, fprintf, 0);
555 #endif
557 va_end(ap);
558 abort();
561 /***************/
562 /* ballooning */
564 static QEMUBalloonEvent *qemu_balloon_event;
565 void *qemu_balloon_event_opaque;
567 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
569 qemu_balloon_event = func;
570 qemu_balloon_event_opaque = opaque;
573 void qemu_balloon(ram_addr_t target)
575 if (qemu_balloon_event)
576 qemu_balloon_event(qemu_balloon_event_opaque, target);
579 ram_addr_t qemu_balloon_status(void)
581 if (qemu_balloon_event)
582 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
583 return 0;
586 /***********************************************************/
587 /* keyboard/mouse */
589 static QEMUPutKBDEvent *qemu_put_kbd_event;
590 static void *qemu_put_kbd_event_opaque;
591 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
592 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
594 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
596 qemu_put_kbd_event_opaque = opaque;
597 qemu_put_kbd_event = func;
600 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
601 void *opaque, int absolute,
602 const char *name)
604 QEMUPutMouseEntry *s, *cursor;
606 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
608 s->qemu_put_mouse_event = func;
609 s->qemu_put_mouse_event_opaque = opaque;
610 s->qemu_put_mouse_event_absolute = absolute;
611 s->qemu_put_mouse_event_name = qemu_strdup(name);
612 s->next = NULL;
614 if (!qemu_put_mouse_event_head) {
615 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
616 return s;
619 cursor = qemu_put_mouse_event_head;
620 while (cursor->next != NULL)
621 cursor = cursor->next;
623 cursor->next = s;
624 qemu_put_mouse_event_current = s;
626 return s;
629 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
631 QEMUPutMouseEntry *prev = NULL, *cursor;
633 if (!qemu_put_mouse_event_head || entry == NULL)
634 return;
636 cursor = qemu_put_mouse_event_head;
637 while (cursor != NULL && cursor != entry) {
638 prev = cursor;
639 cursor = cursor->next;
642 if (cursor == NULL) // does not exist or list empty
643 return;
644 else if (prev == NULL) { // entry is head
645 qemu_put_mouse_event_head = cursor->next;
646 if (qemu_put_mouse_event_current == entry)
647 qemu_put_mouse_event_current = cursor->next;
648 qemu_free(entry->qemu_put_mouse_event_name);
649 qemu_free(entry);
650 return;
653 prev->next = entry->next;
655 if (qemu_put_mouse_event_current == entry)
656 qemu_put_mouse_event_current = prev;
658 qemu_free(entry->qemu_put_mouse_event_name);
659 qemu_free(entry);
662 void kbd_put_keycode(int keycode)
664 if (qemu_put_kbd_event) {
665 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
669 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
671 QEMUPutMouseEvent *mouse_event;
672 void *mouse_event_opaque;
673 int width;
675 if (!qemu_put_mouse_event_current) {
676 return;
679 mouse_event =
680 qemu_put_mouse_event_current->qemu_put_mouse_event;
681 mouse_event_opaque =
682 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
684 if (mouse_event) {
685 if (graphic_rotate) {
686 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
687 width = 0x7fff;
688 else
689 width = graphic_width - 1;
690 mouse_event(mouse_event_opaque,
691 width - dy, dx, dz, buttons_state);
692 } else
693 mouse_event(mouse_event_opaque,
694 dx, dy, dz, buttons_state);
698 int kbd_mouse_is_absolute(void)
700 if (!qemu_put_mouse_event_current)
701 return 0;
703 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
706 void do_info_mice(Monitor *mon)
708 QEMUPutMouseEntry *cursor;
709 int index = 0;
711 if (!qemu_put_mouse_event_head) {
712 monitor_printf(mon, "No mouse devices connected\n");
713 return;
716 monitor_printf(mon, "Mouse devices available:\n");
717 cursor = qemu_put_mouse_event_head;
718 while (cursor != NULL) {
719 monitor_printf(mon, "%c Mouse #%d: %s\n",
720 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
721 index, cursor->qemu_put_mouse_event_name);
722 index++;
723 cursor = cursor->next;
727 void do_mouse_set(Monitor *mon, int index)
729 QEMUPutMouseEntry *cursor;
730 int i = 0;
732 if (!qemu_put_mouse_event_head) {
733 monitor_printf(mon, "No mouse devices connected\n");
734 return;
737 cursor = qemu_put_mouse_event_head;
738 while (cursor != NULL && index != i) {
739 i++;
740 cursor = cursor->next;
743 if (cursor != NULL)
744 qemu_put_mouse_event_current = cursor;
745 else
746 monitor_printf(mon, "Mouse at given index not found\n");
749 /* compute with 96 bit intermediate result: (a*b)/c */
750 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
752 union {
753 uint64_t ll;
754 struct {
755 #ifdef WORDS_BIGENDIAN
756 uint32_t high, low;
757 #else
758 uint32_t low, high;
759 #endif
760 } l;
761 } u, res;
762 uint64_t rl, rh;
764 u.ll = a;
765 rl = (uint64_t)u.l.low * (uint64_t)b;
766 rh = (uint64_t)u.l.high * (uint64_t)b;
767 rh += (rl >> 32);
768 res.l.high = rh / c;
769 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
770 return res.ll;
773 /***********************************************************/
774 /* real time host monotonic timer */
776 #define QEMU_TIMER_BASE 1000000000LL
778 #ifdef WIN32
780 static int64_t clock_freq;
782 static void init_get_clock(void)
784 LARGE_INTEGER freq;
785 int ret;
786 ret = QueryPerformanceFrequency(&freq);
787 if (ret == 0) {
788 fprintf(stderr, "Could not calibrate ticks\n");
789 exit(1);
791 clock_freq = freq.QuadPart;
794 static int64_t get_clock(void)
796 LARGE_INTEGER ti;
797 QueryPerformanceCounter(&ti);
798 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
801 #else
803 static int use_rt_clock;
805 static void init_get_clock(void)
807 use_rt_clock = 0;
808 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
809 || defined(__DragonFly__)
811 struct timespec ts;
812 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
813 use_rt_clock = 1;
816 #endif
819 static int64_t get_clock(void)
821 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
822 || defined(__DragonFly__)
823 if (use_rt_clock) {
824 struct timespec ts;
825 clock_gettime(CLOCK_MONOTONIC, &ts);
826 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
827 } else
828 #endif
830 /* XXX: using gettimeofday leads to problems if the date
831 changes, so it should be avoided. */
832 struct timeval tv;
833 gettimeofday(&tv, NULL);
834 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
837 #endif
839 /* Return the virtual CPU time, based on the instruction counter. */
840 static int64_t cpu_get_icount(void)
842 int64_t icount;
843 CPUState *env = cpu_single_env;;
844 icount = qemu_icount;
845 if (env) {
846 if (!can_do_io(env))
847 fprintf(stderr, "Bad clock read\n");
848 icount -= (env->icount_decr.u16.low + env->icount_extra);
850 return qemu_icount_bias + (icount << icount_time_shift);
853 /***********************************************************/
854 /* guest cycle counter */
856 static int64_t cpu_ticks_prev;
857 static int64_t cpu_ticks_offset;
858 static int64_t cpu_clock_offset;
859 static int cpu_ticks_enabled;
861 /* return the host CPU cycle counter and handle stop/restart */
862 int64_t cpu_get_ticks(void)
864 if (use_icount) {
865 return cpu_get_icount();
867 if (!cpu_ticks_enabled) {
868 return cpu_ticks_offset;
869 } else {
870 int64_t ticks;
871 ticks = cpu_get_real_ticks();
872 if (cpu_ticks_prev > ticks) {
873 /* Note: non increasing ticks may happen if the host uses
874 software suspend */
875 cpu_ticks_offset += cpu_ticks_prev - ticks;
877 cpu_ticks_prev = ticks;
878 return ticks + cpu_ticks_offset;
882 /* return the host CPU monotonic timer and handle stop/restart */
883 static int64_t cpu_get_clock(void)
885 int64_t ti;
886 if (!cpu_ticks_enabled) {
887 return cpu_clock_offset;
888 } else {
889 ti = get_clock();
890 return ti + cpu_clock_offset;
894 /* enable cpu_get_ticks() */
895 void cpu_enable_ticks(void)
897 if (!cpu_ticks_enabled) {
898 cpu_ticks_offset -= cpu_get_real_ticks();
899 cpu_clock_offset -= get_clock();
900 cpu_ticks_enabled = 1;
904 /* disable cpu_get_ticks() : the clock is stopped. You must not call
905 cpu_get_ticks() after that. */
906 void cpu_disable_ticks(void)
908 if (cpu_ticks_enabled) {
909 cpu_ticks_offset = cpu_get_ticks();
910 cpu_clock_offset = cpu_get_clock();
911 cpu_ticks_enabled = 0;
915 /***********************************************************/
916 /* timers */
918 #define QEMU_TIMER_REALTIME 0
919 #define QEMU_TIMER_VIRTUAL 1
921 struct QEMUClock {
922 int type;
923 /* XXX: add frequency */
926 struct QEMUTimer {
927 QEMUClock *clock;
928 int64_t expire_time;
929 QEMUTimerCB *cb;
930 void *opaque;
931 struct QEMUTimer *next;
934 struct qemu_alarm_timer {
935 char const *name;
936 unsigned int flags;
938 int (*start)(struct qemu_alarm_timer *t);
939 void (*stop)(struct qemu_alarm_timer *t);
940 void (*rearm)(struct qemu_alarm_timer *t);
941 void *priv;
944 #define ALARM_FLAG_DYNTICKS 0x1
945 #define ALARM_FLAG_EXPIRED 0x2
947 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
949 return t && (t->flags & ALARM_FLAG_DYNTICKS);
952 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
954 if (!alarm_has_dynticks(t))
955 return;
957 t->rearm(t);
960 /* TODO: MIN_TIMER_REARM_US should be optimized */
961 #define MIN_TIMER_REARM_US 250
963 static struct qemu_alarm_timer *alarm_timer;
965 #ifdef _WIN32
967 struct qemu_alarm_win32 {
968 MMRESULT timerId;
969 unsigned int period;
970 } alarm_win32_data = {0, -1};
972 static int win32_start_timer(struct qemu_alarm_timer *t);
973 static void win32_stop_timer(struct qemu_alarm_timer *t);
974 static void win32_rearm_timer(struct qemu_alarm_timer *t);
976 #else
978 static int unix_start_timer(struct qemu_alarm_timer *t);
979 static void unix_stop_timer(struct qemu_alarm_timer *t);
981 #ifdef __linux__
983 static int dynticks_start_timer(struct qemu_alarm_timer *t);
984 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
985 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
987 static int hpet_start_timer(struct qemu_alarm_timer *t);
988 static void hpet_stop_timer(struct qemu_alarm_timer *t);
990 static int rtc_start_timer(struct qemu_alarm_timer *t);
991 static void rtc_stop_timer(struct qemu_alarm_timer *t);
993 #endif /* __linux__ */
995 #endif /* _WIN32 */
997 /* Correlation between real and virtual time is always going to be
998 fairly approximate, so ignore small variation.
999 When the guest is idle real and virtual time will be aligned in
1000 the IO wait loop. */
1001 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
1003 static void icount_adjust(void)
1005 int64_t cur_time;
1006 int64_t cur_icount;
1007 int64_t delta;
1008 static int64_t last_delta;
1009 /* If the VM is not running, then do nothing. */
1010 if (!vm_running)
1011 return;
1013 cur_time = cpu_get_clock();
1014 cur_icount = qemu_get_clock(vm_clock);
1015 delta = cur_icount - cur_time;
1016 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1017 if (delta > 0
1018 && last_delta + ICOUNT_WOBBLE < delta * 2
1019 && icount_time_shift > 0) {
1020 /* The guest is getting too far ahead. Slow time down. */
1021 icount_time_shift--;
1023 if (delta < 0
1024 && last_delta - ICOUNT_WOBBLE > delta * 2
1025 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1026 /* The guest is getting too far behind. Speed time up. */
1027 icount_time_shift++;
1029 last_delta = delta;
1030 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1033 static void icount_adjust_rt(void * opaque)
1035 qemu_mod_timer(icount_rt_timer,
1036 qemu_get_clock(rt_clock) + 1000);
1037 icount_adjust();
1040 static void icount_adjust_vm(void * opaque)
1042 qemu_mod_timer(icount_vm_timer,
1043 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1044 icount_adjust();
1047 static void init_icount_adjust(void)
1049 /* Have both realtime and virtual time triggers for speed adjustment.
1050 The realtime trigger catches emulated time passing too slowly,
1051 the virtual time trigger catches emulated time passing too fast.
1052 Realtime triggers occur even when idle, so use them less frequently
1053 than VM triggers. */
1054 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1055 qemu_mod_timer(icount_rt_timer,
1056 qemu_get_clock(rt_clock) + 1000);
1057 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1058 qemu_mod_timer(icount_vm_timer,
1059 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1062 static struct qemu_alarm_timer alarm_timers[] = {
1063 #ifndef _WIN32
1064 #ifdef __linux__
1065 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1066 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1067 /* HPET - if available - is preferred */
1068 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1069 /* ...otherwise try RTC */
1070 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1071 #endif
1072 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1073 #else
1074 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1075 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1076 {"win32", 0, win32_start_timer,
1077 win32_stop_timer, NULL, &alarm_win32_data},
1078 #endif
1079 {NULL, }
1082 static void show_available_alarms(void)
1084 int i;
1086 printf("Available alarm timers, in order of precedence:\n");
1087 for (i = 0; alarm_timers[i].name; i++)
1088 printf("%s\n", alarm_timers[i].name);
1091 static void configure_alarms(char const *opt)
1093 int i;
1094 int cur = 0;
1095 int count = ARRAY_SIZE(alarm_timers) - 1;
1096 char *arg;
1097 char *name;
1098 struct qemu_alarm_timer tmp;
1100 if (!strcmp(opt, "?")) {
1101 show_available_alarms();
1102 exit(0);
1105 arg = strdup(opt);
1107 /* Reorder the array */
1108 name = strtok(arg, ",");
1109 while (name) {
1110 for (i = 0; i < count && alarm_timers[i].name; i++) {
1111 if (!strcmp(alarm_timers[i].name, name))
1112 break;
1115 if (i == count) {
1116 fprintf(stderr, "Unknown clock %s\n", name);
1117 goto next;
1120 if (i < cur)
1121 /* Ignore */
1122 goto next;
1124 /* Swap */
1125 tmp = alarm_timers[i];
1126 alarm_timers[i] = alarm_timers[cur];
1127 alarm_timers[cur] = tmp;
1129 cur++;
1130 next:
1131 name = strtok(NULL, ",");
1134 free(arg);
1136 if (cur) {
1137 /* Disable remaining timers */
1138 for (i = cur; i < count; i++)
1139 alarm_timers[i].name = NULL;
1140 } else {
1141 show_available_alarms();
1142 exit(1);
1146 QEMUClock *rt_clock;
1147 QEMUClock *vm_clock;
1149 static QEMUTimer *active_timers[2];
1151 static QEMUClock *qemu_new_clock(int type)
1153 QEMUClock *clock;
1154 clock = qemu_mallocz(sizeof(QEMUClock));
1155 clock->type = type;
1156 return clock;
1159 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1161 QEMUTimer *ts;
1163 ts = qemu_mallocz(sizeof(QEMUTimer));
1164 ts->clock = clock;
1165 ts->cb = cb;
1166 ts->opaque = opaque;
1167 return ts;
1170 void qemu_free_timer(QEMUTimer *ts)
1172 qemu_free(ts);
1175 /* stop a timer, but do not dealloc it */
1176 void qemu_del_timer(QEMUTimer *ts)
1178 QEMUTimer **pt, *t;
1180 /* NOTE: this code must be signal safe because
1181 qemu_timer_expired() can be called from a signal. */
1182 pt = &active_timers[ts->clock->type];
1183 for(;;) {
1184 t = *pt;
1185 if (!t)
1186 break;
1187 if (t == ts) {
1188 *pt = t->next;
1189 break;
1191 pt = &t->next;
1195 /* modify the current timer so that it will be fired when current_time
1196 >= expire_time. The corresponding callback will be called. */
1197 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1199 QEMUTimer **pt, *t;
1201 qemu_del_timer(ts);
1203 /* add the timer in the sorted list */
1204 /* NOTE: this code must be signal safe because
1205 qemu_timer_expired() can be called from a signal. */
1206 pt = &active_timers[ts->clock->type];
1207 for(;;) {
1208 t = *pt;
1209 if (!t)
1210 break;
1211 if (t->expire_time > expire_time)
1212 break;
1213 pt = &t->next;
1215 ts->expire_time = expire_time;
1216 ts->next = *pt;
1217 *pt = ts;
1219 /* Rearm if necessary */
1220 if (pt == &active_timers[ts->clock->type]) {
1221 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1222 qemu_rearm_alarm_timer(alarm_timer);
1224 /* Interrupt execution to force deadline recalculation. */
1225 if (use_icount)
1226 qemu_notify_event();
1230 int qemu_timer_pending(QEMUTimer *ts)
1232 QEMUTimer *t;
1233 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1234 if (t == ts)
1235 return 1;
1237 return 0;
1240 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1242 if (!timer_head)
1243 return 0;
1244 return (timer_head->expire_time <= current_time);
1247 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1249 QEMUTimer *ts;
1251 for(;;) {
1252 ts = *ptimer_head;
1253 if (!ts || ts->expire_time > current_time)
1254 break;
1255 /* remove timer from the list before calling the callback */
1256 *ptimer_head = ts->next;
1257 ts->next = NULL;
1259 /* run the callback (the timer list can be modified) */
1260 ts->cb(ts->opaque);
1264 int64_t qemu_get_clock(QEMUClock *clock)
1266 switch(clock->type) {
1267 case QEMU_TIMER_REALTIME:
1268 return get_clock() / 1000000;
1269 default:
1270 case QEMU_TIMER_VIRTUAL:
1271 if (use_icount) {
1272 return cpu_get_icount();
1273 } else {
1274 return cpu_get_clock();
1279 static void init_timers(void)
1281 init_get_clock();
1282 ticks_per_sec = QEMU_TIMER_BASE;
1283 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1284 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1287 /* save a timer */
1288 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1290 uint64_t expire_time;
1292 if (qemu_timer_pending(ts)) {
1293 expire_time = ts->expire_time;
1294 } else {
1295 expire_time = -1;
1297 qemu_put_be64(f, expire_time);
1300 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1302 uint64_t expire_time;
1304 expire_time = qemu_get_be64(f);
1305 if (expire_time != -1) {
1306 qemu_mod_timer(ts, expire_time);
1307 } else {
1308 qemu_del_timer(ts);
1312 static void timer_save(QEMUFile *f, void *opaque)
1314 if (cpu_ticks_enabled) {
1315 hw_error("cannot save state if virtual timers are running");
1317 qemu_put_be64(f, cpu_ticks_offset);
1318 qemu_put_be64(f, ticks_per_sec);
1319 qemu_put_be64(f, cpu_clock_offset);
1322 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1324 if (version_id != 1 && version_id != 2)
1325 return -EINVAL;
1326 if (cpu_ticks_enabled) {
1327 return -EINVAL;
1329 cpu_ticks_offset=qemu_get_be64(f);
1330 ticks_per_sec=qemu_get_be64(f);
1331 if (version_id == 2) {
1332 cpu_clock_offset=qemu_get_be64(f);
1334 return 0;
1337 static void qemu_event_increment(void);
1339 #ifdef _WIN32
1340 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1341 DWORD_PTR dwUser, DWORD_PTR dw1,
1342 DWORD_PTR dw2)
1343 #else
1344 static void host_alarm_handler(int host_signum)
1345 #endif
1347 #if 0
1348 #define DISP_FREQ 1000
1350 static int64_t delta_min = INT64_MAX;
1351 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1352 static int count;
1353 ti = qemu_get_clock(vm_clock);
1354 if (last_clock != 0) {
1355 delta = ti - last_clock;
1356 if (delta < delta_min)
1357 delta_min = delta;
1358 if (delta > delta_max)
1359 delta_max = delta;
1360 delta_cum += delta;
1361 if (++count == DISP_FREQ) {
1362 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1363 muldiv64(delta_min, 1000000, ticks_per_sec),
1364 muldiv64(delta_max, 1000000, ticks_per_sec),
1365 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1366 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1367 count = 0;
1368 delta_min = INT64_MAX;
1369 delta_max = 0;
1370 delta_cum = 0;
1373 last_clock = ti;
1375 #endif
1376 if (alarm_has_dynticks(alarm_timer) ||
1377 (!use_icount &&
1378 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1379 qemu_get_clock(vm_clock))) ||
1380 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1381 qemu_get_clock(rt_clock))) {
1382 qemu_event_increment();
1383 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1385 #ifndef CONFIG_IOTHREAD
1386 if (next_cpu) {
1387 /* stop the currently executing cpu because a timer occured */
1388 cpu_exit(next_cpu);
1389 #ifdef CONFIG_KQEMU
1390 if (next_cpu->kqemu_enabled) {
1391 kqemu_cpu_interrupt(next_cpu);
1393 #endif
1395 #endif
1396 timer_alarm_pending = 1;
1397 qemu_notify_event();
1401 static int64_t qemu_next_deadline(void)
1403 int64_t delta;
1405 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1406 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1407 qemu_get_clock(vm_clock);
1408 } else {
1409 /* To avoid problems with overflow limit this to 2^32. */
1410 delta = INT32_MAX;
1413 if (delta < 0)
1414 delta = 0;
1416 return delta;
1419 #if defined(__linux__) || defined(_WIN32)
1420 static uint64_t qemu_next_deadline_dyntick(void)
1422 int64_t delta;
1423 int64_t rtdelta;
1425 if (use_icount)
1426 delta = INT32_MAX;
1427 else
1428 delta = (qemu_next_deadline() + 999) / 1000;
1430 if (active_timers[QEMU_TIMER_REALTIME]) {
1431 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1432 qemu_get_clock(rt_clock))*1000;
1433 if (rtdelta < delta)
1434 delta = rtdelta;
1437 if (delta < MIN_TIMER_REARM_US)
1438 delta = MIN_TIMER_REARM_US;
1440 return delta;
1442 #endif
1444 #ifndef _WIN32
1446 /* Sets a specific flag */
1447 static int fcntl_setfl(int fd, int flag)
1449 int flags;
1451 flags = fcntl(fd, F_GETFL);
1452 if (flags == -1)
1453 return -errno;
1455 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1456 return -errno;
1458 return 0;
1461 #if defined(__linux__)
1463 #define RTC_FREQ 1024
1465 static void enable_sigio_timer(int fd)
1467 struct sigaction act;
1469 /* timer signal */
1470 sigfillset(&act.sa_mask);
1471 act.sa_flags = 0;
1472 act.sa_handler = host_alarm_handler;
1474 sigaction(SIGIO, &act, NULL);
1475 fcntl_setfl(fd, O_ASYNC);
1476 fcntl(fd, F_SETOWN, getpid());
1479 static int hpet_start_timer(struct qemu_alarm_timer *t)
1481 struct hpet_info info;
1482 int r, fd;
1484 fd = open("/dev/hpet", O_RDONLY);
1485 if (fd < 0)
1486 return -1;
1488 /* Set frequency */
1489 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1490 if (r < 0) {
1491 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1492 "error, but for better emulation accuracy type:\n"
1493 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1494 goto fail;
1497 /* Check capabilities */
1498 r = ioctl(fd, HPET_INFO, &info);
1499 if (r < 0)
1500 goto fail;
1502 /* Enable periodic mode */
1503 r = ioctl(fd, HPET_EPI, 0);
1504 if (info.hi_flags && (r < 0))
1505 goto fail;
1507 /* Enable interrupt */
1508 r = ioctl(fd, HPET_IE_ON, 0);
1509 if (r < 0)
1510 goto fail;
1512 enable_sigio_timer(fd);
1513 t->priv = (void *)(long)fd;
1515 return 0;
1516 fail:
1517 close(fd);
1518 return -1;
1521 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1523 int fd = (long)t->priv;
1525 close(fd);
1528 static int rtc_start_timer(struct qemu_alarm_timer *t)
1530 int rtc_fd;
1531 unsigned long current_rtc_freq = 0;
1533 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1534 if (rtc_fd < 0)
1535 return -1;
1536 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1537 if (current_rtc_freq != RTC_FREQ &&
1538 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1539 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1540 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1541 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1542 goto fail;
1544 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1545 fail:
1546 close(rtc_fd);
1547 return -1;
1550 enable_sigio_timer(rtc_fd);
1552 t->priv = (void *)(long)rtc_fd;
1554 return 0;
1557 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1559 int rtc_fd = (long)t->priv;
1561 close(rtc_fd);
1564 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1566 struct sigevent ev;
1567 timer_t host_timer;
1568 struct sigaction act;
1570 sigfillset(&act.sa_mask);
1571 act.sa_flags = 0;
1572 act.sa_handler = host_alarm_handler;
1574 sigaction(SIGALRM, &act, NULL);
1577 * Initialize ev struct to 0 to avoid valgrind complaining
1578 * about uninitialized data in timer_create call
1580 memset(&ev, 0, sizeof(ev));
1581 ev.sigev_value.sival_int = 0;
1582 ev.sigev_notify = SIGEV_SIGNAL;
1583 ev.sigev_signo = SIGALRM;
1585 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1586 perror("timer_create");
1588 /* disable dynticks */
1589 fprintf(stderr, "Dynamic Ticks disabled\n");
1591 return -1;
1594 t->priv = (void *)(long)host_timer;
1596 return 0;
1599 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1601 timer_t host_timer = (timer_t)(long)t->priv;
1603 timer_delete(host_timer);
1606 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1608 timer_t host_timer = (timer_t)(long)t->priv;
1609 struct itimerspec timeout;
1610 int64_t nearest_delta_us = INT64_MAX;
1611 int64_t current_us;
1613 if (!active_timers[QEMU_TIMER_REALTIME] &&
1614 !active_timers[QEMU_TIMER_VIRTUAL])
1615 return;
1617 nearest_delta_us = qemu_next_deadline_dyntick();
1619 /* check whether a timer is already running */
1620 if (timer_gettime(host_timer, &timeout)) {
1621 perror("gettime");
1622 fprintf(stderr, "Internal timer error: aborting\n");
1623 exit(1);
1625 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1626 if (current_us && current_us <= nearest_delta_us)
1627 return;
1629 timeout.it_interval.tv_sec = 0;
1630 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1631 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1632 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1633 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1634 perror("settime");
1635 fprintf(stderr, "Internal timer error: aborting\n");
1636 exit(1);
1640 #endif /* defined(__linux__) */
1642 static int unix_start_timer(struct qemu_alarm_timer *t)
1644 struct sigaction act;
1645 struct itimerval itv;
1646 int err;
1648 /* timer signal */
1649 sigfillset(&act.sa_mask);
1650 act.sa_flags = 0;
1651 act.sa_handler = host_alarm_handler;
1653 sigaction(SIGALRM, &act, NULL);
1655 itv.it_interval.tv_sec = 0;
1656 /* for i386 kernel 2.6 to get 1 ms */
1657 itv.it_interval.tv_usec = 999;
1658 itv.it_value.tv_sec = 0;
1659 itv.it_value.tv_usec = 10 * 1000;
1661 err = setitimer(ITIMER_REAL, &itv, NULL);
1662 if (err)
1663 return -1;
1665 return 0;
1668 static void unix_stop_timer(struct qemu_alarm_timer *t)
1670 struct itimerval itv;
1672 memset(&itv, 0, sizeof(itv));
1673 setitimer(ITIMER_REAL, &itv, NULL);
1676 #endif /* !defined(_WIN32) */
1679 #ifdef _WIN32
1681 static int win32_start_timer(struct qemu_alarm_timer *t)
1683 TIMECAPS tc;
1684 struct qemu_alarm_win32 *data = t->priv;
1685 UINT flags;
1687 memset(&tc, 0, sizeof(tc));
1688 timeGetDevCaps(&tc, sizeof(tc));
1690 if (data->period < tc.wPeriodMin)
1691 data->period = tc.wPeriodMin;
1693 timeBeginPeriod(data->period);
1695 flags = TIME_CALLBACK_FUNCTION;
1696 if (alarm_has_dynticks(t))
1697 flags |= TIME_ONESHOT;
1698 else
1699 flags |= TIME_PERIODIC;
1701 data->timerId = timeSetEvent(1, // interval (ms)
1702 data->period, // resolution
1703 host_alarm_handler, // function
1704 (DWORD)t, // parameter
1705 flags);
1707 if (!data->timerId) {
1708 perror("Failed to initialize win32 alarm timer");
1709 timeEndPeriod(data->period);
1710 return -1;
1713 return 0;
1716 static void win32_stop_timer(struct qemu_alarm_timer *t)
1718 struct qemu_alarm_win32 *data = t->priv;
1720 timeKillEvent(data->timerId);
1721 timeEndPeriod(data->period);
1724 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1726 struct qemu_alarm_win32 *data = t->priv;
1727 uint64_t nearest_delta_us;
1729 if (!active_timers[QEMU_TIMER_REALTIME] &&
1730 !active_timers[QEMU_TIMER_VIRTUAL])
1731 return;
1733 nearest_delta_us = qemu_next_deadline_dyntick();
1734 nearest_delta_us /= 1000;
1736 timeKillEvent(data->timerId);
1738 data->timerId = timeSetEvent(1,
1739 data->period,
1740 host_alarm_handler,
1741 (DWORD)t,
1742 TIME_ONESHOT | TIME_PERIODIC);
1744 if (!data->timerId) {
1745 perror("Failed to re-arm win32 alarm timer");
1747 timeEndPeriod(data->period);
1748 exit(1);
1752 #endif /* _WIN32 */
1754 static int init_timer_alarm(void)
1756 struct qemu_alarm_timer *t = NULL;
1757 int i, err = -1;
1759 for (i = 0; alarm_timers[i].name; i++) {
1760 t = &alarm_timers[i];
1762 err = t->start(t);
1763 if (!err)
1764 break;
1767 if (err) {
1768 err = -ENOENT;
1769 goto fail;
1772 alarm_timer = t;
1774 return 0;
1776 fail:
1777 return err;
1780 static void quit_timers(void)
1782 alarm_timer->stop(alarm_timer);
1783 alarm_timer = NULL;
1786 /***********************************************************/
1787 /* host time/date access */
1788 void qemu_get_timedate(struct tm *tm, int offset)
1790 time_t ti;
1791 struct tm *ret;
1793 time(&ti);
1794 ti += offset;
1795 if (rtc_date_offset == -1) {
1796 if (rtc_utc)
1797 ret = gmtime(&ti);
1798 else
1799 ret = localtime(&ti);
1800 } else {
1801 ti -= rtc_date_offset;
1802 ret = gmtime(&ti);
1805 memcpy(tm, ret, sizeof(struct tm));
1808 int qemu_timedate_diff(struct tm *tm)
1810 time_t seconds;
1812 if (rtc_date_offset == -1)
1813 if (rtc_utc)
1814 seconds = mktimegm(tm);
1815 else
1816 seconds = mktime(tm);
1817 else
1818 seconds = mktimegm(tm) + rtc_date_offset;
1820 return seconds - time(NULL);
1823 #ifdef _WIN32
1824 static void socket_cleanup(void)
1826 WSACleanup();
1829 static int socket_init(void)
1831 WSADATA Data;
1832 int ret, err;
1834 ret = WSAStartup(MAKEWORD(2,2), &Data);
1835 if (ret != 0) {
1836 err = WSAGetLastError();
1837 fprintf(stderr, "WSAStartup: %d\n", err);
1838 return -1;
1840 atexit(socket_cleanup);
1841 return 0;
1843 #endif
1845 int get_param_value(char *buf, int buf_size,
1846 const char *tag, const char *str)
1848 const char *p;
1849 char option[128];
1851 p = str;
1852 for(;;) {
1853 p = get_opt_name(option, sizeof(option), p, '=');
1854 if (*p != '=')
1855 break;
1856 p++;
1857 if (!strcmp(tag, option)) {
1858 (void)get_opt_value(buf, buf_size, p);
1859 return strlen(buf);
1860 } else {
1861 p = get_opt_value(NULL, 0, p);
1863 if (*p != ',')
1864 break;
1865 p++;
1867 return 0;
1870 int check_params(char *buf, int buf_size,
1871 const char * const *params, const char *str)
1873 const char *p;
1874 int i;
1876 p = str;
1877 while (*p != '\0') {
1878 p = get_opt_name(buf, buf_size, p, '=');
1879 if (*p != '=') {
1880 return -1;
1882 p++;
1883 for (i = 0; params[i] != NULL; i++) {
1884 if (!strcmp(params[i], buf)) {
1885 break;
1888 if (params[i] == NULL) {
1889 return -1;
1891 p = get_opt_value(NULL, 0, p);
1892 if (*p != ',') {
1893 break;
1895 p++;
1897 return 0;
1900 /***********************************************************/
1901 /* Bluetooth support */
1902 static int nb_hcis;
1903 static int cur_hci;
1904 static struct HCIInfo *hci_table[MAX_NICS];
1906 static struct bt_vlan_s {
1907 struct bt_scatternet_s net;
1908 int id;
1909 struct bt_vlan_s *next;
1910 } *first_bt_vlan;
1912 /* find or alloc a new bluetooth "VLAN" */
1913 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1915 struct bt_vlan_s **pvlan, *vlan;
1916 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1917 if (vlan->id == id)
1918 return &vlan->net;
1920 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1921 vlan->id = id;
1922 pvlan = &first_bt_vlan;
1923 while (*pvlan != NULL)
1924 pvlan = &(*pvlan)->next;
1925 *pvlan = vlan;
1926 return &vlan->net;
1929 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1933 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1935 return -ENOTSUP;
1938 static struct HCIInfo null_hci = {
1939 .cmd_send = null_hci_send,
1940 .sco_send = null_hci_send,
1941 .acl_send = null_hci_send,
1942 .bdaddr_set = null_hci_addr_set,
1945 struct HCIInfo *qemu_next_hci(void)
1947 if (cur_hci == nb_hcis)
1948 return &null_hci;
1950 return hci_table[cur_hci++];
1953 static struct HCIInfo *hci_init(const char *str)
1955 char *endp;
1956 struct bt_scatternet_s *vlan = 0;
1958 if (!strcmp(str, "null"))
1959 /* null */
1960 return &null_hci;
1961 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1962 /* host[:hciN] */
1963 return bt_host_hci(str[4] ? str + 5 : "hci0");
1964 else if (!strncmp(str, "hci", 3)) {
1965 /* hci[,vlan=n] */
1966 if (str[3]) {
1967 if (!strncmp(str + 3, ",vlan=", 6)) {
1968 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1969 if (*endp)
1970 vlan = 0;
1972 } else
1973 vlan = qemu_find_bt_vlan(0);
1974 if (vlan)
1975 return bt_new_hci(vlan);
1978 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1980 return 0;
1983 static int bt_hci_parse(const char *str)
1985 struct HCIInfo *hci;
1986 bdaddr_t bdaddr;
1988 if (nb_hcis >= MAX_NICS) {
1989 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1990 return -1;
1993 hci = hci_init(str);
1994 if (!hci)
1995 return -1;
1997 bdaddr.b[0] = 0x52;
1998 bdaddr.b[1] = 0x54;
1999 bdaddr.b[2] = 0x00;
2000 bdaddr.b[3] = 0x12;
2001 bdaddr.b[4] = 0x34;
2002 bdaddr.b[5] = 0x56 + nb_hcis;
2003 hci->bdaddr_set(hci, bdaddr.b);
2005 hci_table[nb_hcis++] = hci;
2007 return 0;
2010 static void bt_vhci_add(int vlan_id)
2012 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2014 if (!vlan->slave)
2015 fprintf(stderr, "qemu: warning: adding a VHCI to "
2016 "an empty scatternet %i\n", vlan_id);
2018 bt_vhci_init(bt_new_hci(vlan));
2021 static struct bt_device_s *bt_device_add(const char *opt)
2023 struct bt_scatternet_s *vlan;
2024 int vlan_id = 0;
2025 char *endp = strstr(opt, ",vlan=");
2026 int len = (endp ? endp - opt : strlen(opt)) + 1;
2027 char devname[10];
2029 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2031 if (endp) {
2032 vlan_id = strtol(endp + 6, &endp, 0);
2033 if (*endp) {
2034 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2035 return 0;
2039 vlan = qemu_find_bt_vlan(vlan_id);
2041 if (!vlan->slave)
2042 fprintf(stderr, "qemu: warning: adding a slave device to "
2043 "an empty scatternet %i\n", vlan_id);
2045 if (!strcmp(devname, "keyboard"))
2046 return bt_keyboard_init(vlan);
2048 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2049 return 0;
2052 static int bt_parse(const char *opt)
2054 const char *endp, *p;
2055 int vlan;
2057 if (strstart(opt, "hci", &endp)) {
2058 if (!*endp || *endp == ',') {
2059 if (*endp)
2060 if (!strstart(endp, ",vlan=", 0))
2061 opt = endp + 1;
2063 return bt_hci_parse(opt);
2065 } else if (strstart(opt, "vhci", &endp)) {
2066 if (!*endp || *endp == ',') {
2067 if (*endp) {
2068 if (strstart(endp, ",vlan=", &p)) {
2069 vlan = strtol(p, (char **) &endp, 0);
2070 if (*endp) {
2071 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2072 return 1;
2074 } else {
2075 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2076 return 1;
2078 } else
2079 vlan = 0;
2081 bt_vhci_add(vlan);
2082 return 0;
2084 } else if (strstart(opt, "device:", &endp))
2085 return !bt_device_add(endp);
2087 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2088 return 1;
2091 /***********************************************************/
2092 /* QEMU Block devices */
2094 #define HD_ALIAS "index=%d,media=disk"
2095 #define CDROM_ALIAS "index=2,media=cdrom"
2096 #define FD_ALIAS "index=%d,if=floppy"
2097 #define PFLASH_ALIAS "if=pflash"
2098 #define MTD_ALIAS "if=mtd"
2099 #define SD_ALIAS "index=0,if=sd"
2101 static int drive_opt_get_free_idx(void)
2103 int index;
2105 for (index = 0; index < MAX_DRIVES; index++)
2106 if (!drives_opt[index].used) {
2107 drives_opt[index].used = 1;
2108 return index;
2111 return -1;
2114 static int drive_get_free_idx(void)
2116 int index;
2118 for (index = 0; index < MAX_DRIVES; index++)
2119 if (!drives_table[index].used) {
2120 drives_table[index].used = 1;
2121 return index;
2124 return -1;
2127 int drive_add(const char *file, const char *fmt, ...)
2129 va_list ap;
2130 int index = drive_opt_get_free_idx();
2132 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2133 fprintf(stderr, "qemu: too many drives\n");
2134 return -1;
2137 drives_opt[index].file = file;
2138 va_start(ap, fmt);
2139 vsnprintf(drives_opt[index].opt,
2140 sizeof(drives_opt[0].opt), fmt, ap);
2141 va_end(ap);
2143 nb_drives_opt++;
2144 return index;
2147 void drive_remove(int index)
2149 drives_opt[index].used = 0;
2150 nb_drives_opt--;
2153 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2155 int index;
2157 /* seek interface, bus and unit */
2159 for (index = 0; index < MAX_DRIVES; index++)
2160 if (drives_table[index].type == type &&
2161 drives_table[index].bus == bus &&
2162 drives_table[index].unit == unit &&
2163 drives_table[index].used)
2164 return index;
2166 return -1;
2169 int drive_get_max_bus(BlockInterfaceType type)
2171 int max_bus;
2172 int index;
2174 max_bus = -1;
2175 for (index = 0; index < nb_drives; index++) {
2176 if(drives_table[index].type == type &&
2177 drives_table[index].bus > max_bus)
2178 max_bus = drives_table[index].bus;
2180 return max_bus;
2183 const char *drive_get_serial(BlockDriverState *bdrv)
2185 int index;
2187 for (index = 0; index < nb_drives; index++)
2188 if (drives_table[index].bdrv == bdrv)
2189 return drives_table[index].serial;
2191 return "\0";
2194 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2196 int index;
2198 for (index = 0; index < nb_drives; index++)
2199 if (drives_table[index].bdrv == bdrv)
2200 return drives_table[index].onerror;
2202 return BLOCK_ERR_STOP_ENOSPC;
2205 static void bdrv_format_print(void *opaque, const char *name)
2207 fprintf(stderr, " %s", name);
2210 void drive_uninit(BlockDriverState *bdrv)
2212 int i;
2214 for (i = 0; i < MAX_DRIVES; i++)
2215 if (drives_table[i].bdrv == bdrv) {
2216 drives_table[i].bdrv = NULL;
2217 drives_table[i].used = 0;
2218 drive_remove(drives_table[i].drive_opt_idx);
2219 nb_drives--;
2220 break;
2224 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2226 char buf[128];
2227 char file[1024];
2228 char devname[128];
2229 char serial[21];
2230 const char *mediastr = "";
2231 BlockInterfaceType type;
2232 enum { MEDIA_DISK, MEDIA_CDROM } media;
2233 int bus_id, unit_id;
2234 int cyls, heads, secs, translation;
2235 BlockDriverState *bdrv;
2236 BlockDriver *drv = NULL;
2237 QEMUMachine *machine = opaque;
2238 int max_devs;
2239 int index;
2240 int cache;
2241 int bdrv_flags, onerror;
2242 const char *devaddr;
2243 int drives_table_idx;
2244 char *str = arg->opt;
2245 static const char * const params[] = { "bus", "unit", "if", "index",
2246 "cyls", "heads", "secs", "trans",
2247 "media", "snapshot", "file",
2248 "cache", "format", "serial",
2249 "werror", "addr",
2250 "boot",
2251 NULL };
2253 if (check_params(buf, sizeof(buf), params, str) < 0) {
2254 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2255 buf, str);
2256 return -1;
2259 file[0] = 0;
2260 cyls = heads = secs = 0;
2261 bus_id = 0;
2262 unit_id = -1;
2263 translation = BIOS_ATA_TRANSLATION_AUTO;
2264 index = -1;
2265 cache = 3;
2267 if (machine->use_scsi) {
2268 type = IF_SCSI;
2269 max_devs = MAX_SCSI_DEVS;
2270 pstrcpy(devname, sizeof(devname), "scsi");
2271 } else {
2272 type = IF_IDE;
2273 max_devs = MAX_IDE_DEVS;
2274 pstrcpy(devname, sizeof(devname), "ide");
2276 media = MEDIA_DISK;
2278 /* extract parameters */
2280 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2281 bus_id = strtol(buf, NULL, 0);
2282 if (bus_id < 0) {
2283 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2284 return -1;
2288 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2289 unit_id = strtol(buf, NULL, 0);
2290 if (unit_id < 0) {
2291 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2292 return -1;
2296 if (get_param_value(buf, sizeof(buf), "if", str)) {
2297 pstrcpy(devname, sizeof(devname), buf);
2298 if (!strcmp(buf, "ide")) {
2299 type = IF_IDE;
2300 max_devs = MAX_IDE_DEVS;
2301 } else if (!strcmp(buf, "scsi")) {
2302 type = IF_SCSI;
2303 max_devs = MAX_SCSI_DEVS;
2304 } else if (!strcmp(buf, "floppy")) {
2305 type = IF_FLOPPY;
2306 max_devs = 0;
2307 } else if (!strcmp(buf, "pflash")) {
2308 type = IF_PFLASH;
2309 max_devs = 0;
2310 } else if (!strcmp(buf, "mtd")) {
2311 type = IF_MTD;
2312 max_devs = 0;
2313 } else if (!strcmp(buf, "sd")) {
2314 type = IF_SD;
2315 max_devs = 0;
2316 } else if (!strcmp(buf, "virtio")) {
2317 type = IF_VIRTIO;
2318 max_devs = 0;
2319 } else if (!strcmp(buf, "xen")) {
2320 type = IF_XEN;
2321 max_devs = 0;
2322 } else {
2323 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2324 return -1;
2328 if (get_param_value(buf, sizeof(buf), "index", str)) {
2329 index = strtol(buf, NULL, 0);
2330 if (index < 0) {
2331 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2332 return -1;
2336 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2337 cyls = strtol(buf, NULL, 0);
2340 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2341 heads = strtol(buf, NULL, 0);
2344 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2345 secs = strtol(buf, NULL, 0);
2348 if (cyls || heads || secs) {
2349 if (cyls < 1 || cyls > 16383) {
2350 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2351 return -1;
2353 if (heads < 1 || heads > 16) {
2354 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2355 return -1;
2357 if (secs < 1 || secs > 63) {
2358 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2359 return -1;
2363 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2364 if (!cyls) {
2365 fprintf(stderr,
2366 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2367 str);
2368 return -1;
2370 if (!strcmp(buf, "none"))
2371 translation = BIOS_ATA_TRANSLATION_NONE;
2372 else if (!strcmp(buf, "lba"))
2373 translation = BIOS_ATA_TRANSLATION_LBA;
2374 else if (!strcmp(buf, "auto"))
2375 translation = BIOS_ATA_TRANSLATION_AUTO;
2376 else {
2377 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2378 return -1;
2382 if (get_param_value(buf, sizeof(buf), "media", str)) {
2383 if (!strcmp(buf, "disk")) {
2384 media = MEDIA_DISK;
2385 } else if (!strcmp(buf, "cdrom")) {
2386 if (cyls || secs || heads) {
2387 fprintf(stderr,
2388 "qemu: '%s' invalid physical CHS format\n", str);
2389 return -1;
2391 media = MEDIA_CDROM;
2392 } else {
2393 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2394 return -1;
2398 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2399 if (!strcmp(buf, "on"))
2400 snapshot = 1;
2401 else if (!strcmp(buf, "off"))
2402 snapshot = 0;
2403 else {
2404 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2405 return -1;
2409 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2410 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2411 cache = 0;
2412 else if (!strcmp(buf, "writethrough"))
2413 cache = 1;
2414 else if (!strcmp(buf, "writeback"))
2415 cache = 2;
2416 else {
2417 fprintf(stderr, "qemu: invalid cache option\n");
2418 return -1;
2422 if (get_param_value(buf, sizeof(buf), "format", str)) {
2423 if (strcmp(buf, "?") == 0) {
2424 fprintf(stderr, "qemu: Supported formats:");
2425 bdrv_iterate_format(bdrv_format_print, NULL);
2426 fprintf(stderr, "\n");
2427 return -1;
2429 drv = bdrv_find_format(buf);
2430 if (!drv) {
2431 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2432 return -1;
2436 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2437 if (!strcmp(buf, "on")) {
2438 if (extboot_drive != -1) {
2439 fprintf(stderr, "qemu: two bootable drives specified\n");
2440 return -1;
2442 extboot_drive = nb_drives;
2443 } else if (strcmp(buf, "off")) {
2444 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2445 return -1;
2449 if (arg->file == NULL)
2450 get_param_value(file, sizeof(file), "file", str);
2451 else
2452 pstrcpy(file, sizeof(file), arg->file);
2454 if (!get_param_value(serial, sizeof(serial), "serial", str))
2455 memset(serial, 0, sizeof(serial));
2457 onerror = BLOCK_ERR_STOP_ENOSPC;
2458 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2459 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2460 fprintf(stderr, "werror is no supported by this format\n");
2461 return -1;
2463 if (!strcmp(buf, "ignore"))
2464 onerror = BLOCK_ERR_IGNORE;
2465 else if (!strcmp(buf, "enospc"))
2466 onerror = BLOCK_ERR_STOP_ENOSPC;
2467 else if (!strcmp(buf, "stop"))
2468 onerror = BLOCK_ERR_STOP_ANY;
2469 else if (!strcmp(buf, "report"))
2470 onerror = BLOCK_ERR_REPORT;
2471 else {
2472 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2473 return -1;
2477 devaddr = NULL;
2478 if (get_param_value(buf, sizeof(buf), "addr", str)) {
2479 if (type != IF_VIRTIO) {
2480 fprintf(stderr, "addr is not supported by in '%s'\n", str);
2481 return -1;
2483 devaddr = strdup(buf);
2486 /* compute bus and unit according index */
2488 if (index != -1) {
2489 if (bus_id != 0 || unit_id != -1) {
2490 fprintf(stderr,
2491 "qemu: '%s' index cannot be used with bus and unit\n", str);
2492 return -1;
2494 if (max_devs == 0)
2496 unit_id = index;
2497 bus_id = 0;
2498 } else {
2499 unit_id = index % max_devs;
2500 bus_id = index / max_devs;
2504 /* if user doesn't specify a unit_id,
2505 * try to find the first free
2508 if (unit_id == -1) {
2509 unit_id = 0;
2510 while (drive_get_index(type, bus_id, unit_id) != -1) {
2511 unit_id++;
2512 if (max_devs && unit_id >= max_devs) {
2513 unit_id -= max_devs;
2514 bus_id++;
2519 /* check unit id */
2521 if (max_devs && unit_id >= max_devs) {
2522 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2523 str, unit_id, max_devs - 1);
2524 return -1;
2528 * ignore multiple definitions
2531 if (drive_get_index(type, bus_id, unit_id) != -1)
2532 return -2;
2534 /* init */
2536 if (type == IF_IDE || type == IF_SCSI)
2537 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2538 if (max_devs)
2539 snprintf(buf, sizeof(buf), "%s%i%s%i",
2540 devname, bus_id, mediastr, unit_id);
2541 else
2542 snprintf(buf, sizeof(buf), "%s%s%i",
2543 devname, mediastr, unit_id);
2544 bdrv = bdrv_new(buf);
2545 drives_table_idx = drive_get_free_idx();
2546 drives_table[drives_table_idx].bdrv = bdrv;
2547 drives_table[drives_table_idx].devaddr = devaddr;
2548 drives_table[drives_table_idx].type = type;
2549 drives_table[drives_table_idx].bus = bus_id;
2550 drives_table[drives_table_idx].unit = unit_id;
2551 drives_table[drives_table_idx].onerror = onerror;
2552 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2553 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2554 nb_drives++;
2556 switch(type) {
2557 case IF_IDE:
2558 case IF_SCSI:
2559 case IF_XEN:
2560 switch(media) {
2561 case MEDIA_DISK:
2562 if (cyls != 0) {
2563 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2564 bdrv_set_translation_hint(bdrv, translation);
2566 break;
2567 case MEDIA_CDROM:
2568 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2569 break;
2571 break;
2572 case IF_SD:
2573 /* FIXME: This isn't really a floppy, but it's a reasonable
2574 approximation. */
2575 case IF_FLOPPY:
2576 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2577 break;
2578 case IF_PFLASH:
2579 case IF_MTD:
2580 case IF_VIRTIO:
2581 break;
2582 case IF_COUNT:
2583 abort();
2585 if (!file[0])
2586 return -2;
2587 bdrv_flags = 0;
2588 if (snapshot) {
2589 bdrv_flags |= BDRV_O_SNAPSHOT;
2590 cache = 2; /* always use write-back with snapshot */
2592 if (cache == 0) /* no caching */
2593 bdrv_flags |= BDRV_O_NOCACHE;
2594 else if (cache == 2) /* write-back */
2595 bdrv_flags |= BDRV_O_CACHE_WB;
2596 else if (cache == 3) /* not specified */
2597 bdrv_flags |= BDRV_O_CACHE_DEF;
2598 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2599 fprintf(stderr, "qemu: could not open disk image %s\n",
2600 file);
2601 return -1;
2603 if (bdrv_key_required(bdrv))
2604 autostart = 0;
2605 return drives_table_idx;
2608 static void numa_add(const char *optarg)
2610 char option[128];
2611 char *endptr;
2612 unsigned long long value, endvalue;
2613 int nodenr;
2615 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2616 if (!strcmp(option, "node")) {
2617 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2618 nodenr = nb_numa_nodes;
2619 } else {
2620 nodenr = strtoull(option, NULL, 10);
2623 if (get_param_value(option, 128, "mem", optarg) == 0) {
2624 node_mem[nodenr] = 0;
2625 } else {
2626 value = strtoull(option, &endptr, 0);
2627 switch (*endptr) {
2628 case 0: case 'M': case 'm':
2629 value <<= 20;
2630 break;
2631 case 'G': case 'g':
2632 value <<= 30;
2633 break;
2635 node_mem[nodenr] = value;
2637 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2638 node_cpumask[nodenr] = 0;
2639 } else {
2640 value = strtoull(option, &endptr, 10);
2641 if (value >= 64) {
2642 value = 63;
2643 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2644 } else {
2645 if (*endptr == '-') {
2646 endvalue = strtoull(endptr+1, &endptr, 10);
2647 if (endvalue >= 63) {
2648 endvalue = 62;
2649 fprintf(stderr,
2650 "only 63 CPUs in NUMA mode supported.\n");
2652 value = (1 << (endvalue + 1)) - (1 << value);
2653 } else {
2654 value = 1 << value;
2657 node_cpumask[nodenr] = value;
2659 nb_numa_nodes++;
2661 return;
2664 /***********************************************************/
2665 /* USB devices */
2667 static USBPort *used_usb_ports;
2668 static USBPort *free_usb_ports;
2670 /* ??? Maybe change this to register a hub to keep track of the topology. */
2671 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2672 usb_attachfn attach)
2674 port->opaque = opaque;
2675 port->index = index;
2676 port->attach = attach;
2677 port->next = free_usb_ports;
2678 free_usb_ports = port;
2681 int usb_device_add_dev(USBDevice *dev)
2683 USBPort *port;
2685 /* Find a USB port to add the device to. */
2686 port = free_usb_ports;
2687 if (!port->next) {
2688 USBDevice *hub;
2690 /* Create a new hub and chain it on. */
2691 free_usb_ports = NULL;
2692 port->next = used_usb_ports;
2693 used_usb_ports = port;
2695 hub = usb_hub_init(VM_USB_HUB_SIZE);
2696 usb_attach(port, hub);
2697 port = free_usb_ports;
2700 free_usb_ports = port->next;
2701 port->next = used_usb_ports;
2702 used_usb_ports = port;
2703 usb_attach(port, dev);
2704 return 0;
2707 static void usb_msd_password_cb(void *opaque, int err)
2709 USBDevice *dev = opaque;
2711 if (!err)
2712 usb_device_add_dev(dev);
2713 else
2714 dev->handle_destroy(dev);
2717 static int usb_device_add(const char *devname, int is_hotplug)
2719 const char *p;
2720 USBDevice *dev;
2722 if (!free_usb_ports)
2723 return -1;
2725 if (strstart(devname, "host:", &p)) {
2726 dev = usb_host_device_open(p);
2727 } else if (!strcmp(devname, "mouse")) {
2728 dev = usb_mouse_init();
2729 } else if (!strcmp(devname, "tablet")) {
2730 dev = usb_tablet_init();
2731 } else if (!strcmp(devname, "keyboard")) {
2732 dev = usb_keyboard_init();
2733 } else if (strstart(devname, "disk:", &p)) {
2734 BlockDriverState *bs;
2736 dev = usb_msd_init(p);
2737 if (!dev)
2738 return -1;
2739 bs = usb_msd_get_bdrv(dev);
2740 if (bdrv_key_required(bs)) {
2741 autostart = 0;
2742 if (is_hotplug) {
2743 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2744 dev);
2745 return 0;
2748 } else if (!strcmp(devname, "wacom-tablet")) {
2749 dev = usb_wacom_init();
2750 } else if (strstart(devname, "serial:", &p)) {
2751 dev = usb_serial_init(p);
2752 #ifdef CONFIG_BRLAPI
2753 } else if (!strcmp(devname, "braille")) {
2754 dev = usb_baum_init();
2755 #endif
2756 } else if (strstart(devname, "net:", &p)) {
2757 int nic = nb_nics;
2759 if (net_client_init(NULL, "nic", p) < 0)
2760 return -1;
2761 nd_table[nic].model = "usb";
2762 dev = usb_net_init(&nd_table[nic]);
2763 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2764 dev = usb_bt_init(devname[2] ? hci_init(p) :
2765 bt_new_hci(qemu_find_bt_vlan(0)));
2766 } else {
2767 return -1;
2769 if (!dev)
2770 return -1;
2772 return usb_device_add_dev(dev);
2775 int usb_device_del_addr(int bus_num, int addr)
2777 USBPort *port;
2778 USBPort **lastp;
2779 USBDevice *dev;
2781 if (!used_usb_ports)
2782 return -1;
2784 if (bus_num != 0)
2785 return -1;
2787 lastp = &used_usb_ports;
2788 port = used_usb_ports;
2789 while (port && port->dev->addr != addr) {
2790 lastp = &port->next;
2791 port = port->next;
2794 if (!port)
2795 return -1;
2797 dev = port->dev;
2798 *lastp = port->next;
2799 usb_attach(port, NULL);
2800 dev->handle_destroy(dev);
2801 port->next = free_usb_ports;
2802 free_usb_ports = port;
2803 return 0;
2806 static int usb_device_del(const char *devname)
2808 int bus_num, addr;
2809 const char *p;
2811 if (strstart(devname, "host:", &p))
2812 return usb_host_device_close(p);
2814 if (!used_usb_ports)
2815 return -1;
2817 p = strchr(devname, '.');
2818 if (!p)
2819 return -1;
2820 bus_num = strtoul(devname, NULL, 0);
2821 addr = strtoul(p + 1, NULL, 0);
2823 return usb_device_del_addr(bus_num, addr);
2826 void do_usb_add(Monitor *mon, const char *devname)
2828 usb_device_add(devname, 1);
2831 void do_usb_del(Monitor *mon, const char *devname)
2833 usb_device_del(devname);
2836 void usb_info(Monitor *mon)
2838 USBDevice *dev;
2839 USBPort *port;
2840 const char *speed_str;
2842 if (!usb_enabled) {
2843 monitor_printf(mon, "USB support not enabled\n");
2844 return;
2847 for (port = used_usb_ports; port; port = port->next) {
2848 dev = port->dev;
2849 if (!dev)
2850 continue;
2851 switch(dev->speed) {
2852 case USB_SPEED_LOW:
2853 speed_str = "1.5";
2854 break;
2855 case USB_SPEED_FULL:
2856 speed_str = "12";
2857 break;
2858 case USB_SPEED_HIGH:
2859 speed_str = "480";
2860 break;
2861 default:
2862 speed_str = "?";
2863 break;
2865 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2866 0, dev->addr, speed_str, dev->devname);
2870 /***********************************************************/
2871 /* PCMCIA/Cardbus */
2873 static struct pcmcia_socket_entry_s {
2874 PCMCIASocket *socket;
2875 struct pcmcia_socket_entry_s *next;
2876 } *pcmcia_sockets = 0;
2878 void pcmcia_socket_register(PCMCIASocket *socket)
2880 struct pcmcia_socket_entry_s *entry;
2882 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2883 entry->socket = socket;
2884 entry->next = pcmcia_sockets;
2885 pcmcia_sockets = entry;
2888 void pcmcia_socket_unregister(PCMCIASocket *socket)
2890 struct pcmcia_socket_entry_s *entry, **ptr;
2892 ptr = &pcmcia_sockets;
2893 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2894 if (entry->socket == socket) {
2895 *ptr = entry->next;
2896 qemu_free(entry);
2900 void pcmcia_info(Monitor *mon)
2902 struct pcmcia_socket_entry_s *iter;
2904 if (!pcmcia_sockets)
2905 monitor_printf(mon, "No PCMCIA sockets\n");
2907 for (iter = pcmcia_sockets; iter; iter = iter->next)
2908 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2909 iter->socket->attached ? iter->socket->card_string :
2910 "Empty");
2913 /***********************************************************/
2914 /* register display */
2916 struct DisplayAllocator default_allocator = {
2917 defaultallocator_create_displaysurface,
2918 defaultallocator_resize_displaysurface,
2919 defaultallocator_free_displaysurface
2922 void register_displaystate(DisplayState *ds)
2924 DisplayState **s;
2925 s = &display_state;
2926 while (*s != NULL)
2927 s = &(*s)->next;
2928 ds->next = NULL;
2929 *s = ds;
2932 DisplayState *get_displaystate(void)
2934 return display_state;
2937 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2939 if(ds->allocator == &default_allocator) ds->allocator = da;
2940 return ds->allocator;
2943 /* dumb display */
2945 static void dumb_display_init(void)
2947 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2948 ds->allocator = &default_allocator;
2949 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2950 register_displaystate(ds);
2953 /***********************************************************/
2954 /* I/O handling */
2956 typedef struct IOHandlerRecord {
2957 int fd;
2958 IOCanRWHandler *fd_read_poll;
2959 IOHandler *fd_read;
2960 IOHandler *fd_write;
2961 int deleted;
2962 void *opaque;
2963 /* temporary data */
2964 struct pollfd *ufd;
2965 struct IOHandlerRecord *next;
2966 } IOHandlerRecord;
2968 static IOHandlerRecord *first_io_handler;
2970 /* XXX: fd_read_poll should be suppressed, but an API change is
2971 necessary in the character devices to suppress fd_can_read(). */
2972 int qemu_set_fd_handler2(int fd,
2973 IOCanRWHandler *fd_read_poll,
2974 IOHandler *fd_read,
2975 IOHandler *fd_write,
2976 void *opaque)
2978 IOHandlerRecord **pioh, *ioh;
2980 if (!fd_read && !fd_write) {
2981 pioh = &first_io_handler;
2982 for(;;) {
2983 ioh = *pioh;
2984 if (ioh == NULL)
2985 break;
2986 if (ioh->fd == fd) {
2987 ioh->deleted = 1;
2988 break;
2990 pioh = &ioh->next;
2992 } else {
2993 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2994 if (ioh->fd == fd)
2995 goto found;
2997 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2998 ioh->next = first_io_handler;
2999 first_io_handler = ioh;
3000 found:
3001 ioh->fd = fd;
3002 ioh->fd_read_poll = fd_read_poll;
3003 ioh->fd_read = fd_read;
3004 ioh->fd_write = fd_write;
3005 ioh->opaque = opaque;
3006 ioh->deleted = 0;
3008 qemu_notify_event();
3009 return 0;
3012 int qemu_set_fd_handler(int fd,
3013 IOHandler *fd_read,
3014 IOHandler *fd_write,
3015 void *opaque)
3017 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3020 #ifdef _WIN32
3021 /***********************************************************/
3022 /* Polling handling */
3024 typedef struct PollingEntry {
3025 PollingFunc *func;
3026 void *opaque;
3027 struct PollingEntry *next;
3028 } PollingEntry;
3030 static PollingEntry *first_polling_entry;
3032 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3034 PollingEntry **ppe, *pe;
3035 pe = qemu_mallocz(sizeof(PollingEntry));
3036 pe->func = func;
3037 pe->opaque = opaque;
3038 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3039 *ppe = pe;
3040 return 0;
3043 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3045 PollingEntry **ppe, *pe;
3046 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3047 pe = *ppe;
3048 if (pe->func == func && pe->opaque == opaque) {
3049 *ppe = pe->next;
3050 qemu_free(pe);
3051 break;
3056 /***********************************************************/
3057 /* Wait objects support */
3058 typedef struct WaitObjects {
3059 int num;
3060 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3061 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3062 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3063 } WaitObjects;
3065 static WaitObjects wait_objects = {0};
3067 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3069 WaitObjects *w = &wait_objects;
3071 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3072 return -1;
3073 w->events[w->num] = handle;
3074 w->func[w->num] = func;
3075 w->opaque[w->num] = opaque;
3076 w->num++;
3077 return 0;
3080 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3082 int i, found;
3083 WaitObjects *w = &wait_objects;
3085 found = 0;
3086 for (i = 0; i < w->num; i++) {
3087 if (w->events[i] == handle)
3088 found = 1;
3089 if (found) {
3090 w->events[i] = w->events[i + 1];
3091 w->func[i] = w->func[i + 1];
3092 w->opaque[i] = w->opaque[i + 1];
3095 if (found)
3096 w->num--;
3098 #endif
3100 /***********************************************************/
3101 /* ram save/restore */
3103 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3105 int v;
3107 v = qemu_get_byte(f);
3108 switch(v) {
3109 case 0:
3110 if (qemu_get_buffer(f, buf, len) != len)
3111 return -EIO;
3112 break;
3113 case 1:
3114 v = qemu_get_byte(f);
3115 memset(buf, v, len);
3116 break;
3117 default:
3118 return -EINVAL;
3121 if (qemu_file_has_error(f))
3122 return -EIO;
3124 return 0;
3127 static int ram_load_v1(QEMUFile *f, void *opaque)
3129 int ret;
3130 ram_addr_t i;
3132 if (qemu_get_be32(f) != last_ram_offset)
3133 return -EINVAL;
3134 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
3135 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3136 continue;
3137 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
3138 if (ret)
3139 return ret;
3141 return 0;
3144 #define BDRV_HASH_BLOCK_SIZE 1024
3145 #define IOBUF_SIZE 4096
3146 #define RAM_CBLOCK_MAGIC 0xfabe
3148 typedef struct RamDecompressState {
3149 z_stream zstream;
3150 QEMUFile *f;
3151 uint8_t buf[IOBUF_SIZE];
3152 } RamDecompressState;
3154 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3156 int ret;
3157 memset(s, 0, sizeof(*s));
3158 s->f = f;
3159 ret = inflateInit(&s->zstream);
3160 if (ret != Z_OK)
3161 return -1;
3162 return 0;
3165 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3167 int ret, clen;
3169 s->zstream.avail_out = len;
3170 s->zstream.next_out = buf;
3171 while (s->zstream.avail_out > 0) {
3172 if (s->zstream.avail_in == 0) {
3173 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3174 return -1;
3175 clen = qemu_get_be16(s->f);
3176 if (clen > IOBUF_SIZE)
3177 return -1;
3178 qemu_get_buffer(s->f, s->buf, clen);
3179 s->zstream.avail_in = clen;
3180 s->zstream.next_in = s->buf;
3182 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3183 if (ret != Z_OK && ret != Z_STREAM_END) {
3184 return -1;
3187 return 0;
3190 static void ram_decompress_close(RamDecompressState *s)
3192 inflateEnd(&s->zstream);
3195 #define RAM_SAVE_FLAG_FULL 0x01
3196 #define RAM_SAVE_FLAG_COMPRESS 0x02
3197 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3198 #define RAM_SAVE_FLAG_PAGE 0x08
3199 #define RAM_SAVE_FLAG_EOS 0x10
3201 static int is_dup_page(uint8_t *page, uint8_t ch)
3203 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3204 uint32_t *array = (uint32_t *)page;
3205 int i;
3207 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3208 if (array[i] != val)
3209 return 0;
3212 return 1;
3215 static int ram_save_block(QEMUFile *f)
3217 static ram_addr_t current_addr = 0;
3218 ram_addr_t saved_addr = current_addr;
3219 ram_addr_t addr = 0;
3220 int found = 0;
3222 while (addr < last_ram_offset) {
3223 if (kvm_enabled() && current_addr == 0) {
3224 int r;
3225 r = kvm_update_dirty_pages_log();
3226 if (r) {
3227 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3228 qemu_file_set_error(f);
3229 return 0;
3232 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3233 uint8_t *p;
3235 cpu_physical_memory_reset_dirty(current_addr,
3236 current_addr + TARGET_PAGE_SIZE,
3237 MIGRATION_DIRTY_FLAG);
3239 p = qemu_get_ram_ptr(current_addr);
3241 if (is_dup_page(p, *p)) {
3242 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3243 qemu_put_byte(f, *p);
3244 } else {
3245 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3246 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3249 found = 1;
3250 break;
3252 addr += TARGET_PAGE_SIZE;
3253 current_addr = (saved_addr + addr) % last_ram_offset;
3256 return found;
3259 static uint64_t bytes_transferred = 0;
3261 static ram_addr_t ram_save_remaining(void)
3263 ram_addr_t addr;
3264 ram_addr_t count = 0;
3266 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3267 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3268 count++;
3271 return count;
3274 uint64_t ram_bytes_remaining(void)
3276 return ram_save_remaining() * TARGET_PAGE_SIZE;
3279 uint64_t ram_bytes_transferred(void)
3281 return bytes_transferred;
3284 uint64_t ram_bytes_total(void)
3286 return last_ram_offset;
3289 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3291 ram_addr_t addr;
3292 uint64_t bytes_transferred_last;
3293 double bwidth = 0;
3294 uint64_t expected_time = 0;
3296 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3297 qemu_file_set_error(f);
3298 return 0;
3301 if (stage == 1) {
3302 /* Make sure all dirty bits are set */
3303 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3304 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3305 cpu_physical_memory_set_dirty(addr);
3308 /* Enable dirty memory tracking */
3309 cpu_physical_memory_set_dirty_tracking(1);
3311 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3314 bytes_transferred_last = bytes_transferred;
3315 bwidth = get_clock();
3317 while (!qemu_file_rate_limit(f)) {
3318 int ret;
3320 ret = ram_save_block(f);
3321 bytes_transferred += ret * TARGET_PAGE_SIZE;
3322 if (ret == 0) /* no more blocks */
3323 break;
3326 bwidth = get_clock() - bwidth;
3327 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3329 /* if we haven't transferred anything this round, force expected_time to a
3330 * a very high value, but without crashing */
3331 if (bwidth == 0)
3332 bwidth = 0.000001;
3334 /* try transferring iterative blocks of memory */
3336 if (stage == 3) {
3338 /* flush all remaining blocks regardless of rate limiting */
3339 while (ram_save_block(f) != 0) {
3340 bytes_transferred += TARGET_PAGE_SIZE;
3342 cpu_physical_memory_set_dirty_tracking(0);
3345 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3347 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3349 return (stage == 2) && (expected_time <= migrate_max_downtime());
3352 static int ram_load_dead(QEMUFile *f, void *opaque)
3354 RamDecompressState s1, *s = &s1;
3355 uint8_t buf[10];
3356 ram_addr_t i;
3358 if (ram_decompress_open(s, f) < 0)
3359 return -EINVAL;
3360 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3361 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3362 continue;
3363 if (ram_decompress_buf(s, buf, 1) < 0) {
3364 fprintf(stderr, "Error while reading ram block header\n");
3365 goto error;
3367 if (buf[0] == 0) {
3368 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3369 BDRV_HASH_BLOCK_SIZE) < 0) {
3370 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3371 goto error;
3373 } else {
3374 error:
3375 printf("Error block header\n");
3376 return -EINVAL;
3379 ram_decompress_close(s);
3381 return 0;
3384 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3386 ram_addr_t addr;
3387 int flags;
3389 if (version_id == 1)
3390 return ram_load_v1(f, opaque);
3392 if (version_id == 2) {
3393 if (qemu_get_be32(f) != last_ram_offset)
3394 return -EINVAL;
3395 return ram_load_dead(f, opaque);
3398 if (version_id != 3)
3399 return -EINVAL;
3401 do {
3402 addr = qemu_get_be64(f);
3404 flags = addr & ~TARGET_PAGE_MASK;
3405 addr &= TARGET_PAGE_MASK;
3407 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3408 if (addr != last_ram_offset)
3409 return -EINVAL;
3412 if (flags & RAM_SAVE_FLAG_FULL) {
3413 if (ram_load_dead(f, opaque) < 0)
3414 return -EINVAL;
3417 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3418 uint8_t ch = qemu_get_byte(f);
3419 #if defined(__linux__)
3420 if (ch == 0 &&
3421 (!kvm_enabled() || kvm_has_sync_mmu())) {
3422 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3423 } else
3424 #endif
3425 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3426 } else if (flags & RAM_SAVE_FLAG_PAGE)
3427 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3428 } while (!(flags & RAM_SAVE_FLAG_EOS));
3430 return 0;
3433 void qemu_service_io(void)
3435 qemu_notify_event();
3438 /***********************************************************/
3439 /* bottom halves (can be seen as timers which expire ASAP) */
3441 struct QEMUBH {
3442 QEMUBHFunc *cb;
3443 void *opaque;
3444 int scheduled;
3445 int idle;
3446 int deleted;
3447 QEMUBH *next;
3450 static QEMUBH *first_bh = NULL;
3452 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3454 QEMUBH *bh;
3455 bh = qemu_mallocz(sizeof(QEMUBH));
3456 bh->cb = cb;
3457 bh->opaque = opaque;
3458 bh->next = first_bh;
3459 first_bh = bh;
3460 return bh;
3463 int qemu_bh_poll(void)
3465 QEMUBH *bh, **bhp;
3466 int ret;
3468 ret = 0;
3469 for (bh = first_bh; bh; bh = bh->next) {
3470 if (!bh->deleted && bh->scheduled) {
3471 bh->scheduled = 0;
3472 if (!bh->idle)
3473 ret = 1;
3474 bh->idle = 0;
3475 bh->cb(bh->opaque);
3479 /* remove deleted bhs */
3480 bhp = &first_bh;
3481 while (*bhp) {
3482 bh = *bhp;
3483 if (bh->deleted) {
3484 *bhp = bh->next;
3485 qemu_free(bh);
3486 } else
3487 bhp = &bh->next;
3490 return ret;
3493 void qemu_bh_schedule_idle(QEMUBH *bh)
3495 if (bh->scheduled)
3496 return;
3497 bh->scheduled = 1;
3498 bh->idle = 1;
3501 void qemu_bh_schedule(QEMUBH *bh)
3503 if (bh->scheduled)
3504 return;
3505 bh->scheduled = 1;
3506 bh->idle = 0;
3507 /* stop the currently executing CPU to execute the BH ASAP */
3508 qemu_notify_event();
3511 void qemu_bh_cancel(QEMUBH *bh)
3513 bh->scheduled = 0;
3516 void qemu_bh_delete(QEMUBH *bh)
3518 bh->scheduled = 0;
3519 bh->deleted = 1;
3522 static void qemu_bh_update_timeout(int *timeout)
3524 QEMUBH *bh;
3526 for (bh = first_bh; bh; bh = bh->next) {
3527 if (!bh->deleted && bh->scheduled) {
3528 if (bh->idle) {
3529 /* idle bottom halves will be polled at least
3530 * every 10ms */
3531 *timeout = MIN(10, *timeout);
3532 } else {
3533 /* non-idle bottom halves will be executed
3534 * immediately */
3535 *timeout = 0;
3536 break;
3542 /***********************************************************/
3543 /* machine registration */
3545 static QEMUMachine *first_machine = NULL;
3546 QEMUMachine *current_machine = NULL;
3548 int qemu_register_machine(QEMUMachine *m)
3550 QEMUMachine **pm;
3551 pm = &first_machine;
3552 while (*pm != NULL)
3553 pm = &(*pm)->next;
3554 m->next = NULL;
3555 *pm = m;
3556 return 0;
3559 static QEMUMachine *find_machine(const char *name)
3561 QEMUMachine *m;
3563 for(m = first_machine; m != NULL; m = m->next) {
3564 if (!strcmp(m->name, name))
3565 return m;
3567 return NULL;
3570 static QEMUMachine *find_default_machine(void)
3572 QEMUMachine *m;
3574 for(m = first_machine; m != NULL; m = m->next) {
3575 if (m->is_default) {
3576 return m;
3579 return NULL;
3582 /***********************************************************/
3583 /* main execution loop */
3585 static void gui_update(void *opaque)
3587 uint64_t interval = GUI_REFRESH_INTERVAL;
3588 DisplayState *ds = opaque;
3589 DisplayChangeListener *dcl = ds->listeners;
3591 dpy_refresh(ds);
3593 while (dcl != NULL) {
3594 if (dcl->gui_timer_interval &&
3595 dcl->gui_timer_interval < interval)
3596 interval = dcl->gui_timer_interval;
3597 dcl = dcl->next;
3599 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3602 static void nographic_update(void *opaque)
3604 uint64_t interval = GUI_REFRESH_INTERVAL;
3606 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3609 struct vm_change_state_entry {
3610 VMChangeStateHandler *cb;
3611 void *opaque;
3612 LIST_ENTRY (vm_change_state_entry) entries;
3615 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3617 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3618 void *opaque)
3620 VMChangeStateEntry *e;
3622 e = qemu_mallocz(sizeof (*e));
3624 e->cb = cb;
3625 e->opaque = opaque;
3626 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3627 return e;
3630 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3632 LIST_REMOVE (e, entries);
3633 qemu_free (e);
3636 static void vm_state_notify(int running, int reason)
3638 VMChangeStateEntry *e;
3640 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3641 e->cb(e->opaque, running, reason);
3645 static void resume_all_vcpus(void);
3646 static void pause_all_vcpus(void);
3648 void vm_start(void)
3650 if (!vm_running) {
3651 cpu_enable_ticks();
3652 vm_running = 1;
3653 vm_state_notify(1, 0);
3654 qemu_rearm_alarm_timer(alarm_timer);
3655 resume_all_vcpus();
3659 /* reset/shutdown handler */
3661 typedef struct QEMUResetEntry {
3662 QEMUResetHandler *func;
3663 void *opaque;
3664 int order;
3665 struct QEMUResetEntry *next;
3666 } QEMUResetEntry;
3668 static QEMUResetEntry *first_reset_entry;
3669 static int reset_requested;
3670 static int shutdown_requested;
3671 static int powerdown_requested;
3672 static int debug_requested;
3673 static int vmstop_requested;
3675 int qemu_no_shutdown(void)
3677 int r = no_shutdown;
3678 no_shutdown = 0;
3679 return r;
3682 int qemu_shutdown_requested(void)
3684 int r = shutdown_requested;
3685 shutdown_requested = 0;
3686 return r;
3689 int qemu_reset_requested(void)
3691 int r = reset_requested;
3692 reset_requested = 0;
3693 return r;
3696 int qemu_powerdown_requested(void)
3698 int r = powerdown_requested;
3699 powerdown_requested = 0;
3700 return r;
3703 static int qemu_debug_requested(void)
3705 int r = debug_requested;
3706 debug_requested = 0;
3707 return r;
3710 static int qemu_vmstop_requested(void)
3712 int r = vmstop_requested;
3713 vmstop_requested = 0;
3714 return r;
3717 static void do_vm_stop(int reason)
3719 if (vm_running) {
3720 cpu_disable_ticks();
3721 vm_running = 0;
3722 pause_all_vcpus();
3723 vm_state_notify(0, reason);
3727 void qemu_register_reset(QEMUResetHandler *func, int order, void *opaque)
3729 QEMUResetEntry **pre, *re;
3731 pre = &first_reset_entry;
3732 while (*pre != NULL && (*pre)->order >= order) {
3733 pre = &(*pre)->next;
3735 re = qemu_mallocz(sizeof(QEMUResetEntry));
3736 re->func = func;
3737 re->opaque = opaque;
3738 re->order = order;
3739 re->next = NULL;
3740 *pre = re;
3743 void qemu_system_reset(void)
3745 QEMUResetEntry *re;
3747 /* reset all devices */
3748 for(re = first_reset_entry; re != NULL; re = re->next) {
3749 re->func(re->opaque);
3753 void qemu_system_reset_request(void)
3755 if (no_reboot) {
3756 shutdown_requested = 1;
3757 } else {
3758 reset_requested = 1;
3760 if (cpu_single_env) {
3761 qemu_kvm_cpu_stop(cpu_single_env);
3763 qemu_notify_event();
3766 void qemu_system_shutdown_request(void)
3768 shutdown_requested = 1;
3769 qemu_notify_event();
3772 void qemu_system_powerdown_request(void)
3774 powerdown_requested = 1;
3775 qemu_notify_event();
3778 #ifdef CONFIG_IOTHREAD
3779 static void qemu_system_vmstop_request(int reason)
3781 vmstop_requested = reason;
3782 qemu_notify_event();
3784 #endif
3786 #ifndef _WIN32
3787 static int io_thread_fd = -1;
3789 static void qemu_event_increment(void)
3791 static const char byte = 0;
3793 if (io_thread_fd == -1)
3794 return;
3796 write(io_thread_fd, &byte, sizeof(byte));
3799 static void qemu_event_read(void *opaque)
3801 int fd = (unsigned long)opaque;
3802 ssize_t len;
3804 /* Drain the notify pipe */
3805 do {
3806 char buffer[512];
3807 len = read(fd, buffer, sizeof(buffer));
3808 } while ((len == -1 && errno == EINTR) || len > 0);
3811 static int qemu_event_init(void)
3813 int err;
3814 int fds[2];
3816 err = pipe(fds);
3817 if (err == -1)
3818 return -errno;
3820 err = fcntl_setfl(fds[0], O_NONBLOCK);
3821 if (err < 0)
3822 goto fail;
3824 err = fcntl_setfl(fds[1], O_NONBLOCK);
3825 if (err < 0)
3826 goto fail;
3828 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3829 (void *)(unsigned long)fds[0]);
3831 io_thread_fd = fds[1];
3832 return 0;
3834 fail:
3835 close(fds[0]);
3836 close(fds[1]);
3837 return err;
3839 #else
3840 HANDLE qemu_event_handle;
3842 static void dummy_event_handler(void *opaque)
3846 static int qemu_event_init(void)
3848 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3849 if (!qemu_event_handle) {
3850 perror("Failed CreateEvent");
3851 return -1;
3853 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3854 return 0;
3857 static void qemu_event_increment(void)
3859 SetEvent(qemu_event_handle);
3861 #endif
3863 static int cpu_can_run(CPUState *env)
3865 if (env->stop)
3866 return 0;
3867 if (env->stopped)
3868 return 0;
3869 return 1;
3872 #ifndef CONFIG_IOTHREAD
3873 static int qemu_init_main_loop(void)
3875 return qemu_event_init();
3878 void qemu_init_vcpu(void *_env)
3880 CPUState *env = _env;
3882 if (kvm_enabled())
3883 kvm_init_vcpu(env);
3884 return;
3887 int qemu_cpu_self(void *env)
3889 return 1;
3892 static void resume_all_vcpus(void)
3896 static void pause_all_vcpus(void)
3900 void qemu_cpu_kick(void *env)
3902 return;
3905 void qemu_notify_event(void)
3907 CPUState *env = cpu_single_env;
3909 if (kvm_enabled()) {
3910 qemu_kvm_notify_work();
3911 return;
3913 if (env) {
3914 cpu_exit(env);
3915 #ifdef USE_KQEMU
3916 if (env->kqemu_enabled)
3917 kqemu_cpu_interrupt(env);
3918 #endif
3922 #define qemu_mutex_lock_iothread() do { } while (0)
3923 #define qemu_mutex_unlock_iothread() do { } while (0)
3925 void vm_stop(int reason)
3927 do_vm_stop(reason);
3930 #else /* CONFIG_IOTHREAD */
3932 #include "qemu-thread.h"
3934 QemuMutex qemu_global_mutex;
3935 static QemuMutex qemu_fair_mutex;
3937 static QemuThread io_thread;
3939 static QemuThread *tcg_cpu_thread;
3940 static QemuCond *tcg_halt_cond;
3942 static int qemu_system_ready;
3943 /* cpu creation */
3944 static QemuCond qemu_cpu_cond;
3945 /* system init */
3946 static QemuCond qemu_system_cond;
3947 static QemuCond qemu_pause_cond;
3949 static void block_io_signals(void);
3950 static void unblock_io_signals(void);
3951 static int tcg_has_work(void);
3953 static int qemu_init_main_loop(void)
3955 int ret;
3957 ret = qemu_event_init();
3958 if (ret)
3959 return ret;
3961 qemu_cond_init(&qemu_pause_cond);
3962 qemu_mutex_init(&qemu_fair_mutex);
3963 qemu_mutex_init(&qemu_global_mutex);
3964 qemu_mutex_lock(&qemu_global_mutex);
3966 unblock_io_signals();
3967 qemu_thread_self(&io_thread);
3969 return 0;
3972 static void qemu_wait_io_event(CPUState *env)
3974 while (!tcg_has_work())
3975 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3977 qemu_mutex_unlock(&qemu_global_mutex);
3980 * Users of qemu_global_mutex can be starved, having no chance
3981 * to acquire it since this path will get to it first.
3982 * So use another lock to provide fairness.
3984 qemu_mutex_lock(&qemu_fair_mutex);
3985 qemu_mutex_unlock(&qemu_fair_mutex);
3987 qemu_mutex_lock(&qemu_global_mutex);
3988 if (env->stop) {
3989 env->stop = 0;
3990 env->stopped = 1;
3991 qemu_cond_signal(&qemu_pause_cond);
3995 static int qemu_cpu_exec(CPUState *env);
3997 static void *kvm_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 env->created = 1;
4007 qemu_cond_signal(&qemu_cpu_cond);
4009 /* and wait for machine initialization */
4010 while (!qemu_system_ready)
4011 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
4013 while (1) {
4014 if (cpu_can_run(env))
4015 qemu_cpu_exec(env);
4016 qemu_wait_io_event(env);
4019 return NULL;
4022 static void tcg_cpu_exec(void);
4024 static void *tcg_cpu_thread_fn(void *arg)
4026 CPUState *env = arg;
4028 block_io_signals();
4029 qemu_thread_self(env->thread);
4031 /* signal CPU creation */
4032 qemu_mutex_lock(&qemu_global_mutex);
4033 for (env = first_cpu; env != NULL; env = env->next_cpu)
4034 env->created = 1;
4035 qemu_cond_signal(&qemu_cpu_cond);
4037 /* and wait for machine initialization */
4038 while (!qemu_system_ready)
4039 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
4041 while (1) {
4042 tcg_cpu_exec();
4043 qemu_wait_io_event(cur_cpu);
4046 return NULL;
4049 void qemu_cpu_kick(void *_env)
4051 CPUState *env = _env;
4052 qemu_cond_broadcast(env->halt_cond);
4053 if (kvm_enabled())
4054 qemu_thread_signal(env->thread, SIGUSR1);
4057 int qemu_cpu_self(void *env)
4059 return (cpu_single_env != NULL);
4062 static void cpu_signal(int sig)
4064 if (cpu_single_env)
4065 cpu_exit(cpu_single_env);
4068 static void block_io_signals(void)
4070 sigset_t set;
4071 struct sigaction sigact;
4073 sigemptyset(&set);
4074 sigaddset(&set, SIGUSR2);
4075 sigaddset(&set, SIGIO);
4076 sigaddset(&set, SIGALRM);
4077 pthread_sigmask(SIG_BLOCK, &set, NULL);
4079 sigemptyset(&set);
4080 sigaddset(&set, SIGUSR1);
4081 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4083 memset(&sigact, 0, sizeof(sigact));
4084 sigact.sa_handler = cpu_signal;
4085 sigaction(SIGUSR1, &sigact, NULL);
4088 static void unblock_io_signals(void)
4090 sigset_t set;
4092 sigemptyset(&set);
4093 sigaddset(&set, SIGUSR2);
4094 sigaddset(&set, SIGIO);
4095 sigaddset(&set, SIGALRM);
4096 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4098 sigemptyset(&set);
4099 sigaddset(&set, SIGUSR1);
4100 pthread_sigmask(SIG_BLOCK, &set, NULL);
4103 static void qemu_signal_lock(unsigned int msecs)
4105 qemu_mutex_lock(&qemu_fair_mutex);
4107 while (qemu_mutex_trylock(&qemu_global_mutex)) {
4108 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
4109 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
4110 break;
4112 qemu_mutex_unlock(&qemu_fair_mutex);
4115 static void qemu_mutex_lock_iothread(void)
4117 if (kvm_enabled()) {
4118 qemu_mutex_lock(&qemu_fair_mutex);
4119 qemu_mutex_lock(&qemu_global_mutex);
4120 qemu_mutex_unlock(&qemu_fair_mutex);
4121 } else
4122 qemu_signal_lock(100);
4125 static void qemu_mutex_unlock_iothread(void)
4127 qemu_mutex_unlock(&qemu_global_mutex);
4130 static int all_vcpus_paused(void)
4132 CPUState *penv = first_cpu;
4134 while (penv) {
4135 if (!penv->stopped)
4136 return 0;
4137 penv = (CPUState *)penv->next_cpu;
4140 return 1;
4143 static void pause_all_vcpus(void)
4145 CPUState *penv = first_cpu;
4147 while (penv) {
4148 penv->stop = 1;
4149 qemu_thread_signal(penv->thread, SIGUSR1);
4150 qemu_cpu_kick(penv);
4151 penv = (CPUState *)penv->next_cpu;
4154 while (!all_vcpus_paused()) {
4155 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
4156 penv = first_cpu;
4157 while (penv) {
4158 qemu_thread_signal(penv->thread, SIGUSR1);
4159 penv = (CPUState *)penv->next_cpu;
4164 static void resume_all_vcpus(void)
4166 CPUState *penv = first_cpu;
4168 while (penv) {
4169 penv->stop = 0;
4170 penv->stopped = 0;
4171 qemu_thread_signal(penv->thread, SIGUSR1);
4172 qemu_cpu_kick(penv);
4173 penv = (CPUState *)penv->next_cpu;
4177 static void tcg_init_vcpu(void *_env)
4179 CPUState *env = _env;
4180 /* share a single thread for all cpus with TCG */
4181 if (!tcg_cpu_thread) {
4182 env->thread = qemu_mallocz(sizeof(QemuThread));
4183 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4184 qemu_cond_init(env->halt_cond);
4185 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
4186 while (env->created == 0)
4187 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4188 tcg_cpu_thread = env->thread;
4189 tcg_halt_cond = env->halt_cond;
4190 } else {
4191 env->thread = tcg_cpu_thread;
4192 env->halt_cond = tcg_halt_cond;
4196 static void kvm_start_vcpu(CPUState *env)
4198 kvm_init_vcpu(env);
4199 env->thread = qemu_mallocz(sizeof(QemuThread));
4200 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4201 qemu_cond_init(env->halt_cond);
4202 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
4203 while (env->created == 0)
4204 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4207 void qemu_init_vcpu(void *_env)
4209 CPUState *env = _env;
4211 if (kvm_enabled())
4212 kvm_start_vcpu(env);
4213 else
4214 tcg_init_vcpu(env);
4217 void qemu_notify_event(void)
4219 qemu_event_increment();
4222 void vm_stop(int reason)
4224 QemuThread me;
4225 qemu_thread_self(&me);
4227 if (!qemu_thread_equal(&me, &io_thread)) {
4228 qemu_system_vmstop_request(reason);
4230 * FIXME: should not return to device code in case
4231 * vm_stop() has been requested.
4233 if (cpu_single_env) {
4234 cpu_exit(cpu_single_env);
4235 cpu_single_env->stop = 1;
4237 return;
4239 do_vm_stop(reason);
4242 #endif
4245 #ifdef _WIN32
4246 static void host_main_loop_wait(int *timeout)
4248 int ret, ret2, i;
4249 PollingEntry *pe;
4252 /* XXX: need to suppress polling by better using win32 events */
4253 ret = 0;
4254 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4255 ret |= pe->func(pe->opaque);
4257 if (ret == 0) {
4258 int err;
4259 WaitObjects *w = &wait_objects;
4261 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4262 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4263 if (w->func[ret - WAIT_OBJECT_0])
4264 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4266 /* Check for additional signaled events */
4267 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4269 /* Check if event is signaled */
4270 ret2 = WaitForSingleObject(w->events[i], 0);
4271 if(ret2 == WAIT_OBJECT_0) {
4272 if (w->func[i])
4273 w->func[i](w->opaque[i]);
4274 } else if (ret2 == WAIT_TIMEOUT) {
4275 } else {
4276 err = GetLastError();
4277 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4280 } else if (ret == WAIT_TIMEOUT) {
4281 } else {
4282 err = GetLastError();
4283 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4287 *timeout = 0;
4289 #else
4290 static void host_main_loop_wait(int *timeout)
4293 #endif
4295 void main_loop_wait(int timeout)
4297 IOHandlerRecord *ioh;
4298 fd_set rfds, wfds, xfds;
4299 int ret, nfds;
4300 struct timeval tv;
4302 qemu_bh_update_timeout(&timeout);
4304 host_main_loop_wait(&timeout);
4306 /* poll any events */
4307 /* XXX: separate device handlers from system ones */
4308 nfds = -1;
4309 FD_ZERO(&rfds);
4310 FD_ZERO(&wfds);
4311 FD_ZERO(&xfds);
4312 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4313 if (ioh->deleted)
4314 continue;
4315 if (ioh->fd_read &&
4316 (!ioh->fd_read_poll ||
4317 ioh->fd_read_poll(ioh->opaque) != 0)) {
4318 FD_SET(ioh->fd, &rfds);
4319 if (ioh->fd > nfds)
4320 nfds = ioh->fd;
4322 if (ioh->fd_write) {
4323 FD_SET(ioh->fd, &wfds);
4324 if (ioh->fd > nfds)
4325 nfds = ioh->fd;
4329 tv.tv_sec = timeout / 1000;
4330 tv.tv_usec = (timeout % 1000) * 1000;
4332 #if defined(CONFIG_SLIRP)
4333 if (slirp_is_inited()) {
4334 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4336 #endif
4337 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4338 if (ret > 0) {
4339 IOHandlerRecord **pioh;
4341 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4342 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4343 ioh->fd_read(ioh->opaque);
4344 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
4345 FD_CLR(ioh->fd, &rfds);
4347 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4348 ioh->fd_write(ioh->opaque);
4352 /* remove deleted IO handlers */
4353 pioh = &first_io_handler;
4354 while (*pioh) {
4355 ioh = *pioh;
4356 if (ioh->deleted) {
4357 *pioh = ioh->next;
4358 qemu_free(ioh);
4359 } else
4360 pioh = &ioh->next;
4363 #if defined(CONFIG_SLIRP)
4364 if (slirp_is_inited()) {
4365 if (ret < 0) {
4366 FD_ZERO(&rfds);
4367 FD_ZERO(&wfds);
4368 FD_ZERO(&xfds);
4370 slirp_select_poll(&rfds, &wfds, &xfds);
4372 #endif
4374 /* rearm timer, if not periodic */
4375 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4376 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4377 qemu_rearm_alarm_timer(alarm_timer);
4380 /* vm time timers */
4381 if (vm_running) {
4382 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4383 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4384 qemu_get_clock(vm_clock));
4387 /* real time timers */
4388 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4389 qemu_get_clock(rt_clock));
4391 /* Check bottom-halves last in case any of the earlier events triggered
4392 them. */
4393 qemu_bh_poll();
4397 static int qemu_cpu_exec(CPUState *env)
4399 int ret;
4400 #ifdef CONFIG_PROFILER
4401 int64_t ti;
4402 #endif
4404 #ifdef CONFIG_PROFILER
4405 ti = profile_getclock();
4406 #endif
4407 if (use_icount) {
4408 int64_t count;
4409 int decr;
4410 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4411 env->icount_decr.u16.low = 0;
4412 env->icount_extra = 0;
4413 count = qemu_next_deadline();
4414 count = (count + (1 << icount_time_shift) - 1)
4415 >> icount_time_shift;
4416 qemu_icount += count;
4417 decr = (count > 0xffff) ? 0xffff : count;
4418 count -= decr;
4419 env->icount_decr.u16.low = decr;
4420 env->icount_extra = count;
4422 ret = cpu_exec(env);
4423 #ifdef CONFIG_PROFILER
4424 qemu_time += profile_getclock() - ti;
4425 #endif
4426 if (use_icount) {
4427 /* Fold pending instructions back into the
4428 instruction counter, and clear the interrupt flag. */
4429 qemu_icount -= (env->icount_decr.u16.low
4430 + env->icount_extra);
4431 env->icount_decr.u32 = 0;
4432 env->icount_extra = 0;
4434 return ret;
4437 static void tcg_cpu_exec(void)
4439 int ret = 0;
4441 if (next_cpu == NULL)
4442 next_cpu = first_cpu;
4443 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4444 CPUState *env = cur_cpu = next_cpu;
4446 if (!vm_running)
4447 break;
4448 if (timer_alarm_pending) {
4449 timer_alarm_pending = 0;
4450 break;
4452 if (cpu_can_run(env))
4453 ret = qemu_cpu_exec(env);
4454 if (ret == EXCP_DEBUG) {
4455 gdb_set_stop_cpu(env);
4456 debug_requested = 1;
4457 break;
4462 static int cpu_has_work(CPUState *env)
4464 if (env->stop)
4465 return 1;
4466 if (env->stopped)
4467 return 0;
4468 if (!env->halted)
4469 return 1;
4470 if (qemu_cpu_has_work(env))
4471 return 1;
4472 return 0;
4475 static int tcg_has_work(void)
4477 CPUState *env;
4479 for (env = first_cpu; env != NULL; env = env->next_cpu)
4480 if (cpu_has_work(env))
4481 return 1;
4482 return 0;
4485 static int qemu_calculate_timeout(void)
4487 #ifndef CONFIG_IOTHREAD
4488 int timeout;
4490 if (!vm_running)
4491 timeout = 5000;
4492 else if (tcg_has_work())
4493 timeout = 0;
4494 else if (!use_icount)
4495 timeout = 5000;
4496 else {
4497 /* XXX: use timeout computed from timers */
4498 int64_t add;
4499 int64_t delta;
4500 /* Advance virtual time to the next event. */
4501 if (use_icount == 1) {
4502 /* When not using an adaptive execution frequency
4503 we tend to get badly out of sync with real time,
4504 so just delay for a reasonable amount of time. */
4505 delta = 0;
4506 } else {
4507 delta = cpu_get_icount() - cpu_get_clock();
4509 if (delta > 0) {
4510 /* If virtual time is ahead of real time then just
4511 wait for IO. */
4512 timeout = (delta / 1000000) + 1;
4513 } else {
4514 /* Wait for either IO to occur or the next
4515 timer event. */
4516 add = qemu_next_deadline();
4517 /* We advance the timer before checking for IO.
4518 Limit the amount we advance so that early IO
4519 activity won't get the guest too far ahead. */
4520 if (add > 10000000)
4521 add = 10000000;
4522 delta += add;
4523 add = (add + (1 << icount_time_shift) - 1)
4524 >> icount_time_shift;
4525 qemu_icount += add;
4526 timeout = delta / 1000000;
4527 if (timeout < 0)
4528 timeout = 0;
4532 return timeout;
4533 #else /* CONFIG_IOTHREAD */
4534 return 1000;
4535 #endif
4538 static int vm_can_run(void)
4540 if (powerdown_requested)
4541 return 0;
4542 if (reset_requested)
4543 return 0;
4544 if (shutdown_requested)
4545 return 0;
4546 if (debug_requested)
4547 return 0;
4548 return 1;
4551 static void main_loop(void)
4553 int r;
4555 if (kvm_enabled()) {
4556 kvm_main_loop();
4557 cpu_disable_ticks();
4558 return;
4561 #ifdef CONFIG_IOTHREAD
4562 qemu_system_ready = 1;
4563 qemu_cond_broadcast(&qemu_system_cond);
4564 #endif
4566 for (;;) {
4567 do {
4568 #ifdef CONFIG_PROFILER
4569 int64_t ti;
4570 #endif
4571 #ifndef CONFIG_IOTHREAD
4572 tcg_cpu_exec();
4573 #endif
4574 #ifdef CONFIG_PROFILER
4575 ti = profile_getclock();
4576 #endif
4577 main_loop_wait(qemu_calculate_timeout());
4578 #ifdef CONFIG_PROFILER
4579 dev_time += profile_getclock() - ti;
4580 #endif
4581 } while (vm_can_run());
4583 if (qemu_debug_requested())
4584 vm_stop(EXCP_DEBUG);
4585 if (qemu_shutdown_requested()) {
4586 if (no_shutdown) {
4587 vm_stop(0);
4588 no_shutdown = 0;
4589 } else
4590 break;
4592 if (qemu_reset_requested()) {
4593 pause_all_vcpus();
4594 qemu_system_reset();
4595 resume_all_vcpus();
4597 if (qemu_powerdown_requested())
4598 qemu_system_powerdown();
4599 if ((r = qemu_vmstop_requested()))
4600 vm_stop(r);
4602 pause_all_vcpus();
4605 static void version(void)
4607 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4610 static void help(int exitcode)
4612 version();
4613 printf("usage: %s [options] [disk_image]\n"
4614 "\n"
4615 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4616 "\n"
4617 #define DEF(option, opt_arg, opt_enum, opt_help) \
4618 opt_help
4619 #define DEFHEADING(text) stringify(text) "\n"
4620 #include "qemu-options.h"
4621 #undef DEF
4622 #undef DEFHEADING
4623 #undef GEN_DOCS
4624 "\n"
4625 "During emulation, the following keys are useful:\n"
4626 "ctrl-alt-f toggle full screen\n"
4627 "ctrl-alt-n switch to virtual console 'n'\n"
4628 "ctrl-alt toggle mouse and keyboard grab\n"
4629 "\n"
4630 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4632 "qemu",
4633 DEFAULT_RAM_SIZE,
4634 #ifndef _WIN32
4635 DEFAULT_NETWORK_SCRIPT,
4636 DEFAULT_NETWORK_DOWN_SCRIPT,
4637 #endif
4638 DEFAULT_GDBSTUB_PORT,
4639 "/tmp/qemu.log");
4640 exit(exitcode);
4643 #define HAS_ARG 0x0001
4645 enum {
4646 #define DEF(option, opt_arg, opt_enum, opt_help) \
4647 opt_enum,
4648 #define DEFHEADING(text)
4649 #include "qemu-options.h"
4650 #undef DEF
4651 #undef DEFHEADING
4652 #undef GEN_DOCS
4655 typedef struct QEMUOption {
4656 const char *name;
4657 int flags;
4658 int index;
4659 } QEMUOption;
4661 static const QEMUOption qemu_options[] = {
4662 { "h", 0, QEMU_OPTION_h },
4663 #define DEF(option, opt_arg, opt_enum, opt_help) \
4664 { option, opt_arg, opt_enum },
4665 #define DEFHEADING(text)
4666 #include "qemu-options.h"
4667 #undef DEF
4668 #undef DEFHEADING
4669 #undef GEN_DOCS
4670 { NULL },
4673 #ifdef HAS_AUDIO
4674 struct soundhw soundhw[] = {
4675 #ifdef HAS_AUDIO_CHOICE
4676 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4678 "pcspk",
4679 "PC speaker",
4682 { .init_isa = pcspk_audio_init }
4684 #endif
4686 #ifdef CONFIG_SB16
4688 "sb16",
4689 "Creative Sound Blaster 16",
4692 { .init_isa = SB16_init }
4694 #endif
4696 #ifdef CONFIG_CS4231A
4698 "cs4231a",
4699 "CS4231A",
4702 { .init_isa = cs4231a_init }
4704 #endif
4706 #ifdef CONFIG_ADLIB
4708 "adlib",
4709 #ifdef HAS_YMF262
4710 "Yamaha YMF262 (OPL3)",
4711 #else
4712 "Yamaha YM3812 (OPL2)",
4713 #endif
4716 { .init_isa = Adlib_init }
4718 #endif
4720 #ifdef CONFIG_GUS
4722 "gus",
4723 "Gravis Ultrasound GF1",
4726 { .init_isa = GUS_init }
4728 #endif
4730 #ifdef CONFIG_AC97
4732 "ac97",
4733 "Intel 82801AA AC97 Audio",
4736 { .init_pci = ac97_init }
4738 #endif
4740 #ifdef CONFIG_ES1370
4742 "es1370",
4743 "ENSONIQ AudioPCI ES1370",
4746 { .init_pci = es1370_init }
4748 #endif
4750 #endif /* HAS_AUDIO_CHOICE */
4752 { NULL, NULL, 0, 0, { NULL } }
4755 static void select_soundhw (const char *optarg)
4757 struct soundhw *c;
4759 if (*optarg == '?') {
4760 show_valid_cards:
4762 printf ("Valid sound card names (comma separated):\n");
4763 for (c = soundhw; c->name; ++c) {
4764 printf ("%-11s %s\n", c->name, c->descr);
4766 printf ("\n-soundhw all will enable all of the above\n");
4767 exit (*optarg != '?');
4769 else {
4770 size_t l;
4771 const char *p;
4772 char *e;
4773 int bad_card = 0;
4775 if (!strcmp (optarg, "all")) {
4776 for (c = soundhw; c->name; ++c) {
4777 c->enabled = 1;
4779 return;
4782 p = optarg;
4783 while (*p) {
4784 e = strchr (p, ',');
4785 l = !e ? strlen (p) : (size_t) (e - p);
4787 for (c = soundhw; c->name; ++c) {
4788 if (!strncmp (c->name, p, l)) {
4789 c->enabled = 1;
4790 break;
4794 if (!c->name) {
4795 if (l > 80) {
4796 fprintf (stderr,
4797 "Unknown sound card name (too big to show)\n");
4799 else {
4800 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4801 (int) l, p);
4803 bad_card = 1;
4805 p += l + (e != NULL);
4808 if (bad_card)
4809 goto show_valid_cards;
4812 #endif
4814 static void select_vgahw (const char *p)
4816 const char *opts;
4818 cirrus_vga_enabled = 0;
4819 std_vga_enabled = 0;
4820 vmsvga_enabled = 0;
4821 xenfb_enabled = 0;
4822 if (strstart(p, "std", &opts)) {
4823 std_vga_enabled = 1;
4824 } else if (strstart(p, "cirrus", &opts)) {
4825 cirrus_vga_enabled = 1;
4826 } else if (strstart(p, "vmware", &opts)) {
4827 vmsvga_enabled = 1;
4828 } else if (strstart(p, "xenfb", &opts)) {
4829 xenfb_enabled = 1;
4830 } else if (!strstart(p, "none", &opts)) {
4831 invalid_vga:
4832 fprintf(stderr, "Unknown vga type: %s\n", p);
4833 exit(1);
4835 while (*opts) {
4836 const char *nextopt;
4838 if (strstart(opts, ",retrace=", &nextopt)) {
4839 opts = nextopt;
4840 if (strstart(opts, "dumb", &nextopt))
4841 vga_retrace_method = VGA_RETRACE_DUMB;
4842 else if (strstart(opts, "precise", &nextopt))
4843 vga_retrace_method = VGA_RETRACE_PRECISE;
4844 else goto invalid_vga;
4845 } else goto invalid_vga;
4846 opts = nextopt;
4850 #ifdef _WIN32
4851 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4853 exit(STATUS_CONTROL_C_EXIT);
4854 return TRUE;
4856 #endif
4858 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4860 int ret;
4862 if(strlen(str) != 36)
4863 return -1;
4865 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4866 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4867 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4869 if(ret != 16)
4870 return -1;
4872 #ifdef TARGET_I386
4873 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4874 #endif
4876 return 0;
4879 #define MAX_NET_CLIENTS 32
4881 #ifndef _WIN32
4883 static void termsig_handler(int signal)
4885 qemu_system_shutdown_request();
4888 static void sigchld_handler(int signal)
4890 waitpid(-1, NULL, WNOHANG);
4893 static void sighandler_setup(void)
4895 struct sigaction act;
4897 memset(&act, 0, sizeof(act));
4898 act.sa_handler = termsig_handler;
4899 sigaction(SIGINT, &act, NULL);
4900 sigaction(SIGHUP, &act, NULL);
4901 sigaction(SIGTERM, &act, NULL);
4903 act.sa_handler = sigchld_handler;
4904 act.sa_flags = SA_NOCLDSTOP;
4905 sigaction(SIGCHLD, &act, NULL);
4908 #endif
4910 #ifdef _WIN32
4911 /* Look for support files in the same directory as the executable. */
4912 static char *find_datadir(const char *argv0)
4914 char *p;
4915 char buf[MAX_PATH];
4916 DWORD len;
4918 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4919 if (len == 0) {
4920 return NULL;
4923 buf[len] = 0;
4924 p = buf + len - 1;
4925 while (p != buf && *p != '\\')
4926 p--;
4927 *p = 0;
4928 if (access(buf, R_OK) == 0) {
4929 return qemu_strdup(buf);
4931 return NULL;
4933 #else /* !_WIN32 */
4935 /* Find a likely location for support files using the location of the binary.
4936 For installed binaries this will be "$bindir/../share/qemu". When
4937 running from the build tree this will be "$bindir/../pc-bios". */
4938 #define SHARE_SUFFIX "/share/qemu"
4939 #define BUILD_SUFFIX "/pc-bios"
4940 static char *find_datadir(const char *argv0)
4942 char *dir;
4943 char *p = NULL;
4944 char *res;
4945 #ifdef PATH_MAX
4946 char buf[PATH_MAX];
4947 #endif
4948 size_t max_len;
4950 #if defined(__linux__)
4952 int len;
4953 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4954 if (len > 0) {
4955 buf[len] = 0;
4956 p = buf;
4959 #elif defined(__FreeBSD__)
4961 int len;
4962 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4963 if (len > 0) {
4964 buf[len] = 0;
4965 p = buf;
4968 #endif
4969 /* If we don't have any way of figuring out the actual executable
4970 location then try argv[0]. */
4971 if (!p) {
4972 #ifdef PATH_MAX
4973 p = buf;
4974 #endif
4975 p = realpath(argv0, p);
4976 if (!p) {
4977 return NULL;
4980 dir = dirname(p);
4981 dir = dirname(dir);
4983 max_len = strlen(dir) +
4984 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4985 res = qemu_mallocz(max_len);
4986 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4987 if (access(res, R_OK)) {
4988 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4989 if (access(res, R_OK)) {
4990 qemu_free(res);
4991 res = NULL;
4994 #ifndef PATH_MAX
4995 free(p);
4996 #endif
4997 return res;
4999 #undef SHARE_SUFFIX
5000 #undef BUILD_SUFFIX
5001 #endif
5003 char *qemu_find_file(int type, const char *name)
5005 int len;
5006 const char *subdir;
5007 char *buf;
5009 /* If name contains path separators then try it as a straight path. */
5010 if ((strchr(name, '/') || strchr(name, '\\'))
5011 && access(name, R_OK) == 0) {
5012 return strdup(name);
5014 switch (type) {
5015 case QEMU_FILE_TYPE_BIOS:
5016 subdir = "";
5017 break;
5018 case QEMU_FILE_TYPE_KEYMAP:
5019 subdir = "keymaps/";
5020 break;
5021 default:
5022 abort();
5024 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
5025 buf = qemu_mallocz(len);
5026 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
5027 if (access(buf, R_OK)) {
5028 qemu_free(buf);
5029 return NULL;
5031 return buf;
5034 int main(int argc, char **argv, char **envp)
5036 const char *gdbstub_dev = NULL;
5037 uint32_t boot_devices_bitmap = 0;
5038 int i;
5039 int snapshot, linux_boot, net_boot;
5040 const char *initrd_filename;
5041 const char *kernel_filename, *kernel_cmdline;
5042 const char *boot_devices = "";
5043 DisplayState *ds;
5044 DisplayChangeListener *dcl;
5045 int cyls, heads, secs, translation;
5046 const char *net_clients[MAX_NET_CLIENTS];
5047 int nb_net_clients;
5048 const char *bt_opts[MAX_BT_CMDLINE];
5049 int nb_bt_opts;
5050 int hda_index;
5051 int optind;
5052 const char *r, *optarg;
5053 CharDriverState *monitor_hd = NULL;
5054 const char *monitor_device;
5055 const char *serial_devices[MAX_SERIAL_PORTS];
5056 int serial_device_index;
5057 const char *parallel_devices[MAX_PARALLEL_PORTS];
5058 int parallel_device_index;
5059 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
5060 int virtio_console_index;
5061 const char *loadvm = NULL;
5062 QEMUMachine *machine;
5063 const char *cpu_model;
5064 const char *usb_devices[MAX_USB_CMDLINE];
5065 int usb_devices_index;
5066 #ifndef _WIN32
5067 int fds[2];
5068 #endif
5069 int tb_size;
5070 const char *pid_file = NULL;
5071 const char *incoming = NULL;
5072 #ifndef _WIN32
5073 int fd = 0;
5074 struct passwd *pwd = NULL;
5075 const char *chroot_dir = NULL;
5076 const char *run_as = NULL;
5077 #endif
5078 CPUState *env;
5079 int show_vnc_port = 0;
5081 qemu_cache_utils_init(envp);
5083 LIST_INIT (&vm_change_state_head);
5084 #ifndef _WIN32
5086 struct sigaction act;
5087 sigfillset(&act.sa_mask);
5088 act.sa_flags = 0;
5089 act.sa_handler = SIG_IGN;
5090 sigaction(SIGPIPE, &act, NULL);
5092 #else
5093 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5094 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5095 QEMU to run on a single CPU */
5097 HANDLE h;
5098 DWORD mask, smask;
5099 int i;
5100 h = GetCurrentProcess();
5101 if (GetProcessAffinityMask(h, &mask, &smask)) {
5102 for(i = 0; i < 32; i++) {
5103 if (mask & (1 << i))
5104 break;
5106 if (i != 32) {
5107 mask = 1 << i;
5108 SetProcessAffinityMask(h, mask);
5112 #endif
5114 module_call_init(MODULE_INIT_MACHINE);
5115 machine = find_default_machine();
5116 cpu_model = NULL;
5117 initrd_filename = NULL;
5118 ram_size = 0;
5119 snapshot = 0;
5120 kernel_filename = NULL;
5121 kernel_cmdline = "";
5122 cyls = heads = secs = 0;
5123 translation = BIOS_ATA_TRANSLATION_AUTO;
5124 monitor_device = "vc:80Cx24C";
5126 serial_devices[0] = "vc:80Cx24C";
5127 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5128 serial_devices[i] = NULL;
5129 serial_device_index = 0;
5131 parallel_devices[0] = "vc:80Cx24C";
5132 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5133 parallel_devices[i] = NULL;
5134 parallel_device_index = 0;
5136 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
5137 virtio_consoles[i] = NULL;
5138 virtio_console_index = 0;
5140 for (i = 0; i < MAX_NODES; i++) {
5141 node_mem[i] = 0;
5142 node_cpumask[i] = 0;
5145 usb_devices_index = 0;
5146 assigned_devices_index = 0;
5148 nb_net_clients = 0;
5149 nb_bt_opts = 0;
5150 nb_drives = 0;
5151 nb_drives_opt = 0;
5152 nb_numa_nodes = 0;
5153 hda_index = -1;
5155 nb_nics = 0;
5157 tb_size = 0;
5158 autostart= 1;
5160 register_watchdogs();
5162 optind = 1;
5163 for(;;) {
5164 if (optind >= argc)
5165 break;
5166 r = argv[optind];
5167 if (r[0] != '-') {
5168 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5169 } else {
5170 const QEMUOption *popt;
5172 optind++;
5173 /* Treat --foo the same as -foo. */
5174 if (r[1] == '-')
5175 r++;
5176 popt = qemu_options;
5177 for(;;) {
5178 if (!popt->name) {
5179 fprintf(stderr, "%s: invalid option -- '%s'\n",
5180 argv[0], r);
5181 exit(1);
5183 if (!strcmp(popt->name, r + 1))
5184 break;
5185 popt++;
5187 if (popt->flags & HAS_ARG) {
5188 if (optind >= argc) {
5189 fprintf(stderr, "%s: option '%s' requires an argument\n",
5190 argv[0], r);
5191 exit(1);
5193 optarg = argv[optind++];
5194 } else {
5195 optarg = NULL;
5198 switch(popt->index) {
5199 case QEMU_OPTION_M:
5200 machine = find_machine(optarg);
5201 if (!machine) {
5202 QEMUMachine *m;
5203 printf("Supported machines are:\n");
5204 for(m = first_machine; m != NULL; m = m->next) {
5205 printf("%-10s %s%s\n",
5206 m->name, m->desc,
5207 m->is_default ? " (default)" : "");
5209 exit(*optarg != '?');
5211 break;
5212 case QEMU_OPTION_cpu:
5213 /* hw initialization will check this */
5214 if (*optarg == '?') {
5215 /* XXX: implement xxx_cpu_list for targets that still miss it */
5216 #if defined(cpu_list)
5217 cpu_list(stdout, &fprintf);
5218 #endif
5219 exit(0);
5220 } else {
5221 cpu_model = optarg;
5223 break;
5224 case QEMU_OPTION_initrd:
5225 initrd_filename = optarg;
5226 break;
5227 case QEMU_OPTION_hda:
5228 if (cyls == 0)
5229 hda_index = drive_add(optarg, HD_ALIAS, 0);
5230 else
5231 hda_index = drive_add(optarg, HD_ALIAS
5232 ",cyls=%d,heads=%d,secs=%d%s",
5233 0, cyls, heads, secs,
5234 translation == BIOS_ATA_TRANSLATION_LBA ?
5235 ",trans=lba" :
5236 translation == BIOS_ATA_TRANSLATION_NONE ?
5237 ",trans=none" : "");
5238 break;
5239 case QEMU_OPTION_hdb:
5240 case QEMU_OPTION_hdc:
5241 case QEMU_OPTION_hdd:
5242 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5243 break;
5244 case QEMU_OPTION_drive:
5245 drive_add(NULL, "%s", optarg);
5246 break;
5247 case QEMU_OPTION_mtdblock:
5248 drive_add(optarg, MTD_ALIAS);
5249 break;
5250 case QEMU_OPTION_sd:
5251 drive_add(optarg, SD_ALIAS);
5252 break;
5253 case QEMU_OPTION_pflash:
5254 drive_add(optarg, PFLASH_ALIAS);
5255 break;
5256 case QEMU_OPTION_snapshot:
5257 snapshot = 1;
5258 break;
5259 case QEMU_OPTION_hdachs:
5261 const char *p;
5262 p = optarg;
5263 cyls = strtol(p, (char **)&p, 0);
5264 if (cyls < 1 || cyls > 16383)
5265 goto chs_fail;
5266 if (*p != ',')
5267 goto chs_fail;
5268 p++;
5269 heads = strtol(p, (char **)&p, 0);
5270 if (heads < 1 || heads > 16)
5271 goto chs_fail;
5272 if (*p != ',')
5273 goto chs_fail;
5274 p++;
5275 secs = strtol(p, (char **)&p, 0);
5276 if (secs < 1 || secs > 63)
5277 goto chs_fail;
5278 if (*p == ',') {
5279 p++;
5280 if (!strcmp(p, "none"))
5281 translation = BIOS_ATA_TRANSLATION_NONE;
5282 else if (!strcmp(p, "lba"))
5283 translation = BIOS_ATA_TRANSLATION_LBA;
5284 else if (!strcmp(p, "auto"))
5285 translation = BIOS_ATA_TRANSLATION_AUTO;
5286 else
5287 goto chs_fail;
5288 } else if (*p != '\0') {
5289 chs_fail:
5290 fprintf(stderr, "qemu: invalid physical CHS format\n");
5291 exit(1);
5293 if (hda_index != -1)
5294 snprintf(drives_opt[hda_index].opt,
5295 sizeof(drives_opt[hda_index].opt),
5296 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5297 0, cyls, heads, secs,
5298 translation == BIOS_ATA_TRANSLATION_LBA ?
5299 ",trans=lba" :
5300 translation == BIOS_ATA_TRANSLATION_NONE ?
5301 ",trans=none" : "");
5303 break;
5304 case QEMU_OPTION_numa:
5305 if (nb_numa_nodes >= MAX_NODES) {
5306 fprintf(stderr, "qemu: too many NUMA nodes\n");
5307 exit(1);
5309 numa_add(optarg);
5310 break;
5311 case QEMU_OPTION_nographic:
5312 display_type = DT_NOGRAPHIC;
5313 break;
5314 #ifdef CONFIG_CURSES
5315 case QEMU_OPTION_curses:
5316 display_type = DT_CURSES;
5317 break;
5318 #endif
5319 case QEMU_OPTION_portrait:
5320 graphic_rotate = 1;
5321 break;
5322 case QEMU_OPTION_kernel:
5323 kernel_filename = optarg;
5324 break;
5325 case QEMU_OPTION_append:
5326 kernel_cmdline = optarg;
5327 break;
5328 case QEMU_OPTION_cdrom:
5329 drive_add(optarg, CDROM_ALIAS);
5330 break;
5331 case QEMU_OPTION_boot:
5332 boot_devices = optarg;
5333 /* We just do some generic consistency checks */
5335 /* Could easily be extended to 64 devices if needed */
5336 const char *p;
5338 boot_devices_bitmap = 0;
5339 for (p = boot_devices; *p != '\0'; p++) {
5340 /* Allowed boot devices are:
5341 * a b : floppy disk drives
5342 * c ... f : IDE disk drives
5343 * g ... m : machine implementation dependant drives
5344 * n ... p : network devices
5345 * It's up to each machine implementation to check
5346 * if the given boot devices match the actual hardware
5347 * implementation and firmware features.
5349 if (*p < 'a' || *p > 'q') {
5350 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5351 exit(1);
5353 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5354 fprintf(stderr,
5355 "Boot device '%c' was given twice\n",*p);
5356 exit(1);
5358 boot_devices_bitmap |= 1 << (*p - 'a');
5361 break;
5362 case QEMU_OPTION_fda:
5363 case QEMU_OPTION_fdb:
5364 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5365 break;
5366 #ifdef TARGET_I386
5367 case QEMU_OPTION_no_fd_bootchk:
5368 fd_bootchk = 0;
5369 break;
5370 #endif
5371 case QEMU_OPTION_net:
5372 if (nb_net_clients >= MAX_NET_CLIENTS) {
5373 fprintf(stderr, "qemu: too many network clients\n");
5374 exit(1);
5376 net_clients[nb_net_clients] = optarg;
5377 nb_net_clients++;
5378 break;
5379 #ifdef CONFIG_SLIRP
5380 case QEMU_OPTION_tftp:
5381 tftp_prefix = optarg;
5382 break;
5383 case QEMU_OPTION_bootp:
5384 bootp_filename = optarg;
5385 break;
5386 #ifndef _WIN32
5387 case QEMU_OPTION_smb:
5388 net_slirp_smb(optarg);
5389 break;
5390 #endif
5391 case QEMU_OPTION_redir:
5392 net_slirp_redir(NULL, optarg, NULL);
5393 break;
5394 #endif
5395 case QEMU_OPTION_bt:
5396 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5397 fprintf(stderr, "qemu: too many bluetooth options\n");
5398 exit(1);
5400 bt_opts[nb_bt_opts++] = optarg;
5401 break;
5402 #ifdef HAS_AUDIO
5403 case QEMU_OPTION_audio_help:
5404 AUD_help ();
5405 exit (0);
5406 break;
5407 case QEMU_OPTION_soundhw:
5408 select_soundhw (optarg);
5409 break;
5410 #endif
5411 case QEMU_OPTION_h:
5412 help(0);
5413 break;
5414 case QEMU_OPTION_version:
5415 version();
5416 exit(0);
5417 break;
5418 case QEMU_OPTION_m: {
5419 uint64_t value;
5420 char *ptr;
5422 value = strtoul(optarg, &ptr, 10);
5423 switch (*ptr) {
5424 case 0: case 'M': case 'm':
5425 value <<= 20;
5426 break;
5427 case 'G': case 'g':
5428 value <<= 30;
5429 break;
5430 default:
5431 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5432 exit(1);
5435 /* On 32-bit hosts, QEMU is limited by virtual address space */
5436 if (value > (2047 << 20)
5437 #ifndef CONFIG_KQEMU
5438 && HOST_LONG_BITS == 32
5439 #endif
5441 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5442 exit(1);
5444 if (value != (uint64_t)(ram_addr_t)value) {
5445 fprintf(stderr, "qemu: ram size too large\n");
5446 exit(1);
5448 ram_size = value;
5449 break;
5451 case QEMU_OPTION_d:
5453 int mask;
5454 const CPULogItem *item;
5456 mask = cpu_str_to_log_mask(optarg);
5457 if (!mask) {
5458 printf("Log items (comma separated):\n");
5459 for(item = cpu_log_items; item->mask != 0; item++) {
5460 printf("%-10s %s\n", item->name, item->help);
5462 exit(1);
5464 cpu_set_log(mask);
5466 break;
5467 case QEMU_OPTION_s:
5468 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5469 break;
5470 case QEMU_OPTION_gdb:
5471 gdbstub_dev = optarg;
5472 break;
5473 case QEMU_OPTION_L:
5474 data_dir = optarg;
5475 break;
5476 case QEMU_OPTION_bios:
5477 bios_name = optarg;
5478 break;
5479 case QEMU_OPTION_singlestep:
5480 singlestep = 1;
5481 break;
5482 case QEMU_OPTION_S:
5483 autostart = 0;
5484 break;
5485 #ifndef _WIN32
5486 case QEMU_OPTION_k:
5487 keyboard_layout = optarg;
5488 break;
5489 #endif
5490 case QEMU_OPTION_localtime:
5491 rtc_utc = 0;
5492 break;
5493 case QEMU_OPTION_vga:
5494 select_vgahw (optarg);
5495 break;
5496 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5497 case QEMU_OPTION_g:
5499 const char *p;
5500 int w, h, depth;
5501 p = optarg;
5502 w = strtol(p, (char **)&p, 10);
5503 if (w <= 0) {
5504 graphic_error:
5505 fprintf(stderr, "qemu: invalid resolution or depth\n");
5506 exit(1);
5508 if (*p != 'x')
5509 goto graphic_error;
5510 p++;
5511 h = strtol(p, (char **)&p, 10);
5512 if (h <= 0)
5513 goto graphic_error;
5514 if (*p == 'x') {
5515 p++;
5516 depth = strtol(p, (char **)&p, 10);
5517 if (depth != 8 && depth != 15 && depth != 16 &&
5518 depth != 24 && depth != 32)
5519 goto graphic_error;
5520 } else if (*p == '\0') {
5521 depth = graphic_depth;
5522 } else {
5523 goto graphic_error;
5526 graphic_width = w;
5527 graphic_height = h;
5528 graphic_depth = depth;
5530 break;
5531 #endif
5532 case QEMU_OPTION_echr:
5534 char *r;
5535 term_escape_char = strtol(optarg, &r, 0);
5536 if (r == optarg)
5537 printf("Bad argument to echr\n");
5538 break;
5540 case QEMU_OPTION_monitor:
5541 monitor_device = optarg;
5542 break;
5543 case QEMU_OPTION_serial:
5544 if (serial_device_index >= MAX_SERIAL_PORTS) {
5545 fprintf(stderr, "qemu: too many serial ports\n");
5546 exit(1);
5548 serial_devices[serial_device_index] = optarg;
5549 serial_device_index++;
5550 break;
5551 case QEMU_OPTION_watchdog:
5552 i = select_watchdog(optarg);
5553 if (i > 0)
5554 exit (i == 1 ? 1 : 0);
5555 break;
5556 case QEMU_OPTION_watchdog_action:
5557 if (select_watchdog_action(optarg) == -1) {
5558 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5559 exit(1);
5561 break;
5562 case QEMU_OPTION_virtiocon:
5563 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5564 fprintf(stderr, "qemu: too many virtio consoles\n");
5565 exit(1);
5567 virtio_consoles[virtio_console_index] = optarg;
5568 virtio_console_index++;
5569 break;
5570 case QEMU_OPTION_parallel:
5571 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5572 fprintf(stderr, "qemu: too many parallel ports\n");
5573 exit(1);
5575 parallel_devices[parallel_device_index] = optarg;
5576 parallel_device_index++;
5577 break;
5578 case QEMU_OPTION_loadvm:
5579 loadvm = optarg;
5580 break;
5581 case QEMU_OPTION_full_screen:
5582 full_screen = 1;
5583 break;
5584 #ifdef CONFIG_SDL
5585 case QEMU_OPTION_no_frame:
5586 no_frame = 1;
5587 break;
5588 case QEMU_OPTION_alt_grab:
5589 alt_grab = 1;
5590 break;
5591 case QEMU_OPTION_no_quit:
5592 no_quit = 1;
5593 break;
5594 case QEMU_OPTION_sdl:
5595 display_type = DT_SDL;
5596 break;
5597 #endif
5598 case QEMU_OPTION_pidfile:
5599 pid_file = optarg;
5600 break;
5601 #ifdef TARGET_I386
5602 case QEMU_OPTION_win2k_hack:
5603 win2k_install_hack = 1;
5604 break;
5605 case QEMU_OPTION_rtc_td_hack:
5606 rtc_td_hack = 1;
5607 break;
5608 case QEMU_OPTION_acpitable:
5609 if(acpi_table_add(optarg) < 0) {
5610 fprintf(stderr, "Wrong acpi table provided\n");
5611 exit(1);
5613 break;
5614 case QEMU_OPTION_smbios:
5615 if(smbios_entry_add(optarg) < 0) {
5616 fprintf(stderr, "Wrong smbios provided\n");
5617 exit(1);
5619 break;
5620 #endif
5621 #ifdef CONFIG_KQEMU
5622 case QEMU_OPTION_no_kqemu:
5623 kqemu_allowed = 0;
5624 break;
5625 case QEMU_OPTION_kernel_kqemu:
5626 kqemu_allowed = 2;
5627 break;
5628 #endif
5629 #ifdef CONFIG_KVM
5630 case QEMU_OPTION_enable_kvm:
5631 kvm_allowed = 1;
5632 #ifdef CONFIG_KQEMU
5633 kqemu_allowed = 0;
5634 #endif
5635 break;
5636 #endif
5637 #ifdef USE_KVM
5638 case QEMU_OPTION_no_kvm:
5639 kvm_allowed = 0;
5640 break;
5641 case QEMU_OPTION_no_kvm_irqchip: {
5642 kvm_irqchip = 0;
5643 kvm_pit = 0;
5644 break;
5646 case QEMU_OPTION_no_kvm_pit: {
5647 kvm_pit = 0;
5648 break;
5650 case QEMU_OPTION_no_kvm_pit_reinjection: {
5651 kvm_pit_reinject = 0;
5652 break;
5654 case QEMU_OPTION_enable_nesting: {
5655 kvm_nested = 1;
5656 break;
5658 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5659 case QEMU_OPTION_pcidevice:
5660 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5661 fprintf(stderr, "Too many assigned devices\n");
5662 exit(1);
5664 assigned_devices[assigned_devices_index] = optarg;
5665 assigned_devices_index++;
5666 break;
5667 #endif
5668 #endif
5669 case QEMU_OPTION_usb:
5670 usb_enabled = 1;
5671 break;
5672 case QEMU_OPTION_usbdevice:
5673 usb_enabled = 1;
5674 if (usb_devices_index >= MAX_USB_CMDLINE) {
5675 fprintf(stderr, "Too many USB devices\n");
5676 exit(1);
5678 usb_devices[usb_devices_index] = optarg;
5679 usb_devices_index++;
5680 break;
5681 case QEMU_OPTION_smp:
5682 smp_cpus = atoi(optarg);
5683 if (smp_cpus < 1) {
5684 fprintf(stderr, "Invalid number of CPUs\n");
5685 exit(1);
5687 break;
5688 case QEMU_OPTION_vnc:
5689 display_type = DT_VNC;
5690 vnc_display = optarg;
5691 break;
5692 #ifdef TARGET_I386
5693 case QEMU_OPTION_no_acpi:
5694 acpi_enabled = 0;
5695 break;
5696 case QEMU_OPTION_no_hpet:
5697 no_hpet = 1;
5698 break;
5699 case QEMU_OPTION_no_virtio_balloon:
5700 no_virtio_balloon = 1;
5701 break;
5702 #endif
5703 case QEMU_OPTION_no_reboot:
5704 no_reboot = 1;
5705 break;
5706 case QEMU_OPTION_no_shutdown:
5707 no_shutdown = 1;
5708 break;
5709 case QEMU_OPTION_show_cursor:
5710 cursor_hide = 0;
5711 break;
5712 case QEMU_OPTION_uuid:
5713 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5714 fprintf(stderr, "Fail to parse UUID string."
5715 " Wrong format.\n");
5716 exit(1);
5718 break;
5719 #ifndef _WIN32
5720 case QEMU_OPTION_daemonize:
5721 daemonize = 1;
5722 break;
5723 #endif
5724 case QEMU_OPTION_option_rom:
5725 if (nb_option_roms >= MAX_OPTION_ROMS) {
5726 fprintf(stderr, "Too many option ROMs\n");
5727 exit(1);
5729 option_rom[nb_option_roms] = optarg;
5730 nb_option_roms++;
5731 break;
5732 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5733 case QEMU_OPTION_semihosting:
5734 semihosting_enabled = 1;
5735 break;
5736 #endif
5737 case QEMU_OPTION_tdf:
5738 time_drift_fix = 1;
5739 break;
5740 case QEMU_OPTION_kvm_shadow_memory:
5741 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5742 break;
5743 case QEMU_OPTION_mempath:
5744 mem_path = optarg;
5745 break;
5746 #ifdef MAP_POPULATE
5747 case QEMU_OPTION_mem_prealloc:
5748 mem_prealloc = !mem_prealloc;
5749 break;
5750 #endif
5751 case QEMU_OPTION_name:
5752 qemu_name = optarg;
5753 break;
5754 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5755 case QEMU_OPTION_prom_env:
5756 if (nb_prom_envs >= MAX_PROM_ENVS) {
5757 fprintf(stderr, "Too many prom variables\n");
5758 exit(1);
5760 prom_envs[nb_prom_envs] = optarg;
5761 nb_prom_envs++;
5762 break;
5763 #endif
5764 #ifdef TARGET_ARM
5765 case QEMU_OPTION_old_param:
5766 old_param = 1;
5767 break;
5768 #endif
5769 case QEMU_OPTION_clock:
5770 configure_alarms(optarg);
5771 break;
5772 case QEMU_OPTION_startdate:
5774 struct tm tm;
5775 time_t rtc_start_date;
5776 if (!strcmp(optarg, "now")) {
5777 rtc_date_offset = -1;
5778 } else {
5779 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5780 &tm.tm_year,
5781 &tm.tm_mon,
5782 &tm.tm_mday,
5783 &tm.tm_hour,
5784 &tm.tm_min,
5785 &tm.tm_sec) == 6) {
5786 /* OK */
5787 } else if (sscanf(optarg, "%d-%d-%d",
5788 &tm.tm_year,
5789 &tm.tm_mon,
5790 &tm.tm_mday) == 3) {
5791 tm.tm_hour = 0;
5792 tm.tm_min = 0;
5793 tm.tm_sec = 0;
5794 } else {
5795 goto date_fail;
5797 tm.tm_year -= 1900;
5798 tm.tm_mon--;
5799 rtc_start_date = mktimegm(&tm);
5800 if (rtc_start_date == -1) {
5801 date_fail:
5802 fprintf(stderr, "Invalid date format. Valid format are:\n"
5803 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5804 exit(1);
5806 rtc_date_offset = time(NULL) - rtc_start_date;
5809 break;
5810 case QEMU_OPTION_tb_size:
5811 tb_size = strtol(optarg, NULL, 0);
5812 if (tb_size < 0)
5813 tb_size = 0;
5814 break;
5815 case QEMU_OPTION_icount:
5816 use_icount = 1;
5817 if (strcmp(optarg, "auto") == 0) {
5818 icount_time_shift = -1;
5819 } else {
5820 icount_time_shift = strtol(optarg, NULL, 0);
5822 break;
5823 case QEMU_OPTION_incoming:
5824 incoming = optarg;
5825 break;
5826 #ifndef _WIN32
5827 case QEMU_OPTION_chroot:
5828 chroot_dir = optarg;
5829 break;
5830 case QEMU_OPTION_runas:
5831 run_as = optarg;
5832 break;
5833 case QEMU_OPTION_nvram:
5834 nvram = optarg;
5835 break;
5836 #endif
5837 #ifdef CONFIG_XEN
5838 case QEMU_OPTION_xen_domid:
5839 xen_domid = atoi(optarg);
5840 break;
5841 case QEMU_OPTION_xen_create:
5842 xen_mode = XEN_CREATE;
5843 break;
5844 case QEMU_OPTION_xen_attach:
5845 xen_mode = XEN_ATTACH;
5846 break;
5847 #endif
5852 /* If no data_dir is specified then try to find it relative to the
5853 executable path. */
5854 if (!data_dir) {
5855 data_dir = find_datadir(argv[0]);
5857 /* If all else fails use the install patch specified when building. */
5858 if (!data_dir) {
5859 data_dir = CONFIG_QEMU_SHAREDIR;
5862 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5863 if (kvm_allowed && kqemu_allowed) {
5864 fprintf(stderr,
5865 "You can not enable both KVM and kqemu at the same time\n");
5866 exit(1);
5868 #endif
5870 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5871 if (smp_cpus > machine->max_cpus) {
5872 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5873 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5874 machine->max_cpus);
5875 exit(1);
5878 if (display_type == DT_NOGRAPHIC) {
5879 if (serial_device_index == 0)
5880 serial_devices[0] = "stdio";
5881 if (parallel_device_index == 0)
5882 parallel_devices[0] = "null";
5883 if (strncmp(monitor_device, "vc", 2) == 0)
5884 monitor_device = "stdio";
5887 #ifndef _WIN32
5888 if (daemonize) {
5889 pid_t pid;
5891 if (pipe(fds) == -1)
5892 exit(1);
5894 pid = fork();
5895 if (pid > 0) {
5896 uint8_t status;
5897 ssize_t len;
5899 close(fds[1]);
5901 again:
5902 len = read(fds[0], &status, 1);
5903 if (len == -1 && (errno == EINTR))
5904 goto again;
5906 if (len != 1)
5907 exit(1);
5908 else if (status == 1) {
5909 fprintf(stderr, "Could not acquire pidfile\n");
5910 exit(1);
5911 } else
5912 exit(0);
5913 } else if (pid < 0)
5914 exit(1);
5916 setsid();
5918 pid = fork();
5919 if (pid > 0)
5920 exit(0);
5921 else if (pid < 0)
5922 exit(1);
5924 umask(027);
5926 signal(SIGTSTP, SIG_IGN);
5927 signal(SIGTTOU, SIG_IGN);
5928 signal(SIGTTIN, SIG_IGN);
5931 #ifdef USE_KVM
5932 if (kvm_enabled()) {
5933 if (kvm_qemu_init() < 0) {
5934 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5935 #ifdef NO_CPU_EMULATION
5936 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5937 exit(1);
5938 #endif
5939 kvm_allowed = 0;
5942 #endif
5944 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5945 if (daemonize) {
5946 uint8_t status = 1;
5947 write(fds[1], &status, 1);
5948 } else
5949 fprintf(stderr, "Could not acquire pid file\n");
5950 exit(1);
5952 #endif
5954 #ifdef CONFIG_KQEMU
5955 if (smp_cpus > 1)
5956 kqemu_allowed = 0;
5957 #endif
5958 if (qemu_init_main_loop()) {
5959 fprintf(stderr, "qemu_init_main_loop failed\n");
5960 exit(1);
5962 linux_boot = (kernel_filename != NULL);
5964 if (!linux_boot && *kernel_cmdline != '\0') {
5965 fprintf(stderr, "-append only allowed with -kernel option\n");
5966 exit(1);
5969 if (!linux_boot && initrd_filename != NULL) {
5970 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5971 exit(1);
5974 /* boot to floppy or the default cd if no hard disk defined yet */
5975 if (!boot_devices[0]) {
5976 boot_devices = "cad";
5978 setvbuf(stdout, NULL, _IOLBF, 0);
5980 init_timers();
5981 if (init_timer_alarm() < 0) {
5982 fprintf(stderr, "could not initialize alarm timer\n");
5983 exit(1);
5985 if (use_icount && icount_time_shift < 0) {
5986 use_icount = 2;
5987 /* 125MIPS seems a reasonable initial guess at the guest speed.
5988 It will be corrected fairly quickly anyway. */
5989 icount_time_shift = 3;
5990 init_icount_adjust();
5993 #ifdef _WIN32
5994 socket_init();
5995 #endif
5997 /* init network clients */
5998 if (nb_net_clients == 0) {
5999 /* if no clients, we use a default config */
6000 net_clients[nb_net_clients++] = "nic";
6001 #ifdef CONFIG_SLIRP
6002 net_clients[nb_net_clients++] = "user";
6003 #endif
6006 for(i = 0;i < nb_net_clients; i++) {
6007 if (net_client_parse(net_clients[i]) < 0)
6008 exit(1);
6011 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
6012 net_set_boot_mask(net_boot);
6014 net_client_check();
6016 /* init the bluetooth world */
6017 for (i = 0; i < nb_bt_opts; i++)
6018 if (bt_parse(bt_opts[i]))
6019 exit(1);
6021 /* init the memory */
6022 if (ram_size == 0)
6023 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6025 if (kvm_enabled()) {
6026 if (kvm_qemu_create_context() < 0) {
6027 fprintf(stderr, "Could not create KVM context\n");
6028 exit(1);
6032 #ifdef CONFIG_KQEMU
6033 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
6034 guest ram allocation. It needs to go away. */
6035 if (kqemu_allowed) {
6036 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
6037 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
6038 if (!kqemu_phys_ram_base) {
6039 fprintf(stderr, "Could not allocate physical memory\n");
6040 exit(1);
6043 #endif
6045 /* init the dynamic translator */
6046 cpu_exec_init_all(tb_size * 1024 * 1024);
6048 bdrv_init();
6050 /* we always create the cdrom drive, even if no disk is there */
6052 if (nb_drives_opt < MAX_DRIVES)
6053 drive_add(NULL, CDROM_ALIAS);
6055 /* we always create at least one floppy */
6057 if (nb_drives_opt < MAX_DRIVES)
6058 drive_add(NULL, FD_ALIAS, 0);
6060 /* we always create one sd slot, even if no card is in it */
6062 if (nb_drives_opt < MAX_DRIVES)
6063 drive_add(NULL, SD_ALIAS);
6065 /* open the virtual block devices
6066 * note that migration with device
6067 * hot add/remove is broken.
6069 for(i = 0; i < nb_drives_opt; i++)
6070 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
6071 exit(1);
6073 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6074 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
6076 #ifndef _WIN32
6077 /* must be after terminal init, SDL library changes signal handlers */
6078 sighandler_setup();
6079 #endif
6081 /* Maintain compatibility with multiple stdio monitors */
6082 if (!strcmp(monitor_device,"stdio")) {
6083 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
6084 const char *devname = serial_devices[i];
6085 if (devname && !strcmp(devname,"mon:stdio")) {
6086 monitor_device = NULL;
6087 break;
6088 } else if (devname && !strcmp(devname,"stdio")) {
6089 monitor_device = NULL;
6090 serial_devices[i] = "mon:stdio";
6091 break;
6096 if (nb_numa_nodes > 0) {
6097 int i;
6099 if (nb_numa_nodes > smp_cpus) {
6100 nb_numa_nodes = smp_cpus;
6103 /* If no memory size if given for any node, assume the default case
6104 * and distribute the available memory equally across all nodes
6106 for (i = 0; i < nb_numa_nodes; i++) {
6107 if (node_mem[i] != 0)
6108 break;
6110 if (i == nb_numa_nodes) {
6111 uint64_t usedmem = 0;
6113 /* On Linux, the each node's border has to be 8MB aligned,
6114 * the final node gets the rest.
6116 for (i = 0; i < nb_numa_nodes - 1; i++) {
6117 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
6118 usedmem += node_mem[i];
6120 node_mem[i] = ram_size - usedmem;
6123 for (i = 0; i < nb_numa_nodes; i++) {
6124 if (node_cpumask[i] != 0)
6125 break;
6127 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6128 * must cope with this anyway, because there are BIOSes out there in
6129 * real machines which also use this scheme.
6131 if (i == nb_numa_nodes) {
6132 for (i = 0; i < smp_cpus; i++) {
6133 node_cpumask[i % nb_numa_nodes] |= 1 << i;
6138 #ifdef KVM_UPSTREAM
6139 if (kvm_enabled()) {
6140 int ret;
6142 ret = kvm_init(smp_cpus);
6143 if (ret < 0) {
6144 fprintf(stderr, "failed to initialize KVM\n");
6145 exit(1);
6148 #endif
6150 if (monitor_device) {
6151 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
6152 if (!monitor_hd) {
6153 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6154 exit(1);
6158 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6159 const char *devname = serial_devices[i];
6160 if (devname && strcmp(devname, "none")) {
6161 char label[32];
6162 snprintf(label, sizeof(label), "serial%d", i);
6163 serial_hds[i] = qemu_chr_open(label, devname, NULL);
6164 if (!serial_hds[i]) {
6165 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6166 devname);
6167 exit(1);
6172 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6173 const char *devname = parallel_devices[i];
6174 if (devname && strcmp(devname, "none")) {
6175 char label[32];
6176 snprintf(label, sizeof(label), "parallel%d", i);
6177 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
6178 if (!parallel_hds[i]) {
6179 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6180 devname);
6181 exit(1);
6186 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6187 const char *devname = virtio_consoles[i];
6188 if (devname && strcmp(devname, "none")) {
6189 char label[32];
6190 snprintf(label, sizeof(label), "virtcon%d", i);
6191 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
6192 if (!virtcon_hds[i]) {
6193 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
6194 devname);
6195 exit(1);
6200 module_call_init(MODULE_INIT_DEVICE);
6202 if (kvm_enabled())
6203 kvm_init_ap();
6205 machine->init(ram_size, boot_devices,
6206 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6209 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6210 for (i = 0; i < nb_numa_nodes; i++) {
6211 if (node_cpumask[i] & (1 << env->cpu_index)) {
6212 env->numa_node = i;
6217 current_machine = machine;
6219 /* Set KVM's vcpu state to qemu's initial CPUState. */
6220 if (kvm_enabled()) {
6221 int ret;
6223 ret = kvm_sync_vcpus();
6224 if (ret < 0) {
6225 fprintf(stderr, "failed to initialize vcpus\n");
6226 exit(1);
6230 /* init USB devices */
6231 if (usb_enabled) {
6232 for(i = 0; i < usb_devices_index; i++) {
6233 if (usb_device_add(usb_devices[i], 0) < 0) {
6234 fprintf(stderr, "Warning: could not add USB device %s\n",
6235 usb_devices[i]);
6240 if (!display_state)
6241 dumb_display_init();
6242 /* just use the first displaystate for the moment */
6243 ds = display_state;
6245 if (display_type == DT_DEFAULT) {
6246 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6247 display_type = DT_SDL;
6248 #else
6249 display_type = DT_VNC;
6250 vnc_display = "localhost:0,to=99";
6251 show_vnc_port = 1;
6252 #endif
6256 switch (display_type) {
6257 case DT_NOGRAPHIC:
6258 break;
6259 #if defined(CONFIG_CURSES)
6260 case DT_CURSES:
6261 curses_display_init(ds, full_screen);
6262 break;
6263 #endif
6264 #if defined(CONFIG_SDL)
6265 case DT_SDL:
6266 sdl_display_init(ds, full_screen, no_frame);
6267 break;
6268 #elif defined(CONFIG_COCOA)
6269 case DT_SDL:
6270 cocoa_display_init(ds, full_screen);
6271 break;
6272 #endif
6273 case DT_VNC:
6274 vnc_display_init(ds);
6275 if (vnc_display_open(ds, vnc_display) < 0)
6276 exit(1);
6278 if (show_vnc_port) {
6279 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6281 break;
6282 default:
6283 break;
6285 dpy_resize(ds);
6287 dcl = ds->listeners;
6288 while (dcl != NULL) {
6289 if (dcl->dpy_refresh != NULL) {
6290 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6291 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6293 dcl = dcl->next;
6296 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6297 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6298 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6301 text_consoles_set_display(display_state);
6302 qemu_chr_initial_reset();
6304 if (monitor_device && monitor_hd)
6305 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6307 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6308 const char *devname = serial_devices[i];
6309 if (devname && strcmp(devname, "none")) {
6310 if (strstart(devname, "vc", 0))
6311 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6315 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6316 const char *devname = parallel_devices[i];
6317 if (devname && strcmp(devname, "none")) {
6318 if (strstart(devname, "vc", 0))
6319 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6323 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6324 const char *devname = virtio_consoles[i];
6325 if (virtcon_hds[i] && devname) {
6326 if (strstart(devname, "vc", 0))
6327 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6331 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6332 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6333 gdbstub_dev);
6334 exit(1);
6337 if (loadvm)
6338 do_loadvm(cur_mon, loadvm);
6340 if (incoming) {
6341 autostart = 0; /* fixme how to deal with -daemonize */
6342 qemu_start_incoming_migration(incoming);
6345 if (autostart)
6346 vm_start();
6348 #ifndef _WIN32
6349 if (daemonize) {
6350 uint8_t status = 0;
6351 ssize_t len;
6353 again1:
6354 len = write(fds[1], &status, 1);
6355 if (len == -1 && (errno == EINTR))
6356 goto again1;
6358 if (len != 1)
6359 exit(1);
6361 chdir("/");
6362 TFR(fd = open("/dev/null", O_RDWR));
6363 if (fd == -1)
6364 exit(1);
6367 if (run_as) {
6368 pwd = getpwnam(run_as);
6369 if (!pwd) {
6370 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6371 exit(1);
6375 if (chroot_dir) {
6376 if (chroot(chroot_dir) < 0) {
6377 fprintf(stderr, "chroot failed\n");
6378 exit(1);
6380 chdir("/");
6383 if (run_as) {
6384 if (setgid(pwd->pw_gid) < 0) {
6385 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6386 exit(1);
6388 if (setuid(pwd->pw_uid) < 0) {
6389 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6390 exit(1);
6392 if (setuid(0) != -1) {
6393 fprintf(stderr, "Dropping privileges failed\n");
6394 exit(1);
6398 if (daemonize) {
6399 dup2(fd, 0);
6400 dup2(fd, 1);
6401 dup2(fd, 2);
6403 close(fd);
6405 #endif
6407 main_loop();
6408 quit_timers();
6409 net_cleanup();
6411 return 0;