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_shutdown_requested(void)
3649 int r
= shutdown_requested
;
3650 shutdown_requested
= 0;
3654 int qemu_reset_requested(void)
3656 int r
= reset_requested
;
3657 reset_requested
= 0;
3661 int qemu_powerdown_requested(void)
3663 int r
= powerdown_requested
;
3664 powerdown_requested
= 0;
3668 static int qemu_debug_requested(void)
3670 int r
= debug_requested
;
3671 debug_requested
= 0;
3675 static int qemu_vmstop_requested(void)
3677 int r
= vmstop_requested
;
3678 vmstop_requested
= 0;
3682 static void do_vm_stop(int reason
)
3685 cpu_disable_ticks();
3688 vm_state_notify(0, reason
);
3692 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3694 QEMUResetEntry
**pre
, *re
;
3696 pre
= &first_reset_entry
;
3697 while (*pre
!= NULL
)
3698 pre
= &(*pre
)->next
;
3699 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3701 re
->opaque
= opaque
;
3706 void qemu_system_reset(void)
3710 /* reset all devices */
3711 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
3712 re
->func(re
->opaque
);
3718 void qemu_system_reset_request(void)
3721 shutdown_requested
= 1;
3723 reset_requested
= 1;
3725 if (cpu_single_env
) {
3726 qemu_kvm_cpu_stop(cpu_single_env
);
3727 cpu_exit(cpu_single_env
);
3729 qemu_notify_event();
3732 void qemu_system_shutdown_request(void)
3734 shutdown_requested
= 1;
3735 qemu_notify_event();
3738 void qemu_system_powerdown_request(void)
3740 powerdown_requested
= 1;
3741 qemu_notify_event();
3744 #ifdef CONFIG_IOTHREAD
3745 static void qemu_system_vmstop_request(int reason
)
3747 vmstop_requested
= reason
;
3748 qemu_notify_event();
3753 static int io_thread_fd
= -1;
3755 static void qemu_event_increment(void)
3757 static const char byte
= 0;
3759 if (io_thread_fd
== -1)
3762 write(io_thread_fd
, &byte
, sizeof(byte
));
3765 static void qemu_event_read(void *opaque
)
3767 int fd
= (unsigned long)opaque
;
3770 /* Drain the notify pipe */
3773 len
= read(fd
, buffer
, sizeof(buffer
));
3774 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
3777 static int qemu_event_init(void)
3786 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3790 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3794 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3795 (void *)(unsigned long)fds
[0]);
3797 io_thread_fd
= fds
[1];
3806 HANDLE qemu_event_handle
;
3808 static void dummy_event_handler(void *opaque
)
3812 static int qemu_event_init(void)
3814 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3815 if (!qemu_event_handle
) {
3816 perror("Failed CreateEvent");
3819 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3823 static void qemu_event_increment(void)
3825 SetEvent(qemu_event_handle
);
3829 static int cpu_can_run(CPUState
*env
)
3838 #ifndef CONFIG_IOTHREAD
3839 static int qemu_init_main_loop(void)
3841 return qemu_event_init();
3844 void qemu_init_vcpu(void *_env
)
3846 CPUState
*env
= _env
;
3853 int qemu_cpu_self(void *env
)
3858 static void resume_all_vcpus(void)
3862 static void pause_all_vcpus(void)
3866 void qemu_cpu_kick(void *env
)
3871 void qemu_notify_event(void)
3873 CPUState
*env
= cpu_single_env
;
3875 if (kvm_enabled()) {
3876 qemu_kvm_notify_work();
3882 if (env
->kqemu_enabled
)
3883 kqemu_cpu_interrupt(env
);
3888 #define qemu_mutex_lock_iothread() do { } while (0)
3889 #define qemu_mutex_unlock_iothread() do { } while (0)
3891 void vm_stop(int reason
)
3896 #else /* CONFIG_IOTHREAD */
3898 #include "qemu-thread.h"
3900 QemuMutex qemu_global_mutex
;
3901 static QemuMutex qemu_fair_mutex
;
3903 static QemuThread io_thread
;
3905 static QemuThread
*tcg_cpu_thread
;
3906 static QemuCond
*tcg_halt_cond
;
3908 static int qemu_system_ready
;
3910 static QemuCond qemu_cpu_cond
;
3912 static QemuCond qemu_system_cond
;
3913 static QemuCond qemu_pause_cond
;
3915 static void block_io_signals(void);
3916 static void unblock_io_signals(void);
3917 static int tcg_has_work(void);
3919 static int qemu_init_main_loop(void)
3923 ret
= qemu_event_init();
3927 qemu_cond_init(&qemu_pause_cond
);
3928 qemu_mutex_init(&qemu_fair_mutex
);
3929 qemu_mutex_init(&qemu_global_mutex
);
3930 qemu_mutex_lock(&qemu_global_mutex
);
3932 unblock_io_signals();
3933 qemu_thread_self(&io_thread
);
3938 static void qemu_wait_io_event(CPUState
*env
)
3940 while (!tcg_has_work())
3941 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3943 qemu_mutex_unlock(&qemu_global_mutex
);
3946 * Users of qemu_global_mutex can be starved, having no chance
3947 * to acquire it since this path will get to it first.
3948 * So use another lock to provide fairness.
3950 qemu_mutex_lock(&qemu_fair_mutex
);
3951 qemu_mutex_unlock(&qemu_fair_mutex
);
3953 qemu_mutex_lock(&qemu_global_mutex
);
3957 qemu_cond_signal(&qemu_pause_cond
);
3961 static int qemu_cpu_exec(CPUState
*env
);
3963 static void *kvm_cpu_thread_fn(void *arg
)
3965 CPUState
*env
= arg
;
3968 qemu_thread_self(env
->thread
);
3970 /* signal CPU creation */
3971 qemu_mutex_lock(&qemu_global_mutex
);
3973 qemu_cond_signal(&qemu_cpu_cond
);
3975 /* and wait for machine initialization */
3976 while (!qemu_system_ready
)
3977 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3980 if (cpu_can_run(env
))
3982 qemu_wait_io_event(env
);
3988 static void tcg_cpu_exec(void);
3990 static void *tcg_cpu_thread_fn(void *arg
)
3992 CPUState
*env
= arg
;
3995 qemu_thread_self(env
->thread
);
3997 /* signal CPU creation */
3998 qemu_mutex_lock(&qemu_global_mutex
);
3999 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4001 qemu_cond_signal(&qemu_cpu_cond
);
4003 /* and wait for machine initialization */
4004 while (!qemu_system_ready
)
4005 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
4009 qemu_wait_io_event(cur_cpu
);
4015 void qemu_cpu_kick(void *_env
)
4017 CPUState
*env
= _env
;
4018 qemu_cond_broadcast(env
->halt_cond
);
4020 qemu_thread_signal(env
->thread
, SIGUSR1
);
4023 int qemu_cpu_self(void *env
)
4025 return (cpu_single_env
!= NULL
);
4028 static void cpu_signal(int sig
)
4031 cpu_exit(cpu_single_env
);
4034 static void block_io_signals(void)
4037 struct sigaction sigact
;
4040 sigaddset(&set
, SIGUSR2
);
4041 sigaddset(&set
, SIGIO
);
4042 sigaddset(&set
, SIGALRM
);
4043 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
4046 sigaddset(&set
, SIGUSR1
);
4047 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
4049 memset(&sigact
, 0, sizeof(sigact
));
4050 sigact
.sa_handler
= cpu_signal
;
4051 sigaction(SIGUSR1
, &sigact
, NULL
);
4054 static void unblock_io_signals(void)
4059 sigaddset(&set
, SIGUSR2
);
4060 sigaddset(&set
, SIGIO
);
4061 sigaddset(&set
, SIGALRM
);
4062 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
4065 sigaddset(&set
, SIGUSR1
);
4066 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
4069 static void qemu_signal_lock(unsigned int msecs
)
4071 qemu_mutex_lock(&qemu_fair_mutex
);
4073 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
4074 qemu_thread_signal(tcg_cpu_thread
, SIGUSR1
);
4075 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
4078 qemu_mutex_unlock(&qemu_fair_mutex
);
4081 static void qemu_mutex_lock_iothread(void)
4083 if (kvm_enabled()) {
4084 qemu_mutex_lock(&qemu_fair_mutex
);
4085 qemu_mutex_lock(&qemu_global_mutex
);
4086 qemu_mutex_unlock(&qemu_fair_mutex
);
4088 qemu_signal_lock(100);
4091 static void qemu_mutex_unlock_iothread(void)
4093 qemu_mutex_unlock(&qemu_global_mutex
);
4096 static int all_vcpus_paused(void)
4098 CPUState
*penv
= first_cpu
;
4103 penv
= (CPUState
*)penv
->next_cpu
;
4109 static void pause_all_vcpus(void)
4111 CPUState
*penv
= first_cpu
;
4115 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4116 qemu_cpu_kick(penv
);
4117 penv
= (CPUState
*)penv
->next_cpu
;
4120 while (!all_vcpus_paused()) {
4121 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
4124 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4125 penv
= (CPUState
*)penv
->next_cpu
;
4130 static void resume_all_vcpus(void)
4132 CPUState
*penv
= first_cpu
;
4137 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4138 qemu_cpu_kick(penv
);
4139 penv
= (CPUState
*)penv
->next_cpu
;
4143 static void tcg_init_vcpu(void *_env
)
4145 CPUState
*env
= _env
;
4146 /* share a single thread for all cpus with TCG */
4147 if (!tcg_cpu_thread
) {
4148 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
4149 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
4150 qemu_cond_init(env
->halt_cond
);
4151 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
4152 while (env
->created
== 0)
4153 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
4154 tcg_cpu_thread
= env
->thread
;
4155 tcg_halt_cond
= env
->halt_cond
;
4157 env
->thread
= tcg_cpu_thread
;
4158 env
->halt_cond
= tcg_halt_cond
;
4162 static void kvm_start_vcpu(CPUState
*env
)
4165 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
4166 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
4167 qemu_cond_init(env
->halt_cond
);
4168 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
4169 while (env
->created
== 0)
4170 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
4173 void qemu_init_vcpu(void *_env
)
4175 CPUState
*env
= _env
;
4178 kvm_start_vcpu(env
);
4183 void qemu_notify_event(void)
4185 qemu_event_increment();
4188 void vm_stop(int reason
)
4191 qemu_thread_self(&me
);
4193 if (!qemu_thread_equal(&me
, &io_thread
)) {
4194 qemu_system_vmstop_request(reason
);
4196 * FIXME: should not return to device code in case
4197 * vm_stop() has been requested.
4199 if (cpu_single_env
) {
4200 cpu_exit(cpu_single_env
);
4201 cpu_single_env
->stop
= 1;
4212 static void host_main_loop_wait(int *timeout
)
4218 /* XXX: need to suppress polling by better using win32 events */
4220 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
4221 ret
|= pe
->func(pe
->opaque
);
4225 WaitObjects
*w
= &wait_objects
;
4227 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
4228 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
4229 if (w
->func
[ret
- WAIT_OBJECT_0
])
4230 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
4232 /* Check for additional signaled events */
4233 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
4235 /* Check if event is signaled */
4236 ret2
= WaitForSingleObject(w
->events
[i
], 0);
4237 if(ret2
== WAIT_OBJECT_0
) {
4239 w
->func
[i
](w
->opaque
[i
]);
4240 } else if (ret2
== WAIT_TIMEOUT
) {
4242 err
= GetLastError();
4243 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
4246 } else if (ret
== WAIT_TIMEOUT
) {
4248 err
= GetLastError();
4249 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
4256 static void host_main_loop_wait(int *timeout
)
4261 void main_loop_wait(int timeout
)
4263 IOHandlerRecord
*ioh
;
4264 fd_set rfds
, wfds
, xfds
;
4268 qemu_bh_update_timeout(&timeout
);
4270 host_main_loop_wait(&timeout
);
4272 /* poll any events */
4273 /* XXX: separate device handlers from system ones */
4278 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4282 (!ioh
->fd_read_poll
||
4283 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
4284 FD_SET(ioh
->fd
, &rfds
);
4288 if (ioh
->fd_write
) {
4289 FD_SET(ioh
->fd
, &wfds
);
4295 tv
.tv_sec
= timeout
/ 1000;
4296 tv
.tv_usec
= (timeout
% 1000) * 1000;
4298 #if defined(CONFIG_SLIRP)
4299 if (slirp_is_inited()) {
4300 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
4303 ret
= qemu_select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
4305 IOHandlerRecord
**pioh
;
4307 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4308 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
4309 ioh
->fd_read(ioh
->opaque
);
4310 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
4311 FD_CLR(ioh
->fd
, &rfds
);
4313 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
4314 ioh
->fd_write(ioh
->opaque
);
4318 /* remove deleted IO handlers */
4319 pioh
= &first_io_handler
;
4329 #if defined(CONFIG_SLIRP)
4330 if (slirp_is_inited()) {
4336 slirp_select_poll(&rfds
, &wfds
, &xfds
);
4340 /* rearm timer, if not periodic */
4341 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
4342 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
4343 qemu_rearm_alarm_timer(alarm_timer
);
4346 /* vm time timers */
4348 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
4349 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
4350 qemu_get_clock(vm_clock
));
4353 /* real time timers */
4354 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
4355 qemu_get_clock(rt_clock
));
4357 /* Check bottom-halves last in case any of the earlier events triggered
4363 static int qemu_cpu_exec(CPUState
*env
)
4366 #ifdef CONFIG_PROFILER
4370 #ifdef CONFIG_PROFILER
4371 ti
= profile_getclock();
4376 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
4377 env
->icount_decr
.u16
.low
= 0;
4378 env
->icount_extra
= 0;
4379 count
= qemu_next_deadline();
4380 count
= (count
+ (1 << icount_time_shift
) - 1)
4381 >> icount_time_shift
;
4382 qemu_icount
+= count
;
4383 decr
= (count
> 0xffff) ? 0xffff : count
;
4385 env
->icount_decr
.u16
.low
= decr
;
4386 env
->icount_extra
= count
;
4388 ret
= cpu_exec(env
);
4389 #ifdef CONFIG_PROFILER
4390 qemu_time
+= profile_getclock() - ti
;
4393 /* Fold pending instructions back into the
4394 instruction counter, and clear the interrupt flag. */
4395 qemu_icount
-= (env
->icount_decr
.u16
.low
4396 + env
->icount_extra
);
4397 env
->icount_decr
.u32
= 0;
4398 env
->icount_extra
= 0;
4403 static void tcg_cpu_exec(void)
4407 if (next_cpu
== NULL
)
4408 next_cpu
= first_cpu
;
4409 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
4410 CPUState
*env
= cur_cpu
= next_cpu
;
4414 if (timer_alarm_pending
) {
4415 timer_alarm_pending
= 0;
4418 if (cpu_can_run(env
))
4419 ret
= qemu_cpu_exec(env
);
4420 #ifndef CONFIG_GDBSTUB
4421 if (ret
== EXCP_DEBUG
) {
4422 gdb_set_stop_cpu(env
);
4423 debug_requested
= 1;
4430 static int cpu_has_work(CPUState
*env
)
4438 if (qemu_cpu_has_work(env
))
4443 static int tcg_has_work(void)
4447 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4448 if (cpu_has_work(env
))
4453 static int qemu_calculate_timeout(void)
4459 else if (tcg_has_work())
4461 else if (!use_icount
)
4464 /* XXX: use timeout computed from timers */
4467 /* Advance virtual time to the next event. */
4468 if (use_icount
== 1) {
4469 /* When not using an adaptive execution frequency
4470 we tend to get badly out of sync with real time,
4471 so just delay for a reasonable amount of time. */
4474 delta
= cpu_get_icount() - cpu_get_clock();
4477 /* If virtual time is ahead of real time then just
4479 timeout
= (delta
/ 1000000) + 1;
4481 /* Wait for either IO to occur or the next
4483 add
= qemu_next_deadline();
4484 /* We advance the timer before checking for IO.
4485 Limit the amount we advance so that early IO
4486 activity won't get the guest too far ahead. */
4490 add
= (add
+ (1 << icount_time_shift
) - 1)
4491 >> icount_time_shift
;
4493 timeout
= delta
/ 1000000;
4502 static int vm_can_run(void)
4504 if (powerdown_requested
)
4506 if (reset_requested
)
4508 if (shutdown_requested
)
4510 if (debug_requested
)
4515 static void main_loop(void)
4519 if (kvm_enabled()) {
4521 cpu_disable_ticks();
4525 #ifdef CONFIG_IOTHREAD
4526 qemu_system_ready
= 1;
4527 qemu_cond_broadcast(&qemu_system_cond
);
4532 #ifdef CONFIG_PROFILER
4535 #ifndef CONFIG_IOTHREAD
4538 #ifdef CONFIG_PROFILER
4539 ti
= profile_getclock();
4541 #ifdef CONFIG_IOTHREAD
4542 main_loop_wait(1000);
4544 main_loop_wait(qemu_calculate_timeout());
4546 #ifdef CONFIG_PROFILER
4547 dev_time
+= profile_getclock() - ti
;
4549 } while (vm_can_run());
4551 if (qemu_debug_requested())
4552 vm_stop(EXCP_DEBUG
);
4553 if (qemu_shutdown_requested()) {
4560 if (qemu_reset_requested()) {
4562 qemu_system_reset();
4565 if (qemu_powerdown_requested())
4566 qemu_system_powerdown();
4567 if ((r
= qemu_vmstop_requested()))
4573 static void version(void)
4575 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4578 static void help(int exitcode
)
4581 printf("usage: %s [options] [disk_image]\n"
4583 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4585 #define DEF(option, opt_arg, opt_enum, opt_help) \
4587 #define DEFHEADING(text) stringify(text) "\n"
4588 #include "qemu-options.h"
4593 "During emulation, the following keys are useful:\n"
4594 "ctrl-alt-f toggle full screen\n"
4595 "ctrl-alt-n switch to virtual console 'n'\n"
4596 "ctrl-alt toggle mouse and keyboard grab\n"
4598 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4603 DEFAULT_NETWORK_SCRIPT
,
4604 DEFAULT_NETWORK_DOWN_SCRIPT
,
4606 DEFAULT_GDBSTUB_PORT
,
4611 #define HAS_ARG 0x0001
4614 #define DEF(option, opt_arg, opt_enum, opt_help) \
4616 #define DEFHEADING(text)
4617 #include "qemu-options.h"
4623 typedef struct QEMUOption
{
4629 static const QEMUOption qemu_options
[] = {
4630 { "h", 0, QEMU_OPTION_h
},
4631 #define DEF(option, opt_arg, opt_enum, opt_help) \
4632 { option, opt_arg, opt_enum },
4633 #define DEFHEADING(text)
4634 #include "qemu-options.h"
4642 struct soundhw soundhw
[] = {
4643 #ifdef HAS_AUDIO_CHOICE
4644 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4650 { .init_isa
= pcspk_audio_init
}
4657 "Creative Sound Blaster 16",
4660 { .init_isa
= SB16_init
}
4664 #ifdef CONFIG_CS4231A
4670 { .init_isa
= cs4231a_init
}
4678 "Yamaha YMF262 (OPL3)",
4680 "Yamaha YM3812 (OPL2)",
4684 { .init_isa
= Adlib_init
}
4691 "Gravis Ultrasound GF1",
4694 { .init_isa
= GUS_init
}
4701 "Intel 82801AA AC97 Audio",
4704 { .init_pci
= ac97_init
}
4708 #ifdef CONFIG_ES1370
4711 "ENSONIQ AudioPCI ES1370",
4714 { .init_pci
= es1370_init
}
4718 #endif /* HAS_AUDIO_CHOICE */
4720 { NULL
, NULL
, 0, 0, { NULL
} }
4723 static void select_soundhw (const char *optarg
)
4727 if (*optarg
== '?') {
4730 printf ("Valid sound card names (comma separated):\n");
4731 for (c
= soundhw
; c
->name
; ++c
) {
4732 printf ("%-11s %s\n", c
->name
, c
->descr
);
4734 printf ("\n-soundhw all will enable all of the above\n");
4735 exit (*optarg
!= '?');
4743 if (!strcmp (optarg
, "all")) {
4744 for (c
= soundhw
; c
->name
; ++c
) {
4752 e
= strchr (p
, ',');
4753 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4755 for (c
= soundhw
; c
->name
; ++c
) {
4756 if (!strncmp (c
->name
, p
, l
)) {
4765 "Unknown sound card name (too big to show)\n");
4768 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4773 p
+= l
+ (e
!= NULL
);
4777 goto show_valid_cards
;
4782 static void select_vgahw (const char *p
)
4786 cirrus_vga_enabled
= 0;
4787 std_vga_enabled
= 0;
4790 if (strstart(p
, "std", &opts
)) {
4791 std_vga_enabled
= 1;
4792 } else if (strstart(p
, "cirrus", &opts
)) {
4793 cirrus_vga_enabled
= 1;
4794 } else if (strstart(p
, "vmware", &opts
)) {
4796 } else if (strstart(p
, "xenfb", &opts
)) {
4798 } else if (!strstart(p
, "none", &opts
)) {
4800 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4804 const char *nextopt
;
4806 if (strstart(opts
, ",retrace=", &nextopt
)) {
4808 if (strstart(opts
, "dumb", &nextopt
))
4809 vga_retrace_method
= VGA_RETRACE_DUMB
;
4810 else if (strstart(opts
, "precise", &nextopt
))
4811 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4812 else goto invalid_vga
;
4813 } else goto invalid_vga
;
4819 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4821 exit(STATUS_CONTROL_C_EXIT
);
4826 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4830 if(strlen(str
) != 36)
4833 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4834 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4835 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4841 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4847 #define MAX_NET_CLIENTS 32
4851 #define HUGETLBFS_MAGIC 0x958458f6
4853 static long gethugepagesize(const char *path
)
4859 ret
= statfs(path
, &fs
);
4860 } while (ret
!= 0 && errno
== EINTR
);
4867 if (fs
.f_type
!= HUGETLBFS_MAGIC
)
4868 fprintf(stderr
, "Warning: path not on HugeTLBFS: %s\n", path
);
4873 static void *alloc_mem_area(size_t memory
, unsigned long *len
, const char *path
)
4882 if (!kvm_has_sync_mmu()) {
4883 fprintf(stderr
, "host lacks mmu notifiers, disabling --mem-path\n");
4887 if (asprintf(&filename
, "%s/kvm.XXXXXX", path
) == -1)
4890 hpagesize
= gethugepagesize(path
);
4894 fd
= mkstemp(filename
);
4903 memory
= (memory
+hpagesize
-1) & ~(hpagesize
-1);
4906 * ftruncate is not supported by hugetlbfs in older
4907 * hosts, so don't bother checking for errors.
4908 * If anything goes wrong with it under other filesystems,
4911 ftruncate(fd
, memory
);
4914 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4915 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4916 * to sidestep this quirk.
4918 flags
= mem_prealloc
? MAP_POPULATE
|MAP_SHARED
: MAP_PRIVATE
;
4919 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, flags
, fd
, 0);
4921 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
, fd
, 0);
4923 if (area
== MAP_FAILED
) {
4924 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4935 static void termsig_handler(int signal
)
4937 qemu_system_shutdown_request();
4940 static void termsig_setup(void)
4942 struct sigaction act
;
4944 memset(&act
, 0, sizeof(act
));
4945 act
.sa_handler
= termsig_handler
;
4946 sigaction(SIGINT
, &act
, NULL
);
4947 sigaction(SIGHUP
, &act
, NULL
);
4948 sigaction(SIGTERM
, &act
, NULL
);
4953 int main(int argc
, char **argv
, char **envp
)
4955 #ifdef CONFIG_GDBSTUB
4956 const char *gdbstub_dev
= NULL
;
4958 uint32_t boot_devices_bitmap
= 0;
4960 int snapshot
, linux_boot
, net_boot
;
4961 const char *initrd_filename
;
4962 const char *kernel_filename
, *kernel_cmdline
;
4963 const char *boot_devices
= "";
4965 DisplayChangeListener
*dcl
;
4966 int cyls
, heads
, secs
, translation
;
4967 const char *net_clients
[MAX_NET_CLIENTS
];
4969 const char *bt_opts
[MAX_BT_CMDLINE
];
4973 const char *r
, *optarg
;
4974 CharDriverState
*monitor_hd
= NULL
;
4975 const char *monitor_device
;
4976 const char *serial_devices
[MAX_SERIAL_PORTS
];
4977 int serial_device_index
;
4978 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
4979 int parallel_device_index
;
4980 const char *virtio_consoles
[MAX_VIRTIO_CONSOLES
];
4981 int virtio_console_index
;
4982 const char *loadvm
= NULL
;
4983 QEMUMachine
*machine
;
4984 const char *cpu_model
;
4985 const char *usb_devices
[MAX_USB_CMDLINE
];
4986 int usb_devices_index
;
4991 const char *pid_file
= NULL
;
4992 const char *incoming
= NULL
;
4995 struct passwd
*pwd
= NULL
;
4996 const char *chroot_dir
= NULL
;
4997 const char *run_as
= NULL
;
5001 qemu_cache_utils_init(envp
);
5003 LIST_INIT (&vm_change_state_head
);
5006 struct sigaction act
;
5007 sigfillset(&act
.sa_mask
);
5009 act
.sa_handler
= SIG_IGN
;
5010 sigaction(SIGPIPE
, &act
, NULL
);
5013 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
5014 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5015 QEMU to run on a single CPU */
5020 h
= GetCurrentProcess();
5021 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
5022 for(i
= 0; i
< 32; i
++) {
5023 if (mask
& (1 << i
))
5028 SetProcessAffinityMask(h
, mask
);
5034 register_machines();
5035 machine
= first_machine
;
5037 initrd_filename
= NULL
;
5039 vga_ram_size
= VGA_RAM_SIZE
;
5043 kernel_filename
= NULL
;
5044 kernel_cmdline
= "";
5045 cyls
= heads
= secs
= 0;
5046 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5047 monitor_device
= "vc:80Cx24C";
5049 serial_devices
[0] = "vc:80Cx24C";
5050 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
5051 serial_devices
[i
] = NULL
;
5052 serial_device_index
= 0;
5054 parallel_devices
[0] = "vc:80Cx24C";
5055 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
5056 parallel_devices
[i
] = NULL
;
5057 parallel_device_index
= 0;
5059 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++)
5060 virtio_consoles
[i
] = NULL
;
5061 virtio_console_index
= 0;
5063 for (i
= 0; i
< MAX_NODES
; i
++) {
5065 node_cpumask
[i
] = 0;
5068 usb_devices_index
= 0;
5069 assigned_devices_index
= 0;
5083 register_watchdogs();
5091 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
5093 const QEMUOption
*popt
;
5096 /* Treat --foo the same as -foo. */
5099 popt
= qemu_options
;
5102 fprintf(stderr
, "%s: invalid option -- '%s'\n",
5106 if (!strcmp(popt
->name
, r
+ 1))
5110 if (popt
->flags
& HAS_ARG
) {
5111 if (optind
>= argc
) {
5112 fprintf(stderr
, "%s: option '%s' requires an argument\n",
5116 optarg
= argv
[optind
++];
5121 switch(popt
->index
) {
5123 machine
= find_machine(optarg
);
5126 printf("Supported machines are:\n");
5127 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5128 printf("%-10s %s%s\n",
5130 m
== first_machine
? " (default)" : "");
5132 exit(*optarg
!= '?');
5135 case QEMU_OPTION_cpu
:
5136 /* hw initialization will check this */
5137 if (*optarg
== '?') {
5138 /* XXX: implement xxx_cpu_list for targets that still miss it */
5139 #if defined(cpu_list)
5140 cpu_list(stdout
, &fprintf
);
5147 case QEMU_OPTION_initrd
:
5148 initrd_filename
= optarg
;
5150 case QEMU_OPTION_hda
:
5152 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
5154 hda_index
= drive_add(optarg
, HD_ALIAS
5155 ",cyls=%d,heads=%d,secs=%d%s",
5156 0, cyls
, heads
, secs
,
5157 translation
== BIOS_ATA_TRANSLATION_LBA
?
5159 translation
== BIOS_ATA_TRANSLATION_NONE
?
5160 ",trans=none" : "");
5162 case QEMU_OPTION_hdb
:
5163 case QEMU_OPTION_hdc
:
5164 case QEMU_OPTION_hdd
:
5165 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
5167 case QEMU_OPTION_drive
:
5168 drive_add(NULL
, "%s", optarg
);
5170 case QEMU_OPTION_mtdblock
:
5171 drive_add(optarg
, MTD_ALIAS
);
5173 case QEMU_OPTION_sd
:
5174 drive_add(optarg
, SD_ALIAS
);
5176 case QEMU_OPTION_pflash
:
5177 drive_add(optarg
, PFLASH_ALIAS
);
5179 case QEMU_OPTION_snapshot
:
5182 case QEMU_OPTION_hdachs
:
5186 cyls
= strtol(p
, (char **)&p
, 0);
5187 if (cyls
< 1 || cyls
> 16383)
5192 heads
= strtol(p
, (char **)&p
, 0);
5193 if (heads
< 1 || heads
> 16)
5198 secs
= strtol(p
, (char **)&p
, 0);
5199 if (secs
< 1 || secs
> 63)
5203 if (!strcmp(p
, "none"))
5204 translation
= BIOS_ATA_TRANSLATION_NONE
;
5205 else if (!strcmp(p
, "lba"))
5206 translation
= BIOS_ATA_TRANSLATION_LBA
;
5207 else if (!strcmp(p
, "auto"))
5208 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5211 } else if (*p
!= '\0') {
5213 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5216 if (hda_index
!= -1)
5217 snprintf(drives_opt
[hda_index
].opt
,
5218 sizeof(drives_opt
[hda_index
].opt
),
5219 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
5220 0, cyls
, heads
, secs
,
5221 translation
== BIOS_ATA_TRANSLATION_LBA
?
5223 translation
== BIOS_ATA_TRANSLATION_NONE
?
5224 ",trans=none" : "");
5227 case QEMU_OPTION_numa
:
5228 if (nb_numa_nodes
>= MAX_NODES
) {
5229 fprintf(stderr
, "qemu: too many NUMA nodes\n");
5234 case QEMU_OPTION_nographic
:
5237 #ifdef CONFIG_CURSES
5238 case QEMU_OPTION_curses
:
5242 case QEMU_OPTION_portrait
:
5245 case QEMU_OPTION_kernel
:
5246 kernel_filename
= optarg
;
5248 case QEMU_OPTION_append
:
5249 kernel_cmdline
= optarg
;
5251 case QEMU_OPTION_cdrom
:
5252 drive_add(optarg
, CDROM_ALIAS
);
5254 case QEMU_OPTION_boot
:
5255 boot_devices
= optarg
;
5256 /* We just do some generic consistency checks */
5258 /* Could easily be extended to 64 devices if needed */
5261 boot_devices_bitmap
= 0;
5262 for (p
= boot_devices
; *p
!= '\0'; p
++) {
5263 /* Allowed boot devices are:
5264 * a b : floppy disk drives
5265 * c ... f : IDE disk drives
5266 * g ... m : machine implementation dependant drives
5267 * n ... p : network devices
5268 * It's up to each machine implementation to check
5269 * if the given boot devices match the actual hardware
5270 * implementation and firmware features.
5272 if (*p
< 'a' || *p
> 'q') {
5273 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
5276 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
5278 "Boot device '%c' was given twice\n",*p
);
5281 boot_devices_bitmap
|= 1 << (*p
- 'a');
5285 case QEMU_OPTION_fda
:
5286 case QEMU_OPTION_fdb
:
5287 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
5290 case QEMU_OPTION_no_fd_bootchk
:
5294 case QEMU_OPTION_net
:
5295 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
5296 fprintf(stderr
, "qemu: too many network clients\n");
5299 net_clients
[nb_net_clients
] = optarg
;
5303 case QEMU_OPTION_tftp
:
5304 tftp_prefix
= optarg
;
5306 case QEMU_OPTION_bootp
:
5307 bootp_filename
= optarg
;
5310 case QEMU_OPTION_smb
:
5311 net_slirp_smb(optarg
);
5314 case QEMU_OPTION_redir
:
5315 net_slirp_redir(NULL
, optarg
);
5318 case QEMU_OPTION_bt
:
5319 if (nb_bt_opts
>= MAX_BT_CMDLINE
) {
5320 fprintf(stderr
, "qemu: too many bluetooth options\n");
5323 bt_opts
[nb_bt_opts
++] = optarg
;
5326 case QEMU_OPTION_audio_help
:
5330 case QEMU_OPTION_soundhw
:
5331 select_soundhw (optarg
);
5337 case QEMU_OPTION_version
:
5341 case QEMU_OPTION_m
: {
5345 value
= strtoul(optarg
, &ptr
, 10);
5347 case 0: case 'M': case 'm':
5354 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5358 /* On 32-bit hosts, QEMU is limited by virtual address space */
5359 if (value
> (2047 << 20)
5360 #ifndef CONFIG_KQEMU
5361 && HOST_LONG_BITS
== 32
5364 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5367 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5368 fprintf(stderr
, "qemu: ram size too large\n");
5377 const CPULogItem
*item
;
5379 mask
= cpu_str_to_log_mask(optarg
);
5381 printf("Log items (comma separated):\n");
5382 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5383 printf("%-10s %s\n", item
->name
, item
->help
);
5390 #ifdef CONFIG_GDBSTUB
5392 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5394 case QEMU_OPTION_gdb
:
5395 gdbstub_dev
= optarg
;
5401 case QEMU_OPTION_bios
:
5404 case QEMU_OPTION_singlestep
:
5412 keyboard_layout
= optarg
;
5415 case QEMU_OPTION_localtime
:
5418 case QEMU_OPTION_vga
:
5419 select_vgahw (optarg
);
5421 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5427 w
= strtol(p
, (char **)&p
, 10);
5430 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5436 h
= strtol(p
, (char **)&p
, 10);
5441 depth
= strtol(p
, (char **)&p
, 10);
5442 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5443 depth
!= 24 && depth
!= 32)
5445 } else if (*p
== '\0') {
5446 depth
= graphic_depth
;
5453 graphic_depth
= depth
;
5457 case QEMU_OPTION_echr
:
5460 term_escape_char
= strtol(optarg
, &r
, 0);
5462 printf("Bad argument to echr\n");
5465 case QEMU_OPTION_monitor
:
5466 monitor_device
= optarg
;
5468 case QEMU_OPTION_serial
:
5469 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
5470 fprintf(stderr
, "qemu: too many serial ports\n");
5473 serial_devices
[serial_device_index
] = optarg
;
5474 serial_device_index
++;
5476 case QEMU_OPTION_watchdog
:
5477 i
= select_watchdog(optarg
);
5479 exit (i
== 1 ? 1 : 0);
5481 case QEMU_OPTION_watchdog_action
:
5482 if (select_watchdog_action(optarg
) == -1) {
5483 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5487 case QEMU_OPTION_virtiocon
:
5488 if (virtio_console_index
>= MAX_VIRTIO_CONSOLES
) {
5489 fprintf(stderr
, "qemu: too many virtio consoles\n");
5492 virtio_consoles
[virtio_console_index
] = optarg
;
5493 virtio_console_index
++;
5495 case QEMU_OPTION_parallel
:
5496 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
5497 fprintf(stderr
, "qemu: too many parallel ports\n");
5500 parallel_devices
[parallel_device_index
] = optarg
;
5501 parallel_device_index
++;
5503 case QEMU_OPTION_loadvm
:
5506 case QEMU_OPTION_full_screen
:
5510 case QEMU_OPTION_no_frame
:
5513 case QEMU_OPTION_alt_grab
:
5516 case QEMU_OPTION_no_quit
:
5519 case QEMU_OPTION_sdl
:
5523 case QEMU_OPTION_pidfile
:
5527 case QEMU_OPTION_win2k_hack
:
5528 win2k_install_hack
= 1;
5530 case QEMU_OPTION_rtc_td_hack
:
5533 case QEMU_OPTION_acpitable
:
5534 if(acpi_table_add(optarg
) < 0) {
5535 fprintf(stderr
, "Wrong acpi table provided\n");
5539 case QEMU_OPTION_smbios
:
5540 if(smbios_entry_add(optarg
) < 0) {
5541 fprintf(stderr
, "Wrong smbios provided\n");
5547 case QEMU_OPTION_no_kqemu
:
5550 case QEMU_OPTION_kernel_kqemu
:
5555 case QEMU_OPTION_enable_kvm
:
5563 case QEMU_OPTION_no_kvm
:
5566 case QEMU_OPTION_no_kvm_irqchip
: {
5571 case QEMU_OPTION_no_kvm_pit
: {
5575 case QEMU_OPTION_no_kvm_pit_reinjection
: {
5576 kvm_pit_reinject
= 0;
5579 case QEMU_OPTION_enable_nesting
: {
5583 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5584 case QEMU_OPTION_pcidevice
:
5585 if (assigned_devices_index
>= MAX_DEV_ASSIGN_CMDLINE
) {
5586 fprintf(stderr
, "Too many assigned devices\n");
5589 assigned_devices
[assigned_devices_index
] = optarg
;
5590 assigned_devices_index
++;
5594 case QEMU_OPTION_usb
:
5597 case QEMU_OPTION_usbdevice
:
5599 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
5600 fprintf(stderr
, "Too many USB devices\n");
5603 usb_devices
[usb_devices_index
] = optarg
;
5604 usb_devices_index
++;
5606 case QEMU_OPTION_smp
:
5607 smp_cpus
= atoi(optarg
);
5609 fprintf(stderr
, "Invalid number of CPUs\n");
5613 case QEMU_OPTION_vnc
:
5614 vnc_display
= optarg
;
5617 case QEMU_OPTION_no_acpi
:
5620 case QEMU_OPTION_no_hpet
:
5624 case QEMU_OPTION_no_reboot
:
5627 case QEMU_OPTION_no_shutdown
:
5630 case QEMU_OPTION_show_cursor
:
5633 case QEMU_OPTION_uuid
:
5634 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5635 fprintf(stderr
, "Fail to parse UUID string."
5636 " Wrong format.\n");
5641 case QEMU_OPTION_daemonize
:
5645 case QEMU_OPTION_option_rom
:
5646 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5647 fprintf(stderr
, "Too many option ROMs\n");
5650 option_rom
[nb_option_roms
] = optarg
;
5653 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5654 case QEMU_OPTION_semihosting
:
5655 semihosting_enabled
= 1;
5658 case QEMU_OPTION_tdf
:
5661 case QEMU_OPTION_kvm_shadow_memory
:
5662 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
5664 case QEMU_OPTION_mempath
:
5668 case QEMU_OPTION_mem_prealloc
:
5669 mem_prealloc
= !mem_prealloc
;
5672 case QEMU_OPTION_name
:
5675 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5676 case QEMU_OPTION_prom_env
:
5677 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5678 fprintf(stderr
, "Too many prom variables\n");
5681 prom_envs
[nb_prom_envs
] = optarg
;
5686 case QEMU_OPTION_old_param
:
5690 case QEMU_OPTION_clock
:
5691 configure_alarms(optarg
);
5693 case QEMU_OPTION_startdate
:
5696 time_t rtc_start_date
;
5697 if (!strcmp(optarg
, "now")) {
5698 rtc_date_offset
= -1;
5700 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
5708 } else if (sscanf(optarg
, "%d-%d-%d",
5711 &tm
.tm_mday
) == 3) {
5720 rtc_start_date
= mktimegm(&tm
);
5721 if (rtc_start_date
== -1) {
5723 fprintf(stderr
, "Invalid date format. Valid format are:\n"
5724 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5727 rtc_date_offset
= time(NULL
) - rtc_start_date
;
5731 case QEMU_OPTION_tb_size
:
5732 tb_size
= strtol(optarg
, NULL
, 0);
5736 case QEMU_OPTION_icount
:
5738 if (strcmp(optarg
, "auto") == 0) {
5739 icount_time_shift
= -1;
5741 icount_time_shift
= strtol(optarg
, NULL
, 0);
5744 case QEMU_OPTION_incoming
:
5748 case QEMU_OPTION_chroot
:
5749 chroot_dir
= optarg
;
5751 case QEMU_OPTION_runas
:
5754 case QEMU_OPTION_nvram
:
5759 case QEMU_OPTION_xen_domid
:
5760 xen_domid
= atoi(optarg
);
5762 case QEMU_OPTION_xen_create
:
5763 xen_mode
= XEN_CREATE
;
5765 case QEMU_OPTION_xen_attach
:
5766 xen_mode
= XEN_ATTACH
;
5773 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5774 if (kvm_allowed
&& kqemu_allowed
) {
5776 "You can not enable both KVM and kqemu at the same time\n");
5781 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5782 if (smp_cpus
> machine
->max_cpus
) {
5783 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5784 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5790 if (serial_device_index
== 0)
5791 serial_devices
[0] = "stdio";
5792 if (parallel_device_index
== 0)
5793 parallel_devices
[0] = "null";
5794 if (strncmp(monitor_device
, "vc", 2) == 0)
5795 monitor_device
= "stdio";
5802 if (pipe(fds
) == -1)
5813 len
= read(fds
[0], &status
, 1);
5814 if (len
== -1 && (errno
== EINTR
))
5819 else if (status
== 1) {
5820 fprintf(stderr
, "Could not acquire pidfile\n");
5837 signal(SIGTSTP
, SIG_IGN
);
5838 signal(SIGTTOU
, SIG_IGN
);
5839 signal(SIGTTIN
, SIG_IGN
);
5843 if (kvm_enabled()) {
5844 if (kvm_qemu_init() < 0) {
5845 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
5846 #ifdef NO_CPU_EMULATION
5847 fprintf(stderr
, "Compiled with --disable-cpu-emulation, exiting.\n");
5855 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5858 write(fds
[1], &status
, 1);
5860 fprintf(stderr
, "Could not acquire pid file\n");
5869 if (qemu_init_main_loop()) {
5870 fprintf(stderr
, "qemu_init_main_loop failed\n");
5873 linux_boot
= (kernel_filename
!= NULL
);
5874 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5876 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5877 fprintf(stderr
, "-append only allowed with -kernel option\n");
5881 if (!linux_boot
&& initrd_filename
!= NULL
) {
5882 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5886 /* boot to floppy or the default cd if no hard disk defined yet */
5887 if (!boot_devices
[0]) {
5888 boot_devices
= "cad";
5890 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5893 if (init_timer_alarm() < 0) {
5894 fprintf(stderr
, "could not initialize alarm timer\n");
5897 if (use_icount
&& icount_time_shift
< 0) {
5899 /* 125MIPS seems a reasonable initial guess at the guest speed.
5900 It will be corrected fairly quickly anyway. */
5901 icount_time_shift
= 3;
5902 init_icount_adjust();
5909 /* init network clients */
5910 if (nb_net_clients
== 0) {
5911 /* if no clients, we use a default config */
5912 net_clients
[nb_net_clients
++] = "nic";
5914 net_clients
[nb_net_clients
++] = "user";
5918 for(i
= 0;i
< nb_net_clients
; i
++) {
5919 if (net_client_parse(net_clients
[i
]) < 0)
5925 /* XXX: this should be moved in the PC machine instantiation code */
5926 if (net_boot
!= 0) {
5928 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
5929 const char *model
= nd_table
[i
].model
;
5931 if (net_boot
& (1 << i
)) {
5934 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
5935 if (get_image_size(buf
) > 0) {
5936 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5937 fprintf(stderr
, "Too many option ROMs\n");
5940 option_rom
[nb_option_roms
] = strdup(buf
);
5947 fprintf(stderr
, "No valid PXE rom found for network device\n");
5953 /* init the bluetooth world */
5954 for (i
= 0; i
< nb_bt_opts
; i
++)
5955 if (bt_parse(bt_opts
[i
]))
5958 /* init the memory */
5960 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5962 if (kvm_enabled()) {
5963 if (kvm_qemu_create_context() < 0) {
5964 fprintf(stderr
, "Could not create KVM context\n");
5970 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5971 guest ram allocation. It needs to go away. */
5972 if (kqemu_allowed
) {
5973 kqemu_phys_ram_size
= ram_size
+ VGA_RAM_SIZE
+ 4 * 1024 * 1024;
5974 kqemu_phys_ram_base
= qemu_vmalloc(kqemu_phys_ram_size
);
5975 if (!kqemu_phys_ram_base
) {
5976 fprintf(stderr
, "Could not allocate physical memory\n");
5982 /* init the dynamic translator */
5983 cpu_exec_init_all(tb_size
* 1024 * 1024);
5988 /* we always create the cdrom drive, even if no disk is there */
5990 if (nb_drives_opt
< MAX_DRIVES
)
5991 drive_add(NULL
, CDROM_ALIAS
);
5993 /* we always create at least one floppy */
5995 if (nb_drives_opt
< MAX_DRIVES
)
5996 drive_add(NULL
, FD_ALIAS
, 0);
5998 /* we always create one sd slot, even if no card is in it */
6000 if (nb_drives_opt
< MAX_DRIVES
)
6001 drive_add(NULL
, SD_ALIAS
);
6003 /* open the virtual block devices
6004 * note that migration with device
6005 * hot add/remove is broken.
6007 for(i
= 0; i
< nb_drives_opt
; i
++)
6008 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
6011 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
6012 register_savevm_live("ram", 0, 3, ram_save_live
, NULL
, ram_load
, NULL
);
6015 /* must be after terminal init, SDL library changes signal handlers */
6019 /* Maintain compatibility with multiple stdio monitors */
6020 if (!strcmp(monitor_device
,"stdio")) {
6021 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6022 const char *devname
= serial_devices
[i
];
6023 if (devname
&& !strcmp(devname
,"mon:stdio")) {
6024 monitor_device
= NULL
;
6026 } else if (devname
&& !strcmp(devname
,"stdio")) {
6027 monitor_device
= NULL
;
6028 serial_devices
[i
] = "mon:stdio";
6034 if (nb_numa_nodes
> 0) {
6037 if (nb_numa_nodes
> smp_cpus
) {
6038 nb_numa_nodes
= smp_cpus
;
6041 /* If no memory size if given for any node, assume the default case
6042 * and distribute the available memory equally across all nodes
6044 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6045 if (node_mem
[i
] != 0)
6048 if (i
== nb_numa_nodes
) {
6049 uint64_t usedmem
= 0;
6051 /* On Linux, the each node's border has to be 8MB aligned,
6052 * the final node gets the rest.
6054 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
6055 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
6056 usedmem
+= node_mem
[i
];
6058 node_mem
[i
] = ram_size
- usedmem
;
6061 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6062 if (node_cpumask
[i
] != 0)
6065 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6066 * must cope with this anyway, because there are BIOSes out there in
6067 * real machines which also use this scheme.
6069 if (i
== nb_numa_nodes
) {
6070 for (i
= 0; i
< smp_cpus
; i
++) {
6071 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
6077 if (kvm_enabled()) {
6080 ret
= kvm_init(smp_cpus
);
6082 fprintf(stderr
, "failed to initialize KVM\n");
6088 if (monitor_device
) {
6089 monitor_hd
= qemu_chr_open("monitor", monitor_device
, NULL
);
6091 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
6096 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6097 const char *devname
= serial_devices
[i
];
6098 if (devname
&& strcmp(devname
, "none")) {
6100 snprintf(label
, sizeof(label
), "serial%d", i
);
6101 serial_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6102 if (!serial_hds
[i
]) {
6103 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
6110 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
6111 const char *devname
= parallel_devices
[i
];
6112 if (devname
&& strcmp(devname
, "none")) {
6114 snprintf(label
, sizeof(label
), "parallel%d", i
);
6115 parallel_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6116 if (!parallel_hds
[i
]) {
6117 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
6124 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
6125 const char *devname
= virtio_consoles
[i
];
6126 if (devname
&& strcmp(devname
, "none")) {
6128 snprintf(label
, sizeof(label
), "virtcon%d", i
);
6129 virtcon_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6130 if (!virtcon_hds
[i
]) {
6131 fprintf(stderr
, "qemu: could not open virtio console '%s'\n",
6141 machine
->init(ram_size
, vga_ram_size
, boot_devices
,
6142 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
6145 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
6146 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6147 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
6153 current_machine
= machine
;
6155 /* Set KVM's vcpu state to qemu's initial CPUState. */
6156 if (kvm_enabled()) {
6159 ret
= kvm_sync_vcpus();
6161 fprintf(stderr
, "failed to initialize vcpus\n");
6166 /* init USB devices */
6168 for(i
= 0; i
< usb_devices_index
; i
++) {
6169 if (usb_device_add(usb_devices
[i
], 0) < 0) {
6170 fprintf(stderr
, "Warning: could not add USB device %s\n",
6177 dumb_display_init();
6178 /* just use the first displaystate for the moment */
6183 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
6187 #if defined(CONFIG_CURSES)
6189 /* At the moment curses cannot be used with other displays */
6190 curses_display_init(ds
, full_screen
);
6194 if (vnc_display
!= NULL
) {
6195 vnc_display_init(ds
);
6196 if (vnc_display_open(ds
, vnc_display
) < 0)
6199 #if defined(CONFIG_SDL)
6200 if (sdl
|| !vnc_display
)
6201 sdl_display_init(ds
, full_screen
, no_frame
);
6202 #elif defined(CONFIG_COCOA)
6203 if (sdl
|| !vnc_display
)
6204 cocoa_display_init(ds
, full_screen
);
6210 dcl
= ds
->listeners
;
6211 while (dcl
!= NULL
) {
6212 if (dcl
->dpy_refresh
!= NULL
) {
6213 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
6214 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
6219 if (nographic
|| (vnc_display
&& !sdl
)) {
6220 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
6221 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
6224 text_consoles_set_display(display_state
);
6225 qemu_chr_initial_reset();
6227 if (monitor_device
&& monitor_hd
)
6228 monitor_init(monitor_hd
, MONITOR_USE_READLINE
| MONITOR_IS_DEFAULT
);
6230 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6231 const char *devname
= serial_devices
[i
];
6232 if (devname
&& strcmp(devname
, "none")) {
6234 snprintf(label
, sizeof(label
), "serial%d", i
);
6235 if (strstart(devname
, "vc", 0))
6236 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
6240 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
6241 const char *devname
= parallel_devices
[i
];
6242 if (devname
&& strcmp(devname
, "none")) {
6244 snprintf(label
, sizeof(label
), "parallel%d", i
);
6245 if (strstart(devname
, "vc", 0))
6246 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
6250 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
6251 const char *devname
= virtio_consoles
[i
];
6252 if (virtcon_hds
[i
] && devname
) {
6254 snprintf(label
, sizeof(label
), "virtcon%d", i
);
6255 if (strstart(devname
, "vc", 0))
6256 qemu_chr_printf(virtcon_hds
[i
], "virtio console%d\r\n", i
);
6260 #ifdef CONFIG_GDBSTUB
6261 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
6262 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
6269 do_loadvm(cur_mon
, loadvm
);
6272 autostart
= 0; /* fixme how to deal with -daemonize */
6273 qemu_start_incoming_migration(incoming
);
6285 len
= write(fds
[1], &status
, 1);
6286 if (len
== -1 && (errno
== EINTR
))
6293 TFR(fd
= open("/dev/null", O_RDWR
));
6299 pwd
= getpwnam(run_as
);
6301 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
6307 if (chroot(chroot_dir
) < 0) {
6308 fprintf(stderr
, "chroot failed\n");
6315 if (setgid(pwd
->pw_gid
) < 0) {
6316 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
6319 if (setuid(pwd
->pw_uid
) < 0) {
6320 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
6323 if (setuid(0) != -1) {
6324 fprintf(stderr
, "Dropping privileges failed\n");