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
581 /* XXX: add frequency */
589 struct QEMUTimer
*next
;
592 struct qemu_alarm_timer
{
594 int (*start
)(struct qemu_alarm_timer
*t
);
595 void (*stop
)(struct qemu_alarm_timer
*t
);
596 void (*rearm
)(struct qemu_alarm_timer
*t
);
603 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
608 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
610 if (!alarm_has_dynticks(t
))
616 /* TODO: MIN_TIMER_REARM_US should be optimized */
617 #define MIN_TIMER_REARM_US 250
619 static struct qemu_alarm_timer
*alarm_timer
;
623 struct qemu_alarm_win32
{
626 } alarm_win32_data
= {0, 0};
628 static int win32_start_timer(struct qemu_alarm_timer
*t
);
629 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
630 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
634 static int unix_start_timer(struct qemu_alarm_timer
*t
);
635 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
639 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
640 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
641 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
643 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
644 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
646 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
647 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
649 #endif /* __linux__ */
653 /* Correlation between real and virtual time is always going to be
654 fairly approximate, so ignore small variation.
655 When the guest is idle real and virtual time will be aligned in
657 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
659 static void icount_adjust(void)
664 static int64_t last_delta
;
665 /* If the VM is not running, then do nothing. */
669 cur_time
= cpu_get_clock();
670 cur_icount
= qemu_get_clock(vm_clock
);
671 delta
= cur_icount
- cur_time
;
672 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
674 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
675 && icount_time_shift
> 0) {
676 /* The guest is getting too far ahead. Slow time down. */
680 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
681 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
682 /* The guest is getting too far behind. Speed time up. */
686 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
689 static void icount_adjust_rt(void * opaque
)
691 qemu_mod_timer(icount_rt_timer
,
692 qemu_get_clock(rt_clock
) + 1000);
696 static void icount_adjust_vm(void * opaque
)
698 qemu_mod_timer(icount_vm_timer
,
699 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
703 static void init_icount_adjust(void)
705 /* Have both realtime and virtual time triggers for speed adjustment.
706 The realtime trigger catches emulated time passing too slowly,
707 the virtual time trigger catches emulated time passing too fast.
708 Realtime triggers occur even when idle, so use them less frequently
710 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
711 qemu_mod_timer(icount_rt_timer
,
712 qemu_get_clock(rt_clock
) + 1000);
713 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
714 qemu_mod_timer(icount_vm_timer
,
715 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
718 static struct qemu_alarm_timer alarm_timers
[] = {
721 {"dynticks", dynticks_start_timer
,
722 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
723 /* HPET - if available - is preferred */
724 {"hpet", hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
725 /* ...otherwise try RTC */
726 {"rtc", rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
728 {"unix", unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
730 {"dynticks", win32_start_timer
,
731 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
732 {"win32", win32_start_timer
,
733 win32_stop_timer
, NULL
, &alarm_win32_data
},
738 static void show_available_alarms(void)
742 printf("Available alarm timers, in order of precedence:\n");
743 for (i
= 0; alarm_timers
[i
].name
; i
++)
744 printf("%s\n", alarm_timers
[i
].name
);
747 static void configure_alarms(char const *opt
)
751 int count
= ARRAY_SIZE(alarm_timers
) - 1;
754 struct qemu_alarm_timer tmp
;
756 if (!strcmp(opt
, "?")) {
757 show_available_alarms();
761 arg
= qemu_strdup(opt
);
763 /* Reorder the array */
764 name
= strtok(arg
, ",");
766 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
767 if (!strcmp(alarm_timers
[i
].name
, name
))
772 fprintf(stderr
, "Unknown clock %s\n", name
);
781 tmp
= alarm_timers
[i
];
782 alarm_timers
[i
] = alarm_timers
[cur
];
783 alarm_timers
[cur
] = tmp
;
787 name
= strtok(NULL
, ",");
793 /* Disable remaining timers */
794 for (i
= cur
; i
< count
; i
++)
795 alarm_timers
[i
].name
= NULL
;
797 show_available_alarms();
802 #define QEMU_NUM_CLOCKS 3
806 QEMUClock
*host_clock
;
808 static QEMUTimer
*active_timers
[QEMU_NUM_CLOCKS
];
810 static QEMUClock
*qemu_new_clock(int type
)
813 clock
= qemu_mallocz(sizeof(QEMUClock
));
818 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
822 ts
= qemu_mallocz(sizeof(QEMUTimer
));
829 void qemu_free_timer(QEMUTimer
*ts
)
834 /* stop a timer, but do not dealloc it */
835 void qemu_del_timer(QEMUTimer
*ts
)
839 /* NOTE: this code must be signal safe because
840 qemu_timer_expired() can be called from a signal. */
841 pt
= &active_timers
[ts
->clock
->type
];
854 /* modify the current timer so that it will be fired when current_time
855 >= expire_time. The corresponding callback will be called. */
856 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
862 /* add the timer in the sorted list */
863 /* NOTE: this code must be signal safe because
864 qemu_timer_expired() can be called from a signal. */
865 pt
= &active_timers
[ts
->clock
->type
];
870 if (t
->expire_time
> expire_time
)
874 ts
->expire_time
= expire_time
;
878 /* Rearm if necessary */
879 if (pt
== &active_timers
[ts
->clock
->type
]) {
880 if (!alarm_timer
->pending
) {
881 qemu_rearm_alarm_timer(alarm_timer
);
883 /* Interrupt execution to force deadline recalculation. */
889 int qemu_timer_pending(QEMUTimer
*ts
)
892 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
899 int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
903 return (timer_head
->expire_time
<= current_time
);
906 static void qemu_run_timers(QEMUClock
*clock
)
908 QEMUTimer
**ptimer_head
, *ts
;
909 int64_t current_time
;
911 current_time
= qemu_get_clock (clock
);
912 ptimer_head
= &active_timers
[clock
->type
];
915 if (!ts
|| ts
->expire_time
> current_time
)
917 /* remove timer from the list before calling the callback */
918 *ptimer_head
= ts
->next
;
921 /* run the callback (the timer list can be modified) */
926 int64_t qemu_get_clock(QEMUClock
*clock
)
928 switch(clock
->type
) {
929 case QEMU_CLOCK_REALTIME
:
930 return get_clock() / 1000000;
932 case QEMU_CLOCK_VIRTUAL
:
934 return cpu_get_icount();
936 return cpu_get_clock();
938 case QEMU_CLOCK_HOST
:
939 return get_clock_realtime();
943 int64_t qemu_get_clock_ns(QEMUClock
*clock
)
945 switch(clock
->type
) {
946 case QEMU_CLOCK_REALTIME
:
949 case QEMU_CLOCK_VIRTUAL
:
951 return cpu_get_icount();
953 return cpu_get_clock();
955 case QEMU_CLOCK_HOST
:
956 return get_clock_realtime();
960 static void init_clocks(void)
963 rt_clock
= qemu_new_clock(QEMU_CLOCK_REALTIME
);
964 vm_clock
= qemu_new_clock(QEMU_CLOCK_VIRTUAL
);
965 host_clock
= qemu_new_clock(QEMU_CLOCK_HOST
);
967 rtc_clock
= host_clock
;
971 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
973 uint64_t expire_time
;
975 if (qemu_timer_pending(ts
)) {
976 expire_time
= ts
->expire_time
;
980 qemu_put_be64(f
, expire_time
);
983 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
985 uint64_t expire_time
;
987 expire_time
= qemu_get_be64(f
);
988 if (expire_time
!= -1) {
989 qemu_mod_timer(ts
, expire_time
);
995 static const VMStateDescription vmstate_timers
= {
998 .minimum_version_id
= 1,
999 .minimum_version_id_old
= 1,
1000 .fields
= (VMStateField
[]) {
1001 VMSTATE_INT64(cpu_ticks_offset
, TimersState
),
1002 VMSTATE_INT64(dummy
, TimersState
),
1003 VMSTATE_INT64_V(cpu_clock_offset
, TimersState
, 2),
1004 VMSTATE_END_OF_LIST()
1008 static void qemu_run_all_timers(void)
1010 /* rearm timer, if not periodic */
1011 if (alarm_timer
->expired
) {
1012 alarm_timer
->expired
= 0;
1013 qemu_rearm_alarm_timer(alarm_timer
);
1016 alarm_timer
->pending
= 0;
1018 /* vm time timers */
1020 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
1021 qemu_run_timers(vm_clock
);
1024 qemu_run_timers(rt_clock
);
1025 qemu_run_timers(host_clock
);
1029 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1030 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1033 static void host_alarm_handler(int host_signum
)
1036 struct qemu_alarm_timer
*t
= alarm_timer
;
1041 #define DISP_FREQ 1000
1043 static int64_t delta_min
= INT64_MAX
;
1044 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1046 ti
= qemu_get_clock(vm_clock
);
1047 if (last_clock
!= 0) {
1048 delta
= ti
- last_clock
;
1049 if (delta
< delta_min
)
1051 if (delta
> delta_max
)
1054 if (++count
== DISP_FREQ
) {
1055 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1056 muldiv64(delta_min
, 1000000, get_ticks_per_sec()),
1057 muldiv64(delta_max
, 1000000, get_ticks_per_sec()),
1058 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, get_ticks_per_sec()),
1059 (double)get_ticks_per_sec() / ((double)delta_cum
/ DISP_FREQ
));
1061 delta_min
= INT64_MAX
;
1069 if (alarm_has_dynticks(t
) ||
1071 qemu_timer_expired(active_timers
[QEMU_CLOCK_VIRTUAL
],
1072 qemu_get_clock(vm_clock
))) ||
1073 qemu_timer_expired(active_timers
[QEMU_CLOCK_REALTIME
],
1074 qemu_get_clock(rt_clock
)) ||
1075 qemu_timer_expired(active_timers
[QEMU_CLOCK_HOST
],
1076 qemu_get_clock(host_clock
))) {
1078 t
->expired
= alarm_has_dynticks(t
);
1080 qemu_notify_event();
1084 static int64_t qemu_next_deadline(void)
1086 /* To avoid problems with overflow limit this to 2^32. */
1087 int64_t delta
= INT32_MAX
;
1089 if (active_timers
[QEMU_CLOCK_VIRTUAL
]) {
1090 delta
= active_timers
[QEMU_CLOCK_VIRTUAL
]->expire_time
-
1091 qemu_get_clock(vm_clock
);
1093 if (active_timers
[QEMU_CLOCK_HOST
]) {
1094 int64_t hdelta
= active_timers
[QEMU_CLOCK_HOST
]->expire_time
-
1095 qemu_get_clock(host_clock
);
1106 #if defined(__linux__)
1107 static uint64_t qemu_next_deadline_dyntick(void)
1115 delta
= (qemu_next_deadline() + 999) / 1000;
1117 if (active_timers
[QEMU_CLOCK_REALTIME
]) {
1118 rtdelta
= (active_timers
[QEMU_CLOCK_REALTIME
]->expire_time
-
1119 qemu_get_clock(rt_clock
))*1000;
1120 if (rtdelta
< delta
)
1124 if (delta
< MIN_TIMER_REARM_US
)
1125 delta
= MIN_TIMER_REARM_US
;
1133 /* Sets a specific flag */
1134 static int fcntl_setfl(int fd
, int flag
)
1138 flags
= fcntl(fd
, F_GETFL
);
1142 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1148 #if defined(__linux__)
1150 #define RTC_FREQ 1024
1152 static void enable_sigio_timer(int fd
)
1154 struct sigaction act
;
1157 sigfillset(&act
.sa_mask
);
1159 act
.sa_handler
= host_alarm_handler
;
1161 sigaction(SIGIO
, &act
, NULL
);
1162 fcntl_setfl(fd
, O_ASYNC
);
1163 fcntl(fd
, F_SETOWN
, getpid());
1166 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1168 struct hpet_info info
;
1171 fd
= qemu_open("/dev/hpet", O_RDONLY
);
1176 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1178 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1179 "error, but for better emulation accuracy type:\n"
1180 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1184 /* Check capabilities */
1185 r
= ioctl(fd
, HPET_INFO
, &info
);
1189 /* Enable periodic mode */
1190 r
= ioctl(fd
, HPET_EPI
, 0);
1191 if (info
.hi_flags
&& (r
< 0))
1194 /* Enable interrupt */
1195 r
= ioctl(fd
, HPET_IE_ON
, 0);
1199 enable_sigio_timer(fd
);
1200 t
->priv
= (void *)(long)fd
;
1208 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1210 int fd
= (long)t
->priv
;
1215 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1218 unsigned long current_rtc_freq
= 0;
1220 TFR(rtc_fd
= qemu_open("/dev/rtc", O_RDONLY
));
1223 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1224 if (current_rtc_freq
!= RTC_FREQ
&&
1225 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1226 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1227 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1228 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1231 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1237 enable_sigio_timer(rtc_fd
);
1239 t
->priv
= (void *)(long)rtc_fd
;
1244 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1246 int rtc_fd
= (long)t
->priv
;
1251 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1255 struct sigaction act
;
1257 sigfillset(&act
.sa_mask
);
1259 act
.sa_handler
= host_alarm_handler
;
1261 sigaction(SIGALRM
, &act
, NULL
);
1264 * Initialize ev struct to 0 to avoid valgrind complaining
1265 * about uninitialized data in timer_create call
1267 memset(&ev
, 0, sizeof(ev
));
1268 ev
.sigev_value
.sival_int
= 0;
1269 ev
.sigev_notify
= SIGEV_SIGNAL
;
1270 ev
.sigev_signo
= SIGALRM
;
1272 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1273 perror("timer_create");
1275 /* disable dynticks */
1276 fprintf(stderr
, "Dynamic Ticks disabled\n");
1281 t
->priv
= (void *)(long)host_timer
;
1286 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1288 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1290 timer_delete(host_timer
);
1293 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1295 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1296 struct itimerspec timeout
;
1297 int64_t nearest_delta_us
= INT64_MAX
;
1300 assert(alarm_has_dynticks(t
));
1301 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1302 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1303 !active_timers
[QEMU_CLOCK_HOST
])
1306 nearest_delta_us
= qemu_next_deadline_dyntick();
1308 /* check whether a timer is already running */
1309 if (timer_gettime(host_timer
, &timeout
)) {
1311 fprintf(stderr
, "Internal timer error: aborting\n");
1314 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1315 if (current_us
&& current_us
<= nearest_delta_us
)
1318 timeout
.it_interval
.tv_sec
= 0;
1319 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1320 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1321 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1322 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1324 fprintf(stderr
, "Internal timer error: aborting\n");
1329 #endif /* defined(__linux__) */
1331 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1333 struct sigaction act
;
1334 struct itimerval itv
;
1338 sigfillset(&act
.sa_mask
);
1340 act
.sa_handler
= host_alarm_handler
;
1342 sigaction(SIGALRM
, &act
, NULL
);
1344 itv
.it_interval
.tv_sec
= 0;
1345 /* for i386 kernel 2.6 to get 1 ms */
1346 itv
.it_interval
.tv_usec
= 999;
1347 itv
.it_value
.tv_sec
= 0;
1348 itv
.it_value
.tv_usec
= 10 * 1000;
1350 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1357 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1359 struct itimerval itv
;
1361 memset(&itv
, 0, sizeof(itv
));
1362 setitimer(ITIMER_REAL
, &itv
, NULL
);
1365 #endif /* !defined(_WIN32) */
1370 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1373 struct qemu_alarm_win32
*data
= t
->priv
;
1376 memset(&tc
, 0, sizeof(tc
));
1377 timeGetDevCaps(&tc
, sizeof(tc
));
1379 data
->period
= tc
.wPeriodMin
;
1380 timeBeginPeriod(data
->period
);
1382 flags
= TIME_CALLBACK_FUNCTION
;
1383 if (alarm_has_dynticks(t
))
1384 flags
|= TIME_ONESHOT
;
1386 flags
|= TIME_PERIODIC
;
1388 data
->timerId
= timeSetEvent(1, // interval (ms)
1389 data
->period
, // resolution
1390 host_alarm_handler
, // function
1391 (DWORD
)t
, // parameter
1394 if (!data
->timerId
) {
1395 fprintf(stderr
, "Failed to initialize win32 alarm timer: %ld\n",
1397 timeEndPeriod(data
->period
);
1404 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1406 struct qemu_alarm_win32
*data
= t
->priv
;
1408 timeKillEvent(data
->timerId
);
1409 timeEndPeriod(data
->period
);
1412 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1414 struct qemu_alarm_win32
*data
= t
->priv
;
1416 assert(alarm_has_dynticks(t
));
1417 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1418 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1419 !active_timers
[QEMU_CLOCK_HOST
])
1422 timeKillEvent(data
->timerId
);
1424 data
->timerId
= timeSetEvent(1,
1428 TIME_ONESHOT
| TIME_CALLBACK_FUNCTION
);
1430 if (!data
->timerId
) {
1431 fprintf(stderr
, "Failed to re-arm win32 alarm timer %ld\n",
1434 timeEndPeriod(data
->period
);
1441 static void alarm_timer_on_change_state_rearm(void *opaque
, int running
, int reason
)
1444 qemu_rearm_alarm_timer((struct qemu_alarm_timer
*) opaque
);
1447 static int init_timer_alarm(void)
1449 struct qemu_alarm_timer
*t
= NULL
;
1452 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1453 t
= &alarm_timers
[i
];
1465 /* first event is at time 0 */
1468 qemu_add_vm_change_state_handler(alarm_timer_on_change_state_rearm
, t
);
1476 static void quit_timers(void)
1478 struct qemu_alarm_timer
*t
= alarm_timer
;
1483 /***********************************************************/
1484 /* host time/date access */
1485 void qemu_get_timedate(struct tm
*tm
, int offset
)
1492 if (rtc_date_offset
== -1) {
1496 ret
= localtime(&ti
);
1498 ti
-= rtc_date_offset
;
1502 memcpy(tm
, ret
, sizeof(struct tm
));
1505 int qemu_timedate_diff(struct tm
*tm
)
1509 if (rtc_date_offset
== -1)
1511 seconds
= mktimegm(tm
);
1513 seconds
= mktime(tm
);
1515 seconds
= mktimegm(tm
) + rtc_date_offset
;
1517 return seconds
- time(NULL
);
1520 void rtc_change_mon_event(struct tm
*tm
)
1524 data
= qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm
));
1525 monitor_protocol_event(QEVENT_RTC_CHANGE
, data
);
1526 qobject_decref(data
);
1529 static void configure_rtc_date_offset(const char *startdate
, int legacy
)
1531 time_t rtc_start_date
;
1534 if (!strcmp(startdate
, "now") && legacy
) {
1535 rtc_date_offset
= -1;
1537 if (sscanf(startdate
, "%d-%d-%dT%d:%d:%d",
1545 } else if (sscanf(startdate
, "%d-%d-%d",
1548 &tm
.tm_mday
) == 3) {
1557 rtc_start_date
= mktimegm(&tm
);
1558 if (rtc_start_date
== -1) {
1560 fprintf(stderr
, "Invalid date format. Valid formats are:\n"
1561 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1564 rtc_date_offset
= time(NULL
) - rtc_start_date
;
1568 static void configure_rtc(QemuOpts
*opts
)
1572 value
= qemu_opt_get(opts
, "base");
1574 if (!strcmp(value
, "utc")) {
1576 } else if (!strcmp(value
, "localtime")) {
1579 configure_rtc_date_offset(value
, 0);
1582 value
= qemu_opt_get(opts
, "clock");
1584 if (!strcmp(value
, "host")) {
1585 rtc_clock
= host_clock
;
1586 } else if (!strcmp(value
, "vm")) {
1587 rtc_clock
= vm_clock
;
1589 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1593 #ifdef CONFIG_TARGET_I386
1594 value
= qemu_opt_get(opts
, "driftfix");
1596 if (!strcmp(buf
, "slew")) {
1598 } else if (!strcmp(buf
, "none")) {
1601 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1609 static void socket_cleanup(void)
1614 static int socket_init(void)
1619 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1621 err
= WSAGetLastError();
1622 fprintf(stderr
, "WSAStartup: %d\n", err
);
1625 atexit(socket_cleanup
);
1630 /***********************************************************/
1631 /* Bluetooth support */
1634 static struct HCIInfo
*hci_table
[MAX_NICS
];
1636 static struct bt_vlan_s
{
1637 struct bt_scatternet_s net
;
1639 struct bt_vlan_s
*next
;
1642 /* find or alloc a new bluetooth "VLAN" */
1643 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1645 struct bt_vlan_s
**pvlan
, *vlan
;
1646 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1650 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1652 pvlan
= &first_bt_vlan
;
1653 while (*pvlan
!= NULL
)
1654 pvlan
= &(*pvlan
)->next
;
1659 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1663 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1668 static struct HCIInfo null_hci
= {
1669 .cmd_send
= null_hci_send
,
1670 .sco_send
= null_hci_send
,
1671 .acl_send
= null_hci_send
,
1672 .bdaddr_set
= null_hci_addr_set
,
1675 struct HCIInfo
*qemu_next_hci(void)
1677 if (cur_hci
== nb_hcis
)
1680 return hci_table
[cur_hci
++];
1683 static struct HCIInfo
*hci_init(const char *str
)
1686 struct bt_scatternet_s
*vlan
= 0;
1688 if (!strcmp(str
, "null"))
1691 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
1693 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
1694 else if (!strncmp(str
, "hci", 3)) {
1697 if (!strncmp(str
+ 3, ",vlan=", 6)) {
1698 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
1703 vlan
= qemu_find_bt_vlan(0);
1705 return bt_new_hci(vlan
);
1708 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
1713 static int bt_hci_parse(const char *str
)
1715 struct HCIInfo
*hci
;
1718 if (nb_hcis
>= MAX_NICS
) {
1719 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
1723 hci
= hci_init(str
);
1732 bdaddr
.b
[5] = 0x56 + nb_hcis
;
1733 hci
->bdaddr_set(hci
, bdaddr
.b
);
1735 hci_table
[nb_hcis
++] = hci
;
1740 static void bt_vhci_add(int vlan_id
)
1742 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
1745 fprintf(stderr
, "qemu: warning: adding a VHCI to "
1746 "an empty scatternet %i\n", vlan_id
);
1748 bt_vhci_init(bt_new_hci(vlan
));
1751 static struct bt_device_s
*bt_device_add(const char *opt
)
1753 struct bt_scatternet_s
*vlan
;
1755 char *endp
= strstr(opt
, ",vlan=");
1756 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
1759 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
1762 vlan_id
= strtol(endp
+ 6, &endp
, 0);
1764 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
1769 vlan
= qemu_find_bt_vlan(vlan_id
);
1772 fprintf(stderr
, "qemu: warning: adding a slave device to "
1773 "an empty scatternet %i\n", vlan_id
);
1775 if (!strcmp(devname
, "keyboard"))
1776 return bt_keyboard_init(vlan
);
1778 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
1782 static int bt_parse(const char *opt
)
1784 const char *endp
, *p
;
1787 if (strstart(opt
, "hci", &endp
)) {
1788 if (!*endp
|| *endp
== ',') {
1790 if (!strstart(endp
, ",vlan=", 0))
1793 return bt_hci_parse(opt
);
1795 } else if (strstart(opt
, "vhci", &endp
)) {
1796 if (!*endp
|| *endp
== ',') {
1798 if (strstart(endp
, ",vlan=", &p
)) {
1799 vlan
= strtol(p
, (char **) &endp
, 0);
1801 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
1805 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
1814 } else if (strstart(opt
, "device:", &endp
))
1815 return !bt_device_add(endp
);
1817 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
1821 /***********************************************************/
1822 /* QEMU Block devices */
1824 #define HD_ALIAS "index=%d,media=disk"
1825 #define CDROM_ALIAS "index=2,media=cdrom"
1826 #define FD_ALIAS "index=%d,if=floppy"
1827 #define PFLASH_ALIAS "if=pflash"
1828 #define MTD_ALIAS "if=mtd"
1829 #define SD_ALIAS "index=0,if=sd"
1831 QemuOpts
*drive_add(const char *file
, const char *fmt
, ...)
1838 vsnprintf(optstr
, sizeof(optstr
), fmt
, ap
);
1841 opts
= qemu_opts_parse(&qemu_drive_opts
, optstr
, 0);
1843 fprintf(stderr
, "%s: huh? duplicate? (%s)\n",
1844 __FUNCTION__
, optstr
);
1848 qemu_opt_set(opts
, "file", file
);
1852 DriveInfo
*drive_get(BlockInterfaceType type
, int bus
, int unit
)
1856 /* seek interface, bus and unit */
1858 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1859 if (dinfo
->type
== type
&&
1860 dinfo
->bus
== bus
&&
1861 dinfo
->unit
== unit
)
1868 DriveInfo
*drive_get_by_id(const char *id
)
1872 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1873 if (strcmp(id
, dinfo
->id
))
1880 int drive_get_max_bus(BlockInterfaceType type
)
1886 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1887 if(dinfo
->type
== type
&&
1888 dinfo
->bus
> max_bus
)
1889 max_bus
= dinfo
->bus
;
1894 const char *drive_get_serial(BlockDriverState
*bdrv
)
1898 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1899 if (dinfo
->bdrv
== bdrv
)
1900 return dinfo
->serial
;
1906 BlockInterfaceErrorAction
drive_get_on_error(
1907 BlockDriverState
*bdrv
, int is_read
)
1911 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1912 if (dinfo
->bdrv
== bdrv
)
1913 return is_read
? dinfo
->on_read_error
: dinfo
->on_write_error
;
1916 return is_read
? BLOCK_ERR_REPORT
: BLOCK_ERR_STOP_ENOSPC
;
1919 static void bdrv_format_print(void *opaque
, const char *name
)
1921 fprintf(stderr
, " %s", name
);
1924 void drive_uninit(DriveInfo
*dinfo
)
1926 qemu_opts_del(dinfo
->opts
);
1927 bdrv_delete(dinfo
->bdrv
);
1928 QTAILQ_REMOVE(&drives
, dinfo
, next
);
1932 static int parse_block_error_action(const char *buf
, int is_read
)
1934 if (!strcmp(buf
, "ignore")) {
1935 return BLOCK_ERR_IGNORE
;
1936 } else if (!is_read
&& !strcmp(buf
, "enospc")) {
1937 return BLOCK_ERR_STOP_ENOSPC
;
1938 } else if (!strcmp(buf
, "stop")) {
1939 return BLOCK_ERR_STOP_ANY
;
1940 } else if (!strcmp(buf
, "report")) {
1941 return BLOCK_ERR_REPORT
;
1943 fprintf(stderr
, "qemu: '%s' invalid %s error action\n",
1944 buf
, is_read
? "read" : "write");
1949 DriveInfo
*drive_init(QemuOpts
*opts
, void *opaque
,
1953 const char *file
= NULL
;
1956 const char *mediastr
= "";
1957 BlockInterfaceType type
;
1958 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
1959 int bus_id
, unit_id
;
1960 int cyls
, heads
, secs
, translation
;
1961 BlockDriver
*drv
= NULL
;
1962 QEMUMachine
*machine
= opaque
;
1969 int on_read_error
, on_write_error
;
1970 const char *devaddr
;
1976 translation
= BIOS_ATA_TRANSLATION_AUTO
;
1979 if (machine
&& machine
->use_scsi
) {
1981 max_devs
= MAX_SCSI_DEVS
;
1982 pstrcpy(devname
, sizeof(devname
), "scsi");
1985 max_devs
= MAX_IDE_DEVS
;
1986 pstrcpy(devname
, sizeof(devname
), "ide");
1990 /* extract parameters */
1991 bus_id
= qemu_opt_get_number(opts
, "bus", 0);
1992 unit_id
= qemu_opt_get_number(opts
, "unit", -1);
1993 index
= qemu_opt_get_number(opts
, "index", -1);
1995 cyls
= qemu_opt_get_number(opts
, "cyls", 0);
1996 heads
= qemu_opt_get_number(opts
, "heads", 0);
1997 secs
= qemu_opt_get_number(opts
, "secs", 0);
1999 snapshot
= qemu_opt_get_bool(opts
, "snapshot", 0);
2000 ro
= qemu_opt_get_bool(opts
, "readonly", 0);
2002 file
= qemu_opt_get(opts
, "file");
2003 serial
= qemu_opt_get(opts
, "serial");
2005 if ((buf
= qemu_opt_get(opts
, "if")) != NULL
) {
2006 pstrcpy(devname
, sizeof(devname
), buf
);
2007 if (!strcmp(buf
, "ide")) {
2009 max_devs
= MAX_IDE_DEVS
;
2010 } else if (!strcmp(buf
, "scsi")) {
2012 max_devs
= MAX_SCSI_DEVS
;
2013 } else if (!strcmp(buf
, "floppy")) {
2016 } else if (!strcmp(buf
, "pflash")) {
2019 } else if (!strcmp(buf
, "mtd")) {
2022 } else if (!strcmp(buf
, "sd")) {
2025 } else if (!strcmp(buf
, "virtio")) {
2028 } else if (!strcmp(buf
, "xen")) {
2031 } else if (!strcmp(buf
, "none")) {
2035 fprintf(stderr
, "qemu: unsupported bus type '%s'\n", buf
);
2040 if (cyls
|| heads
|| secs
) {
2041 if (cyls
< 1 || (type
== IF_IDE
&& cyls
> 16383)) {
2042 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", buf
);
2045 if (heads
< 1 || (type
== IF_IDE
&& heads
> 16)) {
2046 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", buf
);
2049 if (secs
< 1 || (type
== IF_IDE
&& secs
> 63)) {
2050 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", buf
);
2055 if ((buf
= qemu_opt_get(opts
, "trans")) != NULL
) {
2058 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2062 if (!strcmp(buf
, "none"))
2063 translation
= BIOS_ATA_TRANSLATION_NONE
;
2064 else if (!strcmp(buf
, "lba"))
2065 translation
= BIOS_ATA_TRANSLATION_LBA
;
2066 else if (!strcmp(buf
, "auto"))
2067 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2069 fprintf(stderr
, "qemu: '%s' invalid translation type\n", buf
);
2074 if ((buf
= qemu_opt_get(opts
, "media")) != NULL
) {
2075 if (!strcmp(buf
, "disk")) {
2077 } else if (!strcmp(buf
, "cdrom")) {
2078 if (cyls
|| secs
|| heads
) {
2080 "qemu: '%s' invalid physical CHS format\n", buf
);
2083 media
= MEDIA_CDROM
;
2085 fprintf(stderr
, "qemu: '%s' invalid media\n", buf
);
2090 if ((buf
= qemu_opt_get(opts
, "cache")) != NULL
) {
2091 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2093 else if (!strcmp(buf
, "writethrough"))
2095 else if (!strcmp(buf
, "writeback"))
2098 fprintf(stderr
, "qemu: invalid cache option\n");
2103 #ifdef CONFIG_LINUX_AIO
2104 if ((buf
= qemu_opt_get(opts
, "aio")) != NULL
) {
2105 if (!strcmp(buf
, "threads"))
2107 else if (!strcmp(buf
, "native"))
2110 fprintf(stderr
, "qemu: invalid aio option\n");
2116 if ((buf
= qemu_opt_get(opts
, "format")) != NULL
) {
2117 if (strcmp(buf
, "?") == 0) {
2118 fprintf(stderr
, "qemu: Supported formats:");
2119 bdrv_iterate_format(bdrv_format_print
, NULL
);
2120 fprintf(stderr
, "\n");
2123 drv
= bdrv_find_whitelisted_format(buf
);
2125 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2130 on_write_error
= BLOCK_ERR_STOP_ENOSPC
;
2131 if ((buf
= qemu_opt_get(opts
, "werror")) != NULL
) {
2132 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2133 fprintf(stderr
, "werror is no supported by this format\n");
2137 on_write_error
= parse_block_error_action(buf
, 0);
2138 if (on_write_error
< 0) {
2143 on_read_error
= BLOCK_ERR_REPORT
;
2144 if ((buf
= qemu_opt_get(opts
, "rerror")) != NULL
) {
2145 if (type
!= IF_IDE
&& type
!= IF_VIRTIO
) {
2146 fprintf(stderr
, "rerror is no supported by this format\n");
2150 on_read_error
= parse_block_error_action(buf
, 1);
2151 if (on_read_error
< 0) {
2156 if ((devaddr
= qemu_opt_get(opts
, "addr")) != NULL
) {
2157 if (type
!= IF_VIRTIO
) {
2158 fprintf(stderr
, "addr is not supported\n");
2163 /* compute bus and unit according index */
2166 if (bus_id
!= 0 || unit_id
!= -1) {
2168 "qemu: index cannot be used with bus and unit\n");
2176 unit_id
= index
% max_devs
;
2177 bus_id
= index
/ max_devs
;
2181 /* if user doesn't specify a unit_id,
2182 * try to find the first free
2185 if (unit_id
== -1) {
2187 while (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2189 if (max_devs
&& unit_id
>= max_devs
) {
2190 unit_id
-= max_devs
;
2198 if (max_devs
&& unit_id
>= max_devs
) {
2199 fprintf(stderr
, "qemu: unit %d too big (max is %d)\n",
2200 unit_id
, max_devs
- 1);
2205 * ignore multiple definitions
2208 if (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2215 dinfo
= qemu_mallocz(sizeof(*dinfo
));
2216 if ((buf
= qemu_opts_id(opts
)) != NULL
) {
2217 dinfo
->id
= qemu_strdup(buf
);
2219 /* no id supplied -> create one */
2220 dinfo
->id
= qemu_mallocz(32);
2221 if (type
== IF_IDE
|| type
== IF_SCSI
)
2222 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2224 snprintf(dinfo
->id
, 32, "%s%i%s%i",
2225 devname
, bus_id
, mediastr
, unit_id
);
2227 snprintf(dinfo
->id
, 32, "%s%s%i",
2228 devname
, mediastr
, unit_id
);
2230 dinfo
->bdrv
= bdrv_new(dinfo
->id
);
2231 dinfo
->devaddr
= devaddr
;
2233 dinfo
->bus
= bus_id
;
2234 dinfo
->unit
= unit_id
;
2235 dinfo
->on_read_error
= on_read_error
;
2236 dinfo
->on_write_error
= on_write_error
;
2239 strncpy(dinfo
->serial
, serial
, sizeof(serial
));
2240 QTAILQ_INSERT_TAIL(&drives
, dinfo
, next
);
2250 bdrv_set_geometry_hint(dinfo
->bdrv
, cyls
, heads
, secs
);
2251 bdrv_set_translation_hint(dinfo
->bdrv
, translation
);
2255 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_CDROM
);
2260 /* FIXME: This isn't really a floppy, but it's a reasonable
2263 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_FLOPPY
);
2269 /* add virtio block device */
2270 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
2271 qemu_opt_set(opts
, "driver", "virtio-blk-pci");
2272 qemu_opt_set(opts
, "drive", dinfo
->id
);
2274 qemu_opt_set(opts
, "addr", devaddr
);
2285 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2286 cache
= 2; /* always use write-back with snapshot */
2288 if (cache
== 0) /* no caching */
2289 bdrv_flags
|= BDRV_O_NOCACHE
;
2290 else if (cache
== 2) /* write-back */
2291 bdrv_flags
|= BDRV_O_CACHE_WB
;
2294 bdrv_flags
|= BDRV_O_NATIVE_AIO
;
2296 bdrv_flags
&= ~BDRV_O_NATIVE_AIO
;
2300 if (type
!= IF_SCSI
&& type
!= IF_VIRTIO
&& type
!= IF_FLOPPY
) {
2301 fprintf(stderr
, "qemu: readonly flag not supported for drive with this interface\n");
2306 * cdrom is read-only. Set it now, after above interface checking
2307 * since readonly attribute not explicitly required, so no error.
2309 if (media
== MEDIA_CDROM
) {
2312 bdrv_flags
|= ro
? 0 : BDRV_O_RDWR
;
2314 if (bdrv_open2(dinfo
->bdrv
, file
, bdrv_flags
, drv
) < 0) {
2315 fprintf(stderr
, "qemu: could not open disk image %s: %s\n",
2316 file
, strerror(errno
));
2320 if (bdrv_key_required(dinfo
->bdrv
))
2326 static int drive_init_func(QemuOpts
*opts
, void *opaque
)
2328 QEMUMachine
*machine
= opaque
;
2329 int fatal_error
= 0;
2331 if (drive_init(opts
, machine
, &fatal_error
) == NULL
) {
2338 static int drive_enable_snapshot(QemuOpts
*opts
, void *opaque
)
2340 if (NULL
== qemu_opt_get(opts
, "snapshot")) {
2341 qemu_opt_set(opts
, "snapshot", "on");
2346 void qemu_register_boot_set(QEMUBootSetHandler
*func
, void *opaque
)
2348 boot_set_handler
= func
;
2349 boot_set_opaque
= opaque
;
2352 int qemu_boot_set(const char *boot_devices
)
2354 if (!boot_set_handler
) {
2357 return boot_set_handler(boot_set_opaque
, boot_devices
);
2360 static int parse_bootdevices(char *devices
)
2362 /* We just do some generic consistency checks */
2366 for (p
= devices
; *p
!= '\0'; p
++) {
2367 /* Allowed boot devices are:
2368 * a-b: floppy disk drives
2369 * c-f: IDE disk drives
2370 * g-m: machine implementation dependant drives
2371 * n-p: network devices
2372 * It's up to each machine implementation to check if the given boot
2373 * devices match the actual hardware implementation and firmware
2376 if (*p
< 'a' || *p
> 'p') {
2377 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
2380 if (bitmap
& (1 << (*p
- 'a'))) {
2381 fprintf(stderr
, "Boot device '%c' was given twice\n", *p
);
2384 bitmap
|= 1 << (*p
- 'a');
2389 static void restore_boot_devices(void *opaque
)
2391 char *standard_boot_devices
= opaque
;
2393 qemu_boot_set(standard_boot_devices
);
2395 qemu_unregister_reset(restore_boot_devices
, standard_boot_devices
);
2396 qemu_free(standard_boot_devices
);
2399 static void numa_add(const char *optarg
)
2403 unsigned long long value
, endvalue
;
2406 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2407 if (!strcmp(option
, "node")) {
2408 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2409 nodenr
= nb_numa_nodes
;
2411 nodenr
= strtoull(option
, NULL
, 10);
2414 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2415 node_mem
[nodenr
] = 0;
2417 value
= strtoull(option
, &endptr
, 0);
2419 case 0: case 'M': case 'm':
2426 node_mem
[nodenr
] = value
;
2428 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2429 node_cpumask
[nodenr
] = 0;
2431 value
= strtoull(option
, &endptr
, 10);
2434 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2436 if (*endptr
== '-') {
2437 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2438 if (endvalue
>= 63) {
2441 "only 63 CPUs in NUMA mode supported.\n");
2443 value
= (2ULL << endvalue
) - (1ULL << value
);
2445 value
= 1ULL << value
;
2448 node_cpumask
[nodenr
] = value
;
2455 static void smp_parse(const char *optarg
)
2457 int smp
, sockets
= 0, threads
= 0, cores
= 0;
2461 smp
= strtoul(optarg
, &endptr
, 10);
2462 if (endptr
!= optarg
) {
2463 if (*endptr
== ',') {
2467 if (get_param_value(option
, 128, "sockets", endptr
) != 0)
2468 sockets
= strtoull(option
, NULL
, 10);
2469 if (get_param_value(option
, 128, "cores", endptr
) != 0)
2470 cores
= strtoull(option
, NULL
, 10);
2471 if (get_param_value(option
, 128, "threads", endptr
) != 0)
2472 threads
= strtoull(option
, NULL
, 10);
2473 if (get_param_value(option
, 128, "maxcpus", endptr
) != 0)
2474 max_cpus
= strtoull(option
, NULL
, 10);
2476 /* compute missing values, prefer sockets over cores over threads */
2477 if (smp
== 0 || sockets
== 0) {
2478 sockets
= sockets
> 0 ? sockets
: 1;
2479 cores
= cores
> 0 ? cores
: 1;
2480 threads
= threads
> 0 ? threads
: 1;
2482 smp
= cores
* threads
* sockets
;
2486 threads
= threads
> 0 ? threads
: 1;
2487 cores
= smp
/ (sockets
* threads
);
2490 threads
= smp
/ (cores
* sockets
);
2495 smp_cores
= cores
> 0 ? cores
: 1;
2496 smp_threads
= threads
> 0 ? threads
: 1;
2498 max_cpus
= smp_cpus
;
2501 /***********************************************************/
2504 static int usb_device_add(const char *devname
, int is_hotplug
)
2507 USBDevice
*dev
= NULL
;
2512 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2513 dev
= usbdevice_create(devname
);
2517 /* the other ones */
2518 if (strstart(devname
, "host:", &p
)) {
2519 dev
= usb_host_device_open(p
);
2520 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2521 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2522 bt_new_hci(qemu_find_bt_vlan(0)));
2533 static int usb_device_del(const char *devname
)
2538 if (strstart(devname
, "host:", &p
))
2539 return usb_host_device_close(p
);
2544 p
= strchr(devname
, '.');
2547 bus_num
= strtoul(devname
, NULL
, 0);
2548 addr
= strtoul(p
+ 1, NULL
, 0);
2550 return usb_device_delete_addr(bus_num
, addr
);
2553 static int usb_parse(const char *cmdline
)
2556 r
= usb_device_add(cmdline
, 0);
2558 fprintf(stderr
, "qemu: could not add USB device '%s'\n", cmdline
);
2563 void do_usb_add(Monitor
*mon
, const QDict
*qdict
)
2565 const char *devname
= qdict_get_str(qdict
, "devname");
2566 if (usb_device_add(devname
, 1) < 0) {
2567 error_report("could not add USB device '%s'", devname
);
2571 void do_usb_del(Monitor
*mon
, const QDict
*qdict
)
2573 const char *devname
= qdict_get_str(qdict
, "devname");
2574 if (usb_device_del(devname
) < 0) {
2575 error_report("could not delete USB device '%s'", devname
);
2579 /***********************************************************/
2580 /* PCMCIA/Cardbus */
2582 static struct pcmcia_socket_entry_s
{
2583 PCMCIASocket
*socket
;
2584 struct pcmcia_socket_entry_s
*next
;
2585 } *pcmcia_sockets
= 0;
2587 void pcmcia_socket_register(PCMCIASocket
*socket
)
2589 struct pcmcia_socket_entry_s
*entry
;
2591 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2592 entry
->socket
= socket
;
2593 entry
->next
= pcmcia_sockets
;
2594 pcmcia_sockets
= entry
;
2597 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2599 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2601 ptr
= &pcmcia_sockets
;
2602 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2603 if (entry
->socket
== socket
) {
2609 void pcmcia_info(Monitor
*mon
)
2611 struct pcmcia_socket_entry_s
*iter
;
2613 if (!pcmcia_sockets
)
2614 monitor_printf(mon
, "No PCMCIA sockets\n");
2616 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2617 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2618 iter
->socket
->attached
? iter
->socket
->card_string
:
2622 /***********************************************************/
2625 typedef struct IOHandlerRecord
{
2627 IOCanRWHandler
*fd_read_poll
;
2629 IOHandler
*fd_write
;
2632 /* temporary data */
2634 struct IOHandlerRecord
*next
;
2637 static IOHandlerRecord
*first_io_handler
;
2639 /* XXX: fd_read_poll should be suppressed, but an API change is
2640 necessary in the character devices to suppress fd_can_read(). */
2641 int qemu_set_fd_handler2(int fd
,
2642 IOCanRWHandler
*fd_read_poll
,
2644 IOHandler
*fd_write
,
2647 IOHandlerRecord
**pioh
, *ioh
;
2649 if (!fd_read
&& !fd_write
) {
2650 pioh
= &first_io_handler
;
2655 if (ioh
->fd
== fd
) {
2662 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
2666 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
2667 ioh
->next
= first_io_handler
;
2668 first_io_handler
= ioh
;
2671 ioh
->fd_read_poll
= fd_read_poll
;
2672 ioh
->fd_read
= fd_read
;
2673 ioh
->fd_write
= fd_write
;
2674 ioh
->opaque
= opaque
;
2680 int qemu_set_fd_handler(int fd
,
2682 IOHandler
*fd_write
,
2685 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
2689 /***********************************************************/
2690 /* Polling handling */
2692 typedef struct PollingEntry
{
2695 struct PollingEntry
*next
;
2698 static PollingEntry
*first_polling_entry
;
2700 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
2702 PollingEntry
**ppe
, *pe
;
2703 pe
= qemu_mallocz(sizeof(PollingEntry
));
2705 pe
->opaque
= opaque
;
2706 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
2711 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
2713 PollingEntry
**ppe
, *pe
;
2714 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
2716 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
2724 /***********************************************************/
2725 /* Wait objects support */
2726 typedef struct WaitObjects
{
2728 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
2729 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
2730 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
2733 static WaitObjects wait_objects
= {0};
2735 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2737 WaitObjects
*w
= &wait_objects
;
2739 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
2741 w
->events
[w
->num
] = handle
;
2742 w
->func
[w
->num
] = func
;
2743 w
->opaque
[w
->num
] = opaque
;
2748 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2751 WaitObjects
*w
= &wait_objects
;
2754 for (i
= 0; i
< w
->num
; i
++) {
2755 if (w
->events
[i
] == handle
)
2758 w
->events
[i
] = w
->events
[i
+ 1];
2759 w
->func
[i
] = w
->func
[i
+ 1];
2760 w
->opaque
[i
] = w
->opaque
[i
+ 1];
2768 /***********************************************************/
2769 /* ram save/restore */
2771 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2772 #define RAM_SAVE_FLAG_COMPRESS 0x02
2773 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2774 #define RAM_SAVE_FLAG_PAGE 0x08
2775 #define RAM_SAVE_FLAG_EOS 0x10
2777 static int is_dup_page(uint8_t *page
, uint8_t ch
)
2779 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
2780 uint32_t *array
= (uint32_t *)page
;
2783 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
2784 if (array
[i
] != val
)
2791 static int ram_save_block(QEMUFile
*f
)
2793 static ram_addr_t current_addr
= 0;
2794 ram_addr_t saved_addr
= current_addr
;
2795 ram_addr_t addr
= 0;
2798 while (addr
< last_ram_offset
) {
2799 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
2802 cpu_physical_memory_reset_dirty(current_addr
,
2803 current_addr
+ TARGET_PAGE_SIZE
,
2804 MIGRATION_DIRTY_FLAG
);
2806 p
= qemu_get_ram_ptr(current_addr
);
2808 if (is_dup_page(p
, *p
)) {
2809 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
2810 qemu_put_byte(f
, *p
);
2812 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
2813 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
2819 addr
+= TARGET_PAGE_SIZE
;
2820 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
2826 static uint64_t bytes_transferred
;
2828 static ram_addr_t
ram_save_remaining(void)
2831 ram_addr_t count
= 0;
2833 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2834 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2841 uint64_t ram_bytes_remaining(void)
2843 return ram_save_remaining() * TARGET_PAGE_SIZE
;
2846 uint64_t ram_bytes_transferred(void)
2848 return bytes_transferred
;
2851 uint64_t ram_bytes_total(void)
2853 return last_ram_offset
;
2856 static int ram_save_live(Monitor
*mon
, QEMUFile
*f
, int stage
, void *opaque
)
2859 uint64_t bytes_transferred_last
;
2861 uint64_t expected_time
= 0;
2864 cpu_physical_memory_set_dirty_tracking(0);
2868 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX
) != 0) {
2869 qemu_file_set_error(f
);
2874 bytes_transferred
= 0;
2876 /* Make sure all dirty bits are set */
2877 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2878 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2879 cpu_physical_memory_set_dirty(addr
);
2882 /* Enable dirty memory tracking */
2883 cpu_physical_memory_set_dirty_tracking(1);
2885 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
2888 bytes_transferred_last
= bytes_transferred
;
2889 bwidth
= qemu_get_clock_ns(rt_clock
);
2891 while (!qemu_file_rate_limit(f
)) {
2894 ret
= ram_save_block(f
);
2895 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
2896 if (ret
== 0) /* no more blocks */
2900 bwidth
= qemu_get_clock_ns(rt_clock
) - bwidth
;
2901 bwidth
= (bytes_transferred
- bytes_transferred_last
) / bwidth
;
2903 /* if we haven't transferred anything this round, force expected_time to a
2904 * a very high value, but without crashing */
2908 /* try transferring iterative blocks of memory */
2910 /* flush all remaining blocks regardless of rate limiting */
2911 while (ram_save_block(f
) != 0) {
2912 bytes_transferred
+= TARGET_PAGE_SIZE
;
2914 cpu_physical_memory_set_dirty_tracking(0);
2917 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
2919 expected_time
= ram_save_remaining() * TARGET_PAGE_SIZE
/ bwidth
;
2921 return (stage
== 2) && (expected_time
<= migrate_max_downtime());
2924 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
2929 if (version_id
!= 3)
2933 addr
= qemu_get_be64(f
);
2935 flags
= addr
& ~TARGET_PAGE_MASK
;
2936 addr
&= TARGET_PAGE_MASK
;
2938 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
2939 if (addr
!= last_ram_offset
)
2943 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
2944 uint8_t ch
= qemu_get_byte(f
);
2945 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
2948 (!kvm_enabled() || kvm_has_sync_mmu())) {
2949 madvise(qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
, MADV_DONTNEED
);
2952 } else if (flags
& RAM_SAVE_FLAG_PAGE
) {
2953 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
2955 if (qemu_file_has_error(f
)) {
2958 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
2963 void qemu_service_io(void)
2965 qemu_notify_event();
2968 /***********************************************************/
2969 /* machine registration */
2971 static QEMUMachine
*first_machine
= NULL
;
2972 QEMUMachine
*current_machine
= NULL
;
2974 int qemu_register_machine(QEMUMachine
*m
)
2977 pm
= &first_machine
;
2985 static QEMUMachine
*find_machine(const char *name
)
2989 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
2990 if (!strcmp(m
->name
, name
))
2992 if (m
->alias
&& !strcmp(m
->alias
, name
))
2998 static QEMUMachine
*find_default_machine(void)
3002 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3003 if (m
->is_default
) {
3010 /***********************************************************/
3011 /* main execution loop */
3013 static void gui_update(void *opaque
)
3015 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3016 DisplayState
*ds
= opaque
;
3017 DisplayChangeListener
*dcl
= ds
->listeners
;
3019 qemu_flush_coalesced_mmio_buffer();
3022 while (dcl
!= NULL
) {
3023 if (dcl
->gui_timer_interval
&&
3024 dcl
->gui_timer_interval
< interval
)
3025 interval
= dcl
->gui_timer_interval
;
3028 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3031 static void nographic_update(void *opaque
)
3033 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3035 qemu_flush_coalesced_mmio_buffer();
3036 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3039 void cpu_synchronize_all_states(void)
3043 for (cpu
= first_cpu
; cpu
; cpu
= cpu
->next_cpu
) {
3044 cpu_synchronize_state(cpu
);
3048 void cpu_synchronize_all_post_reset(void)
3052 for (cpu
= first_cpu
; cpu
; cpu
= cpu
->next_cpu
) {
3053 cpu_synchronize_post_reset(cpu
);
3057 void cpu_synchronize_all_post_init(void)
3061 for (cpu
= first_cpu
; cpu
; cpu
= cpu
->next_cpu
) {
3062 cpu_synchronize_post_init(cpu
);
3066 struct vm_change_state_entry
{
3067 VMChangeStateHandler
*cb
;
3069 QLIST_ENTRY (vm_change_state_entry
) entries
;
3072 static QLIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3074 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3077 VMChangeStateEntry
*e
;
3079 e
= qemu_mallocz(sizeof (*e
));
3083 QLIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3087 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3089 QLIST_REMOVE (e
, entries
);
3093 static void vm_state_notify(int running
, int reason
)
3095 VMChangeStateEntry
*e
;
3097 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3098 e
->cb(e
->opaque
, running
, reason
);
3102 static void resume_all_vcpus(void);
3103 static void pause_all_vcpus(void);
3110 vm_state_notify(1, 0);
3115 /* reset/shutdown handler */
3117 typedef struct QEMUResetEntry
{
3118 QTAILQ_ENTRY(QEMUResetEntry
) entry
;
3119 QEMUResetHandler
*func
;
3123 static QTAILQ_HEAD(reset_handlers
, QEMUResetEntry
) reset_handlers
=
3124 QTAILQ_HEAD_INITIALIZER(reset_handlers
);
3125 static int reset_requested
;
3126 static int shutdown_requested
;
3127 static int powerdown_requested
;
3128 static int debug_requested
;
3129 static int vmstop_requested
;
3131 int qemu_shutdown_requested(void)
3133 int r
= shutdown_requested
;
3134 shutdown_requested
= 0;
3138 int qemu_reset_requested(void)
3140 int r
= reset_requested
;
3141 reset_requested
= 0;
3145 int qemu_powerdown_requested(void)
3147 int r
= powerdown_requested
;
3148 powerdown_requested
= 0;
3152 static int qemu_debug_requested(void)
3154 int r
= debug_requested
;
3155 debug_requested
= 0;
3159 static int qemu_vmstop_requested(void)
3161 int r
= vmstop_requested
;
3162 vmstop_requested
= 0;
3166 static void do_vm_stop(int reason
)
3169 cpu_disable_ticks();
3172 vm_state_notify(0, reason
);
3173 monitor_protocol_event(QEVENT_STOP
, NULL
);
3177 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3179 QEMUResetEntry
*re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3182 re
->opaque
= opaque
;
3183 QTAILQ_INSERT_TAIL(&reset_handlers
, re
, entry
);
3186 void qemu_unregister_reset(QEMUResetHandler
*func
, void *opaque
)
3190 QTAILQ_FOREACH(re
, &reset_handlers
, entry
) {
3191 if (re
->func
== func
&& re
->opaque
== opaque
) {
3192 QTAILQ_REMOVE(&reset_handlers
, re
, entry
);
3199 void qemu_system_reset(void)
3201 QEMUResetEntry
*re
, *nre
;
3203 /* reset all devices */
3204 QTAILQ_FOREACH_SAFE(re
, &reset_handlers
, entry
, nre
) {
3205 re
->func(re
->opaque
);
3207 monitor_protocol_event(QEVENT_RESET
, NULL
);
3208 cpu_synchronize_all_post_reset();
3211 void qemu_system_reset_request(void)
3214 shutdown_requested
= 1;
3216 reset_requested
= 1;
3218 qemu_notify_event();
3221 void qemu_system_shutdown_request(void)
3223 shutdown_requested
= 1;
3224 qemu_notify_event();
3227 void qemu_system_powerdown_request(void)
3229 powerdown_requested
= 1;
3230 qemu_notify_event();
3233 #ifdef CONFIG_IOTHREAD
3234 static void qemu_system_vmstop_request(int reason
)
3236 vmstop_requested
= reason
;
3237 qemu_notify_event();
3242 static int io_thread_fd
= -1;
3244 static void qemu_event_increment(void)
3246 /* Write 8 bytes to be compatible with eventfd. */
3247 static uint64_t val
= 1;
3250 if (io_thread_fd
== -1)
3254 ret
= write(io_thread_fd
, &val
, sizeof(val
));
3255 } while (ret
< 0 && errno
== EINTR
);
3257 /* EAGAIN is fine, a read must be pending. */
3258 if (ret
< 0 && errno
!= EAGAIN
) {
3259 fprintf(stderr
, "qemu_event_increment: write() filed: %s\n",
3265 static void qemu_event_read(void *opaque
)
3267 int fd
= (unsigned long)opaque
;
3271 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
3273 len
= read(fd
, buffer
, sizeof(buffer
));
3274 } while ((len
== -1 && errno
== EINTR
) || len
== sizeof(buffer
));
3277 static int qemu_event_init(void)
3282 err
= qemu_eventfd(fds
);
3286 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3290 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3294 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3295 (void *)(unsigned long)fds
[0]);
3297 io_thread_fd
= fds
[1];
3306 HANDLE qemu_event_handle
;
3308 static void dummy_event_handler(void *opaque
)
3312 static int qemu_event_init(void)
3314 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3315 if (!qemu_event_handle
) {
3316 fprintf(stderr
, "Failed CreateEvent: %ld\n", GetLastError());
3319 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3323 static void qemu_event_increment(void)
3325 if (!SetEvent(qemu_event_handle
)) {
3326 fprintf(stderr
, "qemu_event_increment: SetEvent failed: %ld\n",
3333 static int cpu_can_run(CPUState
*env
)
3344 #ifndef CONFIG_IOTHREAD
3345 static int qemu_init_main_loop(void)
3347 return qemu_event_init();
3350 void qemu_init_vcpu(void *_env
)
3352 CPUState
*env
= _env
;
3354 env
->nr_cores
= smp_cores
;
3355 env
->nr_threads
= smp_threads
;
3361 int qemu_cpu_self(void *env
)
3366 static void resume_all_vcpus(void)
3370 static void pause_all_vcpus(void)
3374 void qemu_cpu_kick(void *env
)
3379 void qemu_notify_event(void)
3381 CPUState
*env
= cpu_single_env
;
3383 qemu_event_increment ();
3387 if (next_cpu
&& env
!= next_cpu
) {
3392 void qemu_mutex_lock_iothread(void) {}
3393 void qemu_mutex_unlock_iothread(void) {}
3395 void vm_stop(int reason
)
3400 #else /* CONFIG_IOTHREAD */
3402 #include "qemu-thread.h"
3404 QemuMutex qemu_global_mutex
;
3405 static QemuMutex qemu_fair_mutex
;
3407 static QemuThread io_thread
;
3409 static QemuThread
*tcg_cpu_thread
;
3410 static QemuCond
*tcg_halt_cond
;
3412 static int qemu_system_ready
;
3414 static QemuCond qemu_cpu_cond
;
3416 static QemuCond qemu_system_cond
;
3417 static QemuCond qemu_pause_cond
;
3419 static void tcg_block_io_signals(void);
3420 static void kvm_block_io_signals(CPUState
*env
);
3421 static void unblock_io_signals(void);
3422 static int tcg_has_work(void);
3423 static int cpu_has_work(CPUState
*env
);
3425 static int qemu_init_main_loop(void)
3429 ret
= qemu_event_init();
3433 qemu_cond_init(&qemu_pause_cond
);
3434 qemu_mutex_init(&qemu_fair_mutex
);
3435 qemu_mutex_init(&qemu_global_mutex
);
3436 qemu_mutex_lock(&qemu_global_mutex
);
3438 unblock_io_signals();
3439 qemu_thread_self(&io_thread
);
3444 static void qemu_wait_io_event_common(CPUState
*env
)
3449 qemu_cond_signal(&qemu_pause_cond
);
3453 static void qemu_wait_io_event(CPUState
*env
)
3455 while (!tcg_has_work())
3456 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3458 qemu_mutex_unlock(&qemu_global_mutex
);
3461 * Users of qemu_global_mutex can be starved, having no chance
3462 * to acquire it since this path will get to it first.
3463 * So use another lock to provide fairness.
3465 qemu_mutex_lock(&qemu_fair_mutex
);
3466 qemu_mutex_unlock(&qemu_fair_mutex
);
3468 qemu_mutex_lock(&qemu_global_mutex
);
3469 qemu_wait_io_event_common(env
);
3472 static void qemu_kvm_eat_signal(CPUState
*env
, int timeout
)
3479 ts
.tv_sec
= timeout
/ 1000;
3480 ts
.tv_nsec
= (timeout
% 1000) * 1000000;
3482 sigemptyset(&waitset
);
3483 sigaddset(&waitset
, SIG_IPI
);
3485 qemu_mutex_unlock(&qemu_global_mutex
);
3486 r
= sigtimedwait(&waitset
, &siginfo
, &ts
);
3488 qemu_mutex_lock(&qemu_global_mutex
);
3490 if (r
== -1 && !(e
== EAGAIN
|| e
== EINTR
)) {
3491 fprintf(stderr
, "sigtimedwait: %s\n", strerror(e
));
3496 static void qemu_kvm_wait_io_event(CPUState
*env
)
3498 while (!cpu_has_work(env
))
3499 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3501 qemu_kvm_eat_signal(env
, 0);
3502 qemu_wait_io_event_common(env
);
3505 static int qemu_cpu_exec(CPUState
*env
);
3507 static void *kvm_cpu_thread_fn(void *arg
)
3509 CPUState
*env
= arg
;
3511 qemu_thread_self(env
->thread
);
3515 kvm_block_io_signals(env
);
3517 /* signal CPU creation */
3518 qemu_mutex_lock(&qemu_global_mutex
);
3520 qemu_cond_signal(&qemu_cpu_cond
);
3522 /* and wait for machine initialization */
3523 while (!qemu_system_ready
)
3524 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3527 if (cpu_can_run(env
))
3529 qemu_kvm_wait_io_event(env
);
3535 static void tcg_cpu_exec(void);
3537 static void *tcg_cpu_thread_fn(void *arg
)
3539 CPUState
*env
= arg
;
3541 tcg_block_io_signals();
3542 qemu_thread_self(env
->thread
);
3544 /* signal CPU creation */
3545 qemu_mutex_lock(&qemu_global_mutex
);
3546 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
3548 qemu_cond_signal(&qemu_cpu_cond
);
3550 /* and wait for machine initialization */
3551 while (!qemu_system_ready
)
3552 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3556 qemu_wait_io_event(cur_cpu
);
3562 void qemu_cpu_kick(void *_env
)
3564 CPUState
*env
= _env
;
3565 qemu_cond_broadcast(env
->halt_cond
);
3567 qemu_thread_signal(env
->thread
, SIG_IPI
);
3570 int qemu_cpu_self(void *_env
)
3572 CPUState
*env
= _env
;
3575 qemu_thread_self(&this);
3577 return qemu_thread_equal(&this, env
->thread
);
3580 static void cpu_signal(int sig
)
3583 cpu_exit(cpu_single_env
);
3586 static void tcg_block_io_signals(void)
3589 struct sigaction sigact
;
3592 sigaddset(&set
, SIGUSR2
);
3593 sigaddset(&set
, SIGIO
);
3594 sigaddset(&set
, SIGALRM
);
3595 sigaddset(&set
, SIGCHLD
);
3596 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3599 sigaddset(&set
, SIG_IPI
);
3600 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3602 memset(&sigact
, 0, sizeof(sigact
));
3603 sigact
.sa_handler
= cpu_signal
;
3604 sigaction(SIG_IPI
, &sigact
, NULL
);
3607 static void dummy_signal(int sig
)
3611 static void kvm_block_io_signals(CPUState
*env
)
3615 struct sigaction sigact
;
3618 sigaddset(&set
, SIGUSR2
);
3619 sigaddset(&set
, SIGIO
);
3620 sigaddset(&set
, SIGALRM
);
3621 sigaddset(&set
, SIGCHLD
);
3622 sigaddset(&set
, SIG_IPI
);
3623 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3625 pthread_sigmask(SIG_BLOCK
, NULL
, &set
);
3626 sigdelset(&set
, SIG_IPI
);
3628 memset(&sigact
, 0, sizeof(sigact
));
3629 sigact
.sa_handler
= dummy_signal
;
3630 sigaction(SIG_IPI
, &sigact
, NULL
);
3632 r
= kvm_set_signal_mask(env
, &set
);
3634 fprintf(stderr
, "kvm_set_signal_mask: %s\n", strerror(r
));
3639 static void unblock_io_signals(void)
3644 sigaddset(&set
, SIGUSR2
);
3645 sigaddset(&set
, SIGIO
);
3646 sigaddset(&set
, SIGALRM
);
3647 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3650 sigaddset(&set
, SIG_IPI
);
3651 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3654 static void qemu_signal_lock(unsigned int msecs
)
3656 qemu_mutex_lock(&qemu_fair_mutex
);
3658 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
3659 qemu_thread_signal(tcg_cpu_thread
, SIG_IPI
);
3660 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
3663 qemu_mutex_unlock(&qemu_fair_mutex
);
3666 void qemu_mutex_lock_iothread(void)
3668 if (kvm_enabled()) {
3669 qemu_mutex_lock(&qemu_fair_mutex
);
3670 qemu_mutex_lock(&qemu_global_mutex
);
3671 qemu_mutex_unlock(&qemu_fair_mutex
);
3673 qemu_signal_lock(100);
3676 void qemu_mutex_unlock_iothread(void)
3678 qemu_mutex_unlock(&qemu_global_mutex
);
3681 static int all_vcpus_paused(void)
3683 CPUState
*penv
= first_cpu
;
3688 penv
= (CPUState
*)penv
->next_cpu
;
3694 static void pause_all_vcpus(void)
3696 CPUState
*penv
= first_cpu
;
3700 qemu_thread_signal(penv
->thread
, SIG_IPI
);
3701 qemu_cpu_kick(penv
);
3702 penv
= (CPUState
*)penv
->next_cpu
;
3705 while (!all_vcpus_paused()) {
3706 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
3709 qemu_thread_signal(penv
->thread
, SIG_IPI
);
3710 penv
= (CPUState
*)penv
->next_cpu
;
3715 static void resume_all_vcpus(void)
3717 CPUState
*penv
= first_cpu
;
3722 qemu_thread_signal(penv
->thread
, SIG_IPI
);
3723 qemu_cpu_kick(penv
);
3724 penv
= (CPUState
*)penv
->next_cpu
;
3728 static void tcg_init_vcpu(void *_env
)
3730 CPUState
*env
= _env
;
3731 /* share a single thread for all cpus with TCG */
3732 if (!tcg_cpu_thread
) {
3733 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3734 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3735 qemu_cond_init(env
->halt_cond
);
3736 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
3737 while (env
->created
== 0)
3738 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3739 tcg_cpu_thread
= env
->thread
;
3740 tcg_halt_cond
= env
->halt_cond
;
3742 env
->thread
= tcg_cpu_thread
;
3743 env
->halt_cond
= tcg_halt_cond
;
3747 static void kvm_start_vcpu(CPUState
*env
)
3749 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3750 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3751 qemu_cond_init(env
->halt_cond
);
3752 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
3753 while (env
->created
== 0)
3754 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3757 void qemu_init_vcpu(void *_env
)
3759 CPUState
*env
= _env
;
3761 env
->nr_cores
= smp_cores
;
3762 env
->nr_threads
= smp_threads
;
3764 kvm_start_vcpu(env
);
3769 void qemu_notify_event(void)
3771 qemu_event_increment();
3774 void vm_stop(int reason
)
3777 qemu_thread_self(&me
);
3779 if (!qemu_thread_equal(&me
, &io_thread
)) {
3780 qemu_system_vmstop_request(reason
);
3782 * FIXME: should not return to device code in case
3783 * vm_stop() has been requested.
3785 if (cpu_single_env
) {
3786 cpu_exit(cpu_single_env
);
3787 cpu_single_env
->stop
= 1;
3798 static void host_main_loop_wait(int *timeout
)
3804 /* XXX: need to suppress polling by better using win32 events */
3806 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
3807 ret
|= pe
->func(pe
->opaque
);
3811 WaitObjects
*w
= &wait_objects
;
3813 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
3814 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
3815 if (w
->func
[ret
- WAIT_OBJECT_0
])
3816 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
3818 /* Check for additional signaled events */
3819 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
3821 /* Check if event is signaled */
3822 ret2
= WaitForSingleObject(w
->events
[i
], 0);
3823 if(ret2
== WAIT_OBJECT_0
) {
3825 w
->func
[i
](w
->opaque
[i
]);
3826 } else if (ret2
== WAIT_TIMEOUT
) {
3828 err
= GetLastError();
3829 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
3832 } else if (ret
== WAIT_TIMEOUT
) {
3834 err
= GetLastError();
3835 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
3842 static void host_main_loop_wait(int *timeout
)
3847 void main_loop_wait(int timeout
)
3849 IOHandlerRecord
*ioh
;
3850 fd_set rfds
, wfds
, xfds
;
3854 qemu_bh_update_timeout(&timeout
);
3856 host_main_loop_wait(&timeout
);
3858 /* poll any events */
3859 /* XXX: separate device handlers from system ones */
3864 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3868 (!ioh
->fd_read_poll
||
3869 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
3870 FD_SET(ioh
->fd
, &rfds
);
3874 if (ioh
->fd_write
) {
3875 FD_SET(ioh
->fd
, &wfds
);
3881 tv
.tv_sec
= timeout
/ 1000;
3882 tv
.tv_usec
= (timeout
% 1000) * 1000;
3884 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
3886 qemu_mutex_unlock_iothread();
3887 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
3888 qemu_mutex_lock_iothread();
3890 IOHandlerRecord
**pioh
;
3892 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3893 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
3894 ioh
->fd_read(ioh
->opaque
);
3896 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
3897 ioh
->fd_write(ioh
->opaque
);
3901 /* remove deleted IO handlers */
3902 pioh
= &first_io_handler
;
3913 slirp_select_poll(&rfds
, &wfds
, &xfds
, (ret
< 0));
3915 qemu_run_all_timers();
3917 /* Check bottom-halves last in case any of the earlier events triggered
3923 static int qemu_cpu_exec(CPUState
*env
)
3926 #ifdef CONFIG_PROFILER
3930 #ifdef CONFIG_PROFILER
3931 ti
= profile_getclock();
3936 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
3937 env
->icount_decr
.u16
.low
= 0;
3938 env
->icount_extra
= 0;
3939 count
= qemu_next_deadline();
3940 count
= (count
+ (1 << icount_time_shift
) - 1)
3941 >> icount_time_shift
;
3942 qemu_icount
+= count
;
3943 decr
= (count
> 0xffff) ? 0xffff : count
;
3945 env
->icount_decr
.u16
.low
= decr
;
3946 env
->icount_extra
= count
;
3948 ret
= cpu_exec(env
);
3949 #ifdef CONFIG_PROFILER
3950 qemu_time
+= profile_getclock() - ti
;
3953 /* Fold pending instructions back into the
3954 instruction counter, and clear the interrupt flag. */
3955 qemu_icount
-= (env
->icount_decr
.u16
.low
3956 + env
->icount_extra
);
3957 env
->icount_decr
.u32
= 0;
3958 env
->icount_extra
= 0;
3963 static void tcg_cpu_exec(void)
3967 if (next_cpu
== NULL
)
3968 next_cpu
= first_cpu
;
3969 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
3970 CPUState
*env
= cur_cpu
= next_cpu
;
3972 if (alarm_timer
->pending
)
3974 if (cpu_can_run(env
))
3975 ret
= qemu_cpu_exec(env
);
3979 if (ret
== EXCP_DEBUG
) {
3980 gdb_set_stop_cpu(env
);
3981 debug_requested
= 1;
3987 static int cpu_has_work(CPUState
*env
)
3995 if (qemu_cpu_has_work(env
))
4000 static int tcg_has_work(void)
4004 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4005 if (cpu_has_work(env
))
4010 static int qemu_calculate_timeout(void)
4012 #ifndef CONFIG_IOTHREAD
4017 else if (tcg_has_work())
4019 else if (!use_icount
)
4022 /* XXX: use timeout computed from timers */
4025 /* Advance virtual time to the next event. */
4026 if (use_icount
== 1) {
4027 /* When not using an adaptive execution frequency
4028 we tend to get badly out of sync with real time,
4029 so just delay for a reasonable amount of time. */
4032 delta
= cpu_get_icount() - cpu_get_clock();
4035 /* If virtual time is ahead of real time then just
4037 timeout
= (delta
/ 1000000) + 1;
4039 /* Wait for either IO to occur or the next
4041 add
= qemu_next_deadline();
4042 /* We advance the timer before checking for IO.
4043 Limit the amount we advance so that early IO
4044 activity won't get the guest too far ahead. */
4048 add
= (add
+ (1 << icount_time_shift
) - 1)
4049 >> icount_time_shift
;
4051 timeout
= delta
/ 1000000;
4058 #else /* CONFIG_IOTHREAD */
4063 static int vm_can_run(void)
4065 if (powerdown_requested
)
4067 if (reset_requested
)
4069 if (shutdown_requested
)
4071 if (debug_requested
)
4076 qemu_irq qemu_system_powerdown
;
4078 static void main_loop(void)
4082 #ifdef CONFIG_IOTHREAD
4083 qemu_system_ready
= 1;
4084 qemu_cond_broadcast(&qemu_system_cond
);
4089 #ifdef CONFIG_PROFILER
4092 #ifndef CONFIG_IOTHREAD
4095 #ifdef CONFIG_PROFILER
4096 ti
= profile_getclock();
4098 main_loop_wait(qemu_calculate_timeout());
4099 #ifdef CONFIG_PROFILER
4100 dev_time
+= profile_getclock() - ti
;
4102 } while (vm_can_run());
4104 if (qemu_debug_requested()) {
4105 vm_stop(EXCP_DEBUG
);
4107 if (qemu_shutdown_requested()) {
4108 monitor_protocol_event(QEVENT_SHUTDOWN
, NULL
);
4115 if (qemu_reset_requested()) {
4117 qemu_system_reset();
4120 if (qemu_powerdown_requested()) {
4121 monitor_protocol_event(QEVENT_POWERDOWN
, NULL
);
4122 qemu_irq_raise(qemu_system_powerdown
);
4124 if ((r
= qemu_vmstop_requested())) {
4131 static void version(void)
4133 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4136 static void help(int exitcode
)
4138 const char *options_help
=
4139 #define DEF(option, opt_arg, opt_enum, opt_help) \
4141 #define DEFHEADING(text) stringify(text) "\n"
4142 #include "qemu-options.h"
4148 printf("usage: %s [options] [disk_image]\n"
4150 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4153 "During emulation, the following keys are useful:\n"
4154 "ctrl-alt-f toggle full screen\n"
4155 "ctrl-alt-n switch to virtual console 'n'\n"
4156 "ctrl-alt toggle mouse and keyboard grab\n"
4158 "When using -nographic, press 'ctrl-a h' to get some help.\n",
4164 #define HAS_ARG 0x0001
4167 #define DEF(option, opt_arg, opt_enum, opt_help) \
4169 #define DEFHEADING(text)
4170 #include "qemu-options.h"
4176 typedef struct QEMUOption
{
4182 static const QEMUOption qemu_options
[] = {
4183 { "h", 0, QEMU_OPTION_h
},
4184 #define DEF(option, opt_arg, opt_enum, opt_help) \
4185 { option, opt_arg, opt_enum },
4186 #define DEFHEADING(text)
4187 #include "qemu-options.h"
4195 struct soundhw soundhw
[] = {
4196 #ifdef HAS_AUDIO_CHOICE
4197 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4203 { .init_isa
= pcspk_audio_init
}
4210 "Creative Sound Blaster 16",
4213 { .init_isa
= SB16_init
}
4217 #ifdef CONFIG_CS4231A
4223 { .init_isa
= cs4231a_init
}
4231 "Yamaha YMF262 (OPL3)",
4233 "Yamaha YM3812 (OPL2)",
4237 { .init_isa
= Adlib_init
}
4244 "Gravis Ultrasound GF1",
4247 { .init_isa
= GUS_init
}
4254 "Intel 82801AA AC97 Audio",
4257 { .init_pci
= ac97_init
}
4261 #ifdef CONFIG_ES1370
4264 "ENSONIQ AudioPCI ES1370",
4267 { .init_pci
= es1370_init
}
4271 #endif /* HAS_AUDIO_CHOICE */
4273 { NULL
, NULL
, 0, 0, { NULL
} }
4276 static void select_soundhw (const char *optarg
)
4280 if (*optarg
== '?') {
4283 printf ("Valid sound card names (comma separated):\n");
4284 for (c
= soundhw
; c
->name
; ++c
) {
4285 printf ("%-11s %s\n", c
->name
, c
->descr
);
4287 printf ("\n-soundhw all will enable all of the above\n");
4288 exit (*optarg
!= '?');
4296 if (!strcmp (optarg
, "all")) {
4297 for (c
= soundhw
; c
->name
; ++c
) {
4305 e
= strchr (p
, ',');
4306 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4308 for (c
= soundhw
; c
->name
; ++c
) {
4309 if (!strncmp (c
->name
, p
, l
) && !c
->name
[l
]) {
4318 "Unknown sound card name (too big to show)\n");
4321 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4326 p
+= l
+ (e
!= NULL
);
4330 goto show_valid_cards
;
4335 static void select_vgahw (const char *p
)
4340 vga_interface_type
= VGA_NONE
;
4341 if (strstart(p
, "std", &opts
)) {
4342 vga_interface_type
= VGA_STD
;
4343 } else if (strstart(p
, "cirrus", &opts
)) {
4344 vga_interface_type
= VGA_CIRRUS
;
4345 } else if (strstart(p
, "vmware", &opts
)) {
4346 vga_interface_type
= VGA_VMWARE
;
4347 } else if (strstart(p
, "xenfb", &opts
)) {
4348 vga_interface_type
= VGA_XENFB
;
4349 } else if (!strstart(p
, "none", &opts
)) {
4351 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4355 const char *nextopt
;
4357 if (strstart(opts
, ",retrace=", &nextopt
)) {
4359 if (strstart(opts
, "dumb", &nextopt
))
4360 vga_retrace_method
= VGA_RETRACE_DUMB
;
4361 else if (strstart(opts
, "precise", &nextopt
))
4362 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4363 else goto invalid_vga
;
4364 } else goto invalid_vga
;
4370 static int balloon_parse(const char *arg
)
4374 if (strcmp(arg
, "none") == 0) {
4378 if (!strncmp(arg
, "virtio", 6)) {
4379 if (arg
[6] == ',') {
4380 /* have params -> parse them */
4381 opts
= qemu_opts_parse(&qemu_device_opts
, arg
+7, 0);
4385 /* create empty opts */
4386 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4388 qemu_opt_set(opts
, "driver", "virtio-balloon-pci");
4397 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4399 exit(STATUS_CONTROL_C_EXIT
);
4404 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4408 if(strlen(str
) != 36)
4411 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4412 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4413 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4419 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4427 static void termsig_handler(int signal
)
4429 qemu_system_shutdown_request();
4432 static void sigchld_handler(int signal
)
4434 waitpid(-1, NULL
, WNOHANG
);
4437 static void sighandler_setup(void)
4439 struct sigaction act
;
4441 memset(&act
, 0, sizeof(act
));
4442 act
.sa_handler
= termsig_handler
;
4443 sigaction(SIGINT
, &act
, NULL
);
4444 sigaction(SIGHUP
, &act
, NULL
);
4445 sigaction(SIGTERM
, &act
, NULL
);
4447 act
.sa_handler
= sigchld_handler
;
4448 act
.sa_flags
= SA_NOCLDSTOP
;
4449 sigaction(SIGCHLD
, &act
, NULL
);
4455 /* Look for support files in the same directory as the executable. */
4456 static char *find_datadir(const char *argv0
)
4462 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
4469 while (p
!= buf
&& *p
!= '\\')
4472 if (access(buf
, R_OK
) == 0) {
4473 return qemu_strdup(buf
);
4479 /* Find a likely location for support files using the location of the binary.
4480 For installed binaries this will be "$bindir/../share/qemu". When
4481 running from the build tree this will be "$bindir/../pc-bios". */
4482 #define SHARE_SUFFIX "/share/qemu"
4483 #define BUILD_SUFFIX "/pc-bios"
4484 static char *find_datadir(const char *argv0
)
4492 #if defined(__linux__)
4495 len
= readlink("/proc/self/exe", buf
, sizeof(buf
) - 1);
4501 #elif defined(__FreeBSD__)
4504 len
= readlink("/proc/curproc/file", buf
, sizeof(buf
) - 1);
4511 /* If we don't have any way of figuring out the actual executable
4512 location then try argv[0]. */
4514 p
= realpath(argv0
, buf
);
4522 max_len
= strlen(dir
) +
4523 MAX(strlen(SHARE_SUFFIX
), strlen(BUILD_SUFFIX
)) + 1;
4524 res
= qemu_mallocz(max_len
);
4525 snprintf(res
, max_len
, "%s%s", dir
, SHARE_SUFFIX
);
4526 if (access(res
, R_OK
)) {
4527 snprintf(res
, max_len
, "%s%s", dir
, BUILD_SUFFIX
);
4528 if (access(res
, R_OK
)) {
4540 char *qemu_find_file(int type
, const char *name
)
4546 /* If name contains path separators then try it as a straight path. */
4547 if ((strchr(name
, '/') || strchr(name
, '\\'))
4548 && access(name
, R_OK
) == 0) {
4549 return qemu_strdup(name
);
4552 case QEMU_FILE_TYPE_BIOS
:
4555 case QEMU_FILE_TYPE_KEYMAP
:
4556 subdir
= "keymaps/";
4561 len
= strlen(data_dir
) + strlen(name
) + strlen(subdir
) + 2;
4562 buf
= qemu_mallocz(len
);
4563 snprintf(buf
, len
, "%s/%s%s", data_dir
, subdir
, name
);
4564 if (access(buf
, R_OK
)) {
4571 static int device_help_func(QemuOpts
*opts
, void *opaque
)
4573 return qdev_device_help(opts
);
4576 static int device_init_func(QemuOpts
*opts
, void *opaque
)
4580 dev
= qdev_device_add(opts
);
4586 static int chardev_init_func(QemuOpts
*opts
, void *opaque
)
4588 CharDriverState
*chr
;
4590 chr
= qemu_chr_open_opts(opts
, NULL
);
4596 static int mon_init_func(QemuOpts
*opts
, void *opaque
)
4598 CharDriverState
*chr
;
4599 const char *chardev
;
4603 mode
= qemu_opt_get(opts
, "mode");
4607 if (strcmp(mode
, "readline") == 0) {
4608 flags
= MONITOR_USE_READLINE
;
4609 } else if (strcmp(mode
, "control") == 0) {
4610 flags
= MONITOR_USE_CONTROL
;
4612 fprintf(stderr
, "unknown monitor mode \"%s\"\n", mode
);
4616 if (qemu_opt_get_bool(opts
, "default", 0))
4617 flags
|= MONITOR_IS_DEFAULT
;
4619 chardev
= qemu_opt_get(opts
, "chardev");
4620 chr
= qemu_chr_find(chardev
);
4622 fprintf(stderr
, "chardev \"%s\" not found\n", chardev
);
4626 monitor_init(chr
, flags
);
4630 static void monitor_parse(const char *optarg
, const char *mode
)
4632 static int monitor_device_index
= 0;
4638 if (strstart(optarg
, "chardev:", &p
)) {
4639 snprintf(label
, sizeof(label
), "%s", p
);
4641 if (monitor_device_index
) {
4642 snprintf(label
, sizeof(label
), "monitor%d",
4643 monitor_device_index
);
4645 snprintf(label
, sizeof(label
), "monitor");
4648 opts
= qemu_chr_parse_compat(label
, optarg
);
4650 fprintf(stderr
, "parse error: %s\n", optarg
);
4655 opts
= qemu_opts_create(&qemu_mon_opts
, label
, 1);
4657 fprintf(stderr
, "duplicate chardev: %s\n", label
);
4660 qemu_opt_set(opts
, "mode", mode
);
4661 qemu_opt_set(opts
, "chardev", label
);
4663 qemu_opt_set(opts
, "default", "on");
4664 monitor_device_index
++;
4667 struct device_config
{
4669 DEV_USB
, /* -usbdevice */
4671 DEV_SERIAL
, /* -serial */
4672 DEV_PARALLEL
, /* -parallel */
4673 DEV_VIRTCON
, /* -virtioconsole */
4674 DEV_DEBUGCON
, /* -debugcon */
4676 const char *cmdline
;
4677 QTAILQ_ENTRY(device_config
) next
;
4679 QTAILQ_HEAD(, device_config
) device_configs
= QTAILQ_HEAD_INITIALIZER(device_configs
);
4681 static void add_device_config(int type
, const char *cmdline
)
4683 struct device_config
*conf
;
4685 conf
= qemu_mallocz(sizeof(*conf
));
4687 conf
->cmdline
= cmdline
;
4688 QTAILQ_INSERT_TAIL(&device_configs
, conf
, next
);
4691 static int foreach_device_config(int type
, int (*func
)(const char *cmdline
))
4693 struct device_config
*conf
;
4696 QTAILQ_FOREACH(conf
, &device_configs
, next
) {
4697 if (conf
->type
!= type
)
4699 rc
= func(conf
->cmdline
);
4706 static int serial_parse(const char *devname
)
4708 static int index
= 0;
4711 if (strcmp(devname
, "none") == 0)
4713 if (index
== MAX_SERIAL_PORTS
) {
4714 fprintf(stderr
, "qemu: too many serial ports\n");
4717 snprintf(label
, sizeof(label
), "serial%d", index
);
4718 serial_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4719 if (!serial_hds
[index
]) {
4720 fprintf(stderr
, "qemu: could not open serial device '%s': %s\n",
4721 devname
, strerror(errno
));
4728 static int parallel_parse(const char *devname
)
4730 static int index
= 0;
4733 if (strcmp(devname
, "none") == 0)
4735 if (index
== MAX_PARALLEL_PORTS
) {
4736 fprintf(stderr
, "qemu: too many parallel ports\n");
4739 snprintf(label
, sizeof(label
), "parallel%d", index
);
4740 parallel_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4741 if (!parallel_hds
[index
]) {
4742 fprintf(stderr
, "qemu: could not open parallel device '%s': %s\n",
4743 devname
, strerror(errno
));
4750 static int virtcon_parse(const char *devname
)
4752 static int index
= 0;
4754 QemuOpts
*bus_opts
, *dev_opts
;
4756 if (strcmp(devname
, "none") == 0)
4758 if (index
== MAX_VIRTIO_CONSOLES
) {
4759 fprintf(stderr
, "qemu: too many virtio consoles\n");
4763 bus_opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4764 qemu_opt_set(bus_opts
, "driver", "virtio-serial");
4766 dev_opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4767 qemu_opt_set(dev_opts
, "driver", "virtconsole");
4769 snprintf(label
, sizeof(label
), "virtcon%d", index
);
4770 virtcon_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4771 if (!virtcon_hds
[index
]) {
4772 fprintf(stderr
, "qemu: could not open virtio console '%s': %s\n",
4773 devname
, strerror(errno
));
4776 qemu_opt_set(dev_opts
, "chardev", label
);
4782 static int debugcon_parse(const char *devname
)
4786 if (!qemu_chr_open("debugcon", devname
, NULL
)) {
4789 opts
= qemu_opts_create(&qemu_device_opts
, "debugcon", 1);
4791 fprintf(stderr
, "qemu: already have a debugcon device\n");
4794 qemu_opt_set(opts
, "driver", "isa-debugcon");
4795 qemu_opt_set(opts
, "chardev", "debugcon");
4799 static const QEMUOption
*lookup_opt(int argc
, char **argv
,
4800 const char **poptarg
, int *poptind
)
4802 const QEMUOption
*popt
;
4803 int optind
= *poptind
;
4804 char *r
= argv
[optind
];
4807 loc_set_cmdline(argv
, optind
, 1);
4809 /* Treat --foo the same as -foo. */
4812 popt
= qemu_options
;
4815 error_report("invalid option");
4818 if (!strcmp(popt
->name
, r
+ 1))
4822 if (popt
->flags
& HAS_ARG
) {
4823 if (optind
>= argc
) {
4824 error_report("requires an argument");
4827 optarg
= argv
[optind
++];
4828 loc_set_cmdline(argv
, optind
- 2, 2);
4839 int main(int argc
, char **argv
, char **envp
)
4841 const char *gdbstub_dev
= NULL
;
4842 uint32_t boot_devices_bitmap
= 0;
4844 int snapshot
, linux_boot
, net_boot
;
4845 const char *initrd_filename
;
4846 const char *kernel_filename
, *kernel_cmdline
;
4847 char boot_devices
[33] = "cad"; /* default to HD->floppy->CD-ROM */
4849 DisplayChangeListener
*dcl
;
4850 int cyls
, heads
, secs
, translation
;
4851 QemuOpts
*hda_opts
= NULL
, *opts
;
4854 const char *loadvm
= NULL
;
4855 QEMUMachine
*machine
;
4856 const char *cpu_model
;
4861 const char *pid_file
= NULL
;
4862 const char *incoming
= NULL
;
4865 struct passwd
*pwd
= NULL
;
4866 const char *chroot_dir
= NULL
;
4867 const char *run_as
= NULL
;
4870 int show_vnc_port
= 0;
4873 error_set_progname(argv
[0]);
4877 qemu_cache_utils_init(envp
);
4879 QLIST_INIT (&vm_change_state_head
);
4882 struct sigaction act
;
4883 sigfillset(&act
.sa_mask
);
4885 act
.sa_handler
= SIG_IGN
;
4886 sigaction(SIGPIPE
, &act
, NULL
);
4889 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4890 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4891 QEMU to run on a single CPU */
4896 h
= GetCurrentProcess();
4897 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4898 for(i
= 0; i
< 32; i
++) {
4899 if (mask
& (1 << i
))
4904 SetProcessAffinityMask(h
, mask
);
4910 module_call_init(MODULE_INIT_MACHINE
);
4911 machine
= find_default_machine();
4913 initrd_filename
= NULL
;
4916 kernel_filename
= NULL
;
4917 kernel_cmdline
= "";
4918 cyls
= heads
= secs
= 0;
4919 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4921 for (i
= 0; i
< MAX_NODES
; i
++) {
4923 node_cpumask
[i
] = 0;
4932 /* first pass of option parsing */
4934 while (optind
< argc
) {
4935 if (argv
[optind
][0] != '-') {
4940 const QEMUOption
*popt
;
4942 popt
= lookup_opt(argc
, argv
, &optarg
, &optind
);
4943 switch (popt
->index
) {
4944 case QEMU_OPTION_nodefconfig
:
4955 fname
= CONFIG_QEMU_CONFDIR
"/qemu.conf";
4956 fp
= fopen(fname
, "r");
4958 if (qemu_config_parse(fp
, fname
) != 0) {
4964 fname
= CONFIG_QEMU_CONFDIR
"/target-" TARGET_ARCH
".conf";
4965 fp
= fopen(fname
, "r");
4967 if (qemu_config_parse(fp
, fname
) != 0) {
4973 #if defined(cpudef_setup)
4974 cpudef_setup(); /* parse cpu definitions in target config file */
4977 /* second pass of option parsing */
4982 if (argv
[optind
][0] != '-') {
4983 hda_opts
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
4985 const QEMUOption
*popt
;
4987 popt
= lookup_opt(argc
, argv
, &optarg
, &optind
);
4988 switch(popt
->index
) {
4990 machine
= find_machine(optarg
);
4993 printf("Supported machines are:\n");
4994 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
4996 printf("%-10s %s (alias of %s)\n",
4997 m
->alias
, m
->desc
, m
->name
);
4998 printf("%-10s %s%s\n",
5000 m
->is_default
? " (default)" : "");
5002 exit(*optarg
!= '?');
5005 case QEMU_OPTION_cpu
:
5006 /* hw initialization will check this */
5007 if (*optarg
== '?') {
5008 /* XXX: implement xxx_cpu_list for targets that still miss it */
5009 #if defined(cpu_list_id)
5010 cpu_list_id(stdout
, &fprintf
, optarg
);
5011 #elif defined(cpu_list)
5012 cpu_list(stdout
, &fprintf
); /* deprecated */
5019 case QEMU_OPTION_initrd
:
5020 initrd_filename
= optarg
;
5022 case QEMU_OPTION_hda
:
5024 hda_opts
= drive_add(optarg
, HD_ALIAS
, 0);
5026 hda_opts
= drive_add(optarg
, HD_ALIAS
5027 ",cyls=%d,heads=%d,secs=%d%s",
5028 0, cyls
, heads
, secs
,
5029 translation
== BIOS_ATA_TRANSLATION_LBA
?
5031 translation
== BIOS_ATA_TRANSLATION_NONE
?
5032 ",trans=none" : "");
5034 case QEMU_OPTION_hdb
:
5035 case QEMU_OPTION_hdc
:
5036 case QEMU_OPTION_hdd
:
5037 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
5039 case QEMU_OPTION_drive
:
5040 drive_add(NULL
, "%s", optarg
);
5042 case QEMU_OPTION_set
:
5043 if (qemu_set_option(optarg
) != 0)
5046 case QEMU_OPTION_global
:
5047 if (qemu_global_option(optarg
) != 0)
5050 case QEMU_OPTION_mtdblock
:
5051 drive_add(optarg
, MTD_ALIAS
);
5053 case QEMU_OPTION_sd
:
5054 drive_add(optarg
, SD_ALIAS
);
5056 case QEMU_OPTION_pflash
:
5057 drive_add(optarg
, PFLASH_ALIAS
);
5059 case QEMU_OPTION_snapshot
:
5062 case QEMU_OPTION_hdachs
:
5066 cyls
= strtol(p
, (char **)&p
, 0);
5067 if (cyls
< 1 || cyls
> 16383)
5072 heads
= strtol(p
, (char **)&p
, 0);
5073 if (heads
< 1 || heads
> 16)
5078 secs
= strtol(p
, (char **)&p
, 0);
5079 if (secs
< 1 || secs
> 63)
5083 if (!strcmp(p
, "none"))
5084 translation
= BIOS_ATA_TRANSLATION_NONE
;
5085 else if (!strcmp(p
, "lba"))
5086 translation
= BIOS_ATA_TRANSLATION_LBA
;
5087 else if (!strcmp(p
, "auto"))
5088 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5091 } else if (*p
!= '\0') {
5093 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5096 if (hda_opts
!= NULL
) {
5098 snprintf(num
, sizeof(num
), "%d", cyls
);
5099 qemu_opt_set(hda_opts
, "cyls", num
);
5100 snprintf(num
, sizeof(num
), "%d", heads
);
5101 qemu_opt_set(hda_opts
, "heads", num
);
5102 snprintf(num
, sizeof(num
), "%d", secs
);
5103 qemu_opt_set(hda_opts
, "secs", num
);
5104 if (translation
== BIOS_ATA_TRANSLATION_LBA
)
5105 qemu_opt_set(hda_opts
, "trans", "lba");
5106 if (translation
== BIOS_ATA_TRANSLATION_NONE
)
5107 qemu_opt_set(hda_opts
, "trans", "none");
5111 case QEMU_OPTION_numa
:
5112 if (nb_numa_nodes
>= MAX_NODES
) {
5113 fprintf(stderr
, "qemu: too many NUMA nodes\n");
5118 case QEMU_OPTION_nographic
:
5119 display_type
= DT_NOGRAPHIC
;
5121 #ifdef CONFIG_CURSES
5122 case QEMU_OPTION_curses
:
5123 display_type
= DT_CURSES
;
5126 case QEMU_OPTION_portrait
:
5129 case QEMU_OPTION_kernel
:
5130 kernel_filename
= optarg
;
5132 case QEMU_OPTION_append
:
5133 kernel_cmdline
= optarg
;
5135 case QEMU_OPTION_cdrom
:
5136 drive_add(optarg
, CDROM_ALIAS
);
5138 case QEMU_OPTION_boot
:
5140 static const char * const params
[] = {
5141 "order", "once", "menu", NULL
5143 char buf
[sizeof(boot_devices
)];
5144 char *standard_boot_devices
;
5147 if (!strchr(optarg
, '=')) {
5149 pstrcpy(buf
, sizeof(buf
), optarg
);
5150 } else if (check_params(buf
, sizeof(buf
), params
, optarg
) < 0) {
5152 "qemu: unknown boot parameter '%s' in '%s'\n",
5158 get_param_value(buf
, sizeof(buf
), "order", optarg
)) {
5159 boot_devices_bitmap
= parse_bootdevices(buf
);
5160 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5163 if (get_param_value(buf
, sizeof(buf
),
5165 boot_devices_bitmap
|= parse_bootdevices(buf
);
5166 standard_boot_devices
= qemu_strdup(boot_devices
);
5167 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5168 qemu_register_reset(restore_boot_devices
,
5169 standard_boot_devices
);
5171 if (get_param_value(buf
, sizeof(buf
),
5173 if (!strcmp(buf
, "on")) {
5175 } else if (!strcmp(buf
, "off")) {
5179 "qemu: invalid option value '%s'\n",
5187 case QEMU_OPTION_fda
:
5188 case QEMU_OPTION_fdb
:
5189 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
5192 case QEMU_OPTION_no_fd_bootchk
:
5196 case QEMU_OPTION_netdev
:
5197 if (net_client_parse(&qemu_netdev_opts
, optarg
) == -1) {
5201 case QEMU_OPTION_net
:
5202 if (net_client_parse(&qemu_net_opts
, optarg
) == -1) {
5207 case QEMU_OPTION_tftp
:
5208 legacy_tftp_prefix
= optarg
;
5210 case QEMU_OPTION_bootp
:
5211 legacy_bootp_filename
= optarg
;
5214 case QEMU_OPTION_smb
:
5215 if (net_slirp_smb(optarg
) < 0)
5219 case QEMU_OPTION_redir
:
5220 if (net_slirp_redir(optarg
) < 0)
5224 case QEMU_OPTION_bt
:
5225 add_device_config(DEV_BT
, optarg
);
5228 case QEMU_OPTION_audio_help
:
5232 case QEMU_OPTION_soundhw
:
5233 select_soundhw (optarg
);
5239 case QEMU_OPTION_version
:
5243 case QEMU_OPTION_m
: {
5247 value
= strtoul(optarg
, &ptr
, 10);
5249 case 0: case 'M': case 'm':
5256 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5260 /* On 32-bit hosts, QEMU is limited by virtual address space */
5261 if (value
> (2047 << 20) && HOST_LONG_BITS
== 32) {
5262 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5265 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5266 fprintf(stderr
, "qemu: ram size too large\n");
5272 case QEMU_OPTION_mempath
:
5276 case QEMU_OPTION_mem_prealloc
:
5283 const CPULogItem
*item
;
5285 mask
= cpu_str_to_log_mask(optarg
);
5287 printf("Log items (comma separated):\n");
5288 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5289 printf("%-10s %s\n", item
->name
, item
->help
);
5297 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5299 case QEMU_OPTION_gdb
:
5300 gdbstub_dev
= optarg
;
5305 case QEMU_OPTION_bios
:
5308 case QEMU_OPTION_singlestep
:
5315 keyboard_layout
= optarg
;
5317 case QEMU_OPTION_localtime
:
5320 case QEMU_OPTION_vga
:
5321 select_vgahw (optarg
);
5323 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5329 w
= strtol(p
, (char **)&p
, 10);
5332 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5338 h
= strtol(p
, (char **)&p
, 10);
5343 depth
= strtol(p
, (char **)&p
, 10);
5344 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5345 depth
!= 24 && depth
!= 32)
5347 } else if (*p
== '\0') {
5348 depth
= graphic_depth
;
5355 graphic_depth
= depth
;
5359 case QEMU_OPTION_echr
:
5362 term_escape_char
= strtol(optarg
, &r
, 0);
5364 printf("Bad argument to echr\n");
5367 case QEMU_OPTION_monitor
:
5368 monitor_parse(optarg
, "readline");
5369 default_monitor
= 0;
5371 case QEMU_OPTION_qmp
:
5372 monitor_parse(optarg
, "control");
5373 default_monitor
= 0;
5375 case QEMU_OPTION_mon
:
5376 opts
= qemu_opts_parse(&qemu_mon_opts
, optarg
, 1);
5378 fprintf(stderr
, "parse error: %s\n", optarg
);
5381 default_monitor
= 0;
5383 case QEMU_OPTION_chardev
:
5384 opts
= qemu_opts_parse(&qemu_chardev_opts
, optarg
, 1);
5386 fprintf(stderr
, "parse error: %s\n", optarg
);
5390 case QEMU_OPTION_serial
:
5391 add_device_config(DEV_SERIAL
, optarg
);
5393 if (strncmp(optarg
, "mon:", 4) == 0) {
5394 default_monitor
= 0;
5397 case QEMU_OPTION_watchdog
:
5400 "qemu: only one watchdog option may be given\n");
5405 case QEMU_OPTION_watchdog_action
:
5406 if (select_watchdog_action(optarg
) == -1) {
5407 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5411 case QEMU_OPTION_virtiocon
:
5412 add_device_config(DEV_VIRTCON
, optarg
);
5413 default_virtcon
= 0;
5414 if (strncmp(optarg
, "mon:", 4) == 0) {
5415 default_monitor
= 0;
5418 case QEMU_OPTION_parallel
:
5419 add_device_config(DEV_PARALLEL
, optarg
);
5420 default_parallel
= 0;
5421 if (strncmp(optarg
, "mon:", 4) == 0) {
5422 default_monitor
= 0;
5425 case QEMU_OPTION_debugcon
:
5426 add_device_config(DEV_DEBUGCON
, optarg
);
5428 case QEMU_OPTION_loadvm
:
5431 case QEMU_OPTION_full_screen
:
5435 case QEMU_OPTION_no_frame
:
5438 case QEMU_OPTION_alt_grab
:
5441 case QEMU_OPTION_ctrl_grab
:
5444 case QEMU_OPTION_no_quit
:
5447 case QEMU_OPTION_sdl
:
5448 display_type
= DT_SDL
;
5451 case QEMU_OPTION_pidfile
:
5455 case QEMU_OPTION_win2k_hack
:
5456 win2k_install_hack
= 1;
5458 case QEMU_OPTION_rtc_td_hack
:
5461 case QEMU_OPTION_acpitable
:
5462 if(acpi_table_add(optarg
) < 0) {
5463 fprintf(stderr
, "Wrong acpi table provided\n");
5467 case QEMU_OPTION_smbios
:
5468 if(smbios_entry_add(optarg
) < 0) {
5469 fprintf(stderr
, "Wrong smbios provided\n");
5475 case QEMU_OPTION_enable_kvm
:
5479 case QEMU_OPTION_usb
:
5482 case QEMU_OPTION_usbdevice
:
5484 add_device_config(DEV_USB
, optarg
);
5486 case QEMU_OPTION_device
:
5487 if (!qemu_opts_parse(&qemu_device_opts
, optarg
, 1)) {
5491 case QEMU_OPTION_smp
:
5494 fprintf(stderr
, "Invalid number of CPUs\n");
5497 if (max_cpus
< smp_cpus
) {
5498 fprintf(stderr
, "maxcpus must be equal to or greater than "
5502 if (max_cpus
> 255) {
5503 fprintf(stderr
, "Unsupported number of maxcpus\n");
5507 case QEMU_OPTION_vnc
:
5508 display_type
= DT_VNC
;
5509 vnc_display
= optarg
;
5512 case QEMU_OPTION_no_acpi
:
5515 case QEMU_OPTION_no_hpet
:
5518 case QEMU_OPTION_balloon
:
5519 if (balloon_parse(optarg
) < 0) {
5520 fprintf(stderr
, "Unknown -balloon argument %s\n", optarg
);
5525 case QEMU_OPTION_no_reboot
:
5528 case QEMU_OPTION_no_shutdown
:
5531 case QEMU_OPTION_show_cursor
:
5534 case QEMU_OPTION_uuid
:
5535 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5536 fprintf(stderr
, "Fail to parse UUID string."
5537 " Wrong format.\n");
5542 case QEMU_OPTION_daemonize
:
5546 case QEMU_OPTION_option_rom
:
5547 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5548 fprintf(stderr
, "Too many option ROMs\n");
5551 option_rom
[nb_option_roms
] = optarg
;
5554 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5555 case QEMU_OPTION_semihosting
:
5556 semihosting_enabled
= 1;
5559 case QEMU_OPTION_name
:
5560 qemu_name
= qemu_strdup(optarg
);
5562 char *p
= strchr(qemu_name
, ',');
5565 if (strncmp(p
, "process=", 8)) {
5566 fprintf(stderr
, "Unknown subargument %s to -name", p
);
5574 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5575 case QEMU_OPTION_prom_env
:
5576 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5577 fprintf(stderr
, "Too many prom variables\n");
5580 prom_envs
[nb_prom_envs
] = optarg
;
5585 case QEMU_OPTION_old_param
:
5589 case QEMU_OPTION_clock
:
5590 configure_alarms(optarg
);
5592 case QEMU_OPTION_startdate
:
5593 configure_rtc_date_offset(optarg
, 1);
5595 case QEMU_OPTION_rtc
:
5596 opts
= qemu_opts_parse(&qemu_rtc_opts
, optarg
, 0);
5598 fprintf(stderr
, "parse error: %s\n", optarg
);
5601 configure_rtc(opts
);
5603 case QEMU_OPTION_tb_size
:
5604 tb_size
= strtol(optarg
, NULL
, 0);
5608 case QEMU_OPTION_icount
:
5610 if (strcmp(optarg
, "auto") == 0) {
5611 icount_time_shift
= -1;
5613 icount_time_shift
= strtol(optarg
, NULL
, 0);
5616 case QEMU_OPTION_incoming
:
5619 case QEMU_OPTION_nodefaults
:
5621 default_parallel
= 0;
5622 default_virtcon
= 0;
5623 default_monitor
= 0;
5631 case QEMU_OPTION_chroot
:
5632 chroot_dir
= optarg
;
5634 case QEMU_OPTION_runas
:
5639 case QEMU_OPTION_xen_domid
:
5640 xen_domid
= atoi(optarg
);
5642 case QEMU_OPTION_xen_create
:
5643 xen_mode
= XEN_CREATE
;
5645 case QEMU_OPTION_xen_attach
:
5646 xen_mode
= XEN_ATTACH
;
5649 case QEMU_OPTION_readconfig
:
5652 fp
= fopen(optarg
, "r");
5654 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5657 if (qemu_config_parse(fp
, optarg
) != 0) {
5663 case QEMU_OPTION_writeconfig
:
5666 if (strcmp(optarg
, "-") == 0) {
5669 fp
= fopen(optarg
, "w");
5671 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5675 qemu_config_write(fp
);
5684 /* If no data_dir is specified then try to find it relative to the
5687 data_dir
= find_datadir(argv
[0]);
5689 /* If all else fails use the install patch specified when building. */
5691 data_dir
= CONFIG_QEMU_SHAREDIR
;
5695 * Default to max_cpus = smp_cpus, in case the user doesn't
5696 * specify a max_cpus value.
5699 max_cpus
= smp_cpus
;
5701 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5702 if (smp_cpus
> machine
->max_cpus
) {
5703 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5704 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5709 qemu_opts_foreach(&qemu_device_opts
, default_driver_check
, NULL
, 0);
5710 qemu_opts_foreach(&qemu_global_opts
, default_driver_check
, NULL
, 0);
5712 if (machine
->no_serial
) {
5715 if (machine
->no_parallel
) {
5716 default_parallel
= 0;
5718 if (!machine
->use_virtcon
) {
5719 default_virtcon
= 0;
5721 if (machine
->no_vga
) {
5724 if (machine
->no_floppy
) {
5727 if (machine
->no_cdrom
) {
5730 if (machine
->no_sdcard
) {
5734 if (display_type
== DT_NOGRAPHIC
) {
5735 if (default_parallel
)
5736 add_device_config(DEV_PARALLEL
, "null");
5737 if (default_serial
&& default_monitor
) {
5738 add_device_config(DEV_SERIAL
, "mon:stdio");
5739 } else if (default_virtcon
&& default_monitor
) {
5740 add_device_config(DEV_VIRTCON
, "mon:stdio");
5743 add_device_config(DEV_SERIAL
, "stdio");
5744 if (default_virtcon
)
5745 add_device_config(DEV_VIRTCON
, "stdio");
5746 if (default_monitor
)
5747 monitor_parse("stdio", "readline");
5751 add_device_config(DEV_SERIAL
, "vc:80Cx24C");
5752 if (default_parallel
)
5753 add_device_config(DEV_PARALLEL
, "vc:80Cx24C");
5754 if (default_monitor
)
5755 monitor_parse("vc:80Cx24C", "readline");
5756 if (default_virtcon
)
5757 add_device_config(DEV_VIRTCON
, "vc:80Cx24C");
5760 vga_interface_type
= VGA_CIRRUS
;
5762 if (qemu_opts_foreach(&qemu_chardev_opts
, chardev_init_func
, NULL
, 1) != 0)
5769 if (pipe(fds
) == -1)
5780 len
= read(fds
[0], &status
, 1);
5781 if (len
== -1 && (errno
== EINTR
))
5786 else if (status
== 1) {
5787 fprintf(stderr
, "Could not acquire pidfile: %s\n", strerror(errno
));
5795 qemu_set_cloexec(fds
[1]);
5807 signal(SIGTSTP
, SIG_IGN
);
5808 signal(SIGTTOU
, SIG_IGN
);
5809 signal(SIGTTIN
, SIG_IGN
);
5813 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5817 if (write(fds
[1], &status
, 1) != 1) {
5818 perror("daemonize. Writing to pipe\n");
5822 fprintf(stderr
, "Could not acquire pid file: %s\n", strerror(errno
));
5826 if (kvm_enabled()) {
5829 ret
= kvm_init(smp_cpus
);
5831 fprintf(stderr
, "failed to initialize KVM\n");
5836 if (qemu_init_main_loop()) {
5837 fprintf(stderr
, "qemu_init_main_loop failed\n");
5840 linux_boot
= (kernel_filename
!= NULL
);
5842 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5843 fprintf(stderr
, "-append only allowed with -kernel option\n");
5847 if (!linux_boot
&& initrd_filename
!= NULL
) {
5848 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5853 /* Win32 doesn't support line-buffering and requires size >= 2 */
5854 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5857 if (init_timer_alarm() < 0) {
5858 fprintf(stderr
, "could not initialize alarm timer\n");
5861 if (use_icount
&& icount_time_shift
< 0) {
5863 /* 125MIPS seems a reasonable initial guess at the guest speed.
5864 It will be corrected fairly quickly anyway. */
5865 icount_time_shift
= 3;
5866 init_icount_adjust();
5873 if (net_init_clients() < 0) {
5877 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5878 net_set_boot_mask(net_boot
);
5880 /* init the bluetooth world */
5881 if (foreach_device_config(DEV_BT
, bt_parse
))
5884 /* init the memory */
5886 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5888 /* init the dynamic translator */
5889 cpu_exec_init_all(tb_size
* 1024 * 1024);
5891 bdrv_init_with_whitelist();
5895 if (default_cdrom
) {
5896 /* we always create the cdrom drive, even if no disk is there */
5897 drive_add(NULL
, CDROM_ALIAS
);
5900 if (default_floppy
) {
5901 /* we always create at least one floppy */
5902 drive_add(NULL
, FD_ALIAS
, 0);
5905 if (default_sdcard
) {
5906 /* we always create one sd slot, even if no card is in it */
5907 drive_add(NULL
, SD_ALIAS
);
5910 /* open the virtual block devices */
5912 qemu_opts_foreach(&qemu_drive_opts
, drive_enable_snapshot
, NULL
, 0);
5913 if (qemu_opts_foreach(&qemu_drive_opts
, drive_init_func
, machine
, 1) != 0)
5916 vmstate_register(0, &vmstate_timers
,&timers_state
);
5917 register_savevm_live("ram", 0, 3, NULL
, ram_save_live
, NULL
,
5920 if (nb_numa_nodes
> 0) {
5923 if (nb_numa_nodes
> smp_cpus
) {
5924 nb_numa_nodes
= smp_cpus
;
5927 /* If no memory size if given for any node, assume the default case
5928 * and distribute the available memory equally across all nodes
5930 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5931 if (node_mem
[i
] != 0)
5934 if (i
== nb_numa_nodes
) {
5935 uint64_t usedmem
= 0;
5937 /* On Linux, the each node's border has to be 8MB aligned,
5938 * the final node gets the rest.
5940 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
5941 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
5942 usedmem
+= node_mem
[i
];
5944 node_mem
[i
] = ram_size
- usedmem
;
5947 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5948 if (node_cpumask
[i
] != 0)
5951 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5952 * must cope with this anyway, because there are BIOSes out there in
5953 * real machines which also use this scheme.
5955 if (i
== nb_numa_nodes
) {
5956 for (i
= 0; i
< smp_cpus
; i
++) {
5957 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
5962 if (foreach_device_config(DEV_SERIAL
, serial_parse
) < 0)
5964 if (foreach_device_config(DEV_PARALLEL
, parallel_parse
) < 0)
5966 if (foreach_device_config(DEV_VIRTCON
, virtcon_parse
) < 0)
5968 if (foreach_device_config(DEV_DEBUGCON
, debugcon_parse
) < 0)
5971 module_call_init(MODULE_INIT_DEVICE
);
5973 if (qemu_opts_foreach(&qemu_device_opts
, device_help_func
, NULL
, 0) != 0)
5977 i
= select_watchdog(watchdog
);
5979 exit (i
== 1 ? 1 : 0);
5982 if (machine
->compat_props
) {
5983 qdev_prop_register_global_list(machine
->compat_props
);
5987 machine
->init(ram_size
, boot_devices
,
5988 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
5990 cpu_synchronize_all_post_init();
5993 /* must be after terminal init, SDL library changes signal handlers */
5997 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
5998 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5999 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
6005 current_machine
= machine
;
6007 /* init USB devices */
6009 if (foreach_device_config(DEV_USB
, usb_parse
) < 0)
6013 /* init generic devices */
6014 if (qemu_opts_foreach(&qemu_device_opts
, device_init_func
, NULL
, 1) != 0)
6017 net_check_clients();
6019 /* just use the first displaystate for the moment */
6020 ds
= get_displaystate();
6022 if (display_type
== DT_DEFAULT
) {
6023 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6024 display_type
= DT_SDL
;
6026 display_type
= DT_VNC
;
6027 vnc_display
= "localhost:0,to=99";
6033 switch (display_type
) {
6036 #if defined(CONFIG_CURSES)
6038 curses_display_init(ds
, full_screen
);
6041 #if defined(CONFIG_SDL)
6043 sdl_display_init(ds
, full_screen
, no_frame
);
6045 #elif defined(CONFIG_COCOA)
6047 cocoa_display_init(ds
, full_screen
);
6051 vnc_display_init(ds
);
6052 if (vnc_display_open(ds
, vnc_display
) < 0)
6055 if (show_vnc_port
) {
6056 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
6064 dcl
= ds
->listeners
;
6065 while (dcl
!= NULL
) {
6066 if (dcl
->dpy_refresh
!= NULL
) {
6067 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
6068 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
6073 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
6074 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
6075 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
6078 text_consoles_set_display(ds
);
6080 if (qemu_opts_foreach(&qemu_mon_opts
, mon_init_func
, NULL
, 1) != 0)
6083 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
6084 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
6089 qdev_machine_creation_done();
6091 if (rom_load_all() != 0) {
6092 fprintf(stderr
, "rom loading failed\n");
6096 qemu_system_reset();
6098 if (load_vmstate(loadvm
) < 0) {
6104 qemu_start_incoming_migration(incoming
);
6105 } else if (autostart
) {
6115 len
= write(fds
[1], &status
, 1);
6116 if (len
== -1 && (errno
== EINTR
))
6123 perror("not able to chdir to /");
6126 TFR(fd
= qemu_open("/dev/null", O_RDWR
));
6132 pwd
= getpwnam(run_as
);
6134 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
6140 if (chroot(chroot_dir
) < 0) {
6141 fprintf(stderr
, "chroot failed\n");
6145 perror("not able to chdir to /");
6151 if (setgid(pwd
->pw_gid
) < 0) {
6152 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
6155 if (setuid(pwd
->pw_uid
) < 0) {
6156 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
6159 if (setuid(0) != -1) {
6160 fprintf(stderr
, "Dropping privileges failed\n");