4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
38 #include <sys/times.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
47 #include <arpa/inet.h>
50 #include <sys/select.h>
53 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
62 #include <linux/rtc.h>
63 #include <sys/prctl.h>
65 /* For the benefit of older linux systems which don't supply it,
66 we use a local copy of hpet.h. */
67 /* #include <linux/hpet.h> */
70 #include <linux/ppdev.h>
71 #include <linux/parport.h>
75 #include <sys/ethernet.h>
76 #include <sys/sockio.h>
77 #include <netinet/arp.h>
78 #include <netinet/in.h>
79 #include <netinet/in_systm.h>
80 #include <netinet/ip.h>
81 #include <netinet/ip_icmp.h> // must come after ip.h
82 #include <netinet/udp.h>
83 #include <netinet/tcp.h>
87 /* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
88 discussion about Solaris header problems */
89 extern int madvise(caddr_t
, size_t, int);
94 #if defined(__OpenBSD__)
98 #if defined(CONFIG_VDE)
99 #include <libvdeplug.h>
104 #include <mmsystem.h>
108 #if defined(__APPLE__) || defined(main)
110 int qemu_main(int argc
, char **argv
, char **envp
);
111 int main(int argc
, char **argv
)
113 return qemu_main(argc
, argv
, NULL
);
116 #define main qemu_main
118 #endif /* CONFIG_SDL */
122 #define main qemu_main
123 #endif /* CONFIG_COCOA */
126 #include "hw/boards.h"
128 #include "hw/pcmcia.h"
130 #include "hw/audiodev.h"
134 #include "hw/watchdog.h"
135 #include "hw/smbios.h"
138 #include "hw/loader.h"
141 #include "net/slirp.h"
146 #include "qemu-timer.h"
147 #include "qemu-char.h"
148 #include "cache-utils.h"
150 #include "block_int.h"
151 #include "block-migration.h"
153 #include "audio/audio.h"
154 #include "migration.h"
157 #include "qemu-option.h"
158 #include "qemu-config.h"
159 #include "qemu-objects.h"
160 #include "hw/device-assignment.h"
164 #include "exec-all.h"
166 #include "qemu_socket.h"
168 #include "slirp/libslirp.h"
170 #include "qemu-queue.h"
173 //#define DEBUG_SLIRP
175 #define DEFAULT_RAM_SIZE 128
177 #define MAX_VIRTIO_CONSOLES 1
179 static const char *data_dir
;
180 const char *bios_name
= NULL
;
181 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
182 to store the VM snapshots */
183 struct drivelist drives
= QTAILQ_HEAD_INITIALIZER(drives
);
184 struct driveoptlist driveopts
= QTAILQ_HEAD_INITIALIZER(driveopts
);
185 DriveInfo
*extboot_drive
= NULL
;
186 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
187 DisplayType display_type
= DT_DEFAULT
;
188 const char* keyboard_layout
= NULL
;
190 const char *mem_path
= NULL
;
192 int mem_prealloc
= 0; /* force preallocation of physical target memory */
195 NICInfo nd_table
[MAX_NICS
];
198 static int rtc_utc
= 1;
199 static int rtc_date_offset
= -1; /* -1 means no change */
200 QEMUClock
*rtc_clock
;
201 int vga_interface_type
= VGA_NONE
;
203 int graphic_width
= 1024;
204 int graphic_height
= 768;
205 int graphic_depth
= 8;
207 int graphic_width
= 800;
208 int graphic_height
= 600;
209 int graphic_depth
= 15;
211 static int full_screen
= 0;
213 static int no_frame
= 0;
216 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
217 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
218 CharDriverState
*virtcon_hds
[MAX_VIRTIO_CONSOLES
];
220 int win2k_install_hack
= 0;
225 const char *assigned_devices
[MAX_DEV_ASSIGN_CMDLINE
];
226 int assigned_devices_index
;
231 const char *vnc_display
;
232 int acpi_enabled
= 1;
240 int graphic_rotate
= 0;
241 uint8_t irq0override
= 1;
245 const char *watchdog
;
246 const char *option_rom
[MAX_OPTION_ROMS
];
248 int semihosting_enabled
= 0;
249 int time_drift_fix
= 0;
250 unsigned int kvm_shadow_memory
= 0;
254 const char *qemu_name
;
257 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
258 unsigned int nb_prom_envs
= 0;
259 const char *prom_envs
[MAX_PROM_ENVS
];
261 const char *nvram
= NULL
;
265 uint64_t node_mem
[MAX_NODES
];
266 uint64_t node_cpumask
[MAX_NODES
];
268 static CPUState
*cur_cpu
;
269 static CPUState
*next_cpu
;
270 static int timer_alarm_pending
= 1;
271 /* Conversion factor from emulated instructions to virtual clock ticks. */
272 static int icount_time_shift
;
273 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
274 #define MAX_ICOUNT_SHIFT 10
275 /* Compensate for varying guest execution speed. */
276 static int64_t qemu_icount_bias
;
277 static QEMUTimer
*icount_rt_timer
;
278 static QEMUTimer
*icount_vm_timer
;
279 static QEMUTimer
*nographic_timer
;
281 uint8_t qemu_uuid
[16];
283 static QEMUBootSetHandler
*boot_set_handler
;
284 static void *boot_set_opaque
;
287 #define SIG_IPI (SIGRTMIN+4)
289 #define SIG_IPI SIGUSR1
292 static int default_serial
= 1;
293 static int default_parallel
= 1;
294 static int default_virtcon
= 1;
295 static int default_monitor
= 1;
296 static int default_vga
= 1;
297 static int default_floppy
= 1;
298 static int default_cdrom
= 1;
299 static int default_sdcard
= 1;
305 { .driver
= "isa-serial", .flag
= &default_serial
},
306 { .driver
= "isa-parallel", .flag
= &default_parallel
},
307 { .driver
= "isa-fdc", .flag
= &default_floppy
},
308 { .driver
= "ide-drive", .flag
= &default_cdrom
},
309 { .driver
= "virtio-serial-pci", .flag
= &default_virtcon
},
310 { .driver
= "virtio-serial-s390", .flag
= &default_virtcon
},
311 { .driver
= "virtio-serial", .flag
= &default_virtcon
},
312 { .driver
= "VGA", .flag
= &default_vga
},
313 { .driver
= "cirrus-vga", .flag
= &default_vga
},
314 { .driver
= "vmware-svga", .flag
= &default_vga
},
317 static int default_driver_check(QemuOpts
*opts
, void *opaque
)
319 const char *driver
= qemu_opt_get(opts
, "driver");
324 for (i
= 0; i
< ARRAY_SIZE(default_list
); i
++) {
325 if (strcmp(default_list
[i
].driver
, driver
) != 0)
327 *(default_list
[i
].flag
) = 0;
332 /***********************************************************/
333 /* x86 ISA bus support */
335 target_phys_addr_t isa_mem_base
= 0;
338 /***********************************************************/
339 void hw_error(const char *fmt
, ...)
345 fprintf(stderr
, "qemu: hardware error: ");
346 vfprintf(stderr
, fmt
, ap
);
347 fprintf(stderr
, "\n");
348 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
349 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
351 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
353 cpu_dump_state(env
, stderr
, fprintf
, 0);
360 static void set_proc_name(const char *s
)
362 #if defined(__linux__) && defined(PR_SET_NAME)
366 name
[sizeof(name
) - 1] = 0;
367 strncpy(name
, s
, sizeof(name
));
368 /* Could rewrite argv[0] too, but that's a bit more complicated.
369 This simple way is enough for `top'. */
370 prctl(PR_SET_NAME
, name
);
377 static QEMUBalloonEvent
*qemu_balloon_event
;
378 void *qemu_balloon_event_opaque
;
380 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
382 qemu_balloon_event
= func
;
383 qemu_balloon_event_opaque
= opaque
;
386 int qemu_balloon(ram_addr_t target
, MonitorCompletion cb
, void *opaque
)
388 if (qemu_balloon_event
) {
389 qemu_balloon_event(qemu_balloon_event_opaque
, target
, cb
, opaque
);
396 int qemu_balloon_status(MonitorCompletion cb
, void *opaque
)
398 if (qemu_balloon_event
) {
399 qemu_balloon_event(qemu_balloon_event_opaque
, 0, cb
, opaque
);
407 /***********************************************************/
408 /* real time host monotonic timer */
410 /* compute with 96 bit intermediate result: (a*b)/c */
411 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
416 #ifdef HOST_WORDS_BIGENDIAN
426 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
427 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
430 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
434 static int64_t get_clock_realtime(void)
438 gettimeofday(&tv
, NULL
);
439 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
444 static int64_t clock_freq
;
446 static void init_get_clock(void)
450 ret
= QueryPerformanceFrequency(&freq
);
452 fprintf(stderr
, "Could not calibrate ticks\n");
455 clock_freq
= freq
.QuadPart
;
458 static int64_t get_clock(void)
461 QueryPerformanceCounter(&ti
);
462 return muldiv64(ti
.QuadPart
, get_ticks_per_sec(), clock_freq
);
467 static int use_rt_clock
;
469 static void init_get_clock(void)
472 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
473 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
476 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
483 static int64_t get_clock(void)
485 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
486 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
489 clock_gettime(CLOCK_MONOTONIC
, &ts
);
490 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
494 /* XXX: using gettimeofday leads to problems if the date
495 changes, so it should be avoided. */
496 return get_clock_realtime();
501 /* Return the virtual CPU time, based on the instruction counter. */
502 static int64_t cpu_get_icount(void)
505 CPUState
*env
= cpu_single_env
;;
506 icount
= qemu_icount
;
509 fprintf(stderr
, "Bad clock read\n");
510 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
512 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
515 /***********************************************************/
516 /* guest cycle counter */
518 typedef struct TimersState
{
519 int64_t cpu_ticks_prev
;
520 int64_t cpu_ticks_offset
;
521 int64_t cpu_clock_offset
;
522 int32_t cpu_ticks_enabled
;
526 TimersState timers_state
;
528 /* return the host CPU cycle counter and handle stop/restart */
529 int64_t cpu_get_ticks(void)
532 return cpu_get_icount();
534 if (!timers_state
.cpu_ticks_enabled
) {
535 return timers_state
.cpu_ticks_offset
;
538 ticks
= cpu_get_real_ticks();
539 if (timers_state
.cpu_ticks_prev
> ticks
) {
540 /* Note: non increasing ticks may happen if the host uses
542 timers_state
.cpu_ticks_offset
+= timers_state
.cpu_ticks_prev
- ticks
;
544 timers_state
.cpu_ticks_prev
= ticks
;
545 return ticks
+ timers_state
.cpu_ticks_offset
;
549 /* return the host CPU monotonic timer and handle stop/restart */
550 static int64_t cpu_get_clock(void)
553 if (!timers_state
.cpu_ticks_enabled
) {
554 return timers_state
.cpu_clock_offset
;
557 return ti
+ timers_state
.cpu_clock_offset
;
561 /* enable cpu_get_ticks() */
562 void cpu_enable_ticks(void)
564 if (!timers_state
.cpu_ticks_enabled
) {
565 timers_state
.cpu_ticks_offset
-= cpu_get_real_ticks();
566 timers_state
.cpu_clock_offset
-= get_clock();
567 timers_state
.cpu_ticks_enabled
= 1;
571 /* disable cpu_get_ticks() : the clock is stopped. You must not call
572 cpu_get_ticks() after that. */
573 void cpu_disable_ticks(void)
575 if (timers_state
.cpu_ticks_enabled
) {
576 timers_state
.cpu_ticks_offset
= cpu_get_ticks();
577 timers_state
.cpu_clock_offset
= cpu_get_clock();
578 timers_state
.cpu_ticks_enabled
= 0;
582 /***********************************************************/
585 #define QEMU_CLOCK_REALTIME 0
586 #define QEMU_CLOCK_VIRTUAL 1
587 #define QEMU_CLOCK_HOST 2
591 /* XXX: add frequency */
599 struct QEMUTimer
*next
;
602 struct qemu_alarm_timer
{
606 int (*start
)(struct qemu_alarm_timer
*t
);
607 void (*stop
)(struct qemu_alarm_timer
*t
);
608 void (*rearm
)(struct qemu_alarm_timer
*t
);
612 #define ALARM_FLAG_DYNTICKS 0x1
613 #define ALARM_FLAG_EXPIRED 0x2
615 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
617 return t
&& (t
->flags
& ALARM_FLAG_DYNTICKS
);
620 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
622 if (!alarm_has_dynticks(t
))
628 /* TODO: MIN_TIMER_REARM_US should be optimized */
629 #define MIN_TIMER_REARM_US 250
631 static struct qemu_alarm_timer
*alarm_timer
;
635 struct qemu_alarm_win32
{
638 } alarm_win32_data
= {0, -1};
640 static int win32_start_timer(struct qemu_alarm_timer
*t
);
641 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
642 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
646 static int unix_start_timer(struct qemu_alarm_timer
*t
);
647 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
651 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
652 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
653 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
655 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
656 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
658 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
659 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
661 #endif /* __linux__ */
665 /* Correlation between real and virtual time is always going to be
666 fairly approximate, so ignore small variation.
667 When the guest is idle real and virtual time will be aligned in
669 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
671 static void icount_adjust(void)
676 static int64_t last_delta
;
677 /* If the VM is not running, then do nothing. */
681 cur_time
= cpu_get_clock();
682 cur_icount
= qemu_get_clock(vm_clock
);
683 delta
= cur_icount
- cur_time
;
684 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
686 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
687 && icount_time_shift
> 0) {
688 /* The guest is getting too far ahead. Slow time down. */
692 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
693 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
694 /* The guest is getting too far behind. Speed time up. */
698 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
701 static void icount_adjust_rt(void * opaque
)
703 qemu_mod_timer(icount_rt_timer
,
704 qemu_get_clock(rt_clock
) + 1000);
708 static void icount_adjust_vm(void * opaque
)
710 qemu_mod_timer(icount_vm_timer
,
711 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
715 static void init_icount_adjust(void)
717 /* Have both realtime and virtual time triggers for speed adjustment.
718 The realtime trigger catches emulated time passing too slowly,
719 the virtual time trigger catches emulated time passing too fast.
720 Realtime triggers occur even when idle, so use them less frequently
722 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
723 qemu_mod_timer(icount_rt_timer
,
724 qemu_get_clock(rt_clock
) + 1000);
725 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
726 qemu_mod_timer(icount_vm_timer
,
727 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
730 static struct qemu_alarm_timer alarm_timers
[] = {
733 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
734 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
735 /* HPET - if available - is preferred */
736 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
737 /* ...otherwise try RTC */
738 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
740 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
742 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
743 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
744 {"win32", 0, win32_start_timer
,
745 win32_stop_timer
, NULL
, &alarm_win32_data
},
750 static void show_available_alarms(void)
754 printf("Available alarm timers, in order of precedence:\n");
755 for (i
= 0; alarm_timers
[i
].name
; i
++)
756 printf("%s\n", alarm_timers
[i
].name
);
759 static void configure_alarms(char const *opt
)
763 int count
= ARRAY_SIZE(alarm_timers
) - 1;
766 struct qemu_alarm_timer tmp
;
768 if (!strcmp(opt
, "?")) {
769 show_available_alarms();
773 arg
= qemu_strdup(opt
);
775 /* Reorder the array */
776 name
= strtok(arg
, ",");
778 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
779 if (!strcmp(alarm_timers
[i
].name
, name
))
784 fprintf(stderr
, "Unknown clock %s\n", name
);
793 tmp
= alarm_timers
[i
];
794 alarm_timers
[i
] = alarm_timers
[cur
];
795 alarm_timers
[cur
] = tmp
;
799 name
= strtok(NULL
, ",");
805 /* Disable remaining timers */
806 for (i
= cur
; i
< count
; i
++)
807 alarm_timers
[i
].name
= NULL
;
809 show_available_alarms();
814 #define QEMU_NUM_CLOCKS 3
818 QEMUClock
*host_clock
;
820 static QEMUTimer
*active_timers
[QEMU_NUM_CLOCKS
];
822 static QEMUClock
*qemu_new_clock(int type
)
825 clock
= qemu_mallocz(sizeof(QEMUClock
));
830 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
834 ts
= qemu_mallocz(sizeof(QEMUTimer
));
841 void qemu_free_timer(QEMUTimer
*ts
)
846 /* stop a timer, but do not dealloc it */
847 void qemu_del_timer(QEMUTimer
*ts
)
851 /* NOTE: this code must be signal safe because
852 qemu_timer_expired() can be called from a signal. */
853 pt
= &active_timers
[ts
->clock
->type
];
866 /* modify the current timer so that it will be fired when current_time
867 >= expire_time. The corresponding callback will be called. */
868 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
874 /* add the timer in the sorted list */
875 /* NOTE: this code must be signal safe because
876 qemu_timer_expired() can be called from a signal. */
877 pt
= &active_timers
[ts
->clock
->type
];
882 if (t
->expire_time
> expire_time
)
886 ts
->expire_time
= expire_time
;
890 /* Rearm if necessary */
891 if (pt
== &active_timers
[ts
->clock
->type
]) {
892 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
893 qemu_rearm_alarm_timer(alarm_timer
);
895 /* Interrupt execution to force deadline recalculation. */
901 int qemu_timer_pending(QEMUTimer
*ts
)
904 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
911 int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
915 return (timer_head
->expire_time
<= current_time
);
918 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
924 if (!ts
|| ts
->expire_time
> current_time
)
926 /* remove timer from the list before calling the callback */
927 *ptimer_head
= ts
->next
;
930 /* run the callback (the timer list can be modified) */
935 int64_t qemu_get_clock(QEMUClock
*clock
)
937 switch(clock
->type
) {
938 case QEMU_CLOCK_REALTIME
:
939 return get_clock() / 1000000;
941 case QEMU_CLOCK_VIRTUAL
:
943 return cpu_get_icount();
945 return cpu_get_clock();
947 case QEMU_CLOCK_HOST
:
948 return get_clock_realtime();
952 int64_t qemu_get_clock_ns(QEMUClock
*clock
)
954 switch(clock
->type
) {
955 case QEMU_CLOCK_REALTIME
:
958 case QEMU_CLOCK_VIRTUAL
:
960 return cpu_get_icount();
962 return cpu_get_clock();
964 case QEMU_CLOCK_HOST
:
965 return get_clock_realtime();
969 static void init_clocks(void)
972 rt_clock
= qemu_new_clock(QEMU_CLOCK_REALTIME
);
973 vm_clock
= qemu_new_clock(QEMU_CLOCK_VIRTUAL
);
974 host_clock
= qemu_new_clock(QEMU_CLOCK_HOST
);
976 rtc_clock
= host_clock
;
980 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
982 uint64_t expire_time
;
984 if (qemu_timer_pending(ts
)) {
985 expire_time
= ts
->expire_time
;
989 qemu_put_be64(f
, expire_time
);
992 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
994 uint64_t expire_time
;
996 expire_time
= qemu_get_be64(f
);
997 if (expire_time
!= -1) {
998 qemu_mod_timer(ts
, expire_time
);
1004 static const VMStateDescription vmstate_timers
= {
1007 .minimum_version_id
= 1,
1008 .minimum_version_id_old
= 1,
1009 .fields
= (VMStateField
[]) {
1010 VMSTATE_INT64(cpu_ticks_offset
, TimersState
),
1011 VMSTATE_INT64(dummy
, TimersState
),
1012 VMSTATE_INT64_V(cpu_clock_offset
, TimersState
, 2),
1013 VMSTATE_END_OF_LIST()
1017 static void qemu_event_increment(void);
1020 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1021 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1024 static void host_alarm_handler(int host_signum
)
1028 #define DISP_FREQ 1000
1030 static int64_t delta_min
= INT64_MAX
;
1031 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1033 ti
= qemu_get_clock(vm_clock
);
1034 if (last_clock
!= 0) {
1035 delta
= ti
- last_clock
;
1036 if (delta
< delta_min
)
1038 if (delta
> delta_max
)
1041 if (++count
== DISP_FREQ
) {
1042 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1043 muldiv64(delta_min
, 1000000, get_ticks_per_sec()),
1044 muldiv64(delta_max
, 1000000, get_ticks_per_sec()),
1045 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, get_ticks_per_sec()),
1046 (double)get_ticks_per_sec() / ((double)delta_cum
/ DISP_FREQ
));
1048 delta_min
= INT64_MAX
;
1056 if (alarm_has_dynticks(alarm_timer
) ||
1058 qemu_timer_expired(active_timers
[QEMU_CLOCK_VIRTUAL
],
1059 qemu_get_clock(vm_clock
))) ||
1060 qemu_timer_expired(active_timers
[QEMU_CLOCK_REALTIME
],
1061 qemu_get_clock(rt_clock
)) ||
1062 qemu_timer_expired(active_timers
[QEMU_CLOCK_HOST
],
1063 qemu_get_clock(host_clock
))) {
1064 qemu_event_increment();
1065 if (alarm_timer
) alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1067 #ifndef CONFIG_IOTHREAD
1069 /* stop the currently executing cpu because a timer occured */
1073 timer_alarm_pending
= 1;
1074 qemu_notify_event();
1078 static int64_t qemu_next_deadline(void)
1080 /* To avoid problems with overflow limit this to 2^32. */
1081 int64_t delta
= INT32_MAX
;
1083 if (active_timers
[QEMU_CLOCK_VIRTUAL
]) {
1084 delta
= active_timers
[QEMU_CLOCK_VIRTUAL
]->expire_time
-
1085 qemu_get_clock(vm_clock
);
1087 if (active_timers
[QEMU_CLOCK_HOST
]) {
1088 int64_t hdelta
= active_timers
[QEMU_CLOCK_HOST
]->expire_time
-
1089 qemu_get_clock(host_clock
);
1100 #if defined(__linux__)
1101 static uint64_t qemu_next_deadline_dyntick(void)
1109 delta
= (qemu_next_deadline() + 999) / 1000;
1111 if (active_timers
[QEMU_CLOCK_REALTIME
]) {
1112 rtdelta
= (active_timers
[QEMU_CLOCK_REALTIME
]->expire_time
-
1113 qemu_get_clock(rt_clock
))*1000;
1114 if (rtdelta
< delta
)
1118 if (delta
< MIN_TIMER_REARM_US
)
1119 delta
= MIN_TIMER_REARM_US
;
1127 /* Sets a specific flag */
1128 static int fcntl_setfl(int fd
, int flag
)
1132 flags
= fcntl(fd
, F_GETFL
);
1136 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1142 #if defined(__linux__)
1144 #define RTC_FREQ 1024
1146 static void enable_sigio_timer(int fd
)
1148 struct sigaction act
;
1151 sigfillset(&act
.sa_mask
);
1153 act
.sa_handler
= host_alarm_handler
;
1155 sigaction(SIGIO
, &act
, NULL
);
1156 fcntl_setfl(fd
, O_ASYNC
);
1157 fcntl(fd
, F_SETOWN
, getpid());
1160 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1162 struct hpet_info info
;
1165 fd
= qemu_open("/dev/hpet", O_RDONLY
);
1170 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1172 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1173 "error, but for better emulation accuracy type:\n"
1174 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1178 /* Check capabilities */
1179 r
= ioctl(fd
, HPET_INFO
, &info
);
1183 /* Enable periodic mode */
1184 r
= ioctl(fd
, HPET_EPI
, 0);
1185 if (info
.hi_flags
&& (r
< 0))
1188 /* Enable interrupt */
1189 r
= ioctl(fd
, HPET_IE_ON
, 0);
1193 enable_sigio_timer(fd
);
1194 t
->priv
= (void *)(long)fd
;
1202 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1204 int fd
= (long)t
->priv
;
1209 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1212 unsigned long current_rtc_freq
= 0;
1214 TFR(rtc_fd
= qemu_open("/dev/rtc", O_RDONLY
));
1217 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1218 if (current_rtc_freq
!= RTC_FREQ
&&
1219 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1220 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1221 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1222 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1225 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1231 enable_sigio_timer(rtc_fd
);
1233 t
->priv
= (void *)(long)rtc_fd
;
1238 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1240 int rtc_fd
= (long)t
->priv
;
1245 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1249 struct sigaction act
;
1251 sigfillset(&act
.sa_mask
);
1253 act
.sa_handler
= host_alarm_handler
;
1255 sigaction(SIGALRM
, &act
, NULL
);
1258 * Initialize ev struct to 0 to avoid valgrind complaining
1259 * about uninitialized data in timer_create call
1261 memset(&ev
, 0, sizeof(ev
));
1262 ev
.sigev_value
.sival_int
= 0;
1263 ev
.sigev_notify
= SIGEV_SIGNAL
;
1264 ev
.sigev_signo
= SIGALRM
;
1266 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1267 perror("timer_create");
1269 /* disable dynticks */
1270 fprintf(stderr
, "Dynamic Ticks disabled\n");
1275 t
->priv
= (void *)(long)host_timer
;
1280 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1282 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1284 timer_delete(host_timer
);
1287 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1289 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1290 struct itimerspec timeout
;
1291 int64_t nearest_delta_us
= INT64_MAX
;
1294 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1295 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1296 !active_timers
[QEMU_CLOCK_HOST
])
1299 nearest_delta_us
= qemu_next_deadline_dyntick();
1301 /* check whether a timer is already running */
1302 if (timer_gettime(host_timer
, &timeout
)) {
1304 fprintf(stderr
, "Internal timer error: aborting\n");
1307 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1308 if (current_us
&& current_us
<= nearest_delta_us
)
1311 timeout
.it_interval
.tv_sec
= 0;
1312 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1313 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1314 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1315 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1317 fprintf(stderr
, "Internal timer error: aborting\n");
1322 #endif /* defined(__linux__) */
1324 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1326 struct sigaction act
;
1327 struct itimerval itv
;
1331 sigfillset(&act
.sa_mask
);
1333 act
.sa_handler
= host_alarm_handler
;
1335 sigaction(SIGALRM
, &act
, NULL
);
1337 itv
.it_interval
.tv_sec
= 0;
1338 /* for i386 kernel 2.6 to get 1 ms */
1339 itv
.it_interval
.tv_usec
= 999;
1340 itv
.it_value
.tv_sec
= 0;
1341 itv
.it_value
.tv_usec
= 10 * 1000;
1343 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1350 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1352 struct itimerval itv
;
1354 memset(&itv
, 0, sizeof(itv
));
1355 setitimer(ITIMER_REAL
, &itv
, NULL
);
1358 #endif /* !defined(_WIN32) */
1363 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1366 struct qemu_alarm_win32
*data
= t
->priv
;
1369 memset(&tc
, 0, sizeof(tc
));
1370 timeGetDevCaps(&tc
, sizeof(tc
));
1372 if (data
->period
< tc
.wPeriodMin
)
1373 data
->period
= tc
.wPeriodMin
;
1375 timeBeginPeriod(data
->period
);
1377 flags
= TIME_CALLBACK_FUNCTION
;
1378 if (alarm_has_dynticks(t
))
1379 flags
|= TIME_ONESHOT
;
1381 flags
|= TIME_PERIODIC
;
1383 data
->timerId
= timeSetEvent(1, // interval (ms)
1384 data
->period
, // resolution
1385 host_alarm_handler
, // function
1386 (DWORD
)t
, // parameter
1389 if (!data
->timerId
) {
1390 fprintf(stderr
, "Failed to initialize win32 alarm timer: %ld\n",
1392 timeEndPeriod(data
->period
);
1399 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1401 struct qemu_alarm_win32
*data
= t
->priv
;
1403 timeKillEvent(data
->timerId
);
1404 timeEndPeriod(data
->period
);
1407 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1409 struct qemu_alarm_win32
*data
= t
->priv
;
1411 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1412 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1413 !active_timers
[QEMU_CLOCK_HOST
])
1416 timeKillEvent(data
->timerId
);
1418 data
->timerId
= timeSetEvent(1,
1422 TIME_ONESHOT
| TIME_PERIODIC
);
1424 if (!data
->timerId
) {
1425 fprintf(stderr
, "Failed to re-arm win32 alarm timer %ld\n",
1428 timeEndPeriod(data
->period
);
1435 static int init_timer_alarm(void)
1437 struct qemu_alarm_timer
*t
= NULL
;
1440 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1441 t
= &alarm_timers
[i
];
1461 static void quit_timers(void)
1463 alarm_timer
->stop(alarm_timer
);
1467 /***********************************************************/
1468 /* host time/date access */
1469 void qemu_get_timedate(struct tm
*tm
, int offset
)
1476 if (rtc_date_offset
== -1) {
1480 ret
= localtime(&ti
);
1482 ti
-= rtc_date_offset
;
1486 memcpy(tm
, ret
, sizeof(struct tm
));
1489 int qemu_timedate_diff(struct tm
*tm
)
1493 if (rtc_date_offset
== -1)
1495 seconds
= mktimegm(tm
);
1497 seconds
= mktime(tm
);
1499 seconds
= mktimegm(tm
) + rtc_date_offset
;
1501 return seconds
- time(NULL
);
1504 void rtc_change_mon_event(struct tm
*tm
)
1508 data
= qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm
));
1509 monitor_protocol_event(QEVENT_RTC_CHANGE
, data
);
1510 qobject_decref(data
);
1513 static void configure_rtc_date_offset(const char *startdate
, int legacy
)
1515 time_t rtc_start_date
;
1518 if (!strcmp(startdate
, "now") && legacy
) {
1519 rtc_date_offset
= -1;
1521 if (sscanf(startdate
, "%d-%d-%dT%d:%d:%d",
1529 } else if (sscanf(startdate
, "%d-%d-%d",
1532 &tm
.tm_mday
) == 3) {
1541 rtc_start_date
= mktimegm(&tm
);
1542 if (rtc_start_date
== -1) {
1544 fprintf(stderr
, "Invalid date format. Valid formats are:\n"
1545 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1548 rtc_date_offset
= time(NULL
) - rtc_start_date
;
1552 static void configure_rtc(QemuOpts
*opts
)
1556 value
= qemu_opt_get(opts
, "base");
1558 if (!strcmp(value
, "utc")) {
1560 } else if (!strcmp(value
, "localtime")) {
1563 configure_rtc_date_offset(value
, 0);
1566 value
= qemu_opt_get(opts
, "clock");
1568 if (!strcmp(value
, "host")) {
1569 rtc_clock
= host_clock
;
1570 } else if (!strcmp(value
, "vm")) {
1571 rtc_clock
= vm_clock
;
1573 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1577 #ifdef CONFIG_TARGET_I386
1578 value
= qemu_opt_get(opts
, "driftfix");
1580 if (!strcmp(buf
, "slew")) {
1582 } else if (!strcmp(buf
, "none")) {
1585 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
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 QemuOpts
*drive_add(const char *file
, const char *fmt
, ...)
1822 vsnprintf(optstr
, sizeof(optstr
), fmt
, ap
);
1825 opts
= qemu_opts_parse(&qemu_drive_opts
, optstr
, NULL
);
1827 fprintf(stderr
, "%s: huh? duplicate? (%s)\n",
1828 __FUNCTION__
, optstr
);
1832 qemu_opt_set(opts
, "file", file
);
1836 DriveInfo
*drive_get(BlockInterfaceType type
, int bus
, int unit
)
1840 /* seek interface, bus and unit */
1842 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1843 if (dinfo
->type
== type
&&
1844 dinfo
->bus
== bus
&&
1845 dinfo
->unit
== unit
)
1852 DriveInfo
*drive_get_by_id(const char *id
)
1856 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1857 if (strcmp(id
, dinfo
->id
))
1864 int drive_get_max_bus(BlockInterfaceType type
)
1870 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1871 if(dinfo
->type
== type
&&
1872 dinfo
->bus
> max_bus
)
1873 max_bus
= dinfo
->bus
;
1878 const char *drive_get_serial(BlockDriverState
*bdrv
)
1882 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1883 if (dinfo
->bdrv
== bdrv
)
1884 return dinfo
->serial
;
1890 BlockInterfaceErrorAction
drive_get_on_error(
1891 BlockDriverState
*bdrv
, int is_read
)
1895 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1896 if (dinfo
->bdrv
== bdrv
)
1897 return is_read
? dinfo
->on_read_error
: dinfo
->on_write_error
;
1900 return is_read
? BLOCK_ERR_REPORT
: BLOCK_ERR_STOP_ENOSPC
;
1903 static void bdrv_format_print(void *opaque
, const char *name
)
1905 fprintf(stderr
, " %s", name
);
1908 void drive_uninit(DriveInfo
*dinfo
)
1910 qemu_opts_del(dinfo
->opts
);
1911 bdrv_delete(dinfo
->bdrv
);
1912 QTAILQ_REMOVE(&drives
, dinfo
, next
);
1916 static int parse_block_error_action(const char *buf
, int is_read
)
1918 if (!strcmp(buf
, "ignore")) {
1919 return BLOCK_ERR_IGNORE
;
1920 } else if (!is_read
&& !strcmp(buf
, "enospc")) {
1921 return BLOCK_ERR_STOP_ENOSPC
;
1922 } else if (!strcmp(buf
, "stop")) {
1923 return BLOCK_ERR_STOP_ANY
;
1924 } else if (!strcmp(buf
, "report")) {
1925 return BLOCK_ERR_REPORT
;
1927 fprintf(stderr
, "qemu: '%s' invalid %s error action\n",
1928 buf
, is_read
? "read" : "write");
1933 DriveInfo
*drive_init(QemuOpts
*opts
, void *opaque
,
1937 const char *file
= NULL
;
1940 const char *mediastr
= "";
1941 BlockInterfaceType type
;
1942 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
1943 int bus_id
, unit_id
;
1944 int cyls
, heads
, secs
, translation
;
1945 BlockDriver
*drv
= NULL
;
1946 QEMUMachine
*machine
= opaque
;
1953 int on_read_error
, on_write_error
;
1954 const char *devaddr
;
1961 translation
= BIOS_ATA_TRANSLATION_AUTO
;
1964 if (machine
&& machine
->use_scsi
) {
1966 max_devs
= MAX_SCSI_DEVS
;
1967 pstrcpy(devname
, sizeof(devname
), "scsi");
1970 max_devs
= MAX_IDE_DEVS
;
1971 pstrcpy(devname
, sizeof(devname
), "ide");
1975 /* extract parameters */
1976 bus_id
= qemu_opt_get_number(opts
, "bus", 0);
1977 unit_id
= qemu_opt_get_number(opts
, "unit", -1);
1978 index
= qemu_opt_get_number(opts
, "index", -1);
1980 cyls
= qemu_opt_get_number(opts
, "cyls", 0);
1981 heads
= qemu_opt_get_number(opts
, "heads", 0);
1982 secs
= qemu_opt_get_number(opts
, "secs", 0);
1984 snapshot
= qemu_opt_get_bool(opts
, "snapshot", 0);
1985 ro
= qemu_opt_get_bool(opts
, "readonly", 0);
1987 file
= qemu_opt_get(opts
, "file");
1988 serial
= qemu_opt_get(opts
, "serial");
1990 if ((buf
= qemu_opt_get(opts
, "if")) != NULL
) {
1991 pstrcpy(devname
, sizeof(devname
), buf
);
1992 if (!strcmp(buf
, "ide")) {
1994 max_devs
= MAX_IDE_DEVS
;
1995 } else if (!strcmp(buf
, "scsi")) {
1997 max_devs
= MAX_SCSI_DEVS
;
1998 } else if (!strcmp(buf
, "floppy")) {
2001 } else if (!strcmp(buf
, "pflash")) {
2004 } else if (!strcmp(buf
, "mtd")) {
2007 } else if (!strcmp(buf
, "sd")) {
2010 } else if (!strcmp(buf
, "virtio")) {
2013 } else if (!strcmp(buf
, "xen")) {
2016 } else if (!strcmp(buf
, "none")) {
2020 fprintf(stderr
, "qemu: unsupported bus type '%s'\n", buf
);
2025 if (cyls
|| heads
|| secs
) {
2026 if (cyls
< 1 || (type
== IF_IDE
&& cyls
> 16383)) {
2027 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", buf
);
2030 if (heads
< 1 || (type
== IF_IDE
&& heads
> 16)) {
2031 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", buf
);
2034 if (secs
< 1 || (type
== IF_IDE
&& secs
> 63)) {
2035 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", buf
);
2040 if ((buf
= qemu_opt_get(opts
, "trans")) != NULL
) {
2043 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2047 if (!strcmp(buf
, "none"))
2048 translation
= BIOS_ATA_TRANSLATION_NONE
;
2049 else if (!strcmp(buf
, "lba"))
2050 translation
= BIOS_ATA_TRANSLATION_LBA
;
2051 else if (!strcmp(buf
, "auto"))
2052 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2054 fprintf(stderr
, "qemu: '%s' invalid translation type\n", buf
);
2059 if ((buf
= qemu_opt_get(opts
, "media")) != NULL
) {
2060 if (!strcmp(buf
, "disk")) {
2062 } else if (!strcmp(buf
, "cdrom")) {
2063 if (cyls
|| secs
|| heads
) {
2065 "qemu: '%s' invalid physical CHS format\n", buf
);
2068 media
= MEDIA_CDROM
;
2070 fprintf(stderr
, "qemu: '%s' invalid media\n", buf
);
2075 if ((buf
= qemu_opt_get(opts
, "cache")) != NULL
) {
2076 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2078 else if (!strcmp(buf
, "writethrough"))
2080 else if (!strcmp(buf
, "writeback"))
2083 fprintf(stderr
, "qemu: invalid cache option\n");
2088 #ifdef CONFIG_LINUX_AIO
2089 if ((buf
= qemu_opt_get(opts
, "aio")) != NULL
) {
2090 if (!strcmp(buf
, "threads"))
2092 else if (!strcmp(buf
, "native"))
2095 fprintf(stderr
, "qemu: invalid aio option\n");
2101 if ((buf
= qemu_opt_get(opts
, "format")) != NULL
) {
2102 if (strcmp(buf
, "?") == 0) {
2103 fprintf(stderr
, "qemu: Supported formats:");
2104 bdrv_iterate_format(bdrv_format_print
, NULL
);
2105 fprintf(stderr
, "\n");
2108 drv
= bdrv_find_whitelisted_format(buf
);
2110 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2115 is_extboot
= qemu_opt_get_bool(opts
, "boot", 0);
2116 if (is_extboot
&& extboot_drive
) {
2117 fprintf(stderr
, "qemu: two bootable drives specified\n");
2121 on_write_error
= BLOCK_ERR_STOP_ENOSPC
;
2122 if ((buf
= qemu_opt_get(opts
, "werror")) != NULL
) {
2123 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2124 fprintf(stderr
, "werror is no supported by this format\n");
2128 on_write_error
= parse_block_error_action(buf
, 0);
2129 if (on_write_error
< 0) {
2134 on_read_error
= BLOCK_ERR_REPORT
;
2135 if ((buf
= qemu_opt_get(opts
, "rerror")) != NULL
) {
2136 if (type
!= IF_IDE
&& type
!= IF_VIRTIO
) {
2137 fprintf(stderr
, "rerror is no supported by this format\n");
2141 on_read_error
= parse_block_error_action(buf
, 1);
2142 if (on_read_error
< 0) {
2147 if ((devaddr
= qemu_opt_get(opts
, "addr")) != NULL
) {
2148 if (type
!= IF_VIRTIO
) {
2149 fprintf(stderr
, "addr is not supported\n");
2154 /* compute bus and unit according index */
2157 if (bus_id
!= 0 || unit_id
!= -1) {
2159 "qemu: index cannot be used with bus and unit\n");
2167 unit_id
= index
% max_devs
;
2168 bus_id
= index
/ max_devs
;
2172 /* if user doesn't specify a unit_id,
2173 * try to find the first free
2176 if (unit_id
== -1) {
2178 while (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2180 if (max_devs
&& unit_id
>= max_devs
) {
2181 unit_id
-= max_devs
;
2189 if (max_devs
&& unit_id
>= max_devs
) {
2190 fprintf(stderr
, "qemu: unit %d too big (max is %d)\n",
2191 unit_id
, max_devs
- 1);
2196 * ignore multiple definitions
2199 if (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2206 dinfo
= qemu_mallocz(sizeof(*dinfo
));
2207 if ((buf
= qemu_opts_id(opts
)) != NULL
) {
2208 dinfo
->id
= qemu_strdup(buf
);
2210 /* no id supplied -> create one */
2211 dinfo
->id
= qemu_mallocz(32);
2212 if (type
== IF_IDE
|| type
== IF_SCSI
)
2213 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2215 snprintf(dinfo
->id
, 32, "%s%i%s%i",
2216 devname
, bus_id
, mediastr
, unit_id
);
2218 snprintf(dinfo
->id
, 32, "%s%s%i",
2219 devname
, mediastr
, unit_id
);
2221 dinfo
->bdrv
= bdrv_new(dinfo
->id
);
2222 dinfo
->devaddr
= devaddr
;
2224 dinfo
->bus
= bus_id
;
2225 dinfo
->unit
= unit_id
;
2226 dinfo
->on_read_error
= on_read_error
;
2227 dinfo
->on_write_error
= on_write_error
;
2230 strncpy(dinfo
->serial
, serial
, sizeof(serial
));
2231 QTAILQ_INSERT_TAIL(&drives
, dinfo
, next
);
2233 extboot_drive
= dinfo
;
2244 bdrv_set_geometry_hint(dinfo
->bdrv
, cyls
, heads
, secs
);
2245 bdrv_set_translation_hint(dinfo
->bdrv
, translation
);
2249 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_CDROM
);
2254 /* FIXME: This isn't really a floppy, but it's a reasonable
2257 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_FLOPPY
);
2263 /* add virtio block device */
2264 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
2265 qemu_opt_set(opts
, "driver", "virtio-blk-pci");
2266 qemu_opt_set(opts
, "drive", dinfo
->id
);
2268 qemu_opt_set(opts
, "addr", devaddr
);
2279 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2280 cache
= 2; /* always use write-back with snapshot */
2282 if (cache
== 0) /* no caching */
2283 bdrv_flags
|= BDRV_O_NOCACHE
;
2284 else if (cache
== 2) /* write-back */
2285 bdrv_flags
|= BDRV_O_CACHE_WB
;
2288 bdrv_flags
|= BDRV_O_NATIVE_AIO
;
2290 bdrv_flags
&= ~BDRV_O_NATIVE_AIO
;
2294 if (type
!= IF_SCSI
&& type
!= IF_VIRTIO
&& type
!= IF_FLOPPY
) {
2295 fprintf(stderr
, "qemu: readonly flag not supported for drive with this interface\n");
2300 * cdrom is read-only. Set it now, after above interface checking
2301 * since readonly attribute not explicitly required, so no error.
2303 if (media
== MEDIA_CDROM
) {
2306 bdrv_flags
|= ro
? 0 : BDRV_O_RDWR
;
2308 if (bdrv_open2(dinfo
->bdrv
, file
, bdrv_flags
, drv
) < 0) {
2309 fprintf(stderr
, "qemu: could not open disk image %s: %s\n",
2310 file
, strerror(errno
));
2314 if (bdrv_key_required(dinfo
->bdrv
))
2320 static int drive_init_func(QemuOpts
*opts
, void *opaque
)
2322 QEMUMachine
*machine
= opaque
;
2323 int fatal_error
= 0;
2325 if (drive_init(opts
, machine
, &fatal_error
) == NULL
) {
2332 static int drive_enable_snapshot(QemuOpts
*opts
, void *opaque
)
2334 if (NULL
== qemu_opt_get(opts
, "snapshot")) {
2335 qemu_opt_set(opts
, "snapshot", "on");
2340 void qemu_register_boot_set(QEMUBootSetHandler
*func
, void *opaque
)
2342 boot_set_handler
= func
;
2343 boot_set_opaque
= opaque
;
2346 int qemu_boot_set(const char *boot_devices
)
2348 if (!boot_set_handler
) {
2351 return boot_set_handler(boot_set_opaque
, boot_devices
);
2354 static int parse_bootdevices(char *devices
)
2356 /* We just do some generic consistency checks */
2360 for (p
= devices
; *p
!= '\0'; p
++) {
2361 /* Allowed boot devices are:
2362 * a-b: floppy disk drives
2363 * c-f: IDE disk drives
2364 * g-m: machine implementation dependant drives
2365 * n-p: network devices
2366 * It's up to each machine implementation to check if the given boot
2367 * devices match the actual hardware implementation and firmware
2370 if (*p
< 'a' || *p
> 'p') {
2371 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
2374 if (bitmap
& (1 << (*p
- 'a'))) {
2375 fprintf(stderr
, "Boot device '%c' was given twice\n", *p
);
2378 bitmap
|= 1 << (*p
- 'a');
2383 static void restore_boot_devices(void *opaque
)
2385 char *standard_boot_devices
= opaque
;
2387 qemu_boot_set(standard_boot_devices
);
2389 qemu_unregister_reset(restore_boot_devices
, standard_boot_devices
);
2390 qemu_free(standard_boot_devices
);
2393 static void numa_add(const char *optarg
)
2397 unsigned long long value
, endvalue
;
2400 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2401 if (!strcmp(option
, "node")) {
2402 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2403 nodenr
= nb_numa_nodes
;
2405 nodenr
= strtoull(option
, NULL
, 10);
2408 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2409 node_mem
[nodenr
] = 0;
2411 value
= strtoull(option
, &endptr
, 0);
2413 case 0: case 'M': case 'm':
2420 node_mem
[nodenr
] = value
;
2422 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2423 node_cpumask
[nodenr
] = 0;
2425 value
= strtoull(option
, &endptr
, 10);
2428 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2430 if (*endptr
== '-') {
2431 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2432 if (endvalue
>= 63) {
2435 "only 63 CPUs in NUMA mode supported.\n");
2437 value
= (2ULL << endvalue
) - (1ULL << value
);
2439 value
= 1ULL << value
;
2442 node_cpumask
[nodenr
] = value
;
2449 static void smp_parse(const char *optarg
)
2451 int smp
, sockets
= 0, threads
= 0, cores
= 0;
2455 smp
= strtoul(optarg
, &endptr
, 10);
2456 if (endptr
!= optarg
) {
2457 if (*endptr
== ',') {
2461 if (get_param_value(option
, 128, "sockets", endptr
) != 0)
2462 sockets
= strtoull(option
, NULL
, 10);
2463 if (get_param_value(option
, 128, "cores", endptr
) != 0)
2464 cores
= strtoull(option
, NULL
, 10);
2465 if (get_param_value(option
, 128, "threads", endptr
) != 0)
2466 threads
= strtoull(option
, NULL
, 10);
2467 if (get_param_value(option
, 128, "maxcpus", endptr
) != 0)
2468 max_cpus
= strtoull(option
, NULL
, 10);
2470 /* compute missing values, prefer sockets over cores over threads */
2471 if (smp
== 0 || sockets
== 0) {
2472 sockets
= sockets
> 0 ? sockets
: 1;
2473 cores
= cores
> 0 ? cores
: 1;
2474 threads
= threads
> 0 ? threads
: 1;
2476 smp
= cores
* threads
* sockets
;
2480 threads
= threads
> 0 ? threads
: 1;
2481 cores
= smp
/ (sockets
* threads
);
2484 threads
= smp
/ (cores
* sockets
);
2489 smp_cores
= cores
> 0 ? cores
: 1;
2490 smp_threads
= threads
> 0 ? threads
: 1;
2492 max_cpus
= smp_cpus
;
2495 /***********************************************************/
2498 static int usb_device_add(const char *devname
, int is_hotplug
)
2501 USBDevice
*dev
= NULL
;
2506 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2507 dev
= usbdevice_create(devname
);
2511 /* the other ones */
2512 if (strstart(devname
, "host:", &p
)) {
2513 dev
= usb_host_device_open(p
);
2514 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2515 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2516 bt_new_hci(qemu_find_bt_vlan(0)));
2527 static int usb_device_del(const char *devname
)
2532 if (strstart(devname
, "host:", &p
))
2533 return usb_host_device_close(p
);
2538 p
= strchr(devname
, '.');
2541 bus_num
= strtoul(devname
, NULL
, 0);
2542 addr
= strtoul(p
+ 1, NULL
, 0);
2544 return usb_device_delete_addr(bus_num
, addr
);
2547 static int usb_parse(const char *cmdline
)
2550 r
= usb_device_add(cmdline
, 0);
2552 fprintf(stderr
, "qemu: could not add USB device '%s'\n", cmdline
);
2557 void do_usb_add(Monitor
*mon
, const QDict
*qdict
)
2559 const char *devname
= qdict_get_str(qdict
, "devname");
2560 if (usb_device_add(devname
, 1) < 0) {
2561 qemu_error("could not add USB device '%s'\n", devname
);
2565 void do_usb_del(Monitor
*mon
, const QDict
*qdict
)
2567 const char *devname
= qdict_get_str(qdict
, "devname");
2568 if (usb_device_del(devname
) < 0) {
2569 qemu_error("could not delete USB device '%s'\n", devname
);
2573 /***********************************************************/
2574 /* PCMCIA/Cardbus */
2576 static struct pcmcia_socket_entry_s
{
2577 PCMCIASocket
*socket
;
2578 struct pcmcia_socket_entry_s
*next
;
2579 } *pcmcia_sockets
= 0;
2581 void pcmcia_socket_register(PCMCIASocket
*socket
)
2583 struct pcmcia_socket_entry_s
*entry
;
2585 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2586 entry
->socket
= socket
;
2587 entry
->next
= pcmcia_sockets
;
2588 pcmcia_sockets
= entry
;
2591 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2593 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2595 ptr
= &pcmcia_sockets
;
2596 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2597 if (entry
->socket
== socket
) {
2603 void pcmcia_info(Monitor
*mon
)
2605 struct pcmcia_socket_entry_s
*iter
;
2607 if (!pcmcia_sockets
)
2608 monitor_printf(mon
, "No PCMCIA sockets\n");
2610 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2611 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2612 iter
->socket
->attached
? iter
->socket
->card_string
:
2616 /***********************************************************/
2619 typedef struct IOHandlerRecord
{
2621 IOCanRWHandler
*fd_read_poll
;
2623 IOHandler
*fd_write
;
2626 /* temporary data */
2628 struct IOHandlerRecord
*next
;
2631 static IOHandlerRecord
*first_io_handler
;
2633 /* XXX: fd_read_poll should be suppressed, but an API change is
2634 necessary in the character devices to suppress fd_can_read(). */
2635 int qemu_set_fd_handler2(int fd
,
2636 IOCanRWHandler
*fd_read_poll
,
2638 IOHandler
*fd_write
,
2641 IOHandlerRecord
**pioh
, *ioh
;
2643 if (!fd_read
&& !fd_write
) {
2644 pioh
= &first_io_handler
;
2649 if (ioh
->fd
== fd
) {
2656 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
2660 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
2661 ioh
->next
= first_io_handler
;
2662 first_io_handler
= ioh
;
2665 ioh
->fd_read_poll
= fd_read_poll
;
2666 ioh
->fd_read
= fd_read
;
2667 ioh
->fd_write
= fd_write
;
2668 ioh
->opaque
= opaque
;
2671 qemu_notify_event();
2675 int qemu_set_fd_handler(int fd
,
2677 IOHandler
*fd_write
,
2680 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
2684 /***********************************************************/
2685 /* Polling handling */
2687 typedef struct PollingEntry
{
2690 struct PollingEntry
*next
;
2693 static PollingEntry
*first_polling_entry
;
2695 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
2697 PollingEntry
**ppe
, *pe
;
2698 pe
= qemu_mallocz(sizeof(PollingEntry
));
2700 pe
->opaque
= opaque
;
2701 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
2706 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
2708 PollingEntry
**ppe
, *pe
;
2709 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
2711 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
2719 /***********************************************************/
2720 /* Wait objects support */
2721 typedef struct WaitObjects
{
2723 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
2724 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
2725 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
2728 static WaitObjects wait_objects
= {0};
2730 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2732 WaitObjects
*w
= &wait_objects
;
2734 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
2736 w
->events
[w
->num
] = handle
;
2737 w
->func
[w
->num
] = func
;
2738 w
->opaque
[w
->num
] = opaque
;
2743 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2746 WaitObjects
*w
= &wait_objects
;
2749 for (i
= 0; i
< w
->num
; i
++) {
2750 if (w
->events
[i
] == handle
)
2753 w
->events
[i
] = w
->events
[i
+ 1];
2754 w
->func
[i
] = w
->func
[i
+ 1];
2755 w
->opaque
[i
] = w
->opaque
[i
+ 1];
2763 /***********************************************************/
2764 /* ram save/restore */
2766 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2767 #define RAM_SAVE_FLAG_COMPRESS 0x02
2768 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2769 #define RAM_SAVE_FLAG_PAGE 0x08
2770 #define RAM_SAVE_FLAG_EOS 0x10
2772 static int is_dup_page(uint8_t *page
, uint8_t ch
)
2774 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
2775 uint32_t *array
= (uint32_t *)page
;
2778 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
2779 if (array
[i
] != val
)
2786 static int ram_save_block(QEMUFile
*f
)
2788 static ram_addr_t current_addr
= 0;
2789 ram_addr_t saved_addr
= current_addr
;
2790 ram_addr_t addr
= 0;
2793 while (addr
< last_ram_offset
) {
2794 if (kvm_enabled() && current_addr
== 0) {
2796 r
= kvm_update_dirty_pages_log();
2798 fprintf(stderr
, "%s: update dirty pages log failed %d\n", __FUNCTION__
, r
);
2799 qemu_file_set_error(f
);
2803 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
2806 cpu_physical_memory_reset_dirty(current_addr
,
2807 current_addr
+ TARGET_PAGE_SIZE
,
2808 MIGRATION_DIRTY_FLAG
);
2810 p
= qemu_get_ram_ptr(current_addr
);
2812 if (is_dup_page(p
, *p
)) {
2813 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
2814 qemu_put_byte(f
, *p
);
2816 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
2817 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
2823 addr
+= TARGET_PAGE_SIZE
;
2824 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
2830 static uint64_t bytes_transferred
;
2832 static ram_addr_t
ram_save_remaining(void)
2835 ram_addr_t count
= 0;
2837 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2838 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2845 uint64_t ram_bytes_remaining(void)
2847 return ram_save_remaining() * TARGET_PAGE_SIZE
;
2850 uint64_t ram_bytes_transferred(void)
2852 return bytes_transferred
;
2855 uint64_t ram_bytes_total(void)
2857 return last_ram_offset
;
2860 static int ram_save_live(Monitor
*mon
, QEMUFile
*f
, int stage
, void *opaque
)
2863 uint64_t bytes_transferred_last
;
2865 uint64_t expected_time
= 0;
2868 cpu_physical_memory_set_dirty_tracking(0);
2872 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX
) != 0) {
2873 qemu_file_set_error(f
);
2878 bytes_transferred
= 0;
2880 /* Make sure all dirty bits are set */
2881 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2882 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2883 cpu_physical_memory_set_dirty(addr
);
2886 /* Enable dirty memory tracking */
2887 cpu_physical_memory_set_dirty_tracking(1);
2889 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
2892 bytes_transferred_last
= bytes_transferred
;
2893 bwidth
= qemu_get_clock_ns(rt_clock
);
2895 while (!qemu_file_rate_limit(f
)) {
2898 ret
= ram_save_block(f
);
2899 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
2900 if (ret
== 0) /* no more blocks */
2904 bwidth
= qemu_get_clock_ns(rt_clock
) - bwidth
;
2905 bwidth
= (bytes_transferred
- bytes_transferred_last
) / bwidth
;
2907 /* if we haven't transferred anything this round, force expected_time to a
2908 * a very high value, but without crashing */
2912 /* try transferring iterative blocks of memory */
2914 /* flush all remaining blocks regardless of rate limiting */
2915 while (ram_save_block(f
) != 0) {
2916 bytes_transferred
+= TARGET_PAGE_SIZE
;
2918 cpu_physical_memory_set_dirty_tracking(0);
2921 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
2923 expected_time
= ram_save_remaining() * TARGET_PAGE_SIZE
/ bwidth
;
2925 return (stage
== 2) && (expected_time
<= migrate_max_downtime());
2928 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
2933 if (version_id
!= 3)
2937 addr
= qemu_get_be64(f
);
2939 flags
= addr
& ~TARGET_PAGE_MASK
;
2940 addr
&= TARGET_PAGE_MASK
;
2942 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
2943 if (addr
!= last_ram_offset
)
2947 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
2948 uint8_t ch
= qemu_get_byte(f
);
2949 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
2952 (!kvm_enabled() || kvm_has_sync_mmu())) {
2953 madvise(qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
, MADV_DONTNEED
);
2956 } else if (flags
& RAM_SAVE_FLAG_PAGE
) {
2957 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
2959 if (qemu_file_has_error(f
)) {
2962 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
2967 void qemu_service_io(void)
2969 qemu_notify_event();
2972 /***********************************************************/
2973 /* machine registration */
2975 static QEMUMachine
*first_machine
= NULL
;
2976 QEMUMachine
*current_machine
= NULL
;
2978 int qemu_register_machine(QEMUMachine
*m
)
2981 pm
= &first_machine
;
2989 static QEMUMachine
*find_machine(const char *name
)
2993 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
2994 if (!strcmp(m
->name
, name
))
2996 if (m
->alias
&& !strcmp(m
->alias
, name
))
3002 static QEMUMachine
*find_default_machine(void)
3006 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3007 if (m
->is_default
) {
3014 /***********************************************************/
3015 /* main execution loop */
3017 static void gui_update(void *opaque
)
3019 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3020 DisplayState
*ds
= opaque
;
3021 DisplayChangeListener
*dcl
= ds
->listeners
;
3023 qemu_flush_coalesced_mmio_buffer();
3026 while (dcl
!= NULL
) {
3027 if (dcl
->gui_timer_interval
&&
3028 dcl
->gui_timer_interval
< interval
)
3029 interval
= dcl
->gui_timer_interval
;
3032 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3035 static void nographic_update(void *opaque
)
3037 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3039 qemu_flush_coalesced_mmio_buffer();
3040 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3043 void cpu_synchronize_all_states(void)
3047 for (cpu
= first_cpu
; cpu
; cpu
= cpu
->next_cpu
) {
3048 cpu_synchronize_state(cpu
);
3052 void cpu_synchronize_all_post_reset(void)
3056 for (cpu
= first_cpu
; cpu
; cpu
= cpu
->next_cpu
) {
3057 cpu_synchronize_post_reset(cpu
);
3061 void cpu_synchronize_all_post_init(void)
3065 for (cpu
= first_cpu
; cpu
; cpu
= cpu
->next_cpu
) {
3066 cpu_synchronize_post_init(cpu
);
3070 struct vm_change_state_entry
{
3071 VMChangeStateHandler
*cb
;
3073 QLIST_ENTRY (vm_change_state_entry
) entries
;
3076 static QLIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3078 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3081 VMChangeStateEntry
*e
;
3083 e
= qemu_mallocz(sizeof (*e
));
3087 QLIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3091 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3093 QLIST_REMOVE (e
, entries
);
3097 static void vm_state_notify(int running
, int reason
)
3099 VMChangeStateEntry
*e
;
3101 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3102 e
->cb(e
->opaque
, running
, reason
);
3106 static void resume_all_vcpus(void);
3107 static void pause_all_vcpus(void);
3114 vm_state_notify(1, 0);
3115 qemu_rearm_alarm_timer(alarm_timer
);
3120 /* reset/shutdown handler */
3122 typedef struct QEMUResetEntry
{
3123 QTAILQ_ENTRY(QEMUResetEntry
) entry
;
3124 QEMUResetHandler
*func
;
3128 static QTAILQ_HEAD(reset_handlers
, QEMUResetEntry
) reset_handlers
=
3129 QTAILQ_HEAD_INITIALIZER(reset_handlers
);
3130 static int reset_requested
;
3131 static int shutdown_requested
;
3132 static int powerdown_requested
;
3133 static int debug_requested
;
3134 static int vmstop_requested
;
3136 int qemu_no_shutdown(void)
3138 int r
= no_shutdown
;
3143 int qemu_shutdown_requested(void)
3145 int r
= shutdown_requested
;
3146 shutdown_requested
= 0;
3150 int qemu_reset_requested(void)
3152 int r
= reset_requested
;
3153 reset_requested
= 0;
3157 int qemu_powerdown_requested(void)
3159 int r
= powerdown_requested
;
3160 powerdown_requested
= 0;
3164 static int qemu_debug_requested(void)
3166 int r
= debug_requested
;
3167 debug_requested
= 0;
3171 static int qemu_vmstop_requested(void)
3173 int r
= vmstop_requested
;
3174 vmstop_requested
= 0;
3178 static void do_vm_stop(int reason
)
3181 cpu_disable_ticks();
3184 vm_state_notify(0, reason
);
3185 monitor_protocol_event(QEVENT_STOP
, NULL
);
3189 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3191 QEMUResetEntry
*re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3194 re
->opaque
= opaque
;
3195 QTAILQ_INSERT_TAIL(&reset_handlers
, re
, entry
);
3198 void qemu_unregister_reset(QEMUResetHandler
*func
, void *opaque
)
3202 QTAILQ_FOREACH(re
, &reset_handlers
, entry
) {
3203 if (re
->func
== func
&& re
->opaque
== opaque
) {
3204 QTAILQ_REMOVE(&reset_handlers
, re
, entry
);
3211 void qemu_system_reset(void)
3213 QEMUResetEntry
*re
, *nre
;
3215 /* reset all devices */
3216 QTAILQ_FOREACH_SAFE(re
, &reset_handlers
, entry
, nre
) {
3217 re
->func(re
->opaque
);
3219 monitor_protocol_event(QEVENT_RESET
, NULL
);
3220 cpu_synchronize_all_post_reset();
3223 void qemu_system_reset_request(void)
3226 shutdown_requested
= 1;
3228 reset_requested
= 1;
3230 if (cpu_single_env
) {
3231 cpu_single_env
->stopped
= 1;
3233 qemu_notify_event();
3236 void qemu_system_shutdown_request(void)
3238 shutdown_requested
= 1;
3239 qemu_notify_event();
3242 void qemu_system_powerdown_request(void)
3244 powerdown_requested
= 1;
3245 qemu_notify_event();
3248 #ifdef CONFIG_IOTHREAD
3249 static void qemu_system_vmstop_request(int reason
)
3251 vmstop_requested
= reason
;
3252 qemu_notify_event();
3257 static int io_thread_fd
= -1;
3259 static void qemu_event_increment(void)
3261 /* Write 8 bytes to be compatible with eventfd. */
3262 static uint64_t val
= 1;
3265 if (io_thread_fd
== -1)
3269 ret
= write(io_thread_fd
, &val
, sizeof(val
));
3270 } while (ret
< 0 && errno
== EINTR
);
3272 /* EAGAIN is fine, a read must be pending. */
3273 if (ret
< 0 && errno
!= EAGAIN
) {
3274 fprintf(stderr
, "qemu_event_increment: write() filed: %s\n",
3280 static void qemu_event_read(void *opaque
)
3282 int fd
= (unsigned long)opaque
;
3286 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
3288 len
= read(fd
, buffer
, sizeof(buffer
));
3289 } while ((len
== -1 && errno
== EINTR
) || len
== sizeof(buffer
));
3292 static int qemu_event_init(void)
3297 err
= qemu_eventfd(fds
);
3301 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3305 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3309 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3310 (void *)(unsigned long)fds
[0]);
3312 io_thread_fd
= fds
[1];
3321 HANDLE qemu_event_handle
;
3323 static void dummy_event_handler(void *opaque
)
3327 static int qemu_event_init(void)
3329 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3330 if (!qemu_event_handle
) {
3331 fprintf(stderr
, "Failed CreateEvent: %ld\n", GetLastError());
3334 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3338 static void qemu_event_increment(void)
3340 if (!SetEvent(qemu_event_handle
)) {
3341 fprintf(stderr
, "qemu_event_increment: SetEvent failed: %ld\n",
3348 static int cpu_can_run(CPUState
*env
)
3359 #ifndef CONFIG_IOTHREAD
3360 static int qemu_init_main_loop(void)
3362 return qemu_event_init();
3365 void qemu_init_vcpu(void *_env
)
3367 CPUState
*env
= _env
;
3369 env
->nr_cores
= smp_cores
;
3370 env
->nr_threads
= smp_threads
;
3376 int qemu_cpu_self(void *env
)
3381 static void resume_all_vcpus(void)
3385 static void pause_all_vcpus(void)
3389 void qemu_cpu_kick(void *env
)
3394 void qemu_notify_event(void)
3396 CPUState
*env
= cpu_single_env
;
3398 if (kvm_enabled()) {
3399 qemu_kvm_notify_work();
3407 #if defined(KVM_UPSTREAM) || !defined(CONFIG_KVM)
3408 void qemu_mutex_lock_iothread(void) {}
3409 void qemu_mutex_unlock_iothread(void) {}
3412 void vm_stop(int reason
)
3417 #else /* CONFIG_IOTHREAD */
3419 #include "qemu-thread.h"
3421 QemuMutex qemu_global_mutex
;
3422 static QemuMutex qemu_fair_mutex
;
3424 static QemuThread io_thread
;
3426 static QemuThread
*tcg_cpu_thread
;
3427 static QemuCond
*tcg_halt_cond
;
3429 static int qemu_system_ready
;
3431 static QemuCond qemu_cpu_cond
;
3433 static QemuCond qemu_system_cond
;
3434 static QemuCond qemu_pause_cond
;
3436 static void tcg_block_io_signals(void);
3437 static void kvm_block_io_signals(CPUState
*env
);
3438 static void unblock_io_signals(void);
3439 static int tcg_has_work(void);
3440 static int cpu_has_work(CPUState
*env
);
3442 static int qemu_init_main_loop(void)
3446 ret
= qemu_event_init();
3450 qemu_cond_init(&qemu_pause_cond
);
3451 qemu_mutex_init(&qemu_fair_mutex
);
3452 qemu_mutex_init(&qemu_global_mutex
);
3453 qemu_mutex_lock(&qemu_global_mutex
);
3455 unblock_io_signals();
3456 qemu_thread_self(&io_thread
);
3461 static void qemu_wait_io_event_common(CPUState
*env
)
3466 qemu_cond_signal(&qemu_pause_cond
);
3470 static void qemu_wait_io_event(CPUState
*env
)
3472 while (!tcg_has_work())
3473 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3475 qemu_mutex_unlock(&qemu_global_mutex
);
3478 * Users of qemu_global_mutex can be starved, having no chance
3479 * to acquire it since this path will get to it first.
3480 * So use another lock to provide fairness.
3482 qemu_mutex_lock(&qemu_fair_mutex
);
3483 qemu_mutex_unlock(&qemu_fair_mutex
);
3485 qemu_mutex_lock(&qemu_global_mutex
);
3486 qemu_wait_io_event_common(env
);
3489 static void qemu_kvm_eat_signal(CPUState
*env
, int timeout
)
3496 ts
.tv_sec
= timeout
/ 1000;
3497 ts
.tv_nsec
= (timeout
% 1000) * 1000000;
3499 sigemptyset(&waitset
);
3500 sigaddset(&waitset
, SIG_IPI
);
3502 qemu_mutex_unlock(&qemu_global_mutex
);
3503 r
= sigtimedwait(&waitset
, &siginfo
, &ts
);
3505 qemu_mutex_lock(&qemu_global_mutex
);
3507 if (r
== -1 && !(e
== EAGAIN
|| e
== EINTR
)) {
3508 fprintf(stderr
, "sigtimedwait: %s\n", strerror(e
));
3513 static void qemu_kvm_wait_io_event(CPUState
*env
)
3515 while (!cpu_has_work(env
))
3516 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3518 qemu_kvm_eat_signal(env
, 0);
3519 qemu_wait_io_event_common(env
);
3522 static int qemu_cpu_exec(CPUState
*env
);
3524 static void *kvm_cpu_thread_fn(void *arg
)
3526 CPUState
*env
= arg
;
3528 qemu_thread_self(env
->thread
);
3532 kvm_block_io_signals(env
);
3534 /* signal CPU creation */
3535 qemu_mutex_lock(&qemu_global_mutex
);
3537 qemu_cond_signal(&qemu_cpu_cond
);
3539 /* and wait for machine initialization */
3540 while (!qemu_system_ready
)
3541 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3544 if (cpu_can_run(env
))
3546 qemu_kvm_wait_io_event(env
);
3552 static void tcg_cpu_exec(void);
3554 static void *tcg_cpu_thread_fn(void *arg
)
3556 CPUState
*env
= arg
;
3558 tcg_block_io_signals();
3559 qemu_thread_self(env
->thread
);
3561 /* signal CPU creation */
3562 qemu_mutex_lock(&qemu_global_mutex
);
3563 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
3565 qemu_cond_signal(&qemu_cpu_cond
);
3567 /* and wait for machine initialization */
3568 while (!qemu_system_ready
)
3569 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3573 qemu_wait_io_event(cur_cpu
);
3579 void qemu_cpu_kick(void *_env
)
3581 CPUState
*env
= _env
;
3582 qemu_cond_broadcast(env
->halt_cond
);
3584 qemu_thread_signal(env
->thread
, SIG_IPI
);
3587 int qemu_cpu_self(void *_env
)
3589 CPUState
*env
= _env
;
3592 qemu_thread_self(&this);
3594 return qemu_thread_equal(&this, env
->thread
);
3597 static void cpu_signal(int sig
)
3600 cpu_exit(cpu_single_env
);
3603 static void tcg_block_io_signals(void)
3606 struct sigaction sigact
;
3609 sigaddset(&set
, SIGUSR2
);
3610 sigaddset(&set
, SIGIO
);
3611 sigaddset(&set
, SIGALRM
);
3612 sigaddset(&set
, SIGCHLD
);
3613 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3616 sigaddset(&set
, SIG_IPI
);
3617 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3619 memset(&sigact
, 0, sizeof(sigact
));
3620 sigact
.sa_handler
= cpu_signal
;
3621 sigaction(SIG_IPI
, &sigact
, NULL
);
3624 static void dummy_signal(int sig
)
3628 static void kvm_block_io_signals(CPUState
*env
)
3632 struct sigaction sigact
;
3635 sigaddset(&set
, SIGUSR2
);
3636 sigaddset(&set
, SIGIO
);
3637 sigaddset(&set
, SIGALRM
);
3638 sigaddset(&set
, SIGCHLD
);
3639 sigaddset(&set
, SIG_IPI
);
3640 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3642 pthread_sigmask(SIG_BLOCK
, NULL
, &set
);
3643 sigdelset(&set
, SIG_IPI
);
3645 memset(&sigact
, 0, sizeof(sigact
));
3646 sigact
.sa_handler
= dummy_signal
;
3647 sigaction(SIG_IPI
, &sigact
, NULL
);
3649 r
= kvm_set_signal_mask(env
, &set
);
3651 fprintf(stderr
, "kvm_set_signal_mask: %s\n", strerror(r
));
3656 static void unblock_io_signals(void)
3661 sigaddset(&set
, SIGUSR2
);
3662 sigaddset(&set
, SIGIO
);
3663 sigaddset(&set
, SIGALRM
);
3664 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3667 sigaddset(&set
, SIG_IPI
);
3668 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3671 static void qemu_signal_lock(unsigned int msecs
)
3673 qemu_mutex_lock(&qemu_fair_mutex
);
3675 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
3676 qemu_thread_signal(tcg_cpu_thread
, SIG_IPI
);
3677 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
3680 qemu_mutex_unlock(&qemu_fair_mutex
);
3683 void qemu_mutex_lock_iothread(void)
3685 if (kvm_enabled()) {
3686 qemu_mutex_lock(&qemu_fair_mutex
);
3687 qemu_mutex_lock(&qemu_global_mutex
);
3688 qemu_mutex_unlock(&qemu_fair_mutex
);
3690 qemu_signal_lock(100);
3693 void qemu_mutex_unlock_iothread(void)
3695 qemu_mutex_unlock(&qemu_global_mutex
);
3698 static int all_vcpus_paused(void)
3700 CPUState
*penv
= first_cpu
;
3705 penv
= (CPUState
*)penv
->next_cpu
;
3711 static void pause_all_vcpus(void)
3713 CPUState
*penv
= first_cpu
;
3717 qemu_thread_signal(penv
->thread
, SIG_IPI
);
3718 qemu_cpu_kick(penv
);
3719 penv
= (CPUState
*)penv
->next_cpu
;
3722 while (!all_vcpus_paused()) {
3723 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
3726 qemu_thread_signal(penv
->thread
, SIG_IPI
);
3727 penv
= (CPUState
*)penv
->next_cpu
;
3732 static void resume_all_vcpus(void)
3734 CPUState
*penv
= first_cpu
;
3739 qemu_thread_signal(penv
->thread
, SIG_IPI
);
3740 qemu_cpu_kick(penv
);
3741 penv
= (CPUState
*)penv
->next_cpu
;
3745 static void tcg_init_vcpu(void *_env
)
3747 CPUState
*env
= _env
;
3748 /* share a single thread for all cpus with TCG */
3749 if (!tcg_cpu_thread
) {
3750 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3751 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3752 qemu_cond_init(env
->halt_cond
);
3753 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
3754 while (env
->created
== 0)
3755 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3756 tcg_cpu_thread
= env
->thread
;
3757 tcg_halt_cond
= env
->halt_cond
;
3759 env
->thread
= tcg_cpu_thread
;
3760 env
->halt_cond
= tcg_halt_cond
;
3764 static void kvm_start_vcpu(CPUState
*env
)
3766 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3767 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3768 qemu_cond_init(env
->halt_cond
);
3769 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
3770 while (env
->created
== 0)
3771 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3774 void qemu_init_vcpu(void *_env
)
3776 CPUState
*env
= _env
;
3778 env
->nr_cores
= smp_cores
;
3779 env
->nr_threads
= smp_threads
;
3781 kvm_start_vcpu(env
);
3786 void qemu_notify_event(void)
3788 qemu_event_increment();
3791 void vm_stop(int reason
)
3794 qemu_thread_self(&me
);
3796 if (!qemu_thread_equal(&me
, &io_thread
)) {
3797 qemu_system_vmstop_request(reason
);
3799 * FIXME: should not return to device code in case
3800 * vm_stop() has been requested.
3802 if (cpu_single_env
) {
3803 cpu_exit(cpu_single_env
);
3804 cpu_single_env
->stop
= 1;
3815 static void host_main_loop_wait(int *timeout
)
3821 /* XXX: need to suppress polling by better using win32 events */
3823 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
3824 ret
|= pe
->func(pe
->opaque
);
3828 WaitObjects
*w
= &wait_objects
;
3830 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
3831 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
3832 if (w
->func
[ret
- WAIT_OBJECT_0
])
3833 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
3835 /* Check for additional signaled events */
3836 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
3838 /* Check if event is signaled */
3839 ret2
= WaitForSingleObject(w
->events
[i
], 0);
3840 if(ret2
== WAIT_OBJECT_0
) {
3842 w
->func
[i
](w
->opaque
[i
]);
3843 } else if (ret2
== WAIT_TIMEOUT
) {
3845 err
= GetLastError();
3846 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
3849 } else if (ret
== WAIT_TIMEOUT
) {
3851 err
= GetLastError();
3852 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
3859 static void host_main_loop_wait(int *timeout
)
3864 void main_loop_wait(int timeout
)
3866 IOHandlerRecord
*ioh
;
3867 fd_set rfds
, wfds
, xfds
;
3871 qemu_bh_update_timeout(&timeout
);
3873 host_main_loop_wait(&timeout
);
3875 /* poll any events */
3876 /* XXX: separate device handlers from system ones */
3881 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3885 (!ioh
->fd_read_poll
||
3886 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
3887 FD_SET(ioh
->fd
, &rfds
);
3891 if (ioh
->fd_write
) {
3892 FD_SET(ioh
->fd
, &wfds
);
3898 tv
.tv_sec
= timeout
/ 1000;
3899 tv
.tv_usec
= (timeout
% 1000) * 1000;
3901 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
3903 qemu_mutex_unlock_iothread();
3904 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
3905 qemu_mutex_lock_iothread();
3907 IOHandlerRecord
**pioh
;
3909 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3910 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
3911 ioh
->fd_read(ioh
->opaque
);
3912 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
3913 FD_CLR(ioh
->fd
, &rfds
);
3915 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
3916 ioh
->fd_write(ioh
->opaque
);
3920 /* remove deleted IO handlers */
3921 pioh
= &first_io_handler
;
3932 slirp_select_poll(&rfds
, &wfds
, &xfds
, (ret
< 0));
3934 /* rearm timer, if not periodic */
3935 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
3936 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
3937 qemu_rearm_alarm_timer(alarm_timer
);
3940 /* vm time timers */
3942 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
3943 qemu_run_timers(&active_timers
[QEMU_CLOCK_VIRTUAL
],
3944 qemu_get_clock(vm_clock
));
3947 /* real time timers */
3948 qemu_run_timers(&active_timers
[QEMU_CLOCK_REALTIME
],
3949 qemu_get_clock(rt_clock
));
3951 qemu_run_timers(&active_timers
[QEMU_CLOCK_HOST
],
3952 qemu_get_clock(host_clock
));
3954 /* Check bottom-halves last in case any of the earlier events triggered
3960 static int qemu_cpu_exec(CPUState
*env
)
3963 #ifdef CONFIG_PROFILER
3967 #ifdef CONFIG_PROFILER
3968 ti
= profile_getclock();
3973 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
3974 env
->icount_decr
.u16
.low
= 0;
3975 env
->icount_extra
= 0;
3976 count
= qemu_next_deadline();
3977 count
= (count
+ (1 << icount_time_shift
) - 1)
3978 >> icount_time_shift
;
3979 qemu_icount
+= count
;
3980 decr
= (count
> 0xffff) ? 0xffff : count
;
3982 env
->icount_decr
.u16
.low
= decr
;
3983 env
->icount_extra
= count
;
3985 ret
= cpu_exec(env
);
3986 #ifdef CONFIG_PROFILER
3987 qemu_time
+= profile_getclock() - ti
;
3990 /* Fold pending instructions back into the
3991 instruction counter, and clear the interrupt flag. */
3992 qemu_icount
-= (env
->icount_decr
.u16
.low
3993 + env
->icount_extra
);
3994 env
->icount_decr
.u32
= 0;
3995 env
->icount_extra
= 0;
4000 static void tcg_cpu_exec(void)
4004 if (next_cpu
== NULL
)
4005 next_cpu
= first_cpu
;
4006 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
4007 CPUState
*env
= cur_cpu
= next_cpu
;
4009 if (timer_alarm_pending
) {
4010 timer_alarm_pending
= 0;
4013 if (cpu_can_run(env
))
4014 ret
= qemu_cpu_exec(env
);
4018 if (ret
== EXCP_DEBUG
) {
4019 gdb_set_stop_cpu(env
);
4020 debug_requested
= 1;
4026 static int cpu_has_work(CPUState
*env
)
4034 if (qemu_cpu_has_work(env
))
4039 static int tcg_has_work(void)
4043 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4044 if (cpu_has_work(env
))
4049 static int qemu_calculate_timeout(void)
4051 #ifndef CONFIG_IOTHREAD
4056 else if (tcg_has_work())
4058 else if (!use_icount
)
4061 /* XXX: use timeout computed from timers */
4064 /* Advance virtual time to the next event. */
4065 if (use_icount
== 1) {
4066 /* When not using an adaptive execution frequency
4067 we tend to get badly out of sync with real time,
4068 so just delay for a reasonable amount of time. */
4071 delta
= cpu_get_icount() - cpu_get_clock();
4074 /* If virtual time is ahead of real time then just
4076 timeout
= (delta
/ 1000000) + 1;
4078 /* Wait for either IO to occur or the next
4080 add
= qemu_next_deadline();
4081 /* We advance the timer before checking for IO.
4082 Limit the amount we advance so that early IO
4083 activity won't get the guest too far ahead. */
4087 add
= (add
+ (1 << icount_time_shift
) - 1)
4088 >> icount_time_shift
;
4090 timeout
= delta
/ 1000000;
4097 #else /* CONFIG_IOTHREAD */
4102 static int vm_can_run(void)
4104 if (powerdown_requested
)
4106 if (reset_requested
)
4108 if (shutdown_requested
)
4110 if (debug_requested
)
4115 qemu_irq qemu_system_powerdown
;
4117 static void main_loop(void)
4121 if (kvm_enabled()) {
4123 cpu_disable_ticks();
4127 #ifdef CONFIG_IOTHREAD
4128 qemu_system_ready
= 1;
4129 qemu_cond_broadcast(&qemu_system_cond
);
4134 #ifdef CONFIG_PROFILER
4137 #ifndef CONFIG_IOTHREAD
4140 #ifdef CONFIG_PROFILER
4141 ti
= profile_getclock();
4143 main_loop_wait(qemu_calculate_timeout());
4144 #ifdef CONFIG_PROFILER
4145 dev_time
+= profile_getclock() - ti
;
4147 } while (vm_can_run());
4149 if (qemu_debug_requested()) {
4150 vm_stop(EXCP_DEBUG
);
4152 if (qemu_shutdown_requested()) {
4153 monitor_protocol_event(QEVENT_SHUTDOWN
, NULL
);
4160 if (qemu_reset_requested()) {
4162 qemu_system_reset();
4165 if (qemu_powerdown_requested()) {
4166 monitor_protocol_event(QEVENT_POWERDOWN
, NULL
);
4167 qemu_irq_raise(qemu_system_powerdown
);
4169 if ((r
= qemu_vmstop_requested())) {
4176 static void version(void)
4178 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4181 static void help(int exitcode
)
4183 const char *options_help
=
4184 #define DEF(option, opt_arg, opt_enum, opt_help) \
4186 #define DEFHEADING(text) stringify(text) "\n"
4187 #include "qemu-options.h"
4193 printf("usage: %s [options] [disk_image]\n"
4195 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4198 "During emulation, the following keys are useful:\n"
4199 "ctrl-alt-f toggle full screen\n"
4200 "ctrl-alt-n switch to virtual console 'n'\n"
4201 "ctrl-alt toggle mouse and keyboard grab\n"
4203 "When using -nographic, press 'ctrl-a h' to get some help.\n",
4209 #define HAS_ARG 0x0001
4212 #define DEF(option, opt_arg, opt_enum, opt_help) \
4214 #define DEFHEADING(text)
4215 #include "qemu-options.h"
4221 typedef struct QEMUOption
{
4227 static const QEMUOption qemu_options
[] = {
4228 { "h", 0, QEMU_OPTION_h
},
4229 #define DEF(option, opt_arg, opt_enum, opt_help) \
4230 { option, opt_arg, opt_enum },
4231 #define DEFHEADING(text)
4232 #include "qemu-options.h"
4240 struct soundhw soundhw
[] = {
4241 #ifdef HAS_AUDIO_CHOICE
4242 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4248 { .init_isa
= pcspk_audio_init
}
4255 "Creative Sound Blaster 16",
4258 { .init_isa
= SB16_init
}
4262 #ifdef CONFIG_CS4231A
4268 { .init_isa
= cs4231a_init
}
4276 "Yamaha YMF262 (OPL3)",
4278 "Yamaha YM3812 (OPL2)",
4282 { .init_isa
= Adlib_init
}
4289 "Gravis Ultrasound GF1",
4292 { .init_isa
= GUS_init
}
4299 "Intel 82801AA AC97 Audio",
4302 { .init_pci
= ac97_init
}
4306 #ifdef CONFIG_ES1370
4309 "ENSONIQ AudioPCI ES1370",
4312 { .init_pci
= es1370_init
}
4316 #endif /* HAS_AUDIO_CHOICE */
4318 { NULL
, NULL
, 0, 0, { NULL
} }
4321 static void select_soundhw (const char *optarg
)
4325 if (*optarg
== '?') {
4328 printf ("Valid sound card names (comma separated):\n");
4329 for (c
= soundhw
; c
->name
; ++c
) {
4330 printf ("%-11s %s\n", c
->name
, c
->descr
);
4332 printf ("\n-soundhw all will enable all of the above\n");
4333 exit (*optarg
!= '?');
4341 if (!strcmp (optarg
, "all")) {
4342 for (c
= soundhw
; c
->name
; ++c
) {
4350 e
= strchr (p
, ',');
4351 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4353 for (c
= soundhw
; c
->name
; ++c
) {
4354 if (!strncmp (c
->name
, p
, l
) && !c
->name
[l
]) {
4363 "Unknown sound card name (too big to show)\n");
4366 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4371 p
+= l
+ (e
!= NULL
);
4375 goto show_valid_cards
;
4380 static void select_vgahw (const char *p
)
4385 vga_interface_type
= VGA_NONE
;
4386 if (strstart(p
, "std", &opts
)) {
4387 vga_interface_type
= VGA_STD
;
4388 } else if (strstart(p
, "cirrus", &opts
)) {
4389 vga_interface_type
= VGA_CIRRUS
;
4390 } else if (strstart(p
, "vmware", &opts
)) {
4391 vga_interface_type
= VGA_VMWARE
;
4392 } else if (strstart(p
, "xenfb", &opts
)) {
4393 vga_interface_type
= VGA_XENFB
;
4394 } else if (!strstart(p
, "none", &opts
)) {
4396 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4400 const char *nextopt
;
4402 if (strstart(opts
, ",retrace=", &nextopt
)) {
4404 if (strstart(opts
, "dumb", &nextopt
))
4405 vga_retrace_method
= VGA_RETRACE_DUMB
;
4406 else if (strstart(opts
, "precise", &nextopt
))
4407 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4408 else goto invalid_vga
;
4409 } else goto invalid_vga
;
4415 static int balloon_parse(const char *arg
)
4419 if (strcmp(arg
, "none") == 0) {
4423 if (!strncmp(arg
, "virtio", 6)) {
4424 if (arg
[6] == ',') {
4425 /* have params -> parse them */
4426 opts
= qemu_opts_parse(&qemu_device_opts
, arg
+7, NULL
);
4430 /* create empty opts */
4431 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4433 qemu_opt_set(opts
, "driver", "virtio-balloon-pci");
4442 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4444 exit(STATUS_CONTROL_C_EXIT
);
4449 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4453 if(strlen(str
) != 36)
4456 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4457 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4458 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4464 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4472 static void termsig_handler(int signal
)
4474 qemu_system_shutdown_request();
4477 static void sigchld_handler(int signal
)
4479 waitpid(-1, NULL
, WNOHANG
);
4482 static void sighandler_setup(void)
4484 struct sigaction act
;
4486 memset(&act
, 0, sizeof(act
));
4487 act
.sa_handler
= termsig_handler
;
4488 sigaction(SIGINT
, &act
, NULL
);
4489 sigaction(SIGHUP
, &act
, NULL
);
4490 sigaction(SIGTERM
, &act
, NULL
);
4492 act
.sa_handler
= sigchld_handler
;
4493 act
.sa_flags
= SA_NOCLDSTOP
;
4494 sigaction(SIGCHLD
, &act
, NULL
);
4500 /* Look for support files in the same directory as the executable. */
4501 static char *find_datadir(const char *argv0
)
4507 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
4514 while (p
!= buf
&& *p
!= '\\')
4517 if (access(buf
, R_OK
) == 0) {
4518 return qemu_strdup(buf
);
4524 /* Find a likely location for support files using the location of the binary.
4525 For installed binaries this will be "$bindir/../share/qemu". When
4526 running from the build tree this will be "$bindir/../pc-bios". */
4527 #define SHARE_SUFFIX "/share/qemu"
4528 #define BUILD_SUFFIX "/pc-bios"
4529 static char *find_datadir(const char *argv0
)
4537 #if defined(__linux__)
4540 len
= readlink("/proc/self/exe", buf
, sizeof(buf
) - 1);
4546 #elif defined(__FreeBSD__)
4549 len
= readlink("/proc/curproc/file", buf
, sizeof(buf
) - 1);
4556 /* If we don't have any way of figuring out the actual executable
4557 location then try argv[0]. */
4559 p
= realpath(argv0
, buf
);
4567 max_len
= strlen(dir
) +
4568 MAX(strlen(SHARE_SUFFIX
), strlen(BUILD_SUFFIX
)) + 1;
4569 res
= qemu_mallocz(max_len
);
4570 snprintf(res
, max_len
, "%s%s", dir
, SHARE_SUFFIX
);
4571 if (access(res
, R_OK
)) {
4572 snprintf(res
, max_len
, "%s%s", dir
, BUILD_SUFFIX
);
4573 if (access(res
, R_OK
)) {
4585 char *qemu_find_file(int type
, const char *name
)
4591 /* If name contains path separators then try it as a straight path. */
4592 if ((strchr(name
, '/') || strchr(name
, '\\'))
4593 && access(name
, R_OK
) == 0) {
4594 return qemu_strdup(name
);
4597 case QEMU_FILE_TYPE_BIOS
:
4600 case QEMU_FILE_TYPE_KEYMAP
:
4601 subdir
= "keymaps/";
4606 len
= strlen(data_dir
) + strlen(name
) + strlen(subdir
) + 2;
4607 buf
= qemu_mallocz(len
);
4608 snprintf(buf
, len
, "%s/%s%s", data_dir
, subdir
, name
);
4609 if (access(buf
, R_OK
)) {
4616 static int device_help_func(QemuOpts
*opts
, void *opaque
)
4618 return qdev_device_help(opts
);
4621 static int device_init_func(QemuOpts
*opts
, void *opaque
)
4625 dev
= qdev_device_add(opts
);
4631 static int chardev_init_func(QemuOpts
*opts
, void *opaque
)
4633 CharDriverState
*chr
;
4635 chr
= qemu_chr_open_opts(opts
, NULL
);
4641 static int mon_init_func(QemuOpts
*opts
, void *opaque
)
4643 CharDriverState
*chr
;
4644 const char *chardev
;
4648 mode
= qemu_opt_get(opts
, "mode");
4652 if (strcmp(mode
, "readline") == 0) {
4653 flags
= MONITOR_USE_READLINE
;
4654 } else if (strcmp(mode
, "control") == 0) {
4655 flags
= MONITOR_USE_CONTROL
;
4657 fprintf(stderr
, "unknown monitor mode \"%s\"\n", mode
);
4661 if (qemu_opt_get_bool(opts
, "default", 0))
4662 flags
|= MONITOR_IS_DEFAULT
;
4664 chardev
= qemu_opt_get(opts
, "chardev");
4665 chr
= qemu_chr_find(chardev
);
4667 fprintf(stderr
, "chardev \"%s\" not found\n", chardev
);
4671 monitor_init(chr
, flags
);
4675 static void monitor_parse(const char *optarg
, const char *mode
)
4677 static int monitor_device_index
= 0;
4683 if (strstart(optarg
, "chardev:", &p
)) {
4684 snprintf(label
, sizeof(label
), "%s", p
);
4686 if (monitor_device_index
) {
4687 snprintf(label
, sizeof(label
), "monitor%d",
4688 monitor_device_index
);
4690 snprintf(label
, sizeof(label
), "monitor");
4693 opts
= qemu_chr_parse_compat(label
, optarg
);
4695 fprintf(stderr
, "parse error: %s\n", optarg
);
4700 opts
= qemu_opts_create(&qemu_mon_opts
, label
, 1);
4702 fprintf(stderr
, "duplicate chardev: %s\n", label
);
4705 qemu_opt_set(opts
, "mode", mode
);
4706 qemu_opt_set(opts
, "chardev", label
);
4708 qemu_opt_set(opts
, "default", "on");
4709 monitor_device_index
++;
4712 struct device_config
{
4714 DEV_USB
, /* -usbdevice */
4716 DEV_SERIAL
, /* -serial */
4717 DEV_PARALLEL
, /* -parallel */
4718 DEV_VIRTCON
, /* -virtioconsole */
4719 DEV_DEBUGCON
, /* -debugcon */
4721 const char *cmdline
;
4722 QTAILQ_ENTRY(device_config
) next
;
4724 QTAILQ_HEAD(, device_config
) device_configs
= QTAILQ_HEAD_INITIALIZER(device_configs
);
4726 static void add_device_config(int type
, const char *cmdline
)
4728 struct device_config
*conf
;
4730 conf
= qemu_mallocz(sizeof(*conf
));
4732 conf
->cmdline
= cmdline
;
4733 QTAILQ_INSERT_TAIL(&device_configs
, conf
, next
);
4736 static int foreach_device_config(int type
, int (*func
)(const char *cmdline
))
4738 struct device_config
*conf
;
4741 QTAILQ_FOREACH(conf
, &device_configs
, next
) {
4742 if (conf
->type
!= type
)
4744 rc
= func(conf
->cmdline
);
4751 static int serial_parse(const char *devname
)
4753 static int index
= 0;
4756 if (strcmp(devname
, "none") == 0)
4758 if (index
== MAX_SERIAL_PORTS
) {
4759 fprintf(stderr
, "qemu: too many serial ports\n");
4762 snprintf(label
, sizeof(label
), "serial%d", index
);
4763 serial_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4764 if (!serial_hds
[index
]) {
4765 fprintf(stderr
, "qemu: could not open serial device '%s': %s\n",
4766 devname
, strerror(errno
));
4773 static int parallel_parse(const char *devname
)
4775 static int index
= 0;
4778 if (strcmp(devname
, "none") == 0)
4780 if (index
== MAX_PARALLEL_PORTS
) {
4781 fprintf(stderr
, "qemu: too many parallel ports\n");
4784 snprintf(label
, sizeof(label
), "parallel%d", index
);
4785 parallel_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4786 if (!parallel_hds
[index
]) {
4787 fprintf(stderr
, "qemu: could not open parallel device '%s': %s\n",
4788 devname
, strerror(errno
));
4795 static int virtcon_parse(const char *devname
)
4797 static int index
= 0;
4799 QemuOpts
*bus_opts
, *dev_opts
;
4801 if (strcmp(devname
, "none") == 0)
4803 if (index
== MAX_VIRTIO_CONSOLES
) {
4804 fprintf(stderr
, "qemu: too many virtio consoles\n");
4808 bus_opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4809 qemu_opt_set(bus_opts
, "driver", "virtio-serial");
4811 dev_opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4812 qemu_opt_set(dev_opts
, "driver", "virtconsole");
4814 snprintf(label
, sizeof(label
), "virtcon%d", index
);
4815 virtcon_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4816 if (!virtcon_hds
[index
]) {
4817 fprintf(stderr
, "qemu: could not open virtio console '%s': %s\n",
4818 devname
, strerror(errno
));
4821 qemu_opt_set(dev_opts
, "chardev", label
);
4827 static int debugcon_parse(const char *devname
)
4831 if (!qemu_chr_open("debugcon", devname
, NULL
)) {
4834 opts
= qemu_opts_create(&qemu_device_opts
, "debugcon", 1);
4836 fprintf(stderr
, "qemu: already have a debugcon device\n");
4839 qemu_opt_set(opts
, "driver", "isa-debugcon");
4840 qemu_opt_set(opts
, "chardev", "debugcon");
4844 static const QEMUOption
*lookup_opt(int argc
, char **argv
,
4845 const char **poptarg
, int *poptind
)
4847 const QEMUOption
*popt
;
4848 int optind
= *poptind
;
4849 char *r
= argv
[optind
];
4853 /* Treat --foo the same as -foo. */
4856 popt
= qemu_options
;
4859 fprintf(stderr
, "%s: invalid option -- '%s'\n",
4863 if (!strcmp(popt
->name
, r
+ 1))
4867 if (popt
->flags
& HAS_ARG
) {
4868 if (optind
>= argc
) {
4869 fprintf(stderr
, "%s: option '%s' requires an argument\n",
4873 optarg
= argv
[optind
++];
4884 int main(int argc
, char **argv
, char **envp
)
4886 const char *gdbstub_dev
= NULL
;
4887 uint32_t boot_devices_bitmap
= 0;
4889 int snapshot
, linux_boot
, net_boot
;
4890 const char *initrd_filename
;
4891 const char *kernel_filename
, *kernel_cmdline
;
4892 char boot_devices
[33] = "cad"; /* default to HD->floppy->CD-ROM */
4894 DisplayChangeListener
*dcl
;
4895 int cyls
, heads
, secs
, translation
;
4896 QemuOpts
*hda_opts
= NULL
, *opts
;
4899 const char *loadvm
= NULL
;
4900 QEMUMachine
*machine
;
4901 const char *cpu_model
;
4906 const char *pid_file
= NULL
;
4907 const char *incoming
= NULL
;
4910 struct passwd
*pwd
= NULL
;
4911 const char *chroot_dir
= NULL
;
4912 const char *run_as
= NULL
;
4915 int show_vnc_port
= 0;
4920 qemu_errors_to_file(stderr
);
4921 qemu_cache_utils_init(envp
);
4923 QLIST_INIT (&vm_change_state_head
);
4926 struct sigaction act
;
4927 sigfillset(&act
.sa_mask
);
4929 act
.sa_handler
= SIG_IGN
;
4930 sigaction(SIGPIPE
, &act
, NULL
);
4933 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4934 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4935 QEMU to run on a single CPU */
4940 h
= GetCurrentProcess();
4941 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4942 for(i
= 0; i
< 32; i
++) {
4943 if (mask
& (1 << i
))
4948 SetProcessAffinityMask(h
, mask
);
4954 module_call_init(MODULE_INIT_MACHINE
);
4955 machine
= find_default_machine();
4957 initrd_filename
= NULL
;
4960 kernel_filename
= NULL
;
4961 kernel_cmdline
= "";
4962 cyls
= heads
= secs
= 0;
4963 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4965 for (i
= 0; i
< MAX_NODES
; i
++) {
4967 node_cpumask
[i
] = 0;
4970 assigned_devices_index
= 0;
4978 /* first pass of option parsing */
4980 while (optind
< argc
) {
4981 if (argv
[optind
][0] != '-') {
4986 const QEMUOption
*popt
;
4988 popt
= lookup_opt(argc
, argv
, &optarg
, &optind
);
4989 switch (popt
->index
) {
4990 case QEMU_OPTION_nodefconfig
:
4999 fp
= fopen(CONFIG_QEMU_CONFDIR
"/qemu.conf", "r");
5001 if (qemu_config_parse(fp
) != 0) {
5007 fp
= fopen(CONFIG_QEMU_CONFDIR
"/target-" TARGET_ARCH
".conf", "r");
5009 if (qemu_config_parse(fp
) != 0) {
5015 #if defined(cpudef_setup)
5016 cpudef_setup(); /* parse cpu definitions in target config file */
5019 /* second pass of option parsing */
5024 if (argv
[optind
][0] != '-') {
5025 hda_opts
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
5027 const QEMUOption
*popt
;
5029 popt
= lookup_opt(argc
, argv
, &optarg
, &optind
);
5030 switch(popt
->index
) {
5032 machine
= find_machine(optarg
);
5035 printf("Supported machines are:\n");
5036 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5038 printf("%-10s %s (alias of %s)\n",
5039 m
->alias
, m
->desc
, m
->name
);
5040 printf("%-10s %s%s\n",
5042 m
->is_default
? " (default)" : "");
5044 exit(*optarg
!= '?');
5047 case QEMU_OPTION_cpu
:
5048 /* hw initialization will check this */
5049 if (*optarg
== '?') {
5050 /* XXX: implement xxx_cpu_list for targets that still miss it */
5051 #if defined(cpu_list_id)
5052 cpu_list_id(stdout
, &fprintf
, optarg
);
5053 #elif defined(cpu_list)
5054 cpu_list(stdout
, &fprintf
); /* deprecated */
5061 case QEMU_OPTION_initrd
:
5062 initrd_filename
= optarg
;
5064 case QEMU_OPTION_hda
:
5066 hda_opts
= drive_add(optarg
, HD_ALIAS
, 0);
5068 hda_opts
= drive_add(optarg
, HD_ALIAS
5069 ",cyls=%d,heads=%d,secs=%d%s",
5070 0, cyls
, heads
, secs
,
5071 translation
== BIOS_ATA_TRANSLATION_LBA
?
5073 translation
== BIOS_ATA_TRANSLATION_NONE
?
5074 ",trans=none" : "");
5076 case QEMU_OPTION_hdb
:
5077 case QEMU_OPTION_hdc
:
5078 case QEMU_OPTION_hdd
:
5079 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
5081 case QEMU_OPTION_drive
:
5082 drive_add(NULL
, "%s", optarg
);
5084 case QEMU_OPTION_set
:
5085 if (qemu_set_option(optarg
) != 0)
5088 case QEMU_OPTION_global
:
5089 if (qemu_global_option(optarg
) != 0)
5092 case QEMU_OPTION_mtdblock
:
5093 drive_add(optarg
, MTD_ALIAS
);
5095 case QEMU_OPTION_sd
:
5096 drive_add(optarg
, SD_ALIAS
);
5098 case QEMU_OPTION_pflash
:
5099 drive_add(optarg
, PFLASH_ALIAS
);
5101 case QEMU_OPTION_snapshot
:
5104 case QEMU_OPTION_hdachs
:
5108 cyls
= strtol(p
, (char **)&p
, 0);
5109 if (cyls
< 1 || cyls
> 16383)
5114 heads
= strtol(p
, (char **)&p
, 0);
5115 if (heads
< 1 || heads
> 16)
5120 secs
= strtol(p
, (char **)&p
, 0);
5121 if (secs
< 1 || secs
> 63)
5125 if (!strcmp(p
, "none"))
5126 translation
= BIOS_ATA_TRANSLATION_NONE
;
5127 else if (!strcmp(p
, "lba"))
5128 translation
= BIOS_ATA_TRANSLATION_LBA
;
5129 else if (!strcmp(p
, "auto"))
5130 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5133 } else if (*p
!= '\0') {
5135 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5138 if (hda_opts
!= NULL
) {
5140 snprintf(num
, sizeof(num
), "%d", cyls
);
5141 qemu_opt_set(hda_opts
, "cyls", num
);
5142 snprintf(num
, sizeof(num
), "%d", heads
);
5143 qemu_opt_set(hda_opts
, "heads", num
);
5144 snprintf(num
, sizeof(num
), "%d", secs
);
5145 qemu_opt_set(hda_opts
, "secs", num
);
5146 if (translation
== BIOS_ATA_TRANSLATION_LBA
)
5147 qemu_opt_set(hda_opts
, "trans", "lba");
5148 if (translation
== BIOS_ATA_TRANSLATION_NONE
)
5149 qemu_opt_set(hda_opts
, "trans", "none");
5153 case QEMU_OPTION_numa
:
5154 if (nb_numa_nodes
>= MAX_NODES
) {
5155 fprintf(stderr
, "qemu: too many NUMA nodes\n");
5160 case QEMU_OPTION_nographic
:
5161 display_type
= DT_NOGRAPHIC
;
5163 #ifdef CONFIG_CURSES
5164 case QEMU_OPTION_curses
:
5165 display_type
= DT_CURSES
;
5168 case QEMU_OPTION_portrait
:
5171 case QEMU_OPTION_kernel
:
5172 kernel_filename
= optarg
;
5174 case QEMU_OPTION_append
:
5175 kernel_cmdline
= optarg
;
5177 case QEMU_OPTION_cdrom
:
5178 drive_add(optarg
, CDROM_ALIAS
);
5180 case QEMU_OPTION_boot
:
5182 static const char * const params
[] = {
5183 "order", "once", "menu", NULL
5185 char buf
[sizeof(boot_devices
)];
5186 char *standard_boot_devices
;
5189 if (!strchr(optarg
, '=')) {
5191 pstrcpy(buf
, sizeof(buf
), optarg
);
5192 } else if (check_params(buf
, sizeof(buf
), params
, optarg
) < 0) {
5194 "qemu: unknown boot parameter '%s' in '%s'\n",
5200 get_param_value(buf
, sizeof(buf
), "order", optarg
)) {
5201 boot_devices_bitmap
= parse_bootdevices(buf
);
5202 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5205 if (get_param_value(buf
, sizeof(buf
),
5207 boot_devices_bitmap
|= parse_bootdevices(buf
);
5208 standard_boot_devices
= qemu_strdup(boot_devices
);
5209 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5210 qemu_register_reset(restore_boot_devices
,
5211 standard_boot_devices
);
5213 if (get_param_value(buf
, sizeof(buf
),
5215 if (!strcmp(buf
, "on")) {
5217 } else if (!strcmp(buf
, "off")) {
5221 "qemu: invalid option value '%s'\n",
5229 case QEMU_OPTION_fda
:
5230 case QEMU_OPTION_fdb
:
5231 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
5234 case QEMU_OPTION_no_fd_bootchk
:
5238 case QEMU_OPTION_netdev
:
5239 if (net_client_parse(&qemu_netdev_opts
, optarg
) == -1) {
5243 case QEMU_OPTION_net
:
5244 if (net_client_parse(&qemu_net_opts
, optarg
) == -1) {
5249 case QEMU_OPTION_tftp
:
5250 legacy_tftp_prefix
= optarg
;
5252 case QEMU_OPTION_bootp
:
5253 legacy_bootp_filename
= optarg
;
5256 case QEMU_OPTION_smb
:
5257 if (net_slirp_smb(optarg
) < 0)
5261 case QEMU_OPTION_redir
:
5262 if (net_slirp_redir(optarg
) < 0)
5266 case QEMU_OPTION_bt
:
5267 add_device_config(DEV_BT
, optarg
);
5270 case QEMU_OPTION_audio_help
:
5274 case QEMU_OPTION_soundhw
:
5275 select_soundhw (optarg
);
5281 case QEMU_OPTION_version
:
5285 case QEMU_OPTION_m
: {
5289 value
= strtoul(optarg
, &ptr
, 10);
5291 case 0: case 'M': case 'm':
5298 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5302 /* On 32-bit hosts, QEMU is limited by virtual address space */
5303 if (value
> (2047 << 20) && HOST_LONG_BITS
== 32) {
5304 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5307 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5308 fprintf(stderr
, "qemu: ram size too large\n");
5314 case QEMU_OPTION_mempath
:
5318 case QEMU_OPTION_mem_prealloc
:
5325 const CPULogItem
*item
;
5327 mask
= cpu_str_to_log_mask(optarg
);
5329 printf("Log items (comma separated):\n");
5330 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5331 printf("%-10s %s\n", item
->name
, item
->help
);
5339 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5341 case QEMU_OPTION_gdb
:
5342 gdbstub_dev
= optarg
;
5347 case QEMU_OPTION_bios
:
5350 case QEMU_OPTION_singlestep
:
5357 keyboard_layout
= optarg
;
5359 case QEMU_OPTION_localtime
:
5362 case QEMU_OPTION_vga
:
5363 select_vgahw (optarg
);
5365 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5371 w
= strtol(p
, (char **)&p
, 10);
5374 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5380 h
= strtol(p
, (char **)&p
, 10);
5385 depth
= strtol(p
, (char **)&p
, 10);
5386 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5387 depth
!= 24 && depth
!= 32)
5389 } else if (*p
== '\0') {
5390 depth
= graphic_depth
;
5397 graphic_depth
= depth
;
5401 case QEMU_OPTION_echr
:
5404 term_escape_char
= strtol(optarg
, &r
, 0);
5406 printf("Bad argument to echr\n");
5409 case QEMU_OPTION_monitor
:
5410 monitor_parse(optarg
, "readline");
5411 default_monitor
= 0;
5413 case QEMU_OPTION_qmp
:
5414 monitor_parse(optarg
, "control");
5415 default_monitor
= 0;
5417 case QEMU_OPTION_mon
:
5418 opts
= qemu_opts_parse(&qemu_mon_opts
, optarg
, "chardev");
5420 fprintf(stderr
, "parse error: %s\n", optarg
);
5423 default_monitor
= 0;
5425 case QEMU_OPTION_chardev
:
5426 opts
= qemu_opts_parse(&qemu_chardev_opts
, optarg
, "backend");
5428 fprintf(stderr
, "parse error: %s\n", optarg
);
5432 case QEMU_OPTION_serial
:
5433 add_device_config(DEV_SERIAL
, optarg
);
5435 if (strncmp(optarg
, "mon:", 4) == 0) {
5436 default_monitor
= 0;
5439 case QEMU_OPTION_watchdog
:
5442 "qemu: only one watchdog option may be given\n");
5447 case QEMU_OPTION_watchdog_action
:
5448 if (select_watchdog_action(optarg
) == -1) {
5449 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5453 case QEMU_OPTION_virtiocon
:
5454 add_device_config(DEV_VIRTCON
, optarg
);
5455 default_virtcon
= 0;
5456 if (strncmp(optarg
, "mon:", 4) == 0) {
5457 default_monitor
= 0;
5460 case QEMU_OPTION_parallel
:
5461 add_device_config(DEV_PARALLEL
, optarg
);
5462 default_parallel
= 0;
5463 if (strncmp(optarg
, "mon:", 4) == 0) {
5464 default_monitor
= 0;
5467 case QEMU_OPTION_debugcon
:
5468 add_device_config(DEV_DEBUGCON
, optarg
);
5470 case QEMU_OPTION_loadvm
:
5473 case QEMU_OPTION_full_screen
:
5477 case QEMU_OPTION_no_frame
:
5480 case QEMU_OPTION_alt_grab
:
5483 case QEMU_OPTION_ctrl_grab
:
5486 case QEMU_OPTION_no_quit
:
5489 case QEMU_OPTION_sdl
:
5490 display_type
= DT_SDL
;
5493 case QEMU_OPTION_pidfile
:
5497 case QEMU_OPTION_win2k_hack
:
5498 win2k_install_hack
= 1;
5500 case QEMU_OPTION_rtc_td_hack
:
5503 case QEMU_OPTION_acpitable
:
5504 if(acpi_table_add(optarg
) < 0) {
5505 fprintf(stderr
, "Wrong acpi table provided\n");
5509 case QEMU_OPTION_smbios
:
5510 if(smbios_entry_add(optarg
) < 0) {
5511 fprintf(stderr
, "Wrong smbios provided\n");
5518 case QEMU_OPTION_enable_kvm
:
5522 case QEMU_OPTION_no_kvm
:
5525 case QEMU_OPTION_no_kvm_irqchip
: {
5530 case QEMU_OPTION_no_kvm_pit
: {
5534 case QEMU_OPTION_no_kvm_pit_reinjection
: {
5535 kvm_pit_reinject
= 0;
5538 case QEMU_OPTION_enable_nesting
: {
5542 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5543 case QEMU_OPTION_pcidevice
:
5544 if (assigned_devices_index
>= MAX_DEV_ASSIGN_CMDLINE
) {
5545 fprintf(stderr
, "Too many assigned devices\n");
5548 assigned_devices
[assigned_devices_index
] = optarg
;
5549 assigned_devices_index
++;
5553 case QEMU_OPTION_usb
:
5556 case QEMU_OPTION_usbdevice
:
5558 add_device_config(DEV_USB
, optarg
);
5560 case QEMU_OPTION_device
:
5561 if (!qemu_opts_parse(&qemu_device_opts
, optarg
, "driver")) {
5565 case QEMU_OPTION_smp
:
5568 fprintf(stderr
, "Invalid number of CPUs\n");
5571 if (max_cpus
< smp_cpus
) {
5572 fprintf(stderr
, "maxcpus must be equal to or greater than "
5576 if (max_cpus
> 255) {
5577 fprintf(stderr
, "Unsupported number of maxcpus\n");
5581 case QEMU_OPTION_vnc
:
5582 display_type
= DT_VNC
;
5583 vnc_display
= optarg
;
5586 case QEMU_OPTION_no_acpi
:
5589 case QEMU_OPTION_no_hpet
:
5592 case QEMU_OPTION_balloon
:
5593 if (balloon_parse(optarg
) < 0) {
5594 fprintf(stderr
, "Unknown -balloon argument %s\n", optarg
);
5599 case QEMU_OPTION_no_reboot
:
5602 case QEMU_OPTION_no_shutdown
:
5605 case QEMU_OPTION_show_cursor
:
5608 case QEMU_OPTION_uuid
:
5609 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5610 fprintf(stderr
, "Fail to parse UUID string."
5611 " Wrong format.\n");
5616 case QEMU_OPTION_daemonize
:
5620 case QEMU_OPTION_option_rom
:
5621 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5622 fprintf(stderr
, "Too many option ROMs\n");
5625 option_rom
[nb_option_roms
] = optarg
;
5628 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5629 case QEMU_OPTION_semihosting
:
5630 semihosting_enabled
= 1;
5633 case QEMU_OPTION_tdf
:
5636 case QEMU_OPTION_kvm_shadow_memory
:
5637 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
5639 case QEMU_OPTION_name
:
5640 qemu_name
= qemu_strdup(optarg
);
5642 char *p
= strchr(qemu_name
, ',');
5645 if (strncmp(p
, "process=", 8)) {
5646 fprintf(stderr
, "Unknown subargument %s to -name", p
);
5654 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5655 case QEMU_OPTION_prom_env
:
5656 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5657 fprintf(stderr
, "Too many prom variables\n");
5660 prom_envs
[nb_prom_envs
] = optarg
;
5665 case QEMU_OPTION_old_param
:
5669 case QEMU_OPTION_clock
:
5670 configure_alarms(optarg
);
5672 case QEMU_OPTION_startdate
:
5673 configure_rtc_date_offset(optarg
, 1);
5675 case QEMU_OPTION_rtc
:
5676 opts
= qemu_opts_parse(&qemu_rtc_opts
, optarg
, NULL
);
5678 fprintf(stderr
, "parse error: %s\n", optarg
);
5681 configure_rtc(opts
);
5683 case QEMU_OPTION_tb_size
:
5684 tb_size
= strtol(optarg
, NULL
, 0);
5688 case QEMU_OPTION_icount
:
5690 if (strcmp(optarg
, "auto") == 0) {
5691 icount_time_shift
= -1;
5693 icount_time_shift
= strtol(optarg
, NULL
, 0);
5696 case QEMU_OPTION_incoming
:
5699 case QEMU_OPTION_nodefaults
:
5701 default_parallel
= 0;
5702 default_virtcon
= 0;
5703 default_monitor
= 0;
5711 case QEMU_OPTION_chroot
:
5712 chroot_dir
= optarg
;
5714 case QEMU_OPTION_runas
:
5717 case QEMU_OPTION_nvram
:
5722 case QEMU_OPTION_xen_domid
:
5723 xen_domid
= atoi(optarg
);
5725 case QEMU_OPTION_xen_create
:
5726 xen_mode
= XEN_CREATE
;
5728 case QEMU_OPTION_xen_attach
:
5729 xen_mode
= XEN_ATTACH
;
5732 case QEMU_OPTION_readconfig
:
5735 fp
= fopen(optarg
, "r");
5737 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5740 if (qemu_config_parse(fp
) != 0) {
5746 case QEMU_OPTION_writeconfig
:
5749 if (strcmp(optarg
, "-") == 0) {
5752 fp
= fopen(optarg
, "w");
5754 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5758 qemu_config_write(fp
);
5766 /* If no data_dir is specified then try to find it relative to the
5769 data_dir
= find_datadir(argv
[0]);
5771 /* If all else fails use the install patch specified when building. */
5773 data_dir
= CONFIG_QEMU_SHAREDIR
;
5777 * Default to max_cpus = smp_cpus, in case the user doesn't
5778 * specify a max_cpus value.
5781 max_cpus
= smp_cpus
;
5783 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5784 if (smp_cpus
> machine
->max_cpus
) {
5785 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5786 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5791 qemu_opts_foreach(&qemu_device_opts
, default_driver_check
, NULL
, 0);
5792 qemu_opts_foreach(&qemu_global_opts
, default_driver_check
, NULL
, 0);
5794 if (machine
->no_serial
) {
5797 if (machine
->no_parallel
) {
5798 default_parallel
= 0;
5800 if (!machine
->use_virtcon
) {
5801 default_virtcon
= 0;
5803 if (machine
->no_vga
) {
5806 if (machine
->no_floppy
) {
5809 if (machine
->no_cdrom
) {
5812 if (machine
->no_sdcard
) {
5816 if (display_type
== DT_NOGRAPHIC
) {
5817 if (default_parallel
)
5818 add_device_config(DEV_PARALLEL
, "null");
5819 if (default_serial
&& default_monitor
) {
5820 add_device_config(DEV_SERIAL
, "mon:stdio");
5821 } else if (default_virtcon
&& default_monitor
) {
5822 add_device_config(DEV_VIRTCON
, "mon:stdio");
5825 add_device_config(DEV_SERIAL
, "stdio");
5826 if (default_virtcon
)
5827 add_device_config(DEV_VIRTCON
, "stdio");
5828 if (default_monitor
)
5829 monitor_parse("stdio", "readline");
5833 add_device_config(DEV_SERIAL
, "vc:80Cx24C");
5834 if (default_parallel
)
5835 add_device_config(DEV_PARALLEL
, "vc:80Cx24C");
5836 if (default_monitor
)
5837 monitor_parse("vc:80Cx24C", "readline");
5838 if (default_virtcon
)
5839 add_device_config(DEV_VIRTCON
, "vc:80Cx24C");
5842 vga_interface_type
= VGA_CIRRUS
;
5844 if (qemu_opts_foreach(&qemu_chardev_opts
, chardev_init_func
, NULL
, 1) != 0)
5851 if (pipe(fds
) == -1)
5862 len
= read(fds
[0], &status
, 1);
5863 if (len
== -1 && (errno
== EINTR
))
5868 else if (status
== 1) {
5869 fprintf(stderr
, "Could not acquire pidfile: %s\n", strerror(errno
));
5877 qemu_set_cloexec(fds
[1]);
5889 signal(SIGTSTP
, SIG_IGN
);
5890 signal(SIGTTOU
, SIG_IGN
);
5891 signal(SIGTTIN
, SIG_IGN
);
5895 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5899 if (write(fds
[1], &status
, 1) != 1) {
5900 perror("daemonize. Writing to pipe\n");
5904 fprintf(stderr
, "Could not acquire pid file: %s\n", strerror(errno
));
5908 if (kvm_enabled()) {
5911 ret
= kvm_init(smp_cpus
);
5913 #if defined(KVM_UPSTREAM) || defined(CONFIG_NO_CPU_EMULATION)
5914 fprintf(stderr
, "failed to initialize KVM\n");
5918 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
5924 if (qemu_init_main_loop()) {
5925 fprintf(stderr
, "qemu_init_main_loop failed\n");
5928 linux_boot
= (kernel_filename
!= NULL
);
5930 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5931 fprintf(stderr
, "-append only allowed with -kernel option\n");
5935 if (!linux_boot
&& initrd_filename
!= NULL
) {
5936 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5941 /* Win32 doesn't support line-buffering and requires size >= 2 */
5942 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5945 if (init_timer_alarm() < 0) {
5946 fprintf(stderr
, "could not initialize alarm timer\n");
5949 if (use_icount
&& icount_time_shift
< 0) {
5951 /* 125MIPS seems a reasonable initial guess at the guest speed.
5952 It will be corrected fairly quickly anyway. */
5953 icount_time_shift
= 3;
5954 init_icount_adjust();
5961 if (net_init_clients() < 0) {
5965 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5966 net_set_boot_mask(net_boot
);
5968 /* init the bluetooth world */
5969 if (foreach_device_config(DEV_BT
, bt_parse
))
5972 /* init the memory */
5974 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5976 /* init the dynamic translator */
5977 cpu_exec_init_all(tb_size
* 1024 * 1024);
5979 bdrv_init_with_whitelist();
5983 if (default_cdrom
) {
5984 /* we always create the cdrom drive, even if no disk is there */
5985 drive_add(NULL
, CDROM_ALIAS
);
5988 if (default_floppy
) {
5989 /* we always create at least one floppy */
5990 drive_add(NULL
, FD_ALIAS
, 0);
5993 if (default_sdcard
) {
5994 /* we always create one sd slot, even if no card is in it */
5995 drive_add(NULL
, SD_ALIAS
);
5998 /* open the virtual block devices */
6000 qemu_opts_foreach(&qemu_drive_opts
, drive_enable_snapshot
, NULL
, 0);
6001 if (qemu_opts_foreach(&qemu_drive_opts
, drive_init_func
, machine
, 1) != 0)
6004 vmstate_register(0, &vmstate_timers
,&timers_state
);
6005 register_savevm_live("ram", 0, 3, NULL
, ram_save_live
, NULL
,
6008 if (nb_numa_nodes
> 0) {
6011 if (nb_numa_nodes
> smp_cpus
) {
6012 nb_numa_nodes
= smp_cpus
;
6015 /* If no memory size if given for any node, assume the default case
6016 * and distribute the available memory equally across all nodes
6018 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6019 if (node_mem
[i
] != 0)
6022 if (i
== nb_numa_nodes
) {
6023 uint64_t usedmem
= 0;
6025 /* On Linux, the each node's border has to be 8MB aligned,
6026 * the final node gets the rest.
6028 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
6029 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
6030 usedmem
+= node_mem
[i
];
6032 node_mem
[i
] = ram_size
- usedmem
;
6035 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6036 if (node_cpumask
[i
] != 0)
6039 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6040 * must cope with this anyway, because there are BIOSes out there in
6041 * real machines which also use this scheme.
6043 if (i
== nb_numa_nodes
) {
6044 for (i
= 0; i
< smp_cpus
; i
++) {
6045 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
6050 if (foreach_device_config(DEV_SERIAL
, serial_parse
) < 0)
6052 if (foreach_device_config(DEV_PARALLEL
, parallel_parse
) < 0)
6054 if (foreach_device_config(DEV_VIRTCON
, virtcon_parse
) < 0)
6056 if (foreach_device_config(DEV_DEBUGCON
, debugcon_parse
) < 0)
6059 module_call_init(MODULE_INIT_DEVICE
);
6061 if (qemu_opts_foreach(&qemu_device_opts
, device_help_func
, NULL
, 0) != 0)
6065 i
= select_watchdog(watchdog
);
6067 exit (i
== 1 ? 1 : 0);
6070 if (machine
->compat_props
) {
6071 qdev_prop_register_global_list(machine
->compat_props
);
6075 machine
->init(ram_size
, boot_devices
,
6076 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
6078 cpu_synchronize_all_post_init();
6081 /* must be after terminal init, SDL library changes signal handlers */
6085 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
6086 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6087 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
6093 current_machine
= machine
;
6095 /* init USB devices */
6097 if (foreach_device_config(DEV_USB
, usb_parse
) < 0)
6101 /* init generic devices */
6102 if (qemu_opts_foreach(&qemu_device_opts
, device_init_func
, NULL
, 1) != 0)
6105 net_check_clients();
6107 /* just use the first displaystate for the moment */
6108 ds
= get_displaystate();
6110 if (display_type
== DT_DEFAULT
) {
6111 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6112 display_type
= DT_SDL
;
6114 display_type
= DT_VNC
;
6115 vnc_display
= "localhost:0,to=99";
6121 switch (display_type
) {
6124 #if defined(CONFIG_CURSES)
6126 curses_display_init(ds
, full_screen
);
6129 #if defined(CONFIG_SDL)
6131 sdl_display_init(ds
, full_screen
, no_frame
);
6133 #elif defined(CONFIG_COCOA)
6135 cocoa_display_init(ds
, full_screen
);
6139 vnc_display_init(ds
);
6140 if (vnc_display_open(ds
, vnc_display
) < 0)
6143 if (show_vnc_port
) {
6144 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
6152 dcl
= ds
->listeners
;
6153 while (dcl
!= NULL
) {
6154 if (dcl
->dpy_refresh
!= NULL
) {
6155 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
6156 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
6161 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
6162 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
6163 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
6166 text_consoles_set_display(ds
);
6168 if (qemu_opts_foreach(&qemu_mon_opts
, mon_init_func
, NULL
, 1) != 0)
6171 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
6172 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
6177 qdev_machine_creation_done();
6179 if (rom_load_all() != 0) {
6180 fprintf(stderr
, "rom loading failed\n");
6184 qemu_system_reset();
6186 if (load_vmstate(cur_mon
, loadvm
) < 0) {
6192 qemu_start_incoming_migration(incoming
);
6193 } else if (autostart
) {
6203 len
= write(fds
[1], &status
, 1);
6204 if (len
== -1 && (errno
== EINTR
))
6211 perror("not able to chdir to /");
6214 TFR(fd
= qemu_open("/dev/null", O_RDWR
));
6220 pwd
= getpwnam(run_as
);
6222 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
6228 if (chroot(chroot_dir
) < 0) {
6229 fprintf(stderr
, "chroot failed\n");
6233 perror("not able to chdir to /");
6239 if (setgid(pwd
->pw_gid
) < 0) {
6240 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
6243 if (setuid(pwd
->pw_uid
) < 0) {
6244 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
6247 if (setuid(0) != -1) {
6248 fprintf(stderr
, "Dropping privileges failed\n");