4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
32 /* Needed early for HOST_BSD etc. */
33 #include "config-host.h"
37 #include <sys/times.h>
41 #include <sys/ioctl.h>
42 #include <sys/resource.h>
43 #include <sys/socket.h>
45 #include <netinet/in.h>
47 #if defined(__NetBSD__)
48 #include <net/if_tap.h>
51 #include <linux/if_tun.h>
53 #include <arpa/inet.h>
56 #include <sys/select.h>
59 #if defined(__FreeBSD__) || defined(__DragonFly__)
64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65 #include <freebsd/stdlib.h>
70 #include <linux/rtc.h>
72 /* For the benefit of older linux systems which don't supply it,
73 we use a local copy of hpet.h. */
74 /* #include <linux/hpet.h> */
77 #include <linux/ppdev.h>
78 #include <linux/parport.h>
82 #include <sys/ethernet.h>
83 #include <sys/sockio.h>
84 #include <netinet/arp.h>
85 #include <netinet/in.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip_icmp.h> // must come after ip.h
89 #include <netinet/udp.h>
90 #include <netinet/tcp.h>
98 #if defined(__OpenBSD__)
102 #if defined(CONFIG_VDE)
103 #include <libvdeplug.h>
109 #include <sys/timeb.h>
110 #include <mmsystem.h>
111 #define getopt_long_only getopt_long
112 #define memalign(align, size) malloc(size)
118 int qemu_main(int argc
, char **argv
, char **envp
);
119 int main(int argc
, char **argv
)
121 qemu_main(argc
, argv
, NULL
);
124 #define main qemu_main
126 #endif /* CONFIG_SDL */
130 #define main qemu_main
131 #endif /* CONFIG_COCOA */
134 #include "hw/boards.h"
136 #include "hw/pcmcia.h"
138 #include "hw/audiodev.h"
142 #include "hw/watchdog.h"
143 #include "hw/smbios.h"
151 #include "qemu-timer.h"
152 #include "qemu-char.h"
153 #include "cache-utils.h"
156 #include "audio/audio.h"
157 #include "migration.h"
160 #include "qemu-kvm.h"
161 #include "hw/device-assignment.h"
165 #include "exec-all.h"
167 #include "qemu_socket.h"
169 #if defined(CONFIG_SLIRP)
170 #include "libslirp.h"
173 //#define DEBUG_UNUSED_IOPORT
174 //#define DEBUG_IOPORT
176 //#define DEBUG_SLIRP
180 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
182 # define LOG_IOPORT(...) do { } while (0)
185 #define DEFAULT_RAM_SIZE 128
187 /* Max number of USB devices that can be specified on the commandline. */
188 #define MAX_USB_CMDLINE 8
190 /* Max number of bluetooth switches on the commandline. */
191 #define MAX_BT_CMDLINE 10
193 /* XXX: use a two level table to limit memory usage */
194 #define MAX_IOPORTS 65536
196 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
197 const char *bios_name
= NULL
;
198 static void *ioport_opaque
[MAX_IOPORTS
];
199 static IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
200 static IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
201 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
202 to store the VM snapshots */
203 DriveInfo drives_table
[MAX_DRIVES
+1];
205 int extboot_drive
= -1;
206 static int vga_ram_size
;
207 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
208 static DisplayState
*display_state
;
212 const char* keyboard_layout
= NULL
;
213 int64_t ticks_per_sec
;
216 NICInfo nd_table
[MAX_NICS
];
218 static int autostart
;
219 static int rtc_utc
= 1;
220 static int rtc_date_offset
= -1; /* -1 means no change */
221 int cirrus_vga_enabled
= 1;
222 int std_vga_enabled
= 0;
223 int vmsvga_enabled
= 0;
224 int xenfb_enabled
= 0;
226 int graphic_width
= 1024;
227 int graphic_height
= 768;
228 int graphic_depth
= 8;
230 int graphic_width
= 800;
231 int graphic_height
= 600;
232 int graphic_depth
= 15;
234 static int full_screen
= 0;
236 static int no_frame
= 0;
239 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
240 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
241 CharDriverState
*virtcon_hds
[MAX_VIRTIO_CONSOLES
];
243 int win2k_install_hack
= 0;
248 const char *assigned_devices
[MAX_DEV_ASSIGN_CMDLINE
];
249 int assigned_devices_index
;
251 const char *vnc_display
;
252 int acpi_enabled
= 1;
258 int graphic_rotate
= 0;
262 WatchdogTimerModel
*watchdog
= NULL
;
263 int watchdog_action
= WDT_RESET
;
264 const char *option_rom
[MAX_OPTION_ROMS
];
266 int semihosting_enabled
= 0;
267 int time_drift_fix
= 0;
268 unsigned int kvm_shadow_memory
= 0;
269 const char *mem_path
= NULL
;
271 int mem_prealloc
= 1; /* force preallocation of physical target memory */
277 const char *qemu_name
;
279 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
280 unsigned int nb_prom_envs
= 0;
281 const char *prom_envs
[MAX_PROM_ENVS
];
284 const char *nvram
= NULL
;
285 struct drive_opt drives_opt
[MAX_DRIVES
];
288 uint64_t node_mem
[MAX_NODES
];
289 uint64_t node_cpumask
[MAX_NODES
];
291 static CPUState
*cur_cpu
;
292 static CPUState
*next_cpu
;
293 static int timer_alarm_pending
= 1;
294 /* Conversion factor from emulated instructions to virtual clock ticks. */
295 static int icount_time_shift
;
296 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
297 #define MAX_ICOUNT_SHIFT 10
298 /* Compensate for varying guest execution speed. */
299 static int64_t qemu_icount_bias
;
300 static QEMUTimer
*icount_rt_timer
;
301 static QEMUTimer
*icount_vm_timer
;
302 static QEMUTimer
*nographic_timer
;
304 uint8_t qemu_uuid
[16];
306 static int qemu_select(int max_fd
, fd_set
*rfds
, fd_set
*wfds
, fd_set
*xfds
,
311 /* KVM holds a mutex while QEMU code is running, we need hooks to
312 release the mutex whenever QEMU code sleeps. */
316 ret
= select(max_fd
, rfds
, wfds
, xfds
, tv
);
324 /***********************************************************/
325 /* x86 ISA bus support */
327 target_phys_addr_t isa_mem_base
= 0;
330 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
331 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
333 static uint32_t ioport_read(int index
, uint32_t address
)
335 static IOPortReadFunc
*default_func
[3] = {
336 default_ioport_readb
,
337 default_ioport_readw
,
340 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
342 func
= default_func
[index
];
343 return func(ioport_opaque
[address
], address
);
346 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
348 static IOPortWriteFunc
*default_func
[3] = {
349 default_ioport_writeb
,
350 default_ioport_writew
,
351 default_ioport_writel
353 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
355 func
= default_func
[index
];
356 func(ioport_opaque
[address
], address
, data
);
359 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
361 #ifdef DEBUG_UNUSED_IOPORT
362 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
367 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
369 #ifdef DEBUG_UNUSED_IOPORT
370 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
374 /* default is to make two byte accesses */
375 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
378 data
= ioport_read(0, address
);
379 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
380 data
|= ioport_read(0, address
) << 8;
384 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
386 ioport_write(0, address
, data
& 0xff);
387 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
388 ioport_write(0, address
, (data
>> 8) & 0xff);
391 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
393 #ifdef DEBUG_UNUSED_IOPORT
394 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
399 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
401 #ifdef DEBUG_UNUSED_IOPORT
402 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
406 /* size is the word size in byte */
407 int register_ioport_read(int start
, int length
, int size
,
408 IOPortReadFunc
*func
, void *opaque
)
414 } else if (size
== 2) {
416 } else if (size
== 4) {
419 hw_error("register_ioport_read: invalid size");
422 for(i
= start
; i
< start
+ length
; i
+= size
) {
423 ioport_read_table
[bsize
][i
] = func
;
424 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
425 hw_error("register_ioport_read: invalid opaque");
426 ioport_opaque
[i
] = opaque
;
431 /* size is the word size in byte */
432 int register_ioport_write(int start
, int length
, int size
,
433 IOPortWriteFunc
*func
, void *opaque
)
439 } else if (size
== 2) {
441 } else if (size
== 4) {
444 hw_error("register_ioport_write: invalid size");
447 for(i
= start
; i
< start
+ length
; i
+= size
) {
448 ioport_write_table
[bsize
][i
] = func
;
449 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
450 hw_error("register_ioport_write: invalid opaque");
451 ioport_opaque
[i
] = opaque
;
456 void isa_unassign_ioport(int start
, int length
)
460 for(i
= start
; i
< start
+ length
; i
++) {
461 ioport_read_table
[0][i
] = default_ioport_readb
;
462 ioport_read_table
[1][i
] = default_ioport_readw
;
463 ioport_read_table
[2][i
] = default_ioport_readl
;
465 ioport_write_table
[0][i
] = default_ioport_writeb
;
466 ioport_write_table
[1][i
] = default_ioport_writew
;
467 ioport_write_table
[2][i
] = default_ioport_writel
;
469 ioport_opaque
[i
] = NULL
;
473 /***********************************************************/
475 void cpu_outb(CPUState
*env
, int addr
, int val
)
477 LOG_IOPORT("outb: %04x %02x\n", addr
, val
);
478 ioport_write(0, addr
, val
);
481 env
->last_io_time
= cpu_get_time_fast();
485 void cpu_outw(CPUState
*env
, int addr
, int val
)
487 LOG_IOPORT("outw: %04x %04x\n", addr
, val
);
488 ioport_write(1, addr
, val
);
491 env
->last_io_time
= cpu_get_time_fast();
495 void cpu_outl(CPUState
*env
, int addr
, int val
)
497 LOG_IOPORT("outl: %04x %08x\n", addr
, val
);
498 ioport_write(2, addr
, val
);
501 env
->last_io_time
= cpu_get_time_fast();
505 int cpu_inb(CPUState
*env
, int addr
)
508 val
= ioport_read(0, addr
);
509 LOG_IOPORT("inb : %04x %02x\n", addr
, val
);
512 env
->last_io_time
= cpu_get_time_fast();
517 int cpu_inw(CPUState
*env
, int addr
)
520 val
= ioport_read(1, addr
);
521 LOG_IOPORT("inw : %04x %04x\n", addr
, val
);
524 env
->last_io_time
= cpu_get_time_fast();
529 int cpu_inl(CPUState
*env
, int addr
)
532 val
= ioport_read(2, addr
);
533 LOG_IOPORT("inl : %04x %08x\n", addr
, val
);
536 env
->last_io_time
= cpu_get_time_fast();
541 /***********************************************************/
542 void hw_error(const char *fmt
, ...)
548 fprintf(stderr
, "qemu: hardware error: ");
549 vfprintf(stderr
, fmt
, ap
);
550 fprintf(stderr
, "\n");
551 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
552 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
554 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
556 cpu_dump_state(env
, stderr
, fprintf
, 0);
566 static QEMUBalloonEvent
*qemu_balloon_event
;
567 void *qemu_balloon_event_opaque
;
569 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
571 qemu_balloon_event
= func
;
572 qemu_balloon_event_opaque
= opaque
;
575 void qemu_balloon(ram_addr_t target
)
577 if (qemu_balloon_event
)
578 qemu_balloon_event(qemu_balloon_event_opaque
, target
);
581 ram_addr_t
qemu_balloon_status(void)
583 if (qemu_balloon_event
)
584 return qemu_balloon_event(qemu_balloon_event_opaque
, 0);
588 /***********************************************************/
591 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
592 static void *qemu_put_kbd_event_opaque
;
593 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
594 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
596 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
598 qemu_put_kbd_event_opaque
= opaque
;
599 qemu_put_kbd_event
= func
;
602 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
603 void *opaque
, int absolute
,
606 QEMUPutMouseEntry
*s
, *cursor
;
608 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
610 s
->qemu_put_mouse_event
= func
;
611 s
->qemu_put_mouse_event_opaque
= opaque
;
612 s
->qemu_put_mouse_event_absolute
= absolute
;
613 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
616 if (!qemu_put_mouse_event_head
) {
617 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
621 cursor
= qemu_put_mouse_event_head
;
622 while (cursor
->next
!= NULL
)
623 cursor
= cursor
->next
;
626 qemu_put_mouse_event_current
= s
;
631 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
633 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
635 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
638 cursor
= qemu_put_mouse_event_head
;
639 while (cursor
!= NULL
&& cursor
!= entry
) {
641 cursor
= cursor
->next
;
644 if (cursor
== NULL
) // does not exist or list empty
646 else if (prev
== NULL
) { // entry is head
647 qemu_put_mouse_event_head
= cursor
->next
;
648 if (qemu_put_mouse_event_current
== entry
)
649 qemu_put_mouse_event_current
= cursor
->next
;
650 qemu_free(entry
->qemu_put_mouse_event_name
);
655 prev
->next
= entry
->next
;
657 if (qemu_put_mouse_event_current
== entry
)
658 qemu_put_mouse_event_current
= prev
;
660 qemu_free(entry
->qemu_put_mouse_event_name
);
664 void kbd_put_keycode(int keycode
)
666 if (qemu_put_kbd_event
) {
667 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
671 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
673 QEMUPutMouseEvent
*mouse_event
;
674 void *mouse_event_opaque
;
677 if (!qemu_put_mouse_event_current
) {
682 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
684 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
687 if (graphic_rotate
) {
688 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
691 width
= graphic_width
- 1;
692 mouse_event(mouse_event_opaque
,
693 width
- dy
, dx
, dz
, buttons_state
);
695 mouse_event(mouse_event_opaque
,
696 dx
, dy
, dz
, buttons_state
);
700 int kbd_mouse_is_absolute(void)
702 if (!qemu_put_mouse_event_current
)
705 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
708 void do_info_mice(Monitor
*mon
)
710 QEMUPutMouseEntry
*cursor
;
713 if (!qemu_put_mouse_event_head
) {
714 monitor_printf(mon
, "No mouse devices connected\n");
718 monitor_printf(mon
, "Mouse devices available:\n");
719 cursor
= qemu_put_mouse_event_head
;
720 while (cursor
!= NULL
) {
721 monitor_printf(mon
, "%c Mouse #%d: %s\n",
722 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
723 index
, cursor
->qemu_put_mouse_event_name
);
725 cursor
= cursor
->next
;
729 void do_mouse_set(Monitor
*mon
, int index
)
731 QEMUPutMouseEntry
*cursor
;
734 if (!qemu_put_mouse_event_head
) {
735 monitor_printf(mon
, "No mouse devices connected\n");
739 cursor
= qemu_put_mouse_event_head
;
740 while (cursor
!= NULL
&& index
!= i
) {
742 cursor
= cursor
->next
;
746 qemu_put_mouse_event_current
= cursor
;
748 monitor_printf(mon
, "Mouse at given index not found\n");
751 /* compute with 96 bit intermediate result: (a*b)/c */
752 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
757 #ifdef WORDS_BIGENDIAN
767 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
768 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
771 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
775 /***********************************************************/
776 /* real time host monotonic timer */
778 #define QEMU_TIMER_BASE 1000000000LL
782 static int64_t clock_freq
;
784 static void init_get_clock(void)
788 ret
= QueryPerformanceFrequency(&freq
);
790 fprintf(stderr
, "Could not calibrate ticks\n");
793 clock_freq
= freq
.QuadPart
;
796 static int64_t get_clock(void)
799 QueryPerformanceCounter(&ti
);
800 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
805 static int use_rt_clock
;
807 static void init_get_clock(void)
810 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
811 || defined(__DragonFly__)
814 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
821 static int64_t get_clock(void)
823 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
824 || defined(__DragonFly__)
827 clock_gettime(CLOCK_MONOTONIC
, &ts
);
828 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
832 /* XXX: using gettimeofday leads to problems if the date
833 changes, so it should be avoided. */
835 gettimeofday(&tv
, NULL
);
836 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
841 /* Return the virtual CPU time, based on the instruction counter. */
842 static int64_t cpu_get_icount(void)
845 CPUState
*env
= cpu_single_env
;;
846 icount
= qemu_icount
;
849 fprintf(stderr
, "Bad clock read\n");
850 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
852 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
855 /***********************************************************/
856 /* guest cycle counter */
858 static int64_t cpu_ticks_prev
;
859 static int64_t cpu_ticks_offset
;
860 static int64_t cpu_clock_offset
;
861 static int cpu_ticks_enabled
;
863 /* return the host CPU cycle counter and handle stop/restart */
864 int64_t cpu_get_ticks(void)
867 return cpu_get_icount();
869 if (!cpu_ticks_enabled
) {
870 return cpu_ticks_offset
;
873 ticks
= cpu_get_real_ticks();
874 if (cpu_ticks_prev
> ticks
) {
875 /* Note: non increasing ticks may happen if the host uses
877 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
879 cpu_ticks_prev
= ticks
;
880 return ticks
+ cpu_ticks_offset
;
884 /* return the host CPU monotonic timer and handle stop/restart */
885 static int64_t cpu_get_clock(void)
888 if (!cpu_ticks_enabled
) {
889 return cpu_clock_offset
;
892 return ti
+ cpu_clock_offset
;
896 /* enable cpu_get_ticks() */
897 void cpu_enable_ticks(void)
899 if (!cpu_ticks_enabled
) {
900 cpu_ticks_offset
-= cpu_get_real_ticks();
901 cpu_clock_offset
-= get_clock();
902 cpu_ticks_enabled
= 1;
906 /* disable cpu_get_ticks() : the clock is stopped. You must not call
907 cpu_get_ticks() after that. */
908 void cpu_disable_ticks(void)
910 if (cpu_ticks_enabled
) {
911 cpu_ticks_offset
= cpu_get_ticks();
912 cpu_clock_offset
= cpu_get_clock();
913 cpu_ticks_enabled
= 0;
917 /***********************************************************/
920 #define QEMU_TIMER_REALTIME 0
921 #define QEMU_TIMER_VIRTUAL 1
925 /* XXX: add frequency */
933 struct QEMUTimer
*next
;
936 struct qemu_alarm_timer
{
940 int (*start
)(struct qemu_alarm_timer
*t
);
941 void (*stop
)(struct qemu_alarm_timer
*t
);
942 void (*rearm
)(struct qemu_alarm_timer
*t
);
946 #define ALARM_FLAG_DYNTICKS 0x1
947 #define ALARM_FLAG_EXPIRED 0x2
949 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
951 return t
->flags
& ALARM_FLAG_DYNTICKS
;
954 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
956 if (!alarm_has_dynticks(t
))
962 /* TODO: MIN_TIMER_REARM_US should be optimized */
963 #define MIN_TIMER_REARM_US 250
965 static struct qemu_alarm_timer
*alarm_timer
;
969 struct qemu_alarm_win32
{
972 } alarm_win32_data
= {0, -1};
974 static int win32_start_timer(struct qemu_alarm_timer
*t
);
975 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
976 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
980 static int unix_start_timer(struct qemu_alarm_timer
*t
);
981 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
985 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
986 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
987 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
989 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
990 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
992 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
993 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
995 #endif /* __linux__ */
999 /* Correlation between real and virtual time is always going to be
1000 fairly approximate, so ignore small variation.
1001 When the guest is idle real and virtual time will be aligned in
1002 the IO wait loop. */
1003 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
1005 static void icount_adjust(void)
1010 static int64_t last_delta
;
1011 /* If the VM is not running, then do nothing. */
1015 cur_time
= cpu_get_clock();
1016 cur_icount
= qemu_get_clock(vm_clock
);
1017 delta
= cur_icount
- cur_time
;
1018 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1020 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
1021 && icount_time_shift
> 0) {
1022 /* The guest is getting too far ahead. Slow time down. */
1023 icount_time_shift
--;
1026 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
1027 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
1028 /* The guest is getting too far behind. Speed time up. */
1029 icount_time_shift
++;
1032 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
1035 static void icount_adjust_rt(void * opaque
)
1037 qemu_mod_timer(icount_rt_timer
,
1038 qemu_get_clock(rt_clock
) + 1000);
1042 static void icount_adjust_vm(void * opaque
)
1044 qemu_mod_timer(icount_vm_timer
,
1045 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1049 static void init_icount_adjust(void)
1051 /* Have both realtime and virtual time triggers for speed adjustment.
1052 The realtime trigger catches emulated time passing too slowly,
1053 the virtual time trigger catches emulated time passing too fast.
1054 Realtime triggers occur even when idle, so use them less frequently
1055 than VM triggers. */
1056 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
1057 qemu_mod_timer(icount_rt_timer
,
1058 qemu_get_clock(rt_clock
) + 1000);
1059 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
1060 qemu_mod_timer(icount_vm_timer
,
1061 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1064 static struct qemu_alarm_timer alarm_timers
[] = {
1067 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
1068 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
1069 /* HPET - if available - is preferred */
1070 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
1071 /* ...otherwise try RTC */
1072 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1074 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1076 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1077 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1078 {"win32", 0, win32_start_timer
,
1079 win32_stop_timer
, NULL
, &alarm_win32_data
},
1084 static void show_available_alarms(void)
1088 printf("Available alarm timers, in order of precedence:\n");
1089 for (i
= 0; alarm_timers
[i
].name
; i
++)
1090 printf("%s\n", alarm_timers
[i
].name
);
1093 static void configure_alarms(char const *opt
)
1097 int count
= ARRAY_SIZE(alarm_timers
) - 1;
1100 struct qemu_alarm_timer tmp
;
1102 if (!strcmp(opt
, "?")) {
1103 show_available_alarms();
1109 /* Reorder the array */
1110 name
= strtok(arg
, ",");
1112 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1113 if (!strcmp(alarm_timers
[i
].name
, name
))
1118 fprintf(stderr
, "Unknown clock %s\n", name
);
1127 tmp
= alarm_timers
[i
];
1128 alarm_timers
[i
] = alarm_timers
[cur
];
1129 alarm_timers
[cur
] = tmp
;
1133 name
= strtok(NULL
, ",");
1139 /* Disable remaining timers */
1140 for (i
= cur
; i
< count
; i
++)
1141 alarm_timers
[i
].name
= NULL
;
1143 show_available_alarms();
1148 QEMUClock
*rt_clock
;
1149 QEMUClock
*vm_clock
;
1151 static QEMUTimer
*active_timers
[2];
1153 static QEMUClock
*qemu_new_clock(int type
)
1156 clock
= qemu_mallocz(sizeof(QEMUClock
));
1161 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1165 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1168 ts
->opaque
= opaque
;
1172 void qemu_free_timer(QEMUTimer
*ts
)
1177 /* stop a timer, but do not dealloc it */
1178 void qemu_del_timer(QEMUTimer
*ts
)
1182 /* NOTE: this code must be signal safe because
1183 qemu_timer_expired() can be called from a signal. */
1184 pt
= &active_timers
[ts
->clock
->type
];
1197 /* modify the current timer so that it will be fired when current_time
1198 >= expire_time. The corresponding callback will be called. */
1199 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1205 /* add the timer in the sorted list */
1206 /* NOTE: this code must be signal safe because
1207 qemu_timer_expired() can be called from a signal. */
1208 pt
= &active_timers
[ts
->clock
->type
];
1213 if (t
->expire_time
> expire_time
)
1217 ts
->expire_time
= expire_time
;
1221 /* Rearm if necessary */
1222 if (pt
== &active_timers
[ts
->clock
->type
]) {
1223 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1224 qemu_rearm_alarm_timer(alarm_timer
);
1226 /* Interrupt execution to force deadline recalculation. */
1228 qemu_notify_event();
1232 int qemu_timer_pending(QEMUTimer
*ts
)
1235 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1242 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1246 return (timer_head
->expire_time
<= current_time
);
1249 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1255 if (!ts
|| ts
->expire_time
> current_time
)
1257 /* remove timer from the list before calling the callback */
1258 *ptimer_head
= ts
->next
;
1261 /* run the callback (the timer list can be modified) */
1266 int64_t qemu_get_clock(QEMUClock
*clock
)
1268 switch(clock
->type
) {
1269 case QEMU_TIMER_REALTIME
:
1270 return get_clock() / 1000000;
1272 case QEMU_TIMER_VIRTUAL
:
1274 return cpu_get_icount();
1276 return cpu_get_clock();
1281 static void init_timers(void)
1284 ticks_per_sec
= QEMU_TIMER_BASE
;
1285 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1286 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1290 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1292 uint64_t expire_time
;
1294 if (qemu_timer_pending(ts
)) {
1295 expire_time
= ts
->expire_time
;
1299 qemu_put_be64(f
, expire_time
);
1302 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1304 uint64_t expire_time
;
1306 expire_time
= qemu_get_be64(f
);
1307 if (expire_time
!= -1) {
1308 qemu_mod_timer(ts
, expire_time
);
1314 static void timer_save(QEMUFile
*f
, void *opaque
)
1316 if (cpu_ticks_enabled
) {
1317 hw_error("cannot save state if virtual timers are running");
1319 qemu_put_be64(f
, cpu_ticks_offset
);
1320 qemu_put_be64(f
, ticks_per_sec
);
1321 qemu_put_be64(f
, cpu_clock_offset
);
1324 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1326 if (version_id
!= 1 && version_id
!= 2)
1328 if (cpu_ticks_enabled
) {
1331 cpu_ticks_offset
=qemu_get_be64(f
);
1332 ticks_per_sec
=qemu_get_be64(f
);
1333 if (version_id
== 2) {
1334 cpu_clock_offset
=qemu_get_be64(f
);
1339 static void qemu_event_increment(void);
1342 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1343 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1346 static void host_alarm_handler(int host_signum
)
1350 #define DISP_FREQ 1000
1352 static int64_t delta_min
= INT64_MAX
;
1353 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1355 ti
= qemu_get_clock(vm_clock
);
1356 if (last_clock
!= 0) {
1357 delta
= ti
- last_clock
;
1358 if (delta
< delta_min
)
1360 if (delta
> delta_max
)
1363 if (++count
== DISP_FREQ
) {
1364 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1365 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1366 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1367 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1368 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1370 delta_min
= INT64_MAX
;
1378 if (alarm_has_dynticks(alarm_timer
) ||
1380 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1381 qemu_get_clock(vm_clock
))) ||
1382 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1383 qemu_get_clock(rt_clock
))) {
1384 qemu_event_increment();
1385 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1387 #ifndef CONFIG_IOTHREAD
1389 /* stop the currently executing cpu because a timer occured */
1392 if (next_cpu
->kqemu_enabled
) {
1393 kqemu_cpu_interrupt(next_cpu
);
1398 timer_alarm_pending
= 1;
1399 qemu_notify_event();
1403 static int64_t qemu_next_deadline(void)
1407 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1408 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1409 qemu_get_clock(vm_clock
);
1411 /* To avoid problems with overflow limit this to 2^32. */
1421 #if defined(__linux__) || defined(_WIN32)
1422 static uint64_t qemu_next_deadline_dyntick(void)
1430 delta
= (qemu_next_deadline() + 999) / 1000;
1432 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1433 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1434 qemu_get_clock(rt_clock
))*1000;
1435 if (rtdelta
< delta
)
1439 if (delta
< MIN_TIMER_REARM_US
)
1440 delta
= MIN_TIMER_REARM_US
;
1448 /* Sets a specific flag */
1449 static int fcntl_setfl(int fd
, int flag
)
1453 flags
= fcntl(fd
, F_GETFL
);
1457 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1463 #if defined(__linux__)
1465 #define RTC_FREQ 1024
1467 static void enable_sigio_timer(int fd
)
1469 struct sigaction act
;
1472 sigfillset(&act
.sa_mask
);
1474 act
.sa_handler
= host_alarm_handler
;
1476 sigaction(SIGIO
, &act
, NULL
);
1477 fcntl_setfl(fd
, O_ASYNC
);
1478 fcntl(fd
, F_SETOWN
, getpid());
1481 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1483 struct hpet_info info
;
1486 fd
= open("/dev/hpet", O_RDONLY
);
1491 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1493 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1494 "error, but for better emulation accuracy type:\n"
1495 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1499 /* Check capabilities */
1500 r
= ioctl(fd
, HPET_INFO
, &info
);
1504 /* Enable periodic mode */
1505 r
= ioctl(fd
, HPET_EPI
, 0);
1506 if (info
.hi_flags
&& (r
< 0))
1509 /* Enable interrupt */
1510 r
= ioctl(fd
, HPET_IE_ON
, 0);
1514 enable_sigio_timer(fd
);
1515 t
->priv
= (void *)(long)fd
;
1523 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1525 int fd
= (long)t
->priv
;
1530 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1533 unsigned long current_rtc_freq
= 0;
1535 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1538 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1539 if (current_rtc_freq
!= RTC_FREQ
&&
1540 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1541 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1542 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1543 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1546 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1552 enable_sigio_timer(rtc_fd
);
1554 t
->priv
= (void *)(long)rtc_fd
;
1559 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1561 int rtc_fd
= (long)t
->priv
;
1566 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1570 struct sigaction act
;
1572 sigfillset(&act
.sa_mask
);
1574 act
.sa_handler
= host_alarm_handler
;
1576 sigaction(SIGALRM
, &act
, NULL
);
1578 ev
.sigev_value
.sival_int
= 0;
1579 ev
.sigev_notify
= SIGEV_SIGNAL
;
1580 ev
.sigev_signo
= SIGALRM
;
1582 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1583 perror("timer_create");
1585 /* disable dynticks */
1586 fprintf(stderr
, "Dynamic Ticks disabled\n");
1591 t
->priv
= (void *)(long)host_timer
;
1596 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1598 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1600 timer_delete(host_timer
);
1603 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1605 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1606 struct itimerspec timeout
;
1607 int64_t nearest_delta_us
= INT64_MAX
;
1610 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1611 !active_timers
[QEMU_TIMER_VIRTUAL
])
1614 nearest_delta_us
= qemu_next_deadline_dyntick();
1616 /* check whether a timer is already running */
1617 if (timer_gettime(host_timer
, &timeout
)) {
1619 fprintf(stderr
, "Internal timer error: aborting\n");
1622 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1623 if (current_us
&& current_us
<= nearest_delta_us
)
1626 timeout
.it_interval
.tv_sec
= 0;
1627 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1628 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1629 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1630 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1632 fprintf(stderr
, "Internal timer error: aborting\n");
1637 #endif /* defined(__linux__) */
1639 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1641 struct sigaction act
;
1642 struct itimerval itv
;
1646 sigfillset(&act
.sa_mask
);
1648 act
.sa_handler
= host_alarm_handler
;
1650 sigaction(SIGALRM
, &act
, NULL
);
1652 itv
.it_interval
.tv_sec
= 0;
1653 /* for i386 kernel 2.6 to get 1 ms */
1654 itv
.it_interval
.tv_usec
= 999;
1655 itv
.it_value
.tv_sec
= 0;
1656 itv
.it_value
.tv_usec
= 10 * 1000;
1658 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1665 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1667 struct itimerval itv
;
1669 memset(&itv
, 0, sizeof(itv
));
1670 setitimer(ITIMER_REAL
, &itv
, NULL
);
1673 #endif /* !defined(_WIN32) */
1678 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1681 struct qemu_alarm_win32
*data
= t
->priv
;
1684 memset(&tc
, 0, sizeof(tc
));
1685 timeGetDevCaps(&tc
, sizeof(tc
));
1687 if (data
->period
< tc
.wPeriodMin
)
1688 data
->period
= tc
.wPeriodMin
;
1690 timeBeginPeriod(data
->period
);
1692 flags
= TIME_CALLBACK_FUNCTION
;
1693 if (alarm_has_dynticks(t
))
1694 flags
|= TIME_ONESHOT
;
1696 flags
|= TIME_PERIODIC
;
1698 data
->timerId
= timeSetEvent(1, // interval (ms)
1699 data
->period
, // resolution
1700 host_alarm_handler
, // function
1701 (DWORD
)t
, // parameter
1704 if (!data
->timerId
) {
1705 perror("Failed to initialize win32 alarm timer");
1706 timeEndPeriod(data
->period
);
1713 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1715 struct qemu_alarm_win32
*data
= t
->priv
;
1717 timeKillEvent(data
->timerId
);
1718 timeEndPeriod(data
->period
);
1721 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1723 struct qemu_alarm_win32
*data
= t
->priv
;
1724 uint64_t nearest_delta_us
;
1726 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1727 !active_timers
[QEMU_TIMER_VIRTUAL
])
1730 nearest_delta_us
= qemu_next_deadline_dyntick();
1731 nearest_delta_us
/= 1000;
1733 timeKillEvent(data
->timerId
);
1735 data
->timerId
= timeSetEvent(1,
1739 TIME_ONESHOT
| TIME_PERIODIC
);
1741 if (!data
->timerId
) {
1742 perror("Failed to re-arm win32 alarm timer");
1744 timeEndPeriod(data
->period
);
1751 static int init_timer_alarm(void)
1753 struct qemu_alarm_timer
*t
= NULL
;
1756 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1757 t
= &alarm_timers
[i
];
1777 static void quit_timers(void)
1779 alarm_timer
->stop(alarm_timer
);
1783 /***********************************************************/
1784 /* host time/date access */
1785 void qemu_get_timedate(struct tm
*tm
, int offset
)
1792 if (rtc_date_offset
== -1) {
1796 ret
= localtime(&ti
);
1798 ti
-= rtc_date_offset
;
1802 memcpy(tm
, ret
, sizeof(struct tm
));
1805 int qemu_timedate_diff(struct tm
*tm
)
1809 if (rtc_date_offset
== -1)
1811 seconds
= mktimegm(tm
);
1813 seconds
= mktime(tm
);
1815 seconds
= mktimegm(tm
) + rtc_date_offset
;
1817 return seconds
- time(NULL
);
1821 static void socket_cleanup(void)
1826 static int socket_init(void)
1831 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1833 err
= WSAGetLastError();
1834 fprintf(stderr
, "WSAStartup: %d\n", err
);
1837 atexit(socket_cleanup
);
1842 const char *get_opt_name(char *buf
, int buf_size
, const char *p
, char delim
)
1847 while (*p
!= '\0' && *p
!= delim
) {
1848 if (q
&& (q
- buf
) < buf_size
- 1)
1858 const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
1863 while (*p
!= '\0') {
1865 if (*(p
+ 1) != ',')
1869 if (q
&& (q
- buf
) < buf_size
- 1)
1879 int get_param_value(char *buf
, int buf_size
,
1880 const char *tag
, const char *str
)
1887 p
= get_opt_name(option
, sizeof(option
), p
, '=');
1891 if (!strcmp(tag
, option
)) {
1892 (void)get_opt_value(buf
, buf_size
, p
);
1895 p
= get_opt_value(NULL
, 0, p
);
1904 int check_params(const char * const *params
, const char *str
)
1906 int name_buf_size
= 1;
1912 for (i
= 0; params
[i
] != NULL
; i
++) {
1913 len
= strlen(params
[i
]) + 1;
1914 if (len
> name_buf_size
) {
1915 name_buf_size
= len
;
1918 name_buf
= qemu_malloc(name_buf_size
);
1921 while (*p
!= '\0') {
1922 p
= get_opt_name(name_buf
, name_buf_size
, p
, '=');
1928 for(i
= 0; params
[i
] != NULL
; i
++)
1929 if (!strcmp(params
[i
], name_buf
))
1931 if (params
[i
] == NULL
) {
1935 p
= get_opt_value(NULL
, 0, p
);
1941 qemu_free(name_buf
);
1945 /***********************************************************/
1946 /* Bluetooth support */
1949 static struct HCIInfo
*hci_table
[MAX_NICS
];
1951 static struct bt_vlan_s
{
1952 struct bt_scatternet_s net
;
1954 struct bt_vlan_s
*next
;
1957 /* find or alloc a new bluetooth "VLAN" */
1958 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1960 struct bt_vlan_s
**pvlan
, *vlan
;
1961 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1965 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1967 pvlan
= &first_bt_vlan
;
1968 while (*pvlan
!= NULL
)
1969 pvlan
= &(*pvlan
)->next
;
1974 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1978 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1983 static struct HCIInfo null_hci
= {
1984 .cmd_send
= null_hci_send
,
1985 .sco_send
= null_hci_send
,
1986 .acl_send
= null_hci_send
,
1987 .bdaddr_set
= null_hci_addr_set
,
1990 struct HCIInfo
*qemu_next_hci(void)
1992 if (cur_hci
== nb_hcis
)
1995 return hci_table
[cur_hci
++];
1998 static struct HCIInfo
*hci_init(const char *str
)
2001 struct bt_scatternet_s
*vlan
= 0;
2003 if (!strcmp(str
, "null"))
2006 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
2008 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
2009 else if (!strncmp(str
, "hci", 3)) {
2012 if (!strncmp(str
+ 3, ",vlan=", 6)) {
2013 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
2018 vlan
= qemu_find_bt_vlan(0);
2020 return bt_new_hci(vlan
);
2023 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
2028 static int bt_hci_parse(const char *str
)
2030 struct HCIInfo
*hci
;
2033 if (nb_hcis
>= MAX_NICS
) {
2034 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
2038 hci
= hci_init(str
);
2047 bdaddr
.b
[5] = 0x56 + nb_hcis
;
2048 hci
->bdaddr_set(hci
, bdaddr
.b
);
2050 hci_table
[nb_hcis
++] = hci
;
2055 static void bt_vhci_add(int vlan_id
)
2057 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
2060 fprintf(stderr
, "qemu: warning: adding a VHCI to "
2061 "an empty scatternet %i\n", vlan_id
);
2063 bt_vhci_init(bt_new_hci(vlan
));
2066 static struct bt_device_s
*bt_device_add(const char *opt
)
2068 struct bt_scatternet_s
*vlan
;
2070 char *endp
= strstr(opt
, ",vlan=");
2071 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
2074 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
2077 vlan_id
= strtol(endp
+ 6, &endp
, 0);
2079 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
2084 vlan
= qemu_find_bt_vlan(vlan_id
);
2087 fprintf(stderr
, "qemu: warning: adding a slave device to "
2088 "an empty scatternet %i\n", vlan_id
);
2090 if (!strcmp(devname
, "keyboard"))
2091 return bt_keyboard_init(vlan
);
2093 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
2097 static int bt_parse(const char *opt
)
2099 const char *endp
, *p
;
2102 if (strstart(opt
, "hci", &endp
)) {
2103 if (!*endp
|| *endp
== ',') {
2105 if (!strstart(endp
, ",vlan=", 0))
2108 return bt_hci_parse(opt
);
2110 } else if (strstart(opt
, "vhci", &endp
)) {
2111 if (!*endp
|| *endp
== ',') {
2113 if (strstart(endp
, ",vlan=", &p
)) {
2114 vlan
= strtol(p
, (char **) &endp
, 0);
2116 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
2120 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
2129 } else if (strstart(opt
, "device:", &endp
))
2130 return !bt_device_add(endp
);
2132 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
2136 /***********************************************************/
2137 /* QEMU Block devices */
2139 #define HD_ALIAS "index=%d,media=disk"
2140 #define CDROM_ALIAS "index=2,media=cdrom"
2141 #define FD_ALIAS "index=%d,if=floppy"
2142 #define PFLASH_ALIAS "if=pflash"
2143 #define MTD_ALIAS "if=mtd"
2144 #define SD_ALIAS "index=0,if=sd"
2146 static int drive_opt_get_free_idx(void)
2150 for (index
= 0; index
< MAX_DRIVES
; index
++)
2151 if (!drives_opt
[index
].used
) {
2152 drives_opt
[index
].used
= 1;
2159 static int drive_get_free_idx(void)
2163 for (index
= 0; index
< MAX_DRIVES
; index
++)
2164 if (!drives_table
[index
].used
) {
2165 drives_table
[index
].used
= 1;
2172 int drive_add(const char *file
, const char *fmt
, ...)
2175 int index
= drive_opt_get_free_idx();
2177 if (nb_drives_opt
>= MAX_DRIVES
|| index
== -1) {
2178 fprintf(stderr
, "qemu: too many drives\n");
2182 drives_opt
[index
].file
= file
;
2184 vsnprintf(drives_opt
[index
].opt
,
2185 sizeof(drives_opt
[0].opt
), fmt
, ap
);
2192 void drive_remove(int index
)
2194 drives_opt
[index
].used
= 0;
2198 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
2202 /* seek interface, bus and unit */
2204 for (index
= 0; index
< MAX_DRIVES
; index
++)
2205 if (drives_table
[index
].type
== type
&&
2206 drives_table
[index
].bus
== bus
&&
2207 drives_table
[index
].unit
== unit
&&
2208 drives_table
[index
].used
)
2214 int drive_get_max_bus(BlockInterfaceType type
)
2220 for (index
= 0; index
< nb_drives
; index
++) {
2221 if(drives_table
[index
].type
== type
&&
2222 drives_table
[index
].bus
> max_bus
)
2223 max_bus
= drives_table
[index
].bus
;
2228 const char *drive_get_serial(BlockDriverState
*bdrv
)
2232 for (index
= 0; index
< nb_drives
; index
++)
2233 if (drives_table
[index
].bdrv
== bdrv
)
2234 return drives_table
[index
].serial
;
2239 BlockInterfaceErrorAction
drive_get_onerror(BlockDriverState
*bdrv
)
2243 for (index
= 0; index
< nb_drives
; index
++)
2244 if (drives_table
[index
].bdrv
== bdrv
)
2245 return drives_table
[index
].onerror
;
2247 return BLOCK_ERR_STOP_ENOSPC
;
2250 static void bdrv_format_print(void *opaque
, const char *name
)
2252 fprintf(stderr
, " %s", name
);
2255 void drive_uninit(BlockDriverState
*bdrv
)
2259 for (i
= 0; i
< MAX_DRIVES
; i
++)
2260 if (drives_table
[i
].bdrv
== bdrv
) {
2261 drives_table
[i
].bdrv
= NULL
;
2262 drives_table
[i
].used
= 0;
2263 drive_remove(drives_table
[i
].drive_opt_idx
);
2269 int drive_init(struct drive_opt
*arg
, int snapshot
, void *opaque
)
2275 const char *mediastr
= "";
2276 BlockInterfaceType type
;
2277 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
2278 int bus_id
, unit_id
;
2279 int cyls
, heads
, secs
, translation
;
2280 BlockDriverState
*bdrv
;
2281 BlockDriver
*drv
= NULL
;
2282 QEMUMachine
*machine
= opaque
;
2286 int bdrv_flags
, onerror
;
2287 int drives_table_idx
;
2288 char *str
= arg
->opt
;
2289 static const char * const params
[] = { "bus", "unit", "if", "index",
2290 "cyls", "heads", "secs", "trans",
2291 "media", "snapshot", "file",
2292 "cache", "format", "serial", "werror",
2295 if (check_params(params
, str
) < 0) {
2296 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
2302 cyls
= heads
= secs
= 0;
2305 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2309 if (machine
->use_scsi
) {
2311 max_devs
= MAX_SCSI_DEVS
;
2312 pstrcpy(devname
, sizeof(devname
), "scsi");
2315 max_devs
= MAX_IDE_DEVS
;
2316 pstrcpy(devname
, sizeof(devname
), "ide");
2320 /* extract parameters */
2322 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
2323 bus_id
= strtol(buf
, NULL
, 0);
2325 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
2330 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
2331 unit_id
= strtol(buf
, NULL
, 0);
2333 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
2338 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
2339 pstrcpy(devname
, sizeof(devname
), buf
);
2340 if (!strcmp(buf
, "ide")) {
2342 max_devs
= MAX_IDE_DEVS
;
2343 } else if (!strcmp(buf
, "scsi")) {
2345 max_devs
= MAX_SCSI_DEVS
;
2346 } else if (!strcmp(buf
, "floppy")) {
2349 } else if (!strcmp(buf
, "pflash")) {
2352 } else if (!strcmp(buf
, "mtd")) {
2355 } else if (!strcmp(buf
, "sd")) {
2358 } else if (!strcmp(buf
, "virtio")) {
2361 } else if (!strcmp(buf
, "xen")) {
2365 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
2370 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
2371 index
= strtol(buf
, NULL
, 0);
2373 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
2378 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
2379 cyls
= strtol(buf
, NULL
, 0);
2382 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
2383 heads
= strtol(buf
, NULL
, 0);
2386 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
2387 secs
= strtol(buf
, NULL
, 0);
2390 if (cyls
|| heads
|| secs
) {
2391 if (cyls
< 1 || cyls
> 16383) {
2392 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
2395 if (heads
< 1 || heads
> 16) {
2396 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
2399 if (secs
< 1 || secs
> 63) {
2400 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
2405 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
2408 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2412 if (!strcmp(buf
, "none"))
2413 translation
= BIOS_ATA_TRANSLATION_NONE
;
2414 else if (!strcmp(buf
, "lba"))
2415 translation
= BIOS_ATA_TRANSLATION_LBA
;
2416 else if (!strcmp(buf
, "auto"))
2417 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2419 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
2424 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
2425 if (!strcmp(buf
, "disk")) {
2427 } else if (!strcmp(buf
, "cdrom")) {
2428 if (cyls
|| secs
|| heads
) {
2430 "qemu: '%s' invalid physical CHS format\n", str
);
2433 media
= MEDIA_CDROM
;
2435 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
2440 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
2441 if (!strcmp(buf
, "on"))
2443 else if (!strcmp(buf
, "off"))
2446 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
2451 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
2452 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2454 else if (!strcmp(buf
, "writethrough"))
2456 else if (!strcmp(buf
, "writeback"))
2459 fprintf(stderr
, "qemu: invalid cache option\n");
2464 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
2465 if (strcmp(buf
, "?") == 0) {
2466 fprintf(stderr
, "qemu: Supported formats:");
2467 bdrv_iterate_format(bdrv_format_print
, NULL
);
2468 fprintf(stderr
, "\n");
2471 drv
= bdrv_find_format(buf
);
2473 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2478 if (get_param_value(buf
, sizeof(buf
), "boot", str
)) {
2479 if (!strcmp(buf
, "on")) {
2480 if (extboot_drive
!= -1) {
2481 fprintf(stderr
, "qemu: two bootable drives specified\n");
2484 extboot_drive
= nb_drives
;
2485 } else if (strcmp(buf
, "off")) {
2486 fprintf(stderr
, "qemu: '%s' invalid boot option\n", str
);
2491 if (arg
->file
== NULL
)
2492 get_param_value(file
, sizeof(file
), "file", str
);
2494 pstrcpy(file
, sizeof(file
), arg
->file
);
2496 if (!get_param_value(serial
, sizeof(serial
), "serial", str
))
2497 memset(serial
, 0, sizeof(serial
));
2499 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2500 if (get_param_value(buf
, sizeof(serial
), "werror", str
)) {
2501 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2502 fprintf(stderr
, "werror is no supported by this format\n");
2505 if (!strcmp(buf
, "ignore"))
2506 onerror
= BLOCK_ERR_IGNORE
;
2507 else if (!strcmp(buf
, "enospc"))
2508 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2509 else if (!strcmp(buf
, "stop"))
2510 onerror
= BLOCK_ERR_STOP_ANY
;
2511 else if (!strcmp(buf
, "report"))
2512 onerror
= BLOCK_ERR_REPORT
;
2514 fprintf(stderr
, "qemu: '%s' invalid write error action\n", buf
);
2519 /* compute bus and unit according index */
2522 if (bus_id
!= 0 || unit_id
!= -1) {
2524 "qemu: '%s' index cannot be used with bus and unit\n", str
);
2532 unit_id
= index
% max_devs
;
2533 bus_id
= index
/ max_devs
;
2537 /* if user doesn't specify a unit_id,
2538 * try to find the first free
2541 if (unit_id
== -1) {
2543 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
2545 if (max_devs
&& unit_id
>= max_devs
) {
2546 unit_id
-= max_devs
;
2554 if (max_devs
&& unit_id
>= max_devs
) {
2555 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
2556 str
, unit_id
, max_devs
- 1);
2561 * ignore multiple definitions
2564 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
2569 if (type
== IF_IDE
|| type
== IF_SCSI
)
2570 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2572 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
2573 devname
, bus_id
, mediastr
, unit_id
);
2575 snprintf(buf
, sizeof(buf
), "%s%s%i",
2576 devname
, mediastr
, unit_id
);
2577 bdrv
= bdrv_new(buf
);
2578 drives_table_idx
= drive_get_free_idx();
2579 drives_table
[drives_table_idx
].bdrv
= bdrv
;
2580 drives_table
[drives_table_idx
].type
= type
;
2581 drives_table
[drives_table_idx
].bus
= bus_id
;
2582 drives_table
[drives_table_idx
].unit
= unit_id
;
2583 drives_table
[drives_table_idx
].onerror
= onerror
;
2584 drives_table
[drives_table_idx
].drive_opt_idx
= arg
- drives_opt
;
2585 strncpy(drives_table
[drives_table_idx
].serial
, serial
, sizeof(serial
));
2595 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
2596 bdrv_set_translation_hint(bdrv
, translation
);
2600 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
2605 /* FIXME: This isn't really a floppy, but it's a reasonable
2608 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
2619 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2620 cache
= 2; /* always use write-back with snapshot */
2622 if (cache
== 0) /* no caching */
2623 bdrv_flags
|= BDRV_O_NOCACHE
;
2624 else if (cache
== 2) /* write-back */
2625 bdrv_flags
|= BDRV_O_CACHE_WB
;
2626 else if (cache
== 3) /* not specified */
2627 bdrv_flags
|= BDRV_O_CACHE_DEF
;
2628 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0) {
2629 fprintf(stderr
, "qemu: could not open disk image %s\n",
2633 if (bdrv_key_required(bdrv
))
2635 return drives_table_idx
;
2638 static void numa_add(const char *optarg
)
2642 unsigned long long value
, endvalue
;
2645 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2646 if (!strcmp(option
, "node")) {
2647 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2648 nodenr
= nb_numa_nodes
;
2650 nodenr
= strtoull(option
, NULL
, 10);
2653 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2654 node_mem
[nodenr
] = 0;
2656 value
= strtoull(option
, &endptr
, 0);
2658 case 0: case 'M': case 'm':
2665 node_mem
[nodenr
] = value
;
2667 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2668 node_cpumask
[nodenr
] = 0;
2670 value
= strtoull(option
, &endptr
, 10);
2673 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2675 if (*endptr
== '-') {
2676 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2677 if (endvalue
>= 63) {
2680 "only 63 CPUs in NUMA mode supported.\n");
2682 value
= (1 << (endvalue
+ 1)) - (1 << value
);
2687 node_cpumask
[nodenr
] = value
;
2694 /***********************************************************/
2697 static USBPort
*used_usb_ports
;
2698 static USBPort
*free_usb_ports
;
2700 /* ??? Maybe change this to register a hub to keep track of the topology. */
2701 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
2702 usb_attachfn attach
)
2704 port
->opaque
= opaque
;
2705 port
->index
= index
;
2706 port
->attach
= attach
;
2707 port
->next
= free_usb_ports
;
2708 free_usb_ports
= port
;
2711 int usb_device_add_dev(USBDevice
*dev
)
2715 /* Find a USB port to add the device to. */
2716 port
= free_usb_ports
;
2720 /* Create a new hub and chain it on. */
2721 free_usb_ports
= NULL
;
2722 port
->next
= used_usb_ports
;
2723 used_usb_ports
= port
;
2725 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
2726 usb_attach(port
, hub
);
2727 port
= free_usb_ports
;
2730 free_usb_ports
= port
->next
;
2731 port
->next
= used_usb_ports
;
2732 used_usb_ports
= port
;
2733 usb_attach(port
, dev
);
2737 static void usb_msd_password_cb(void *opaque
, int err
)
2739 USBDevice
*dev
= opaque
;
2742 usb_device_add_dev(dev
);
2744 dev
->handle_destroy(dev
);
2747 static int usb_device_add(const char *devname
, int is_hotplug
)
2752 if (!free_usb_ports
)
2755 if (strstart(devname
, "host:", &p
)) {
2756 dev
= usb_host_device_open(p
);
2757 } else if (!strcmp(devname
, "mouse")) {
2758 dev
= usb_mouse_init();
2759 } else if (!strcmp(devname
, "tablet")) {
2760 dev
= usb_tablet_init();
2761 } else if (!strcmp(devname
, "keyboard")) {
2762 dev
= usb_keyboard_init();
2763 } else if (strstart(devname
, "disk:", &p
)) {
2764 BlockDriverState
*bs
;
2766 dev
= usb_msd_init(p
);
2769 bs
= usb_msd_get_bdrv(dev
);
2770 if (bdrv_key_required(bs
)) {
2773 monitor_read_bdrv_key_start(cur_mon
, bs
, usb_msd_password_cb
,
2778 } else if (!strcmp(devname
, "wacom-tablet")) {
2779 dev
= usb_wacom_init();
2780 } else if (strstart(devname
, "serial:", &p
)) {
2781 dev
= usb_serial_init(p
);
2782 #ifdef CONFIG_BRLAPI
2783 } else if (!strcmp(devname
, "braille")) {
2784 dev
= usb_baum_init();
2786 } else if (strstart(devname
, "net:", &p
)) {
2789 if (net_client_init("nic", p
) < 0)
2791 nd_table
[nic
].model
= "usb";
2792 dev
= usb_net_init(&nd_table
[nic
]);
2793 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2794 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2795 bt_new_hci(qemu_find_bt_vlan(0)));
2802 return usb_device_add_dev(dev
);
2805 int usb_device_del_addr(int bus_num
, int addr
)
2811 if (!used_usb_ports
)
2817 lastp
= &used_usb_ports
;
2818 port
= used_usb_ports
;
2819 while (port
&& port
->dev
->addr
!= addr
) {
2820 lastp
= &port
->next
;
2828 *lastp
= port
->next
;
2829 usb_attach(port
, NULL
);
2830 dev
->handle_destroy(dev
);
2831 port
->next
= free_usb_ports
;
2832 free_usb_ports
= port
;
2836 static int usb_device_del(const char *devname
)
2841 if (strstart(devname
, "host:", &p
))
2842 return usb_host_device_close(p
);
2844 if (!used_usb_ports
)
2847 p
= strchr(devname
, '.');
2850 bus_num
= strtoul(devname
, NULL
, 0);
2851 addr
= strtoul(p
+ 1, NULL
, 0);
2853 return usb_device_del_addr(bus_num
, addr
);
2856 void do_usb_add(Monitor
*mon
, const char *devname
)
2858 usb_device_add(devname
, 1);
2861 void do_usb_del(Monitor
*mon
, const char *devname
)
2863 usb_device_del(devname
);
2866 void usb_info(Monitor
*mon
)
2870 const char *speed_str
;
2873 monitor_printf(mon
, "USB support not enabled\n");
2877 for (port
= used_usb_ports
; port
; port
= port
->next
) {
2881 switch(dev
->speed
) {
2885 case USB_SPEED_FULL
:
2888 case USB_SPEED_HIGH
:
2895 monitor_printf(mon
, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2896 0, dev
->addr
, speed_str
, dev
->devname
);
2900 /***********************************************************/
2901 /* PCMCIA/Cardbus */
2903 static struct pcmcia_socket_entry_s
{
2904 struct pcmcia_socket_s
*socket
;
2905 struct pcmcia_socket_entry_s
*next
;
2906 } *pcmcia_sockets
= 0;
2908 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
2910 struct pcmcia_socket_entry_s
*entry
;
2912 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2913 entry
->socket
= socket
;
2914 entry
->next
= pcmcia_sockets
;
2915 pcmcia_sockets
= entry
;
2918 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
2920 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2922 ptr
= &pcmcia_sockets
;
2923 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2924 if (entry
->socket
== socket
) {
2930 void pcmcia_info(Monitor
*mon
)
2932 struct pcmcia_socket_entry_s
*iter
;
2934 if (!pcmcia_sockets
)
2935 monitor_printf(mon
, "No PCMCIA sockets\n");
2937 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2938 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2939 iter
->socket
->attached
? iter
->socket
->card_string
:
2943 /***********************************************************/
2944 /* register display */
2946 struct DisplayAllocator default_allocator
= {
2947 defaultallocator_create_displaysurface
,
2948 defaultallocator_resize_displaysurface
,
2949 defaultallocator_free_displaysurface
2952 void register_displaystate(DisplayState
*ds
)
2962 DisplayState
*get_displaystate(void)
2964 return display_state
;
2967 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
2969 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
2970 return ds
->allocator
;
2975 static void dumb_display_init(void)
2977 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
2978 ds
->allocator
= &default_allocator
;
2979 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
2980 register_displaystate(ds
);
2983 /***********************************************************/
2986 typedef struct IOHandlerRecord
{
2988 IOCanRWHandler
*fd_read_poll
;
2990 IOHandler
*fd_write
;
2993 /* temporary data */
2995 struct IOHandlerRecord
*next
;
2998 static IOHandlerRecord
*first_io_handler
;
3000 /* XXX: fd_read_poll should be suppressed, but an API change is
3001 necessary in the character devices to suppress fd_can_read(). */
3002 int qemu_set_fd_handler2(int fd
,
3003 IOCanRWHandler
*fd_read_poll
,
3005 IOHandler
*fd_write
,
3008 IOHandlerRecord
**pioh
, *ioh
;
3010 if (!fd_read
&& !fd_write
) {
3011 pioh
= &first_io_handler
;
3016 if (ioh
->fd
== fd
) {
3023 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3027 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
3028 ioh
->next
= first_io_handler
;
3029 first_io_handler
= ioh
;
3032 ioh
->fd_read_poll
= fd_read_poll
;
3033 ioh
->fd_read
= fd_read
;
3034 ioh
->fd_write
= fd_write
;
3035 ioh
->opaque
= opaque
;
3038 qemu_notify_event();
3042 int qemu_set_fd_handler(int fd
,
3044 IOHandler
*fd_write
,
3047 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
3051 /***********************************************************/
3052 /* Polling handling */
3054 typedef struct PollingEntry
{
3057 struct PollingEntry
*next
;
3060 static PollingEntry
*first_polling_entry
;
3062 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
3064 PollingEntry
**ppe
, *pe
;
3065 pe
= qemu_mallocz(sizeof(PollingEntry
));
3067 pe
->opaque
= opaque
;
3068 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
3073 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
3075 PollingEntry
**ppe
, *pe
;
3076 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
3078 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
3086 /***********************************************************/
3087 /* Wait objects support */
3088 typedef struct WaitObjects
{
3090 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
3091 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
3092 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
3095 static WaitObjects wait_objects
= {0};
3097 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
3099 WaitObjects
*w
= &wait_objects
;
3101 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
3103 w
->events
[w
->num
] = handle
;
3104 w
->func
[w
->num
] = func
;
3105 w
->opaque
[w
->num
] = opaque
;
3110 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
3113 WaitObjects
*w
= &wait_objects
;
3116 for (i
= 0; i
< w
->num
; i
++) {
3117 if (w
->events
[i
] == handle
)
3120 w
->events
[i
] = w
->events
[i
+ 1];
3121 w
->func
[i
] = w
->func
[i
+ 1];
3122 w
->opaque
[i
] = w
->opaque
[i
+ 1];
3130 /***********************************************************/
3131 /* ram save/restore */
3133 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
3137 v
= qemu_get_byte(f
);
3140 if (qemu_get_buffer(f
, buf
, len
) != len
)
3144 v
= qemu_get_byte(f
);
3145 memset(buf
, v
, len
);
3151 if (qemu_file_has_error(f
))
3157 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
3162 if (qemu_get_be32(f
) != last_ram_offset
)
3164 for(i
= 0; i
< last_ram_offset
; i
+= TARGET_PAGE_SIZE
) {
3165 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3167 ret
= ram_get_page(f
, qemu_get_ram_ptr(i
), TARGET_PAGE_SIZE
);
3174 #define BDRV_HASH_BLOCK_SIZE 1024
3175 #define IOBUF_SIZE 4096
3176 #define RAM_CBLOCK_MAGIC 0xfabe
3178 typedef struct RamDecompressState
{
3181 uint8_t buf
[IOBUF_SIZE
];
3182 } RamDecompressState
;
3184 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
3187 memset(s
, 0, sizeof(*s
));
3189 ret
= inflateInit(&s
->zstream
);
3195 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
3199 s
->zstream
.avail_out
= len
;
3200 s
->zstream
.next_out
= buf
;
3201 while (s
->zstream
.avail_out
> 0) {
3202 if (s
->zstream
.avail_in
== 0) {
3203 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
3205 clen
= qemu_get_be16(s
->f
);
3206 if (clen
> IOBUF_SIZE
)
3208 qemu_get_buffer(s
->f
, s
->buf
, clen
);
3209 s
->zstream
.avail_in
= clen
;
3210 s
->zstream
.next_in
= s
->buf
;
3212 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
3213 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
3220 static void ram_decompress_close(RamDecompressState
*s
)
3222 inflateEnd(&s
->zstream
);
3225 #define RAM_SAVE_FLAG_FULL 0x01
3226 #define RAM_SAVE_FLAG_COMPRESS 0x02
3227 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3228 #define RAM_SAVE_FLAG_PAGE 0x08
3229 #define RAM_SAVE_FLAG_EOS 0x10
3231 static int is_dup_page(uint8_t *page
, uint8_t ch
)
3233 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
3234 uint32_t *array
= (uint32_t *)page
;
3237 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
3238 if (array
[i
] != val
)
3245 static int ram_save_block(QEMUFile
*f
)
3247 static ram_addr_t current_addr
= 0;
3248 ram_addr_t saved_addr
= current_addr
;
3249 ram_addr_t addr
= 0;
3252 while (addr
< last_ram_offset
) {
3253 if (kvm_enabled() && current_addr
== 0) {
3255 r
= kvm_update_dirty_pages_log();
3257 fprintf(stderr
, "%s: update dirty pages log failed %d\n", __FUNCTION__
, r
);
3258 qemu_file_set_error(f
);
3262 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
3265 cpu_physical_memory_reset_dirty(current_addr
,
3266 current_addr
+ TARGET_PAGE_SIZE
,
3267 MIGRATION_DIRTY_FLAG
);
3269 p
= qemu_get_ram_ptr(current_addr
);
3271 if (is_dup_page(p
, *p
)) {
3272 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
3273 qemu_put_byte(f
, *p
);
3275 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
3276 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
3282 addr
+= TARGET_PAGE_SIZE
;
3283 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
3289 static ram_addr_t ram_save_threshold
= 10;
3291 static ram_addr_t
ram_save_remaining(void)
3294 ram_addr_t count
= 0;
3296 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3297 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3304 static int ram_save_live(QEMUFile
*f
, int stage
, void *opaque
)
3309 /* Make sure all dirty bits are set */
3310 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3311 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3312 cpu_physical_memory_set_dirty(addr
);
3315 /* Enable dirty memory tracking */
3316 cpu_physical_memory_set_dirty_tracking(1);
3318 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
3321 while (!qemu_file_rate_limit(f
)) {
3324 ret
= ram_save_block(f
);
3325 if (ret
== 0) /* no more blocks */
3329 /* try transferring iterative blocks of memory */
3333 /* flush all remaining blocks regardless of rate limiting */
3334 while (ram_save_block(f
) != 0);
3335 cpu_physical_memory_set_dirty_tracking(0);
3338 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3340 return (stage
== 2) && (ram_save_remaining() < ram_save_threshold
);
3343 static int ram_load_dead(QEMUFile
*f
, void *opaque
)
3345 RamDecompressState s1
, *s
= &s1
;
3349 if (ram_decompress_open(s
, f
) < 0)
3351 for(i
= 0; i
< last_ram_offset
; i
+= BDRV_HASH_BLOCK_SIZE
) {
3352 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3354 if (ram_decompress_buf(s
, buf
, 1) < 0) {
3355 fprintf(stderr
, "Error while reading ram block header\n");
3359 if (ram_decompress_buf(s
, qemu_get_ram_ptr(i
),
3360 BDRV_HASH_BLOCK_SIZE
) < 0) {
3361 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
3366 printf("Error block header\n");
3370 ram_decompress_close(s
);
3375 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
3380 if (version_id
== 1)
3381 return ram_load_v1(f
, opaque
);
3383 if (version_id
== 2) {
3384 if (qemu_get_be32(f
) != last_ram_offset
)
3386 return ram_load_dead(f
, opaque
);
3389 if (version_id
!= 3)
3393 addr
= qemu_get_be64(f
);
3395 flags
= addr
& ~TARGET_PAGE_MASK
;
3396 addr
&= TARGET_PAGE_MASK
;
3398 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
3399 if (addr
!= last_ram_offset
)
3403 if (flags
& RAM_SAVE_FLAG_FULL
) {
3404 if (ram_load_dead(f
, opaque
) < 0)
3408 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
3409 uint8_t ch
= qemu_get_byte(f
);
3410 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
3411 } else if (flags
& RAM_SAVE_FLAG_PAGE
)
3412 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
3413 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
3418 void qemu_service_io(void)
3420 qemu_notify_event();
3423 /***********************************************************/
3424 /* bottom halves (can be seen as timers which expire ASAP) */
3435 static QEMUBH
*first_bh
= NULL
;
3437 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
3440 bh
= qemu_mallocz(sizeof(QEMUBH
));
3442 bh
->opaque
= opaque
;
3443 bh
->next
= first_bh
;
3448 int qemu_bh_poll(void)
3454 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3455 if (!bh
->deleted
&& bh
->scheduled
) {
3464 /* remove deleted bhs */
3478 void qemu_bh_schedule_idle(QEMUBH
*bh
)
3486 void qemu_bh_schedule(QEMUBH
*bh
)
3492 /* stop the currently executing CPU to execute the BH ASAP */
3493 qemu_notify_event();
3496 void qemu_bh_cancel(QEMUBH
*bh
)
3501 void qemu_bh_delete(QEMUBH
*bh
)
3507 static void qemu_bh_update_timeout(int *timeout
)
3511 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3512 if (!bh
->deleted
&& bh
->scheduled
) {
3514 /* idle bottom halves will be polled at least
3516 *timeout
= MIN(10, *timeout
);
3518 /* non-idle bottom halves will be executed
3527 /***********************************************************/
3528 /* machine registration */
3530 static QEMUMachine
*first_machine
= NULL
;
3531 QEMUMachine
*current_machine
= NULL
;
3533 int qemu_register_machine(QEMUMachine
*m
)
3536 pm
= &first_machine
;
3544 static QEMUMachine
*find_machine(const char *name
)
3548 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3549 if (!strcmp(m
->name
, name
))
3555 /***********************************************************/
3556 /* main execution loop */
3558 static void gui_update(void *opaque
)
3560 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3561 DisplayState
*ds
= opaque
;
3562 DisplayChangeListener
*dcl
= ds
->listeners
;
3566 while (dcl
!= NULL
) {
3567 if (dcl
->gui_timer_interval
&&
3568 dcl
->gui_timer_interval
< interval
)
3569 interval
= dcl
->gui_timer_interval
;
3572 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3575 static void nographic_update(void *opaque
)
3577 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3579 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3582 struct vm_change_state_entry
{
3583 VMChangeStateHandler
*cb
;
3585 LIST_ENTRY (vm_change_state_entry
) entries
;
3588 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3590 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3593 VMChangeStateEntry
*e
;
3595 e
= qemu_mallocz(sizeof (*e
));
3599 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3603 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3605 LIST_REMOVE (e
, entries
);
3609 static void vm_state_notify(int running
, int reason
)
3611 VMChangeStateEntry
*e
;
3613 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3614 e
->cb(e
->opaque
, running
, reason
);
3618 static void resume_all_vcpus(void);
3619 static void pause_all_vcpus(void);
3626 vm_state_notify(1, 0);
3627 qemu_rearm_alarm_timer(alarm_timer
);
3632 /* reset/shutdown handler */
3634 typedef struct QEMUResetEntry
{
3635 QEMUResetHandler
*func
;
3637 struct QEMUResetEntry
*next
;
3640 static QEMUResetEntry
*first_reset_entry
;
3641 static int reset_requested
;
3642 static int shutdown_requested
;
3643 static int powerdown_requested
;
3644 static int debug_requested
;
3645 static int vmstop_requested
;
3647 int qemu_no_shutdown(void)
3649 int r
= no_shutdown
;
3654 int qemu_shutdown_requested(void)
3656 int r
= shutdown_requested
;
3657 shutdown_requested
= 0;
3661 int qemu_reset_requested(void)
3663 int r
= reset_requested
;
3664 reset_requested
= 0;
3668 int qemu_powerdown_requested(void)
3670 int r
= powerdown_requested
;
3671 powerdown_requested
= 0;
3675 static int qemu_debug_requested(void)
3677 int r
= debug_requested
;
3678 debug_requested
= 0;
3682 static int qemu_vmstop_requested(void)
3684 int r
= vmstop_requested
;
3685 vmstop_requested
= 0;
3689 static void do_vm_stop(int reason
)
3692 cpu_disable_ticks();
3695 vm_state_notify(0, reason
);
3699 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3701 QEMUResetEntry
**pre
, *re
;
3703 pre
= &first_reset_entry
;
3704 while (*pre
!= NULL
)
3705 pre
= &(*pre
)->next
;
3706 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3708 re
->opaque
= opaque
;
3713 void qemu_system_reset(void)
3717 /* reset all devices */
3718 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
3719 re
->func(re
->opaque
);
3725 void qemu_system_reset_request(void)
3728 shutdown_requested
= 1;
3730 reset_requested
= 1;
3732 if (cpu_single_env
) {
3733 qemu_kvm_cpu_stop(cpu_single_env
);
3734 cpu_exit(cpu_single_env
);
3736 qemu_notify_event();
3739 void qemu_system_shutdown_request(void)
3741 shutdown_requested
= 1;
3742 qemu_notify_event();
3745 void qemu_system_powerdown_request(void)
3747 powerdown_requested
= 1;
3748 qemu_notify_event();
3751 #ifdef CONFIG_IOTHREAD
3752 static void qemu_system_vmstop_request(int reason
)
3754 vmstop_requested
= reason
;
3755 qemu_notify_event();
3760 static int io_thread_fd
= -1;
3762 static void qemu_event_increment(void)
3764 static const char byte
= 0;
3766 if (io_thread_fd
== -1)
3769 write(io_thread_fd
, &byte
, sizeof(byte
));
3772 static void qemu_event_read(void *opaque
)
3774 int fd
= (unsigned long)opaque
;
3777 /* Drain the notify pipe */
3780 len
= read(fd
, buffer
, sizeof(buffer
));
3781 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
3784 static int qemu_event_init(void)
3793 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3797 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3801 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3802 (void *)(unsigned long)fds
[0]);
3804 io_thread_fd
= fds
[1];
3813 HANDLE qemu_event_handle
;
3815 static void dummy_event_handler(void *opaque
)
3819 static int qemu_event_init(void)
3821 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3822 if (!qemu_event_handle
) {
3823 perror("Failed CreateEvent");
3826 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3830 static void qemu_event_increment(void)
3832 SetEvent(qemu_event_handle
);
3836 static int cpu_can_run(CPUState
*env
)
3845 #ifndef CONFIG_IOTHREAD
3846 static int qemu_init_main_loop(void)
3848 return qemu_event_init();
3851 void qemu_init_vcpu(void *_env
)
3853 CPUState
*env
= _env
;
3860 int qemu_cpu_self(void *env
)
3865 static void resume_all_vcpus(void)
3869 static void pause_all_vcpus(void)
3873 void qemu_cpu_kick(void *env
)
3878 void qemu_notify_event(void)
3880 CPUState
*env
= cpu_single_env
;
3882 if (kvm_enabled()) {
3883 qemu_kvm_notify_work();
3889 if (env
->kqemu_enabled
)
3890 kqemu_cpu_interrupt(env
);
3895 #define qemu_mutex_lock_iothread() do { } while (0)
3896 #define qemu_mutex_unlock_iothread() do { } while (0)
3898 void vm_stop(int reason
)
3903 #else /* CONFIG_IOTHREAD */
3905 #include "qemu-thread.h"
3907 QemuMutex qemu_global_mutex
;
3908 static QemuMutex qemu_fair_mutex
;
3910 static QemuThread io_thread
;
3912 static QemuThread
*tcg_cpu_thread
;
3913 static QemuCond
*tcg_halt_cond
;
3915 static int qemu_system_ready
;
3917 static QemuCond qemu_cpu_cond
;
3919 static QemuCond qemu_system_cond
;
3920 static QemuCond qemu_pause_cond
;
3922 static void block_io_signals(void);
3923 static void unblock_io_signals(void);
3924 static int tcg_has_work(void);
3926 static int qemu_init_main_loop(void)
3930 ret
= qemu_event_init();
3934 qemu_cond_init(&qemu_pause_cond
);
3935 qemu_mutex_init(&qemu_fair_mutex
);
3936 qemu_mutex_init(&qemu_global_mutex
);
3937 qemu_mutex_lock(&qemu_global_mutex
);
3939 unblock_io_signals();
3940 qemu_thread_self(&io_thread
);
3945 static void qemu_wait_io_event(CPUState
*env
)
3947 while (!tcg_has_work())
3948 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3950 qemu_mutex_unlock(&qemu_global_mutex
);
3953 * Users of qemu_global_mutex can be starved, having no chance
3954 * to acquire it since this path will get to it first.
3955 * So use another lock to provide fairness.
3957 qemu_mutex_lock(&qemu_fair_mutex
);
3958 qemu_mutex_unlock(&qemu_fair_mutex
);
3960 qemu_mutex_lock(&qemu_global_mutex
);
3964 qemu_cond_signal(&qemu_pause_cond
);
3968 static int qemu_cpu_exec(CPUState
*env
);
3970 static void *kvm_cpu_thread_fn(void *arg
)
3972 CPUState
*env
= arg
;
3975 qemu_thread_self(env
->thread
);
3977 /* signal CPU creation */
3978 qemu_mutex_lock(&qemu_global_mutex
);
3980 qemu_cond_signal(&qemu_cpu_cond
);
3982 /* and wait for machine initialization */
3983 while (!qemu_system_ready
)
3984 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3987 if (cpu_can_run(env
))
3989 qemu_wait_io_event(env
);
3995 static void tcg_cpu_exec(void);
3997 static void *tcg_cpu_thread_fn(void *arg
)
3999 CPUState
*env
= arg
;
4002 qemu_thread_self(env
->thread
);
4004 /* signal CPU creation */
4005 qemu_mutex_lock(&qemu_global_mutex
);
4006 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4008 qemu_cond_signal(&qemu_cpu_cond
);
4010 /* and wait for machine initialization */
4011 while (!qemu_system_ready
)
4012 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
4016 qemu_wait_io_event(cur_cpu
);
4022 void qemu_cpu_kick(void *_env
)
4024 CPUState
*env
= _env
;
4025 qemu_cond_broadcast(env
->halt_cond
);
4027 qemu_thread_signal(env
->thread
, SIGUSR1
);
4030 int qemu_cpu_self(void *env
)
4032 return (cpu_single_env
!= NULL
);
4035 static void cpu_signal(int sig
)
4038 cpu_exit(cpu_single_env
);
4041 static void block_io_signals(void)
4044 struct sigaction sigact
;
4047 sigaddset(&set
, SIGUSR2
);
4048 sigaddset(&set
, SIGIO
);
4049 sigaddset(&set
, SIGALRM
);
4050 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
4053 sigaddset(&set
, SIGUSR1
);
4054 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
4056 memset(&sigact
, 0, sizeof(sigact
));
4057 sigact
.sa_handler
= cpu_signal
;
4058 sigaction(SIGUSR1
, &sigact
, NULL
);
4061 static void unblock_io_signals(void)
4066 sigaddset(&set
, SIGUSR2
);
4067 sigaddset(&set
, SIGIO
);
4068 sigaddset(&set
, SIGALRM
);
4069 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
4072 sigaddset(&set
, SIGUSR1
);
4073 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
4076 static void qemu_signal_lock(unsigned int msecs
)
4078 qemu_mutex_lock(&qemu_fair_mutex
);
4080 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
4081 qemu_thread_signal(tcg_cpu_thread
, SIGUSR1
);
4082 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
4085 qemu_mutex_unlock(&qemu_fair_mutex
);
4088 static void qemu_mutex_lock_iothread(void)
4090 if (kvm_enabled()) {
4091 qemu_mutex_lock(&qemu_fair_mutex
);
4092 qemu_mutex_lock(&qemu_global_mutex
);
4093 qemu_mutex_unlock(&qemu_fair_mutex
);
4095 qemu_signal_lock(100);
4098 static void qemu_mutex_unlock_iothread(void)
4100 qemu_mutex_unlock(&qemu_global_mutex
);
4103 static int all_vcpus_paused(void)
4105 CPUState
*penv
= first_cpu
;
4110 penv
= (CPUState
*)penv
->next_cpu
;
4116 static void pause_all_vcpus(void)
4118 CPUState
*penv
= first_cpu
;
4122 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4123 qemu_cpu_kick(penv
);
4124 penv
= (CPUState
*)penv
->next_cpu
;
4127 while (!all_vcpus_paused()) {
4128 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
4131 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4132 penv
= (CPUState
*)penv
->next_cpu
;
4137 static void resume_all_vcpus(void)
4139 CPUState
*penv
= first_cpu
;
4144 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4145 qemu_cpu_kick(penv
);
4146 penv
= (CPUState
*)penv
->next_cpu
;
4150 static void tcg_init_vcpu(void *_env
)
4152 CPUState
*env
= _env
;
4153 /* share a single thread for all cpus with TCG */
4154 if (!tcg_cpu_thread
) {
4155 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
4156 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
4157 qemu_cond_init(env
->halt_cond
);
4158 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
4159 while (env
->created
== 0)
4160 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
4161 tcg_cpu_thread
= env
->thread
;
4162 tcg_halt_cond
= env
->halt_cond
;
4164 env
->thread
= tcg_cpu_thread
;
4165 env
->halt_cond
= tcg_halt_cond
;
4169 static void kvm_start_vcpu(CPUState
*env
)
4172 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
4173 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
4174 qemu_cond_init(env
->halt_cond
);
4175 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
4176 while (env
->created
== 0)
4177 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
4180 void qemu_init_vcpu(void *_env
)
4182 CPUState
*env
= _env
;
4185 kvm_start_vcpu(env
);
4190 void qemu_notify_event(void)
4192 qemu_event_increment();
4195 void vm_stop(int reason
)
4198 qemu_thread_self(&me
);
4200 if (!qemu_thread_equal(&me
, &io_thread
)) {
4201 qemu_system_vmstop_request(reason
);
4203 * FIXME: should not return to device code in case
4204 * vm_stop() has been requested.
4206 if (cpu_single_env
) {
4207 cpu_exit(cpu_single_env
);
4208 cpu_single_env
->stop
= 1;
4219 static void host_main_loop_wait(int *timeout
)
4225 /* XXX: need to suppress polling by better using win32 events */
4227 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
4228 ret
|= pe
->func(pe
->opaque
);
4232 WaitObjects
*w
= &wait_objects
;
4234 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
4235 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
4236 if (w
->func
[ret
- WAIT_OBJECT_0
])
4237 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
4239 /* Check for additional signaled events */
4240 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
4242 /* Check if event is signaled */
4243 ret2
= WaitForSingleObject(w
->events
[i
], 0);
4244 if(ret2
== WAIT_OBJECT_0
) {
4246 w
->func
[i
](w
->opaque
[i
]);
4247 } else if (ret2
== WAIT_TIMEOUT
) {
4249 err
= GetLastError();
4250 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
4253 } else if (ret
== WAIT_TIMEOUT
) {
4255 err
= GetLastError();
4256 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
4263 static void host_main_loop_wait(int *timeout
)
4268 void main_loop_wait(int timeout
)
4270 IOHandlerRecord
*ioh
;
4271 fd_set rfds
, wfds
, xfds
;
4275 qemu_bh_update_timeout(&timeout
);
4277 host_main_loop_wait(&timeout
);
4279 /* poll any events */
4280 /* XXX: separate device handlers from system ones */
4285 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4289 (!ioh
->fd_read_poll
||
4290 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
4291 FD_SET(ioh
->fd
, &rfds
);
4295 if (ioh
->fd_write
) {
4296 FD_SET(ioh
->fd
, &wfds
);
4302 tv
.tv_sec
= timeout
/ 1000;
4303 tv
.tv_usec
= (timeout
% 1000) * 1000;
4305 #if defined(CONFIG_SLIRP)
4306 if (slirp_is_inited()) {
4307 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
4310 ret
= qemu_select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
4312 IOHandlerRecord
**pioh
;
4314 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4315 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
4316 ioh
->fd_read(ioh
->opaque
);
4317 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
4318 FD_CLR(ioh
->fd
, &rfds
);
4320 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
4321 ioh
->fd_write(ioh
->opaque
);
4325 /* remove deleted IO handlers */
4326 pioh
= &first_io_handler
;
4336 #if defined(CONFIG_SLIRP)
4337 if (slirp_is_inited()) {
4343 slirp_select_poll(&rfds
, &wfds
, &xfds
);
4347 /* rearm timer, if not periodic */
4348 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
4349 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
4350 qemu_rearm_alarm_timer(alarm_timer
);
4353 /* vm time timers */
4355 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
4356 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
4357 qemu_get_clock(vm_clock
));
4360 /* real time timers */
4361 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
4362 qemu_get_clock(rt_clock
));
4364 /* Check bottom-halves last in case any of the earlier events triggered
4370 static int qemu_cpu_exec(CPUState
*env
)
4373 #ifdef CONFIG_PROFILER
4377 #ifdef CONFIG_PROFILER
4378 ti
= profile_getclock();
4383 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
4384 env
->icount_decr
.u16
.low
= 0;
4385 env
->icount_extra
= 0;
4386 count
= qemu_next_deadline();
4387 count
= (count
+ (1 << icount_time_shift
) - 1)
4388 >> icount_time_shift
;
4389 qemu_icount
+= count
;
4390 decr
= (count
> 0xffff) ? 0xffff : count
;
4392 env
->icount_decr
.u16
.low
= decr
;
4393 env
->icount_extra
= count
;
4395 ret
= cpu_exec(env
);
4396 #ifdef CONFIG_PROFILER
4397 qemu_time
+= profile_getclock() - ti
;
4400 /* Fold pending instructions back into the
4401 instruction counter, and clear the interrupt flag. */
4402 qemu_icount
-= (env
->icount_decr
.u16
.low
4403 + env
->icount_extra
);
4404 env
->icount_decr
.u32
= 0;
4405 env
->icount_extra
= 0;
4410 static void tcg_cpu_exec(void)
4414 if (next_cpu
== NULL
)
4415 next_cpu
= first_cpu
;
4416 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
4417 CPUState
*env
= cur_cpu
= next_cpu
;
4421 if (timer_alarm_pending
) {
4422 timer_alarm_pending
= 0;
4425 if (cpu_can_run(env
))
4426 ret
= qemu_cpu_exec(env
);
4427 if (ret
== EXCP_DEBUG
) {
4428 gdb_set_stop_cpu(env
);
4429 debug_requested
= 1;
4435 static int cpu_has_work(CPUState
*env
)
4443 if (qemu_cpu_has_work(env
))
4448 static int tcg_has_work(void)
4452 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4453 if (cpu_has_work(env
))
4458 static int qemu_calculate_timeout(void)
4464 else if (tcg_has_work())
4466 else if (!use_icount
)
4469 /* XXX: use timeout computed from timers */
4472 /* Advance virtual time to the next event. */
4473 if (use_icount
== 1) {
4474 /* When not using an adaptive execution frequency
4475 we tend to get badly out of sync with real time,
4476 so just delay for a reasonable amount of time. */
4479 delta
= cpu_get_icount() - cpu_get_clock();
4482 /* If virtual time is ahead of real time then just
4484 timeout
= (delta
/ 1000000) + 1;
4486 /* Wait for either IO to occur or the next
4488 add
= qemu_next_deadline();
4489 /* We advance the timer before checking for IO.
4490 Limit the amount we advance so that early IO
4491 activity won't get the guest too far ahead. */
4495 add
= (add
+ (1 << icount_time_shift
) - 1)
4496 >> icount_time_shift
;
4498 timeout
= delta
/ 1000000;
4507 static int vm_can_run(void)
4509 if (powerdown_requested
)
4511 if (reset_requested
)
4513 if (shutdown_requested
)
4515 if (debug_requested
)
4520 static void main_loop(void)
4524 if (kvm_enabled()) {
4526 cpu_disable_ticks();
4530 #ifdef CONFIG_IOTHREAD
4531 qemu_system_ready
= 1;
4532 qemu_cond_broadcast(&qemu_system_cond
);
4537 #ifdef CONFIG_PROFILER
4540 #ifndef CONFIG_IOTHREAD
4543 #ifdef CONFIG_PROFILER
4544 ti
= profile_getclock();
4546 #ifdef CONFIG_IOTHREAD
4547 main_loop_wait(1000);
4549 main_loop_wait(qemu_calculate_timeout());
4551 #ifdef CONFIG_PROFILER
4552 dev_time
+= profile_getclock() - ti
;
4554 } while (vm_can_run());
4556 if (qemu_debug_requested())
4557 vm_stop(EXCP_DEBUG
);
4558 if (qemu_shutdown_requested()) {
4565 if (qemu_reset_requested()) {
4567 qemu_system_reset();
4570 if (qemu_powerdown_requested())
4571 qemu_system_powerdown();
4572 if ((r
= qemu_vmstop_requested()))
4578 static void version(void)
4580 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4583 static void help(int exitcode
)
4586 printf("usage: %s [options] [disk_image]\n"
4588 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4590 #define DEF(option, opt_arg, opt_enum, opt_help) \
4592 #define DEFHEADING(text) stringify(text) "\n"
4593 #include "qemu-options.h"
4598 "During emulation, the following keys are useful:\n"
4599 "ctrl-alt-f toggle full screen\n"
4600 "ctrl-alt-n switch to virtual console 'n'\n"
4601 "ctrl-alt toggle mouse and keyboard grab\n"
4603 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4608 DEFAULT_NETWORK_SCRIPT
,
4609 DEFAULT_NETWORK_DOWN_SCRIPT
,
4611 DEFAULT_GDBSTUB_PORT
,
4616 #define HAS_ARG 0x0001
4619 #define DEF(option, opt_arg, opt_enum, opt_help) \
4621 #define DEFHEADING(text)
4622 #include "qemu-options.h"
4628 typedef struct QEMUOption
{
4634 static const QEMUOption qemu_options
[] = {
4635 { "h", 0, QEMU_OPTION_h
},
4636 #define DEF(option, opt_arg, opt_enum, opt_help) \
4637 { option, opt_arg, opt_enum },
4638 #define DEFHEADING(text)
4639 #include "qemu-options.h"
4647 struct soundhw soundhw
[] = {
4648 #ifdef HAS_AUDIO_CHOICE
4649 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4655 { .init_isa
= pcspk_audio_init
}
4662 "Creative Sound Blaster 16",
4665 { .init_isa
= SB16_init
}
4669 #ifdef CONFIG_CS4231A
4675 { .init_isa
= cs4231a_init
}
4683 "Yamaha YMF262 (OPL3)",
4685 "Yamaha YM3812 (OPL2)",
4689 { .init_isa
= Adlib_init
}
4696 "Gravis Ultrasound GF1",
4699 { .init_isa
= GUS_init
}
4706 "Intel 82801AA AC97 Audio",
4709 { .init_pci
= ac97_init
}
4713 #ifdef CONFIG_ES1370
4716 "ENSONIQ AudioPCI ES1370",
4719 { .init_pci
= es1370_init
}
4723 #endif /* HAS_AUDIO_CHOICE */
4725 { NULL
, NULL
, 0, 0, { NULL
} }
4728 static void select_soundhw (const char *optarg
)
4732 if (*optarg
== '?') {
4735 printf ("Valid sound card names (comma separated):\n");
4736 for (c
= soundhw
; c
->name
; ++c
) {
4737 printf ("%-11s %s\n", c
->name
, c
->descr
);
4739 printf ("\n-soundhw all will enable all of the above\n");
4740 exit (*optarg
!= '?');
4748 if (!strcmp (optarg
, "all")) {
4749 for (c
= soundhw
; c
->name
; ++c
) {
4757 e
= strchr (p
, ',');
4758 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4760 for (c
= soundhw
; c
->name
; ++c
) {
4761 if (!strncmp (c
->name
, p
, l
)) {
4770 "Unknown sound card name (too big to show)\n");
4773 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4778 p
+= l
+ (e
!= NULL
);
4782 goto show_valid_cards
;
4787 static void select_vgahw (const char *p
)
4791 cirrus_vga_enabled
= 0;
4792 std_vga_enabled
= 0;
4795 if (strstart(p
, "std", &opts
)) {
4796 std_vga_enabled
= 1;
4797 } else if (strstart(p
, "cirrus", &opts
)) {
4798 cirrus_vga_enabled
= 1;
4799 } else if (strstart(p
, "vmware", &opts
)) {
4801 } else if (strstart(p
, "xenfb", &opts
)) {
4803 } else if (!strstart(p
, "none", &opts
)) {
4805 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4809 const char *nextopt
;
4811 if (strstart(opts
, ",retrace=", &nextopt
)) {
4813 if (strstart(opts
, "dumb", &nextopt
))
4814 vga_retrace_method
= VGA_RETRACE_DUMB
;
4815 else if (strstart(opts
, "precise", &nextopt
))
4816 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4817 else goto invalid_vga
;
4818 } else goto invalid_vga
;
4824 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4826 exit(STATUS_CONTROL_C_EXIT
);
4831 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4835 if(strlen(str
) != 36)
4838 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4839 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4840 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4846 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4852 #define MAX_NET_CLIENTS 32
4856 #define HUGETLBFS_MAGIC 0x958458f6
4858 static long gethugepagesize(const char *path
)
4864 ret
= statfs(path
, &fs
);
4865 } while (ret
!= 0 && errno
== EINTR
);
4872 if (fs
.f_type
!= HUGETLBFS_MAGIC
)
4873 fprintf(stderr
, "Warning: path not on HugeTLBFS: %s\n", path
);
4878 static void *alloc_mem_area(size_t memory
, unsigned long *len
, const char *path
)
4887 if (!kvm_has_sync_mmu()) {
4888 fprintf(stderr
, "host lacks mmu notifiers, disabling --mem-path\n");
4892 if (asprintf(&filename
, "%s/kvm.XXXXXX", path
) == -1)
4895 hpagesize
= gethugepagesize(path
);
4899 fd
= mkstemp(filename
);
4908 memory
= (memory
+hpagesize
-1) & ~(hpagesize
-1);
4911 * ftruncate is not supported by hugetlbfs in older
4912 * hosts, so don't bother checking for errors.
4913 * If anything goes wrong with it under other filesystems,
4916 ftruncate(fd
, memory
);
4919 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4920 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4921 * to sidestep this quirk.
4923 flags
= mem_prealloc
? MAP_POPULATE
|MAP_SHARED
: MAP_PRIVATE
;
4924 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, flags
, fd
, 0);
4926 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
, fd
, 0);
4928 if (area
== MAP_FAILED
) {
4929 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4940 static void termsig_handler(int signal
)
4942 qemu_system_shutdown_request();
4945 static void termsig_setup(void)
4947 struct sigaction act
;
4949 memset(&act
, 0, sizeof(act
));
4950 act
.sa_handler
= termsig_handler
;
4951 sigaction(SIGINT
, &act
, NULL
);
4952 sigaction(SIGHUP
, &act
, NULL
);
4953 sigaction(SIGTERM
, &act
, NULL
);
4958 int main(int argc
, char **argv
, char **envp
)
4960 const char *gdbstub_dev
= NULL
;
4961 uint32_t boot_devices_bitmap
= 0;
4963 int snapshot
, linux_boot
, net_boot
;
4964 const char *initrd_filename
;
4965 const char *kernel_filename
, *kernel_cmdline
;
4966 const char *boot_devices
= "";
4968 DisplayChangeListener
*dcl
;
4969 int cyls
, heads
, secs
, translation
;
4970 const char *net_clients
[MAX_NET_CLIENTS
];
4972 const char *bt_opts
[MAX_BT_CMDLINE
];
4976 const char *r
, *optarg
;
4977 CharDriverState
*monitor_hd
= NULL
;
4978 const char *monitor_device
;
4979 const char *serial_devices
[MAX_SERIAL_PORTS
];
4980 int serial_device_index
;
4981 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
4982 int parallel_device_index
;
4983 const char *virtio_consoles
[MAX_VIRTIO_CONSOLES
];
4984 int virtio_console_index
;
4985 const char *loadvm
= NULL
;
4986 QEMUMachine
*machine
;
4987 const char *cpu_model
;
4988 const char *usb_devices
[MAX_USB_CMDLINE
];
4989 int usb_devices_index
;
4994 const char *pid_file
= NULL
;
4995 const char *incoming
= NULL
;
4998 struct passwd
*pwd
= NULL
;
4999 const char *chroot_dir
= NULL
;
5000 const char *run_as
= NULL
;
5004 qemu_cache_utils_init(envp
);
5006 LIST_INIT (&vm_change_state_head
);
5009 struct sigaction act
;
5010 sigfillset(&act
.sa_mask
);
5012 act
.sa_handler
= SIG_IGN
;
5013 sigaction(SIGPIPE
, &act
, NULL
);
5016 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
5017 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5018 QEMU to run on a single CPU */
5023 h
= GetCurrentProcess();
5024 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
5025 for(i
= 0; i
< 32; i
++) {
5026 if (mask
& (1 << i
))
5031 SetProcessAffinityMask(h
, mask
);
5037 register_machines();
5038 machine
= first_machine
;
5040 initrd_filename
= NULL
;
5042 vga_ram_size
= VGA_RAM_SIZE
;
5046 kernel_filename
= NULL
;
5047 kernel_cmdline
= "";
5048 cyls
= heads
= secs
= 0;
5049 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5050 monitor_device
= "vc:80Cx24C";
5052 serial_devices
[0] = "vc:80Cx24C";
5053 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
5054 serial_devices
[i
] = NULL
;
5055 serial_device_index
= 0;
5057 parallel_devices
[0] = "vc:80Cx24C";
5058 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
5059 parallel_devices
[i
] = NULL
;
5060 parallel_device_index
= 0;
5062 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++)
5063 virtio_consoles
[i
] = NULL
;
5064 virtio_console_index
= 0;
5066 for (i
= 0; i
< MAX_NODES
; i
++) {
5068 node_cpumask
[i
] = 0;
5071 usb_devices_index
= 0;
5072 assigned_devices_index
= 0;
5086 register_watchdogs();
5094 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
5096 const QEMUOption
*popt
;
5099 /* Treat --foo the same as -foo. */
5102 popt
= qemu_options
;
5105 fprintf(stderr
, "%s: invalid option -- '%s'\n",
5109 if (!strcmp(popt
->name
, r
+ 1))
5113 if (popt
->flags
& HAS_ARG
) {
5114 if (optind
>= argc
) {
5115 fprintf(stderr
, "%s: option '%s' requires an argument\n",
5119 optarg
= argv
[optind
++];
5124 switch(popt
->index
) {
5126 machine
= find_machine(optarg
);
5129 printf("Supported machines are:\n");
5130 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5131 printf("%-10s %s%s\n",
5133 m
== first_machine
? " (default)" : "");
5135 exit(*optarg
!= '?');
5138 case QEMU_OPTION_cpu
:
5139 /* hw initialization will check this */
5140 if (*optarg
== '?') {
5141 /* XXX: implement xxx_cpu_list for targets that still miss it */
5142 #if defined(cpu_list)
5143 cpu_list(stdout
, &fprintf
);
5150 case QEMU_OPTION_initrd
:
5151 initrd_filename
= optarg
;
5153 case QEMU_OPTION_hda
:
5155 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
5157 hda_index
= drive_add(optarg
, HD_ALIAS
5158 ",cyls=%d,heads=%d,secs=%d%s",
5159 0, cyls
, heads
, secs
,
5160 translation
== BIOS_ATA_TRANSLATION_LBA
?
5162 translation
== BIOS_ATA_TRANSLATION_NONE
?
5163 ",trans=none" : "");
5165 case QEMU_OPTION_hdb
:
5166 case QEMU_OPTION_hdc
:
5167 case QEMU_OPTION_hdd
:
5168 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
5170 case QEMU_OPTION_drive
:
5171 drive_add(NULL
, "%s", optarg
);
5173 case QEMU_OPTION_mtdblock
:
5174 drive_add(optarg
, MTD_ALIAS
);
5176 case QEMU_OPTION_sd
:
5177 drive_add(optarg
, SD_ALIAS
);
5179 case QEMU_OPTION_pflash
:
5180 drive_add(optarg
, PFLASH_ALIAS
);
5182 case QEMU_OPTION_snapshot
:
5185 case QEMU_OPTION_hdachs
:
5189 cyls
= strtol(p
, (char **)&p
, 0);
5190 if (cyls
< 1 || cyls
> 16383)
5195 heads
= strtol(p
, (char **)&p
, 0);
5196 if (heads
< 1 || heads
> 16)
5201 secs
= strtol(p
, (char **)&p
, 0);
5202 if (secs
< 1 || secs
> 63)
5206 if (!strcmp(p
, "none"))
5207 translation
= BIOS_ATA_TRANSLATION_NONE
;
5208 else if (!strcmp(p
, "lba"))
5209 translation
= BIOS_ATA_TRANSLATION_LBA
;
5210 else if (!strcmp(p
, "auto"))
5211 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5214 } else if (*p
!= '\0') {
5216 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5219 if (hda_index
!= -1)
5220 snprintf(drives_opt
[hda_index
].opt
,
5221 sizeof(drives_opt
[hda_index
].opt
),
5222 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
5223 0, cyls
, heads
, secs
,
5224 translation
== BIOS_ATA_TRANSLATION_LBA
?
5226 translation
== BIOS_ATA_TRANSLATION_NONE
?
5227 ",trans=none" : "");
5230 case QEMU_OPTION_numa
:
5231 if (nb_numa_nodes
>= MAX_NODES
) {
5232 fprintf(stderr
, "qemu: too many NUMA nodes\n");
5237 case QEMU_OPTION_nographic
:
5240 #ifdef CONFIG_CURSES
5241 case QEMU_OPTION_curses
:
5245 case QEMU_OPTION_portrait
:
5248 case QEMU_OPTION_kernel
:
5249 kernel_filename
= optarg
;
5251 case QEMU_OPTION_append
:
5252 kernel_cmdline
= optarg
;
5254 case QEMU_OPTION_cdrom
:
5255 drive_add(optarg
, CDROM_ALIAS
);
5257 case QEMU_OPTION_boot
:
5258 boot_devices
= optarg
;
5259 /* We just do some generic consistency checks */
5261 /* Could easily be extended to 64 devices if needed */
5264 boot_devices_bitmap
= 0;
5265 for (p
= boot_devices
; *p
!= '\0'; p
++) {
5266 /* Allowed boot devices are:
5267 * a b : floppy disk drives
5268 * c ... f : IDE disk drives
5269 * g ... m : machine implementation dependant drives
5270 * n ... p : network devices
5271 * It's up to each machine implementation to check
5272 * if the given boot devices match the actual hardware
5273 * implementation and firmware features.
5275 if (*p
< 'a' || *p
> 'q') {
5276 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
5279 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
5281 "Boot device '%c' was given twice\n",*p
);
5284 boot_devices_bitmap
|= 1 << (*p
- 'a');
5288 case QEMU_OPTION_fda
:
5289 case QEMU_OPTION_fdb
:
5290 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
5293 case QEMU_OPTION_no_fd_bootchk
:
5297 case QEMU_OPTION_net
:
5298 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
5299 fprintf(stderr
, "qemu: too many network clients\n");
5302 net_clients
[nb_net_clients
] = optarg
;
5306 case QEMU_OPTION_tftp
:
5307 tftp_prefix
= optarg
;
5309 case QEMU_OPTION_bootp
:
5310 bootp_filename
= optarg
;
5313 case QEMU_OPTION_smb
:
5314 net_slirp_smb(optarg
);
5317 case QEMU_OPTION_redir
:
5318 net_slirp_redir(NULL
, optarg
);
5321 case QEMU_OPTION_bt
:
5322 if (nb_bt_opts
>= MAX_BT_CMDLINE
) {
5323 fprintf(stderr
, "qemu: too many bluetooth options\n");
5326 bt_opts
[nb_bt_opts
++] = optarg
;
5329 case QEMU_OPTION_audio_help
:
5333 case QEMU_OPTION_soundhw
:
5334 select_soundhw (optarg
);
5340 case QEMU_OPTION_version
:
5344 case QEMU_OPTION_m
: {
5348 value
= strtoul(optarg
, &ptr
, 10);
5350 case 0: case 'M': case 'm':
5357 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5361 /* On 32-bit hosts, QEMU is limited by virtual address space */
5362 if (value
> (2047 << 20)
5363 #ifndef CONFIG_KQEMU
5364 && HOST_LONG_BITS
== 32
5367 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5370 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5371 fprintf(stderr
, "qemu: ram size too large\n");
5380 const CPULogItem
*item
;
5382 mask
= cpu_str_to_log_mask(optarg
);
5384 printf("Log items (comma separated):\n");
5385 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5386 printf("%-10s %s\n", item
->name
, item
->help
);
5394 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5396 case QEMU_OPTION_gdb
:
5397 gdbstub_dev
= optarg
;
5402 case QEMU_OPTION_bios
:
5405 case QEMU_OPTION_singlestep
:
5413 keyboard_layout
= optarg
;
5416 case QEMU_OPTION_localtime
:
5419 case QEMU_OPTION_vga
:
5420 select_vgahw (optarg
);
5422 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5428 w
= strtol(p
, (char **)&p
, 10);
5431 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5437 h
= strtol(p
, (char **)&p
, 10);
5442 depth
= strtol(p
, (char **)&p
, 10);
5443 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5444 depth
!= 24 && depth
!= 32)
5446 } else if (*p
== '\0') {
5447 depth
= graphic_depth
;
5454 graphic_depth
= depth
;
5458 case QEMU_OPTION_echr
:
5461 term_escape_char
= strtol(optarg
, &r
, 0);
5463 printf("Bad argument to echr\n");
5466 case QEMU_OPTION_monitor
:
5467 monitor_device
= optarg
;
5469 case QEMU_OPTION_serial
:
5470 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
5471 fprintf(stderr
, "qemu: too many serial ports\n");
5474 serial_devices
[serial_device_index
] = optarg
;
5475 serial_device_index
++;
5477 case QEMU_OPTION_watchdog
:
5478 i
= select_watchdog(optarg
);
5480 exit (i
== 1 ? 1 : 0);
5482 case QEMU_OPTION_watchdog_action
:
5483 if (select_watchdog_action(optarg
) == -1) {
5484 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5488 case QEMU_OPTION_virtiocon
:
5489 if (virtio_console_index
>= MAX_VIRTIO_CONSOLES
) {
5490 fprintf(stderr
, "qemu: too many virtio consoles\n");
5493 virtio_consoles
[virtio_console_index
] = optarg
;
5494 virtio_console_index
++;
5496 case QEMU_OPTION_parallel
:
5497 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
5498 fprintf(stderr
, "qemu: too many parallel ports\n");
5501 parallel_devices
[parallel_device_index
] = optarg
;
5502 parallel_device_index
++;
5504 case QEMU_OPTION_loadvm
:
5507 case QEMU_OPTION_full_screen
:
5511 case QEMU_OPTION_no_frame
:
5514 case QEMU_OPTION_alt_grab
:
5517 case QEMU_OPTION_no_quit
:
5520 case QEMU_OPTION_sdl
:
5524 case QEMU_OPTION_pidfile
:
5528 case QEMU_OPTION_win2k_hack
:
5529 win2k_install_hack
= 1;
5531 case QEMU_OPTION_rtc_td_hack
:
5534 case QEMU_OPTION_acpitable
:
5535 if(acpi_table_add(optarg
) < 0) {
5536 fprintf(stderr
, "Wrong acpi table provided\n");
5540 case QEMU_OPTION_smbios
:
5541 if(smbios_entry_add(optarg
) < 0) {
5542 fprintf(stderr
, "Wrong smbios provided\n");
5548 case QEMU_OPTION_no_kqemu
:
5551 case QEMU_OPTION_kernel_kqemu
:
5556 case QEMU_OPTION_enable_kvm
:
5564 case QEMU_OPTION_no_kvm
:
5567 case QEMU_OPTION_no_kvm_irqchip
: {
5572 case QEMU_OPTION_no_kvm_pit
: {
5576 case QEMU_OPTION_no_kvm_pit_reinjection
: {
5577 kvm_pit_reinject
= 0;
5580 case QEMU_OPTION_enable_nesting
: {
5584 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5585 case QEMU_OPTION_pcidevice
:
5586 if (assigned_devices_index
>= MAX_DEV_ASSIGN_CMDLINE
) {
5587 fprintf(stderr
, "Too many assigned devices\n");
5590 assigned_devices
[assigned_devices_index
] = optarg
;
5591 assigned_devices_index
++;
5595 case QEMU_OPTION_usb
:
5598 case QEMU_OPTION_usbdevice
:
5600 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
5601 fprintf(stderr
, "Too many USB devices\n");
5604 usb_devices
[usb_devices_index
] = optarg
;
5605 usb_devices_index
++;
5607 case QEMU_OPTION_smp
:
5608 smp_cpus
= atoi(optarg
);
5610 fprintf(stderr
, "Invalid number of CPUs\n");
5614 case QEMU_OPTION_vnc
:
5615 vnc_display
= optarg
;
5618 case QEMU_OPTION_no_acpi
:
5621 case QEMU_OPTION_no_hpet
:
5625 case QEMU_OPTION_no_reboot
:
5628 case QEMU_OPTION_no_shutdown
:
5631 case QEMU_OPTION_show_cursor
:
5634 case QEMU_OPTION_uuid
:
5635 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5636 fprintf(stderr
, "Fail to parse UUID string."
5637 " Wrong format.\n");
5642 case QEMU_OPTION_daemonize
:
5646 case QEMU_OPTION_option_rom
:
5647 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5648 fprintf(stderr
, "Too many option ROMs\n");
5651 option_rom
[nb_option_roms
] = optarg
;
5654 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5655 case QEMU_OPTION_semihosting
:
5656 semihosting_enabled
= 1;
5659 case QEMU_OPTION_tdf
:
5662 case QEMU_OPTION_kvm_shadow_memory
:
5663 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
5665 case QEMU_OPTION_mempath
:
5669 case QEMU_OPTION_mem_prealloc
:
5670 mem_prealloc
= !mem_prealloc
;
5673 case QEMU_OPTION_name
:
5676 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5677 case QEMU_OPTION_prom_env
:
5678 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5679 fprintf(stderr
, "Too many prom variables\n");
5682 prom_envs
[nb_prom_envs
] = optarg
;
5687 case QEMU_OPTION_old_param
:
5691 case QEMU_OPTION_clock
:
5692 configure_alarms(optarg
);
5694 case QEMU_OPTION_startdate
:
5697 time_t rtc_start_date
;
5698 if (!strcmp(optarg
, "now")) {
5699 rtc_date_offset
= -1;
5701 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
5709 } else if (sscanf(optarg
, "%d-%d-%d",
5712 &tm
.tm_mday
) == 3) {
5721 rtc_start_date
= mktimegm(&tm
);
5722 if (rtc_start_date
== -1) {
5724 fprintf(stderr
, "Invalid date format. Valid format are:\n"
5725 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5728 rtc_date_offset
= time(NULL
) - rtc_start_date
;
5732 case QEMU_OPTION_tb_size
:
5733 tb_size
= strtol(optarg
, NULL
, 0);
5737 case QEMU_OPTION_icount
:
5739 if (strcmp(optarg
, "auto") == 0) {
5740 icount_time_shift
= -1;
5742 icount_time_shift
= strtol(optarg
, NULL
, 0);
5745 case QEMU_OPTION_incoming
:
5749 case QEMU_OPTION_chroot
:
5750 chroot_dir
= optarg
;
5752 case QEMU_OPTION_runas
:
5755 case QEMU_OPTION_nvram
:
5760 case QEMU_OPTION_xen_domid
:
5761 xen_domid
= atoi(optarg
);
5763 case QEMU_OPTION_xen_create
:
5764 xen_mode
= XEN_CREATE
;
5766 case QEMU_OPTION_xen_attach
:
5767 xen_mode
= XEN_ATTACH
;
5774 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5775 if (kvm_allowed
&& kqemu_allowed
) {
5777 "You can not enable both KVM and kqemu at the same time\n");
5782 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5783 if (smp_cpus
> machine
->max_cpus
) {
5784 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5785 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5791 if (serial_device_index
== 0)
5792 serial_devices
[0] = "stdio";
5793 if (parallel_device_index
== 0)
5794 parallel_devices
[0] = "null";
5795 if (strncmp(monitor_device
, "vc", 2) == 0)
5796 monitor_device
= "stdio";
5803 if (pipe(fds
) == -1)
5814 len
= read(fds
[0], &status
, 1);
5815 if (len
== -1 && (errno
== EINTR
))
5820 else if (status
== 1) {
5821 fprintf(stderr
, "Could not acquire pidfile\n");
5838 signal(SIGTSTP
, SIG_IGN
);
5839 signal(SIGTTOU
, SIG_IGN
);
5840 signal(SIGTTIN
, SIG_IGN
);
5844 if (kvm_enabled()) {
5845 if (kvm_qemu_init() < 0) {
5846 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
5847 #ifdef NO_CPU_EMULATION
5848 fprintf(stderr
, "Compiled with --disable-cpu-emulation, exiting.\n");
5856 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5859 write(fds
[1], &status
, 1);
5861 fprintf(stderr
, "Could not acquire pid file\n");
5870 if (qemu_init_main_loop()) {
5871 fprintf(stderr
, "qemu_init_main_loop failed\n");
5874 linux_boot
= (kernel_filename
!= NULL
);
5875 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5877 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5878 fprintf(stderr
, "-append only allowed with -kernel option\n");
5882 if (!linux_boot
&& initrd_filename
!= NULL
) {
5883 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5887 /* boot to floppy or the default cd if no hard disk defined yet */
5888 if (!boot_devices
[0]) {
5889 boot_devices
= "cad";
5891 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5894 if (init_timer_alarm() < 0) {
5895 fprintf(stderr
, "could not initialize alarm timer\n");
5898 if (use_icount
&& icount_time_shift
< 0) {
5900 /* 125MIPS seems a reasonable initial guess at the guest speed.
5901 It will be corrected fairly quickly anyway. */
5902 icount_time_shift
= 3;
5903 init_icount_adjust();
5910 /* init network clients */
5911 if (nb_net_clients
== 0) {
5912 /* if no clients, we use a default config */
5913 net_clients
[nb_net_clients
++] = "nic";
5915 net_clients
[nb_net_clients
++] = "user";
5919 for(i
= 0;i
< nb_net_clients
; i
++) {
5920 if (net_client_parse(net_clients
[i
]) < 0)
5926 /* XXX: this should be moved in the PC machine instantiation code */
5927 if (net_boot
!= 0) {
5929 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
5930 const char *model
= nd_table
[i
].model
;
5932 if (net_boot
& (1 << i
)) {
5935 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
5936 if (get_image_size(buf
) > 0) {
5937 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5938 fprintf(stderr
, "Too many option ROMs\n");
5941 option_rom
[nb_option_roms
] = strdup(buf
);
5948 fprintf(stderr
, "No valid PXE rom found for network device\n");
5954 /* init the bluetooth world */
5955 for (i
= 0; i
< nb_bt_opts
; i
++)
5956 if (bt_parse(bt_opts
[i
]))
5959 /* init the memory */
5961 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5963 if (kvm_enabled()) {
5964 if (kvm_qemu_create_context() < 0) {
5965 fprintf(stderr
, "Could not create KVM context\n");
5971 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5972 guest ram allocation. It needs to go away. */
5973 if (kqemu_allowed
) {
5974 kqemu_phys_ram_size
= ram_size
+ VGA_RAM_SIZE
+ 4 * 1024 * 1024;
5975 kqemu_phys_ram_base
= qemu_vmalloc(kqemu_phys_ram_size
);
5976 if (!kqemu_phys_ram_base
) {
5977 fprintf(stderr
, "Could not allocate physical memory\n");
5983 /* init the dynamic translator */
5984 cpu_exec_init_all(tb_size
* 1024 * 1024);
5989 /* we always create the cdrom drive, even if no disk is there */
5991 if (nb_drives_opt
< MAX_DRIVES
)
5992 drive_add(NULL
, CDROM_ALIAS
);
5994 /* we always create at least one floppy */
5996 if (nb_drives_opt
< MAX_DRIVES
)
5997 drive_add(NULL
, FD_ALIAS
, 0);
5999 /* we always create one sd slot, even if no card is in it */
6001 if (nb_drives_opt
< MAX_DRIVES
)
6002 drive_add(NULL
, SD_ALIAS
);
6004 /* open the virtual block devices
6005 * note that migration with device
6006 * hot add/remove is broken.
6008 for(i
= 0; i
< nb_drives_opt
; i
++)
6009 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
6012 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
6013 register_savevm_live("ram", 0, 3, ram_save_live
, NULL
, ram_load
, NULL
);
6016 /* must be after terminal init, SDL library changes signal handlers */
6020 /* Maintain compatibility with multiple stdio monitors */
6021 if (!strcmp(monitor_device
,"stdio")) {
6022 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6023 const char *devname
= serial_devices
[i
];
6024 if (devname
&& !strcmp(devname
,"mon:stdio")) {
6025 monitor_device
= NULL
;
6027 } else if (devname
&& !strcmp(devname
,"stdio")) {
6028 monitor_device
= NULL
;
6029 serial_devices
[i
] = "mon:stdio";
6035 if (nb_numa_nodes
> 0) {
6038 if (nb_numa_nodes
> smp_cpus
) {
6039 nb_numa_nodes
= smp_cpus
;
6042 /* If no memory size if given for any node, assume the default case
6043 * and distribute the available memory equally across all nodes
6045 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6046 if (node_mem
[i
] != 0)
6049 if (i
== nb_numa_nodes
) {
6050 uint64_t usedmem
= 0;
6052 /* On Linux, the each node's border has to be 8MB aligned,
6053 * the final node gets the rest.
6055 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
6056 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
6057 usedmem
+= node_mem
[i
];
6059 node_mem
[i
] = ram_size
- usedmem
;
6062 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6063 if (node_cpumask
[i
] != 0)
6066 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6067 * must cope with this anyway, because there are BIOSes out there in
6068 * real machines which also use this scheme.
6070 if (i
== nb_numa_nodes
) {
6071 for (i
= 0; i
< smp_cpus
; i
++) {
6072 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
6078 if (kvm_enabled()) {
6081 ret
= kvm_init(smp_cpus
);
6083 fprintf(stderr
, "failed to initialize KVM\n");
6089 if (monitor_device
) {
6090 monitor_hd
= qemu_chr_open("monitor", monitor_device
, NULL
);
6092 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
6097 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6098 const char *devname
= serial_devices
[i
];
6099 if (devname
&& strcmp(devname
, "none")) {
6101 snprintf(label
, sizeof(label
), "serial%d", i
);
6102 serial_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6103 if (!serial_hds
[i
]) {
6104 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
6111 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
6112 const char *devname
= parallel_devices
[i
];
6113 if (devname
&& strcmp(devname
, "none")) {
6115 snprintf(label
, sizeof(label
), "parallel%d", i
);
6116 parallel_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6117 if (!parallel_hds
[i
]) {
6118 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
6125 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
6126 const char *devname
= virtio_consoles
[i
];
6127 if (devname
&& strcmp(devname
, "none")) {
6129 snprintf(label
, sizeof(label
), "virtcon%d", i
);
6130 virtcon_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6131 if (!virtcon_hds
[i
]) {
6132 fprintf(stderr
, "qemu: could not open virtio console '%s'\n",
6142 machine
->init(ram_size
, vga_ram_size
, boot_devices
,
6143 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
6146 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
6147 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6148 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
6154 current_machine
= machine
;
6156 /* Set KVM's vcpu state to qemu's initial CPUState. */
6157 if (kvm_enabled()) {
6160 ret
= kvm_sync_vcpus();
6162 fprintf(stderr
, "failed to initialize vcpus\n");
6167 /* init USB devices */
6169 for(i
= 0; i
< usb_devices_index
; i
++) {
6170 if (usb_device_add(usb_devices
[i
], 0) < 0) {
6171 fprintf(stderr
, "Warning: could not add USB device %s\n",
6178 dumb_display_init();
6179 /* just use the first displaystate for the moment */
6184 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
6188 #if defined(CONFIG_CURSES)
6190 /* At the moment curses cannot be used with other displays */
6191 curses_display_init(ds
, full_screen
);
6195 if (vnc_display
!= NULL
) {
6196 vnc_display_init(ds
);
6197 if (vnc_display_open(ds
, vnc_display
) < 0)
6200 #if defined(CONFIG_SDL)
6201 if (sdl
|| !vnc_display
)
6202 sdl_display_init(ds
, full_screen
, no_frame
);
6203 #elif defined(CONFIG_COCOA)
6204 if (sdl
|| !vnc_display
)
6205 cocoa_display_init(ds
, full_screen
);
6211 dcl
= ds
->listeners
;
6212 while (dcl
!= NULL
) {
6213 if (dcl
->dpy_refresh
!= NULL
) {
6214 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
6215 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
6220 if (nographic
|| (vnc_display
&& !sdl
)) {
6221 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
6222 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
6225 text_consoles_set_display(display_state
);
6226 qemu_chr_initial_reset();
6228 if (monitor_device
&& monitor_hd
)
6229 monitor_init(monitor_hd
, MONITOR_USE_READLINE
| MONITOR_IS_DEFAULT
);
6231 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6232 const char *devname
= serial_devices
[i
];
6233 if (devname
&& strcmp(devname
, "none")) {
6235 snprintf(label
, sizeof(label
), "serial%d", i
);
6236 if (strstart(devname
, "vc", 0))
6237 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
6241 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
6242 const char *devname
= parallel_devices
[i
];
6243 if (devname
&& strcmp(devname
, "none")) {
6245 snprintf(label
, sizeof(label
), "parallel%d", i
);
6246 if (strstart(devname
, "vc", 0))
6247 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
6251 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
6252 const char *devname
= virtio_consoles
[i
];
6253 if (virtcon_hds
[i
] && devname
) {
6255 snprintf(label
, sizeof(label
), "virtcon%d", i
);
6256 if (strstart(devname
, "vc", 0))
6257 qemu_chr_printf(virtcon_hds
[i
], "virtio console%d\r\n", i
);
6261 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
6262 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
6268 do_loadvm(cur_mon
, loadvm
);
6271 autostart
= 0; /* fixme how to deal with -daemonize */
6272 qemu_start_incoming_migration(incoming
);
6284 len
= write(fds
[1], &status
, 1);
6285 if (len
== -1 && (errno
== EINTR
))
6292 TFR(fd
= open("/dev/null", O_RDWR
));
6298 pwd
= getpwnam(run_as
);
6300 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
6306 if (chroot(chroot_dir
) < 0) {
6307 fprintf(stderr
, "chroot failed\n");
6314 if (setgid(pwd
->pw_gid
) < 0) {
6315 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
6318 if (setuid(pwd
->pw_uid
) < 0) {
6319 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
6322 if (setuid(0) != -1) {
6323 fprintf(stderr
, "Dropping privileges failed\n");