Merge commit '253d0942fac33c5c15c9a7f8657f55f125dc5816' into upstream-merge
[qemu-kvm/fedora.git] / vl.c
blobc3cc7e0dc7ec65077317346b3c665cefdf1c3407
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 #include "slirp/libslirp.h"
172 //#define DEBUG_UNUSED_IOPORT
173 //#define DEBUG_IOPORT
174 //#define DEBUG_NET
175 //#define DEBUG_SLIRP
178 #ifdef DEBUG_IOPORT
179 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
180 #else
181 # define LOG_IOPORT(...) do { } while (0)
182 #endif
184 #define DEFAULT_RAM_SIZE 128
186 /* Max number of USB devices that can be specified on the commandline. */
187 #define MAX_USB_CMDLINE 8
189 /* Max number of bluetooth switches on the commandline. */
190 #define MAX_BT_CMDLINE 10
192 /* XXX: use a two level table to limit memory usage */
193 #define MAX_IOPORTS 65536
195 static const char *data_dir;
196 const char *bios_name = NULL;
197 static void *ioport_opaque[MAX_IOPORTS];
198 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
199 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
200 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
201 to store the VM snapshots */
202 DriveInfo drives_table[MAX_DRIVES+1];
203 int nb_drives;
204 int extboot_drive = -1;
205 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
206 static DisplayState *display_state;
207 DisplayType display_type = DT_DEFAULT;
208 const char* keyboard_layout = NULL;
209 int64_t ticks_per_sec;
210 ram_addr_t ram_size;
211 int nb_nics;
212 NICInfo nd_table[MAX_NICS];
213 int vm_running;
214 static int autostart;
215 static int rtc_utc = 1;
216 static int rtc_date_offset = -1; /* -1 means no change */
217 int cirrus_vga_enabled = 1;
218 int std_vga_enabled = 0;
219 int vmsvga_enabled = 0;
220 int xenfb_enabled = 0;
221 #ifdef TARGET_SPARC
222 int graphic_width = 1024;
223 int graphic_height = 768;
224 int graphic_depth = 8;
225 #else
226 int graphic_width = 800;
227 int graphic_height = 600;
228 int graphic_depth = 15;
229 #endif
230 static int full_screen = 0;
231 #ifdef CONFIG_SDL
232 static int no_frame = 0;
233 #endif
234 int no_quit = 0;
235 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
236 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
237 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
238 #ifdef TARGET_I386
239 int win2k_install_hack = 0;
240 int rtc_td_hack = 0;
241 #endif
242 int usb_enabled = 0;
243 int singlestep = 0;
244 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
245 int assigned_devices_index;
246 int smp_cpus = 1;
247 const char *vnc_display;
248 int acpi_enabled = 1;
249 int no_hpet = 0;
250 int no_virtio_balloon = 0;
251 int fd_bootchk = 1;
252 int no_reboot = 0;
253 int no_shutdown = 0;
254 int cursor_hide = 1;
255 int graphic_rotate = 0;
256 #ifndef _WIN32
257 int daemonize = 0;
258 #endif
259 WatchdogTimerModel *watchdog = NULL;
260 int watchdog_action = WDT_RESET;
261 const char *option_rom[MAX_OPTION_ROMS];
262 int nb_option_roms;
263 int semihosting_enabled = 0;
264 int time_drift_fix = 0;
265 unsigned int kvm_shadow_memory = 0;
266 const char *mem_path = NULL;
267 #ifdef MAP_POPULATE
268 int mem_prealloc = 1; /* force preallocation of physical target memory */
269 #endif
270 #ifdef TARGET_ARM
271 int old_param = 0;
272 #endif
273 const char *qemu_name;
274 int alt_grab = 0;
275 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
276 unsigned int nb_prom_envs = 0;
277 const char *prom_envs[MAX_PROM_ENVS];
278 #endif
279 int nb_drives_opt;
280 const char *nvram = NULL;
281 struct drive_opt drives_opt[MAX_DRIVES];
283 int nb_numa_nodes;
284 uint64_t node_mem[MAX_NODES];
285 uint64_t node_cpumask[MAX_NODES];
287 static CPUState *cur_cpu;
288 static CPUState *next_cpu;
289 static int timer_alarm_pending = 1;
290 /* Conversion factor from emulated instructions to virtual clock ticks. */
291 static int icount_time_shift;
292 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
293 #define MAX_ICOUNT_SHIFT 10
294 /* Compensate for varying guest execution speed. */
295 static int64_t qemu_icount_bias;
296 static QEMUTimer *icount_rt_timer;
297 static QEMUTimer *icount_vm_timer;
298 static QEMUTimer *nographic_timer;
300 uint8_t qemu_uuid[16];
302 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
303 struct timeval *tv)
305 int ret;
307 /* KVM holds a mutex while QEMU code is running, we need hooks to
308 release the mutex whenever QEMU code sleeps. */
310 kvm_sleep_begin();
312 ret = select(max_fd, rfds, wfds, xfds, tv);
314 kvm_sleep_end();
316 return ret;
320 /***********************************************************/
321 /* x86 ISA bus support */
323 target_phys_addr_t isa_mem_base = 0;
324 PicState2 *isa_pic;
326 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
327 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
329 static uint32_t ioport_read(int index, uint32_t address)
331 static IOPortReadFunc *default_func[3] = {
332 default_ioport_readb,
333 default_ioport_readw,
334 default_ioport_readl
336 IOPortReadFunc *func = ioport_read_table[index][address];
337 if (!func)
338 func = default_func[index];
339 return func(ioport_opaque[address], address);
342 static void ioport_write(int index, uint32_t address, uint32_t data)
344 static IOPortWriteFunc *default_func[3] = {
345 default_ioport_writeb,
346 default_ioport_writew,
347 default_ioport_writel
349 IOPortWriteFunc *func = ioport_write_table[index][address];
350 if (!func)
351 func = default_func[index];
352 func(ioport_opaque[address], address, data);
355 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
357 #ifdef DEBUG_UNUSED_IOPORT
358 fprintf(stderr, "unused inb: port=0x%04x\n", address);
359 #endif
360 return 0xff;
363 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
365 #ifdef DEBUG_UNUSED_IOPORT
366 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
367 #endif
370 /* default is to make two byte accesses */
371 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
373 uint32_t data;
374 data = ioport_read(0, address);
375 address = (address + 1) & (MAX_IOPORTS - 1);
376 data |= ioport_read(0, address) << 8;
377 return data;
380 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
382 ioport_write(0, address, data & 0xff);
383 address = (address + 1) & (MAX_IOPORTS - 1);
384 ioport_write(0, address, (data >> 8) & 0xff);
387 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
389 #ifdef DEBUG_UNUSED_IOPORT
390 fprintf(stderr, "unused inl: port=0x%04x\n", address);
391 #endif
392 return 0xffffffff;
395 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
397 #ifdef DEBUG_UNUSED_IOPORT
398 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
399 #endif
402 /* size is the word size in byte */
403 int register_ioport_read(int start, int length, int size,
404 IOPortReadFunc *func, void *opaque)
406 int i, bsize;
408 if (size == 1) {
409 bsize = 0;
410 } else if (size == 2) {
411 bsize = 1;
412 } else if (size == 4) {
413 bsize = 2;
414 } else {
415 hw_error("register_ioport_read: invalid size");
416 return -1;
418 for(i = start; i < start + length; i += size) {
419 ioport_read_table[bsize][i] = func;
420 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
421 hw_error("register_ioport_read: invalid opaque");
422 ioport_opaque[i] = opaque;
424 return 0;
427 /* size is the word size in byte */
428 int register_ioport_write(int start, int length, int size,
429 IOPortWriteFunc *func, void *opaque)
431 int i, bsize;
433 if (size == 1) {
434 bsize = 0;
435 } else if (size == 2) {
436 bsize = 1;
437 } else if (size == 4) {
438 bsize = 2;
439 } else {
440 hw_error("register_ioport_write: invalid size");
441 return -1;
443 for(i = start; i < start + length; i += size) {
444 ioport_write_table[bsize][i] = func;
445 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
446 hw_error("register_ioport_write: invalid opaque");
447 ioport_opaque[i] = opaque;
449 return 0;
452 void isa_unassign_ioport(int start, int length)
454 int i;
456 for(i = start; i < start + length; i++) {
457 ioport_read_table[0][i] = default_ioport_readb;
458 ioport_read_table[1][i] = default_ioport_readw;
459 ioport_read_table[2][i] = default_ioport_readl;
461 ioport_write_table[0][i] = default_ioport_writeb;
462 ioport_write_table[1][i] = default_ioport_writew;
463 ioport_write_table[2][i] = default_ioport_writel;
465 ioport_opaque[i] = NULL;
469 /***********************************************************/
471 void cpu_outb(CPUState *env, int addr, int val)
473 LOG_IOPORT("outb: %04x %02x\n", addr, val);
474 ioport_write(0, addr, val);
475 #ifdef CONFIG_KQEMU
476 if (env)
477 env->last_io_time = cpu_get_time_fast();
478 #endif
481 void cpu_outw(CPUState *env, int addr, int val)
483 LOG_IOPORT("outw: %04x %04x\n", addr, val);
484 ioport_write(1, addr, val);
485 #ifdef CONFIG_KQEMU
486 if (env)
487 env->last_io_time = cpu_get_time_fast();
488 #endif
491 void cpu_outl(CPUState *env, int addr, int val)
493 LOG_IOPORT("outl: %04x %08x\n", addr, val);
494 ioport_write(2, addr, val);
495 #ifdef CONFIG_KQEMU
496 if (env)
497 env->last_io_time = cpu_get_time_fast();
498 #endif
501 int cpu_inb(CPUState *env, int addr)
503 int val;
504 val = ioport_read(0, addr);
505 LOG_IOPORT("inb : %04x %02x\n", addr, val);
506 #ifdef CONFIG_KQEMU
507 if (env)
508 env->last_io_time = cpu_get_time_fast();
509 #endif
510 return val;
513 int cpu_inw(CPUState *env, int addr)
515 int val;
516 val = ioport_read(1, addr);
517 LOG_IOPORT("inw : %04x %04x\n", addr, val);
518 #ifdef CONFIG_KQEMU
519 if (env)
520 env->last_io_time = cpu_get_time_fast();
521 #endif
522 return val;
525 int cpu_inl(CPUState *env, int addr)
527 int val;
528 val = ioport_read(2, addr);
529 LOG_IOPORT("inl : %04x %08x\n", addr, val);
530 #ifdef CONFIG_KQEMU
531 if (env)
532 env->last_io_time = cpu_get_time_fast();
533 #endif
534 return val;
537 /***********************************************************/
538 void hw_error(const char *fmt, ...)
540 va_list ap;
541 CPUState *env;
543 va_start(ap, fmt);
544 fprintf(stderr, "qemu: hardware error: ");
545 vfprintf(stderr, fmt, ap);
546 fprintf(stderr, "\n");
547 for(env = first_cpu; env != NULL; env = env->next_cpu) {
548 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
549 #ifdef TARGET_I386
550 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
551 #else
552 cpu_dump_state(env, stderr, fprintf, 0);
553 #endif
555 va_end(ap);
556 abort();
559 /***************/
560 /* ballooning */
562 static QEMUBalloonEvent *qemu_balloon_event;
563 void *qemu_balloon_event_opaque;
565 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
567 qemu_balloon_event = func;
568 qemu_balloon_event_opaque = opaque;
571 void qemu_balloon(ram_addr_t target)
573 if (qemu_balloon_event)
574 qemu_balloon_event(qemu_balloon_event_opaque, target);
577 ram_addr_t qemu_balloon_status(void)
579 if (qemu_balloon_event)
580 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
581 return 0;
584 /***********************************************************/
585 /* keyboard/mouse */
587 static QEMUPutKBDEvent *qemu_put_kbd_event;
588 static void *qemu_put_kbd_event_opaque;
589 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
590 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
592 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
594 qemu_put_kbd_event_opaque = opaque;
595 qemu_put_kbd_event = func;
598 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
599 void *opaque, int absolute,
600 const char *name)
602 QEMUPutMouseEntry *s, *cursor;
604 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
606 s->qemu_put_mouse_event = func;
607 s->qemu_put_mouse_event_opaque = opaque;
608 s->qemu_put_mouse_event_absolute = absolute;
609 s->qemu_put_mouse_event_name = qemu_strdup(name);
610 s->next = NULL;
612 if (!qemu_put_mouse_event_head) {
613 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
614 return s;
617 cursor = qemu_put_mouse_event_head;
618 while (cursor->next != NULL)
619 cursor = cursor->next;
621 cursor->next = s;
622 qemu_put_mouse_event_current = s;
624 return s;
627 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
629 QEMUPutMouseEntry *prev = NULL, *cursor;
631 if (!qemu_put_mouse_event_head || entry == NULL)
632 return;
634 cursor = qemu_put_mouse_event_head;
635 while (cursor != NULL && cursor != entry) {
636 prev = cursor;
637 cursor = cursor->next;
640 if (cursor == NULL) // does not exist or list empty
641 return;
642 else if (prev == NULL) { // entry is head
643 qemu_put_mouse_event_head = cursor->next;
644 if (qemu_put_mouse_event_current == entry)
645 qemu_put_mouse_event_current = cursor->next;
646 qemu_free(entry->qemu_put_mouse_event_name);
647 qemu_free(entry);
648 return;
651 prev->next = entry->next;
653 if (qemu_put_mouse_event_current == entry)
654 qemu_put_mouse_event_current = prev;
656 qemu_free(entry->qemu_put_mouse_event_name);
657 qemu_free(entry);
660 void kbd_put_keycode(int keycode)
662 if (qemu_put_kbd_event) {
663 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
667 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
669 QEMUPutMouseEvent *mouse_event;
670 void *mouse_event_opaque;
671 int width;
673 if (!qemu_put_mouse_event_current) {
674 return;
677 mouse_event =
678 qemu_put_mouse_event_current->qemu_put_mouse_event;
679 mouse_event_opaque =
680 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
682 if (mouse_event) {
683 if (graphic_rotate) {
684 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
685 width = 0x7fff;
686 else
687 width = graphic_width - 1;
688 mouse_event(mouse_event_opaque,
689 width - dy, dx, dz, buttons_state);
690 } else
691 mouse_event(mouse_event_opaque,
692 dx, dy, dz, buttons_state);
696 int kbd_mouse_is_absolute(void)
698 if (!qemu_put_mouse_event_current)
699 return 0;
701 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
704 void do_info_mice(Monitor *mon)
706 QEMUPutMouseEntry *cursor;
707 int index = 0;
709 if (!qemu_put_mouse_event_head) {
710 monitor_printf(mon, "No mouse devices connected\n");
711 return;
714 monitor_printf(mon, "Mouse devices available:\n");
715 cursor = qemu_put_mouse_event_head;
716 while (cursor != NULL) {
717 monitor_printf(mon, "%c Mouse #%d: %s\n",
718 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
719 index, cursor->qemu_put_mouse_event_name);
720 index++;
721 cursor = cursor->next;
725 void do_mouse_set(Monitor *mon, int index)
727 QEMUPutMouseEntry *cursor;
728 int i = 0;
730 if (!qemu_put_mouse_event_head) {
731 monitor_printf(mon, "No mouse devices connected\n");
732 return;
735 cursor = qemu_put_mouse_event_head;
736 while (cursor != NULL && index != i) {
737 i++;
738 cursor = cursor->next;
741 if (cursor != NULL)
742 qemu_put_mouse_event_current = cursor;
743 else
744 monitor_printf(mon, "Mouse at given index not found\n");
747 /* compute with 96 bit intermediate result: (a*b)/c */
748 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
750 union {
751 uint64_t ll;
752 struct {
753 #ifdef WORDS_BIGENDIAN
754 uint32_t high, low;
755 #else
756 uint32_t low, high;
757 #endif
758 } l;
759 } u, res;
760 uint64_t rl, rh;
762 u.ll = a;
763 rl = (uint64_t)u.l.low * (uint64_t)b;
764 rh = (uint64_t)u.l.high * (uint64_t)b;
765 rh += (rl >> 32);
766 res.l.high = rh / c;
767 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
768 return res.ll;
771 /***********************************************************/
772 /* real time host monotonic timer */
774 #define QEMU_TIMER_BASE 1000000000LL
776 #ifdef WIN32
778 static int64_t clock_freq;
780 static void init_get_clock(void)
782 LARGE_INTEGER freq;
783 int ret;
784 ret = QueryPerformanceFrequency(&freq);
785 if (ret == 0) {
786 fprintf(stderr, "Could not calibrate ticks\n");
787 exit(1);
789 clock_freq = freq.QuadPart;
792 static int64_t get_clock(void)
794 LARGE_INTEGER ti;
795 QueryPerformanceCounter(&ti);
796 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
799 #else
801 static int use_rt_clock;
803 static void init_get_clock(void)
805 use_rt_clock = 0;
806 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
807 || defined(__DragonFly__)
809 struct timespec ts;
810 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
811 use_rt_clock = 1;
814 #endif
817 static int64_t get_clock(void)
819 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
820 || defined(__DragonFly__)
821 if (use_rt_clock) {
822 struct timespec ts;
823 clock_gettime(CLOCK_MONOTONIC, &ts);
824 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
825 } else
826 #endif
828 /* XXX: using gettimeofday leads to problems if the date
829 changes, so it should be avoided. */
830 struct timeval tv;
831 gettimeofday(&tv, NULL);
832 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
835 #endif
837 /* Return the virtual CPU time, based on the instruction counter. */
838 static int64_t cpu_get_icount(void)
840 int64_t icount;
841 CPUState *env = cpu_single_env;;
842 icount = qemu_icount;
843 if (env) {
844 if (!can_do_io(env))
845 fprintf(stderr, "Bad clock read\n");
846 icount -= (env->icount_decr.u16.low + env->icount_extra);
848 return qemu_icount_bias + (icount << icount_time_shift);
851 /***********************************************************/
852 /* guest cycle counter */
854 static int64_t cpu_ticks_prev;
855 static int64_t cpu_ticks_offset;
856 static int64_t cpu_clock_offset;
857 static int cpu_ticks_enabled;
859 /* return the host CPU cycle counter and handle stop/restart */
860 int64_t cpu_get_ticks(void)
862 if (use_icount) {
863 return cpu_get_icount();
865 if (!cpu_ticks_enabled) {
866 return cpu_ticks_offset;
867 } else {
868 int64_t ticks;
869 ticks = cpu_get_real_ticks();
870 if (cpu_ticks_prev > ticks) {
871 /* Note: non increasing ticks may happen if the host uses
872 software suspend */
873 cpu_ticks_offset += cpu_ticks_prev - ticks;
875 cpu_ticks_prev = ticks;
876 return ticks + cpu_ticks_offset;
880 /* return the host CPU monotonic timer and handle stop/restart */
881 static int64_t cpu_get_clock(void)
883 int64_t ti;
884 if (!cpu_ticks_enabled) {
885 return cpu_clock_offset;
886 } else {
887 ti = get_clock();
888 return ti + cpu_clock_offset;
892 /* enable cpu_get_ticks() */
893 void cpu_enable_ticks(void)
895 if (!cpu_ticks_enabled) {
896 cpu_ticks_offset -= cpu_get_real_ticks();
897 cpu_clock_offset -= get_clock();
898 cpu_ticks_enabled = 1;
902 /* disable cpu_get_ticks() : the clock is stopped. You must not call
903 cpu_get_ticks() after that. */
904 void cpu_disable_ticks(void)
906 if (cpu_ticks_enabled) {
907 cpu_ticks_offset = cpu_get_ticks();
908 cpu_clock_offset = cpu_get_clock();
909 cpu_ticks_enabled = 0;
913 /***********************************************************/
914 /* timers */
916 #define QEMU_TIMER_REALTIME 0
917 #define QEMU_TIMER_VIRTUAL 1
919 struct QEMUClock {
920 int type;
921 /* XXX: add frequency */
924 struct QEMUTimer {
925 QEMUClock *clock;
926 int64_t expire_time;
927 QEMUTimerCB *cb;
928 void *opaque;
929 struct QEMUTimer *next;
932 struct qemu_alarm_timer {
933 char const *name;
934 unsigned int flags;
936 int (*start)(struct qemu_alarm_timer *t);
937 void (*stop)(struct qemu_alarm_timer *t);
938 void (*rearm)(struct qemu_alarm_timer *t);
939 void *priv;
942 #define ALARM_FLAG_DYNTICKS 0x1
943 #define ALARM_FLAG_EXPIRED 0x2
945 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
947 return t && (t->flags & ALARM_FLAG_DYNTICKS);
950 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
952 if (!alarm_has_dynticks(t))
953 return;
955 t->rearm(t);
958 /* TODO: MIN_TIMER_REARM_US should be optimized */
959 #define MIN_TIMER_REARM_US 250
961 static struct qemu_alarm_timer *alarm_timer;
963 #ifdef _WIN32
965 struct qemu_alarm_win32 {
966 MMRESULT timerId;
967 unsigned int period;
968 } alarm_win32_data = {0, -1};
970 static int win32_start_timer(struct qemu_alarm_timer *t);
971 static void win32_stop_timer(struct qemu_alarm_timer *t);
972 static void win32_rearm_timer(struct qemu_alarm_timer *t);
974 #else
976 static int unix_start_timer(struct qemu_alarm_timer *t);
977 static void unix_stop_timer(struct qemu_alarm_timer *t);
979 #ifdef __linux__
981 static int dynticks_start_timer(struct qemu_alarm_timer *t);
982 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
983 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
985 static int hpet_start_timer(struct qemu_alarm_timer *t);
986 static void hpet_stop_timer(struct qemu_alarm_timer *t);
988 static int rtc_start_timer(struct qemu_alarm_timer *t);
989 static void rtc_stop_timer(struct qemu_alarm_timer *t);
991 #endif /* __linux__ */
993 #endif /* _WIN32 */
995 /* Correlation between real and virtual time is always going to be
996 fairly approximate, so ignore small variation.
997 When the guest is idle real and virtual time will be aligned in
998 the IO wait loop. */
999 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
1001 static void icount_adjust(void)
1003 int64_t cur_time;
1004 int64_t cur_icount;
1005 int64_t delta;
1006 static int64_t last_delta;
1007 /* If the VM is not running, then do nothing. */
1008 if (!vm_running)
1009 return;
1011 cur_time = cpu_get_clock();
1012 cur_icount = qemu_get_clock(vm_clock);
1013 delta = cur_icount - cur_time;
1014 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1015 if (delta > 0
1016 && last_delta + ICOUNT_WOBBLE < delta * 2
1017 && icount_time_shift > 0) {
1018 /* The guest is getting too far ahead. Slow time down. */
1019 icount_time_shift--;
1021 if (delta < 0
1022 && last_delta - ICOUNT_WOBBLE > delta * 2
1023 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1024 /* The guest is getting too far behind. Speed time up. */
1025 icount_time_shift++;
1027 last_delta = delta;
1028 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1031 static void icount_adjust_rt(void * opaque)
1033 qemu_mod_timer(icount_rt_timer,
1034 qemu_get_clock(rt_clock) + 1000);
1035 icount_adjust();
1038 static void icount_adjust_vm(void * opaque)
1040 qemu_mod_timer(icount_vm_timer,
1041 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1042 icount_adjust();
1045 static void init_icount_adjust(void)
1047 /* Have both realtime and virtual time triggers for speed adjustment.
1048 The realtime trigger catches emulated time passing too slowly,
1049 the virtual time trigger catches emulated time passing too fast.
1050 Realtime triggers occur even when idle, so use them less frequently
1051 than VM triggers. */
1052 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1053 qemu_mod_timer(icount_rt_timer,
1054 qemu_get_clock(rt_clock) + 1000);
1055 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1056 qemu_mod_timer(icount_vm_timer,
1057 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1060 static struct qemu_alarm_timer alarm_timers[] = {
1061 #ifndef _WIN32
1062 #ifdef __linux__
1063 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1064 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1065 /* HPET - if available - is preferred */
1066 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1067 /* ...otherwise try RTC */
1068 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1069 #endif
1070 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1071 #else
1072 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1073 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1074 {"win32", 0, win32_start_timer,
1075 win32_stop_timer, NULL, &alarm_win32_data},
1076 #endif
1077 {NULL, }
1080 static void show_available_alarms(void)
1082 int i;
1084 printf("Available alarm timers, in order of precedence:\n");
1085 for (i = 0; alarm_timers[i].name; i++)
1086 printf("%s\n", alarm_timers[i].name);
1089 static void configure_alarms(char const *opt)
1091 int i;
1092 int cur = 0;
1093 int count = ARRAY_SIZE(alarm_timers) - 1;
1094 char *arg;
1095 char *name;
1096 struct qemu_alarm_timer tmp;
1098 if (!strcmp(opt, "?")) {
1099 show_available_alarms();
1100 exit(0);
1103 arg = strdup(opt);
1105 /* Reorder the array */
1106 name = strtok(arg, ",");
1107 while (name) {
1108 for (i = 0; i < count && alarm_timers[i].name; i++) {
1109 if (!strcmp(alarm_timers[i].name, name))
1110 break;
1113 if (i == count) {
1114 fprintf(stderr, "Unknown clock %s\n", name);
1115 goto next;
1118 if (i < cur)
1119 /* Ignore */
1120 goto next;
1122 /* Swap */
1123 tmp = alarm_timers[i];
1124 alarm_timers[i] = alarm_timers[cur];
1125 alarm_timers[cur] = tmp;
1127 cur++;
1128 next:
1129 name = strtok(NULL, ",");
1132 free(arg);
1134 if (cur) {
1135 /* Disable remaining timers */
1136 for (i = cur; i < count; i++)
1137 alarm_timers[i].name = NULL;
1138 } else {
1139 show_available_alarms();
1140 exit(1);
1144 QEMUClock *rt_clock;
1145 QEMUClock *vm_clock;
1147 static QEMUTimer *active_timers[2];
1149 static QEMUClock *qemu_new_clock(int type)
1151 QEMUClock *clock;
1152 clock = qemu_mallocz(sizeof(QEMUClock));
1153 clock->type = type;
1154 return clock;
1157 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1159 QEMUTimer *ts;
1161 ts = qemu_mallocz(sizeof(QEMUTimer));
1162 ts->clock = clock;
1163 ts->cb = cb;
1164 ts->opaque = opaque;
1165 return ts;
1168 void qemu_free_timer(QEMUTimer *ts)
1170 qemu_free(ts);
1173 /* stop a timer, but do not dealloc it */
1174 void qemu_del_timer(QEMUTimer *ts)
1176 QEMUTimer **pt, *t;
1178 /* NOTE: this code must be signal safe because
1179 qemu_timer_expired() can be called from a signal. */
1180 pt = &active_timers[ts->clock->type];
1181 for(;;) {
1182 t = *pt;
1183 if (!t)
1184 break;
1185 if (t == ts) {
1186 *pt = t->next;
1187 break;
1189 pt = &t->next;
1193 /* modify the current timer so that it will be fired when current_time
1194 >= expire_time. The corresponding callback will be called. */
1195 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1197 QEMUTimer **pt, *t;
1199 qemu_del_timer(ts);
1201 /* add the timer in the sorted list */
1202 /* NOTE: this code must be signal safe because
1203 qemu_timer_expired() can be called from a signal. */
1204 pt = &active_timers[ts->clock->type];
1205 for(;;) {
1206 t = *pt;
1207 if (!t)
1208 break;
1209 if (t->expire_time > expire_time)
1210 break;
1211 pt = &t->next;
1213 ts->expire_time = expire_time;
1214 ts->next = *pt;
1215 *pt = ts;
1217 /* Rearm if necessary */
1218 if (pt == &active_timers[ts->clock->type]) {
1219 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1220 qemu_rearm_alarm_timer(alarm_timer);
1222 /* Interrupt execution to force deadline recalculation. */
1223 if (use_icount)
1224 qemu_notify_event();
1228 int qemu_timer_pending(QEMUTimer *ts)
1230 QEMUTimer *t;
1231 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1232 if (t == ts)
1233 return 1;
1235 return 0;
1238 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1240 if (!timer_head)
1241 return 0;
1242 return (timer_head->expire_time <= current_time);
1245 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1247 QEMUTimer *ts;
1249 for(;;) {
1250 ts = *ptimer_head;
1251 if (!ts || ts->expire_time > current_time)
1252 break;
1253 /* remove timer from the list before calling the callback */
1254 *ptimer_head = ts->next;
1255 ts->next = NULL;
1257 /* run the callback (the timer list can be modified) */
1258 ts->cb(ts->opaque);
1262 int64_t qemu_get_clock(QEMUClock *clock)
1264 switch(clock->type) {
1265 case QEMU_TIMER_REALTIME:
1266 return get_clock() / 1000000;
1267 default:
1268 case QEMU_TIMER_VIRTUAL:
1269 if (use_icount) {
1270 return cpu_get_icount();
1271 } else {
1272 return cpu_get_clock();
1277 static void init_timers(void)
1279 init_get_clock();
1280 ticks_per_sec = QEMU_TIMER_BASE;
1281 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1282 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1285 /* save a timer */
1286 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1288 uint64_t expire_time;
1290 if (qemu_timer_pending(ts)) {
1291 expire_time = ts->expire_time;
1292 } else {
1293 expire_time = -1;
1295 qemu_put_be64(f, expire_time);
1298 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1300 uint64_t expire_time;
1302 expire_time = qemu_get_be64(f);
1303 if (expire_time != -1) {
1304 qemu_mod_timer(ts, expire_time);
1305 } else {
1306 qemu_del_timer(ts);
1310 static void timer_save(QEMUFile *f, void *opaque)
1312 if (cpu_ticks_enabled) {
1313 hw_error("cannot save state if virtual timers are running");
1315 qemu_put_be64(f, cpu_ticks_offset);
1316 qemu_put_be64(f, ticks_per_sec);
1317 qemu_put_be64(f, cpu_clock_offset);
1320 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1322 if (version_id != 1 && version_id != 2)
1323 return -EINVAL;
1324 if (cpu_ticks_enabled) {
1325 return -EINVAL;
1327 cpu_ticks_offset=qemu_get_be64(f);
1328 ticks_per_sec=qemu_get_be64(f);
1329 if (version_id == 2) {
1330 cpu_clock_offset=qemu_get_be64(f);
1332 return 0;
1335 static void qemu_event_increment(void);
1337 #ifdef _WIN32
1338 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1339 DWORD_PTR dwUser, DWORD_PTR dw1,
1340 DWORD_PTR dw2)
1341 #else
1342 static void host_alarm_handler(int host_signum)
1343 #endif
1345 #if 0
1346 #define DISP_FREQ 1000
1348 static int64_t delta_min = INT64_MAX;
1349 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1350 static int count;
1351 ti = qemu_get_clock(vm_clock);
1352 if (last_clock != 0) {
1353 delta = ti - last_clock;
1354 if (delta < delta_min)
1355 delta_min = delta;
1356 if (delta > delta_max)
1357 delta_max = delta;
1358 delta_cum += delta;
1359 if (++count == DISP_FREQ) {
1360 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1361 muldiv64(delta_min, 1000000, ticks_per_sec),
1362 muldiv64(delta_max, 1000000, ticks_per_sec),
1363 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1364 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1365 count = 0;
1366 delta_min = INT64_MAX;
1367 delta_max = 0;
1368 delta_cum = 0;
1371 last_clock = ti;
1373 #endif
1374 if (alarm_has_dynticks(alarm_timer) ||
1375 (!use_icount &&
1376 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1377 qemu_get_clock(vm_clock))) ||
1378 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1379 qemu_get_clock(rt_clock))) {
1380 qemu_event_increment();
1381 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1383 #ifndef CONFIG_IOTHREAD
1384 if (next_cpu) {
1385 /* stop the currently executing cpu because a timer occured */
1386 cpu_exit(next_cpu);
1387 #ifdef CONFIG_KQEMU
1388 if (next_cpu->kqemu_enabled) {
1389 kqemu_cpu_interrupt(next_cpu);
1391 #endif
1393 #endif
1394 timer_alarm_pending = 1;
1395 qemu_notify_event();
1399 static int64_t qemu_next_deadline(void)
1401 int64_t delta;
1403 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1404 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1405 qemu_get_clock(vm_clock);
1406 } else {
1407 /* To avoid problems with overflow limit this to 2^32. */
1408 delta = INT32_MAX;
1411 if (delta < 0)
1412 delta = 0;
1414 return delta;
1417 #if defined(__linux__) || defined(_WIN32)
1418 static uint64_t qemu_next_deadline_dyntick(void)
1420 int64_t delta;
1421 int64_t rtdelta;
1423 if (use_icount)
1424 delta = INT32_MAX;
1425 else
1426 delta = (qemu_next_deadline() + 999) / 1000;
1428 if (active_timers[QEMU_TIMER_REALTIME]) {
1429 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1430 qemu_get_clock(rt_clock))*1000;
1431 if (rtdelta < delta)
1432 delta = rtdelta;
1435 if (delta < MIN_TIMER_REARM_US)
1436 delta = MIN_TIMER_REARM_US;
1438 return delta;
1440 #endif
1442 #ifndef _WIN32
1444 /* Sets a specific flag */
1445 static int fcntl_setfl(int fd, int flag)
1447 int flags;
1449 flags = fcntl(fd, F_GETFL);
1450 if (flags == -1)
1451 return -errno;
1453 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1454 return -errno;
1456 return 0;
1459 #if defined(__linux__)
1461 #define RTC_FREQ 1024
1463 static void enable_sigio_timer(int fd)
1465 struct sigaction act;
1467 /* timer signal */
1468 sigfillset(&act.sa_mask);
1469 act.sa_flags = 0;
1470 act.sa_handler = host_alarm_handler;
1472 sigaction(SIGIO, &act, NULL);
1473 fcntl_setfl(fd, O_ASYNC);
1474 fcntl(fd, F_SETOWN, getpid());
1477 static int hpet_start_timer(struct qemu_alarm_timer *t)
1479 struct hpet_info info;
1480 int r, fd;
1482 fd = open("/dev/hpet", O_RDONLY);
1483 if (fd < 0)
1484 return -1;
1486 /* Set frequency */
1487 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1488 if (r < 0) {
1489 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1490 "error, but for better emulation accuracy type:\n"
1491 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1492 goto fail;
1495 /* Check capabilities */
1496 r = ioctl(fd, HPET_INFO, &info);
1497 if (r < 0)
1498 goto fail;
1500 /* Enable periodic mode */
1501 r = ioctl(fd, HPET_EPI, 0);
1502 if (info.hi_flags && (r < 0))
1503 goto fail;
1505 /* Enable interrupt */
1506 r = ioctl(fd, HPET_IE_ON, 0);
1507 if (r < 0)
1508 goto fail;
1510 enable_sigio_timer(fd);
1511 t->priv = (void *)(long)fd;
1513 return 0;
1514 fail:
1515 close(fd);
1516 return -1;
1519 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1521 int fd = (long)t->priv;
1523 close(fd);
1526 static int rtc_start_timer(struct qemu_alarm_timer *t)
1528 int rtc_fd;
1529 unsigned long current_rtc_freq = 0;
1531 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1532 if (rtc_fd < 0)
1533 return -1;
1534 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1535 if (current_rtc_freq != RTC_FREQ &&
1536 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1537 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1538 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1539 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1540 goto fail;
1542 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1543 fail:
1544 close(rtc_fd);
1545 return -1;
1548 enable_sigio_timer(rtc_fd);
1550 t->priv = (void *)(long)rtc_fd;
1552 return 0;
1555 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1557 int rtc_fd = (long)t->priv;
1559 close(rtc_fd);
1562 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1564 struct sigevent ev;
1565 timer_t host_timer;
1566 struct sigaction act;
1568 sigfillset(&act.sa_mask);
1569 act.sa_flags = 0;
1570 act.sa_handler = host_alarm_handler;
1572 sigaction(SIGALRM, &act, NULL);
1575 * Initialize ev struct to 0 to avoid valgrind complaining
1576 * about uninitialized data in timer_create call
1578 memset(&ev, 0, sizeof(ev));
1579 ev.sigev_value.sival_int = 0;
1580 ev.sigev_notify = SIGEV_SIGNAL;
1581 ev.sigev_signo = SIGALRM;
1583 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1584 perror("timer_create");
1586 /* disable dynticks */
1587 fprintf(stderr, "Dynamic Ticks disabled\n");
1589 return -1;
1592 t->priv = (void *)(long)host_timer;
1594 return 0;
1597 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1599 timer_t host_timer = (timer_t)(long)t->priv;
1601 timer_delete(host_timer);
1604 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1606 timer_t host_timer = (timer_t)(long)t->priv;
1607 struct itimerspec timeout;
1608 int64_t nearest_delta_us = INT64_MAX;
1609 int64_t current_us;
1611 if (!active_timers[QEMU_TIMER_REALTIME] &&
1612 !active_timers[QEMU_TIMER_VIRTUAL])
1613 return;
1615 nearest_delta_us = qemu_next_deadline_dyntick();
1617 /* check whether a timer is already running */
1618 if (timer_gettime(host_timer, &timeout)) {
1619 perror("gettime");
1620 fprintf(stderr, "Internal timer error: aborting\n");
1621 exit(1);
1623 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1624 if (current_us && current_us <= nearest_delta_us)
1625 return;
1627 timeout.it_interval.tv_sec = 0;
1628 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1629 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1630 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1631 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1632 perror("settime");
1633 fprintf(stderr, "Internal timer error: aborting\n");
1634 exit(1);
1638 #endif /* defined(__linux__) */
1640 static int unix_start_timer(struct qemu_alarm_timer *t)
1642 struct sigaction act;
1643 struct itimerval itv;
1644 int err;
1646 /* timer signal */
1647 sigfillset(&act.sa_mask);
1648 act.sa_flags = 0;
1649 act.sa_handler = host_alarm_handler;
1651 sigaction(SIGALRM, &act, NULL);
1653 itv.it_interval.tv_sec = 0;
1654 /* for i386 kernel 2.6 to get 1 ms */
1655 itv.it_interval.tv_usec = 999;
1656 itv.it_value.tv_sec = 0;
1657 itv.it_value.tv_usec = 10 * 1000;
1659 err = setitimer(ITIMER_REAL, &itv, NULL);
1660 if (err)
1661 return -1;
1663 return 0;
1666 static void unix_stop_timer(struct qemu_alarm_timer *t)
1668 struct itimerval itv;
1670 memset(&itv, 0, sizeof(itv));
1671 setitimer(ITIMER_REAL, &itv, NULL);
1674 #endif /* !defined(_WIN32) */
1677 #ifdef _WIN32
1679 static int win32_start_timer(struct qemu_alarm_timer *t)
1681 TIMECAPS tc;
1682 struct qemu_alarm_win32 *data = t->priv;
1683 UINT flags;
1685 memset(&tc, 0, sizeof(tc));
1686 timeGetDevCaps(&tc, sizeof(tc));
1688 if (data->period < tc.wPeriodMin)
1689 data->period = tc.wPeriodMin;
1691 timeBeginPeriod(data->period);
1693 flags = TIME_CALLBACK_FUNCTION;
1694 if (alarm_has_dynticks(t))
1695 flags |= TIME_ONESHOT;
1696 else
1697 flags |= TIME_PERIODIC;
1699 data->timerId = timeSetEvent(1, // interval (ms)
1700 data->period, // resolution
1701 host_alarm_handler, // function
1702 (DWORD)t, // parameter
1703 flags);
1705 if (!data->timerId) {
1706 perror("Failed to initialize win32 alarm timer");
1707 timeEndPeriod(data->period);
1708 return -1;
1711 return 0;
1714 static void win32_stop_timer(struct qemu_alarm_timer *t)
1716 struct qemu_alarm_win32 *data = t->priv;
1718 timeKillEvent(data->timerId);
1719 timeEndPeriod(data->period);
1722 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1724 struct qemu_alarm_win32 *data = t->priv;
1725 uint64_t nearest_delta_us;
1727 if (!active_timers[QEMU_TIMER_REALTIME] &&
1728 !active_timers[QEMU_TIMER_VIRTUAL])
1729 return;
1731 nearest_delta_us = qemu_next_deadline_dyntick();
1732 nearest_delta_us /= 1000;
1734 timeKillEvent(data->timerId);
1736 data->timerId = timeSetEvent(1,
1737 data->period,
1738 host_alarm_handler,
1739 (DWORD)t,
1740 TIME_ONESHOT | TIME_PERIODIC);
1742 if (!data->timerId) {
1743 perror("Failed to re-arm win32 alarm timer");
1745 timeEndPeriod(data->period);
1746 exit(1);
1750 #endif /* _WIN32 */
1752 static int init_timer_alarm(void)
1754 struct qemu_alarm_timer *t = NULL;
1755 int i, err = -1;
1757 for (i = 0; alarm_timers[i].name; i++) {
1758 t = &alarm_timers[i];
1760 err = t->start(t);
1761 if (!err)
1762 break;
1765 if (err) {
1766 err = -ENOENT;
1767 goto fail;
1770 alarm_timer = t;
1772 return 0;
1774 fail:
1775 return err;
1778 static void quit_timers(void)
1780 alarm_timer->stop(alarm_timer);
1781 alarm_timer = NULL;
1784 /***********************************************************/
1785 /* host time/date access */
1786 void qemu_get_timedate(struct tm *tm, int offset)
1788 time_t ti;
1789 struct tm *ret;
1791 time(&ti);
1792 ti += offset;
1793 if (rtc_date_offset == -1) {
1794 if (rtc_utc)
1795 ret = gmtime(&ti);
1796 else
1797 ret = localtime(&ti);
1798 } else {
1799 ti -= rtc_date_offset;
1800 ret = gmtime(&ti);
1803 memcpy(tm, ret, sizeof(struct tm));
1806 int qemu_timedate_diff(struct tm *tm)
1808 time_t seconds;
1810 if (rtc_date_offset == -1)
1811 if (rtc_utc)
1812 seconds = mktimegm(tm);
1813 else
1814 seconds = mktime(tm);
1815 else
1816 seconds = mktimegm(tm) + rtc_date_offset;
1818 return seconds - time(NULL);
1821 #ifdef _WIN32
1822 static void socket_cleanup(void)
1824 WSACleanup();
1827 static int socket_init(void)
1829 WSADATA Data;
1830 int ret, err;
1832 ret = WSAStartup(MAKEWORD(2,2), &Data);
1833 if (ret != 0) {
1834 err = WSAGetLastError();
1835 fprintf(stderr, "WSAStartup: %d\n", err);
1836 return -1;
1838 atexit(socket_cleanup);
1839 return 0;
1841 #endif
1843 int get_next_param_value(char *buf, int buf_size,
1844 const char *tag, const char **pstr)
1846 const char *p;
1847 char option[128];
1849 p = *pstr;
1850 for(;;) {
1851 p = get_opt_name(option, sizeof(option), p, '=');
1852 if (*p != '=')
1853 break;
1854 p++;
1855 if (!strcmp(tag, option)) {
1856 *pstr = get_opt_value(buf, buf_size, p);
1857 if (**pstr == ',') {
1858 (*pstr)++;
1860 return strlen(buf);
1861 } else {
1862 p = get_opt_value(NULL, 0, p);
1864 if (*p != ',')
1865 break;
1866 p++;
1868 return 0;
1871 int get_param_value(char *buf, int buf_size,
1872 const char *tag, const char *str)
1874 return get_next_param_value(buf, buf_size, tag, &str);
1877 int check_params(char *buf, int buf_size,
1878 const char * const *params, const char *str)
1880 const char *p;
1881 int i;
1883 p = str;
1884 while (*p != '\0') {
1885 p = get_opt_name(buf, buf_size, p, '=');
1886 if (*p != '=') {
1887 return -1;
1889 p++;
1890 for (i = 0; params[i] != NULL; i++) {
1891 if (!strcmp(params[i], buf)) {
1892 break;
1895 if (params[i] == NULL) {
1896 return -1;
1898 p = get_opt_value(NULL, 0, p);
1899 if (*p != ',') {
1900 break;
1902 p++;
1904 return 0;
1907 /***********************************************************/
1908 /* Bluetooth support */
1909 static int nb_hcis;
1910 static int cur_hci;
1911 static struct HCIInfo *hci_table[MAX_NICS];
1913 static struct bt_vlan_s {
1914 struct bt_scatternet_s net;
1915 int id;
1916 struct bt_vlan_s *next;
1917 } *first_bt_vlan;
1919 /* find or alloc a new bluetooth "VLAN" */
1920 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1922 struct bt_vlan_s **pvlan, *vlan;
1923 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1924 if (vlan->id == id)
1925 return &vlan->net;
1927 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1928 vlan->id = id;
1929 pvlan = &first_bt_vlan;
1930 while (*pvlan != NULL)
1931 pvlan = &(*pvlan)->next;
1932 *pvlan = vlan;
1933 return &vlan->net;
1936 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1940 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1942 return -ENOTSUP;
1945 static struct HCIInfo null_hci = {
1946 .cmd_send = null_hci_send,
1947 .sco_send = null_hci_send,
1948 .acl_send = null_hci_send,
1949 .bdaddr_set = null_hci_addr_set,
1952 struct HCIInfo *qemu_next_hci(void)
1954 if (cur_hci == nb_hcis)
1955 return &null_hci;
1957 return hci_table[cur_hci++];
1960 static struct HCIInfo *hci_init(const char *str)
1962 char *endp;
1963 struct bt_scatternet_s *vlan = 0;
1965 if (!strcmp(str, "null"))
1966 /* null */
1967 return &null_hci;
1968 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1969 /* host[:hciN] */
1970 return bt_host_hci(str[4] ? str + 5 : "hci0");
1971 else if (!strncmp(str, "hci", 3)) {
1972 /* hci[,vlan=n] */
1973 if (str[3]) {
1974 if (!strncmp(str + 3, ",vlan=", 6)) {
1975 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1976 if (*endp)
1977 vlan = 0;
1979 } else
1980 vlan = qemu_find_bt_vlan(0);
1981 if (vlan)
1982 return bt_new_hci(vlan);
1985 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1987 return 0;
1990 static int bt_hci_parse(const char *str)
1992 struct HCIInfo *hci;
1993 bdaddr_t bdaddr;
1995 if (nb_hcis >= MAX_NICS) {
1996 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1997 return -1;
2000 hci = hci_init(str);
2001 if (!hci)
2002 return -1;
2004 bdaddr.b[0] = 0x52;
2005 bdaddr.b[1] = 0x54;
2006 bdaddr.b[2] = 0x00;
2007 bdaddr.b[3] = 0x12;
2008 bdaddr.b[4] = 0x34;
2009 bdaddr.b[5] = 0x56 + nb_hcis;
2010 hci->bdaddr_set(hci, bdaddr.b);
2012 hci_table[nb_hcis++] = hci;
2014 return 0;
2017 static void bt_vhci_add(int vlan_id)
2019 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2021 if (!vlan->slave)
2022 fprintf(stderr, "qemu: warning: adding a VHCI to "
2023 "an empty scatternet %i\n", vlan_id);
2025 bt_vhci_init(bt_new_hci(vlan));
2028 static struct bt_device_s *bt_device_add(const char *opt)
2030 struct bt_scatternet_s *vlan;
2031 int vlan_id = 0;
2032 char *endp = strstr(opt, ",vlan=");
2033 int len = (endp ? endp - opt : strlen(opt)) + 1;
2034 char devname[10];
2036 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2038 if (endp) {
2039 vlan_id = strtol(endp + 6, &endp, 0);
2040 if (*endp) {
2041 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2042 return 0;
2046 vlan = qemu_find_bt_vlan(vlan_id);
2048 if (!vlan->slave)
2049 fprintf(stderr, "qemu: warning: adding a slave device to "
2050 "an empty scatternet %i\n", vlan_id);
2052 if (!strcmp(devname, "keyboard"))
2053 return bt_keyboard_init(vlan);
2055 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2056 return 0;
2059 static int bt_parse(const char *opt)
2061 const char *endp, *p;
2062 int vlan;
2064 if (strstart(opt, "hci", &endp)) {
2065 if (!*endp || *endp == ',') {
2066 if (*endp)
2067 if (!strstart(endp, ",vlan=", 0))
2068 opt = endp + 1;
2070 return bt_hci_parse(opt);
2072 } else if (strstart(opt, "vhci", &endp)) {
2073 if (!*endp || *endp == ',') {
2074 if (*endp) {
2075 if (strstart(endp, ",vlan=", &p)) {
2076 vlan = strtol(p, (char **) &endp, 0);
2077 if (*endp) {
2078 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2079 return 1;
2081 } else {
2082 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2083 return 1;
2085 } else
2086 vlan = 0;
2088 bt_vhci_add(vlan);
2089 return 0;
2091 } else if (strstart(opt, "device:", &endp))
2092 return !bt_device_add(endp);
2094 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2095 return 1;
2098 /***********************************************************/
2099 /* QEMU Block devices */
2101 #define HD_ALIAS "index=%d,media=disk"
2102 #define CDROM_ALIAS "index=2,media=cdrom"
2103 #define FD_ALIAS "index=%d,if=floppy"
2104 #define PFLASH_ALIAS "if=pflash"
2105 #define MTD_ALIAS "if=mtd"
2106 #define SD_ALIAS "index=0,if=sd"
2108 static int drive_opt_get_free_idx(void)
2110 int index;
2112 for (index = 0; index < MAX_DRIVES; index++)
2113 if (!drives_opt[index].used) {
2114 drives_opt[index].used = 1;
2115 return index;
2118 return -1;
2121 static int drive_get_free_idx(void)
2123 int index;
2125 for (index = 0; index < MAX_DRIVES; index++)
2126 if (!drives_table[index].used) {
2127 drives_table[index].used = 1;
2128 return index;
2131 return -1;
2134 int drive_add(const char *file, const char *fmt, ...)
2136 va_list ap;
2137 int index = drive_opt_get_free_idx();
2139 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2140 fprintf(stderr, "qemu: too many drives\n");
2141 return -1;
2144 drives_opt[index].file = file;
2145 va_start(ap, fmt);
2146 vsnprintf(drives_opt[index].opt,
2147 sizeof(drives_opt[0].opt), fmt, ap);
2148 va_end(ap);
2150 nb_drives_opt++;
2151 return index;
2154 void drive_remove(int index)
2156 drives_opt[index].used = 0;
2157 nb_drives_opt--;
2160 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2162 int index;
2164 /* seek interface, bus and unit */
2166 for (index = 0; index < MAX_DRIVES; index++)
2167 if (drives_table[index].type == type &&
2168 drives_table[index].bus == bus &&
2169 drives_table[index].unit == unit &&
2170 drives_table[index].used)
2171 return index;
2173 return -1;
2176 int drive_get_max_bus(BlockInterfaceType type)
2178 int max_bus;
2179 int index;
2181 max_bus = -1;
2182 for (index = 0; index < nb_drives; index++) {
2183 if(drives_table[index].type == type &&
2184 drives_table[index].bus > max_bus)
2185 max_bus = drives_table[index].bus;
2187 return max_bus;
2190 const char *drive_get_serial(BlockDriverState *bdrv)
2192 int index;
2194 for (index = 0; index < nb_drives; index++)
2195 if (drives_table[index].bdrv == bdrv)
2196 return drives_table[index].serial;
2198 return "\0";
2201 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2203 int index;
2205 for (index = 0; index < nb_drives; index++)
2206 if (drives_table[index].bdrv == bdrv)
2207 return drives_table[index].onerror;
2209 return BLOCK_ERR_STOP_ENOSPC;
2212 static void bdrv_format_print(void *opaque, const char *name)
2214 fprintf(stderr, " %s", name);
2217 void drive_uninit(BlockDriverState *bdrv)
2219 int i;
2221 for (i = 0; i < MAX_DRIVES; i++)
2222 if (drives_table[i].bdrv == bdrv) {
2223 drives_table[i].bdrv = NULL;
2224 drives_table[i].used = 0;
2225 drive_remove(drives_table[i].drive_opt_idx);
2226 nb_drives--;
2227 break;
2231 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2233 char buf[128];
2234 char file[1024];
2235 char devname[128];
2236 char serial[21];
2237 const char *mediastr = "";
2238 BlockInterfaceType type;
2239 enum { MEDIA_DISK, MEDIA_CDROM } media;
2240 int bus_id, unit_id;
2241 int cyls, heads, secs, translation;
2242 BlockDriverState *bdrv;
2243 BlockDriver *drv = NULL;
2244 QEMUMachine *machine = opaque;
2245 int max_devs;
2246 int index;
2247 int cache;
2248 int bdrv_flags, onerror;
2249 const char *devaddr;
2250 int drives_table_idx;
2251 char *str = arg->opt;
2252 static const char * const params[] = { "bus", "unit", "if", "index",
2253 "cyls", "heads", "secs", "trans",
2254 "media", "snapshot", "file",
2255 "cache", "format", "serial",
2256 "werror", "addr",
2257 "boot",
2258 NULL };
2260 if (check_params(buf, sizeof(buf), params, str) < 0) {
2261 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2262 buf, str);
2263 return -1;
2266 file[0] = 0;
2267 cyls = heads = secs = 0;
2268 bus_id = 0;
2269 unit_id = -1;
2270 translation = BIOS_ATA_TRANSLATION_AUTO;
2271 index = -1;
2272 cache = 3;
2274 if (machine->use_scsi) {
2275 type = IF_SCSI;
2276 max_devs = MAX_SCSI_DEVS;
2277 pstrcpy(devname, sizeof(devname), "scsi");
2278 } else {
2279 type = IF_IDE;
2280 max_devs = MAX_IDE_DEVS;
2281 pstrcpy(devname, sizeof(devname), "ide");
2283 media = MEDIA_DISK;
2285 /* extract parameters */
2287 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2288 bus_id = strtol(buf, NULL, 0);
2289 if (bus_id < 0) {
2290 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2291 return -1;
2295 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2296 unit_id = strtol(buf, NULL, 0);
2297 if (unit_id < 0) {
2298 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2299 return -1;
2303 if (get_param_value(buf, sizeof(buf), "if", str)) {
2304 pstrcpy(devname, sizeof(devname), buf);
2305 if (!strcmp(buf, "ide")) {
2306 type = IF_IDE;
2307 max_devs = MAX_IDE_DEVS;
2308 } else if (!strcmp(buf, "scsi")) {
2309 type = IF_SCSI;
2310 max_devs = MAX_SCSI_DEVS;
2311 } else if (!strcmp(buf, "floppy")) {
2312 type = IF_FLOPPY;
2313 max_devs = 0;
2314 } else if (!strcmp(buf, "pflash")) {
2315 type = IF_PFLASH;
2316 max_devs = 0;
2317 } else if (!strcmp(buf, "mtd")) {
2318 type = IF_MTD;
2319 max_devs = 0;
2320 } else if (!strcmp(buf, "sd")) {
2321 type = IF_SD;
2322 max_devs = 0;
2323 } else if (!strcmp(buf, "virtio")) {
2324 type = IF_VIRTIO;
2325 max_devs = 0;
2326 } else if (!strcmp(buf, "xen")) {
2327 type = IF_XEN;
2328 max_devs = 0;
2329 } else {
2330 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2331 return -1;
2335 if (get_param_value(buf, sizeof(buf), "index", str)) {
2336 index = strtol(buf, NULL, 0);
2337 if (index < 0) {
2338 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2339 return -1;
2343 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2344 cyls = strtol(buf, NULL, 0);
2347 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2348 heads = strtol(buf, NULL, 0);
2351 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2352 secs = strtol(buf, NULL, 0);
2355 if (cyls || heads || secs) {
2356 if (cyls < 1 || cyls > 16383) {
2357 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2358 return -1;
2360 if (heads < 1 || heads > 16) {
2361 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2362 return -1;
2364 if (secs < 1 || secs > 63) {
2365 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2366 return -1;
2370 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2371 if (!cyls) {
2372 fprintf(stderr,
2373 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2374 str);
2375 return -1;
2377 if (!strcmp(buf, "none"))
2378 translation = BIOS_ATA_TRANSLATION_NONE;
2379 else if (!strcmp(buf, "lba"))
2380 translation = BIOS_ATA_TRANSLATION_LBA;
2381 else if (!strcmp(buf, "auto"))
2382 translation = BIOS_ATA_TRANSLATION_AUTO;
2383 else {
2384 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2385 return -1;
2389 if (get_param_value(buf, sizeof(buf), "media", str)) {
2390 if (!strcmp(buf, "disk")) {
2391 media = MEDIA_DISK;
2392 } else if (!strcmp(buf, "cdrom")) {
2393 if (cyls || secs || heads) {
2394 fprintf(stderr,
2395 "qemu: '%s' invalid physical CHS format\n", str);
2396 return -1;
2398 media = MEDIA_CDROM;
2399 } else {
2400 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2401 return -1;
2405 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2406 if (!strcmp(buf, "on"))
2407 snapshot = 1;
2408 else if (!strcmp(buf, "off"))
2409 snapshot = 0;
2410 else {
2411 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2412 return -1;
2416 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2417 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2418 cache = 0;
2419 else if (!strcmp(buf, "writethrough"))
2420 cache = 1;
2421 else if (!strcmp(buf, "writeback"))
2422 cache = 2;
2423 else {
2424 fprintf(stderr, "qemu: invalid cache option\n");
2425 return -1;
2429 if (get_param_value(buf, sizeof(buf), "format", str)) {
2430 if (strcmp(buf, "?") == 0) {
2431 fprintf(stderr, "qemu: Supported formats:");
2432 bdrv_iterate_format(bdrv_format_print, NULL);
2433 fprintf(stderr, "\n");
2434 return -1;
2436 drv = bdrv_find_format(buf);
2437 if (!drv) {
2438 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2439 return -1;
2443 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2444 if (!strcmp(buf, "on")) {
2445 if (extboot_drive != -1) {
2446 fprintf(stderr, "qemu: two bootable drives specified\n");
2447 return -1;
2449 extboot_drive = nb_drives;
2450 } else if (strcmp(buf, "off")) {
2451 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2452 return -1;
2456 if (arg->file == NULL)
2457 get_param_value(file, sizeof(file), "file", str);
2458 else
2459 pstrcpy(file, sizeof(file), arg->file);
2461 if (!get_param_value(serial, sizeof(serial), "serial", str))
2462 memset(serial, 0, sizeof(serial));
2464 onerror = BLOCK_ERR_STOP_ENOSPC;
2465 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2466 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2467 fprintf(stderr, "werror is no supported by this format\n");
2468 return -1;
2470 if (!strcmp(buf, "ignore"))
2471 onerror = BLOCK_ERR_IGNORE;
2472 else if (!strcmp(buf, "enospc"))
2473 onerror = BLOCK_ERR_STOP_ENOSPC;
2474 else if (!strcmp(buf, "stop"))
2475 onerror = BLOCK_ERR_STOP_ANY;
2476 else if (!strcmp(buf, "report"))
2477 onerror = BLOCK_ERR_REPORT;
2478 else {
2479 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2480 return -1;
2484 devaddr = NULL;
2485 if (get_param_value(buf, sizeof(buf), "addr", str)) {
2486 if (type != IF_VIRTIO) {
2487 fprintf(stderr, "addr is not supported by in '%s'\n", str);
2488 return -1;
2490 devaddr = strdup(buf);
2493 /* compute bus and unit according index */
2495 if (index != -1) {
2496 if (bus_id != 0 || unit_id != -1) {
2497 fprintf(stderr,
2498 "qemu: '%s' index cannot be used with bus and unit\n", str);
2499 return -1;
2501 if (max_devs == 0)
2503 unit_id = index;
2504 bus_id = 0;
2505 } else {
2506 unit_id = index % max_devs;
2507 bus_id = index / max_devs;
2511 /* if user doesn't specify a unit_id,
2512 * try to find the first free
2515 if (unit_id == -1) {
2516 unit_id = 0;
2517 while (drive_get_index(type, bus_id, unit_id) != -1) {
2518 unit_id++;
2519 if (max_devs && unit_id >= max_devs) {
2520 unit_id -= max_devs;
2521 bus_id++;
2526 /* check unit id */
2528 if (max_devs && unit_id >= max_devs) {
2529 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2530 str, unit_id, max_devs - 1);
2531 return -1;
2535 * ignore multiple definitions
2538 if (drive_get_index(type, bus_id, unit_id) != -1)
2539 return -2;
2541 /* init */
2543 if (type == IF_IDE || type == IF_SCSI)
2544 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2545 if (max_devs)
2546 snprintf(buf, sizeof(buf), "%s%i%s%i",
2547 devname, bus_id, mediastr, unit_id);
2548 else
2549 snprintf(buf, sizeof(buf), "%s%s%i",
2550 devname, mediastr, unit_id);
2551 bdrv = bdrv_new(buf);
2552 drives_table_idx = drive_get_free_idx();
2553 drives_table[drives_table_idx].bdrv = bdrv;
2554 drives_table[drives_table_idx].devaddr = devaddr;
2555 drives_table[drives_table_idx].type = type;
2556 drives_table[drives_table_idx].bus = bus_id;
2557 drives_table[drives_table_idx].unit = unit_id;
2558 drives_table[drives_table_idx].onerror = onerror;
2559 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2560 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2561 nb_drives++;
2563 switch(type) {
2564 case IF_IDE:
2565 case IF_SCSI:
2566 case IF_XEN:
2567 switch(media) {
2568 case MEDIA_DISK:
2569 if (cyls != 0) {
2570 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2571 bdrv_set_translation_hint(bdrv, translation);
2573 break;
2574 case MEDIA_CDROM:
2575 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2576 break;
2578 break;
2579 case IF_SD:
2580 /* FIXME: This isn't really a floppy, but it's a reasonable
2581 approximation. */
2582 case IF_FLOPPY:
2583 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2584 break;
2585 case IF_PFLASH:
2586 case IF_MTD:
2587 case IF_VIRTIO:
2588 break;
2589 case IF_COUNT:
2590 abort();
2592 if (!file[0])
2593 return -2;
2594 bdrv_flags = 0;
2595 if (snapshot) {
2596 bdrv_flags |= BDRV_O_SNAPSHOT;
2597 cache = 2; /* always use write-back with snapshot */
2599 if (cache == 0) /* no caching */
2600 bdrv_flags |= BDRV_O_NOCACHE;
2601 else if (cache == 2) /* write-back */
2602 bdrv_flags |= BDRV_O_CACHE_WB;
2603 else if (cache == 3) /* not specified */
2604 bdrv_flags |= BDRV_O_CACHE_DEF;
2605 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2606 fprintf(stderr, "qemu: could not open disk image %s\n",
2607 file);
2608 return -1;
2610 if (bdrv_key_required(bdrv))
2611 autostart = 0;
2612 return drives_table_idx;
2615 static void numa_add(const char *optarg)
2617 char option[128];
2618 char *endptr;
2619 unsigned long long value, endvalue;
2620 int nodenr;
2622 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2623 if (!strcmp(option, "node")) {
2624 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2625 nodenr = nb_numa_nodes;
2626 } else {
2627 nodenr = strtoull(option, NULL, 10);
2630 if (get_param_value(option, 128, "mem", optarg) == 0) {
2631 node_mem[nodenr] = 0;
2632 } else {
2633 value = strtoull(option, &endptr, 0);
2634 switch (*endptr) {
2635 case 0: case 'M': case 'm':
2636 value <<= 20;
2637 break;
2638 case 'G': case 'g':
2639 value <<= 30;
2640 break;
2642 node_mem[nodenr] = value;
2644 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2645 node_cpumask[nodenr] = 0;
2646 } else {
2647 value = strtoull(option, &endptr, 10);
2648 if (value >= 64) {
2649 value = 63;
2650 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2651 } else {
2652 if (*endptr == '-') {
2653 endvalue = strtoull(endptr+1, &endptr, 10);
2654 if (endvalue >= 63) {
2655 endvalue = 62;
2656 fprintf(stderr,
2657 "only 63 CPUs in NUMA mode supported.\n");
2659 value = (1 << (endvalue + 1)) - (1 << value);
2660 } else {
2661 value = 1 << value;
2664 node_cpumask[nodenr] = value;
2666 nb_numa_nodes++;
2668 return;
2671 /***********************************************************/
2672 /* USB devices */
2674 static USBPort *used_usb_ports;
2675 static USBPort *free_usb_ports;
2677 /* ??? Maybe change this to register a hub to keep track of the topology. */
2678 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2679 usb_attachfn attach)
2681 port->opaque = opaque;
2682 port->index = index;
2683 port->attach = attach;
2684 port->next = free_usb_ports;
2685 free_usb_ports = port;
2688 int usb_device_add_dev(USBDevice *dev)
2690 USBPort *port;
2692 /* Find a USB port to add the device to. */
2693 port = free_usb_ports;
2694 if (!port->next) {
2695 USBDevice *hub;
2697 /* Create a new hub and chain it on. */
2698 free_usb_ports = NULL;
2699 port->next = used_usb_ports;
2700 used_usb_ports = port;
2702 hub = usb_hub_init(VM_USB_HUB_SIZE);
2703 usb_attach(port, hub);
2704 port = free_usb_ports;
2707 free_usb_ports = port->next;
2708 port->next = used_usb_ports;
2709 used_usb_ports = port;
2710 usb_attach(port, dev);
2711 return 0;
2714 static void usb_msd_password_cb(void *opaque, int err)
2716 USBDevice *dev = opaque;
2718 if (!err)
2719 usb_device_add_dev(dev);
2720 else
2721 dev->handle_destroy(dev);
2724 static int usb_device_add(const char *devname, int is_hotplug)
2726 const char *p;
2727 USBDevice *dev;
2729 if (!free_usb_ports)
2730 return -1;
2732 if (strstart(devname, "host:", &p)) {
2733 dev = usb_host_device_open(p);
2734 } else if (!strcmp(devname, "mouse")) {
2735 dev = usb_mouse_init();
2736 } else if (!strcmp(devname, "tablet")) {
2737 dev = usb_tablet_init();
2738 } else if (!strcmp(devname, "keyboard")) {
2739 dev = usb_keyboard_init();
2740 } else if (strstart(devname, "disk:", &p)) {
2741 BlockDriverState *bs;
2743 dev = usb_msd_init(p);
2744 if (!dev)
2745 return -1;
2746 bs = usb_msd_get_bdrv(dev);
2747 if (bdrv_key_required(bs)) {
2748 autostart = 0;
2749 if (is_hotplug) {
2750 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2751 dev);
2752 return 0;
2755 } else if (!strcmp(devname, "wacom-tablet")) {
2756 dev = usb_wacom_init();
2757 } else if (strstart(devname, "serial:", &p)) {
2758 dev = usb_serial_init(p);
2759 #ifdef CONFIG_BRLAPI
2760 } else if (!strcmp(devname, "braille")) {
2761 dev = usb_baum_init();
2762 #endif
2763 } else if (strstart(devname, "net:", &p)) {
2764 int nic = nb_nics;
2766 if (net_client_init(NULL, "nic", p) < 0)
2767 return -1;
2768 nd_table[nic].model = "usb";
2769 dev = usb_net_init(&nd_table[nic]);
2770 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2771 dev = usb_bt_init(devname[2] ? hci_init(p) :
2772 bt_new_hci(qemu_find_bt_vlan(0)));
2773 } else {
2774 return -1;
2776 if (!dev)
2777 return -1;
2779 return usb_device_add_dev(dev);
2782 int usb_device_del_addr(int bus_num, int addr)
2784 USBPort *port;
2785 USBPort **lastp;
2786 USBDevice *dev;
2788 if (!used_usb_ports)
2789 return -1;
2791 if (bus_num != 0)
2792 return -1;
2794 lastp = &used_usb_ports;
2795 port = used_usb_ports;
2796 while (port && port->dev->addr != addr) {
2797 lastp = &port->next;
2798 port = port->next;
2801 if (!port)
2802 return -1;
2804 dev = port->dev;
2805 *lastp = port->next;
2806 usb_attach(port, NULL);
2807 dev->handle_destroy(dev);
2808 port->next = free_usb_ports;
2809 free_usb_ports = port;
2810 return 0;
2813 static int usb_device_del(const char *devname)
2815 int bus_num, addr;
2816 const char *p;
2818 if (strstart(devname, "host:", &p))
2819 return usb_host_device_close(p);
2821 if (!used_usb_ports)
2822 return -1;
2824 p = strchr(devname, '.');
2825 if (!p)
2826 return -1;
2827 bus_num = strtoul(devname, NULL, 0);
2828 addr = strtoul(p + 1, NULL, 0);
2830 return usb_device_del_addr(bus_num, addr);
2833 void do_usb_add(Monitor *mon, const char *devname)
2835 usb_device_add(devname, 1);
2838 void do_usb_del(Monitor *mon, const char *devname)
2840 usb_device_del(devname);
2843 void usb_info(Monitor *mon)
2845 USBDevice *dev;
2846 USBPort *port;
2847 const char *speed_str;
2849 if (!usb_enabled) {
2850 monitor_printf(mon, "USB support not enabled\n");
2851 return;
2854 for (port = used_usb_ports; port; port = port->next) {
2855 dev = port->dev;
2856 if (!dev)
2857 continue;
2858 switch(dev->speed) {
2859 case USB_SPEED_LOW:
2860 speed_str = "1.5";
2861 break;
2862 case USB_SPEED_FULL:
2863 speed_str = "12";
2864 break;
2865 case USB_SPEED_HIGH:
2866 speed_str = "480";
2867 break;
2868 default:
2869 speed_str = "?";
2870 break;
2872 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2873 0, dev->addr, speed_str, dev->devname);
2877 /***********************************************************/
2878 /* PCMCIA/Cardbus */
2880 static struct pcmcia_socket_entry_s {
2881 PCMCIASocket *socket;
2882 struct pcmcia_socket_entry_s *next;
2883 } *pcmcia_sockets = 0;
2885 void pcmcia_socket_register(PCMCIASocket *socket)
2887 struct pcmcia_socket_entry_s *entry;
2889 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2890 entry->socket = socket;
2891 entry->next = pcmcia_sockets;
2892 pcmcia_sockets = entry;
2895 void pcmcia_socket_unregister(PCMCIASocket *socket)
2897 struct pcmcia_socket_entry_s *entry, **ptr;
2899 ptr = &pcmcia_sockets;
2900 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2901 if (entry->socket == socket) {
2902 *ptr = entry->next;
2903 qemu_free(entry);
2907 void pcmcia_info(Monitor *mon)
2909 struct pcmcia_socket_entry_s *iter;
2911 if (!pcmcia_sockets)
2912 monitor_printf(mon, "No PCMCIA sockets\n");
2914 for (iter = pcmcia_sockets; iter; iter = iter->next)
2915 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2916 iter->socket->attached ? iter->socket->card_string :
2917 "Empty");
2920 /***********************************************************/
2921 /* register display */
2923 struct DisplayAllocator default_allocator = {
2924 defaultallocator_create_displaysurface,
2925 defaultallocator_resize_displaysurface,
2926 defaultallocator_free_displaysurface
2929 void register_displaystate(DisplayState *ds)
2931 DisplayState **s;
2932 s = &display_state;
2933 while (*s != NULL)
2934 s = &(*s)->next;
2935 ds->next = NULL;
2936 *s = ds;
2939 DisplayState *get_displaystate(void)
2941 return display_state;
2944 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2946 if(ds->allocator == &default_allocator) ds->allocator = da;
2947 return ds->allocator;
2950 /* dumb display */
2952 static void dumb_display_init(void)
2954 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2955 ds->allocator = &default_allocator;
2956 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2957 register_displaystate(ds);
2960 /***********************************************************/
2961 /* I/O handling */
2963 typedef struct IOHandlerRecord {
2964 int fd;
2965 IOCanRWHandler *fd_read_poll;
2966 IOHandler *fd_read;
2967 IOHandler *fd_write;
2968 int deleted;
2969 void *opaque;
2970 /* temporary data */
2971 struct pollfd *ufd;
2972 struct IOHandlerRecord *next;
2973 } IOHandlerRecord;
2975 static IOHandlerRecord *first_io_handler;
2977 /* XXX: fd_read_poll should be suppressed, but an API change is
2978 necessary in the character devices to suppress fd_can_read(). */
2979 int qemu_set_fd_handler2(int fd,
2980 IOCanRWHandler *fd_read_poll,
2981 IOHandler *fd_read,
2982 IOHandler *fd_write,
2983 void *opaque)
2985 IOHandlerRecord **pioh, *ioh;
2987 if (!fd_read && !fd_write) {
2988 pioh = &first_io_handler;
2989 for(;;) {
2990 ioh = *pioh;
2991 if (ioh == NULL)
2992 break;
2993 if (ioh->fd == fd) {
2994 ioh->deleted = 1;
2995 break;
2997 pioh = &ioh->next;
2999 } else {
3000 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3001 if (ioh->fd == fd)
3002 goto found;
3004 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3005 ioh->next = first_io_handler;
3006 first_io_handler = ioh;
3007 found:
3008 ioh->fd = fd;
3009 ioh->fd_read_poll = fd_read_poll;
3010 ioh->fd_read = fd_read;
3011 ioh->fd_write = fd_write;
3012 ioh->opaque = opaque;
3013 ioh->deleted = 0;
3015 qemu_notify_event();
3016 return 0;
3019 int qemu_set_fd_handler(int fd,
3020 IOHandler *fd_read,
3021 IOHandler *fd_write,
3022 void *opaque)
3024 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3027 #ifdef _WIN32
3028 /***********************************************************/
3029 /* Polling handling */
3031 typedef struct PollingEntry {
3032 PollingFunc *func;
3033 void *opaque;
3034 struct PollingEntry *next;
3035 } PollingEntry;
3037 static PollingEntry *first_polling_entry;
3039 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3041 PollingEntry **ppe, *pe;
3042 pe = qemu_mallocz(sizeof(PollingEntry));
3043 pe->func = func;
3044 pe->opaque = opaque;
3045 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3046 *ppe = pe;
3047 return 0;
3050 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3052 PollingEntry **ppe, *pe;
3053 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3054 pe = *ppe;
3055 if (pe->func == func && pe->opaque == opaque) {
3056 *ppe = pe->next;
3057 qemu_free(pe);
3058 break;
3063 /***********************************************************/
3064 /* Wait objects support */
3065 typedef struct WaitObjects {
3066 int num;
3067 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3068 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3069 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3070 } WaitObjects;
3072 static WaitObjects wait_objects = {0};
3074 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3076 WaitObjects *w = &wait_objects;
3078 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3079 return -1;
3080 w->events[w->num] = handle;
3081 w->func[w->num] = func;
3082 w->opaque[w->num] = opaque;
3083 w->num++;
3084 return 0;
3087 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3089 int i, found;
3090 WaitObjects *w = &wait_objects;
3092 found = 0;
3093 for (i = 0; i < w->num; i++) {
3094 if (w->events[i] == handle)
3095 found = 1;
3096 if (found) {
3097 w->events[i] = w->events[i + 1];
3098 w->func[i] = w->func[i + 1];
3099 w->opaque[i] = w->opaque[i + 1];
3102 if (found)
3103 w->num--;
3105 #endif
3107 /***********************************************************/
3108 /* ram save/restore */
3110 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3112 int v;
3114 v = qemu_get_byte(f);
3115 switch(v) {
3116 case 0:
3117 if (qemu_get_buffer(f, buf, len) != len)
3118 return -EIO;
3119 break;
3120 case 1:
3121 v = qemu_get_byte(f);
3122 memset(buf, v, len);
3123 break;
3124 default:
3125 return -EINVAL;
3128 if (qemu_file_has_error(f))
3129 return -EIO;
3131 return 0;
3134 static int ram_load_v1(QEMUFile *f, void *opaque)
3136 int ret;
3137 ram_addr_t i;
3139 if (qemu_get_be32(f) != last_ram_offset)
3140 return -EINVAL;
3141 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
3142 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3143 continue;
3144 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
3145 if (ret)
3146 return ret;
3148 return 0;
3151 #define BDRV_HASH_BLOCK_SIZE 1024
3152 #define IOBUF_SIZE 4096
3153 #define RAM_CBLOCK_MAGIC 0xfabe
3155 typedef struct RamDecompressState {
3156 z_stream zstream;
3157 QEMUFile *f;
3158 uint8_t buf[IOBUF_SIZE];
3159 } RamDecompressState;
3161 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3163 int ret;
3164 memset(s, 0, sizeof(*s));
3165 s->f = f;
3166 ret = inflateInit(&s->zstream);
3167 if (ret != Z_OK)
3168 return -1;
3169 return 0;
3172 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3174 int ret, clen;
3176 s->zstream.avail_out = len;
3177 s->zstream.next_out = buf;
3178 while (s->zstream.avail_out > 0) {
3179 if (s->zstream.avail_in == 0) {
3180 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3181 return -1;
3182 clen = qemu_get_be16(s->f);
3183 if (clen > IOBUF_SIZE)
3184 return -1;
3185 qemu_get_buffer(s->f, s->buf, clen);
3186 s->zstream.avail_in = clen;
3187 s->zstream.next_in = s->buf;
3189 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3190 if (ret != Z_OK && ret != Z_STREAM_END) {
3191 return -1;
3194 return 0;
3197 static void ram_decompress_close(RamDecompressState *s)
3199 inflateEnd(&s->zstream);
3202 #define RAM_SAVE_FLAG_FULL 0x01
3203 #define RAM_SAVE_FLAG_COMPRESS 0x02
3204 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3205 #define RAM_SAVE_FLAG_PAGE 0x08
3206 #define RAM_SAVE_FLAG_EOS 0x10
3208 static int is_dup_page(uint8_t *page, uint8_t ch)
3210 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3211 uint32_t *array = (uint32_t *)page;
3212 int i;
3214 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3215 if (array[i] != val)
3216 return 0;
3219 return 1;
3222 static int ram_save_block(QEMUFile *f)
3224 static ram_addr_t current_addr = 0;
3225 ram_addr_t saved_addr = current_addr;
3226 ram_addr_t addr = 0;
3227 int found = 0;
3229 while (addr < last_ram_offset) {
3230 if (kvm_enabled() && current_addr == 0) {
3231 int r;
3232 r = kvm_update_dirty_pages_log();
3233 if (r) {
3234 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3235 qemu_file_set_error(f);
3236 return 0;
3239 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3240 uint8_t *p;
3242 cpu_physical_memory_reset_dirty(current_addr,
3243 current_addr + TARGET_PAGE_SIZE,
3244 MIGRATION_DIRTY_FLAG);
3246 p = qemu_get_ram_ptr(current_addr);
3248 if (is_dup_page(p, *p)) {
3249 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3250 qemu_put_byte(f, *p);
3251 } else {
3252 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3253 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3256 found = 1;
3257 break;
3259 addr += TARGET_PAGE_SIZE;
3260 current_addr = (saved_addr + addr) % last_ram_offset;
3263 return found;
3266 static uint64_t bytes_transferred = 0;
3268 static ram_addr_t ram_save_remaining(void)
3270 ram_addr_t addr;
3271 ram_addr_t count = 0;
3273 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3274 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3275 count++;
3278 return count;
3281 uint64_t ram_bytes_remaining(void)
3283 return ram_save_remaining() * TARGET_PAGE_SIZE;
3286 uint64_t ram_bytes_transferred(void)
3288 return bytes_transferred;
3291 uint64_t ram_bytes_total(void)
3293 return last_ram_offset;
3296 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3298 ram_addr_t addr;
3299 uint64_t bytes_transferred_last;
3300 double bwidth = 0;
3301 uint64_t expected_time = 0;
3303 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3304 qemu_file_set_error(f);
3305 return 0;
3308 if (stage == 1) {
3309 /* Make sure all dirty bits are set */
3310 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3311 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3312 cpu_physical_memory_set_dirty(addr);
3315 /* Enable dirty memory tracking */
3316 cpu_physical_memory_set_dirty_tracking(1);
3318 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3321 bytes_transferred_last = bytes_transferred;
3322 bwidth = get_clock();
3324 while (!qemu_file_rate_limit(f)) {
3325 int ret;
3327 ret = ram_save_block(f);
3328 bytes_transferred += ret * TARGET_PAGE_SIZE;
3329 if (ret == 0) /* no more blocks */
3330 break;
3333 bwidth = get_clock() - bwidth;
3334 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3336 /* if we haven't transferred anything this round, force expected_time to a
3337 * a very high value, but without crashing */
3338 if (bwidth == 0)
3339 bwidth = 0.000001;
3341 /* try transferring iterative blocks of memory */
3343 if (stage == 3) {
3345 /* flush all remaining blocks regardless of rate limiting */
3346 while (ram_save_block(f) != 0) {
3347 bytes_transferred += TARGET_PAGE_SIZE;
3349 cpu_physical_memory_set_dirty_tracking(0);
3352 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3354 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3356 return (stage == 2) && (expected_time <= migrate_max_downtime());
3359 static int ram_load_dead(QEMUFile *f, void *opaque)
3361 RamDecompressState s1, *s = &s1;
3362 uint8_t buf[10];
3363 ram_addr_t i;
3365 if (ram_decompress_open(s, f) < 0)
3366 return -EINVAL;
3367 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3368 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3369 continue;
3370 if (ram_decompress_buf(s, buf, 1) < 0) {
3371 fprintf(stderr, "Error while reading ram block header\n");
3372 goto error;
3374 if (buf[0] == 0) {
3375 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3376 BDRV_HASH_BLOCK_SIZE) < 0) {
3377 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3378 goto error;
3380 } else {
3381 error:
3382 printf("Error block header\n");
3383 return -EINVAL;
3386 ram_decompress_close(s);
3388 return 0;
3391 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3393 ram_addr_t addr;
3394 int flags;
3396 if (version_id == 1)
3397 return ram_load_v1(f, opaque);
3399 if (version_id == 2) {
3400 if (qemu_get_be32(f) != last_ram_offset)
3401 return -EINVAL;
3402 return ram_load_dead(f, opaque);
3405 if (version_id != 3)
3406 return -EINVAL;
3408 do {
3409 addr = qemu_get_be64(f);
3411 flags = addr & ~TARGET_PAGE_MASK;
3412 addr &= TARGET_PAGE_MASK;
3414 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3415 if (addr != last_ram_offset)
3416 return -EINVAL;
3419 if (flags & RAM_SAVE_FLAG_FULL) {
3420 if (ram_load_dead(f, opaque) < 0)
3421 return -EINVAL;
3424 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3425 uint8_t ch = qemu_get_byte(f);
3426 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3427 #ifndef _WIN32
3428 if (ch == 0 &&
3429 (!kvm_enabled() || kvm_has_sync_mmu())) {
3430 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3432 #endif
3433 } else if (flags & RAM_SAVE_FLAG_PAGE)
3434 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3435 } while (!(flags & RAM_SAVE_FLAG_EOS));
3437 return 0;
3440 void qemu_service_io(void)
3442 qemu_notify_event();
3445 /***********************************************************/
3446 /* bottom halves (can be seen as timers which expire ASAP) */
3448 struct QEMUBH {
3449 QEMUBHFunc *cb;
3450 void *opaque;
3451 int scheduled;
3452 int idle;
3453 int deleted;
3454 QEMUBH *next;
3457 static QEMUBH *first_bh = NULL;
3459 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3461 QEMUBH *bh;
3462 bh = qemu_mallocz(sizeof(QEMUBH));
3463 bh->cb = cb;
3464 bh->opaque = opaque;
3465 bh->next = first_bh;
3466 first_bh = bh;
3467 return bh;
3470 int qemu_bh_poll(void)
3472 QEMUBH *bh, **bhp;
3473 int ret;
3475 ret = 0;
3476 for (bh = first_bh; bh; bh = bh->next) {
3477 if (!bh->deleted && bh->scheduled) {
3478 bh->scheduled = 0;
3479 if (!bh->idle)
3480 ret = 1;
3481 bh->idle = 0;
3482 bh->cb(bh->opaque);
3486 /* remove deleted bhs */
3487 bhp = &first_bh;
3488 while (*bhp) {
3489 bh = *bhp;
3490 if (bh->deleted) {
3491 *bhp = bh->next;
3492 qemu_free(bh);
3493 } else
3494 bhp = &bh->next;
3497 return ret;
3500 void qemu_bh_schedule_idle(QEMUBH *bh)
3502 if (bh->scheduled)
3503 return;
3504 bh->scheduled = 1;
3505 bh->idle = 1;
3508 void qemu_bh_schedule(QEMUBH *bh)
3510 if (bh->scheduled)
3511 return;
3512 bh->scheduled = 1;
3513 bh->idle = 0;
3514 /* stop the currently executing CPU to execute the BH ASAP */
3515 qemu_notify_event();
3518 void qemu_bh_cancel(QEMUBH *bh)
3520 bh->scheduled = 0;
3523 void qemu_bh_delete(QEMUBH *bh)
3525 bh->scheduled = 0;
3526 bh->deleted = 1;
3529 static void qemu_bh_update_timeout(int *timeout)
3531 QEMUBH *bh;
3533 for (bh = first_bh; bh; bh = bh->next) {
3534 if (!bh->deleted && bh->scheduled) {
3535 if (bh->idle) {
3536 /* idle bottom halves will be polled at least
3537 * every 10ms */
3538 *timeout = MIN(10, *timeout);
3539 } else {
3540 /* non-idle bottom halves will be executed
3541 * immediately */
3542 *timeout = 0;
3543 break;
3549 /***********************************************************/
3550 /* machine registration */
3552 static QEMUMachine *first_machine = NULL;
3553 QEMUMachine *current_machine = NULL;
3555 int qemu_register_machine(QEMUMachine *m)
3557 QEMUMachine **pm;
3558 pm = &first_machine;
3559 while (*pm != NULL)
3560 pm = &(*pm)->next;
3561 m->next = NULL;
3562 *pm = m;
3563 return 0;
3566 static QEMUMachine *find_machine(const char *name)
3568 QEMUMachine *m;
3570 for(m = first_machine; m != NULL; m = m->next) {
3571 if (!strcmp(m->name, name))
3572 return m;
3574 return NULL;
3577 static QEMUMachine *find_default_machine(void)
3579 QEMUMachine *m;
3581 for(m = first_machine; m != NULL; m = m->next) {
3582 if (m->is_default) {
3583 return m;
3586 return NULL;
3589 /***********************************************************/
3590 /* main execution loop */
3592 static void gui_update(void *opaque)
3594 uint64_t interval = GUI_REFRESH_INTERVAL;
3595 DisplayState *ds = opaque;
3596 DisplayChangeListener *dcl = ds->listeners;
3598 dpy_refresh(ds);
3600 while (dcl != NULL) {
3601 if (dcl->gui_timer_interval &&
3602 dcl->gui_timer_interval < interval)
3603 interval = dcl->gui_timer_interval;
3604 dcl = dcl->next;
3606 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3609 static void nographic_update(void *opaque)
3611 uint64_t interval = GUI_REFRESH_INTERVAL;
3613 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3616 struct vm_change_state_entry {
3617 VMChangeStateHandler *cb;
3618 void *opaque;
3619 LIST_ENTRY (vm_change_state_entry) entries;
3622 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3624 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3625 void *opaque)
3627 VMChangeStateEntry *e;
3629 e = qemu_mallocz(sizeof (*e));
3631 e->cb = cb;
3632 e->opaque = opaque;
3633 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3634 return e;
3637 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3639 LIST_REMOVE (e, entries);
3640 qemu_free (e);
3643 static void vm_state_notify(int running, int reason)
3645 VMChangeStateEntry *e;
3647 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3648 e->cb(e->opaque, running, reason);
3652 static void resume_all_vcpus(void);
3653 static void pause_all_vcpus(void);
3655 void vm_start(void)
3657 if (!vm_running) {
3658 cpu_enable_ticks();
3659 vm_running = 1;
3660 vm_state_notify(1, 0);
3661 qemu_rearm_alarm_timer(alarm_timer);
3662 resume_all_vcpus();
3666 /* reset/shutdown handler */
3668 typedef struct QEMUResetEntry {
3669 QEMUResetHandler *func;
3670 void *opaque;
3671 int order;
3672 struct QEMUResetEntry *next;
3673 } QEMUResetEntry;
3675 static QEMUResetEntry *first_reset_entry;
3676 static int reset_requested;
3677 static int shutdown_requested;
3678 static int powerdown_requested;
3679 static int debug_requested;
3680 static int vmstop_requested;
3682 int qemu_no_shutdown(void)
3684 int r = no_shutdown;
3685 no_shutdown = 0;
3686 return r;
3689 int qemu_shutdown_requested(void)
3691 int r = shutdown_requested;
3692 shutdown_requested = 0;
3693 return r;
3696 int qemu_reset_requested(void)
3698 int r = reset_requested;
3699 reset_requested = 0;
3700 return r;
3703 int qemu_powerdown_requested(void)
3705 int r = powerdown_requested;
3706 powerdown_requested = 0;
3707 return r;
3710 static int qemu_debug_requested(void)
3712 int r = debug_requested;
3713 debug_requested = 0;
3714 return r;
3717 static int qemu_vmstop_requested(void)
3719 int r = vmstop_requested;
3720 vmstop_requested = 0;
3721 return r;
3724 static void do_vm_stop(int reason)
3726 if (vm_running) {
3727 cpu_disable_ticks();
3728 vm_running = 0;
3729 pause_all_vcpus();
3730 vm_state_notify(0, reason);
3734 void qemu_register_reset(QEMUResetHandler *func, int order, void *opaque)
3736 QEMUResetEntry **pre, *re;
3738 pre = &first_reset_entry;
3739 while (*pre != NULL && (*pre)->order >= order) {
3740 pre = &(*pre)->next;
3742 re = qemu_mallocz(sizeof(QEMUResetEntry));
3743 re->func = func;
3744 re->opaque = opaque;
3745 re->order = order;
3746 re->next = NULL;
3747 *pre = re;
3750 void qemu_system_reset(void)
3752 QEMUResetEntry *re;
3754 /* reset all devices */
3755 for(re = first_reset_entry; re != NULL; re = re->next) {
3756 re->func(re->opaque);
3760 void qemu_system_reset_request(void)
3762 if (no_reboot) {
3763 shutdown_requested = 1;
3764 } else {
3765 reset_requested = 1;
3767 if (cpu_single_env) {
3768 qemu_kvm_cpu_stop(cpu_single_env);
3770 qemu_notify_event();
3773 void qemu_system_shutdown_request(void)
3775 shutdown_requested = 1;
3776 qemu_notify_event();
3779 void qemu_system_powerdown_request(void)
3781 powerdown_requested = 1;
3782 qemu_notify_event();
3785 #ifdef CONFIG_IOTHREAD
3786 static void qemu_system_vmstop_request(int reason)
3788 vmstop_requested = reason;
3789 qemu_notify_event();
3791 #endif
3793 #ifndef _WIN32
3794 static int io_thread_fd = -1;
3796 static void qemu_event_increment(void)
3798 static const char byte = 0;
3800 if (io_thread_fd == -1)
3801 return;
3803 write(io_thread_fd, &byte, sizeof(byte));
3806 static void qemu_event_read(void *opaque)
3808 int fd = (unsigned long)opaque;
3809 ssize_t len;
3811 /* Drain the notify pipe */
3812 do {
3813 char buffer[512];
3814 len = read(fd, buffer, sizeof(buffer));
3815 } while ((len == -1 && errno == EINTR) || len > 0);
3818 static int qemu_event_init(void)
3820 int err;
3821 int fds[2];
3823 err = pipe(fds);
3824 if (err == -1)
3825 return -errno;
3827 err = fcntl_setfl(fds[0], O_NONBLOCK);
3828 if (err < 0)
3829 goto fail;
3831 err = fcntl_setfl(fds[1], O_NONBLOCK);
3832 if (err < 0)
3833 goto fail;
3835 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3836 (void *)(unsigned long)fds[0]);
3838 io_thread_fd = fds[1];
3839 return 0;
3841 fail:
3842 close(fds[0]);
3843 close(fds[1]);
3844 return err;
3846 #else
3847 HANDLE qemu_event_handle;
3849 static void dummy_event_handler(void *opaque)
3853 static int qemu_event_init(void)
3855 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3856 if (!qemu_event_handle) {
3857 perror("Failed CreateEvent");
3858 return -1;
3860 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3861 return 0;
3864 static void qemu_event_increment(void)
3866 SetEvent(qemu_event_handle);
3868 #endif
3870 static int cpu_can_run(CPUState *env)
3872 if (env->stop)
3873 return 0;
3874 if (env->stopped)
3875 return 0;
3876 return 1;
3879 #ifndef CONFIG_IOTHREAD
3880 static int qemu_init_main_loop(void)
3882 return qemu_event_init();
3885 void qemu_init_vcpu(void *_env)
3887 CPUState *env = _env;
3889 if (kvm_enabled())
3890 kvm_init_vcpu(env);
3891 return;
3894 int qemu_cpu_self(void *env)
3896 return 1;
3899 static void resume_all_vcpus(void)
3903 static void pause_all_vcpus(void)
3907 void qemu_cpu_kick(void *env)
3909 return;
3912 void qemu_notify_event(void)
3914 CPUState *env = cpu_single_env;
3916 if (kvm_enabled()) {
3917 qemu_kvm_notify_work();
3918 return;
3920 if (env) {
3921 cpu_exit(env);
3922 #ifdef USE_KQEMU
3923 if (env->kqemu_enabled)
3924 kqemu_cpu_interrupt(env);
3925 #endif
3929 #define qemu_mutex_lock_iothread() do { } while (0)
3930 #define qemu_mutex_unlock_iothread() do { } while (0)
3932 void vm_stop(int reason)
3934 do_vm_stop(reason);
3937 #else /* CONFIG_IOTHREAD */
3939 #include "qemu-thread.h"
3941 QemuMutex qemu_global_mutex;
3942 static QemuMutex qemu_fair_mutex;
3944 static QemuThread io_thread;
3946 static QemuThread *tcg_cpu_thread;
3947 static QemuCond *tcg_halt_cond;
3949 static int qemu_system_ready;
3950 /* cpu creation */
3951 static QemuCond qemu_cpu_cond;
3952 /* system init */
3953 static QemuCond qemu_system_cond;
3954 static QemuCond qemu_pause_cond;
3956 static void block_io_signals(void);
3957 static void unblock_io_signals(void);
3958 static int tcg_has_work(void);
3960 static int qemu_init_main_loop(void)
3962 int ret;
3964 ret = qemu_event_init();
3965 if (ret)
3966 return ret;
3968 qemu_cond_init(&qemu_pause_cond);
3969 qemu_mutex_init(&qemu_fair_mutex);
3970 qemu_mutex_init(&qemu_global_mutex);
3971 qemu_mutex_lock(&qemu_global_mutex);
3973 unblock_io_signals();
3974 qemu_thread_self(&io_thread);
3976 return 0;
3979 static void qemu_wait_io_event(CPUState *env)
3981 while (!tcg_has_work())
3982 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3984 qemu_mutex_unlock(&qemu_global_mutex);
3987 * Users of qemu_global_mutex can be starved, having no chance
3988 * to acquire it since this path will get to it first.
3989 * So use another lock to provide fairness.
3991 qemu_mutex_lock(&qemu_fair_mutex);
3992 qemu_mutex_unlock(&qemu_fair_mutex);
3994 qemu_mutex_lock(&qemu_global_mutex);
3995 if (env->stop) {
3996 env->stop = 0;
3997 env->stopped = 1;
3998 qemu_cond_signal(&qemu_pause_cond);
4002 static int qemu_cpu_exec(CPUState *env);
4004 static void *kvm_cpu_thread_fn(void *arg)
4006 CPUState *env = arg;
4008 block_io_signals();
4009 qemu_thread_self(env->thread);
4011 /* signal CPU creation */
4012 qemu_mutex_lock(&qemu_global_mutex);
4013 env->created = 1;
4014 qemu_cond_signal(&qemu_cpu_cond);
4016 /* and wait for machine initialization */
4017 while (!qemu_system_ready)
4018 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
4020 while (1) {
4021 if (cpu_can_run(env))
4022 qemu_cpu_exec(env);
4023 qemu_wait_io_event(env);
4026 return NULL;
4029 static void tcg_cpu_exec(void);
4031 static void *tcg_cpu_thread_fn(void *arg)
4033 CPUState *env = arg;
4035 block_io_signals();
4036 qemu_thread_self(env->thread);
4038 /* signal CPU creation */
4039 qemu_mutex_lock(&qemu_global_mutex);
4040 for (env = first_cpu; env != NULL; env = env->next_cpu)
4041 env->created = 1;
4042 qemu_cond_signal(&qemu_cpu_cond);
4044 /* and wait for machine initialization */
4045 while (!qemu_system_ready)
4046 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
4048 while (1) {
4049 tcg_cpu_exec();
4050 qemu_wait_io_event(cur_cpu);
4053 return NULL;
4056 void qemu_cpu_kick(void *_env)
4058 CPUState *env = _env;
4059 qemu_cond_broadcast(env->halt_cond);
4060 if (kvm_enabled())
4061 qemu_thread_signal(env->thread, SIGUSR1);
4064 int qemu_cpu_self(void *env)
4066 return (cpu_single_env != NULL);
4069 static void cpu_signal(int sig)
4071 if (cpu_single_env)
4072 cpu_exit(cpu_single_env);
4075 static void block_io_signals(void)
4077 sigset_t set;
4078 struct sigaction sigact;
4080 sigemptyset(&set);
4081 sigaddset(&set, SIGUSR2);
4082 sigaddset(&set, SIGIO);
4083 sigaddset(&set, SIGALRM);
4084 pthread_sigmask(SIG_BLOCK, &set, NULL);
4086 sigemptyset(&set);
4087 sigaddset(&set, SIGUSR1);
4088 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4090 memset(&sigact, 0, sizeof(sigact));
4091 sigact.sa_handler = cpu_signal;
4092 sigaction(SIGUSR1, &sigact, NULL);
4095 static void unblock_io_signals(void)
4097 sigset_t set;
4099 sigemptyset(&set);
4100 sigaddset(&set, SIGUSR2);
4101 sigaddset(&set, SIGIO);
4102 sigaddset(&set, SIGALRM);
4103 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4105 sigemptyset(&set);
4106 sigaddset(&set, SIGUSR1);
4107 pthread_sigmask(SIG_BLOCK, &set, NULL);
4110 static void qemu_signal_lock(unsigned int msecs)
4112 qemu_mutex_lock(&qemu_fair_mutex);
4114 while (qemu_mutex_trylock(&qemu_global_mutex)) {
4115 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
4116 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
4117 break;
4119 qemu_mutex_unlock(&qemu_fair_mutex);
4122 static void qemu_mutex_lock_iothread(void)
4124 if (kvm_enabled()) {
4125 qemu_mutex_lock(&qemu_fair_mutex);
4126 qemu_mutex_lock(&qemu_global_mutex);
4127 qemu_mutex_unlock(&qemu_fair_mutex);
4128 } else
4129 qemu_signal_lock(100);
4132 static void qemu_mutex_unlock_iothread(void)
4134 qemu_mutex_unlock(&qemu_global_mutex);
4137 static int all_vcpus_paused(void)
4139 CPUState *penv = first_cpu;
4141 while (penv) {
4142 if (!penv->stopped)
4143 return 0;
4144 penv = (CPUState *)penv->next_cpu;
4147 return 1;
4150 static void pause_all_vcpus(void)
4152 CPUState *penv = first_cpu;
4154 while (penv) {
4155 penv->stop = 1;
4156 qemu_thread_signal(penv->thread, SIGUSR1);
4157 qemu_cpu_kick(penv);
4158 penv = (CPUState *)penv->next_cpu;
4161 while (!all_vcpus_paused()) {
4162 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
4163 penv = first_cpu;
4164 while (penv) {
4165 qemu_thread_signal(penv->thread, SIGUSR1);
4166 penv = (CPUState *)penv->next_cpu;
4171 static void resume_all_vcpus(void)
4173 CPUState *penv = first_cpu;
4175 while (penv) {
4176 penv->stop = 0;
4177 penv->stopped = 0;
4178 qemu_thread_signal(penv->thread, SIGUSR1);
4179 qemu_cpu_kick(penv);
4180 penv = (CPUState *)penv->next_cpu;
4184 static void tcg_init_vcpu(void *_env)
4186 CPUState *env = _env;
4187 /* share a single thread for all cpus with TCG */
4188 if (!tcg_cpu_thread) {
4189 env->thread = qemu_mallocz(sizeof(QemuThread));
4190 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4191 qemu_cond_init(env->halt_cond);
4192 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
4193 while (env->created == 0)
4194 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4195 tcg_cpu_thread = env->thread;
4196 tcg_halt_cond = env->halt_cond;
4197 } else {
4198 env->thread = tcg_cpu_thread;
4199 env->halt_cond = tcg_halt_cond;
4203 static void kvm_start_vcpu(CPUState *env)
4205 kvm_init_vcpu(env);
4206 env->thread = qemu_mallocz(sizeof(QemuThread));
4207 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4208 qemu_cond_init(env->halt_cond);
4209 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
4210 while (env->created == 0)
4211 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4214 void qemu_init_vcpu(void *_env)
4216 CPUState *env = _env;
4218 if (kvm_enabled())
4219 kvm_start_vcpu(env);
4220 else
4221 tcg_init_vcpu(env);
4224 void qemu_notify_event(void)
4226 qemu_event_increment();
4229 void vm_stop(int reason)
4231 QemuThread me;
4232 qemu_thread_self(&me);
4234 if (!qemu_thread_equal(&me, &io_thread)) {
4235 qemu_system_vmstop_request(reason);
4237 * FIXME: should not return to device code in case
4238 * vm_stop() has been requested.
4240 if (cpu_single_env) {
4241 cpu_exit(cpu_single_env);
4242 cpu_single_env->stop = 1;
4244 return;
4246 do_vm_stop(reason);
4249 #endif
4252 #ifdef _WIN32
4253 static void host_main_loop_wait(int *timeout)
4255 int ret, ret2, i;
4256 PollingEntry *pe;
4259 /* XXX: need to suppress polling by better using win32 events */
4260 ret = 0;
4261 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4262 ret |= pe->func(pe->opaque);
4264 if (ret == 0) {
4265 int err;
4266 WaitObjects *w = &wait_objects;
4268 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4269 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4270 if (w->func[ret - WAIT_OBJECT_0])
4271 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4273 /* Check for additional signaled events */
4274 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4276 /* Check if event is signaled */
4277 ret2 = WaitForSingleObject(w->events[i], 0);
4278 if(ret2 == WAIT_OBJECT_0) {
4279 if (w->func[i])
4280 w->func[i](w->opaque[i]);
4281 } else if (ret2 == WAIT_TIMEOUT) {
4282 } else {
4283 err = GetLastError();
4284 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4287 } else if (ret == WAIT_TIMEOUT) {
4288 } else {
4289 err = GetLastError();
4290 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4294 *timeout = 0;
4296 #else
4297 static void host_main_loop_wait(int *timeout)
4300 #endif
4302 void main_loop_wait(int timeout)
4304 IOHandlerRecord *ioh;
4305 fd_set rfds, wfds, xfds;
4306 int ret, nfds;
4307 struct timeval tv;
4309 qemu_bh_update_timeout(&timeout);
4311 host_main_loop_wait(&timeout);
4313 /* poll any events */
4314 /* XXX: separate device handlers from system ones */
4315 nfds = -1;
4316 FD_ZERO(&rfds);
4317 FD_ZERO(&wfds);
4318 FD_ZERO(&xfds);
4319 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4320 if (ioh->deleted)
4321 continue;
4322 if (ioh->fd_read &&
4323 (!ioh->fd_read_poll ||
4324 ioh->fd_read_poll(ioh->opaque) != 0)) {
4325 FD_SET(ioh->fd, &rfds);
4326 if (ioh->fd > nfds)
4327 nfds = ioh->fd;
4329 if (ioh->fd_write) {
4330 FD_SET(ioh->fd, &wfds);
4331 if (ioh->fd > nfds)
4332 nfds = ioh->fd;
4336 tv.tv_sec = timeout / 1000;
4337 tv.tv_usec = (timeout % 1000) * 1000;
4339 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4341 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4342 if (ret > 0) {
4343 IOHandlerRecord **pioh;
4345 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4346 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4347 ioh->fd_read(ioh->opaque);
4348 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
4349 FD_CLR(ioh->fd, &rfds);
4351 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4352 ioh->fd_write(ioh->opaque);
4356 /* remove deleted IO handlers */
4357 pioh = &first_io_handler;
4358 while (*pioh) {
4359 ioh = *pioh;
4360 if (ioh->deleted) {
4361 *pioh = ioh->next;
4362 qemu_free(ioh);
4363 } else
4364 pioh = &ioh->next;
4368 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4370 /* rearm timer, if not periodic */
4371 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4372 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4373 qemu_rearm_alarm_timer(alarm_timer);
4376 /* vm time timers */
4377 if (vm_running) {
4378 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4379 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4380 qemu_get_clock(vm_clock));
4383 /* real time timers */
4384 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4385 qemu_get_clock(rt_clock));
4387 /* Check bottom-halves last in case any of the earlier events triggered
4388 them. */
4389 qemu_bh_poll();
4393 static int qemu_cpu_exec(CPUState *env)
4395 int ret;
4396 #ifdef CONFIG_PROFILER
4397 int64_t ti;
4398 #endif
4400 #ifdef CONFIG_PROFILER
4401 ti = profile_getclock();
4402 #endif
4403 if (use_icount) {
4404 int64_t count;
4405 int decr;
4406 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4407 env->icount_decr.u16.low = 0;
4408 env->icount_extra = 0;
4409 count = qemu_next_deadline();
4410 count = (count + (1 << icount_time_shift) - 1)
4411 >> icount_time_shift;
4412 qemu_icount += count;
4413 decr = (count > 0xffff) ? 0xffff : count;
4414 count -= decr;
4415 env->icount_decr.u16.low = decr;
4416 env->icount_extra = count;
4418 ret = cpu_exec(env);
4419 #ifdef CONFIG_PROFILER
4420 qemu_time += profile_getclock() - ti;
4421 #endif
4422 if (use_icount) {
4423 /* Fold pending instructions back into the
4424 instruction counter, and clear the interrupt flag. */
4425 qemu_icount -= (env->icount_decr.u16.low
4426 + env->icount_extra);
4427 env->icount_decr.u32 = 0;
4428 env->icount_extra = 0;
4430 return ret;
4433 static void tcg_cpu_exec(void)
4435 int ret = 0;
4437 if (next_cpu == NULL)
4438 next_cpu = first_cpu;
4439 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4440 CPUState *env = cur_cpu = next_cpu;
4442 if (!vm_running)
4443 break;
4444 if (timer_alarm_pending) {
4445 timer_alarm_pending = 0;
4446 break;
4448 if (cpu_can_run(env))
4449 ret = qemu_cpu_exec(env);
4450 if (ret == EXCP_DEBUG) {
4451 gdb_set_stop_cpu(env);
4452 debug_requested = 1;
4453 break;
4458 static int cpu_has_work(CPUState *env)
4460 if (env->stop)
4461 return 1;
4462 if (env->stopped)
4463 return 0;
4464 if (!env->halted)
4465 return 1;
4466 if (qemu_cpu_has_work(env))
4467 return 1;
4468 return 0;
4471 static int tcg_has_work(void)
4473 CPUState *env;
4475 for (env = first_cpu; env != NULL; env = env->next_cpu)
4476 if (cpu_has_work(env))
4477 return 1;
4478 return 0;
4481 static int qemu_calculate_timeout(void)
4483 #ifndef CONFIG_IOTHREAD
4484 int timeout;
4486 if (!vm_running)
4487 timeout = 5000;
4488 else if (tcg_has_work())
4489 timeout = 0;
4490 else if (!use_icount)
4491 timeout = 5000;
4492 else {
4493 /* XXX: use timeout computed from timers */
4494 int64_t add;
4495 int64_t delta;
4496 /* Advance virtual time to the next event. */
4497 if (use_icount == 1) {
4498 /* When not using an adaptive execution frequency
4499 we tend to get badly out of sync with real time,
4500 so just delay for a reasonable amount of time. */
4501 delta = 0;
4502 } else {
4503 delta = cpu_get_icount() - cpu_get_clock();
4505 if (delta > 0) {
4506 /* If virtual time is ahead of real time then just
4507 wait for IO. */
4508 timeout = (delta / 1000000) + 1;
4509 } else {
4510 /* Wait for either IO to occur or the next
4511 timer event. */
4512 add = qemu_next_deadline();
4513 /* We advance the timer before checking for IO.
4514 Limit the amount we advance so that early IO
4515 activity won't get the guest too far ahead. */
4516 if (add > 10000000)
4517 add = 10000000;
4518 delta += add;
4519 add = (add + (1 << icount_time_shift) - 1)
4520 >> icount_time_shift;
4521 qemu_icount += add;
4522 timeout = delta / 1000000;
4523 if (timeout < 0)
4524 timeout = 0;
4528 return timeout;
4529 #else /* CONFIG_IOTHREAD */
4530 return 1000;
4531 #endif
4534 static int vm_can_run(void)
4536 if (powerdown_requested)
4537 return 0;
4538 if (reset_requested)
4539 return 0;
4540 if (shutdown_requested)
4541 return 0;
4542 if (debug_requested)
4543 return 0;
4544 return 1;
4547 static void main_loop(void)
4549 int r;
4551 if (kvm_enabled()) {
4552 kvm_main_loop();
4553 cpu_disable_ticks();
4554 return;
4557 #ifdef CONFIG_IOTHREAD
4558 qemu_system_ready = 1;
4559 qemu_cond_broadcast(&qemu_system_cond);
4560 #endif
4562 for (;;) {
4563 do {
4564 #ifdef CONFIG_PROFILER
4565 int64_t ti;
4566 #endif
4567 #ifndef CONFIG_IOTHREAD
4568 tcg_cpu_exec();
4569 #endif
4570 #ifdef CONFIG_PROFILER
4571 ti = profile_getclock();
4572 #endif
4573 main_loop_wait(qemu_calculate_timeout());
4574 #ifdef CONFIG_PROFILER
4575 dev_time += profile_getclock() - ti;
4576 #endif
4577 } while (vm_can_run());
4579 if (qemu_debug_requested())
4580 vm_stop(EXCP_DEBUG);
4581 if (qemu_shutdown_requested()) {
4582 if (no_shutdown) {
4583 vm_stop(0);
4584 no_shutdown = 0;
4585 } else
4586 break;
4588 if (qemu_reset_requested()) {
4589 pause_all_vcpus();
4590 qemu_system_reset();
4591 resume_all_vcpus();
4593 if (qemu_powerdown_requested())
4594 qemu_system_powerdown();
4595 if ((r = qemu_vmstop_requested()))
4596 vm_stop(r);
4598 pause_all_vcpus();
4601 static void version(void)
4603 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4606 static void help(int exitcode)
4608 version();
4609 printf("usage: %s [options] [disk_image]\n"
4610 "\n"
4611 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4612 "\n"
4613 #define DEF(option, opt_arg, opt_enum, opt_help) \
4614 opt_help
4615 #define DEFHEADING(text) stringify(text) "\n"
4616 #include "qemu-options.h"
4617 #undef DEF
4618 #undef DEFHEADING
4619 #undef GEN_DOCS
4620 "\n"
4621 "During emulation, the following keys are useful:\n"
4622 "ctrl-alt-f toggle full screen\n"
4623 "ctrl-alt-n switch to virtual console 'n'\n"
4624 "ctrl-alt toggle mouse and keyboard grab\n"
4625 "\n"
4626 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4628 "qemu",
4629 DEFAULT_RAM_SIZE,
4630 #ifndef _WIN32
4631 DEFAULT_NETWORK_SCRIPT,
4632 DEFAULT_NETWORK_DOWN_SCRIPT,
4633 #endif
4634 DEFAULT_GDBSTUB_PORT,
4635 "/tmp/qemu.log");
4636 exit(exitcode);
4639 #define HAS_ARG 0x0001
4641 enum {
4642 #define DEF(option, opt_arg, opt_enum, opt_help) \
4643 opt_enum,
4644 #define DEFHEADING(text)
4645 #include "qemu-options.h"
4646 #undef DEF
4647 #undef DEFHEADING
4648 #undef GEN_DOCS
4651 typedef struct QEMUOption {
4652 const char *name;
4653 int flags;
4654 int index;
4655 } QEMUOption;
4657 static const QEMUOption qemu_options[] = {
4658 { "h", 0, QEMU_OPTION_h },
4659 #define DEF(option, opt_arg, opt_enum, opt_help) \
4660 { option, opt_arg, opt_enum },
4661 #define DEFHEADING(text)
4662 #include "qemu-options.h"
4663 #undef DEF
4664 #undef DEFHEADING
4665 #undef GEN_DOCS
4666 { NULL },
4669 #ifdef HAS_AUDIO
4670 struct soundhw soundhw[] = {
4671 #ifdef HAS_AUDIO_CHOICE
4672 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4674 "pcspk",
4675 "PC speaker",
4678 { .init_isa = pcspk_audio_init }
4680 #endif
4682 #ifdef CONFIG_SB16
4684 "sb16",
4685 "Creative Sound Blaster 16",
4688 { .init_isa = SB16_init }
4690 #endif
4692 #ifdef CONFIG_CS4231A
4694 "cs4231a",
4695 "CS4231A",
4698 { .init_isa = cs4231a_init }
4700 #endif
4702 #ifdef CONFIG_ADLIB
4704 "adlib",
4705 #ifdef HAS_YMF262
4706 "Yamaha YMF262 (OPL3)",
4707 #else
4708 "Yamaha YM3812 (OPL2)",
4709 #endif
4712 { .init_isa = Adlib_init }
4714 #endif
4716 #ifdef CONFIG_GUS
4718 "gus",
4719 "Gravis Ultrasound GF1",
4722 { .init_isa = GUS_init }
4724 #endif
4726 #ifdef CONFIG_AC97
4728 "ac97",
4729 "Intel 82801AA AC97 Audio",
4732 { .init_pci = ac97_init }
4734 #endif
4736 #ifdef CONFIG_ES1370
4738 "es1370",
4739 "ENSONIQ AudioPCI ES1370",
4742 { .init_pci = es1370_init }
4744 #endif
4746 #endif /* HAS_AUDIO_CHOICE */
4748 { NULL, NULL, 0, 0, { NULL } }
4751 static void select_soundhw (const char *optarg)
4753 struct soundhw *c;
4755 if (*optarg == '?') {
4756 show_valid_cards:
4758 printf ("Valid sound card names (comma separated):\n");
4759 for (c = soundhw; c->name; ++c) {
4760 printf ("%-11s %s\n", c->name, c->descr);
4762 printf ("\n-soundhw all will enable all of the above\n");
4763 exit (*optarg != '?');
4765 else {
4766 size_t l;
4767 const char *p;
4768 char *e;
4769 int bad_card = 0;
4771 if (!strcmp (optarg, "all")) {
4772 for (c = soundhw; c->name; ++c) {
4773 c->enabled = 1;
4775 return;
4778 p = optarg;
4779 while (*p) {
4780 e = strchr (p, ',');
4781 l = !e ? strlen (p) : (size_t) (e - p);
4783 for (c = soundhw; c->name; ++c) {
4784 if (!strncmp (c->name, p, l)) {
4785 c->enabled = 1;
4786 break;
4790 if (!c->name) {
4791 if (l > 80) {
4792 fprintf (stderr,
4793 "Unknown sound card name (too big to show)\n");
4795 else {
4796 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4797 (int) l, p);
4799 bad_card = 1;
4801 p += l + (e != NULL);
4804 if (bad_card)
4805 goto show_valid_cards;
4808 #endif
4810 static void select_vgahw (const char *p)
4812 const char *opts;
4814 cirrus_vga_enabled = 0;
4815 std_vga_enabled = 0;
4816 vmsvga_enabled = 0;
4817 xenfb_enabled = 0;
4818 if (strstart(p, "std", &opts)) {
4819 std_vga_enabled = 1;
4820 } else if (strstart(p, "cirrus", &opts)) {
4821 cirrus_vga_enabled = 1;
4822 } else if (strstart(p, "vmware", &opts)) {
4823 vmsvga_enabled = 1;
4824 } else if (strstart(p, "xenfb", &opts)) {
4825 xenfb_enabled = 1;
4826 } else if (!strstart(p, "none", &opts)) {
4827 invalid_vga:
4828 fprintf(stderr, "Unknown vga type: %s\n", p);
4829 exit(1);
4831 while (*opts) {
4832 const char *nextopt;
4834 if (strstart(opts, ",retrace=", &nextopt)) {
4835 opts = nextopt;
4836 if (strstart(opts, "dumb", &nextopt))
4837 vga_retrace_method = VGA_RETRACE_DUMB;
4838 else if (strstart(opts, "precise", &nextopt))
4839 vga_retrace_method = VGA_RETRACE_PRECISE;
4840 else goto invalid_vga;
4841 } else goto invalid_vga;
4842 opts = nextopt;
4846 #ifdef _WIN32
4847 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4849 exit(STATUS_CONTROL_C_EXIT);
4850 return TRUE;
4852 #endif
4854 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4856 int ret;
4858 if(strlen(str) != 36)
4859 return -1;
4861 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4862 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4863 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4865 if(ret != 16)
4866 return -1;
4868 #ifdef TARGET_I386
4869 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4870 #endif
4872 return 0;
4875 #define MAX_NET_CLIENTS 32
4877 #ifndef _WIN32
4879 static void termsig_handler(int signal)
4881 qemu_system_shutdown_request();
4884 static void sigchld_handler(int signal)
4886 waitpid(-1, NULL, WNOHANG);
4889 static void sighandler_setup(void)
4891 struct sigaction act;
4893 memset(&act, 0, sizeof(act));
4894 act.sa_handler = termsig_handler;
4895 sigaction(SIGINT, &act, NULL);
4896 sigaction(SIGHUP, &act, NULL);
4897 sigaction(SIGTERM, &act, NULL);
4899 act.sa_handler = sigchld_handler;
4900 act.sa_flags = SA_NOCLDSTOP;
4901 sigaction(SIGCHLD, &act, NULL);
4904 #endif
4906 #ifdef _WIN32
4907 /* Look for support files in the same directory as the executable. */
4908 static char *find_datadir(const char *argv0)
4910 char *p;
4911 char buf[MAX_PATH];
4912 DWORD len;
4914 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4915 if (len == 0) {
4916 return NULL;
4919 buf[len] = 0;
4920 p = buf + len - 1;
4921 while (p != buf && *p != '\\')
4922 p--;
4923 *p = 0;
4924 if (access(buf, R_OK) == 0) {
4925 return qemu_strdup(buf);
4927 return NULL;
4929 #else /* !_WIN32 */
4931 /* Find a likely location for support files using the location of the binary.
4932 For installed binaries this will be "$bindir/../share/qemu". When
4933 running from the build tree this will be "$bindir/../pc-bios". */
4934 #define SHARE_SUFFIX "/share/qemu"
4935 #define BUILD_SUFFIX "/pc-bios"
4936 static char *find_datadir(const char *argv0)
4938 char *dir;
4939 char *p = NULL;
4940 char *res;
4941 #ifdef PATH_MAX
4942 char buf[PATH_MAX];
4943 #endif
4944 size_t max_len;
4946 #if defined(__linux__)
4948 int len;
4949 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4950 if (len > 0) {
4951 buf[len] = 0;
4952 p = buf;
4955 #elif defined(__FreeBSD__)
4957 int len;
4958 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4959 if (len > 0) {
4960 buf[len] = 0;
4961 p = buf;
4964 #endif
4965 /* If we don't have any way of figuring out the actual executable
4966 location then try argv[0]. */
4967 if (!p) {
4968 #ifdef PATH_MAX
4969 p = buf;
4970 #endif
4971 p = realpath(argv0, p);
4972 if (!p) {
4973 return NULL;
4976 dir = dirname(p);
4977 dir = dirname(dir);
4979 max_len = strlen(dir) +
4980 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4981 res = qemu_mallocz(max_len);
4982 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4983 if (access(res, R_OK)) {
4984 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4985 if (access(res, R_OK)) {
4986 qemu_free(res);
4987 res = NULL;
4990 #ifndef PATH_MAX
4991 free(p);
4992 #endif
4993 return res;
4995 #undef SHARE_SUFFIX
4996 #undef BUILD_SUFFIX
4997 #endif
4999 char *qemu_find_file(int type, const char *name)
5001 int len;
5002 const char *subdir;
5003 char *buf;
5005 /* If name contains path separators then try it as a straight path. */
5006 if ((strchr(name, '/') || strchr(name, '\\'))
5007 && access(name, R_OK) == 0) {
5008 return strdup(name);
5010 switch (type) {
5011 case QEMU_FILE_TYPE_BIOS:
5012 subdir = "";
5013 break;
5014 case QEMU_FILE_TYPE_KEYMAP:
5015 subdir = "keymaps/";
5016 break;
5017 default:
5018 abort();
5020 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
5021 buf = qemu_mallocz(len);
5022 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
5023 if (access(buf, R_OK)) {
5024 qemu_free(buf);
5025 return NULL;
5027 return buf;
5030 int main(int argc, char **argv, char **envp)
5032 const char *gdbstub_dev = NULL;
5033 uint32_t boot_devices_bitmap = 0;
5034 int i;
5035 int snapshot, linux_boot, net_boot;
5036 const char *initrd_filename;
5037 const char *kernel_filename, *kernel_cmdline;
5038 const char *boot_devices = "";
5039 DisplayState *ds;
5040 DisplayChangeListener *dcl;
5041 int cyls, heads, secs, translation;
5042 const char *net_clients[MAX_NET_CLIENTS];
5043 int nb_net_clients;
5044 const char *bt_opts[MAX_BT_CMDLINE];
5045 int nb_bt_opts;
5046 int hda_index;
5047 int optind;
5048 const char *r, *optarg;
5049 CharDriverState *monitor_hd = NULL;
5050 const char *monitor_device;
5051 const char *serial_devices[MAX_SERIAL_PORTS];
5052 int serial_device_index;
5053 const char *parallel_devices[MAX_PARALLEL_PORTS];
5054 int parallel_device_index;
5055 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
5056 int virtio_console_index;
5057 const char *loadvm = NULL;
5058 QEMUMachine *machine;
5059 const char *cpu_model;
5060 const char *usb_devices[MAX_USB_CMDLINE];
5061 int usb_devices_index;
5062 #ifndef _WIN32
5063 int fds[2];
5064 #endif
5065 int tb_size;
5066 const char *pid_file = NULL;
5067 const char *incoming = NULL;
5068 #ifndef _WIN32
5069 int fd = 0;
5070 struct passwd *pwd = NULL;
5071 const char *chroot_dir = NULL;
5072 const char *run_as = NULL;
5073 #endif
5074 CPUState *env;
5075 int show_vnc_port = 0;
5077 qemu_cache_utils_init(envp);
5079 LIST_INIT (&vm_change_state_head);
5080 #ifndef _WIN32
5082 struct sigaction act;
5083 sigfillset(&act.sa_mask);
5084 act.sa_flags = 0;
5085 act.sa_handler = SIG_IGN;
5086 sigaction(SIGPIPE, &act, NULL);
5088 #else
5089 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5090 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5091 QEMU to run on a single CPU */
5093 HANDLE h;
5094 DWORD mask, smask;
5095 int i;
5096 h = GetCurrentProcess();
5097 if (GetProcessAffinityMask(h, &mask, &smask)) {
5098 for(i = 0; i < 32; i++) {
5099 if (mask & (1 << i))
5100 break;
5102 if (i != 32) {
5103 mask = 1 << i;
5104 SetProcessAffinityMask(h, mask);
5108 #endif
5110 module_call_init(MODULE_INIT_MACHINE);
5111 machine = find_default_machine();
5112 cpu_model = NULL;
5113 initrd_filename = NULL;
5114 ram_size = 0;
5115 snapshot = 0;
5116 kernel_filename = NULL;
5117 kernel_cmdline = "";
5118 cyls = heads = secs = 0;
5119 translation = BIOS_ATA_TRANSLATION_AUTO;
5120 monitor_device = "vc:80Cx24C";
5122 serial_devices[0] = "vc:80Cx24C";
5123 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5124 serial_devices[i] = NULL;
5125 serial_device_index = 0;
5127 parallel_devices[0] = "vc:80Cx24C";
5128 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5129 parallel_devices[i] = NULL;
5130 parallel_device_index = 0;
5132 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
5133 virtio_consoles[i] = NULL;
5134 virtio_console_index = 0;
5136 for (i = 0; i < MAX_NODES; i++) {
5137 node_mem[i] = 0;
5138 node_cpumask[i] = 0;
5141 usb_devices_index = 0;
5142 assigned_devices_index = 0;
5144 nb_net_clients = 0;
5145 nb_bt_opts = 0;
5146 nb_drives = 0;
5147 nb_drives_opt = 0;
5148 nb_numa_nodes = 0;
5149 hda_index = -1;
5151 nb_nics = 0;
5153 tb_size = 0;
5154 autostart= 1;
5156 register_watchdogs();
5158 optind = 1;
5159 for(;;) {
5160 if (optind >= argc)
5161 break;
5162 r = argv[optind];
5163 if (r[0] != '-') {
5164 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5165 } else {
5166 const QEMUOption *popt;
5168 optind++;
5169 /* Treat --foo the same as -foo. */
5170 if (r[1] == '-')
5171 r++;
5172 popt = qemu_options;
5173 for(;;) {
5174 if (!popt->name) {
5175 fprintf(stderr, "%s: invalid option -- '%s'\n",
5176 argv[0], r);
5177 exit(1);
5179 if (!strcmp(popt->name, r + 1))
5180 break;
5181 popt++;
5183 if (popt->flags & HAS_ARG) {
5184 if (optind >= argc) {
5185 fprintf(stderr, "%s: option '%s' requires an argument\n",
5186 argv[0], r);
5187 exit(1);
5189 optarg = argv[optind++];
5190 } else {
5191 optarg = NULL;
5194 switch(popt->index) {
5195 case QEMU_OPTION_M:
5196 machine = find_machine(optarg);
5197 if (!machine) {
5198 QEMUMachine *m;
5199 printf("Supported machines are:\n");
5200 for(m = first_machine; m != NULL; m = m->next) {
5201 printf("%-10s %s%s\n",
5202 m->name, m->desc,
5203 m->is_default ? " (default)" : "");
5205 exit(*optarg != '?');
5207 break;
5208 case QEMU_OPTION_cpu:
5209 /* hw initialization will check this */
5210 if (*optarg == '?') {
5211 /* XXX: implement xxx_cpu_list for targets that still miss it */
5212 #if defined(cpu_list)
5213 cpu_list(stdout, &fprintf);
5214 #endif
5215 exit(0);
5216 } else {
5217 cpu_model = optarg;
5219 break;
5220 case QEMU_OPTION_initrd:
5221 initrd_filename = optarg;
5222 break;
5223 case QEMU_OPTION_hda:
5224 if (cyls == 0)
5225 hda_index = drive_add(optarg, HD_ALIAS, 0);
5226 else
5227 hda_index = drive_add(optarg, HD_ALIAS
5228 ",cyls=%d,heads=%d,secs=%d%s",
5229 0, cyls, heads, secs,
5230 translation == BIOS_ATA_TRANSLATION_LBA ?
5231 ",trans=lba" :
5232 translation == BIOS_ATA_TRANSLATION_NONE ?
5233 ",trans=none" : "");
5234 break;
5235 case QEMU_OPTION_hdb:
5236 case QEMU_OPTION_hdc:
5237 case QEMU_OPTION_hdd:
5238 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5239 break;
5240 case QEMU_OPTION_drive:
5241 drive_add(NULL, "%s", optarg);
5242 break;
5243 case QEMU_OPTION_mtdblock:
5244 drive_add(optarg, MTD_ALIAS);
5245 break;
5246 case QEMU_OPTION_sd:
5247 drive_add(optarg, SD_ALIAS);
5248 break;
5249 case QEMU_OPTION_pflash:
5250 drive_add(optarg, PFLASH_ALIAS);
5251 break;
5252 case QEMU_OPTION_snapshot:
5253 snapshot = 1;
5254 break;
5255 case QEMU_OPTION_hdachs:
5257 const char *p;
5258 p = optarg;
5259 cyls = strtol(p, (char **)&p, 0);
5260 if (cyls < 1 || cyls > 16383)
5261 goto chs_fail;
5262 if (*p != ',')
5263 goto chs_fail;
5264 p++;
5265 heads = strtol(p, (char **)&p, 0);
5266 if (heads < 1 || heads > 16)
5267 goto chs_fail;
5268 if (*p != ',')
5269 goto chs_fail;
5270 p++;
5271 secs = strtol(p, (char **)&p, 0);
5272 if (secs < 1 || secs > 63)
5273 goto chs_fail;
5274 if (*p == ',') {
5275 p++;
5276 if (!strcmp(p, "none"))
5277 translation = BIOS_ATA_TRANSLATION_NONE;
5278 else if (!strcmp(p, "lba"))
5279 translation = BIOS_ATA_TRANSLATION_LBA;
5280 else if (!strcmp(p, "auto"))
5281 translation = BIOS_ATA_TRANSLATION_AUTO;
5282 else
5283 goto chs_fail;
5284 } else if (*p != '\0') {
5285 chs_fail:
5286 fprintf(stderr, "qemu: invalid physical CHS format\n");
5287 exit(1);
5289 if (hda_index != -1)
5290 snprintf(drives_opt[hda_index].opt,
5291 sizeof(drives_opt[hda_index].opt),
5292 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5293 0, cyls, heads, secs,
5294 translation == BIOS_ATA_TRANSLATION_LBA ?
5295 ",trans=lba" :
5296 translation == BIOS_ATA_TRANSLATION_NONE ?
5297 ",trans=none" : "");
5299 break;
5300 case QEMU_OPTION_numa:
5301 if (nb_numa_nodes >= MAX_NODES) {
5302 fprintf(stderr, "qemu: too many NUMA nodes\n");
5303 exit(1);
5305 numa_add(optarg);
5306 break;
5307 case QEMU_OPTION_nographic:
5308 display_type = DT_NOGRAPHIC;
5309 break;
5310 #ifdef CONFIG_CURSES
5311 case QEMU_OPTION_curses:
5312 display_type = DT_CURSES;
5313 break;
5314 #endif
5315 case QEMU_OPTION_portrait:
5316 graphic_rotate = 1;
5317 break;
5318 case QEMU_OPTION_kernel:
5319 kernel_filename = optarg;
5320 break;
5321 case QEMU_OPTION_append:
5322 kernel_cmdline = optarg;
5323 break;
5324 case QEMU_OPTION_cdrom:
5325 drive_add(optarg, CDROM_ALIAS);
5326 break;
5327 case QEMU_OPTION_boot:
5328 boot_devices = optarg;
5329 /* We just do some generic consistency checks */
5331 /* Could easily be extended to 64 devices if needed */
5332 const char *p;
5334 boot_devices_bitmap = 0;
5335 for (p = boot_devices; *p != '\0'; p++) {
5336 /* Allowed boot devices are:
5337 * a b : floppy disk drives
5338 * c ... f : IDE disk drives
5339 * g ... m : machine implementation dependant drives
5340 * n ... p : network devices
5341 * It's up to each machine implementation to check
5342 * if the given boot devices match the actual hardware
5343 * implementation and firmware features.
5345 if (*p < 'a' || *p > 'q') {
5346 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5347 exit(1);
5349 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5350 fprintf(stderr,
5351 "Boot device '%c' was given twice\n",*p);
5352 exit(1);
5354 boot_devices_bitmap |= 1 << (*p - 'a');
5357 break;
5358 case QEMU_OPTION_fda:
5359 case QEMU_OPTION_fdb:
5360 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5361 break;
5362 #ifdef TARGET_I386
5363 case QEMU_OPTION_no_fd_bootchk:
5364 fd_bootchk = 0;
5365 break;
5366 #endif
5367 case QEMU_OPTION_net:
5368 if (nb_net_clients >= MAX_NET_CLIENTS) {
5369 fprintf(stderr, "qemu: too many network clients\n");
5370 exit(1);
5372 net_clients[nb_net_clients] = optarg;
5373 nb_net_clients++;
5374 break;
5375 #ifdef CONFIG_SLIRP
5376 case QEMU_OPTION_tftp:
5377 legacy_tftp_prefix = optarg;
5378 break;
5379 case QEMU_OPTION_bootp:
5380 legacy_bootp_filename = optarg;
5381 break;
5382 #ifndef _WIN32
5383 case QEMU_OPTION_smb:
5384 net_slirp_smb(optarg);
5385 break;
5386 #endif
5387 case QEMU_OPTION_redir:
5388 net_slirp_redir(optarg);
5389 break;
5390 #endif
5391 case QEMU_OPTION_bt:
5392 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5393 fprintf(stderr, "qemu: too many bluetooth options\n");
5394 exit(1);
5396 bt_opts[nb_bt_opts++] = optarg;
5397 break;
5398 #ifdef HAS_AUDIO
5399 case QEMU_OPTION_audio_help:
5400 AUD_help ();
5401 exit (0);
5402 break;
5403 case QEMU_OPTION_soundhw:
5404 select_soundhw (optarg);
5405 break;
5406 #endif
5407 case QEMU_OPTION_h:
5408 help(0);
5409 break;
5410 case QEMU_OPTION_version:
5411 version();
5412 exit(0);
5413 break;
5414 case QEMU_OPTION_m: {
5415 uint64_t value;
5416 char *ptr;
5418 value = strtoul(optarg, &ptr, 10);
5419 switch (*ptr) {
5420 case 0: case 'M': case 'm':
5421 value <<= 20;
5422 break;
5423 case 'G': case 'g':
5424 value <<= 30;
5425 break;
5426 default:
5427 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5428 exit(1);
5431 /* On 32-bit hosts, QEMU is limited by virtual address space */
5432 if (value > (2047 << 20)
5433 #ifndef CONFIG_KQEMU
5434 && HOST_LONG_BITS == 32
5435 #endif
5437 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5438 exit(1);
5440 if (value != (uint64_t)(ram_addr_t)value) {
5441 fprintf(stderr, "qemu: ram size too large\n");
5442 exit(1);
5444 ram_size = value;
5445 break;
5447 case QEMU_OPTION_d:
5449 int mask;
5450 const CPULogItem *item;
5452 mask = cpu_str_to_log_mask(optarg);
5453 if (!mask) {
5454 printf("Log items (comma separated):\n");
5455 for(item = cpu_log_items; item->mask != 0; item++) {
5456 printf("%-10s %s\n", item->name, item->help);
5458 exit(1);
5460 cpu_set_log(mask);
5462 break;
5463 case QEMU_OPTION_s:
5464 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5465 break;
5466 case QEMU_OPTION_gdb:
5467 gdbstub_dev = optarg;
5468 break;
5469 case QEMU_OPTION_L:
5470 data_dir = optarg;
5471 break;
5472 case QEMU_OPTION_bios:
5473 bios_name = optarg;
5474 break;
5475 case QEMU_OPTION_singlestep:
5476 singlestep = 1;
5477 break;
5478 case QEMU_OPTION_S:
5479 autostart = 0;
5480 break;
5481 #ifndef _WIN32
5482 case QEMU_OPTION_k:
5483 keyboard_layout = optarg;
5484 break;
5485 #endif
5486 case QEMU_OPTION_localtime:
5487 rtc_utc = 0;
5488 break;
5489 case QEMU_OPTION_vga:
5490 select_vgahw (optarg);
5491 break;
5492 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5493 case QEMU_OPTION_g:
5495 const char *p;
5496 int w, h, depth;
5497 p = optarg;
5498 w = strtol(p, (char **)&p, 10);
5499 if (w <= 0) {
5500 graphic_error:
5501 fprintf(stderr, "qemu: invalid resolution or depth\n");
5502 exit(1);
5504 if (*p != 'x')
5505 goto graphic_error;
5506 p++;
5507 h = strtol(p, (char **)&p, 10);
5508 if (h <= 0)
5509 goto graphic_error;
5510 if (*p == 'x') {
5511 p++;
5512 depth = strtol(p, (char **)&p, 10);
5513 if (depth != 8 && depth != 15 && depth != 16 &&
5514 depth != 24 && depth != 32)
5515 goto graphic_error;
5516 } else if (*p == '\0') {
5517 depth = graphic_depth;
5518 } else {
5519 goto graphic_error;
5522 graphic_width = w;
5523 graphic_height = h;
5524 graphic_depth = depth;
5526 break;
5527 #endif
5528 case QEMU_OPTION_echr:
5530 char *r;
5531 term_escape_char = strtol(optarg, &r, 0);
5532 if (r == optarg)
5533 printf("Bad argument to echr\n");
5534 break;
5536 case QEMU_OPTION_monitor:
5537 monitor_device = optarg;
5538 break;
5539 case QEMU_OPTION_serial:
5540 if (serial_device_index >= MAX_SERIAL_PORTS) {
5541 fprintf(stderr, "qemu: too many serial ports\n");
5542 exit(1);
5544 serial_devices[serial_device_index] = optarg;
5545 serial_device_index++;
5546 break;
5547 case QEMU_OPTION_watchdog:
5548 i = select_watchdog(optarg);
5549 if (i > 0)
5550 exit (i == 1 ? 1 : 0);
5551 break;
5552 case QEMU_OPTION_watchdog_action:
5553 if (select_watchdog_action(optarg) == -1) {
5554 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5555 exit(1);
5557 break;
5558 case QEMU_OPTION_virtiocon:
5559 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5560 fprintf(stderr, "qemu: too many virtio consoles\n");
5561 exit(1);
5563 virtio_consoles[virtio_console_index] = optarg;
5564 virtio_console_index++;
5565 break;
5566 case QEMU_OPTION_parallel:
5567 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5568 fprintf(stderr, "qemu: too many parallel ports\n");
5569 exit(1);
5571 parallel_devices[parallel_device_index] = optarg;
5572 parallel_device_index++;
5573 break;
5574 case QEMU_OPTION_loadvm:
5575 loadvm = optarg;
5576 break;
5577 case QEMU_OPTION_full_screen:
5578 full_screen = 1;
5579 break;
5580 #ifdef CONFIG_SDL
5581 case QEMU_OPTION_no_frame:
5582 no_frame = 1;
5583 break;
5584 case QEMU_OPTION_alt_grab:
5585 alt_grab = 1;
5586 break;
5587 case QEMU_OPTION_no_quit:
5588 no_quit = 1;
5589 break;
5590 case QEMU_OPTION_sdl:
5591 display_type = DT_SDL;
5592 break;
5593 #endif
5594 case QEMU_OPTION_pidfile:
5595 pid_file = optarg;
5596 break;
5597 #ifdef TARGET_I386
5598 case QEMU_OPTION_win2k_hack:
5599 win2k_install_hack = 1;
5600 break;
5601 case QEMU_OPTION_rtc_td_hack:
5602 rtc_td_hack = 1;
5603 break;
5604 case QEMU_OPTION_acpitable:
5605 if(acpi_table_add(optarg) < 0) {
5606 fprintf(stderr, "Wrong acpi table provided\n");
5607 exit(1);
5609 break;
5610 case QEMU_OPTION_smbios:
5611 if(smbios_entry_add(optarg) < 0) {
5612 fprintf(stderr, "Wrong smbios provided\n");
5613 exit(1);
5615 break;
5616 #endif
5617 #ifdef CONFIG_KQEMU
5618 case QEMU_OPTION_no_kqemu:
5619 kqemu_allowed = 0;
5620 break;
5621 case QEMU_OPTION_kernel_kqemu:
5622 kqemu_allowed = 2;
5623 break;
5624 #endif
5625 #ifdef CONFIG_KVM
5626 case QEMU_OPTION_enable_kvm:
5627 kvm_allowed = 1;
5628 #ifdef CONFIG_KQEMU
5629 kqemu_allowed = 0;
5630 #endif
5631 break;
5632 #endif
5633 #ifdef USE_KVM
5634 case QEMU_OPTION_no_kvm:
5635 kvm_allowed = 0;
5636 break;
5637 case QEMU_OPTION_no_kvm_irqchip: {
5638 kvm_irqchip = 0;
5639 kvm_pit = 0;
5640 break;
5642 case QEMU_OPTION_no_kvm_pit: {
5643 kvm_pit = 0;
5644 break;
5646 case QEMU_OPTION_no_kvm_pit_reinjection: {
5647 kvm_pit_reinject = 0;
5648 break;
5650 case QEMU_OPTION_enable_nesting: {
5651 kvm_nested = 1;
5652 break;
5654 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5655 case QEMU_OPTION_pcidevice:
5656 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5657 fprintf(stderr, "Too many assigned devices\n");
5658 exit(1);
5660 assigned_devices[assigned_devices_index] = optarg;
5661 assigned_devices_index++;
5662 break;
5663 #endif
5664 #endif
5665 case QEMU_OPTION_usb:
5666 usb_enabled = 1;
5667 break;
5668 case QEMU_OPTION_usbdevice:
5669 usb_enabled = 1;
5670 if (usb_devices_index >= MAX_USB_CMDLINE) {
5671 fprintf(stderr, "Too many USB devices\n");
5672 exit(1);
5674 usb_devices[usb_devices_index] = optarg;
5675 usb_devices_index++;
5676 break;
5677 case QEMU_OPTION_smp:
5678 smp_cpus = atoi(optarg);
5679 if (smp_cpus < 1) {
5680 fprintf(stderr, "Invalid number of CPUs\n");
5681 exit(1);
5683 break;
5684 case QEMU_OPTION_vnc:
5685 display_type = DT_VNC;
5686 vnc_display = optarg;
5687 break;
5688 #ifdef TARGET_I386
5689 case QEMU_OPTION_no_acpi:
5690 acpi_enabled = 0;
5691 break;
5692 case QEMU_OPTION_no_hpet:
5693 no_hpet = 1;
5694 break;
5695 case QEMU_OPTION_no_virtio_balloon:
5696 no_virtio_balloon = 1;
5697 break;
5698 #endif
5699 case QEMU_OPTION_no_reboot:
5700 no_reboot = 1;
5701 break;
5702 case QEMU_OPTION_no_shutdown:
5703 no_shutdown = 1;
5704 break;
5705 case QEMU_OPTION_show_cursor:
5706 cursor_hide = 0;
5707 break;
5708 case QEMU_OPTION_uuid:
5709 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5710 fprintf(stderr, "Fail to parse UUID string."
5711 " Wrong format.\n");
5712 exit(1);
5714 break;
5715 #ifndef _WIN32
5716 case QEMU_OPTION_daemonize:
5717 daemonize = 1;
5718 break;
5719 #endif
5720 case QEMU_OPTION_option_rom:
5721 if (nb_option_roms >= MAX_OPTION_ROMS) {
5722 fprintf(stderr, "Too many option ROMs\n");
5723 exit(1);
5725 option_rom[nb_option_roms] = optarg;
5726 nb_option_roms++;
5727 break;
5728 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5729 case QEMU_OPTION_semihosting:
5730 semihosting_enabled = 1;
5731 break;
5732 #endif
5733 case QEMU_OPTION_tdf:
5734 time_drift_fix = 1;
5735 break;
5736 case QEMU_OPTION_kvm_shadow_memory:
5737 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5738 break;
5739 case QEMU_OPTION_mempath:
5740 mem_path = optarg;
5741 break;
5742 #ifdef MAP_POPULATE
5743 case QEMU_OPTION_mem_prealloc:
5744 mem_prealloc = !mem_prealloc;
5745 break;
5746 #endif
5747 case QEMU_OPTION_name:
5748 qemu_name = optarg;
5749 break;
5750 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5751 case QEMU_OPTION_prom_env:
5752 if (nb_prom_envs >= MAX_PROM_ENVS) {
5753 fprintf(stderr, "Too many prom variables\n");
5754 exit(1);
5756 prom_envs[nb_prom_envs] = optarg;
5757 nb_prom_envs++;
5758 break;
5759 #endif
5760 #ifdef TARGET_ARM
5761 case QEMU_OPTION_old_param:
5762 old_param = 1;
5763 break;
5764 #endif
5765 case QEMU_OPTION_clock:
5766 configure_alarms(optarg);
5767 break;
5768 case QEMU_OPTION_startdate:
5770 struct tm tm;
5771 time_t rtc_start_date;
5772 if (!strcmp(optarg, "now")) {
5773 rtc_date_offset = -1;
5774 } else {
5775 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5776 &tm.tm_year,
5777 &tm.tm_mon,
5778 &tm.tm_mday,
5779 &tm.tm_hour,
5780 &tm.tm_min,
5781 &tm.tm_sec) == 6) {
5782 /* OK */
5783 } else if (sscanf(optarg, "%d-%d-%d",
5784 &tm.tm_year,
5785 &tm.tm_mon,
5786 &tm.tm_mday) == 3) {
5787 tm.tm_hour = 0;
5788 tm.tm_min = 0;
5789 tm.tm_sec = 0;
5790 } else {
5791 goto date_fail;
5793 tm.tm_year -= 1900;
5794 tm.tm_mon--;
5795 rtc_start_date = mktimegm(&tm);
5796 if (rtc_start_date == -1) {
5797 date_fail:
5798 fprintf(stderr, "Invalid date format. Valid format are:\n"
5799 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5800 exit(1);
5802 rtc_date_offset = time(NULL) - rtc_start_date;
5805 break;
5806 case QEMU_OPTION_tb_size:
5807 tb_size = strtol(optarg, NULL, 0);
5808 if (tb_size < 0)
5809 tb_size = 0;
5810 break;
5811 case QEMU_OPTION_icount:
5812 use_icount = 1;
5813 if (strcmp(optarg, "auto") == 0) {
5814 icount_time_shift = -1;
5815 } else {
5816 icount_time_shift = strtol(optarg, NULL, 0);
5818 break;
5819 case QEMU_OPTION_incoming:
5820 incoming = optarg;
5821 break;
5822 #ifndef _WIN32
5823 case QEMU_OPTION_chroot:
5824 chroot_dir = optarg;
5825 break;
5826 case QEMU_OPTION_runas:
5827 run_as = optarg;
5828 break;
5829 case QEMU_OPTION_nvram:
5830 nvram = optarg;
5831 break;
5832 #endif
5833 #ifdef CONFIG_XEN
5834 case QEMU_OPTION_xen_domid:
5835 xen_domid = atoi(optarg);
5836 break;
5837 case QEMU_OPTION_xen_create:
5838 xen_mode = XEN_CREATE;
5839 break;
5840 case QEMU_OPTION_xen_attach:
5841 xen_mode = XEN_ATTACH;
5842 break;
5843 #endif
5848 /* If no data_dir is specified then try to find it relative to the
5849 executable path. */
5850 if (!data_dir) {
5851 data_dir = find_datadir(argv[0]);
5853 /* If all else fails use the install patch specified when building. */
5854 if (!data_dir) {
5855 data_dir = CONFIG_QEMU_SHAREDIR;
5858 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5859 if (kvm_allowed && kqemu_allowed) {
5860 fprintf(stderr,
5861 "You can not enable both KVM and kqemu at the same time\n");
5862 exit(1);
5864 #endif
5866 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5867 if (smp_cpus > machine->max_cpus) {
5868 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5869 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5870 machine->max_cpus);
5871 exit(1);
5874 if (display_type == DT_NOGRAPHIC) {
5875 if (serial_device_index == 0)
5876 serial_devices[0] = "stdio";
5877 if (parallel_device_index == 0)
5878 parallel_devices[0] = "null";
5879 if (strncmp(monitor_device, "vc", 2) == 0)
5880 monitor_device = "stdio";
5883 #ifndef _WIN32
5884 if (daemonize) {
5885 pid_t pid;
5887 if (pipe(fds) == -1)
5888 exit(1);
5890 pid = fork();
5891 if (pid > 0) {
5892 uint8_t status;
5893 ssize_t len;
5895 close(fds[1]);
5897 again:
5898 len = read(fds[0], &status, 1);
5899 if (len == -1 && (errno == EINTR))
5900 goto again;
5902 if (len != 1)
5903 exit(1);
5904 else if (status == 1) {
5905 fprintf(stderr, "Could not acquire pidfile\n");
5906 exit(1);
5907 } else
5908 exit(0);
5909 } else if (pid < 0)
5910 exit(1);
5912 setsid();
5914 pid = fork();
5915 if (pid > 0)
5916 exit(0);
5917 else if (pid < 0)
5918 exit(1);
5920 umask(027);
5922 signal(SIGTSTP, SIG_IGN);
5923 signal(SIGTTOU, SIG_IGN);
5924 signal(SIGTTIN, SIG_IGN);
5927 #ifdef USE_KVM
5928 if (kvm_enabled()) {
5929 if (kvm_qemu_init() < 0) {
5930 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5931 #ifdef NO_CPU_EMULATION
5932 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5933 exit(1);
5934 #endif
5935 kvm_allowed = 0;
5938 #endif
5940 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5941 if (daemonize) {
5942 uint8_t status = 1;
5943 write(fds[1], &status, 1);
5944 } else
5945 fprintf(stderr, "Could not acquire pid file\n");
5946 exit(1);
5948 #endif
5950 #ifdef CONFIG_KQEMU
5951 if (smp_cpus > 1)
5952 kqemu_allowed = 0;
5953 #endif
5954 if (qemu_init_main_loop()) {
5955 fprintf(stderr, "qemu_init_main_loop failed\n");
5956 exit(1);
5958 linux_boot = (kernel_filename != NULL);
5960 if (!linux_boot && *kernel_cmdline != '\0') {
5961 fprintf(stderr, "-append only allowed with -kernel option\n");
5962 exit(1);
5965 if (!linux_boot && initrd_filename != NULL) {
5966 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5967 exit(1);
5970 /* boot to floppy or the default cd if no hard disk defined yet */
5971 if (!boot_devices[0]) {
5972 boot_devices = "cad";
5974 setvbuf(stdout, NULL, _IOLBF, 0);
5976 init_timers();
5977 if (init_timer_alarm() < 0) {
5978 fprintf(stderr, "could not initialize alarm timer\n");
5979 exit(1);
5981 if (use_icount && icount_time_shift < 0) {
5982 use_icount = 2;
5983 /* 125MIPS seems a reasonable initial guess at the guest speed.
5984 It will be corrected fairly quickly anyway. */
5985 icount_time_shift = 3;
5986 init_icount_adjust();
5989 #ifdef _WIN32
5990 socket_init();
5991 #endif
5993 /* init network clients */
5994 if (nb_net_clients == 0) {
5995 /* if no clients, we use a default config */
5996 net_clients[nb_net_clients++] = "nic";
5997 #ifdef CONFIG_SLIRP
5998 net_clients[nb_net_clients++] = "user";
5999 #endif
6002 for(i = 0;i < nb_net_clients; i++) {
6003 if (net_client_parse(net_clients[i]) < 0)
6004 exit(1);
6007 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
6008 net_set_boot_mask(net_boot);
6010 net_client_check();
6012 /* init the bluetooth world */
6013 for (i = 0; i < nb_bt_opts; i++)
6014 if (bt_parse(bt_opts[i]))
6015 exit(1);
6017 /* init the memory */
6018 if (ram_size == 0)
6019 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6021 if (kvm_enabled()) {
6022 if (kvm_qemu_create_context() < 0) {
6023 fprintf(stderr, "Could not create KVM context\n");
6024 exit(1);
6028 #ifdef CONFIG_KQEMU
6029 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
6030 guest ram allocation. It needs to go away. */
6031 if (kqemu_allowed) {
6032 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
6033 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
6034 if (!kqemu_phys_ram_base) {
6035 fprintf(stderr, "Could not allocate physical memory\n");
6036 exit(1);
6039 #endif
6041 /* init the dynamic translator */
6042 cpu_exec_init_all(tb_size * 1024 * 1024);
6044 bdrv_init();
6046 /* we always create the cdrom drive, even if no disk is there */
6048 if (nb_drives_opt < MAX_DRIVES)
6049 drive_add(NULL, CDROM_ALIAS);
6051 /* we always create at least one floppy */
6053 if (nb_drives_opt < MAX_DRIVES)
6054 drive_add(NULL, FD_ALIAS, 0);
6056 /* we always create one sd slot, even if no card is in it */
6058 if (nb_drives_opt < MAX_DRIVES)
6059 drive_add(NULL, SD_ALIAS);
6061 /* open the virtual block devices
6062 * note that migration with device
6063 * hot add/remove is broken.
6065 for(i = 0; i < nb_drives_opt; i++)
6066 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
6067 exit(1);
6069 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6070 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
6072 #ifndef _WIN32
6073 /* must be after terminal init, SDL library changes signal handlers */
6074 sighandler_setup();
6075 #endif
6077 /* Maintain compatibility with multiple stdio monitors */
6078 if (!strcmp(monitor_device,"stdio")) {
6079 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
6080 const char *devname = serial_devices[i];
6081 if (devname && !strcmp(devname,"mon:stdio")) {
6082 monitor_device = NULL;
6083 break;
6084 } else if (devname && !strcmp(devname,"stdio")) {
6085 monitor_device = NULL;
6086 serial_devices[i] = "mon:stdio";
6087 break;
6092 if (nb_numa_nodes > 0) {
6093 int i;
6095 if (nb_numa_nodes > smp_cpus) {
6096 nb_numa_nodes = smp_cpus;
6099 /* If no memory size if given for any node, assume the default case
6100 * and distribute the available memory equally across all nodes
6102 for (i = 0; i < nb_numa_nodes; i++) {
6103 if (node_mem[i] != 0)
6104 break;
6106 if (i == nb_numa_nodes) {
6107 uint64_t usedmem = 0;
6109 /* On Linux, the each node's border has to be 8MB aligned,
6110 * the final node gets the rest.
6112 for (i = 0; i < nb_numa_nodes - 1; i++) {
6113 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
6114 usedmem += node_mem[i];
6116 node_mem[i] = ram_size - usedmem;
6119 for (i = 0; i < nb_numa_nodes; i++) {
6120 if (node_cpumask[i] != 0)
6121 break;
6123 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6124 * must cope with this anyway, because there are BIOSes out there in
6125 * real machines which also use this scheme.
6127 if (i == nb_numa_nodes) {
6128 for (i = 0; i < smp_cpus; i++) {
6129 node_cpumask[i % nb_numa_nodes] |= 1 << i;
6134 #ifdef KVM_UPSTREAM
6135 if (kvm_enabled()) {
6136 int ret;
6138 ret = kvm_init(smp_cpus);
6139 if (ret < 0) {
6140 fprintf(stderr, "failed to initialize KVM\n");
6141 exit(1);
6144 #endif
6146 if (monitor_device) {
6147 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
6148 if (!monitor_hd) {
6149 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6150 exit(1);
6154 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6155 const char *devname = serial_devices[i];
6156 if (devname && strcmp(devname, "none")) {
6157 char label[32];
6158 snprintf(label, sizeof(label), "serial%d", i);
6159 serial_hds[i] = qemu_chr_open(label, devname, NULL);
6160 if (!serial_hds[i]) {
6161 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6162 devname);
6163 exit(1);
6168 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6169 const char *devname = parallel_devices[i];
6170 if (devname && strcmp(devname, "none")) {
6171 char label[32];
6172 snprintf(label, sizeof(label), "parallel%d", i);
6173 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
6174 if (!parallel_hds[i]) {
6175 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6176 devname);
6177 exit(1);
6182 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6183 const char *devname = virtio_consoles[i];
6184 if (devname && strcmp(devname, "none")) {
6185 char label[32];
6186 snprintf(label, sizeof(label), "virtcon%d", i);
6187 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
6188 if (!virtcon_hds[i]) {
6189 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
6190 devname);
6191 exit(1);
6196 module_call_init(MODULE_INIT_DEVICE);
6198 if (kvm_enabled())
6199 kvm_init_ap();
6201 machine->init(ram_size, boot_devices,
6202 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6205 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6206 for (i = 0; i < nb_numa_nodes; i++) {
6207 if (node_cpumask[i] & (1 << env->cpu_index)) {
6208 env->numa_node = i;
6213 current_machine = machine;
6215 /* Set KVM's vcpu state to qemu's initial CPUState. */
6216 if (kvm_enabled()) {
6217 int ret;
6219 ret = kvm_sync_vcpus();
6220 if (ret < 0) {
6221 fprintf(stderr, "failed to initialize vcpus\n");
6222 exit(1);
6226 /* init USB devices */
6227 if (usb_enabled) {
6228 for(i = 0; i < usb_devices_index; i++) {
6229 if (usb_device_add(usb_devices[i], 0) < 0) {
6230 fprintf(stderr, "Warning: could not add USB device %s\n",
6231 usb_devices[i]);
6236 if (!display_state)
6237 dumb_display_init();
6238 /* just use the first displaystate for the moment */
6239 ds = display_state;
6241 if (display_type == DT_DEFAULT) {
6242 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6243 display_type = DT_SDL;
6244 #else
6245 display_type = DT_VNC;
6246 vnc_display = "localhost:0,to=99";
6247 show_vnc_port = 1;
6248 #endif
6252 switch (display_type) {
6253 case DT_NOGRAPHIC:
6254 break;
6255 #if defined(CONFIG_CURSES)
6256 case DT_CURSES:
6257 curses_display_init(ds, full_screen);
6258 break;
6259 #endif
6260 #if defined(CONFIG_SDL)
6261 case DT_SDL:
6262 sdl_display_init(ds, full_screen, no_frame);
6263 break;
6264 #elif defined(CONFIG_COCOA)
6265 case DT_SDL:
6266 cocoa_display_init(ds, full_screen);
6267 break;
6268 #endif
6269 case DT_VNC:
6270 vnc_display_init(ds);
6271 if (vnc_display_open(ds, vnc_display) < 0)
6272 exit(1);
6274 if (show_vnc_port) {
6275 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6277 break;
6278 default:
6279 break;
6281 dpy_resize(ds);
6283 dcl = ds->listeners;
6284 while (dcl != NULL) {
6285 if (dcl->dpy_refresh != NULL) {
6286 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6287 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6289 dcl = dcl->next;
6292 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6293 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6294 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6297 text_consoles_set_display(display_state);
6298 qemu_chr_initial_reset();
6300 if (monitor_device && monitor_hd)
6301 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6303 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6304 const char *devname = serial_devices[i];
6305 if (devname && strcmp(devname, "none")) {
6306 if (strstart(devname, "vc", 0))
6307 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6311 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6312 const char *devname = parallel_devices[i];
6313 if (devname && strcmp(devname, "none")) {
6314 if (strstart(devname, "vc", 0))
6315 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6319 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6320 const char *devname = virtio_consoles[i];
6321 if (virtcon_hds[i] && devname) {
6322 if (strstart(devname, "vc", 0))
6323 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6327 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6328 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6329 gdbstub_dev);
6330 exit(1);
6333 if (loadvm)
6334 do_loadvm(cur_mon, loadvm);
6336 if (incoming) {
6337 autostart = 0; /* fixme how to deal with -daemonize */
6338 qemu_start_incoming_migration(incoming);
6341 if (autostart)
6342 vm_start();
6344 #ifndef _WIN32
6345 if (daemonize) {
6346 uint8_t status = 0;
6347 ssize_t len;
6349 again1:
6350 len = write(fds[1], &status, 1);
6351 if (len == -1 && (errno == EINTR))
6352 goto again1;
6354 if (len != 1)
6355 exit(1);
6357 chdir("/");
6358 TFR(fd = open("/dev/null", O_RDWR));
6359 if (fd == -1)
6360 exit(1);
6363 if (run_as) {
6364 pwd = getpwnam(run_as);
6365 if (!pwd) {
6366 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6367 exit(1);
6371 if (chroot_dir) {
6372 if (chroot(chroot_dir) < 0) {
6373 fprintf(stderr, "chroot failed\n");
6374 exit(1);
6376 chdir("/");
6379 if (run_as) {
6380 if (setgid(pwd->pw_gid) < 0) {
6381 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6382 exit(1);
6384 if (setuid(pwd->pw_uid) < 0) {
6385 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6386 exit(1);
6388 if (setuid(0) != -1) {
6389 fprintf(stderr, "Dropping privileges failed\n");
6390 exit(1);
6394 if (daemonize) {
6395 dup2(fd, 0);
6396 dup2(fd, 1);
6397 dup2(fd, 2);
6399 close(fd);
6401 #endif
6403 main_loop();
6404 quit_timers();
6405 net_cleanup();
6407 return 0;