Merge commit '6dbe553fe9ffdee008c1bbbe1af2d030e0f04aab' into upstream-merge
[qemu-kvm/fedora.git] / vl.c
blobcf52ed299a06cb252304b4164f419709f29ad843
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
32 /* Needed early for HOST_BSD etc. */
33 #include "config-host.h"
35 #ifndef _WIN32
36 #include <libgen.h>
37 #include <pwd.h>
38 #include <sys/times.h>
39 #include <sys/wait.h>
40 #include <termios.h>
41 #include <sys/mman.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <net/if.h>
47 #if defined(__NetBSD__)
48 #include <net/if_tap.h>
49 #endif
50 #ifdef __linux__
51 #include <linux/if_tun.h>
52 #endif
53 #include <arpa/inet.h>
54 #include <dirent.h>
55 #include <netdb.h>
56 #include <sys/select.h>
57 #ifdef HOST_BSD
58 #include <sys/stat.h>
59 #if defined(__FreeBSD__) || defined(__DragonFly__)
60 #include <libutil.h>
61 #else
62 #include <util.h>
63 #endif
64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65 #include <freebsd/stdlib.h>
66 #else
67 #ifdef __linux__
68 #include <pty.h>
69 #include <malloc.h>
70 #include <linux/rtc.h>
72 /* For the benefit of older linux systems which don't supply it,
73 we use a local copy of hpet.h. */
74 /* #include <linux/hpet.h> */
75 #include "hpet.h"
77 #include <linux/ppdev.h>
78 #include <linux/parport.h>
79 #endif
80 #ifdef __sun__
81 #include <sys/stat.h>
82 #include <sys/ethernet.h>
83 #include <sys/sockio.h>
84 #include <netinet/arp.h>
85 #include <netinet/in.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip_icmp.h> // must come after ip.h
89 #include <netinet/udp.h>
90 #include <netinet/tcp.h>
91 #include <net/if.h>
92 #include <syslog.h>
93 #include <stropts.h>
94 #endif
95 #endif
96 #endif
98 #if defined(__OpenBSD__)
99 #include <util.h>
100 #endif
102 #if defined(CONFIG_VDE)
103 #include <libvdeplug.h>
104 #endif
106 #ifdef _WIN32
107 #include <windows.h>
108 #include <malloc.h>
109 #include <sys/timeb.h>
110 #include <mmsystem.h>
111 #define getopt_long_only getopt_long
112 #define memalign(align, size) malloc(size)
113 #endif
115 #ifdef CONFIG_SDL
116 #if defined(__APPLE__) || defined(main)
117 #include <SDL.h>
118 int qemu_main(int argc, char **argv, char **envp);
119 int main(int argc, char **argv)
121 return qemu_main(argc, argv, NULL);
123 #undef main
124 #define main qemu_main
125 #endif
126 #endif /* CONFIG_SDL */
128 #ifdef CONFIG_COCOA
129 #undef main
130 #define main qemu_main
131 #endif /* CONFIG_COCOA */
133 #include "hw/hw.h"
134 #include "hw/boards.h"
135 #include "hw/usb.h"
136 #include "hw/pcmcia.h"
137 #include "hw/pc.h"
138 #include "hw/audiodev.h"
139 #include "hw/isa.h"
140 #include "hw/baum.h"
141 #include "hw/bt.h"
142 #include "hw/watchdog.h"
143 #include "hw/smbios.h"
144 #include "hw/xen.h"
145 #include "bt-host.h"
146 #include "net.h"
147 #include "monitor.h"
148 #include "console.h"
149 #include "sysemu.h"
150 #include "gdbstub.h"
151 #include "qemu-timer.h"
152 #include "qemu-char.h"
153 #include "cache-utils.h"
154 #include "block.h"
155 #include "dma.h"
156 #include "audio/audio.h"
157 #include "migration.h"
158 #include "kvm.h"
159 #include "balloon.h"
160 #include "qemu-option.h"
161 #include "qemu-kvm.h"
162 #include "hw/device-assignment.h"
164 #include "disas.h"
166 #include "exec-all.h"
168 #include "qemu_socket.h"
170 #if defined(CONFIG_SLIRP)
171 #include "libslirp.h"
172 #endif
174 //#define DEBUG_UNUSED_IOPORT
175 //#define DEBUG_IOPORT
176 //#define DEBUG_NET
177 //#define DEBUG_SLIRP
180 #ifdef DEBUG_IOPORT
181 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
182 #else
183 # define LOG_IOPORT(...) do { } while (0)
184 #endif
186 #define DEFAULT_RAM_SIZE 128
188 /* Max number of USB devices that can be specified on the commandline. */
189 #define MAX_USB_CMDLINE 8
191 /* Max number of bluetooth switches on the commandline. */
192 #define MAX_BT_CMDLINE 10
194 /* XXX: use a two level table to limit memory usage */
195 #define MAX_IOPORTS 65536
197 static const char *data_dir;
198 const char *bios_name = NULL;
199 static void *ioport_opaque[MAX_IOPORTS];
200 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
201 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
202 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
203 to store the VM snapshots */
204 DriveInfo drives_table[MAX_DRIVES+1];
205 int nb_drives;
206 int extboot_drive = -1;
207 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
208 static DisplayState *display_state;
209 DisplayType display_type = DT_DEFAULT;
210 const char* keyboard_layout = NULL;
211 int64_t ticks_per_sec;
212 ram_addr_t ram_size;
213 int nb_nics;
214 NICInfo nd_table[MAX_NICS];
215 int vm_running;
216 static int autostart;
217 static int rtc_utc = 1;
218 static int rtc_date_offset = -1; /* -1 means no change */
219 int cirrus_vga_enabled = 1;
220 int std_vga_enabled = 0;
221 int vmsvga_enabled = 0;
222 int xenfb_enabled = 0;
223 #ifdef TARGET_SPARC
224 int graphic_width = 1024;
225 int graphic_height = 768;
226 int graphic_depth = 8;
227 #else
228 int graphic_width = 800;
229 int graphic_height = 600;
230 int graphic_depth = 15;
231 #endif
232 static int full_screen = 0;
233 #ifdef CONFIG_SDL
234 static int no_frame = 0;
235 #endif
236 int no_quit = 0;
237 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
238 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
239 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
240 #ifdef TARGET_I386
241 int win2k_install_hack = 0;
242 int rtc_td_hack = 0;
243 #endif
244 int usb_enabled = 0;
245 int singlestep = 0;
246 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
247 int assigned_devices_index;
248 int smp_cpus = 1;
249 const char *vnc_display;
250 int acpi_enabled = 1;
251 int no_hpet = 0;
252 int no_virtio_balloon = 0;
253 int fd_bootchk = 1;
254 int no_reboot = 0;
255 int no_shutdown = 0;
256 int cursor_hide = 1;
257 int graphic_rotate = 0;
258 #ifndef _WIN32
259 int daemonize = 0;
260 #endif
261 WatchdogTimerModel *watchdog = NULL;
262 int watchdog_action = WDT_RESET;
263 const char *option_rom[MAX_OPTION_ROMS];
264 int nb_option_roms;
265 int semihosting_enabled = 0;
266 int time_drift_fix = 0;
267 unsigned int kvm_shadow_memory = 0;
268 const char *mem_path = NULL;
269 #ifdef MAP_POPULATE
270 int mem_prealloc = 1; /* force preallocation of physical target memory */
271 #endif
272 #ifdef TARGET_ARM
273 int old_param = 0;
274 #endif
275 const char *qemu_name;
276 int alt_grab = 0;
277 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
278 unsigned int nb_prom_envs = 0;
279 const char *prom_envs[MAX_PROM_ENVS];
280 #endif
281 int nb_drives_opt;
282 const char *nvram = NULL;
283 struct drive_opt drives_opt[MAX_DRIVES];
285 int nb_numa_nodes;
286 uint64_t node_mem[MAX_NODES];
287 uint64_t node_cpumask[MAX_NODES];
289 static CPUState *cur_cpu;
290 static CPUState *next_cpu;
291 static int timer_alarm_pending = 1;
292 /* Conversion factor from emulated instructions to virtual clock ticks. */
293 static int icount_time_shift;
294 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
295 #define MAX_ICOUNT_SHIFT 10
296 /* Compensate for varying guest execution speed. */
297 static int64_t qemu_icount_bias;
298 static QEMUTimer *icount_rt_timer;
299 static QEMUTimer *icount_vm_timer;
300 static QEMUTimer *nographic_timer;
302 uint8_t qemu_uuid[16];
304 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
305 struct timeval *tv)
307 int ret;
309 /* KVM holds a mutex while QEMU code is running, we need hooks to
310 release the mutex whenever QEMU code sleeps. */
312 kvm_sleep_begin();
314 ret = select(max_fd, rfds, wfds, xfds, tv);
316 kvm_sleep_end();
318 return ret;
322 /***********************************************************/
323 /* x86 ISA bus support */
325 target_phys_addr_t isa_mem_base = 0;
326 PicState2 *isa_pic;
328 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
329 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
331 static uint32_t ioport_read(int index, uint32_t address)
333 static IOPortReadFunc *default_func[3] = {
334 default_ioport_readb,
335 default_ioport_readw,
336 default_ioport_readl
338 IOPortReadFunc *func = ioport_read_table[index][address];
339 if (!func)
340 func = default_func[index];
341 return func(ioport_opaque[address], address);
344 static void ioport_write(int index, uint32_t address, uint32_t data)
346 static IOPortWriteFunc *default_func[3] = {
347 default_ioport_writeb,
348 default_ioport_writew,
349 default_ioport_writel
351 IOPortWriteFunc *func = ioport_write_table[index][address];
352 if (!func)
353 func = default_func[index];
354 func(ioport_opaque[address], address, data);
357 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
359 #ifdef DEBUG_UNUSED_IOPORT
360 fprintf(stderr, "unused inb: port=0x%04x\n", address);
361 #endif
362 return 0xff;
365 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
367 #ifdef DEBUG_UNUSED_IOPORT
368 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
369 #endif
372 /* default is to make two byte accesses */
373 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
375 uint32_t data;
376 data = ioport_read(0, address);
377 address = (address + 1) & (MAX_IOPORTS - 1);
378 data |= ioport_read(0, address) << 8;
379 return data;
382 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
384 ioport_write(0, address, data & 0xff);
385 address = (address + 1) & (MAX_IOPORTS - 1);
386 ioport_write(0, address, (data >> 8) & 0xff);
389 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
391 #ifdef DEBUG_UNUSED_IOPORT
392 fprintf(stderr, "unused inl: port=0x%04x\n", address);
393 #endif
394 return 0xffffffff;
397 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
399 #ifdef DEBUG_UNUSED_IOPORT
400 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
401 #endif
404 /* size is the word size in byte */
405 int register_ioport_read(int start, int length, int size,
406 IOPortReadFunc *func, void *opaque)
408 int i, bsize;
410 if (size == 1) {
411 bsize = 0;
412 } else if (size == 2) {
413 bsize = 1;
414 } else if (size == 4) {
415 bsize = 2;
416 } else {
417 hw_error("register_ioport_read: invalid size");
418 return -1;
420 for(i = start; i < start + length; i += size) {
421 ioport_read_table[bsize][i] = func;
422 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
423 hw_error("register_ioport_read: invalid opaque");
424 ioport_opaque[i] = opaque;
426 return 0;
429 /* size is the word size in byte */
430 int register_ioport_write(int start, int length, int size,
431 IOPortWriteFunc *func, void *opaque)
433 int i, bsize;
435 if (size == 1) {
436 bsize = 0;
437 } else if (size == 2) {
438 bsize = 1;
439 } else if (size == 4) {
440 bsize = 2;
441 } else {
442 hw_error("register_ioport_write: invalid size");
443 return -1;
445 for(i = start; i < start + length; i += size) {
446 ioport_write_table[bsize][i] = func;
447 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
448 hw_error("register_ioport_write: invalid opaque");
449 ioport_opaque[i] = opaque;
451 return 0;
454 void isa_unassign_ioport(int start, int length)
456 int i;
458 for(i = start; i < start + length; i++) {
459 ioport_read_table[0][i] = default_ioport_readb;
460 ioport_read_table[1][i] = default_ioport_readw;
461 ioport_read_table[2][i] = default_ioport_readl;
463 ioport_write_table[0][i] = default_ioport_writeb;
464 ioport_write_table[1][i] = default_ioport_writew;
465 ioport_write_table[2][i] = default_ioport_writel;
467 ioport_opaque[i] = NULL;
471 /***********************************************************/
473 void cpu_outb(CPUState *env, int addr, int val)
475 LOG_IOPORT("outb: %04x %02x\n", addr, val);
476 ioport_write(0, addr, val);
477 #ifdef CONFIG_KQEMU
478 if (env)
479 env->last_io_time = cpu_get_time_fast();
480 #endif
483 void cpu_outw(CPUState *env, int addr, int val)
485 LOG_IOPORT("outw: %04x %04x\n", addr, val);
486 ioport_write(1, addr, val);
487 #ifdef CONFIG_KQEMU
488 if (env)
489 env->last_io_time = cpu_get_time_fast();
490 #endif
493 void cpu_outl(CPUState *env, int addr, int val)
495 LOG_IOPORT("outl: %04x %08x\n", addr, val);
496 ioport_write(2, addr, val);
497 #ifdef CONFIG_KQEMU
498 if (env)
499 env->last_io_time = cpu_get_time_fast();
500 #endif
503 int cpu_inb(CPUState *env, int addr)
505 int val;
506 val = ioport_read(0, addr);
507 LOG_IOPORT("inb : %04x %02x\n", addr, val);
508 #ifdef CONFIG_KQEMU
509 if (env)
510 env->last_io_time = cpu_get_time_fast();
511 #endif
512 return val;
515 int cpu_inw(CPUState *env, int addr)
517 int val;
518 val = ioport_read(1, addr);
519 LOG_IOPORT("inw : %04x %04x\n", addr, val);
520 #ifdef CONFIG_KQEMU
521 if (env)
522 env->last_io_time = cpu_get_time_fast();
523 #endif
524 return val;
527 int cpu_inl(CPUState *env, int addr)
529 int val;
530 val = ioport_read(2, addr);
531 LOG_IOPORT("inl : %04x %08x\n", addr, val);
532 #ifdef CONFIG_KQEMU
533 if (env)
534 env->last_io_time = cpu_get_time_fast();
535 #endif
536 return val;
539 /***********************************************************/
540 void hw_error(const char *fmt, ...)
542 va_list ap;
543 CPUState *env;
545 va_start(ap, fmt);
546 fprintf(stderr, "qemu: hardware error: ");
547 vfprintf(stderr, fmt, ap);
548 fprintf(stderr, "\n");
549 for(env = first_cpu; env != NULL; env = env->next_cpu) {
550 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
551 #ifdef TARGET_I386
552 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
553 #else
554 cpu_dump_state(env, stderr, fprintf, 0);
555 #endif
557 va_end(ap);
558 abort();
561 /***************/
562 /* ballooning */
564 static QEMUBalloonEvent *qemu_balloon_event;
565 void *qemu_balloon_event_opaque;
567 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
569 qemu_balloon_event = func;
570 qemu_balloon_event_opaque = opaque;
573 void qemu_balloon(ram_addr_t target)
575 if (qemu_balloon_event)
576 qemu_balloon_event(qemu_balloon_event_opaque, target);
579 ram_addr_t qemu_balloon_status(void)
581 if (qemu_balloon_event)
582 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
583 return 0;
586 /***********************************************************/
587 /* keyboard/mouse */
589 static QEMUPutKBDEvent *qemu_put_kbd_event;
590 static void *qemu_put_kbd_event_opaque;
591 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
592 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
594 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
596 qemu_put_kbd_event_opaque = opaque;
597 qemu_put_kbd_event = func;
600 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
601 void *opaque, int absolute,
602 const char *name)
604 QEMUPutMouseEntry *s, *cursor;
606 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
608 s->qemu_put_mouse_event = func;
609 s->qemu_put_mouse_event_opaque = opaque;
610 s->qemu_put_mouse_event_absolute = absolute;
611 s->qemu_put_mouse_event_name = qemu_strdup(name);
612 s->next = NULL;
614 if (!qemu_put_mouse_event_head) {
615 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
616 return s;
619 cursor = qemu_put_mouse_event_head;
620 while (cursor->next != NULL)
621 cursor = cursor->next;
623 cursor->next = s;
624 qemu_put_mouse_event_current = s;
626 return s;
629 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
631 QEMUPutMouseEntry *prev = NULL, *cursor;
633 if (!qemu_put_mouse_event_head || entry == NULL)
634 return;
636 cursor = qemu_put_mouse_event_head;
637 while (cursor != NULL && cursor != entry) {
638 prev = cursor;
639 cursor = cursor->next;
642 if (cursor == NULL) // does not exist or list empty
643 return;
644 else if (prev == NULL) { // entry is head
645 qemu_put_mouse_event_head = cursor->next;
646 if (qemu_put_mouse_event_current == entry)
647 qemu_put_mouse_event_current = cursor->next;
648 qemu_free(entry->qemu_put_mouse_event_name);
649 qemu_free(entry);
650 return;
653 prev->next = entry->next;
655 if (qemu_put_mouse_event_current == entry)
656 qemu_put_mouse_event_current = prev;
658 qemu_free(entry->qemu_put_mouse_event_name);
659 qemu_free(entry);
662 void kbd_put_keycode(int keycode)
664 if (qemu_put_kbd_event) {
665 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
669 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
671 QEMUPutMouseEvent *mouse_event;
672 void *mouse_event_opaque;
673 int width;
675 if (!qemu_put_mouse_event_current) {
676 return;
679 mouse_event =
680 qemu_put_mouse_event_current->qemu_put_mouse_event;
681 mouse_event_opaque =
682 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
684 if (mouse_event) {
685 if (graphic_rotate) {
686 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
687 width = 0x7fff;
688 else
689 width = graphic_width - 1;
690 mouse_event(mouse_event_opaque,
691 width - dy, dx, dz, buttons_state);
692 } else
693 mouse_event(mouse_event_opaque,
694 dx, dy, dz, buttons_state);
698 int kbd_mouse_is_absolute(void)
700 if (!qemu_put_mouse_event_current)
701 return 0;
703 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
706 void do_info_mice(Monitor *mon)
708 QEMUPutMouseEntry *cursor;
709 int index = 0;
711 if (!qemu_put_mouse_event_head) {
712 monitor_printf(mon, "No mouse devices connected\n");
713 return;
716 monitor_printf(mon, "Mouse devices available:\n");
717 cursor = qemu_put_mouse_event_head;
718 while (cursor != NULL) {
719 monitor_printf(mon, "%c Mouse #%d: %s\n",
720 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
721 index, cursor->qemu_put_mouse_event_name);
722 index++;
723 cursor = cursor->next;
727 void do_mouse_set(Monitor *mon, int index)
729 QEMUPutMouseEntry *cursor;
730 int i = 0;
732 if (!qemu_put_mouse_event_head) {
733 monitor_printf(mon, "No mouse devices connected\n");
734 return;
737 cursor = qemu_put_mouse_event_head;
738 while (cursor != NULL && index != i) {
739 i++;
740 cursor = cursor->next;
743 if (cursor != NULL)
744 qemu_put_mouse_event_current = cursor;
745 else
746 monitor_printf(mon, "Mouse at given index not found\n");
749 /* compute with 96 bit intermediate result: (a*b)/c */
750 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
752 union {
753 uint64_t ll;
754 struct {
755 #ifdef WORDS_BIGENDIAN
756 uint32_t high, low;
757 #else
758 uint32_t low, high;
759 #endif
760 } l;
761 } u, res;
762 uint64_t rl, rh;
764 u.ll = a;
765 rl = (uint64_t)u.l.low * (uint64_t)b;
766 rh = (uint64_t)u.l.high * (uint64_t)b;
767 rh += (rl >> 32);
768 res.l.high = rh / c;
769 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
770 return res.ll;
773 /***********************************************************/
774 /* real time host monotonic timer */
776 #define QEMU_TIMER_BASE 1000000000LL
778 #ifdef WIN32
780 static int64_t clock_freq;
782 static void init_get_clock(void)
784 LARGE_INTEGER freq;
785 int ret;
786 ret = QueryPerformanceFrequency(&freq);
787 if (ret == 0) {
788 fprintf(stderr, "Could not calibrate ticks\n");
789 exit(1);
791 clock_freq = freq.QuadPart;
794 static int64_t get_clock(void)
796 LARGE_INTEGER ti;
797 QueryPerformanceCounter(&ti);
798 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
801 #else
803 static int use_rt_clock;
805 static void init_get_clock(void)
807 use_rt_clock = 0;
808 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
809 || defined(__DragonFly__)
811 struct timespec ts;
812 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
813 use_rt_clock = 1;
816 #endif
819 static int64_t get_clock(void)
821 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
822 || defined(__DragonFly__)
823 if (use_rt_clock) {
824 struct timespec ts;
825 clock_gettime(CLOCK_MONOTONIC, &ts);
826 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
827 } else
828 #endif
830 /* XXX: using gettimeofday leads to problems if the date
831 changes, so it should be avoided. */
832 struct timeval tv;
833 gettimeofday(&tv, NULL);
834 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
837 #endif
839 /* Return the virtual CPU time, based on the instruction counter. */
840 static int64_t cpu_get_icount(void)
842 int64_t icount;
843 CPUState *env = cpu_single_env;;
844 icount = qemu_icount;
845 if (env) {
846 if (!can_do_io(env))
847 fprintf(stderr, "Bad clock read\n");
848 icount -= (env->icount_decr.u16.low + env->icount_extra);
850 return qemu_icount_bias + (icount << icount_time_shift);
853 /***********************************************************/
854 /* guest cycle counter */
856 static int64_t cpu_ticks_prev;
857 static int64_t cpu_ticks_offset;
858 static int64_t cpu_clock_offset;
859 static int cpu_ticks_enabled;
861 /* return the host CPU cycle counter and handle stop/restart */
862 int64_t cpu_get_ticks(void)
864 if (use_icount) {
865 return cpu_get_icount();
867 if (!cpu_ticks_enabled) {
868 return cpu_ticks_offset;
869 } else {
870 int64_t ticks;
871 ticks = cpu_get_real_ticks();
872 if (cpu_ticks_prev > ticks) {
873 /* Note: non increasing ticks may happen if the host uses
874 software suspend */
875 cpu_ticks_offset += cpu_ticks_prev - ticks;
877 cpu_ticks_prev = ticks;
878 return ticks + cpu_ticks_offset;
882 /* return the host CPU monotonic timer and handle stop/restart */
883 static int64_t cpu_get_clock(void)
885 int64_t ti;
886 if (!cpu_ticks_enabled) {
887 return cpu_clock_offset;
888 } else {
889 ti = get_clock();
890 return ti + cpu_clock_offset;
894 /* enable cpu_get_ticks() */
895 void cpu_enable_ticks(void)
897 if (!cpu_ticks_enabled) {
898 cpu_ticks_offset -= cpu_get_real_ticks();
899 cpu_clock_offset -= get_clock();
900 cpu_ticks_enabled = 1;
904 /* disable cpu_get_ticks() : the clock is stopped. You must not call
905 cpu_get_ticks() after that. */
906 void cpu_disable_ticks(void)
908 if (cpu_ticks_enabled) {
909 cpu_ticks_offset = cpu_get_ticks();
910 cpu_clock_offset = cpu_get_clock();
911 cpu_ticks_enabled = 0;
915 /***********************************************************/
916 /* timers */
918 #define QEMU_TIMER_REALTIME 0
919 #define QEMU_TIMER_VIRTUAL 1
921 struct QEMUClock {
922 int type;
923 /* XXX: add frequency */
926 struct QEMUTimer {
927 QEMUClock *clock;
928 int64_t expire_time;
929 QEMUTimerCB *cb;
930 void *opaque;
931 struct QEMUTimer *next;
934 struct qemu_alarm_timer {
935 char const *name;
936 unsigned int flags;
938 int (*start)(struct qemu_alarm_timer *t);
939 void (*stop)(struct qemu_alarm_timer *t);
940 void (*rearm)(struct qemu_alarm_timer *t);
941 void *priv;
944 #define ALARM_FLAG_DYNTICKS 0x1
945 #define ALARM_FLAG_EXPIRED 0x2
947 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
949 return t && (t->flags & ALARM_FLAG_DYNTICKS);
952 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
954 if (!alarm_has_dynticks(t))
955 return;
957 t->rearm(t);
960 /* TODO: MIN_TIMER_REARM_US should be optimized */
961 #define MIN_TIMER_REARM_US 250
963 static struct qemu_alarm_timer *alarm_timer;
965 #ifdef _WIN32
967 struct qemu_alarm_win32 {
968 MMRESULT timerId;
969 unsigned int period;
970 } alarm_win32_data = {0, -1};
972 static int win32_start_timer(struct qemu_alarm_timer *t);
973 static void win32_stop_timer(struct qemu_alarm_timer *t);
974 static void win32_rearm_timer(struct qemu_alarm_timer *t);
976 #else
978 static int unix_start_timer(struct qemu_alarm_timer *t);
979 static void unix_stop_timer(struct qemu_alarm_timer *t);
981 #ifdef __linux__
983 static int dynticks_start_timer(struct qemu_alarm_timer *t);
984 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
985 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
987 static int hpet_start_timer(struct qemu_alarm_timer *t);
988 static void hpet_stop_timer(struct qemu_alarm_timer *t);
990 static int rtc_start_timer(struct qemu_alarm_timer *t);
991 static void rtc_stop_timer(struct qemu_alarm_timer *t);
993 #endif /* __linux__ */
995 #endif /* _WIN32 */
997 /* Correlation between real and virtual time is always going to be
998 fairly approximate, so ignore small variation.
999 When the guest is idle real and virtual time will be aligned in
1000 the IO wait loop. */
1001 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
1003 static void icount_adjust(void)
1005 int64_t cur_time;
1006 int64_t cur_icount;
1007 int64_t delta;
1008 static int64_t last_delta;
1009 /* If the VM is not running, then do nothing. */
1010 if (!vm_running)
1011 return;
1013 cur_time = cpu_get_clock();
1014 cur_icount = qemu_get_clock(vm_clock);
1015 delta = cur_icount - cur_time;
1016 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1017 if (delta > 0
1018 && last_delta + ICOUNT_WOBBLE < delta * 2
1019 && icount_time_shift > 0) {
1020 /* The guest is getting too far ahead. Slow time down. */
1021 icount_time_shift--;
1023 if (delta < 0
1024 && last_delta - ICOUNT_WOBBLE > delta * 2
1025 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1026 /* The guest is getting too far behind. Speed time up. */
1027 icount_time_shift++;
1029 last_delta = delta;
1030 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1033 static void icount_adjust_rt(void * opaque)
1035 qemu_mod_timer(icount_rt_timer,
1036 qemu_get_clock(rt_clock) + 1000);
1037 icount_adjust();
1040 static void icount_adjust_vm(void * opaque)
1042 qemu_mod_timer(icount_vm_timer,
1043 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1044 icount_adjust();
1047 static void init_icount_adjust(void)
1049 /* Have both realtime and virtual time triggers for speed adjustment.
1050 The realtime trigger catches emulated time passing too slowly,
1051 the virtual time trigger catches emulated time passing too fast.
1052 Realtime triggers occur even when idle, so use them less frequently
1053 than VM triggers. */
1054 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1055 qemu_mod_timer(icount_rt_timer,
1056 qemu_get_clock(rt_clock) + 1000);
1057 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1058 qemu_mod_timer(icount_vm_timer,
1059 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1062 static struct qemu_alarm_timer alarm_timers[] = {
1063 #ifndef _WIN32
1064 #ifdef __linux__
1065 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1066 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1067 /* HPET - if available - is preferred */
1068 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1069 /* ...otherwise try RTC */
1070 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1071 #endif
1072 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1073 #else
1074 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1075 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1076 {"win32", 0, win32_start_timer,
1077 win32_stop_timer, NULL, &alarm_win32_data},
1078 #endif
1079 {NULL, }
1082 static void show_available_alarms(void)
1084 int i;
1086 printf("Available alarm timers, in order of precedence:\n");
1087 for (i = 0; alarm_timers[i].name; i++)
1088 printf("%s\n", alarm_timers[i].name);
1091 static void configure_alarms(char const *opt)
1093 int i;
1094 int cur = 0;
1095 int count = ARRAY_SIZE(alarm_timers) - 1;
1096 char *arg;
1097 char *name;
1098 struct qemu_alarm_timer tmp;
1100 if (!strcmp(opt, "?")) {
1101 show_available_alarms();
1102 exit(0);
1105 arg = strdup(opt);
1107 /* Reorder the array */
1108 name = strtok(arg, ",");
1109 while (name) {
1110 for (i = 0; i < count && alarm_timers[i].name; i++) {
1111 if (!strcmp(alarm_timers[i].name, name))
1112 break;
1115 if (i == count) {
1116 fprintf(stderr, "Unknown clock %s\n", name);
1117 goto next;
1120 if (i < cur)
1121 /* Ignore */
1122 goto next;
1124 /* Swap */
1125 tmp = alarm_timers[i];
1126 alarm_timers[i] = alarm_timers[cur];
1127 alarm_timers[cur] = tmp;
1129 cur++;
1130 next:
1131 name = strtok(NULL, ",");
1134 free(arg);
1136 if (cur) {
1137 /* Disable remaining timers */
1138 for (i = cur; i < count; i++)
1139 alarm_timers[i].name = NULL;
1140 } else {
1141 show_available_alarms();
1142 exit(1);
1146 QEMUClock *rt_clock;
1147 QEMUClock *vm_clock;
1149 static QEMUTimer *active_timers[2];
1151 static QEMUClock *qemu_new_clock(int type)
1153 QEMUClock *clock;
1154 clock = qemu_mallocz(sizeof(QEMUClock));
1155 clock->type = type;
1156 return clock;
1159 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1161 QEMUTimer *ts;
1163 ts = qemu_mallocz(sizeof(QEMUTimer));
1164 ts->clock = clock;
1165 ts->cb = cb;
1166 ts->opaque = opaque;
1167 return ts;
1170 void qemu_free_timer(QEMUTimer *ts)
1172 qemu_free(ts);
1175 /* stop a timer, but do not dealloc it */
1176 void qemu_del_timer(QEMUTimer *ts)
1178 QEMUTimer **pt, *t;
1180 /* NOTE: this code must be signal safe because
1181 qemu_timer_expired() can be called from a signal. */
1182 pt = &active_timers[ts->clock->type];
1183 for(;;) {
1184 t = *pt;
1185 if (!t)
1186 break;
1187 if (t == ts) {
1188 *pt = t->next;
1189 break;
1191 pt = &t->next;
1195 /* modify the current timer so that it will be fired when current_time
1196 >= expire_time. The corresponding callback will be called. */
1197 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1199 QEMUTimer **pt, *t;
1201 qemu_del_timer(ts);
1203 /* add the timer in the sorted list */
1204 /* NOTE: this code must be signal safe because
1205 qemu_timer_expired() can be called from a signal. */
1206 pt = &active_timers[ts->clock->type];
1207 for(;;) {
1208 t = *pt;
1209 if (!t)
1210 break;
1211 if (t->expire_time > expire_time)
1212 break;
1213 pt = &t->next;
1215 ts->expire_time = expire_time;
1216 ts->next = *pt;
1217 *pt = ts;
1219 /* Rearm if necessary */
1220 if (pt == &active_timers[ts->clock->type]) {
1221 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1222 qemu_rearm_alarm_timer(alarm_timer);
1224 /* Interrupt execution to force deadline recalculation. */
1225 if (use_icount)
1226 qemu_notify_event();
1230 int qemu_timer_pending(QEMUTimer *ts)
1232 QEMUTimer *t;
1233 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1234 if (t == ts)
1235 return 1;
1237 return 0;
1240 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1242 if (!timer_head)
1243 return 0;
1244 return (timer_head->expire_time <= current_time);
1247 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1249 QEMUTimer *ts;
1251 for(;;) {
1252 ts = *ptimer_head;
1253 if (!ts || ts->expire_time > current_time)
1254 break;
1255 /* remove timer from the list before calling the callback */
1256 *ptimer_head = ts->next;
1257 ts->next = NULL;
1259 /* run the callback (the timer list can be modified) */
1260 ts->cb(ts->opaque);
1264 int64_t qemu_get_clock(QEMUClock *clock)
1266 switch(clock->type) {
1267 case QEMU_TIMER_REALTIME:
1268 return get_clock() / 1000000;
1269 default:
1270 case QEMU_TIMER_VIRTUAL:
1271 if (use_icount) {
1272 return cpu_get_icount();
1273 } else {
1274 return cpu_get_clock();
1279 static void init_timers(void)
1281 init_get_clock();
1282 ticks_per_sec = QEMU_TIMER_BASE;
1283 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1284 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1287 /* save a timer */
1288 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1290 uint64_t expire_time;
1292 if (qemu_timer_pending(ts)) {
1293 expire_time = ts->expire_time;
1294 } else {
1295 expire_time = -1;
1297 qemu_put_be64(f, expire_time);
1300 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1302 uint64_t expire_time;
1304 expire_time = qemu_get_be64(f);
1305 if (expire_time != -1) {
1306 qemu_mod_timer(ts, expire_time);
1307 } else {
1308 qemu_del_timer(ts);
1312 static void timer_save(QEMUFile *f, void *opaque)
1314 if (cpu_ticks_enabled) {
1315 hw_error("cannot save state if virtual timers are running");
1317 qemu_put_be64(f, cpu_ticks_offset);
1318 qemu_put_be64(f, ticks_per_sec);
1319 qemu_put_be64(f, cpu_clock_offset);
1322 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1324 if (version_id != 1 && version_id != 2)
1325 return -EINVAL;
1326 if (cpu_ticks_enabled) {
1327 return -EINVAL;
1329 cpu_ticks_offset=qemu_get_be64(f);
1330 ticks_per_sec=qemu_get_be64(f);
1331 if (version_id == 2) {
1332 cpu_clock_offset=qemu_get_be64(f);
1334 return 0;
1337 static void qemu_event_increment(void);
1339 #ifdef _WIN32
1340 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1341 DWORD_PTR dwUser, DWORD_PTR dw1,
1342 DWORD_PTR dw2)
1343 #else
1344 static void host_alarm_handler(int host_signum)
1345 #endif
1347 #if 0
1348 #define DISP_FREQ 1000
1350 static int64_t delta_min = INT64_MAX;
1351 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1352 static int count;
1353 ti = qemu_get_clock(vm_clock);
1354 if (last_clock != 0) {
1355 delta = ti - last_clock;
1356 if (delta < delta_min)
1357 delta_min = delta;
1358 if (delta > delta_max)
1359 delta_max = delta;
1360 delta_cum += delta;
1361 if (++count == DISP_FREQ) {
1362 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1363 muldiv64(delta_min, 1000000, ticks_per_sec),
1364 muldiv64(delta_max, 1000000, ticks_per_sec),
1365 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1366 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1367 count = 0;
1368 delta_min = INT64_MAX;
1369 delta_max = 0;
1370 delta_cum = 0;
1373 last_clock = ti;
1375 #endif
1376 if (alarm_has_dynticks(alarm_timer) ||
1377 (!use_icount &&
1378 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1379 qemu_get_clock(vm_clock))) ||
1380 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1381 qemu_get_clock(rt_clock))) {
1382 qemu_event_increment();
1383 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1385 #ifndef CONFIG_IOTHREAD
1386 if (next_cpu) {
1387 /* stop the currently executing cpu because a timer occured */
1388 cpu_exit(next_cpu);
1389 #ifdef CONFIG_KQEMU
1390 if (next_cpu->kqemu_enabled) {
1391 kqemu_cpu_interrupt(next_cpu);
1393 #endif
1395 #endif
1396 timer_alarm_pending = 1;
1397 qemu_notify_event();
1401 static int64_t qemu_next_deadline(void)
1403 int64_t delta;
1405 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1406 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1407 qemu_get_clock(vm_clock);
1408 } else {
1409 /* To avoid problems with overflow limit this to 2^32. */
1410 delta = INT32_MAX;
1413 if (delta < 0)
1414 delta = 0;
1416 return delta;
1419 #if defined(__linux__) || defined(_WIN32)
1420 static uint64_t qemu_next_deadline_dyntick(void)
1422 int64_t delta;
1423 int64_t rtdelta;
1425 if (use_icount)
1426 delta = INT32_MAX;
1427 else
1428 delta = (qemu_next_deadline() + 999) / 1000;
1430 if (active_timers[QEMU_TIMER_REALTIME]) {
1431 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1432 qemu_get_clock(rt_clock))*1000;
1433 if (rtdelta < delta)
1434 delta = rtdelta;
1437 if (delta < MIN_TIMER_REARM_US)
1438 delta = MIN_TIMER_REARM_US;
1440 return delta;
1442 #endif
1444 #ifndef _WIN32
1446 /* Sets a specific flag */
1447 static int fcntl_setfl(int fd, int flag)
1449 int flags;
1451 flags = fcntl(fd, F_GETFL);
1452 if (flags == -1)
1453 return -errno;
1455 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1456 return -errno;
1458 return 0;
1461 #if defined(__linux__)
1463 #define RTC_FREQ 1024
1465 static void enable_sigio_timer(int fd)
1467 struct sigaction act;
1469 /* timer signal */
1470 sigfillset(&act.sa_mask);
1471 act.sa_flags = 0;
1472 act.sa_handler = host_alarm_handler;
1474 sigaction(SIGIO, &act, NULL);
1475 fcntl_setfl(fd, O_ASYNC);
1476 fcntl(fd, F_SETOWN, getpid());
1479 static int hpet_start_timer(struct qemu_alarm_timer *t)
1481 struct hpet_info info;
1482 int r, fd;
1484 fd = open("/dev/hpet", O_RDONLY);
1485 if (fd < 0)
1486 return -1;
1488 /* Set frequency */
1489 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1490 if (r < 0) {
1491 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1492 "error, but for better emulation accuracy type:\n"
1493 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1494 goto fail;
1497 /* Check capabilities */
1498 r = ioctl(fd, HPET_INFO, &info);
1499 if (r < 0)
1500 goto fail;
1502 /* Enable periodic mode */
1503 r = ioctl(fd, HPET_EPI, 0);
1504 if (info.hi_flags && (r < 0))
1505 goto fail;
1507 /* Enable interrupt */
1508 r = ioctl(fd, HPET_IE_ON, 0);
1509 if (r < 0)
1510 goto fail;
1512 enable_sigio_timer(fd);
1513 t->priv = (void *)(long)fd;
1515 return 0;
1516 fail:
1517 close(fd);
1518 return -1;
1521 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1523 int fd = (long)t->priv;
1525 close(fd);
1528 static int rtc_start_timer(struct qemu_alarm_timer *t)
1530 int rtc_fd;
1531 unsigned long current_rtc_freq = 0;
1533 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1534 if (rtc_fd < 0)
1535 return -1;
1536 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1537 if (current_rtc_freq != RTC_FREQ &&
1538 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1539 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1540 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1541 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1542 goto fail;
1544 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1545 fail:
1546 close(rtc_fd);
1547 return -1;
1550 enable_sigio_timer(rtc_fd);
1552 t->priv = (void *)(long)rtc_fd;
1554 return 0;
1557 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1559 int rtc_fd = (long)t->priv;
1561 close(rtc_fd);
1564 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1566 struct sigevent ev;
1567 timer_t host_timer;
1568 struct sigaction act;
1570 sigfillset(&act.sa_mask);
1571 act.sa_flags = 0;
1572 act.sa_handler = host_alarm_handler;
1574 sigaction(SIGALRM, &act, NULL);
1577 * Initialize ev struct to 0 to avoid valgrind complaining
1578 * about uninitialized data in timer_create call
1580 memset(&ev, 0, sizeof(ev));
1581 ev.sigev_value.sival_int = 0;
1582 ev.sigev_notify = SIGEV_SIGNAL;
1583 ev.sigev_signo = SIGALRM;
1585 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1586 perror("timer_create");
1588 /* disable dynticks */
1589 fprintf(stderr, "Dynamic Ticks disabled\n");
1591 return -1;
1594 t->priv = (void *)(long)host_timer;
1596 return 0;
1599 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1601 timer_t host_timer = (timer_t)(long)t->priv;
1603 timer_delete(host_timer);
1606 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1608 timer_t host_timer = (timer_t)(long)t->priv;
1609 struct itimerspec timeout;
1610 int64_t nearest_delta_us = INT64_MAX;
1611 int64_t current_us;
1613 if (!active_timers[QEMU_TIMER_REALTIME] &&
1614 !active_timers[QEMU_TIMER_VIRTUAL])
1615 return;
1617 nearest_delta_us = qemu_next_deadline_dyntick();
1619 /* check whether a timer is already running */
1620 if (timer_gettime(host_timer, &timeout)) {
1621 perror("gettime");
1622 fprintf(stderr, "Internal timer error: aborting\n");
1623 exit(1);
1625 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1626 if (current_us && current_us <= nearest_delta_us)
1627 return;
1629 timeout.it_interval.tv_sec = 0;
1630 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1631 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1632 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1633 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1634 perror("settime");
1635 fprintf(stderr, "Internal timer error: aborting\n");
1636 exit(1);
1640 #endif /* defined(__linux__) */
1642 static int unix_start_timer(struct qemu_alarm_timer *t)
1644 struct sigaction act;
1645 struct itimerval itv;
1646 int err;
1648 /* timer signal */
1649 sigfillset(&act.sa_mask);
1650 act.sa_flags = 0;
1651 act.sa_handler = host_alarm_handler;
1653 sigaction(SIGALRM, &act, NULL);
1655 itv.it_interval.tv_sec = 0;
1656 /* for i386 kernel 2.6 to get 1 ms */
1657 itv.it_interval.tv_usec = 999;
1658 itv.it_value.tv_sec = 0;
1659 itv.it_value.tv_usec = 10 * 1000;
1661 err = setitimer(ITIMER_REAL, &itv, NULL);
1662 if (err)
1663 return -1;
1665 return 0;
1668 static void unix_stop_timer(struct qemu_alarm_timer *t)
1670 struct itimerval itv;
1672 memset(&itv, 0, sizeof(itv));
1673 setitimer(ITIMER_REAL, &itv, NULL);
1676 #endif /* !defined(_WIN32) */
1679 #ifdef _WIN32
1681 static int win32_start_timer(struct qemu_alarm_timer *t)
1683 TIMECAPS tc;
1684 struct qemu_alarm_win32 *data = t->priv;
1685 UINT flags;
1687 memset(&tc, 0, sizeof(tc));
1688 timeGetDevCaps(&tc, sizeof(tc));
1690 if (data->period < tc.wPeriodMin)
1691 data->period = tc.wPeriodMin;
1693 timeBeginPeriod(data->period);
1695 flags = TIME_CALLBACK_FUNCTION;
1696 if (alarm_has_dynticks(t))
1697 flags |= TIME_ONESHOT;
1698 else
1699 flags |= TIME_PERIODIC;
1701 data->timerId = timeSetEvent(1, // interval (ms)
1702 data->period, // resolution
1703 host_alarm_handler, // function
1704 (DWORD)t, // parameter
1705 flags);
1707 if (!data->timerId) {
1708 perror("Failed to initialize win32 alarm timer");
1709 timeEndPeriod(data->period);
1710 return -1;
1713 return 0;
1716 static void win32_stop_timer(struct qemu_alarm_timer *t)
1718 struct qemu_alarm_win32 *data = t->priv;
1720 timeKillEvent(data->timerId);
1721 timeEndPeriod(data->period);
1724 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1726 struct qemu_alarm_win32 *data = t->priv;
1727 uint64_t nearest_delta_us;
1729 if (!active_timers[QEMU_TIMER_REALTIME] &&
1730 !active_timers[QEMU_TIMER_VIRTUAL])
1731 return;
1733 nearest_delta_us = qemu_next_deadline_dyntick();
1734 nearest_delta_us /= 1000;
1736 timeKillEvent(data->timerId);
1738 data->timerId = timeSetEvent(1,
1739 data->period,
1740 host_alarm_handler,
1741 (DWORD)t,
1742 TIME_ONESHOT | TIME_PERIODIC);
1744 if (!data->timerId) {
1745 perror("Failed to re-arm win32 alarm timer");
1747 timeEndPeriod(data->period);
1748 exit(1);
1752 #endif /* _WIN32 */
1754 static int init_timer_alarm(void)
1756 struct qemu_alarm_timer *t = NULL;
1757 int i, err = -1;
1759 for (i = 0; alarm_timers[i].name; i++) {
1760 t = &alarm_timers[i];
1762 err = t->start(t);
1763 if (!err)
1764 break;
1767 if (err) {
1768 err = -ENOENT;
1769 goto fail;
1772 alarm_timer = t;
1774 return 0;
1776 fail:
1777 return err;
1780 static void quit_timers(void)
1782 alarm_timer->stop(alarm_timer);
1783 alarm_timer = NULL;
1786 /***********************************************************/
1787 /* host time/date access */
1788 void qemu_get_timedate(struct tm *tm, int offset)
1790 time_t ti;
1791 struct tm *ret;
1793 time(&ti);
1794 ti += offset;
1795 if (rtc_date_offset == -1) {
1796 if (rtc_utc)
1797 ret = gmtime(&ti);
1798 else
1799 ret = localtime(&ti);
1800 } else {
1801 ti -= rtc_date_offset;
1802 ret = gmtime(&ti);
1805 memcpy(tm, ret, sizeof(struct tm));
1808 int qemu_timedate_diff(struct tm *tm)
1810 time_t seconds;
1812 if (rtc_date_offset == -1)
1813 if (rtc_utc)
1814 seconds = mktimegm(tm);
1815 else
1816 seconds = mktime(tm);
1817 else
1818 seconds = mktimegm(tm) + rtc_date_offset;
1820 return seconds - time(NULL);
1823 #ifdef _WIN32
1824 static void socket_cleanup(void)
1826 WSACleanup();
1829 static int socket_init(void)
1831 WSADATA Data;
1832 int ret, err;
1834 ret = WSAStartup(MAKEWORD(2,2), &Data);
1835 if (ret != 0) {
1836 err = WSAGetLastError();
1837 fprintf(stderr, "WSAStartup: %d\n", err);
1838 return -1;
1840 atexit(socket_cleanup);
1841 return 0;
1843 #endif
1845 int get_next_param_value(char *buf, int buf_size,
1846 const char *tag, const char **pstr)
1848 const char *p;
1849 char option[128];
1851 p = *pstr;
1852 for(;;) {
1853 p = get_opt_name(option, sizeof(option), p, '=');
1854 if (*p != '=')
1855 break;
1856 p++;
1857 if (!strcmp(tag, option)) {
1858 *pstr = get_opt_value(buf, buf_size, p);
1859 if (**pstr == ',') {
1860 (*pstr)++;
1862 return strlen(buf);
1863 } else {
1864 p = get_opt_value(NULL, 0, p);
1866 if (*p != ',')
1867 break;
1868 p++;
1870 return 0;
1873 int get_param_value(char *buf, int buf_size,
1874 const char *tag, const char *str)
1876 return get_next_param_value(buf, buf_size, tag, &str);
1879 int check_params(char *buf, int buf_size,
1880 const char * const *params, const char *str)
1882 const char *p;
1883 int i;
1885 p = str;
1886 while (*p != '\0') {
1887 p = get_opt_name(buf, buf_size, p, '=');
1888 if (*p != '=') {
1889 return -1;
1891 p++;
1892 for (i = 0; params[i] != NULL; i++) {
1893 if (!strcmp(params[i], buf)) {
1894 break;
1897 if (params[i] == NULL) {
1898 return -1;
1900 p = get_opt_value(NULL, 0, p);
1901 if (*p != ',') {
1902 break;
1904 p++;
1906 return 0;
1909 /***********************************************************/
1910 /* Bluetooth support */
1911 static int nb_hcis;
1912 static int cur_hci;
1913 static struct HCIInfo *hci_table[MAX_NICS];
1915 static struct bt_vlan_s {
1916 struct bt_scatternet_s net;
1917 int id;
1918 struct bt_vlan_s *next;
1919 } *first_bt_vlan;
1921 /* find or alloc a new bluetooth "VLAN" */
1922 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1924 struct bt_vlan_s **pvlan, *vlan;
1925 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1926 if (vlan->id == id)
1927 return &vlan->net;
1929 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1930 vlan->id = id;
1931 pvlan = &first_bt_vlan;
1932 while (*pvlan != NULL)
1933 pvlan = &(*pvlan)->next;
1934 *pvlan = vlan;
1935 return &vlan->net;
1938 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1942 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1944 return -ENOTSUP;
1947 static struct HCIInfo null_hci = {
1948 .cmd_send = null_hci_send,
1949 .sco_send = null_hci_send,
1950 .acl_send = null_hci_send,
1951 .bdaddr_set = null_hci_addr_set,
1954 struct HCIInfo *qemu_next_hci(void)
1956 if (cur_hci == nb_hcis)
1957 return &null_hci;
1959 return hci_table[cur_hci++];
1962 static struct HCIInfo *hci_init(const char *str)
1964 char *endp;
1965 struct bt_scatternet_s *vlan = 0;
1967 if (!strcmp(str, "null"))
1968 /* null */
1969 return &null_hci;
1970 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1971 /* host[:hciN] */
1972 return bt_host_hci(str[4] ? str + 5 : "hci0");
1973 else if (!strncmp(str, "hci", 3)) {
1974 /* hci[,vlan=n] */
1975 if (str[3]) {
1976 if (!strncmp(str + 3, ",vlan=", 6)) {
1977 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1978 if (*endp)
1979 vlan = 0;
1981 } else
1982 vlan = qemu_find_bt_vlan(0);
1983 if (vlan)
1984 return bt_new_hci(vlan);
1987 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1989 return 0;
1992 static int bt_hci_parse(const char *str)
1994 struct HCIInfo *hci;
1995 bdaddr_t bdaddr;
1997 if (nb_hcis >= MAX_NICS) {
1998 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1999 return -1;
2002 hci = hci_init(str);
2003 if (!hci)
2004 return -1;
2006 bdaddr.b[0] = 0x52;
2007 bdaddr.b[1] = 0x54;
2008 bdaddr.b[2] = 0x00;
2009 bdaddr.b[3] = 0x12;
2010 bdaddr.b[4] = 0x34;
2011 bdaddr.b[5] = 0x56 + nb_hcis;
2012 hci->bdaddr_set(hci, bdaddr.b);
2014 hci_table[nb_hcis++] = hci;
2016 return 0;
2019 static void bt_vhci_add(int vlan_id)
2021 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2023 if (!vlan->slave)
2024 fprintf(stderr, "qemu: warning: adding a VHCI to "
2025 "an empty scatternet %i\n", vlan_id);
2027 bt_vhci_init(bt_new_hci(vlan));
2030 static struct bt_device_s *bt_device_add(const char *opt)
2032 struct bt_scatternet_s *vlan;
2033 int vlan_id = 0;
2034 char *endp = strstr(opt, ",vlan=");
2035 int len = (endp ? endp - opt : strlen(opt)) + 1;
2036 char devname[10];
2038 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2040 if (endp) {
2041 vlan_id = strtol(endp + 6, &endp, 0);
2042 if (*endp) {
2043 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2044 return 0;
2048 vlan = qemu_find_bt_vlan(vlan_id);
2050 if (!vlan->slave)
2051 fprintf(stderr, "qemu: warning: adding a slave device to "
2052 "an empty scatternet %i\n", vlan_id);
2054 if (!strcmp(devname, "keyboard"))
2055 return bt_keyboard_init(vlan);
2057 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2058 return 0;
2061 static int bt_parse(const char *opt)
2063 const char *endp, *p;
2064 int vlan;
2066 if (strstart(opt, "hci", &endp)) {
2067 if (!*endp || *endp == ',') {
2068 if (*endp)
2069 if (!strstart(endp, ",vlan=", 0))
2070 opt = endp + 1;
2072 return bt_hci_parse(opt);
2074 } else if (strstart(opt, "vhci", &endp)) {
2075 if (!*endp || *endp == ',') {
2076 if (*endp) {
2077 if (strstart(endp, ",vlan=", &p)) {
2078 vlan = strtol(p, (char **) &endp, 0);
2079 if (*endp) {
2080 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2081 return 1;
2083 } else {
2084 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2085 return 1;
2087 } else
2088 vlan = 0;
2090 bt_vhci_add(vlan);
2091 return 0;
2093 } else if (strstart(opt, "device:", &endp))
2094 return !bt_device_add(endp);
2096 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2097 return 1;
2100 /***********************************************************/
2101 /* QEMU Block devices */
2103 #define HD_ALIAS "index=%d,media=disk"
2104 #define CDROM_ALIAS "index=2,media=cdrom"
2105 #define FD_ALIAS "index=%d,if=floppy"
2106 #define PFLASH_ALIAS "if=pflash"
2107 #define MTD_ALIAS "if=mtd"
2108 #define SD_ALIAS "index=0,if=sd"
2110 static int drive_opt_get_free_idx(void)
2112 int index;
2114 for (index = 0; index < MAX_DRIVES; index++)
2115 if (!drives_opt[index].used) {
2116 drives_opt[index].used = 1;
2117 return index;
2120 return -1;
2123 static int drive_get_free_idx(void)
2125 int index;
2127 for (index = 0; index < MAX_DRIVES; index++)
2128 if (!drives_table[index].used) {
2129 drives_table[index].used = 1;
2130 return index;
2133 return -1;
2136 int drive_add(const char *file, const char *fmt, ...)
2138 va_list ap;
2139 int index = drive_opt_get_free_idx();
2141 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2142 fprintf(stderr, "qemu: too many drives\n");
2143 return -1;
2146 drives_opt[index].file = file;
2147 va_start(ap, fmt);
2148 vsnprintf(drives_opt[index].opt,
2149 sizeof(drives_opt[0].opt), fmt, ap);
2150 va_end(ap);
2152 nb_drives_opt++;
2153 return index;
2156 void drive_remove(int index)
2158 drives_opt[index].used = 0;
2159 nb_drives_opt--;
2162 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2164 int index;
2166 /* seek interface, bus and unit */
2168 for (index = 0; index < MAX_DRIVES; index++)
2169 if (drives_table[index].type == type &&
2170 drives_table[index].bus == bus &&
2171 drives_table[index].unit == unit &&
2172 drives_table[index].used)
2173 return index;
2175 return -1;
2178 int drive_get_max_bus(BlockInterfaceType type)
2180 int max_bus;
2181 int index;
2183 max_bus = -1;
2184 for (index = 0; index < nb_drives; index++) {
2185 if(drives_table[index].type == type &&
2186 drives_table[index].bus > max_bus)
2187 max_bus = drives_table[index].bus;
2189 return max_bus;
2192 const char *drive_get_serial(BlockDriverState *bdrv)
2194 int index;
2196 for (index = 0; index < nb_drives; index++)
2197 if (drives_table[index].bdrv == bdrv)
2198 return drives_table[index].serial;
2200 return "\0";
2203 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2205 int index;
2207 for (index = 0; index < nb_drives; index++)
2208 if (drives_table[index].bdrv == bdrv)
2209 return drives_table[index].onerror;
2211 return BLOCK_ERR_STOP_ENOSPC;
2214 static void bdrv_format_print(void *opaque, const char *name)
2216 fprintf(stderr, " %s", name);
2219 void drive_uninit(BlockDriverState *bdrv)
2221 int i;
2223 for (i = 0; i < MAX_DRIVES; i++)
2224 if (drives_table[i].bdrv == bdrv) {
2225 drives_table[i].bdrv = NULL;
2226 drives_table[i].used = 0;
2227 drive_remove(drives_table[i].drive_opt_idx);
2228 nb_drives--;
2229 break;
2233 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2235 char buf[128];
2236 char file[1024];
2237 char devname[128];
2238 char serial[21];
2239 const char *mediastr = "";
2240 BlockInterfaceType type;
2241 enum { MEDIA_DISK, MEDIA_CDROM } media;
2242 int bus_id, unit_id;
2243 int cyls, heads, secs, translation;
2244 BlockDriverState *bdrv;
2245 BlockDriver *drv = NULL;
2246 QEMUMachine *machine = opaque;
2247 int max_devs;
2248 int index;
2249 int cache;
2250 int bdrv_flags, onerror;
2251 const char *devaddr;
2252 int drives_table_idx;
2253 char *str = arg->opt;
2254 static const char * const params[] = { "bus", "unit", "if", "index",
2255 "cyls", "heads", "secs", "trans",
2256 "media", "snapshot", "file",
2257 "cache", "format", "serial",
2258 "werror", "addr",
2259 "boot",
2260 NULL };
2262 if (check_params(buf, sizeof(buf), params, str) < 0) {
2263 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2264 buf, str);
2265 return -1;
2268 file[0] = 0;
2269 cyls = heads = secs = 0;
2270 bus_id = 0;
2271 unit_id = -1;
2272 translation = BIOS_ATA_TRANSLATION_AUTO;
2273 index = -1;
2274 cache = 3;
2276 if (machine->use_scsi) {
2277 type = IF_SCSI;
2278 max_devs = MAX_SCSI_DEVS;
2279 pstrcpy(devname, sizeof(devname), "scsi");
2280 } else {
2281 type = IF_IDE;
2282 max_devs = MAX_IDE_DEVS;
2283 pstrcpy(devname, sizeof(devname), "ide");
2285 media = MEDIA_DISK;
2287 /* extract parameters */
2289 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2290 bus_id = strtol(buf, NULL, 0);
2291 if (bus_id < 0) {
2292 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2293 return -1;
2297 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2298 unit_id = strtol(buf, NULL, 0);
2299 if (unit_id < 0) {
2300 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2301 return -1;
2305 if (get_param_value(buf, sizeof(buf), "if", str)) {
2306 pstrcpy(devname, sizeof(devname), buf);
2307 if (!strcmp(buf, "ide")) {
2308 type = IF_IDE;
2309 max_devs = MAX_IDE_DEVS;
2310 } else if (!strcmp(buf, "scsi")) {
2311 type = IF_SCSI;
2312 max_devs = MAX_SCSI_DEVS;
2313 } else if (!strcmp(buf, "floppy")) {
2314 type = IF_FLOPPY;
2315 max_devs = 0;
2316 } else if (!strcmp(buf, "pflash")) {
2317 type = IF_PFLASH;
2318 max_devs = 0;
2319 } else if (!strcmp(buf, "mtd")) {
2320 type = IF_MTD;
2321 max_devs = 0;
2322 } else if (!strcmp(buf, "sd")) {
2323 type = IF_SD;
2324 max_devs = 0;
2325 } else if (!strcmp(buf, "virtio")) {
2326 type = IF_VIRTIO;
2327 max_devs = 0;
2328 } else if (!strcmp(buf, "xen")) {
2329 type = IF_XEN;
2330 max_devs = 0;
2331 } else {
2332 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2333 return -1;
2337 if (get_param_value(buf, sizeof(buf), "index", str)) {
2338 index = strtol(buf, NULL, 0);
2339 if (index < 0) {
2340 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2341 return -1;
2345 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2346 cyls = strtol(buf, NULL, 0);
2349 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2350 heads = strtol(buf, NULL, 0);
2353 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2354 secs = strtol(buf, NULL, 0);
2357 if (cyls || heads || secs) {
2358 if (cyls < 1 || cyls > 16383) {
2359 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2360 return -1;
2362 if (heads < 1 || heads > 16) {
2363 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2364 return -1;
2366 if (secs < 1 || secs > 63) {
2367 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2368 return -1;
2372 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2373 if (!cyls) {
2374 fprintf(stderr,
2375 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2376 str);
2377 return -1;
2379 if (!strcmp(buf, "none"))
2380 translation = BIOS_ATA_TRANSLATION_NONE;
2381 else if (!strcmp(buf, "lba"))
2382 translation = BIOS_ATA_TRANSLATION_LBA;
2383 else if (!strcmp(buf, "auto"))
2384 translation = BIOS_ATA_TRANSLATION_AUTO;
2385 else {
2386 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2387 return -1;
2391 if (get_param_value(buf, sizeof(buf), "media", str)) {
2392 if (!strcmp(buf, "disk")) {
2393 media = MEDIA_DISK;
2394 } else if (!strcmp(buf, "cdrom")) {
2395 if (cyls || secs || heads) {
2396 fprintf(stderr,
2397 "qemu: '%s' invalid physical CHS format\n", str);
2398 return -1;
2400 media = MEDIA_CDROM;
2401 } else {
2402 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2403 return -1;
2407 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2408 if (!strcmp(buf, "on"))
2409 snapshot = 1;
2410 else if (!strcmp(buf, "off"))
2411 snapshot = 0;
2412 else {
2413 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2414 return -1;
2418 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2419 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2420 cache = 0;
2421 else if (!strcmp(buf, "writethrough"))
2422 cache = 1;
2423 else if (!strcmp(buf, "writeback"))
2424 cache = 2;
2425 else {
2426 fprintf(stderr, "qemu: invalid cache option\n");
2427 return -1;
2431 if (get_param_value(buf, sizeof(buf), "format", str)) {
2432 if (strcmp(buf, "?") == 0) {
2433 fprintf(stderr, "qemu: Supported formats:");
2434 bdrv_iterate_format(bdrv_format_print, NULL);
2435 fprintf(stderr, "\n");
2436 return -1;
2438 drv = bdrv_find_format(buf);
2439 if (!drv) {
2440 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2441 return -1;
2445 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2446 if (!strcmp(buf, "on")) {
2447 if (extboot_drive != -1) {
2448 fprintf(stderr, "qemu: two bootable drives specified\n");
2449 return -1;
2451 extboot_drive = nb_drives;
2452 } else if (strcmp(buf, "off")) {
2453 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2454 return -1;
2458 if (arg->file == NULL)
2459 get_param_value(file, sizeof(file), "file", str);
2460 else
2461 pstrcpy(file, sizeof(file), arg->file);
2463 if (!get_param_value(serial, sizeof(serial), "serial", str))
2464 memset(serial, 0, sizeof(serial));
2466 onerror = BLOCK_ERR_STOP_ENOSPC;
2467 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2468 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2469 fprintf(stderr, "werror is no supported by this format\n");
2470 return -1;
2472 if (!strcmp(buf, "ignore"))
2473 onerror = BLOCK_ERR_IGNORE;
2474 else if (!strcmp(buf, "enospc"))
2475 onerror = BLOCK_ERR_STOP_ENOSPC;
2476 else if (!strcmp(buf, "stop"))
2477 onerror = BLOCK_ERR_STOP_ANY;
2478 else if (!strcmp(buf, "report"))
2479 onerror = BLOCK_ERR_REPORT;
2480 else {
2481 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2482 return -1;
2486 devaddr = NULL;
2487 if (get_param_value(buf, sizeof(buf), "addr", str)) {
2488 if (type != IF_VIRTIO) {
2489 fprintf(stderr, "addr is not supported by in '%s'\n", str);
2490 return -1;
2492 devaddr = strdup(buf);
2495 /* compute bus and unit according index */
2497 if (index != -1) {
2498 if (bus_id != 0 || unit_id != -1) {
2499 fprintf(stderr,
2500 "qemu: '%s' index cannot be used with bus and unit\n", str);
2501 return -1;
2503 if (max_devs == 0)
2505 unit_id = index;
2506 bus_id = 0;
2507 } else {
2508 unit_id = index % max_devs;
2509 bus_id = index / max_devs;
2513 /* if user doesn't specify a unit_id,
2514 * try to find the first free
2517 if (unit_id == -1) {
2518 unit_id = 0;
2519 while (drive_get_index(type, bus_id, unit_id) != -1) {
2520 unit_id++;
2521 if (max_devs && unit_id >= max_devs) {
2522 unit_id -= max_devs;
2523 bus_id++;
2528 /* check unit id */
2530 if (max_devs && unit_id >= max_devs) {
2531 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2532 str, unit_id, max_devs - 1);
2533 return -1;
2537 * ignore multiple definitions
2540 if (drive_get_index(type, bus_id, unit_id) != -1)
2541 return -2;
2543 /* init */
2545 if (type == IF_IDE || type == IF_SCSI)
2546 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2547 if (max_devs)
2548 snprintf(buf, sizeof(buf), "%s%i%s%i",
2549 devname, bus_id, mediastr, unit_id);
2550 else
2551 snprintf(buf, sizeof(buf), "%s%s%i",
2552 devname, mediastr, unit_id);
2553 bdrv = bdrv_new(buf);
2554 drives_table_idx = drive_get_free_idx();
2555 drives_table[drives_table_idx].bdrv = bdrv;
2556 drives_table[drives_table_idx].devaddr = devaddr;
2557 drives_table[drives_table_idx].type = type;
2558 drives_table[drives_table_idx].bus = bus_id;
2559 drives_table[drives_table_idx].unit = unit_id;
2560 drives_table[drives_table_idx].onerror = onerror;
2561 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2562 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2563 nb_drives++;
2565 switch(type) {
2566 case IF_IDE:
2567 case IF_SCSI:
2568 case IF_XEN:
2569 switch(media) {
2570 case MEDIA_DISK:
2571 if (cyls != 0) {
2572 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2573 bdrv_set_translation_hint(bdrv, translation);
2575 break;
2576 case MEDIA_CDROM:
2577 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2578 break;
2580 break;
2581 case IF_SD:
2582 /* FIXME: This isn't really a floppy, but it's a reasonable
2583 approximation. */
2584 case IF_FLOPPY:
2585 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2586 break;
2587 case IF_PFLASH:
2588 case IF_MTD:
2589 case IF_VIRTIO:
2590 break;
2591 case IF_COUNT:
2592 abort();
2594 if (!file[0])
2595 return -2;
2596 bdrv_flags = 0;
2597 if (snapshot) {
2598 bdrv_flags |= BDRV_O_SNAPSHOT;
2599 cache = 2; /* always use write-back with snapshot */
2601 if (cache == 0) /* no caching */
2602 bdrv_flags |= BDRV_O_NOCACHE;
2603 else if (cache == 2) /* write-back */
2604 bdrv_flags |= BDRV_O_CACHE_WB;
2605 else if (cache == 3) /* not specified */
2606 bdrv_flags |= BDRV_O_CACHE_DEF;
2607 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2608 fprintf(stderr, "qemu: could not open disk image %s\n",
2609 file);
2610 return -1;
2612 if (bdrv_key_required(bdrv))
2613 autostart = 0;
2614 return drives_table_idx;
2617 static void numa_add(const char *optarg)
2619 char option[128];
2620 char *endptr;
2621 unsigned long long value, endvalue;
2622 int nodenr;
2624 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2625 if (!strcmp(option, "node")) {
2626 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2627 nodenr = nb_numa_nodes;
2628 } else {
2629 nodenr = strtoull(option, NULL, 10);
2632 if (get_param_value(option, 128, "mem", optarg) == 0) {
2633 node_mem[nodenr] = 0;
2634 } else {
2635 value = strtoull(option, &endptr, 0);
2636 switch (*endptr) {
2637 case 0: case 'M': case 'm':
2638 value <<= 20;
2639 break;
2640 case 'G': case 'g':
2641 value <<= 30;
2642 break;
2644 node_mem[nodenr] = value;
2646 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2647 node_cpumask[nodenr] = 0;
2648 } else {
2649 value = strtoull(option, &endptr, 10);
2650 if (value >= 64) {
2651 value = 63;
2652 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2653 } else {
2654 if (*endptr == '-') {
2655 endvalue = strtoull(endptr+1, &endptr, 10);
2656 if (endvalue >= 63) {
2657 endvalue = 62;
2658 fprintf(stderr,
2659 "only 63 CPUs in NUMA mode supported.\n");
2661 value = (1 << (endvalue + 1)) - (1 << value);
2662 } else {
2663 value = 1 << value;
2666 node_cpumask[nodenr] = value;
2668 nb_numa_nodes++;
2670 return;
2673 /***********************************************************/
2674 /* USB devices */
2676 static USBPort *used_usb_ports;
2677 static USBPort *free_usb_ports;
2679 /* ??? Maybe change this to register a hub to keep track of the topology. */
2680 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2681 usb_attachfn attach)
2683 port->opaque = opaque;
2684 port->index = index;
2685 port->attach = attach;
2686 port->next = free_usb_ports;
2687 free_usb_ports = port;
2690 int usb_device_add_dev(USBDevice *dev)
2692 USBPort *port;
2694 /* Find a USB port to add the device to. */
2695 port = free_usb_ports;
2696 if (!port->next) {
2697 USBDevice *hub;
2699 /* Create a new hub and chain it on. */
2700 free_usb_ports = NULL;
2701 port->next = used_usb_ports;
2702 used_usb_ports = port;
2704 hub = usb_hub_init(VM_USB_HUB_SIZE);
2705 usb_attach(port, hub);
2706 port = free_usb_ports;
2709 free_usb_ports = port->next;
2710 port->next = used_usb_ports;
2711 used_usb_ports = port;
2712 usb_attach(port, dev);
2713 return 0;
2716 static void usb_msd_password_cb(void *opaque, int err)
2718 USBDevice *dev = opaque;
2720 if (!err)
2721 usb_device_add_dev(dev);
2722 else
2723 dev->handle_destroy(dev);
2726 static int usb_device_add(const char *devname, int is_hotplug)
2728 const char *p;
2729 USBDevice *dev;
2731 if (!free_usb_ports)
2732 return -1;
2734 if (strstart(devname, "host:", &p)) {
2735 dev = usb_host_device_open(p);
2736 } else if (!strcmp(devname, "mouse")) {
2737 dev = usb_mouse_init();
2738 } else if (!strcmp(devname, "tablet")) {
2739 dev = usb_tablet_init();
2740 } else if (!strcmp(devname, "keyboard")) {
2741 dev = usb_keyboard_init();
2742 } else if (strstart(devname, "disk:", &p)) {
2743 BlockDriverState *bs;
2745 dev = usb_msd_init(p);
2746 if (!dev)
2747 return -1;
2748 bs = usb_msd_get_bdrv(dev);
2749 if (bdrv_key_required(bs)) {
2750 autostart = 0;
2751 if (is_hotplug) {
2752 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2753 dev);
2754 return 0;
2757 } else if (!strcmp(devname, "wacom-tablet")) {
2758 dev = usb_wacom_init();
2759 } else if (strstart(devname, "serial:", &p)) {
2760 dev = usb_serial_init(p);
2761 #ifdef CONFIG_BRLAPI
2762 } else if (!strcmp(devname, "braille")) {
2763 dev = usb_baum_init();
2764 #endif
2765 } else if (strstart(devname, "net:", &p)) {
2766 int nic = nb_nics;
2768 if (net_client_init(NULL, "nic", p) < 0)
2769 return -1;
2770 nd_table[nic].model = "usb";
2771 dev = usb_net_init(&nd_table[nic]);
2772 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2773 dev = usb_bt_init(devname[2] ? hci_init(p) :
2774 bt_new_hci(qemu_find_bt_vlan(0)));
2775 } else {
2776 return -1;
2778 if (!dev)
2779 return -1;
2781 return usb_device_add_dev(dev);
2784 int usb_device_del_addr(int bus_num, int addr)
2786 USBPort *port;
2787 USBPort **lastp;
2788 USBDevice *dev;
2790 if (!used_usb_ports)
2791 return -1;
2793 if (bus_num != 0)
2794 return -1;
2796 lastp = &used_usb_ports;
2797 port = used_usb_ports;
2798 while (port && port->dev->addr != addr) {
2799 lastp = &port->next;
2800 port = port->next;
2803 if (!port)
2804 return -1;
2806 dev = port->dev;
2807 *lastp = port->next;
2808 usb_attach(port, NULL);
2809 dev->handle_destroy(dev);
2810 port->next = free_usb_ports;
2811 free_usb_ports = port;
2812 return 0;
2815 static int usb_device_del(const char *devname)
2817 int bus_num, addr;
2818 const char *p;
2820 if (strstart(devname, "host:", &p))
2821 return usb_host_device_close(p);
2823 if (!used_usb_ports)
2824 return -1;
2826 p = strchr(devname, '.');
2827 if (!p)
2828 return -1;
2829 bus_num = strtoul(devname, NULL, 0);
2830 addr = strtoul(p + 1, NULL, 0);
2832 return usb_device_del_addr(bus_num, addr);
2835 void do_usb_add(Monitor *mon, const char *devname)
2837 usb_device_add(devname, 1);
2840 void do_usb_del(Monitor *mon, const char *devname)
2842 usb_device_del(devname);
2845 void usb_info(Monitor *mon)
2847 USBDevice *dev;
2848 USBPort *port;
2849 const char *speed_str;
2851 if (!usb_enabled) {
2852 monitor_printf(mon, "USB support not enabled\n");
2853 return;
2856 for (port = used_usb_ports; port; port = port->next) {
2857 dev = port->dev;
2858 if (!dev)
2859 continue;
2860 switch(dev->speed) {
2861 case USB_SPEED_LOW:
2862 speed_str = "1.5";
2863 break;
2864 case USB_SPEED_FULL:
2865 speed_str = "12";
2866 break;
2867 case USB_SPEED_HIGH:
2868 speed_str = "480";
2869 break;
2870 default:
2871 speed_str = "?";
2872 break;
2874 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2875 0, dev->addr, speed_str, dev->devname);
2879 /***********************************************************/
2880 /* PCMCIA/Cardbus */
2882 static struct pcmcia_socket_entry_s {
2883 PCMCIASocket *socket;
2884 struct pcmcia_socket_entry_s *next;
2885 } *pcmcia_sockets = 0;
2887 void pcmcia_socket_register(PCMCIASocket *socket)
2889 struct pcmcia_socket_entry_s *entry;
2891 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2892 entry->socket = socket;
2893 entry->next = pcmcia_sockets;
2894 pcmcia_sockets = entry;
2897 void pcmcia_socket_unregister(PCMCIASocket *socket)
2899 struct pcmcia_socket_entry_s *entry, **ptr;
2901 ptr = &pcmcia_sockets;
2902 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2903 if (entry->socket == socket) {
2904 *ptr = entry->next;
2905 qemu_free(entry);
2909 void pcmcia_info(Monitor *mon)
2911 struct pcmcia_socket_entry_s *iter;
2913 if (!pcmcia_sockets)
2914 monitor_printf(mon, "No PCMCIA sockets\n");
2916 for (iter = pcmcia_sockets; iter; iter = iter->next)
2917 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2918 iter->socket->attached ? iter->socket->card_string :
2919 "Empty");
2922 /***********************************************************/
2923 /* register display */
2925 struct DisplayAllocator default_allocator = {
2926 defaultallocator_create_displaysurface,
2927 defaultallocator_resize_displaysurface,
2928 defaultallocator_free_displaysurface
2931 void register_displaystate(DisplayState *ds)
2933 DisplayState **s;
2934 s = &display_state;
2935 while (*s != NULL)
2936 s = &(*s)->next;
2937 ds->next = NULL;
2938 *s = ds;
2941 DisplayState *get_displaystate(void)
2943 return display_state;
2946 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2948 if(ds->allocator == &default_allocator) ds->allocator = da;
2949 return ds->allocator;
2952 /* dumb display */
2954 static void dumb_display_init(void)
2956 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2957 ds->allocator = &default_allocator;
2958 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2959 register_displaystate(ds);
2962 /***********************************************************/
2963 /* I/O handling */
2965 typedef struct IOHandlerRecord {
2966 int fd;
2967 IOCanRWHandler *fd_read_poll;
2968 IOHandler *fd_read;
2969 IOHandler *fd_write;
2970 int deleted;
2971 void *opaque;
2972 /* temporary data */
2973 struct pollfd *ufd;
2974 struct IOHandlerRecord *next;
2975 } IOHandlerRecord;
2977 static IOHandlerRecord *first_io_handler;
2979 /* XXX: fd_read_poll should be suppressed, but an API change is
2980 necessary in the character devices to suppress fd_can_read(). */
2981 int qemu_set_fd_handler2(int fd,
2982 IOCanRWHandler *fd_read_poll,
2983 IOHandler *fd_read,
2984 IOHandler *fd_write,
2985 void *opaque)
2987 IOHandlerRecord **pioh, *ioh;
2989 if (!fd_read && !fd_write) {
2990 pioh = &first_io_handler;
2991 for(;;) {
2992 ioh = *pioh;
2993 if (ioh == NULL)
2994 break;
2995 if (ioh->fd == fd) {
2996 ioh->deleted = 1;
2997 break;
2999 pioh = &ioh->next;
3001 } else {
3002 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3003 if (ioh->fd == fd)
3004 goto found;
3006 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3007 ioh->next = first_io_handler;
3008 first_io_handler = ioh;
3009 found:
3010 ioh->fd = fd;
3011 ioh->fd_read_poll = fd_read_poll;
3012 ioh->fd_read = fd_read;
3013 ioh->fd_write = fd_write;
3014 ioh->opaque = opaque;
3015 ioh->deleted = 0;
3017 qemu_notify_event();
3018 return 0;
3021 int qemu_set_fd_handler(int fd,
3022 IOHandler *fd_read,
3023 IOHandler *fd_write,
3024 void *opaque)
3026 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3029 #ifdef _WIN32
3030 /***********************************************************/
3031 /* Polling handling */
3033 typedef struct PollingEntry {
3034 PollingFunc *func;
3035 void *opaque;
3036 struct PollingEntry *next;
3037 } PollingEntry;
3039 static PollingEntry *first_polling_entry;
3041 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3043 PollingEntry **ppe, *pe;
3044 pe = qemu_mallocz(sizeof(PollingEntry));
3045 pe->func = func;
3046 pe->opaque = opaque;
3047 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3048 *ppe = pe;
3049 return 0;
3052 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3054 PollingEntry **ppe, *pe;
3055 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3056 pe = *ppe;
3057 if (pe->func == func && pe->opaque == opaque) {
3058 *ppe = pe->next;
3059 qemu_free(pe);
3060 break;
3065 /***********************************************************/
3066 /* Wait objects support */
3067 typedef struct WaitObjects {
3068 int num;
3069 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3070 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3071 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3072 } WaitObjects;
3074 static WaitObjects wait_objects = {0};
3076 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3078 WaitObjects *w = &wait_objects;
3080 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3081 return -1;
3082 w->events[w->num] = handle;
3083 w->func[w->num] = func;
3084 w->opaque[w->num] = opaque;
3085 w->num++;
3086 return 0;
3089 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3091 int i, found;
3092 WaitObjects *w = &wait_objects;
3094 found = 0;
3095 for (i = 0; i < w->num; i++) {
3096 if (w->events[i] == handle)
3097 found = 1;
3098 if (found) {
3099 w->events[i] = w->events[i + 1];
3100 w->func[i] = w->func[i + 1];
3101 w->opaque[i] = w->opaque[i + 1];
3104 if (found)
3105 w->num--;
3107 #endif
3109 /***********************************************************/
3110 /* ram save/restore */
3112 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3114 int v;
3116 v = qemu_get_byte(f);
3117 switch(v) {
3118 case 0:
3119 if (qemu_get_buffer(f, buf, len) != len)
3120 return -EIO;
3121 break;
3122 case 1:
3123 v = qemu_get_byte(f);
3124 memset(buf, v, len);
3125 break;
3126 default:
3127 return -EINVAL;
3130 if (qemu_file_has_error(f))
3131 return -EIO;
3133 return 0;
3136 static int ram_load_v1(QEMUFile *f, void *opaque)
3138 int ret;
3139 ram_addr_t i;
3141 if (qemu_get_be32(f) != last_ram_offset)
3142 return -EINVAL;
3143 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
3144 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3145 continue;
3146 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
3147 if (ret)
3148 return ret;
3150 return 0;
3153 #define BDRV_HASH_BLOCK_SIZE 1024
3154 #define IOBUF_SIZE 4096
3155 #define RAM_CBLOCK_MAGIC 0xfabe
3157 typedef struct RamDecompressState {
3158 z_stream zstream;
3159 QEMUFile *f;
3160 uint8_t buf[IOBUF_SIZE];
3161 } RamDecompressState;
3163 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3165 int ret;
3166 memset(s, 0, sizeof(*s));
3167 s->f = f;
3168 ret = inflateInit(&s->zstream);
3169 if (ret != Z_OK)
3170 return -1;
3171 return 0;
3174 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3176 int ret, clen;
3178 s->zstream.avail_out = len;
3179 s->zstream.next_out = buf;
3180 while (s->zstream.avail_out > 0) {
3181 if (s->zstream.avail_in == 0) {
3182 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3183 return -1;
3184 clen = qemu_get_be16(s->f);
3185 if (clen > IOBUF_SIZE)
3186 return -1;
3187 qemu_get_buffer(s->f, s->buf, clen);
3188 s->zstream.avail_in = clen;
3189 s->zstream.next_in = s->buf;
3191 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3192 if (ret != Z_OK && ret != Z_STREAM_END) {
3193 return -1;
3196 return 0;
3199 static void ram_decompress_close(RamDecompressState *s)
3201 inflateEnd(&s->zstream);
3204 #define RAM_SAVE_FLAG_FULL 0x01
3205 #define RAM_SAVE_FLAG_COMPRESS 0x02
3206 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3207 #define RAM_SAVE_FLAG_PAGE 0x08
3208 #define RAM_SAVE_FLAG_EOS 0x10
3210 static int is_dup_page(uint8_t *page, uint8_t ch)
3212 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3213 uint32_t *array = (uint32_t *)page;
3214 int i;
3216 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3217 if (array[i] != val)
3218 return 0;
3221 return 1;
3224 static int ram_save_block(QEMUFile *f)
3226 static ram_addr_t current_addr = 0;
3227 ram_addr_t saved_addr = current_addr;
3228 ram_addr_t addr = 0;
3229 int found = 0;
3231 while (addr < last_ram_offset) {
3232 if (kvm_enabled() && current_addr == 0) {
3233 int r;
3234 r = kvm_update_dirty_pages_log();
3235 if (r) {
3236 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3237 qemu_file_set_error(f);
3238 return 0;
3241 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3242 uint8_t *p;
3244 cpu_physical_memory_reset_dirty(current_addr,
3245 current_addr + TARGET_PAGE_SIZE,
3246 MIGRATION_DIRTY_FLAG);
3248 p = qemu_get_ram_ptr(current_addr);
3250 if (is_dup_page(p, *p)) {
3251 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3252 qemu_put_byte(f, *p);
3253 } else {
3254 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3255 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3258 found = 1;
3259 break;
3261 addr += TARGET_PAGE_SIZE;
3262 current_addr = (saved_addr + addr) % last_ram_offset;
3265 return found;
3268 static uint64_t bytes_transferred = 0;
3270 static ram_addr_t ram_save_remaining(void)
3272 ram_addr_t addr;
3273 ram_addr_t count = 0;
3275 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3276 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3277 count++;
3280 return count;
3283 uint64_t ram_bytes_remaining(void)
3285 return ram_save_remaining() * TARGET_PAGE_SIZE;
3288 uint64_t ram_bytes_transferred(void)
3290 return bytes_transferred;
3293 uint64_t ram_bytes_total(void)
3295 return last_ram_offset;
3298 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3300 ram_addr_t addr;
3301 uint64_t bytes_transferred_last;
3302 double bwidth = 0;
3303 uint64_t expected_time = 0;
3305 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3306 qemu_file_set_error(f);
3307 return 0;
3310 if (stage == 1) {
3311 /* Make sure all dirty bits are set */
3312 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3313 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3314 cpu_physical_memory_set_dirty(addr);
3317 /* Enable dirty memory tracking */
3318 cpu_physical_memory_set_dirty_tracking(1);
3320 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3323 bytes_transferred_last = bytes_transferred;
3324 bwidth = get_clock();
3326 while (!qemu_file_rate_limit(f)) {
3327 int ret;
3329 ret = ram_save_block(f);
3330 bytes_transferred += ret * TARGET_PAGE_SIZE;
3331 if (ret == 0) /* no more blocks */
3332 break;
3335 bwidth = get_clock() - bwidth;
3336 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3338 /* if we haven't transferred anything this round, force expected_time to a
3339 * a very high value, but without crashing */
3340 if (bwidth == 0)
3341 bwidth = 0.000001;
3343 /* try transferring iterative blocks of memory */
3345 if (stage == 3) {
3347 /* flush all remaining blocks regardless of rate limiting */
3348 while (ram_save_block(f) != 0) {
3349 bytes_transferred += TARGET_PAGE_SIZE;
3351 cpu_physical_memory_set_dirty_tracking(0);
3354 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3356 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3358 return (stage == 2) && (expected_time <= migrate_max_downtime());
3361 static int ram_load_dead(QEMUFile *f, void *opaque)
3363 RamDecompressState s1, *s = &s1;
3364 uint8_t buf[10];
3365 ram_addr_t i;
3367 if (ram_decompress_open(s, f) < 0)
3368 return -EINVAL;
3369 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3370 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3371 continue;
3372 if (ram_decompress_buf(s, buf, 1) < 0) {
3373 fprintf(stderr, "Error while reading ram block header\n");
3374 goto error;
3376 if (buf[0] == 0) {
3377 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3378 BDRV_HASH_BLOCK_SIZE) < 0) {
3379 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3380 goto error;
3382 } else {
3383 error:
3384 printf("Error block header\n");
3385 return -EINVAL;
3388 ram_decompress_close(s);
3390 return 0;
3393 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3395 ram_addr_t addr;
3396 int flags;
3398 if (version_id == 1)
3399 return ram_load_v1(f, opaque);
3401 if (version_id == 2) {
3402 if (qemu_get_be32(f) != last_ram_offset)
3403 return -EINVAL;
3404 return ram_load_dead(f, opaque);
3407 if (version_id != 3)
3408 return -EINVAL;
3410 do {
3411 addr = qemu_get_be64(f);
3413 flags = addr & ~TARGET_PAGE_MASK;
3414 addr &= TARGET_PAGE_MASK;
3416 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3417 if (addr != last_ram_offset)
3418 return -EINVAL;
3421 if (flags & RAM_SAVE_FLAG_FULL) {
3422 if (ram_load_dead(f, opaque) < 0)
3423 return -EINVAL;
3426 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3427 uint8_t ch = qemu_get_byte(f);
3428 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3429 #ifndef _WIN32
3430 if (ch == 0 &&
3431 (!kvm_enabled() || kvm_has_sync_mmu())) {
3432 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3434 #endif
3435 } else if (flags & RAM_SAVE_FLAG_PAGE)
3436 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3437 } while (!(flags & RAM_SAVE_FLAG_EOS));
3439 return 0;
3442 void qemu_service_io(void)
3444 qemu_notify_event();
3447 /***********************************************************/
3448 /* bottom halves (can be seen as timers which expire ASAP) */
3450 struct QEMUBH {
3451 QEMUBHFunc *cb;
3452 void *opaque;
3453 int scheduled;
3454 int idle;
3455 int deleted;
3456 QEMUBH *next;
3459 static QEMUBH *first_bh = NULL;
3461 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3463 QEMUBH *bh;
3464 bh = qemu_mallocz(sizeof(QEMUBH));
3465 bh->cb = cb;
3466 bh->opaque = opaque;
3467 bh->next = first_bh;
3468 first_bh = bh;
3469 return bh;
3472 int qemu_bh_poll(void)
3474 QEMUBH *bh, **bhp;
3475 int ret;
3477 ret = 0;
3478 for (bh = first_bh; bh; bh = bh->next) {
3479 if (!bh->deleted && bh->scheduled) {
3480 bh->scheduled = 0;
3481 if (!bh->idle)
3482 ret = 1;
3483 bh->idle = 0;
3484 bh->cb(bh->opaque);
3488 /* remove deleted bhs */
3489 bhp = &first_bh;
3490 while (*bhp) {
3491 bh = *bhp;
3492 if (bh->deleted) {
3493 *bhp = bh->next;
3494 qemu_free(bh);
3495 } else
3496 bhp = &bh->next;
3499 return ret;
3502 void qemu_bh_schedule_idle(QEMUBH *bh)
3504 if (bh->scheduled)
3505 return;
3506 bh->scheduled = 1;
3507 bh->idle = 1;
3510 void qemu_bh_schedule(QEMUBH *bh)
3512 if (bh->scheduled)
3513 return;
3514 bh->scheduled = 1;
3515 bh->idle = 0;
3516 /* stop the currently executing CPU to execute the BH ASAP */
3517 qemu_notify_event();
3520 void qemu_bh_cancel(QEMUBH *bh)
3522 bh->scheduled = 0;
3525 void qemu_bh_delete(QEMUBH *bh)
3527 bh->scheduled = 0;
3528 bh->deleted = 1;
3531 static void qemu_bh_update_timeout(int *timeout)
3533 QEMUBH *bh;
3535 for (bh = first_bh; bh; bh = bh->next) {
3536 if (!bh->deleted && bh->scheduled) {
3537 if (bh->idle) {
3538 /* idle bottom halves will be polled at least
3539 * every 10ms */
3540 *timeout = MIN(10, *timeout);
3541 } else {
3542 /* non-idle bottom halves will be executed
3543 * immediately */
3544 *timeout = 0;
3545 break;
3551 /***********************************************************/
3552 /* machine registration */
3554 static QEMUMachine *first_machine = NULL;
3555 QEMUMachine *current_machine = NULL;
3557 int qemu_register_machine(QEMUMachine *m)
3559 QEMUMachine **pm;
3560 pm = &first_machine;
3561 while (*pm != NULL)
3562 pm = &(*pm)->next;
3563 m->next = NULL;
3564 *pm = m;
3565 return 0;
3568 static QEMUMachine *find_machine(const char *name)
3570 QEMUMachine *m;
3572 for(m = first_machine; m != NULL; m = m->next) {
3573 if (!strcmp(m->name, name))
3574 return m;
3576 return NULL;
3579 static QEMUMachine *find_default_machine(void)
3581 QEMUMachine *m;
3583 for(m = first_machine; m != NULL; m = m->next) {
3584 if (m->is_default) {
3585 return m;
3588 return NULL;
3591 /***********************************************************/
3592 /* main execution loop */
3594 static void gui_update(void *opaque)
3596 uint64_t interval = GUI_REFRESH_INTERVAL;
3597 DisplayState *ds = opaque;
3598 DisplayChangeListener *dcl = ds->listeners;
3600 dpy_refresh(ds);
3602 while (dcl != NULL) {
3603 if (dcl->gui_timer_interval &&
3604 dcl->gui_timer_interval < interval)
3605 interval = dcl->gui_timer_interval;
3606 dcl = dcl->next;
3608 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3611 static void nographic_update(void *opaque)
3613 uint64_t interval = GUI_REFRESH_INTERVAL;
3615 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3618 struct vm_change_state_entry {
3619 VMChangeStateHandler *cb;
3620 void *opaque;
3621 LIST_ENTRY (vm_change_state_entry) entries;
3624 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3626 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3627 void *opaque)
3629 VMChangeStateEntry *e;
3631 e = qemu_mallocz(sizeof (*e));
3633 e->cb = cb;
3634 e->opaque = opaque;
3635 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3636 return e;
3639 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3641 LIST_REMOVE (e, entries);
3642 qemu_free (e);
3645 static void vm_state_notify(int running, int reason)
3647 VMChangeStateEntry *e;
3649 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3650 e->cb(e->opaque, running, reason);
3654 static void resume_all_vcpus(void);
3655 static void pause_all_vcpus(void);
3657 void vm_start(void)
3659 if (!vm_running) {
3660 cpu_enable_ticks();
3661 vm_running = 1;
3662 vm_state_notify(1, 0);
3663 qemu_rearm_alarm_timer(alarm_timer);
3664 resume_all_vcpus();
3668 /* reset/shutdown handler */
3670 typedef struct QEMUResetEntry {
3671 QEMUResetHandler *func;
3672 void *opaque;
3673 int order;
3674 struct QEMUResetEntry *next;
3675 } QEMUResetEntry;
3677 static QEMUResetEntry *first_reset_entry;
3678 static int reset_requested;
3679 static int shutdown_requested;
3680 static int powerdown_requested;
3681 static int debug_requested;
3682 static int vmstop_requested;
3684 int qemu_no_shutdown(void)
3686 int r = no_shutdown;
3687 no_shutdown = 0;
3688 return r;
3691 int qemu_shutdown_requested(void)
3693 int r = shutdown_requested;
3694 shutdown_requested = 0;
3695 return r;
3698 int qemu_reset_requested(void)
3700 int r = reset_requested;
3701 reset_requested = 0;
3702 return r;
3705 int qemu_powerdown_requested(void)
3707 int r = powerdown_requested;
3708 powerdown_requested = 0;
3709 return r;
3712 static int qemu_debug_requested(void)
3714 int r = debug_requested;
3715 debug_requested = 0;
3716 return r;
3719 static int qemu_vmstop_requested(void)
3721 int r = vmstop_requested;
3722 vmstop_requested = 0;
3723 return r;
3726 static void do_vm_stop(int reason)
3728 if (vm_running) {
3729 cpu_disable_ticks();
3730 vm_running = 0;
3731 pause_all_vcpus();
3732 vm_state_notify(0, reason);
3736 void qemu_register_reset(QEMUResetHandler *func, int order, void *opaque)
3738 QEMUResetEntry **pre, *re;
3740 pre = &first_reset_entry;
3741 while (*pre != NULL && (*pre)->order >= order) {
3742 pre = &(*pre)->next;
3744 re = qemu_mallocz(sizeof(QEMUResetEntry));
3745 re->func = func;
3746 re->opaque = opaque;
3747 re->order = order;
3748 re->next = NULL;
3749 *pre = re;
3752 void qemu_system_reset(void)
3754 QEMUResetEntry *re;
3756 /* reset all devices */
3757 for(re = first_reset_entry; re != NULL; re = re->next) {
3758 re->func(re->opaque);
3762 void qemu_system_reset_request(void)
3764 if (no_reboot) {
3765 shutdown_requested = 1;
3766 } else {
3767 reset_requested = 1;
3769 if (cpu_single_env) {
3770 qemu_kvm_cpu_stop(cpu_single_env);
3772 qemu_notify_event();
3775 void qemu_system_shutdown_request(void)
3777 shutdown_requested = 1;
3778 qemu_notify_event();
3781 void qemu_system_powerdown_request(void)
3783 powerdown_requested = 1;
3784 qemu_notify_event();
3787 #ifdef CONFIG_IOTHREAD
3788 static void qemu_system_vmstop_request(int reason)
3790 vmstop_requested = reason;
3791 qemu_notify_event();
3793 #endif
3795 #ifndef _WIN32
3796 static int io_thread_fd = -1;
3798 static void qemu_event_increment(void)
3800 static const char byte = 0;
3802 if (io_thread_fd == -1)
3803 return;
3805 write(io_thread_fd, &byte, sizeof(byte));
3808 static void qemu_event_read(void *opaque)
3810 int fd = (unsigned long)opaque;
3811 ssize_t len;
3813 /* Drain the notify pipe */
3814 do {
3815 char buffer[512];
3816 len = read(fd, buffer, sizeof(buffer));
3817 } while ((len == -1 && errno == EINTR) || len > 0);
3820 static int qemu_event_init(void)
3822 int err;
3823 int fds[2];
3825 err = pipe(fds);
3826 if (err == -1)
3827 return -errno;
3829 err = fcntl_setfl(fds[0], O_NONBLOCK);
3830 if (err < 0)
3831 goto fail;
3833 err = fcntl_setfl(fds[1], O_NONBLOCK);
3834 if (err < 0)
3835 goto fail;
3837 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3838 (void *)(unsigned long)fds[0]);
3840 io_thread_fd = fds[1];
3841 return 0;
3843 fail:
3844 close(fds[0]);
3845 close(fds[1]);
3846 return err;
3848 #else
3849 HANDLE qemu_event_handle;
3851 static void dummy_event_handler(void *opaque)
3855 static int qemu_event_init(void)
3857 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3858 if (!qemu_event_handle) {
3859 perror("Failed CreateEvent");
3860 return -1;
3862 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3863 return 0;
3866 static void qemu_event_increment(void)
3868 SetEvent(qemu_event_handle);
3870 #endif
3872 static int cpu_can_run(CPUState *env)
3874 if (env->stop)
3875 return 0;
3876 if (env->stopped)
3877 return 0;
3878 return 1;
3881 #ifndef CONFIG_IOTHREAD
3882 static int qemu_init_main_loop(void)
3884 return qemu_event_init();
3887 void qemu_init_vcpu(void *_env)
3889 CPUState *env = _env;
3891 if (kvm_enabled())
3892 kvm_init_vcpu(env);
3893 return;
3896 int qemu_cpu_self(void *env)
3898 return 1;
3901 static void resume_all_vcpus(void)
3905 static void pause_all_vcpus(void)
3909 void qemu_cpu_kick(void *env)
3911 return;
3914 void qemu_notify_event(void)
3916 CPUState *env = cpu_single_env;
3918 if (kvm_enabled()) {
3919 qemu_kvm_notify_work();
3920 return;
3922 if (env) {
3923 cpu_exit(env);
3924 #ifdef USE_KQEMU
3925 if (env->kqemu_enabled)
3926 kqemu_cpu_interrupt(env);
3927 #endif
3931 #define qemu_mutex_lock_iothread() do { } while (0)
3932 #define qemu_mutex_unlock_iothread() do { } while (0)
3934 void vm_stop(int reason)
3936 do_vm_stop(reason);
3939 #else /* CONFIG_IOTHREAD */
3941 #include "qemu-thread.h"
3943 QemuMutex qemu_global_mutex;
3944 static QemuMutex qemu_fair_mutex;
3946 static QemuThread io_thread;
3948 static QemuThread *tcg_cpu_thread;
3949 static QemuCond *tcg_halt_cond;
3951 static int qemu_system_ready;
3952 /* cpu creation */
3953 static QemuCond qemu_cpu_cond;
3954 /* system init */
3955 static QemuCond qemu_system_cond;
3956 static QemuCond qemu_pause_cond;
3958 static void block_io_signals(void);
3959 static void unblock_io_signals(void);
3960 static int tcg_has_work(void);
3962 static int qemu_init_main_loop(void)
3964 int ret;
3966 ret = qemu_event_init();
3967 if (ret)
3968 return ret;
3970 qemu_cond_init(&qemu_pause_cond);
3971 qemu_mutex_init(&qemu_fair_mutex);
3972 qemu_mutex_init(&qemu_global_mutex);
3973 qemu_mutex_lock(&qemu_global_mutex);
3975 unblock_io_signals();
3976 qemu_thread_self(&io_thread);
3978 return 0;
3981 static void qemu_wait_io_event(CPUState *env)
3983 while (!tcg_has_work())
3984 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3986 qemu_mutex_unlock(&qemu_global_mutex);
3989 * Users of qemu_global_mutex can be starved, having no chance
3990 * to acquire it since this path will get to it first.
3991 * So use another lock to provide fairness.
3993 qemu_mutex_lock(&qemu_fair_mutex);
3994 qemu_mutex_unlock(&qemu_fair_mutex);
3996 qemu_mutex_lock(&qemu_global_mutex);
3997 if (env->stop) {
3998 env->stop = 0;
3999 env->stopped = 1;
4000 qemu_cond_signal(&qemu_pause_cond);
4004 static int qemu_cpu_exec(CPUState *env);
4006 static void *kvm_cpu_thread_fn(void *arg)
4008 CPUState *env = arg;
4010 block_io_signals();
4011 qemu_thread_self(env->thread);
4013 /* signal CPU creation */
4014 qemu_mutex_lock(&qemu_global_mutex);
4015 env->created = 1;
4016 qemu_cond_signal(&qemu_cpu_cond);
4018 /* and wait for machine initialization */
4019 while (!qemu_system_ready)
4020 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
4022 while (1) {
4023 if (cpu_can_run(env))
4024 qemu_cpu_exec(env);
4025 qemu_wait_io_event(env);
4028 return NULL;
4031 static void tcg_cpu_exec(void);
4033 static void *tcg_cpu_thread_fn(void *arg)
4035 CPUState *env = arg;
4037 block_io_signals();
4038 qemu_thread_self(env->thread);
4040 /* signal CPU creation */
4041 qemu_mutex_lock(&qemu_global_mutex);
4042 for (env = first_cpu; env != NULL; env = env->next_cpu)
4043 env->created = 1;
4044 qemu_cond_signal(&qemu_cpu_cond);
4046 /* and wait for machine initialization */
4047 while (!qemu_system_ready)
4048 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
4050 while (1) {
4051 tcg_cpu_exec();
4052 qemu_wait_io_event(cur_cpu);
4055 return NULL;
4058 void qemu_cpu_kick(void *_env)
4060 CPUState *env = _env;
4061 qemu_cond_broadcast(env->halt_cond);
4062 if (kvm_enabled())
4063 qemu_thread_signal(env->thread, SIGUSR1);
4066 int qemu_cpu_self(void *env)
4068 return (cpu_single_env != NULL);
4071 static void cpu_signal(int sig)
4073 if (cpu_single_env)
4074 cpu_exit(cpu_single_env);
4077 static void block_io_signals(void)
4079 sigset_t set;
4080 struct sigaction sigact;
4082 sigemptyset(&set);
4083 sigaddset(&set, SIGUSR2);
4084 sigaddset(&set, SIGIO);
4085 sigaddset(&set, SIGALRM);
4086 pthread_sigmask(SIG_BLOCK, &set, NULL);
4088 sigemptyset(&set);
4089 sigaddset(&set, SIGUSR1);
4090 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4092 memset(&sigact, 0, sizeof(sigact));
4093 sigact.sa_handler = cpu_signal;
4094 sigaction(SIGUSR1, &sigact, NULL);
4097 static void unblock_io_signals(void)
4099 sigset_t set;
4101 sigemptyset(&set);
4102 sigaddset(&set, SIGUSR2);
4103 sigaddset(&set, SIGIO);
4104 sigaddset(&set, SIGALRM);
4105 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4107 sigemptyset(&set);
4108 sigaddset(&set, SIGUSR1);
4109 pthread_sigmask(SIG_BLOCK, &set, NULL);
4112 static void qemu_signal_lock(unsigned int msecs)
4114 qemu_mutex_lock(&qemu_fair_mutex);
4116 while (qemu_mutex_trylock(&qemu_global_mutex)) {
4117 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
4118 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
4119 break;
4121 qemu_mutex_unlock(&qemu_fair_mutex);
4124 static void qemu_mutex_lock_iothread(void)
4126 if (kvm_enabled()) {
4127 qemu_mutex_lock(&qemu_fair_mutex);
4128 qemu_mutex_lock(&qemu_global_mutex);
4129 qemu_mutex_unlock(&qemu_fair_mutex);
4130 } else
4131 qemu_signal_lock(100);
4134 static void qemu_mutex_unlock_iothread(void)
4136 qemu_mutex_unlock(&qemu_global_mutex);
4139 static int all_vcpus_paused(void)
4141 CPUState *penv = first_cpu;
4143 while (penv) {
4144 if (!penv->stopped)
4145 return 0;
4146 penv = (CPUState *)penv->next_cpu;
4149 return 1;
4152 static void pause_all_vcpus(void)
4154 CPUState *penv = first_cpu;
4156 while (penv) {
4157 penv->stop = 1;
4158 qemu_thread_signal(penv->thread, SIGUSR1);
4159 qemu_cpu_kick(penv);
4160 penv = (CPUState *)penv->next_cpu;
4163 while (!all_vcpus_paused()) {
4164 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
4165 penv = first_cpu;
4166 while (penv) {
4167 qemu_thread_signal(penv->thread, SIGUSR1);
4168 penv = (CPUState *)penv->next_cpu;
4173 static void resume_all_vcpus(void)
4175 CPUState *penv = first_cpu;
4177 while (penv) {
4178 penv->stop = 0;
4179 penv->stopped = 0;
4180 qemu_thread_signal(penv->thread, SIGUSR1);
4181 qemu_cpu_kick(penv);
4182 penv = (CPUState *)penv->next_cpu;
4186 static void tcg_init_vcpu(void *_env)
4188 CPUState *env = _env;
4189 /* share a single thread for all cpus with TCG */
4190 if (!tcg_cpu_thread) {
4191 env->thread = qemu_mallocz(sizeof(QemuThread));
4192 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4193 qemu_cond_init(env->halt_cond);
4194 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
4195 while (env->created == 0)
4196 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4197 tcg_cpu_thread = env->thread;
4198 tcg_halt_cond = env->halt_cond;
4199 } else {
4200 env->thread = tcg_cpu_thread;
4201 env->halt_cond = tcg_halt_cond;
4205 static void kvm_start_vcpu(CPUState *env)
4207 kvm_init_vcpu(env);
4208 env->thread = qemu_mallocz(sizeof(QemuThread));
4209 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4210 qemu_cond_init(env->halt_cond);
4211 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
4212 while (env->created == 0)
4213 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4216 void qemu_init_vcpu(void *_env)
4218 CPUState *env = _env;
4220 if (kvm_enabled())
4221 kvm_start_vcpu(env);
4222 else
4223 tcg_init_vcpu(env);
4226 void qemu_notify_event(void)
4228 qemu_event_increment();
4231 void vm_stop(int reason)
4233 QemuThread me;
4234 qemu_thread_self(&me);
4236 if (!qemu_thread_equal(&me, &io_thread)) {
4237 qemu_system_vmstop_request(reason);
4239 * FIXME: should not return to device code in case
4240 * vm_stop() has been requested.
4242 if (cpu_single_env) {
4243 cpu_exit(cpu_single_env);
4244 cpu_single_env->stop = 1;
4246 return;
4248 do_vm_stop(reason);
4251 #endif
4254 #ifdef _WIN32
4255 static void host_main_loop_wait(int *timeout)
4257 int ret, ret2, i;
4258 PollingEntry *pe;
4261 /* XXX: need to suppress polling by better using win32 events */
4262 ret = 0;
4263 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4264 ret |= pe->func(pe->opaque);
4266 if (ret == 0) {
4267 int err;
4268 WaitObjects *w = &wait_objects;
4270 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4271 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4272 if (w->func[ret - WAIT_OBJECT_0])
4273 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4275 /* Check for additional signaled events */
4276 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4278 /* Check if event is signaled */
4279 ret2 = WaitForSingleObject(w->events[i], 0);
4280 if(ret2 == WAIT_OBJECT_0) {
4281 if (w->func[i])
4282 w->func[i](w->opaque[i]);
4283 } else if (ret2 == WAIT_TIMEOUT) {
4284 } else {
4285 err = GetLastError();
4286 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4289 } else if (ret == WAIT_TIMEOUT) {
4290 } else {
4291 err = GetLastError();
4292 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4296 *timeout = 0;
4298 #else
4299 static void host_main_loop_wait(int *timeout)
4302 #endif
4304 void main_loop_wait(int timeout)
4306 IOHandlerRecord *ioh;
4307 fd_set rfds, wfds, xfds;
4308 int ret, nfds;
4309 struct timeval tv;
4311 qemu_bh_update_timeout(&timeout);
4313 host_main_loop_wait(&timeout);
4315 /* poll any events */
4316 /* XXX: separate device handlers from system ones */
4317 nfds = -1;
4318 FD_ZERO(&rfds);
4319 FD_ZERO(&wfds);
4320 FD_ZERO(&xfds);
4321 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4322 if (ioh->deleted)
4323 continue;
4324 if (ioh->fd_read &&
4325 (!ioh->fd_read_poll ||
4326 ioh->fd_read_poll(ioh->opaque) != 0)) {
4327 FD_SET(ioh->fd, &rfds);
4328 if (ioh->fd > nfds)
4329 nfds = ioh->fd;
4331 if (ioh->fd_write) {
4332 FD_SET(ioh->fd, &wfds);
4333 if (ioh->fd > nfds)
4334 nfds = ioh->fd;
4338 tv.tv_sec = timeout / 1000;
4339 tv.tv_usec = (timeout % 1000) * 1000;
4341 #if defined(CONFIG_SLIRP)
4342 if (slirp_is_inited()) {
4343 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4345 #endif
4346 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4347 if (ret > 0) {
4348 IOHandlerRecord **pioh;
4350 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4351 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4352 ioh->fd_read(ioh->opaque);
4353 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
4354 FD_CLR(ioh->fd, &rfds);
4356 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4357 ioh->fd_write(ioh->opaque);
4361 /* remove deleted IO handlers */
4362 pioh = &first_io_handler;
4363 while (*pioh) {
4364 ioh = *pioh;
4365 if (ioh->deleted) {
4366 *pioh = ioh->next;
4367 qemu_free(ioh);
4368 } else
4369 pioh = &ioh->next;
4372 #if defined(CONFIG_SLIRP)
4373 if (slirp_is_inited()) {
4374 if (ret < 0) {
4375 FD_ZERO(&rfds);
4376 FD_ZERO(&wfds);
4377 FD_ZERO(&xfds);
4379 slirp_select_poll(&rfds, &wfds, &xfds);
4381 #endif
4383 /* rearm timer, if not periodic */
4384 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4385 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4386 qemu_rearm_alarm_timer(alarm_timer);
4389 /* vm time timers */
4390 if (vm_running) {
4391 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4392 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4393 qemu_get_clock(vm_clock));
4396 /* real time timers */
4397 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4398 qemu_get_clock(rt_clock));
4400 /* Check bottom-halves last in case any of the earlier events triggered
4401 them. */
4402 qemu_bh_poll();
4406 static int qemu_cpu_exec(CPUState *env)
4408 int ret;
4409 #ifdef CONFIG_PROFILER
4410 int64_t ti;
4411 #endif
4413 #ifdef CONFIG_PROFILER
4414 ti = profile_getclock();
4415 #endif
4416 if (use_icount) {
4417 int64_t count;
4418 int decr;
4419 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4420 env->icount_decr.u16.low = 0;
4421 env->icount_extra = 0;
4422 count = qemu_next_deadline();
4423 count = (count + (1 << icount_time_shift) - 1)
4424 >> icount_time_shift;
4425 qemu_icount += count;
4426 decr = (count > 0xffff) ? 0xffff : count;
4427 count -= decr;
4428 env->icount_decr.u16.low = decr;
4429 env->icount_extra = count;
4431 ret = cpu_exec(env);
4432 #ifdef CONFIG_PROFILER
4433 qemu_time += profile_getclock() - ti;
4434 #endif
4435 if (use_icount) {
4436 /* Fold pending instructions back into the
4437 instruction counter, and clear the interrupt flag. */
4438 qemu_icount -= (env->icount_decr.u16.low
4439 + env->icount_extra);
4440 env->icount_decr.u32 = 0;
4441 env->icount_extra = 0;
4443 return ret;
4446 static void tcg_cpu_exec(void)
4448 int ret = 0;
4450 if (next_cpu == NULL)
4451 next_cpu = first_cpu;
4452 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4453 CPUState *env = cur_cpu = next_cpu;
4455 if (!vm_running)
4456 break;
4457 if (timer_alarm_pending) {
4458 timer_alarm_pending = 0;
4459 break;
4461 if (cpu_can_run(env))
4462 ret = qemu_cpu_exec(env);
4463 if (ret == EXCP_DEBUG) {
4464 gdb_set_stop_cpu(env);
4465 debug_requested = 1;
4466 break;
4471 static int cpu_has_work(CPUState *env)
4473 if (env->stop)
4474 return 1;
4475 if (env->stopped)
4476 return 0;
4477 if (!env->halted)
4478 return 1;
4479 if (qemu_cpu_has_work(env))
4480 return 1;
4481 return 0;
4484 static int tcg_has_work(void)
4486 CPUState *env;
4488 for (env = first_cpu; env != NULL; env = env->next_cpu)
4489 if (cpu_has_work(env))
4490 return 1;
4491 return 0;
4494 static int qemu_calculate_timeout(void)
4496 #ifndef CONFIG_IOTHREAD
4497 int timeout;
4499 if (!vm_running)
4500 timeout = 5000;
4501 else if (tcg_has_work())
4502 timeout = 0;
4503 else if (!use_icount)
4504 timeout = 5000;
4505 else {
4506 /* XXX: use timeout computed from timers */
4507 int64_t add;
4508 int64_t delta;
4509 /* Advance virtual time to the next event. */
4510 if (use_icount == 1) {
4511 /* When not using an adaptive execution frequency
4512 we tend to get badly out of sync with real time,
4513 so just delay for a reasonable amount of time. */
4514 delta = 0;
4515 } else {
4516 delta = cpu_get_icount() - cpu_get_clock();
4518 if (delta > 0) {
4519 /* If virtual time is ahead of real time then just
4520 wait for IO. */
4521 timeout = (delta / 1000000) + 1;
4522 } else {
4523 /* Wait for either IO to occur or the next
4524 timer event. */
4525 add = qemu_next_deadline();
4526 /* We advance the timer before checking for IO.
4527 Limit the amount we advance so that early IO
4528 activity won't get the guest too far ahead. */
4529 if (add > 10000000)
4530 add = 10000000;
4531 delta += add;
4532 add = (add + (1 << icount_time_shift) - 1)
4533 >> icount_time_shift;
4534 qemu_icount += add;
4535 timeout = delta / 1000000;
4536 if (timeout < 0)
4537 timeout = 0;
4541 return timeout;
4542 #else /* CONFIG_IOTHREAD */
4543 return 1000;
4544 #endif
4547 static int vm_can_run(void)
4549 if (powerdown_requested)
4550 return 0;
4551 if (reset_requested)
4552 return 0;
4553 if (shutdown_requested)
4554 return 0;
4555 if (debug_requested)
4556 return 0;
4557 return 1;
4560 static void main_loop(void)
4562 int r;
4564 if (kvm_enabled()) {
4565 kvm_main_loop();
4566 cpu_disable_ticks();
4567 return;
4570 #ifdef CONFIG_IOTHREAD
4571 qemu_system_ready = 1;
4572 qemu_cond_broadcast(&qemu_system_cond);
4573 #endif
4575 for (;;) {
4576 do {
4577 #ifdef CONFIG_PROFILER
4578 int64_t ti;
4579 #endif
4580 #ifndef CONFIG_IOTHREAD
4581 tcg_cpu_exec();
4582 #endif
4583 #ifdef CONFIG_PROFILER
4584 ti = profile_getclock();
4585 #endif
4586 main_loop_wait(qemu_calculate_timeout());
4587 #ifdef CONFIG_PROFILER
4588 dev_time += profile_getclock() - ti;
4589 #endif
4590 } while (vm_can_run());
4592 if (qemu_debug_requested())
4593 vm_stop(EXCP_DEBUG);
4594 if (qemu_shutdown_requested()) {
4595 if (no_shutdown) {
4596 vm_stop(0);
4597 no_shutdown = 0;
4598 } else
4599 break;
4601 if (qemu_reset_requested()) {
4602 pause_all_vcpus();
4603 qemu_system_reset();
4604 resume_all_vcpus();
4606 if (qemu_powerdown_requested())
4607 qemu_system_powerdown();
4608 if ((r = qemu_vmstop_requested()))
4609 vm_stop(r);
4611 pause_all_vcpus();
4614 static void version(void)
4616 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4619 static void help(int exitcode)
4621 version();
4622 printf("usage: %s [options] [disk_image]\n"
4623 "\n"
4624 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4625 "\n"
4626 #define DEF(option, opt_arg, opt_enum, opt_help) \
4627 opt_help
4628 #define DEFHEADING(text) stringify(text) "\n"
4629 #include "qemu-options.h"
4630 #undef DEF
4631 #undef DEFHEADING
4632 #undef GEN_DOCS
4633 "\n"
4634 "During emulation, the following keys are useful:\n"
4635 "ctrl-alt-f toggle full screen\n"
4636 "ctrl-alt-n switch to virtual console 'n'\n"
4637 "ctrl-alt toggle mouse and keyboard grab\n"
4638 "\n"
4639 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4641 "qemu",
4642 DEFAULT_RAM_SIZE,
4643 #ifndef _WIN32
4644 DEFAULT_NETWORK_SCRIPT,
4645 DEFAULT_NETWORK_DOWN_SCRIPT,
4646 #endif
4647 DEFAULT_GDBSTUB_PORT,
4648 "/tmp/qemu.log");
4649 exit(exitcode);
4652 #define HAS_ARG 0x0001
4654 enum {
4655 #define DEF(option, opt_arg, opt_enum, opt_help) \
4656 opt_enum,
4657 #define DEFHEADING(text)
4658 #include "qemu-options.h"
4659 #undef DEF
4660 #undef DEFHEADING
4661 #undef GEN_DOCS
4664 typedef struct QEMUOption {
4665 const char *name;
4666 int flags;
4667 int index;
4668 } QEMUOption;
4670 static const QEMUOption qemu_options[] = {
4671 { "h", 0, QEMU_OPTION_h },
4672 #define DEF(option, opt_arg, opt_enum, opt_help) \
4673 { option, opt_arg, opt_enum },
4674 #define DEFHEADING(text)
4675 #include "qemu-options.h"
4676 #undef DEF
4677 #undef DEFHEADING
4678 #undef GEN_DOCS
4679 { NULL },
4682 #ifdef HAS_AUDIO
4683 struct soundhw soundhw[] = {
4684 #ifdef HAS_AUDIO_CHOICE
4685 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4687 "pcspk",
4688 "PC speaker",
4691 { .init_isa = pcspk_audio_init }
4693 #endif
4695 #ifdef CONFIG_SB16
4697 "sb16",
4698 "Creative Sound Blaster 16",
4701 { .init_isa = SB16_init }
4703 #endif
4705 #ifdef CONFIG_CS4231A
4707 "cs4231a",
4708 "CS4231A",
4711 { .init_isa = cs4231a_init }
4713 #endif
4715 #ifdef CONFIG_ADLIB
4717 "adlib",
4718 #ifdef HAS_YMF262
4719 "Yamaha YMF262 (OPL3)",
4720 #else
4721 "Yamaha YM3812 (OPL2)",
4722 #endif
4725 { .init_isa = Adlib_init }
4727 #endif
4729 #ifdef CONFIG_GUS
4731 "gus",
4732 "Gravis Ultrasound GF1",
4735 { .init_isa = GUS_init }
4737 #endif
4739 #ifdef CONFIG_AC97
4741 "ac97",
4742 "Intel 82801AA AC97 Audio",
4745 { .init_pci = ac97_init }
4747 #endif
4749 #ifdef CONFIG_ES1370
4751 "es1370",
4752 "ENSONIQ AudioPCI ES1370",
4755 { .init_pci = es1370_init }
4757 #endif
4759 #endif /* HAS_AUDIO_CHOICE */
4761 { NULL, NULL, 0, 0, { NULL } }
4764 static void select_soundhw (const char *optarg)
4766 struct soundhw *c;
4768 if (*optarg == '?') {
4769 show_valid_cards:
4771 printf ("Valid sound card names (comma separated):\n");
4772 for (c = soundhw; c->name; ++c) {
4773 printf ("%-11s %s\n", c->name, c->descr);
4775 printf ("\n-soundhw all will enable all of the above\n");
4776 exit (*optarg != '?');
4778 else {
4779 size_t l;
4780 const char *p;
4781 char *e;
4782 int bad_card = 0;
4784 if (!strcmp (optarg, "all")) {
4785 for (c = soundhw; c->name; ++c) {
4786 c->enabled = 1;
4788 return;
4791 p = optarg;
4792 while (*p) {
4793 e = strchr (p, ',');
4794 l = !e ? strlen (p) : (size_t) (e - p);
4796 for (c = soundhw; c->name; ++c) {
4797 if (!strncmp (c->name, p, l)) {
4798 c->enabled = 1;
4799 break;
4803 if (!c->name) {
4804 if (l > 80) {
4805 fprintf (stderr,
4806 "Unknown sound card name (too big to show)\n");
4808 else {
4809 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4810 (int) l, p);
4812 bad_card = 1;
4814 p += l + (e != NULL);
4817 if (bad_card)
4818 goto show_valid_cards;
4821 #endif
4823 static void select_vgahw (const char *p)
4825 const char *opts;
4827 cirrus_vga_enabled = 0;
4828 std_vga_enabled = 0;
4829 vmsvga_enabled = 0;
4830 xenfb_enabled = 0;
4831 if (strstart(p, "std", &opts)) {
4832 std_vga_enabled = 1;
4833 } else if (strstart(p, "cirrus", &opts)) {
4834 cirrus_vga_enabled = 1;
4835 } else if (strstart(p, "vmware", &opts)) {
4836 vmsvga_enabled = 1;
4837 } else if (strstart(p, "xenfb", &opts)) {
4838 xenfb_enabled = 1;
4839 } else if (!strstart(p, "none", &opts)) {
4840 invalid_vga:
4841 fprintf(stderr, "Unknown vga type: %s\n", p);
4842 exit(1);
4844 while (*opts) {
4845 const char *nextopt;
4847 if (strstart(opts, ",retrace=", &nextopt)) {
4848 opts = nextopt;
4849 if (strstart(opts, "dumb", &nextopt))
4850 vga_retrace_method = VGA_RETRACE_DUMB;
4851 else if (strstart(opts, "precise", &nextopt))
4852 vga_retrace_method = VGA_RETRACE_PRECISE;
4853 else goto invalid_vga;
4854 } else goto invalid_vga;
4855 opts = nextopt;
4859 #ifdef _WIN32
4860 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4862 exit(STATUS_CONTROL_C_EXIT);
4863 return TRUE;
4865 #endif
4867 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4869 int ret;
4871 if(strlen(str) != 36)
4872 return -1;
4874 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4875 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4876 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4878 if(ret != 16)
4879 return -1;
4881 #ifdef TARGET_I386
4882 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4883 #endif
4885 return 0;
4888 #define MAX_NET_CLIENTS 32
4890 #ifndef _WIN32
4892 static void termsig_handler(int signal)
4894 qemu_system_shutdown_request();
4897 static void sigchld_handler(int signal)
4899 waitpid(-1, NULL, WNOHANG);
4902 static void sighandler_setup(void)
4904 struct sigaction act;
4906 memset(&act, 0, sizeof(act));
4907 act.sa_handler = termsig_handler;
4908 sigaction(SIGINT, &act, NULL);
4909 sigaction(SIGHUP, &act, NULL);
4910 sigaction(SIGTERM, &act, NULL);
4912 act.sa_handler = sigchld_handler;
4913 act.sa_flags = SA_NOCLDSTOP;
4914 sigaction(SIGCHLD, &act, NULL);
4917 #endif
4919 #ifdef _WIN32
4920 /* Look for support files in the same directory as the executable. */
4921 static char *find_datadir(const char *argv0)
4923 char *p;
4924 char buf[MAX_PATH];
4925 DWORD len;
4927 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4928 if (len == 0) {
4929 return NULL;
4932 buf[len] = 0;
4933 p = buf + len - 1;
4934 while (p != buf && *p != '\\')
4935 p--;
4936 *p = 0;
4937 if (access(buf, R_OK) == 0) {
4938 return qemu_strdup(buf);
4940 return NULL;
4942 #else /* !_WIN32 */
4944 /* Find a likely location for support files using the location of the binary.
4945 For installed binaries this will be "$bindir/../share/qemu". When
4946 running from the build tree this will be "$bindir/../pc-bios". */
4947 #define SHARE_SUFFIX "/share/qemu"
4948 #define BUILD_SUFFIX "/pc-bios"
4949 static char *find_datadir(const char *argv0)
4951 char *dir;
4952 char *p = NULL;
4953 char *res;
4954 #ifdef PATH_MAX
4955 char buf[PATH_MAX];
4956 #endif
4957 size_t max_len;
4959 #if defined(__linux__)
4961 int len;
4962 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4963 if (len > 0) {
4964 buf[len] = 0;
4965 p = buf;
4968 #elif defined(__FreeBSD__)
4970 int len;
4971 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4972 if (len > 0) {
4973 buf[len] = 0;
4974 p = buf;
4977 #endif
4978 /* If we don't have any way of figuring out the actual executable
4979 location then try argv[0]. */
4980 if (!p) {
4981 #ifdef PATH_MAX
4982 p = buf;
4983 #endif
4984 p = realpath(argv0, p);
4985 if (!p) {
4986 return NULL;
4989 dir = dirname(p);
4990 dir = dirname(dir);
4992 max_len = strlen(dir) +
4993 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4994 res = qemu_mallocz(max_len);
4995 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4996 if (access(res, R_OK)) {
4997 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4998 if (access(res, R_OK)) {
4999 qemu_free(res);
5000 res = NULL;
5003 #ifndef PATH_MAX
5004 free(p);
5005 #endif
5006 return res;
5008 #undef SHARE_SUFFIX
5009 #undef BUILD_SUFFIX
5010 #endif
5012 char *qemu_find_file(int type, const char *name)
5014 int len;
5015 const char *subdir;
5016 char *buf;
5018 /* If name contains path separators then try it as a straight path. */
5019 if ((strchr(name, '/') || strchr(name, '\\'))
5020 && access(name, R_OK) == 0) {
5021 return strdup(name);
5023 switch (type) {
5024 case QEMU_FILE_TYPE_BIOS:
5025 subdir = "";
5026 break;
5027 case QEMU_FILE_TYPE_KEYMAP:
5028 subdir = "keymaps/";
5029 break;
5030 default:
5031 abort();
5033 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
5034 buf = qemu_mallocz(len);
5035 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
5036 if (access(buf, R_OK)) {
5037 qemu_free(buf);
5038 return NULL;
5040 return buf;
5043 int main(int argc, char **argv, char **envp)
5045 const char *gdbstub_dev = NULL;
5046 uint32_t boot_devices_bitmap = 0;
5047 int i;
5048 int snapshot, linux_boot, net_boot;
5049 const char *initrd_filename;
5050 const char *kernel_filename, *kernel_cmdline;
5051 const char *boot_devices = "";
5052 DisplayState *ds;
5053 DisplayChangeListener *dcl;
5054 int cyls, heads, secs, translation;
5055 const char *net_clients[MAX_NET_CLIENTS];
5056 int nb_net_clients;
5057 const char *bt_opts[MAX_BT_CMDLINE];
5058 int nb_bt_opts;
5059 int hda_index;
5060 int optind;
5061 const char *r, *optarg;
5062 CharDriverState *monitor_hd = NULL;
5063 const char *monitor_device;
5064 const char *serial_devices[MAX_SERIAL_PORTS];
5065 int serial_device_index;
5066 const char *parallel_devices[MAX_PARALLEL_PORTS];
5067 int parallel_device_index;
5068 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
5069 int virtio_console_index;
5070 const char *loadvm = NULL;
5071 QEMUMachine *machine;
5072 const char *cpu_model;
5073 const char *usb_devices[MAX_USB_CMDLINE];
5074 int usb_devices_index;
5075 #ifndef _WIN32
5076 int fds[2];
5077 #endif
5078 int tb_size;
5079 const char *pid_file = NULL;
5080 const char *incoming = NULL;
5081 #ifndef _WIN32
5082 int fd = 0;
5083 struct passwd *pwd = NULL;
5084 const char *chroot_dir = NULL;
5085 const char *run_as = NULL;
5086 #endif
5087 CPUState *env;
5088 int show_vnc_port = 0;
5090 qemu_cache_utils_init(envp);
5092 LIST_INIT (&vm_change_state_head);
5093 #ifndef _WIN32
5095 struct sigaction act;
5096 sigfillset(&act.sa_mask);
5097 act.sa_flags = 0;
5098 act.sa_handler = SIG_IGN;
5099 sigaction(SIGPIPE, &act, NULL);
5101 #else
5102 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5103 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5104 QEMU to run on a single CPU */
5106 HANDLE h;
5107 DWORD mask, smask;
5108 int i;
5109 h = GetCurrentProcess();
5110 if (GetProcessAffinityMask(h, &mask, &smask)) {
5111 for(i = 0; i < 32; i++) {
5112 if (mask & (1 << i))
5113 break;
5115 if (i != 32) {
5116 mask = 1 << i;
5117 SetProcessAffinityMask(h, mask);
5121 #endif
5123 module_call_init(MODULE_INIT_MACHINE);
5124 machine = find_default_machine();
5125 cpu_model = NULL;
5126 initrd_filename = NULL;
5127 ram_size = 0;
5128 snapshot = 0;
5129 kernel_filename = NULL;
5130 kernel_cmdline = "";
5131 cyls = heads = secs = 0;
5132 translation = BIOS_ATA_TRANSLATION_AUTO;
5133 monitor_device = "vc:80Cx24C";
5135 serial_devices[0] = "vc:80Cx24C";
5136 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5137 serial_devices[i] = NULL;
5138 serial_device_index = 0;
5140 parallel_devices[0] = "vc:80Cx24C";
5141 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5142 parallel_devices[i] = NULL;
5143 parallel_device_index = 0;
5145 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
5146 virtio_consoles[i] = NULL;
5147 virtio_console_index = 0;
5149 for (i = 0; i < MAX_NODES; i++) {
5150 node_mem[i] = 0;
5151 node_cpumask[i] = 0;
5154 usb_devices_index = 0;
5155 assigned_devices_index = 0;
5157 nb_net_clients = 0;
5158 nb_bt_opts = 0;
5159 nb_drives = 0;
5160 nb_drives_opt = 0;
5161 nb_numa_nodes = 0;
5162 hda_index = -1;
5164 nb_nics = 0;
5166 tb_size = 0;
5167 autostart= 1;
5169 register_watchdogs();
5171 optind = 1;
5172 for(;;) {
5173 if (optind >= argc)
5174 break;
5175 r = argv[optind];
5176 if (r[0] != '-') {
5177 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5178 } else {
5179 const QEMUOption *popt;
5181 optind++;
5182 /* Treat --foo the same as -foo. */
5183 if (r[1] == '-')
5184 r++;
5185 popt = qemu_options;
5186 for(;;) {
5187 if (!popt->name) {
5188 fprintf(stderr, "%s: invalid option -- '%s'\n",
5189 argv[0], r);
5190 exit(1);
5192 if (!strcmp(popt->name, r + 1))
5193 break;
5194 popt++;
5196 if (popt->flags & HAS_ARG) {
5197 if (optind >= argc) {
5198 fprintf(stderr, "%s: option '%s' requires an argument\n",
5199 argv[0], r);
5200 exit(1);
5202 optarg = argv[optind++];
5203 } else {
5204 optarg = NULL;
5207 switch(popt->index) {
5208 case QEMU_OPTION_M:
5209 machine = find_machine(optarg);
5210 if (!machine) {
5211 QEMUMachine *m;
5212 printf("Supported machines are:\n");
5213 for(m = first_machine; m != NULL; m = m->next) {
5214 printf("%-10s %s%s\n",
5215 m->name, m->desc,
5216 m->is_default ? " (default)" : "");
5218 exit(*optarg != '?');
5220 break;
5221 case QEMU_OPTION_cpu:
5222 /* hw initialization will check this */
5223 if (*optarg == '?') {
5224 /* XXX: implement xxx_cpu_list for targets that still miss it */
5225 #if defined(cpu_list)
5226 cpu_list(stdout, &fprintf);
5227 #endif
5228 exit(0);
5229 } else {
5230 cpu_model = optarg;
5232 break;
5233 case QEMU_OPTION_initrd:
5234 initrd_filename = optarg;
5235 break;
5236 case QEMU_OPTION_hda:
5237 if (cyls == 0)
5238 hda_index = drive_add(optarg, HD_ALIAS, 0);
5239 else
5240 hda_index = drive_add(optarg, HD_ALIAS
5241 ",cyls=%d,heads=%d,secs=%d%s",
5242 0, cyls, heads, secs,
5243 translation == BIOS_ATA_TRANSLATION_LBA ?
5244 ",trans=lba" :
5245 translation == BIOS_ATA_TRANSLATION_NONE ?
5246 ",trans=none" : "");
5247 break;
5248 case QEMU_OPTION_hdb:
5249 case QEMU_OPTION_hdc:
5250 case QEMU_OPTION_hdd:
5251 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5252 break;
5253 case QEMU_OPTION_drive:
5254 drive_add(NULL, "%s", optarg);
5255 break;
5256 case QEMU_OPTION_mtdblock:
5257 drive_add(optarg, MTD_ALIAS);
5258 break;
5259 case QEMU_OPTION_sd:
5260 drive_add(optarg, SD_ALIAS);
5261 break;
5262 case QEMU_OPTION_pflash:
5263 drive_add(optarg, PFLASH_ALIAS);
5264 break;
5265 case QEMU_OPTION_snapshot:
5266 snapshot = 1;
5267 break;
5268 case QEMU_OPTION_hdachs:
5270 const char *p;
5271 p = optarg;
5272 cyls = strtol(p, (char **)&p, 0);
5273 if (cyls < 1 || cyls > 16383)
5274 goto chs_fail;
5275 if (*p != ',')
5276 goto chs_fail;
5277 p++;
5278 heads = strtol(p, (char **)&p, 0);
5279 if (heads < 1 || heads > 16)
5280 goto chs_fail;
5281 if (*p != ',')
5282 goto chs_fail;
5283 p++;
5284 secs = strtol(p, (char **)&p, 0);
5285 if (secs < 1 || secs > 63)
5286 goto chs_fail;
5287 if (*p == ',') {
5288 p++;
5289 if (!strcmp(p, "none"))
5290 translation = BIOS_ATA_TRANSLATION_NONE;
5291 else if (!strcmp(p, "lba"))
5292 translation = BIOS_ATA_TRANSLATION_LBA;
5293 else if (!strcmp(p, "auto"))
5294 translation = BIOS_ATA_TRANSLATION_AUTO;
5295 else
5296 goto chs_fail;
5297 } else if (*p != '\0') {
5298 chs_fail:
5299 fprintf(stderr, "qemu: invalid physical CHS format\n");
5300 exit(1);
5302 if (hda_index != -1)
5303 snprintf(drives_opt[hda_index].opt,
5304 sizeof(drives_opt[hda_index].opt),
5305 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5306 0, cyls, heads, secs,
5307 translation == BIOS_ATA_TRANSLATION_LBA ?
5308 ",trans=lba" :
5309 translation == BIOS_ATA_TRANSLATION_NONE ?
5310 ",trans=none" : "");
5312 break;
5313 case QEMU_OPTION_numa:
5314 if (nb_numa_nodes >= MAX_NODES) {
5315 fprintf(stderr, "qemu: too many NUMA nodes\n");
5316 exit(1);
5318 numa_add(optarg);
5319 break;
5320 case QEMU_OPTION_nographic:
5321 display_type = DT_NOGRAPHIC;
5322 break;
5323 #ifdef CONFIG_CURSES
5324 case QEMU_OPTION_curses:
5325 display_type = DT_CURSES;
5326 break;
5327 #endif
5328 case QEMU_OPTION_portrait:
5329 graphic_rotate = 1;
5330 break;
5331 case QEMU_OPTION_kernel:
5332 kernel_filename = optarg;
5333 break;
5334 case QEMU_OPTION_append:
5335 kernel_cmdline = optarg;
5336 break;
5337 case QEMU_OPTION_cdrom:
5338 drive_add(optarg, CDROM_ALIAS);
5339 break;
5340 case QEMU_OPTION_boot:
5341 boot_devices = optarg;
5342 /* We just do some generic consistency checks */
5344 /* Could easily be extended to 64 devices if needed */
5345 const char *p;
5347 boot_devices_bitmap = 0;
5348 for (p = boot_devices; *p != '\0'; p++) {
5349 /* Allowed boot devices are:
5350 * a b : floppy disk drives
5351 * c ... f : IDE disk drives
5352 * g ... m : machine implementation dependant drives
5353 * n ... p : network devices
5354 * It's up to each machine implementation to check
5355 * if the given boot devices match the actual hardware
5356 * implementation and firmware features.
5358 if (*p < 'a' || *p > 'q') {
5359 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5360 exit(1);
5362 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5363 fprintf(stderr,
5364 "Boot device '%c' was given twice\n",*p);
5365 exit(1);
5367 boot_devices_bitmap |= 1 << (*p - 'a');
5370 break;
5371 case QEMU_OPTION_fda:
5372 case QEMU_OPTION_fdb:
5373 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5374 break;
5375 #ifdef TARGET_I386
5376 case QEMU_OPTION_no_fd_bootchk:
5377 fd_bootchk = 0;
5378 break;
5379 #endif
5380 case QEMU_OPTION_net:
5381 if (nb_net_clients >= MAX_NET_CLIENTS) {
5382 fprintf(stderr, "qemu: too many network clients\n");
5383 exit(1);
5385 net_clients[nb_net_clients] = optarg;
5386 nb_net_clients++;
5387 break;
5388 #ifdef CONFIG_SLIRP
5389 case QEMU_OPTION_tftp:
5390 legacy_tftp_prefix = optarg;
5391 break;
5392 case QEMU_OPTION_bootp:
5393 legacy_bootp_filename = optarg;
5394 break;
5395 #ifndef _WIN32
5396 case QEMU_OPTION_smb:
5397 net_slirp_smb(optarg);
5398 break;
5399 #endif
5400 case QEMU_OPTION_redir:
5401 net_slirp_redir(optarg);
5402 break;
5403 #endif
5404 case QEMU_OPTION_bt:
5405 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5406 fprintf(stderr, "qemu: too many bluetooth options\n");
5407 exit(1);
5409 bt_opts[nb_bt_opts++] = optarg;
5410 break;
5411 #ifdef HAS_AUDIO
5412 case QEMU_OPTION_audio_help:
5413 AUD_help ();
5414 exit (0);
5415 break;
5416 case QEMU_OPTION_soundhw:
5417 select_soundhw (optarg);
5418 break;
5419 #endif
5420 case QEMU_OPTION_h:
5421 help(0);
5422 break;
5423 case QEMU_OPTION_version:
5424 version();
5425 exit(0);
5426 break;
5427 case QEMU_OPTION_m: {
5428 uint64_t value;
5429 char *ptr;
5431 value = strtoul(optarg, &ptr, 10);
5432 switch (*ptr) {
5433 case 0: case 'M': case 'm':
5434 value <<= 20;
5435 break;
5436 case 'G': case 'g':
5437 value <<= 30;
5438 break;
5439 default:
5440 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5441 exit(1);
5444 /* On 32-bit hosts, QEMU is limited by virtual address space */
5445 if (value > (2047 << 20)
5446 #ifndef CONFIG_KQEMU
5447 && HOST_LONG_BITS == 32
5448 #endif
5450 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5451 exit(1);
5453 if (value != (uint64_t)(ram_addr_t)value) {
5454 fprintf(stderr, "qemu: ram size too large\n");
5455 exit(1);
5457 ram_size = value;
5458 break;
5460 case QEMU_OPTION_d:
5462 int mask;
5463 const CPULogItem *item;
5465 mask = cpu_str_to_log_mask(optarg);
5466 if (!mask) {
5467 printf("Log items (comma separated):\n");
5468 for(item = cpu_log_items; item->mask != 0; item++) {
5469 printf("%-10s %s\n", item->name, item->help);
5471 exit(1);
5473 cpu_set_log(mask);
5475 break;
5476 case QEMU_OPTION_s:
5477 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5478 break;
5479 case QEMU_OPTION_gdb:
5480 gdbstub_dev = optarg;
5481 break;
5482 case QEMU_OPTION_L:
5483 data_dir = optarg;
5484 break;
5485 case QEMU_OPTION_bios:
5486 bios_name = optarg;
5487 break;
5488 case QEMU_OPTION_singlestep:
5489 singlestep = 1;
5490 break;
5491 case QEMU_OPTION_S:
5492 autostart = 0;
5493 break;
5494 #ifndef _WIN32
5495 case QEMU_OPTION_k:
5496 keyboard_layout = optarg;
5497 break;
5498 #endif
5499 case QEMU_OPTION_localtime:
5500 rtc_utc = 0;
5501 break;
5502 case QEMU_OPTION_vga:
5503 select_vgahw (optarg);
5504 break;
5505 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5506 case QEMU_OPTION_g:
5508 const char *p;
5509 int w, h, depth;
5510 p = optarg;
5511 w = strtol(p, (char **)&p, 10);
5512 if (w <= 0) {
5513 graphic_error:
5514 fprintf(stderr, "qemu: invalid resolution or depth\n");
5515 exit(1);
5517 if (*p != 'x')
5518 goto graphic_error;
5519 p++;
5520 h = strtol(p, (char **)&p, 10);
5521 if (h <= 0)
5522 goto graphic_error;
5523 if (*p == 'x') {
5524 p++;
5525 depth = strtol(p, (char **)&p, 10);
5526 if (depth != 8 && depth != 15 && depth != 16 &&
5527 depth != 24 && depth != 32)
5528 goto graphic_error;
5529 } else if (*p == '\0') {
5530 depth = graphic_depth;
5531 } else {
5532 goto graphic_error;
5535 graphic_width = w;
5536 graphic_height = h;
5537 graphic_depth = depth;
5539 break;
5540 #endif
5541 case QEMU_OPTION_echr:
5543 char *r;
5544 term_escape_char = strtol(optarg, &r, 0);
5545 if (r == optarg)
5546 printf("Bad argument to echr\n");
5547 break;
5549 case QEMU_OPTION_monitor:
5550 monitor_device = optarg;
5551 break;
5552 case QEMU_OPTION_serial:
5553 if (serial_device_index >= MAX_SERIAL_PORTS) {
5554 fprintf(stderr, "qemu: too many serial ports\n");
5555 exit(1);
5557 serial_devices[serial_device_index] = optarg;
5558 serial_device_index++;
5559 break;
5560 case QEMU_OPTION_watchdog:
5561 i = select_watchdog(optarg);
5562 if (i > 0)
5563 exit (i == 1 ? 1 : 0);
5564 break;
5565 case QEMU_OPTION_watchdog_action:
5566 if (select_watchdog_action(optarg) == -1) {
5567 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5568 exit(1);
5570 break;
5571 case QEMU_OPTION_virtiocon:
5572 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5573 fprintf(stderr, "qemu: too many virtio consoles\n");
5574 exit(1);
5576 virtio_consoles[virtio_console_index] = optarg;
5577 virtio_console_index++;
5578 break;
5579 case QEMU_OPTION_parallel:
5580 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5581 fprintf(stderr, "qemu: too many parallel ports\n");
5582 exit(1);
5584 parallel_devices[parallel_device_index] = optarg;
5585 parallel_device_index++;
5586 break;
5587 case QEMU_OPTION_loadvm:
5588 loadvm = optarg;
5589 break;
5590 case QEMU_OPTION_full_screen:
5591 full_screen = 1;
5592 break;
5593 #ifdef CONFIG_SDL
5594 case QEMU_OPTION_no_frame:
5595 no_frame = 1;
5596 break;
5597 case QEMU_OPTION_alt_grab:
5598 alt_grab = 1;
5599 break;
5600 case QEMU_OPTION_no_quit:
5601 no_quit = 1;
5602 break;
5603 case QEMU_OPTION_sdl:
5604 display_type = DT_SDL;
5605 break;
5606 #endif
5607 case QEMU_OPTION_pidfile:
5608 pid_file = optarg;
5609 break;
5610 #ifdef TARGET_I386
5611 case QEMU_OPTION_win2k_hack:
5612 win2k_install_hack = 1;
5613 break;
5614 case QEMU_OPTION_rtc_td_hack:
5615 rtc_td_hack = 1;
5616 break;
5617 case QEMU_OPTION_acpitable:
5618 if(acpi_table_add(optarg) < 0) {
5619 fprintf(stderr, "Wrong acpi table provided\n");
5620 exit(1);
5622 break;
5623 case QEMU_OPTION_smbios:
5624 if(smbios_entry_add(optarg) < 0) {
5625 fprintf(stderr, "Wrong smbios provided\n");
5626 exit(1);
5628 break;
5629 #endif
5630 #ifdef CONFIG_KQEMU
5631 case QEMU_OPTION_no_kqemu:
5632 kqemu_allowed = 0;
5633 break;
5634 case QEMU_OPTION_kernel_kqemu:
5635 kqemu_allowed = 2;
5636 break;
5637 #endif
5638 #ifdef CONFIG_KVM
5639 case QEMU_OPTION_enable_kvm:
5640 kvm_allowed = 1;
5641 #ifdef CONFIG_KQEMU
5642 kqemu_allowed = 0;
5643 #endif
5644 break;
5645 #endif
5646 #ifdef USE_KVM
5647 case QEMU_OPTION_no_kvm:
5648 kvm_allowed = 0;
5649 break;
5650 case QEMU_OPTION_no_kvm_irqchip: {
5651 kvm_irqchip = 0;
5652 kvm_pit = 0;
5653 break;
5655 case QEMU_OPTION_no_kvm_pit: {
5656 kvm_pit = 0;
5657 break;
5659 case QEMU_OPTION_no_kvm_pit_reinjection: {
5660 kvm_pit_reinject = 0;
5661 break;
5663 case QEMU_OPTION_enable_nesting: {
5664 kvm_nested = 1;
5665 break;
5667 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5668 case QEMU_OPTION_pcidevice:
5669 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5670 fprintf(stderr, "Too many assigned devices\n");
5671 exit(1);
5673 assigned_devices[assigned_devices_index] = optarg;
5674 assigned_devices_index++;
5675 break;
5676 #endif
5677 #endif
5678 case QEMU_OPTION_usb:
5679 usb_enabled = 1;
5680 break;
5681 case QEMU_OPTION_usbdevice:
5682 usb_enabled = 1;
5683 if (usb_devices_index >= MAX_USB_CMDLINE) {
5684 fprintf(stderr, "Too many USB devices\n");
5685 exit(1);
5687 usb_devices[usb_devices_index] = optarg;
5688 usb_devices_index++;
5689 break;
5690 case QEMU_OPTION_smp:
5691 smp_cpus = atoi(optarg);
5692 if (smp_cpus < 1) {
5693 fprintf(stderr, "Invalid number of CPUs\n");
5694 exit(1);
5696 break;
5697 case QEMU_OPTION_vnc:
5698 display_type = DT_VNC;
5699 vnc_display = optarg;
5700 break;
5701 #ifdef TARGET_I386
5702 case QEMU_OPTION_no_acpi:
5703 acpi_enabled = 0;
5704 break;
5705 case QEMU_OPTION_no_hpet:
5706 no_hpet = 1;
5707 break;
5708 case QEMU_OPTION_no_virtio_balloon:
5709 no_virtio_balloon = 1;
5710 break;
5711 #endif
5712 case QEMU_OPTION_no_reboot:
5713 no_reboot = 1;
5714 break;
5715 case QEMU_OPTION_no_shutdown:
5716 no_shutdown = 1;
5717 break;
5718 case QEMU_OPTION_show_cursor:
5719 cursor_hide = 0;
5720 break;
5721 case QEMU_OPTION_uuid:
5722 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5723 fprintf(stderr, "Fail to parse UUID string."
5724 " Wrong format.\n");
5725 exit(1);
5727 break;
5728 #ifndef _WIN32
5729 case QEMU_OPTION_daemonize:
5730 daemonize = 1;
5731 break;
5732 #endif
5733 case QEMU_OPTION_option_rom:
5734 if (nb_option_roms >= MAX_OPTION_ROMS) {
5735 fprintf(stderr, "Too many option ROMs\n");
5736 exit(1);
5738 option_rom[nb_option_roms] = optarg;
5739 nb_option_roms++;
5740 break;
5741 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5742 case QEMU_OPTION_semihosting:
5743 semihosting_enabled = 1;
5744 break;
5745 #endif
5746 case QEMU_OPTION_tdf:
5747 time_drift_fix = 1;
5748 break;
5749 case QEMU_OPTION_kvm_shadow_memory:
5750 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5751 break;
5752 case QEMU_OPTION_mempath:
5753 mem_path = optarg;
5754 break;
5755 #ifdef MAP_POPULATE
5756 case QEMU_OPTION_mem_prealloc:
5757 mem_prealloc = !mem_prealloc;
5758 break;
5759 #endif
5760 case QEMU_OPTION_name:
5761 qemu_name = optarg;
5762 break;
5763 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5764 case QEMU_OPTION_prom_env:
5765 if (nb_prom_envs >= MAX_PROM_ENVS) {
5766 fprintf(stderr, "Too many prom variables\n");
5767 exit(1);
5769 prom_envs[nb_prom_envs] = optarg;
5770 nb_prom_envs++;
5771 break;
5772 #endif
5773 #ifdef TARGET_ARM
5774 case QEMU_OPTION_old_param:
5775 old_param = 1;
5776 break;
5777 #endif
5778 case QEMU_OPTION_clock:
5779 configure_alarms(optarg);
5780 break;
5781 case QEMU_OPTION_startdate:
5783 struct tm tm;
5784 time_t rtc_start_date;
5785 if (!strcmp(optarg, "now")) {
5786 rtc_date_offset = -1;
5787 } else {
5788 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5789 &tm.tm_year,
5790 &tm.tm_mon,
5791 &tm.tm_mday,
5792 &tm.tm_hour,
5793 &tm.tm_min,
5794 &tm.tm_sec) == 6) {
5795 /* OK */
5796 } else if (sscanf(optarg, "%d-%d-%d",
5797 &tm.tm_year,
5798 &tm.tm_mon,
5799 &tm.tm_mday) == 3) {
5800 tm.tm_hour = 0;
5801 tm.tm_min = 0;
5802 tm.tm_sec = 0;
5803 } else {
5804 goto date_fail;
5806 tm.tm_year -= 1900;
5807 tm.tm_mon--;
5808 rtc_start_date = mktimegm(&tm);
5809 if (rtc_start_date == -1) {
5810 date_fail:
5811 fprintf(stderr, "Invalid date format. Valid format are:\n"
5812 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5813 exit(1);
5815 rtc_date_offset = time(NULL) - rtc_start_date;
5818 break;
5819 case QEMU_OPTION_tb_size:
5820 tb_size = strtol(optarg, NULL, 0);
5821 if (tb_size < 0)
5822 tb_size = 0;
5823 break;
5824 case QEMU_OPTION_icount:
5825 use_icount = 1;
5826 if (strcmp(optarg, "auto") == 0) {
5827 icount_time_shift = -1;
5828 } else {
5829 icount_time_shift = strtol(optarg, NULL, 0);
5831 break;
5832 case QEMU_OPTION_incoming:
5833 incoming = optarg;
5834 break;
5835 #ifndef _WIN32
5836 case QEMU_OPTION_chroot:
5837 chroot_dir = optarg;
5838 break;
5839 case QEMU_OPTION_runas:
5840 run_as = optarg;
5841 break;
5842 case QEMU_OPTION_nvram:
5843 nvram = optarg;
5844 break;
5845 #endif
5846 #ifdef CONFIG_XEN
5847 case QEMU_OPTION_xen_domid:
5848 xen_domid = atoi(optarg);
5849 break;
5850 case QEMU_OPTION_xen_create:
5851 xen_mode = XEN_CREATE;
5852 break;
5853 case QEMU_OPTION_xen_attach:
5854 xen_mode = XEN_ATTACH;
5855 break;
5856 #endif
5861 /* If no data_dir is specified then try to find it relative to the
5862 executable path. */
5863 if (!data_dir) {
5864 data_dir = find_datadir(argv[0]);
5866 /* If all else fails use the install patch specified when building. */
5867 if (!data_dir) {
5868 data_dir = CONFIG_QEMU_SHAREDIR;
5871 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5872 if (kvm_allowed && kqemu_allowed) {
5873 fprintf(stderr,
5874 "You can not enable both KVM and kqemu at the same time\n");
5875 exit(1);
5877 #endif
5879 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5880 if (smp_cpus > machine->max_cpus) {
5881 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5882 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5883 machine->max_cpus);
5884 exit(1);
5887 if (display_type == DT_NOGRAPHIC) {
5888 if (serial_device_index == 0)
5889 serial_devices[0] = "stdio";
5890 if (parallel_device_index == 0)
5891 parallel_devices[0] = "null";
5892 if (strncmp(monitor_device, "vc", 2) == 0)
5893 monitor_device = "stdio";
5896 #ifndef _WIN32
5897 if (daemonize) {
5898 pid_t pid;
5900 if (pipe(fds) == -1)
5901 exit(1);
5903 pid = fork();
5904 if (pid > 0) {
5905 uint8_t status;
5906 ssize_t len;
5908 close(fds[1]);
5910 again:
5911 len = read(fds[0], &status, 1);
5912 if (len == -1 && (errno == EINTR))
5913 goto again;
5915 if (len != 1)
5916 exit(1);
5917 else if (status == 1) {
5918 fprintf(stderr, "Could not acquire pidfile\n");
5919 exit(1);
5920 } else
5921 exit(0);
5922 } else if (pid < 0)
5923 exit(1);
5925 setsid();
5927 pid = fork();
5928 if (pid > 0)
5929 exit(0);
5930 else if (pid < 0)
5931 exit(1);
5933 umask(027);
5935 signal(SIGTSTP, SIG_IGN);
5936 signal(SIGTTOU, SIG_IGN);
5937 signal(SIGTTIN, SIG_IGN);
5940 #ifdef USE_KVM
5941 if (kvm_enabled()) {
5942 if (kvm_qemu_init() < 0) {
5943 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5944 #ifdef NO_CPU_EMULATION
5945 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5946 exit(1);
5947 #endif
5948 kvm_allowed = 0;
5951 #endif
5953 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5954 if (daemonize) {
5955 uint8_t status = 1;
5956 write(fds[1], &status, 1);
5957 } else
5958 fprintf(stderr, "Could not acquire pid file\n");
5959 exit(1);
5961 #endif
5963 #ifdef CONFIG_KQEMU
5964 if (smp_cpus > 1)
5965 kqemu_allowed = 0;
5966 #endif
5967 if (qemu_init_main_loop()) {
5968 fprintf(stderr, "qemu_init_main_loop failed\n");
5969 exit(1);
5971 linux_boot = (kernel_filename != NULL);
5973 if (!linux_boot && *kernel_cmdline != '\0') {
5974 fprintf(stderr, "-append only allowed with -kernel option\n");
5975 exit(1);
5978 if (!linux_boot && initrd_filename != NULL) {
5979 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5980 exit(1);
5983 /* boot to floppy or the default cd if no hard disk defined yet */
5984 if (!boot_devices[0]) {
5985 boot_devices = "cad";
5987 setvbuf(stdout, NULL, _IOLBF, 0);
5989 init_timers();
5990 if (init_timer_alarm() < 0) {
5991 fprintf(stderr, "could not initialize alarm timer\n");
5992 exit(1);
5994 if (use_icount && icount_time_shift < 0) {
5995 use_icount = 2;
5996 /* 125MIPS seems a reasonable initial guess at the guest speed.
5997 It will be corrected fairly quickly anyway. */
5998 icount_time_shift = 3;
5999 init_icount_adjust();
6002 #ifdef _WIN32
6003 socket_init();
6004 #endif
6006 /* init network clients */
6007 if (nb_net_clients == 0) {
6008 /* if no clients, we use a default config */
6009 net_clients[nb_net_clients++] = "nic";
6010 #ifdef CONFIG_SLIRP
6011 net_clients[nb_net_clients++] = "user";
6012 #endif
6015 for(i = 0;i < nb_net_clients; i++) {
6016 if (net_client_parse(net_clients[i]) < 0)
6017 exit(1);
6020 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
6021 net_set_boot_mask(net_boot);
6023 net_client_check();
6025 /* init the bluetooth world */
6026 for (i = 0; i < nb_bt_opts; i++)
6027 if (bt_parse(bt_opts[i]))
6028 exit(1);
6030 /* init the memory */
6031 if (ram_size == 0)
6032 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6034 if (kvm_enabled()) {
6035 if (kvm_qemu_create_context() < 0) {
6036 fprintf(stderr, "Could not create KVM context\n");
6037 exit(1);
6041 #ifdef CONFIG_KQEMU
6042 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
6043 guest ram allocation. It needs to go away. */
6044 if (kqemu_allowed) {
6045 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
6046 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
6047 if (!kqemu_phys_ram_base) {
6048 fprintf(stderr, "Could not allocate physical memory\n");
6049 exit(1);
6052 #endif
6054 /* init the dynamic translator */
6055 cpu_exec_init_all(tb_size * 1024 * 1024);
6057 bdrv_init();
6059 /* we always create the cdrom drive, even if no disk is there */
6061 if (nb_drives_opt < MAX_DRIVES)
6062 drive_add(NULL, CDROM_ALIAS);
6064 /* we always create at least one floppy */
6066 if (nb_drives_opt < MAX_DRIVES)
6067 drive_add(NULL, FD_ALIAS, 0);
6069 /* we always create one sd slot, even if no card is in it */
6071 if (nb_drives_opt < MAX_DRIVES)
6072 drive_add(NULL, SD_ALIAS);
6074 /* open the virtual block devices
6075 * note that migration with device
6076 * hot add/remove is broken.
6078 for(i = 0; i < nb_drives_opt; i++)
6079 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
6080 exit(1);
6082 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6083 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
6085 #ifndef _WIN32
6086 /* must be after terminal init, SDL library changes signal handlers */
6087 sighandler_setup();
6088 #endif
6090 /* Maintain compatibility with multiple stdio monitors */
6091 if (!strcmp(monitor_device,"stdio")) {
6092 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
6093 const char *devname = serial_devices[i];
6094 if (devname && !strcmp(devname,"mon:stdio")) {
6095 monitor_device = NULL;
6096 break;
6097 } else if (devname && !strcmp(devname,"stdio")) {
6098 monitor_device = NULL;
6099 serial_devices[i] = "mon:stdio";
6100 break;
6105 if (nb_numa_nodes > 0) {
6106 int i;
6108 if (nb_numa_nodes > smp_cpus) {
6109 nb_numa_nodes = smp_cpus;
6112 /* If no memory size if given for any node, assume the default case
6113 * and distribute the available memory equally across all nodes
6115 for (i = 0; i < nb_numa_nodes; i++) {
6116 if (node_mem[i] != 0)
6117 break;
6119 if (i == nb_numa_nodes) {
6120 uint64_t usedmem = 0;
6122 /* On Linux, the each node's border has to be 8MB aligned,
6123 * the final node gets the rest.
6125 for (i = 0; i < nb_numa_nodes - 1; i++) {
6126 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
6127 usedmem += node_mem[i];
6129 node_mem[i] = ram_size - usedmem;
6132 for (i = 0; i < nb_numa_nodes; i++) {
6133 if (node_cpumask[i] != 0)
6134 break;
6136 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6137 * must cope with this anyway, because there are BIOSes out there in
6138 * real machines which also use this scheme.
6140 if (i == nb_numa_nodes) {
6141 for (i = 0; i < smp_cpus; i++) {
6142 node_cpumask[i % nb_numa_nodes] |= 1 << i;
6147 #ifdef KVM_UPSTREAM
6148 if (kvm_enabled()) {
6149 int ret;
6151 ret = kvm_init(smp_cpus);
6152 if (ret < 0) {
6153 fprintf(stderr, "failed to initialize KVM\n");
6154 exit(1);
6157 #endif
6159 if (monitor_device) {
6160 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
6161 if (!monitor_hd) {
6162 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6163 exit(1);
6167 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6168 const char *devname = serial_devices[i];
6169 if (devname && strcmp(devname, "none")) {
6170 char label[32];
6171 snprintf(label, sizeof(label), "serial%d", i);
6172 serial_hds[i] = qemu_chr_open(label, devname, NULL);
6173 if (!serial_hds[i]) {
6174 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6175 devname);
6176 exit(1);
6181 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6182 const char *devname = parallel_devices[i];
6183 if (devname && strcmp(devname, "none")) {
6184 char label[32];
6185 snprintf(label, sizeof(label), "parallel%d", i);
6186 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
6187 if (!parallel_hds[i]) {
6188 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6189 devname);
6190 exit(1);
6195 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6196 const char *devname = virtio_consoles[i];
6197 if (devname && strcmp(devname, "none")) {
6198 char label[32];
6199 snprintf(label, sizeof(label), "virtcon%d", i);
6200 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
6201 if (!virtcon_hds[i]) {
6202 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
6203 devname);
6204 exit(1);
6209 module_call_init(MODULE_INIT_DEVICE);
6211 if (kvm_enabled())
6212 kvm_init_ap();
6214 machine->init(ram_size, boot_devices,
6215 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6218 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6219 for (i = 0; i < nb_numa_nodes; i++) {
6220 if (node_cpumask[i] & (1 << env->cpu_index)) {
6221 env->numa_node = i;
6226 current_machine = machine;
6228 /* Set KVM's vcpu state to qemu's initial CPUState. */
6229 if (kvm_enabled()) {
6230 int ret;
6232 ret = kvm_sync_vcpus();
6233 if (ret < 0) {
6234 fprintf(stderr, "failed to initialize vcpus\n");
6235 exit(1);
6239 /* init USB devices */
6240 if (usb_enabled) {
6241 for(i = 0; i < usb_devices_index; i++) {
6242 if (usb_device_add(usb_devices[i], 0) < 0) {
6243 fprintf(stderr, "Warning: could not add USB device %s\n",
6244 usb_devices[i]);
6249 if (!display_state)
6250 dumb_display_init();
6251 /* just use the first displaystate for the moment */
6252 ds = display_state;
6254 if (display_type == DT_DEFAULT) {
6255 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6256 display_type = DT_SDL;
6257 #else
6258 display_type = DT_VNC;
6259 vnc_display = "localhost:0,to=99";
6260 show_vnc_port = 1;
6261 #endif
6265 switch (display_type) {
6266 case DT_NOGRAPHIC:
6267 break;
6268 #if defined(CONFIG_CURSES)
6269 case DT_CURSES:
6270 curses_display_init(ds, full_screen);
6271 break;
6272 #endif
6273 #if defined(CONFIG_SDL)
6274 case DT_SDL:
6275 sdl_display_init(ds, full_screen, no_frame);
6276 break;
6277 #elif defined(CONFIG_COCOA)
6278 case DT_SDL:
6279 cocoa_display_init(ds, full_screen);
6280 break;
6281 #endif
6282 case DT_VNC:
6283 vnc_display_init(ds);
6284 if (vnc_display_open(ds, vnc_display) < 0)
6285 exit(1);
6287 if (show_vnc_port) {
6288 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6290 break;
6291 default:
6292 break;
6294 dpy_resize(ds);
6296 dcl = ds->listeners;
6297 while (dcl != NULL) {
6298 if (dcl->dpy_refresh != NULL) {
6299 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6300 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6302 dcl = dcl->next;
6305 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6306 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6307 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6310 text_consoles_set_display(display_state);
6311 qemu_chr_initial_reset();
6313 if (monitor_device && monitor_hd)
6314 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6316 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6317 const char *devname = serial_devices[i];
6318 if (devname && strcmp(devname, "none")) {
6319 if (strstart(devname, "vc", 0))
6320 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6324 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6325 const char *devname = parallel_devices[i];
6326 if (devname && strcmp(devname, "none")) {
6327 if (strstart(devname, "vc", 0))
6328 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6332 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6333 const char *devname = virtio_consoles[i];
6334 if (virtcon_hds[i] && devname) {
6335 if (strstart(devname, "vc", 0))
6336 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6340 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6341 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6342 gdbstub_dev);
6343 exit(1);
6346 if (loadvm)
6347 do_loadvm(cur_mon, loadvm);
6349 if (incoming) {
6350 autostart = 0; /* fixme how to deal with -daemonize */
6351 qemu_start_incoming_migration(incoming);
6354 if (autostart)
6355 vm_start();
6357 #ifndef _WIN32
6358 if (daemonize) {
6359 uint8_t status = 0;
6360 ssize_t len;
6362 again1:
6363 len = write(fds[1], &status, 1);
6364 if (len == -1 && (errno == EINTR))
6365 goto again1;
6367 if (len != 1)
6368 exit(1);
6370 chdir("/");
6371 TFR(fd = open("/dev/null", O_RDWR));
6372 if (fd == -1)
6373 exit(1);
6376 if (run_as) {
6377 pwd = getpwnam(run_as);
6378 if (!pwd) {
6379 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6380 exit(1);
6384 if (chroot_dir) {
6385 if (chroot(chroot_dir) < 0) {
6386 fprintf(stderr, "chroot failed\n");
6387 exit(1);
6389 chdir("/");
6392 if (run_as) {
6393 if (setgid(pwd->pw_gid) < 0) {
6394 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6395 exit(1);
6397 if (setuid(pwd->pw_uid) < 0) {
6398 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6399 exit(1);
6401 if (setuid(0) != -1) {
6402 fprintf(stderr, "Dropping privileges failed\n");
6403 exit(1);
6407 if (daemonize) {
6408 dup2(fd, 0);
6409 dup2(fd, 1);
6410 dup2(fd, 2);
6412 close(fd);
6414 #endif
6416 main_loop();
6417 quit_timers();
6418 net_cleanup();
6420 return 0;