4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
32 /* Needed early for HOST_BSD etc. */
33 #include "config-host.h"
38 #include <sys/times.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
47 #if defined(__NetBSD__)
48 #include <net/if_tap.h>
51 #include <linux/if_tun.h>
53 #include <arpa/inet.h>
56 #include <sys/select.h>
59 #if defined(__FreeBSD__) || defined(__DragonFly__)
64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65 #include <freebsd/stdlib.h>
70 #include <linux/rtc.h>
72 /* For the benefit of older linux systems which don't supply it,
73 we use a local copy of hpet.h. */
74 /* #include <linux/hpet.h> */
77 #include <linux/ppdev.h>
78 #include <linux/parport.h>
82 #include <sys/ethernet.h>
83 #include <sys/sockio.h>
84 #include <netinet/arp.h>
85 #include <netinet/in.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip_icmp.h> // must come after ip.h
89 #include <netinet/udp.h>
90 #include <netinet/tcp.h>
98 #if defined(__OpenBSD__)
102 #if defined(CONFIG_VDE)
103 #include <libvdeplug.h>
109 #include <sys/timeb.h>
110 #include <mmsystem.h>
111 #define getopt_long_only getopt_long
112 #define memalign(align, size) malloc(size)
116 #if defined(__APPLE__) || defined(main)
118 int qemu_main(int argc, char **argv, char **envp);
119 int main(int argc, char **argv)
121 return qemu_main(argc, argv, NULL);
124 #define main qemu_main
126 #endif /* CONFIG_SDL */
130 #define main qemu_main
131 #endif /* CONFIG_COCOA */
134 #include "hw/boards.h"
136 #include "hw/pcmcia.h"
138 #include "hw/audiodev.h"
142 #include "hw/watchdog.h"
143 #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"
164 #include "exec-all.h"
166 #include "qemu_socket.h"
168 #include "slirp/libslirp.h"
171 //#define DEBUG_SLIRP
173 #define DEFAULT_RAM_SIZE 128
175 /* Max number of USB devices that can be specified on the commandline. */
176 #define MAX_USB_CMDLINE 8
178 /* Max number of bluetooth switches on the commandline. */
179 #define MAX_BT_CMDLINE 10
181 static const char *data_dir;
182 const char *bios_name = NULL;
183 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
184 to store the VM snapshots */
185 DriveInfo drives_table[MAX_DRIVES+1];
187 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
188 static DisplayState *display_state;
189 DisplayType display_type = DT_DEFAULT;
190 const char* keyboard_layout = NULL;
191 int64_t ticks_per_sec;
194 NICInfo nd_table[MAX_NICS];
196 static int autostart;
197 static int rtc_utc = 1;
198 static int rtc_date_offset = -1; /* -1 means no change */
199 int cirrus_vga_enabled = 1;
200 int std_vga_enabled = 0;
201 int vmsvga_enabled = 0;
202 int xenfb_enabled = 0;
204 int graphic_width = 1024;
205 int graphic_height = 768;
206 int graphic_depth = 8;
208 int graphic_width = 800;
209 int graphic_height = 600;
210 int graphic_depth = 15;
212 static int full_screen = 0;
214 static int no_frame = 0;
217 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
218 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
219 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
221 int win2k_install_hack = 0;
227 const char *vnc_display;
228 int acpi_enabled = 1;
230 int virtio_balloon = 1;
231 const char *virtio_balloon_devaddr;
236 int graphic_rotate = 0;
240 WatchdogTimerModel *watchdog = NULL;
241 int watchdog_action = WDT_RESET;
242 const char *option_rom[MAX_OPTION_ROMS];
244 int semihosting_enabled = 0;
248 const char *qemu_name;
250 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
251 unsigned int nb_prom_envs = 0;
252 const char *prom_envs[MAX_PROM_ENVS];
255 struct drive_opt drives_opt[MAX_DRIVES];
258 uint64_t node_mem[MAX_NODES];
259 uint64_t node_cpumask[MAX_NODES];
261 static CPUState *cur_cpu;
262 static CPUState *next_cpu;
263 static int timer_alarm_pending = 1;
264 /* Conversion factor from emulated instructions to virtual clock ticks. */
265 static int icount_time_shift;
266 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
267 #define MAX_ICOUNT_SHIFT 10
268 /* Compensate for varying guest execution speed. */
269 static int64_t qemu_icount_bias;
270 static QEMUTimer *icount_rt_timer;
271 static QEMUTimer *icount_vm_timer;
272 static QEMUTimer *nographic_timer;
274 uint8_t qemu_uuid[16];
276 /***********************************************************/
277 /* x86 ISA bus support */
279 target_phys_addr_t isa_mem_base = 0;
282 /***********************************************************/
283 void hw_error(const char *fmt, ...)
289 fprintf(stderr, "qemu: hardware error: ");
290 vfprintf(stderr, fmt, ap);
291 fprintf(stderr, "\n");
292 for(env = first_cpu; env != NULL; env = env->next_cpu) {
293 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
295 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
297 cpu_dump_state(env, stderr, fprintf, 0);
307 static QEMUBalloonEvent *qemu_balloon_event;
308 void *qemu_balloon_event_opaque;
310 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
312 qemu_balloon_event = func;
313 qemu_balloon_event_opaque = opaque;
316 void qemu_balloon(ram_addr_t target)
318 if (qemu_balloon_event)
319 qemu_balloon_event(qemu_balloon_event_opaque, target);
322 ram_addr_t qemu_balloon_status(void)
324 if (qemu_balloon_event)
325 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
329 /***********************************************************/
332 static QEMUPutKBDEvent *qemu_put_kbd_event;
333 static void *qemu_put_kbd_event_opaque;
334 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
335 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
337 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
339 qemu_put_kbd_event_opaque = opaque;
340 qemu_put_kbd_event = func;
343 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
344 void *opaque, int absolute,
347 QEMUPutMouseEntry *s, *cursor;
349 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
351 s->qemu_put_mouse_event = func;
352 s->qemu_put_mouse_event_opaque = opaque;
353 s->qemu_put_mouse_event_absolute = absolute;
354 s->qemu_put_mouse_event_name = qemu_strdup(name);
357 if (!qemu_put_mouse_event_head) {
358 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
362 cursor = qemu_put_mouse_event_head;
363 while (cursor->next != NULL)
364 cursor = cursor->next;
367 qemu_put_mouse_event_current = s;
372 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
374 QEMUPutMouseEntry *prev = NULL, *cursor;
376 if (!qemu_put_mouse_event_head || entry == NULL)
379 cursor = qemu_put_mouse_event_head;
380 while (cursor != NULL && cursor != entry) {
382 cursor = cursor->next;
385 if (cursor == NULL) // does not exist or list empty
387 else if (prev == NULL) { // entry is head
388 qemu_put_mouse_event_head = cursor->next;
389 if (qemu_put_mouse_event_current == entry)
390 qemu_put_mouse_event_current = cursor->next;
391 qemu_free(entry->qemu_put_mouse_event_name);
396 prev->next = entry->next;
398 if (qemu_put_mouse_event_current == entry)
399 qemu_put_mouse_event_current = prev;
401 qemu_free(entry->qemu_put_mouse_event_name);
405 void kbd_put_keycode(int keycode)
407 if (qemu_put_kbd_event) {
408 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
412 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
414 QEMUPutMouseEvent *mouse_event;
415 void *mouse_event_opaque;
418 if (!qemu_put_mouse_event_current) {
423 qemu_put_mouse_event_current->qemu_put_mouse_event;
425 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
428 if (graphic_rotate) {
429 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
432 width = graphic_width - 1;
433 mouse_event(mouse_event_opaque,
434 width - dy, dx, dz, buttons_state);
436 mouse_event(mouse_event_opaque,
437 dx, dy, dz, buttons_state);
441 int kbd_mouse_is_absolute(void)
443 if (!qemu_put_mouse_event_current)
446 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
449 void do_info_mice(Monitor *mon)
451 QEMUPutMouseEntry *cursor;
454 if (!qemu_put_mouse_event_head) {
455 monitor_printf(mon, "No mouse devices connected\n");
459 monitor_printf(mon, "Mouse devices available:\n");
460 cursor = qemu_put_mouse_event_head;
461 while (cursor != NULL) {
462 monitor_printf(mon, "%c Mouse #%d: %s\n",
463 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
464 index, cursor->qemu_put_mouse_event_name);
466 cursor = cursor->next;
470 void do_mouse_set(Monitor *mon, int index)
472 QEMUPutMouseEntry *cursor;
475 if (!qemu_put_mouse_event_head) {
476 monitor_printf(mon, "No mouse devices connected\n");
480 cursor = qemu_put_mouse_event_head;
481 while (cursor != NULL && index != i) {
483 cursor = cursor->next;
487 qemu_put_mouse_event_current = cursor;
489 monitor_printf(mon, "Mouse at given index not found\n");
492 /* compute with 96 bit intermediate result: (a*b)/c */
493 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
498 #ifdef WORDS_BIGENDIAN
508 rl = (uint64_t)u.l.low * (uint64_t)b;
509 rh = (uint64_t)u.l.high * (uint64_t)b;
512 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
516 /***********************************************************/
517 /* real time host monotonic timer */
519 #define QEMU_TIMER_BASE 1000000000LL
523 static int64_t clock_freq;
525 static void init_get_clock(void)
529 ret = QueryPerformanceFrequency(&freq);
531 fprintf(stderr, "Could not calibrate ticks\n");
534 clock_freq = freq.QuadPart;
537 static int64_t get_clock(void)
540 QueryPerformanceCounter(&ti);
541 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
546 static int use_rt_clock;
548 static void init_get_clock(void)
551 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
552 || defined(__DragonFly__)
555 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
562 static int64_t get_clock(void)
564 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
565 || defined(__DragonFly__)
568 clock_gettime(CLOCK_MONOTONIC, &ts);
569 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
573 /* XXX: using gettimeofday leads to problems if the date
574 changes, so it should be avoided. */
576 gettimeofday(&tv, NULL);
577 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
582 /* Return the virtual CPU time, based on the instruction counter. */
583 static int64_t cpu_get_icount(void)
586 CPUState *env = cpu_single_env;;
587 icount = qemu_icount;
590 fprintf(stderr, "Bad clock read\n");
591 icount -= (env->icount_decr.u16.low + env->icount_extra);
593 return qemu_icount_bias + (icount << icount_time_shift);
596 /***********************************************************/
597 /* guest cycle counter */
599 static int64_t cpu_ticks_prev;
600 static int64_t cpu_ticks_offset;
601 static int64_t cpu_clock_offset;
602 static int cpu_ticks_enabled;
604 /* return the host CPU cycle counter and handle stop/restart */
605 int64_t cpu_get_ticks(void)
608 return cpu_get_icount();
610 if (!cpu_ticks_enabled) {
611 return cpu_ticks_offset;
614 ticks = cpu_get_real_ticks();
615 if (cpu_ticks_prev > ticks) {
616 /* Note: non increasing ticks may happen if the host uses
618 cpu_ticks_offset += cpu_ticks_prev - ticks;
620 cpu_ticks_prev = ticks;
621 return ticks + cpu_ticks_offset;
625 /* return the host CPU monotonic timer and handle stop/restart */
626 static int64_t cpu_get_clock(void)
629 if (!cpu_ticks_enabled) {
630 return cpu_clock_offset;
633 return ti + cpu_clock_offset;
637 /* enable cpu_get_ticks() */
638 void cpu_enable_ticks(void)
640 if (!cpu_ticks_enabled) {
641 cpu_ticks_offset -= cpu_get_real_ticks();
642 cpu_clock_offset -= get_clock();
643 cpu_ticks_enabled = 1;
647 /* disable cpu_get_ticks() : the clock is stopped. You must not call
648 cpu_get_ticks() after that. */
649 void cpu_disable_ticks(void)
651 if (cpu_ticks_enabled) {
652 cpu_ticks_offset = cpu_get_ticks();
653 cpu_clock_offset = cpu_get_clock();
654 cpu_ticks_enabled = 0;
658 /***********************************************************/
661 #define QEMU_TIMER_REALTIME 0
662 #define QEMU_TIMER_VIRTUAL 1
666 /* XXX: add frequency */
674 struct QEMUTimer *next;
677 struct qemu_alarm_timer {
681 int (*start)(struct qemu_alarm_timer *t);
682 void (*stop)(struct qemu_alarm_timer *t);
683 void (*rearm)(struct qemu_alarm_timer *t);
687 #define ALARM_FLAG_DYNTICKS 0x1
688 #define ALARM_FLAG_EXPIRED 0x2
690 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
692 return t && (t->flags & ALARM_FLAG_DYNTICKS);
695 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
697 if (!alarm_has_dynticks(t))
703 /* TODO: MIN_TIMER_REARM_US should be optimized */
704 #define MIN_TIMER_REARM_US 250
706 static struct qemu_alarm_timer *alarm_timer;
710 struct qemu_alarm_win32 {
713 } alarm_win32_data = {0, -1};
715 static int win32_start_timer(struct qemu_alarm_timer *t);
716 static void win32_stop_timer(struct qemu_alarm_timer *t);
717 static void win32_rearm_timer(struct qemu_alarm_timer *t);
721 static int unix_start_timer(struct qemu_alarm_timer *t);
722 static void unix_stop_timer(struct qemu_alarm_timer *t);
726 static int dynticks_start_timer(struct qemu_alarm_timer *t);
727 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
728 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
730 static int hpet_start_timer(struct qemu_alarm_timer *t);
731 static void hpet_stop_timer(struct qemu_alarm_timer *t);
733 static int rtc_start_timer(struct qemu_alarm_timer *t);
734 static void rtc_stop_timer(struct qemu_alarm_timer *t);
736 #endif /* __linux__ */
740 /* Correlation between real and virtual time is always going to be
741 fairly approximate, so ignore small variation.
742 When the guest is idle real and virtual time will be aligned in
744 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
746 static void icount_adjust(void)
751 static int64_t last_delta;
752 /* If the VM is not running, then do nothing. */
756 cur_time = cpu_get_clock();
757 cur_icount = qemu_get_clock(vm_clock);
758 delta = cur_icount - cur_time;
759 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
761 && last_delta + ICOUNT_WOBBLE < delta * 2
762 && icount_time_shift > 0) {
763 /* The guest is getting too far ahead. Slow time down. */
767 && last_delta - ICOUNT_WOBBLE > delta * 2
768 && icount_time_shift < MAX_ICOUNT_SHIFT) {
769 /* The guest is getting too far behind. Speed time up. */
773 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
776 static void icount_adjust_rt(void * opaque)
778 qemu_mod_timer(icount_rt_timer,
779 qemu_get_clock(rt_clock) + 1000);
783 static void icount_adjust_vm(void * opaque)
785 qemu_mod_timer(icount_vm_timer,
786 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
790 static void init_icount_adjust(void)
792 /* Have both realtime and virtual time triggers for speed adjustment.
793 The realtime trigger catches emulated time passing too slowly,
794 the virtual time trigger catches emulated time passing too fast.
795 Realtime triggers occur even when idle, so use them less frequently
797 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
798 qemu_mod_timer(icount_rt_timer,
799 qemu_get_clock(rt_clock) + 1000);
800 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
801 qemu_mod_timer(icount_vm_timer,
802 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
805 static struct qemu_alarm_timer alarm_timers[] = {
808 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
809 dynticks_stop_timer, dynticks_rearm_timer, NULL},
810 /* HPET - if available - is preferred */
811 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
812 /* ...otherwise try RTC */
813 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
815 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
817 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
818 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
819 {"win32", 0, win32_start_timer,
820 win32_stop_timer, NULL, &alarm_win32_data},
825 static void show_available_alarms(void)
829 printf("Available alarm timers, in order of precedence:\n");
830 for (i = 0; alarm_timers[i].name; i++)
831 printf("%s\n", alarm_timers[i].name);
834 static void configure_alarms(char const *opt)
838 int count = ARRAY_SIZE(alarm_timers) - 1;
841 struct qemu_alarm_timer tmp;
843 if (!strcmp(opt, "?")) {
844 show_available_alarms();
850 /* Reorder the array */
851 name = strtok(arg, ",");
853 for (i = 0; i < count && alarm_timers[i].name; i++) {
854 if (!strcmp(alarm_timers[i].name, name))
859 fprintf(stderr, "Unknown clock %s\n", name);
868 tmp = alarm_timers[i];
869 alarm_timers[i] = alarm_timers[cur];
870 alarm_timers[cur] = tmp;
874 name = strtok(NULL, ",");
880 /* Disable remaining timers */
881 for (i = cur; i < count; i++)
882 alarm_timers[i].name = NULL;
884 show_available_alarms();
892 static QEMUTimer *active_timers[2];
894 static QEMUClock *qemu_new_clock(int type)
897 clock = qemu_mallocz(sizeof(QEMUClock));
902 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
906 ts = qemu_mallocz(sizeof(QEMUTimer));
913 void qemu_free_timer(QEMUTimer *ts)
918 /* stop a timer, but do not dealloc it */
919 void qemu_del_timer(QEMUTimer *ts)
923 /* NOTE: this code must be signal safe because
924 qemu_timer_expired() can be called from a signal. */
925 pt = &active_timers[ts->clock->type];
938 /* modify the current timer so that it will be fired when current_time
939 >= expire_time. The corresponding callback will be called. */
940 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
946 /* add the timer in the sorted list */
947 /* NOTE: this code must be signal safe because
948 qemu_timer_expired() can be called from a signal. */
949 pt = &active_timers[ts->clock->type];
954 if (t->expire_time > expire_time)
958 ts->expire_time = expire_time;
962 /* Rearm if necessary */
963 if (pt == &active_timers[ts->clock->type]) {
964 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
965 qemu_rearm_alarm_timer(alarm_timer);
967 /* Interrupt execution to force deadline recalculation. */
973 int qemu_timer_pending(QEMUTimer *ts)
976 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
983 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
987 return (timer_head->expire_time <= current_time);
990 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
996 if (!ts || ts->expire_time > current_time)
998 /* remove timer from the list before calling the callback */
999 *ptimer_head = ts->next;
1002 /* run the callback (the timer list can be modified) */
1007 int64_t qemu_get_clock(QEMUClock *clock)
1009 switch(clock->type) {
1010 case QEMU_TIMER_REALTIME:
1011 return get_clock() / 1000000;
1013 case QEMU_TIMER_VIRTUAL:
1015 return cpu_get_icount();
1017 return cpu_get_clock();
1022 static void init_timers(void)
1025 ticks_per_sec = QEMU_TIMER_BASE;
1026 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1027 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1031 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1033 uint64_t expire_time;
1035 if (qemu_timer_pending(ts)) {
1036 expire_time = ts->expire_time;
1040 qemu_put_be64(f, expire_time);
1043 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1045 uint64_t expire_time;
1047 expire_time = qemu_get_be64(f);
1048 if (expire_time != -1) {
1049 qemu_mod_timer(ts, expire_time);
1055 static void timer_save(QEMUFile *f, void *opaque)
1057 if (cpu_ticks_enabled) {
1058 hw_error("cannot save state if virtual timers are running");
1060 qemu_put_be64(f, cpu_ticks_offset);
1061 qemu_put_be64(f, ticks_per_sec);
1062 qemu_put_be64(f, cpu_clock_offset);
1065 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1067 if (version_id != 1 && version_id != 2)
1069 if (cpu_ticks_enabled) {
1072 cpu_ticks_offset=qemu_get_be64(f);
1073 ticks_per_sec=qemu_get_be64(f);
1074 if (version_id == 2) {
1075 cpu_clock_offset=qemu_get_be64(f);
1080 static void qemu_event_increment(void);
1083 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1084 DWORD_PTR dwUser, DWORD_PTR dw1,
1087 static void host_alarm_handler(int host_signum)
1091 #define DISP_FREQ 1000
1093 static int64_t delta_min = INT64_MAX;
1094 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1096 ti = qemu_get_clock(vm_clock);
1097 if (last_clock != 0) {
1098 delta = ti - last_clock;
1099 if (delta < delta_min)
1101 if (delta > delta_max)
1104 if (++count == DISP_FREQ) {
1105 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1106 muldiv64(delta_min, 1000000, ticks_per_sec),
1107 muldiv64(delta_max, 1000000, ticks_per_sec),
1108 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1109 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1111 delta_min = INT64_MAX;
1119 if (alarm_has_dynticks(alarm_timer) ||
1121 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1122 qemu_get_clock(vm_clock))) ||
1123 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1124 qemu_get_clock(rt_clock))) {
1125 qemu_event_increment();
1126 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1128 #ifndef CONFIG_IOTHREAD
1130 /* stop the currently executing cpu because a timer occured */
1133 if (next_cpu->kqemu_enabled) {
1134 kqemu_cpu_interrupt(next_cpu);
1139 timer_alarm_pending = 1;
1140 qemu_notify_event();
1144 static int64_t qemu_next_deadline(void)
1148 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1149 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1150 qemu_get_clock(vm_clock);
1152 /* To avoid problems with overflow limit this to 2^32. */
1162 #if defined(__linux__) || defined(_WIN32)
1163 static uint64_t qemu_next_deadline_dyntick(void)
1171 delta = (qemu_next_deadline() + 999) / 1000;
1173 if (active_timers[QEMU_TIMER_REALTIME]) {
1174 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1175 qemu_get_clock(rt_clock))*1000;
1176 if (rtdelta < delta)
1180 if (delta < MIN_TIMER_REARM_US)
1181 delta = MIN_TIMER_REARM_US;
1189 /* Sets a specific flag */
1190 static int fcntl_setfl(int fd, int flag)
1194 flags = fcntl(fd, F_GETFL);
1198 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1204 #if defined(__linux__)
1206 #define RTC_FREQ 1024
1208 static void enable_sigio_timer(int fd)
1210 struct sigaction act;
1213 sigfillset(&act.sa_mask);
1215 act.sa_handler = host_alarm_handler;
1217 sigaction(SIGIO, &act, NULL);
1218 fcntl_setfl(fd, O_ASYNC);
1219 fcntl(fd, F_SETOWN, getpid());
1222 static int hpet_start_timer(struct qemu_alarm_timer *t)
1224 struct hpet_info info;
1227 fd = open("/dev/hpet", O_RDONLY);
1232 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1234 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1235 "error, but for better emulation accuracy type:\n"
1236 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1240 /* Check capabilities */
1241 r = ioctl(fd, HPET_INFO, &info);
1245 /* Enable periodic mode */
1246 r = ioctl(fd, HPET_EPI, 0);
1247 if (info.hi_flags && (r < 0))
1250 /* Enable interrupt */
1251 r = ioctl(fd, HPET_IE_ON, 0);
1255 enable_sigio_timer(fd);
1256 t->priv = (void *)(long)fd;
1264 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1266 int fd = (long)t->priv;
1271 static int rtc_start_timer(struct qemu_alarm_timer *t)
1274 unsigned long current_rtc_freq = 0;
1276 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1279 ioctl(rtc_fd, RTC_IRQP_READ, ¤t_rtc_freq);
1280 if (current_rtc_freq != RTC_FREQ &&
1281 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1282 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1283 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1284 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1287 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1293 enable_sigio_timer(rtc_fd);
1295 t->priv = (void *)(long)rtc_fd;
1300 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1302 int rtc_fd = (long)t->priv;
1307 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1311 struct sigaction act;
1313 sigfillset(&act.sa_mask);
1315 act.sa_handler = host_alarm_handler;
1317 sigaction(SIGALRM, &act, NULL);
1320 * Initialize ev struct to 0 to avoid valgrind complaining
1321 * about uninitialized data in timer_create call
1323 memset(&ev, 0, sizeof(ev));
1324 ev.sigev_value.sival_int = 0;
1325 ev.sigev_notify = SIGEV_SIGNAL;
1326 ev.sigev_signo = SIGALRM;
1328 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1329 perror("timer_create");
1331 /* disable dynticks */
1332 fprintf(stderr, "Dynamic Ticks disabled\n");
1337 t->priv = (void *)(long)host_timer;
1342 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1344 timer_t host_timer = (timer_t)(long)t->priv;
1346 timer_delete(host_timer);
1349 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1351 timer_t host_timer = (timer_t)(long)t->priv;
1352 struct itimerspec timeout;
1353 int64_t nearest_delta_us = INT64_MAX;
1356 if (!active_timers[QEMU_TIMER_REALTIME] &&
1357 !active_timers[QEMU_TIMER_VIRTUAL])
1360 nearest_delta_us = qemu_next_deadline_dyntick();
1362 /* check whether a timer is already running */
1363 if (timer_gettime(host_timer, &timeout)) {
1365 fprintf(stderr, "Internal timer error: aborting\n");
1368 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1369 if (current_us && current_us <= nearest_delta_us)
1372 timeout.it_interval.tv_sec = 0;
1373 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1374 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1375 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1376 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1378 fprintf(stderr, "Internal timer error: aborting\n");
1383 #endif /* defined(__linux__) */
1385 static int unix_start_timer(struct qemu_alarm_timer *t)
1387 struct sigaction act;
1388 struct itimerval itv;
1392 sigfillset(&act.sa_mask);
1394 act.sa_handler = host_alarm_handler;
1396 sigaction(SIGALRM, &act, NULL);
1398 itv.it_interval.tv_sec = 0;
1399 /* for i386 kernel 2.6 to get 1 ms */
1400 itv.it_interval.tv_usec = 999;
1401 itv.it_value.tv_sec = 0;
1402 itv.it_value.tv_usec = 10 * 1000;
1404 err = setitimer(ITIMER_REAL, &itv, NULL);
1411 static void unix_stop_timer(struct qemu_alarm_timer *t)
1413 struct itimerval itv;
1415 memset(&itv, 0, sizeof(itv));
1416 setitimer(ITIMER_REAL, &itv, NULL);
1419 #endif /* !defined(_WIN32) */
1424 static int win32_start_timer(struct qemu_alarm_timer *t)
1427 struct qemu_alarm_win32 *data = t->priv;
1430 memset(&tc, 0, sizeof(tc));
1431 timeGetDevCaps(&tc, sizeof(tc));
1433 if (data->period < tc.wPeriodMin)
1434 data->period = tc.wPeriodMin;
1436 timeBeginPeriod(data->period);
1438 flags = TIME_CALLBACK_FUNCTION;
1439 if (alarm_has_dynticks(t))
1440 flags |= TIME_ONESHOT;
1442 flags |= TIME_PERIODIC;
1444 data->timerId = timeSetEvent(1, // interval (ms)
1445 data->period, // resolution
1446 host_alarm_handler, // function
1447 (DWORD)t, // parameter
1450 if (!data->timerId) {
1451 perror("Failed to initialize win32 alarm timer");
1452 timeEndPeriod(data->period);
1459 static void win32_stop_timer(struct qemu_alarm_timer *t)
1461 struct qemu_alarm_win32 *data = t->priv;
1463 timeKillEvent(data->timerId);
1464 timeEndPeriod(data->period);
1467 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1469 struct qemu_alarm_win32 *data = t->priv;
1470 uint64_t nearest_delta_us;
1472 if (!active_timers[QEMU_TIMER_REALTIME] &&
1473 !active_timers[QEMU_TIMER_VIRTUAL])
1476 nearest_delta_us = qemu_next_deadline_dyntick();
1477 nearest_delta_us /= 1000;
1479 timeKillEvent(data->timerId);
1481 data->timerId = timeSetEvent(1,
1485 TIME_ONESHOT | TIME_PERIODIC);
1487 if (!data->timerId) {
1488 perror("Failed to re-arm win32 alarm timer");
1490 timeEndPeriod(data->period);
1497 static int init_timer_alarm(void)
1499 struct qemu_alarm_timer *t = NULL;
1502 for (i = 0; alarm_timers[i].name; i++) {
1503 t = &alarm_timers[i];
1523 static void quit_timers(void)
1525 alarm_timer->stop(alarm_timer);
1529 /***********************************************************/
1530 /* host time/date access */
1531 void qemu_get_timedate(struct tm *tm, int offset)
1538 if (rtc_date_offset == -1) {
1542 ret = localtime(&ti);
1544 ti -= rtc_date_offset;
1548 memcpy(tm, ret, sizeof(struct tm));
1551 int qemu_timedate_diff(struct tm *tm)
1555 if (rtc_date_offset == -1)
1557 seconds = mktimegm(tm);
1559 seconds = mktime(tm);
1561 seconds = mktimegm(tm) + rtc_date_offset;
1563 return seconds - time(NULL);
1567 static void socket_cleanup(void)
1572 static int socket_init(void)
1577 ret = WSAStartup(MAKEWORD(2,2), &Data);
1579 err = WSAGetLastError();
1580 fprintf(stderr, "WSAStartup: %d\n", err);
1583 atexit(socket_cleanup);
1588 int get_next_param_value(char *buf, int buf_size,
1589 const char *tag, const char **pstr)
1596 p = get_opt_name(option, sizeof(option), p, '=');
1600 if (!strcmp(tag, option)) {
1601 *pstr = get_opt_value(buf, buf_size, p);
1602 if (**pstr == ',') {
1607 p = get_opt_value(NULL, 0, p);
1616 int get_param_value(char *buf, int buf_size,
1617 const char *tag, const char *str)
1619 return get_next_param_value(buf, buf_size, tag, &str);
1622 int check_params(char *buf, int buf_size,
1623 const char * const *params, const char *str)
1629 while (*p != '\0') {
1630 p = get_opt_name(buf, buf_size, p, '=');
1635 for (i = 0; params[i] != NULL; i++) {
1636 if (!strcmp(params[i], buf)) {
1640 if (params[i] == NULL) {
1643 p = get_opt_value(NULL, 0, p);
1652 /***********************************************************/
1653 /* Bluetooth support */
1656 static struct HCIInfo *hci_table[MAX_NICS];
1658 static struct bt_vlan_s {
1659 struct bt_scatternet_s net;
1661 struct bt_vlan_s *next;
1664 /* find or alloc a new bluetooth "VLAN" */
1665 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1667 struct bt_vlan_s **pvlan, *vlan;
1668 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1672 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1674 pvlan = &first_bt_vlan;
1675 while (*pvlan != NULL)
1676 pvlan = &(*pvlan)->next;
1681 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1685 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1690 static struct HCIInfo null_hci = {
1691 .cmd_send = null_hci_send,
1692 .sco_send = null_hci_send,
1693 .acl_send = null_hci_send,
1694 .bdaddr_set = null_hci_addr_set,
1697 struct HCIInfo *qemu_next_hci(void)
1699 if (cur_hci == nb_hcis)
1702 return hci_table[cur_hci++];
1705 static struct HCIInfo *hci_init(const char *str)
1708 struct bt_scatternet_s *vlan = 0;
1710 if (!strcmp(str, "null"))
1713 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1715 return bt_host_hci(str[4] ? str + 5 : "hci0");
1716 else if (!strncmp(str, "hci", 3)) {
1719 if (!strncmp(str + 3, ",vlan=", 6)) {
1720 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1725 vlan = qemu_find_bt_vlan(0);
1727 return bt_new_hci(vlan);
1730 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1735 static int bt_hci_parse(const char *str)
1737 struct HCIInfo *hci;
1740 if (nb_hcis >= MAX_NICS) {
1741 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1745 hci = hci_init(str);
1754 bdaddr.b[5] = 0x56 + nb_hcis;
1755 hci->bdaddr_set(hci, bdaddr.b);
1757 hci_table[nb_hcis++] = hci;
1762 static void bt_vhci_add(int vlan_id)
1764 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1767 fprintf(stderr, "qemu: warning: adding a VHCI to "
1768 "an empty scatternet %i\n", vlan_id);
1770 bt_vhci_init(bt_new_hci(vlan));
1773 static struct bt_device_s *bt_device_add(const char *opt)
1775 struct bt_scatternet_s *vlan;
1777 char *endp = strstr(opt, ",vlan=");
1778 int len = (endp ? endp - opt : strlen(opt)) + 1;
1781 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1784 vlan_id = strtol(endp + 6, &endp, 0);
1786 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1791 vlan = qemu_find_bt_vlan(vlan_id);
1794 fprintf(stderr, "qemu: warning: adding a slave device to "
1795 "an empty scatternet %i\n", vlan_id);
1797 if (!strcmp(devname, "keyboard"))
1798 return bt_keyboard_init(vlan);
1800 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1804 static int bt_parse(const char *opt)
1806 const char *endp, *p;
1809 if (strstart(opt, "hci", &endp)) {
1810 if (!*endp || *endp == ',') {
1812 if (!strstart(endp, ",vlan=", 0))
1815 return bt_hci_parse(opt);
1817 } else if (strstart(opt, "vhci", &endp)) {
1818 if (!*endp || *endp == ',') {
1820 if (strstart(endp, ",vlan=", &p)) {
1821 vlan = strtol(p, (char **) &endp, 0);
1823 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1827 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1836 } else if (strstart(opt, "device:", &endp))
1837 return !bt_device_add(endp);
1839 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1843 /***********************************************************/
1844 /* QEMU Block devices */
1846 #define HD_ALIAS "index=%d,media=disk"
1847 #define CDROM_ALIAS "index=2,media=cdrom"
1848 #define FD_ALIAS "index=%d,if=floppy"
1849 #define PFLASH_ALIAS "if=pflash"
1850 #define MTD_ALIAS "if=mtd"
1851 #define SD_ALIAS "index=0,if=sd"
1853 static int drive_opt_get_free_idx(void)
1857 for (index = 0; index < MAX_DRIVES; index++)
1858 if (!drives_opt[index].used) {
1859 drives_opt[index].used = 1;
1866 static int drive_get_free_idx(void)
1870 for (index = 0; index < MAX_DRIVES; index++)
1871 if (!drives_table[index].used) {
1872 drives_table[index].used = 1;
1879 int drive_add(const char *file, const char *fmt, ...)
1882 int index = drive_opt_get_free_idx();
1884 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
1885 fprintf(stderr, "qemu: too many drives\n");
1889 drives_opt[index].file = file;
1891 vsnprintf(drives_opt[index].opt,
1892 sizeof(drives_opt[0].opt), fmt, ap);
1899 void drive_remove(int index)
1901 drives_opt[index].used = 0;
1905 int drive_get_index(BlockInterfaceType type, int bus, int unit)
1909 /* seek interface, bus and unit */
1911 for (index = 0; index < MAX_DRIVES; index++)
1912 if (drives_table[index].type == type &&
1913 drives_table[index].bus == bus &&
1914 drives_table[index].unit == unit &&
1915 drives_table[index].used)
1921 int drive_get_max_bus(BlockInterfaceType type)
1927 for (index = 0; index < nb_drives; index++) {
1928 if(drives_table[index].type == type &&
1929 drives_table[index].bus > max_bus)
1930 max_bus = drives_table[index].bus;
1935 const char *drive_get_serial(BlockDriverState *bdrv)
1939 for (index = 0; index < nb_drives; index++)
1940 if (drives_table[index].bdrv == bdrv)
1941 return drives_table[index].serial;
1946 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1950 for (index = 0; index < nb_drives; index++)
1951 if (drives_table[index].bdrv == bdrv)
1952 return drives_table[index].onerror;
1954 return BLOCK_ERR_STOP_ENOSPC;
1957 static void bdrv_format_print(void *opaque, const char *name)
1959 fprintf(stderr, " %s", name);
1962 void drive_uninit(BlockDriverState *bdrv)
1966 for (i = 0; i < MAX_DRIVES; i++)
1967 if (drives_table[i].bdrv == bdrv) {
1968 drives_table[i].bdrv = NULL;
1969 drives_table[i].used = 0;
1970 drive_remove(drives_table[i].drive_opt_idx);
1976 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
1982 const char *mediastr = "";
1983 BlockInterfaceType type;
1984 enum { MEDIA_DISK, MEDIA_CDROM } media;
1985 int bus_id, unit_id;
1986 int cyls, heads, secs, translation;
1987 BlockDriverState *bdrv;
1988 BlockDriver *drv = NULL;
1989 QEMUMachine *machine = opaque;
1993 int bdrv_flags, onerror;
1994 const char *devaddr;
1995 int drives_table_idx;
1996 char *str = arg->opt;
1997 static const char * const params[] = { "bus", "unit", "if", "index",
1998 "cyls", "heads", "secs", "trans",
1999 "media", "snapshot", "file",
2000 "cache", "format", "serial",
2004 if (check_params(buf, sizeof(buf), params, str) < 0) {
2005 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2011 cyls = heads = secs = 0;
2014 translation = BIOS_ATA_TRANSLATION_AUTO;
2018 if (machine->use_scsi) {
2020 max_devs = MAX_SCSI_DEVS;
2021 pstrcpy(devname, sizeof(devname), "scsi");
2024 max_devs = MAX_IDE_DEVS;
2025 pstrcpy(devname, sizeof(devname), "ide");
2029 /* extract parameters */
2031 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2032 bus_id = strtol(buf, NULL, 0);
2034 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2039 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2040 unit_id = strtol(buf, NULL, 0);
2042 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2047 if (get_param_value(buf, sizeof(buf), "if", str)) {
2048 pstrcpy(devname, sizeof(devname), buf);
2049 if (!strcmp(buf, "ide")) {
2051 max_devs = MAX_IDE_DEVS;
2052 } else if (!strcmp(buf, "scsi")) {
2054 max_devs = MAX_SCSI_DEVS;
2055 } else if (!strcmp(buf, "floppy")) {
2058 } else if (!strcmp(buf, "pflash")) {
2061 } else if (!strcmp(buf, "mtd")) {
2064 } else if (!strcmp(buf, "sd")) {
2067 } else if (!strcmp(buf, "virtio")) {
2070 } else if (!strcmp(buf, "xen")) {
2074 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2079 if (get_param_value(buf, sizeof(buf), "index", str)) {
2080 index = strtol(buf, NULL, 0);
2082 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2087 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2088 cyls = strtol(buf, NULL, 0);
2091 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2092 heads = strtol(buf, NULL, 0);
2095 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2096 secs = strtol(buf, NULL, 0);
2099 if (cyls || heads || secs) {
2100 if (cyls < 1 || cyls > 16383) {
2101 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2104 if (heads < 1 || heads > 16) {
2105 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2108 if (secs < 1 || secs > 63) {
2109 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2114 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2117 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2121 if (!strcmp(buf, "none"))
2122 translation = BIOS_ATA_TRANSLATION_NONE;
2123 else if (!strcmp(buf, "lba"))
2124 translation = BIOS_ATA_TRANSLATION_LBA;
2125 else if (!strcmp(buf, "auto"))
2126 translation = BIOS_ATA_TRANSLATION_AUTO;
2128 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2133 if (get_param_value(buf, sizeof(buf), "media", str)) {
2134 if (!strcmp(buf, "disk")) {
2136 } else if (!strcmp(buf, "cdrom")) {
2137 if (cyls || secs || heads) {
2139 "qemu: '%s' invalid physical CHS format\n", str);
2142 media = MEDIA_CDROM;
2144 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2149 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2150 if (!strcmp(buf, "on"))
2152 else if (!strcmp(buf, "off"))
2155 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2160 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2161 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2163 else if (!strcmp(buf, "writethrough"))
2165 else if (!strcmp(buf, "writeback"))
2168 fprintf(stderr, "qemu: invalid cache option\n");
2173 if (get_param_value(buf, sizeof(buf), "format", str)) {
2174 if (strcmp(buf, "?") == 0) {
2175 fprintf(stderr, "qemu: Supported formats:");
2176 bdrv_iterate_format(bdrv_format_print, NULL);
2177 fprintf(stderr, "\n");
2180 drv = bdrv_find_format(buf);
2182 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2187 if (arg->file == NULL)
2188 get_param_value(file, sizeof(file), "file", str);
2190 pstrcpy(file, sizeof(file), arg->file);
2192 if (!get_param_value(serial, sizeof(serial), "serial", str))
2193 memset(serial, 0, sizeof(serial));
2195 onerror = BLOCK_ERR_STOP_ENOSPC;
2196 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2197 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2198 fprintf(stderr, "werror is no supported by this format\n");
2201 if (!strcmp(buf, "ignore"))
2202 onerror = BLOCK_ERR_IGNORE;
2203 else if (!strcmp(buf, "enospc"))
2204 onerror = BLOCK_ERR_STOP_ENOSPC;
2205 else if (!strcmp(buf, "stop"))
2206 onerror = BLOCK_ERR_STOP_ANY;
2207 else if (!strcmp(buf, "report"))
2208 onerror = BLOCK_ERR_REPORT;
2210 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2216 if (get_param_value(buf, sizeof(buf), "addr", str)) {
2217 if (type != IF_VIRTIO) {
2218 fprintf(stderr, "addr is not supported by in '%s'\n", str);
2221 devaddr = strdup(buf);
2224 /* compute bus and unit according index */
2227 if (bus_id != 0 || unit_id != -1) {
2229 "qemu: '%s' index cannot be used with bus and unit\n", str);
2237 unit_id = index % max_devs;
2238 bus_id = index / max_devs;
2242 /* if user doesn't specify a unit_id,
2243 * try to find the first free
2246 if (unit_id == -1) {
2248 while (drive_get_index(type, bus_id, unit_id) != -1) {
2250 if (max_devs && unit_id >= max_devs) {
2251 unit_id -= max_devs;
2259 if (max_devs && unit_id >= max_devs) {
2260 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2261 str, unit_id, max_devs - 1);
2266 * ignore multiple definitions
2269 if (drive_get_index(type, bus_id, unit_id) != -1)
2274 if (type == IF_IDE || type == IF_SCSI)
2275 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2277 snprintf(buf, sizeof(buf), "%s%i%s%i",
2278 devname, bus_id, mediastr, unit_id);
2280 snprintf(buf, sizeof(buf), "%s%s%i",
2281 devname, mediastr, unit_id);
2282 bdrv = bdrv_new(buf);
2283 drives_table_idx = drive_get_free_idx();
2284 drives_table[drives_table_idx].bdrv = bdrv;
2285 drives_table[drives_table_idx].devaddr = devaddr;
2286 drives_table[drives_table_idx].type = type;
2287 drives_table[drives_table_idx].bus = bus_id;
2288 drives_table[drives_table_idx].unit = unit_id;
2289 drives_table[drives_table_idx].onerror = onerror;
2290 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2291 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2301 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2302 bdrv_set_translation_hint(bdrv, translation);
2306 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2311 /* FIXME: This isn't really a floppy, but it's a reasonable
2314 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2327 bdrv_flags |= BDRV_O_SNAPSHOT;
2328 cache = 2; /* always use write-back with snapshot */
2330 if (cache == 0) /* no caching */
2331 bdrv_flags |= BDRV_O_NOCACHE;
2332 else if (cache == 2) /* write-back */
2333 bdrv_flags |= BDRV_O_CACHE_WB;
2334 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2335 fprintf(stderr, "qemu: could not open disk image %s\n",
2339 if (bdrv_key_required(bdrv))
2341 return drives_table_idx;
2344 static void numa_add(const char *optarg)
2348 unsigned long long value, endvalue;
2351 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2352 if (!strcmp(option, "node")) {
2353 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2354 nodenr = nb_numa_nodes;
2356 nodenr = strtoull(option, NULL, 10);
2359 if (get_param_value(option, 128, "mem", optarg) == 0) {
2360 node_mem[nodenr] = 0;
2362 value = strtoull(option, &endptr, 0);
2364 case 0: case 'M': case 'm':
2371 node_mem[nodenr] = value;
2373 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2374 node_cpumask[nodenr] = 0;
2376 value = strtoull(option, &endptr, 10);
2379 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2381 if (*endptr == '-') {
2382 endvalue = strtoull(endptr+1, &endptr, 10);
2383 if (endvalue >= 63) {
2386 "only 63 CPUs in NUMA mode supported.\n");
2388 value = (1 << (endvalue + 1)) - (1 << value);
2393 node_cpumask[nodenr] = value;
2400 /***********************************************************/
2403 static USBPort *used_usb_ports;
2404 static USBPort *free_usb_ports;
2406 /* ??? Maybe change this to register a hub to keep track of the topology. */
2407 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2408 usb_attachfn attach)
2410 port->opaque = opaque;
2411 port->index = index;
2412 port->attach = attach;
2413 port->next = free_usb_ports;
2414 free_usb_ports = port;
2417 int usb_device_add_dev(USBDevice *dev)
2421 /* Find a USB port to add the device to. */
2422 port = free_usb_ports;
2426 /* Create a new hub and chain it on. */
2427 free_usb_ports = NULL;
2428 port->next = used_usb_ports;
2429 used_usb_ports = port;
2431 hub = usb_hub_init(VM_USB_HUB_SIZE);
2432 usb_attach(port, hub);
2433 port = free_usb_ports;
2436 free_usb_ports = port->next;
2437 port->next = used_usb_ports;
2438 used_usb_ports = port;
2439 usb_attach(port, dev);
2443 static void usb_msd_password_cb(void *opaque, int err)
2445 USBDevice *dev = opaque;
2448 usb_device_add_dev(dev);
2450 dev->handle_destroy(dev);
2453 static int usb_device_add(const char *devname, int is_hotplug)
2458 if (!free_usb_ports)
2461 if (strstart(devname, "host:", &p)) {
2462 dev = usb_host_device_open(p);
2463 } else if (!strcmp(devname, "mouse")) {
2464 dev = usb_mouse_init();
2465 } else if (!strcmp(devname, "tablet")) {
2466 dev = usb_tablet_init();
2467 } else if (!strcmp(devname, "keyboard")) {
2468 dev = usb_keyboard_init();
2469 } else if (strstart(devname, "disk:", &p)) {
2470 BlockDriverState *bs;
2472 dev = usb_msd_init(p);
2475 bs = usb_msd_get_bdrv(dev);
2476 if (bdrv_key_required(bs)) {
2479 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2484 } else if (!strcmp(devname, "wacom-tablet")) {
2485 dev = usb_wacom_init();
2486 } else if (strstart(devname, "serial:", &p)) {
2487 dev = usb_serial_init(p);
2488 #ifdef CONFIG_BRLAPI
2489 } else if (!strcmp(devname, "braille")) {
2490 dev = usb_baum_init();
2492 } else if (strstart(devname, "net:", &p)) {
2495 if (net_client_init(NULL, "nic", p) < 0)
2497 nd_table[nic].model = "usb";
2498 dev = usb_net_init(&nd_table[nic]);
2499 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2500 dev = usb_bt_init(devname[2] ? hci_init(p) :
2501 bt_new_hci(qemu_find_bt_vlan(0)));
2508 return usb_device_add_dev(dev);
2511 int usb_device_del_addr(int bus_num, int addr)
2517 if (!used_usb_ports)
2523 lastp = &used_usb_ports;
2524 port = used_usb_ports;
2525 while (port && port->dev->addr != addr) {
2526 lastp = &port->next;
2534 *lastp = port->next;
2535 usb_attach(port, NULL);
2536 dev->handle_destroy(dev);
2537 port->next = free_usb_ports;
2538 free_usb_ports = port;
2542 static int usb_device_del(const char *devname)
2547 if (strstart(devname, "host:", &p))
2548 return usb_host_device_close(p);
2550 if (!used_usb_ports)
2553 p = strchr(devname, '.');
2556 bus_num = strtoul(devname, NULL, 0);
2557 addr = strtoul(p + 1, NULL, 0);
2559 return usb_device_del_addr(bus_num, addr);
2562 void do_usb_add(Monitor *mon, const char *devname)
2564 usb_device_add(devname, 1);
2567 void do_usb_del(Monitor *mon, const char *devname)
2569 usb_device_del(devname);
2572 void usb_info(Monitor *mon)
2576 const char *speed_str;
2579 monitor_printf(mon, "USB support not enabled\n");
2583 for (port = used_usb_ports; port; port = port->next) {
2587 switch(dev->speed) {
2591 case USB_SPEED_FULL:
2594 case USB_SPEED_HIGH:
2601 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2602 0, dev->addr, speed_str, dev->devname);
2606 /***********************************************************/
2607 /* PCMCIA/Cardbus */
2609 static struct pcmcia_socket_entry_s {
2610 PCMCIASocket *socket;
2611 struct pcmcia_socket_entry_s *next;
2612 } *pcmcia_sockets = 0;
2614 void pcmcia_socket_register(PCMCIASocket *socket)
2616 struct pcmcia_socket_entry_s *entry;
2618 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2619 entry->socket = socket;
2620 entry->next = pcmcia_sockets;
2621 pcmcia_sockets = entry;
2624 void pcmcia_socket_unregister(PCMCIASocket *socket)
2626 struct pcmcia_socket_entry_s *entry, **ptr;
2628 ptr = &pcmcia_sockets;
2629 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2630 if (entry->socket == socket) {
2636 void pcmcia_info(Monitor *mon)
2638 struct pcmcia_socket_entry_s *iter;
2640 if (!pcmcia_sockets)
2641 monitor_printf(mon, "No PCMCIA sockets\n");
2643 for (iter = pcmcia_sockets; iter; iter = iter->next)
2644 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2645 iter->socket->attached ? iter->socket->card_string :
2649 /***********************************************************/
2650 /* register display */
2652 struct DisplayAllocator default_allocator = {
2653 defaultallocator_create_displaysurface,
2654 defaultallocator_resize_displaysurface,
2655 defaultallocator_free_displaysurface
2658 void register_displaystate(DisplayState *ds)
2668 DisplayState *get_displaystate(void)
2670 return display_state;
2673 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2675 if(ds->allocator == &default_allocator) ds->allocator = da;
2676 return ds->allocator;
2681 static void dumb_display_init(void)
2683 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2684 ds->allocator = &default_allocator;
2685 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2686 register_displaystate(ds);
2689 /***********************************************************/
2692 typedef struct IOHandlerRecord {
2694 IOCanRWHandler *fd_read_poll;
2696 IOHandler *fd_write;
2699 /* temporary data */
2701 struct IOHandlerRecord *next;
2704 static IOHandlerRecord *first_io_handler;
2706 /* XXX: fd_read_poll should be suppressed, but an API change is
2707 necessary in the character devices to suppress fd_can_read(). */
2708 int qemu_set_fd_handler2(int fd,
2709 IOCanRWHandler *fd_read_poll,
2711 IOHandler *fd_write,
2714 IOHandlerRecord **pioh, *ioh;
2716 if (!fd_read && !fd_write) {
2717 pioh = &first_io_handler;
2722 if (ioh->fd == fd) {
2729 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2733 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2734 ioh->next = first_io_handler;
2735 first_io_handler = ioh;
2738 ioh->fd_read_poll = fd_read_poll;
2739 ioh->fd_read = fd_read;
2740 ioh->fd_write = fd_write;
2741 ioh->opaque = opaque;
2747 int qemu_set_fd_handler(int fd,
2749 IOHandler *fd_write,
2752 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2756 /***********************************************************/
2757 /* Polling handling */
2759 typedef struct PollingEntry {
2762 struct PollingEntry *next;
2765 static PollingEntry *first_polling_entry;
2767 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2769 PollingEntry **ppe, *pe;
2770 pe = qemu_mallocz(sizeof(PollingEntry));
2772 pe->opaque = opaque;
2773 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2778 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2780 PollingEntry **ppe, *pe;
2781 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2783 if (pe->func == func && pe->opaque == opaque) {
2791 /***********************************************************/
2792 /* Wait objects support */
2793 typedef struct WaitObjects {
2795 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2796 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2797 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2800 static WaitObjects wait_objects = {0};
2802 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2804 WaitObjects *w = &wait_objects;
2806 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2808 w->events[w->num] = handle;
2809 w->func[w->num] = func;
2810 w->opaque[w->num] = opaque;
2815 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2818 WaitObjects *w = &wait_objects;
2821 for (i = 0; i < w->num; i++) {
2822 if (w->events[i] == handle)
2825 w->events[i] = w->events[i + 1];
2826 w->func[i] = w->func[i + 1];
2827 w->opaque[i] = w->opaque[i + 1];
2835 /***********************************************************/
2836 /* ram save/restore */
2838 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2842 v = qemu_get_byte(f);
2845 if (qemu_get_buffer(f, buf, len) != len)
2849 v = qemu_get_byte(f);
2850 memset(buf, v, len);
2856 if (qemu_file_has_error(f))
2862 static int ram_load_v1(QEMUFile *f, void *opaque)
2867 if (qemu_get_be32(f) != last_ram_offset)
2869 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2870 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2877 #define BDRV_HASH_BLOCK_SIZE 1024
2878 #define IOBUF_SIZE 4096
2879 #define RAM_CBLOCK_MAGIC 0xfabe
2881 typedef struct RamDecompressState {
2884 uint8_t buf[IOBUF_SIZE];
2885 } RamDecompressState;
2887 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2890 memset(s, 0, sizeof(*s));
2892 ret = inflateInit(&s->zstream);
2898 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2902 s->zstream.avail_out = len;
2903 s->zstream.next_out = buf;
2904 while (s->zstream.avail_out > 0) {
2905 if (s->zstream.avail_in == 0) {
2906 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
2908 clen = qemu_get_be16(s->f);
2909 if (clen > IOBUF_SIZE)
2911 qemu_get_buffer(s->f, s->buf, clen);
2912 s->zstream.avail_in = clen;
2913 s->zstream.next_in = s->buf;
2915 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
2916 if (ret != Z_OK && ret != Z_STREAM_END) {
2923 static void ram_decompress_close(RamDecompressState *s)
2925 inflateEnd(&s->zstream);
2928 #define RAM_SAVE_FLAG_FULL 0x01
2929 #define RAM_SAVE_FLAG_COMPRESS 0x02
2930 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2931 #define RAM_SAVE_FLAG_PAGE 0x08
2932 #define RAM_SAVE_FLAG_EOS 0x10
2934 static int is_dup_page(uint8_t *page, uint8_t ch)
2936 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2937 uint32_t *array = (uint32_t *)page;
2940 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2941 if (array[i] != val)
2948 static int ram_save_block(QEMUFile *f)
2950 static ram_addr_t current_addr = 0;
2951 ram_addr_t saved_addr = current_addr;
2952 ram_addr_t addr = 0;
2955 while (addr < last_ram_offset) {
2956 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2959 cpu_physical_memory_reset_dirty(current_addr,
2960 current_addr + TARGET_PAGE_SIZE,
2961 MIGRATION_DIRTY_FLAG);
2963 p = qemu_get_ram_ptr(current_addr);
2965 if (is_dup_page(p, *p)) {
2966 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2967 qemu_put_byte(f, *p);
2969 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2970 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2976 addr += TARGET_PAGE_SIZE;
2977 current_addr = (saved_addr + addr) % last_ram_offset;
2983 static uint64_t bytes_transferred = 0;
2985 static ram_addr_t ram_save_remaining(void)
2988 ram_addr_t count = 0;
2990 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2991 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2998 uint64_t ram_bytes_remaining(void)
3000 return ram_save_remaining() * TARGET_PAGE_SIZE;
3003 uint64_t ram_bytes_transferred(void)
3005 return bytes_transferred;
3008 uint64_t ram_bytes_total(void)
3010 return last_ram_offset;
3013 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3016 uint64_t bytes_transferred_last;
3018 uint64_t expected_time = 0;
3020 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3021 qemu_file_set_error(f);
3026 /* Make sure all dirty bits are set */
3027 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3028 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3029 cpu_physical_memory_set_dirty(addr);
3032 /* Enable dirty memory tracking */
3033 cpu_physical_memory_set_dirty_tracking(1);
3035 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3038 bytes_transferred_last = bytes_transferred;
3039 bwidth = get_clock();
3041 while (!qemu_file_rate_limit(f)) {
3044 ret = ram_save_block(f);
3045 bytes_transferred += ret * TARGET_PAGE_SIZE;
3046 if (ret == 0) /* no more blocks */
3050 bwidth = get_clock() - bwidth;
3051 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3053 /* if we haven't transferred anything this round, force expected_time to a
3054 * a very high value, but without crashing */
3058 /* try transferring iterative blocks of memory */
3062 /* flush all remaining blocks regardless of rate limiting */
3063 while (ram_save_block(f) != 0) {
3064 bytes_transferred += TARGET_PAGE_SIZE;
3066 cpu_physical_memory_set_dirty_tracking(0);
3069 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3071 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3073 return (stage == 2) && (expected_time <= migrate_max_downtime());
3076 static int ram_load_dead(QEMUFile *f, void *opaque)
3078 RamDecompressState s1, *s = &s1;
3082 if (ram_decompress_open(s, f) < 0)
3084 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3085 if (ram_decompress_buf(s, buf, 1) < 0) {
3086 fprintf(stderr, "Error while reading ram block header\n");
3090 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3091 BDRV_HASH_BLOCK_SIZE) < 0) {
3092 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3097 printf("Error block header\n");
3101 ram_decompress_close(s);
3106 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3111 if (version_id == 1)
3112 return ram_load_v1(f, opaque);
3114 if (version_id == 2) {
3115 if (qemu_get_be32(f) != last_ram_offset)
3117 return ram_load_dead(f, opaque);
3120 if (version_id != 3)
3124 addr = qemu_get_be64(f);
3126 flags = addr & ~TARGET_PAGE_MASK;
3127 addr &= TARGET_PAGE_MASK;
3129 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3130 if (addr != last_ram_offset)
3134 if (flags & RAM_SAVE_FLAG_FULL) {
3135 if (ram_load_dead(f, opaque) < 0)
3139 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3140 uint8_t ch = qemu_get_byte(f);
3141 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3144 (!kvm_enabled() || kvm_has_sync_mmu())) {
3145 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3148 } else if (flags & RAM_SAVE_FLAG_PAGE)
3149 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3150 } while (!(flags & RAM_SAVE_FLAG_EOS));
3155 void qemu_service_io(void)
3157 qemu_notify_event();
3160 /***********************************************************/
3161 /* bottom halves (can be seen as timers which expire ASAP) */
3172 static QEMUBH *first_bh = NULL;
3174 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3177 bh = qemu_mallocz(sizeof(QEMUBH));
3179 bh->opaque = opaque;
3180 bh->next = first_bh;
3185 int qemu_bh_poll(void)
3191 for (bh = first_bh; bh; bh = bh->next) {
3192 if (!bh->deleted && bh->scheduled) {
3201 /* remove deleted bhs */
3215 void qemu_bh_schedule_idle(QEMUBH *bh)
3223 void qemu_bh_schedule(QEMUBH *bh)
3229 /* stop the currently executing CPU to execute the BH ASAP */
3230 qemu_notify_event();
3233 void qemu_bh_cancel(QEMUBH *bh)
3238 void qemu_bh_delete(QEMUBH *bh)
3244 static void qemu_bh_update_timeout(int *timeout)
3248 for (bh = first_bh; bh; bh = bh->next) {
3249 if (!bh->deleted && bh->scheduled) {
3251 /* idle bottom halves will be polled at least
3253 *timeout = MIN(10, *timeout);
3255 /* non-idle bottom halves will be executed
3264 /***********************************************************/
3265 /* machine registration */
3267 static QEMUMachine *first_machine = NULL;
3268 QEMUMachine *current_machine = NULL;
3270 int qemu_register_machine(QEMUMachine *m)
3273 pm = &first_machine;
3281 static QEMUMachine *find_machine(const char *name)
3285 for(m = first_machine; m != NULL; m = m->next) {
3286 if (!strcmp(m->name, name))
3292 static QEMUMachine *find_default_machine(void)
3296 for(m = first_machine; m != NULL; m = m->next) {
3297 if (m->is_default) {
3304 /***********************************************************/
3305 /* main execution loop */
3307 static void gui_update(void *opaque)
3309 uint64_t interval = GUI_REFRESH_INTERVAL;
3310 DisplayState *ds = opaque;
3311 DisplayChangeListener *dcl = ds->listeners;
3315 while (dcl != NULL) {
3316 if (dcl->gui_timer_interval &&
3317 dcl->gui_timer_interval < interval)
3318 interval = dcl->gui_timer_interval;
3321 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3324 static void nographic_update(void *opaque)
3326 uint64_t interval = GUI_REFRESH_INTERVAL;
3328 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3331 struct vm_change_state_entry {
3332 VMChangeStateHandler *cb;
3334 LIST_ENTRY (vm_change_state_entry) entries;
3337 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3339 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3342 VMChangeStateEntry *e;
3344 e = qemu_mallocz(sizeof (*e));
3348 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3352 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3354 LIST_REMOVE (e, entries);
3358 static void vm_state_notify(int running, int reason)
3360 VMChangeStateEntry *e;
3362 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3363 e->cb(e->opaque, running, reason);
3367 static void resume_all_vcpus(void);
3368 static void pause_all_vcpus(void);
3375 vm_state_notify(1, 0);
3376 qemu_rearm_alarm_timer(alarm_timer);
3381 /* reset/shutdown handler */
3383 typedef struct QEMUResetEntry {
3384 QEMUResetHandler *func;
3386 struct QEMUResetEntry *next;
3389 static QEMUResetEntry *first_reset_entry;
3390 static int reset_requested;
3391 static int shutdown_requested;
3392 static int powerdown_requested;
3393 static int debug_requested;
3394 static int vmstop_requested;
3396 int qemu_shutdown_requested(void)
3398 int r = shutdown_requested;
3399 shutdown_requested = 0;
3403 int qemu_reset_requested(void)
3405 int r = reset_requested;
3406 reset_requested = 0;
3410 int qemu_powerdown_requested(void)
3412 int r = powerdown_requested;
3413 powerdown_requested = 0;
3417 static int qemu_debug_requested(void)
3419 int r = debug_requested;
3420 debug_requested = 0;
3424 static int qemu_vmstop_requested(void)
3426 int r = vmstop_requested;
3427 vmstop_requested = 0;
3431 static void do_vm_stop(int reason)
3434 cpu_disable_ticks();
3437 vm_state_notify(0, reason);
3441 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3443 QEMUResetEntry **pre, *re;
3445 pre = &first_reset_entry;
3446 while (*pre != NULL)
3447 pre = &(*pre)->next;
3448 re = qemu_mallocz(sizeof(QEMUResetEntry));
3450 re->opaque = opaque;
3455 void qemu_system_reset(void)
3459 /* reset all devices */
3460 for(re = first_reset_entry; re != NULL; re = re->next) {
3461 re->func(re->opaque);
3465 void qemu_system_reset_request(void)
3468 shutdown_requested = 1;
3470 reset_requested = 1;
3472 qemu_notify_event();
3475 void qemu_system_shutdown_request(void)
3477 shutdown_requested = 1;
3478 qemu_notify_event();
3481 void qemu_system_powerdown_request(void)
3483 powerdown_requested = 1;
3484 qemu_notify_event();
3487 #ifdef CONFIG_IOTHREAD
3488 static void qemu_system_vmstop_request(int reason)
3490 vmstop_requested = reason;
3491 qemu_notify_event();
3496 static int io_thread_fd = -1;
3498 static void qemu_event_increment(void)
3500 static const char byte = 0;
3502 if (io_thread_fd == -1)
3505 write(io_thread_fd, &byte, sizeof(byte));
3508 static void qemu_event_read(void *opaque)
3510 int fd = (unsigned long)opaque;
3513 /* Drain the notify pipe */
3516 len = read(fd, buffer, sizeof(buffer));
3517 } while ((len == -1 && errno == EINTR) || len > 0);
3520 static int qemu_event_init(void)
3529 err = fcntl_setfl(fds[0], O_NONBLOCK);
3533 err = fcntl_setfl(fds[1], O_NONBLOCK);
3537 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3538 (void *)(unsigned long)fds[0]);
3540 io_thread_fd = fds[1];
3549 HANDLE qemu_event_handle;
3551 static void dummy_event_handler(void *opaque)
3555 static int qemu_event_init(void)
3557 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3558 if (!qemu_event_handle) {
3559 perror("Failed CreateEvent");
3562 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3566 static void qemu_event_increment(void)
3568 SetEvent(qemu_event_handle);
3572 static int cpu_can_run(CPUState *env)
3581 #ifndef CONFIG_IOTHREAD
3582 static int qemu_init_main_loop(void)
3584 return qemu_event_init();
3587 void qemu_init_vcpu(void *_env)
3589 CPUState *env = _env;
3596 int qemu_cpu_self(void *env)
3601 static void resume_all_vcpus(void)
3605 static void pause_all_vcpus(void)
3609 void qemu_cpu_kick(void *env)
3614 void qemu_notify_event(void)
3616 CPUState *env = cpu_single_env;
3621 if (env->kqemu_enabled)
3622 kqemu_cpu_interrupt(env);
3627 #define qemu_mutex_lock_iothread() do { } while (0)
3628 #define qemu_mutex_unlock_iothread() do { } while (0)
3630 void vm_stop(int reason)
3635 #else /* CONFIG_IOTHREAD */
3637 #include "qemu-thread.h"
3639 QemuMutex qemu_global_mutex;
3640 static QemuMutex qemu_fair_mutex;
3642 static QemuThread io_thread;
3644 static QemuThread *tcg_cpu_thread;
3645 static QemuCond *tcg_halt_cond;
3647 static int qemu_system_ready;
3649 static QemuCond qemu_cpu_cond;
3651 static QemuCond qemu_system_cond;
3652 static QemuCond qemu_pause_cond;
3654 static void block_io_signals(void);
3655 static void unblock_io_signals(void);
3656 static int tcg_has_work(void);
3658 static int qemu_init_main_loop(void)
3662 ret = qemu_event_init();
3666 qemu_cond_init(&qemu_pause_cond);
3667 qemu_mutex_init(&qemu_fair_mutex);
3668 qemu_mutex_init(&qemu_global_mutex);
3669 qemu_mutex_lock(&qemu_global_mutex);
3671 unblock_io_signals();
3672 qemu_thread_self(&io_thread);
3677 static void qemu_wait_io_event(CPUState *env)
3679 while (!tcg_has_work())
3680 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3682 qemu_mutex_unlock(&qemu_global_mutex);
3685 * Users of qemu_global_mutex can be starved, having no chance
3686 * to acquire it since this path will get to it first.
3687 * So use another lock to provide fairness.
3689 qemu_mutex_lock(&qemu_fair_mutex);
3690 qemu_mutex_unlock(&qemu_fair_mutex);
3692 qemu_mutex_lock(&qemu_global_mutex);
3696 qemu_cond_signal(&qemu_pause_cond);
3700 static int qemu_cpu_exec(CPUState *env);
3702 static void *kvm_cpu_thread_fn(void *arg)
3704 CPUState *env = arg;
3707 qemu_thread_self(env->thread);
3709 /* signal CPU creation */
3710 qemu_mutex_lock(&qemu_global_mutex);
3712 qemu_cond_signal(&qemu_cpu_cond);
3714 /* and wait for machine initialization */
3715 while (!qemu_system_ready)
3716 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3719 if (cpu_can_run(env))
3721 qemu_wait_io_event(env);
3727 static void tcg_cpu_exec(void);
3729 static void *tcg_cpu_thread_fn(void *arg)
3731 CPUState *env = arg;
3734 qemu_thread_self(env->thread);
3736 /* signal CPU creation */
3737 qemu_mutex_lock(&qemu_global_mutex);
3738 for (env = first_cpu; env != NULL; env = env->next_cpu)
3740 qemu_cond_signal(&qemu_cpu_cond);
3742 /* and wait for machine initialization */
3743 while (!qemu_system_ready)
3744 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3748 qemu_wait_io_event(cur_cpu);
3754 void qemu_cpu_kick(void *_env)
3756 CPUState *env = _env;
3757 qemu_cond_broadcast(env->halt_cond);
3759 qemu_thread_signal(env->thread, SIGUSR1);
3762 int qemu_cpu_self(void *env)
3764 return (cpu_single_env != NULL);
3767 static void cpu_signal(int sig)
3770 cpu_exit(cpu_single_env);
3773 static void block_io_signals(void)
3776 struct sigaction sigact;
3779 sigaddset(&set, SIGUSR2);
3780 sigaddset(&set, SIGIO);
3781 sigaddset(&set, SIGALRM);
3782 pthread_sigmask(SIG_BLOCK, &set, NULL);
3785 sigaddset(&set, SIGUSR1);
3786 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3788 memset(&sigact, 0, sizeof(sigact));
3789 sigact.sa_handler = cpu_signal;
3790 sigaction(SIGUSR1, &sigact, NULL);
3793 static void unblock_io_signals(void)
3798 sigaddset(&set, SIGUSR2);
3799 sigaddset(&set, SIGIO);
3800 sigaddset(&set, SIGALRM);
3801 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3804 sigaddset(&set, SIGUSR1);
3805 pthread_sigmask(SIG_BLOCK, &set, NULL);
3808 static void qemu_signal_lock(unsigned int msecs)
3810 qemu_mutex_lock(&qemu_fair_mutex);
3812 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3813 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3814 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3817 qemu_mutex_unlock(&qemu_fair_mutex);
3820 static void qemu_mutex_lock_iothread(void)
3822 if (kvm_enabled()) {
3823 qemu_mutex_lock(&qemu_fair_mutex);
3824 qemu_mutex_lock(&qemu_global_mutex);
3825 qemu_mutex_unlock(&qemu_fair_mutex);
3827 qemu_signal_lock(100);
3830 static void qemu_mutex_unlock_iothread(void)
3832 qemu_mutex_unlock(&qemu_global_mutex);
3835 static int all_vcpus_paused(void)
3837 CPUState *penv = first_cpu;
3842 penv = (CPUState *)penv->next_cpu;
3848 static void pause_all_vcpus(void)
3850 CPUState *penv = first_cpu;
3854 qemu_thread_signal(penv->thread, SIGUSR1);
3855 qemu_cpu_kick(penv);
3856 penv = (CPUState *)penv->next_cpu;
3859 while (!all_vcpus_paused()) {
3860 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3863 qemu_thread_signal(penv->thread, SIGUSR1);
3864 penv = (CPUState *)penv->next_cpu;
3869 static void resume_all_vcpus(void)
3871 CPUState *penv = first_cpu;
3876 qemu_thread_signal(penv->thread, SIGUSR1);
3877 qemu_cpu_kick(penv);
3878 penv = (CPUState *)penv->next_cpu;
3882 static void tcg_init_vcpu(void *_env)
3884 CPUState *env = _env;
3885 /* share a single thread for all cpus with TCG */
3886 if (!tcg_cpu_thread) {
3887 env->thread = qemu_mallocz(sizeof(QemuThread));
3888 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3889 qemu_cond_init(env->halt_cond);
3890 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3891 while (env->created == 0)
3892 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3893 tcg_cpu_thread = env->thread;
3894 tcg_halt_cond = env->halt_cond;
3896 env->thread = tcg_cpu_thread;
3897 env->halt_cond = tcg_halt_cond;
3901 static void kvm_start_vcpu(CPUState *env)
3904 env->thread = qemu_mallocz(sizeof(QemuThread));
3905 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3906 qemu_cond_init(env->halt_cond);
3907 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3908 while (env->created == 0)
3909 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3912 void qemu_init_vcpu(void *_env)
3914 CPUState *env = _env;
3917 kvm_start_vcpu(env);
3922 void qemu_notify_event(void)
3924 qemu_event_increment();
3927 void vm_stop(int reason)
3930 qemu_thread_self(&me);
3932 if (!qemu_thread_equal(&me, &io_thread)) {
3933 qemu_system_vmstop_request(reason);
3935 * FIXME: should not return to device code in case
3936 * vm_stop() has been requested.
3938 if (cpu_single_env) {
3939 cpu_exit(cpu_single_env);
3940 cpu_single_env->stop = 1;
3951 static void host_main_loop_wait(int *timeout)
3957 /* XXX: need to suppress polling by better using win32 events */
3959 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3960 ret |= pe->func(pe->opaque);
3964 WaitObjects *w = &wait_objects;
3966 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3967 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3968 if (w->func[ret - WAIT_OBJECT_0])
3969 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3971 /* Check for additional signaled events */
3972 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3974 /* Check if event is signaled */
3975 ret2 = WaitForSingleObject(w->events[i], 0);
3976 if(ret2 == WAIT_OBJECT_0) {
3978 w->func[i](w->opaque[i]);
3979 } else if (ret2 == WAIT_TIMEOUT) {
3981 err = GetLastError();
3982 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3985 } else if (ret == WAIT_TIMEOUT) {
3987 err = GetLastError();
3988 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3995 static void host_main_loop_wait(int *timeout)
4000 void main_loop_wait(int timeout)
4002 IOHandlerRecord *ioh;
4003 fd_set rfds, wfds, xfds;
4007 qemu_bh_update_timeout(&timeout);
4009 host_main_loop_wait(&timeout);
4011 /* poll any events */
4012 /* XXX: separate device handlers from system ones */
4017 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4021 (!ioh->fd_read_poll ||
4022 ioh->fd_read_poll(ioh->opaque) != 0)) {
4023 FD_SET(ioh->fd, &rfds);
4027 if (ioh->fd_write) {
4028 FD_SET(ioh->fd, &wfds);
4034 tv.tv_sec = timeout / 1000;
4035 tv.tv_usec = (timeout % 1000) * 1000;
4037 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4039 qemu_mutex_unlock_iothread();
4040 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4041 qemu_mutex_lock_iothread();
4043 IOHandlerRecord **pioh;
4045 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4046 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4047 ioh->fd_read(ioh->opaque);
4049 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4050 ioh->fd_write(ioh->opaque);
4054 /* remove deleted IO handlers */
4055 pioh = &first_io_handler;
4066 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4068 /* rearm timer, if not periodic */
4069 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4070 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4071 qemu_rearm_alarm_timer(alarm_timer);
4074 /* vm time timers */
4076 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4077 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4078 qemu_get_clock(vm_clock));
4081 /* real time timers */
4082 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4083 qemu_get_clock(rt_clock));
4085 /* Check bottom-halves last in case any of the earlier events triggered
4091 static int qemu_cpu_exec(CPUState *env)
4094 #ifdef CONFIG_PROFILER
4098 #ifdef CONFIG_PROFILER
4099 ti = profile_getclock();
4104 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4105 env->icount_decr.u16.low = 0;
4106 env->icount_extra = 0;
4107 count = qemu_next_deadline();
4108 count = (count + (1 << icount_time_shift) - 1)
4109 >> icount_time_shift;
4110 qemu_icount += count;
4111 decr = (count > 0xffff) ? 0xffff : count;
4113 env->icount_decr.u16.low = decr;
4114 env->icount_extra = count;
4116 ret = cpu_exec(env);
4117 #ifdef CONFIG_PROFILER
4118 qemu_time += profile_getclock() - ti;
4121 /* Fold pending instructions back into the
4122 instruction counter, and clear the interrupt flag. */
4123 qemu_icount -= (env->icount_decr.u16.low
4124 + env->icount_extra);
4125 env->icount_decr.u32 = 0;
4126 env->icount_extra = 0;
4131 static void tcg_cpu_exec(void)
4135 if (next_cpu == NULL)
4136 next_cpu = first_cpu;
4137 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4138 CPUState *env = cur_cpu = next_cpu;
4142 if (timer_alarm_pending) {
4143 timer_alarm_pending = 0;
4146 if (cpu_can_run(env))
4147 ret = qemu_cpu_exec(env);
4148 if (ret == EXCP_DEBUG) {
4149 gdb_set_stop_cpu(env);
4150 debug_requested = 1;
4156 static int cpu_has_work(CPUState *env)
4164 if (qemu_cpu_has_work(env))
4169 static int tcg_has_work(void)
4173 for (env = first_cpu; env != NULL; env = env->next_cpu)
4174 if (cpu_has_work(env))
4179 static int qemu_calculate_timeout(void)
4181 #ifndef CONFIG_IOTHREAD
4186 else if (tcg_has_work())
4188 else if (!use_icount)
4191 /* XXX: use timeout computed from timers */
4194 /* Advance virtual time to the next event. */
4195 if (use_icount == 1) {
4196 /* When not using an adaptive execution frequency
4197 we tend to get badly out of sync with real time,
4198 so just delay for a reasonable amount of time. */
4201 delta = cpu_get_icount() - cpu_get_clock();
4204 /* If virtual time is ahead of real time then just
4206 timeout = (delta / 1000000) + 1;
4208 /* Wait for either IO to occur or the next
4210 add = qemu_next_deadline();
4211 /* We advance the timer before checking for IO.
4212 Limit the amount we advance so that early IO
4213 activity won't get the guest too far ahead. */
4217 add = (add + (1 << icount_time_shift) - 1)
4218 >> icount_time_shift;
4220 timeout = delta / 1000000;
4227 #else /* CONFIG_IOTHREAD */
4232 static int vm_can_run(void)
4234 if (powerdown_requested)
4236 if (reset_requested)
4238 if (shutdown_requested)
4240 if (debug_requested)
4245 static void main_loop(void)
4249 #ifdef CONFIG_IOTHREAD
4250 qemu_system_ready = 1;
4251 qemu_cond_broadcast(&qemu_system_cond);
4256 #ifdef CONFIG_PROFILER
4259 #ifndef CONFIG_IOTHREAD
4262 #ifdef CONFIG_PROFILER
4263 ti = profile_getclock();
4265 main_loop_wait(qemu_calculate_timeout());
4266 #ifdef CONFIG_PROFILER
4267 dev_time += profile_getclock() - ti;
4269 } while (vm_can_run());
4271 if (qemu_debug_requested())
4272 vm_stop(EXCP_DEBUG);
4273 if (qemu_shutdown_requested()) {
4280 if (qemu_reset_requested()) {
4282 qemu_system_reset();
4285 if (qemu_powerdown_requested())
4286 qemu_system_powerdown();
4287 if ((r = qemu_vmstop_requested()))
4293 static void version(void)
4295 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4298 static void help(int exitcode)
4301 printf("usage: %s [options] [disk_image]\n"
4303 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4305 #define DEF(option, opt_arg, opt_enum, opt_help) \
4307 #define DEFHEADING(text) stringify(text) "\n"
4308 #include "qemu-options.h"
4313 "During emulation, the following keys are useful:\n"
4314 "ctrl-alt-f toggle full screen\n"
4315 "ctrl-alt-n switch to virtual console 'n'\n"
4316 "ctrl-alt toggle mouse and keyboard grab\n"
4318 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4323 DEFAULT_NETWORK_SCRIPT,
4324 DEFAULT_NETWORK_DOWN_SCRIPT,
4326 DEFAULT_GDBSTUB_PORT,
4331 #define HAS_ARG 0x0001
4334 #define DEF(option, opt_arg, opt_enum, opt_help) \
4336 #define DEFHEADING(text)
4337 #include "qemu-options.h"
4343 typedef struct QEMUOption {
4349 static const QEMUOption qemu_options[] = {
4350 { "h", 0, QEMU_OPTION_h },
4351 #define DEF(option, opt_arg, opt_enum, opt_help) \
4352 { option, opt_arg, opt_enum },
4353 #define DEFHEADING(text)
4354 #include "qemu-options.h"
4362 struct soundhw soundhw[] = {
4363 #ifdef HAS_AUDIO_CHOICE
4364 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4370 { .init_isa = pcspk_audio_init }
4377 "Creative Sound Blaster 16",
4380 { .init_isa = SB16_init }
4384 #ifdef CONFIG_CS4231A
4390 { .init_isa = cs4231a_init }
4398 "Yamaha YMF262 (OPL3)",
4400 "Yamaha YM3812 (OPL2)",
4404 { .init_isa = Adlib_init }
4411 "Gravis Ultrasound GF1",
4414 { .init_isa = GUS_init }
4421 "Intel 82801AA AC97 Audio",
4424 { .init_pci = ac97_init }
4428 #ifdef CONFIG_ES1370
4431 "ENSONIQ AudioPCI ES1370",
4434 { .init_pci = es1370_init }
4438 #endif /* HAS_AUDIO_CHOICE */
4440 { NULL, NULL, 0, 0, { NULL } }
4443 static void select_soundhw (const char *optarg)
4447 if (*optarg == '?') {
4450 printf ("Valid sound card names (comma separated):\n");
4451 for (c = soundhw; c->name; ++c) {
4452 printf ("%-11s %s\n", c->name, c->descr);
4454 printf ("\n-soundhw all will enable all of the above\n");
4455 exit (*optarg != '?');
4463 if (!strcmp (optarg, "all")) {
4464 for (c = soundhw; c->name; ++c) {
4472 e = strchr (p, ',');
4473 l = !e ? strlen (p) : (size_t) (e - p);
4475 for (c = soundhw; c->name; ++c) {
4476 if (!strncmp (c->name, p, l)) {
4485 "Unknown sound card name (too big to show)\n");
4488 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4493 p += l + (e != NULL);
4497 goto show_valid_cards;
4502 static void select_vgahw (const char *p)
4506 cirrus_vga_enabled = 0;
4507 std_vga_enabled = 0;
4510 if (strstart(p, "std", &opts)) {
4511 std_vga_enabled = 1;
4512 } else if (strstart(p, "cirrus", &opts)) {
4513 cirrus_vga_enabled = 1;
4514 } else if (strstart(p, "vmware", &opts)) {
4516 } else if (strstart(p, "xenfb", &opts)) {
4518 } else if (!strstart(p, "none", &opts)) {
4520 fprintf(stderr, "Unknown vga type: %s\n", p);
4524 const char *nextopt;
4526 if (strstart(opts, ",retrace=", &nextopt)) {
4528 if (strstart(opts, "dumb", &nextopt))
4529 vga_retrace_method = VGA_RETRACE_DUMB;
4530 else if (strstart(opts, "precise", &nextopt))
4531 vga_retrace_method = VGA_RETRACE_PRECISE;
4532 else goto invalid_vga;
4533 } else goto invalid_vga;
4539 static int balloon_parse(const char *arg)
4544 if (!strcmp(arg, "none")) {
4546 } else if (!strncmp(arg, "virtio", 6)) {
4548 if (arg[6] == ',') {
4550 if (get_param_value(buf, sizeof(buf), "addr", p)) {
4551 virtio_balloon_devaddr = strdup(buf);
4562 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4564 exit(STATUS_CONTROL_C_EXIT);
4569 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4573 if(strlen(str) != 36)
4576 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4577 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4578 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4584 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4590 #define MAX_NET_CLIENTS 32
4594 static void termsig_handler(int signal)
4596 qemu_system_shutdown_request();
4599 static void sigchld_handler(int signal)
4601 waitpid(-1, NULL, WNOHANG);
4604 static void sighandler_setup(void)
4606 struct sigaction act;
4608 memset(&act, 0, sizeof(act));
4609 act.sa_handler = termsig_handler;
4610 sigaction(SIGINT, &act, NULL);
4611 sigaction(SIGHUP, &act, NULL);
4612 sigaction(SIGTERM, &act, NULL);
4614 act.sa_handler = sigchld_handler;
4615 act.sa_flags = SA_NOCLDSTOP;
4616 sigaction(SIGCHLD, &act, NULL);
4622 /* Look for support files in the same directory as the executable. */
4623 static char *find_datadir(const char *argv0)
4629 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4636 while (p != buf && *p != '\\')
4639 if (access(buf, R_OK) == 0) {
4640 return qemu_strdup(buf);
4646 /* Find a likely location for support files using the location of the binary.
4647 For installed binaries this will be "$bindir/../share/qemu". When
4648 running from the build tree this will be "$bindir/../pc-bios". */
4649 #define SHARE_SUFFIX "/share/qemu"
4650 #define BUILD_SUFFIX "/pc-bios"
4651 static char *find_datadir(const char *argv0)
4661 #if defined(__linux__)
4664 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4670 #elif defined(__FreeBSD__)
4673 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4680 /* If we don't have any way of figuring out the actual executable
4681 location then try argv[0]. */
4686 p = realpath(argv0, p);
4694 max_len = strlen(dir) +
4695 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4696 res = qemu_mallocz(max_len);
4697 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4698 if (access(res, R_OK)) {
4699 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4700 if (access(res, R_OK)) {
4714 char *qemu_find_file(int type, const char *name)
4720 /* If name contains path separators then try it as a straight path. */
4721 if ((strchr(name, '/') || strchr(name, '\\'))
4722 && access(name, R_OK) == 0) {
4723 return strdup(name);
4726 case QEMU_FILE_TYPE_BIOS:
4729 case QEMU_FILE_TYPE_KEYMAP:
4730 subdir = "keymaps/";
4735 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4736 buf = qemu_mallocz(len);
4737 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4738 if (access(buf, R_OK)) {
4745 int main(int argc, char **argv, char **envp)
4747 const char *gdbstub_dev = NULL;
4748 uint32_t boot_devices_bitmap = 0;
4750 int snapshot, linux_boot, net_boot;
4751 const char *initrd_filename;
4752 const char *kernel_filename, *kernel_cmdline;
4753 const char *boot_devices = "";
4755 DisplayChangeListener *dcl;
4756 int cyls, heads, secs, translation;
4757 const char *net_clients[MAX_NET_CLIENTS];
4759 const char *bt_opts[MAX_BT_CMDLINE];
4763 const char *r, *optarg;
4764 CharDriverState *monitor_hd = NULL;
4765 const char *monitor_device;
4766 const char *serial_devices[MAX_SERIAL_PORTS];
4767 int serial_device_index;
4768 const char *parallel_devices[MAX_PARALLEL_PORTS];
4769 int parallel_device_index;
4770 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4771 int virtio_console_index;
4772 const char *loadvm = NULL;
4773 QEMUMachine *machine;
4774 const char *cpu_model;
4775 const char *usb_devices[MAX_USB_CMDLINE];
4776 int usb_devices_index;
4781 const char *pid_file = NULL;
4782 const char *incoming = NULL;
4785 struct passwd *pwd = NULL;
4786 const char *chroot_dir = NULL;
4787 const char *run_as = NULL;
4790 int show_vnc_port = 0;
4792 qemu_cache_utils_init(envp);
4794 LIST_INIT (&vm_change_state_head);
4797 struct sigaction act;
4798 sigfillset(&act.sa_mask);
4800 act.sa_handler = SIG_IGN;
4801 sigaction(SIGPIPE, &act, NULL);
4804 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4805 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4806 QEMU to run on a single CPU */
4811 h = GetCurrentProcess();
4812 if (GetProcessAffinityMask(h, &mask, &smask)) {
4813 for(i = 0; i < 32; i++) {
4814 if (mask & (1 << i))
4819 SetProcessAffinityMask(h, mask);
4825 module_call_init(MODULE_INIT_MACHINE);
4826 machine = find_default_machine();
4828 initrd_filename = NULL;
4831 kernel_filename = NULL;
4832 kernel_cmdline = "";
4833 cyls = heads = secs = 0;
4834 translation = BIOS_ATA_TRANSLATION_AUTO;
4835 monitor_device = "vc:80Cx24C";
4837 serial_devices[0] = "vc:80Cx24C";
4838 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4839 serial_devices[i] = NULL;
4840 serial_device_index = 0;
4842 parallel_devices[0] = "vc:80Cx24C";
4843 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4844 parallel_devices[i] = NULL;
4845 parallel_device_index = 0;
4847 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4848 virtio_consoles[i] = NULL;
4849 virtio_console_index = 0;
4851 for (i = 0; i < MAX_NODES; i++) {
4853 node_cpumask[i] = 0;
4856 usb_devices_index = 0;
4870 register_watchdogs();
4878 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4880 const QEMUOption *popt;
4883 /* Treat --foo the same as -foo. */
4886 popt = qemu_options;
4889 fprintf(stderr, "%s: invalid option -- '%s'\n",
4893 if (!strcmp(popt->name, r + 1))
4897 if (popt->flags & HAS_ARG) {
4898 if (optind >= argc) {
4899 fprintf(stderr, "%s: option '%s' requires an argument\n",
4903 optarg = argv[optind++];
4908 switch(popt->index) {
4910 machine = find_machine(optarg);
4913 printf("Supported machines are:\n");
4914 for(m = first_machine; m != NULL; m = m->next) {
4915 printf("%-10s %s%s\n",
4917 m->is_default ? " (default)" : "");
4919 exit(*optarg != '?');
4922 case QEMU_OPTION_cpu:
4923 /* hw initialization will check this */
4924 if (*optarg == '?') {
4925 /* XXX: implement xxx_cpu_list for targets that still miss it */
4926 #if defined(cpu_list)
4927 cpu_list(stdout, &fprintf);
4934 case QEMU_OPTION_initrd:
4935 initrd_filename = optarg;
4937 case QEMU_OPTION_hda:
4939 hda_index = drive_add(optarg, HD_ALIAS, 0);
4941 hda_index = drive_add(optarg, HD_ALIAS
4942 ",cyls=%d,heads=%d,secs=%d%s",
4943 0, cyls, heads, secs,
4944 translation == BIOS_ATA_TRANSLATION_LBA ?
4946 translation == BIOS_ATA_TRANSLATION_NONE ?
4947 ",trans=none" : "");
4949 case QEMU_OPTION_hdb:
4950 case QEMU_OPTION_hdc:
4951 case QEMU_OPTION_hdd:
4952 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4954 case QEMU_OPTION_drive:
4955 drive_add(NULL, "%s", optarg);
4957 case QEMU_OPTION_mtdblock:
4958 drive_add(optarg, MTD_ALIAS);
4960 case QEMU_OPTION_sd:
4961 drive_add(optarg, SD_ALIAS);
4963 case QEMU_OPTION_pflash:
4964 drive_add(optarg, PFLASH_ALIAS);
4966 case QEMU_OPTION_snapshot:
4969 case QEMU_OPTION_hdachs:
4973 cyls = strtol(p, (char **)&p, 0);
4974 if (cyls < 1 || cyls > 16383)
4979 heads = strtol(p, (char **)&p, 0);
4980 if (heads < 1 || heads > 16)
4985 secs = strtol(p, (char **)&p, 0);
4986 if (secs < 1 || secs > 63)
4990 if (!strcmp(p, "none"))
4991 translation = BIOS_ATA_TRANSLATION_NONE;
4992 else if (!strcmp(p, "lba"))
4993 translation = BIOS_ATA_TRANSLATION_LBA;
4994 else if (!strcmp(p, "auto"))
4995 translation = BIOS_ATA_TRANSLATION_AUTO;
4998 } else if (*p != '\0') {
5000 fprintf(stderr, "qemu: invalid physical CHS format\n");
5003 if (hda_index != -1)
5004 snprintf(drives_opt[hda_index].opt,
5005 sizeof(drives_opt[hda_index].opt),
5006 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5007 0, cyls, heads, secs,
5008 translation == BIOS_ATA_TRANSLATION_LBA ?
5010 translation == BIOS_ATA_TRANSLATION_NONE ?
5011 ",trans=none" : "");
5014 case QEMU_OPTION_numa:
5015 if (nb_numa_nodes >= MAX_NODES) {
5016 fprintf(stderr, "qemu: too many NUMA nodes\n");
5021 case QEMU_OPTION_nographic:
5022 display_type = DT_NOGRAPHIC;
5024 #ifdef CONFIG_CURSES
5025 case QEMU_OPTION_curses:
5026 display_type = DT_CURSES;
5029 case QEMU_OPTION_portrait:
5032 case QEMU_OPTION_kernel:
5033 kernel_filename = optarg;
5035 case QEMU_OPTION_append:
5036 kernel_cmdline = optarg;
5038 case QEMU_OPTION_cdrom:
5039 drive_add(optarg, CDROM_ALIAS);
5041 case QEMU_OPTION_boot:
5042 boot_devices = optarg;
5043 /* We just do some generic consistency checks */
5045 /* Could easily be extended to 64 devices if needed */
5048 boot_devices_bitmap = 0;
5049 for (p = boot_devices; *p != '\0'; p++) {
5050 /* Allowed boot devices are:
5051 * a b : floppy disk drives
5052 * c ... f : IDE disk drives
5053 * g ... m : machine implementation dependant drives
5054 * n ... p : network devices
5055 * It's up to each machine implementation to check
5056 * if the given boot devices match the actual hardware
5057 * implementation and firmware features.
5059 if (*p < 'a' || *p > 'q') {
5060 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5063 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5065 "Boot device '%c' was given twice\n",*p);
5068 boot_devices_bitmap |= 1 << (*p - 'a');
5072 case QEMU_OPTION_fda:
5073 case QEMU_OPTION_fdb:
5074 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5077 case QEMU_OPTION_no_fd_bootchk:
5081 case QEMU_OPTION_net:
5082 if (nb_net_clients >= MAX_NET_CLIENTS) {
5083 fprintf(stderr, "qemu: too many network clients\n");
5086 net_clients[nb_net_clients] = optarg;
5090 case QEMU_OPTION_tftp:
5091 legacy_tftp_prefix = optarg;
5093 case QEMU_OPTION_bootp:
5094 legacy_bootp_filename = optarg;
5097 case QEMU_OPTION_smb:
5098 net_slirp_smb(optarg);
5101 case QEMU_OPTION_redir:
5102 net_slirp_redir(optarg);
5105 case QEMU_OPTION_bt:
5106 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5107 fprintf(stderr, "qemu: too many bluetooth options\n");
5110 bt_opts[nb_bt_opts++] = optarg;
5113 case QEMU_OPTION_audio_help:
5117 case QEMU_OPTION_soundhw:
5118 select_soundhw (optarg);
5124 case QEMU_OPTION_version:
5128 case QEMU_OPTION_m: {
5132 value = strtoul(optarg, &ptr, 10);
5134 case 0: case 'M': case 'm':
5141 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5145 /* On 32-bit hosts, QEMU is limited by virtual address space */
5146 if (value > (2047 << 20)
5147 #ifndef CONFIG_KQEMU
5148 && HOST_LONG_BITS == 32
5151 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5154 if (value != (uint64_t)(ram_addr_t)value) {
5155 fprintf(stderr, "qemu: ram size too large\n");
5164 const CPULogItem *item;
5166 mask = cpu_str_to_log_mask(optarg);
5168 printf("Log items (comma separated):\n");
5169 for(item = cpu_log_items; item->mask != 0; item++) {
5170 printf("%-10s %s\n", item->name, item->help);
5178 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5180 case QEMU_OPTION_gdb:
5181 gdbstub_dev = optarg;
5186 case QEMU_OPTION_bios:
5189 case QEMU_OPTION_singlestep:
5197 keyboard_layout = optarg;
5200 case QEMU_OPTION_localtime:
5203 case QEMU_OPTION_vga:
5204 select_vgahw (optarg);
5206 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5212 w = strtol(p, (char **)&p, 10);
5215 fprintf(stderr, "qemu: invalid resolution or depth\n");
5221 h = strtol(p, (char **)&p, 10);
5226 depth = strtol(p, (char **)&p, 10);
5227 if (depth != 8 && depth != 15 && depth != 16 &&
5228 depth != 24 && depth != 32)
5230 } else if (*p == '\0') {
5231 depth = graphic_depth;
5238 graphic_depth = depth;
5242 case QEMU_OPTION_echr:
5245 term_escape_char = strtol(optarg, &r, 0);
5247 printf("Bad argument to echr\n");
5250 case QEMU_OPTION_monitor:
5251 monitor_device = optarg;
5253 case QEMU_OPTION_serial:
5254 if (serial_device_index >= MAX_SERIAL_PORTS) {
5255 fprintf(stderr, "qemu: too many serial ports\n");
5258 serial_devices[serial_device_index] = optarg;
5259 serial_device_index++;
5261 case QEMU_OPTION_watchdog:
5262 i = select_watchdog(optarg);
5264 exit (i == 1 ? 1 : 0);
5266 case QEMU_OPTION_watchdog_action:
5267 if (select_watchdog_action(optarg) == -1) {
5268 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5272 case QEMU_OPTION_virtiocon:
5273 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5274 fprintf(stderr, "qemu: too many virtio consoles\n");
5277 virtio_consoles[virtio_console_index] = optarg;
5278 virtio_console_index++;
5280 case QEMU_OPTION_parallel:
5281 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5282 fprintf(stderr, "qemu: too many parallel ports\n");
5285 parallel_devices[parallel_device_index] = optarg;
5286 parallel_device_index++;
5288 case QEMU_OPTION_loadvm:
5291 case QEMU_OPTION_full_screen:
5295 case QEMU_OPTION_no_frame:
5298 case QEMU_OPTION_alt_grab:
5301 case QEMU_OPTION_no_quit:
5304 case QEMU_OPTION_sdl:
5305 display_type = DT_SDL;
5308 case QEMU_OPTION_pidfile:
5312 case QEMU_OPTION_win2k_hack:
5313 win2k_install_hack = 1;
5315 case QEMU_OPTION_rtc_td_hack:
5318 case QEMU_OPTION_acpitable:
5319 if(acpi_table_add(optarg) < 0) {
5320 fprintf(stderr, "Wrong acpi table provided\n");
5324 case QEMU_OPTION_smbios:
5325 if(smbios_entry_add(optarg) < 0) {
5326 fprintf(stderr, "Wrong smbios provided\n");
5332 case QEMU_OPTION_no_kqemu:
5335 case QEMU_OPTION_kernel_kqemu:
5340 case QEMU_OPTION_enable_kvm:
5347 case QEMU_OPTION_usb:
5350 case QEMU_OPTION_usbdevice:
5352 if (usb_devices_index >= MAX_USB_CMDLINE) {
5353 fprintf(stderr, "Too many USB devices\n");
5356 usb_devices[usb_devices_index] = optarg;
5357 usb_devices_index++;
5359 case QEMU_OPTION_smp:
5360 smp_cpus = atoi(optarg);
5362 fprintf(stderr, "Invalid number of CPUs\n");
5366 case QEMU_OPTION_vnc:
5367 display_type = DT_VNC;
5368 vnc_display = optarg;
5371 case QEMU_OPTION_no_acpi:
5374 case QEMU_OPTION_no_hpet:
5377 case QEMU_OPTION_balloon:
5378 if (balloon_parse(optarg) < 0) {
5379 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5384 case QEMU_OPTION_no_reboot:
5387 case QEMU_OPTION_no_shutdown:
5390 case QEMU_OPTION_show_cursor:
5393 case QEMU_OPTION_uuid:
5394 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5395 fprintf(stderr, "Fail to parse UUID string."
5396 " Wrong format.\n");
5401 case QEMU_OPTION_daemonize:
5405 case QEMU_OPTION_option_rom:
5406 if (nb_option_roms >= MAX_OPTION_ROMS) {
5407 fprintf(stderr, "Too many option ROMs\n");
5410 option_rom[nb_option_roms] = optarg;
5413 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5414 case QEMU_OPTION_semihosting:
5415 semihosting_enabled = 1;
5418 case QEMU_OPTION_name:
5421 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5422 case QEMU_OPTION_prom_env:
5423 if (nb_prom_envs >= MAX_PROM_ENVS) {
5424 fprintf(stderr, "Too many prom variables\n");
5427 prom_envs[nb_prom_envs] = optarg;
5432 case QEMU_OPTION_old_param:
5436 case QEMU_OPTION_clock:
5437 configure_alarms(optarg);
5439 case QEMU_OPTION_startdate:
5442 time_t rtc_start_date;
5443 if (!strcmp(optarg, "now")) {
5444 rtc_date_offset = -1;
5446 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5454 } else if (sscanf(optarg, "%d-%d-%d",
5457 &tm.tm_mday) == 3) {
5466 rtc_start_date = mktimegm(&tm);
5467 if (rtc_start_date == -1) {
5469 fprintf(stderr, "Invalid date format. Valid format are:\n"
5470 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5473 rtc_date_offset = time(NULL) - rtc_start_date;
5477 case QEMU_OPTION_tb_size:
5478 tb_size = strtol(optarg, NULL, 0);
5482 case QEMU_OPTION_icount:
5484 if (strcmp(optarg, "auto") == 0) {
5485 icount_time_shift = -1;
5487 icount_time_shift = strtol(optarg, NULL, 0);
5490 case QEMU_OPTION_incoming:
5494 case QEMU_OPTION_chroot:
5495 chroot_dir = optarg;
5497 case QEMU_OPTION_runas:
5502 case QEMU_OPTION_xen_domid:
5503 xen_domid = atoi(optarg);
5505 case QEMU_OPTION_xen_create:
5506 xen_mode = XEN_CREATE;
5508 case QEMU_OPTION_xen_attach:
5509 xen_mode = XEN_ATTACH;
5516 /* If no data_dir is specified then try to find it relative to the
5519 data_dir = find_datadir(argv[0]);
5521 /* If all else fails use the install patch specified when building. */
5523 data_dir = CONFIG_QEMU_SHAREDIR;
5526 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5527 if (kvm_allowed && kqemu_allowed) {
5529 "You can not enable both KVM and kqemu at the same time\n");
5534 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5535 if (smp_cpus > machine->max_cpus) {
5536 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5537 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5542 if (display_type == DT_NOGRAPHIC) {
5543 if (serial_device_index == 0)
5544 serial_devices[0] = "stdio";
5545 if (parallel_device_index == 0)
5546 parallel_devices[0] = "null";
5547 if (strncmp(monitor_device, "vc", 2) == 0)
5548 monitor_device = "stdio";
5555 if (pipe(fds) == -1)
5566 len = read(fds[0], &status, 1);
5567 if (len == -1 && (errno == EINTR))
5572 else if (status == 1) {
5573 fprintf(stderr, "Could not acquire pidfile\n");
5590 signal(SIGTSTP, SIG_IGN);
5591 signal(SIGTTOU, SIG_IGN);
5592 signal(SIGTTIN, SIG_IGN);
5595 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5598 write(fds[1], &status, 1);
5600 fprintf(stderr, "Could not acquire pid file\n");
5609 if (qemu_init_main_loop()) {
5610 fprintf(stderr, "qemu_init_main_loop failed\n");
5613 linux_boot = (kernel_filename != NULL);
5615 if (!linux_boot && *kernel_cmdline != '\0') {
5616 fprintf(stderr, "-append only allowed with -kernel option\n");
5620 if (!linux_boot && initrd_filename != NULL) {
5621 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5625 /* boot to floppy or the default cd if no hard disk defined yet */
5626 if (!boot_devices[0]) {
5627 boot_devices = "cad";
5629 setvbuf(stdout, NULL, _IOLBF, 0);
5632 if (init_timer_alarm() < 0) {
5633 fprintf(stderr, "could not initialize alarm timer\n");
5636 if (use_icount && icount_time_shift < 0) {
5638 /* 125MIPS seems a reasonable initial guess at the guest speed.
5639 It will be corrected fairly quickly anyway. */
5640 icount_time_shift = 3;
5641 init_icount_adjust();
5648 /* init network clients */
5649 if (nb_net_clients == 0) {
5650 /* if no clients, we use a default config */
5651 net_clients[nb_net_clients++] = "nic";
5653 net_clients[nb_net_clients++] = "user";
5657 for(i = 0;i < nb_net_clients; i++) {
5658 if (net_client_parse(net_clients[i]) < 0)
5662 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5663 net_set_boot_mask(net_boot);
5667 /* init the bluetooth world */
5668 for (i = 0; i < nb_bt_opts; i++)
5669 if (bt_parse(bt_opts[i]))
5672 /* init the memory */
5674 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5677 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5678 guest ram allocation. It needs to go away. */
5679 if (kqemu_allowed) {
5680 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
5681 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5682 if (!kqemu_phys_ram_base) {
5683 fprintf(stderr, "Could not allocate physical memory\n");
5689 /* init the dynamic translator */
5690 cpu_exec_init_all(tb_size * 1024 * 1024);
5694 /* we always create the cdrom drive, even if no disk is there */
5696 if (nb_drives_opt < MAX_DRIVES)
5697 drive_add(NULL, CDROM_ALIAS);
5699 /* we always create at least one floppy */
5701 if (nb_drives_opt < MAX_DRIVES)
5702 drive_add(NULL, FD_ALIAS, 0);
5704 /* we always create one sd slot, even if no card is in it */
5706 if (nb_drives_opt < MAX_DRIVES)
5707 drive_add(NULL, SD_ALIAS);
5709 /* open the virtual block devices */
5711 for(i = 0; i < nb_drives_opt; i++)
5712 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5715 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5716 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5719 /* must be after terminal init, SDL library changes signal handlers */
5723 /* Maintain compatibility with multiple stdio monitors */
5724 if (!strcmp(monitor_device,"stdio")) {
5725 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5726 const char *devname = serial_devices[i];
5727 if (devname && !strcmp(devname,"mon:stdio")) {
5728 monitor_device = NULL;
5730 } else if (devname && !strcmp(devname,"stdio")) {
5731 monitor_device = NULL;
5732 serial_devices[i] = "mon:stdio";
5738 if (nb_numa_nodes > 0) {
5741 if (nb_numa_nodes > smp_cpus) {
5742 nb_numa_nodes = smp_cpus;
5745 /* If no memory size if given for any node, assume the default case
5746 * and distribute the available memory equally across all nodes
5748 for (i = 0; i < nb_numa_nodes; i++) {
5749 if (node_mem[i] != 0)
5752 if (i == nb_numa_nodes) {
5753 uint64_t usedmem = 0;
5755 /* On Linux, the each node's border has to be 8MB aligned,
5756 * the final node gets the rest.
5758 for (i = 0; i < nb_numa_nodes - 1; i++) {
5759 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5760 usedmem += node_mem[i];
5762 node_mem[i] = ram_size - usedmem;
5765 for (i = 0; i < nb_numa_nodes; i++) {
5766 if (node_cpumask[i] != 0)
5769 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5770 * must cope with this anyway, because there are BIOSes out there in
5771 * real machines which also use this scheme.
5773 if (i == nb_numa_nodes) {
5774 for (i = 0; i < smp_cpus; i++) {
5775 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5780 if (kvm_enabled()) {
5783 ret = kvm_init(smp_cpus);
5785 fprintf(stderr, "failed to initialize KVM\n");
5790 if (monitor_device) {
5791 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5793 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5798 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5799 const char *devname = serial_devices[i];
5800 if (devname && strcmp(devname, "none")) {
5802 snprintf(label, sizeof(label), "serial%d", i);
5803 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5804 if (!serial_hds[i]) {
5805 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5812 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5813 const char *devname = parallel_devices[i];
5814 if (devname && strcmp(devname, "none")) {
5816 snprintf(label, sizeof(label), "parallel%d", i);
5817 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5818 if (!parallel_hds[i]) {
5819 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5826 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5827 const char *devname = virtio_consoles[i];
5828 if (devname && strcmp(devname, "none")) {
5830 snprintf(label, sizeof(label), "virtcon%d", i);
5831 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5832 if (!virtcon_hds[i]) {
5833 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5840 module_call_init(MODULE_INIT_DEVICE);
5842 machine->init(ram_size, boot_devices,
5843 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5846 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5847 for (i = 0; i < nb_numa_nodes; i++) {
5848 if (node_cpumask[i] & (1 << env->cpu_index)) {
5854 current_machine = machine;
5856 /* init USB devices */
5858 for(i = 0; i < usb_devices_index; i++) {
5859 if (usb_device_add(usb_devices[i], 0) < 0) {
5860 fprintf(stderr, "Warning: could not add USB device %s\n",
5867 dumb_display_init();
5868 /* just use the first displaystate for the moment */
5871 if (display_type == DT_DEFAULT) {
5872 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5873 display_type = DT_SDL;
5875 display_type = DT_VNC;
5876 vnc_display = "localhost:0,to=99";
5882 switch (display_type) {
5885 #if defined(CONFIG_CURSES)
5887 curses_display_init(ds, full_screen);
5890 #if defined(CONFIG_SDL)
5892 sdl_display_init(ds, full_screen, no_frame);
5894 #elif defined(CONFIG_COCOA)
5896 cocoa_display_init(ds, full_screen);
5900 vnc_display_init(ds);
5901 if (vnc_display_open(ds, vnc_display) < 0)
5904 if (show_vnc_port) {
5905 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5913 dcl = ds->listeners;
5914 while (dcl != NULL) {
5915 if (dcl->dpy_refresh != NULL) {
5916 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5917 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5922 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5923 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5924 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5927 text_consoles_set_display(display_state);
5928 qemu_chr_initial_reset();
5930 if (monitor_device && monitor_hd)
5931 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
5933 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5934 const char *devname = serial_devices[i];
5935 if (devname && strcmp(devname, "none")) {
5936 if (strstart(devname, "vc", 0))
5937 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5941 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5942 const char *devname = parallel_devices[i];
5943 if (devname && strcmp(devname, "none")) {
5944 if (strstart(devname, "vc", 0))
5945 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5949 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5950 const char *devname = virtio_consoles[i];
5951 if (virtcon_hds[i] && devname) {
5952 if (strstart(devname, "vc", 0))
5953 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5957 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5958 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5964 do_loadvm(cur_mon, loadvm);
5967 autostart = 0; /* fixme how to deal with -daemonize */
5968 qemu_start_incoming_migration(incoming);
5980 len = write(fds[1], &status, 1);
5981 if (len == -1 && (errno == EINTR))
5988 TFR(fd = open("/dev/null", O_RDWR));
5994 pwd = getpwnam(run_as);
5996 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6002 if (chroot(chroot_dir) < 0) {
6003 fprintf(stderr, "chroot failed\n");
6010 if (setgid(pwd->pw_gid) < 0) {
6011 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6014 if (setuid(pwd->pw_uid) < 0) {
6015 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6018 if (setuid(0) != -1) {
6019 fprintf(stderr, "Dropping privileges failed\n");