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-option.h"
161 #include "qemu-kvm.h"
162 #include "hw/device-assignment.h"
166 #include "exec-all.h"
168 #include "qemu_socket.h"
170 #if defined(CONFIG_SLIRP)
171 #include "libslirp.h"
174 //#define DEBUG_UNUSED_IOPORT
175 //#define DEBUG_IOPORT
177 //#define DEBUG_SLIRP
181 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
183 # define LOG_IOPORT(...) do { } while (0)
186 #define DEFAULT_RAM_SIZE 128
188 /* Max number of USB devices that can be specified on the commandline. */
189 #define MAX_USB_CMDLINE 8
191 /* Max number of bluetooth switches on the commandline. */
192 #define MAX_BT_CMDLINE 10
194 /* XXX: use a two level table to limit memory usage */
195 #define MAX_IOPORTS 65536
197 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
198 const char *bios_name
= NULL
;
199 static void *ioport_opaque
[MAX_IOPORTS
];
200 static IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
201 static IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
202 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
203 to store the VM snapshots */
204 DriveInfo drives_table
[MAX_DRIVES
+1];
206 int extboot_drive
= -1;
207 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
208 static DisplayState
*display_state
;
209 DisplayType display_type
= DT_DEFAULT
;
210 const char* keyboard_layout
= NULL
;
211 int64_t ticks_per_sec
;
214 NICInfo nd_table
[MAX_NICS
];
216 static int autostart
;
217 static int rtc_utc
= 1;
218 static int rtc_date_offset
= -1; /* -1 means no change */
219 int cirrus_vga_enabled
= 1;
220 int std_vga_enabled
= 0;
221 int vmsvga_enabled
= 0;
222 int xenfb_enabled
= 0;
224 int graphic_width
= 1024;
225 int graphic_height
= 768;
226 int graphic_depth
= 8;
228 int graphic_width
= 800;
229 int graphic_height
= 600;
230 int graphic_depth
= 15;
232 static int full_screen
= 0;
234 static int no_frame
= 0;
237 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
238 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
239 CharDriverState
*virtcon_hds
[MAX_VIRTIO_CONSOLES
];
241 int win2k_install_hack
= 0;
246 const char *assigned_devices
[MAX_DEV_ASSIGN_CMDLINE
];
247 int assigned_devices_index
;
249 const char *vnc_display
;
250 int acpi_enabled
= 1;
256 int graphic_rotate
= 0;
260 WatchdogTimerModel
*watchdog
= NULL
;
261 int watchdog_action
= WDT_RESET
;
262 const char *option_rom
[MAX_OPTION_ROMS
];
264 int semihosting_enabled
= 0;
265 int time_drift_fix
= 0;
266 unsigned int kvm_shadow_memory
= 0;
267 const char *mem_path
= NULL
;
269 int mem_prealloc
= 1; /* force preallocation of physical target memory */
275 const char *qemu_name
;
277 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
278 unsigned int nb_prom_envs
= 0;
279 const char *prom_envs
[MAX_PROM_ENVS
];
282 const char *nvram
= NULL
;
283 struct drive_opt drives_opt
[MAX_DRIVES
];
286 uint64_t node_mem
[MAX_NODES
];
287 uint64_t node_cpumask
[MAX_NODES
];
289 static CPUState
*cur_cpu
;
290 static CPUState
*next_cpu
;
291 static int timer_alarm_pending
= 1;
292 /* Conversion factor from emulated instructions to virtual clock ticks. */
293 static int icount_time_shift
;
294 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
295 #define MAX_ICOUNT_SHIFT 10
296 /* Compensate for varying guest execution speed. */
297 static int64_t qemu_icount_bias
;
298 static QEMUTimer
*icount_rt_timer
;
299 static QEMUTimer
*icount_vm_timer
;
300 static QEMUTimer
*nographic_timer
;
302 uint8_t qemu_uuid
[16];
304 static int qemu_select(int max_fd
, fd_set
*rfds
, fd_set
*wfds
, fd_set
*xfds
,
309 /* KVM holds a mutex while QEMU code is running, we need hooks to
310 release the mutex whenever QEMU code sleeps. */
314 ret
= select(max_fd
, rfds
, wfds
, xfds
, tv
);
322 /***********************************************************/
323 /* x86 ISA bus support */
325 target_phys_addr_t isa_mem_base
= 0;
328 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
329 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
331 static uint32_t ioport_read(int index
, uint32_t address
)
333 static IOPortReadFunc
*default_func
[3] = {
334 default_ioport_readb
,
335 default_ioport_readw
,
338 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
340 func
= default_func
[index
];
341 return func(ioport_opaque
[address
], address
);
344 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
346 static IOPortWriteFunc
*default_func
[3] = {
347 default_ioport_writeb
,
348 default_ioport_writew
,
349 default_ioport_writel
351 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
353 func
= default_func
[index
];
354 func(ioport_opaque
[address
], address
, data
);
357 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
359 #ifdef DEBUG_UNUSED_IOPORT
360 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
365 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
367 #ifdef DEBUG_UNUSED_IOPORT
368 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
372 /* default is to make two byte accesses */
373 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
376 data
= ioport_read(0, address
);
377 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
378 data
|= ioport_read(0, address
) << 8;
382 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
384 ioport_write(0, address
, data
& 0xff);
385 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
386 ioport_write(0, address
, (data
>> 8) & 0xff);
389 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
391 #ifdef DEBUG_UNUSED_IOPORT
392 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
397 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
399 #ifdef DEBUG_UNUSED_IOPORT
400 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
404 /* size is the word size in byte */
405 int register_ioport_read(int start
, int length
, int size
,
406 IOPortReadFunc
*func
, void *opaque
)
412 } else if (size
== 2) {
414 } else if (size
== 4) {
417 hw_error("register_ioport_read: invalid size");
420 for(i
= start
; i
< start
+ length
; i
+= size
) {
421 ioport_read_table
[bsize
][i
] = func
;
422 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
423 hw_error("register_ioport_read: invalid opaque");
424 ioport_opaque
[i
] = opaque
;
429 /* size is the word size in byte */
430 int register_ioport_write(int start
, int length
, int size
,
431 IOPortWriteFunc
*func
, void *opaque
)
437 } else if (size
== 2) {
439 } else if (size
== 4) {
442 hw_error("register_ioport_write: invalid size");
445 for(i
= start
; i
< start
+ length
; i
+= size
) {
446 ioport_write_table
[bsize
][i
] = func
;
447 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
448 hw_error("register_ioport_write: invalid opaque");
449 ioport_opaque
[i
] = opaque
;
454 void isa_unassign_ioport(int start
, int length
)
458 for(i
= start
; i
< start
+ length
; i
++) {
459 ioport_read_table
[0][i
] = default_ioport_readb
;
460 ioport_read_table
[1][i
] = default_ioport_readw
;
461 ioport_read_table
[2][i
] = default_ioport_readl
;
463 ioport_write_table
[0][i
] = default_ioport_writeb
;
464 ioport_write_table
[1][i
] = default_ioport_writew
;
465 ioport_write_table
[2][i
] = default_ioport_writel
;
467 ioport_opaque
[i
] = NULL
;
471 /***********************************************************/
473 void cpu_outb(CPUState
*env
, int addr
, int val
)
475 LOG_IOPORT("outb: %04x %02x\n", addr
, val
);
476 ioport_write(0, addr
, val
);
479 env
->last_io_time
= cpu_get_time_fast();
483 void cpu_outw(CPUState
*env
, int addr
, int val
)
485 LOG_IOPORT("outw: %04x %04x\n", addr
, val
);
486 ioport_write(1, addr
, val
);
489 env
->last_io_time
= cpu_get_time_fast();
493 void cpu_outl(CPUState
*env
, int addr
, int val
)
495 LOG_IOPORT("outl: %04x %08x\n", addr
, val
);
496 ioport_write(2, addr
, val
);
499 env
->last_io_time
= cpu_get_time_fast();
503 int cpu_inb(CPUState
*env
, int addr
)
506 val
= ioport_read(0, addr
);
507 LOG_IOPORT("inb : %04x %02x\n", addr
, val
);
510 env
->last_io_time
= cpu_get_time_fast();
515 int cpu_inw(CPUState
*env
, int addr
)
518 val
= ioport_read(1, addr
);
519 LOG_IOPORT("inw : %04x %04x\n", addr
, val
);
522 env
->last_io_time
= cpu_get_time_fast();
527 int cpu_inl(CPUState
*env
, int addr
)
530 val
= ioport_read(2, addr
);
531 LOG_IOPORT("inl : %04x %08x\n", addr
, val
);
534 env
->last_io_time
= cpu_get_time_fast();
539 /***********************************************************/
540 void hw_error(const char *fmt
, ...)
546 fprintf(stderr
, "qemu: hardware error: ");
547 vfprintf(stderr
, fmt
, ap
);
548 fprintf(stderr
, "\n");
549 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
550 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
552 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
554 cpu_dump_state(env
, stderr
, fprintf
, 0);
564 static QEMUBalloonEvent
*qemu_balloon_event
;
565 void *qemu_balloon_event_opaque
;
567 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
569 qemu_balloon_event
= func
;
570 qemu_balloon_event_opaque
= opaque
;
573 void qemu_balloon(ram_addr_t target
)
575 if (qemu_balloon_event
)
576 qemu_balloon_event(qemu_balloon_event_opaque
, target
);
579 ram_addr_t
qemu_balloon_status(void)
581 if (qemu_balloon_event
)
582 return qemu_balloon_event(qemu_balloon_event_opaque
, 0);
586 /***********************************************************/
589 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
590 static void *qemu_put_kbd_event_opaque
;
591 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
592 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
594 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
596 qemu_put_kbd_event_opaque
= opaque
;
597 qemu_put_kbd_event
= func
;
600 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
601 void *opaque
, int absolute
,
604 QEMUPutMouseEntry
*s
, *cursor
;
606 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
608 s
->qemu_put_mouse_event
= func
;
609 s
->qemu_put_mouse_event_opaque
= opaque
;
610 s
->qemu_put_mouse_event_absolute
= absolute
;
611 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
614 if (!qemu_put_mouse_event_head
) {
615 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
619 cursor
= qemu_put_mouse_event_head
;
620 while (cursor
->next
!= NULL
)
621 cursor
= cursor
->next
;
624 qemu_put_mouse_event_current
= s
;
629 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
631 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
633 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
636 cursor
= qemu_put_mouse_event_head
;
637 while (cursor
!= NULL
&& cursor
!= entry
) {
639 cursor
= cursor
->next
;
642 if (cursor
== NULL
) // does not exist or list empty
644 else if (prev
== NULL
) { // entry is head
645 qemu_put_mouse_event_head
= cursor
->next
;
646 if (qemu_put_mouse_event_current
== entry
)
647 qemu_put_mouse_event_current
= cursor
->next
;
648 qemu_free(entry
->qemu_put_mouse_event_name
);
653 prev
->next
= entry
->next
;
655 if (qemu_put_mouse_event_current
== entry
)
656 qemu_put_mouse_event_current
= prev
;
658 qemu_free(entry
->qemu_put_mouse_event_name
);
662 void kbd_put_keycode(int keycode
)
664 if (qemu_put_kbd_event
) {
665 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
669 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
671 QEMUPutMouseEvent
*mouse_event
;
672 void *mouse_event_opaque
;
675 if (!qemu_put_mouse_event_current
) {
680 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
682 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
685 if (graphic_rotate
) {
686 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
689 width
= graphic_width
- 1;
690 mouse_event(mouse_event_opaque
,
691 width
- dy
, dx
, dz
, buttons_state
);
693 mouse_event(mouse_event_opaque
,
694 dx
, dy
, dz
, buttons_state
);
698 int kbd_mouse_is_absolute(void)
700 if (!qemu_put_mouse_event_current
)
703 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
706 void do_info_mice(Monitor
*mon
)
708 QEMUPutMouseEntry
*cursor
;
711 if (!qemu_put_mouse_event_head
) {
712 monitor_printf(mon
, "No mouse devices connected\n");
716 monitor_printf(mon
, "Mouse devices available:\n");
717 cursor
= qemu_put_mouse_event_head
;
718 while (cursor
!= NULL
) {
719 monitor_printf(mon
, "%c Mouse #%d: %s\n",
720 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
721 index
, cursor
->qemu_put_mouse_event_name
);
723 cursor
= cursor
->next
;
727 void do_mouse_set(Monitor
*mon
, int index
)
729 QEMUPutMouseEntry
*cursor
;
732 if (!qemu_put_mouse_event_head
) {
733 monitor_printf(mon
, "No mouse devices connected\n");
737 cursor
= qemu_put_mouse_event_head
;
738 while (cursor
!= NULL
&& index
!= i
) {
740 cursor
= cursor
->next
;
744 qemu_put_mouse_event_current
= cursor
;
746 monitor_printf(mon
, "Mouse at given index not found\n");
749 /* compute with 96 bit intermediate result: (a*b)/c */
750 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
755 #ifdef WORDS_BIGENDIAN
765 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
766 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
769 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
773 /***********************************************************/
774 /* real time host monotonic timer */
776 #define QEMU_TIMER_BASE 1000000000LL
780 static int64_t clock_freq
;
782 static void init_get_clock(void)
786 ret
= QueryPerformanceFrequency(&freq
);
788 fprintf(stderr
, "Could not calibrate ticks\n");
791 clock_freq
= freq
.QuadPart
;
794 static int64_t get_clock(void)
797 QueryPerformanceCounter(&ti
);
798 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
803 static int use_rt_clock
;
805 static void init_get_clock(void)
808 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
809 || defined(__DragonFly__)
812 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
819 static int64_t get_clock(void)
821 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
822 || defined(__DragonFly__)
825 clock_gettime(CLOCK_MONOTONIC
, &ts
);
826 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
830 /* XXX: using gettimeofday leads to problems if the date
831 changes, so it should be avoided. */
833 gettimeofday(&tv
, NULL
);
834 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
839 /* Return the virtual CPU time, based on the instruction counter. */
840 static int64_t cpu_get_icount(void)
843 CPUState
*env
= cpu_single_env
;;
844 icount
= qemu_icount
;
847 fprintf(stderr
, "Bad clock read\n");
848 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
850 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
853 /***********************************************************/
854 /* guest cycle counter */
856 static int64_t cpu_ticks_prev
;
857 static int64_t cpu_ticks_offset
;
858 static int64_t cpu_clock_offset
;
859 static int cpu_ticks_enabled
;
861 /* return the host CPU cycle counter and handle stop/restart */
862 int64_t cpu_get_ticks(void)
865 return cpu_get_icount();
867 if (!cpu_ticks_enabled
) {
868 return cpu_ticks_offset
;
871 ticks
= cpu_get_real_ticks();
872 if (cpu_ticks_prev
> ticks
) {
873 /* Note: non increasing ticks may happen if the host uses
875 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
877 cpu_ticks_prev
= ticks
;
878 return ticks
+ cpu_ticks_offset
;
882 /* return the host CPU monotonic timer and handle stop/restart */
883 static int64_t cpu_get_clock(void)
886 if (!cpu_ticks_enabled
) {
887 return cpu_clock_offset
;
890 return ti
+ cpu_clock_offset
;
894 /* enable cpu_get_ticks() */
895 void cpu_enable_ticks(void)
897 if (!cpu_ticks_enabled
) {
898 cpu_ticks_offset
-= cpu_get_real_ticks();
899 cpu_clock_offset
-= get_clock();
900 cpu_ticks_enabled
= 1;
904 /* disable cpu_get_ticks() : the clock is stopped. You must not call
905 cpu_get_ticks() after that. */
906 void cpu_disable_ticks(void)
908 if (cpu_ticks_enabled
) {
909 cpu_ticks_offset
= cpu_get_ticks();
910 cpu_clock_offset
= cpu_get_clock();
911 cpu_ticks_enabled
= 0;
915 /***********************************************************/
918 #define QEMU_TIMER_REALTIME 0
919 #define QEMU_TIMER_VIRTUAL 1
923 /* XXX: add frequency */
931 struct QEMUTimer
*next
;
934 struct qemu_alarm_timer
{
938 int (*start
)(struct qemu_alarm_timer
*t
);
939 void (*stop
)(struct qemu_alarm_timer
*t
);
940 void (*rearm
)(struct qemu_alarm_timer
*t
);
944 #define ALARM_FLAG_DYNTICKS 0x1
945 #define ALARM_FLAG_EXPIRED 0x2
947 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
949 return t
&& (t
->flags
& ALARM_FLAG_DYNTICKS
);
952 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
954 if (!alarm_has_dynticks(t
))
960 /* TODO: MIN_TIMER_REARM_US should be optimized */
961 #define MIN_TIMER_REARM_US 250
963 static struct qemu_alarm_timer
*alarm_timer
;
967 struct qemu_alarm_win32
{
970 } alarm_win32_data
= {0, -1};
972 static int win32_start_timer(struct qemu_alarm_timer
*t
);
973 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
974 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
978 static int unix_start_timer(struct qemu_alarm_timer
*t
);
979 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
983 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
984 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
985 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
987 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
988 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
990 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
991 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
993 #endif /* __linux__ */
997 /* Correlation between real and virtual time is always going to be
998 fairly approximate, so ignore small variation.
999 When the guest is idle real and virtual time will be aligned in
1000 the IO wait loop. */
1001 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
1003 static void icount_adjust(void)
1008 static int64_t last_delta
;
1009 /* If the VM is not running, then do nothing. */
1013 cur_time
= cpu_get_clock();
1014 cur_icount
= qemu_get_clock(vm_clock
);
1015 delta
= cur_icount
- cur_time
;
1016 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1018 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
1019 && icount_time_shift
> 0) {
1020 /* The guest is getting too far ahead. Slow time down. */
1021 icount_time_shift
--;
1024 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
1025 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
1026 /* The guest is getting too far behind. Speed time up. */
1027 icount_time_shift
++;
1030 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
1033 static void icount_adjust_rt(void * opaque
)
1035 qemu_mod_timer(icount_rt_timer
,
1036 qemu_get_clock(rt_clock
) + 1000);
1040 static void icount_adjust_vm(void * opaque
)
1042 qemu_mod_timer(icount_vm_timer
,
1043 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1047 static void init_icount_adjust(void)
1049 /* Have both realtime and virtual time triggers for speed adjustment.
1050 The realtime trigger catches emulated time passing too slowly,
1051 the virtual time trigger catches emulated time passing too fast.
1052 Realtime triggers occur even when idle, so use them less frequently
1053 than VM triggers. */
1054 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
1055 qemu_mod_timer(icount_rt_timer
,
1056 qemu_get_clock(rt_clock
) + 1000);
1057 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
1058 qemu_mod_timer(icount_vm_timer
,
1059 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1062 static struct qemu_alarm_timer alarm_timers
[] = {
1065 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
1066 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
1067 /* HPET - if available - is preferred */
1068 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
1069 /* ...otherwise try RTC */
1070 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1072 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1074 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1075 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1076 {"win32", 0, win32_start_timer
,
1077 win32_stop_timer
, NULL
, &alarm_win32_data
},
1082 static void show_available_alarms(void)
1086 printf("Available alarm timers, in order of precedence:\n");
1087 for (i
= 0; alarm_timers
[i
].name
; i
++)
1088 printf("%s\n", alarm_timers
[i
].name
);
1091 static void configure_alarms(char const *opt
)
1095 int count
= ARRAY_SIZE(alarm_timers
) - 1;
1098 struct qemu_alarm_timer tmp
;
1100 if (!strcmp(opt
, "?")) {
1101 show_available_alarms();
1107 /* Reorder the array */
1108 name
= strtok(arg
, ",");
1110 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1111 if (!strcmp(alarm_timers
[i
].name
, name
))
1116 fprintf(stderr
, "Unknown clock %s\n", name
);
1125 tmp
= alarm_timers
[i
];
1126 alarm_timers
[i
] = alarm_timers
[cur
];
1127 alarm_timers
[cur
] = tmp
;
1131 name
= strtok(NULL
, ",");
1137 /* Disable remaining timers */
1138 for (i
= cur
; i
< count
; i
++)
1139 alarm_timers
[i
].name
= NULL
;
1141 show_available_alarms();
1146 QEMUClock
*rt_clock
;
1147 QEMUClock
*vm_clock
;
1149 static QEMUTimer
*active_timers
[2];
1151 static QEMUClock
*qemu_new_clock(int type
)
1154 clock
= qemu_mallocz(sizeof(QEMUClock
));
1159 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1163 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1166 ts
->opaque
= opaque
;
1170 void qemu_free_timer(QEMUTimer
*ts
)
1175 /* stop a timer, but do not dealloc it */
1176 void qemu_del_timer(QEMUTimer
*ts
)
1180 /* NOTE: this code must be signal safe because
1181 qemu_timer_expired() can be called from a signal. */
1182 pt
= &active_timers
[ts
->clock
->type
];
1195 /* modify the current timer so that it will be fired when current_time
1196 >= expire_time. The corresponding callback will be called. */
1197 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1203 /* add the timer in the sorted list */
1204 /* NOTE: this code must be signal safe because
1205 qemu_timer_expired() can be called from a signal. */
1206 pt
= &active_timers
[ts
->clock
->type
];
1211 if (t
->expire_time
> expire_time
)
1215 ts
->expire_time
= expire_time
;
1219 /* Rearm if necessary */
1220 if (pt
== &active_timers
[ts
->clock
->type
]) {
1221 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1222 qemu_rearm_alarm_timer(alarm_timer
);
1224 /* Interrupt execution to force deadline recalculation. */
1226 qemu_notify_event();
1230 int qemu_timer_pending(QEMUTimer
*ts
)
1233 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1240 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1244 return (timer_head
->expire_time
<= current_time
);
1247 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1253 if (!ts
|| ts
->expire_time
> current_time
)
1255 /* remove timer from the list before calling the callback */
1256 *ptimer_head
= ts
->next
;
1259 /* run the callback (the timer list can be modified) */
1264 int64_t qemu_get_clock(QEMUClock
*clock
)
1266 switch(clock
->type
) {
1267 case QEMU_TIMER_REALTIME
:
1268 return get_clock() / 1000000;
1270 case QEMU_TIMER_VIRTUAL
:
1272 return cpu_get_icount();
1274 return cpu_get_clock();
1279 static void init_timers(void)
1282 ticks_per_sec
= QEMU_TIMER_BASE
;
1283 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1284 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1288 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1290 uint64_t expire_time
;
1292 if (qemu_timer_pending(ts
)) {
1293 expire_time
= ts
->expire_time
;
1297 qemu_put_be64(f
, expire_time
);
1300 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1302 uint64_t expire_time
;
1304 expire_time
= qemu_get_be64(f
);
1305 if (expire_time
!= -1) {
1306 qemu_mod_timer(ts
, expire_time
);
1312 static void timer_save(QEMUFile
*f
, void *opaque
)
1314 if (cpu_ticks_enabled
) {
1315 hw_error("cannot save state if virtual timers are running");
1317 qemu_put_be64(f
, cpu_ticks_offset
);
1318 qemu_put_be64(f
, ticks_per_sec
);
1319 qemu_put_be64(f
, cpu_clock_offset
);
1322 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1324 if (version_id
!= 1 && version_id
!= 2)
1326 if (cpu_ticks_enabled
) {
1329 cpu_ticks_offset
=qemu_get_be64(f
);
1330 ticks_per_sec
=qemu_get_be64(f
);
1331 if (version_id
== 2) {
1332 cpu_clock_offset
=qemu_get_be64(f
);
1337 static void qemu_event_increment(void);
1340 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1341 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1344 static void host_alarm_handler(int host_signum
)
1348 #define DISP_FREQ 1000
1350 static int64_t delta_min
= INT64_MAX
;
1351 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1353 ti
= qemu_get_clock(vm_clock
);
1354 if (last_clock
!= 0) {
1355 delta
= ti
- last_clock
;
1356 if (delta
< delta_min
)
1358 if (delta
> delta_max
)
1361 if (++count
== DISP_FREQ
) {
1362 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1363 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1364 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1365 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1366 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1368 delta_min
= INT64_MAX
;
1376 if (alarm_has_dynticks(alarm_timer
) ||
1378 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1379 qemu_get_clock(vm_clock
))) ||
1380 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1381 qemu_get_clock(rt_clock
))) {
1382 qemu_event_increment();
1383 if (alarm_timer
) alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1385 #ifndef CONFIG_IOTHREAD
1387 /* stop the currently executing cpu because a timer occured */
1390 if (next_cpu
->kqemu_enabled
) {
1391 kqemu_cpu_interrupt(next_cpu
);
1396 timer_alarm_pending
= 1;
1397 qemu_notify_event();
1401 static int64_t qemu_next_deadline(void)
1405 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1406 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1407 qemu_get_clock(vm_clock
);
1409 /* To avoid problems with overflow limit this to 2^32. */
1419 #if defined(__linux__) || defined(_WIN32)
1420 static uint64_t qemu_next_deadline_dyntick(void)
1428 delta
= (qemu_next_deadline() + 999) / 1000;
1430 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1431 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1432 qemu_get_clock(rt_clock
))*1000;
1433 if (rtdelta
< delta
)
1437 if (delta
< MIN_TIMER_REARM_US
)
1438 delta
= MIN_TIMER_REARM_US
;
1446 /* Sets a specific flag */
1447 static int fcntl_setfl(int fd
, int flag
)
1451 flags
= fcntl(fd
, F_GETFL
);
1455 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1461 #if defined(__linux__)
1463 #define RTC_FREQ 1024
1465 static void enable_sigio_timer(int fd
)
1467 struct sigaction act
;
1470 sigfillset(&act
.sa_mask
);
1472 act
.sa_handler
= host_alarm_handler
;
1474 sigaction(SIGIO
, &act
, NULL
);
1475 fcntl_setfl(fd
, O_ASYNC
);
1476 fcntl(fd
, F_SETOWN
, getpid());
1479 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1481 struct hpet_info info
;
1484 fd
= open("/dev/hpet", O_RDONLY
);
1489 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1491 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1492 "error, but for better emulation accuracy type:\n"
1493 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1497 /* Check capabilities */
1498 r
= ioctl(fd
, HPET_INFO
, &info
);
1502 /* Enable periodic mode */
1503 r
= ioctl(fd
, HPET_EPI
, 0);
1504 if (info
.hi_flags
&& (r
< 0))
1507 /* Enable interrupt */
1508 r
= ioctl(fd
, HPET_IE_ON
, 0);
1512 enable_sigio_timer(fd
);
1513 t
->priv
= (void *)(long)fd
;
1521 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1523 int fd
= (long)t
->priv
;
1528 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1531 unsigned long current_rtc_freq
= 0;
1533 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1536 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1537 if (current_rtc_freq
!= RTC_FREQ
&&
1538 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1539 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1540 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1541 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1544 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1550 enable_sigio_timer(rtc_fd
);
1552 t
->priv
= (void *)(long)rtc_fd
;
1557 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1559 int rtc_fd
= (long)t
->priv
;
1564 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1568 struct sigaction act
;
1570 sigfillset(&act
.sa_mask
);
1572 act
.sa_handler
= host_alarm_handler
;
1574 sigaction(SIGALRM
, &act
, NULL
);
1577 * Initialize ev struct to 0 to avoid valgrind complaining
1578 * about uninitialized data in timer_create call
1580 memset(&ev
, 0, sizeof(ev
));
1581 ev
.sigev_value
.sival_int
= 0;
1582 ev
.sigev_notify
= SIGEV_SIGNAL
;
1583 ev
.sigev_signo
= SIGALRM
;
1585 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1586 perror("timer_create");
1588 /* disable dynticks */
1589 fprintf(stderr
, "Dynamic Ticks disabled\n");
1594 t
->priv
= (void *)(long)host_timer
;
1599 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1601 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1603 timer_delete(host_timer
);
1606 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1608 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1609 struct itimerspec timeout
;
1610 int64_t nearest_delta_us
= INT64_MAX
;
1613 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1614 !active_timers
[QEMU_TIMER_VIRTUAL
])
1617 nearest_delta_us
= qemu_next_deadline_dyntick();
1619 /* check whether a timer is already running */
1620 if (timer_gettime(host_timer
, &timeout
)) {
1622 fprintf(stderr
, "Internal timer error: aborting\n");
1625 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1626 if (current_us
&& current_us
<= nearest_delta_us
)
1629 timeout
.it_interval
.tv_sec
= 0;
1630 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1631 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1632 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1633 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1635 fprintf(stderr
, "Internal timer error: aborting\n");
1640 #endif /* defined(__linux__) */
1642 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1644 struct sigaction act
;
1645 struct itimerval itv
;
1649 sigfillset(&act
.sa_mask
);
1651 act
.sa_handler
= host_alarm_handler
;
1653 sigaction(SIGALRM
, &act
, NULL
);
1655 itv
.it_interval
.tv_sec
= 0;
1656 /* for i386 kernel 2.6 to get 1 ms */
1657 itv
.it_interval
.tv_usec
= 999;
1658 itv
.it_value
.tv_sec
= 0;
1659 itv
.it_value
.tv_usec
= 10 * 1000;
1661 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1668 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1670 struct itimerval itv
;
1672 memset(&itv
, 0, sizeof(itv
));
1673 setitimer(ITIMER_REAL
, &itv
, NULL
);
1676 #endif /* !defined(_WIN32) */
1681 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1684 struct qemu_alarm_win32
*data
= t
->priv
;
1687 memset(&tc
, 0, sizeof(tc
));
1688 timeGetDevCaps(&tc
, sizeof(tc
));
1690 if (data
->period
< tc
.wPeriodMin
)
1691 data
->period
= tc
.wPeriodMin
;
1693 timeBeginPeriod(data
->period
);
1695 flags
= TIME_CALLBACK_FUNCTION
;
1696 if (alarm_has_dynticks(t
))
1697 flags
|= TIME_ONESHOT
;
1699 flags
|= TIME_PERIODIC
;
1701 data
->timerId
= timeSetEvent(1, // interval (ms)
1702 data
->period
, // resolution
1703 host_alarm_handler
, // function
1704 (DWORD
)t
, // parameter
1707 if (!data
->timerId
) {
1708 perror("Failed to initialize win32 alarm timer");
1709 timeEndPeriod(data
->period
);
1716 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1718 struct qemu_alarm_win32
*data
= t
->priv
;
1720 timeKillEvent(data
->timerId
);
1721 timeEndPeriod(data
->period
);
1724 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1726 struct qemu_alarm_win32
*data
= t
->priv
;
1727 uint64_t nearest_delta_us
;
1729 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1730 !active_timers
[QEMU_TIMER_VIRTUAL
])
1733 nearest_delta_us
= qemu_next_deadline_dyntick();
1734 nearest_delta_us
/= 1000;
1736 timeKillEvent(data
->timerId
);
1738 data
->timerId
= timeSetEvent(1,
1742 TIME_ONESHOT
| TIME_PERIODIC
);
1744 if (!data
->timerId
) {
1745 perror("Failed to re-arm win32 alarm timer");
1747 timeEndPeriod(data
->period
);
1754 static int init_timer_alarm(void)
1756 struct qemu_alarm_timer
*t
= NULL
;
1759 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1760 t
= &alarm_timers
[i
];
1780 static void quit_timers(void)
1782 alarm_timer
->stop(alarm_timer
);
1786 /***********************************************************/
1787 /* host time/date access */
1788 void qemu_get_timedate(struct tm
*tm
, int offset
)
1795 if (rtc_date_offset
== -1) {
1799 ret
= localtime(&ti
);
1801 ti
-= rtc_date_offset
;
1805 memcpy(tm
, ret
, sizeof(struct tm
));
1808 int qemu_timedate_diff(struct tm
*tm
)
1812 if (rtc_date_offset
== -1)
1814 seconds
= mktimegm(tm
);
1816 seconds
= mktime(tm
);
1818 seconds
= mktimegm(tm
) + rtc_date_offset
;
1820 return seconds
- time(NULL
);
1824 static void socket_cleanup(void)
1829 static int socket_init(void)
1834 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1836 err
= WSAGetLastError();
1837 fprintf(stderr
, "WSAStartup: %d\n", err
);
1840 atexit(socket_cleanup
);
1845 int get_param_value(char *buf
, int buf_size
,
1846 const char *tag
, const char *str
)
1853 p
= get_opt_name(option
, sizeof(option
), p
, '=');
1857 if (!strcmp(tag
, option
)) {
1858 (void)get_opt_value(buf
, buf_size
, p
);
1861 p
= get_opt_value(NULL
, 0, p
);
1870 int check_params(const char * const *params
, const char *str
)
1872 int name_buf_size
= 1;
1878 for (i
= 0; params
[i
] != NULL
; i
++) {
1879 len
= strlen(params
[i
]) + 1;
1880 if (len
> name_buf_size
) {
1881 name_buf_size
= len
;
1884 name_buf
= qemu_malloc(name_buf_size
);
1887 while (*p
!= '\0') {
1888 p
= get_opt_name(name_buf
, name_buf_size
, p
, '=');
1894 for(i
= 0; params
[i
] != NULL
; i
++)
1895 if (!strcmp(params
[i
], name_buf
))
1897 if (params
[i
] == NULL
) {
1901 p
= get_opt_value(NULL
, 0, p
);
1907 qemu_free(name_buf
);
1911 /***********************************************************/
1912 /* Bluetooth support */
1915 static struct HCIInfo
*hci_table
[MAX_NICS
];
1917 static struct bt_vlan_s
{
1918 struct bt_scatternet_s net
;
1920 struct bt_vlan_s
*next
;
1923 /* find or alloc a new bluetooth "VLAN" */
1924 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1926 struct bt_vlan_s
**pvlan
, *vlan
;
1927 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1931 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1933 pvlan
= &first_bt_vlan
;
1934 while (*pvlan
!= NULL
)
1935 pvlan
= &(*pvlan
)->next
;
1940 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1944 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1949 static struct HCIInfo null_hci
= {
1950 .cmd_send
= null_hci_send
,
1951 .sco_send
= null_hci_send
,
1952 .acl_send
= null_hci_send
,
1953 .bdaddr_set
= null_hci_addr_set
,
1956 struct HCIInfo
*qemu_next_hci(void)
1958 if (cur_hci
== nb_hcis
)
1961 return hci_table
[cur_hci
++];
1964 static struct HCIInfo
*hci_init(const char *str
)
1967 struct bt_scatternet_s
*vlan
= 0;
1969 if (!strcmp(str
, "null"))
1972 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
1974 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
1975 else if (!strncmp(str
, "hci", 3)) {
1978 if (!strncmp(str
+ 3, ",vlan=", 6)) {
1979 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
1984 vlan
= qemu_find_bt_vlan(0);
1986 return bt_new_hci(vlan
);
1989 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
1994 static int bt_hci_parse(const char *str
)
1996 struct HCIInfo
*hci
;
1999 if (nb_hcis
>= MAX_NICS
) {
2000 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
2004 hci
= hci_init(str
);
2013 bdaddr
.b
[5] = 0x56 + nb_hcis
;
2014 hci
->bdaddr_set(hci
, bdaddr
.b
);
2016 hci_table
[nb_hcis
++] = hci
;
2021 static void bt_vhci_add(int vlan_id
)
2023 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
2026 fprintf(stderr
, "qemu: warning: adding a VHCI to "
2027 "an empty scatternet %i\n", vlan_id
);
2029 bt_vhci_init(bt_new_hci(vlan
));
2032 static struct bt_device_s
*bt_device_add(const char *opt
)
2034 struct bt_scatternet_s
*vlan
;
2036 char *endp
= strstr(opt
, ",vlan=");
2037 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
2040 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
2043 vlan_id
= strtol(endp
+ 6, &endp
, 0);
2045 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
2050 vlan
= qemu_find_bt_vlan(vlan_id
);
2053 fprintf(stderr
, "qemu: warning: adding a slave device to "
2054 "an empty scatternet %i\n", vlan_id
);
2056 if (!strcmp(devname
, "keyboard"))
2057 return bt_keyboard_init(vlan
);
2059 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
2063 static int bt_parse(const char *opt
)
2065 const char *endp
, *p
;
2068 if (strstart(opt
, "hci", &endp
)) {
2069 if (!*endp
|| *endp
== ',') {
2071 if (!strstart(endp
, ",vlan=", 0))
2074 return bt_hci_parse(opt
);
2076 } else if (strstart(opt
, "vhci", &endp
)) {
2077 if (!*endp
|| *endp
== ',') {
2079 if (strstart(endp
, ",vlan=", &p
)) {
2080 vlan
= strtol(p
, (char **) &endp
, 0);
2082 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
2086 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
2095 } else if (strstart(opt
, "device:", &endp
))
2096 return !bt_device_add(endp
);
2098 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
2102 /***********************************************************/
2103 /* QEMU Block devices */
2105 #define HD_ALIAS "index=%d,media=disk"
2106 #define CDROM_ALIAS "index=2,media=cdrom"
2107 #define FD_ALIAS "index=%d,if=floppy"
2108 #define PFLASH_ALIAS "if=pflash"
2109 #define MTD_ALIAS "if=mtd"
2110 #define SD_ALIAS "index=0,if=sd"
2112 static int drive_opt_get_free_idx(void)
2116 for (index
= 0; index
< MAX_DRIVES
; index
++)
2117 if (!drives_opt
[index
].used
) {
2118 drives_opt
[index
].used
= 1;
2125 static int drive_get_free_idx(void)
2129 for (index
= 0; index
< MAX_DRIVES
; index
++)
2130 if (!drives_table
[index
].used
) {
2131 drives_table
[index
].used
= 1;
2138 int drive_add(const char *file
, const char *fmt
, ...)
2141 int index
= drive_opt_get_free_idx();
2143 if (nb_drives_opt
>= MAX_DRIVES
|| index
== -1) {
2144 fprintf(stderr
, "qemu: too many drives\n");
2148 drives_opt
[index
].file
= file
;
2150 vsnprintf(drives_opt
[index
].opt
,
2151 sizeof(drives_opt
[0].opt
), fmt
, ap
);
2158 void drive_remove(int index
)
2160 drives_opt
[index
].used
= 0;
2164 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
2168 /* seek interface, bus and unit */
2170 for (index
= 0; index
< MAX_DRIVES
; index
++)
2171 if (drives_table
[index
].type
== type
&&
2172 drives_table
[index
].bus
== bus
&&
2173 drives_table
[index
].unit
== unit
&&
2174 drives_table
[index
].used
)
2180 int drive_get_max_bus(BlockInterfaceType type
)
2186 for (index
= 0; index
< nb_drives
; index
++) {
2187 if(drives_table
[index
].type
== type
&&
2188 drives_table
[index
].bus
> max_bus
)
2189 max_bus
= drives_table
[index
].bus
;
2194 const char *drive_get_serial(BlockDriverState
*bdrv
)
2198 for (index
= 0; index
< nb_drives
; index
++)
2199 if (drives_table
[index
].bdrv
== bdrv
)
2200 return drives_table
[index
].serial
;
2205 BlockInterfaceErrorAction
drive_get_onerror(BlockDriverState
*bdrv
)
2209 for (index
= 0; index
< nb_drives
; index
++)
2210 if (drives_table
[index
].bdrv
== bdrv
)
2211 return drives_table
[index
].onerror
;
2213 return BLOCK_ERR_STOP_ENOSPC
;
2216 static void bdrv_format_print(void *opaque
, const char *name
)
2218 fprintf(stderr
, " %s", name
);
2221 void drive_uninit(BlockDriverState
*bdrv
)
2225 for (i
= 0; i
< MAX_DRIVES
; i
++)
2226 if (drives_table
[i
].bdrv
== bdrv
) {
2227 drives_table
[i
].bdrv
= NULL
;
2228 drives_table
[i
].used
= 0;
2229 drive_remove(drives_table
[i
].drive_opt_idx
);
2235 int drive_init(struct drive_opt
*arg
, int snapshot
, void *opaque
)
2241 const char *mediastr
= "";
2242 BlockInterfaceType type
;
2243 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
2244 int bus_id
, unit_id
;
2245 int cyls
, heads
, secs
, translation
;
2246 BlockDriverState
*bdrv
;
2247 BlockDriver
*drv
= NULL
;
2248 QEMUMachine
*machine
= opaque
;
2252 int bdrv_flags
, onerror
;
2253 int drives_table_idx
;
2254 char *str
= arg
->opt
;
2255 static const char * const params
[] = { "bus", "unit", "if", "index",
2256 "cyls", "heads", "secs", "trans",
2257 "media", "snapshot", "file",
2258 "cache", "format", "serial", "werror",
2261 if (check_params(params
, str
) < 0) {
2262 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
2268 cyls
= heads
= secs
= 0;
2271 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2275 if (machine
->use_scsi
) {
2277 max_devs
= MAX_SCSI_DEVS
;
2278 pstrcpy(devname
, sizeof(devname
), "scsi");
2281 max_devs
= MAX_IDE_DEVS
;
2282 pstrcpy(devname
, sizeof(devname
), "ide");
2286 /* extract parameters */
2288 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
2289 bus_id
= strtol(buf
, NULL
, 0);
2291 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
2296 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
2297 unit_id
= strtol(buf
, NULL
, 0);
2299 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
2304 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
2305 pstrcpy(devname
, sizeof(devname
), buf
);
2306 if (!strcmp(buf
, "ide")) {
2308 max_devs
= MAX_IDE_DEVS
;
2309 } else if (!strcmp(buf
, "scsi")) {
2311 max_devs
= MAX_SCSI_DEVS
;
2312 } else if (!strcmp(buf
, "floppy")) {
2315 } else if (!strcmp(buf
, "pflash")) {
2318 } else if (!strcmp(buf
, "mtd")) {
2321 } else if (!strcmp(buf
, "sd")) {
2324 } else if (!strcmp(buf
, "virtio")) {
2327 } else if (!strcmp(buf
, "xen")) {
2331 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
2336 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
2337 index
= strtol(buf
, NULL
, 0);
2339 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
2344 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
2345 cyls
= strtol(buf
, NULL
, 0);
2348 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
2349 heads
= strtol(buf
, NULL
, 0);
2352 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
2353 secs
= strtol(buf
, NULL
, 0);
2356 if (cyls
|| heads
|| secs
) {
2357 if (cyls
< 1 || cyls
> 16383) {
2358 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
2361 if (heads
< 1 || heads
> 16) {
2362 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
2365 if (secs
< 1 || secs
> 63) {
2366 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
2371 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
2374 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2378 if (!strcmp(buf
, "none"))
2379 translation
= BIOS_ATA_TRANSLATION_NONE
;
2380 else if (!strcmp(buf
, "lba"))
2381 translation
= BIOS_ATA_TRANSLATION_LBA
;
2382 else if (!strcmp(buf
, "auto"))
2383 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2385 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
2390 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
2391 if (!strcmp(buf
, "disk")) {
2393 } else if (!strcmp(buf
, "cdrom")) {
2394 if (cyls
|| secs
|| heads
) {
2396 "qemu: '%s' invalid physical CHS format\n", str
);
2399 media
= MEDIA_CDROM
;
2401 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
2406 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
2407 if (!strcmp(buf
, "on"))
2409 else if (!strcmp(buf
, "off"))
2412 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
2417 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
2418 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2420 else if (!strcmp(buf
, "writethrough"))
2422 else if (!strcmp(buf
, "writeback"))
2425 fprintf(stderr
, "qemu: invalid cache option\n");
2430 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
2431 if (strcmp(buf
, "?") == 0) {
2432 fprintf(stderr
, "qemu: Supported formats:");
2433 bdrv_iterate_format(bdrv_format_print
, NULL
);
2434 fprintf(stderr
, "\n");
2437 drv
= bdrv_find_format(buf
);
2439 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2444 if (get_param_value(buf
, sizeof(buf
), "boot", str
)) {
2445 if (!strcmp(buf
, "on")) {
2446 if (extboot_drive
!= -1) {
2447 fprintf(stderr
, "qemu: two bootable drives specified\n");
2450 extboot_drive
= nb_drives
;
2451 } else if (strcmp(buf
, "off")) {
2452 fprintf(stderr
, "qemu: '%s' invalid boot option\n", str
);
2457 if (arg
->file
== NULL
)
2458 get_param_value(file
, sizeof(file
), "file", str
);
2460 pstrcpy(file
, sizeof(file
), arg
->file
);
2462 if (!get_param_value(serial
, sizeof(serial
), "serial", str
))
2463 memset(serial
, 0, sizeof(serial
));
2465 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2466 if (get_param_value(buf
, sizeof(serial
), "werror", str
)) {
2467 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2468 fprintf(stderr
, "werror is no supported by this format\n");
2471 if (!strcmp(buf
, "ignore"))
2472 onerror
= BLOCK_ERR_IGNORE
;
2473 else if (!strcmp(buf
, "enospc"))
2474 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2475 else if (!strcmp(buf
, "stop"))
2476 onerror
= BLOCK_ERR_STOP_ANY
;
2477 else if (!strcmp(buf
, "report"))
2478 onerror
= BLOCK_ERR_REPORT
;
2480 fprintf(stderr
, "qemu: '%s' invalid write error action\n", buf
);
2485 /* compute bus and unit according index */
2488 if (bus_id
!= 0 || unit_id
!= -1) {
2490 "qemu: '%s' index cannot be used with bus and unit\n", str
);
2498 unit_id
= index
% max_devs
;
2499 bus_id
= index
/ max_devs
;
2503 /* if user doesn't specify a unit_id,
2504 * try to find the first free
2507 if (unit_id
== -1) {
2509 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
2511 if (max_devs
&& unit_id
>= max_devs
) {
2512 unit_id
-= max_devs
;
2520 if (max_devs
&& unit_id
>= max_devs
) {
2521 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
2522 str
, unit_id
, max_devs
- 1);
2527 * ignore multiple definitions
2530 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
2535 if (type
== IF_IDE
|| type
== IF_SCSI
)
2536 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2538 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
2539 devname
, bus_id
, mediastr
, unit_id
);
2541 snprintf(buf
, sizeof(buf
), "%s%s%i",
2542 devname
, mediastr
, unit_id
);
2543 bdrv
= bdrv_new(buf
);
2544 drives_table_idx
= drive_get_free_idx();
2545 drives_table
[drives_table_idx
].bdrv
= bdrv
;
2546 drives_table
[drives_table_idx
].type
= type
;
2547 drives_table
[drives_table_idx
].bus
= bus_id
;
2548 drives_table
[drives_table_idx
].unit
= unit_id
;
2549 drives_table
[drives_table_idx
].onerror
= onerror
;
2550 drives_table
[drives_table_idx
].drive_opt_idx
= arg
- drives_opt
;
2551 strncpy(drives_table
[drives_table_idx
].serial
, serial
, sizeof(serial
));
2561 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
2562 bdrv_set_translation_hint(bdrv
, translation
);
2566 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
2571 /* FIXME: This isn't really a floppy, but it's a reasonable
2574 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
2587 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2588 cache
= 2; /* always use write-back with snapshot */
2590 if (cache
== 0) /* no caching */
2591 bdrv_flags
|= BDRV_O_NOCACHE
;
2592 else if (cache
== 2) /* write-back */
2593 bdrv_flags
|= BDRV_O_CACHE_WB
;
2594 else if (cache
== 3) /* not specified */
2595 bdrv_flags
|= BDRV_O_CACHE_DEF
;
2596 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0) {
2597 fprintf(stderr
, "qemu: could not open disk image %s\n",
2601 if (bdrv_key_required(bdrv
))
2603 return drives_table_idx
;
2606 static void numa_add(const char *optarg
)
2610 unsigned long long value
, endvalue
;
2613 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2614 if (!strcmp(option
, "node")) {
2615 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2616 nodenr
= nb_numa_nodes
;
2618 nodenr
= strtoull(option
, NULL
, 10);
2621 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2622 node_mem
[nodenr
] = 0;
2624 value
= strtoull(option
, &endptr
, 0);
2626 case 0: case 'M': case 'm':
2633 node_mem
[nodenr
] = value
;
2635 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2636 node_cpumask
[nodenr
] = 0;
2638 value
= strtoull(option
, &endptr
, 10);
2641 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2643 if (*endptr
== '-') {
2644 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2645 if (endvalue
>= 63) {
2648 "only 63 CPUs in NUMA mode supported.\n");
2650 value
= (1 << (endvalue
+ 1)) - (1 << value
);
2655 node_cpumask
[nodenr
] = value
;
2662 /***********************************************************/
2665 static USBPort
*used_usb_ports
;
2666 static USBPort
*free_usb_ports
;
2668 /* ??? Maybe change this to register a hub to keep track of the topology. */
2669 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
2670 usb_attachfn attach
)
2672 port
->opaque
= opaque
;
2673 port
->index
= index
;
2674 port
->attach
= attach
;
2675 port
->next
= free_usb_ports
;
2676 free_usb_ports
= port
;
2679 int usb_device_add_dev(USBDevice
*dev
)
2683 /* Find a USB port to add the device to. */
2684 port
= free_usb_ports
;
2688 /* Create a new hub and chain it on. */
2689 free_usb_ports
= NULL
;
2690 port
->next
= used_usb_ports
;
2691 used_usb_ports
= port
;
2693 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
2694 usb_attach(port
, hub
);
2695 port
= free_usb_ports
;
2698 free_usb_ports
= port
->next
;
2699 port
->next
= used_usb_ports
;
2700 used_usb_ports
= port
;
2701 usb_attach(port
, dev
);
2705 static void usb_msd_password_cb(void *opaque
, int err
)
2707 USBDevice
*dev
= opaque
;
2710 usb_device_add_dev(dev
);
2712 dev
->handle_destroy(dev
);
2715 static int usb_device_add(const char *devname
, int is_hotplug
)
2720 if (!free_usb_ports
)
2723 if (strstart(devname
, "host:", &p
)) {
2724 dev
= usb_host_device_open(p
);
2725 } else if (!strcmp(devname
, "mouse")) {
2726 dev
= usb_mouse_init();
2727 } else if (!strcmp(devname
, "tablet")) {
2728 dev
= usb_tablet_init();
2729 } else if (!strcmp(devname
, "keyboard")) {
2730 dev
= usb_keyboard_init();
2731 } else if (strstart(devname
, "disk:", &p
)) {
2732 BlockDriverState
*bs
;
2734 dev
= usb_msd_init(p
);
2737 bs
= usb_msd_get_bdrv(dev
);
2738 if (bdrv_key_required(bs
)) {
2741 monitor_read_bdrv_key_start(cur_mon
, bs
, usb_msd_password_cb
,
2746 } else if (!strcmp(devname
, "wacom-tablet")) {
2747 dev
= usb_wacom_init();
2748 } else if (strstart(devname
, "serial:", &p
)) {
2749 dev
= usb_serial_init(p
);
2750 #ifdef CONFIG_BRLAPI
2751 } else if (!strcmp(devname
, "braille")) {
2752 dev
= usb_baum_init();
2754 } else if (strstart(devname
, "net:", &p
)) {
2757 if (net_client_init("nic", p
) < 0)
2759 nd_table
[nic
].model
= "usb";
2760 dev
= usb_net_init(&nd_table
[nic
]);
2761 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2762 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2763 bt_new_hci(qemu_find_bt_vlan(0)));
2770 return usb_device_add_dev(dev
);
2773 int usb_device_del_addr(int bus_num
, int addr
)
2779 if (!used_usb_ports
)
2785 lastp
= &used_usb_ports
;
2786 port
= used_usb_ports
;
2787 while (port
&& port
->dev
->addr
!= addr
) {
2788 lastp
= &port
->next
;
2796 *lastp
= port
->next
;
2797 usb_attach(port
, NULL
);
2798 dev
->handle_destroy(dev
);
2799 port
->next
= free_usb_ports
;
2800 free_usb_ports
= port
;
2804 static int usb_device_del(const char *devname
)
2809 if (strstart(devname
, "host:", &p
))
2810 return usb_host_device_close(p
);
2812 if (!used_usb_ports
)
2815 p
= strchr(devname
, '.');
2818 bus_num
= strtoul(devname
, NULL
, 0);
2819 addr
= strtoul(p
+ 1, NULL
, 0);
2821 return usb_device_del_addr(bus_num
, addr
);
2824 void do_usb_add(Monitor
*mon
, const char *devname
)
2826 usb_device_add(devname
, 1);
2829 void do_usb_del(Monitor
*mon
, const char *devname
)
2831 usb_device_del(devname
);
2834 void usb_info(Monitor
*mon
)
2838 const char *speed_str
;
2841 monitor_printf(mon
, "USB support not enabled\n");
2845 for (port
= used_usb_ports
; port
; port
= port
->next
) {
2849 switch(dev
->speed
) {
2853 case USB_SPEED_FULL
:
2856 case USB_SPEED_HIGH
:
2863 monitor_printf(mon
, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2864 0, dev
->addr
, speed_str
, dev
->devname
);
2868 /***********************************************************/
2869 /* PCMCIA/Cardbus */
2871 static struct pcmcia_socket_entry_s
{
2872 PCMCIASocket
*socket
;
2873 struct pcmcia_socket_entry_s
*next
;
2874 } *pcmcia_sockets
= 0;
2876 void pcmcia_socket_register(PCMCIASocket
*socket
)
2878 struct pcmcia_socket_entry_s
*entry
;
2880 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2881 entry
->socket
= socket
;
2882 entry
->next
= pcmcia_sockets
;
2883 pcmcia_sockets
= entry
;
2886 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2888 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2890 ptr
= &pcmcia_sockets
;
2891 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2892 if (entry
->socket
== socket
) {
2898 void pcmcia_info(Monitor
*mon
)
2900 struct pcmcia_socket_entry_s
*iter
;
2902 if (!pcmcia_sockets
)
2903 monitor_printf(mon
, "No PCMCIA sockets\n");
2905 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2906 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2907 iter
->socket
->attached
? iter
->socket
->card_string
:
2911 /***********************************************************/
2912 /* register display */
2914 struct DisplayAllocator default_allocator
= {
2915 defaultallocator_create_displaysurface
,
2916 defaultallocator_resize_displaysurface
,
2917 defaultallocator_free_displaysurface
2920 void register_displaystate(DisplayState
*ds
)
2930 DisplayState
*get_displaystate(void)
2932 return display_state
;
2935 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
2937 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
2938 return ds
->allocator
;
2943 static void dumb_display_init(void)
2945 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
2946 ds
->allocator
= &default_allocator
;
2947 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
2948 register_displaystate(ds
);
2951 /***********************************************************/
2954 typedef struct IOHandlerRecord
{
2956 IOCanRWHandler
*fd_read_poll
;
2958 IOHandler
*fd_write
;
2961 /* temporary data */
2963 struct IOHandlerRecord
*next
;
2966 static IOHandlerRecord
*first_io_handler
;
2968 /* XXX: fd_read_poll should be suppressed, but an API change is
2969 necessary in the character devices to suppress fd_can_read(). */
2970 int qemu_set_fd_handler2(int fd
,
2971 IOCanRWHandler
*fd_read_poll
,
2973 IOHandler
*fd_write
,
2976 IOHandlerRecord
**pioh
, *ioh
;
2978 if (!fd_read
&& !fd_write
) {
2979 pioh
= &first_io_handler
;
2984 if (ioh
->fd
== fd
) {
2991 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
2995 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
2996 ioh
->next
= first_io_handler
;
2997 first_io_handler
= ioh
;
3000 ioh
->fd_read_poll
= fd_read_poll
;
3001 ioh
->fd_read
= fd_read
;
3002 ioh
->fd_write
= fd_write
;
3003 ioh
->opaque
= opaque
;
3006 qemu_notify_event();
3010 int qemu_set_fd_handler(int fd
,
3012 IOHandler
*fd_write
,
3015 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
3019 /***********************************************************/
3020 /* Polling handling */
3022 typedef struct PollingEntry
{
3025 struct PollingEntry
*next
;
3028 static PollingEntry
*first_polling_entry
;
3030 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
3032 PollingEntry
**ppe
, *pe
;
3033 pe
= qemu_mallocz(sizeof(PollingEntry
));
3035 pe
->opaque
= opaque
;
3036 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
3041 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
3043 PollingEntry
**ppe
, *pe
;
3044 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
3046 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
3054 /***********************************************************/
3055 /* Wait objects support */
3056 typedef struct WaitObjects
{
3058 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
3059 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
3060 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
3063 static WaitObjects wait_objects
= {0};
3065 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
3067 WaitObjects
*w
= &wait_objects
;
3069 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
3071 w
->events
[w
->num
] = handle
;
3072 w
->func
[w
->num
] = func
;
3073 w
->opaque
[w
->num
] = opaque
;
3078 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
3081 WaitObjects
*w
= &wait_objects
;
3084 for (i
= 0; i
< w
->num
; i
++) {
3085 if (w
->events
[i
] == handle
)
3088 w
->events
[i
] = w
->events
[i
+ 1];
3089 w
->func
[i
] = w
->func
[i
+ 1];
3090 w
->opaque
[i
] = w
->opaque
[i
+ 1];
3098 /***********************************************************/
3099 /* ram save/restore */
3101 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
3105 v
= qemu_get_byte(f
);
3108 if (qemu_get_buffer(f
, buf
, len
) != len
)
3112 v
= qemu_get_byte(f
);
3113 memset(buf
, v
, len
);
3119 if (qemu_file_has_error(f
))
3125 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
3130 if (qemu_get_be32(f
) != last_ram_offset
)
3132 for(i
= 0; i
< last_ram_offset
; i
+= TARGET_PAGE_SIZE
) {
3133 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3135 ret
= ram_get_page(f
, qemu_get_ram_ptr(i
), TARGET_PAGE_SIZE
);
3142 #define BDRV_HASH_BLOCK_SIZE 1024
3143 #define IOBUF_SIZE 4096
3144 #define RAM_CBLOCK_MAGIC 0xfabe
3146 typedef struct RamDecompressState
{
3149 uint8_t buf
[IOBUF_SIZE
];
3150 } RamDecompressState
;
3152 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
3155 memset(s
, 0, sizeof(*s
));
3157 ret
= inflateInit(&s
->zstream
);
3163 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
3167 s
->zstream
.avail_out
= len
;
3168 s
->zstream
.next_out
= buf
;
3169 while (s
->zstream
.avail_out
> 0) {
3170 if (s
->zstream
.avail_in
== 0) {
3171 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
3173 clen
= qemu_get_be16(s
->f
);
3174 if (clen
> IOBUF_SIZE
)
3176 qemu_get_buffer(s
->f
, s
->buf
, clen
);
3177 s
->zstream
.avail_in
= clen
;
3178 s
->zstream
.next_in
= s
->buf
;
3180 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
3181 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
3188 static void ram_decompress_close(RamDecompressState
*s
)
3190 inflateEnd(&s
->zstream
);
3193 #define RAM_SAVE_FLAG_FULL 0x01
3194 #define RAM_SAVE_FLAG_COMPRESS 0x02
3195 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3196 #define RAM_SAVE_FLAG_PAGE 0x08
3197 #define RAM_SAVE_FLAG_EOS 0x10
3199 static int is_dup_page(uint8_t *page
, uint8_t ch
)
3201 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
3202 uint32_t *array
= (uint32_t *)page
;
3205 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
3206 if (array
[i
] != val
)
3213 static int ram_save_block(QEMUFile
*f
)
3215 static ram_addr_t current_addr
= 0;
3216 ram_addr_t saved_addr
= current_addr
;
3217 ram_addr_t addr
= 0;
3220 while (addr
< last_ram_offset
) {
3221 if (kvm_enabled() && current_addr
== 0) {
3223 r
= kvm_update_dirty_pages_log();
3225 fprintf(stderr
, "%s: update dirty pages log failed %d\n", __FUNCTION__
, r
);
3226 qemu_file_set_error(f
);
3230 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
3233 cpu_physical_memory_reset_dirty(current_addr
,
3234 current_addr
+ TARGET_PAGE_SIZE
,
3235 MIGRATION_DIRTY_FLAG
);
3237 p
= qemu_get_ram_ptr(current_addr
);
3239 if (is_dup_page(p
, *p
)) {
3240 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
3241 qemu_put_byte(f
, *p
);
3243 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
3244 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
3250 addr
+= TARGET_PAGE_SIZE
;
3251 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
3257 static ram_addr_t ram_save_threshold
= 10;
3258 static uint64_t bytes_transferred
= 0;
3260 static ram_addr_t
ram_save_remaining(void)
3263 ram_addr_t count
= 0;
3265 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3266 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3273 uint64_t ram_bytes_remaining(void)
3275 return ram_save_remaining() * TARGET_PAGE_SIZE
;
3278 uint64_t ram_bytes_transferred(void)
3280 return bytes_transferred
;
3283 uint64_t ram_bytes_total(void)
3285 return last_ram_offset
;
3288 static int ram_save_live(QEMUFile
*f
, int stage
, void *opaque
)
3292 if (cpu_physical_sync_dirty_bitmap(0, last_ram_offset
) != 0) {
3293 qemu_file_set_error(f
);
3298 /* Make sure all dirty bits are set */
3299 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3300 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3301 cpu_physical_memory_set_dirty(addr
);
3304 /* Enable dirty memory tracking */
3305 cpu_physical_memory_set_dirty_tracking(1);
3307 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
3310 while (!qemu_file_rate_limit(f
)) {
3313 ret
= ram_save_block(f
);
3314 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
3315 if (ret
== 0) /* no more blocks */
3319 /* try transferring iterative blocks of memory */
3323 /* flush all remaining blocks regardless of rate limiting */
3324 while (ram_save_block(f
) != 0) {
3325 bytes_transferred
+= TARGET_PAGE_SIZE
;
3327 cpu_physical_memory_set_dirty_tracking(0);
3330 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3332 return (stage
== 2) && (ram_save_remaining() < ram_save_threshold
);
3335 static int ram_load_dead(QEMUFile
*f
, void *opaque
)
3337 RamDecompressState s1
, *s
= &s1
;
3341 if (ram_decompress_open(s
, f
) < 0)
3343 for(i
= 0; i
< last_ram_offset
; i
+= BDRV_HASH_BLOCK_SIZE
) {
3344 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3346 if (ram_decompress_buf(s
, buf
, 1) < 0) {
3347 fprintf(stderr
, "Error while reading ram block header\n");
3351 if (ram_decompress_buf(s
, qemu_get_ram_ptr(i
),
3352 BDRV_HASH_BLOCK_SIZE
) < 0) {
3353 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
3358 printf("Error block header\n");
3362 ram_decompress_close(s
);
3367 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
3372 if (version_id
== 1)
3373 return ram_load_v1(f
, opaque
);
3375 if (version_id
== 2) {
3376 if (qemu_get_be32(f
) != last_ram_offset
)
3378 return ram_load_dead(f
, opaque
);
3381 if (version_id
!= 3)
3385 addr
= qemu_get_be64(f
);
3387 flags
= addr
& ~TARGET_PAGE_MASK
;
3388 addr
&= TARGET_PAGE_MASK
;
3390 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
3391 if (addr
!= last_ram_offset
)
3395 if (flags
& RAM_SAVE_FLAG_FULL
) {
3396 if (ram_load_dead(f
, opaque
) < 0)
3400 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
3401 uint8_t ch
= qemu_get_byte(f
);
3402 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
3403 } else if (flags
& RAM_SAVE_FLAG_PAGE
)
3404 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
3405 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
3410 void qemu_service_io(void)
3412 qemu_notify_event();
3415 /***********************************************************/
3416 /* bottom halves (can be seen as timers which expire ASAP) */
3427 static QEMUBH
*first_bh
= NULL
;
3429 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
3432 bh
= qemu_mallocz(sizeof(QEMUBH
));
3434 bh
->opaque
= opaque
;
3435 bh
->next
= first_bh
;
3440 int qemu_bh_poll(void)
3446 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3447 if (!bh
->deleted
&& bh
->scheduled
) {
3456 /* remove deleted bhs */
3470 void qemu_bh_schedule_idle(QEMUBH
*bh
)
3478 void qemu_bh_schedule(QEMUBH
*bh
)
3484 /* stop the currently executing CPU to execute the BH ASAP */
3485 qemu_notify_event();
3488 void qemu_bh_cancel(QEMUBH
*bh
)
3493 void qemu_bh_delete(QEMUBH
*bh
)
3499 static void qemu_bh_update_timeout(int *timeout
)
3503 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3504 if (!bh
->deleted
&& bh
->scheduled
) {
3506 /* idle bottom halves will be polled at least
3508 *timeout
= MIN(10, *timeout
);
3510 /* non-idle bottom halves will be executed
3519 /***********************************************************/
3520 /* machine registration */
3522 static QEMUMachine
*first_machine
= NULL
;
3523 QEMUMachine
*current_machine
= NULL
;
3525 int qemu_register_machine(QEMUMachine
*m
)
3528 pm
= &first_machine
;
3536 static QEMUMachine
*find_machine(const char *name
)
3540 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3541 if (!strcmp(m
->name
, name
))
3547 static QEMUMachine
*find_default_machine(void)
3551 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3552 if (m
->is_default
) {
3559 /***********************************************************/
3560 /* main execution loop */
3562 static void gui_update(void *opaque
)
3564 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3565 DisplayState
*ds
= opaque
;
3566 DisplayChangeListener
*dcl
= ds
->listeners
;
3570 while (dcl
!= NULL
) {
3571 if (dcl
->gui_timer_interval
&&
3572 dcl
->gui_timer_interval
< interval
)
3573 interval
= dcl
->gui_timer_interval
;
3576 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3579 static void nographic_update(void *opaque
)
3581 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3583 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3586 struct vm_change_state_entry
{
3587 VMChangeStateHandler
*cb
;
3589 LIST_ENTRY (vm_change_state_entry
) entries
;
3592 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3594 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3597 VMChangeStateEntry
*e
;
3599 e
= qemu_mallocz(sizeof (*e
));
3603 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3607 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3609 LIST_REMOVE (e
, entries
);
3613 static void vm_state_notify(int running
, int reason
)
3615 VMChangeStateEntry
*e
;
3617 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3618 e
->cb(e
->opaque
, running
, reason
);
3622 static void resume_all_vcpus(void);
3623 static void pause_all_vcpus(void);
3630 vm_state_notify(1, 0);
3631 qemu_rearm_alarm_timer(alarm_timer
);
3636 /* reset/shutdown handler */
3638 typedef struct QEMUResetEntry
{
3639 QEMUResetHandler
*func
;
3642 struct QEMUResetEntry
*next
;
3645 static QEMUResetEntry
*first_reset_entry
;
3646 static int reset_requested
;
3647 static int shutdown_requested
;
3648 static int powerdown_requested
;
3649 static int debug_requested
;
3650 static int vmstop_requested
;
3652 int qemu_no_shutdown(void)
3654 int r
= no_shutdown
;
3659 int qemu_shutdown_requested(void)
3661 int r
= shutdown_requested
;
3662 shutdown_requested
= 0;
3666 int qemu_reset_requested(void)
3668 int r
= reset_requested
;
3669 reset_requested
= 0;
3673 int qemu_powerdown_requested(void)
3675 int r
= powerdown_requested
;
3676 powerdown_requested
= 0;
3680 static int qemu_debug_requested(void)
3682 int r
= debug_requested
;
3683 debug_requested
= 0;
3687 static int qemu_vmstop_requested(void)
3689 int r
= vmstop_requested
;
3690 vmstop_requested
= 0;
3694 static void do_vm_stop(int reason
)
3697 cpu_disable_ticks();
3700 vm_state_notify(0, reason
);
3704 void qemu_register_reset(QEMUResetHandler
*func
, int order
, void *opaque
)
3706 QEMUResetEntry
**pre
, *re
;
3708 pre
= &first_reset_entry
;
3709 while (*pre
!= NULL
&& (*pre
)->order
>= order
) {
3710 pre
= &(*pre
)->next
;
3712 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3714 re
->opaque
= opaque
;
3720 void qemu_system_reset(void)
3724 /* reset all devices */
3725 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
3726 re
->func(re
->opaque
);
3730 void qemu_system_reset_request(void)
3733 shutdown_requested
= 1;
3735 reset_requested
= 1;
3737 if (cpu_single_env
) {
3738 qemu_kvm_cpu_stop(cpu_single_env
);
3739 cpu_exit(cpu_single_env
);
3741 qemu_notify_event();
3744 void qemu_system_shutdown_request(void)
3746 shutdown_requested
= 1;
3747 qemu_notify_event();
3750 void qemu_system_powerdown_request(void)
3752 powerdown_requested
= 1;
3753 qemu_notify_event();
3756 #ifdef CONFIG_IOTHREAD
3757 static void qemu_system_vmstop_request(int reason
)
3759 vmstop_requested
= reason
;
3760 qemu_notify_event();
3765 static int io_thread_fd
= -1;
3767 static void qemu_event_increment(void)
3769 static const char byte
= 0;
3771 if (io_thread_fd
== -1)
3774 write(io_thread_fd
, &byte
, sizeof(byte
));
3777 static void qemu_event_read(void *opaque
)
3779 int fd
= (unsigned long)opaque
;
3782 /* Drain the notify pipe */
3785 len
= read(fd
, buffer
, sizeof(buffer
));
3786 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
3789 static int qemu_event_init(void)
3798 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3802 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3806 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3807 (void *)(unsigned long)fds
[0]);
3809 io_thread_fd
= fds
[1];
3818 HANDLE qemu_event_handle
;
3820 static void dummy_event_handler(void *opaque
)
3824 static int qemu_event_init(void)
3826 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3827 if (!qemu_event_handle
) {
3828 perror("Failed CreateEvent");
3831 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3835 static void qemu_event_increment(void)
3837 SetEvent(qemu_event_handle
);
3841 static int cpu_can_run(CPUState
*env
)
3850 #ifndef CONFIG_IOTHREAD
3851 static int qemu_init_main_loop(void)
3853 return qemu_event_init();
3856 void qemu_init_vcpu(void *_env
)
3858 CPUState
*env
= _env
;
3865 int qemu_cpu_self(void *env
)
3870 static void resume_all_vcpus(void)
3874 static void pause_all_vcpus(void)
3878 void qemu_cpu_kick(void *env
)
3883 void qemu_notify_event(void)
3885 CPUState
*env
= cpu_single_env
;
3887 if (kvm_enabled()) {
3888 qemu_kvm_notify_work();
3894 if (env
->kqemu_enabled
)
3895 kqemu_cpu_interrupt(env
);
3900 #define qemu_mutex_lock_iothread() do { } while (0)
3901 #define qemu_mutex_unlock_iothread() do { } while (0)
3903 void vm_stop(int reason
)
3908 #else /* CONFIG_IOTHREAD */
3910 #include "qemu-thread.h"
3912 QemuMutex qemu_global_mutex
;
3913 static QemuMutex qemu_fair_mutex
;
3915 static QemuThread io_thread
;
3917 static QemuThread
*tcg_cpu_thread
;
3918 static QemuCond
*tcg_halt_cond
;
3920 static int qemu_system_ready
;
3922 static QemuCond qemu_cpu_cond
;
3924 static QemuCond qemu_system_cond
;
3925 static QemuCond qemu_pause_cond
;
3927 static void block_io_signals(void);
3928 static void unblock_io_signals(void);
3929 static int tcg_has_work(void);
3931 static int qemu_init_main_loop(void)
3935 ret
= qemu_event_init();
3939 qemu_cond_init(&qemu_pause_cond
);
3940 qemu_mutex_init(&qemu_fair_mutex
);
3941 qemu_mutex_init(&qemu_global_mutex
);
3942 qemu_mutex_lock(&qemu_global_mutex
);
3944 unblock_io_signals();
3945 qemu_thread_self(&io_thread
);
3950 static void qemu_wait_io_event(CPUState
*env
)
3952 while (!tcg_has_work())
3953 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3955 qemu_mutex_unlock(&qemu_global_mutex
);
3958 * Users of qemu_global_mutex can be starved, having no chance
3959 * to acquire it since this path will get to it first.
3960 * So use another lock to provide fairness.
3962 qemu_mutex_lock(&qemu_fair_mutex
);
3963 qemu_mutex_unlock(&qemu_fair_mutex
);
3965 qemu_mutex_lock(&qemu_global_mutex
);
3969 qemu_cond_signal(&qemu_pause_cond
);
3973 static int qemu_cpu_exec(CPUState
*env
);
3975 static void *kvm_cpu_thread_fn(void *arg
)
3977 CPUState
*env
= arg
;
3980 qemu_thread_self(env
->thread
);
3982 /* signal CPU creation */
3983 qemu_mutex_lock(&qemu_global_mutex
);
3985 qemu_cond_signal(&qemu_cpu_cond
);
3987 /* and wait for machine initialization */
3988 while (!qemu_system_ready
)
3989 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3992 if (cpu_can_run(env
))
3994 qemu_wait_io_event(env
);
4000 static void tcg_cpu_exec(void);
4002 static void *tcg_cpu_thread_fn(void *arg
)
4004 CPUState
*env
= arg
;
4007 qemu_thread_self(env
->thread
);
4009 /* signal CPU creation */
4010 qemu_mutex_lock(&qemu_global_mutex
);
4011 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4013 qemu_cond_signal(&qemu_cpu_cond
);
4015 /* and wait for machine initialization */
4016 while (!qemu_system_ready
)
4017 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
4021 qemu_wait_io_event(cur_cpu
);
4027 void qemu_cpu_kick(void *_env
)
4029 CPUState
*env
= _env
;
4030 qemu_cond_broadcast(env
->halt_cond
);
4032 qemu_thread_signal(env
->thread
, SIGUSR1
);
4035 int qemu_cpu_self(void *env
)
4037 return (cpu_single_env
!= NULL
);
4040 static void cpu_signal(int sig
)
4043 cpu_exit(cpu_single_env
);
4046 static void block_io_signals(void)
4049 struct sigaction sigact
;
4052 sigaddset(&set
, SIGUSR2
);
4053 sigaddset(&set
, SIGIO
);
4054 sigaddset(&set
, SIGALRM
);
4055 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
4058 sigaddset(&set
, SIGUSR1
);
4059 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
4061 memset(&sigact
, 0, sizeof(sigact
));
4062 sigact
.sa_handler
= cpu_signal
;
4063 sigaction(SIGUSR1
, &sigact
, NULL
);
4066 static void unblock_io_signals(void)
4071 sigaddset(&set
, SIGUSR2
);
4072 sigaddset(&set
, SIGIO
);
4073 sigaddset(&set
, SIGALRM
);
4074 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
4077 sigaddset(&set
, SIGUSR1
);
4078 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
4081 static void qemu_signal_lock(unsigned int msecs
)
4083 qemu_mutex_lock(&qemu_fair_mutex
);
4085 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
4086 qemu_thread_signal(tcg_cpu_thread
, SIGUSR1
);
4087 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
4090 qemu_mutex_unlock(&qemu_fair_mutex
);
4093 static void qemu_mutex_lock_iothread(void)
4095 if (kvm_enabled()) {
4096 qemu_mutex_lock(&qemu_fair_mutex
);
4097 qemu_mutex_lock(&qemu_global_mutex
);
4098 qemu_mutex_unlock(&qemu_fair_mutex
);
4100 qemu_signal_lock(100);
4103 static void qemu_mutex_unlock_iothread(void)
4105 qemu_mutex_unlock(&qemu_global_mutex
);
4108 static int all_vcpus_paused(void)
4110 CPUState
*penv
= first_cpu
;
4115 penv
= (CPUState
*)penv
->next_cpu
;
4121 static void pause_all_vcpus(void)
4123 CPUState
*penv
= first_cpu
;
4127 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4128 qemu_cpu_kick(penv
);
4129 penv
= (CPUState
*)penv
->next_cpu
;
4132 while (!all_vcpus_paused()) {
4133 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
4136 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4137 penv
= (CPUState
*)penv
->next_cpu
;
4142 static void resume_all_vcpus(void)
4144 CPUState
*penv
= first_cpu
;
4149 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4150 qemu_cpu_kick(penv
);
4151 penv
= (CPUState
*)penv
->next_cpu
;
4155 static void tcg_init_vcpu(void *_env
)
4157 CPUState
*env
= _env
;
4158 /* share a single thread for all cpus with TCG */
4159 if (!tcg_cpu_thread
) {
4160 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
4161 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
4162 qemu_cond_init(env
->halt_cond
);
4163 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
4164 while (env
->created
== 0)
4165 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
4166 tcg_cpu_thread
= env
->thread
;
4167 tcg_halt_cond
= env
->halt_cond
;
4169 env
->thread
= tcg_cpu_thread
;
4170 env
->halt_cond
= tcg_halt_cond
;
4174 static void kvm_start_vcpu(CPUState
*env
)
4177 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
4178 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
4179 qemu_cond_init(env
->halt_cond
);
4180 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
4181 while (env
->created
== 0)
4182 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
4185 void qemu_init_vcpu(void *_env
)
4187 CPUState
*env
= _env
;
4190 kvm_start_vcpu(env
);
4195 void qemu_notify_event(void)
4197 qemu_event_increment();
4200 void vm_stop(int reason
)
4203 qemu_thread_self(&me
);
4205 if (!qemu_thread_equal(&me
, &io_thread
)) {
4206 qemu_system_vmstop_request(reason
);
4208 * FIXME: should not return to device code in case
4209 * vm_stop() has been requested.
4211 if (cpu_single_env
) {
4212 cpu_exit(cpu_single_env
);
4213 cpu_single_env
->stop
= 1;
4224 static void host_main_loop_wait(int *timeout
)
4230 /* XXX: need to suppress polling by better using win32 events */
4232 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
4233 ret
|= pe
->func(pe
->opaque
);
4237 WaitObjects
*w
= &wait_objects
;
4239 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
4240 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
4241 if (w
->func
[ret
- WAIT_OBJECT_0
])
4242 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
4244 /* Check for additional signaled events */
4245 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
4247 /* Check if event is signaled */
4248 ret2
= WaitForSingleObject(w
->events
[i
], 0);
4249 if(ret2
== WAIT_OBJECT_0
) {
4251 w
->func
[i
](w
->opaque
[i
]);
4252 } else if (ret2
== WAIT_TIMEOUT
) {
4254 err
= GetLastError();
4255 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
4258 } else if (ret
== WAIT_TIMEOUT
) {
4260 err
= GetLastError();
4261 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
4268 static void host_main_loop_wait(int *timeout
)
4273 void main_loop_wait(int timeout
)
4275 IOHandlerRecord
*ioh
;
4276 fd_set rfds
, wfds
, xfds
;
4280 qemu_bh_update_timeout(&timeout
);
4282 host_main_loop_wait(&timeout
);
4284 /* poll any events */
4285 /* XXX: separate device handlers from system ones */
4290 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4294 (!ioh
->fd_read_poll
||
4295 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
4296 FD_SET(ioh
->fd
, &rfds
);
4300 if (ioh
->fd_write
) {
4301 FD_SET(ioh
->fd
, &wfds
);
4307 tv
.tv_sec
= timeout
/ 1000;
4308 tv
.tv_usec
= (timeout
% 1000) * 1000;
4310 #if defined(CONFIG_SLIRP)
4311 if (slirp_is_inited()) {
4312 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
4315 ret
= qemu_select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
4317 IOHandlerRecord
**pioh
;
4319 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4320 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
4321 ioh
->fd_read(ioh
->opaque
);
4322 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
4323 FD_CLR(ioh
->fd
, &rfds
);
4325 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
4326 ioh
->fd_write(ioh
->opaque
);
4330 /* remove deleted IO handlers */
4331 pioh
= &first_io_handler
;
4341 #if defined(CONFIG_SLIRP)
4342 if (slirp_is_inited()) {
4348 slirp_select_poll(&rfds
, &wfds
, &xfds
);
4352 /* rearm timer, if not periodic */
4353 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
4354 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
4355 qemu_rearm_alarm_timer(alarm_timer
);
4358 /* vm time timers */
4360 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
4361 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
4362 qemu_get_clock(vm_clock
));
4365 /* real time timers */
4366 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
4367 qemu_get_clock(rt_clock
));
4369 /* Check bottom-halves last in case any of the earlier events triggered
4375 static int qemu_cpu_exec(CPUState
*env
)
4378 #ifdef CONFIG_PROFILER
4382 #ifdef CONFIG_PROFILER
4383 ti
= profile_getclock();
4388 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
4389 env
->icount_decr
.u16
.low
= 0;
4390 env
->icount_extra
= 0;
4391 count
= qemu_next_deadline();
4392 count
= (count
+ (1 << icount_time_shift
) - 1)
4393 >> icount_time_shift
;
4394 qemu_icount
+= count
;
4395 decr
= (count
> 0xffff) ? 0xffff : count
;
4397 env
->icount_decr
.u16
.low
= decr
;
4398 env
->icount_extra
= count
;
4400 ret
= cpu_exec(env
);
4401 #ifdef CONFIG_PROFILER
4402 qemu_time
+= profile_getclock() - ti
;
4405 /* Fold pending instructions back into the
4406 instruction counter, and clear the interrupt flag. */
4407 qemu_icount
-= (env
->icount_decr
.u16
.low
4408 + env
->icount_extra
);
4409 env
->icount_decr
.u32
= 0;
4410 env
->icount_extra
= 0;
4415 static void tcg_cpu_exec(void)
4419 if (next_cpu
== NULL
)
4420 next_cpu
= first_cpu
;
4421 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
4422 CPUState
*env
= cur_cpu
= next_cpu
;
4426 if (timer_alarm_pending
) {
4427 timer_alarm_pending
= 0;
4430 if (cpu_can_run(env
))
4431 ret
= qemu_cpu_exec(env
);
4432 if (ret
== EXCP_DEBUG
) {
4433 gdb_set_stop_cpu(env
);
4434 debug_requested
= 1;
4440 static int cpu_has_work(CPUState
*env
)
4448 if (qemu_cpu_has_work(env
))
4453 static int tcg_has_work(void)
4457 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4458 if (cpu_has_work(env
))
4463 static int qemu_calculate_timeout(void)
4469 else if (tcg_has_work())
4471 else if (!use_icount
)
4474 /* XXX: use timeout computed from timers */
4477 /* Advance virtual time to the next event. */
4478 if (use_icount
== 1) {
4479 /* When not using an adaptive execution frequency
4480 we tend to get badly out of sync with real time,
4481 so just delay for a reasonable amount of time. */
4484 delta
= cpu_get_icount() - cpu_get_clock();
4487 /* If virtual time is ahead of real time then just
4489 timeout
= (delta
/ 1000000) + 1;
4491 /* Wait for either IO to occur or the next
4493 add
= qemu_next_deadline();
4494 /* We advance the timer before checking for IO.
4495 Limit the amount we advance so that early IO
4496 activity won't get the guest too far ahead. */
4500 add
= (add
+ (1 << icount_time_shift
) - 1)
4501 >> icount_time_shift
;
4503 timeout
= delta
/ 1000000;
4512 static int vm_can_run(void)
4514 if (powerdown_requested
)
4516 if (reset_requested
)
4518 if (shutdown_requested
)
4520 if (debug_requested
)
4525 static void main_loop(void)
4529 if (kvm_enabled()) {
4531 cpu_disable_ticks();
4535 #ifdef CONFIG_IOTHREAD
4536 qemu_system_ready
= 1;
4537 qemu_cond_broadcast(&qemu_system_cond
);
4542 #ifdef CONFIG_PROFILER
4545 #ifndef CONFIG_IOTHREAD
4548 #ifdef CONFIG_PROFILER
4549 ti
= profile_getclock();
4551 #ifdef CONFIG_IOTHREAD
4552 main_loop_wait(1000);
4554 main_loop_wait(qemu_calculate_timeout());
4556 #ifdef CONFIG_PROFILER
4557 dev_time
+= profile_getclock() - ti
;
4559 } while (vm_can_run());
4561 if (qemu_debug_requested())
4562 vm_stop(EXCP_DEBUG
);
4563 if (qemu_shutdown_requested()) {
4570 if (qemu_reset_requested()) {
4572 qemu_system_reset();
4575 if (qemu_powerdown_requested())
4576 qemu_system_powerdown();
4577 if ((r
= qemu_vmstop_requested()))
4583 static void version(void)
4585 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4588 static void help(int exitcode
)
4591 printf("usage: %s [options] [disk_image]\n"
4593 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4595 #define DEF(option, opt_arg, opt_enum, opt_help) \
4597 #define DEFHEADING(text) stringify(text) "\n"
4598 #include "qemu-options.h"
4603 "During emulation, the following keys are useful:\n"
4604 "ctrl-alt-f toggle full screen\n"
4605 "ctrl-alt-n switch to virtual console 'n'\n"
4606 "ctrl-alt toggle mouse and keyboard grab\n"
4608 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4613 DEFAULT_NETWORK_SCRIPT
,
4614 DEFAULT_NETWORK_DOWN_SCRIPT
,
4616 DEFAULT_GDBSTUB_PORT
,
4621 #define HAS_ARG 0x0001
4624 #define DEF(option, opt_arg, opt_enum, opt_help) \
4626 #define DEFHEADING(text)
4627 #include "qemu-options.h"
4633 typedef struct QEMUOption
{
4639 static const QEMUOption qemu_options
[] = {
4640 { "h", 0, QEMU_OPTION_h
},
4641 #define DEF(option, opt_arg, opt_enum, opt_help) \
4642 { option, opt_arg, opt_enum },
4643 #define DEFHEADING(text)
4644 #include "qemu-options.h"
4652 struct soundhw soundhw
[] = {
4653 #ifdef HAS_AUDIO_CHOICE
4654 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4660 { .init_isa
= pcspk_audio_init
}
4667 "Creative Sound Blaster 16",
4670 { .init_isa
= SB16_init
}
4674 #ifdef CONFIG_CS4231A
4680 { .init_isa
= cs4231a_init
}
4688 "Yamaha YMF262 (OPL3)",
4690 "Yamaha YM3812 (OPL2)",
4694 { .init_isa
= Adlib_init
}
4701 "Gravis Ultrasound GF1",
4704 { .init_isa
= GUS_init
}
4711 "Intel 82801AA AC97 Audio",
4714 { .init_pci
= ac97_init
}
4718 #ifdef CONFIG_ES1370
4721 "ENSONIQ AudioPCI ES1370",
4724 { .init_pci
= es1370_init
}
4728 #endif /* HAS_AUDIO_CHOICE */
4730 { NULL
, NULL
, 0, 0, { NULL
} }
4733 static void select_soundhw (const char *optarg
)
4737 if (*optarg
== '?') {
4740 printf ("Valid sound card names (comma separated):\n");
4741 for (c
= soundhw
; c
->name
; ++c
) {
4742 printf ("%-11s %s\n", c
->name
, c
->descr
);
4744 printf ("\n-soundhw all will enable all of the above\n");
4745 exit (*optarg
!= '?');
4753 if (!strcmp (optarg
, "all")) {
4754 for (c
= soundhw
; c
->name
; ++c
) {
4762 e
= strchr (p
, ',');
4763 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4765 for (c
= soundhw
; c
->name
; ++c
) {
4766 if (!strncmp (c
->name
, p
, l
)) {
4775 "Unknown sound card name (too big to show)\n");
4778 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4783 p
+= l
+ (e
!= NULL
);
4787 goto show_valid_cards
;
4792 static void select_vgahw (const char *p
)
4796 cirrus_vga_enabled
= 0;
4797 std_vga_enabled
= 0;
4800 if (strstart(p
, "std", &opts
)) {
4801 std_vga_enabled
= 1;
4802 } else if (strstart(p
, "cirrus", &opts
)) {
4803 cirrus_vga_enabled
= 1;
4804 } else if (strstart(p
, "vmware", &opts
)) {
4806 } else if (strstart(p
, "xenfb", &opts
)) {
4808 } else if (!strstart(p
, "none", &opts
)) {
4810 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4814 const char *nextopt
;
4816 if (strstart(opts
, ",retrace=", &nextopt
)) {
4818 if (strstart(opts
, "dumb", &nextopt
))
4819 vga_retrace_method
= VGA_RETRACE_DUMB
;
4820 else if (strstart(opts
, "precise", &nextopt
))
4821 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4822 else goto invalid_vga
;
4823 } else goto invalid_vga
;
4829 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4831 exit(STATUS_CONTROL_C_EXIT
);
4836 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4840 if(strlen(str
) != 36)
4843 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4844 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4845 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4851 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4857 #define MAX_NET_CLIENTS 32
4861 #define HUGETLBFS_MAGIC 0x958458f6
4863 static long gethugepagesize(const char *path
)
4869 ret
= statfs(path
, &fs
);
4870 } while (ret
!= 0 && errno
== EINTR
);
4877 if (fs
.f_type
!= HUGETLBFS_MAGIC
)
4878 fprintf(stderr
, "Warning: path not on HugeTLBFS: %s\n", path
);
4883 static void *alloc_mem_area(size_t memory
, unsigned long *len
, const char *path
)
4892 if (!kvm_has_sync_mmu()) {
4893 fprintf(stderr
, "host lacks mmu notifiers, disabling --mem-path\n");
4897 if (asprintf(&filename
, "%s/kvm.XXXXXX", path
) == -1)
4900 hpagesize
= gethugepagesize(path
);
4904 fd
= mkstemp(filename
);
4913 memory
= (memory
+hpagesize
-1) & ~(hpagesize
-1);
4916 * ftruncate is not supported by hugetlbfs in older
4917 * hosts, so don't bother checking for errors.
4918 * If anything goes wrong with it under other filesystems,
4921 ftruncate(fd
, memory
);
4924 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4925 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4926 * to sidestep this quirk.
4928 flags
= mem_prealloc
? MAP_POPULATE
|MAP_SHARED
: MAP_PRIVATE
;
4929 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, flags
, fd
, 0);
4931 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
, fd
, 0);
4933 if (area
== MAP_FAILED
) {
4934 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4945 static void termsig_handler(int signal
)
4947 qemu_system_shutdown_request();
4950 static void termsig_setup(void)
4952 struct sigaction act
;
4954 memset(&act
, 0, sizeof(act
));
4955 act
.sa_handler
= termsig_handler
;
4956 sigaction(SIGINT
, &act
, NULL
);
4957 sigaction(SIGHUP
, &act
, NULL
);
4958 sigaction(SIGTERM
, &act
, NULL
);
4963 int main(int argc
, char **argv
, char **envp
)
4965 const char *gdbstub_dev
= NULL
;
4966 uint32_t boot_devices_bitmap
= 0;
4968 int snapshot
, linux_boot
, net_boot
;
4969 const char *initrd_filename
;
4970 const char *kernel_filename
, *kernel_cmdline
;
4971 const char *boot_devices
= "";
4973 DisplayChangeListener
*dcl
;
4974 int cyls
, heads
, secs
, translation
;
4975 const char *net_clients
[MAX_NET_CLIENTS
];
4977 const char *bt_opts
[MAX_BT_CMDLINE
];
4981 const char *r
, *optarg
;
4982 CharDriverState
*monitor_hd
= NULL
;
4983 const char *monitor_device
;
4984 const char *serial_devices
[MAX_SERIAL_PORTS
];
4985 int serial_device_index
;
4986 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
4987 int parallel_device_index
;
4988 const char *virtio_consoles
[MAX_VIRTIO_CONSOLES
];
4989 int virtio_console_index
;
4990 const char *loadvm
= NULL
;
4991 QEMUMachine
*machine
;
4992 const char *cpu_model
;
4993 const char *usb_devices
[MAX_USB_CMDLINE
];
4994 int usb_devices_index
;
4999 const char *pid_file
= NULL
;
5000 const char *incoming
= NULL
;
5003 struct passwd
*pwd
= NULL
;
5004 const char *chroot_dir
= NULL
;
5005 const char *run_as
= NULL
;
5008 int show_vnc_port
= 0;
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
= find_default_machine();
5046 initrd_filename
= NULL
;
5049 kernel_filename
= NULL
;
5050 kernel_cmdline
= "";
5051 cyls
= heads
= secs
= 0;
5052 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5053 monitor_device
= "vc:80Cx24C";
5055 serial_devices
[0] = "vc:80Cx24C";
5056 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
5057 serial_devices
[i
] = NULL
;
5058 serial_device_index
= 0;
5060 parallel_devices
[0] = "vc:80Cx24C";
5061 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
5062 parallel_devices
[i
] = NULL
;
5063 parallel_device_index
= 0;
5065 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++)
5066 virtio_consoles
[i
] = NULL
;
5067 virtio_console_index
= 0;
5069 for (i
= 0; i
< MAX_NODES
; i
++) {
5071 node_cpumask
[i
] = 0;
5074 usb_devices_index
= 0;
5075 assigned_devices_index
= 0;
5089 register_watchdogs();
5097 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
5099 const QEMUOption
*popt
;
5102 /* Treat --foo the same as -foo. */
5105 popt
= qemu_options
;
5108 fprintf(stderr
, "%s: invalid option -- '%s'\n",
5112 if (!strcmp(popt
->name
, r
+ 1))
5116 if (popt
->flags
& HAS_ARG
) {
5117 if (optind
>= argc
) {
5118 fprintf(stderr
, "%s: option '%s' requires an argument\n",
5122 optarg
= argv
[optind
++];
5127 switch(popt
->index
) {
5129 machine
= find_machine(optarg
);
5132 printf("Supported machines are:\n");
5133 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5134 printf("%-10s %s%s\n",
5136 m
->is_default
? " (default)" : "");
5138 exit(*optarg
!= '?');
5141 case QEMU_OPTION_cpu
:
5142 /* hw initialization will check this */
5143 if (*optarg
== '?') {
5144 /* XXX: implement xxx_cpu_list for targets that still miss it */
5145 #if defined(cpu_list)
5146 cpu_list(stdout
, &fprintf
);
5153 case QEMU_OPTION_initrd
:
5154 initrd_filename
= optarg
;
5156 case QEMU_OPTION_hda
:
5158 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
5160 hda_index
= drive_add(optarg
, HD_ALIAS
5161 ",cyls=%d,heads=%d,secs=%d%s",
5162 0, cyls
, heads
, secs
,
5163 translation
== BIOS_ATA_TRANSLATION_LBA
?
5165 translation
== BIOS_ATA_TRANSLATION_NONE
?
5166 ",trans=none" : "");
5168 case QEMU_OPTION_hdb
:
5169 case QEMU_OPTION_hdc
:
5170 case QEMU_OPTION_hdd
:
5171 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
5173 case QEMU_OPTION_drive
:
5174 drive_add(NULL
, "%s", optarg
);
5176 case QEMU_OPTION_mtdblock
:
5177 drive_add(optarg
, MTD_ALIAS
);
5179 case QEMU_OPTION_sd
:
5180 drive_add(optarg
, SD_ALIAS
);
5182 case QEMU_OPTION_pflash
:
5183 drive_add(optarg
, PFLASH_ALIAS
);
5185 case QEMU_OPTION_snapshot
:
5188 case QEMU_OPTION_hdachs
:
5192 cyls
= strtol(p
, (char **)&p
, 0);
5193 if (cyls
< 1 || cyls
> 16383)
5198 heads
= strtol(p
, (char **)&p
, 0);
5199 if (heads
< 1 || heads
> 16)
5204 secs
= strtol(p
, (char **)&p
, 0);
5205 if (secs
< 1 || secs
> 63)
5209 if (!strcmp(p
, "none"))
5210 translation
= BIOS_ATA_TRANSLATION_NONE
;
5211 else if (!strcmp(p
, "lba"))
5212 translation
= BIOS_ATA_TRANSLATION_LBA
;
5213 else if (!strcmp(p
, "auto"))
5214 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5217 } else if (*p
!= '\0') {
5219 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5222 if (hda_index
!= -1)
5223 snprintf(drives_opt
[hda_index
].opt
,
5224 sizeof(drives_opt
[hda_index
].opt
),
5225 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
5226 0, cyls
, heads
, secs
,
5227 translation
== BIOS_ATA_TRANSLATION_LBA
?
5229 translation
== BIOS_ATA_TRANSLATION_NONE
?
5230 ",trans=none" : "");
5233 case QEMU_OPTION_numa
:
5234 if (nb_numa_nodes
>= MAX_NODES
) {
5235 fprintf(stderr
, "qemu: too many NUMA nodes\n");
5240 case QEMU_OPTION_nographic
:
5241 display_type
= DT_NOGRAPHIC
;
5243 #ifdef CONFIG_CURSES
5244 case QEMU_OPTION_curses
:
5245 display_type
= DT_CURSES
;
5248 case QEMU_OPTION_portrait
:
5251 case QEMU_OPTION_kernel
:
5252 kernel_filename
= optarg
;
5254 case QEMU_OPTION_append
:
5255 kernel_cmdline
= optarg
;
5257 case QEMU_OPTION_cdrom
:
5258 drive_add(optarg
, CDROM_ALIAS
);
5260 case QEMU_OPTION_boot
:
5261 boot_devices
= optarg
;
5262 /* We just do some generic consistency checks */
5264 /* Could easily be extended to 64 devices if needed */
5267 boot_devices_bitmap
= 0;
5268 for (p
= boot_devices
; *p
!= '\0'; p
++) {
5269 /* Allowed boot devices are:
5270 * a b : floppy disk drives
5271 * c ... f : IDE disk drives
5272 * g ... m : machine implementation dependant drives
5273 * n ... p : network devices
5274 * It's up to each machine implementation to check
5275 * if the given boot devices match the actual hardware
5276 * implementation and firmware features.
5278 if (*p
< 'a' || *p
> 'q') {
5279 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
5282 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
5284 "Boot device '%c' was given twice\n",*p
);
5287 boot_devices_bitmap
|= 1 << (*p
- 'a');
5291 case QEMU_OPTION_fda
:
5292 case QEMU_OPTION_fdb
:
5293 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
5296 case QEMU_OPTION_no_fd_bootchk
:
5300 case QEMU_OPTION_net
:
5301 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
5302 fprintf(stderr
, "qemu: too many network clients\n");
5305 net_clients
[nb_net_clients
] = optarg
;
5309 case QEMU_OPTION_tftp
:
5310 tftp_prefix
= optarg
;
5312 case QEMU_OPTION_bootp
:
5313 bootp_filename
= optarg
;
5316 case QEMU_OPTION_smb
:
5317 net_slirp_smb(optarg
);
5320 case QEMU_OPTION_redir
:
5321 net_slirp_redir(NULL
, optarg
);
5324 case QEMU_OPTION_bt
:
5325 if (nb_bt_opts
>= MAX_BT_CMDLINE
) {
5326 fprintf(stderr
, "qemu: too many bluetooth options\n");
5329 bt_opts
[nb_bt_opts
++] = optarg
;
5332 case QEMU_OPTION_audio_help
:
5336 case QEMU_OPTION_soundhw
:
5337 select_soundhw (optarg
);
5343 case QEMU_OPTION_version
:
5347 case QEMU_OPTION_m
: {
5351 value
= strtoul(optarg
, &ptr
, 10);
5353 case 0: case 'M': case 'm':
5360 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5364 /* On 32-bit hosts, QEMU is limited by virtual address space */
5365 if (value
> (2047 << 20)
5366 #ifndef CONFIG_KQEMU
5367 && HOST_LONG_BITS
== 32
5370 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5373 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5374 fprintf(stderr
, "qemu: ram size too large\n");
5383 const CPULogItem
*item
;
5385 mask
= cpu_str_to_log_mask(optarg
);
5387 printf("Log items (comma separated):\n");
5388 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5389 printf("%-10s %s\n", item
->name
, item
->help
);
5397 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5399 case QEMU_OPTION_gdb
:
5400 gdbstub_dev
= optarg
;
5405 case QEMU_OPTION_bios
:
5408 case QEMU_OPTION_singlestep
:
5416 keyboard_layout
= optarg
;
5419 case QEMU_OPTION_localtime
:
5422 case QEMU_OPTION_vga
:
5423 select_vgahw (optarg
);
5425 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5431 w
= strtol(p
, (char **)&p
, 10);
5434 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5440 h
= strtol(p
, (char **)&p
, 10);
5445 depth
= strtol(p
, (char **)&p
, 10);
5446 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5447 depth
!= 24 && depth
!= 32)
5449 } else if (*p
== '\0') {
5450 depth
= graphic_depth
;
5457 graphic_depth
= depth
;
5461 case QEMU_OPTION_echr
:
5464 term_escape_char
= strtol(optarg
, &r
, 0);
5466 printf("Bad argument to echr\n");
5469 case QEMU_OPTION_monitor
:
5470 monitor_device
= optarg
;
5472 case QEMU_OPTION_serial
:
5473 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
5474 fprintf(stderr
, "qemu: too many serial ports\n");
5477 serial_devices
[serial_device_index
] = optarg
;
5478 serial_device_index
++;
5480 case QEMU_OPTION_watchdog
:
5481 i
= select_watchdog(optarg
);
5483 exit (i
== 1 ? 1 : 0);
5485 case QEMU_OPTION_watchdog_action
:
5486 if (select_watchdog_action(optarg
) == -1) {
5487 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5491 case QEMU_OPTION_virtiocon
:
5492 if (virtio_console_index
>= MAX_VIRTIO_CONSOLES
) {
5493 fprintf(stderr
, "qemu: too many virtio consoles\n");
5496 virtio_consoles
[virtio_console_index
] = optarg
;
5497 virtio_console_index
++;
5499 case QEMU_OPTION_parallel
:
5500 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
5501 fprintf(stderr
, "qemu: too many parallel ports\n");
5504 parallel_devices
[parallel_device_index
] = optarg
;
5505 parallel_device_index
++;
5507 case QEMU_OPTION_loadvm
:
5510 case QEMU_OPTION_full_screen
:
5514 case QEMU_OPTION_no_frame
:
5517 case QEMU_OPTION_alt_grab
:
5520 case QEMU_OPTION_no_quit
:
5523 case QEMU_OPTION_sdl
:
5524 display_type
= DT_SDL
;
5527 case QEMU_OPTION_pidfile
:
5531 case QEMU_OPTION_win2k_hack
:
5532 win2k_install_hack
= 1;
5534 case QEMU_OPTION_rtc_td_hack
:
5537 case QEMU_OPTION_acpitable
:
5538 if(acpi_table_add(optarg
) < 0) {
5539 fprintf(stderr
, "Wrong acpi table provided\n");
5543 case QEMU_OPTION_smbios
:
5544 if(smbios_entry_add(optarg
) < 0) {
5545 fprintf(stderr
, "Wrong smbios provided\n");
5551 case QEMU_OPTION_no_kqemu
:
5554 case QEMU_OPTION_kernel_kqemu
:
5559 case QEMU_OPTION_enable_kvm
:
5567 case QEMU_OPTION_no_kvm
:
5570 case QEMU_OPTION_no_kvm_irqchip
: {
5575 case QEMU_OPTION_no_kvm_pit
: {
5579 case QEMU_OPTION_no_kvm_pit_reinjection
: {
5580 kvm_pit_reinject
= 0;
5583 case QEMU_OPTION_enable_nesting
: {
5587 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5588 case QEMU_OPTION_pcidevice
:
5589 if (assigned_devices_index
>= MAX_DEV_ASSIGN_CMDLINE
) {
5590 fprintf(stderr
, "Too many assigned devices\n");
5593 assigned_devices
[assigned_devices_index
] = optarg
;
5594 assigned_devices_index
++;
5598 case QEMU_OPTION_usb
:
5601 case QEMU_OPTION_usbdevice
:
5603 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
5604 fprintf(stderr
, "Too many USB devices\n");
5607 usb_devices
[usb_devices_index
] = optarg
;
5608 usb_devices_index
++;
5610 case QEMU_OPTION_smp
:
5611 smp_cpus
= atoi(optarg
);
5613 fprintf(stderr
, "Invalid number of CPUs\n");
5617 case QEMU_OPTION_vnc
:
5618 display_type
= DT_VNC
;
5619 vnc_display
= optarg
;
5622 case QEMU_OPTION_no_acpi
:
5625 case QEMU_OPTION_no_hpet
:
5629 case QEMU_OPTION_no_reboot
:
5632 case QEMU_OPTION_no_shutdown
:
5635 case QEMU_OPTION_show_cursor
:
5638 case QEMU_OPTION_uuid
:
5639 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5640 fprintf(stderr
, "Fail to parse UUID string."
5641 " Wrong format.\n");
5646 case QEMU_OPTION_daemonize
:
5650 case QEMU_OPTION_option_rom
:
5651 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5652 fprintf(stderr
, "Too many option ROMs\n");
5655 option_rom
[nb_option_roms
] = optarg
;
5658 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5659 case QEMU_OPTION_semihosting
:
5660 semihosting_enabled
= 1;
5663 case QEMU_OPTION_tdf
:
5666 case QEMU_OPTION_kvm_shadow_memory
:
5667 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
5669 case QEMU_OPTION_mempath
:
5673 case QEMU_OPTION_mem_prealloc
:
5674 mem_prealloc
= !mem_prealloc
;
5677 case QEMU_OPTION_name
:
5680 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5681 case QEMU_OPTION_prom_env
:
5682 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5683 fprintf(stderr
, "Too many prom variables\n");
5686 prom_envs
[nb_prom_envs
] = optarg
;
5691 case QEMU_OPTION_old_param
:
5695 case QEMU_OPTION_clock
:
5696 configure_alarms(optarg
);
5698 case QEMU_OPTION_startdate
:
5701 time_t rtc_start_date
;
5702 if (!strcmp(optarg
, "now")) {
5703 rtc_date_offset
= -1;
5705 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
5713 } else if (sscanf(optarg
, "%d-%d-%d",
5716 &tm
.tm_mday
) == 3) {
5725 rtc_start_date
= mktimegm(&tm
);
5726 if (rtc_start_date
== -1) {
5728 fprintf(stderr
, "Invalid date format. Valid format are:\n"
5729 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5732 rtc_date_offset
= time(NULL
) - rtc_start_date
;
5736 case QEMU_OPTION_tb_size
:
5737 tb_size
= strtol(optarg
, NULL
, 0);
5741 case QEMU_OPTION_icount
:
5743 if (strcmp(optarg
, "auto") == 0) {
5744 icount_time_shift
= -1;
5746 icount_time_shift
= strtol(optarg
, NULL
, 0);
5749 case QEMU_OPTION_incoming
:
5753 case QEMU_OPTION_chroot
:
5754 chroot_dir
= optarg
;
5756 case QEMU_OPTION_runas
:
5759 case QEMU_OPTION_nvram
:
5764 case QEMU_OPTION_xen_domid
:
5765 xen_domid
= atoi(optarg
);
5767 case QEMU_OPTION_xen_create
:
5768 xen_mode
= XEN_CREATE
;
5770 case QEMU_OPTION_xen_attach
:
5771 xen_mode
= XEN_ATTACH
;
5778 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5779 if (kvm_allowed
&& kqemu_allowed
) {
5781 "You can not enable both KVM and kqemu at the same time\n");
5786 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5787 if (smp_cpus
> machine
->max_cpus
) {
5788 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5789 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5794 if (display_type
== DT_NOGRAPHIC
) {
5795 if (serial_device_index
== 0)
5796 serial_devices
[0] = "stdio";
5797 if (parallel_device_index
== 0)
5798 parallel_devices
[0] = "null";
5799 if (strncmp(monitor_device
, "vc", 2) == 0)
5800 monitor_device
= "stdio";
5807 if (pipe(fds
) == -1)
5818 len
= read(fds
[0], &status
, 1);
5819 if (len
== -1 && (errno
== EINTR
))
5824 else if (status
== 1) {
5825 fprintf(stderr
, "Could not acquire pidfile\n");
5842 signal(SIGTSTP
, SIG_IGN
);
5843 signal(SIGTTOU
, SIG_IGN
);
5844 signal(SIGTTIN
, SIG_IGN
);
5848 if (kvm_enabled()) {
5849 if (kvm_qemu_init() < 0) {
5850 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
5851 #ifdef NO_CPU_EMULATION
5852 fprintf(stderr
, "Compiled with --disable-cpu-emulation, exiting.\n");
5860 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5863 write(fds
[1], &status
, 1);
5865 fprintf(stderr
, "Could not acquire pid file\n");
5874 if (qemu_init_main_loop()) {
5875 fprintf(stderr
, "qemu_init_main_loop failed\n");
5878 linux_boot
= (kernel_filename
!= NULL
);
5879 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5881 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5882 fprintf(stderr
, "-append only allowed with -kernel option\n");
5886 if (!linux_boot
&& initrd_filename
!= NULL
) {
5887 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5891 /* boot to floppy or the default cd if no hard disk defined yet */
5892 if (!boot_devices
[0]) {
5893 boot_devices
= "cad";
5895 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5898 if (init_timer_alarm() < 0) {
5899 fprintf(stderr
, "could not initialize alarm timer\n");
5902 if (use_icount
&& icount_time_shift
< 0) {
5904 /* 125MIPS seems a reasonable initial guess at the guest speed.
5905 It will be corrected fairly quickly anyway. */
5906 icount_time_shift
= 3;
5907 init_icount_adjust();
5914 /* init network clients */
5915 if (nb_net_clients
== 0) {
5916 /* if no clients, we use a default config */
5917 net_clients
[nb_net_clients
++] = "nic";
5919 net_clients
[nb_net_clients
++] = "user";
5923 for(i
= 0;i
< nb_net_clients
; i
++) {
5924 if (net_client_parse(net_clients
[i
]) < 0)
5930 /* XXX: this should be moved in the PC machine instantiation code */
5931 if (net_boot
!= 0) {
5933 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
5934 const char *model
= nd_table
[i
].model
;
5936 if (net_boot
& (1 << i
)) {
5939 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
5940 if (get_image_size(buf
) > 0) {
5941 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5942 fprintf(stderr
, "Too many option ROMs\n");
5945 option_rom
[nb_option_roms
] = strdup(buf
);
5952 fprintf(stderr
, "No valid PXE rom found for network device\n");
5958 /* init the bluetooth world */
5959 for (i
= 0; i
< nb_bt_opts
; i
++)
5960 if (bt_parse(bt_opts
[i
]))
5963 /* init the memory */
5965 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5967 if (kvm_enabled()) {
5968 if (kvm_qemu_create_context() < 0) {
5969 fprintf(stderr
, "Could not create KVM context\n");
5975 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5976 guest ram allocation. It needs to go away. */
5977 if (kqemu_allowed
) {
5978 kqemu_phys_ram_size
= ram_size
+ 8 * 1024 * 1024 + 4 * 1024 * 1024;
5979 kqemu_phys_ram_base
= qemu_vmalloc(kqemu_phys_ram_size
);
5980 if (!kqemu_phys_ram_base
) {
5981 fprintf(stderr
, "Could not allocate physical memory\n");
5987 /* init the dynamic translator */
5988 cpu_exec_init_all(tb_size
* 1024 * 1024);
5993 /* we always create the cdrom drive, even if no disk is there */
5995 if (nb_drives_opt
< MAX_DRIVES
)
5996 drive_add(NULL
, CDROM_ALIAS
);
5998 /* we always create at least one floppy */
6000 if (nb_drives_opt
< MAX_DRIVES
)
6001 drive_add(NULL
, FD_ALIAS
, 0);
6003 /* we always create one sd slot, even if no card is in it */
6005 if (nb_drives_opt
< MAX_DRIVES
)
6006 drive_add(NULL
, SD_ALIAS
);
6008 /* open the virtual block devices
6009 * note that migration with device
6010 * hot add/remove is broken.
6012 for(i
= 0; i
< nb_drives_opt
; i
++)
6013 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
6016 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
6017 register_savevm_live("ram", 0, 3, ram_save_live
, NULL
, ram_load
, NULL
);
6020 /* must be after terminal init, SDL library changes signal handlers */
6024 /* Maintain compatibility with multiple stdio monitors */
6025 if (!strcmp(monitor_device
,"stdio")) {
6026 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6027 const char *devname
= serial_devices
[i
];
6028 if (devname
&& !strcmp(devname
,"mon:stdio")) {
6029 monitor_device
= NULL
;
6031 } else if (devname
&& !strcmp(devname
,"stdio")) {
6032 monitor_device
= NULL
;
6033 serial_devices
[i
] = "mon:stdio";
6039 if (nb_numa_nodes
> 0) {
6042 if (nb_numa_nodes
> smp_cpus
) {
6043 nb_numa_nodes
= smp_cpus
;
6046 /* If no memory size if given for any node, assume the default case
6047 * and distribute the available memory equally across all nodes
6049 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6050 if (node_mem
[i
] != 0)
6053 if (i
== nb_numa_nodes
) {
6054 uint64_t usedmem
= 0;
6056 /* On Linux, the each node's border has to be 8MB aligned,
6057 * the final node gets the rest.
6059 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
6060 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
6061 usedmem
+= node_mem
[i
];
6063 node_mem
[i
] = ram_size
- usedmem
;
6066 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6067 if (node_cpumask
[i
] != 0)
6070 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6071 * must cope with this anyway, because there are BIOSes out there in
6072 * real machines which also use this scheme.
6074 if (i
== nb_numa_nodes
) {
6075 for (i
= 0; i
< smp_cpus
; i
++) {
6076 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
6082 if (kvm_enabled()) {
6085 ret
= kvm_init(smp_cpus
);
6087 fprintf(stderr
, "failed to initialize KVM\n");
6093 if (monitor_device
) {
6094 monitor_hd
= qemu_chr_open("monitor", monitor_device
, NULL
);
6096 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
6101 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6102 const char *devname
= serial_devices
[i
];
6103 if (devname
&& strcmp(devname
, "none")) {
6105 snprintf(label
, sizeof(label
), "serial%d", i
);
6106 serial_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6107 if (!serial_hds
[i
]) {
6108 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
6115 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
6116 const char *devname
= parallel_devices
[i
];
6117 if (devname
&& strcmp(devname
, "none")) {
6119 snprintf(label
, sizeof(label
), "parallel%d", i
);
6120 parallel_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6121 if (!parallel_hds
[i
]) {
6122 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
6129 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
6130 const char *devname
= virtio_consoles
[i
];
6131 if (devname
&& strcmp(devname
, "none")) {
6133 snprintf(label
, sizeof(label
), "virtcon%d", i
);
6134 virtcon_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6135 if (!virtcon_hds
[i
]) {
6136 fprintf(stderr
, "qemu: could not open virtio console '%s'\n",
6143 module_call_init(MODULE_INIT_DEVICE
);
6148 machine
->init(ram_size
, boot_devices
,
6149 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
6152 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
6153 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6154 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
6160 current_machine
= machine
;
6162 /* Set KVM's vcpu state to qemu's initial CPUState. */
6163 if (kvm_enabled()) {
6166 ret
= kvm_sync_vcpus();
6168 fprintf(stderr
, "failed to initialize vcpus\n");
6173 /* init USB devices */
6175 for(i
= 0; i
< usb_devices_index
; i
++) {
6176 if (usb_device_add(usb_devices
[i
], 0) < 0) {
6177 fprintf(stderr
, "Warning: could not add USB device %s\n",
6184 dumb_display_init();
6185 /* just use the first displaystate for the moment */
6188 if (display_type
== DT_DEFAULT
) {
6189 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6190 display_type
= DT_SDL
;
6192 display_type
= DT_VNC
;
6193 vnc_display
= "localhost:0,to=99";
6199 switch (display_type
) {
6202 #if defined(CONFIG_CURSES)
6204 curses_display_init(ds
, full_screen
);
6207 #if defined(CONFIG_SDL)
6209 sdl_display_init(ds
, full_screen
, no_frame
);
6211 #elif defined(CONFIG_COCOA)
6213 cocoa_display_init(ds
, full_screen
);
6217 vnc_display_init(ds
);
6218 if (vnc_display_open(ds
, vnc_display
) < 0)
6221 if (show_vnc_port
) {
6222 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
6230 dcl
= ds
->listeners
;
6231 while (dcl
!= NULL
) {
6232 if (dcl
->dpy_refresh
!= NULL
) {
6233 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
6234 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
6239 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
6240 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
6241 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
6244 text_consoles_set_display(display_state
);
6245 qemu_chr_initial_reset();
6247 if (monitor_device
&& monitor_hd
)
6248 monitor_init(monitor_hd
, MONITOR_USE_READLINE
| MONITOR_IS_DEFAULT
);
6250 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6251 const char *devname
= serial_devices
[i
];
6252 if (devname
&& strcmp(devname
, "none")) {
6254 snprintf(label
, sizeof(label
), "serial%d", i
);
6255 if (strstart(devname
, "vc", 0))
6256 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
6260 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
6261 const char *devname
= parallel_devices
[i
];
6262 if (devname
&& strcmp(devname
, "none")) {
6264 snprintf(label
, sizeof(label
), "parallel%d", i
);
6265 if (strstart(devname
, "vc", 0))
6266 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
6270 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
6271 const char *devname
= virtio_consoles
[i
];
6272 if (virtcon_hds
[i
] && devname
) {
6274 snprintf(label
, sizeof(label
), "virtcon%d", i
);
6275 if (strstart(devname
, "vc", 0))
6276 qemu_chr_printf(virtcon_hds
[i
], "virtio console%d\r\n", i
);
6280 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
6281 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
6287 do_loadvm(cur_mon
, loadvm
);
6290 autostart
= 0; /* fixme how to deal with -daemonize */
6291 qemu_start_incoming_migration(incoming
);
6303 len
= write(fds
[1], &status
, 1);
6304 if (len
== -1 && (errno
== EINTR
))
6311 TFR(fd
= open("/dev/null", O_RDWR
));
6317 pwd
= getpwnam(run_as
);
6319 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
6325 if (chroot(chroot_dir
) < 0) {
6326 fprintf(stderr
, "chroot failed\n");
6333 if (setgid(pwd
->pw_gid
) < 0) {
6334 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
6337 if (setuid(pwd
->pw_uid
) < 0) {
6338 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
6341 if (setuid(0) != -1) {
6342 fprintf(stderr
, "Dropping privileges failed\n");