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
;
191 NICInfo nd_table
[MAX_NICS
];
194 static int rtc_utc
= 1;
195 static int rtc_date_offset
= -1; /* -1 means no change */
196 QEMUClock
*rtc_clock
;
197 int vga_interface_type
= VGA_NONE
;
199 int graphic_width
= 1024;
200 int graphic_height
= 768;
201 int graphic_depth
= 8;
203 int graphic_width
= 800;
204 int graphic_height
= 600;
205 int graphic_depth
= 15;
207 static int full_screen
= 0;
209 static int no_frame
= 0;
212 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
213 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
214 CharDriverState
*virtcon_hds
[MAX_VIRTIO_CONSOLES
];
216 int win2k_install_hack
= 0;
221 const char *assigned_devices
[MAX_DEV_ASSIGN_CMDLINE
];
222 int assigned_devices_index
;
227 const char *vnc_display
;
228 int acpi_enabled
= 1;
236 int graphic_rotate
= 0;
237 uint8_t irq0override
= 1;
241 const char *watchdog
;
242 const char *option_rom
[MAX_OPTION_ROMS
];
244 int semihosting_enabled
= 0;
245 int time_drift_fix
= 0;
246 unsigned int kvm_shadow_memory
= 0;
247 const char *mem_path
= NULL
;
249 int mem_prealloc
= 1; /* force preallocation of physical target memory */
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 static void configure_rtc_date_offset(const char *startdate
, int legacy
)
1506 time_t rtc_start_date
;
1509 if (!strcmp(startdate
, "now") && legacy
) {
1510 rtc_date_offset
= -1;
1512 if (sscanf(startdate
, "%d-%d-%dT%d:%d:%d",
1520 } else if (sscanf(startdate
, "%d-%d-%d",
1523 &tm
.tm_mday
) == 3) {
1532 rtc_start_date
= mktimegm(&tm
);
1533 if (rtc_start_date
== -1) {
1535 fprintf(stderr
, "Invalid date format. Valid formats are:\n"
1536 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1539 rtc_date_offset
= time(NULL
) - rtc_start_date
;
1543 static void configure_rtc(QemuOpts
*opts
)
1547 value
= qemu_opt_get(opts
, "base");
1549 if (!strcmp(value
, "utc")) {
1551 } else if (!strcmp(value
, "localtime")) {
1554 configure_rtc_date_offset(value
, 0);
1557 value
= qemu_opt_get(opts
, "clock");
1559 if (!strcmp(value
, "host")) {
1560 rtc_clock
= host_clock
;
1561 } else if (!strcmp(value
, "vm")) {
1562 rtc_clock
= vm_clock
;
1564 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1568 #ifdef CONFIG_TARGET_I386
1569 value
= qemu_opt_get(opts
, "driftfix");
1571 if (!strcmp(buf
, "slew")) {
1573 } else if (!strcmp(buf
, "none")) {
1576 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1584 static void socket_cleanup(void)
1589 static int socket_init(void)
1594 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1596 err
= WSAGetLastError();
1597 fprintf(stderr
, "WSAStartup: %d\n", err
);
1600 atexit(socket_cleanup
);
1605 /***********************************************************/
1606 /* Bluetooth support */
1609 static struct HCIInfo
*hci_table
[MAX_NICS
];
1611 static struct bt_vlan_s
{
1612 struct bt_scatternet_s net
;
1614 struct bt_vlan_s
*next
;
1617 /* find or alloc a new bluetooth "VLAN" */
1618 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1620 struct bt_vlan_s
**pvlan
, *vlan
;
1621 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1625 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1627 pvlan
= &first_bt_vlan
;
1628 while (*pvlan
!= NULL
)
1629 pvlan
= &(*pvlan
)->next
;
1634 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1638 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1643 static struct HCIInfo null_hci
= {
1644 .cmd_send
= null_hci_send
,
1645 .sco_send
= null_hci_send
,
1646 .acl_send
= null_hci_send
,
1647 .bdaddr_set
= null_hci_addr_set
,
1650 struct HCIInfo
*qemu_next_hci(void)
1652 if (cur_hci
== nb_hcis
)
1655 return hci_table
[cur_hci
++];
1658 static struct HCIInfo
*hci_init(const char *str
)
1661 struct bt_scatternet_s
*vlan
= 0;
1663 if (!strcmp(str
, "null"))
1666 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
1668 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
1669 else if (!strncmp(str
, "hci", 3)) {
1672 if (!strncmp(str
+ 3, ",vlan=", 6)) {
1673 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
1678 vlan
= qemu_find_bt_vlan(0);
1680 return bt_new_hci(vlan
);
1683 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
1688 static int bt_hci_parse(const char *str
)
1690 struct HCIInfo
*hci
;
1693 if (nb_hcis
>= MAX_NICS
) {
1694 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
1698 hci
= hci_init(str
);
1707 bdaddr
.b
[5] = 0x56 + nb_hcis
;
1708 hci
->bdaddr_set(hci
, bdaddr
.b
);
1710 hci_table
[nb_hcis
++] = hci
;
1715 static void bt_vhci_add(int vlan_id
)
1717 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
1720 fprintf(stderr
, "qemu: warning: adding a VHCI to "
1721 "an empty scatternet %i\n", vlan_id
);
1723 bt_vhci_init(bt_new_hci(vlan
));
1726 static struct bt_device_s
*bt_device_add(const char *opt
)
1728 struct bt_scatternet_s
*vlan
;
1730 char *endp
= strstr(opt
, ",vlan=");
1731 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
1734 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
1737 vlan_id
= strtol(endp
+ 6, &endp
, 0);
1739 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
1744 vlan
= qemu_find_bt_vlan(vlan_id
);
1747 fprintf(stderr
, "qemu: warning: adding a slave device to "
1748 "an empty scatternet %i\n", vlan_id
);
1750 if (!strcmp(devname
, "keyboard"))
1751 return bt_keyboard_init(vlan
);
1753 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
1757 static int bt_parse(const char *opt
)
1759 const char *endp
, *p
;
1762 if (strstart(opt
, "hci", &endp
)) {
1763 if (!*endp
|| *endp
== ',') {
1765 if (!strstart(endp
, ",vlan=", 0))
1768 return bt_hci_parse(opt
);
1770 } else if (strstart(opt
, "vhci", &endp
)) {
1771 if (!*endp
|| *endp
== ',') {
1773 if (strstart(endp
, ",vlan=", &p
)) {
1774 vlan
= strtol(p
, (char **) &endp
, 0);
1776 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
1780 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
1789 } else if (strstart(opt
, "device:", &endp
))
1790 return !bt_device_add(endp
);
1792 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
1796 /***********************************************************/
1797 /* QEMU Block devices */
1799 #define HD_ALIAS "index=%d,media=disk"
1800 #define CDROM_ALIAS "index=2,media=cdrom"
1801 #define FD_ALIAS "index=%d,if=floppy"
1802 #define PFLASH_ALIAS "if=pflash"
1803 #define MTD_ALIAS "if=mtd"
1804 #define SD_ALIAS "index=0,if=sd"
1806 QemuOpts
*drive_add(const char *file
, const char *fmt
, ...)
1813 vsnprintf(optstr
, sizeof(optstr
), fmt
, ap
);
1816 opts
= qemu_opts_parse(&qemu_drive_opts
, optstr
, NULL
);
1818 fprintf(stderr
, "%s: huh? duplicate? (%s)\n",
1819 __FUNCTION__
, optstr
);
1823 qemu_opt_set(opts
, "file", file
);
1827 DriveInfo
*drive_get(BlockInterfaceType type
, int bus
, int unit
)
1831 /* seek interface, bus and unit */
1833 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1834 if (dinfo
->type
== type
&&
1835 dinfo
->bus
== bus
&&
1836 dinfo
->unit
== unit
)
1843 DriveInfo
*drive_get_by_id(const char *id
)
1847 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1848 if (strcmp(id
, dinfo
->id
))
1855 int drive_get_max_bus(BlockInterfaceType type
)
1861 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1862 if(dinfo
->type
== type
&&
1863 dinfo
->bus
> max_bus
)
1864 max_bus
= dinfo
->bus
;
1869 const char *drive_get_serial(BlockDriverState
*bdrv
)
1873 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1874 if (dinfo
->bdrv
== bdrv
)
1875 return dinfo
->serial
;
1881 BlockInterfaceErrorAction
drive_get_on_error(
1882 BlockDriverState
*bdrv
, int is_read
)
1886 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1887 if (dinfo
->bdrv
== bdrv
)
1888 return is_read
? dinfo
->on_read_error
: dinfo
->on_write_error
;
1891 return is_read
? BLOCK_ERR_REPORT
: BLOCK_ERR_STOP_ENOSPC
;
1894 static void bdrv_format_print(void *opaque
, const char *name
)
1896 fprintf(stderr
, " %s", name
);
1899 void drive_uninit(DriveInfo
*dinfo
)
1901 qemu_opts_del(dinfo
->opts
);
1902 bdrv_delete(dinfo
->bdrv
);
1903 QTAILQ_REMOVE(&drives
, dinfo
, next
);
1907 static int parse_block_error_action(const char *buf
, int is_read
)
1909 if (!strcmp(buf
, "ignore")) {
1910 return BLOCK_ERR_IGNORE
;
1911 } else if (!is_read
&& !strcmp(buf
, "enospc")) {
1912 return BLOCK_ERR_STOP_ENOSPC
;
1913 } else if (!strcmp(buf
, "stop")) {
1914 return BLOCK_ERR_STOP_ANY
;
1915 } else if (!strcmp(buf
, "report")) {
1916 return BLOCK_ERR_REPORT
;
1918 fprintf(stderr
, "qemu: '%s' invalid %s error action\n",
1919 buf
, is_read
? "read" : "write");
1924 DriveInfo
*drive_init(QemuOpts
*opts
, void *opaque
,
1928 const char *file
= NULL
;
1931 const char *mediastr
= "";
1932 BlockInterfaceType type
;
1933 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
1934 int bus_id
, unit_id
;
1935 int cyls
, heads
, secs
, translation
;
1936 BlockDriver
*drv
= NULL
;
1937 QEMUMachine
*machine
= opaque
;
1944 int on_read_error
, on_write_error
;
1945 const char *devaddr
;
1952 translation
= BIOS_ATA_TRANSLATION_AUTO
;
1955 if (machine
&& machine
->use_scsi
) {
1957 max_devs
= MAX_SCSI_DEVS
;
1958 pstrcpy(devname
, sizeof(devname
), "scsi");
1961 max_devs
= MAX_IDE_DEVS
;
1962 pstrcpy(devname
, sizeof(devname
), "ide");
1966 /* extract parameters */
1967 bus_id
= qemu_opt_get_number(opts
, "bus", 0);
1968 unit_id
= qemu_opt_get_number(opts
, "unit", -1);
1969 index
= qemu_opt_get_number(opts
, "index", -1);
1971 cyls
= qemu_opt_get_number(opts
, "cyls", 0);
1972 heads
= qemu_opt_get_number(opts
, "heads", 0);
1973 secs
= qemu_opt_get_number(opts
, "secs", 0);
1975 snapshot
= qemu_opt_get_bool(opts
, "snapshot", 0);
1976 ro
= qemu_opt_get_bool(opts
, "readonly", 0);
1978 file
= qemu_opt_get(opts
, "file");
1979 serial
= qemu_opt_get(opts
, "serial");
1981 if ((buf
= qemu_opt_get(opts
, "if")) != NULL
) {
1982 pstrcpy(devname
, sizeof(devname
), buf
);
1983 if (!strcmp(buf
, "ide")) {
1985 max_devs
= MAX_IDE_DEVS
;
1986 } else if (!strcmp(buf
, "scsi")) {
1988 max_devs
= MAX_SCSI_DEVS
;
1989 } else if (!strcmp(buf
, "floppy")) {
1992 } else if (!strcmp(buf
, "pflash")) {
1995 } else if (!strcmp(buf
, "mtd")) {
1998 } else if (!strcmp(buf
, "sd")) {
2001 } else if (!strcmp(buf
, "virtio")) {
2004 } else if (!strcmp(buf
, "xen")) {
2007 } else if (!strcmp(buf
, "none")) {
2011 fprintf(stderr
, "qemu: unsupported bus type '%s'\n", buf
);
2016 if (cyls
|| heads
|| secs
) {
2017 if (cyls
< 1 || (type
== IF_IDE
&& cyls
> 16383)) {
2018 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", buf
);
2021 if (heads
< 1 || (type
== IF_IDE
&& heads
> 16)) {
2022 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", buf
);
2025 if (secs
< 1 || (type
== IF_IDE
&& secs
> 63)) {
2026 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", buf
);
2031 if ((buf
= qemu_opt_get(opts
, "trans")) != NULL
) {
2034 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2038 if (!strcmp(buf
, "none"))
2039 translation
= BIOS_ATA_TRANSLATION_NONE
;
2040 else if (!strcmp(buf
, "lba"))
2041 translation
= BIOS_ATA_TRANSLATION_LBA
;
2042 else if (!strcmp(buf
, "auto"))
2043 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2045 fprintf(stderr
, "qemu: '%s' invalid translation type\n", buf
);
2050 if ((buf
= qemu_opt_get(opts
, "media")) != NULL
) {
2051 if (!strcmp(buf
, "disk")) {
2053 } else if (!strcmp(buf
, "cdrom")) {
2054 if (cyls
|| secs
|| heads
) {
2056 "qemu: '%s' invalid physical CHS format\n", buf
);
2059 media
= MEDIA_CDROM
;
2061 fprintf(stderr
, "qemu: '%s' invalid media\n", buf
);
2066 if ((buf
= qemu_opt_get(opts
, "cache")) != NULL
) {
2067 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2069 else if (!strcmp(buf
, "writethrough"))
2071 else if (!strcmp(buf
, "writeback"))
2074 fprintf(stderr
, "qemu: invalid cache option\n");
2079 #ifdef CONFIG_LINUX_AIO
2080 if ((buf
= qemu_opt_get(opts
, "aio")) != NULL
) {
2081 if (!strcmp(buf
, "threads"))
2083 else if (!strcmp(buf
, "native"))
2086 fprintf(stderr
, "qemu: invalid aio option\n");
2092 if ((buf
= qemu_opt_get(opts
, "format")) != NULL
) {
2093 if (strcmp(buf
, "?") == 0) {
2094 fprintf(stderr
, "qemu: Supported formats:");
2095 bdrv_iterate_format(bdrv_format_print
, NULL
);
2096 fprintf(stderr
, "\n");
2099 drv
= bdrv_find_whitelisted_format(buf
);
2101 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2106 is_extboot
= qemu_opt_get_bool(opts
, "boot", 0);
2107 if (is_extboot
&& extboot_drive
) {
2108 fprintf(stderr
, "qemu: two bootable drives specified\n");
2112 on_write_error
= BLOCK_ERR_STOP_ENOSPC
;
2113 if ((buf
= qemu_opt_get(opts
, "werror")) != NULL
) {
2114 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2115 fprintf(stderr
, "werror is no supported by this format\n");
2119 on_write_error
= parse_block_error_action(buf
, 0);
2120 if (on_write_error
< 0) {
2125 on_read_error
= BLOCK_ERR_REPORT
;
2126 if ((buf
= qemu_opt_get(opts
, "rerror")) != NULL
) {
2127 if (type
!= IF_IDE
&& type
!= IF_VIRTIO
) {
2128 fprintf(stderr
, "rerror is no supported by this format\n");
2132 on_read_error
= parse_block_error_action(buf
, 1);
2133 if (on_read_error
< 0) {
2138 if ((devaddr
= qemu_opt_get(opts
, "addr")) != NULL
) {
2139 if (type
!= IF_VIRTIO
) {
2140 fprintf(stderr
, "addr is not supported\n");
2145 /* compute bus and unit according index */
2148 if (bus_id
!= 0 || unit_id
!= -1) {
2150 "qemu: index cannot be used with bus and unit\n");
2158 unit_id
= index
% max_devs
;
2159 bus_id
= index
/ max_devs
;
2163 /* if user doesn't specify a unit_id,
2164 * try to find the first free
2167 if (unit_id
== -1) {
2169 while (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2171 if (max_devs
&& unit_id
>= max_devs
) {
2172 unit_id
-= max_devs
;
2180 if (max_devs
&& unit_id
>= max_devs
) {
2181 fprintf(stderr
, "qemu: unit %d too big (max is %d)\n",
2182 unit_id
, max_devs
- 1);
2187 * ignore multiple definitions
2190 if (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2197 dinfo
= qemu_mallocz(sizeof(*dinfo
));
2198 if ((buf
= qemu_opts_id(opts
)) != NULL
) {
2199 dinfo
->id
= qemu_strdup(buf
);
2201 /* no id supplied -> create one */
2202 dinfo
->id
= qemu_mallocz(32);
2203 if (type
== IF_IDE
|| type
== IF_SCSI
)
2204 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2206 snprintf(dinfo
->id
, 32, "%s%i%s%i",
2207 devname
, bus_id
, mediastr
, unit_id
);
2209 snprintf(dinfo
->id
, 32, "%s%s%i",
2210 devname
, mediastr
, unit_id
);
2212 dinfo
->bdrv
= bdrv_new(dinfo
->id
);
2213 dinfo
->devaddr
= devaddr
;
2215 dinfo
->bus
= bus_id
;
2216 dinfo
->unit
= unit_id
;
2217 dinfo
->on_read_error
= on_read_error
;
2218 dinfo
->on_write_error
= on_write_error
;
2221 strncpy(dinfo
->serial
, serial
, sizeof(serial
));
2222 QTAILQ_INSERT_TAIL(&drives
, dinfo
, next
);
2224 extboot_drive
= dinfo
;
2235 bdrv_set_geometry_hint(dinfo
->bdrv
, cyls
, heads
, secs
);
2236 bdrv_set_translation_hint(dinfo
->bdrv
, translation
);
2240 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_CDROM
);
2245 /* FIXME: This isn't really a floppy, but it's a reasonable
2248 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_FLOPPY
);
2254 /* add virtio block device */
2255 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
2256 qemu_opt_set(opts
, "driver", "virtio-blk-pci");
2257 qemu_opt_set(opts
, "drive", dinfo
->id
);
2259 qemu_opt_set(opts
, "addr", devaddr
);
2270 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2271 cache
= 2; /* always use write-back with snapshot */
2273 if (cache
== 0) /* no caching */
2274 bdrv_flags
|= BDRV_O_NOCACHE
;
2275 else if (cache
== 2) /* write-back */
2276 bdrv_flags
|= BDRV_O_CACHE_WB
;
2279 bdrv_flags
|= BDRV_O_NATIVE_AIO
;
2281 bdrv_flags
&= ~BDRV_O_NATIVE_AIO
;
2285 if (type
!= IF_SCSI
&& type
!= IF_VIRTIO
&& type
!= IF_FLOPPY
) {
2286 fprintf(stderr
, "qemu: readonly flag not supported for drive with this interface\n");
2291 * cdrom is read-only. Set it now, after above interface checking
2292 * since readonly attribute not explicitly required, so no error.
2294 if (media
== MEDIA_CDROM
) {
2297 bdrv_flags
|= ro
? 0 : BDRV_O_RDWR
;
2299 if (bdrv_open2(dinfo
->bdrv
, file
, bdrv_flags
, drv
) < 0) {
2300 fprintf(stderr
, "qemu: could not open disk image %s: %s\n",
2301 file
, strerror(errno
));
2305 if (bdrv_key_required(dinfo
->bdrv
))
2311 static int drive_init_func(QemuOpts
*opts
, void *opaque
)
2313 QEMUMachine
*machine
= opaque
;
2314 int fatal_error
= 0;
2316 if (drive_init(opts
, machine
, &fatal_error
) == NULL
) {
2323 static int drive_enable_snapshot(QemuOpts
*opts
, void *opaque
)
2325 if (NULL
== qemu_opt_get(opts
, "snapshot")) {
2326 qemu_opt_set(opts
, "snapshot", "on");
2331 void qemu_register_boot_set(QEMUBootSetHandler
*func
, void *opaque
)
2333 boot_set_handler
= func
;
2334 boot_set_opaque
= opaque
;
2337 int qemu_boot_set(const char *boot_devices
)
2339 if (!boot_set_handler
) {
2342 return boot_set_handler(boot_set_opaque
, boot_devices
);
2345 static int parse_bootdevices(char *devices
)
2347 /* We just do some generic consistency checks */
2351 for (p
= devices
; *p
!= '\0'; p
++) {
2352 /* Allowed boot devices are:
2353 * a-b: floppy disk drives
2354 * c-f: IDE disk drives
2355 * g-m: machine implementation dependant drives
2356 * n-p: network devices
2357 * It's up to each machine implementation to check if the given boot
2358 * devices match the actual hardware implementation and firmware
2361 if (*p
< 'a' || *p
> 'p') {
2362 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
2365 if (bitmap
& (1 << (*p
- 'a'))) {
2366 fprintf(stderr
, "Boot device '%c' was given twice\n", *p
);
2369 bitmap
|= 1 << (*p
- 'a');
2374 static void restore_boot_devices(void *opaque
)
2376 char *standard_boot_devices
= opaque
;
2378 qemu_boot_set(standard_boot_devices
);
2380 qemu_unregister_reset(restore_boot_devices
, standard_boot_devices
);
2381 qemu_free(standard_boot_devices
);
2384 static void numa_add(const char *optarg
)
2388 unsigned long long value
, endvalue
;
2391 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2392 if (!strcmp(option
, "node")) {
2393 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2394 nodenr
= nb_numa_nodes
;
2396 nodenr
= strtoull(option
, NULL
, 10);
2399 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2400 node_mem
[nodenr
] = 0;
2402 value
= strtoull(option
, &endptr
, 0);
2404 case 0: case 'M': case 'm':
2411 node_mem
[nodenr
] = value
;
2413 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2414 node_cpumask
[nodenr
] = 0;
2416 value
= strtoull(option
, &endptr
, 10);
2419 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2421 if (*endptr
== '-') {
2422 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2423 if (endvalue
>= 63) {
2426 "only 63 CPUs in NUMA mode supported.\n");
2428 value
= (2ULL << endvalue
) - (1ULL << value
);
2430 value
= 1ULL << value
;
2433 node_cpumask
[nodenr
] = value
;
2440 static void smp_parse(const char *optarg
)
2442 int smp
, sockets
= 0, threads
= 0, cores
= 0;
2446 smp
= strtoul(optarg
, &endptr
, 10);
2447 if (endptr
!= optarg
) {
2448 if (*endptr
== ',') {
2452 if (get_param_value(option
, 128, "sockets", endptr
) != 0)
2453 sockets
= strtoull(option
, NULL
, 10);
2454 if (get_param_value(option
, 128, "cores", endptr
) != 0)
2455 cores
= strtoull(option
, NULL
, 10);
2456 if (get_param_value(option
, 128, "threads", endptr
) != 0)
2457 threads
= strtoull(option
, NULL
, 10);
2458 if (get_param_value(option
, 128, "maxcpus", endptr
) != 0)
2459 max_cpus
= strtoull(option
, NULL
, 10);
2461 /* compute missing values, prefer sockets over cores over threads */
2462 if (smp
== 0 || sockets
== 0) {
2463 sockets
= sockets
> 0 ? sockets
: 1;
2464 cores
= cores
> 0 ? cores
: 1;
2465 threads
= threads
> 0 ? threads
: 1;
2467 smp
= cores
* threads
* sockets
;
2471 threads
= threads
> 0 ? threads
: 1;
2472 cores
= smp
/ (sockets
* threads
);
2475 threads
= smp
/ (cores
* sockets
);
2480 smp_cores
= cores
> 0 ? cores
: 1;
2481 smp_threads
= threads
> 0 ? threads
: 1;
2483 max_cpus
= smp_cpus
;
2486 /***********************************************************/
2489 static int usb_device_add(const char *devname
, int is_hotplug
)
2492 USBDevice
*dev
= NULL
;
2497 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2498 dev
= usbdevice_create(devname
);
2502 /* the other ones */
2503 if (strstart(devname
, "host:", &p
)) {
2504 dev
= usb_host_device_open(p
);
2505 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2506 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2507 bt_new_hci(qemu_find_bt_vlan(0)));
2518 static int usb_device_del(const char *devname
)
2523 if (strstart(devname
, "host:", &p
))
2524 return usb_host_device_close(p
);
2529 p
= strchr(devname
, '.');
2532 bus_num
= strtoul(devname
, NULL
, 0);
2533 addr
= strtoul(p
+ 1, NULL
, 0);
2535 return usb_device_delete_addr(bus_num
, addr
);
2538 static int usb_parse(const char *cmdline
)
2541 r
= usb_device_add(cmdline
, 0);
2543 fprintf(stderr
, "qemu: could not add USB device '%s'\n", cmdline
);
2548 void do_usb_add(Monitor
*mon
, const QDict
*qdict
)
2550 const char *devname
= qdict_get_str(qdict
, "devname");
2551 if (usb_device_add(devname
, 1) < 0) {
2552 qemu_error("could not add USB device '%s'\n", devname
);
2556 void do_usb_del(Monitor
*mon
, const QDict
*qdict
)
2558 const char *devname
= qdict_get_str(qdict
, "devname");
2559 if (usb_device_del(devname
) < 0) {
2560 qemu_error("could not delete USB device '%s'\n", devname
);
2564 /***********************************************************/
2565 /* PCMCIA/Cardbus */
2567 static struct pcmcia_socket_entry_s
{
2568 PCMCIASocket
*socket
;
2569 struct pcmcia_socket_entry_s
*next
;
2570 } *pcmcia_sockets
= 0;
2572 void pcmcia_socket_register(PCMCIASocket
*socket
)
2574 struct pcmcia_socket_entry_s
*entry
;
2576 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2577 entry
->socket
= socket
;
2578 entry
->next
= pcmcia_sockets
;
2579 pcmcia_sockets
= entry
;
2582 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2584 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2586 ptr
= &pcmcia_sockets
;
2587 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2588 if (entry
->socket
== socket
) {
2594 void pcmcia_info(Monitor
*mon
)
2596 struct pcmcia_socket_entry_s
*iter
;
2598 if (!pcmcia_sockets
)
2599 monitor_printf(mon
, "No PCMCIA sockets\n");
2601 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2602 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2603 iter
->socket
->attached
? iter
->socket
->card_string
:
2607 /***********************************************************/
2610 typedef struct IOHandlerRecord
{
2612 IOCanRWHandler
*fd_read_poll
;
2614 IOHandler
*fd_write
;
2617 /* temporary data */
2619 struct IOHandlerRecord
*next
;
2622 static IOHandlerRecord
*first_io_handler
;
2624 /* XXX: fd_read_poll should be suppressed, but an API change is
2625 necessary in the character devices to suppress fd_can_read(). */
2626 int qemu_set_fd_handler2(int fd
,
2627 IOCanRWHandler
*fd_read_poll
,
2629 IOHandler
*fd_write
,
2632 IOHandlerRecord
**pioh
, *ioh
;
2634 if (!fd_read
&& !fd_write
) {
2635 pioh
= &first_io_handler
;
2640 if (ioh
->fd
== fd
) {
2647 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
2651 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
2652 ioh
->next
= first_io_handler
;
2653 first_io_handler
= ioh
;
2656 ioh
->fd_read_poll
= fd_read_poll
;
2657 ioh
->fd_read
= fd_read
;
2658 ioh
->fd_write
= fd_write
;
2659 ioh
->opaque
= opaque
;
2662 qemu_notify_event();
2666 int qemu_set_fd_handler(int fd
,
2668 IOHandler
*fd_write
,
2671 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
2675 /***********************************************************/
2676 /* Polling handling */
2678 typedef struct PollingEntry
{
2681 struct PollingEntry
*next
;
2684 static PollingEntry
*first_polling_entry
;
2686 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
2688 PollingEntry
**ppe
, *pe
;
2689 pe
= qemu_mallocz(sizeof(PollingEntry
));
2691 pe
->opaque
= opaque
;
2692 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
2697 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
2699 PollingEntry
**ppe
, *pe
;
2700 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
2702 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
2710 /***********************************************************/
2711 /* Wait objects support */
2712 typedef struct WaitObjects
{
2714 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
2715 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
2716 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
2719 static WaitObjects wait_objects
= {0};
2721 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2723 WaitObjects
*w
= &wait_objects
;
2725 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
2727 w
->events
[w
->num
] = handle
;
2728 w
->func
[w
->num
] = func
;
2729 w
->opaque
[w
->num
] = opaque
;
2734 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2737 WaitObjects
*w
= &wait_objects
;
2740 for (i
= 0; i
< w
->num
; i
++) {
2741 if (w
->events
[i
] == handle
)
2744 w
->events
[i
] = w
->events
[i
+ 1];
2745 w
->func
[i
] = w
->func
[i
+ 1];
2746 w
->opaque
[i
] = w
->opaque
[i
+ 1];
2754 /***********************************************************/
2755 /* ram save/restore */
2757 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2758 #define RAM_SAVE_FLAG_COMPRESS 0x02
2759 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2760 #define RAM_SAVE_FLAG_PAGE 0x08
2761 #define RAM_SAVE_FLAG_EOS 0x10
2763 static int is_dup_page(uint8_t *page
, uint8_t ch
)
2765 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
2766 uint32_t *array
= (uint32_t *)page
;
2769 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
2770 if (array
[i
] != val
)
2777 static int ram_save_block(QEMUFile
*f
)
2779 static ram_addr_t current_addr
= 0;
2780 ram_addr_t saved_addr
= current_addr
;
2781 ram_addr_t addr
= 0;
2784 while (addr
< last_ram_offset
) {
2785 if (kvm_enabled() && current_addr
== 0) {
2787 r
= kvm_update_dirty_pages_log();
2789 fprintf(stderr
, "%s: update dirty pages log failed %d\n", __FUNCTION__
, r
);
2790 qemu_file_set_error(f
);
2794 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
2797 cpu_physical_memory_reset_dirty(current_addr
,
2798 current_addr
+ TARGET_PAGE_SIZE
,
2799 MIGRATION_DIRTY_FLAG
);
2801 p
= qemu_get_ram_ptr(current_addr
);
2803 if (is_dup_page(p
, *p
)) {
2804 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
2805 qemu_put_byte(f
, *p
);
2807 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
2808 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
2814 addr
+= TARGET_PAGE_SIZE
;
2815 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
2821 static uint64_t bytes_transferred
;
2823 static ram_addr_t
ram_save_remaining(void)
2826 ram_addr_t count
= 0;
2828 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2829 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2836 uint64_t ram_bytes_remaining(void)
2838 return ram_save_remaining() * TARGET_PAGE_SIZE
;
2841 uint64_t ram_bytes_transferred(void)
2843 return bytes_transferred
;
2846 uint64_t ram_bytes_total(void)
2848 return last_ram_offset
;
2851 static int ram_save_live(Monitor
*mon
, QEMUFile
*f
, int stage
, void *opaque
)
2854 uint64_t bytes_transferred_last
;
2856 uint64_t expected_time
= 0;
2859 cpu_physical_memory_set_dirty_tracking(0);
2863 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX
) != 0) {
2864 qemu_file_set_error(f
);
2869 bytes_transferred
= 0;
2871 /* Make sure all dirty bits are set */
2872 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2873 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2874 cpu_physical_memory_set_dirty(addr
);
2877 /* Enable dirty memory tracking */
2878 cpu_physical_memory_set_dirty_tracking(1);
2880 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
2883 bytes_transferred_last
= bytes_transferred
;
2884 bwidth
= qemu_get_clock_ns(rt_clock
);
2886 while (!qemu_file_rate_limit(f
)) {
2889 ret
= ram_save_block(f
);
2890 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
2891 if (ret
== 0) /* no more blocks */
2895 bwidth
= qemu_get_clock_ns(rt_clock
) - bwidth
;
2896 bwidth
= (bytes_transferred
- bytes_transferred_last
) / bwidth
;
2898 /* if we haven't transferred anything this round, force expected_time to a
2899 * a very high value, but without crashing */
2903 /* try transferring iterative blocks of memory */
2905 /* flush all remaining blocks regardless of rate limiting */
2906 while (ram_save_block(f
) != 0) {
2907 bytes_transferred
+= TARGET_PAGE_SIZE
;
2909 cpu_physical_memory_set_dirty_tracking(0);
2912 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
2914 expected_time
= ram_save_remaining() * TARGET_PAGE_SIZE
/ bwidth
;
2916 return (stage
== 2) && (expected_time
<= migrate_max_downtime());
2919 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
2924 if (version_id
!= 3)
2928 addr
= qemu_get_be64(f
);
2930 flags
= addr
& ~TARGET_PAGE_MASK
;
2931 addr
&= TARGET_PAGE_MASK
;
2933 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
2934 if (addr
!= last_ram_offset
)
2938 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
2939 uint8_t ch
= qemu_get_byte(f
);
2940 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
2943 (!kvm_enabled() || kvm_has_sync_mmu())) {
2944 madvise(qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
, MADV_DONTNEED
);
2947 } else if (flags
& RAM_SAVE_FLAG_PAGE
) {
2948 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
2950 if (qemu_file_has_error(f
)) {
2953 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
2958 void qemu_service_io(void)
2960 qemu_notify_event();
2963 /***********************************************************/
2964 /* machine registration */
2966 static QEMUMachine
*first_machine
= NULL
;
2967 QEMUMachine
*current_machine
= NULL
;
2969 int qemu_register_machine(QEMUMachine
*m
)
2972 pm
= &first_machine
;
2980 static QEMUMachine
*find_machine(const char *name
)
2984 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
2985 if (!strcmp(m
->name
, name
))
2987 if (m
->alias
&& !strcmp(m
->alias
, name
))
2993 static QEMUMachine
*find_default_machine(void)
2997 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
2998 if (m
->is_default
) {
3005 /***********************************************************/
3006 /* main execution loop */
3008 static void gui_update(void *opaque
)
3010 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3011 DisplayState
*ds
= opaque
;
3012 DisplayChangeListener
*dcl
= ds
->listeners
;
3014 qemu_flush_coalesced_mmio_buffer();
3017 while (dcl
!= NULL
) {
3018 if (dcl
->gui_timer_interval
&&
3019 dcl
->gui_timer_interval
< interval
)
3020 interval
= dcl
->gui_timer_interval
;
3023 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3026 static void nographic_update(void *opaque
)
3028 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3030 qemu_flush_coalesced_mmio_buffer();
3031 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3034 struct vm_change_state_entry
{
3035 VMChangeStateHandler
*cb
;
3037 QLIST_ENTRY (vm_change_state_entry
) entries
;
3040 static QLIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3042 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3045 VMChangeStateEntry
*e
;
3047 e
= qemu_mallocz(sizeof (*e
));
3051 QLIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3055 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3057 QLIST_REMOVE (e
, entries
);
3061 static void vm_state_notify(int running
, int reason
)
3063 VMChangeStateEntry
*e
;
3065 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3066 e
->cb(e
->opaque
, running
, reason
);
3070 static void resume_all_vcpus(void);
3071 static void pause_all_vcpus(void);
3078 vm_state_notify(1, 0);
3079 qemu_rearm_alarm_timer(alarm_timer
);
3084 /* reset/shutdown handler */
3086 typedef struct QEMUResetEntry
{
3087 QTAILQ_ENTRY(QEMUResetEntry
) entry
;
3088 QEMUResetHandler
*func
;
3092 static QTAILQ_HEAD(reset_handlers
, QEMUResetEntry
) reset_handlers
=
3093 QTAILQ_HEAD_INITIALIZER(reset_handlers
);
3094 static int reset_requested
;
3095 static int shutdown_requested
;
3096 static int powerdown_requested
;
3097 static int debug_requested
;
3098 static int vmstop_requested
;
3100 int qemu_no_shutdown(void)
3102 int r
= no_shutdown
;
3107 int qemu_shutdown_requested(void)
3109 int r
= shutdown_requested
;
3110 shutdown_requested
= 0;
3114 int qemu_reset_requested(void)
3116 int r
= reset_requested
;
3117 reset_requested
= 0;
3121 int qemu_powerdown_requested(void)
3123 int r
= powerdown_requested
;
3124 powerdown_requested
= 0;
3128 static int qemu_debug_requested(void)
3130 int r
= debug_requested
;
3131 debug_requested
= 0;
3135 static int qemu_vmstop_requested(void)
3137 int r
= vmstop_requested
;
3138 vmstop_requested
= 0;
3142 static void do_vm_stop(int reason
)
3145 cpu_disable_ticks();
3148 vm_state_notify(0, reason
);
3152 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3154 QEMUResetEntry
*re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3157 re
->opaque
= opaque
;
3158 QTAILQ_INSERT_TAIL(&reset_handlers
, re
, entry
);
3161 void qemu_unregister_reset(QEMUResetHandler
*func
, void *opaque
)
3165 QTAILQ_FOREACH(re
, &reset_handlers
, entry
) {
3166 if (re
->func
== func
&& re
->opaque
== opaque
) {
3167 QTAILQ_REMOVE(&reset_handlers
, re
, entry
);
3174 void qemu_system_reset(void)
3176 QEMUResetEntry
*re
, *nre
;
3178 /* reset all devices */
3179 QTAILQ_FOREACH_SAFE(re
, &reset_handlers
, entry
, nre
) {
3180 re
->func(re
->opaque
);
3184 void qemu_system_reset_request(void)
3187 shutdown_requested
= 1;
3189 reset_requested
= 1;
3191 if (cpu_single_env
) {
3192 cpu_single_env
->stopped
= 1;
3194 qemu_notify_event();
3197 void qemu_system_shutdown_request(void)
3199 shutdown_requested
= 1;
3200 qemu_notify_event();
3203 void qemu_system_powerdown_request(void)
3205 powerdown_requested
= 1;
3206 qemu_notify_event();
3209 #ifdef CONFIG_IOTHREAD
3210 static void qemu_system_vmstop_request(int reason
)
3212 vmstop_requested
= reason
;
3213 qemu_notify_event();
3218 static int io_thread_fd
= -1;
3220 static void qemu_event_increment(void)
3222 /* Write 8 bytes to be compatible with eventfd. */
3223 static uint64_t val
= 1;
3226 if (io_thread_fd
== -1)
3230 ret
= write(io_thread_fd
, &val
, sizeof(val
));
3231 } while (ret
< 0 && errno
== EINTR
);
3233 /* EAGAIN is fine, a read must be pending. */
3234 if (ret
< 0 && errno
!= EAGAIN
) {
3235 fprintf(stderr
, "qemu_event_increment: write() filed: %s\n",
3241 static void qemu_event_read(void *opaque
)
3243 int fd
= (unsigned long)opaque
;
3247 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
3249 len
= read(fd
, buffer
, sizeof(buffer
));
3250 } while ((len
== -1 && errno
== EINTR
) || len
== sizeof(buffer
));
3253 static int qemu_event_init(void)
3258 err
= qemu_eventfd(fds
);
3262 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3266 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3270 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3271 (void *)(unsigned long)fds
[0]);
3273 io_thread_fd
= fds
[1];
3282 HANDLE qemu_event_handle
;
3284 static void dummy_event_handler(void *opaque
)
3288 static int qemu_event_init(void)
3290 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3291 if (!qemu_event_handle
) {
3292 fprintf(stderr
, "Failed CreateEvent: %ld\n", GetLastError());
3295 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3299 static void qemu_event_increment(void)
3301 if (!SetEvent(qemu_event_handle
)) {
3302 fprintf(stderr
, "qemu_event_increment: SetEvent failed: %ld\n",
3309 static int cpu_can_run(CPUState
*env
)
3320 #ifndef CONFIG_IOTHREAD
3321 static int qemu_init_main_loop(void)
3323 return qemu_event_init();
3326 void qemu_init_vcpu(void *_env
)
3328 CPUState
*env
= _env
;
3330 env
->nr_cores
= smp_cores
;
3331 env
->nr_threads
= smp_threads
;
3337 int qemu_cpu_self(void *env
)
3342 static void resume_all_vcpus(void)
3346 static void pause_all_vcpus(void)
3350 void qemu_cpu_kick(void *env
)
3355 void qemu_notify_event(void)
3357 CPUState
*env
= cpu_single_env
;
3359 if (kvm_enabled()) {
3360 qemu_kvm_notify_work();
3368 #if defined(KVM_UPSTREAM) || !defined(CONFIG_KVM)
3369 void qemu_mutex_lock_iothread(void) {}
3370 void qemu_mutex_unlock_iothread(void) {}
3373 void vm_stop(int reason
)
3378 #else /* CONFIG_IOTHREAD */
3380 #include "qemu-thread.h"
3382 QemuMutex qemu_global_mutex
;
3383 static QemuMutex qemu_fair_mutex
;
3385 static QemuThread io_thread
;
3387 static QemuThread
*tcg_cpu_thread
;
3388 static QemuCond
*tcg_halt_cond
;
3390 static int qemu_system_ready
;
3392 static QemuCond qemu_cpu_cond
;
3394 static QemuCond qemu_system_cond
;
3395 static QemuCond qemu_pause_cond
;
3397 static void tcg_block_io_signals(void);
3398 static void kvm_block_io_signals(CPUState
*env
);
3399 static void unblock_io_signals(void);
3400 static int tcg_has_work(void);
3401 static int cpu_has_work(CPUState
*env
);
3403 static int qemu_init_main_loop(void)
3407 ret
= qemu_event_init();
3411 qemu_cond_init(&qemu_pause_cond
);
3412 qemu_mutex_init(&qemu_fair_mutex
);
3413 qemu_mutex_init(&qemu_global_mutex
);
3414 qemu_mutex_lock(&qemu_global_mutex
);
3416 unblock_io_signals();
3417 qemu_thread_self(&io_thread
);
3422 static void qemu_wait_io_event_common(CPUState
*env
)
3427 qemu_cond_signal(&qemu_pause_cond
);
3431 static void qemu_wait_io_event(CPUState
*env
)
3433 while (!tcg_has_work())
3434 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3436 qemu_mutex_unlock(&qemu_global_mutex
);
3439 * Users of qemu_global_mutex can be starved, having no chance
3440 * to acquire it since this path will get to it first.
3441 * So use another lock to provide fairness.
3443 qemu_mutex_lock(&qemu_fair_mutex
);
3444 qemu_mutex_unlock(&qemu_fair_mutex
);
3446 qemu_mutex_lock(&qemu_global_mutex
);
3447 qemu_wait_io_event_common(env
);
3450 static void qemu_kvm_eat_signal(CPUState
*env
, int timeout
)
3457 ts
.tv_sec
= timeout
/ 1000;
3458 ts
.tv_nsec
= (timeout
% 1000) * 1000000;
3460 sigemptyset(&waitset
);
3461 sigaddset(&waitset
, SIG_IPI
);
3463 qemu_mutex_unlock(&qemu_global_mutex
);
3464 r
= sigtimedwait(&waitset
, &siginfo
, &ts
);
3466 qemu_mutex_lock(&qemu_global_mutex
);
3468 if (r
== -1 && !(e
== EAGAIN
|| e
== EINTR
)) {
3469 fprintf(stderr
, "sigtimedwait: %s\n", strerror(e
));
3474 static void qemu_kvm_wait_io_event(CPUState
*env
)
3476 while (!cpu_has_work(env
))
3477 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3479 qemu_kvm_eat_signal(env
, 0);
3480 qemu_wait_io_event_common(env
);
3483 static int qemu_cpu_exec(CPUState
*env
);
3485 static void *kvm_cpu_thread_fn(void *arg
)
3487 CPUState
*env
= arg
;
3489 qemu_thread_self(env
->thread
);
3493 kvm_block_io_signals(env
);
3495 /* signal CPU creation */
3496 qemu_mutex_lock(&qemu_global_mutex
);
3498 qemu_cond_signal(&qemu_cpu_cond
);
3500 /* and wait for machine initialization */
3501 while (!qemu_system_ready
)
3502 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3505 if (cpu_can_run(env
))
3507 qemu_kvm_wait_io_event(env
);
3513 static void tcg_cpu_exec(void);
3515 static void *tcg_cpu_thread_fn(void *arg
)
3517 CPUState
*env
= arg
;
3519 tcg_block_io_signals();
3520 qemu_thread_self(env
->thread
);
3522 /* signal CPU creation */
3523 qemu_mutex_lock(&qemu_global_mutex
);
3524 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
3526 qemu_cond_signal(&qemu_cpu_cond
);
3528 /* and wait for machine initialization */
3529 while (!qemu_system_ready
)
3530 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3534 qemu_wait_io_event(cur_cpu
);
3540 void qemu_cpu_kick(void *_env
)
3542 CPUState
*env
= _env
;
3543 qemu_cond_broadcast(env
->halt_cond
);
3545 qemu_thread_signal(env
->thread
, SIG_IPI
);
3548 int qemu_cpu_self(void *_env
)
3550 CPUState
*env
= _env
;
3553 qemu_thread_self(&this);
3555 return qemu_thread_equal(&this, env
->thread
);
3558 static void cpu_signal(int sig
)
3561 cpu_exit(cpu_single_env
);
3564 static void tcg_block_io_signals(void)
3567 struct sigaction sigact
;
3570 sigaddset(&set
, SIGUSR2
);
3571 sigaddset(&set
, SIGIO
);
3572 sigaddset(&set
, SIGALRM
);
3573 sigaddset(&set
, SIGCHLD
);
3574 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3577 sigaddset(&set
, SIG_IPI
);
3578 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3580 memset(&sigact
, 0, sizeof(sigact
));
3581 sigact
.sa_handler
= cpu_signal
;
3582 sigaction(SIG_IPI
, &sigact
, NULL
);
3585 static void dummy_signal(int sig
)
3589 static void kvm_block_io_signals(CPUState
*env
)
3593 struct sigaction sigact
;
3596 sigaddset(&set
, SIGUSR2
);
3597 sigaddset(&set
, SIGIO
);
3598 sigaddset(&set
, SIGALRM
);
3599 sigaddset(&set
, SIGCHLD
);
3600 sigaddset(&set
, SIG_IPI
);
3601 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3603 pthread_sigmask(SIG_BLOCK
, NULL
, &set
);
3604 sigdelset(&set
, SIG_IPI
);
3606 memset(&sigact
, 0, sizeof(sigact
));
3607 sigact
.sa_handler
= dummy_signal
;
3608 sigaction(SIG_IPI
, &sigact
, NULL
);
3610 r
= kvm_set_signal_mask(env
, &set
);
3612 fprintf(stderr
, "kvm_set_signal_mask: %s\n", strerror(r
));
3617 static void unblock_io_signals(void)
3622 sigaddset(&set
, SIGUSR2
);
3623 sigaddset(&set
, SIGIO
);
3624 sigaddset(&set
, SIGALRM
);
3625 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3628 sigaddset(&set
, SIG_IPI
);
3629 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3632 static void qemu_signal_lock(unsigned int msecs
)
3634 qemu_mutex_lock(&qemu_fair_mutex
);
3636 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
3637 qemu_thread_signal(tcg_cpu_thread
, SIG_IPI
);
3638 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
3641 qemu_mutex_unlock(&qemu_fair_mutex
);
3644 void qemu_mutex_lock_iothread(void)
3646 if (kvm_enabled()) {
3647 qemu_mutex_lock(&qemu_fair_mutex
);
3648 qemu_mutex_lock(&qemu_global_mutex
);
3649 qemu_mutex_unlock(&qemu_fair_mutex
);
3651 qemu_signal_lock(100);
3654 void qemu_mutex_unlock_iothread(void)
3656 qemu_mutex_unlock(&qemu_global_mutex
);
3659 static int all_vcpus_paused(void)
3661 CPUState
*penv
= first_cpu
;
3666 penv
= (CPUState
*)penv
->next_cpu
;
3672 static void pause_all_vcpus(void)
3674 CPUState
*penv
= first_cpu
;
3678 qemu_thread_signal(penv
->thread
, SIG_IPI
);
3679 qemu_cpu_kick(penv
);
3680 penv
= (CPUState
*)penv
->next_cpu
;
3683 while (!all_vcpus_paused()) {
3684 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
3687 qemu_thread_signal(penv
->thread
, SIG_IPI
);
3688 penv
= (CPUState
*)penv
->next_cpu
;
3693 static void resume_all_vcpus(void)
3695 CPUState
*penv
= first_cpu
;
3700 qemu_thread_signal(penv
->thread
, SIG_IPI
);
3701 qemu_cpu_kick(penv
);
3702 penv
= (CPUState
*)penv
->next_cpu
;
3706 static void tcg_init_vcpu(void *_env
)
3708 CPUState
*env
= _env
;
3709 /* share a single thread for all cpus with TCG */
3710 if (!tcg_cpu_thread
) {
3711 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3712 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3713 qemu_cond_init(env
->halt_cond
);
3714 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
3715 while (env
->created
== 0)
3716 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3717 tcg_cpu_thread
= env
->thread
;
3718 tcg_halt_cond
= env
->halt_cond
;
3720 env
->thread
= tcg_cpu_thread
;
3721 env
->halt_cond
= tcg_halt_cond
;
3725 static void kvm_start_vcpu(CPUState
*env
)
3727 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3728 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3729 qemu_cond_init(env
->halt_cond
);
3730 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
3731 while (env
->created
== 0)
3732 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3735 void qemu_init_vcpu(void *_env
)
3737 CPUState
*env
= _env
;
3739 env
->nr_cores
= smp_cores
;
3740 env
->nr_threads
= smp_threads
;
3742 kvm_start_vcpu(env
);
3747 void qemu_notify_event(void)
3749 qemu_event_increment();
3752 void vm_stop(int reason
)
3755 qemu_thread_self(&me
);
3757 if (!qemu_thread_equal(&me
, &io_thread
)) {
3758 qemu_system_vmstop_request(reason
);
3760 * FIXME: should not return to device code in case
3761 * vm_stop() has been requested.
3763 if (cpu_single_env
) {
3764 cpu_exit(cpu_single_env
);
3765 cpu_single_env
->stop
= 1;
3776 static void host_main_loop_wait(int *timeout
)
3782 /* XXX: need to suppress polling by better using win32 events */
3784 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
3785 ret
|= pe
->func(pe
->opaque
);
3789 WaitObjects
*w
= &wait_objects
;
3791 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
3792 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
3793 if (w
->func
[ret
- WAIT_OBJECT_0
])
3794 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
3796 /* Check for additional signaled events */
3797 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
3799 /* Check if event is signaled */
3800 ret2
= WaitForSingleObject(w
->events
[i
], 0);
3801 if(ret2
== WAIT_OBJECT_0
) {
3803 w
->func
[i
](w
->opaque
[i
]);
3804 } else if (ret2
== WAIT_TIMEOUT
) {
3806 err
= GetLastError();
3807 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
3810 } else if (ret
== WAIT_TIMEOUT
) {
3812 err
= GetLastError();
3813 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
3820 static void host_main_loop_wait(int *timeout
)
3825 void main_loop_wait(int timeout
)
3827 IOHandlerRecord
*ioh
;
3828 fd_set rfds
, wfds
, xfds
;
3832 qemu_bh_update_timeout(&timeout
);
3834 host_main_loop_wait(&timeout
);
3836 /* poll any events */
3837 /* XXX: separate device handlers from system ones */
3842 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3846 (!ioh
->fd_read_poll
||
3847 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
3848 FD_SET(ioh
->fd
, &rfds
);
3852 if (ioh
->fd_write
) {
3853 FD_SET(ioh
->fd
, &wfds
);
3859 tv
.tv_sec
= timeout
/ 1000;
3860 tv
.tv_usec
= (timeout
% 1000) * 1000;
3862 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
3864 qemu_mutex_unlock_iothread();
3865 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
3866 qemu_mutex_lock_iothread();
3868 IOHandlerRecord
**pioh
;
3870 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3871 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
3872 ioh
->fd_read(ioh
->opaque
);
3873 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
3874 FD_CLR(ioh
->fd
, &rfds
);
3876 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
3877 ioh
->fd_write(ioh
->opaque
);
3881 /* remove deleted IO handlers */
3882 pioh
= &first_io_handler
;
3893 slirp_select_poll(&rfds
, &wfds
, &xfds
, (ret
< 0));
3895 /* rearm timer, if not periodic */
3896 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
3897 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
3898 qemu_rearm_alarm_timer(alarm_timer
);
3901 /* vm time timers */
3903 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
3904 qemu_run_timers(&active_timers
[QEMU_CLOCK_VIRTUAL
],
3905 qemu_get_clock(vm_clock
));
3908 /* real time timers */
3909 qemu_run_timers(&active_timers
[QEMU_CLOCK_REALTIME
],
3910 qemu_get_clock(rt_clock
));
3912 qemu_run_timers(&active_timers
[QEMU_CLOCK_HOST
],
3913 qemu_get_clock(host_clock
));
3915 /* Check bottom-halves last in case any of the earlier events triggered
3921 static int qemu_cpu_exec(CPUState
*env
)
3924 #ifdef CONFIG_PROFILER
3928 #ifdef CONFIG_PROFILER
3929 ti
= profile_getclock();
3934 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
3935 env
->icount_decr
.u16
.low
= 0;
3936 env
->icount_extra
= 0;
3937 count
= qemu_next_deadline();
3938 count
= (count
+ (1 << icount_time_shift
) - 1)
3939 >> icount_time_shift
;
3940 qemu_icount
+= count
;
3941 decr
= (count
> 0xffff) ? 0xffff : count
;
3943 env
->icount_decr
.u16
.low
= decr
;
3944 env
->icount_extra
= count
;
3946 ret
= cpu_exec(env
);
3947 #ifdef CONFIG_PROFILER
3948 qemu_time
+= profile_getclock() - ti
;
3951 /* Fold pending instructions back into the
3952 instruction counter, and clear the interrupt flag. */
3953 qemu_icount
-= (env
->icount_decr
.u16
.low
3954 + env
->icount_extra
);
3955 env
->icount_decr
.u32
= 0;
3956 env
->icount_extra
= 0;
3961 static void tcg_cpu_exec(void)
3965 if (next_cpu
== NULL
)
3966 next_cpu
= first_cpu
;
3967 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
3968 CPUState
*env
= cur_cpu
= next_cpu
;
3970 if (timer_alarm_pending
) {
3971 timer_alarm_pending
= 0;
3974 if (cpu_can_run(env
))
3975 ret
= qemu_cpu_exec(env
);
3979 if (ret
== EXCP_DEBUG
) {
3980 gdb_set_stop_cpu(env
);
3981 debug_requested
= 1;
3987 static int cpu_has_work(CPUState
*env
)
3995 if (qemu_cpu_has_work(env
))
4000 static int tcg_has_work(void)
4004 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4005 if (cpu_has_work(env
))
4010 static int qemu_calculate_timeout(void)
4012 #ifndef CONFIG_IOTHREAD
4017 else if (tcg_has_work())
4019 else if (!use_icount
)
4022 /* XXX: use timeout computed from timers */
4025 /* Advance virtual time to the next event. */
4026 if (use_icount
== 1) {
4027 /* When not using an adaptive execution frequency
4028 we tend to get badly out of sync with real time,
4029 so just delay for a reasonable amount of time. */
4032 delta
= cpu_get_icount() - cpu_get_clock();
4035 /* If virtual time is ahead of real time then just
4037 timeout
= (delta
/ 1000000) + 1;
4039 /* Wait for either IO to occur or the next
4041 add
= qemu_next_deadline();
4042 /* We advance the timer before checking for IO.
4043 Limit the amount we advance so that early IO
4044 activity won't get the guest too far ahead. */
4048 add
= (add
+ (1 << icount_time_shift
) - 1)
4049 >> icount_time_shift
;
4051 timeout
= delta
/ 1000000;
4058 #else /* CONFIG_IOTHREAD */
4063 static int vm_can_run(void)
4065 if (powerdown_requested
)
4067 if (reset_requested
)
4069 if (shutdown_requested
)
4071 if (debug_requested
)
4076 qemu_irq qemu_system_powerdown
;
4078 static void main_loop(void)
4082 if (kvm_enabled()) {
4084 cpu_disable_ticks();
4088 #ifdef CONFIG_IOTHREAD
4089 qemu_system_ready
= 1;
4090 qemu_cond_broadcast(&qemu_system_cond
);
4095 #ifdef CONFIG_PROFILER
4098 #ifndef CONFIG_IOTHREAD
4101 #ifdef CONFIG_PROFILER
4102 ti
= profile_getclock();
4104 main_loop_wait(qemu_calculate_timeout());
4105 #ifdef CONFIG_PROFILER
4106 dev_time
+= profile_getclock() - ti
;
4108 } while (vm_can_run());
4110 if (qemu_debug_requested()) {
4111 monitor_protocol_event(QEVENT_DEBUG
, NULL
);
4112 vm_stop(EXCP_DEBUG
);
4114 if (qemu_shutdown_requested()) {
4115 monitor_protocol_event(QEVENT_SHUTDOWN
, NULL
);
4122 if (qemu_reset_requested()) {
4123 monitor_protocol_event(QEVENT_RESET
, NULL
);
4125 qemu_system_reset();
4128 if (qemu_powerdown_requested()) {
4129 monitor_protocol_event(QEVENT_POWERDOWN
, NULL
);
4130 qemu_irq_raise(qemu_system_powerdown
);
4132 if ((r
= qemu_vmstop_requested())) {
4133 monitor_protocol_event(QEVENT_STOP
, NULL
);
4140 static void version(void)
4142 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4145 static void help(int exitcode
)
4147 const char *options_help
=
4148 #define DEF(option, opt_arg, opt_enum, opt_help) \
4150 #define DEFHEADING(text) stringify(text) "\n"
4151 #include "qemu-options.h"
4157 printf("usage: %s [options] [disk_image]\n"
4159 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4162 "During emulation, the following keys are useful:\n"
4163 "ctrl-alt-f toggle full screen\n"
4164 "ctrl-alt-n switch to virtual console 'n'\n"
4165 "ctrl-alt toggle mouse and keyboard grab\n"
4167 "When using -nographic, press 'ctrl-a h' to get some help.\n",
4173 #define HAS_ARG 0x0001
4176 #define DEF(option, opt_arg, opt_enum, opt_help) \
4178 #define DEFHEADING(text)
4179 #include "qemu-options.h"
4185 typedef struct QEMUOption
{
4191 static const QEMUOption qemu_options
[] = {
4192 { "h", 0, QEMU_OPTION_h
},
4193 #define DEF(option, opt_arg, opt_enum, opt_help) \
4194 { option, opt_arg, opt_enum },
4195 #define DEFHEADING(text)
4196 #include "qemu-options.h"
4204 struct soundhw soundhw
[] = {
4205 #ifdef HAS_AUDIO_CHOICE
4206 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4212 { .init_isa
= pcspk_audio_init
}
4219 "Creative Sound Blaster 16",
4222 { .init_isa
= SB16_init
}
4226 #ifdef CONFIG_CS4231A
4232 { .init_isa
= cs4231a_init
}
4240 "Yamaha YMF262 (OPL3)",
4242 "Yamaha YM3812 (OPL2)",
4246 { .init_isa
= Adlib_init
}
4253 "Gravis Ultrasound GF1",
4256 { .init_isa
= GUS_init
}
4263 "Intel 82801AA AC97 Audio",
4266 { .init_pci
= ac97_init
}
4270 #ifdef CONFIG_ES1370
4273 "ENSONIQ AudioPCI ES1370",
4276 { .init_pci
= es1370_init
}
4280 #endif /* HAS_AUDIO_CHOICE */
4282 { NULL
, NULL
, 0, 0, { NULL
} }
4285 static void select_soundhw (const char *optarg
)
4289 if (*optarg
== '?') {
4292 printf ("Valid sound card names (comma separated):\n");
4293 for (c
= soundhw
; c
->name
; ++c
) {
4294 printf ("%-11s %s\n", c
->name
, c
->descr
);
4296 printf ("\n-soundhw all will enable all of the above\n");
4297 exit (*optarg
!= '?');
4305 if (!strcmp (optarg
, "all")) {
4306 for (c
= soundhw
; c
->name
; ++c
) {
4314 e
= strchr (p
, ',');
4315 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4317 for (c
= soundhw
; c
->name
; ++c
) {
4318 if (!strncmp (c
->name
, p
, l
) && !c
->name
[l
]) {
4327 "Unknown sound card name (too big to show)\n");
4330 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4335 p
+= l
+ (e
!= NULL
);
4339 goto show_valid_cards
;
4344 static void select_vgahw (const char *p
)
4349 vga_interface_type
= VGA_NONE
;
4350 if (strstart(p
, "std", &opts
)) {
4351 vga_interface_type
= VGA_STD
;
4352 } else if (strstart(p
, "cirrus", &opts
)) {
4353 vga_interface_type
= VGA_CIRRUS
;
4354 } else if (strstart(p
, "vmware", &opts
)) {
4355 vga_interface_type
= VGA_VMWARE
;
4356 } else if (strstart(p
, "xenfb", &opts
)) {
4357 vga_interface_type
= VGA_XENFB
;
4358 } else if (!strstart(p
, "none", &opts
)) {
4360 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4364 const char *nextopt
;
4366 if (strstart(opts
, ",retrace=", &nextopt
)) {
4368 if (strstart(opts
, "dumb", &nextopt
))
4369 vga_retrace_method
= VGA_RETRACE_DUMB
;
4370 else if (strstart(opts
, "precise", &nextopt
))
4371 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4372 else goto invalid_vga
;
4373 } else goto invalid_vga
;
4379 static int balloon_parse(const char *arg
)
4383 if (strcmp(arg
, "none") == 0) {
4387 if (!strncmp(arg
, "virtio", 6)) {
4388 if (arg
[6] == ',') {
4389 /* have params -> parse them */
4390 opts
= qemu_opts_parse(&qemu_device_opts
, arg
+7, NULL
);
4394 /* create empty opts */
4395 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4397 qemu_opt_set(opts
, "driver", "virtio-balloon-pci");
4406 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4408 exit(STATUS_CONTROL_C_EXIT
);
4413 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4417 if(strlen(str
) != 36)
4420 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4421 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4422 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4428 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4436 static void termsig_handler(int signal
)
4438 qemu_system_shutdown_request();
4441 static void sigchld_handler(int signal
)
4443 waitpid(-1, NULL
, WNOHANG
);
4446 static void sighandler_setup(void)
4448 struct sigaction act
;
4450 memset(&act
, 0, sizeof(act
));
4451 act
.sa_handler
= termsig_handler
;
4452 sigaction(SIGINT
, &act
, NULL
);
4453 sigaction(SIGHUP
, &act
, NULL
);
4454 sigaction(SIGTERM
, &act
, NULL
);
4456 act
.sa_handler
= sigchld_handler
;
4457 act
.sa_flags
= SA_NOCLDSTOP
;
4458 sigaction(SIGCHLD
, &act
, NULL
);
4464 /* Look for support files in the same directory as the executable. */
4465 static char *find_datadir(const char *argv0
)
4471 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
4478 while (p
!= buf
&& *p
!= '\\')
4481 if (access(buf
, R_OK
) == 0) {
4482 return qemu_strdup(buf
);
4488 /* Find a likely location for support files using the location of the binary.
4489 For installed binaries this will be "$bindir/../share/qemu". When
4490 running from the build tree this will be "$bindir/../pc-bios". */
4491 #define SHARE_SUFFIX "/share/qemu"
4492 #define BUILD_SUFFIX "/pc-bios"
4493 static char *find_datadir(const char *argv0
)
4501 #if defined(__linux__)
4504 len
= readlink("/proc/self/exe", buf
, sizeof(buf
) - 1);
4510 #elif defined(__FreeBSD__)
4513 len
= readlink("/proc/curproc/file", buf
, sizeof(buf
) - 1);
4520 /* If we don't have any way of figuring out the actual executable
4521 location then try argv[0]. */
4523 p
= realpath(argv0
, buf
);
4531 max_len
= strlen(dir
) +
4532 MAX(strlen(SHARE_SUFFIX
), strlen(BUILD_SUFFIX
)) + 1;
4533 res
= qemu_mallocz(max_len
);
4534 snprintf(res
, max_len
, "%s%s", dir
, SHARE_SUFFIX
);
4535 if (access(res
, R_OK
)) {
4536 snprintf(res
, max_len
, "%s%s", dir
, BUILD_SUFFIX
);
4537 if (access(res
, R_OK
)) {
4549 char *qemu_find_file(int type
, const char *name
)
4555 /* If name contains path separators then try it as a straight path. */
4556 if ((strchr(name
, '/') || strchr(name
, '\\'))
4557 && access(name
, R_OK
) == 0) {
4558 return qemu_strdup(name
);
4561 case QEMU_FILE_TYPE_BIOS
:
4564 case QEMU_FILE_TYPE_KEYMAP
:
4565 subdir
= "keymaps/";
4570 len
= strlen(data_dir
) + strlen(name
) + strlen(subdir
) + 2;
4571 buf
= qemu_mallocz(len
);
4572 snprintf(buf
, len
, "%s/%s%s", data_dir
, subdir
, name
);
4573 if (access(buf
, R_OK
)) {
4580 static int device_help_func(QemuOpts
*opts
, void *opaque
)
4582 return qdev_device_help(opts
);
4585 static int device_init_func(QemuOpts
*opts
, void *opaque
)
4589 dev
= qdev_device_add(opts
);
4595 static int chardev_init_func(QemuOpts
*opts
, void *opaque
)
4597 CharDriverState
*chr
;
4599 chr
= qemu_chr_open_opts(opts
, NULL
);
4605 static int mon_init_func(QemuOpts
*opts
, void *opaque
)
4607 CharDriverState
*chr
;
4608 const char *chardev
;
4612 mode
= qemu_opt_get(opts
, "mode");
4616 if (strcmp(mode
, "readline") == 0) {
4617 flags
= MONITOR_USE_READLINE
;
4618 } else if (strcmp(mode
, "control") == 0) {
4619 flags
= MONITOR_USE_CONTROL
;
4621 fprintf(stderr
, "unknown monitor mode \"%s\"\n", mode
);
4625 if (qemu_opt_get_bool(opts
, "default", 0))
4626 flags
|= MONITOR_IS_DEFAULT
;
4628 chardev
= qemu_opt_get(opts
, "chardev");
4629 chr
= qemu_chr_find(chardev
);
4631 fprintf(stderr
, "chardev \"%s\" not found\n", chardev
);
4635 monitor_init(chr
, flags
);
4639 static void monitor_parse(const char *optarg
, const char *mode
)
4641 static int monitor_device_index
= 0;
4647 if (strstart(optarg
, "chardev:", &p
)) {
4648 snprintf(label
, sizeof(label
), "%s", p
);
4650 if (monitor_device_index
) {
4651 snprintf(label
, sizeof(label
), "monitor%d",
4652 monitor_device_index
);
4654 snprintf(label
, sizeof(label
), "monitor");
4657 opts
= qemu_chr_parse_compat(label
, optarg
);
4659 fprintf(stderr
, "parse error: %s\n", optarg
);
4664 opts
= qemu_opts_create(&qemu_mon_opts
, label
, 1);
4666 fprintf(stderr
, "duplicate chardev: %s\n", label
);
4669 qemu_opt_set(opts
, "mode", mode
);
4670 qemu_opt_set(opts
, "chardev", label
);
4672 qemu_opt_set(opts
, "default", "on");
4673 monitor_device_index
++;
4676 struct device_config
{
4678 DEV_USB
, /* -usbdevice */
4680 DEV_SERIAL
, /* -serial */
4681 DEV_PARALLEL
, /* -parallel */
4682 DEV_VIRTCON
, /* -virtioconsole */
4683 DEV_DEBUGCON
, /* -debugcon */
4685 const char *cmdline
;
4686 QTAILQ_ENTRY(device_config
) next
;
4688 QTAILQ_HEAD(, device_config
) device_configs
= QTAILQ_HEAD_INITIALIZER(device_configs
);
4690 static void add_device_config(int type
, const char *cmdline
)
4692 struct device_config
*conf
;
4694 conf
= qemu_mallocz(sizeof(*conf
));
4696 conf
->cmdline
= cmdline
;
4697 QTAILQ_INSERT_TAIL(&device_configs
, conf
, next
);
4700 static int foreach_device_config(int type
, int (*func
)(const char *cmdline
))
4702 struct device_config
*conf
;
4705 QTAILQ_FOREACH(conf
, &device_configs
, next
) {
4706 if (conf
->type
!= type
)
4708 rc
= func(conf
->cmdline
);
4715 static int serial_parse(const char *devname
)
4717 static int index
= 0;
4720 if (strcmp(devname
, "none") == 0)
4722 if (index
== MAX_SERIAL_PORTS
) {
4723 fprintf(stderr
, "qemu: too many serial ports\n");
4726 snprintf(label
, sizeof(label
), "serial%d", index
);
4727 serial_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4728 if (!serial_hds
[index
]) {
4729 fprintf(stderr
, "qemu: could not open serial device '%s': %s\n",
4730 devname
, strerror(errno
));
4737 static int parallel_parse(const char *devname
)
4739 static int index
= 0;
4742 if (strcmp(devname
, "none") == 0)
4744 if (index
== MAX_PARALLEL_PORTS
) {
4745 fprintf(stderr
, "qemu: too many parallel ports\n");
4748 snprintf(label
, sizeof(label
), "parallel%d", index
);
4749 parallel_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4750 if (!parallel_hds
[index
]) {
4751 fprintf(stderr
, "qemu: could not open parallel device '%s': %s\n",
4752 devname
, strerror(errno
));
4759 static int virtcon_parse(const char *devname
)
4761 static int index
= 0;
4763 QemuOpts
*bus_opts
, *dev_opts
;
4765 if (strcmp(devname
, "none") == 0)
4767 if (index
== MAX_VIRTIO_CONSOLES
) {
4768 fprintf(stderr
, "qemu: too many virtio consoles\n");
4772 bus_opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4773 qemu_opt_set(bus_opts
, "driver", "virtio-serial");
4775 dev_opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4776 qemu_opt_set(dev_opts
, "driver", "virtconsole");
4778 snprintf(label
, sizeof(label
), "virtcon%d", index
);
4779 virtcon_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4780 if (!virtcon_hds
[index
]) {
4781 fprintf(stderr
, "qemu: could not open virtio console '%s': %s\n",
4782 devname
, strerror(errno
));
4785 qemu_opt_set(dev_opts
, "chardev", label
);
4791 static int debugcon_parse(const char *devname
)
4795 if (!qemu_chr_open("debugcon", devname
, NULL
)) {
4798 opts
= qemu_opts_create(&qemu_device_opts
, "debugcon", 1);
4800 fprintf(stderr
, "qemu: already have a debugcon device\n");
4803 qemu_opt_set(opts
, "driver", "isa-debugcon");
4804 qemu_opt_set(opts
, "chardev", "debugcon");
4808 static const QEMUOption
*lookup_opt(int argc
, char **argv
,
4809 const char **poptarg
, int *poptind
)
4811 const QEMUOption
*popt
;
4812 int optind
= *poptind
;
4813 char *r
= argv
[optind
];
4817 /* Treat --foo the same as -foo. */
4820 popt
= qemu_options
;
4823 fprintf(stderr
, "%s: invalid option -- '%s'\n",
4827 if (!strcmp(popt
->name
, r
+ 1))
4831 if (popt
->flags
& HAS_ARG
) {
4832 if (optind
>= argc
) {
4833 fprintf(stderr
, "%s: option '%s' requires an argument\n",
4837 optarg
= argv
[optind
++];
4848 int main(int argc
, char **argv
, char **envp
)
4850 const char *gdbstub_dev
= NULL
;
4851 uint32_t boot_devices_bitmap
= 0;
4853 int snapshot
, linux_boot
, net_boot
;
4854 const char *initrd_filename
;
4855 const char *kernel_filename
, *kernel_cmdline
;
4856 char boot_devices
[33] = "cad"; /* default to HD->floppy->CD-ROM */
4858 DisplayChangeListener
*dcl
;
4859 int cyls
, heads
, secs
, translation
;
4860 QemuOpts
*hda_opts
= NULL
, *opts
;
4863 const char *loadvm
= NULL
;
4864 QEMUMachine
*machine
;
4865 const char *cpu_model
;
4870 const char *pid_file
= NULL
;
4871 const char *incoming
= NULL
;
4874 struct passwd
*pwd
= NULL
;
4875 const char *chroot_dir
= NULL
;
4876 const char *run_as
= NULL
;
4879 int show_vnc_port
= 0;
4884 qemu_errors_to_file(stderr
);
4885 qemu_cache_utils_init(envp
);
4887 QLIST_INIT (&vm_change_state_head
);
4890 struct sigaction act
;
4891 sigfillset(&act
.sa_mask
);
4893 act
.sa_handler
= SIG_IGN
;
4894 sigaction(SIGPIPE
, &act
, NULL
);
4897 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4898 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4899 QEMU to run on a single CPU */
4904 h
= GetCurrentProcess();
4905 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4906 for(i
= 0; i
< 32; i
++) {
4907 if (mask
& (1 << i
))
4912 SetProcessAffinityMask(h
, mask
);
4918 module_call_init(MODULE_INIT_MACHINE
);
4919 machine
= find_default_machine();
4921 initrd_filename
= NULL
;
4924 kernel_filename
= NULL
;
4925 kernel_cmdline
= "";
4926 cyls
= heads
= secs
= 0;
4927 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4929 for (i
= 0; i
< MAX_NODES
; i
++) {
4931 node_cpumask
[i
] = 0;
4934 assigned_devices_index
= 0;
4942 /* first pass of option parsing */
4944 while (optind
< argc
) {
4945 if (argv
[optind
][0] != '-') {
4950 const QEMUOption
*popt
;
4952 popt
= lookup_opt(argc
, argv
, &optarg
, &optind
);
4953 switch (popt
->index
) {
4954 case QEMU_OPTION_nodefconfig
:
4963 fp
= fopen(CONFIG_QEMU_CONFDIR
"/qemu.conf", "r");
4965 if (qemu_config_parse(fp
) != 0) {
4971 fp
= fopen(CONFIG_QEMU_CONFDIR
"/target-" TARGET_ARCH
".conf", "r");
4973 if (qemu_config_parse(fp
) != 0) {
4979 #if defined(cpudef_setup)
4980 cpudef_setup(); /* parse cpu definitions in target config file */
4983 /* second pass of option parsing */
4988 if (argv
[optind
][0] != '-') {
4989 hda_opts
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
4991 const QEMUOption
*popt
;
4993 popt
= lookup_opt(argc
, argv
, &optarg
, &optind
);
4994 switch(popt
->index
) {
4996 machine
= find_machine(optarg
);
4999 printf("Supported machines are:\n");
5000 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5002 printf("%-10s %s (alias of %s)\n",
5003 m
->alias
, m
->desc
, m
->name
);
5004 printf("%-10s %s%s\n",
5006 m
->is_default
? " (default)" : "");
5008 exit(*optarg
!= '?');
5011 case QEMU_OPTION_cpu
:
5012 /* hw initialization will check this */
5013 if (*optarg
== '?') {
5014 /* XXX: implement xxx_cpu_list for targets that still miss it */
5015 #if defined(cpu_list_id)
5016 cpu_list_id(stdout
, &fprintf
, optarg
);
5017 #elif defined(cpu_list)
5018 cpu_list(stdout
, &fprintf
); /* deprecated */
5025 case QEMU_OPTION_initrd
:
5026 initrd_filename
= optarg
;
5028 case QEMU_OPTION_hda
:
5030 hda_opts
= drive_add(optarg
, HD_ALIAS
, 0);
5032 hda_opts
= drive_add(optarg
, HD_ALIAS
5033 ",cyls=%d,heads=%d,secs=%d%s",
5034 0, cyls
, heads
, secs
,
5035 translation
== BIOS_ATA_TRANSLATION_LBA
?
5037 translation
== BIOS_ATA_TRANSLATION_NONE
?
5038 ",trans=none" : "");
5040 case QEMU_OPTION_hdb
:
5041 case QEMU_OPTION_hdc
:
5042 case QEMU_OPTION_hdd
:
5043 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
5045 case QEMU_OPTION_drive
:
5046 drive_add(NULL
, "%s", optarg
);
5048 case QEMU_OPTION_set
:
5049 if (qemu_set_option(optarg
) != 0)
5052 case QEMU_OPTION_global
:
5053 if (qemu_global_option(optarg
) != 0)
5056 case QEMU_OPTION_mtdblock
:
5057 drive_add(optarg
, MTD_ALIAS
);
5059 case QEMU_OPTION_sd
:
5060 drive_add(optarg
, SD_ALIAS
);
5062 case QEMU_OPTION_pflash
:
5063 drive_add(optarg
, PFLASH_ALIAS
);
5065 case QEMU_OPTION_snapshot
:
5068 case QEMU_OPTION_hdachs
:
5072 cyls
= strtol(p
, (char **)&p
, 0);
5073 if (cyls
< 1 || cyls
> 16383)
5078 heads
= strtol(p
, (char **)&p
, 0);
5079 if (heads
< 1 || heads
> 16)
5084 secs
= strtol(p
, (char **)&p
, 0);
5085 if (secs
< 1 || secs
> 63)
5089 if (!strcmp(p
, "none"))
5090 translation
= BIOS_ATA_TRANSLATION_NONE
;
5091 else if (!strcmp(p
, "lba"))
5092 translation
= BIOS_ATA_TRANSLATION_LBA
;
5093 else if (!strcmp(p
, "auto"))
5094 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5097 } else if (*p
!= '\0') {
5099 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5102 if (hda_opts
!= NULL
) {
5104 snprintf(num
, sizeof(num
), "%d", cyls
);
5105 qemu_opt_set(hda_opts
, "cyls", num
);
5106 snprintf(num
, sizeof(num
), "%d", heads
);
5107 qemu_opt_set(hda_opts
, "heads", num
);
5108 snprintf(num
, sizeof(num
), "%d", secs
);
5109 qemu_opt_set(hda_opts
, "secs", num
);
5110 if (translation
== BIOS_ATA_TRANSLATION_LBA
)
5111 qemu_opt_set(hda_opts
, "trans", "lba");
5112 if (translation
== BIOS_ATA_TRANSLATION_NONE
)
5113 qemu_opt_set(hda_opts
, "trans", "none");
5117 case QEMU_OPTION_numa
:
5118 if (nb_numa_nodes
>= MAX_NODES
) {
5119 fprintf(stderr
, "qemu: too many NUMA nodes\n");
5124 case QEMU_OPTION_nographic
:
5125 display_type
= DT_NOGRAPHIC
;
5127 #ifdef CONFIG_CURSES
5128 case QEMU_OPTION_curses
:
5129 display_type
= DT_CURSES
;
5132 case QEMU_OPTION_portrait
:
5135 case QEMU_OPTION_kernel
:
5136 kernel_filename
= optarg
;
5138 case QEMU_OPTION_append
:
5139 kernel_cmdline
= optarg
;
5141 case QEMU_OPTION_cdrom
:
5142 drive_add(optarg
, CDROM_ALIAS
);
5144 case QEMU_OPTION_boot
:
5146 static const char * const params
[] = {
5147 "order", "once", "menu", NULL
5149 char buf
[sizeof(boot_devices
)];
5150 char *standard_boot_devices
;
5153 if (!strchr(optarg
, '=')) {
5155 pstrcpy(buf
, sizeof(buf
), optarg
);
5156 } else if (check_params(buf
, sizeof(buf
), params
, optarg
) < 0) {
5158 "qemu: unknown boot parameter '%s' in '%s'\n",
5164 get_param_value(buf
, sizeof(buf
), "order", optarg
)) {
5165 boot_devices_bitmap
= parse_bootdevices(buf
);
5166 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5169 if (get_param_value(buf
, sizeof(buf
),
5171 boot_devices_bitmap
|= parse_bootdevices(buf
);
5172 standard_boot_devices
= qemu_strdup(boot_devices
);
5173 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5174 qemu_register_reset(restore_boot_devices
,
5175 standard_boot_devices
);
5177 if (get_param_value(buf
, sizeof(buf
),
5179 if (!strcmp(buf
, "on")) {
5181 } else if (!strcmp(buf
, "off")) {
5185 "qemu: invalid option value '%s'\n",
5193 case QEMU_OPTION_fda
:
5194 case QEMU_OPTION_fdb
:
5195 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
5198 case QEMU_OPTION_no_fd_bootchk
:
5202 case QEMU_OPTION_netdev
:
5203 if (net_client_parse(&qemu_netdev_opts
, optarg
) == -1) {
5207 case QEMU_OPTION_net
:
5208 if (net_client_parse(&qemu_net_opts
, optarg
) == -1) {
5213 case QEMU_OPTION_tftp
:
5214 legacy_tftp_prefix
= optarg
;
5216 case QEMU_OPTION_bootp
:
5217 legacy_bootp_filename
= optarg
;
5220 case QEMU_OPTION_smb
:
5221 if (net_slirp_smb(optarg
) < 0)
5225 case QEMU_OPTION_redir
:
5226 if (net_slirp_redir(optarg
) < 0)
5230 case QEMU_OPTION_bt
:
5231 add_device_config(DEV_BT
, optarg
);
5234 case QEMU_OPTION_audio_help
:
5238 case QEMU_OPTION_soundhw
:
5239 select_soundhw (optarg
);
5245 case QEMU_OPTION_version
:
5249 case QEMU_OPTION_m
: {
5253 value
= strtoul(optarg
, &ptr
, 10);
5255 case 0: case 'M': case 'm':
5262 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5266 /* On 32-bit hosts, QEMU is limited by virtual address space */
5267 if (value
> (2047 << 20) && HOST_LONG_BITS
== 32) {
5268 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5271 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5272 fprintf(stderr
, "qemu: ram size too large\n");
5281 const CPULogItem
*item
;
5283 mask
= cpu_str_to_log_mask(optarg
);
5285 printf("Log items (comma separated):\n");
5286 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5287 printf("%-10s %s\n", item
->name
, item
->help
);
5295 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5297 case QEMU_OPTION_gdb
:
5298 gdbstub_dev
= optarg
;
5303 case QEMU_OPTION_bios
:
5306 case QEMU_OPTION_singlestep
:
5313 keyboard_layout
= optarg
;
5315 case QEMU_OPTION_localtime
:
5318 case QEMU_OPTION_vga
:
5319 select_vgahw (optarg
);
5321 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5327 w
= strtol(p
, (char **)&p
, 10);
5330 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5336 h
= strtol(p
, (char **)&p
, 10);
5341 depth
= strtol(p
, (char **)&p
, 10);
5342 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5343 depth
!= 24 && depth
!= 32)
5345 } else if (*p
== '\0') {
5346 depth
= graphic_depth
;
5353 graphic_depth
= depth
;
5357 case QEMU_OPTION_echr
:
5360 term_escape_char
= strtol(optarg
, &r
, 0);
5362 printf("Bad argument to echr\n");
5365 case QEMU_OPTION_monitor
:
5366 monitor_parse(optarg
, "readline");
5367 default_monitor
= 0;
5369 case QEMU_OPTION_qmp
:
5370 monitor_parse(optarg
, "control");
5371 default_monitor
= 0;
5373 case QEMU_OPTION_mon
:
5374 opts
= qemu_opts_parse(&qemu_mon_opts
, optarg
, "chardev");
5376 fprintf(stderr
, "parse error: %s\n", optarg
);
5379 default_monitor
= 0;
5381 case QEMU_OPTION_chardev
:
5382 opts
= qemu_opts_parse(&qemu_chardev_opts
, optarg
, "backend");
5384 fprintf(stderr
, "parse error: %s\n", optarg
);
5388 case QEMU_OPTION_serial
:
5389 add_device_config(DEV_SERIAL
, optarg
);
5392 case QEMU_OPTION_watchdog
:
5395 "qemu: only one watchdog option may be given\n");
5400 case QEMU_OPTION_watchdog_action
:
5401 if (select_watchdog_action(optarg
) == -1) {
5402 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5406 case QEMU_OPTION_virtiocon
:
5407 add_device_config(DEV_VIRTCON
, optarg
);
5408 default_virtcon
= 0;
5410 case QEMU_OPTION_parallel
:
5411 add_device_config(DEV_PARALLEL
, optarg
);
5412 default_parallel
= 0;
5414 case QEMU_OPTION_debugcon
:
5415 add_device_config(DEV_DEBUGCON
, optarg
);
5417 case QEMU_OPTION_loadvm
:
5420 case QEMU_OPTION_full_screen
:
5424 case QEMU_OPTION_no_frame
:
5427 case QEMU_OPTION_alt_grab
:
5430 case QEMU_OPTION_ctrl_grab
:
5433 case QEMU_OPTION_no_quit
:
5436 case QEMU_OPTION_sdl
:
5437 display_type
= DT_SDL
;
5440 case QEMU_OPTION_pidfile
:
5444 case QEMU_OPTION_win2k_hack
:
5445 win2k_install_hack
= 1;
5447 case QEMU_OPTION_rtc_td_hack
:
5450 case QEMU_OPTION_acpitable
:
5451 if(acpi_table_add(optarg
) < 0) {
5452 fprintf(stderr
, "Wrong acpi table provided\n");
5456 case QEMU_OPTION_smbios
:
5457 if(smbios_entry_add(optarg
) < 0) {
5458 fprintf(stderr
, "Wrong smbios provided\n");
5465 case QEMU_OPTION_enable_kvm
:
5469 case QEMU_OPTION_no_kvm
:
5472 case QEMU_OPTION_no_kvm_irqchip
: {
5477 case QEMU_OPTION_no_kvm_pit
: {
5481 case QEMU_OPTION_no_kvm_pit_reinjection
: {
5482 kvm_pit_reinject
= 0;
5485 case QEMU_OPTION_enable_nesting
: {
5489 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5490 case QEMU_OPTION_pcidevice
:
5491 if (assigned_devices_index
>= MAX_DEV_ASSIGN_CMDLINE
) {
5492 fprintf(stderr
, "Too many assigned devices\n");
5495 assigned_devices
[assigned_devices_index
] = optarg
;
5496 assigned_devices_index
++;
5500 case QEMU_OPTION_usb
:
5503 case QEMU_OPTION_usbdevice
:
5505 add_device_config(DEV_USB
, optarg
);
5507 case QEMU_OPTION_device
:
5508 if (!qemu_opts_parse(&qemu_device_opts
, optarg
, "driver")) {
5512 case QEMU_OPTION_smp
:
5515 fprintf(stderr
, "Invalid number of CPUs\n");
5518 if (max_cpus
< smp_cpus
) {
5519 fprintf(stderr
, "maxcpus must be equal to or greater than "
5523 if (max_cpus
> 255) {
5524 fprintf(stderr
, "Unsupported number of maxcpus\n");
5528 case QEMU_OPTION_vnc
:
5529 display_type
= DT_VNC
;
5530 vnc_display
= optarg
;
5533 case QEMU_OPTION_no_acpi
:
5536 case QEMU_OPTION_no_hpet
:
5539 case QEMU_OPTION_balloon
:
5540 if (balloon_parse(optarg
) < 0) {
5541 fprintf(stderr
, "Unknown -balloon argument %s\n", optarg
);
5546 case QEMU_OPTION_no_reboot
:
5549 case QEMU_OPTION_no_shutdown
:
5552 case QEMU_OPTION_show_cursor
:
5555 case QEMU_OPTION_uuid
:
5556 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5557 fprintf(stderr
, "Fail to parse UUID string."
5558 " Wrong format.\n");
5563 case QEMU_OPTION_daemonize
:
5567 case QEMU_OPTION_option_rom
:
5568 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5569 fprintf(stderr
, "Too many option ROMs\n");
5572 option_rom
[nb_option_roms
] = optarg
;
5575 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5576 case QEMU_OPTION_semihosting
:
5577 semihosting_enabled
= 1;
5580 case QEMU_OPTION_tdf
:
5583 case QEMU_OPTION_kvm_shadow_memory
:
5584 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
5586 case QEMU_OPTION_mempath
:
5590 case QEMU_OPTION_mem_prealloc
:
5591 mem_prealloc
= !mem_prealloc
;
5594 case QEMU_OPTION_name
:
5595 qemu_name
= qemu_strdup(optarg
);
5597 char *p
= strchr(qemu_name
, ',');
5600 if (strncmp(p
, "process=", 8)) {
5601 fprintf(stderr
, "Unknown subargument %s to -name", p
);
5609 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5610 case QEMU_OPTION_prom_env
:
5611 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5612 fprintf(stderr
, "Too many prom variables\n");
5615 prom_envs
[nb_prom_envs
] = optarg
;
5620 case QEMU_OPTION_old_param
:
5624 case QEMU_OPTION_clock
:
5625 configure_alarms(optarg
);
5627 case QEMU_OPTION_startdate
:
5628 configure_rtc_date_offset(optarg
, 1);
5630 case QEMU_OPTION_rtc
:
5631 opts
= qemu_opts_parse(&qemu_rtc_opts
, optarg
, NULL
);
5633 fprintf(stderr
, "parse error: %s\n", optarg
);
5636 configure_rtc(opts
);
5638 case QEMU_OPTION_tb_size
:
5639 tb_size
= strtol(optarg
, NULL
, 0);
5643 case QEMU_OPTION_icount
:
5645 if (strcmp(optarg
, "auto") == 0) {
5646 icount_time_shift
= -1;
5648 icount_time_shift
= strtol(optarg
, NULL
, 0);
5651 case QEMU_OPTION_incoming
:
5654 case QEMU_OPTION_nodefaults
:
5656 default_parallel
= 0;
5657 default_virtcon
= 0;
5658 default_monitor
= 0;
5666 case QEMU_OPTION_chroot
:
5667 chroot_dir
= optarg
;
5669 case QEMU_OPTION_runas
:
5672 case QEMU_OPTION_nvram
:
5677 case QEMU_OPTION_xen_domid
:
5678 xen_domid
= atoi(optarg
);
5680 case QEMU_OPTION_xen_create
:
5681 xen_mode
= XEN_CREATE
;
5683 case QEMU_OPTION_xen_attach
:
5684 xen_mode
= XEN_ATTACH
;
5687 case QEMU_OPTION_readconfig
:
5690 fp
= fopen(optarg
, "r");
5692 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5695 if (qemu_config_parse(fp
) != 0) {
5701 case QEMU_OPTION_writeconfig
:
5704 if (strcmp(optarg
, "-") == 0) {
5707 fp
= fopen(optarg
, "w");
5709 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5713 qemu_config_write(fp
);
5721 /* If no data_dir is specified then try to find it relative to the
5724 data_dir
= find_datadir(argv
[0]);
5726 /* If all else fails use the install patch specified when building. */
5728 data_dir
= CONFIG_QEMU_SHAREDIR
;
5732 * Default to max_cpus = smp_cpus, in case the user doesn't
5733 * specify a max_cpus value.
5736 max_cpus
= smp_cpus
;
5738 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5739 if (smp_cpus
> machine
->max_cpus
) {
5740 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5741 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5746 qemu_opts_foreach(&qemu_device_opts
, default_driver_check
, NULL
, 0);
5747 qemu_opts_foreach(&qemu_global_opts
, default_driver_check
, NULL
, 0);
5749 if (machine
->no_serial
) {
5752 if (machine
->no_parallel
) {
5753 default_parallel
= 0;
5755 if (!machine
->use_virtcon
) {
5756 default_virtcon
= 0;
5758 if (machine
->no_vga
) {
5761 if (machine
->no_floppy
) {
5764 if (machine
->no_cdrom
) {
5767 if (machine
->no_sdcard
) {
5771 if (display_type
== DT_NOGRAPHIC
) {
5772 if (default_parallel
)
5773 add_device_config(DEV_PARALLEL
, "null");
5774 if (default_serial
&& default_monitor
) {
5775 add_device_config(DEV_SERIAL
, "mon:stdio");
5776 } else if (default_virtcon
&& default_monitor
) {
5777 add_device_config(DEV_VIRTCON
, "mon:stdio");
5780 add_device_config(DEV_SERIAL
, "stdio");
5781 if (default_virtcon
)
5782 add_device_config(DEV_VIRTCON
, "stdio");
5783 if (default_monitor
)
5784 monitor_parse("stdio", "readline");
5788 add_device_config(DEV_SERIAL
, "vc:80Cx24C");
5789 if (default_parallel
)
5790 add_device_config(DEV_PARALLEL
, "vc:80Cx24C");
5791 if (default_monitor
)
5792 monitor_parse("vc:80Cx24C", "readline");
5793 if (default_virtcon
)
5794 add_device_config(DEV_VIRTCON
, "vc:80Cx24C");
5797 vga_interface_type
= VGA_CIRRUS
;
5799 if (qemu_opts_foreach(&qemu_chardev_opts
, chardev_init_func
, NULL
, 1) != 0)
5806 if (pipe(fds
) == -1)
5817 len
= read(fds
[0], &status
, 1);
5818 if (len
== -1 && (errno
== EINTR
))
5823 else if (status
== 1) {
5824 fprintf(stderr
, "Could not acquire pidfile: %s\n", strerror(errno
));
5832 qemu_set_cloexec(fds
[1]);
5844 signal(SIGTSTP
, SIG_IGN
);
5845 signal(SIGTTOU
, SIG_IGN
);
5846 signal(SIGTTIN
, SIG_IGN
);
5850 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5854 if (write(fds
[1], &status
, 1) != 1) {
5855 perror("daemonize. Writing to pipe\n");
5859 fprintf(stderr
, "Could not acquire pid file: %s\n", strerror(errno
));
5863 if (kvm_enabled()) {
5866 ret
= kvm_init(smp_cpus
);
5868 #if defined(KVM_UPSTREAM) || defined(CONFIG_NO_CPU_EMULATION)
5869 fprintf(stderr
, "failed to initialize KVM\n");
5873 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
5879 if (qemu_init_main_loop()) {
5880 fprintf(stderr
, "qemu_init_main_loop failed\n");
5883 linux_boot
= (kernel_filename
!= NULL
);
5885 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5886 fprintf(stderr
, "-append only allowed with -kernel option\n");
5890 if (!linux_boot
&& initrd_filename
!= NULL
) {
5891 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5896 /* Win32 doesn't support line-buffering and requires size >= 2 */
5897 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5900 if (init_timer_alarm() < 0) {
5901 fprintf(stderr
, "could not initialize alarm timer\n");
5904 if (use_icount
&& icount_time_shift
< 0) {
5906 /* 125MIPS seems a reasonable initial guess at the guest speed.
5907 It will be corrected fairly quickly anyway. */
5908 icount_time_shift
= 3;
5909 init_icount_adjust();
5916 if (net_init_clients() < 0) {
5920 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5921 net_set_boot_mask(net_boot
);
5923 /* init the bluetooth world */
5924 if (foreach_device_config(DEV_BT
, bt_parse
))
5927 /* init the memory */
5929 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5931 /* init the dynamic translator */
5932 cpu_exec_init_all(tb_size
* 1024 * 1024);
5934 bdrv_init_with_whitelist();
5938 if (default_cdrom
) {
5939 /* we always create the cdrom drive, even if no disk is there */
5940 drive_add(NULL
, CDROM_ALIAS
);
5943 if (default_floppy
) {
5944 /* we always create at least one floppy */
5945 drive_add(NULL
, FD_ALIAS
, 0);
5948 if (default_sdcard
) {
5949 /* we always create one sd slot, even if no card is in it */
5950 drive_add(NULL
, SD_ALIAS
);
5953 /* open the virtual block devices */
5955 qemu_opts_foreach(&qemu_drive_opts
, drive_enable_snapshot
, NULL
, 0);
5956 if (qemu_opts_foreach(&qemu_drive_opts
, drive_init_func
, machine
, 1) != 0)
5959 vmstate_register(0, &vmstate_timers
,&timers_state
);
5960 register_savevm_live("ram", 0, 3, NULL
, ram_save_live
, NULL
,
5963 if (nb_numa_nodes
> 0) {
5966 if (nb_numa_nodes
> smp_cpus
) {
5967 nb_numa_nodes
= smp_cpus
;
5970 /* If no memory size if given for any node, assume the default case
5971 * and distribute the available memory equally across all nodes
5973 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5974 if (node_mem
[i
] != 0)
5977 if (i
== nb_numa_nodes
) {
5978 uint64_t usedmem
= 0;
5980 /* On Linux, the each node's border has to be 8MB aligned,
5981 * the final node gets the rest.
5983 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
5984 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
5985 usedmem
+= node_mem
[i
];
5987 node_mem
[i
] = ram_size
- usedmem
;
5990 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5991 if (node_cpumask
[i
] != 0)
5994 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5995 * must cope with this anyway, because there are BIOSes out there in
5996 * real machines which also use this scheme.
5998 if (i
== nb_numa_nodes
) {
5999 for (i
= 0; i
< smp_cpus
; i
++) {
6000 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
6005 if (foreach_device_config(DEV_SERIAL
, serial_parse
) < 0)
6007 if (foreach_device_config(DEV_PARALLEL
, parallel_parse
) < 0)
6009 if (foreach_device_config(DEV_VIRTCON
, virtcon_parse
) < 0)
6011 if (foreach_device_config(DEV_DEBUGCON
, debugcon_parse
) < 0)
6014 module_call_init(MODULE_INIT_DEVICE
);
6016 if (qemu_opts_foreach(&qemu_device_opts
, device_help_func
, NULL
, 0) != 0)
6020 i
= select_watchdog(watchdog
);
6022 exit (i
== 1 ? 1 : 0);
6025 if (machine
->compat_props
) {
6026 qdev_prop_register_global_list(machine
->compat_props
);
6030 machine
->init(ram_size
, boot_devices
,
6031 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
6035 /* must be after terminal init, SDL library changes signal handlers */
6039 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
6040 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6041 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
6047 current_machine
= machine
;
6049 /* init USB devices */
6051 if (foreach_device_config(DEV_USB
, usb_parse
) < 0)
6055 /* init generic devices */
6056 if (qemu_opts_foreach(&qemu_device_opts
, device_init_func
, NULL
, 1) != 0)
6059 net_check_clients();
6061 /* just use the first displaystate for the moment */
6062 ds
= get_displaystate();
6064 if (display_type
== DT_DEFAULT
) {
6065 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6066 display_type
= DT_SDL
;
6068 display_type
= DT_VNC
;
6069 vnc_display
= "localhost:0,to=99";
6075 switch (display_type
) {
6078 #if defined(CONFIG_CURSES)
6080 curses_display_init(ds
, full_screen
);
6083 #if defined(CONFIG_SDL)
6085 sdl_display_init(ds
, full_screen
, no_frame
);
6087 #elif defined(CONFIG_COCOA)
6089 cocoa_display_init(ds
, full_screen
);
6093 vnc_display_init(ds
);
6094 if (vnc_display_open(ds
, vnc_display
) < 0)
6097 if (show_vnc_port
) {
6098 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
6106 dcl
= ds
->listeners
;
6107 while (dcl
!= NULL
) {
6108 if (dcl
->dpy_refresh
!= NULL
) {
6109 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
6110 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
6115 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
6116 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
6117 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
6120 text_consoles_set_display(ds
);
6122 if (qemu_opts_foreach(&qemu_mon_opts
, mon_init_func
, NULL
, 1) != 0)
6125 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
6126 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
6131 qdev_machine_creation_done();
6133 if (rom_load_all() != 0) {
6134 fprintf(stderr
, "rom loading failed\n");
6138 qemu_system_reset();
6140 if (load_vmstate(cur_mon
, loadvm
) < 0) {
6146 qemu_start_incoming_migration(incoming
);
6147 } else if (autostart
) {
6157 len
= write(fds
[1], &status
, 1);
6158 if (len
== -1 && (errno
== EINTR
))
6165 perror("not able to chdir to /");
6168 TFR(fd
= qemu_open("/dev/null", O_RDWR
));
6174 pwd
= getpwnam(run_as
);
6176 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
6182 if (chroot(chroot_dir
) < 0) {
6183 fprintf(stderr
, "chroot failed\n");
6187 perror("not able to chdir to /");
6193 if (setgid(pwd
->pw_gid
) < 0) {
6194 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
6197 if (setuid(pwd
->pw_uid
) < 0) {
6198 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
6201 if (setuid(0) != -1) {
6202 fprintf(stderr
, "Dropping privileges failed\n");