Merge branch 'upstream-merge'
[qemu-kvm/fedora.git] / vl.c
blob5d86e69a9d56ef4e021e43207b5ffa008f1ec762
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
32 /* Needed early for HOST_BSD etc. */
33 #include "config-host.h"
35 #ifndef _WIN32
36 #include <libgen.h>
37 #include <pwd.h>
38 #include <sys/times.h>
39 #include <sys/wait.h>
40 #include <termios.h>
41 #include <sys/mman.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <net/if.h>
47 #if defined(__NetBSD__)
48 #include <net/if_tap.h>
49 #endif
50 #ifdef __linux__
51 #include <linux/if_tun.h>
52 #endif
53 #include <arpa/inet.h>
54 #include <dirent.h>
55 #include <netdb.h>
56 #include <sys/select.h>
57 #ifdef HOST_BSD
58 #include <sys/stat.h>
59 #if defined(__FreeBSD__) || defined(__DragonFly__)
60 #include <libutil.h>
61 #else
62 #include <util.h>
63 #endif
64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65 #include <freebsd/stdlib.h>
66 #else
67 #ifdef __linux__
68 #include <pty.h>
69 #include <malloc.h>
70 #include <linux/rtc.h>
72 /* For the benefit of older linux systems which don't supply it,
73 we use a local copy of hpet.h. */
74 /* #include <linux/hpet.h> */
75 #include "hpet.h"
77 #include <linux/ppdev.h>
78 #include <linux/parport.h>
79 #endif
80 #ifdef __sun__
81 #include <sys/stat.h>
82 #include <sys/ethernet.h>
83 #include <sys/sockio.h>
84 #include <netinet/arp.h>
85 #include <netinet/in.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip_icmp.h> // must come after ip.h
89 #include <netinet/udp.h>
90 #include <netinet/tcp.h>
91 #include <net/if.h>
92 #include <syslog.h>
93 #include <stropts.h>
94 #endif
95 #endif
96 #endif
98 #if defined(__OpenBSD__)
99 #include <util.h>
100 #endif
102 #if defined(CONFIG_VDE)
103 #include <libvdeplug.h>
104 #endif
106 #ifdef _WIN32
107 #include <windows.h>
108 #include <malloc.h>
109 #include <sys/timeb.h>
110 #include <mmsystem.h>
111 #define getopt_long_only getopt_long
112 #define memalign(align, size) malloc(size)
113 #endif
115 #ifdef CONFIG_SDL
116 #if defined(__APPLE__) || defined(main)
117 #include <SDL.h>
118 int qemu_main(int argc, char **argv, char **envp);
119 int main(int argc, char **argv)
121 return qemu_main(argc, argv, NULL);
123 #undef main
124 #define main qemu_main
125 #endif
126 #endif /* CONFIG_SDL */
128 #ifdef CONFIG_COCOA
129 #undef main
130 #define main qemu_main
131 #endif /* CONFIG_COCOA */
133 #include "hw/hw.h"
134 #include "hw/boards.h"
135 #include "hw/usb.h"
136 #include "hw/pcmcia.h"
137 #include "hw/pc.h"
138 #include "hw/audiodev.h"
139 #include "hw/isa.h"
140 #include "hw/baum.h"
141 #include "hw/bt.h"
142 #include "hw/watchdog.h"
143 #include "hw/smbios.h"
144 #include "hw/xen.h"
145 #include "bt-host.h"
146 #include "net.h"
147 #include "monitor.h"
148 #include "console.h"
149 #include "sysemu.h"
150 #include "gdbstub.h"
151 #include "qemu-timer.h"
152 #include "qemu-char.h"
153 #include "cache-utils.h"
154 #include "block.h"
155 #include "dma.h"
156 #include "audio/audio.h"
157 #include "migration.h"
158 #include "kvm.h"
159 #include "balloon.h"
160 #include "qemu-option.h"
161 #include "qemu-kvm.h"
162 #include "hw/device-assignment.h"
164 #include "disas.h"
166 #include "exec-all.h"
168 #include "qemu_socket.h"
170 #include "slirp/libslirp.h"
172 //#define DEBUG_UNUSED_IOPORT
173 //#define DEBUG_IOPORT
174 //#define DEBUG_NET
175 //#define DEBUG_SLIRP
178 #ifdef DEBUG_IOPORT
179 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
180 #else
181 # define LOG_IOPORT(...) do { } while (0)
182 #endif
184 #define DEFAULT_RAM_SIZE 128
186 /* Max number of USB devices that can be specified on the commandline. */
187 #define MAX_USB_CMDLINE 8
189 /* Max number of bluetooth switches on the commandline. */
190 #define MAX_BT_CMDLINE 10
192 /* XXX: use a two level table to limit memory usage */
193 #define MAX_IOPORTS 65536
195 static const char *data_dir;
196 const char *bios_name = NULL;
197 static void *ioport_opaque[MAX_IOPORTS];
198 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
199 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
200 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
201 to store the VM snapshots */
202 DriveInfo drives_table[MAX_DRIVES+1];
203 int nb_drives;
204 int extboot_drive = -1;
205 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
206 static DisplayState *display_state;
207 DisplayType display_type = DT_DEFAULT;
208 const char* keyboard_layout = NULL;
209 int64_t ticks_per_sec;
210 ram_addr_t ram_size;
211 int nb_nics;
212 NICInfo nd_table[MAX_NICS];
213 int vm_running;
214 static int autostart;
215 static int rtc_utc = 1;
216 static int rtc_date_offset = -1; /* -1 means no change */
217 int cirrus_vga_enabled = 1;
218 int std_vga_enabled = 0;
219 int vmsvga_enabled = 0;
220 int xenfb_enabled = 0;
221 #ifdef TARGET_SPARC
222 int graphic_width = 1024;
223 int graphic_height = 768;
224 int graphic_depth = 8;
225 #else
226 int graphic_width = 800;
227 int graphic_height = 600;
228 int graphic_depth = 15;
229 #endif
230 static int full_screen = 0;
231 #ifdef CONFIG_SDL
232 static int no_frame = 0;
233 #endif
234 int no_quit = 0;
235 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
236 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
237 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
238 #ifdef TARGET_I386
239 int win2k_install_hack = 0;
240 int rtc_td_hack = 0;
241 #endif
242 int usb_enabled = 0;
243 int singlestep = 0;
244 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
245 int assigned_devices_index;
246 int smp_cpus = 1;
247 const char *vnc_display;
248 int acpi_enabled = 1;
249 int no_hpet = 0;
250 int virtio_balloon = 1;
251 const char *virtio_balloon_devaddr;
252 int fd_bootchk = 1;
253 int no_reboot = 0;
254 int no_shutdown = 0;
255 int cursor_hide = 1;
256 int graphic_rotate = 0;
257 #ifndef _WIN32
258 int daemonize = 0;
259 #endif
260 WatchdogTimerModel *watchdog = NULL;
261 int watchdog_action = WDT_RESET;
262 const char *option_rom[MAX_OPTION_ROMS];
263 int nb_option_roms;
264 int semihosting_enabled = 0;
265 int time_drift_fix = 0;
266 unsigned int kvm_shadow_memory = 0;
267 const char *mem_path = NULL;
268 #ifdef MAP_POPULATE
269 int mem_prealloc = 1; /* force preallocation of physical target memory */
270 #endif
271 #ifdef TARGET_ARM
272 int old_param = 0;
273 #endif
274 const char *qemu_name;
275 int alt_grab = 0;
276 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
277 unsigned int nb_prom_envs = 0;
278 const char *prom_envs[MAX_PROM_ENVS];
279 #endif
280 int nb_drives_opt;
281 const char *nvram = NULL;
282 struct drive_opt drives_opt[MAX_DRIVES];
284 int nb_numa_nodes;
285 uint64_t node_mem[MAX_NODES];
286 uint64_t node_cpumask[MAX_NODES];
288 static CPUState *cur_cpu;
289 static CPUState *next_cpu;
290 static int timer_alarm_pending = 1;
291 /* Conversion factor from emulated instructions to virtual clock ticks. */
292 static int icount_time_shift;
293 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
294 #define MAX_ICOUNT_SHIFT 10
295 /* Compensate for varying guest execution speed. */
296 static int64_t qemu_icount_bias;
297 static QEMUTimer *icount_rt_timer;
298 static QEMUTimer *icount_vm_timer;
299 static QEMUTimer *nographic_timer;
301 uint8_t qemu_uuid[16];
303 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
304 struct timeval *tv)
306 int ret;
308 /* KVM holds a mutex while QEMU code is running, we need hooks to
309 release the mutex whenever QEMU code sleeps. */
311 kvm_sleep_begin();
313 ret = select(max_fd, rfds, wfds, xfds, tv);
315 kvm_sleep_end();
317 return ret;
321 /***********************************************************/
322 /* x86 ISA bus support */
324 target_phys_addr_t isa_mem_base = 0;
325 PicState2 *isa_pic;
327 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
328 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
330 static uint32_t ioport_read(int index, uint32_t address)
332 static IOPortReadFunc *default_func[3] = {
333 default_ioport_readb,
334 default_ioport_readw,
335 default_ioport_readl
337 IOPortReadFunc *func = ioport_read_table[index][address];
338 if (!func)
339 func = default_func[index];
340 return func(ioport_opaque[address], address);
343 static void ioport_write(int index, uint32_t address, uint32_t data)
345 static IOPortWriteFunc *default_func[3] = {
346 default_ioport_writeb,
347 default_ioport_writew,
348 default_ioport_writel
350 IOPortWriteFunc *func = ioport_write_table[index][address];
351 if (!func)
352 func = default_func[index];
353 func(ioport_opaque[address], address, data);
356 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
358 #ifdef DEBUG_UNUSED_IOPORT
359 fprintf(stderr, "unused inb: port=0x%04x\n", address);
360 #endif
361 return 0xff;
364 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
366 #ifdef DEBUG_UNUSED_IOPORT
367 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
368 #endif
371 /* default is to make two byte accesses */
372 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
374 uint32_t data;
375 data = ioport_read(0, address);
376 address = (address + 1) & (MAX_IOPORTS - 1);
377 data |= ioport_read(0, address) << 8;
378 return data;
381 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
383 ioport_write(0, address, data & 0xff);
384 address = (address + 1) & (MAX_IOPORTS - 1);
385 ioport_write(0, address, (data >> 8) & 0xff);
388 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
390 #ifdef DEBUG_UNUSED_IOPORT
391 fprintf(stderr, "unused inl: port=0x%04x\n", address);
392 #endif
393 return 0xffffffff;
396 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
398 #ifdef DEBUG_UNUSED_IOPORT
399 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
400 #endif
403 /* size is the word size in byte */
404 int register_ioport_read(int start, int length, int size,
405 IOPortReadFunc *func, void *opaque)
407 int i, bsize;
409 if (size == 1) {
410 bsize = 0;
411 } else if (size == 2) {
412 bsize = 1;
413 } else if (size == 4) {
414 bsize = 2;
415 } else {
416 hw_error("register_ioport_read: invalid size");
417 return -1;
419 for(i = start; i < start + length; i += size) {
420 ioport_read_table[bsize][i] = func;
421 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
422 hw_error("register_ioport_read: invalid opaque");
423 ioport_opaque[i] = opaque;
425 return 0;
428 /* size is the word size in byte */
429 int register_ioport_write(int start, int length, int size,
430 IOPortWriteFunc *func, void *opaque)
432 int i, bsize;
434 if (size == 1) {
435 bsize = 0;
436 } else if (size == 2) {
437 bsize = 1;
438 } else if (size == 4) {
439 bsize = 2;
440 } else {
441 hw_error("register_ioport_write: invalid size");
442 return -1;
444 for(i = start; i < start + length; i += size) {
445 ioport_write_table[bsize][i] = func;
446 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
447 hw_error("register_ioport_write: invalid opaque");
448 ioport_opaque[i] = opaque;
450 return 0;
453 void isa_unassign_ioport(int start, int length)
455 int i;
457 for(i = start; i < start + length; i++) {
458 ioport_read_table[0][i] = default_ioport_readb;
459 ioport_read_table[1][i] = default_ioport_readw;
460 ioport_read_table[2][i] = default_ioport_readl;
462 ioport_write_table[0][i] = default_ioport_writeb;
463 ioport_write_table[1][i] = default_ioport_writew;
464 ioport_write_table[2][i] = default_ioport_writel;
466 ioport_opaque[i] = NULL;
470 /***********************************************************/
472 void cpu_outb(CPUState *env, int addr, int val)
474 LOG_IOPORT("outb: %04x %02x\n", addr, val);
475 ioport_write(0, addr, val);
476 #ifdef CONFIG_KQEMU
477 if (env)
478 env->last_io_time = cpu_get_time_fast();
479 #endif
482 void cpu_outw(CPUState *env, int addr, int val)
484 LOG_IOPORT("outw: %04x %04x\n", addr, val);
485 ioport_write(1, addr, val);
486 #ifdef CONFIG_KQEMU
487 if (env)
488 env->last_io_time = cpu_get_time_fast();
489 #endif
492 void cpu_outl(CPUState *env, int addr, int val)
494 LOG_IOPORT("outl: %04x %08x\n", addr, val);
495 ioport_write(2, addr, val);
496 #ifdef CONFIG_KQEMU
497 if (env)
498 env->last_io_time = cpu_get_time_fast();
499 #endif
502 int cpu_inb(CPUState *env, int addr)
504 int val;
505 val = ioport_read(0, addr);
506 LOG_IOPORT("inb : %04x %02x\n", addr, val);
507 #ifdef CONFIG_KQEMU
508 if (env)
509 env->last_io_time = cpu_get_time_fast();
510 #endif
511 return val;
514 int cpu_inw(CPUState *env, int addr)
516 int val;
517 val = ioport_read(1, addr);
518 LOG_IOPORT("inw : %04x %04x\n", addr, val);
519 #ifdef CONFIG_KQEMU
520 if (env)
521 env->last_io_time = cpu_get_time_fast();
522 #endif
523 return val;
526 int cpu_inl(CPUState *env, int addr)
528 int val;
529 val = ioport_read(2, addr);
530 LOG_IOPORT("inl : %04x %08x\n", addr, val);
531 #ifdef CONFIG_KQEMU
532 if (env)
533 env->last_io_time = cpu_get_time_fast();
534 #endif
535 return val;
538 /***********************************************************/
539 void hw_error(const char *fmt, ...)
541 va_list ap;
542 CPUState *env;
544 va_start(ap, fmt);
545 fprintf(stderr, "qemu: hardware error: ");
546 vfprintf(stderr, fmt, ap);
547 fprintf(stderr, "\n");
548 for(env = first_cpu; env != NULL; env = env->next_cpu) {
549 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
550 #ifdef TARGET_I386
551 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
552 #else
553 cpu_dump_state(env, stderr, fprintf, 0);
554 #endif
556 va_end(ap);
557 abort();
560 /***************/
561 /* ballooning */
563 static QEMUBalloonEvent *qemu_balloon_event;
564 void *qemu_balloon_event_opaque;
566 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
568 qemu_balloon_event = func;
569 qemu_balloon_event_opaque = opaque;
572 void qemu_balloon(ram_addr_t target)
574 if (qemu_balloon_event)
575 qemu_balloon_event(qemu_balloon_event_opaque, target);
578 ram_addr_t qemu_balloon_status(void)
580 if (qemu_balloon_event)
581 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
582 return 0;
585 /***********************************************************/
586 /* keyboard/mouse */
588 static QEMUPutKBDEvent *qemu_put_kbd_event;
589 static void *qemu_put_kbd_event_opaque;
590 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
591 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
593 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
595 qemu_put_kbd_event_opaque = opaque;
596 qemu_put_kbd_event = func;
599 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
600 void *opaque, int absolute,
601 const char *name)
603 QEMUPutMouseEntry *s, *cursor;
605 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
607 s->qemu_put_mouse_event = func;
608 s->qemu_put_mouse_event_opaque = opaque;
609 s->qemu_put_mouse_event_absolute = absolute;
610 s->qemu_put_mouse_event_name = qemu_strdup(name);
611 s->next = NULL;
613 if (!qemu_put_mouse_event_head) {
614 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
615 return s;
618 cursor = qemu_put_mouse_event_head;
619 while (cursor->next != NULL)
620 cursor = cursor->next;
622 cursor->next = s;
623 qemu_put_mouse_event_current = s;
625 return s;
628 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
630 QEMUPutMouseEntry *prev = NULL, *cursor;
632 if (!qemu_put_mouse_event_head || entry == NULL)
633 return;
635 cursor = qemu_put_mouse_event_head;
636 while (cursor != NULL && cursor != entry) {
637 prev = cursor;
638 cursor = cursor->next;
641 if (cursor == NULL) // does not exist or list empty
642 return;
643 else if (prev == NULL) { // entry is head
644 qemu_put_mouse_event_head = cursor->next;
645 if (qemu_put_mouse_event_current == entry)
646 qemu_put_mouse_event_current = cursor->next;
647 qemu_free(entry->qemu_put_mouse_event_name);
648 qemu_free(entry);
649 return;
652 prev->next = entry->next;
654 if (qemu_put_mouse_event_current == entry)
655 qemu_put_mouse_event_current = prev;
657 qemu_free(entry->qemu_put_mouse_event_name);
658 qemu_free(entry);
661 void kbd_put_keycode(int keycode)
663 if (qemu_put_kbd_event) {
664 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
668 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
670 QEMUPutMouseEvent *mouse_event;
671 void *mouse_event_opaque;
672 int width;
674 if (!qemu_put_mouse_event_current) {
675 return;
678 mouse_event =
679 qemu_put_mouse_event_current->qemu_put_mouse_event;
680 mouse_event_opaque =
681 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
683 if (mouse_event) {
684 if (graphic_rotate) {
685 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
686 width = 0x7fff;
687 else
688 width = graphic_width - 1;
689 mouse_event(mouse_event_opaque,
690 width - dy, dx, dz, buttons_state);
691 } else
692 mouse_event(mouse_event_opaque,
693 dx, dy, dz, buttons_state);
697 int kbd_mouse_is_absolute(void)
699 if (!qemu_put_mouse_event_current)
700 return 0;
702 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
705 void do_info_mice(Monitor *mon)
707 QEMUPutMouseEntry *cursor;
708 int index = 0;
710 if (!qemu_put_mouse_event_head) {
711 monitor_printf(mon, "No mouse devices connected\n");
712 return;
715 monitor_printf(mon, "Mouse devices available:\n");
716 cursor = qemu_put_mouse_event_head;
717 while (cursor != NULL) {
718 monitor_printf(mon, "%c Mouse #%d: %s\n",
719 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
720 index, cursor->qemu_put_mouse_event_name);
721 index++;
722 cursor = cursor->next;
726 void do_mouse_set(Monitor *mon, int index)
728 QEMUPutMouseEntry *cursor;
729 int i = 0;
731 if (!qemu_put_mouse_event_head) {
732 monitor_printf(mon, "No mouse devices connected\n");
733 return;
736 cursor = qemu_put_mouse_event_head;
737 while (cursor != NULL && index != i) {
738 i++;
739 cursor = cursor->next;
742 if (cursor != NULL)
743 qemu_put_mouse_event_current = cursor;
744 else
745 monitor_printf(mon, "Mouse at given index not found\n");
748 /* compute with 96 bit intermediate result: (a*b)/c */
749 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
751 union {
752 uint64_t ll;
753 struct {
754 #ifdef WORDS_BIGENDIAN
755 uint32_t high, low;
756 #else
757 uint32_t low, high;
758 #endif
759 } l;
760 } u, res;
761 uint64_t rl, rh;
763 u.ll = a;
764 rl = (uint64_t)u.l.low * (uint64_t)b;
765 rh = (uint64_t)u.l.high * (uint64_t)b;
766 rh += (rl >> 32);
767 res.l.high = rh / c;
768 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
769 return res.ll;
772 /***********************************************************/
773 /* real time host monotonic timer */
775 #define QEMU_TIMER_BASE 1000000000LL
777 #ifdef WIN32
779 static int64_t clock_freq;
781 static void init_get_clock(void)
783 LARGE_INTEGER freq;
784 int ret;
785 ret = QueryPerformanceFrequency(&freq);
786 if (ret == 0) {
787 fprintf(stderr, "Could not calibrate ticks\n");
788 exit(1);
790 clock_freq = freq.QuadPart;
793 static int64_t get_clock(void)
795 LARGE_INTEGER ti;
796 QueryPerformanceCounter(&ti);
797 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
800 #else
802 static int use_rt_clock;
804 static void init_get_clock(void)
806 use_rt_clock = 0;
807 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
808 || defined(__DragonFly__)
810 struct timespec ts;
811 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
812 use_rt_clock = 1;
815 #endif
818 static int64_t get_clock(void)
820 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
821 || defined(__DragonFly__)
822 if (use_rt_clock) {
823 struct timespec ts;
824 clock_gettime(CLOCK_MONOTONIC, &ts);
825 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
826 } else
827 #endif
829 /* XXX: using gettimeofday leads to problems if the date
830 changes, so it should be avoided. */
831 struct timeval tv;
832 gettimeofday(&tv, NULL);
833 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
836 #endif
838 /* Return the virtual CPU time, based on the instruction counter. */
839 static int64_t cpu_get_icount(void)
841 int64_t icount;
842 CPUState *env = cpu_single_env;;
843 icount = qemu_icount;
844 if (env) {
845 if (!can_do_io(env))
846 fprintf(stderr, "Bad clock read\n");
847 icount -= (env->icount_decr.u16.low + env->icount_extra);
849 return qemu_icount_bias + (icount << icount_time_shift);
852 /***********************************************************/
853 /* guest cycle counter */
855 static int64_t cpu_ticks_prev;
856 static int64_t cpu_ticks_offset;
857 static int64_t cpu_clock_offset;
858 static int cpu_ticks_enabled;
860 /* return the host CPU cycle counter and handle stop/restart */
861 int64_t cpu_get_ticks(void)
863 if (use_icount) {
864 return cpu_get_icount();
866 if (!cpu_ticks_enabled) {
867 return cpu_ticks_offset;
868 } else {
869 int64_t ticks;
870 ticks = cpu_get_real_ticks();
871 if (cpu_ticks_prev > ticks) {
872 /* Note: non increasing ticks may happen if the host uses
873 software suspend */
874 cpu_ticks_offset += cpu_ticks_prev - ticks;
876 cpu_ticks_prev = ticks;
877 return ticks + cpu_ticks_offset;
881 /* return the host CPU monotonic timer and handle stop/restart */
882 static int64_t cpu_get_clock(void)
884 int64_t ti;
885 if (!cpu_ticks_enabled) {
886 return cpu_clock_offset;
887 } else {
888 ti = get_clock();
889 return ti + cpu_clock_offset;
893 /* enable cpu_get_ticks() */
894 void cpu_enable_ticks(void)
896 if (!cpu_ticks_enabled) {
897 cpu_ticks_offset -= cpu_get_real_ticks();
898 cpu_clock_offset -= get_clock();
899 cpu_ticks_enabled = 1;
903 /* disable cpu_get_ticks() : the clock is stopped. You must not call
904 cpu_get_ticks() after that. */
905 void cpu_disable_ticks(void)
907 if (cpu_ticks_enabled) {
908 cpu_ticks_offset = cpu_get_ticks();
909 cpu_clock_offset = cpu_get_clock();
910 cpu_ticks_enabled = 0;
914 /***********************************************************/
915 /* timers */
917 #define QEMU_TIMER_REALTIME 0
918 #define QEMU_TIMER_VIRTUAL 1
920 struct QEMUClock {
921 int type;
922 /* XXX: add frequency */
925 struct QEMUTimer {
926 QEMUClock *clock;
927 int64_t expire_time;
928 QEMUTimerCB *cb;
929 void *opaque;
930 struct QEMUTimer *next;
933 struct qemu_alarm_timer {
934 char const *name;
935 unsigned int flags;
937 int (*start)(struct qemu_alarm_timer *t);
938 void (*stop)(struct qemu_alarm_timer *t);
939 void (*rearm)(struct qemu_alarm_timer *t);
940 void *priv;
943 #define ALARM_FLAG_DYNTICKS 0x1
944 #define ALARM_FLAG_EXPIRED 0x2
946 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
948 return t && (t->flags & ALARM_FLAG_DYNTICKS);
951 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
953 if (!alarm_has_dynticks(t))
954 return;
956 t->rearm(t);
959 /* TODO: MIN_TIMER_REARM_US should be optimized */
960 #define MIN_TIMER_REARM_US 250
962 static struct qemu_alarm_timer *alarm_timer;
964 #ifdef _WIN32
966 struct qemu_alarm_win32 {
967 MMRESULT timerId;
968 unsigned int period;
969 } alarm_win32_data = {0, -1};
971 static int win32_start_timer(struct qemu_alarm_timer *t);
972 static void win32_stop_timer(struct qemu_alarm_timer *t);
973 static void win32_rearm_timer(struct qemu_alarm_timer *t);
975 #else
977 static int unix_start_timer(struct qemu_alarm_timer *t);
978 static void unix_stop_timer(struct qemu_alarm_timer *t);
980 #ifdef __linux__
982 static int dynticks_start_timer(struct qemu_alarm_timer *t);
983 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
984 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
986 static int hpet_start_timer(struct qemu_alarm_timer *t);
987 static void hpet_stop_timer(struct qemu_alarm_timer *t);
989 static int rtc_start_timer(struct qemu_alarm_timer *t);
990 static void rtc_stop_timer(struct qemu_alarm_timer *t);
992 #endif /* __linux__ */
994 #endif /* _WIN32 */
996 /* Correlation between real and virtual time is always going to be
997 fairly approximate, so ignore small variation.
998 When the guest is idle real and virtual time will be aligned in
999 the IO wait loop. */
1000 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
1002 static void icount_adjust(void)
1004 int64_t cur_time;
1005 int64_t cur_icount;
1006 int64_t delta;
1007 static int64_t last_delta;
1008 /* If the VM is not running, then do nothing. */
1009 if (!vm_running)
1010 return;
1012 cur_time = cpu_get_clock();
1013 cur_icount = qemu_get_clock(vm_clock);
1014 delta = cur_icount - cur_time;
1015 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1016 if (delta > 0
1017 && last_delta + ICOUNT_WOBBLE < delta * 2
1018 && icount_time_shift > 0) {
1019 /* The guest is getting too far ahead. Slow time down. */
1020 icount_time_shift--;
1022 if (delta < 0
1023 && last_delta - ICOUNT_WOBBLE > delta * 2
1024 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1025 /* The guest is getting too far behind. Speed time up. */
1026 icount_time_shift++;
1028 last_delta = delta;
1029 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1032 static void icount_adjust_rt(void * opaque)
1034 qemu_mod_timer(icount_rt_timer,
1035 qemu_get_clock(rt_clock) + 1000);
1036 icount_adjust();
1039 static void icount_adjust_vm(void * opaque)
1041 qemu_mod_timer(icount_vm_timer,
1042 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1043 icount_adjust();
1046 static void init_icount_adjust(void)
1048 /* Have both realtime and virtual time triggers for speed adjustment.
1049 The realtime trigger catches emulated time passing too slowly,
1050 the virtual time trigger catches emulated time passing too fast.
1051 Realtime triggers occur even when idle, so use them less frequently
1052 than VM triggers. */
1053 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1054 qemu_mod_timer(icount_rt_timer,
1055 qemu_get_clock(rt_clock) + 1000);
1056 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1057 qemu_mod_timer(icount_vm_timer,
1058 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1061 static struct qemu_alarm_timer alarm_timers[] = {
1062 #ifndef _WIN32
1063 #ifdef __linux__
1064 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1065 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1066 /* HPET - if available - is preferred */
1067 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1068 /* ...otherwise try RTC */
1069 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1070 #endif
1071 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1072 #else
1073 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1074 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1075 {"win32", 0, win32_start_timer,
1076 win32_stop_timer, NULL, &alarm_win32_data},
1077 #endif
1078 {NULL, }
1081 static void show_available_alarms(void)
1083 int i;
1085 printf("Available alarm timers, in order of precedence:\n");
1086 for (i = 0; alarm_timers[i].name; i++)
1087 printf("%s\n", alarm_timers[i].name);
1090 static void configure_alarms(char const *opt)
1092 int i;
1093 int cur = 0;
1094 int count = ARRAY_SIZE(alarm_timers) - 1;
1095 char *arg;
1096 char *name;
1097 struct qemu_alarm_timer tmp;
1099 if (!strcmp(opt, "?")) {
1100 show_available_alarms();
1101 exit(0);
1104 arg = strdup(opt);
1106 /* Reorder the array */
1107 name = strtok(arg, ",");
1108 while (name) {
1109 for (i = 0; i < count && alarm_timers[i].name; i++) {
1110 if (!strcmp(alarm_timers[i].name, name))
1111 break;
1114 if (i == count) {
1115 fprintf(stderr, "Unknown clock %s\n", name);
1116 goto next;
1119 if (i < cur)
1120 /* Ignore */
1121 goto next;
1123 /* Swap */
1124 tmp = alarm_timers[i];
1125 alarm_timers[i] = alarm_timers[cur];
1126 alarm_timers[cur] = tmp;
1128 cur++;
1129 next:
1130 name = strtok(NULL, ",");
1133 free(arg);
1135 if (cur) {
1136 /* Disable remaining timers */
1137 for (i = cur; i < count; i++)
1138 alarm_timers[i].name = NULL;
1139 } else {
1140 show_available_alarms();
1141 exit(1);
1145 QEMUClock *rt_clock;
1146 QEMUClock *vm_clock;
1148 static QEMUTimer *active_timers[2];
1150 static QEMUClock *qemu_new_clock(int type)
1152 QEMUClock *clock;
1153 clock = qemu_mallocz(sizeof(QEMUClock));
1154 clock->type = type;
1155 return clock;
1158 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1160 QEMUTimer *ts;
1162 ts = qemu_mallocz(sizeof(QEMUTimer));
1163 ts->clock = clock;
1164 ts->cb = cb;
1165 ts->opaque = opaque;
1166 return ts;
1169 void qemu_free_timer(QEMUTimer *ts)
1171 qemu_free(ts);
1174 /* stop a timer, but do not dealloc it */
1175 void qemu_del_timer(QEMUTimer *ts)
1177 QEMUTimer **pt, *t;
1179 /* NOTE: this code must be signal safe because
1180 qemu_timer_expired() can be called from a signal. */
1181 pt = &active_timers[ts->clock->type];
1182 for(;;) {
1183 t = *pt;
1184 if (!t)
1185 break;
1186 if (t == ts) {
1187 *pt = t->next;
1188 break;
1190 pt = &t->next;
1194 /* modify the current timer so that it will be fired when current_time
1195 >= expire_time. The corresponding callback will be called. */
1196 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1198 QEMUTimer **pt, *t;
1200 qemu_del_timer(ts);
1202 /* add the timer in the sorted list */
1203 /* NOTE: this code must be signal safe because
1204 qemu_timer_expired() can be called from a signal. */
1205 pt = &active_timers[ts->clock->type];
1206 for(;;) {
1207 t = *pt;
1208 if (!t)
1209 break;
1210 if (t->expire_time > expire_time)
1211 break;
1212 pt = &t->next;
1214 ts->expire_time = expire_time;
1215 ts->next = *pt;
1216 *pt = ts;
1218 /* Rearm if necessary */
1219 if (pt == &active_timers[ts->clock->type]) {
1220 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1221 qemu_rearm_alarm_timer(alarm_timer);
1223 /* Interrupt execution to force deadline recalculation. */
1224 if (use_icount)
1225 qemu_notify_event();
1229 int qemu_timer_pending(QEMUTimer *ts)
1231 QEMUTimer *t;
1232 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1233 if (t == ts)
1234 return 1;
1236 return 0;
1239 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1241 if (!timer_head)
1242 return 0;
1243 return (timer_head->expire_time <= current_time);
1246 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1248 QEMUTimer *ts;
1250 for(;;) {
1251 ts = *ptimer_head;
1252 if (!ts || ts->expire_time > current_time)
1253 break;
1254 /* remove timer from the list before calling the callback */
1255 *ptimer_head = ts->next;
1256 ts->next = NULL;
1258 /* run the callback (the timer list can be modified) */
1259 ts->cb(ts->opaque);
1263 int64_t qemu_get_clock(QEMUClock *clock)
1265 switch(clock->type) {
1266 case QEMU_TIMER_REALTIME:
1267 return get_clock() / 1000000;
1268 default:
1269 case QEMU_TIMER_VIRTUAL:
1270 if (use_icount) {
1271 return cpu_get_icount();
1272 } else {
1273 return cpu_get_clock();
1278 static void init_timers(void)
1280 init_get_clock();
1281 ticks_per_sec = QEMU_TIMER_BASE;
1282 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1283 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1286 /* save a timer */
1287 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1289 uint64_t expire_time;
1291 if (qemu_timer_pending(ts)) {
1292 expire_time = ts->expire_time;
1293 } else {
1294 expire_time = -1;
1296 qemu_put_be64(f, expire_time);
1299 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1301 uint64_t expire_time;
1303 expire_time = qemu_get_be64(f);
1304 if (expire_time != -1) {
1305 qemu_mod_timer(ts, expire_time);
1306 } else {
1307 qemu_del_timer(ts);
1311 static void timer_save(QEMUFile *f, void *opaque)
1313 if (cpu_ticks_enabled) {
1314 hw_error("cannot save state if virtual timers are running");
1316 qemu_put_be64(f, cpu_ticks_offset);
1317 qemu_put_be64(f, ticks_per_sec);
1318 qemu_put_be64(f, cpu_clock_offset);
1321 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1323 if (version_id != 1 && version_id != 2)
1324 return -EINVAL;
1325 if (cpu_ticks_enabled) {
1326 return -EINVAL;
1328 cpu_ticks_offset=qemu_get_be64(f);
1329 ticks_per_sec=qemu_get_be64(f);
1330 if (version_id == 2) {
1331 cpu_clock_offset=qemu_get_be64(f);
1333 return 0;
1336 static void qemu_event_increment(void);
1338 #ifdef _WIN32
1339 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1340 DWORD_PTR dwUser, DWORD_PTR dw1,
1341 DWORD_PTR dw2)
1342 #else
1343 static void host_alarm_handler(int host_signum)
1344 #endif
1346 #if 0
1347 #define DISP_FREQ 1000
1349 static int64_t delta_min = INT64_MAX;
1350 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1351 static int count;
1352 ti = qemu_get_clock(vm_clock);
1353 if (last_clock != 0) {
1354 delta = ti - last_clock;
1355 if (delta < delta_min)
1356 delta_min = delta;
1357 if (delta > delta_max)
1358 delta_max = delta;
1359 delta_cum += delta;
1360 if (++count == DISP_FREQ) {
1361 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1362 muldiv64(delta_min, 1000000, ticks_per_sec),
1363 muldiv64(delta_max, 1000000, ticks_per_sec),
1364 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1365 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1366 count = 0;
1367 delta_min = INT64_MAX;
1368 delta_max = 0;
1369 delta_cum = 0;
1372 last_clock = ti;
1374 #endif
1375 if (alarm_has_dynticks(alarm_timer) ||
1376 (!use_icount &&
1377 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1378 qemu_get_clock(vm_clock))) ||
1379 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1380 qemu_get_clock(rt_clock))) {
1381 qemu_event_increment();
1382 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1384 #ifndef CONFIG_IOTHREAD
1385 if (next_cpu) {
1386 /* stop the currently executing cpu because a timer occured */
1387 cpu_exit(next_cpu);
1388 #ifdef CONFIG_KQEMU
1389 if (next_cpu->kqemu_enabled) {
1390 kqemu_cpu_interrupt(next_cpu);
1392 #endif
1394 #endif
1395 timer_alarm_pending = 1;
1396 qemu_notify_event();
1400 static int64_t qemu_next_deadline(void)
1402 int64_t delta;
1404 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1405 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1406 qemu_get_clock(vm_clock);
1407 } else {
1408 /* To avoid problems with overflow limit this to 2^32. */
1409 delta = INT32_MAX;
1412 if (delta < 0)
1413 delta = 0;
1415 return delta;
1418 #if defined(__linux__) || defined(_WIN32)
1419 static uint64_t qemu_next_deadline_dyntick(void)
1421 int64_t delta;
1422 int64_t rtdelta;
1424 if (use_icount)
1425 delta = INT32_MAX;
1426 else
1427 delta = (qemu_next_deadline() + 999) / 1000;
1429 if (active_timers[QEMU_TIMER_REALTIME]) {
1430 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1431 qemu_get_clock(rt_clock))*1000;
1432 if (rtdelta < delta)
1433 delta = rtdelta;
1436 if (delta < MIN_TIMER_REARM_US)
1437 delta = MIN_TIMER_REARM_US;
1439 return delta;
1441 #endif
1443 #ifndef _WIN32
1445 /* Sets a specific flag */
1446 static int fcntl_setfl(int fd, int flag)
1448 int flags;
1450 flags = fcntl(fd, F_GETFL);
1451 if (flags == -1)
1452 return -errno;
1454 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1455 return -errno;
1457 return 0;
1460 #if defined(__linux__)
1462 #define RTC_FREQ 1024
1464 static void enable_sigio_timer(int fd)
1466 struct sigaction act;
1468 /* timer signal */
1469 sigfillset(&act.sa_mask);
1470 act.sa_flags = 0;
1471 act.sa_handler = host_alarm_handler;
1473 sigaction(SIGIO, &act, NULL);
1474 fcntl_setfl(fd, O_ASYNC);
1475 fcntl(fd, F_SETOWN, getpid());
1478 static int hpet_start_timer(struct qemu_alarm_timer *t)
1480 struct hpet_info info;
1481 int r, fd;
1483 fd = open("/dev/hpet", O_RDONLY);
1484 if (fd < 0)
1485 return -1;
1487 /* Set frequency */
1488 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1489 if (r < 0) {
1490 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1491 "error, but for better emulation accuracy type:\n"
1492 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1493 goto fail;
1496 /* Check capabilities */
1497 r = ioctl(fd, HPET_INFO, &info);
1498 if (r < 0)
1499 goto fail;
1501 /* Enable periodic mode */
1502 r = ioctl(fd, HPET_EPI, 0);
1503 if (info.hi_flags && (r < 0))
1504 goto fail;
1506 /* Enable interrupt */
1507 r = ioctl(fd, HPET_IE_ON, 0);
1508 if (r < 0)
1509 goto fail;
1511 enable_sigio_timer(fd);
1512 t->priv = (void *)(long)fd;
1514 return 0;
1515 fail:
1516 close(fd);
1517 return -1;
1520 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1522 int fd = (long)t->priv;
1524 close(fd);
1527 static int rtc_start_timer(struct qemu_alarm_timer *t)
1529 int rtc_fd;
1530 unsigned long current_rtc_freq = 0;
1532 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1533 if (rtc_fd < 0)
1534 return -1;
1535 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1536 if (current_rtc_freq != RTC_FREQ &&
1537 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1538 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1539 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1540 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1541 goto fail;
1543 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1544 fail:
1545 close(rtc_fd);
1546 return -1;
1549 enable_sigio_timer(rtc_fd);
1551 t->priv = (void *)(long)rtc_fd;
1553 return 0;
1556 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1558 int rtc_fd = (long)t->priv;
1560 close(rtc_fd);
1563 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1565 struct sigevent ev;
1566 timer_t host_timer;
1567 struct sigaction act;
1569 sigfillset(&act.sa_mask);
1570 act.sa_flags = 0;
1571 act.sa_handler = host_alarm_handler;
1573 sigaction(SIGALRM, &act, NULL);
1576 * Initialize ev struct to 0 to avoid valgrind complaining
1577 * about uninitialized data in timer_create call
1579 memset(&ev, 0, sizeof(ev));
1580 ev.sigev_value.sival_int = 0;
1581 ev.sigev_notify = SIGEV_SIGNAL;
1582 ev.sigev_signo = SIGALRM;
1584 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1585 perror("timer_create");
1587 /* disable dynticks */
1588 fprintf(stderr, "Dynamic Ticks disabled\n");
1590 return -1;
1593 t->priv = (void *)(long)host_timer;
1595 return 0;
1598 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1600 timer_t host_timer = (timer_t)(long)t->priv;
1602 timer_delete(host_timer);
1605 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1607 timer_t host_timer = (timer_t)(long)t->priv;
1608 struct itimerspec timeout;
1609 int64_t nearest_delta_us = INT64_MAX;
1610 int64_t current_us;
1612 if (!active_timers[QEMU_TIMER_REALTIME] &&
1613 !active_timers[QEMU_TIMER_VIRTUAL])
1614 return;
1616 nearest_delta_us = qemu_next_deadline_dyntick();
1618 /* check whether a timer is already running */
1619 if (timer_gettime(host_timer, &timeout)) {
1620 perror("gettime");
1621 fprintf(stderr, "Internal timer error: aborting\n");
1622 exit(1);
1624 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1625 if (current_us && current_us <= nearest_delta_us)
1626 return;
1628 timeout.it_interval.tv_sec = 0;
1629 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1630 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1631 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1632 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1633 perror("settime");
1634 fprintf(stderr, "Internal timer error: aborting\n");
1635 exit(1);
1639 #endif /* defined(__linux__) */
1641 static int unix_start_timer(struct qemu_alarm_timer *t)
1643 struct sigaction act;
1644 struct itimerval itv;
1645 int err;
1647 /* timer signal */
1648 sigfillset(&act.sa_mask);
1649 act.sa_flags = 0;
1650 act.sa_handler = host_alarm_handler;
1652 sigaction(SIGALRM, &act, NULL);
1654 itv.it_interval.tv_sec = 0;
1655 /* for i386 kernel 2.6 to get 1 ms */
1656 itv.it_interval.tv_usec = 999;
1657 itv.it_value.tv_sec = 0;
1658 itv.it_value.tv_usec = 10 * 1000;
1660 err = setitimer(ITIMER_REAL, &itv, NULL);
1661 if (err)
1662 return -1;
1664 return 0;
1667 static void unix_stop_timer(struct qemu_alarm_timer *t)
1669 struct itimerval itv;
1671 memset(&itv, 0, sizeof(itv));
1672 setitimer(ITIMER_REAL, &itv, NULL);
1675 #endif /* !defined(_WIN32) */
1678 #ifdef _WIN32
1680 static int win32_start_timer(struct qemu_alarm_timer *t)
1682 TIMECAPS tc;
1683 struct qemu_alarm_win32 *data = t->priv;
1684 UINT flags;
1686 memset(&tc, 0, sizeof(tc));
1687 timeGetDevCaps(&tc, sizeof(tc));
1689 if (data->period < tc.wPeriodMin)
1690 data->period = tc.wPeriodMin;
1692 timeBeginPeriod(data->period);
1694 flags = TIME_CALLBACK_FUNCTION;
1695 if (alarm_has_dynticks(t))
1696 flags |= TIME_ONESHOT;
1697 else
1698 flags |= TIME_PERIODIC;
1700 data->timerId = timeSetEvent(1, // interval (ms)
1701 data->period, // resolution
1702 host_alarm_handler, // function
1703 (DWORD)t, // parameter
1704 flags);
1706 if (!data->timerId) {
1707 perror("Failed to initialize win32 alarm timer");
1708 timeEndPeriod(data->period);
1709 return -1;
1712 return 0;
1715 static void win32_stop_timer(struct qemu_alarm_timer *t)
1717 struct qemu_alarm_win32 *data = t->priv;
1719 timeKillEvent(data->timerId);
1720 timeEndPeriod(data->period);
1723 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1725 struct qemu_alarm_win32 *data = t->priv;
1726 uint64_t nearest_delta_us;
1728 if (!active_timers[QEMU_TIMER_REALTIME] &&
1729 !active_timers[QEMU_TIMER_VIRTUAL])
1730 return;
1732 nearest_delta_us = qemu_next_deadline_dyntick();
1733 nearest_delta_us /= 1000;
1735 timeKillEvent(data->timerId);
1737 data->timerId = timeSetEvent(1,
1738 data->period,
1739 host_alarm_handler,
1740 (DWORD)t,
1741 TIME_ONESHOT | TIME_PERIODIC);
1743 if (!data->timerId) {
1744 perror("Failed to re-arm win32 alarm timer");
1746 timeEndPeriod(data->period);
1747 exit(1);
1751 #endif /* _WIN32 */
1753 static int init_timer_alarm(void)
1755 struct qemu_alarm_timer *t = NULL;
1756 int i, err = -1;
1758 for (i = 0; alarm_timers[i].name; i++) {
1759 t = &alarm_timers[i];
1761 err = t->start(t);
1762 if (!err)
1763 break;
1766 if (err) {
1767 err = -ENOENT;
1768 goto fail;
1771 alarm_timer = t;
1773 return 0;
1775 fail:
1776 return err;
1779 static void quit_timers(void)
1781 alarm_timer->stop(alarm_timer);
1782 alarm_timer = NULL;
1785 /***********************************************************/
1786 /* host time/date access */
1787 void qemu_get_timedate(struct tm *tm, int offset)
1789 time_t ti;
1790 struct tm *ret;
1792 time(&ti);
1793 ti += offset;
1794 if (rtc_date_offset == -1) {
1795 if (rtc_utc)
1796 ret = gmtime(&ti);
1797 else
1798 ret = localtime(&ti);
1799 } else {
1800 ti -= rtc_date_offset;
1801 ret = gmtime(&ti);
1804 memcpy(tm, ret, sizeof(struct tm));
1807 int qemu_timedate_diff(struct tm *tm)
1809 time_t seconds;
1811 if (rtc_date_offset == -1)
1812 if (rtc_utc)
1813 seconds = mktimegm(tm);
1814 else
1815 seconds = mktime(tm);
1816 else
1817 seconds = mktimegm(tm) + rtc_date_offset;
1819 return seconds - time(NULL);
1822 #ifdef _WIN32
1823 static void socket_cleanup(void)
1825 WSACleanup();
1828 static int socket_init(void)
1830 WSADATA Data;
1831 int ret, err;
1833 ret = WSAStartup(MAKEWORD(2,2), &Data);
1834 if (ret != 0) {
1835 err = WSAGetLastError();
1836 fprintf(stderr, "WSAStartup: %d\n", err);
1837 return -1;
1839 atexit(socket_cleanup);
1840 return 0;
1842 #endif
1844 int get_next_param_value(char *buf, int buf_size,
1845 const char *tag, const char **pstr)
1847 const char *p;
1848 char option[128];
1850 p = *pstr;
1851 for(;;) {
1852 p = get_opt_name(option, sizeof(option), p, '=');
1853 if (*p != '=')
1854 break;
1855 p++;
1856 if (!strcmp(tag, option)) {
1857 *pstr = get_opt_value(buf, buf_size, p);
1858 if (**pstr == ',') {
1859 (*pstr)++;
1861 return strlen(buf);
1862 } else {
1863 p = get_opt_value(NULL, 0, p);
1865 if (*p != ',')
1866 break;
1867 p++;
1869 return 0;
1872 int get_param_value(char *buf, int buf_size,
1873 const char *tag, const char *str)
1875 return get_next_param_value(buf, buf_size, tag, &str);
1878 int check_params(char *buf, int buf_size,
1879 const char * const *params, const char *str)
1881 const char *p;
1882 int i;
1884 p = str;
1885 while (*p != '\0') {
1886 p = get_opt_name(buf, buf_size, p, '=');
1887 if (*p != '=') {
1888 return -1;
1890 p++;
1891 for (i = 0; params[i] != NULL; i++) {
1892 if (!strcmp(params[i], buf)) {
1893 break;
1896 if (params[i] == NULL) {
1897 return -1;
1899 p = get_opt_value(NULL, 0, p);
1900 if (*p != ',') {
1901 break;
1903 p++;
1905 return 0;
1908 /***********************************************************/
1909 /* Bluetooth support */
1910 static int nb_hcis;
1911 static int cur_hci;
1912 static struct HCIInfo *hci_table[MAX_NICS];
1914 static struct bt_vlan_s {
1915 struct bt_scatternet_s net;
1916 int id;
1917 struct bt_vlan_s *next;
1918 } *first_bt_vlan;
1920 /* find or alloc a new bluetooth "VLAN" */
1921 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1923 struct bt_vlan_s **pvlan, *vlan;
1924 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1925 if (vlan->id == id)
1926 return &vlan->net;
1928 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1929 vlan->id = id;
1930 pvlan = &first_bt_vlan;
1931 while (*pvlan != NULL)
1932 pvlan = &(*pvlan)->next;
1933 *pvlan = vlan;
1934 return &vlan->net;
1937 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1941 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1943 return -ENOTSUP;
1946 static struct HCIInfo null_hci = {
1947 .cmd_send = null_hci_send,
1948 .sco_send = null_hci_send,
1949 .acl_send = null_hci_send,
1950 .bdaddr_set = null_hci_addr_set,
1953 struct HCIInfo *qemu_next_hci(void)
1955 if (cur_hci == nb_hcis)
1956 return &null_hci;
1958 return hci_table[cur_hci++];
1961 static struct HCIInfo *hci_init(const char *str)
1963 char *endp;
1964 struct bt_scatternet_s *vlan = 0;
1966 if (!strcmp(str, "null"))
1967 /* null */
1968 return &null_hci;
1969 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1970 /* host[:hciN] */
1971 return bt_host_hci(str[4] ? str + 5 : "hci0");
1972 else if (!strncmp(str, "hci", 3)) {
1973 /* hci[,vlan=n] */
1974 if (str[3]) {
1975 if (!strncmp(str + 3, ",vlan=", 6)) {
1976 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1977 if (*endp)
1978 vlan = 0;
1980 } else
1981 vlan = qemu_find_bt_vlan(0);
1982 if (vlan)
1983 return bt_new_hci(vlan);
1986 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1988 return 0;
1991 static int bt_hci_parse(const char *str)
1993 struct HCIInfo *hci;
1994 bdaddr_t bdaddr;
1996 if (nb_hcis >= MAX_NICS) {
1997 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1998 return -1;
2001 hci = hci_init(str);
2002 if (!hci)
2003 return -1;
2005 bdaddr.b[0] = 0x52;
2006 bdaddr.b[1] = 0x54;
2007 bdaddr.b[2] = 0x00;
2008 bdaddr.b[3] = 0x12;
2009 bdaddr.b[4] = 0x34;
2010 bdaddr.b[5] = 0x56 + nb_hcis;
2011 hci->bdaddr_set(hci, bdaddr.b);
2013 hci_table[nb_hcis++] = hci;
2015 return 0;
2018 static void bt_vhci_add(int vlan_id)
2020 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2022 if (!vlan->slave)
2023 fprintf(stderr, "qemu: warning: adding a VHCI to "
2024 "an empty scatternet %i\n", vlan_id);
2026 bt_vhci_init(bt_new_hci(vlan));
2029 static struct bt_device_s *bt_device_add(const char *opt)
2031 struct bt_scatternet_s *vlan;
2032 int vlan_id = 0;
2033 char *endp = strstr(opt, ",vlan=");
2034 int len = (endp ? endp - opt : strlen(opt)) + 1;
2035 char devname[10];
2037 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2039 if (endp) {
2040 vlan_id = strtol(endp + 6, &endp, 0);
2041 if (*endp) {
2042 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2043 return 0;
2047 vlan = qemu_find_bt_vlan(vlan_id);
2049 if (!vlan->slave)
2050 fprintf(stderr, "qemu: warning: adding a slave device to "
2051 "an empty scatternet %i\n", vlan_id);
2053 if (!strcmp(devname, "keyboard"))
2054 return bt_keyboard_init(vlan);
2056 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2057 return 0;
2060 static int bt_parse(const char *opt)
2062 const char *endp, *p;
2063 int vlan;
2065 if (strstart(opt, "hci", &endp)) {
2066 if (!*endp || *endp == ',') {
2067 if (*endp)
2068 if (!strstart(endp, ",vlan=", 0))
2069 opt = endp + 1;
2071 return bt_hci_parse(opt);
2073 } else if (strstart(opt, "vhci", &endp)) {
2074 if (!*endp || *endp == ',') {
2075 if (*endp) {
2076 if (strstart(endp, ",vlan=", &p)) {
2077 vlan = strtol(p, (char **) &endp, 0);
2078 if (*endp) {
2079 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2080 return 1;
2082 } else {
2083 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2084 return 1;
2086 } else
2087 vlan = 0;
2089 bt_vhci_add(vlan);
2090 return 0;
2092 } else if (strstart(opt, "device:", &endp))
2093 return !bt_device_add(endp);
2095 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2096 return 1;
2099 /***********************************************************/
2100 /* QEMU Block devices */
2102 #define HD_ALIAS "index=%d,media=disk"
2103 #define CDROM_ALIAS "index=2,media=cdrom"
2104 #define FD_ALIAS "index=%d,if=floppy"
2105 #define PFLASH_ALIAS "if=pflash"
2106 #define MTD_ALIAS "if=mtd"
2107 #define SD_ALIAS "index=0,if=sd"
2109 static int drive_opt_get_free_idx(void)
2111 int index;
2113 for (index = 0; index < MAX_DRIVES; index++)
2114 if (!drives_opt[index].used) {
2115 drives_opt[index].used = 1;
2116 return index;
2119 return -1;
2122 static int drive_get_free_idx(void)
2124 int index;
2126 for (index = 0; index < MAX_DRIVES; index++)
2127 if (!drives_table[index].used) {
2128 drives_table[index].used = 1;
2129 return index;
2132 return -1;
2135 int drive_add(const char *file, const char *fmt, ...)
2137 va_list ap;
2138 int index = drive_opt_get_free_idx();
2140 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2141 fprintf(stderr, "qemu: too many drives\n");
2142 return -1;
2145 drives_opt[index].file = file;
2146 va_start(ap, fmt);
2147 vsnprintf(drives_opt[index].opt,
2148 sizeof(drives_opt[0].opt), fmt, ap);
2149 va_end(ap);
2151 nb_drives_opt++;
2152 return index;
2155 void drive_remove(int index)
2157 drives_opt[index].used = 0;
2158 nb_drives_opt--;
2161 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2163 int index;
2165 /* seek interface, bus and unit */
2167 for (index = 0; index < MAX_DRIVES; index++)
2168 if (drives_table[index].type == type &&
2169 drives_table[index].bus == bus &&
2170 drives_table[index].unit == unit &&
2171 drives_table[index].used)
2172 return index;
2174 return -1;
2177 int drive_get_max_bus(BlockInterfaceType type)
2179 int max_bus;
2180 int index;
2182 max_bus = -1;
2183 for (index = 0; index < nb_drives; index++) {
2184 if(drives_table[index].type == type &&
2185 drives_table[index].bus > max_bus)
2186 max_bus = drives_table[index].bus;
2188 return max_bus;
2191 const char *drive_get_serial(BlockDriverState *bdrv)
2193 int index;
2195 for (index = 0; index < nb_drives; index++)
2196 if (drives_table[index].bdrv == bdrv)
2197 return drives_table[index].serial;
2199 return "\0";
2202 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2204 int index;
2206 for (index = 0; index < nb_drives; index++)
2207 if (drives_table[index].bdrv == bdrv)
2208 return drives_table[index].onerror;
2210 return BLOCK_ERR_STOP_ENOSPC;
2213 static void bdrv_format_print(void *opaque, const char *name)
2215 fprintf(stderr, " %s", name);
2218 void drive_uninit(BlockDriverState *bdrv)
2220 int i;
2222 for (i = 0; i < MAX_DRIVES; i++)
2223 if (drives_table[i].bdrv == bdrv) {
2224 drives_table[i].bdrv = NULL;
2225 drives_table[i].used = 0;
2226 drive_remove(drives_table[i].drive_opt_idx);
2227 nb_drives--;
2228 break;
2232 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2234 char buf[128];
2235 char file[1024];
2236 char devname[128];
2237 char serial[21];
2238 const char *mediastr = "";
2239 BlockInterfaceType type;
2240 enum { MEDIA_DISK, MEDIA_CDROM } media;
2241 int bus_id, unit_id;
2242 int cyls, heads, secs, translation;
2243 BlockDriverState *bdrv;
2244 BlockDriver *drv = NULL;
2245 QEMUMachine *machine = opaque;
2246 int max_devs;
2247 int index;
2248 int cache;
2249 int bdrv_flags, onerror;
2250 const char *devaddr;
2251 int drives_table_idx;
2252 char *str = arg->opt;
2253 static const char * const params[] = { "bus", "unit", "if", "index",
2254 "cyls", "heads", "secs", "trans",
2255 "media", "snapshot", "file",
2256 "cache", "format", "serial",
2257 "werror", "addr",
2258 "boot",
2259 NULL };
2261 if (check_params(buf, sizeof(buf), params, str) < 0) {
2262 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2263 buf, str);
2264 return -1;
2267 file[0] = 0;
2268 cyls = heads = secs = 0;
2269 bus_id = 0;
2270 unit_id = -1;
2271 translation = BIOS_ATA_TRANSLATION_AUTO;
2272 index = -1;
2273 cache = 3;
2275 if (machine->use_scsi) {
2276 type = IF_SCSI;
2277 max_devs = MAX_SCSI_DEVS;
2278 pstrcpy(devname, sizeof(devname), "scsi");
2279 } else {
2280 type = IF_IDE;
2281 max_devs = MAX_IDE_DEVS;
2282 pstrcpy(devname, sizeof(devname), "ide");
2284 media = MEDIA_DISK;
2286 /* extract parameters */
2288 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2289 bus_id = strtol(buf, NULL, 0);
2290 if (bus_id < 0) {
2291 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2292 return -1;
2296 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2297 unit_id = strtol(buf, NULL, 0);
2298 if (unit_id < 0) {
2299 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2300 return -1;
2304 if (get_param_value(buf, sizeof(buf), "if", str)) {
2305 pstrcpy(devname, sizeof(devname), buf);
2306 if (!strcmp(buf, "ide")) {
2307 type = IF_IDE;
2308 max_devs = MAX_IDE_DEVS;
2309 } else if (!strcmp(buf, "scsi")) {
2310 type = IF_SCSI;
2311 max_devs = MAX_SCSI_DEVS;
2312 } else if (!strcmp(buf, "floppy")) {
2313 type = IF_FLOPPY;
2314 max_devs = 0;
2315 } else if (!strcmp(buf, "pflash")) {
2316 type = IF_PFLASH;
2317 max_devs = 0;
2318 } else if (!strcmp(buf, "mtd")) {
2319 type = IF_MTD;
2320 max_devs = 0;
2321 } else if (!strcmp(buf, "sd")) {
2322 type = IF_SD;
2323 max_devs = 0;
2324 } else if (!strcmp(buf, "virtio")) {
2325 type = IF_VIRTIO;
2326 max_devs = 0;
2327 } else if (!strcmp(buf, "xen")) {
2328 type = IF_XEN;
2329 max_devs = 0;
2330 } else {
2331 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2332 return -1;
2336 if (get_param_value(buf, sizeof(buf), "index", str)) {
2337 index = strtol(buf, NULL, 0);
2338 if (index < 0) {
2339 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2340 return -1;
2344 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2345 cyls = strtol(buf, NULL, 0);
2348 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2349 heads = strtol(buf, NULL, 0);
2352 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2353 secs = strtol(buf, NULL, 0);
2356 if (cyls || heads || secs) {
2357 if (cyls < 1 || cyls > 16383) {
2358 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2359 return -1;
2361 if (heads < 1 || heads > 16) {
2362 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2363 return -1;
2365 if (secs < 1 || secs > 63) {
2366 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2367 return -1;
2371 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2372 if (!cyls) {
2373 fprintf(stderr,
2374 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2375 str);
2376 return -1;
2378 if (!strcmp(buf, "none"))
2379 translation = BIOS_ATA_TRANSLATION_NONE;
2380 else if (!strcmp(buf, "lba"))
2381 translation = BIOS_ATA_TRANSLATION_LBA;
2382 else if (!strcmp(buf, "auto"))
2383 translation = BIOS_ATA_TRANSLATION_AUTO;
2384 else {
2385 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2386 return -1;
2390 if (get_param_value(buf, sizeof(buf), "media", str)) {
2391 if (!strcmp(buf, "disk")) {
2392 media = MEDIA_DISK;
2393 } else if (!strcmp(buf, "cdrom")) {
2394 if (cyls || secs || heads) {
2395 fprintf(stderr,
2396 "qemu: '%s' invalid physical CHS format\n", str);
2397 return -1;
2399 media = MEDIA_CDROM;
2400 } else {
2401 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2402 return -1;
2406 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2407 if (!strcmp(buf, "on"))
2408 snapshot = 1;
2409 else if (!strcmp(buf, "off"))
2410 snapshot = 0;
2411 else {
2412 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2413 return -1;
2417 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2418 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2419 cache = 0;
2420 else if (!strcmp(buf, "writethrough"))
2421 cache = 1;
2422 else if (!strcmp(buf, "writeback"))
2423 cache = 2;
2424 else {
2425 fprintf(stderr, "qemu: invalid cache option\n");
2426 return -1;
2430 if (get_param_value(buf, sizeof(buf), "format", str)) {
2431 if (strcmp(buf, "?") == 0) {
2432 fprintf(stderr, "qemu: Supported formats:");
2433 bdrv_iterate_format(bdrv_format_print, NULL);
2434 fprintf(stderr, "\n");
2435 return -1;
2437 drv = bdrv_find_format(buf);
2438 if (!drv) {
2439 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2440 return -1;
2444 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2445 if (!strcmp(buf, "on")) {
2446 if (extboot_drive != -1) {
2447 fprintf(stderr, "qemu: two bootable drives specified\n");
2448 return -1;
2450 extboot_drive = nb_drives;
2451 } else if (strcmp(buf, "off")) {
2452 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2453 return -1;
2457 if (arg->file == NULL)
2458 get_param_value(file, sizeof(file), "file", str);
2459 else
2460 pstrcpy(file, sizeof(file), arg->file);
2462 if (!get_param_value(serial, sizeof(serial), "serial", str))
2463 memset(serial, 0, sizeof(serial));
2465 onerror = BLOCK_ERR_STOP_ENOSPC;
2466 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2467 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2468 fprintf(stderr, "werror is no supported by this format\n");
2469 return -1;
2471 if (!strcmp(buf, "ignore"))
2472 onerror = BLOCK_ERR_IGNORE;
2473 else if (!strcmp(buf, "enospc"))
2474 onerror = BLOCK_ERR_STOP_ENOSPC;
2475 else if (!strcmp(buf, "stop"))
2476 onerror = BLOCK_ERR_STOP_ANY;
2477 else if (!strcmp(buf, "report"))
2478 onerror = BLOCK_ERR_REPORT;
2479 else {
2480 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2481 return -1;
2485 devaddr = NULL;
2486 if (get_param_value(buf, sizeof(buf), "addr", str)) {
2487 if (type != IF_VIRTIO) {
2488 fprintf(stderr, "addr is not supported by in '%s'\n", str);
2489 return -1;
2491 devaddr = strdup(buf);
2494 /* compute bus and unit according index */
2496 if (index != -1) {
2497 if (bus_id != 0 || unit_id != -1) {
2498 fprintf(stderr,
2499 "qemu: '%s' index cannot be used with bus and unit\n", str);
2500 return -1;
2502 if (max_devs == 0)
2504 unit_id = index;
2505 bus_id = 0;
2506 } else {
2507 unit_id = index % max_devs;
2508 bus_id = index / max_devs;
2512 /* if user doesn't specify a unit_id,
2513 * try to find the first free
2516 if (unit_id == -1) {
2517 unit_id = 0;
2518 while (drive_get_index(type, bus_id, unit_id) != -1) {
2519 unit_id++;
2520 if (max_devs && unit_id >= max_devs) {
2521 unit_id -= max_devs;
2522 bus_id++;
2527 /* check unit id */
2529 if (max_devs && unit_id >= max_devs) {
2530 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2531 str, unit_id, max_devs - 1);
2532 return -1;
2536 * ignore multiple definitions
2539 if (drive_get_index(type, bus_id, unit_id) != -1)
2540 return -2;
2542 /* init */
2544 if (type == IF_IDE || type == IF_SCSI)
2545 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2546 if (max_devs)
2547 snprintf(buf, sizeof(buf), "%s%i%s%i",
2548 devname, bus_id, mediastr, unit_id);
2549 else
2550 snprintf(buf, sizeof(buf), "%s%s%i",
2551 devname, mediastr, unit_id);
2552 bdrv = bdrv_new(buf);
2553 drives_table_idx = drive_get_free_idx();
2554 drives_table[drives_table_idx].bdrv = bdrv;
2555 drives_table[drives_table_idx].devaddr = devaddr;
2556 drives_table[drives_table_idx].type = type;
2557 drives_table[drives_table_idx].bus = bus_id;
2558 drives_table[drives_table_idx].unit = unit_id;
2559 drives_table[drives_table_idx].onerror = onerror;
2560 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2561 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2562 nb_drives++;
2564 switch(type) {
2565 case IF_IDE:
2566 case IF_SCSI:
2567 case IF_XEN:
2568 switch(media) {
2569 case MEDIA_DISK:
2570 if (cyls != 0) {
2571 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2572 bdrv_set_translation_hint(bdrv, translation);
2574 break;
2575 case MEDIA_CDROM:
2576 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2577 break;
2579 break;
2580 case IF_SD:
2581 /* FIXME: This isn't really a floppy, but it's a reasonable
2582 approximation. */
2583 case IF_FLOPPY:
2584 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2585 break;
2586 case IF_PFLASH:
2587 case IF_MTD:
2588 case IF_VIRTIO:
2589 break;
2590 case IF_COUNT:
2591 abort();
2593 if (!file[0])
2594 return -2;
2595 bdrv_flags = 0;
2596 if (snapshot) {
2597 bdrv_flags |= BDRV_O_SNAPSHOT;
2598 cache = 2; /* always use write-back with snapshot */
2600 if (cache == 0) /* no caching */
2601 bdrv_flags |= BDRV_O_NOCACHE;
2602 else if (cache == 2) /* write-back */
2603 bdrv_flags |= BDRV_O_CACHE_WB;
2604 else if (cache == 3) /* not specified */
2605 bdrv_flags |= BDRV_O_CACHE_DEF;
2606 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2607 fprintf(stderr, "qemu: could not open disk image %s\n",
2608 file);
2609 return -1;
2611 if (bdrv_key_required(bdrv))
2612 autostart = 0;
2613 return drives_table_idx;
2616 static void numa_add(const char *optarg)
2618 char option[128];
2619 char *endptr;
2620 unsigned long long value, endvalue;
2621 int nodenr;
2623 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2624 if (!strcmp(option, "node")) {
2625 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2626 nodenr = nb_numa_nodes;
2627 } else {
2628 nodenr = strtoull(option, NULL, 10);
2631 if (get_param_value(option, 128, "mem", optarg) == 0) {
2632 node_mem[nodenr] = 0;
2633 } else {
2634 value = strtoull(option, &endptr, 0);
2635 switch (*endptr) {
2636 case 0: case 'M': case 'm':
2637 value <<= 20;
2638 break;
2639 case 'G': case 'g':
2640 value <<= 30;
2641 break;
2643 node_mem[nodenr] = value;
2645 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2646 node_cpumask[nodenr] = 0;
2647 } else {
2648 value = strtoull(option, &endptr, 10);
2649 if (value >= 64) {
2650 value = 63;
2651 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2652 } else {
2653 if (*endptr == '-') {
2654 endvalue = strtoull(endptr+1, &endptr, 10);
2655 if (endvalue >= 63) {
2656 endvalue = 62;
2657 fprintf(stderr,
2658 "only 63 CPUs in NUMA mode supported.\n");
2660 value = (1 << (endvalue + 1)) - (1 << value);
2661 } else {
2662 value = 1 << value;
2665 node_cpumask[nodenr] = value;
2667 nb_numa_nodes++;
2669 return;
2672 /***********************************************************/
2673 /* USB devices */
2675 static USBPort *used_usb_ports;
2676 static USBPort *free_usb_ports;
2678 /* ??? Maybe change this to register a hub to keep track of the topology. */
2679 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2680 usb_attachfn attach)
2682 port->opaque = opaque;
2683 port->index = index;
2684 port->attach = attach;
2685 port->next = free_usb_ports;
2686 free_usb_ports = port;
2689 int usb_device_add_dev(USBDevice *dev)
2691 USBPort *port;
2693 /* Find a USB port to add the device to. */
2694 port = free_usb_ports;
2695 if (!port->next) {
2696 USBDevice *hub;
2698 /* Create a new hub and chain it on. */
2699 free_usb_ports = NULL;
2700 port->next = used_usb_ports;
2701 used_usb_ports = port;
2703 hub = usb_hub_init(VM_USB_HUB_SIZE);
2704 usb_attach(port, hub);
2705 port = free_usb_ports;
2708 free_usb_ports = port->next;
2709 port->next = used_usb_ports;
2710 used_usb_ports = port;
2711 usb_attach(port, dev);
2712 return 0;
2715 static void usb_msd_password_cb(void *opaque, int err)
2717 USBDevice *dev = opaque;
2719 if (!err)
2720 usb_device_add_dev(dev);
2721 else
2722 dev->handle_destroy(dev);
2725 static int usb_device_add(const char *devname, int is_hotplug)
2727 const char *p;
2728 USBDevice *dev;
2730 if (!free_usb_ports)
2731 return -1;
2733 if (strstart(devname, "host:", &p)) {
2734 dev = usb_host_device_open(p);
2735 } else if (!strcmp(devname, "mouse")) {
2736 dev = usb_mouse_init();
2737 } else if (!strcmp(devname, "tablet")) {
2738 dev = usb_tablet_init();
2739 } else if (!strcmp(devname, "keyboard")) {
2740 dev = usb_keyboard_init();
2741 } else if (strstart(devname, "disk:", &p)) {
2742 BlockDriverState *bs;
2744 dev = usb_msd_init(p);
2745 if (!dev)
2746 return -1;
2747 bs = usb_msd_get_bdrv(dev);
2748 if (bdrv_key_required(bs)) {
2749 autostart = 0;
2750 if (is_hotplug) {
2751 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2752 dev);
2753 return 0;
2756 } else if (!strcmp(devname, "wacom-tablet")) {
2757 dev = usb_wacom_init();
2758 } else if (strstart(devname, "serial:", &p)) {
2759 dev = usb_serial_init(p);
2760 #ifdef CONFIG_BRLAPI
2761 } else if (!strcmp(devname, "braille")) {
2762 dev = usb_baum_init();
2763 #endif
2764 } else if (strstart(devname, "net:", &p)) {
2765 int nic = nb_nics;
2767 if (net_client_init(NULL, "nic", p) < 0)
2768 return -1;
2769 nd_table[nic].model = "usb";
2770 dev = usb_net_init(&nd_table[nic]);
2771 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2772 dev = usb_bt_init(devname[2] ? hci_init(p) :
2773 bt_new_hci(qemu_find_bt_vlan(0)));
2774 } else {
2775 return -1;
2777 if (!dev)
2778 return -1;
2780 return usb_device_add_dev(dev);
2783 int usb_device_del_addr(int bus_num, int addr)
2785 USBPort *port;
2786 USBPort **lastp;
2787 USBDevice *dev;
2789 if (!used_usb_ports)
2790 return -1;
2792 if (bus_num != 0)
2793 return -1;
2795 lastp = &used_usb_ports;
2796 port = used_usb_ports;
2797 while (port && port->dev->addr != addr) {
2798 lastp = &port->next;
2799 port = port->next;
2802 if (!port)
2803 return -1;
2805 dev = port->dev;
2806 *lastp = port->next;
2807 usb_attach(port, NULL);
2808 dev->handle_destroy(dev);
2809 port->next = free_usb_ports;
2810 free_usb_ports = port;
2811 return 0;
2814 static int usb_device_del(const char *devname)
2816 int bus_num, addr;
2817 const char *p;
2819 if (strstart(devname, "host:", &p))
2820 return usb_host_device_close(p);
2822 if (!used_usb_ports)
2823 return -1;
2825 p = strchr(devname, '.');
2826 if (!p)
2827 return -1;
2828 bus_num = strtoul(devname, NULL, 0);
2829 addr = strtoul(p + 1, NULL, 0);
2831 return usb_device_del_addr(bus_num, addr);
2834 void do_usb_add(Monitor *mon, const char *devname)
2836 usb_device_add(devname, 1);
2839 void do_usb_del(Monitor *mon, const char *devname)
2841 usb_device_del(devname);
2844 void usb_info(Monitor *mon)
2846 USBDevice *dev;
2847 USBPort *port;
2848 const char *speed_str;
2850 if (!usb_enabled) {
2851 monitor_printf(mon, "USB support not enabled\n");
2852 return;
2855 for (port = used_usb_ports; port; port = port->next) {
2856 dev = port->dev;
2857 if (!dev)
2858 continue;
2859 switch(dev->speed) {
2860 case USB_SPEED_LOW:
2861 speed_str = "1.5";
2862 break;
2863 case USB_SPEED_FULL:
2864 speed_str = "12";
2865 break;
2866 case USB_SPEED_HIGH:
2867 speed_str = "480";
2868 break;
2869 default:
2870 speed_str = "?";
2871 break;
2873 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2874 0, dev->addr, speed_str, dev->devname);
2878 /***********************************************************/
2879 /* PCMCIA/Cardbus */
2881 static struct pcmcia_socket_entry_s {
2882 PCMCIASocket *socket;
2883 struct pcmcia_socket_entry_s *next;
2884 } *pcmcia_sockets = 0;
2886 void pcmcia_socket_register(PCMCIASocket *socket)
2888 struct pcmcia_socket_entry_s *entry;
2890 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2891 entry->socket = socket;
2892 entry->next = pcmcia_sockets;
2893 pcmcia_sockets = entry;
2896 void pcmcia_socket_unregister(PCMCIASocket *socket)
2898 struct pcmcia_socket_entry_s *entry, **ptr;
2900 ptr = &pcmcia_sockets;
2901 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2902 if (entry->socket == socket) {
2903 *ptr = entry->next;
2904 qemu_free(entry);
2908 void pcmcia_info(Monitor *mon)
2910 struct pcmcia_socket_entry_s *iter;
2912 if (!pcmcia_sockets)
2913 monitor_printf(mon, "No PCMCIA sockets\n");
2915 for (iter = pcmcia_sockets; iter; iter = iter->next)
2916 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2917 iter->socket->attached ? iter->socket->card_string :
2918 "Empty");
2921 /***********************************************************/
2922 /* register display */
2924 struct DisplayAllocator default_allocator = {
2925 defaultallocator_create_displaysurface,
2926 defaultallocator_resize_displaysurface,
2927 defaultallocator_free_displaysurface
2930 void register_displaystate(DisplayState *ds)
2932 DisplayState **s;
2933 s = &display_state;
2934 while (*s != NULL)
2935 s = &(*s)->next;
2936 ds->next = NULL;
2937 *s = ds;
2940 DisplayState *get_displaystate(void)
2942 return display_state;
2945 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2947 if(ds->allocator == &default_allocator) ds->allocator = da;
2948 return ds->allocator;
2951 /* dumb display */
2953 static void dumb_display_init(void)
2955 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2956 ds->allocator = &default_allocator;
2957 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2958 register_displaystate(ds);
2961 /***********************************************************/
2962 /* I/O handling */
2964 typedef struct IOHandlerRecord {
2965 int fd;
2966 IOCanRWHandler *fd_read_poll;
2967 IOHandler *fd_read;
2968 IOHandler *fd_write;
2969 int deleted;
2970 void *opaque;
2971 /* temporary data */
2972 struct pollfd *ufd;
2973 struct IOHandlerRecord *next;
2974 } IOHandlerRecord;
2976 static IOHandlerRecord *first_io_handler;
2978 /* XXX: fd_read_poll should be suppressed, but an API change is
2979 necessary in the character devices to suppress fd_can_read(). */
2980 int qemu_set_fd_handler2(int fd,
2981 IOCanRWHandler *fd_read_poll,
2982 IOHandler *fd_read,
2983 IOHandler *fd_write,
2984 void *opaque)
2986 IOHandlerRecord **pioh, *ioh;
2988 if (!fd_read && !fd_write) {
2989 pioh = &first_io_handler;
2990 for(;;) {
2991 ioh = *pioh;
2992 if (ioh == NULL)
2993 break;
2994 if (ioh->fd == fd) {
2995 ioh->deleted = 1;
2996 break;
2998 pioh = &ioh->next;
3000 } else {
3001 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3002 if (ioh->fd == fd)
3003 goto found;
3005 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3006 ioh->next = first_io_handler;
3007 first_io_handler = ioh;
3008 found:
3009 ioh->fd = fd;
3010 ioh->fd_read_poll = fd_read_poll;
3011 ioh->fd_read = fd_read;
3012 ioh->fd_write = fd_write;
3013 ioh->opaque = opaque;
3014 ioh->deleted = 0;
3016 qemu_notify_event();
3017 return 0;
3020 int qemu_set_fd_handler(int fd,
3021 IOHandler *fd_read,
3022 IOHandler *fd_write,
3023 void *opaque)
3025 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3028 #ifdef _WIN32
3029 /***********************************************************/
3030 /* Polling handling */
3032 typedef struct PollingEntry {
3033 PollingFunc *func;
3034 void *opaque;
3035 struct PollingEntry *next;
3036 } PollingEntry;
3038 static PollingEntry *first_polling_entry;
3040 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3042 PollingEntry **ppe, *pe;
3043 pe = qemu_mallocz(sizeof(PollingEntry));
3044 pe->func = func;
3045 pe->opaque = opaque;
3046 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3047 *ppe = pe;
3048 return 0;
3051 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3053 PollingEntry **ppe, *pe;
3054 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3055 pe = *ppe;
3056 if (pe->func == func && pe->opaque == opaque) {
3057 *ppe = pe->next;
3058 qemu_free(pe);
3059 break;
3064 /***********************************************************/
3065 /* Wait objects support */
3066 typedef struct WaitObjects {
3067 int num;
3068 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3069 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3070 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3071 } WaitObjects;
3073 static WaitObjects wait_objects = {0};
3075 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3077 WaitObjects *w = &wait_objects;
3079 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3080 return -1;
3081 w->events[w->num] = handle;
3082 w->func[w->num] = func;
3083 w->opaque[w->num] = opaque;
3084 w->num++;
3085 return 0;
3088 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3090 int i, found;
3091 WaitObjects *w = &wait_objects;
3093 found = 0;
3094 for (i = 0; i < w->num; i++) {
3095 if (w->events[i] == handle)
3096 found = 1;
3097 if (found) {
3098 w->events[i] = w->events[i + 1];
3099 w->func[i] = w->func[i + 1];
3100 w->opaque[i] = w->opaque[i + 1];
3103 if (found)
3104 w->num--;
3106 #endif
3108 /***********************************************************/
3109 /* ram save/restore */
3111 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3113 int v;
3115 v = qemu_get_byte(f);
3116 switch(v) {
3117 case 0:
3118 if (qemu_get_buffer(f, buf, len) != len)
3119 return -EIO;
3120 break;
3121 case 1:
3122 v = qemu_get_byte(f);
3123 memset(buf, v, len);
3124 break;
3125 default:
3126 return -EINVAL;
3129 if (qemu_file_has_error(f))
3130 return -EIO;
3132 return 0;
3135 static int ram_load_v1(QEMUFile *f, void *opaque)
3137 int ret;
3138 ram_addr_t i;
3140 if (qemu_get_be32(f) != last_ram_offset)
3141 return -EINVAL;
3142 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
3143 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3144 continue;
3145 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
3146 if (ret)
3147 return ret;
3149 return 0;
3152 #define BDRV_HASH_BLOCK_SIZE 1024
3153 #define IOBUF_SIZE 4096
3154 #define RAM_CBLOCK_MAGIC 0xfabe
3156 typedef struct RamDecompressState {
3157 z_stream zstream;
3158 QEMUFile *f;
3159 uint8_t buf[IOBUF_SIZE];
3160 } RamDecompressState;
3162 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3164 int ret;
3165 memset(s, 0, sizeof(*s));
3166 s->f = f;
3167 ret = inflateInit(&s->zstream);
3168 if (ret != Z_OK)
3169 return -1;
3170 return 0;
3173 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3175 int ret, clen;
3177 s->zstream.avail_out = len;
3178 s->zstream.next_out = buf;
3179 while (s->zstream.avail_out > 0) {
3180 if (s->zstream.avail_in == 0) {
3181 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3182 return -1;
3183 clen = qemu_get_be16(s->f);
3184 if (clen > IOBUF_SIZE)
3185 return -1;
3186 qemu_get_buffer(s->f, s->buf, clen);
3187 s->zstream.avail_in = clen;
3188 s->zstream.next_in = s->buf;
3190 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3191 if (ret != Z_OK && ret != Z_STREAM_END) {
3192 return -1;
3195 return 0;
3198 static void ram_decompress_close(RamDecompressState *s)
3200 inflateEnd(&s->zstream);
3203 #define RAM_SAVE_FLAG_FULL 0x01
3204 #define RAM_SAVE_FLAG_COMPRESS 0x02
3205 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3206 #define RAM_SAVE_FLAG_PAGE 0x08
3207 #define RAM_SAVE_FLAG_EOS 0x10
3209 static int is_dup_page(uint8_t *page, uint8_t ch)
3211 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3212 uint32_t *array = (uint32_t *)page;
3213 int i;
3215 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3216 if (array[i] != val)
3217 return 0;
3220 return 1;
3223 static int ram_save_block(QEMUFile *f)
3225 static ram_addr_t current_addr = 0;
3226 ram_addr_t saved_addr = current_addr;
3227 ram_addr_t addr = 0;
3228 int found = 0;
3230 while (addr < last_ram_offset) {
3231 if (kvm_enabled() && current_addr == 0) {
3232 int r;
3233 r = kvm_update_dirty_pages_log();
3234 if (r) {
3235 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3236 qemu_file_set_error(f);
3237 return 0;
3240 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3241 uint8_t *p;
3243 cpu_physical_memory_reset_dirty(current_addr,
3244 current_addr + TARGET_PAGE_SIZE,
3245 MIGRATION_DIRTY_FLAG);
3247 p = qemu_get_ram_ptr(current_addr);
3249 if (is_dup_page(p, *p)) {
3250 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3251 qemu_put_byte(f, *p);
3252 } else {
3253 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3254 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3257 found = 1;
3258 break;
3260 addr += TARGET_PAGE_SIZE;
3261 current_addr = (saved_addr + addr) % last_ram_offset;
3264 return found;
3267 static uint64_t bytes_transferred = 0;
3269 static ram_addr_t ram_save_remaining(void)
3271 ram_addr_t addr;
3272 ram_addr_t count = 0;
3274 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3275 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3276 count++;
3279 return count;
3282 uint64_t ram_bytes_remaining(void)
3284 return ram_save_remaining() * TARGET_PAGE_SIZE;
3287 uint64_t ram_bytes_transferred(void)
3289 return bytes_transferred;
3292 uint64_t ram_bytes_total(void)
3294 return last_ram_offset;
3297 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3299 ram_addr_t addr;
3300 uint64_t bytes_transferred_last;
3301 double bwidth = 0;
3302 uint64_t expected_time = 0;
3304 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3305 qemu_file_set_error(f);
3306 return 0;
3309 if (stage == 1) {
3310 /* Make sure all dirty bits are set */
3311 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3312 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3313 cpu_physical_memory_set_dirty(addr);
3316 /* Enable dirty memory tracking */
3317 cpu_physical_memory_set_dirty_tracking(1);
3319 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3322 bytes_transferred_last = bytes_transferred;
3323 bwidth = get_clock();
3325 while (!qemu_file_rate_limit(f)) {
3326 int ret;
3328 ret = ram_save_block(f);
3329 bytes_transferred += ret * TARGET_PAGE_SIZE;
3330 if (ret == 0) /* no more blocks */
3331 break;
3334 bwidth = get_clock() - bwidth;
3335 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3337 /* if we haven't transferred anything this round, force expected_time to a
3338 * a very high value, but without crashing */
3339 if (bwidth == 0)
3340 bwidth = 0.000001;
3342 /* try transferring iterative blocks of memory */
3344 if (stage == 3) {
3346 /* flush all remaining blocks regardless of rate limiting */
3347 while (ram_save_block(f) != 0) {
3348 bytes_transferred += TARGET_PAGE_SIZE;
3350 cpu_physical_memory_set_dirty_tracking(0);
3353 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3355 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3357 return (stage == 2) && (expected_time <= migrate_max_downtime());
3360 static int ram_load_dead(QEMUFile *f, void *opaque)
3362 RamDecompressState s1, *s = &s1;
3363 uint8_t buf[10];
3364 ram_addr_t i;
3366 if (ram_decompress_open(s, f) < 0)
3367 return -EINVAL;
3368 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3369 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3370 continue;
3371 if (ram_decompress_buf(s, buf, 1) < 0) {
3372 fprintf(stderr, "Error while reading ram block header\n");
3373 goto error;
3375 if (buf[0] == 0) {
3376 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3377 BDRV_HASH_BLOCK_SIZE) < 0) {
3378 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3379 goto error;
3381 } else {
3382 error:
3383 printf("Error block header\n");
3384 return -EINVAL;
3387 ram_decompress_close(s);
3389 return 0;
3392 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3394 ram_addr_t addr;
3395 int flags;
3397 if (version_id == 1)
3398 return ram_load_v1(f, opaque);
3400 if (version_id == 2) {
3401 if (qemu_get_be32(f) != last_ram_offset)
3402 return -EINVAL;
3403 return ram_load_dead(f, opaque);
3406 if (version_id != 3)
3407 return -EINVAL;
3409 do {
3410 addr = qemu_get_be64(f);
3412 flags = addr & ~TARGET_PAGE_MASK;
3413 addr &= TARGET_PAGE_MASK;
3415 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3416 if (addr != last_ram_offset)
3417 return -EINVAL;
3420 if (flags & RAM_SAVE_FLAG_FULL) {
3421 if (ram_load_dead(f, opaque) < 0)
3422 return -EINVAL;
3425 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3426 uint8_t ch = qemu_get_byte(f);
3427 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3428 #ifndef _WIN32
3429 if (ch == 0 &&
3430 (!kvm_enabled() || kvm_has_sync_mmu())) {
3431 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3433 #endif
3434 } else if (flags & RAM_SAVE_FLAG_PAGE)
3435 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3436 } while (!(flags & RAM_SAVE_FLAG_EOS));
3438 return 0;
3441 void qemu_service_io(void)
3443 qemu_notify_event();
3446 /***********************************************************/
3447 /* bottom halves (can be seen as timers which expire ASAP) */
3449 struct QEMUBH {
3450 QEMUBHFunc *cb;
3451 void *opaque;
3452 int scheduled;
3453 int idle;
3454 int deleted;
3455 QEMUBH *next;
3458 static QEMUBH *first_bh = NULL;
3460 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3462 QEMUBH *bh;
3463 bh = qemu_mallocz(sizeof(QEMUBH));
3464 bh->cb = cb;
3465 bh->opaque = opaque;
3466 bh->next = first_bh;
3467 first_bh = bh;
3468 return bh;
3471 int qemu_bh_poll(void)
3473 QEMUBH *bh, **bhp;
3474 int ret;
3476 ret = 0;
3477 for (bh = first_bh; bh; bh = bh->next) {
3478 if (!bh->deleted && bh->scheduled) {
3479 bh->scheduled = 0;
3480 if (!bh->idle)
3481 ret = 1;
3482 bh->idle = 0;
3483 bh->cb(bh->opaque);
3487 /* remove deleted bhs */
3488 bhp = &first_bh;
3489 while (*bhp) {
3490 bh = *bhp;
3491 if (bh->deleted) {
3492 *bhp = bh->next;
3493 qemu_free(bh);
3494 } else
3495 bhp = &bh->next;
3498 return ret;
3501 void qemu_bh_schedule_idle(QEMUBH *bh)
3503 if (bh->scheduled)
3504 return;
3505 bh->scheduled = 1;
3506 bh->idle = 1;
3509 void qemu_bh_schedule(QEMUBH *bh)
3511 if (bh->scheduled)
3512 return;
3513 bh->scheduled = 1;
3514 bh->idle = 0;
3515 /* stop the currently executing CPU to execute the BH ASAP */
3516 qemu_notify_event();
3519 void qemu_bh_cancel(QEMUBH *bh)
3521 bh->scheduled = 0;
3524 void qemu_bh_delete(QEMUBH *bh)
3526 bh->scheduled = 0;
3527 bh->deleted = 1;
3530 static void qemu_bh_update_timeout(int *timeout)
3532 QEMUBH *bh;
3534 for (bh = first_bh; bh; bh = bh->next) {
3535 if (!bh->deleted && bh->scheduled) {
3536 if (bh->idle) {
3537 /* idle bottom halves will be polled at least
3538 * every 10ms */
3539 *timeout = MIN(10, *timeout);
3540 } else {
3541 /* non-idle bottom halves will be executed
3542 * immediately */
3543 *timeout = 0;
3544 break;
3550 /***********************************************************/
3551 /* machine registration */
3553 static QEMUMachine *first_machine = NULL;
3554 QEMUMachine *current_machine = NULL;
3556 int qemu_register_machine(QEMUMachine *m)
3558 QEMUMachine **pm;
3559 pm = &first_machine;
3560 while (*pm != NULL)
3561 pm = &(*pm)->next;
3562 m->next = NULL;
3563 *pm = m;
3564 return 0;
3567 static QEMUMachine *find_machine(const char *name)
3569 QEMUMachine *m;
3571 for(m = first_machine; m != NULL; m = m->next) {
3572 if (!strcmp(m->name, name))
3573 return m;
3575 return NULL;
3578 static QEMUMachine *find_default_machine(void)
3580 QEMUMachine *m;
3582 for(m = first_machine; m != NULL; m = m->next) {
3583 if (m->is_default) {
3584 return m;
3587 return NULL;
3590 /***********************************************************/
3591 /* main execution loop */
3593 static void gui_update(void *opaque)
3595 uint64_t interval = GUI_REFRESH_INTERVAL;
3596 DisplayState *ds = opaque;
3597 DisplayChangeListener *dcl = ds->listeners;
3599 dpy_refresh(ds);
3601 while (dcl != NULL) {
3602 if (dcl->gui_timer_interval &&
3603 dcl->gui_timer_interval < interval)
3604 interval = dcl->gui_timer_interval;
3605 dcl = dcl->next;
3607 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3610 static void nographic_update(void *opaque)
3612 uint64_t interval = GUI_REFRESH_INTERVAL;
3614 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3617 struct vm_change_state_entry {
3618 VMChangeStateHandler *cb;
3619 void *opaque;
3620 LIST_ENTRY (vm_change_state_entry) entries;
3623 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3625 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3626 void *opaque)
3628 VMChangeStateEntry *e;
3630 e = qemu_mallocz(sizeof (*e));
3632 e->cb = cb;
3633 e->opaque = opaque;
3634 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3635 return e;
3638 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3640 LIST_REMOVE (e, entries);
3641 qemu_free (e);
3644 static void vm_state_notify(int running, int reason)
3646 VMChangeStateEntry *e;
3648 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3649 e->cb(e->opaque, running, reason);
3653 static void resume_all_vcpus(void);
3654 static void pause_all_vcpus(void);
3656 void vm_start(void)
3658 if (!vm_running) {
3659 cpu_enable_ticks();
3660 vm_running = 1;
3661 vm_state_notify(1, 0);
3662 qemu_rearm_alarm_timer(alarm_timer);
3663 resume_all_vcpus();
3667 /* reset/shutdown handler */
3669 typedef struct QEMUResetEntry {
3670 QEMUResetHandler *func;
3671 void *opaque;
3672 struct QEMUResetEntry *next;
3673 } QEMUResetEntry;
3675 static QEMUResetEntry *first_reset_entry;
3676 static int reset_requested;
3677 static int shutdown_requested;
3678 static int powerdown_requested;
3679 static int debug_requested;
3680 static int vmstop_requested;
3682 int qemu_no_shutdown(void)
3684 int r = no_shutdown;
3685 no_shutdown = 0;
3686 return r;
3689 int qemu_shutdown_requested(void)
3691 int r = shutdown_requested;
3692 shutdown_requested = 0;
3693 return r;
3696 int qemu_reset_requested(void)
3698 int r = reset_requested;
3699 reset_requested = 0;
3700 return r;
3703 int qemu_powerdown_requested(void)
3705 int r = powerdown_requested;
3706 powerdown_requested = 0;
3707 return r;
3710 static int qemu_debug_requested(void)
3712 int r = debug_requested;
3713 debug_requested = 0;
3714 return r;
3717 static int qemu_vmstop_requested(void)
3719 int r = vmstop_requested;
3720 vmstop_requested = 0;
3721 return r;
3724 static void do_vm_stop(int reason)
3726 if (vm_running) {
3727 cpu_disable_ticks();
3728 vm_running = 0;
3729 pause_all_vcpus();
3730 vm_state_notify(0, reason);
3734 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3736 QEMUResetEntry **pre, *re;
3738 pre = &first_reset_entry;
3739 while (*pre != NULL)
3740 pre = &(*pre)->next;
3741 re = qemu_mallocz(sizeof(QEMUResetEntry));
3742 re->func = func;
3743 re->opaque = opaque;
3744 re->next = NULL;
3745 *pre = re;
3748 void qemu_system_reset(void)
3750 QEMUResetEntry *re;
3752 /* reset all devices */
3753 for(re = first_reset_entry; re != NULL; re = re->next) {
3754 re->func(re->opaque);
3758 void qemu_system_reset_request(void)
3760 if (no_reboot) {
3761 shutdown_requested = 1;
3762 } else {
3763 reset_requested = 1;
3765 if (cpu_single_env) {
3766 qemu_kvm_cpu_stop(cpu_single_env);
3768 qemu_notify_event();
3771 void qemu_system_shutdown_request(void)
3773 shutdown_requested = 1;
3774 qemu_notify_event();
3777 void qemu_system_powerdown_request(void)
3779 powerdown_requested = 1;
3780 qemu_notify_event();
3783 #ifdef CONFIG_IOTHREAD
3784 static void qemu_system_vmstop_request(int reason)
3786 vmstop_requested = reason;
3787 qemu_notify_event();
3789 #endif
3791 #ifndef _WIN32
3792 static int io_thread_fd = -1;
3794 static void qemu_event_increment(void)
3796 static const char byte = 0;
3798 if (io_thread_fd == -1)
3799 return;
3801 write(io_thread_fd, &byte, sizeof(byte));
3804 static void qemu_event_read(void *opaque)
3806 int fd = (unsigned long)opaque;
3807 ssize_t len;
3809 /* Drain the notify pipe */
3810 do {
3811 char buffer[512];
3812 len = read(fd, buffer, sizeof(buffer));
3813 } while ((len == -1 && errno == EINTR) || len > 0);
3816 static int qemu_event_init(void)
3818 int err;
3819 int fds[2];
3821 err = pipe(fds);
3822 if (err == -1)
3823 return -errno;
3825 err = fcntl_setfl(fds[0], O_NONBLOCK);
3826 if (err < 0)
3827 goto fail;
3829 err = fcntl_setfl(fds[1], O_NONBLOCK);
3830 if (err < 0)
3831 goto fail;
3833 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3834 (void *)(unsigned long)fds[0]);
3836 io_thread_fd = fds[1];
3837 return 0;
3839 fail:
3840 close(fds[0]);
3841 close(fds[1]);
3842 return err;
3844 #else
3845 HANDLE qemu_event_handle;
3847 static void dummy_event_handler(void *opaque)
3851 static int qemu_event_init(void)
3853 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3854 if (!qemu_event_handle) {
3855 perror("Failed CreateEvent");
3856 return -1;
3858 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3859 return 0;
3862 static void qemu_event_increment(void)
3864 SetEvent(qemu_event_handle);
3866 #endif
3868 static int cpu_can_run(CPUState *env)
3870 if (env->stop)
3871 return 0;
3872 if (env->stopped)
3873 return 0;
3874 return 1;
3877 #ifndef CONFIG_IOTHREAD
3878 static int qemu_init_main_loop(void)
3880 return qemu_event_init();
3883 void qemu_init_vcpu(void *_env)
3885 CPUState *env = _env;
3887 if (kvm_enabled())
3888 kvm_init_vcpu(env);
3889 return;
3892 int qemu_cpu_self(void *env)
3894 return 1;
3897 static void resume_all_vcpus(void)
3901 static void pause_all_vcpus(void)
3905 void qemu_cpu_kick(void *env)
3907 return;
3910 void qemu_notify_event(void)
3912 CPUState *env = cpu_single_env;
3914 if (kvm_enabled()) {
3915 qemu_kvm_notify_work();
3916 return;
3918 if (env) {
3919 cpu_exit(env);
3920 #ifdef USE_KQEMU
3921 if (env->kqemu_enabled)
3922 kqemu_cpu_interrupt(env);
3923 #endif
3927 #define qemu_mutex_lock_iothread() do { } while (0)
3928 #define qemu_mutex_unlock_iothread() do { } while (0)
3930 void vm_stop(int reason)
3932 do_vm_stop(reason);
3935 #else /* CONFIG_IOTHREAD */
3937 #include "qemu-thread.h"
3939 QemuMutex qemu_global_mutex;
3940 static QemuMutex qemu_fair_mutex;
3942 static QemuThread io_thread;
3944 static QemuThread *tcg_cpu_thread;
3945 static QemuCond *tcg_halt_cond;
3947 static int qemu_system_ready;
3948 /* cpu creation */
3949 static QemuCond qemu_cpu_cond;
3950 /* system init */
3951 static QemuCond qemu_system_cond;
3952 static QemuCond qemu_pause_cond;
3954 static void block_io_signals(void);
3955 static void unblock_io_signals(void);
3956 static int tcg_has_work(void);
3958 static int qemu_init_main_loop(void)
3960 int ret;
3962 ret = qemu_event_init();
3963 if (ret)
3964 return ret;
3966 qemu_cond_init(&qemu_pause_cond);
3967 qemu_mutex_init(&qemu_fair_mutex);
3968 qemu_mutex_init(&qemu_global_mutex);
3969 qemu_mutex_lock(&qemu_global_mutex);
3971 unblock_io_signals();
3972 qemu_thread_self(&io_thread);
3974 return 0;
3977 static void qemu_wait_io_event(CPUState *env)
3979 while (!tcg_has_work())
3980 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3982 qemu_mutex_unlock(&qemu_global_mutex);
3985 * Users of qemu_global_mutex can be starved, having no chance
3986 * to acquire it since this path will get to it first.
3987 * So use another lock to provide fairness.
3989 qemu_mutex_lock(&qemu_fair_mutex);
3990 qemu_mutex_unlock(&qemu_fair_mutex);
3992 qemu_mutex_lock(&qemu_global_mutex);
3993 if (env->stop) {
3994 env->stop = 0;
3995 env->stopped = 1;
3996 qemu_cond_signal(&qemu_pause_cond);
4000 static int qemu_cpu_exec(CPUState *env);
4002 static void *kvm_cpu_thread_fn(void *arg)
4004 CPUState *env = arg;
4006 block_io_signals();
4007 qemu_thread_self(env->thread);
4009 /* signal CPU creation */
4010 qemu_mutex_lock(&qemu_global_mutex);
4011 env->created = 1;
4012 qemu_cond_signal(&qemu_cpu_cond);
4014 /* and wait for machine initialization */
4015 while (!qemu_system_ready)
4016 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
4018 while (1) {
4019 if (cpu_can_run(env))
4020 qemu_cpu_exec(env);
4021 qemu_wait_io_event(env);
4024 return NULL;
4027 static void tcg_cpu_exec(void);
4029 static void *tcg_cpu_thread_fn(void *arg)
4031 CPUState *env = arg;
4033 block_io_signals();
4034 qemu_thread_self(env->thread);
4036 /* signal CPU creation */
4037 qemu_mutex_lock(&qemu_global_mutex);
4038 for (env = first_cpu; env != NULL; env = env->next_cpu)
4039 env->created = 1;
4040 qemu_cond_signal(&qemu_cpu_cond);
4042 /* and wait for machine initialization */
4043 while (!qemu_system_ready)
4044 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
4046 while (1) {
4047 tcg_cpu_exec();
4048 qemu_wait_io_event(cur_cpu);
4051 return NULL;
4054 void qemu_cpu_kick(void *_env)
4056 CPUState *env = _env;
4057 qemu_cond_broadcast(env->halt_cond);
4058 if (kvm_enabled())
4059 qemu_thread_signal(env->thread, SIGUSR1);
4062 int qemu_cpu_self(void *env)
4064 return (cpu_single_env != NULL);
4067 static void cpu_signal(int sig)
4069 if (cpu_single_env)
4070 cpu_exit(cpu_single_env);
4073 static void block_io_signals(void)
4075 sigset_t set;
4076 struct sigaction sigact;
4078 sigemptyset(&set);
4079 sigaddset(&set, SIGUSR2);
4080 sigaddset(&set, SIGIO);
4081 sigaddset(&set, SIGALRM);
4082 pthread_sigmask(SIG_BLOCK, &set, NULL);
4084 sigemptyset(&set);
4085 sigaddset(&set, SIGUSR1);
4086 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4088 memset(&sigact, 0, sizeof(sigact));
4089 sigact.sa_handler = cpu_signal;
4090 sigaction(SIGUSR1, &sigact, NULL);
4093 static void unblock_io_signals(void)
4095 sigset_t set;
4097 sigemptyset(&set);
4098 sigaddset(&set, SIGUSR2);
4099 sigaddset(&set, SIGIO);
4100 sigaddset(&set, SIGALRM);
4101 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4103 sigemptyset(&set);
4104 sigaddset(&set, SIGUSR1);
4105 pthread_sigmask(SIG_BLOCK, &set, NULL);
4108 static void qemu_signal_lock(unsigned int msecs)
4110 qemu_mutex_lock(&qemu_fair_mutex);
4112 while (qemu_mutex_trylock(&qemu_global_mutex)) {
4113 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
4114 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
4115 break;
4117 qemu_mutex_unlock(&qemu_fair_mutex);
4120 static void qemu_mutex_lock_iothread(void)
4122 if (kvm_enabled()) {
4123 qemu_mutex_lock(&qemu_fair_mutex);
4124 qemu_mutex_lock(&qemu_global_mutex);
4125 qemu_mutex_unlock(&qemu_fair_mutex);
4126 } else
4127 qemu_signal_lock(100);
4130 static void qemu_mutex_unlock_iothread(void)
4132 qemu_mutex_unlock(&qemu_global_mutex);
4135 static int all_vcpus_paused(void)
4137 CPUState *penv = first_cpu;
4139 while (penv) {
4140 if (!penv->stopped)
4141 return 0;
4142 penv = (CPUState *)penv->next_cpu;
4145 return 1;
4148 static void pause_all_vcpus(void)
4150 CPUState *penv = first_cpu;
4152 while (penv) {
4153 penv->stop = 1;
4154 qemu_thread_signal(penv->thread, SIGUSR1);
4155 qemu_cpu_kick(penv);
4156 penv = (CPUState *)penv->next_cpu;
4159 while (!all_vcpus_paused()) {
4160 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
4161 penv = first_cpu;
4162 while (penv) {
4163 qemu_thread_signal(penv->thread, SIGUSR1);
4164 penv = (CPUState *)penv->next_cpu;
4169 static void resume_all_vcpus(void)
4171 CPUState *penv = first_cpu;
4173 while (penv) {
4174 penv->stop = 0;
4175 penv->stopped = 0;
4176 qemu_thread_signal(penv->thread, SIGUSR1);
4177 qemu_cpu_kick(penv);
4178 penv = (CPUState *)penv->next_cpu;
4182 static void tcg_init_vcpu(void *_env)
4184 CPUState *env = _env;
4185 /* share a single thread for all cpus with TCG */
4186 if (!tcg_cpu_thread) {
4187 env->thread = qemu_mallocz(sizeof(QemuThread));
4188 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4189 qemu_cond_init(env->halt_cond);
4190 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
4191 while (env->created == 0)
4192 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4193 tcg_cpu_thread = env->thread;
4194 tcg_halt_cond = env->halt_cond;
4195 } else {
4196 env->thread = tcg_cpu_thread;
4197 env->halt_cond = tcg_halt_cond;
4201 static void kvm_start_vcpu(CPUState *env)
4203 kvm_init_vcpu(env);
4204 env->thread = qemu_mallocz(sizeof(QemuThread));
4205 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4206 qemu_cond_init(env->halt_cond);
4207 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
4208 while (env->created == 0)
4209 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4212 void qemu_init_vcpu(void *_env)
4214 CPUState *env = _env;
4216 if (kvm_enabled())
4217 kvm_start_vcpu(env);
4218 else
4219 tcg_init_vcpu(env);
4222 void qemu_notify_event(void)
4224 qemu_event_increment();
4227 void vm_stop(int reason)
4229 QemuThread me;
4230 qemu_thread_self(&me);
4232 if (!qemu_thread_equal(&me, &io_thread)) {
4233 qemu_system_vmstop_request(reason);
4235 * FIXME: should not return to device code in case
4236 * vm_stop() has been requested.
4238 if (cpu_single_env) {
4239 cpu_exit(cpu_single_env);
4240 cpu_single_env->stop = 1;
4242 return;
4244 do_vm_stop(reason);
4247 #endif
4250 #ifdef _WIN32
4251 static void host_main_loop_wait(int *timeout)
4253 int ret, ret2, i;
4254 PollingEntry *pe;
4257 /* XXX: need to suppress polling by better using win32 events */
4258 ret = 0;
4259 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4260 ret |= pe->func(pe->opaque);
4262 if (ret == 0) {
4263 int err;
4264 WaitObjects *w = &wait_objects;
4266 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4267 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4268 if (w->func[ret - WAIT_OBJECT_0])
4269 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4271 /* Check for additional signaled events */
4272 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4274 /* Check if event is signaled */
4275 ret2 = WaitForSingleObject(w->events[i], 0);
4276 if(ret2 == WAIT_OBJECT_0) {
4277 if (w->func[i])
4278 w->func[i](w->opaque[i]);
4279 } else if (ret2 == WAIT_TIMEOUT) {
4280 } else {
4281 err = GetLastError();
4282 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4285 } else if (ret == WAIT_TIMEOUT) {
4286 } else {
4287 err = GetLastError();
4288 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4292 *timeout = 0;
4294 #else
4295 static void host_main_loop_wait(int *timeout)
4298 #endif
4300 void main_loop_wait(int timeout)
4302 IOHandlerRecord *ioh;
4303 fd_set rfds, wfds, xfds;
4304 int ret, nfds;
4305 struct timeval tv;
4307 qemu_bh_update_timeout(&timeout);
4309 host_main_loop_wait(&timeout);
4311 /* poll any events */
4312 /* XXX: separate device handlers from system ones */
4313 nfds = -1;
4314 FD_ZERO(&rfds);
4315 FD_ZERO(&wfds);
4316 FD_ZERO(&xfds);
4317 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4318 if (ioh->deleted)
4319 continue;
4320 if (ioh->fd_read &&
4321 (!ioh->fd_read_poll ||
4322 ioh->fd_read_poll(ioh->opaque) != 0)) {
4323 FD_SET(ioh->fd, &rfds);
4324 if (ioh->fd > nfds)
4325 nfds = ioh->fd;
4327 if (ioh->fd_write) {
4328 FD_SET(ioh->fd, &wfds);
4329 if (ioh->fd > nfds)
4330 nfds = ioh->fd;
4334 tv.tv_sec = timeout / 1000;
4335 tv.tv_usec = (timeout % 1000) * 1000;
4337 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4339 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4340 if (ret > 0) {
4341 IOHandlerRecord **pioh;
4343 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4344 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4345 ioh->fd_read(ioh->opaque);
4346 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
4347 FD_CLR(ioh->fd, &rfds);
4349 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4350 ioh->fd_write(ioh->opaque);
4354 /* remove deleted IO handlers */
4355 pioh = &first_io_handler;
4356 while (*pioh) {
4357 ioh = *pioh;
4358 if (ioh->deleted) {
4359 *pioh = ioh->next;
4360 qemu_free(ioh);
4361 } else
4362 pioh = &ioh->next;
4366 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4368 /* rearm timer, if not periodic */
4369 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4370 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4371 qemu_rearm_alarm_timer(alarm_timer);
4374 /* vm time timers */
4375 if (vm_running) {
4376 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4377 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4378 qemu_get_clock(vm_clock));
4381 /* real time timers */
4382 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4383 qemu_get_clock(rt_clock));
4385 /* Check bottom-halves last in case any of the earlier events triggered
4386 them. */
4387 qemu_bh_poll();
4391 static int qemu_cpu_exec(CPUState *env)
4393 int ret;
4394 #ifdef CONFIG_PROFILER
4395 int64_t ti;
4396 #endif
4398 #ifdef CONFIG_PROFILER
4399 ti = profile_getclock();
4400 #endif
4401 if (use_icount) {
4402 int64_t count;
4403 int decr;
4404 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4405 env->icount_decr.u16.low = 0;
4406 env->icount_extra = 0;
4407 count = qemu_next_deadline();
4408 count = (count + (1 << icount_time_shift) - 1)
4409 >> icount_time_shift;
4410 qemu_icount += count;
4411 decr = (count > 0xffff) ? 0xffff : count;
4412 count -= decr;
4413 env->icount_decr.u16.low = decr;
4414 env->icount_extra = count;
4416 ret = cpu_exec(env);
4417 #ifdef CONFIG_PROFILER
4418 qemu_time += profile_getclock() - ti;
4419 #endif
4420 if (use_icount) {
4421 /* Fold pending instructions back into the
4422 instruction counter, and clear the interrupt flag. */
4423 qemu_icount -= (env->icount_decr.u16.low
4424 + env->icount_extra);
4425 env->icount_decr.u32 = 0;
4426 env->icount_extra = 0;
4428 return ret;
4431 static void tcg_cpu_exec(void)
4433 int ret = 0;
4435 if (next_cpu == NULL)
4436 next_cpu = first_cpu;
4437 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4438 CPUState *env = cur_cpu = next_cpu;
4440 if (!vm_running)
4441 break;
4442 if (timer_alarm_pending) {
4443 timer_alarm_pending = 0;
4444 break;
4446 if (cpu_can_run(env))
4447 ret = qemu_cpu_exec(env);
4448 if (ret == EXCP_DEBUG) {
4449 gdb_set_stop_cpu(env);
4450 debug_requested = 1;
4451 break;
4456 static int cpu_has_work(CPUState *env)
4458 if (env->stop)
4459 return 1;
4460 if (env->stopped)
4461 return 0;
4462 if (!env->halted)
4463 return 1;
4464 if (qemu_cpu_has_work(env))
4465 return 1;
4466 return 0;
4469 static int tcg_has_work(void)
4471 CPUState *env;
4473 for (env = first_cpu; env != NULL; env = env->next_cpu)
4474 if (cpu_has_work(env))
4475 return 1;
4476 return 0;
4479 static int qemu_calculate_timeout(void)
4481 #ifndef CONFIG_IOTHREAD
4482 int timeout;
4484 if (!vm_running)
4485 timeout = 5000;
4486 else if (tcg_has_work())
4487 timeout = 0;
4488 else if (!use_icount)
4489 timeout = 5000;
4490 else {
4491 /* XXX: use timeout computed from timers */
4492 int64_t add;
4493 int64_t delta;
4494 /* Advance virtual time to the next event. */
4495 if (use_icount == 1) {
4496 /* When not using an adaptive execution frequency
4497 we tend to get badly out of sync with real time,
4498 so just delay for a reasonable amount of time. */
4499 delta = 0;
4500 } else {
4501 delta = cpu_get_icount() - cpu_get_clock();
4503 if (delta > 0) {
4504 /* If virtual time is ahead of real time then just
4505 wait for IO. */
4506 timeout = (delta / 1000000) + 1;
4507 } else {
4508 /* Wait for either IO to occur or the next
4509 timer event. */
4510 add = qemu_next_deadline();
4511 /* We advance the timer before checking for IO.
4512 Limit the amount we advance so that early IO
4513 activity won't get the guest too far ahead. */
4514 if (add > 10000000)
4515 add = 10000000;
4516 delta += add;
4517 add = (add + (1 << icount_time_shift) - 1)
4518 >> icount_time_shift;
4519 qemu_icount += add;
4520 timeout = delta / 1000000;
4521 if (timeout < 0)
4522 timeout = 0;
4526 return timeout;
4527 #else /* CONFIG_IOTHREAD */
4528 return 1000;
4529 #endif
4532 static int vm_can_run(void)
4534 if (powerdown_requested)
4535 return 0;
4536 if (reset_requested)
4537 return 0;
4538 if (shutdown_requested)
4539 return 0;
4540 if (debug_requested)
4541 return 0;
4542 return 1;
4545 static void main_loop(void)
4547 int r;
4549 if (kvm_enabled()) {
4550 kvm_main_loop();
4551 cpu_disable_ticks();
4552 return;
4555 #ifdef CONFIG_IOTHREAD
4556 qemu_system_ready = 1;
4557 qemu_cond_broadcast(&qemu_system_cond);
4558 #endif
4560 for (;;) {
4561 do {
4562 #ifdef CONFIG_PROFILER
4563 int64_t ti;
4564 #endif
4565 #ifndef CONFIG_IOTHREAD
4566 tcg_cpu_exec();
4567 #endif
4568 #ifdef CONFIG_PROFILER
4569 ti = profile_getclock();
4570 #endif
4571 main_loop_wait(qemu_calculate_timeout());
4572 #ifdef CONFIG_PROFILER
4573 dev_time += profile_getclock() - ti;
4574 #endif
4575 } while (vm_can_run());
4577 if (qemu_debug_requested())
4578 vm_stop(EXCP_DEBUG);
4579 if (qemu_shutdown_requested()) {
4580 if (no_shutdown) {
4581 vm_stop(0);
4582 no_shutdown = 0;
4583 } else
4584 break;
4586 if (qemu_reset_requested()) {
4587 pause_all_vcpus();
4588 qemu_system_reset();
4589 resume_all_vcpus();
4591 if (qemu_powerdown_requested())
4592 qemu_system_powerdown();
4593 if ((r = qemu_vmstop_requested()))
4594 vm_stop(r);
4596 pause_all_vcpus();
4599 static void version(void)
4601 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4604 static void help(int exitcode)
4606 version();
4607 printf("usage: %s [options] [disk_image]\n"
4608 "\n"
4609 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4610 "\n"
4611 #define DEF(option, opt_arg, opt_enum, opt_help) \
4612 opt_help
4613 #define DEFHEADING(text) stringify(text) "\n"
4614 #include "qemu-options.h"
4615 #undef DEF
4616 #undef DEFHEADING
4617 #undef GEN_DOCS
4618 "\n"
4619 "During emulation, the following keys are useful:\n"
4620 "ctrl-alt-f toggle full screen\n"
4621 "ctrl-alt-n switch to virtual console 'n'\n"
4622 "ctrl-alt toggle mouse and keyboard grab\n"
4623 "\n"
4624 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4626 "qemu",
4627 DEFAULT_RAM_SIZE,
4628 #ifndef _WIN32
4629 DEFAULT_NETWORK_SCRIPT,
4630 DEFAULT_NETWORK_DOWN_SCRIPT,
4631 #endif
4632 DEFAULT_GDBSTUB_PORT,
4633 "/tmp/qemu.log");
4634 exit(exitcode);
4637 #define HAS_ARG 0x0001
4639 enum {
4640 #define DEF(option, opt_arg, opt_enum, opt_help) \
4641 opt_enum,
4642 #define DEFHEADING(text)
4643 #include "qemu-options.h"
4644 #undef DEF
4645 #undef DEFHEADING
4646 #undef GEN_DOCS
4649 typedef struct QEMUOption {
4650 const char *name;
4651 int flags;
4652 int index;
4653 } QEMUOption;
4655 static const QEMUOption qemu_options[] = {
4656 { "h", 0, QEMU_OPTION_h },
4657 #define DEF(option, opt_arg, opt_enum, opt_help) \
4658 { option, opt_arg, opt_enum },
4659 #define DEFHEADING(text)
4660 #include "qemu-options.h"
4661 #undef DEF
4662 #undef DEFHEADING
4663 #undef GEN_DOCS
4664 { NULL },
4667 #ifdef HAS_AUDIO
4668 struct soundhw soundhw[] = {
4669 #ifdef HAS_AUDIO_CHOICE
4670 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4672 "pcspk",
4673 "PC speaker",
4676 { .init_isa = pcspk_audio_init }
4678 #endif
4680 #ifdef CONFIG_SB16
4682 "sb16",
4683 "Creative Sound Blaster 16",
4686 { .init_isa = SB16_init }
4688 #endif
4690 #ifdef CONFIG_CS4231A
4692 "cs4231a",
4693 "CS4231A",
4696 { .init_isa = cs4231a_init }
4698 #endif
4700 #ifdef CONFIG_ADLIB
4702 "adlib",
4703 #ifdef HAS_YMF262
4704 "Yamaha YMF262 (OPL3)",
4705 #else
4706 "Yamaha YM3812 (OPL2)",
4707 #endif
4710 { .init_isa = Adlib_init }
4712 #endif
4714 #ifdef CONFIG_GUS
4716 "gus",
4717 "Gravis Ultrasound GF1",
4720 { .init_isa = GUS_init }
4722 #endif
4724 #ifdef CONFIG_AC97
4726 "ac97",
4727 "Intel 82801AA AC97 Audio",
4730 { .init_pci = ac97_init }
4732 #endif
4734 #ifdef CONFIG_ES1370
4736 "es1370",
4737 "ENSONIQ AudioPCI ES1370",
4740 { .init_pci = es1370_init }
4742 #endif
4744 #endif /* HAS_AUDIO_CHOICE */
4746 { NULL, NULL, 0, 0, { NULL } }
4749 static void select_soundhw (const char *optarg)
4751 struct soundhw *c;
4753 if (*optarg == '?') {
4754 show_valid_cards:
4756 printf ("Valid sound card names (comma separated):\n");
4757 for (c = soundhw; c->name; ++c) {
4758 printf ("%-11s %s\n", c->name, c->descr);
4760 printf ("\n-soundhw all will enable all of the above\n");
4761 exit (*optarg != '?');
4763 else {
4764 size_t l;
4765 const char *p;
4766 char *e;
4767 int bad_card = 0;
4769 if (!strcmp (optarg, "all")) {
4770 for (c = soundhw; c->name; ++c) {
4771 c->enabled = 1;
4773 return;
4776 p = optarg;
4777 while (*p) {
4778 e = strchr (p, ',');
4779 l = !e ? strlen (p) : (size_t) (e - p);
4781 for (c = soundhw; c->name; ++c) {
4782 if (!strncmp (c->name, p, l)) {
4783 c->enabled = 1;
4784 break;
4788 if (!c->name) {
4789 if (l > 80) {
4790 fprintf (stderr,
4791 "Unknown sound card name (too big to show)\n");
4793 else {
4794 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4795 (int) l, p);
4797 bad_card = 1;
4799 p += l + (e != NULL);
4802 if (bad_card)
4803 goto show_valid_cards;
4806 #endif
4808 static void select_vgahw (const char *p)
4810 const char *opts;
4812 cirrus_vga_enabled = 0;
4813 std_vga_enabled = 0;
4814 vmsvga_enabled = 0;
4815 xenfb_enabled = 0;
4816 if (strstart(p, "std", &opts)) {
4817 std_vga_enabled = 1;
4818 } else if (strstart(p, "cirrus", &opts)) {
4819 cirrus_vga_enabled = 1;
4820 } else if (strstart(p, "vmware", &opts)) {
4821 vmsvga_enabled = 1;
4822 } else if (strstart(p, "xenfb", &opts)) {
4823 xenfb_enabled = 1;
4824 } else if (!strstart(p, "none", &opts)) {
4825 invalid_vga:
4826 fprintf(stderr, "Unknown vga type: %s\n", p);
4827 exit(1);
4829 while (*opts) {
4830 const char *nextopt;
4832 if (strstart(opts, ",retrace=", &nextopt)) {
4833 opts = nextopt;
4834 if (strstart(opts, "dumb", &nextopt))
4835 vga_retrace_method = VGA_RETRACE_DUMB;
4836 else if (strstart(opts, "precise", &nextopt))
4837 vga_retrace_method = VGA_RETRACE_PRECISE;
4838 else goto invalid_vga;
4839 } else goto invalid_vga;
4840 opts = nextopt;
4844 #ifdef TARGET_I386
4845 static int balloon_parse(const char *arg)
4847 char buf[128];
4848 const char *p;
4850 if (!strcmp(arg, "none")) {
4851 virtio_balloon = 0;
4852 } else if (!strncmp(arg, "virtio", 6)) {
4853 virtio_balloon = 1;
4854 if (arg[6] == ',') {
4855 p = arg + 7;
4856 if (get_param_value(buf, sizeof(buf), "addr", p)) {
4857 virtio_balloon_devaddr = strdup(buf);
4860 } else {
4861 return -1;
4863 return 0;
4865 #endif
4867 #ifdef _WIN32
4868 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4870 exit(STATUS_CONTROL_C_EXIT);
4871 return TRUE;
4873 #endif
4875 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4877 int ret;
4879 if(strlen(str) != 36)
4880 return -1;
4882 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4883 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4884 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4886 if(ret != 16)
4887 return -1;
4889 #ifdef TARGET_I386
4890 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4891 #endif
4893 return 0;
4896 #define MAX_NET_CLIENTS 32
4898 #ifndef _WIN32
4900 static void termsig_handler(int signal)
4902 qemu_system_shutdown_request();
4905 static void sigchld_handler(int signal)
4907 waitpid(-1, NULL, WNOHANG);
4910 static void sighandler_setup(void)
4912 struct sigaction act;
4914 memset(&act, 0, sizeof(act));
4915 act.sa_handler = termsig_handler;
4916 sigaction(SIGINT, &act, NULL);
4917 sigaction(SIGHUP, &act, NULL);
4918 sigaction(SIGTERM, &act, NULL);
4920 act.sa_handler = sigchld_handler;
4921 act.sa_flags = SA_NOCLDSTOP;
4922 sigaction(SIGCHLD, &act, NULL);
4925 #endif
4927 #ifdef _WIN32
4928 /* Look for support files in the same directory as the executable. */
4929 static char *find_datadir(const char *argv0)
4931 char *p;
4932 char buf[MAX_PATH];
4933 DWORD len;
4935 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4936 if (len == 0) {
4937 return NULL;
4940 buf[len] = 0;
4941 p = buf + len - 1;
4942 while (p != buf && *p != '\\')
4943 p--;
4944 *p = 0;
4945 if (access(buf, R_OK) == 0) {
4946 return qemu_strdup(buf);
4948 return NULL;
4950 #else /* !_WIN32 */
4952 /* Find a likely location for support files using the location of the binary.
4953 For installed binaries this will be "$bindir/../share/qemu". When
4954 running from the build tree this will be "$bindir/../pc-bios". */
4955 #define SHARE_SUFFIX "/share/qemu"
4956 #define BUILD_SUFFIX "/pc-bios"
4957 static char *find_datadir(const char *argv0)
4959 char *dir;
4960 char *p = NULL;
4961 char *res;
4962 #ifdef PATH_MAX
4963 char buf[PATH_MAX];
4964 #endif
4965 size_t max_len;
4967 #if defined(__linux__)
4969 int len;
4970 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4971 if (len > 0) {
4972 buf[len] = 0;
4973 p = buf;
4976 #elif defined(__FreeBSD__)
4978 int len;
4979 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4980 if (len > 0) {
4981 buf[len] = 0;
4982 p = buf;
4985 #endif
4986 /* If we don't have any way of figuring out the actual executable
4987 location then try argv[0]. */
4988 if (!p) {
4989 #ifdef PATH_MAX
4990 p = buf;
4991 #endif
4992 p = realpath(argv0, p);
4993 if (!p) {
4994 return NULL;
4997 dir = dirname(p);
4998 dir = dirname(dir);
5000 max_len = strlen(dir) +
5001 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
5002 res = qemu_mallocz(max_len);
5003 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
5004 if (access(res, R_OK)) {
5005 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
5006 if (access(res, R_OK)) {
5007 qemu_free(res);
5008 res = NULL;
5011 #ifndef PATH_MAX
5012 free(p);
5013 #endif
5014 return res;
5016 #undef SHARE_SUFFIX
5017 #undef BUILD_SUFFIX
5018 #endif
5020 char *qemu_find_file(int type, const char *name)
5022 int len;
5023 const char *subdir;
5024 char *buf;
5026 /* If name contains path separators then try it as a straight path. */
5027 if ((strchr(name, '/') || strchr(name, '\\'))
5028 && access(name, R_OK) == 0) {
5029 return strdup(name);
5031 switch (type) {
5032 case QEMU_FILE_TYPE_BIOS:
5033 subdir = "";
5034 break;
5035 case QEMU_FILE_TYPE_KEYMAP:
5036 subdir = "keymaps/";
5037 break;
5038 default:
5039 abort();
5041 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
5042 buf = qemu_mallocz(len);
5043 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
5044 if (access(buf, R_OK)) {
5045 qemu_free(buf);
5046 return NULL;
5048 return buf;
5051 int main(int argc, char **argv, char **envp)
5053 const char *gdbstub_dev = NULL;
5054 uint32_t boot_devices_bitmap = 0;
5055 int i;
5056 int snapshot, linux_boot, net_boot;
5057 const char *initrd_filename;
5058 const char *kernel_filename, *kernel_cmdline;
5059 const char *boot_devices = "";
5060 DisplayState *ds;
5061 DisplayChangeListener *dcl;
5062 int cyls, heads, secs, translation;
5063 const char *net_clients[MAX_NET_CLIENTS];
5064 int nb_net_clients;
5065 const char *bt_opts[MAX_BT_CMDLINE];
5066 int nb_bt_opts;
5067 int hda_index;
5068 int optind;
5069 const char *r, *optarg;
5070 CharDriverState *monitor_hd = NULL;
5071 const char *monitor_device;
5072 const char *serial_devices[MAX_SERIAL_PORTS];
5073 int serial_device_index;
5074 const char *parallel_devices[MAX_PARALLEL_PORTS];
5075 int parallel_device_index;
5076 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
5077 int virtio_console_index;
5078 const char *loadvm = NULL;
5079 QEMUMachine *machine;
5080 const char *cpu_model;
5081 const char *usb_devices[MAX_USB_CMDLINE];
5082 int usb_devices_index;
5083 #ifndef _WIN32
5084 int fds[2];
5085 #endif
5086 int tb_size;
5087 const char *pid_file = NULL;
5088 const char *incoming = NULL;
5089 #ifndef _WIN32
5090 int fd = 0;
5091 struct passwd *pwd = NULL;
5092 const char *chroot_dir = NULL;
5093 const char *run_as = NULL;
5094 #endif
5095 CPUState *env;
5096 int show_vnc_port = 0;
5098 qemu_cache_utils_init(envp);
5100 LIST_INIT (&vm_change_state_head);
5101 #ifndef _WIN32
5103 struct sigaction act;
5104 sigfillset(&act.sa_mask);
5105 act.sa_flags = 0;
5106 act.sa_handler = SIG_IGN;
5107 sigaction(SIGPIPE, &act, NULL);
5109 #else
5110 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5111 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5112 QEMU to run on a single CPU */
5114 HANDLE h;
5115 DWORD mask, smask;
5116 int i;
5117 h = GetCurrentProcess();
5118 if (GetProcessAffinityMask(h, &mask, &smask)) {
5119 for(i = 0; i < 32; i++) {
5120 if (mask & (1 << i))
5121 break;
5123 if (i != 32) {
5124 mask = 1 << i;
5125 SetProcessAffinityMask(h, mask);
5129 #endif
5131 module_call_init(MODULE_INIT_MACHINE);
5132 machine = find_default_machine();
5133 cpu_model = NULL;
5134 initrd_filename = NULL;
5135 ram_size = 0;
5136 snapshot = 0;
5137 kernel_filename = NULL;
5138 kernel_cmdline = "";
5139 cyls = heads = secs = 0;
5140 translation = BIOS_ATA_TRANSLATION_AUTO;
5141 monitor_device = "vc:80Cx24C";
5143 serial_devices[0] = "vc:80Cx24C";
5144 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5145 serial_devices[i] = NULL;
5146 serial_device_index = 0;
5148 parallel_devices[0] = "vc:80Cx24C";
5149 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5150 parallel_devices[i] = NULL;
5151 parallel_device_index = 0;
5153 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
5154 virtio_consoles[i] = NULL;
5155 virtio_console_index = 0;
5157 for (i = 0; i < MAX_NODES; i++) {
5158 node_mem[i] = 0;
5159 node_cpumask[i] = 0;
5162 usb_devices_index = 0;
5163 assigned_devices_index = 0;
5165 nb_net_clients = 0;
5166 nb_bt_opts = 0;
5167 nb_drives = 0;
5168 nb_drives_opt = 0;
5169 nb_numa_nodes = 0;
5170 hda_index = -1;
5172 nb_nics = 0;
5174 tb_size = 0;
5175 autostart= 1;
5177 register_watchdogs();
5179 optind = 1;
5180 for(;;) {
5181 if (optind >= argc)
5182 break;
5183 r = argv[optind];
5184 if (r[0] != '-') {
5185 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5186 } else {
5187 const QEMUOption *popt;
5189 optind++;
5190 /* Treat --foo the same as -foo. */
5191 if (r[1] == '-')
5192 r++;
5193 popt = qemu_options;
5194 for(;;) {
5195 if (!popt->name) {
5196 fprintf(stderr, "%s: invalid option -- '%s'\n",
5197 argv[0], r);
5198 exit(1);
5200 if (!strcmp(popt->name, r + 1))
5201 break;
5202 popt++;
5204 if (popt->flags & HAS_ARG) {
5205 if (optind >= argc) {
5206 fprintf(stderr, "%s: option '%s' requires an argument\n",
5207 argv[0], r);
5208 exit(1);
5210 optarg = argv[optind++];
5211 } else {
5212 optarg = NULL;
5215 switch(popt->index) {
5216 case QEMU_OPTION_M:
5217 machine = find_machine(optarg);
5218 if (!machine) {
5219 QEMUMachine *m;
5220 printf("Supported machines are:\n");
5221 for(m = first_machine; m != NULL; m = m->next) {
5222 printf("%-10s %s%s\n",
5223 m->name, m->desc,
5224 m->is_default ? " (default)" : "");
5226 exit(*optarg != '?');
5228 break;
5229 case QEMU_OPTION_cpu:
5230 /* hw initialization will check this */
5231 if (*optarg == '?') {
5232 /* XXX: implement xxx_cpu_list for targets that still miss it */
5233 #if defined(cpu_list)
5234 cpu_list(stdout, &fprintf);
5235 #endif
5236 exit(0);
5237 } else {
5238 cpu_model = optarg;
5240 break;
5241 case QEMU_OPTION_initrd:
5242 initrd_filename = optarg;
5243 break;
5244 case QEMU_OPTION_hda:
5245 if (cyls == 0)
5246 hda_index = drive_add(optarg, HD_ALIAS, 0);
5247 else
5248 hda_index = drive_add(optarg, HD_ALIAS
5249 ",cyls=%d,heads=%d,secs=%d%s",
5250 0, cyls, heads, secs,
5251 translation == BIOS_ATA_TRANSLATION_LBA ?
5252 ",trans=lba" :
5253 translation == BIOS_ATA_TRANSLATION_NONE ?
5254 ",trans=none" : "");
5255 break;
5256 case QEMU_OPTION_hdb:
5257 case QEMU_OPTION_hdc:
5258 case QEMU_OPTION_hdd:
5259 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5260 break;
5261 case QEMU_OPTION_drive:
5262 drive_add(NULL, "%s", optarg);
5263 break;
5264 case QEMU_OPTION_mtdblock:
5265 drive_add(optarg, MTD_ALIAS);
5266 break;
5267 case QEMU_OPTION_sd:
5268 drive_add(optarg, SD_ALIAS);
5269 break;
5270 case QEMU_OPTION_pflash:
5271 drive_add(optarg, PFLASH_ALIAS);
5272 break;
5273 case QEMU_OPTION_snapshot:
5274 snapshot = 1;
5275 break;
5276 case QEMU_OPTION_hdachs:
5278 const char *p;
5279 p = optarg;
5280 cyls = strtol(p, (char **)&p, 0);
5281 if (cyls < 1 || cyls > 16383)
5282 goto chs_fail;
5283 if (*p != ',')
5284 goto chs_fail;
5285 p++;
5286 heads = strtol(p, (char **)&p, 0);
5287 if (heads < 1 || heads > 16)
5288 goto chs_fail;
5289 if (*p != ',')
5290 goto chs_fail;
5291 p++;
5292 secs = strtol(p, (char **)&p, 0);
5293 if (secs < 1 || secs > 63)
5294 goto chs_fail;
5295 if (*p == ',') {
5296 p++;
5297 if (!strcmp(p, "none"))
5298 translation = BIOS_ATA_TRANSLATION_NONE;
5299 else if (!strcmp(p, "lba"))
5300 translation = BIOS_ATA_TRANSLATION_LBA;
5301 else if (!strcmp(p, "auto"))
5302 translation = BIOS_ATA_TRANSLATION_AUTO;
5303 else
5304 goto chs_fail;
5305 } else if (*p != '\0') {
5306 chs_fail:
5307 fprintf(stderr, "qemu: invalid physical CHS format\n");
5308 exit(1);
5310 if (hda_index != -1)
5311 snprintf(drives_opt[hda_index].opt,
5312 sizeof(drives_opt[hda_index].opt),
5313 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5314 0, cyls, heads, secs,
5315 translation == BIOS_ATA_TRANSLATION_LBA ?
5316 ",trans=lba" :
5317 translation == BIOS_ATA_TRANSLATION_NONE ?
5318 ",trans=none" : "");
5320 break;
5321 case QEMU_OPTION_numa:
5322 if (nb_numa_nodes >= MAX_NODES) {
5323 fprintf(stderr, "qemu: too many NUMA nodes\n");
5324 exit(1);
5326 numa_add(optarg);
5327 break;
5328 case QEMU_OPTION_nographic:
5329 display_type = DT_NOGRAPHIC;
5330 break;
5331 #ifdef CONFIG_CURSES
5332 case QEMU_OPTION_curses:
5333 display_type = DT_CURSES;
5334 break;
5335 #endif
5336 case QEMU_OPTION_portrait:
5337 graphic_rotate = 1;
5338 break;
5339 case QEMU_OPTION_kernel:
5340 kernel_filename = optarg;
5341 break;
5342 case QEMU_OPTION_append:
5343 kernel_cmdline = optarg;
5344 break;
5345 case QEMU_OPTION_cdrom:
5346 drive_add(optarg, CDROM_ALIAS);
5347 break;
5348 case QEMU_OPTION_boot:
5349 boot_devices = optarg;
5350 /* We just do some generic consistency checks */
5352 /* Could easily be extended to 64 devices if needed */
5353 const char *p;
5355 boot_devices_bitmap = 0;
5356 for (p = boot_devices; *p != '\0'; p++) {
5357 /* Allowed boot devices are:
5358 * a b : floppy disk drives
5359 * c ... f : IDE disk drives
5360 * g ... m : machine implementation dependant drives
5361 * n ... p : network devices
5362 * It's up to each machine implementation to check
5363 * if the given boot devices match the actual hardware
5364 * implementation and firmware features.
5366 if (*p < 'a' || *p > 'q') {
5367 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5368 exit(1);
5370 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5371 fprintf(stderr,
5372 "Boot device '%c' was given twice\n",*p);
5373 exit(1);
5375 boot_devices_bitmap |= 1 << (*p - 'a');
5378 break;
5379 case QEMU_OPTION_fda:
5380 case QEMU_OPTION_fdb:
5381 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5382 break;
5383 #ifdef TARGET_I386
5384 case QEMU_OPTION_no_fd_bootchk:
5385 fd_bootchk = 0;
5386 break;
5387 #endif
5388 case QEMU_OPTION_net:
5389 if (nb_net_clients >= MAX_NET_CLIENTS) {
5390 fprintf(stderr, "qemu: too many network clients\n");
5391 exit(1);
5393 net_clients[nb_net_clients] = optarg;
5394 nb_net_clients++;
5395 break;
5396 #ifdef CONFIG_SLIRP
5397 case QEMU_OPTION_tftp:
5398 legacy_tftp_prefix = optarg;
5399 break;
5400 case QEMU_OPTION_bootp:
5401 legacy_bootp_filename = optarg;
5402 break;
5403 #ifndef _WIN32
5404 case QEMU_OPTION_smb:
5405 net_slirp_smb(optarg);
5406 break;
5407 #endif
5408 case QEMU_OPTION_redir:
5409 net_slirp_redir(optarg);
5410 break;
5411 #endif
5412 case QEMU_OPTION_bt:
5413 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5414 fprintf(stderr, "qemu: too many bluetooth options\n");
5415 exit(1);
5417 bt_opts[nb_bt_opts++] = optarg;
5418 break;
5419 #ifdef HAS_AUDIO
5420 case QEMU_OPTION_audio_help:
5421 AUD_help ();
5422 exit (0);
5423 break;
5424 case QEMU_OPTION_soundhw:
5425 select_soundhw (optarg);
5426 break;
5427 #endif
5428 case QEMU_OPTION_h:
5429 help(0);
5430 break;
5431 case QEMU_OPTION_version:
5432 version();
5433 exit(0);
5434 break;
5435 case QEMU_OPTION_m: {
5436 uint64_t value;
5437 char *ptr;
5439 value = strtoul(optarg, &ptr, 10);
5440 switch (*ptr) {
5441 case 0: case 'M': case 'm':
5442 value <<= 20;
5443 break;
5444 case 'G': case 'g':
5445 value <<= 30;
5446 break;
5447 default:
5448 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5449 exit(1);
5452 /* On 32-bit hosts, QEMU is limited by virtual address space */
5453 if (value > (2047 << 20)
5454 #ifndef CONFIG_KQEMU
5455 && HOST_LONG_BITS == 32
5456 #endif
5458 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5459 exit(1);
5461 if (value != (uint64_t)(ram_addr_t)value) {
5462 fprintf(stderr, "qemu: ram size too large\n");
5463 exit(1);
5465 ram_size = value;
5466 break;
5468 case QEMU_OPTION_d:
5470 int mask;
5471 const CPULogItem *item;
5473 mask = cpu_str_to_log_mask(optarg);
5474 if (!mask) {
5475 printf("Log items (comma separated):\n");
5476 for(item = cpu_log_items; item->mask != 0; item++) {
5477 printf("%-10s %s\n", item->name, item->help);
5479 exit(1);
5481 cpu_set_log(mask);
5483 break;
5484 case QEMU_OPTION_s:
5485 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5486 break;
5487 case QEMU_OPTION_gdb:
5488 gdbstub_dev = optarg;
5489 break;
5490 case QEMU_OPTION_L:
5491 data_dir = optarg;
5492 break;
5493 case QEMU_OPTION_bios:
5494 bios_name = optarg;
5495 break;
5496 case QEMU_OPTION_singlestep:
5497 singlestep = 1;
5498 break;
5499 case QEMU_OPTION_S:
5500 autostart = 0;
5501 break;
5502 #ifndef _WIN32
5503 case QEMU_OPTION_k:
5504 keyboard_layout = optarg;
5505 break;
5506 #endif
5507 case QEMU_OPTION_localtime:
5508 rtc_utc = 0;
5509 break;
5510 case QEMU_OPTION_vga:
5511 select_vgahw (optarg);
5512 break;
5513 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5514 case QEMU_OPTION_g:
5516 const char *p;
5517 int w, h, depth;
5518 p = optarg;
5519 w = strtol(p, (char **)&p, 10);
5520 if (w <= 0) {
5521 graphic_error:
5522 fprintf(stderr, "qemu: invalid resolution or depth\n");
5523 exit(1);
5525 if (*p != 'x')
5526 goto graphic_error;
5527 p++;
5528 h = strtol(p, (char **)&p, 10);
5529 if (h <= 0)
5530 goto graphic_error;
5531 if (*p == 'x') {
5532 p++;
5533 depth = strtol(p, (char **)&p, 10);
5534 if (depth != 8 && depth != 15 && depth != 16 &&
5535 depth != 24 && depth != 32)
5536 goto graphic_error;
5537 } else if (*p == '\0') {
5538 depth = graphic_depth;
5539 } else {
5540 goto graphic_error;
5543 graphic_width = w;
5544 graphic_height = h;
5545 graphic_depth = depth;
5547 break;
5548 #endif
5549 case QEMU_OPTION_echr:
5551 char *r;
5552 term_escape_char = strtol(optarg, &r, 0);
5553 if (r == optarg)
5554 printf("Bad argument to echr\n");
5555 break;
5557 case QEMU_OPTION_monitor:
5558 monitor_device = optarg;
5559 break;
5560 case QEMU_OPTION_serial:
5561 if (serial_device_index >= MAX_SERIAL_PORTS) {
5562 fprintf(stderr, "qemu: too many serial ports\n");
5563 exit(1);
5565 serial_devices[serial_device_index] = optarg;
5566 serial_device_index++;
5567 break;
5568 case QEMU_OPTION_watchdog:
5569 i = select_watchdog(optarg);
5570 if (i > 0)
5571 exit (i == 1 ? 1 : 0);
5572 break;
5573 case QEMU_OPTION_watchdog_action:
5574 if (select_watchdog_action(optarg) == -1) {
5575 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5576 exit(1);
5578 break;
5579 case QEMU_OPTION_virtiocon:
5580 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5581 fprintf(stderr, "qemu: too many virtio consoles\n");
5582 exit(1);
5584 virtio_consoles[virtio_console_index] = optarg;
5585 virtio_console_index++;
5586 break;
5587 case QEMU_OPTION_parallel:
5588 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5589 fprintf(stderr, "qemu: too many parallel ports\n");
5590 exit(1);
5592 parallel_devices[parallel_device_index] = optarg;
5593 parallel_device_index++;
5594 break;
5595 case QEMU_OPTION_loadvm:
5596 loadvm = optarg;
5597 break;
5598 case QEMU_OPTION_full_screen:
5599 full_screen = 1;
5600 break;
5601 #ifdef CONFIG_SDL
5602 case QEMU_OPTION_no_frame:
5603 no_frame = 1;
5604 break;
5605 case QEMU_OPTION_alt_grab:
5606 alt_grab = 1;
5607 break;
5608 case QEMU_OPTION_no_quit:
5609 no_quit = 1;
5610 break;
5611 case QEMU_OPTION_sdl:
5612 display_type = DT_SDL;
5613 break;
5614 #endif
5615 case QEMU_OPTION_pidfile:
5616 pid_file = optarg;
5617 break;
5618 #ifdef TARGET_I386
5619 case QEMU_OPTION_win2k_hack:
5620 win2k_install_hack = 1;
5621 break;
5622 case QEMU_OPTION_rtc_td_hack:
5623 rtc_td_hack = 1;
5624 break;
5625 case QEMU_OPTION_acpitable:
5626 if(acpi_table_add(optarg) < 0) {
5627 fprintf(stderr, "Wrong acpi table provided\n");
5628 exit(1);
5630 break;
5631 case QEMU_OPTION_smbios:
5632 if(smbios_entry_add(optarg) < 0) {
5633 fprintf(stderr, "Wrong smbios provided\n");
5634 exit(1);
5636 break;
5637 #endif
5638 #ifdef CONFIG_KQEMU
5639 case QEMU_OPTION_no_kqemu:
5640 kqemu_allowed = 0;
5641 break;
5642 case QEMU_OPTION_kernel_kqemu:
5643 kqemu_allowed = 2;
5644 break;
5645 #endif
5646 #ifdef CONFIG_KVM
5647 case QEMU_OPTION_enable_kvm:
5648 kvm_allowed = 1;
5649 #ifdef CONFIG_KQEMU
5650 kqemu_allowed = 0;
5651 #endif
5652 break;
5653 #endif
5654 #ifdef USE_KVM
5655 case QEMU_OPTION_no_kvm:
5656 kvm_allowed = 0;
5657 break;
5658 case QEMU_OPTION_no_kvm_irqchip: {
5659 kvm_irqchip = 0;
5660 kvm_pit = 0;
5661 break;
5663 case QEMU_OPTION_no_kvm_pit: {
5664 kvm_pit = 0;
5665 break;
5667 case QEMU_OPTION_no_kvm_pit_reinjection: {
5668 kvm_pit_reinject = 0;
5669 break;
5671 case QEMU_OPTION_enable_nesting: {
5672 kvm_nested = 1;
5673 break;
5675 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5676 case QEMU_OPTION_pcidevice:
5677 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5678 fprintf(stderr, "Too many assigned devices\n");
5679 exit(1);
5681 assigned_devices[assigned_devices_index] = optarg;
5682 assigned_devices_index++;
5683 break;
5684 #endif
5685 #endif
5686 case QEMU_OPTION_usb:
5687 usb_enabled = 1;
5688 break;
5689 case QEMU_OPTION_usbdevice:
5690 usb_enabled = 1;
5691 if (usb_devices_index >= MAX_USB_CMDLINE) {
5692 fprintf(stderr, "Too many USB devices\n");
5693 exit(1);
5695 usb_devices[usb_devices_index] = optarg;
5696 usb_devices_index++;
5697 break;
5698 case QEMU_OPTION_smp:
5699 smp_cpus = atoi(optarg);
5700 if (smp_cpus < 1) {
5701 fprintf(stderr, "Invalid number of CPUs\n");
5702 exit(1);
5704 break;
5705 case QEMU_OPTION_vnc:
5706 display_type = DT_VNC;
5707 vnc_display = optarg;
5708 break;
5709 #ifdef TARGET_I386
5710 case QEMU_OPTION_no_acpi:
5711 acpi_enabled = 0;
5712 break;
5713 case QEMU_OPTION_no_hpet:
5714 no_hpet = 1;
5715 break;
5716 case QEMU_OPTION_balloon:
5717 if (balloon_parse(optarg) < 0) {
5718 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5719 exit(1);
5721 break;
5722 #endif
5723 case QEMU_OPTION_no_reboot:
5724 no_reboot = 1;
5725 break;
5726 case QEMU_OPTION_no_shutdown:
5727 no_shutdown = 1;
5728 break;
5729 case QEMU_OPTION_show_cursor:
5730 cursor_hide = 0;
5731 break;
5732 case QEMU_OPTION_uuid:
5733 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5734 fprintf(stderr, "Fail to parse UUID string."
5735 " Wrong format.\n");
5736 exit(1);
5738 break;
5739 #ifndef _WIN32
5740 case QEMU_OPTION_daemonize:
5741 daemonize = 1;
5742 break;
5743 #endif
5744 case QEMU_OPTION_option_rom:
5745 if (nb_option_roms >= MAX_OPTION_ROMS) {
5746 fprintf(stderr, "Too many option ROMs\n");
5747 exit(1);
5749 option_rom[nb_option_roms] = optarg;
5750 nb_option_roms++;
5751 break;
5752 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5753 case QEMU_OPTION_semihosting:
5754 semihosting_enabled = 1;
5755 break;
5756 #endif
5757 case QEMU_OPTION_tdf:
5758 time_drift_fix = 1;
5759 break;
5760 case QEMU_OPTION_kvm_shadow_memory:
5761 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5762 break;
5763 case QEMU_OPTION_mempath:
5764 mem_path = optarg;
5765 break;
5766 #ifdef MAP_POPULATE
5767 case QEMU_OPTION_mem_prealloc:
5768 mem_prealloc = !mem_prealloc;
5769 break;
5770 #endif
5771 case QEMU_OPTION_name:
5772 qemu_name = optarg;
5773 break;
5774 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5775 case QEMU_OPTION_prom_env:
5776 if (nb_prom_envs >= MAX_PROM_ENVS) {
5777 fprintf(stderr, "Too many prom variables\n");
5778 exit(1);
5780 prom_envs[nb_prom_envs] = optarg;
5781 nb_prom_envs++;
5782 break;
5783 #endif
5784 #ifdef TARGET_ARM
5785 case QEMU_OPTION_old_param:
5786 old_param = 1;
5787 break;
5788 #endif
5789 case QEMU_OPTION_clock:
5790 configure_alarms(optarg);
5791 break;
5792 case QEMU_OPTION_startdate:
5794 struct tm tm;
5795 time_t rtc_start_date;
5796 if (!strcmp(optarg, "now")) {
5797 rtc_date_offset = -1;
5798 } else {
5799 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5800 &tm.tm_year,
5801 &tm.tm_mon,
5802 &tm.tm_mday,
5803 &tm.tm_hour,
5804 &tm.tm_min,
5805 &tm.tm_sec) == 6) {
5806 /* OK */
5807 } else if (sscanf(optarg, "%d-%d-%d",
5808 &tm.tm_year,
5809 &tm.tm_mon,
5810 &tm.tm_mday) == 3) {
5811 tm.tm_hour = 0;
5812 tm.tm_min = 0;
5813 tm.tm_sec = 0;
5814 } else {
5815 goto date_fail;
5817 tm.tm_year -= 1900;
5818 tm.tm_mon--;
5819 rtc_start_date = mktimegm(&tm);
5820 if (rtc_start_date == -1) {
5821 date_fail:
5822 fprintf(stderr, "Invalid date format. Valid format are:\n"
5823 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5824 exit(1);
5826 rtc_date_offset = time(NULL) - rtc_start_date;
5829 break;
5830 case QEMU_OPTION_tb_size:
5831 tb_size = strtol(optarg, NULL, 0);
5832 if (tb_size < 0)
5833 tb_size = 0;
5834 break;
5835 case QEMU_OPTION_icount:
5836 use_icount = 1;
5837 if (strcmp(optarg, "auto") == 0) {
5838 icount_time_shift = -1;
5839 } else {
5840 icount_time_shift = strtol(optarg, NULL, 0);
5842 break;
5843 case QEMU_OPTION_incoming:
5844 incoming = optarg;
5845 break;
5846 #ifndef _WIN32
5847 case QEMU_OPTION_chroot:
5848 chroot_dir = optarg;
5849 break;
5850 case QEMU_OPTION_runas:
5851 run_as = optarg;
5852 break;
5853 case QEMU_OPTION_nvram:
5854 nvram = optarg;
5855 break;
5856 #endif
5857 #ifdef CONFIG_XEN
5858 case QEMU_OPTION_xen_domid:
5859 xen_domid = atoi(optarg);
5860 break;
5861 case QEMU_OPTION_xen_create:
5862 xen_mode = XEN_CREATE;
5863 break;
5864 case QEMU_OPTION_xen_attach:
5865 xen_mode = XEN_ATTACH;
5866 break;
5867 #endif
5872 /* If no data_dir is specified then try to find it relative to the
5873 executable path. */
5874 if (!data_dir) {
5875 data_dir = find_datadir(argv[0]);
5877 /* If all else fails use the install patch specified when building. */
5878 if (!data_dir) {
5879 data_dir = CONFIG_QEMU_SHAREDIR;
5882 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5883 if (kvm_allowed && kqemu_allowed) {
5884 fprintf(stderr,
5885 "You can not enable both KVM and kqemu at the same time\n");
5886 exit(1);
5888 #endif
5890 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5891 if (smp_cpus > machine->max_cpus) {
5892 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5893 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5894 machine->max_cpus);
5895 exit(1);
5898 if (display_type == DT_NOGRAPHIC) {
5899 if (serial_device_index == 0)
5900 serial_devices[0] = "stdio";
5901 if (parallel_device_index == 0)
5902 parallel_devices[0] = "null";
5903 if (strncmp(monitor_device, "vc", 2) == 0)
5904 monitor_device = "stdio";
5907 #ifndef _WIN32
5908 if (daemonize) {
5909 pid_t pid;
5911 if (pipe(fds) == -1)
5912 exit(1);
5914 pid = fork();
5915 if (pid > 0) {
5916 uint8_t status;
5917 ssize_t len;
5919 close(fds[1]);
5921 again:
5922 len = read(fds[0], &status, 1);
5923 if (len == -1 && (errno == EINTR))
5924 goto again;
5926 if (len != 1)
5927 exit(1);
5928 else if (status == 1) {
5929 fprintf(stderr, "Could not acquire pidfile\n");
5930 exit(1);
5931 } else
5932 exit(0);
5933 } else if (pid < 0)
5934 exit(1);
5936 setsid();
5938 pid = fork();
5939 if (pid > 0)
5940 exit(0);
5941 else if (pid < 0)
5942 exit(1);
5944 umask(027);
5946 signal(SIGTSTP, SIG_IGN);
5947 signal(SIGTTOU, SIG_IGN);
5948 signal(SIGTTIN, SIG_IGN);
5951 #ifdef USE_KVM
5952 if (kvm_enabled()) {
5953 if (kvm_qemu_init() < 0) {
5954 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5955 #ifdef NO_CPU_EMULATION
5956 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5957 exit(1);
5958 #endif
5959 kvm_allowed = 0;
5962 #endif
5964 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5965 if (daemonize) {
5966 uint8_t status = 1;
5967 write(fds[1], &status, 1);
5968 } else
5969 fprintf(stderr, "Could not acquire pid file\n");
5970 exit(1);
5972 #endif
5974 #ifdef CONFIG_KQEMU
5975 if (smp_cpus > 1)
5976 kqemu_allowed = 0;
5977 #endif
5978 if (qemu_init_main_loop()) {
5979 fprintf(stderr, "qemu_init_main_loop failed\n");
5980 exit(1);
5982 linux_boot = (kernel_filename != NULL);
5984 if (!linux_boot && *kernel_cmdline != '\0') {
5985 fprintf(stderr, "-append only allowed with -kernel option\n");
5986 exit(1);
5989 if (!linux_boot && initrd_filename != NULL) {
5990 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5991 exit(1);
5994 /* boot to floppy or the default cd if no hard disk defined yet */
5995 if (!boot_devices[0]) {
5996 boot_devices = "cad";
5998 setvbuf(stdout, NULL, _IOLBF, 0);
6000 init_timers();
6001 if (init_timer_alarm() < 0) {
6002 fprintf(stderr, "could not initialize alarm timer\n");
6003 exit(1);
6005 if (use_icount && icount_time_shift < 0) {
6006 use_icount = 2;
6007 /* 125MIPS seems a reasonable initial guess at the guest speed.
6008 It will be corrected fairly quickly anyway. */
6009 icount_time_shift = 3;
6010 init_icount_adjust();
6013 #ifdef _WIN32
6014 socket_init();
6015 #endif
6017 /* init network clients */
6018 if (nb_net_clients == 0) {
6019 /* if no clients, we use a default config */
6020 net_clients[nb_net_clients++] = "nic";
6021 #ifdef CONFIG_SLIRP
6022 net_clients[nb_net_clients++] = "user";
6023 #endif
6026 for(i = 0;i < nb_net_clients; i++) {
6027 if (net_client_parse(net_clients[i]) < 0)
6028 exit(1);
6031 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
6032 net_set_boot_mask(net_boot);
6034 net_client_check();
6036 /* init the bluetooth world */
6037 for (i = 0; i < nb_bt_opts; i++)
6038 if (bt_parse(bt_opts[i]))
6039 exit(1);
6041 /* init the memory */
6042 if (ram_size == 0)
6043 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6045 if (kvm_enabled()) {
6046 if (kvm_qemu_create_context() < 0) {
6047 fprintf(stderr, "Could not create KVM context\n");
6048 exit(1);
6052 #ifdef CONFIG_KQEMU
6053 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
6054 guest ram allocation. It needs to go away. */
6055 if (kqemu_allowed) {
6056 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
6057 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
6058 if (!kqemu_phys_ram_base) {
6059 fprintf(stderr, "Could not allocate physical memory\n");
6060 exit(1);
6063 #endif
6065 /* init the dynamic translator */
6066 cpu_exec_init_all(tb_size * 1024 * 1024);
6068 bdrv_init();
6070 /* we always create the cdrom drive, even if no disk is there */
6072 if (nb_drives_opt < MAX_DRIVES)
6073 drive_add(NULL, CDROM_ALIAS);
6075 /* we always create at least one floppy */
6077 if (nb_drives_opt < MAX_DRIVES)
6078 drive_add(NULL, FD_ALIAS, 0);
6080 /* we always create one sd slot, even if no card is in it */
6082 if (nb_drives_opt < MAX_DRIVES)
6083 drive_add(NULL, SD_ALIAS);
6085 /* open the virtual block devices
6086 * note that migration with device
6087 * hot add/remove is broken.
6089 for(i = 0; i < nb_drives_opt; i++)
6090 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
6091 exit(1);
6093 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6094 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
6096 #ifndef _WIN32
6097 /* must be after terminal init, SDL library changes signal handlers */
6098 sighandler_setup();
6099 #endif
6101 /* Maintain compatibility with multiple stdio monitors */
6102 if (!strcmp(monitor_device,"stdio")) {
6103 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
6104 const char *devname = serial_devices[i];
6105 if (devname && !strcmp(devname,"mon:stdio")) {
6106 monitor_device = NULL;
6107 break;
6108 } else if (devname && !strcmp(devname,"stdio")) {
6109 monitor_device = NULL;
6110 serial_devices[i] = "mon:stdio";
6111 break;
6116 if (nb_numa_nodes > 0) {
6117 int i;
6119 if (nb_numa_nodes > smp_cpus) {
6120 nb_numa_nodes = smp_cpus;
6123 /* If no memory size if given for any node, assume the default case
6124 * and distribute the available memory equally across all nodes
6126 for (i = 0; i < nb_numa_nodes; i++) {
6127 if (node_mem[i] != 0)
6128 break;
6130 if (i == nb_numa_nodes) {
6131 uint64_t usedmem = 0;
6133 /* On Linux, the each node's border has to be 8MB aligned,
6134 * the final node gets the rest.
6136 for (i = 0; i < nb_numa_nodes - 1; i++) {
6137 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
6138 usedmem += node_mem[i];
6140 node_mem[i] = ram_size - usedmem;
6143 for (i = 0; i < nb_numa_nodes; i++) {
6144 if (node_cpumask[i] != 0)
6145 break;
6147 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6148 * must cope with this anyway, because there are BIOSes out there in
6149 * real machines which also use this scheme.
6151 if (i == nb_numa_nodes) {
6152 for (i = 0; i < smp_cpus; i++) {
6153 node_cpumask[i % nb_numa_nodes] |= 1 << i;
6158 #ifdef KVM_UPSTREAM
6159 if (kvm_enabled()) {
6160 int ret;
6162 ret = kvm_init(smp_cpus);
6163 if (ret < 0) {
6164 fprintf(stderr, "failed to initialize KVM\n");
6165 exit(1);
6168 #endif
6170 if (monitor_device) {
6171 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
6172 if (!monitor_hd) {
6173 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6174 exit(1);
6178 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6179 const char *devname = serial_devices[i];
6180 if (devname && strcmp(devname, "none")) {
6181 char label[32];
6182 snprintf(label, sizeof(label), "serial%d", i);
6183 serial_hds[i] = qemu_chr_open(label, devname, NULL);
6184 if (!serial_hds[i]) {
6185 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6186 devname);
6187 exit(1);
6192 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6193 const char *devname = parallel_devices[i];
6194 if (devname && strcmp(devname, "none")) {
6195 char label[32];
6196 snprintf(label, sizeof(label), "parallel%d", i);
6197 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
6198 if (!parallel_hds[i]) {
6199 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6200 devname);
6201 exit(1);
6206 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6207 const char *devname = virtio_consoles[i];
6208 if (devname && strcmp(devname, "none")) {
6209 char label[32];
6210 snprintf(label, sizeof(label), "virtcon%d", i);
6211 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
6212 if (!virtcon_hds[i]) {
6213 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
6214 devname);
6215 exit(1);
6220 module_call_init(MODULE_INIT_DEVICE);
6222 if (kvm_enabled())
6223 kvm_init_ap();
6225 machine->init(ram_size, boot_devices,
6226 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6229 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6230 for (i = 0; i < nb_numa_nodes; i++) {
6231 if (node_cpumask[i] & (1 << env->cpu_index)) {
6232 env->numa_node = i;
6237 current_machine = machine;
6239 /* init USB devices */
6240 if (usb_enabled) {
6241 for(i = 0; i < usb_devices_index; i++) {
6242 if (usb_device_add(usb_devices[i], 0) < 0) {
6243 fprintf(stderr, "Warning: could not add USB device %s\n",
6244 usb_devices[i]);
6249 if (!display_state)
6250 dumb_display_init();
6251 /* just use the first displaystate for the moment */
6252 ds = display_state;
6254 if (display_type == DT_DEFAULT) {
6255 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6256 display_type = DT_SDL;
6257 #else
6258 display_type = DT_VNC;
6259 vnc_display = "localhost:0,to=99";
6260 show_vnc_port = 1;
6261 #endif
6265 switch (display_type) {
6266 case DT_NOGRAPHIC:
6267 break;
6268 #if defined(CONFIG_CURSES)
6269 case DT_CURSES:
6270 curses_display_init(ds, full_screen);
6271 break;
6272 #endif
6273 #if defined(CONFIG_SDL)
6274 case DT_SDL:
6275 sdl_display_init(ds, full_screen, no_frame);
6276 break;
6277 #elif defined(CONFIG_COCOA)
6278 case DT_SDL:
6279 cocoa_display_init(ds, full_screen);
6280 break;
6281 #endif
6282 case DT_VNC:
6283 vnc_display_init(ds);
6284 if (vnc_display_open(ds, vnc_display) < 0)
6285 exit(1);
6287 if (show_vnc_port) {
6288 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6290 break;
6291 default:
6292 break;
6294 dpy_resize(ds);
6296 dcl = ds->listeners;
6297 while (dcl != NULL) {
6298 if (dcl->dpy_refresh != NULL) {
6299 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6300 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6302 dcl = dcl->next;
6305 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6306 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6307 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6310 text_consoles_set_display(display_state);
6311 qemu_chr_initial_reset();
6313 if (monitor_device && monitor_hd)
6314 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6316 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6317 const char *devname = serial_devices[i];
6318 if (devname && strcmp(devname, "none")) {
6319 if (strstart(devname, "vc", 0))
6320 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6324 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6325 const char *devname = parallel_devices[i];
6326 if (devname && strcmp(devname, "none")) {
6327 if (strstart(devname, "vc", 0))
6328 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6332 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6333 const char *devname = virtio_consoles[i];
6334 if (virtcon_hds[i] && devname) {
6335 if (strstart(devname, "vc", 0))
6336 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6340 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6341 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6342 gdbstub_dev);
6343 exit(1);
6346 if (loadvm)
6347 do_loadvm(cur_mon, loadvm);
6349 if (incoming) {
6350 autostart = 0; /* fixme how to deal with -daemonize */
6351 qemu_start_incoming_migration(incoming);
6354 if (autostart)
6355 vm_start();
6357 #ifndef _WIN32
6358 if (daemonize) {
6359 uint8_t status = 0;
6360 ssize_t len;
6362 again1:
6363 len = write(fds[1], &status, 1);
6364 if (len == -1 && (errno == EINTR))
6365 goto again1;
6367 if (len != 1)
6368 exit(1);
6370 chdir("/");
6371 TFR(fd = open("/dev/null", O_RDWR));
6372 if (fd == -1)
6373 exit(1);
6376 if (run_as) {
6377 pwd = getpwnam(run_as);
6378 if (!pwd) {
6379 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6380 exit(1);
6384 if (chroot_dir) {
6385 if (chroot(chroot_dir) < 0) {
6386 fprintf(stderr, "chroot failed\n");
6387 exit(1);
6389 chdir("/");
6392 if (run_as) {
6393 if (setgid(pwd->pw_gid) < 0) {
6394 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6395 exit(1);
6397 if (setuid(pwd->pw_uid) < 0) {
6398 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6399 exit(1);
6401 if (setuid(0) != -1) {
6402 fprintf(stderr, "Dropping privileges failed\n");
6403 exit(1);
6407 if (daemonize) {
6408 dup2(fd, 0);
6409 dup2(fd, 1);
6410 dup2(fd, 2);
6412 close(fd);
6414 #endif
6416 main_loop();
6417 quit_timers();
6418 net_cleanup();
6420 return 0;