4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
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>
95 /* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
96 discussion about Solaris header problems */
97 extern int madvise(caddr_t
, size_t, int);
102 #if defined(__OpenBSD__)
106 #if defined(CONFIG_VDE)
107 #include <libvdeplug.h>
112 #include <mmsystem.h>
116 #if defined(__APPLE__) || defined(main)
118 int qemu_main(int argc
, char **argv
, char **envp
);
119 int main(int argc
, char **argv
)
121 return qemu_main(argc
, argv
, NULL
);
124 #define main qemu_main
126 #endif /* CONFIG_SDL */
130 #define main qemu_main
131 #endif /* CONFIG_COCOA */
134 #include "hw/boards.h"
136 #include "hw/pcmcia.h"
138 #include "hw/audiodev.h"
142 #include "hw/watchdog.h"
143 #include "hw/smbios.h"
146 #include "hw/loader.h"
153 #include "qemu-timer.h"
154 #include "qemu-char.h"
155 #include "cache-utils.h"
158 #include "audio/audio.h"
159 #include "migration.h"
162 #include "qemu-option.h"
163 #include "qemu-config.h"
164 #include "qemu-kvm.h"
165 #include "hw/device-assignment.h"
169 #include "exec-all.h"
171 #include "qemu_socket.h"
173 #include "slirp/libslirp.h"
175 #include "qemu-queue.h"
178 //#define DEBUG_SLIRP
180 #define DEFAULT_RAM_SIZE 128
182 /* Maximum number of monitor devices */
183 #define MAX_MONITOR_DEVICES 10
185 static const char *data_dir
;
186 const char *bios_name
= NULL
;
187 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
188 to store the VM snapshots */
189 struct drivelist drives
= QTAILQ_HEAD_INITIALIZER(drives
);
190 struct driveoptlist driveopts
= QTAILQ_HEAD_INITIALIZER(driveopts
);
191 DriveInfo
*extboot_drive
= NULL
;
192 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
193 static DisplayState
*display_state
;
194 DisplayType display_type
= DT_DEFAULT
;
195 const char* keyboard_layout
= NULL
;
198 NICInfo nd_table
[MAX_NICS
];
201 static int rtc_utc
= 1;
202 static int rtc_date_offset
= -1; /* -1 means no change */
203 QEMUClock
*rtc_clock
;
204 int vga_interface_type
= VGA_CIRRUS
;
206 int graphic_width
= 1024;
207 int graphic_height
= 768;
208 int graphic_depth
= 8;
210 int graphic_width
= 800;
211 int graphic_height
= 600;
212 int graphic_depth
= 15;
214 static int full_screen
= 0;
216 static int no_frame
= 0;
219 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
220 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
221 CharDriverState
*virtcon_hds
[MAX_VIRTIO_CONSOLES
];
223 int win2k_install_hack
= 0;
228 const char *assigned_devices
[MAX_DEV_ASSIGN_CMDLINE
];
229 int assigned_devices_index
;
234 const char *vnc_display
;
235 int acpi_enabled
= 1;
243 int graphic_rotate
= 0;
244 uint8_t irq0override
= 1;
248 const char *watchdog
;
249 const char *option_rom
[MAX_OPTION_ROMS
];
251 int semihosting_enabled
= 0;
252 int time_drift_fix
= 0;
253 unsigned int kvm_shadow_memory
= 0;
254 const char *mem_path
= NULL
;
256 int mem_prealloc
= 1; /* force preallocation of physical target memory */
261 const char *qemu_name
;
264 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
265 unsigned int nb_prom_envs
= 0;
266 const char *prom_envs
[MAX_PROM_ENVS
];
268 const char *nvram
= NULL
;
272 uint64_t node_mem
[MAX_NODES
];
273 uint64_t node_cpumask
[MAX_NODES
];
275 static CPUState
*cur_cpu
;
276 static CPUState
*next_cpu
;
277 static int timer_alarm_pending
= 1;
278 /* Conversion factor from emulated instructions to virtual clock ticks. */
279 static int icount_time_shift
;
280 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
281 #define MAX_ICOUNT_SHIFT 10
282 /* Compensate for varying guest execution speed. */
283 static int64_t qemu_icount_bias
;
284 static QEMUTimer
*icount_rt_timer
;
285 static QEMUTimer
*icount_vm_timer
;
286 static QEMUTimer
*nographic_timer
;
288 uint8_t qemu_uuid
[16];
290 static QEMUBootSetHandler
*boot_set_handler
;
291 static void *boot_set_opaque
;
293 /***********************************************************/
294 /* x86 ISA bus support */
296 target_phys_addr_t isa_mem_base
= 0;
299 /***********************************************************/
300 void hw_error(const char *fmt
, ...)
306 fprintf(stderr
, "qemu: hardware error: ");
307 vfprintf(stderr
, fmt
, ap
);
308 fprintf(stderr
, "\n");
309 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
310 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
312 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
314 cpu_dump_state(env
, stderr
, fprintf
, 0);
321 static void set_proc_name(const char *s
)
323 #if defined(__linux__) && defined(PR_SET_NAME)
327 name
[sizeof(name
) - 1] = 0;
328 strncpy(name
, s
, sizeof(name
));
329 /* Could rewrite argv[0] too, but that's a bit more complicated.
330 This simple way is enough for `top'. */
331 prctl(PR_SET_NAME
, name
);
338 static QEMUBalloonEvent
*qemu_balloon_event
;
339 void *qemu_balloon_event_opaque
;
341 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
343 qemu_balloon_event
= func
;
344 qemu_balloon_event_opaque
= opaque
;
347 void qemu_balloon(ram_addr_t target
)
349 if (qemu_balloon_event
)
350 qemu_balloon_event(qemu_balloon_event_opaque
, target
);
353 ram_addr_t
qemu_balloon_status(void)
355 if (qemu_balloon_event
)
356 return qemu_balloon_event(qemu_balloon_event_opaque
, 0);
360 /***********************************************************/
363 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
364 static void *qemu_put_kbd_event_opaque
;
365 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
366 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
368 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
370 qemu_put_kbd_event_opaque
= opaque
;
371 qemu_put_kbd_event
= func
;
374 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
375 void *opaque
, int absolute
,
378 QEMUPutMouseEntry
*s
, *cursor
;
380 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
382 s
->qemu_put_mouse_event
= func
;
383 s
->qemu_put_mouse_event_opaque
= opaque
;
384 s
->qemu_put_mouse_event_absolute
= absolute
;
385 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
388 if (!qemu_put_mouse_event_head
) {
389 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
393 cursor
= qemu_put_mouse_event_head
;
394 while (cursor
->next
!= NULL
)
395 cursor
= cursor
->next
;
398 qemu_put_mouse_event_current
= s
;
403 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
405 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
407 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
410 cursor
= qemu_put_mouse_event_head
;
411 while (cursor
!= NULL
&& cursor
!= entry
) {
413 cursor
= cursor
->next
;
416 if (cursor
== NULL
) // does not exist or list empty
418 else if (prev
== NULL
) { // entry is head
419 qemu_put_mouse_event_head
= cursor
->next
;
420 if (qemu_put_mouse_event_current
== entry
)
421 qemu_put_mouse_event_current
= cursor
->next
;
422 qemu_free(entry
->qemu_put_mouse_event_name
);
427 prev
->next
= entry
->next
;
429 if (qemu_put_mouse_event_current
== entry
)
430 qemu_put_mouse_event_current
= prev
;
432 qemu_free(entry
->qemu_put_mouse_event_name
);
436 void kbd_put_keycode(int keycode
)
438 if (qemu_put_kbd_event
) {
439 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
443 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
445 QEMUPutMouseEvent
*mouse_event
;
446 void *mouse_event_opaque
;
449 if (!qemu_put_mouse_event_current
) {
454 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
456 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
459 if (graphic_rotate
) {
460 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
463 width
= graphic_width
- 1;
464 mouse_event(mouse_event_opaque
,
465 width
- dy
, dx
, dz
, buttons_state
);
467 mouse_event(mouse_event_opaque
,
468 dx
, dy
, dz
, buttons_state
);
472 int kbd_mouse_is_absolute(void)
474 if (!qemu_put_mouse_event_current
)
477 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
480 void do_info_mice(Monitor
*mon
)
482 QEMUPutMouseEntry
*cursor
;
485 if (!qemu_put_mouse_event_head
) {
486 monitor_printf(mon
, "No mouse devices connected\n");
490 monitor_printf(mon
, "Mouse devices available:\n");
491 cursor
= qemu_put_mouse_event_head
;
492 while (cursor
!= NULL
) {
493 monitor_printf(mon
, "%c Mouse #%d: %s\n",
494 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
495 index
, cursor
->qemu_put_mouse_event_name
);
497 cursor
= cursor
->next
;
501 void do_mouse_set(Monitor
*mon
, const QDict
*qdict
)
503 QEMUPutMouseEntry
*cursor
;
505 int index
= qdict_get_int(qdict
, "index");
507 if (!qemu_put_mouse_event_head
) {
508 monitor_printf(mon
, "No mouse devices connected\n");
512 cursor
= qemu_put_mouse_event_head
;
513 while (cursor
!= NULL
&& index
!= i
) {
515 cursor
= cursor
->next
;
519 qemu_put_mouse_event_current
= cursor
;
521 monitor_printf(mon
, "Mouse at given index not found\n");
524 /* compute with 96 bit intermediate result: (a*b)/c */
525 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
530 #ifdef HOST_WORDS_BIGENDIAN
540 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
541 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
544 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
548 /***********************************************************/
549 /* real time host monotonic timer */
551 static int64_t get_clock_realtime(void)
555 gettimeofday(&tv
, NULL
);
556 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
561 static int64_t clock_freq
;
563 static void init_get_clock(void)
567 ret
= QueryPerformanceFrequency(&freq
);
569 fprintf(stderr
, "Could not calibrate ticks\n");
572 clock_freq
= freq
.QuadPart
;
575 static int64_t get_clock(void)
578 QueryPerformanceCounter(&ti
);
579 return muldiv64(ti
.QuadPart
, get_ticks_per_sec(), clock_freq
);
584 static int use_rt_clock
;
586 static void init_get_clock(void)
589 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
590 || defined(__DragonFly__)
593 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
600 static int64_t get_clock(void)
602 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
603 || defined(__DragonFly__)
606 clock_gettime(CLOCK_MONOTONIC
, &ts
);
607 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
611 /* XXX: using gettimeofday leads to problems if the date
612 changes, so it should be avoided. */
613 return get_clock_realtime();
618 /* Return the virtual CPU time, based on the instruction counter. */
619 static int64_t cpu_get_icount(void)
622 CPUState
*env
= cpu_single_env
;;
623 icount
= qemu_icount
;
626 fprintf(stderr
, "Bad clock read\n");
627 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
629 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
632 /***********************************************************/
633 /* guest cycle counter */
635 typedef struct TimersState
{
636 int64_t cpu_ticks_prev
;
637 int64_t cpu_ticks_offset
;
638 int64_t cpu_clock_offset
;
639 int32_t cpu_ticks_enabled
;
643 TimersState timers_state
;
645 /* return the host CPU cycle counter and handle stop/restart */
646 int64_t cpu_get_ticks(void)
649 return cpu_get_icount();
651 if (!timers_state
.cpu_ticks_enabled
) {
652 return timers_state
.cpu_ticks_offset
;
655 ticks
= cpu_get_real_ticks();
656 if (timers_state
.cpu_ticks_prev
> ticks
) {
657 /* Note: non increasing ticks may happen if the host uses
659 timers_state
.cpu_ticks_offset
+= timers_state
.cpu_ticks_prev
- ticks
;
661 timers_state
.cpu_ticks_prev
= ticks
;
662 return ticks
+ timers_state
.cpu_ticks_offset
;
666 /* return the host CPU monotonic timer and handle stop/restart */
667 static int64_t cpu_get_clock(void)
670 if (!timers_state
.cpu_ticks_enabled
) {
671 return timers_state
.cpu_clock_offset
;
674 return ti
+ timers_state
.cpu_clock_offset
;
678 /* enable cpu_get_ticks() */
679 void cpu_enable_ticks(void)
681 if (!timers_state
.cpu_ticks_enabled
) {
682 timers_state
.cpu_ticks_offset
-= cpu_get_real_ticks();
683 timers_state
.cpu_clock_offset
-= get_clock();
684 timers_state
.cpu_ticks_enabled
= 1;
688 /* disable cpu_get_ticks() : the clock is stopped. You must not call
689 cpu_get_ticks() after that. */
690 void cpu_disable_ticks(void)
692 if (timers_state
.cpu_ticks_enabled
) {
693 timers_state
.cpu_ticks_offset
= cpu_get_ticks();
694 timers_state
.cpu_clock_offset
= cpu_get_clock();
695 timers_state
.cpu_ticks_enabled
= 0;
699 /***********************************************************/
702 #define QEMU_CLOCK_REALTIME 0
703 #define QEMU_CLOCK_VIRTUAL 1
704 #define QEMU_CLOCK_HOST 2
708 /* XXX: add frequency */
716 struct QEMUTimer
*next
;
719 struct qemu_alarm_timer
{
723 int (*start
)(struct qemu_alarm_timer
*t
);
724 void (*stop
)(struct qemu_alarm_timer
*t
);
725 void (*rearm
)(struct qemu_alarm_timer
*t
);
729 #define ALARM_FLAG_DYNTICKS 0x1
730 #define ALARM_FLAG_EXPIRED 0x2
732 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
734 return t
&& (t
->flags
& ALARM_FLAG_DYNTICKS
);
737 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
739 if (!alarm_has_dynticks(t
))
745 /* TODO: MIN_TIMER_REARM_US should be optimized */
746 #define MIN_TIMER_REARM_US 250
748 static struct qemu_alarm_timer
*alarm_timer
;
752 struct qemu_alarm_win32
{
755 } alarm_win32_data
= {0, -1};
757 static int win32_start_timer(struct qemu_alarm_timer
*t
);
758 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
759 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
763 static int unix_start_timer(struct qemu_alarm_timer
*t
);
764 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
768 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
769 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
770 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
772 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
773 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
775 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
776 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
778 #endif /* __linux__ */
782 /* Correlation between real and virtual time is always going to be
783 fairly approximate, so ignore small variation.
784 When the guest is idle real and virtual time will be aligned in
786 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
788 static void icount_adjust(void)
793 static int64_t last_delta
;
794 /* If the VM is not running, then do nothing. */
798 cur_time
= cpu_get_clock();
799 cur_icount
= qemu_get_clock(vm_clock
);
800 delta
= cur_icount
- cur_time
;
801 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
803 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
804 && icount_time_shift
> 0) {
805 /* The guest is getting too far ahead. Slow time down. */
809 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
810 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
811 /* The guest is getting too far behind. Speed time up. */
815 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
818 static void icount_adjust_rt(void * opaque
)
820 qemu_mod_timer(icount_rt_timer
,
821 qemu_get_clock(rt_clock
) + 1000);
825 static void icount_adjust_vm(void * opaque
)
827 qemu_mod_timer(icount_vm_timer
,
828 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
832 static void init_icount_adjust(void)
834 /* Have both realtime and virtual time triggers for speed adjustment.
835 The realtime trigger catches emulated time passing too slowly,
836 the virtual time trigger catches emulated time passing too fast.
837 Realtime triggers occur even when idle, so use them less frequently
839 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
840 qemu_mod_timer(icount_rt_timer
,
841 qemu_get_clock(rt_clock
) + 1000);
842 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
843 qemu_mod_timer(icount_vm_timer
,
844 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
847 static struct qemu_alarm_timer alarm_timers
[] = {
850 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
851 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
852 /* HPET - if available - is preferred */
853 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
854 /* ...otherwise try RTC */
855 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
857 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
859 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
860 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
861 {"win32", 0, win32_start_timer
,
862 win32_stop_timer
, NULL
, &alarm_win32_data
},
867 static void show_available_alarms(void)
871 printf("Available alarm timers, in order of precedence:\n");
872 for (i
= 0; alarm_timers
[i
].name
; i
++)
873 printf("%s\n", alarm_timers
[i
].name
);
876 static void configure_alarms(char const *opt
)
880 int count
= ARRAY_SIZE(alarm_timers
) - 1;
883 struct qemu_alarm_timer tmp
;
885 if (!strcmp(opt
, "?")) {
886 show_available_alarms();
890 arg
= qemu_strdup(opt
);
892 /* Reorder the array */
893 name
= strtok(arg
, ",");
895 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
896 if (!strcmp(alarm_timers
[i
].name
, name
))
901 fprintf(stderr
, "Unknown clock %s\n", name
);
910 tmp
= alarm_timers
[i
];
911 alarm_timers
[i
] = alarm_timers
[cur
];
912 alarm_timers
[cur
] = tmp
;
916 name
= strtok(NULL
, ",");
922 /* Disable remaining timers */
923 for (i
= cur
; i
< count
; i
++)
924 alarm_timers
[i
].name
= NULL
;
926 show_available_alarms();
931 #define QEMU_NUM_CLOCKS 3
935 QEMUClock
*host_clock
;
937 static QEMUTimer
*active_timers
[QEMU_NUM_CLOCKS
];
939 static QEMUClock
*qemu_new_clock(int type
)
942 clock
= qemu_mallocz(sizeof(QEMUClock
));
947 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
951 ts
= qemu_mallocz(sizeof(QEMUTimer
));
958 void qemu_free_timer(QEMUTimer
*ts
)
963 /* stop a timer, but do not dealloc it */
964 void qemu_del_timer(QEMUTimer
*ts
)
968 /* NOTE: this code must be signal safe because
969 qemu_timer_expired() can be called from a signal. */
970 pt
= &active_timers
[ts
->clock
->type
];
983 /* modify the current timer so that it will be fired when current_time
984 >= expire_time. The corresponding callback will be called. */
985 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
991 /* add the timer in the sorted list */
992 /* NOTE: this code must be signal safe because
993 qemu_timer_expired() can be called from a signal. */
994 pt
= &active_timers
[ts
->clock
->type
];
999 if (t
->expire_time
> expire_time
)
1003 ts
->expire_time
= expire_time
;
1007 /* Rearm if necessary */
1008 if (pt
== &active_timers
[ts
->clock
->type
]) {
1009 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1010 qemu_rearm_alarm_timer(alarm_timer
);
1012 /* Interrupt execution to force deadline recalculation. */
1014 qemu_notify_event();
1018 int qemu_timer_pending(QEMUTimer
*ts
)
1021 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1028 int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1032 return (timer_head
->expire_time
<= current_time
);
1035 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1041 if (!ts
|| ts
->expire_time
> current_time
)
1043 /* remove timer from the list before calling the callback */
1044 *ptimer_head
= ts
->next
;
1047 /* run the callback (the timer list can be modified) */
1052 int64_t qemu_get_clock(QEMUClock
*clock
)
1054 switch(clock
->type
) {
1055 case QEMU_CLOCK_REALTIME
:
1056 return get_clock() / 1000000;
1058 case QEMU_CLOCK_VIRTUAL
:
1060 return cpu_get_icount();
1062 return cpu_get_clock();
1064 case QEMU_CLOCK_HOST
:
1065 return get_clock_realtime();
1069 static void init_clocks(void)
1072 rt_clock
= qemu_new_clock(QEMU_CLOCK_REALTIME
);
1073 vm_clock
= qemu_new_clock(QEMU_CLOCK_VIRTUAL
);
1074 host_clock
= qemu_new_clock(QEMU_CLOCK_HOST
);
1076 rtc_clock
= host_clock
;
1080 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1082 uint64_t expire_time
;
1084 if (qemu_timer_pending(ts
)) {
1085 expire_time
= ts
->expire_time
;
1089 qemu_put_be64(f
, expire_time
);
1092 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1094 uint64_t expire_time
;
1096 expire_time
= qemu_get_be64(f
);
1097 if (expire_time
!= -1) {
1098 qemu_mod_timer(ts
, expire_time
);
1104 static const VMStateDescription vmstate_timers
= {
1107 .minimum_version_id
= 1,
1108 .minimum_version_id_old
= 1,
1109 .fields
= (VMStateField
[]) {
1110 VMSTATE_INT64(cpu_ticks_offset
, TimersState
),
1111 VMSTATE_INT64(dummy
, TimersState
),
1112 VMSTATE_INT64_V(cpu_clock_offset
, TimersState
, 2),
1113 VMSTATE_END_OF_LIST()
1117 static void qemu_event_increment(void);
1120 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1121 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1124 static void host_alarm_handler(int host_signum
)
1128 #define DISP_FREQ 1000
1130 static int64_t delta_min
= INT64_MAX
;
1131 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1133 ti
= qemu_get_clock(vm_clock
);
1134 if (last_clock
!= 0) {
1135 delta
= ti
- last_clock
;
1136 if (delta
< delta_min
)
1138 if (delta
> delta_max
)
1141 if (++count
== DISP_FREQ
) {
1142 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1143 muldiv64(delta_min
, 1000000, get_ticks_per_sec()),
1144 muldiv64(delta_max
, 1000000, get_ticks_per_sec()),
1145 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, get_ticks_per_sec()),
1146 (double)get_ticks_per_sec() / ((double)delta_cum
/ DISP_FREQ
));
1148 delta_min
= INT64_MAX
;
1156 if (alarm_has_dynticks(alarm_timer
) ||
1158 qemu_timer_expired(active_timers
[QEMU_CLOCK_VIRTUAL
],
1159 qemu_get_clock(vm_clock
))) ||
1160 qemu_timer_expired(active_timers
[QEMU_CLOCK_REALTIME
],
1161 qemu_get_clock(rt_clock
)) ||
1162 qemu_timer_expired(active_timers
[QEMU_CLOCK_HOST
],
1163 qemu_get_clock(host_clock
))) {
1164 qemu_event_increment();
1165 if (alarm_timer
) alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1167 #ifndef CONFIG_IOTHREAD
1169 /* stop the currently executing cpu because a timer occured */
1173 timer_alarm_pending
= 1;
1174 qemu_notify_event();
1178 static int64_t qemu_next_deadline(void)
1180 /* To avoid problems with overflow limit this to 2^32. */
1181 int64_t delta
= INT32_MAX
;
1183 if (active_timers
[QEMU_CLOCK_VIRTUAL
]) {
1184 delta
= active_timers
[QEMU_CLOCK_VIRTUAL
]->expire_time
-
1185 qemu_get_clock(vm_clock
);
1187 if (active_timers
[QEMU_CLOCK_HOST
]) {
1188 int64_t hdelta
= active_timers
[QEMU_CLOCK_HOST
]->expire_time
-
1189 qemu_get_clock(host_clock
);
1200 #if defined(__linux__)
1201 static uint64_t qemu_next_deadline_dyntick(void)
1209 delta
= (qemu_next_deadline() + 999) / 1000;
1211 if (active_timers
[QEMU_CLOCK_REALTIME
]) {
1212 rtdelta
= (active_timers
[QEMU_CLOCK_REALTIME
]->expire_time
-
1213 qemu_get_clock(rt_clock
))*1000;
1214 if (rtdelta
< delta
)
1218 if (delta
< MIN_TIMER_REARM_US
)
1219 delta
= MIN_TIMER_REARM_US
;
1227 /* Sets a specific flag */
1228 static int fcntl_setfl(int fd
, int flag
)
1232 flags
= fcntl(fd
, F_GETFL
);
1236 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1242 #if defined(__linux__)
1244 #define RTC_FREQ 1024
1246 static void enable_sigio_timer(int fd
)
1248 struct sigaction act
;
1251 sigfillset(&act
.sa_mask
);
1253 act
.sa_handler
= host_alarm_handler
;
1255 sigaction(SIGIO
, &act
, NULL
);
1256 fcntl_setfl(fd
, O_ASYNC
);
1257 fcntl(fd
, F_SETOWN
, getpid());
1260 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1262 struct hpet_info info
;
1265 fd
= open("/dev/hpet", O_RDONLY
);
1270 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1272 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1273 "error, but for better emulation accuracy type:\n"
1274 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1278 /* Check capabilities */
1279 r
= ioctl(fd
, HPET_INFO
, &info
);
1283 /* Enable periodic mode */
1284 r
= ioctl(fd
, HPET_EPI
, 0);
1285 if (info
.hi_flags
&& (r
< 0))
1288 /* Enable interrupt */
1289 r
= ioctl(fd
, HPET_IE_ON
, 0);
1293 enable_sigio_timer(fd
);
1294 t
->priv
= (void *)(long)fd
;
1302 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1304 int fd
= (long)t
->priv
;
1309 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1312 unsigned long current_rtc_freq
= 0;
1314 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1317 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1318 if (current_rtc_freq
!= RTC_FREQ
&&
1319 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1320 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1321 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1322 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1325 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1331 enable_sigio_timer(rtc_fd
);
1333 t
->priv
= (void *)(long)rtc_fd
;
1338 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1340 int rtc_fd
= (long)t
->priv
;
1345 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1349 struct sigaction act
;
1351 sigfillset(&act
.sa_mask
);
1353 act
.sa_handler
= host_alarm_handler
;
1355 sigaction(SIGALRM
, &act
, NULL
);
1358 * Initialize ev struct to 0 to avoid valgrind complaining
1359 * about uninitialized data in timer_create call
1361 memset(&ev
, 0, sizeof(ev
));
1362 ev
.sigev_value
.sival_int
= 0;
1363 ev
.sigev_notify
= SIGEV_SIGNAL
;
1364 ev
.sigev_signo
= SIGALRM
;
1366 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1367 perror("timer_create");
1369 /* disable dynticks */
1370 fprintf(stderr
, "Dynamic Ticks disabled\n");
1375 t
->priv
= (void *)(long)host_timer
;
1380 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1382 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1384 timer_delete(host_timer
);
1387 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1389 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1390 struct itimerspec timeout
;
1391 int64_t nearest_delta_us
= INT64_MAX
;
1394 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1395 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1396 !active_timers
[QEMU_CLOCK_HOST
])
1399 nearest_delta_us
= qemu_next_deadline_dyntick();
1401 /* check whether a timer is already running */
1402 if (timer_gettime(host_timer
, &timeout
)) {
1404 fprintf(stderr
, "Internal timer error: aborting\n");
1407 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1408 if (current_us
&& current_us
<= nearest_delta_us
)
1411 timeout
.it_interval
.tv_sec
= 0;
1412 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1413 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1414 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1415 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1417 fprintf(stderr
, "Internal timer error: aborting\n");
1422 #endif /* defined(__linux__) */
1424 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1426 struct sigaction act
;
1427 struct itimerval itv
;
1431 sigfillset(&act
.sa_mask
);
1433 act
.sa_handler
= host_alarm_handler
;
1435 sigaction(SIGALRM
, &act
, NULL
);
1437 itv
.it_interval
.tv_sec
= 0;
1438 /* for i386 kernel 2.6 to get 1 ms */
1439 itv
.it_interval
.tv_usec
= 999;
1440 itv
.it_value
.tv_sec
= 0;
1441 itv
.it_value
.tv_usec
= 10 * 1000;
1443 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1450 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1452 struct itimerval itv
;
1454 memset(&itv
, 0, sizeof(itv
));
1455 setitimer(ITIMER_REAL
, &itv
, NULL
);
1458 #endif /* !defined(_WIN32) */
1463 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1466 struct qemu_alarm_win32
*data
= t
->priv
;
1469 memset(&tc
, 0, sizeof(tc
));
1470 timeGetDevCaps(&tc
, sizeof(tc
));
1472 if (data
->period
< tc
.wPeriodMin
)
1473 data
->period
= tc
.wPeriodMin
;
1475 timeBeginPeriod(data
->period
);
1477 flags
= TIME_CALLBACK_FUNCTION
;
1478 if (alarm_has_dynticks(t
))
1479 flags
|= TIME_ONESHOT
;
1481 flags
|= TIME_PERIODIC
;
1483 data
->timerId
= timeSetEvent(1, // interval (ms)
1484 data
->period
, // resolution
1485 host_alarm_handler
, // function
1486 (DWORD
)t
, // parameter
1489 if (!data
->timerId
) {
1490 fprintf(stderr
, "Failed to initialize win32 alarm timer: %ld\n",
1492 timeEndPeriod(data
->period
);
1499 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1501 struct qemu_alarm_win32
*data
= t
->priv
;
1503 timeKillEvent(data
->timerId
);
1504 timeEndPeriod(data
->period
);
1507 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1509 struct qemu_alarm_win32
*data
= t
->priv
;
1511 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1512 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1513 !active_timers
[QEMU_CLOCK_HOST
])
1516 timeKillEvent(data
->timerId
);
1518 data
->timerId
= timeSetEvent(1,
1522 TIME_ONESHOT
| TIME_PERIODIC
);
1524 if (!data
->timerId
) {
1525 fprintf(stderr
, "Failed to re-arm win32 alarm timer %ld\n",
1528 timeEndPeriod(data
->period
);
1535 static int init_timer_alarm(void)
1537 struct qemu_alarm_timer
*t
= NULL
;
1540 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1541 t
= &alarm_timers
[i
];
1561 static void quit_timers(void)
1563 alarm_timer
->stop(alarm_timer
);
1567 /***********************************************************/
1568 /* host time/date access */
1569 void qemu_get_timedate(struct tm
*tm
, int offset
)
1576 if (rtc_date_offset
== -1) {
1580 ret
= localtime(&ti
);
1582 ti
-= rtc_date_offset
;
1586 memcpy(tm
, ret
, sizeof(struct tm
));
1589 int qemu_timedate_diff(struct tm
*tm
)
1593 if (rtc_date_offset
== -1)
1595 seconds
= mktimegm(tm
);
1597 seconds
= mktime(tm
);
1599 seconds
= mktimegm(tm
) + rtc_date_offset
;
1601 return seconds
- time(NULL
);
1604 static void configure_rtc_date_offset(const char *startdate
, int legacy
)
1606 time_t rtc_start_date
;
1609 if (!strcmp(startdate
, "now") && legacy
) {
1610 rtc_date_offset
= -1;
1612 if (sscanf(startdate
, "%d-%d-%dT%d:%d:%d",
1620 } else if (sscanf(startdate
, "%d-%d-%d",
1623 &tm
.tm_mday
) == 3) {
1632 rtc_start_date
= mktimegm(&tm
);
1633 if (rtc_start_date
== -1) {
1635 fprintf(stderr
, "Invalid date format. Valid formats are:\n"
1636 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1639 rtc_date_offset
= time(NULL
) - rtc_start_date
;
1643 static void configure_rtc(QemuOpts
*opts
)
1647 value
= qemu_opt_get(opts
, "base");
1649 if (!strcmp(value
, "utc")) {
1651 } else if (!strcmp(value
, "localtime")) {
1654 configure_rtc_date_offset(value
, 0);
1657 value
= qemu_opt_get(opts
, "clock");
1659 if (!strcmp(value
, "host")) {
1660 rtc_clock
= host_clock
;
1661 } else if (!strcmp(value
, "vm")) {
1662 rtc_clock
= vm_clock
;
1664 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1668 #ifdef CONFIG_TARGET_I386
1669 value
= qemu_opt_get(opts
, "driftfix");
1671 if (!strcmp(buf
, "slew")) {
1673 } else if (!strcmp(buf
, "none")) {
1676 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1684 static void socket_cleanup(void)
1689 static int socket_init(void)
1694 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1696 err
= WSAGetLastError();
1697 fprintf(stderr
, "WSAStartup: %d\n", err
);
1700 atexit(socket_cleanup
);
1705 /***********************************************************/
1706 /* Bluetooth support */
1709 static struct HCIInfo
*hci_table
[MAX_NICS
];
1711 static struct bt_vlan_s
{
1712 struct bt_scatternet_s net
;
1714 struct bt_vlan_s
*next
;
1717 /* find or alloc a new bluetooth "VLAN" */
1718 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1720 struct bt_vlan_s
**pvlan
, *vlan
;
1721 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1725 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1727 pvlan
= &first_bt_vlan
;
1728 while (*pvlan
!= NULL
)
1729 pvlan
= &(*pvlan
)->next
;
1734 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1738 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1743 static struct HCIInfo null_hci
= {
1744 .cmd_send
= null_hci_send
,
1745 .sco_send
= null_hci_send
,
1746 .acl_send
= null_hci_send
,
1747 .bdaddr_set
= null_hci_addr_set
,
1750 struct HCIInfo
*qemu_next_hci(void)
1752 if (cur_hci
== nb_hcis
)
1755 return hci_table
[cur_hci
++];
1758 static struct HCIInfo
*hci_init(const char *str
)
1761 struct bt_scatternet_s
*vlan
= 0;
1763 if (!strcmp(str
, "null"))
1766 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
1768 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
1769 else if (!strncmp(str
, "hci", 3)) {
1772 if (!strncmp(str
+ 3, ",vlan=", 6)) {
1773 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
1778 vlan
= qemu_find_bt_vlan(0);
1780 return bt_new_hci(vlan
);
1783 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
1788 static int bt_hci_parse(const char *str
)
1790 struct HCIInfo
*hci
;
1793 if (nb_hcis
>= MAX_NICS
) {
1794 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
1798 hci
= hci_init(str
);
1807 bdaddr
.b
[5] = 0x56 + nb_hcis
;
1808 hci
->bdaddr_set(hci
, bdaddr
.b
);
1810 hci_table
[nb_hcis
++] = hci
;
1815 static void bt_vhci_add(int vlan_id
)
1817 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
1820 fprintf(stderr
, "qemu: warning: adding a VHCI to "
1821 "an empty scatternet %i\n", vlan_id
);
1823 bt_vhci_init(bt_new_hci(vlan
));
1826 static struct bt_device_s
*bt_device_add(const char *opt
)
1828 struct bt_scatternet_s
*vlan
;
1830 char *endp
= strstr(opt
, ",vlan=");
1831 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
1834 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
1837 vlan_id
= strtol(endp
+ 6, &endp
, 0);
1839 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
1844 vlan
= qemu_find_bt_vlan(vlan_id
);
1847 fprintf(stderr
, "qemu: warning: adding a slave device to "
1848 "an empty scatternet %i\n", vlan_id
);
1850 if (!strcmp(devname
, "keyboard"))
1851 return bt_keyboard_init(vlan
);
1853 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
1857 static int bt_parse(const char *opt
)
1859 const char *endp
, *p
;
1862 if (strstart(opt
, "hci", &endp
)) {
1863 if (!*endp
|| *endp
== ',') {
1865 if (!strstart(endp
, ",vlan=", 0))
1868 return bt_hci_parse(opt
);
1870 } else if (strstart(opt
, "vhci", &endp
)) {
1871 if (!*endp
|| *endp
== ',') {
1873 if (strstart(endp
, ",vlan=", &p
)) {
1874 vlan
= strtol(p
, (char **) &endp
, 0);
1876 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
1880 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
1889 } else if (strstart(opt
, "device:", &endp
))
1890 return !bt_device_add(endp
);
1892 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
1896 /***********************************************************/
1897 /* QEMU Block devices */
1899 #define HD_ALIAS "index=%d,media=disk"
1900 #define CDROM_ALIAS "index=2,media=cdrom"
1901 #define FD_ALIAS "index=%d,if=floppy"
1902 #define PFLASH_ALIAS "if=pflash"
1903 #define MTD_ALIAS "if=mtd"
1904 #define SD_ALIAS "index=0,if=sd"
1906 QemuOpts
*drive_add(const char *file
, const char *fmt
, ...)
1913 vsnprintf(optstr
, sizeof(optstr
), fmt
, ap
);
1916 opts
= qemu_opts_parse(&qemu_drive_opts
, optstr
, NULL
);
1918 fprintf(stderr
, "%s: huh? duplicate? (%s)\n",
1919 __FUNCTION__
, optstr
);
1923 qemu_opt_set(opts
, "file", file
);
1927 DriveInfo
*drive_get(BlockInterfaceType type
, int bus
, int unit
)
1931 /* seek interface, bus and unit */
1933 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1934 if (dinfo
->type
== type
&&
1935 dinfo
->bus
== bus
&&
1936 dinfo
->unit
== unit
)
1943 DriveInfo
*drive_get_by_id(const char *id
)
1947 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1948 if (strcmp(id
, dinfo
->id
))
1955 int drive_get_max_bus(BlockInterfaceType type
)
1961 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1962 if(dinfo
->type
== type
&&
1963 dinfo
->bus
> max_bus
)
1964 max_bus
= dinfo
->bus
;
1969 const char *drive_get_serial(BlockDriverState
*bdrv
)
1973 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1974 if (dinfo
->bdrv
== bdrv
)
1975 return dinfo
->serial
;
1981 BlockInterfaceErrorAction
drive_get_onerror(BlockDriverState
*bdrv
)
1985 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1986 if (dinfo
->bdrv
== bdrv
)
1987 return dinfo
->onerror
;
1990 return BLOCK_ERR_STOP_ENOSPC
;
1993 static void bdrv_format_print(void *opaque
, const char *name
)
1995 fprintf(stderr
, " %s", name
);
1998 void drive_uninit(DriveInfo
*dinfo
)
2000 qemu_opts_del(dinfo
->opts
);
2001 bdrv_delete(dinfo
->bdrv
);
2002 QTAILQ_REMOVE(&drives
, dinfo
, next
);
2006 DriveInfo
*drive_init(QemuOpts
*opts
, void *opaque
,
2010 const char *file
= NULL
;
2013 const char *mediastr
= "";
2014 BlockInterfaceType type
;
2015 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
2016 int bus_id
, unit_id
;
2017 int cyls
, heads
, secs
, translation
;
2018 BlockDriver
*drv
= NULL
;
2019 QEMUMachine
*machine
= opaque
;
2024 int bdrv_flags
, onerror
;
2025 const char *devaddr
;
2032 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2035 if (machine
&& machine
->use_scsi
) {
2037 max_devs
= MAX_SCSI_DEVS
;
2038 pstrcpy(devname
, sizeof(devname
), "scsi");
2041 max_devs
= MAX_IDE_DEVS
;
2042 pstrcpy(devname
, sizeof(devname
), "ide");
2046 /* extract parameters */
2047 bus_id
= qemu_opt_get_number(opts
, "bus", 0);
2048 unit_id
= qemu_opt_get_number(opts
, "unit", -1);
2049 index
= qemu_opt_get_number(opts
, "index", -1);
2051 cyls
= qemu_opt_get_number(opts
, "cyls", 0);
2052 heads
= qemu_opt_get_number(opts
, "heads", 0);
2053 secs
= qemu_opt_get_number(opts
, "secs", 0);
2055 snapshot
= qemu_opt_get_bool(opts
, "snapshot", 0);
2057 file
= qemu_opt_get(opts
, "file");
2058 serial
= qemu_opt_get(opts
, "serial");
2060 if ((buf
= qemu_opt_get(opts
, "if")) != NULL
) {
2061 pstrcpy(devname
, sizeof(devname
), buf
);
2062 if (!strcmp(buf
, "ide")) {
2064 max_devs
= MAX_IDE_DEVS
;
2065 } else if (!strcmp(buf
, "scsi")) {
2067 max_devs
= MAX_SCSI_DEVS
;
2068 } else if (!strcmp(buf
, "floppy")) {
2071 } else if (!strcmp(buf
, "pflash")) {
2074 } else if (!strcmp(buf
, "mtd")) {
2077 } else if (!strcmp(buf
, "sd")) {
2080 } else if (!strcmp(buf
, "virtio")) {
2083 } else if (!strcmp(buf
, "xen")) {
2086 } else if (!strcmp(buf
, "none")) {
2090 fprintf(stderr
, "qemu: unsupported bus type '%s'\n", buf
);
2095 if (cyls
|| heads
|| secs
) {
2096 if (cyls
< 1 || (type
== IF_IDE
&& cyls
> 16383)) {
2097 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", buf
);
2100 if (heads
< 1 || (type
== IF_IDE
&& heads
> 16)) {
2101 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", buf
);
2104 if (secs
< 1 || (type
== IF_IDE
&& secs
> 63)) {
2105 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", buf
);
2110 if ((buf
= qemu_opt_get(opts
, "trans")) != NULL
) {
2113 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2117 if (!strcmp(buf
, "none"))
2118 translation
= BIOS_ATA_TRANSLATION_NONE
;
2119 else if (!strcmp(buf
, "lba"))
2120 translation
= BIOS_ATA_TRANSLATION_LBA
;
2121 else if (!strcmp(buf
, "auto"))
2122 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2124 fprintf(stderr
, "qemu: '%s' invalid translation type\n", buf
);
2129 if ((buf
= qemu_opt_get(opts
, "media")) != NULL
) {
2130 if (!strcmp(buf
, "disk")) {
2132 } else if (!strcmp(buf
, "cdrom")) {
2133 if (cyls
|| secs
|| heads
) {
2135 "qemu: '%s' invalid physical CHS format\n", buf
);
2138 media
= MEDIA_CDROM
;
2140 fprintf(stderr
, "qemu: '%s' invalid media\n", buf
);
2145 if ((buf
= qemu_opt_get(opts
, "cache")) != NULL
) {
2146 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2148 else if (!strcmp(buf
, "writethrough"))
2150 else if (!strcmp(buf
, "writeback"))
2153 fprintf(stderr
, "qemu: invalid cache option\n");
2158 #ifdef CONFIG_LINUX_AIO
2159 if ((buf
= qemu_opt_get(opts
, "aio")) != NULL
) {
2160 if (!strcmp(buf
, "threads"))
2162 else if (!strcmp(buf
, "native"))
2165 fprintf(stderr
, "qemu: invalid aio option\n");
2171 if ((buf
= qemu_opt_get(opts
, "format")) != NULL
) {
2172 if (strcmp(buf
, "?") == 0) {
2173 fprintf(stderr
, "qemu: Supported formats:");
2174 bdrv_iterate_format(bdrv_format_print
, NULL
);
2175 fprintf(stderr
, "\n");
2178 drv
= bdrv_find_format(buf
);
2180 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2185 is_extboot
= qemu_opt_get_bool(opts
, "boot", 0);
2186 if (is_extboot
&& extboot_drive
) {
2187 fprintf(stderr
, "qemu: two bootable drives specified\n");
2191 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2192 if ((buf
= qemu_opt_get(opts
, "werror")) != NULL
) {
2193 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2194 fprintf(stderr
, "werror is no supported by this format\n");
2197 if (!strcmp(buf
, "ignore"))
2198 onerror
= BLOCK_ERR_IGNORE
;
2199 else if (!strcmp(buf
, "enospc"))
2200 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2201 else if (!strcmp(buf
, "stop"))
2202 onerror
= BLOCK_ERR_STOP_ANY
;
2203 else if (!strcmp(buf
, "report"))
2204 onerror
= BLOCK_ERR_REPORT
;
2206 fprintf(stderr
, "qemu: '%s' invalid write error action\n", buf
);
2211 if ((devaddr
= qemu_opt_get(opts
, "addr")) != NULL
) {
2212 if (type
!= IF_VIRTIO
) {
2213 fprintf(stderr
, "addr is not supported\n");
2218 /* compute bus and unit according index */
2221 if (bus_id
!= 0 || unit_id
!= -1) {
2223 "qemu: index cannot be used with bus and unit\n");
2231 unit_id
= index
% max_devs
;
2232 bus_id
= index
/ max_devs
;
2236 /* if user doesn't specify a unit_id,
2237 * try to find the first free
2240 if (unit_id
== -1) {
2242 while (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2244 if (max_devs
&& unit_id
>= max_devs
) {
2245 unit_id
-= max_devs
;
2253 if (max_devs
&& unit_id
>= max_devs
) {
2254 fprintf(stderr
, "qemu: unit %d too big (max is %d)\n",
2255 unit_id
, max_devs
- 1);
2260 * ignore multiple definitions
2263 if (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2270 dinfo
= qemu_mallocz(sizeof(*dinfo
));
2271 if ((buf
= qemu_opts_id(opts
)) != NULL
) {
2272 dinfo
->id
= qemu_strdup(buf
);
2274 /* no id supplied -> create one */
2275 dinfo
->id
= qemu_mallocz(32);
2276 if (type
== IF_IDE
|| type
== IF_SCSI
)
2277 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2279 snprintf(dinfo
->id
, 32, "%s%i%s%i",
2280 devname
, bus_id
, mediastr
, unit_id
);
2282 snprintf(dinfo
->id
, 32, "%s%s%i",
2283 devname
, mediastr
, unit_id
);
2285 dinfo
->bdrv
= bdrv_new(dinfo
->id
);
2286 dinfo
->devaddr
= devaddr
;
2288 dinfo
->bus
= bus_id
;
2289 dinfo
->unit
= unit_id
;
2290 dinfo
->onerror
= onerror
;
2293 strncpy(dinfo
->serial
, serial
, sizeof(serial
));
2294 QTAILQ_INSERT_TAIL(&drives
, dinfo
, next
);
2296 extboot_drive
= dinfo
;
2307 bdrv_set_geometry_hint(dinfo
->bdrv
, cyls
, heads
, secs
);
2308 bdrv_set_translation_hint(dinfo
->bdrv
, translation
);
2312 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_CDROM
);
2317 /* FIXME: This isn't really a floppy, but it's a reasonable
2320 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_FLOPPY
);
2326 /* add virtio block device */
2327 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
2328 qemu_opt_set(opts
, "driver", "virtio-blk-pci");
2329 qemu_opt_set(opts
, "drive", dinfo
->id
);
2331 qemu_opt_set(opts
, "addr", devaddr
);
2342 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2343 cache
= 2; /* always use write-back with snapshot */
2345 if (cache
== 0) /* no caching */
2346 bdrv_flags
|= BDRV_O_NOCACHE
;
2347 else if (cache
== 2) /* write-back */
2348 bdrv_flags
|= BDRV_O_CACHE_WB
;
2351 bdrv_flags
|= BDRV_O_NATIVE_AIO
;
2353 bdrv_flags
&= ~BDRV_O_NATIVE_AIO
;
2356 if (bdrv_open2(dinfo
->bdrv
, file
, bdrv_flags
, drv
) < 0) {
2357 fprintf(stderr
, "qemu: could not open disk image %s: %s\n",
2358 file
, strerror(errno
));
2362 if (bdrv_key_required(dinfo
->bdrv
))
2368 static int drive_init_func(QemuOpts
*opts
, void *opaque
)
2370 QEMUMachine
*machine
= opaque
;
2371 int fatal_error
= 0;
2373 if (drive_init(opts
, machine
, &fatal_error
) == NULL
) {
2380 static int drive_enable_snapshot(QemuOpts
*opts
, void *opaque
)
2382 if (NULL
== qemu_opt_get(opts
, "snapshot")) {
2383 qemu_opt_set(opts
, "snapshot", "on");
2388 void qemu_register_boot_set(QEMUBootSetHandler
*func
, void *opaque
)
2390 boot_set_handler
= func
;
2391 boot_set_opaque
= opaque
;
2394 int qemu_boot_set(const char *boot_devices
)
2396 if (!boot_set_handler
) {
2399 return boot_set_handler(boot_set_opaque
, boot_devices
);
2402 static int parse_bootdevices(char *devices
)
2404 /* We just do some generic consistency checks */
2408 for (p
= devices
; *p
!= '\0'; p
++) {
2409 /* Allowed boot devices are:
2410 * a-b: floppy disk drives
2411 * c-f: IDE disk drives
2412 * g-m: machine implementation dependant drives
2413 * n-p: network devices
2414 * It's up to each machine implementation to check if the given boot
2415 * devices match the actual hardware implementation and firmware
2418 if (*p
< 'a' || *p
> 'p') {
2419 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
2422 if (bitmap
& (1 << (*p
- 'a'))) {
2423 fprintf(stderr
, "Boot device '%c' was given twice\n", *p
);
2426 bitmap
|= 1 << (*p
- 'a');
2431 static void restore_boot_devices(void *opaque
)
2433 char *standard_boot_devices
= opaque
;
2435 qemu_boot_set(standard_boot_devices
);
2437 qemu_unregister_reset(restore_boot_devices
, standard_boot_devices
);
2438 qemu_free(standard_boot_devices
);
2441 static void numa_add(const char *optarg
)
2445 unsigned long long value
, endvalue
;
2448 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2449 if (!strcmp(option
, "node")) {
2450 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2451 nodenr
= nb_numa_nodes
;
2453 nodenr
= strtoull(option
, NULL
, 10);
2456 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2457 node_mem
[nodenr
] = 0;
2459 value
= strtoull(option
, &endptr
, 0);
2461 case 0: case 'M': case 'm':
2468 node_mem
[nodenr
] = value
;
2470 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2471 node_cpumask
[nodenr
] = 0;
2473 value
= strtoull(option
, &endptr
, 10);
2476 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2478 if (*endptr
== '-') {
2479 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2480 if (endvalue
>= 63) {
2483 "only 63 CPUs in NUMA mode supported.\n");
2485 value
= (1 << (endvalue
+ 1)) - (1 << value
);
2490 node_cpumask
[nodenr
] = value
;
2497 static void smp_parse(const char *optarg
)
2499 int smp
, sockets
= 0, threads
= 0, cores
= 0;
2503 smp
= strtoul(optarg
, &endptr
, 10);
2504 if (endptr
!= optarg
) {
2505 if (*endptr
== ',') {
2509 if (get_param_value(option
, 128, "sockets", endptr
) != 0)
2510 sockets
= strtoull(option
, NULL
, 10);
2511 if (get_param_value(option
, 128, "cores", endptr
) != 0)
2512 cores
= strtoull(option
, NULL
, 10);
2513 if (get_param_value(option
, 128, "threads", endptr
) != 0)
2514 threads
= strtoull(option
, NULL
, 10);
2515 if (get_param_value(option
, 128, "maxcpus", endptr
) != 0)
2516 max_cpus
= strtoull(option
, NULL
, 10);
2518 /* compute missing values, prefer sockets over cores over threads */
2519 if (smp
== 0 || sockets
== 0) {
2520 sockets
= sockets
> 0 ? sockets
: 1;
2521 cores
= cores
> 0 ? cores
: 1;
2522 threads
= threads
> 0 ? threads
: 1;
2524 smp
= cores
* threads
* sockets
;
2526 sockets
= smp
/ (cores
* threads
);
2530 threads
= threads
> 0 ? threads
: 1;
2531 cores
= smp
/ (sockets
* threads
);
2534 sockets
= smp
/ (cores
* threads
);
2536 threads
= smp
/ (cores
* sockets
);
2541 smp_cores
= cores
> 0 ? cores
: 1;
2542 smp_threads
= threads
> 0 ? threads
: 1;
2544 max_cpus
= smp_cpus
;
2547 /***********************************************************/
2550 static void usb_msd_password_cb(void *opaque
, int err
)
2552 USBDevice
*dev
= opaque
;
2555 usb_device_attach(dev
);
2557 dev
->info
->handle_destroy(dev
);
2566 .qdev
= "QEMU USB Mouse",
2569 .qdev
= "QEMU USB Tablet",
2572 .qdev
= "QEMU USB Keyboard",
2574 .name
= "wacom-tablet",
2575 .qdev
= "QEMU PenPartner Tablet",
2579 static int usb_device_add(const char *devname
, int is_hotplug
)
2582 USBBus
*bus
= usb_bus_find(-1 /* any */);
2583 USBDevice
*dev
= NULL
;
2589 /* simple devices which don't need extra care */
2590 for (i
= 0; i
< ARRAY_SIZE(usbdevs
); i
++) {
2591 if (strcmp(devname
, usbdevs
[i
].name
) != 0)
2593 dev
= usb_create_simple(bus
, usbdevs
[i
].qdev
);
2597 /* the other ones */
2598 if (strstart(devname
, "host:", &p
)) {
2599 dev
= usb_host_device_open(p
);
2600 } else if (strstart(devname
, "disk:", &p
)) {
2601 BlockDriverState
*bs
;
2603 dev
= usb_msd_init(p
);
2606 bs
= usb_msd_get_bdrv(dev
);
2607 if (bdrv_key_required(bs
)) {
2610 monitor_read_bdrv_key_start(cur_mon
, bs
, usb_msd_password_cb
,
2615 } else if (strstart(devname
, "serial:", &p
)) {
2616 dev
= usb_serial_init(p
);
2617 #ifdef CONFIG_BRLAPI
2618 } else if (!strcmp(devname
, "braille")) {
2619 dev
= usb_baum_init();
2621 } else if (strstart(devname
, "net:", &p
)) {
2625 opts
= qemu_opts_parse(&qemu_net_opts
, p
, NULL
);
2630 qemu_opt_set(opts
, "type", "nic");
2631 qemu_opt_set(opts
, "model", "usb");
2633 idx
= net_client_init(NULL
, opts
, 0);
2638 dev
= usb_net_init(&nd_table
[idx
]);
2639 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2640 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2641 bt_new_hci(qemu_find_bt_vlan(0)));
2652 static int usb_device_del(const char *devname
)
2657 if (strstart(devname
, "host:", &p
))
2658 return usb_host_device_close(p
);
2663 p
= strchr(devname
, '.');
2666 bus_num
= strtoul(devname
, NULL
, 0);
2667 addr
= strtoul(p
+ 1, NULL
, 0);
2669 return usb_device_delete_addr(bus_num
, addr
);
2672 static int usb_parse(const char *cmdline
)
2674 return usb_device_add(cmdline
, 0);
2677 void do_usb_add(Monitor
*mon
, const QDict
*qdict
)
2679 usb_device_add(qdict_get_str(qdict
, "devname"), 1);
2682 void do_usb_del(Monitor
*mon
, const QDict
*qdict
)
2684 usb_device_del(qdict_get_str(qdict
, "devname"));
2687 /***********************************************************/
2688 /* PCMCIA/Cardbus */
2690 static struct pcmcia_socket_entry_s
{
2691 PCMCIASocket
*socket
;
2692 struct pcmcia_socket_entry_s
*next
;
2693 } *pcmcia_sockets
= 0;
2695 void pcmcia_socket_register(PCMCIASocket
*socket
)
2697 struct pcmcia_socket_entry_s
*entry
;
2699 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2700 entry
->socket
= socket
;
2701 entry
->next
= pcmcia_sockets
;
2702 pcmcia_sockets
= entry
;
2705 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2707 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2709 ptr
= &pcmcia_sockets
;
2710 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2711 if (entry
->socket
== socket
) {
2717 void pcmcia_info(Monitor
*mon
)
2719 struct pcmcia_socket_entry_s
*iter
;
2721 if (!pcmcia_sockets
)
2722 monitor_printf(mon
, "No PCMCIA sockets\n");
2724 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2725 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2726 iter
->socket
->attached
? iter
->socket
->card_string
:
2730 /***********************************************************/
2731 /* register display */
2733 struct DisplayAllocator default_allocator
= {
2734 defaultallocator_create_displaysurface
,
2735 defaultallocator_resize_displaysurface
,
2736 defaultallocator_free_displaysurface
2739 void register_displaystate(DisplayState
*ds
)
2749 DisplayState
*get_displaystate(void)
2751 return display_state
;
2754 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
2756 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
2757 return ds
->allocator
;
2762 static void dumb_display_init(void)
2764 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
2765 ds
->allocator
= &default_allocator
;
2766 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
2767 register_displaystate(ds
);
2770 /***********************************************************/
2773 typedef struct IOHandlerRecord
{
2775 IOCanRWHandler
*fd_read_poll
;
2777 IOHandler
*fd_write
;
2780 /* temporary data */
2782 struct IOHandlerRecord
*next
;
2785 static IOHandlerRecord
*first_io_handler
;
2787 /* XXX: fd_read_poll should be suppressed, but an API change is
2788 necessary in the character devices to suppress fd_can_read(). */
2789 int qemu_set_fd_handler2(int fd
,
2790 IOCanRWHandler
*fd_read_poll
,
2792 IOHandler
*fd_write
,
2795 IOHandlerRecord
**pioh
, *ioh
;
2797 if (!fd_read
&& !fd_write
) {
2798 pioh
= &first_io_handler
;
2803 if (ioh
->fd
== fd
) {
2810 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
2814 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
2815 ioh
->next
= first_io_handler
;
2816 first_io_handler
= ioh
;
2819 ioh
->fd_read_poll
= fd_read_poll
;
2820 ioh
->fd_read
= fd_read
;
2821 ioh
->fd_write
= fd_write
;
2822 ioh
->opaque
= opaque
;
2825 qemu_notify_event();
2829 int qemu_set_fd_handler(int fd
,
2831 IOHandler
*fd_write
,
2834 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
2838 /***********************************************************/
2839 /* Polling handling */
2841 typedef struct PollingEntry
{
2844 struct PollingEntry
*next
;
2847 static PollingEntry
*first_polling_entry
;
2849 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
2851 PollingEntry
**ppe
, *pe
;
2852 pe
= qemu_mallocz(sizeof(PollingEntry
));
2854 pe
->opaque
= opaque
;
2855 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
2860 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
2862 PollingEntry
**ppe
, *pe
;
2863 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
2865 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
2873 /***********************************************************/
2874 /* Wait objects support */
2875 typedef struct WaitObjects
{
2877 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
2878 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
2879 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
2882 static WaitObjects wait_objects
= {0};
2884 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2886 WaitObjects
*w
= &wait_objects
;
2888 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
2890 w
->events
[w
->num
] = handle
;
2891 w
->func
[w
->num
] = func
;
2892 w
->opaque
[w
->num
] = opaque
;
2897 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2900 WaitObjects
*w
= &wait_objects
;
2903 for (i
= 0; i
< w
->num
; i
++) {
2904 if (w
->events
[i
] == handle
)
2907 w
->events
[i
] = w
->events
[i
+ 1];
2908 w
->func
[i
] = w
->func
[i
+ 1];
2909 w
->opaque
[i
] = w
->opaque
[i
+ 1];
2917 /***********************************************************/
2918 /* ram save/restore */
2920 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2921 #define RAM_SAVE_FLAG_COMPRESS 0x02
2922 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2923 #define RAM_SAVE_FLAG_PAGE 0x08
2924 #define RAM_SAVE_FLAG_EOS 0x10
2926 static int is_dup_page(uint8_t *page
, uint8_t ch
)
2928 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
2929 uint32_t *array
= (uint32_t *)page
;
2932 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
2933 if (array
[i
] != val
)
2940 static int ram_save_block(QEMUFile
*f
)
2942 static ram_addr_t current_addr
= 0;
2943 ram_addr_t saved_addr
= current_addr
;
2944 ram_addr_t addr
= 0;
2947 while (addr
< last_ram_offset
) {
2948 if (kvm_enabled() && current_addr
== 0) {
2950 r
= kvm_update_dirty_pages_log();
2952 fprintf(stderr
, "%s: update dirty pages log failed %d\n", __FUNCTION__
, r
);
2953 qemu_file_set_error(f
);
2957 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
2960 cpu_physical_memory_reset_dirty(current_addr
,
2961 current_addr
+ TARGET_PAGE_SIZE
,
2962 MIGRATION_DIRTY_FLAG
);
2964 p
= qemu_get_ram_ptr(current_addr
);
2966 if (is_dup_page(p
, *p
)) {
2967 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
2968 qemu_put_byte(f
, *p
);
2970 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
2971 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
2977 addr
+= TARGET_PAGE_SIZE
;
2978 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
2984 static uint64_t bytes_transferred
= 0;
2986 static ram_addr_t
ram_save_remaining(void)
2989 ram_addr_t count
= 0;
2991 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2992 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2999 uint64_t ram_bytes_remaining(void)
3001 return ram_save_remaining() * TARGET_PAGE_SIZE
;
3004 uint64_t ram_bytes_transferred(void)
3006 return bytes_transferred
;
3009 uint64_t ram_bytes_total(void)
3011 return last_ram_offset
;
3014 static int ram_save_live(QEMUFile
*f
, int stage
, void *opaque
)
3017 uint64_t bytes_transferred_last
;
3019 uint64_t expected_time
= 0;
3021 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX
) != 0) {
3022 qemu_file_set_error(f
);
3027 /* Make sure all dirty bits are set */
3028 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3029 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3030 cpu_physical_memory_set_dirty(addr
);
3033 /* Enable dirty memory tracking */
3034 cpu_physical_memory_set_dirty_tracking(1);
3036 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
3039 bytes_transferred_last
= bytes_transferred
;
3040 bwidth
= get_clock();
3042 while (!qemu_file_rate_limit(f
)) {
3045 ret
= ram_save_block(f
);
3046 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
3047 if (ret
== 0) /* no more blocks */
3051 bwidth
= get_clock() - bwidth
;
3052 bwidth
= (bytes_transferred
- bytes_transferred_last
) / bwidth
;
3054 /* if we haven't transferred anything this round, force expected_time to a
3055 * a very high value, but without crashing */
3059 /* try transferring iterative blocks of memory */
3063 /* flush all remaining blocks regardless of rate limiting */
3064 while (ram_save_block(f
) != 0) {
3065 bytes_transferred
+= TARGET_PAGE_SIZE
;
3067 cpu_physical_memory_set_dirty_tracking(0);
3070 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3072 expected_time
= ram_save_remaining() * TARGET_PAGE_SIZE
/ bwidth
;
3074 return (stage
== 2) && (expected_time
<= migrate_max_downtime());
3077 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
3082 if (version_id
!= 3)
3086 addr
= qemu_get_be64(f
);
3088 flags
= addr
& ~TARGET_PAGE_MASK
;
3089 addr
&= TARGET_PAGE_MASK
;
3091 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
3092 if (addr
!= last_ram_offset
)
3096 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
3097 uint8_t ch
= qemu_get_byte(f
);
3098 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
3101 (!kvm_enabled() || kvm_has_sync_mmu())) {
3102 madvise(qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
, MADV_DONTNEED
);
3105 } else if (flags
& RAM_SAVE_FLAG_PAGE
)
3106 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
3107 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
3112 void qemu_service_io(void)
3114 qemu_notify_event();
3117 /***********************************************************/
3118 /* bottom halves (can be seen as timers which expire ASAP) */
3129 static QEMUBH
*first_bh
= NULL
;
3131 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
3134 bh
= qemu_mallocz(sizeof(QEMUBH
));
3136 bh
->opaque
= opaque
;
3137 bh
->next
= first_bh
;
3142 int qemu_bh_poll(void)
3148 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3149 if (!bh
->deleted
&& bh
->scheduled
) {
3158 /* remove deleted bhs */
3172 void qemu_bh_schedule_idle(QEMUBH
*bh
)
3180 void qemu_bh_schedule(QEMUBH
*bh
)
3186 /* stop the currently executing CPU to execute the BH ASAP */
3187 qemu_notify_event();
3190 void qemu_bh_cancel(QEMUBH
*bh
)
3195 void qemu_bh_delete(QEMUBH
*bh
)
3201 static void qemu_bh_update_timeout(int *timeout
)
3205 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3206 if (!bh
->deleted
&& bh
->scheduled
) {
3208 /* idle bottom halves will be polled at least
3210 *timeout
= MIN(10, *timeout
);
3212 /* non-idle bottom halves will be executed
3221 /***********************************************************/
3222 /* machine registration */
3224 static QEMUMachine
*first_machine
= NULL
;
3225 QEMUMachine
*current_machine
= NULL
;
3227 int qemu_register_machine(QEMUMachine
*m
)
3230 pm
= &first_machine
;
3238 static QEMUMachine
*find_machine(const char *name
)
3242 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3243 if (!strcmp(m
->name
, name
))
3245 if (m
->alias
&& !strcmp(m
->alias
, name
))
3251 static QEMUMachine
*find_default_machine(void)
3255 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3256 if (m
->is_default
) {
3263 /***********************************************************/
3264 /* main execution loop */
3266 static void gui_update(void *opaque
)
3268 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3269 DisplayState
*ds
= opaque
;
3270 DisplayChangeListener
*dcl
= ds
->listeners
;
3274 while (dcl
!= NULL
) {
3275 if (dcl
->gui_timer_interval
&&
3276 dcl
->gui_timer_interval
< interval
)
3277 interval
= dcl
->gui_timer_interval
;
3280 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3283 static void nographic_update(void *opaque
)
3285 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3287 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3290 struct vm_change_state_entry
{
3291 VMChangeStateHandler
*cb
;
3293 QLIST_ENTRY (vm_change_state_entry
) entries
;
3296 static QLIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3298 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3301 VMChangeStateEntry
*e
;
3303 e
= qemu_mallocz(sizeof (*e
));
3307 QLIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3311 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3313 QLIST_REMOVE (e
, entries
);
3317 static void vm_state_notify(int running
, int reason
)
3319 VMChangeStateEntry
*e
;
3321 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3322 e
->cb(e
->opaque
, running
, reason
);
3326 static void resume_all_vcpus(void);
3327 static void pause_all_vcpus(void);
3334 vm_state_notify(1, 0);
3335 qemu_rearm_alarm_timer(alarm_timer
);
3340 /* reset/shutdown handler */
3342 typedef struct QEMUResetEntry
{
3343 QTAILQ_ENTRY(QEMUResetEntry
) entry
;
3344 QEMUResetHandler
*func
;
3348 static QTAILQ_HEAD(reset_handlers
, QEMUResetEntry
) reset_handlers
=
3349 QTAILQ_HEAD_INITIALIZER(reset_handlers
);
3350 static int reset_requested
;
3351 static int shutdown_requested
;
3352 static int powerdown_requested
;
3353 static int debug_requested
;
3354 static int vmstop_requested
;
3356 int qemu_no_shutdown(void)
3358 int r
= no_shutdown
;
3363 int qemu_shutdown_requested(void)
3365 int r
= shutdown_requested
;
3366 shutdown_requested
= 0;
3370 int qemu_reset_requested(void)
3372 int r
= reset_requested
;
3373 reset_requested
= 0;
3377 int qemu_powerdown_requested(void)
3379 int r
= powerdown_requested
;
3380 powerdown_requested
= 0;
3384 static int qemu_debug_requested(void)
3386 int r
= debug_requested
;
3387 debug_requested
= 0;
3391 static int qemu_vmstop_requested(void)
3393 int r
= vmstop_requested
;
3394 vmstop_requested
= 0;
3398 static void do_vm_stop(int reason
)
3401 cpu_disable_ticks();
3404 vm_state_notify(0, reason
);
3408 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3410 QEMUResetEntry
*re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3413 re
->opaque
= opaque
;
3414 QTAILQ_INSERT_TAIL(&reset_handlers
, re
, entry
);
3417 void qemu_unregister_reset(QEMUResetHandler
*func
, void *opaque
)
3421 QTAILQ_FOREACH(re
, &reset_handlers
, entry
) {
3422 if (re
->func
== func
&& re
->opaque
== opaque
) {
3423 QTAILQ_REMOVE(&reset_handlers
, re
, entry
);
3430 void qemu_system_reset(void)
3432 QEMUResetEntry
*re
, *nre
;
3434 /* reset all devices */
3435 QTAILQ_FOREACH_SAFE(re
, &reset_handlers
, entry
, nre
) {
3436 re
->func(re
->opaque
);
3440 void qemu_system_reset_request(void)
3443 shutdown_requested
= 1;
3445 reset_requested
= 1;
3447 if (cpu_single_env
) {
3448 cpu_single_env
->stopped
= 1;
3450 qemu_notify_event();
3453 void qemu_system_shutdown_request(void)
3455 shutdown_requested
= 1;
3456 qemu_notify_event();
3459 void qemu_system_powerdown_request(void)
3461 powerdown_requested
= 1;
3462 qemu_notify_event();
3465 #ifdef CONFIG_IOTHREAD
3466 static void qemu_system_vmstop_request(int reason
)
3468 vmstop_requested
= reason
;
3469 qemu_notify_event();
3474 static int io_thread_fd
= -1;
3476 static void qemu_event_increment(void)
3478 static const char byte
= 0;
3480 if (io_thread_fd
== -1)
3483 write(io_thread_fd
, &byte
, sizeof(byte
));
3486 static void qemu_event_read(void *opaque
)
3488 int fd
= (unsigned long)opaque
;
3491 /* Drain the notify pipe */
3494 len
= read(fd
, buffer
, sizeof(buffer
));
3495 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
3498 static int qemu_event_init(void)
3507 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3511 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3515 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3516 (void *)(unsigned long)fds
[0]);
3518 io_thread_fd
= fds
[1];
3527 HANDLE qemu_event_handle
;
3529 static void dummy_event_handler(void *opaque
)
3533 static int qemu_event_init(void)
3535 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3536 if (!qemu_event_handle
) {
3537 fprintf(stderr
, "Failed CreateEvent: %ld\n", GetLastError());
3540 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3544 static void qemu_event_increment(void)
3546 if (!SetEvent(qemu_event_handle
)) {
3547 fprintf(stderr
, "qemu_event_increment: SetEvent failed: %ld\n",
3554 static int cpu_can_run(CPUState
*env
)
3563 #ifndef CONFIG_IOTHREAD
3564 static int qemu_init_main_loop(void)
3566 return qemu_event_init();
3569 void qemu_init_vcpu(void *_env
)
3571 CPUState
*env
= _env
;
3575 env
->nr_cores
= smp_cores
;
3576 env
->nr_threads
= smp_threads
;
3580 int qemu_cpu_self(void *env
)
3585 static void resume_all_vcpus(void)
3589 static void pause_all_vcpus(void)
3593 void qemu_cpu_kick(void *env
)
3598 void qemu_notify_event(void)
3600 CPUState
*env
= cpu_single_env
;
3602 if (kvm_enabled()) {
3603 qemu_kvm_notify_work();
3612 void qemu_mutex_lock_iothread(void) {}
3613 void qemu_mutex_unlock_iothread(void) {}
3616 void vm_stop(int reason
)
3621 #else /* CONFIG_IOTHREAD */
3623 #include "qemu-thread.h"
3625 QemuMutex qemu_global_mutex
;
3626 static QemuMutex qemu_fair_mutex
;
3628 static QemuThread io_thread
;
3630 static QemuThread
*tcg_cpu_thread
;
3631 static QemuCond
*tcg_halt_cond
;
3633 static int qemu_system_ready
;
3635 static QemuCond qemu_cpu_cond
;
3637 static QemuCond qemu_system_cond
;
3638 static QemuCond qemu_pause_cond
;
3640 static void block_io_signals(void);
3641 static void unblock_io_signals(void);
3642 static int tcg_has_work(void);
3644 static int qemu_init_main_loop(void)
3648 ret
= qemu_event_init();
3652 qemu_cond_init(&qemu_pause_cond
);
3653 qemu_mutex_init(&qemu_fair_mutex
);
3654 qemu_mutex_init(&qemu_global_mutex
);
3655 qemu_mutex_lock(&qemu_global_mutex
);
3657 unblock_io_signals();
3658 qemu_thread_self(&io_thread
);
3663 static void qemu_wait_io_event(CPUState
*env
)
3665 while (!tcg_has_work())
3666 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3668 qemu_mutex_unlock(&qemu_global_mutex
);
3671 * Users of qemu_global_mutex can be starved, having no chance
3672 * to acquire it since this path will get to it first.
3673 * So use another lock to provide fairness.
3675 qemu_mutex_lock(&qemu_fair_mutex
);
3676 qemu_mutex_unlock(&qemu_fair_mutex
);
3678 qemu_mutex_lock(&qemu_global_mutex
);
3682 qemu_cond_signal(&qemu_pause_cond
);
3686 static int qemu_cpu_exec(CPUState
*env
);
3688 static void *kvm_cpu_thread_fn(void *arg
)
3690 CPUState
*env
= arg
;
3693 qemu_thread_self(env
->thread
);
3697 /* signal CPU creation */
3698 qemu_mutex_lock(&qemu_global_mutex
);
3700 qemu_cond_signal(&qemu_cpu_cond
);
3702 /* and wait for machine initialization */
3703 while (!qemu_system_ready
)
3704 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3707 if (cpu_can_run(env
))
3709 qemu_wait_io_event(env
);
3715 static void tcg_cpu_exec(void);
3717 static void *tcg_cpu_thread_fn(void *arg
)
3719 CPUState
*env
= arg
;
3722 qemu_thread_self(env
->thread
);
3724 /* signal CPU creation */
3725 qemu_mutex_lock(&qemu_global_mutex
);
3726 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
3728 qemu_cond_signal(&qemu_cpu_cond
);
3730 /* and wait for machine initialization */
3731 while (!qemu_system_ready
)
3732 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3736 qemu_wait_io_event(cur_cpu
);
3742 void qemu_cpu_kick(void *_env
)
3744 CPUState
*env
= _env
;
3745 qemu_cond_broadcast(env
->halt_cond
);
3747 qemu_thread_signal(env
->thread
, SIGUSR1
);
3750 int qemu_cpu_self(void *_env
)
3752 CPUState
*env
= _env
;
3755 qemu_thread_self(&this);
3757 return qemu_thread_equal(&this, env
->thread
);
3760 static void cpu_signal(int sig
)
3763 cpu_exit(cpu_single_env
);
3766 static void block_io_signals(void)
3769 struct sigaction sigact
;
3772 sigaddset(&set
, SIGUSR2
);
3773 sigaddset(&set
, SIGIO
);
3774 sigaddset(&set
, SIGALRM
);
3775 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3778 sigaddset(&set
, SIGUSR1
);
3779 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3781 memset(&sigact
, 0, sizeof(sigact
));
3782 sigact
.sa_handler
= cpu_signal
;
3783 sigaction(SIGUSR1
, &sigact
, NULL
);
3786 static void unblock_io_signals(void)
3791 sigaddset(&set
, SIGUSR2
);
3792 sigaddset(&set
, SIGIO
);
3793 sigaddset(&set
, SIGALRM
);
3794 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3797 sigaddset(&set
, SIGUSR1
);
3798 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3801 static void qemu_signal_lock(unsigned int msecs
)
3803 qemu_mutex_lock(&qemu_fair_mutex
);
3805 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
3806 qemu_thread_signal(tcg_cpu_thread
, SIGUSR1
);
3807 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
3810 qemu_mutex_unlock(&qemu_fair_mutex
);
3813 void qemu_mutex_lock_iothread(void)
3815 if (kvm_enabled()) {
3816 qemu_mutex_lock(&qemu_fair_mutex
);
3817 qemu_mutex_lock(&qemu_global_mutex
);
3818 qemu_mutex_unlock(&qemu_fair_mutex
);
3820 qemu_signal_lock(100);
3823 void qemu_mutex_unlock_iothread(void)
3825 qemu_mutex_unlock(&qemu_global_mutex
);
3828 static int all_vcpus_paused(void)
3830 CPUState
*penv
= first_cpu
;
3835 penv
= (CPUState
*)penv
->next_cpu
;
3841 static void pause_all_vcpus(void)
3843 CPUState
*penv
= first_cpu
;
3847 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3848 qemu_cpu_kick(penv
);
3849 penv
= (CPUState
*)penv
->next_cpu
;
3852 while (!all_vcpus_paused()) {
3853 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
3856 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3857 penv
= (CPUState
*)penv
->next_cpu
;
3862 static void resume_all_vcpus(void)
3864 CPUState
*penv
= first_cpu
;
3869 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3870 qemu_cpu_kick(penv
);
3871 penv
= (CPUState
*)penv
->next_cpu
;
3875 static void tcg_init_vcpu(void *_env
)
3877 CPUState
*env
= _env
;
3878 /* share a single thread for all cpus with TCG */
3879 if (!tcg_cpu_thread
) {
3880 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3881 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3882 qemu_cond_init(env
->halt_cond
);
3883 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
3884 while (env
->created
== 0)
3885 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3886 tcg_cpu_thread
= env
->thread
;
3887 tcg_halt_cond
= env
->halt_cond
;
3889 env
->thread
= tcg_cpu_thread
;
3890 env
->halt_cond
= tcg_halt_cond
;
3894 static void kvm_start_vcpu(CPUState
*env
)
3896 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3897 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3898 qemu_cond_init(env
->halt_cond
);
3899 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
3900 while (env
->created
== 0)
3901 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3904 void qemu_init_vcpu(void *_env
)
3906 CPUState
*env
= _env
;
3909 kvm_start_vcpu(env
);
3912 env
->nr_cores
= smp_cores
;
3913 env
->nr_threads
= smp_threads
;
3916 void qemu_notify_event(void)
3918 qemu_event_increment();
3921 void vm_stop(int reason
)
3924 qemu_thread_self(&me
);
3926 if (!qemu_thread_equal(&me
, &io_thread
)) {
3927 qemu_system_vmstop_request(reason
);
3929 * FIXME: should not return to device code in case
3930 * vm_stop() has been requested.
3932 if (cpu_single_env
) {
3933 cpu_exit(cpu_single_env
);
3934 cpu_single_env
->stop
= 1;
3945 static void host_main_loop_wait(int *timeout
)
3951 /* XXX: need to suppress polling by better using win32 events */
3953 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
3954 ret
|= pe
->func(pe
->opaque
);
3958 WaitObjects
*w
= &wait_objects
;
3960 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
3961 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
3962 if (w
->func
[ret
- WAIT_OBJECT_0
])
3963 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
3965 /* Check for additional signaled events */
3966 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
3968 /* Check if event is signaled */
3969 ret2
= WaitForSingleObject(w
->events
[i
], 0);
3970 if(ret2
== WAIT_OBJECT_0
) {
3972 w
->func
[i
](w
->opaque
[i
]);
3973 } else if (ret2
== WAIT_TIMEOUT
) {
3975 err
= GetLastError();
3976 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
3979 } else if (ret
== WAIT_TIMEOUT
) {
3981 err
= GetLastError();
3982 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
3989 static void host_main_loop_wait(int *timeout
)
3994 void main_loop_wait(int timeout
)
3996 IOHandlerRecord
*ioh
;
3997 fd_set rfds
, wfds
, xfds
;
4001 qemu_bh_update_timeout(&timeout
);
4003 host_main_loop_wait(&timeout
);
4005 /* poll any events */
4006 /* XXX: separate device handlers from system ones */
4011 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4015 (!ioh
->fd_read_poll
||
4016 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
4017 FD_SET(ioh
->fd
, &rfds
);
4021 if (ioh
->fd_write
) {
4022 FD_SET(ioh
->fd
, &wfds
);
4028 tv
.tv_sec
= timeout
/ 1000;
4029 tv
.tv_usec
= (timeout
% 1000) * 1000;
4031 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
4033 qemu_mutex_unlock_iothread();
4034 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
4035 qemu_mutex_lock_iothread();
4037 IOHandlerRecord
**pioh
;
4039 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4040 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
4041 ioh
->fd_read(ioh
->opaque
);
4042 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
4043 FD_CLR(ioh
->fd
, &rfds
);
4045 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
4046 ioh
->fd_write(ioh
->opaque
);
4050 /* remove deleted IO handlers */
4051 pioh
= &first_io_handler
;
4062 slirp_select_poll(&rfds
, &wfds
, &xfds
, (ret
< 0));
4064 /* rearm timer, if not periodic */
4065 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
4066 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
4067 qemu_rearm_alarm_timer(alarm_timer
);
4070 /* vm time timers */
4072 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
4073 qemu_run_timers(&active_timers
[QEMU_CLOCK_VIRTUAL
],
4074 qemu_get_clock(vm_clock
));
4077 /* real time timers */
4078 qemu_run_timers(&active_timers
[QEMU_CLOCK_REALTIME
],
4079 qemu_get_clock(rt_clock
));
4081 qemu_run_timers(&active_timers
[QEMU_CLOCK_HOST
],
4082 qemu_get_clock(host_clock
));
4084 /* Check bottom-halves last in case any of the earlier events triggered
4090 static int qemu_cpu_exec(CPUState
*env
)
4093 #ifdef CONFIG_PROFILER
4097 #ifdef CONFIG_PROFILER
4098 ti
= profile_getclock();
4103 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
4104 env
->icount_decr
.u16
.low
= 0;
4105 env
->icount_extra
= 0;
4106 count
= qemu_next_deadline();
4107 count
= (count
+ (1 << icount_time_shift
) - 1)
4108 >> icount_time_shift
;
4109 qemu_icount
+= count
;
4110 decr
= (count
> 0xffff) ? 0xffff : count
;
4112 env
->icount_decr
.u16
.low
= decr
;
4113 env
->icount_extra
= count
;
4115 ret
= cpu_exec(env
);
4116 #ifdef CONFIG_PROFILER
4117 qemu_time
+= profile_getclock() - ti
;
4120 /* Fold pending instructions back into the
4121 instruction counter, and clear the interrupt flag. */
4122 qemu_icount
-= (env
->icount_decr
.u16
.low
4123 + env
->icount_extra
);
4124 env
->icount_decr
.u32
= 0;
4125 env
->icount_extra
= 0;
4130 static void tcg_cpu_exec(void)
4134 if (next_cpu
== NULL
)
4135 next_cpu
= first_cpu
;
4136 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
4137 CPUState
*env
= cur_cpu
= next_cpu
;
4141 if (timer_alarm_pending
) {
4142 timer_alarm_pending
= 0;
4145 if (cpu_can_run(env
))
4146 ret
= qemu_cpu_exec(env
);
4147 if (ret
== EXCP_DEBUG
) {
4148 gdb_set_stop_cpu(env
);
4149 debug_requested
= 1;
4155 static int cpu_has_work(CPUState
*env
)
4163 if (qemu_cpu_has_work(env
))
4168 static int tcg_has_work(void)
4172 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4173 if (cpu_has_work(env
))
4178 static int qemu_calculate_timeout(void)
4180 #ifndef CONFIG_IOTHREAD
4185 else if (tcg_has_work())
4187 else if (!use_icount
)
4190 /* XXX: use timeout computed from timers */
4193 /* Advance virtual time to the next event. */
4194 if (use_icount
== 1) {
4195 /* When not using an adaptive execution frequency
4196 we tend to get badly out of sync with real time,
4197 so just delay for a reasonable amount of time. */
4200 delta
= cpu_get_icount() - cpu_get_clock();
4203 /* If virtual time is ahead of real time then just
4205 timeout
= (delta
/ 1000000) + 1;
4207 /* Wait for either IO to occur or the next
4209 add
= qemu_next_deadline();
4210 /* We advance the timer before checking for IO.
4211 Limit the amount we advance so that early IO
4212 activity won't get the guest too far ahead. */
4216 add
= (add
+ (1 << icount_time_shift
) - 1)
4217 >> icount_time_shift
;
4219 timeout
= delta
/ 1000000;
4226 #else /* CONFIG_IOTHREAD */
4231 static int vm_can_run(void)
4233 if (powerdown_requested
)
4235 if (reset_requested
)
4237 if (shutdown_requested
)
4239 if (debug_requested
)
4244 qemu_irq qemu_system_powerdown
;
4246 static void main_loop(void)
4250 if (kvm_enabled()) {
4252 cpu_disable_ticks();
4256 #ifdef CONFIG_IOTHREAD
4257 qemu_system_ready
= 1;
4258 qemu_cond_broadcast(&qemu_system_cond
);
4263 #ifdef CONFIG_PROFILER
4266 #ifndef CONFIG_IOTHREAD
4269 #ifdef CONFIG_PROFILER
4270 ti
= profile_getclock();
4272 main_loop_wait(qemu_calculate_timeout());
4273 #ifdef CONFIG_PROFILER
4274 dev_time
+= profile_getclock() - ti
;
4276 } while (vm_can_run());
4278 if (qemu_debug_requested())
4279 vm_stop(EXCP_DEBUG
);
4280 if (qemu_shutdown_requested()) {
4287 if (qemu_reset_requested()) {
4289 qemu_system_reset();
4292 if (qemu_powerdown_requested()) {
4293 qemu_irq_raise(qemu_system_powerdown
);
4295 if ((r
= qemu_vmstop_requested()))
4301 static void version(void)
4303 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4306 static void help(int exitcode
)
4309 printf("usage: %s [options] [disk_image]\n"
4311 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4313 #define DEF(option, opt_arg, opt_enum, opt_help) \
4315 #define DEFHEADING(text) stringify(text) "\n"
4316 #include "qemu-options.h"
4321 "During emulation, the following keys are useful:\n"
4322 "ctrl-alt-f toggle full screen\n"
4323 "ctrl-alt-n switch to virtual console 'n'\n"
4324 "ctrl-alt toggle mouse and keyboard grab\n"
4326 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4331 DEFAULT_NETWORK_SCRIPT
,
4332 DEFAULT_NETWORK_DOWN_SCRIPT
,
4334 DEFAULT_GDBSTUB_PORT
,
4339 #define HAS_ARG 0x0001
4342 #define DEF(option, opt_arg, opt_enum, opt_help) \
4344 #define DEFHEADING(text)
4345 #include "qemu-options.h"
4351 typedef struct QEMUOption
{
4357 static const QEMUOption qemu_options
[] = {
4358 { "h", 0, QEMU_OPTION_h
},
4359 #define DEF(option, opt_arg, opt_enum, opt_help) \
4360 { option, opt_arg, opt_enum },
4361 #define DEFHEADING(text)
4362 #include "qemu-options.h"
4370 struct soundhw soundhw
[] = {
4371 #ifdef HAS_AUDIO_CHOICE
4372 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4378 { .init_isa
= pcspk_audio_init
}
4385 "Creative Sound Blaster 16",
4388 { .init_isa
= SB16_init
}
4392 #ifdef CONFIG_CS4231A
4398 { .init_isa
= cs4231a_init
}
4406 "Yamaha YMF262 (OPL3)",
4408 "Yamaha YM3812 (OPL2)",
4412 { .init_isa
= Adlib_init
}
4419 "Gravis Ultrasound GF1",
4422 { .init_isa
= GUS_init
}
4429 "Intel 82801AA AC97 Audio",
4432 { .init_pci
= ac97_init
}
4436 #ifdef CONFIG_ES1370
4439 "ENSONIQ AudioPCI ES1370",
4442 { .init_pci
= es1370_init
}
4446 #endif /* HAS_AUDIO_CHOICE */
4448 { NULL
, NULL
, 0, 0, { NULL
} }
4451 static void select_soundhw (const char *optarg
)
4455 if (*optarg
== '?') {
4458 printf ("Valid sound card names (comma separated):\n");
4459 for (c
= soundhw
; c
->name
; ++c
) {
4460 printf ("%-11s %s\n", c
->name
, c
->descr
);
4462 printf ("\n-soundhw all will enable all of the above\n");
4463 exit (*optarg
!= '?');
4471 if (!strcmp (optarg
, "all")) {
4472 for (c
= soundhw
; c
->name
; ++c
) {
4480 e
= strchr (p
, ',');
4481 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4483 for (c
= soundhw
; c
->name
; ++c
) {
4484 if (!strncmp (c
->name
, p
, l
) && !c
->name
[l
]) {
4493 "Unknown sound card name (too big to show)\n");
4496 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4501 p
+= l
+ (e
!= NULL
);
4505 goto show_valid_cards
;
4510 static void select_vgahw (const char *p
)
4514 vga_interface_type
= VGA_NONE
;
4515 if (strstart(p
, "std", &opts
)) {
4516 vga_interface_type
= VGA_STD
;
4517 } else if (strstart(p
, "cirrus", &opts
)) {
4518 vga_interface_type
= VGA_CIRRUS
;
4519 } else if (strstart(p
, "vmware", &opts
)) {
4520 vga_interface_type
= VGA_VMWARE
;
4521 } else if (strstart(p
, "xenfb", &opts
)) {
4522 vga_interface_type
= VGA_XENFB
;
4523 } else if (!strstart(p
, "none", &opts
)) {
4525 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4529 const char *nextopt
;
4531 if (strstart(opts
, ",retrace=", &nextopt
)) {
4533 if (strstart(opts
, "dumb", &nextopt
))
4534 vga_retrace_method
= VGA_RETRACE_DUMB
;
4535 else if (strstart(opts
, "precise", &nextopt
))
4536 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4537 else goto invalid_vga
;
4538 } else goto invalid_vga
;
4544 static int balloon_parse(const char *arg
)
4548 if (strcmp(arg
, "none") == 0) {
4552 if (!strncmp(arg
, "virtio", 6)) {
4553 if (arg
[6] == ',') {
4554 /* have params -> parse them */
4555 opts
= qemu_opts_parse(&qemu_device_opts
, arg
+7, NULL
);
4559 /* create empty opts */
4560 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4562 qemu_opt_set(opts
, "driver", "virtio-balloon-pci");
4571 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4573 exit(STATUS_CONTROL_C_EXIT
);
4578 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4582 if(strlen(str
) != 36)
4585 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4586 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4587 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4593 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4601 static void termsig_handler(int signal
)
4603 qemu_system_shutdown_request();
4606 static void sigchld_handler(int signal
)
4608 waitpid(-1, NULL
, WNOHANG
);
4611 static void sighandler_setup(void)
4613 struct sigaction act
;
4615 memset(&act
, 0, sizeof(act
));
4616 act
.sa_handler
= termsig_handler
;
4617 sigaction(SIGINT
, &act
, NULL
);
4618 sigaction(SIGHUP
, &act
, NULL
);
4619 sigaction(SIGTERM
, &act
, NULL
);
4621 act
.sa_handler
= sigchld_handler
;
4622 act
.sa_flags
= SA_NOCLDSTOP
;
4623 sigaction(SIGCHLD
, &act
, NULL
);
4629 /* Look for support files in the same directory as the executable. */
4630 static char *find_datadir(const char *argv0
)
4636 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
4643 while (p
!= buf
&& *p
!= '\\')
4646 if (access(buf
, R_OK
) == 0) {
4647 return qemu_strdup(buf
);
4653 /* Find a likely location for support files using the location of the binary.
4654 For installed binaries this will be "$bindir/../share/qemu". When
4655 running from the build tree this will be "$bindir/../pc-bios". */
4656 #define SHARE_SUFFIX "/share/qemu"
4657 #define BUILD_SUFFIX "/pc-bios"
4658 static char *find_datadir(const char *argv0
)
4666 #if defined(__linux__)
4669 len
= readlink("/proc/self/exe", buf
, sizeof(buf
) - 1);
4675 #elif defined(__FreeBSD__)
4678 len
= readlink("/proc/curproc/file", buf
, sizeof(buf
) - 1);
4685 /* If we don't have any way of figuring out the actual executable
4686 location then try argv[0]. */
4688 p
= realpath(argv0
, buf
);
4696 max_len
= strlen(dir
) +
4697 MAX(strlen(SHARE_SUFFIX
), strlen(BUILD_SUFFIX
)) + 1;
4698 res
= qemu_mallocz(max_len
);
4699 snprintf(res
, max_len
, "%s%s", dir
, SHARE_SUFFIX
);
4700 if (access(res
, R_OK
)) {
4701 snprintf(res
, max_len
, "%s%s", dir
, BUILD_SUFFIX
);
4702 if (access(res
, R_OK
)) {
4714 char *qemu_find_file(int type
, const char *name
)
4720 /* If name contains path separators then try it as a straight path. */
4721 if ((strchr(name
, '/') || strchr(name
, '\\'))
4722 && access(name
, R_OK
) == 0) {
4723 return qemu_strdup(name
);
4726 case QEMU_FILE_TYPE_BIOS
:
4729 case QEMU_FILE_TYPE_KEYMAP
:
4730 subdir
= "keymaps/";
4735 len
= strlen(data_dir
) + strlen(name
) + strlen(subdir
) + 2;
4736 buf
= qemu_mallocz(len
);
4737 snprintf(buf
, len
, "%s/%s%s", data_dir
, subdir
, name
);
4738 if (access(buf
, R_OK
)) {
4745 static int device_init_func(QemuOpts
*opts
, void *opaque
)
4749 dev
= qdev_device_add(opts
);
4755 struct device_config
{
4757 DEV_USB
, /* -usbdevice */
4760 const char *cmdline
;
4761 QTAILQ_ENTRY(device_config
) next
;
4763 QTAILQ_HEAD(, device_config
) device_configs
= QTAILQ_HEAD_INITIALIZER(device_configs
);
4765 static void add_device_config(int type
, const char *cmdline
)
4767 struct device_config
*conf
;
4769 conf
= qemu_mallocz(sizeof(*conf
));
4771 conf
->cmdline
= cmdline
;
4772 QTAILQ_INSERT_TAIL(&device_configs
, conf
, next
);
4775 static int foreach_device_config(int type
, int (*func
)(const char *cmdline
))
4777 struct device_config
*conf
;
4780 QTAILQ_FOREACH(conf
, &device_configs
, next
) {
4781 if (conf
->type
!= type
)
4783 rc
= func(conf
->cmdline
);
4790 int main(int argc
, char **argv
, char **envp
)
4792 const char *gdbstub_dev
= NULL
;
4793 uint32_t boot_devices_bitmap
= 0;
4795 int snapshot
, linux_boot
, net_boot
;
4796 const char *initrd_filename
;
4797 const char *kernel_filename
, *kernel_cmdline
;
4798 char boot_devices
[33] = "cad"; /* default to HD->floppy->CD-ROM */
4800 DisplayChangeListener
*dcl
;
4801 int cyls
, heads
, secs
, translation
;
4802 QemuOpts
*hda_opts
= NULL
, *opts
;
4804 const char *r
, *optarg
;
4805 CharDriverState
*monitor_hds
[MAX_MONITOR_DEVICES
];
4806 const char *monitor_devices
[MAX_MONITOR_DEVICES
];
4807 int monitor_device_index
;
4808 const char *serial_devices
[MAX_SERIAL_PORTS
];
4809 int serial_device_index
;
4810 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
4811 int parallel_device_index
;
4812 const char *virtio_consoles
[MAX_VIRTIO_CONSOLES
];
4813 int virtio_console_index
;
4814 const char *loadvm
= NULL
;
4815 QEMUMachine
*machine
;
4816 const char *cpu_model
;
4821 const char *pid_file
= NULL
;
4822 const char *incoming
= NULL
;
4825 struct passwd
*pwd
= NULL
;
4826 const char *chroot_dir
= NULL
;
4827 const char *run_as
= NULL
;
4830 int show_vnc_port
= 0;
4834 qemu_errors_to_file(stderr
);
4835 qemu_cache_utils_init(envp
);
4837 QLIST_INIT (&vm_change_state_head
);
4840 struct sigaction act
;
4841 sigfillset(&act
.sa_mask
);
4843 act
.sa_handler
= SIG_IGN
;
4844 sigaction(SIGPIPE
, &act
, NULL
);
4847 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4848 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4849 QEMU to run on a single CPU */
4854 h
= GetCurrentProcess();
4855 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4856 for(i
= 0; i
< 32; i
++) {
4857 if (mask
& (1 << i
))
4862 SetProcessAffinityMask(h
, mask
);
4868 module_call_init(MODULE_INIT_MACHINE
);
4869 machine
= find_default_machine();
4871 initrd_filename
= NULL
;
4874 kernel_filename
= NULL
;
4875 kernel_cmdline
= "";
4876 cyls
= heads
= secs
= 0;
4877 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4879 serial_devices
[0] = "vc:80Cx24C";
4880 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
4881 serial_devices
[i
] = NULL
;
4882 serial_device_index
= 0;
4884 parallel_devices
[0] = "vc:80Cx24C";
4885 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
4886 parallel_devices
[i
] = NULL
;
4887 parallel_device_index
= 0;
4889 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++)
4890 virtio_consoles
[i
] = NULL
;
4891 virtio_console_index
= 0;
4893 monitor_devices
[0] = "vc:80Cx24C";
4894 for (i
= 1; i
< MAX_MONITOR_DEVICES
; i
++) {
4895 monitor_devices
[i
] = NULL
;
4897 monitor_device_index
= 0;
4899 for (i
= 0; i
< MAX_NODES
; i
++) {
4901 node_cpumask
[i
] = 0;
4904 assigned_devices_index
= 0;
4918 hda_opts
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
4920 const QEMUOption
*popt
;
4923 /* Treat --foo the same as -foo. */
4926 popt
= qemu_options
;
4929 fprintf(stderr
, "%s: invalid option -- '%s'\n",
4933 if (!strcmp(popt
->name
, r
+ 1))
4937 if (popt
->flags
& HAS_ARG
) {
4938 if (optind
>= argc
) {
4939 fprintf(stderr
, "%s: option '%s' requires an argument\n",
4943 optarg
= argv
[optind
++];
4948 switch(popt
->index
) {
4950 machine
= find_machine(optarg
);
4953 printf("Supported machines are:\n");
4954 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
4956 printf("%-10s %s (alias of %s)\n",
4957 m
->alias
, m
->desc
, m
->name
);
4958 printf("%-10s %s%s\n",
4960 m
->is_default
? " (default)" : "");
4962 exit(*optarg
!= '?');
4965 case QEMU_OPTION_cpu
:
4966 /* hw initialization will check this */
4967 if (*optarg
== '?') {
4968 /* XXX: implement xxx_cpu_list for targets that still miss it */
4969 #if defined(cpu_list)
4970 cpu_list(stdout
, &fprintf
);
4977 case QEMU_OPTION_initrd
:
4978 initrd_filename
= optarg
;
4980 case QEMU_OPTION_hda
:
4982 hda_opts
= drive_add(optarg
, HD_ALIAS
, 0);
4984 hda_opts
= drive_add(optarg
, HD_ALIAS
4985 ",cyls=%d,heads=%d,secs=%d%s",
4986 0, cyls
, heads
, secs
,
4987 translation
== BIOS_ATA_TRANSLATION_LBA
?
4989 translation
== BIOS_ATA_TRANSLATION_NONE
?
4990 ",trans=none" : "");
4992 case QEMU_OPTION_hdb
:
4993 case QEMU_OPTION_hdc
:
4994 case QEMU_OPTION_hdd
:
4995 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
4997 case QEMU_OPTION_drive
:
4998 drive_add(NULL
, "%s", optarg
);
5000 case QEMU_OPTION_set
:
5001 if (qemu_set_option(optarg
) != 0)
5004 case QEMU_OPTION_mtdblock
:
5005 drive_add(optarg
, MTD_ALIAS
);
5007 case QEMU_OPTION_sd
:
5008 drive_add(optarg
, SD_ALIAS
);
5010 case QEMU_OPTION_pflash
:
5011 drive_add(optarg
, PFLASH_ALIAS
);
5013 case QEMU_OPTION_snapshot
:
5016 case QEMU_OPTION_hdachs
:
5020 cyls
= strtol(p
, (char **)&p
, 0);
5021 if (cyls
< 1 || cyls
> 16383)
5026 heads
= strtol(p
, (char **)&p
, 0);
5027 if (heads
< 1 || heads
> 16)
5032 secs
= strtol(p
, (char **)&p
, 0);
5033 if (secs
< 1 || secs
> 63)
5037 if (!strcmp(p
, "none"))
5038 translation
= BIOS_ATA_TRANSLATION_NONE
;
5039 else if (!strcmp(p
, "lba"))
5040 translation
= BIOS_ATA_TRANSLATION_LBA
;
5041 else if (!strcmp(p
, "auto"))
5042 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5045 } else if (*p
!= '\0') {
5047 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5050 if (hda_opts
!= NULL
) {
5052 snprintf(num
, sizeof(num
), "%d", cyls
);
5053 qemu_opt_set(hda_opts
, "cyls", num
);
5054 snprintf(num
, sizeof(num
), "%d", heads
);
5055 qemu_opt_set(hda_opts
, "heads", num
);
5056 snprintf(num
, sizeof(num
), "%d", secs
);
5057 qemu_opt_set(hda_opts
, "secs", num
);
5058 if (translation
== BIOS_ATA_TRANSLATION_LBA
)
5059 qemu_opt_set(hda_opts
, "trans", "lba");
5060 if (translation
== BIOS_ATA_TRANSLATION_NONE
)
5061 qemu_opt_set(hda_opts
, "trans", "none");
5065 case QEMU_OPTION_numa
:
5066 if (nb_numa_nodes
>= MAX_NODES
) {
5067 fprintf(stderr
, "qemu: too many NUMA nodes\n");
5072 case QEMU_OPTION_nographic
:
5073 display_type
= DT_NOGRAPHIC
;
5075 #ifdef CONFIG_CURSES
5076 case QEMU_OPTION_curses
:
5077 display_type
= DT_CURSES
;
5080 case QEMU_OPTION_portrait
:
5083 case QEMU_OPTION_kernel
:
5084 kernel_filename
= optarg
;
5086 case QEMU_OPTION_append
:
5087 kernel_cmdline
= optarg
;
5089 case QEMU_OPTION_cdrom
:
5090 drive_add(optarg
, CDROM_ALIAS
);
5092 case QEMU_OPTION_boot
:
5094 static const char * const params
[] = {
5095 "order", "once", "menu", NULL
5097 char buf
[sizeof(boot_devices
)];
5098 char *standard_boot_devices
;
5101 if (!strchr(optarg
, '=')) {
5103 pstrcpy(buf
, sizeof(buf
), optarg
);
5104 } else if (check_params(buf
, sizeof(buf
), params
, optarg
) < 0) {
5106 "qemu: unknown boot parameter '%s' in '%s'\n",
5112 get_param_value(buf
, sizeof(buf
), "order", optarg
)) {
5113 boot_devices_bitmap
= parse_bootdevices(buf
);
5114 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5117 if (get_param_value(buf
, sizeof(buf
),
5119 boot_devices_bitmap
|= parse_bootdevices(buf
);
5120 standard_boot_devices
= qemu_strdup(boot_devices
);
5121 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5122 qemu_register_reset(restore_boot_devices
,
5123 standard_boot_devices
);
5125 if (get_param_value(buf
, sizeof(buf
),
5127 if (!strcmp(buf
, "on")) {
5129 } else if (!strcmp(buf
, "off")) {
5133 "qemu: invalid option value '%s'\n",
5141 case QEMU_OPTION_fda
:
5142 case QEMU_OPTION_fdb
:
5143 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
5146 case QEMU_OPTION_no_fd_bootchk
:
5150 case QEMU_OPTION_netdev
:
5151 if (net_client_parse(&qemu_netdev_opts
, optarg
) == -1) {
5155 case QEMU_OPTION_net
:
5156 if (net_client_parse(&qemu_net_opts
, optarg
) == -1) {
5161 case QEMU_OPTION_tftp
:
5162 legacy_tftp_prefix
= optarg
;
5164 case QEMU_OPTION_bootp
:
5165 legacy_bootp_filename
= optarg
;
5168 case QEMU_OPTION_smb
:
5169 if (net_slirp_smb(optarg
) < 0)
5173 case QEMU_OPTION_redir
:
5174 if (net_slirp_redir(optarg
) < 0)
5178 case QEMU_OPTION_bt
:
5179 add_device_config(DEV_BT
, optarg
);
5182 case QEMU_OPTION_audio_help
:
5186 case QEMU_OPTION_soundhw
:
5187 select_soundhw (optarg
);
5193 case QEMU_OPTION_version
:
5197 case QEMU_OPTION_m
: {
5201 value
= strtoul(optarg
, &ptr
, 10);
5203 case 0: case 'M': case 'm':
5210 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5214 /* On 32-bit hosts, QEMU is limited by virtual address space */
5215 if (value
> (2047 << 20) && HOST_LONG_BITS
== 32) {
5216 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5219 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5220 fprintf(stderr
, "qemu: ram size too large\n");
5229 const CPULogItem
*item
;
5231 mask
= cpu_str_to_log_mask(optarg
);
5233 printf("Log items (comma separated):\n");
5234 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5235 printf("%-10s %s\n", item
->name
, item
->help
);
5243 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5245 case QEMU_OPTION_gdb
:
5246 gdbstub_dev
= optarg
;
5251 case QEMU_OPTION_bios
:
5254 case QEMU_OPTION_singlestep
:
5262 keyboard_layout
= optarg
;
5265 case QEMU_OPTION_localtime
:
5268 case QEMU_OPTION_vga
:
5269 select_vgahw (optarg
);
5271 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5277 w
= strtol(p
, (char **)&p
, 10);
5280 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5286 h
= strtol(p
, (char **)&p
, 10);
5291 depth
= strtol(p
, (char **)&p
, 10);
5292 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5293 depth
!= 24 && depth
!= 32)
5295 } else if (*p
== '\0') {
5296 depth
= graphic_depth
;
5303 graphic_depth
= depth
;
5307 case QEMU_OPTION_echr
:
5310 term_escape_char
= strtol(optarg
, &r
, 0);
5312 printf("Bad argument to echr\n");
5315 case QEMU_OPTION_monitor
:
5316 if (monitor_device_index
>= MAX_MONITOR_DEVICES
) {
5317 fprintf(stderr
, "qemu: too many monitor devices\n");
5320 monitor_devices
[monitor_device_index
] = optarg
;
5321 monitor_device_index
++;
5323 case QEMU_OPTION_chardev
:
5324 opts
= qemu_opts_parse(&qemu_chardev_opts
, optarg
, "backend");
5326 fprintf(stderr
, "parse error: %s\n", optarg
);
5329 if (qemu_chr_open_opts(opts
, NULL
) == NULL
) {
5333 case QEMU_OPTION_serial
:
5334 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
5335 fprintf(stderr
, "qemu: too many serial ports\n");
5338 serial_devices
[serial_device_index
] = optarg
;
5339 serial_device_index
++;
5341 case QEMU_OPTION_watchdog
:
5344 "qemu: only one watchdog option may be given\n");
5349 case QEMU_OPTION_watchdog_action
:
5350 if (select_watchdog_action(optarg
) == -1) {
5351 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5355 case QEMU_OPTION_virtiocon
:
5356 if (virtio_console_index
>= MAX_VIRTIO_CONSOLES
) {
5357 fprintf(stderr
, "qemu: too many virtio consoles\n");
5360 virtio_consoles
[virtio_console_index
] = optarg
;
5361 virtio_console_index
++;
5363 case QEMU_OPTION_parallel
:
5364 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
5365 fprintf(stderr
, "qemu: too many parallel ports\n");
5368 parallel_devices
[parallel_device_index
] = optarg
;
5369 parallel_device_index
++;
5371 case QEMU_OPTION_loadvm
:
5374 case QEMU_OPTION_full_screen
:
5378 case QEMU_OPTION_no_frame
:
5381 case QEMU_OPTION_alt_grab
:
5384 case QEMU_OPTION_ctrl_grab
:
5387 case QEMU_OPTION_no_quit
:
5390 case QEMU_OPTION_sdl
:
5391 display_type
= DT_SDL
;
5394 case QEMU_OPTION_pidfile
:
5398 case QEMU_OPTION_win2k_hack
:
5399 win2k_install_hack
= 1;
5401 case QEMU_OPTION_rtc_td_hack
:
5404 case QEMU_OPTION_acpitable
:
5405 if(acpi_table_add(optarg
) < 0) {
5406 fprintf(stderr
, "Wrong acpi table provided\n");
5410 case QEMU_OPTION_smbios
:
5411 if(smbios_entry_add(optarg
) < 0) {
5412 fprintf(stderr
, "Wrong smbios provided\n");
5419 case QEMU_OPTION_enable_kvm
:
5423 case QEMU_OPTION_no_kvm
:
5426 case QEMU_OPTION_no_kvm_irqchip
: {
5431 case QEMU_OPTION_no_kvm_pit
: {
5435 case QEMU_OPTION_no_kvm_pit_reinjection
: {
5436 kvm_pit_reinject
= 0;
5439 case QEMU_OPTION_enable_nesting
: {
5443 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5444 case QEMU_OPTION_pcidevice
:
5445 if (assigned_devices_index
>= MAX_DEV_ASSIGN_CMDLINE
) {
5446 fprintf(stderr
, "Too many assigned devices\n");
5449 assigned_devices
[assigned_devices_index
] = optarg
;
5450 assigned_devices_index
++;
5454 case QEMU_OPTION_usb
:
5457 case QEMU_OPTION_usbdevice
:
5459 add_device_config(DEV_USB
, optarg
);
5461 case QEMU_OPTION_device
:
5462 if (!qemu_opts_parse(&qemu_device_opts
, optarg
, "driver")) {
5466 case QEMU_OPTION_smp
:
5469 fprintf(stderr
, "Invalid number of CPUs\n");
5472 if (max_cpus
< smp_cpus
) {
5473 fprintf(stderr
, "maxcpus must be equal to or greater than "
5477 if (max_cpus
> 255) {
5478 fprintf(stderr
, "Unsupported number of maxcpus\n");
5482 case QEMU_OPTION_vnc
:
5483 display_type
= DT_VNC
;
5484 vnc_display
= optarg
;
5487 case QEMU_OPTION_no_acpi
:
5490 case QEMU_OPTION_no_hpet
:
5493 case QEMU_OPTION_balloon
:
5494 if (balloon_parse(optarg
) < 0) {
5495 fprintf(stderr
, "Unknown -balloon argument %s\n", optarg
);
5500 case QEMU_OPTION_no_reboot
:
5503 case QEMU_OPTION_no_shutdown
:
5506 case QEMU_OPTION_show_cursor
:
5509 case QEMU_OPTION_uuid
:
5510 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5511 fprintf(stderr
, "Fail to parse UUID string."
5512 " Wrong format.\n");
5517 case QEMU_OPTION_daemonize
:
5521 case QEMU_OPTION_option_rom
:
5522 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5523 fprintf(stderr
, "Too many option ROMs\n");
5526 option_rom
[nb_option_roms
] = optarg
;
5529 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5530 case QEMU_OPTION_semihosting
:
5531 semihosting_enabled
= 1;
5534 case QEMU_OPTION_tdf
:
5537 case QEMU_OPTION_kvm_shadow_memory
:
5538 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
5540 case QEMU_OPTION_mempath
:
5544 case QEMU_OPTION_mem_prealloc
:
5545 mem_prealloc
= !mem_prealloc
;
5548 case QEMU_OPTION_name
:
5549 qemu_name
= qemu_strdup(optarg
);
5551 char *p
= strchr(qemu_name
, ',');
5554 if (strncmp(p
, "process=", 8)) {
5555 fprintf(stderr
, "Unknown subargument %s to -name", p
);
5563 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5564 case QEMU_OPTION_prom_env
:
5565 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5566 fprintf(stderr
, "Too many prom variables\n");
5569 prom_envs
[nb_prom_envs
] = optarg
;
5574 case QEMU_OPTION_old_param
:
5578 case QEMU_OPTION_clock
:
5579 configure_alarms(optarg
);
5581 case QEMU_OPTION_startdate
:
5582 configure_rtc_date_offset(optarg
, 1);
5584 case QEMU_OPTION_rtc
:
5585 opts
= qemu_opts_parse(&qemu_rtc_opts
, optarg
, NULL
);
5587 fprintf(stderr
, "parse error: %s\n", optarg
);
5590 configure_rtc(opts
);
5592 case QEMU_OPTION_tb_size
:
5593 tb_size
= strtol(optarg
, NULL
, 0);
5597 case QEMU_OPTION_icount
:
5599 if (strcmp(optarg
, "auto") == 0) {
5600 icount_time_shift
= -1;
5602 icount_time_shift
= strtol(optarg
, NULL
, 0);
5605 case QEMU_OPTION_incoming
:
5609 case QEMU_OPTION_chroot
:
5610 chroot_dir
= optarg
;
5612 case QEMU_OPTION_runas
:
5615 case QEMU_OPTION_nvram
:
5620 case QEMU_OPTION_xen_domid
:
5621 xen_domid
= atoi(optarg
);
5623 case QEMU_OPTION_xen_create
:
5624 xen_mode
= XEN_CREATE
;
5626 case QEMU_OPTION_xen_attach
:
5627 xen_mode
= XEN_ATTACH
;
5634 /* If no data_dir is specified then try to find it relative to the
5637 data_dir
= find_datadir(argv
[0]);
5639 /* If all else fails use the install patch specified when building. */
5641 data_dir
= CONFIG_QEMU_SHAREDIR
;
5645 * Default to max_cpus = smp_cpus, in case the user doesn't
5646 * specify a max_cpus value.
5649 max_cpus
= smp_cpus
;
5651 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5652 if (smp_cpus
> machine
->max_cpus
) {
5653 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5654 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5659 if (display_type
== DT_NOGRAPHIC
) {
5660 if (serial_device_index
== 0)
5661 serial_devices
[0] = "stdio";
5662 if (parallel_device_index
== 0)
5663 parallel_devices
[0] = "null";
5664 if (strncmp(monitor_devices
[0], "vc", 2) == 0) {
5665 monitor_devices
[0] = "stdio";
5673 if (pipe(fds
) == -1)
5684 len
= read(fds
[0], &status
, 1);
5685 if (len
== -1 && (errno
== EINTR
))
5690 else if (status
== 1) {
5691 fprintf(stderr
, "Could not acquire pidfile: %s\n", strerror(errno
));
5708 signal(SIGTSTP
, SIG_IGN
);
5709 signal(SIGTTOU
, SIG_IGN
);
5710 signal(SIGTTIN
, SIG_IGN
);
5713 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5716 write(fds
[1], &status
, 1);
5718 fprintf(stderr
, "Could not acquire pid file: %s\n", strerror(errno
));
5723 if (kvm_enabled()) {
5726 ret
= kvm_init(smp_cpus
);
5728 #if defined(KVM_UPSTREAM) || defined(CONFIG_NO_CPU_EMULATION)
5729 fprintf(stderr
, "failed to initialize KVM\n");
5732 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
5737 if (qemu_init_main_loop()) {
5738 fprintf(stderr
, "qemu_init_main_loop failed\n");
5741 linux_boot
= (kernel_filename
!= NULL
);
5743 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5744 fprintf(stderr
, "-append only allowed with -kernel option\n");
5748 if (!linux_boot
&& initrd_filename
!= NULL
) {
5749 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5754 /* Win32 doesn't support line-buffering and requires size >= 2 */
5755 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5758 if (init_timer_alarm() < 0) {
5759 fprintf(stderr
, "could not initialize alarm timer\n");
5762 if (use_icount
&& icount_time_shift
< 0) {
5764 /* 125MIPS seems a reasonable initial guess at the guest speed.
5765 It will be corrected fairly quickly anyway. */
5766 icount_time_shift
= 3;
5767 init_icount_adjust();
5774 if (net_init_clients() < 0) {
5778 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5779 net_set_boot_mask(net_boot
);
5781 /* init the bluetooth world */
5782 if (foreach_device_config(DEV_BT
, bt_parse
))
5785 /* init the memory */
5787 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5789 /* init the dynamic translator */
5790 cpu_exec_init_all(tb_size
* 1024 * 1024);
5794 /* we always create the cdrom drive, even if no disk is there */
5795 drive_add(NULL
, CDROM_ALIAS
);
5797 /* we always create at least one floppy */
5798 drive_add(NULL
, FD_ALIAS
, 0);
5800 /* we always create one sd slot, even if no card is in it */
5801 drive_add(NULL
, SD_ALIAS
);
5803 /* open the virtual block devices */
5805 qemu_opts_foreach(&qemu_drive_opts
, drive_enable_snapshot
, NULL
, 0);
5806 if (qemu_opts_foreach(&qemu_drive_opts
, drive_init_func
, machine
, 1) != 0)
5809 vmstate_register(0, &vmstate_timers
,&timers_state
);
5810 register_savevm_live("ram", 0, 3, ram_save_live
, NULL
, ram_load
, NULL
);
5812 /* Maintain compatibility with multiple stdio monitors */
5813 if (!strcmp(monitor_devices
[0],"stdio")) {
5814 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5815 const char *devname
= serial_devices
[i
];
5816 if (devname
&& !strcmp(devname
,"mon:stdio")) {
5817 monitor_devices
[0] = NULL
;
5819 } else if (devname
&& !strcmp(devname
,"stdio")) {
5820 monitor_devices
[0] = NULL
;
5821 serial_devices
[i
] = "mon:stdio";
5827 if (nb_numa_nodes
> 0) {
5830 if (nb_numa_nodes
> smp_cpus
) {
5831 nb_numa_nodes
= smp_cpus
;
5834 /* If no memory size if given for any node, assume the default case
5835 * and distribute the available memory equally across all nodes
5837 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5838 if (node_mem
[i
] != 0)
5841 if (i
== nb_numa_nodes
) {
5842 uint64_t usedmem
= 0;
5844 /* On Linux, the each node's border has to be 8MB aligned,
5845 * the final node gets the rest.
5847 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
5848 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
5849 usedmem
+= node_mem
[i
];
5851 node_mem
[i
] = ram_size
- usedmem
;
5854 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5855 if (node_cpumask
[i
] != 0)
5858 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5859 * must cope with this anyway, because there are BIOSes out there in
5860 * real machines which also use this scheme.
5862 if (i
== nb_numa_nodes
) {
5863 for (i
= 0; i
< smp_cpus
; i
++) {
5864 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
5869 for (i
= 0; i
< MAX_MONITOR_DEVICES
; i
++) {
5870 const char *devname
= monitor_devices
[i
];
5871 if (devname
&& strcmp(devname
, "none")) {
5874 snprintf(label
, sizeof(label
), "monitor");
5876 snprintf(label
, sizeof(label
), "monitor%d", i
);
5878 monitor_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5879 if (!monitor_hds
[i
]) {
5880 fprintf(stderr
, "qemu: could not open monitor device '%s'\n",
5887 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5888 const char *devname
= serial_devices
[i
];
5889 if (devname
&& strcmp(devname
, "none")) {
5891 snprintf(label
, sizeof(label
), "serial%d", i
);
5892 serial_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5893 if (!serial_hds
[i
]) {
5894 fprintf(stderr
, "qemu: could not open serial device '%s': %s\n",
5895 devname
, strerror(errno
));
5901 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
5902 const char *devname
= parallel_devices
[i
];
5903 if (devname
&& strcmp(devname
, "none")) {
5905 snprintf(label
, sizeof(label
), "parallel%d", i
);
5906 parallel_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5907 if (!parallel_hds
[i
]) {
5908 fprintf(stderr
, "qemu: could not open parallel device '%s': %s\n",
5909 devname
, strerror(errno
));
5915 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
5916 const char *devname
= virtio_consoles
[i
];
5917 if (devname
&& strcmp(devname
, "none")) {
5919 snprintf(label
, sizeof(label
), "virtcon%d", i
);
5920 virtcon_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5921 if (!virtcon_hds
[i
]) {
5922 fprintf(stderr
, "qemu: could not open virtio console '%s': %s\n",
5923 devname
, strerror(errno
));
5929 module_call_init(MODULE_INIT_DEVICE
);
5932 i
= select_watchdog(watchdog
);
5934 exit (i
== 1 ? 1 : 0);
5937 if (machine
->compat_props
) {
5938 qdev_prop_register_compat(machine
->compat_props
);
5940 machine
->init(ram_size
, boot_devices
,
5941 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
5945 /* must be after terminal init, SDL library changes signal handlers */
5949 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
5950 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5951 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
5957 current_machine
= machine
;
5959 /* init USB devices */
5961 if (foreach_device_config(DEV_USB
, usb_parse
) < 0)
5965 /* init generic devices */
5966 if (qemu_opts_foreach(&qemu_device_opts
, device_init_func
, NULL
, 1) != 0)
5970 dumb_display_init();
5971 /* just use the first displaystate for the moment */
5974 if (display_type
== DT_DEFAULT
) {
5975 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5976 display_type
= DT_SDL
;
5978 display_type
= DT_VNC
;
5979 vnc_display
= "localhost:0,to=99";
5985 switch (display_type
) {
5988 #if defined(CONFIG_CURSES)
5990 curses_display_init(ds
, full_screen
);
5993 #if defined(CONFIG_SDL)
5995 sdl_display_init(ds
, full_screen
, no_frame
);
5997 #elif defined(CONFIG_COCOA)
5999 cocoa_display_init(ds
, full_screen
);
6003 vnc_display_init(ds
);
6004 if (vnc_display_open(ds
, vnc_display
) < 0)
6007 if (show_vnc_port
) {
6008 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
6016 dcl
= ds
->listeners
;
6017 while (dcl
!= NULL
) {
6018 if (dcl
->dpy_refresh
!= NULL
) {
6019 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
6020 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
6025 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
6026 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
6027 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
6030 text_consoles_set_display(display_state
);
6031 qemu_chr_initial_reset();
6033 for (i
= 0; i
< MAX_MONITOR_DEVICES
; i
++) {
6034 if (monitor_devices
[i
] && monitor_hds
[i
]) {
6035 monitor_init(monitor_hds
[i
],
6036 MONITOR_USE_READLINE
|
6037 ((i
== 0) ? MONITOR_IS_DEFAULT
: 0));
6041 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6042 const char *devname
= serial_devices
[i
];
6043 if (devname
&& strcmp(devname
, "none")) {
6044 if (strstart(devname
, "vc", 0))
6045 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
6049 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
6050 const char *devname
= parallel_devices
[i
];
6051 if (devname
&& strcmp(devname
, "none")) {
6052 if (strstart(devname
, "vc", 0))
6053 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
6057 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
6058 const char *devname
= virtio_consoles
[i
];
6059 if (virtcon_hds
[i
] && devname
) {
6060 if (strstart(devname
, "vc", 0))
6061 qemu_chr_printf(virtcon_hds
[i
], "virtio console%d\r\n", i
);
6065 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
6066 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
6071 qdev_machine_creation_done();
6076 if (load_vmstate(cur_mon
, loadvm
) < 0) {
6082 qemu_start_incoming_migration(incoming
);
6083 } else if (autostart
) {
6093 len
= write(fds
[1], &status
, 1);
6094 if (len
== -1 && (errno
== EINTR
))
6101 TFR(fd
= open("/dev/null", O_RDWR
));
6107 pwd
= getpwnam(run_as
);
6109 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
6115 if (chroot(chroot_dir
) < 0) {
6116 fprintf(stderr
, "chroot failed\n");
6123 if (setgid(pwd
->pw_gid
) < 0) {
6124 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
6127 if (setuid(pwd
->pw_uid
) < 0) {
6128 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
6131 if (setuid(0) != -1) {
6132 fprintf(stderr
, "Dropping privileges failed\n");