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>
71 #include <sys/prctl.h>
73 /* For the benefit of older linux systems which don't supply it,
74 we use a local copy of hpet.h. */
75 /* #include <linux/hpet.h> */
78 #include <linux/ppdev.h>
79 #include <linux/parport.h>
83 #include <sys/ethernet.h>
84 #include <sys/sockio.h>
85 #include <netinet/arp.h>
86 #include <netinet/in.h>
87 #include <netinet/in_systm.h>
88 #include <netinet/ip.h>
89 #include <netinet/ip_icmp.h> // must come after ip.h
90 #include <netinet/udp.h>
91 #include <netinet/tcp.h>
99 #if defined(__OpenBSD__)
103 #if defined(CONFIG_VDE)
104 #include <libvdeplug.h>
110 #include <sys/timeb.h>
111 #include <mmsystem.h>
112 #define getopt_long_only getopt_long
113 #define memalign(align, size) malloc(size)
117 #if defined(__APPLE__) || defined(main)
119 int qemu_main(int argc
, char **argv
, char **envp
);
120 int main(int argc
, char **argv
)
122 return qemu_main(argc
, argv
, NULL
);
125 #define main qemu_main
127 #endif /* CONFIG_SDL */
131 #define main qemu_main
132 #endif /* CONFIG_COCOA */
135 #include "hw/boards.h"
137 #include "hw/pcmcia.h"
139 #include "hw/audiodev.h"
143 #include "hw/watchdog.h"
144 #include "hw/smbios.h"
152 #include "qemu-timer.h"
153 #include "qemu-char.h"
154 #include "cache-utils.h"
157 #include "audio/audio.h"
158 #include "migration.h"
161 #include "qemu-option.h"
162 #include "qemu-kvm.h"
163 #include "hw/device-assignment.h"
167 #include "exec-all.h"
169 #include "qemu_socket.h"
171 #include "slirp/libslirp.h"
174 //#define DEBUG_SLIRP
176 #define DEFAULT_RAM_SIZE 128
178 /* Max number of USB devices that can be specified on the commandline. */
179 #define MAX_USB_CMDLINE 8
181 /* Max number of bluetooth switches on the commandline. */
182 #define MAX_BT_CMDLINE 10
184 static const char *data_dir
;
185 const char *bios_name
= NULL
;
186 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
187 to store the VM snapshots */
188 DriveInfo drives_table
[MAX_DRIVES
+1];
190 int extboot_drive
= -1;
191 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
192 static DisplayState
*display_state
;
193 DisplayType display_type
= DT_DEFAULT
;
194 const char* keyboard_layout
= NULL
;
195 int64_t ticks_per_sec
;
198 NICInfo nd_table
[MAX_NICS
];
200 static int autostart
;
201 static int rtc_utc
= 1;
202 static int rtc_date_offset
= -1; /* -1 means no change */
203 int cirrus_vga_enabled
= 1;
204 int std_vga_enabled
= 0;
205 int vmsvga_enabled
= 0;
206 int xenfb_enabled
= 0;
208 int graphic_width
= 1024;
209 int graphic_height
= 768;
210 int graphic_depth
= 8;
212 int graphic_width
= 800;
213 int graphic_height
= 600;
214 int graphic_depth
= 15;
216 static int full_screen
= 0;
218 static int no_frame
= 0;
221 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
222 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
223 CharDriverState
*virtcon_hds
[MAX_VIRTIO_CONSOLES
];
225 int win2k_install_hack
= 0;
230 const char *assigned_devices
[MAX_DEV_ASSIGN_CMDLINE
];
231 int assigned_devices_index
;
233 const char *vnc_display
;
234 int acpi_enabled
= 1;
238 int virtio_balloon
= 1;
239 const char *virtio_balloon_devaddr
;
244 int graphic_rotate
= 0;
245 uint8_t irq0override
= 1;
249 WatchdogTimerModel
*watchdog
= NULL
;
250 int watchdog_action
= WDT_RESET
;
251 const char *option_rom
[MAX_OPTION_ROMS
];
253 int semihosting_enabled
= 0;
254 int time_drift_fix
= 0;
255 unsigned int kvm_shadow_memory
= 0;
256 const char *mem_path
= NULL
;
258 int mem_prealloc
= 1; /* force preallocation of physical target memory */
263 const char *qemu_name
;
265 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
266 unsigned int nb_prom_envs
= 0;
267 const char *prom_envs
[MAX_PROM_ENVS
];
270 const char *nvram
= NULL
;
271 struct drive_opt drives_opt
[MAX_DRIVES
];
275 uint64_t node_mem
[MAX_NODES
];
276 uint64_t node_cpumask
[MAX_NODES
];
278 static CPUState
*cur_cpu
;
279 static CPUState
*next_cpu
;
280 static int timer_alarm_pending
= 1;
281 /* Conversion factor from emulated instructions to virtual clock ticks. */
282 static int icount_time_shift
;
283 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
284 #define MAX_ICOUNT_SHIFT 10
285 /* Compensate for varying guest execution speed. */
286 static int64_t qemu_icount_bias
;
287 static QEMUTimer
*icount_rt_timer
;
288 static QEMUTimer
*icount_vm_timer
;
289 static QEMUTimer
*nographic_timer
;
291 uint8_t qemu_uuid
[16];
293 static QEMUBootSetHandler
*boot_set_handler
;
294 static void *boot_set_opaque
;
296 /***********************************************************/
297 /* x86 ISA bus support */
299 target_phys_addr_t isa_mem_base
= 0;
302 /***********************************************************/
303 void hw_error(const char *fmt
, ...)
309 fprintf(stderr
, "qemu: hardware error: ");
310 vfprintf(stderr
, fmt
, ap
);
311 fprintf(stderr
, "\n");
312 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
313 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
315 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
317 cpu_dump_state(env
, stderr
, fprintf
, 0);
324 static void set_proc_name(const char *s
)
330 name
[sizeof(name
) - 1] = 0;
331 strncpy(name
, s
, sizeof(name
));
332 /* Could rewrite argv[0] too, but that's a bit more complicated.
333 This simple way is enough for `top'. */
334 prctl(PR_SET_NAME
, name
);
341 static QEMUBalloonEvent
*qemu_balloon_event
;
342 void *qemu_balloon_event_opaque
;
344 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
346 qemu_balloon_event
= func
;
347 qemu_balloon_event_opaque
= opaque
;
350 void qemu_balloon(ram_addr_t target
)
352 if (qemu_balloon_event
)
353 qemu_balloon_event(qemu_balloon_event_opaque
, target
);
356 ram_addr_t
qemu_balloon_status(void)
358 if (qemu_balloon_event
)
359 return qemu_balloon_event(qemu_balloon_event_opaque
, 0);
363 /***********************************************************/
366 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
367 static void *qemu_put_kbd_event_opaque
;
368 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
369 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
371 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
373 qemu_put_kbd_event_opaque
= opaque
;
374 qemu_put_kbd_event
= func
;
377 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
378 void *opaque
, int absolute
,
381 QEMUPutMouseEntry
*s
, *cursor
;
383 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
385 s
->qemu_put_mouse_event
= func
;
386 s
->qemu_put_mouse_event_opaque
= opaque
;
387 s
->qemu_put_mouse_event_absolute
= absolute
;
388 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
391 if (!qemu_put_mouse_event_head
) {
392 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
396 cursor
= qemu_put_mouse_event_head
;
397 while (cursor
->next
!= NULL
)
398 cursor
= cursor
->next
;
401 qemu_put_mouse_event_current
= s
;
406 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
408 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
410 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
413 cursor
= qemu_put_mouse_event_head
;
414 while (cursor
!= NULL
&& cursor
!= entry
) {
416 cursor
= cursor
->next
;
419 if (cursor
== NULL
) // does not exist or list empty
421 else if (prev
== NULL
) { // entry is head
422 qemu_put_mouse_event_head
= cursor
->next
;
423 if (qemu_put_mouse_event_current
== entry
)
424 qemu_put_mouse_event_current
= cursor
->next
;
425 qemu_free(entry
->qemu_put_mouse_event_name
);
430 prev
->next
= entry
->next
;
432 if (qemu_put_mouse_event_current
== entry
)
433 qemu_put_mouse_event_current
= prev
;
435 qemu_free(entry
->qemu_put_mouse_event_name
);
439 void kbd_put_keycode(int keycode
)
441 if (qemu_put_kbd_event
) {
442 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
446 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
448 QEMUPutMouseEvent
*mouse_event
;
449 void *mouse_event_opaque
;
452 if (!qemu_put_mouse_event_current
) {
457 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
459 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
462 if (graphic_rotate
) {
463 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
466 width
= graphic_width
- 1;
467 mouse_event(mouse_event_opaque
,
468 width
- dy
, dx
, dz
, buttons_state
);
470 mouse_event(mouse_event_opaque
,
471 dx
, dy
, dz
, buttons_state
);
475 int kbd_mouse_is_absolute(void)
477 if (!qemu_put_mouse_event_current
)
480 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
483 void do_info_mice(Monitor
*mon
)
485 QEMUPutMouseEntry
*cursor
;
488 if (!qemu_put_mouse_event_head
) {
489 monitor_printf(mon
, "No mouse devices connected\n");
493 monitor_printf(mon
, "Mouse devices available:\n");
494 cursor
= qemu_put_mouse_event_head
;
495 while (cursor
!= NULL
) {
496 monitor_printf(mon
, "%c Mouse #%d: %s\n",
497 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
498 index
, cursor
->qemu_put_mouse_event_name
);
500 cursor
= cursor
->next
;
504 void do_mouse_set(Monitor
*mon
, int index
)
506 QEMUPutMouseEntry
*cursor
;
509 if (!qemu_put_mouse_event_head
) {
510 monitor_printf(mon
, "No mouse devices connected\n");
514 cursor
= qemu_put_mouse_event_head
;
515 while (cursor
!= NULL
&& index
!= i
) {
517 cursor
= cursor
->next
;
521 qemu_put_mouse_event_current
= cursor
;
523 monitor_printf(mon
, "Mouse at given index not found\n");
526 /* compute with 96 bit intermediate result: (a*b)/c */
527 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
532 #ifdef WORDS_BIGENDIAN
542 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
543 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
546 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
550 /***********************************************************/
551 /* real time host monotonic timer */
553 #define QEMU_TIMER_BASE 1000000000LL
557 static int64_t clock_freq
;
559 static void init_get_clock(void)
563 ret
= QueryPerformanceFrequency(&freq
);
565 fprintf(stderr
, "Could not calibrate ticks\n");
568 clock_freq
= freq
.QuadPart
;
571 static int64_t get_clock(void)
574 QueryPerformanceCounter(&ti
);
575 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
580 static int use_rt_clock
;
582 static void init_get_clock(void)
585 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
586 || defined(__DragonFly__)
589 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
596 static int64_t get_clock(void)
598 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
599 || defined(__DragonFly__)
602 clock_gettime(CLOCK_MONOTONIC
, &ts
);
603 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
607 /* XXX: using gettimeofday leads to problems if the date
608 changes, so it should be avoided. */
610 gettimeofday(&tv
, NULL
);
611 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
616 /* Return the virtual CPU time, based on the instruction counter. */
617 static int64_t cpu_get_icount(void)
620 CPUState
*env
= cpu_single_env
;;
621 icount
= qemu_icount
;
624 fprintf(stderr
, "Bad clock read\n");
625 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
627 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
630 /***********************************************************/
631 /* guest cycle counter */
633 static int64_t cpu_ticks_prev
;
634 static int64_t cpu_ticks_offset
;
635 static int64_t cpu_clock_offset
;
636 static int cpu_ticks_enabled
;
638 /* return the host CPU cycle counter and handle stop/restart */
639 int64_t cpu_get_ticks(void)
642 return cpu_get_icount();
644 if (!cpu_ticks_enabled
) {
645 return cpu_ticks_offset
;
648 ticks
= cpu_get_real_ticks();
649 if (cpu_ticks_prev
> ticks
) {
650 /* Note: non increasing ticks may happen if the host uses
652 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
654 cpu_ticks_prev
= ticks
;
655 return ticks
+ cpu_ticks_offset
;
659 /* return the host CPU monotonic timer and handle stop/restart */
660 static int64_t cpu_get_clock(void)
663 if (!cpu_ticks_enabled
) {
664 return cpu_clock_offset
;
667 return ti
+ cpu_clock_offset
;
671 /* enable cpu_get_ticks() */
672 void cpu_enable_ticks(void)
674 if (!cpu_ticks_enabled
) {
675 cpu_ticks_offset
-= cpu_get_real_ticks();
676 cpu_clock_offset
-= get_clock();
677 cpu_ticks_enabled
= 1;
681 /* disable cpu_get_ticks() : the clock is stopped. You must not call
682 cpu_get_ticks() after that. */
683 void cpu_disable_ticks(void)
685 if (cpu_ticks_enabled
) {
686 cpu_ticks_offset
= cpu_get_ticks();
687 cpu_clock_offset
= cpu_get_clock();
688 cpu_ticks_enabled
= 0;
692 /***********************************************************/
695 #define QEMU_TIMER_REALTIME 0
696 #define QEMU_TIMER_VIRTUAL 1
700 /* XXX: add frequency */
708 struct QEMUTimer
*next
;
711 struct qemu_alarm_timer
{
715 int (*start
)(struct qemu_alarm_timer
*t
);
716 void (*stop
)(struct qemu_alarm_timer
*t
);
717 void (*rearm
)(struct qemu_alarm_timer
*t
);
721 #define ALARM_FLAG_DYNTICKS 0x1
722 #define ALARM_FLAG_EXPIRED 0x2
724 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
726 return t
&& (t
->flags
& ALARM_FLAG_DYNTICKS
);
729 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
731 if (!alarm_has_dynticks(t
))
737 /* TODO: MIN_TIMER_REARM_US should be optimized */
738 #define MIN_TIMER_REARM_US 250
740 static struct qemu_alarm_timer
*alarm_timer
;
744 struct qemu_alarm_win32
{
747 } alarm_win32_data
= {0, -1};
749 static int win32_start_timer(struct qemu_alarm_timer
*t
);
750 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
751 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
755 static int unix_start_timer(struct qemu_alarm_timer
*t
);
756 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
760 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
761 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
762 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
764 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
765 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
767 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
768 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
770 #endif /* __linux__ */
774 /* Correlation between real and virtual time is always going to be
775 fairly approximate, so ignore small variation.
776 When the guest is idle real and virtual time will be aligned in
778 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
780 static void icount_adjust(void)
785 static int64_t last_delta
;
786 /* If the VM is not running, then do nothing. */
790 cur_time
= cpu_get_clock();
791 cur_icount
= qemu_get_clock(vm_clock
);
792 delta
= cur_icount
- cur_time
;
793 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
795 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
796 && icount_time_shift
> 0) {
797 /* The guest is getting too far ahead. Slow time down. */
801 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
802 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
803 /* The guest is getting too far behind. Speed time up. */
807 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
810 static void icount_adjust_rt(void * opaque
)
812 qemu_mod_timer(icount_rt_timer
,
813 qemu_get_clock(rt_clock
) + 1000);
817 static void icount_adjust_vm(void * opaque
)
819 qemu_mod_timer(icount_vm_timer
,
820 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
824 static void init_icount_adjust(void)
826 /* Have both realtime and virtual time triggers for speed adjustment.
827 The realtime trigger catches emulated time passing too slowly,
828 the virtual time trigger catches emulated time passing too fast.
829 Realtime triggers occur even when idle, so use them less frequently
831 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
832 qemu_mod_timer(icount_rt_timer
,
833 qemu_get_clock(rt_clock
) + 1000);
834 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
835 qemu_mod_timer(icount_vm_timer
,
836 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
839 static struct qemu_alarm_timer alarm_timers
[] = {
842 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
843 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
844 /* HPET - if available - is preferred */
845 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
846 /* ...otherwise try RTC */
847 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
849 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
851 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
852 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
853 {"win32", 0, win32_start_timer
,
854 win32_stop_timer
, NULL
, &alarm_win32_data
},
859 static void show_available_alarms(void)
863 printf("Available alarm timers, in order of precedence:\n");
864 for (i
= 0; alarm_timers
[i
].name
; i
++)
865 printf("%s\n", alarm_timers
[i
].name
);
868 static void configure_alarms(char const *opt
)
872 int count
= ARRAY_SIZE(alarm_timers
) - 1;
875 struct qemu_alarm_timer tmp
;
877 if (!strcmp(opt
, "?")) {
878 show_available_alarms();
884 /* Reorder the array */
885 name
= strtok(arg
, ",");
887 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
888 if (!strcmp(alarm_timers
[i
].name
, name
))
893 fprintf(stderr
, "Unknown clock %s\n", name
);
902 tmp
= alarm_timers
[i
];
903 alarm_timers
[i
] = alarm_timers
[cur
];
904 alarm_timers
[cur
] = tmp
;
908 name
= strtok(NULL
, ",");
914 /* Disable remaining timers */
915 for (i
= cur
; i
< count
; i
++)
916 alarm_timers
[i
].name
= NULL
;
918 show_available_alarms();
926 static QEMUTimer
*active_timers
[2];
928 static QEMUClock
*qemu_new_clock(int type
)
931 clock
= qemu_mallocz(sizeof(QEMUClock
));
936 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
940 ts
= qemu_mallocz(sizeof(QEMUTimer
));
947 void qemu_free_timer(QEMUTimer
*ts
)
952 /* stop a timer, but do not dealloc it */
953 void qemu_del_timer(QEMUTimer
*ts
)
957 /* NOTE: this code must be signal safe because
958 qemu_timer_expired() can be called from a signal. */
959 pt
= &active_timers
[ts
->clock
->type
];
972 /* modify the current timer so that it will be fired when current_time
973 >= expire_time. The corresponding callback will be called. */
974 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
980 /* add the timer in the sorted list */
981 /* NOTE: this code must be signal safe because
982 qemu_timer_expired() can be called from a signal. */
983 pt
= &active_timers
[ts
->clock
->type
];
988 if (t
->expire_time
> expire_time
)
992 ts
->expire_time
= expire_time
;
996 /* Rearm if necessary */
997 if (pt
== &active_timers
[ts
->clock
->type
]) {
998 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
999 qemu_rearm_alarm_timer(alarm_timer
);
1001 /* Interrupt execution to force deadline recalculation. */
1003 qemu_notify_event();
1007 int qemu_timer_pending(QEMUTimer
*ts
)
1010 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1017 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1021 return (timer_head
->expire_time
<= current_time
);
1024 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1030 if (!ts
|| ts
->expire_time
> current_time
)
1032 /* remove timer from the list before calling the callback */
1033 *ptimer_head
= ts
->next
;
1036 /* run the callback (the timer list can be modified) */
1041 int64_t qemu_get_clock(QEMUClock
*clock
)
1043 switch(clock
->type
) {
1044 case QEMU_TIMER_REALTIME
:
1045 return get_clock() / 1000000;
1047 case QEMU_TIMER_VIRTUAL
:
1049 return cpu_get_icount();
1051 return cpu_get_clock();
1056 static void init_timers(void)
1059 ticks_per_sec
= QEMU_TIMER_BASE
;
1060 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1061 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1065 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1067 uint64_t expire_time
;
1069 if (qemu_timer_pending(ts
)) {
1070 expire_time
= ts
->expire_time
;
1074 qemu_put_be64(f
, expire_time
);
1077 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1079 uint64_t expire_time
;
1081 expire_time
= qemu_get_be64(f
);
1082 if (expire_time
!= -1) {
1083 qemu_mod_timer(ts
, expire_time
);
1089 static void timer_save(QEMUFile
*f
, void *opaque
)
1091 if (cpu_ticks_enabled
) {
1092 hw_error("cannot save state if virtual timers are running");
1094 qemu_put_be64(f
, cpu_ticks_offset
);
1095 qemu_put_be64(f
, ticks_per_sec
);
1096 qemu_put_be64(f
, cpu_clock_offset
);
1099 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1101 if (version_id
!= 1 && version_id
!= 2)
1103 if (cpu_ticks_enabled
) {
1106 cpu_ticks_offset
=qemu_get_be64(f
);
1107 ticks_per_sec
=qemu_get_be64(f
);
1108 if (version_id
== 2) {
1109 cpu_clock_offset
=qemu_get_be64(f
);
1114 static void qemu_event_increment(void);
1117 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1118 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1121 static void host_alarm_handler(int host_signum
)
1125 #define DISP_FREQ 1000
1127 static int64_t delta_min
= INT64_MAX
;
1128 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1130 ti
= qemu_get_clock(vm_clock
);
1131 if (last_clock
!= 0) {
1132 delta
= ti
- last_clock
;
1133 if (delta
< delta_min
)
1135 if (delta
> delta_max
)
1138 if (++count
== DISP_FREQ
) {
1139 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1140 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1141 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1142 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1143 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1145 delta_min
= INT64_MAX
;
1153 if (alarm_has_dynticks(alarm_timer
) ||
1155 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1156 qemu_get_clock(vm_clock
))) ||
1157 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1158 qemu_get_clock(rt_clock
))) {
1159 qemu_event_increment();
1160 if (alarm_timer
) alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1162 #ifndef CONFIG_IOTHREAD
1164 /* stop the currently executing cpu because a timer occured */
1167 if (next_cpu
->kqemu_enabled
) {
1168 kqemu_cpu_interrupt(next_cpu
);
1173 timer_alarm_pending
= 1;
1174 qemu_notify_event();
1178 static int64_t qemu_next_deadline(void)
1182 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1183 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1184 qemu_get_clock(vm_clock
);
1186 /* To avoid problems with overflow limit this to 2^32. */
1196 #if defined(__linux__) || defined(_WIN32)
1197 static uint64_t qemu_next_deadline_dyntick(void)
1205 delta
= (qemu_next_deadline() + 999) / 1000;
1207 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1208 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1209 qemu_get_clock(rt_clock
))*1000;
1210 if (rtdelta
< delta
)
1214 if (delta
< MIN_TIMER_REARM_US
)
1215 delta
= MIN_TIMER_REARM_US
;
1223 /* Sets a specific flag */
1224 static int fcntl_setfl(int fd
, int flag
)
1228 flags
= fcntl(fd
, F_GETFL
);
1232 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1238 #if defined(__linux__)
1240 #define RTC_FREQ 1024
1242 static void enable_sigio_timer(int fd
)
1244 struct sigaction act
;
1247 sigfillset(&act
.sa_mask
);
1249 act
.sa_handler
= host_alarm_handler
;
1251 sigaction(SIGIO
, &act
, NULL
);
1252 fcntl_setfl(fd
, O_ASYNC
);
1253 fcntl(fd
, F_SETOWN
, getpid());
1256 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1258 struct hpet_info info
;
1261 fd
= open("/dev/hpet", O_RDONLY
);
1266 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1268 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1269 "error, but for better emulation accuracy type:\n"
1270 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1274 /* Check capabilities */
1275 r
= ioctl(fd
, HPET_INFO
, &info
);
1279 /* Enable periodic mode */
1280 r
= ioctl(fd
, HPET_EPI
, 0);
1281 if (info
.hi_flags
&& (r
< 0))
1284 /* Enable interrupt */
1285 r
= ioctl(fd
, HPET_IE_ON
, 0);
1289 enable_sigio_timer(fd
);
1290 t
->priv
= (void *)(long)fd
;
1298 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1300 int fd
= (long)t
->priv
;
1305 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1308 unsigned long current_rtc_freq
= 0;
1310 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1313 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1314 if (current_rtc_freq
!= RTC_FREQ
&&
1315 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1316 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1317 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1318 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1321 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1327 enable_sigio_timer(rtc_fd
);
1329 t
->priv
= (void *)(long)rtc_fd
;
1334 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1336 int rtc_fd
= (long)t
->priv
;
1341 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1345 struct sigaction act
;
1347 sigfillset(&act
.sa_mask
);
1349 act
.sa_handler
= host_alarm_handler
;
1351 sigaction(SIGALRM
, &act
, NULL
);
1354 * Initialize ev struct to 0 to avoid valgrind complaining
1355 * about uninitialized data in timer_create call
1357 memset(&ev
, 0, sizeof(ev
));
1358 ev
.sigev_value
.sival_int
= 0;
1359 ev
.sigev_notify
= SIGEV_SIGNAL
;
1360 ev
.sigev_signo
= SIGALRM
;
1362 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1363 perror("timer_create");
1365 /* disable dynticks */
1366 fprintf(stderr
, "Dynamic Ticks disabled\n");
1371 t
->priv
= (void *)(long)host_timer
;
1376 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1378 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1380 timer_delete(host_timer
);
1383 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1385 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1386 struct itimerspec timeout
;
1387 int64_t nearest_delta_us
= INT64_MAX
;
1390 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1391 !active_timers
[QEMU_TIMER_VIRTUAL
])
1394 nearest_delta_us
= qemu_next_deadline_dyntick();
1396 /* check whether a timer is already running */
1397 if (timer_gettime(host_timer
, &timeout
)) {
1399 fprintf(stderr
, "Internal timer error: aborting\n");
1402 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1403 if (current_us
&& current_us
<= nearest_delta_us
)
1406 timeout
.it_interval
.tv_sec
= 0;
1407 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1408 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1409 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1410 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1412 fprintf(stderr
, "Internal timer error: aborting\n");
1417 #endif /* defined(__linux__) */
1419 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1421 struct sigaction act
;
1422 struct itimerval itv
;
1426 sigfillset(&act
.sa_mask
);
1428 act
.sa_handler
= host_alarm_handler
;
1430 sigaction(SIGALRM
, &act
, NULL
);
1432 itv
.it_interval
.tv_sec
= 0;
1433 /* for i386 kernel 2.6 to get 1 ms */
1434 itv
.it_interval
.tv_usec
= 999;
1435 itv
.it_value
.tv_sec
= 0;
1436 itv
.it_value
.tv_usec
= 10 * 1000;
1438 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1445 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1447 struct itimerval itv
;
1449 memset(&itv
, 0, sizeof(itv
));
1450 setitimer(ITIMER_REAL
, &itv
, NULL
);
1453 #endif /* !defined(_WIN32) */
1458 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1461 struct qemu_alarm_win32
*data
= t
->priv
;
1464 memset(&tc
, 0, sizeof(tc
));
1465 timeGetDevCaps(&tc
, sizeof(tc
));
1467 if (data
->period
< tc
.wPeriodMin
)
1468 data
->period
= tc
.wPeriodMin
;
1470 timeBeginPeriod(data
->period
);
1472 flags
= TIME_CALLBACK_FUNCTION
;
1473 if (alarm_has_dynticks(t
))
1474 flags
|= TIME_ONESHOT
;
1476 flags
|= TIME_PERIODIC
;
1478 data
->timerId
= timeSetEvent(1, // interval (ms)
1479 data
->period
, // resolution
1480 host_alarm_handler
, // function
1481 (DWORD
)t
, // parameter
1484 if (!data
->timerId
) {
1485 perror("Failed to initialize win32 alarm timer");
1486 timeEndPeriod(data
->period
);
1493 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1495 struct qemu_alarm_win32
*data
= t
->priv
;
1497 timeKillEvent(data
->timerId
);
1498 timeEndPeriod(data
->period
);
1501 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1503 struct qemu_alarm_win32
*data
= t
->priv
;
1504 uint64_t nearest_delta_us
;
1506 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1507 !active_timers
[QEMU_TIMER_VIRTUAL
])
1510 nearest_delta_us
= qemu_next_deadline_dyntick();
1511 nearest_delta_us
/= 1000;
1513 timeKillEvent(data
->timerId
);
1515 data
->timerId
= timeSetEvent(1,
1519 TIME_ONESHOT
| TIME_PERIODIC
);
1521 if (!data
->timerId
) {
1522 perror("Failed to re-arm win32 alarm timer");
1524 timeEndPeriod(data
->period
);
1531 static int init_timer_alarm(void)
1533 struct qemu_alarm_timer
*t
= NULL
;
1536 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1537 t
= &alarm_timers
[i
];
1557 static void quit_timers(void)
1559 alarm_timer
->stop(alarm_timer
);
1563 /***********************************************************/
1564 /* host time/date access */
1565 void qemu_get_timedate(struct tm
*tm
, int offset
)
1572 if (rtc_date_offset
== -1) {
1576 ret
= localtime(&ti
);
1578 ti
-= rtc_date_offset
;
1582 memcpy(tm
, ret
, sizeof(struct tm
));
1585 int qemu_timedate_diff(struct tm
*tm
)
1589 if (rtc_date_offset
== -1)
1591 seconds
= mktimegm(tm
);
1593 seconds
= mktime(tm
);
1595 seconds
= mktimegm(tm
) + rtc_date_offset
;
1597 return seconds
- time(NULL
);
1601 static void socket_cleanup(void)
1606 static int socket_init(void)
1611 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1613 err
= WSAGetLastError();
1614 fprintf(stderr
, "WSAStartup: %d\n", err
);
1617 atexit(socket_cleanup
);
1622 int get_next_param_value(char *buf
, int buf_size
,
1623 const char *tag
, const char **pstr
)
1630 p
= get_opt_name(option
, sizeof(option
), p
, '=');
1634 if (!strcmp(tag
, option
)) {
1635 *pstr
= get_opt_value(buf
, buf_size
, p
);
1636 if (**pstr
== ',') {
1641 p
= get_opt_value(NULL
, 0, p
);
1650 int get_param_value(char *buf
, int buf_size
,
1651 const char *tag
, const char *str
)
1653 return get_next_param_value(buf
, buf_size
, tag
, &str
);
1656 int check_params(char *buf
, int buf_size
,
1657 const char * const *params
, const char *str
)
1663 while (*p
!= '\0') {
1664 p
= get_opt_name(buf
, buf_size
, p
, '=');
1669 for (i
= 0; params
[i
] != NULL
; i
++) {
1670 if (!strcmp(params
[i
], buf
)) {
1674 if (params
[i
] == NULL
) {
1677 p
= get_opt_value(NULL
, 0, p
);
1686 /***********************************************************/
1687 /* Bluetooth support */
1690 static struct HCIInfo
*hci_table
[MAX_NICS
];
1692 static struct bt_vlan_s
{
1693 struct bt_scatternet_s net
;
1695 struct bt_vlan_s
*next
;
1698 /* find or alloc a new bluetooth "VLAN" */
1699 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1701 struct bt_vlan_s
**pvlan
, *vlan
;
1702 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1706 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1708 pvlan
= &first_bt_vlan
;
1709 while (*pvlan
!= NULL
)
1710 pvlan
= &(*pvlan
)->next
;
1715 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1719 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1724 static struct HCIInfo null_hci
= {
1725 .cmd_send
= null_hci_send
,
1726 .sco_send
= null_hci_send
,
1727 .acl_send
= null_hci_send
,
1728 .bdaddr_set
= null_hci_addr_set
,
1731 struct HCIInfo
*qemu_next_hci(void)
1733 if (cur_hci
== nb_hcis
)
1736 return hci_table
[cur_hci
++];
1739 static struct HCIInfo
*hci_init(const char *str
)
1742 struct bt_scatternet_s
*vlan
= 0;
1744 if (!strcmp(str
, "null"))
1747 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
1749 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
1750 else if (!strncmp(str
, "hci", 3)) {
1753 if (!strncmp(str
+ 3, ",vlan=", 6)) {
1754 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
1759 vlan
= qemu_find_bt_vlan(0);
1761 return bt_new_hci(vlan
);
1764 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
1769 static int bt_hci_parse(const char *str
)
1771 struct HCIInfo
*hci
;
1774 if (nb_hcis
>= MAX_NICS
) {
1775 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
1779 hci
= hci_init(str
);
1788 bdaddr
.b
[5] = 0x56 + nb_hcis
;
1789 hci
->bdaddr_set(hci
, bdaddr
.b
);
1791 hci_table
[nb_hcis
++] = hci
;
1796 static void bt_vhci_add(int vlan_id
)
1798 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
1801 fprintf(stderr
, "qemu: warning: adding a VHCI to "
1802 "an empty scatternet %i\n", vlan_id
);
1804 bt_vhci_init(bt_new_hci(vlan
));
1807 static struct bt_device_s
*bt_device_add(const char *opt
)
1809 struct bt_scatternet_s
*vlan
;
1811 char *endp
= strstr(opt
, ",vlan=");
1812 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
1815 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
1818 vlan_id
= strtol(endp
+ 6, &endp
, 0);
1820 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
1825 vlan
= qemu_find_bt_vlan(vlan_id
);
1828 fprintf(stderr
, "qemu: warning: adding a slave device to "
1829 "an empty scatternet %i\n", vlan_id
);
1831 if (!strcmp(devname
, "keyboard"))
1832 return bt_keyboard_init(vlan
);
1834 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
1838 static int bt_parse(const char *opt
)
1840 const char *endp
, *p
;
1843 if (strstart(opt
, "hci", &endp
)) {
1844 if (!*endp
|| *endp
== ',') {
1846 if (!strstart(endp
, ",vlan=", 0))
1849 return bt_hci_parse(opt
);
1851 } else if (strstart(opt
, "vhci", &endp
)) {
1852 if (!*endp
|| *endp
== ',') {
1854 if (strstart(endp
, ",vlan=", &p
)) {
1855 vlan
= strtol(p
, (char **) &endp
, 0);
1857 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
1861 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
1870 } else if (strstart(opt
, "device:", &endp
))
1871 return !bt_device_add(endp
);
1873 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
1877 /***********************************************************/
1878 /* QEMU Block devices */
1880 #define HD_ALIAS "index=%d,media=disk"
1881 #define CDROM_ALIAS "index=2,media=cdrom"
1882 #define FD_ALIAS "index=%d,if=floppy"
1883 #define PFLASH_ALIAS "if=pflash"
1884 #define MTD_ALIAS "if=mtd"
1885 #define SD_ALIAS "index=0,if=sd"
1887 static int drive_opt_get_free_idx(void)
1891 for (index
= 0; index
< MAX_DRIVES
; index
++)
1892 if (!drives_opt
[index
].used
) {
1893 drives_opt
[index
].used
= 1;
1900 static int drive_get_free_idx(void)
1904 for (index
= 0; index
< MAX_DRIVES
; index
++)
1905 if (!drives_table
[index
].used
) {
1906 drives_table
[index
].used
= 1;
1913 int drive_add(const char *file
, const char *fmt
, ...)
1916 int index
= drive_opt_get_free_idx();
1918 if (nb_drives_opt
>= MAX_DRIVES
|| index
== -1) {
1919 fprintf(stderr
, "qemu: too many drives\n");
1923 drives_opt
[index
].file
= file
;
1925 vsnprintf(drives_opt
[index
].opt
,
1926 sizeof(drives_opt
[0].opt
), fmt
, ap
);
1933 void drive_remove(int index
)
1935 drives_opt
[index
].used
= 0;
1939 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
1943 /* seek interface, bus and unit */
1945 for (index
= 0; index
< MAX_DRIVES
; index
++)
1946 if (drives_table
[index
].type
== type
&&
1947 drives_table
[index
].bus
== bus
&&
1948 drives_table
[index
].unit
== unit
&&
1949 drives_table
[index
].used
)
1955 int drive_get_max_bus(BlockInterfaceType type
)
1961 for (index
= 0; index
< nb_drives
; index
++) {
1962 if(drives_table
[index
].type
== type
&&
1963 drives_table
[index
].bus
> max_bus
)
1964 max_bus
= drives_table
[index
].bus
;
1969 const char *drive_get_serial(BlockDriverState
*bdrv
)
1973 for (index
= 0; index
< nb_drives
; index
++)
1974 if (drives_table
[index
].bdrv
== bdrv
)
1975 return drives_table
[index
].serial
;
1980 BlockInterfaceErrorAction
drive_get_onerror(BlockDriverState
*bdrv
)
1984 for (index
= 0; index
< nb_drives
; index
++)
1985 if (drives_table
[index
].bdrv
== bdrv
)
1986 return drives_table
[index
].onerror
;
1988 return BLOCK_ERR_STOP_ENOSPC
;
1991 static void bdrv_format_print(void *opaque
, const char *name
)
1993 fprintf(stderr
, " %s", name
);
1996 void drive_uninit(BlockDriverState
*bdrv
)
2000 for (i
= 0; i
< MAX_DRIVES
; i
++)
2001 if (drives_table
[i
].bdrv
== bdrv
) {
2002 drives_table
[i
].bdrv
= NULL
;
2003 drives_table
[i
].used
= 0;
2004 drive_remove(drives_table
[i
].drive_opt_idx
);
2010 int drive_init(struct drive_opt
*arg
, int snapshot
, void *opaque
)
2016 const char *mediastr
= "";
2017 BlockInterfaceType type
;
2018 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
2019 int bus_id
, unit_id
;
2020 int cyls
, heads
, secs
, translation
;
2021 BlockDriverState
*bdrv
;
2022 BlockDriver
*drv
= NULL
;
2023 QEMUMachine
*machine
= opaque
;
2027 int bdrv_flags
, onerror
;
2028 const char *devaddr
;
2029 int drives_table_idx
;
2030 char *str
= arg
->opt
;
2031 static const char * const params
[] = { "bus", "unit", "if", "index",
2032 "cyls", "heads", "secs", "trans",
2033 "media", "snapshot", "file",
2034 "cache", "format", "serial",
2039 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
2040 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
2046 cyls
= heads
= secs
= 0;
2049 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2053 if (machine
->use_scsi
) {
2055 max_devs
= MAX_SCSI_DEVS
;
2056 pstrcpy(devname
, sizeof(devname
), "scsi");
2059 max_devs
= MAX_IDE_DEVS
;
2060 pstrcpy(devname
, sizeof(devname
), "ide");
2064 /* extract parameters */
2066 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
2067 bus_id
= strtol(buf
, NULL
, 0);
2069 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
2074 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
2075 unit_id
= strtol(buf
, NULL
, 0);
2077 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
2082 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
2083 pstrcpy(devname
, sizeof(devname
), buf
);
2084 if (!strcmp(buf
, "ide")) {
2086 max_devs
= MAX_IDE_DEVS
;
2087 } else if (!strcmp(buf
, "scsi")) {
2089 max_devs
= MAX_SCSI_DEVS
;
2090 } else if (!strcmp(buf
, "floppy")) {
2093 } else if (!strcmp(buf
, "pflash")) {
2096 } else if (!strcmp(buf
, "mtd")) {
2099 } else if (!strcmp(buf
, "sd")) {
2102 } else if (!strcmp(buf
, "virtio")) {
2105 } else if (!strcmp(buf
, "xen")) {
2109 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
2114 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
2115 index
= strtol(buf
, NULL
, 0);
2117 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
2122 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
2123 cyls
= strtol(buf
, NULL
, 0);
2126 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
2127 heads
= strtol(buf
, NULL
, 0);
2130 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
2131 secs
= strtol(buf
, NULL
, 0);
2134 if (cyls
|| heads
|| secs
) {
2135 if (cyls
< 1 || cyls
> 16383) {
2136 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
2139 if (heads
< 1 || heads
> 16) {
2140 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
2143 if (secs
< 1 || secs
> 63) {
2144 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
2149 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
2152 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2156 if (!strcmp(buf
, "none"))
2157 translation
= BIOS_ATA_TRANSLATION_NONE
;
2158 else if (!strcmp(buf
, "lba"))
2159 translation
= BIOS_ATA_TRANSLATION_LBA
;
2160 else if (!strcmp(buf
, "auto"))
2161 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2163 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
2168 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
2169 if (!strcmp(buf
, "disk")) {
2171 } else if (!strcmp(buf
, "cdrom")) {
2172 if (cyls
|| secs
|| heads
) {
2174 "qemu: '%s' invalid physical CHS format\n", str
);
2177 media
= MEDIA_CDROM
;
2179 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
2184 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
2185 if (!strcmp(buf
, "on"))
2187 else if (!strcmp(buf
, "off"))
2190 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
2195 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
2196 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2198 else if (!strcmp(buf
, "writethrough"))
2200 else if (!strcmp(buf
, "writeback"))
2203 fprintf(stderr
, "qemu: invalid cache option\n");
2208 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
2209 if (strcmp(buf
, "?") == 0) {
2210 fprintf(stderr
, "qemu: Supported formats:");
2211 bdrv_iterate_format(bdrv_format_print
, NULL
);
2212 fprintf(stderr
, "\n");
2215 drv
= bdrv_find_format(buf
);
2217 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2222 if (get_param_value(buf
, sizeof(buf
), "boot", str
)) {
2223 if (!strcmp(buf
, "on")) {
2224 if (extboot_drive
!= -1) {
2225 fprintf(stderr
, "qemu: two bootable drives specified\n");
2228 extboot_drive
= nb_drives
;
2229 } else if (strcmp(buf
, "off")) {
2230 fprintf(stderr
, "qemu: '%s' invalid boot option\n", str
);
2235 if (arg
->file
== NULL
)
2236 get_param_value(file
, sizeof(file
), "file", str
);
2238 pstrcpy(file
, sizeof(file
), arg
->file
);
2240 if (!get_param_value(serial
, sizeof(serial
), "serial", str
))
2241 memset(serial
, 0, sizeof(serial
));
2243 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2244 if (get_param_value(buf
, sizeof(serial
), "werror", str
)) {
2245 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2246 fprintf(stderr
, "werror is no supported by this format\n");
2249 if (!strcmp(buf
, "ignore"))
2250 onerror
= BLOCK_ERR_IGNORE
;
2251 else if (!strcmp(buf
, "enospc"))
2252 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2253 else if (!strcmp(buf
, "stop"))
2254 onerror
= BLOCK_ERR_STOP_ANY
;
2255 else if (!strcmp(buf
, "report"))
2256 onerror
= BLOCK_ERR_REPORT
;
2258 fprintf(stderr
, "qemu: '%s' invalid write error action\n", buf
);
2264 if (get_param_value(buf
, sizeof(buf
), "addr", str
)) {
2265 if (type
!= IF_VIRTIO
) {
2266 fprintf(stderr
, "addr is not supported by in '%s'\n", str
);
2269 devaddr
= strdup(buf
);
2272 /* compute bus and unit according index */
2275 if (bus_id
!= 0 || unit_id
!= -1) {
2277 "qemu: '%s' index cannot be used with bus and unit\n", str
);
2285 unit_id
= index
% max_devs
;
2286 bus_id
= index
/ max_devs
;
2290 /* if user doesn't specify a unit_id,
2291 * try to find the first free
2294 if (unit_id
== -1) {
2296 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
2298 if (max_devs
&& unit_id
>= max_devs
) {
2299 unit_id
-= max_devs
;
2307 if (max_devs
&& unit_id
>= max_devs
) {
2308 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
2309 str
, unit_id
, max_devs
- 1);
2314 * ignore multiple definitions
2317 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
2322 if (type
== IF_IDE
|| type
== IF_SCSI
)
2323 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2325 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
2326 devname
, bus_id
, mediastr
, unit_id
);
2328 snprintf(buf
, sizeof(buf
), "%s%s%i",
2329 devname
, mediastr
, unit_id
);
2330 bdrv
= bdrv_new(buf
);
2331 drives_table_idx
= drive_get_free_idx();
2332 drives_table
[drives_table_idx
].bdrv
= bdrv
;
2333 drives_table
[drives_table_idx
].devaddr
= devaddr
;
2334 drives_table
[drives_table_idx
].type
= type
;
2335 drives_table
[drives_table_idx
].bus
= bus_id
;
2336 drives_table
[drives_table_idx
].unit
= unit_id
;
2337 drives_table
[drives_table_idx
].onerror
= onerror
;
2338 drives_table
[drives_table_idx
].drive_opt_idx
= arg
- drives_opt
;
2339 strncpy(drives_table
[drives_table_idx
].serial
, serial
, sizeof(serial
));
2349 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
2350 bdrv_set_translation_hint(bdrv
, translation
);
2354 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
2359 /* FIXME: This isn't really a floppy, but it's a reasonable
2362 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
2375 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2376 cache
= 2; /* always use write-back with snapshot */
2378 if (cache
== 0) /* no caching */
2379 bdrv_flags
|= BDRV_O_NOCACHE
;
2380 else if (cache
== 2) /* write-back */
2381 bdrv_flags
|= BDRV_O_CACHE_WB
;
2382 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0) {
2383 fprintf(stderr
, "qemu: could not open disk image %s\n",
2387 if (bdrv_key_required(bdrv
))
2389 return drives_table_idx
;
2392 void qemu_register_boot_set(QEMUBootSetHandler
*func
, void *opaque
)
2394 boot_set_handler
= func
;
2395 boot_set_opaque
= opaque
;
2398 int qemu_boot_set(const char *boot_devices
)
2400 if (!boot_set_handler
) {
2403 return boot_set_handler(boot_set_opaque
, boot_devices
);
2406 static int parse_bootdevices(char *devices
)
2408 /* We just do some generic consistency checks */
2412 for (p
= devices
; *p
!= '\0'; p
++) {
2413 /* Allowed boot devices are:
2414 * a-b: floppy disk drives
2415 * c-f: IDE disk drives
2416 * g-m: machine implementation dependant drives
2417 * n-p: network devices
2418 * It's up to each machine implementation to check if the given boot
2419 * devices match the actual hardware implementation and firmware
2422 if (*p
< 'a' || *p
> 'p') {
2423 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
2426 if (bitmap
& (1 << (*p
- 'a'))) {
2427 fprintf(stderr
, "Boot device '%c' was given twice\n", *p
);
2430 bitmap
|= 1 << (*p
- 'a');
2435 static void restore_boot_devices(void *opaque
)
2437 char *standard_boot_devices
= opaque
;
2439 qemu_boot_set(standard_boot_devices
);
2441 qemu_unregister_reset(restore_boot_devices
, standard_boot_devices
);
2442 qemu_free(standard_boot_devices
);
2445 static void numa_add(const char *optarg
)
2449 unsigned long long value
, endvalue
;
2452 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2453 if (!strcmp(option
, "node")) {
2454 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2455 nodenr
= nb_numa_nodes
;
2457 nodenr
= strtoull(option
, NULL
, 10);
2460 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2461 node_mem
[nodenr
] = 0;
2463 value
= strtoull(option
, &endptr
, 0);
2465 case 0: case 'M': case 'm':
2472 node_mem
[nodenr
] = value
;
2474 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2475 node_cpumask
[nodenr
] = 0;
2477 value
= strtoull(option
, &endptr
, 10);
2480 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2482 if (*endptr
== '-') {
2483 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2484 if (endvalue
>= 63) {
2487 "only 63 CPUs in NUMA mode supported.\n");
2489 value
= (1 << (endvalue
+ 1)) - (1 << value
);
2494 node_cpumask
[nodenr
] = value
;
2501 /***********************************************************/
2504 static USBPort
*used_usb_ports
;
2505 static USBPort
*free_usb_ports
;
2507 /* ??? Maybe change this to register a hub to keep track of the topology. */
2508 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
2509 usb_attachfn attach
)
2511 port
->opaque
= opaque
;
2512 port
->index
= index
;
2513 port
->attach
= attach
;
2514 port
->next
= free_usb_ports
;
2515 free_usb_ports
= port
;
2518 int usb_device_add_dev(USBDevice
*dev
)
2522 /* Find a USB port to add the device to. */
2523 port
= free_usb_ports
;
2527 /* Create a new hub and chain it on. */
2528 free_usb_ports
= NULL
;
2529 port
->next
= used_usb_ports
;
2530 used_usb_ports
= port
;
2532 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
2533 usb_attach(port
, hub
);
2534 port
= free_usb_ports
;
2537 free_usb_ports
= port
->next
;
2538 port
->next
= used_usb_ports
;
2539 used_usb_ports
= port
;
2540 usb_attach(port
, dev
);
2544 static void usb_msd_password_cb(void *opaque
, int err
)
2546 USBDevice
*dev
= opaque
;
2549 usb_device_add_dev(dev
);
2551 dev
->handle_destroy(dev
);
2554 static int usb_device_add(const char *devname
, int is_hotplug
)
2559 if (!free_usb_ports
)
2562 if (strstart(devname
, "host:", &p
)) {
2563 dev
= usb_host_device_open(p
);
2564 } else if (!strcmp(devname
, "mouse")) {
2565 dev
= usb_mouse_init();
2566 } else if (!strcmp(devname
, "tablet")) {
2567 dev
= usb_tablet_init();
2568 } else if (!strcmp(devname
, "keyboard")) {
2569 dev
= usb_keyboard_init();
2570 } else if (strstart(devname
, "disk:", &p
)) {
2571 BlockDriverState
*bs
;
2573 dev
= usb_msd_init(p
);
2576 bs
= usb_msd_get_bdrv(dev
);
2577 if (bdrv_key_required(bs
)) {
2580 monitor_read_bdrv_key_start(cur_mon
, bs
, usb_msd_password_cb
,
2585 } else if (!strcmp(devname
, "wacom-tablet")) {
2586 dev
= usb_wacom_init();
2587 } else if (strstart(devname
, "serial:", &p
)) {
2588 dev
= usb_serial_init(p
);
2589 #ifdef CONFIG_BRLAPI
2590 } else if (!strcmp(devname
, "braille")) {
2591 dev
= usb_baum_init();
2593 } else if (strstart(devname
, "net:", &p
)) {
2596 if (net_client_init(NULL
, "nic", p
) < 0)
2598 nd_table
[nic
].model
= "usb";
2599 dev
= usb_net_init(&nd_table
[nic
]);
2600 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2601 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2602 bt_new_hci(qemu_find_bt_vlan(0)));
2609 return usb_device_add_dev(dev
);
2612 int usb_device_del_addr(int bus_num
, int addr
)
2618 if (!used_usb_ports
)
2624 lastp
= &used_usb_ports
;
2625 port
= used_usb_ports
;
2626 while (port
&& port
->dev
->addr
!= addr
) {
2627 lastp
= &port
->next
;
2635 *lastp
= port
->next
;
2636 usb_attach(port
, NULL
);
2637 dev
->handle_destroy(dev
);
2638 port
->next
= free_usb_ports
;
2639 free_usb_ports
= port
;
2643 static int usb_device_del(const char *devname
)
2648 if (strstart(devname
, "host:", &p
))
2649 return usb_host_device_close(p
);
2651 if (!used_usb_ports
)
2654 p
= strchr(devname
, '.');
2657 bus_num
= strtoul(devname
, NULL
, 0);
2658 addr
= strtoul(p
+ 1, NULL
, 0);
2660 return usb_device_del_addr(bus_num
, addr
);
2663 void do_usb_add(Monitor
*mon
, const char *devname
)
2665 usb_device_add(devname
, 1);
2668 void do_usb_del(Monitor
*mon
, const char *devname
)
2670 usb_device_del(devname
);
2673 void usb_info(Monitor
*mon
)
2677 const char *speed_str
;
2680 monitor_printf(mon
, "USB support not enabled\n");
2684 for (port
= used_usb_ports
; port
; port
= port
->next
) {
2688 switch(dev
->speed
) {
2692 case USB_SPEED_FULL
:
2695 case USB_SPEED_HIGH
:
2702 monitor_printf(mon
, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2703 0, dev
->addr
, speed_str
, dev
->devname
);
2707 /***********************************************************/
2708 /* PCMCIA/Cardbus */
2710 static struct pcmcia_socket_entry_s
{
2711 PCMCIASocket
*socket
;
2712 struct pcmcia_socket_entry_s
*next
;
2713 } *pcmcia_sockets
= 0;
2715 void pcmcia_socket_register(PCMCIASocket
*socket
)
2717 struct pcmcia_socket_entry_s
*entry
;
2719 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2720 entry
->socket
= socket
;
2721 entry
->next
= pcmcia_sockets
;
2722 pcmcia_sockets
= entry
;
2725 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2727 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2729 ptr
= &pcmcia_sockets
;
2730 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2731 if (entry
->socket
== socket
) {
2737 void pcmcia_info(Monitor
*mon
)
2739 struct pcmcia_socket_entry_s
*iter
;
2741 if (!pcmcia_sockets
)
2742 monitor_printf(mon
, "No PCMCIA sockets\n");
2744 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2745 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2746 iter
->socket
->attached
? iter
->socket
->card_string
:
2750 /***********************************************************/
2751 /* register display */
2753 struct DisplayAllocator default_allocator
= {
2754 defaultallocator_create_displaysurface
,
2755 defaultallocator_resize_displaysurface
,
2756 defaultallocator_free_displaysurface
2759 void register_displaystate(DisplayState
*ds
)
2769 DisplayState
*get_displaystate(void)
2771 return display_state
;
2774 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
2776 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
2777 return ds
->allocator
;
2782 static void dumb_display_init(void)
2784 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
2785 ds
->allocator
= &default_allocator
;
2786 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
2787 register_displaystate(ds
);
2790 /***********************************************************/
2793 typedef struct IOHandlerRecord
{
2795 IOCanRWHandler
*fd_read_poll
;
2797 IOHandler
*fd_write
;
2800 /* temporary data */
2802 struct IOHandlerRecord
*next
;
2805 static IOHandlerRecord
*first_io_handler
;
2807 /* XXX: fd_read_poll should be suppressed, but an API change is
2808 necessary in the character devices to suppress fd_can_read(). */
2809 int qemu_set_fd_handler2(int fd
,
2810 IOCanRWHandler
*fd_read_poll
,
2812 IOHandler
*fd_write
,
2815 IOHandlerRecord
**pioh
, *ioh
;
2817 if (!fd_read
&& !fd_write
) {
2818 pioh
= &first_io_handler
;
2823 if (ioh
->fd
== fd
) {
2830 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
2834 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
2835 ioh
->next
= first_io_handler
;
2836 first_io_handler
= ioh
;
2839 ioh
->fd_read_poll
= fd_read_poll
;
2840 ioh
->fd_read
= fd_read
;
2841 ioh
->fd_write
= fd_write
;
2842 ioh
->opaque
= opaque
;
2845 qemu_notify_event();
2849 int qemu_set_fd_handler(int fd
,
2851 IOHandler
*fd_write
,
2854 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
2858 /***********************************************************/
2859 /* Polling handling */
2861 typedef struct PollingEntry
{
2864 struct PollingEntry
*next
;
2867 static PollingEntry
*first_polling_entry
;
2869 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
2871 PollingEntry
**ppe
, *pe
;
2872 pe
= qemu_mallocz(sizeof(PollingEntry
));
2874 pe
->opaque
= opaque
;
2875 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
2880 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
2882 PollingEntry
**ppe
, *pe
;
2883 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
2885 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
2893 /***********************************************************/
2894 /* Wait objects support */
2895 typedef struct WaitObjects
{
2897 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
2898 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
2899 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
2902 static WaitObjects wait_objects
= {0};
2904 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2906 WaitObjects
*w
= &wait_objects
;
2908 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
2910 w
->events
[w
->num
] = handle
;
2911 w
->func
[w
->num
] = func
;
2912 w
->opaque
[w
->num
] = opaque
;
2917 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2920 WaitObjects
*w
= &wait_objects
;
2923 for (i
= 0; i
< w
->num
; i
++) {
2924 if (w
->events
[i
] == handle
)
2927 w
->events
[i
] = w
->events
[i
+ 1];
2928 w
->func
[i
] = w
->func
[i
+ 1];
2929 w
->opaque
[i
] = w
->opaque
[i
+ 1];
2937 /***********************************************************/
2938 /* ram save/restore */
2940 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
2944 v
= qemu_get_byte(f
);
2947 if (qemu_get_buffer(f
, buf
, len
) != len
)
2951 v
= qemu_get_byte(f
);
2952 memset(buf
, v
, len
);
2958 if (qemu_file_has_error(f
))
2964 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
2969 if (qemu_get_be32(f
) != last_ram_offset
)
2971 for(i
= 0; i
< last_ram_offset
; i
+= TARGET_PAGE_SIZE
) {
2972 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
2974 ret
= ram_get_page(f
, qemu_get_ram_ptr(i
), TARGET_PAGE_SIZE
);
2981 #define BDRV_HASH_BLOCK_SIZE 1024
2982 #define IOBUF_SIZE 4096
2983 #define RAM_CBLOCK_MAGIC 0xfabe
2985 typedef struct RamDecompressState
{
2988 uint8_t buf
[IOBUF_SIZE
];
2989 } RamDecompressState
;
2991 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
2994 memset(s
, 0, sizeof(*s
));
2996 ret
= inflateInit(&s
->zstream
);
3002 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
3006 s
->zstream
.avail_out
= len
;
3007 s
->zstream
.next_out
= buf
;
3008 while (s
->zstream
.avail_out
> 0) {
3009 if (s
->zstream
.avail_in
== 0) {
3010 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
3012 clen
= qemu_get_be16(s
->f
);
3013 if (clen
> IOBUF_SIZE
)
3015 qemu_get_buffer(s
->f
, s
->buf
, clen
);
3016 s
->zstream
.avail_in
= clen
;
3017 s
->zstream
.next_in
= s
->buf
;
3019 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
3020 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
3027 static void ram_decompress_close(RamDecompressState
*s
)
3029 inflateEnd(&s
->zstream
);
3032 #define RAM_SAVE_FLAG_FULL 0x01
3033 #define RAM_SAVE_FLAG_COMPRESS 0x02
3034 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3035 #define RAM_SAVE_FLAG_PAGE 0x08
3036 #define RAM_SAVE_FLAG_EOS 0x10
3038 static int is_dup_page(uint8_t *page
, uint8_t ch
)
3040 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
3041 uint32_t *array
= (uint32_t *)page
;
3044 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
3045 if (array
[i
] != val
)
3052 static int ram_save_block(QEMUFile
*f
)
3054 static ram_addr_t current_addr
= 0;
3055 ram_addr_t saved_addr
= current_addr
;
3056 ram_addr_t addr
= 0;
3059 while (addr
< last_ram_offset
) {
3060 if (kvm_enabled() && current_addr
== 0) {
3062 r
= kvm_update_dirty_pages_log();
3064 fprintf(stderr
, "%s: update dirty pages log failed %d\n", __FUNCTION__
, r
);
3065 qemu_file_set_error(f
);
3069 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
3072 cpu_physical_memory_reset_dirty(current_addr
,
3073 current_addr
+ TARGET_PAGE_SIZE
,
3074 MIGRATION_DIRTY_FLAG
);
3076 p
= qemu_get_ram_ptr(current_addr
);
3078 if (is_dup_page(p
, *p
)) {
3079 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
3080 qemu_put_byte(f
, *p
);
3082 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
3083 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
3089 addr
+= TARGET_PAGE_SIZE
;
3090 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
3096 static uint64_t bytes_transferred
= 0;
3098 static ram_addr_t
ram_save_remaining(void)
3101 ram_addr_t count
= 0;
3103 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3104 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3111 uint64_t ram_bytes_remaining(void)
3113 return ram_save_remaining() * TARGET_PAGE_SIZE
;
3116 uint64_t ram_bytes_transferred(void)
3118 return bytes_transferred
;
3121 uint64_t ram_bytes_total(void)
3123 return last_ram_offset
;
3126 static int ram_save_live(QEMUFile
*f
, int stage
, void *opaque
)
3129 uint64_t bytes_transferred_last
;
3131 uint64_t expected_time
= 0;
3133 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX
) != 0) {
3134 qemu_file_set_error(f
);
3139 /* Make sure all dirty bits are set */
3140 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3141 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3142 cpu_physical_memory_set_dirty(addr
);
3145 /* Enable dirty memory tracking */
3146 cpu_physical_memory_set_dirty_tracking(1);
3148 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
3151 bytes_transferred_last
= bytes_transferred
;
3152 bwidth
= get_clock();
3154 while (!qemu_file_rate_limit(f
)) {
3157 ret
= ram_save_block(f
);
3158 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
3159 if (ret
== 0) /* no more blocks */
3163 bwidth
= get_clock() - bwidth
;
3164 bwidth
= (bytes_transferred
- bytes_transferred_last
) / bwidth
;
3166 /* if we haven't transferred anything this round, force expected_time to a
3167 * a very high value, but without crashing */
3171 /* try transferring iterative blocks of memory */
3175 /* flush all remaining blocks regardless of rate limiting */
3176 while (ram_save_block(f
) != 0) {
3177 bytes_transferred
+= TARGET_PAGE_SIZE
;
3179 cpu_physical_memory_set_dirty_tracking(0);
3182 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3184 expected_time
= ram_save_remaining() * TARGET_PAGE_SIZE
/ bwidth
;
3186 return (stage
== 2) && (expected_time
<= migrate_max_downtime());
3189 static int ram_load_dead(QEMUFile
*f
, void *opaque
)
3191 RamDecompressState s1
, *s
= &s1
;
3195 if (ram_decompress_open(s
, f
) < 0)
3197 for(i
= 0; i
< last_ram_offset
; i
+= BDRV_HASH_BLOCK_SIZE
) {
3198 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3200 if (ram_decompress_buf(s
, buf
, 1) < 0) {
3201 fprintf(stderr
, "Error while reading ram block header\n");
3205 if (ram_decompress_buf(s
, qemu_get_ram_ptr(i
),
3206 BDRV_HASH_BLOCK_SIZE
) < 0) {
3207 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
3212 printf("Error block header\n");
3216 ram_decompress_close(s
);
3221 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
3226 if (version_id
== 1)
3227 return ram_load_v1(f
, opaque
);
3229 if (version_id
== 2) {
3230 if (qemu_get_be32(f
) != last_ram_offset
)
3232 return ram_load_dead(f
, opaque
);
3235 if (version_id
!= 3)
3239 addr
= qemu_get_be64(f
);
3241 flags
= addr
& ~TARGET_PAGE_MASK
;
3242 addr
&= TARGET_PAGE_MASK
;
3244 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
3245 if (addr
!= last_ram_offset
)
3249 if (flags
& RAM_SAVE_FLAG_FULL
) {
3250 if (ram_load_dead(f
, opaque
) < 0)
3254 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
3255 uint8_t ch
= qemu_get_byte(f
);
3256 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
3259 (!kvm_enabled() || kvm_has_sync_mmu())) {
3260 madvise(qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
, MADV_DONTNEED
);
3263 } else if (flags
& RAM_SAVE_FLAG_PAGE
)
3264 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
3265 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
3270 void qemu_service_io(void)
3272 qemu_notify_event();
3275 /***********************************************************/
3276 /* bottom halves (can be seen as timers which expire ASAP) */
3287 static QEMUBH
*first_bh
= NULL
;
3289 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
3292 bh
= qemu_mallocz(sizeof(QEMUBH
));
3294 bh
->opaque
= opaque
;
3295 bh
->next
= first_bh
;
3300 int qemu_bh_poll(void)
3306 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3307 if (!bh
->deleted
&& bh
->scheduled
) {
3316 /* remove deleted bhs */
3330 void qemu_bh_schedule_idle(QEMUBH
*bh
)
3338 void qemu_bh_schedule(QEMUBH
*bh
)
3344 /* stop the currently executing CPU to execute the BH ASAP */
3345 qemu_notify_event();
3348 void qemu_bh_cancel(QEMUBH
*bh
)
3353 void qemu_bh_delete(QEMUBH
*bh
)
3359 static void qemu_bh_update_timeout(int *timeout
)
3363 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3364 if (!bh
->deleted
&& bh
->scheduled
) {
3366 /* idle bottom halves will be polled at least
3368 *timeout
= MIN(10, *timeout
);
3370 /* non-idle bottom halves will be executed
3379 /***********************************************************/
3380 /* machine registration */
3382 static QEMUMachine
*first_machine
= NULL
;
3383 QEMUMachine
*current_machine
= NULL
;
3385 int qemu_register_machine(QEMUMachine
*m
)
3388 pm
= &first_machine
;
3396 static QEMUMachine
*find_machine(const char *name
)
3400 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3401 if (!strcmp(m
->name
, name
))
3407 static QEMUMachine
*find_default_machine(void)
3411 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3412 if (m
->is_default
) {
3419 /***********************************************************/
3420 /* main execution loop */
3422 static void gui_update(void *opaque
)
3424 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3425 DisplayState
*ds
= opaque
;
3426 DisplayChangeListener
*dcl
= ds
->listeners
;
3430 while (dcl
!= NULL
) {
3431 if (dcl
->gui_timer_interval
&&
3432 dcl
->gui_timer_interval
< interval
)
3433 interval
= dcl
->gui_timer_interval
;
3436 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3439 static void nographic_update(void *opaque
)
3441 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3443 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3446 struct vm_change_state_entry
{
3447 VMChangeStateHandler
*cb
;
3449 LIST_ENTRY (vm_change_state_entry
) entries
;
3452 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3454 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3457 VMChangeStateEntry
*e
;
3459 e
= qemu_mallocz(sizeof (*e
));
3463 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3467 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3469 LIST_REMOVE (e
, entries
);
3473 static void vm_state_notify(int running
, int reason
)
3475 VMChangeStateEntry
*e
;
3477 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3478 e
->cb(e
->opaque
, running
, reason
);
3482 static void resume_all_vcpus(void);
3483 static void pause_all_vcpus(void);
3490 vm_state_notify(1, 0);
3491 qemu_rearm_alarm_timer(alarm_timer
);
3496 /* reset/shutdown handler */
3498 typedef struct QEMUResetEntry
{
3499 TAILQ_ENTRY(QEMUResetEntry
) entry
;
3500 QEMUResetHandler
*func
;
3504 static TAILQ_HEAD(reset_handlers
, QEMUResetEntry
) reset_handlers
=
3505 TAILQ_HEAD_INITIALIZER(reset_handlers
);
3506 static int reset_requested
;
3507 static int shutdown_requested
;
3508 static int powerdown_requested
;
3509 static int debug_requested
;
3510 static int vmstop_requested
;
3512 int qemu_no_shutdown(void)
3514 int r
= no_shutdown
;
3519 int qemu_shutdown_requested(void)
3521 int r
= shutdown_requested
;
3522 shutdown_requested
= 0;
3526 int qemu_reset_requested(void)
3528 int r
= reset_requested
;
3529 reset_requested
= 0;
3533 int qemu_powerdown_requested(void)
3535 int r
= powerdown_requested
;
3536 powerdown_requested
= 0;
3540 static int qemu_debug_requested(void)
3542 int r
= debug_requested
;
3543 debug_requested
= 0;
3547 static int qemu_vmstop_requested(void)
3549 int r
= vmstop_requested
;
3550 vmstop_requested
= 0;
3554 static void do_vm_stop(int reason
)
3557 cpu_disable_ticks();
3560 vm_state_notify(0, reason
);
3564 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3566 QEMUResetEntry
*re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3569 re
->opaque
= opaque
;
3570 TAILQ_INSERT_TAIL(&reset_handlers
, re
, entry
);
3573 void qemu_unregister_reset(QEMUResetHandler
*func
, void *opaque
)
3577 TAILQ_FOREACH(re
, &reset_handlers
, entry
) {
3578 if (re
->func
== func
&& re
->opaque
== opaque
) {
3579 TAILQ_REMOVE(&reset_handlers
, re
, entry
);
3586 void qemu_system_reset(void)
3588 QEMUResetEntry
*re
, *nre
;
3590 /* reset all devices */
3591 TAILQ_FOREACH_SAFE(re
, &reset_handlers
, entry
, nre
) {
3592 re
->func(re
->opaque
);
3596 void qemu_system_reset_request(void)
3599 shutdown_requested
= 1;
3601 reset_requested
= 1;
3603 if (cpu_single_env
) {
3604 cpu_single_env
->stopped
= 1;
3606 qemu_notify_event();
3609 void qemu_system_shutdown_request(void)
3611 shutdown_requested
= 1;
3612 qemu_notify_event();
3615 void qemu_system_powerdown_request(void)
3617 powerdown_requested
= 1;
3618 qemu_notify_event();
3621 #ifdef CONFIG_IOTHREAD
3622 static void qemu_system_vmstop_request(int reason
)
3624 vmstop_requested
= reason
;
3625 qemu_notify_event();
3630 static int io_thread_fd
= -1;
3632 static void qemu_event_increment(void)
3634 static const char byte
= 0;
3636 if (io_thread_fd
== -1)
3639 write(io_thread_fd
, &byte
, sizeof(byte
));
3642 static void qemu_event_read(void *opaque
)
3644 int fd
= (unsigned long)opaque
;
3647 /* Drain the notify pipe */
3650 len
= read(fd
, buffer
, sizeof(buffer
));
3651 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
3654 static int qemu_event_init(void)
3663 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3667 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3671 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3672 (void *)(unsigned long)fds
[0]);
3674 io_thread_fd
= fds
[1];
3683 HANDLE qemu_event_handle
;
3685 static void dummy_event_handler(void *opaque
)
3689 static int qemu_event_init(void)
3691 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3692 if (!qemu_event_handle
) {
3693 perror("Failed CreateEvent");
3696 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3700 static void qemu_event_increment(void)
3702 SetEvent(qemu_event_handle
);
3706 static int cpu_can_run(CPUState
*env
)
3715 #ifndef CONFIG_IOTHREAD
3716 static int qemu_init_main_loop(void)
3718 return qemu_event_init();
3721 void qemu_init_vcpu(void *_env
)
3723 CPUState
*env
= _env
;
3730 int qemu_cpu_self(void *env
)
3735 static void resume_all_vcpus(void)
3739 static void pause_all_vcpus(void)
3743 void qemu_cpu_kick(void *env
)
3748 void qemu_notify_event(void)
3750 CPUState
*env
= cpu_single_env
;
3752 if (kvm_enabled()) {
3753 qemu_kvm_notify_work();
3759 if (env
->kqemu_enabled
)
3760 kqemu_cpu_interrupt(env
);
3766 #define qemu_mutex_lock_iothread() do { } while (0)
3767 #define qemu_mutex_unlock_iothread() do { } while (0)
3770 void vm_stop(int reason
)
3775 #else /* CONFIG_IOTHREAD */
3777 #include "qemu-thread.h"
3779 QemuMutex qemu_global_mutex
;
3780 static QemuMutex qemu_fair_mutex
;
3782 static QemuThread io_thread
;
3784 static QemuThread
*tcg_cpu_thread
;
3785 static QemuCond
*tcg_halt_cond
;
3787 static int qemu_system_ready
;
3789 static QemuCond qemu_cpu_cond
;
3791 static QemuCond qemu_system_cond
;
3792 static QemuCond qemu_pause_cond
;
3794 static void block_io_signals(void);
3795 static void unblock_io_signals(void);
3796 static int tcg_has_work(void);
3798 static int qemu_init_main_loop(void)
3802 ret
= qemu_event_init();
3806 qemu_cond_init(&qemu_pause_cond
);
3807 qemu_mutex_init(&qemu_fair_mutex
);
3808 qemu_mutex_init(&qemu_global_mutex
);
3809 qemu_mutex_lock(&qemu_global_mutex
);
3811 unblock_io_signals();
3812 qemu_thread_self(&io_thread
);
3817 static void qemu_wait_io_event(CPUState
*env
)
3819 while (!tcg_has_work())
3820 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3822 qemu_mutex_unlock(&qemu_global_mutex
);
3825 * Users of qemu_global_mutex can be starved, having no chance
3826 * to acquire it since this path will get to it first.
3827 * So use another lock to provide fairness.
3829 qemu_mutex_lock(&qemu_fair_mutex
);
3830 qemu_mutex_unlock(&qemu_fair_mutex
);
3832 qemu_mutex_lock(&qemu_global_mutex
);
3836 qemu_cond_signal(&qemu_pause_cond
);
3840 static int qemu_cpu_exec(CPUState
*env
);
3842 static void *kvm_cpu_thread_fn(void *arg
)
3844 CPUState
*env
= arg
;
3847 qemu_thread_self(env
->thread
);
3849 /* signal CPU creation */
3850 qemu_mutex_lock(&qemu_global_mutex
);
3852 qemu_cond_signal(&qemu_cpu_cond
);
3854 /* and wait for machine initialization */
3855 while (!qemu_system_ready
)
3856 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3859 if (cpu_can_run(env
))
3861 qemu_wait_io_event(env
);
3867 static void tcg_cpu_exec(void);
3869 static void *tcg_cpu_thread_fn(void *arg
)
3871 CPUState
*env
= arg
;
3874 qemu_thread_self(env
->thread
);
3876 /* signal CPU creation */
3877 qemu_mutex_lock(&qemu_global_mutex
);
3878 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
3880 qemu_cond_signal(&qemu_cpu_cond
);
3882 /* and wait for machine initialization */
3883 while (!qemu_system_ready
)
3884 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3888 qemu_wait_io_event(cur_cpu
);
3894 void qemu_cpu_kick(void *_env
)
3896 CPUState
*env
= _env
;
3897 qemu_cond_broadcast(env
->halt_cond
);
3899 qemu_thread_signal(env
->thread
, SIGUSR1
);
3902 int qemu_cpu_self(void *env
)
3904 return (cpu_single_env
!= NULL
);
3907 static void cpu_signal(int sig
)
3910 cpu_exit(cpu_single_env
);
3913 static void block_io_signals(void)
3916 struct sigaction sigact
;
3919 sigaddset(&set
, SIGUSR2
);
3920 sigaddset(&set
, SIGIO
);
3921 sigaddset(&set
, SIGALRM
);
3922 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3925 sigaddset(&set
, SIGUSR1
);
3926 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3928 memset(&sigact
, 0, sizeof(sigact
));
3929 sigact
.sa_handler
= cpu_signal
;
3930 sigaction(SIGUSR1
, &sigact
, NULL
);
3933 static void unblock_io_signals(void)
3938 sigaddset(&set
, SIGUSR2
);
3939 sigaddset(&set
, SIGIO
);
3940 sigaddset(&set
, SIGALRM
);
3941 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3944 sigaddset(&set
, SIGUSR1
);
3945 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3948 static void qemu_signal_lock(unsigned int msecs
)
3950 qemu_mutex_lock(&qemu_fair_mutex
);
3952 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
3953 qemu_thread_signal(tcg_cpu_thread
, SIGUSR1
);
3954 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
3957 qemu_mutex_unlock(&qemu_fair_mutex
);
3960 static void qemu_mutex_lock_iothread(void)
3962 if (kvm_enabled()) {
3963 qemu_mutex_lock(&qemu_fair_mutex
);
3964 qemu_mutex_lock(&qemu_global_mutex
);
3965 qemu_mutex_unlock(&qemu_fair_mutex
);
3967 qemu_signal_lock(100);
3970 static void qemu_mutex_unlock_iothread(void)
3972 qemu_mutex_unlock(&qemu_global_mutex
);
3975 static int all_vcpus_paused(void)
3977 CPUState
*penv
= first_cpu
;
3982 penv
= (CPUState
*)penv
->next_cpu
;
3988 static void pause_all_vcpus(void)
3990 CPUState
*penv
= first_cpu
;
3994 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3995 qemu_cpu_kick(penv
);
3996 penv
= (CPUState
*)penv
->next_cpu
;
3999 while (!all_vcpus_paused()) {
4000 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
4003 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4004 penv
= (CPUState
*)penv
->next_cpu
;
4009 static void resume_all_vcpus(void)
4011 CPUState
*penv
= first_cpu
;
4016 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4017 qemu_cpu_kick(penv
);
4018 penv
= (CPUState
*)penv
->next_cpu
;
4022 static void tcg_init_vcpu(void *_env
)
4024 CPUState
*env
= _env
;
4025 /* share a single thread for all cpus with TCG */
4026 if (!tcg_cpu_thread
) {
4027 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
4028 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
4029 qemu_cond_init(env
->halt_cond
);
4030 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
4031 while (env
->created
== 0)
4032 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
4033 tcg_cpu_thread
= env
->thread
;
4034 tcg_halt_cond
= env
->halt_cond
;
4036 env
->thread
= tcg_cpu_thread
;
4037 env
->halt_cond
= tcg_halt_cond
;
4041 static void kvm_start_vcpu(CPUState
*env
)
4044 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
4045 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
4046 qemu_cond_init(env
->halt_cond
);
4047 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
4048 while (env
->created
== 0)
4049 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
4052 void qemu_init_vcpu(void *_env
)
4054 CPUState
*env
= _env
;
4057 kvm_start_vcpu(env
);
4062 void qemu_notify_event(void)
4064 qemu_event_increment();
4067 void vm_stop(int reason
)
4070 qemu_thread_self(&me
);
4072 if (!qemu_thread_equal(&me
, &io_thread
)) {
4073 qemu_system_vmstop_request(reason
);
4075 * FIXME: should not return to device code in case
4076 * vm_stop() has been requested.
4078 if (cpu_single_env
) {
4079 cpu_exit(cpu_single_env
);
4080 cpu_single_env
->stop
= 1;
4091 static void host_main_loop_wait(int *timeout
)
4097 /* XXX: need to suppress polling by better using win32 events */
4099 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
4100 ret
|= pe
->func(pe
->opaque
);
4104 WaitObjects
*w
= &wait_objects
;
4106 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
4107 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
4108 if (w
->func
[ret
- WAIT_OBJECT_0
])
4109 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
4111 /* Check for additional signaled events */
4112 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
4114 /* Check if event is signaled */
4115 ret2
= WaitForSingleObject(w
->events
[i
], 0);
4116 if(ret2
== WAIT_OBJECT_0
) {
4118 w
->func
[i
](w
->opaque
[i
]);
4119 } else if (ret2
== WAIT_TIMEOUT
) {
4121 err
= GetLastError();
4122 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
4125 } else if (ret
== WAIT_TIMEOUT
) {
4127 err
= GetLastError();
4128 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
4135 static void host_main_loop_wait(int *timeout
)
4140 void main_loop_wait(int timeout
)
4142 IOHandlerRecord
*ioh
;
4143 fd_set rfds
, wfds
, xfds
;
4147 qemu_bh_update_timeout(&timeout
);
4149 host_main_loop_wait(&timeout
);
4151 /* poll any events */
4152 /* XXX: separate device handlers from system ones */
4157 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4161 (!ioh
->fd_read_poll
||
4162 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
4163 FD_SET(ioh
->fd
, &rfds
);
4167 if (ioh
->fd_write
) {
4168 FD_SET(ioh
->fd
, &wfds
);
4174 tv
.tv_sec
= timeout
/ 1000;
4175 tv
.tv_usec
= (timeout
% 1000) * 1000;
4177 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
4179 qemu_mutex_unlock_iothread();
4180 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
4181 qemu_mutex_lock_iothread();
4183 IOHandlerRecord
**pioh
;
4185 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4186 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
4187 ioh
->fd_read(ioh
->opaque
);
4188 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
4189 FD_CLR(ioh
->fd
, &rfds
);
4191 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
4192 ioh
->fd_write(ioh
->opaque
);
4196 /* remove deleted IO handlers */
4197 pioh
= &first_io_handler
;
4208 slirp_select_poll(&rfds
, &wfds
, &xfds
, (ret
< 0));
4210 /* rearm timer, if not periodic */
4211 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
4212 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
4213 qemu_rearm_alarm_timer(alarm_timer
);
4216 /* vm time timers */
4218 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
4219 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
4220 qemu_get_clock(vm_clock
));
4223 /* real time timers */
4224 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
4225 qemu_get_clock(rt_clock
));
4227 /* Check bottom-halves last in case any of the earlier events triggered
4233 static int qemu_cpu_exec(CPUState
*env
)
4236 #ifdef CONFIG_PROFILER
4240 #ifdef CONFIG_PROFILER
4241 ti
= profile_getclock();
4246 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
4247 env
->icount_decr
.u16
.low
= 0;
4248 env
->icount_extra
= 0;
4249 count
= qemu_next_deadline();
4250 count
= (count
+ (1 << icount_time_shift
) - 1)
4251 >> icount_time_shift
;
4252 qemu_icount
+= count
;
4253 decr
= (count
> 0xffff) ? 0xffff : count
;
4255 env
->icount_decr
.u16
.low
= decr
;
4256 env
->icount_extra
= count
;
4258 ret
= cpu_exec(env
);
4259 #ifdef CONFIG_PROFILER
4260 qemu_time
+= profile_getclock() - ti
;
4263 /* Fold pending instructions back into the
4264 instruction counter, and clear the interrupt flag. */
4265 qemu_icount
-= (env
->icount_decr
.u16
.low
4266 + env
->icount_extra
);
4267 env
->icount_decr
.u32
= 0;
4268 env
->icount_extra
= 0;
4273 static void tcg_cpu_exec(void)
4277 if (next_cpu
== NULL
)
4278 next_cpu
= first_cpu
;
4279 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
4280 CPUState
*env
= cur_cpu
= next_cpu
;
4284 if (timer_alarm_pending
) {
4285 timer_alarm_pending
= 0;
4288 if (cpu_can_run(env
))
4289 ret
= qemu_cpu_exec(env
);
4290 if (ret
== EXCP_DEBUG
) {
4291 gdb_set_stop_cpu(env
);
4292 debug_requested
= 1;
4298 static int cpu_has_work(CPUState
*env
)
4306 if (qemu_cpu_has_work(env
))
4311 static int tcg_has_work(void)
4315 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4316 if (cpu_has_work(env
))
4321 static int qemu_calculate_timeout(void)
4323 #ifndef CONFIG_IOTHREAD
4328 else if (tcg_has_work())
4330 else if (!use_icount
)
4333 /* XXX: use timeout computed from timers */
4336 /* Advance virtual time to the next event. */
4337 if (use_icount
== 1) {
4338 /* When not using an adaptive execution frequency
4339 we tend to get badly out of sync with real time,
4340 so just delay for a reasonable amount of time. */
4343 delta
= cpu_get_icount() - cpu_get_clock();
4346 /* If virtual time is ahead of real time then just
4348 timeout
= (delta
/ 1000000) + 1;
4350 /* Wait for either IO to occur or the next
4352 add
= qemu_next_deadline();
4353 /* We advance the timer before checking for IO.
4354 Limit the amount we advance so that early IO
4355 activity won't get the guest too far ahead. */
4359 add
= (add
+ (1 << icount_time_shift
) - 1)
4360 >> icount_time_shift
;
4362 timeout
= delta
/ 1000000;
4369 #else /* CONFIG_IOTHREAD */
4374 static int vm_can_run(void)
4376 if (powerdown_requested
)
4378 if (reset_requested
)
4380 if (shutdown_requested
)
4382 if (debug_requested
)
4387 static void main_loop(void)
4391 if (kvm_enabled()) {
4393 cpu_disable_ticks();
4397 #ifdef CONFIG_IOTHREAD
4398 qemu_system_ready
= 1;
4399 qemu_cond_broadcast(&qemu_system_cond
);
4404 #ifdef CONFIG_PROFILER
4407 #ifndef CONFIG_IOTHREAD
4410 #ifdef CONFIG_PROFILER
4411 ti
= profile_getclock();
4413 main_loop_wait(qemu_calculate_timeout());
4414 #ifdef CONFIG_PROFILER
4415 dev_time
+= profile_getclock() - ti
;
4417 } while (vm_can_run());
4419 if (qemu_debug_requested())
4420 vm_stop(EXCP_DEBUG
);
4421 if (qemu_shutdown_requested()) {
4428 if (qemu_reset_requested()) {
4430 qemu_system_reset();
4433 if (qemu_powerdown_requested())
4434 qemu_system_powerdown();
4435 if ((r
= qemu_vmstop_requested()))
4441 static void version(void)
4443 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4446 static void help(int exitcode
)
4449 printf("usage: %s [options] [disk_image]\n"
4451 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4453 #define DEF(option, opt_arg, opt_enum, opt_help) \
4455 #define DEFHEADING(text) stringify(text) "\n"
4456 #include "qemu-options.h"
4461 "During emulation, the following keys are useful:\n"
4462 "ctrl-alt-f toggle full screen\n"
4463 "ctrl-alt-n switch to virtual console 'n'\n"
4464 "ctrl-alt toggle mouse and keyboard grab\n"
4466 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4471 DEFAULT_NETWORK_SCRIPT
,
4472 DEFAULT_NETWORK_DOWN_SCRIPT
,
4474 DEFAULT_GDBSTUB_PORT
,
4479 #define HAS_ARG 0x0001
4482 #define DEF(option, opt_arg, opt_enum, opt_help) \
4484 #define DEFHEADING(text)
4485 #include "qemu-options.h"
4491 typedef struct QEMUOption
{
4497 static const QEMUOption qemu_options
[] = {
4498 { "h", 0, QEMU_OPTION_h
},
4499 #define DEF(option, opt_arg, opt_enum, opt_help) \
4500 { option, opt_arg, opt_enum },
4501 #define DEFHEADING(text)
4502 #include "qemu-options.h"
4510 struct soundhw soundhw
[] = {
4511 #ifdef HAS_AUDIO_CHOICE
4512 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4518 { .init_isa
= pcspk_audio_init
}
4525 "Creative Sound Blaster 16",
4528 { .init_isa
= SB16_init
}
4532 #ifdef CONFIG_CS4231A
4538 { .init_isa
= cs4231a_init
}
4546 "Yamaha YMF262 (OPL3)",
4548 "Yamaha YM3812 (OPL2)",
4552 { .init_isa
= Adlib_init
}
4559 "Gravis Ultrasound GF1",
4562 { .init_isa
= GUS_init
}
4569 "Intel 82801AA AC97 Audio",
4572 { .init_pci
= ac97_init
}
4576 #ifdef CONFIG_ES1370
4579 "ENSONIQ AudioPCI ES1370",
4582 { .init_pci
= es1370_init
}
4586 #endif /* HAS_AUDIO_CHOICE */
4588 { NULL
, NULL
, 0, 0, { NULL
} }
4591 static void select_soundhw (const char *optarg
)
4595 if (*optarg
== '?') {
4598 printf ("Valid sound card names (comma separated):\n");
4599 for (c
= soundhw
; c
->name
; ++c
) {
4600 printf ("%-11s %s\n", c
->name
, c
->descr
);
4602 printf ("\n-soundhw all will enable all of the above\n");
4603 exit (*optarg
!= '?');
4611 if (!strcmp (optarg
, "all")) {
4612 for (c
= soundhw
; c
->name
; ++c
) {
4620 e
= strchr (p
, ',');
4621 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4623 for (c
= soundhw
; c
->name
; ++c
) {
4624 if (!strncmp (c
->name
, p
, l
)) {
4633 "Unknown sound card name (too big to show)\n");
4636 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4641 p
+= l
+ (e
!= NULL
);
4645 goto show_valid_cards
;
4650 static void select_vgahw (const char *p
)
4654 cirrus_vga_enabled
= 0;
4655 std_vga_enabled
= 0;
4658 if (strstart(p
, "std", &opts
)) {
4659 std_vga_enabled
= 1;
4660 } else if (strstart(p
, "cirrus", &opts
)) {
4661 cirrus_vga_enabled
= 1;
4662 } else if (strstart(p
, "vmware", &opts
)) {
4664 } else if (strstart(p
, "xenfb", &opts
)) {
4666 } else if (!strstart(p
, "none", &opts
)) {
4668 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4672 const char *nextopt
;
4674 if (strstart(opts
, ",retrace=", &nextopt
)) {
4676 if (strstart(opts
, "dumb", &nextopt
))
4677 vga_retrace_method
= VGA_RETRACE_DUMB
;
4678 else if (strstart(opts
, "precise", &nextopt
))
4679 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4680 else goto invalid_vga
;
4681 } else goto invalid_vga
;
4687 static int balloon_parse(const char *arg
)
4692 if (!strcmp(arg
, "none")) {
4694 } else if (!strncmp(arg
, "virtio", 6)) {
4696 if (arg
[6] == ',') {
4698 if (get_param_value(buf
, sizeof(buf
), "addr", p
)) {
4699 virtio_balloon_devaddr
= strdup(buf
);
4710 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4712 exit(STATUS_CONTROL_C_EXIT
);
4717 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4721 if(strlen(str
) != 36)
4724 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4725 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4726 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4732 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4738 #define MAX_NET_CLIENTS 32
4742 static void termsig_handler(int signal
)
4744 qemu_system_shutdown_request();
4747 static void sigchld_handler(int signal
)
4749 waitpid(-1, NULL
, WNOHANG
);
4752 static void sighandler_setup(void)
4754 struct sigaction act
;
4756 memset(&act
, 0, sizeof(act
));
4757 act
.sa_handler
= termsig_handler
;
4758 sigaction(SIGINT
, &act
, NULL
);
4759 sigaction(SIGHUP
, &act
, NULL
);
4760 sigaction(SIGTERM
, &act
, NULL
);
4762 act
.sa_handler
= sigchld_handler
;
4763 act
.sa_flags
= SA_NOCLDSTOP
;
4764 sigaction(SIGCHLD
, &act
, NULL
);
4770 /* Look for support files in the same directory as the executable. */
4771 static char *find_datadir(const char *argv0
)
4777 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
4784 while (p
!= buf
&& *p
!= '\\')
4787 if (access(buf
, R_OK
) == 0) {
4788 return qemu_strdup(buf
);
4794 /* Find a likely location for support files using the location of the binary.
4795 For installed binaries this will be "$bindir/../share/qemu". When
4796 running from the build tree this will be "$bindir/../pc-bios". */
4797 #define SHARE_SUFFIX "/share/qemu"
4798 #define BUILD_SUFFIX "/pc-bios"
4799 static char *find_datadir(const char *argv0
)
4809 #if defined(__linux__)
4812 len
= readlink("/proc/self/exe", buf
, sizeof(buf
) - 1);
4818 #elif defined(__FreeBSD__)
4821 len
= readlink("/proc/curproc/file", buf
, sizeof(buf
) - 1);
4828 /* If we don't have any way of figuring out the actual executable
4829 location then try argv[0]. */
4834 p
= realpath(argv0
, p
);
4842 max_len
= strlen(dir
) +
4843 MAX(strlen(SHARE_SUFFIX
), strlen(BUILD_SUFFIX
)) + 1;
4844 res
= qemu_mallocz(max_len
);
4845 snprintf(res
, max_len
, "%s%s", dir
, SHARE_SUFFIX
);
4846 if (access(res
, R_OK
)) {
4847 snprintf(res
, max_len
, "%s%s", dir
, BUILD_SUFFIX
);
4848 if (access(res
, R_OK
)) {
4862 char *qemu_find_file(int type
, const char *name
)
4868 /* If name contains path separators then try it as a straight path. */
4869 if ((strchr(name
, '/') || strchr(name
, '\\'))
4870 && access(name
, R_OK
) == 0) {
4871 return strdup(name
);
4874 case QEMU_FILE_TYPE_BIOS
:
4877 case QEMU_FILE_TYPE_KEYMAP
:
4878 subdir
= "keymaps/";
4883 len
= strlen(data_dir
) + strlen(name
) + strlen(subdir
) + 2;
4884 buf
= qemu_mallocz(len
);
4885 snprintf(buf
, len
, "%s/%s%s", data_dir
, subdir
, name
);
4886 if (access(buf
, R_OK
)) {
4893 int main(int argc
, char **argv
, char **envp
)
4895 const char *gdbstub_dev
= NULL
;
4896 uint32_t boot_devices_bitmap
= 0;
4898 int snapshot
, linux_boot
, net_boot
;
4899 const char *initrd_filename
;
4900 const char *kernel_filename
, *kernel_cmdline
;
4901 char boot_devices
[33] = "cad"; /* default to HD->floppy->CD-ROM */
4903 DisplayChangeListener
*dcl
;
4904 int cyls
, heads
, secs
, translation
;
4905 const char *net_clients
[MAX_NET_CLIENTS
];
4907 const char *bt_opts
[MAX_BT_CMDLINE
];
4911 const char *r
, *optarg
;
4912 CharDriverState
*monitor_hd
= NULL
;
4913 const char *monitor_device
;
4914 const char *serial_devices
[MAX_SERIAL_PORTS
];
4915 int serial_device_index
;
4916 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
4917 int parallel_device_index
;
4918 const char *virtio_consoles
[MAX_VIRTIO_CONSOLES
];
4919 int virtio_console_index
;
4920 const char *loadvm
= NULL
;
4921 QEMUMachine
*machine
;
4922 const char *cpu_model
;
4923 const char *usb_devices
[MAX_USB_CMDLINE
];
4924 int usb_devices_index
;
4929 const char *pid_file
= NULL
;
4930 const char *incoming
= NULL
;
4933 struct passwd
*pwd
= NULL
;
4934 const char *chroot_dir
= NULL
;
4935 const char *run_as
= NULL
;
4938 int show_vnc_port
= 0;
4940 qemu_cache_utils_init(envp
);
4942 LIST_INIT (&vm_change_state_head
);
4945 struct sigaction act
;
4946 sigfillset(&act
.sa_mask
);
4948 act
.sa_handler
= SIG_IGN
;
4949 sigaction(SIGPIPE
, &act
, NULL
);
4952 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4953 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4954 QEMU to run on a single CPU */
4959 h
= GetCurrentProcess();
4960 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4961 for(i
= 0; i
< 32; i
++) {
4962 if (mask
& (1 << i
))
4967 SetProcessAffinityMask(h
, mask
);
4973 module_call_init(MODULE_INIT_MACHINE
);
4974 machine
= find_default_machine();
4976 initrd_filename
= NULL
;
4979 kernel_filename
= NULL
;
4980 kernel_cmdline
= "";
4981 cyls
= heads
= secs
= 0;
4982 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4983 monitor_device
= "vc:80Cx24C";
4985 serial_devices
[0] = "vc:80Cx24C";
4986 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
4987 serial_devices
[i
] = NULL
;
4988 serial_device_index
= 0;
4990 parallel_devices
[0] = "vc:80Cx24C";
4991 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
4992 parallel_devices
[i
] = NULL
;
4993 parallel_device_index
= 0;
4995 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++)
4996 virtio_consoles
[i
] = NULL
;
4997 virtio_console_index
= 0;
4999 for (i
= 0; i
< MAX_NODES
; i
++) {
5001 node_cpumask
[i
] = 0;
5004 usb_devices_index
= 0;
5005 assigned_devices_index
= 0;
5019 register_watchdogs();
5027 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
5029 const QEMUOption
*popt
;
5032 /* Treat --foo the same as -foo. */
5035 popt
= qemu_options
;
5038 fprintf(stderr
, "%s: invalid option -- '%s'\n",
5042 if (!strcmp(popt
->name
, r
+ 1))
5046 if (popt
->flags
& HAS_ARG
) {
5047 if (optind
>= argc
) {
5048 fprintf(stderr
, "%s: option '%s' requires an argument\n",
5052 optarg
= argv
[optind
++];
5057 switch(popt
->index
) {
5059 machine
= find_machine(optarg
);
5062 printf("Supported machines are:\n");
5063 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5064 printf("%-10s %s%s\n",
5066 m
->is_default
? " (default)" : "");
5068 exit(*optarg
!= '?');
5071 case QEMU_OPTION_cpu
:
5072 /* hw initialization will check this */
5073 if (*optarg
== '?') {
5074 /* XXX: implement xxx_cpu_list for targets that still miss it */
5075 #if defined(cpu_list)
5076 cpu_list(stdout
, &fprintf
);
5083 case QEMU_OPTION_initrd
:
5084 initrd_filename
= optarg
;
5086 case QEMU_OPTION_hda
:
5088 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
5090 hda_index
= drive_add(optarg
, HD_ALIAS
5091 ",cyls=%d,heads=%d,secs=%d%s",
5092 0, cyls
, heads
, secs
,
5093 translation
== BIOS_ATA_TRANSLATION_LBA
?
5095 translation
== BIOS_ATA_TRANSLATION_NONE
?
5096 ",trans=none" : "");
5098 case QEMU_OPTION_hdb
:
5099 case QEMU_OPTION_hdc
:
5100 case QEMU_OPTION_hdd
:
5101 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
5103 case QEMU_OPTION_drive
:
5104 drive_add(NULL
, "%s", optarg
);
5106 case QEMU_OPTION_mtdblock
:
5107 drive_add(optarg
, MTD_ALIAS
);
5109 case QEMU_OPTION_sd
:
5110 drive_add(optarg
, SD_ALIAS
);
5112 case QEMU_OPTION_pflash
:
5113 drive_add(optarg
, PFLASH_ALIAS
);
5115 case QEMU_OPTION_snapshot
:
5118 case QEMU_OPTION_hdachs
:
5122 cyls
= strtol(p
, (char **)&p
, 0);
5123 if (cyls
< 1 || cyls
> 16383)
5128 heads
= strtol(p
, (char **)&p
, 0);
5129 if (heads
< 1 || heads
> 16)
5134 secs
= strtol(p
, (char **)&p
, 0);
5135 if (secs
< 1 || secs
> 63)
5139 if (!strcmp(p
, "none"))
5140 translation
= BIOS_ATA_TRANSLATION_NONE
;
5141 else if (!strcmp(p
, "lba"))
5142 translation
= BIOS_ATA_TRANSLATION_LBA
;
5143 else if (!strcmp(p
, "auto"))
5144 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5147 } else if (*p
!= '\0') {
5149 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5152 if (hda_index
!= -1)
5153 snprintf(drives_opt
[hda_index
].opt
,
5154 sizeof(drives_opt
[hda_index
].opt
),
5155 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
5156 0, cyls
, heads
, secs
,
5157 translation
== BIOS_ATA_TRANSLATION_LBA
?
5159 translation
== BIOS_ATA_TRANSLATION_NONE
?
5160 ",trans=none" : "");
5163 case QEMU_OPTION_numa
:
5164 if (nb_numa_nodes
>= MAX_NODES
) {
5165 fprintf(stderr
, "qemu: too many NUMA nodes\n");
5170 case QEMU_OPTION_nographic
:
5171 display_type
= DT_NOGRAPHIC
;
5173 #ifdef CONFIG_CURSES
5174 case QEMU_OPTION_curses
:
5175 display_type
= DT_CURSES
;
5178 case QEMU_OPTION_portrait
:
5181 case QEMU_OPTION_kernel
:
5182 kernel_filename
= optarg
;
5184 case QEMU_OPTION_append
:
5185 kernel_cmdline
= optarg
;
5187 case QEMU_OPTION_cdrom
:
5188 drive_add(optarg
, CDROM_ALIAS
);
5190 case QEMU_OPTION_boot
:
5192 static const char * const params
[] = {
5193 "order", "once", "menu", NULL
5195 char buf
[sizeof(boot_devices
)];
5196 char *standard_boot_devices
;
5199 if (!strchr(optarg
, '=')) {
5201 pstrcpy(buf
, sizeof(buf
), optarg
);
5202 } else if (check_params(buf
, sizeof(buf
), params
, optarg
) < 0) {
5204 "qemu: unknown boot parameter '%s' in '%s'\n",
5210 get_param_value(buf
, sizeof(buf
), "order", optarg
)) {
5211 boot_devices_bitmap
= parse_bootdevices(buf
);
5212 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5215 if (get_param_value(buf
, sizeof(buf
),
5217 boot_devices_bitmap
|= parse_bootdevices(buf
);
5218 standard_boot_devices
= qemu_strdup(boot_devices
);
5219 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5220 qemu_register_reset(restore_boot_devices
,
5221 standard_boot_devices
);
5223 if (get_param_value(buf
, sizeof(buf
),
5225 if (!strcmp(buf
, "on")) {
5227 } else if (!strcmp(buf
, "off")) {
5231 "qemu: invalid option value '%s'\n",
5239 case QEMU_OPTION_fda
:
5240 case QEMU_OPTION_fdb
:
5241 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
5244 case QEMU_OPTION_no_fd_bootchk
:
5248 case QEMU_OPTION_net
:
5249 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
5250 fprintf(stderr
, "qemu: too many network clients\n");
5253 net_clients
[nb_net_clients
] = optarg
;
5257 case QEMU_OPTION_tftp
:
5258 legacy_tftp_prefix
= optarg
;
5260 case QEMU_OPTION_bootp
:
5261 legacy_bootp_filename
= optarg
;
5264 case QEMU_OPTION_smb
:
5265 net_slirp_smb(optarg
);
5268 case QEMU_OPTION_redir
:
5269 net_slirp_redir(optarg
);
5272 case QEMU_OPTION_bt
:
5273 if (nb_bt_opts
>= MAX_BT_CMDLINE
) {
5274 fprintf(stderr
, "qemu: too many bluetooth options\n");
5277 bt_opts
[nb_bt_opts
++] = optarg
;
5280 case QEMU_OPTION_audio_help
:
5284 case QEMU_OPTION_soundhw
:
5285 select_soundhw (optarg
);
5291 case QEMU_OPTION_version
:
5295 case QEMU_OPTION_m
: {
5299 value
= strtoul(optarg
, &ptr
, 10);
5301 case 0: case 'M': case 'm':
5308 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5312 /* On 32-bit hosts, QEMU is limited by virtual address space */
5313 if (value
> (2047 << 20)
5314 #ifndef CONFIG_KQEMU
5315 && HOST_LONG_BITS
== 32
5318 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5321 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5322 fprintf(stderr
, "qemu: ram size too large\n");
5331 const CPULogItem
*item
;
5333 mask
= cpu_str_to_log_mask(optarg
);
5335 printf("Log items (comma separated):\n");
5336 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5337 printf("%-10s %s\n", item
->name
, item
->help
);
5345 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5347 case QEMU_OPTION_gdb
:
5348 gdbstub_dev
= optarg
;
5353 case QEMU_OPTION_bios
:
5356 case QEMU_OPTION_singlestep
:
5364 keyboard_layout
= optarg
;
5367 case QEMU_OPTION_localtime
:
5370 case QEMU_OPTION_vga
:
5371 select_vgahw (optarg
);
5373 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5379 w
= strtol(p
, (char **)&p
, 10);
5382 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5388 h
= strtol(p
, (char **)&p
, 10);
5393 depth
= strtol(p
, (char **)&p
, 10);
5394 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5395 depth
!= 24 && depth
!= 32)
5397 } else if (*p
== '\0') {
5398 depth
= graphic_depth
;
5405 graphic_depth
= depth
;
5409 case QEMU_OPTION_echr
:
5412 term_escape_char
= strtol(optarg
, &r
, 0);
5414 printf("Bad argument to echr\n");
5417 case QEMU_OPTION_monitor
:
5418 monitor_device
= optarg
;
5420 case QEMU_OPTION_serial
:
5421 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
5422 fprintf(stderr
, "qemu: too many serial ports\n");
5425 serial_devices
[serial_device_index
] = optarg
;
5426 serial_device_index
++;
5428 case QEMU_OPTION_watchdog
:
5429 i
= select_watchdog(optarg
);
5431 exit (i
== 1 ? 1 : 0);
5433 case QEMU_OPTION_watchdog_action
:
5434 if (select_watchdog_action(optarg
) == -1) {
5435 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5439 case QEMU_OPTION_virtiocon
:
5440 if (virtio_console_index
>= MAX_VIRTIO_CONSOLES
) {
5441 fprintf(stderr
, "qemu: too many virtio consoles\n");
5444 virtio_consoles
[virtio_console_index
] = optarg
;
5445 virtio_console_index
++;
5447 case QEMU_OPTION_parallel
:
5448 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
5449 fprintf(stderr
, "qemu: too many parallel ports\n");
5452 parallel_devices
[parallel_device_index
] = optarg
;
5453 parallel_device_index
++;
5455 case QEMU_OPTION_loadvm
:
5458 case QEMU_OPTION_full_screen
:
5462 case QEMU_OPTION_no_frame
:
5465 case QEMU_OPTION_alt_grab
:
5468 case QEMU_OPTION_no_quit
:
5471 case QEMU_OPTION_sdl
:
5472 display_type
= DT_SDL
;
5475 case QEMU_OPTION_pidfile
:
5479 case QEMU_OPTION_win2k_hack
:
5480 win2k_install_hack
= 1;
5482 case QEMU_OPTION_rtc_td_hack
:
5485 case QEMU_OPTION_acpitable
:
5486 if(acpi_table_add(optarg
) < 0) {
5487 fprintf(stderr
, "Wrong acpi table provided\n");
5491 case QEMU_OPTION_smbios
:
5492 if(smbios_entry_add(optarg
) < 0) {
5493 fprintf(stderr
, "Wrong smbios provided\n");
5499 case QEMU_OPTION_enable_kqemu
:
5502 case QEMU_OPTION_kernel_kqemu
:
5508 case QEMU_OPTION_enable_kvm
:
5515 case QEMU_OPTION_no_kvm
:
5518 case QEMU_OPTION_no_kvm_irqchip
: {
5523 case QEMU_OPTION_no_kvm_pit
: {
5527 case QEMU_OPTION_no_kvm_pit_reinjection
: {
5528 kvm_pit_reinject
= 0;
5531 case QEMU_OPTION_enable_nesting
: {
5535 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5536 case QEMU_OPTION_pcidevice
:
5537 if (assigned_devices_index
>= MAX_DEV_ASSIGN_CMDLINE
) {
5538 fprintf(stderr
, "Too many assigned devices\n");
5541 assigned_devices
[assigned_devices_index
] = optarg
;
5542 assigned_devices_index
++;
5546 case QEMU_OPTION_usb
:
5549 case QEMU_OPTION_usbdevice
:
5551 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
5552 fprintf(stderr
, "Too many USB devices\n");
5555 usb_devices
[usb_devices_index
] = optarg
;
5556 usb_devices_index
++;
5558 case QEMU_OPTION_smp
:
5559 smp_cpus
= atoi(optarg
);
5561 fprintf(stderr
, "Invalid number of CPUs\n");
5565 case QEMU_OPTION_vnc
:
5566 display_type
= DT_VNC
;
5567 vnc_display
= optarg
;
5570 case QEMU_OPTION_no_acpi
:
5573 case QEMU_OPTION_no_hpet
:
5576 case QEMU_OPTION_balloon
:
5577 if (balloon_parse(optarg
) < 0) {
5578 fprintf(stderr
, "Unknown -balloon argument %s\n", optarg
);
5583 case QEMU_OPTION_no_reboot
:
5586 case QEMU_OPTION_no_shutdown
:
5589 case QEMU_OPTION_show_cursor
:
5592 case QEMU_OPTION_uuid
:
5593 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5594 fprintf(stderr
, "Fail to parse UUID string."
5595 " Wrong format.\n");
5600 case QEMU_OPTION_daemonize
:
5604 case QEMU_OPTION_option_rom
:
5605 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5606 fprintf(stderr
, "Too many option ROMs\n");
5609 option_rom
[nb_option_roms
] = optarg
;
5612 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5613 case QEMU_OPTION_semihosting
:
5614 semihosting_enabled
= 1;
5617 case QEMU_OPTION_tdf
:
5620 case QEMU_OPTION_kvm_shadow_memory
:
5621 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
5623 case QEMU_OPTION_mempath
:
5627 case QEMU_OPTION_mem_prealloc
:
5628 mem_prealloc
= !mem_prealloc
;
5631 case QEMU_OPTION_name
:
5632 qemu_name
= qemu_strdup(optarg
);
5634 char *p
= strchr(qemu_name
, ',');
5637 if (strncmp(p
, "process=", 8)) {
5638 fprintf(stderr
, "Unknown subargument %s to -name", p
);
5646 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5647 case QEMU_OPTION_prom_env
:
5648 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5649 fprintf(stderr
, "Too many prom variables\n");
5652 prom_envs
[nb_prom_envs
] = optarg
;
5657 case QEMU_OPTION_old_param
:
5661 case QEMU_OPTION_clock
:
5662 configure_alarms(optarg
);
5664 case QEMU_OPTION_startdate
:
5667 time_t rtc_start_date
;
5668 if (!strcmp(optarg
, "now")) {
5669 rtc_date_offset
= -1;
5671 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
5679 } else if (sscanf(optarg
, "%d-%d-%d",
5682 &tm
.tm_mday
) == 3) {
5691 rtc_start_date
= mktimegm(&tm
);
5692 if (rtc_start_date
== -1) {
5694 fprintf(stderr
, "Invalid date format. Valid format are:\n"
5695 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5698 rtc_date_offset
= time(NULL
) - rtc_start_date
;
5702 case QEMU_OPTION_tb_size
:
5703 tb_size
= strtol(optarg
, NULL
, 0);
5707 case QEMU_OPTION_icount
:
5709 if (strcmp(optarg
, "auto") == 0) {
5710 icount_time_shift
= -1;
5712 icount_time_shift
= strtol(optarg
, NULL
, 0);
5715 case QEMU_OPTION_incoming
:
5719 case QEMU_OPTION_chroot
:
5720 chroot_dir
= optarg
;
5722 case QEMU_OPTION_runas
:
5725 case QEMU_OPTION_nvram
:
5730 case QEMU_OPTION_xen_domid
:
5731 xen_domid
= atoi(optarg
);
5733 case QEMU_OPTION_xen_create
:
5734 xen_mode
= XEN_CREATE
;
5736 case QEMU_OPTION_xen_attach
:
5737 xen_mode
= XEN_ATTACH
;
5744 /* If no data_dir is specified then try to find it relative to the
5747 data_dir
= find_datadir(argv
[0]);
5749 /* If all else fails use the install patch specified when building. */
5751 data_dir
= CONFIG_QEMU_SHAREDIR
;
5754 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5755 if (kvm_allowed
&& kqemu_allowed
) {
5757 "You can not enable both KVM and kqemu at the same time\n");
5762 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5763 if (smp_cpus
> machine
->max_cpus
) {
5764 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5765 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5770 if (display_type
== DT_NOGRAPHIC
) {
5771 if (serial_device_index
== 0)
5772 serial_devices
[0] = "stdio";
5773 if (parallel_device_index
== 0)
5774 parallel_devices
[0] = "null";
5775 if (strncmp(monitor_device
, "vc", 2) == 0)
5776 monitor_device
= "stdio";
5783 if (pipe(fds
) == -1)
5794 len
= read(fds
[0], &status
, 1);
5795 if (len
== -1 && (errno
== EINTR
))
5800 else if (status
== 1) {
5801 fprintf(stderr
, "Could not acquire pidfile\n");
5818 signal(SIGTSTP
, SIG_IGN
);
5819 signal(SIGTTOU
, SIG_IGN
);
5820 signal(SIGTTIN
, SIG_IGN
);
5823 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5826 write(fds
[1], &status
, 1);
5828 fprintf(stderr
, "Could not acquire pid file\n");
5837 if (qemu_init_main_loop()) {
5838 fprintf(stderr
, "qemu_init_main_loop failed\n");
5841 linux_boot
= (kernel_filename
!= NULL
);
5843 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5844 fprintf(stderr
, "-append only allowed with -kernel option\n");
5848 if (!linux_boot
&& initrd_filename
!= NULL
) {
5849 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5853 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5856 if (init_timer_alarm() < 0) {
5857 fprintf(stderr
, "could not initialize alarm timer\n");
5860 if (use_icount
&& icount_time_shift
< 0) {
5862 /* 125MIPS seems a reasonable initial guess at the guest speed.
5863 It will be corrected fairly quickly anyway. */
5864 icount_time_shift
= 3;
5865 init_icount_adjust();
5872 /* init network clients */
5873 if (nb_net_clients
== 0) {
5874 /* if no clients, we use a default config */
5875 net_clients
[nb_net_clients
++] = "nic";
5877 net_clients
[nb_net_clients
++] = "user";
5881 for(i
= 0;i
< nb_net_clients
; i
++) {
5882 if (net_client_parse(net_clients
[i
]) < 0)
5886 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5887 net_set_boot_mask(net_boot
);
5891 /* init the bluetooth world */
5892 for (i
= 0; i
< nb_bt_opts
; i
++)
5893 if (bt_parse(bt_opts
[i
]))
5896 /* init the memory */
5898 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5901 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5902 guest ram allocation. It needs to go away. */
5903 if (kqemu_allowed
) {
5904 kqemu_phys_ram_size
= ram_size
+ 8 * 1024 * 1024 + 4 * 1024 * 1024;
5905 kqemu_phys_ram_base
= qemu_vmalloc(kqemu_phys_ram_size
);
5906 if (!kqemu_phys_ram_base
) {
5907 fprintf(stderr
, "Could not allocate physical memory\n");
5913 /* init the dynamic translator */
5914 cpu_exec_init_all(tb_size
* 1024 * 1024);
5918 /* we always create the cdrom drive, even if no disk is there */
5920 if (nb_drives_opt
< MAX_DRIVES
)
5921 drive_add(NULL
, CDROM_ALIAS
);
5923 /* we always create at least one floppy */
5925 if (nb_drives_opt
< MAX_DRIVES
)
5926 drive_add(NULL
, FD_ALIAS
, 0);
5928 /* we always create one sd slot, even if no card is in it */
5930 if (nb_drives_opt
< MAX_DRIVES
)
5931 drive_add(NULL
, SD_ALIAS
);
5933 /* open the virtual block devices */
5935 for(i
= 0; i
< nb_drives_opt
; i
++)
5936 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
5939 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
5940 register_savevm_live("ram", 0, 3, ram_save_live
, NULL
, ram_load
, NULL
);
5943 /* must be after terminal init, SDL library changes signal handlers */
5947 /* Maintain compatibility with multiple stdio monitors */
5948 if (!strcmp(monitor_device
,"stdio")) {
5949 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5950 const char *devname
= serial_devices
[i
];
5951 if (devname
&& !strcmp(devname
,"mon:stdio")) {
5952 monitor_device
= NULL
;
5954 } else if (devname
&& !strcmp(devname
,"stdio")) {
5955 monitor_device
= NULL
;
5956 serial_devices
[i
] = "mon:stdio";
5962 if (nb_numa_nodes
> 0) {
5965 if (nb_numa_nodes
> smp_cpus
) {
5966 nb_numa_nodes
= smp_cpus
;
5969 /* If no memory size if given for any node, assume the default case
5970 * and distribute the available memory equally across all nodes
5972 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5973 if (node_mem
[i
] != 0)
5976 if (i
== nb_numa_nodes
) {
5977 uint64_t usedmem
= 0;
5979 /* On Linux, the each node's border has to be 8MB aligned,
5980 * the final node gets the rest.
5982 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
5983 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
5984 usedmem
+= node_mem
[i
];
5986 node_mem
[i
] = ram_size
- usedmem
;
5989 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5990 if (node_cpumask
[i
] != 0)
5993 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5994 * must cope with this anyway, because there are BIOSes out there in
5995 * real machines which also use this scheme.
5997 if (i
== nb_numa_nodes
) {
5998 for (i
= 0; i
< smp_cpus
; i
++) {
5999 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
6004 if (kvm_enabled()) {
6007 ret
= kvm_init(smp_cpus
);
6009 #if defined(KVM_UPSTREAM) || defined(NO_CPU_EMULATION)
6010 fprintf(stderr
, "failed to initialize KVM\n");
6013 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
6018 if (monitor_device
) {
6019 monitor_hd
= qemu_chr_open("monitor", monitor_device
, NULL
);
6021 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
6026 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6027 const char *devname
= serial_devices
[i
];
6028 if (devname
&& strcmp(devname
, "none")) {
6030 snprintf(label
, sizeof(label
), "serial%d", i
);
6031 serial_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6032 if (!serial_hds
[i
]) {
6033 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
6040 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
6041 const char *devname
= parallel_devices
[i
];
6042 if (devname
&& strcmp(devname
, "none")) {
6044 snprintf(label
, sizeof(label
), "parallel%d", i
);
6045 parallel_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6046 if (!parallel_hds
[i
]) {
6047 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
6054 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
6055 const char *devname
= virtio_consoles
[i
];
6056 if (devname
&& strcmp(devname
, "none")) {
6058 snprintf(label
, sizeof(label
), "virtcon%d", i
);
6059 virtcon_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6060 if (!virtcon_hds
[i
]) {
6061 fprintf(stderr
, "qemu: could not open virtio console '%s'\n",
6068 module_call_init(MODULE_INIT_DEVICE
);
6070 machine
->init(ram_size
, boot_devices
,
6071 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
6074 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
6075 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6076 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
6082 current_machine
= machine
;
6084 /* init USB devices */
6086 for(i
= 0; i
< usb_devices_index
; i
++) {
6087 if (usb_device_add(usb_devices
[i
], 0) < 0) {
6088 fprintf(stderr
, "Warning: could not add USB device %s\n",
6095 dumb_display_init();
6096 /* just use the first displaystate for the moment */
6099 if (display_type
== DT_DEFAULT
) {
6100 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6101 display_type
= DT_SDL
;
6103 display_type
= DT_VNC
;
6104 vnc_display
= "localhost:0,to=99";
6110 switch (display_type
) {
6113 #if defined(CONFIG_CURSES)
6115 curses_display_init(ds
, full_screen
);
6118 #if defined(CONFIG_SDL)
6120 sdl_display_init(ds
, full_screen
, no_frame
);
6122 #elif defined(CONFIG_COCOA)
6124 cocoa_display_init(ds
, full_screen
);
6128 vnc_display_init(ds
);
6129 if (vnc_display_open(ds
, vnc_display
) < 0)
6132 if (show_vnc_port
) {
6133 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
6141 dcl
= ds
->listeners
;
6142 while (dcl
!= NULL
) {
6143 if (dcl
->dpy_refresh
!= NULL
) {
6144 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
6145 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
6150 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
6151 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
6152 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
6155 text_consoles_set_display(display_state
);
6156 qemu_chr_initial_reset();
6158 if (monitor_device
&& monitor_hd
)
6159 monitor_init(monitor_hd
, MONITOR_USE_READLINE
| MONITOR_IS_DEFAULT
);
6161 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6162 const char *devname
= serial_devices
[i
];
6163 if (devname
&& strcmp(devname
, "none")) {
6164 if (strstart(devname
, "vc", 0))
6165 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
6169 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
6170 const char *devname
= parallel_devices
[i
];
6171 if (devname
&& strcmp(devname
, "none")) {
6172 if (strstart(devname
, "vc", 0))
6173 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
6177 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
6178 const char *devname
= virtio_consoles
[i
];
6179 if (virtcon_hds
[i
] && devname
) {
6180 if (strstart(devname
, "vc", 0))
6181 qemu_chr_printf(virtcon_hds
[i
], "virtio console%d\r\n", i
);
6185 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
6186 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
6192 do_loadvm(cur_mon
, loadvm
);
6195 autostart
= 0; /* fixme how to deal with -daemonize */
6196 qemu_start_incoming_migration(incoming
);
6208 len
= write(fds
[1], &status
, 1);
6209 if (len
== -1 && (errno
== EINTR
))
6216 TFR(fd
= open("/dev/null", O_RDWR
));
6222 pwd
= getpwnam(run_as
);
6224 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
6230 if (chroot(chroot_dir
) < 0) {
6231 fprintf(stderr
, "chroot failed\n");
6238 if (setgid(pwd
->pw_gid
) < 0) {
6239 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
6242 if (setuid(pwd
->pw_uid
) < 0) {
6243 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
6246 if (setuid(0) != -1) {
6247 fprintf(stderr
, "Dropping privileges failed\n");