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
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
34 /* Needed early to override system queue definitions on BSD */
35 #include "sys-queue.h"
40 #include <sys/times.h>
44 #include <sys/ioctl.h>
45 #include <sys/resource.h>
46 #include <sys/socket.h>
47 #include <netinet/in.h>
49 #if defined(__NetBSD__)
50 #include <net/if_tap.h>
53 #include <linux/if_tun.h>
55 #include <arpa/inet.h>
58 #include <sys/select.h>
61 #if defined(__FreeBSD__) || defined(__DragonFly__)
66 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
67 #include <freebsd/stdlib.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> */
80 #include <linux/ppdev.h>
81 #include <linux/parport.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>
101 #if defined(__OpenBSD__)
105 #if defined(CONFIG_VDE)
106 #include <libvdeplug.h>
111 #include <mmsystem.h>
115 #if defined(__APPLE__) || defined(main)
117 int qemu_main(int argc, char **argv, char **envp);
118 int main(int argc, char **argv)
120 return qemu_main(argc, argv, NULL);
123 #define main qemu_main
125 #endif /* CONFIG_SDL */
129 #define main qemu_main
130 #endif /* CONFIG_COCOA */
133 #include "hw/boards.h"
135 #include "hw/pcmcia.h"
137 #include "hw/audiodev.h"
141 #include "hw/watchdog.h"
142 #include "hw/smbios.h"
151 #include "qemu-timer.h"
152 #include "qemu-char.h"
153 #include "cache-utils.h"
156 #include "audio/audio.h"
157 #include "migration.h"
160 #include "qemu-option.h"
161 #include "qemu-config.h"
165 #include "exec-all.h"
167 #include "qemu_socket.h"
169 #include "slirp/libslirp.h"
172 //#define DEBUG_SLIRP
174 #define DEFAULT_RAM_SIZE 128
176 static const char *data_dir;
177 const char *bios_name = NULL;
178 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
179 to store the VM snapshots */
180 struct drivelist drives = TAILQ_HEAD_INITIALIZER(drives);
181 struct driveoptlist driveopts = TAILQ_HEAD_INITIALIZER(driveopts);
182 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
183 static DisplayState *display_state;
184 DisplayType display_type = DT_DEFAULT;
185 const char* keyboard_layout = NULL;
186 int64_t ticks_per_sec;
189 NICInfo nd_table[MAX_NICS];
192 static int rtc_utc = 1;
193 static int rtc_date_offset = -1; /* -1 means no change */
194 int vga_interface_type = VGA_CIRRUS;
196 int graphic_width = 1024;
197 int graphic_height = 768;
198 int graphic_depth = 8;
200 int graphic_width = 800;
201 int graphic_height = 600;
202 int graphic_depth = 15;
204 static int full_screen = 0;
206 static int no_frame = 0;
209 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
210 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
211 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
213 int win2k_install_hack = 0;
220 const char *vnc_display;
221 int acpi_enabled = 1;
223 int virtio_balloon = 1;
224 const char *virtio_balloon_devaddr;
229 int graphic_rotate = 0;
230 uint8_t irq0override = 1;
234 WatchdogTimerModel *watchdog = NULL;
235 int watchdog_action = WDT_RESET;
236 const char *option_rom[MAX_OPTION_ROMS];
238 int semihosting_enabled = 0;
242 const char *qemu_name;
244 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
245 unsigned int nb_prom_envs = 0;
246 const char *prom_envs[MAX_PROM_ENVS];
251 uint64_t node_mem[MAX_NODES];
252 uint64_t node_cpumask[MAX_NODES];
254 static CPUState *cur_cpu;
255 static CPUState *next_cpu;
256 static int timer_alarm_pending = 1;
257 /* Conversion factor from emulated instructions to virtual clock ticks. */
258 static int icount_time_shift;
259 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
260 #define MAX_ICOUNT_SHIFT 10
261 /* Compensate for varying guest execution speed. */
262 static int64_t qemu_icount_bias;
263 static QEMUTimer *icount_rt_timer;
264 static QEMUTimer *icount_vm_timer;
265 static QEMUTimer *nographic_timer;
267 uint8_t qemu_uuid[16];
269 static QEMUBootSetHandler *boot_set_handler;
270 static void *boot_set_opaque;
272 /***********************************************************/
273 /* x86 ISA bus support */
275 target_phys_addr_t isa_mem_base = 0;
278 /***********************************************************/
279 void hw_error(const char *fmt, ...)
285 fprintf(stderr, "qemu: hardware error: ");
286 vfprintf(stderr, fmt, ap);
287 fprintf(stderr, "\n");
288 for(env = first_cpu; env != NULL; env = env->next_cpu) {
289 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
291 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
293 cpu_dump_state(env, stderr, fprintf, 0);
300 static void set_proc_name(const char *s)
302 #if defined(__linux__) && defined(PR_SET_NAME)
306 name[sizeof(name) - 1] = 0;
307 strncpy(name, s, sizeof(name));
308 /* Could rewrite argv[0] too, but that's a bit more complicated.
309 This simple way is enough for `top'. */
310 prctl(PR_SET_NAME, name);
317 static QEMUBalloonEvent *qemu_balloon_event;
318 void *qemu_balloon_event_opaque;
320 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
322 qemu_balloon_event = func;
323 qemu_balloon_event_opaque = opaque;
326 void qemu_balloon(ram_addr_t target)
328 if (qemu_balloon_event)
329 qemu_balloon_event(qemu_balloon_event_opaque, target);
332 ram_addr_t qemu_balloon_status(void)
334 if (qemu_balloon_event)
335 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
339 /***********************************************************/
342 static QEMUPutKBDEvent *qemu_put_kbd_event;
343 static void *qemu_put_kbd_event_opaque;
344 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
345 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
347 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
349 qemu_put_kbd_event_opaque = opaque;
350 qemu_put_kbd_event = func;
353 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
354 void *opaque, int absolute,
357 QEMUPutMouseEntry *s, *cursor;
359 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
361 s->qemu_put_mouse_event = func;
362 s->qemu_put_mouse_event_opaque = opaque;
363 s->qemu_put_mouse_event_absolute = absolute;
364 s->qemu_put_mouse_event_name = qemu_strdup(name);
367 if (!qemu_put_mouse_event_head) {
368 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
372 cursor = qemu_put_mouse_event_head;
373 while (cursor->next != NULL)
374 cursor = cursor->next;
377 qemu_put_mouse_event_current = s;
382 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
384 QEMUPutMouseEntry *prev = NULL, *cursor;
386 if (!qemu_put_mouse_event_head || entry == NULL)
389 cursor = qemu_put_mouse_event_head;
390 while (cursor != NULL && cursor != entry) {
392 cursor = cursor->next;
395 if (cursor == NULL) // does not exist or list empty
397 else if (prev == NULL) { // entry is head
398 qemu_put_mouse_event_head = cursor->next;
399 if (qemu_put_mouse_event_current == entry)
400 qemu_put_mouse_event_current = cursor->next;
401 qemu_free(entry->qemu_put_mouse_event_name);
406 prev->next = entry->next;
408 if (qemu_put_mouse_event_current == entry)
409 qemu_put_mouse_event_current = prev;
411 qemu_free(entry->qemu_put_mouse_event_name);
415 void kbd_put_keycode(int keycode)
417 if (qemu_put_kbd_event) {
418 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
422 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
424 QEMUPutMouseEvent *mouse_event;
425 void *mouse_event_opaque;
428 if (!qemu_put_mouse_event_current) {
433 qemu_put_mouse_event_current->qemu_put_mouse_event;
435 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
438 if (graphic_rotate) {
439 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
442 width = graphic_width - 1;
443 mouse_event(mouse_event_opaque,
444 width - dy, dx, dz, buttons_state);
446 mouse_event(mouse_event_opaque,
447 dx, dy, dz, buttons_state);
451 int kbd_mouse_is_absolute(void)
453 if (!qemu_put_mouse_event_current)
456 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
459 void do_info_mice(Monitor *mon)
461 QEMUPutMouseEntry *cursor;
464 if (!qemu_put_mouse_event_head) {
465 monitor_printf(mon, "No mouse devices connected\n");
469 monitor_printf(mon, "Mouse devices available:\n");
470 cursor = qemu_put_mouse_event_head;
471 while (cursor != NULL) {
472 monitor_printf(mon, "%c Mouse #%d: %s\n",
473 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
474 index, cursor->qemu_put_mouse_event_name);
476 cursor = cursor->next;
480 void do_mouse_set(Monitor *mon, int index)
482 QEMUPutMouseEntry *cursor;
485 if (!qemu_put_mouse_event_head) {
486 monitor_printf(mon, "No mouse devices connected\n");
490 cursor = qemu_put_mouse_event_head;
491 while (cursor != NULL && index != i) {
493 cursor = cursor->next;
497 qemu_put_mouse_event_current = cursor;
499 monitor_printf(mon, "Mouse at given index not found\n");
502 /* compute with 96 bit intermediate result: (a*b)/c */
503 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
508 #ifdef HOST_WORDS_BIGENDIAN
518 rl = (uint64_t)u.l.low * (uint64_t)b;
519 rh = (uint64_t)u.l.high * (uint64_t)b;
522 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
526 /***********************************************************/
527 /* real time host monotonic timer */
529 #define QEMU_TIMER_BASE 1000000000LL
533 static int64_t clock_freq;
535 static void init_get_clock(void)
539 ret = QueryPerformanceFrequency(&freq);
541 fprintf(stderr, "Could not calibrate ticks\n");
544 clock_freq = freq.QuadPart;
547 static int64_t get_clock(void)
550 QueryPerformanceCounter(&ti);
551 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
556 static int use_rt_clock;
558 static void init_get_clock(void)
561 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
562 || defined(__DragonFly__)
565 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
572 static int64_t get_clock(void)
574 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
575 || defined(__DragonFly__)
578 clock_gettime(CLOCK_MONOTONIC, &ts);
579 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
583 /* XXX: using gettimeofday leads to problems if the date
584 changes, so it should be avoided. */
586 gettimeofday(&tv, NULL);
587 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
592 /* Return the virtual CPU time, based on the instruction counter. */
593 static int64_t cpu_get_icount(void)
596 CPUState *env = cpu_single_env;;
597 icount = qemu_icount;
600 fprintf(stderr, "Bad clock read\n");
601 icount -= (env->icount_decr.u16.low + env->icount_extra);
603 return qemu_icount_bias + (icount << icount_time_shift);
606 /***********************************************************/
607 /* guest cycle counter */
609 static int64_t cpu_ticks_prev;
610 static int64_t cpu_ticks_offset;
611 static int64_t cpu_clock_offset;
612 static int cpu_ticks_enabled;
614 /* return the host CPU cycle counter and handle stop/restart */
615 int64_t cpu_get_ticks(void)
618 return cpu_get_icount();
620 if (!cpu_ticks_enabled) {
621 return cpu_ticks_offset;
624 ticks = cpu_get_real_ticks();
625 if (cpu_ticks_prev > ticks) {
626 /* Note: non increasing ticks may happen if the host uses
628 cpu_ticks_offset += cpu_ticks_prev - ticks;
630 cpu_ticks_prev = ticks;
631 return ticks + cpu_ticks_offset;
635 /* return the host CPU monotonic timer and handle stop/restart */
636 static int64_t cpu_get_clock(void)
639 if (!cpu_ticks_enabled) {
640 return cpu_clock_offset;
643 return ti + cpu_clock_offset;
647 /* enable cpu_get_ticks() */
648 void cpu_enable_ticks(void)
650 if (!cpu_ticks_enabled) {
651 cpu_ticks_offset -= cpu_get_real_ticks();
652 cpu_clock_offset -= get_clock();
653 cpu_ticks_enabled = 1;
657 /* disable cpu_get_ticks() : the clock is stopped. You must not call
658 cpu_get_ticks() after that. */
659 void cpu_disable_ticks(void)
661 if (cpu_ticks_enabled) {
662 cpu_ticks_offset = cpu_get_ticks();
663 cpu_clock_offset = cpu_get_clock();
664 cpu_ticks_enabled = 0;
668 /***********************************************************/
671 #define QEMU_TIMER_REALTIME 0
672 #define QEMU_TIMER_VIRTUAL 1
676 /* XXX: add frequency */
684 struct QEMUTimer *next;
687 struct qemu_alarm_timer {
691 int (*start)(struct qemu_alarm_timer *t);
692 void (*stop)(struct qemu_alarm_timer *t);
693 void (*rearm)(struct qemu_alarm_timer *t);
697 #define ALARM_FLAG_DYNTICKS 0x1
698 #define ALARM_FLAG_EXPIRED 0x2
700 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
702 return t && (t->flags & ALARM_FLAG_DYNTICKS);
705 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
707 if (!alarm_has_dynticks(t))
713 /* TODO: MIN_TIMER_REARM_US should be optimized */
714 #define MIN_TIMER_REARM_US 250
716 static struct qemu_alarm_timer *alarm_timer;
720 struct qemu_alarm_win32 {
723 } alarm_win32_data = {0, -1};
725 static int win32_start_timer(struct qemu_alarm_timer *t);
726 static void win32_stop_timer(struct qemu_alarm_timer *t);
727 static void win32_rearm_timer(struct qemu_alarm_timer *t);
731 static int unix_start_timer(struct qemu_alarm_timer *t);
732 static void unix_stop_timer(struct qemu_alarm_timer *t);
736 static int dynticks_start_timer(struct qemu_alarm_timer *t);
737 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
738 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
740 static int hpet_start_timer(struct qemu_alarm_timer *t);
741 static void hpet_stop_timer(struct qemu_alarm_timer *t);
743 static int rtc_start_timer(struct qemu_alarm_timer *t);
744 static void rtc_stop_timer(struct qemu_alarm_timer *t);
746 #endif /* __linux__ */
750 /* Correlation between real and virtual time is always going to be
751 fairly approximate, so ignore small variation.
752 When the guest is idle real and virtual time will be aligned in
754 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
756 static void icount_adjust(void)
761 static int64_t last_delta;
762 /* If the VM is not running, then do nothing. */
766 cur_time = cpu_get_clock();
767 cur_icount = qemu_get_clock(vm_clock);
768 delta = cur_icount - cur_time;
769 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
771 && last_delta + ICOUNT_WOBBLE < delta * 2
772 && icount_time_shift > 0) {
773 /* The guest is getting too far ahead. Slow time down. */
777 && last_delta - ICOUNT_WOBBLE > delta * 2
778 && icount_time_shift < MAX_ICOUNT_SHIFT) {
779 /* The guest is getting too far behind. Speed time up. */
783 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
786 static void icount_adjust_rt(void * opaque)
788 qemu_mod_timer(icount_rt_timer,
789 qemu_get_clock(rt_clock) + 1000);
793 static void icount_adjust_vm(void * opaque)
795 qemu_mod_timer(icount_vm_timer,
796 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
800 static void init_icount_adjust(void)
802 /* Have both realtime and virtual time triggers for speed adjustment.
803 The realtime trigger catches emulated time passing too slowly,
804 the virtual time trigger catches emulated time passing too fast.
805 Realtime triggers occur even when idle, so use them less frequently
807 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
808 qemu_mod_timer(icount_rt_timer,
809 qemu_get_clock(rt_clock) + 1000);
810 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
811 qemu_mod_timer(icount_vm_timer,
812 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
815 static struct qemu_alarm_timer alarm_timers[] = {
818 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
819 dynticks_stop_timer, dynticks_rearm_timer, NULL},
820 /* HPET - if available - is preferred */
821 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
822 /* ...otherwise try RTC */
823 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
825 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
827 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
828 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
829 {"win32", 0, win32_start_timer,
830 win32_stop_timer, NULL, &alarm_win32_data},
835 static void show_available_alarms(void)
839 printf("Available alarm timers, in order of precedence:\n");
840 for (i = 0; alarm_timers[i].name; i++)
841 printf("%s\n", alarm_timers[i].name);
844 static void configure_alarms(char const *opt)
848 int count = ARRAY_SIZE(alarm_timers) - 1;
851 struct qemu_alarm_timer tmp;
853 if (!strcmp(opt, "?")) {
854 show_available_alarms();
860 /* Reorder the array */
861 name = strtok(arg, ",");
863 for (i = 0; i < count && alarm_timers[i].name; i++) {
864 if (!strcmp(alarm_timers[i].name, name))
869 fprintf(stderr, "Unknown clock %s\n", name);
878 tmp = alarm_timers[i];
879 alarm_timers[i] = alarm_timers[cur];
880 alarm_timers[cur] = tmp;
884 name = strtok(NULL, ",");
890 /* Disable remaining timers */
891 for (i = cur; i < count; i++)
892 alarm_timers[i].name = NULL;
894 show_available_alarms();
902 static QEMUTimer *active_timers[2];
904 static QEMUClock *qemu_new_clock(int type)
907 clock = qemu_mallocz(sizeof(QEMUClock));
912 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
916 ts = qemu_mallocz(sizeof(QEMUTimer));
923 void qemu_free_timer(QEMUTimer *ts)
928 /* stop a timer, but do not dealloc it */
929 void qemu_del_timer(QEMUTimer *ts)
933 /* NOTE: this code must be signal safe because
934 qemu_timer_expired() can be called from a signal. */
935 pt = &active_timers[ts->clock->type];
948 /* modify the current timer so that it will be fired when current_time
949 >= expire_time. The corresponding callback will be called. */
950 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
956 /* add the timer in the sorted list */
957 /* NOTE: this code must be signal safe because
958 qemu_timer_expired() can be called from a signal. */
959 pt = &active_timers[ts->clock->type];
964 if (t->expire_time > expire_time)
968 ts->expire_time = expire_time;
972 /* Rearm if necessary */
973 if (pt == &active_timers[ts->clock->type]) {
974 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
975 qemu_rearm_alarm_timer(alarm_timer);
977 /* Interrupt execution to force deadline recalculation. */
983 int qemu_timer_pending(QEMUTimer *ts)
986 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
993 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
997 return (timer_head->expire_time <= current_time);
1000 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1006 if (!ts || ts->expire_time > current_time)
1008 /* remove timer from the list before calling the callback */
1009 *ptimer_head = ts->next;
1012 /* run the callback (the timer list can be modified) */
1017 int64_t qemu_get_clock(QEMUClock *clock)
1019 switch(clock->type) {
1020 case QEMU_TIMER_REALTIME:
1021 return get_clock() / 1000000;
1023 case QEMU_TIMER_VIRTUAL:
1025 return cpu_get_icount();
1027 return cpu_get_clock();
1032 static void init_timers(void)
1035 ticks_per_sec = QEMU_TIMER_BASE;
1036 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1037 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1041 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1043 uint64_t expire_time;
1045 if (qemu_timer_pending(ts)) {
1046 expire_time = ts->expire_time;
1050 qemu_put_be64(f, expire_time);
1053 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1055 uint64_t expire_time;
1057 expire_time = qemu_get_be64(f);
1058 if (expire_time != -1) {
1059 qemu_mod_timer(ts, expire_time);
1065 static void timer_save(QEMUFile *f, void *opaque)
1067 if (cpu_ticks_enabled) {
1068 hw_error("cannot save state if virtual timers are running");
1070 qemu_put_be64(f, cpu_ticks_offset);
1071 qemu_put_be64(f, ticks_per_sec);
1072 qemu_put_be64(f, cpu_clock_offset);
1075 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1077 if (version_id != 1 && version_id != 2)
1079 if (cpu_ticks_enabled) {
1082 cpu_ticks_offset=qemu_get_be64(f);
1083 ticks_per_sec=qemu_get_be64(f);
1084 if (version_id == 2) {
1085 cpu_clock_offset=qemu_get_be64(f);
1090 static void qemu_event_increment(void);
1093 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1094 DWORD_PTR dwUser, DWORD_PTR dw1,
1097 static void host_alarm_handler(int host_signum)
1101 #define DISP_FREQ 1000
1103 static int64_t delta_min = INT64_MAX;
1104 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1106 ti = qemu_get_clock(vm_clock);
1107 if (last_clock != 0) {
1108 delta = ti - last_clock;
1109 if (delta < delta_min)
1111 if (delta > delta_max)
1114 if (++count == DISP_FREQ) {
1115 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1116 muldiv64(delta_min, 1000000, ticks_per_sec),
1117 muldiv64(delta_max, 1000000, ticks_per_sec),
1118 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1119 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1121 delta_min = INT64_MAX;
1129 if (alarm_has_dynticks(alarm_timer) ||
1131 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1132 qemu_get_clock(vm_clock))) ||
1133 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1134 qemu_get_clock(rt_clock))) {
1135 qemu_event_increment();
1136 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1138 #ifndef CONFIG_IOTHREAD
1140 /* stop the currently executing cpu because a timer occured */
1143 if (next_cpu->kqemu_enabled) {
1144 kqemu_cpu_interrupt(next_cpu);
1149 timer_alarm_pending = 1;
1150 qemu_notify_event();
1154 static int64_t qemu_next_deadline(void)
1158 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1159 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1160 qemu_get_clock(vm_clock);
1162 /* To avoid problems with overflow limit this to 2^32. */
1172 #if defined(__linux__) || defined(_WIN32)
1173 static uint64_t qemu_next_deadline_dyntick(void)
1181 delta = (qemu_next_deadline() + 999) / 1000;
1183 if (active_timers[QEMU_TIMER_REALTIME]) {
1184 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1185 qemu_get_clock(rt_clock))*1000;
1186 if (rtdelta < delta)
1190 if (delta < MIN_TIMER_REARM_US)
1191 delta = MIN_TIMER_REARM_US;
1199 /* Sets a specific flag */
1200 static int fcntl_setfl(int fd, int flag)
1204 flags = fcntl(fd, F_GETFL);
1208 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1214 #if defined(__linux__)
1216 #define RTC_FREQ 1024
1218 static void enable_sigio_timer(int fd)
1220 struct sigaction act;
1223 sigfillset(&act.sa_mask);
1225 act.sa_handler = host_alarm_handler;
1227 sigaction(SIGIO, &act, NULL);
1228 fcntl_setfl(fd, O_ASYNC);
1229 fcntl(fd, F_SETOWN, getpid());
1232 static int hpet_start_timer(struct qemu_alarm_timer *t)
1234 struct hpet_info info;
1237 fd = open("/dev/hpet", O_RDONLY);
1242 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1244 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1245 "error, but for better emulation accuracy type:\n"
1246 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1250 /* Check capabilities */
1251 r = ioctl(fd, HPET_INFO, &info);
1255 /* Enable periodic mode */
1256 r = ioctl(fd, HPET_EPI, 0);
1257 if (info.hi_flags && (r < 0))
1260 /* Enable interrupt */
1261 r = ioctl(fd, HPET_IE_ON, 0);
1265 enable_sigio_timer(fd);
1266 t->priv = (void *)(long)fd;
1274 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1276 int fd = (long)t->priv;
1281 static int rtc_start_timer(struct qemu_alarm_timer *t)
1284 unsigned long current_rtc_freq = 0;
1286 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1289 ioctl(rtc_fd, RTC_IRQP_READ, ¤t_rtc_freq);
1290 if (current_rtc_freq != RTC_FREQ &&
1291 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1292 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1293 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1294 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1297 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1303 enable_sigio_timer(rtc_fd);
1305 t->priv = (void *)(long)rtc_fd;
1310 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1312 int rtc_fd = (long)t->priv;
1317 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1321 struct sigaction act;
1323 sigfillset(&act.sa_mask);
1325 act.sa_handler = host_alarm_handler;
1327 sigaction(SIGALRM, &act, NULL);
1330 * Initialize ev struct to 0 to avoid valgrind complaining
1331 * about uninitialized data in timer_create call
1333 memset(&ev, 0, sizeof(ev));
1334 ev.sigev_value.sival_int = 0;
1335 ev.sigev_notify = SIGEV_SIGNAL;
1336 ev.sigev_signo = SIGALRM;
1338 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1339 perror("timer_create");
1341 /* disable dynticks */
1342 fprintf(stderr, "Dynamic Ticks disabled\n");
1347 t->priv = (void *)(long)host_timer;
1352 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1354 timer_t host_timer = (timer_t)(long)t->priv;
1356 timer_delete(host_timer);
1359 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1361 timer_t host_timer = (timer_t)(long)t->priv;
1362 struct itimerspec timeout;
1363 int64_t nearest_delta_us = INT64_MAX;
1366 if (!active_timers[QEMU_TIMER_REALTIME] &&
1367 !active_timers[QEMU_TIMER_VIRTUAL])
1370 nearest_delta_us = qemu_next_deadline_dyntick();
1372 /* check whether a timer is already running */
1373 if (timer_gettime(host_timer, &timeout)) {
1375 fprintf(stderr, "Internal timer error: aborting\n");
1378 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1379 if (current_us && current_us <= nearest_delta_us)
1382 timeout.it_interval.tv_sec = 0;
1383 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1384 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1385 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1386 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1388 fprintf(stderr, "Internal timer error: aborting\n");
1393 #endif /* defined(__linux__) */
1395 static int unix_start_timer(struct qemu_alarm_timer *t)
1397 struct sigaction act;
1398 struct itimerval itv;
1402 sigfillset(&act.sa_mask);
1404 act.sa_handler = host_alarm_handler;
1406 sigaction(SIGALRM, &act, NULL);
1408 itv.it_interval.tv_sec = 0;
1409 /* for i386 kernel 2.6 to get 1 ms */
1410 itv.it_interval.tv_usec = 999;
1411 itv.it_value.tv_sec = 0;
1412 itv.it_value.tv_usec = 10 * 1000;
1414 err = setitimer(ITIMER_REAL, &itv, NULL);
1421 static void unix_stop_timer(struct qemu_alarm_timer *t)
1423 struct itimerval itv;
1425 memset(&itv, 0, sizeof(itv));
1426 setitimer(ITIMER_REAL, &itv, NULL);
1429 #endif /* !defined(_WIN32) */
1434 static int win32_start_timer(struct qemu_alarm_timer *t)
1437 struct qemu_alarm_win32 *data = t->priv;
1440 memset(&tc, 0, sizeof(tc));
1441 timeGetDevCaps(&tc, sizeof(tc));
1443 if (data->period < tc.wPeriodMin)
1444 data->period = tc.wPeriodMin;
1446 timeBeginPeriod(data->period);
1448 flags = TIME_CALLBACK_FUNCTION;
1449 if (alarm_has_dynticks(t))
1450 flags |= TIME_ONESHOT;
1452 flags |= TIME_PERIODIC;
1454 data->timerId = timeSetEvent(1, // interval (ms)
1455 data->period, // resolution
1456 host_alarm_handler, // function
1457 (DWORD)t, // parameter
1460 if (!data->timerId) {
1461 perror("Failed to initialize win32 alarm timer");
1462 timeEndPeriod(data->period);
1469 static void win32_stop_timer(struct qemu_alarm_timer *t)
1471 struct qemu_alarm_win32 *data = t->priv;
1473 timeKillEvent(data->timerId);
1474 timeEndPeriod(data->period);
1477 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1479 struct qemu_alarm_win32 *data = t->priv;
1480 uint64_t nearest_delta_us;
1482 if (!active_timers[QEMU_TIMER_REALTIME] &&
1483 !active_timers[QEMU_TIMER_VIRTUAL])
1486 nearest_delta_us = qemu_next_deadline_dyntick();
1487 nearest_delta_us /= 1000;
1489 timeKillEvent(data->timerId);
1491 data->timerId = timeSetEvent(1,
1495 TIME_ONESHOT | TIME_PERIODIC);
1497 if (!data->timerId) {
1498 perror("Failed to re-arm win32 alarm timer");
1500 timeEndPeriod(data->period);
1507 static int init_timer_alarm(void)
1509 struct qemu_alarm_timer *t = NULL;
1512 for (i = 0; alarm_timers[i].name; i++) {
1513 t = &alarm_timers[i];
1533 static void quit_timers(void)
1535 alarm_timer->stop(alarm_timer);
1539 /***********************************************************/
1540 /* host time/date access */
1541 void qemu_get_timedate(struct tm *tm, int offset)
1548 if (rtc_date_offset == -1) {
1552 ret = localtime(&ti);
1554 ti -= rtc_date_offset;
1558 memcpy(tm, ret, sizeof(struct tm));
1561 int qemu_timedate_diff(struct tm *tm)
1565 if (rtc_date_offset == -1)
1567 seconds = mktimegm(tm);
1569 seconds = mktime(tm);
1571 seconds = mktimegm(tm) + rtc_date_offset;
1573 return seconds - time(NULL);
1577 static void socket_cleanup(void)
1582 static int socket_init(void)
1587 ret = WSAStartup(MAKEWORD(2,2), &Data);
1589 err = WSAGetLastError();
1590 fprintf(stderr, "WSAStartup: %d\n", err);
1593 atexit(socket_cleanup);
1598 /***********************************************************/
1599 /* Bluetooth support */
1602 static struct HCIInfo *hci_table[MAX_NICS];
1604 static struct bt_vlan_s {
1605 struct bt_scatternet_s net;
1607 struct bt_vlan_s *next;
1610 /* find or alloc a new bluetooth "VLAN" */
1611 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1613 struct bt_vlan_s **pvlan, *vlan;
1614 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1618 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1620 pvlan = &first_bt_vlan;
1621 while (*pvlan != NULL)
1622 pvlan = &(*pvlan)->next;
1627 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1631 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1636 static struct HCIInfo null_hci = {
1637 .cmd_send = null_hci_send,
1638 .sco_send = null_hci_send,
1639 .acl_send = null_hci_send,
1640 .bdaddr_set = null_hci_addr_set,
1643 struct HCIInfo *qemu_next_hci(void)
1645 if (cur_hci == nb_hcis)
1648 return hci_table[cur_hci++];
1651 static struct HCIInfo *hci_init(const char *str)
1654 struct bt_scatternet_s *vlan = 0;
1656 if (!strcmp(str, "null"))
1659 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1661 return bt_host_hci(str[4] ? str + 5 : "hci0");
1662 else if (!strncmp(str, "hci", 3)) {
1665 if (!strncmp(str + 3, ",vlan=", 6)) {
1666 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1671 vlan = qemu_find_bt_vlan(0);
1673 return bt_new_hci(vlan);
1676 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1681 static int bt_hci_parse(const char *str)
1683 struct HCIInfo *hci;
1686 if (nb_hcis >= MAX_NICS) {
1687 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1691 hci = hci_init(str);
1700 bdaddr.b[5] = 0x56 + nb_hcis;
1701 hci->bdaddr_set(hci, bdaddr.b);
1703 hci_table[nb_hcis++] = hci;
1708 static void bt_vhci_add(int vlan_id)
1710 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1713 fprintf(stderr, "qemu: warning: adding a VHCI to "
1714 "an empty scatternet %i\n", vlan_id);
1716 bt_vhci_init(bt_new_hci(vlan));
1719 static struct bt_device_s *bt_device_add(const char *opt)
1721 struct bt_scatternet_s *vlan;
1723 char *endp = strstr(opt, ",vlan=");
1724 int len = (endp ? endp - opt : strlen(opt)) + 1;
1727 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1730 vlan_id = strtol(endp + 6, &endp, 0);
1732 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1737 vlan = qemu_find_bt_vlan(vlan_id);
1740 fprintf(stderr, "qemu: warning: adding a slave device to "
1741 "an empty scatternet %i\n", vlan_id);
1743 if (!strcmp(devname, "keyboard"))
1744 return bt_keyboard_init(vlan);
1746 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1750 static int bt_parse(const char *opt)
1752 const char *endp, *p;
1755 if (strstart(opt, "hci", &endp)) {
1756 if (!*endp || *endp == ',') {
1758 if (!strstart(endp, ",vlan=", 0))
1761 return bt_hci_parse(opt);
1763 } else if (strstart(opt, "vhci", &endp)) {
1764 if (!*endp || *endp == ',') {
1766 if (strstart(endp, ",vlan=", &p)) {
1767 vlan = strtol(p, (char **) &endp, 0);
1769 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1773 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1782 } else if (strstart(opt, "device:", &endp))
1783 return !bt_device_add(endp);
1785 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1789 /***********************************************************/
1790 /* QEMU Block devices */
1792 #define HD_ALIAS "index=%d,media=disk"
1793 #define CDROM_ALIAS "index=2,media=cdrom"
1794 #define FD_ALIAS "index=%d,if=floppy"
1795 #define PFLASH_ALIAS "if=pflash"
1796 #define MTD_ALIAS "if=mtd"
1797 #define SD_ALIAS "index=0,if=sd"
1799 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1806 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1809 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1811 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1812 __FUNCTION__, optstr);
1816 qemu_opt_set(opts, "file", file);
1820 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1824 /* seek interface, bus and unit */
1826 TAILQ_FOREACH(dinfo, &drives, next) {
1827 if (dinfo->type == type &&
1828 dinfo->bus == bus &&
1829 dinfo->unit == unit)
1836 DriveInfo *drive_get_by_id(const char *id)
1840 TAILQ_FOREACH(dinfo, &drives, next) {
1841 if (strcmp(id, dinfo->id))
1848 int drive_get_max_bus(BlockInterfaceType type)
1854 TAILQ_FOREACH(dinfo, &drives, next) {
1855 if(dinfo->type == type &&
1856 dinfo->bus > max_bus)
1857 max_bus = dinfo->bus;
1862 const char *drive_get_serial(BlockDriverState *bdrv)
1866 TAILQ_FOREACH(dinfo, &drives, next) {
1867 if (dinfo->bdrv == bdrv)
1868 return dinfo->serial;
1874 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1878 TAILQ_FOREACH(dinfo, &drives, next) {
1879 if (dinfo->bdrv == bdrv)
1880 return dinfo->onerror;
1883 return BLOCK_ERR_STOP_ENOSPC;
1886 static void bdrv_format_print(void *opaque, const char *name)
1888 fprintf(stderr, " %s", name);
1891 void drive_uninit(BlockDriverState *bdrv)
1895 TAILQ_FOREACH(dinfo, &drives, next) {
1896 if (dinfo->bdrv != bdrv)
1898 qemu_opts_del(dinfo->opts);
1899 TAILQ_REMOVE(&drives, dinfo, next);
1905 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1909 const char *file = NULL;
1912 const char *mediastr = "";
1913 BlockInterfaceType type;
1914 enum { MEDIA_DISK, MEDIA_CDROM } media;
1915 int bus_id, unit_id;
1916 int cyls, heads, secs, translation;
1917 BlockDriver *drv = NULL;
1918 QEMUMachine *machine = opaque;
1922 int bdrv_flags, onerror;
1923 const char *devaddr;
1929 translation = BIOS_ATA_TRANSLATION_AUTO;
1932 if (machine->use_scsi) {
1934 max_devs = MAX_SCSI_DEVS;
1935 pstrcpy(devname, sizeof(devname), "scsi");
1938 max_devs = MAX_IDE_DEVS;
1939 pstrcpy(devname, sizeof(devname), "ide");
1943 /* extract parameters */
1944 bus_id = qemu_opt_get_number(opts, "bus", 0);
1945 unit_id = qemu_opt_get_number(opts, "unit", -1);
1946 index = qemu_opt_get_number(opts, "index", -1);
1948 cyls = qemu_opt_get_number(opts, "cyls", 0);
1949 heads = qemu_opt_get_number(opts, "heads", 0);
1950 secs = qemu_opt_get_number(opts, "secs", 0);
1952 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1954 file = qemu_opt_get(opts, "file");
1955 serial = qemu_opt_get(opts, "serial");
1957 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1958 pstrcpy(devname, sizeof(devname), buf);
1959 if (!strcmp(buf, "ide")) {
1961 max_devs = MAX_IDE_DEVS;
1962 } else if (!strcmp(buf, "scsi")) {
1964 max_devs = MAX_SCSI_DEVS;
1965 } else if (!strcmp(buf, "floppy")) {
1968 } else if (!strcmp(buf, "pflash")) {
1971 } else if (!strcmp(buf, "mtd")) {
1974 } else if (!strcmp(buf, "sd")) {
1977 } else if (!strcmp(buf, "virtio")) {
1980 } else if (!strcmp(buf, "xen")) {
1983 } else if (!strcmp(buf, "none")) {
1987 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
1992 if (cyls || heads || secs) {
1993 if (cyls < 1 || cyls > 16383) {
1994 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
1997 if (heads < 1 || heads > 16) {
1998 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2001 if (secs < 1 || secs > 63) {
2002 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2007 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2010 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2014 if (!strcmp(buf, "none"))
2015 translation = BIOS_ATA_TRANSLATION_NONE;
2016 else if (!strcmp(buf, "lba"))
2017 translation = BIOS_ATA_TRANSLATION_LBA;
2018 else if (!strcmp(buf, "auto"))
2019 translation = BIOS_ATA_TRANSLATION_AUTO;
2021 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2026 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2027 if (!strcmp(buf, "disk")) {
2029 } else if (!strcmp(buf, "cdrom")) {
2030 if (cyls || secs || heads) {
2032 "qemu: '%s' invalid physical CHS format\n", buf);
2035 media = MEDIA_CDROM;
2037 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2042 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2043 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2045 else if (!strcmp(buf, "writethrough"))
2047 else if (!strcmp(buf, "writeback"))
2050 fprintf(stderr, "qemu: invalid cache option\n");
2055 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2056 if (strcmp(buf, "?") == 0) {
2057 fprintf(stderr, "qemu: Supported formats:");
2058 bdrv_iterate_format(bdrv_format_print, NULL);
2059 fprintf(stderr, "\n");
2062 drv = bdrv_find_format(buf);
2064 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2069 onerror = BLOCK_ERR_STOP_ENOSPC;
2070 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2071 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2072 fprintf(stderr, "werror is no supported by this format\n");
2075 if (!strcmp(buf, "ignore"))
2076 onerror = BLOCK_ERR_IGNORE;
2077 else if (!strcmp(buf, "enospc"))
2078 onerror = BLOCK_ERR_STOP_ENOSPC;
2079 else if (!strcmp(buf, "stop"))
2080 onerror = BLOCK_ERR_STOP_ANY;
2081 else if (!strcmp(buf, "report"))
2082 onerror = BLOCK_ERR_REPORT;
2084 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2089 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2090 if (type != IF_VIRTIO) {
2091 fprintf(stderr, "addr is not supported\n");
2096 /* compute bus and unit according index */
2099 if (bus_id != 0 || unit_id != -1) {
2101 "qemu: index cannot be used with bus and unit\n");
2109 unit_id = index % max_devs;
2110 bus_id = index / max_devs;
2114 /* if user doesn't specify a unit_id,
2115 * try to find the first free
2118 if (unit_id == -1) {
2120 while (drive_get(type, bus_id, unit_id) != NULL) {
2122 if (max_devs && unit_id >= max_devs) {
2123 unit_id -= max_devs;
2131 if (max_devs && unit_id >= max_devs) {
2132 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2133 unit_id, max_devs - 1);
2138 * ignore multiple definitions
2141 if (drive_get(type, bus_id, unit_id) != NULL) {
2148 dinfo = qemu_mallocz(sizeof(*dinfo));
2149 if ((buf = qemu_opts_id(opts)) != NULL) {
2150 dinfo->id = qemu_strdup(buf);
2152 /* no id supplied -> create one */
2153 dinfo->id = qemu_mallocz(32);
2154 if (type == IF_IDE || type == IF_SCSI)
2155 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2157 snprintf(dinfo->id, 32, "%s%i%s%i",
2158 devname, bus_id, mediastr, unit_id);
2160 snprintf(dinfo->id, 32, "%s%s%i",
2161 devname, mediastr, unit_id);
2163 dinfo->bdrv = bdrv_new(dinfo->id);
2164 dinfo->devaddr = devaddr;
2166 dinfo->bus = bus_id;
2167 dinfo->unit = unit_id;
2168 dinfo->onerror = onerror;
2171 strncpy(dinfo->serial, serial, sizeof(serial));
2172 TAILQ_INSERT_TAIL(&drives, dinfo, next);
2181 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2182 bdrv_set_translation_hint(dinfo->bdrv, translation);
2186 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2191 /* FIXME: This isn't really a floppy, but it's a reasonable
2194 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2201 /* add virtio block device */
2202 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2203 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2204 qemu_opt_set(opts, "drive", dinfo->id);
2206 qemu_opt_set(opts, "addr", devaddr);
2217 bdrv_flags |= BDRV_O_SNAPSHOT;
2218 cache = 2; /* always use write-back with snapshot */
2220 if (cache == 0) /* no caching */
2221 bdrv_flags |= BDRV_O_NOCACHE;
2222 else if (cache == 2) /* write-back */
2223 bdrv_flags |= BDRV_O_CACHE_WB;
2224 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2225 fprintf(stderr, "qemu: could not open disk image %s\n",
2229 if (bdrv_key_required(dinfo->bdrv))
2235 static int drive_init_func(QemuOpts *opts, void *opaque)
2237 QEMUMachine *machine = opaque;
2238 int fatal_error = 0;
2240 if (drive_init(opts, machine, &fatal_error) == NULL) {
2247 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2249 if (NULL == qemu_opt_get(opts, "snapshot")) {
2250 qemu_opt_set(opts, "snapshot", "on");
2255 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2257 boot_set_handler = func;
2258 boot_set_opaque = opaque;
2261 int qemu_boot_set(const char *boot_devices)
2263 if (!boot_set_handler) {
2266 return boot_set_handler(boot_set_opaque, boot_devices);
2269 static int parse_bootdevices(char *devices)
2271 /* We just do some generic consistency checks */
2275 for (p = devices; *p != '\0'; p++) {
2276 /* Allowed boot devices are:
2277 * a-b: floppy disk drives
2278 * c-f: IDE disk drives
2279 * g-m: machine implementation dependant drives
2280 * n-p: network devices
2281 * It's up to each machine implementation to check if the given boot
2282 * devices match the actual hardware implementation and firmware
2285 if (*p < 'a' || *p > 'p') {
2286 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2289 if (bitmap & (1 << (*p - 'a'))) {
2290 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2293 bitmap |= 1 << (*p - 'a');
2298 static void restore_boot_devices(void *opaque)
2300 char *standard_boot_devices = opaque;
2302 qemu_boot_set(standard_boot_devices);
2304 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2305 qemu_free(standard_boot_devices);
2308 static void numa_add(const char *optarg)
2312 unsigned long long value, endvalue;
2315 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2316 if (!strcmp(option, "node")) {
2317 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2318 nodenr = nb_numa_nodes;
2320 nodenr = strtoull(option, NULL, 10);
2323 if (get_param_value(option, 128, "mem", optarg) == 0) {
2324 node_mem[nodenr] = 0;
2326 value = strtoull(option, &endptr, 0);
2328 case 0: case 'M': case 'm':
2335 node_mem[nodenr] = value;
2337 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2338 node_cpumask[nodenr] = 0;
2340 value = strtoull(option, &endptr, 10);
2343 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2345 if (*endptr == '-') {
2346 endvalue = strtoull(endptr+1, &endptr, 10);
2347 if (endvalue >= 63) {
2350 "only 63 CPUs in NUMA mode supported.\n");
2352 value = (1 << (endvalue + 1)) - (1 << value);
2357 node_cpumask[nodenr] = value;
2364 /***********************************************************/
2367 static USBPort *used_usb_ports;
2368 static USBPort *free_usb_ports;
2370 /* ??? Maybe change this to register a hub to keep track of the topology. */
2371 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2372 usb_attachfn attach)
2374 port->opaque = opaque;
2375 port->index = index;
2376 port->attach = attach;
2377 port->next = free_usb_ports;
2378 free_usb_ports = port;
2381 int usb_device_add_dev(USBDevice *dev)
2385 /* Find a USB port to add the device to. */
2386 port = free_usb_ports;
2390 /* Create a new hub and chain it on. */
2391 free_usb_ports = NULL;
2392 port->next = used_usb_ports;
2393 used_usb_ports = port;
2395 hub = usb_hub_init(VM_USB_HUB_SIZE);
2396 usb_attach(port, hub);
2397 port = free_usb_ports;
2400 free_usb_ports = port->next;
2401 port->next = used_usb_ports;
2402 used_usb_ports = port;
2403 usb_attach(port, dev);
2407 static void usb_msd_password_cb(void *opaque, int err)
2409 USBDevice *dev = opaque;
2412 usb_device_add_dev(dev);
2414 dev->handle_destroy(dev);
2417 static int usb_device_add(const char *devname, int is_hotplug)
2422 if (!free_usb_ports)
2425 if (strstart(devname, "host:", &p)) {
2426 dev = usb_host_device_open(p);
2427 } else if (!strcmp(devname, "mouse")) {
2428 dev = usb_mouse_init();
2429 } else if (!strcmp(devname, "tablet")) {
2430 dev = usb_tablet_init();
2431 } else if (!strcmp(devname, "keyboard")) {
2432 dev = usb_keyboard_init();
2433 } else if (strstart(devname, "disk:", &p)) {
2434 BlockDriverState *bs;
2436 dev = usb_msd_init(p);
2439 bs = usb_msd_get_bdrv(dev);
2440 if (bdrv_key_required(bs)) {
2443 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2448 } else if (!strcmp(devname, "wacom-tablet")) {
2449 dev = usb_wacom_init();
2450 } else if (strstart(devname, "serial:", &p)) {
2451 dev = usb_serial_init(p);
2452 #ifdef CONFIG_BRLAPI
2453 } else if (!strcmp(devname, "braille")) {
2454 dev = usb_baum_init();
2456 } else if (strstart(devname, "net:", &p)) {
2459 if (net_client_init(NULL, "nic", p) < 0)
2461 nd_table[nic].model = "usb";
2462 dev = usb_net_init(&nd_table[nic]);
2463 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2464 dev = usb_bt_init(devname[2] ? hci_init(p) :
2465 bt_new_hci(qemu_find_bt_vlan(0)));
2472 return usb_device_add_dev(dev);
2475 int usb_device_del_addr(int bus_num, int addr)
2481 if (!used_usb_ports)
2487 lastp = &used_usb_ports;
2488 port = used_usb_ports;
2489 while (port && port->dev->addr != addr) {
2490 lastp = &port->next;
2498 *lastp = port->next;
2499 usb_attach(port, NULL);
2500 dev->handle_destroy(dev);
2501 port->next = free_usb_ports;
2502 free_usb_ports = port;
2506 static int usb_device_del(const char *devname)
2511 if (strstart(devname, "host:", &p))
2512 return usb_host_device_close(p);
2514 if (!used_usb_ports)
2517 p = strchr(devname, '.');
2520 bus_num = strtoul(devname, NULL, 0);
2521 addr = strtoul(p + 1, NULL, 0);
2523 return usb_device_del_addr(bus_num, addr);
2526 static int usb_parse(const char *cmdline)
2528 return usb_device_add(cmdline, 0);
2531 void do_usb_add(Monitor *mon, const char *devname)
2533 usb_device_add(devname, 1);
2536 void do_usb_del(Monitor *mon, const char *devname)
2538 usb_device_del(devname);
2541 void usb_info(Monitor *mon)
2545 const char *speed_str;
2548 monitor_printf(mon, "USB support not enabled\n");
2552 for (port = used_usb_ports; port; port = port->next) {
2556 switch(dev->speed) {
2560 case USB_SPEED_FULL:
2563 case USB_SPEED_HIGH:
2570 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2571 0, dev->addr, speed_str, dev->devname);
2575 /***********************************************************/
2576 /* PCMCIA/Cardbus */
2578 static struct pcmcia_socket_entry_s {
2579 PCMCIASocket *socket;
2580 struct pcmcia_socket_entry_s *next;
2581 } *pcmcia_sockets = 0;
2583 void pcmcia_socket_register(PCMCIASocket *socket)
2585 struct pcmcia_socket_entry_s *entry;
2587 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2588 entry->socket = socket;
2589 entry->next = pcmcia_sockets;
2590 pcmcia_sockets = entry;
2593 void pcmcia_socket_unregister(PCMCIASocket *socket)
2595 struct pcmcia_socket_entry_s *entry, **ptr;
2597 ptr = &pcmcia_sockets;
2598 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2599 if (entry->socket == socket) {
2605 void pcmcia_info(Monitor *mon)
2607 struct pcmcia_socket_entry_s *iter;
2609 if (!pcmcia_sockets)
2610 monitor_printf(mon, "No PCMCIA sockets\n");
2612 for (iter = pcmcia_sockets; iter; iter = iter->next)
2613 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2614 iter->socket->attached ? iter->socket->card_string :
2618 /***********************************************************/
2619 /* register display */
2621 struct DisplayAllocator default_allocator = {
2622 defaultallocator_create_displaysurface,
2623 defaultallocator_resize_displaysurface,
2624 defaultallocator_free_displaysurface
2627 void register_displaystate(DisplayState *ds)
2637 DisplayState *get_displaystate(void)
2639 return display_state;
2642 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2644 if(ds->allocator == &default_allocator) ds->allocator = da;
2645 return ds->allocator;
2650 static void dumb_display_init(void)
2652 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2653 ds->allocator = &default_allocator;
2654 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2655 register_displaystate(ds);
2658 /***********************************************************/
2661 typedef struct IOHandlerRecord {
2663 IOCanRWHandler *fd_read_poll;
2665 IOHandler *fd_write;
2668 /* temporary data */
2670 struct IOHandlerRecord *next;
2673 static IOHandlerRecord *first_io_handler;
2675 /* XXX: fd_read_poll should be suppressed, but an API change is
2676 necessary in the character devices to suppress fd_can_read(). */
2677 int qemu_set_fd_handler2(int fd,
2678 IOCanRWHandler *fd_read_poll,
2680 IOHandler *fd_write,
2683 IOHandlerRecord **pioh, *ioh;
2685 if (!fd_read && !fd_write) {
2686 pioh = &first_io_handler;
2691 if (ioh->fd == fd) {
2698 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2702 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2703 ioh->next = first_io_handler;
2704 first_io_handler = ioh;
2707 ioh->fd_read_poll = fd_read_poll;
2708 ioh->fd_read = fd_read;
2709 ioh->fd_write = fd_write;
2710 ioh->opaque = opaque;
2716 int qemu_set_fd_handler(int fd,
2718 IOHandler *fd_write,
2721 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2725 /***********************************************************/
2726 /* Polling handling */
2728 typedef struct PollingEntry {
2731 struct PollingEntry *next;
2734 static PollingEntry *first_polling_entry;
2736 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2738 PollingEntry **ppe, *pe;
2739 pe = qemu_mallocz(sizeof(PollingEntry));
2741 pe->opaque = opaque;
2742 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2747 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2749 PollingEntry **ppe, *pe;
2750 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2752 if (pe->func == func && pe->opaque == opaque) {
2760 /***********************************************************/
2761 /* Wait objects support */
2762 typedef struct WaitObjects {
2764 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2765 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2766 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2769 static WaitObjects wait_objects = {0};
2771 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2773 WaitObjects *w = &wait_objects;
2775 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2777 w->events[w->num] = handle;
2778 w->func[w->num] = func;
2779 w->opaque[w->num] = opaque;
2784 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2787 WaitObjects *w = &wait_objects;
2790 for (i = 0; i < w->num; i++) {
2791 if (w->events[i] == handle)
2794 w->events[i] = w->events[i + 1];
2795 w->func[i] = w->func[i + 1];
2796 w->opaque[i] = w->opaque[i + 1];
2804 /***********************************************************/
2805 /* ram save/restore */
2807 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2811 v = qemu_get_byte(f);
2814 if (qemu_get_buffer(f, buf, len) != len)
2818 v = qemu_get_byte(f);
2819 memset(buf, v, len);
2825 if (qemu_file_has_error(f))
2831 static int ram_load_v1(QEMUFile *f, void *opaque)
2836 if (qemu_get_be32(f) != last_ram_offset)
2838 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2839 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2846 #define BDRV_HASH_BLOCK_SIZE 1024
2847 #define IOBUF_SIZE 4096
2848 #define RAM_CBLOCK_MAGIC 0xfabe
2850 typedef struct RamDecompressState {
2853 uint8_t buf[IOBUF_SIZE];
2854 } RamDecompressState;
2856 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2859 memset(s, 0, sizeof(*s));
2861 ret = inflateInit(&s->zstream);
2867 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2871 s->zstream.avail_out = len;
2872 s->zstream.next_out = buf;
2873 while (s->zstream.avail_out > 0) {
2874 if (s->zstream.avail_in == 0) {
2875 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
2877 clen = qemu_get_be16(s->f);
2878 if (clen > IOBUF_SIZE)
2880 qemu_get_buffer(s->f, s->buf, clen);
2881 s->zstream.avail_in = clen;
2882 s->zstream.next_in = s->buf;
2884 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
2885 if (ret != Z_OK && ret != Z_STREAM_END) {
2892 static void ram_decompress_close(RamDecompressState *s)
2894 inflateEnd(&s->zstream);
2897 #define RAM_SAVE_FLAG_FULL 0x01
2898 #define RAM_SAVE_FLAG_COMPRESS 0x02
2899 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2900 #define RAM_SAVE_FLAG_PAGE 0x08
2901 #define RAM_SAVE_FLAG_EOS 0x10
2903 static int is_dup_page(uint8_t *page, uint8_t ch)
2905 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2906 uint32_t *array = (uint32_t *)page;
2909 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2910 if (array[i] != val)
2917 static int ram_save_block(QEMUFile *f)
2919 static ram_addr_t current_addr = 0;
2920 ram_addr_t saved_addr = current_addr;
2921 ram_addr_t addr = 0;
2924 while (addr < last_ram_offset) {
2925 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2928 cpu_physical_memory_reset_dirty(current_addr,
2929 current_addr + TARGET_PAGE_SIZE,
2930 MIGRATION_DIRTY_FLAG);
2932 p = qemu_get_ram_ptr(current_addr);
2934 if (is_dup_page(p, *p)) {
2935 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2936 qemu_put_byte(f, *p);
2938 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2939 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2945 addr += TARGET_PAGE_SIZE;
2946 current_addr = (saved_addr + addr) % last_ram_offset;
2952 static uint64_t bytes_transferred = 0;
2954 static ram_addr_t ram_save_remaining(void)
2957 ram_addr_t count = 0;
2959 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2960 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2967 uint64_t ram_bytes_remaining(void)
2969 return ram_save_remaining() * TARGET_PAGE_SIZE;
2972 uint64_t ram_bytes_transferred(void)
2974 return bytes_transferred;
2977 uint64_t ram_bytes_total(void)
2979 return last_ram_offset;
2982 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
2985 uint64_t bytes_transferred_last;
2987 uint64_t expected_time = 0;
2989 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2990 qemu_file_set_error(f);
2995 /* Make sure all dirty bits are set */
2996 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2997 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2998 cpu_physical_memory_set_dirty(addr);
3001 /* Enable dirty memory tracking */
3002 cpu_physical_memory_set_dirty_tracking(1);
3004 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3007 bytes_transferred_last = bytes_transferred;
3008 bwidth = get_clock();
3010 while (!qemu_file_rate_limit(f)) {
3013 ret = ram_save_block(f);
3014 bytes_transferred += ret * TARGET_PAGE_SIZE;
3015 if (ret == 0) /* no more blocks */
3019 bwidth = get_clock() - bwidth;
3020 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3022 /* if we haven't transferred anything this round, force expected_time to a
3023 * a very high value, but without crashing */
3027 /* try transferring iterative blocks of memory */
3031 /* flush all remaining blocks regardless of rate limiting */
3032 while (ram_save_block(f) != 0) {
3033 bytes_transferred += TARGET_PAGE_SIZE;
3035 cpu_physical_memory_set_dirty_tracking(0);
3038 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3040 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3042 return (stage == 2) && (expected_time <= migrate_max_downtime());
3045 static int ram_load_dead(QEMUFile *f, void *opaque)
3047 RamDecompressState s1, *s = &s1;
3051 if (ram_decompress_open(s, f) < 0)
3053 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3054 if (ram_decompress_buf(s, buf, 1) < 0) {
3055 fprintf(stderr, "Error while reading ram block header\n");
3059 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3060 BDRV_HASH_BLOCK_SIZE) < 0) {
3061 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3066 printf("Error block header\n");
3070 ram_decompress_close(s);
3075 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3080 if (version_id == 1)
3081 return ram_load_v1(f, opaque);
3083 if (version_id == 2) {
3084 if (qemu_get_be32(f) != last_ram_offset)
3086 return ram_load_dead(f, opaque);
3089 if (version_id != 3)
3093 addr = qemu_get_be64(f);
3095 flags = addr & ~TARGET_PAGE_MASK;
3096 addr &= TARGET_PAGE_MASK;
3098 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3099 if (addr != last_ram_offset)
3103 if (flags & RAM_SAVE_FLAG_FULL) {
3104 if (ram_load_dead(f, opaque) < 0)
3108 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3109 uint8_t ch = qemu_get_byte(f);
3110 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3113 (!kvm_enabled() || kvm_has_sync_mmu())) {
3114 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3117 } else if (flags & RAM_SAVE_FLAG_PAGE)
3118 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3119 } while (!(flags & RAM_SAVE_FLAG_EOS));
3124 void qemu_service_io(void)
3126 qemu_notify_event();
3129 /***********************************************************/
3130 /* bottom halves (can be seen as timers which expire ASAP) */
3141 static QEMUBH *first_bh = NULL;
3143 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3146 bh = qemu_mallocz(sizeof(QEMUBH));
3148 bh->opaque = opaque;
3149 bh->next = first_bh;
3154 int qemu_bh_poll(void)
3160 for (bh = first_bh; bh; bh = bh->next) {
3161 if (!bh->deleted && bh->scheduled) {
3170 /* remove deleted bhs */
3184 void qemu_bh_schedule_idle(QEMUBH *bh)
3192 void qemu_bh_schedule(QEMUBH *bh)
3198 /* stop the currently executing CPU to execute the BH ASAP */
3199 qemu_notify_event();
3202 void qemu_bh_cancel(QEMUBH *bh)
3207 void qemu_bh_delete(QEMUBH *bh)
3213 static void qemu_bh_update_timeout(int *timeout)
3217 for (bh = first_bh; bh; bh = bh->next) {
3218 if (!bh->deleted && bh->scheduled) {
3220 /* idle bottom halves will be polled at least
3222 *timeout = MIN(10, *timeout);
3224 /* non-idle bottom halves will be executed
3233 /***********************************************************/
3234 /* machine registration */
3236 static QEMUMachine *first_machine = NULL;
3237 QEMUMachine *current_machine = NULL;
3239 int qemu_register_machine(QEMUMachine *m)
3242 pm = &first_machine;
3250 static QEMUMachine *find_machine(const char *name)
3254 for(m = first_machine; m != NULL; m = m->next) {
3255 if (!strcmp(m->name, name))
3257 if (m->alias && !strcmp(m->alias, name))
3263 static QEMUMachine *find_default_machine(void)
3267 for(m = first_machine; m != NULL; m = m->next) {
3268 if (m->is_default) {
3275 /***********************************************************/
3276 /* main execution loop */
3278 static void gui_update(void *opaque)
3280 uint64_t interval = GUI_REFRESH_INTERVAL;
3281 DisplayState *ds = opaque;
3282 DisplayChangeListener *dcl = ds->listeners;
3286 while (dcl != NULL) {
3287 if (dcl->gui_timer_interval &&
3288 dcl->gui_timer_interval < interval)
3289 interval = dcl->gui_timer_interval;
3292 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3295 static void nographic_update(void *opaque)
3297 uint64_t interval = GUI_REFRESH_INTERVAL;
3299 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3302 struct vm_change_state_entry {
3303 VMChangeStateHandler *cb;
3305 LIST_ENTRY (vm_change_state_entry) entries;
3308 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3310 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3313 VMChangeStateEntry *e;
3315 e = qemu_mallocz(sizeof (*e));
3319 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3323 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3325 LIST_REMOVE (e, entries);
3329 static void vm_state_notify(int running, int reason)
3331 VMChangeStateEntry *e;
3333 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3334 e->cb(e->opaque, running, reason);
3338 static void resume_all_vcpus(void);
3339 static void pause_all_vcpus(void);
3346 vm_state_notify(1, 0);
3347 qemu_rearm_alarm_timer(alarm_timer);
3352 /* reset/shutdown handler */
3354 typedef struct QEMUResetEntry {
3355 TAILQ_ENTRY(QEMUResetEntry) entry;
3356 QEMUResetHandler *func;
3360 static TAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3361 TAILQ_HEAD_INITIALIZER(reset_handlers);
3362 static int reset_requested;
3363 static int shutdown_requested;
3364 static int powerdown_requested;
3365 static int debug_requested;
3366 static int vmstop_requested;
3368 int qemu_shutdown_requested(void)
3370 int r = shutdown_requested;
3371 shutdown_requested = 0;
3375 int qemu_reset_requested(void)
3377 int r = reset_requested;
3378 reset_requested = 0;
3382 int qemu_powerdown_requested(void)
3384 int r = powerdown_requested;
3385 powerdown_requested = 0;
3389 static int qemu_debug_requested(void)
3391 int r = debug_requested;
3392 debug_requested = 0;
3396 static int qemu_vmstop_requested(void)
3398 int r = vmstop_requested;
3399 vmstop_requested = 0;
3403 static void do_vm_stop(int reason)
3406 cpu_disable_ticks();
3409 vm_state_notify(0, reason);
3413 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3415 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3418 re->opaque = opaque;
3419 TAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3422 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3426 TAILQ_FOREACH(re, &reset_handlers, entry) {
3427 if (re->func == func && re->opaque == opaque) {
3428 TAILQ_REMOVE(&reset_handlers, re, entry);
3435 void qemu_system_reset(void)
3437 QEMUResetEntry *re, *nre;
3439 /* reset all devices */
3440 TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3441 re->func(re->opaque);
3445 void qemu_system_reset_request(void)
3448 shutdown_requested = 1;
3450 reset_requested = 1;
3452 qemu_notify_event();
3455 void qemu_system_shutdown_request(void)
3457 shutdown_requested = 1;
3458 qemu_notify_event();
3461 void qemu_system_powerdown_request(void)
3463 powerdown_requested = 1;
3464 qemu_notify_event();
3467 #ifdef CONFIG_IOTHREAD
3468 static void qemu_system_vmstop_request(int reason)
3470 vmstop_requested = reason;
3471 qemu_notify_event();
3476 static int io_thread_fd = -1;
3478 static void qemu_event_increment(void)
3480 static const char byte = 0;
3482 if (io_thread_fd == -1)
3485 write(io_thread_fd, &byte, sizeof(byte));
3488 static void qemu_event_read(void *opaque)
3490 int fd = (unsigned long)opaque;
3493 /* Drain the notify pipe */
3496 len = read(fd, buffer, sizeof(buffer));
3497 } while ((len == -1 && errno == EINTR) || len > 0);
3500 static int qemu_event_init(void)
3509 err = fcntl_setfl(fds[0], O_NONBLOCK);
3513 err = fcntl_setfl(fds[1], O_NONBLOCK);
3517 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3518 (void *)(unsigned long)fds[0]);
3520 io_thread_fd = fds[1];
3529 HANDLE qemu_event_handle;
3531 static void dummy_event_handler(void *opaque)
3535 static int qemu_event_init(void)
3537 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3538 if (!qemu_event_handle) {
3539 perror("Failed CreateEvent");
3542 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3546 static void qemu_event_increment(void)
3548 SetEvent(qemu_event_handle);
3552 static int cpu_can_run(CPUState *env)
3561 #ifndef CONFIG_IOTHREAD
3562 static int qemu_init_main_loop(void)
3564 return qemu_event_init();
3567 void qemu_init_vcpu(void *_env)
3569 CPUState *env = _env;
3576 int qemu_cpu_self(void *env)
3581 static void resume_all_vcpus(void)
3585 static void pause_all_vcpus(void)
3589 void qemu_cpu_kick(void *env)
3594 void qemu_notify_event(void)
3596 CPUState *env = cpu_single_env;
3601 if (env->kqemu_enabled)
3602 kqemu_cpu_interrupt(env);
3607 #define qemu_mutex_lock_iothread() do { } while (0)
3608 #define qemu_mutex_unlock_iothread() do { } while (0)
3610 void vm_stop(int reason)
3615 #else /* CONFIG_IOTHREAD */
3617 #include "qemu-thread.h"
3619 QemuMutex qemu_global_mutex;
3620 static QemuMutex qemu_fair_mutex;
3622 static QemuThread io_thread;
3624 static QemuThread *tcg_cpu_thread;
3625 static QemuCond *tcg_halt_cond;
3627 static int qemu_system_ready;
3629 static QemuCond qemu_cpu_cond;
3631 static QemuCond qemu_system_cond;
3632 static QemuCond qemu_pause_cond;
3634 static void block_io_signals(void);
3635 static void unblock_io_signals(void);
3636 static int tcg_has_work(void);
3638 static int qemu_init_main_loop(void)
3642 ret = qemu_event_init();
3646 qemu_cond_init(&qemu_pause_cond);
3647 qemu_mutex_init(&qemu_fair_mutex);
3648 qemu_mutex_init(&qemu_global_mutex);
3649 qemu_mutex_lock(&qemu_global_mutex);
3651 unblock_io_signals();
3652 qemu_thread_self(&io_thread);
3657 static void qemu_wait_io_event(CPUState *env)
3659 while (!tcg_has_work())
3660 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3662 qemu_mutex_unlock(&qemu_global_mutex);
3665 * Users of qemu_global_mutex can be starved, having no chance
3666 * to acquire it since this path will get to it first.
3667 * So use another lock to provide fairness.
3669 qemu_mutex_lock(&qemu_fair_mutex);
3670 qemu_mutex_unlock(&qemu_fair_mutex);
3672 qemu_mutex_lock(&qemu_global_mutex);
3676 qemu_cond_signal(&qemu_pause_cond);
3680 static int qemu_cpu_exec(CPUState *env);
3682 static void *kvm_cpu_thread_fn(void *arg)
3684 CPUState *env = arg;
3687 qemu_thread_self(env->thread);
3689 /* signal CPU creation */
3690 qemu_mutex_lock(&qemu_global_mutex);
3692 qemu_cond_signal(&qemu_cpu_cond);
3694 /* and wait for machine initialization */
3695 while (!qemu_system_ready)
3696 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3699 if (cpu_can_run(env))
3701 qemu_wait_io_event(env);
3707 static void tcg_cpu_exec(void);
3709 static void *tcg_cpu_thread_fn(void *arg)
3711 CPUState *env = arg;
3714 qemu_thread_self(env->thread);
3716 /* signal CPU creation */
3717 qemu_mutex_lock(&qemu_global_mutex);
3718 for (env = first_cpu; env != NULL; env = env->next_cpu)
3720 qemu_cond_signal(&qemu_cpu_cond);
3722 /* and wait for machine initialization */
3723 while (!qemu_system_ready)
3724 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3728 qemu_wait_io_event(cur_cpu);
3734 void qemu_cpu_kick(void *_env)
3736 CPUState *env = _env;
3737 qemu_cond_broadcast(env->halt_cond);
3739 qemu_thread_signal(env->thread, SIGUSR1);
3742 int qemu_cpu_self(void *env)
3744 return (cpu_single_env != NULL);
3747 static void cpu_signal(int sig)
3750 cpu_exit(cpu_single_env);
3753 static void block_io_signals(void)
3756 struct sigaction sigact;
3759 sigaddset(&set, SIGUSR2);
3760 sigaddset(&set, SIGIO);
3761 sigaddset(&set, SIGALRM);
3762 pthread_sigmask(SIG_BLOCK, &set, NULL);
3765 sigaddset(&set, SIGUSR1);
3766 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3768 memset(&sigact, 0, sizeof(sigact));
3769 sigact.sa_handler = cpu_signal;
3770 sigaction(SIGUSR1, &sigact, NULL);
3773 static void unblock_io_signals(void)
3778 sigaddset(&set, SIGUSR2);
3779 sigaddset(&set, SIGIO);
3780 sigaddset(&set, SIGALRM);
3781 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3784 sigaddset(&set, SIGUSR1);
3785 pthread_sigmask(SIG_BLOCK, &set, NULL);
3788 static void qemu_signal_lock(unsigned int msecs)
3790 qemu_mutex_lock(&qemu_fair_mutex);
3792 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3793 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3794 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3797 qemu_mutex_unlock(&qemu_fair_mutex);
3800 static void qemu_mutex_lock_iothread(void)
3802 if (kvm_enabled()) {
3803 qemu_mutex_lock(&qemu_fair_mutex);
3804 qemu_mutex_lock(&qemu_global_mutex);
3805 qemu_mutex_unlock(&qemu_fair_mutex);
3807 qemu_signal_lock(100);
3810 static void qemu_mutex_unlock_iothread(void)
3812 qemu_mutex_unlock(&qemu_global_mutex);
3815 static int all_vcpus_paused(void)
3817 CPUState *penv = first_cpu;
3822 penv = (CPUState *)penv->next_cpu;
3828 static void pause_all_vcpus(void)
3830 CPUState *penv = first_cpu;
3834 qemu_thread_signal(penv->thread, SIGUSR1);
3835 qemu_cpu_kick(penv);
3836 penv = (CPUState *)penv->next_cpu;
3839 while (!all_vcpus_paused()) {
3840 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3843 qemu_thread_signal(penv->thread, SIGUSR1);
3844 penv = (CPUState *)penv->next_cpu;
3849 static void resume_all_vcpus(void)
3851 CPUState *penv = first_cpu;
3856 qemu_thread_signal(penv->thread, SIGUSR1);
3857 qemu_cpu_kick(penv);
3858 penv = (CPUState *)penv->next_cpu;
3862 static void tcg_init_vcpu(void *_env)
3864 CPUState *env = _env;
3865 /* share a single thread for all cpus with TCG */
3866 if (!tcg_cpu_thread) {
3867 env->thread = qemu_mallocz(sizeof(QemuThread));
3868 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3869 qemu_cond_init(env->halt_cond);
3870 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3871 while (env->created == 0)
3872 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3873 tcg_cpu_thread = env->thread;
3874 tcg_halt_cond = env->halt_cond;
3876 env->thread = tcg_cpu_thread;
3877 env->halt_cond = tcg_halt_cond;
3881 static void kvm_start_vcpu(CPUState *env)
3884 env->thread = qemu_mallocz(sizeof(QemuThread));
3885 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3886 qemu_cond_init(env->halt_cond);
3887 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3888 while (env->created == 0)
3889 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3892 void qemu_init_vcpu(void *_env)
3894 CPUState *env = _env;
3897 kvm_start_vcpu(env);
3902 void qemu_notify_event(void)
3904 qemu_event_increment();
3907 void vm_stop(int reason)
3910 qemu_thread_self(&me);
3912 if (!qemu_thread_equal(&me, &io_thread)) {
3913 qemu_system_vmstop_request(reason);
3915 * FIXME: should not return to device code in case
3916 * vm_stop() has been requested.
3918 if (cpu_single_env) {
3919 cpu_exit(cpu_single_env);
3920 cpu_single_env->stop = 1;
3931 static void host_main_loop_wait(int *timeout)
3937 /* XXX: need to suppress polling by better using win32 events */
3939 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3940 ret |= pe->func(pe->opaque);
3944 WaitObjects *w = &wait_objects;
3946 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3947 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3948 if (w->func[ret - WAIT_OBJECT_0])
3949 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3951 /* Check for additional signaled events */
3952 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3954 /* Check if event is signaled */
3955 ret2 = WaitForSingleObject(w->events[i], 0);
3956 if(ret2 == WAIT_OBJECT_0) {
3958 w->func[i](w->opaque[i]);
3959 } else if (ret2 == WAIT_TIMEOUT) {
3961 err = GetLastError();
3962 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3965 } else if (ret == WAIT_TIMEOUT) {
3967 err = GetLastError();
3968 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3975 static void host_main_loop_wait(int *timeout)
3980 void main_loop_wait(int timeout)
3982 IOHandlerRecord *ioh;
3983 fd_set rfds, wfds, xfds;
3987 qemu_bh_update_timeout(&timeout);
3989 host_main_loop_wait(&timeout);
3991 /* poll any events */
3992 /* XXX: separate device handlers from system ones */
3997 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4001 (!ioh->fd_read_poll ||
4002 ioh->fd_read_poll(ioh->opaque) != 0)) {
4003 FD_SET(ioh->fd, &rfds);
4007 if (ioh->fd_write) {
4008 FD_SET(ioh->fd, &wfds);
4014 tv.tv_sec = timeout / 1000;
4015 tv.tv_usec = (timeout % 1000) * 1000;
4017 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4019 qemu_mutex_unlock_iothread();
4020 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4021 qemu_mutex_lock_iothread();
4023 IOHandlerRecord **pioh;
4025 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4026 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4027 ioh->fd_read(ioh->opaque);
4029 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4030 ioh->fd_write(ioh->opaque);
4034 /* remove deleted IO handlers */
4035 pioh = &first_io_handler;
4046 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4048 /* rearm timer, if not periodic */
4049 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4050 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4051 qemu_rearm_alarm_timer(alarm_timer);
4054 /* vm time timers */
4056 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4057 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4058 qemu_get_clock(vm_clock));
4061 /* real time timers */
4062 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4063 qemu_get_clock(rt_clock));
4065 /* Check bottom-halves last in case any of the earlier events triggered
4071 static int qemu_cpu_exec(CPUState *env)
4074 #ifdef CONFIG_PROFILER
4078 #ifdef CONFIG_PROFILER
4079 ti = profile_getclock();
4084 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4085 env->icount_decr.u16.low = 0;
4086 env->icount_extra = 0;
4087 count = qemu_next_deadline();
4088 count = (count + (1 << icount_time_shift) - 1)
4089 >> icount_time_shift;
4090 qemu_icount += count;
4091 decr = (count > 0xffff) ? 0xffff : count;
4093 env->icount_decr.u16.low = decr;
4094 env->icount_extra = count;
4096 ret = cpu_exec(env);
4097 #ifdef CONFIG_PROFILER
4098 qemu_time += profile_getclock() - ti;
4101 /* Fold pending instructions back into the
4102 instruction counter, and clear the interrupt flag. */
4103 qemu_icount -= (env->icount_decr.u16.low
4104 + env->icount_extra);
4105 env->icount_decr.u32 = 0;
4106 env->icount_extra = 0;
4111 static void tcg_cpu_exec(void)
4115 if (next_cpu == NULL)
4116 next_cpu = first_cpu;
4117 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4118 CPUState *env = cur_cpu = next_cpu;
4122 if (timer_alarm_pending) {
4123 timer_alarm_pending = 0;
4126 if (cpu_can_run(env))
4127 ret = qemu_cpu_exec(env);
4128 if (ret == EXCP_DEBUG) {
4129 gdb_set_stop_cpu(env);
4130 debug_requested = 1;
4136 static int cpu_has_work(CPUState *env)
4144 if (qemu_cpu_has_work(env))
4149 static int tcg_has_work(void)
4153 for (env = first_cpu; env != NULL; env = env->next_cpu)
4154 if (cpu_has_work(env))
4159 static int qemu_calculate_timeout(void)
4161 #ifndef CONFIG_IOTHREAD
4166 else if (tcg_has_work())
4168 else if (!use_icount)
4171 /* XXX: use timeout computed from timers */
4174 /* Advance virtual time to the next event. */
4175 if (use_icount == 1) {
4176 /* When not using an adaptive execution frequency
4177 we tend to get badly out of sync with real time,
4178 so just delay for a reasonable amount of time. */
4181 delta = cpu_get_icount() - cpu_get_clock();
4184 /* If virtual time is ahead of real time then just
4186 timeout = (delta / 1000000) + 1;
4188 /* Wait for either IO to occur or the next
4190 add = qemu_next_deadline();
4191 /* We advance the timer before checking for IO.
4192 Limit the amount we advance so that early IO
4193 activity won't get the guest too far ahead. */
4197 add = (add + (1 << icount_time_shift) - 1)
4198 >> icount_time_shift;
4200 timeout = delta / 1000000;
4207 #else /* CONFIG_IOTHREAD */
4212 static int vm_can_run(void)
4214 if (powerdown_requested)
4216 if (reset_requested)
4218 if (shutdown_requested)
4220 if (debug_requested)
4225 qemu_irq qemu_system_powerdown;
4227 static void main_loop(void)
4231 #ifdef CONFIG_IOTHREAD
4232 qemu_system_ready = 1;
4233 qemu_cond_broadcast(&qemu_system_cond);
4238 #ifdef CONFIG_PROFILER
4241 #ifndef CONFIG_IOTHREAD
4244 #ifdef CONFIG_PROFILER
4245 ti = profile_getclock();
4247 main_loop_wait(qemu_calculate_timeout());
4248 #ifdef CONFIG_PROFILER
4249 dev_time += profile_getclock() - ti;
4251 } while (vm_can_run());
4253 if (qemu_debug_requested())
4254 vm_stop(EXCP_DEBUG);
4255 if (qemu_shutdown_requested()) {
4262 if (qemu_reset_requested()) {
4264 qemu_system_reset();
4267 if (qemu_powerdown_requested()) {
4268 qemu_irq_raise(qemu_system_powerdown);
4270 if ((r = qemu_vmstop_requested()))
4276 static void version(void)
4278 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4281 static void help(int exitcode)
4284 printf("usage: %s [options] [disk_image]\n"
4286 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4288 #define DEF(option, opt_arg, opt_enum, opt_help) \
4290 #define DEFHEADING(text) stringify(text) "\n"
4291 #include "qemu-options.h"
4296 "During emulation, the following keys are useful:\n"
4297 "ctrl-alt-f toggle full screen\n"
4298 "ctrl-alt-n switch to virtual console 'n'\n"
4299 "ctrl-alt toggle mouse and keyboard grab\n"
4301 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4306 DEFAULT_NETWORK_SCRIPT,
4307 DEFAULT_NETWORK_DOWN_SCRIPT,
4309 DEFAULT_GDBSTUB_PORT,
4314 #define HAS_ARG 0x0001
4317 #define DEF(option, opt_arg, opt_enum, opt_help) \
4319 #define DEFHEADING(text)
4320 #include "qemu-options.h"
4326 typedef struct QEMUOption {
4332 static const QEMUOption qemu_options[] = {
4333 { "h", 0, QEMU_OPTION_h },
4334 #define DEF(option, opt_arg, opt_enum, opt_help) \
4335 { option, opt_arg, opt_enum },
4336 #define DEFHEADING(text)
4337 #include "qemu-options.h"
4345 struct soundhw soundhw[] = {
4346 #ifdef HAS_AUDIO_CHOICE
4347 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4353 { .init_isa = pcspk_audio_init }
4360 "Creative Sound Blaster 16",
4363 { .init_isa = SB16_init }
4367 #ifdef CONFIG_CS4231A
4373 { .init_isa = cs4231a_init }
4381 "Yamaha YMF262 (OPL3)",
4383 "Yamaha YM3812 (OPL2)",
4387 { .init_isa = Adlib_init }
4394 "Gravis Ultrasound GF1",
4397 { .init_isa = GUS_init }
4404 "Intel 82801AA AC97 Audio",
4407 { .init_pci = ac97_init }
4411 #ifdef CONFIG_ES1370
4414 "ENSONIQ AudioPCI ES1370",
4417 { .init_pci = es1370_init }
4421 #endif /* HAS_AUDIO_CHOICE */
4423 { NULL, NULL, 0, 0, { NULL } }
4426 static void select_soundhw (const char *optarg)
4430 if (*optarg == '?') {
4433 printf ("Valid sound card names (comma separated):\n");
4434 for (c = soundhw; c->name; ++c) {
4435 printf ("%-11s %s\n", c->name, c->descr);
4437 printf ("\n-soundhw all will enable all of the above\n");
4438 exit (*optarg != '?');
4446 if (!strcmp (optarg, "all")) {
4447 for (c = soundhw; c->name; ++c) {
4455 e = strchr (p, ',');
4456 l = !e ? strlen (p) : (size_t) (e - p);
4458 for (c = soundhw; c->name; ++c) {
4459 if (!strncmp (c->name, p, l)) {
4468 "Unknown sound card name (too big to show)\n");
4471 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4476 p += l + (e != NULL);
4480 goto show_valid_cards;
4485 static void select_vgahw (const char *p)
4489 vga_interface_type = VGA_NONE;
4490 if (strstart(p, "std", &opts)) {
4491 vga_interface_type = VGA_STD;
4492 } else if (strstart(p, "cirrus", &opts)) {
4493 vga_interface_type = VGA_CIRRUS;
4494 } else if (strstart(p, "vmware", &opts)) {
4495 vga_interface_type = VGA_VMWARE;
4496 } else if (strstart(p, "xenfb", &opts)) {
4497 vga_interface_type = VGA_XENFB;
4498 } else if (!strstart(p, "none", &opts)) {
4500 fprintf(stderr, "Unknown vga type: %s\n", p);
4504 const char *nextopt;
4506 if (strstart(opts, ",retrace=", &nextopt)) {
4508 if (strstart(opts, "dumb", &nextopt))
4509 vga_retrace_method = VGA_RETRACE_DUMB;
4510 else if (strstart(opts, "precise", &nextopt))
4511 vga_retrace_method = VGA_RETRACE_PRECISE;
4512 else goto invalid_vga;
4513 } else goto invalid_vga;
4519 static int balloon_parse(const char *arg)
4524 if (!strcmp(arg, "none")) {
4526 } else if (!strncmp(arg, "virtio", 6)) {
4528 if (arg[6] == ',') {
4530 if (get_param_value(buf, sizeof(buf), "addr", p)) {
4531 virtio_balloon_devaddr = strdup(buf);
4542 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4544 exit(STATUS_CONTROL_C_EXIT);
4549 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4553 if(strlen(str) != 36)
4556 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4557 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4558 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4564 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4570 #define MAX_NET_CLIENTS 32
4574 static void termsig_handler(int signal)
4576 qemu_system_shutdown_request();
4579 static void sigchld_handler(int signal)
4581 waitpid(-1, NULL, WNOHANG);
4584 static void sighandler_setup(void)
4586 struct sigaction act;
4588 memset(&act, 0, sizeof(act));
4589 act.sa_handler = termsig_handler;
4590 sigaction(SIGINT, &act, NULL);
4591 sigaction(SIGHUP, &act, NULL);
4592 sigaction(SIGTERM, &act, NULL);
4594 act.sa_handler = sigchld_handler;
4595 act.sa_flags = SA_NOCLDSTOP;
4596 sigaction(SIGCHLD, &act, NULL);
4602 /* Look for support files in the same directory as the executable. */
4603 static char *find_datadir(const char *argv0)
4609 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4616 while (p != buf && *p != '\\')
4619 if (access(buf, R_OK) == 0) {
4620 return qemu_strdup(buf);
4626 /* Find a likely location for support files using the location of the binary.
4627 For installed binaries this will be "$bindir/../share/qemu". When
4628 running from the build tree this will be "$bindir/../pc-bios". */
4629 #define SHARE_SUFFIX "/share/qemu"
4630 #define BUILD_SUFFIX "/pc-bios"
4631 static char *find_datadir(const char *argv0)
4641 #if defined(__linux__)
4644 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4650 #elif defined(__FreeBSD__)
4653 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4660 /* If we don't have any way of figuring out the actual executable
4661 location then try argv[0]. */
4666 p = realpath(argv0, p);
4674 max_len = strlen(dir) +
4675 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4676 res = qemu_mallocz(max_len);
4677 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4678 if (access(res, R_OK)) {
4679 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4680 if (access(res, R_OK)) {
4694 char *qemu_find_file(int type, const char *name)
4700 /* If name contains path separators then try it as a straight path. */
4701 if ((strchr(name, '/') || strchr(name, '\\'))
4702 && access(name, R_OK) == 0) {
4703 return strdup(name);
4706 case QEMU_FILE_TYPE_BIOS:
4709 case QEMU_FILE_TYPE_KEYMAP:
4710 subdir = "keymaps/";
4715 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4716 buf = qemu_mallocz(len);
4717 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4718 if (access(buf, R_OK)) {
4725 static int device_init_func(QemuOpts *opts, void *opaque)
4729 dev = qdev_device_add(opts);
4735 struct device_config {
4737 DEV_USB, /* -usbdevice */
4740 const char *cmdline;
4741 TAILQ_ENTRY(device_config) next;
4743 TAILQ_HEAD(, device_config) device_configs = TAILQ_HEAD_INITIALIZER(device_configs);
4745 static void add_device_config(int type, const char *cmdline)
4747 struct device_config *conf;
4749 conf = qemu_mallocz(sizeof(*conf));
4751 conf->cmdline = cmdline;
4752 TAILQ_INSERT_TAIL(&device_configs, conf, next);
4755 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4757 struct device_config *conf;
4760 TAILQ_FOREACH(conf, &device_configs, next) {
4761 if (conf->type != type)
4763 rc = func(conf->cmdline);
4770 int main(int argc, char **argv, char **envp)
4772 const char *gdbstub_dev = NULL;
4773 uint32_t boot_devices_bitmap = 0;
4775 int snapshot, linux_boot, net_boot;
4776 const char *initrd_filename;
4777 const char *kernel_filename, *kernel_cmdline;
4778 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4780 DisplayChangeListener *dcl;
4781 int cyls, heads, secs, translation;
4782 const char *net_clients[MAX_NET_CLIENTS];
4784 QemuOpts *hda_opts = NULL, *opts;
4786 const char *r, *optarg;
4787 CharDriverState *monitor_hd = NULL;
4788 const char *monitor_device;
4789 const char *serial_devices[MAX_SERIAL_PORTS];
4790 int serial_device_index;
4791 const char *parallel_devices[MAX_PARALLEL_PORTS];
4792 int parallel_device_index;
4793 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4794 int virtio_console_index;
4795 const char *loadvm = NULL;
4796 QEMUMachine *machine;
4797 const char *cpu_model;
4802 const char *pid_file = NULL;
4803 const char *incoming = NULL;
4806 struct passwd *pwd = NULL;
4807 const char *chroot_dir = NULL;
4808 const char *run_as = NULL;
4811 int show_vnc_port = 0;
4813 qemu_cache_utils_init(envp);
4815 LIST_INIT (&vm_change_state_head);
4818 struct sigaction act;
4819 sigfillset(&act.sa_mask);
4821 act.sa_handler = SIG_IGN;
4822 sigaction(SIGPIPE, &act, NULL);
4825 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4826 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4827 QEMU to run on a single CPU */
4832 h = GetCurrentProcess();
4833 if (GetProcessAffinityMask(h, &mask, &smask)) {
4834 for(i = 0; i < 32; i++) {
4835 if (mask & (1 << i))
4840 SetProcessAffinityMask(h, mask);
4846 module_call_init(MODULE_INIT_MACHINE);
4847 machine = find_default_machine();
4849 initrd_filename = NULL;
4852 kernel_filename = NULL;
4853 kernel_cmdline = "";
4854 cyls = heads = secs = 0;
4855 translation = BIOS_ATA_TRANSLATION_AUTO;
4856 monitor_device = "vc:80Cx24C";
4858 serial_devices[0] = "vc:80Cx24C";
4859 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4860 serial_devices[i] = NULL;
4861 serial_device_index = 0;
4863 parallel_devices[0] = "vc:80Cx24C";
4864 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4865 parallel_devices[i] = NULL;
4866 parallel_device_index = 0;
4868 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4869 virtio_consoles[i] = NULL;
4870 virtio_console_index = 0;
4872 for (i = 0; i < MAX_NODES; i++) {
4874 node_cpumask[i] = 0;
4884 register_watchdogs();
4892 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4894 const QEMUOption *popt;
4897 /* Treat --foo the same as -foo. */
4900 popt = qemu_options;
4903 fprintf(stderr, "%s: invalid option -- '%s'\n",
4907 if (!strcmp(popt->name, r + 1))
4911 if (popt->flags & HAS_ARG) {
4912 if (optind >= argc) {
4913 fprintf(stderr, "%s: option '%s' requires an argument\n",
4917 optarg = argv[optind++];
4922 switch(popt->index) {
4924 machine = find_machine(optarg);
4927 printf("Supported machines are:\n");
4928 for(m = first_machine; m != NULL; m = m->next) {
4930 printf("%-10s %s (alias of %s)\n",
4931 m->alias, m->desc, m->name);
4932 printf("%-10s %s%s\n",
4934 m->is_default ? " (default)" : "");
4936 exit(*optarg != '?');
4939 case QEMU_OPTION_cpu:
4940 /* hw initialization will check this */
4941 if (*optarg == '?') {
4942 /* XXX: implement xxx_cpu_list for targets that still miss it */
4943 #if defined(cpu_list)
4944 cpu_list(stdout, &fprintf);
4951 case QEMU_OPTION_initrd:
4952 initrd_filename = optarg;
4954 case QEMU_OPTION_hda:
4956 hda_opts = drive_add(optarg, HD_ALIAS, 0);
4958 hda_opts = drive_add(optarg, HD_ALIAS
4959 ",cyls=%d,heads=%d,secs=%d%s",
4960 0, cyls, heads, secs,
4961 translation == BIOS_ATA_TRANSLATION_LBA ?
4963 translation == BIOS_ATA_TRANSLATION_NONE ?
4964 ",trans=none" : "");
4966 case QEMU_OPTION_hdb:
4967 case QEMU_OPTION_hdc:
4968 case QEMU_OPTION_hdd:
4969 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4971 case QEMU_OPTION_drive:
4972 drive_add(NULL, "%s", optarg);
4974 case QEMU_OPTION_set:
4975 if (qemu_set_option(optarg) != 0)
4978 case QEMU_OPTION_mtdblock:
4979 drive_add(optarg, MTD_ALIAS);
4981 case QEMU_OPTION_sd:
4982 drive_add(optarg, SD_ALIAS);
4984 case QEMU_OPTION_pflash:
4985 drive_add(optarg, PFLASH_ALIAS);
4987 case QEMU_OPTION_snapshot:
4990 case QEMU_OPTION_hdachs:
4994 cyls = strtol(p, (char **)&p, 0);
4995 if (cyls < 1 || cyls > 16383)
5000 heads = strtol(p, (char **)&p, 0);
5001 if (heads < 1 || heads > 16)
5006 secs = strtol(p, (char **)&p, 0);
5007 if (secs < 1 || secs > 63)
5011 if (!strcmp(p, "none"))
5012 translation = BIOS_ATA_TRANSLATION_NONE;
5013 else if (!strcmp(p, "lba"))
5014 translation = BIOS_ATA_TRANSLATION_LBA;
5015 else if (!strcmp(p, "auto"))
5016 translation = BIOS_ATA_TRANSLATION_AUTO;
5019 } else if (*p != '\0') {
5021 fprintf(stderr, "qemu: invalid physical CHS format\n");
5024 if (hda_opts != NULL) {
5026 snprintf(num, sizeof(num), "%d", cyls);
5027 qemu_opt_set(hda_opts, "cyls", num);
5028 snprintf(num, sizeof(num), "%d", heads);
5029 qemu_opt_set(hda_opts, "heads", num);
5030 snprintf(num, sizeof(num), "%d", secs);
5031 qemu_opt_set(hda_opts, "secs", num);
5032 if (translation == BIOS_ATA_TRANSLATION_LBA)
5033 qemu_opt_set(hda_opts, "trans", "lba");
5034 if (translation == BIOS_ATA_TRANSLATION_NONE)
5035 qemu_opt_set(hda_opts, "trans", "none");
5039 case QEMU_OPTION_numa:
5040 if (nb_numa_nodes >= MAX_NODES) {
5041 fprintf(stderr, "qemu: too many NUMA nodes\n");
5046 case QEMU_OPTION_nographic:
5047 display_type = DT_NOGRAPHIC;
5049 #ifdef CONFIG_CURSES
5050 case QEMU_OPTION_curses:
5051 display_type = DT_CURSES;
5054 case QEMU_OPTION_portrait:
5057 case QEMU_OPTION_kernel:
5058 kernel_filename = optarg;
5060 case QEMU_OPTION_append:
5061 kernel_cmdline = optarg;
5063 case QEMU_OPTION_cdrom:
5064 drive_add(optarg, CDROM_ALIAS);
5066 case QEMU_OPTION_boot:
5068 static const char * const params[] = {
5069 "order", "once", "menu", NULL
5071 char buf[sizeof(boot_devices)];
5072 char *standard_boot_devices;
5075 if (!strchr(optarg, '=')) {
5077 pstrcpy(buf, sizeof(buf), optarg);
5078 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5080 "qemu: unknown boot parameter '%s' in '%s'\n",
5086 get_param_value(buf, sizeof(buf), "order", optarg)) {
5087 boot_devices_bitmap = parse_bootdevices(buf);
5088 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5091 if (get_param_value(buf, sizeof(buf),
5093 boot_devices_bitmap |= parse_bootdevices(buf);
5094 standard_boot_devices = qemu_strdup(boot_devices);
5095 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5096 qemu_register_reset(restore_boot_devices,
5097 standard_boot_devices);
5099 if (get_param_value(buf, sizeof(buf),
5101 if (!strcmp(buf, "on")) {
5103 } else if (!strcmp(buf, "off")) {
5107 "qemu: invalid option value '%s'\n",
5115 case QEMU_OPTION_fda:
5116 case QEMU_OPTION_fdb:
5117 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5120 case QEMU_OPTION_no_fd_bootchk:
5124 case QEMU_OPTION_net:
5125 if (nb_net_clients >= MAX_NET_CLIENTS) {
5126 fprintf(stderr, "qemu: too many network clients\n");
5129 net_clients[nb_net_clients] = optarg;
5133 case QEMU_OPTION_tftp:
5134 legacy_tftp_prefix = optarg;
5136 case QEMU_OPTION_bootp:
5137 legacy_bootp_filename = optarg;
5140 case QEMU_OPTION_smb:
5141 net_slirp_smb(optarg);
5144 case QEMU_OPTION_redir:
5145 net_slirp_redir(optarg);
5148 case QEMU_OPTION_bt:
5149 add_device_config(DEV_BT, optarg);
5152 case QEMU_OPTION_audio_help:
5156 case QEMU_OPTION_soundhw:
5157 select_soundhw (optarg);
5163 case QEMU_OPTION_version:
5167 case QEMU_OPTION_m: {
5171 value = strtoul(optarg, &ptr, 10);
5173 case 0: case 'M': case 'm':
5180 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5184 /* On 32-bit hosts, QEMU is limited by virtual address space */
5185 if (value > (2047 << 20)
5186 #ifndef CONFIG_KQEMU
5187 && HOST_LONG_BITS == 32
5190 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5193 if (value != (uint64_t)(ram_addr_t)value) {
5194 fprintf(stderr, "qemu: ram size too large\n");
5203 const CPULogItem *item;
5205 mask = cpu_str_to_log_mask(optarg);
5207 printf("Log items (comma separated):\n");
5208 for(item = cpu_log_items; item->mask != 0; item++) {
5209 printf("%-10s %s\n", item->name, item->help);
5217 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5219 case QEMU_OPTION_gdb:
5220 gdbstub_dev = optarg;
5225 case QEMU_OPTION_bios:
5228 case QEMU_OPTION_singlestep:
5236 keyboard_layout = optarg;
5239 case QEMU_OPTION_localtime:
5242 case QEMU_OPTION_vga:
5243 select_vgahw (optarg);
5245 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5251 w = strtol(p, (char **)&p, 10);
5254 fprintf(stderr, "qemu: invalid resolution or depth\n");
5260 h = strtol(p, (char **)&p, 10);
5265 depth = strtol(p, (char **)&p, 10);
5266 if (depth != 8 && depth != 15 && depth != 16 &&
5267 depth != 24 && depth != 32)
5269 } else if (*p == '\0') {
5270 depth = graphic_depth;
5277 graphic_depth = depth;
5281 case QEMU_OPTION_echr:
5284 term_escape_char = strtol(optarg, &r, 0);
5286 printf("Bad argument to echr\n");
5289 case QEMU_OPTION_monitor:
5290 monitor_device = optarg;
5292 case QEMU_OPTION_serial:
5293 if (serial_device_index >= MAX_SERIAL_PORTS) {
5294 fprintf(stderr, "qemu: too many serial ports\n");
5297 serial_devices[serial_device_index] = optarg;
5298 serial_device_index++;
5300 case QEMU_OPTION_watchdog:
5301 i = select_watchdog(optarg);
5303 exit (i == 1 ? 1 : 0);
5305 case QEMU_OPTION_watchdog_action:
5306 if (select_watchdog_action(optarg) == -1) {
5307 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5311 case QEMU_OPTION_virtiocon:
5312 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5313 fprintf(stderr, "qemu: too many virtio consoles\n");
5316 virtio_consoles[virtio_console_index] = optarg;
5317 virtio_console_index++;
5319 case QEMU_OPTION_parallel:
5320 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5321 fprintf(stderr, "qemu: too many parallel ports\n");
5324 parallel_devices[parallel_device_index] = optarg;
5325 parallel_device_index++;
5327 case QEMU_OPTION_loadvm:
5330 case QEMU_OPTION_full_screen:
5334 case QEMU_OPTION_no_frame:
5337 case QEMU_OPTION_alt_grab:
5340 case QEMU_OPTION_no_quit:
5343 case QEMU_OPTION_sdl:
5344 display_type = DT_SDL;
5347 case QEMU_OPTION_pidfile:
5351 case QEMU_OPTION_win2k_hack:
5352 win2k_install_hack = 1;
5354 case QEMU_OPTION_rtc_td_hack:
5357 case QEMU_OPTION_acpitable:
5358 if(acpi_table_add(optarg) < 0) {
5359 fprintf(stderr, "Wrong acpi table provided\n");
5363 case QEMU_OPTION_smbios:
5364 if(smbios_entry_add(optarg) < 0) {
5365 fprintf(stderr, "Wrong smbios provided\n");
5371 case QEMU_OPTION_enable_kqemu:
5374 case QEMU_OPTION_kernel_kqemu:
5379 case QEMU_OPTION_enable_kvm:
5386 case QEMU_OPTION_usb:
5389 case QEMU_OPTION_usbdevice:
5391 add_device_config(DEV_USB, optarg);
5393 case QEMU_OPTION_device:
5394 opts = qemu_opts_parse(&qemu_device_opts, optarg, "driver");
5396 fprintf(stderr, "parse error: %s\n", optarg);
5400 case QEMU_OPTION_smp:
5404 smp_cpus = strtol(optarg, &p, 10);
5406 fprintf(stderr, "Invalid number of CPUs\n");
5411 if (get_param_value(option, 128, "maxcpus", p))
5412 max_cpus = strtol(option, NULL, 0);
5413 if (max_cpus < smp_cpus) {
5414 fprintf(stderr, "maxcpus must be equal to or greater than "
5418 if (max_cpus > 255) {
5419 fprintf(stderr, "Unsupported number of maxcpus\n");
5424 case QEMU_OPTION_vnc:
5425 display_type = DT_VNC;
5426 vnc_display = optarg;
5429 case QEMU_OPTION_no_acpi:
5432 case QEMU_OPTION_no_hpet:
5435 case QEMU_OPTION_balloon:
5436 if (balloon_parse(optarg) < 0) {
5437 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5442 case QEMU_OPTION_no_reboot:
5445 case QEMU_OPTION_no_shutdown:
5448 case QEMU_OPTION_show_cursor:
5451 case QEMU_OPTION_uuid:
5452 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5453 fprintf(stderr, "Fail to parse UUID string."
5454 " Wrong format.\n");
5459 case QEMU_OPTION_daemonize:
5463 case QEMU_OPTION_option_rom:
5464 if (nb_option_roms >= MAX_OPTION_ROMS) {
5465 fprintf(stderr, "Too many option ROMs\n");
5468 option_rom[nb_option_roms] = optarg;
5471 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5472 case QEMU_OPTION_semihosting:
5473 semihosting_enabled = 1;
5476 case QEMU_OPTION_name:
5477 qemu_name = qemu_strdup(optarg);
5479 char *p = strchr(qemu_name, ',');
5482 if (strncmp(p, "process=", 8)) {
5483 fprintf(stderr, "Unknown subargument %s to -name", p);
5491 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5492 case QEMU_OPTION_prom_env:
5493 if (nb_prom_envs >= MAX_PROM_ENVS) {
5494 fprintf(stderr, "Too many prom variables\n");
5497 prom_envs[nb_prom_envs] = optarg;
5502 case QEMU_OPTION_old_param:
5506 case QEMU_OPTION_clock:
5507 configure_alarms(optarg);
5509 case QEMU_OPTION_startdate:
5512 time_t rtc_start_date;
5513 if (!strcmp(optarg, "now")) {
5514 rtc_date_offset = -1;
5516 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5524 } else if (sscanf(optarg, "%d-%d-%d",
5527 &tm.tm_mday) == 3) {
5536 rtc_start_date = mktimegm(&tm);
5537 if (rtc_start_date == -1) {
5539 fprintf(stderr, "Invalid date format. Valid format are:\n"
5540 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5543 rtc_date_offset = time(NULL) - rtc_start_date;
5547 case QEMU_OPTION_tb_size:
5548 tb_size = strtol(optarg, NULL, 0);
5552 case QEMU_OPTION_icount:
5554 if (strcmp(optarg, "auto") == 0) {
5555 icount_time_shift = -1;
5557 icount_time_shift = strtol(optarg, NULL, 0);
5560 case QEMU_OPTION_incoming:
5564 case QEMU_OPTION_chroot:
5565 chroot_dir = optarg;
5567 case QEMU_OPTION_runas:
5572 case QEMU_OPTION_xen_domid:
5573 xen_domid = atoi(optarg);
5575 case QEMU_OPTION_xen_create:
5576 xen_mode = XEN_CREATE;
5578 case QEMU_OPTION_xen_attach:
5579 xen_mode = XEN_ATTACH;
5586 /* If no data_dir is specified then try to find it relative to the
5589 data_dir = find_datadir(argv[0]);
5591 /* If all else fails use the install patch specified when building. */
5593 data_dir = CONFIG_QEMU_SHAREDIR;
5596 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5597 if (kvm_allowed && kqemu_allowed) {
5599 "You can not enable both KVM and kqemu at the same time\n");
5605 * Default to max_cpus = smp_cpus, in case the user doesn't
5606 * specify a max_cpus value.
5609 max_cpus = smp_cpus;
5611 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5612 if (smp_cpus > machine->max_cpus) {
5613 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5614 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5619 if (display_type == DT_NOGRAPHIC) {
5620 if (serial_device_index == 0)
5621 serial_devices[0] = "stdio";
5622 if (parallel_device_index == 0)
5623 parallel_devices[0] = "null";
5624 if (strncmp(monitor_device, "vc", 2) == 0)
5625 monitor_device = "stdio";
5632 if (pipe(fds) == -1)
5643 len = read(fds[0], &status, 1);
5644 if (len == -1 && (errno == EINTR))
5649 else if (status == 1) {
5650 fprintf(stderr, "Could not acquire pidfile\n");
5667 signal(SIGTSTP, SIG_IGN);
5668 signal(SIGTTOU, SIG_IGN);
5669 signal(SIGTTIN, SIG_IGN);
5672 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5675 write(fds[1], &status, 1);
5677 fprintf(stderr, "Could not acquire pid file\n");
5686 if (qemu_init_main_loop()) {
5687 fprintf(stderr, "qemu_init_main_loop failed\n");
5690 linux_boot = (kernel_filename != NULL);
5692 if (!linux_boot && *kernel_cmdline != '\0') {
5693 fprintf(stderr, "-append only allowed with -kernel option\n");
5697 if (!linux_boot && initrd_filename != NULL) {
5698 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5703 /* Win32 doesn't support line-buffering and requires size >= 2 */
5704 setvbuf(stdout, NULL, _IOLBF, 0);
5708 if (init_timer_alarm() < 0) {
5709 fprintf(stderr, "could not initialize alarm timer\n");
5712 if (use_icount && icount_time_shift < 0) {
5714 /* 125MIPS seems a reasonable initial guess at the guest speed.
5715 It will be corrected fairly quickly anyway. */
5716 icount_time_shift = 3;
5717 init_icount_adjust();
5724 /* init network clients */
5725 if (nb_net_clients == 0) {
5726 /* if no clients, we use a default config */
5727 net_clients[nb_net_clients++] = "nic";
5729 net_clients[nb_net_clients++] = "user";
5733 for(i = 0;i < nb_net_clients; i++) {
5734 if (net_client_parse(net_clients[i]) < 0)
5738 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5739 net_set_boot_mask(net_boot);
5743 /* init the bluetooth world */
5744 if (foreach_device_config(DEV_BT, bt_parse))
5747 /* init the memory */
5749 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5752 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5753 guest ram allocation. It needs to go away. */
5754 if (kqemu_allowed) {
5755 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
5756 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5757 if (!kqemu_phys_ram_base) {
5758 fprintf(stderr, "Could not allocate physical memory\n");
5764 /* init the dynamic translator */
5765 cpu_exec_init_all(tb_size * 1024 * 1024);
5769 /* we always create the cdrom drive, even if no disk is there */
5770 drive_add(NULL, CDROM_ALIAS);
5772 /* we always create at least one floppy */
5773 drive_add(NULL, FD_ALIAS, 0);
5775 /* we always create one sd slot, even if no card is in it */
5776 drive_add(NULL, SD_ALIAS);
5778 /* open the virtual block devices */
5780 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5781 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5784 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5785 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5788 /* must be after terminal init, SDL library changes signal handlers */
5792 /* Maintain compatibility with multiple stdio monitors */
5793 if (!strcmp(monitor_device,"stdio")) {
5794 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5795 const char *devname = serial_devices[i];
5796 if (devname && !strcmp(devname,"mon:stdio")) {
5797 monitor_device = NULL;
5799 } else if (devname && !strcmp(devname,"stdio")) {
5800 monitor_device = NULL;
5801 serial_devices[i] = "mon:stdio";
5807 if (nb_numa_nodes > 0) {
5810 if (nb_numa_nodes > smp_cpus) {
5811 nb_numa_nodes = smp_cpus;
5814 /* If no memory size if given for any node, assume the default case
5815 * and distribute the available memory equally across all nodes
5817 for (i = 0; i < nb_numa_nodes; i++) {
5818 if (node_mem[i] != 0)
5821 if (i == nb_numa_nodes) {
5822 uint64_t usedmem = 0;
5824 /* On Linux, the each node's border has to be 8MB aligned,
5825 * the final node gets the rest.
5827 for (i = 0; i < nb_numa_nodes - 1; i++) {
5828 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5829 usedmem += node_mem[i];
5831 node_mem[i] = ram_size - usedmem;
5834 for (i = 0; i < nb_numa_nodes; i++) {
5835 if (node_cpumask[i] != 0)
5838 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5839 * must cope with this anyway, because there are BIOSes out there in
5840 * real machines which also use this scheme.
5842 if (i == nb_numa_nodes) {
5843 for (i = 0; i < smp_cpus; i++) {
5844 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5849 if (kvm_enabled()) {
5852 ret = kvm_init(smp_cpus);
5854 fprintf(stderr, "failed to initialize KVM\n");
5859 if (monitor_device) {
5860 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5862 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5867 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5868 const char *devname = serial_devices[i];
5869 if (devname && strcmp(devname, "none")) {
5871 snprintf(label, sizeof(label), "serial%d", i);
5872 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5873 if (!serial_hds[i]) {
5874 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5881 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5882 const char *devname = parallel_devices[i];
5883 if (devname && strcmp(devname, "none")) {
5885 snprintf(label, sizeof(label), "parallel%d", i);
5886 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5887 if (!parallel_hds[i]) {
5888 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5895 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5896 const char *devname = virtio_consoles[i];
5897 if (devname && strcmp(devname, "none")) {
5899 snprintf(label, sizeof(label), "virtcon%d", i);
5900 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5901 if (!virtcon_hds[i]) {
5902 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5909 module_call_init(MODULE_INIT_DEVICE);
5911 if (machine->compat_props) {
5912 qdev_prop_register_compat(machine->compat_props);
5914 machine->init(ram_size, boot_devices,
5915 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5918 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5919 for (i = 0; i < nb_numa_nodes; i++) {
5920 if (node_cpumask[i] & (1 << env->cpu_index)) {
5926 current_machine = machine;
5928 /* init USB devices */
5930 foreach_device_config(DEV_USB, usb_parse);
5933 /* init generic devices */
5934 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5938 dumb_display_init();
5939 /* just use the first displaystate for the moment */
5942 if (display_type == DT_DEFAULT) {
5943 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5944 display_type = DT_SDL;
5946 display_type = DT_VNC;
5947 vnc_display = "localhost:0,to=99";
5953 switch (display_type) {
5956 #if defined(CONFIG_CURSES)
5958 curses_display_init(ds, full_screen);
5961 #if defined(CONFIG_SDL)
5963 sdl_display_init(ds, full_screen, no_frame);
5965 #elif defined(CONFIG_COCOA)
5967 cocoa_display_init(ds, full_screen);
5971 vnc_display_init(ds);
5972 if (vnc_display_open(ds, vnc_display) < 0)
5975 if (show_vnc_port) {
5976 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5984 dcl = ds->listeners;
5985 while (dcl != NULL) {
5986 if (dcl->dpy_refresh != NULL) {
5987 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5988 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5993 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5994 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5995 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5998 text_consoles_set_display(display_state);
5999 qemu_chr_initial_reset();
6001 if (monitor_device && monitor_hd)
6002 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6004 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6005 const char *devname = serial_devices[i];
6006 if (devname && strcmp(devname, "none")) {
6007 if (strstart(devname, "vc", 0))
6008 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6012 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6013 const char *devname = parallel_devices[i];
6014 if (devname && strcmp(devname, "none")) {
6015 if (strstart(devname, "vc", 0))
6016 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6020 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6021 const char *devname = virtio_consoles[i];
6022 if (virtcon_hds[i] && devname) {
6023 if (strstart(devname, "vc", 0))
6024 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6028 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6029 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6035 do_loadvm(cur_mon, loadvm);
6038 qemu_start_incoming_migration(incoming);
6039 } else if (autostart) {
6049 len = write(fds[1], &status, 1);
6050 if (len == -1 && (errno == EINTR))
6057 TFR(fd = open("/dev/null", O_RDWR));
6063 pwd = getpwnam(run_as);
6065 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6071 if (chroot(chroot_dir) < 0) {
6072 fprintf(stderr, "chroot failed\n");
6079 if (setgid(pwd->pw_gid) < 0) {
6080 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6083 if (setuid(pwd->pw_uid) < 0) {
6084 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6087 if (setuid(0) != -1) {
6088 fprintf(stderr, "Dropping privileges failed\n");