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 HOST_BSD etc. */
33 #include "config-host.h"
37 #include <sys/times.h>
41 #include <sys/ioctl.h>
42 #include <sys/resource.h>
43 #include <sys/socket.h>
45 #include <netinet/in.h>
47 #if defined(__NetBSD__)
48 #include <net/if_tap.h>
51 #include <linux/if_tun.h>
53 #include <arpa/inet.h>
56 #include <sys/select.h>
59 #if defined(__FreeBSD__) || defined(__DragonFly__)
64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65 #include <freebsd/stdlib.h>
70 #include <linux/rtc.h>
72 /* For the benefit of older linux systems which don't supply it,
73 we use a local copy of hpet.h. */
74 /* #include <linux/hpet.h> */
77 #include <linux/ppdev.h>
78 #include <linux/parport.h>
82 #include <sys/ethernet.h>
83 #include <sys/sockio.h>
84 #include <netinet/arp.h>
85 #include <netinet/in.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip_icmp.h> // must come after ip.h
89 #include <netinet/udp.h>
90 #include <netinet/tcp.h>
98 #if defined(__OpenBSD__)
102 #if defined(CONFIG_VDE)
103 #include <libvdeplug.h>
109 #include <sys/timeb.h>
110 #include <mmsystem.h>
111 #define getopt_long_only getopt_long
112 #define memalign(align, size) malloc(size)
118 int qemu_main(int argc
, char **argv
, char **envp
);
119 int main(int argc
, char **argv
)
121 qemu_main(argc
, argv
, NULL
);
124 #define main qemu_main
126 #endif /* CONFIG_SDL */
130 #define main qemu_main
131 #endif /* CONFIG_COCOA */
134 #include "hw/boards.h"
136 #include "hw/pcmcia.h"
138 #include "hw/audiodev.h"
142 #include "hw/watchdog.h"
143 #include "hw/smbios.h"
151 #include "qemu-timer.h"
152 #include "qemu-char.h"
153 #include "cache-utils.h"
156 #include "audio/audio.h"
157 #include "migration.h"
160 #include "qemu-kvm.h"
161 #include "hw/device-assignment.h"
165 #include "exec-all.h"
167 #include "qemu_socket.h"
169 #if defined(CONFIG_SLIRP)
170 #include "libslirp.h"
173 //#define DEBUG_UNUSED_IOPORT
174 //#define DEBUG_IOPORT
176 //#define DEBUG_SLIRP
180 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
182 # define LOG_IOPORT(...) do { } while (0)
185 #define DEFAULT_RAM_SIZE 128
187 /* Max number of USB devices that can be specified on the commandline. */
188 #define MAX_USB_CMDLINE 8
190 /* Max number of bluetooth switches on the commandline. */
191 #define MAX_BT_CMDLINE 10
193 /* XXX: use a two level table to limit memory usage */
194 #define MAX_IOPORTS 65536
196 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
197 const char *bios_name
= NULL
;
198 static void *ioport_opaque
[MAX_IOPORTS
];
199 static IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
200 static IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
201 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
202 to store the VM snapshots */
203 DriveInfo drives_table
[MAX_DRIVES
+1];
205 int extboot_drive
= -1;
206 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
207 static DisplayState
*display_state
;
211 const char* keyboard_layout
= NULL
;
212 int64_t ticks_per_sec
;
215 NICInfo nd_table
[MAX_NICS
];
217 static int autostart
;
218 static int rtc_utc
= 1;
219 static int rtc_date_offset
= -1; /* -1 means no change */
220 int cirrus_vga_enabled
= 1;
221 int std_vga_enabled
= 0;
222 int vmsvga_enabled
= 0;
223 int xenfb_enabled
= 0;
225 int graphic_width
= 1024;
226 int graphic_height
= 768;
227 int graphic_depth
= 8;
229 int graphic_width
= 800;
230 int graphic_height
= 600;
231 int graphic_depth
= 15;
233 static int full_screen
= 0;
235 static int no_frame
= 0;
238 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
239 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
240 CharDriverState
*virtcon_hds
[MAX_VIRTIO_CONSOLES
];
242 int win2k_install_hack
= 0;
247 const char *assigned_devices
[MAX_DEV_ASSIGN_CMDLINE
];
248 int assigned_devices_index
;
250 const char *vnc_display
;
251 int acpi_enabled
= 1;
257 int graphic_rotate
= 0;
261 WatchdogTimerModel
*watchdog
= NULL
;
262 int watchdog_action
= WDT_RESET
;
263 const char *option_rom
[MAX_OPTION_ROMS
];
265 int semihosting_enabled
= 0;
266 int time_drift_fix
= 0;
267 unsigned int kvm_shadow_memory
= 0;
268 const char *mem_path
= NULL
;
270 int mem_prealloc
= 1; /* force preallocation of physical target memory */
276 const char *qemu_name
;
278 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
279 unsigned int nb_prom_envs
= 0;
280 const char *prom_envs
[MAX_PROM_ENVS
];
283 const char *nvram
= NULL
;
284 struct drive_opt drives_opt
[MAX_DRIVES
];
287 uint64_t node_mem
[MAX_NODES
];
288 uint64_t node_cpumask
[MAX_NODES
];
290 static CPUState
*cur_cpu
;
291 static CPUState
*next_cpu
;
292 static int timer_alarm_pending
= 1;
293 /* Conversion factor from emulated instructions to virtual clock ticks. */
294 static int icount_time_shift
;
295 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
296 #define MAX_ICOUNT_SHIFT 10
297 /* Compensate for varying guest execution speed. */
298 static int64_t qemu_icount_bias
;
299 static QEMUTimer
*icount_rt_timer
;
300 static QEMUTimer
*icount_vm_timer
;
301 static QEMUTimer
*nographic_timer
;
303 uint8_t qemu_uuid
[16];
305 static int qemu_select(int max_fd
, fd_set
*rfds
, fd_set
*wfds
, fd_set
*xfds
,
310 /* KVM holds a mutex while QEMU code is running, we need hooks to
311 release the mutex whenever QEMU code sleeps. */
315 ret
= select(max_fd
, rfds
, wfds
, xfds
, tv
);
323 /***********************************************************/
324 /* x86 ISA bus support */
326 target_phys_addr_t isa_mem_base
= 0;
329 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
330 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
332 static uint32_t ioport_read(int index
, uint32_t address
)
334 static IOPortReadFunc
*default_func
[3] = {
335 default_ioport_readb
,
336 default_ioport_readw
,
339 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
341 func
= default_func
[index
];
342 return func(ioport_opaque
[address
], address
);
345 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
347 static IOPortWriteFunc
*default_func
[3] = {
348 default_ioport_writeb
,
349 default_ioport_writew
,
350 default_ioport_writel
352 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
354 func
= default_func
[index
];
355 func(ioport_opaque
[address
], address
, data
);
358 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
360 #ifdef DEBUG_UNUSED_IOPORT
361 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
366 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
368 #ifdef DEBUG_UNUSED_IOPORT
369 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
373 /* default is to make two byte accesses */
374 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
377 data
= ioport_read(0, address
);
378 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
379 data
|= ioport_read(0, address
) << 8;
383 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
385 ioport_write(0, address
, data
& 0xff);
386 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
387 ioport_write(0, address
, (data
>> 8) & 0xff);
390 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
392 #ifdef DEBUG_UNUSED_IOPORT
393 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
398 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
400 #ifdef DEBUG_UNUSED_IOPORT
401 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
405 /* size is the word size in byte */
406 int register_ioport_read(int start
, int length
, int size
,
407 IOPortReadFunc
*func
, void *opaque
)
413 } else if (size
== 2) {
415 } else if (size
== 4) {
418 hw_error("register_ioport_read: invalid size");
421 for(i
= start
; i
< start
+ length
; i
+= size
) {
422 ioport_read_table
[bsize
][i
] = func
;
423 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
424 hw_error("register_ioport_read: invalid opaque");
425 ioport_opaque
[i
] = opaque
;
430 /* size is the word size in byte */
431 int register_ioport_write(int start
, int length
, int size
,
432 IOPortWriteFunc
*func
, void *opaque
)
438 } else if (size
== 2) {
440 } else if (size
== 4) {
443 hw_error("register_ioport_write: invalid size");
446 for(i
= start
; i
< start
+ length
; i
+= size
) {
447 ioport_write_table
[bsize
][i
] = func
;
448 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
449 hw_error("register_ioport_write: invalid opaque");
450 ioport_opaque
[i
] = opaque
;
455 void isa_unassign_ioport(int start
, int length
)
459 for(i
= start
; i
< start
+ length
; i
++) {
460 ioport_read_table
[0][i
] = default_ioport_readb
;
461 ioport_read_table
[1][i
] = default_ioport_readw
;
462 ioport_read_table
[2][i
] = default_ioport_readl
;
464 ioport_write_table
[0][i
] = default_ioport_writeb
;
465 ioport_write_table
[1][i
] = default_ioport_writew
;
466 ioport_write_table
[2][i
] = default_ioport_writel
;
468 ioport_opaque
[i
] = NULL
;
472 /***********************************************************/
474 void cpu_outb(CPUState
*env
, int addr
, int val
)
476 LOG_IOPORT("outb: %04x %02x\n", addr
, val
);
477 ioport_write(0, addr
, val
);
480 env
->last_io_time
= cpu_get_time_fast();
484 void cpu_outw(CPUState
*env
, int addr
, int val
)
486 LOG_IOPORT("outw: %04x %04x\n", addr
, val
);
487 ioport_write(1, addr
, val
);
490 env
->last_io_time
= cpu_get_time_fast();
494 void cpu_outl(CPUState
*env
, int addr
, int val
)
496 LOG_IOPORT("outl: %04x %08x\n", addr
, val
);
497 ioport_write(2, addr
, val
);
500 env
->last_io_time
= cpu_get_time_fast();
504 int cpu_inb(CPUState
*env
, int addr
)
507 val
= ioport_read(0, addr
);
508 LOG_IOPORT("inb : %04x %02x\n", addr
, val
);
511 env
->last_io_time
= cpu_get_time_fast();
516 int cpu_inw(CPUState
*env
, int addr
)
519 val
= ioport_read(1, addr
);
520 LOG_IOPORT("inw : %04x %04x\n", addr
, val
);
523 env
->last_io_time
= cpu_get_time_fast();
528 int cpu_inl(CPUState
*env
, int addr
)
531 val
= ioport_read(2, addr
);
532 LOG_IOPORT("inl : %04x %08x\n", addr
, val
);
535 env
->last_io_time
= cpu_get_time_fast();
540 /***********************************************************/
541 void hw_error(const char *fmt
, ...)
547 fprintf(stderr
, "qemu: hardware error: ");
548 vfprintf(stderr
, fmt
, ap
);
549 fprintf(stderr
, "\n");
550 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
551 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
553 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
555 cpu_dump_state(env
, stderr
, fprintf
, 0);
565 static QEMUBalloonEvent
*qemu_balloon_event
;
566 void *qemu_balloon_event_opaque
;
568 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
570 qemu_balloon_event
= func
;
571 qemu_balloon_event_opaque
= opaque
;
574 void qemu_balloon(ram_addr_t target
)
576 if (qemu_balloon_event
)
577 qemu_balloon_event(qemu_balloon_event_opaque
, target
);
580 ram_addr_t
qemu_balloon_status(void)
582 if (qemu_balloon_event
)
583 return qemu_balloon_event(qemu_balloon_event_opaque
, 0);
587 /***********************************************************/
590 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
591 static void *qemu_put_kbd_event_opaque
;
592 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
593 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
595 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
597 qemu_put_kbd_event_opaque
= opaque
;
598 qemu_put_kbd_event
= func
;
601 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
602 void *opaque
, int absolute
,
605 QEMUPutMouseEntry
*s
, *cursor
;
607 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
609 s
->qemu_put_mouse_event
= func
;
610 s
->qemu_put_mouse_event_opaque
= opaque
;
611 s
->qemu_put_mouse_event_absolute
= absolute
;
612 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
615 if (!qemu_put_mouse_event_head
) {
616 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
620 cursor
= qemu_put_mouse_event_head
;
621 while (cursor
->next
!= NULL
)
622 cursor
= cursor
->next
;
625 qemu_put_mouse_event_current
= s
;
630 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
632 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
634 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
637 cursor
= qemu_put_mouse_event_head
;
638 while (cursor
!= NULL
&& cursor
!= entry
) {
640 cursor
= cursor
->next
;
643 if (cursor
== NULL
) // does not exist or list empty
645 else if (prev
== NULL
) { // entry is head
646 qemu_put_mouse_event_head
= cursor
->next
;
647 if (qemu_put_mouse_event_current
== entry
)
648 qemu_put_mouse_event_current
= cursor
->next
;
649 qemu_free(entry
->qemu_put_mouse_event_name
);
654 prev
->next
= entry
->next
;
656 if (qemu_put_mouse_event_current
== entry
)
657 qemu_put_mouse_event_current
= prev
;
659 qemu_free(entry
->qemu_put_mouse_event_name
);
663 void kbd_put_keycode(int keycode
)
665 if (qemu_put_kbd_event
) {
666 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
670 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
672 QEMUPutMouseEvent
*mouse_event
;
673 void *mouse_event_opaque
;
676 if (!qemu_put_mouse_event_current
) {
681 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
683 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
686 if (graphic_rotate
) {
687 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
690 width
= graphic_width
- 1;
691 mouse_event(mouse_event_opaque
,
692 width
- dy
, dx
, dz
, buttons_state
);
694 mouse_event(mouse_event_opaque
,
695 dx
, dy
, dz
, buttons_state
);
699 int kbd_mouse_is_absolute(void)
701 if (!qemu_put_mouse_event_current
)
704 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
707 void do_info_mice(Monitor
*mon
)
709 QEMUPutMouseEntry
*cursor
;
712 if (!qemu_put_mouse_event_head
) {
713 monitor_printf(mon
, "No mouse devices connected\n");
717 monitor_printf(mon
, "Mouse devices available:\n");
718 cursor
= qemu_put_mouse_event_head
;
719 while (cursor
!= NULL
) {
720 monitor_printf(mon
, "%c Mouse #%d: %s\n",
721 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
722 index
, cursor
->qemu_put_mouse_event_name
);
724 cursor
= cursor
->next
;
728 void do_mouse_set(Monitor
*mon
, int index
)
730 QEMUPutMouseEntry
*cursor
;
733 if (!qemu_put_mouse_event_head
) {
734 monitor_printf(mon
, "No mouse devices connected\n");
738 cursor
= qemu_put_mouse_event_head
;
739 while (cursor
!= NULL
&& index
!= i
) {
741 cursor
= cursor
->next
;
745 qemu_put_mouse_event_current
= cursor
;
747 monitor_printf(mon
, "Mouse at given index not found\n");
750 /* compute with 96 bit intermediate result: (a*b)/c */
751 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
756 #ifdef WORDS_BIGENDIAN
766 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
767 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
770 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
774 /***********************************************************/
775 /* real time host monotonic timer */
777 #define QEMU_TIMER_BASE 1000000000LL
781 static int64_t clock_freq
;
783 static void init_get_clock(void)
787 ret
= QueryPerformanceFrequency(&freq
);
789 fprintf(stderr
, "Could not calibrate ticks\n");
792 clock_freq
= freq
.QuadPart
;
795 static int64_t get_clock(void)
798 QueryPerformanceCounter(&ti
);
799 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
804 static int use_rt_clock
;
806 static void init_get_clock(void)
809 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
810 || defined(__DragonFly__)
813 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
820 static int64_t get_clock(void)
822 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
823 || defined(__DragonFly__)
826 clock_gettime(CLOCK_MONOTONIC
, &ts
);
827 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
831 /* XXX: using gettimeofday leads to problems if the date
832 changes, so it should be avoided. */
834 gettimeofday(&tv
, NULL
);
835 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
840 /* Return the virtual CPU time, based on the instruction counter. */
841 static int64_t cpu_get_icount(void)
844 CPUState
*env
= cpu_single_env
;;
845 icount
= qemu_icount
;
848 fprintf(stderr
, "Bad clock read\n");
849 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
851 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
854 /***********************************************************/
855 /* guest cycle counter */
857 static int64_t cpu_ticks_prev
;
858 static int64_t cpu_ticks_offset
;
859 static int64_t cpu_clock_offset
;
860 static int cpu_ticks_enabled
;
862 /* return the host CPU cycle counter and handle stop/restart */
863 int64_t cpu_get_ticks(void)
866 return cpu_get_icount();
868 if (!cpu_ticks_enabled
) {
869 return cpu_ticks_offset
;
872 ticks
= cpu_get_real_ticks();
873 if (cpu_ticks_prev
> ticks
) {
874 /* Note: non increasing ticks may happen if the host uses
876 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
878 cpu_ticks_prev
= ticks
;
879 return ticks
+ cpu_ticks_offset
;
883 /* return the host CPU monotonic timer and handle stop/restart */
884 static int64_t cpu_get_clock(void)
887 if (!cpu_ticks_enabled
) {
888 return cpu_clock_offset
;
891 return ti
+ cpu_clock_offset
;
895 /* enable cpu_get_ticks() */
896 void cpu_enable_ticks(void)
898 if (!cpu_ticks_enabled
) {
899 cpu_ticks_offset
-= cpu_get_real_ticks();
900 cpu_clock_offset
-= get_clock();
901 cpu_ticks_enabled
= 1;
905 /* disable cpu_get_ticks() : the clock is stopped. You must not call
906 cpu_get_ticks() after that. */
907 void cpu_disable_ticks(void)
909 if (cpu_ticks_enabled
) {
910 cpu_ticks_offset
= cpu_get_ticks();
911 cpu_clock_offset
= cpu_get_clock();
912 cpu_ticks_enabled
= 0;
916 /***********************************************************/
919 #define QEMU_TIMER_REALTIME 0
920 #define QEMU_TIMER_VIRTUAL 1
924 /* XXX: add frequency */
932 struct QEMUTimer
*next
;
935 struct qemu_alarm_timer
{
939 int (*start
)(struct qemu_alarm_timer
*t
);
940 void (*stop
)(struct qemu_alarm_timer
*t
);
941 void (*rearm
)(struct qemu_alarm_timer
*t
);
945 #define ALARM_FLAG_DYNTICKS 0x1
946 #define ALARM_FLAG_EXPIRED 0x2
948 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
950 return t
&& (t
->flags
& ALARM_FLAG_DYNTICKS
);
953 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
955 if (!alarm_has_dynticks(t
))
961 /* TODO: MIN_TIMER_REARM_US should be optimized */
962 #define MIN_TIMER_REARM_US 250
964 static struct qemu_alarm_timer
*alarm_timer
;
968 struct qemu_alarm_win32
{
971 } alarm_win32_data
= {0, -1};
973 static int win32_start_timer(struct qemu_alarm_timer
*t
);
974 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
975 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
979 static int unix_start_timer(struct qemu_alarm_timer
*t
);
980 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
984 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
985 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
986 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
988 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
989 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
991 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
992 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
994 #endif /* __linux__ */
998 /* Correlation between real and virtual time is always going to be
999 fairly approximate, so ignore small variation.
1000 When the guest is idle real and virtual time will be aligned in
1001 the IO wait loop. */
1002 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
1004 static void icount_adjust(void)
1009 static int64_t last_delta
;
1010 /* If the VM is not running, then do nothing. */
1014 cur_time
= cpu_get_clock();
1015 cur_icount
= qemu_get_clock(vm_clock
);
1016 delta
= cur_icount
- cur_time
;
1017 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1019 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
1020 && icount_time_shift
> 0) {
1021 /* The guest is getting too far ahead. Slow time down. */
1022 icount_time_shift
--;
1025 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
1026 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
1027 /* The guest is getting too far behind. Speed time up. */
1028 icount_time_shift
++;
1031 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
1034 static void icount_adjust_rt(void * opaque
)
1036 qemu_mod_timer(icount_rt_timer
,
1037 qemu_get_clock(rt_clock
) + 1000);
1041 static void icount_adjust_vm(void * opaque
)
1043 qemu_mod_timer(icount_vm_timer
,
1044 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1048 static void init_icount_adjust(void)
1050 /* Have both realtime and virtual time triggers for speed adjustment.
1051 The realtime trigger catches emulated time passing too slowly,
1052 the virtual time trigger catches emulated time passing too fast.
1053 Realtime triggers occur even when idle, so use them less frequently
1054 than VM triggers. */
1055 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
1056 qemu_mod_timer(icount_rt_timer
,
1057 qemu_get_clock(rt_clock
) + 1000);
1058 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
1059 qemu_mod_timer(icount_vm_timer
,
1060 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1063 static struct qemu_alarm_timer alarm_timers
[] = {
1066 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
1067 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
1068 /* HPET - if available - is preferred */
1069 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
1070 /* ...otherwise try RTC */
1071 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1073 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1075 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1076 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1077 {"win32", 0, win32_start_timer
,
1078 win32_stop_timer
, NULL
, &alarm_win32_data
},
1083 static void show_available_alarms(void)
1087 printf("Available alarm timers, in order of precedence:\n");
1088 for (i
= 0; alarm_timers
[i
].name
; i
++)
1089 printf("%s\n", alarm_timers
[i
].name
);
1092 static void configure_alarms(char const *opt
)
1096 int count
= ARRAY_SIZE(alarm_timers
) - 1;
1099 struct qemu_alarm_timer tmp
;
1101 if (!strcmp(opt
, "?")) {
1102 show_available_alarms();
1108 /* Reorder the array */
1109 name
= strtok(arg
, ",");
1111 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1112 if (!strcmp(alarm_timers
[i
].name
, name
))
1117 fprintf(stderr
, "Unknown clock %s\n", name
);
1126 tmp
= alarm_timers
[i
];
1127 alarm_timers
[i
] = alarm_timers
[cur
];
1128 alarm_timers
[cur
] = tmp
;
1132 name
= strtok(NULL
, ",");
1138 /* Disable remaining timers */
1139 for (i
= cur
; i
< count
; i
++)
1140 alarm_timers
[i
].name
= NULL
;
1142 show_available_alarms();
1147 QEMUClock
*rt_clock
;
1148 QEMUClock
*vm_clock
;
1150 static QEMUTimer
*active_timers
[2];
1152 static QEMUClock
*qemu_new_clock(int type
)
1155 clock
= qemu_mallocz(sizeof(QEMUClock
));
1160 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1164 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1167 ts
->opaque
= opaque
;
1171 void qemu_free_timer(QEMUTimer
*ts
)
1176 /* stop a timer, but do not dealloc it */
1177 void qemu_del_timer(QEMUTimer
*ts
)
1181 /* NOTE: this code must be signal safe because
1182 qemu_timer_expired() can be called from a signal. */
1183 pt
= &active_timers
[ts
->clock
->type
];
1196 /* modify the current timer so that it will be fired when current_time
1197 >= expire_time. The corresponding callback will be called. */
1198 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1204 /* add the timer in the sorted list */
1205 /* NOTE: this code must be signal safe because
1206 qemu_timer_expired() can be called from a signal. */
1207 pt
= &active_timers
[ts
->clock
->type
];
1212 if (t
->expire_time
> expire_time
)
1216 ts
->expire_time
= expire_time
;
1220 /* Rearm if necessary */
1221 if (pt
== &active_timers
[ts
->clock
->type
]) {
1222 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1223 qemu_rearm_alarm_timer(alarm_timer
);
1225 /* Interrupt execution to force deadline recalculation. */
1227 qemu_notify_event();
1231 int qemu_timer_pending(QEMUTimer
*ts
)
1234 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1241 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1245 return (timer_head
->expire_time
<= current_time
);
1248 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1254 if (!ts
|| ts
->expire_time
> current_time
)
1256 /* remove timer from the list before calling the callback */
1257 *ptimer_head
= ts
->next
;
1260 /* run the callback (the timer list can be modified) */
1265 int64_t qemu_get_clock(QEMUClock
*clock
)
1267 switch(clock
->type
) {
1268 case QEMU_TIMER_REALTIME
:
1269 return get_clock() / 1000000;
1271 case QEMU_TIMER_VIRTUAL
:
1273 return cpu_get_icount();
1275 return cpu_get_clock();
1280 static void init_timers(void)
1283 ticks_per_sec
= QEMU_TIMER_BASE
;
1284 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1285 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1289 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1291 uint64_t expire_time
;
1293 if (qemu_timer_pending(ts
)) {
1294 expire_time
= ts
->expire_time
;
1298 qemu_put_be64(f
, expire_time
);
1301 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1303 uint64_t expire_time
;
1305 expire_time
= qemu_get_be64(f
);
1306 if (expire_time
!= -1) {
1307 qemu_mod_timer(ts
, expire_time
);
1313 static void timer_save(QEMUFile
*f
, void *opaque
)
1315 if (cpu_ticks_enabled
) {
1316 hw_error("cannot save state if virtual timers are running");
1318 qemu_put_be64(f
, cpu_ticks_offset
);
1319 qemu_put_be64(f
, ticks_per_sec
);
1320 qemu_put_be64(f
, cpu_clock_offset
);
1323 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1325 if (version_id
!= 1 && version_id
!= 2)
1327 if (cpu_ticks_enabled
) {
1330 cpu_ticks_offset
=qemu_get_be64(f
);
1331 ticks_per_sec
=qemu_get_be64(f
);
1332 if (version_id
== 2) {
1333 cpu_clock_offset
=qemu_get_be64(f
);
1338 static void qemu_event_increment(void);
1341 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1342 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1345 static void host_alarm_handler(int host_signum
)
1349 #define DISP_FREQ 1000
1351 static int64_t delta_min
= INT64_MAX
;
1352 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1354 ti
= qemu_get_clock(vm_clock
);
1355 if (last_clock
!= 0) {
1356 delta
= ti
- last_clock
;
1357 if (delta
< delta_min
)
1359 if (delta
> delta_max
)
1362 if (++count
== DISP_FREQ
) {
1363 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1364 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1365 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1366 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1367 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1369 delta_min
= INT64_MAX
;
1377 if (alarm_has_dynticks(alarm_timer
) ||
1379 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1380 qemu_get_clock(vm_clock
))) ||
1381 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1382 qemu_get_clock(rt_clock
))) {
1383 qemu_event_increment();
1384 if (alarm_timer
) alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1386 #ifndef CONFIG_IOTHREAD
1388 /* stop the currently executing cpu because a timer occured */
1391 if (next_cpu
->kqemu_enabled
) {
1392 kqemu_cpu_interrupt(next_cpu
);
1397 timer_alarm_pending
= 1;
1398 qemu_notify_event();
1402 static int64_t qemu_next_deadline(void)
1406 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1407 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1408 qemu_get_clock(vm_clock
);
1410 /* To avoid problems with overflow limit this to 2^32. */
1420 #if defined(__linux__) || defined(_WIN32)
1421 static uint64_t qemu_next_deadline_dyntick(void)
1429 delta
= (qemu_next_deadline() + 999) / 1000;
1431 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1432 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1433 qemu_get_clock(rt_clock
))*1000;
1434 if (rtdelta
< delta
)
1438 if (delta
< MIN_TIMER_REARM_US
)
1439 delta
= MIN_TIMER_REARM_US
;
1447 /* Sets a specific flag */
1448 static int fcntl_setfl(int fd
, int flag
)
1452 flags
= fcntl(fd
, F_GETFL
);
1456 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1462 #if defined(__linux__)
1464 #define RTC_FREQ 1024
1466 static void enable_sigio_timer(int fd
)
1468 struct sigaction act
;
1471 sigfillset(&act
.sa_mask
);
1473 act
.sa_handler
= host_alarm_handler
;
1475 sigaction(SIGIO
, &act
, NULL
);
1476 fcntl_setfl(fd
, O_ASYNC
);
1477 fcntl(fd
, F_SETOWN
, getpid());
1480 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1482 struct hpet_info info
;
1485 fd
= open("/dev/hpet", O_RDONLY
);
1490 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1492 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1493 "error, but for better emulation accuracy type:\n"
1494 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1498 /* Check capabilities */
1499 r
= ioctl(fd
, HPET_INFO
, &info
);
1503 /* Enable periodic mode */
1504 r
= ioctl(fd
, HPET_EPI
, 0);
1505 if (info
.hi_flags
&& (r
< 0))
1508 /* Enable interrupt */
1509 r
= ioctl(fd
, HPET_IE_ON
, 0);
1513 enable_sigio_timer(fd
);
1514 t
->priv
= (void *)(long)fd
;
1522 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1524 int fd
= (long)t
->priv
;
1529 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1532 unsigned long current_rtc_freq
= 0;
1534 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1537 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1538 if (current_rtc_freq
!= RTC_FREQ
&&
1539 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1540 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1541 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1542 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1545 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1551 enable_sigio_timer(rtc_fd
);
1553 t
->priv
= (void *)(long)rtc_fd
;
1558 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1560 int rtc_fd
= (long)t
->priv
;
1565 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1569 struct sigaction act
;
1571 sigfillset(&act
.sa_mask
);
1573 act
.sa_handler
= host_alarm_handler
;
1575 sigaction(SIGALRM
, &act
, NULL
);
1578 * Initialize ev struct to 0 to avoid valgrind complaining
1579 * about uninitialized data in timer_create call
1581 memset(&ev
, 0, sizeof(ev
));
1582 ev
.sigev_value
.sival_int
= 0;
1583 ev
.sigev_notify
= SIGEV_SIGNAL
;
1584 ev
.sigev_signo
= SIGALRM
;
1586 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1587 perror("timer_create");
1589 /* disable dynticks */
1590 fprintf(stderr
, "Dynamic Ticks disabled\n");
1595 t
->priv
= (void *)(long)host_timer
;
1600 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1602 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1604 timer_delete(host_timer
);
1607 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1609 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1610 struct itimerspec timeout
;
1611 int64_t nearest_delta_us
= INT64_MAX
;
1614 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1615 !active_timers
[QEMU_TIMER_VIRTUAL
])
1618 nearest_delta_us
= qemu_next_deadline_dyntick();
1620 /* check whether a timer is already running */
1621 if (timer_gettime(host_timer
, &timeout
)) {
1623 fprintf(stderr
, "Internal timer error: aborting\n");
1626 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1627 if (current_us
&& current_us
<= nearest_delta_us
)
1630 timeout
.it_interval
.tv_sec
= 0;
1631 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1632 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1633 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1634 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1636 fprintf(stderr
, "Internal timer error: aborting\n");
1641 #endif /* defined(__linux__) */
1643 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1645 struct sigaction act
;
1646 struct itimerval itv
;
1650 sigfillset(&act
.sa_mask
);
1652 act
.sa_handler
= host_alarm_handler
;
1654 sigaction(SIGALRM
, &act
, NULL
);
1656 itv
.it_interval
.tv_sec
= 0;
1657 /* for i386 kernel 2.6 to get 1 ms */
1658 itv
.it_interval
.tv_usec
= 999;
1659 itv
.it_value
.tv_sec
= 0;
1660 itv
.it_value
.tv_usec
= 10 * 1000;
1662 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1669 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1671 struct itimerval itv
;
1673 memset(&itv
, 0, sizeof(itv
));
1674 setitimer(ITIMER_REAL
, &itv
, NULL
);
1677 #endif /* !defined(_WIN32) */
1682 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1685 struct qemu_alarm_win32
*data
= t
->priv
;
1688 memset(&tc
, 0, sizeof(tc
));
1689 timeGetDevCaps(&tc
, sizeof(tc
));
1691 if (data
->period
< tc
.wPeriodMin
)
1692 data
->period
= tc
.wPeriodMin
;
1694 timeBeginPeriod(data
->period
);
1696 flags
= TIME_CALLBACK_FUNCTION
;
1697 if (alarm_has_dynticks(t
))
1698 flags
|= TIME_ONESHOT
;
1700 flags
|= TIME_PERIODIC
;
1702 data
->timerId
= timeSetEvent(1, // interval (ms)
1703 data
->period
, // resolution
1704 host_alarm_handler
, // function
1705 (DWORD
)t
, // parameter
1708 if (!data
->timerId
) {
1709 perror("Failed to initialize win32 alarm timer");
1710 timeEndPeriod(data
->period
);
1717 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1719 struct qemu_alarm_win32
*data
= t
->priv
;
1721 timeKillEvent(data
->timerId
);
1722 timeEndPeriod(data
->period
);
1725 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1727 struct qemu_alarm_win32
*data
= t
->priv
;
1728 uint64_t nearest_delta_us
;
1730 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1731 !active_timers
[QEMU_TIMER_VIRTUAL
])
1734 nearest_delta_us
= qemu_next_deadline_dyntick();
1735 nearest_delta_us
/= 1000;
1737 timeKillEvent(data
->timerId
);
1739 data
->timerId
= timeSetEvent(1,
1743 TIME_ONESHOT
| TIME_PERIODIC
);
1745 if (!data
->timerId
) {
1746 perror("Failed to re-arm win32 alarm timer");
1748 timeEndPeriod(data
->period
);
1755 static int init_timer_alarm(void)
1757 struct qemu_alarm_timer
*t
= NULL
;
1760 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1761 t
= &alarm_timers
[i
];
1781 static void quit_timers(void)
1783 alarm_timer
->stop(alarm_timer
);
1787 /***********************************************************/
1788 /* host time/date access */
1789 void qemu_get_timedate(struct tm
*tm
, int offset
)
1796 if (rtc_date_offset
== -1) {
1800 ret
= localtime(&ti
);
1802 ti
-= rtc_date_offset
;
1806 memcpy(tm
, ret
, sizeof(struct tm
));
1809 int qemu_timedate_diff(struct tm
*tm
)
1813 if (rtc_date_offset
== -1)
1815 seconds
= mktimegm(tm
);
1817 seconds
= mktime(tm
);
1819 seconds
= mktimegm(tm
) + rtc_date_offset
;
1821 return seconds
- time(NULL
);
1825 static void socket_cleanup(void)
1830 static int socket_init(void)
1835 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1837 err
= WSAGetLastError();
1838 fprintf(stderr
, "WSAStartup: %d\n", err
);
1841 atexit(socket_cleanup
);
1846 const char *get_opt_name(char *buf
, int buf_size
, const char *p
, char delim
)
1851 while (*p
!= '\0' && *p
!= delim
) {
1852 if (q
&& (q
- buf
) < buf_size
- 1)
1862 const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
1867 while (*p
!= '\0') {
1869 if (*(p
+ 1) != ',')
1873 if (q
&& (q
- buf
) < buf_size
- 1)
1883 int get_param_value(char *buf
, int buf_size
,
1884 const char *tag
, const char *str
)
1891 p
= get_opt_name(option
, sizeof(option
), p
, '=');
1895 if (!strcmp(tag
, option
)) {
1896 (void)get_opt_value(buf
, buf_size
, p
);
1899 p
= get_opt_value(NULL
, 0, p
);
1908 int check_params(const char * const *params
, const char *str
)
1910 int name_buf_size
= 1;
1916 for (i
= 0; params
[i
] != NULL
; i
++) {
1917 len
= strlen(params
[i
]) + 1;
1918 if (len
> name_buf_size
) {
1919 name_buf_size
= len
;
1922 name_buf
= qemu_malloc(name_buf_size
);
1925 while (*p
!= '\0') {
1926 p
= get_opt_name(name_buf
, name_buf_size
, p
, '=');
1932 for(i
= 0; params
[i
] != NULL
; i
++)
1933 if (!strcmp(params
[i
], name_buf
))
1935 if (params
[i
] == NULL
) {
1939 p
= get_opt_value(NULL
, 0, p
);
1945 qemu_free(name_buf
);
1949 /***********************************************************/
1950 /* Bluetooth support */
1953 static struct HCIInfo
*hci_table
[MAX_NICS
];
1955 static struct bt_vlan_s
{
1956 struct bt_scatternet_s net
;
1958 struct bt_vlan_s
*next
;
1961 /* find or alloc a new bluetooth "VLAN" */
1962 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1964 struct bt_vlan_s
**pvlan
, *vlan
;
1965 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1969 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1971 pvlan
= &first_bt_vlan
;
1972 while (*pvlan
!= NULL
)
1973 pvlan
= &(*pvlan
)->next
;
1978 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1982 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1987 static struct HCIInfo null_hci
= {
1988 .cmd_send
= null_hci_send
,
1989 .sco_send
= null_hci_send
,
1990 .acl_send
= null_hci_send
,
1991 .bdaddr_set
= null_hci_addr_set
,
1994 struct HCIInfo
*qemu_next_hci(void)
1996 if (cur_hci
== nb_hcis
)
1999 return hci_table
[cur_hci
++];
2002 static struct HCIInfo
*hci_init(const char *str
)
2005 struct bt_scatternet_s
*vlan
= 0;
2007 if (!strcmp(str
, "null"))
2010 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
2012 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
2013 else if (!strncmp(str
, "hci", 3)) {
2016 if (!strncmp(str
+ 3, ",vlan=", 6)) {
2017 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
2022 vlan
= qemu_find_bt_vlan(0);
2024 return bt_new_hci(vlan
);
2027 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
2032 static int bt_hci_parse(const char *str
)
2034 struct HCIInfo
*hci
;
2037 if (nb_hcis
>= MAX_NICS
) {
2038 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
2042 hci
= hci_init(str
);
2051 bdaddr
.b
[5] = 0x56 + nb_hcis
;
2052 hci
->bdaddr_set(hci
, bdaddr
.b
);
2054 hci_table
[nb_hcis
++] = hci
;
2059 static void bt_vhci_add(int vlan_id
)
2061 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
2064 fprintf(stderr
, "qemu: warning: adding a VHCI to "
2065 "an empty scatternet %i\n", vlan_id
);
2067 bt_vhci_init(bt_new_hci(vlan
));
2070 static struct bt_device_s
*bt_device_add(const char *opt
)
2072 struct bt_scatternet_s
*vlan
;
2074 char *endp
= strstr(opt
, ",vlan=");
2075 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
2078 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
2081 vlan_id
= strtol(endp
+ 6, &endp
, 0);
2083 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
2088 vlan
= qemu_find_bt_vlan(vlan_id
);
2091 fprintf(stderr
, "qemu: warning: adding a slave device to "
2092 "an empty scatternet %i\n", vlan_id
);
2094 if (!strcmp(devname
, "keyboard"))
2095 return bt_keyboard_init(vlan
);
2097 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
2101 static int bt_parse(const char *opt
)
2103 const char *endp
, *p
;
2106 if (strstart(opt
, "hci", &endp
)) {
2107 if (!*endp
|| *endp
== ',') {
2109 if (!strstart(endp
, ",vlan=", 0))
2112 return bt_hci_parse(opt
);
2114 } else if (strstart(opt
, "vhci", &endp
)) {
2115 if (!*endp
|| *endp
== ',') {
2117 if (strstart(endp
, ",vlan=", &p
)) {
2118 vlan
= strtol(p
, (char **) &endp
, 0);
2120 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
2124 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
2133 } else if (strstart(opt
, "device:", &endp
))
2134 return !bt_device_add(endp
);
2136 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
2140 /***********************************************************/
2141 /* QEMU Block devices */
2143 #define HD_ALIAS "index=%d,media=disk"
2144 #define CDROM_ALIAS "index=2,media=cdrom"
2145 #define FD_ALIAS "index=%d,if=floppy"
2146 #define PFLASH_ALIAS "if=pflash"
2147 #define MTD_ALIAS "if=mtd"
2148 #define SD_ALIAS "index=0,if=sd"
2150 static int drive_opt_get_free_idx(void)
2154 for (index
= 0; index
< MAX_DRIVES
; index
++)
2155 if (!drives_opt
[index
].used
) {
2156 drives_opt
[index
].used
= 1;
2163 static int drive_get_free_idx(void)
2167 for (index
= 0; index
< MAX_DRIVES
; index
++)
2168 if (!drives_table
[index
].used
) {
2169 drives_table
[index
].used
= 1;
2176 int drive_add(const char *file
, const char *fmt
, ...)
2179 int index
= drive_opt_get_free_idx();
2181 if (nb_drives_opt
>= MAX_DRIVES
|| index
== -1) {
2182 fprintf(stderr
, "qemu: too many drives\n");
2186 drives_opt
[index
].file
= file
;
2188 vsnprintf(drives_opt
[index
].opt
,
2189 sizeof(drives_opt
[0].opt
), fmt
, ap
);
2196 void drive_remove(int index
)
2198 drives_opt
[index
].used
= 0;
2202 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
2206 /* seek interface, bus and unit */
2208 for (index
= 0; index
< MAX_DRIVES
; index
++)
2209 if (drives_table
[index
].type
== type
&&
2210 drives_table
[index
].bus
== bus
&&
2211 drives_table
[index
].unit
== unit
&&
2212 drives_table
[index
].used
)
2218 int drive_get_max_bus(BlockInterfaceType type
)
2224 for (index
= 0; index
< nb_drives
; index
++) {
2225 if(drives_table
[index
].type
== type
&&
2226 drives_table
[index
].bus
> max_bus
)
2227 max_bus
= drives_table
[index
].bus
;
2232 const char *drive_get_serial(BlockDriverState
*bdrv
)
2236 for (index
= 0; index
< nb_drives
; index
++)
2237 if (drives_table
[index
].bdrv
== bdrv
)
2238 return drives_table
[index
].serial
;
2243 BlockInterfaceErrorAction
drive_get_onerror(BlockDriverState
*bdrv
)
2247 for (index
= 0; index
< nb_drives
; index
++)
2248 if (drives_table
[index
].bdrv
== bdrv
)
2249 return drives_table
[index
].onerror
;
2251 return BLOCK_ERR_STOP_ENOSPC
;
2254 static void bdrv_format_print(void *opaque
, const char *name
)
2256 fprintf(stderr
, " %s", name
);
2259 void drive_uninit(BlockDriverState
*bdrv
)
2263 for (i
= 0; i
< MAX_DRIVES
; i
++)
2264 if (drives_table
[i
].bdrv
== bdrv
) {
2265 drives_table
[i
].bdrv
= NULL
;
2266 drives_table
[i
].used
= 0;
2267 drive_remove(drives_table
[i
].drive_opt_idx
);
2273 int drive_init(struct drive_opt
*arg
, int snapshot
, void *opaque
)
2279 const char *mediastr
= "";
2280 BlockInterfaceType type
;
2281 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
2282 int bus_id
, unit_id
;
2283 int cyls
, heads
, secs
, translation
;
2284 BlockDriverState
*bdrv
;
2285 BlockDriver
*drv
= NULL
;
2286 QEMUMachine
*machine
= opaque
;
2290 int bdrv_flags
, onerror
;
2291 int drives_table_idx
;
2292 char *str
= arg
->opt
;
2293 static const char * const params
[] = { "bus", "unit", "if", "index",
2294 "cyls", "heads", "secs", "trans",
2295 "media", "snapshot", "file",
2296 "cache", "format", "serial", "werror",
2299 if (check_params(params
, str
) < 0) {
2300 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
2306 cyls
= heads
= secs
= 0;
2309 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2313 if (machine
->use_scsi
) {
2315 max_devs
= MAX_SCSI_DEVS
;
2316 pstrcpy(devname
, sizeof(devname
), "scsi");
2319 max_devs
= MAX_IDE_DEVS
;
2320 pstrcpy(devname
, sizeof(devname
), "ide");
2324 /* extract parameters */
2326 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
2327 bus_id
= strtol(buf
, NULL
, 0);
2329 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
2334 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
2335 unit_id
= strtol(buf
, NULL
, 0);
2337 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
2342 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
2343 pstrcpy(devname
, sizeof(devname
), buf
);
2344 if (!strcmp(buf
, "ide")) {
2346 max_devs
= MAX_IDE_DEVS
;
2347 } else if (!strcmp(buf
, "scsi")) {
2349 max_devs
= MAX_SCSI_DEVS
;
2350 } else if (!strcmp(buf
, "floppy")) {
2353 } else if (!strcmp(buf
, "pflash")) {
2356 } else if (!strcmp(buf
, "mtd")) {
2359 } else if (!strcmp(buf
, "sd")) {
2362 } else if (!strcmp(buf
, "virtio")) {
2365 } else if (!strcmp(buf
, "xen")) {
2369 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
2374 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
2375 index
= strtol(buf
, NULL
, 0);
2377 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
2382 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
2383 cyls
= strtol(buf
, NULL
, 0);
2386 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
2387 heads
= strtol(buf
, NULL
, 0);
2390 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
2391 secs
= strtol(buf
, NULL
, 0);
2394 if (cyls
|| heads
|| secs
) {
2395 if (cyls
< 1 || cyls
> 16383) {
2396 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
2399 if (heads
< 1 || heads
> 16) {
2400 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
2403 if (secs
< 1 || secs
> 63) {
2404 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
2409 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
2412 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2416 if (!strcmp(buf
, "none"))
2417 translation
= BIOS_ATA_TRANSLATION_NONE
;
2418 else if (!strcmp(buf
, "lba"))
2419 translation
= BIOS_ATA_TRANSLATION_LBA
;
2420 else if (!strcmp(buf
, "auto"))
2421 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2423 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
2428 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
2429 if (!strcmp(buf
, "disk")) {
2431 } else if (!strcmp(buf
, "cdrom")) {
2432 if (cyls
|| secs
|| heads
) {
2434 "qemu: '%s' invalid physical CHS format\n", str
);
2437 media
= MEDIA_CDROM
;
2439 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
2444 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
2445 if (!strcmp(buf
, "on"))
2447 else if (!strcmp(buf
, "off"))
2450 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
2455 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
2456 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2458 else if (!strcmp(buf
, "writethrough"))
2460 else if (!strcmp(buf
, "writeback"))
2463 fprintf(stderr
, "qemu: invalid cache option\n");
2468 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
2469 if (strcmp(buf
, "?") == 0) {
2470 fprintf(stderr
, "qemu: Supported formats:");
2471 bdrv_iterate_format(bdrv_format_print
, NULL
);
2472 fprintf(stderr
, "\n");
2475 drv
= bdrv_find_format(buf
);
2477 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2482 if (get_param_value(buf
, sizeof(buf
), "boot", str
)) {
2483 if (!strcmp(buf
, "on")) {
2484 if (extboot_drive
!= -1) {
2485 fprintf(stderr
, "qemu: two bootable drives specified\n");
2488 extboot_drive
= nb_drives
;
2489 } else if (strcmp(buf
, "off")) {
2490 fprintf(stderr
, "qemu: '%s' invalid boot option\n", str
);
2495 if (arg
->file
== NULL
)
2496 get_param_value(file
, sizeof(file
), "file", str
);
2498 pstrcpy(file
, sizeof(file
), arg
->file
);
2500 if (!get_param_value(serial
, sizeof(serial
), "serial", str
))
2501 memset(serial
, 0, sizeof(serial
));
2503 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2504 if (get_param_value(buf
, sizeof(serial
), "werror", str
)) {
2505 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2506 fprintf(stderr
, "werror is no supported by this format\n");
2509 if (!strcmp(buf
, "ignore"))
2510 onerror
= BLOCK_ERR_IGNORE
;
2511 else if (!strcmp(buf
, "enospc"))
2512 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2513 else if (!strcmp(buf
, "stop"))
2514 onerror
= BLOCK_ERR_STOP_ANY
;
2515 else if (!strcmp(buf
, "report"))
2516 onerror
= BLOCK_ERR_REPORT
;
2518 fprintf(stderr
, "qemu: '%s' invalid write error action\n", buf
);
2523 /* compute bus and unit according index */
2526 if (bus_id
!= 0 || unit_id
!= -1) {
2528 "qemu: '%s' index cannot be used with bus and unit\n", str
);
2536 unit_id
= index
% max_devs
;
2537 bus_id
= index
/ max_devs
;
2541 /* if user doesn't specify a unit_id,
2542 * try to find the first free
2545 if (unit_id
== -1) {
2547 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
2549 if (max_devs
&& unit_id
>= max_devs
) {
2550 unit_id
-= max_devs
;
2558 if (max_devs
&& unit_id
>= max_devs
) {
2559 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
2560 str
, unit_id
, max_devs
- 1);
2565 * ignore multiple definitions
2568 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
2573 if (type
== IF_IDE
|| type
== IF_SCSI
)
2574 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2576 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
2577 devname
, bus_id
, mediastr
, unit_id
);
2579 snprintf(buf
, sizeof(buf
), "%s%s%i",
2580 devname
, mediastr
, unit_id
);
2581 bdrv
= bdrv_new(buf
);
2582 drives_table_idx
= drive_get_free_idx();
2583 drives_table
[drives_table_idx
].bdrv
= bdrv
;
2584 drives_table
[drives_table_idx
].type
= type
;
2585 drives_table
[drives_table_idx
].bus
= bus_id
;
2586 drives_table
[drives_table_idx
].unit
= unit_id
;
2587 drives_table
[drives_table_idx
].onerror
= onerror
;
2588 drives_table
[drives_table_idx
].drive_opt_idx
= arg
- drives_opt
;
2589 strncpy(drives_table
[drives_table_idx
].serial
, serial
, sizeof(serial
));
2599 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
2600 bdrv_set_translation_hint(bdrv
, translation
);
2604 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
2609 /* FIXME: This isn't really a floppy, but it's a reasonable
2612 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
2625 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2626 cache
= 2; /* always use write-back with snapshot */
2628 if (cache
== 0) /* no caching */
2629 bdrv_flags
|= BDRV_O_NOCACHE
;
2630 else if (cache
== 2) /* write-back */
2631 bdrv_flags
|= BDRV_O_CACHE_WB
;
2632 else if (cache
== 3) /* not specified */
2633 bdrv_flags
|= BDRV_O_CACHE_DEF
;
2634 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0) {
2635 fprintf(stderr
, "qemu: could not open disk image %s\n",
2639 if (bdrv_key_required(bdrv
))
2641 return drives_table_idx
;
2644 static void numa_add(const char *optarg
)
2648 unsigned long long value
, endvalue
;
2651 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2652 if (!strcmp(option
, "node")) {
2653 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2654 nodenr
= nb_numa_nodes
;
2656 nodenr
= strtoull(option
, NULL
, 10);
2659 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2660 node_mem
[nodenr
] = 0;
2662 value
= strtoull(option
, &endptr
, 0);
2664 case 0: case 'M': case 'm':
2671 node_mem
[nodenr
] = value
;
2673 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2674 node_cpumask
[nodenr
] = 0;
2676 value
= strtoull(option
, &endptr
, 10);
2679 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2681 if (*endptr
== '-') {
2682 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2683 if (endvalue
>= 63) {
2686 "only 63 CPUs in NUMA mode supported.\n");
2688 value
= (1 << (endvalue
+ 1)) - (1 << value
);
2693 node_cpumask
[nodenr
] = value
;
2700 /***********************************************************/
2703 static USBPort
*used_usb_ports
;
2704 static USBPort
*free_usb_ports
;
2706 /* ??? Maybe change this to register a hub to keep track of the topology. */
2707 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
2708 usb_attachfn attach
)
2710 port
->opaque
= opaque
;
2711 port
->index
= index
;
2712 port
->attach
= attach
;
2713 port
->next
= free_usb_ports
;
2714 free_usb_ports
= port
;
2717 int usb_device_add_dev(USBDevice
*dev
)
2721 /* Find a USB port to add the device to. */
2722 port
= free_usb_ports
;
2726 /* Create a new hub and chain it on. */
2727 free_usb_ports
= NULL
;
2728 port
->next
= used_usb_ports
;
2729 used_usb_ports
= port
;
2731 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
2732 usb_attach(port
, hub
);
2733 port
= free_usb_ports
;
2736 free_usb_ports
= port
->next
;
2737 port
->next
= used_usb_ports
;
2738 used_usb_ports
= port
;
2739 usb_attach(port
, dev
);
2743 static void usb_msd_password_cb(void *opaque
, int err
)
2745 USBDevice
*dev
= opaque
;
2748 usb_device_add_dev(dev
);
2750 dev
->handle_destroy(dev
);
2753 static int usb_device_add(const char *devname
, int is_hotplug
)
2758 if (!free_usb_ports
)
2761 if (strstart(devname
, "host:", &p
)) {
2762 dev
= usb_host_device_open(p
);
2763 } else if (!strcmp(devname
, "mouse")) {
2764 dev
= usb_mouse_init();
2765 } else if (!strcmp(devname
, "tablet")) {
2766 dev
= usb_tablet_init();
2767 } else if (!strcmp(devname
, "keyboard")) {
2768 dev
= usb_keyboard_init();
2769 } else if (strstart(devname
, "disk:", &p
)) {
2770 BlockDriverState
*bs
;
2772 dev
= usb_msd_init(p
);
2775 bs
= usb_msd_get_bdrv(dev
);
2776 if (bdrv_key_required(bs
)) {
2779 monitor_read_bdrv_key_start(cur_mon
, bs
, usb_msd_password_cb
,
2784 } else if (!strcmp(devname
, "wacom-tablet")) {
2785 dev
= usb_wacom_init();
2786 } else if (strstart(devname
, "serial:", &p
)) {
2787 dev
= usb_serial_init(p
);
2788 #ifdef CONFIG_BRLAPI
2789 } else if (!strcmp(devname
, "braille")) {
2790 dev
= usb_baum_init();
2792 } else if (strstart(devname
, "net:", &p
)) {
2795 if (net_client_init("nic", p
) < 0)
2797 nd_table
[nic
].model
= "usb";
2798 dev
= usb_net_init(&nd_table
[nic
]);
2799 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2800 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2801 bt_new_hci(qemu_find_bt_vlan(0)));
2808 return usb_device_add_dev(dev
);
2811 int usb_device_del_addr(int bus_num
, int addr
)
2817 if (!used_usb_ports
)
2823 lastp
= &used_usb_ports
;
2824 port
= used_usb_ports
;
2825 while (port
&& port
->dev
->addr
!= addr
) {
2826 lastp
= &port
->next
;
2834 *lastp
= port
->next
;
2835 usb_attach(port
, NULL
);
2836 dev
->handle_destroy(dev
);
2837 port
->next
= free_usb_ports
;
2838 free_usb_ports
= port
;
2842 static int usb_device_del(const char *devname
)
2847 if (strstart(devname
, "host:", &p
))
2848 return usb_host_device_close(p
);
2850 if (!used_usb_ports
)
2853 p
= strchr(devname
, '.');
2856 bus_num
= strtoul(devname
, NULL
, 0);
2857 addr
= strtoul(p
+ 1, NULL
, 0);
2859 return usb_device_del_addr(bus_num
, addr
);
2862 void do_usb_add(Monitor
*mon
, const char *devname
)
2864 usb_device_add(devname
, 1);
2867 void do_usb_del(Monitor
*mon
, const char *devname
)
2869 usb_device_del(devname
);
2872 void usb_info(Monitor
*mon
)
2876 const char *speed_str
;
2879 monitor_printf(mon
, "USB support not enabled\n");
2883 for (port
= used_usb_ports
; port
; port
= port
->next
) {
2887 switch(dev
->speed
) {
2891 case USB_SPEED_FULL
:
2894 case USB_SPEED_HIGH
:
2901 monitor_printf(mon
, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2902 0, dev
->addr
, speed_str
, dev
->devname
);
2906 /***********************************************************/
2907 /* PCMCIA/Cardbus */
2909 static struct pcmcia_socket_entry_s
{
2910 PCMCIASocket
*socket
;
2911 struct pcmcia_socket_entry_s
*next
;
2912 } *pcmcia_sockets
= 0;
2914 void pcmcia_socket_register(PCMCIASocket
*socket
)
2916 struct pcmcia_socket_entry_s
*entry
;
2918 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2919 entry
->socket
= socket
;
2920 entry
->next
= pcmcia_sockets
;
2921 pcmcia_sockets
= entry
;
2924 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2926 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2928 ptr
= &pcmcia_sockets
;
2929 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2930 if (entry
->socket
== socket
) {
2936 void pcmcia_info(Monitor
*mon
)
2938 struct pcmcia_socket_entry_s
*iter
;
2940 if (!pcmcia_sockets
)
2941 monitor_printf(mon
, "No PCMCIA sockets\n");
2943 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2944 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2945 iter
->socket
->attached
? iter
->socket
->card_string
:
2949 /***********************************************************/
2950 /* register display */
2952 struct DisplayAllocator default_allocator
= {
2953 defaultallocator_create_displaysurface
,
2954 defaultallocator_resize_displaysurface
,
2955 defaultallocator_free_displaysurface
2958 void register_displaystate(DisplayState
*ds
)
2968 DisplayState
*get_displaystate(void)
2970 return display_state
;
2973 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
2975 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
2976 return ds
->allocator
;
2981 static void dumb_display_init(void)
2983 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
2984 ds
->allocator
= &default_allocator
;
2985 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
2986 register_displaystate(ds
);
2989 /***********************************************************/
2992 typedef struct IOHandlerRecord
{
2994 IOCanRWHandler
*fd_read_poll
;
2996 IOHandler
*fd_write
;
2999 /* temporary data */
3001 struct IOHandlerRecord
*next
;
3004 static IOHandlerRecord
*first_io_handler
;
3006 /* XXX: fd_read_poll should be suppressed, but an API change is
3007 necessary in the character devices to suppress fd_can_read(). */
3008 int qemu_set_fd_handler2(int fd
,
3009 IOCanRWHandler
*fd_read_poll
,
3011 IOHandler
*fd_write
,
3014 IOHandlerRecord
**pioh
, *ioh
;
3016 if (!fd_read
&& !fd_write
) {
3017 pioh
= &first_io_handler
;
3022 if (ioh
->fd
== fd
) {
3029 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3033 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
3034 ioh
->next
= first_io_handler
;
3035 first_io_handler
= ioh
;
3038 ioh
->fd_read_poll
= fd_read_poll
;
3039 ioh
->fd_read
= fd_read
;
3040 ioh
->fd_write
= fd_write
;
3041 ioh
->opaque
= opaque
;
3044 qemu_notify_event();
3048 int qemu_set_fd_handler(int fd
,
3050 IOHandler
*fd_write
,
3053 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
3057 /***********************************************************/
3058 /* Polling handling */
3060 typedef struct PollingEntry
{
3063 struct PollingEntry
*next
;
3066 static PollingEntry
*first_polling_entry
;
3068 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
3070 PollingEntry
**ppe
, *pe
;
3071 pe
= qemu_mallocz(sizeof(PollingEntry
));
3073 pe
->opaque
= opaque
;
3074 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
3079 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
3081 PollingEntry
**ppe
, *pe
;
3082 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
3084 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
3092 /***********************************************************/
3093 /* Wait objects support */
3094 typedef struct WaitObjects
{
3096 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
3097 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
3098 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
3101 static WaitObjects wait_objects
= {0};
3103 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
3105 WaitObjects
*w
= &wait_objects
;
3107 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
3109 w
->events
[w
->num
] = handle
;
3110 w
->func
[w
->num
] = func
;
3111 w
->opaque
[w
->num
] = opaque
;
3116 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
3119 WaitObjects
*w
= &wait_objects
;
3122 for (i
= 0; i
< w
->num
; i
++) {
3123 if (w
->events
[i
] == handle
)
3126 w
->events
[i
] = w
->events
[i
+ 1];
3127 w
->func
[i
] = w
->func
[i
+ 1];
3128 w
->opaque
[i
] = w
->opaque
[i
+ 1];
3136 /***********************************************************/
3137 /* ram save/restore */
3139 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
3143 v
= qemu_get_byte(f
);
3146 if (qemu_get_buffer(f
, buf
, len
) != len
)
3150 v
= qemu_get_byte(f
);
3151 memset(buf
, v
, len
);
3157 if (qemu_file_has_error(f
))
3163 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
3168 if (qemu_get_be32(f
) != last_ram_offset
)
3170 for(i
= 0; i
< last_ram_offset
; i
+= TARGET_PAGE_SIZE
) {
3171 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3173 ret
= ram_get_page(f
, qemu_get_ram_ptr(i
), TARGET_PAGE_SIZE
);
3180 #define BDRV_HASH_BLOCK_SIZE 1024
3181 #define IOBUF_SIZE 4096
3182 #define RAM_CBLOCK_MAGIC 0xfabe
3184 typedef struct RamDecompressState
{
3187 uint8_t buf
[IOBUF_SIZE
];
3188 } RamDecompressState
;
3190 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
3193 memset(s
, 0, sizeof(*s
));
3195 ret
= inflateInit(&s
->zstream
);
3201 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
3205 s
->zstream
.avail_out
= len
;
3206 s
->zstream
.next_out
= buf
;
3207 while (s
->zstream
.avail_out
> 0) {
3208 if (s
->zstream
.avail_in
== 0) {
3209 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
3211 clen
= qemu_get_be16(s
->f
);
3212 if (clen
> IOBUF_SIZE
)
3214 qemu_get_buffer(s
->f
, s
->buf
, clen
);
3215 s
->zstream
.avail_in
= clen
;
3216 s
->zstream
.next_in
= s
->buf
;
3218 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
3219 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
3226 static void ram_decompress_close(RamDecompressState
*s
)
3228 inflateEnd(&s
->zstream
);
3231 #define RAM_SAVE_FLAG_FULL 0x01
3232 #define RAM_SAVE_FLAG_COMPRESS 0x02
3233 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3234 #define RAM_SAVE_FLAG_PAGE 0x08
3235 #define RAM_SAVE_FLAG_EOS 0x10
3237 static int is_dup_page(uint8_t *page
, uint8_t ch
)
3239 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
3240 uint32_t *array
= (uint32_t *)page
;
3243 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
3244 if (array
[i
] != val
)
3251 static int ram_save_block(QEMUFile
*f
)
3253 static ram_addr_t current_addr
= 0;
3254 ram_addr_t saved_addr
= current_addr
;
3255 ram_addr_t addr
= 0;
3258 while (addr
< last_ram_offset
) {
3259 if (kvm_enabled() && current_addr
== 0) {
3261 r
= kvm_update_dirty_pages_log();
3263 fprintf(stderr
, "%s: update dirty pages log failed %d\n", __FUNCTION__
, r
);
3264 qemu_file_set_error(f
);
3268 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
3271 cpu_physical_memory_reset_dirty(current_addr
,
3272 current_addr
+ TARGET_PAGE_SIZE
,
3273 MIGRATION_DIRTY_FLAG
);
3275 p
= qemu_get_ram_ptr(current_addr
);
3277 if (is_dup_page(p
, *p
)) {
3278 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
3279 qemu_put_byte(f
, *p
);
3281 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
3282 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
3288 addr
+= TARGET_PAGE_SIZE
;
3289 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
3295 static ram_addr_t ram_save_threshold
= 10;
3297 static ram_addr_t
ram_save_remaining(void)
3300 ram_addr_t count
= 0;
3302 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3303 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3310 static int ram_save_live(QEMUFile
*f
, int stage
, void *opaque
)
3315 /* Make sure all dirty bits are set */
3316 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3317 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3318 cpu_physical_memory_set_dirty(addr
);
3321 /* Enable dirty memory tracking */
3322 cpu_physical_memory_set_dirty_tracking(1);
3324 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
3327 while (!qemu_file_rate_limit(f
)) {
3330 ret
= ram_save_block(f
);
3331 if (ret
== 0) /* no more blocks */
3335 /* try transferring iterative blocks of memory */
3339 /* flush all remaining blocks regardless of rate limiting */
3340 while (ram_save_block(f
) != 0);
3341 cpu_physical_memory_set_dirty_tracking(0);
3344 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3346 return (stage
== 2) && (ram_save_remaining() < ram_save_threshold
);
3349 static int ram_load_dead(QEMUFile
*f
, void *opaque
)
3351 RamDecompressState s1
, *s
= &s1
;
3355 if (ram_decompress_open(s
, f
) < 0)
3357 for(i
= 0; i
< last_ram_offset
; i
+= BDRV_HASH_BLOCK_SIZE
) {
3358 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3360 if (ram_decompress_buf(s
, buf
, 1) < 0) {
3361 fprintf(stderr
, "Error while reading ram block header\n");
3365 if (ram_decompress_buf(s
, qemu_get_ram_ptr(i
),
3366 BDRV_HASH_BLOCK_SIZE
) < 0) {
3367 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
3372 printf("Error block header\n");
3376 ram_decompress_close(s
);
3381 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
3386 if (version_id
== 1)
3387 return ram_load_v1(f
, opaque
);
3389 if (version_id
== 2) {
3390 if (qemu_get_be32(f
) != last_ram_offset
)
3392 return ram_load_dead(f
, opaque
);
3395 if (version_id
!= 3)
3399 addr
= qemu_get_be64(f
);
3401 flags
= addr
& ~TARGET_PAGE_MASK
;
3402 addr
&= TARGET_PAGE_MASK
;
3404 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
3405 if (addr
!= last_ram_offset
)
3409 if (flags
& RAM_SAVE_FLAG_FULL
) {
3410 if (ram_load_dead(f
, opaque
) < 0)
3414 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
3415 uint8_t ch
= qemu_get_byte(f
);
3416 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
3417 } else if (flags
& RAM_SAVE_FLAG_PAGE
)
3418 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
3419 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
3424 void qemu_service_io(void)
3426 qemu_notify_event();
3429 /***********************************************************/
3430 /* bottom halves (can be seen as timers which expire ASAP) */
3441 static QEMUBH
*first_bh
= NULL
;
3443 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
3446 bh
= qemu_mallocz(sizeof(QEMUBH
));
3448 bh
->opaque
= opaque
;
3449 bh
->next
= first_bh
;
3454 int qemu_bh_poll(void)
3460 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3461 if (!bh
->deleted
&& bh
->scheduled
) {
3470 /* remove deleted bhs */
3484 void qemu_bh_schedule_idle(QEMUBH
*bh
)
3492 void qemu_bh_schedule(QEMUBH
*bh
)
3498 /* stop the currently executing CPU to execute the BH ASAP */
3499 qemu_notify_event();
3502 void qemu_bh_cancel(QEMUBH
*bh
)
3507 void qemu_bh_delete(QEMUBH
*bh
)
3513 static void qemu_bh_update_timeout(int *timeout
)
3517 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3518 if (!bh
->deleted
&& bh
->scheduled
) {
3520 /* idle bottom halves will be polled at least
3522 *timeout
= MIN(10, *timeout
);
3524 /* non-idle bottom halves will be executed
3533 /***********************************************************/
3534 /* machine registration */
3536 static QEMUMachine
*first_machine
= NULL
;
3537 QEMUMachine
*current_machine
= NULL
;
3539 int qemu_register_machine(QEMUMachine
*m
)
3542 pm
= &first_machine
;
3550 static QEMUMachine
*find_machine(const char *name
)
3554 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3555 if (!strcmp(m
->name
, name
))
3561 /***********************************************************/
3562 /* main execution loop */
3564 static void gui_update(void *opaque
)
3566 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3567 DisplayState
*ds
= opaque
;
3568 DisplayChangeListener
*dcl
= ds
->listeners
;
3572 while (dcl
!= NULL
) {
3573 if (dcl
->gui_timer_interval
&&
3574 dcl
->gui_timer_interval
< interval
)
3575 interval
= dcl
->gui_timer_interval
;
3578 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3581 static void nographic_update(void *opaque
)
3583 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3585 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3588 struct vm_change_state_entry
{
3589 VMChangeStateHandler
*cb
;
3591 LIST_ENTRY (vm_change_state_entry
) entries
;
3594 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3596 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3599 VMChangeStateEntry
*e
;
3601 e
= qemu_mallocz(sizeof (*e
));
3605 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3609 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3611 LIST_REMOVE (e
, entries
);
3615 static void vm_state_notify(int running
, int reason
)
3617 VMChangeStateEntry
*e
;
3619 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3620 e
->cb(e
->opaque
, running
, reason
);
3624 static void resume_all_vcpus(void);
3625 static void pause_all_vcpus(void);
3632 vm_state_notify(1, 0);
3633 qemu_rearm_alarm_timer(alarm_timer
);
3638 /* reset/shutdown handler */
3640 typedef struct QEMUResetEntry
{
3641 QEMUResetHandler
*func
;
3643 struct QEMUResetEntry
*next
;
3646 static QEMUResetEntry
*first_reset_entry
;
3647 static int reset_requested
;
3648 static int shutdown_requested
;
3649 static int powerdown_requested
;
3650 static int debug_requested
;
3651 static int vmstop_requested
;
3653 int qemu_no_shutdown(void)
3655 int r
= no_shutdown
;
3660 int qemu_shutdown_requested(void)
3662 int r
= shutdown_requested
;
3663 shutdown_requested
= 0;
3667 int qemu_reset_requested(void)
3669 int r
= reset_requested
;
3670 reset_requested
= 0;
3674 int qemu_powerdown_requested(void)
3676 int r
= powerdown_requested
;
3677 powerdown_requested
= 0;
3681 static int qemu_debug_requested(void)
3683 int r
= debug_requested
;
3684 debug_requested
= 0;
3688 static int qemu_vmstop_requested(void)
3690 int r
= vmstop_requested
;
3691 vmstop_requested
= 0;
3695 static void do_vm_stop(int reason
)
3698 cpu_disable_ticks();
3701 vm_state_notify(0, reason
);
3705 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3707 QEMUResetEntry
**pre
, *re
;
3709 pre
= &first_reset_entry
;
3710 while (*pre
!= NULL
)
3711 pre
= &(*pre
)->next
;
3712 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3714 re
->opaque
= opaque
;
3719 void qemu_system_reset(void)
3723 /* reset all devices */
3724 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
3725 re
->func(re
->opaque
);
3731 void qemu_system_reset_request(void)
3734 shutdown_requested
= 1;
3736 reset_requested
= 1;
3738 if (cpu_single_env
) {
3739 qemu_kvm_cpu_stop(cpu_single_env
);
3740 cpu_exit(cpu_single_env
);
3742 qemu_notify_event();
3745 void qemu_system_shutdown_request(void)
3747 shutdown_requested
= 1;
3748 qemu_notify_event();
3751 void qemu_system_powerdown_request(void)
3753 powerdown_requested
= 1;
3754 qemu_notify_event();
3757 #ifdef CONFIG_IOTHREAD
3758 static void qemu_system_vmstop_request(int reason
)
3760 vmstop_requested
= reason
;
3761 qemu_notify_event();
3766 static int io_thread_fd
= -1;
3768 static void qemu_event_increment(void)
3770 static const char byte
= 0;
3772 if (io_thread_fd
== -1)
3775 write(io_thread_fd
, &byte
, sizeof(byte
));
3778 static void qemu_event_read(void *opaque
)
3780 int fd
= (unsigned long)opaque
;
3783 /* Drain the notify pipe */
3786 len
= read(fd
, buffer
, sizeof(buffer
));
3787 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
3790 static int qemu_event_init(void)
3799 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3803 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3807 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3808 (void *)(unsigned long)fds
[0]);
3810 io_thread_fd
= fds
[1];
3819 HANDLE qemu_event_handle
;
3821 static void dummy_event_handler(void *opaque
)
3825 static int qemu_event_init(void)
3827 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3828 if (!qemu_event_handle
) {
3829 perror("Failed CreateEvent");
3832 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3836 static void qemu_event_increment(void)
3838 SetEvent(qemu_event_handle
);
3842 static int cpu_can_run(CPUState
*env
)
3851 #ifndef CONFIG_IOTHREAD
3852 static int qemu_init_main_loop(void)
3854 return qemu_event_init();
3857 void qemu_init_vcpu(void *_env
)
3859 CPUState
*env
= _env
;
3866 int qemu_cpu_self(void *env
)
3871 static void resume_all_vcpus(void)
3875 static void pause_all_vcpus(void)
3879 void qemu_cpu_kick(void *env
)
3884 void qemu_notify_event(void)
3886 CPUState
*env
= cpu_single_env
;
3888 if (kvm_enabled()) {
3889 qemu_kvm_notify_work();
3895 if (env
->kqemu_enabled
)
3896 kqemu_cpu_interrupt(env
);
3901 #define qemu_mutex_lock_iothread() do { } while (0)
3902 #define qemu_mutex_unlock_iothread() do { } while (0)
3904 void vm_stop(int reason
)
3909 #else /* CONFIG_IOTHREAD */
3911 #include "qemu-thread.h"
3913 QemuMutex qemu_global_mutex
;
3914 static QemuMutex qemu_fair_mutex
;
3916 static QemuThread io_thread
;
3918 static QemuThread
*tcg_cpu_thread
;
3919 static QemuCond
*tcg_halt_cond
;
3921 static int qemu_system_ready
;
3923 static QemuCond qemu_cpu_cond
;
3925 static QemuCond qemu_system_cond
;
3926 static QemuCond qemu_pause_cond
;
3928 static void block_io_signals(void);
3929 static void unblock_io_signals(void);
3930 static int tcg_has_work(void);
3932 static int qemu_init_main_loop(void)
3936 ret
= qemu_event_init();
3940 qemu_cond_init(&qemu_pause_cond
);
3941 qemu_mutex_init(&qemu_fair_mutex
);
3942 qemu_mutex_init(&qemu_global_mutex
);
3943 qemu_mutex_lock(&qemu_global_mutex
);
3945 unblock_io_signals();
3946 qemu_thread_self(&io_thread
);
3951 static void qemu_wait_io_event(CPUState
*env
)
3953 while (!tcg_has_work())
3954 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3956 qemu_mutex_unlock(&qemu_global_mutex
);
3959 * Users of qemu_global_mutex can be starved, having no chance
3960 * to acquire it since this path will get to it first.
3961 * So use another lock to provide fairness.
3963 qemu_mutex_lock(&qemu_fair_mutex
);
3964 qemu_mutex_unlock(&qemu_fair_mutex
);
3966 qemu_mutex_lock(&qemu_global_mutex
);
3970 qemu_cond_signal(&qemu_pause_cond
);
3974 static int qemu_cpu_exec(CPUState
*env
);
3976 static void *kvm_cpu_thread_fn(void *arg
)
3978 CPUState
*env
= arg
;
3981 qemu_thread_self(env
->thread
);
3983 /* signal CPU creation */
3984 qemu_mutex_lock(&qemu_global_mutex
);
3986 qemu_cond_signal(&qemu_cpu_cond
);
3988 /* and wait for machine initialization */
3989 while (!qemu_system_ready
)
3990 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3993 if (cpu_can_run(env
))
3995 qemu_wait_io_event(env
);
4001 static void tcg_cpu_exec(void);
4003 static void *tcg_cpu_thread_fn(void *arg
)
4005 CPUState
*env
= arg
;
4008 qemu_thread_self(env
->thread
);
4010 /* signal CPU creation */
4011 qemu_mutex_lock(&qemu_global_mutex
);
4012 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4014 qemu_cond_signal(&qemu_cpu_cond
);
4016 /* and wait for machine initialization */
4017 while (!qemu_system_ready
)
4018 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
4022 qemu_wait_io_event(cur_cpu
);
4028 void qemu_cpu_kick(void *_env
)
4030 CPUState
*env
= _env
;
4031 qemu_cond_broadcast(env
->halt_cond
);
4033 qemu_thread_signal(env
->thread
, SIGUSR1
);
4036 int qemu_cpu_self(void *env
)
4038 return (cpu_single_env
!= NULL
);
4041 static void cpu_signal(int sig
)
4044 cpu_exit(cpu_single_env
);
4047 static void block_io_signals(void)
4050 struct sigaction sigact
;
4053 sigaddset(&set
, SIGUSR2
);
4054 sigaddset(&set
, SIGIO
);
4055 sigaddset(&set
, SIGALRM
);
4056 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
4059 sigaddset(&set
, SIGUSR1
);
4060 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
4062 memset(&sigact
, 0, sizeof(sigact
));
4063 sigact
.sa_handler
= cpu_signal
;
4064 sigaction(SIGUSR1
, &sigact
, NULL
);
4067 static void unblock_io_signals(void)
4072 sigaddset(&set
, SIGUSR2
);
4073 sigaddset(&set
, SIGIO
);
4074 sigaddset(&set
, SIGALRM
);
4075 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
4078 sigaddset(&set
, SIGUSR1
);
4079 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
4082 static void qemu_signal_lock(unsigned int msecs
)
4084 qemu_mutex_lock(&qemu_fair_mutex
);
4086 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
4087 qemu_thread_signal(tcg_cpu_thread
, SIGUSR1
);
4088 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
4091 qemu_mutex_unlock(&qemu_fair_mutex
);
4094 static void qemu_mutex_lock_iothread(void)
4096 if (kvm_enabled()) {
4097 qemu_mutex_lock(&qemu_fair_mutex
);
4098 qemu_mutex_lock(&qemu_global_mutex
);
4099 qemu_mutex_unlock(&qemu_fair_mutex
);
4101 qemu_signal_lock(100);
4104 static void qemu_mutex_unlock_iothread(void)
4106 qemu_mutex_unlock(&qemu_global_mutex
);
4109 static int all_vcpus_paused(void)
4111 CPUState
*penv
= first_cpu
;
4116 penv
= (CPUState
*)penv
->next_cpu
;
4122 static void pause_all_vcpus(void)
4124 CPUState
*penv
= first_cpu
;
4128 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4129 qemu_cpu_kick(penv
);
4130 penv
= (CPUState
*)penv
->next_cpu
;
4133 while (!all_vcpus_paused()) {
4134 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
4137 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4138 penv
= (CPUState
*)penv
->next_cpu
;
4143 static void resume_all_vcpus(void)
4145 CPUState
*penv
= first_cpu
;
4150 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4151 qemu_cpu_kick(penv
);
4152 penv
= (CPUState
*)penv
->next_cpu
;
4156 static void tcg_init_vcpu(void *_env
)
4158 CPUState
*env
= _env
;
4159 /* share a single thread for all cpus with TCG */
4160 if (!tcg_cpu_thread
) {
4161 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
4162 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
4163 qemu_cond_init(env
->halt_cond
);
4164 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
4165 while (env
->created
== 0)
4166 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
4167 tcg_cpu_thread
= env
->thread
;
4168 tcg_halt_cond
= env
->halt_cond
;
4170 env
->thread
= tcg_cpu_thread
;
4171 env
->halt_cond
= tcg_halt_cond
;
4175 static void kvm_start_vcpu(CPUState
*env
)
4178 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
4179 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
4180 qemu_cond_init(env
->halt_cond
);
4181 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
4182 while (env
->created
== 0)
4183 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
4186 void qemu_init_vcpu(void *_env
)
4188 CPUState
*env
= _env
;
4191 kvm_start_vcpu(env
);
4196 void qemu_notify_event(void)
4198 qemu_event_increment();
4201 void vm_stop(int reason
)
4204 qemu_thread_self(&me
);
4206 if (!qemu_thread_equal(&me
, &io_thread
)) {
4207 qemu_system_vmstop_request(reason
);
4209 * FIXME: should not return to device code in case
4210 * vm_stop() has been requested.
4212 if (cpu_single_env
) {
4213 cpu_exit(cpu_single_env
);
4214 cpu_single_env
->stop
= 1;
4225 static void host_main_loop_wait(int *timeout
)
4231 /* XXX: need to suppress polling by better using win32 events */
4233 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
4234 ret
|= pe
->func(pe
->opaque
);
4238 WaitObjects
*w
= &wait_objects
;
4240 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
4241 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
4242 if (w
->func
[ret
- WAIT_OBJECT_0
])
4243 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
4245 /* Check for additional signaled events */
4246 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
4248 /* Check if event is signaled */
4249 ret2
= WaitForSingleObject(w
->events
[i
], 0);
4250 if(ret2
== WAIT_OBJECT_0
) {
4252 w
->func
[i
](w
->opaque
[i
]);
4253 } else if (ret2
== WAIT_TIMEOUT
) {
4255 err
= GetLastError();
4256 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
4259 } else if (ret
== WAIT_TIMEOUT
) {
4261 err
= GetLastError();
4262 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
4269 static void host_main_loop_wait(int *timeout
)
4274 void main_loop_wait(int timeout
)
4276 IOHandlerRecord
*ioh
;
4277 fd_set rfds
, wfds
, xfds
;
4281 qemu_bh_update_timeout(&timeout
);
4283 host_main_loop_wait(&timeout
);
4285 /* poll any events */
4286 /* XXX: separate device handlers from system ones */
4291 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4295 (!ioh
->fd_read_poll
||
4296 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
4297 FD_SET(ioh
->fd
, &rfds
);
4301 if (ioh
->fd_write
) {
4302 FD_SET(ioh
->fd
, &wfds
);
4308 tv
.tv_sec
= timeout
/ 1000;
4309 tv
.tv_usec
= (timeout
% 1000) * 1000;
4311 #if defined(CONFIG_SLIRP)
4312 if (slirp_is_inited()) {
4313 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
4316 ret
= qemu_select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
4318 IOHandlerRecord
**pioh
;
4320 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4321 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
4322 ioh
->fd_read(ioh
->opaque
);
4323 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
4324 FD_CLR(ioh
->fd
, &rfds
);
4326 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
4327 ioh
->fd_write(ioh
->opaque
);
4331 /* remove deleted IO handlers */
4332 pioh
= &first_io_handler
;
4342 #if defined(CONFIG_SLIRP)
4343 if (slirp_is_inited()) {
4349 slirp_select_poll(&rfds
, &wfds
, &xfds
);
4353 /* rearm timer, if not periodic */
4354 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
4355 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
4356 qemu_rearm_alarm_timer(alarm_timer
);
4359 /* vm time timers */
4361 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
4362 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
4363 qemu_get_clock(vm_clock
));
4366 /* real time timers */
4367 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
4368 qemu_get_clock(rt_clock
));
4370 /* Check bottom-halves last in case any of the earlier events triggered
4376 static int qemu_cpu_exec(CPUState
*env
)
4379 #ifdef CONFIG_PROFILER
4383 #ifdef CONFIG_PROFILER
4384 ti
= profile_getclock();
4389 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
4390 env
->icount_decr
.u16
.low
= 0;
4391 env
->icount_extra
= 0;
4392 count
= qemu_next_deadline();
4393 count
= (count
+ (1 << icount_time_shift
) - 1)
4394 >> icount_time_shift
;
4395 qemu_icount
+= count
;
4396 decr
= (count
> 0xffff) ? 0xffff : count
;
4398 env
->icount_decr
.u16
.low
= decr
;
4399 env
->icount_extra
= count
;
4401 ret
= cpu_exec(env
);
4402 #ifdef CONFIG_PROFILER
4403 qemu_time
+= profile_getclock() - ti
;
4406 /* Fold pending instructions back into the
4407 instruction counter, and clear the interrupt flag. */
4408 qemu_icount
-= (env
->icount_decr
.u16
.low
4409 + env
->icount_extra
);
4410 env
->icount_decr
.u32
= 0;
4411 env
->icount_extra
= 0;
4416 static void tcg_cpu_exec(void)
4420 if (next_cpu
== NULL
)
4421 next_cpu
= first_cpu
;
4422 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
4423 CPUState
*env
= cur_cpu
= next_cpu
;
4427 if (timer_alarm_pending
) {
4428 timer_alarm_pending
= 0;
4431 if (cpu_can_run(env
))
4432 ret
= qemu_cpu_exec(env
);
4433 if (ret
== EXCP_DEBUG
) {
4434 gdb_set_stop_cpu(env
);
4435 debug_requested
= 1;
4441 static int cpu_has_work(CPUState
*env
)
4449 if (qemu_cpu_has_work(env
))
4454 static int tcg_has_work(void)
4458 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4459 if (cpu_has_work(env
))
4464 static int qemu_calculate_timeout(void)
4470 else if (tcg_has_work())
4472 else if (!use_icount
)
4475 /* XXX: use timeout computed from timers */
4478 /* Advance virtual time to the next event. */
4479 if (use_icount
== 1) {
4480 /* When not using an adaptive execution frequency
4481 we tend to get badly out of sync with real time,
4482 so just delay for a reasonable amount of time. */
4485 delta
= cpu_get_icount() - cpu_get_clock();
4488 /* If virtual time is ahead of real time then just
4490 timeout
= (delta
/ 1000000) + 1;
4492 /* Wait for either IO to occur or the next
4494 add
= qemu_next_deadline();
4495 /* We advance the timer before checking for IO.
4496 Limit the amount we advance so that early IO
4497 activity won't get the guest too far ahead. */
4501 add
= (add
+ (1 << icount_time_shift
) - 1)
4502 >> icount_time_shift
;
4504 timeout
= delta
/ 1000000;
4513 static int vm_can_run(void)
4515 if (powerdown_requested
)
4517 if (reset_requested
)
4519 if (shutdown_requested
)
4521 if (debug_requested
)
4526 static void main_loop(void)
4530 if (kvm_enabled()) {
4532 cpu_disable_ticks();
4536 #ifdef CONFIG_IOTHREAD
4537 qemu_system_ready
= 1;
4538 qemu_cond_broadcast(&qemu_system_cond
);
4543 #ifdef CONFIG_PROFILER
4546 #ifndef CONFIG_IOTHREAD
4549 #ifdef CONFIG_PROFILER
4550 ti
= profile_getclock();
4552 #ifdef CONFIG_IOTHREAD
4553 main_loop_wait(1000);
4555 main_loop_wait(qemu_calculate_timeout());
4557 #ifdef CONFIG_PROFILER
4558 dev_time
+= profile_getclock() - ti
;
4560 } while (vm_can_run());
4562 if (qemu_debug_requested())
4563 vm_stop(EXCP_DEBUG
);
4564 if (qemu_shutdown_requested()) {
4571 if (qemu_reset_requested()) {
4573 qemu_system_reset();
4576 if (qemu_powerdown_requested())
4577 qemu_system_powerdown();
4578 if ((r
= qemu_vmstop_requested()))
4584 static void version(void)
4586 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4589 static void help(int exitcode
)
4592 printf("usage: %s [options] [disk_image]\n"
4594 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4596 #define DEF(option, opt_arg, opt_enum, opt_help) \
4598 #define DEFHEADING(text) stringify(text) "\n"
4599 #include "qemu-options.h"
4604 "During emulation, the following keys are useful:\n"
4605 "ctrl-alt-f toggle full screen\n"
4606 "ctrl-alt-n switch to virtual console 'n'\n"
4607 "ctrl-alt toggle mouse and keyboard grab\n"
4609 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4614 DEFAULT_NETWORK_SCRIPT
,
4615 DEFAULT_NETWORK_DOWN_SCRIPT
,
4617 DEFAULT_GDBSTUB_PORT
,
4622 #define HAS_ARG 0x0001
4625 #define DEF(option, opt_arg, opt_enum, opt_help) \
4627 #define DEFHEADING(text)
4628 #include "qemu-options.h"
4634 typedef struct QEMUOption
{
4640 static const QEMUOption qemu_options
[] = {
4641 { "h", 0, QEMU_OPTION_h
},
4642 #define DEF(option, opt_arg, opt_enum, opt_help) \
4643 { option, opt_arg, opt_enum },
4644 #define DEFHEADING(text)
4645 #include "qemu-options.h"
4653 struct soundhw soundhw
[] = {
4654 #ifdef HAS_AUDIO_CHOICE
4655 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4661 { .init_isa
= pcspk_audio_init
}
4668 "Creative Sound Blaster 16",
4671 { .init_isa
= SB16_init
}
4675 #ifdef CONFIG_CS4231A
4681 { .init_isa
= cs4231a_init
}
4689 "Yamaha YMF262 (OPL3)",
4691 "Yamaha YM3812 (OPL2)",
4695 { .init_isa
= Adlib_init
}
4702 "Gravis Ultrasound GF1",
4705 { .init_isa
= GUS_init
}
4712 "Intel 82801AA AC97 Audio",
4715 { .init_pci
= ac97_init
}
4719 #ifdef CONFIG_ES1370
4722 "ENSONIQ AudioPCI ES1370",
4725 { .init_pci
= es1370_init
}
4729 #endif /* HAS_AUDIO_CHOICE */
4731 { NULL
, NULL
, 0, 0, { NULL
} }
4734 static void select_soundhw (const char *optarg
)
4738 if (*optarg
== '?') {
4741 printf ("Valid sound card names (comma separated):\n");
4742 for (c
= soundhw
; c
->name
; ++c
) {
4743 printf ("%-11s %s\n", c
->name
, c
->descr
);
4745 printf ("\n-soundhw all will enable all of the above\n");
4746 exit (*optarg
!= '?');
4754 if (!strcmp (optarg
, "all")) {
4755 for (c
= soundhw
; c
->name
; ++c
) {
4763 e
= strchr (p
, ',');
4764 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4766 for (c
= soundhw
; c
->name
; ++c
) {
4767 if (!strncmp (c
->name
, p
, l
)) {
4776 "Unknown sound card name (too big to show)\n");
4779 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4784 p
+= l
+ (e
!= NULL
);
4788 goto show_valid_cards
;
4793 static void select_vgahw (const char *p
)
4797 cirrus_vga_enabled
= 0;
4798 std_vga_enabled
= 0;
4801 if (strstart(p
, "std", &opts
)) {
4802 std_vga_enabled
= 1;
4803 } else if (strstart(p
, "cirrus", &opts
)) {
4804 cirrus_vga_enabled
= 1;
4805 } else if (strstart(p
, "vmware", &opts
)) {
4807 } else if (strstart(p
, "xenfb", &opts
)) {
4809 } else if (!strstart(p
, "none", &opts
)) {
4811 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4815 const char *nextopt
;
4817 if (strstart(opts
, ",retrace=", &nextopt
)) {
4819 if (strstart(opts
, "dumb", &nextopt
))
4820 vga_retrace_method
= VGA_RETRACE_DUMB
;
4821 else if (strstart(opts
, "precise", &nextopt
))
4822 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4823 else goto invalid_vga
;
4824 } else goto invalid_vga
;
4830 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4832 exit(STATUS_CONTROL_C_EXIT
);
4837 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4841 if(strlen(str
) != 36)
4844 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4845 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4846 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4852 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4858 #define MAX_NET_CLIENTS 32
4862 #define HUGETLBFS_MAGIC 0x958458f6
4864 static long gethugepagesize(const char *path
)
4870 ret
= statfs(path
, &fs
);
4871 } while (ret
!= 0 && errno
== EINTR
);
4878 if (fs
.f_type
!= HUGETLBFS_MAGIC
)
4879 fprintf(stderr
, "Warning: path not on HugeTLBFS: %s\n", path
);
4884 static void *alloc_mem_area(size_t memory
, unsigned long *len
, const char *path
)
4893 if (!kvm_has_sync_mmu()) {
4894 fprintf(stderr
, "host lacks mmu notifiers, disabling --mem-path\n");
4898 if (asprintf(&filename
, "%s/kvm.XXXXXX", path
) == -1)
4901 hpagesize
= gethugepagesize(path
);
4905 fd
= mkstemp(filename
);
4914 memory
= (memory
+hpagesize
-1) & ~(hpagesize
-1);
4917 * ftruncate is not supported by hugetlbfs in older
4918 * hosts, so don't bother checking for errors.
4919 * If anything goes wrong with it under other filesystems,
4922 ftruncate(fd
, memory
);
4925 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4926 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4927 * to sidestep this quirk.
4929 flags
= mem_prealloc
? MAP_POPULATE
|MAP_SHARED
: MAP_PRIVATE
;
4930 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, flags
, fd
, 0);
4932 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
, fd
, 0);
4934 if (area
== MAP_FAILED
) {
4935 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4946 static void termsig_handler(int signal
)
4948 qemu_system_shutdown_request();
4951 static void termsig_setup(void)
4953 struct sigaction act
;
4955 memset(&act
, 0, sizeof(act
));
4956 act
.sa_handler
= termsig_handler
;
4957 sigaction(SIGINT
, &act
, NULL
);
4958 sigaction(SIGHUP
, &act
, NULL
);
4959 sigaction(SIGTERM
, &act
, NULL
);
4964 int main(int argc
, char **argv
, char **envp
)
4966 const char *gdbstub_dev
= NULL
;
4967 uint32_t boot_devices_bitmap
= 0;
4969 int snapshot
, linux_boot
, net_boot
;
4970 const char *initrd_filename
;
4971 const char *kernel_filename
, *kernel_cmdline
;
4972 const char *boot_devices
= "";
4974 DisplayChangeListener
*dcl
;
4975 int cyls
, heads
, secs
, translation
;
4976 const char *net_clients
[MAX_NET_CLIENTS
];
4978 const char *bt_opts
[MAX_BT_CMDLINE
];
4982 const char *r
, *optarg
;
4983 CharDriverState
*monitor_hd
= NULL
;
4984 const char *monitor_device
;
4985 const char *serial_devices
[MAX_SERIAL_PORTS
];
4986 int serial_device_index
;
4987 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
4988 int parallel_device_index
;
4989 const char *virtio_consoles
[MAX_VIRTIO_CONSOLES
];
4990 int virtio_console_index
;
4991 const char *loadvm
= NULL
;
4992 QEMUMachine
*machine
;
4993 const char *cpu_model
;
4994 const char *usb_devices
[MAX_USB_CMDLINE
];
4995 int usb_devices_index
;
5000 const char *pid_file
= NULL
;
5001 const char *incoming
= NULL
;
5004 struct passwd
*pwd
= NULL
;
5005 const char *chroot_dir
= NULL
;
5006 const char *run_as
= NULL
;
5010 qemu_cache_utils_init(envp
);
5012 LIST_INIT (&vm_change_state_head
);
5015 struct sigaction act
;
5016 sigfillset(&act
.sa_mask
);
5018 act
.sa_handler
= SIG_IGN
;
5019 sigaction(SIGPIPE
, &act
, NULL
);
5022 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
5023 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5024 QEMU to run on a single CPU */
5029 h
= GetCurrentProcess();
5030 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
5031 for(i
= 0; i
< 32; i
++) {
5032 if (mask
& (1 << i
))
5037 SetProcessAffinityMask(h
, mask
);
5043 module_call_init(MODULE_INIT_MACHINE
);
5044 machine
= first_machine
;
5046 initrd_filename
= NULL
;
5051 kernel_filename
= NULL
;
5052 kernel_cmdline
= "";
5053 cyls
= heads
= secs
= 0;
5054 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5055 monitor_device
= "vc:80Cx24C";
5057 serial_devices
[0] = "vc:80Cx24C";
5058 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
5059 serial_devices
[i
] = NULL
;
5060 serial_device_index
= 0;
5062 parallel_devices
[0] = "vc:80Cx24C";
5063 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
5064 parallel_devices
[i
] = NULL
;
5065 parallel_device_index
= 0;
5067 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++)
5068 virtio_consoles
[i
] = NULL
;
5069 virtio_console_index
= 0;
5071 for (i
= 0; i
< MAX_NODES
; i
++) {
5073 node_cpumask
[i
] = 0;
5076 usb_devices_index
= 0;
5077 assigned_devices_index
= 0;
5091 register_watchdogs();
5099 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
5101 const QEMUOption
*popt
;
5104 /* Treat --foo the same as -foo. */
5107 popt
= qemu_options
;
5110 fprintf(stderr
, "%s: invalid option -- '%s'\n",
5114 if (!strcmp(popt
->name
, r
+ 1))
5118 if (popt
->flags
& HAS_ARG
) {
5119 if (optind
>= argc
) {
5120 fprintf(stderr
, "%s: option '%s' requires an argument\n",
5124 optarg
= argv
[optind
++];
5129 switch(popt
->index
) {
5131 machine
= find_machine(optarg
);
5134 printf("Supported machines are:\n");
5135 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5136 printf("%-10s %s%s\n",
5138 m
== first_machine
? " (default)" : "");
5140 exit(*optarg
!= '?');
5143 case QEMU_OPTION_cpu
:
5144 /* hw initialization will check this */
5145 if (*optarg
== '?') {
5146 /* XXX: implement xxx_cpu_list for targets that still miss it */
5147 #if defined(cpu_list)
5148 cpu_list(stdout
, &fprintf
);
5155 case QEMU_OPTION_initrd
:
5156 initrd_filename
= optarg
;
5158 case QEMU_OPTION_hda
:
5160 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
5162 hda_index
= drive_add(optarg
, HD_ALIAS
5163 ",cyls=%d,heads=%d,secs=%d%s",
5164 0, cyls
, heads
, secs
,
5165 translation
== BIOS_ATA_TRANSLATION_LBA
?
5167 translation
== BIOS_ATA_TRANSLATION_NONE
?
5168 ",trans=none" : "");
5170 case QEMU_OPTION_hdb
:
5171 case QEMU_OPTION_hdc
:
5172 case QEMU_OPTION_hdd
:
5173 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
5175 case QEMU_OPTION_drive
:
5176 drive_add(NULL
, "%s", optarg
);
5178 case QEMU_OPTION_mtdblock
:
5179 drive_add(optarg
, MTD_ALIAS
);
5181 case QEMU_OPTION_sd
:
5182 drive_add(optarg
, SD_ALIAS
);
5184 case QEMU_OPTION_pflash
:
5185 drive_add(optarg
, PFLASH_ALIAS
);
5187 case QEMU_OPTION_snapshot
:
5190 case QEMU_OPTION_hdachs
:
5194 cyls
= strtol(p
, (char **)&p
, 0);
5195 if (cyls
< 1 || cyls
> 16383)
5200 heads
= strtol(p
, (char **)&p
, 0);
5201 if (heads
< 1 || heads
> 16)
5206 secs
= strtol(p
, (char **)&p
, 0);
5207 if (secs
< 1 || secs
> 63)
5211 if (!strcmp(p
, "none"))
5212 translation
= BIOS_ATA_TRANSLATION_NONE
;
5213 else if (!strcmp(p
, "lba"))
5214 translation
= BIOS_ATA_TRANSLATION_LBA
;
5215 else if (!strcmp(p
, "auto"))
5216 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5219 } else if (*p
!= '\0') {
5221 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5224 if (hda_index
!= -1)
5225 snprintf(drives_opt
[hda_index
].opt
,
5226 sizeof(drives_opt
[hda_index
].opt
),
5227 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
5228 0, cyls
, heads
, secs
,
5229 translation
== BIOS_ATA_TRANSLATION_LBA
?
5231 translation
== BIOS_ATA_TRANSLATION_NONE
?
5232 ",trans=none" : "");
5235 case QEMU_OPTION_numa
:
5236 if (nb_numa_nodes
>= MAX_NODES
) {
5237 fprintf(stderr
, "qemu: too many NUMA nodes\n");
5242 case QEMU_OPTION_nographic
:
5245 #ifdef CONFIG_CURSES
5246 case QEMU_OPTION_curses
:
5250 case QEMU_OPTION_portrait
:
5253 case QEMU_OPTION_kernel
:
5254 kernel_filename
= optarg
;
5256 case QEMU_OPTION_append
:
5257 kernel_cmdline
= optarg
;
5259 case QEMU_OPTION_cdrom
:
5260 drive_add(optarg
, CDROM_ALIAS
);
5262 case QEMU_OPTION_boot
:
5263 boot_devices
= optarg
;
5264 /* We just do some generic consistency checks */
5266 /* Could easily be extended to 64 devices if needed */
5269 boot_devices_bitmap
= 0;
5270 for (p
= boot_devices
; *p
!= '\0'; p
++) {
5271 /* Allowed boot devices are:
5272 * a b : floppy disk drives
5273 * c ... f : IDE disk drives
5274 * g ... m : machine implementation dependant drives
5275 * n ... p : network devices
5276 * It's up to each machine implementation to check
5277 * if the given boot devices match the actual hardware
5278 * implementation and firmware features.
5280 if (*p
< 'a' || *p
> 'q') {
5281 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
5284 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
5286 "Boot device '%c' was given twice\n",*p
);
5289 boot_devices_bitmap
|= 1 << (*p
- 'a');
5293 case QEMU_OPTION_fda
:
5294 case QEMU_OPTION_fdb
:
5295 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
5298 case QEMU_OPTION_no_fd_bootchk
:
5302 case QEMU_OPTION_net
:
5303 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
5304 fprintf(stderr
, "qemu: too many network clients\n");
5307 net_clients
[nb_net_clients
] = optarg
;
5311 case QEMU_OPTION_tftp
:
5312 tftp_prefix
= optarg
;
5314 case QEMU_OPTION_bootp
:
5315 bootp_filename
= optarg
;
5318 case QEMU_OPTION_smb
:
5319 net_slirp_smb(optarg
);
5322 case QEMU_OPTION_redir
:
5323 net_slirp_redir(NULL
, optarg
);
5326 case QEMU_OPTION_bt
:
5327 if (nb_bt_opts
>= MAX_BT_CMDLINE
) {
5328 fprintf(stderr
, "qemu: too many bluetooth options\n");
5331 bt_opts
[nb_bt_opts
++] = optarg
;
5334 case QEMU_OPTION_audio_help
:
5338 case QEMU_OPTION_soundhw
:
5339 select_soundhw (optarg
);
5345 case QEMU_OPTION_version
:
5349 case QEMU_OPTION_m
: {
5353 value
= strtoul(optarg
, &ptr
, 10);
5355 case 0: case 'M': case 'm':
5362 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5366 /* On 32-bit hosts, QEMU is limited by virtual address space */
5367 if (value
> (2047 << 20)
5368 #ifndef CONFIG_KQEMU
5369 && HOST_LONG_BITS
== 32
5372 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5375 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5376 fprintf(stderr
, "qemu: ram size too large\n");
5385 const CPULogItem
*item
;
5387 mask
= cpu_str_to_log_mask(optarg
);
5389 printf("Log items (comma separated):\n");
5390 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5391 printf("%-10s %s\n", item
->name
, item
->help
);
5399 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5401 case QEMU_OPTION_gdb
:
5402 gdbstub_dev
= optarg
;
5407 case QEMU_OPTION_bios
:
5410 case QEMU_OPTION_singlestep
:
5418 keyboard_layout
= optarg
;
5421 case QEMU_OPTION_localtime
:
5424 case QEMU_OPTION_vga
:
5425 select_vgahw (optarg
);
5427 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5433 w
= strtol(p
, (char **)&p
, 10);
5436 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5442 h
= strtol(p
, (char **)&p
, 10);
5447 depth
= strtol(p
, (char **)&p
, 10);
5448 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5449 depth
!= 24 && depth
!= 32)
5451 } else if (*p
== '\0') {
5452 depth
= graphic_depth
;
5459 graphic_depth
= depth
;
5463 case QEMU_OPTION_echr
:
5466 term_escape_char
= strtol(optarg
, &r
, 0);
5468 printf("Bad argument to echr\n");
5471 case QEMU_OPTION_monitor
:
5472 monitor_device
= optarg
;
5474 case QEMU_OPTION_serial
:
5475 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
5476 fprintf(stderr
, "qemu: too many serial ports\n");
5479 serial_devices
[serial_device_index
] = optarg
;
5480 serial_device_index
++;
5482 case QEMU_OPTION_watchdog
:
5483 i
= select_watchdog(optarg
);
5485 exit (i
== 1 ? 1 : 0);
5487 case QEMU_OPTION_watchdog_action
:
5488 if (select_watchdog_action(optarg
) == -1) {
5489 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5493 case QEMU_OPTION_virtiocon
:
5494 if (virtio_console_index
>= MAX_VIRTIO_CONSOLES
) {
5495 fprintf(stderr
, "qemu: too many virtio consoles\n");
5498 virtio_consoles
[virtio_console_index
] = optarg
;
5499 virtio_console_index
++;
5501 case QEMU_OPTION_parallel
:
5502 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
5503 fprintf(stderr
, "qemu: too many parallel ports\n");
5506 parallel_devices
[parallel_device_index
] = optarg
;
5507 parallel_device_index
++;
5509 case QEMU_OPTION_loadvm
:
5512 case QEMU_OPTION_full_screen
:
5516 case QEMU_OPTION_no_frame
:
5519 case QEMU_OPTION_alt_grab
:
5522 case QEMU_OPTION_no_quit
:
5525 case QEMU_OPTION_sdl
:
5529 case QEMU_OPTION_pidfile
:
5533 case QEMU_OPTION_win2k_hack
:
5534 win2k_install_hack
= 1;
5536 case QEMU_OPTION_rtc_td_hack
:
5539 case QEMU_OPTION_acpitable
:
5540 if(acpi_table_add(optarg
) < 0) {
5541 fprintf(stderr
, "Wrong acpi table provided\n");
5545 case QEMU_OPTION_smbios
:
5546 if(smbios_entry_add(optarg
) < 0) {
5547 fprintf(stderr
, "Wrong smbios provided\n");
5553 case QEMU_OPTION_no_kqemu
:
5556 case QEMU_OPTION_kernel_kqemu
:
5561 case QEMU_OPTION_enable_kvm
:
5569 case QEMU_OPTION_no_kvm
:
5572 case QEMU_OPTION_no_kvm_irqchip
: {
5577 case QEMU_OPTION_no_kvm_pit
: {
5581 case QEMU_OPTION_no_kvm_pit_reinjection
: {
5582 kvm_pit_reinject
= 0;
5585 case QEMU_OPTION_enable_nesting
: {
5589 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5590 case QEMU_OPTION_pcidevice
:
5591 if (assigned_devices_index
>= MAX_DEV_ASSIGN_CMDLINE
) {
5592 fprintf(stderr
, "Too many assigned devices\n");
5595 assigned_devices
[assigned_devices_index
] = optarg
;
5596 assigned_devices_index
++;
5600 case QEMU_OPTION_usb
:
5603 case QEMU_OPTION_usbdevice
:
5605 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
5606 fprintf(stderr
, "Too many USB devices\n");
5609 usb_devices
[usb_devices_index
] = optarg
;
5610 usb_devices_index
++;
5612 case QEMU_OPTION_smp
:
5613 smp_cpus
= atoi(optarg
);
5615 fprintf(stderr
, "Invalid number of CPUs\n");
5619 case QEMU_OPTION_vnc
:
5620 vnc_display
= optarg
;
5623 case QEMU_OPTION_no_acpi
:
5626 case QEMU_OPTION_no_hpet
:
5630 case QEMU_OPTION_no_reboot
:
5633 case QEMU_OPTION_no_shutdown
:
5636 case QEMU_OPTION_show_cursor
:
5639 case QEMU_OPTION_uuid
:
5640 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5641 fprintf(stderr
, "Fail to parse UUID string."
5642 " Wrong format.\n");
5647 case QEMU_OPTION_daemonize
:
5651 case QEMU_OPTION_option_rom
:
5652 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5653 fprintf(stderr
, "Too many option ROMs\n");
5656 option_rom
[nb_option_roms
] = optarg
;
5659 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5660 case QEMU_OPTION_semihosting
:
5661 semihosting_enabled
= 1;
5664 case QEMU_OPTION_tdf
:
5667 case QEMU_OPTION_kvm_shadow_memory
:
5668 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
5670 case QEMU_OPTION_mempath
:
5674 case QEMU_OPTION_mem_prealloc
:
5675 mem_prealloc
= !mem_prealloc
;
5678 case QEMU_OPTION_name
:
5681 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5682 case QEMU_OPTION_prom_env
:
5683 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5684 fprintf(stderr
, "Too many prom variables\n");
5687 prom_envs
[nb_prom_envs
] = optarg
;
5692 case QEMU_OPTION_old_param
:
5696 case QEMU_OPTION_clock
:
5697 configure_alarms(optarg
);
5699 case QEMU_OPTION_startdate
:
5702 time_t rtc_start_date
;
5703 if (!strcmp(optarg
, "now")) {
5704 rtc_date_offset
= -1;
5706 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
5714 } else if (sscanf(optarg
, "%d-%d-%d",
5717 &tm
.tm_mday
) == 3) {
5726 rtc_start_date
= mktimegm(&tm
);
5727 if (rtc_start_date
== -1) {
5729 fprintf(stderr
, "Invalid date format. Valid format are:\n"
5730 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5733 rtc_date_offset
= time(NULL
) - rtc_start_date
;
5737 case QEMU_OPTION_tb_size
:
5738 tb_size
= strtol(optarg
, NULL
, 0);
5742 case QEMU_OPTION_icount
:
5744 if (strcmp(optarg
, "auto") == 0) {
5745 icount_time_shift
= -1;
5747 icount_time_shift
= strtol(optarg
, NULL
, 0);
5750 case QEMU_OPTION_incoming
:
5754 case QEMU_OPTION_chroot
:
5755 chroot_dir
= optarg
;
5757 case QEMU_OPTION_runas
:
5760 case QEMU_OPTION_nvram
:
5765 case QEMU_OPTION_xen_domid
:
5766 xen_domid
= atoi(optarg
);
5768 case QEMU_OPTION_xen_create
:
5769 xen_mode
= XEN_CREATE
;
5771 case QEMU_OPTION_xen_attach
:
5772 xen_mode
= XEN_ATTACH
;
5779 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5780 if (kvm_allowed
&& kqemu_allowed
) {
5782 "You can not enable both KVM and kqemu at the same time\n");
5787 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5788 if (smp_cpus
> machine
->max_cpus
) {
5789 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5790 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5796 if (serial_device_index
== 0)
5797 serial_devices
[0] = "stdio";
5798 if (parallel_device_index
== 0)
5799 parallel_devices
[0] = "null";
5800 if (strncmp(monitor_device
, "vc", 2) == 0)
5801 monitor_device
= "stdio";
5808 if (pipe(fds
) == -1)
5819 len
= read(fds
[0], &status
, 1);
5820 if (len
== -1 && (errno
== EINTR
))
5825 else if (status
== 1) {
5826 fprintf(stderr
, "Could not acquire pidfile\n");
5843 signal(SIGTSTP
, SIG_IGN
);
5844 signal(SIGTTOU
, SIG_IGN
);
5845 signal(SIGTTIN
, SIG_IGN
);
5849 if (kvm_enabled()) {
5850 if (kvm_qemu_init() < 0) {
5851 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
5852 #ifdef NO_CPU_EMULATION
5853 fprintf(stderr
, "Compiled with --disable-cpu-emulation, exiting.\n");
5861 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5864 write(fds
[1], &status
, 1);
5866 fprintf(stderr
, "Could not acquire pid file\n");
5875 if (qemu_init_main_loop()) {
5876 fprintf(stderr
, "qemu_init_main_loop failed\n");
5879 linux_boot
= (kernel_filename
!= NULL
);
5880 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5882 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5883 fprintf(stderr
, "-append only allowed with -kernel option\n");
5887 if (!linux_boot
&& initrd_filename
!= NULL
) {
5888 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5892 /* boot to floppy or the default cd if no hard disk defined yet */
5893 if (!boot_devices
[0]) {
5894 boot_devices
= "cad";
5896 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5899 if (init_timer_alarm() < 0) {
5900 fprintf(stderr
, "could not initialize alarm timer\n");
5903 if (use_icount
&& icount_time_shift
< 0) {
5905 /* 125MIPS seems a reasonable initial guess at the guest speed.
5906 It will be corrected fairly quickly anyway. */
5907 icount_time_shift
= 3;
5908 init_icount_adjust();
5915 /* init network clients */
5916 if (nb_net_clients
== 0) {
5917 /* if no clients, we use a default config */
5918 net_clients
[nb_net_clients
++] = "nic";
5920 net_clients
[nb_net_clients
++] = "user";
5924 for(i
= 0;i
< nb_net_clients
; i
++) {
5925 if (net_client_parse(net_clients
[i
]) < 0)
5931 /* XXX: this should be moved in the PC machine instantiation code */
5932 if (net_boot
!= 0) {
5934 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
5935 const char *model
= nd_table
[i
].model
;
5937 if (net_boot
& (1 << i
)) {
5940 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
5941 if (get_image_size(buf
) > 0) {
5942 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5943 fprintf(stderr
, "Too many option ROMs\n");
5946 option_rom
[nb_option_roms
] = strdup(buf
);
5953 fprintf(stderr
, "No valid PXE rom found for network device\n");
5959 /* init the bluetooth world */
5960 for (i
= 0; i
< nb_bt_opts
; i
++)
5961 if (bt_parse(bt_opts
[i
]))
5964 /* init the memory */
5966 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5968 if (kvm_enabled()) {
5969 if (kvm_qemu_create_context() < 0) {
5970 fprintf(stderr
, "Could not create KVM context\n");
5976 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5977 guest ram allocation. It needs to go away. */
5978 if (kqemu_allowed
) {
5979 kqemu_phys_ram_size
= ram_size
+ 8 * 1024 * 1024 + 4 * 1024 * 1024;
5980 kqemu_phys_ram_base
= qemu_vmalloc(kqemu_phys_ram_size
);
5981 if (!kqemu_phys_ram_base
) {
5982 fprintf(stderr
, "Could not allocate physical memory\n");
5988 /* init the dynamic translator */
5989 cpu_exec_init_all(tb_size
* 1024 * 1024);
5994 /* we always create the cdrom drive, even if no disk is there */
5996 if (nb_drives_opt
< MAX_DRIVES
)
5997 drive_add(NULL
, CDROM_ALIAS
);
5999 /* we always create at least one floppy */
6001 if (nb_drives_opt
< MAX_DRIVES
)
6002 drive_add(NULL
, FD_ALIAS
, 0);
6004 /* we always create one sd slot, even if no card is in it */
6006 if (nb_drives_opt
< MAX_DRIVES
)
6007 drive_add(NULL
, SD_ALIAS
);
6009 /* open the virtual block devices
6010 * note that migration with device
6011 * hot add/remove is broken.
6013 for(i
= 0; i
< nb_drives_opt
; i
++)
6014 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
6017 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
6018 register_savevm_live("ram", 0, 3, ram_save_live
, NULL
, ram_load
, NULL
);
6021 /* must be after terminal init, SDL library changes signal handlers */
6025 /* Maintain compatibility with multiple stdio monitors */
6026 if (!strcmp(monitor_device
,"stdio")) {
6027 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6028 const char *devname
= serial_devices
[i
];
6029 if (devname
&& !strcmp(devname
,"mon:stdio")) {
6030 monitor_device
= NULL
;
6032 } else if (devname
&& !strcmp(devname
,"stdio")) {
6033 monitor_device
= NULL
;
6034 serial_devices
[i
] = "mon:stdio";
6040 if (nb_numa_nodes
> 0) {
6043 if (nb_numa_nodes
> smp_cpus
) {
6044 nb_numa_nodes
= smp_cpus
;
6047 /* If no memory size if given for any node, assume the default case
6048 * and distribute the available memory equally across all nodes
6050 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6051 if (node_mem
[i
] != 0)
6054 if (i
== nb_numa_nodes
) {
6055 uint64_t usedmem
= 0;
6057 /* On Linux, the each node's border has to be 8MB aligned,
6058 * the final node gets the rest.
6060 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
6061 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
6062 usedmem
+= node_mem
[i
];
6064 node_mem
[i
] = ram_size
- usedmem
;
6067 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6068 if (node_cpumask
[i
] != 0)
6071 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6072 * must cope with this anyway, because there are BIOSes out there in
6073 * real machines which also use this scheme.
6075 if (i
== nb_numa_nodes
) {
6076 for (i
= 0; i
< smp_cpus
; i
++) {
6077 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
6083 if (kvm_enabled()) {
6086 ret
= kvm_init(smp_cpus
);
6088 fprintf(stderr
, "failed to initialize KVM\n");
6094 if (monitor_device
) {
6095 monitor_hd
= qemu_chr_open("monitor", monitor_device
, NULL
);
6097 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
6102 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6103 const char *devname
= serial_devices
[i
];
6104 if (devname
&& strcmp(devname
, "none")) {
6106 snprintf(label
, sizeof(label
), "serial%d", i
);
6107 serial_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6108 if (!serial_hds
[i
]) {
6109 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
6116 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
6117 const char *devname
= parallel_devices
[i
];
6118 if (devname
&& strcmp(devname
, "none")) {
6120 snprintf(label
, sizeof(label
), "parallel%d", i
);
6121 parallel_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6122 if (!parallel_hds
[i
]) {
6123 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
6130 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
6131 const char *devname
= virtio_consoles
[i
];
6132 if (devname
&& strcmp(devname
, "none")) {
6134 snprintf(label
, sizeof(label
), "virtcon%d", i
);
6135 virtcon_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6136 if (!virtcon_hds
[i
]) {
6137 fprintf(stderr
, "qemu: could not open virtio console '%s'\n",
6144 module_call_init(MODULE_INIT_DEVICE
);
6149 machine
->init(ram_size
, boot_devices
,
6150 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
6153 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
6154 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6155 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
6161 current_machine
= machine
;
6163 /* Set KVM's vcpu state to qemu's initial CPUState. */
6164 if (kvm_enabled()) {
6167 ret
= kvm_sync_vcpus();
6169 fprintf(stderr
, "failed to initialize vcpus\n");
6174 /* init USB devices */
6176 for(i
= 0; i
< usb_devices_index
; i
++) {
6177 if (usb_device_add(usb_devices
[i
], 0) < 0) {
6178 fprintf(stderr
, "Warning: could not add USB device %s\n",
6185 dumb_display_init();
6186 /* just use the first displaystate for the moment */
6191 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
6195 #if defined(CONFIG_CURSES)
6197 /* At the moment curses cannot be used with other displays */
6198 curses_display_init(ds
, full_screen
);
6201 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6203 #if defined(CONFIG_SDL)
6204 sdl_display_init(ds
, full_screen
, no_frame
);
6205 #elif defined(CONFIG_COCOA)
6206 cocoa_display_init(ds
, full_screen
);
6213 if (vnc_display
== NULL
) {
6214 vnc_display
= "localhost:0,to=99";
6218 vnc_display_init(ds
);
6219 if (vnc_display_open(ds
, vnc_display
) < 0)
6223 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
6229 dcl
= ds
->listeners
;
6230 while (dcl
!= NULL
) {
6231 if (dcl
->dpy_refresh
!= NULL
) {
6232 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
6233 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
6238 if (nographic
|| (vnc_display
&& !sdl
)) {
6239 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
6240 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
6243 text_consoles_set_display(display_state
);
6244 qemu_chr_initial_reset();
6246 if (monitor_device
&& monitor_hd
)
6247 monitor_init(monitor_hd
, MONITOR_USE_READLINE
| MONITOR_IS_DEFAULT
);
6249 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6250 const char *devname
= serial_devices
[i
];
6251 if (devname
&& strcmp(devname
, "none")) {
6253 snprintf(label
, sizeof(label
), "serial%d", i
);
6254 if (strstart(devname
, "vc", 0))
6255 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
6259 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
6260 const char *devname
= parallel_devices
[i
];
6261 if (devname
&& strcmp(devname
, "none")) {
6263 snprintf(label
, sizeof(label
), "parallel%d", i
);
6264 if (strstart(devname
, "vc", 0))
6265 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
6269 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
6270 const char *devname
= virtio_consoles
[i
];
6271 if (virtcon_hds
[i
] && devname
) {
6273 snprintf(label
, sizeof(label
), "virtcon%d", i
);
6274 if (strstart(devname
, "vc", 0))
6275 qemu_chr_printf(virtcon_hds
[i
], "virtio console%d\r\n", i
);
6279 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
6280 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
6286 do_loadvm(cur_mon
, loadvm
);
6289 autostart
= 0; /* fixme how to deal with -daemonize */
6290 qemu_start_incoming_migration(incoming
);
6302 len
= write(fds
[1], &status
, 1);
6303 if (len
== -1 && (errno
== EINTR
))
6310 TFR(fd
= open("/dev/null", O_RDWR
));
6316 pwd
= getpwnam(run_as
);
6318 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
6324 if (chroot(chroot_dir
) < 0) {
6325 fprintf(stderr
, "chroot failed\n");
6332 if (setgid(pwd
->pw_gid
) < 0) {
6333 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
6336 if (setuid(pwd
->pw_uid
) < 0) {
6337 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
6340 if (setuid(0) != -1) {
6341 fprintf(stderr
, "Dropping privileges failed\n");