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 HOST_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>
112 #include <sys/timeb.h>
113 #include <mmsystem.h>
114 #define getopt_long_only getopt_long
115 #define memalign(align, size) malloc(size)
119 #if defined(__APPLE__) || defined(main)
121 int qemu_main(int argc, char **argv, char **envp);
122 int main(int argc, char **argv)
124 return qemu_main(argc, argv, NULL);
127 #define main qemu_main
129 #endif /* CONFIG_SDL */
133 #define main qemu_main
134 #endif /* CONFIG_COCOA */
137 #include "hw/boards.h"
139 #include "hw/pcmcia.h"
141 #include "hw/audiodev.h"
145 #include "hw/watchdog.h"
146 #include "hw/smbios.h"
155 #include "qemu-timer.h"
156 #include "qemu-char.h"
157 #include "cache-utils.h"
160 #include "audio/audio.h"
161 #include "migration.h"
164 #include "qemu-option.h"
168 #include "exec-all.h"
170 #include "qemu_socket.h"
172 #include "slirp/libslirp.h"
175 //#define DEBUG_SLIRP
177 #define DEFAULT_RAM_SIZE 128
179 static const char *data_dir;
180 const char *bios_name = NULL;
181 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
182 to store the VM snapshots */
183 DriveInfo drives_table[MAX_DRIVES+1];
185 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
186 static DisplayState *display_state;
187 DisplayType display_type = DT_DEFAULT;
188 const char* keyboard_layout = NULL;
189 int64_t ticks_per_sec;
192 NICInfo nd_table[MAX_NICS];
194 static int autostart;
195 static int rtc_utc = 1;
196 static int rtc_date_offset = -1; /* -1 means no change */
197 int cirrus_vga_enabled = 1;
198 int std_vga_enabled = 0;
199 int vmsvga_enabled = 0;
200 int xenfb_enabled = 0;
202 int graphic_width = 1024;
203 int graphic_height = 768;
204 int graphic_depth = 8;
206 int graphic_width = 800;
207 int graphic_height = 600;
208 int graphic_depth = 15;
210 static int full_screen = 0;
212 static int no_frame = 0;
215 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
216 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
217 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
219 int win2k_install_hack = 0;
225 const char *vnc_display;
226 int acpi_enabled = 1;
228 int virtio_balloon = 1;
229 const char *virtio_balloon_devaddr;
234 int graphic_rotate = 0;
238 WatchdogTimerModel *watchdog = NULL;
239 int watchdog_action = WDT_RESET;
240 const char *option_rom[MAX_OPTION_ROMS];
242 int semihosting_enabled = 0;
246 const char *qemu_name;
248 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
249 unsigned int nb_prom_envs = 0;
250 const char *prom_envs[MAX_PROM_ENVS];
253 struct drive_opt drives_opt[MAX_DRIVES];
257 uint64_t node_mem[MAX_NODES];
258 uint64_t node_cpumask[MAX_NODES];
260 static CPUState *cur_cpu;
261 static CPUState *next_cpu;
262 static int timer_alarm_pending = 1;
263 /* Conversion factor from emulated instructions to virtual clock ticks. */
264 static int icount_time_shift;
265 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
266 #define MAX_ICOUNT_SHIFT 10
267 /* Compensate for varying guest execution speed. */
268 static int64_t qemu_icount_bias;
269 static QEMUTimer *icount_rt_timer;
270 static QEMUTimer *icount_vm_timer;
271 static QEMUTimer *nographic_timer;
273 uint8_t qemu_uuid[16];
275 static QEMUBootSetHandler *boot_set_handler;
276 static void *boot_set_opaque;
278 /***********************************************************/
279 /* x86 ISA bus support */
281 target_phys_addr_t isa_mem_base = 0;
284 /***********************************************************/
285 void hw_error(const char *fmt, ...)
291 fprintf(stderr, "qemu: hardware error: ");
292 vfprintf(stderr, fmt, ap);
293 fprintf(stderr, "\n");
294 for(env = first_cpu; env != NULL; env = env->next_cpu) {
295 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
297 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
299 cpu_dump_state(env, stderr, fprintf, 0);
306 static void set_proc_name(const char *s)
312 name[sizeof(name) - 1] = 0;
313 strncpy(name, s, sizeof(name));
314 /* Could rewrite argv[0] too, but that's a bit more complicated.
315 This simple way is enough for `top'. */
316 prctl(PR_SET_NAME, name);
323 static QEMUBalloonEvent *qemu_balloon_event;
324 void *qemu_balloon_event_opaque;
326 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
328 qemu_balloon_event = func;
329 qemu_balloon_event_opaque = opaque;
332 void qemu_balloon(ram_addr_t target)
334 if (qemu_balloon_event)
335 qemu_balloon_event(qemu_balloon_event_opaque, target);
338 ram_addr_t qemu_balloon_status(void)
340 if (qemu_balloon_event)
341 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
345 /***********************************************************/
348 static QEMUPutKBDEvent *qemu_put_kbd_event;
349 static void *qemu_put_kbd_event_opaque;
350 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
351 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
353 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
355 qemu_put_kbd_event_opaque = opaque;
356 qemu_put_kbd_event = func;
359 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
360 void *opaque, int absolute,
363 QEMUPutMouseEntry *s, *cursor;
365 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
367 s->qemu_put_mouse_event = func;
368 s->qemu_put_mouse_event_opaque = opaque;
369 s->qemu_put_mouse_event_absolute = absolute;
370 s->qemu_put_mouse_event_name = qemu_strdup(name);
373 if (!qemu_put_mouse_event_head) {
374 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
378 cursor = qemu_put_mouse_event_head;
379 while (cursor->next != NULL)
380 cursor = cursor->next;
383 qemu_put_mouse_event_current = s;
388 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
390 QEMUPutMouseEntry *prev = NULL, *cursor;
392 if (!qemu_put_mouse_event_head || entry == NULL)
395 cursor = qemu_put_mouse_event_head;
396 while (cursor != NULL && cursor != entry) {
398 cursor = cursor->next;
401 if (cursor == NULL) // does not exist or list empty
403 else if (prev == NULL) { // entry is head
404 qemu_put_mouse_event_head = cursor->next;
405 if (qemu_put_mouse_event_current == entry)
406 qemu_put_mouse_event_current = cursor->next;
407 qemu_free(entry->qemu_put_mouse_event_name);
412 prev->next = entry->next;
414 if (qemu_put_mouse_event_current == entry)
415 qemu_put_mouse_event_current = prev;
417 qemu_free(entry->qemu_put_mouse_event_name);
421 void kbd_put_keycode(int keycode)
423 if (qemu_put_kbd_event) {
424 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
428 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
430 QEMUPutMouseEvent *mouse_event;
431 void *mouse_event_opaque;
434 if (!qemu_put_mouse_event_current) {
439 qemu_put_mouse_event_current->qemu_put_mouse_event;
441 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
444 if (graphic_rotate) {
445 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
448 width = graphic_width - 1;
449 mouse_event(mouse_event_opaque,
450 width - dy, dx, dz, buttons_state);
452 mouse_event(mouse_event_opaque,
453 dx, dy, dz, buttons_state);
457 int kbd_mouse_is_absolute(void)
459 if (!qemu_put_mouse_event_current)
462 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
465 void do_info_mice(Monitor *mon)
467 QEMUPutMouseEntry *cursor;
470 if (!qemu_put_mouse_event_head) {
471 monitor_printf(mon, "No mouse devices connected\n");
475 monitor_printf(mon, "Mouse devices available:\n");
476 cursor = qemu_put_mouse_event_head;
477 while (cursor != NULL) {
478 monitor_printf(mon, "%c Mouse #%d: %s\n",
479 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
480 index, cursor->qemu_put_mouse_event_name);
482 cursor = cursor->next;
486 void do_mouse_set(Monitor *mon, int index)
488 QEMUPutMouseEntry *cursor;
491 if (!qemu_put_mouse_event_head) {
492 monitor_printf(mon, "No mouse devices connected\n");
496 cursor = qemu_put_mouse_event_head;
497 while (cursor != NULL && index != i) {
499 cursor = cursor->next;
503 qemu_put_mouse_event_current = cursor;
505 monitor_printf(mon, "Mouse at given index not found\n");
508 /* compute with 96 bit intermediate result: (a*b)/c */
509 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
514 #ifdef WORDS_BIGENDIAN
524 rl = (uint64_t)u.l.low * (uint64_t)b;
525 rh = (uint64_t)u.l.high * (uint64_t)b;
528 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
532 /***********************************************************/
533 /* real time host monotonic timer */
535 #define QEMU_TIMER_BASE 1000000000LL
539 static int64_t clock_freq;
541 static void init_get_clock(void)
545 ret = QueryPerformanceFrequency(&freq);
547 fprintf(stderr, "Could not calibrate ticks\n");
550 clock_freq = freq.QuadPart;
553 static int64_t get_clock(void)
556 QueryPerformanceCounter(&ti);
557 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
562 static int use_rt_clock;
564 static void init_get_clock(void)
567 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
568 || defined(__DragonFly__)
571 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
578 static int64_t get_clock(void)
580 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
581 || defined(__DragonFly__)
584 clock_gettime(CLOCK_MONOTONIC, &ts);
585 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
589 /* XXX: using gettimeofday leads to problems if the date
590 changes, so it should be avoided. */
592 gettimeofday(&tv, NULL);
593 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
598 /* Return the virtual CPU time, based on the instruction counter. */
599 static int64_t cpu_get_icount(void)
602 CPUState *env = cpu_single_env;;
603 icount = qemu_icount;
606 fprintf(stderr, "Bad clock read\n");
607 icount -= (env->icount_decr.u16.low + env->icount_extra);
609 return qemu_icount_bias + (icount << icount_time_shift);
612 /***********************************************************/
613 /* guest cycle counter */
615 static int64_t cpu_ticks_prev;
616 static int64_t cpu_ticks_offset;
617 static int64_t cpu_clock_offset;
618 static int cpu_ticks_enabled;
620 /* return the host CPU cycle counter and handle stop/restart */
621 int64_t cpu_get_ticks(void)
624 return cpu_get_icount();
626 if (!cpu_ticks_enabled) {
627 return cpu_ticks_offset;
630 ticks = cpu_get_real_ticks();
631 if (cpu_ticks_prev > ticks) {
632 /* Note: non increasing ticks may happen if the host uses
634 cpu_ticks_offset += cpu_ticks_prev - ticks;
636 cpu_ticks_prev = ticks;
637 return ticks + cpu_ticks_offset;
641 /* return the host CPU monotonic timer and handle stop/restart */
642 static int64_t cpu_get_clock(void)
645 if (!cpu_ticks_enabled) {
646 return cpu_clock_offset;
649 return ti + cpu_clock_offset;
653 /* enable cpu_get_ticks() */
654 void cpu_enable_ticks(void)
656 if (!cpu_ticks_enabled) {
657 cpu_ticks_offset -= cpu_get_real_ticks();
658 cpu_clock_offset -= get_clock();
659 cpu_ticks_enabled = 1;
663 /* disable cpu_get_ticks() : the clock is stopped. You must not call
664 cpu_get_ticks() after that. */
665 void cpu_disable_ticks(void)
667 if (cpu_ticks_enabled) {
668 cpu_ticks_offset = cpu_get_ticks();
669 cpu_clock_offset = cpu_get_clock();
670 cpu_ticks_enabled = 0;
674 /***********************************************************/
677 #define QEMU_TIMER_REALTIME 0
678 #define QEMU_TIMER_VIRTUAL 1
682 /* XXX: add frequency */
690 struct QEMUTimer *next;
693 struct qemu_alarm_timer {
697 int (*start)(struct qemu_alarm_timer *t);
698 void (*stop)(struct qemu_alarm_timer *t);
699 void (*rearm)(struct qemu_alarm_timer *t);
703 #define ALARM_FLAG_DYNTICKS 0x1
704 #define ALARM_FLAG_EXPIRED 0x2
706 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
708 return t && (t->flags & ALARM_FLAG_DYNTICKS);
711 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
713 if (!alarm_has_dynticks(t))
719 /* TODO: MIN_TIMER_REARM_US should be optimized */
720 #define MIN_TIMER_REARM_US 250
722 static struct qemu_alarm_timer *alarm_timer;
726 struct qemu_alarm_win32 {
729 } alarm_win32_data = {0, -1};
731 static int win32_start_timer(struct qemu_alarm_timer *t);
732 static void win32_stop_timer(struct qemu_alarm_timer *t);
733 static void win32_rearm_timer(struct qemu_alarm_timer *t);
737 static int unix_start_timer(struct qemu_alarm_timer *t);
738 static void unix_stop_timer(struct qemu_alarm_timer *t);
742 static int dynticks_start_timer(struct qemu_alarm_timer *t);
743 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
744 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
746 static int hpet_start_timer(struct qemu_alarm_timer *t);
747 static void hpet_stop_timer(struct qemu_alarm_timer *t);
749 static int rtc_start_timer(struct qemu_alarm_timer *t);
750 static void rtc_stop_timer(struct qemu_alarm_timer *t);
752 #endif /* __linux__ */
756 /* Correlation between real and virtual time is always going to be
757 fairly approximate, so ignore small variation.
758 When the guest is idle real and virtual time will be aligned in
760 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
762 static void icount_adjust(void)
767 static int64_t last_delta;
768 /* If the VM is not running, then do nothing. */
772 cur_time = cpu_get_clock();
773 cur_icount = qemu_get_clock(vm_clock);
774 delta = cur_icount - cur_time;
775 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
777 && last_delta + ICOUNT_WOBBLE < delta * 2
778 && icount_time_shift > 0) {
779 /* The guest is getting too far ahead. Slow time down. */
783 && last_delta - ICOUNT_WOBBLE > delta * 2
784 && icount_time_shift < MAX_ICOUNT_SHIFT) {
785 /* The guest is getting too far behind. Speed time up. */
789 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
792 static void icount_adjust_rt(void * opaque)
794 qemu_mod_timer(icount_rt_timer,
795 qemu_get_clock(rt_clock) + 1000);
799 static void icount_adjust_vm(void * opaque)
801 qemu_mod_timer(icount_vm_timer,
802 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
806 static void init_icount_adjust(void)
808 /* Have both realtime and virtual time triggers for speed adjustment.
809 The realtime trigger catches emulated time passing too slowly,
810 the virtual time trigger catches emulated time passing too fast.
811 Realtime triggers occur even when idle, so use them less frequently
813 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
814 qemu_mod_timer(icount_rt_timer,
815 qemu_get_clock(rt_clock) + 1000);
816 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
817 qemu_mod_timer(icount_vm_timer,
818 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
821 static struct qemu_alarm_timer alarm_timers[] = {
824 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
825 dynticks_stop_timer, dynticks_rearm_timer, NULL},
826 /* HPET - if available - is preferred */
827 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
828 /* ...otherwise try RTC */
829 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
831 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
833 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
834 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
835 {"win32", 0, win32_start_timer,
836 win32_stop_timer, NULL, &alarm_win32_data},
841 static void show_available_alarms(void)
845 printf("Available alarm timers, in order of precedence:\n");
846 for (i = 0; alarm_timers[i].name; i++)
847 printf("%s\n", alarm_timers[i].name);
850 static void configure_alarms(char const *opt)
854 int count = ARRAY_SIZE(alarm_timers) - 1;
857 struct qemu_alarm_timer tmp;
859 if (!strcmp(opt, "?")) {
860 show_available_alarms();
866 /* Reorder the array */
867 name = strtok(arg, ",");
869 for (i = 0; i < count && alarm_timers[i].name; i++) {
870 if (!strcmp(alarm_timers[i].name, name))
875 fprintf(stderr, "Unknown clock %s\n", name);
884 tmp = alarm_timers[i];
885 alarm_timers[i] = alarm_timers[cur];
886 alarm_timers[cur] = tmp;
890 name = strtok(NULL, ",");
896 /* Disable remaining timers */
897 for (i = cur; i < count; i++)
898 alarm_timers[i].name = NULL;
900 show_available_alarms();
908 static QEMUTimer *active_timers[2];
910 static QEMUClock *qemu_new_clock(int type)
913 clock = qemu_mallocz(sizeof(QEMUClock));
918 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
922 ts = qemu_mallocz(sizeof(QEMUTimer));
929 void qemu_free_timer(QEMUTimer *ts)
934 /* stop a timer, but do not dealloc it */
935 void qemu_del_timer(QEMUTimer *ts)
939 /* NOTE: this code must be signal safe because
940 qemu_timer_expired() can be called from a signal. */
941 pt = &active_timers[ts->clock->type];
954 /* modify the current timer so that it will be fired when current_time
955 >= expire_time. The corresponding callback will be called. */
956 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
962 /* add the timer in the sorted list */
963 /* NOTE: this code must be signal safe because
964 qemu_timer_expired() can be called from a signal. */
965 pt = &active_timers[ts->clock->type];
970 if (t->expire_time > expire_time)
974 ts->expire_time = expire_time;
978 /* Rearm if necessary */
979 if (pt == &active_timers[ts->clock->type]) {
980 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
981 qemu_rearm_alarm_timer(alarm_timer);
983 /* Interrupt execution to force deadline recalculation. */
989 int qemu_timer_pending(QEMUTimer *ts)
992 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
999 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1003 return (timer_head->expire_time <= current_time);
1006 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1012 if (!ts || ts->expire_time > current_time)
1014 /* remove timer from the list before calling the callback */
1015 *ptimer_head = ts->next;
1018 /* run the callback (the timer list can be modified) */
1023 int64_t qemu_get_clock(QEMUClock *clock)
1025 switch(clock->type) {
1026 case QEMU_TIMER_REALTIME:
1027 return get_clock() / 1000000;
1029 case QEMU_TIMER_VIRTUAL:
1031 return cpu_get_icount();
1033 return cpu_get_clock();
1038 static void init_timers(void)
1041 ticks_per_sec = QEMU_TIMER_BASE;
1042 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1043 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1047 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1049 uint64_t expire_time;
1051 if (qemu_timer_pending(ts)) {
1052 expire_time = ts->expire_time;
1056 qemu_put_be64(f, expire_time);
1059 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1061 uint64_t expire_time;
1063 expire_time = qemu_get_be64(f);
1064 if (expire_time != -1) {
1065 qemu_mod_timer(ts, expire_time);
1071 static void timer_save(QEMUFile *f, void *opaque)
1073 if (cpu_ticks_enabled) {
1074 hw_error("cannot save state if virtual timers are running");
1076 qemu_put_be64(f, cpu_ticks_offset);
1077 qemu_put_be64(f, ticks_per_sec);
1078 qemu_put_be64(f, cpu_clock_offset);
1081 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1083 if (version_id != 1 && version_id != 2)
1085 if (cpu_ticks_enabled) {
1088 cpu_ticks_offset=qemu_get_be64(f);
1089 ticks_per_sec=qemu_get_be64(f);
1090 if (version_id == 2) {
1091 cpu_clock_offset=qemu_get_be64(f);
1096 static void qemu_event_increment(void);
1099 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1100 DWORD_PTR dwUser, DWORD_PTR dw1,
1103 static void host_alarm_handler(int host_signum)
1107 #define DISP_FREQ 1000
1109 static int64_t delta_min = INT64_MAX;
1110 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1112 ti = qemu_get_clock(vm_clock);
1113 if (last_clock != 0) {
1114 delta = ti - last_clock;
1115 if (delta < delta_min)
1117 if (delta > delta_max)
1120 if (++count == DISP_FREQ) {
1121 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1122 muldiv64(delta_min, 1000000, ticks_per_sec),
1123 muldiv64(delta_max, 1000000, ticks_per_sec),
1124 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1125 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1127 delta_min = INT64_MAX;
1135 if (alarm_has_dynticks(alarm_timer) ||
1137 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1138 qemu_get_clock(vm_clock))) ||
1139 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1140 qemu_get_clock(rt_clock))) {
1141 qemu_event_increment();
1142 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1144 #ifndef CONFIG_IOTHREAD
1146 /* stop the currently executing cpu because a timer occured */
1149 if (next_cpu->kqemu_enabled) {
1150 kqemu_cpu_interrupt(next_cpu);
1155 timer_alarm_pending = 1;
1156 qemu_notify_event();
1160 static int64_t qemu_next_deadline(void)
1164 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1165 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1166 qemu_get_clock(vm_clock);
1168 /* To avoid problems with overflow limit this to 2^32. */
1178 #if defined(__linux__) || defined(_WIN32)
1179 static uint64_t qemu_next_deadline_dyntick(void)
1187 delta = (qemu_next_deadline() + 999) / 1000;
1189 if (active_timers[QEMU_TIMER_REALTIME]) {
1190 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1191 qemu_get_clock(rt_clock))*1000;
1192 if (rtdelta < delta)
1196 if (delta < MIN_TIMER_REARM_US)
1197 delta = MIN_TIMER_REARM_US;
1205 /* Sets a specific flag */
1206 static int fcntl_setfl(int fd, int flag)
1210 flags = fcntl(fd, F_GETFL);
1214 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1220 #if defined(__linux__)
1222 #define RTC_FREQ 1024
1224 static void enable_sigio_timer(int fd)
1226 struct sigaction act;
1229 sigfillset(&act.sa_mask);
1231 act.sa_handler = host_alarm_handler;
1233 sigaction(SIGIO, &act, NULL);
1234 fcntl_setfl(fd, O_ASYNC);
1235 fcntl(fd, F_SETOWN, getpid());
1238 static int hpet_start_timer(struct qemu_alarm_timer *t)
1240 struct hpet_info info;
1243 fd = open("/dev/hpet", O_RDONLY);
1248 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1250 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1251 "error, but for better emulation accuracy type:\n"
1252 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1256 /* Check capabilities */
1257 r = ioctl(fd, HPET_INFO, &info);
1261 /* Enable periodic mode */
1262 r = ioctl(fd, HPET_EPI, 0);
1263 if (info.hi_flags && (r < 0))
1266 /* Enable interrupt */
1267 r = ioctl(fd, HPET_IE_ON, 0);
1271 enable_sigio_timer(fd);
1272 t->priv = (void *)(long)fd;
1280 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1282 int fd = (long)t->priv;
1287 static int rtc_start_timer(struct qemu_alarm_timer *t)
1290 unsigned long current_rtc_freq = 0;
1292 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1295 ioctl(rtc_fd, RTC_IRQP_READ, ¤t_rtc_freq);
1296 if (current_rtc_freq != RTC_FREQ &&
1297 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1298 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1299 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1300 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1303 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1309 enable_sigio_timer(rtc_fd);
1311 t->priv = (void *)(long)rtc_fd;
1316 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1318 int rtc_fd = (long)t->priv;
1323 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1327 struct sigaction act;
1329 sigfillset(&act.sa_mask);
1331 act.sa_handler = host_alarm_handler;
1333 sigaction(SIGALRM, &act, NULL);
1336 * Initialize ev struct to 0 to avoid valgrind complaining
1337 * about uninitialized data in timer_create call
1339 memset(&ev, 0, sizeof(ev));
1340 ev.sigev_value.sival_int = 0;
1341 ev.sigev_notify = SIGEV_SIGNAL;
1342 ev.sigev_signo = SIGALRM;
1344 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1345 perror("timer_create");
1347 /* disable dynticks */
1348 fprintf(stderr, "Dynamic Ticks disabled\n");
1353 t->priv = (void *)(long)host_timer;
1358 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1360 timer_t host_timer = (timer_t)(long)t->priv;
1362 timer_delete(host_timer);
1365 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1367 timer_t host_timer = (timer_t)(long)t->priv;
1368 struct itimerspec timeout;
1369 int64_t nearest_delta_us = INT64_MAX;
1372 if (!active_timers[QEMU_TIMER_REALTIME] &&
1373 !active_timers[QEMU_TIMER_VIRTUAL])
1376 nearest_delta_us = qemu_next_deadline_dyntick();
1378 /* check whether a timer is already running */
1379 if (timer_gettime(host_timer, &timeout)) {
1381 fprintf(stderr, "Internal timer error: aborting\n");
1384 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1385 if (current_us && current_us <= nearest_delta_us)
1388 timeout.it_interval.tv_sec = 0;
1389 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1390 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1391 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1392 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1394 fprintf(stderr, "Internal timer error: aborting\n");
1399 #endif /* defined(__linux__) */
1401 static int unix_start_timer(struct qemu_alarm_timer *t)
1403 struct sigaction act;
1404 struct itimerval itv;
1408 sigfillset(&act.sa_mask);
1410 act.sa_handler = host_alarm_handler;
1412 sigaction(SIGALRM, &act, NULL);
1414 itv.it_interval.tv_sec = 0;
1415 /* for i386 kernel 2.6 to get 1 ms */
1416 itv.it_interval.tv_usec = 999;
1417 itv.it_value.tv_sec = 0;
1418 itv.it_value.tv_usec = 10 * 1000;
1420 err = setitimer(ITIMER_REAL, &itv, NULL);
1427 static void unix_stop_timer(struct qemu_alarm_timer *t)
1429 struct itimerval itv;
1431 memset(&itv, 0, sizeof(itv));
1432 setitimer(ITIMER_REAL, &itv, NULL);
1435 #endif /* !defined(_WIN32) */
1440 static int win32_start_timer(struct qemu_alarm_timer *t)
1443 struct qemu_alarm_win32 *data = t->priv;
1446 memset(&tc, 0, sizeof(tc));
1447 timeGetDevCaps(&tc, sizeof(tc));
1449 if (data->period < tc.wPeriodMin)
1450 data->period = tc.wPeriodMin;
1452 timeBeginPeriod(data->period);
1454 flags = TIME_CALLBACK_FUNCTION;
1455 if (alarm_has_dynticks(t))
1456 flags |= TIME_ONESHOT;
1458 flags |= TIME_PERIODIC;
1460 data->timerId = timeSetEvent(1, // interval (ms)
1461 data->period, // resolution
1462 host_alarm_handler, // function
1463 (DWORD)t, // parameter
1466 if (!data->timerId) {
1467 perror("Failed to initialize win32 alarm timer");
1468 timeEndPeriod(data->period);
1475 static void win32_stop_timer(struct qemu_alarm_timer *t)
1477 struct qemu_alarm_win32 *data = t->priv;
1479 timeKillEvent(data->timerId);
1480 timeEndPeriod(data->period);
1483 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1485 struct qemu_alarm_win32 *data = t->priv;
1486 uint64_t nearest_delta_us;
1488 if (!active_timers[QEMU_TIMER_REALTIME] &&
1489 !active_timers[QEMU_TIMER_VIRTUAL])
1492 nearest_delta_us = qemu_next_deadline_dyntick();
1493 nearest_delta_us /= 1000;
1495 timeKillEvent(data->timerId);
1497 data->timerId = timeSetEvent(1,
1501 TIME_ONESHOT | TIME_PERIODIC);
1503 if (!data->timerId) {
1504 perror("Failed to re-arm win32 alarm timer");
1506 timeEndPeriod(data->period);
1513 static int init_timer_alarm(void)
1515 struct qemu_alarm_timer *t = NULL;
1518 for (i = 0; alarm_timers[i].name; i++) {
1519 t = &alarm_timers[i];
1539 static void quit_timers(void)
1541 alarm_timer->stop(alarm_timer);
1545 /***********************************************************/
1546 /* host time/date access */
1547 void qemu_get_timedate(struct tm *tm, int offset)
1554 if (rtc_date_offset == -1) {
1558 ret = localtime(&ti);
1560 ti -= rtc_date_offset;
1564 memcpy(tm, ret, sizeof(struct tm));
1567 int qemu_timedate_diff(struct tm *tm)
1571 if (rtc_date_offset == -1)
1573 seconds = mktimegm(tm);
1575 seconds = mktime(tm);
1577 seconds = mktimegm(tm) + rtc_date_offset;
1579 return seconds - time(NULL);
1583 static void socket_cleanup(void)
1588 static int socket_init(void)
1593 ret = WSAStartup(MAKEWORD(2,2), &Data);
1595 err = WSAGetLastError();
1596 fprintf(stderr, "WSAStartup: %d\n", err);
1599 atexit(socket_cleanup);
1604 int get_next_param_value(char *buf, int buf_size,
1605 const char *tag, const char **pstr)
1612 p = get_opt_name(option, sizeof(option), p, '=');
1616 if (!strcmp(tag, option)) {
1617 *pstr = get_opt_value(buf, buf_size, p);
1618 if (**pstr == ',') {
1623 p = get_opt_value(NULL, 0, p);
1632 int get_param_value(char *buf, int buf_size,
1633 const char *tag, const char *str)
1635 return get_next_param_value(buf, buf_size, tag, &str);
1638 int check_params(char *buf, int buf_size,
1639 const char * const *params, const char *str)
1645 while (*p != '\0') {
1646 p = get_opt_name(buf, buf_size, p, '=');
1651 for (i = 0; params[i] != NULL; i++) {
1652 if (!strcmp(params[i], buf)) {
1656 if (params[i] == NULL) {
1659 p = get_opt_value(NULL, 0, p);
1668 /***********************************************************/
1669 /* Bluetooth support */
1672 static struct HCIInfo *hci_table[MAX_NICS];
1674 static struct bt_vlan_s {
1675 struct bt_scatternet_s net;
1677 struct bt_vlan_s *next;
1680 /* find or alloc a new bluetooth "VLAN" */
1681 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1683 struct bt_vlan_s **pvlan, *vlan;
1684 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1688 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1690 pvlan = &first_bt_vlan;
1691 while (*pvlan != NULL)
1692 pvlan = &(*pvlan)->next;
1697 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1701 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1706 static struct HCIInfo null_hci = {
1707 .cmd_send = null_hci_send,
1708 .sco_send = null_hci_send,
1709 .acl_send = null_hci_send,
1710 .bdaddr_set = null_hci_addr_set,
1713 struct HCIInfo *qemu_next_hci(void)
1715 if (cur_hci == nb_hcis)
1718 return hci_table[cur_hci++];
1721 static struct HCIInfo *hci_init(const char *str)
1724 struct bt_scatternet_s *vlan = 0;
1726 if (!strcmp(str, "null"))
1729 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1731 return bt_host_hci(str[4] ? str + 5 : "hci0");
1732 else if (!strncmp(str, "hci", 3)) {
1735 if (!strncmp(str + 3, ",vlan=", 6)) {
1736 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1741 vlan = qemu_find_bt_vlan(0);
1743 return bt_new_hci(vlan);
1746 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1751 static int bt_hci_parse(const char *str)
1753 struct HCIInfo *hci;
1756 if (nb_hcis >= MAX_NICS) {
1757 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1761 hci = hci_init(str);
1770 bdaddr.b[5] = 0x56 + nb_hcis;
1771 hci->bdaddr_set(hci, bdaddr.b);
1773 hci_table[nb_hcis++] = hci;
1778 static void bt_vhci_add(int vlan_id)
1780 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1783 fprintf(stderr, "qemu: warning: adding a VHCI to "
1784 "an empty scatternet %i\n", vlan_id);
1786 bt_vhci_init(bt_new_hci(vlan));
1789 static struct bt_device_s *bt_device_add(const char *opt)
1791 struct bt_scatternet_s *vlan;
1793 char *endp = strstr(opt, ",vlan=");
1794 int len = (endp ? endp - opt : strlen(opt)) + 1;
1797 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1800 vlan_id = strtol(endp + 6, &endp, 0);
1802 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1807 vlan = qemu_find_bt_vlan(vlan_id);
1810 fprintf(stderr, "qemu: warning: adding a slave device to "
1811 "an empty scatternet %i\n", vlan_id);
1813 if (!strcmp(devname, "keyboard"))
1814 return bt_keyboard_init(vlan);
1816 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1820 static int bt_parse(const char *opt)
1822 const char *endp, *p;
1825 if (strstart(opt, "hci", &endp)) {
1826 if (!*endp || *endp == ',') {
1828 if (!strstart(endp, ",vlan=", 0))
1831 return bt_hci_parse(opt);
1833 } else if (strstart(opt, "vhci", &endp)) {
1834 if (!*endp || *endp == ',') {
1836 if (strstart(endp, ",vlan=", &p)) {
1837 vlan = strtol(p, (char **) &endp, 0);
1839 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1843 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1852 } else if (strstart(opt, "device:", &endp))
1853 return !bt_device_add(endp);
1855 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1859 /***********************************************************/
1860 /* QEMU Block devices */
1862 #define HD_ALIAS "index=%d,media=disk"
1863 #define CDROM_ALIAS "index=2,media=cdrom"
1864 #define FD_ALIAS "index=%d,if=floppy"
1865 #define PFLASH_ALIAS "if=pflash"
1866 #define MTD_ALIAS "if=mtd"
1867 #define SD_ALIAS "index=0,if=sd"
1869 static int drive_opt_get_free_idx(void)
1873 for (index = 0; index < MAX_DRIVES; index++)
1874 if (!drives_opt[index].used) {
1875 drives_opt[index].used = 1;
1882 static int drive_get_free_idx(void)
1886 for (index = 0; index < MAX_DRIVES; index++)
1887 if (!drives_table[index].used) {
1888 drives_table[index].used = 1;
1895 int drive_add(const char *file, const char *fmt, ...)
1898 int index = drive_opt_get_free_idx();
1900 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
1901 fprintf(stderr, "qemu: too many drives\n");
1905 drives_opt[index].file = file;
1907 vsnprintf(drives_opt[index].opt,
1908 sizeof(drives_opt[0].opt), fmt, ap);
1915 void drive_remove(int index)
1917 drives_opt[index].used = 0;
1921 int drive_get_index(BlockInterfaceType type, int bus, int unit)
1925 /* seek interface, bus and unit */
1927 for (index = 0; index < MAX_DRIVES; index++)
1928 if (drives_table[index].type == type &&
1929 drives_table[index].bus == bus &&
1930 drives_table[index].unit == unit &&
1931 drives_table[index].used)
1937 int drive_get_max_bus(BlockInterfaceType type)
1943 for (index = 0; index < nb_drives; index++) {
1944 if(drives_table[index].type == type &&
1945 drives_table[index].bus > max_bus)
1946 max_bus = drives_table[index].bus;
1951 const char *drive_get_serial(BlockDriverState *bdrv)
1955 for (index = 0; index < nb_drives; index++)
1956 if (drives_table[index].bdrv == bdrv)
1957 return drives_table[index].serial;
1962 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1966 for (index = 0; index < nb_drives; index++)
1967 if (drives_table[index].bdrv == bdrv)
1968 return drives_table[index].onerror;
1970 return BLOCK_ERR_STOP_ENOSPC;
1973 static void bdrv_format_print(void *opaque, const char *name)
1975 fprintf(stderr, " %s", name);
1978 void drive_uninit(BlockDriverState *bdrv)
1982 for (i = 0; i < MAX_DRIVES; i++)
1983 if (drives_table[i].bdrv == bdrv) {
1984 drives_table[i].bdrv = NULL;
1985 drives_table[i].used = 0;
1986 drive_remove(drives_table[i].drive_opt_idx);
1992 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
1998 const char *mediastr = "";
1999 BlockInterfaceType type;
2000 enum { MEDIA_DISK, MEDIA_CDROM } media;
2001 int bus_id, unit_id;
2002 int cyls, heads, secs, translation;
2003 BlockDriverState *bdrv;
2004 BlockDriver *drv = NULL;
2005 QEMUMachine *machine = opaque;
2009 int bdrv_flags, onerror;
2010 const char *devaddr;
2011 int drives_table_idx;
2012 char *str = arg->opt;
2013 static const char * const params[] = { "bus", "unit", "if", "index",
2014 "cyls", "heads", "secs", "trans",
2015 "media", "snapshot", "file",
2016 "cache", "format", "serial",
2020 if (check_params(buf, sizeof(buf), params, str) < 0) {
2021 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2027 cyls = heads = secs = 0;
2030 translation = BIOS_ATA_TRANSLATION_AUTO;
2034 if (machine->use_scsi) {
2036 max_devs = MAX_SCSI_DEVS;
2037 pstrcpy(devname, sizeof(devname), "scsi");
2040 max_devs = MAX_IDE_DEVS;
2041 pstrcpy(devname, sizeof(devname), "ide");
2045 /* extract parameters */
2047 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2048 bus_id = strtol(buf, NULL, 0);
2050 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2055 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2056 unit_id = strtol(buf, NULL, 0);
2058 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2063 if (get_param_value(buf, sizeof(buf), "if", str)) {
2064 pstrcpy(devname, sizeof(devname), buf);
2065 if (!strcmp(buf, "ide")) {
2067 max_devs = MAX_IDE_DEVS;
2068 } else if (!strcmp(buf, "scsi")) {
2070 max_devs = MAX_SCSI_DEVS;
2071 } else if (!strcmp(buf, "floppy")) {
2074 } else if (!strcmp(buf, "pflash")) {
2077 } else if (!strcmp(buf, "mtd")) {
2080 } else if (!strcmp(buf, "sd")) {
2083 } else if (!strcmp(buf, "virtio")) {
2086 } else if (!strcmp(buf, "xen")) {
2090 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2095 if (get_param_value(buf, sizeof(buf), "index", str)) {
2096 index = strtol(buf, NULL, 0);
2098 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2103 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2104 cyls = strtol(buf, NULL, 0);
2107 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2108 heads = strtol(buf, NULL, 0);
2111 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2112 secs = strtol(buf, NULL, 0);
2115 if (cyls || heads || secs) {
2116 if (cyls < 1 || cyls > 16383) {
2117 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2120 if (heads < 1 || heads > 16) {
2121 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2124 if (secs < 1 || secs > 63) {
2125 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2130 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2133 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2137 if (!strcmp(buf, "none"))
2138 translation = BIOS_ATA_TRANSLATION_NONE;
2139 else if (!strcmp(buf, "lba"))
2140 translation = BIOS_ATA_TRANSLATION_LBA;
2141 else if (!strcmp(buf, "auto"))
2142 translation = BIOS_ATA_TRANSLATION_AUTO;
2144 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2149 if (get_param_value(buf, sizeof(buf), "media", str)) {
2150 if (!strcmp(buf, "disk")) {
2152 } else if (!strcmp(buf, "cdrom")) {
2153 if (cyls || secs || heads) {
2155 "qemu: '%s' invalid physical CHS format\n", str);
2158 media = MEDIA_CDROM;
2160 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2165 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2166 if (!strcmp(buf, "on"))
2168 else if (!strcmp(buf, "off"))
2171 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2176 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2177 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2179 else if (!strcmp(buf, "writethrough"))
2181 else if (!strcmp(buf, "writeback"))
2184 fprintf(stderr, "qemu: invalid cache option\n");
2189 if (get_param_value(buf, sizeof(buf), "format", str)) {
2190 if (strcmp(buf, "?") == 0) {
2191 fprintf(stderr, "qemu: Supported formats:");
2192 bdrv_iterate_format(bdrv_format_print, NULL);
2193 fprintf(stderr, "\n");
2196 drv = bdrv_find_format(buf);
2198 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2203 if (arg->file == NULL)
2204 get_param_value(file, sizeof(file), "file", str);
2206 pstrcpy(file, sizeof(file), arg->file);
2208 if (!get_param_value(serial, sizeof(serial), "serial", str))
2209 memset(serial, 0, sizeof(serial));
2211 onerror = BLOCK_ERR_STOP_ENOSPC;
2212 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2213 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2214 fprintf(stderr, "werror is no supported by this format\n");
2217 if (!strcmp(buf, "ignore"))
2218 onerror = BLOCK_ERR_IGNORE;
2219 else if (!strcmp(buf, "enospc"))
2220 onerror = BLOCK_ERR_STOP_ENOSPC;
2221 else if (!strcmp(buf, "stop"))
2222 onerror = BLOCK_ERR_STOP_ANY;
2223 else if (!strcmp(buf, "report"))
2224 onerror = BLOCK_ERR_REPORT;
2226 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2232 if (get_param_value(buf, sizeof(buf), "addr", str)) {
2233 if (type != IF_VIRTIO) {
2234 fprintf(stderr, "addr is not supported by in '%s'\n", str);
2237 devaddr = strdup(buf);
2240 /* compute bus and unit according index */
2243 if (bus_id != 0 || unit_id != -1) {
2245 "qemu: '%s' index cannot be used with bus and unit\n", str);
2253 unit_id = index % max_devs;
2254 bus_id = index / max_devs;
2258 /* if user doesn't specify a unit_id,
2259 * try to find the first free
2262 if (unit_id == -1) {
2264 while (drive_get_index(type, bus_id, unit_id) != -1) {
2266 if (max_devs && unit_id >= max_devs) {
2267 unit_id -= max_devs;
2275 if (max_devs && unit_id >= max_devs) {
2276 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2277 str, unit_id, max_devs - 1);
2282 * ignore multiple definitions
2285 if (drive_get_index(type, bus_id, unit_id) != -1)
2290 if (type == IF_IDE || type == IF_SCSI)
2291 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2293 snprintf(buf, sizeof(buf), "%s%i%s%i",
2294 devname, bus_id, mediastr, unit_id);
2296 snprintf(buf, sizeof(buf), "%s%s%i",
2297 devname, mediastr, unit_id);
2298 bdrv = bdrv_new(buf);
2299 drives_table_idx = drive_get_free_idx();
2300 drives_table[drives_table_idx].bdrv = bdrv;
2301 drives_table[drives_table_idx].devaddr = devaddr;
2302 drives_table[drives_table_idx].type = type;
2303 drives_table[drives_table_idx].bus = bus_id;
2304 drives_table[drives_table_idx].unit = unit_id;
2305 drives_table[drives_table_idx].onerror = onerror;
2306 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2307 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2317 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2318 bdrv_set_translation_hint(bdrv, translation);
2322 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2327 /* FIXME: This isn't really a floppy, but it's a reasonable
2330 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2343 bdrv_flags |= BDRV_O_SNAPSHOT;
2344 cache = 2; /* always use write-back with snapshot */
2346 if (cache == 0) /* no caching */
2347 bdrv_flags |= BDRV_O_NOCACHE;
2348 else if (cache == 2) /* write-back */
2349 bdrv_flags |= BDRV_O_CACHE_WB;
2350 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2351 fprintf(stderr, "qemu: could not open disk image %s\n",
2355 if (bdrv_key_required(bdrv))
2357 return drives_table_idx;
2360 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2362 boot_set_handler = func;
2363 boot_set_opaque = opaque;
2366 int qemu_boot_set(const char *boot_devices)
2368 if (!boot_set_handler) {
2371 return boot_set_handler(boot_set_opaque, boot_devices);
2374 static int parse_bootdevices(char *devices)
2376 /* We just do some generic consistency checks */
2380 for (p = devices; *p != '\0'; p++) {
2381 /* Allowed boot devices are:
2382 * a-b: floppy disk drives
2383 * c-f: IDE disk drives
2384 * g-m: machine implementation dependant drives
2385 * n-p: network devices
2386 * It's up to each machine implementation to check if the given boot
2387 * devices match the actual hardware implementation and firmware
2390 if (*p < 'a' || *p > 'p') {
2391 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2394 if (bitmap & (1 << (*p - 'a'))) {
2395 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2398 bitmap |= 1 << (*p - 'a');
2403 static void restore_boot_devices(void *opaque)
2405 char *standard_boot_devices = opaque;
2407 qemu_boot_set(standard_boot_devices);
2409 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2410 qemu_free(standard_boot_devices);
2413 static void numa_add(const char *optarg)
2417 unsigned long long value, endvalue;
2420 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2421 if (!strcmp(option, "node")) {
2422 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2423 nodenr = nb_numa_nodes;
2425 nodenr = strtoull(option, NULL, 10);
2428 if (get_param_value(option, 128, "mem", optarg) == 0) {
2429 node_mem[nodenr] = 0;
2431 value = strtoull(option, &endptr, 0);
2433 case 0: case 'M': case 'm':
2440 node_mem[nodenr] = value;
2442 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2443 node_cpumask[nodenr] = 0;
2445 value = strtoull(option, &endptr, 10);
2448 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2450 if (*endptr == '-') {
2451 endvalue = strtoull(endptr+1, &endptr, 10);
2452 if (endvalue >= 63) {
2455 "only 63 CPUs in NUMA mode supported.\n");
2457 value = (1 << (endvalue + 1)) - (1 << value);
2462 node_cpumask[nodenr] = value;
2469 /***********************************************************/
2472 static USBPort *used_usb_ports;
2473 static USBPort *free_usb_ports;
2475 /* ??? Maybe change this to register a hub to keep track of the topology. */
2476 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2477 usb_attachfn attach)
2479 port->opaque = opaque;
2480 port->index = index;
2481 port->attach = attach;
2482 port->next = free_usb_ports;
2483 free_usb_ports = port;
2486 int usb_device_add_dev(USBDevice *dev)
2490 /* Find a USB port to add the device to. */
2491 port = free_usb_ports;
2495 /* Create a new hub and chain it on. */
2496 free_usb_ports = NULL;
2497 port->next = used_usb_ports;
2498 used_usb_ports = port;
2500 hub = usb_hub_init(VM_USB_HUB_SIZE);
2501 usb_attach(port, hub);
2502 port = free_usb_ports;
2505 free_usb_ports = port->next;
2506 port->next = used_usb_ports;
2507 used_usb_ports = port;
2508 usb_attach(port, dev);
2512 static void usb_msd_password_cb(void *opaque, int err)
2514 USBDevice *dev = opaque;
2517 usb_device_add_dev(dev);
2519 dev->handle_destroy(dev);
2522 static int usb_device_add(const char *devname, int is_hotplug)
2527 if (!free_usb_ports)
2530 if (strstart(devname, "host:", &p)) {
2531 dev = usb_host_device_open(p);
2532 } else if (!strcmp(devname, "mouse")) {
2533 dev = usb_mouse_init();
2534 } else if (!strcmp(devname, "tablet")) {
2535 dev = usb_tablet_init();
2536 } else if (!strcmp(devname, "keyboard")) {
2537 dev = usb_keyboard_init();
2538 } else if (strstart(devname, "disk:", &p)) {
2539 BlockDriverState *bs;
2541 dev = usb_msd_init(p);
2544 bs = usb_msd_get_bdrv(dev);
2545 if (bdrv_key_required(bs)) {
2548 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2553 } else if (!strcmp(devname, "wacom-tablet")) {
2554 dev = usb_wacom_init();
2555 } else if (strstart(devname, "serial:", &p)) {
2556 dev = usb_serial_init(p);
2557 #ifdef CONFIG_BRLAPI
2558 } else if (!strcmp(devname, "braille")) {
2559 dev = usb_baum_init();
2561 } else if (strstart(devname, "net:", &p)) {
2564 if (net_client_init(NULL, "nic", p) < 0)
2566 nd_table[nic].model = "usb";
2567 dev = usb_net_init(&nd_table[nic]);
2568 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2569 dev = usb_bt_init(devname[2] ? hci_init(p) :
2570 bt_new_hci(qemu_find_bt_vlan(0)));
2577 return usb_device_add_dev(dev);
2580 int usb_device_del_addr(int bus_num, int addr)
2586 if (!used_usb_ports)
2592 lastp = &used_usb_ports;
2593 port = used_usb_ports;
2594 while (port && port->dev->addr != addr) {
2595 lastp = &port->next;
2603 *lastp = port->next;
2604 usb_attach(port, NULL);
2605 dev->handle_destroy(dev);
2606 port->next = free_usb_ports;
2607 free_usb_ports = port;
2611 static int usb_device_del(const char *devname)
2616 if (strstart(devname, "host:", &p))
2617 return usb_host_device_close(p);
2619 if (!used_usb_ports)
2622 p = strchr(devname, '.');
2625 bus_num = strtoul(devname, NULL, 0);
2626 addr = strtoul(p + 1, NULL, 0);
2628 return usb_device_del_addr(bus_num, addr);
2631 static int usb_parse(const char *cmdline)
2633 return usb_device_add(cmdline, 0);
2636 void do_usb_add(Monitor *mon, const char *devname)
2638 usb_device_add(devname, 1);
2641 void do_usb_del(Monitor *mon, const char *devname)
2643 usb_device_del(devname);
2646 void usb_info(Monitor *mon)
2650 const char *speed_str;
2653 monitor_printf(mon, "USB support not enabled\n");
2657 for (port = used_usb_ports; port; port = port->next) {
2661 switch(dev->speed) {
2665 case USB_SPEED_FULL:
2668 case USB_SPEED_HIGH:
2675 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2676 0, dev->addr, speed_str, dev->devname);
2680 /***********************************************************/
2681 /* PCMCIA/Cardbus */
2683 static struct pcmcia_socket_entry_s {
2684 PCMCIASocket *socket;
2685 struct pcmcia_socket_entry_s *next;
2686 } *pcmcia_sockets = 0;
2688 void pcmcia_socket_register(PCMCIASocket *socket)
2690 struct pcmcia_socket_entry_s *entry;
2692 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2693 entry->socket = socket;
2694 entry->next = pcmcia_sockets;
2695 pcmcia_sockets = entry;
2698 void pcmcia_socket_unregister(PCMCIASocket *socket)
2700 struct pcmcia_socket_entry_s *entry, **ptr;
2702 ptr = &pcmcia_sockets;
2703 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2704 if (entry->socket == socket) {
2710 void pcmcia_info(Monitor *mon)
2712 struct pcmcia_socket_entry_s *iter;
2714 if (!pcmcia_sockets)
2715 monitor_printf(mon, "No PCMCIA sockets\n");
2717 for (iter = pcmcia_sockets; iter; iter = iter->next)
2718 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2719 iter->socket->attached ? iter->socket->card_string :
2723 /***********************************************************/
2724 /* register display */
2726 struct DisplayAllocator default_allocator = {
2727 defaultallocator_create_displaysurface,
2728 defaultallocator_resize_displaysurface,
2729 defaultallocator_free_displaysurface
2732 void register_displaystate(DisplayState *ds)
2742 DisplayState *get_displaystate(void)
2744 return display_state;
2747 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2749 if(ds->allocator == &default_allocator) ds->allocator = da;
2750 return ds->allocator;
2755 static void dumb_display_init(void)
2757 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2758 ds->allocator = &default_allocator;
2759 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2760 register_displaystate(ds);
2763 /***********************************************************/
2766 typedef struct IOHandlerRecord {
2768 IOCanRWHandler *fd_read_poll;
2770 IOHandler *fd_write;
2773 /* temporary data */
2775 struct IOHandlerRecord *next;
2778 static IOHandlerRecord *first_io_handler;
2780 /* XXX: fd_read_poll should be suppressed, but an API change is
2781 necessary in the character devices to suppress fd_can_read(). */
2782 int qemu_set_fd_handler2(int fd,
2783 IOCanRWHandler *fd_read_poll,
2785 IOHandler *fd_write,
2788 IOHandlerRecord **pioh, *ioh;
2790 if (!fd_read && !fd_write) {
2791 pioh = &first_io_handler;
2796 if (ioh->fd == fd) {
2803 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2807 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2808 ioh->next = first_io_handler;
2809 first_io_handler = ioh;
2812 ioh->fd_read_poll = fd_read_poll;
2813 ioh->fd_read = fd_read;
2814 ioh->fd_write = fd_write;
2815 ioh->opaque = opaque;
2821 int qemu_set_fd_handler(int fd,
2823 IOHandler *fd_write,
2826 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2830 /***********************************************************/
2831 /* Polling handling */
2833 typedef struct PollingEntry {
2836 struct PollingEntry *next;
2839 static PollingEntry *first_polling_entry;
2841 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2843 PollingEntry **ppe, *pe;
2844 pe = qemu_mallocz(sizeof(PollingEntry));
2846 pe->opaque = opaque;
2847 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2852 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2854 PollingEntry **ppe, *pe;
2855 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2857 if (pe->func == func && pe->opaque == opaque) {
2865 /***********************************************************/
2866 /* Wait objects support */
2867 typedef struct WaitObjects {
2869 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2870 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2871 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2874 static WaitObjects wait_objects = {0};
2876 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2878 WaitObjects *w = &wait_objects;
2880 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2882 w->events[w->num] = handle;
2883 w->func[w->num] = func;
2884 w->opaque[w->num] = opaque;
2889 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2892 WaitObjects *w = &wait_objects;
2895 for (i = 0; i < w->num; i++) {
2896 if (w->events[i] == handle)
2899 w->events[i] = w->events[i + 1];
2900 w->func[i] = w->func[i + 1];
2901 w->opaque[i] = w->opaque[i + 1];
2909 /***********************************************************/
2910 /* ram save/restore */
2912 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2916 v = qemu_get_byte(f);
2919 if (qemu_get_buffer(f, buf, len) != len)
2923 v = qemu_get_byte(f);
2924 memset(buf, v, len);
2930 if (qemu_file_has_error(f))
2936 static int ram_load_v1(QEMUFile *f, void *opaque)
2941 if (qemu_get_be32(f) != last_ram_offset)
2943 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2944 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2951 #define BDRV_HASH_BLOCK_SIZE 1024
2952 #define IOBUF_SIZE 4096
2953 #define RAM_CBLOCK_MAGIC 0xfabe
2955 typedef struct RamDecompressState {
2958 uint8_t buf[IOBUF_SIZE];
2959 } RamDecompressState;
2961 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2964 memset(s, 0, sizeof(*s));
2966 ret = inflateInit(&s->zstream);
2972 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2976 s->zstream.avail_out = len;
2977 s->zstream.next_out = buf;
2978 while (s->zstream.avail_out > 0) {
2979 if (s->zstream.avail_in == 0) {
2980 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
2982 clen = qemu_get_be16(s->f);
2983 if (clen > IOBUF_SIZE)
2985 qemu_get_buffer(s->f, s->buf, clen);
2986 s->zstream.avail_in = clen;
2987 s->zstream.next_in = s->buf;
2989 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
2990 if (ret != Z_OK && ret != Z_STREAM_END) {
2997 static void ram_decompress_close(RamDecompressState *s)
2999 inflateEnd(&s->zstream);
3002 #define RAM_SAVE_FLAG_FULL 0x01
3003 #define RAM_SAVE_FLAG_COMPRESS 0x02
3004 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3005 #define RAM_SAVE_FLAG_PAGE 0x08
3006 #define RAM_SAVE_FLAG_EOS 0x10
3008 static int is_dup_page(uint8_t *page, uint8_t ch)
3010 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3011 uint32_t *array = (uint32_t *)page;
3014 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3015 if (array[i] != val)
3022 static int ram_save_block(QEMUFile *f)
3024 static ram_addr_t current_addr = 0;
3025 ram_addr_t saved_addr = current_addr;
3026 ram_addr_t addr = 0;
3029 while (addr < last_ram_offset) {
3030 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3033 cpu_physical_memory_reset_dirty(current_addr,
3034 current_addr + TARGET_PAGE_SIZE,
3035 MIGRATION_DIRTY_FLAG);
3037 p = qemu_get_ram_ptr(current_addr);
3039 if (is_dup_page(p, *p)) {
3040 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3041 qemu_put_byte(f, *p);
3043 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3044 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3050 addr += TARGET_PAGE_SIZE;
3051 current_addr = (saved_addr + addr) % last_ram_offset;
3057 static uint64_t bytes_transferred = 0;
3059 static ram_addr_t ram_save_remaining(void)
3062 ram_addr_t count = 0;
3064 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3065 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3072 uint64_t ram_bytes_remaining(void)
3074 return ram_save_remaining() * TARGET_PAGE_SIZE;
3077 uint64_t ram_bytes_transferred(void)
3079 return bytes_transferred;
3082 uint64_t ram_bytes_total(void)
3084 return last_ram_offset;
3087 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3090 uint64_t bytes_transferred_last;
3092 uint64_t expected_time = 0;
3094 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3095 qemu_file_set_error(f);
3100 /* Make sure all dirty bits are set */
3101 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3102 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3103 cpu_physical_memory_set_dirty(addr);
3106 /* Enable dirty memory tracking */
3107 cpu_physical_memory_set_dirty_tracking(1);
3109 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3112 bytes_transferred_last = bytes_transferred;
3113 bwidth = get_clock();
3115 while (!qemu_file_rate_limit(f)) {
3118 ret = ram_save_block(f);
3119 bytes_transferred += ret * TARGET_PAGE_SIZE;
3120 if (ret == 0) /* no more blocks */
3124 bwidth = get_clock() - bwidth;
3125 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3127 /* if we haven't transferred anything this round, force expected_time to a
3128 * a very high value, but without crashing */
3132 /* try transferring iterative blocks of memory */
3136 /* flush all remaining blocks regardless of rate limiting */
3137 while (ram_save_block(f) != 0) {
3138 bytes_transferred += TARGET_PAGE_SIZE;
3140 cpu_physical_memory_set_dirty_tracking(0);
3143 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3145 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3147 return (stage == 2) && (expected_time <= migrate_max_downtime());
3150 static int ram_load_dead(QEMUFile *f, void *opaque)
3152 RamDecompressState s1, *s = &s1;
3156 if (ram_decompress_open(s, f) < 0)
3158 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3159 if (ram_decompress_buf(s, buf, 1) < 0) {
3160 fprintf(stderr, "Error while reading ram block header\n");
3164 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3165 BDRV_HASH_BLOCK_SIZE) < 0) {
3166 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3171 printf("Error block header\n");
3175 ram_decompress_close(s);
3180 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3185 if (version_id == 1)
3186 return ram_load_v1(f, opaque);
3188 if (version_id == 2) {
3189 if (qemu_get_be32(f) != last_ram_offset)
3191 return ram_load_dead(f, opaque);
3194 if (version_id != 3)
3198 addr = qemu_get_be64(f);
3200 flags = addr & ~TARGET_PAGE_MASK;
3201 addr &= TARGET_PAGE_MASK;
3203 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3204 if (addr != last_ram_offset)
3208 if (flags & RAM_SAVE_FLAG_FULL) {
3209 if (ram_load_dead(f, opaque) < 0)
3213 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3214 uint8_t ch = qemu_get_byte(f);
3215 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3218 (!kvm_enabled() || kvm_has_sync_mmu())) {
3219 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3222 } else if (flags & RAM_SAVE_FLAG_PAGE)
3223 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3224 } while (!(flags & RAM_SAVE_FLAG_EOS));
3229 void qemu_service_io(void)
3231 qemu_notify_event();
3234 /***********************************************************/
3235 /* bottom halves (can be seen as timers which expire ASAP) */
3246 static QEMUBH *first_bh = NULL;
3248 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3251 bh = qemu_mallocz(sizeof(QEMUBH));
3253 bh->opaque = opaque;
3254 bh->next = first_bh;
3259 int qemu_bh_poll(void)
3265 for (bh = first_bh; bh; bh = bh->next) {
3266 if (!bh->deleted && bh->scheduled) {
3275 /* remove deleted bhs */
3289 void qemu_bh_schedule_idle(QEMUBH *bh)
3297 void qemu_bh_schedule(QEMUBH *bh)
3303 /* stop the currently executing CPU to execute the BH ASAP */
3304 qemu_notify_event();
3307 void qemu_bh_cancel(QEMUBH *bh)
3312 void qemu_bh_delete(QEMUBH *bh)
3318 static void qemu_bh_update_timeout(int *timeout)
3322 for (bh = first_bh; bh; bh = bh->next) {
3323 if (!bh->deleted && bh->scheduled) {
3325 /* idle bottom halves will be polled at least
3327 *timeout = MIN(10, *timeout);
3329 /* non-idle bottom halves will be executed
3338 /***********************************************************/
3339 /* machine registration */
3341 static QEMUMachine *first_machine = NULL;
3342 QEMUMachine *current_machine = NULL;
3344 int qemu_register_machine(QEMUMachine *m)
3347 pm = &first_machine;
3355 static QEMUMachine *find_machine(const char *name)
3359 for(m = first_machine; m != NULL; m = m->next) {
3360 if (!strcmp(m->name, name))
3362 if (m->alias && !strcmp(m->alias, name))
3368 static QEMUMachine *find_default_machine(void)
3372 for(m = first_machine; m != NULL; m = m->next) {
3373 if (m->is_default) {
3380 /***********************************************************/
3381 /* main execution loop */
3383 static void gui_update(void *opaque)
3385 uint64_t interval = GUI_REFRESH_INTERVAL;
3386 DisplayState *ds = opaque;
3387 DisplayChangeListener *dcl = ds->listeners;
3391 while (dcl != NULL) {
3392 if (dcl->gui_timer_interval &&
3393 dcl->gui_timer_interval < interval)
3394 interval = dcl->gui_timer_interval;
3397 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3400 static void nographic_update(void *opaque)
3402 uint64_t interval = GUI_REFRESH_INTERVAL;
3404 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3407 struct vm_change_state_entry {
3408 VMChangeStateHandler *cb;
3410 LIST_ENTRY (vm_change_state_entry) entries;
3413 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3415 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3418 VMChangeStateEntry *e;
3420 e = qemu_mallocz(sizeof (*e));
3424 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3428 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3430 LIST_REMOVE (e, entries);
3434 static void vm_state_notify(int running, int reason)
3436 VMChangeStateEntry *e;
3438 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3439 e->cb(e->opaque, running, reason);
3443 static void resume_all_vcpus(void);
3444 static void pause_all_vcpus(void);
3451 vm_state_notify(1, 0);
3452 qemu_rearm_alarm_timer(alarm_timer);
3457 /* reset/shutdown handler */
3459 typedef struct QEMUResetEntry {
3460 TAILQ_ENTRY(QEMUResetEntry) entry;
3461 QEMUResetHandler *func;
3465 static TAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3466 TAILQ_HEAD_INITIALIZER(reset_handlers);
3467 static int reset_requested;
3468 static int shutdown_requested;
3469 static int powerdown_requested;
3470 static int debug_requested;
3471 static int vmstop_requested;
3473 int qemu_shutdown_requested(void)
3475 int r = shutdown_requested;
3476 shutdown_requested = 0;
3480 int qemu_reset_requested(void)
3482 int r = reset_requested;
3483 reset_requested = 0;
3487 int qemu_powerdown_requested(void)
3489 int r = powerdown_requested;
3490 powerdown_requested = 0;
3494 static int qemu_debug_requested(void)
3496 int r = debug_requested;
3497 debug_requested = 0;
3501 static int qemu_vmstop_requested(void)
3503 int r = vmstop_requested;
3504 vmstop_requested = 0;
3508 static void do_vm_stop(int reason)
3511 cpu_disable_ticks();
3514 vm_state_notify(0, reason);
3518 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3520 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3523 re->opaque = opaque;
3524 TAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3527 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3531 TAILQ_FOREACH(re, &reset_handlers, entry) {
3532 if (re->func == func && re->opaque == opaque) {
3533 TAILQ_REMOVE(&reset_handlers, re, entry);
3540 void qemu_system_reset(void)
3542 QEMUResetEntry *re, *nre;
3544 /* reset all devices */
3545 TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3546 re->func(re->opaque);
3550 void qemu_system_reset_request(void)
3553 shutdown_requested = 1;
3555 reset_requested = 1;
3557 qemu_notify_event();
3560 void qemu_system_shutdown_request(void)
3562 shutdown_requested = 1;
3563 qemu_notify_event();
3566 void qemu_system_powerdown_request(void)
3568 powerdown_requested = 1;
3569 qemu_notify_event();
3572 #ifdef CONFIG_IOTHREAD
3573 static void qemu_system_vmstop_request(int reason)
3575 vmstop_requested = reason;
3576 qemu_notify_event();
3581 static int io_thread_fd = -1;
3583 static void qemu_event_increment(void)
3585 static const char byte = 0;
3587 if (io_thread_fd == -1)
3590 write(io_thread_fd, &byte, sizeof(byte));
3593 static void qemu_event_read(void *opaque)
3595 int fd = (unsigned long)opaque;
3598 /* Drain the notify pipe */
3601 len = read(fd, buffer, sizeof(buffer));
3602 } while ((len == -1 && errno == EINTR) || len > 0);
3605 static int qemu_event_init(void)
3614 err = fcntl_setfl(fds[0], O_NONBLOCK);
3618 err = fcntl_setfl(fds[1], O_NONBLOCK);
3622 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3623 (void *)(unsigned long)fds[0]);
3625 io_thread_fd = fds[1];
3634 HANDLE qemu_event_handle;
3636 static void dummy_event_handler(void *opaque)
3640 static int qemu_event_init(void)
3642 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3643 if (!qemu_event_handle) {
3644 perror("Failed CreateEvent");
3647 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3651 static void qemu_event_increment(void)
3653 SetEvent(qemu_event_handle);
3657 static int cpu_can_run(CPUState *env)
3666 #ifndef CONFIG_IOTHREAD
3667 static int qemu_init_main_loop(void)
3669 return qemu_event_init();
3672 void qemu_init_vcpu(void *_env)
3674 CPUState *env = _env;
3681 int qemu_cpu_self(void *env)
3686 static void resume_all_vcpus(void)
3690 static void pause_all_vcpus(void)
3694 void qemu_cpu_kick(void *env)
3699 void qemu_notify_event(void)
3701 CPUState *env = cpu_single_env;
3706 if (env->kqemu_enabled)
3707 kqemu_cpu_interrupt(env);
3712 #define qemu_mutex_lock_iothread() do { } while (0)
3713 #define qemu_mutex_unlock_iothread() do { } while (0)
3715 void vm_stop(int reason)
3720 #else /* CONFIG_IOTHREAD */
3722 #include "qemu-thread.h"
3724 QemuMutex qemu_global_mutex;
3725 static QemuMutex qemu_fair_mutex;
3727 static QemuThread io_thread;
3729 static QemuThread *tcg_cpu_thread;
3730 static QemuCond *tcg_halt_cond;
3732 static int qemu_system_ready;
3734 static QemuCond qemu_cpu_cond;
3736 static QemuCond qemu_system_cond;
3737 static QemuCond qemu_pause_cond;
3739 static void block_io_signals(void);
3740 static void unblock_io_signals(void);
3741 static int tcg_has_work(void);
3743 static int qemu_init_main_loop(void)
3747 ret = qemu_event_init();
3751 qemu_cond_init(&qemu_pause_cond);
3752 qemu_mutex_init(&qemu_fair_mutex);
3753 qemu_mutex_init(&qemu_global_mutex);
3754 qemu_mutex_lock(&qemu_global_mutex);
3756 unblock_io_signals();
3757 qemu_thread_self(&io_thread);
3762 static void qemu_wait_io_event(CPUState *env)
3764 while (!tcg_has_work())
3765 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3767 qemu_mutex_unlock(&qemu_global_mutex);
3770 * Users of qemu_global_mutex can be starved, having no chance
3771 * to acquire it since this path will get to it first.
3772 * So use another lock to provide fairness.
3774 qemu_mutex_lock(&qemu_fair_mutex);
3775 qemu_mutex_unlock(&qemu_fair_mutex);
3777 qemu_mutex_lock(&qemu_global_mutex);
3781 qemu_cond_signal(&qemu_pause_cond);
3785 static int qemu_cpu_exec(CPUState *env);
3787 static void *kvm_cpu_thread_fn(void *arg)
3789 CPUState *env = arg;
3792 qemu_thread_self(env->thread);
3794 /* signal CPU creation */
3795 qemu_mutex_lock(&qemu_global_mutex);
3797 qemu_cond_signal(&qemu_cpu_cond);
3799 /* and wait for machine initialization */
3800 while (!qemu_system_ready)
3801 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3804 if (cpu_can_run(env))
3806 qemu_wait_io_event(env);
3812 static void tcg_cpu_exec(void);
3814 static void *tcg_cpu_thread_fn(void *arg)
3816 CPUState *env = arg;
3819 qemu_thread_self(env->thread);
3821 /* signal CPU creation */
3822 qemu_mutex_lock(&qemu_global_mutex);
3823 for (env = first_cpu; env != NULL; env = env->next_cpu)
3825 qemu_cond_signal(&qemu_cpu_cond);
3827 /* and wait for machine initialization */
3828 while (!qemu_system_ready)
3829 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3833 qemu_wait_io_event(cur_cpu);
3839 void qemu_cpu_kick(void *_env)
3841 CPUState *env = _env;
3842 qemu_cond_broadcast(env->halt_cond);
3844 qemu_thread_signal(env->thread, SIGUSR1);
3847 int qemu_cpu_self(void *env)
3849 return (cpu_single_env != NULL);
3852 static void cpu_signal(int sig)
3855 cpu_exit(cpu_single_env);
3858 static void block_io_signals(void)
3861 struct sigaction sigact;
3864 sigaddset(&set, SIGUSR2);
3865 sigaddset(&set, SIGIO);
3866 sigaddset(&set, SIGALRM);
3867 pthread_sigmask(SIG_BLOCK, &set, NULL);
3870 sigaddset(&set, SIGUSR1);
3871 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3873 memset(&sigact, 0, sizeof(sigact));
3874 sigact.sa_handler = cpu_signal;
3875 sigaction(SIGUSR1, &sigact, NULL);
3878 static void unblock_io_signals(void)
3883 sigaddset(&set, SIGUSR2);
3884 sigaddset(&set, SIGIO);
3885 sigaddset(&set, SIGALRM);
3886 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3889 sigaddset(&set, SIGUSR1);
3890 pthread_sigmask(SIG_BLOCK, &set, NULL);
3893 static void qemu_signal_lock(unsigned int msecs)
3895 qemu_mutex_lock(&qemu_fair_mutex);
3897 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3898 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3899 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3902 qemu_mutex_unlock(&qemu_fair_mutex);
3905 static void qemu_mutex_lock_iothread(void)
3907 if (kvm_enabled()) {
3908 qemu_mutex_lock(&qemu_fair_mutex);
3909 qemu_mutex_lock(&qemu_global_mutex);
3910 qemu_mutex_unlock(&qemu_fair_mutex);
3912 qemu_signal_lock(100);
3915 static void qemu_mutex_unlock_iothread(void)
3917 qemu_mutex_unlock(&qemu_global_mutex);
3920 static int all_vcpus_paused(void)
3922 CPUState *penv = first_cpu;
3927 penv = (CPUState *)penv->next_cpu;
3933 static void pause_all_vcpus(void)
3935 CPUState *penv = first_cpu;
3939 qemu_thread_signal(penv->thread, SIGUSR1);
3940 qemu_cpu_kick(penv);
3941 penv = (CPUState *)penv->next_cpu;
3944 while (!all_vcpus_paused()) {
3945 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3948 qemu_thread_signal(penv->thread, SIGUSR1);
3949 penv = (CPUState *)penv->next_cpu;
3954 static void resume_all_vcpus(void)
3956 CPUState *penv = first_cpu;
3961 qemu_thread_signal(penv->thread, SIGUSR1);
3962 qemu_cpu_kick(penv);
3963 penv = (CPUState *)penv->next_cpu;
3967 static void tcg_init_vcpu(void *_env)
3969 CPUState *env = _env;
3970 /* share a single thread for all cpus with TCG */
3971 if (!tcg_cpu_thread) {
3972 env->thread = qemu_mallocz(sizeof(QemuThread));
3973 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3974 qemu_cond_init(env->halt_cond);
3975 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3976 while (env->created == 0)
3977 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3978 tcg_cpu_thread = env->thread;
3979 tcg_halt_cond = env->halt_cond;
3981 env->thread = tcg_cpu_thread;
3982 env->halt_cond = tcg_halt_cond;
3986 static void kvm_start_vcpu(CPUState *env)
3989 env->thread = qemu_mallocz(sizeof(QemuThread));
3990 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3991 qemu_cond_init(env->halt_cond);
3992 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3993 while (env->created == 0)
3994 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3997 void qemu_init_vcpu(void *_env)
3999 CPUState *env = _env;
4002 kvm_start_vcpu(env);
4007 void qemu_notify_event(void)
4009 qemu_event_increment();
4012 void vm_stop(int reason)
4015 qemu_thread_self(&me);
4017 if (!qemu_thread_equal(&me, &io_thread)) {
4018 qemu_system_vmstop_request(reason);
4020 * FIXME: should not return to device code in case
4021 * vm_stop() has been requested.
4023 if (cpu_single_env) {
4024 cpu_exit(cpu_single_env);
4025 cpu_single_env->stop = 1;
4036 static void host_main_loop_wait(int *timeout)
4042 /* XXX: need to suppress polling by better using win32 events */
4044 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4045 ret |= pe->func(pe->opaque);
4049 WaitObjects *w = &wait_objects;
4051 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4052 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4053 if (w->func[ret - WAIT_OBJECT_0])
4054 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4056 /* Check for additional signaled events */
4057 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4059 /* Check if event is signaled */
4060 ret2 = WaitForSingleObject(w->events[i], 0);
4061 if(ret2 == WAIT_OBJECT_0) {
4063 w->func[i](w->opaque[i]);
4064 } else if (ret2 == WAIT_TIMEOUT) {
4066 err = GetLastError();
4067 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4070 } else if (ret == WAIT_TIMEOUT) {
4072 err = GetLastError();
4073 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4080 static void host_main_loop_wait(int *timeout)
4085 void main_loop_wait(int timeout)
4087 IOHandlerRecord *ioh;
4088 fd_set rfds, wfds, xfds;
4092 qemu_bh_update_timeout(&timeout);
4094 host_main_loop_wait(&timeout);
4096 /* poll any events */
4097 /* XXX: separate device handlers from system ones */
4102 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4106 (!ioh->fd_read_poll ||
4107 ioh->fd_read_poll(ioh->opaque) != 0)) {
4108 FD_SET(ioh->fd, &rfds);
4112 if (ioh->fd_write) {
4113 FD_SET(ioh->fd, &wfds);
4119 tv.tv_sec = timeout / 1000;
4120 tv.tv_usec = (timeout % 1000) * 1000;
4122 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4124 qemu_mutex_unlock_iothread();
4125 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4126 qemu_mutex_lock_iothread();
4128 IOHandlerRecord **pioh;
4130 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4131 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4132 ioh->fd_read(ioh->opaque);
4134 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4135 ioh->fd_write(ioh->opaque);
4139 /* remove deleted IO handlers */
4140 pioh = &first_io_handler;
4151 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4153 /* rearm timer, if not periodic */
4154 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4155 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4156 qemu_rearm_alarm_timer(alarm_timer);
4159 /* vm time timers */
4161 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4162 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4163 qemu_get_clock(vm_clock));
4166 /* real time timers */
4167 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4168 qemu_get_clock(rt_clock));
4170 /* Check bottom-halves last in case any of the earlier events triggered
4176 static int qemu_cpu_exec(CPUState *env)
4179 #ifdef CONFIG_PROFILER
4183 #ifdef CONFIG_PROFILER
4184 ti = profile_getclock();
4189 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4190 env->icount_decr.u16.low = 0;
4191 env->icount_extra = 0;
4192 count = qemu_next_deadline();
4193 count = (count + (1 << icount_time_shift) - 1)
4194 >> icount_time_shift;
4195 qemu_icount += count;
4196 decr = (count > 0xffff) ? 0xffff : count;
4198 env->icount_decr.u16.low = decr;
4199 env->icount_extra = count;
4201 ret = cpu_exec(env);
4202 #ifdef CONFIG_PROFILER
4203 qemu_time += profile_getclock() - ti;
4206 /* Fold pending instructions back into the
4207 instruction counter, and clear the interrupt flag. */
4208 qemu_icount -= (env->icount_decr.u16.low
4209 + env->icount_extra);
4210 env->icount_decr.u32 = 0;
4211 env->icount_extra = 0;
4216 static void tcg_cpu_exec(void)
4220 if (next_cpu == NULL)
4221 next_cpu = first_cpu;
4222 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4223 CPUState *env = cur_cpu = next_cpu;
4227 if (timer_alarm_pending) {
4228 timer_alarm_pending = 0;
4231 if (cpu_can_run(env))
4232 ret = qemu_cpu_exec(env);
4233 if (ret == EXCP_DEBUG) {
4234 gdb_set_stop_cpu(env);
4235 debug_requested = 1;
4241 static int cpu_has_work(CPUState *env)
4249 if (qemu_cpu_has_work(env))
4254 static int tcg_has_work(void)
4258 for (env = first_cpu; env != NULL; env = env->next_cpu)
4259 if (cpu_has_work(env))
4264 static int qemu_calculate_timeout(void)
4266 #ifndef CONFIG_IOTHREAD
4271 else if (tcg_has_work())
4273 else if (!use_icount)
4276 /* XXX: use timeout computed from timers */
4279 /* Advance virtual time to the next event. */
4280 if (use_icount == 1) {
4281 /* When not using an adaptive execution frequency
4282 we tend to get badly out of sync with real time,
4283 so just delay for a reasonable amount of time. */
4286 delta = cpu_get_icount() - cpu_get_clock();
4289 /* If virtual time is ahead of real time then just
4291 timeout = (delta / 1000000) + 1;
4293 /* Wait for either IO to occur or the next
4295 add = qemu_next_deadline();
4296 /* We advance the timer before checking for IO.
4297 Limit the amount we advance so that early IO
4298 activity won't get the guest too far ahead. */
4302 add = (add + (1 << icount_time_shift) - 1)
4303 >> icount_time_shift;
4305 timeout = delta / 1000000;
4312 #else /* CONFIG_IOTHREAD */
4317 static int vm_can_run(void)
4319 if (powerdown_requested)
4321 if (reset_requested)
4323 if (shutdown_requested)
4325 if (debug_requested)
4330 static void main_loop(void)
4334 #ifdef CONFIG_IOTHREAD
4335 qemu_system_ready = 1;
4336 qemu_cond_broadcast(&qemu_system_cond);
4341 #ifdef CONFIG_PROFILER
4344 #ifndef CONFIG_IOTHREAD
4347 #ifdef CONFIG_PROFILER
4348 ti = profile_getclock();
4350 main_loop_wait(qemu_calculate_timeout());
4351 #ifdef CONFIG_PROFILER
4352 dev_time += profile_getclock() - ti;
4354 } while (vm_can_run());
4356 if (qemu_debug_requested())
4357 vm_stop(EXCP_DEBUG);
4358 if (qemu_shutdown_requested()) {
4365 if (qemu_reset_requested()) {
4367 qemu_system_reset();
4370 if (qemu_powerdown_requested())
4371 qemu_system_powerdown();
4372 if ((r = qemu_vmstop_requested()))
4378 static void version(void)
4380 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4383 static void help(int exitcode)
4386 printf("usage: %s [options] [disk_image]\n"
4388 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4390 #define DEF(option, opt_arg, opt_enum, opt_help) \
4392 #define DEFHEADING(text) stringify(text) "\n"
4393 #include "qemu-options.h"
4398 "During emulation, the following keys are useful:\n"
4399 "ctrl-alt-f toggle full screen\n"
4400 "ctrl-alt-n switch to virtual console 'n'\n"
4401 "ctrl-alt toggle mouse and keyboard grab\n"
4403 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4408 DEFAULT_NETWORK_SCRIPT,
4409 DEFAULT_NETWORK_DOWN_SCRIPT,
4411 DEFAULT_GDBSTUB_PORT,
4416 #define HAS_ARG 0x0001
4419 #define DEF(option, opt_arg, opt_enum, opt_help) \
4421 #define DEFHEADING(text)
4422 #include "qemu-options.h"
4428 typedef struct QEMUOption {
4434 static const QEMUOption qemu_options[] = {
4435 { "h", 0, QEMU_OPTION_h },
4436 #define DEF(option, opt_arg, opt_enum, opt_help) \
4437 { option, opt_arg, opt_enum },
4438 #define DEFHEADING(text)
4439 #include "qemu-options.h"
4447 struct soundhw soundhw[] = {
4448 #ifdef HAS_AUDIO_CHOICE
4449 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4455 { .init_isa = pcspk_audio_init }
4462 "Creative Sound Blaster 16",
4465 { .init_isa = SB16_init }
4469 #ifdef CONFIG_CS4231A
4475 { .init_isa = cs4231a_init }
4483 "Yamaha YMF262 (OPL3)",
4485 "Yamaha YM3812 (OPL2)",
4489 { .init_isa = Adlib_init }
4496 "Gravis Ultrasound GF1",
4499 { .init_isa = GUS_init }
4506 "Intel 82801AA AC97 Audio",
4509 { .init_pci = ac97_init }
4513 #ifdef CONFIG_ES1370
4516 "ENSONIQ AudioPCI ES1370",
4519 { .init_pci = es1370_init }
4523 #endif /* HAS_AUDIO_CHOICE */
4525 { NULL, NULL, 0, 0, { NULL } }
4528 static void select_soundhw (const char *optarg)
4532 if (*optarg == '?') {
4535 printf ("Valid sound card names (comma separated):\n");
4536 for (c = soundhw; c->name; ++c) {
4537 printf ("%-11s %s\n", c->name, c->descr);
4539 printf ("\n-soundhw all will enable all of the above\n");
4540 exit (*optarg != '?');
4548 if (!strcmp (optarg, "all")) {
4549 for (c = soundhw; c->name; ++c) {
4557 e = strchr (p, ',');
4558 l = !e ? strlen (p) : (size_t) (e - p);
4560 for (c = soundhw; c->name; ++c) {
4561 if (!strncmp (c->name, p, l)) {
4570 "Unknown sound card name (too big to show)\n");
4573 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4578 p += l + (e != NULL);
4582 goto show_valid_cards;
4587 static void select_vgahw (const char *p)
4591 cirrus_vga_enabled = 0;
4592 std_vga_enabled = 0;
4595 if (strstart(p, "std", &opts)) {
4596 std_vga_enabled = 1;
4597 } else if (strstart(p, "cirrus", &opts)) {
4598 cirrus_vga_enabled = 1;
4599 } else if (strstart(p, "vmware", &opts)) {
4601 } else if (strstart(p, "xenfb", &opts)) {
4603 } else if (!strstart(p, "none", &opts)) {
4605 fprintf(stderr, "Unknown vga type: %s\n", p);
4609 const char *nextopt;
4611 if (strstart(opts, ",retrace=", &nextopt)) {
4613 if (strstart(opts, "dumb", &nextopt))
4614 vga_retrace_method = VGA_RETRACE_DUMB;
4615 else if (strstart(opts, "precise", &nextopt))
4616 vga_retrace_method = VGA_RETRACE_PRECISE;
4617 else goto invalid_vga;
4618 } else goto invalid_vga;
4624 static int balloon_parse(const char *arg)
4629 if (!strcmp(arg, "none")) {
4631 } else if (!strncmp(arg, "virtio", 6)) {
4633 if (arg[6] == ',') {
4635 if (get_param_value(buf, sizeof(buf), "addr", p)) {
4636 virtio_balloon_devaddr = strdup(buf);
4647 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4649 exit(STATUS_CONTROL_C_EXIT);
4654 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4658 if(strlen(str) != 36)
4661 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4662 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4663 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4669 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4675 #define MAX_NET_CLIENTS 32
4679 static void termsig_handler(int signal)
4681 qemu_system_shutdown_request();
4684 static void sigchld_handler(int signal)
4686 waitpid(-1, NULL, WNOHANG);
4689 static void sighandler_setup(void)
4691 struct sigaction act;
4693 memset(&act, 0, sizeof(act));
4694 act.sa_handler = termsig_handler;
4695 sigaction(SIGINT, &act, NULL);
4696 sigaction(SIGHUP, &act, NULL);
4697 sigaction(SIGTERM, &act, NULL);
4699 act.sa_handler = sigchld_handler;
4700 act.sa_flags = SA_NOCLDSTOP;
4701 sigaction(SIGCHLD, &act, NULL);
4707 /* Look for support files in the same directory as the executable. */
4708 static char *find_datadir(const char *argv0)
4714 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4721 while (p != buf && *p != '\\')
4724 if (access(buf, R_OK) == 0) {
4725 return qemu_strdup(buf);
4731 /* Find a likely location for support files using the location of the binary.
4732 For installed binaries this will be "$bindir/../share/qemu". When
4733 running from the build tree this will be "$bindir/../pc-bios". */
4734 #define SHARE_SUFFIX "/share/qemu"
4735 #define BUILD_SUFFIX "/pc-bios"
4736 static char *find_datadir(const char *argv0)
4746 #if defined(__linux__)
4749 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4755 #elif defined(__FreeBSD__)
4758 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4765 /* If we don't have any way of figuring out the actual executable
4766 location then try argv[0]. */
4771 p = realpath(argv0, p);
4779 max_len = strlen(dir) +
4780 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4781 res = qemu_mallocz(max_len);
4782 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4783 if (access(res, R_OK)) {
4784 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4785 if (access(res, R_OK)) {
4799 char *qemu_find_file(int type, const char *name)
4805 /* If name contains path separators then try it as a straight path. */
4806 if ((strchr(name, '/') || strchr(name, '\\'))
4807 && access(name, R_OK) == 0) {
4808 return strdup(name);
4811 case QEMU_FILE_TYPE_BIOS:
4814 case QEMU_FILE_TYPE_KEYMAP:
4815 subdir = "keymaps/";
4820 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4821 buf = qemu_mallocz(len);
4822 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4823 if (access(buf, R_OK)) {
4830 struct device_config {
4832 DEV_GENERIC, /* -device */
4833 DEV_USB, /* -usbdevice */
4836 const char *cmdline;
4837 TAILQ_ENTRY(device_config) next;
4839 TAILQ_HEAD(, device_config) device_configs = TAILQ_HEAD_INITIALIZER(device_configs);
4841 static void add_device_config(int type, const char *cmdline)
4843 struct device_config *conf;
4845 conf = qemu_mallocz(sizeof(*conf));
4847 conf->cmdline = cmdline;
4848 TAILQ_INSERT_TAIL(&device_configs, conf, next);
4851 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4853 struct device_config *conf;
4856 TAILQ_FOREACH(conf, &device_configs, next) {
4857 if (conf->type != type)
4859 rc = func(conf->cmdline);
4866 static int generic_parse(const char *cmdline)
4870 dev = qdev_device_add(cmdline);
4876 int main(int argc, char **argv, char **envp)
4878 const char *gdbstub_dev = NULL;
4879 uint32_t boot_devices_bitmap = 0;
4881 int snapshot, linux_boot, net_boot;
4882 const char *initrd_filename;
4883 const char *kernel_filename, *kernel_cmdline;
4884 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4886 DisplayChangeListener *dcl;
4887 int cyls, heads, secs, translation;
4888 const char *net_clients[MAX_NET_CLIENTS];
4892 const char *r, *optarg;
4893 CharDriverState *monitor_hd = NULL;
4894 const char *monitor_device;
4895 const char *serial_devices[MAX_SERIAL_PORTS];
4896 int serial_device_index;
4897 const char *parallel_devices[MAX_PARALLEL_PORTS];
4898 int parallel_device_index;
4899 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4900 int virtio_console_index;
4901 const char *loadvm = NULL;
4902 QEMUMachine *machine;
4903 const char *cpu_model;
4908 const char *pid_file = NULL;
4909 const char *incoming = NULL;
4912 struct passwd *pwd = NULL;
4913 const char *chroot_dir = NULL;
4914 const char *run_as = NULL;
4917 int show_vnc_port = 0;
4919 qemu_cache_utils_init(envp);
4921 LIST_INIT (&vm_change_state_head);
4924 struct sigaction act;
4925 sigfillset(&act.sa_mask);
4927 act.sa_handler = SIG_IGN;
4928 sigaction(SIGPIPE, &act, NULL);
4931 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4932 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4933 QEMU to run on a single CPU */
4938 h = GetCurrentProcess();
4939 if (GetProcessAffinityMask(h, &mask, &smask)) {
4940 for(i = 0; i < 32; i++) {
4941 if (mask & (1 << i))
4946 SetProcessAffinityMask(h, mask);
4952 module_call_init(MODULE_INIT_MACHINE);
4953 machine = find_default_machine();
4955 initrd_filename = NULL;
4958 kernel_filename = NULL;
4959 kernel_cmdline = "";
4960 cyls = heads = secs = 0;
4961 translation = BIOS_ATA_TRANSLATION_AUTO;
4962 monitor_device = "vc:80Cx24C";
4964 serial_devices[0] = "vc:80Cx24C";
4965 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4966 serial_devices[i] = NULL;
4967 serial_device_index = 0;
4969 parallel_devices[0] = "vc:80Cx24C";
4970 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4971 parallel_devices[i] = NULL;
4972 parallel_device_index = 0;
4974 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4975 virtio_consoles[i] = NULL;
4976 virtio_console_index = 0;
4978 for (i = 0; i < MAX_NODES; i++) {
4980 node_cpumask[i] = 0;
4994 register_watchdogs();
5002 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5004 const QEMUOption *popt;
5007 /* Treat --foo the same as -foo. */
5010 popt = qemu_options;
5013 fprintf(stderr, "%s: invalid option -- '%s'\n",
5017 if (!strcmp(popt->name, r + 1))
5021 if (popt->flags & HAS_ARG) {
5022 if (optind >= argc) {
5023 fprintf(stderr, "%s: option '%s' requires an argument\n",
5027 optarg = argv[optind++];
5032 switch(popt->index) {
5034 machine = find_machine(optarg);
5037 printf("Supported machines are:\n");
5038 for(m = first_machine; m != NULL; m = m->next) {
5040 printf("%-10s %s (alias of %s)\n",
5041 m->alias, m->desc, m->name);
5042 printf("%-10s %s%s\n",
5044 m->is_default ? " (default)" : "");
5046 exit(*optarg != '?');
5049 case QEMU_OPTION_cpu:
5050 /* hw initialization will check this */
5051 if (*optarg == '?') {
5052 /* XXX: implement xxx_cpu_list for targets that still miss it */
5053 #if defined(cpu_list)
5054 cpu_list(stdout, &fprintf);
5061 case QEMU_OPTION_initrd:
5062 initrd_filename = optarg;
5064 case QEMU_OPTION_hda:
5066 hda_index = drive_add(optarg, HD_ALIAS, 0);
5068 hda_index = drive_add(optarg, HD_ALIAS
5069 ",cyls=%d,heads=%d,secs=%d%s",
5070 0, cyls, heads, secs,
5071 translation == BIOS_ATA_TRANSLATION_LBA ?
5073 translation == BIOS_ATA_TRANSLATION_NONE ?
5074 ",trans=none" : "");
5076 case QEMU_OPTION_hdb:
5077 case QEMU_OPTION_hdc:
5078 case QEMU_OPTION_hdd:
5079 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5081 case QEMU_OPTION_drive:
5082 drive_add(NULL, "%s", optarg);
5084 case QEMU_OPTION_mtdblock:
5085 drive_add(optarg, MTD_ALIAS);
5087 case QEMU_OPTION_sd:
5088 drive_add(optarg, SD_ALIAS);
5090 case QEMU_OPTION_pflash:
5091 drive_add(optarg, PFLASH_ALIAS);
5093 case QEMU_OPTION_snapshot:
5096 case QEMU_OPTION_hdachs:
5100 cyls = strtol(p, (char **)&p, 0);
5101 if (cyls < 1 || cyls > 16383)
5106 heads = strtol(p, (char **)&p, 0);
5107 if (heads < 1 || heads > 16)
5112 secs = strtol(p, (char **)&p, 0);
5113 if (secs < 1 || secs > 63)
5117 if (!strcmp(p, "none"))
5118 translation = BIOS_ATA_TRANSLATION_NONE;
5119 else if (!strcmp(p, "lba"))
5120 translation = BIOS_ATA_TRANSLATION_LBA;
5121 else if (!strcmp(p, "auto"))
5122 translation = BIOS_ATA_TRANSLATION_AUTO;
5125 } else if (*p != '\0') {
5127 fprintf(stderr, "qemu: invalid physical CHS format\n");
5130 if (hda_index != -1)
5131 snprintf(drives_opt[hda_index].opt,
5132 sizeof(drives_opt[hda_index].opt),
5133 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5134 0, cyls, heads, secs,
5135 translation == BIOS_ATA_TRANSLATION_LBA ?
5137 translation == BIOS_ATA_TRANSLATION_NONE ?
5138 ",trans=none" : "");
5141 case QEMU_OPTION_numa:
5142 if (nb_numa_nodes >= MAX_NODES) {
5143 fprintf(stderr, "qemu: too many NUMA nodes\n");
5148 case QEMU_OPTION_nographic:
5149 display_type = DT_NOGRAPHIC;
5151 #ifdef CONFIG_CURSES
5152 case QEMU_OPTION_curses:
5153 display_type = DT_CURSES;
5156 case QEMU_OPTION_portrait:
5159 case QEMU_OPTION_kernel:
5160 kernel_filename = optarg;
5162 case QEMU_OPTION_append:
5163 kernel_cmdline = optarg;
5165 case QEMU_OPTION_cdrom:
5166 drive_add(optarg, CDROM_ALIAS);
5168 case QEMU_OPTION_boot:
5170 static const char * const params[] = {
5171 "order", "once", "menu", NULL
5173 char buf[sizeof(boot_devices)];
5174 char *standard_boot_devices;
5177 if (!strchr(optarg, '=')) {
5179 pstrcpy(buf, sizeof(buf), optarg);
5180 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5182 "qemu: unknown boot parameter '%s' in '%s'\n",
5188 get_param_value(buf, sizeof(buf), "order", optarg)) {
5189 boot_devices_bitmap = parse_bootdevices(buf);
5190 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5193 if (get_param_value(buf, sizeof(buf),
5195 boot_devices_bitmap |= parse_bootdevices(buf);
5196 standard_boot_devices = qemu_strdup(boot_devices);
5197 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5198 qemu_register_reset(restore_boot_devices,
5199 standard_boot_devices);
5201 if (get_param_value(buf, sizeof(buf),
5203 if (!strcmp(buf, "on")) {
5205 } else if (!strcmp(buf, "off")) {
5209 "qemu: invalid option value '%s'\n",
5217 case QEMU_OPTION_fda:
5218 case QEMU_OPTION_fdb:
5219 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5222 case QEMU_OPTION_no_fd_bootchk:
5226 case QEMU_OPTION_net:
5227 if (nb_net_clients >= MAX_NET_CLIENTS) {
5228 fprintf(stderr, "qemu: too many network clients\n");
5231 net_clients[nb_net_clients] = optarg;
5235 case QEMU_OPTION_tftp:
5236 legacy_tftp_prefix = optarg;
5238 case QEMU_OPTION_bootp:
5239 legacy_bootp_filename = optarg;
5242 case QEMU_OPTION_smb:
5243 net_slirp_smb(optarg);
5246 case QEMU_OPTION_redir:
5247 net_slirp_redir(optarg);
5250 case QEMU_OPTION_bt:
5251 add_device_config(DEV_BT, optarg);
5254 case QEMU_OPTION_audio_help:
5258 case QEMU_OPTION_soundhw:
5259 select_soundhw (optarg);
5265 case QEMU_OPTION_version:
5269 case QEMU_OPTION_m: {
5273 value = strtoul(optarg, &ptr, 10);
5275 case 0: case 'M': case 'm':
5282 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5286 /* On 32-bit hosts, QEMU is limited by virtual address space */
5287 if (value > (2047 << 20)
5288 #ifndef CONFIG_KQEMU
5289 && HOST_LONG_BITS == 32
5292 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5295 if (value != (uint64_t)(ram_addr_t)value) {
5296 fprintf(stderr, "qemu: ram size too large\n");
5305 const CPULogItem *item;
5307 mask = cpu_str_to_log_mask(optarg);
5309 printf("Log items (comma separated):\n");
5310 for(item = cpu_log_items; item->mask != 0; item++) {
5311 printf("%-10s %s\n", item->name, item->help);
5319 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5321 case QEMU_OPTION_gdb:
5322 gdbstub_dev = optarg;
5327 case QEMU_OPTION_bios:
5330 case QEMU_OPTION_singlestep:
5338 keyboard_layout = optarg;
5341 case QEMU_OPTION_localtime:
5344 case QEMU_OPTION_vga:
5345 select_vgahw (optarg);
5347 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5353 w = strtol(p, (char **)&p, 10);
5356 fprintf(stderr, "qemu: invalid resolution or depth\n");
5362 h = strtol(p, (char **)&p, 10);
5367 depth = strtol(p, (char **)&p, 10);
5368 if (depth != 8 && depth != 15 && depth != 16 &&
5369 depth != 24 && depth != 32)
5371 } else if (*p == '\0') {
5372 depth = graphic_depth;
5379 graphic_depth = depth;
5383 case QEMU_OPTION_echr:
5386 term_escape_char = strtol(optarg, &r, 0);
5388 printf("Bad argument to echr\n");
5391 case QEMU_OPTION_monitor:
5392 monitor_device = optarg;
5394 case QEMU_OPTION_serial:
5395 if (serial_device_index >= MAX_SERIAL_PORTS) {
5396 fprintf(stderr, "qemu: too many serial ports\n");
5399 serial_devices[serial_device_index] = optarg;
5400 serial_device_index++;
5402 case QEMU_OPTION_watchdog:
5403 i = select_watchdog(optarg);
5405 exit (i == 1 ? 1 : 0);
5407 case QEMU_OPTION_watchdog_action:
5408 if (select_watchdog_action(optarg) == -1) {
5409 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5413 case QEMU_OPTION_virtiocon:
5414 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5415 fprintf(stderr, "qemu: too many virtio consoles\n");
5418 virtio_consoles[virtio_console_index] = optarg;
5419 virtio_console_index++;
5421 case QEMU_OPTION_parallel:
5422 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5423 fprintf(stderr, "qemu: too many parallel ports\n");
5426 parallel_devices[parallel_device_index] = optarg;
5427 parallel_device_index++;
5429 case QEMU_OPTION_loadvm:
5432 case QEMU_OPTION_full_screen:
5436 case QEMU_OPTION_no_frame:
5439 case QEMU_OPTION_alt_grab:
5442 case QEMU_OPTION_no_quit:
5445 case QEMU_OPTION_sdl:
5446 display_type = DT_SDL;
5449 case QEMU_OPTION_pidfile:
5453 case QEMU_OPTION_win2k_hack:
5454 win2k_install_hack = 1;
5456 case QEMU_OPTION_rtc_td_hack:
5459 case QEMU_OPTION_acpitable:
5460 if(acpi_table_add(optarg) < 0) {
5461 fprintf(stderr, "Wrong acpi table provided\n");
5465 case QEMU_OPTION_smbios:
5466 if(smbios_entry_add(optarg) < 0) {
5467 fprintf(stderr, "Wrong smbios provided\n");
5473 case QEMU_OPTION_enable_kqemu:
5476 case QEMU_OPTION_kernel_kqemu:
5481 case QEMU_OPTION_enable_kvm:
5488 case QEMU_OPTION_usb:
5491 case QEMU_OPTION_usbdevice:
5493 add_device_config(DEV_USB, optarg);
5495 case QEMU_OPTION_device:
5496 add_device_config(DEV_GENERIC, optarg);
5498 case QEMU_OPTION_smp:
5499 smp_cpus = atoi(optarg);
5501 fprintf(stderr, "Invalid number of CPUs\n");
5505 case QEMU_OPTION_vnc:
5506 display_type = DT_VNC;
5507 vnc_display = optarg;
5510 case QEMU_OPTION_no_acpi:
5513 case QEMU_OPTION_no_hpet:
5516 case QEMU_OPTION_balloon:
5517 if (balloon_parse(optarg) < 0) {
5518 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5523 case QEMU_OPTION_no_reboot:
5526 case QEMU_OPTION_no_shutdown:
5529 case QEMU_OPTION_show_cursor:
5532 case QEMU_OPTION_uuid:
5533 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5534 fprintf(stderr, "Fail to parse UUID string."
5535 " Wrong format.\n");
5540 case QEMU_OPTION_daemonize:
5544 case QEMU_OPTION_option_rom:
5545 if (nb_option_roms >= MAX_OPTION_ROMS) {
5546 fprintf(stderr, "Too many option ROMs\n");
5549 option_rom[nb_option_roms] = optarg;
5552 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5553 case QEMU_OPTION_semihosting:
5554 semihosting_enabled = 1;
5557 case QEMU_OPTION_name:
5558 qemu_name = qemu_strdup(optarg);
5560 char *p = strchr(qemu_name, ',');
5563 if (strncmp(p, "process=", 8)) {
5564 fprintf(stderr, "Unknown subargument %s to -name", p);
5572 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5573 case QEMU_OPTION_prom_env:
5574 if (nb_prom_envs >= MAX_PROM_ENVS) {
5575 fprintf(stderr, "Too many prom variables\n");
5578 prom_envs[nb_prom_envs] = optarg;
5583 case QEMU_OPTION_old_param:
5587 case QEMU_OPTION_clock:
5588 configure_alarms(optarg);
5590 case QEMU_OPTION_startdate:
5593 time_t rtc_start_date;
5594 if (!strcmp(optarg, "now")) {
5595 rtc_date_offset = -1;
5597 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5605 } else if (sscanf(optarg, "%d-%d-%d",
5608 &tm.tm_mday) == 3) {
5617 rtc_start_date = mktimegm(&tm);
5618 if (rtc_start_date == -1) {
5620 fprintf(stderr, "Invalid date format. Valid format are:\n"
5621 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5624 rtc_date_offset = time(NULL) - rtc_start_date;
5628 case QEMU_OPTION_tb_size:
5629 tb_size = strtol(optarg, NULL, 0);
5633 case QEMU_OPTION_icount:
5635 if (strcmp(optarg, "auto") == 0) {
5636 icount_time_shift = -1;
5638 icount_time_shift = strtol(optarg, NULL, 0);
5641 case QEMU_OPTION_incoming:
5645 case QEMU_OPTION_chroot:
5646 chroot_dir = optarg;
5648 case QEMU_OPTION_runas:
5653 case QEMU_OPTION_xen_domid:
5654 xen_domid = atoi(optarg);
5656 case QEMU_OPTION_xen_create:
5657 xen_mode = XEN_CREATE;
5659 case QEMU_OPTION_xen_attach:
5660 xen_mode = XEN_ATTACH;
5667 /* If no data_dir is specified then try to find it relative to the
5670 data_dir = find_datadir(argv[0]);
5672 /* If all else fails use the install patch specified when building. */
5674 data_dir = CONFIG_QEMU_SHAREDIR;
5677 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5678 if (kvm_allowed && kqemu_allowed) {
5680 "You can not enable both KVM and kqemu at the same time\n");
5685 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5686 if (smp_cpus > machine->max_cpus) {
5687 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5688 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5693 if (display_type == DT_NOGRAPHIC) {
5694 if (serial_device_index == 0)
5695 serial_devices[0] = "stdio";
5696 if (parallel_device_index == 0)
5697 parallel_devices[0] = "null";
5698 if (strncmp(monitor_device, "vc", 2) == 0)
5699 monitor_device = "stdio";
5706 if (pipe(fds) == -1)
5717 len = read(fds[0], &status, 1);
5718 if (len == -1 && (errno == EINTR))
5723 else if (status == 1) {
5724 fprintf(stderr, "Could not acquire pidfile\n");
5741 signal(SIGTSTP, SIG_IGN);
5742 signal(SIGTTOU, SIG_IGN);
5743 signal(SIGTTIN, SIG_IGN);
5746 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5749 write(fds[1], &status, 1);
5751 fprintf(stderr, "Could not acquire pid file\n");
5760 if (qemu_init_main_loop()) {
5761 fprintf(stderr, "qemu_init_main_loop failed\n");
5764 linux_boot = (kernel_filename != NULL);
5766 if (!linux_boot && *kernel_cmdline != '\0') {
5767 fprintf(stderr, "-append only allowed with -kernel option\n");
5771 if (!linux_boot && initrd_filename != NULL) {
5772 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5776 setvbuf(stdout, NULL, _IOLBF, 0);
5779 if (init_timer_alarm() < 0) {
5780 fprintf(stderr, "could not initialize alarm timer\n");
5783 if (use_icount && icount_time_shift < 0) {
5785 /* 125MIPS seems a reasonable initial guess at the guest speed.
5786 It will be corrected fairly quickly anyway. */
5787 icount_time_shift = 3;
5788 init_icount_adjust();
5795 /* init network clients */
5796 if (nb_net_clients == 0) {
5797 /* if no clients, we use a default config */
5798 net_clients[nb_net_clients++] = "nic";
5800 net_clients[nb_net_clients++] = "user";
5804 for(i = 0;i < nb_net_clients; i++) {
5805 if (net_client_parse(net_clients[i]) < 0)
5809 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5810 net_set_boot_mask(net_boot);
5814 /* init the bluetooth world */
5815 if (foreach_device_config(DEV_BT, bt_parse))
5818 /* init the memory */
5820 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5823 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5824 guest ram allocation. It needs to go away. */
5825 if (kqemu_allowed) {
5826 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
5827 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5828 if (!kqemu_phys_ram_base) {
5829 fprintf(stderr, "Could not allocate physical memory\n");
5835 /* init the dynamic translator */
5836 cpu_exec_init_all(tb_size * 1024 * 1024);
5840 /* we always create the cdrom drive, even if no disk is there */
5842 if (nb_drives_opt < MAX_DRIVES)
5843 drive_add(NULL, CDROM_ALIAS);
5845 /* we always create at least one floppy */
5847 if (nb_drives_opt < MAX_DRIVES)
5848 drive_add(NULL, FD_ALIAS, 0);
5850 /* we always create one sd slot, even if no card is in it */
5852 if (nb_drives_opt < MAX_DRIVES)
5853 drive_add(NULL, SD_ALIAS);
5855 /* open the virtual block devices */
5857 for(i = 0; i < nb_drives_opt; i++)
5858 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5861 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5862 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5865 /* must be after terminal init, SDL library changes signal handlers */
5869 /* Maintain compatibility with multiple stdio monitors */
5870 if (!strcmp(monitor_device,"stdio")) {
5871 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5872 const char *devname = serial_devices[i];
5873 if (devname && !strcmp(devname,"mon:stdio")) {
5874 monitor_device = NULL;
5876 } else if (devname && !strcmp(devname,"stdio")) {
5877 monitor_device = NULL;
5878 serial_devices[i] = "mon:stdio";
5884 if (nb_numa_nodes > 0) {
5887 if (nb_numa_nodes > smp_cpus) {
5888 nb_numa_nodes = smp_cpus;
5891 /* If no memory size if given for any node, assume the default case
5892 * and distribute the available memory equally across all nodes
5894 for (i = 0; i < nb_numa_nodes; i++) {
5895 if (node_mem[i] != 0)
5898 if (i == nb_numa_nodes) {
5899 uint64_t usedmem = 0;
5901 /* On Linux, the each node's border has to be 8MB aligned,
5902 * the final node gets the rest.
5904 for (i = 0; i < nb_numa_nodes - 1; i++) {
5905 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5906 usedmem += node_mem[i];
5908 node_mem[i] = ram_size - usedmem;
5911 for (i = 0; i < nb_numa_nodes; i++) {
5912 if (node_cpumask[i] != 0)
5915 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5916 * must cope with this anyway, because there are BIOSes out there in
5917 * real machines which also use this scheme.
5919 if (i == nb_numa_nodes) {
5920 for (i = 0; i < smp_cpus; i++) {
5921 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5926 if (kvm_enabled()) {
5929 ret = kvm_init(smp_cpus);
5931 fprintf(stderr, "failed to initialize KVM\n");
5936 if (monitor_device) {
5937 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5939 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5944 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5945 const char *devname = serial_devices[i];
5946 if (devname && strcmp(devname, "none")) {
5948 snprintf(label, sizeof(label), "serial%d", i);
5949 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5950 if (!serial_hds[i]) {
5951 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5958 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5959 const char *devname = parallel_devices[i];
5960 if (devname && strcmp(devname, "none")) {
5962 snprintf(label, sizeof(label), "parallel%d", i);
5963 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5964 if (!parallel_hds[i]) {
5965 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5972 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5973 const char *devname = virtio_consoles[i];
5974 if (devname && strcmp(devname, "none")) {
5976 snprintf(label, sizeof(label), "virtcon%d", i);
5977 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5978 if (!virtcon_hds[i]) {
5979 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5986 module_call_init(MODULE_INIT_DEVICE);
5988 if (machine->compat_props) {
5989 qdev_prop_register_compat(machine->compat_props);
5991 machine->init(ram_size, boot_devices,
5992 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5995 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5996 for (i = 0; i < nb_numa_nodes; i++) {
5997 if (node_cpumask[i] & (1 << env->cpu_index)) {
6003 current_machine = machine;
6005 /* init USB devices */
6007 foreach_device_config(DEV_USB, usb_parse);
6010 /* init generic devices */
6011 if (foreach_device_config(DEV_GENERIC, generic_parse))
6015 dumb_display_init();
6016 /* just use the first displaystate for the moment */
6019 if (display_type == DT_DEFAULT) {
6020 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6021 display_type = DT_SDL;
6023 display_type = DT_VNC;
6024 vnc_display = "localhost:0,to=99";
6030 switch (display_type) {
6033 #if defined(CONFIG_CURSES)
6035 curses_display_init(ds, full_screen);
6038 #if defined(CONFIG_SDL)
6040 sdl_display_init(ds, full_screen, no_frame);
6042 #elif defined(CONFIG_COCOA)
6044 cocoa_display_init(ds, full_screen);
6048 vnc_display_init(ds);
6049 if (vnc_display_open(ds, vnc_display) < 0)
6052 if (show_vnc_port) {
6053 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6061 dcl = ds->listeners;
6062 while (dcl != NULL) {
6063 if (dcl->dpy_refresh != NULL) {
6064 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6065 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6070 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6071 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6072 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6075 text_consoles_set_display(display_state);
6076 qemu_chr_initial_reset();
6078 if (monitor_device && monitor_hd)
6079 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6081 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6082 const char *devname = serial_devices[i];
6083 if (devname && strcmp(devname, "none")) {
6084 if (strstart(devname, "vc", 0))
6085 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6089 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6090 const char *devname = parallel_devices[i];
6091 if (devname && strcmp(devname, "none")) {
6092 if (strstart(devname, "vc", 0))
6093 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6097 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6098 const char *devname = virtio_consoles[i];
6099 if (virtcon_hds[i] && devname) {
6100 if (strstart(devname, "vc", 0))
6101 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6105 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6106 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6112 do_loadvm(cur_mon, loadvm);
6115 qemu_start_incoming_migration(incoming);
6126 len = write(fds[1], &status, 1);
6127 if (len == -1 && (errno == EINTR))
6134 TFR(fd = open("/dev/null", O_RDWR));
6140 pwd = getpwnam(run_as);
6142 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6148 if (chroot(chroot_dir) < 0) {
6149 fprintf(stderr, "chroot failed\n");
6156 if (setgid(pwd->pw_gid) < 0) {
6157 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6160 if (setuid(pwd->pw_uid) < 0) {
6161 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6164 if (setuid(0) != -1) {
6165 fprintf(stderr, "Dropping privileges failed\n");