4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
34 /* Needed early to override system queue definitions on BSD */
35 #include "sys-queue.h"
40 #include <sys/times.h>
44 #include <sys/ioctl.h>
45 #include <sys/resource.h>
46 #include <sys/socket.h>
47 #include <netinet/in.h>
49 #if defined(__NetBSD__)
50 #include <net/if_tap.h>
53 #include <linux/if_tun.h>
55 #include <arpa/inet.h>
58 #include <sys/select.h>
61 #if defined(__FreeBSD__) || defined(__DragonFly__)
66 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
67 #include <freebsd/stdlib.h>
72 #include <linux/rtc.h>
73 #include <sys/prctl.h>
75 /* For the benefit of older linux systems which don't supply it,
76 we use a local copy of hpet.h. */
77 /* #include <linux/hpet.h> */
80 #include <linux/ppdev.h>
81 #include <linux/parport.h>
85 #include <sys/ethernet.h>
86 #include <sys/sockio.h>
87 #include <netinet/arp.h>
88 #include <netinet/in.h>
89 #include <netinet/in_systm.h>
90 #include <netinet/ip.h>
91 #include <netinet/ip_icmp.h> // must come after ip.h
92 #include <netinet/udp.h>
93 #include <netinet/tcp.h>
101 #if defined(__OpenBSD__)
105 #if defined(CONFIG_VDE)
106 #include <libvdeplug.h>
111 #include <mmsystem.h>
115 #if defined(__APPLE__) || defined(main)
117 int qemu_main(int argc, char **argv, char **envp);
118 int main(int argc, char **argv)
120 return qemu_main(argc, argv, NULL);
123 #define main qemu_main
125 #endif /* CONFIG_SDL */
129 #define main qemu_main
130 #endif /* CONFIG_COCOA */
133 #include "hw/boards.h"
135 #include "hw/pcmcia.h"
137 #include "hw/audiodev.h"
141 #include "hw/watchdog.h"
142 #include "hw/smbios.h"
151 #include "qemu-timer.h"
152 #include "qemu-char.h"
153 #include "cache-utils.h"
156 #include "audio/audio.h"
157 #include "migration.h"
160 #include "qemu-option.h"
161 #include "qemu-config.h"
165 #include "exec-all.h"
167 #include "qemu_socket.h"
169 #include "slirp/libslirp.h"
172 //#define DEBUG_SLIRP
174 #define DEFAULT_RAM_SIZE 128
176 static const char *data_dir;
177 const char *bios_name = NULL;
178 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
179 to store the VM snapshots */
180 struct drivelist drives = TAILQ_HEAD_INITIALIZER(drives);
181 struct driveoptlist driveopts = TAILQ_HEAD_INITIALIZER(driveopts);
182 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
183 static DisplayState *display_state;
184 DisplayType display_type = DT_DEFAULT;
185 const char* keyboard_layout = NULL;
186 int64_t ticks_per_sec;
189 NICInfo nd_table[MAX_NICS];
192 static int rtc_utc = 1;
193 static int rtc_date_offset = -1; /* -1 means no change */
194 int vga_interface_type = VGA_CIRRUS;
196 int graphic_width = 1024;
197 int graphic_height = 768;
198 int graphic_depth = 8;
200 int graphic_width = 800;
201 int graphic_height = 600;
202 int graphic_depth = 15;
204 static int full_screen = 0;
206 static int no_frame = 0;
209 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
210 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
211 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
213 int win2k_install_hack = 0;
222 const char *vnc_display;
223 int acpi_enabled = 1;
225 int virtio_balloon = 1;
226 const char *virtio_balloon_devaddr;
231 int graphic_rotate = 0;
232 uint8_t irq0override = 1;
236 const char *option_rom[MAX_OPTION_ROMS];
238 int semihosting_enabled = 0;
242 const char *qemu_name;
244 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
245 unsigned int nb_prom_envs = 0;
246 const char *prom_envs[MAX_PROM_ENVS];
251 uint64_t node_mem[MAX_NODES];
252 uint64_t node_cpumask[MAX_NODES];
254 static CPUState *cur_cpu;
255 static CPUState *next_cpu;
256 static int timer_alarm_pending = 1;
257 /* Conversion factor from emulated instructions to virtual clock ticks. */
258 static int icount_time_shift;
259 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
260 #define MAX_ICOUNT_SHIFT 10
261 /* Compensate for varying guest execution speed. */
262 static int64_t qemu_icount_bias;
263 static QEMUTimer *icount_rt_timer;
264 static QEMUTimer *icount_vm_timer;
265 static QEMUTimer *nographic_timer;
267 uint8_t qemu_uuid[16];
269 static QEMUBootSetHandler *boot_set_handler;
270 static void *boot_set_opaque;
272 /***********************************************************/
273 /* x86 ISA bus support */
275 target_phys_addr_t isa_mem_base = 0;
278 /***********************************************************/
279 void hw_error(const char *fmt, ...)
285 fprintf(stderr, "qemu: hardware error: ");
286 vfprintf(stderr, fmt, ap);
287 fprintf(stderr, "\n");
288 for(env = first_cpu; env != NULL; env = env->next_cpu) {
289 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
291 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
293 cpu_dump_state(env, stderr, fprintf, 0);
300 static void set_proc_name(const char *s)
302 #if defined(__linux__) && defined(PR_SET_NAME)
306 name[sizeof(name) - 1] = 0;
307 strncpy(name, s, sizeof(name));
308 /* Could rewrite argv[0] too, but that's a bit more complicated.
309 This simple way is enough for `top'. */
310 prctl(PR_SET_NAME, name);
317 static QEMUBalloonEvent *qemu_balloon_event;
318 void *qemu_balloon_event_opaque;
320 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
322 qemu_balloon_event = func;
323 qemu_balloon_event_opaque = opaque;
326 void qemu_balloon(ram_addr_t target)
328 if (qemu_balloon_event)
329 qemu_balloon_event(qemu_balloon_event_opaque, target);
332 ram_addr_t qemu_balloon_status(void)
334 if (qemu_balloon_event)
335 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
339 /***********************************************************/
342 static QEMUPutKBDEvent *qemu_put_kbd_event;
343 static void *qemu_put_kbd_event_opaque;
344 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
345 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
347 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
349 qemu_put_kbd_event_opaque = opaque;
350 qemu_put_kbd_event = func;
353 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
354 void *opaque, int absolute,
357 QEMUPutMouseEntry *s, *cursor;
359 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
361 s->qemu_put_mouse_event = func;
362 s->qemu_put_mouse_event_opaque = opaque;
363 s->qemu_put_mouse_event_absolute = absolute;
364 s->qemu_put_mouse_event_name = qemu_strdup(name);
367 if (!qemu_put_mouse_event_head) {
368 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
372 cursor = qemu_put_mouse_event_head;
373 while (cursor->next != NULL)
374 cursor = cursor->next;
377 qemu_put_mouse_event_current = s;
382 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
384 QEMUPutMouseEntry *prev = NULL, *cursor;
386 if (!qemu_put_mouse_event_head || entry == NULL)
389 cursor = qemu_put_mouse_event_head;
390 while (cursor != NULL && cursor != entry) {
392 cursor = cursor->next;
395 if (cursor == NULL) // does not exist or list empty
397 else if (prev == NULL) { // entry is head
398 qemu_put_mouse_event_head = cursor->next;
399 if (qemu_put_mouse_event_current == entry)
400 qemu_put_mouse_event_current = cursor->next;
401 qemu_free(entry->qemu_put_mouse_event_name);
406 prev->next = entry->next;
408 if (qemu_put_mouse_event_current == entry)
409 qemu_put_mouse_event_current = prev;
411 qemu_free(entry->qemu_put_mouse_event_name);
415 void kbd_put_keycode(int keycode)
417 if (qemu_put_kbd_event) {
418 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
422 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
424 QEMUPutMouseEvent *mouse_event;
425 void *mouse_event_opaque;
428 if (!qemu_put_mouse_event_current) {
433 qemu_put_mouse_event_current->qemu_put_mouse_event;
435 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
438 if (graphic_rotate) {
439 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
442 width = graphic_width - 1;
443 mouse_event(mouse_event_opaque,
444 width - dy, dx, dz, buttons_state);
446 mouse_event(mouse_event_opaque,
447 dx, dy, dz, buttons_state);
451 int kbd_mouse_is_absolute(void)
453 if (!qemu_put_mouse_event_current)
456 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
459 void do_info_mice(Monitor *mon)
461 QEMUPutMouseEntry *cursor;
464 if (!qemu_put_mouse_event_head) {
465 monitor_printf(mon, "No mouse devices connected\n");
469 monitor_printf(mon, "Mouse devices available:\n");
470 cursor = qemu_put_mouse_event_head;
471 while (cursor != NULL) {
472 monitor_printf(mon, "%c Mouse #%d: %s\n",
473 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
474 index, cursor->qemu_put_mouse_event_name);
476 cursor = cursor->next;
480 void do_mouse_set(Monitor *mon, int index)
482 QEMUPutMouseEntry *cursor;
485 if (!qemu_put_mouse_event_head) {
486 monitor_printf(mon, "No mouse devices connected\n");
490 cursor = qemu_put_mouse_event_head;
491 while (cursor != NULL && index != i) {
493 cursor = cursor->next;
497 qemu_put_mouse_event_current = cursor;
499 monitor_printf(mon, "Mouse at given index not found\n");
502 /* compute with 96 bit intermediate result: (a*b)/c */
503 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
508 #ifdef HOST_WORDS_BIGENDIAN
518 rl = (uint64_t)u.l.low * (uint64_t)b;
519 rh = (uint64_t)u.l.high * (uint64_t)b;
522 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
526 /***********************************************************/
527 /* real time host monotonic timer */
529 #define QEMU_TIMER_BASE 1000000000LL
533 static int64_t clock_freq;
535 static void init_get_clock(void)
539 ret = QueryPerformanceFrequency(&freq);
541 fprintf(stderr, "Could not calibrate ticks\n");
544 clock_freq = freq.QuadPart;
547 static int64_t get_clock(void)
550 QueryPerformanceCounter(&ti);
551 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
556 static int use_rt_clock;
558 static void init_get_clock(void)
561 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
562 || defined(__DragonFly__)
565 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
572 static int64_t get_clock(void)
574 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
575 || defined(__DragonFly__)
578 clock_gettime(CLOCK_MONOTONIC, &ts);
579 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
583 /* XXX: using gettimeofday leads to problems if the date
584 changes, so it should be avoided. */
586 gettimeofday(&tv, NULL);
587 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
592 /* Return the virtual CPU time, based on the instruction counter. */
593 static int64_t cpu_get_icount(void)
596 CPUState *env = cpu_single_env;;
597 icount = qemu_icount;
600 fprintf(stderr, "Bad clock read\n");
601 icount -= (env->icount_decr.u16.low + env->icount_extra);
603 return qemu_icount_bias + (icount << icount_time_shift);
606 /***********************************************************/
607 /* guest cycle counter */
609 static int64_t cpu_ticks_prev;
610 static int64_t cpu_ticks_offset;
611 static int64_t cpu_clock_offset;
612 static int cpu_ticks_enabled;
614 /* return the host CPU cycle counter and handle stop/restart */
615 int64_t cpu_get_ticks(void)
618 return cpu_get_icount();
620 if (!cpu_ticks_enabled) {
621 return cpu_ticks_offset;
624 ticks = cpu_get_real_ticks();
625 if (cpu_ticks_prev > ticks) {
626 /* Note: non increasing ticks may happen if the host uses
628 cpu_ticks_offset += cpu_ticks_prev - ticks;
630 cpu_ticks_prev = ticks;
631 return ticks + cpu_ticks_offset;
635 /* return the host CPU monotonic timer and handle stop/restart */
636 static int64_t cpu_get_clock(void)
639 if (!cpu_ticks_enabled) {
640 return cpu_clock_offset;
643 return ti + cpu_clock_offset;
647 /* enable cpu_get_ticks() */
648 void cpu_enable_ticks(void)
650 if (!cpu_ticks_enabled) {
651 cpu_ticks_offset -= cpu_get_real_ticks();
652 cpu_clock_offset -= get_clock();
653 cpu_ticks_enabled = 1;
657 /* disable cpu_get_ticks() : the clock is stopped. You must not call
658 cpu_get_ticks() after that. */
659 void cpu_disable_ticks(void)
661 if (cpu_ticks_enabled) {
662 cpu_ticks_offset = cpu_get_ticks();
663 cpu_clock_offset = cpu_get_clock();
664 cpu_ticks_enabled = 0;
668 /***********************************************************/
671 #define QEMU_TIMER_REALTIME 0
672 #define QEMU_TIMER_VIRTUAL 1
676 /* XXX: add frequency */
684 struct QEMUTimer *next;
687 struct qemu_alarm_timer {
691 int (*start)(struct qemu_alarm_timer *t);
692 void (*stop)(struct qemu_alarm_timer *t);
693 void (*rearm)(struct qemu_alarm_timer *t);
697 #define ALARM_FLAG_DYNTICKS 0x1
698 #define ALARM_FLAG_EXPIRED 0x2
700 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
702 return t && (t->flags & ALARM_FLAG_DYNTICKS);
705 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
707 if (!alarm_has_dynticks(t))
713 /* TODO: MIN_TIMER_REARM_US should be optimized */
714 #define MIN_TIMER_REARM_US 250
716 static struct qemu_alarm_timer *alarm_timer;
720 struct qemu_alarm_win32 {
723 } alarm_win32_data = {0, -1};
725 static int win32_start_timer(struct qemu_alarm_timer *t);
726 static void win32_stop_timer(struct qemu_alarm_timer *t);
727 static void win32_rearm_timer(struct qemu_alarm_timer *t);
731 static int unix_start_timer(struct qemu_alarm_timer *t);
732 static void unix_stop_timer(struct qemu_alarm_timer *t);
736 static int dynticks_start_timer(struct qemu_alarm_timer *t);
737 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
738 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
740 static int hpet_start_timer(struct qemu_alarm_timer *t);
741 static void hpet_stop_timer(struct qemu_alarm_timer *t);
743 static int rtc_start_timer(struct qemu_alarm_timer *t);
744 static void rtc_stop_timer(struct qemu_alarm_timer *t);
746 #endif /* __linux__ */
750 /* Correlation between real and virtual time is always going to be
751 fairly approximate, so ignore small variation.
752 When the guest is idle real and virtual time will be aligned in
754 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
756 static void icount_adjust(void)
761 static int64_t last_delta;
762 /* If the VM is not running, then do nothing. */
766 cur_time = cpu_get_clock();
767 cur_icount = qemu_get_clock(vm_clock);
768 delta = cur_icount - cur_time;
769 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
771 && last_delta + ICOUNT_WOBBLE < delta * 2
772 && icount_time_shift > 0) {
773 /* The guest is getting too far ahead. Slow time down. */
777 && last_delta - ICOUNT_WOBBLE > delta * 2
778 && icount_time_shift < MAX_ICOUNT_SHIFT) {
779 /* The guest is getting too far behind. Speed time up. */
783 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
786 static void icount_adjust_rt(void * opaque)
788 qemu_mod_timer(icount_rt_timer,
789 qemu_get_clock(rt_clock) + 1000);
793 static void icount_adjust_vm(void * opaque)
795 qemu_mod_timer(icount_vm_timer,
796 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
800 static void init_icount_adjust(void)
802 /* Have both realtime and virtual time triggers for speed adjustment.
803 The realtime trigger catches emulated time passing too slowly,
804 the virtual time trigger catches emulated time passing too fast.
805 Realtime triggers occur even when idle, so use them less frequently
807 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
808 qemu_mod_timer(icount_rt_timer,
809 qemu_get_clock(rt_clock) + 1000);
810 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
811 qemu_mod_timer(icount_vm_timer,
812 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
815 static struct qemu_alarm_timer alarm_timers[] = {
818 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
819 dynticks_stop_timer, dynticks_rearm_timer, NULL},
820 /* HPET - if available - is preferred */
821 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
822 /* ...otherwise try RTC */
823 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
825 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
827 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
828 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
829 {"win32", 0, win32_start_timer,
830 win32_stop_timer, NULL, &alarm_win32_data},
835 static void show_available_alarms(void)
839 printf("Available alarm timers, in order of precedence:\n");
840 for (i = 0; alarm_timers[i].name; i++)
841 printf("%s\n", alarm_timers[i].name);
844 static void configure_alarms(char const *opt)
848 int count = ARRAY_SIZE(alarm_timers) - 1;
851 struct qemu_alarm_timer tmp;
853 if (!strcmp(opt, "?")) {
854 show_available_alarms();
860 /* Reorder the array */
861 name = strtok(arg, ",");
863 for (i = 0; i < count && alarm_timers[i].name; i++) {
864 if (!strcmp(alarm_timers[i].name, name))
869 fprintf(stderr, "Unknown clock %s\n", name);
878 tmp = alarm_timers[i];
879 alarm_timers[i] = alarm_timers[cur];
880 alarm_timers[cur] = tmp;
884 name = strtok(NULL, ",");
890 /* Disable remaining timers */
891 for (i = cur; i < count; i++)
892 alarm_timers[i].name = NULL;
894 show_available_alarms();
902 static QEMUTimer *active_timers[2];
904 static QEMUClock *qemu_new_clock(int type)
907 clock = qemu_mallocz(sizeof(QEMUClock));
912 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
916 ts = qemu_mallocz(sizeof(QEMUTimer));
923 void qemu_free_timer(QEMUTimer *ts)
928 /* stop a timer, but do not dealloc it */
929 void qemu_del_timer(QEMUTimer *ts)
933 /* NOTE: this code must be signal safe because
934 qemu_timer_expired() can be called from a signal. */
935 pt = &active_timers[ts->clock->type];
948 /* modify the current timer so that it will be fired when current_time
949 >= expire_time. The corresponding callback will be called. */
950 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
956 /* add the timer in the sorted list */
957 /* NOTE: this code must be signal safe because
958 qemu_timer_expired() can be called from a signal. */
959 pt = &active_timers[ts->clock->type];
964 if (t->expire_time > expire_time)
968 ts->expire_time = expire_time;
972 /* Rearm if necessary */
973 if (pt == &active_timers[ts->clock->type]) {
974 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
975 qemu_rearm_alarm_timer(alarm_timer);
977 /* Interrupt execution to force deadline recalculation. */
983 int qemu_timer_pending(QEMUTimer *ts)
986 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
993 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
997 return (timer_head->expire_time <= current_time);
1000 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1006 if (!ts || ts->expire_time > current_time)
1008 /* remove timer from the list before calling the callback */
1009 *ptimer_head = ts->next;
1012 /* run the callback (the timer list can be modified) */
1017 int64_t qemu_get_clock(QEMUClock *clock)
1019 switch(clock->type) {
1020 case QEMU_TIMER_REALTIME:
1021 return get_clock() / 1000000;
1023 case QEMU_TIMER_VIRTUAL:
1025 return cpu_get_icount();
1027 return cpu_get_clock();
1032 static void init_timers(void)
1035 ticks_per_sec = QEMU_TIMER_BASE;
1036 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1037 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1041 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1043 uint64_t expire_time;
1045 if (qemu_timer_pending(ts)) {
1046 expire_time = ts->expire_time;
1050 qemu_put_be64(f, expire_time);
1053 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1055 uint64_t expire_time;
1057 expire_time = qemu_get_be64(f);
1058 if (expire_time != -1) {
1059 qemu_mod_timer(ts, expire_time);
1065 static void timer_save(QEMUFile *f, void *opaque)
1067 if (cpu_ticks_enabled) {
1068 hw_error("cannot save state if virtual timers are running");
1070 qemu_put_be64(f, cpu_ticks_offset);
1071 qemu_put_be64(f, ticks_per_sec);
1072 qemu_put_be64(f, cpu_clock_offset);
1075 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1077 if (version_id != 1 && version_id != 2)
1079 if (cpu_ticks_enabled) {
1082 cpu_ticks_offset=qemu_get_be64(f);
1083 ticks_per_sec=qemu_get_be64(f);
1084 if (version_id == 2) {
1085 cpu_clock_offset=qemu_get_be64(f);
1090 static void qemu_event_increment(void);
1093 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1094 DWORD_PTR dwUser, DWORD_PTR dw1,
1097 static void host_alarm_handler(int host_signum)
1101 #define DISP_FREQ 1000
1103 static int64_t delta_min = INT64_MAX;
1104 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1106 ti = qemu_get_clock(vm_clock);
1107 if (last_clock != 0) {
1108 delta = ti - last_clock;
1109 if (delta < delta_min)
1111 if (delta > delta_max)
1114 if (++count == DISP_FREQ) {
1115 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1116 muldiv64(delta_min, 1000000, ticks_per_sec),
1117 muldiv64(delta_max, 1000000, ticks_per_sec),
1118 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1119 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1121 delta_min = INT64_MAX;
1129 if (alarm_has_dynticks(alarm_timer) ||
1131 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1132 qemu_get_clock(vm_clock))) ||
1133 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1134 qemu_get_clock(rt_clock))) {
1135 qemu_event_increment();
1136 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1138 #ifndef CONFIG_IOTHREAD
1140 /* stop the currently executing cpu because a timer occured */
1144 timer_alarm_pending = 1;
1145 qemu_notify_event();
1149 static int64_t qemu_next_deadline(void)
1153 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1154 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1155 qemu_get_clock(vm_clock);
1157 /* To avoid problems with overflow limit this to 2^32. */
1167 #if defined(__linux__) || defined(_WIN32)
1168 static uint64_t qemu_next_deadline_dyntick(void)
1176 delta = (qemu_next_deadline() + 999) / 1000;
1178 if (active_timers[QEMU_TIMER_REALTIME]) {
1179 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1180 qemu_get_clock(rt_clock))*1000;
1181 if (rtdelta < delta)
1185 if (delta < MIN_TIMER_REARM_US)
1186 delta = MIN_TIMER_REARM_US;
1194 /* Sets a specific flag */
1195 static int fcntl_setfl(int fd, int flag)
1199 flags = fcntl(fd, F_GETFL);
1203 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1209 #if defined(__linux__)
1211 #define RTC_FREQ 1024
1213 static void enable_sigio_timer(int fd)
1215 struct sigaction act;
1218 sigfillset(&act.sa_mask);
1220 act.sa_handler = host_alarm_handler;
1222 sigaction(SIGIO, &act, NULL);
1223 fcntl_setfl(fd, O_ASYNC);
1224 fcntl(fd, F_SETOWN, getpid());
1227 static int hpet_start_timer(struct qemu_alarm_timer *t)
1229 struct hpet_info info;
1232 fd = open("/dev/hpet", O_RDONLY);
1237 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1239 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1240 "error, but for better emulation accuracy type:\n"
1241 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1245 /* Check capabilities */
1246 r = ioctl(fd, HPET_INFO, &info);
1250 /* Enable periodic mode */
1251 r = ioctl(fd, HPET_EPI, 0);
1252 if (info.hi_flags && (r < 0))
1255 /* Enable interrupt */
1256 r = ioctl(fd, HPET_IE_ON, 0);
1260 enable_sigio_timer(fd);
1261 t->priv = (void *)(long)fd;
1269 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1271 int fd = (long)t->priv;
1276 static int rtc_start_timer(struct qemu_alarm_timer *t)
1279 unsigned long current_rtc_freq = 0;
1281 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1284 ioctl(rtc_fd, RTC_IRQP_READ, ¤t_rtc_freq);
1285 if (current_rtc_freq != RTC_FREQ &&
1286 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1287 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1288 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1289 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1292 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1298 enable_sigio_timer(rtc_fd);
1300 t->priv = (void *)(long)rtc_fd;
1305 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1307 int rtc_fd = (long)t->priv;
1312 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1316 struct sigaction act;
1318 sigfillset(&act.sa_mask);
1320 act.sa_handler = host_alarm_handler;
1322 sigaction(SIGALRM, &act, NULL);
1325 * Initialize ev struct to 0 to avoid valgrind complaining
1326 * about uninitialized data in timer_create call
1328 memset(&ev, 0, sizeof(ev));
1329 ev.sigev_value.sival_int = 0;
1330 ev.sigev_notify = SIGEV_SIGNAL;
1331 ev.sigev_signo = SIGALRM;
1333 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1334 perror("timer_create");
1336 /* disable dynticks */
1337 fprintf(stderr, "Dynamic Ticks disabled\n");
1342 t->priv = (void *)(long)host_timer;
1347 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1349 timer_t host_timer = (timer_t)(long)t->priv;
1351 timer_delete(host_timer);
1354 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1356 timer_t host_timer = (timer_t)(long)t->priv;
1357 struct itimerspec timeout;
1358 int64_t nearest_delta_us = INT64_MAX;
1361 if (!active_timers[QEMU_TIMER_REALTIME] &&
1362 !active_timers[QEMU_TIMER_VIRTUAL])
1365 nearest_delta_us = qemu_next_deadline_dyntick();
1367 /* check whether a timer is already running */
1368 if (timer_gettime(host_timer, &timeout)) {
1370 fprintf(stderr, "Internal timer error: aborting\n");
1373 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1374 if (current_us && current_us <= nearest_delta_us)
1377 timeout.it_interval.tv_sec = 0;
1378 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1379 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1380 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1381 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1383 fprintf(stderr, "Internal timer error: aborting\n");
1388 #endif /* defined(__linux__) */
1390 static int unix_start_timer(struct qemu_alarm_timer *t)
1392 struct sigaction act;
1393 struct itimerval itv;
1397 sigfillset(&act.sa_mask);
1399 act.sa_handler = host_alarm_handler;
1401 sigaction(SIGALRM, &act, NULL);
1403 itv.it_interval.tv_sec = 0;
1404 /* for i386 kernel 2.6 to get 1 ms */
1405 itv.it_interval.tv_usec = 999;
1406 itv.it_value.tv_sec = 0;
1407 itv.it_value.tv_usec = 10 * 1000;
1409 err = setitimer(ITIMER_REAL, &itv, NULL);
1416 static void unix_stop_timer(struct qemu_alarm_timer *t)
1418 struct itimerval itv;
1420 memset(&itv, 0, sizeof(itv));
1421 setitimer(ITIMER_REAL, &itv, NULL);
1424 #endif /* !defined(_WIN32) */
1429 static int win32_start_timer(struct qemu_alarm_timer *t)
1432 struct qemu_alarm_win32 *data = t->priv;
1435 memset(&tc, 0, sizeof(tc));
1436 timeGetDevCaps(&tc, sizeof(tc));
1438 if (data->period < tc.wPeriodMin)
1439 data->period = tc.wPeriodMin;
1441 timeBeginPeriod(data->period);
1443 flags = TIME_CALLBACK_FUNCTION;
1444 if (alarm_has_dynticks(t))
1445 flags |= TIME_ONESHOT;
1447 flags |= TIME_PERIODIC;
1449 data->timerId = timeSetEvent(1, // interval (ms)
1450 data->period, // resolution
1451 host_alarm_handler, // function
1452 (DWORD)t, // parameter
1455 if (!data->timerId) {
1456 perror("Failed to initialize win32 alarm timer");
1457 timeEndPeriod(data->period);
1464 static void win32_stop_timer(struct qemu_alarm_timer *t)
1466 struct qemu_alarm_win32 *data = t->priv;
1468 timeKillEvent(data->timerId);
1469 timeEndPeriod(data->period);
1472 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1474 struct qemu_alarm_win32 *data = t->priv;
1475 uint64_t nearest_delta_us;
1477 if (!active_timers[QEMU_TIMER_REALTIME] &&
1478 !active_timers[QEMU_TIMER_VIRTUAL])
1481 nearest_delta_us = qemu_next_deadline_dyntick();
1482 nearest_delta_us /= 1000;
1484 timeKillEvent(data->timerId);
1486 data->timerId = timeSetEvent(1,
1490 TIME_ONESHOT | TIME_PERIODIC);
1492 if (!data->timerId) {
1493 perror("Failed to re-arm win32 alarm timer");
1495 timeEndPeriod(data->period);
1502 static int init_timer_alarm(void)
1504 struct qemu_alarm_timer *t = NULL;
1507 for (i = 0; alarm_timers[i].name; i++) {
1508 t = &alarm_timers[i];
1528 static void quit_timers(void)
1530 alarm_timer->stop(alarm_timer);
1534 /***********************************************************/
1535 /* host time/date access */
1536 void qemu_get_timedate(struct tm *tm, int offset)
1543 if (rtc_date_offset == -1) {
1547 ret = localtime(&ti);
1549 ti -= rtc_date_offset;
1553 memcpy(tm, ret, sizeof(struct tm));
1556 int qemu_timedate_diff(struct tm *tm)
1560 if (rtc_date_offset == -1)
1562 seconds = mktimegm(tm);
1564 seconds = mktime(tm);
1566 seconds = mktimegm(tm) + rtc_date_offset;
1568 return seconds - time(NULL);
1572 static void socket_cleanup(void)
1577 static int socket_init(void)
1582 ret = WSAStartup(MAKEWORD(2,2), &Data);
1584 err = WSAGetLastError();
1585 fprintf(stderr, "WSAStartup: %d\n", err);
1588 atexit(socket_cleanup);
1593 /***********************************************************/
1594 /* Bluetooth support */
1597 static struct HCIInfo *hci_table[MAX_NICS];
1599 static struct bt_vlan_s {
1600 struct bt_scatternet_s net;
1602 struct bt_vlan_s *next;
1605 /* find or alloc a new bluetooth "VLAN" */
1606 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1608 struct bt_vlan_s **pvlan, *vlan;
1609 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1613 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1615 pvlan = &first_bt_vlan;
1616 while (*pvlan != NULL)
1617 pvlan = &(*pvlan)->next;
1622 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1626 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1631 static struct HCIInfo null_hci = {
1632 .cmd_send = null_hci_send,
1633 .sco_send = null_hci_send,
1634 .acl_send = null_hci_send,
1635 .bdaddr_set = null_hci_addr_set,
1638 struct HCIInfo *qemu_next_hci(void)
1640 if (cur_hci == nb_hcis)
1643 return hci_table[cur_hci++];
1646 static struct HCIInfo *hci_init(const char *str)
1649 struct bt_scatternet_s *vlan = 0;
1651 if (!strcmp(str, "null"))
1654 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1656 return bt_host_hci(str[4] ? str + 5 : "hci0");
1657 else if (!strncmp(str, "hci", 3)) {
1660 if (!strncmp(str + 3, ",vlan=", 6)) {
1661 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1666 vlan = qemu_find_bt_vlan(0);
1668 return bt_new_hci(vlan);
1671 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1676 static int bt_hci_parse(const char *str)
1678 struct HCIInfo *hci;
1681 if (nb_hcis >= MAX_NICS) {
1682 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1686 hci = hci_init(str);
1695 bdaddr.b[5] = 0x56 + nb_hcis;
1696 hci->bdaddr_set(hci, bdaddr.b);
1698 hci_table[nb_hcis++] = hci;
1703 static void bt_vhci_add(int vlan_id)
1705 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1708 fprintf(stderr, "qemu: warning: adding a VHCI to "
1709 "an empty scatternet %i\n", vlan_id);
1711 bt_vhci_init(bt_new_hci(vlan));
1714 static struct bt_device_s *bt_device_add(const char *opt)
1716 struct bt_scatternet_s *vlan;
1718 char *endp = strstr(opt, ",vlan=");
1719 int len = (endp ? endp - opt : strlen(opt)) + 1;
1722 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1725 vlan_id = strtol(endp + 6, &endp, 0);
1727 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1732 vlan = qemu_find_bt_vlan(vlan_id);
1735 fprintf(stderr, "qemu: warning: adding a slave device to "
1736 "an empty scatternet %i\n", vlan_id);
1738 if (!strcmp(devname, "keyboard"))
1739 return bt_keyboard_init(vlan);
1741 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1745 static int bt_parse(const char *opt)
1747 const char *endp, *p;
1750 if (strstart(opt, "hci", &endp)) {
1751 if (!*endp || *endp == ',') {
1753 if (!strstart(endp, ",vlan=", 0))
1756 return bt_hci_parse(opt);
1758 } else if (strstart(opt, "vhci", &endp)) {
1759 if (!*endp || *endp == ',') {
1761 if (strstart(endp, ",vlan=", &p)) {
1762 vlan = strtol(p, (char **) &endp, 0);
1764 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1768 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1777 } else if (strstart(opt, "device:", &endp))
1778 return !bt_device_add(endp);
1780 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1784 /***********************************************************/
1785 /* QEMU Block devices */
1787 #define HD_ALIAS "index=%d,media=disk"
1788 #define CDROM_ALIAS "index=2,media=cdrom"
1789 #define FD_ALIAS "index=%d,if=floppy"
1790 #define PFLASH_ALIAS "if=pflash"
1791 #define MTD_ALIAS "if=mtd"
1792 #define SD_ALIAS "index=0,if=sd"
1794 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1801 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1804 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1806 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1807 __FUNCTION__, optstr);
1811 qemu_opt_set(opts, "file", file);
1815 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1819 /* seek interface, bus and unit */
1821 TAILQ_FOREACH(dinfo, &drives, next) {
1822 if (dinfo->type == type &&
1823 dinfo->bus == bus &&
1824 dinfo->unit == unit)
1831 DriveInfo *drive_get_by_id(const char *id)
1835 TAILQ_FOREACH(dinfo, &drives, next) {
1836 if (strcmp(id, dinfo->id))
1843 int drive_get_max_bus(BlockInterfaceType type)
1849 TAILQ_FOREACH(dinfo, &drives, next) {
1850 if(dinfo->type == type &&
1851 dinfo->bus > max_bus)
1852 max_bus = dinfo->bus;
1857 const char *drive_get_serial(BlockDriverState *bdrv)
1861 TAILQ_FOREACH(dinfo, &drives, next) {
1862 if (dinfo->bdrv == bdrv)
1863 return dinfo->serial;
1869 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1873 TAILQ_FOREACH(dinfo, &drives, next) {
1874 if (dinfo->bdrv == bdrv)
1875 return dinfo->onerror;
1878 return BLOCK_ERR_STOP_ENOSPC;
1881 static void bdrv_format_print(void *opaque, const char *name)
1883 fprintf(stderr, " %s", name);
1886 void drive_uninit(BlockDriverState *bdrv)
1890 TAILQ_FOREACH(dinfo, &drives, next) {
1891 if (dinfo->bdrv != bdrv)
1893 qemu_opts_del(dinfo->opts);
1894 TAILQ_REMOVE(&drives, dinfo, next);
1900 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1904 const char *file = NULL;
1907 const char *mediastr = "";
1908 BlockInterfaceType type;
1909 enum { MEDIA_DISK, MEDIA_CDROM } media;
1910 int bus_id, unit_id;
1911 int cyls, heads, secs, translation;
1912 BlockDriver *drv = NULL;
1913 QEMUMachine *machine = opaque;
1918 int bdrv_flags, onerror;
1919 const char *devaddr;
1925 translation = BIOS_ATA_TRANSLATION_AUTO;
1928 if (machine->use_scsi) {
1930 max_devs = MAX_SCSI_DEVS;
1931 pstrcpy(devname, sizeof(devname), "scsi");
1934 max_devs = MAX_IDE_DEVS;
1935 pstrcpy(devname, sizeof(devname), "ide");
1939 /* extract parameters */
1940 bus_id = qemu_opt_get_number(opts, "bus", 0);
1941 unit_id = qemu_opt_get_number(opts, "unit", -1);
1942 index = qemu_opt_get_number(opts, "index", -1);
1944 cyls = qemu_opt_get_number(opts, "cyls", 0);
1945 heads = qemu_opt_get_number(opts, "heads", 0);
1946 secs = qemu_opt_get_number(opts, "secs", 0);
1948 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1950 file = qemu_opt_get(opts, "file");
1951 serial = qemu_opt_get(opts, "serial");
1953 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1954 pstrcpy(devname, sizeof(devname), buf);
1955 if (!strcmp(buf, "ide")) {
1957 max_devs = MAX_IDE_DEVS;
1958 } else if (!strcmp(buf, "scsi")) {
1960 max_devs = MAX_SCSI_DEVS;
1961 } else if (!strcmp(buf, "floppy")) {
1964 } else if (!strcmp(buf, "pflash")) {
1967 } else if (!strcmp(buf, "mtd")) {
1970 } else if (!strcmp(buf, "sd")) {
1973 } else if (!strcmp(buf, "virtio")) {
1976 } else if (!strcmp(buf, "xen")) {
1979 } else if (!strcmp(buf, "none")) {
1983 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
1988 if (cyls || heads || secs) {
1989 if (cyls < 1 || cyls > 16383) {
1990 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
1993 if (heads < 1 || heads > 16) {
1994 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
1997 if (secs < 1 || secs > 63) {
1998 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2003 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2006 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2010 if (!strcmp(buf, "none"))
2011 translation = BIOS_ATA_TRANSLATION_NONE;
2012 else if (!strcmp(buf, "lba"))
2013 translation = BIOS_ATA_TRANSLATION_LBA;
2014 else if (!strcmp(buf, "auto"))
2015 translation = BIOS_ATA_TRANSLATION_AUTO;
2017 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2022 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2023 if (!strcmp(buf, "disk")) {
2025 } else if (!strcmp(buf, "cdrom")) {
2026 if (cyls || secs || heads) {
2028 "qemu: '%s' invalid physical CHS format\n", buf);
2031 media = MEDIA_CDROM;
2033 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2038 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2039 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2041 else if (!strcmp(buf, "writethrough"))
2043 else if (!strcmp(buf, "writeback"))
2046 fprintf(stderr, "qemu: invalid cache option\n");
2051 #ifdef CONFIG_LINUX_AIO
2052 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2053 if (!strcmp(buf, "threads"))
2055 else if (!strcmp(buf, "native"))
2058 fprintf(stderr, "qemu: invalid aio option\n");
2064 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2065 if (strcmp(buf, "?") == 0) {
2066 fprintf(stderr, "qemu: Supported formats:");
2067 bdrv_iterate_format(bdrv_format_print, NULL);
2068 fprintf(stderr, "\n");
2071 drv = bdrv_find_format(buf);
2073 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2078 onerror = BLOCK_ERR_STOP_ENOSPC;
2079 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2080 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2081 fprintf(stderr, "werror is no supported by this format\n");
2084 if (!strcmp(buf, "ignore"))
2085 onerror = BLOCK_ERR_IGNORE;
2086 else if (!strcmp(buf, "enospc"))
2087 onerror = BLOCK_ERR_STOP_ENOSPC;
2088 else if (!strcmp(buf, "stop"))
2089 onerror = BLOCK_ERR_STOP_ANY;
2090 else if (!strcmp(buf, "report"))
2091 onerror = BLOCK_ERR_REPORT;
2093 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2098 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2099 if (type != IF_VIRTIO) {
2100 fprintf(stderr, "addr is not supported\n");
2105 /* compute bus and unit according index */
2108 if (bus_id != 0 || unit_id != -1) {
2110 "qemu: index cannot be used with bus and unit\n");
2118 unit_id = index % max_devs;
2119 bus_id = index / max_devs;
2123 /* if user doesn't specify a unit_id,
2124 * try to find the first free
2127 if (unit_id == -1) {
2129 while (drive_get(type, bus_id, unit_id) != NULL) {
2131 if (max_devs && unit_id >= max_devs) {
2132 unit_id -= max_devs;
2140 if (max_devs && unit_id >= max_devs) {
2141 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2142 unit_id, max_devs - 1);
2147 * ignore multiple definitions
2150 if (drive_get(type, bus_id, unit_id) != NULL) {
2157 dinfo = qemu_mallocz(sizeof(*dinfo));
2158 if ((buf = qemu_opts_id(opts)) != NULL) {
2159 dinfo->id = qemu_strdup(buf);
2161 /* no id supplied -> create one */
2162 dinfo->id = qemu_mallocz(32);
2163 if (type == IF_IDE || type == IF_SCSI)
2164 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2166 snprintf(dinfo->id, 32, "%s%i%s%i",
2167 devname, bus_id, mediastr, unit_id);
2169 snprintf(dinfo->id, 32, "%s%s%i",
2170 devname, mediastr, unit_id);
2172 dinfo->bdrv = bdrv_new(dinfo->id);
2173 dinfo->devaddr = devaddr;
2175 dinfo->bus = bus_id;
2176 dinfo->unit = unit_id;
2177 dinfo->onerror = onerror;
2180 strncpy(dinfo->serial, serial, sizeof(serial));
2181 TAILQ_INSERT_TAIL(&drives, dinfo, next);
2190 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2191 bdrv_set_translation_hint(dinfo->bdrv, translation);
2195 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2200 /* FIXME: This isn't really a floppy, but it's a reasonable
2203 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2210 /* add virtio block device */
2211 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2212 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2213 qemu_opt_set(opts, "drive", dinfo->id);
2215 qemu_opt_set(opts, "addr", devaddr);
2226 bdrv_flags |= BDRV_O_SNAPSHOT;
2227 cache = 2; /* always use write-back with snapshot */
2229 if (cache == 0) /* no caching */
2230 bdrv_flags |= BDRV_O_NOCACHE;
2231 else if (cache == 2) /* write-back */
2232 bdrv_flags |= BDRV_O_CACHE_WB;
2235 bdrv_flags |= BDRV_O_NATIVE_AIO;
2237 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2240 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2241 fprintf(stderr, "qemu: could not open disk image %s\n",
2246 if (bdrv_key_required(dinfo->bdrv))
2252 static int drive_init_func(QemuOpts *opts, void *opaque)
2254 QEMUMachine *machine = opaque;
2255 int fatal_error = 0;
2257 if (drive_init(opts, machine, &fatal_error) == NULL) {
2264 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2266 if (NULL == qemu_opt_get(opts, "snapshot")) {
2267 qemu_opt_set(opts, "snapshot", "on");
2272 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2274 boot_set_handler = func;
2275 boot_set_opaque = opaque;
2278 int qemu_boot_set(const char *boot_devices)
2280 if (!boot_set_handler) {
2283 return boot_set_handler(boot_set_opaque, boot_devices);
2286 static int parse_bootdevices(char *devices)
2288 /* We just do some generic consistency checks */
2292 for (p = devices; *p != '\0'; p++) {
2293 /* Allowed boot devices are:
2294 * a-b: floppy disk drives
2295 * c-f: IDE disk drives
2296 * g-m: machine implementation dependant drives
2297 * n-p: network devices
2298 * It's up to each machine implementation to check if the given boot
2299 * devices match the actual hardware implementation and firmware
2302 if (*p < 'a' || *p > 'p') {
2303 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2306 if (bitmap & (1 << (*p - 'a'))) {
2307 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2310 bitmap |= 1 << (*p - 'a');
2315 static void restore_boot_devices(void *opaque)
2317 char *standard_boot_devices = opaque;
2319 qemu_boot_set(standard_boot_devices);
2321 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2322 qemu_free(standard_boot_devices);
2325 static void numa_add(const char *optarg)
2329 unsigned long long value, endvalue;
2332 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2333 if (!strcmp(option, "node")) {
2334 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2335 nodenr = nb_numa_nodes;
2337 nodenr = strtoull(option, NULL, 10);
2340 if (get_param_value(option, 128, "mem", optarg) == 0) {
2341 node_mem[nodenr] = 0;
2343 value = strtoull(option, &endptr, 0);
2345 case 0: case 'M': case 'm':
2352 node_mem[nodenr] = value;
2354 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2355 node_cpumask[nodenr] = 0;
2357 value = strtoull(option, &endptr, 10);
2360 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2362 if (*endptr == '-') {
2363 endvalue = strtoull(endptr+1, &endptr, 10);
2364 if (endvalue >= 63) {
2367 "only 63 CPUs in NUMA mode supported.\n");
2369 value = (1 << (endvalue + 1)) - (1 << value);
2374 node_cpumask[nodenr] = value;
2381 static void smp_parse(const char *optarg)
2383 int smp, sockets = 0, threads = 0, cores = 0;
2387 smp = strtoul(optarg, &endptr, 10);
2388 if (endptr != optarg) {
2389 if (*endptr == ',') {
2393 if (get_param_value(option, 128, "sockets", endptr) != 0)
2394 sockets = strtoull(option, NULL, 10);
2395 if (get_param_value(option, 128, "cores", endptr) != 0)
2396 cores = strtoull(option, NULL, 10);
2397 if (get_param_value(option, 128, "threads", endptr) != 0)
2398 threads = strtoull(option, NULL, 10);
2399 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2400 max_cpus = strtoull(option, NULL, 10);
2402 /* compute missing values, prefer sockets over cores over threads */
2403 if (smp == 0 || sockets == 0) {
2404 sockets = sockets > 0 ? sockets : 1;
2405 cores = cores > 0 ? cores : 1;
2406 threads = threads > 0 ? threads : 1;
2408 smp = cores * threads * sockets;
2410 sockets = smp / (cores * threads);
2414 threads = threads > 0 ? threads : 1;
2415 cores = smp / (sockets * threads);
2418 sockets = smp / (cores * threads);
2420 threads = smp / (cores * sockets);
2425 smp_cores = cores > 0 ? cores : 1;
2426 smp_threads = threads > 0 ? threads : 1;
2428 max_cpus = smp_cpus;
2431 /***********************************************************/
2434 static USBPort *used_usb_ports;
2435 static USBPort *free_usb_ports;
2437 /* ??? Maybe change this to register a hub to keep track of the topology. */
2438 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2439 usb_attachfn attach)
2441 port->opaque = opaque;
2442 port->index = index;
2443 port->attach = attach;
2444 port->next = free_usb_ports;
2445 free_usb_ports = port;
2448 int usb_device_add_dev(USBDevice *dev)
2452 /* Find a USB port to add the device to. */
2453 port = free_usb_ports;
2457 /* Create a new hub and chain it on. */
2458 free_usb_ports = NULL;
2459 port->next = used_usb_ports;
2460 used_usb_ports = port;
2462 hub = usb_hub_init(VM_USB_HUB_SIZE);
2463 usb_attach(port, hub);
2464 port = free_usb_ports;
2467 free_usb_ports = port->next;
2468 port->next = used_usb_ports;
2469 used_usb_ports = port;
2470 usb_attach(port, dev);
2474 static void usb_msd_password_cb(void *opaque, int err)
2476 USBDevice *dev = opaque;
2479 usb_device_add_dev(dev);
2481 dev->handle_destroy(dev);
2484 static int usb_device_add(const char *devname, int is_hotplug)
2489 if (!free_usb_ports)
2492 if (strstart(devname, "host:", &p)) {
2493 dev = usb_host_device_open(p);
2494 } else if (!strcmp(devname, "mouse")) {
2495 dev = usb_mouse_init();
2496 } else if (!strcmp(devname, "tablet")) {
2497 dev = usb_tablet_init();
2498 } else if (!strcmp(devname, "keyboard")) {
2499 dev = usb_keyboard_init();
2500 } else if (strstart(devname, "disk:", &p)) {
2501 BlockDriverState *bs;
2503 dev = usb_msd_init(p);
2506 bs = usb_msd_get_bdrv(dev);
2507 if (bdrv_key_required(bs)) {
2510 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2515 } else if (!strcmp(devname, "wacom-tablet")) {
2516 dev = usb_wacom_init();
2517 } else if (strstart(devname, "serial:", &p)) {
2518 dev = usb_serial_init(p);
2519 #ifdef CONFIG_BRLAPI
2520 } else if (!strcmp(devname, "braille")) {
2521 dev = usb_baum_init();
2523 } else if (strstart(devname, "net:", &p)) {
2526 if (net_client_init(NULL, "nic", p) < 0)
2528 nd_table[nic].model = "usb";
2529 dev = usb_net_init(&nd_table[nic]);
2530 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2531 dev = usb_bt_init(devname[2] ? hci_init(p) :
2532 bt_new_hci(qemu_find_bt_vlan(0)));
2539 return usb_device_add_dev(dev);
2542 int usb_device_del_addr(int bus_num, int addr)
2548 if (!used_usb_ports)
2554 lastp = &used_usb_ports;
2555 port = used_usb_ports;
2556 while (port && port->dev->addr != addr) {
2557 lastp = &port->next;
2565 *lastp = port->next;
2566 usb_attach(port, NULL);
2567 dev->handle_destroy(dev);
2568 port->next = free_usb_ports;
2569 free_usb_ports = port;
2573 static int usb_device_del(const char *devname)
2578 if (strstart(devname, "host:", &p))
2579 return usb_host_device_close(p);
2581 if (!used_usb_ports)
2584 p = strchr(devname, '.');
2587 bus_num = strtoul(devname, NULL, 0);
2588 addr = strtoul(p + 1, NULL, 0);
2590 return usb_device_del_addr(bus_num, addr);
2593 static int usb_parse(const char *cmdline)
2595 return usb_device_add(cmdline, 0);
2598 void do_usb_add(Monitor *mon, const char *devname)
2600 usb_device_add(devname, 1);
2603 void do_usb_del(Monitor *mon, const char *devname)
2605 usb_device_del(devname);
2608 void usb_info(Monitor *mon)
2612 const char *speed_str;
2615 monitor_printf(mon, "USB support not enabled\n");
2619 for (port = used_usb_ports; port; port = port->next) {
2623 switch(dev->speed) {
2627 case USB_SPEED_FULL:
2630 case USB_SPEED_HIGH:
2637 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2638 0, dev->addr, speed_str, dev->devname);
2642 /***********************************************************/
2643 /* PCMCIA/Cardbus */
2645 static struct pcmcia_socket_entry_s {
2646 PCMCIASocket *socket;
2647 struct pcmcia_socket_entry_s *next;
2648 } *pcmcia_sockets = 0;
2650 void pcmcia_socket_register(PCMCIASocket *socket)
2652 struct pcmcia_socket_entry_s *entry;
2654 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2655 entry->socket = socket;
2656 entry->next = pcmcia_sockets;
2657 pcmcia_sockets = entry;
2660 void pcmcia_socket_unregister(PCMCIASocket *socket)
2662 struct pcmcia_socket_entry_s *entry, **ptr;
2664 ptr = &pcmcia_sockets;
2665 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2666 if (entry->socket == socket) {
2672 void pcmcia_info(Monitor *mon)
2674 struct pcmcia_socket_entry_s *iter;
2676 if (!pcmcia_sockets)
2677 monitor_printf(mon, "No PCMCIA sockets\n");
2679 for (iter = pcmcia_sockets; iter; iter = iter->next)
2680 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2681 iter->socket->attached ? iter->socket->card_string :
2685 /***********************************************************/
2686 /* register display */
2688 struct DisplayAllocator default_allocator = {
2689 defaultallocator_create_displaysurface,
2690 defaultallocator_resize_displaysurface,
2691 defaultallocator_free_displaysurface
2694 void register_displaystate(DisplayState *ds)
2704 DisplayState *get_displaystate(void)
2706 return display_state;
2709 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2711 if(ds->allocator == &default_allocator) ds->allocator = da;
2712 return ds->allocator;
2717 static void dumb_display_init(void)
2719 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2720 ds->allocator = &default_allocator;
2721 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2722 register_displaystate(ds);
2725 /***********************************************************/
2728 typedef struct IOHandlerRecord {
2730 IOCanRWHandler *fd_read_poll;
2732 IOHandler *fd_write;
2735 /* temporary data */
2737 struct IOHandlerRecord *next;
2740 static IOHandlerRecord *first_io_handler;
2742 /* XXX: fd_read_poll should be suppressed, but an API change is
2743 necessary in the character devices to suppress fd_can_read(). */
2744 int qemu_set_fd_handler2(int fd,
2745 IOCanRWHandler *fd_read_poll,
2747 IOHandler *fd_write,
2750 IOHandlerRecord **pioh, *ioh;
2752 if (!fd_read && !fd_write) {
2753 pioh = &first_io_handler;
2758 if (ioh->fd == fd) {
2765 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2769 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2770 ioh->next = first_io_handler;
2771 first_io_handler = ioh;
2774 ioh->fd_read_poll = fd_read_poll;
2775 ioh->fd_read = fd_read;
2776 ioh->fd_write = fd_write;
2777 ioh->opaque = opaque;
2783 int qemu_set_fd_handler(int fd,
2785 IOHandler *fd_write,
2788 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2792 /***********************************************************/
2793 /* Polling handling */
2795 typedef struct PollingEntry {
2798 struct PollingEntry *next;
2801 static PollingEntry *first_polling_entry;
2803 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2805 PollingEntry **ppe, *pe;
2806 pe = qemu_mallocz(sizeof(PollingEntry));
2808 pe->opaque = opaque;
2809 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2814 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2816 PollingEntry **ppe, *pe;
2817 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2819 if (pe->func == func && pe->opaque == opaque) {
2827 /***********************************************************/
2828 /* Wait objects support */
2829 typedef struct WaitObjects {
2831 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2832 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2833 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2836 static WaitObjects wait_objects = {0};
2838 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2840 WaitObjects *w = &wait_objects;
2842 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2844 w->events[w->num] = handle;
2845 w->func[w->num] = func;
2846 w->opaque[w->num] = opaque;
2851 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2854 WaitObjects *w = &wait_objects;
2857 for (i = 0; i < w->num; i++) {
2858 if (w->events[i] == handle)
2861 w->events[i] = w->events[i + 1];
2862 w->func[i] = w->func[i + 1];
2863 w->opaque[i] = w->opaque[i + 1];
2871 /***********************************************************/
2872 /* ram save/restore */
2874 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2878 v = qemu_get_byte(f);
2881 if (qemu_get_buffer(f, buf, len) != len)
2885 v = qemu_get_byte(f);
2886 memset(buf, v, len);
2892 if (qemu_file_has_error(f))
2898 static int ram_load_v1(QEMUFile *f, void *opaque)
2903 if (qemu_get_be32(f) != last_ram_offset)
2905 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2906 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2913 #define BDRV_HASH_BLOCK_SIZE 1024
2914 #define IOBUF_SIZE 4096
2915 #define RAM_CBLOCK_MAGIC 0xfabe
2917 typedef struct RamDecompressState {
2920 uint8_t buf[IOBUF_SIZE];
2921 } RamDecompressState;
2923 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2926 memset(s, 0, sizeof(*s));
2928 ret = inflateInit(&s->zstream);
2934 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2938 s->zstream.avail_out = len;
2939 s->zstream.next_out = buf;
2940 while (s->zstream.avail_out > 0) {
2941 if (s->zstream.avail_in == 0) {
2942 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
2944 clen = qemu_get_be16(s->f);
2945 if (clen > IOBUF_SIZE)
2947 qemu_get_buffer(s->f, s->buf, clen);
2948 s->zstream.avail_in = clen;
2949 s->zstream.next_in = s->buf;
2951 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
2952 if (ret != Z_OK && ret != Z_STREAM_END) {
2959 static void ram_decompress_close(RamDecompressState *s)
2961 inflateEnd(&s->zstream);
2964 #define RAM_SAVE_FLAG_FULL 0x01
2965 #define RAM_SAVE_FLAG_COMPRESS 0x02
2966 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2967 #define RAM_SAVE_FLAG_PAGE 0x08
2968 #define RAM_SAVE_FLAG_EOS 0x10
2970 static int is_dup_page(uint8_t *page, uint8_t ch)
2972 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2973 uint32_t *array = (uint32_t *)page;
2976 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2977 if (array[i] != val)
2984 static int ram_save_block(QEMUFile *f)
2986 static ram_addr_t current_addr = 0;
2987 ram_addr_t saved_addr = current_addr;
2988 ram_addr_t addr = 0;
2991 while (addr < last_ram_offset) {
2992 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2995 cpu_physical_memory_reset_dirty(current_addr,
2996 current_addr + TARGET_PAGE_SIZE,
2997 MIGRATION_DIRTY_FLAG);
2999 p = qemu_get_ram_ptr(current_addr);
3001 if (is_dup_page(p, *p)) {
3002 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3003 qemu_put_byte(f, *p);
3005 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3006 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3012 addr += TARGET_PAGE_SIZE;
3013 current_addr = (saved_addr + addr) % last_ram_offset;
3019 static uint64_t bytes_transferred = 0;
3021 static ram_addr_t ram_save_remaining(void)
3024 ram_addr_t count = 0;
3026 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3027 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3034 uint64_t ram_bytes_remaining(void)
3036 return ram_save_remaining() * TARGET_PAGE_SIZE;
3039 uint64_t ram_bytes_transferred(void)
3041 return bytes_transferred;
3044 uint64_t ram_bytes_total(void)
3046 return last_ram_offset;
3049 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3052 uint64_t bytes_transferred_last;
3054 uint64_t expected_time = 0;
3056 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3057 qemu_file_set_error(f);
3062 /* Make sure all dirty bits are set */
3063 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3064 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3065 cpu_physical_memory_set_dirty(addr);
3068 /* Enable dirty memory tracking */
3069 cpu_physical_memory_set_dirty_tracking(1);
3071 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3074 bytes_transferred_last = bytes_transferred;
3075 bwidth = get_clock();
3077 while (!qemu_file_rate_limit(f)) {
3080 ret = ram_save_block(f);
3081 bytes_transferred += ret * TARGET_PAGE_SIZE;
3082 if (ret == 0) /* no more blocks */
3086 bwidth = get_clock() - bwidth;
3087 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3089 /* if we haven't transferred anything this round, force expected_time to a
3090 * a very high value, but without crashing */
3094 /* try transferring iterative blocks of memory */
3098 /* flush all remaining blocks regardless of rate limiting */
3099 while (ram_save_block(f) != 0) {
3100 bytes_transferred += TARGET_PAGE_SIZE;
3102 cpu_physical_memory_set_dirty_tracking(0);
3105 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3107 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3109 return (stage == 2) && (expected_time <= migrate_max_downtime());
3112 static int ram_load_dead(QEMUFile *f, void *opaque)
3114 RamDecompressState s1, *s = &s1;
3118 if (ram_decompress_open(s, f) < 0)
3120 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3121 if (ram_decompress_buf(s, buf, 1) < 0) {
3122 fprintf(stderr, "Error while reading ram block header\n");
3126 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3127 BDRV_HASH_BLOCK_SIZE) < 0) {
3128 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3133 printf("Error block header\n");
3137 ram_decompress_close(s);
3142 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3147 if (version_id == 1)
3148 return ram_load_v1(f, opaque);
3150 if (version_id == 2) {
3151 if (qemu_get_be32(f) != last_ram_offset)
3153 return ram_load_dead(f, opaque);
3156 if (version_id != 3)
3160 addr = qemu_get_be64(f);
3162 flags = addr & ~TARGET_PAGE_MASK;
3163 addr &= TARGET_PAGE_MASK;
3165 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3166 if (addr != last_ram_offset)
3170 if (flags & RAM_SAVE_FLAG_FULL) {
3171 if (ram_load_dead(f, opaque) < 0)
3175 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3176 uint8_t ch = qemu_get_byte(f);
3177 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3180 (!kvm_enabled() || kvm_has_sync_mmu())) {
3181 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3184 } else if (flags & RAM_SAVE_FLAG_PAGE)
3185 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3186 } while (!(flags & RAM_SAVE_FLAG_EOS));
3191 void qemu_service_io(void)
3193 qemu_notify_event();
3196 /***********************************************************/
3197 /* bottom halves (can be seen as timers which expire ASAP) */
3208 static QEMUBH *first_bh = NULL;
3210 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3213 bh = qemu_mallocz(sizeof(QEMUBH));
3215 bh->opaque = opaque;
3216 bh->next = first_bh;
3221 int qemu_bh_poll(void)
3227 for (bh = first_bh; bh; bh = bh->next) {
3228 if (!bh->deleted && bh->scheduled) {
3237 /* remove deleted bhs */
3251 void qemu_bh_schedule_idle(QEMUBH *bh)
3259 void qemu_bh_schedule(QEMUBH *bh)
3265 /* stop the currently executing CPU to execute the BH ASAP */
3266 qemu_notify_event();
3269 void qemu_bh_cancel(QEMUBH *bh)
3274 void qemu_bh_delete(QEMUBH *bh)
3280 static void qemu_bh_update_timeout(int *timeout)
3284 for (bh = first_bh; bh; bh = bh->next) {
3285 if (!bh->deleted && bh->scheduled) {
3287 /* idle bottom halves will be polled at least
3289 *timeout = MIN(10, *timeout);
3291 /* non-idle bottom halves will be executed
3300 /***********************************************************/
3301 /* machine registration */
3303 static QEMUMachine *first_machine = NULL;
3304 QEMUMachine *current_machine = NULL;
3306 int qemu_register_machine(QEMUMachine *m)
3309 pm = &first_machine;
3317 static QEMUMachine *find_machine(const char *name)
3321 for(m = first_machine; m != NULL; m = m->next) {
3322 if (!strcmp(m->name, name))
3324 if (m->alias && !strcmp(m->alias, name))
3330 static QEMUMachine *find_default_machine(void)
3334 for(m = first_machine; m != NULL; m = m->next) {
3335 if (m->is_default) {
3342 /***********************************************************/
3343 /* main execution loop */
3345 static void gui_update(void *opaque)
3347 uint64_t interval = GUI_REFRESH_INTERVAL;
3348 DisplayState *ds = opaque;
3349 DisplayChangeListener *dcl = ds->listeners;
3353 while (dcl != NULL) {
3354 if (dcl->gui_timer_interval &&
3355 dcl->gui_timer_interval < interval)
3356 interval = dcl->gui_timer_interval;
3359 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3362 static void nographic_update(void *opaque)
3364 uint64_t interval = GUI_REFRESH_INTERVAL;
3366 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3369 struct vm_change_state_entry {
3370 VMChangeStateHandler *cb;
3372 LIST_ENTRY (vm_change_state_entry) entries;
3375 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3377 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3380 VMChangeStateEntry *e;
3382 e = qemu_mallocz(sizeof (*e));
3386 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3390 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3392 LIST_REMOVE (e, entries);
3396 static void vm_state_notify(int running, int reason)
3398 VMChangeStateEntry *e;
3400 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3401 e->cb(e->opaque, running, reason);
3405 static void resume_all_vcpus(void);
3406 static void pause_all_vcpus(void);
3413 vm_state_notify(1, 0);
3414 qemu_rearm_alarm_timer(alarm_timer);
3419 /* reset/shutdown handler */
3421 typedef struct QEMUResetEntry {
3422 TAILQ_ENTRY(QEMUResetEntry) entry;
3423 QEMUResetHandler *func;
3427 static TAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3428 TAILQ_HEAD_INITIALIZER(reset_handlers);
3429 static int reset_requested;
3430 static int shutdown_requested;
3431 static int powerdown_requested;
3432 static int debug_requested;
3433 static int vmstop_requested;
3435 int qemu_shutdown_requested(void)
3437 int r = shutdown_requested;
3438 shutdown_requested = 0;
3442 int qemu_reset_requested(void)
3444 int r = reset_requested;
3445 reset_requested = 0;
3449 int qemu_powerdown_requested(void)
3451 int r = powerdown_requested;
3452 powerdown_requested = 0;
3456 static int qemu_debug_requested(void)
3458 int r = debug_requested;
3459 debug_requested = 0;
3463 static int qemu_vmstop_requested(void)
3465 int r = vmstop_requested;
3466 vmstop_requested = 0;
3470 static void do_vm_stop(int reason)
3473 cpu_disable_ticks();
3476 vm_state_notify(0, reason);
3480 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3482 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3485 re->opaque = opaque;
3486 TAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3489 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3493 TAILQ_FOREACH(re, &reset_handlers, entry) {
3494 if (re->func == func && re->opaque == opaque) {
3495 TAILQ_REMOVE(&reset_handlers, re, entry);
3502 void qemu_system_reset(void)
3504 QEMUResetEntry *re, *nre;
3506 /* reset all devices */
3507 TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3508 re->func(re->opaque);
3512 void qemu_system_reset_request(void)
3515 shutdown_requested = 1;
3517 reset_requested = 1;
3519 qemu_notify_event();
3522 void qemu_system_shutdown_request(void)
3524 shutdown_requested = 1;
3525 qemu_notify_event();
3528 void qemu_system_powerdown_request(void)
3530 powerdown_requested = 1;
3531 qemu_notify_event();
3534 #ifdef CONFIG_IOTHREAD
3535 static void qemu_system_vmstop_request(int reason)
3537 vmstop_requested = reason;
3538 qemu_notify_event();
3543 static int io_thread_fd = -1;
3545 static void qemu_event_increment(void)
3547 static const char byte = 0;
3549 if (io_thread_fd == -1)
3552 write(io_thread_fd, &byte, sizeof(byte));
3555 static void qemu_event_read(void *opaque)
3557 int fd = (unsigned long)opaque;
3560 /* Drain the notify pipe */
3563 len = read(fd, buffer, sizeof(buffer));
3564 } while ((len == -1 && errno == EINTR) || len > 0);
3567 static int qemu_event_init(void)
3576 err = fcntl_setfl(fds[0], O_NONBLOCK);
3580 err = fcntl_setfl(fds[1], O_NONBLOCK);
3584 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3585 (void *)(unsigned long)fds[0]);
3587 io_thread_fd = fds[1];
3596 HANDLE qemu_event_handle;
3598 static void dummy_event_handler(void *opaque)
3602 static int qemu_event_init(void)
3604 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3605 if (!qemu_event_handle) {
3606 perror("Failed CreateEvent");
3609 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3613 static void qemu_event_increment(void)
3615 SetEvent(qemu_event_handle);
3619 static int cpu_can_run(CPUState *env)
3628 #ifndef CONFIG_IOTHREAD
3629 static int qemu_init_main_loop(void)
3631 return qemu_event_init();
3634 void qemu_init_vcpu(void *_env)
3636 CPUState *env = _env;
3640 env->nr_cores = smp_cores;
3641 env->nr_threads = smp_threads;
3645 int qemu_cpu_self(void *env)
3650 static void resume_all_vcpus(void)
3654 static void pause_all_vcpus(void)
3658 void qemu_cpu_kick(void *env)
3663 void qemu_notify_event(void)
3665 CPUState *env = cpu_single_env;
3672 #define qemu_mutex_lock_iothread() do { } while (0)
3673 #define qemu_mutex_unlock_iothread() do { } while (0)
3675 void vm_stop(int reason)
3680 #else /* CONFIG_IOTHREAD */
3682 #include "qemu-thread.h"
3684 QemuMutex qemu_global_mutex;
3685 static QemuMutex qemu_fair_mutex;
3687 static QemuThread io_thread;
3689 static QemuThread *tcg_cpu_thread;
3690 static QemuCond *tcg_halt_cond;
3692 static int qemu_system_ready;
3694 static QemuCond qemu_cpu_cond;
3696 static QemuCond qemu_system_cond;
3697 static QemuCond qemu_pause_cond;
3699 static void block_io_signals(void);
3700 static void unblock_io_signals(void);
3701 static int tcg_has_work(void);
3703 static int qemu_init_main_loop(void)
3707 ret = qemu_event_init();
3711 qemu_cond_init(&qemu_pause_cond);
3712 qemu_mutex_init(&qemu_fair_mutex);
3713 qemu_mutex_init(&qemu_global_mutex);
3714 qemu_mutex_lock(&qemu_global_mutex);
3716 unblock_io_signals();
3717 qemu_thread_self(&io_thread);
3722 static void qemu_wait_io_event(CPUState *env)
3724 while (!tcg_has_work())
3725 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3727 qemu_mutex_unlock(&qemu_global_mutex);
3730 * Users of qemu_global_mutex can be starved, having no chance
3731 * to acquire it since this path will get to it first.
3732 * So use another lock to provide fairness.
3734 qemu_mutex_lock(&qemu_fair_mutex);
3735 qemu_mutex_unlock(&qemu_fair_mutex);
3737 qemu_mutex_lock(&qemu_global_mutex);
3741 qemu_cond_signal(&qemu_pause_cond);
3745 static int qemu_cpu_exec(CPUState *env);
3747 static void *kvm_cpu_thread_fn(void *arg)
3749 CPUState *env = arg;
3752 qemu_thread_self(env->thread);
3754 /* signal CPU creation */
3755 qemu_mutex_lock(&qemu_global_mutex);
3757 qemu_cond_signal(&qemu_cpu_cond);
3759 /* and wait for machine initialization */
3760 while (!qemu_system_ready)
3761 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3764 if (cpu_can_run(env))
3766 qemu_wait_io_event(env);
3772 static void tcg_cpu_exec(void);
3774 static void *tcg_cpu_thread_fn(void *arg)
3776 CPUState *env = arg;
3779 qemu_thread_self(env->thread);
3781 /* signal CPU creation */
3782 qemu_mutex_lock(&qemu_global_mutex);
3783 for (env = first_cpu; env != NULL; env = env->next_cpu)
3785 qemu_cond_signal(&qemu_cpu_cond);
3787 /* and wait for machine initialization */
3788 while (!qemu_system_ready)
3789 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3793 qemu_wait_io_event(cur_cpu);
3799 void qemu_cpu_kick(void *_env)
3801 CPUState *env = _env;
3802 qemu_cond_broadcast(env->halt_cond);
3804 qemu_thread_signal(env->thread, SIGUSR1);
3807 int qemu_cpu_self(void *env)
3809 return (cpu_single_env != NULL);
3812 static void cpu_signal(int sig)
3815 cpu_exit(cpu_single_env);
3818 static void block_io_signals(void)
3821 struct sigaction sigact;
3824 sigaddset(&set, SIGUSR2);
3825 sigaddset(&set, SIGIO);
3826 sigaddset(&set, SIGALRM);
3827 pthread_sigmask(SIG_BLOCK, &set, NULL);
3830 sigaddset(&set, SIGUSR1);
3831 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3833 memset(&sigact, 0, sizeof(sigact));
3834 sigact.sa_handler = cpu_signal;
3835 sigaction(SIGUSR1, &sigact, NULL);
3838 static void unblock_io_signals(void)
3843 sigaddset(&set, SIGUSR2);
3844 sigaddset(&set, SIGIO);
3845 sigaddset(&set, SIGALRM);
3846 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3849 sigaddset(&set, SIGUSR1);
3850 pthread_sigmask(SIG_BLOCK, &set, NULL);
3853 static void qemu_signal_lock(unsigned int msecs)
3855 qemu_mutex_lock(&qemu_fair_mutex);
3857 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3858 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3859 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3862 qemu_mutex_unlock(&qemu_fair_mutex);
3865 static void qemu_mutex_lock_iothread(void)
3867 if (kvm_enabled()) {
3868 qemu_mutex_lock(&qemu_fair_mutex);
3869 qemu_mutex_lock(&qemu_global_mutex);
3870 qemu_mutex_unlock(&qemu_fair_mutex);
3872 qemu_signal_lock(100);
3875 static void qemu_mutex_unlock_iothread(void)
3877 qemu_mutex_unlock(&qemu_global_mutex);
3880 static int all_vcpus_paused(void)
3882 CPUState *penv = first_cpu;
3887 penv = (CPUState *)penv->next_cpu;
3893 static void pause_all_vcpus(void)
3895 CPUState *penv = first_cpu;
3899 qemu_thread_signal(penv->thread, SIGUSR1);
3900 qemu_cpu_kick(penv);
3901 penv = (CPUState *)penv->next_cpu;
3904 while (!all_vcpus_paused()) {
3905 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3908 qemu_thread_signal(penv->thread, SIGUSR1);
3909 penv = (CPUState *)penv->next_cpu;
3914 static void resume_all_vcpus(void)
3916 CPUState *penv = first_cpu;
3921 qemu_thread_signal(penv->thread, SIGUSR1);
3922 qemu_cpu_kick(penv);
3923 penv = (CPUState *)penv->next_cpu;
3927 static void tcg_init_vcpu(void *_env)
3929 CPUState *env = _env;
3930 /* share a single thread for all cpus with TCG */
3931 if (!tcg_cpu_thread) {
3932 env->thread = qemu_mallocz(sizeof(QemuThread));
3933 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3934 qemu_cond_init(env->halt_cond);
3935 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3936 while (env->created == 0)
3937 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3938 tcg_cpu_thread = env->thread;
3939 tcg_halt_cond = env->halt_cond;
3941 env->thread = tcg_cpu_thread;
3942 env->halt_cond = tcg_halt_cond;
3946 static void kvm_start_vcpu(CPUState *env)
3949 env->thread = qemu_mallocz(sizeof(QemuThread));
3950 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3951 qemu_cond_init(env->halt_cond);
3952 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3953 while (env->created == 0)
3954 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3957 void qemu_init_vcpu(void *_env)
3959 CPUState *env = _env;
3962 kvm_start_vcpu(env);
3965 env->nr_cores = smp_cores;
3966 env->nr_threads = smp_threads;
3969 void qemu_notify_event(void)
3971 qemu_event_increment();
3974 void vm_stop(int reason)
3977 qemu_thread_self(&me);
3979 if (!qemu_thread_equal(&me, &io_thread)) {
3980 qemu_system_vmstop_request(reason);
3982 * FIXME: should not return to device code in case
3983 * vm_stop() has been requested.
3985 if (cpu_single_env) {
3986 cpu_exit(cpu_single_env);
3987 cpu_single_env->stop = 1;
3998 static void host_main_loop_wait(int *timeout)
4004 /* XXX: need to suppress polling by better using win32 events */
4006 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4007 ret |= pe->func(pe->opaque);
4011 WaitObjects *w = &wait_objects;
4013 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4014 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4015 if (w->func[ret - WAIT_OBJECT_0])
4016 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4018 /* Check for additional signaled events */
4019 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4021 /* Check if event is signaled */
4022 ret2 = WaitForSingleObject(w->events[i], 0);
4023 if(ret2 == WAIT_OBJECT_0) {
4025 w->func[i](w->opaque[i]);
4026 } else if (ret2 == WAIT_TIMEOUT) {
4028 err = GetLastError();
4029 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4032 } else if (ret == WAIT_TIMEOUT) {
4034 err = GetLastError();
4035 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4042 static void host_main_loop_wait(int *timeout)
4047 void main_loop_wait(int timeout)
4049 IOHandlerRecord *ioh;
4050 fd_set rfds, wfds, xfds;
4054 qemu_bh_update_timeout(&timeout);
4056 host_main_loop_wait(&timeout);
4058 /* poll any events */
4059 /* XXX: separate device handlers from system ones */
4064 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4068 (!ioh->fd_read_poll ||
4069 ioh->fd_read_poll(ioh->opaque) != 0)) {
4070 FD_SET(ioh->fd, &rfds);
4074 if (ioh->fd_write) {
4075 FD_SET(ioh->fd, &wfds);
4081 tv.tv_sec = timeout / 1000;
4082 tv.tv_usec = (timeout % 1000) * 1000;
4084 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4086 qemu_mutex_unlock_iothread();
4087 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4088 qemu_mutex_lock_iothread();
4090 IOHandlerRecord **pioh;
4092 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4093 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4094 ioh->fd_read(ioh->opaque);
4096 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4097 ioh->fd_write(ioh->opaque);
4101 /* remove deleted IO handlers */
4102 pioh = &first_io_handler;
4113 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4115 /* rearm timer, if not periodic */
4116 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4117 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4118 qemu_rearm_alarm_timer(alarm_timer);
4121 /* vm time timers */
4123 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4124 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4125 qemu_get_clock(vm_clock));
4128 /* real time timers */
4129 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4130 qemu_get_clock(rt_clock));
4132 /* Check bottom-halves last in case any of the earlier events triggered
4138 static int qemu_cpu_exec(CPUState *env)
4141 #ifdef CONFIG_PROFILER
4145 #ifdef CONFIG_PROFILER
4146 ti = profile_getclock();
4151 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4152 env->icount_decr.u16.low = 0;
4153 env->icount_extra = 0;
4154 count = qemu_next_deadline();
4155 count = (count + (1 << icount_time_shift) - 1)
4156 >> icount_time_shift;
4157 qemu_icount += count;
4158 decr = (count > 0xffff) ? 0xffff : count;
4160 env->icount_decr.u16.low = decr;
4161 env->icount_extra = count;
4163 ret = cpu_exec(env);
4164 #ifdef CONFIG_PROFILER
4165 qemu_time += profile_getclock() - ti;
4168 /* Fold pending instructions back into the
4169 instruction counter, and clear the interrupt flag. */
4170 qemu_icount -= (env->icount_decr.u16.low
4171 + env->icount_extra);
4172 env->icount_decr.u32 = 0;
4173 env->icount_extra = 0;
4178 static void tcg_cpu_exec(void)
4182 if (next_cpu == NULL)
4183 next_cpu = first_cpu;
4184 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4185 CPUState *env = cur_cpu = next_cpu;
4189 if (timer_alarm_pending) {
4190 timer_alarm_pending = 0;
4193 if (cpu_can_run(env))
4194 ret = qemu_cpu_exec(env);
4195 if (ret == EXCP_DEBUG) {
4196 gdb_set_stop_cpu(env);
4197 debug_requested = 1;
4203 static int cpu_has_work(CPUState *env)
4211 if (qemu_cpu_has_work(env))
4216 static int tcg_has_work(void)
4220 for (env = first_cpu; env != NULL; env = env->next_cpu)
4221 if (cpu_has_work(env))
4226 static int qemu_calculate_timeout(void)
4228 #ifndef CONFIG_IOTHREAD
4233 else if (tcg_has_work())
4235 else if (!use_icount)
4238 /* XXX: use timeout computed from timers */
4241 /* Advance virtual time to the next event. */
4242 if (use_icount == 1) {
4243 /* When not using an adaptive execution frequency
4244 we tend to get badly out of sync with real time,
4245 so just delay for a reasonable amount of time. */
4248 delta = cpu_get_icount() - cpu_get_clock();
4251 /* If virtual time is ahead of real time then just
4253 timeout = (delta / 1000000) + 1;
4255 /* Wait for either IO to occur or the next
4257 add = qemu_next_deadline();
4258 /* We advance the timer before checking for IO.
4259 Limit the amount we advance so that early IO
4260 activity won't get the guest too far ahead. */
4264 add = (add + (1 << icount_time_shift) - 1)
4265 >> icount_time_shift;
4267 timeout = delta / 1000000;
4274 #else /* CONFIG_IOTHREAD */
4279 static int vm_can_run(void)
4281 if (powerdown_requested)
4283 if (reset_requested)
4285 if (shutdown_requested)
4287 if (debug_requested)
4292 qemu_irq qemu_system_powerdown;
4294 static void main_loop(void)
4298 #ifdef CONFIG_IOTHREAD
4299 qemu_system_ready = 1;
4300 qemu_cond_broadcast(&qemu_system_cond);
4305 #ifdef CONFIG_PROFILER
4308 #ifndef CONFIG_IOTHREAD
4311 #ifdef CONFIG_PROFILER
4312 ti = profile_getclock();
4314 main_loop_wait(qemu_calculate_timeout());
4315 #ifdef CONFIG_PROFILER
4316 dev_time += profile_getclock() - ti;
4318 } while (vm_can_run());
4320 if (qemu_debug_requested())
4321 vm_stop(EXCP_DEBUG);
4322 if (qemu_shutdown_requested()) {
4329 if (qemu_reset_requested()) {
4331 qemu_system_reset();
4334 if (qemu_powerdown_requested()) {
4335 qemu_irq_raise(qemu_system_powerdown);
4337 if ((r = qemu_vmstop_requested()))
4343 static void version(void)
4345 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4348 static void help(int exitcode)
4351 printf("usage: %s [options] [disk_image]\n"
4353 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4355 #define DEF(option, opt_arg, opt_enum, opt_help) \
4357 #define DEFHEADING(text) stringify(text) "\n"
4358 #include "qemu-options.h"
4363 "During emulation, the following keys are useful:\n"
4364 "ctrl-alt-f toggle full screen\n"
4365 "ctrl-alt-n switch to virtual console 'n'\n"
4366 "ctrl-alt toggle mouse and keyboard grab\n"
4368 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4373 DEFAULT_NETWORK_SCRIPT,
4374 DEFAULT_NETWORK_DOWN_SCRIPT,
4376 DEFAULT_GDBSTUB_PORT,
4381 #define HAS_ARG 0x0001
4384 #define DEF(option, opt_arg, opt_enum, opt_help) \
4386 #define DEFHEADING(text)
4387 #include "qemu-options.h"
4393 typedef struct QEMUOption {
4399 static const QEMUOption qemu_options[] = {
4400 { "h", 0, QEMU_OPTION_h },
4401 #define DEF(option, opt_arg, opt_enum, opt_help) \
4402 { option, opt_arg, opt_enum },
4403 #define DEFHEADING(text)
4404 #include "qemu-options.h"
4412 struct soundhw soundhw[] = {
4413 #ifdef HAS_AUDIO_CHOICE
4414 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4420 { .init_isa = pcspk_audio_init }
4427 "Creative Sound Blaster 16",
4430 { .init_isa = SB16_init }
4434 #ifdef CONFIG_CS4231A
4440 { .init_isa = cs4231a_init }
4448 "Yamaha YMF262 (OPL3)",
4450 "Yamaha YM3812 (OPL2)",
4454 { .init_isa = Adlib_init }
4461 "Gravis Ultrasound GF1",
4464 { .init_isa = GUS_init }
4471 "Intel 82801AA AC97 Audio",
4474 { .init_pci = ac97_init }
4478 #ifdef CONFIG_ES1370
4481 "ENSONIQ AudioPCI ES1370",
4484 { .init_pci = es1370_init }
4488 #endif /* HAS_AUDIO_CHOICE */
4490 { NULL, NULL, 0, 0, { NULL } }
4493 static void select_soundhw (const char *optarg)
4497 if (*optarg == '?') {
4500 printf ("Valid sound card names (comma separated):\n");
4501 for (c = soundhw; c->name; ++c) {
4502 printf ("%-11s %s\n", c->name, c->descr);
4504 printf ("\n-soundhw all will enable all of the above\n");
4505 exit (*optarg != '?');
4513 if (!strcmp (optarg, "all")) {
4514 for (c = soundhw; c->name; ++c) {
4522 e = strchr (p, ',');
4523 l = !e ? strlen (p) : (size_t) (e - p);
4525 for (c = soundhw; c->name; ++c) {
4526 if (!strncmp (c->name, p, l)) {
4535 "Unknown sound card name (too big to show)\n");
4538 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4543 p += l + (e != NULL);
4547 goto show_valid_cards;
4552 static void select_vgahw (const char *p)
4556 vga_interface_type = VGA_NONE;
4557 if (strstart(p, "std", &opts)) {
4558 vga_interface_type = VGA_STD;
4559 } else if (strstart(p, "cirrus", &opts)) {
4560 vga_interface_type = VGA_CIRRUS;
4561 } else if (strstart(p, "vmware", &opts)) {
4562 vga_interface_type = VGA_VMWARE;
4563 } else if (strstart(p, "xenfb", &opts)) {
4564 vga_interface_type = VGA_XENFB;
4565 } else if (!strstart(p, "none", &opts)) {
4567 fprintf(stderr, "Unknown vga type: %s\n", p);
4571 const char *nextopt;
4573 if (strstart(opts, ",retrace=", &nextopt)) {
4575 if (strstart(opts, "dumb", &nextopt))
4576 vga_retrace_method = VGA_RETRACE_DUMB;
4577 else if (strstart(opts, "precise", &nextopt))
4578 vga_retrace_method = VGA_RETRACE_PRECISE;
4579 else goto invalid_vga;
4580 } else goto invalid_vga;
4586 static int balloon_parse(const char *arg)
4591 if (!strcmp(arg, "none")) {
4593 } else if (!strncmp(arg, "virtio", 6)) {
4595 if (arg[6] == ',') {
4597 if (get_param_value(buf, sizeof(buf), "addr", p)) {
4598 virtio_balloon_devaddr = strdup(buf);
4609 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4611 exit(STATUS_CONTROL_C_EXIT);
4616 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4620 if(strlen(str) != 36)
4623 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4624 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4625 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4631 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4637 #define MAX_NET_CLIENTS 32
4641 static void termsig_handler(int signal)
4643 qemu_system_shutdown_request();
4646 static void sigchld_handler(int signal)
4648 waitpid(-1, NULL, WNOHANG);
4651 static void sighandler_setup(void)
4653 struct sigaction act;
4655 memset(&act, 0, sizeof(act));
4656 act.sa_handler = termsig_handler;
4657 sigaction(SIGINT, &act, NULL);
4658 sigaction(SIGHUP, &act, NULL);
4659 sigaction(SIGTERM, &act, NULL);
4661 act.sa_handler = sigchld_handler;
4662 act.sa_flags = SA_NOCLDSTOP;
4663 sigaction(SIGCHLD, &act, NULL);
4669 /* Look for support files in the same directory as the executable. */
4670 static char *find_datadir(const char *argv0)
4676 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4683 while (p != buf && *p != '\\')
4686 if (access(buf, R_OK) == 0) {
4687 return qemu_strdup(buf);
4693 /* Find a likely location for support files using the location of the binary.
4694 For installed binaries this will be "$bindir/../share/qemu". When
4695 running from the build tree this will be "$bindir/../pc-bios". */
4696 #define SHARE_SUFFIX "/share/qemu"
4697 #define BUILD_SUFFIX "/pc-bios"
4698 static char *find_datadir(const char *argv0)
4708 #if defined(__linux__)
4711 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4717 #elif defined(__FreeBSD__)
4720 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4727 /* If we don't have any way of figuring out the actual executable
4728 location then try argv[0]. */
4733 p = realpath(argv0, p);
4741 max_len = strlen(dir) +
4742 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4743 res = qemu_mallocz(max_len);
4744 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4745 if (access(res, R_OK)) {
4746 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4747 if (access(res, R_OK)) {
4761 char *qemu_find_file(int type, const char *name)
4767 /* If name contains path separators then try it as a straight path. */
4768 if ((strchr(name, '/') || strchr(name, '\\'))
4769 && access(name, R_OK) == 0) {
4770 return strdup(name);
4773 case QEMU_FILE_TYPE_BIOS:
4776 case QEMU_FILE_TYPE_KEYMAP:
4777 subdir = "keymaps/";
4782 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4783 buf = qemu_mallocz(len);
4784 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4785 if (access(buf, R_OK)) {
4792 static int device_init_func(QemuOpts *opts, void *opaque)
4796 dev = qdev_device_add(opts);
4802 struct device_config {
4804 DEV_USB, /* -usbdevice */
4807 const char *cmdline;
4808 TAILQ_ENTRY(device_config) next;
4810 TAILQ_HEAD(, device_config) device_configs = TAILQ_HEAD_INITIALIZER(device_configs);
4812 static void add_device_config(int type, const char *cmdline)
4814 struct device_config *conf;
4816 conf = qemu_mallocz(sizeof(*conf));
4818 conf->cmdline = cmdline;
4819 TAILQ_INSERT_TAIL(&device_configs, conf, next);
4822 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4824 struct device_config *conf;
4827 TAILQ_FOREACH(conf, &device_configs, next) {
4828 if (conf->type != type)
4830 rc = func(conf->cmdline);
4837 int main(int argc, char **argv, char **envp)
4839 const char *gdbstub_dev = NULL;
4840 uint32_t boot_devices_bitmap = 0;
4842 int snapshot, linux_boot, net_boot;
4843 const char *initrd_filename;
4844 const char *kernel_filename, *kernel_cmdline;
4845 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4847 DisplayChangeListener *dcl;
4848 int cyls, heads, secs, translation;
4849 const char *net_clients[MAX_NET_CLIENTS];
4851 QemuOpts *hda_opts = NULL, *opts;
4853 const char *r, *optarg;
4854 CharDriverState *monitor_hd = NULL;
4855 const char *monitor_device;
4856 const char *serial_devices[MAX_SERIAL_PORTS];
4857 int serial_device_index;
4858 const char *parallel_devices[MAX_PARALLEL_PORTS];
4859 int parallel_device_index;
4860 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4861 int virtio_console_index;
4862 const char *loadvm = NULL;
4863 QEMUMachine *machine;
4864 const char *cpu_model;
4869 const char *pid_file = NULL;
4870 const char *incoming = NULL;
4873 struct passwd *pwd = NULL;
4874 const char *chroot_dir = NULL;
4875 const char *run_as = NULL;
4878 int show_vnc_port = 0;
4880 qemu_cache_utils_init(envp);
4882 LIST_INIT (&vm_change_state_head);
4885 struct sigaction act;
4886 sigfillset(&act.sa_mask);
4888 act.sa_handler = SIG_IGN;
4889 sigaction(SIGPIPE, &act, NULL);
4892 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4893 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4894 QEMU to run on a single CPU */
4899 h = GetCurrentProcess();
4900 if (GetProcessAffinityMask(h, &mask, &smask)) {
4901 for(i = 0; i < 32; i++) {
4902 if (mask & (1 << i))
4907 SetProcessAffinityMask(h, mask);
4913 module_call_init(MODULE_INIT_MACHINE);
4914 machine = find_default_machine();
4916 initrd_filename = NULL;
4919 kernel_filename = NULL;
4920 kernel_cmdline = "";
4921 cyls = heads = secs = 0;
4922 translation = BIOS_ATA_TRANSLATION_AUTO;
4923 monitor_device = "vc:80Cx24C";
4925 serial_devices[0] = "vc:80Cx24C";
4926 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4927 serial_devices[i] = NULL;
4928 serial_device_index = 0;
4930 parallel_devices[0] = "vc:80Cx24C";
4931 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4932 parallel_devices[i] = NULL;
4933 parallel_device_index = 0;
4935 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4936 virtio_consoles[i] = NULL;
4937 virtio_console_index = 0;
4939 for (i = 0; i < MAX_NODES; i++) {
4941 node_cpumask[i] = 0;
4951 register_watchdogs();
4959 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4961 const QEMUOption *popt;
4964 /* Treat --foo the same as -foo. */
4967 popt = qemu_options;
4970 fprintf(stderr, "%s: invalid option -- '%s'\n",
4974 if (!strcmp(popt->name, r + 1))
4978 if (popt->flags & HAS_ARG) {
4979 if (optind >= argc) {
4980 fprintf(stderr, "%s: option '%s' requires an argument\n",
4984 optarg = argv[optind++];
4989 switch(popt->index) {
4991 machine = find_machine(optarg);
4994 printf("Supported machines are:\n");
4995 for(m = first_machine; m != NULL; m = m->next) {
4997 printf("%-10s %s (alias of %s)\n",
4998 m->alias, m->desc, m->name);
4999 printf("%-10s %s%s\n",
5001 m->is_default ? " (default)" : "");
5003 exit(*optarg != '?');
5006 case QEMU_OPTION_cpu:
5007 /* hw initialization will check this */
5008 if (*optarg == '?') {
5009 /* XXX: implement xxx_cpu_list for targets that still miss it */
5010 #if defined(cpu_list)
5011 cpu_list(stdout, &fprintf);
5018 case QEMU_OPTION_initrd:
5019 initrd_filename = optarg;
5021 case QEMU_OPTION_hda:
5023 hda_opts = drive_add(optarg, HD_ALIAS, 0);
5025 hda_opts = drive_add(optarg, HD_ALIAS
5026 ",cyls=%d,heads=%d,secs=%d%s",
5027 0, cyls, heads, secs,
5028 translation == BIOS_ATA_TRANSLATION_LBA ?
5030 translation == BIOS_ATA_TRANSLATION_NONE ?
5031 ",trans=none" : "");
5033 case QEMU_OPTION_hdb:
5034 case QEMU_OPTION_hdc:
5035 case QEMU_OPTION_hdd:
5036 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5038 case QEMU_OPTION_drive:
5039 drive_add(NULL, "%s", optarg);
5041 case QEMU_OPTION_set:
5042 if (qemu_set_option(optarg) != 0)
5045 case QEMU_OPTION_mtdblock:
5046 drive_add(optarg, MTD_ALIAS);
5048 case QEMU_OPTION_sd:
5049 drive_add(optarg, SD_ALIAS);
5051 case QEMU_OPTION_pflash:
5052 drive_add(optarg, PFLASH_ALIAS);
5054 case QEMU_OPTION_snapshot:
5057 case QEMU_OPTION_hdachs:
5061 cyls = strtol(p, (char **)&p, 0);
5062 if (cyls < 1 || cyls > 16383)
5067 heads = strtol(p, (char **)&p, 0);
5068 if (heads < 1 || heads > 16)
5073 secs = strtol(p, (char **)&p, 0);
5074 if (secs < 1 || secs > 63)
5078 if (!strcmp(p, "none"))
5079 translation = BIOS_ATA_TRANSLATION_NONE;
5080 else if (!strcmp(p, "lba"))
5081 translation = BIOS_ATA_TRANSLATION_LBA;
5082 else if (!strcmp(p, "auto"))
5083 translation = BIOS_ATA_TRANSLATION_AUTO;
5086 } else if (*p != '\0') {
5088 fprintf(stderr, "qemu: invalid physical CHS format\n");
5091 if (hda_opts != NULL) {
5093 snprintf(num, sizeof(num), "%d", cyls);
5094 qemu_opt_set(hda_opts, "cyls", num);
5095 snprintf(num, sizeof(num), "%d", heads);
5096 qemu_opt_set(hda_opts, "heads", num);
5097 snprintf(num, sizeof(num), "%d", secs);
5098 qemu_opt_set(hda_opts, "secs", num);
5099 if (translation == BIOS_ATA_TRANSLATION_LBA)
5100 qemu_opt_set(hda_opts, "trans", "lba");
5101 if (translation == BIOS_ATA_TRANSLATION_NONE)
5102 qemu_opt_set(hda_opts, "trans", "none");
5106 case QEMU_OPTION_numa:
5107 if (nb_numa_nodes >= MAX_NODES) {
5108 fprintf(stderr, "qemu: too many NUMA nodes\n");
5113 case QEMU_OPTION_nographic:
5114 display_type = DT_NOGRAPHIC;
5116 #ifdef CONFIG_CURSES
5117 case QEMU_OPTION_curses:
5118 display_type = DT_CURSES;
5121 case QEMU_OPTION_portrait:
5124 case QEMU_OPTION_kernel:
5125 kernel_filename = optarg;
5127 case QEMU_OPTION_append:
5128 kernel_cmdline = optarg;
5130 case QEMU_OPTION_cdrom:
5131 drive_add(optarg, CDROM_ALIAS);
5133 case QEMU_OPTION_boot:
5135 static const char * const params[] = {
5136 "order", "once", "menu", NULL
5138 char buf[sizeof(boot_devices)];
5139 char *standard_boot_devices;
5142 if (!strchr(optarg, '=')) {
5144 pstrcpy(buf, sizeof(buf), optarg);
5145 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5147 "qemu: unknown boot parameter '%s' in '%s'\n",
5153 get_param_value(buf, sizeof(buf), "order", optarg)) {
5154 boot_devices_bitmap = parse_bootdevices(buf);
5155 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5158 if (get_param_value(buf, sizeof(buf),
5160 boot_devices_bitmap |= parse_bootdevices(buf);
5161 standard_boot_devices = qemu_strdup(boot_devices);
5162 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5163 qemu_register_reset(restore_boot_devices,
5164 standard_boot_devices);
5166 if (get_param_value(buf, sizeof(buf),
5168 if (!strcmp(buf, "on")) {
5170 } else if (!strcmp(buf, "off")) {
5174 "qemu: invalid option value '%s'\n",
5182 case QEMU_OPTION_fda:
5183 case QEMU_OPTION_fdb:
5184 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5187 case QEMU_OPTION_no_fd_bootchk:
5191 case QEMU_OPTION_net:
5192 if (nb_net_clients >= MAX_NET_CLIENTS) {
5193 fprintf(stderr, "qemu: too many network clients\n");
5196 net_clients[nb_net_clients] = optarg;
5200 case QEMU_OPTION_tftp:
5201 legacy_tftp_prefix = optarg;
5203 case QEMU_OPTION_bootp:
5204 legacy_bootp_filename = optarg;
5207 case QEMU_OPTION_smb:
5208 net_slirp_smb(optarg);
5211 case QEMU_OPTION_redir:
5212 net_slirp_redir(optarg);
5215 case QEMU_OPTION_bt:
5216 add_device_config(DEV_BT, optarg);
5219 case QEMU_OPTION_audio_help:
5223 case QEMU_OPTION_soundhw:
5224 select_soundhw (optarg);
5230 case QEMU_OPTION_version:
5234 case QEMU_OPTION_m: {
5238 value = strtoul(optarg, &ptr, 10);
5240 case 0: case 'M': case 'm':
5247 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5251 /* On 32-bit hosts, QEMU is limited by virtual address space */
5252 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5253 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5256 if (value != (uint64_t)(ram_addr_t)value) {
5257 fprintf(stderr, "qemu: ram size too large\n");
5266 const CPULogItem *item;
5268 mask = cpu_str_to_log_mask(optarg);
5270 printf("Log items (comma separated):\n");
5271 for(item = cpu_log_items; item->mask != 0; item++) {
5272 printf("%-10s %s\n", item->name, item->help);
5280 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5282 case QEMU_OPTION_gdb:
5283 gdbstub_dev = optarg;
5288 case QEMU_OPTION_bios:
5291 case QEMU_OPTION_singlestep:
5299 keyboard_layout = optarg;
5302 case QEMU_OPTION_localtime:
5305 case QEMU_OPTION_vga:
5306 select_vgahw (optarg);
5308 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5314 w = strtol(p, (char **)&p, 10);
5317 fprintf(stderr, "qemu: invalid resolution or depth\n");
5323 h = strtol(p, (char **)&p, 10);
5328 depth = strtol(p, (char **)&p, 10);
5329 if (depth != 8 && depth != 15 && depth != 16 &&
5330 depth != 24 && depth != 32)
5332 } else if (*p == '\0') {
5333 depth = graphic_depth;
5340 graphic_depth = depth;
5344 case QEMU_OPTION_echr:
5347 term_escape_char = strtol(optarg, &r, 0);
5349 printf("Bad argument to echr\n");
5352 case QEMU_OPTION_monitor:
5353 monitor_device = optarg;
5355 case QEMU_OPTION_serial:
5356 if (serial_device_index >= MAX_SERIAL_PORTS) {
5357 fprintf(stderr, "qemu: too many serial ports\n");
5360 serial_devices[serial_device_index] = optarg;
5361 serial_device_index++;
5363 case QEMU_OPTION_watchdog:
5364 i = select_watchdog(optarg);
5366 exit (i == 1 ? 1 : 0);
5368 case QEMU_OPTION_watchdog_action:
5369 if (select_watchdog_action(optarg) == -1) {
5370 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5374 case QEMU_OPTION_virtiocon:
5375 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5376 fprintf(stderr, "qemu: too many virtio consoles\n");
5379 virtio_consoles[virtio_console_index] = optarg;
5380 virtio_console_index++;
5382 case QEMU_OPTION_parallel:
5383 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5384 fprintf(stderr, "qemu: too many parallel ports\n");
5387 parallel_devices[parallel_device_index] = optarg;
5388 parallel_device_index++;
5390 case QEMU_OPTION_loadvm:
5393 case QEMU_OPTION_full_screen:
5397 case QEMU_OPTION_no_frame:
5400 case QEMU_OPTION_alt_grab:
5403 case QEMU_OPTION_no_quit:
5406 case QEMU_OPTION_sdl:
5407 display_type = DT_SDL;
5410 case QEMU_OPTION_pidfile:
5414 case QEMU_OPTION_win2k_hack:
5415 win2k_install_hack = 1;
5417 case QEMU_OPTION_rtc_td_hack:
5420 case QEMU_OPTION_acpitable:
5421 if(acpi_table_add(optarg) < 0) {
5422 fprintf(stderr, "Wrong acpi table provided\n");
5426 case QEMU_OPTION_smbios:
5427 if(smbios_entry_add(optarg) < 0) {
5428 fprintf(stderr, "Wrong smbios provided\n");
5434 case QEMU_OPTION_enable_kvm:
5438 case QEMU_OPTION_usb:
5441 case QEMU_OPTION_usbdevice:
5443 add_device_config(DEV_USB, optarg);
5445 case QEMU_OPTION_device:
5446 opts = qemu_opts_parse(&qemu_device_opts, optarg, "driver");
5448 fprintf(stderr, "parse error: %s\n", optarg);
5452 case QEMU_OPTION_smp:
5455 fprintf(stderr, "Invalid number of CPUs\n");
5458 if (max_cpus < smp_cpus) {
5459 fprintf(stderr, "maxcpus must be equal to or greater than "
5463 if (max_cpus > 255) {
5464 fprintf(stderr, "Unsupported number of maxcpus\n");
5468 case QEMU_OPTION_vnc:
5469 display_type = DT_VNC;
5470 vnc_display = optarg;
5473 case QEMU_OPTION_no_acpi:
5476 case QEMU_OPTION_no_hpet:
5479 case QEMU_OPTION_balloon:
5480 if (balloon_parse(optarg) < 0) {
5481 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5486 case QEMU_OPTION_no_reboot:
5489 case QEMU_OPTION_no_shutdown:
5492 case QEMU_OPTION_show_cursor:
5495 case QEMU_OPTION_uuid:
5496 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5497 fprintf(stderr, "Fail to parse UUID string."
5498 " Wrong format.\n");
5503 case QEMU_OPTION_daemonize:
5507 case QEMU_OPTION_option_rom:
5508 if (nb_option_roms >= MAX_OPTION_ROMS) {
5509 fprintf(stderr, "Too many option ROMs\n");
5512 option_rom[nb_option_roms] = optarg;
5515 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5516 case QEMU_OPTION_semihosting:
5517 semihosting_enabled = 1;
5520 case QEMU_OPTION_name:
5521 qemu_name = qemu_strdup(optarg);
5523 char *p = strchr(qemu_name, ',');
5526 if (strncmp(p, "process=", 8)) {
5527 fprintf(stderr, "Unknown subargument %s to -name", p);
5535 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5536 case QEMU_OPTION_prom_env:
5537 if (nb_prom_envs >= MAX_PROM_ENVS) {
5538 fprintf(stderr, "Too many prom variables\n");
5541 prom_envs[nb_prom_envs] = optarg;
5546 case QEMU_OPTION_old_param:
5550 case QEMU_OPTION_clock:
5551 configure_alarms(optarg);
5553 case QEMU_OPTION_startdate:
5556 time_t rtc_start_date;
5557 if (!strcmp(optarg, "now")) {
5558 rtc_date_offset = -1;
5560 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5568 } else if (sscanf(optarg, "%d-%d-%d",
5571 &tm.tm_mday) == 3) {
5580 rtc_start_date = mktimegm(&tm);
5581 if (rtc_start_date == -1) {
5583 fprintf(stderr, "Invalid date format. Valid format are:\n"
5584 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5587 rtc_date_offset = time(NULL) - rtc_start_date;
5591 case QEMU_OPTION_tb_size:
5592 tb_size = strtol(optarg, NULL, 0);
5596 case QEMU_OPTION_icount:
5598 if (strcmp(optarg, "auto") == 0) {
5599 icount_time_shift = -1;
5601 icount_time_shift = strtol(optarg, NULL, 0);
5604 case QEMU_OPTION_incoming:
5608 case QEMU_OPTION_chroot:
5609 chroot_dir = optarg;
5611 case QEMU_OPTION_runas:
5616 case QEMU_OPTION_xen_domid:
5617 xen_domid = atoi(optarg);
5619 case QEMU_OPTION_xen_create:
5620 xen_mode = XEN_CREATE;
5622 case QEMU_OPTION_xen_attach:
5623 xen_mode = XEN_ATTACH;
5630 /* If no data_dir is specified then try to find it relative to the
5633 data_dir = find_datadir(argv[0]);
5635 /* If all else fails use the install patch specified when building. */
5637 data_dir = CONFIG_QEMU_SHAREDIR;
5641 * Default to max_cpus = smp_cpus, in case the user doesn't
5642 * specify a max_cpus value.
5645 max_cpus = smp_cpus;
5647 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5648 if (smp_cpus > machine->max_cpus) {
5649 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5650 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5655 if (display_type == DT_NOGRAPHIC) {
5656 if (serial_device_index == 0)
5657 serial_devices[0] = "stdio";
5658 if (parallel_device_index == 0)
5659 parallel_devices[0] = "null";
5660 if (strncmp(monitor_device, "vc", 2) == 0)
5661 monitor_device = "stdio";
5668 if (pipe(fds) == -1)
5679 len = read(fds[0], &status, 1);
5680 if (len == -1 && (errno == EINTR))
5685 else if (status == 1) {
5686 fprintf(stderr, "Could not acquire pidfile\n");
5703 signal(SIGTSTP, SIG_IGN);
5704 signal(SIGTTOU, SIG_IGN);
5705 signal(SIGTTIN, SIG_IGN);
5708 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5711 write(fds[1], &status, 1);
5713 fprintf(stderr, "Could not acquire pid file\n");
5718 if (qemu_init_main_loop()) {
5719 fprintf(stderr, "qemu_init_main_loop failed\n");
5722 linux_boot = (kernel_filename != NULL);
5724 if (!linux_boot && *kernel_cmdline != '\0') {
5725 fprintf(stderr, "-append only allowed with -kernel option\n");
5729 if (!linux_boot && initrd_filename != NULL) {
5730 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5735 /* Win32 doesn't support line-buffering and requires size >= 2 */
5736 setvbuf(stdout, NULL, _IOLBF, 0);
5740 if (init_timer_alarm() < 0) {
5741 fprintf(stderr, "could not initialize alarm timer\n");
5744 if (use_icount && icount_time_shift < 0) {
5746 /* 125MIPS seems a reasonable initial guess at the guest speed.
5747 It will be corrected fairly quickly anyway. */
5748 icount_time_shift = 3;
5749 init_icount_adjust();
5756 /* init network clients */
5757 if (nb_net_clients == 0) {
5758 /* if no clients, we use a default config */
5759 net_clients[nb_net_clients++] = "nic";
5761 net_clients[nb_net_clients++] = "user";
5765 for(i = 0;i < nb_net_clients; i++) {
5766 if (net_client_parse(net_clients[i]) < 0)
5770 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5771 net_set_boot_mask(net_boot);
5775 /* init the bluetooth world */
5776 if (foreach_device_config(DEV_BT, bt_parse))
5779 /* init the memory */
5781 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5783 /* init the dynamic translator */
5784 cpu_exec_init_all(tb_size * 1024 * 1024);
5788 /* we always create the cdrom drive, even if no disk is there */
5789 drive_add(NULL, CDROM_ALIAS);
5791 /* we always create at least one floppy */
5792 drive_add(NULL, FD_ALIAS, 0);
5794 /* we always create one sd slot, even if no card is in it */
5795 drive_add(NULL, SD_ALIAS);
5797 /* open the virtual block devices */
5799 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5800 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5803 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5804 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5807 /* must be after terminal init, SDL library changes signal handlers */
5811 /* Maintain compatibility with multiple stdio monitors */
5812 if (!strcmp(monitor_device,"stdio")) {
5813 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5814 const char *devname = serial_devices[i];
5815 if (devname && !strcmp(devname,"mon:stdio")) {
5816 monitor_device = NULL;
5818 } else if (devname && !strcmp(devname,"stdio")) {
5819 monitor_device = NULL;
5820 serial_devices[i] = "mon:stdio";
5826 if (nb_numa_nodes > 0) {
5829 if (nb_numa_nodes > smp_cpus) {
5830 nb_numa_nodes = smp_cpus;
5833 /* If no memory size if given for any node, assume the default case
5834 * and distribute the available memory equally across all nodes
5836 for (i = 0; i < nb_numa_nodes; i++) {
5837 if (node_mem[i] != 0)
5840 if (i == nb_numa_nodes) {
5841 uint64_t usedmem = 0;
5843 /* On Linux, the each node's border has to be 8MB aligned,
5844 * the final node gets the rest.
5846 for (i = 0; i < nb_numa_nodes - 1; i++) {
5847 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5848 usedmem += node_mem[i];
5850 node_mem[i] = ram_size - usedmem;
5853 for (i = 0; i < nb_numa_nodes; i++) {
5854 if (node_cpumask[i] != 0)
5857 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5858 * must cope with this anyway, because there are BIOSes out there in
5859 * real machines which also use this scheme.
5861 if (i == nb_numa_nodes) {
5862 for (i = 0; i < smp_cpus; i++) {
5863 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5868 if (kvm_enabled()) {
5871 ret = kvm_init(smp_cpus);
5873 fprintf(stderr, "failed to initialize KVM\n");
5878 if (monitor_device) {
5879 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5881 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5886 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5887 const char *devname = serial_devices[i];
5888 if (devname && strcmp(devname, "none")) {
5890 snprintf(label, sizeof(label), "serial%d", i);
5891 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5892 if (!serial_hds[i]) {
5893 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5900 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5901 const char *devname = parallel_devices[i];
5902 if (devname && strcmp(devname, "none")) {
5904 snprintf(label, sizeof(label), "parallel%d", i);
5905 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5906 if (!parallel_hds[i]) {
5907 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5914 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5915 const char *devname = virtio_consoles[i];
5916 if (devname && strcmp(devname, "none")) {
5918 snprintf(label, sizeof(label), "virtcon%d", i);
5919 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5920 if (!virtcon_hds[i]) {
5921 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5928 module_call_init(MODULE_INIT_DEVICE);
5930 if (machine->compat_props) {
5931 qdev_prop_register_compat(machine->compat_props);
5933 machine->init(ram_size, boot_devices,
5934 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5937 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5938 for (i = 0; i < nb_numa_nodes; i++) {
5939 if (node_cpumask[i] & (1 << env->cpu_index)) {
5945 current_machine = machine;
5947 /* init USB devices */
5949 foreach_device_config(DEV_USB, usb_parse);
5952 /* init generic devices */
5953 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5957 dumb_display_init();
5958 /* just use the first displaystate for the moment */
5961 if (display_type == DT_DEFAULT) {
5962 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5963 display_type = DT_SDL;
5965 display_type = DT_VNC;
5966 vnc_display = "localhost:0,to=99";
5972 switch (display_type) {
5975 #if defined(CONFIG_CURSES)
5977 curses_display_init(ds, full_screen);
5980 #if defined(CONFIG_SDL)
5982 sdl_display_init(ds, full_screen, no_frame);
5984 #elif defined(CONFIG_COCOA)
5986 cocoa_display_init(ds, full_screen);
5990 vnc_display_init(ds);
5991 if (vnc_display_open(ds, vnc_display) < 0)
5994 if (show_vnc_port) {
5995 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6003 dcl = ds->listeners;
6004 while (dcl != NULL) {
6005 if (dcl->dpy_refresh != NULL) {
6006 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6007 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6012 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6013 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6014 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6017 text_consoles_set_display(display_state);
6018 qemu_chr_initial_reset();
6020 if (monitor_device && monitor_hd)
6021 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6023 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6024 const char *devname = serial_devices[i];
6025 if (devname && strcmp(devname, "none")) {
6026 if (strstart(devname, "vc", 0))
6027 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6031 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6032 const char *devname = parallel_devices[i];
6033 if (devname && strcmp(devname, "none")) {
6034 if (strstart(devname, "vc", 0))
6035 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6039 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6040 const char *devname = virtio_consoles[i];
6041 if (virtcon_hds[i] && devname) {
6042 if (strstart(devname, "vc", 0))
6043 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6047 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6048 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6054 if (load_vmstate(cur_mon, loadvm) < 0) {
6060 qemu_start_incoming_migration(incoming);
6061 } else if (autostart) {
6071 len = write(fds[1], &status, 1);
6072 if (len == -1 && (errno == EINTR))
6079 TFR(fd = open("/dev/null", O_RDWR));
6085 pwd = getpwnam(run_as);
6087 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6093 if (chroot(chroot_dir) < 0) {
6094 fprintf(stderr, "chroot failed\n");
6101 if (setgid(pwd->pw_gid) < 0) {
6102 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6105 if (setuid(pwd->pw_uid) < 0) {
6106 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6109 if (setuid(0) != -1) {
6110 fprintf(stderr, "Dropping privileges failed\n");