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"
163 #include "exec-all.h"
165 #include "qemu_socket.h"
167 #include "slirp/libslirp.h"
169 #include "qemu-queue.h"
172 //#define DEBUG_SLIRP
174 #define DEFAULT_RAM_SIZE 128
176 #define MAX_VIRTIO_CONSOLES 1
178 static const char *data_dir
;
179 const char *bios_name
= NULL
;
180 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
181 to store the VM snapshots */
182 struct drivelist drives
= QTAILQ_HEAD_INITIALIZER(drives
);
183 struct driveoptlist driveopts
= QTAILQ_HEAD_INITIALIZER(driveopts
);
184 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
185 DisplayType display_type
= DT_DEFAULT
;
186 const char* keyboard_layout
= NULL
;
188 const char *mem_path
= NULL
;
190 int mem_prealloc
= 0; /* force preallocation of physical target memory */
193 NICInfo nd_table
[MAX_NICS
];
196 static int rtc_utc
= 1;
197 static int rtc_date_offset
= -1; /* -1 means no change */
198 QEMUClock
*rtc_clock
;
199 int vga_interface_type
= VGA_NONE
;
201 int graphic_width
= 1024;
202 int graphic_height
= 768;
203 int graphic_depth
= 8;
205 int graphic_width
= 800;
206 int graphic_height
= 600;
207 int graphic_depth
= 15;
209 static int full_screen
= 0;
211 static int no_frame
= 0;
214 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
215 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
216 CharDriverState
*virtcon_hds
[MAX_VIRTIO_CONSOLES
];
218 int win2k_install_hack
= 0;
227 const char *vnc_display
;
228 int acpi_enabled
= 1;
234 int graphic_rotate
= 0;
235 uint8_t irq0override
= 1;
239 const char *watchdog
;
240 const char *option_rom
[MAX_OPTION_ROMS
];
242 int semihosting_enabled
= 0;
246 const char *qemu_name
;
249 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
250 unsigned int nb_prom_envs
= 0;
251 const char *prom_envs
[MAX_PROM_ENVS
];
256 uint64_t node_mem
[MAX_NODES
];
257 uint64_t node_cpumask
[MAX_NODES
];
259 static CPUState
*cur_cpu
;
260 static CPUState
*next_cpu
;
261 /* Conversion factor from emulated instructions to virtual clock ticks. */
262 static int icount_time_shift
;
263 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
264 #define MAX_ICOUNT_SHIFT 10
265 /* Compensate for varying guest execution speed. */
266 static int64_t qemu_icount_bias
;
267 static QEMUTimer
*icount_rt_timer
;
268 static QEMUTimer
*icount_vm_timer
;
269 static QEMUTimer
*nographic_timer
;
271 uint8_t qemu_uuid
[16];
273 static QEMUBootSetHandler
*boot_set_handler
;
274 static void *boot_set_opaque
;
277 #define SIG_IPI (SIGRTMIN+4)
279 #define SIG_IPI SIGUSR1
282 static int default_serial
= 1;
283 static int default_parallel
= 1;
284 static int default_virtcon
= 1;
285 static int default_monitor
= 1;
286 static int default_vga
= 1;
287 static int default_floppy
= 1;
288 static int default_cdrom
= 1;
289 static int default_sdcard
= 1;
295 { .driver
= "isa-serial", .flag
= &default_serial
},
296 { .driver
= "isa-parallel", .flag
= &default_parallel
},
297 { .driver
= "isa-fdc", .flag
= &default_floppy
},
298 { .driver
= "ide-drive", .flag
= &default_cdrom
},
299 { .driver
= "virtio-serial-pci", .flag
= &default_virtcon
},
300 { .driver
= "virtio-serial-s390", .flag
= &default_virtcon
},
301 { .driver
= "virtio-serial", .flag
= &default_virtcon
},
302 { .driver
= "VGA", .flag
= &default_vga
},
303 { .driver
= "cirrus-vga", .flag
= &default_vga
},
304 { .driver
= "vmware-svga", .flag
= &default_vga
},
307 static int default_driver_check(QemuOpts
*opts
, void *opaque
)
309 const char *driver
= qemu_opt_get(opts
, "driver");
314 for (i
= 0; i
< ARRAY_SIZE(default_list
); i
++) {
315 if (strcmp(default_list
[i
].driver
, driver
) != 0)
317 *(default_list
[i
].flag
) = 0;
322 /***********************************************************/
323 /* x86 ISA bus support */
325 target_phys_addr_t isa_mem_base
= 0;
328 /***********************************************************/
329 void hw_error(const char *fmt
, ...)
335 fprintf(stderr
, "qemu: hardware error: ");
336 vfprintf(stderr
, fmt
, ap
);
337 fprintf(stderr
, "\n");
338 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
339 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
341 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
343 cpu_dump_state(env
, stderr
, fprintf
, 0);
350 static void set_proc_name(const char *s
)
352 #if defined(__linux__) && defined(PR_SET_NAME)
356 name
[sizeof(name
) - 1] = 0;
357 strncpy(name
, s
, sizeof(name
));
358 /* Could rewrite argv[0] too, but that's a bit more complicated.
359 This simple way is enough for `top'. */
360 prctl(PR_SET_NAME
, name
);
367 static QEMUBalloonEvent
*qemu_balloon_event
;
368 void *qemu_balloon_event_opaque
;
370 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
372 qemu_balloon_event
= func
;
373 qemu_balloon_event_opaque
= opaque
;
376 int qemu_balloon(ram_addr_t target
, MonitorCompletion cb
, void *opaque
)
378 if (qemu_balloon_event
) {
379 qemu_balloon_event(qemu_balloon_event_opaque
, target
, cb
, opaque
);
386 int qemu_balloon_status(MonitorCompletion cb
, void *opaque
)
388 if (qemu_balloon_event
) {
389 qemu_balloon_event(qemu_balloon_event_opaque
, 0, cb
, opaque
);
397 /***********************************************************/
398 /* real time host monotonic timer */
400 /* compute with 96 bit intermediate result: (a*b)/c */
401 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
406 #ifdef HOST_WORDS_BIGENDIAN
416 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
417 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
420 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
424 static int64_t get_clock_realtime(void)
428 gettimeofday(&tv
, NULL
);
429 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
434 static int64_t clock_freq
;
436 static void init_get_clock(void)
440 ret
= QueryPerformanceFrequency(&freq
);
442 fprintf(stderr
, "Could not calibrate ticks\n");
445 clock_freq
= freq
.QuadPart
;
448 static int64_t get_clock(void)
451 QueryPerformanceCounter(&ti
);
452 return muldiv64(ti
.QuadPart
, get_ticks_per_sec(), clock_freq
);
457 static int use_rt_clock
;
459 static void init_get_clock(void)
462 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
463 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
466 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
473 static int64_t get_clock(void)
475 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
476 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
479 clock_gettime(CLOCK_MONOTONIC
, &ts
);
480 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
484 /* XXX: using gettimeofday leads to problems if the date
485 changes, so it should be avoided. */
486 return get_clock_realtime();
491 /* Return the virtual CPU time, based on the instruction counter. */
492 static int64_t cpu_get_icount(void)
495 CPUState
*env
= cpu_single_env
;;
496 icount
= qemu_icount
;
499 fprintf(stderr
, "Bad clock read\n");
500 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
502 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
505 /***********************************************************/
506 /* guest cycle counter */
508 typedef struct TimersState
{
509 int64_t cpu_ticks_prev
;
510 int64_t cpu_ticks_offset
;
511 int64_t cpu_clock_offset
;
512 int32_t cpu_ticks_enabled
;
516 TimersState timers_state
;
518 /* return the host CPU cycle counter and handle stop/restart */
519 int64_t cpu_get_ticks(void)
522 return cpu_get_icount();
524 if (!timers_state
.cpu_ticks_enabled
) {
525 return timers_state
.cpu_ticks_offset
;
528 ticks
= cpu_get_real_ticks();
529 if (timers_state
.cpu_ticks_prev
> ticks
) {
530 /* Note: non increasing ticks may happen if the host uses
532 timers_state
.cpu_ticks_offset
+= timers_state
.cpu_ticks_prev
- ticks
;
534 timers_state
.cpu_ticks_prev
= ticks
;
535 return ticks
+ timers_state
.cpu_ticks_offset
;
539 /* return the host CPU monotonic timer and handle stop/restart */
540 static int64_t cpu_get_clock(void)
543 if (!timers_state
.cpu_ticks_enabled
) {
544 return timers_state
.cpu_clock_offset
;
547 return ti
+ timers_state
.cpu_clock_offset
;
551 /* enable cpu_get_ticks() */
552 void cpu_enable_ticks(void)
554 if (!timers_state
.cpu_ticks_enabled
) {
555 timers_state
.cpu_ticks_offset
-= cpu_get_real_ticks();
556 timers_state
.cpu_clock_offset
-= get_clock();
557 timers_state
.cpu_ticks_enabled
= 1;
561 /* disable cpu_get_ticks() : the clock is stopped. You must not call
562 cpu_get_ticks() after that. */
563 void cpu_disable_ticks(void)
565 if (timers_state
.cpu_ticks_enabled
) {
566 timers_state
.cpu_ticks_offset
= cpu_get_ticks();
567 timers_state
.cpu_clock_offset
= cpu_get_clock();
568 timers_state
.cpu_ticks_enabled
= 0;
572 /***********************************************************/
575 #define QEMU_CLOCK_REALTIME 0
576 #define QEMU_CLOCK_VIRTUAL 1
577 #define QEMU_CLOCK_HOST 2
582 /* XXX: add frequency */
590 struct QEMUTimer
*next
;
593 struct qemu_alarm_timer
{
595 int (*start
)(struct qemu_alarm_timer
*t
);
596 void (*stop
)(struct qemu_alarm_timer
*t
);
597 void (*rearm
)(struct qemu_alarm_timer
*t
);
604 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
609 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
611 if (!alarm_has_dynticks(t
))
617 /* TODO: MIN_TIMER_REARM_US should be optimized */
618 #define MIN_TIMER_REARM_US 250
620 static struct qemu_alarm_timer
*alarm_timer
;
624 struct qemu_alarm_win32
{
627 } alarm_win32_data
= {0, 0};
629 static int win32_start_timer(struct qemu_alarm_timer
*t
);
630 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
631 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
635 static int unix_start_timer(struct qemu_alarm_timer
*t
);
636 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
640 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
641 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
642 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
644 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
645 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
647 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
648 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
650 #endif /* __linux__ */
654 /* Correlation between real and virtual time is always going to be
655 fairly approximate, so ignore small variation.
656 When the guest is idle real and virtual time will be aligned in
658 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
660 static void icount_adjust(void)
665 static int64_t last_delta
;
666 /* If the VM is not running, then do nothing. */
670 cur_time
= cpu_get_clock();
671 cur_icount
= qemu_get_clock(vm_clock
);
672 delta
= cur_icount
- cur_time
;
673 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
675 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
676 && icount_time_shift
> 0) {
677 /* The guest is getting too far ahead. Slow time down. */
681 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
682 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
683 /* The guest is getting too far behind. Speed time up. */
687 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
690 static void icount_adjust_rt(void * opaque
)
692 qemu_mod_timer(icount_rt_timer
,
693 qemu_get_clock(rt_clock
) + 1000);
697 static void icount_adjust_vm(void * opaque
)
699 qemu_mod_timer(icount_vm_timer
,
700 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
704 static void init_icount_adjust(void)
706 /* Have both realtime and virtual time triggers for speed adjustment.
707 The realtime trigger catches emulated time passing too slowly,
708 the virtual time trigger catches emulated time passing too fast.
709 Realtime triggers occur even when idle, so use them less frequently
711 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
712 qemu_mod_timer(icount_rt_timer
,
713 qemu_get_clock(rt_clock
) + 1000);
714 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
715 qemu_mod_timer(icount_vm_timer
,
716 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
719 static struct qemu_alarm_timer alarm_timers
[] = {
722 {"dynticks", dynticks_start_timer
,
723 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
724 /* HPET - if available - is preferred */
725 {"hpet", hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
726 /* ...otherwise try RTC */
727 {"rtc", rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
729 {"unix", unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
731 {"dynticks", win32_start_timer
,
732 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
733 {"win32", win32_start_timer
,
734 win32_stop_timer
, NULL
, &alarm_win32_data
},
739 static void show_available_alarms(void)
743 printf("Available alarm timers, in order of precedence:\n");
744 for (i
= 0; alarm_timers
[i
].name
; i
++)
745 printf("%s\n", alarm_timers
[i
].name
);
748 static void configure_alarms(char const *opt
)
752 int count
= ARRAY_SIZE(alarm_timers
) - 1;
755 struct qemu_alarm_timer tmp
;
757 if (!strcmp(opt
, "?")) {
758 show_available_alarms();
762 arg
= qemu_strdup(opt
);
764 /* Reorder the array */
765 name
= strtok(arg
, ",");
767 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
768 if (!strcmp(alarm_timers
[i
].name
, name
))
773 fprintf(stderr
, "Unknown clock %s\n", name
);
782 tmp
= alarm_timers
[i
];
783 alarm_timers
[i
] = alarm_timers
[cur
];
784 alarm_timers
[cur
] = tmp
;
788 name
= strtok(NULL
, ",");
794 /* Disable remaining timers */
795 for (i
= cur
; i
< count
; i
++)
796 alarm_timers
[i
].name
= NULL
;
798 show_available_alarms();
803 #define QEMU_NUM_CLOCKS 3
807 QEMUClock
*host_clock
;
809 static QEMUTimer
*active_timers
[QEMU_NUM_CLOCKS
];
811 static QEMUClock
*qemu_new_clock(int type
)
814 clock
= qemu_mallocz(sizeof(QEMUClock
));
820 static void qemu_clock_enable(QEMUClock
*clock
, int enabled
)
822 clock
->enabled
= enabled
;
825 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
829 ts
= qemu_mallocz(sizeof(QEMUTimer
));
836 void qemu_free_timer(QEMUTimer
*ts
)
841 /* stop a timer, but do not dealloc it */
842 void qemu_del_timer(QEMUTimer
*ts
)
846 /* NOTE: this code must be signal safe because
847 qemu_timer_expired() can be called from a signal. */
848 pt
= &active_timers
[ts
->clock
->type
];
861 /* modify the current timer so that it will be fired when current_time
862 >= expire_time. The corresponding callback will be called. */
863 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
869 /* add the timer in the sorted list */
870 /* NOTE: this code must be signal safe because
871 qemu_timer_expired() can be called from a signal. */
872 pt
= &active_timers
[ts
->clock
->type
];
877 if (t
->expire_time
> expire_time
)
881 ts
->expire_time
= expire_time
;
885 /* Rearm if necessary */
886 if (pt
== &active_timers
[ts
->clock
->type
]) {
887 if (!alarm_timer
->pending
) {
888 qemu_rearm_alarm_timer(alarm_timer
);
890 /* Interrupt execution to force deadline recalculation. */
896 int qemu_timer_pending(QEMUTimer
*ts
)
899 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
906 int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
910 return (timer_head
->expire_time
<= current_time
);
913 static void qemu_run_timers(QEMUClock
*clock
)
915 QEMUTimer
**ptimer_head
, *ts
;
916 int64_t current_time
;
921 current_time
= qemu_get_clock (clock
);
922 ptimer_head
= &active_timers
[clock
->type
];
925 if (!ts
|| ts
->expire_time
> current_time
)
927 /* remove timer from the list before calling the callback */
928 *ptimer_head
= ts
->next
;
931 /* run the callback (the timer list can be modified) */
936 int64_t qemu_get_clock(QEMUClock
*clock
)
938 switch(clock
->type
) {
939 case QEMU_CLOCK_REALTIME
:
940 return get_clock() / 1000000;
942 case QEMU_CLOCK_VIRTUAL
:
944 return cpu_get_icount();
946 return cpu_get_clock();
948 case QEMU_CLOCK_HOST
:
949 return get_clock_realtime();
953 int64_t qemu_get_clock_ns(QEMUClock
*clock
)
955 switch(clock
->type
) {
956 case QEMU_CLOCK_REALTIME
:
959 case QEMU_CLOCK_VIRTUAL
:
961 return cpu_get_icount();
963 return cpu_get_clock();
965 case QEMU_CLOCK_HOST
:
966 return get_clock_realtime();
970 static void init_clocks(void)
973 rt_clock
= qemu_new_clock(QEMU_CLOCK_REALTIME
);
974 vm_clock
= qemu_new_clock(QEMU_CLOCK_VIRTUAL
);
975 host_clock
= qemu_new_clock(QEMU_CLOCK_HOST
);
977 rtc_clock
= host_clock
;
981 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
983 uint64_t expire_time
;
985 if (qemu_timer_pending(ts
)) {
986 expire_time
= ts
->expire_time
;
990 qemu_put_be64(f
, expire_time
);
993 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
995 uint64_t expire_time
;
997 expire_time
= qemu_get_be64(f
);
998 if (expire_time
!= -1) {
999 qemu_mod_timer(ts
, expire_time
);
1005 static const VMStateDescription vmstate_timers
= {
1008 .minimum_version_id
= 1,
1009 .minimum_version_id_old
= 1,
1010 .fields
= (VMStateField
[]) {
1011 VMSTATE_INT64(cpu_ticks_offset
, TimersState
),
1012 VMSTATE_INT64(dummy
, TimersState
),
1013 VMSTATE_INT64_V(cpu_clock_offset
, TimersState
, 2),
1014 VMSTATE_END_OF_LIST()
1018 static void qemu_run_all_timers(void)
1020 /* rearm timer, if not periodic */
1021 if (alarm_timer
->expired
) {
1022 alarm_timer
->expired
= 0;
1023 qemu_rearm_alarm_timer(alarm_timer
);
1026 alarm_timer
->pending
= 0;
1028 /* vm time timers */
1030 qemu_run_timers(vm_clock
);
1033 qemu_run_timers(rt_clock
);
1034 qemu_run_timers(host_clock
);
1038 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1039 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1042 static void host_alarm_handler(int host_signum
)
1045 struct qemu_alarm_timer
*t
= alarm_timer
;
1050 #define DISP_FREQ 1000
1052 static int64_t delta_min
= INT64_MAX
;
1053 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1055 ti
= qemu_get_clock(vm_clock
);
1056 if (last_clock
!= 0) {
1057 delta
= ti
- last_clock
;
1058 if (delta
< delta_min
)
1060 if (delta
> delta_max
)
1063 if (++count
== DISP_FREQ
) {
1064 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1065 muldiv64(delta_min
, 1000000, get_ticks_per_sec()),
1066 muldiv64(delta_max
, 1000000, get_ticks_per_sec()),
1067 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, get_ticks_per_sec()),
1068 (double)get_ticks_per_sec() / ((double)delta_cum
/ DISP_FREQ
));
1070 delta_min
= INT64_MAX
;
1078 if (alarm_has_dynticks(t
) ||
1080 qemu_timer_expired(active_timers
[QEMU_CLOCK_VIRTUAL
],
1081 qemu_get_clock(vm_clock
))) ||
1082 qemu_timer_expired(active_timers
[QEMU_CLOCK_REALTIME
],
1083 qemu_get_clock(rt_clock
)) ||
1084 qemu_timer_expired(active_timers
[QEMU_CLOCK_HOST
],
1085 qemu_get_clock(host_clock
))) {
1087 t
->expired
= alarm_has_dynticks(t
);
1089 qemu_notify_event();
1093 static int64_t qemu_next_deadline(void)
1095 /* To avoid problems with overflow limit this to 2^32. */
1096 int64_t delta
= INT32_MAX
;
1098 if (active_timers
[QEMU_CLOCK_VIRTUAL
]) {
1099 delta
= active_timers
[QEMU_CLOCK_VIRTUAL
]->expire_time
-
1100 qemu_get_clock(vm_clock
);
1102 if (active_timers
[QEMU_CLOCK_HOST
]) {
1103 int64_t hdelta
= active_timers
[QEMU_CLOCK_HOST
]->expire_time
-
1104 qemu_get_clock(host_clock
);
1115 #if defined(__linux__)
1116 static uint64_t qemu_next_deadline_dyntick(void)
1124 delta
= (qemu_next_deadline() + 999) / 1000;
1126 if (active_timers
[QEMU_CLOCK_REALTIME
]) {
1127 rtdelta
= (active_timers
[QEMU_CLOCK_REALTIME
]->expire_time
-
1128 qemu_get_clock(rt_clock
))*1000;
1129 if (rtdelta
< delta
)
1133 if (delta
< MIN_TIMER_REARM_US
)
1134 delta
= MIN_TIMER_REARM_US
;
1142 /* Sets a specific flag */
1143 static int fcntl_setfl(int fd
, int flag
)
1147 flags
= fcntl(fd
, F_GETFL
);
1151 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1157 #if defined(__linux__)
1159 #define RTC_FREQ 1024
1161 static void enable_sigio_timer(int fd
)
1163 struct sigaction act
;
1166 sigfillset(&act
.sa_mask
);
1168 act
.sa_handler
= host_alarm_handler
;
1170 sigaction(SIGIO
, &act
, NULL
);
1171 fcntl_setfl(fd
, O_ASYNC
);
1172 fcntl(fd
, F_SETOWN
, getpid());
1175 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1177 struct hpet_info info
;
1180 fd
= qemu_open("/dev/hpet", O_RDONLY
);
1185 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1187 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1188 "error, but for better emulation accuracy type:\n"
1189 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1193 /* Check capabilities */
1194 r
= ioctl(fd
, HPET_INFO
, &info
);
1198 /* Enable periodic mode */
1199 r
= ioctl(fd
, HPET_EPI
, 0);
1200 if (info
.hi_flags
&& (r
< 0))
1203 /* Enable interrupt */
1204 r
= ioctl(fd
, HPET_IE_ON
, 0);
1208 enable_sigio_timer(fd
);
1209 t
->priv
= (void *)(long)fd
;
1217 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1219 int fd
= (long)t
->priv
;
1224 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1227 unsigned long current_rtc_freq
= 0;
1229 TFR(rtc_fd
= qemu_open("/dev/rtc", O_RDONLY
));
1232 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1233 if (current_rtc_freq
!= RTC_FREQ
&&
1234 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1235 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1236 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1237 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1240 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1246 enable_sigio_timer(rtc_fd
);
1248 t
->priv
= (void *)(long)rtc_fd
;
1253 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1255 int rtc_fd
= (long)t
->priv
;
1260 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1264 struct sigaction act
;
1266 sigfillset(&act
.sa_mask
);
1268 act
.sa_handler
= host_alarm_handler
;
1270 sigaction(SIGALRM
, &act
, NULL
);
1273 * Initialize ev struct to 0 to avoid valgrind complaining
1274 * about uninitialized data in timer_create call
1276 memset(&ev
, 0, sizeof(ev
));
1277 ev
.sigev_value
.sival_int
= 0;
1278 ev
.sigev_notify
= SIGEV_SIGNAL
;
1279 ev
.sigev_signo
= SIGALRM
;
1281 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1282 perror("timer_create");
1284 /* disable dynticks */
1285 fprintf(stderr
, "Dynamic Ticks disabled\n");
1290 t
->priv
= (void *)(long)host_timer
;
1295 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1297 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1299 timer_delete(host_timer
);
1302 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1304 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1305 struct itimerspec timeout
;
1306 int64_t nearest_delta_us
= INT64_MAX
;
1309 assert(alarm_has_dynticks(t
));
1310 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1311 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1312 !active_timers
[QEMU_CLOCK_HOST
])
1315 nearest_delta_us
= qemu_next_deadline_dyntick();
1317 /* check whether a timer is already running */
1318 if (timer_gettime(host_timer
, &timeout
)) {
1320 fprintf(stderr
, "Internal timer error: aborting\n");
1323 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1324 if (current_us
&& current_us
<= nearest_delta_us
)
1327 timeout
.it_interval
.tv_sec
= 0;
1328 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1329 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1330 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1331 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1333 fprintf(stderr
, "Internal timer error: aborting\n");
1338 #endif /* defined(__linux__) */
1340 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1342 struct sigaction act
;
1343 struct itimerval itv
;
1347 sigfillset(&act
.sa_mask
);
1349 act
.sa_handler
= host_alarm_handler
;
1351 sigaction(SIGALRM
, &act
, NULL
);
1353 itv
.it_interval
.tv_sec
= 0;
1354 /* for i386 kernel 2.6 to get 1 ms */
1355 itv
.it_interval
.tv_usec
= 999;
1356 itv
.it_value
.tv_sec
= 0;
1357 itv
.it_value
.tv_usec
= 10 * 1000;
1359 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1366 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1368 struct itimerval itv
;
1370 memset(&itv
, 0, sizeof(itv
));
1371 setitimer(ITIMER_REAL
, &itv
, NULL
);
1374 #endif /* !defined(_WIN32) */
1379 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1382 struct qemu_alarm_win32
*data
= t
->priv
;
1385 memset(&tc
, 0, sizeof(tc
));
1386 timeGetDevCaps(&tc
, sizeof(tc
));
1388 data
->period
= tc
.wPeriodMin
;
1389 timeBeginPeriod(data
->period
);
1391 flags
= TIME_CALLBACK_FUNCTION
;
1392 if (alarm_has_dynticks(t
))
1393 flags
|= TIME_ONESHOT
;
1395 flags
|= TIME_PERIODIC
;
1397 data
->timerId
= timeSetEvent(1, // interval (ms)
1398 data
->period
, // resolution
1399 host_alarm_handler
, // function
1400 (DWORD
)t
, // parameter
1403 if (!data
->timerId
) {
1404 fprintf(stderr
, "Failed to initialize win32 alarm timer: %ld\n",
1406 timeEndPeriod(data
->period
);
1413 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1415 struct qemu_alarm_win32
*data
= t
->priv
;
1417 timeKillEvent(data
->timerId
);
1418 timeEndPeriod(data
->period
);
1421 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1423 struct qemu_alarm_win32
*data
= t
->priv
;
1425 assert(alarm_has_dynticks(t
));
1426 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1427 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1428 !active_timers
[QEMU_CLOCK_HOST
])
1431 timeKillEvent(data
->timerId
);
1433 data
->timerId
= timeSetEvent(1,
1437 TIME_ONESHOT
| TIME_CALLBACK_FUNCTION
);
1439 if (!data
->timerId
) {
1440 fprintf(stderr
, "Failed to re-arm win32 alarm timer %ld\n",
1443 timeEndPeriod(data
->period
);
1450 static void alarm_timer_on_change_state_rearm(void *opaque
, int running
, int reason
)
1453 qemu_rearm_alarm_timer((struct qemu_alarm_timer
*) opaque
);
1456 static int init_timer_alarm(void)
1458 struct qemu_alarm_timer
*t
= NULL
;
1461 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1462 t
= &alarm_timers
[i
];
1474 /* first event is at time 0 */
1477 qemu_add_vm_change_state_handler(alarm_timer_on_change_state_rearm
, t
);
1485 static void quit_timers(void)
1487 struct qemu_alarm_timer
*t
= alarm_timer
;
1492 /***********************************************************/
1493 /* host time/date access */
1494 void qemu_get_timedate(struct tm
*tm
, int offset
)
1501 if (rtc_date_offset
== -1) {
1505 ret
= localtime(&ti
);
1507 ti
-= rtc_date_offset
;
1511 memcpy(tm
, ret
, sizeof(struct tm
));
1514 int qemu_timedate_diff(struct tm
*tm
)
1518 if (rtc_date_offset
== -1)
1520 seconds
= mktimegm(tm
);
1522 seconds
= mktime(tm
);
1524 seconds
= mktimegm(tm
) + rtc_date_offset
;
1526 return seconds
- time(NULL
);
1529 void rtc_change_mon_event(struct tm
*tm
)
1533 data
= qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm
));
1534 monitor_protocol_event(QEVENT_RTC_CHANGE
, data
);
1535 qobject_decref(data
);
1538 static void configure_rtc_date_offset(const char *startdate
, int legacy
)
1540 time_t rtc_start_date
;
1543 if (!strcmp(startdate
, "now") && legacy
) {
1544 rtc_date_offset
= -1;
1546 if (sscanf(startdate
, "%d-%d-%dT%d:%d:%d",
1554 } else if (sscanf(startdate
, "%d-%d-%d",
1557 &tm
.tm_mday
) == 3) {
1566 rtc_start_date
= mktimegm(&tm
);
1567 if (rtc_start_date
== -1) {
1569 fprintf(stderr
, "Invalid date format. Valid formats are:\n"
1570 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1573 rtc_date_offset
= time(NULL
) - rtc_start_date
;
1577 static void configure_rtc(QemuOpts
*opts
)
1581 value
= qemu_opt_get(opts
, "base");
1583 if (!strcmp(value
, "utc")) {
1585 } else if (!strcmp(value
, "localtime")) {
1588 configure_rtc_date_offset(value
, 0);
1591 value
= qemu_opt_get(opts
, "clock");
1593 if (!strcmp(value
, "host")) {
1594 rtc_clock
= host_clock
;
1595 } else if (!strcmp(value
, "vm")) {
1596 rtc_clock
= vm_clock
;
1598 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1602 #ifdef CONFIG_TARGET_I386
1603 value
= qemu_opt_get(opts
, "driftfix");
1605 if (!strcmp(buf
, "slew")) {
1607 } else if (!strcmp(buf
, "none")) {
1610 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1618 static void socket_cleanup(void)
1623 static int socket_init(void)
1628 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1630 err
= WSAGetLastError();
1631 fprintf(stderr
, "WSAStartup: %d\n", err
);
1634 atexit(socket_cleanup
);
1639 /***********************************************************/
1640 /* Bluetooth support */
1643 static struct HCIInfo
*hci_table
[MAX_NICS
];
1645 static struct bt_vlan_s
{
1646 struct bt_scatternet_s net
;
1648 struct bt_vlan_s
*next
;
1651 /* find or alloc a new bluetooth "VLAN" */
1652 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1654 struct bt_vlan_s
**pvlan
, *vlan
;
1655 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1659 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1661 pvlan
= &first_bt_vlan
;
1662 while (*pvlan
!= NULL
)
1663 pvlan
= &(*pvlan
)->next
;
1668 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1672 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1677 static struct HCIInfo null_hci
= {
1678 .cmd_send
= null_hci_send
,
1679 .sco_send
= null_hci_send
,
1680 .acl_send
= null_hci_send
,
1681 .bdaddr_set
= null_hci_addr_set
,
1684 struct HCIInfo
*qemu_next_hci(void)
1686 if (cur_hci
== nb_hcis
)
1689 return hci_table
[cur_hci
++];
1692 static struct HCIInfo
*hci_init(const char *str
)
1695 struct bt_scatternet_s
*vlan
= 0;
1697 if (!strcmp(str
, "null"))
1700 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
1702 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
1703 else if (!strncmp(str
, "hci", 3)) {
1706 if (!strncmp(str
+ 3, ",vlan=", 6)) {
1707 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
1712 vlan
= qemu_find_bt_vlan(0);
1714 return bt_new_hci(vlan
);
1717 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
1722 static int bt_hci_parse(const char *str
)
1724 struct HCIInfo
*hci
;
1727 if (nb_hcis
>= MAX_NICS
) {
1728 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
1732 hci
= hci_init(str
);
1741 bdaddr
.b
[5] = 0x56 + nb_hcis
;
1742 hci
->bdaddr_set(hci
, bdaddr
.b
);
1744 hci_table
[nb_hcis
++] = hci
;
1749 static void bt_vhci_add(int vlan_id
)
1751 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
1754 fprintf(stderr
, "qemu: warning: adding a VHCI to "
1755 "an empty scatternet %i\n", vlan_id
);
1757 bt_vhci_init(bt_new_hci(vlan
));
1760 static struct bt_device_s
*bt_device_add(const char *opt
)
1762 struct bt_scatternet_s
*vlan
;
1764 char *endp
= strstr(opt
, ",vlan=");
1765 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
1768 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
1771 vlan_id
= strtol(endp
+ 6, &endp
, 0);
1773 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
1778 vlan
= qemu_find_bt_vlan(vlan_id
);
1781 fprintf(stderr
, "qemu: warning: adding a slave device to "
1782 "an empty scatternet %i\n", vlan_id
);
1784 if (!strcmp(devname
, "keyboard"))
1785 return bt_keyboard_init(vlan
);
1787 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
1791 static int bt_parse(const char *opt
)
1793 const char *endp
, *p
;
1796 if (strstart(opt
, "hci", &endp
)) {
1797 if (!*endp
|| *endp
== ',') {
1799 if (!strstart(endp
, ",vlan=", 0))
1802 return bt_hci_parse(opt
);
1804 } else if (strstart(opt
, "vhci", &endp
)) {
1805 if (!*endp
|| *endp
== ',') {
1807 if (strstart(endp
, ",vlan=", &p
)) {
1808 vlan
= strtol(p
, (char **) &endp
, 0);
1810 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
1814 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
1823 } else if (strstart(opt
, "device:", &endp
))
1824 return !bt_device_add(endp
);
1826 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
1830 /***********************************************************/
1831 /* QEMU Block devices */
1833 #define HD_ALIAS "index=%d,media=disk"
1834 #define CDROM_ALIAS "index=2,media=cdrom"
1835 #define FD_ALIAS "index=%d,if=floppy"
1836 #define PFLASH_ALIAS "if=pflash"
1837 #define MTD_ALIAS "if=mtd"
1838 #define SD_ALIAS "index=0,if=sd"
1840 QemuOpts
*drive_add(const char *file
, const char *fmt
, ...)
1847 vsnprintf(optstr
, sizeof(optstr
), fmt
, ap
);
1850 opts
= qemu_opts_parse(&qemu_drive_opts
, optstr
, 0);
1852 fprintf(stderr
, "%s: huh? duplicate? (%s)\n",
1853 __FUNCTION__
, optstr
);
1857 qemu_opt_set(opts
, "file", file
);
1861 DriveInfo
*drive_get(BlockInterfaceType type
, int bus
, int unit
)
1865 /* seek interface, bus and unit */
1867 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1868 if (dinfo
->type
== type
&&
1869 dinfo
->bus
== bus
&&
1870 dinfo
->unit
== unit
)
1877 DriveInfo
*drive_get_by_id(const char *id
)
1881 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1882 if (strcmp(id
, dinfo
->id
))
1889 int drive_get_max_bus(BlockInterfaceType type
)
1895 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1896 if(dinfo
->type
== type
&&
1897 dinfo
->bus
> max_bus
)
1898 max_bus
= dinfo
->bus
;
1903 const char *drive_get_serial(BlockDriverState
*bdrv
)
1907 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1908 if (dinfo
->bdrv
== bdrv
)
1909 return dinfo
->serial
;
1915 BlockInterfaceErrorAction
drive_get_on_error(
1916 BlockDriverState
*bdrv
, int is_read
)
1920 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1921 if (dinfo
->bdrv
== bdrv
)
1922 return is_read
? dinfo
->on_read_error
: dinfo
->on_write_error
;
1925 return is_read
? BLOCK_ERR_REPORT
: BLOCK_ERR_STOP_ENOSPC
;
1928 static void bdrv_format_print(void *opaque
, const char *name
)
1930 fprintf(stderr
, " %s", name
);
1933 void drive_uninit(DriveInfo
*dinfo
)
1935 qemu_opts_del(dinfo
->opts
);
1936 bdrv_delete(dinfo
->bdrv
);
1937 QTAILQ_REMOVE(&drives
, dinfo
, next
);
1941 static int parse_block_error_action(const char *buf
, int is_read
)
1943 if (!strcmp(buf
, "ignore")) {
1944 return BLOCK_ERR_IGNORE
;
1945 } else if (!is_read
&& !strcmp(buf
, "enospc")) {
1946 return BLOCK_ERR_STOP_ENOSPC
;
1947 } else if (!strcmp(buf
, "stop")) {
1948 return BLOCK_ERR_STOP_ANY
;
1949 } else if (!strcmp(buf
, "report")) {
1950 return BLOCK_ERR_REPORT
;
1952 fprintf(stderr
, "qemu: '%s' invalid %s error action\n",
1953 buf
, is_read
? "read" : "write");
1958 DriveInfo
*drive_init(QemuOpts
*opts
, void *opaque
,
1962 const char *file
= NULL
;
1965 const char *mediastr
= "";
1966 BlockInterfaceType type
;
1967 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
1968 int bus_id
, unit_id
;
1969 int cyls
, heads
, secs
, translation
;
1970 BlockDriver
*drv
= NULL
;
1971 QEMUMachine
*machine
= opaque
;
1978 int on_read_error
, on_write_error
;
1979 const char *devaddr
;
1985 translation
= BIOS_ATA_TRANSLATION_AUTO
;
1988 if (machine
&& machine
->use_scsi
) {
1990 max_devs
= MAX_SCSI_DEVS
;
1991 pstrcpy(devname
, sizeof(devname
), "scsi");
1994 max_devs
= MAX_IDE_DEVS
;
1995 pstrcpy(devname
, sizeof(devname
), "ide");
1999 /* extract parameters */
2000 bus_id
= qemu_opt_get_number(opts
, "bus", 0);
2001 unit_id
= qemu_opt_get_number(opts
, "unit", -1);
2002 index
= qemu_opt_get_number(opts
, "index", -1);
2004 cyls
= qemu_opt_get_number(opts
, "cyls", 0);
2005 heads
= qemu_opt_get_number(opts
, "heads", 0);
2006 secs
= qemu_opt_get_number(opts
, "secs", 0);
2008 snapshot
= qemu_opt_get_bool(opts
, "snapshot", 0);
2009 ro
= qemu_opt_get_bool(opts
, "readonly", 0);
2011 file
= qemu_opt_get(opts
, "file");
2012 serial
= qemu_opt_get(opts
, "serial");
2014 if ((buf
= qemu_opt_get(opts
, "if")) != NULL
) {
2015 pstrcpy(devname
, sizeof(devname
), buf
);
2016 if (!strcmp(buf
, "ide")) {
2018 max_devs
= MAX_IDE_DEVS
;
2019 } else if (!strcmp(buf
, "scsi")) {
2021 max_devs
= MAX_SCSI_DEVS
;
2022 } else if (!strcmp(buf
, "floppy")) {
2025 } else if (!strcmp(buf
, "pflash")) {
2028 } else if (!strcmp(buf
, "mtd")) {
2031 } else if (!strcmp(buf
, "sd")) {
2034 } else if (!strcmp(buf
, "virtio")) {
2037 } else if (!strcmp(buf
, "xen")) {
2040 } else if (!strcmp(buf
, "none")) {
2044 fprintf(stderr
, "qemu: unsupported bus type '%s'\n", buf
);
2049 if (cyls
|| heads
|| secs
) {
2050 if (cyls
< 1 || (type
== IF_IDE
&& cyls
> 16383)) {
2051 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", buf
);
2054 if (heads
< 1 || (type
== IF_IDE
&& heads
> 16)) {
2055 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", buf
);
2058 if (secs
< 1 || (type
== IF_IDE
&& secs
> 63)) {
2059 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", buf
);
2064 if ((buf
= qemu_opt_get(opts
, "trans")) != NULL
) {
2067 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2071 if (!strcmp(buf
, "none"))
2072 translation
= BIOS_ATA_TRANSLATION_NONE
;
2073 else if (!strcmp(buf
, "lba"))
2074 translation
= BIOS_ATA_TRANSLATION_LBA
;
2075 else if (!strcmp(buf
, "auto"))
2076 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2078 fprintf(stderr
, "qemu: '%s' invalid translation type\n", buf
);
2083 if ((buf
= qemu_opt_get(opts
, "media")) != NULL
) {
2084 if (!strcmp(buf
, "disk")) {
2086 } else if (!strcmp(buf
, "cdrom")) {
2087 if (cyls
|| secs
|| heads
) {
2089 "qemu: '%s' invalid physical CHS format\n", buf
);
2092 media
= MEDIA_CDROM
;
2094 fprintf(stderr
, "qemu: '%s' invalid media\n", buf
);
2099 if ((buf
= qemu_opt_get(opts
, "cache")) != NULL
) {
2100 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2102 else if (!strcmp(buf
, "writethrough"))
2104 else if (!strcmp(buf
, "writeback"))
2107 fprintf(stderr
, "qemu: invalid cache option\n");
2112 #ifdef CONFIG_LINUX_AIO
2113 if ((buf
= qemu_opt_get(opts
, "aio")) != NULL
) {
2114 if (!strcmp(buf
, "threads"))
2116 else if (!strcmp(buf
, "native"))
2119 fprintf(stderr
, "qemu: invalid aio option\n");
2125 if ((buf
= qemu_opt_get(opts
, "format")) != NULL
) {
2126 if (strcmp(buf
, "?") == 0) {
2127 fprintf(stderr
, "qemu: Supported formats:");
2128 bdrv_iterate_format(bdrv_format_print
, NULL
);
2129 fprintf(stderr
, "\n");
2132 drv
= bdrv_find_whitelisted_format(buf
);
2134 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2139 on_write_error
= BLOCK_ERR_STOP_ENOSPC
;
2140 if ((buf
= qemu_opt_get(opts
, "werror")) != NULL
) {
2141 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2142 fprintf(stderr
, "werror is no supported by this format\n");
2146 on_write_error
= parse_block_error_action(buf
, 0);
2147 if (on_write_error
< 0) {
2152 on_read_error
= BLOCK_ERR_REPORT
;
2153 if ((buf
= qemu_opt_get(opts
, "rerror")) != NULL
) {
2154 if (type
!= IF_IDE
&& type
!= IF_VIRTIO
) {
2155 fprintf(stderr
, "rerror is no supported by this format\n");
2159 on_read_error
= parse_block_error_action(buf
, 1);
2160 if (on_read_error
< 0) {
2165 if ((devaddr
= qemu_opt_get(opts
, "addr")) != NULL
) {
2166 if (type
!= IF_VIRTIO
) {
2167 fprintf(stderr
, "addr is not supported\n");
2172 /* compute bus and unit according index */
2175 if (bus_id
!= 0 || unit_id
!= -1) {
2177 "qemu: index cannot be used with bus and unit\n");
2185 unit_id
= index
% max_devs
;
2186 bus_id
= index
/ max_devs
;
2190 /* if user doesn't specify a unit_id,
2191 * try to find the first free
2194 if (unit_id
== -1) {
2196 while (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2198 if (max_devs
&& unit_id
>= max_devs
) {
2199 unit_id
-= max_devs
;
2207 if (max_devs
&& unit_id
>= max_devs
) {
2208 fprintf(stderr
, "qemu: unit %d too big (max is %d)\n",
2209 unit_id
, max_devs
- 1);
2214 * ignore multiple definitions
2217 if (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2224 dinfo
= qemu_mallocz(sizeof(*dinfo
));
2225 if ((buf
= qemu_opts_id(opts
)) != NULL
) {
2226 dinfo
->id
= qemu_strdup(buf
);
2228 /* no id supplied -> create one */
2229 dinfo
->id
= qemu_mallocz(32);
2230 if (type
== IF_IDE
|| type
== IF_SCSI
)
2231 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2233 snprintf(dinfo
->id
, 32, "%s%i%s%i",
2234 devname
, bus_id
, mediastr
, unit_id
);
2236 snprintf(dinfo
->id
, 32, "%s%s%i",
2237 devname
, mediastr
, unit_id
);
2239 dinfo
->bdrv
= bdrv_new(dinfo
->id
);
2240 dinfo
->devaddr
= devaddr
;
2242 dinfo
->bus
= bus_id
;
2243 dinfo
->unit
= unit_id
;
2244 dinfo
->on_read_error
= on_read_error
;
2245 dinfo
->on_write_error
= on_write_error
;
2248 strncpy(dinfo
->serial
, serial
, sizeof(serial
));
2249 QTAILQ_INSERT_TAIL(&drives
, dinfo
, next
);
2259 bdrv_set_geometry_hint(dinfo
->bdrv
, cyls
, heads
, secs
);
2260 bdrv_set_translation_hint(dinfo
->bdrv
, translation
);
2264 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_CDROM
);
2269 /* FIXME: This isn't really a floppy, but it's a reasonable
2272 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_FLOPPY
);
2278 /* add virtio block device */
2279 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
2280 qemu_opt_set(opts
, "driver", "virtio-blk-pci");
2281 qemu_opt_set(opts
, "drive", dinfo
->id
);
2283 qemu_opt_set(opts
, "addr", devaddr
);
2294 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2295 cache
= 2; /* always use write-back with snapshot */
2297 if (cache
== 0) /* no caching */
2298 bdrv_flags
|= BDRV_O_NOCACHE
;
2299 else if (cache
== 2) /* write-back */
2300 bdrv_flags
|= BDRV_O_CACHE_WB
;
2303 bdrv_flags
|= BDRV_O_NATIVE_AIO
;
2305 bdrv_flags
&= ~BDRV_O_NATIVE_AIO
;
2309 if (type
!= IF_SCSI
&& type
!= IF_VIRTIO
&& type
!= IF_FLOPPY
) {
2310 fprintf(stderr
, "qemu: readonly flag not supported for drive with this interface\n");
2315 * cdrom is read-only. Set it now, after above interface checking
2316 * since readonly attribute not explicitly required, so no error.
2318 if (media
== MEDIA_CDROM
) {
2321 bdrv_flags
|= ro
? 0 : BDRV_O_RDWR
;
2323 if (bdrv_open2(dinfo
->bdrv
, file
, bdrv_flags
, drv
) < 0) {
2324 fprintf(stderr
, "qemu: could not open disk image %s: %s\n",
2325 file
, strerror(errno
));
2329 if (bdrv_key_required(dinfo
->bdrv
))
2335 static int drive_init_func(QemuOpts
*opts
, void *opaque
)
2337 QEMUMachine
*machine
= opaque
;
2338 int fatal_error
= 0;
2340 if (drive_init(opts
, machine
, &fatal_error
) == NULL
) {
2347 static int drive_enable_snapshot(QemuOpts
*opts
, void *opaque
)
2349 if (NULL
== qemu_opt_get(opts
, "snapshot")) {
2350 qemu_opt_set(opts
, "snapshot", "on");
2355 void qemu_register_boot_set(QEMUBootSetHandler
*func
, void *opaque
)
2357 boot_set_handler
= func
;
2358 boot_set_opaque
= opaque
;
2361 int qemu_boot_set(const char *boot_devices
)
2363 if (!boot_set_handler
) {
2366 return boot_set_handler(boot_set_opaque
, boot_devices
);
2369 static int parse_bootdevices(char *devices
)
2371 /* We just do some generic consistency checks */
2375 for (p
= devices
; *p
!= '\0'; p
++) {
2376 /* Allowed boot devices are:
2377 * a-b: floppy disk drives
2378 * c-f: IDE disk drives
2379 * g-m: machine implementation dependant drives
2380 * n-p: network devices
2381 * It's up to each machine implementation to check if the given boot
2382 * devices match the actual hardware implementation and firmware
2385 if (*p
< 'a' || *p
> 'p') {
2386 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
2389 if (bitmap
& (1 << (*p
- 'a'))) {
2390 fprintf(stderr
, "Boot device '%c' was given twice\n", *p
);
2393 bitmap
|= 1 << (*p
- 'a');
2398 static void restore_boot_devices(void *opaque
)
2400 char *standard_boot_devices
= opaque
;
2402 qemu_boot_set(standard_boot_devices
);
2404 qemu_unregister_reset(restore_boot_devices
, standard_boot_devices
);
2405 qemu_free(standard_boot_devices
);
2408 static void numa_add(const char *optarg
)
2412 unsigned long long value
, endvalue
;
2415 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2416 if (!strcmp(option
, "node")) {
2417 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2418 nodenr
= nb_numa_nodes
;
2420 nodenr
= strtoull(option
, NULL
, 10);
2423 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2424 node_mem
[nodenr
] = 0;
2426 value
= strtoull(option
, &endptr
, 0);
2428 case 0: case 'M': case 'm':
2435 node_mem
[nodenr
] = value
;
2437 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2438 node_cpumask
[nodenr
] = 0;
2440 value
= strtoull(option
, &endptr
, 10);
2443 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2445 if (*endptr
== '-') {
2446 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2447 if (endvalue
>= 63) {
2450 "only 63 CPUs in NUMA mode supported.\n");
2452 value
= (2ULL << endvalue
) - (1ULL << value
);
2454 value
= 1ULL << value
;
2457 node_cpumask
[nodenr
] = value
;
2464 static void smp_parse(const char *optarg
)
2466 int smp
, sockets
= 0, threads
= 0, cores
= 0;
2470 smp
= strtoul(optarg
, &endptr
, 10);
2471 if (endptr
!= optarg
) {
2472 if (*endptr
== ',') {
2476 if (get_param_value(option
, 128, "sockets", endptr
) != 0)
2477 sockets
= strtoull(option
, NULL
, 10);
2478 if (get_param_value(option
, 128, "cores", endptr
) != 0)
2479 cores
= strtoull(option
, NULL
, 10);
2480 if (get_param_value(option
, 128, "threads", endptr
) != 0)
2481 threads
= strtoull(option
, NULL
, 10);
2482 if (get_param_value(option
, 128, "maxcpus", endptr
) != 0)
2483 max_cpus
= strtoull(option
, NULL
, 10);
2485 /* compute missing values, prefer sockets over cores over threads */
2486 if (smp
== 0 || sockets
== 0) {
2487 sockets
= sockets
> 0 ? sockets
: 1;
2488 cores
= cores
> 0 ? cores
: 1;
2489 threads
= threads
> 0 ? threads
: 1;
2491 smp
= cores
* threads
* sockets
;
2495 threads
= threads
> 0 ? threads
: 1;
2496 cores
= smp
/ (sockets
* threads
);
2499 threads
= smp
/ (cores
* sockets
);
2504 smp_cores
= cores
> 0 ? cores
: 1;
2505 smp_threads
= threads
> 0 ? threads
: 1;
2507 max_cpus
= smp_cpus
;
2510 /***********************************************************/
2513 static int usb_device_add(const char *devname
, int is_hotplug
)
2516 USBDevice
*dev
= NULL
;
2521 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2522 dev
= usbdevice_create(devname
);
2526 /* the other ones */
2527 if (strstart(devname
, "host:", &p
)) {
2528 dev
= usb_host_device_open(p
);
2529 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2530 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2531 bt_new_hci(qemu_find_bt_vlan(0)));
2542 static int usb_device_del(const char *devname
)
2547 if (strstart(devname
, "host:", &p
))
2548 return usb_host_device_close(p
);
2553 p
= strchr(devname
, '.');
2556 bus_num
= strtoul(devname
, NULL
, 0);
2557 addr
= strtoul(p
+ 1, NULL
, 0);
2559 return usb_device_delete_addr(bus_num
, addr
);
2562 static int usb_parse(const char *cmdline
)
2565 r
= usb_device_add(cmdline
, 0);
2567 fprintf(stderr
, "qemu: could not add USB device '%s'\n", cmdline
);
2572 void do_usb_add(Monitor
*mon
, const QDict
*qdict
)
2574 const char *devname
= qdict_get_str(qdict
, "devname");
2575 if (usb_device_add(devname
, 1) < 0) {
2576 error_report("could not add USB device '%s'", devname
);
2580 void do_usb_del(Monitor
*mon
, const QDict
*qdict
)
2582 const char *devname
= qdict_get_str(qdict
, "devname");
2583 if (usb_device_del(devname
) < 0) {
2584 error_report("could not delete USB device '%s'", devname
);
2588 /***********************************************************/
2589 /* PCMCIA/Cardbus */
2591 static struct pcmcia_socket_entry_s
{
2592 PCMCIASocket
*socket
;
2593 struct pcmcia_socket_entry_s
*next
;
2594 } *pcmcia_sockets
= 0;
2596 void pcmcia_socket_register(PCMCIASocket
*socket
)
2598 struct pcmcia_socket_entry_s
*entry
;
2600 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2601 entry
->socket
= socket
;
2602 entry
->next
= pcmcia_sockets
;
2603 pcmcia_sockets
= entry
;
2606 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2608 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2610 ptr
= &pcmcia_sockets
;
2611 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2612 if (entry
->socket
== socket
) {
2618 void pcmcia_info(Monitor
*mon
)
2620 struct pcmcia_socket_entry_s
*iter
;
2622 if (!pcmcia_sockets
)
2623 monitor_printf(mon
, "No PCMCIA sockets\n");
2625 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2626 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2627 iter
->socket
->attached
? iter
->socket
->card_string
:
2631 /***********************************************************/
2634 typedef struct IOHandlerRecord
{
2636 IOCanRWHandler
*fd_read_poll
;
2638 IOHandler
*fd_write
;
2641 /* temporary data */
2643 struct IOHandlerRecord
*next
;
2646 static IOHandlerRecord
*first_io_handler
;
2648 /* XXX: fd_read_poll should be suppressed, but an API change is
2649 necessary in the character devices to suppress fd_can_read(). */
2650 int qemu_set_fd_handler2(int fd
,
2651 IOCanRWHandler
*fd_read_poll
,
2653 IOHandler
*fd_write
,
2656 IOHandlerRecord
**pioh
, *ioh
;
2658 if (!fd_read
&& !fd_write
) {
2659 pioh
= &first_io_handler
;
2664 if (ioh
->fd
== fd
) {
2671 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
2675 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
2676 ioh
->next
= first_io_handler
;
2677 first_io_handler
= ioh
;
2680 ioh
->fd_read_poll
= fd_read_poll
;
2681 ioh
->fd_read
= fd_read
;
2682 ioh
->fd_write
= fd_write
;
2683 ioh
->opaque
= opaque
;
2689 int qemu_set_fd_handler(int fd
,
2691 IOHandler
*fd_write
,
2694 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
2698 /***********************************************************/
2699 /* Polling handling */
2701 typedef struct PollingEntry
{
2704 struct PollingEntry
*next
;
2707 static PollingEntry
*first_polling_entry
;
2709 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
2711 PollingEntry
**ppe
, *pe
;
2712 pe
= qemu_mallocz(sizeof(PollingEntry
));
2714 pe
->opaque
= opaque
;
2715 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
2720 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
2722 PollingEntry
**ppe
, *pe
;
2723 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
2725 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
2733 /***********************************************************/
2734 /* Wait objects support */
2735 typedef struct WaitObjects
{
2737 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
2738 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
2739 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
2742 static WaitObjects wait_objects
= {0};
2744 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2746 WaitObjects
*w
= &wait_objects
;
2748 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
2750 w
->events
[w
->num
] = handle
;
2751 w
->func
[w
->num
] = func
;
2752 w
->opaque
[w
->num
] = opaque
;
2757 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2760 WaitObjects
*w
= &wait_objects
;
2763 for (i
= 0; i
< w
->num
; i
++) {
2764 if (w
->events
[i
] == handle
)
2767 w
->events
[i
] = w
->events
[i
+ 1];
2768 w
->func
[i
] = w
->func
[i
+ 1];
2769 w
->opaque
[i
] = w
->opaque
[i
+ 1];
2777 /***********************************************************/
2778 /* ram save/restore */
2780 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2781 #define RAM_SAVE_FLAG_COMPRESS 0x02
2782 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2783 #define RAM_SAVE_FLAG_PAGE 0x08
2784 #define RAM_SAVE_FLAG_EOS 0x10
2786 static int is_dup_page(uint8_t *page
, uint8_t ch
)
2788 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
2789 uint32_t *array
= (uint32_t *)page
;
2792 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
2793 if (array
[i
] != val
)
2800 static int ram_save_block(QEMUFile
*f
)
2802 static ram_addr_t current_addr
= 0;
2803 ram_addr_t saved_addr
= current_addr
;
2804 ram_addr_t addr
= 0;
2807 while (addr
< last_ram_offset
) {
2808 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
2811 cpu_physical_memory_reset_dirty(current_addr
,
2812 current_addr
+ TARGET_PAGE_SIZE
,
2813 MIGRATION_DIRTY_FLAG
);
2815 p
= qemu_get_ram_ptr(current_addr
);
2817 if (is_dup_page(p
, *p
)) {
2818 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
2819 qemu_put_byte(f
, *p
);
2821 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
2822 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
2828 addr
+= TARGET_PAGE_SIZE
;
2829 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
2835 static uint64_t bytes_transferred
;
2837 static ram_addr_t
ram_save_remaining(void)
2840 ram_addr_t count
= 0;
2842 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2843 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2850 uint64_t ram_bytes_remaining(void)
2852 return ram_save_remaining() * TARGET_PAGE_SIZE
;
2855 uint64_t ram_bytes_transferred(void)
2857 return bytes_transferred
;
2860 uint64_t ram_bytes_total(void)
2862 return last_ram_offset
;
2865 static int ram_save_live(Monitor
*mon
, QEMUFile
*f
, int stage
, void *opaque
)
2868 uint64_t bytes_transferred_last
;
2870 uint64_t expected_time
= 0;
2873 cpu_physical_memory_set_dirty_tracking(0);
2877 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX
) != 0) {
2878 qemu_file_set_error(f
);
2883 bytes_transferred
= 0;
2885 /* Make sure all dirty bits are set */
2886 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2887 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2888 cpu_physical_memory_set_dirty(addr
);
2891 /* Enable dirty memory tracking */
2892 cpu_physical_memory_set_dirty_tracking(1);
2894 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
2897 bytes_transferred_last
= bytes_transferred
;
2898 bwidth
= qemu_get_clock_ns(rt_clock
);
2900 while (!qemu_file_rate_limit(f
)) {
2903 ret
= ram_save_block(f
);
2904 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
2905 if (ret
== 0) /* no more blocks */
2909 bwidth
= qemu_get_clock_ns(rt_clock
) - bwidth
;
2910 bwidth
= (bytes_transferred
- bytes_transferred_last
) / bwidth
;
2912 /* if we haven't transferred anything this round, force expected_time to a
2913 * a very high value, but without crashing */
2917 /* try transferring iterative blocks of memory */
2919 /* flush all remaining blocks regardless of rate limiting */
2920 while (ram_save_block(f
) != 0) {
2921 bytes_transferred
+= TARGET_PAGE_SIZE
;
2923 cpu_physical_memory_set_dirty_tracking(0);
2926 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
2928 expected_time
= ram_save_remaining() * TARGET_PAGE_SIZE
/ bwidth
;
2930 return (stage
== 2) && (expected_time
<= migrate_max_downtime());
2933 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
2938 if (version_id
!= 3)
2942 addr
= qemu_get_be64(f
);
2944 flags
= addr
& ~TARGET_PAGE_MASK
;
2945 addr
&= TARGET_PAGE_MASK
;
2947 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
2948 if (addr
!= last_ram_offset
)
2952 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
2953 uint8_t ch
= qemu_get_byte(f
);
2954 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
2957 (!kvm_enabled() || kvm_has_sync_mmu())) {
2958 madvise(qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
, MADV_DONTNEED
);
2961 } else if (flags
& RAM_SAVE_FLAG_PAGE
) {
2962 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
2964 if (qemu_file_has_error(f
)) {
2967 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
2972 void qemu_service_io(void)
2974 qemu_notify_event();
2977 /***********************************************************/
2978 /* machine registration */
2980 static QEMUMachine
*first_machine
= NULL
;
2981 QEMUMachine
*current_machine
= NULL
;
2983 int qemu_register_machine(QEMUMachine
*m
)
2986 pm
= &first_machine
;
2994 static QEMUMachine
*find_machine(const char *name
)
2998 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
2999 if (!strcmp(m
->name
, name
))
3001 if (m
->alias
&& !strcmp(m
->alias
, name
))
3007 static QEMUMachine
*find_default_machine(void)
3011 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3012 if (m
->is_default
) {
3019 /***********************************************************/
3020 /* main execution loop */
3022 static void gui_update(void *opaque
)
3024 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3025 DisplayState
*ds
= opaque
;
3026 DisplayChangeListener
*dcl
= ds
->listeners
;
3028 qemu_flush_coalesced_mmio_buffer();
3031 while (dcl
!= NULL
) {
3032 if (dcl
->gui_timer_interval
&&
3033 dcl
->gui_timer_interval
< interval
)
3034 interval
= dcl
->gui_timer_interval
;
3037 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3040 static void nographic_update(void *opaque
)
3042 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3044 qemu_flush_coalesced_mmio_buffer();
3045 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3048 void cpu_synchronize_all_states(void)
3052 for (cpu
= first_cpu
; cpu
; cpu
= cpu
->next_cpu
) {
3053 cpu_synchronize_state(cpu
);
3057 void cpu_synchronize_all_post_reset(void)
3061 for (cpu
= first_cpu
; cpu
; cpu
= cpu
->next_cpu
) {
3062 cpu_synchronize_post_reset(cpu
);
3066 void cpu_synchronize_all_post_init(void)
3070 for (cpu
= first_cpu
; cpu
; cpu
= cpu
->next_cpu
) {
3071 cpu_synchronize_post_init(cpu
);
3075 struct vm_change_state_entry
{
3076 VMChangeStateHandler
*cb
;
3078 QLIST_ENTRY (vm_change_state_entry
) entries
;
3081 static QLIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3083 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3086 VMChangeStateEntry
*e
;
3088 e
= qemu_mallocz(sizeof (*e
));
3092 QLIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3096 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3098 QLIST_REMOVE (e
, entries
);
3102 static void vm_state_notify(int running
, int reason
)
3104 VMChangeStateEntry
*e
;
3106 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3107 e
->cb(e
->opaque
, running
, reason
);
3111 static void resume_all_vcpus(void);
3112 static void pause_all_vcpus(void);
3119 vm_state_notify(1, 0);
3124 /* reset/shutdown handler */
3126 typedef struct QEMUResetEntry
{
3127 QTAILQ_ENTRY(QEMUResetEntry
) entry
;
3128 QEMUResetHandler
*func
;
3132 static QTAILQ_HEAD(reset_handlers
, QEMUResetEntry
) reset_handlers
=
3133 QTAILQ_HEAD_INITIALIZER(reset_handlers
);
3134 static int reset_requested
;
3135 static int shutdown_requested
;
3136 static int powerdown_requested
;
3137 static int debug_requested
;
3138 static int vmstop_requested
;
3140 int qemu_shutdown_requested(void)
3142 int r
= shutdown_requested
;
3143 shutdown_requested
= 0;
3147 int qemu_reset_requested(void)
3149 int r
= reset_requested
;
3150 reset_requested
= 0;
3154 int qemu_powerdown_requested(void)
3156 int r
= powerdown_requested
;
3157 powerdown_requested
= 0;
3161 static int qemu_debug_requested(void)
3163 int r
= debug_requested
;
3164 debug_requested
= 0;
3168 static int qemu_vmstop_requested(void)
3170 int r
= vmstop_requested
;
3171 vmstop_requested
= 0;
3175 static void do_vm_stop(int reason
)
3178 cpu_disable_ticks();
3181 vm_state_notify(0, reason
);
3182 monitor_protocol_event(QEVENT_STOP
, NULL
);
3186 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3188 QEMUResetEntry
*re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3191 re
->opaque
= opaque
;
3192 QTAILQ_INSERT_TAIL(&reset_handlers
, re
, entry
);
3195 void qemu_unregister_reset(QEMUResetHandler
*func
, void *opaque
)
3199 QTAILQ_FOREACH(re
, &reset_handlers
, entry
) {
3200 if (re
->func
== func
&& re
->opaque
== opaque
) {
3201 QTAILQ_REMOVE(&reset_handlers
, re
, entry
);
3208 void qemu_system_reset(void)
3210 QEMUResetEntry
*re
, *nre
;
3212 /* reset all devices */
3213 QTAILQ_FOREACH_SAFE(re
, &reset_handlers
, entry
, nre
) {
3214 re
->func(re
->opaque
);
3216 monitor_protocol_event(QEVENT_RESET
, NULL
);
3217 cpu_synchronize_all_post_reset();
3220 void qemu_system_reset_request(void)
3223 shutdown_requested
= 1;
3225 reset_requested
= 1;
3227 qemu_notify_event();
3230 void qemu_system_shutdown_request(void)
3232 shutdown_requested
= 1;
3233 qemu_notify_event();
3236 void qemu_system_powerdown_request(void)
3238 powerdown_requested
= 1;
3239 qemu_notify_event();
3242 #ifdef CONFIG_IOTHREAD
3243 static void qemu_system_vmstop_request(int reason
)
3245 vmstop_requested
= reason
;
3246 qemu_notify_event();
3251 static int io_thread_fd
= -1;
3253 static void qemu_event_increment(void)
3255 /* Write 8 bytes to be compatible with eventfd. */
3256 static uint64_t val
= 1;
3259 if (io_thread_fd
== -1)
3263 ret
= write(io_thread_fd
, &val
, sizeof(val
));
3264 } while (ret
< 0 && errno
== EINTR
);
3266 /* EAGAIN is fine, a read must be pending. */
3267 if (ret
< 0 && errno
!= EAGAIN
) {
3268 fprintf(stderr
, "qemu_event_increment: write() filed: %s\n",
3274 static void qemu_event_read(void *opaque
)
3276 int fd
= (unsigned long)opaque
;
3280 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
3282 len
= read(fd
, buffer
, sizeof(buffer
));
3283 } while ((len
== -1 && errno
== EINTR
) || len
== sizeof(buffer
));
3286 static int qemu_event_init(void)
3291 err
= qemu_eventfd(fds
);
3295 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3299 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3303 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3304 (void *)(unsigned long)fds
[0]);
3306 io_thread_fd
= fds
[1];
3315 HANDLE qemu_event_handle
;
3317 static void dummy_event_handler(void *opaque
)
3321 static int qemu_event_init(void)
3323 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3324 if (!qemu_event_handle
) {
3325 fprintf(stderr
, "Failed CreateEvent: %ld\n", GetLastError());
3328 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3332 static void qemu_event_increment(void)
3334 if (!SetEvent(qemu_event_handle
)) {
3335 fprintf(stderr
, "qemu_event_increment: SetEvent failed: %ld\n",
3342 static int cpu_can_run(CPUState
*env
)
3353 #ifndef CONFIG_IOTHREAD
3354 static int qemu_init_main_loop(void)
3356 return qemu_event_init();
3359 void qemu_init_vcpu(void *_env
)
3361 CPUState
*env
= _env
;
3363 env
->nr_cores
= smp_cores
;
3364 env
->nr_threads
= smp_threads
;
3370 int qemu_cpu_self(void *env
)
3375 static void resume_all_vcpus(void)
3379 static void pause_all_vcpus(void)
3383 void qemu_cpu_kick(void *env
)
3388 void qemu_notify_event(void)
3390 CPUState
*env
= cpu_single_env
;
3392 qemu_event_increment ();
3396 if (next_cpu
&& env
!= next_cpu
) {
3401 void qemu_mutex_lock_iothread(void) {}
3402 void qemu_mutex_unlock_iothread(void) {}
3404 void vm_stop(int reason
)
3409 #else /* CONFIG_IOTHREAD */
3411 #include "qemu-thread.h"
3413 QemuMutex qemu_global_mutex
;
3414 static QemuMutex qemu_fair_mutex
;
3416 static QemuThread io_thread
;
3418 static QemuThread
*tcg_cpu_thread
;
3419 static QemuCond
*tcg_halt_cond
;
3421 static int qemu_system_ready
;
3423 static QemuCond qemu_cpu_cond
;
3425 static QemuCond qemu_system_cond
;
3426 static QemuCond qemu_pause_cond
;
3428 static void tcg_block_io_signals(void);
3429 static void kvm_block_io_signals(CPUState
*env
);
3430 static void unblock_io_signals(void);
3431 static int tcg_has_work(void);
3432 static int cpu_has_work(CPUState
*env
);
3434 static int qemu_init_main_loop(void)
3438 ret
= qemu_event_init();
3442 qemu_cond_init(&qemu_pause_cond
);
3443 qemu_mutex_init(&qemu_fair_mutex
);
3444 qemu_mutex_init(&qemu_global_mutex
);
3445 qemu_mutex_lock(&qemu_global_mutex
);
3447 unblock_io_signals();
3448 qemu_thread_self(&io_thread
);
3453 static void qemu_wait_io_event_common(CPUState
*env
)
3458 qemu_cond_signal(&qemu_pause_cond
);
3462 static void qemu_wait_io_event(CPUState
*env
)
3464 while (!tcg_has_work())
3465 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3467 qemu_mutex_unlock(&qemu_global_mutex
);
3470 * Users of qemu_global_mutex can be starved, having no chance
3471 * to acquire it since this path will get to it first.
3472 * So use another lock to provide fairness.
3474 qemu_mutex_lock(&qemu_fair_mutex
);
3475 qemu_mutex_unlock(&qemu_fair_mutex
);
3477 qemu_mutex_lock(&qemu_global_mutex
);
3478 qemu_wait_io_event_common(env
);
3481 static void qemu_kvm_eat_signal(CPUState
*env
, int timeout
)
3488 ts
.tv_sec
= timeout
/ 1000;
3489 ts
.tv_nsec
= (timeout
% 1000) * 1000000;
3491 sigemptyset(&waitset
);
3492 sigaddset(&waitset
, SIG_IPI
);
3494 qemu_mutex_unlock(&qemu_global_mutex
);
3495 r
= sigtimedwait(&waitset
, &siginfo
, &ts
);
3497 qemu_mutex_lock(&qemu_global_mutex
);
3499 if (r
== -1 && !(e
== EAGAIN
|| e
== EINTR
)) {
3500 fprintf(stderr
, "sigtimedwait: %s\n", strerror(e
));
3505 static void qemu_kvm_wait_io_event(CPUState
*env
)
3507 while (!cpu_has_work(env
))
3508 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3510 qemu_kvm_eat_signal(env
, 0);
3511 qemu_wait_io_event_common(env
);
3514 static int qemu_cpu_exec(CPUState
*env
);
3516 static void *kvm_cpu_thread_fn(void *arg
)
3518 CPUState
*env
= arg
;
3520 qemu_thread_self(env
->thread
);
3524 kvm_block_io_signals(env
);
3526 /* signal CPU creation */
3527 qemu_mutex_lock(&qemu_global_mutex
);
3529 qemu_cond_signal(&qemu_cpu_cond
);
3531 /* and wait for machine initialization */
3532 while (!qemu_system_ready
)
3533 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3536 if (cpu_can_run(env
))
3538 qemu_kvm_wait_io_event(env
);
3544 static void tcg_cpu_exec(void);
3546 static void *tcg_cpu_thread_fn(void *arg
)
3548 CPUState
*env
= arg
;
3550 tcg_block_io_signals();
3551 qemu_thread_self(env
->thread
);
3553 /* signal CPU creation */
3554 qemu_mutex_lock(&qemu_global_mutex
);
3555 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
3557 qemu_cond_signal(&qemu_cpu_cond
);
3559 /* and wait for machine initialization */
3560 while (!qemu_system_ready
)
3561 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3565 qemu_wait_io_event(cur_cpu
);
3571 void qemu_cpu_kick(void *_env
)
3573 CPUState
*env
= _env
;
3574 qemu_cond_broadcast(env
->halt_cond
);
3576 qemu_thread_signal(env
->thread
, SIG_IPI
);
3579 int qemu_cpu_self(void *_env
)
3581 CPUState
*env
= _env
;
3584 qemu_thread_self(&this);
3586 return qemu_thread_equal(&this, env
->thread
);
3589 static void cpu_signal(int sig
)
3592 cpu_exit(cpu_single_env
);
3595 static void tcg_block_io_signals(void)
3598 struct sigaction sigact
;
3601 sigaddset(&set
, SIGUSR2
);
3602 sigaddset(&set
, SIGIO
);
3603 sigaddset(&set
, SIGALRM
);
3604 sigaddset(&set
, SIGCHLD
);
3605 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3608 sigaddset(&set
, SIG_IPI
);
3609 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3611 memset(&sigact
, 0, sizeof(sigact
));
3612 sigact
.sa_handler
= cpu_signal
;
3613 sigaction(SIG_IPI
, &sigact
, NULL
);
3616 static void dummy_signal(int sig
)
3620 static void kvm_block_io_signals(CPUState
*env
)
3624 struct sigaction sigact
;
3627 sigaddset(&set
, SIGUSR2
);
3628 sigaddset(&set
, SIGIO
);
3629 sigaddset(&set
, SIGALRM
);
3630 sigaddset(&set
, SIGCHLD
);
3631 sigaddset(&set
, SIG_IPI
);
3632 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3634 pthread_sigmask(SIG_BLOCK
, NULL
, &set
);
3635 sigdelset(&set
, SIG_IPI
);
3637 memset(&sigact
, 0, sizeof(sigact
));
3638 sigact
.sa_handler
= dummy_signal
;
3639 sigaction(SIG_IPI
, &sigact
, NULL
);
3641 r
= kvm_set_signal_mask(env
, &set
);
3643 fprintf(stderr
, "kvm_set_signal_mask: %s\n", strerror(r
));
3648 static void unblock_io_signals(void)
3653 sigaddset(&set
, SIGUSR2
);
3654 sigaddset(&set
, SIGIO
);
3655 sigaddset(&set
, SIGALRM
);
3656 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3659 sigaddset(&set
, SIG_IPI
);
3660 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3663 static void qemu_signal_lock(unsigned int msecs
)
3665 qemu_mutex_lock(&qemu_fair_mutex
);
3667 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
3668 qemu_thread_signal(tcg_cpu_thread
, SIG_IPI
);
3669 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
3672 qemu_mutex_unlock(&qemu_fair_mutex
);
3675 void qemu_mutex_lock_iothread(void)
3677 if (kvm_enabled()) {
3678 qemu_mutex_lock(&qemu_fair_mutex
);
3679 qemu_mutex_lock(&qemu_global_mutex
);
3680 qemu_mutex_unlock(&qemu_fair_mutex
);
3682 qemu_signal_lock(100);
3685 void qemu_mutex_unlock_iothread(void)
3687 qemu_mutex_unlock(&qemu_global_mutex
);
3690 static int all_vcpus_paused(void)
3692 CPUState
*penv
= first_cpu
;
3697 penv
= (CPUState
*)penv
->next_cpu
;
3703 static void pause_all_vcpus(void)
3705 CPUState
*penv
= first_cpu
;
3709 qemu_thread_signal(penv
->thread
, SIG_IPI
);
3710 qemu_cpu_kick(penv
);
3711 penv
= (CPUState
*)penv
->next_cpu
;
3714 while (!all_vcpus_paused()) {
3715 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
3718 qemu_thread_signal(penv
->thread
, SIG_IPI
);
3719 penv
= (CPUState
*)penv
->next_cpu
;
3724 static void resume_all_vcpus(void)
3726 CPUState
*penv
= first_cpu
;
3731 qemu_thread_signal(penv
->thread
, SIG_IPI
);
3732 qemu_cpu_kick(penv
);
3733 penv
= (CPUState
*)penv
->next_cpu
;
3737 static void tcg_init_vcpu(void *_env
)
3739 CPUState
*env
= _env
;
3740 /* share a single thread for all cpus with TCG */
3741 if (!tcg_cpu_thread
) {
3742 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3743 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3744 qemu_cond_init(env
->halt_cond
);
3745 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
3746 while (env
->created
== 0)
3747 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3748 tcg_cpu_thread
= env
->thread
;
3749 tcg_halt_cond
= env
->halt_cond
;
3751 env
->thread
= tcg_cpu_thread
;
3752 env
->halt_cond
= tcg_halt_cond
;
3756 static void kvm_start_vcpu(CPUState
*env
)
3758 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3759 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3760 qemu_cond_init(env
->halt_cond
);
3761 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
3762 while (env
->created
== 0)
3763 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3766 void qemu_init_vcpu(void *_env
)
3768 CPUState
*env
= _env
;
3770 env
->nr_cores
= smp_cores
;
3771 env
->nr_threads
= smp_threads
;
3773 kvm_start_vcpu(env
);
3778 void qemu_notify_event(void)
3780 qemu_event_increment();
3783 void vm_stop(int reason
)
3786 qemu_thread_self(&me
);
3788 if (!qemu_thread_equal(&me
, &io_thread
)) {
3789 qemu_system_vmstop_request(reason
);
3791 * FIXME: should not return to device code in case
3792 * vm_stop() has been requested.
3794 if (cpu_single_env
) {
3795 cpu_exit(cpu_single_env
);
3796 cpu_single_env
->stop
= 1;
3807 static void host_main_loop_wait(int *timeout
)
3813 /* XXX: need to suppress polling by better using win32 events */
3815 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
3816 ret
|= pe
->func(pe
->opaque
);
3820 WaitObjects
*w
= &wait_objects
;
3822 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
3823 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
3824 if (w
->func
[ret
- WAIT_OBJECT_0
])
3825 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
3827 /* Check for additional signaled events */
3828 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
3830 /* Check if event is signaled */
3831 ret2
= WaitForSingleObject(w
->events
[i
], 0);
3832 if(ret2
== WAIT_OBJECT_0
) {
3834 w
->func
[i
](w
->opaque
[i
]);
3835 } else if (ret2
== WAIT_TIMEOUT
) {
3837 err
= GetLastError();
3838 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
3841 } else if (ret
== WAIT_TIMEOUT
) {
3843 err
= GetLastError();
3844 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
3851 static void host_main_loop_wait(int *timeout
)
3856 void main_loop_wait(int timeout
)
3858 IOHandlerRecord
*ioh
;
3859 fd_set rfds
, wfds
, xfds
;
3863 qemu_bh_update_timeout(&timeout
);
3865 host_main_loop_wait(&timeout
);
3867 /* poll any events */
3868 /* XXX: separate device handlers from system ones */
3873 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3877 (!ioh
->fd_read_poll
||
3878 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
3879 FD_SET(ioh
->fd
, &rfds
);
3883 if (ioh
->fd_write
) {
3884 FD_SET(ioh
->fd
, &wfds
);
3890 tv
.tv_sec
= timeout
/ 1000;
3891 tv
.tv_usec
= (timeout
% 1000) * 1000;
3893 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
3895 qemu_mutex_unlock_iothread();
3896 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
3897 qemu_mutex_lock_iothread();
3899 IOHandlerRecord
**pioh
;
3901 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3902 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
3903 ioh
->fd_read(ioh
->opaque
);
3905 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
3906 ioh
->fd_write(ioh
->opaque
);
3910 /* remove deleted IO handlers */
3911 pioh
= &first_io_handler
;
3922 slirp_select_poll(&rfds
, &wfds
, &xfds
, (ret
< 0));
3924 qemu_run_all_timers();
3926 /* Check bottom-halves last in case any of the earlier events triggered
3932 static int qemu_cpu_exec(CPUState
*env
)
3935 #ifdef CONFIG_PROFILER
3939 #ifdef CONFIG_PROFILER
3940 ti
= profile_getclock();
3945 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
3946 env
->icount_decr
.u16
.low
= 0;
3947 env
->icount_extra
= 0;
3948 count
= qemu_next_deadline();
3949 count
= (count
+ (1 << icount_time_shift
) - 1)
3950 >> icount_time_shift
;
3951 qemu_icount
+= count
;
3952 decr
= (count
> 0xffff) ? 0xffff : count
;
3954 env
->icount_decr
.u16
.low
= decr
;
3955 env
->icount_extra
= count
;
3957 ret
= cpu_exec(env
);
3958 #ifdef CONFIG_PROFILER
3959 qemu_time
+= profile_getclock() - ti
;
3962 /* Fold pending instructions back into the
3963 instruction counter, and clear the interrupt flag. */
3964 qemu_icount
-= (env
->icount_decr
.u16
.low
3965 + env
->icount_extra
);
3966 env
->icount_decr
.u32
= 0;
3967 env
->icount_extra
= 0;
3972 static void tcg_cpu_exec(void)
3976 if (next_cpu
== NULL
)
3977 next_cpu
= first_cpu
;
3978 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
3979 CPUState
*env
= cur_cpu
= next_cpu
;
3981 qemu_clock_enable(vm_clock
,
3982 (cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
) == 0);
3984 if (alarm_timer
->pending
)
3986 if (cpu_can_run(env
))
3987 ret
= qemu_cpu_exec(env
);
3991 if (ret
== EXCP_DEBUG
) {
3992 gdb_set_stop_cpu(env
);
3993 debug_requested
= 1;
3999 static int cpu_has_work(CPUState
*env
)
4007 if (qemu_cpu_has_work(env
))
4012 static int tcg_has_work(void)
4016 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4017 if (cpu_has_work(env
))
4022 static int qemu_calculate_timeout(void)
4024 #ifndef CONFIG_IOTHREAD
4029 else if (tcg_has_work())
4031 else if (!use_icount
)
4034 /* XXX: use timeout computed from timers */
4037 /* Advance virtual time to the next event. */
4038 if (use_icount
== 1) {
4039 /* When not using an adaptive execution frequency
4040 we tend to get badly out of sync with real time,
4041 so just delay for a reasonable amount of time. */
4044 delta
= cpu_get_icount() - cpu_get_clock();
4047 /* If virtual time is ahead of real time then just
4049 timeout
= (delta
/ 1000000) + 1;
4051 /* Wait for either IO to occur or the next
4053 add
= qemu_next_deadline();
4054 /* We advance the timer before checking for IO.
4055 Limit the amount we advance so that early IO
4056 activity won't get the guest too far ahead. */
4060 add
= (add
+ (1 << icount_time_shift
) - 1)
4061 >> icount_time_shift
;
4063 timeout
= delta
/ 1000000;
4070 #else /* CONFIG_IOTHREAD */
4075 static int vm_can_run(void)
4077 if (powerdown_requested
)
4079 if (reset_requested
)
4081 if (shutdown_requested
)
4083 if (debug_requested
)
4088 qemu_irq qemu_system_powerdown
;
4090 static void main_loop(void)
4094 #ifdef CONFIG_IOTHREAD
4095 qemu_system_ready
= 1;
4096 qemu_cond_broadcast(&qemu_system_cond
);
4101 #ifdef CONFIG_PROFILER
4104 #ifndef CONFIG_IOTHREAD
4107 #ifdef CONFIG_PROFILER
4108 ti
= profile_getclock();
4110 main_loop_wait(qemu_calculate_timeout());
4111 #ifdef CONFIG_PROFILER
4112 dev_time
+= profile_getclock() - ti
;
4114 } while (vm_can_run());
4116 if (qemu_debug_requested()) {
4117 vm_stop(EXCP_DEBUG
);
4119 if (qemu_shutdown_requested()) {
4120 monitor_protocol_event(QEVENT_SHUTDOWN
, NULL
);
4127 if (qemu_reset_requested()) {
4129 qemu_system_reset();
4132 if (qemu_powerdown_requested()) {
4133 monitor_protocol_event(QEVENT_POWERDOWN
, NULL
);
4134 qemu_irq_raise(qemu_system_powerdown
);
4136 if ((r
= qemu_vmstop_requested())) {
4143 static void version(void)
4145 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4148 static void help(int exitcode
)
4150 const char *options_help
=
4151 #define DEF(option, opt_arg, opt_enum, opt_help) \
4153 #define DEFHEADING(text) stringify(text) "\n"
4154 #include "qemu-options.h"
4160 printf("usage: %s [options] [disk_image]\n"
4162 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4165 "During emulation, the following keys are useful:\n"
4166 "ctrl-alt-f toggle full screen\n"
4167 "ctrl-alt-n switch to virtual console 'n'\n"
4168 "ctrl-alt toggle mouse and keyboard grab\n"
4170 "When using -nographic, press 'ctrl-a h' to get some help.\n",
4176 #define HAS_ARG 0x0001
4179 #define DEF(option, opt_arg, opt_enum, opt_help) \
4181 #define DEFHEADING(text)
4182 #include "qemu-options.h"
4188 typedef struct QEMUOption
{
4194 static const QEMUOption qemu_options
[] = {
4195 { "h", 0, QEMU_OPTION_h
},
4196 #define DEF(option, opt_arg, opt_enum, opt_help) \
4197 { option, opt_arg, opt_enum },
4198 #define DEFHEADING(text)
4199 #include "qemu-options.h"
4207 struct soundhw soundhw
[] = {
4208 #ifdef HAS_AUDIO_CHOICE
4209 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4215 { .init_isa
= pcspk_audio_init
}
4222 "Creative Sound Blaster 16",
4225 { .init_isa
= SB16_init
}
4229 #ifdef CONFIG_CS4231A
4235 { .init_isa
= cs4231a_init
}
4243 "Yamaha YMF262 (OPL3)",
4245 "Yamaha YM3812 (OPL2)",
4249 { .init_isa
= Adlib_init
}
4256 "Gravis Ultrasound GF1",
4259 { .init_isa
= GUS_init
}
4266 "Intel 82801AA AC97 Audio",
4269 { .init_pci
= ac97_init
}
4273 #ifdef CONFIG_ES1370
4276 "ENSONIQ AudioPCI ES1370",
4279 { .init_pci
= es1370_init
}
4283 #endif /* HAS_AUDIO_CHOICE */
4285 { NULL
, NULL
, 0, 0, { NULL
} }
4288 static void select_soundhw (const char *optarg
)
4292 if (*optarg
== '?') {
4295 printf ("Valid sound card names (comma separated):\n");
4296 for (c
= soundhw
; c
->name
; ++c
) {
4297 printf ("%-11s %s\n", c
->name
, c
->descr
);
4299 printf ("\n-soundhw all will enable all of the above\n");
4300 exit (*optarg
!= '?');
4308 if (!strcmp (optarg
, "all")) {
4309 for (c
= soundhw
; c
->name
; ++c
) {
4317 e
= strchr (p
, ',');
4318 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4320 for (c
= soundhw
; c
->name
; ++c
) {
4321 if (!strncmp (c
->name
, p
, l
) && !c
->name
[l
]) {
4330 "Unknown sound card name (too big to show)\n");
4333 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4338 p
+= l
+ (e
!= NULL
);
4342 goto show_valid_cards
;
4347 static void select_vgahw (const char *p
)
4352 vga_interface_type
= VGA_NONE
;
4353 if (strstart(p
, "std", &opts
)) {
4354 vga_interface_type
= VGA_STD
;
4355 } else if (strstart(p
, "cirrus", &opts
)) {
4356 vga_interface_type
= VGA_CIRRUS
;
4357 } else if (strstart(p
, "vmware", &opts
)) {
4358 vga_interface_type
= VGA_VMWARE
;
4359 } else if (strstart(p
, "xenfb", &opts
)) {
4360 vga_interface_type
= VGA_XENFB
;
4361 } else if (!strstart(p
, "none", &opts
)) {
4363 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4367 const char *nextopt
;
4369 if (strstart(opts
, ",retrace=", &nextopt
)) {
4371 if (strstart(opts
, "dumb", &nextopt
))
4372 vga_retrace_method
= VGA_RETRACE_DUMB
;
4373 else if (strstart(opts
, "precise", &nextopt
))
4374 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4375 else goto invalid_vga
;
4376 } else goto invalid_vga
;
4382 static int balloon_parse(const char *arg
)
4386 if (strcmp(arg
, "none") == 0) {
4390 if (!strncmp(arg
, "virtio", 6)) {
4391 if (arg
[6] == ',') {
4392 /* have params -> parse them */
4393 opts
= qemu_opts_parse(&qemu_device_opts
, arg
+7, 0);
4397 /* create empty opts */
4398 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4400 qemu_opt_set(opts
, "driver", "virtio-balloon-pci");
4409 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4411 exit(STATUS_CONTROL_C_EXIT
);
4416 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4420 if(strlen(str
) != 36)
4423 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4424 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4425 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4431 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4439 static void termsig_handler(int signal
)
4441 qemu_system_shutdown_request();
4444 static void sigchld_handler(int signal
)
4446 waitpid(-1, NULL
, WNOHANG
);
4449 static void sighandler_setup(void)
4451 struct sigaction act
;
4453 memset(&act
, 0, sizeof(act
));
4454 act
.sa_handler
= termsig_handler
;
4455 sigaction(SIGINT
, &act
, NULL
);
4456 sigaction(SIGHUP
, &act
, NULL
);
4457 sigaction(SIGTERM
, &act
, NULL
);
4459 act
.sa_handler
= sigchld_handler
;
4460 act
.sa_flags
= SA_NOCLDSTOP
;
4461 sigaction(SIGCHLD
, &act
, NULL
);
4467 /* Look for support files in the same directory as the executable. */
4468 static char *find_datadir(const char *argv0
)
4474 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
4481 while (p
!= buf
&& *p
!= '\\')
4484 if (access(buf
, R_OK
) == 0) {
4485 return qemu_strdup(buf
);
4491 /* Find a likely location for support files using the location of the binary.
4492 For installed binaries this will be "$bindir/../share/qemu". When
4493 running from the build tree this will be "$bindir/../pc-bios". */
4494 #define SHARE_SUFFIX "/share/qemu"
4495 #define BUILD_SUFFIX "/pc-bios"
4496 static char *find_datadir(const char *argv0
)
4504 #if defined(__linux__)
4507 len
= readlink("/proc/self/exe", buf
, sizeof(buf
) - 1);
4513 #elif defined(__FreeBSD__)
4516 len
= readlink("/proc/curproc/file", buf
, sizeof(buf
) - 1);
4523 /* If we don't have any way of figuring out the actual executable
4524 location then try argv[0]. */
4526 p
= realpath(argv0
, buf
);
4534 max_len
= strlen(dir
) +
4535 MAX(strlen(SHARE_SUFFIX
), strlen(BUILD_SUFFIX
)) + 1;
4536 res
= qemu_mallocz(max_len
);
4537 snprintf(res
, max_len
, "%s%s", dir
, SHARE_SUFFIX
);
4538 if (access(res
, R_OK
)) {
4539 snprintf(res
, max_len
, "%s%s", dir
, BUILD_SUFFIX
);
4540 if (access(res
, R_OK
)) {
4552 char *qemu_find_file(int type
, const char *name
)
4558 /* If name contains path separators then try it as a straight path. */
4559 if ((strchr(name
, '/') || strchr(name
, '\\'))
4560 && access(name
, R_OK
) == 0) {
4561 return qemu_strdup(name
);
4564 case QEMU_FILE_TYPE_BIOS
:
4567 case QEMU_FILE_TYPE_KEYMAP
:
4568 subdir
= "keymaps/";
4573 len
= strlen(data_dir
) + strlen(name
) + strlen(subdir
) + 2;
4574 buf
= qemu_mallocz(len
);
4575 snprintf(buf
, len
, "%s/%s%s", data_dir
, subdir
, name
);
4576 if (access(buf
, R_OK
)) {
4583 static int device_help_func(QemuOpts
*opts
, void *opaque
)
4585 return qdev_device_help(opts
);
4588 static int device_init_func(QemuOpts
*opts
, void *opaque
)
4592 dev
= qdev_device_add(opts
);
4598 static int chardev_init_func(QemuOpts
*opts
, void *opaque
)
4600 CharDriverState
*chr
;
4602 chr
= qemu_chr_open_opts(opts
, NULL
);
4608 static int mon_init_func(QemuOpts
*opts
, void *opaque
)
4610 CharDriverState
*chr
;
4611 const char *chardev
;
4615 mode
= qemu_opt_get(opts
, "mode");
4619 if (strcmp(mode
, "readline") == 0) {
4620 flags
= MONITOR_USE_READLINE
;
4621 } else if (strcmp(mode
, "control") == 0) {
4622 flags
= MONITOR_USE_CONTROL
;
4624 fprintf(stderr
, "unknown monitor mode \"%s\"\n", mode
);
4628 if (qemu_opt_get_bool(opts
, "default", 0))
4629 flags
|= MONITOR_IS_DEFAULT
;
4631 chardev
= qemu_opt_get(opts
, "chardev");
4632 chr
= qemu_chr_find(chardev
);
4634 fprintf(stderr
, "chardev \"%s\" not found\n", chardev
);
4638 monitor_init(chr
, flags
);
4642 static void monitor_parse(const char *optarg
, const char *mode
)
4644 static int monitor_device_index
= 0;
4650 if (strstart(optarg
, "chardev:", &p
)) {
4651 snprintf(label
, sizeof(label
), "%s", p
);
4653 if (monitor_device_index
) {
4654 snprintf(label
, sizeof(label
), "monitor%d",
4655 monitor_device_index
);
4657 snprintf(label
, sizeof(label
), "monitor");
4660 opts
= qemu_chr_parse_compat(label
, optarg
);
4662 fprintf(stderr
, "parse error: %s\n", optarg
);
4667 opts
= qemu_opts_create(&qemu_mon_opts
, label
, 1);
4669 fprintf(stderr
, "duplicate chardev: %s\n", label
);
4672 qemu_opt_set(opts
, "mode", mode
);
4673 qemu_opt_set(opts
, "chardev", label
);
4675 qemu_opt_set(opts
, "default", "on");
4676 monitor_device_index
++;
4679 struct device_config
{
4681 DEV_USB
, /* -usbdevice */
4683 DEV_SERIAL
, /* -serial */
4684 DEV_PARALLEL
, /* -parallel */
4685 DEV_VIRTCON
, /* -virtioconsole */
4686 DEV_DEBUGCON
, /* -debugcon */
4688 const char *cmdline
;
4689 QTAILQ_ENTRY(device_config
) next
;
4691 QTAILQ_HEAD(, device_config
) device_configs
= QTAILQ_HEAD_INITIALIZER(device_configs
);
4693 static void add_device_config(int type
, const char *cmdline
)
4695 struct device_config
*conf
;
4697 conf
= qemu_mallocz(sizeof(*conf
));
4699 conf
->cmdline
= cmdline
;
4700 QTAILQ_INSERT_TAIL(&device_configs
, conf
, next
);
4703 static int foreach_device_config(int type
, int (*func
)(const char *cmdline
))
4705 struct device_config
*conf
;
4708 QTAILQ_FOREACH(conf
, &device_configs
, next
) {
4709 if (conf
->type
!= type
)
4711 rc
= func(conf
->cmdline
);
4718 static int serial_parse(const char *devname
)
4720 static int index
= 0;
4723 if (strcmp(devname
, "none") == 0)
4725 if (index
== MAX_SERIAL_PORTS
) {
4726 fprintf(stderr
, "qemu: too many serial ports\n");
4729 snprintf(label
, sizeof(label
), "serial%d", index
);
4730 serial_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4731 if (!serial_hds
[index
]) {
4732 fprintf(stderr
, "qemu: could not open serial device '%s': %s\n",
4733 devname
, strerror(errno
));
4740 static int parallel_parse(const char *devname
)
4742 static int index
= 0;
4745 if (strcmp(devname
, "none") == 0)
4747 if (index
== MAX_PARALLEL_PORTS
) {
4748 fprintf(stderr
, "qemu: too many parallel ports\n");
4751 snprintf(label
, sizeof(label
), "parallel%d", index
);
4752 parallel_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4753 if (!parallel_hds
[index
]) {
4754 fprintf(stderr
, "qemu: could not open parallel device '%s': %s\n",
4755 devname
, strerror(errno
));
4762 static int virtcon_parse(const char *devname
)
4764 static int index
= 0;
4766 QemuOpts
*bus_opts
, *dev_opts
;
4768 if (strcmp(devname
, "none") == 0)
4770 if (index
== MAX_VIRTIO_CONSOLES
) {
4771 fprintf(stderr
, "qemu: too many virtio consoles\n");
4775 bus_opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4776 qemu_opt_set(bus_opts
, "driver", "virtio-serial");
4778 dev_opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4779 qemu_opt_set(dev_opts
, "driver", "virtconsole");
4781 snprintf(label
, sizeof(label
), "virtcon%d", index
);
4782 virtcon_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4783 if (!virtcon_hds
[index
]) {
4784 fprintf(stderr
, "qemu: could not open virtio console '%s': %s\n",
4785 devname
, strerror(errno
));
4788 qemu_opt_set(dev_opts
, "chardev", label
);
4794 static int debugcon_parse(const char *devname
)
4798 if (!qemu_chr_open("debugcon", devname
, NULL
)) {
4801 opts
= qemu_opts_create(&qemu_device_opts
, "debugcon", 1);
4803 fprintf(stderr
, "qemu: already have a debugcon device\n");
4806 qemu_opt_set(opts
, "driver", "isa-debugcon");
4807 qemu_opt_set(opts
, "chardev", "debugcon");
4811 static const QEMUOption
*lookup_opt(int argc
, char **argv
,
4812 const char **poptarg
, int *poptind
)
4814 const QEMUOption
*popt
;
4815 int optind
= *poptind
;
4816 char *r
= argv
[optind
];
4819 loc_set_cmdline(argv
, optind
, 1);
4821 /* Treat --foo the same as -foo. */
4824 popt
= qemu_options
;
4827 error_report("invalid option");
4830 if (!strcmp(popt
->name
, r
+ 1))
4834 if (popt
->flags
& HAS_ARG
) {
4835 if (optind
>= argc
) {
4836 error_report("requires an argument");
4839 optarg
= argv
[optind
++];
4840 loc_set_cmdline(argv
, optind
- 2, 2);
4851 int main(int argc
, char **argv
, char **envp
)
4853 const char *gdbstub_dev
= NULL
;
4854 uint32_t boot_devices_bitmap
= 0;
4856 int snapshot
, linux_boot
, net_boot
;
4857 const char *initrd_filename
;
4858 const char *kernel_filename
, *kernel_cmdline
;
4859 char boot_devices
[33] = "cad"; /* default to HD->floppy->CD-ROM */
4861 DisplayChangeListener
*dcl
;
4862 int cyls
, heads
, secs
, translation
;
4863 QemuOpts
*hda_opts
= NULL
, *opts
;
4866 const char *loadvm
= NULL
;
4867 QEMUMachine
*machine
;
4868 const char *cpu_model
;
4873 const char *pid_file
= NULL
;
4874 const char *incoming
= NULL
;
4877 struct passwd
*pwd
= NULL
;
4878 const char *chroot_dir
= NULL
;
4879 const char *run_as
= NULL
;
4882 int show_vnc_port
= 0;
4885 error_set_progname(argv
[0]);
4889 qemu_cache_utils_init(envp
);
4891 QLIST_INIT (&vm_change_state_head
);
4894 struct sigaction act
;
4895 sigfillset(&act
.sa_mask
);
4897 act
.sa_handler
= SIG_IGN
;
4898 sigaction(SIGPIPE
, &act
, NULL
);
4901 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4902 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4903 QEMU to run on a single CPU */
4908 h
= GetCurrentProcess();
4909 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4910 for(i
= 0; i
< 32; i
++) {
4911 if (mask
& (1 << i
))
4916 SetProcessAffinityMask(h
, mask
);
4922 module_call_init(MODULE_INIT_MACHINE
);
4923 machine
= find_default_machine();
4925 initrd_filename
= NULL
;
4928 kernel_filename
= NULL
;
4929 kernel_cmdline
= "";
4930 cyls
= heads
= secs
= 0;
4931 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4933 for (i
= 0; i
< MAX_NODES
; i
++) {
4935 node_cpumask
[i
] = 0;
4944 /* first pass of option parsing */
4946 while (optind
< argc
) {
4947 if (argv
[optind
][0] != '-') {
4952 const QEMUOption
*popt
;
4954 popt
= lookup_opt(argc
, argv
, &optarg
, &optind
);
4955 switch (popt
->index
) {
4956 case QEMU_OPTION_nodefconfig
:
4967 fname
= CONFIG_QEMU_CONFDIR
"/qemu.conf";
4968 fp
= fopen(fname
, "r");
4970 if (qemu_config_parse(fp
, fname
) != 0) {
4976 fname
= CONFIG_QEMU_CONFDIR
"/target-" TARGET_ARCH
".conf";
4977 fp
= fopen(fname
, "r");
4979 if (qemu_config_parse(fp
, fname
) != 0) {
4985 #if defined(cpudef_setup)
4986 cpudef_setup(); /* parse cpu definitions in target config file */
4989 /* second pass of option parsing */
4994 if (argv
[optind
][0] != '-') {
4995 hda_opts
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
4997 const QEMUOption
*popt
;
4999 popt
= lookup_opt(argc
, argv
, &optarg
, &optind
);
5000 switch(popt
->index
) {
5002 machine
= find_machine(optarg
);
5005 printf("Supported machines are:\n");
5006 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5008 printf("%-10s %s (alias of %s)\n",
5009 m
->alias
, m
->desc
, m
->name
);
5010 printf("%-10s %s%s\n",
5012 m
->is_default
? " (default)" : "");
5014 exit(*optarg
!= '?');
5017 case QEMU_OPTION_cpu
:
5018 /* hw initialization will check this */
5019 if (*optarg
== '?') {
5020 /* XXX: implement xxx_cpu_list for targets that still miss it */
5021 #if defined(cpu_list_id)
5022 cpu_list_id(stdout
, &fprintf
, optarg
);
5023 #elif defined(cpu_list)
5024 cpu_list(stdout
, &fprintf
); /* deprecated */
5031 case QEMU_OPTION_initrd
:
5032 initrd_filename
= optarg
;
5034 case QEMU_OPTION_hda
:
5036 hda_opts
= drive_add(optarg
, HD_ALIAS
, 0);
5038 hda_opts
= drive_add(optarg
, HD_ALIAS
5039 ",cyls=%d,heads=%d,secs=%d%s",
5040 0, cyls
, heads
, secs
,
5041 translation
== BIOS_ATA_TRANSLATION_LBA
?
5043 translation
== BIOS_ATA_TRANSLATION_NONE
?
5044 ",trans=none" : "");
5046 case QEMU_OPTION_hdb
:
5047 case QEMU_OPTION_hdc
:
5048 case QEMU_OPTION_hdd
:
5049 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
5051 case QEMU_OPTION_drive
:
5052 drive_add(NULL
, "%s", optarg
);
5054 case QEMU_OPTION_set
:
5055 if (qemu_set_option(optarg
) != 0)
5058 case QEMU_OPTION_global
:
5059 if (qemu_global_option(optarg
) != 0)
5062 case QEMU_OPTION_mtdblock
:
5063 drive_add(optarg
, MTD_ALIAS
);
5065 case QEMU_OPTION_sd
:
5066 drive_add(optarg
, SD_ALIAS
);
5068 case QEMU_OPTION_pflash
:
5069 drive_add(optarg
, PFLASH_ALIAS
);
5071 case QEMU_OPTION_snapshot
:
5074 case QEMU_OPTION_hdachs
:
5078 cyls
= strtol(p
, (char **)&p
, 0);
5079 if (cyls
< 1 || cyls
> 16383)
5084 heads
= strtol(p
, (char **)&p
, 0);
5085 if (heads
< 1 || heads
> 16)
5090 secs
= strtol(p
, (char **)&p
, 0);
5091 if (secs
< 1 || secs
> 63)
5095 if (!strcmp(p
, "none"))
5096 translation
= BIOS_ATA_TRANSLATION_NONE
;
5097 else if (!strcmp(p
, "lba"))
5098 translation
= BIOS_ATA_TRANSLATION_LBA
;
5099 else if (!strcmp(p
, "auto"))
5100 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5103 } else if (*p
!= '\0') {
5105 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5108 if (hda_opts
!= NULL
) {
5110 snprintf(num
, sizeof(num
), "%d", cyls
);
5111 qemu_opt_set(hda_opts
, "cyls", num
);
5112 snprintf(num
, sizeof(num
), "%d", heads
);
5113 qemu_opt_set(hda_opts
, "heads", num
);
5114 snprintf(num
, sizeof(num
), "%d", secs
);
5115 qemu_opt_set(hda_opts
, "secs", num
);
5116 if (translation
== BIOS_ATA_TRANSLATION_LBA
)
5117 qemu_opt_set(hda_opts
, "trans", "lba");
5118 if (translation
== BIOS_ATA_TRANSLATION_NONE
)
5119 qemu_opt_set(hda_opts
, "trans", "none");
5123 case QEMU_OPTION_numa
:
5124 if (nb_numa_nodes
>= MAX_NODES
) {
5125 fprintf(stderr
, "qemu: too many NUMA nodes\n");
5130 case QEMU_OPTION_nographic
:
5131 display_type
= DT_NOGRAPHIC
;
5133 #ifdef CONFIG_CURSES
5134 case QEMU_OPTION_curses
:
5135 display_type
= DT_CURSES
;
5138 case QEMU_OPTION_portrait
:
5141 case QEMU_OPTION_kernel
:
5142 kernel_filename
= optarg
;
5144 case QEMU_OPTION_append
:
5145 kernel_cmdline
= optarg
;
5147 case QEMU_OPTION_cdrom
:
5148 drive_add(optarg
, CDROM_ALIAS
);
5150 case QEMU_OPTION_boot
:
5152 static const char * const params
[] = {
5153 "order", "once", "menu", NULL
5155 char buf
[sizeof(boot_devices
)];
5156 char *standard_boot_devices
;
5159 if (!strchr(optarg
, '=')) {
5161 pstrcpy(buf
, sizeof(buf
), optarg
);
5162 } else if (check_params(buf
, sizeof(buf
), params
, optarg
) < 0) {
5164 "qemu: unknown boot parameter '%s' in '%s'\n",
5170 get_param_value(buf
, sizeof(buf
), "order", optarg
)) {
5171 boot_devices_bitmap
= parse_bootdevices(buf
);
5172 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5175 if (get_param_value(buf
, sizeof(buf
),
5177 boot_devices_bitmap
|= parse_bootdevices(buf
);
5178 standard_boot_devices
= qemu_strdup(boot_devices
);
5179 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5180 qemu_register_reset(restore_boot_devices
,
5181 standard_boot_devices
);
5183 if (get_param_value(buf
, sizeof(buf
),
5185 if (!strcmp(buf
, "on")) {
5187 } else if (!strcmp(buf
, "off")) {
5191 "qemu: invalid option value '%s'\n",
5199 case QEMU_OPTION_fda
:
5200 case QEMU_OPTION_fdb
:
5201 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
5204 case QEMU_OPTION_no_fd_bootchk
:
5208 case QEMU_OPTION_netdev
:
5209 if (net_client_parse(&qemu_netdev_opts
, optarg
) == -1) {
5213 case QEMU_OPTION_net
:
5214 if (net_client_parse(&qemu_net_opts
, optarg
) == -1) {
5219 case QEMU_OPTION_tftp
:
5220 legacy_tftp_prefix
= optarg
;
5222 case QEMU_OPTION_bootp
:
5223 legacy_bootp_filename
= optarg
;
5226 case QEMU_OPTION_smb
:
5227 if (net_slirp_smb(optarg
) < 0)
5231 case QEMU_OPTION_redir
:
5232 if (net_slirp_redir(optarg
) < 0)
5236 case QEMU_OPTION_bt
:
5237 add_device_config(DEV_BT
, optarg
);
5240 case QEMU_OPTION_audio_help
:
5244 case QEMU_OPTION_soundhw
:
5245 select_soundhw (optarg
);
5251 case QEMU_OPTION_version
:
5255 case QEMU_OPTION_m
: {
5259 value
= strtoul(optarg
, &ptr
, 10);
5261 case 0: case 'M': case 'm':
5268 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5272 /* On 32-bit hosts, QEMU is limited by virtual address space */
5273 if (value
> (2047 << 20) && HOST_LONG_BITS
== 32) {
5274 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5277 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5278 fprintf(stderr
, "qemu: ram size too large\n");
5284 case QEMU_OPTION_mempath
:
5288 case QEMU_OPTION_mem_prealloc
:
5295 const CPULogItem
*item
;
5297 mask
= cpu_str_to_log_mask(optarg
);
5299 printf("Log items (comma separated):\n");
5300 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5301 printf("%-10s %s\n", item
->name
, item
->help
);
5309 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5311 case QEMU_OPTION_gdb
:
5312 gdbstub_dev
= optarg
;
5317 case QEMU_OPTION_bios
:
5320 case QEMU_OPTION_singlestep
:
5327 keyboard_layout
= optarg
;
5329 case QEMU_OPTION_localtime
:
5332 case QEMU_OPTION_vga
:
5333 select_vgahw (optarg
);
5335 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5341 w
= strtol(p
, (char **)&p
, 10);
5344 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5350 h
= strtol(p
, (char **)&p
, 10);
5355 depth
= strtol(p
, (char **)&p
, 10);
5356 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5357 depth
!= 24 && depth
!= 32)
5359 } else if (*p
== '\0') {
5360 depth
= graphic_depth
;
5367 graphic_depth
= depth
;
5371 case QEMU_OPTION_echr
:
5374 term_escape_char
= strtol(optarg
, &r
, 0);
5376 printf("Bad argument to echr\n");
5379 case QEMU_OPTION_monitor
:
5380 monitor_parse(optarg
, "readline");
5381 default_monitor
= 0;
5383 case QEMU_OPTION_qmp
:
5384 monitor_parse(optarg
, "control");
5385 default_monitor
= 0;
5387 case QEMU_OPTION_mon
:
5388 opts
= qemu_opts_parse(&qemu_mon_opts
, optarg
, 1);
5390 fprintf(stderr
, "parse error: %s\n", optarg
);
5393 default_monitor
= 0;
5395 case QEMU_OPTION_chardev
:
5396 opts
= qemu_opts_parse(&qemu_chardev_opts
, optarg
, 1);
5398 fprintf(stderr
, "parse error: %s\n", optarg
);
5402 case QEMU_OPTION_serial
:
5403 add_device_config(DEV_SERIAL
, optarg
);
5405 if (strncmp(optarg
, "mon:", 4) == 0) {
5406 default_monitor
= 0;
5409 case QEMU_OPTION_watchdog
:
5412 "qemu: only one watchdog option may be given\n");
5417 case QEMU_OPTION_watchdog_action
:
5418 if (select_watchdog_action(optarg
) == -1) {
5419 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5423 case QEMU_OPTION_virtiocon
:
5424 add_device_config(DEV_VIRTCON
, optarg
);
5425 default_virtcon
= 0;
5426 if (strncmp(optarg
, "mon:", 4) == 0) {
5427 default_monitor
= 0;
5430 case QEMU_OPTION_parallel
:
5431 add_device_config(DEV_PARALLEL
, optarg
);
5432 default_parallel
= 0;
5433 if (strncmp(optarg
, "mon:", 4) == 0) {
5434 default_monitor
= 0;
5437 case QEMU_OPTION_debugcon
:
5438 add_device_config(DEV_DEBUGCON
, optarg
);
5440 case QEMU_OPTION_loadvm
:
5443 case QEMU_OPTION_full_screen
:
5447 case QEMU_OPTION_no_frame
:
5450 case QEMU_OPTION_alt_grab
:
5453 case QEMU_OPTION_ctrl_grab
:
5456 case QEMU_OPTION_no_quit
:
5459 case QEMU_OPTION_sdl
:
5460 display_type
= DT_SDL
;
5463 case QEMU_OPTION_pidfile
:
5467 case QEMU_OPTION_win2k_hack
:
5468 win2k_install_hack
= 1;
5470 case QEMU_OPTION_rtc_td_hack
:
5473 case QEMU_OPTION_acpitable
:
5474 if(acpi_table_add(optarg
) < 0) {
5475 fprintf(stderr
, "Wrong acpi table provided\n");
5479 case QEMU_OPTION_smbios
:
5480 if(smbios_entry_add(optarg
) < 0) {
5481 fprintf(stderr
, "Wrong smbios provided\n");
5487 case QEMU_OPTION_enable_kvm
:
5491 case QEMU_OPTION_usb
:
5494 case QEMU_OPTION_usbdevice
:
5496 add_device_config(DEV_USB
, optarg
);
5498 case QEMU_OPTION_device
:
5499 if (!qemu_opts_parse(&qemu_device_opts
, optarg
, 1)) {
5503 case QEMU_OPTION_smp
:
5506 fprintf(stderr
, "Invalid number of CPUs\n");
5509 if (max_cpus
< smp_cpus
) {
5510 fprintf(stderr
, "maxcpus must be equal to or greater than "
5514 if (max_cpus
> 255) {
5515 fprintf(stderr
, "Unsupported number of maxcpus\n");
5519 case QEMU_OPTION_vnc
:
5520 display_type
= DT_VNC
;
5521 vnc_display
= optarg
;
5524 case QEMU_OPTION_no_acpi
:
5527 case QEMU_OPTION_no_hpet
:
5530 case QEMU_OPTION_balloon
:
5531 if (balloon_parse(optarg
) < 0) {
5532 fprintf(stderr
, "Unknown -balloon argument %s\n", optarg
);
5537 case QEMU_OPTION_no_reboot
:
5540 case QEMU_OPTION_no_shutdown
:
5543 case QEMU_OPTION_show_cursor
:
5546 case QEMU_OPTION_uuid
:
5547 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5548 fprintf(stderr
, "Fail to parse UUID string."
5549 " Wrong format.\n");
5554 case QEMU_OPTION_daemonize
:
5558 case QEMU_OPTION_option_rom
:
5559 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5560 fprintf(stderr
, "Too many option ROMs\n");
5563 option_rom
[nb_option_roms
] = optarg
;
5566 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5567 case QEMU_OPTION_semihosting
:
5568 semihosting_enabled
= 1;
5571 case QEMU_OPTION_name
:
5572 qemu_name
= qemu_strdup(optarg
);
5574 char *p
= strchr(qemu_name
, ',');
5577 if (strncmp(p
, "process=", 8)) {
5578 fprintf(stderr
, "Unknown subargument %s to -name", p
);
5586 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5587 case QEMU_OPTION_prom_env
:
5588 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5589 fprintf(stderr
, "Too many prom variables\n");
5592 prom_envs
[nb_prom_envs
] = optarg
;
5597 case QEMU_OPTION_old_param
:
5601 case QEMU_OPTION_clock
:
5602 configure_alarms(optarg
);
5604 case QEMU_OPTION_startdate
:
5605 configure_rtc_date_offset(optarg
, 1);
5607 case QEMU_OPTION_rtc
:
5608 opts
= qemu_opts_parse(&qemu_rtc_opts
, optarg
, 0);
5610 fprintf(stderr
, "parse error: %s\n", optarg
);
5613 configure_rtc(opts
);
5615 case QEMU_OPTION_tb_size
:
5616 tb_size
= strtol(optarg
, NULL
, 0);
5620 case QEMU_OPTION_icount
:
5622 if (strcmp(optarg
, "auto") == 0) {
5623 icount_time_shift
= -1;
5625 icount_time_shift
= strtol(optarg
, NULL
, 0);
5628 case QEMU_OPTION_incoming
:
5631 case QEMU_OPTION_nodefaults
:
5633 default_parallel
= 0;
5634 default_virtcon
= 0;
5635 default_monitor
= 0;
5643 case QEMU_OPTION_chroot
:
5644 chroot_dir
= optarg
;
5646 case QEMU_OPTION_runas
:
5651 case QEMU_OPTION_xen_domid
:
5652 xen_domid
= atoi(optarg
);
5654 case QEMU_OPTION_xen_create
:
5655 xen_mode
= XEN_CREATE
;
5657 case QEMU_OPTION_xen_attach
:
5658 xen_mode
= XEN_ATTACH
;
5661 case QEMU_OPTION_readconfig
:
5664 fp
= fopen(optarg
, "r");
5666 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5669 if (qemu_config_parse(fp
, optarg
) != 0) {
5675 case QEMU_OPTION_writeconfig
:
5678 if (strcmp(optarg
, "-") == 0) {
5681 fp
= fopen(optarg
, "w");
5683 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5687 qemu_config_write(fp
);
5696 /* If no data_dir is specified then try to find it relative to the
5699 data_dir
= find_datadir(argv
[0]);
5701 /* If all else fails use the install patch specified when building. */
5703 data_dir
= CONFIG_QEMU_SHAREDIR
;
5707 * Default to max_cpus = smp_cpus, in case the user doesn't
5708 * specify a max_cpus value.
5711 max_cpus
= smp_cpus
;
5713 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5714 if (smp_cpus
> machine
->max_cpus
) {
5715 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5716 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5721 qemu_opts_foreach(&qemu_device_opts
, default_driver_check
, NULL
, 0);
5722 qemu_opts_foreach(&qemu_global_opts
, default_driver_check
, NULL
, 0);
5724 if (machine
->no_serial
) {
5727 if (machine
->no_parallel
) {
5728 default_parallel
= 0;
5730 if (!machine
->use_virtcon
) {
5731 default_virtcon
= 0;
5733 if (machine
->no_vga
) {
5736 if (machine
->no_floppy
) {
5739 if (machine
->no_cdrom
) {
5742 if (machine
->no_sdcard
) {
5746 if (display_type
== DT_NOGRAPHIC
) {
5747 if (default_parallel
)
5748 add_device_config(DEV_PARALLEL
, "null");
5749 if (default_serial
&& default_monitor
) {
5750 add_device_config(DEV_SERIAL
, "mon:stdio");
5751 } else if (default_virtcon
&& default_monitor
) {
5752 add_device_config(DEV_VIRTCON
, "mon:stdio");
5755 add_device_config(DEV_SERIAL
, "stdio");
5756 if (default_virtcon
)
5757 add_device_config(DEV_VIRTCON
, "stdio");
5758 if (default_monitor
)
5759 monitor_parse("stdio", "readline");
5763 add_device_config(DEV_SERIAL
, "vc:80Cx24C");
5764 if (default_parallel
)
5765 add_device_config(DEV_PARALLEL
, "vc:80Cx24C");
5766 if (default_monitor
)
5767 monitor_parse("vc:80Cx24C", "readline");
5768 if (default_virtcon
)
5769 add_device_config(DEV_VIRTCON
, "vc:80Cx24C");
5772 vga_interface_type
= VGA_CIRRUS
;
5774 if (qemu_opts_foreach(&qemu_chardev_opts
, chardev_init_func
, NULL
, 1) != 0)
5781 if (pipe(fds
) == -1)
5792 len
= read(fds
[0], &status
, 1);
5793 if (len
== -1 && (errno
== EINTR
))
5798 else if (status
== 1) {
5799 fprintf(stderr
, "Could not acquire pidfile: %s\n", strerror(errno
));
5807 qemu_set_cloexec(fds
[1]);
5819 signal(SIGTSTP
, SIG_IGN
);
5820 signal(SIGTTOU
, SIG_IGN
);
5821 signal(SIGTTIN
, SIG_IGN
);
5825 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5829 if (write(fds
[1], &status
, 1) != 1) {
5830 perror("daemonize. Writing to pipe\n");
5834 fprintf(stderr
, "Could not acquire pid file: %s\n", strerror(errno
));
5838 if (kvm_enabled()) {
5841 ret
= kvm_init(smp_cpus
);
5843 fprintf(stderr
, "failed to initialize KVM\n");
5848 if (qemu_init_main_loop()) {
5849 fprintf(stderr
, "qemu_init_main_loop failed\n");
5852 linux_boot
= (kernel_filename
!= NULL
);
5854 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5855 fprintf(stderr
, "-append only allowed with -kernel option\n");
5859 if (!linux_boot
&& initrd_filename
!= NULL
) {
5860 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5865 /* Win32 doesn't support line-buffering and requires size >= 2 */
5866 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5869 if (init_timer_alarm() < 0) {
5870 fprintf(stderr
, "could not initialize alarm timer\n");
5873 if (use_icount
&& icount_time_shift
< 0) {
5875 /* 125MIPS seems a reasonable initial guess at the guest speed.
5876 It will be corrected fairly quickly anyway. */
5877 icount_time_shift
= 3;
5878 init_icount_adjust();
5885 if (net_init_clients() < 0) {
5889 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5890 net_set_boot_mask(net_boot
);
5892 /* init the bluetooth world */
5893 if (foreach_device_config(DEV_BT
, bt_parse
))
5896 /* init the memory */
5898 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5900 /* init the dynamic translator */
5901 cpu_exec_init_all(tb_size
* 1024 * 1024);
5903 bdrv_init_with_whitelist();
5907 if (default_cdrom
) {
5908 /* we always create the cdrom drive, even if no disk is there */
5909 drive_add(NULL
, CDROM_ALIAS
);
5912 if (default_floppy
) {
5913 /* we always create at least one floppy */
5914 drive_add(NULL
, FD_ALIAS
, 0);
5917 if (default_sdcard
) {
5918 /* we always create one sd slot, even if no card is in it */
5919 drive_add(NULL
, SD_ALIAS
);
5922 /* open the virtual block devices */
5924 qemu_opts_foreach(&qemu_drive_opts
, drive_enable_snapshot
, NULL
, 0);
5925 if (qemu_opts_foreach(&qemu_drive_opts
, drive_init_func
, machine
, 1) != 0)
5928 vmstate_register(0, &vmstate_timers
,&timers_state
);
5929 register_savevm_live("ram", 0, 3, NULL
, ram_save_live
, NULL
,
5932 if (nb_numa_nodes
> 0) {
5935 if (nb_numa_nodes
> smp_cpus
) {
5936 nb_numa_nodes
= smp_cpus
;
5939 /* If no memory size if given for any node, assume the default case
5940 * and distribute the available memory equally across all nodes
5942 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5943 if (node_mem
[i
] != 0)
5946 if (i
== nb_numa_nodes
) {
5947 uint64_t usedmem
= 0;
5949 /* On Linux, the each node's border has to be 8MB aligned,
5950 * the final node gets the rest.
5952 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
5953 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
5954 usedmem
+= node_mem
[i
];
5956 node_mem
[i
] = ram_size
- usedmem
;
5959 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5960 if (node_cpumask
[i
] != 0)
5963 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5964 * must cope with this anyway, because there are BIOSes out there in
5965 * real machines which also use this scheme.
5967 if (i
== nb_numa_nodes
) {
5968 for (i
= 0; i
< smp_cpus
; i
++) {
5969 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
5974 if (foreach_device_config(DEV_SERIAL
, serial_parse
) < 0)
5976 if (foreach_device_config(DEV_PARALLEL
, parallel_parse
) < 0)
5978 if (foreach_device_config(DEV_VIRTCON
, virtcon_parse
) < 0)
5980 if (foreach_device_config(DEV_DEBUGCON
, debugcon_parse
) < 0)
5983 module_call_init(MODULE_INIT_DEVICE
);
5985 if (qemu_opts_foreach(&qemu_device_opts
, device_help_func
, NULL
, 0) != 0)
5989 i
= select_watchdog(watchdog
);
5991 exit (i
== 1 ? 1 : 0);
5994 if (machine
->compat_props
) {
5995 qdev_prop_register_global_list(machine
->compat_props
);
5999 machine
->init(ram_size
, boot_devices
,
6000 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
6002 cpu_synchronize_all_post_init();
6005 /* must be after terminal init, SDL library changes signal handlers */
6009 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
6010 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6011 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
6017 current_machine
= machine
;
6019 /* init USB devices */
6021 if (foreach_device_config(DEV_USB
, usb_parse
) < 0)
6025 /* init generic devices */
6026 if (qemu_opts_foreach(&qemu_device_opts
, device_init_func
, NULL
, 1) != 0)
6029 net_check_clients();
6031 /* just use the first displaystate for the moment */
6032 ds
= get_displaystate();
6034 if (display_type
== DT_DEFAULT
) {
6035 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6036 display_type
= DT_SDL
;
6038 display_type
= DT_VNC
;
6039 vnc_display
= "localhost:0,to=99";
6045 switch (display_type
) {
6048 #if defined(CONFIG_CURSES)
6050 curses_display_init(ds
, full_screen
);
6053 #if defined(CONFIG_SDL)
6055 sdl_display_init(ds
, full_screen
, no_frame
);
6057 #elif defined(CONFIG_COCOA)
6059 cocoa_display_init(ds
, full_screen
);
6063 vnc_display_init(ds
);
6064 if (vnc_display_open(ds
, vnc_display
) < 0)
6067 if (show_vnc_port
) {
6068 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
6076 dcl
= ds
->listeners
;
6077 while (dcl
!= NULL
) {
6078 if (dcl
->dpy_refresh
!= NULL
) {
6079 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
6080 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
6085 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
6086 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
6087 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
6090 text_consoles_set_display(ds
);
6092 if (qemu_opts_foreach(&qemu_mon_opts
, mon_init_func
, NULL
, 1) != 0)
6095 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
6096 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
6101 qdev_machine_creation_done();
6103 if (rom_load_all() != 0) {
6104 fprintf(stderr
, "rom loading failed\n");
6108 qemu_system_reset();
6110 if (load_vmstate(loadvm
) < 0) {
6116 qemu_start_incoming_migration(incoming
);
6117 } else if (autostart
) {
6127 len
= write(fds
[1], &status
, 1);
6128 if (len
== -1 && (errno
== EINTR
))
6135 perror("not able to chdir to /");
6138 TFR(fd
= qemu_open("/dev/null", O_RDWR
));
6144 pwd
= getpwnam(run_as
);
6146 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
6152 if (chroot(chroot_dir
) < 0) {
6153 fprintf(stderr
, "chroot failed\n");
6157 perror("not able to chdir to /");
6163 if (setgid(pwd
->pw_gid
) < 0) {
6164 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
6167 if (setuid(pwd
->pw_uid
) < 0) {
6168 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
6171 if (setuid(0) != -1) {
6172 fprintf(stderr
, "Dropping privileges failed\n");