Merge commit 'dedd9ecaf9' into stable-0.11
[qemu-kvm/fedora.git] / vl.c
bloba4bd657a5245c46fbc80d76f57ecf8208997431f
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"
34 /* Needed early to override system queue definitions on BSD */
35 #include "sys-queue.h"
37 #ifndef _WIN32
38 #include <libgen.h>
39 #include <pwd.h>
40 #include <sys/times.h>
41 #include <sys/wait.h>
42 #include <termios.h>
43 #include <sys/mman.h>
44 #include <sys/ioctl.h>
45 #include <sys/resource.h>
46 #include <sys/socket.h>
47 #include <netinet/in.h>
48 #include <net/if.h>
49 #if defined(__NetBSD__)
50 #include <net/if_tap.h>
51 #endif
52 #ifdef __linux__
53 #include <linux/if_tun.h>
54 #endif
55 #include <arpa/inet.h>
56 #include <dirent.h>
57 #include <netdb.h>
58 #include <sys/select.h>
59 #ifdef HOST_BSD
60 #include <sys/stat.h>
61 #if defined(__FreeBSD__) || defined(__DragonFly__)
62 #include <libutil.h>
63 #else
64 #include <util.h>
65 #endif
66 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
67 #include <freebsd/stdlib.h>
68 #else
69 #ifdef __linux__
70 #include <pty.h>
71 #include <malloc.h>
72 #include <linux/rtc.h>
73 #include <sys/prctl.h>
75 /* For the benefit of older linux systems which don't supply it,
76 we use a local copy of hpet.h. */
77 /* #include <linux/hpet.h> */
78 #include "hpet.h"
80 #include <linux/ppdev.h>
81 #include <linux/parport.h>
82 #endif
83 #ifdef __sun__
84 #include <sys/stat.h>
85 #include <sys/ethernet.h>
86 #include <sys/sockio.h>
87 #include <netinet/arp.h>
88 #include <netinet/in.h>
89 #include <netinet/in_systm.h>
90 #include <netinet/ip.h>
91 #include <netinet/ip_icmp.h> // must come after ip.h
92 #include <netinet/udp.h>
93 #include <netinet/tcp.h>
94 #include <net/if.h>
95 #include <syslog.h>
96 #include <stropts.h>
97 #endif
98 #endif
99 #endif
101 #if defined(__OpenBSD__)
102 #include <util.h>
103 #endif
105 #if defined(CONFIG_VDE)
106 #include <libvdeplug.h>
107 #endif
109 #ifdef _WIN32
110 #include <windows.h>
111 #include <malloc.h>
112 #include <sys/timeb.h>
113 #include <mmsystem.h>
114 #define getopt_long_only getopt_long
115 #define memalign(align, size) malloc(size)
116 #endif
118 #ifdef CONFIG_SDL
119 #if defined(__APPLE__) || defined(main)
120 #include <SDL.h>
121 int qemu_main(int argc, char **argv, char **envp);
122 int main(int argc, char **argv)
124 return qemu_main(argc, argv, NULL);
126 #undef main
127 #define main qemu_main
128 #endif
129 #endif /* CONFIG_SDL */
131 #ifdef CONFIG_COCOA
132 #undef main
133 #define main qemu_main
134 #endif /* CONFIG_COCOA */
136 #include "hw/hw.h"
137 #include "hw/boards.h"
138 #include "hw/usb.h"
139 #include "hw/pcmcia.h"
140 #include "hw/pc.h"
141 #include "hw/audiodev.h"
142 #include "hw/isa.h"
143 #include "hw/baum.h"
144 #include "hw/bt.h"
145 #include "hw/watchdog.h"
146 #include "hw/smbios.h"
147 #include "hw/xen.h"
148 #include "bt-host.h"
149 #include "net.h"
150 #include "monitor.h"
151 #include "console.h"
152 #include "sysemu.h"
153 #include "gdbstub.h"
154 #include "qemu-timer.h"
155 #include "qemu-char.h"
156 #include "cache-utils.h"
157 #include "block.h"
158 #include "dma.h"
159 #include "audio/audio.h"
160 #include "migration.h"
161 #include "kvm.h"
162 #include "balloon.h"
163 #include "qemu-option.h"
164 #include "qemu-kvm.h"
165 #include "hw/device-assignment.h"
167 #include "disas.h"
169 #include "exec-all.h"
171 #include "qemu_socket.h"
173 #include "slirp/libslirp.h"
175 //#define DEBUG_NET
176 //#define DEBUG_SLIRP
178 #define DEFAULT_RAM_SIZE 128
180 /* Max number of USB devices that can be specified on the commandline. */
181 #define MAX_USB_CMDLINE 8
183 /* Max number of bluetooth switches on the commandline. */
184 #define MAX_BT_CMDLINE 10
186 static const char *data_dir;
187 const char *bios_name = NULL;
188 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
189 to store the VM snapshots */
190 DriveInfo drives_table[MAX_DRIVES+1];
191 int nb_drives;
192 int extboot_drive = -1;
193 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
194 static DisplayState *display_state;
195 DisplayType display_type = DT_DEFAULT;
196 const char* keyboard_layout = NULL;
197 int64_t ticks_per_sec;
198 ram_addr_t ram_size;
199 int nb_nics;
200 NICInfo nd_table[MAX_NICS];
201 int vm_running;
202 static int autostart;
203 static int rtc_utc = 1;
204 static int rtc_date_offset = -1; /* -1 means no change */
205 int cirrus_vga_enabled = 1;
206 int std_vga_enabled = 0;
207 int vmsvga_enabled = 0;
208 int xenfb_enabled = 0;
209 #ifdef TARGET_SPARC
210 int graphic_width = 1024;
211 int graphic_height = 768;
212 int graphic_depth = 8;
213 #else
214 int graphic_width = 800;
215 int graphic_height = 600;
216 int graphic_depth = 15;
217 #endif
218 static int full_screen = 0;
219 #ifdef CONFIG_SDL
220 static int no_frame = 0;
221 #endif
222 int no_quit = 0;
223 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
224 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
225 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
226 #ifdef TARGET_I386
227 int win2k_install_hack = 0;
228 int rtc_td_hack = 0;
229 #endif
230 int usb_enabled = 0;
231 int singlestep = 0;
232 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
233 int assigned_devices_index;
234 int smp_cpus = 1;
235 const char *vnc_display;
236 int acpi_enabled = 1;
237 #ifdef TARGET_I386
238 int no_hpet = 0;
239 #endif
240 int virtio_balloon = 1;
241 const char *virtio_balloon_devaddr;
242 int fd_bootchk = 1;
243 int no_reboot = 0;
244 int no_shutdown = 0;
245 int cursor_hide = 1;
246 int graphic_rotate = 0;
247 uint8_t irq0override = 1;
248 #ifndef _WIN32
249 int daemonize = 0;
250 #endif
251 WatchdogTimerModel *watchdog = NULL;
252 int watchdog_action = WDT_RESET;
253 const char *option_rom[MAX_OPTION_ROMS];
254 int nb_option_roms;
255 int semihosting_enabled = 0;
256 int time_drift_fix = 0;
257 unsigned int kvm_shadow_memory = 0;
258 const char *mem_path = NULL;
259 #ifdef MAP_POPULATE
260 int mem_prealloc = 1; /* force preallocation of physical target memory */
261 #endif
262 #ifdef TARGET_ARM
263 int old_param = 0;
264 #endif
265 const char *qemu_name;
266 int alt_grab = 0;
267 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
268 unsigned int nb_prom_envs = 0;
269 const char *prom_envs[MAX_PROM_ENVS];
270 #endif
271 int nb_drives_opt;
272 const char *nvram = NULL;
273 struct drive_opt drives_opt[MAX_DRIVES];
274 int boot_menu;
276 int nb_numa_nodes;
277 uint64_t node_mem[MAX_NODES];
278 uint64_t node_cpumask[MAX_NODES];
280 static CPUState *cur_cpu;
281 static CPUState *next_cpu;
282 static int timer_alarm_pending = 1;
283 /* Conversion factor from emulated instructions to virtual clock ticks. */
284 static int icount_time_shift;
285 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
286 #define MAX_ICOUNT_SHIFT 10
287 /* Compensate for varying guest execution speed. */
288 static int64_t qemu_icount_bias;
289 static QEMUTimer *icount_rt_timer;
290 static QEMUTimer *icount_vm_timer;
291 static QEMUTimer *nographic_timer;
293 uint8_t qemu_uuid[16];
295 static QEMUBootSetHandler *boot_set_handler;
296 static void *boot_set_opaque;
298 /***********************************************************/
299 /* x86 ISA bus support */
301 target_phys_addr_t isa_mem_base = 0;
302 PicState2 *isa_pic;
304 /***********************************************************/
305 void hw_error(const char *fmt, ...)
307 va_list ap;
308 CPUState *env;
310 va_start(ap, fmt);
311 fprintf(stderr, "qemu: hardware error: ");
312 vfprintf(stderr, fmt, ap);
313 fprintf(stderr, "\n");
314 for(env = first_cpu; env != NULL; env = env->next_cpu) {
315 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
316 #ifdef TARGET_I386
317 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
318 #else
319 cpu_dump_state(env, stderr, fprintf, 0);
320 #endif
322 va_end(ap);
323 abort();
326 static void set_proc_name(const char *s)
328 #ifdef __linux__
329 char name[16];
330 if (!s)
331 return;
332 name[sizeof(name) - 1] = 0;
333 strncpy(name, s, sizeof(name));
334 /* Could rewrite argv[0] too, but that's a bit more complicated.
335 This simple way is enough for `top'. */
336 prctl(PR_SET_NAME, name);
337 #endif
340 /***************/
341 /* ballooning */
343 static QEMUBalloonEvent *qemu_balloon_event;
344 void *qemu_balloon_event_opaque;
346 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
348 qemu_balloon_event = func;
349 qemu_balloon_event_opaque = opaque;
352 void qemu_balloon(ram_addr_t target)
354 if (qemu_balloon_event)
355 qemu_balloon_event(qemu_balloon_event_opaque, target);
358 ram_addr_t qemu_balloon_status(void)
360 if (qemu_balloon_event)
361 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
362 return 0;
365 /***********************************************************/
366 /* keyboard/mouse */
368 static QEMUPutKBDEvent *qemu_put_kbd_event;
369 static void *qemu_put_kbd_event_opaque;
370 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
371 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
373 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
375 qemu_put_kbd_event_opaque = opaque;
376 qemu_put_kbd_event = func;
379 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
380 void *opaque, int absolute,
381 const char *name)
383 QEMUPutMouseEntry *s, *cursor;
385 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
387 s->qemu_put_mouse_event = func;
388 s->qemu_put_mouse_event_opaque = opaque;
389 s->qemu_put_mouse_event_absolute = absolute;
390 s->qemu_put_mouse_event_name = qemu_strdup(name);
391 s->next = NULL;
393 if (!qemu_put_mouse_event_head) {
394 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
395 return s;
398 cursor = qemu_put_mouse_event_head;
399 while (cursor->next != NULL)
400 cursor = cursor->next;
402 cursor->next = s;
403 qemu_put_mouse_event_current = s;
405 return s;
408 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
410 QEMUPutMouseEntry *prev = NULL, *cursor;
412 if (!qemu_put_mouse_event_head || entry == NULL)
413 return;
415 cursor = qemu_put_mouse_event_head;
416 while (cursor != NULL && cursor != entry) {
417 prev = cursor;
418 cursor = cursor->next;
421 if (cursor == NULL) // does not exist or list empty
422 return;
423 else if (prev == NULL) { // entry is head
424 qemu_put_mouse_event_head = cursor->next;
425 if (qemu_put_mouse_event_current == entry)
426 qemu_put_mouse_event_current = cursor->next;
427 qemu_free(entry->qemu_put_mouse_event_name);
428 qemu_free(entry);
429 return;
432 prev->next = entry->next;
434 if (qemu_put_mouse_event_current == entry)
435 qemu_put_mouse_event_current = prev;
437 qemu_free(entry->qemu_put_mouse_event_name);
438 qemu_free(entry);
441 void kbd_put_keycode(int keycode)
443 if (qemu_put_kbd_event) {
444 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
448 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
450 QEMUPutMouseEvent *mouse_event;
451 void *mouse_event_opaque;
452 int width;
454 if (!qemu_put_mouse_event_current) {
455 return;
458 mouse_event =
459 qemu_put_mouse_event_current->qemu_put_mouse_event;
460 mouse_event_opaque =
461 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
463 if (mouse_event) {
464 if (graphic_rotate) {
465 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
466 width = 0x7fff;
467 else
468 width = graphic_width - 1;
469 mouse_event(mouse_event_opaque,
470 width - dy, dx, dz, buttons_state);
471 } else
472 mouse_event(mouse_event_opaque,
473 dx, dy, dz, buttons_state);
477 int kbd_mouse_is_absolute(void)
479 if (!qemu_put_mouse_event_current)
480 return 0;
482 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
485 void do_info_mice(Monitor *mon)
487 QEMUPutMouseEntry *cursor;
488 int index = 0;
490 if (!qemu_put_mouse_event_head) {
491 monitor_printf(mon, "No mouse devices connected\n");
492 return;
495 monitor_printf(mon, "Mouse devices available:\n");
496 cursor = qemu_put_mouse_event_head;
497 while (cursor != NULL) {
498 monitor_printf(mon, "%c Mouse #%d: %s\n",
499 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
500 index, cursor->qemu_put_mouse_event_name);
501 index++;
502 cursor = cursor->next;
506 void do_mouse_set(Monitor *mon, int index)
508 QEMUPutMouseEntry *cursor;
509 int i = 0;
511 if (!qemu_put_mouse_event_head) {
512 monitor_printf(mon, "No mouse devices connected\n");
513 return;
516 cursor = qemu_put_mouse_event_head;
517 while (cursor != NULL && index != i) {
518 i++;
519 cursor = cursor->next;
522 if (cursor != NULL)
523 qemu_put_mouse_event_current = cursor;
524 else
525 monitor_printf(mon, "Mouse at given index not found\n");
528 /* compute with 96 bit intermediate result: (a*b)/c */
529 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
531 union {
532 uint64_t ll;
533 struct {
534 #ifdef WORDS_BIGENDIAN
535 uint32_t high, low;
536 #else
537 uint32_t low, high;
538 #endif
539 } l;
540 } u, res;
541 uint64_t rl, rh;
543 u.ll = a;
544 rl = (uint64_t)u.l.low * (uint64_t)b;
545 rh = (uint64_t)u.l.high * (uint64_t)b;
546 rh += (rl >> 32);
547 res.l.high = rh / c;
548 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
549 return res.ll;
552 /***********************************************************/
553 /* real time host monotonic timer */
555 #define QEMU_TIMER_BASE 1000000000LL
557 #ifdef WIN32
559 static int64_t clock_freq;
561 static void init_get_clock(void)
563 LARGE_INTEGER freq;
564 int ret;
565 ret = QueryPerformanceFrequency(&freq);
566 if (ret == 0) {
567 fprintf(stderr, "Could not calibrate ticks\n");
568 exit(1);
570 clock_freq = freq.QuadPart;
573 static int64_t get_clock(void)
575 LARGE_INTEGER ti;
576 QueryPerformanceCounter(&ti);
577 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
580 #else
582 static int use_rt_clock;
584 static void init_get_clock(void)
586 use_rt_clock = 0;
587 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
588 || defined(__DragonFly__)
590 struct timespec ts;
591 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
592 use_rt_clock = 1;
595 #endif
598 static int64_t get_clock(void)
600 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
601 || defined(__DragonFly__)
602 if (use_rt_clock) {
603 struct timespec ts;
604 clock_gettime(CLOCK_MONOTONIC, &ts);
605 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
606 } else
607 #endif
609 /* XXX: using gettimeofday leads to problems if the date
610 changes, so it should be avoided. */
611 struct timeval tv;
612 gettimeofday(&tv, NULL);
613 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
616 #endif
618 /* Return the virtual CPU time, based on the instruction counter. */
619 static int64_t cpu_get_icount(void)
621 int64_t icount;
622 CPUState *env = cpu_single_env;;
623 icount = qemu_icount;
624 if (env) {
625 if (!can_do_io(env))
626 fprintf(stderr, "Bad clock read\n");
627 icount -= (env->icount_decr.u16.low + env->icount_extra);
629 return qemu_icount_bias + (icount << icount_time_shift);
632 /***********************************************************/
633 /* guest cycle counter */
635 static int64_t cpu_ticks_prev;
636 static int64_t cpu_ticks_offset;
637 static int64_t cpu_clock_offset;
638 static int cpu_ticks_enabled;
640 /* return the host CPU cycle counter and handle stop/restart */
641 int64_t cpu_get_ticks(void)
643 if (use_icount) {
644 return cpu_get_icount();
646 if (!cpu_ticks_enabled) {
647 return cpu_ticks_offset;
648 } else {
649 int64_t ticks;
650 ticks = cpu_get_real_ticks();
651 if (cpu_ticks_prev > ticks) {
652 /* Note: non increasing ticks may happen if the host uses
653 software suspend */
654 cpu_ticks_offset += cpu_ticks_prev - ticks;
656 cpu_ticks_prev = ticks;
657 return ticks + cpu_ticks_offset;
661 /* return the host CPU monotonic timer and handle stop/restart */
662 static int64_t cpu_get_clock(void)
664 int64_t ti;
665 if (!cpu_ticks_enabled) {
666 return cpu_clock_offset;
667 } else {
668 ti = get_clock();
669 return ti + cpu_clock_offset;
673 /* enable cpu_get_ticks() */
674 void cpu_enable_ticks(void)
676 if (!cpu_ticks_enabled) {
677 cpu_ticks_offset -= cpu_get_real_ticks();
678 cpu_clock_offset -= get_clock();
679 cpu_ticks_enabled = 1;
683 /* disable cpu_get_ticks() : the clock is stopped. You must not call
684 cpu_get_ticks() after that. */
685 void cpu_disable_ticks(void)
687 if (cpu_ticks_enabled) {
688 cpu_ticks_offset = cpu_get_ticks();
689 cpu_clock_offset = cpu_get_clock();
690 cpu_ticks_enabled = 0;
694 /***********************************************************/
695 /* timers */
697 #define QEMU_TIMER_REALTIME 0
698 #define QEMU_TIMER_VIRTUAL 1
700 struct QEMUClock {
701 int type;
702 /* XXX: add frequency */
705 struct QEMUTimer {
706 QEMUClock *clock;
707 int64_t expire_time;
708 QEMUTimerCB *cb;
709 void *opaque;
710 struct QEMUTimer *next;
713 struct qemu_alarm_timer {
714 char const *name;
715 unsigned int flags;
717 int (*start)(struct qemu_alarm_timer *t);
718 void (*stop)(struct qemu_alarm_timer *t);
719 void (*rearm)(struct qemu_alarm_timer *t);
720 void *priv;
723 #define ALARM_FLAG_DYNTICKS 0x1
724 #define ALARM_FLAG_EXPIRED 0x2
726 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
728 return t && (t->flags & ALARM_FLAG_DYNTICKS);
731 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
733 if (!alarm_has_dynticks(t))
734 return;
736 t->rearm(t);
739 /* TODO: MIN_TIMER_REARM_US should be optimized */
740 #define MIN_TIMER_REARM_US 250
742 static struct qemu_alarm_timer *alarm_timer;
744 #ifdef _WIN32
746 struct qemu_alarm_win32 {
747 MMRESULT timerId;
748 unsigned int period;
749 } alarm_win32_data = {0, -1};
751 static int win32_start_timer(struct qemu_alarm_timer *t);
752 static void win32_stop_timer(struct qemu_alarm_timer *t);
753 static void win32_rearm_timer(struct qemu_alarm_timer *t);
755 #else
757 static int unix_start_timer(struct qemu_alarm_timer *t);
758 static void unix_stop_timer(struct qemu_alarm_timer *t);
760 #ifdef __linux__
762 static int dynticks_start_timer(struct qemu_alarm_timer *t);
763 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
764 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
766 static int hpet_start_timer(struct qemu_alarm_timer *t);
767 static void hpet_stop_timer(struct qemu_alarm_timer *t);
769 static int rtc_start_timer(struct qemu_alarm_timer *t);
770 static void rtc_stop_timer(struct qemu_alarm_timer *t);
772 #endif /* __linux__ */
774 #endif /* _WIN32 */
776 /* Correlation between real and virtual time is always going to be
777 fairly approximate, so ignore small variation.
778 When the guest is idle real and virtual time will be aligned in
779 the IO wait loop. */
780 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
782 static void icount_adjust(void)
784 int64_t cur_time;
785 int64_t cur_icount;
786 int64_t delta;
787 static int64_t last_delta;
788 /* If the VM is not running, then do nothing. */
789 if (!vm_running)
790 return;
792 cur_time = cpu_get_clock();
793 cur_icount = qemu_get_clock(vm_clock);
794 delta = cur_icount - cur_time;
795 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
796 if (delta > 0
797 && last_delta + ICOUNT_WOBBLE < delta * 2
798 && icount_time_shift > 0) {
799 /* The guest is getting too far ahead. Slow time down. */
800 icount_time_shift--;
802 if (delta < 0
803 && last_delta - ICOUNT_WOBBLE > delta * 2
804 && icount_time_shift < MAX_ICOUNT_SHIFT) {
805 /* The guest is getting too far behind. Speed time up. */
806 icount_time_shift++;
808 last_delta = delta;
809 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
812 static void icount_adjust_rt(void * opaque)
814 qemu_mod_timer(icount_rt_timer,
815 qemu_get_clock(rt_clock) + 1000);
816 icount_adjust();
819 static void icount_adjust_vm(void * opaque)
821 qemu_mod_timer(icount_vm_timer,
822 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
823 icount_adjust();
826 static void init_icount_adjust(void)
828 /* Have both realtime and virtual time triggers for speed adjustment.
829 The realtime trigger catches emulated time passing too slowly,
830 the virtual time trigger catches emulated time passing too fast.
831 Realtime triggers occur even when idle, so use them less frequently
832 than VM triggers. */
833 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
834 qemu_mod_timer(icount_rt_timer,
835 qemu_get_clock(rt_clock) + 1000);
836 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
837 qemu_mod_timer(icount_vm_timer,
838 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
841 static struct qemu_alarm_timer alarm_timers[] = {
842 #ifndef _WIN32
843 #ifdef __linux__
844 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
845 dynticks_stop_timer, dynticks_rearm_timer, NULL},
846 /* HPET - if available - is preferred */
847 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
848 /* ...otherwise try RTC */
849 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
850 #endif
851 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
852 #else
853 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
854 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
855 {"win32", 0, win32_start_timer,
856 win32_stop_timer, NULL, &alarm_win32_data},
857 #endif
858 {NULL, }
861 static void show_available_alarms(void)
863 int i;
865 printf("Available alarm timers, in order of precedence:\n");
866 for (i = 0; alarm_timers[i].name; i++)
867 printf("%s\n", alarm_timers[i].name);
870 static void configure_alarms(char const *opt)
872 int i;
873 int cur = 0;
874 int count = ARRAY_SIZE(alarm_timers) - 1;
875 char *arg;
876 char *name;
877 struct qemu_alarm_timer tmp;
879 if (!strcmp(opt, "?")) {
880 show_available_alarms();
881 exit(0);
884 arg = strdup(opt);
886 /* Reorder the array */
887 name = strtok(arg, ",");
888 while (name) {
889 for (i = 0; i < count && alarm_timers[i].name; i++) {
890 if (!strcmp(alarm_timers[i].name, name))
891 break;
894 if (i == count) {
895 fprintf(stderr, "Unknown clock %s\n", name);
896 goto next;
899 if (i < cur)
900 /* Ignore */
901 goto next;
903 /* Swap */
904 tmp = alarm_timers[i];
905 alarm_timers[i] = alarm_timers[cur];
906 alarm_timers[cur] = tmp;
908 cur++;
909 next:
910 name = strtok(NULL, ",");
913 free(arg);
915 if (cur) {
916 /* Disable remaining timers */
917 for (i = cur; i < count; i++)
918 alarm_timers[i].name = NULL;
919 } else {
920 show_available_alarms();
921 exit(1);
925 QEMUClock *rt_clock;
926 QEMUClock *vm_clock;
928 static QEMUTimer *active_timers[2];
930 static QEMUClock *qemu_new_clock(int type)
932 QEMUClock *clock;
933 clock = qemu_mallocz(sizeof(QEMUClock));
934 clock->type = type;
935 return clock;
938 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
940 QEMUTimer *ts;
942 ts = qemu_mallocz(sizeof(QEMUTimer));
943 ts->clock = clock;
944 ts->cb = cb;
945 ts->opaque = opaque;
946 return ts;
949 void qemu_free_timer(QEMUTimer *ts)
951 qemu_free(ts);
954 /* stop a timer, but do not dealloc it */
955 void qemu_del_timer(QEMUTimer *ts)
957 QEMUTimer **pt, *t;
959 /* NOTE: this code must be signal safe because
960 qemu_timer_expired() can be called from a signal. */
961 pt = &active_timers[ts->clock->type];
962 for(;;) {
963 t = *pt;
964 if (!t)
965 break;
966 if (t == ts) {
967 *pt = t->next;
968 break;
970 pt = &t->next;
974 /* modify the current timer so that it will be fired when current_time
975 >= expire_time. The corresponding callback will be called. */
976 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
978 QEMUTimer **pt, *t;
980 qemu_del_timer(ts);
982 /* add the timer in the sorted list */
983 /* NOTE: this code must be signal safe because
984 qemu_timer_expired() can be called from a signal. */
985 pt = &active_timers[ts->clock->type];
986 for(;;) {
987 t = *pt;
988 if (!t)
989 break;
990 if (t->expire_time > expire_time)
991 break;
992 pt = &t->next;
994 ts->expire_time = expire_time;
995 ts->next = *pt;
996 *pt = ts;
998 /* Rearm if necessary */
999 if (pt == &active_timers[ts->clock->type]) {
1000 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1001 qemu_rearm_alarm_timer(alarm_timer);
1003 /* Interrupt execution to force deadline recalculation. */
1004 if (use_icount)
1005 qemu_notify_event();
1009 int qemu_timer_pending(QEMUTimer *ts)
1011 QEMUTimer *t;
1012 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1013 if (t == ts)
1014 return 1;
1016 return 0;
1019 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1021 if (!timer_head)
1022 return 0;
1023 return (timer_head->expire_time <= current_time);
1026 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1028 QEMUTimer *ts;
1030 for(;;) {
1031 ts = *ptimer_head;
1032 if (!ts || ts->expire_time > current_time)
1033 break;
1034 /* remove timer from the list before calling the callback */
1035 *ptimer_head = ts->next;
1036 ts->next = NULL;
1038 /* run the callback (the timer list can be modified) */
1039 ts->cb(ts->opaque);
1043 int64_t qemu_get_clock(QEMUClock *clock)
1045 switch(clock->type) {
1046 case QEMU_TIMER_REALTIME:
1047 return get_clock() / 1000000;
1048 default:
1049 case QEMU_TIMER_VIRTUAL:
1050 if (use_icount) {
1051 return cpu_get_icount();
1052 } else {
1053 return cpu_get_clock();
1058 static void init_timers(void)
1060 init_get_clock();
1061 ticks_per_sec = QEMU_TIMER_BASE;
1062 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1063 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1066 /* save a timer */
1067 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1069 uint64_t expire_time;
1071 if (qemu_timer_pending(ts)) {
1072 expire_time = ts->expire_time;
1073 } else {
1074 expire_time = -1;
1076 qemu_put_be64(f, expire_time);
1079 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1081 uint64_t expire_time;
1083 expire_time = qemu_get_be64(f);
1084 if (expire_time != -1) {
1085 qemu_mod_timer(ts, expire_time);
1086 } else {
1087 qemu_del_timer(ts);
1091 static void timer_save(QEMUFile *f, void *opaque)
1093 if (cpu_ticks_enabled) {
1094 hw_error("cannot save state if virtual timers are running");
1096 qemu_put_be64(f, cpu_ticks_offset);
1097 qemu_put_be64(f, ticks_per_sec);
1098 qemu_put_be64(f, cpu_clock_offset);
1101 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1103 if (version_id != 1 && version_id != 2)
1104 return -EINVAL;
1105 if (cpu_ticks_enabled) {
1106 return -EINVAL;
1108 cpu_ticks_offset=qemu_get_be64(f);
1109 ticks_per_sec=qemu_get_be64(f);
1110 if (version_id == 2) {
1111 cpu_clock_offset=qemu_get_be64(f);
1113 return 0;
1116 static void qemu_event_increment(void);
1118 #ifdef _WIN32
1119 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1120 DWORD_PTR dwUser, DWORD_PTR dw1,
1121 DWORD_PTR dw2)
1122 #else
1123 static void host_alarm_handler(int host_signum)
1124 #endif
1126 #if 0
1127 #define DISP_FREQ 1000
1129 static int64_t delta_min = INT64_MAX;
1130 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1131 static int count;
1132 ti = qemu_get_clock(vm_clock);
1133 if (last_clock != 0) {
1134 delta = ti - last_clock;
1135 if (delta < delta_min)
1136 delta_min = delta;
1137 if (delta > delta_max)
1138 delta_max = delta;
1139 delta_cum += delta;
1140 if (++count == DISP_FREQ) {
1141 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1142 muldiv64(delta_min, 1000000, ticks_per_sec),
1143 muldiv64(delta_max, 1000000, ticks_per_sec),
1144 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1145 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1146 count = 0;
1147 delta_min = INT64_MAX;
1148 delta_max = 0;
1149 delta_cum = 0;
1152 last_clock = ti;
1154 #endif
1155 if (alarm_has_dynticks(alarm_timer) ||
1156 (!use_icount &&
1157 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1158 qemu_get_clock(vm_clock))) ||
1159 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1160 qemu_get_clock(rt_clock))) {
1161 qemu_event_increment();
1162 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1164 #ifndef CONFIG_IOTHREAD
1165 if (next_cpu) {
1166 /* stop the currently executing cpu because a timer occured */
1167 cpu_exit(next_cpu);
1168 #ifdef CONFIG_KQEMU
1169 if (next_cpu->kqemu_enabled) {
1170 kqemu_cpu_interrupt(next_cpu);
1172 #endif
1174 #endif
1175 timer_alarm_pending = 1;
1176 qemu_notify_event();
1180 static int64_t qemu_next_deadline(void)
1182 int64_t delta;
1184 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1185 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1186 qemu_get_clock(vm_clock);
1187 } else {
1188 /* To avoid problems with overflow limit this to 2^32. */
1189 delta = INT32_MAX;
1192 if (delta < 0)
1193 delta = 0;
1195 return delta;
1198 #if defined(__linux__) || defined(_WIN32)
1199 static uint64_t qemu_next_deadline_dyntick(void)
1201 int64_t delta;
1202 int64_t rtdelta;
1204 if (use_icount)
1205 delta = INT32_MAX;
1206 else
1207 delta = (qemu_next_deadline() + 999) / 1000;
1209 if (active_timers[QEMU_TIMER_REALTIME]) {
1210 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1211 qemu_get_clock(rt_clock))*1000;
1212 if (rtdelta < delta)
1213 delta = rtdelta;
1216 if (delta < MIN_TIMER_REARM_US)
1217 delta = MIN_TIMER_REARM_US;
1219 return delta;
1221 #endif
1223 #ifndef _WIN32
1225 /* Sets a specific flag */
1226 static int fcntl_setfl(int fd, int flag)
1228 int flags;
1230 flags = fcntl(fd, F_GETFL);
1231 if (flags == -1)
1232 return -errno;
1234 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1235 return -errno;
1237 return 0;
1240 #if defined(__linux__)
1242 #define RTC_FREQ 1024
1244 static void enable_sigio_timer(int fd)
1246 struct sigaction act;
1248 /* timer signal */
1249 sigfillset(&act.sa_mask);
1250 act.sa_flags = 0;
1251 act.sa_handler = host_alarm_handler;
1253 sigaction(SIGIO, &act, NULL);
1254 fcntl_setfl(fd, O_ASYNC);
1255 fcntl(fd, F_SETOWN, getpid());
1258 static int hpet_start_timer(struct qemu_alarm_timer *t)
1260 struct hpet_info info;
1261 int r, fd;
1263 fd = open("/dev/hpet", O_RDONLY);
1264 if (fd < 0)
1265 return -1;
1267 /* Set frequency */
1268 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1269 if (r < 0) {
1270 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1271 "error, but for better emulation accuracy type:\n"
1272 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1273 goto fail;
1276 /* Check capabilities */
1277 r = ioctl(fd, HPET_INFO, &info);
1278 if (r < 0)
1279 goto fail;
1281 /* Enable periodic mode */
1282 r = ioctl(fd, HPET_EPI, 0);
1283 if (info.hi_flags && (r < 0))
1284 goto fail;
1286 /* Enable interrupt */
1287 r = ioctl(fd, HPET_IE_ON, 0);
1288 if (r < 0)
1289 goto fail;
1291 enable_sigio_timer(fd);
1292 t->priv = (void *)(long)fd;
1294 return 0;
1295 fail:
1296 close(fd);
1297 return -1;
1300 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1302 int fd = (long)t->priv;
1304 close(fd);
1307 static int rtc_start_timer(struct qemu_alarm_timer *t)
1309 int rtc_fd;
1310 unsigned long current_rtc_freq = 0;
1312 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1313 if (rtc_fd < 0)
1314 return -1;
1315 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1316 if (current_rtc_freq != RTC_FREQ &&
1317 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1318 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1319 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1320 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1321 goto fail;
1323 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1324 fail:
1325 close(rtc_fd);
1326 return -1;
1329 enable_sigio_timer(rtc_fd);
1331 t->priv = (void *)(long)rtc_fd;
1333 return 0;
1336 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1338 int rtc_fd = (long)t->priv;
1340 close(rtc_fd);
1343 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1345 struct sigevent ev;
1346 timer_t host_timer;
1347 struct sigaction act;
1349 sigfillset(&act.sa_mask);
1350 act.sa_flags = 0;
1351 act.sa_handler = host_alarm_handler;
1353 sigaction(SIGALRM, &act, NULL);
1356 * Initialize ev struct to 0 to avoid valgrind complaining
1357 * about uninitialized data in timer_create call
1359 memset(&ev, 0, sizeof(ev));
1360 ev.sigev_value.sival_int = 0;
1361 ev.sigev_notify = SIGEV_SIGNAL;
1362 ev.sigev_signo = SIGALRM;
1364 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1365 perror("timer_create");
1367 /* disable dynticks */
1368 fprintf(stderr, "Dynamic Ticks disabled\n");
1370 return -1;
1373 t->priv = (void *)(long)host_timer;
1375 return 0;
1378 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1380 timer_t host_timer = (timer_t)(long)t->priv;
1382 timer_delete(host_timer);
1385 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1387 timer_t host_timer = (timer_t)(long)t->priv;
1388 struct itimerspec timeout;
1389 int64_t nearest_delta_us = INT64_MAX;
1390 int64_t current_us;
1392 if (!active_timers[QEMU_TIMER_REALTIME] &&
1393 !active_timers[QEMU_TIMER_VIRTUAL])
1394 return;
1396 nearest_delta_us = qemu_next_deadline_dyntick();
1398 /* check whether a timer is already running */
1399 if (timer_gettime(host_timer, &timeout)) {
1400 perror("gettime");
1401 fprintf(stderr, "Internal timer error: aborting\n");
1402 exit(1);
1404 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1405 if (current_us && current_us <= nearest_delta_us)
1406 return;
1408 timeout.it_interval.tv_sec = 0;
1409 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1410 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1411 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1412 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1413 perror("settime");
1414 fprintf(stderr, "Internal timer error: aborting\n");
1415 exit(1);
1419 #endif /* defined(__linux__) */
1421 static int unix_start_timer(struct qemu_alarm_timer *t)
1423 struct sigaction act;
1424 struct itimerval itv;
1425 int err;
1427 /* timer signal */
1428 sigfillset(&act.sa_mask);
1429 act.sa_flags = 0;
1430 act.sa_handler = host_alarm_handler;
1432 sigaction(SIGALRM, &act, NULL);
1434 itv.it_interval.tv_sec = 0;
1435 /* for i386 kernel 2.6 to get 1 ms */
1436 itv.it_interval.tv_usec = 999;
1437 itv.it_value.tv_sec = 0;
1438 itv.it_value.tv_usec = 10 * 1000;
1440 err = setitimer(ITIMER_REAL, &itv, NULL);
1441 if (err)
1442 return -1;
1444 return 0;
1447 static void unix_stop_timer(struct qemu_alarm_timer *t)
1449 struct itimerval itv;
1451 memset(&itv, 0, sizeof(itv));
1452 setitimer(ITIMER_REAL, &itv, NULL);
1455 #endif /* !defined(_WIN32) */
1458 #ifdef _WIN32
1460 static int win32_start_timer(struct qemu_alarm_timer *t)
1462 TIMECAPS tc;
1463 struct qemu_alarm_win32 *data = t->priv;
1464 UINT flags;
1466 memset(&tc, 0, sizeof(tc));
1467 timeGetDevCaps(&tc, sizeof(tc));
1469 if (data->period < tc.wPeriodMin)
1470 data->period = tc.wPeriodMin;
1472 timeBeginPeriod(data->period);
1474 flags = TIME_CALLBACK_FUNCTION;
1475 if (alarm_has_dynticks(t))
1476 flags |= TIME_ONESHOT;
1477 else
1478 flags |= TIME_PERIODIC;
1480 data->timerId = timeSetEvent(1, // interval (ms)
1481 data->period, // resolution
1482 host_alarm_handler, // function
1483 (DWORD)t, // parameter
1484 flags);
1486 if (!data->timerId) {
1487 perror("Failed to initialize win32 alarm timer");
1488 timeEndPeriod(data->period);
1489 return -1;
1492 return 0;
1495 static void win32_stop_timer(struct qemu_alarm_timer *t)
1497 struct qemu_alarm_win32 *data = t->priv;
1499 timeKillEvent(data->timerId);
1500 timeEndPeriod(data->period);
1503 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1505 struct qemu_alarm_win32 *data = t->priv;
1506 uint64_t nearest_delta_us;
1508 if (!active_timers[QEMU_TIMER_REALTIME] &&
1509 !active_timers[QEMU_TIMER_VIRTUAL])
1510 return;
1512 nearest_delta_us = qemu_next_deadline_dyntick();
1513 nearest_delta_us /= 1000;
1515 timeKillEvent(data->timerId);
1517 data->timerId = timeSetEvent(1,
1518 data->period,
1519 host_alarm_handler,
1520 (DWORD)t,
1521 TIME_ONESHOT | TIME_PERIODIC);
1523 if (!data->timerId) {
1524 perror("Failed to re-arm win32 alarm timer");
1526 timeEndPeriod(data->period);
1527 exit(1);
1531 #endif /* _WIN32 */
1533 static int init_timer_alarm(void)
1535 struct qemu_alarm_timer *t = NULL;
1536 int i, err = -1;
1538 for (i = 0; alarm_timers[i].name; i++) {
1539 t = &alarm_timers[i];
1541 err = t->start(t);
1542 if (!err)
1543 break;
1546 if (err) {
1547 err = -ENOENT;
1548 goto fail;
1551 alarm_timer = t;
1553 return 0;
1555 fail:
1556 return err;
1559 static void quit_timers(void)
1561 alarm_timer->stop(alarm_timer);
1562 alarm_timer = NULL;
1565 /***********************************************************/
1566 /* host time/date access */
1567 void qemu_get_timedate(struct tm *tm, int offset)
1569 time_t ti;
1570 struct tm *ret;
1572 time(&ti);
1573 ti += offset;
1574 if (rtc_date_offset == -1) {
1575 if (rtc_utc)
1576 ret = gmtime(&ti);
1577 else
1578 ret = localtime(&ti);
1579 } else {
1580 ti -= rtc_date_offset;
1581 ret = gmtime(&ti);
1584 memcpy(tm, ret, sizeof(struct tm));
1587 int qemu_timedate_diff(struct tm *tm)
1589 time_t seconds;
1591 if (rtc_date_offset == -1)
1592 if (rtc_utc)
1593 seconds = mktimegm(tm);
1594 else
1595 seconds = mktime(tm);
1596 else
1597 seconds = mktimegm(tm) + rtc_date_offset;
1599 return seconds - time(NULL);
1602 #ifdef _WIN32
1603 static void socket_cleanup(void)
1605 WSACleanup();
1608 static int socket_init(void)
1610 WSADATA Data;
1611 int ret, err;
1613 ret = WSAStartup(MAKEWORD(2,2), &Data);
1614 if (ret != 0) {
1615 err = WSAGetLastError();
1616 fprintf(stderr, "WSAStartup: %d\n", err);
1617 return -1;
1619 atexit(socket_cleanup);
1620 return 0;
1622 #endif
1624 int get_next_param_value(char *buf, int buf_size,
1625 const char *tag, const char **pstr)
1627 const char *p;
1628 char option[128];
1630 p = *pstr;
1631 for(;;) {
1632 p = get_opt_name(option, sizeof(option), p, '=');
1633 if (*p != '=')
1634 break;
1635 p++;
1636 if (!strcmp(tag, option)) {
1637 *pstr = get_opt_value(buf, buf_size, p);
1638 if (**pstr == ',') {
1639 (*pstr)++;
1641 return strlen(buf);
1642 } else {
1643 p = get_opt_value(NULL, 0, p);
1645 if (*p != ',')
1646 break;
1647 p++;
1649 return 0;
1652 int get_param_value(char *buf, int buf_size,
1653 const char *tag, const char *str)
1655 return get_next_param_value(buf, buf_size, tag, &str);
1658 int check_params(char *buf, int buf_size,
1659 const char * const *params, const char *str)
1661 const char *p;
1662 int i;
1664 p = str;
1665 while (*p != '\0') {
1666 p = get_opt_name(buf, buf_size, p, '=');
1667 if (*p != '=') {
1668 return -1;
1670 p++;
1671 for (i = 0; params[i] != NULL; i++) {
1672 if (!strcmp(params[i], buf)) {
1673 break;
1676 if (params[i] == NULL) {
1677 return -1;
1679 p = get_opt_value(NULL, 0, p);
1680 if (*p != ',') {
1681 break;
1683 p++;
1685 return 0;
1688 /***********************************************************/
1689 /* Bluetooth support */
1690 static int nb_hcis;
1691 static int cur_hci;
1692 static struct HCIInfo *hci_table[MAX_NICS];
1694 static struct bt_vlan_s {
1695 struct bt_scatternet_s net;
1696 int id;
1697 struct bt_vlan_s *next;
1698 } *first_bt_vlan;
1700 /* find or alloc a new bluetooth "VLAN" */
1701 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1703 struct bt_vlan_s **pvlan, *vlan;
1704 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1705 if (vlan->id == id)
1706 return &vlan->net;
1708 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1709 vlan->id = id;
1710 pvlan = &first_bt_vlan;
1711 while (*pvlan != NULL)
1712 pvlan = &(*pvlan)->next;
1713 *pvlan = vlan;
1714 return &vlan->net;
1717 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1721 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1723 return -ENOTSUP;
1726 static struct HCIInfo null_hci = {
1727 .cmd_send = null_hci_send,
1728 .sco_send = null_hci_send,
1729 .acl_send = null_hci_send,
1730 .bdaddr_set = null_hci_addr_set,
1733 struct HCIInfo *qemu_next_hci(void)
1735 if (cur_hci == nb_hcis)
1736 return &null_hci;
1738 return hci_table[cur_hci++];
1741 static struct HCIInfo *hci_init(const char *str)
1743 char *endp;
1744 struct bt_scatternet_s *vlan = 0;
1746 if (!strcmp(str, "null"))
1747 /* null */
1748 return &null_hci;
1749 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1750 /* host[:hciN] */
1751 return bt_host_hci(str[4] ? str + 5 : "hci0");
1752 else if (!strncmp(str, "hci", 3)) {
1753 /* hci[,vlan=n] */
1754 if (str[3]) {
1755 if (!strncmp(str + 3, ",vlan=", 6)) {
1756 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1757 if (*endp)
1758 vlan = 0;
1760 } else
1761 vlan = qemu_find_bt_vlan(0);
1762 if (vlan)
1763 return bt_new_hci(vlan);
1766 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1768 return 0;
1771 static int bt_hci_parse(const char *str)
1773 struct HCIInfo *hci;
1774 bdaddr_t bdaddr;
1776 if (nb_hcis >= MAX_NICS) {
1777 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1778 return -1;
1781 hci = hci_init(str);
1782 if (!hci)
1783 return -1;
1785 bdaddr.b[0] = 0x52;
1786 bdaddr.b[1] = 0x54;
1787 bdaddr.b[2] = 0x00;
1788 bdaddr.b[3] = 0x12;
1789 bdaddr.b[4] = 0x34;
1790 bdaddr.b[5] = 0x56 + nb_hcis;
1791 hci->bdaddr_set(hci, bdaddr.b);
1793 hci_table[nb_hcis++] = hci;
1795 return 0;
1798 static void bt_vhci_add(int vlan_id)
1800 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1802 if (!vlan->slave)
1803 fprintf(stderr, "qemu: warning: adding a VHCI to "
1804 "an empty scatternet %i\n", vlan_id);
1806 bt_vhci_init(bt_new_hci(vlan));
1809 static struct bt_device_s *bt_device_add(const char *opt)
1811 struct bt_scatternet_s *vlan;
1812 int vlan_id = 0;
1813 char *endp = strstr(opt, ",vlan=");
1814 int len = (endp ? endp - opt : strlen(opt)) + 1;
1815 char devname[10];
1817 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1819 if (endp) {
1820 vlan_id = strtol(endp + 6, &endp, 0);
1821 if (*endp) {
1822 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1823 return 0;
1827 vlan = qemu_find_bt_vlan(vlan_id);
1829 if (!vlan->slave)
1830 fprintf(stderr, "qemu: warning: adding a slave device to "
1831 "an empty scatternet %i\n", vlan_id);
1833 if (!strcmp(devname, "keyboard"))
1834 return bt_keyboard_init(vlan);
1836 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1837 return 0;
1840 static int bt_parse(const char *opt)
1842 const char *endp, *p;
1843 int vlan;
1845 if (strstart(opt, "hci", &endp)) {
1846 if (!*endp || *endp == ',') {
1847 if (*endp)
1848 if (!strstart(endp, ",vlan=", 0))
1849 opt = endp + 1;
1851 return bt_hci_parse(opt);
1853 } else if (strstart(opt, "vhci", &endp)) {
1854 if (!*endp || *endp == ',') {
1855 if (*endp) {
1856 if (strstart(endp, ",vlan=", &p)) {
1857 vlan = strtol(p, (char **) &endp, 0);
1858 if (*endp) {
1859 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1860 return 1;
1862 } else {
1863 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1864 return 1;
1866 } else
1867 vlan = 0;
1869 bt_vhci_add(vlan);
1870 return 0;
1872 } else if (strstart(opt, "device:", &endp))
1873 return !bt_device_add(endp);
1875 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1876 return 1;
1879 /***********************************************************/
1880 /* QEMU Block devices */
1882 #define HD_ALIAS "index=%d,media=disk"
1883 #define CDROM_ALIAS "index=2,media=cdrom"
1884 #define FD_ALIAS "index=%d,if=floppy"
1885 #define PFLASH_ALIAS "if=pflash"
1886 #define MTD_ALIAS "if=mtd"
1887 #define SD_ALIAS "index=0,if=sd"
1889 static int drive_opt_get_free_idx(void)
1891 int index;
1893 for (index = 0; index < MAX_DRIVES; index++)
1894 if (!drives_opt[index].used) {
1895 drives_opt[index].used = 1;
1896 return index;
1899 return -1;
1902 static int drive_get_free_idx(void)
1904 int index;
1906 for (index = 0; index < MAX_DRIVES; index++)
1907 if (!drives_table[index].used) {
1908 drives_table[index].used = 1;
1909 return index;
1912 return -1;
1915 int drive_add(const char *file, const char *fmt, ...)
1917 va_list ap;
1918 int index = drive_opt_get_free_idx();
1920 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
1921 fprintf(stderr, "qemu: too many drives\n");
1922 return -1;
1925 drives_opt[index].file = file;
1926 va_start(ap, fmt);
1927 vsnprintf(drives_opt[index].opt,
1928 sizeof(drives_opt[0].opt), fmt, ap);
1929 va_end(ap);
1931 nb_drives_opt++;
1932 return index;
1935 void drive_remove(int index)
1937 drives_opt[index].used = 0;
1938 nb_drives_opt--;
1941 int drive_get_index(BlockInterfaceType type, int bus, int unit)
1943 int index;
1945 /* seek interface, bus and unit */
1947 for (index = 0; index < MAX_DRIVES; index++)
1948 if (drives_table[index].type == type &&
1949 drives_table[index].bus == bus &&
1950 drives_table[index].unit == unit &&
1951 drives_table[index].used)
1952 return index;
1954 return -1;
1957 int drive_get_max_bus(BlockInterfaceType type)
1959 int max_bus;
1960 int index;
1962 max_bus = -1;
1963 for (index = 0; index < nb_drives; index++) {
1964 if(drives_table[index].type == type &&
1965 drives_table[index].bus > max_bus)
1966 max_bus = drives_table[index].bus;
1968 return max_bus;
1971 const char *drive_get_serial(BlockDriverState *bdrv)
1973 int index;
1975 for (index = 0; index < nb_drives; index++)
1976 if (drives_table[index].bdrv == bdrv)
1977 return drives_table[index].serial;
1979 return "\0";
1982 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1984 int index;
1986 for (index = 0; index < nb_drives; index++)
1987 if (drives_table[index].bdrv == bdrv)
1988 return drives_table[index].onerror;
1990 return BLOCK_ERR_STOP_ENOSPC;
1993 static void bdrv_format_print(void *opaque, const char *name)
1995 fprintf(stderr, " %s", name);
1998 void drive_uninit(BlockDriverState *bdrv)
2000 int i;
2002 for (i = 0; i < MAX_DRIVES; i++)
2003 if (drives_table[i].bdrv == bdrv) {
2004 drives_table[i].bdrv = NULL;
2005 drives_table[i].used = 0;
2006 drive_remove(drives_table[i].drive_opt_idx);
2007 nb_drives--;
2008 break;
2012 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2014 char buf[128];
2015 char file[1024];
2016 char devname[128];
2017 char serial[21];
2018 const char *mediastr = "";
2019 BlockInterfaceType type;
2020 enum { MEDIA_DISK, MEDIA_CDROM } media;
2021 int bus_id, unit_id;
2022 int cyls, heads, secs, translation;
2023 BlockDriverState *bdrv;
2024 BlockDriver *drv = NULL;
2025 QEMUMachine *machine = opaque;
2026 int max_devs;
2027 int index;
2028 int cache;
2029 int bdrv_flags, onerror;
2030 const char *devaddr;
2031 int drives_table_idx;
2032 char *str = arg->opt;
2033 static const char * const params[] = { "bus", "unit", "if", "index",
2034 "cyls", "heads", "secs", "trans",
2035 "media", "snapshot", "file",
2036 "cache", "format", "serial",
2037 "werror", "addr",
2038 "boot",
2039 NULL };
2041 if (check_params(buf, sizeof(buf), params, str) < 0) {
2042 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2043 buf, str);
2044 return -1;
2047 file[0] = 0;
2048 cyls = heads = secs = 0;
2049 bus_id = 0;
2050 unit_id = -1;
2051 translation = BIOS_ATA_TRANSLATION_AUTO;
2052 index = -1;
2053 cache = 1;
2055 if (machine->use_scsi) {
2056 type = IF_SCSI;
2057 max_devs = MAX_SCSI_DEVS;
2058 pstrcpy(devname, sizeof(devname), "scsi");
2059 } else {
2060 type = IF_IDE;
2061 max_devs = MAX_IDE_DEVS;
2062 pstrcpy(devname, sizeof(devname), "ide");
2064 media = MEDIA_DISK;
2066 /* extract parameters */
2068 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2069 bus_id = strtol(buf, NULL, 0);
2070 if (bus_id < 0) {
2071 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2072 return -1;
2076 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2077 unit_id = strtol(buf, NULL, 0);
2078 if (unit_id < 0) {
2079 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2080 return -1;
2084 if (get_param_value(buf, sizeof(buf), "if", str)) {
2085 pstrcpy(devname, sizeof(devname), buf);
2086 if (!strcmp(buf, "ide")) {
2087 type = IF_IDE;
2088 max_devs = MAX_IDE_DEVS;
2089 } else if (!strcmp(buf, "scsi")) {
2090 type = IF_SCSI;
2091 max_devs = MAX_SCSI_DEVS;
2092 } else if (!strcmp(buf, "floppy")) {
2093 type = IF_FLOPPY;
2094 max_devs = 0;
2095 } else if (!strcmp(buf, "pflash")) {
2096 type = IF_PFLASH;
2097 max_devs = 0;
2098 } else if (!strcmp(buf, "mtd")) {
2099 type = IF_MTD;
2100 max_devs = 0;
2101 } else if (!strcmp(buf, "sd")) {
2102 type = IF_SD;
2103 max_devs = 0;
2104 } else if (!strcmp(buf, "virtio")) {
2105 type = IF_VIRTIO;
2106 max_devs = 0;
2107 } else if (!strcmp(buf, "xen")) {
2108 type = IF_XEN;
2109 max_devs = 0;
2110 } else {
2111 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2112 return -1;
2116 if (get_param_value(buf, sizeof(buf), "index", str)) {
2117 index = strtol(buf, NULL, 0);
2118 if (index < 0) {
2119 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2120 return -1;
2124 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2125 cyls = strtol(buf, NULL, 0);
2128 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2129 heads = strtol(buf, NULL, 0);
2132 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2133 secs = strtol(buf, NULL, 0);
2136 if (cyls || heads || secs) {
2137 if (cyls < 1 || cyls > 16383) {
2138 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2139 return -1;
2141 if (heads < 1 || heads > 16) {
2142 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2143 return -1;
2145 if (secs < 1 || secs > 63) {
2146 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2147 return -1;
2151 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2152 if (!cyls) {
2153 fprintf(stderr,
2154 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2155 str);
2156 return -1;
2158 if (!strcmp(buf, "none"))
2159 translation = BIOS_ATA_TRANSLATION_NONE;
2160 else if (!strcmp(buf, "lba"))
2161 translation = BIOS_ATA_TRANSLATION_LBA;
2162 else if (!strcmp(buf, "auto"))
2163 translation = BIOS_ATA_TRANSLATION_AUTO;
2164 else {
2165 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2166 return -1;
2170 if (get_param_value(buf, sizeof(buf), "media", str)) {
2171 if (!strcmp(buf, "disk")) {
2172 media = MEDIA_DISK;
2173 } else if (!strcmp(buf, "cdrom")) {
2174 if (cyls || secs || heads) {
2175 fprintf(stderr,
2176 "qemu: '%s' invalid physical CHS format\n", str);
2177 return -1;
2179 media = MEDIA_CDROM;
2180 } else {
2181 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2182 return -1;
2186 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2187 if (!strcmp(buf, "on"))
2188 snapshot = 1;
2189 else if (!strcmp(buf, "off"))
2190 snapshot = 0;
2191 else {
2192 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2193 return -1;
2197 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2198 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2199 cache = 0;
2200 else if (!strcmp(buf, "writethrough"))
2201 cache = 1;
2202 else if (!strcmp(buf, "writeback"))
2203 cache = 2;
2204 else {
2205 fprintf(stderr, "qemu: invalid cache option\n");
2206 return -1;
2210 if (get_param_value(buf, sizeof(buf), "format", str)) {
2211 if (strcmp(buf, "?") == 0) {
2212 fprintf(stderr, "qemu: Supported formats:");
2213 bdrv_iterate_format(bdrv_format_print, NULL);
2214 fprintf(stderr, "\n");
2215 return -1;
2217 drv = bdrv_find_format(buf);
2218 if (!drv) {
2219 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2220 return -1;
2224 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2225 if (!strcmp(buf, "on")) {
2226 if (extboot_drive != -1) {
2227 fprintf(stderr, "qemu: two bootable drives specified\n");
2228 return -1;
2230 extboot_drive = nb_drives;
2231 } else if (strcmp(buf, "off")) {
2232 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2233 return -1;
2237 if (arg->file == NULL)
2238 get_param_value(file, sizeof(file), "file", str);
2239 else
2240 pstrcpy(file, sizeof(file), arg->file);
2242 if (!get_param_value(serial, sizeof(serial), "serial", str))
2243 memset(serial, 0, sizeof(serial));
2245 onerror = BLOCK_ERR_STOP_ENOSPC;
2246 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2247 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2248 fprintf(stderr, "werror is no supported by this format\n");
2249 return -1;
2251 if (!strcmp(buf, "ignore"))
2252 onerror = BLOCK_ERR_IGNORE;
2253 else if (!strcmp(buf, "enospc"))
2254 onerror = BLOCK_ERR_STOP_ENOSPC;
2255 else if (!strcmp(buf, "stop"))
2256 onerror = BLOCK_ERR_STOP_ANY;
2257 else if (!strcmp(buf, "report"))
2258 onerror = BLOCK_ERR_REPORT;
2259 else {
2260 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2261 return -1;
2265 devaddr = NULL;
2266 if (get_param_value(buf, sizeof(buf), "addr", str)) {
2267 if (type != IF_VIRTIO) {
2268 fprintf(stderr, "addr is not supported by in '%s'\n", str);
2269 return -1;
2271 devaddr = strdup(buf);
2274 /* compute bus and unit according index */
2276 if (index != -1) {
2277 if (bus_id != 0 || unit_id != -1) {
2278 fprintf(stderr,
2279 "qemu: '%s' index cannot be used with bus and unit\n", str);
2280 return -1;
2282 if (max_devs == 0)
2284 unit_id = index;
2285 bus_id = 0;
2286 } else {
2287 unit_id = index % max_devs;
2288 bus_id = index / max_devs;
2292 /* if user doesn't specify a unit_id,
2293 * try to find the first free
2296 if (unit_id == -1) {
2297 unit_id = 0;
2298 while (drive_get_index(type, bus_id, unit_id) != -1) {
2299 unit_id++;
2300 if (max_devs && unit_id >= max_devs) {
2301 unit_id -= max_devs;
2302 bus_id++;
2307 /* check unit id */
2309 if (max_devs && unit_id >= max_devs) {
2310 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2311 str, unit_id, max_devs - 1);
2312 return -1;
2316 * ignore multiple definitions
2319 if (drive_get_index(type, bus_id, unit_id) != -1)
2320 return -2;
2322 /* init */
2324 if (type == IF_IDE || type == IF_SCSI)
2325 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2326 if (max_devs)
2327 snprintf(buf, sizeof(buf), "%s%i%s%i",
2328 devname, bus_id, mediastr, unit_id);
2329 else
2330 snprintf(buf, sizeof(buf), "%s%s%i",
2331 devname, mediastr, unit_id);
2332 bdrv = bdrv_new(buf);
2333 drives_table_idx = drive_get_free_idx();
2334 drives_table[drives_table_idx].bdrv = bdrv;
2335 drives_table[drives_table_idx].devaddr = devaddr;
2336 drives_table[drives_table_idx].type = type;
2337 drives_table[drives_table_idx].bus = bus_id;
2338 drives_table[drives_table_idx].unit = unit_id;
2339 drives_table[drives_table_idx].onerror = onerror;
2340 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2341 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2342 nb_drives++;
2344 switch(type) {
2345 case IF_IDE:
2346 case IF_SCSI:
2347 case IF_XEN:
2348 switch(media) {
2349 case MEDIA_DISK:
2350 if (cyls != 0) {
2351 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2352 bdrv_set_translation_hint(bdrv, translation);
2354 break;
2355 case MEDIA_CDROM:
2356 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2357 break;
2359 break;
2360 case IF_SD:
2361 /* FIXME: This isn't really a floppy, but it's a reasonable
2362 approximation. */
2363 case IF_FLOPPY:
2364 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2365 break;
2366 case IF_PFLASH:
2367 case IF_MTD:
2368 case IF_VIRTIO:
2369 break;
2370 case IF_COUNT:
2371 abort();
2373 if (!file[0])
2374 return -2;
2375 bdrv_flags = 0;
2376 if (snapshot) {
2377 bdrv_flags |= BDRV_O_SNAPSHOT;
2378 cache = 2; /* always use write-back with snapshot */
2380 if (cache == 0) /* no caching */
2381 bdrv_flags |= BDRV_O_NOCACHE;
2382 else if (cache == 2) /* write-back */
2383 bdrv_flags |= BDRV_O_CACHE_WB;
2384 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2385 fprintf(stderr, "qemu: could not open disk image %s\n",
2386 file);
2387 return -1;
2389 if (bdrv_key_required(bdrv))
2390 autostart = 0;
2391 return drives_table_idx;
2394 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2396 boot_set_handler = func;
2397 boot_set_opaque = opaque;
2400 int qemu_boot_set(const char *boot_devices)
2402 if (!boot_set_handler) {
2403 return -EINVAL;
2405 return boot_set_handler(boot_set_opaque, boot_devices);
2408 static int parse_bootdevices(char *devices)
2410 /* We just do some generic consistency checks */
2411 const char *p;
2412 int bitmap = 0;
2414 for (p = devices; *p != '\0'; p++) {
2415 /* Allowed boot devices are:
2416 * a-b: floppy disk drives
2417 * c-f: IDE disk drives
2418 * g-m: machine implementation dependant drives
2419 * n-p: network devices
2420 * It's up to each machine implementation to check if the given boot
2421 * devices match the actual hardware implementation and firmware
2422 * features.
2424 if (*p < 'a' || *p > 'p') {
2425 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2426 exit(1);
2428 if (bitmap & (1 << (*p - 'a'))) {
2429 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2430 exit(1);
2432 bitmap |= 1 << (*p - 'a');
2434 return bitmap;
2437 static void restore_boot_devices(void *opaque)
2439 char *standard_boot_devices = opaque;
2441 qemu_boot_set(standard_boot_devices);
2443 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2444 qemu_free(standard_boot_devices);
2447 static void numa_add(const char *optarg)
2449 char option[128];
2450 char *endptr;
2451 unsigned long long value, endvalue;
2452 int nodenr;
2454 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2455 if (!strcmp(option, "node")) {
2456 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2457 nodenr = nb_numa_nodes;
2458 } else {
2459 nodenr = strtoull(option, NULL, 10);
2462 if (get_param_value(option, 128, "mem", optarg) == 0) {
2463 node_mem[nodenr] = 0;
2464 } else {
2465 value = strtoull(option, &endptr, 0);
2466 switch (*endptr) {
2467 case 0: case 'M': case 'm':
2468 value <<= 20;
2469 break;
2470 case 'G': case 'g':
2471 value <<= 30;
2472 break;
2474 node_mem[nodenr] = value;
2476 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2477 node_cpumask[nodenr] = 0;
2478 } else {
2479 value = strtoull(option, &endptr, 10);
2480 if (value >= 64) {
2481 value = 63;
2482 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2483 } else {
2484 if (*endptr == '-') {
2485 endvalue = strtoull(endptr+1, &endptr, 10);
2486 if (endvalue >= 63) {
2487 endvalue = 62;
2488 fprintf(stderr,
2489 "only 63 CPUs in NUMA mode supported.\n");
2491 value = (1 << (endvalue + 1)) - (1 << value);
2492 } else {
2493 value = 1 << value;
2496 node_cpumask[nodenr] = value;
2498 nb_numa_nodes++;
2500 return;
2503 /***********************************************************/
2504 /* USB devices */
2506 static USBPort *used_usb_ports;
2507 static USBPort *free_usb_ports;
2509 /* ??? Maybe change this to register a hub to keep track of the topology. */
2510 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2511 usb_attachfn attach)
2513 port->opaque = opaque;
2514 port->index = index;
2515 port->attach = attach;
2516 port->next = free_usb_ports;
2517 free_usb_ports = port;
2520 int usb_device_add_dev(USBDevice *dev)
2522 USBPort *port;
2524 /* Find a USB port to add the device to. */
2525 port = free_usb_ports;
2526 if (!port->next) {
2527 USBDevice *hub;
2529 /* Create a new hub and chain it on. */
2530 free_usb_ports = NULL;
2531 port->next = used_usb_ports;
2532 used_usb_ports = port;
2534 hub = usb_hub_init(VM_USB_HUB_SIZE);
2535 usb_attach(port, hub);
2536 port = free_usb_ports;
2539 free_usb_ports = port->next;
2540 port->next = used_usb_ports;
2541 used_usb_ports = port;
2542 usb_attach(port, dev);
2543 return 0;
2546 static void usb_msd_password_cb(void *opaque, int err)
2548 USBDevice *dev = opaque;
2550 if (!err)
2551 usb_device_add_dev(dev);
2552 else
2553 dev->handle_destroy(dev);
2556 static int usb_device_add(const char *devname, int is_hotplug)
2558 const char *p;
2559 USBDevice *dev;
2561 if (!free_usb_ports)
2562 return -1;
2564 if (strstart(devname, "host:", &p)) {
2565 dev = usb_host_device_open(p);
2566 } else if (!strcmp(devname, "mouse")) {
2567 dev = usb_mouse_init();
2568 } else if (!strcmp(devname, "tablet")) {
2569 dev = usb_tablet_init();
2570 } else if (!strcmp(devname, "keyboard")) {
2571 dev = usb_keyboard_init();
2572 } else if (strstart(devname, "disk:", &p)) {
2573 BlockDriverState *bs;
2575 dev = usb_msd_init(p);
2576 if (!dev)
2577 return -1;
2578 bs = usb_msd_get_bdrv(dev);
2579 if (bdrv_key_required(bs)) {
2580 autostart = 0;
2581 if (is_hotplug) {
2582 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2583 dev);
2584 return 0;
2587 } else if (!strcmp(devname, "wacom-tablet")) {
2588 dev = usb_wacom_init();
2589 } else if (strstart(devname, "serial:", &p)) {
2590 dev = usb_serial_init(p);
2591 #ifdef CONFIG_BRLAPI
2592 } else if (!strcmp(devname, "braille")) {
2593 dev = usb_baum_init();
2594 #endif
2595 } else if (strstart(devname, "net:", &p)) {
2596 int nic = nb_nics;
2598 if (net_client_init(NULL, "nic", p) < 0)
2599 return -1;
2600 nd_table[nic].model = "usb";
2601 dev = usb_net_init(&nd_table[nic]);
2602 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2603 dev = usb_bt_init(devname[2] ? hci_init(p) :
2604 bt_new_hci(qemu_find_bt_vlan(0)));
2605 } else {
2606 return -1;
2608 if (!dev)
2609 return -1;
2611 return usb_device_add_dev(dev);
2614 int usb_device_del_addr(int bus_num, int addr)
2616 USBPort *port;
2617 USBPort **lastp;
2618 USBDevice *dev;
2620 if (!used_usb_ports)
2621 return -1;
2623 if (bus_num != 0)
2624 return -1;
2626 lastp = &used_usb_ports;
2627 port = used_usb_ports;
2628 while (port && port->dev->addr != addr) {
2629 lastp = &port->next;
2630 port = port->next;
2633 if (!port)
2634 return -1;
2636 dev = port->dev;
2637 *lastp = port->next;
2638 usb_attach(port, NULL);
2639 dev->handle_destroy(dev);
2640 port->next = free_usb_ports;
2641 free_usb_ports = port;
2642 return 0;
2645 static int usb_device_del(const char *devname)
2647 int bus_num, addr;
2648 const char *p;
2650 if (strstart(devname, "host:", &p))
2651 return usb_host_device_close(p);
2653 if (!used_usb_ports)
2654 return -1;
2656 p = strchr(devname, '.');
2657 if (!p)
2658 return -1;
2659 bus_num = strtoul(devname, NULL, 0);
2660 addr = strtoul(p + 1, NULL, 0);
2662 return usb_device_del_addr(bus_num, addr);
2665 void do_usb_add(Monitor *mon, const char *devname)
2667 usb_device_add(devname, 1);
2670 void do_usb_del(Monitor *mon, const char *devname)
2672 usb_device_del(devname);
2675 void usb_info(Monitor *mon)
2677 USBDevice *dev;
2678 USBPort *port;
2679 const char *speed_str;
2681 if (!usb_enabled) {
2682 monitor_printf(mon, "USB support not enabled\n");
2683 return;
2686 for (port = used_usb_ports; port; port = port->next) {
2687 dev = port->dev;
2688 if (!dev)
2689 continue;
2690 switch(dev->speed) {
2691 case USB_SPEED_LOW:
2692 speed_str = "1.5";
2693 break;
2694 case USB_SPEED_FULL:
2695 speed_str = "12";
2696 break;
2697 case USB_SPEED_HIGH:
2698 speed_str = "480";
2699 break;
2700 default:
2701 speed_str = "?";
2702 break;
2704 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2705 0, dev->addr, speed_str, dev->devname);
2709 /***********************************************************/
2710 /* PCMCIA/Cardbus */
2712 static struct pcmcia_socket_entry_s {
2713 PCMCIASocket *socket;
2714 struct pcmcia_socket_entry_s *next;
2715 } *pcmcia_sockets = 0;
2717 void pcmcia_socket_register(PCMCIASocket *socket)
2719 struct pcmcia_socket_entry_s *entry;
2721 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2722 entry->socket = socket;
2723 entry->next = pcmcia_sockets;
2724 pcmcia_sockets = entry;
2727 void pcmcia_socket_unregister(PCMCIASocket *socket)
2729 struct pcmcia_socket_entry_s *entry, **ptr;
2731 ptr = &pcmcia_sockets;
2732 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2733 if (entry->socket == socket) {
2734 *ptr = entry->next;
2735 qemu_free(entry);
2739 void pcmcia_info(Monitor *mon)
2741 struct pcmcia_socket_entry_s *iter;
2743 if (!pcmcia_sockets)
2744 monitor_printf(mon, "No PCMCIA sockets\n");
2746 for (iter = pcmcia_sockets; iter; iter = iter->next)
2747 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2748 iter->socket->attached ? iter->socket->card_string :
2749 "Empty");
2752 /***********************************************************/
2753 /* register display */
2755 struct DisplayAllocator default_allocator = {
2756 defaultallocator_create_displaysurface,
2757 defaultallocator_resize_displaysurface,
2758 defaultallocator_free_displaysurface
2761 void register_displaystate(DisplayState *ds)
2763 DisplayState **s;
2764 s = &display_state;
2765 while (*s != NULL)
2766 s = &(*s)->next;
2767 ds->next = NULL;
2768 *s = ds;
2771 DisplayState *get_displaystate(void)
2773 return display_state;
2776 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2778 if(ds->allocator == &default_allocator) ds->allocator = da;
2779 return ds->allocator;
2782 /* dumb display */
2784 static void dumb_display_init(void)
2786 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2787 ds->allocator = &default_allocator;
2788 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2789 register_displaystate(ds);
2792 /***********************************************************/
2793 /* I/O handling */
2795 typedef struct IOHandlerRecord {
2796 int fd;
2797 IOCanRWHandler *fd_read_poll;
2798 IOHandler *fd_read;
2799 IOHandler *fd_write;
2800 int deleted;
2801 void *opaque;
2802 /* temporary data */
2803 struct pollfd *ufd;
2804 struct IOHandlerRecord *next;
2805 } IOHandlerRecord;
2807 static IOHandlerRecord *first_io_handler;
2809 /* XXX: fd_read_poll should be suppressed, but an API change is
2810 necessary in the character devices to suppress fd_can_read(). */
2811 int qemu_set_fd_handler2(int fd,
2812 IOCanRWHandler *fd_read_poll,
2813 IOHandler *fd_read,
2814 IOHandler *fd_write,
2815 void *opaque)
2817 IOHandlerRecord **pioh, *ioh;
2819 if (!fd_read && !fd_write) {
2820 pioh = &first_io_handler;
2821 for(;;) {
2822 ioh = *pioh;
2823 if (ioh == NULL)
2824 break;
2825 if (ioh->fd == fd) {
2826 ioh->deleted = 1;
2827 break;
2829 pioh = &ioh->next;
2831 } else {
2832 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2833 if (ioh->fd == fd)
2834 goto found;
2836 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2837 ioh->next = first_io_handler;
2838 first_io_handler = ioh;
2839 found:
2840 ioh->fd = fd;
2841 ioh->fd_read_poll = fd_read_poll;
2842 ioh->fd_read = fd_read;
2843 ioh->fd_write = fd_write;
2844 ioh->opaque = opaque;
2845 ioh->deleted = 0;
2847 qemu_notify_event();
2848 return 0;
2851 int qemu_set_fd_handler(int fd,
2852 IOHandler *fd_read,
2853 IOHandler *fd_write,
2854 void *opaque)
2856 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2859 #ifdef _WIN32
2860 /***********************************************************/
2861 /* Polling handling */
2863 typedef struct PollingEntry {
2864 PollingFunc *func;
2865 void *opaque;
2866 struct PollingEntry *next;
2867 } PollingEntry;
2869 static PollingEntry *first_polling_entry;
2871 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2873 PollingEntry **ppe, *pe;
2874 pe = qemu_mallocz(sizeof(PollingEntry));
2875 pe->func = func;
2876 pe->opaque = opaque;
2877 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2878 *ppe = pe;
2879 return 0;
2882 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2884 PollingEntry **ppe, *pe;
2885 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2886 pe = *ppe;
2887 if (pe->func == func && pe->opaque == opaque) {
2888 *ppe = pe->next;
2889 qemu_free(pe);
2890 break;
2895 /***********************************************************/
2896 /* Wait objects support */
2897 typedef struct WaitObjects {
2898 int num;
2899 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2900 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2901 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2902 } WaitObjects;
2904 static WaitObjects wait_objects = {0};
2906 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2908 WaitObjects *w = &wait_objects;
2910 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2911 return -1;
2912 w->events[w->num] = handle;
2913 w->func[w->num] = func;
2914 w->opaque[w->num] = opaque;
2915 w->num++;
2916 return 0;
2919 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2921 int i, found;
2922 WaitObjects *w = &wait_objects;
2924 found = 0;
2925 for (i = 0; i < w->num; i++) {
2926 if (w->events[i] == handle)
2927 found = 1;
2928 if (found) {
2929 w->events[i] = w->events[i + 1];
2930 w->func[i] = w->func[i + 1];
2931 w->opaque[i] = w->opaque[i + 1];
2934 if (found)
2935 w->num--;
2937 #endif
2939 /***********************************************************/
2940 /* ram save/restore */
2942 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2944 int v;
2946 v = qemu_get_byte(f);
2947 switch(v) {
2948 case 0:
2949 if (qemu_get_buffer(f, buf, len) != len)
2950 return -EIO;
2951 break;
2952 case 1:
2953 v = qemu_get_byte(f);
2954 memset(buf, v, len);
2955 break;
2956 default:
2957 return -EINVAL;
2960 if (qemu_file_has_error(f))
2961 return -EIO;
2963 return 0;
2966 static int ram_load_v1(QEMUFile *f, void *opaque)
2968 int ret;
2969 ram_addr_t i;
2971 if (qemu_get_be32(f) != last_ram_offset)
2972 return -EINVAL;
2973 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2974 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
2975 continue;
2976 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2977 if (ret)
2978 return ret;
2980 return 0;
2983 #define BDRV_HASH_BLOCK_SIZE 1024
2984 #define IOBUF_SIZE 4096
2985 #define RAM_CBLOCK_MAGIC 0xfabe
2987 typedef struct RamDecompressState {
2988 z_stream zstream;
2989 QEMUFile *f;
2990 uint8_t buf[IOBUF_SIZE];
2991 } RamDecompressState;
2993 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2995 int ret;
2996 memset(s, 0, sizeof(*s));
2997 s->f = f;
2998 ret = inflateInit(&s->zstream);
2999 if (ret != Z_OK)
3000 return -1;
3001 return 0;
3004 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3006 int ret, clen;
3008 s->zstream.avail_out = len;
3009 s->zstream.next_out = buf;
3010 while (s->zstream.avail_out > 0) {
3011 if (s->zstream.avail_in == 0) {
3012 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3013 return -1;
3014 clen = qemu_get_be16(s->f);
3015 if (clen > IOBUF_SIZE)
3016 return -1;
3017 qemu_get_buffer(s->f, s->buf, clen);
3018 s->zstream.avail_in = clen;
3019 s->zstream.next_in = s->buf;
3021 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3022 if (ret != Z_OK && ret != Z_STREAM_END) {
3023 return -1;
3026 return 0;
3029 static void ram_decompress_close(RamDecompressState *s)
3031 inflateEnd(&s->zstream);
3034 #define RAM_SAVE_FLAG_FULL 0x01
3035 #define RAM_SAVE_FLAG_COMPRESS 0x02
3036 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3037 #define RAM_SAVE_FLAG_PAGE 0x08
3038 #define RAM_SAVE_FLAG_EOS 0x10
3040 static int is_dup_page(uint8_t *page, uint8_t ch)
3042 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3043 uint32_t *array = (uint32_t *)page;
3044 int i;
3046 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3047 if (array[i] != val)
3048 return 0;
3051 return 1;
3054 static int ram_save_block(QEMUFile *f)
3056 static ram_addr_t current_addr = 0;
3057 ram_addr_t saved_addr = current_addr;
3058 ram_addr_t addr = 0;
3059 int found = 0;
3061 while (addr < last_ram_offset) {
3062 if (kvm_enabled() && current_addr == 0) {
3063 int r;
3064 r = kvm_update_dirty_pages_log();
3065 if (r) {
3066 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3067 qemu_file_set_error(f);
3068 return 0;
3071 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3072 uint8_t *p;
3074 cpu_physical_memory_reset_dirty(current_addr,
3075 current_addr + TARGET_PAGE_SIZE,
3076 MIGRATION_DIRTY_FLAG);
3078 p = qemu_get_ram_ptr(current_addr);
3080 if (is_dup_page(p, *p)) {
3081 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3082 qemu_put_byte(f, *p);
3083 } else {
3084 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3085 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3088 found = 1;
3089 break;
3091 addr += TARGET_PAGE_SIZE;
3092 current_addr = (saved_addr + addr) % last_ram_offset;
3095 return found;
3098 static uint64_t bytes_transferred = 0;
3100 static ram_addr_t ram_save_remaining(void)
3102 ram_addr_t addr;
3103 ram_addr_t count = 0;
3105 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3106 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3107 count++;
3110 return count;
3113 uint64_t ram_bytes_remaining(void)
3115 return ram_save_remaining() * TARGET_PAGE_SIZE;
3118 uint64_t ram_bytes_transferred(void)
3120 return bytes_transferred;
3123 uint64_t ram_bytes_total(void)
3125 return last_ram_offset;
3128 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3130 ram_addr_t addr;
3131 uint64_t bytes_transferred_last;
3132 double bwidth = 0;
3133 uint64_t expected_time = 0;
3135 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3136 qemu_file_set_error(f);
3137 return 0;
3140 if (stage == 1) {
3141 /* Make sure all dirty bits are set */
3142 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3143 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3144 cpu_physical_memory_set_dirty(addr);
3147 /* Enable dirty memory tracking */
3148 cpu_physical_memory_set_dirty_tracking(1);
3150 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3153 bytes_transferred_last = bytes_transferred;
3154 bwidth = get_clock();
3156 while (!qemu_file_rate_limit(f)) {
3157 int ret;
3159 ret = ram_save_block(f);
3160 bytes_transferred += ret * TARGET_PAGE_SIZE;
3161 if (ret == 0) /* no more blocks */
3162 break;
3165 bwidth = get_clock() - bwidth;
3166 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3168 /* if we haven't transferred anything this round, force expected_time to a
3169 * a very high value, but without crashing */
3170 if (bwidth == 0)
3171 bwidth = 0.000001;
3173 /* try transferring iterative blocks of memory */
3175 if (stage == 3) {
3177 /* flush all remaining blocks regardless of rate limiting */
3178 while (ram_save_block(f) != 0) {
3179 bytes_transferred += TARGET_PAGE_SIZE;
3181 cpu_physical_memory_set_dirty_tracking(0);
3184 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3186 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3188 return (stage == 2) && (expected_time <= migrate_max_downtime());
3191 static int ram_load_dead(QEMUFile *f, void *opaque)
3193 RamDecompressState s1, *s = &s1;
3194 uint8_t buf[10];
3195 ram_addr_t i;
3197 if (ram_decompress_open(s, f) < 0)
3198 return -EINVAL;
3199 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3200 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3201 continue;
3202 if (ram_decompress_buf(s, buf, 1) < 0) {
3203 fprintf(stderr, "Error while reading ram block header\n");
3204 goto error;
3206 if (buf[0] == 0) {
3207 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3208 BDRV_HASH_BLOCK_SIZE) < 0) {
3209 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3210 goto error;
3212 } else {
3213 error:
3214 printf("Error block header\n");
3215 return -EINVAL;
3218 ram_decompress_close(s);
3220 return 0;
3223 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3225 ram_addr_t addr;
3226 int flags;
3228 if (version_id == 1)
3229 return ram_load_v1(f, opaque);
3231 if (version_id == 2) {
3232 if (qemu_get_be32(f) != last_ram_offset)
3233 return -EINVAL;
3234 return ram_load_dead(f, opaque);
3237 if (version_id != 3)
3238 return -EINVAL;
3240 do {
3241 addr = qemu_get_be64(f);
3243 flags = addr & ~TARGET_PAGE_MASK;
3244 addr &= TARGET_PAGE_MASK;
3246 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3247 if (addr != last_ram_offset)
3248 return -EINVAL;
3251 if (flags & RAM_SAVE_FLAG_FULL) {
3252 if (ram_load_dead(f, opaque) < 0)
3253 return -EINVAL;
3256 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3257 uint8_t ch = qemu_get_byte(f);
3258 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3259 #ifndef _WIN32
3260 if (ch == 0 &&
3261 (!kvm_enabled() || kvm_has_sync_mmu())) {
3262 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3264 #endif
3265 } else if (flags & RAM_SAVE_FLAG_PAGE)
3266 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3267 } while (!(flags & RAM_SAVE_FLAG_EOS));
3269 return 0;
3272 void qemu_service_io(void)
3274 qemu_notify_event();
3277 /***********************************************************/
3278 /* bottom halves (can be seen as timers which expire ASAP) */
3280 struct QEMUBH {
3281 QEMUBHFunc *cb;
3282 void *opaque;
3283 int scheduled;
3284 int idle;
3285 int deleted;
3286 QEMUBH *next;
3289 static QEMUBH *first_bh = NULL;
3291 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3293 QEMUBH *bh;
3294 bh = qemu_mallocz(sizeof(QEMUBH));
3295 bh->cb = cb;
3296 bh->opaque = opaque;
3297 bh->next = first_bh;
3298 first_bh = bh;
3299 return bh;
3302 int qemu_bh_poll(void)
3304 QEMUBH *bh, **bhp;
3305 int ret;
3307 ret = 0;
3308 for (bh = first_bh; bh; bh = bh->next) {
3309 if (!bh->deleted && bh->scheduled) {
3310 bh->scheduled = 0;
3311 if (!bh->idle)
3312 ret = 1;
3313 bh->idle = 0;
3314 bh->cb(bh->opaque);
3318 /* remove deleted bhs */
3319 bhp = &first_bh;
3320 while (*bhp) {
3321 bh = *bhp;
3322 if (bh->deleted) {
3323 *bhp = bh->next;
3324 qemu_free(bh);
3325 } else
3326 bhp = &bh->next;
3329 return ret;
3332 void qemu_bh_schedule_idle(QEMUBH *bh)
3334 if (bh->scheduled)
3335 return;
3336 bh->scheduled = 1;
3337 bh->idle = 1;
3340 void qemu_bh_schedule(QEMUBH *bh)
3342 if (bh->scheduled)
3343 return;
3344 bh->scheduled = 1;
3345 bh->idle = 0;
3346 /* stop the currently executing CPU to execute the BH ASAP */
3347 qemu_notify_event();
3350 void qemu_bh_cancel(QEMUBH *bh)
3352 bh->scheduled = 0;
3355 void qemu_bh_delete(QEMUBH *bh)
3357 bh->scheduled = 0;
3358 bh->deleted = 1;
3361 static void qemu_bh_update_timeout(int *timeout)
3363 QEMUBH *bh;
3365 for (bh = first_bh; bh; bh = bh->next) {
3366 if (!bh->deleted && bh->scheduled) {
3367 if (bh->idle) {
3368 /* idle bottom halves will be polled at least
3369 * every 10ms */
3370 *timeout = MIN(10, *timeout);
3371 } else {
3372 /* non-idle bottom halves will be executed
3373 * immediately */
3374 *timeout = 0;
3375 break;
3381 /***********************************************************/
3382 /* machine registration */
3384 static QEMUMachine *first_machine = NULL;
3385 QEMUMachine *current_machine = NULL;
3387 int qemu_register_machine(QEMUMachine *m)
3389 QEMUMachine **pm;
3390 pm = &first_machine;
3391 while (*pm != NULL)
3392 pm = &(*pm)->next;
3393 m->next = NULL;
3394 *pm = m;
3395 return 0;
3398 static QEMUMachine *find_machine(const char *name)
3400 QEMUMachine *m;
3402 for(m = first_machine; m != NULL; m = m->next) {
3403 if (!strcmp(m->name, name))
3404 return m;
3406 return NULL;
3409 static QEMUMachine *find_default_machine(void)
3411 QEMUMachine *m;
3413 for(m = first_machine; m != NULL; m = m->next) {
3414 if (m->is_default) {
3415 return m;
3418 return NULL;
3421 /***********************************************************/
3422 /* main execution loop */
3424 static void gui_update(void *opaque)
3426 uint64_t interval = GUI_REFRESH_INTERVAL;
3427 DisplayState *ds = opaque;
3428 DisplayChangeListener *dcl = ds->listeners;
3430 dpy_refresh(ds);
3432 while (dcl != NULL) {
3433 if (dcl->gui_timer_interval &&
3434 dcl->gui_timer_interval < interval)
3435 interval = dcl->gui_timer_interval;
3436 dcl = dcl->next;
3438 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3441 static void nographic_update(void *opaque)
3443 uint64_t interval = GUI_REFRESH_INTERVAL;
3445 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3448 struct vm_change_state_entry {
3449 VMChangeStateHandler *cb;
3450 void *opaque;
3451 LIST_ENTRY (vm_change_state_entry) entries;
3454 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3456 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3457 void *opaque)
3459 VMChangeStateEntry *e;
3461 e = qemu_mallocz(sizeof (*e));
3463 e->cb = cb;
3464 e->opaque = opaque;
3465 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3466 return e;
3469 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3471 LIST_REMOVE (e, entries);
3472 qemu_free (e);
3475 static void vm_state_notify(int running, int reason)
3477 VMChangeStateEntry *e;
3479 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3480 e->cb(e->opaque, running, reason);
3484 static void resume_all_vcpus(void);
3485 static void pause_all_vcpus(void);
3487 void vm_start(void)
3489 if (!vm_running) {
3490 cpu_enable_ticks();
3491 vm_running = 1;
3492 vm_state_notify(1, 0);
3493 qemu_rearm_alarm_timer(alarm_timer);
3494 resume_all_vcpus();
3498 /* reset/shutdown handler */
3500 typedef struct QEMUResetEntry {
3501 TAILQ_ENTRY(QEMUResetEntry) entry;
3502 QEMUResetHandler *func;
3503 void *opaque;
3504 } QEMUResetEntry;
3506 static TAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3507 TAILQ_HEAD_INITIALIZER(reset_handlers);
3508 static int reset_requested;
3509 static int shutdown_requested;
3510 static int powerdown_requested;
3511 static int debug_requested;
3512 static int vmstop_requested;
3514 int qemu_no_shutdown(void)
3516 int r = no_shutdown;
3517 no_shutdown = 0;
3518 return r;
3521 int qemu_shutdown_requested(void)
3523 int r = shutdown_requested;
3524 shutdown_requested = 0;
3525 return r;
3528 int qemu_reset_requested(void)
3530 int r = reset_requested;
3531 reset_requested = 0;
3532 return r;
3535 int qemu_powerdown_requested(void)
3537 int r = powerdown_requested;
3538 powerdown_requested = 0;
3539 return r;
3542 static int qemu_debug_requested(void)
3544 int r = debug_requested;
3545 debug_requested = 0;
3546 return r;
3549 static int qemu_vmstop_requested(void)
3551 int r = vmstop_requested;
3552 vmstop_requested = 0;
3553 return r;
3556 static void do_vm_stop(int reason)
3558 if (vm_running) {
3559 cpu_disable_ticks();
3560 vm_running = 0;
3561 pause_all_vcpus();
3562 vm_state_notify(0, reason);
3566 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3568 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3570 re->func = func;
3571 re->opaque = opaque;
3572 TAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3575 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3577 QEMUResetEntry *re;
3579 TAILQ_FOREACH(re, &reset_handlers, entry) {
3580 if (re->func == func && re->opaque == opaque) {
3581 TAILQ_REMOVE(&reset_handlers, re, entry);
3582 qemu_free(re);
3583 return;
3588 void qemu_system_reset(void)
3590 QEMUResetEntry *re, *nre;
3592 /* reset all devices */
3593 TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3594 re->func(re->opaque);
3598 void qemu_system_reset_request(void)
3600 if (no_reboot) {
3601 shutdown_requested = 1;
3602 } else {
3603 reset_requested = 1;
3605 if (cpu_single_env) {
3606 cpu_single_env->stopped = 1;
3608 qemu_notify_event();
3611 void qemu_system_shutdown_request(void)
3613 shutdown_requested = 1;
3614 qemu_notify_event();
3617 void qemu_system_powerdown_request(void)
3619 powerdown_requested = 1;
3620 qemu_notify_event();
3623 #ifdef CONFIG_IOTHREAD
3624 static void qemu_system_vmstop_request(int reason)
3626 vmstop_requested = reason;
3627 qemu_notify_event();
3629 #endif
3631 #ifndef _WIN32
3632 static int io_thread_fd = -1;
3634 static void qemu_event_increment(void)
3636 static const char byte = 0;
3638 if (io_thread_fd == -1)
3639 return;
3641 write(io_thread_fd, &byte, sizeof(byte));
3644 static void qemu_event_read(void *opaque)
3646 int fd = (unsigned long)opaque;
3647 ssize_t len;
3649 /* Drain the notify pipe */
3650 do {
3651 char buffer[512];
3652 len = read(fd, buffer, sizeof(buffer));
3653 } while ((len == -1 && errno == EINTR) || len > 0);
3656 static int qemu_event_init(void)
3658 int err;
3659 int fds[2];
3661 err = pipe(fds);
3662 if (err == -1)
3663 return -errno;
3665 err = fcntl_setfl(fds[0], O_NONBLOCK);
3666 if (err < 0)
3667 goto fail;
3669 err = fcntl_setfl(fds[1], O_NONBLOCK);
3670 if (err < 0)
3671 goto fail;
3673 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3674 (void *)(unsigned long)fds[0]);
3676 io_thread_fd = fds[1];
3677 return 0;
3679 fail:
3680 close(fds[0]);
3681 close(fds[1]);
3682 return err;
3684 #else
3685 HANDLE qemu_event_handle;
3687 static void dummy_event_handler(void *opaque)
3691 static int qemu_event_init(void)
3693 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3694 if (!qemu_event_handle) {
3695 perror("Failed CreateEvent");
3696 return -1;
3698 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3699 return 0;
3702 static void qemu_event_increment(void)
3704 SetEvent(qemu_event_handle);
3706 #endif
3708 static int cpu_can_run(CPUState *env)
3710 if (env->stop)
3711 return 0;
3712 if (env->stopped)
3713 return 0;
3714 return 1;
3717 #ifndef CONFIG_IOTHREAD
3718 static int qemu_init_main_loop(void)
3720 return qemu_event_init();
3723 void qemu_init_vcpu(void *_env)
3725 CPUState *env = _env;
3727 if (kvm_enabled())
3728 kvm_init_vcpu(env);
3729 return;
3732 int qemu_cpu_self(void *env)
3734 return 1;
3737 static void resume_all_vcpus(void)
3741 static void pause_all_vcpus(void)
3745 void qemu_cpu_kick(void *env)
3747 return;
3750 void qemu_notify_event(void)
3752 CPUState *env = cpu_single_env;
3754 if (kvm_enabled()) {
3755 qemu_kvm_notify_work();
3756 return;
3758 if (env) {
3759 cpu_exit(env);
3760 #ifdef USE_KQEMU
3761 if (env->kqemu_enabled)
3762 kqemu_cpu_interrupt(env);
3763 #endif
3767 #ifdef KVM_UPSTREAM
3768 #define qemu_mutex_lock_iothread() do { } while (0)
3769 #define qemu_mutex_unlock_iothread() do { } while (0)
3770 #endif
3772 void vm_stop(int reason)
3774 do_vm_stop(reason);
3777 #else /* CONFIG_IOTHREAD */
3779 #include "qemu-thread.h"
3781 QemuMutex qemu_global_mutex;
3782 static QemuMutex qemu_fair_mutex;
3784 static QemuThread io_thread;
3786 static QemuThread *tcg_cpu_thread;
3787 static QemuCond *tcg_halt_cond;
3789 static int qemu_system_ready;
3790 /* cpu creation */
3791 static QemuCond qemu_cpu_cond;
3792 /* system init */
3793 static QemuCond qemu_system_cond;
3794 static QemuCond qemu_pause_cond;
3796 static void block_io_signals(void);
3797 static void unblock_io_signals(void);
3798 static int tcg_has_work(void);
3800 static int qemu_init_main_loop(void)
3802 int ret;
3804 ret = qemu_event_init();
3805 if (ret)
3806 return ret;
3808 qemu_cond_init(&qemu_pause_cond);
3809 qemu_mutex_init(&qemu_fair_mutex);
3810 qemu_mutex_init(&qemu_global_mutex);
3811 qemu_mutex_lock(&qemu_global_mutex);
3813 unblock_io_signals();
3814 qemu_thread_self(&io_thread);
3816 return 0;
3819 static void qemu_wait_io_event(CPUState *env)
3821 while (!tcg_has_work())
3822 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3824 qemu_mutex_unlock(&qemu_global_mutex);
3827 * Users of qemu_global_mutex can be starved, having no chance
3828 * to acquire it since this path will get to it first.
3829 * So use another lock to provide fairness.
3831 qemu_mutex_lock(&qemu_fair_mutex);
3832 qemu_mutex_unlock(&qemu_fair_mutex);
3834 qemu_mutex_lock(&qemu_global_mutex);
3835 if (env->stop) {
3836 env->stop = 0;
3837 env->stopped = 1;
3838 qemu_cond_signal(&qemu_pause_cond);
3842 static int qemu_cpu_exec(CPUState *env);
3844 static void *kvm_cpu_thread_fn(void *arg)
3846 CPUState *env = arg;
3848 block_io_signals();
3849 qemu_thread_self(env->thread);
3851 /* signal CPU creation */
3852 qemu_mutex_lock(&qemu_global_mutex);
3853 env->created = 1;
3854 qemu_cond_signal(&qemu_cpu_cond);
3856 /* and wait for machine initialization */
3857 while (!qemu_system_ready)
3858 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3860 while (1) {
3861 if (cpu_can_run(env))
3862 qemu_cpu_exec(env);
3863 qemu_wait_io_event(env);
3866 return NULL;
3869 static void tcg_cpu_exec(void);
3871 static void *tcg_cpu_thread_fn(void *arg)
3873 CPUState *env = arg;
3875 block_io_signals();
3876 qemu_thread_self(env->thread);
3878 /* signal CPU creation */
3879 qemu_mutex_lock(&qemu_global_mutex);
3880 for (env = first_cpu; env != NULL; env = env->next_cpu)
3881 env->created = 1;
3882 qemu_cond_signal(&qemu_cpu_cond);
3884 /* and wait for machine initialization */
3885 while (!qemu_system_ready)
3886 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3888 while (1) {
3889 tcg_cpu_exec();
3890 qemu_wait_io_event(cur_cpu);
3893 return NULL;
3896 void qemu_cpu_kick(void *_env)
3898 CPUState *env = _env;
3899 qemu_cond_broadcast(env->halt_cond);
3900 if (kvm_enabled())
3901 qemu_thread_signal(env->thread, SIGUSR1);
3904 int qemu_cpu_self(void *env)
3906 return (cpu_single_env != NULL);
3909 static void cpu_signal(int sig)
3911 if (cpu_single_env)
3912 cpu_exit(cpu_single_env);
3915 static void block_io_signals(void)
3917 sigset_t set;
3918 struct sigaction sigact;
3920 sigemptyset(&set);
3921 sigaddset(&set, SIGUSR2);
3922 sigaddset(&set, SIGIO);
3923 sigaddset(&set, SIGALRM);
3924 pthread_sigmask(SIG_BLOCK, &set, NULL);
3926 sigemptyset(&set);
3927 sigaddset(&set, SIGUSR1);
3928 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3930 memset(&sigact, 0, sizeof(sigact));
3931 sigact.sa_handler = cpu_signal;
3932 sigaction(SIGUSR1, &sigact, NULL);
3935 static void unblock_io_signals(void)
3937 sigset_t set;
3939 sigemptyset(&set);
3940 sigaddset(&set, SIGUSR2);
3941 sigaddset(&set, SIGIO);
3942 sigaddset(&set, SIGALRM);
3943 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3945 sigemptyset(&set);
3946 sigaddset(&set, SIGUSR1);
3947 pthread_sigmask(SIG_BLOCK, &set, NULL);
3950 static void qemu_signal_lock(unsigned int msecs)
3952 qemu_mutex_lock(&qemu_fair_mutex);
3954 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3955 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3956 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3957 break;
3959 qemu_mutex_unlock(&qemu_fair_mutex);
3962 static void qemu_mutex_lock_iothread(void)
3964 if (kvm_enabled()) {
3965 qemu_mutex_lock(&qemu_fair_mutex);
3966 qemu_mutex_lock(&qemu_global_mutex);
3967 qemu_mutex_unlock(&qemu_fair_mutex);
3968 } else
3969 qemu_signal_lock(100);
3972 static void qemu_mutex_unlock_iothread(void)
3974 qemu_mutex_unlock(&qemu_global_mutex);
3977 static int all_vcpus_paused(void)
3979 CPUState *penv = first_cpu;
3981 while (penv) {
3982 if (!penv->stopped)
3983 return 0;
3984 penv = (CPUState *)penv->next_cpu;
3987 return 1;
3990 static void pause_all_vcpus(void)
3992 CPUState *penv = first_cpu;
3994 while (penv) {
3995 penv->stop = 1;
3996 qemu_thread_signal(penv->thread, SIGUSR1);
3997 qemu_cpu_kick(penv);
3998 penv = (CPUState *)penv->next_cpu;
4001 while (!all_vcpus_paused()) {
4002 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
4003 penv = first_cpu;
4004 while (penv) {
4005 qemu_thread_signal(penv->thread, SIGUSR1);
4006 penv = (CPUState *)penv->next_cpu;
4011 static void resume_all_vcpus(void)
4013 CPUState *penv = first_cpu;
4015 while (penv) {
4016 penv->stop = 0;
4017 penv->stopped = 0;
4018 qemu_thread_signal(penv->thread, SIGUSR1);
4019 qemu_cpu_kick(penv);
4020 penv = (CPUState *)penv->next_cpu;
4024 static void tcg_init_vcpu(void *_env)
4026 CPUState *env = _env;
4027 /* share a single thread for all cpus with TCG */
4028 if (!tcg_cpu_thread) {
4029 env->thread = qemu_mallocz(sizeof(QemuThread));
4030 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4031 qemu_cond_init(env->halt_cond);
4032 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
4033 while (env->created == 0)
4034 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4035 tcg_cpu_thread = env->thread;
4036 tcg_halt_cond = env->halt_cond;
4037 } else {
4038 env->thread = tcg_cpu_thread;
4039 env->halt_cond = tcg_halt_cond;
4043 static void kvm_start_vcpu(CPUState *env)
4045 kvm_init_vcpu(env);
4046 env->thread = qemu_mallocz(sizeof(QemuThread));
4047 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4048 qemu_cond_init(env->halt_cond);
4049 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
4050 while (env->created == 0)
4051 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4054 void qemu_init_vcpu(void *_env)
4056 CPUState *env = _env;
4058 if (kvm_enabled())
4059 kvm_start_vcpu(env);
4060 else
4061 tcg_init_vcpu(env);
4064 void qemu_notify_event(void)
4066 qemu_event_increment();
4069 void vm_stop(int reason)
4071 QemuThread me;
4072 qemu_thread_self(&me);
4074 if (!qemu_thread_equal(&me, &io_thread)) {
4075 qemu_system_vmstop_request(reason);
4077 * FIXME: should not return to device code in case
4078 * vm_stop() has been requested.
4080 if (cpu_single_env) {
4081 cpu_exit(cpu_single_env);
4082 cpu_single_env->stop = 1;
4084 return;
4086 do_vm_stop(reason);
4089 #endif
4092 #ifdef _WIN32
4093 static void host_main_loop_wait(int *timeout)
4095 int ret, ret2, i;
4096 PollingEntry *pe;
4099 /* XXX: need to suppress polling by better using win32 events */
4100 ret = 0;
4101 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4102 ret |= pe->func(pe->opaque);
4104 if (ret == 0) {
4105 int err;
4106 WaitObjects *w = &wait_objects;
4108 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4109 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4110 if (w->func[ret - WAIT_OBJECT_0])
4111 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4113 /* Check for additional signaled events */
4114 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4116 /* Check if event is signaled */
4117 ret2 = WaitForSingleObject(w->events[i], 0);
4118 if(ret2 == WAIT_OBJECT_0) {
4119 if (w->func[i])
4120 w->func[i](w->opaque[i]);
4121 } else if (ret2 == WAIT_TIMEOUT) {
4122 } else {
4123 err = GetLastError();
4124 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4127 } else if (ret == WAIT_TIMEOUT) {
4128 } else {
4129 err = GetLastError();
4130 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4134 *timeout = 0;
4136 #else
4137 static void host_main_loop_wait(int *timeout)
4140 #endif
4142 void main_loop_wait(int timeout)
4144 IOHandlerRecord *ioh;
4145 fd_set rfds, wfds, xfds;
4146 int ret, nfds;
4147 struct timeval tv;
4149 qemu_bh_update_timeout(&timeout);
4151 host_main_loop_wait(&timeout);
4153 /* poll any events */
4154 /* XXX: separate device handlers from system ones */
4155 nfds = -1;
4156 FD_ZERO(&rfds);
4157 FD_ZERO(&wfds);
4158 FD_ZERO(&xfds);
4159 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4160 if (ioh->deleted)
4161 continue;
4162 if (ioh->fd_read &&
4163 (!ioh->fd_read_poll ||
4164 ioh->fd_read_poll(ioh->opaque) != 0)) {
4165 FD_SET(ioh->fd, &rfds);
4166 if (ioh->fd > nfds)
4167 nfds = ioh->fd;
4169 if (ioh->fd_write) {
4170 FD_SET(ioh->fd, &wfds);
4171 if (ioh->fd > nfds)
4172 nfds = ioh->fd;
4176 tv.tv_sec = timeout / 1000;
4177 tv.tv_usec = (timeout % 1000) * 1000;
4179 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4181 qemu_mutex_unlock_iothread();
4182 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4183 qemu_mutex_lock_iothread();
4184 if (ret > 0) {
4185 IOHandlerRecord **pioh;
4187 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4188 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4189 ioh->fd_read(ioh->opaque);
4190 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
4191 FD_CLR(ioh->fd, &rfds);
4193 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4194 ioh->fd_write(ioh->opaque);
4198 /* remove deleted IO handlers */
4199 pioh = &first_io_handler;
4200 while (*pioh) {
4201 ioh = *pioh;
4202 if (ioh->deleted) {
4203 *pioh = ioh->next;
4204 qemu_free(ioh);
4205 } else
4206 pioh = &ioh->next;
4210 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4212 /* rearm timer, if not periodic */
4213 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4214 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4215 qemu_rearm_alarm_timer(alarm_timer);
4218 /* vm time timers */
4219 if (vm_running) {
4220 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4221 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4222 qemu_get_clock(vm_clock));
4225 /* real time timers */
4226 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4227 qemu_get_clock(rt_clock));
4229 /* Check bottom-halves last in case any of the earlier events triggered
4230 them. */
4231 qemu_bh_poll();
4235 static int qemu_cpu_exec(CPUState *env)
4237 int ret;
4238 #ifdef CONFIG_PROFILER
4239 int64_t ti;
4240 #endif
4242 #ifdef CONFIG_PROFILER
4243 ti = profile_getclock();
4244 #endif
4245 if (use_icount) {
4246 int64_t count;
4247 int decr;
4248 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4249 env->icount_decr.u16.low = 0;
4250 env->icount_extra = 0;
4251 count = qemu_next_deadline();
4252 count = (count + (1 << icount_time_shift) - 1)
4253 >> icount_time_shift;
4254 qemu_icount += count;
4255 decr = (count > 0xffff) ? 0xffff : count;
4256 count -= decr;
4257 env->icount_decr.u16.low = decr;
4258 env->icount_extra = count;
4260 ret = cpu_exec(env);
4261 #ifdef CONFIG_PROFILER
4262 qemu_time += profile_getclock() - ti;
4263 #endif
4264 if (use_icount) {
4265 /* Fold pending instructions back into the
4266 instruction counter, and clear the interrupt flag. */
4267 qemu_icount -= (env->icount_decr.u16.low
4268 + env->icount_extra);
4269 env->icount_decr.u32 = 0;
4270 env->icount_extra = 0;
4272 return ret;
4275 static void tcg_cpu_exec(void)
4277 int ret = 0;
4279 if (next_cpu == NULL)
4280 next_cpu = first_cpu;
4281 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4282 CPUState *env = cur_cpu = next_cpu;
4284 if (!vm_running)
4285 break;
4286 if (timer_alarm_pending) {
4287 timer_alarm_pending = 0;
4288 break;
4290 if (cpu_can_run(env))
4291 ret = qemu_cpu_exec(env);
4292 if (ret == EXCP_DEBUG) {
4293 gdb_set_stop_cpu(env);
4294 debug_requested = 1;
4295 break;
4300 static int cpu_has_work(CPUState *env)
4302 if (env->stop)
4303 return 1;
4304 if (env->stopped)
4305 return 0;
4306 if (!env->halted)
4307 return 1;
4308 if (qemu_cpu_has_work(env))
4309 return 1;
4310 return 0;
4313 static int tcg_has_work(void)
4315 CPUState *env;
4317 for (env = first_cpu; env != NULL; env = env->next_cpu)
4318 if (cpu_has_work(env))
4319 return 1;
4320 return 0;
4323 static int qemu_calculate_timeout(void)
4325 #ifndef CONFIG_IOTHREAD
4326 int timeout;
4328 if (!vm_running)
4329 timeout = 5000;
4330 else if (tcg_has_work())
4331 timeout = 0;
4332 else if (!use_icount)
4333 timeout = 5000;
4334 else {
4335 /* XXX: use timeout computed from timers */
4336 int64_t add;
4337 int64_t delta;
4338 /* Advance virtual time to the next event. */
4339 if (use_icount == 1) {
4340 /* When not using an adaptive execution frequency
4341 we tend to get badly out of sync with real time,
4342 so just delay for a reasonable amount of time. */
4343 delta = 0;
4344 } else {
4345 delta = cpu_get_icount() - cpu_get_clock();
4347 if (delta > 0) {
4348 /* If virtual time is ahead of real time then just
4349 wait for IO. */
4350 timeout = (delta / 1000000) + 1;
4351 } else {
4352 /* Wait for either IO to occur or the next
4353 timer event. */
4354 add = qemu_next_deadline();
4355 /* We advance the timer before checking for IO.
4356 Limit the amount we advance so that early IO
4357 activity won't get the guest too far ahead. */
4358 if (add > 10000000)
4359 add = 10000000;
4360 delta += add;
4361 add = (add + (1 << icount_time_shift) - 1)
4362 >> icount_time_shift;
4363 qemu_icount += add;
4364 timeout = delta / 1000000;
4365 if (timeout < 0)
4366 timeout = 0;
4370 return timeout;
4371 #else /* CONFIG_IOTHREAD */
4372 return 1000;
4373 #endif
4376 static int vm_can_run(void)
4378 if (powerdown_requested)
4379 return 0;
4380 if (reset_requested)
4381 return 0;
4382 if (shutdown_requested)
4383 return 0;
4384 if (debug_requested)
4385 return 0;
4386 return 1;
4389 static void main_loop(void)
4391 int r;
4393 if (kvm_enabled()) {
4394 kvm_main_loop();
4395 cpu_disable_ticks();
4396 return;
4399 #ifdef CONFIG_IOTHREAD
4400 qemu_system_ready = 1;
4401 qemu_cond_broadcast(&qemu_system_cond);
4402 #endif
4404 for (;;) {
4405 do {
4406 #ifdef CONFIG_PROFILER
4407 int64_t ti;
4408 #endif
4409 #ifndef CONFIG_IOTHREAD
4410 tcg_cpu_exec();
4411 #endif
4412 #ifdef CONFIG_PROFILER
4413 ti = profile_getclock();
4414 #endif
4415 main_loop_wait(qemu_calculate_timeout());
4416 #ifdef CONFIG_PROFILER
4417 dev_time += profile_getclock() - ti;
4418 #endif
4419 } while (vm_can_run());
4421 if (qemu_debug_requested())
4422 vm_stop(EXCP_DEBUG);
4423 if (qemu_shutdown_requested()) {
4424 if (no_shutdown) {
4425 vm_stop(0);
4426 no_shutdown = 0;
4427 } else
4428 break;
4430 if (qemu_reset_requested()) {
4431 pause_all_vcpus();
4432 qemu_system_reset();
4433 resume_all_vcpus();
4435 if (qemu_powerdown_requested())
4436 qemu_system_powerdown();
4437 if ((r = qemu_vmstop_requested()))
4438 vm_stop(r);
4440 pause_all_vcpus();
4443 static void version(void)
4445 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4448 static void help(int exitcode)
4450 version();
4451 printf("usage: %s [options] [disk_image]\n"
4452 "\n"
4453 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4454 "\n"
4455 #define DEF(option, opt_arg, opt_enum, opt_help) \
4456 opt_help
4457 #define DEFHEADING(text) stringify(text) "\n"
4458 #include "qemu-options.h"
4459 #undef DEF
4460 #undef DEFHEADING
4461 #undef GEN_DOCS
4462 "\n"
4463 "During emulation, the following keys are useful:\n"
4464 "ctrl-alt-f toggle full screen\n"
4465 "ctrl-alt-n switch to virtual console 'n'\n"
4466 "ctrl-alt toggle mouse and keyboard grab\n"
4467 "\n"
4468 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4470 "qemu",
4471 DEFAULT_RAM_SIZE,
4472 #ifndef _WIN32
4473 DEFAULT_NETWORK_SCRIPT,
4474 DEFAULT_NETWORK_DOWN_SCRIPT,
4475 #endif
4476 DEFAULT_GDBSTUB_PORT,
4477 "/tmp/qemu.log");
4478 exit(exitcode);
4481 #define HAS_ARG 0x0001
4483 enum {
4484 #define DEF(option, opt_arg, opt_enum, opt_help) \
4485 opt_enum,
4486 #define DEFHEADING(text)
4487 #include "qemu-options.h"
4488 #undef DEF
4489 #undef DEFHEADING
4490 #undef GEN_DOCS
4493 typedef struct QEMUOption {
4494 const char *name;
4495 int flags;
4496 int index;
4497 } QEMUOption;
4499 static const QEMUOption qemu_options[] = {
4500 { "h", 0, QEMU_OPTION_h },
4501 #define DEF(option, opt_arg, opt_enum, opt_help) \
4502 { option, opt_arg, opt_enum },
4503 #define DEFHEADING(text)
4504 #include "qemu-options.h"
4505 #undef DEF
4506 #undef DEFHEADING
4507 #undef GEN_DOCS
4508 { NULL },
4511 #ifdef HAS_AUDIO
4512 struct soundhw soundhw[] = {
4513 #ifdef HAS_AUDIO_CHOICE
4514 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4516 "pcspk",
4517 "PC speaker",
4520 { .init_isa = pcspk_audio_init }
4522 #endif
4524 #ifdef CONFIG_SB16
4526 "sb16",
4527 "Creative Sound Blaster 16",
4530 { .init_isa = SB16_init }
4532 #endif
4534 #ifdef CONFIG_CS4231A
4536 "cs4231a",
4537 "CS4231A",
4540 { .init_isa = cs4231a_init }
4542 #endif
4544 #ifdef CONFIG_ADLIB
4546 "adlib",
4547 #ifdef HAS_YMF262
4548 "Yamaha YMF262 (OPL3)",
4549 #else
4550 "Yamaha YM3812 (OPL2)",
4551 #endif
4554 { .init_isa = Adlib_init }
4556 #endif
4558 #ifdef CONFIG_GUS
4560 "gus",
4561 "Gravis Ultrasound GF1",
4564 { .init_isa = GUS_init }
4566 #endif
4568 #ifdef CONFIG_AC97
4570 "ac97",
4571 "Intel 82801AA AC97 Audio",
4574 { .init_pci = ac97_init }
4576 #endif
4578 #ifdef CONFIG_ES1370
4580 "es1370",
4581 "ENSONIQ AudioPCI ES1370",
4584 { .init_pci = es1370_init }
4586 #endif
4588 #endif /* HAS_AUDIO_CHOICE */
4590 { NULL, NULL, 0, 0, { NULL } }
4593 static void select_soundhw (const char *optarg)
4595 struct soundhw *c;
4597 if (*optarg == '?') {
4598 show_valid_cards:
4600 printf ("Valid sound card names (comma separated):\n");
4601 for (c = soundhw; c->name; ++c) {
4602 printf ("%-11s %s\n", c->name, c->descr);
4604 printf ("\n-soundhw all will enable all of the above\n");
4605 exit (*optarg != '?');
4607 else {
4608 size_t l;
4609 const char *p;
4610 char *e;
4611 int bad_card = 0;
4613 if (!strcmp (optarg, "all")) {
4614 for (c = soundhw; c->name; ++c) {
4615 c->enabled = 1;
4617 return;
4620 p = optarg;
4621 while (*p) {
4622 e = strchr (p, ',');
4623 l = !e ? strlen (p) : (size_t) (e - p);
4625 for (c = soundhw; c->name; ++c) {
4626 if (!strncmp (c->name, p, l)) {
4627 c->enabled = 1;
4628 break;
4632 if (!c->name) {
4633 if (l > 80) {
4634 fprintf (stderr,
4635 "Unknown sound card name (too big to show)\n");
4637 else {
4638 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4639 (int) l, p);
4641 bad_card = 1;
4643 p += l + (e != NULL);
4646 if (bad_card)
4647 goto show_valid_cards;
4650 #endif
4652 static void select_vgahw (const char *p)
4654 const char *opts;
4656 cirrus_vga_enabled = 0;
4657 std_vga_enabled = 0;
4658 vmsvga_enabled = 0;
4659 xenfb_enabled = 0;
4660 if (strstart(p, "std", &opts)) {
4661 std_vga_enabled = 1;
4662 } else if (strstart(p, "cirrus", &opts)) {
4663 cirrus_vga_enabled = 1;
4664 } else if (strstart(p, "vmware", &opts)) {
4665 vmsvga_enabled = 1;
4666 } else if (strstart(p, "xenfb", &opts)) {
4667 xenfb_enabled = 1;
4668 } else if (!strstart(p, "none", &opts)) {
4669 invalid_vga:
4670 fprintf(stderr, "Unknown vga type: %s\n", p);
4671 exit(1);
4673 while (*opts) {
4674 const char *nextopt;
4676 if (strstart(opts, ",retrace=", &nextopt)) {
4677 opts = nextopt;
4678 if (strstart(opts, "dumb", &nextopt))
4679 vga_retrace_method = VGA_RETRACE_DUMB;
4680 else if (strstart(opts, "precise", &nextopt))
4681 vga_retrace_method = VGA_RETRACE_PRECISE;
4682 else goto invalid_vga;
4683 } else goto invalid_vga;
4684 opts = nextopt;
4688 #ifdef TARGET_I386
4689 static int balloon_parse(const char *arg)
4691 char buf[128];
4692 const char *p;
4694 if (!strcmp(arg, "none")) {
4695 virtio_balloon = 0;
4696 } else if (!strncmp(arg, "virtio", 6)) {
4697 virtio_balloon = 1;
4698 if (arg[6] == ',') {
4699 p = arg + 7;
4700 if (get_param_value(buf, sizeof(buf), "addr", p)) {
4701 virtio_balloon_devaddr = strdup(buf);
4704 } else {
4705 return -1;
4707 return 0;
4709 #endif
4711 #ifdef _WIN32
4712 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4714 exit(STATUS_CONTROL_C_EXIT);
4715 return TRUE;
4717 #endif
4719 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4721 int ret;
4723 if(strlen(str) != 36)
4724 return -1;
4726 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4727 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4728 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4730 if(ret != 16)
4731 return -1;
4733 #ifdef TARGET_I386
4734 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4735 #endif
4737 return 0;
4740 #define MAX_NET_CLIENTS 32
4742 #ifndef _WIN32
4744 static void termsig_handler(int signal)
4746 qemu_system_shutdown_request();
4749 static void sigchld_handler(int signal)
4751 waitpid(-1, NULL, WNOHANG);
4754 static void sighandler_setup(void)
4756 struct sigaction act;
4758 memset(&act, 0, sizeof(act));
4759 act.sa_handler = termsig_handler;
4760 sigaction(SIGINT, &act, NULL);
4761 sigaction(SIGHUP, &act, NULL);
4762 sigaction(SIGTERM, &act, NULL);
4764 act.sa_handler = sigchld_handler;
4765 act.sa_flags = SA_NOCLDSTOP;
4766 sigaction(SIGCHLD, &act, NULL);
4769 #endif
4771 #ifdef _WIN32
4772 /* Look for support files in the same directory as the executable. */
4773 static char *find_datadir(const char *argv0)
4775 char *p;
4776 char buf[MAX_PATH];
4777 DWORD len;
4779 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4780 if (len == 0) {
4781 return NULL;
4784 buf[len] = 0;
4785 p = buf + len - 1;
4786 while (p != buf && *p != '\\')
4787 p--;
4788 *p = 0;
4789 if (access(buf, R_OK) == 0) {
4790 return qemu_strdup(buf);
4792 return NULL;
4794 #else /* !_WIN32 */
4796 /* Find a likely location for support files using the location of the binary.
4797 For installed binaries this will be "$bindir/../share/qemu". When
4798 running from the build tree this will be "$bindir/../pc-bios". */
4799 #define SHARE_SUFFIX "/share/qemu"
4800 #define BUILD_SUFFIX "/pc-bios"
4801 static char *find_datadir(const char *argv0)
4803 char *dir;
4804 char *p = NULL;
4805 char *res;
4806 #ifdef PATH_MAX
4807 char buf[PATH_MAX];
4808 #endif
4809 size_t max_len;
4811 #if defined(__linux__)
4813 int len;
4814 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4815 if (len > 0) {
4816 buf[len] = 0;
4817 p = buf;
4820 #elif defined(__FreeBSD__)
4822 int len;
4823 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4824 if (len > 0) {
4825 buf[len] = 0;
4826 p = buf;
4829 #endif
4830 /* If we don't have any way of figuring out the actual executable
4831 location then try argv[0]. */
4832 if (!p) {
4833 #ifdef PATH_MAX
4834 p = buf;
4835 #endif
4836 p = realpath(argv0, p);
4837 if (!p) {
4838 return NULL;
4841 dir = dirname(p);
4842 dir = dirname(dir);
4844 max_len = strlen(dir) +
4845 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4846 res = qemu_mallocz(max_len);
4847 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4848 if (access(res, R_OK)) {
4849 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4850 if (access(res, R_OK)) {
4851 qemu_free(res);
4852 res = NULL;
4855 #ifndef PATH_MAX
4856 free(p);
4857 #endif
4858 return res;
4860 #undef SHARE_SUFFIX
4861 #undef BUILD_SUFFIX
4862 #endif
4864 char *qemu_find_file(int type, const char *name)
4866 int len;
4867 const char *subdir;
4868 char *buf;
4870 /* If name contains path separators then try it as a straight path. */
4871 if ((strchr(name, '/') || strchr(name, '\\'))
4872 && access(name, R_OK) == 0) {
4873 return strdup(name);
4875 switch (type) {
4876 case QEMU_FILE_TYPE_BIOS:
4877 subdir = "";
4878 break;
4879 case QEMU_FILE_TYPE_KEYMAP:
4880 subdir = "keymaps/";
4881 break;
4882 default:
4883 abort();
4885 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4886 buf = qemu_mallocz(len);
4887 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4888 if (access(buf, R_OK)) {
4889 qemu_free(buf);
4890 return NULL;
4892 return buf;
4895 int main(int argc, char **argv, char **envp)
4897 const char *gdbstub_dev = NULL;
4898 uint32_t boot_devices_bitmap = 0;
4899 int i;
4900 int snapshot, linux_boot, net_boot;
4901 const char *initrd_filename;
4902 const char *kernel_filename, *kernel_cmdline;
4903 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4904 DisplayState *ds;
4905 DisplayChangeListener *dcl;
4906 int cyls, heads, secs, translation;
4907 const char *net_clients[MAX_NET_CLIENTS];
4908 int nb_net_clients;
4909 const char *bt_opts[MAX_BT_CMDLINE];
4910 int nb_bt_opts;
4911 int hda_index;
4912 int optind;
4913 const char *r, *optarg;
4914 CharDriverState *monitor_hd = NULL;
4915 const char *monitor_device;
4916 const char *serial_devices[MAX_SERIAL_PORTS];
4917 int serial_device_index;
4918 const char *parallel_devices[MAX_PARALLEL_PORTS];
4919 int parallel_device_index;
4920 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4921 int virtio_console_index;
4922 const char *loadvm = NULL;
4923 QEMUMachine *machine;
4924 const char *cpu_model;
4925 const char *usb_devices[MAX_USB_CMDLINE];
4926 int usb_devices_index;
4927 #ifndef _WIN32
4928 int fds[2];
4929 #endif
4930 int tb_size;
4931 const char *pid_file = NULL;
4932 const char *incoming = NULL;
4933 #ifndef _WIN32
4934 int fd = 0;
4935 struct passwd *pwd = NULL;
4936 const char *chroot_dir = NULL;
4937 const char *run_as = NULL;
4938 #endif
4939 CPUState *env;
4940 int show_vnc_port = 0;
4942 qemu_cache_utils_init(envp);
4944 LIST_INIT (&vm_change_state_head);
4945 #ifndef _WIN32
4947 struct sigaction act;
4948 sigfillset(&act.sa_mask);
4949 act.sa_flags = 0;
4950 act.sa_handler = SIG_IGN;
4951 sigaction(SIGPIPE, &act, NULL);
4953 #else
4954 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4955 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4956 QEMU to run on a single CPU */
4958 HANDLE h;
4959 DWORD mask, smask;
4960 int i;
4961 h = GetCurrentProcess();
4962 if (GetProcessAffinityMask(h, &mask, &smask)) {
4963 for(i = 0; i < 32; i++) {
4964 if (mask & (1 << i))
4965 break;
4967 if (i != 32) {
4968 mask = 1 << i;
4969 SetProcessAffinityMask(h, mask);
4973 #endif
4975 module_call_init(MODULE_INIT_MACHINE);
4976 machine = find_default_machine();
4977 cpu_model = NULL;
4978 initrd_filename = NULL;
4979 ram_size = 0;
4980 snapshot = 0;
4981 kernel_filename = NULL;
4982 kernel_cmdline = "";
4983 cyls = heads = secs = 0;
4984 translation = BIOS_ATA_TRANSLATION_AUTO;
4985 monitor_device = "vc:80Cx24C";
4987 serial_devices[0] = "vc:80Cx24C";
4988 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4989 serial_devices[i] = NULL;
4990 serial_device_index = 0;
4992 parallel_devices[0] = "vc:80Cx24C";
4993 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4994 parallel_devices[i] = NULL;
4995 parallel_device_index = 0;
4997 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4998 virtio_consoles[i] = NULL;
4999 virtio_console_index = 0;
5001 for (i = 0; i < MAX_NODES; i++) {
5002 node_mem[i] = 0;
5003 node_cpumask[i] = 0;
5006 usb_devices_index = 0;
5007 assigned_devices_index = 0;
5009 nb_net_clients = 0;
5010 nb_bt_opts = 0;
5011 nb_drives = 0;
5012 nb_drives_opt = 0;
5013 nb_numa_nodes = 0;
5014 hda_index = -1;
5016 nb_nics = 0;
5018 tb_size = 0;
5019 autostart= 1;
5021 register_watchdogs();
5023 optind = 1;
5024 for(;;) {
5025 if (optind >= argc)
5026 break;
5027 r = argv[optind];
5028 if (r[0] != '-') {
5029 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5030 } else {
5031 const QEMUOption *popt;
5033 optind++;
5034 /* Treat --foo the same as -foo. */
5035 if (r[1] == '-')
5036 r++;
5037 popt = qemu_options;
5038 for(;;) {
5039 if (!popt->name) {
5040 fprintf(stderr, "%s: invalid option -- '%s'\n",
5041 argv[0], r);
5042 exit(1);
5044 if (!strcmp(popt->name, r + 1))
5045 break;
5046 popt++;
5048 if (popt->flags & HAS_ARG) {
5049 if (optind >= argc) {
5050 fprintf(stderr, "%s: option '%s' requires an argument\n",
5051 argv[0], r);
5052 exit(1);
5054 optarg = argv[optind++];
5055 } else {
5056 optarg = NULL;
5059 switch(popt->index) {
5060 case QEMU_OPTION_M:
5061 machine = find_machine(optarg);
5062 if (!machine) {
5063 QEMUMachine *m;
5064 printf("Supported machines are:\n");
5065 for(m = first_machine; m != NULL; m = m->next) {
5066 printf("%-10s %s%s\n",
5067 m->name, m->desc,
5068 m->is_default ? " (default)" : "");
5070 exit(*optarg != '?');
5072 break;
5073 case QEMU_OPTION_cpu:
5074 /* hw initialization will check this */
5075 if (*optarg == '?') {
5076 /* XXX: implement xxx_cpu_list for targets that still miss it */
5077 #if defined(cpu_list)
5078 cpu_list(stdout, &fprintf);
5079 #endif
5080 exit(0);
5081 } else {
5082 cpu_model = optarg;
5084 break;
5085 case QEMU_OPTION_initrd:
5086 initrd_filename = optarg;
5087 break;
5088 case QEMU_OPTION_hda:
5089 if (cyls == 0)
5090 hda_index = drive_add(optarg, HD_ALIAS, 0);
5091 else
5092 hda_index = drive_add(optarg, HD_ALIAS
5093 ",cyls=%d,heads=%d,secs=%d%s",
5094 0, cyls, heads, secs,
5095 translation == BIOS_ATA_TRANSLATION_LBA ?
5096 ",trans=lba" :
5097 translation == BIOS_ATA_TRANSLATION_NONE ?
5098 ",trans=none" : "");
5099 break;
5100 case QEMU_OPTION_hdb:
5101 case QEMU_OPTION_hdc:
5102 case QEMU_OPTION_hdd:
5103 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5104 break;
5105 case QEMU_OPTION_drive:
5106 drive_add(NULL, "%s", optarg);
5107 break;
5108 case QEMU_OPTION_mtdblock:
5109 drive_add(optarg, MTD_ALIAS);
5110 break;
5111 case QEMU_OPTION_sd:
5112 drive_add(optarg, SD_ALIAS);
5113 break;
5114 case QEMU_OPTION_pflash:
5115 drive_add(optarg, PFLASH_ALIAS);
5116 break;
5117 case QEMU_OPTION_snapshot:
5118 snapshot = 1;
5119 break;
5120 case QEMU_OPTION_hdachs:
5122 const char *p;
5123 p = optarg;
5124 cyls = strtol(p, (char **)&p, 0);
5125 if (cyls < 1 || cyls > 16383)
5126 goto chs_fail;
5127 if (*p != ',')
5128 goto chs_fail;
5129 p++;
5130 heads = strtol(p, (char **)&p, 0);
5131 if (heads < 1 || heads > 16)
5132 goto chs_fail;
5133 if (*p != ',')
5134 goto chs_fail;
5135 p++;
5136 secs = strtol(p, (char **)&p, 0);
5137 if (secs < 1 || secs > 63)
5138 goto chs_fail;
5139 if (*p == ',') {
5140 p++;
5141 if (!strcmp(p, "none"))
5142 translation = BIOS_ATA_TRANSLATION_NONE;
5143 else if (!strcmp(p, "lba"))
5144 translation = BIOS_ATA_TRANSLATION_LBA;
5145 else if (!strcmp(p, "auto"))
5146 translation = BIOS_ATA_TRANSLATION_AUTO;
5147 else
5148 goto chs_fail;
5149 } else if (*p != '\0') {
5150 chs_fail:
5151 fprintf(stderr, "qemu: invalid physical CHS format\n");
5152 exit(1);
5154 if (hda_index != -1)
5155 snprintf(drives_opt[hda_index].opt,
5156 sizeof(drives_opt[hda_index].opt),
5157 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5158 0, cyls, heads, secs,
5159 translation == BIOS_ATA_TRANSLATION_LBA ?
5160 ",trans=lba" :
5161 translation == BIOS_ATA_TRANSLATION_NONE ?
5162 ",trans=none" : "");
5164 break;
5165 case QEMU_OPTION_numa:
5166 if (nb_numa_nodes >= MAX_NODES) {
5167 fprintf(stderr, "qemu: too many NUMA nodes\n");
5168 exit(1);
5170 numa_add(optarg);
5171 break;
5172 case QEMU_OPTION_nographic:
5173 display_type = DT_NOGRAPHIC;
5174 break;
5175 #ifdef CONFIG_CURSES
5176 case QEMU_OPTION_curses:
5177 display_type = DT_CURSES;
5178 break;
5179 #endif
5180 case QEMU_OPTION_portrait:
5181 graphic_rotate = 1;
5182 break;
5183 case QEMU_OPTION_kernel:
5184 kernel_filename = optarg;
5185 break;
5186 case QEMU_OPTION_append:
5187 kernel_cmdline = optarg;
5188 break;
5189 case QEMU_OPTION_cdrom:
5190 drive_add(optarg, CDROM_ALIAS);
5191 break;
5192 case QEMU_OPTION_boot:
5194 static const char * const params[] = {
5195 "order", "once", "menu", NULL
5197 char buf[sizeof(boot_devices)];
5198 char *standard_boot_devices;
5199 int legacy = 0;
5201 if (!strchr(optarg, '=')) {
5202 legacy = 1;
5203 pstrcpy(buf, sizeof(buf), optarg);
5204 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5205 fprintf(stderr,
5206 "qemu: unknown boot parameter '%s' in '%s'\n",
5207 buf, optarg);
5208 exit(1);
5211 if (legacy ||
5212 get_param_value(buf, sizeof(buf), "order", optarg)) {
5213 boot_devices_bitmap = parse_bootdevices(buf);
5214 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5216 if (!legacy) {
5217 if (get_param_value(buf, sizeof(buf),
5218 "once", optarg)) {
5219 boot_devices_bitmap |= parse_bootdevices(buf);
5220 standard_boot_devices = qemu_strdup(boot_devices);
5221 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5222 qemu_register_reset(restore_boot_devices,
5223 standard_boot_devices);
5225 if (get_param_value(buf, sizeof(buf),
5226 "menu", optarg)) {
5227 if (!strcmp(buf, "on")) {
5228 boot_menu = 1;
5229 } else if (!strcmp(buf, "off")) {
5230 boot_menu = 0;
5231 } else {
5232 fprintf(stderr,
5233 "qemu: invalid option value '%s'\n",
5234 buf);
5235 exit(1);
5240 break;
5241 case QEMU_OPTION_fda:
5242 case QEMU_OPTION_fdb:
5243 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5244 break;
5245 #ifdef TARGET_I386
5246 case QEMU_OPTION_no_fd_bootchk:
5247 fd_bootchk = 0;
5248 break;
5249 #endif
5250 case QEMU_OPTION_net:
5251 if (nb_net_clients >= MAX_NET_CLIENTS) {
5252 fprintf(stderr, "qemu: too many network clients\n");
5253 exit(1);
5255 net_clients[nb_net_clients] = optarg;
5256 nb_net_clients++;
5257 break;
5258 #ifdef CONFIG_SLIRP
5259 case QEMU_OPTION_tftp:
5260 legacy_tftp_prefix = optarg;
5261 break;
5262 case QEMU_OPTION_bootp:
5263 legacy_bootp_filename = optarg;
5264 break;
5265 #ifndef _WIN32
5266 case QEMU_OPTION_smb:
5267 net_slirp_smb(optarg);
5268 break;
5269 #endif
5270 case QEMU_OPTION_redir:
5271 net_slirp_redir(optarg);
5272 break;
5273 #endif
5274 case QEMU_OPTION_bt:
5275 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5276 fprintf(stderr, "qemu: too many bluetooth options\n");
5277 exit(1);
5279 bt_opts[nb_bt_opts++] = optarg;
5280 break;
5281 #ifdef HAS_AUDIO
5282 case QEMU_OPTION_audio_help:
5283 AUD_help ();
5284 exit (0);
5285 break;
5286 case QEMU_OPTION_soundhw:
5287 select_soundhw (optarg);
5288 break;
5289 #endif
5290 case QEMU_OPTION_h:
5291 help(0);
5292 break;
5293 case QEMU_OPTION_version:
5294 version();
5295 exit(0);
5296 break;
5297 case QEMU_OPTION_m: {
5298 uint64_t value;
5299 char *ptr;
5301 value = strtoul(optarg, &ptr, 10);
5302 switch (*ptr) {
5303 case 0: case 'M': case 'm':
5304 value <<= 20;
5305 break;
5306 case 'G': case 'g':
5307 value <<= 30;
5308 break;
5309 default:
5310 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5311 exit(1);
5314 /* On 32-bit hosts, QEMU is limited by virtual address space */
5315 if (value > (2047 << 20)
5316 #ifndef CONFIG_KQEMU
5317 && HOST_LONG_BITS == 32
5318 #endif
5320 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5321 exit(1);
5323 if (value != (uint64_t)(ram_addr_t)value) {
5324 fprintf(stderr, "qemu: ram size too large\n");
5325 exit(1);
5327 ram_size = value;
5328 break;
5330 case QEMU_OPTION_d:
5332 int mask;
5333 const CPULogItem *item;
5335 mask = cpu_str_to_log_mask(optarg);
5336 if (!mask) {
5337 printf("Log items (comma separated):\n");
5338 for(item = cpu_log_items; item->mask != 0; item++) {
5339 printf("%-10s %s\n", item->name, item->help);
5341 exit(1);
5343 cpu_set_log(mask);
5345 break;
5346 case QEMU_OPTION_s:
5347 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5348 break;
5349 case QEMU_OPTION_gdb:
5350 gdbstub_dev = optarg;
5351 break;
5352 case QEMU_OPTION_L:
5353 data_dir = optarg;
5354 break;
5355 case QEMU_OPTION_bios:
5356 bios_name = optarg;
5357 break;
5358 case QEMU_OPTION_singlestep:
5359 singlestep = 1;
5360 break;
5361 case QEMU_OPTION_S:
5362 autostart = 0;
5363 break;
5364 #ifndef _WIN32
5365 case QEMU_OPTION_k:
5366 keyboard_layout = optarg;
5367 break;
5368 #endif
5369 case QEMU_OPTION_localtime:
5370 rtc_utc = 0;
5371 break;
5372 case QEMU_OPTION_vga:
5373 select_vgahw (optarg);
5374 break;
5375 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5376 case QEMU_OPTION_g:
5378 const char *p;
5379 int w, h, depth;
5380 p = optarg;
5381 w = strtol(p, (char **)&p, 10);
5382 if (w <= 0) {
5383 graphic_error:
5384 fprintf(stderr, "qemu: invalid resolution or depth\n");
5385 exit(1);
5387 if (*p != 'x')
5388 goto graphic_error;
5389 p++;
5390 h = strtol(p, (char **)&p, 10);
5391 if (h <= 0)
5392 goto graphic_error;
5393 if (*p == 'x') {
5394 p++;
5395 depth = strtol(p, (char **)&p, 10);
5396 if (depth != 8 && depth != 15 && depth != 16 &&
5397 depth != 24 && depth != 32)
5398 goto graphic_error;
5399 } else if (*p == '\0') {
5400 depth = graphic_depth;
5401 } else {
5402 goto graphic_error;
5405 graphic_width = w;
5406 graphic_height = h;
5407 graphic_depth = depth;
5409 break;
5410 #endif
5411 case QEMU_OPTION_echr:
5413 char *r;
5414 term_escape_char = strtol(optarg, &r, 0);
5415 if (r == optarg)
5416 printf("Bad argument to echr\n");
5417 break;
5419 case QEMU_OPTION_monitor:
5420 monitor_device = optarg;
5421 break;
5422 case QEMU_OPTION_serial:
5423 if (serial_device_index >= MAX_SERIAL_PORTS) {
5424 fprintf(stderr, "qemu: too many serial ports\n");
5425 exit(1);
5427 serial_devices[serial_device_index] = optarg;
5428 serial_device_index++;
5429 break;
5430 case QEMU_OPTION_watchdog:
5431 i = select_watchdog(optarg);
5432 if (i > 0)
5433 exit (i == 1 ? 1 : 0);
5434 break;
5435 case QEMU_OPTION_watchdog_action:
5436 if (select_watchdog_action(optarg) == -1) {
5437 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5438 exit(1);
5440 break;
5441 case QEMU_OPTION_virtiocon:
5442 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5443 fprintf(stderr, "qemu: too many virtio consoles\n");
5444 exit(1);
5446 virtio_consoles[virtio_console_index] = optarg;
5447 virtio_console_index++;
5448 break;
5449 case QEMU_OPTION_parallel:
5450 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5451 fprintf(stderr, "qemu: too many parallel ports\n");
5452 exit(1);
5454 parallel_devices[parallel_device_index] = optarg;
5455 parallel_device_index++;
5456 break;
5457 case QEMU_OPTION_loadvm:
5458 loadvm = optarg;
5459 break;
5460 case QEMU_OPTION_full_screen:
5461 full_screen = 1;
5462 break;
5463 #ifdef CONFIG_SDL
5464 case QEMU_OPTION_no_frame:
5465 no_frame = 1;
5466 break;
5467 case QEMU_OPTION_alt_grab:
5468 alt_grab = 1;
5469 break;
5470 case QEMU_OPTION_no_quit:
5471 no_quit = 1;
5472 break;
5473 case QEMU_OPTION_sdl:
5474 display_type = DT_SDL;
5475 break;
5476 #endif
5477 case QEMU_OPTION_pidfile:
5478 pid_file = optarg;
5479 break;
5480 #ifdef TARGET_I386
5481 case QEMU_OPTION_win2k_hack:
5482 win2k_install_hack = 1;
5483 break;
5484 case QEMU_OPTION_rtc_td_hack:
5485 rtc_td_hack = 1;
5486 break;
5487 case QEMU_OPTION_acpitable:
5488 if(acpi_table_add(optarg) < 0) {
5489 fprintf(stderr, "Wrong acpi table provided\n");
5490 exit(1);
5492 break;
5493 case QEMU_OPTION_smbios:
5494 if(smbios_entry_add(optarg) < 0) {
5495 fprintf(stderr, "Wrong smbios provided\n");
5496 exit(1);
5498 break;
5499 #endif
5500 #ifdef CONFIG_KQEMU
5501 case QEMU_OPTION_enable_kqemu:
5502 kqemu_allowed = 1;
5503 break;
5504 case QEMU_OPTION_kernel_kqemu:
5505 kqemu_allowed = 2;
5506 break;
5507 #endif
5508 #ifdef CONFIG_KVM
5509 #ifdef KVM_UPSTREAM
5510 case QEMU_OPTION_enable_kvm:
5511 kvm_allowed = 1;
5512 #ifdef CONFIG_KQEMU
5513 kqemu_allowed = 0;
5514 #endif
5515 #endif
5516 break;
5517 case QEMU_OPTION_no_kvm:
5518 kvm_allowed = 0;
5519 break;
5520 case QEMU_OPTION_no_kvm_irqchip: {
5521 kvm_irqchip = 0;
5522 kvm_pit = 0;
5523 break;
5525 case QEMU_OPTION_no_kvm_pit: {
5526 kvm_pit = 0;
5527 break;
5529 case QEMU_OPTION_no_kvm_pit_reinjection: {
5530 kvm_pit_reinject = 0;
5531 break;
5533 case QEMU_OPTION_enable_nesting: {
5534 kvm_nested = 1;
5535 break;
5537 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5538 case QEMU_OPTION_pcidevice:
5539 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5540 fprintf(stderr, "Too many assigned devices\n");
5541 exit(1);
5543 assigned_devices[assigned_devices_index] = optarg;
5544 assigned_devices_index++;
5545 break;
5546 #endif
5547 #endif
5548 case QEMU_OPTION_usb:
5549 usb_enabled = 1;
5550 break;
5551 case QEMU_OPTION_usbdevice:
5552 usb_enabled = 1;
5553 if (usb_devices_index >= MAX_USB_CMDLINE) {
5554 fprintf(stderr, "Too many USB devices\n");
5555 exit(1);
5557 usb_devices[usb_devices_index] = optarg;
5558 usb_devices_index++;
5559 break;
5560 case QEMU_OPTION_smp:
5561 smp_cpus = atoi(optarg);
5562 if (smp_cpus < 1) {
5563 fprintf(stderr, "Invalid number of CPUs\n");
5564 exit(1);
5566 break;
5567 case QEMU_OPTION_vnc:
5568 display_type = DT_VNC;
5569 vnc_display = optarg;
5570 break;
5571 #ifdef TARGET_I386
5572 case QEMU_OPTION_no_acpi:
5573 acpi_enabled = 0;
5574 break;
5575 case QEMU_OPTION_no_hpet:
5576 no_hpet = 1;
5577 break;
5578 case QEMU_OPTION_balloon:
5579 if (balloon_parse(optarg) < 0) {
5580 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5581 exit(1);
5583 break;
5584 #endif
5585 case QEMU_OPTION_no_reboot:
5586 no_reboot = 1;
5587 break;
5588 case QEMU_OPTION_no_shutdown:
5589 no_shutdown = 1;
5590 break;
5591 case QEMU_OPTION_show_cursor:
5592 cursor_hide = 0;
5593 break;
5594 case QEMU_OPTION_uuid:
5595 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5596 fprintf(stderr, "Fail to parse UUID string."
5597 " Wrong format.\n");
5598 exit(1);
5600 break;
5601 #ifndef _WIN32
5602 case QEMU_OPTION_daemonize:
5603 daemonize = 1;
5604 break;
5605 #endif
5606 case QEMU_OPTION_option_rom:
5607 if (nb_option_roms >= MAX_OPTION_ROMS) {
5608 fprintf(stderr, "Too many option ROMs\n");
5609 exit(1);
5611 option_rom[nb_option_roms] = optarg;
5612 nb_option_roms++;
5613 break;
5614 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5615 case QEMU_OPTION_semihosting:
5616 semihosting_enabled = 1;
5617 break;
5618 #endif
5619 case QEMU_OPTION_tdf:
5620 time_drift_fix = 1;
5621 break;
5622 case QEMU_OPTION_kvm_shadow_memory:
5623 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5624 break;
5625 case QEMU_OPTION_mempath:
5626 mem_path = optarg;
5627 break;
5628 #ifdef MAP_POPULATE
5629 case QEMU_OPTION_mem_prealloc:
5630 mem_prealloc = !mem_prealloc;
5631 break;
5632 #endif
5633 case QEMU_OPTION_name:
5634 qemu_name = qemu_strdup(optarg);
5636 char *p = strchr(qemu_name, ',');
5637 if (p != NULL) {
5638 *p++ = 0;
5639 if (strncmp(p, "process=", 8)) {
5640 fprintf(stderr, "Unknown subargument %s to -name", p);
5641 exit(1);
5643 p += 8;
5644 set_proc_name(p);
5647 break;
5648 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5649 case QEMU_OPTION_prom_env:
5650 if (nb_prom_envs >= MAX_PROM_ENVS) {
5651 fprintf(stderr, "Too many prom variables\n");
5652 exit(1);
5654 prom_envs[nb_prom_envs] = optarg;
5655 nb_prom_envs++;
5656 break;
5657 #endif
5658 #ifdef TARGET_ARM
5659 case QEMU_OPTION_old_param:
5660 old_param = 1;
5661 break;
5662 #endif
5663 case QEMU_OPTION_clock:
5664 configure_alarms(optarg);
5665 break;
5666 case QEMU_OPTION_startdate:
5668 struct tm tm;
5669 time_t rtc_start_date;
5670 if (!strcmp(optarg, "now")) {
5671 rtc_date_offset = -1;
5672 } else {
5673 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5674 &tm.tm_year,
5675 &tm.tm_mon,
5676 &tm.tm_mday,
5677 &tm.tm_hour,
5678 &tm.tm_min,
5679 &tm.tm_sec) == 6) {
5680 /* OK */
5681 } else if (sscanf(optarg, "%d-%d-%d",
5682 &tm.tm_year,
5683 &tm.tm_mon,
5684 &tm.tm_mday) == 3) {
5685 tm.tm_hour = 0;
5686 tm.tm_min = 0;
5687 tm.tm_sec = 0;
5688 } else {
5689 goto date_fail;
5691 tm.tm_year -= 1900;
5692 tm.tm_mon--;
5693 rtc_start_date = mktimegm(&tm);
5694 if (rtc_start_date == -1) {
5695 date_fail:
5696 fprintf(stderr, "Invalid date format. Valid format are:\n"
5697 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5698 exit(1);
5700 rtc_date_offset = time(NULL) - rtc_start_date;
5703 break;
5704 case QEMU_OPTION_tb_size:
5705 tb_size = strtol(optarg, NULL, 0);
5706 if (tb_size < 0)
5707 tb_size = 0;
5708 break;
5709 case QEMU_OPTION_icount:
5710 use_icount = 1;
5711 if (strcmp(optarg, "auto") == 0) {
5712 icount_time_shift = -1;
5713 } else {
5714 icount_time_shift = strtol(optarg, NULL, 0);
5716 break;
5717 case QEMU_OPTION_incoming:
5718 incoming = optarg;
5719 break;
5720 #ifndef _WIN32
5721 case QEMU_OPTION_chroot:
5722 chroot_dir = optarg;
5723 break;
5724 case QEMU_OPTION_runas:
5725 run_as = optarg;
5726 break;
5727 case QEMU_OPTION_nvram:
5728 nvram = optarg;
5729 break;
5730 #endif
5731 #ifdef CONFIG_XEN
5732 case QEMU_OPTION_xen_domid:
5733 xen_domid = atoi(optarg);
5734 break;
5735 case QEMU_OPTION_xen_create:
5736 xen_mode = XEN_CREATE;
5737 break;
5738 case QEMU_OPTION_xen_attach:
5739 xen_mode = XEN_ATTACH;
5740 break;
5741 #endif
5746 /* If no data_dir is specified then try to find it relative to the
5747 executable path. */
5748 if (!data_dir) {
5749 data_dir = find_datadir(argv[0]);
5751 /* If all else fails use the install patch specified when building. */
5752 if (!data_dir) {
5753 data_dir = CONFIG_QEMU_SHAREDIR;
5756 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5757 if (kvm_allowed && kqemu_allowed) {
5758 fprintf(stderr,
5759 "You can not enable both KVM and kqemu at the same time\n");
5760 exit(1);
5762 #endif
5764 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5765 if (smp_cpus > machine->max_cpus) {
5766 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5767 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5768 machine->max_cpus);
5769 exit(1);
5772 if (display_type == DT_NOGRAPHIC) {
5773 if (serial_device_index == 0)
5774 serial_devices[0] = "stdio";
5775 if (parallel_device_index == 0)
5776 parallel_devices[0] = "null";
5777 if (strncmp(monitor_device, "vc", 2) == 0)
5778 monitor_device = "stdio";
5781 #ifndef _WIN32
5782 if (daemonize) {
5783 pid_t pid;
5785 if (pipe(fds) == -1)
5786 exit(1);
5788 pid = fork();
5789 if (pid > 0) {
5790 uint8_t status;
5791 ssize_t len;
5793 close(fds[1]);
5795 again:
5796 len = read(fds[0], &status, 1);
5797 if (len == -1 && (errno == EINTR))
5798 goto again;
5800 if (len != 1)
5801 exit(1);
5802 else if (status == 1) {
5803 fprintf(stderr, "Could not acquire pidfile\n");
5804 exit(1);
5805 } else
5806 exit(0);
5807 } else if (pid < 0)
5808 exit(1);
5810 setsid();
5812 pid = fork();
5813 if (pid > 0)
5814 exit(0);
5815 else if (pid < 0)
5816 exit(1);
5818 umask(027);
5820 signal(SIGTSTP, SIG_IGN);
5821 signal(SIGTTOU, SIG_IGN);
5822 signal(SIGTTIN, SIG_IGN);
5825 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5826 if (daemonize) {
5827 uint8_t status = 1;
5828 write(fds[1], &status, 1);
5829 } else
5830 fprintf(stderr, "Could not acquire pid file\n");
5831 exit(1);
5833 #endif
5835 #ifdef CONFIG_KQEMU
5836 if (smp_cpus > 1)
5837 kqemu_allowed = 0;
5838 #endif
5839 if (qemu_init_main_loop()) {
5840 fprintf(stderr, "qemu_init_main_loop failed\n");
5841 exit(1);
5843 linux_boot = (kernel_filename != NULL);
5845 if (!linux_boot && *kernel_cmdline != '\0') {
5846 fprintf(stderr, "-append only allowed with -kernel option\n");
5847 exit(1);
5850 if (!linux_boot && initrd_filename != NULL) {
5851 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5852 exit(1);
5855 setvbuf(stdout, NULL, _IOLBF, 0);
5857 init_timers();
5858 if (init_timer_alarm() < 0) {
5859 fprintf(stderr, "could not initialize alarm timer\n");
5860 exit(1);
5862 if (use_icount && icount_time_shift < 0) {
5863 use_icount = 2;
5864 /* 125MIPS seems a reasonable initial guess at the guest speed.
5865 It will be corrected fairly quickly anyway. */
5866 icount_time_shift = 3;
5867 init_icount_adjust();
5870 #ifdef _WIN32
5871 socket_init();
5872 #endif
5874 /* init network clients */
5875 if (nb_net_clients == 0) {
5876 /* if no clients, we use a default config */
5877 net_clients[nb_net_clients++] = "nic";
5878 #ifdef CONFIG_SLIRP
5879 net_clients[nb_net_clients++] = "user";
5880 #endif
5883 for(i = 0;i < nb_net_clients; i++) {
5884 if (net_client_parse(net_clients[i]) < 0)
5885 exit(1);
5888 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5889 net_set_boot_mask(net_boot);
5891 net_client_check();
5893 /* init the bluetooth world */
5894 for (i = 0; i < nb_bt_opts; i++)
5895 if (bt_parse(bt_opts[i]))
5896 exit(1);
5898 /* init the memory */
5899 if (ram_size == 0)
5900 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5902 #ifdef CONFIG_KQEMU
5903 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5904 guest ram allocation. It needs to go away. */
5905 if (kqemu_allowed) {
5906 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
5907 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5908 if (!kqemu_phys_ram_base) {
5909 fprintf(stderr, "Could not allocate physical memory\n");
5910 exit(1);
5913 #endif
5915 /* init the dynamic translator */
5916 cpu_exec_init_all(tb_size * 1024 * 1024);
5918 bdrv_init();
5920 /* we always create the cdrom drive, even if no disk is there */
5922 if (nb_drives_opt < MAX_DRIVES)
5923 drive_add(NULL, CDROM_ALIAS);
5925 /* we always create at least one floppy */
5927 if (nb_drives_opt < MAX_DRIVES)
5928 drive_add(NULL, FD_ALIAS, 0);
5930 /* we always create one sd slot, even if no card is in it */
5932 if (nb_drives_opt < MAX_DRIVES)
5933 drive_add(NULL, SD_ALIAS);
5935 /* open the virtual block devices */
5937 for(i = 0; i < nb_drives_opt; i++)
5938 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5939 exit(1);
5941 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5942 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5944 #ifndef _WIN32
5945 /* must be after terminal init, SDL library changes signal handlers */
5946 sighandler_setup();
5947 #endif
5949 /* Maintain compatibility with multiple stdio monitors */
5950 if (!strcmp(monitor_device,"stdio")) {
5951 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5952 const char *devname = serial_devices[i];
5953 if (devname && !strcmp(devname,"mon:stdio")) {
5954 monitor_device = NULL;
5955 break;
5956 } else if (devname && !strcmp(devname,"stdio")) {
5957 monitor_device = NULL;
5958 serial_devices[i] = "mon:stdio";
5959 break;
5964 if (nb_numa_nodes > 0) {
5965 int i;
5967 if (nb_numa_nodes > smp_cpus) {
5968 nb_numa_nodes = smp_cpus;
5971 /* If no memory size if given for any node, assume the default case
5972 * and distribute the available memory equally across all nodes
5974 for (i = 0; i < nb_numa_nodes; i++) {
5975 if (node_mem[i] != 0)
5976 break;
5978 if (i == nb_numa_nodes) {
5979 uint64_t usedmem = 0;
5981 /* On Linux, the each node's border has to be 8MB aligned,
5982 * the final node gets the rest.
5984 for (i = 0; i < nb_numa_nodes - 1; i++) {
5985 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5986 usedmem += node_mem[i];
5988 node_mem[i] = ram_size - usedmem;
5991 for (i = 0; i < nb_numa_nodes; i++) {
5992 if (node_cpumask[i] != 0)
5993 break;
5995 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5996 * must cope with this anyway, because there are BIOSes out there in
5997 * real machines which also use this scheme.
5999 if (i == nb_numa_nodes) {
6000 for (i = 0; i < smp_cpus; i++) {
6001 node_cpumask[i % nb_numa_nodes] |= 1 << i;
6006 if (kvm_enabled()) {
6007 int ret;
6009 ret = kvm_init(smp_cpus);
6010 if (ret < 0) {
6011 #if defined(KVM_UPSTREAM) || defined(NO_CPU_EMULATION)
6012 fprintf(stderr, "failed to initialize KVM\n");
6013 exit(1);
6014 #endif
6015 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
6016 kvm_allowed = 0;
6020 if (monitor_device) {
6021 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
6022 if (!monitor_hd) {
6023 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6024 exit(1);
6028 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6029 const char *devname = serial_devices[i];
6030 if (devname && strcmp(devname, "none")) {
6031 char label[32];
6032 snprintf(label, sizeof(label), "serial%d", i);
6033 serial_hds[i] = qemu_chr_open(label, devname, NULL);
6034 if (!serial_hds[i]) {
6035 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6036 devname);
6037 exit(1);
6042 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6043 const char *devname = parallel_devices[i];
6044 if (devname && strcmp(devname, "none")) {
6045 char label[32];
6046 snprintf(label, sizeof(label), "parallel%d", i);
6047 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
6048 if (!parallel_hds[i]) {
6049 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6050 devname);
6051 exit(1);
6056 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6057 const char *devname = virtio_consoles[i];
6058 if (devname && strcmp(devname, "none")) {
6059 char label[32];
6060 snprintf(label, sizeof(label), "virtcon%d", i);
6061 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
6062 if (!virtcon_hds[i]) {
6063 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
6064 devname);
6065 exit(1);
6070 module_call_init(MODULE_INIT_DEVICE);
6072 if (machine->compat_props) {
6073 qdev_prop_register_compat(machine->compat_props);
6075 machine->init(ram_size, boot_devices,
6076 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6079 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6080 for (i = 0; i < nb_numa_nodes; i++) {
6081 if (node_cpumask[i] & (1 << env->cpu_index)) {
6082 env->numa_node = i;
6087 current_machine = machine;
6089 /* init USB devices */
6090 if (usb_enabled) {
6091 for(i = 0; i < usb_devices_index; i++) {
6092 if (usb_device_add(usb_devices[i], 0) < 0) {
6093 fprintf(stderr, "Warning: could not add USB device %s\n",
6094 usb_devices[i]);
6099 if (!display_state)
6100 dumb_display_init();
6101 /* just use the first displaystate for the moment */
6102 ds = display_state;
6104 if (display_type == DT_DEFAULT) {
6105 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6106 display_type = DT_SDL;
6107 #else
6108 display_type = DT_VNC;
6109 vnc_display = "localhost:0,to=99";
6110 show_vnc_port = 1;
6111 #endif
6115 switch (display_type) {
6116 case DT_NOGRAPHIC:
6117 break;
6118 #if defined(CONFIG_CURSES)
6119 case DT_CURSES:
6120 curses_display_init(ds, full_screen);
6121 break;
6122 #endif
6123 #if defined(CONFIG_SDL)
6124 case DT_SDL:
6125 sdl_display_init(ds, full_screen, no_frame);
6126 break;
6127 #elif defined(CONFIG_COCOA)
6128 case DT_SDL:
6129 cocoa_display_init(ds, full_screen);
6130 break;
6131 #endif
6132 case DT_VNC:
6133 vnc_display_init(ds);
6134 if (vnc_display_open(ds, vnc_display) < 0)
6135 exit(1);
6137 if (show_vnc_port) {
6138 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6140 break;
6141 default:
6142 break;
6144 dpy_resize(ds);
6146 dcl = ds->listeners;
6147 while (dcl != NULL) {
6148 if (dcl->dpy_refresh != NULL) {
6149 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6150 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6152 dcl = dcl->next;
6155 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6156 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6157 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6160 text_consoles_set_display(display_state);
6161 qemu_chr_initial_reset();
6163 if (monitor_device && monitor_hd)
6164 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6166 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6167 const char *devname = serial_devices[i];
6168 if (devname && strcmp(devname, "none")) {
6169 if (strstart(devname, "vc", 0))
6170 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6174 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6175 const char *devname = parallel_devices[i];
6176 if (devname && strcmp(devname, "none")) {
6177 if (strstart(devname, "vc", 0))
6178 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6182 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6183 const char *devname = virtio_consoles[i];
6184 if (virtcon_hds[i] && devname) {
6185 if (strstart(devname, "vc", 0))
6186 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6190 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6191 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6192 gdbstub_dev);
6193 exit(1);
6196 if (loadvm)
6197 do_loadvm(cur_mon, loadvm);
6199 if (incoming) {
6200 autostart = 0;
6201 qemu_start_incoming_migration(incoming);
6204 if (autostart)
6205 vm_start();
6207 #ifndef _WIN32
6208 if (daemonize) {
6209 uint8_t status = 0;
6210 ssize_t len;
6212 again1:
6213 len = write(fds[1], &status, 1);
6214 if (len == -1 && (errno == EINTR))
6215 goto again1;
6217 if (len != 1)
6218 exit(1);
6220 chdir("/");
6221 TFR(fd = open("/dev/null", O_RDWR));
6222 if (fd == -1)
6223 exit(1);
6226 if (run_as) {
6227 pwd = getpwnam(run_as);
6228 if (!pwd) {
6229 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6230 exit(1);
6234 if (chroot_dir) {
6235 if (chroot(chroot_dir) < 0) {
6236 fprintf(stderr, "chroot failed\n");
6237 exit(1);
6239 chdir("/");
6242 if (run_as) {
6243 if (setgid(pwd->pw_gid) < 0) {
6244 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6245 exit(1);
6247 if (setuid(pwd->pw_uid) < 0) {
6248 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6249 exit(1);
6251 if (setuid(0) != -1) {
6252 fprintf(stderr, "Dropping privileges failed\n");
6253 exit(1);
6257 if (daemonize) {
6258 dup2(fd, 0);
6259 dup2(fd, 1);
6260 dup2(fd, 2);
6262 close(fd);
6264 #endif
6266 main_loop();
6267 quit_timers();
6268 net_cleanup();
6270 return 0;