4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
34 /* Needed early to override system queue definitions on BSD */
35 #include "sys-queue.h"
40 #include <sys/times.h>
44 #include <sys/ioctl.h>
45 #include <sys/resource.h>
46 #include <sys/socket.h>
47 #include <netinet/in.h>
49 #if defined(__NetBSD__)
50 #include <net/if_tap.h>
53 #include <linux/if_tun.h>
55 #include <arpa/inet.h>
58 #include <sys/select.h>
61 #if defined(__FreeBSD__) || defined(__DragonFly__)
66 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
67 #include <freebsd/stdlib.h>
72 #include <linux/rtc.h>
73 #include <sys/prctl.h>
75 /* For the benefit of older linux systems which don't supply it,
76 we use a local copy of hpet.h. */
77 /* #include <linux/hpet.h> */
80 #include <linux/ppdev.h>
81 #include <linux/parport.h>
85 #include <sys/ethernet.h>
86 #include <sys/sockio.h>
87 #include <netinet/arp.h>
88 #include <netinet/in.h>
89 #include <netinet/in_systm.h>
90 #include <netinet/ip.h>
91 #include <netinet/ip_icmp.h> // must come after ip.h
92 #include <netinet/udp.h>
93 #include <netinet/tcp.h>
101 #if defined(__OpenBSD__)
105 #if defined(CONFIG_VDE)
106 #include <libvdeplug.h>
111 #include <mmsystem.h>
115 #if defined(__APPLE__) || defined(main)
117 int qemu_main(int argc
, char **argv
, char **envp
);
118 int main(int argc
, char **argv
)
120 return qemu_main(argc
, argv
, NULL
);
123 #define main qemu_main
125 #endif /* CONFIG_SDL */
129 #define main qemu_main
130 #endif /* CONFIG_COCOA */
133 #include "hw/boards.h"
135 #include "hw/pcmcia.h"
137 #include "hw/audiodev.h"
141 #include "hw/watchdog.h"
142 #include "hw/smbios.h"
151 #include "qemu-timer.h"
152 #include "qemu-char.h"
153 #include "cache-utils.h"
156 #include "audio/audio.h"
157 #include "migration.h"
160 #include "qemu-option.h"
161 #include "qemu-kvm.h"
162 #include "hw/device-assignment.h"
166 #include "exec-all.h"
168 #include "qemu_socket.h"
170 #include "slirp/libslirp.h"
173 //#define DEBUG_SLIRP
175 #define DEFAULT_RAM_SIZE 128
177 static const char *data_dir
;
178 const char *bios_name
= NULL
;
179 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
180 to store the VM snapshots */
181 struct drivelist drives
= TAILQ_HEAD_INITIALIZER(drives
);
182 struct driveoptlist driveopts
= TAILQ_HEAD_INITIALIZER(driveopts
);
183 DriveInfo
*extboot_drive
= NULL
;
184 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
185 static DisplayState
*display_state
;
186 DisplayType display_type
= DT_DEFAULT
;
187 const char* keyboard_layout
= NULL
;
188 int64_t ticks_per_sec
;
191 NICInfo nd_table
[MAX_NICS
];
194 static int rtc_utc
= 1;
195 static int rtc_date_offset
= -1; /* -1 means no change */
196 int cirrus_vga_enabled
= 1;
197 int std_vga_enabled
= 0;
198 int vmsvga_enabled
= 0;
199 int xenfb_enabled
= 0;
201 int graphic_width
= 1024;
202 int graphic_height
= 768;
203 int graphic_depth
= 8;
205 int graphic_width
= 800;
206 int graphic_height
= 600;
207 int graphic_depth
= 15;
209 static int full_screen
= 0;
211 static int no_frame
= 0;
214 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
215 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
216 CharDriverState
*virtcon_hds
[MAX_VIRTIO_CONSOLES
];
218 int win2k_install_hack
= 0;
223 const char *assigned_devices
[MAX_DEV_ASSIGN_CMDLINE
];
224 int assigned_devices_index
;
227 const char *vnc_display
;
228 int acpi_enabled
= 1;
232 int virtio_balloon
= 1;
233 const char *virtio_balloon_devaddr
;
238 int graphic_rotate
= 0;
239 uint8_t irq0override
= 1;
243 WatchdogTimerModel
*watchdog
= NULL
;
244 int watchdog_action
= WDT_RESET
;
245 const char *option_rom
[MAX_OPTION_ROMS
];
247 int semihosting_enabled
= 0;
248 int time_drift_fix
= 0;
249 unsigned int kvm_shadow_memory
= 0;
250 const char *mem_path
= NULL
;
252 int mem_prealloc
= 1; /* force preallocation of physical target memory */
257 const char *qemu_name
;
259 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
260 unsigned int nb_prom_envs
= 0;
261 const char *prom_envs
[MAX_PROM_ENVS
];
263 const char *nvram
= NULL
;
267 uint64_t node_mem
[MAX_NODES
];
268 uint64_t node_cpumask
[MAX_NODES
];
270 static CPUState
*cur_cpu
;
271 static CPUState
*next_cpu
;
272 static int timer_alarm_pending
= 1;
273 /* Conversion factor from emulated instructions to virtual clock ticks. */
274 static int icount_time_shift
;
275 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
276 #define MAX_ICOUNT_SHIFT 10
277 /* Compensate for varying guest execution speed. */
278 static int64_t qemu_icount_bias
;
279 static QEMUTimer
*icount_rt_timer
;
280 static QEMUTimer
*icount_vm_timer
;
281 static QEMUTimer
*nographic_timer
;
283 uint8_t qemu_uuid
[16];
285 static QEMUBootSetHandler
*boot_set_handler
;
286 static void *boot_set_opaque
;
288 /***********************************************************/
289 /* x86 ISA bus support */
291 target_phys_addr_t isa_mem_base
= 0;
294 /***********************************************************/
295 void hw_error(const char *fmt
, ...)
301 fprintf(stderr
, "qemu: hardware error: ");
302 vfprintf(stderr
, fmt
, ap
);
303 fprintf(stderr
, "\n");
304 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
305 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
307 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
309 cpu_dump_state(env
, stderr
, fprintf
, 0);
316 static void set_proc_name(const char *s
)
322 name
[sizeof(name
) - 1] = 0;
323 strncpy(name
, s
, sizeof(name
));
324 /* Could rewrite argv[0] too, but that's a bit more complicated.
325 This simple way is enough for `top'. */
326 prctl(PR_SET_NAME
, name
);
333 static QEMUBalloonEvent
*qemu_balloon_event
;
334 void *qemu_balloon_event_opaque
;
336 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
338 qemu_balloon_event
= func
;
339 qemu_balloon_event_opaque
= opaque
;
342 void qemu_balloon(ram_addr_t target
)
344 if (qemu_balloon_event
)
345 qemu_balloon_event(qemu_balloon_event_opaque
, target
);
348 ram_addr_t
qemu_balloon_status(void)
350 if (qemu_balloon_event
)
351 return qemu_balloon_event(qemu_balloon_event_opaque
, 0);
355 /***********************************************************/
358 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
359 static void *qemu_put_kbd_event_opaque
;
360 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
361 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
363 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
365 qemu_put_kbd_event_opaque
= opaque
;
366 qemu_put_kbd_event
= func
;
369 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
370 void *opaque
, int absolute
,
373 QEMUPutMouseEntry
*s
, *cursor
;
375 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
377 s
->qemu_put_mouse_event
= func
;
378 s
->qemu_put_mouse_event_opaque
= opaque
;
379 s
->qemu_put_mouse_event_absolute
= absolute
;
380 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
383 if (!qemu_put_mouse_event_head
) {
384 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
388 cursor
= qemu_put_mouse_event_head
;
389 while (cursor
->next
!= NULL
)
390 cursor
= cursor
->next
;
393 qemu_put_mouse_event_current
= s
;
398 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
400 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
402 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
405 cursor
= qemu_put_mouse_event_head
;
406 while (cursor
!= NULL
&& cursor
!= entry
) {
408 cursor
= cursor
->next
;
411 if (cursor
== NULL
) // does not exist or list empty
413 else if (prev
== NULL
) { // entry is head
414 qemu_put_mouse_event_head
= cursor
->next
;
415 if (qemu_put_mouse_event_current
== entry
)
416 qemu_put_mouse_event_current
= cursor
->next
;
417 qemu_free(entry
->qemu_put_mouse_event_name
);
422 prev
->next
= entry
->next
;
424 if (qemu_put_mouse_event_current
== entry
)
425 qemu_put_mouse_event_current
= prev
;
427 qemu_free(entry
->qemu_put_mouse_event_name
);
431 void kbd_put_keycode(int keycode
)
433 if (qemu_put_kbd_event
) {
434 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
438 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
440 QEMUPutMouseEvent
*mouse_event
;
441 void *mouse_event_opaque
;
444 if (!qemu_put_mouse_event_current
) {
449 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
451 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
454 if (graphic_rotate
) {
455 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
458 width
= graphic_width
- 1;
459 mouse_event(mouse_event_opaque
,
460 width
- dy
, dx
, dz
, buttons_state
);
462 mouse_event(mouse_event_opaque
,
463 dx
, dy
, dz
, buttons_state
);
467 int kbd_mouse_is_absolute(void)
469 if (!qemu_put_mouse_event_current
)
472 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
475 void do_info_mice(Monitor
*mon
)
477 QEMUPutMouseEntry
*cursor
;
480 if (!qemu_put_mouse_event_head
) {
481 monitor_printf(mon
, "No mouse devices connected\n");
485 monitor_printf(mon
, "Mouse devices available:\n");
486 cursor
= qemu_put_mouse_event_head
;
487 while (cursor
!= NULL
) {
488 monitor_printf(mon
, "%c Mouse #%d: %s\n",
489 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
490 index
, cursor
->qemu_put_mouse_event_name
);
492 cursor
= cursor
->next
;
496 void do_mouse_set(Monitor
*mon
, int index
)
498 QEMUPutMouseEntry
*cursor
;
501 if (!qemu_put_mouse_event_head
) {
502 monitor_printf(mon
, "No mouse devices connected\n");
506 cursor
= qemu_put_mouse_event_head
;
507 while (cursor
!= NULL
&& index
!= i
) {
509 cursor
= cursor
->next
;
513 qemu_put_mouse_event_current
= cursor
;
515 monitor_printf(mon
, "Mouse at given index not found\n");
518 /* compute with 96 bit intermediate result: (a*b)/c */
519 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
524 #ifdef HOST_WORDS_BIGENDIAN
534 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
535 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
538 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
542 /***********************************************************/
543 /* real time host monotonic timer */
545 #define QEMU_TIMER_BASE 1000000000LL
549 static int64_t clock_freq
;
551 static void init_get_clock(void)
555 ret
= QueryPerformanceFrequency(&freq
);
557 fprintf(stderr
, "Could not calibrate ticks\n");
560 clock_freq
= freq
.QuadPart
;
563 static int64_t get_clock(void)
566 QueryPerformanceCounter(&ti
);
567 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
572 static int use_rt_clock
;
574 static void init_get_clock(void)
577 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
578 || defined(__DragonFly__)
581 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
588 static int64_t get_clock(void)
590 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
591 || defined(__DragonFly__)
594 clock_gettime(CLOCK_MONOTONIC
, &ts
);
595 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
599 /* XXX: using gettimeofday leads to problems if the date
600 changes, so it should be avoided. */
602 gettimeofday(&tv
, NULL
);
603 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
608 /* Return the virtual CPU time, based on the instruction counter. */
609 static int64_t cpu_get_icount(void)
612 CPUState
*env
= cpu_single_env
;;
613 icount
= qemu_icount
;
616 fprintf(stderr
, "Bad clock read\n");
617 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
619 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
622 /***********************************************************/
623 /* guest cycle counter */
625 static int64_t cpu_ticks_prev
;
626 static int64_t cpu_ticks_offset
;
627 static int64_t cpu_clock_offset
;
628 static int cpu_ticks_enabled
;
630 /* return the host CPU cycle counter and handle stop/restart */
631 int64_t cpu_get_ticks(void)
634 return cpu_get_icount();
636 if (!cpu_ticks_enabled
) {
637 return cpu_ticks_offset
;
640 ticks
= cpu_get_real_ticks();
641 if (cpu_ticks_prev
> ticks
) {
642 /* Note: non increasing ticks may happen if the host uses
644 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
646 cpu_ticks_prev
= ticks
;
647 return ticks
+ cpu_ticks_offset
;
651 /* return the host CPU monotonic timer and handle stop/restart */
652 static int64_t cpu_get_clock(void)
655 if (!cpu_ticks_enabled
) {
656 return cpu_clock_offset
;
659 return ti
+ cpu_clock_offset
;
663 /* enable cpu_get_ticks() */
664 void cpu_enable_ticks(void)
666 if (!cpu_ticks_enabled
) {
667 cpu_ticks_offset
-= cpu_get_real_ticks();
668 cpu_clock_offset
-= get_clock();
669 cpu_ticks_enabled
= 1;
673 /* disable cpu_get_ticks() : the clock is stopped. You must not call
674 cpu_get_ticks() after that. */
675 void cpu_disable_ticks(void)
677 if (cpu_ticks_enabled
) {
678 cpu_ticks_offset
= cpu_get_ticks();
679 cpu_clock_offset
= cpu_get_clock();
680 cpu_ticks_enabled
= 0;
684 /***********************************************************/
687 #define QEMU_TIMER_REALTIME 0
688 #define QEMU_TIMER_VIRTUAL 1
692 /* XXX: add frequency */
700 struct QEMUTimer
*next
;
703 struct qemu_alarm_timer
{
707 int (*start
)(struct qemu_alarm_timer
*t
);
708 void (*stop
)(struct qemu_alarm_timer
*t
);
709 void (*rearm
)(struct qemu_alarm_timer
*t
);
713 #define ALARM_FLAG_DYNTICKS 0x1
714 #define ALARM_FLAG_EXPIRED 0x2
716 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
718 return t
&& (t
->flags
& ALARM_FLAG_DYNTICKS
);
721 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
723 if (!alarm_has_dynticks(t
))
729 /* TODO: MIN_TIMER_REARM_US should be optimized */
730 #define MIN_TIMER_REARM_US 250
732 static struct qemu_alarm_timer
*alarm_timer
;
736 struct qemu_alarm_win32
{
739 } alarm_win32_data
= {0, -1};
741 static int win32_start_timer(struct qemu_alarm_timer
*t
);
742 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
743 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
747 static int unix_start_timer(struct qemu_alarm_timer
*t
);
748 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
752 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
753 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
754 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
756 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
757 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
759 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
760 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
762 #endif /* __linux__ */
766 /* Correlation between real and virtual time is always going to be
767 fairly approximate, so ignore small variation.
768 When the guest is idle real and virtual time will be aligned in
770 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
772 static void icount_adjust(void)
777 static int64_t last_delta
;
778 /* If the VM is not running, then do nothing. */
782 cur_time
= cpu_get_clock();
783 cur_icount
= qemu_get_clock(vm_clock
);
784 delta
= cur_icount
- cur_time
;
785 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
787 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
788 && icount_time_shift
> 0) {
789 /* The guest is getting too far ahead. Slow time down. */
793 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
794 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
795 /* The guest is getting too far behind. Speed time up. */
799 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
802 static void icount_adjust_rt(void * opaque
)
804 qemu_mod_timer(icount_rt_timer
,
805 qemu_get_clock(rt_clock
) + 1000);
809 static void icount_adjust_vm(void * opaque
)
811 qemu_mod_timer(icount_vm_timer
,
812 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
816 static void init_icount_adjust(void)
818 /* Have both realtime and virtual time triggers for speed adjustment.
819 The realtime trigger catches emulated time passing too slowly,
820 the virtual time trigger catches emulated time passing too fast.
821 Realtime triggers occur even when idle, so use them less frequently
823 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
824 qemu_mod_timer(icount_rt_timer
,
825 qemu_get_clock(rt_clock
) + 1000);
826 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
827 qemu_mod_timer(icount_vm_timer
,
828 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
831 static struct qemu_alarm_timer alarm_timers
[] = {
834 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
835 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
836 /* HPET - if available - is preferred */
837 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
838 /* ...otherwise try RTC */
839 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
841 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
843 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
844 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
845 {"win32", 0, win32_start_timer
,
846 win32_stop_timer
, NULL
, &alarm_win32_data
},
851 static void show_available_alarms(void)
855 printf("Available alarm timers, in order of precedence:\n");
856 for (i
= 0; alarm_timers
[i
].name
; i
++)
857 printf("%s\n", alarm_timers
[i
].name
);
860 static void configure_alarms(char const *opt
)
864 int count
= ARRAY_SIZE(alarm_timers
) - 1;
867 struct qemu_alarm_timer tmp
;
869 if (!strcmp(opt
, "?")) {
870 show_available_alarms();
876 /* Reorder the array */
877 name
= strtok(arg
, ",");
879 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
880 if (!strcmp(alarm_timers
[i
].name
, name
))
885 fprintf(stderr
, "Unknown clock %s\n", name
);
894 tmp
= alarm_timers
[i
];
895 alarm_timers
[i
] = alarm_timers
[cur
];
896 alarm_timers
[cur
] = tmp
;
900 name
= strtok(NULL
, ",");
906 /* Disable remaining timers */
907 for (i
= cur
; i
< count
; i
++)
908 alarm_timers
[i
].name
= NULL
;
910 show_available_alarms();
918 static QEMUTimer
*active_timers
[2];
920 static QEMUClock
*qemu_new_clock(int type
)
923 clock
= qemu_mallocz(sizeof(QEMUClock
));
928 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
932 ts
= qemu_mallocz(sizeof(QEMUTimer
));
939 void qemu_free_timer(QEMUTimer
*ts
)
944 /* stop a timer, but do not dealloc it */
945 void qemu_del_timer(QEMUTimer
*ts
)
949 /* NOTE: this code must be signal safe because
950 qemu_timer_expired() can be called from a signal. */
951 pt
= &active_timers
[ts
->clock
->type
];
964 /* modify the current timer so that it will be fired when current_time
965 >= expire_time. The corresponding callback will be called. */
966 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
972 /* add the timer in the sorted list */
973 /* NOTE: this code must be signal safe because
974 qemu_timer_expired() can be called from a signal. */
975 pt
= &active_timers
[ts
->clock
->type
];
980 if (t
->expire_time
> expire_time
)
984 ts
->expire_time
= expire_time
;
988 /* Rearm if necessary */
989 if (pt
== &active_timers
[ts
->clock
->type
]) {
990 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
991 qemu_rearm_alarm_timer(alarm_timer
);
993 /* Interrupt execution to force deadline recalculation. */
999 int qemu_timer_pending(QEMUTimer
*ts
)
1002 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1009 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1013 return (timer_head
->expire_time
<= current_time
);
1016 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1022 if (!ts
|| ts
->expire_time
> current_time
)
1024 /* remove timer from the list before calling the callback */
1025 *ptimer_head
= ts
->next
;
1028 /* run the callback (the timer list can be modified) */
1033 int64_t qemu_get_clock(QEMUClock
*clock
)
1035 switch(clock
->type
) {
1036 case QEMU_TIMER_REALTIME
:
1037 return get_clock() / 1000000;
1039 case QEMU_TIMER_VIRTUAL
:
1041 return cpu_get_icount();
1043 return cpu_get_clock();
1048 static void init_timers(void)
1051 ticks_per_sec
= QEMU_TIMER_BASE
;
1052 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1053 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1057 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1059 uint64_t expire_time
;
1061 if (qemu_timer_pending(ts
)) {
1062 expire_time
= ts
->expire_time
;
1066 qemu_put_be64(f
, expire_time
);
1069 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1071 uint64_t expire_time
;
1073 expire_time
= qemu_get_be64(f
);
1074 if (expire_time
!= -1) {
1075 qemu_mod_timer(ts
, expire_time
);
1081 static void timer_save(QEMUFile
*f
, void *opaque
)
1083 if (cpu_ticks_enabled
) {
1084 hw_error("cannot save state if virtual timers are running");
1086 qemu_put_be64(f
, cpu_ticks_offset
);
1087 qemu_put_be64(f
, ticks_per_sec
);
1088 qemu_put_be64(f
, cpu_clock_offset
);
1091 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1093 if (version_id
!= 1 && version_id
!= 2)
1095 if (cpu_ticks_enabled
) {
1098 cpu_ticks_offset
=qemu_get_be64(f
);
1099 ticks_per_sec
=qemu_get_be64(f
);
1100 if (version_id
== 2) {
1101 cpu_clock_offset
=qemu_get_be64(f
);
1106 static void qemu_event_increment(void);
1109 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1110 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1113 static void host_alarm_handler(int host_signum
)
1117 #define DISP_FREQ 1000
1119 static int64_t delta_min
= INT64_MAX
;
1120 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1122 ti
= qemu_get_clock(vm_clock
);
1123 if (last_clock
!= 0) {
1124 delta
= ti
- last_clock
;
1125 if (delta
< delta_min
)
1127 if (delta
> delta_max
)
1130 if (++count
== DISP_FREQ
) {
1131 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1132 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1133 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1134 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1135 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1137 delta_min
= INT64_MAX
;
1145 if (alarm_has_dynticks(alarm_timer
) ||
1147 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1148 qemu_get_clock(vm_clock
))) ||
1149 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1150 qemu_get_clock(rt_clock
))) {
1151 qemu_event_increment();
1152 if (alarm_timer
) alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1154 #ifndef CONFIG_IOTHREAD
1156 /* stop the currently executing cpu because a timer occured */
1159 if (next_cpu
->kqemu_enabled
) {
1160 kqemu_cpu_interrupt(next_cpu
);
1165 timer_alarm_pending
= 1;
1166 qemu_notify_event();
1170 static int64_t qemu_next_deadline(void)
1174 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1175 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1176 qemu_get_clock(vm_clock
);
1178 /* To avoid problems with overflow limit this to 2^32. */
1188 #if defined(__linux__) || defined(_WIN32)
1189 static uint64_t qemu_next_deadline_dyntick(void)
1197 delta
= (qemu_next_deadline() + 999) / 1000;
1199 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1200 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1201 qemu_get_clock(rt_clock
))*1000;
1202 if (rtdelta
< delta
)
1206 if (delta
< MIN_TIMER_REARM_US
)
1207 delta
= MIN_TIMER_REARM_US
;
1215 /* Sets a specific flag */
1216 static int fcntl_setfl(int fd
, int flag
)
1220 flags
= fcntl(fd
, F_GETFL
);
1224 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1230 #if defined(__linux__)
1232 #define RTC_FREQ 1024
1234 static void enable_sigio_timer(int fd
)
1236 struct sigaction act
;
1239 sigfillset(&act
.sa_mask
);
1241 act
.sa_handler
= host_alarm_handler
;
1243 sigaction(SIGIO
, &act
, NULL
);
1244 fcntl_setfl(fd
, O_ASYNC
);
1245 fcntl(fd
, F_SETOWN
, getpid());
1248 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1250 struct hpet_info info
;
1253 fd
= open("/dev/hpet", O_RDONLY
);
1258 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1260 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1261 "error, but for better emulation accuracy type:\n"
1262 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1266 /* Check capabilities */
1267 r
= ioctl(fd
, HPET_INFO
, &info
);
1271 /* Enable periodic mode */
1272 r
= ioctl(fd
, HPET_EPI
, 0);
1273 if (info
.hi_flags
&& (r
< 0))
1276 /* Enable interrupt */
1277 r
= ioctl(fd
, HPET_IE_ON
, 0);
1281 enable_sigio_timer(fd
);
1282 t
->priv
= (void *)(long)fd
;
1290 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1292 int fd
= (long)t
->priv
;
1297 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1300 unsigned long current_rtc_freq
= 0;
1302 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1305 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1306 if (current_rtc_freq
!= RTC_FREQ
&&
1307 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1308 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1309 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1310 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1313 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1319 enable_sigio_timer(rtc_fd
);
1321 t
->priv
= (void *)(long)rtc_fd
;
1326 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1328 int rtc_fd
= (long)t
->priv
;
1333 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1337 struct sigaction act
;
1339 sigfillset(&act
.sa_mask
);
1341 act
.sa_handler
= host_alarm_handler
;
1343 sigaction(SIGALRM
, &act
, NULL
);
1346 * Initialize ev struct to 0 to avoid valgrind complaining
1347 * about uninitialized data in timer_create call
1349 memset(&ev
, 0, sizeof(ev
));
1350 ev
.sigev_value
.sival_int
= 0;
1351 ev
.sigev_notify
= SIGEV_SIGNAL
;
1352 ev
.sigev_signo
= SIGALRM
;
1354 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1355 perror("timer_create");
1357 /* disable dynticks */
1358 fprintf(stderr
, "Dynamic Ticks disabled\n");
1363 t
->priv
= (void *)(long)host_timer
;
1368 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1370 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1372 timer_delete(host_timer
);
1375 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1377 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1378 struct itimerspec timeout
;
1379 int64_t nearest_delta_us
= INT64_MAX
;
1382 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1383 !active_timers
[QEMU_TIMER_VIRTUAL
])
1386 nearest_delta_us
= qemu_next_deadline_dyntick();
1388 /* check whether a timer is already running */
1389 if (timer_gettime(host_timer
, &timeout
)) {
1391 fprintf(stderr
, "Internal timer error: aborting\n");
1394 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1395 if (current_us
&& current_us
<= nearest_delta_us
)
1398 timeout
.it_interval
.tv_sec
= 0;
1399 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1400 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1401 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1402 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1404 fprintf(stderr
, "Internal timer error: aborting\n");
1409 #endif /* defined(__linux__) */
1411 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1413 struct sigaction act
;
1414 struct itimerval itv
;
1418 sigfillset(&act
.sa_mask
);
1420 act
.sa_handler
= host_alarm_handler
;
1422 sigaction(SIGALRM
, &act
, NULL
);
1424 itv
.it_interval
.tv_sec
= 0;
1425 /* for i386 kernel 2.6 to get 1 ms */
1426 itv
.it_interval
.tv_usec
= 999;
1427 itv
.it_value
.tv_sec
= 0;
1428 itv
.it_value
.tv_usec
= 10 * 1000;
1430 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1437 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1439 struct itimerval itv
;
1441 memset(&itv
, 0, sizeof(itv
));
1442 setitimer(ITIMER_REAL
, &itv
, NULL
);
1445 #endif /* !defined(_WIN32) */
1450 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1453 struct qemu_alarm_win32
*data
= t
->priv
;
1456 memset(&tc
, 0, sizeof(tc
));
1457 timeGetDevCaps(&tc
, sizeof(tc
));
1459 if (data
->period
< tc
.wPeriodMin
)
1460 data
->period
= tc
.wPeriodMin
;
1462 timeBeginPeriod(data
->period
);
1464 flags
= TIME_CALLBACK_FUNCTION
;
1465 if (alarm_has_dynticks(t
))
1466 flags
|= TIME_ONESHOT
;
1468 flags
|= TIME_PERIODIC
;
1470 data
->timerId
= timeSetEvent(1, // interval (ms)
1471 data
->period
, // resolution
1472 host_alarm_handler
, // function
1473 (DWORD
)t
, // parameter
1476 if (!data
->timerId
) {
1477 perror("Failed to initialize win32 alarm timer");
1478 timeEndPeriod(data
->period
);
1485 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1487 struct qemu_alarm_win32
*data
= t
->priv
;
1489 timeKillEvent(data
->timerId
);
1490 timeEndPeriod(data
->period
);
1493 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1495 struct qemu_alarm_win32
*data
= t
->priv
;
1496 uint64_t nearest_delta_us
;
1498 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1499 !active_timers
[QEMU_TIMER_VIRTUAL
])
1502 nearest_delta_us
= qemu_next_deadline_dyntick();
1503 nearest_delta_us
/= 1000;
1505 timeKillEvent(data
->timerId
);
1507 data
->timerId
= timeSetEvent(1,
1511 TIME_ONESHOT
| TIME_PERIODIC
);
1513 if (!data
->timerId
) {
1514 perror("Failed to re-arm win32 alarm timer");
1516 timeEndPeriod(data
->period
);
1523 static int init_timer_alarm(void)
1525 struct qemu_alarm_timer
*t
= NULL
;
1528 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1529 t
= &alarm_timers
[i
];
1549 static void quit_timers(void)
1551 alarm_timer
->stop(alarm_timer
);
1555 /***********************************************************/
1556 /* host time/date access */
1557 void qemu_get_timedate(struct tm
*tm
, int offset
)
1564 if (rtc_date_offset
== -1) {
1568 ret
= localtime(&ti
);
1570 ti
-= rtc_date_offset
;
1574 memcpy(tm
, ret
, sizeof(struct tm
));
1577 int qemu_timedate_diff(struct tm
*tm
)
1581 if (rtc_date_offset
== -1)
1583 seconds
= mktimegm(tm
);
1585 seconds
= mktime(tm
);
1587 seconds
= mktimegm(tm
) + rtc_date_offset
;
1589 return seconds
- time(NULL
);
1593 static void socket_cleanup(void)
1598 static int socket_init(void)
1603 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1605 err
= WSAGetLastError();
1606 fprintf(stderr
, "WSAStartup: %d\n", err
);
1609 atexit(socket_cleanup
);
1614 /***********************************************************/
1615 /* Bluetooth support */
1618 static struct HCIInfo
*hci_table
[MAX_NICS
];
1620 static struct bt_vlan_s
{
1621 struct bt_scatternet_s net
;
1623 struct bt_vlan_s
*next
;
1626 /* find or alloc a new bluetooth "VLAN" */
1627 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1629 struct bt_vlan_s
**pvlan
, *vlan
;
1630 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1634 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1636 pvlan
= &first_bt_vlan
;
1637 while (*pvlan
!= NULL
)
1638 pvlan
= &(*pvlan
)->next
;
1643 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1647 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1652 static struct HCIInfo null_hci
= {
1653 .cmd_send
= null_hci_send
,
1654 .sco_send
= null_hci_send
,
1655 .acl_send
= null_hci_send
,
1656 .bdaddr_set
= null_hci_addr_set
,
1659 struct HCIInfo
*qemu_next_hci(void)
1661 if (cur_hci
== nb_hcis
)
1664 return hci_table
[cur_hci
++];
1667 static struct HCIInfo
*hci_init(const char *str
)
1670 struct bt_scatternet_s
*vlan
= 0;
1672 if (!strcmp(str
, "null"))
1675 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
1677 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
1678 else if (!strncmp(str
, "hci", 3)) {
1681 if (!strncmp(str
+ 3, ",vlan=", 6)) {
1682 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
1687 vlan
= qemu_find_bt_vlan(0);
1689 return bt_new_hci(vlan
);
1692 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
1697 static int bt_hci_parse(const char *str
)
1699 struct HCIInfo
*hci
;
1702 if (nb_hcis
>= MAX_NICS
) {
1703 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
1707 hci
= hci_init(str
);
1716 bdaddr
.b
[5] = 0x56 + nb_hcis
;
1717 hci
->bdaddr_set(hci
, bdaddr
.b
);
1719 hci_table
[nb_hcis
++] = hci
;
1724 static void bt_vhci_add(int vlan_id
)
1726 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
1729 fprintf(stderr
, "qemu: warning: adding a VHCI to "
1730 "an empty scatternet %i\n", vlan_id
);
1732 bt_vhci_init(bt_new_hci(vlan
));
1735 static struct bt_device_s
*bt_device_add(const char *opt
)
1737 struct bt_scatternet_s
*vlan
;
1739 char *endp
= strstr(opt
, ",vlan=");
1740 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
1743 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
1746 vlan_id
= strtol(endp
+ 6, &endp
, 0);
1748 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
1753 vlan
= qemu_find_bt_vlan(vlan_id
);
1756 fprintf(stderr
, "qemu: warning: adding a slave device to "
1757 "an empty scatternet %i\n", vlan_id
);
1759 if (!strcmp(devname
, "keyboard"))
1760 return bt_keyboard_init(vlan
);
1762 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
1766 static int bt_parse(const char *opt
)
1768 const char *endp
, *p
;
1771 if (strstart(opt
, "hci", &endp
)) {
1772 if (!*endp
|| *endp
== ',') {
1774 if (!strstart(endp
, ",vlan=", 0))
1777 return bt_hci_parse(opt
);
1779 } else if (strstart(opt
, "vhci", &endp
)) {
1780 if (!*endp
|| *endp
== ',') {
1782 if (strstart(endp
, ",vlan=", &p
)) {
1783 vlan
= strtol(p
, (char **) &endp
, 0);
1785 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
1789 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
1798 } else if (strstart(opt
, "device:", &endp
))
1799 return !bt_device_add(endp
);
1801 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
1805 /***********************************************************/
1806 /* QEMU Block devices */
1808 #define HD_ALIAS "index=%d,media=disk"
1809 #define CDROM_ALIAS "index=2,media=cdrom"
1810 #define FD_ALIAS "index=%d,if=floppy"
1811 #define PFLASH_ALIAS "if=pflash"
1812 #define MTD_ALIAS "if=mtd"
1813 #define SD_ALIAS "index=0,if=sd"
1815 static QemuOptsList drive_opt_list
= {
1817 .head
= TAILQ_HEAD_INITIALIZER(drive_opt_list
.head
),
1821 .type
= QEMU_OPT_NUMBER
,
1822 .help
= "bus number",
1825 .type
= QEMU_OPT_NUMBER
,
1826 .help
= "unit number (i.e. lun for scsi)",
1829 .type
= QEMU_OPT_STRING
,
1830 .help
= "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
1833 .type
= QEMU_OPT_NUMBER
,
1836 .type
= QEMU_OPT_NUMBER
,
1837 .help
= "number of cylinders (ide disk geometry)",
1840 .type
= QEMU_OPT_NUMBER
,
1841 .help
= "number of heads (ide disk geometry)",
1844 .type
= QEMU_OPT_NUMBER
,
1845 .help
= "number of sectors (ide disk geometry)",
1848 .type
= QEMU_OPT_STRING
,
1849 .help
= "chs translation (auto, lba. none)",
1852 .type
= QEMU_OPT_STRING
,
1853 .help
= "media type (disk, cdrom)",
1856 .type
= QEMU_OPT_BOOL
,
1859 .type
= QEMU_OPT_STRING
,
1860 .help
= "disk image",
1863 .type
= QEMU_OPT_STRING
,
1864 .help
= "host cache usage (none, writeback, writethrough)",
1867 .type
= QEMU_OPT_STRING
,
1868 .help
= "disk format (raw, qcow2, ...)",
1871 .type
= QEMU_OPT_STRING
,
1874 .type
= QEMU_OPT_STRING
,
1877 .type
= QEMU_OPT_STRING
,
1878 .help
= "pci address (virtio only)",
1881 .type
= QEMU_OPT_BOOL
,
1882 .help
= "make this a boot drive",
1884 { /* end if list */ }
1888 QemuOpts
*drive_add(const char *file
, const char *fmt
, ...)
1895 vsnprintf(optstr
, sizeof(optstr
), fmt
, ap
);
1898 opts
= qemu_opts_parse(&drive_opt_list
, optstr
, NULL
);
1900 fprintf(stderr
, "%s: huh? duplicate? (%s)\n",
1901 __FUNCTION__
, optstr
);
1905 qemu_opt_set(opts
, "file", file
);
1909 DriveInfo
*drive_get(BlockInterfaceType type
, int bus
, int unit
)
1913 /* seek interface, bus and unit */
1915 TAILQ_FOREACH(dinfo
, &drives
, next
) {
1916 if (dinfo
->type
== type
&&
1917 dinfo
->bus
== bus
&&
1918 dinfo
->unit
== unit
)
1925 DriveInfo
*drive_get_by_id(char *id
)
1929 TAILQ_FOREACH(dinfo
, &drives
, next
) {
1930 if (strcmp(id
, dinfo
->id
))
1937 int drive_get_max_bus(BlockInterfaceType type
)
1943 TAILQ_FOREACH(dinfo
, &drives
, next
) {
1944 if(dinfo
->type
== type
&&
1945 dinfo
->bus
> max_bus
)
1946 max_bus
= dinfo
->bus
;
1951 const char *drive_get_serial(BlockDriverState
*bdrv
)
1955 TAILQ_FOREACH(dinfo
, &drives
, next
) {
1956 if (dinfo
->bdrv
== bdrv
)
1957 return dinfo
->serial
;
1963 BlockInterfaceErrorAction
drive_get_onerror(BlockDriverState
*bdrv
)
1967 TAILQ_FOREACH(dinfo
, &drives
, next
) {
1968 if (dinfo
->bdrv
== bdrv
)
1969 return dinfo
->onerror
;
1972 return BLOCK_ERR_STOP_ENOSPC
;
1975 static void bdrv_format_print(void *opaque
, const char *name
)
1977 fprintf(stderr
, " %s", name
);
1980 void drive_uninit(BlockDriverState
*bdrv
)
1984 TAILQ_FOREACH(dinfo
, &drives
, next
) {
1985 if (dinfo
->bdrv
!= bdrv
)
1987 qemu_opts_del(dinfo
->opts
);
1988 TAILQ_REMOVE(&drives
, dinfo
, next
);
1994 DriveInfo
*drive_init(QemuOpts
*opts
, void *opaque
,
1998 const char *file
= NULL
;
2001 const char *mediastr
= "";
2002 BlockInterfaceType type
;
2003 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
2004 int bus_id
, unit_id
;
2005 int cyls
, heads
, secs
, translation
;
2006 BlockDriver
*drv
= NULL
;
2007 QEMUMachine
*machine
= opaque
;
2011 int bdrv_flags
, onerror
;
2012 const char *devaddr
;
2019 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2022 if (machine
->use_scsi
) {
2024 max_devs
= MAX_SCSI_DEVS
;
2025 pstrcpy(devname
, sizeof(devname
), "scsi");
2028 max_devs
= MAX_IDE_DEVS
;
2029 pstrcpy(devname
, sizeof(devname
), "ide");
2033 /* extract parameters */
2034 bus_id
= qemu_opt_get_number(opts
, "bus", 0);
2035 unit_id
= qemu_opt_get_number(opts
, "unit", -1);
2036 index
= qemu_opt_get_number(opts
, "index", -1);
2038 cyls
= qemu_opt_get_number(opts
, "cyls", 0);
2039 heads
= qemu_opt_get_number(opts
, "heads", 0);
2040 secs
= qemu_opt_get_number(opts
, "secs", 0);
2042 snapshot
= qemu_opt_get_bool(opts
, "snapshot", 0);
2044 file
= qemu_opt_get(opts
, "file");
2045 serial
= qemu_opt_get(opts
, "serial");
2047 if ((buf
= qemu_opt_get(opts
, "if")) != NULL
) {
2048 pstrcpy(devname
, sizeof(devname
), buf
);
2049 if (!strcmp(buf
, "ide")) {
2051 max_devs
= MAX_IDE_DEVS
;
2052 } else if (!strcmp(buf
, "scsi")) {
2054 max_devs
= MAX_SCSI_DEVS
;
2055 } else if (!strcmp(buf
, "floppy")) {
2058 } else if (!strcmp(buf
, "pflash")) {
2061 } else if (!strcmp(buf
, "mtd")) {
2064 } else if (!strcmp(buf
, "sd")) {
2067 } else if (!strcmp(buf
, "virtio")) {
2070 } else if (!strcmp(buf
, "xen")) {
2074 fprintf(stderr
, "qemu: unsupported bus type '%s'\n", buf
);
2079 if (cyls
|| heads
|| secs
) {
2080 if (cyls
< 1 || cyls
> 16383) {
2081 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", buf
);
2084 if (heads
< 1 || heads
> 16) {
2085 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", buf
);
2088 if (secs
< 1 || secs
> 63) {
2089 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", buf
);
2094 if ((buf
= qemu_opt_get(opts
, "trans")) != NULL
) {
2097 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2101 if (!strcmp(buf
, "none"))
2102 translation
= BIOS_ATA_TRANSLATION_NONE
;
2103 else if (!strcmp(buf
, "lba"))
2104 translation
= BIOS_ATA_TRANSLATION_LBA
;
2105 else if (!strcmp(buf
, "auto"))
2106 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2108 fprintf(stderr
, "qemu: '%s' invalid translation type\n", buf
);
2113 if ((buf
= qemu_opt_get(opts
, "media")) != NULL
) {
2114 if (!strcmp(buf
, "disk")) {
2116 } else if (!strcmp(buf
, "cdrom")) {
2117 if (cyls
|| secs
|| heads
) {
2119 "qemu: '%s' invalid physical CHS format\n", buf
);
2122 media
= MEDIA_CDROM
;
2124 fprintf(stderr
, "qemu: '%s' invalid media\n", buf
);
2129 if ((buf
= qemu_opt_get(opts
, "cache")) != NULL
) {
2130 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2132 else if (!strcmp(buf
, "writethrough"))
2134 else if (!strcmp(buf
, "writeback"))
2137 fprintf(stderr
, "qemu: invalid cache option\n");
2142 if ((buf
= qemu_opt_get(opts
, "format")) != NULL
) {
2143 if (strcmp(buf
, "?") == 0) {
2144 fprintf(stderr
, "qemu: Supported formats:");
2145 bdrv_iterate_format(bdrv_format_print
, NULL
);
2146 fprintf(stderr
, "\n");
2149 drv
= bdrv_find_format(buf
);
2151 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2156 is_extboot
= qemu_opt_get_bool(opts
, "boot", 0);
2157 if (is_extboot
&& extboot_drive
) {
2158 fprintf(stderr
, "qemu: two bootable drives specified\n");
2162 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2163 if ((buf
= qemu_opt_get(opts
, "werror")) != NULL
) {
2164 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2165 fprintf(stderr
, "werror is no supported by this format\n");
2168 if (!strcmp(buf
, "ignore"))
2169 onerror
= BLOCK_ERR_IGNORE
;
2170 else if (!strcmp(buf
, "enospc"))
2171 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2172 else if (!strcmp(buf
, "stop"))
2173 onerror
= BLOCK_ERR_STOP_ANY
;
2174 else if (!strcmp(buf
, "report"))
2175 onerror
= BLOCK_ERR_REPORT
;
2177 fprintf(stderr
, "qemu: '%s' invalid write error action\n", buf
);
2182 if ((devaddr
= qemu_opt_get(opts
, "addr")) != NULL
) {
2183 if (type
!= IF_VIRTIO
) {
2184 fprintf(stderr
, "addr is not supported\n");
2189 /* compute bus and unit according index */
2192 if (bus_id
!= 0 || unit_id
!= -1) {
2194 "qemu: index cannot be used with bus and unit\n");
2202 unit_id
= index
% max_devs
;
2203 bus_id
= index
/ max_devs
;
2207 /* if user doesn't specify a unit_id,
2208 * try to find the first free
2211 if (unit_id
== -1) {
2213 while (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2215 if (max_devs
&& unit_id
>= max_devs
) {
2216 unit_id
-= max_devs
;
2224 if (max_devs
&& unit_id
>= max_devs
) {
2225 fprintf(stderr
, "qemu: unit %d too big (max is %d)\n",
2226 unit_id
, max_devs
- 1);
2231 * ignore multiple definitions
2234 if (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2241 dinfo
= qemu_mallocz(sizeof(*dinfo
));
2242 if ((buf
= qemu_opt_get(opts
, "id")) != NULL
) {
2243 dinfo
->id
= qemu_strdup(buf
);
2245 /* no id supplied -> create one */
2246 dinfo
->id
= qemu_mallocz(32);
2247 if (type
== IF_IDE
|| type
== IF_SCSI
)
2248 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2250 snprintf(dinfo
->id
, 32, "%s%i%s%i",
2251 devname
, bus_id
, mediastr
, unit_id
);
2253 snprintf(dinfo
->id
, 32, "%s%s%i",
2254 devname
, mediastr
, unit_id
);
2256 dinfo
->bdrv
= bdrv_new(dinfo
->id
);
2257 dinfo
->devaddr
= devaddr
;
2259 dinfo
->bus
= bus_id
;
2260 dinfo
->unit
= unit_id
;
2261 dinfo
->onerror
= onerror
;
2264 strncpy(dinfo
->serial
, serial
, sizeof(serial
));
2265 TAILQ_INSERT_TAIL(&drives
, dinfo
, next
);
2267 extboot_drive
= dinfo
;
2277 bdrv_set_geometry_hint(dinfo
->bdrv
, cyls
, heads
, secs
);
2278 bdrv_set_translation_hint(dinfo
->bdrv
, translation
);
2282 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_CDROM
);
2287 /* FIXME: This isn't really a floppy, but it's a reasonable
2290 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_FLOPPY
);
2305 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2306 cache
= 2; /* always use write-back with snapshot */
2308 if (cache
== 0) /* no caching */
2309 bdrv_flags
|= BDRV_O_NOCACHE
;
2310 else if (cache
== 2) /* write-back */
2311 bdrv_flags
|= BDRV_O_CACHE_WB
;
2312 if (bdrv_open2(dinfo
->bdrv
, file
, bdrv_flags
, drv
) < 0) {
2313 fprintf(stderr
, "qemu: could not open disk image %s\n",
2317 if (bdrv_key_required(dinfo
->bdrv
))
2323 static int drive_init_func(QemuOpts
*opts
, void *opaque
)
2325 QEMUMachine
*machine
= opaque
;
2326 int fatal_error
= 0;
2328 if (drive_init(opts
, machine
, &fatal_error
) == NULL
) {
2335 static int drive_enable_snapshot(QemuOpts
*opts
, void *opaque
)
2337 if (NULL
== qemu_opt_get(opts
, "snapshot")) {
2338 qemu_opt_set(opts
, "snapshot", "on");
2343 void qemu_register_boot_set(QEMUBootSetHandler
*func
, void *opaque
)
2345 boot_set_handler
= func
;
2346 boot_set_opaque
= opaque
;
2349 int qemu_boot_set(const char *boot_devices
)
2351 if (!boot_set_handler
) {
2354 return boot_set_handler(boot_set_opaque
, boot_devices
);
2357 static int parse_bootdevices(char *devices
)
2359 /* We just do some generic consistency checks */
2363 for (p
= devices
; *p
!= '\0'; p
++) {
2364 /* Allowed boot devices are:
2365 * a-b: floppy disk drives
2366 * c-f: IDE disk drives
2367 * g-m: machine implementation dependant drives
2368 * n-p: network devices
2369 * It's up to each machine implementation to check if the given boot
2370 * devices match the actual hardware implementation and firmware
2373 if (*p
< 'a' || *p
> 'p') {
2374 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
2377 if (bitmap
& (1 << (*p
- 'a'))) {
2378 fprintf(stderr
, "Boot device '%c' was given twice\n", *p
);
2381 bitmap
|= 1 << (*p
- 'a');
2386 static void restore_boot_devices(void *opaque
)
2388 char *standard_boot_devices
= opaque
;
2390 qemu_boot_set(standard_boot_devices
);
2392 qemu_unregister_reset(restore_boot_devices
, standard_boot_devices
);
2393 qemu_free(standard_boot_devices
);
2396 static void numa_add(const char *optarg
)
2400 unsigned long long value
, endvalue
;
2403 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2404 if (!strcmp(option
, "node")) {
2405 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2406 nodenr
= nb_numa_nodes
;
2408 nodenr
= strtoull(option
, NULL
, 10);
2411 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2412 node_mem
[nodenr
] = 0;
2414 value
= strtoull(option
, &endptr
, 0);
2416 case 0: case 'M': case 'm':
2423 node_mem
[nodenr
] = value
;
2425 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2426 node_cpumask
[nodenr
] = 0;
2428 value
= strtoull(option
, &endptr
, 10);
2431 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2433 if (*endptr
== '-') {
2434 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2435 if (endvalue
>= 63) {
2438 "only 63 CPUs in NUMA mode supported.\n");
2440 value
= (1 << (endvalue
+ 1)) - (1 << value
);
2445 node_cpumask
[nodenr
] = value
;
2452 /***********************************************************/
2455 static USBPort
*used_usb_ports
;
2456 static USBPort
*free_usb_ports
;
2458 /* ??? Maybe change this to register a hub to keep track of the topology. */
2459 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
2460 usb_attachfn attach
)
2462 port
->opaque
= opaque
;
2463 port
->index
= index
;
2464 port
->attach
= attach
;
2465 port
->next
= free_usb_ports
;
2466 free_usb_ports
= port
;
2469 int usb_device_add_dev(USBDevice
*dev
)
2473 /* Find a USB port to add the device to. */
2474 port
= free_usb_ports
;
2478 /* Create a new hub and chain it on. */
2479 free_usb_ports
= NULL
;
2480 port
->next
= used_usb_ports
;
2481 used_usb_ports
= port
;
2483 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
2484 usb_attach(port
, hub
);
2485 port
= free_usb_ports
;
2488 free_usb_ports
= port
->next
;
2489 port
->next
= used_usb_ports
;
2490 used_usb_ports
= port
;
2491 usb_attach(port
, dev
);
2495 static void usb_msd_password_cb(void *opaque
, int err
)
2497 USBDevice
*dev
= opaque
;
2500 usb_device_add_dev(dev
);
2502 dev
->handle_destroy(dev
);
2505 static int usb_device_add(const char *devname
, int is_hotplug
)
2510 if (!free_usb_ports
)
2513 if (strstart(devname
, "host:", &p
)) {
2514 dev
= usb_host_device_open(p
);
2515 } else if (!strcmp(devname
, "mouse")) {
2516 dev
= usb_mouse_init();
2517 } else if (!strcmp(devname
, "tablet")) {
2518 dev
= usb_tablet_init();
2519 } else if (!strcmp(devname
, "keyboard")) {
2520 dev
= usb_keyboard_init();
2521 } else if (strstart(devname
, "disk:", &p
)) {
2522 BlockDriverState
*bs
;
2524 dev
= usb_msd_init(p
);
2527 bs
= usb_msd_get_bdrv(dev
);
2528 if (bdrv_key_required(bs
)) {
2531 monitor_read_bdrv_key_start(cur_mon
, bs
, usb_msd_password_cb
,
2536 } else if (!strcmp(devname
, "wacom-tablet")) {
2537 dev
= usb_wacom_init();
2538 } else if (strstart(devname
, "serial:", &p
)) {
2539 dev
= usb_serial_init(p
);
2540 #ifdef CONFIG_BRLAPI
2541 } else if (!strcmp(devname
, "braille")) {
2542 dev
= usb_baum_init();
2544 } else if (strstart(devname
, "net:", &p
)) {
2547 if (net_client_init(NULL
, "nic", p
) < 0)
2549 nd_table
[nic
].model
= "usb";
2550 dev
= usb_net_init(&nd_table
[nic
]);
2551 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2552 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2553 bt_new_hci(qemu_find_bt_vlan(0)));
2560 return usb_device_add_dev(dev
);
2563 int usb_device_del_addr(int bus_num
, int addr
)
2569 if (!used_usb_ports
)
2575 lastp
= &used_usb_ports
;
2576 port
= used_usb_ports
;
2577 while (port
&& port
->dev
->addr
!= addr
) {
2578 lastp
= &port
->next
;
2586 *lastp
= port
->next
;
2587 usb_attach(port
, NULL
);
2588 dev
->handle_destroy(dev
);
2589 port
->next
= free_usb_ports
;
2590 free_usb_ports
= port
;
2594 static int usb_device_del(const char *devname
)
2599 if (strstart(devname
, "host:", &p
))
2600 return usb_host_device_close(p
);
2602 if (!used_usb_ports
)
2605 p
= strchr(devname
, '.');
2608 bus_num
= strtoul(devname
, NULL
, 0);
2609 addr
= strtoul(p
+ 1, NULL
, 0);
2611 return usb_device_del_addr(bus_num
, addr
);
2614 static int usb_parse(const char *cmdline
)
2616 return usb_device_add(cmdline
, 0);
2619 void do_usb_add(Monitor
*mon
, const char *devname
)
2621 usb_device_add(devname
, 1);
2624 void do_usb_del(Monitor
*mon
, const char *devname
)
2626 usb_device_del(devname
);
2629 void usb_info(Monitor
*mon
)
2633 const char *speed_str
;
2636 monitor_printf(mon
, "USB support not enabled\n");
2640 for (port
= used_usb_ports
; port
; port
= port
->next
) {
2644 switch(dev
->speed
) {
2648 case USB_SPEED_FULL
:
2651 case USB_SPEED_HIGH
:
2658 monitor_printf(mon
, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2659 0, dev
->addr
, speed_str
, dev
->devname
);
2663 /***********************************************************/
2664 /* PCMCIA/Cardbus */
2666 static struct pcmcia_socket_entry_s
{
2667 PCMCIASocket
*socket
;
2668 struct pcmcia_socket_entry_s
*next
;
2669 } *pcmcia_sockets
= 0;
2671 void pcmcia_socket_register(PCMCIASocket
*socket
)
2673 struct pcmcia_socket_entry_s
*entry
;
2675 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2676 entry
->socket
= socket
;
2677 entry
->next
= pcmcia_sockets
;
2678 pcmcia_sockets
= entry
;
2681 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2683 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2685 ptr
= &pcmcia_sockets
;
2686 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2687 if (entry
->socket
== socket
) {
2693 void pcmcia_info(Monitor
*mon
)
2695 struct pcmcia_socket_entry_s
*iter
;
2697 if (!pcmcia_sockets
)
2698 monitor_printf(mon
, "No PCMCIA sockets\n");
2700 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2701 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2702 iter
->socket
->attached
? iter
->socket
->card_string
:
2706 /***********************************************************/
2707 /* register display */
2709 struct DisplayAllocator default_allocator
= {
2710 defaultallocator_create_displaysurface
,
2711 defaultallocator_resize_displaysurface
,
2712 defaultallocator_free_displaysurface
2715 void register_displaystate(DisplayState
*ds
)
2725 DisplayState
*get_displaystate(void)
2727 return display_state
;
2730 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
2732 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
2733 return ds
->allocator
;
2738 static void dumb_display_init(void)
2740 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
2741 ds
->allocator
= &default_allocator
;
2742 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
2743 register_displaystate(ds
);
2746 /***********************************************************/
2749 typedef struct IOHandlerRecord
{
2751 IOCanRWHandler
*fd_read_poll
;
2753 IOHandler
*fd_write
;
2756 /* temporary data */
2758 struct IOHandlerRecord
*next
;
2761 static IOHandlerRecord
*first_io_handler
;
2763 /* XXX: fd_read_poll should be suppressed, but an API change is
2764 necessary in the character devices to suppress fd_can_read(). */
2765 int qemu_set_fd_handler2(int fd
,
2766 IOCanRWHandler
*fd_read_poll
,
2768 IOHandler
*fd_write
,
2771 IOHandlerRecord
**pioh
, *ioh
;
2773 if (!fd_read
&& !fd_write
) {
2774 pioh
= &first_io_handler
;
2779 if (ioh
->fd
== fd
) {
2786 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
2790 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
2791 ioh
->next
= first_io_handler
;
2792 first_io_handler
= ioh
;
2795 ioh
->fd_read_poll
= fd_read_poll
;
2796 ioh
->fd_read
= fd_read
;
2797 ioh
->fd_write
= fd_write
;
2798 ioh
->opaque
= opaque
;
2801 qemu_notify_event();
2805 int qemu_set_fd_handler(int fd
,
2807 IOHandler
*fd_write
,
2810 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
2814 /***********************************************************/
2815 /* Polling handling */
2817 typedef struct PollingEntry
{
2820 struct PollingEntry
*next
;
2823 static PollingEntry
*first_polling_entry
;
2825 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
2827 PollingEntry
**ppe
, *pe
;
2828 pe
= qemu_mallocz(sizeof(PollingEntry
));
2830 pe
->opaque
= opaque
;
2831 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
2836 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
2838 PollingEntry
**ppe
, *pe
;
2839 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
2841 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
2849 /***********************************************************/
2850 /* Wait objects support */
2851 typedef struct WaitObjects
{
2853 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
2854 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
2855 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
2858 static WaitObjects wait_objects
= {0};
2860 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2862 WaitObjects
*w
= &wait_objects
;
2864 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
2866 w
->events
[w
->num
] = handle
;
2867 w
->func
[w
->num
] = func
;
2868 w
->opaque
[w
->num
] = opaque
;
2873 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2876 WaitObjects
*w
= &wait_objects
;
2879 for (i
= 0; i
< w
->num
; i
++) {
2880 if (w
->events
[i
] == handle
)
2883 w
->events
[i
] = w
->events
[i
+ 1];
2884 w
->func
[i
] = w
->func
[i
+ 1];
2885 w
->opaque
[i
] = w
->opaque
[i
+ 1];
2893 /***********************************************************/
2894 /* ram save/restore */
2896 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
2900 v
= qemu_get_byte(f
);
2903 if (qemu_get_buffer(f
, buf
, len
) != len
)
2907 v
= qemu_get_byte(f
);
2908 memset(buf
, v
, len
);
2914 if (qemu_file_has_error(f
))
2920 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
2925 if (qemu_get_be32(f
) != last_ram_offset
)
2927 for(i
= 0; i
< last_ram_offset
; i
+= TARGET_PAGE_SIZE
) {
2928 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
2930 ret
= ram_get_page(f
, qemu_get_ram_ptr(i
), TARGET_PAGE_SIZE
);
2937 #define BDRV_HASH_BLOCK_SIZE 1024
2938 #define IOBUF_SIZE 4096
2939 #define RAM_CBLOCK_MAGIC 0xfabe
2941 typedef struct RamDecompressState
{
2944 uint8_t buf
[IOBUF_SIZE
];
2945 } RamDecompressState
;
2947 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
2950 memset(s
, 0, sizeof(*s
));
2952 ret
= inflateInit(&s
->zstream
);
2958 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
2962 s
->zstream
.avail_out
= len
;
2963 s
->zstream
.next_out
= buf
;
2964 while (s
->zstream
.avail_out
> 0) {
2965 if (s
->zstream
.avail_in
== 0) {
2966 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
2968 clen
= qemu_get_be16(s
->f
);
2969 if (clen
> IOBUF_SIZE
)
2971 qemu_get_buffer(s
->f
, s
->buf
, clen
);
2972 s
->zstream
.avail_in
= clen
;
2973 s
->zstream
.next_in
= s
->buf
;
2975 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
2976 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
2983 static void ram_decompress_close(RamDecompressState
*s
)
2985 inflateEnd(&s
->zstream
);
2988 #define RAM_SAVE_FLAG_FULL 0x01
2989 #define RAM_SAVE_FLAG_COMPRESS 0x02
2990 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2991 #define RAM_SAVE_FLAG_PAGE 0x08
2992 #define RAM_SAVE_FLAG_EOS 0x10
2994 static int is_dup_page(uint8_t *page
, uint8_t ch
)
2996 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
2997 uint32_t *array
= (uint32_t *)page
;
3000 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
3001 if (array
[i
] != val
)
3008 static int ram_save_block(QEMUFile
*f
)
3010 static ram_addr_t current_addr
= 0;
3011 ram_addr_t saved_addr
= current_addr
;
3012 ram_addr_t addr
= 0;
3015 while (addr
< last_ram_offset
) {
3016 if (kvm_enabled() && current_addr
== 0) {
3018 r
= kvm_update_dirty_pages_log();
3020 fprintf(stderr
, "%s: update dirty pages log failed %d\n", __FUNCTION__
, r
);
3021 qemu_file_set_error(f
);
3025 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
3028 cpu_physical_memory_reset_dirty(current_addr
,
3029 current_addr
+ TARGET_PAGE_SIZE
,
3030 MIGRATION_DIRTY_FLAG
);
3032 p
= qemu_get_ram_ptr(current_addr
);
3034 if (is_dup_page(p
, *p
)) {
3035 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
3036 qemu_put_byte(f
, *p
);
3038 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
3039 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
3045 addr
+= TARGET_PAGE_SIZE
;
3046 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
3052 static uint64_t bytes_transferred
= 0;
3054 static ram_addr_t
ram_save_remaining(void)
3057 ram_addr_t count
= 0;
3059 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3060 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3067 uint64_t ram_bytes_remaining(void)
3069 return ram_save_remaining() * TARGET_PAGE_SIZE
;
3072 uint64_t ram_bytes_transferred(void)
3074 return bytes_transferred
;
3077 uint64_t ram_bytes_total(void)
3079 return last_ram_offset
;
3082 static int ram_save_live(QEMUFile
*f
, int stage
, void *opaque
)
3085 uint64_t bytes_transferred_last
;
3087 uint64_t expected_time
= 0;
3089 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX
) != 0) {
3090 qemu_file_set_error(f
);
3095 /* Make sure all dirty bits are set */
3096 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3097 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3098 cpu_physical_memory_set_dirty(addr
);
3101 /* Enable dirty memory tracking */
3102 cpu_physical_memory_set_dirty_tracking(1);
3104 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
3107 bytes_transferred_last
= bytes_transferred
;
3108 bwidth
= get_clock();
3110 while (!qemu_file_rate_limit(f
)) {
3113 ret
= ram_save_block(f
);
3114 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
3115 if (ret
== 0) /* no more blocks */
3119 bwidth
= get_clock() - bwidth
;
3120 bwidth
= (bytes_transferred
- bytes_transferred_last
) / bwidth
;
3122 /* if we haven't transferred anything this round, force expected_time to a
3123 * a very high value, but without crashing */
3127 /* try transferring iterative blocks of memory */
3131 /* flush all remaining blocks regardless of rate limiting */
3132 while (ram_save_block(f
) != 0) {
3133 bytes_transferred
+= TARGET_PAGE_SIZE
;
3135 cpu_physical_memory_set_dirty_tracking(0);
3138 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3140 expected_time
= ram_save_remaining() * TARGET_PAGE_SIZE
/ bwidth
;
3142 return (stage
== 2) && (expected_time
<= migrate_max_downtime());
3145 static int ram_load_dead(QEMUFile
*f
, void *opaque
)
3147 RamDecompressState s1
, *s
= &s1
;
3151 if (ram_decompress_open(s
, f
) < 0)
3153 for(i
= 0; i
< last_ram_offset
; i
+= BDRV_HASH_BLOCK_SIZE
) {
3154 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3156 if (ram_decompress_buf(s
, buf
, 1) < 0) {
3157 fprintf(stderr
, "Error while reading ram block header\n");
3161 if (ram_decompress_buf(s
, qemu_get_ram_ptr(i
),
3162 BDRV_HASH_BLOCK_SIZE
) < 0) {
3163 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
3168 printf("Error block header\n");
3172 ram_decompress_close(s
);
3177 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
3182 if (version_id
== 1)
3183 return ram_load_v1(f
, opaque
);
3185 if (version_id
== 2) {
3186 if (qemu_get_be32(f
) != last_ram_offset
)
3188 return ram_load_dead(f
, opaque
);
3191 if (version_id
!= 3)
3195 addr
= qemu_get_be64(f
);
3197 flags
= addr
& ~TARGET_PAGE_MASK
;
3198 addr
&= TARGET_PAGE_MASK
;
3200 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
3201 if (addr
!= last_ram_offset
)
3205 if (flags
& RAM_SAVE_FLAG_FULL
) {
3206 if (ram_load_dead(f
, opaque
) < 0)
3210 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
3211 uint8_t ch
= qemu_get_byte(f
);
3212 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
3215 (!kvm_enabled() || kvm_has_sync_mmu())) {
3216 madvise(qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
, MADV_DONTNEED
);
3219 } else if (flags
& RAM_SAVE_FLAG_PAGE
)
3220 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
3221 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
3226 void qemu_service_io(void)
3228 qemu_notify_event();
3231 /***********************************************************/
3232 /* bottom halves (can be seen as timers which expire ASAP) */
3243 static QEMUBH
*first_bh
= NULL
;
3245 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
3248 bh
= qemu_mallocz(sizeof(QEMUBH
));
3250 bh
->opaque
= opaque
;
3251 bh
->next
= first_bh
;
3256 int qemu_bh_poll(void)
3262 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3263 if (!bh
->deleted
&& bh
->scheduled
) {
3272 /* remove deleted bhs */
3286 void qemu_bh_schedule_idle(QEMUBH
*bh
)
3294 void qemu_bh_schedule(QEMUBH
*bh
)
3300 /* stop the currently executing CPU to execute the BH ASAP */
3301 qemu_notify_event();
3304 void qemu_bh_cancel(QEMUBH
*bh
)
3309 void qemu_bh_delete(QEMUBH
*bh
)
3315 static void qemu_bh_update_timeout(int *timeout
)
3319 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3320 if (!bh
->deleted
&& bh
->scheduled
) {
3322 /* idle bottom halves will be polled at least
3324 *timeout
= MIN(10, *timeout
);
3326 /* non-idle bottom halves will be executed
3335 /***********************************************************/
3336 /* machine registration */
3338 static QEMUMachine
*first_machine
= NULL
;
3339 QEMUMachine
*current_machine
= NULL
;
3341 int qemu_register_machine(QEMUMachine
*m
)
3344 pm
= &first_machine
;
3352 static QEMUMachine
*find_machine(const char *name
)
3356 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3357 if (!strcmp(m
->name
, name
))
3359 if (m
->alias
&& !strcmp(m
->alias
, name
))
3365 static QEMUMachine
*find_default_machine(void)
3369 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3370 if (m
->is_default
) {
3377 /***********************************************************/
3378 /* main execution loop */
3380 static void gui_update(void *opaque
)
3382 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3383 DisplayState
*ds
= opaque
;
3384 DisplayChangeListener
*dcl
= ds
->listeners
;
3388 while (dcl
!= NULL
) {
3389 if (dcl
->gui_timer_interval
&&
3390 dcl
->gui_timer_interval
< interval
)
3391 interval
= dcl
->gui_timer_interval
;
3394 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3397 static void nographic_update(void *opaque
)
3399 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3401 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3404 struct vm_change_state_entry
{
3405 VMChangeStateHandler
*cb
;
3407 LIST_ENTRY (vm_change_state_entry
) entries
;
3410 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3412 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3415 VMChangeStateEntry
*e
;
3417 e
= qemu_mallocz(sizeof (*e
));
3421 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3425 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3427 LIST_REMOVE (e
, entries
);
3431 static void vm_state_notify(int running
, int reason
)
3433 VMChangeStateEntry
*e
;
3435 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3436 e
->cb(e
->opaque
, running
, reason
);
3440 static void resume_all_vcpus(void);
3441 static void pause_all_vcpus(void);
3448 vm_state_notify(1, 0);
3449 qemu_rearm_alarm_timer(alarm_timer
);
3454 /* reset/shutdown handler */
3456 typedef struct QEMUResetEntry
{
3457 TAILQ_ENTRY(QEMUResetEntry
) entry
;
3458 QEMUResetHandler
*func
;
3462 static TAILQ_HEAD(reset_handlers
, QEMUResetEntry
) reset_handlers
=
3463 TAILQ_HEAD_INITIALIZER(reset_handlers
);
3464 static int reset_requested
;
3465 static int shutdown_requested
;
3466 static int powerdown_requested
;
3467 static int debug_requested
;
3468 static int vmstop_requested
;
3470 int qemu_no_shutdown(void)
3472 int r
= no_shutdown
;
3477 int qemu_shutdown_requested(void)
3479 int r
= shutdown_requested
;
3480 shutdown_requested
= 0;
3484 int qemu_reset_requested(void)
3486 int r
= reset_requested
;
3487 reset_requested
= 0;
3491 int qemu_powerdown_requested(void)
3493 int r
= powerdown_requested
;
3494 powerdown_requested
= 0;
3498 static int qemu_debug_requested(void)
3500 int r
= debug_requested
;
3501 debug_requested
= 0;
3505 static int qemu_vmstop_requested(void)
3507 int r
= vmstop_requested
;
3508 vmstop_requested
= 0;
3512 static void do_vm_stop(int reason
)
3515 cpu_disable_ticks();
3518 vm_state_notify(0, reason
);
3522 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3524 QEMUResetEntry
*re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3527 re
->opaque
= opaque
;
3528 TAILQ_INSERT_TAIL(&reset_handlers
, re
, entry
);
3531 void qemu_unregister_reset(QEMUResetHandler
*func
, void *opaque
)
3535 TAILQ_FOREACH(re
, &reset_handlers
, entry
) {
3536 if (re
->func
== func
&& re
->opaque
== opaque
) {
3537 TAILQ_REMOVE(&reset_handlers
, re
, entry
);
3544 void qemu_system_reset(void)
3546 QEMUResetEntry
*re
, *nre
;
3548 /* reset all devices */
3549 TAILQ_FOREACH_SAFE(re
, &reset_handlers
, entry
, nre
) {
3550 re
->func(re
->opaque
);
3554 void qemu_system_reset_request(void)
3557 shutdown_requested
= 1;
3559 reset_requested
= 1;
3561 if (cpu_single_env
) {
3562 cpu_single_env
->stopped
= 1;
3564 qemu_notify_event();
3567 void qemu_system_shutdown_request(void)
3569 shutdown_requested
= 1;
3570 qemu_notify_event();
3573 void qemu_system_powerdown_request(void)
3575 powerdown_requested
= 1;
3576 qemu_notify_event();
3579 #ifdef CONFIG_IOTHREAD
3580 static void qemu_system_vmstop_request(int reason
)
3582 vmstop_requested
= reason
;
3583 qemu_notify_event();
3588 static int io_thread_fd
= -1;
3590 static void qemu_event_increment(void)
3592 static const char byte
= 0;
3594 if (io_thread_fd
== -1)
3597 write(io_thread_fd
, &byte
, sizeof(byte
));
3600 static void qemu_event_read(void *opaque
)
3602 int fd
= (unsigned long)opaque
;
3605 /* Drain the notify pipe */
3608 len
= read(fd
, buffer
, sizeof(buffer
));
3609 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
3612 static int qemu_event_init(void)
3621 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3625 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3629 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3630 (void *)(unsigned long)fds
[0]);
3632 io_thread_fd
= fds
[1];
3641 HANDLE qemu_event_handle
;
3643 static void dummy_event_handler(void *opaque
)
3647 static int qemu_event_init(void)
3649 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3650 if (!qemu_event_handle
) {
3651 perror("Failed CreateEvent");
3654 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3658 static void qemu_event_increment(void)
3660 SetEvent(qemu_event_handle
);
3664 static int cpu_can_run(CPUState
*env
)
3673 #ifndef CONFIG_IOTHREAD
3674 static int qemu_init_main_loop(void)
3676 return qemu_event_init();
3679 void qemu_init_vcpu(void *_env
)
3681 CPUState
*env
= _env
;
3688 int qemu_cpu_self(void *env
)
3693 static void resume_all_vcpus(void)
3697 static void pause_all_vcpus(void)
3701 void qemu_cpu_kick(void *env
)
3706 void qemu_notify_event(void)
3708 CPUState
*env
= cpu_single_env
;
3710 if (kvm_enabled()) {
3711 qemu_kvm_notify_work();
3717 if (env
->kqemu_enabled
)
3718 kqemu_cpu_interrupt(env
);
3724 #define qemu_mutex_lock_iothread() do { } while (0)
3725 #define qemu_mutex_unlock_iothread() do { } while (0)
3728 void vm_stop(int reason
)
3733 #else /* CONFIG_IOTHREAD */
3735 #include "qemu-thread.h"
3737 QemuMutex qemu_global_mutex
;
3738 static QemuMutex qemu_fair_mutex
;
3740 static QemuThread io_thread
;
3742 static QemuThread
*tcg_cpu_thread
;
3743 static QemuCond
*tcg_halt_cond
;
3745 static int qemu_system_ready
;
3747 static QemuCond qemu_cpu_cond
;
3749 static QemuCond qemu_system_cond
;
3750 static QemuCond qemu_pause_cond
;
3752 static void block_io_signals(void);
3753 static void unblock_io_signals(void);
3754 static int tcg_has_work(void);
3756 static int qemu_init_main_loop(void)
3760 ret
= qemu_event_init();
3764 qemu_cond_init(&qemu_pause_cond
);
3765 qemu_mutex_init(&qemu_fair_mutex
);
3766 qemu_mutex_init(&qemu_global_mutex
);
3767 qemu_mutex_lock(&qemu_global_mutex
);
3769 unblock_io_signals();
3770 qemu_thread_self(&io_thread
);
3775 static void qemu_wait_io_event(CPUState
*env
)
3777 while (!tcg_has_work())
3778 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3780 qemu_mutex_unlock(&qemu_global_mutex
);
3783 * Users of qemu_global_mutex can be starved, having no chance
3784 * to acquire it since this path will get to it first.
3785 * So use another lock to provide fairness.
3787 qemu_mutex_lock(&qemu_fair_mutex
);
3788 qemu_mutex_unlock(&qemu_fair_mutex
);
3790 qemu_mutex_lock(&qemu_global_mutex
);
3794 qemu_cond_signal(&qemu_pause_cond
);
3798 static int qemu_cpu_exec(CPUState
*env
);
3800 static void *kvm_cpu_thread_fn(void *arg
)
3802 CPUState
*env
= arg
;
3805 qemu_thread_self(env
->thread
);
3807 /* signal CPU creation */
3808 qemu_mutex_lock(&qemu_global_mutex
);
3810 qemu_cond_signal(&qemu_cpu_cond
);
3812 /* and wait for machine initialization */
3813 while (!qemu_system_ready
)
3814 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3817 if (cpu_can_run(env
))
3819 qemu_wait_io_event(env
);
3825 static void tcg_cpu_exec(void);
3827 static void *tcg_cpu_thread_fn(void *arg
)
3829 CPUState
*env
= arg
;
3832 qemu_thread_self(env
->thread
);
3834 /* signal CPU creation */
3835 qemu_mutex_lock(&qemu_global_mutex
);
3836 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
3838 qemu_cond_signal(&qemu_cpu_cond
);
3840 /* and wait for machine initialization */
3841 while (!qemu_system_ready
)
3842 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3846 qemu_wait_io_event(cur_cpu
);
3852 void qemu_cpu_kick(void *_env
)
3854 CPUState
*env
= _env
;
3855 qemu_cond_broadcast(env
->halt_cond
);
3857 qemu_thread_signal(env
->thread
, SIGUSR1
);
3860 int qemu_cpu_self(void *env
)
3862 return (cpu_single_env
!= NULL
);
3865 static void cpu_signal(int sig
)
3868 cpu_exit(cpu_single_env
);
3871 static void block_io_signals(void)
3874 struct sigaction sigact
;
3877 sigaddset(&set
, SIGUSR2
);
3878 sigaddset(&set
, SIGIO
);
3879 sigaddset(&set
, SIGALRM
);
3880 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3883 sigaddset(&set
, SIGUSR1
);
3884 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3886 memset(&sigact
, 0, sizeof(sigact
));
3887 sigact
.sa_handler
= cpu_signal
;
3888 sigaction(SIGUSR1
, &sigact
, NULL
);
3891 static void unblock_io_signals(void)
3896 sigaddset(&set
, SIGUSR2
);
3897 sigaddset(&set
, SIGIO
);
3898 sigaddset(&set
, SIGALRM
);
3899 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3902 sigaddset(&set
, SIGUSR1
);
3903 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3906 static void qemu_signal_lock(unsigned int msecs
)
3908 qemu_mutex_lock(&qemu_fair_mutex
);
3910 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
3911 qemu_thread_signal(tcg_cpu_thread
, SIGUSR1
);
3912 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
3915 qemu_mutex_unlock(&qemu_fair_mutex
);
3918 static void qemu_mutex_lock_iothread(void)
3920 if (kvm_enabled()) {
3921 qemu_mutex_lock(&qemu_fair_mutex
);
3922 qemu_mutex_lock(&qemu_global_mutex
);
3923 qemu_mutex_unlock(&qemu_fair_mutex
);
3925 qemu_signal_lock(100);
3928 static void qemu_mutex_unlock_iothread(void)
3930 qemu_mutex_unlock(&qemu_global_mutex
);
3933 static int all_vcpus_paused(void)
3935 CPUState
*penv
= first_cpu
;
3940 penv
= (CPUState
*)penv
->next_cpu
;
3946 static void pause_all_vcpus(void)
3948 CPUState
*penv
= first_cpu
;
3952 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3953 qemu_cpu_kick(penv
);
3954 penv
= (CPUState
*)penv
->next_cpu
;
3957 while (!all_vcpus_paused()) {
3958 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
3961 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3962 penv
= (CPUState
*)penv
->next_cpu
;
3967 static void resume_all_vcpus(void)
3969 CPUState
*penv
= first_cpu
;
3974 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3975 qemu_cpu_kick(penv
);
3976 penv
= (CPUState
*)penv
->next_cpu
;
3980 static void tcg_init_vcpu(void *_env
)
3982 CPUState
*env
= _env
;
3983 /* share a single thread for all cpus with TCG */
3984 if (!tcg_cpu_thread
) {
3985 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3986 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3987 qemu_cond_init(env
->halt_cond
);
3988 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
3989 while (env
->created
== 0)
3990 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3991 tcg_cpu_thread
= env
->thread
;
3992 tcg_halt_cond
= env
->halt_cond
;
3994 env
->thread
= tcg_cpu_thread
;
3995 env
->halt_cond
= tcg_halt_cond
;
3999 static void kvm_start_vcpu(CPUState
*env
)
4002 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
4003 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
4004 qemu_cond_init(env
->halt_cond
);
4005 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
4006 while (env
->created
== 0)
4007 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
4010 void qemu_init_vcpu(void *_env
)
4012 CPUState
*env
= _env
;
4015 kvm_start_vcpu(env
);
4020 void qemu_notify_event(void)
4022 qemu_event_increment();
4025 void vm_stop(int reason
)
4028 qemu_thread_self(&me
);
4030 if (!qemu_thread_equal(&me
, &io_thread
)) {
4031 qemu_system_vmstop_request(reason
);
4033 * FIXME: should not return to device code in case
4034 * vm_stop() has been requested.
4036 if (cpu_single_env
) {
4037 cpu_exit(cpu_single_env
);
4038 cpu_single_env
->stop
= 1;
4049 static void host_main_loop_wait(int *timeout
)
4055 /* XXX: need to suppress polling by better using win32 events */
4057 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
4058 ret
|= pe
->func(pe
->opaque
);
4062 WaitObjects
*w
= &wait_objects
;
4064 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
4065 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
4066 if (w
->func
[ret
- WAIT_OBJECT_0
])
4067 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
4069 /* Check for additional signaled events */
4070 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
4072 /* Check if event is signaled */
4073 ret2
= WaitForSingleObject(w
->events
[i
], 0);
4074 if(ret2
== WAIT_OBJECT_0
) {
4076 w
->func
[i
](w
->opaque
[i
]);
4077 } else if (ret2
== WAIT_TIMEOUT
) {
4079 err
= GetLastError();
4080 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
4083 } else if (ret
== WAIT_TIMEOUT
) {
4085 err
= GetLastError();
4086 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
4093 static void host_main_loop_wait(int *timeout
)
4098 void main_loop_wait(int timeout
)
4100 IOHandlerRecord
*ioh
;
4101 fd_set rfds
, wfds
, xfds
;
4105 qemu_bh_update_timeout(&timeout
);
4107 host_main_loop_wait(&timeout
);
4109 /* poll any events */
4110 /* XXX: separate device handlers from system ones */
4115 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4119 (!ioh
->fd_read_poll
||
4120 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
4121 FD_SET(ioh
->fd
, &rfds
);
4125 if (ioh
->fd_write
) {
4126 FD_SET(ioh
->fd
, &wfds
);
4132 tv
.tv_sec
= timeout
/ 1000;
4133 tv
.tv_usec
= (timeout
% 1000) * 1000;
4135 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
4137 qemu_mutex_unlock_iothread();
4138 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
4139 qemu_mutex_lock_iothread();
4141 IOHandlerRecord
**pioh
;
4143 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4144 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
4145 ioh
->fd_read(ioh
->opaque
);
4146 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
4147 FD_CLR(ioh
->fd
, &rfds
);
4149 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
4150 ioh
->fd_write(ioh
->opaque
);
4154 /* remove deleted IO handlers */
4155 pioh
= &first_io_handler
;
4166 slirp_select_poll(&rfds
, &wfds
, &xfds
, (ret
< 0));
4168 /* rearm timer, if not periodic */
4169 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
4170 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
4171 qemu_rearm_alarm_timer(alarm_timer
);
4174 /* vm time timers */
4176 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
4177 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
4178 qemu_get_clock(vm_clock
));
4181 /* real time timers */
4182 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
4183 qemu_get_clock(rt_clock
));
4185 /* Check bottom-halves last in case any of the earlier events triggered
4191 static int qemu_cpu_exec(CPUState
*env
)
4194 #ifdef CONFIG_PROFILER
4198 #ifdef CONFIG_PROFILER
4199 ti
= profile_getclock();
4204 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
4205 env
->icount_decr
.u16
.low
= 0;
4206 env
->icount_extra
= 0;
4207 count
= qemu_next_deadline();
4208 count
= (count
+ (1 << icount_time_shift
) - 1)
4209 >> icount_time_shift
;
4210 qemu_icount
+= count
;
4211 decr
= (count
> 0xffff) ? 0xffff : count
;
4213 env
->icount_decr
.u16
.low
= decr
;
4214 env
->icount_extra
= count
;
4216 ret
= cpu_exec(env
);
4217 #ifdef CONFIG_PROFILER
4218 qemu_time
+= profile_getclock() - ti
;
4221 /* Fold pending instructions back into the
4222 instruction counter, and clear the interrupt flag. */
4223 qemu_icount
-= (env
->icount_decr
.u16
.low
4224 + env
->icount_extra
);
4225 env
->icount_decr
.u32
= 0;
4226 env
->icount_extra
= 0;
4231 static void tcg_cpu_exec(void)
4235 if (next_cpu
== NULL
)
4236 next_cpu
= first_cpu
;
4237 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
4238 CPUState
*env
= cur_cpu
= next_cpu
;
4242 if (timer_alarm_pending
) {
4243 timer_alarm_pending
= 0;
4246 if (cpu_can_run(env
))
4247 ret
= qemu_cpu_exec(env
);
4248 if (ret
== EXCP_DEBUG
) {
4249 gdb_set_stop_cpu(env
);
4250 debug_requested
= 1;
4256 static int cpu_has_work(CPUState
*env
)
4264 if (qemu_cpu_has_work(env
))
4269 static int tcg_has_work(void)
4273 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4274 if (cpu_has_work(env
))
4279 static int qemu_calculate_timeout(void)
4281 #ifndef CONFIG_IOTHREAD
4286 else if (tcg_has_work())
4288 else if (!use_icount
)
4291 /* XXX: use timeout computed from timers */
4294 /* Advance virtual time to the next event. */
4295 if (use_icount
== 1) {
4296 /* When not using an adaptive execution frequency
4297 we tend to get badly out of sync with real time,
4298 so just delay for a reasonable amount of time. */
4301 delta
= cpu_get_icount() - cpu_get_clock();
4304 /* If virtual time is ahead of real time then just
4306 timeout
= (delta
/ 1000000) + 1;
4308 /* Wait for either IO to occur or the next
4310 add
= qemu_next_deadline();
4311 /* We advance the timer before checking for IO.
4312 Limit the amount we advance so that early IO
4313 activity won't get the guest too far ahead. */
4317 add
= (add
+ (1 << icount_time_shift
) - 1)
4318 >> icount_time_shift
;
4320 timeout
= delta
/ 1000000;
4327 #else /* CONFIG_IOTHREAD */
4332 static int vm_can_run(void)
4334 if (powerdown_requested
)
4336 if (reset_requested
)
4338 if (shutdown_requested
)
4340 if (debug_requested
)
4345 static void main_loop(void)
4349 if (kvm_enabled()) {
4351 cpu_disable_ticks();
4355 #ifdef CONFIG_IOTHREAD
4356 qemu_system_ready
= 1;
4357 qemu_cond_broadcast(&qemu_system_cond
);
4362 #ifdef CONFIG_PROFILER
4365 #ifndef CONFIG_IOTHREAD
4368 #ifdef CONFIG_PROFILER
4369 ti
= profile_getclock();
4371 main_loop_wait(qemu_calculate_timeout());
4372 #ifdef CONFIG_PROFILER
4373 dev_time
+= profile_getclock() - ti
;
4375 } while (vm_can_run());
4377 if (qemu_debug_requested())
4378 vm_stop(EXCP_DEBUG
);
4379 if (qemu_shutdown_requested()) {
4386 if (qemu_reset_requested()) {
4388 qemu_system_reset();
4391 if (qemu_powerdown_requested())
4392 qemu_system_powerdown();
4393 if ((r
= qemu_vmstop_requested()))
4399 static void version(void)
4401 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4404 static void help(int exitcode
)
4407 printf("usage: %s [options] [disk_image]\n"
4409 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4411 #define DEF(option, opt_arg, opt_enum, opt_help) \
4413 #define DEFHEADING(text) stringify(text) "\n"
4414 #include "qemu-options.h"
4419 "During emulation, the following keys are useful:\n"
4420 "ctrl-alt-f toggle full screen\n"
4421 "ctrl-alt-n switch to virtual console 'n'\n"
4422 "ctrl-alt toggle mouse and keyboard grab\n"
4424 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4429 DEFAULT_NETWORK_SCRIPT
,
4430 DEFAULT_NETWORK_DOWN_SCRIPT
,
4432 DEFAULT_GDBSTUB_PORT
,
4437 #define HAS_ARG 0x0001
4440 #define DEF(option, opt_arg, opt_enum, opt_help) \
4442 #define DEFHEADING(text)
4443 #include "qemu-options.h"
4449 typedef struct QEMUOption
{
4455 static const QEMUOption qemu_options
[] = {
4456 { "h", 0, QEMU_OPTION_h
},
4457 #define DEF(option, opt_arg, opt_enum, opt_help) \
4458 { option, opt_arg, opt_enum },
4459 #define DEFHEADING(text)
4460 #include "qemu-options.h"
4468 struct soundhw soundhw
[] = {
4469 #ifdef HAS_AUDIO_CHOICE
4470 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4476 { .init_isa
= pcspk_audio_init
}
4483 "Creative Sound Blaster 16",
4486 { .init_isa
= SB16_init
}
4490 #ifdef CONFIG_CS4231A
4496 { .init_isa
= cs4231a_init
}
4504 "Yamaha YMF262 (OPL3)",
4506 "Yamaha YM3812 (OPL2)",
4510 { .init_isa
= Adlib_init
}
4517 "Gravis Ultrasound GF1",
4520 { .init_isa
= GUS_init
}
4527 "Intel 82801AA AC97 Audio",
4530 { .init_pci
= ac97_init
}
4534 #ifdef CONFIG_ES1370
4537 "ENSONIQ AudioPCI ES1370",
4540 { .init_pci
= es1370_init
}
4544 #endif /* HAS_AUDIO_CHOICE */
4546 { NULL
, NULL
, 0, 0, { NULL
} }
4549 static void select_soundhw (const char *optarg
)
4553 if (*optarg
== '?') {
4556 printf ("Valid sound card names (comma separated):\n");
4557 for (c
= soundhw
; c
->name
; ++c
) {
4558 printf ("%-11s %s\n", c
->name
, c
->descr
);
4560 printf ("\n-soundhw all will enable all of the above\n");
4561 exit (*optarg
!= '?');
4569 if (!strcmp (optarg
, "all")) {
4570 for (c
= soundhw
; c
->name
; ++c
) {
4578 e
= strchr (p
, ',');
4579 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4581 for (c
= soundhw
; c
->name
; ++c
) {
4582 if (!strncmp (c
->name
, p
, l
)) {
4591 "Unknown sound card name (too big to show)\n");
4594 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4599 p
+= l
+ (e
!= NULL
);
4603 goto show_valid_cards
;
4608 static void select_vgahw (const char *p
)
4612 cirrus_vga_enabled
= 0;
4613 std_vga_enabled
= 0;
4616 if (strstart(p
, "std", &opts
)) {
4617 std_vga_enabled
= 1;
4618 } else if (strstart(p
, "cirrus", &opts
)) {
4619 cirrus_vga_enabled
= 1;
4620 } else if (strstart(p
, "vmware", &opts
)) {
4622 } else if (strstart(p
, "xenfb", &opts
)) {
4624 } else if (!strstart(p
, "none", &opts
)) {
4626 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4630 const char *nextopt
;
4632 if (strstart(opts
, ",retrace=", &nextopt
)) {
4634 if (strstart(opts
, "dumb", &nextopt
))
4635 vga_retrace_method
= VGA_RETRACE_DUMB
;
4636 else if (strstart(opts
, "precise", &nextopt
))
4637 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4638 else goto invalid_vga
;
4639 } else goto invalid_vga
;
4645 static int balloon_parse(const char *arg
)
4650 if (!strcmp(arg
, "none")) {
4652 } else if (!strncmp(arg
, "virtio", 6)) {
4654 if (arg
[6] == ',') {
4656 if (get_param_value(buf
, sizeof(buf
), "addr", p
)) {
4657 virtio_balloon_devaddr
= strdup(buf
);
4668 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4670 exit(STATUS_CONTROL_C_EXIT
);
4675 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4679 if(strlen(str
) != 36)
4682 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4683 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4684 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4690 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4696 #define MAX_NET_CLIENTS 32
4700 static void termsig_handler(int signal
)
4702 qemu_system_shutdown_request();
4705 static void sigchld_handler(int signal
)
4707 waitpid(-1, NULL
, WNOHANG
);
4710 static void sighandler_setup(void)
4712 struct sigaction act
;
4714 memset(&act
, 0, sizeof(act
));
4715 act
.sa_handler
= termsig_handler
;
4716 sigaction(SIGINT
, &act
, NULL
);
4717 sigaction(SIGHUP
, &act
, NULL
);
4718 sigaction(SIGTERM
, &act
, NULL
);
4720 act
.sa_handler
= sigchld_handler
;
4721 act
.sa_flags
= SA_NOCLDSTOP
;
4722 sigaction(SIGCHLD
, &act
, NULL
);
4728 /* Look for support files in the same directory as the executable. */
4729 static char *find_datadir(const char *argv0
)
4735 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
4742 while (p
!= buf
&& *p
!= '\\')
4745 if (access(buf
, R_OK
) == 0) {
4746 return qemu_strdup(buf
);
4752 /* Find a likely location for support files using the location of the binary.
4753 For installed binaries this will be "$bindir/../share/qemu". When
4754 running from the build tree this will be "$bindir/../pc-bios". */
4755 #define SHARE_SUFFIX "/share/qemu"
4756 #define BUILD_SUFFIX "/pc-bios"
4757 static char *find_datadir(const char *argv0
)
4767 #if defined(__linux__)
4770 len
= readlink("/proc/self/exe", buf
, sizeof(buf
) - 1);
4776 #elif defined(__FreeBSD__)
4779 len
= readlink("/proc/curproc/file", buf
, sizeof(buf
) - 1);
4786 /* If we don't have any way of figuring out the actual executable
4787 location then try argv[0]. */
4792 p
= realpath(argv0
, p
);
4800 max_len
= strlen(dir
) +
4801 MAX(strlen(SHARE_SUFFIX
), strlen(BUILD_SUFFIX
)) + 1;
4802 res
= qemu_mallocz(max_len
);
4803 snprintf(res
, max_len
, "%s%s", dir
, SHARE_SUFFIX
);
4804 if (access(res
, R_OK
)) {
4805 snprintf(res
, max_len
, "%s%s", dir
, BUILD_SUFFIX
);
4806 if (access(res
, R_OK
)) {
4820 char *qemu_find_file(int type
, const char *name
)
4826 /* If name contains path separators then try it as a straight path. */
4827 if ((strchr(name
, '/') || strchr(name
, '\\'))
4828 && access(name
, R_OK
) == 0) {
4829 return strdup(name
);
4832 case QEMU_FILE_TYPE_BIOS
:
4835 case QEMU_FILE_TYPE_KEYMAP
:
4836 subdir
= "keymaps/";
4841 len
= strlen(data_dir
) + strlen(name
) + strlen(subdir
) + 2;
4842 buf
= qemu_mallocz(len
);
4843 snprintf(buf
, len
, "%s/%s%s", data_dir
, subdir
, name
);
4844 if (access(buf
, R_OK
)) {
4851 struct device_config
{
4853 DEV_GENERIC
, /* -device */
4854 DEV_USB
, /* -usbdevice */
4857 const char *cmdline
;
4858 TAILQ_ENTRY(device_config
) next
;
4860 TAILQ_HEAD(, device_config
) device_configs
= TAILQ_HEAD_INITIALIZER(device_configs
);
4862 static void add_device_config(int type
, const char *cmdline
)
4864 struct device_config
*conf
;
4866 conf
= qemu_mallocz(sizeof(*conf
));
4868 conf
->cmdline
= cmdline
;
4869 TAILQ_INSERT_TAIL(&device_configs
, conf
, next
);
4872 static int foreach_device_config(int type
, int (*func
)(const char *cmdline
))
4874 struct device_config
*conf
;
4877 TAILQ_FOREACH(conf
, &device_configs
, next
) {
4878 if (conf
->type
!= type
)
4880 rc
= func(conf
->cmdline
);
4887 static int generic_parse(const char *cmdline
)
4891 dev
= qdev_device_add(cmdline
);
4897 int main(int argc
, char **argv
, char **envp
)
4899 const char *gdbstub_dev
= NULL
;
4900 uint32_t boot_devices_bitmap
= 0;
4902 int snapshot
, linux_boot
, net_boot
;
4903 const char *initrd_filename
;
4904 const char *kernel_filename
, *kernel_cmdline
;
4905 char boot_devices
[33] = "cad"; /* default to HD->floppy->CD-ROM */
4907 DisplayChangeListener
*dcl
;
4908 int cyls
, heads
, secs
, translation
;
4909 const char *net_clients
[MAX_NET_CLIENTS
];
4911 QemuOpts
*hda_opts
= NULL
;
4913 const char *r
, *optarg
;
4914 CharDriverState
*monitor_hd
= NULL
;
4915 const char *monitor_device
;
4916 const char *serial_devices
[MAX_SERIAL_PORTS
];
4917 int serial_device_index
;
4918 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
4919 int parallel_device_index
;
4920 const char *virtio_consoles
[MAX_VIRTIO_CONSOLES
];
4921 int virtio_console_index
;
4922 const char *loadvm
= NULL
;
4923 QEMUMachine
*machine
;
4924 const char *cpu_model
;
4929 const char *pid_file
= NULL
;
4930 const char *incoming
= NULL
;
4933 struct passwd
*pwd
= NULL
;
4934 const char *chroot_dir
= NULL
;
4935 const char *run_as
= NULL
;
4938 int show_vnc_port
= 0;
4940 qemu_cache_utils_init(envp
);
4942 LIST_INIT (&vm_change_state_head
);
4945 struct sigaction act
;
4946 sigfillset(&act
.sa_mask
);
4948 act
.sa_handler
= SIG_IGN
;
4949 sigaction(SIGPIPE
, &act
, NULL
);
4952 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4953 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4954 QEMU to run on a single CPU */
4959 h
= GetCurrentProcess();
4960 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4961 for(i
= 0; i
< 32; i
++) {
4962 if (mask
& (1 << i
))
4967 SetProcessAffinityMask(h
, mask
);
4973 module_call_init(MODULE_INIT_MACHINE
);
4974 machine
= find_default_machine();
4976 initrd_filename
= NULL
;
4979 kernel_filename
= NULL
;
4980 kernel_cmdline
= "";
4981 cyls
= heads
= secs
= 0;
4982 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4983 monitor_device
= "vc:80Cx24C";
4985 serial_devices
[0] = "vc:80Cx24C";
4986 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
4987 serial_devices
[i
] = NULL
;
4988 serial_device_index
= 0;
4990 parallel_devices
[0] = "vc:80Cx24C";
4991 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
4992 parallel_devices
[i
] = NULL
;
4993 parallel_device_index
= 0;
4995 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++)
4996 virtio_consoles
[i
] = NULL
;
4997 virtio_console_index
= 0;
4999 for (i
= 0; i
< MAX_NODES
; i
++) {
5001 node_cpumask
[i
] = 0;
5004 assigned_devices_index
= 0;
5013 register_watchdogs();
5021 hda_opts
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
5023 const QEMUOption
*popt
;
5026 /* Treat --foo the same as -foo. */
5029 popt
= qemu_options
;
5032 fprintf(stderr
, "%s: invalid option -- '%s'\n",
5036 if (!strcmp(popt
->name
, r
+ 1))
5040 if (popt
->flags
& HAS_ARG
) {
5041 if (optind
>= argc
) {
5042 fprintf(stderr
, "%s: option '%s' requires an argument\n",
5046 optarg
= argv
[optind
++];
5051 switch(popt
->index
) {
5053 machine
= find_machine(optarg
);
5056 printf("Supported machines are:\n");
5057 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5059 printf("%-10s %s (alias of %s)\n",
5060 m
->alias
, m
->desc
, m
->name
);
5061 printf("%-10s %s%s\n",
5063 m
->is_default
? " (default)" : "");
5065 exit(*optarg
!= '?');
5068 case QEMU_OPTION_cpu
:
5069 /* hw initialization will check this */
5070 if (*optarg
== '?') {
5071 /* XXX: implement xxx_cpu_list for targets that still miss it */
5072 #if defined(cpu_list)
5073 cpu_list(stdout
, &fprintf
);
5080 case QEMU_OPTION_initrd
:
5081 initrd_filename
= optarg
;
5083 case QEMU_OPTION_hda
:
5085 hda_opts
= drive_add(optarg
, HD_ALIAS
, 0);
5087 hda_opts
= drive_add(optarg
, HD_ALIAS
5088 ",cyls=%d,heads=%d,secs=%d%s",
5089 0, cyls
, heads
, secs
,
5090 translation
== BIOS_ATA_TRANSLATION_LBA
?
5092 translation
== BIOS_ATA_TRANSLATION_NONE
?
5093 ",trans=none" : "");
5095 case QEMU_OPTION_hdb
:
5096 case QEMU_OPTION_hdc
:
5097 case QEMU_OPTION_hdd
:
5098 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
5100 case QEMU_OPTION_drive
:
5101 drive_add(NULL
, "%s", optarg
);
5103 case QEMU_OPTION_mtdblock
:
5104 drive_add(optarg
, MTD_ALIAS
);
5106 case QEMU_OPTION_sd
:
5107 drive_add(optarg
, SD_ALIAS
);
5109 case QEMU_OPTION_pflash
:
5110 drive_add(optarg
, PFLASH_ALIAS
);
5112 case QEMU_OPTION_snapshot
:
5115 case QEMU_OPTION_hdachs
:
5119 cyls
= strtol(p
, (char **)&p
, 0);
5120 if (cyls
< 1 || cyls
> 16383)
5125 heads
= strtol(p
, (char **)&p
, 0);
5126 if (heads
< 1 || heads
> 16)
5131 secs
= strtol(p
, (char **)&p
, 0);
5132 if (secs
< 1 || secs
> 63)
5136 if (!strcmp(p
, "none"))
5137 translation
= BIOS_ATA_TRANSLATION_NONE
;
5138 else if (!strcmp(p
, "lba"))
5139 translation
= BIOS_ATA_TRANSLATION_LBA
;
5140 else if (!strcmp(p
, "auto"))
5141 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5144 } else if (*p
!= '\0') {
5146 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5149 if (hda_opts
!= NULL
) {
5151 snprintf(num
, sizeof(num
), "%d", cyls
);
5152 qemu_opt_set(hda_opts
, "cyls", num
);
5153 snprintf(num
, sizeof(num
), "%d", heads
);
5154 qemu_opt_set(hda_opts
, "heads", num
);
5155 snprintf(num
, sizeof(num
), "%d", secs
);
5156 qemu_opt_set(hda_opts
, "secs", num
);
5157 if (translation
== BIOS_ATA_TRANSLATION_LBA
)
5158 qemu_opt_set(hda_opts
, "trans", "lba");
5159 if (translation
== BIOS_ATA_TRANSLATION_NONE
)
5160 qemu_opt_set(hda_opts
, "trans", "none");
5164 case QEMU_OPTION_numa
:
5165 if (nb_numa_nodes
>= MAX_NODES
) {
5166 fprintf(stderr
, "qemu: too many NUMA nodes\n");
5171 case QEMU_OPTION_nographic
:
5172 display_type
= DT_NOGRAPHIC
;
5174 #ifdef CONFIG_CURSES
5175 case QEMU_OPTION_curses
:
5176 display_type
= DT_CURSES
;
5179 case QEMU_OPTION_portrait
:
5182 case QEMU_OPTION_kernel
:
5183 kernel_filename
= optarg
;
5185 case QEMU_OPTION_append
:
5186 kernel_cmdline
= optarg
;
5188 case QEMU_OPTION_cdrom
:
5189 drive_add(optarg
, CDROM_ALIAS
);
5191 case QEMU_OPTION_boot
:
5193 static const char * const params
[] = {
5194 "order", "once", "menu", NULL
5196 char buf
[sizeof(boot_devices
)];
5197 char *standard_boot_devices
;
5200 if (!strchr(optarg
, '=')) {
5202 pstrcpy(buf
, sizeof(buf
), optarg
);
5203 } else if (check_params(buf
, sizeof(buf
), params
, optarg
) < 0) {
5205 "qemu: unknown boot parameter '%s' in '%s'\n",
5211 get_param_value(buf
, sizeof(buf
), "order", optarg
)) {
5212 boot_devices_bitmap
= parse_bootdevices(buf
);
5213 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5216 if (get_param_value(buf
, sizeof(buf
),
5218 boot_devices_bitmap
|= parse_bootdevices(buf
);
5219 standard_boot_devices
= qemu_strdup(boot_devices
);
5220 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5221 qemu_register_reset(restore_boot_devices
,
5222 standard_boot_devices
);
5224 if (get_param_value(buf
, sizeof(buf
),
5226 if (!strcmp(buf
, "on")) {
5228 } else if (!strcmp(buf
, "off")) {
5232 "qemu: invalid option value '%s'\n",
5240 case QEMU_OPTION_fda
:
5241 case QEMU_OPTION_fdb
:
5242 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
5245 case QEMU_OPTION_no_fd_bootchk
:
5249 case QEMU_OPTION_net
:
5250 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
5251 fprintf(stderr
, "qemu: too many network clients\n");
5254 net_clients
[nb_net_clients
] = optarg
;
5258 case QEMU_OPTION_tftp
:
5259 legacy_tftp_prefix
= optarg
;
5261 case QEMU_OPTION_bootp
:
5262 legacy_bootp_filename
= optarg
;
5265 case QEMU_OPTION_smb
:
5266 net_slirp_smb(optarg
);
5269 case QEMU_OPTION_redir
:
5270 net_slirp_redir(optarg
);
5273 case QEMU_OPTION_bt
:
5274 add_device_config(DEV_BT
, optarg
);
5277 case QEMU_OPTION_audio_help
:
5281 case QEMU_OPTION_soundhw
:
5282 select_soundhw (optarg
);
5288 case QEMU_OPTION_version
:
5292 case QEMU_OPTION_m
: {
5296 value
= strtoul(optarg
, &ptr
, 10);
5298 case 0: case 'M': case 'm':
5305 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5309 /* On 32-bit hosts, QEMU is limited by virtual address space */
5310 if (value
> (2047 << 20)
5311 #ifndef CONFIG_KQEMU
5312 && HOST_LONG_BITS
== 32
5315 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5318 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5319 fprintf(stderr
, "qemu: ram size too large\n");
5328 const CPULogItem
*item
;
5330 mask
= cpu_str_to_log_mask(optarg
);
5332 printf("Log items (comma separated):\n");
5333 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5334 printf("%-10s %s\n", item
->name
, item
->help
);
5342 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5344 case QEMU_OPTION_gdb
:
5345 gdbstub_dev
= optarg
;
5350 case QEMU_OPTION_bios
:
5353 case QEMU_OPTION_singlestep
:
5361 keyboard_layout
= optarg
;
5364 case QEMU_OPTION_localtime
:
5367 case QEMU_OPTION_vga
:
5368 select_vgahw (optarg
);
5370 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5376 w
= strtol(p
, (char **)&p
, 10);
5379 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5385 h
= strtol(p
, (char **)&p
, 10);
5390 depth
= strtol(p
, (char **)&p
, 10);
5391 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5392 depth
!= 24 && depth
!= 32)
5394 } else if (*p
== '\0') {
5395 depth
= graphic_depth
;
5402 graphic_depth
= depth
;
5406 case QEMU_OPTION_echr
:
5409 term_escape_char
= strtol(optarg
, &r
, 0);
5411 printf("Bad argument to echr\n");
5414 case QEMU_OPTION_monitor
:
5415 monitor_device
= optarg
;
5417 case QEMU_OPTION_serial
:
5418 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
5419 fprintf(stderr
, "qemu: too many serial ports\n");
5422 serial_devices
[serial_device_index
] = optarg
;
5423 serial_device_index
++;
5425 case QEMU_OPTION_watchdog
:
5426 i
= select_watchdog(optarg
);
5428 exit (i
== 1 ? 1 : 0);
5430 case QEMU_OPTION_watchdog_action
:
5431 if (select_watchdog_action(optarg
) == -1) {
5432 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5436 case QEMU_OPTION_virtiocon
:
5437 if (virtio_console_index
>= MAX_VIRTIO_CONSOLES
) {
5438 fprintf(stderr
, "qemu: too many virtio consoles\n");
5441 virtio_consoles
[virtio_console_index
] = optarg
;
5442 virtio_console_index
++;
5444 case QEMU_OPTION_parallel
:
5445 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
5446 fprintf(stderr
, "qemu: too many parallel ports\n");
5449 parallel_devices
[parallel_device_index
] = optarg
;
5450 parallel_device_index
++;
5452 case QEMU_OPTION_loadvm
:
5455 case QEMU_OPTION_full_screen
:
5459 case QEMU_OPTION_no_frame
:
5462 case QEMU_OPTION_alt_grab
:
5465 case QEMU_OPTION_no_quit
:
5468 case QEMU_OPTION_sdl
:
5469 display_type
= DT_SDL
;
5472 case QEMU_OPTION_pidfile
:
5476 case QEMU_OPTION_win2k_hack
:
5477 win2k_install_hack
= 1;
5479 case QEMU_OPTION_rtc_td_hack
:
5482 case QEMU_OPTION_acpitable
:
5483 if(acpi_table_add(optarg
) < 0) {
5484 fprintf(stderr
, "Wrong acpi table provided\n");
5488 case QEMU_OPTION_smbios
:
5489 if(smbios_entry_add(optarg
) < 0) {
5490 fprintf(stderr
, "Wrong smbios provided\n");
5496 case QEMU_OPTION_enable_kqemu
:
5499 case QEMU_OPTION_kernel_kqemu
:
5505 case QEMU_OPTION_enable_kvm
:
5512 case QEMU_OPTION_no_kvm
:
5515 case QEMU_OPTION_no_kvm_irqchip
: {
5520 case QEMU_OPTION_no_kvm_pit
: {
5524 case QEMU_OPTION_no_kvm_pit_reinjection
: {
5525 kvm_pit_reinject
= 0;
5528 case QEMU_OPTION_enable_nesting
: {
5532 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5533 case QEMU_OPTION_pcidevice
:
5534 if (assigned_devices_index
>= MAX_DEV_ASSIGN_CMDLINE
) {
5535 fprintf(stderr
, "Too many assigned devices\n");
5538 assigned_devices
[assigned_devices_index
] = optarg
;
5539 assigned_devices_index
++;
5543 case QEMU_OPTION_usb
:
5546 case QEMU_OPTION_usbdevice
:
5548 add_device_config(DEV_USB
, optarg
);
5550 case QEMU_OPTION_device
:
5551 add_device_config(DEV_GENERIC
, optarg
);
5553 case QEMU_OPTION_smp
:
5557 smp_cpus
= strtol(optarg
, &p
, 10);
5559 fprintf(stderr
, "Invalid number of CPUs\n");
5564 if (get_param_value(option
, 128, "maxcpus", p
))
5565 max_cpus
= strtol(option
, NULL
, 0);
5566 if (max_cpus
< smp_cpus
) {
5567 fprintf(stderr
, "maxcpus must be equal to or greater than "
5571 if (max_cpus
> 255) {
5572 fprintf(stderr
, "Unsupported number of maxcpus\n");
5577 case QEMU_OPTION_vnc
:
5578 display_type
= DT_VNC
;
5579 vnc_display
= optarg
;
5582 case QEMU_OPTION_no_acpi
:
5585 case QEMU_OPTION_no_hpet
:
5588 case QEMU_OPTION_balloon
:
5589 if (balloon_parse(optarg
) < 0) {
5590 fprintf(stderr
, "Unknown -balloon argument %s\n", optarg
);
5595 case QEMU_OPTION_no_reboot
:
5598 case QEMU_OPTION_no_shutdown
:
5601 case QEMU_OPTION_show_cursor
:
5604 case QEMU_OPTION_uuid
:
5605 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5606 fprintf(stderr
, "Fail to parse UUID string."
5607 " Wrong format.\n");
5612 case QEMU_OPTION_daemonize
:
5616 case QEMU_OPTION_option_rom
:
5617 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5618 fprintf(stderr
, "Too many option ROMs\n");
5621 option_rom
[nb_option_roms
] = optarg
;
5624 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5625 case QEMU_OPTION_semihosting
:
5626 semihosting_enabled
= 1;
5629 case QEMU_OPTION_tdf
:
5632 case QEMU_OPTION_kvm_shadow_memory
:
5633 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
5635 case QEMU_OPTION_mempath
:
5639 case QEMU_OPTION_mem_prealloc
:
5640 mem_prealloc
= !mem_prealloc
;
5643 case QEMU_OPTION_name
:
5644 qemu_name
= qemu_strdup(optarg
);
5646 char *p
= strchr(qemu_name
, ',');
5649 if (strncmp(p
, "process=", 8)) {
5650 fprintf(stderr
, "Unknown subargument %s to -name", p
);
5658 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5659 case QEMU_OPTION_prom_env
:
5660 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5661 fprintf(stderr
, "Too many prom variables\n");
5664 prom_envs
[nb_prom_envs
] = optarg
;
5669 case QEMU_OPTION_old_param
:
5673 case QEMU_OPTION_clock
:
5674 configure_alarms(optarg
);
5676 case QEMU_OPTION_startdate
:
5679 time_t rtc_start_date
;
5680 if (!strcmp(optarg
, "now")) {
5681 rtc_date_offset
= -1;
5683 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
5691 } else if (sscanf(optarg
, "%d-%d-%d",
5694 &tm
.tm_mday
) == 3) {
5703 rtc_start_date
= mktimegm(&tm
);
5704 if (rtc_start_date
== -1) {
5706 fprintf(stderr
, "Invalid date format. Valid format are:\n"
5707 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5710 rtc_date_offset
= time(NULL
) - rtc_start_date
;
5714 case QEMU_OPTION_tb_size
:
5715 tb_size
= strtol(optarg
, NULL
, 0);
5719 case QEMU_OPTION_icount
:
5721 if (strcmp(optarg
, "auto") == 0) {
5722 icount_time_shift
= -1;
5724 icount_time_shift
= strtol(optarg
, NULL
, 0);
5727 case QEMU_OPTION_incoming
:
5731 case QEMU_OPTION_chroot
:
5732 chroot_dir
= optarg
;
5734 case QEMU_OPTION_runas
:
5737 case QEMU_OPTION_nvram
:
5742 case QEMU_OPTION_xen_domid
:
5743 xen_domid
= atoi(optarg
);
5745 case QEMU_OPTION_xen_create
:
5746 xen_mode
= XEN_CREATE
;
5748 case QEMU_OPTION_xen_attach
:
5749 xen_mode
= XEN_ATTACH
;
5756 /* If no data_dir is specified then try to find it relative to the
5759 data_dir
= find_datadir(argv
[0]);
5761 /* If all else fails use the install patch specified when building. */
5763 data_dir
= CONFIG_QEMU_SHAREDIR
;
5766 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5767 if (kvm_allowed
&& kqemu_allowed
) {
5769 "You can not enable both KVM and kqemu at the same time\n");
5775 * Default to max_cpus = smp_cpus, in case the user doesn't
5776 * specify a max_cpus value.
5779 max_cpus
= smp_cpus
;
5781 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5782 if (smp_cpus
> machine
->max_cpus
) {
5783 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5784 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5789 if (display_type
== DT_NOGRAPHIC
) {
5790 if (serial_device_index
== 0)
5791 serial_devices
[0] = "stdio";
5792 if (parallel_device_index
== 0)
5793 parallel_devices
[0] = "null";
5794 if (strncmp(monitor_device
, "vc", 2) == 0)
5795 monitor_device
= "stdio";
5802 if (pipe(fds
) == -1)
5813 len
= read(fds
[0], &status
, 1);
5814 if (len
== -1 && (errno
== EINTR
))
5819 else if (status
== 1) {
5820 fprintf(stderr
, "Could not acquire pidfile\n");
5837 signal(SIGTSTP
, SIG_IGN
);
5838 signal(SIGTTOU
, SIG_IGN
);
5839 signal(SIGTTIN
, SIG_IGN
);
5842 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5845 write(fds
[1], &status
, 1);
5847 fprintf(stderr
, "Could not acquire pid file\n");
5856 if (qemu_init_main_loop()) {
5857 fprintf(stderr
, "qemu_init_main_loop failed\n");
5860 linux_boot
= (kernel_filename
!= NULL
);
5862 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5863 fprintf(stderr
, "-append only allowed with -kernel option\n");
5867 if (!linux_boot
&& initrd_filename
!= NULL
) {
5868 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5873 /* Win32 doesn't support line-buffering and requires size >= 2 */
5874 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5878 if (init_timer_alarm() < 0) {
5879 fprintf(stderr
, "could not initialize alarm timer\n");
5882 if (use_icount
&& icount_time_shift
< 0) {
5884 /* 125MIPS seems a reasonable initial guess at the guest speed.
5885 It will be corrected fairly quickly anyway. */
5886 icount_time_shift
= 3;
5887 init_icount_adjust();
5894 /* init network clients */
5895 if (nb_net_clients
== 0) {
5896 /* if no clients, we use a default config */
5897 net_clients
[nb_net_clients
++] = "nic";
5899 net_clients
[nb_net_clients
++] = "user";
5903 for(i
= 0;i
< nb_net_clients
; i
++) {
5904 if (net_client_parse(net_clients
[i
]) < 0)
5908 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5909 net_set_boot_mask(net_boot
);
5913 /* init the bluetooth world */
5914 if (foreach_device_config(DEV_BT
, bt_parse
))
5917 /* init the memory */
5919 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5922 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5923 guest ram allocation. It needs to go away. */
5924 if (kqemu_allowed
) {
5925 kqemu_phys_ram_size
= ram_size
+ 8 * 1024 * 1024 + 4 * 1024 * 1024;
5926 kqemu_phys_ram_base
= qemu_vmalloc(kqemu_phys_ram_size
);
5927 if (!kqemu_phys_ram_base
) {
5928 fprintf(stderr
, "Could not allocate physical memory\n");
5934 /* init the dynamic translator */
5935 cpu_exec_init_all(tb_size
* 1024 * 1024);
5939 /* we always create the cdrom drive, even if no disk is there */
5940 drive_add(NULL
, CDROM_ALIAS
);
5942 /* we always create at least one floppy */
5943 drive_add(NULL
, FD_ALIAS
, 0);
5945 /* we always create one sd slot, even if no card is in it */
5946 drive_add(NULL
, SD_ALIAS
);
5948 /* open the virtual block devices */
5950 qemu_opts_foreach(&drive_opt_list
, drive_enable_snapshot
, NULL
, 0);
5951 if (qemu_opts_foreach(&drive_opt_list
, drive_init_func
, machine
, 1) != 0)
5954 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
5955 register_savevm_live("ram", 0, 3, ram_save_live
, NULL
, ram_load
, NULL
);
5958 /* must be after terminal init, SDL library changes signal handlers */
5962 /* Maintain compatibility with multiple stdio monitors */
5963 if (!strcmp(monitor_device
,"stdio")) {
5964 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5965 const char *devname
= serial_devices
[i
];
5966 if (devname
&& !strcmp(devname
,"mon:stdio")) {
5967 monitor_device
= NULL
;
5969 } else if (devname
&& !strcmp(devname
,"stdio")) {
5970 monitor_device
= NULL
;
5971 serial_devices
[i
] = "mon:stdio";
5977 if (nb_numa_nodes
> 0) {
5980 if (nb_numa_nodes
> smp_cpus
) {
5981 nb_numa_nodes
= smp_cpus
;
5984 /* If no memory size if given for any node, assume the default case
5985 * and distribute the available memory equally across all nodes
5987 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5988 if (node_mem
[i
] != 0)
5991 if (i
== nb_numa_nodes
) {
5992 uint64_t usedmem
= 0;
5994 /* On Linux, the each node's border has to be 8MB aligned,
5995 * the final node gets the rest.
5997 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
5998 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
5999 usedmem
+= node_mem
[i
];
6001 node_mem
[i
] = ram_size
- usedmem
;
6004 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6005 if (node_cpumask
[i
] != 0)
6008 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6009 * must cope with this anyway, because there are BIOSes out there in
6010 * real machines which also use this scheme.
6012 if (i
== nb_numa_nodes
) {
6013 for (i
= 0; i
< smp_cpus
; i
++) {
6014 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
6019 if (kvm_enabled()) {
6022 ret
= kvm_init(smp_cpus
);
6024 #if defined(KVM_UPSTREAM) || defined(NO_CPU_EMULATION)
6025 fprintf(stderr
, "failed to initialize KVM\n");
6028 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
6033 if (monitor_device
) {
6034 monitor_hd
= qemu_chr_open("monitor", monitor_device
, NULL
);
6036 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
6041 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6042 const char *devname
= serial_devices
[i
];
6043 if (devname
&& strcmp(devname
, "none")) {
6045 snprintf(label
, sizeof(label
), "serial%d", i
);
6046 serial_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6047 if (!serial_hds
[i
]) {
6048 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
6055 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
6056 const char *devname
= parallel_devices
[i
];
6057 if (devname
&& strcmp(devname
, "none")) {
6059 snprintf(label
, sizeof(label
), "parallel%d", i
);
6060 parallel_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6061 if (!parallel_hds
[i
]) {
6062 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
6069 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
6070 const char *devname
= virtio_consoles
[i
];
6071 if (devname
&& strcmp(devname
, "none")) {
6073 snprintf(label
, sizeof(label
), "virtcon%d", i
);
6074 virtcon_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6075 if (!virtcon_hds
[i
]) {
6076 fprintf(stderr
, "qemu: could not open virtio console '%s'\n",
6083 module_call_init(MODULE_INIT_DEVICE
);
6085 if (machine
->compat_props
) {
6086 qdev_prop_register_compat(machine
->compat_props
);
6088 machine
->init(ram_size
, boot_devices
,
6089 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
6092 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
6093 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6094 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
6100 current_machine
= machine
;
6102 /* init USB devices */
6104 foreach_device_config(DEV_USB
, usb_parse
);
6107 /* init generic devices */
6108 if (foreach_device_config(DEV_GENERIC
, generic_parse
))
6112 dumb_display_init();
6113 /* just use the first displaystate for the moment */
6116 if (display_type
== DT_DEFAULT
) {
6117 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6118 display_type
= DT_SDL
;
6120 display_type
= DT_VNC
;
6121 vnc_display
= "localhost:0,to=99";
6127 switch (display_type
) {
6130 #if defined(CONFIG_CURSES)
6132 curses_display_init(ds
, full_screen
);
6135 #if defined(CONFIG_SDL)
6137 sdl_display_init(ds
, full_screen
, no_frame
);
6139 #elif defined(CONFIG_COCOA)
6141 cocoa_display_init(ds
, full_screen
);
6145 vnc_display_init(ds
);
6146 if (vnc_display_open(ds
, vnc_display
) < 0)
6149 if (show_vnc_port
) {
6150 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
6158 dcl
= ds
->listeners
;
6159 while (dcl
!= NULL
) {
6160 if (dcl
->dpy_refresh
!= NULL
) {
6161 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
6162 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
6167 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
6168 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
6169 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
6172 text_consoles_set_display(display_state
);
6173 qemu_chr_initial_reset();
6175 if (monitor_device
&& monitor_hd
)
6176 monitor_init(monitor_hd
, MONITOR_USE_READLINE
| MONITOR_IS_DEFAULT
);
6178 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6179 const char *devname
= serial_devices
[i
];
6180 if (devname
&& strcmp(devname
, "none")) {
6181 if (strstart(devname
, "vc", 0))
6182 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
6186 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
6187 const char *devname
= parallel_devices
[i
];
6188 if (devname
&& strcmp(devname
, "none")) {
6189 if (strstart(devname
, "vc", 0))
6190 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
6194 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
6195 const char *devname
= virtio_consoles
[i
];
6196 if (virtcon_hds
[i
] && devname
) {
6197 if (strstart(devname
, "vc", 0))
6198 qemu_chr_printf(virtcon_hds
[i
], "virtio console%d\r\n", i
);
6202 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
6203 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
6209 do_loadvm(cur_mon
, loadvm
);
6213 qemu_start_incoming_migration(incoming
);
6225 len
= write(fds
[1], &status
, 1);
6226 if (len
== -1 && (errno
== EINTR
))
6233 TFR(fd
= open("/dev/null", O_RDWR
));
6239 pwd
= getpwnam(run_as
);
6241 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
6247 if (chroot(chroot_dir
) < 0) {
6248 fprintf(stderr
, "chroot failed\n");
6255 if (setgid(pwd
->pw_gid
) < 0) {
6256 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
6259 if (setuid(pwd
->pw_uid
) < 0) {
6260 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
6263 if (setuid(0) != -1) {
6264 fprintf(stderr
, "Dropping privileges failed\n");