device assignment: Add PCI option ROM support
[qemu-kvm/amd-iommu.git] / vl.c
blob72789997fb5718aabeb95daa46715fa6501e001e
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 #ifdef __APPLE__
117 #include <SDL.h>
118 int qemu_main(int argc, char **argv, char **envp);
119 int main(int argc, char **argv)
121 qemu_main(argc, argv, NULL);
123 #undef main
124 #define main qemu_main
125 #endif
126 #endif /* CONFIG_SDL */
128 #ifdef CONFIG_COCOA
129 #undef main
130 #define main qemu_main
131 #endif /* CONFIG_COCOA */
133 #include "hw/hw.h"
134 #include "hw/boards.h"
135 #include "hw/usb.h"
136 #include "hw/pcmcia.h"
137 #include "hw/pc.h"
138 #include "hw/audiodev.h"
139 #include "hw/isa.h"
140 #include "hw/baum.h"
141 #include "hw/bt.h"
142 #include "hw/watchdog.h"
143 #include "hw/smbios.h"
144 #include "hw/xen.h"
145 #include "bt-host.h"
146 #include "net.h"
147 #include "monitor.h"
148 #include "console.h"
149 #include "sysemu.h"
150 #include "gdbstub.h"
151 #include "qemu-timer.h"
152 #include "qemu-char.h"
153 #include "cache-utils.h"
154 #include "block.h"
155 #include "dma.h"
156 #include "audio/audio.h"
157 #include "migration.h"
158 #include "kvm.h"
159 #include "balloon.h"
160 #include "qemu-option.h"
161 #include "qemu-kvm.h"
162 #include "hw/device-assignment.h"
164 #include "disas.h"
166 #include "exec-all.h"
168 #include "qemu_socket.h"
170 #if defined(CONFIG_SLIRP)
171 #include "libslirp.h"
172 #endif
174 //#define DEBUG_UNUSED_IOPORT
175 //#define DEBUG_IOPORT
176 //#define DEBUG_NET
177 //#define DEBUG_SLIRP
180 #ifdef DEBUG_IOPORT
181 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
182 #else
183 # define LOG_IOPORT(...) do { } while (0)
184 #endif
186 #define DEFAULT_RAM_SIZE 128
188 /* Max number of USB devices that can be specified on the commandline. */
189 #define MAX_USB_CMDLINE 8
191 /* Max number of bluetooth switches on the commandline. */
192 #define MAX_BT_CMDLINE 10
194 /* XXX: use a two level table to limit memory usage */
195 #define MAX_IOPORTS 65536
197 static const char *data_dir;
198 const char *bios_name = NULL;
199 static void *ioport_opaque[MAX_IOPORTS];
200 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
201 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
202 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
203 to store the VM snapshots */
204 DriveInfo drives_table[MAX_DRIVES+1];
205 int nb_drives;
206 int extboot_drive = -1;
207 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
208 static DisplayState *display_state;
209 DisplayType display_type = DT_DEFAULT;
210 const char* keyboard_layout = NULL;
211 int64_t ticks_per_sec;
212 ram_addr_t ram_size;
213 int nb_nics;
214 NICInfo nd_table[MAX_NICS];
215 int vm_running;
216 static int autostart;
217 static int rtc_utc = 1;
218 static int rtc_date_offset = -1; /* -1 means no change */
219 int cirrus_vga_enabled = 1;
220 int std_vga_enabled = 0;
221 int vmsvga_enabled = 0;
222 int xenfb_enabled = 0;
223 #ifdef TARGET_SPARC
224 int graphic_width = 1024;
225 int graphic_height = 768;
226 int graphic_depth = 8;
227 #else
228 int graphic_width = 800;
229 int graphic_height = 600;
230 int graphic_depth = 15;
231 #endif
232 static int full_screen = 0;
233 #ifdef CONFIG_SDL
234 static int no_frame = 0;
235 #endif
236 int no_quit = 0;
237 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
238 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
239 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
240 #ifdef TARGET_I386
241 int win2k_install_hack = 0;
242 int rtc_td_hack = 0;
243 #endif
244 int usb_enabled = 0;
245 int singlestep = 0;
246 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
247 int assigned_devices_index;
248 int smp_cpus = 1;
249 const char *vnc_display;
250 int acpi_enabled = 1;
251 int no_hpet = 0;
252 int no_virtio_balloon = 0;
253 int fd_bootchk = 1;
254 int no_reboot = 0;
255 int no_shutdown = 0;
256 int cursor_hide = 1;
257 int graphic_rotate = 0;
258 #ifndef _WIN32
259 int daemonize = 0;
260 #endif
261 WatchdogTimerModel *watchdog = NULL;
262 int watchdog_action = WDT_RESET;
263 const char *option_rom[MAX_OPTION_ROMS];
264 int nb_option_roms;
265 int semihosting_enabled = 0;
266 int time_drift_fix = 0;
267 unsigned int kvm_shadow_memory = 0;
268 const char *mem_path = NULL;
269 #ifdef MAP_POPULATE
270 int mem_prealloc = 1; /* force preallocation of physical target memory */
271 #endif
272 #ifdef TARGET_ARM
273 int old_param = 0;
274 #endif
275 const char *qemu_name;
276 int alt_grab = 0;
277 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
278 unsigned int nb_prom_envs = 0;
279 const char *prom_envs[MAX_PROM_ENVS];
280 #endif
281 int nb_drives_opt;
282 const char *nvram = NULL;
283 struct drive_opt drives_opt[MAX_DRIVES];
285 int nb_numa_nodes;
286 uint64_t node_mem[MAX_NODES];
287 uint64_t node_cpumask[MAX_NODES];
289 static CPUState *cur_cpu;
290 static CPUState *next_cpu;
291 static int timer_alarm_pending = 1;
292 /* Conversion factor from emulated instructions to virtual clock ticks. */
293 static int icount_time_shift;
294 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
295 #define MAX_ICOUNT_SHIFT 10
296 /* Compensate for varying guest execution speed. */
297 static int64_t qemu_icount_bias;
298 static QEMUTimer *icount_rt_timer;
299 static QEMUTimer *icount_vm_timer;
300 static QEMUTimer *nographic_timer;
302 uint8_t qemu_uuid[16];
304 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
305 struct timeval *tv)
307 int ret;
309 /* KVM holds a mutex while QEMU code is running, we need hooks to
310 release the mutex whenever QEMU code sleeps. */
312 kvm_sleep_begin();
314 ret = select(max_fd, rfds, wfds, xfds, tv);
316 kvm_sleep_end();
318 return ret;
322 /***********************************************************/
323 /* x86 ISA bus support */
325 target_phys_addr_t isa_mem_base = 0;
326 PicState2 *isa_pic;
328 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
329 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
331 static uint32_t ioport_read(int index, uint32_t address)
333 static IOPortReadFunc *default_func[3] = {
334 default_ioport_readb,
335 default_ioport_readw,
336 default_ioport_readl
338 IOPortReadFunc *func = ioport_read_table[index][address];
339 if (!func)
340 func = default_func[index];
341 return func(ioport_opaque[address], address);
344 static void ioport_write(int index, uint32_t address, uint32_t data)
346 static IOPortWriteFunc *default_func[3] = {
347 default_ioport_writeb,
348 default_ioport_writew,
349 default_ioport_writel
351 IOPortWriteFunc *func = ioport_write_table[index][address];
352 if (!func)
353 func = default_func[index];
354 func(ioport_opaque[address], address, data);
357 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
359 #ifdef DEBUG_UNUSED_IOPORT
360 fprintf(stderr, "unused inb: port=0x%04x\n", address);
361 #endif
362 return 0xff;
365 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
367 #ifdef DEBUG_UNUSED_IOPORT
368 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
369 #endif
372 /* default is to make two byte accesses */
373 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
375 uint32_t data;
376 data = ioport_read(0, address);
377 address = (address + 1) & (MAX_IOPORTS - 1);
378 data |= ioport_read(0, address) << 8;
379 return data;
382 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
384 ioport_write(0, address, data & 0xff);
385 address = (address + 1) & (MAX_IOPORTS - 1);
386 ioport_write(0, address, (data >> 8) & 0xff);
389 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
391 #ifdef DEBUG_UNUSED_IOPORT
392 fprintf(stderr, "unused inl: port=0x%04x\n", address);
393 #endif
394 return 0xffffffff;
397 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
399 #ifdef DEBUG_UNUSED_IOPORT
400 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
401 #endif
404 /* size is the word size in byte */
405 int register_ioport_read(int start, int length, int size,
406 IOPortReadFunc *func, void *opaque)
408 int i, bsize;
410 if (size == 1) {
411 bsize = 0;
412 } else if (size == 2) {
413 bsize = 1;
414 } else if (size == 4) {
415 bsize = 2;
416 } else {
417 hw_error("register_ioport_read: invalid size");
418 return -1;
420 for(i = start; i < start + length; i += size) {
421 ioport_read_table[bsize][i] = func;
422 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
423 hw_error("register_ioport_read: invalid opaque");
424 ioport_opaque[i] = opaque;
426 return 0;
429 /* size is the word size in byte */
430 int register_ioport_write(int start, int length, int size,
431 IOPortWriteFunc *func, void *opaque)
433 int i, bsize;
435 if (size == 1) {
436 bsize = 0;
437 } else if (size == 2) {
438 bsize = 1;
439 } else if (size == 4) {
440 bsize = 2;
441 } else {
442 hw_error("register_ioport_write: invalid size");
443 return -1;
445 for(i = start; i < start + length; i += size) {
446 ioport_write_table[bsize][i] = func;
447 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
448 hw_error("register_ioport_write: invalid opaque");
449 ioport_opaque[i] = opaque;
451 return 0;
454 void isa_unassign_ioport(int start, int length)
456 int i;
458 for(i = start; i < start + length; i++) {
459 ioport_read_table[0][i] = default_ioport_readb;
460 ioport_read_table[1][i] = default_ioport_readw;
461 ioport_read_table[2][i] = default_ioport_readl;
463 ioport_write_table[0][i] = default_ioport_writeb;
464 ioport_write_table[1][i] = default_ioport_writew;
465 ioport_write_table[2][i] = default_ioport_writel;
467 ioport_opaque[i] = NULL;
471 /***********************************************************/
473 void cpu_outb(CPUState *env, int addr, int val)
475 LOG_IOPORT("outb: %04x %02x\n", addr, val);
476 ioport_write(0, addr, val);
477 #ifdef CONFIG_KQEMU
478 if (env)
479 env->last_io_time = cpu_get_time_fast();
480 #endif
483 void cpu_outw(CPUState *env, int addr, int val)
485 LOG_IOPORT("outw: %04x %04x\n", addr, val);
486 ioport_write(1, addr, val);
487 #ifdef CONFIG_KQEMU
488 if (env)
489 env->last_io_time = cpu_get_time_fast();
490 #endif
493 void cpu_outl(CPUState *env, int addr, int val)
495 LOG_IOPORT("outl: %04x %08x\n", addr, val);
496 ioport_write(2, addr, val);
497 #ifdef CONFIG_KQEMU
498 if (env)
499 env->last_io_time = cpu_get_time_fast();
500 #endif
503 int cpu_inb(CPUState *env, int addr)
505 int val;
506 val = ioport_read(0, addr);
507 LOG_IOPORT("inb : %04x %02x\n", addr, val);
508 #ifdef CONFIG_KQEMU
509 if (env)
510 env->last_io_time = cpu_get_time_fast();
511 #endif
512 return val;
515 int cpu_inw(CPUState *env, int addr)
517 int val;
518 val = ioport_read(1, addr);
519 LOG_IOPORT("inw : %04x %04x\n", addr, val);
520 #ifdef CONFIG_KQEMU
521 if (env)
522 env->last_io_time = cpu_get_time_fast();
523 #endif
524 return val;
527 int cpu_inl(CPUState *env, int addr)
529 int val;
530 val = ioport_read(2, addr);
531 LOG_IOPORT("inl : %04x %08x\n", addr, val);
532 #ifdef CONFIG_KQEMU
533 if (env)
534 env->last_io_time = cpu_get_time_fast();
535 #endif
536 return val;
539 /***********************************************************/
540 void hw_error(const char *fmt, ...)
542 va_list ap;
543 CPUState *env;
545 va_start(ap, fmt);
546 fprintf(stderr, "qemu: hardware error: ");
547 vfprintf(stderr, fmt, ap);
548 fprintf(stderr, "\n");
549 for(env = first_cpu; env != NULL; env = env->next_cpu) {
550 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
551 #ifdef TARGET_I386
552 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
553 #else
554 cpu_dump_state(env, stderr, fprintf, 0);
555 #endif
557 va_end(ap);
558 abort();
561 /***************/
562 /* ballooning */
564 static QEMUBalloonEvent *qemu_balloon_event;
565 void *qemu_balloon_event_opaque;
567 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
569 qemu_balloon_event = func;
570 qemu_balloon_event_opaque = opaque;
573 void qemu_balloon(ram_addr_t target)
575 if (qemu_balloon_event)
576 qemu_balloon_event(qemu_balloon_event_opaque, target);
579 ram_addr_t qemu_balloon_status(void)
581 if (qemu_balloon_event)
582 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
583 return 0;
586 /***********************************************************/
587 /* keyboard/mouse */
589 static QEMUPutKBDEvent *qemu_put_kbd_event;
590 static void *qemu_put_kbd_event_opaque;
591 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
592 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
594 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
596 qemu_put_kbd_event_opaque = opaque;
597 qemu_put_kbd_event = func;
600 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
601 void *opaque, int absolute,
602 const char *name)
604 QEMUPutMouseEntry *s, *cursor;
606 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
608 s->qemu_put_mouse_event = func;
609 s->qemu_put_mouse_event_opaque = opaque;
610 s->qemu_put_mouse_event_absolute = absolute;
611 s->qemu_put_mouse_event_name = qemu_strdup(name);
612 s->next = NULL;
614 if (!qemu_put_mouse_event_head) {
615 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
616 return s;
619 cursor = qemu_put_mouse_event_head;
620 while (cursor->next != NULL)
621 cursor = cursor->next;
623 cursor->next = s;
624 qemu_put_mouse_event_current = s;
626 return s;
629 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
631 QEMUPutMouseEntry *prev = NULL, *cursor;
633 if (!qemu_put_mouse_event_head || entry == NULL)
634 return;
636 cursor = qemu_put_mouse_event_head;
637 while (cursor != NULL && cursor != entry) {
638 prev = cursor;
639 cursor = cursor->next;
642 if (cursor == NULL) // does not exist or list empty
643 return;
644 else if (prev == NULL) { // entry is head
645 qemu_put_mouse_event_head = cursor->next;
646 if (qemu_put_mouse_event_current == entry)
647 qemu_put_mouse_event_current = cursor->next;
648 qemu_free(entry->qemu_put_mouse_event_name);
649 qemu_free(entry);
650 return;
653 prev->next = entry->next;
655 if (qemu_put_mouse_event_current == entry)
656 qemu_put_mouse_event_current = prev;
658 qemu_free(entry->qemu_put_mouse_event_name);
659 qemu_free(entry);
662 void kbd_put_keycode(int keycode)
664 if (qemu_put_kbd_event) {
665 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
669 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
671 QEMUPutMouseEvent *mouse_event;
672 void *mouse_event_opaque;
673 int width;
675 if (!qemu_put_mouse_event_current) {
676 return;
679 mouse_event =
680 qemu_put_mouse_event_current->qemu_put_mouse_event;
681 mouse_event_opaque =
682 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
684 if (mouse_event) {
685 if (graphic_rotate) {
686 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
687 width = 0x7fff;
688 else
689 width = graphic_width - 1;
690 mouse_event(mouse_event_opaque,
691 width - dy, dx, dz, buttons_state);
692 } else
693 mouse_event(mouse_event_opaque,
694 dx, dy, dz, buttons_state);
698 int kbd_mouse_is_absolute(void)
700 if (!qemu_put_mouse_event_current)
701 return 0;
703 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
706 void do_info_mice(Monitor *mon)
708 QEMUPutMouseEntry *cursor;
709 int index = 0;
711 if (!qemu_put_mouse_event_head) {
712 monitor_printf(mon, "No mouse devices connected\n");
713 return;
716 monitor_printf(mon, "Mouse devices available:\n");
717 cursor = qemu_put_mouse_event_head;
718 while (cursor != NULL) {
719 monitor_printf(mon, "%c Mouse #%d: %s\n",
720 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
721 index, cursor->qemu_put_mouse_event_name);
722 index++;
723 cursor = cursor->next;
727 void do_mouse_set(Monitor *mon, int index)
729 QEMUPutMouseEntry *cursor;
730 int i = 0;
732 if (!qemu_put_mouse_event_head) {
733 monitor_printf(mon, "No mouse devices connected\n");
734 return;
737 cursor = qemu_put_mouse_event_head;
738 while (cursor != NULL && index != i) {
739 i++;
740 cursor = cursor->next;
743 if (cursor != NULL)
744 qemu_put_mouse_event_current = cursor;
745 else
746 monitor_printf(mon, "Mouse at given index not found\n");
749 /* compute with 96 bit intermediate result: (a*b)/c */
750 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
752 union {
753 uint64_t ll;
754 struct {
755 #ifdef WORDS_BIGENDIAN
756 uint32_t high, low;
757 #else
758 uint32_t low, high;
759 #endif
760 } l;
761 } u, res;
762 uint64_t rl, rh;
764 u.ll = a;
765 rl = (uint64_t)u.l.low * (uint64_t)b;
766 rh = (uint64_t)u.l.high * (uint64_t)b;
767 rh += (rl >> 32);
768 res.l.high = rh / c;
769 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
770 return res.ll;
773 /***********************************************************/
774 /* real time host monotonic timer */
776 #define QEMU_TIMER_BASE 1000000000LL
778 #ifdef WIN32
780 static int64_t clock_freq;
782 static void init_get_clock(void)
784 LARGE_INTEGER freq;
785 int ret;
786 ret = QueryPerformanceFrequency(&freq);
787 if (ret == 0) {
788 fprintf(stderr, "Could not calibrate ticks\n");
789 exit(1);
791 clock_freq = freq.QuadPart;
794 static int64_t get_clock(void)
796 LARGE_INTEGER ti;
797 QueryPerformanceCounter(&ti);
798 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
801 #else
803 static int use_rt_clock;
805 static void init_get_clock(void)
807 use_rt_clock = 0;
808 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
809 || defined(__DragonFly__)
811 struct timespec ts;
812 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
813 use_rt_clock = 1;
816 #endif
819 static int64_t get_clock(void)
821 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
822 || defined(__DragonFly__)
823 if (use_rt_clock) {
824 struct timespec ts;
825 clock_gettime(CLOCK_MONOTONIC, &ts);
826 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
827 } else
828 #endif
830 /* XXX: using gettimeofday leads to problems if the date
831 changes, so it should be avoided. */
832 struct timeval tv;
833 gettimeofday(&tv, NULL);
834 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
837 #endif
839 /* Return the virtual CPU time, based on the instruction counter. */
840 static int64_t cpu_get_icount(void)
842 int64_t icount;
843 CPUState *env = cpu_single_env;;
844 icount = qemu_icount;
845 if (env) {
846 if (!can_do_io(env))
847 fprintf(stderr, "Bad clock read\n");
848 icount -= (env->icount_decr.u16.low + env->icount_extra);
850 return qemu_icount_bias + (icount << icount_time_shift);
853 /***********************************************************/
854 /* guest cycle counter */
856 static int64_t cpu_ticks_prev;
857 static int64_t cpu_ticks_offset;
858 static int64_t cpu_clock_offset;
859 static int cpu_ticks_enabled;
861 /* return the host CPU cycle counter and handle stop/restart */
862 int64_t cpu_get_ticks(void)
864 if (use_icount) {
865 return cpu_get_icount();
867 if (!cpu_ticks_enabled) {
868 return cpu_ticks_offset;
869 } else {
870 int64_t ticks;
871 ticks = cpu_get_real_ticks();
872 if (cpu_ticks_prev > ticks) {
873 /* Note: non increasing ticks may happen if the host uses
874 software suspend */
875 cpu_ticks_offset += cpu_ticks_prev - ticks;
877 cpu_ticks_prev = ticks;
878 return ticks + cpu_ticks_offset;
882 /* return the host CPU monotonic timer and handle stop/restart */
883 static int64_t cpu_get_clock(void)
885 int64_t ti;
886 if (!cpu_ticks_enabled) {
887 return cpu_clock_offset;
888 } else {
889 ti = get_clock();
890 return ti + cpu_clock_offset;
894 /* enable cpu_get_ticks() */
895 void cpu_enable_ticks(void)
897 if (!cpu_ticks_enabled) {
898 cpu_ticks_offset -= cpu_get_real_ticks();
899 cpu_clock_offset -= get_clock();
900 cpu_ticks_enabled = 1;
904 /* disable cpu_get_ticks() : the clock is stopped. You must not call
905 cpu_get_ticks() after that. */
906 void cpu_disable_ticks(void)
908 if (cpu_ticks_enabled) {
909 cpu_ticks_offset = cpu_get_ticks();
910 cpu_clock_offset = cpu_get_clock();
911 cpu_ticks_enabled = 0;
915 /***********************************************************/
916 /* timers */
918 #define QEMU_TIMER_REALTIME 0
919 #define QEMU_TIMER_VIRTUAL 1
921 struct QEMUClock {
922 int type;
923 /* XXX: add frequency */
926 struct QEMUTimer {
927 QEMUClock *clock;
928 int64_t expire_time;
929 QEMUTimerCB *cb;
930 void *opaque;
931 struct QEMUTimer *next;
934 struct qemu_alarm_timer {
935 char const *name;
936 unsigned int flags;
938 int (*start)(struct qemu_alarm_timer *t);
939 void (*stop)(struct qemu_alarm_timer *t);
940 void (*rearm)(struct qemu_alarm_timer *t);
941 void *priv;
944 #define ALARM_FLAG_DYNTICKS 0x1
945 #define ALARM_FLAG_EXPIRED 0x2
947 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
949 return t && (t->flags & ALARM_FLAG_DYNTICKS);
952 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
954 if (!alarm_has_dynticks(t))
955 return;
957 t->rearm(t);
960 /* TODO: MIN_TIMER_REARM_US should be optimized */
961 #define MIN_TIMER_REARM_US 250
963 static struct qemu_alarm_timer *alarm_timer;
965 #ifdef _WIN32
967 struct qemu_alarm_win32 {
968 MMRESULT timerId;
969 unsigned int period;
970 } alarm_win32_data = {0, -1};
972 static int win32_start_timer(struct qemu_alarm_timer *t);
973 static void win32_stop_timer(struct qemu_alarm_timer *t);
974 static void win32_rearm_timer(struct qemu_alarm_timer *t);
976 #else
978 static int unix_start_timer(struct qemu_alarm_timer *t);
979 static void unix_stop_timer(struct qemu_alarm_timer *t);
981 #ifdef __linux__
983 static int dynticks_start_timer(struct qemu_alarm_timer *t);
984 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
985 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
987 static int hpet_start_timer(struct qemu_alarm_timer *t);
988 static void hpet_stop_timer(struct qemu_alarm_timer *t);
990 static int rtc_start_timer(struct qemu_alarm_timer *t);
991 static void rtc_stop_timer(struct qemu_alarm_timer *t);
993 #endif /* __linux__ */
995 #endif /* _WIN32 */
997 /* Correlation between real and virtual time is always going to be
998 fairly approximate, so ignore small variation.
999 When the guest is idle real and virtual time will be aligned in
1000 the IO wait loop. */
1001 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
1003 static void icount_adjust(void)
1005 int64_t cur_time;
1006 int64_t cur_icount;
1007 int64_t delta;
1008 static int64_t last_delta;
1009 /* If the VM is not running, then do nothing. */
1010 if (!vm_running)
1011 return;
1013 cur_time = cpu_get_clock();
1014 cur_icount = qemu_get_clock(vm_clock);
1015 delta = cur_icount - cur_time;
1016 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1017 if (delta > 0
1018 && last_delta + ICOUNT_WOBBLE < delta * 2
1019 && icount_time_shift > 0) {
1020 /* The guest is getting too far ahead. Slow time down. */
1021 icount_time_shift--;
1023 if (delta < 0
1024 && last_delta - ICOUNT_WOBBLE > delta * 2
1025 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1026 /* The guest is getting too far behind. Speed time up. */
1027 icount_time_shift++;
1029 last_delta = delta;
1030 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1033 static void icount_adjust_rt(void * opaque)
1035 qemu_mod_timer(icount_rt_timer,
1036 qemu_get_clock(rt_clock) + 1000);
1037 icount_adjust();
1040 static void icount_adjust_vm(void * opaque)
1042 qemu_mod_timer(icount_vm_timer,
1043 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1044 icount_adjust();
1047 static void init_icount_adjust(void)
1049 /* Have both realtime and virtual time triggers for speed adjustment.
1050 The realtime trigger catches emulated time passing too slowly,
1051 the virtual time trigger catches emulated time passing too fast.
1052 Realtime triggers occur even when idle, so use them less frequently
1053 than VM triggers. */
1054 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1055 qemu_mod_timer(icount_rt_timer,
1056 qemu_get_clock(rt_clock) + 1000);
1057 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1058 qemu_mod_timer(icount_vm_timer,
1059 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1062 static struct qemu_alarm_timer alarm_timers[] = {
1063 #ifndef _WIN32
1064 #ifdef __linux__
1065 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1066 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1067 /* HPET - if available - is preferred */
1068 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1069 /* ...otherwise try RTC */
1070 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1071 #endif
1072 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1073 #else
1074 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1075 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1076 {"win32", 0, win32_start_timer,
1077 win32_stop_timer, NULL, &alarm_win32_data},
1078 #endif
1079 {NULL, }
1082 static void show_available_alarms(void)
1084 int i;
1086 printf("Available alarm timers, in order of precedence:\n");
1087 for (i = 0; alarm_timers[i].name; i++)
1088 printf("%s\n", alarm_timers[i].name);
1091 static void configure_alarms(char const *opt)
1093 int i;
1094 int cur = 0;
1095 int count = ARRAY_SIZE(alarm_timers) - 1;
1096 char *arg;
1097 char *name;
1098 struct qemu_alarm_timer tmp;
1100 if (!strcmp(opt, "?")) {
1101 show_available_alarms();
1102 exit(0);
1105 arg = strdup(opt);
1107 /* Reorder the array */
1108 name = strtok(arg, ",");
1109 while (name) {
1110 for (i = 0; i < count && alarm_timers[i].name; i++) {
1111 if (!strcmp(alarm_timers[i].name, name))
1112 break;
1115 if (i == count) {
1116 fprintf(stderr, "Unknown clock %s\n", name);
1117 goto next;
1120 if (i < cur)
1121 /* Ignore */
1122 goto next;
1124 /* Swap */
1125 tmp = alarm_timers[i];
1126 alarm_timers[i] = alarm_timers[cur];
1127 alarm_timers[cur] = tmp;
1129 cur++;
1130 next:
1131 name = strtok(NULL, ",");
1134 free(arg);
1136 if (cur) {
1137 /* Disable remaining timers */
1138 for (i = cur; i < count; i++)
1139 alarm_timers[i].name = NULL;
1140 } else {
1141 show_available_alarms();
1142 exit(1);
1146 QEMUClock *rt_clock;
1147 QEMUClock *vm_clock;
1149 static QEMUTimer *active_timers[2];
1151 static QEMUClock *qemu_new_clock(int type)
1153 QEMUClock *clock;
1154 clock = qemu_mallocz(sizeof(QEMUClock));
1155 clock->type = type;
1156 return clock;
1159 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1161 QEMUTimer *ts;
1163 ts = qemu_mallocz(sizeof(QEMUTimer));
1164 ts->clock = clock;
1165 ts->cb = cb;
1166 ts->opaque = opaque;
1167 return ts;
1170 void qemu_free_timer(QEMUTimer *ts)
1172 qemu_free(ts);
1175 /* stop a timer, but do not dealloc it */
1176 void qemu_del_timer(QEMUTimer *ts)
1178 QEMUTimer **pt, *t;
1180 /* NOTE: this code must be signal safe because
1181 qemu_timer_expired() can be called from a signal. */
1182 pt = &active_timers[ts->clock->type];
1183 for(;;) {
1184 t = *pt;
1185 if (!t)
1186 break;
1187 if (t == ts) {
1188 *pt = t->next;
1189 break;
1191 pt = &t->next;
1195 /* modify the current timer so that it will be fired when current_time
1196 >= expire_time. The corresponding callback will be called. */
1197 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1199 QEMUTimer **pt, *t;
1201 qemu_del_timer(ts);
1203 /* add the timer in the sorted list */
1204 /* NOTE: this code must be signal safe because
1205 qemu_timer_expired() can be called from a signal. */
1206 pt = &active_timers[ts->clock->type];
1207 for(;;) {
1208 t = *pt;
1209 if (!t)
1210 break;
1211 if (t->expire_time > expire_time)
1212 break;
1213 pt = &t->next;
1215 ts->expire_time = expire_time;
1216 ts->next = *pt;
1217 *pt = ts;
1219 /* Rearm if necessary */
1220 if (pt == &active_timers[ts->clock->type]) {
1221 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1222 qemu_rearm_alarm_timer(alarm_timer);
1224 /* Interrupt execution to force deadline recalculation. */
1225 if (use_icount)
1226 qemu_notify_event();
1230 int qemu_timer_pending(QEMUTimer *ts)
1232 QEMUTimer *t;
1233 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1234 if (t == ts)
1235 return 1;
1237 return 0;
1240 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1242 if (!timer_head)
1243 return 0;
1244 return (timer_head->expire_time <= current_time);
1247 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1249 QEMUTimer *ts;
1251 for(;;) {
1252 ts = *ptimer_head;
1253 if (!ts || ts->expire_time > current_time)
1254 break;
1255 /* remove timer from the list before calling the callback */
1256 *ptimer_head = ts->next;
1257 ts->next = NULL;
1259 /* run the callback (the timer list can be modified) */
1260 ts->cb(ts->opaque);
1264 int64_t qemu_get_clock(QEMUClock *clock)
1266 switch(clock->type) {
1267 case QEMU_TIMER_REALTIME:
1268 return get_clock() / 1000000;
1269 default:
1270 case QEMU_TIMER_VIRTUAL:
1271 if (use_icount) {
1272 return cpu_get_icount();
1273 } else {
1274 return cpu_get_clock();
1279 static void init_timers(void)
1281 init_get_clock();
1282 ticks_per_sec = QEMU_TIMER_BASE;
1283 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1284 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1287 /* save a timer */
1288 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1290 uint64_t expire_time;
1292 if (qemu_timer_pending(ts)) {
1293 expire_time = ts->expire_time;
1294 } else {
1295 expire_time = -1;
1297 qemu_put_be64(f, expire_time);
1300 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1302 uint64_t expire_time;
1304 expire_time = qemu_get_be64(f);
1305 if (expire_time != -1) {
1306 qemu_mod_timer(ts, expire_time);
1307 } else {
1308 qemu_del_timer(ts);
1312 static void timer_save(QEMUFile *f, void *opaque)
1314 if (cpu_ticks_enabled) {
1315 hw_error("cannot save state if virtual timers are running");
1317 qemu_put_be64(f, cpu_ticks_offset);
1318 qemu_put_be64(f, ticks_per_sec);
1319 qemu_put_be64(f, cpu_clock_offset);
1322 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1324 if (version_id != 1 && version_id != 2)
1325 return -EINVAL;
1326 if (cpu_ticks_enabled) {
1327 return -EINVAL;
1329 cpu_ticks_offset=qemu_get_be64(f);
1330 ticks_per_sec=qemu_get_be64(f);
1331 if (version_id == 2) {
1332 cpu_clock_offset=qemu_get_be64(f);
1334 return 0;
1337 static void qemu_event_increment(void);
1339 #ifdef _WIN32
1340 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1341 DWORD_PTR dwUser, DWORD_PTR dw1,
1342 DWORD_PTR dw2)
1343 #else
1344 static void host_alarm_handler(int host_signum)
1345 #endif
1347 #if 0
1348 #define DISP_FREQ 1000
1350 static int64_t delta_min = INT64_MAX;
1351 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1352 static int count;
1353 ti = qemu_get_clock(vm_clock);
1354 if (last_clock != 0) {
1355 delta = ti - last_clock;
1356 if (delta < delta_min)
1357 delta_min = delta;
1358 if (delta > delta_max)
1359 delta_max = delta;
1360 delta_cum += delta;
1361 if (++count == DISP_FREQ) {
1362 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1363 muldiv64(delta_min, 1000000, ticks_per_sec),
1364 muldiv64(delta_max, 1000000, ticks_per_sec),
1365 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1366 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1367 count = 0;
1368 delta_min = INT64_MAX;
1369 delta_max = 0;
1370 delta_cum = 0;
1373 last_clock = ti;
1375 #endif
1376 if (alarm_has_dynticks(alarm_timer) ||
1377 (!use_icount &&
1378 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1379 qemu_get_clock(vm_clock))) ||
1380 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1381 qemu_get_clock(rt_clock))) {
1382 qemu_event_increment();
1383 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1385 #ifndef CONFIG_IOTHREAD
1386 if (next_cpu) {
1387 /* stop the currently executing cpu because a timer occured */
1388 cpu_exit(next_cpu);
1389 #ifdef CONFIG_KQEMU
1390 if (next_cpu->kqemu_enabled) {
1391 kqemu_cpu_interrupt(next_cpu);
1393 #endif
1395 #endif
1396 timer_alarm_pending = 1;
1397 qemu_notify_event();
1401 static int64_t qemu_next_deadline(void)
1403 int64_t delta;
1405 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1406 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1407 qemu_get_clock(vm_clock);
1408 } else {
1409 /* To avoid problems with overflow limit this to 2^32. */
1410 delta = INT32_MAX;
1413 if (delta < 0)
1414 delta = 0;
1416 return delta;
1419 #if defined(__linux__) || defined(_WIN32)
1420 static uint64_t qemu_next_deadline_dyntick(void)
1422 int64_t delta;
1423 int64_t rtdelta;
1425 if (use_icount)
1426 delta = INT32_MAX;
1427 else
1428 delta = (qemu_next_deadline() + 999) / 1000;
1430 if (active_timers[QEMU_TIMER_REALTIME]) {
1431 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1432 qemu_get_clock(rt_clock))*1000;
1433 if (rtdelta < delta)
1434 delta = rtdelta;
1437 if (delta < MIN_TIMER_REARM_US)
1438 delta = MIN_TIMER_REARM_US;
1440 return delta;
1442 #endif
1444 #ifndef _WIN32
1446 /* Sets a specific flag */
1447 static int fcntl_setfl(int fd, int flag)
1449 int flags;
1451 flags = fcntl(fd, F_GETFL);
1452 if (flags == -1)
1453 return -errno;
1455 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1456 return -errno;
1458 return 0;
1461 #if defined(__linux__)
1463 #define RTC_FREQ 1024
1465 static void enable_sigio_timer(int fd)
1467 struct sigaction act;
1469 /* timer signal */
1470 sigfillset(&act.sa_mask);
1471 act.sa_flags = 0;
1472 act.sa_handler = host_alarm_handler;
1474 sigaction(SIGIO, &act, NULL);
1475 fcntl_setfl(fd, O_ASYNC);
1476 fcntl(fd, F_SETOWN, getpid());
1479 static int hpet_start_timer(struct qemu_alarm_timer *t)
1481 struct hpet_info info;
1482 int r, fd;
1484 fd = open("/dev/hpet", O_RDONLY);
1485 if (fd < 0)
1486 return -1;
1488 /* Set frequency */
1489 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1490 if (r < 0) {
1491 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1492 "error, but for better emulation accuracy type:\n"
1493 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1494 goto fail;
1497 /* Check capabilities */
1498 r = ioctl(fd, HPET_INFO, &info);
1499 if (r < 0)
1500 goto fail;
1502 /* Enable periodic mode */
1503 r = ioctl(fd, HPET_EPI, 0);
1504 if (info.hi_flags && (r < 0))
1505 goto fail;
1507 /* Enable interrupt */
1508 r = ioctl(fd, HPET_IE_ON, 0);
1509 if (r < 0)
1510 goto fail;
1512 enable_sigio_timer(fd);
1513 t->priv = (void *)(long)fd;
1515 return 0;
1516 fail:
1517 close(fd);
1518 return -1;
1521 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1523 int fd = (long)t->priv;
1525 close(fd);
1528 static int rtc_start_timer(struct qemu_alarm_timer *t)
1530 int rtc_fd;
1531 unsigned long current_rtc_freq = 0;
1533 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1534 if (rtc_fd < 0)
1535 return -1;
1536 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1537 if (current_rtc_freq != RTC_FREQ &&
1538 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1539 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1540 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1541 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1542 goto fail;
1544 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1545 fail:
1546 close(rtc_fd);
1547 return -1;
1550 enable_sigio_timer(rtc_fd);
1552 t->priv = (void *)(long)rtc_fd;
1554 return 0;
1557 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1559 int rtc_fd = (long)t->priv;
1561 close(rtc_fd);
1564 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1566 struct sigevent ev;
1567 timer_t host_timer;
1568 struct sigaction act;
1570 sigfillset(&act.sa_mask);
1571 act.sa_flags = 0;
1572 act.sa_handler = host_alarm_handler;
1574 sigaction(SIGALRM, &act, NULL);
1577 * Initialize ev struct to 0 to avoid valgrind complaining
1578 * about uninitialized data in timer_create call
1580 memset(&ev, 0, sizeof(ev));
1581 ev.sigev_value.sival_int = 0;
1582 ev.sigev_notify = SIGEV_SIGNAL;
1583 ev.sigev_signo = SIGALRM;
1585 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1586 perror("timer_create");
1588 /* disable dynticks */
1589 fprintf(stderr, "Dynamic Ticks disabled\n");
1591 return -1;
1594 t->priv = (void *)(long)host_timer;
1596 return 0;
1599 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1601 timer_t host_timer = (timer_t)(long)t->priv;
1603 timer_delete(host_timer);
1606 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1608 timer_t host_timer = (timer_t)(long)t->priv;
1609 struct itimerspec timeout;
1610 int64_t nearest_delta_us = INT64_MAX;
1611 int64_t current_us;
1613 if (!active_timers[QEMU_TIMER_REALTIME] &&
1614 !active_timers[QEMU_TIMER_VIRTUAL])
1615 return;
1617 nearest_delta_us = qemu_next_deadline_dyntick();
1619 /* check whether a timer is already running */
1620 if (timer_gettime(host_timer, &timeout)) {
1621 perror("gettime");
1622 fprintf(stderr, "Internal timer error: aborting\n");
1623 exit(1);
1625 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1626 if (current_us && current_us <= nearest_delta_us)
1627 return;
1629 timeout.it_interval.tv_sec = 0;
1630 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1631 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1632 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1633 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1634 perror("settime");
1635 fprintf(stderr, "Internal timer error: aborting\n");
1636 exit(1);
1640 #endif /* defined(__linux__) */
1642 static int unix_start_timer(struct qemu_alarm_timer *t)
1644 struct sigaction act;
1645 struct itimerval itv;
1646 int err;
1648 /* timer signal */
1649 sigfillset(&act.sa_mask);
1650 act.sa_flags = 0;
1651 act.sa_handler = host_alarm_handler;
1653 sigaction(SIGALRM, &act, NULL);
1655 itv.it_interval.tv_sec = 0;
1656 /* for i386 kernel 2.6 to get 1 ms */
1657 itv.it_interval.tv_usec = 999;
1658 itv.it_value.tv_sec = 0;
1659 itv.it_value.tv_usec = 10 * 1000;
1661 err = setitimer(ITIMER_REAL, &itv, NULL);
1662 if (err)
1663 return -1;
1665 return 0;
1668 static void unix_stop_timer(struct qemu_alarm_timer *t)
1670 struct itimerval itv;
1672 memset(&itv, 0, sizeof(itv));
1673 setitimer(ITIMER_REAL, &itv, NULL);
1676 #endif /* !defined(_WIN32) */
1679 #ifdef _WIN32
1681 static int win32_start_timer(struct qemu_alarm_timer *t)
1683 TIMECAPS tc;
1684 struct qemu_alarm_win32 *data = t->priv;
1685 UINT flags;
1687 memset(&tc, 0, sizeof(tc));
1688 timeGetDevCaps(&tc, sizeof(tc));
1690 if (data->period < tc.wPeriodMin)
1691 data->period = tc.wPeriodMin;
1693 timeBeginPeriod(data->period);
1695 flags = TIME_CALLBACK_FUNCTION;
1696 if (alarm_has_dynticks(t))
1697 flags |= TIME_ONESHOT;
1698 else
1699 flags |= TIME_PERIODIC;
1701 data->timerId = timeSetEvent(1, // interval (ms)
1702 data->period, // resolution
1703 host_alarm_handler, // function
1704 (DWORD)t, // parameter
1705 flags);
1707 if (!data->timerId) {
1708 perror("Failed to initialize win32 alarm timer");
1709 timeEndPeriod(data->period);
1710 return -1;
1713 return 0;
1716 static void win32_stop_timer(struct qemu_alarm_timer *t)
1718 struct qemu_alarm_win32 *data = t->priv;
1720 timeKillEvent(data->timerId);
1721 timeEndPeriod(data->period);
1724 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1726 struct qemu_alarm_win32 *data = t->priv;
1727 uint64_t nearest_delta_us;
1729 if (!active_timers[QEMU_TIMER_REALTIME] &&
1730 !active_timers[QEMU_TIMER_VIRTUAL])
1731 return;
1733 nearest_delta_us = qemu_next_deadline_dyntick();
1734 nearest_delta_us /= 1000;
1736 timeKillEvent(data->timerId);
1738 data->timerId = timeSetEvent(1,
1739 data->period,
1740 host_alarm_handler,
1741 (DWORD)t,
1742 TIME_ONESHOT | TIME_PERIODIC);
1744 if (!data->timerId) {
1745 perror("Failed to re-arm win32 alarm timer");
1747 timeEndPeriod(data->period);
1748 exit(1);
1752 #endif /* _WIN32 */
1754 static int init_timer_alarm(void)
1756 struct qemu_alarm_timer *t = NULL;
1757 int i, err = -1;
1759 for (i = 0; alarm_timers[i].name; i++) {
1760 t = &alarm_timers[i];
1762 err = t->start(t);
1763 if (!err)
1764 break;
1767 if (err) {
1768 err = -ENOENT;
1769 goto fail;
1772 alarm_timer = t;
1774 return 0;
1776 fail:
1777 return err;
1780 static void quit_timers(void)
1782 alarm_timer->stop(alarm_timer);
1783 alarm_timer = NULL;
1786 /***********************************************************/
1787 /* host time/date access */
1788 void qemu_get_timedate(struct tm *tm, int offset)
1790 time_t ti;
1791 struct tm *ret;
1793 time(&ti);
1794 ti += offset;
1795 if (rtc_date_offset == -1) {
1796 if (rtc_utc)
1797 ret = gmtime(&ti);
1798 else
1799 ret = localtime(&ti);
1800 } else {
1801 ti -= rtc_date_offset;
1802 ret = gmtime(&ti);
1805 memcpy(tm, ret, sizeof(struct tm));
1808 int qemu_timedate_diff(struct tm *tm)
1810 time_t seconds;
1812 if (rtc_date_offset == -1)
1813 if (rtc_utc)
1814 seconds = mktimegm(tm);
1815 else
1816 seconds = mktime(tm);
1817 else
1818 seconds = mktimegm(tm) + rtc_date_offset;
1820 return seconds - time(NULL);
1823 #ifdef _WIN32
1824 static void socket_cleanup(void)
1826 WSACleanup();
1829 static int socket_init(void)
1831 WSADATA Data;
1832 int ret, err;
1834 ret = WSAStartup(MAKEWORD(2,2), &Data);
1835 if (ret != 0) {
1836 err = WSAGetLastError();
1837 fprintf(stderr, "WSAStartup: %d\n", err);
1838 return -1;
1840 atexit(socket_cleanup);
1841 return 0;
1843 #endif
1845 int get_param_value(char *buf, int buf_size,
1846 const char *tag, const char *str)
1848 const char *p;
1849 char option[128];
1851 p = str;
1852 for(;;) {
1853 p = get_opt_name(option, sizeof(option), p, '=');
1854 if (*p != '=')
1855 break;
1856 p++;
1857 if (!strcmp(tag, option)) {
1858 (void)get_opt_value(buf, buf_size, p);
1859 return strlen(buf);
1860 } else {
1861 p = get_opt_value(NULL, 0, p);
1863 if (*p != ',')
1864 break;
1865 p++;
1867 return 0;
1870 int check_params(char *buf, int buf_size,
1871 const char * const *params, const char *str)
1873 const char *p;
1874 int i;
1876 p = str;
1877 while (*p != '\0') {
1878 p = get_opt_name(buf, buf_size, p, '=');
1879 if (*p != '=') {
1880 return -1;
1882 p++;
1883 for (i = 0; params[i] != NULL; i++) {
1884 if (!strcmp(params[i], buf)) {
1885 break;
1888 if (params[i] == NULL) {
1889 return -1;
1891 p = get_opt_value(NULL, 0, p);
1892 if (*p != ',') {
1893 break;
1895 p++;
1897 return 0;
1900 /***********************************************************/
1901 /* Bluetooth support */
1902 static int nb_hcis;
1903 static int cur_hci;
1904 static struct HCIInfo *hci_table[MAX_NICS];
1906 static struct bt_vlan_s {
1907 struct bt_scatternet_s net;
1908 int id;
1909 struct bt_vlan_s *next;
1910 } *first_bt_vlan;
1912 /* find or alloc a new bluetooth "VLAN" */
1913 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1915 struct bt_vlan_s **pvlan, *vlan;
1916 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1917 if (vlan->id == id)
1918 return &vlan->net;
1920 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1921 vlan->id = id;
1922 pvlan = &first_bt_vlan;
1923 while (*pvlan != NULL)
1924 pvlan = &(*pvlan)->next;
1925 *pvlan = vlan;
1926 return &vlan->net;
1929 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1933 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1935 return -ENOTSUP;
1938 static struct HCIInfo null_hci = {
1939 .cmd_send = null_hci_send,
1940 .sco_send = null_hci_send,
1941 .acl_send = null_hci_send,
1942 .bdaddr_set = null_hci_addr_set,
1945 struct HCIInfo *qemu_next_hci(void)
1947 if (cur_hci == nb_hcis)
1948 return &null_hci;
1950 return hci_table[cur_hci++];
1953 static struct HCIInfo *hci_init(const char *str)
1955 char *endp;
1956 struct bt_scatternet_s *vlan = 0;
1958 if (!strcmp(str, "null"))
1959 /* null */
1960 return &null_hci;
1961 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1962 /* host[:hciN] */
1963 return bt_host_hci(str[4] ? str + 5 : "hci0");
1964 else if (!strncmp(str, "hci", 3)) {
1965 /* hci[,vlan=n] */
1966 if (str[3]) {
1967 if (!strncmp(str + 3, ",vlan=", 6)) {
1968 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1969 if (*endp)
1970 vlan = 0;
1972 } else
1973 vlan = qemu_find_bt_vlan(0);
1974 if (vlan)
1975 return bt_new_hci(vlan);
1978 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1980 return 0;
1983 static int bt_hci_parse(const char *str)
1985 struct HCIInfo *hci;
1986 bdaddr_t bdaddr;
1988 if (nb_hcis >= MAX_NICS) {
1989 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1990 return -1;
1993 hci = hci_init(str);
1994 if (!hci)
1995 return -1;
1997 bdaddr.b[0] = 0x52;
1998 bdaddr.b[1] = 0x54;
1999 bdaddr.b[2] = 0x00;
2000 bdaddr.b[3] = 0x12;
2001 bdaddr.b[4] = 0x34;
2002 bdaddr.b[5] = 0x56 + nb_hcis;
2003 hci->bdaddr_set(hci, bdaddr.b);
2005 hci_table[nb_hcis++] = hci;
2007 return 0;
2010 static void bt_vhci_add(int vlan_id)
2012 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2014 if (!vlan->slave)
2015 fprintf(stderr, "qemu: warning: adding a VHCI to "
2016 "an empty scatternet %i\n", vlan_id);
2018 bt_vhci_init(bt_new_hci(vlan));
2021 static struct bt_device_s *bt_device_add(const char *opt)
2023 struct bt_scatternet_s *vlan;
2024 int vlan_id = 0;
2025 char *endp = strstr(opt, ",vlan=");
2026 int len = (endp ? endp - opt : strlen(opt)) + 1;
2027 char devname[10];
2029 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2031 if (endp) {
2032 vlan_id = strtol(endp + 6, &endp, 0);
2033 if (*endp) {
2034 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2035 return 0;
2039 vlan = qemu_find_bt_vlan(vlan_id);
2041 if (!vlan->slave)
2042 fprintf(stderr, "qemu: warning: adding a slave device to "
2043 "an empty scatternet %i\n", vlan_id);
2045 if (!strcmp(devname, "keyboard"))
2046 return bt_keyboard_init(vlan);
2048 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2049 return 0;
2052 static int bt_parse(const char *opt)
2054 const char *endp, *p;
2055 int vlan;
2057 if (strstart(opt, "hci", &endp)) {
2058 if (!*endp || *endp == ',') {
2059 if (*endp)
2060 if (!strstart(endp, ",vlan=", 0))
2061 opt = endp + 1;
2063 return bt_hci_parse(opt);
2065 } else if (strstart(opt, "vhci", &endp)) {
2066 if (!*endp || *endp == ',') {
2067 if (*endp) {
2068 if (strstart(endp, ",vlan=", &p)) {
2069 vlan = strtol(p, (char **) &endp, 0);
2070 if (*endp) {
2071 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2072 return 1;
2074 } else {
2075 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2076 return 1;
2078 } else
2079 vlan = 0;
2081 bt_vhci_add(vlan);
2082 return 0;
2084 } else if (strstart(opt, "device:", &endp))
2085 return !bt_device_add(endp);
2087 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2088 return 1;
2091 /***********************************************************/
2092 /* QEMU Block devices */
2094 #define HD_ALIAS "index=%d,media=disk"
2095 #define CDROM_ALIAS "index=2,media=cdrom"
2096 #define FD_ALIAS "index=%d,if=floppy"
2097 #define PFLASH_ALIAS "if=pflash"
2098 #define MTD_ALIAS "if=mtd"
2099 #define SD_ALIAS "index=0,if=sd"
2101 static int drive_opt_get_free_idx(void)
2103 int index;
2105 for (index = 0; index < MAX_DRIVES; index++)
2106 if (!drives_opt[index].used) {
2107 drives_opt[index].used = 1;
2108 return index;
2111 return -1;
2114 static int drive_get_free_idx(void)
2116 int index;
2118 for (index = 0; index < MAX_DRIVES; index++)
2119 if (!drives_table[index].used) {
2120 drives_table[index].used = 1;
2121 return index;
2124 return -1;
2127 int drive_add(const char *file, const char *fmt, ...)
2129 va_list ap;
2130 int index = drive_opt_get_free_idx();
2132 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2133 fprintf(stderr, "qemu: too many drives\n");
2134 return -1;
2137 drives_opt[index].file = file;
2138 va_start(ap, fmt);
2139 vsnprintf(drives_opt[index].opt,
2140 sizeof(drives_opt[0].opt), fmt, ap);
2141 va_end(ap);
2143 nb_drives_opt++;
2144 return index;
2147 void drive_remove(int index)
2149 drives_opt[index].used = 0;
2150 nb_drives_opt--;
2153 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2155 int index;
2157 /* seek interface, bus and unit */
2159 for (index = 0; index < MAX_DRIVES; index++)
2160 if (drives_table[index].type == type &&
2161 drives_table[index].bus == bus &&
2162 drives_table[index].unit == unit &&
2163 drives_table[index].used)
2164 return index;
2166 return -1;
2169 int drive_get_max_bus(BlockInterfaceType type)
2171 int max_bus;
2172 int index;
2174 max_bus = -1;
2175 for (index = 0; index < nb_drives; index++) {
2176 if(drives_table[index].type == type &&
2177 drives_table[index].bus > max_bus)
2178 max_bus = drives_table[index].bus;
2180 return max_bus;
2183 const char *drive_get_serial(BlockDriverState *bdrv)
2185 int index;
2187 for (index = 0; index < nb_drives; index++)
2188 if (drives_table[index].bdrv == bdrv)
2189 return drives_table[index].serial;
2191 return "\0";
2194 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2196 int index;
2198 for (index = 0; index < nb_drives; index++)
2199 if (drives_table[index].bdrv == bdrv)
2200 return drives_table[index].onerror;
2202 return BLOCK_ERR_STOP_ENOSPC;
2205 static void bdrv_format_print(void *opaque, const char *name)
2207 fprintf(stderr, " %s", name);
2210 void drive_uninit(BlockDriverState *bdrv)
2212 int i;
2214 for (i = 0; i < MAX_DRIVES; i++)
2215 if (drives_table[i].bdrv == bdrv) {
2216 drives_table[i].bdrv = NULL;
2217 drives_table[i].used = 0;
2218 drive_remove(drives_table[i].drive_opt_idx);
2219 nb_drives--;
2220 break;
2224 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2226 char buf[128];
2227 char file[1024];
2228 char devname[128];
2229 char serial[21];
2230 const char *mediastr = "";
2231 BlockInterfaceType type;
2232 enum { MEDIA_DISK, MEDIA_CDROM } media;
2233 int bus_id, unit_id;
2234 int cyls, heads, secs, translation;
2235 BlockDriverState *bdrv;
2236 BlockDriver *drv = NULL;
2237 QEMUMachine *machine = opaque;
2238 int max_devs;
2239 int index;
2240 int cache;
2241 int bdrv_flags, onerror;
2242 int drives_table_idx;
2243 char *str = arg->opt;
2244 static const char * const params[] = { "bus", "unit", "if", "index",
2245 "cyls", "heads", "secs", "trans",
2246 "media", "snapshot", "file",
2247 "cache", "format", "serial", "werror",
2248 "boot", NULL };
2250 if (check_params(buf, sizeof(buf), params, str) < 0) {
2251 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2252 buf, str);
2253 return -1;
2256 file[0] = 0;
2257 cyls = heads = secs = 0;
2258 bus_id = 0;
2259 unit_id = -1;
2260 translation = BIOS_ATA_TRANSLATION_AUTO;
2261 index = -1;
2262 cache = 3;
2264 if (machine->use_scsi) {
2265 type = IF_SCSI;
2266 max_devs = MAX_SCSI_DEVS;
2267 pstrcpy(devname, sizeof(devname), "scsi");
2268 } else {
2269 type = IF_IDE;
2270 max_devs = MAX_IDE_DEVS;
2271 pstrcpy(devname, sizeof(devname), "ide");
2273 media = MEDIA_DISK;
2275 /* extract parameters */
2277 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2278 bus_id = strtol(buf, NULL, 0);
2279 if (bus_id < 0) {
2280 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2281 return -1;
2285 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2286 unit_id = strtol(buf, NULL, 0);
2287 if (unit_id < 0) {
2288 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2289 return -1;
2293 if (get_param_value(buf, sizeof(buf), "if", str)) {
2294 pstrcpy(devname, sizeof(devname), buf);
2295 if (!strcmp(buf, "ide")) {
2296 type = IF_IDE;
2297 max_devs = MAX_IDE_DEVS;
2298 } else if (!strcmp(buf, "scsi")) {
2299 type = IF_SCSI;
2300 max_devs = MAX_SCSI_DEVS;
2301 } else if (!strcmp(buf, "floppy")) {
2302 type = IF_FLOPPY;
2303 max_devs = 0;
2304 } else if (!strcmp(buf, "pflash")) {
2305 type = IF_PFLASH;
2306 max_devs = 0;
2307 } else if (!strcmp(buf, "mtd")) {
2308 type = IF_MTD;
2309 max_devs = 0;
2310 } else if (!strcmp(buf, "sd")) {
2311 type = IF_SD;
2312 max_devs = 0;
2313 } else if (!strcmp(buf, "virtio")) {
2314 type = IF_VIRTIO;
2315 max_devs = 0;
2316 } else if (!strcmp(buf, "xen")) {
2317 type = IF_XEN;
2318 max_devs = 0;
2319 } else {
2320 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2321 return -1;
2325 if (get_param_value(buf, sizeof(buf), "index", str)) {
2326 index = strtol(buf, NULL, 0);
2327 if (index < 0) {
2328 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2329 return -1;
2333 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2334 cyls = strtol(buf, NULL, 0);
2337 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2338 heads = strtol(buf, NULL, 0);
2341 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2342 secs = strtol(buf, NULL, 0);
2345 if (cyls || heads || secs) {
2346 if (cyls < 1 || cyls > 16383) {
2347 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2348 return -1;
2350 if (heads < 1 || heads > 16) {
2351 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2352 return -1;
2354 if (secs < 1 || secs > 63) {
2355 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2356 return -1;
2360 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2361 if (!cyls) {
2362 fprintf(stderr,
2363 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2364 str);
2365 return -1;
2367 if (!strcmp(buf, "none"))
2368 translation = BIOS_ATA_TRANSLATION_NONE;
2369 else if (!strcmp(buf, "lba"))
2370 translation = BIOS_ATA_TRANSLATION_LBA;
2371 else if (!strcmp(buf, "auto"))
2372 translation = BIOS_ATA_TRANSLATION_AUTO;
2373 else {
2374 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2375 return -1;
2379 if (get_param_value(buf, sizeof(buf), "media", str)) {
2380 if (!strcmp(buf, "disk")) {
2381 media = MEDIA_DISK;
2382 } else if (!strcmp(buf, "cdrom")) {
2383 if (cyls || secs || heads) {
2384 fprintf(stderr,
2385 "qemu: '%s' invalid physical CHS format\n", str);
2386 return -1;
2388 media = MEDIA_CDROM;
2389 } else {
2390 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2391 return -1;
2395 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2396 if (!strcmp(buf, "on"))
2397 snapshot = 1;
2398 else if (!strcmp(buf, "off"))
2399 snapshot = 0;
2400 else {
2401 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2402 return -1;
2406 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2407 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2408 cache = 0;
2409 else if (!strcmp(buf, "writethrough"))
2410 cache = 1;
2411 else if (!strcmp(buf, "writeback"))
2412 cache = 2;
2413 else {
2414 fprintf(stderr, "qemu: invalid cache option\n");
2415 return -1;
2419 if (get_param_value(buf, sizeof(buf), "format", str)) {
2420 if (strcmp(buf, "?") == 0) {
2421 fprintf(stderr, "qemu: Supported formats:");
2422 bdrv_iterate_format(bdrv_format_print, NULL);
2423 fprintf(stderr, "\n");
2424 return -1;
2426 drv = bdrv_find_format(buf);
2427 if (!drv) {
2428 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2429 return -1;
2433 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2434 if (!strcmp(buf, "on")) {
2435 if (extboot_drive != -1) {
2436 fprintf(stderr, "qemu: two bootable drives specified\n");
2437 return -1;
2439 extboot_drive = nb_drives;
2440 } else if (strcmp(buf, "off")) {
2441 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2442 return -1;
2446 if (arg->file == NULL)
2447 get_param_value(file, sizeof(file), "file", str);
2448 else
2449 pstrcpy(file, sizeof(file), arg->file);
2451 if (!get_param_value(serial, sizeof(serial), "serial", str))
2452 memset(serial, 0, sizeof(serial));
2454 onerror = BLOCK_ERR_STOP_ENOSPC;
2455 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2456 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2457 fprintf(stderr, "werror is no supported by this format\n");
2458 return -1;
2460 if (!strcmp(buf, "ignore"))
2461 onerror = BLOCK_ERR_IGNORE;
2462 else if (!strcmp(buf, "enospc"))
2463 onerror = BLOCK_ERR_STOP_ENOSPC;
2464 else if (!strcmp(buf, "stop"))
2465 onerror = BLOCK_ERR_STOP_ANY;
2466 else if (!strcmp(buf, "report"))
2467 onerror = BLOCK_ERR_REPORT;
2468 else {
2469 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2470 return -1;
2474 /* compute bus and unit according index */
2476 if (index != -1) {
2477 if (bus_id != 0 || unit_id != -1) {
2478 fprintf(stderr,
2479 "qemu: '%s' index cannot be used with bus and unit\n", str);
2480 return -1;
2482 if (max_devs == 0)
2484 unit_id = index;
2485 bus_id = 0;
2486 } else {
2487 unit_id = index % max_devs;
2488 bus_id = index / max_devs;
2492 /* if user doesn't specify a unit_id,
2493 * try to find the first free
2496 if (unit_id == -1) {
2497 unit_id = 0;
2498 while (drive_get_index(type, bus_id, unit_id) != -1) {
2499 unit_id++;
2500 if (max_devs && unit_id >= max_devs) {
2501 unit_id -= max_devs;
2502 bus_id++;
2507 /* check unit id */
2509 if (max_devs && unit_id >= max_devs) {
2510 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2511 str, unit_id, max_devs - 1);
2512 return -1;
2516 * ignore multiple definitions
2519 if (drive_get_index(type, bus_id, unit_id) != -1)
2520 return -2;
2522 /* init */
2524 if (type == IF_IDE || type == IF_SCSI)
2525 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2526 if (max_devs)
2527 snprintf(buf, sizeof(buf), "%s%i%s%i",
2528 devname, bus_id, mediastr, unit_id);
2529 else
2530 snprintf(buf, sizeof(buf), "%s%s%i",
2531 devname, mediastr, unit_id);
2532 bdrv = bdrv_new(buf);
2533 drives_table_idx = drive_get_free_idx();
2534 drives_table[drives_table_idx].bdrv = bdrv;
2535 drives_table[drives_table_idx].type = type;
2536 drives_table[drives_table_idx].bus = bus_id;
2537 drives_table[drives_table_idx].unit = unit_id;
2538 drives_table[drives_table_idx].onerror = onerror;
2539 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2540 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2541 nb_drives++;
2543 switch(type) {
2544 case IF_IDE:
2545 case IF_SCSI:
2546 case IF_XEN:
2547 switch(media) {
2548 case MEDIA_DISK:
2549 if (cyls != 0) {
2550 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2551 bdrv_set_translation_hint(bdrv, translation);
2553 break;
2554 case MEDIA_CDROM:
2555 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2556 break;
2558 break;
2559 case IF_SD:
2560 /* FIXME: This isn't really a floppy, but it's a reasonable
2561 approximation. */
2562 case IF_FLOPPY:
2563 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2564 break;
2565 case IF_PFLASH:
2566 case IF_MTD:
2567 case IF_VIRTIO:
2568 break;
2569 case IF_COUNT:
2570 abort();
2572 if (!file[0])
2573 return -2;
2574 bdrv_flags = 0;
2575 if (snapshot) {
2576 bdrv_flags |= BDRV_O_SNAPSHOT;
2577 cache = 2; /* always use write-back with snapshot */
2579 if (cache == 0) /* no caching */
2580 bdrv_flags |= BDRV_O_NOCACHE;
2581 else if (cache == 2) /* write-back */
2582 bdrv_flags |= BDRV_O_CACHE_WB;
2583 else if (cache == 3) /* not specified */
2584 bdrv_flags |= BDRV_O_CACHE_DEF;
2585 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2586 fprintf(stderr, "qemu: could not open disk image %s\n",
2587 file);
2588 return -1;
2590 if (bdrv_key_required(bdrv))
2591 autostart = 0;
2592 return drives_table_idx;
2595 static void numa_add(const char *optarg)
2597 char option[128];
2598 char *endptr;
2599 unsigned long long value, endvalue;
2600 int nodenr;
2602 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2603 if (!strcmp(option, "node")) {
2604 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2605 nodenr = nb_numa_nodes;
2606 } else {
2607 nodenr = strtoull(option, NULL, 10);
2610 if (get_param_value(option, 128, "mem", optarg) == 0) {
2611 node_mem[nodenr] = 0;
2612 } else {
2613 value = strtoull(option, &endptr, 0);
2614 switch (*endptr) {
2615 case 0: case 'M': case 'm':
2616 value <<= 20;
2617 break;
2618 case 'G': case 'g':
2619 value <<= 30;
2620 break;
2622 node_mem[nodenr] = value;
2624 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2625 node_cpumask[nodenr] = 0;
2626 } else {
2627 value = strtoull(option, &endptr, 10);
2628 if (value >= 64) {
2629 value = 63;
2630 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2631 } else {
2632 if (*endptr == '-') {
2633 endvalue = strtoull(endptr+1, &endptr, 10);
2634 if (endvalue >= 63) {
2635 endvalue = 62;
2636 fprintf(stderr,
2637 "only 63 CPUs in NUMA mode supported.\n");
2639 value = (1 << (endvalue + 1)) - (1 << value);
2640 } else {
2641 value = 1 << value;
2644 node_cpumask[nodenr] = value;
2646 nb_numa_nodes++;
2648 return;
2651 /***********************************************************/
2652 /* USB devices */
2654 static USBPort *used_usb_ports;
2655 static USBPort *free_usb_ports;
2657 /* ??? Maybe change this to register a hub to keep track of the topology. */
2658 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2659 usb_attachfn attach)
2661 port->opaque = opaque;
2662 port->index = index;
2663 port->attach = attach;
2664 port->next = free_usb_ports;
2665 free_usb_ports = port;
2668 int usb_device_add_dev(USBDevice *dev)
2670 USBPort *port;
2672 /* Find a USB port to add the device to. */
2673 port = free_usb_ports;
2674 if (!port->next) {
2675 USBDevice *hub;
2677 /* Create a new hub and chain it on. */
2678 free_usb_ports = NULL;
2679 port->next = used_usb_ports;
2680 used_usb_ports = port;
2682 hub = usb_hub_init(VM_USB_HUB_SIZE);
2683 usb_attach(port, hub);
2684 port = free_usb_ports;
2687 free_usb_ports = port->next;
2688 port->next = used_usb_ports;
2689 used_usb_ports = port;
2690 usb_attach(port, dev);
2691 return 0;
2694 static void usb_msd_password_cb(void *opaque, int err)
2696 USBDevice *dev = opaque;
2698 if (!err)
2699 usb_device_add_dev(dev);
2700 else
2701 dev->handle_destroy(dev);
2704 static int usb_device_add(const char *devname, int is_hotplug)
2706 const char *p;
2707 USBDevice *dev;
2709 if (!free_usb_ports)
2710 return -1;
2712 if (strstart(devname, "host:", &p)) {
2713 dev = usb_host_device_open(p);
2714 } else if (!strcmp(devname, "mouse")) {
2715 dev = usb_mouse_init();
2716 } else if (!strcmp(devname, "tablet")) {
2717 dev = usb_tablet_init();
2718 } else if (!strcmp(devname, "keyboard")) {
2719 dev = usb_keyboard_init();
2720 } else if (strstart(devname, "disk:", &p)) {
2721 BlockDriverState *bs;
2723 dev = usb_msd_init(p);
2724 if (!dev)
2725 return -1;
2726 bs = usb_msd_get_bdrv(dev);
2727 if (bdrv_key_required(bs)) {
2728 autostart = 0;
2729 if (is_hotplug) {
2730 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2731 dev);
2732 return 0;
2735 } else if (!strcmp(devname, "wacom-tablet")) {
2736 dev = usb_wacom_init();
2737 } else if (strstart(devname, "serial:", &p)) {
2738 dev = usb_serial_init(p);
2739 #ifdef CONFIG_BRLAPI
2740 } else if (!strcmp(devname, "braille")) {
2741 dev = usb_baum_init();
2742 #endif
2743 } else if (strstart(devname, "net:", &p)) {
2744 int nic = nb_nics;
2746 if (net_client_init(NULL, "nic", p) < 0)
2747 return -1;
2748 nd_table[nic].model = "usb";
2749 dev = usb_net_init(&nd_table[nic]);
2750 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2751 dev = usb_bt_init(devname[2] ? hci_init(p) :
2752 bt_new_hci(qemu_find_bt_vlan(0)));
2753 } else {
2754 return -1;
2756 if (!dev)
2757 return -1;
2759 return usb_device_add_dev(dev);
2762 int usb_device_del_addr(int bus_num, int addr)
2764 USBPort *port;
2765 USBPort **lastp;
2766 USBDevice *dev;
2768 if (!used_usb_ports)
2769 return -1;
2771 if (bus_num != 0)
2772 return -1;
2774 lastp = &used_usb_ports;
2775 port = used_usb_ports;
2776 while (port && port->dev->addr != addr) {
2777 lastp = &port->next;
2778 port = port->next;
2781 if (!port)
2782 return -1;
2784 dev = port->dev;
2785 *lastp = port->next;
2786 usb_attach(port, NULL);
2787 dev->handle_destroy(dev);
2788 port->next = free_usb_ports;
2789 free_usb_ports = port;
2790 return 0;
2793 static int usb_device_del(const char *devname)
2795 int bus_num, addr;
2796 const char *p;
2798 if (strstart(devname, "host:", &p))
2799 return usb_host_device_close(p);
2801 if (!used_usb_ports)
2802 return -1;
2804 p = strchr(devname, '.');
2805 if (!p)
2806 return -1;
2807 bus_num = strtoul(devname, NULL, 0);
2808 addr = strtoul(p + 1, NULL, 0);
2810 return usb_device_del_addr(bus_num, addr);
2813 void do_usb_add(Monitor *mon, const char *devname)
2815 usb_device_add(devname, 1);
2818 void do_usb_del(Monitor *mon, const char *devname)
2820 usb_device_del(devname);
2823 void usb_info(Monitor *mon)
2825 USBDevice *dev;
2826 USBPort *port;
2827 const char *speed_str;
2829 if (!usb_enabled) {
2830 monitor_printf(mon, "USB support not enabled\n");
2831 return;
2834 for (port = used_usb_ports; port; port = port->next) {
2835 dev = port->dev;
2836 if (!dev)
2837 continue;
2838 switch(dev->speed) {
2839 case USB_SPEED_LOW:
2840 speed_str = "1.5";
2841 break;
2842 case USB_SPEED_FULL:
2843 speed_str = "12";
2844 break;
2845 case USB_SPEED_HIGH:
2846 speed_str = "480";
2847 break;
2848 default:
2849 speed_str = "?";
2850 break;
2852 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2853 0, dev->addr, speed_str, dev->devname);
2857 /***********************************************************/
2858 /* PCMCIA/Cardbus */
2860 static struct pcmcia_socket_entry_s {
2861 PCMCIASocket *socket;
2862 struct pcmcia_socket_entry_s *next;
2863 } *pcmcia_sockets = 0;
2865 void pcmcia_socket_register(PCMCIASocket *socket)
2867 struct pcmcia_socket_entry_s *entry;
2869 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2870 entry->socket = socket;
2871 entry->next = pcmcia_sockets;
2872 pcmcia_sockets = entry;
2875 void pcmcia_socket_unregister(PCMCIASocket *socket)
2877 struct pcmcia_socket_entry_s *entry, **ptr;
2879 ptr = &pcmcia_sockets;
2880 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2881 if (entry->socket == socket) {
2882 *ptr = entry->next;
2883 qemu_free(entry);
2887 void pcmcia_info(Monitor *mon)
2889 struct pcmcia_socket_entry_s *iter;
2891 if (!pcmcia_sockets)
2892 monitor_printf(mon, "No PCMCIA sockets\n");
2894 for (iter = pcmcia_sockets; iter; iter = iter->next)
2895 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2896 iter->socket->attached ? iter->socket->card_string :
2897 "Empty");
2900 /***********************************************************/
2901 /* register display */
2903 struct DisplayAllocator default_allocator = {
2904 defaultallocator_create_displaysurface,
2905 defaultallocator_resize_displaysurface,
2906 defaultallocator_free_displaysurface
2909 void register_displaystate(DisplayState *ds)
2911 DisplayState **s;
2912 s = &display_state;
2913 while (*s != NULL)
2914 s = &(*s)->next;
2915 ds->next = NULL;
2916 *s = ds;
2919 DisplayState *get_displaystate(void)
2921 return display_state;
2924 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2926 if(ds->allocator == &default_allocator) ds->allocator = da;
2927 return ds->allocator;
2930 /* dumb display */
2932 static void dumb_display_init(void)
2934 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2935 ds->allocator = &default_allocator;
2936 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2937 register_displaystate(ds);
2940 /***********************************************************/
2941 /* I/O handling */
2943 typedef struct IOHandlerRecord {
2944 int fd;
2945 IOCanRWHandler *fd_read_poll;
2946 IOHandler *fd_read;
2947 IOHandler *fd_write;
2948 int deleted;
2949 void *opaque;
2950 /* temporary data */
2951 struct pollfd *ufd;
2952 struct IOHandlerRecord *next;
2953 } IOHandlerRecord;
2955 static IOHandlerRecord *first_io_handler;
2957 /* XXX: fd_read_poll should be suppressed, but an API change is
2958 necessary in the character devices to suppress fd_can_read(). */
2959 int qemu_set_fd_handler2(int fd,
2960 IOCanRWHandler *fd_read_poll,
2961 IOHandler *fd_read,
2962 IOHandler *fd_write,
2963 void *opaque)
2965 IOHandlerRecord **pioh, *ioh;
2967 if (!fd_read && !fd_write) {
2968 pioh = &first_io_handler;
2969 for(;;) {
2970 ioh = *pioh;
2971 if (ioh == NULL)
2972 break;
2973 if (ioh->fd == fd) {
2974 ioh->deleted = 1;
2975 break;
2977 pioh = &ioh->next;
2979 } else {
2980 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2981 if (ioh->fd == fd)
2982 goto found;
2984 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2985 ioh->next = first_io_handler;
2986 first_io_handler = ioh;
2987 found:
2988 ioh->fd = fd;
2989 ioh->fd_read_poll = fd_read_poll;
2990 ioh->fd_read = fd_read;
2991 ioh->fd_write = fd_write;
2992 ioh->opaque = opaque;
2993 ioh->deleted = 0;
2995 qemu_notify_event();
2996 return 0;
2999 int qemu_set_fd_handler(int fd,
3000 IOHandler *fd_read,
3001 IOHandler *fd_write,
3002 void *opaque)
3004 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3007 #ifdef _WIN32
3008 /***********************************************************/
3009 /* Polling handling */
3011 typedef struct PollingEntry {
3012 PollingFunc *func;
3013 void *opaque;
3014 struct PollingEntry *next;
3015 } PollingEntry;
3017 static PollingEntry *first_polling_entry;
3019 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3021 PollingEntry **ppe, *pe;
3022 pe = qemu_mallocz(sizeof(PollingEntry));
3023 pe->func = func;
3024 pe->opaque = opaque;
3025 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3026 *ppe = pe;
3027 return 0;
3030 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3032 PollingEntry **ppe, *pe;
3033 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3034 pe = *ppe;
3035 if (pe->func == func && pe->opaque == opaque) {
3036 *ppe = pe->next;
3037 qemu_free(pe);
3038 break;
3043 /***********************************************************/
3044 /* Wait objects support */
3045 typedef struct WaitObjects {
3046 int num;
3047 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3048 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3049 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3050 } WaitObjects;
3052 static WaitObjects wait_objects = {0};
3054 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3056 WaitObjects *w = &wait_objects;
3058 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3059 return -1;
3060 w->events[w->num] = handle;
3061 w->func[w->num] = func;
3062 w->opaque[w->num] = opaque;
3063 w->num++;
3064 return 0;
3067 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3069 int i, found;
3070 WaitObjects *w = &wait_objects;
3072 found = 0;
3073 for (i = 0; i < w->num; i++) {
3074 if (w->events[i] == handle)
3075 found = 1;
3076 if (found) {
3077 w->events[i] = w->events[i + 1];
3078 w->func[i] = w->func[i + 1];
3079 w->opaque[i] = w->opaque[i + 1];
3082 if (found)
3083 w->num--;
3085 #endif
3087 /***********************************************************/
3088 /* ram save/restore */
3090 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3092 int v;
3094 v = qemu_get_byte(f);
3095 switch(v) {
3096 case 0:
3097 if (qemu_get_buffer(f, buf, len) != len)
3098 return -EIO;
3099 break;
3100 case 1:
3101 v = qemu_get_byte(f);
3102 memset(buf, v, len);
3103 break;
3104 default:
3105 return -EINVAL;
3108 if (qemu_file_has_error(f))
3109 return -EIO;
3111 return 0;
3114 static int ram_load_v1(QEMUFile *f, void *opaque)
3116 int ret;
3117 ram_addr_t i;
3119 if (qemu_get_be32(f) != last_ram_offset)
3120 return -EINVAL;
3121 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
3122 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3123 continue;
3124 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
3125 if (ret)
3126 return ret;
3128 return 0;
3131 #define BDRV_HASH_BLOCK_SIZE 1024
3132 #define IOBUF_SIZE 4096
3133 #define RAM_CBLOCK_MAGIC 0xfabe
3135 typedef struct RamDecompressState {
3136 z_stream zstream;
3137 QEMUFile *f;
3138 uint8_t buf[IOBUF_SIZE];
3139 } RamDecompressState;
3141 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3143 int ret;
3144 memset(s, 0, sizeof(*s));
3145 s->f = f;
3146 ret = inflateInit(&s->zstream);
3147 if (ret != Z_OK)
3148 return -1;
3149 return 0;
3152 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3154 int ret, clen;
3156 s->zstream.avail_out = len;
3157 s->zstream.next_out = buf;
3158 while (s->zstream.avail_out > 0) {
3159 if (s->zstream.avail_in == 0) {
3160 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3161 return -1;
3162 clen = qemu_get_be16(s->f);
3163 if (clen > IOBUF_SIZE)
3164 return -1;
3165 qemu_get_buffer(s->f, s->buf, clen);
3166 s->zstream.avail_in = clen;
3167 s->zstream.next_in = s->buf;
3169 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3170 if (ret != Z_OK && ret != Z_STREAM_END) {
3171 return -1;
3174 return 0;
3177 static void ram_decompress_close(RamDecompressState *s)
3179 inflateEnd(&s->zstream);
3182 #define RAM_SAVE_FLAG_FULL 0x01
3183 #define RAM_SAVE_FLAG_COMPRESS 0x02
3184 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3185 #define RAM_SAVE_FLAG_PAGE 0x08
3186 #define RAM_SAVE_FLAG_EOS 0x10
3188 static int is_dup_page(uint8_t *page, uint8_t ch)
3190 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3191 uint32_t *array = (uint32_t *)page;
3192 int i;
3194 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3195 if (array[i] != val)
3196 return 0;
3199 return 1;
3202 static int ram_save_block(QEMUFile *f)
3204 static ram_addr_t current_addr = 0;
3205 ram_addr_t saved_addr = current_addr;
3206 ram_addr_t addr = 0;
3207 int found = 0;
3209 while (addr < last_ram_offset) {
3210 if (kvm_enabled() && current_addr == 0) {
3211 int r;
3212 r = kvm_update_dirty_pages_log();
3213 if (r) {
3214 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3215 qemu_file_set_error(f);
3216 return 0;
3219 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3220 uint8_t *p;
3222 cpu_physical_memory_reset_dirty(current_addr,
3223 current_addr + TARGET_PAGE_SIZE,
3224 MIGRATION_DIRTY_FLAG);
3226 p = qemu_get_ram_ptr(current_addr);
3228 if (is_dup_page(p, *p)) {
3229 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3230 qemu_put_byte(f, *p);
3231 } else {
3232 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3233 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3236 found = 1;
3237 break;
3239 addr += TARGET_PAGE_SIZE;
3240 current_addr = (saved_addr + addr) % last_ram_offset;
3243 return found;
3246 static uint64_t bytes_transferred = 0;
3248 static ram_addr_t ram_save_remaining(void)
3250 ram_addr_t addr;
3251 ram_addr_t count = 0;
3253 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3254 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3255 count++;
3258 return count;
3261 uint64_t ram_bytes_remaining(void)
3263 return ram_save_remaining() * TARGET_PAGE_SIZE;
3266 uint64_t ram_bytes_transferred(void)
3268 return bytes_transferred;
3271 uint64_t ram_bytes_total(void)
3273 return last_ram_offset;
3276 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3278 ram_addr_t addr;
3279 uint64_t bytes_transferred_last;
3280 double bwidth = 0;
3281 uint64_t expected_time = 0;
3283 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3284 qemu_file_set_error(f);
3285 return 0;
3288 if (stage == 1) {
3289 /* Make sure all dirty bits are set */
3290 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3291 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3292 cpu_physical_memory_set_dirty(addr);
3295 /* Enable dirty memory tracking */
3296 cpu_physical_memory_set_dirty_tracking(1);
3298 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3301 bytes_transferred_last = bytes_transferred;
3302 bwidth = get_clock();
3304 while (!qemu_file_rate_limit(f)) {
3305 int ret;
3307 ret = ram_save_block(f);
3308 bytes_transferred += ret * TARGET_PAGE_SIZE;
3309 if (ret == 0) /* no more blocks */
3310 break;
3313 bwidth = get_clock() - bwidth;
3314 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3316 /* if we haven't transferred anything this round, force expected_time to a
3317 * a very high value, but without crashing */
3318 if (bwidth == 0)
3319 bwidth = 0.000001;
3321 /* try transferring iterative blocks of memory */
3323 if (stage == 3) {
3325 /* flush all remaining blocks regardless of rate limiting */
3326 while (ram_save_block(f) != 0) {
3327 bytes_transferred += TARGET_PAGE_SIZE;
3329 cpu_physical_memory_set_dirty_tracking(0);
3332 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3334 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3336 return (stage == 2) && (expected_time <= migrate_max_downtime());
3339 static int ram_load_dead(QEMUFile *f, void *opaque)
3341 RamDecompressState s1, *s = &s1;
3342 uint8_t buf[10];
3343 ram_addr_t i;
3345 if (ram_decompress_open(s, f) < 0)
3346 return -EINVAL;
3347 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3348 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3349 continue;
3350 if (ram_decompress_buf(s, buf, 1) < 0) {
3351 fprintf(stderr, "Error while reading ram block header\n");
3352 goto error;
3354 if (buf[0] == 0) {
3355 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3356 BDRV_HASH_BLOCK_SIZE) < 0) {
3357 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3358 goto error;
3360 } else {
3361 error:
3362 printf("Error block header\n");
3363 return -EINVAL;
3366 ram_decompress_close(s);
3368 return 0;
3371 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3373 ram_addr_t addr;
3374 int flags;
3376 if (version_id == 1)
3377 return ram_load_v1(f, opaque);
3379 if (version_id == 2) {
3380 if (qemu_get_be32(f) != last_ram_offset)
3381 return -EINVAL;
3382 return ram_load_dead(f, opaque);
3385 if (version_id != 3)
3386 return -EINVAL;
3388 do {
3389 addr = qemu_get_be64(f);
3391 flags = addr & ~TARGET_PAGE_MASK;
3392 addr &= TARGET_PAGE_MASK;
3394 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3395 if (addr != last_ram_offset)
3396 return -EINVAL;
3399 if (flags & RAM_SAVE_FLAG_FULL) {
3400 if (ram_load_dead(f, opaque) < 0)
3401 return -EINVAL;
3404 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3405 uint8_t ch = qemu_get_byte(f);
3406 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3407 } else if (flags & RAM_SAVE_FLAG_PAGE)
3408 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3409 } while (!(flags & RAM_SAVE_FLAG_EOS));
3411 return 0;
3414 void qemu_service_io(void)
3416 qemu_notify_event();
3419 /***********************************************************/
3420 /* bottom halves (can be seen as timers which expire ASAP) */
3422 struct QEMUBH {
3423 QEMUBHFunc *cb;
3424 void *opaque;
3425 int scheduled;
3426 int idle;
3427 int deleted;
3428 QEMUBH *next;
3431 static QEMUBH *first_bh = NULL;
3433 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3435 QEMUBH *bh;
3436 bh = qemu_mallocz(sizeof(QEMUBH));
3437 bh->cb = cb;
3438 bh->opaque = opaque;
3439 bh->next = first_bh;
3440 first_bh = bh;
3441 return bh;
3444 int qemu_bh_poll(void)
3446 QEMUBH *bh, **bhp;
3447 int ret;
3449 ret = 0;
3450 for (bh = first_bh; bh; bh = bh->next) {
3451 if (!bh->deleted && bh->scheduled) {
3452 bh->scheduled = 0;
3453 if (!bh->idle)
3454 ret = 1;
3455 bh->idle = 0;
3456 bh->cb(bh->opaque);
3460 /* remove deleted bhs */
3461 bhp = &first_bh;
3462 while (*bhp) {
3463 bh = *bhp;
3464 if (bh->deleted) {
3465 *bhp = bh->next;
3466 qemu_free(bh);
3467 } else
3468 bhp = &bh->next;
3471 return ret;
3474 void qemu_bh_schedule_idle(QEMUBH *bh)
3476 if (bh->scheduled)
3477 return;
3478 bh->scheduled = 1;
3479 bh->idle = 1;
3482 void qemu_bh_schedule(QEMUBH *bh)
3484 if (bh->scheduled)
3485 return;
3486 bh->scheduled = 1;
3487 bh->idle = 0;
3488 /* stop the currently executing CPU to execute the BH ASAP */
3489 qemu_notify_event();
3492 void qemu_bh_cancel(QEMUBH *bh)
3494 bh->scheduled = 0;
3497 void qemu_bh_delete(QEMUBH *bh)
3499 bh->scheduled = 0;
3500 bh->deleted = 1;
3503 static void qemu_bh_update_timeout(int *timeout)
3505 QEMUBH *bh;
3507 for (bh = first_bh; bh; bh = bh->next) {
3508 if (!bh->deleted && bh->scheduled) {
3509 if (bh->idle) {
3510 /* idle bottom halves will be polled at least
3511 * every 10ms */
3512 *timeout = MIN(10, *timeout);
3513 } else {
3514 /* non-idle bottom halves will be executed
3515 * immediately */
3516 *timeout = 0;
3517 break;
3523 /***********************************************************/
3524 /* machine registration */
3526 static QEMUMachine *first_machine = NULL;
3527 QEMUMachine *current_machine = NULL;
3529 int qemu_register_machine(QEMUMachine *m)
3531 QEMUMachine **pm;
3532 pm = &first_machine;
3533 while (*pm != NULL)
3534 pm = &(*pm)->next;
3535 m->next = NULL;
3536 *pm = m;
3537 return 0;
3540 static QEMUMachine *find_machine(const char *name)
3542 QEMUMachine *m;
3544 for(m = first_machine; m != NULL; m = m->next) {
3545 if (!strcmp(m->name, name))
3546 return m;
3548 return NULL;
3551 static QEMUMachine *find_default_machine(void)
3553 QEMUMachine *m;
3555 for(m = first_machine; m != NULL; m = m->next) {
3556 if (m->is_default) {
3557 return m;
3560 return NULL;
3563 /***********************************************************/
3564 /* main execution loop */
3566 static void gui_update(void *opaque)
3568 uint64_t interval = GUI_REFRESH_INTERVAL;
3569 DisplayState *ds = opaque;
3570 DisplayChangeListener *dcl = ds->listeners;
3572 dpy_refresh(ds);
3574 while (dcl != NULL) {
3575 if (dcl->gui_timer_interval &&
3576 dcl->gui_timer_interval < interval)
3577 interval = dcl->gui_timer_interval;
3578 dcl = dcl->next;
3580 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3583 static void nographic_update(void *opaque)
3585 uint64_t interval = GUI_REFRESH_INTERVAL;
3587 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3590 struct vm_change_state_entry {
3591 VMChangeStateHandler *cb;
3592 void *opaque;
3593 LIST_ENTRY (vm_change_state_entry) entries;
3596 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3598 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3599 void *opaque)
3601 VMChangeStateEntry *e;
3603 e = qemu_mallocz(sizeof (*e));
3605 e->cb = cb;
3606 e->opaque = opaque;
3607 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3608 return e;
3611 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3613 LIST_REMOVE (e, entries);
3614 qemu_free (e);
3617 static void vm_state_notify(int running, int reason)
3619 VMChangeStateEntry *e;
3621 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3622 e->cb(e->opaque, running, reason);
3626 static void resume_all_vcpus(void);
3627 static void pause_all_vcpus(void);
3629 void vm_start(void)
3631 if (!vm_running) {
3632 cpu_enable_ticks();
3633 vm_running = 1;
3634 vm_state_notify(1, 0);
3635 qemu_rearm_alarm_timer(alarm_timer);
3636 resume_all_vcpus();
3640 /* reset/shutdown handler */
3642 typedef struct QEMUResetEntry {
3643 QEMUResetHandler *func;
3644 void *opaque;
3645 int order;
3646 struct QEMUResetEntry *next;
3647 } QEMUResetEntry;
3649 static QEMUResetEntry *first_reset_entry;
3650 static int reset_requested;
3651 static int shutdown_requested;
3652 static int powerdown_requested;
3653 static int debug_requested;
3654 static int vmstop_requested;
3656 int qemu_no_shutdown(void)
3658 int r = no_shutdown;
3659 no_shutdown = 0;
3660 return r;
3663 int qemu_shutdown_requested(void)
3665 int r = shutdown_requested;
3666 shutdown_requested = 0;
3667 return r;
3670 int qemu_reset_requested(void)
3672 int r = reset_requested;
3673 reset_requested = 0;
3674 return r;
3677 int qemu_powerdown_requested(void)
3679 int r = powerdown_requested;
3680 powerdown_requested = 0;
3681 return r;
3684 static int qemu_debug_requested(void)
3686 int r = debug_requested;
3687 debug_requested = 0;
3688 return r;
3691 static int qemu_vmstop_requested(void)
3693 int r = vmstop_requested;
3694 vmstop_requested = 0;
3695 return r;
3698 static void do_vm_stop(int reason)
3700 if (vm_running) {
3701 cpu_disable_ticks();
3702 vm_running = 0;
3703 pause_all_vcpus();
3704 vm_state_notify(0, reason);
3708 void qemu_register_reset(QEMUResetHandler *func, int order, void *opaque)
3710 QEMUResetEntry **pre, *re;
3712 pre = &first_reset_entry;
3713 while (*pre != NULL && (*pre)->order >= order) {
3714 pre = &(*pre)->next;
3716 re = qemu_mallocz(sizeof(QEMUResetEntry));
3717 re->func = func;
3718 re->opaque = opaque;
3719 re->order = order;
3720 re->next = NULL;
3721 *pre = re;
3724 void qemu_system_reset(void)
3726 QEMUResetEntry *re;
3728 /* reset all devices */
3729 for(re = first_reset_entry; re != NULL; re = re->next) {
3730 re->func(re->opaque);
3734 void qemu_system_reset_request(void)
3736 if (no_reboot) {
3737 shutdown_requested = 1;
3738 } else {
3739 reset_requested = 1;
3741 if (cpu_single_env) {
3742 qemu_kvm_cpu_stop(cpu_single_env);
3744 qemu_notify_event();
3747 void qemu_system_shutdown_request(void)
3749 shutdown_requested = 1;
3750 qemu_notify_event();
3753 void qemu_system_powerdown_request(void)
3755 powerdown_requested = 1;
3756 qemu_notify_event();
3759 #ifdef CONFIG_IOTHREAD
3760 static void qemu_system_vmstop_request(int reason)
3762 vmstop_requested = reason;
3763 qemu_notify_event();
3765 #endif
3767 #ifndef _WIN32
3768 static int io_thread_fd = -1;
3770 static void qemu_event_increment(void)
3772 static const char byte = 0;
3774 if (io_thread_fd == -1)
3775 return;
3777 write(io_thread_fd, &byte, sizeof(byte));
3780 static void qemu_event_read(void *opaque)
3782 int fd = (unsigned long)opaque;
3783 ssize_t len;
3785 /* Drain the notify pipe */
3786 do {
3787 char buffer[512];
3788 len = read(fd, buffer, sizeof(buffer));
3789 } while ((len == -1 && errno == EINTR) || len > 0);
3792 static int qemu_event_init(void)
3794 int err;
3795 int fds[2];
3797 err = pipe(fds);
3798 if (err == -1)
3799 return -errno;
3801 err = fcntl_setfl(fds[0], O_NONBLOCK);
3802 if (err < 0)
3803 goto fail;
3805 err = fcntl_setfl(fds[1], O_NONBLOCK);
3806 if (err < 0)
3807 goto fail;
3809 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3810 (void *)(unsigned long)fds[0]);
3812 io_thread_fd = fds[1];
3813 return 0;
3815 fail:
3816 close(fds[0]);
3817 close(fds[1]);
3818 return err;
3820 #else
3821 HANDLE qemu_event_handle;
3823 static void dummy_event_handler(void *opaque)
3827 static int qemu_event_init(void)
3829 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3830 if (!qemu_event_handle) {
3831 perror("Failed CreateEvent");
3832 return -1;
3834 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3835 return 0;
3838 static void qemu_event_increment(void)
3840 SetEvent(qemu_event_handle);
3842 #endif
3844 static int cpu_can_run(CPUState *env)
3846 if (env->stop)
3847 return 0;
3848 if (env->stopped)
3849 return 0;
3850 return 1;
3853 #ifndef CONFIG_IOTHREAD
3854 static int qemu_init_main_loop(void)
3856 return qemu_event_init();
3859 void qemu_init_vcpu(void *_env)
3861 CPUState *env = _env;
3863 if (kvm_enabled())
3864 kvm_init_vcpu(env);
3865 return;
3868 int qemu_cpu_self(void *env)
3870 return 1;
3873 static void resume_all_vcpus(void)
3877 static void pause_all_vcpus(void)
3881 void qemu_cpu_kick(void *env)
3883 return;
3886 void qemu_notify_event(void)
3888 CPUState *env = cpu_single_env;
3890 if (kvm_enabled()) {
3891 qemu_kvm_notify_work();
3892 return;
3894 if (env) {
3895 cpu_exit(env);
3896 #ifdef USE_KQEMU
3897 if (env->kqemu_enabled)
3898 kqemu_cpu_interrupt(env);
3899 #endif
3903 #define qemu_mutex_lock_iothread() do { } while (0)
3904 #define qemu_mutex_unlock_iothread() do { } while (0)
3906 void vm_stop(int reason)
3908 do_vm_stop(reason);
3911 #else /* CONFIG_IOTHREAD */
3913 #include "qemu-thread.h"
3915 QemuMutex qemu_global_mutex;
3916 static QemuMutex qemu_fair_mutex;
3918 static QemuThread io_thread;
3920 static QemuThread *tcg_cpu_thread;
3921 static QemuCond *tcg_halt_cond;
3923 static int qemu_system_ready;
3924 /* cpu creation */
3925 static QemuCond qemu_cpu_cond;
3926 /* system init */
3927 static QemuCond qemu_system_cond;
3928 static QemuCond qemu_pause_cond;
3930 static void block_io_signals(void);
3931 static void unblock_io_signals(void);
3932 static int tcg_has_work(void);
3934 static int qemu_init_main_loop(void)
3936 int ret;
3938 ret = qemu_event_init();
3939 if (ret)
3940 return ret;
3942 qemu_cond_init(&qemu_pause_cond);
3943 qemu_mutex_init(&qemu_fair_mutex);
3944 qemu_mutex_init(&qemu_global_mutex);
3945 qemu_mutex_lock(&qemu_global_mutex);
3947 unblock_io_signals();
3948 qemu_thread_self(&io_thread);
3950 return 0;
3953 static void qemu_wait_io_event(CPUState *env)
3955 while (!tcg_has_work())
3956 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3958 qemu_mutex_unlock(&qemu_global_mutex);
3961 * Users of qemu_global_mutex can be starved, having no chance
3962 * to acquire it since this path will get to it first.
3963 * So use another lock to provide fairness.
3965 qemu_mutex_lock(&qemu_fair_mutex);
3966 qemu_mutex_unlock(&qemu_fair_mutex);
3968 qemu_mutex_lock(&qemu_global_mutex);
3969 if (env->stop) {
3970 env->stop = 0;
3971 env->stopped = 1;
3972 qemu_cond_signal(&qemu_pause_cond);
3976 static int qemu_cpu_exec(CPUState *env);
3978 static void *kvm_cpu_thread_fn(void *arg)
3980 CPUState *env = arg;
3982 block_io_signals();
3983 qemu_thread_self(env->thread);
3985 /* signal CPU creation */
3986 qemu_mutex_lock(&qemu_global_mutex);
3987 env->created = 1;
3988 qemu_cond_signal(&qemu_cpu_cond);
3990 /* and wait for machine initialization */
3991 while (!qemu_system_ready)
3992 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3994 while (1) {
3995 if (cpu_can_run(env))
3996 qemu_cpu_exec(env);
3997 qemu_wait_io_event(env);
4000 return NULL;
4003 static void tcg_cpu_exec(void);
4005 static void *tcg_cpu_thread_fn(void *arg)
4007 CPUState *env = arg;
4009 block_io_signals();
4010 qemu_thread_self(env->thread);
4012 /* signal CPU creation */
4013 qemu_mutex_lock(&qemu_global_mutex);
4014 for (env = first_cpu; env != NULL; env = env->next_cpu)
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 tcg_cpu_exec();
4024 qemu_wait_io_event(cur_cpu);
4027 return NULL;
4030 void qemu_cpu_kick(void *_env)
4032 CPUState *env = _env;
4033 qemu_cond_broadcast(env->halt_cond);
4034 if (kvm_enabled())
4035 qemu_thread_signal(env->thread, SIGUSR1);
4038 int qemu_cpu_self(void *env)
4040 return (cpu_single_env != NULL);
4043 static void cpu_signal(int sig)
4045 if (cpu_single_env)
4046 cpu_exit(cpu_single_env);
4049 static void block_io_signals(void)
4051 sigset_t set;
4052 struct sigaction sigact;
4054 sigemptyset(&set);
4055 sigaddset(&set, SIGUSR2);
4056 sigaddset(&set, SIGIO);
4057 sigaddset(&set, SIGALRM);
4058 pthread_sigmask(SIG_BLOCK, &set, NULL);
4060 sigemptyset(&set);
4061 sigaddset(&set, SIGUSR1);
4062 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4064 memset(&sigact, 0, sizeof(sigact));
4065 sigact.sa_handler = cpu_signal;
4066 sigaction(SIGUSR1, &sigact, NULL);
4069 static void unblock_io_signals(void)
4071 sigset_t set;
4073 sigemptyset(&set);
4074 sigaddset(&set, SIGUSR2);
4075 sigaddset(&set, SIGIO);
4076 sigaddset(&set, SIGALRM);
4077 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4079 sigemptyset(&set);
4080 sigaddset(&set, SIGUSR1);
4081 pthread_sigmask(SIG_BLOCK, &set, NULL);
4084 static void qemu_signal_lock(unsigned int msecs)
4086 qemu_mutex_lock(&qemu_fair_mutex);
4088 while (qemu_mutex_trylock(&qemu_global_mutex)) {
4089 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
4090 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
4091 break;
4093 qemu_mutex_unlock(&qemu_fair_mutex);
4096 static void qemu_mutex_lock_iothread(void)
4098 if (kvm_enabled()) {
4099 qemu_mutex_lock(&qemu_fair_mutex);
4100 qemu_mutex_lock(&qemu_global_mutex);
4101 qemu_mutex_unlock(&qemu_fair_mutex);
4102 } else
4103 qemu_signal_lock(100);
4106 static void qemu_mutex_unlock_iothread(void)
4108 qemu_mutex_unlock(&qemu_global_mutex);
4111 static int all_vcpus_paused(void)
4113 CPUState *penv = first_cpu;
4115 while (penv) {
4116 if (!penv->stopped)
4117 return 0;
4118 penv = (CPUState *)penv->next_cpu;
4121 return 1;
4124 static void pause_all_vcpus(void)
4126 CPUState *penv = first_cpu;
4128 while (penv) {
4129 penv->stop = 1;
4130 qemu_thread_signal(penv->thread, SIGUSR1);
4131 qemu_cpu_kick(penv);
4132 penv = (CPUState *)penv->next_cpu;
4135 while (!all_vcpus_paused()) {
4136 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
4137 penv = first_cpu;
4138 while (penv) {
4139 qemu_thread_signal(penv->thread, SIGUSR1);
4140 penv = (CPUState *)penv->next_cpu;
4145 static void resume_all_vcpus(void)
4147 CPUState *penv = first_cpu;
4149 while (penv) {
4150 penv->stop = 0;
4151 penv->stopped = 0;
4152 qemu_thread_signal(penv->thread, SIGUSR1);
4153 qemu_cpu_kick(penv);
4154 penv = (CPUState *)penv->next_cpu;
4158 static void tcg_init_vcpu(void *_env)
4160 CPUState *env = _env;
4161 /* share a single thread for all cpus with TCG */
4162 if (!tcg_cpu_thread) {
4163 env->thread = qemu_mallocz(sizeof(QemuThread));
4164 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4165 qemu_cond_init(env->halt_cond);
4166 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
4167 while (env->created == 0)
4168 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4169 tcg_cpu_thread = env->thread;
4170 tcg_halt_cond = env->halt_cond;
4171 } else {
4172 env->thread = tcg_cpu_thread;
4173 env->halt_cond = tcg_halt_cond;
4177 static void kvm_start_vcpu(CPUState *env)
4179 kvm_init_vcpu(env);
4180 env->thread = qemu_mallocz(sizeof(QemuThread));
4181 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4182 qemu_cond_init(env->halt_cond);
4183 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
4184 while (env->created == 0)
4185 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4188 void qemu_init_vcpu(void *_env)
4190 CPUState *env = _env;
4192 if (kvm_enabled())
4193 kvm_start_vcpu(env);
4194 else
4195 tcg_init_vcpu(env);
4198 void qemu_notify_event(void)
4200 qemu_event_increment();
4203 void vm_stop(int reason)
4205 QemuThread me;
4206 qemu_thread_self(&me);
4208 if (!qemu_thread_equal(&me, &io_thread)) {
4209 qemu_system_vmstop_request(reason);
4211 * FIXME: should not return to device code in case
4212 * vm_stop() has been requested.
4214 if (cpu_single_env) {
4215 cpu_exit(cpu_single_env);
4216 cpu_single_env->stop = 1;
4218 return;
4220 do_vm_stop(reason);
4223 #endif
4226 #ifdef _WIN32
4227 static void host_main_loop_wait(int *timeout)
4229 int ret, ret2, i;
4230 PollingEntry *pe;
4233 /* XXX: need to suppress polling by better using win32 events */
4234 ret = 0;
4235 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4236 ret |= pe->func(pe->opaque);
4238 if (ret == 0) {
4239 int err;
4240 WaitObjects *w = &wait_objects;
4242 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4243 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4244 if (w->func[ret - WAIT_OBJECT_0])
4245 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4247 /* Check for additional signaled events */
4248 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4250 /* Check if event is signaled */
4251 ret2 = WaitForSingleObject(w->events[i], 0);
4252 if(ret2 == WAIT_OBJECT_0) {
4253 if (w->func[i])
4254 w->func[i](w->opaque[i]);
4255 } else if (ret2 == WAIT_TIMEOUT) {
4256 } else {
4257 err = GetLastError();
4258 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4261 } else if (ret == WAIT_TIMEOUT) {
4262 } else {
4263 err = GetLastError();
4264 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4268 *timeout = 0;
4270 #else
4271 static void host_main_loop_wait(int *timeout)
4274 #endif
4276 void main_loop_wait(int timeout)
4278 IOHandlerRecord *ioh;
4279 fd_set rfds, wfds, xfds;
4280 int ret, nfds;
4281 struct timeval tv;
4283 qemu_bh_update_timeout(&timeout);
4285 host_main_loop_wait(&timeout);
4287 /* poll any events */
4288 /* XXX: separate device handlers from system ones */
4289 nfds = -1;
4290 FD_ZERO(&rfds);
4291 FD_ZERO(&wfds);
4292 FD_ZERO(&xfds);
4293 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4294 if (ioh->deleted)
4295 continue;
4296 if (ioh->fd_read &&
4297 (!ioh->fd_read_poll ||
4298 ioh->fd_read_poll(ioh->opaque) != 0)) {
4299 FD_SET(ioh->fd, &rfds);
4300 if (ioh->fd > nfds)
4301 nfds = ioh->fd;
4303 if (ioh->fd_write) {
4304 FD_SET(ioh->fd, &wfds);
4305 if (ioh->fd > nfds)
4306 nfds = ioh->fd;
4310 tv.tv_sec = timeout / 1000;
4311 tv.tv_usec = (timeout % 1000) * 1000;
4313 #if defined(CONFIG_SLIRP)
4314 if (slirp_is_inited()) {
4315 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4317 #endif
4318 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4319 if (ret > 0) {
4320 IOHandlerRecord **pioh;
4322 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4323 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4324 ioh->fd_read(ioh->opaque);
4325 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
4326 FD_CLR(ioh->fd, &rfds);
4328 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4329 ioh->fd_write(ioh->opaque);
4333 /* remove deleted IO handlers */
4334 pioh = &first_io_handler;
4335 while (*pioh) {
4336 ioh = *pioh;
4337 if (ioh->deleted) {
4338 *pioh = ioh->next;
4339 qemu_free(ioh);
4340 } else
4341 pioh = &ioh->next;
4344 #if defined(CONFIG_SLIRP)
4345 if (slirp_is_inited()) {
4346 if (ret < 0) {
4347 FD_ZERO(&rfds);
4348 FD_ZERO(&wfds);
4349 FD_ZERO(&xfds);
4351 slirp_select_poll(&rfds, &wfds, &xfds);
4353 #endif
4355 /* rearm timer, if not periodic */
4356 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4357 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4358 qemu_rearm_alarm_timer(alarm_timer);
4361 /* vm time timers */
4362 if (vm_running) {
4363 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4364 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4365 qemu_get_clock(vm_clock));
4368 /* real time timers */
4369 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4370 qemu_get_clock(rt_clock));
4372 /* Check bottom-halves last in case any of the earlier events triggered
4373 them. */
4374 qemu_bh_poll();
4378 static int qemu_cpu_exec(CPUState *env)
4380 int ret;
4381 #ifdef CONFIG_PROFILER
4382 int64_t ti;
4383 #endif
4385 #ifdef CONFIG_PROFILER
4386 ti = profile_getclock();
4387 #endif
4388 if (use_icount) {
4389 int64_t count;
4390 int decr;
4391 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4392 env->icount_decr.u16.low = 0;
4393 env->icount_extra = 0;
4394 count = qemu_next_deadline();
4395 count = (count + (1 << icount_time_shift) - 1)
4396 >> icount_time_shift;
4397 qemu_icount += count;
4398 decr = (count > 0xffff) ? 0xffff : count;
4399 count -= decr;
4400 env->icount_decr.u16.low = decr;
4401 env->icount_extra = count;
4403 ret = cpu_exec(env);
4404 #ifdef CONFIG_PROFILER
4405 qemu_time += profile_getclock() - ti;
4406 #endif
4407 if (use_icount) {
4408 /* Fold pending instructions back into the
4409 instruction counter, and clear the interrupt flag. */
4410 qemu_icount -= (env->icount_decr.u16.low
4411 + env->icount_extra);
4412 env->icount_decr.u32 = 0;
4413 env->icount_extra = 0;
4415 return ret;
4418 static void tcg_cpu_exec(void)
4420 int ret = 0;
4422 if (next_cpu == NULL)
4423 next_cpu = first_cpu;
4424 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4425 CPUState *env = cur_cpu = next_cpu;
4427 if (!vm_running)
4428 break;
4429 if (timer_alarm_pending) {
4430 timer_alarm_pending = 0;
4431 break;
4433 if (cpu_can_run(env))
4434 ret = qemu_cpu_exec(env);
4435 if (ret == EXCP_DEBUG) {
4436 gdb_set_stop_cpu(env);
4437 debug_requested = 1;
4438 break;
4443 static int cpu_has_work(CPUState *env)
4445 if (env->stop)
4446 return 1;
4447 if (env->stopped)
4448 return 0;
4449 if (!env->halted)
4450 return 1;
4451 if (qemu_cpu_has_work(env))
4452 return 1;
4453 return 0;
4456 static int tcg_has_work(void)
4458 CPUState *env;
4460 for (env = first_cpu; env != NULL; env = env->next_cpu)
4461 if (cpu_has_work(env))
4462 return 1;
4463 return 0;
4466 static int qemu_calculate_timeout(void)
4468 #ifndef CONFIG_IOTHREAD
4469 int timeout;
4471 if (!vm_running)
4472 timeout = 5000;
4473 else if (tcg_has_work())
4474 timeout = 0;
4475 else if (!use_icount)
4476 timeout = 5000;
4477 else {
4478 /* XXX: use timeout computed from timers */
4479 int64_t add;
4480 int64_t delta;
4481 /* Advance virtual time to the next event. */
4482 if (use_icount == 1) {
4483 /* When not using an adaptive execution frequency
4484 we tend to get badly out of sync with real time,
4485 so just delay for a reasonable amount of time. */
4486 delta = 0;
4487 } else {
4488 delta = cpu_get_icount() - cpu_get_clock();
4490 if (delta > 0) {
4491 /* If virtual time is ahead of real time then just
4492 wait for IO. */
4493 timeout = (delta / 1000000) + 1;
4494 } else {
4495 /* Wait for either IO to occur or the next
4496 timer event. */
4497 add = qemu_next_deadline();
4498 /* We advance the timer before checking for IO.
4499 Limit the amount we advance so that early IO
4500 activity won't get the guest too far ahead. */
4501 if (add > 10000000)
4502 add = 10000000;
4503 delta += add;
4504 add = (add + (1 << icount_time_shift) - 1)
4505 >> icount_time_shift;
4506 qemu_icount += add;
4507 timeout = delta / 1000000;
4508 if (timeout < 0)
4509 timeout = 0;
4513 return timeout;
4514 #else /* CONFIG_IOTHREAD */
4515 return 1000;
4516 #endif
4519 static int vm_can_run(void)
4521 if (powerdown_requested)
4522 return 0;
4523 if (reset_requested)
4524 return 0;
4525 if (shutdown_requested)
4526 return 0;
4527 if (debug_requested)
4528 return 0;
4529 return 1;
4532 static void main_loop(void)
4534 int r;
4536 if (kvm_enabled()) {
4537 kvm_main_loop();
4538 cpu_disable_ticks();
4539 return;
4542 #ifdef CONFIG_IOTHREAD
4543 qemu_system_ready = 1;
4544 qemu_cond_broadcast(&qemu_system_cond);
4545 #endif
4547 for (;;) {
4548 do {
4549 #ifdef CONFIG_PROFILER
4550 int64_t ti;
4551 #endif
4552 #ifndef CONFIG_IOTHREAD
4553 tcg_cpu_exec();
4554 #endif
4555 #ifdef CONFIG_PROFILER
4556 ti = profile_getclock();
4557 #endif
4558 main_loop_wait(qemu_calculate_timeout());
4559 #ifdef CONFIG_PROFILER
4560 dev_time += profile_getclock() - ti;
4561 #endif
4562 } while (vm_can_run());
4564 if (qemu_debug_requested())
4565 vm_stop(EXCP_DEBUG);
4566 if (qemu_shutdown_requested()) {
4567 if (no_shutdown) {
4568 vm_stop(0);
4569 no_shutdown = 0;
4570 } else
4571 break;
4573 if (qemu_reset_requested()) {
4574 pause_all_vcpus();
4575 qemu_system_reset();
4576 resume_all_vcpus();
4578 if (qemu_powerdown_requested())
4579 qemu_system_powerdown();
4580 if ((r = qemu_vmstop_requested()))
4581 vm_stop(r);
4583 pause_all_vcpus();
4586 static void version(void)
4588 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4591 static void help(int exitcode)
4593 version();
4594 printf("usage: %s [options] [disk_image]\n"
4595 "\n"
4596 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4597 "\n"
4598 #define DEF(option, opt_arg, opt_enum, opt_help) \
4599 opt_help
4600 #define DEFHEADING(text) stringify(text) "\n"
4601 #include "qemu-options.h"
4602 #undef DEF
4603 #undef DEFHEADING
4604 #undef GEN_DOCS
4605 "\n"
4606 "During emulation, the following keys are useful:\n"
4607 "ctrl-alt-f toggle full screen\n"
4608 "ctrl-alt-n switch to virtual console 'n'\n"
4609 "ctrl-alt toggle mouse and keyboard grab\n"
4610 "\n"
4611 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4613 "qemu",
4614 DEFAULT_RAM_SIZE,
4615 #ifndef _WIN32
4616 DEFAULT_NETWORK_SCRIPT,
4617 DEFAULT_NETWORK_DOWN_SCRIPT,
4618 #endif
4619 DEFAULT_GDBSTUB_PORT,
4620 "/tmp/qemu.log");
4621 exit(exitcode);
4624 #define HAS_ARG 0x0001
4626 enum {
4627 #define DEF(option, opt_arg, opt_enum, opt_help) \
4628 opt_enum,
4629 #define DEFHEADING(text)
4630 #include "qemu-options.h"
4631 #undef DEF
4632 #undef DEFHEADING
4633 #undef GEN_DOCS
4636 typedef struct QEMUOption {
4637 const char *name;
4638 int flags;
4639 int index;
4640 } QEMUOption;
4642 static const QEMUOption qemu_options[] = {
4643 { "h", 0, QEMU_OPTION_h },
4644 #define DEF(option, opt_arg, opt_enum, opt_help) \
4645 { option, opt_arg, opt_enum },
4646 #define DEFHEADING(text)
4647 #include "qemu-options.h"
4648 #undef DEF
4649 #undef DEFHEADING
4650 #undef GEN_DOCS
4651 { NULL },
4654 #ifdef HAS_AUDIO
4655 struct soundhw soundhw[] = {
4656 #ifdef HAS_AUDIO_CHOICE
4657 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4659 "pcspk",
4660 "PC speaker",
4663 { .init_isa = pcspk_audio_init }
4665 #endif
4667 #ifdef CONFIG_SB16
4669 "sb16",
4670 "Creative Sound Blaster 16",
4673 { .init_isa = SB16_init }
4675 #endif
4677 #ifdef CONFIG_CS4231A
4679 "cs4231a",
4680 "CS4231A",
4683 { .init_isa = cs4231a_init }
4685 #endif
4687 #ifdef CONFIG_ADLIB
4689 "adlib",
4690 #ifdef HAS_YMF262
4691 "Yamaha YMF262 (OPL3)",
4692 #else
4693 "Yamaha YM3812 (OPL2)",
4694 #endif
4697 { .init_isa = Adlib_init }
4699 #endif
4701 #ifdef CONFIG_GUS
4703 "gus",
4704 "Gravis Ultrasound GF1",
4707 { .init_isa = GUS_init }
4709 #endif
4711 #ifdef CONFIG_AC97
4713 "ac97",
4714 "Intel 82801AA AC97 Audio",
4717 { .init_pci = ac97_init }
4719 #endif
4721 #ifdef CONFIG_ES1370
4723 "es1370",
4724 "ENSONIQ AudioPCI ES1370",
4727 { .init_pci = es1370_init }
4729 #endif
4731 #endif /* HAS_AUDIO_CHOICE */
4733 { NULL, NULL, 0, 0, { NULL } }
4736 static void select_soundhw (const char *optarg)
4738 struct soundhw *c;
4740 if (*optarg == '?') {
4741 show_valid_cards:
4743 printf ("Valid sound card names (comma separated):\n");
4744 for (c = soundhw; c->name; ++c) {
4745 printf ("%-11s %s\n", c->name, c->descr);
4747 printf ("\n-soundhw all will enable all of the above\n");
4748 exit (*optarg != '?');
4750 else {
4751 size_t l;
4752 const char *p;
4753 char *e;
4754 int bad_card = 0;
4756 if (!strcmp (optarg, "all")) {
4757 for (c = soundhw; c->name; ++c) {
4758 c->enabled = 1;
4760 return;
4763 p = optarg;
4764 while (*p) {
4765 e = strchr (p, ',');
4766 l = !e ? strlen (p) : (size_t) (e - p);
4768 for (c = soundhw; c->name; ++c) {
4769 if (!strncmp (c->name, p, l)) {
4770 c->enabled = 1;
4771 break;
4775 if (!c->name) {
4776 if (l > 80) {
4777 fprintf (stderr,
4778 "Unknown sound card name (too big to show)\n");
4780 else {
4781 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4782 (int) l, p);
4784 bad_card = 1;
4786 p += l + (e != NULL);
4789 if (bad_card)
4790 goto show_valid_cards;
4793 #endif
4795 static void select_vgahw (const char *p)
4797 const char *opts;
4799 cirrus_vga_enabled = 0;
4800 std_vga_enabled = 0;
4801 vmsvga_enabled = 0;
4802 xenfb_enabled = 0;
4803 if (strstart(p, "std", &opts)) {
4804 std_vga_enabled = 1;
4805 } else if (strstart(p, "cirrus", &opts)) {
4806 cirrus_vga_enabled = 1;
4807 } else if (strstart(p, "vmware", &opts)) {
4808 vmsvga_enabled = 1;
4809 } else if (strstart(p, "xenfb", &opts)) {
4810 xenfb_enabled = 1;
4811 } else if (!strstart(p, "none", &opts)) {
4812 invalid_vga:
4813 fprintf(stderr, "Unknown vga type: %s\n", p);
4814 exit(1);
4816 while (*opts) {
4817 const char *nextopt;
4819 if (strstart(opts, ",retrace=", &nextopt)) {
4820 opts = nextopt;
4821 if (strstart(opts, "dumb", &nextopt))
4822 vga_retrace_method = VGA_RETRACE_DUMB;
4823 else if (strstart(opts, "precise", &nextopt))
4824 vga_retrace_method = VGA_RETRACE_PRECISE;
4825 else goto invalid_vga;
4826 } else goto invalid_vga;
4827 opts = nextopt;
4831 #ifdef _WIN32
4832 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4834 exit(STATUS_CONTROL_C_EXIT);
4835 return TRUE;
4837 #endif
4839 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4841 int ret;
4843 if(strlen(str) != 36)
4844 return -1;
4846 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4847 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4848 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4850 if(ret != 16)
4851 return -1;
4853 #ifdef TARGET_I386
4854 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4855 #endif
4857 return 0;
4860 #define MAX_NET_CLIENTS 32
4862 #ifndef _WIN32
4864 static void termsig_handler(int signal)
4866 qemu_system_shutdown_request();
4869 static void sigchld_handler(int signal)
4871 waitpid(-1, NULL, WNOHANG);
4874 static void sighandler_setup(void)
4876 struct sigaction act;
4878 memset(&act, 0, sizeof(act));
4879 act.sa_handler = termsig_handler;
4880 sigaction(SIGINT, &act, NULL);
4881 sigaction(SIGHUP, &act, NULL);
4882 sigaction(SIGTERM, &act, NULL);
4884 act.sa_handler = sigchld_handler;
4885 act.sa_flags = SA_NOCLDSTOP;
4886 sigaction(SIGCHLD, &act, NULL);
4889 #endif
4891 #ifdef _WIN32
4892 /* Look for support files in the same directory as the executable. */
4893 static char *find_datadir(const char *argv0)
4895 char *p;
4896 char buf[MAX_PATH];
4897 DWORD len;
4899 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4900 if (len == 0) {
4901 return NULL;
4904 buf[len] = 0;
4905 p = buf + len - 1;
4906 while (p != buf && *p != '\\')
4907 p--;
4908 *p = 0;
4909 if (access(buf, R_OK) == 0) {
4910 return qemu_strdup(buf);
4912 return NULL;
4914 #else /* !_WIN32 */
4916 /* Find a likely location for support files using the location of the binary.
4917 For installed binaries this will be "$bindir/../share/qemu". When
4918 running from the build tree this will be "$bindir/../pc-bios". */
4919 #define SHARE_SUFFIX "/share/qemu"
4920 #define BUILD_SUFFIX "/pc-bios"
4921 static char *find_datadir(const char *argv0)
4923 char *dir;
4924 char *p = NULL;
4925 char *res;
4926 #ifdef PATH_MAX
4927 char buf[PATH_MAX];
4928 #endif
4929 size_t max_len;
4931 #if defined(__linux__)
4933 int len;
4934 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4935 if (len > 0) {
4936 buf[len] = 0;
4937 p = buf;
4940 #elif defined(__FreeBSD__)
4942 int len;
4943 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4944 if (len > 0) {
4945 buf[len] = 0;
4946 p = buf;
4949 #endif
4950 /* If we don't have any way of figuring out the actual executable
4951 location then try argv[0]. */
4952 if (!p) {
4953 #ifdef PATH_MAX
4954 p = buf;
4955 #endif
4956 p = realpath(argv0, p);
4957 if (!p) {
4958 return NULL;
4961 dir = dirname(p);
4962 dir = dirname(dir);
4964 max_len = strlen(dir) +
4965 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4966 res = qemu_mallocz(max_len);
4967 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4968 if (access(res, R_OK)) {
4969 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4970 if (access(res, R_OK)) {
4971 qemu_free(res);
4972 res = NULL;
4975 #ifndef PATH_MAX
4976 free(p);
4977 #endif
4978 return res;
4980 #undef SHARE_SUFFIX
4981 #undef BUILD_SUFFIX
4982 #endif
4984 char *qemu_find_file(int type, const char *name)
4986 int len;
4987 const char *subdir;
4988 char *buf;
4990 /* If name contains path separators then try it as a straight path. */
4991 if ((strchr(name, '/') || strchr(name, '\\'))
4992 && access(name, R_OK) == 0) {
4993 return strdup(name);
4995 switch (type) {
4996 case QEMU_FILE_TYPE_BIOS:
4997 subdir = "";
4998 break;
4999 case QEMU_FILE_TYPE_KEYMAP:
5000 subdir = "keymaps/";
5001 break;
5002 default:
5003 abort();
5005 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
5006 buf = qemu_mallocz(len);
5007 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
5008 if (access(buf, R_OK)) {
5009 qemu_free(buf);
5010 return NULL;
5012 return buf;
5015 int main(int argc, char **argv, char **envp)
5017 const char *gdbstub_dev = NULL;
5018 uint32_t boot_devices_bitmap = 0;
5019 int i;
5020 int snapshot, linux_boot, net_boot;
5021 const char *initrd_filename;
5022 const char *kernel_filename, *kernel_cmdline;
5023 const char *boot_devices = "";
5024 DisplayState *ds;
5025 DisplayChangeListener *dcl;
5026 int cyls, heads, secs, translation;
5027 const char *net_clients[MAX_NET_CLIENTS];
5028 int nb_net_clients;
5029 const char *bt_opts[MAX_BT_CMDLINE];
5030 int nb_bt_opts;
5031 int hda_index;
5032 int optind;
5033 const char *r, *optarg;
5034 CharDriverState *monitor_hd = NULL;
5035 const char *monitor_device;
5036 const char *serial_devices[MAX_SERIAL_PORTS];
5037 int serial_device_index;
5038 const char *parallel_devices[MAX_PARALLEL_PORTS];
5039 int parallel_device_index;
5040 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
5041 int virtio_console_index;
5042 const char *loadvm = NULL;
5043 QEMUMachine *machine;
5044 const char *cpu_model;
5045 const char *usb_devices[MAX_USB_CMDLINE];
5046 int usb_devices_index;
5047 #ifndef _WIN32
5048 int fds[2];
5049 #endif
5050 int tb_size;
5051 const char *pid_file = NULL;
5052 const char *incoming = NULL;
5053 #ifndef _WIN32
5054 int fd = 0;
5055 struct passwd *pwd = NULL;
5056 const char *chroot_dir = NULL;
5057 const char *run_as = NULL;
5058 #endif
5059 CPUState *env;
5060 int show_vnc_port = 0;
5062 qemu_cache_utils_init(envp);
5064 LIST_INIT (&vm_change_state_head);
5065 #ifndef _WIN32
5067 struct sigaction act;
5068 sigfillset(&act.sa_mask);
5069 act.sa_flags = 0;
5070 act.sa_handler = SIG_IGN;
5071 sigaction(SIGPIPE, &act, NULL);
5073 #else
5074 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5075 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5076 QEMU to run on a single CPU */
5078 HANDLE h;
5079 DWORD mask, smask;
5080 int i;
5081 h = GetCurrentProcess();
5082 if (GetProcessAffinityMask(h, &mask, &smask)) {
5083 for(i = 0; i < 32; i++) {
5084 if (mask & (1 << i))
5085 break;
5087 if (i != 32) {
5088 mask = 1 << i;
5089 SetProcessAffinityMask(h, mask);
5093 #endif
5095 module_call_init(MODULE_INIT_MACHINE);
5096 machine = find_default_machine();
5097 cpu_model = NULL;
5098 initrd_filename = NULL;
5099 ram_size = 0;
5100 snapshot = 0;
5101 kernel_filename = NULL;
5102 kernel_cmdline = "";
5103 cyls = heads = secs = 0;
5104 translation = BIOS_ATA_TRANSLATION_AUTO;
5105 monitor_device = "vc:80Cx24C";
5107 serial_devices[0] = "vc:80Cx24C";
5108 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5109 serial_devices[i] = NULL;
5110 serial_device_index = 0;
5112 parallel_devices[0] = "vc:80Cx24C";
5113 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5114 parallel_devices[i] = NULL;
5115 parallel_device_index = 0;
5117 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
5118 virtio_consoles[i] = NULL;
5119 virtio_console_index = 0;
5121 for (i = 0; i < MAX_NODES; i++) {
5122 node_mem[i] = 0;
5123 node_cpumask[i] = 0;
5126 usb_devices_index = 0;
5127 assigned_devices_index = 0;
5129 nb_net_clients = 0;
5130 nb_bt_opts = 0;
5131 nb_drives = 0;
5132 nb_drives_opt = 0;
5133 nb_numa_nodes = 0;
5134 hda_index = -1;
5136 nb_nics = 0;
5138 tb_size = 0;
5139 autostart= 1;
5141 register_watchdogs();
5143 optind = 1;
5144 for(;;) {
5145 if (optind >= argc)
5146 break;
5147 r = argv[optind];
5148 if (r[0] != '-') {
5149 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5150 } else {
5151 const QEMUOption *popt;
5153 optind++;
5154 /* Treat --foo the same as -foo. */
5155 if (r[1] == '-')
5156 r++;
5157 popt = qemu_options;
5158 for(;;) {
5159 if (!popt->name) {
5160 fprintf(stderr, "%s: invalid option -- '%s'\n",
5161 argv[0], r);
5162 exit(1);
5164 if (!strcmp(popt->name, r + 1))
5165 break;
5166 popt++;
5168 if (popt->flags & HAS_ARG) {
5169 if (optind >= argc) {
5170 fprintf(stderr, "%s: option '%s' requires an argument\n",
5171 argv[0], r);
5172 exit(1);
5174 optarg = argv[optind++];
5175 } else {
5176 optarg = NULL;
5179 switch(popt->index) {
5180 case QEMU_OPTION_M:
5181 machine = find_machine(optarg);
5182 if (!machine) {
5183 QEMUMachine *m;
5184 printf("Supported machines are:\n");
5185 for(m = first_machine; m != NULL; m = m->next) {
5186 printf("%-10s %s%s\n",
5187 m->name, m->desc,
5188 m->is_default ? " (default)" : "");
5190 exit(*optarg != '?');
5192 break;
5193 case QEMU_OPTION_cpu:
5194 /* hw initialization will check this */
5195 if (*optarg == '?') {
5196 /* XXX: implement xxx_cpu_list for targets that still miss it */
5197 #if defined(cpu_list)
5198 cpu_list(stdout, &fprintf);
5199 #endif
5200 exit(0);
5201 } else {
5202 cpu_model = optarg;
5204 break;
5205 case QEMU_OPTION_initrd:
5206 initrd_filename = optarg;
5207 break;
5208 case QEMU_OPTION_hda:
5209 if (cyls == 0)
5210 hda_index = drive_add(optarg, HD_ALIAS, 0);
5211 else
5212 hda_index = drive_add(optarg, HD_ALIAS
5213 ",cyls=%d,heads=%d,secs=%d%s",
5214 0, cyls, heads, secs,
5215 translation == BIOS_ATA_TRANSLATION_LBA ?
5216 ",trans=lba" :
5217 translation == BIOS_ATA_TRANSLATION_NONE ?
5218 ",trans=none" : "");
5219 break;
5220 case QEMU_OPTION_hdb:
5221 case QEMU_OPTION_hdc:
5222 case QEMU_OPTION_hdd:
5223 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5224 break;
5225 case QEMU_OPTION_drive:
5226 drive_add(NULL, "%s", optarg);
5227 break;
5228 case QEMU_OPTION_mtdblock:
5229 drive_add(optarg, MTD_ALIAS);
5230 break;
5231 case QEMU_OPTION_sd:
5232 drive_add(optarg, SD_ALIAS);
5233 break;
5234 case QEMU_OPTION_pflash:
5235 drive_add(optarg, PFLASH_ALIAS);
5236 break;
5237 case QEMU_OPTION_snapshot:
5238 snapshot = 1;
5239 break;
5240 case QEMU_OPTION_hdachs:
5242 const char *p;
5243 p = optarg;
5244 cyls = strtol(p, (char **)&p, 0);
5245 if (cyls < 1 || cyls > 16383)
5246 goto chs_fail;
5247 if (*p != ',')
5248 goto chs_fail;
5249 p++;
5250 heads = strtol(p, (char **)&p, 0);
5251 if (heads < 1 || heads > 16)
5252 goto chs_fail;
5253 if (*p != ',')
5254 goto chs_fail;
5255 p++;
5256 secs = strtol(p, (char **)&p, 0);
5257 if (secs < 1 || secs > 63)
5258 goto chs_fail;
5259 if (*p == ',') {
5260 p++;
5261 if (!strcmp(p, "none"))
5262 translation = BIOS_ATA_TRANSLATION_NONE;
5263 else if (!strcmp(p, "lba"))
5264 translation = BIOS_ATA_TRANSLATION_LBA;
5265 else if (!strcmp(p, "auto"))
5266 translation = BIOS_ATA_TRANSLATION_AUTO;
5267 else
5268 goto chs_fail;
5269 } else if (*p != '\0') {
5270 chs_fail:
5271 fprintf(stderr, "qemu: invalid physical CHS format\n");
5272 exit(1);
5274 if (hda_index != -1)
5275 snprintf(drives_opt[hda_index].opt,
5276 sizeof(drives_opt[hda_index].opt),
5277 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5278 0, cyls, heads, secs,
5279 translation == BIOS_ATA_TRANSLATION_LBA ?
5280 ",trans=lba" :
5281 translation == BIOS_ATA_TRANSLATION_NONE ?
5282 ",trans=none" : "");
5284 break;
5285 case QEMU_OPTION_numa:
5286 if (nb_numa_nodes >= MAX_NODES) {
5287 fprintf(stderr, "qemu: too many NUMA nodes\n");
5288 exit(1);
5290 numa_add(optarg);
5291 break;
5292 case QEMU_OPTION_nographic:
5293 display_type = DT_NOGRAPHIC;
5294 break;
5295 #ifdef CONFIG_CURSES
5296 case QEMU_OPTION_curses:
5297 display_type = DT_CURSES;
5298 break;
5299 #endif
5300 case QEMU_OPTION_portrait:
5301 graphic_rotate = 1;
5302 break;
5303 case QEMU_OPTION_kernel:
5304 kernel_filename = optarg;
5305 break;
5306 case QEMU_OPTION_append:
5307 kernel_cmdline = optarg;
5308 break;
5309 case QEMU_OPTION_cdrom:
5310 drive_add(optarg, CDROM_ALIAS);
5311 break;
5312 case QEMU_OPTION_boot:
5313 boot_devices = optarg;
5314 /* We just do some generic consistency checks */
5316 /* Could easily be extended to 64 devices if needed */
5317 const char *p;
5319 boot_devices_bitmap = 0;
5320 for (p = boot_devices; *p != '\0'; p++) {
5321 /* Allowed boot devices are:
5322 * a b : floppy disk drives
5323 * c ... f : IDE disk drives
5324 * g ... m : machine implementation dependant drives
5325 * n ... p : network devices
5326 * It's up to each machine implementation to check
5327 * if the given boot devices match the actual hardware
5328 * implementation and firmware features.
5330 if (*p < 'a' || *p > 'q') {
5331 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5332 exit(1);
5334 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5335 fprintf(stderr,
5336 "Boot device '%c' was given twice\n",*p);
5337 exit(1);
5339 boot_devices_bitmap |= 1 << (*p - 'a');
5342 break;
5343 case QEMU_OPTION_fda:
5344 case QEMU_OPTION_fdb:
5345 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5346 break;
5347 #ifdef TARGET_I386
5348 case QEMU_OPTION_no_fd_bootchk:
5349 fd_bootchk = 0;
5350 break;
5351 #endif
5352 case QEMU_OPTION_net:
5353 if (nb_net_clients >= MAX_NET_CLIENTS) {
5354 fprintf(stderr, "qemu: too many network clients\n");
5355 exit(1);
5357 net_clients[nb_net_clients] = optarg;
5358 nb_net_clients++;
5359 break;
5360 #ifdef CONFIG_SLIRP
5361 case QEMU_OPTION_tftp:
5362 tftp_prefix = optarg;
5363 break;
5364 case QEMU_OPTION_bootp:
5365 bootp_filename = optarg;
5366 break;
5367 #ifndef _WIN32
5368 case QEMU_OPTION_smb:
5369 net_slirp_smb(optarg);
5370 break;
5371 #endif
5372 case QEMU_OPTION_redir:
5373 net_slirp_redir(NULL, optarg, NULL);
5374 break;
5375 #endif
5376 case QEMU_OPTION_bt:
5377 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5378 fprintf(stderr, "qemu: too many bluetooth options\n");
5379 exit(1);
5381 bt_opts[nb_bt_opts++] = optarg;
5382 break;
5383 #ifdef HAS_AUDIO
5384 case QEMU_OPTION_audio_help:
5385 AUD_help ();
5386 exit (0);
5387 break;
5388 case QEMU_OPTION_soundhw:
5389 select_soundhw (optarg);
5390 break;
5391 #endif
5392 case QEMU_OPTION_h:
5393 help(0);
5394 break;
5395 case QEMU_OPTION_version:
5396 version();
5397 exit(0);
5398 break;
5399 case QEMU_OPTION_m: {
5400 uint64_t value;
5401 char *ptr;
5403 value = strtoul(optarg, &ptr, 10);
5404 switch (*ptr) {
5405 case 0: case 'M': case 'm':
5406 value <<= 20;
5407 break;
5408 case 'G': case 'g':
5409 value <<= 30;
5410 break;
5411 default:
5412 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5413 exit(1);
5416 /* On 32-bit hosts, QEMU is limited by virtual address space */
5417 if (value > (2047 << 20)
5418 #ifndef CONFIG_KQEMU
5419 && HOST_LONG_BITS == 32
5420 #endif
5422 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5423 exit(1);
5425 if (value != (uint64_t)(ram_addr_t)value) {
5426 fprintf(stderr, "qemu: ram size too large\n");
5427 exit(1);
5429 ram_size = value;
5430 break;
5432 case QEMU_OPTION_d:
5434 int mask;
5435 const CPULogItem *item;
5437 mask = cpu_str_to_log_mask(optarg);
5438 if (!mask) {
5439 printf("Log items (comma separated):\n");
5440 for(item = cpu_log_items; item->mask != 0; item++) {
5441 printf("%-10s %s\n", item->name, item->help);
5443 exit(1);
5445 cpu_set_log(mask);
5447 break;
5448 case QEMU_OPTION_s:
5449 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5450 break;
5451 case QEMU_OPTION_gdb:
5452 gdbstub_dev = optarg;
5453 break;
5454 case QEMU_OPTION_L:
5455 data_dir = optarg;
5456 break;
5457 case QEMU_OPTION_bios:
5458 bios_name = optarg;
5459 break;
5460 case QEMU_OPTION_singlestep:
5461 singlestep = 1;
5462 break;
5463 case QEMU_OPTION_S:
5464 autostart = 0;
5465 break;
5466 #ifndef _WIN32
5467 case QEMU_OPTION_k:
5468 keyboard_layout = optarg;
5469 break;
5470 #endif
5471 case QEMU_OPTION_localtime:
5472 rtc_utc = 0;
5473 break;
5474 case QEMU_OPTION_vga:
5475 select_vgahw (optarg);
5476 break;
5477 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5478 case QEMU_OPTION_g:
5480 const char *p;
5481 int w, h, depth;
5482 p = optarg;
5483 w = strtol(p, (char **)&p, 10);
5484 if (w <= 0) {
5485 graphic_error:
5486 fprintf(stderr, "qemu: invalid resolution or depth\n");
5487 exit(1);
5489 if (*p != 'x')
5490 goto graphic_error;
5491 p++;
5492 h = strtol(p, (char **)&p, 10);
5493 if (h <= 0)
5494 goto graphic_error;
5495 if (*p == 'x') {
5496 p++;
5497 depth = strtol(p, (char **)&p, 10);
5498 if (depth != 8 && depth != 15 && depth != 16 &&
5499 depth != 24 && depth != 32)
5500 goto graphic_error;
5501 } else if (*p == '\0') {
5502 depth = graphic_depth;
5503 } else {
5504 goto graphic_error;
5507 graphic_width = w;
5508 graphic_height = h;
5509 graphic_depth = depth;
5511 break;
5512 #endif
5513 case QEMU_OPTION_echr:
5515 char *r;
5516 term_escape_char = strtol(optarg, &r, 0);
5517 if (r == optarg)
5518 printf("Bad argument to echr\n");
5519 break;
5521 case QEMU_OPTION_monitor:
5522 monitor_device = optarg;
5523 break;
5524 case QEMU_OPTION_serial:
5525 if (serial_device_index >= MAX_SERIAL_PORTS) {
5526 fprintf(stderr, "qemu: too many serial ports\n");
5527 exit(1);
5529 serial_devices[serial_device_index] = optarg;
5530 serial_device_index++;
5531 break;
5532 case QEMU_OPTION_watchdog:
5533 i = select_watchdog(optarg);
5534 if (i > 0)
5535 exit (i == 1 ? 1 : 0);
5536 break;
5537 case QEMU_OPTION_watchdog_action:
5538 if (select_watchdog_action(optarg) == -1) {
5539 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5540 exit(1);
5542 break;
5543 case QEMU_OPTION_virtiocon:
5544 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5545 fprintf(stderr, "qemu: too many virtio consoles\n");
5546 exit(1);
5548 virtio_consoles[virtio_console_index] = optarg;
5549 virtio_console_index++;
5550 break;
5551 case QEMU_OPTION_parallel:
5552 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5553 fprintf(stderr, "qemu: too many parallel ports\n");
5554 exit(1);
5556 parallel_devices[parallel_device_index] = optarg;
5557 parallel_device_index++;
5558 break;
5559 case QEMU_OPTION_loadvm:
5560 loadvm = optarg;
5561 break;
5562 case QEMU_OPTION_full_screen:
5563 full_screen = 1;
5564 break;
5565 #ifdef CONFIG_SDL
5566 case QEMU_OPTION_no_frame:
5567 no_frame = 1;
5568 break;
5569 case QEMU_OPTION_alt_grab:
5570 alt_grab = 1;
5571 break;
5572 case QEMU_OPTION_no_quit:
5573 no_quit = 1;
5574 break;
5575 case QEMU_OPTION_sdl:
5576 display_type = DT_SDL;
5577 break;
5578 #endif
5579 case QEMU_OPTION_pidfile:
5580 pid_file = optarg;
5581 break;
5582 #ifdef TARGET_I386
5583 case QEMU_OPTION_win2k_hack:
5584 win2k_install_hack = 1;
5585 break;
5586 case QEMU_OPTION_rtc_td_hack:
5587 rtc_td_hack = 1;
5588 break;
5589 case QEMU_OPTION_acpitable:
5590 if(acpi_table_add(optarg) < 0) {
5591 fprintf(stderr, "Wrong acpi table provided\n");
5592 exit(1);
5594 break;
5595 case QEMU_OPTION_smbios:
5596 if(smbios_entry_add(optarg) < 0) {
5597 fprintf(stderr, "Wrong smbios provided\n");
5598 exit(1);
5600 break;
5601 #endif
5602 #ifdef CONFIG_KQEMU
5603 case QEMU_OPTION_no_kqemu:
5604 kqemu_allowed = 0;
5605 break;
5606 case QEMU_OPTION_kernel_kqemu:
5607 kqemu_allowed = 2;
5608 break;
5609 #endif
5610 #ifdef CONFIG_KVM
5611 case QEMU_OPTION_enable_kvm:
5612 kvm_allowed = 1;
5613 #ifdef CONFIG_KQEMU
5614 kqemu_allowed = 0;
5615 #endif
5616 break;
5617 #endif
5618 #ifdef USE_KVM
5619 case QEMU_OPTION_no_kvm:
5620 kvm_allowed = 0;
5621 break;
5622 case QEMU_OPTION_no_kvm_irqchip: {
5623 kvm_irqchip = 0;
5624 kvm_pit = 0;
5625 break;
5627 case QEMU_OPTION_no_kvm_pit: {
5628 kvm_pit = 0;
5629 break;
5631 case QEMU_OPTION_no_kvm_pit_reinjection: {
5632 kvm_pit_reinject = 0;
5633 break;
5635 case QEMU_OPTION_enable_nesting: {
5636 kvm_nested = 1;
5637 break;
5639 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5640 case QEMU_OPTION_pcidevice:
5641 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5642 fprintf(stderr, "Too many assigned devices\n");
5643 exit(1);
5645 assigned_devices[assigned_devices_index] = optarg;
5646 assigned_devices_index++;
5647 break;
5648 #endif
5649 #endif
5650 case QEMU_OPTION_usb:
5651 usb_enabled = 1;
5652 break;
5653 case QEMU_OPTION_usbdevice:
5654 usb_enabled = 1;
5655 if (usb_devices_index >= MAX_USB_CMDLINE) {
5656 fprintf(stderr, "Too many USB devices\n");
5657 exit(1);
5659 usb_devices[usb_devices_index] = optarg;
5660 usb_devices_index++;
5661 break;
5662 case QEMU_OPTION_smp:
5663 smp_cpus = atoi(optarg);
5664 if (smp_cpus < 1) {
5665 fprintf(stderr, "Invalid number of CPUs\n");
5666 exit(1);
5668 break;
5669 case QEMU_OPTION_vnc:
5670 display_type = DT_VNC;
5671 vnc_display = optarg;
5672 break;
5673 #ifdef TARGET_I386
5674 case QEMU_OPTION_no_acpi:
5675 acpi_enabled = 0;
5676 break;
5677 case QEMU_OPTION_no_hpet:
5678 no_hpet = 1;
5679 break;
5680 case QEMU_OPTION_no_virtio_balloon:
5681 no_virtio_balloon = 1;
5682 break;
5683 #endif
5684 case QEMU_OPTION_no_reboot:
5685 no_reboot = 1;
5686 break;
5687 case QEMU_OPTION_no_shutdown:
5688 no_shutdown = 1;
5689 break;
5690 case QEMU_OPTION_show_cursor:
5691 cursor_hide = 0;
5692 break;
5693 case QEMU_OPTION_uuid:
5694 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5695 fprintf(stderr, "Fail to parse UUID string."
5696 " Wrong format.\n");
5697 exit(1);
5699 break;
5700 #ifndef _WIN32
5701 case QEMU_OPTION_daemonize:
5702 daemonize = 1;
5703 break;
5704 #endif
5705 case QEMU_OPTION_option_rom:
5706 if (nb_option_roms >= MAX_OPTION_ROMS) {
5707 fprintf(stderr, "Too many option ROMs\n");
5708 exit(1);
5710 option_rom[nb_option_roms] = optarg;
5711 nb_option_roms++;
5712 break;
5713 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5714 case QEMU_OPTION_semihosting:
5715 semihosting_enabled = 1;
5716 break;
5717 #endif
5718 case QEMU_OPTION_tdf:
5719 time_drift_fix = 1;
5720 break;
5721 case QEMU_OPTION_kvm_shadow_memory:
5722 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5723 break;
5724 case QEMU_OPTION_mempath:
5725 mem_path = optarg;
5726 break;
5727 #ifdef MAP_POPULATE
5728 case QEMU_OPTION_mem_prealloc:
5729 mem_prealloc = !mem_prealloc;
5730 break;
5731 #endif
5732 case QEMU_OPTION_name:
5733 qemu_name = optarg;
5734 break;
5735 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5736 case QEMU_OPTION_prom_env:
5737 if (nb_prom_envs >= MAX_PROM_ENVS) {
5738 fprintf(stderr, "Too many prom variables\n");
5739 exit(1);
5741 prom_envs[nb_prom_envs] = optarg;
5742 nb_prom_envs++;
5743 break;
5744 #endif
5745 #ifdef TARGET_ARM
5746 case QEMU_OPTION_old_param:
5747 old_param = 1;
5748 break;
5749 #endif
5750 case QEMU_OPTION_clock:
5751 configure_alarms(optarg);
5752 break;
5753 case QEMU_OPTION_startdate:
5755 struct tm tm;
5756 time_t rtc_start_date;
5757 if (!strcmp(optarg, "now")) {
5758 rtc_date_offset = -1;
5759 } else {
5760 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5761 &tm.tm_year,
5762 &tm.tm_mon,
5763 &tm.tm_mday,
5764 &tm.tm_hour,
5765 &tm.tm_min,
5766 &tm.tm_sec) == 6) {
5767 /* OK */
5768 } else if (sscanf(optarg, "%d-%d-%d",
5769 &tm.tm_year,
5770 &tm.tm_mon,
5771 &tm.tm_mday) == 3) {
5772 tm.tm_hour = 0;
5773 tm.tm_min = 0;
5774 tm.tm_sec = 0;
5775 } else {
5776 goto date_fail;
5778 tm.tm_year -= 1900;
5779 tm.tm_mon--;
5780 rtc_start_date = mktimegm(&tm);
5781 if (rtc_start_date == -1) {
5782 date_fail:
5783 fprintf(stderr, "Invalid date format. Valid format are:\n"
5784 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5785 exit(1);
5787 rtc_date_offset = time(NULL) - rtc_start_date;
5790 break;
5791 case QEMU_OPTION_tb_size:
5792 tb_size = strtol(optarg, NULL, 0);
5793 if (tb_size < 0)
5794 tb_size = 0;
5795 break;
5796 case QEMU_OPTION_icount:
5797 use_icount = 1;
5798 if (strcmp(optarg, "auto") == 0) {
5799 icount_time_shift = -1;
5800 } else {
5801 icount_time_shift = strtol(optarg, NULL, 0);
5803 break;
5804 case QEMU_OPTION_incoming:
5805 incoming = optarg;
5806 break;
5807 #ifndef _WIN32
5808 case QEMU_OPTION_chroot:
5809 chroot_dir = optarg;
5810 break;
5811 case QEMU_OPTION_runas:
5812 run_as = optarg;
5813 break;
5814 case QEMU_OPTION_nvram:
5815 nvram = optarg;
5816 break;
5817 #endif
5818 #ifdef CONFIG_XEN
5819 case QEMU_OPTION_xen_domid:
5820 xen_domid = atoi(optarg);
5821 break;
5822 case QEMU_OPTION_xen_create:
5823 xen_mode = XEN_CREATE;
5824 break;
5825 case QEMU_OPTION_xen_attach:
5826 xen_mode = XEN_ATTACH;
5827 break;
5828 #endif
5833 /* If no data_dir is specified then try to find it relative to the
5834 executable path. */
5835 if (!data_dir) {
5836 data_dir = find_datadir(argv[0]);
5838 /* If all else fails use the install patch specified when building. */
5839 if (!data_dir) {
5840 data_dir = CONFIG_QEMU_SHAREDIR;
5843 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5844 if (kvm_allowed && kqemu_allowed) {
5845 fprintf(stderr,
5846 "You can not enable both KVM and kqemu at the same time\n");
5847 exit(1);
5849 #endif
5851 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5852 if (smp_cpus > machine->max_cpus) {
5853 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5854 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5855 machine->max_cpus);
5856 exit(1);
5859 if (display_type == DT_NOGRAPHIC) {
5860 if (serial_device_index == 0)
5861 serial_devices[0] = "stdio";
5862 if (parallel_device_index == 0)
5863 parallel_devices[0] = "null";
5864 if (strncmp(monitor_device, "vc", 2) == 0)
5865 monitor_device = "stdio";
5868 #ifndef _WIN32
5869 if (daemonize) {
5870 pid_t pid;
5872 if (pipe(fds) == -1)
5873 exit(1);
5875 pid = fork();
5876 if (pid > 0) {
5877 uint8_t status;
5878 ssize_t len;
5880 close(fds[1]);
5882 again:
5883 len = read(fds[0], &status, 1);
5884 if (len == -1 && (errno == EINTR))
5885 goto again;
5887 if (len != 1)
5888 exit(1);
5889 else if (status == 1) {
5890 fprintf(stderr, "Could not acquire pidfile\n");
5891 exit(1);
5892 } else
5893 exit(0);
5894 } else if (pid < 0)
5895 exit(1);
5897 setsid();
5899 pid = fork();
5900 if (pid > 0)
5901 exit(0);
5902 else if (pid < 0)
5903 exit(1);
5905 umask(027);
5907 signal(SIGTSTP, SIG_IGN);
5908 signal(SIGTTOU, SIG_IGN);
5909 signal(SIGTTIN, SIG_IGN);
5912 #ifdef USE_KVM
5913 if (kvm_enabled()) {
5914 if (kvm_qemu_init() < 0) {
5915 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5916 #ifdef NO_CPU_EMULATION
5917 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5918 exit(1);
5919 #endif
5920 kvm_allowed = 0;
5923 #endif
5925 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5926 if (daemonize) {
5927 uint8_t status = 1;
5928 write(fds[1], &status, 1);
5929 } else
5930 fprintf(stderr, "Could not acquire pid file\n");
5931 exit(1);
5933 #endif
5935 #ifdef CONFIG_KQEMU
5936 if (smp_cpus > 1)
5937 kqemu_allowed = 0;
5938 #endif
5939 if (qemu_init_main_loop()) {
5940 fprintf(stderr, "qemu_init_main_loop failed\n");
5941 exit(1);
5943 linux_boot = (kernel_filename != NULL);
5944 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5946 if (!linux_boot && *kernel_cmdline != '\0') {
5947 fprintf(stderr, "-append only allowed with -kernel option\n");
5948 exit(1);
5951 if (!linux_boot && initrd_filename != NULL) {
5952 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5953 exit(1);
5956 /* boot to floppy or the default cd if no hard disk defined yet */
5957 if (!boot_devices[0]) {
5958 boot_devices = "cad";
5960 setvbuf(stdout, NULL, _IOLBF, 0);
5962 init_timers();
5963 if (init_timer_alarm() < 0) {
5964 fprintf(stderr, "could not initialize alarm timer\n");
5965 exit(1);
5967 if (use_icount && icount_time_shift < 0) {
5968 use_icount = 2;
5969 /* 125MIPS seems a reasonable initial guess at the guest speed.
5970 It will be corrected fairly quickly anyway. */
5971 icount_time_shift = 3;
5972 init_icount_adjust();
5975 #ifdef _WIN32
5976 socket_init();
5977 #endif
5979 /* init network clients */
5980 if (nb_net_clients == 0) {
5981 /* if no clients, we use a default config */
5982 net_clients[nb_net_clients++] = "nic";
5983 #ifdef CONFIG_SLIRP
5984 net_clients[nb_net_clients++] = "user";
5985 #endif
5988 for(i = 0;i < nb_net_clients; i++) {
5989 if (net_client_parse(net_clients[i]) < 0)
5990 exit(1);
5992 net_client_check();
5994 #ifdef TARGET_I386
5995 /* XXX: this should be moved in the PC machine instantiation code */
5996 if (net_boot != 0) {
5997 int netroms = 0;
5998 for (i = 0; i < nb_nics && i < 4; i++) {
5999 const char *model = nd_table[i].model;
6000 char buf[1024];
6001 char *filename;
6002 if (net_boot & (1 << i)) {
6003 if (model == NULL)
6004 model = "rtl8139";
6005 snprintf(buf, sizeof(buf), "pxe-%s.bin", model);
6006 filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, buf);
6007 if (filename && get_image_size(filename) > 0) {
6008 if (nb_option_roms >= MAX_OPTION_ROMS) {
6009 fprintf(stderr, "Too many option ROMs\n");
6010 exit(1);
6012 option_rom[nb_option_roms] = qemu_strdup(buf);
6013 nb_option_roms++;
6014 netroms++;
6016 if (filename) {
6017 qemu_free(filename);
6021 if (netroms == 0) {
6022 fprintf(stderr, "No valid PXE rom found for network device\n");
6023 exit(1);
6026 #endif
6028 /* init the bluetooth world */
6029 for (i = 0; i < nb_bt_opts; i++)
6030 if (bt_parse(bt_opts[i]))
6031 exit(1);
6033 /* init the memory */
6034 if (ram_size == 0)
6035 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6037 if (kvm_enabled()) {
6038 if (kvm_qemu_create_context() < 0) {
6039 fprintf(stderr, "Could not create KVM context\n");
6040 exit(1);
6044 #ifdef CONFIG_KQEMU
6045 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
6046 guest ram allocation. It needs to go away. */
6047 if (kqemu_allowed) {
6048 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
6049 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
6050 if (!kqemu_phys_ram_base) {
6051 fprintf(stderr, "Could not allocate physical memory\n");
6052 exit(1);
6055 #endif
6057 /* init the dynamic translator */
6058 cpu_exec_init_all(tb_size * 1024 * 1024);
6060 bdrv_init();
6062 /* we always create the cdrom drive, even if no disk is there */
6064 if (nb_drives_opt < MAX_DRIVES)
6065 drive_add(NULL, CDROM_ALIAS);
6067 /* we always create at least one floppy */
6069 if (nb_drives_opt < MAX_DRIVES)
6070 drive_add(NULL, FD_ALIAS, 0);
6072 /* we always create one sd slot, even if no card is in it */
6074 if (nb_drives_opt < MAX_DRIVES)
6075 drive_add(NULL, SD_ALIAS);
6077 /* open the virtual block devices
6078 * note that migration with device
6079 * hot add/remove is broken.
6081 for(i = 0; i < nb_drives_opt; i++)
6082 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
6083 exit(1);
6085 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6086 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
6088 #ifndef _WIN32
6089 /* must be after terminal init, SDL library changes signal handlers */
6090 sighandler_setup();
6091 #endif
6093 /* Maintain compatibility with multiple stdio monitors */
6094 if (!strcmp(monitor_device,"stdio")) {
6095 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
6096 const char *devname = serial_devices[i];
6097 if (devname && !strcmp(devname,"mon:stdio")) {
6098 monitor_device = NULL;
6099 break;
6100 } else if (devname && !strcmp(devname,"stdio")) {
6101 monitor_device = NULL;
6102 serial_devices[i] = "mon:stdio";
6103 break;
6108 if (nb_numa_nodes > 0) {
6109 int i;
6111 if (nb_numa_nodes > smp_cpus) {
6112 nb_numa_nodes = smp_cpus;
6115 /* If no memory size if given for any node, assume the default case
6116 * and distribute the available memory equally across all nodes
6118 for (i = 0; i < nb_numa_nodes; i++) {
6119 if (node_mem[i] != 0)
6120 break;
6122 if (i == nb_numa_nodes) {
6123 uint64_t usedmem = 0;
6125 /* On Linux, the each node's border has to be 8MB aligned,
6126 * the final node gets the rest.
6128 for (i = 0; i < nb_numa_nodes - 1; i++) {
6129 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
6130 usedmem += node_mem[i];
6132 node_mem[i] = ram_size - usedmem;
6135 for (i = 0; i < nb_numa_nodes; i++) {
6136 if (node_cpumask[i] != 0)
6137 break;
6139 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6140 * must cope with this anyway, because there are BIOSes out there in
6141 * real machines which also use this scheme.
6143 if (i == nb_numa_nodes) {
6144 for (i = 0; i < smp_cpus; i++) {
6145 node_cpumask[i % nb_numa_nodes] |= 1 << i;
6150 #ifdef KVM_UPSTREAM
6151 if (kvm_enabled()) {
6152 int ret;
6154 ret = kvm_init(smp_cpus);
6155 if (ret < 0) {
6156 fprintf(stderr, "failed to initialize KVM\n");
6157 exit(1);
6160 #endif
6162 if (monitor_device) {
6163 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
6164 if (!monitor_hd) {
6165 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6166 exit(1);
6170 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6171 const char *devname = serial_devices[i];
6172 if (devname && strcmp(devname, "none")) {
6173 char label[32];
6174 snprintf(label, sizeof(label), "serial%d", i);
6175 serial_hds[i] = qemu_chr_open(label, devname, NULL);
6176 if (!serial_hds[i]) {
6177 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6178 devname);
6179 exit(1);
6184 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6185 const char *devname = parallel_devices[i];
6186 if (devname && strcmp(devname, "none")) {
6187 char label[32];
6188 snprintf(label, sizeof(label), "parallel%d", i);
6189 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
6190 if (!parallel_hds[i]) {
6191 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6192 devname);
6193 exit(1);
6198 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6199 const char *devname = virtio_consoles[i];
6200 if (devname && strcmp(devname, "none")) {
6201 char label[32];
6202 snprintf(label, sizeof(label), "virtcon%d", i);
6203 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
6204 if (!virtcon_hds[i]) {
6205 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
6206 devname);
6207 exit(1);
6212 module_call_init(MODULE_INIT_DEVICE);
6214 if (kvm_enabled())
6215 kvm_init_ap();
6217 machine->init(ram_size, boot_devices,
6218 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6221 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6222 for (i = 0; i < nb_numa_nodes; i++) {
6223 if (node_cpumask[i] & (1 << env->cpu_index)) {
6224 env->numa_node = i;
6229 current_machine = machine;
6231 /* Set KVM's vcpu state to qemu's initial CPUState. */
6232 if (kvm_enabled()) {
6233 int ret;
6235 ret = kvm_sync_vcpus();
6236 if (ret < 0) {
6237 fprintf(stderr, "failed to initialize vcpus\n");
6238 exit(1);
6242 /* init USB devices */
6243 if (usb_enabled) {
6244 for(i = 0; i < usb_devices_index; i++) {
6245 if (usb_device_add(usb_devices[i], 0) < 0) {
6246 fprintf(stderr, "Warning: could not add USB device %s\n",
6247 usb_devices[i]);
6252 if (!display_state)
6253 dumb_display_init();
6254 /* just use the first displaystate for the moment */
6255 ds = display_state;
6257 if (display_type == DT_DEFAULT) {
6258 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6259 display_type = DT_SDL;
6260 #else
6261 display_type = DT_VNC;
6262 vnc_display = "localhost:0,to=99";
6263 show_vnc_port = 1;
6264 #endif
6268 switch (display_type) {
6269 case DT_NOGRAPHIC:
6270 break;
6271 #if defined(CONFIG_CURSES)
6272 case DT_CURSES:
6273 curses_display_init(ds, full_screen);
6274 break;
6275 #endif
6276 #if defined(CONFIG_SDL)
6277 case DT_SDL:
6278 sdl_display_init(ds, full_screen, no_frame);
6279 break;
6280 #elif defined(CONFIG_COCOA)
6281 case DT_SDL:
6282 cocoa_display_init(ds, full_screen);
6283 break;
6284 #endif
6285 case DT_VNC:
6286 vnc_display_init(ds);
6287 if (vnc_display_open(ds, vnc_display) < 0)
6288 exit(1);
6290 if (show_vnc_port) {
6291 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6293 break;
6294 default:
6295 break;
6297 dpy_resize(ds);
6299 dcl = ds->listeners;
6300 while (dcl != NULL) {
6301 if (dcl->dpy_refresh != NULL) {
6302 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6303 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6305 dcl = dcl->next;
6308 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6309 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6310 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6313 text_consoles_set_display(display_state);
6314 qemu_chr_initial_reset();
6316 if (monitor_device && monitor_hd)
6317 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6319 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6320 const char *devname = serial_devices[i];
6321 if (devname && strcmp(devname, "none")) {
6322 if (strstart(devname, "vc", 0))
6323 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6327 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6328 const char *devname = parallel_devices[i];
6329 if (devname && strcmp(devname, "none")) {
6330 if (strstart(devname, "vc", 0))
6331 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6335 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6336 const char *devname = virtio_consoles[i];
6337 if (virtcon_hds[i] && devname) {
6338 if (strstart(devname, "vc", 0))
6339 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6343 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6344 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6345 gdbstub_dev);
6346 exit(1);
6349 if (loadvm)
6350 do_loadvm(cur_mon, loadvm);
6352 if (incoming) {
6353 autostart = 0; /* fixme how to deal with -daemonize */
6354 qemu_start_incoming_migration(incoming);
6357 if (autostart)
6358 vm_start();
6360 #ifndef _WIN32
6361 if (daemonize) {
6362 uint8_t status = 0;
6363 ssize_t len;
6365 again1:
6366 len = write(fds[1], &status, 1);
6367 if (len == -1 && (errno == EINTR))
6368 goto again1;
6370 if (len != 1)
6371 exit(1);
6373 chdir("/");
6374 TFR(fd = open("/dev/null", O_RDWR));
6375 if (fd == -1)
6376 exit(1);
6379 if (run_as) {
6380 pwd = getpwnam(run_as);
6381 if (!pwd) {
6382 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6383 exit(1);
6387 if (chroot_dir) {
6388 if (chroot(chroot_dir) < 0) {
6389 fprintf(stderr, "chroot failed\n");
6390 exit(1);
6392 chdir("/");
6395 if (run_as) {
6396 if (setgid(pwd->pw_gid) < 0) {
6397 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6398 exit(1);
6400 if (setuid(pwd->pw_uid) < 0) {
6401 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6402 exit(1);
6404 if (setuid(0) != -1) {
6405 fprintf(stderr, "Dropping privileges failed\n");
6406 exit(1);
6410 if (daemonize) {
6411 dup2(fd, 0);
6412 dup2(fd, 1);
6413 dup2(fd, 2);
6415 close(fd);
6417 #endif
6419 main_loop();
6420 quit_timers();
6421 net_cleanup();
6423 return 0;