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 /* Maximum number of monitor devices */
177 #define MAX_MONITOR_DEVICES 10
179 static const char *data_dir;
180 const char *bios_name = NULL;
181 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
182 to store the VM snapshots */
183 struct drivelist drives = TAILQ_HEAD_INITIALIZER(drives);
184 struct driveoptlist driveopts = TAILQ_HEAD_INITIALIZER(driveopts);
185 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
186 static DisplayState *display_state;
187 DisplayType display_type = DT_DEFAULT;
188 const char* keyboard_layout = NULL;
189 int64_t ticks_per_sec;
192 NICInfo nd_table[MAX_NICS];
195 static int rtc_utc = 1;
196 static int rtc_date_offset = -1; /* -1 means no change */
197 int vga_interface_type = VGA_CIRRUS;
199 int graphic_width = 1024;
200 int graphic_height = 768;
201 int graphic_depth = 8;
203 int graphic_width = 800;
204 int graphic_height = 600;
205 int graphic_depth = 15;
207 static int full_screen = 0;
209 static int no_frame = 0;
212 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
213 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
214 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
216 int win2k_install_hack = 0;
225 const char *vnc_display;
226 int acpi_enabled = 1;
232 int graphic_rotate = 0;
233 uint8_t irq0override = 1;
237 const char *watchdog;
238 const char *option_rom[MAX_OPTION_ROMS];
240 int semihosting_enabled = 0;
244 const char *qemu_name;
246 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
247 unsigned int nb_prom_envs = 0;
248 const char *prom_envs[MAX_PROM_ENVS];
253 uint64_t node_mem[MAX_NODES];
254 uint64_t node_cpumask[MAX_NODES];
256 static CPUState *cur_cpu;
257 static CPUState *next_cpu;
258 static int timer_alarm_pending = 1;
259 /* Conversion factor from emulated instructions to virtual clock ticks. */
260 static int icount_time_shift;
261 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
262 #define MAX_ICOUNT_SHIFT 10
263 /* Compensate for varying guest execution speed. */
264 static int64_t qemu_icount_bias;
265 static QEMUTimer *icount_rt_timer;
266 static QEMUTimer *icount_vm_timer;
267 static QEMUTimer *nographic_timer;
269 uint8_t qemu_uuid[16];
271 static QEMUBootSetHandler *boot_set_handler;
272 static void *boot_set_opaque;
274 /***********************************************************/
275 /* x86 ISA bus support */
277 target_phys_addr_t isa_mem_base = 0;
280 /***********************************************************/
281 void hw_error(const char *fmt, ...)
287 fprintf(stderr, "qemu: hardware error: ");
288 vfprintf(stderr, fmt, ap);
289 fprintf(stderr, "\n");
290 for(env = first_cpu; env != NULL; env = env->next_cpu) {
291 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
293 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
295 cpu_dump_state(env, stderr, fprintf, 0);
302 static void set_proc_name(const char *s)
304 #if defined(__linux__) && defined(PR_SET_NAME)
308 name[sizeof(name) - 1] = 0;
309 strncpy(name, s, sizeof(name));
310 /* Could rewrite argv[0] too, but that's a bit more complicated.
311 This simple way is enough for `top'. */
312 prctl(PR_SET_NAME, name);
319 static QEMUBalloonEvent *qemu_balloon_event;
320 void *qemu_balloon_event_opaque;
322 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
324 qemu_balloon_event = func;
325 qemu_balloon_event_opaque = opaque;
328 void qemu_balloon(ram_addr_t target)
330 if (qemu_balloon_event)
331 qemu_balloon_event(qemu_balloon_event_opaque, target);
334 ram_addr_t qemu_balloon_status(void)
336 if (qemu_balloon_event)
337 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
341 /***********************************************************/
344 static QEMUPutKBDEvent *qemu_put_kbd_event;
345 static void *qemu_put_kbd_event_opaque;
346 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
347 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
349 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
351 qemu_put_kbd_event_opaque = opaque;
352 qemu_put_kbd_event = func;
355 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
356 void *opaque, int absolute,
359 QEMUPutMouseEntry *s, *cursor;
361 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
363 s->qemu_put_mouse_event = func;
364 s->qemu_put_mouse_event_opaque = opaque;
365 s->qemu_put_mouse_event_absolute = absolute;
366 s->qemu_put_mouse_event_name = qemu_strdup(name);
369 if (!qemu_put_mouse_event_head) {
370 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
374 cursor = qemu_put_mouse_event_head;
375 while (cursor->next != NULL)
376 cursor = cursor->next;
379 qemu_put_mouse_event_current = s;
384 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
386 QEMUPutMouseEntry *prev = NULL, *cursor;
388 if (!qemu_put_mouse_event_head || entry == NULL)
391 cursor = qemu_put_mouse_event_head;
392 while (cursor != NULL && cursor != entry) {
394 cursor = cursor->next;
397 if (cursor == NULL) // does not exist or list empty
399 else if (prev == NULL) { // entry is head
400 qemu_put_mouse_event_head = cursor->next;
401 if (qemu_put_mouse_event_current == entry)
402 qemu_put_mouse_event_current = cursor->next;
403 qemu_free(entry->qemu_put_mouse_event_name);
408 prev->next = entry->next;
410 if (qemu_put_mouse_event_current == entry)
411 qemu_put_mouse_event_current = prev;
413 qemu_free(entry->qemu_put_mouse_event_name);
417 void kbd_put_keycode(int keycode)
419 if (qemu_put_kbd_event) {
420 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
424 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
426 QEMUPutMouseEvent *mouse_event;
427 void *mouse_event_opaque;
430 if (!qemu_put_mouse_event_current) {
435 qemu_put_mouse_event_current->qemu_put_mouse_event;
437 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
440 if (graphic_rotate) {
441 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
444 width = graphic_width - 1;
445 mouse_event(mouse_event_opaque,
446 width - dy, dx, dz, buttons_state);
448 mouse_event(mouse_event_opaque,
449 dx, dy, dz, buttons_state);
453 int kbd_mouse_is_absolute(void)
455 if (!qemu_put_mouse_event_current)
458 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
461 void do_info_mice(Monitor *mon)
463 QEMUPutMouseEntry *cursor;
466 if (!qemu_put_mouse_event_head) {
467 monitor_printf(mon, "No mouse devices connected\n");
471 monitor_printf(mon, "Mouse devices available:\n");
472 cursor = qemu_put_mouse_event_head;
473 while (cursor != NULL) {
474 monitor_printf(mon, "%c Mouse #%d: %s\n",
475 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
476 index, cursor->qemu_put_mouse_event_name);
478 cursor = cursor->next;
482 void do_mouse_set(Monitor *mon, const QDict *qdict)
484 QEMUPutMouseEntry *cursor;
486 int index = qdict_get_int(qdict, "index");
488 if (!qemu_put_mouse_event_head) {
489 monitor_printf(mon, "No mouse devices connected\n");
493 cursor = qemu_put_mouse_event_head;
494 while (cursor != NULL && index != i) {
496 cursor = cursor->next;
500 qemu_put_mouse_event_current = cursor;
502 monitor_printf(mon, "Mouse at given index not found\n");
505 /* compute with 96 bit intermediate result: (a*b)/c */
506 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
511 #ifdef HOST_WORDS_BIGENDIAN
521 rl = (uint64_t)u.l.low * (uint64_t)b;
522 rh = (uint64_t)u.l.high * (uint64_t)b;
525 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
529 /***********************************************************/
530 /* real time host monotonic timer */
532 #define QEMU_TIMER_BASE 1000000000LL
536 static int64_t clock_freq;
538 static void init_get_clock(void)
542 ret = QueryPerformanceFrequency(&freq);
544 fprintf(stderr, "Could not calibrate ticks\n");
547 clock_freq = freq.QuadPart;
550 static int64_t get_clock(void)
553 QueryPerformanceCounter(&ti);
554 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
559 static int use_rt_clock;
561 static void init_get_clock(void)
564 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
565 || defined(__DragonFly__)
568 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
575 static int64_t get_clock(void)
577 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
578 || defined(__DragonFly__)
581 clock_gettime(CLOCK_MONOTONIC, &ts);
582 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
586 /* XXX: using gettimeofday leads to problems if the date
587 changes, so it should be avoided. */
589 gettimeofday(&tv, NULL);
590 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
595 /* Return the virtual CPU time, based on the instruction counter. */
596 static int64_t cpu_get_icount(void)
599 CPUState *env = cpu_single_env;;
600 icount = qemu_icount;
603 fprintf(stderr, "Bad clock read\n");
604 icount -= (env->icount_decr.u16.low + env->icount_extra);
606 return qemu_icount_bias + (icount << icount_time_shift);
609 /***********************************************************/
610 /* guest cycle counter */
612 static int64_t cpu_ticks_prev;
613 static int64_t cpu_ticks_offset;
614 static int64_t cpu_clock_offset;
615 static int cpu_ticks_enabled;
617 /* return the host CPU cycle counter and handle stop/restart */
618 int64_t cpu_get_ticks(void)
621 return cpu_get_icount();
623 if (!cpu_ticks_enabled) {
624 return cpu_ticks_offset;
627 ticks = cpu_get_real_ticks();
628 if (cpu_ticks_prev > ticks) {
629 /* Note: non increasing ticks may happen if the host uses
631 cpu_ticks_offset += cpu_ticks_prev - ticks;
633 cpu_ticks_prev = ticks;
634 return ticks + cpu_ticks_offset;
638 /* return the host CPU monotonic timer and handle stop/restart */
639 static int64_t cpu_get_clock(void)
642 if (!cpu_ticks_enabled) {
643 return cpu_clock_offset;
646 return ti + cpu_clock_offset;
650 /* enable cpu_get_ticks() */
651 void cpu_enable_ticks(void)
653 if (!cpu_ticks_enabled) {
654 cpu_ticks_offset -= cpu_get_real_ticks();
655 cpu_clock_offset -= get_clock();
656 cpu_ticks_enabled = 1;
660 /* disable cpu_get_ticks() : the clock is stopped. You must not call
661 cpu_get_ticks() after that. */
662 void cpu_disable_ticks(void)
664 if (cpu_ticks_enabled) {
665 cpu_ticks_offset = cpu_get_ticks();
666 cpu_clock_offset = cpu_get_clock();
667 cpu_ticks_enabled = 0;
671 /***********************************************************/
674 #define QEMU_TIMER_REALTIME 0
675 #define QEMU_TIMER_VIRTUAL 1
679 /* XXX: add frequency */
687 struct QEMUTimer *next;
690 struct qemu_alarm_timer {
694 int (*start)(struct qemu_alarm_timer *t);
695 void (*stop)(struct qemu_alarm_timer *t);
696 void (*rearm)(struct qemu_alarm_timer *t);
700 #define ALARM_FLAG_DYNTICKS 0x1
701 #define ALARM_FLAG_EXPIRED 0x2
703 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
705 return t && (t->flags & ALARM_FLAG_DYNTICKS);
708 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
710 if (!alarm_has_dynticks(t))
716 /* TODO: MIN_TIMER_REARM_US should be optimized */
717 #define MIN_TIMER_REARM_US 250
719 static struct qemu_alarm_timer *alarm_timer;
723 struct qemu_alarm_win32 {
726 } alarm_win32_data = {0, -1};
728 static int win32_start_timer(struct qemu_alarm_timer *t);
729 static void win32_stop_timer(struct qemu_alarm_timer *t);
730 static void win32_rearm_timer(struct qemu_alarm_timer *t);
734 static int unix_start_timer(struct qemu_alarm_timer *t);
735 static void unix_stop_timer(struct qemu_alarm_timer *t);
739 static int dynticks_start_timer(struct qemu_alarm_timer *t);
740 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
741 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
743 static int hpet_start_timer(struct qemu_alarm_timer *t);
744 static void hpet_stop_timer(struct qemu_alarm_timer *t);
746 static int rtc_start_timer(struct qemu_alarm_timer *t);
747 static void rtc_stop_timer(struct qemu_alarm_timer *t);
749 #endif /* __linux__ */
753 /* Correlation between real and virtual time is always going to be
754 fairly approximate, so ignore small variation.
755 When the guest is idle real and virtual time will be aligned in
757 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
759 static void icount_adjust(void)
764 static int64_t last_delta;
765 /* If the VM is not running, then do nothing. */
769 cur_time = cpu_get_clock();
770 cur_icount = qemu_get_clock(vm_clock);
771 delta = cur_icount - cur_time;
772 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
774 && last_delta + ICOUNT_WOBBLE < delta * 2
775 && icount_time_shift > 0) {
776 /* The guest is getting too far ahead. Slow time down. */
780 && last_delta - ICOUNT_WOBBLE > delta * 2
781 && icount_time_shift < MAX_ICOUNT_SHIFT) {
782 /* The guest is getting too far behind. Speed time up. */
786 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
789 static void icount_adjust_rt(void * opaque)
791 qemu_mod_timer(icount_rt_timer,
792 qemu_get_clock(rt_clock) + 1000);
796 static void icount_adjust_vm(void * opaque)
798 qemu_mod_timer(icount_vm_timer,
799 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
803 static void init_icount_adjust(void)
805 /* Have both realtime and virtual time triggers for speed adjustment.
806 The realtime trigger catches emulated time passing too slowly,
807 the virtual time trigger catches emulated time passing too fast.
808 Realtime triggers occur even when idle, so use them less frequently
810 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
811 qemu_mod_timer(icount_rt_timer,
812 qemu_get_clock(rt_clock) + 1000);
813 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
814 qemu_mod_timer(icount_vm_timer,
815 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
818 static struct qemu_alarm_timer alarm_timers[] = {
821 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
822 dynticks_stop_timer, dynticks_rearm_timer, NULL},
823 /* HPET - if available - is preferred */
824 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
825 /* ...otherwise try RTC */
826 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
828 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
830 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
831 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
832 {"win32", 0, win32_start_timer,
833 win32_stop_timer, NULL, &alarm_win32_data},
838 static void show_available_alarms(void)
842 printf("Available alarm timers, in order of precedence:\n");
843 for (i = 0; alarm_timers[i].name; i++)
844 printf("%s\n", alarm_timers[i].name);
847 static void configure_alarms(char const *opt)
851 int count = ARRAY_SIZE(alarm_timers) - 1;
854 struct qemu_alarm_timer tmp;
856 if (!strcmp(opt, "?")) {
857 show_available_alarms();
863 /* Reorder the array */
864 name = strtok(arg, ",");
866 for (i = 0; i < count && alarm_timers[i].name; i++) {
867 if (!strcmp(alarm_timers[i].name, name))
872 fprintf(stderr, "Unknown clock %s\n", name);
881 tmp = alarm_timers[i];
882 alarm_timers[i] = alarm_timers[cur];
883 alarm_timers[cur] = tmp;
887 name = strtok(NULL, ",");
893 /* Disable remaining timers */
894 for (i = cur; i < count; i++)
895 alarm_timers[i].name = NULL;
897 show_available_alarms();
905 static QEMUTimer *active_timers[2];
907 static QEMUClock *qemu_new_clock(int type)
910 clock = qemu_mallocz(sizeof(QEMUClock));
915 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
919 ts = qemu_mallocz(sizeof(QEMUTimer));
926 void qemu_free_timer(QEMUTimer *ts)
931 /* stop a timer, but do not dealloc it */
932 void qemu_del_timer(QEMUTimer *ts)
936 /* NOTE: this code must be signal safe because
937 qemu_timer_expired() can be called from a signal. */
938 pt = &active_timers[ts->clock->type];
951 /* modify the current timer so that it will be fired when current_time
952 >= expire_time. The corresponding callback will be called. */
953 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
959 /* add the timer in the sorted list */
960 /* NOTE: this code must be signal safe because
961 qemu_timer_expired() can be called from a signal. */
962 pt = &active_timers[ts->clock->type];
967 if (t->expire_time > expire_time)
971 ts->expire_time = expire_time;
975 /* Rearm if necessary */
976 if (pt == &active_timers[ts->clock->type]) {
977 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
978 qemu_rearm_alarm_timer(alarm_timer);
980 /* Interrupt execution to force deadline recalculation. */
986 int qemu_timer_pending(QEMUTimer *ts)
989 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
996 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1000 return (timer_head->expire_time <= current_time);
1003 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1009 if (!ts || ts->expire_time > current_time)
1011 /* remove timer from the list before calling the callback */
1012 *ptimer_head = ts->next;
1015 /* run the callback (the timer list can be modified) */
1020 int64_t qemu_get_clock(QEMUClock *clock)
1022 switch(clock->type) {
1023 case QEMU_TIMER_REALTIME:
1024 return get_clock() / 1000000;
1026 case QEMU_TIMER_VIRTUAL:
1028 return cpu_get_icount();
1030 return cpu_get_clock();
1035 static void init_timers(void)
1038 ticks_per_sec = QEMU_TIMER_BASE;
1039 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1040 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1044 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1046 uint64_t expire_time;
1048 if (qemu_timer_pending(ts)) {
1049 expire_time = ts->expire_time;
1053 qemu_put_be64(f, expire_time);
1056 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1058 uint64_t expire_time;
1060 expire_time = qemu_get_be64(f);
1061 if (expire_time != -1) {
1062 qemu_mod_timer(ts, expire_time);
1068 static void timer_save(QEMUFile *f, void *opaque)
1070 if (cpu_ticks_enabled) {
1071 hw_error("cannot save state if virtual timers are running");
1073 qemu_put_be64(f, cpu_ticks_offset);
1074 qemu_put_be64(f, ticks_per_sec);
1075 qemu_put_be64(f, cpu_clock_offset);
1078 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1080 if (version_id != 1 && version_id != 2)
1082 if (cpu_ticks_enabled) {
1085 cpu_ticks_offset=qemu_get_be64(f);
1086 ticks_per_sec=qemu_get_be64(f);
1087 if (version_id == 2) {
1088 cpu_clock_offset=qemu_get_be64(f);
1093 static void qemu_event_increment(void);
1096 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1097 DWORD_PTR dwUser, DWORD_PTR dw1,
1100 static void host_alarm_handler(int host_signum)
1104 #define DISP_FREQ 1000
1106 static int64_t delta_min = INT64_MAX;
1107 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1109 ti = qemu_get_clock(vm_clock);
1110 if (last_clock != 0) {
1111 delta = ti - last_clock;
1112 if (delta < delta_min)
1114 if (delta > delta_max)
1117 if (++count == DISP_FREQ) {
1118 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1119 muldiv64(delta_min, 1000000, ticks_per_sec),
1120 muldiv64(delta_max, 1000000, ticks_per_sec),
1121 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1122 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1124 delta_min = INT64_MAX;
1132 if (alarm_has_dynticks(alarm_timer) ||
1134 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1135 qemu_get_clock(vm_clock))) ||
1136 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1137 qemu_get_clock(rt_clock))) {
1138 qemu_event_increment();
1139 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1141 #ifndef CONFIG_IOTHREAD
1143 /* stop the currently executing cpu because a timer occured */
1147 timer_alarm_pending = 1;
1148 qemu_notify_event();
1152 static int64_t qemu_next_deadline(void)
1156 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1157 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1158 qemu_get_clock(vm_clock);
1160 /* To avoid problems with overflow limit this to 2^32. */
1170 #if defined(__linux__) || defined(_WIN32)
1171 static uint64_t qemu_next_deadline_dyntick(void)
1179 delta = (qemu_next_deadline() + 999) / 1000;
1181 if (active_timers[QEMU_TIMER_REALTIME]) {
1182 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1183 qemu_get_clock(rt_clock))*1000;
1184 if (rtdelta < delta)
1188 if (delta < MIN_TIMER_REARM_US)
1189 delta = MIN_TIMER_REARM_US;
1197 /* Sets a specific flag */
1198 static int fcntl_setfl(int fd, int flag)
1202 flags = fcntl(fd, F_GETFL);
1206 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1212 #if defined(__linux__)
1214 #define RTC_FREQ 1024
1216 static void enable_sigio_timer(int fd)
1218 struct sigaction act;
1221 sigfillset(&act.sa_mask);
1223 act.sa_handler = host_alarm_handler;
1225 sigaction(SIGIO, &act, NULL);
1226 fcntl_setfl(fd, O_ASYNC);
1227 fcntl(fd, F_SETOWN, getpid());
1230 static int hpet_start_timer(struct qemu_alarm_timer *t)
1232 struct hpet_info info;
1235 fd = open("/dev/hpet", O_RDONLY);
1240 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1242 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1243 "error, but for better emulation accuracy type:\n"
1244 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1248 /* Check capabilities */
1249 r = ioctl(fd, HPET_INFO, &info);
1253 /* Enable periodic mode */
1254 r = ioctl(fd, HPET_EPI, 0);
1255 if (info.hi_flags && (r < 0))
1258 /* Enable interrupt */
1259 r = ioctl(fd, HPET_IE_ON, 0);
1263 enable_sigio_timer(fd);
1264 t->priv = (void *)(long)fd;
1272 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1274 int fd = (long)t->priv;
1279 static int rtc_start_timer(struct qemu_alarm_timer *t)
1282 unsigned long current_rtc_freq = 0;
1284 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1287 ioctl(rtc_fd, RTC_IRQP_READ, ¤t_rtc_freq);
1288 if (current_rtc_freq != RTC_FREQ &&
1289 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1290 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1291 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1292 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1295 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1301 enable_sigio_timer(rtc_fd);
1303 t->priv = (void *)(long)rtc_fd;
1308 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1310 int rtc_fd = (long)t->priv;
1315 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1319 struct sigaction act;
1321 sigfillset(&act.sa_mask);
1323 act.sa_handler = host_alarm_handler;
1325 sigaction(SIGALRM, &act, NULL);
1328 * Initialize ev struct to 0 to avoid valgrind complaining
1329 * about uninitialized data in timer_create call
1331 memset(&ev, 0, sizeof(ev));
1332 ev.sigev_value.sival_int = 0;
1333 ev.sigev_notify = SIGEV_SIGNAL;
1334 ev.sigev_signo = SIGALRM;
1336 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1337 perror("timer_create");
1339 /* disable dynticks */
1340 fprintf(stderr, "Dynamic Ticks disabled\n");
1345 t->priv = (void *)(long)host_timer;
1350 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1352 timer_t host_timer = (timer_t)(long)t->priv;
1354 timer_delete(host_timer);
1357 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1359 timer_t host_timer = (timer_t)(long)t->priv;
1360 struct itimerspec timeout;
1361 int64_t nearest_delta_us = INT64_MAX;
1364 if (!active_timers[QEMU_TIMER_REALTIME] &&
1365 !active_timers[QEMU_TIMER_VIRTUAL])
1368 nearest_delta_us = qemu_next_deadline_dyntick();
1370 /* check whether a timer is already running */
1371 if (timer_gettime(host_timer, &timeout)) {
1373 fprintf(stderr, "Internal timer error: aborting\n");
1376 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1377 if (current_us && current_us <= nearest_delta_us)
1380 timeout.it_interval.tv_sec = 0;
1381 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1382 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1383 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1384 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1386 fprintf(stderr, "Internal timer error: aborting\n");
1391 #endif /* defined(__linux__) */
1393 static int unix_start_timer(struct qemu_alarm_timer *t)
1395 struct sigaction act;
1396 struct itimerval itv;
1400 sigfillset(&act.sa_mask);
1402 act.sa_handler = host_alarm_handler;
1404 sigaction(SIGALRM, &act, NULL);
1406 itv.it_interval.tv_sec = 0;
1407 /* for i386 kernel 2.6 to get 1 ms */
1408 itv.it_interval.tv_usec = 999;
1409 itv.it_value.tv_sec = 0;
1410 itv.it_value.tv_usec = 10 * 1000;
1412 err = setitimer(ITIMER_REAL, &itv, NULL);
1419 static void unix_stop_timer(struct qemu_alarm_timer *t)
1421 struct itimerval itv;
1423 memset(&itv, 0, sizeof(itv));
1424 setitimer(ITIMER_REAL, &itv, NULL);
1427 #endif /* !defined(_WIN32) */
1432 static int win32_start_timer(struct qemu_alarm_timer *t)
1435 struct qemu_alarm_win32 *data = t->priv;
1438 memset(&tc, 0, sizeof(tc));
1439 timeGetDevCaps(&tc, sizeof(tc));
1441 if (data->period < tc.wPeriodMin)
1442 data->period = tc.wPeriodMin;
1444 timeBeginPeriod(data->period);
1446 flags = TIME_CALLBACK_FUNCTION;
1447 if (alarm_has_dynticks(t))
1448 flags |= TIME_ONESHOT;
1450 flags |= TIME_PERIODIC;
1452 data->timerId = timeSetEvent(1, // interval (ms)
1453 data->period, // resolution
1454 host_alarm_handler, // function
1455 (DWORD)t, // parameter
1458 if (!data->timerId) {
1459 perror("Failed to initialize win32 alarm timer");
1460 timeEndPeriod(data->period);
1467 static void win32_stop_timer(struct qemu_alarm_timer *t)
1469 struct qemu_alarm_win32 *data = t->priv;
1471 timeKillEvent(data->timerId);
1472 timeEndPeriod(data->period);
1475 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1477 struct qemu_alarm_win32 *data = t->priv;
1478 uint64_t nearest_delta_us;
1480 if (!active_timers[QEMU_TIMER_REALTIME] &&
1481 !active_timers[QEMU_TIMER_VIRTUAL])
1484 nearest_delta_us = qemu_next_deadline_dyntick();
1485 nearest_delta_us /= 1000;
1487 timeKillEvent(data->timerId);
1489 data->timerId = timeSetEvent(1,
1493 TIME_ONESHOT | TIME_PERIODIC);
1495 if (!data->timerId) {
1496 perror("Failed to re-arm win32 alarm timer");
1498 timeEndPeriod(data->period);
1505 static int init_timer_alarm(void)
1507 struct qemu_alarm_timer *t = NULL;
1510 for (i = 0; alarm_timers[i].name; i++) {
1511 t = &alarm_timers[i];
1531 static void quit_timers(void)
1533 alarm_timer->stop(alarm_timer);
1537 /***********************************************************/
1538 /* host time/date access */
1539 void qemu_get_timedate(struct tm *tm, int offset)
1546 if (rtc_date_offset == -1) {
1550 ret = localtime(&ti);
1552 ti -= rtc_date_offset;
1556 memcpy(tm, ret, sizeof(struct tm));
1559 int qemu_timedate_diff(struct tm *tm)
1563 if (rtc_date_offset == -1)
1565 seconds = mktimegm(tm);
1567 seconds = mktime(tm);
1569 seconds = mktimegm(tm) + rtc_date_offset;
1571 return seconds - time(NULL);
1575 static void socket_cleanup(void)
1580 static int socket_init(void)
1585 ret = WSAStartup(MAKEWORD(2,2), &Data);
1587 err = WSAGetLastError();
1588 fprintf(stderr, "WSAStartup: %d\n", err);
1591 atexit(socket_cleanup);
1596 /***********************************************************/
1597 /* Bluetooth support */
1600 static struct HCIInfo *hci_table[MAX_NICS];
1602 static struct bt_vlan_s {
1603 struct bt_scatternet_s net;
1605 struct bt_vlan_s *next;
1608 /* find or alloc a new bluetooth "VLAN" */
1609 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1611 struct bt_vlan_s **pvlan, *vlan;
1612 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1616 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1618 pvlan = &first_bt_vlan;
1619 while (*pvlan != NULL)
1620 pvlan = &(*pvlan)->next;
1625 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1629 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1634 static struct HCIInfo null_hci = {
1635 .cmd_send = null_hci_send,
1636 .sco_send = null_hci_send,
1637 .acl_send = null_hci_send,
1638 .bdaddr_set = null_hci_addr_set,
1641 struct HCIInfo *qemu_next_hci(void)
1643 if (cur_hci == nb_hcis)
1646 return hci_table[cur_hci++];
1649 static struct HCIInfo *hci_init(const char *str)
1652 struct bt_scatternet_s *vlan = 0;
1654 if (!strcmp(str, "null"))
1657 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1659 return bt_host_hci(str[4] ? str + 5 : "hci0");
1660 else if (!strncmp(str, "hci", 3)) {
1663 if (!strncmp(str + 3, ",vlan=", 6)) {
1664 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1669 vlan = qemu_find_bt_vlan(0);
1671 return bt_new_hci(vlan);
1674 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1679 static int bt_hci_parse(const char *str)
1681 struct HCIInfo *hci;
1684 if (nb_hcis >= MAX_NICS) {
1685 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1689 hci = hci_init(str);
1698 bdaddr.b[5] = 0x56 + nb_hcis;
1699 hci->bdaddr_set(hci, bdaddr.b);
1701 hci_table[nb_hcis++] = hci;
1706 static void bt_vhci_add(int vlan_id)
1708 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1711 fprintf(stderr, "qemu: warning: adding a VHCI to "
1712 "an empty scatternet %i\n", vlan_id);
1714 bt_vhci_init(bt_new_hci(vlan));
1717 static struct bt_device_s *bt_device_add(const char *opt)
1719 struct bt_scatternet_s *vlan;
1721 char *endp = strstr(opt, ",vlan=");
1722 int len = (endp ? endp - opt : strlen(opt)) + 1;
1725 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1728 vlan_id = strtol(endp + 6, &endp, 0);
1730 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1735 vlan = qemu_find_bt_vlan(vlan_id);
1738 fprintf(stderr, "qemu: warning: adding a slave device to "
1739 "an empty scatternet %i\n", vlan_id);
1741 if (!strcmp(devname, "keyboard"))
1742 return bt_keyboard_init(vlan);
1744 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1748 static int bt_parse(const char *opt)
1750 const char *endp, *p;
1753 if (strstart(opt, "hci", &endp)) {
1754 if (!*endp || *endp == ',') {
1756 if (!strstart(endp, ",vlan=", 0))
1759 return bt_hci_parse(opt);
1761 } else if (strstart(opt, "vhci", &endp)) {
1762 if (!*endp || *endp == ',') {
1764 if (strstart(endp, ",vlan=", &p)) {
1765 vlan = strtol(p, (char **) &endp, 0);
1767 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1771 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1780 } else if (strstart(opt, "device:", &endp))
1781 return !bt_device_add(endp);
1783 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1787 /***********************************************************/
1788 /* QEMU Block devices */
1790 #define HD_ALIAS "index=%d,media=disk"
1791 #define CDROM_ALIAS "index=2,media=cdrom"
1792 #define FD_ALIAS "index=%d,if=floppy"
1793 #define PFLASH_ALIAS "if=pflash"
1794 #define MTD_ALIAS "if=mtd"
1795 #define SD_ALIAS "index=0,if=sd"
1797 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1804 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1807 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1809 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1810 __FUNCTION__, optstr);
1814 qemu_opt_set(opts, "file", file);
1818 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1822 /* seek interface, bus and unit */
1824 TAILQ_FOREACH(dinfo, &drives, next) {
1825 if (dinfo->type == type &&
1826 dinfo->bus == bus &&
1827 dinfo->unit == unit)
1834 DriveInfo *drive_get_by_id(const char *id)
1838 TAILQ_FOREACH(dinfo, &drives, next) {
1839 if (strcmp(id, dinfo->id))
1846 int drive_get_max_bus(BlockInterfaceType type)
1852 TAILQ_FOREACH(dinfo, &drives, next) {
1853 if(dinfo->type == type &&
1854 dinfo->bus > max_bus)
1855 max_bus = dinfo->bus;
1860 const char *drive_get_serial(BlockDriverState *bdrv)
1864 TAILQ_FOREACH(dinfo, &drives, next) {
1865 if (dinfo->bdrv == bdrv)
1866 return dinfo->serial;
1872 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1876 TAILQ_FOREACH(dinfo, &drives, next) {
1877 if (dinfo->bdrv == bdrv)
1878 return dinfo->onerror;
1881 return BLOCK_ERR_STOP_ENOSPC;
1884 static void bdrv_format_print(void *opaque, const char *name)
1886 fprintf(stderr, " %s", name);
1889 void drive_uninit(BlockDriverState *bdrv)
1893 TAILQ_FOREACH(dinfo, &drives, next) {
1894 if (dinfo->bdrv != bdrv)
1896 qemu_opts_del(dinfo->opts);
1897 TAILQ_REMOVE(&drives, dinfo, next);
1903 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1907 const char *file = NULL;
1910 const char *mediastr = "";
1911 BlockInterfaceType type;
1912 enum { MEDIA_DISK, MEDIA_CDROM } media;
1913 int bus_id, unit_id;
1914 int cyls, heads, secs, translation;
1915 BlockDriver *drv = NULL;
1916 QEMUMachine *machine = opaque;
1921 int bdrv_flags, onerror;
1922 const char *devaddr;
1928 translation = BIOS_ATA_TRANSLATION_AUTO;
1931 if (machine->use_scsi) {
1933 max_devs = MAX_SCSI_DEVS;
1934 pstrcpy(devname, sizeof(devname), "scsi");
1937 max_devs = MAX_IDE_DEVS;
1938 pstrcpy(devname, sizeof(devname), "ide");
1942 /* extract parameters */
1943 bus_id = qemu_opt_get_number(opts, "bus", 0);
1944 unit_id = qemu_opt_get_number(opts, "unit", -1);
1945 index = qemu_opt_get_number(opts, "index", -1);
1947 cyls = qemu_opt_get_number(opts, "cyls", 0);
1948 heads = qemu_opt_get_number(opts, "heads", 0);
1949 secs = qemu_opt_get_number(opts, "secs", 0);
1951 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1953 file = qemu_opt_get(opts, "file");
1954 serial = qemu_opt_get(opts, "serial");
1956 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1957 pstrcpy(devname, sizeof(devname), buf);
1958 if (!strcmp(buf, "ide")) {
1960 max_devs = MAX_IDE_DEVS;
1961 } else if (!strcmp(buf, "scsi")) {
1963 max_devs = MAX_SCSI_DEVS;
1964 } else if (!strcmp(buf, "floppy")) {
1967 } else if (!strcmp(buf, "pflash")) {
1970 } else if (!strcmp(buf, "mtd")) {
1973 } else if (!strcmp(buf, "sd")) {
1976 } else if (!strcmp(buf, "virtio")) {
1979 } else if (!strcmp(buf, "xen")) {
1982 } else if (!strcmp(buf, "none")) {
1986 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
1991 if (cyls || heads || secs) {
1992 if (cyls < 1 || cyls > 16383) {
1993 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
1996 if (heads < 1 || heads > 16) {
1997 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2000 if (secs < 1 || secs > 63) {
2001 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2006 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2009 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2013 if (!strcmp(buf, "none"))
2014 translation = BIOS_ATA_TRANSLATION_NONE;
2015 else if (!strcmp(buf, "lba"))
2016 translation = BIOS_ATA_TRANSLATION_LBA;
2017 else if (!strcmp(buf, "auto"))
2018 translation = BIOS_ATA_TRANSLATION_AUTO;
2020 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2025 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2026 if (!strcmp(buf, "disk")) {
2028 } else if (!strcmp(buf, "cdrom")) {
2029 if (cyls || secs || heads) {
2031 "qemu: '%s' invalid physical CHS format\n", buf);
2034 media = MEDIA_CDROM;
2036 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2041 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2042 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2044 else if (!strcmp(buf, "writethrough"))
2046 else if (!strcmp(buf, "writeback"))
2049 fprintf(stderr, "qemu: invalid cache option\n");
2054 #ifdef CONFIG_LINUX_AIO
2055 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2056 if (!strcmp(buf, "threads"))
2058 else if (!strcmp(buf, "native"))
2061 fprintf(stderr, "qemu: invalid aio option\n");
2067 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2068 if (strcmp(buf, "?") == 0) {
2069 fprintf(stderr, "qemu: Supported formats:");
2070 bdrv_iterate_format(bdrv_format_print, NULL);
2071 fprintf(stderr, "\n");
2074 drv = bdrv_find_format(buf);
2076 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2081 onerror = BLOCK_ERR_STOP_ENOSPC;
2082 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2083 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2084 fprintf(stderr, "werror is no supported by this format\n");
2087 if (!strcmp(buf, "ignore"))
2088 onerror = BLOCK_ERR_IGNORE;
2089 else if (!strcmp(buf, "enospc"))
2090 onerror = BLOCK_ERR_STOP_ENOSPC;
2091 else if (!strcmp(buf, "stop"))
2092 onerror = BLOCK_ERR_STOP_ANY;
2093 else if (!strcmp(buf, "report"))
2094 onerror = BLOCK_ERR_REPORT;
2096 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2101 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2102 if (type != IF_VIRTIO) {
2103 fprintf(stderr, "addr is not supported\n");
2108 /* compute bus and unit according index */
2111 if (bus_id != 0 || unit_id != -1) {
2113 "qemu: index cannot be used with bus and unit\n");
2121 unit_id = index % max_devs;
2122 bus_id = index / max_devs;
2126 /* if user doesn't specify a unit_id,
2127 * try to find the first free
2130 if (unit_id == -1) {
2132 while (drive_get(type, bus_id, unit_id) != NULL) {
2134 if (max_devs && unit_id >= max_devs) {
2135 unit_id -= max_devs;
2143 if (max_devs && unit_id >= max_devs) {
2144 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2145 unit_id, max_devs - 1);
2150 * ignore multiple definitions
2153 if (drive_get(type, bus_id, unit_id) != NULL) {
2160 dinfo = qemu_mallocz(sizeof(*dinfo));
2161 if ((buf = qemu_opts_id(opts)) != NULL) {
2162 dinfo->id = qemu_strdup(buf);
2164 /* no id supplied -> create one */
2165 dinfo->id = qemu_mallocz(32);
2166 if (type == IF_IDE || type == IF_SCSI)
2167 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2169 snprintf(dinfo->id, 32, "%s%i%s%i",
2170 devname, bus_id, mediastr, unit_id);
2172 snprintf(dinfo->id, 32, "%s%s%i",
2173 devname, mediastr, unit_id);
2175 dinfo->bdrv = bdrv_new(dinfo->id);
2176 dinfo->devaddr = devaddr;
2178 dinfo->bus = bus_id;
2179 dinfo->unit = unit_id;
2180 dinfo->onerror = onerror;
2183 strncpy(dinfo->serial, serial, sizeof(serial));
2184 TAILQ_INSERT_TAIL(&drives, dinfo, next);
2193 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2194 bdrv_set_translation_hint(dinfo->bdrv, translation);
2198 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2203 /* FIXME: This isn't really a floppy, but it's a reasonable
2206 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2213 /* add virtio block device */
2214 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2215 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2216 qemu_opt_set(opts, "drive", dinfo->id);
2218 qemu_opt_set(opts, "addr", devaddr);
2229 bdrv_flags |= BDRV_O_SNAPSHOT;
2230 cache = 2; /* always use write-back with snapshot */
2232 if (cache == 0) /* no caching */
2233 bdrv_flags |= BDRV_O_NOCACHE;
2234 else if (cache == 2) /* write-back */
2235 bdrv_flags |= BDRV_O_CACHE_WB;
2238 bdrv_flags |= BDRV_O_NATIVE_AIO;
2240 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2243 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2244 fprintf(stderr, "qemu: could not open disk image %s\n",
2249 if (bdrv_key_required(dinfo->bdrv))
2255 static int drive_init_func(QemuOpts *opts, void *opaque)
2257 QEMUMachine *machine = opaque;
2258 int fatal_error = 0;
2260 if (drive_init(opts, machine, &fatal_error) == NULL) {
2267 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2269 if (NULL == qemu_opt_get(opts, "snapshot")) {
2270 qemu_opt_set(opts, "snapshot", "on");
2275 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2277 boot_set_handler = func;
2278 boot_set_opaque = opaque;
2281 int qemu_boot_set(const char *boot_devices)
2283 if (!boot_set_handler) {
2286 return boot_set_handler(boot_set_opaque, boot_devices);
2289 static int parse_bootdevices(char *devices)
2291 /* We just do some generic consistency checks */
2295 for (p = devices; *p != '\0'; p++) {
2296 /* Allowed boot devices are:
2297 * a-b: floppy disk drives
2298 * c-f: IDE disk drives
2299 * g-m: machine implementation dependant drives
2300 * n-p: network devices
2301 * It's up to each machine implementation to check if the given boot
2302 * devices match the actual hardware implementation and firmware
2305 if (*p < 'a' || *p > 'p') {
2306 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2309 if (bitmap & (1 << (*p - 'a'))) {
2310 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2313 bitmap |= 1 << (*p - 'a');
2318 static void restore_boot_devices(void *opaque)
2320 char *standard_boot_devices = opaque;
2322 qemu_boot_set(standard_boot_devices);
2324 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2325 qemu_free(standard_boot_devices);
2328 static void numa_add(const char *optarg)
2332 unsigned long long value, endvalue;
2335 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2336 if (!strcmp(option, "node")) {
2337 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2338 nodenr = nb_numa_nodes;
2340 nodenr = strtoull(option, NULL, 10);
2343 if (get_param_value(option, 128, "mem", optarg) == 0) {
2344 node_mem[nodenr] = 0;
2346 value = strtoull(option, &endptr, 0);
2348 case 0: case 'M': case 'm':
2355 node_mem[nodenr] = value;
2357 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2358 node_cpumask[nodenr] = 0;
2360 value = strtoull(option, &endptr, 10);
2363 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2365 if (*endptr == '-') {
2366 endvalue = strtoull(endptr+1, &endptr, 10);
2367 if (endvalue >= 63) {
2370 "only 63 CPUs in NUMA mode supported.\n");
2372 value = (1 << (endvalue + 1)) - (1 << value);
2377 node_cpumask[nodenr] = value;
2384 static void smp_parse(const char *optarg)
2386 int smp, sockets = 0, threads = 0, cores = 0;
2390 smp = strtoul(optarg, &endptr, 10);
2391 if (endptr != optarg) {
2392 if (*endptr == ',') {
2396 if (get_param_value(option, 128, "sockets", endptr) != 0)
2397 sockets = strtoull(option, NULL, 10);
2398 if (get_param_value(option, 128, "cores", endptr) != 0)
2399 cores = strtoull(option, NULL, 10);
2400 if (get_param_value(option, 128, "threads", endptr) != 0)
2401 threads = strtoull(option, NULL, 10);
2402 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2403 max_cpus = strtoull(option, NULL, 10);
2405 /* compute missing values, prefer sockets over cores over threads */
2406 if (smp == 0 || sockets == 0) {
2407 sockets = sockets > 0 ? sockets : 1;
2408 cores = cores > 0 ? cores : 1;
2409 threads = threads > 0 ? threads : 1;
2411 smp = cores * threads * sockets;
2413 sockets = smp / (cores * threads);
2417 threads = threads > 0 ? threads : 1;
2418 cores = smp / (sockets * threads);
2421 sockets = smp / (cores * threads);
2423 threads = smp / (cores * sockets);
2428 smp_cores = cores > 0 ? cores : 1;
2429 smp_threads = threads > 0 ? threads : 1;
2431 max_cpus = smp_cpus;
2434 /***********************************************************/
2437 static USBPort *used_usb_ports;
2438 static USBPort *free_usb_ports;
2440 /* ??? Maybe change this to register a hub to keep track of the topology. */
2441 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2442 usb_attachfn attach)
2444 port->opaque = opaque;
2445 port->index = index;
2446 port->attach = attach;
2447 port->next = free_usb_ports;
2448 free_usb_ports = port;
2451 int usb_device_add_dev(USBDevice *dev)
2455 /* Find a USB port to add the device to. */
2456 port = free_usb_ports;
2460 /* Create a new hub and chain it on. */
2461 free_usb_ports = NULL;
2462 port->next = used_usb_ports;
2463 used_usb_ports = port;
2465 hub = usb_hub_init(VM_USB_HUB_SIZE);
2466 usb_attach(port, hub);
2467 port = free_usb_ports;
2470 free_usb_ports = port->next;
2471 port->next = used_usb_ports;
2472 used_usb_ports = port;
2473 usb_attach(port, dev);
2477 static void usb_msd_password_cb(void *opaque, int err)
2479 USBDevice *dev = opaque;
2482 usb_device_add_dev(dev);
2484 dev->handle_destroy(dev);
2487 static int usb_device_add(const char *devname, int is_hotplug)
2492 if (!free_usb_ports)
2495 if (strstart(devname, "host:", &p)) {
2496 dev = usb_host_device_open(p);
2497 } else if (!strcmp(devname, "mouse")) {
2498 dev = usb_mouse_init();
2499 } else if (!strcmp(devname, "tablet")) {
2500 dev = usb_tablet_init();
2501 } else if (!strcmp(devname, "keyboard")) {
2502 dev = usb_keyboard_init();
2503 } else if (strstart(devname, "disk:", &p)) {
2504 BlockDriverState *bs;
2506 dev = usb_msd_init(p);
2509 bs = usb_msd_get_bdrv(dev);
2510 if (bdrv_key_required(bs)) {
2513 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2518 } else if (!strcmp(devname, "wacom-tablet")) {
2519 dev = usb_wacom_init();
2520 } else if (strstart(devname, "serial:", &p)) {
2521 dev = usb_serial_init(p);
2522 #ifdef CONFIG_BRLAPI
2523 } else if (!strcmp(devname, "braille")) {
2524 dev = usb_baum_init();
2526 } else if (strstart(devname, "net:", &p)) {
2529 if (net_client_init(NULL, "nic", p) < 0)
2531 nd_table[nic].model = "usb";
2532 dev = usb_net_init(&nd_table[nic]);
2533 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2534 dev = usb_bt_init(devname[2] ? hci_init(p) :
2535 bt_new_hci(qemu_find_bt_vlan(0)));
2542 return usb_device_add_dev(dev);
2545 int usb_device_del_addr(int bus_num, int addr)
2551 if (!used_usb_ports)
2557 lastp = &used_usb_ports;
2558 port = used_usb_ports;
2559 while (port && port->dev->addr != addr) {
2560 lastp = &port->next;
2568 *lastp = port->next;
2569 usb_attach(port, NULL);
2570 dev->handle_destroy(dev);
2571 port->next = free_usb_ports;
2572 free_usb_ports = port;
2576 static int usb_device_del(const char *devname)
2581 if (strstart(devname, "host:", &p))
2582 return usb_host_device_close(p);
2584 if (!used_usb_ports)
2587 p = strchr(devname, '.');
2590 bus_num = strtoul(devname, NULL, 0);
2591 addr = strtoul(p + 1, NULL, 0);
2593 return usb_device_del_addr(bus_num, addr);
2596 static int usb_parse(const char *cmdline)
2598 return usb_device_add(cmdline, 0);
2601 void do_usb_add(Monitor *mon, const QDict *qdict)
2603 usb_device_add(qdict_get_str(qdict, "devname"), 1);
2606 void do_usb_del(Monitor *mon, const QDict *qdict)
2608 usb_device_del(qdict_get_str(qdict, "devname"));
2611 void usb_info(Monitor *mon)
2615 const char *speed_str;
2618 monitor_printf(mon, "USB support not enabled\n");
2622 for (port = used_usb_ports; port; port = port->next) {
2626 switch(dev->speed) {
2630 case USB_SPEED_FULL:
2633 case USB_SPEED_HIGH:
2640 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2641 0, dev->addr, speed_str, dev->devname);
2645 /***********************************************************/
2646 /* PCMCIA/Cardbus */
2648 static struct pcmcia_socket_entry_s {
2649 PCMCIASocket *socket;
2650 struct pcmcia_socket_entry_s *next;
2651 } *pcmcia_sockets = 0;
2653 void pcmcia_socket_register(PCMCIASocket *socket)
2655 struct pcmcia_socket_entry_s *entry;
2657 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2658 entry->socket = socket;
2659 entry->next = pcmcia_sockets;
2660 pcmcia_sockets = entry;
2663 void pcmcia_socket_unregister(PCMCIASocket *socket)
2665 struct pcmcia_socket_entry_s *entry, **ptr;
2667 ptr = &pcmcia_sockets;
2668 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2669 if (entry->socket == socket) {
2675 void pcmcia_info(Monitor *mon)
2677 struct pcmcia_socket_entry_s *iter;
2679 if (!pcmcia_sockets)
2680 monitor_printf(mon, "No PCMCIA sockets\n");
2682 for (iter = pcmcia_sockets; iter; iter = iter->next)
2683 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2684 iter->socket->attached ? iter->socket->card_string :
2688 /***********************************************************/
2689 /* register display */
2691 struct DisplayAllocator default_allocator = {
2692 defaultallocator_create_displaysurface,
2693 defaultallocator_resize_displaysurface,
2694 defaultallocator_free_displaysurface
2697 void register_displaystate(DisplayState *ds)
2707 DisplayState *get_displaystate(void)
2709 return display_state;
2712 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2714 if(ds->allocator == &default_allocator) ds->allocator = da;
2715 return ds->allocator;
2720 static void dumb_display_init(void)
2722 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2723 ds->allocator = &default_allocator;
2724 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2725 register_displaystate(ds);
2728 /***********************************************************/
2731 typedef struct IOHandlerRecord {
2733 IOCanRWHandler *fd_read_poll;
2735 IOHandler *fd_write;
2738 /* temporary data */
2740 struct IOHandlerRecord *next;
2743 static IOHandlerRecord *first_io_handler;
2745 /* XXX: fd_read_poll should be suppressed, but an API change is
2746 necessary in the character devices to suppress fd_can_read(). */
2747 int qemu_set_fd_handler2(int fd,
2748 IOCanRWHandler *fd_read_poll,
2750 IOHandler *fd_write,
2753 IOHandlerRecord **pioh, *ioh;
2755 if (!fd_read && !fd_write) {
2756 pioh = &first_io_handler;
2761 if (ioh->fd == fd) {
2768 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2772 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2773 ioh->next = first_io_handler;
2774 first_io_handler = ioh;
2777 ioh->fd_read_poll = fd_read_poll;
2778 ioh->fd_read = fd_read;
2779 ioh->fd_write = fd_write;
2780 ioh->opaque = opaque;
2786 int qemu_set_fd_handler(int fd,
2788 IOHandler *fd_write,
2791 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2795 /***********************************************************/
2796 /* Polling handling */
2798 typedef struct PollingEntry {
2801 struct PollingEntry *next;
2804 static PollingEntry *first_polling_entry;
2806 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2808 PollingEntry **ppe, *pe;
2809 pe = qemu_mallocz(sizeof(PollingEntry));
2811 pe->opaque = opaque;
2812 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2817 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2819 PollingEntry **ppe, *pe;
2820 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2822 if (pe->func == func && pe->opaque == opaque) {
2830 /***********************************************************/
2831 /* Wait objects support */
2832 typedef struct WaitObjects {
2834 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2835 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2836 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2839 static WaitObjects wait_objects = {0};
2841 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2843 WaitObjects *w = &wait_objects;
2845 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2847 w->events[w->num] = handle;
2848 w->func[w->num] = func;
2849 w->opaque[w->num] = opaque;
2854 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2857 WaitObjects *w = &wait_objects;
2860 for (i = 0; i < w->num; i++) {
2861 if (w->events[i] == handle)
2864 w->events[i] = w->events[i + 1];
2865 w->func[i] = w->func[i + 1];
2866 w->opaque[i] = w->opaque[i + 1];
2874 /***********************************************************/
2875 /* ram save/restore */
2877 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2881 v = qemu_get_byte(f);
2884 if (qemu_get_buffer(f, buf, len) != len)
2888 v = qemu_get_byte(f);
2889 memset(buf, v, len);
2895 if (qemu_file_has_error(f))
2901 static int ram_load_v1(QEMUFile *f, void *opaque)
2906 if (qemu_get_be32(f) != last_ram_offset)
2908 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2909 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2916 #define BDRV_HASH_BLOCK_SIZE 1024
2917 #define IOBUF_SIZE 4096
2918 #define RAM_CBLOCK_MAGIC 0xfabe
2920 typedef struct RamDecompressState {
2923 uint8_t buf[IOBUF_SIZE];
2924 } RamDecompressState;
2926 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2929 memset(s, 0, sizeof(*s));
2931 ret = inflateInit(&s->zstream);
2937 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2941 s->zstream.avail_out = len;
2942 s->zstream.next_out = buf;
2943 while (s->zstream.avail_out > 0) {
2944 if (s->zstream.avail_in == 0) {
2945 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
2947 clen = qemu_get_be16(s->f);
2948 if (clen > IOBUF_SIZE)
2950 qemu_get_buffer(s->f, s->buf, clen);
2951 s->zstream.avail_in = clen;
2952 s->zstream.next_in = s->buf;
2954 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
2955 if (ret != Z_OK && ret != Z_STREAM_END) {
2962 static void ram_decompress_close(RamDecompressState *s)
2964 inflateEnd(&s->zstream);
2967 #define RAM_SAVE_FLAG_FULL 0x01
2968 #define RAM_SAVE_FLAG_COMPRESS 0x02
2969 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2970 #define RAM_SAVE_FLAG_PAGE 0x08
2971 #define RAM_SAVE_FLAG_EOS 0x10
2973 static int is_dup_page(uint8_t *page, uint8_t ch)
2975 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2976 uint32_t *array = (uint32_t *)page;
2979 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2980 if (array[i] != val)
2987 static int ram_save_block(QEMUFile *f)
2989 static ram_addr_t current_addr = 0;
2990 ram_addr_t saved_addr = current_addr;
2991 ram_addr_t addr = 0;
2994 while (addr < last_ram_offset) {
2995 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2998 cpu_physical_memory_reset_dirty(current_addr,
2999 current_addr + TARGET_PAGE_SIZE,
3000 MIGRATION_DIRTY_FLAG);
3002 p = qemu_get_ram_ptr(current_addr);
3004 if (is_dup_page(p, *p)) {
3005 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3006 qemu_put_byte(f, *p);
3008 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3009 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3015 addr += TARGET_PAGE_SIZE;
3016 current_addr = (saved_addr + addr) % last_ram_offset;
3022 static uint64_t bytes_transferred = 0;
3024 static ram_addr_t ram_save_remaining(void)
3027 ram_addr_t count = 0;
3029 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3030 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3037 uint64_t ram_bytes_remaining(void)
3039 return ram_save_remaining() * TARGET_PAGE_SIZE;
3042 uint64_t ram_bytes_transferred(void)
3044 return bytes_transferred;
3047 uint64_t ram_bytes_total(void)
3049 return last_ram_offset;
3052 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3055 uint64_t bytes_transferred_last;
3057 uint64_t expected_time = 0;
3059 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3060 qemu_file_set_error(f);
3065 /* Make sure all dirty bits are set */
3066 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3067 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3068 cpu_physical_memory_set_dirty(addr);
3071 /* Enable dirty memory tracking */
3072 cpu_physical_memory_set_dirty_tracking(1);
3074 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3077 bytes_transferred_last = bytes_transferred;
3078 bwidth = get_clock();
3080 while (!qemu_file_rate_limit(f)) {
3083 ret = ram_save_block(f);
3084 bytes_transferred += ret * TARGET_PAGE_SIZE;
3085 if (ret == 0) /* no more blocks */
3089 bwidth = get_clock() - bwidth;
3090 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3092 /* if we haven't transferred anything this round, force expected_time to a
3093 * a very high value, but without crashing */
3097 /* try transferring iterative blocks of memory */
3101 /* flush all remaining blocks regardless of rate limiting */
3102 while (ram_save_block(f) != 0) {
3103 bytes_transferred += TARGET_PAGE_SIZE;
3105 cpu_physical_memory_set_dirty_tracking(0);
3108 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3110 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3112 return (stage == 2) && (expected_time <= migrate_max_downtime());
3115 static int ram_load_dead(QEMUFile *f, void *opaque)
3117 RamDecompressState s1, *s = &s1;
3121 if (ram_decompress_open(s, f) < 0)
3123 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3124 if (ram_decompress_buf(s, buf, 1) < 0) {
3125 fprintf(stderr, "Error while reading ram block header\n");
3129 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3130 BDRV_HASH_BLOCK_SIZE) < 0) {
3131 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3136 printf("Error block header\n");
3140 ram_decompress_close(s);
3145 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3150 if (version_id == 1)
3151 return ram_load_v1(f, opaque);
3153 if (version_id == 2) {
3154 if (qemu_get_be32(f) != last_ram_offset)
3156 return ram_load_dead(f, opaque);
3159 if (version_id != 3)
3163 addr = qemu_get_be64(f);
3165 flags = addr & ~TARGET_PAGE_MASK;
3166 addr &= TARGET_PAGE_MASK;
3168 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3169 if (addr != last_ram_offset)
3173 if (flags & RAM_SAVE_FLAG_FULL) {
3174 if (ram_load_dead(f, opaque) < 0)
3178 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3179 uint8_t ch = qemu_get_byte(f);
3180 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3183 (!kvm_enabled() || kvm_has_sync_mmu())) {
3184 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3187 } else if (flags & RAM_SAVE_FLAG_PAGE)
3188 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3189 } while (!(flags & RAM_SAVE_FLAG_EOS));
3194 void qemu_service_io(void)
3196 qemu_notify_event();
3199 /***********************************************************/
3200 /* bottom halves (can be seen as timers which expire ASAP) */
3211 static QEMUBH *first_bh = NULL;
3213 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3216 bh = qemu_mallocz(sizeof(QEMUBH));
3218 bh->opaque = opaque;
3219 bh->next = first_bh;
3224 int qemu_bh_poll(void)
3230 for (bh = first_bh; bh; bh = bh->next) {
3231 if (!bh->deleted && bh->scheduled) {
3240 /* remove deleted bhs */
3254 void qemu_bh_schedule_idle(QEMUBH *bh)
3262 void qemu_bh_schedule(QEMUBH *bh)
3268 /* stop the currently executing CPU to execute the BH ASAP */
3269 qemu_notify_event();
3272 void qemu_bh_cancel(QEMUBH *bh)
3277 void qemu_bh_delete(QEMUBH *bh)
3283 static void qemu_bh_update_timeout(int *timeout)
3287 for (bh = first_bh; bh; bh = bh->next) {
3288 if (!bh->deleted && bh->scheduled) {
3290 /* idle bottom halves will be polled at least
3292 *timeout = MIN(10, *timeout);
3294 /* non-idle bottom halves will be executed
3303 /***********************************************************/
3304 /* machine registration */
3306 static QEMUMachine *first_machine = NULL;
3307 QEMUMachine *current_machine = NULL;
3309 int qemu_register_machine(QEMUMachine *m)
3312 pm = &first_machine;
3320 static QEMUMachine *find_machine(const char *name)
3324 for(m = first_machine; m != NULL; m = m->next) {
3325 if (!strcmp(m->name, name))
3327 if (m->alias && !strcmp(m->alias, name))
3333 static QEMUMachine *find_default_machine(void)
3337 for(m = first_machine; m != NULL; m = m->next) {
3338 if (m->is_default) {
3345 /***********************************************************/
3346 /* main execution loop */
3348 static void gui_update(void *opaque)
3350 uint64_t interval = GUI_REFRESH_INTERVAL;
3351 DisplayState *ds = opaque;
3352 DisplayChangeListener *dcl = ds->listeners;
3356 while (dcl != NULL) {
3357 if (dcl->gui_timer_interval &&
3358 dcl->gui_timer_interval < interval)
3359 interval = dcl->gui_timer_interval;
3362 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3365 static void nographic_update(void *opaque)
3367 uint64_t interval = GUI_REFRESH_INTERVAL;
3369 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3372 struct vm_change_state_entry {
3373 VMChangeStateHandler *cb;
3375 LIST_ENTRY (vm_change_state_entry) entries;
3378 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3380 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3383 VMChangeStateEntry *e;
3385 e = qemu_mallocz(sizeof (*e));
3389 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3393 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3395 LIST_REMOVE (e, entries);
3399 static void vm_state_notify(int running, int reason)
3401 VMChangeStateEntry *e;
3403 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3404 e->cb(e->opaque, running, reason);
3408 static void resume_all_vcpus(void);
3409 static void pause_all_vcpus(void);
3416 vm_state_notify(1, 0);
3417 qemu_rearm_alarm_timer(alarm_timer);
3422 /* reset/shutdown handler */
3424 typedef struct QEMUResetEntry {
3425 TAILQ_ENTRY(QEMUResetEntry) entry;
3426 QEMUResetHandler *func;
3430 static TAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3431 TAILQ_HEAD_INITIALIZER(reset_handlers);
3432 static int reset_requested;
3433 static int shutdown_requested;
3434 static int powerdown_requested;
3435 static int debug_requested;
3436 static int vmstop_requested;
3438 int qemu_shutdown_requested(void)
3440 int r = shutdown_requested;
3441 shutdown_requested = 0;
3445 int qemu_reset_requested(void)
3447 int r = reset_requested;
3448 reset_requested = 0;
3452 int qemu_powerdown_requested(void)
3454 int r = powerdown_requested;
3455 powerdown_requested = 0;
3459 static int qemu_debug_requested(void)
3461 int r = debug_requested;
3462 debug_requested = 0;
3466 static int qemu_vmstop_requested(void)
3468 int r = vmstop_requested;
3469 vmstop_requested = 0;
3473 static void do_vm_stop(int reason)
3476 cpu_disable_ticks();
3479 vm_state_notify(0, reason);
3483 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3485 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3488 re->opaque = opaque;
3489 TAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3492 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3496 TAILQ_FOREACH(re, &reset_handlers, entry) {
3497 if (re->func == func && re->opaque == opaque) {
3498 TAILQ_REMOVE(&reset_handlers, re, entry);
3505 void qemu_system_reset(void)
3507 QEMUResetEntry *re, *nre;
3509 /* reset all devices */
3510 TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3511 re->func(re->opaque);
3515 void qemu_system_reset_request(void)
3518 shutdown_requested = 1;
3520 reset_requested = 1;
3522 qemu_notify_event();
3525 void qemu_system_shutdown_request(void)
3527 shutdown_requested = 1;
3528 qemu_notify_event();
3531 void qemu_system_powerdown_request(void)
3533 powerdown_requested = 1;
3534 qemu_notify_event();
3537 #ifdef CONFIG_IOTHREAD
3538 static void qemu_system_vmstop_request(int reason)
3540 vmstop_requested = reason;
3541 qemu_notify_event();
3546 static int io_thread_fd = -1;
3548 static void qemu_event_increment(void)
3550 static const char byte = 0;
3552 if (io_thread_fd == -1)
3555 write(io_thread_fd, &byte, sizeof(byte));
3558 static void qemu_event_read(void *opaque)
3560 int fd = (unsigned long)opaque;
3563 /* Drain the notify pipe */
3566 len = read(fd, buffer, sizeof(buffer));
3567 } while ((len == -1 && errno == EINTR) || len > 0);
3570 static int qemu_event_init(void)
3579 err = fcntl_setfl(fds[0], O_NONBLOCK);
3583 err = fcntl_setfl(fds[1], O_NONBLOCK);
3587 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3588 (void *)(unsigned long)fds[0]);
3590 io_thread_fd = fds[1];
3599 HANDLE qemu_event_handle;
3601 static void dummy_event_handler(void *opaque)
3605 static int qemu_event_init(void)
3607 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3608 if (!qemu_event_handle) {
3609 perror("Failed CreateEvent");
3612 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3616 static void qemu_event_increment(void)
3618 SetEvent(qemu_event_handle);
3622 static int cpu_can_run(CPUState *env)
3631 #ifndef CONFIG_IOTHREAD
3632 static int qemu_init_main_loop(void)
3634 return qemu_event_init();
3637 void qemu_init_vcpu(void *_env)
3639 CPUState *env = _env;
3643 env->nr_cores = smp_cores;
3644 env->nr_threads = smp_threads;
3648 int qemu_cpu_self(void *env)
3653 static void resume_all_vcpus(void)
3657 static void pause_all_vcpus(void)
3661 void qemu_cpu_kick(void *env)
3666 void qemu_notify_event(void)
3668 CPUState *env = cpu_single_env;
3675 #define qemu_mutex_lock_iothread() do { } while (0)
3676 #define qemu_mutex_unlock_iothread() do { } while (0)
3678 void vm_stop(int reason)
3683 #else /* CONFIG_IOTHREAD */
3685 #include "qemu-thread.h"
3687 QemuMutex qemu_global_mutex;
3688 static QemuMutex qemu_fair_mutex;
3690 static QemuThread io_thread;
3692 static QemuThread *tcg_cpu_thread;
3693 static QemuCond *tcg_halt_cond;
3695 static int qemu_system_ready;
3697 static QemuCond qemu_cpu_cond;
3699 static QemuCond qemu_system_cond;
3700 static QemuCond qemu_pause_cond;
3702 static void block_io_signals(void);
3703 static void unblock_io_signals(void);
3704 static int tcg_has_work(void);
3706 static int qemu_init_main_loop(void)
3710 ret = qemu_event_init();
3714 qemu_cond_init(&qemu_pause_cond);
3715 qemu_mutex_init(&qemu_fair_mutex);
3716 qemu_mutex_init(&qemu_global_mutex);
3717 qemu_mutex_lock(&qemu_global_mutex);
3719 unblock_io_signals();
3720 qemu_thread_self(&io_thread);
3725 static void qemu_wait_io_event(CPUState *env)
3727 while (!tcg_has_work())
3728 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3730 qemu_mutex_unlock(&qemu_global_mutex);
3733 * Users of qemu_global_mutex can be starved, having no chance
3734 * to acquire it since this path will get to it first.
3735 * So use another lock to provide fairness.
3737 qemu_mutex_lock(&qemu_fair_mutex);
3738 qemu_mutex_unlock(&qemu_fair_mutex);
3740 qemu_mutex_lock(&qemu_global_mutex);
3744 qemu_cond_signal(&qemu_pause_cond);
3748 static int qemu_cpu_exec(CPUState *env);
3750 static void *kvm_cpu_thread_fn(void *arg)
3752 CPUState *env = arg;
3755 qemu_thread_self(env->thread);
3758 /* signal CPU creation */
3759 qemu_mutex_lock(&qemu_global_mutex);
3761 qemu_cond_signal(&qemu_cpu_cond);
3763 /* and wait for machine initialization */
3764 while (!qemu_system_ready)
3765 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3768 if (cpu_can_run(env))
3770 qemu_wait_io_event(env);
3776 static void tcg_cpu_exec(void);
3778 static void *tcg_cpu_thread_fn(void *arg)
3780 CPUState *env = arg;
3783 qemu_thread_self(env->thread);
3785 /* signal CPU creation */
3786 qemu_mutex_lock(&qemu_global_mutex);
3787 for (env = first_cpu; env != NULL; env = env->next_cpu)
3789 qemu_cond_signal(&qemu_cpu_cond);
3791 /* and wait for machine initialization */
3792 while (!qemu_system_ready)
3793 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3797 qemu_wait_io_event(cur_cpu);
3803 void qemu_cpu_kick(void *_env)
3805 CPUState *env = _env;
3806 qemu_cond_broadcast(env->halt_cond);
3808 qemu_thread_signal(env->thread, SIGUSR1);
3811 int qemu_cpu_self(void *env)
3813 return (cpu_single_env != NULL);
3816 static void cpu_signal(int sig)
3819 cpu_exit(cpu_single_env);
3822 static void block_io_signals(void)
3825 struct sigaction sigact;
3828 sigaddset(&set, SIGUSR2);
3829 sigaddset(&set, SIGIO);
3830 sigaddset(&set, SIGALRM);
3831 pthread_sigmask(SIG_BLOCK, &set, NULL);
3834 sigaddset(&set, SIGUSR1);
3835 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3837 memset(&sigact, 0, sizeof(sigact));
3838 sigact.sa_handler = cpu_signal;
3839 sigaction(SIGUSR1, &sigact, NULL);
3842 static void unblock_io_signals(void)
3847 sigaddset(&set, SIGUSR2);
3848 sigaddset(&set, SIGIO);
3849 sigaddset(&set, SIGALRM);
3850 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3853 sigaddset(&set, SIGUSR1);
3854 pthread_sigmask(SIG_BLOCK, &set, NULL);
3857 static void qemu_signal_lock(unsigned int msecs)
3859 qemu_mutex_lock(&qemu_fair_mutex);
3861 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3862 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3863 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3866 qemu_mutex_unlock(&qemu_fair_mutex);
3869 static void qemu_mutex_lock_iothread(void)
3871 if (kvm_enabled()) {
3872 qemu_mutex_lock(&qemu_fair_mutex);
3873 qemu_mutex_lock(&qemu_global_mutex);
3874 qemu_mutex_unlock(&qemu_fair_mutex);
3876 qemu_signal_lock(100);
3879 static void qemu_mutex_unlock_iothread(void)
3881 qemu_mutex_unlock(&qemu_global_mutex);
3884 static int all_vcpus_paused(void)
3886 CPUState *penv = first_cpu;
3891 penv = (CPUState *)penv->next_cpu;
3897 static void pause_all_vcpus(void)
3899 CPUState *penv = first_cpu;
3903 qemu_thread_signal(penv->thread, SIGUSR1);
3904 qemu_cpu_kick(penv);
3905 penv = (CPUState *)penv->next_cpu;
3908 while (!all_vcpus_paused()) {
3909 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3912 qemu_thread_signal(penv->thread, SIGUSR1);
3913 penv = (CPUState *)penv->next_cpu;
3918 static void resume_all_vcpus(void)
3920 CPUState *penv = first_cpu;
3925 qemu_thread_signal(penv->thread, SIGUSR1);
3926 qemu_cpu_kick(penv);
3927 penv = (CPUState *)penv->next_cpu;
3931 static void tcg_init_vcpu(void *_env)
3933 CPUState *env = _env;
3934 /* share a single thread for all cpus with TCG */
3935 if (!tcg_cpu_thread) {
3936 env->thread = qemu_mallocz(sizeof(QemuThread));
3937 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3938 qemu_cond_init(env->halt_cond);
3939 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3940 while (env->created == 0)
3941 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3942 tcg_cpu_thread = env->thread;
3943 tcg_halt_cond = env->halt_cond;
3945 env->thread = tcg_cpu_thread;
3946 env->halt_cond = tcg_halt_cond;
3950 static void kvm_start_vcpu(CPUState *env)
3952 env->thread = qemu_mallocz(sizeof(QemuThread));
3953 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3954 qemu_cond_init(env->halt_cond);
3955 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3956 while (env->created == 0)
3957 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3960 void qemu_init_vcpu(void *_env)
3962 CPUState *env = _env;
3965 kvm_start_vcpu(env);
3968 env->nr_cores = smp_cores;
3969 env->nr_threads = smp_threads;
3972 void qemu_notify_event(void)
3974 qemu_event_increment();
3977 void vm_stop(int reason)
3980 qemu_thread_self(&me);
3982 if (!qemu_thread_equal(&me, &io_thread)) {
3983 qemu_system_vmstop_request(reason);
3985 * FIXME: should not return to device code in case
3986 * vm_stop() has been requested.
3988 if (cpu_single_env) {
3989 cpu_exit(cpu_single_env);
3990 cpu_single_env->stop = 1;
4001 static void host_main_loop_wait(int *timeout)
4007 /* XXX: need to suppress polling by better using win32 events */
4009 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4010 ret |= pe->func(pe->opaque);
4014 WaitObjects *w = &wait_objects;
4016 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4017 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4018 if (w->func[ret - WAIT_OBJECT_0])
4019 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4021 /* Check for additional signaled events */
4022 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4024 /* Check if event is signaled */
4025 ret2 = WaitForSingleObject(w->events[i], 0);
4026 if(ret2 == WAIT_OBJECT_0) {
4028 w->func[i](w->opaque[i]);
4029 } else if (ret2 == WAIT_TIMEOUT) {
4031 err = GetLastError();
4032 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4035 } else if (ret == WAIT_TIMEOUT) {
4037 err = GetLastError();
4038 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4045 static void host_main_loop_wait(int *timeout)
4050 void main_loop_wait(int timeout)
4052 IOHandlerRecord *ioh;
4053 fd_set rfds, wfds, xfds;
4057 qemu_bh_update_timeout(&timeout);
4059 host_main_loop_wait(&timeout);
4061 /* poll any events */
4062 /* XXX: separate device handlers from system ones */
4067 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4071 (!ioh->fd_read_poll ||
4072 ioh->fd_read_poll(ioh->opaque) != 0)) {
4073 FD_SET(ioh->fd, &rfds);
4077 if (ioh->fd_write) {
4078 FD_SET(ioh->fd, &wfds);
4084 tv.tv_sec = timeout / 1000;
4085 tv.tv_usec = (timeout % 1000) * 1000;
4087 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4089 qemu_mutex_unlock_iothread();
4090 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4091 qemu_mutex_lock_iothread();
4093 IOHandlerRecord **pioh;
4095 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4096 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4097 ioh->fd_read(ioh->opaque);
4099 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4100 ioh->fd_write(ioh->opaque);
4104 /* remove deleted IO handlers */
4105 pioh = &first_io_handler;
4116 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4118 /* rearm timer, if not periodic */
4119 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4120 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4121 qemu_rearm_alarm_timer(alarm_timer);
4124 /* vm time timers */
4126 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4127 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4128 qemu_get_clock(vm_clock));
4131 /* real time timers */
4132 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4133 qemu_get_clock(rt_clock));
4135 /* Check bottom-halves last in case any of the earlier events triggered
4141 static int qemu_cpu_exec(CPUState *env)
4144 #ifdef CONFIG_PROFILER
4148 #ifdef CONFIG_PROFILER
4149 ti = profile_getclock();
4154 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4155 env->icount_decr.u16.low = 0;
4156 env->icount_extra = 0;
4157 count = qemu_next_deadline();
4158 count = (count + (1 << icount_time_shift) - 1)
4159 >> icount_time_shift;
4160 qemu_icount += count;
4161 decr = (count > 0xffff) ? 0xffff : count;
4163 env->icount_decr.u16.low = decr;
4164 env->icount_extra = count;
4166 ret = cpu_exec(env);
4167 #ifdef CONFIG_PROFILER
4168 qemu_time += profile_getclock() - ti;
4171 /* Fold pending instructions back into the
4172 instruction counter, and clear the interrupt flag. */
4173 qemu_icount -= (env->icount_decr.u16.low
4174 + env->icount_extra);
4175 env->icount_decr.u32 = 0;
4176 env->icount_extra = 0;
4181 static void tcg_cpu_exec(void)
4185 if (next_cpu == NULL)
4186 next_cpu = first_cpu;
4187 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4188 CPUState *env = cur_cpu = next_cpu;
4192 if (timer_alarm_pending) {
4193 timer_alarm_pending = 0;
4196 if (cpu_can_run(env))
4197 ret = qemu_cpu_exec(env);
4198 if (ret == EXCP_DEBUG) {
4199 gdb_set_stop_cpu(env);
4200 debug_requested = 1;
4206 static int cpu_has_work(CPUState *env)
4214 if (qemu_cpu_has_work(env))
4219 static int tcg_has_work(void)
4223 for (env = first_cpu; env != NULL; env = env->next_cpu)
4224 if (cpu_has_work(env))
4229 static int qemu_calculate_timeout(void)
4231 #ifndef CONFIG_IOTHREAD
4236 else if (tcg_has_work())
4238 else if (!use_icount)
4241 /* XXX: use timeout computed from timers */
4244 /* Advance virtual time to the next event. */
4245 if (use_icount == 1) {
4246 /* When not using an adaptive execution frequency
4247 we tend to get badly out of sync with real time,
4248 so just delay for a reasonable amount of time. */
4251 delta = cpu_get_icount() - cpu_get_clock();
4254 /* If virtual time is ahead of real time then just
4256 timeout = (delta / 1000000) + 1;
4258 /* Wait for either IO to occur or the next
4260 add = qemu_next_deadline();
4261 /* We advance the timer before checking for IO.
4262 Limit the amount we advance so that early IO
4263 activity won't get the guest too far ahead. */
4267 add = (add + (1 << icount_time_shift) - 1)
4268 >> icount_time_shift;
4270 timeout = delta / 1000000;
4277 #else /* CONFIG_IOTHREAD */
4282 static int vm_can_run(void)
4284 if (powerdown_requested)
4286 if (reset_requested)
4288 if (shutdown_requested)
4290 if (debug_requested)
4295 qemu_irq qemu_system_powerdown;
4297 static void main_loop(void)
4301 #ifdef CONFIG_IOTHREAD
4302 qemu_system_ready = 1;
4303 qemu_cond_broadcast(&qemu_system_cond);
4308 #ifdef CONFIG_PROFILER
4311 #ifndef CONFIG_IOTHREAD
4314 #ifdef CONFIG_PROFILER
4315 ti = profile_getclock();
4317 main_loop_wait(qemu_calculate_timeout());
4318 #ifdef CONFIG_PROFILER
4319 dev_time += profile_getclock() - ti;
4321 } while (vm_can_run());
4323 if (qemu_debug_requested())
4324 vm_stop(EXCP_DEBUG);
4325 if (qemu_shutdown_requested()) {
4332 if (qemu_reset_requested()) {
4334 qemu_system_reset();
4337 if (qemu_powerdown_requested()) {
4338 qemu_irq_raise(qemu_system_powerdown);
4340 if ((r = qemu_vmstop_requested()))
4346 static void version(void)
4348 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4351 static void help(int exitcode)
4354 printf("usage: %s [options] [disk_image]\n"
4356 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4358 #define DEF(option, opt_arg, opt_enum, opt_help) \
4360 #define DEFHEADING(text) stringify(text) "\n"
4361 #include "qemu-options.h"
4366 "During emulation, the following keys are useful:\n"
4367 "ctrl-alt-f toggle full screen\n"
4368 "ctrl-alt-n switch to virtual console 'n'\n"
4369 "ctrl-alt toggle mouse and keyboard grab\n"
4371 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4376 DEFAULT_NETWORK_SCRIPT,
4377 DEFAULT_NETWORK_DOWN_SCRIPT,
4379 DEFAULT_GDBSTUB_PORT,
4384 #define HAS_ARG 0x0001
4387 #define DEF(option, opt_arg, opt_enum, opt_help) \
4389 #define DEFHEADING(text)
4390 #include "qemu-options.h"
4396 typedef struct QEMUOption {
4402 static const QEMUOption qemu_options[] = {
4403 { "h", 0, QEMU_OPTION_h },
4404 #define DEF(option, opt_arg, opt_enum, opt_help) \
4405 { option, opt_arg, opt_enum },
4406 #define DEFHEADING(text)
4407 #include "qemu-options.h"
4415 struct soundhw soundhw[] = {
4416 #ifdef HAS_AUDIO_CHOICE
4417 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4423 { .init_isa = pcspk_audio_init }
4430 "Creative Sound Blaster 16",
4433 { .init_isa = SB16_init }
4437 #ifdef CONFIG_CS4231A
4443 { .init_isa = cs4231a_init }
4451 "Yamaha YMF262 (OPL3)",
4453 "Yamaha YM3812 (OPL2)",
4457 { .init_isa = Adlib_init }
4464 "Gravis Ultrasound GF1",
4467 { .init_isa = GUS_init }
4474 "Intel 82801AA AC97 Audio",
4477 { .init_pci = ac97_init }
4481 #ifdef CONFIG_ES1370
4484 "ENSONIQ AudioPCI ES1370",
4487 { .init_pci = es1370_init }
4491 #endif /* HAS_AUDIO_CHOICE */
4493 { NULL, NULL, 0, 0, { NULL } }
4496 static void select_soundhw (const char *optarg)
4500 if (*optarg == '?') {
4503 printf ("Valid sound card names (comma separated):\n");
4504 for (c = soundhw; c->name; ++c) {
4505 printf ("%-11s %s\n", c->name, c->descr);
4507 printf ("\n-soundhw all will enable all of the above\n");
4508 exit (*optarg != '?');
4516 if (!strcmp (optarg, "all")) {
4517 for (c = soundhw; c->name; ++c) {
4525 e = strchr (p, ',');
4526 l = !e ? strlen (p) : (size_t) (e - p);
4528 for (c = soundhw; c->name; ++c) {
4529 if (!strncmp (c->name, p, l)) {
4538 "Unknown sound card name (too big to show)\n");
4541 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4546 p += l + (e != NULL);
4550 goto show_valid_cards;
4555 static void select_vgahw (const char *p)
4559 vga_interface_type = VGA_NONE;
4560 if (strstart(p, "std", &opts)) {
4561 vga_interface_type = VGA_STD;
4562 } else if (strstart(p, "cirrus", &opts)) {
4563 vga_interface_type = VGA_CIRRUS;
4564 } else if (strstart(p, "vmware", &opts)) {
4565 vga_interface_type = VGA_VMWARE;
4566 } else if (strstart(p, "xenfb", &opts)) {
4567 vga_interface_type = VGA_XENFB;
4568 } else if (!strstart(p, "none", &opts)) {
4570 fprintf(stderr, "Unknown vga type: %s\n", p);
4574 const char *nextopt;
4576 if (strstart(opts, ",retrace=", &nextopt)) {
4578 if (strstart(opts, "dumb", &nextopt))
4579 vga_retrace_method = VGA_RETRACE_DUMB;
4580 else if (strstart(opts, "precise", &nextopt))
4581 vga_retrace_method = VGA_RETRACE_PRECISE;
4582 else goto invalid_vga;
4583 } else goto invalid_vga;
4589 static int balloon_parse(const char *arg)
4593 if (strcmp(arg, "none") == 0) {
4597 if (!strncmp(arg, "virtio", 6)) {
4598 if (arg[6] == ',') {
4599 /* have params -> parse them */
4600 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4604 /* create empty opts */
4605 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4607 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4616 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4618 exit(STATUS_CONTROL_C_EXIT);
4623 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4627 if(strlen(str) != 36)
4630 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4631 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4632 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4638 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4644 #define MAX_NET_CLIENTS 32
4648 static void termsig_handler(int signal)
4650 qemu_system_shutdown_request();
4653 static void sigchld_handler(int signal)
4655 waitpid(-1, NULL, WNOHANG);
4658 static void sighandler_setup(void)
4660 struct sigaction act;
4662 memset(&act, 0, sizeof(act));
4663 act.sa_handler = termsig_handler;
4664 sigaction(SIGINT, &act, NULL);
4665 sigaction(SIGHUP, &act, NULL);
4666 sigaction(SIGTERM, &act, NULL);
4668 act.sa_handler = sigchld_handler;
4669 act.sa_flags = SA_NOCLDSTOP;
4670 sigaction(SIGCHLD, &act, NULL);
4676 /* Look for support files in the same directory as the executable. */
4677 static char *find_datadir(const char *argv0)
4683 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4690 while (p != buf && *p != '\\')
4693 if (access(buf, R_OK) == 0) {
4694 return qemu_strdup(buf);
4700 /* Find a likely location for support files using the location of the binary.
4701 For installed binaries this will be "$bindir/../share/qemu". When
4702 running from the build tree this will be "$bindir/../pc-bios". */
4703 #define SHARE_SUFFIX "/share/qemu"
4704 #define BUILD_SUFFIX "/pc-bios"
4705 static char *find_datadir(const char *argv0)
4715 #if defined(__linux__)
4718 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4724 #elif defined(__FreeBSD__)
4727 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4734 /* If we don't have any way of figuring out the actual executable
4735 location then try argv[0]. */
4740 p = realpath(argv0, p);
4748 max_len = strlen(dir) +
4749 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4750 res = qemu_mallocz(max_len);
4751 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4752 if (access(res, R_OK)) {
4753 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4754 if (access(res, R_OK)) {
4768 char *qemu_find_file(int type, const char *name)
4774 /* If name contains path separators then try it as a straight path. */
4775 if ((strchr(name, '/') || strchr(name, '\\'))
4776 && access(name, R_OK) == 0) {
4777 return strdup(name);
4780 case QEMU_FILE_TYPE_BIOS:
4783 case QEMU_FILE_TYPE_KEYMAP:
4784 subdir = "keymaps/";
4789 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4790 buf = qemu_mallocz(len);
4791 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4792 if (access(buf, R_OK)) {
4799 static int device_init_func(QemuOpts *opts, void *opaque)
4803 dev = qdev_device_add(opts);
4809 struct device_config {
4811 DEV_USB, /* -usbdevice */
4814 const char *cmdline;
4815 TAILQ_ENTRY(device_config) next;
4817 TAILQ_HEAD(, device_config) device_configs = TAILQ_HEAD_INITIALIZER(device_configs);
4819 static void add_device_config(int type, const char *cmdline)
4821 struct device_config *conf;
4823 conf = qemu_mallocz(sizeof(*conf));
4825 conf->cmdline = cmdline;
4826 TAILQ_INSERT_TAIL(&device_configs, conf, next);
4829 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4831 struct device_config *conf;
4834 TAILQ_FOREACH(conf, &device_configs, next) {
4835 if (conf->type != type)
4837 rc = func(conf->cmdline);
4844 int main(int argc, char **argv, char **envp)
4846 const char *gdbstub_dev = NULL;
4847 uint32_t boot_devices_bitmap = 0;
4849 int snapshot, linux_boot, net_boot;
4850 const char *initrd_filename;
4851 const char *kernel_filename, *kernel_cmdline;
4852 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4854 DisplayChangeListener *dcl;
4855 int cyls, heads, secs, translation;
4856 const char *net_clients[MAX_NET_CLIENTS];
4858 QemuOpts *hda_opts = NULL, *opts;
4860 const char *r, *optarg;
4861 CharDriverState *monitor_hds[MAX_MONITOR_DEVICES];
4862 const char *monitor_devices[MAX_MONITOR_DEVICES];
4863 int monitor_device_index;
4864 const char *serial_devices[MAX_SERIAL_PORTS];
4865 int serial_device_index;
4866 const char *parallel_devices[MAX_PARALLEL_PORTS];
4867 int parallel_device_index;
4868 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4869 int virtio_console_index;
4870 const char *loadvm = NULL;
4871 QEMUMachine *machine;
4872 const char *cpu_model;
4877 const char *pid_file = NULL;
4878 const char *incoming = NULL;
4881 struct passwd *pwd = NULL;
4882 const char *chroot_dir = NULL;
4883 const char *run_as = NULL;
4886 int show_vnc_port = 0;
4888 qemu_errors_to_file(stderr);
4889 qemu_cache_utils_init(envp);
4891 LIST_INIT (&vm_change_state_head);
4894 struct sigaction act;
4895 sigfillset(&act.sa_mask);
4897 act.sa_handler = SIG_IGN;
4898 sigaction(SIGPIPE, &act, NULL);
4901 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4902 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4903 QEMU to run on a single CPU */
4908 h = GetCurrentProcess();
4909 if (GetProcessAffinityMask(h, &mask, &smask)) {
4910 for(i = 0; i < 32; i++) {
4911 if (mask & (1 << i))
4916 SetProcessAffinityMask(h, mask);
4922 module_call_init(MODULE_INIT_MACHINE);
4923 machine = find_default_machine();
4925 initrd_filename = NULL;
4928 kernel_filename = NULL;
4929 kernel_cmdline = "";
4930 cyls = heads = secs = 0;
4931 translation = BIOS_ATA_TRANSLATION_AUTO;
4933 serial_devices[0] = "vc:80Cx24C";
4934 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4935 serial_devices[i] = NULL;
4936 serial_device_index = 0;
4938 parallel_devices[0] = "vc:80Cx24C";
4939 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4940 parallel_devices[i] = NULL;
4941 parallel_device_index = 0;
4943 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4944 virtio_consoles[i] = NULL;
4945 virtio_console_index = 0;
4947 monitor_devices[0] = "vc:80Cx24C";
4948 for (i = 1; i < MAX_MONITOR_DEVICES; i++) {
4949 monitor_devices[i] = NULL;
4951 monitor_device_index = 0;
4953 for (i = 0; i < MAX_NODES; i++) {
4955 node_cpumask[i] = 0;
4971 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4973 const QEMUOption *popt;
4976 /* Treat --foo the same as -foo. */
4979 popt = qemu_options;
4982 fprintf(stderr, "%s: invalid option -- '%s'\n",
4986 if (!strcmp(popt->name, r + 1))
4990 if (popt->flags & HAS_ARG) {
4991 if (optind >= argc) {
4992 fprintf(stderr, "%s: option '%s' requires an argument\n",
4996 optarg = argv[optind++];
5001 switch(popt->index) {
5003 machine = find_machine(optarg);
5006 printf("Supported machines are:\n");
5007 for(m = first_machine; m != NULL; m = m->next) {
5009 printf("%-10s %s (alias of %s)\n",
5010 m->alias, m->desc, m->name);
5011 printf("%-10s %s%s\n",
5013 m->is_default ? " (default)" : "");
5015 exit(*optarg != '?');
5018 case QEMU_OPTION_cpu:
5019 /* hw initialization will check this */
5020 if (*optarg == '?') {
5021 /* XXX: implement xxx_cpu_list for targets that still miss it */
5022 #if defined(cpu_list)
5023 cpu_list(stdout, &fprintf);
5030 case QEMU_OPTION_initrd:
5031 initrd_filename = optarg;
5033 case QEMU_OPTION_hda:
5035 hda_opts = drive_add(optarg, HD_ALIAS, 0);
5037 hda_opts = drive_add(optarg, HD_ALIAS
5038 ",cyls=%d,heads=%d,secs=%d%s",
5039 0, cyls, heads, secs,
5040 translation == BIOS_ATA_TRANSLATION_LBA ?
5042 translation == BIOS_ATA_TRANSLATION_NONE ?
5043 ",trans=none" : "");
5045 case QEMU_OPTION_hdb:
5046 case QEMU_OPTION_hdc:
5047 case QEMU_OPTION_hdd:
5048 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5050 case QEMU_OPTION_drive:
5051 drive_add(NULL, "%s", optarg);
5053 case QEMU_OPTION_set:
5054 if (qemu_set_option(optarg) != 0)
5057 case QEMU_OPTION_mtdblock:
5058 drive_add(optarg, MTD_ALIAS);
5060 case QEMU_OPTION_sd:
5061 drive_add(optarg, SD_ALIAS);
5063 case QEMU_OPTION_pflash:
5064 drive_add(optarg, PFLASH_ALIAS);
5066 case QEMU_OPTION_snapshot:
5069 case QEMU_OPTION_hdachs:
5073 cyls = strtol(p, (char **)&p, 0);
5074 if (cyls < 1 || cyls > 16383)
5079 heads = strtol(p, (char **)&p, 0);
5080 if (heads < 1 || heads > 16)
5085 secs = strtol(p, (char **)&p, 0);
5086 if (secs < 1 || secs > 63)
5090 if (!strcmp(p, "none"))
5091 translation = BIOS_ATA_TRANSLATION_NONE;
5092 else if (!strcmp(p, "lba"))
5093 translation = BIOS_ATA_TRANSLATION_LBA;
5094 else if (!strcmp(p, "auto"))
5095 translation = BIOS_ATA_TRANSLATION_AUTO;
5098 } else if (*p != '\0') {
5100 fprintf(stderr, "qemu: invalid physical CHS format\n");
5103 if (hda_opts != NULL) {
5105 snprintf(num, sizeof(num), "%d", cyls);
5106 qemu_opt_set(hda_opts, "cyls", num);
5107 snprintf(num, sizeof(num), "%d", heads);
5108 qemu_opt_set(hda_opts, "heads", num);
5109 snprintf(num, sizeof(num), "%d", secs);
5110 qemu_opt_set(hda_opts, "secs", num);
5111 if (translation == BIOS_ATA_TRANSLATION_LBA)
5112 qemu_opt_set(hda_opts, "trans", "lba");
5113 if (translation == BIOS_ATA_TRANSLATION_NONE)
5114 qemu_opt_set(hda_opts, "trans", "none");
5118 case QEMU_OPTION_numa:
5119 if (nb_numa_nodes >= MAX_NODES) {
5120 fprintf(stderr, "qemu: too many NUMA nodes\n");
5125 case QEMU_OPTION_nographic:
5126 display_type = DT_NOGRAPHIC;
5128 #ifdef CONFIG_CURSES
5129 case QEMU_OPTION_curses:
5130 display_type = DT_CURSES;
5133 case QEMU_OPTION_portrait:
5136 case QEMU_OPTION_kernel:
5137 kernel_filename = optarg;
5139 case QEMU_OPTION_append:
5140 kernel_cmdline = optarg;
5142 case QEMU_OPTION_cdrom:
5143 drive_add(optarg, CDROM_ALIAS);
5145 case QEMU_OPTION_boot:
5147 static const char * const params[] = {
5148 "order", "once", "menu", NULL
5150 char buf[sizeof(boot_devices)];
5151 char *standard_boot_devices;
5154 if (!strchr(optarg, '=')) {
5156 pstrcpy(buf, sizeof(buf), optarg);
5157 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5159 "qemu: unknown boot parameter '%s' in '%s'\n",
5165 get_param_value(buf, sizeof(buf), "order", optarg)) {
5166 boot_devices_bitmap = parse_bootdevices(buf);
5167 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5170 if (get_param_value(buf, sizeof(buf),
5172 boot_devices_bitmap |= parse_bootdevices(buf);
5173 standard_boot_devices = qemu_strdup(boot_devices);
5174 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5175 qemu_register_reset(restore_boot_devices,
5176 standard_boot_devices);
5178 if (get_param_value(buf, sizeof(buf),
5180 if (!strcmp(buf, "on")) {
5182 } else if (!strcmp(buf, "off")) {
5186 "qemu: invalid option value '%s'\n",
5194 case QEMU_OPTION_fda:
5195 case QEMU_OPTION_fdb:
5196 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5199 case QEMU_OPTION_no_fd_bootchk:
5203 case QEMU_OPTION_net:
5204 if (nb_net_clients >= MAX_NET_CLIENTS) {
5205 fprintf(stderr, "qemu: too many network clients\n");
5208 net_clients[nb_net_clients] = optarg;
5212 case QEMU_OPTION_tftp:
5213 legacy_tftp_prefix = optarg;
5215 case QEMU_OPTION_bootp:
5216 legacy_bootp_filename = optarg;
5219 case QEMU_OPTION_smb:
5220 net_slirp_smb(optarg);
5223 case QEMU_OPTION_redir:
5224 net_slirp_redir(optarg);
5227 case QEMU_OPTION_bt:
5228 add_device_config(DEV_BT, optarg);
5231 case QEMU_OPTION_audio_help:
5235 case QEMU_OPTION_soundhw:
5236 select_soundhw (optarg);
5242 case QEMU_OPTION_version:
5246 case QEMU_OPTION_m: {
5250 value = strtoul(optarg, &ptr, 10);
5252 case 0: case 'M': case 'm':
5259 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5263 /* On 32-bit hosts, QEMU is limited by virtual address space */
5264 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5265 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5268 if (value != (uint64_t)(ram_addr_t)value) {
5269 fprintf(stderr, "qemu: ram size too large\n");
5278 const CPULogItem *item;
5280 mask = cpu_str_to_log_mask(optarg);
5282 printf("Log items (comma separated):\n");
5283 for(item = cpu_log_items; item->mask != 0; item++) {
5284 printf("%-10s %s\n", item->name, item->help);
5292 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5294 case QEMU_OPTION_gdb:
5295 gdbstub_dev = optarg;
5300 case QEMU_OPTION_bios:
5303 case QEMU_OPTION_singlestep:
5311 keyboard_layout = optarg;
5314 case QEMU_OPTION_localtime:
5317 case QEMU_OPTION_vga:
5318 select_vgahw (optarg);
5320 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5326 w = strtol(p, (char **)&p, 10);
5329 fprintf(stderr, "qemu: invalid resolution or depth\n");
5335 h = strtol(p, (char **)&p, 10);
5340 depth = strtol(p, (char **)&p, 10);
5341 if (depth != 8 && depth != 15 && depth != 16 &&
5342 depth != 24 && depth != 32)
5344 } else if (*p == '\0') {
5345 depth = graphic_depth;
5352 graphic_depth = depth;
5356 case QEMU_OPTION_echr:
5359 term_escape_char = strtol(optarg, &r, 0);
5361 printf("Bad argument to echr\n");
5364 case QEMU_OPTION_monitor:
5365 if (monitor_device_index >= MAX_MONITOR_DEVICES) {
5366 fprintf(stderr, "qemu: too many monitor devices\n");
5369 monitor_devices[monitor_device_index] = optarg;
5370 monitor_device_index++;
5372 case QEMU_OPTION_serial:
5373 if (serial_device_index >= MAX_SERIAL_PORTS) {
5374 fprintf(stderr, "qemu: too many serial ports\n");
5377 serial_devices[serial_device_index] = optarg;
5378 serial_device_index++;
5380 case QEMU_OPTION_watchdog:
5383 "qemu: only one watchdog option may be given\n");
5388 case QEMU_OPTION_watchdog_action:
5389 if (select_watchdog_action(optarg) == -1) {
5390 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5394 case QEMU_OPTION_virtiocon:
5395 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5396 fprintf(stderr, "qemu: too many virtio consoles\n");
5399 virtio_consoles[virtio_console_index] = optarg;
5400 virtio_console_index++;
5402 case QEMU_OPTION_parallel:
5403 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5404 fprintf(stderr, "qemu: too many parallel ports\n");
5407 parallel_devices[parallel_device_index] = optarg;
5408 parallel_device_index++;
5410 case QEMU_OPTION_loadvm:
5413 case QEMU_OPTION_full_screen:
5417 case QEMU_OPTION_no_frame:
5420 case QEMU_OPTION_alt_grab:
5423 case QEMU_OPTION_no_quit:
5426 case QEMU_OPTION_sdl:
5427 display_type = DT_SDL;
5430 case QEMU_OPTION_pidfile:
5434 case QEMU_OPTION_win2k_hack:
5435 win2k_install_hack = 1;
5437 case QEMU_OPTION_rtc_td_hack:
5440 case QEMU_OPTION_acpitable:
5441 if(acpi_table_add(optarg) < 0) {
5442 fprintf(stderr, "Wrong acpi table provided\n");
5446 case QEMU_OPTION_smbios:
5447 if(smbios_entry_add(optarg) < 0) {
5448 fprintf(stderr, "Wrong smbios provided\n");
5454 case QEMU_OPTION_enable_kvm:
5458 case QEMU_OPTION_usb:
5461 case QEMU_OPTION_usbdevice:
5463 add_device_config(DEV_USB, optarg);
5465 case QEMU_OPTION_device:
5466 opts = qemu_opts_parse(&qemu_device_opts, optarg, "driver");
5468 fprintf(stderr, "parse error: %s\n", optarg);
5472 case QEMU_OPTION_smp:
5475 fprintf(stderr, "Invalid number of CPUs\n");
5478 if (max_cpus < smp_cpus) {
5479 fprintf(stderr, "maxcpus must be equal to or greater than "
5483 if (max_cpus > 255) {
5484 fprintf(stderr, "Unsupported number of maxcpus\n");
5488 case QEMU_OPTION_vnc:
5489 display_type = DT_VNC;
5490 vnc_display = optarg;
5493 case QEMU_OPTION_no_acpi:
5496 case QEMU_OPTION_no_hpet:
5499 case QEMU_OPTION_balloon:
5500 if (balloon_parse(optarg) < 0) {
5501 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5506 case QEMU_OPTION_no_reboot:
5509 case QEMU_OPTION_no_shutdown:
5512 case QEMU_OPTION_show_cursor:
5515 case QEMU_OPTION_uuid:
5516 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5517 fprintf(stderr, "Fail to parse UUID string."
5518 " Wrong format.\n");
5523 case QEMU_OPTION_daemonize:
5527 case QEMU_OPTION_option_rom:
5528 if (nb_option_roms >= MAX_OPTION_ROMS) {
5529 fprintf(stderr, "Too many option ROMs\n");
5532 option_rom[nb_option_roms] = optarg;
5535 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5536 case QEMU_OPTION_semihosting:
5537 semihosting_enabled = 1;
5540 case QEMU_OPTION_name:
5541 qemu_name = qemu_strdup(optarg);
5543 char *p = strchr(qemu_name, ',');
5546 if (strncmp(p, "process=", 8)) {
5547 fprintf(stderr, "Unknown subargument %s to -name", p);
5555 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5556 case QEMU_OPTION_prom_env:
5557 if (nb_prom_envs >= MAX_PROM_ENVS) {
5558 fprintf(stderr, "Too many prom variables\n");
5561 prom_envs[nb_prom_envs] = optarg;
5566 case QEMU_OPTION_old_param:
5570 case QEMU_OPTION_clock:
5571 configure_alarms(optarg);
5573 case QEMU_OPTION_startdate:
5576 time_t rtc_start_date;
5577 if (!strcmp(optarg, "now")) {
5578 rtc_date_offset = -1;
5580 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5588 } else if (sscanf(optarg, "%d-%d-%d",
5591 &tm.tm_mday) == 3) {
5600 rtc_start_date = mktimegm(&tm);
5601 if (rtc_start_date == -1) {
5603 fprintf(stderr, "Invalid date format. Valid format are:\n"
5604 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5607 rtc_date_offset = time(NULL) - rtc_start_date;
5611 case QEMU_OPTION_tb_size:
5612 tb_size = strtol(optarg, NULL, 0);
5616 case QEMU_OPTION_icount:
5618 if (strcmp(optarg, "auto") == 0) {
5619 icount_time_shift = -1;
5621 icount_time_shift = strtol(optarg, NULL, 0);
5624 case QEMU_OPTION_incoming:
5628 case QEMU_OPTION_chroot:
5629 chroot_dir = optarg;
5631 case QEMU_OPTION_runas:
5636 case QEMU_OPTION_xen_domid:
5637 xen_domid = atoi(optarg);
5639 case QEMU_OPTION_xen_create:
5640 xen_mode = XEN_CREATE;
5642 case QEMU_OPTION_xen_attach:
5643 xen_mode = XEN_ATTACH;
5650 /* If no data_dir is specified then try to find it relative to the
5653 data_dir = find_datadir(argv[0]);
5655 /* If all else fails use the install patch specified when building. */
5657 data_dir = CONFIG_QEMU_SHAREDIR;
5661 * Default to max_cpus = smp_cpus, in case the user doesn't
5662 * specify a max_cpus value.
5665 max_cpus = smp_cpus;
5667 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5668 if (smp_cpus > machine->max_cpus) {
5669 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5670 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5675 if (display_type == DT_NOGRAPHIC) {
5676 if (serial_device_index == 0)
5677 serial_devices[0] = "stdio";
5678 if (parallel_device_index == 0)
5679 parallel_devices[0] = "null";
5680 if (strncmp(monitor_devices[0], "vc", 2) == 0) {
5681 monitor_devices[0] = "stdio";
5689 if (pipe(fds) == -1)
5700 len = read(fds[0], &status, 1);
5701 if (len == -1 && (errno == EINTR))
5706 else if (status == 1) {
5707 fprintf(stderr, "Could not acquire pidfile\n");
5724 signal(SIGTSTP, SIG_IGN);
5725 signal(SIGTTOU, SIG_IGN);
5726 signal(SIGTTIN, SIG_IGN);
5729 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5732 write(fds[1], &status, 1);
5734 fprintf(stderr, "Could not acquire pid file\n");
5739 if (qemu_init_main_loop()) {
5740 fprintf(stderr, "qemu_init_main_loop failed\n");
5743 linux_boot = (kernel_filename != NULL);
5745 if (!linux_boot && *kernel_cmdline != '\0') {
5746 fprintf(stderr, "-append only allowed with -kernel option\n");
5750 if (!linux_boot && initrd_filename != NULL) {
5751 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5756 /* Win32 doesn't support line-buffering and requires size >= 2 */
5757 setvbuf(stdout, NULL, _IOLBF, 0);
5761 if (init_timer_alarm() < 0) {
5762 fprintf(stderr, "could not initialize alarm timer\n");
5765 if (use_icount && icount_time_shift < 0) {
5767 /* 125MIPS seems a reasonable initial guess at the guest speed.
5768 It will be corrected fairly quickly anyway. */
5769 icount_time_shift = 3;
5770 init_icount_adjust();
5777 /* init network clients */
5778 if (nb_net_clients == 0) {
5779 /* if no clients, we use a default config */
5780 net_clients[nb_net_clients++] = "nic";
5782 net_clients[nb_net_clients++] = "user";
5786 for(i = 0;i < nb_net_clients; i++) {
5787 if (net_client_parse(net_clients[i]) < 0)
5791 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5792 net_set_boot_mask(net_boot);
5796 /* init the bluetooth world */
5797 if (foreach_device_config(DEV_BT, bt_parse))
5800 /* init the memory */
5802 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5804 /* init the dynamic translator */
5805 cpu_exec_init_all(tb_size * 1024 * 1024);
5809 /* we always create the cdrom drive, even if no disk is there */
5810 drive_add(NULL, CDROM_ALIAS);
5812 /* we always create at least one floppy */
5813 drive_add(NULL, FD_ALIAS, 0);
5815 /* we always create one sd slot, even if no card is in it */
5816 drive_add(NULL, SD_ALIAS);
5818 /* open the virtual block devices */
5820 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5821 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5824 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5825 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5827 /* Maintain compatibility with multiple stdio monitors */
5828 if (!strcmp(monitor_devices[0],"stdio")) {
5829 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5830 const char *devname = serial_devices[i];
5831 if (devname && !strcmp(devname,"mon:stdio")) {
5832 monitor_devices[0] = NULL;
5834 } else if (devname && !strcmp(devname,"stdio")) {
5835 monitor_devices[0] = NULL;
5836 serial_devices[i] = "mon:stdio";
5842 if (nb_numa_nodes > 0) {
5845 if (nb_numa_nodes > smp_cpus) {
5846 nb_numa_nodes = smp_cpus;
5849 /* If no memory size if given for any node, assume the default case
5850 * and distribute the available memory equally across all nodes
5852 for (i = 0; i < nb_numa_nodes; i++) {
5853 if (node_mem[i] != 0)
5856 if (i == nb_numa_nodes) {
5857 uint64_t usedmem = 0;
5859 /* On Linux, the each node's border has to be 8MB aligned,
5860 * the final node gets the rest.
5862 for (i = 0; i < nb_numa_nodes - 1; i++) {
5863 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5864 usedmem += node_mem[i];
5866 node_mem[i] = ram_size - usedmem;
5869 for (i = 0; i < nb_numa_nodes; i++) {
5870 if (node_cpumask[i] != 0)
5873 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5874 * must cope with this anyway, because there are BIOSes out there in
5875 * real machines which also use this scheme.
5877 if (i == nb_numa_nodes) {
5878 for (i = 0; i < smp_cpus; i++) {
5879 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5884 if (kvm_enabled()) {
5887 ret = kvm_init(smp_cpus);
5889 fprintf(stderr, "failed to initialize KVM\n");
5894 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5895 const char *devname = monitor_devices[i];
5896 if (devname && strcmp(devname, "none")) {
5899 snprintf(label, sizeof(label), "monitor");
5901 snprintf(label, sizeof(label), "monitor%d", i);
5903 monitor_hds[i] = qemu_chr_open(label, devname, NULL);
5904 if (!monitor_hds[i]) {
5905 fprintf(stderr, "qemu: could not open monitor device '%s'\n",
5912 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5913 const char *devname = serial_devices[i];
5914 if (devname && strcmp(devname, "none")) {
5916 snprintf(label, sizeof(label), "serial%d", i);
5917 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5918 if (!serial_hds[i]) {
5919 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5926 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5927 const char *devname = parallel_devices[i];
5928 if (devname && strcmp(devname, "none")) {
5930 snprintf(label, sizeof(label), "parallel%d", i);
5931 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5932 if (!parallel_hds[i]) {
5933 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5940 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5941 const char *devname = virtio_consoles[i];
5942 if (devname && strcmp(devname, "none")) {
5944 snprintf(label, sizeof(label), "virtcon%d", i);
5945 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5946 if (!virtcon_hds[i]) {
5947 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5954 module_call_init(MODULE_INIT_DEVICE);
5957 i = select_watchdog(watchdog);
5959 exit (i == 1 ? 1 : 0);
5962 if (machine->compat_props) {
5963 qdev_prop_register_compat(machine->compat_props);
5965 machine->init(ram_size, boot_devices,
5966 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5970 /* must be after terminal init, SDL library changes signal handlers */
5974 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5975 for (i = 0; i < nb_numa_nodes; i++) {
5976 if (node_cpumask[i] & (1 << env->cpu_index)) {
5982 current_machine = machine;
5984 /* init USB devices */
5986 foreach_device_config(DEV_USB, usb_parse);
5989 /* init generic devices */
5990 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5994 dumb_display_init();
5995 /* just use the first displaystate for the moment */
5998 if (display_type == DT_DEFAULT) {
5999 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6000 display_type = DT_SDL;
6002 display_type = DT_VNC;
6003 vnc_display = "localhost:0,to=99";
6009 switch (display_type) {
6012 #if defined(CONFIG_CURSES)
6014 curses_display_init(ds, full_screen);
6017 #if defined(CONFIG_SDL)
6019 sdl_display_init(ds, full_screen, no_frame);
6021 #elif defined(CONFIG_COCOA)
6023 cocoa_display_init(ds, full_screen);
6027 vnc_display_init(ds);
6028 if (vnc_display_open(ds, vnc_display) < 0)
6031 if (show_vnc_port) {
6032 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6040 dcl = ds->listeners;
6041 while (dcl != NULL) {
6042 if (dcl->dpy_refresh != NULL) {
6043 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6044 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6049 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6050 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6051 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6054 text_consoles_set_display(display_state);
6055 qemu_chr_initial_reset();
6057 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
6058 if (monitor_devices[i] && monitor_hds[i]) {
6059 monitor_init(monitor_hds[i],
6060 MONITOR_USE_READLINE |
6061 ((i == 0) ? MONITOR_IS_DEFAULT : 0));
6065 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6066 const char *devname = serial_devices[i];
6067 if (devname && strcmp(devname, "none")) {
6068 if (strstart(devname, "vc", 0))
6069 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6073 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6074 const char *devname = parallel_devices[i];
6075 if (devname && strcmp(devname, "none")) {
6076 if (strstart(devname, "vc", 0))
6077 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6081 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6082 const char *devname = virtio_consoles[i];
6083 if (virtcon_hds[i] && devname) {
6084 if (strstart(devname, "vc", 0))
6085 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6089 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6090 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6096 if (load_vmstate(cur_mon, loadvm) < 0) {
6102 qemu_start_incoming_migration(incoming);
6103 } else if (autostart) {
6113 len = write(fds[1], &status, 1);
6114 if (len == -1 && (errno == EINTR))
6121 TFR(fd = open("/dev/null", O_RDWR));
6127 pwd = getpwnam(run_as);
6129 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6135 if (chroot(chroot_dir) < 0) {
6136 fprintf(stderr, "chroot failed\n");
6143 if (setgid(pwd->pw_gid) < 0) {
6144 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6147 if (setuid(pwd->pw_uid) < 0) {
6148 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6151 if (setuid(0) != -1) {
6152 fprintf(stderr, "Dropping privileges failed\n");