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
33 /* Needed early for HOST_BSD etc. */
34 #include "config-host.h"
38 #include <sys/times.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
46 #include <netinet/in.h>
48 #if defined(__NetBSD__)
49 #include <net/if_tap.h>
52 #include <linux/if_tun.h>
54 #include <arpa/inet.h>
57 #include <sys/select.h>
60 #if defined(__FreeBSD__) || defined(__DragonFly__)
65 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
66 #include <freebsd/stdlib.h>
71 #include <linux/rtc.h>
73 /* For the benefit of older linux systems which don't supply it,
74 we use a local copy of hpet.h. */
75 /* #include <linux/hpet.h> */
78 #include <linux/ppdev.h>
79 #include <linux/parport.h>
83 #include <sys/ethernet.h>
84 #include <sys/sockio.h>
85 #include <netinet/arp.h>
86 #include <netinet/in.h>
87 #include <netinet/in_systm.h>
88 #include <netinet/ip.h>
89 #include <netinet/ip_icmp.h> // must come after ip.h
90 #include <netinet/udp.h>
91 #include <netinet/tcp.h>
99 #if defined(__OpenBSD__)
103 #if defined(CONFIG_VDE)
104 #include <libvdeplug.h>
110 #include <sys/timeb.h>
111 #include <mmsystem.h>
112 #define getopt_long_only getopt_long
113 #define memalign(align, size) malloc(size)
119 int qemu_main(int argc
, char **argv
, char **envp
);
120 int main(int argc
, char **argv
)
122 qemu_main(argc
, argv
, NULL
);
125 #define main qemu_main
127 #endif /* CONFIG_SDL */
131 #define main qemu_main
132 #endif /* CONFIG_COCOA */
135 #include "hw/boards.h"
137 #include "hw/pcmcia.h"
139 #include "hw/audiodev.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 const char *option_rom
[MAX_OPTION_ROMS
];
264 int semihosting_enabled
= 0;
265 int time_drift_fix
= 0;
266 unsigned int kvm_shadow_memory
= 0;
267 const char *mem_path
= NULL
;
269 int mem_prealloc
= 1; /* force preallocation of physical target memory */
272 const char *cpu_vendor_string
;
276 const char *qemu_name
;
278 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
279 unsigned int nb_prom_envs
= 0;
280 const char *prom_envs
[MAX_PROM_ENVS
];
283 const char *nvram
= NULL
;
284 struct drive_opt drives_opt
[MAX_DRIVES
];
287 uint64_t node_mem
[MAX_NODES
];
288 uint64_t node_cpumask
[MAX_NODES
];
290 static CPUState
*cur_cpu
;
291 static CPUState
*next_cpu
;
292 static int event_pending
= 1;
293 /* Conversion factor from emulated instructions to virtual clock ticks. */
294 static int icount_time_shift
;
295 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
296 #define MAX_ICOUNT_SHIFT 10
297 /* Compensate for varying guest execution speed. */
298 static int64_t qemu_icount_bias
;
299 static QEMUTimer
*icount_rt_timer
;
300 static QEMUTimer
*icount_vm_timer
;
301 static QEMUTimer
*nographic_timer
;
303 uint8_t qemu_uuid
[16];
305 /* KVM runs the main loop in a separate thread. If we update one of the lists
306 * that are polled before or after select(), we need to make sure to break out
307 * of the select() to ensure the new item is serviced.
309 static void main_loop_break(void)
312 qemu_kvm_notify_work();
315 /***********************************************************/
316 /* x86 ISA bus support */
318 target_phys_addr_t isa_mem_base
= 0;
321 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
322 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
324 static uint32_t ioport_read(int index
, uint32_t address
)
326 static IOPortReadFunc
*default_func
[3] = {
327 default_ioport_readb
,
328 default_ioport_readw
,
331 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
333 func
= default_func
[index
];
334 return func(ioport_opaque
[address
], address
);
337 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
339 static IOPortWriteFunc
*default_func
[3] = {
340 default_ioport_writeb
,
341 default_ioport_writew
,
342 default_ioport_writel
344 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
346 func
= default_func
[index
];
347 func(ioport_opaque
[address
], address
, data
);
350 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
352 #ifdef DEBUG_UNUSED_IOPORT
353 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
358 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
360 #ifdef DEBUG_UNUSED_IOPORT
361 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
365 /* default is to make two byte accesses */
366 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
369 data
= ioport_read(0, address
);
370 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
371 data
|= ioport_read(0, address
) << 8;
375 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
377 ioport_write(0, address
, data
& 0xff);
378 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
379 ioport_write(0, address
, (data
>> 8) & 0xff);
382 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
384 #ifdef DEBUG_UNUSED_IOPORT
385 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
390 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
392 #ifdef DEBUG_UNUSED_IOPORT
393 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
397 /* size is the word size in byte */
398 int register_ioport_read(int start
, int length
, int size
,
399 IOPortReadFunc
*func
, void *opaque
)
405 } else if (size
== 2) {
407 } else if (size
== 4) {
410 hw_error("register_ioport_read: invalid size");
413 for(i
= start
; i
< start
+ length
; i
+= size
) {
414 ioport_read_table
[bsize
][i
] = func
;
415 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
416 hw_error("register_ioport_read: invalid opaque");
417 ioport_opaque
[i
] = opaque
;
422 /* size is the word size in byte */
423 int register_ioport_write(int start
, int length
, int size
,
424 IOPortWriteFunc
*func
, void *opaque
)
430 } else if (size
== 2) {
432 } else if (size
== 4) {
435 hw_error("register_ioport_write: invalid size");
438 for(i
= start
; i
< start
+ length
; i
+= size
) {
439 ioport_write_table
[bsize
][i
] = func
;
440 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
441 hw_error("register_ioport_write: invalid opaque");
442 ioport_opaque
[i
] = opaque
;
447 void isa_unassign_ioport(int start
, int length
)
451 for(i
= start
; i
< start
+ length
; i
++) {
452 ioport_read_table
[0][i
] = default_ioport_readb
;
453 ioport_read_table
[1][i
] = default_ioport_readw
;
454 ioport_read_table
[2][i
] = default_ioport_readl
;
456 ioport_write_table
[0][i
] = default_ioport_writeb
;
457 ioport_write_table
[1][i
] = default_ioport_writew
;
458 ioport_write_table
[2][i
] = default_ioport_writel
;
460 ioport_opaque
[i
] = NULL
;
464 /***********************************************************/
466 void cpu_outb(CPUState
*env
, int addr
, int val
)
468 LOG_IOPORT("outb: %04x %02x\n", addr
, val
);
469 ioport_write(0, addr
, val
);
472 env
->last_io_time
= cpu_get_time_fast();
476 void cpu_outw(CPUState
*env
, int addr
, int val
)
478 LOG_IOPORT("outw: %04x %04x\n", addr
, val
);
479 ioport_write(1, addr
, val
);
482 env
->last_io_time
= cpu_get_time_fast();
486 void cpu_outl(CPUState
*env
, int addr
, int val
)
488 LOG_IOPORT("outl: %04x %08x\n", addr
, val
);
489 ioport_write(2, addr
, val
);
492 env
->last_io_time
= cpu_get_time_fast();
496 int cpu_inb(CPUState
*env
, int addr
)
499 val
= ioport_read(0, addr
);
500 LOG_IOPORT("inb : %04x %02x\n", addr
, val
);
503 env
->last_io_time
= cpu_get_time_fast();
508 int cpu_inw(CPUState
*env
, int addr
)
511 val
= ioport_read(1, addr
);
512 LOG_IOPORT("inw : %04x %04x\n", addr
, val
);
515 env
->last_io_time
= cpu_get_time_fast();
520 int cpu_inl(CPUState
*env
, int addr
)
523 val
= ioport_read(2, addr
);
524 LOG_IOPORT("inl : %04x %08x\n", addr
, val
);
527 env
->last_io_time
= cpu_get_time_fast();
532 /***********************************************************/
533 void hw_error(const char *fmt
, ...)
539 fprintf(stderr
, "qemu: hardware error: ");
540 vfprintf(stderr
, fmt
, ap
);
541 fprintf(stderr
, "\n");
542 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
543 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
545 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
547 cpu_dump_state(env
, stderr
, fprintf
, 0);
557 static QEMUBalloonEvent
*qemu_balloon_event
;
558 void *qemu_balloon_event_opaque
;
560 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
562 qemu_balloon_event
= func
;
563 qemu_balloon_event_opaque
= opaque
;
566 void qemu_balloon(ram_addr_t target
)
568 if (qemu_balloon_event
)
569 qemu_balloon_event(qemu_balloon_event_opaque
, target
);
572 ram_addr_t
qemu_balloon_status(void)
574 if (qemu_balloon_event
)
575 return qemu_balloon_event(qemu_balloon_event_opaque
, 0);
579 /***********************************************************/
582 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
583 static void *qemu_put_kbd_event_opaque
;
584 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
585 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
587 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
589 qemu_put_kbd_event_opaque
= opaque
;
590 qemu_put_kbd_event
= func
;
593 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
594 void *opaque
, int absolute
,
597 QEMUPutMouseEntry
*s
, *cursor
;
599 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
601 s
->qemu_put_mouse_event
= func
;
602 s
->qemu_put_mouse_event_opaque
= opaque
;
603 s
->qemu_put_mouse_event_absolute
= absolute
;
604 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
607 if (!qemu_put_mouse_event_head
) {
608 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
612 cursor
= qemu_put_mouse_event_head
;
613 while (cursor
->next
!= NULL
)
614 cursor
= cursor
->next
;
617 qemu_put_mouse_event_current
= s
;
622 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
624 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
626 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
629 cursor
= qemu_put_mouse_event_head
;
630 while (cursor
!= NULL
&& cursor
!= entry
) {
632 cursor
= cursor
->next
;
635 if (cursor
== NULL
) // does not exist or list empty
637 else if (prev
== NULL
) { // entry is head
638 qemu_put_mouse_event_head
= cursor
->next
;
639 if (qemu_put_mouse_event_current
== entry
)
640 qemu_put_mouse_event_current
= cursor
->next
;
641 qemu_free(entry
->qemu_put_mouse_event_name
);
646 prev
->next
= entry
->next
;
648 if (qemu_put_mouse_event_current
== entry
)
649 qemu_put_mouse_event_current
= prev
;
651 qemu_free(entry
->qemu_put_mouse_event_name
);
655 void kbd_put_keycode(int keycode
)
657 if (qemu_put_kbd_event
) {
658 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
662 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
664 QEMUPutMouseEvent
*mouse_event
;
665 void *mouse_event_opaque
;
668 if (!qemu_put_mouse_event_current
) {
673 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
675 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
678 if (graphic_rotate
) {
679 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
682 width
= graphic_width
- 1;
683 mouse_event(mouse_event_opaque
,
684 width
- dy
, dx
, dz
, buttons_state
);
686 mouse_event(mouse_event_opaque
,
687 dx
, dy
, dz
, buttons_state
);
691 int kbd_mouse_is_absolute(void)
693 if (!qemu_put_mouse_event_current
)
696 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
699 void do_info_mice(Monitor
*mon
)
701 QEMUPutMouseEntry
*cursor
;
704 if (!qemu_put_mouse_event_head
) {
705 monitor_printf(mon
, "No mouse devices connected\n");
709 monitor_printf(mon
, "Mouse devices available:\n");
710 cursor
= qemu_put_mouse_event_head
;
711 while (cursor
!= NULL
) {
712 monitor_printf(mon
, "%c Mouse #%d: %s\n",
713 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
714 index
, cursor
->qemu_put_mouse_event_name
);
716 cursor
= cursor
->next
;
720 void do_mouse_set(Monitor
*mon
, int index
)
722 QEMUPutMouseEntry
*cursor
;
725 if (!qemu_put_mouse_event_head
) {
726 monitor_printf(mon
, "No mouse devices connected\n");
730 cursor
= qemu_put_mouse_event_head
;
731 while (cursor
!= NULL
&& index
!= i
) {
733 cursor
= cursor
->next
;
737 qemu_put_mouse_event_current
= cursor
;
739 monitor_printf(mon
, "Mouse at given index not found\n");
742 /* compute with 96 bit intermediate result: (a*b)/c */
743 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
748 #ifdef WORDS_BIGENDIAN
758 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
759 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
762 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
766 /***********************************************************/
767 /* real time host monotonic timer */
769 #define QEMU_TIMER_BASE 1000000000LL
773 static int64_t clock_freq
;
775 static void init_get_clock(void)
779 ret
= QueryPerformanceFrequency(&freq
);
781 fprintf(stderr
, "Could not calibrate ticks\n");
784 clock_freq
= freq
.QuadPart
;
787 static int64_t get_clock(void)
790 QueryPerformanceCounter(&ti
);
791 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
796 static int use_rt_clock
;
798 static void init_get_clock(void)
801 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
802 || defined(__DragonFly__)
805 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
812 static int64_t get_clock(void)
814 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
815 || defined(__DragonFly__)
818 clock_gettime(CLOCK_MONOTONIC
, &ts
);
819 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
823 /* XXX: using gettimeofday leads to problems if the date
824 changes, so it should be avoided. */
826 gettimeofday(&tv
, NULL
);
827 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
832 /* Return the virtual CPU time, based on the instruction counter. */
833 static int64_t cpu_get_icount(void)
836 CPUState
*env
= cpu_single_env
;;
837 icount
= qemu_icount
;
840 fprintf(stderr
, "Bad clock read\n");
841 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
843 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
846 /***********************************************************/
847 /* guest cycle counter */
849 static int64_t cpu_ticks_prev
;
850 static int64_t cpu_ticks_offset
;
851 static int64_t cpu_clock_offset
;
852 static int cpu_ticks_enabled
;
854 /* return the host CPU cycle counter and handle stop/restart */
855 int64_t cpu_get_ticks(void)
858 return cpu_get_icount();
860 if (!cpu_ticks_enabled
) {
861 return cpu_ticks_offset
;
864 ticks
= cpu_get_real_ticks();
865 if (cpu_ticks_prev
> ticks
) {
866 /* Note: non increasing ticks may happen if the host uses
868 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
870 cpu_ticks_prev
= ticks
;
871 return ticks
+ cpu_ticks_offset
;
875 /* return the host CPU monotonic timer and handle stop/restart */
876 static int64_t cpu_get_clock(void)
879 if (!cpu_ticks_enabled
) {
880 return cpu_clock_offset
;
883 return ti
+ cpu_clock_offset
;
887 /* enable cpu_get_ticks() */
888 void cpu_enable_ticks(void)
890 if (!cpu_ticks_enabled
) {
891 cpu_ticks_offset
-= cpu_get_real_ticks();
892 cpu_clock_offset
-= get_clock();
893 cpu_ticks_enabled
= 1;
897 /* disable cpu_get_ticks() : the clock is stopped. You must not call
898 cpu_get_ticks() after that. */
899 void cpu_disable_ticks(void)
901 if (cpu_ticks_enabled
) {
902 cpu_ticks_offset
= cpu_get_ticks();
903 cpu_clock_offset
= cpu_get_clock();
904 cpu_ticks_enabled
= 0;
908 /***********************************************************/
911 #define QEMU_TIMER_REALTIME 0
912 #define QEMU_TIMER_VIRTUAL 1
916 /* XXX: add frequency */
924 struct QEMUTimer
*next
;
927 struct qemu_alarm_timer
{
931 int (*start
)(struct qemu_alarm_timer
*t
);
932 void (*stop
)(struct qemu_alarm_timer
*t
);
933 void (*rearm
)(struct qemu_alarm_timer
*t
);
937 #define ALARM_FLAG_DYNTICKS 0x1
938 #define ALARM_FLAG_EXPIRED 0x2
940 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
942 return t
->flags
& ALARM_FLAG_DYNTICKS
;
945 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
947 if (!alarm_has_dynticks(t
))
953 /* TODO: MIN_TIMER_REARM_US should be optimized */
954 #define MIN_TIMER_REARM_US 250
956 static struct qemu_alarm_timer
*alarm_timer
;
958 static int alarm_timer_rfd
, alarm_timer_wfd
;
963 struct qemu_alarm_win32
{
967 } alarm_win32_data
= {0, NULL
, -1};
969 static int win32_start_timer(struct qemu_alarm_timer
*t
);
970 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
971 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
975 static int unix_start_timer(struct qemu_alarm_timer
*t
);
976 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
980 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
981 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
982 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
984 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
985 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
987 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
988 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
990 #endif /* __linux__ */
994 /* Correlation between real and virtual time is always going to be
995 fairly approximate, so ignore small variation.
996 When the guest is idle real and virtual time will be aligned in
998 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
1000 static void icount_adjust(void)
1005 static int64_t last_delta
;
1006 /* If the VM is not running, then do nothing. */
1010 cur_time
= cpu_get_clock();
1011 cur_icount
= qemu_get_clock(vm_clock
);
1012 delta
= cur_icount
- cur_time
;
1013 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1015 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
1016 && icount_time_shift
> 0) {
1017 /* The guest is getting too far ahead. Slow time down. */
1018 icount_time_shift
--;
1021 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
1022 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
1023 /* The guest is getting too far behind. Speed time up. */
1024 icount_time_shift
++;
1027 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
1030 static void icount_adjust_rt(void * opaque
)
1032 qemu_mod_timer(icount_rt_timer
,
1033 qemu_get_clock(rt_clock
) + 1000);
1037 static void icount_adjust_vm(void * opaque
)
1039 qemu_mod_timer(icount_vm_timer
,
1040 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1044 static void init_icount_adjust(void)
1046 /* Have both realtime and virtual time triggers for speed adjustment.
1047 The realtime trigger catches emulated time passing too slowly,
1048 the virtual time trigger catches emulated time passing too fast.
1049 Realtime triggers occur even when idle, so use them less frequently
1050 than VM triggers. */
1051 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
1052 qemu_mod_timer(icount_rt_timer
,
1053 qemu_get_clock(rt_clock
) + 1000);
1054 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
1055 qemu_mod_timer(icount_vm_timer
,
1056 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1059 static struct qemu_alarm_timer alarm_timers
[] = {
1062 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
1063 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
1064 /* HPET - if available - is preferred */
1065 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
1066 /* ...otherwise try RTC */
1067 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1069 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1071 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1072 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1073 {"win32", 0, win32_start_timer
,
1074 win32_stop_timer
, NULL
, &alarm_win32_data
},
1079 static void show_available_alarms(void)
1083 printf("Available alarm timers, in order of precedence:\n");
1084 for (i
= 0; alarm_timers
[i
].name
; i
++)
1085 printf("%s\n", alarm_timers
[i
].name
);
1088 static void configure_alarms(char const *opt
)
1092 int count
= ARRAY_SIZE(alarm_timers
) - 1;
1095 struct qemu_alarm_timer tmp
;
1097 if (!strcmp(opt
, "?")) {
1098 show_available_alarms();
1104 /* Reorder the array */
1105 name
= strtok(arg
, ",");
1107 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1108 if (!strcmp(alarm_timers
[i
].name
, name
))
1113 fprintf(stderr
, "Unknown clock %s\n", name
);
1122 tmp
= alarm_timers
[i
];
1123 alarm_timers
[i
] = alarm_timers
[cur
];
1124 alarm_timers
[cur
] = tmp
;
1128 name
= strtok(NULL
, ",");
1134 /* Disable remaining timers */
1135 for (i
= cur
; i
< count
; i
++)
1136 alarm_timers
[i
].name
= NULL
;
1138 show_available_alarms();
1143 QEMUClock
*rt_clock
;
1144 QEMUClock
*vm_clock
;
1146 static QEMUTimer
*active_timers
[2];
1148 static QEMUClock
*qemu_new_clock(int type
)
1151 clock
= qemu_mallocz(sizeof(QEMUClock
));
1156 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1160 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1163 ts
->opaque
= opaque
;
1167 void qemu_free_timer(QEMUTimer
*ts
)
1172 /* stop a timer, but do not dealloc it */
1173 void qemu_del_timer(QEMUTimer
*ts
)
1177 /* NOTE: this code must be signal safe because
1178 qemu_timer_expired() can be called from a signal. */
1179 pt
= &active_timers
[ts
->clock
->type
];
1192 /* modify the current timer so that it will be fired when current_time
1193 >= expire_time. The corresponding callback will be called. */
1194 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1200 /* add the timer in the sorted list */
1201 /* NOTE: this code must be signal safe because
1202 qemu_timer_expired() can be called from a signal. */
1203 pt
= &active_timers
[ts
->clock
->type
];
1208 if (t
->expire_time
> expire_time
)
1212 ts
->expire_time
= expire_time
;
1216 /* Rearm if necessary */
1217 if (pt
== &active_timers
[ts
->clock
->type
]) {
1218 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1219 qemu_rearm_alarm_timer(alarm_timer
);
1221 /* Interrupt execution to force deadline recalculation. */
1222 if (use_icount
&& cpu_single_env
) {
1223 cpu_exit(cpu_single_env
);
1228 int qemu_timer_pending(QEMUTimer
*ts
)
1231 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1238 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1242 return (timer_head
->expire_time
<= current_time
);
1245 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1251 if (!ts
|| ts
->expire_time
> current_time
)
1253 /* remove timer from the list before calling the callback */
1254 *ptimer_head
= ts
->next
;
1257 /* run the callback (the timer list can be modified) */
1262 int64_t qemu_get_clock(QEMUClock
*clock
)
1264 switch(clock
->type
) {
1265 case QEMU_TIMER_REALTIME
:
1266 return get_clock() / 1000000;
1268 case QEMU_TIMER_VIRTUAL
:
1270 return cpu_get_icount();
1272 return cpu_get_clock();
1277 static void init_timers(void)
1280 ticks_per_sec
= QEMU_TIMER_BASE
;
1281 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1282 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1286 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1288 uint64_t expire_time
;
1290 if (qemu_timer_pending(ts
)) {
1291 expire_time
= ts
->expire_time
;
1295 qemu_put_be64(f
, expire_time
);
1298 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1300 uint64_t expire_time
;
1302 expire_time
= qemu_get_be64(f
);
1303 if (expire_time
!= -1) {
1304 qemu_mod_timer(ts
, expire_time
);
1310 static void timer_save(QEMUFile
*f
, void *opaque
)
1312 if (cpu_ticks_enabled
) {
1313 hw_error("cannot save state if virtual timers are running");
1315 qemu_put_be64(f
, cpu_ticks_offset
);
1316 qemu_put_be64(f
, ticks_per_sec
);
1317 qemu_put_be64(f
, cpu_clock_offset
);
1320 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1322 if (version_id
!= 1 && version_id
!= 2)
1324 if (cpu_ticks_enabled
) {
1327 cpu_ticks_offset
=qemu_get_be64(f
);
1328 ticks_per_sec
=qemu_get_be64(f
);
1329 if (version_id
== 2) {
1330 cpu_clock_offset
=qemu_get_be64(f
);
1336 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1337 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1340 static void host_alarm_handler(int host_signum
)
1344 #define DISP_FREQ 1000
1346 static int64_t delta_min
= INT64_MAX
;
1347 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1349 ti
= qemu_get_clock(vm_clock
);
1350 if (last_clock
!= 0) {
1351 delta
= ti
- last_clock
;
1352 if (delta
< delta_min
)
1354 if (delta
> delta_max
)
1357 if (++count
== DISP_FREQ
) {
1358 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1359 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1360 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1361 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1362 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1364 delta_min
= INT64_MAX
;
1373 alarm_has_dynticks(alarm_timer
) ||
1375 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1376 qemu_get_clock(vm_clock
))) ||
1377 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1378 qemu_get_clock(rt_clock
))) {
1379 CPUState
*env
= next_cpu
;
1382 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1383 SetEvent(data
->host_alarm
);
1385 static const char byte
= 0;
1386 write(alarm_timer_wfd
, &byte
, sizeof(byte
));
1388 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1391 /* stop the currently executing cpu because a timer occured */
1394 if (env
->kqemu_enabled
) {
1395 kqemu_cpu_interrupt(env
);
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) */
1675 static void try_to_rearm_timer(void *opaque
)
1677 struct qemu_alarm_timer
*t
= opaque
;
1681 /* Drain the notify pipe */
1684 len
= read(alarm_timer_rfd
, buffer
, sizeof(buffer
));
1685 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
1688 if (t
->flags
& ALARM_FLAG_EXPIRED
) {
1689 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
1690 qemu_rearm_alarm_timer(alarm_timer
);
1696 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1699 struct qemu_alarm_win32
*data
= t
->priv
;
1702 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1703 if (!data
->host_alarm
) {
1704 perror("Failed CreateEvent");
1708 memset(&tc
, 0, sizeof(tc
));
1709 timeGetDevCaps(&tc
, sizeof(tc
));
1711 if (data
->period
< tc
.wPeriodMin
)
1712 data
->period
= tc
.wPeriodMin
;
1714 timeBeginPeriod(data
->period
);
1716 flags
= TIME_CALLBACK_FUNCTION
;
1717 if (alarm_has_dynticks(t
))
1718 flags
|= TIME_ONESHOT
;
1720 flags
|= TIME_PERIODIC
;
1722 data
->timerId
= timeSetEvent(1, // interval (ms)
1723 data
->period
, // resolution
1724 host_alarm_handler
, // function
1725 (DWORD
)t
, // parameter
1728 if (!data
->timerId
) {
1729 perror("Failed to initialize win32 alarm timer");
1731 timeEndPeriod(data
->period
);
1732 CloseHandle(data
->host_alarm
);
1736 qemu_add_wait_object(data
->host_alarm
, try_to_rearm_timer
, t
);
1741 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1743 struct qemu_alarm_win32
*data
= t
->priv
;
1745 timeKillEvent(data
->timerId
);
1746 timeEndPeriod(data
->period
);
1748 CloseHandle(data
->host_alarm
);
1751 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1753 struct qemu_alarm_win32
*data
= t
->priv
;
1754 uint64_t nearest_delta_us
;
1756 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1757 !active_timers
[QEMU_TIMER_VIRTUAL
])
1760 nearest_delta_us
= qemu_next_deadline_dyntick();
1761 nearest_delta_us
/= 1000;
1763 timeKillEvent(data
->timerId
);
1765 data
->timerId
= timeSetEvent(1,
1769 TIME_ONESHOT
| TIME_PERIODIC
);
1771 if (!data
->timerId
) {
1772 perror("Failed to re-arm win32 alarm timer");
1774 timeEndPeriod(data
->period
);
1775 CloseHandle(data
->host_alarm
);
1782 static int init_timer_alarm(void)
1784 struct qemu_alarm_timer
*t
= NULL
;
1794 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
1798 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
1802 alarm_timer_rfd
= fds
[0];
1803 alarm_timer_wfd
= fds
[1];
1806 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1807 t
= &alarm_timers
[i
];
1820 qemu_set_fd_handler2(alarm_timer_rfd
, NULL
,
1821 try_to_rearm_timer
, NULL
, t
);
1836 static void quit_timers(void)
1838 alarm_timer
->stop(alarm_timer
);
1842 /***********************************************************/
1843 /* host time/date access */
1844 void qemu_get_timedate(struct tm
*tm
, int offset
)
1851 if (rtc_date_offset
== -1) {
1855 ret
= localtime(&ti
);
1857 ti
-= rtc_date_offset
;
1861 memcpy(tm
, ret
, sizeof(struct tm
));
1864 int qemu_timedate_diff(struct tm
*tm
)
1868 if (rtc_date_offset
== -1)
1870 seconds
= mktimegm(tm
);
1872 seconds
= mktime(tm
);
1874 seconds
= mktimegm(tm
) + rtc_date_offset
;
1876 return seconds
- time(NULL
);
1880 static void socket_cleanup(void)
1885 static int socket_init(void)
1890 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1892 err
= WSAGetLastError();
1893 fprintf(stderr
, "WSAStartup: %d\n", err
);
1896 atexit(socket_cleanup
);
1901 const char *get_opt_name(char *buf
, int buf_size
, const char *p
, char delim
)
1906 while (*p
!= '\0' && *p
!= delim
) {
1907 if (q
&& (q
- buf
) < buf_size
- 1)
1917 const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
1922 while (*p
!= '\0') {
1924 if (*(p
+ 1) != ',')
1928 if (q
&& (q
- buf
) < buf_size
- 1)
1938 int get_param_value(char *buf
, int buf_size
,
1939 const char *tag
, const char *str
)
1946 p
= get_opt_name(option
, sizeof(option
), p
, '=');
1950 if (!strcmp(tag
, option
)) {
1951 (void)get_opt_value(buf
, buf_size
, p
);
1954 p
= get_opt_value(NULL
, 0, p
);
1963 int check_params(char *buf
, int buf_size
,
1964 const char * const *params
, const char *str
)
1970 while (*p
!= '\0') {
1971 p
= get_opt_name(buf
, buf_size
, p
, '=');
1975 for(i
= 0; params
[i
] != NULL
; i
++)
1976 if (!strcmp(params
[i
], buf
))
1978 if (params
[i
] == NULL
)
1980 p
= get_opt_value(NULL
, 0, p
);
1988 /***********************************************************/
1989 /* Bluetooth support */
1992 static struct HCIInfo
*hci_table
[MAX_NICS
];
1994 static struct bt_vlan_s
{
1995 struct bt_scatternet_s net
;
1997 struct bt_vlan_s
*next
;
2000 /* find or alloc a new bluetooth "VLAN" */
2001 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
2003 struct bt_vlan_s
**pvlan
, *vlan
;
2004 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
2008 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
2010 pvlan
= &first_bt_vlan
;
2011 while (*pvlan
!= NULL
)
2012 pvlan
= &(*pvlan
)->next
;
2017 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
2021 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
2026 static struct HCIInfo null_hci
= {
2027 .cmd_send
= null_hci_send
,
2028 .sco_send
= null_hci_send
,
2029 .acl_send
= null_hci_send
,
2030 .bdaddr_set
= null_hci_addr_set
,
2033 struct HCIInfo
*qemu_next_hci(void)
2035 if (cur_hci
== nb_hcis
)
2038 return hci_table
[cur_hci
++];
2041 static struct HCIInfo
*hci_init(const char *str
)
2044 struct bt_scatternet_s
*vlan
= 0;
2046 if (!strcmp(str
, "null"))
2049 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
2051 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
2052 else if (!strncmp(str
, "hci", 3)) {
2055 if (!strncmp(str
+ 3, ",vlan=", 6)) {
2056 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
2061 vlan
= qemu_find_bt_vlan(0);
2063 return bt_new_hci(vlan
);
2066 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
2071 static int bt_hci_parse(const char *str
)
2073 struct HCIInfo
*hci
;
2076 if (nb_hcis
>= MAX_NICS
) {
2077 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
2081 hci
= hci_init(str
);
2090 bdaddr
.b
[5] = 0x56 + nb_hcis
;
2091 hci
->bdaddr_set(hci
, bdaddr
.b
);
2093 hci_table
[nb_hcis
++] = hci
;
2098 static void bt_vhci_add(int vlan_id
)
2100 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
2103 fprintf(stderr
, "qemu: warning: adding a VHCI to "
2104 "an empty scatternet %i\n", vlan_id
);
2106 bt_vhci_init(bt_new_hci(vlan
));
2109 static struct bt_device_s
*bt_device_add(const char *opt
)
2111 struct bt_scatternet_s
*vlan
;
2113 char *endp
= strstr(opt
, ",vlan=");
2114 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
2117 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
2120 vlan_id
= strtol(endp
+ 6, &endp
, 0);
2122 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
2127 vlan
= qemu_find_bt_vlan(vlan_id
);
2130 fprintf(stderr
, "qemu: warning: adding a slave device to "
2131 "an empty scatternet %i\n", vlan_id
);
2133 if (!strcmp(devname
, "keyboard"))
2134 return bt_keyboard_init(vlan
);
2136 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
2140 static int bt_parse(const char *opt
)
2142 const char *endp
, *p
;
2145 if (strstart(opt
, "hci", &endp
)) {
2146 if (!*endp
|| *endp
== ',') {
2148 if (!strstart(endp
, ",vlan=", 0))
2151 return bt_hci_parse(opt
);
2153 } else if (strstart(opt
, "vhci", &endp
)) {
2154 if (!*endp
|| *endp
== ',') {
2156 if (strstart(endp
, ",vlan=", &p
)) {
2157 vlan
= strtol(p
, (char **) &endp
, 0);
2159 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
2163 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
2172 } else if (strstart(opt
, "device:", &endp
))
2173 return !bt_device_add(endp
);
2175 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
2179 /***********************************************************/
2180 /* QEMU Block devices */
2182 #define HD_ALIAS "index=%d,media=disk"
2183 #define CDROM_ALIAS "index=2,media=cdrom"
2184 #define FD_ALIAS "index=%d,if=floppy"
2185 #define PFLASH_ALIAS "if=pflash"
2186 #define MTD_ALIAS "if=mtd"
2187 #define SD_ALIAS "index=0,if=sd"
2189 static int drive_opt_get_free_idx(void)
2193 for (index
= 0; index
< MAX_DRIVES
; index
++)
2194 if (!drives_opt
[index
].used
) {
2195 drives_opt
[index
].used
= 1;
2202 static int drive_get_free_idx(void)
2206 for (index
= 0; index
< MAX_DRIVES
; index
++)
2207 if (!drives_table
[index
].used
) {
2208 drives_table
[index
].used
= 1;
2215 int drive_add(const char *file
, const char *fmt
, ...)
2218 int index
= drive_opt_get_free_idx();
2220 if (nb_drives_opt
>= MAX_DRIVES
|| index
== -1) {
2221 fprintf(stderr
, "qemu: too many drives\n");
2225 drives_opt
[index
].file
= file
;
2227 vsnprintf(drives_opt
[index
].opt
,
2228 sizeof(drives_opt
[0].opt
), fmt
, ap
);
2235 void drive_remove(int index
)
2237 drives_opt
[index
].used
= 0;
2241 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
2245 /* seek interface, bus and unit */
2247 for (index
= 0; index
< MAX_DRIVES
; index
++)
2248 if (drives_table
[index
].type
== type
&&
2249 drives_table
[index
].bus
== bus
&&
2250 drives_table
[index
].unit
== unit
&&
2251 drives_table
[index
].used
)
2257 int drive_get_max_bus(BlockInterfaceType type
)
2263 for (index
= 0; index
< nb_drives
; index
++) {
2264 if(drives_table
[index
].type
== type
&&
2265 drives_table
[index
].bus
> max_bus
)
2266 max_bus
= drives_table
[index
].bus
;
2271 const char *drive_get_serial(BlockDriverState
*bdrv
)
2275 for (index
= 0; index
< nb_drives
; index
++)
2276 if (drives_table
[index
].bdrv
== bdrv
)
2277 return drives_table
[index
].serial
;
2282 BlockInterfaceErrorAction
drive_get_onerror(BlockDriverState
*bdrv
)
2286 for (index
= 0; index
< nb_drives
; index
++)
2287 if (drives_table
[index
].bdrv
== bdrv
)
2288 return drives_table
[index
].onerror
;
2290 return BLOCK_ERR_STOP_ENOSPC
;
2293 static void bdrv_format_print(void *opaque
, const char *name
)
2295 fprintf(stderr
, " %s", name
);
2298 void drive_uninit(BlockDriverState
*bdrv
)
2302 for (i
= 0; i
< MAX_DRIVES
; i
++)
2303 if (drives_table
[i
].bdrv
== bdrv
) {
2304 drives_table
[i
].bdrv
= NULL
;
2305 drives_table
[i
].used
= 0;
2306 drive_remove(drives_table
[i
].drive_opt_idx
);
2312 int drive_init(struct drive_opt
*arg
, int snapshot
, void *opaque
)
2318 const char *mediastr
= "";
2319 BlockInterfaceType type
;
2320 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
2321 int bus_id
, unit_id
;
2322 int cyls
, heads
, secs
, translation
;
2323 BlockDriverState
*bdrv
;
2324 BlockDriver
*drv
= NULL
;
2325 QEMUMachine
*machine
= opaque
;
2329 int bdrv_flags
, onerror
;
2330 int drives_table_idx
;
2331 char *str
= arg
->opt
;
2332 static const char * const params
[] = { "bus", "unit", "if", "index",
2333 "cyls", "heads", "secs", "trans",
2334 "media", "snapshot", "file",
2335 "cache", "format", "serial", "werror",
2338 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
2339 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
2345 cyls
= heads
= secs
= 0;
2348 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2352 if (machine
->use_scsi
) {
2354 max_devs
= MAX_SCSI_DEVS
;
2355 pstrcpy(devname
, sizeof(devname
), "scsi");
2358 max_devs
= MAX_IDE_DEVS
;
2359 pstrcpy(devname
, sizeof(devname
), "ide");
2363 /* extract parameters */
2365 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
2366 bus_id
= strtol(buf
, NULL
, 0);
2368 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
2373 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
2374 unit_id
= strtol(buf
, NULL
, 0);
2376 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
2381 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
2382 pstrcpy(devname
, sizeof(devname
), buf
);
2383 if (!strcmp(buf
, "ide")) {
2385 max_devs
= MAX_IDE_DEVS
;
2386 } else if (!strcmp(buf
, "scsi")) {
2388 max_devs
= MAX_SCSI_DEVS
;
2389 } else if (!strcmp(buf
, "floppy")) {
2392 } else if (!strcmp(buf
, "pflash")) {
2395 } else if (!strcmp(buf
, "mtd")) {
2398 } else if (!strcmp(buf
, "sd")) {
2401 } else if (!strcmp(buf
, "virtio")) {
2404 } else if (!strcmp(buf
, "xen")) {
2408 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
2413 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
2414 index
= strtol(buf
, NULL
, 0);
2416 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
2421 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
2422 cyls
= strtol(buf
, NULL
, 0);
2425 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
2426 heads
= strtol(buf
, NULL
, 0);
2429 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
2430 secs
= strtol(buf
, NULL
, 0);
2433 if (cyls
|| heads
|| secs
) {
2434 if (cyls
< 1 || cyls
> 16383) {
2435 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
2438 if (heads
< 1 || heads
> 16) {
2439 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
2442 if (secs
< 1 || secs
> 63) {
2443 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
2448 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
2451 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2455 if (!strcmp(buf
, "none"))
2456 translation
= BIOS_ATA_TRANSLATION_NONE
;
2457 else if (!strcmp(buf
, "lba"))
2458 translation
= BIOS_ATA_TRANSLATION_LBA
;
2459 else if (!strcmp(buf
, "auto"))
2460 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2462 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
2467 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
2468 if (!strcmp(buf
, "disk")) {
2470 } else if (!strcmp(buf
, "cdrom")) {
2471 if (cyls
|| secs
|| heads
) {
2473 "qemu: '%s' invalid physical CHS format\n", str
);
2476 media
= MEDIA_CDROM
;
2478 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
2483 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
2484 if (!strcmp(buf
, "on"))
2486 else if (!strcmp(buf
, "off"))
2489 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
2494 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
2495 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2497 else if (!strcmp(buf
, "writethrough"))
2499 else if (!strcmp(buf
, "writeback"))
2502 fprintf(stderr
, "qemu: invalid cache option\n");
2507 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
2508 if (strcmp(buf
, "?") == 0) {
2509 fprintf(stderr
, "qemu: Supported formats:");
2510 bdrv_iterate_format(bdrv_format_print
, NULL
);
2511 fprintf(stderr
, "\n");
2514 drv
= bdrv_find_format(buf
);
2516 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2521 if (get_param_value(buf
, sizeof(buf
), "boot", str
)) {
2522 if (!strcmp(buf
, "on")) {
2523 if (extboot_drive
!= -1) {
2524 fprintf(stderr
, "qemu: two bootable drives specified\n");
2527 extboot_drive
= nb_drives
;
2528 } else if (strcmp(buf
, "off")) {
2529 fprintf(stderr
, "qemu: '%s' invalid boot option\n", str
);
2534 if (arg
->file
== NULL
)
2535 get_param_value(file
, sizeof(file
), "file", str
);
2537 pstrcpy(file
, sizeof(file
), arg
->file
);
2539 if (!get_param_value(serial
, sizeof(serial
), "serial", str
))
2540 memset(serial
, 0, sizeof(serial
));
2542 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2543 if (get_param_value(buf
, sizeof(serial
), "werror", str
)) {
2544 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2545 fprintf(stderr
, "werror is no supported by this format\n");
2548 if (!strcmp(buf
, "ignore"))
2549 onerror
= BLOCK_ERR_IGNORE
;
2550 else if (!strcmp(buf
, "enospc"))
2551 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2552 else if (!strcmp(buf
, "stop"))
2553 onerror
= BLOCK_ERR_STOP_ANY
;
2554 else if (!strcmp(buf
, "report"))
2555 onerror
= BLOCK_ERR_REPORT
;
2557 fprintf(stderr
, "qemu: '%s' invalid write error action\n", buf
);
2562 /* compute bus and unit according index */
2565 if (bus_id
!= 0 || unit_id
!= -1) {
2567 "qemu: '%s' index cannot be used with bus and unit\n", str
);
2575 unit_id
= index
% max_devs
;
2576 bus_id
= index
/ max_devs
;
2580 /* if user doesn't specify a unit_id,
2581 * try to find the first free
2584 if (unit_id
== -1) {
2586 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
2588 if (max_devs
&& unit_id
>= max_devs
) {
2589 unit_id
-= max_devs
;
2597 if (max_devs
&& unit_id
>= max_devs
) {
2598 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
2599 str
, unit_id
, max_devs
- 1);
2604 * ignore multiple definitions
2607 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
2612 if (type
== IF_IDE
|| type
== IF_SCSI
)
2613 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2615 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
2616 devname
, bus_id
, mediastr
, unit_id
);
2618 snprintf(buf
, sizeof(buf
), "%s%s%i",
2619 devname
, mediastr
, unit_id
);
2620 bdrv
= bdrv_new(buf
);
2621 drives_table_idx
= drive_get_free_idx();
2622 drives_table
[drives_table_idx
].bdrv
= bdrv
;
2623 drives_table
[drives_table_idx
].type
= type
;
2624 drives_table
[drives_table_idx
].bus
= bus_id
;
2625 drives_table
[drives_table_idx
].unit
= unit_id
;
2626 drives_table
[drives_table_idx
].onerror
= onerror
;
2627 drives_table
[drives_table_idx
].drive_opt_idx
= arg
- drives_opt
;
2628 strncpy(drives_table
[drives_table_idx
].serial
, serial
, sizeof(serial
));
2638 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
2639 bdrv_set_translation_hint(bdrv
, translation
);
2643 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
2648 /* FIXME: This isn't really a floppy, but it's a reasonable
2651 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
2662 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2663 cache
= 2; /* always use write-back with snapshot */
2665 if (cache
== 0) /* no caching */
2666 bdrv_flags
|= BDRV_O_NOCACHE
;
2667 else if (cache
== 2) /* write-back */
2668 bdrv_flags
|= BDRV_O_CACHE_WB
;
2669 else if (cache
== 3) /* not specified */
2670 bdrv_flags
|= BDRV_O_CACHE_DEF
;
2671 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0) {
2672 fprintf(stderr
, "qemu: could not open disk image %s\n",
2676 if (bdrv_key_required(bdrv
))
2678 return drives_table_idx
;
2681 static void numa_add(const char *optarg
)
2685 unsigned long long value
, endvalue
;
2688 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2689 if (!strcmp(option
, "node")) {
2690 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2691 nodenr
= nb_numa_nodes
;
2693 nodenr
= strtoull(option
, NULL
, 10);
2696 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2697 node_mem
[nodenr
] = 0;
2699 value
= strtoull(option
, &endptr
, 0);
2701 case 0: case 'M': case 'm':
2708 node_mem
[nodenr
] = value
;
2710 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2711 node_cpumask
[nodenr
] = 0;
2713 value
= strtoull(option
, &endptr
, 10);
2716 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2718 if (*endptr
== '-') {
2719 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2720 if (endvalue
>= 63) {
2723 "only 63 CPUs in NUMA mode supported.\n");
2725 value
= (1 << (endvalue
+ 1)) - (1 << value
);
2730 node_cpumask
[nodenr
] = value
;
2737 /***********************************************************/
2740 static USBPort
*used_usb_ports
;
2741 static USBPort
*free_usb_ports
;
2743 /* ??? Maybe change this to register a hub to keep track of the topology. */
2744 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
2745 usb_attachfn attach
)
2747 port
->opaque
= opaque
;
2748 port
->index
= index
;
2749 port
->attach
= attach
;
2750 port
->next
= free_usb_ports
;
2751 free_usb_ports
= port
;
2754 int usb_device_add_dev(USBDevice
*dev
)
2758 /* Find a USB port to add the device to. */
2759 port
= free_usb_ports
;
2763 /* Create a new hub and chain it on. */
2764 free_usb_ports
= NULL
;
2765 port
->next
= used_usb_ports
;
2766 used_usb_ports
= port
;
2768 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
2769 usb_attach(port
, hub
);
2770 port
= free_usb_ports
;
2773 free_usb_ports
= port
->next
;
2774 port
->next
= used_usb_ports
;
2775 used_usb_ports
= port
;
2776 usb_attach(port
, dev
);
2780 static void usb_msd_password_cb(void *opaque
, int err
)
2782 USBDevice
*dev
= opaque
;
2785 usb_device_add_dev(dev
);
2787 dev
->handle_destroy(dev
);
2790 static int usb_device_add(const char *devname
, int is_hotplug
)
2795 if (!free_usb_ports
)
2798 if (strstart(devname
, "host:", &p
)) {
2799 dev
= usb_host_device_open(p
);
2800 } else if (!strcmp(devname
, "mouse")) {
2801 dev
= usb_mouse_init();
2802 } else if (!strcmp(devname
, "tablet")) {
2803 dev
= usb_tablet_init();
2804 } else if (!strcmp(devname
, "keyboard")) {
2805 dev
= usb_keyboard_init();
2806 } else if (strstart(devname
, "disk:", &p
)) {
2807 BlockDriverState
*bs
;
2809 dev
= usb_msd_init(p
);
2812 bs
= usb_msd_get_bdrv(dev
);
2813 if (bdrv_key_required(bs
)) {
2816 monitor_read_bdrv_key_start(cur_mon
, bs
, usb_msd_password_cb
,
2821 } else if (!strcmp(devname
, "wacom-tablet")) {
2822 dev
= usb_wacom_init();
2823 } else if (strstart(devname
, "serial:", &p
)) {
2824 dev
= usb_serial_init(p
);
2825 #ifdef CONFIG_BRLAPI
2826 } else if (!strcmp(devname
, "braille")) {
2827 dev
= usb_baum_init();
2829 } else if (strstart(devname
, "net:", &p
)) {
2832 if (net_client_init("nic", p
) < 0)
2834 nd_table
[nic
].model
= "usb";
2835 dev
= usb_net_init(&nd_table
[nic
]);
2836 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2837 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2838 bt_new_hci(qemu_find_bt_vlan(0)));
2845 return usb_device_add_dev(dev
);
2848 int usb_device_del_addr(int bus_num
, int addr
)
2854 if (!used_usb_ports
)
2860 lastp
= &used_usb_ports
;
2861 port
= used_usb_ports
;
2862 while (port
&& port
->dev
->addr
!= addr
) {
2863 lastp
= &port
->next
;
2871 *lastp
= port
->next
;
2872 usb_attach(port
, NULL
);
2873 dev
->handle_destroy(dev
);
2874 port
->next
= free_usb_ports
;
2875 free_usb_ports
= port
;
2879 static int usb_device_del(const char *devname
)
2884 if (strstart(devname
, "host:", &p
))
2885 return usb_host_device_close(p
);
2887 if (!used_usb_ports
)
2890 p
= strchr(devname
, '.');
2893 bus_num
= strtoul(devname
, NULL
, 0);
2894 addr
= strtoul(p
+ 1, NULL
, 0);
2896 return usb_device_del_addr(bus_num
, addr
);
2899 void do_usb_add(Monitor
*mon
, const char *devname
)
2901 usb_device_add(devname
, 1);
2904 void do_usb_del(Monitor
*mon
, const char *devname
)
2906 usb_device_del(devname
);
2909 void usb_info(Monitor
*mon
)
2913 const char *speed_str
;
2916 monitor_printf(mon
, "USB support not enabled\n");
2920 for (port
= used_usb_ports
; port
; port
= port
->next
) {
2924 switch(dev
->speed
) {
2928 case USB_SPEED_FULL
:
2931 case USB_SPEED_HIGH
:
2938 monitor_printf(mon
, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2939 0, dev
->addr
, speed_str
, dev
->devname
);
2943 /***********************************************************/
2944 /* PCMCIA/Cardbus */
2946 static struct pcmcia_socket_entry_s
{
2947 struct pcmcia_socket_s
*socket
;
2948 struct pcmcia_socket_entry_s
*next
;
2949 } *pcmcia_sockets
= 0;
2951 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
2953 struct pcmcia_socket_entry_s
*entry
;
2955 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2956 entry
->socket
= socket
;
2957 entry
->next
= pcmcia_sockets
;
2958 pcmcia_sockets
= entry
;
2961 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
2963 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2965 ptr
= &pcmcia_sockets
;
2966 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2967 if (entry
->socket
== socket
) {
2973 void pcmcia_info(Monitor
*mon
)
2975 struct pcmcia_socket_entry_s
*iter
;
2977 if (!pcmcia_sockets
)
2978 monitor_printf(mon
, "No PCMCIA sockets\n");
2980 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2981 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2982 iter
->socket
->attached
? iter
->socket
->card_string
:
2986 /***********************************************************/
2987 /* register display */
2989 struct DisplayAllocator default_allocator
= {
2990 defaultallocator_create_displaysurface
,
2991 defaultallocator_resize_displaysurface
,
2992 defaultallocator_free_displaysurface
2995 void register_displaystate(DisplayState
*ds
)
3005 DisplayState
*get_displaystate(void)
3007 return display_state
;
3010 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
3012 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
3013 return ds
->allocator
;
3018 static void dumb_display_init(void)
3020 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
3021 ds
->allocator
= &default_allocator
;
3022 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
3023 register_displaystate(ds
);
3026 /***********************************************************/
3029 typedef struct IOHandlerRecord
{
3031 IOCanRWHandler
*fd_read_poll
;
3033 IOHandler
*fd_write
;
3036 /* temporary data */
3038 struct IOHandlerRecord
*next
;
3041 static IOHandlerRecord
*first_io_handler
;
3043 /* XXX: fd_read_poll should be suppressed, but an API change is
3044 necessary in the character devices to suppress fd_can_read(). */
3045 int qemu_set_fd_handler2(int fd
,
3046 IOCanRWHandler
*fd_read_poll
,
3048 IOHandler
*fd_write
,
3051 IOHandlerRecord
**pioh
, *ioh
;
3053 if (!fd_read
&& !fd_write
) {
3054 pioh
= &first_io_handler
;
3059 if (ioh
->fd
== fd
) {
3066 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3070 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
3071 ioh
->next
= first_io_handler
;
3072 first_io_handler
= ioh
;
3075 ioh
->fd_read_poll
= fd_read_poll
;
3076 ioh
->fd_read
= fd_read
;
3077 ioh
->fd_write
= fd_write
;
3078 ioh
->opaque
= opaque
;
3085 int qemu_set_fd_handler(int fd
,
3087 IOHandler
*fd_write
,
3090 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
3094 /***********************************************************/
3095 /* Polling handling */
3097 typedef struct PollingEntry
{
3100 struct PollingEntry
*next
;
3103 static PollingEntry
*first_polling_entry
;
3105 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
3107 PollingEntry
**ppe
, *pe
;
3108 pe
= qemu_mallocz(sizeof(PollingEntry
));
3110 pe
->opaque
= opaque
;
3111 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
3116 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
3118 PollingEntry
**ppe
, *pe
;
3119 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
3121 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
3129 /***********************************************************/
3130 /* Wait objects support */
3131 typedef struct WaitObjects
{
3133 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
3134 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
3135 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
3138 static WaitObjects wait_objects
= {0};
3140 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
3142 WaitObjects
*w
= &wait_objects
;
3144 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
3146 w
->events
[w
->num
] = handle
;
3147 w
->func
[w
->num
] = func
;
3148 w
->opaque
[w
->num
] = opaque
;
3153 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
3156 WaitObjects
*w
= &wait_objects
;
3159 for (i
= 0; i
< w
->num
; i
++) {
3160 if (w
->events
[i
] == handle
)
3163 w
->events
[i
] = w
->events
[i
+ 1];
3164 w
->func
[i
] = w
->func
[i
+ 1];
3165 w
->opaque
[i
] = w
->opaque
[i
+ 1];
3173 /***********************************************************/
3174 /* ram save/restore */
3176 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
3180 v
= qemu_get_byte(f
);
3183 if (qemu_get_buffer(f
, buf
, len
) != len
)
3187 v
= qemu_get_byte(f
);
3188 memset(buf
, v
, len
);
3194 if (qemu_file_has_error(f
))
3200 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
3205 if (qemu_get_be32(f
) != last_ram_offset
)
3207 for(i
= 0; i
< last_ram_offset
; i
+= TARGET_PAGE_SIZE
) {
3208 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3210 ret
= ram_get_page(f
, qemu_get_ram_ptr(i
), TARGET_PAGE_SIZE
);
3217 #define BDRV_HASH_BLOCK_SIZE 1024
3218 #define IOBUF_SIZE 4096
3219 #define RAM_CBLOCK_MAGIC 0xfabe
3221 typedef struct RamDecompressState
{
3224 uint8_t buf
[IOBUF_SIZE
];
3225 } RamDecompressState
;
3227 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
3230 memset(s
, 0, sizeof(*s
));
3232 ret
= inflateInit(&s
->zstream
);
3238 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
3242 s
->zstream
.avail_out
= len
;
3243 s
->zstream
.next_out
= buf
;
3244 while (s
->zstream
.avail_out
> 0) {
3245 if (s
->zstream
.avail_in
== 0) {
3246 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
3248 clen
= qemu_get_be16(s
->f
);
3249 if (clen
> IOBUF_SIZE
)
3251 qemu_get_buffer(s
->f
, s
->buf
, clen
);
3252 s
->zstream
.avail_in
= clen
;
3253 s
->zstream
.next_in
= s
->buf
;
3255 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
3256 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
3263 static void ram_decompress_close(RamDecompressState
*s
)
3265 inflateEnd(&s
->zstream
);
3268 #define RAM_SAVE_FLAG_FULL 0x01
3269 #define RAM_SAVE_FLAG_COMPRESS 0x02
3270 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3271 #define RAM_SAVE_FLAG_PAGE 0x08
3272 #define RAM_SAVE_FLAG_EOS 0x10
3274 static int is_dup_page(uint8_t *page
, uint8_t ch
)
3276 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
3277 uint32_t *array
= (uint32_t *)page
;
3280 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
3281 if (array
[i
] != val
)
3288 static int ram_save_block(QEMUFile
*f
)
3290 static ram_addr_t current_addr
= 0;
3291 ram_addr_t saved_addr
= current_addr
;
3292 ram_addr_t addr
= 0;
3295 while (addr
< last_ram_offset
) {
3296 if (kvm_enabled() && current_addr
== 0) {
3298 r
= kvm_update_dirty_pages_log();
3300 fprintf(stderr
, "%s: update dirty pages log failed %d\n", __FUNCTION__
, r
);
3301 qemu_file_set_error(f
);
3305 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
3308 cpu_physical_memory_reset_dirty(current_addr
,
3309 current_addr
+ TARGET_PAGE_SIZE
,
3310 MIGRATION_DIRTY_FLAG
);
3312 p
= qemu_get_ram_ptr(current_addr
);
3314 if (is_dup_page(p
, *p
)) {
3315 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
3316 qemu_put_byte(f
, *p
);
3318 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
3319 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
3325 addr
+= TARGET_PAGE_SIZE
;
3326 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
3332 static ram_addr_t ram_save_threshold
= 10;
3334 static ram_addr_t
ram_save_remaining(void)
3337 ram_addr_t count
= 0;
3339 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3340 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3347 static int ram_save_live(QEMUFile
*f
, int stage
, void *opaque
)
3352 /* Make sure all dirty bits are set */
3353 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3354 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3355 cpu_physical_memory_set_dirty(addr
);
3358 /* Enable dirty memory tracking */
3359 cpu_physical_memory_set_dirty_tracking(1);
3361 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
3364 while (!qemu_file_rate_limit(f
)) {
3367 ret
= ram_save_block(f
);
3368 if (ret
== 0) /* no more blocks */
3372 /* try transferring iterative blocks of memory */
3376 /* flush all remaining blocks regardless of rate limiting */
3377 while (ram_save_block(f
) != 0);
3378 cpu_physical_memory_set_dirty_tracking(0);
3381 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3383 return (stage
== 2) && (ram_save_remaining() < ram_save_threshold
);
3386 static int ram_load_dead(QEMUFile
*f
, void *opaque
)
3388 RamDecompressState s1
, *s
= &s1
;
3392 if (ram_decompress_open(s
, f
) < 0)
3394 for(i
= 0; i
< last_ram_offset
; i
+= BDRV_HASH_BLOCK_SIZE
) {
3395 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3397 if (ram_decompress_buf(s
, buf
, 1) < 0) {
3398 fprintf(stderr
, "Error while reading ram block header\n");
3402 if (ram_decompress_buf(s
, qemu_get_ram_ptr(i
),
3403 BDRV_HASH_BLOCK_SIZE
) < 0) {
3404 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
3409 printf("Error block header\n");
3413 ram_decompress_close(s
);
3418 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
3423 if (version_id
== 1)
3424 return ram_load_v1(f
, opaque
);
3426 if (version_id
== 2) {
3427 if (qemu_get_be32(f
) != last_ram_offset
)
3429 return ram_load_dead(f
, opaque
);
3432 if (version_id
!= 3)
3436 addr
= qemu_get_be64(f
);
3438 flags
= addr
& ~TARGET_PAGE_MASK
;
3439 addr
&= TARGET_PAGE_MASK
;
3441 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
3442 if (addr
!= last_ram_offset
)
3446 if (flags
& RAM_SAVE_FLAG_FULL
) {
3447 if (ram_load_dead(f
, opaque
) < 0)
3451 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
3452 uint8_t ch
= qemu_get_byte(f
);
3453 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
3454 } else if (flags
& RAM_SAVE_FLAG_PAGE
)
3455 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
3456 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
3461 void qemu_service_io(void)
3463 CPUState
*env
= cpu_single_env
;
3467 if (env
->kqemu_enabled
) {
3468 kqemu_cpu_interrupt(env
);
3474 /***********************************************************/
3475 /* bottom halves (can be seen as timers which expire ASAP) */
3486 static QEMUBH
*first_bh
= NULL
;
3488 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
3491 bh
= qemu_mallocz(sizeof(QEMUBH
));
3493 bh
->opaque
= opaque
;
3494 bh
->next
= first_bh
;
3499 int qemu_bh_poll(void)
3505 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3506 if (!bh
->deleted
&& bh
->scheduled
) {
3515 /* remove deleted bhs */
3529 void qemu_bh_schedule_idle(QEMUBH
*bh
)
3537 void qemu_bh_schedule(QEMUBH
*bh
)
3539 CPUState
*env
= cpu_single_env
;
3544 /* stop the currently executing CPU to execute the BH ASAP */
3551 void qemu_bh_cancel(QEMUBH
*bh
)
3556 void qemu_bh_delete(QEMUBH
*bh
)
3562 static void qemu_bh_update_timeout(int *timeout
)
3566 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3567 if (!bh
->deleted
&& bh
->scheduled
) {
3569 /* idle bottom halves will be polled at least
3571 *timeout
= MIN(10, *timeout
);
3573 /* non-idle bottom halves will be executed
3582 /***********************************************************/
3583 /* machine registration */
3585 static QEMUMachine
*first_machine
= NULL
;
3586 QEMUMachine
*current_machine
= NULL
;
3588 int qemu_register_machine(QEMUMachine
*m
)
3591 pm
= &first_machine
;
3599 static QEMUMachine
*find_machine(const char *name
)
3603 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3604 if (!strcmp(m
->name
, name
))
3610 /***********************************************************/
3611 /* main execution loop */
3613 static void gui_update(void *opaque
)
3615 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3616 DisplayState
*ds
= opaque
;
3617 DisplayChangeListener
*dcl
= ds
->listeners
;
3621 while (dcl
!= NULL
) {
3622 if (dcl
->gui_timer_interval
&&
3623 dcl
->gui_timer_interval
< interval
)
3624 interval
= dcl
->gui_timer_interval
;
3627 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3630 static void nographic_update(void *opaque
)
3632 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3634 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3637 struct vm_change_state_entry
{
3638 VMChangeStateHandler
*cb
;
3640 LIST_ENTRY (vm_change_state_entry
) entries
;
3643 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3645 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3648 VMChangeStateEntry
*e
;
3650 e
= qemu_mallocz(sizeof (*e
));
3654 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3658 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3660 LIST_REMOVE (e
, entries
);
3664 static void vm_state_notify(int running
, int reason
)
3666 VMChangeStateEntry
*e
;
3668 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3669 e
->cb(e
->opaque
, running
, reason
);
3678 vm_state_notify(1, 0);
3680 qemu_kvm_resume_all_threads();
3681 qemu_rearm_alarm_timer(alarm_timer
);
3685 void vm_stop(int reason
)
3688 cpu_disable_ticks();
3691 qemu_kvm_pause_all_threads();
3692 vm_state_notify(0, reason
);
3696 /* reset/shutdown handler */
3698 typedef struct QEMUResetEntry
{
3699 QEMUResetHandler
*func
;
3701 struct QEMUResetEntry
*next
;
3704 static QEMUResetEntry
*first_reset_entry
;
3705 static int reset_requested
;
3706 static int shutdown_requested
;
3707 static int powerdown_requested
;
3709 int qemu_shutdown_requested(void)
3711 int r
= shutdown_requested
;
3712 shutdown_requested
= 0;
3716 int qemu_reset_requested(void)
3718 int r
= reset_requested
;
3719 reset_requested
= 0;
3723 int qemu_powerdown_requested(void)
3725 int r
= powerdown_requested
;
3726 powerdown_requested
= 0;
3730 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3732 QEMUResetEntry
**pre
, *re
;
3734 pre
= &first_reset_entry
;
3735 while (*pre
!= NULL
)
3736 pre
= &(*pre
)->next
;
3737 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3739 re
->opaque
= opaque
;
3744 void qemu_system_reset(void)
3748 /* reset all devices */
3749 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
3750 re
->func(re
->opaque
);
3756 void qemu_system_reset_request(void)
3759 shutdown_requested
= 1;
3761 reset_requested
= 1;
3763 if (cpu_single_env
) {
3764 qemu_kvm_cpu_stop(cpu_single_env
);
3765 cpu_exit(cpu_single_env
);
3769 void qemu_system_shutdown_request(void)
3771 shutdown_requested
= 1;
3773 cpu_exit(cpu_single_env
);
3776 void qemu_system_powerdown_request(void)
3778 powerdown_requested
= 1;
3780 cpu_exit(cpu_single_env
);
3783 static int qemu_select(int max_fd
, fd_set
*rfds
, fd_set
*wfds
, fd_set
*xfds
,
3788 /* KVM holds a mutex while QEMU code is running, we need hooks to
3789 release the mutex whenever QEMU code sleeps. */
3793 ret
= select(max_fd
, rfds
, wfds
, xfds
, tv
);
3801 static void host_main_loop_wait(int *timeout
)
3807 /* XXX: need to suppress polling by better using win32 events */
3809 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
3810 ret
|= pe
->func(pe
->opaque
);
3814 WaitObjects
*w
= &wait_objects
;
3816 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
3817 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
3818 if (w
->func
[ret
- WAIT_OBJECT_0
])
3819 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
3821 /* Check for additional signaled events */
3822 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
3824 /* Check if event is signaled */
3825 ret2
= WaitForSingleObject(w
->events
[i
], 0);
3826 if(ret2
== WAIT_OBJECT_0
) {
3828 w
->func
[i
](w
->opaque
[i
]);
3829 } else if (ret2
== WAIT_TIMEOUT
) {
3831 err
= GetLastError();
3832 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
3835 } else if (ret
== WAIT_TIMEOUT
) {
3837 err
= GetLastError();
3838 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
3845 static void host_main_loop_wait(int *timeout
)
3850 void main_loop_wait(int timeout
)
3852 IOHandlerRecord
*ioh
;
3853 fd_set rfds
, wfds
, xfds
;
3857 qemu_bh_update_timeout(&timeout
);
3859 host_main_loop_wait(&timeout
);
3861 /* poll any events */
3862 /* XXX: separate device handlers from system ones */
3867 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3871 (!ioh
->fd_read_poll
||
3872 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
3873 FD_SET(ioh
->fd
, &rfds
);
3877 if (ioh
->fd_write
) {
3878 FD_SET(ioh
->fd
, &wfds
);
3884 tv
.tv_sec
= timeout
/ 1000;
3885 tv
.tv_usec
= (timeout
% 1000) * 1000;
3887 #if defined(CONFIG_SLIRP)
3888 if (slirp_is_inited()) {
3889 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
3892 ret
= qemu_select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
3894 IOHandlerRecord
**pioh
;
3896 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3897 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
3898 ioh
->fd_read(ioh
->opaque
);
3899 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
3900 FD_CLR(ioh
->fd
, &rfds
);
3902 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
3903 ioh
->fd_write(ioh
->opaque
);
3907 /* remove deleted IO handlers */
3908 pioh
= &first_io_handler
;
3918 #if defined(CONFIG_SLIRP)
3919 if (slirp_is_inited()) {
3925 slirp_select_poll(&rfds
, &wfds
, &xfds
);
3929 /* vm time timers */
3930 if (vm_running
&& (!cur_cpu
3931 || likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
))))
3932 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
3933 qemu_get_clock(vm_clock
));
3935 /* real time timers */
3936 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
3937 qemu_get_clock(rt_clock
));
3939 /* Check bottom-halves last in case any of the earlier events triggered
3945 static int main_loop(void)
3948 #ifdef CONFIG_PROFILER
3954 if (kvm_enabled()) {
3956 cpu_disable_ticks();
3960 cur_cpu
= first_cpu
;
3961 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
3968 #ifdef CONFIG_PROFILER
3969 ti
= profile_getclock();
3974 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
3975 env
->icount_decr
.u16
.low
= 0;
3976 env
->icount_extra
= 0;
3977 count
= qemu_next_deadline();
3978 count
= (count
+ (1 << icount_time_shift
) - 1)
3979 >> icount_time_shift
;
3980 qemu_icount
+= count
;
3981 decr
= (count
> 0xffff) ? 0xffff : count
;
3983 env
->icount_decr
.u16
.low
= decr
;
3984 env
->icount_extra
= count
;
3986 ret
= cpu_exec(env
);
3987 #ifdef CONFIG_PROFILER
3988 qemu_time
+= profile_getclock() - ti
;
3991 /* Fold pending instructions back into the
3992 instruction counter, and clear the interrupt flag. */
3993 qemu_icount
-= (env
->icount_decr
.u16
.low
3994 + env
->icount_extra
);
3995 env
->icount_decr
.u32
= 0;
3996 env
->icount_extra
= 0;
3998 next_cpu
= env
->next_cpu
?: first_cpu
;
3999 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
4000 ret
= EXCP_INTERRUPT
;
4004 if (ret
== EXCP_HLT
) {
4005 /* Give the next CPU a chance to run. */
4009 if (ret
!= EXCP_HALTED
)
4011 /* all CPUs are halted ? */
4017 if (shutdown_requested
) {
4018 ret
= EXCP_INTERRUPT
;
4026 if (reset_requested
) {
4027 reset_requested
= 0;
4028 qemu_system_reset();
4029 ret
= EXCP_INTERRUPT
;
4031 if (powerdown_requested
) {
4032 powerdown_requested
= 0;
4033 qemu_system_powerdown();
4034 ret
= EXCP_INTERRUPT
;
4036 #ifdef CONFIG_GDBSTUB
4037 if (unlikely(ret
== EXCP_DEBUG
)) {
4038 gdb_set_stop_cpu(cur_cpu
);
4039 vm_stop(EXCP_DEBUG
);
4042 /* If all cpus are halted then wait until the next IRQ */
4043 /* XXX: use timeout computed from timers */
4044 if (ret
== EXCP_HALTED
) {
4048 /* Advance virtual time to the next event. */
4049 if (use_icount
== 1) {
4050 /* When not using an adaptive execution frequency
4051 we tend to get badly out of sync with real time,
4052 so just delay for a reasonable amount of time. */
4055 delta
= cpu_get_icount() - cpu_get_clock();
4058 /* If virtual time is ahead of real time then just
4060 timeout
= (delta
/ 1000000) + 1;
4062 /* Wait for either IO to occur or the next
4064 add
= qemu_next_deadline();
4065 /* We advance the timer before checking for IO.
4066 Limit the amount we advance so that early IO
4067 activity won't get the guest too far ahead. */
4071 add
= (add
+ (1 << icount_time_shift
) - 1)
4072 >> icount_time_shift
;
4074 timeout
= delta
/ 1000000;
4085 if (shutdown_requested
) {
4086 ret
= EXCP_INTERRUPT
;
4091 #ifdef CONFIG_PROFILER
4092 ti
= profile_getclock();
4094 main_loop_wait(timeout
);
4095 #ifdef CONFIG_PROFILER
4096 dev_time
+= profile_getclock() - ti
;
4099 cpu_disable_ticks();
4103 static void version(void)
4105 printf("QEMU PC emulator version " QEMU_VERSION
" (" KVM_VERSION
")" QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4108 static void help(int exitcode
)
4111 printf("usage: %s [options] [disk_image]\n"
4113 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4115 #define DEF(option, opt_arg, opt_enum, opt_help) \
4117 #define DEFHEADING(text) stringify(text) "\n"
4118 #include "qemu-options.h"
4123 "During emulation, the following keys are useful:\n"
4124 "ctrl-alt-f toggle full screen\n"
4125 "ctrl-alt-n switch to virtual console 'n'\n"
4126 "ctrl-alt toggle mouse and keyboard grab\n"
4128 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4133 DEFAULT_NETWORK_SCRIPT
,
4134 DEFAULT_NETWORK_DOWN_SCRIPT
,
4136 DEFAULT_GDBSTUB_PORT
,
4141 #define HAS_ARG 0x0001
4144 #define DEF(option, opt_arg, opt_enum, opt_help) \
4146 #define DEFHEADING(text)
4147 #include "qemu-options.h"
4153 typedef struct QEMUOption
{
4159 static const QEMUOption qemu_options
[] = {
4160 { "h", 0, QEMU_OPTION_h
},
4161 #define DEF(option, opt_arg, opt_enum, opt_help) \
4162 { option, opt_arg, opt_enum },
4163 #define DEFHEADING(text)
4164 #include "qemu-options.h"
4172 struct soundhw soundhw
[] = {
4173 #ifdef HAS_AUDIO_CHOICE
4174 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4180 { .init_isa
= pcspk_audio_init
}
4187 "Creative Sound Blaster 16",
4190 { .init_isa
= SB16_init
}
4194 #ifdef CONFIG_CS4231A
4200 { .init_isa
= cs4231a_init
}
4208 "Yamaha YMF262 (OPL3)",
4210 "Yamaha YM3812 (OPL2)",
4214 { .init_isa
= Adlib_init
}
4221 "Gravis Ultrasound GF1",
4224 { .init_isa
= GUS_init
}
4231 "Intel 82801AA AC97 Audio",
4234 { .init_pci
= ac97_init
}
4238 #ifdef CONFIG_ES1370
4241 "ENSONIQ AudioPCI ES1370",
4244 { .init_pci
= es1370_init
}
4248 #endif /* HAS_AUDIO_CHOICE */
4250 { NULL
, NULL
, 0, 0, { NULL
} }
4253 static void select_soundhw (const char *optarg
)
4257 if (*optarg
== '?') {
4260 printf ("Valid sound card names (comma separated):\n");
4261 for (c
= soundhw
; c
->name
; ++c
) {
4262 printf ("%-11s %s\n", c
->name
, c
->descr
);
4264 printf ("\n-soundhw all will enable all of the above\n");
4265 exit (*optarg
!= '?');
4273 if (!strcmp (optarg
, "all")) {
4274 for (c
= soundhw
; c
->name
; ++c
) {
4282 e
= strchr (p
, ',');
4283 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4285 for (c
= soundhw
; c
->name
; ++c
) {
4286 if (!strncmp (c
->name
, p
, l
)) {
4295 "Unknown sound card name (too big to show)\n");
4298 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4303 p
+= l
+ (e
!= NULL
);
4307 goto show_valid_cards
;
4312 static void select_vgahw (const char *p
)
4316 cirrus_vga_enabled
= 0;
4317 std_vga_enabled
= 0;
4320 if (strstart(p
, "std", &opts
)) {
4321 std_vga_enabled
= 1;
4322 } else if (strstart(p
, "cirrus", &opts
)) {
4323 cirrus_vga_enabled
= 1;
4324 } else if (strstart(p
, "vmware", &opts
)) {
4326 } else if (strstart(p
, "xenfb", &opts
)) {
4328 } else if (!strstart(p
, "none", &opts
)) {
4330 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4334 const char *nextopt
;
4336 if (strstart(opts
, ",retrace=", &nextopt
)) {
4338 if (strstart(opts
, "dumb", &nextopt
))
4339 vga_retrace_method
= VGA_RETRACE_DUMB
;
4340 else if (strstart(opts
, "precise", &nextopt
))
4341 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4342 else goto invalid_vga
;
4343 } else goto invalid_vga
;
4349 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4351 exit(STATUS_CONTROL_C_EXIT
);
4356 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4360 if(strlen(str
) != 36)
4363 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4364 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4365 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4371 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4377 #define MAX_NET_CLIENTS 32
4379 static int saved_argc
;
4380 static char **saved_argv
;
4381 static const char *saved_incoming
;
4383 void qemu_get_launch_info(int *argc
, char ***argv
, int *opt_daemonize
, const char **opt_incoming
)
4387 *opt_daemonize
= daemonize
;
4388 *opt_incoming
= saved_incoming
;
4393 #define HUGETLBFS_MAGIC 0x958458f6
4395 static long gethugepagesize(const char *path
)
4401 ret
= statfs(path
, &fs
);
4402 } while (ret
!= 0 && errno
== EINTR
);
4409 if (fs
.f_type
!= HUGETLBFS_MAGIC
)
4410 fprintf(stderr
, "Warning: path not on HugeTLBFS: %s\n", path
);
4415 static void *alloc_mem_area(size_t memory
, unsigned long *len
, const char *path
)
4424 if (!kvm_has_sync_mmu()) {
4425 fprintf(stderr
, "host lacks mmu notifiers, disabling --mem-path\n");
4429 if (asprintf(&filename
, "%s/kvm.XXXXXX", path
) == -1)
4432 hpagesize
= gethugepagesize(path
);
4436 fd
= mkstemp(filename
);
4445 memory
= (memory
+hpagesize
-1) & ~(hpagesize
-1);
4448 * ftruncate is not supported by hugetlbfs in older
4449 * hosts, so don't bother checking for errors.
4450 * If anything goes wrong with it under other filesystems,
4453 ftruncate(fd
, memory
);
4456 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4457 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4458 * to sidestep this quirk.
4460 flags
= mem_prealloc
? MAP_POPULATE
|MAP_SHARED
: MAP_PRIVATE
;
4461 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, flags
, fd
, 0);
4463 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
, fd
, 0);
4465 if (area
== MAP_FAILED
) {
4466 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4475 static void *qemu_alloc_physram(unsigned long memory
)
4479 unsigned long map_len
= memory
;
4482 area
= alloc_mem_area(memory
, &map_len
, mem_path
);
4485 area
= qemu_vmalloc(memory
);
4487 if (kvm_setup_guest_memory(area
, map_len
))
4495 static void termsig_handler(int signal
)
4497 qemu_system_shutdown_request();
4500 static void termsig_setup(void)
4502 struct sigaction act
;
4504 memset(&act
, 0, sizeof(act
));
4505 act
.sa_handler
= termsig_handler
;
4506 sigaction(SIGINT
, &act
, NULL
);
4507 sigaction(SIGHUP
, &act
, NULL
);
4508 sigaction(SIGTERM
, &act
, NULL
);
4513 int main(int argc
, char **argv
, char **envp
)
4515 #ifdef CONFIG_GDBSTUB
4516 const char *gdbstub_dev
= NULL
;
4518 uint32_t boot_devices_bitmap
= 0;
4520 int snapshot
, linux_boot
, net_boot
;
4521 const char *initrd_filename
;
4522 const char *kernel_filename
, *kernel_cmdline
;
4523 const char *boot_devices
= "";
4525 DisplayChangeListener
*dcl
;
4526 int cyls
, heads
, secs
, translation
;
4527 const char *net_clients
[MAX_NET_CLIENTS
];
4529 const char *bt_opts
[MAX_BT_CMDLINE
];
4533 const char *r
, *optarg
;
4534 CharDriverState
*monitor_hd
= NULL
;
4535 const char *monitor_device
;
4536 const char *serial_devices
[MAX_SERIAL_PORTS
];
4537 int serial_device_index
;
4538 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
4539 int parallel_device_index
;
4540 const char *virtio_consoles
[MAX_VIRTIO_CONSOLES
];
4541 int virtio_console_index
;
4542 const char *loadvm
= NULL
;
4543 QEMUMachine
*machine
;
4544 const char *cpu_model
;
4545 const char *usb_devices
[MAX_USB_CMDLINE
];
4546 int usb_devices_index
;
4551 const char *pid_file
= NULL
;
4552 const char *incoming
= NULL
;
4555 struct passwd
*pwd
= NULL
;
4556 const char *chroot_dir
= NULL
;
4557 const char *run_as
= NULL
;
4561 qemu_cache_utils_init(envp
);
4563 LIST_INIT (&vm_change_state_head
);
4566 struct sigaction act
;
4567 sigfillset(&act
.sa_mask
);
4569 act
.sa_handler
= SIG_IGN
;
4570 sigaction(SIGPIPE
, &act
, NULL
);
4573 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4574 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4575 QEMU to run on a single CPU */
4580 h
= GetCurrentProcess();
4581 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4582 for(i
= 0; i
< 32; i
++) {
4583 if (mask
& (1 << i
))
4588 SetProcessAffinityMask(h
, mask
);
4594 register_machines();
4595 machine
= first_machine
;
4597 initrd_filename
= NULL
;
4599 vga_ram_size
= VGA_RAM_SIZE
;
4603 kernel_filename
= NULL
;
4604 kernel_cmdline
= "";
4605 cyls
= heads
= secs
= 0;
4606 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4607 monitor_device
= "vc:80Cx24C";
4609 serial_devices
[0] = "vc:80Cx24C";
4610 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
4611 serial_devices
[i
] = NULL
;
4612 serial_device_index
= 0;
4614 parallel_devices
[0] = "vc:80Cx24C";
4615 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
4616 parallel_devices
[i
] = NULL
;
4617 parallel_device_index
= 0;
4619 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++)
4620 virtio_consoles
[i
] = NULL
;
4621 virtio_console_index
= 0;
4623 for (i
= 0; i
< MAX_NODES
; i
++) {
4625 node_cpumask
[i
] = 0;
4628 usb_devices_index
= 0;
4629 assigned_devices_index
= 0;
4649 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
4651 const QEMUOption
*popt
;
4654 /* Treat --foo the same as -foo. */
4657 popt
= qemu_options
;
4660 fprintf(stderr
, "%s: invalid option -- '%s'\n",
4664 if (!strcmp(popt
->name
, r
+ 1))
4668 if (popt
->flags
& HAS_ARG
) {
4669 if (optind
>= argc
) {
4670 fprintf(stderr
, "%s: option '%s' requires an argument\n",
4674 optarg
= argv
[optind
++];
4679 switch(popt
->index
) {
4681 machine
= find_machine(optarg
);
4684 printf("Supported machines are:\n");
4685 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
4686 printf("%-10s %s%s\n",
4688 m
== first_machine
? " (default)" : "");
4690 exit(*optarg
!= '?');
4693 case QEMU_OPTION_cpu
:
4694 /* hw initialization will check this */
4695 if (*optarg
== '?') {
4696 /* XXX: implement xxx_cpu_list for targets that still miss it */
4697 #if defined(cpu_list)
4698 cpu_list(stdout
, &fprintf
);
4705 case QEMU_OPTION_initrd
:
4706 initrd_filename
= optarg
;
4708 case QEMU_OPTION_hda
:
4710 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
4712 hda_index
= drive_add(optarg
, HD_ALIAS
4713 ",cyls=%d,heads=%d,secs=%d%s",
4714 0, cyls
, heads
, secs
,
4715 translation
== BIOS_ATA_TRANSLATION_LBA
?
4717 translation
== BIOS_ATA_TRANSLATION_NONE
?
4718 ",trans=none" : "");
4720 case QEMU_OPTION_hdb
:
4721 case QEMU_OPTION_hdc
:
4722 case QEMU_OPTION_hdd
:
4723 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
4725 case QEMU_OPTION_drive
:
4726 drive_add(NULL
, "%s", optarg
);
4728 case QEMU_OPTION_mtdblock
:
4729 drive_add(optarg
, MTD_ALIAS
);
4731 case QEMU_OPTION_sd
:
4732 drive_add(optarg
, SD_ALIAS
);
4734 case QEMU_OPTION_pflash
:
4735 drive_add(optarg
, PFLASH_ALIAS
);
4737 case QEMU_OPTION_snapshot
:
4740 case QEMU_OPTION_hdachs
:
4744 cyls
= strtol(p
, (char **)&p
, 0);
4745 if (cyls
< 1 || cyls
> 16383)
4750 heads
= strtol(p
, (char **)&p
, 0);
4751 if (heads
< 1 || heads
> 16)
4756 secs
= strtol(p
, (char **)&p
, 0);
4757 if (secs
< 1 || secs
> 63)
4761 if (!strcmp(p
, "none"))
4762 translation
= BIOS_ATA_TRANSLATION_NONE
;
4763 else if (!strcmp(p
, "lba"))
4764 translation
= BIOS_ATA_TRANSLATION_LBA
;
4765 else if (!strcmp(p
, "auto"))
4766 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4769 } else if (*p
!= '\0') {
4771 fprintf(stderr
, "qemu: invalid physical CHS format\n");
4774 if (hda_index
!= -1)
4775 snprintf(drives_opt
[hda_index
].opt
,
4776 sizeof(drives_opt
[hda_index
].opt
),
4777 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
4778 0, cyls
, heads
, secs
,
4779 translation
== BIOS_ATA_TRANSLATION_LBA
?
4781 translation
== BIOS_ATA_TRANSLATION_NONE
?
4782 ",trans=none" : "");
4785 case QEMU_OPTION_numa
:
4786 if (nb_numa_nodes
>= MAX_NODES
) {
4787 fprintf(stderr
, "qemu: too many NUMA nodes\n");
4792 case QEMU_OPTION_nographic
:
4795 #ifdef CONFIG_CURSES
4796 case QEMU_OPTION_curses
:
4800 case QEMU_OPTION_portrait
:
4803 case QEMU_OPTION_kernel
:
4804 kernel_filename
= optarg
;
4806 case QEMU_OPTION_append
:
4807 kernel_cmdline
= optarg
;
4809 case QEMU_OPTION_cdrom
:
4810 drive_add(optarg
, CDROM_ALIAS
);
4812 case QEMU_OPTION_boot
:
4813 boot_devices
= optarg
;
4814 /* We just do some generic consistency checks */
4816 /* Could easily be extended to 64 devices if needed */
4819 boot_devices_bitmap
= 0;
4820 for (p
= boot_devices
; *p
!= '\0'; p
++) {
4821 /* Allowed boot devices are:
4822 * a b : floppy disk drives
4823 * c ... f : IDE disk drives
4824 * g ... m : machine implementation dependant drives
4825 * n ... p : network devices
4826 * It's up to each machine implementation to check
4827 * if the given boot devices match the actual hardware
4828 * implementation and firmware features.
4830 if (*p
< 'a' || *p
> 'q') {
4831 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
4834 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
4836 "Boot device '%c' was given twice\n",*p
);
4839 boot_devices_bitmap
|= 1 << (*p
- 'a');
4843 case QEMU_OPTION_fda
:
4844 case QEMU_OPTION_fdb
:
4845 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
4848 case QEMU_OPTION_no_fd_bootchk
:
4852 case QEMU_OPTION_net
:
4853 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
4854 fprintf(stderr
, "qemu: too many network clients\n");
4857 net_clients
[nb_net_clients
] = optarg
;
4861 case QEMU_OPTION_tftp
:
4862 tftp_prefix
= optarg
;
4864 case QEMU_OPTION_bootp
:
4865 bootp_filename
= optarg
;
4868 case QEMU_OPTION_smb
:
4869 net_slirp_smb(optarg
);
4872 case QEMU_OPTION_redir
:
4873 net_slirp_redir(NULL
, optarg
);
4876 case QEMU_OPTION_bt
:
4877 if (nb_bt_opts
>= MAX_BT_CMDLINE
) {
4878 fprintf(stderr
, "qemu: too many bluetooth options\n");
4881 bt_opts
[nb_bt_opts
++] = optarg
;
4884 case QEMU_OPTION_audio_help
:
4888 case QEMU_OPTION_soundhw
:
4889 select_soundhw (optarg
);
4895 case QEMU_OPTION_version
:
4899 case QEMU_OPTION_m
: {
4903 value
= strtoul(optarg
, &ptr
, 10);
4905 case 0: case 'M': case 'm':
4912 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
4916 /* On 32-bit hosts, QEMU is limited by virtual address space */
4917 if (value
> (2047 << 20)
4918 #ifndef CONFIG_KQEMU
4919 && HOST_LONG_BITS
== 32
4922 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
4925 if (value
!= (uint64_t)(ram_addr_t
)value
) {
4926 fprintf(stderr
, "qemu: ram size too large\n");
4935 const CPULogItem
*item
;
4937 mask
= cpu_str_to_log_mask(optarg
);
4939 printf("Log items (comma separated):\n");
4940 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
4941 printf("%-10s %s\n", item
->name
, item
->help
);
4948 #ifdef CONFIG_GDBSTUB
4950 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
4952 case QEMU_OPTION_gdb
:
4953 gdbstub_dev
= optarg
;
4959 case QEMU_OPTION_bios
:
4962 case QEMU_OPTION_singlestep
:
4970 keyboard_layout
= optarg
;
4973 case QEMU_OPTION_localtime
:
4976 case QEMU_OPTION_vga
:
4977 select_vgahw (optarg
);
4979 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4985 w
= strtol(p
, (char **)&p
, 10);
4988 fprintf(stderr
, "qemu: invalid resolution or depth\n");
4994 h
= strtol(p
, (char **)&p
, 10);
4999 depth
= strtol(p
, (char **)&p
, 10);
5000 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5001 depth
!= 24 && depth
!= 32)
5003 } else if (*p
== '\0') {
5004 depth
= graphic_depth
;
5011 graphic_depth
= depth
;
5015 case QEMU_OPTION_echr
:
5018 term_escape_char
= strtol(optarg
, &r
, 0);
5020 printf("Bad argument to echr\n");
5023 case QEMU_OPTION_monitor
:
5024 monitor_device
= optarg
;
5026 case QEMU_OPTION_serial
:
5027 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
5028 fprintf(stderr
, "qemu: too many serial ports\n");
5031 serial_devices
[serial_device_index
] = optarg
;
5032 serial_device_index
++;
5034 case QEMU_OPTION_virtiocon
:
5035 if (virtio_console_index
>= MAX_VIRTIO_CONSOLES
) {
5036 fprintf(stderr
, "qemu: too many virtio consoles\n");
5039 virtio_consoles
[virtio_console_index
] = optarg
;
5040 virtio_console_index
++;
5042 case QEMU_OPTION_parallel
:
5043 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
5044 fprintf(stderr
, "qemu: too many parallel ports\n");
5047 parallel_devices
[parallel_device_index
] = optarg
;
5048 parallel_device_index
++;
5050 case QEMU_OPTION_loadvm
:
5053 case QEMU_OPTION_full_screen
:
5057 case QEMU_OPTION_no_frame
:
5060 case QEMU_OPTION_alt_grab
:
5063 case QEMU_OPTION_no_quit
:
5066 case QEMU_OPTION_sdl
:
5070 case QEMU_OPTION_pidfile
:
5074 case QEMU_OPTION_win2k_hack
:
5075 win2k_install_hack
= 1;
5077 case QEMU_OPTION_rtc_td_hack
:
5080 case QEMU_OPTION_acpitable
:
5081 if(acpi_table_add(optarg
) < 0) {
5082 fprintf(stderr
, "Wrong acpi table provided\n");
5086 case QEMU_OPTION_smbios
:
5087 if(smbios_entry_add(optarg
) < 0) {
5088 fprintf(stderr
, "Wrong smbios provided\n");
5094 case QEMU_OPTION_no_kqemu
:
5097 case QEMU_OPTION_kernel_kqemu
:
5102 case QEMU_OPTION_enable_kvm
:
5110 case QEMU_OPTION_no_kvm
:
5113 case QEMU_OPTION_no_kvm_irqchip
: {
5118 case QEMU_OPTION_no_kvm_pit
: {
5122 case QEMU_OPTION_no_kvm_pit_reinjection
: {
5123 kvm_pit_reinject
= 0;
5126 case QEMU_OPTION_enable_nesting
: {
5130 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5131 case QEMU_OPTION_pcidevice
:
5132 if (assigned_devices_index
>= MAX_DEV_ASSIGN_CMDLINE
) {
5133 fprintf(stderr
, "Too many assigned devices\n");
5136 assigned_devices
[assigned_devices_index
] = optarg
;
5137 assigned_devices_index
++;
5141 case QEMU_OPTION_usb
:
5144 case QEMU_OPTION_usbdevice
:
5146 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
5147 fprintf(stderr
, "Too many USB devices\n");
5150 usb_devices
[usb_devices_index
] = optarg
;
5151 usb_devices_index
++;
5153 case QEMU_OPTION_smp
:
5154 smp_cpus
= atoi(optarg
);
5156 fprintf(stderr
, "Invalid number of CPUs\n");
5160 case QEMU_OPTION_vnc
:
5161 vnc_display
= optarg
;
5164 case QEMU_OPTION_no_acpi
:
5167 case QEMU_OPTION_no_hpet
:
5171 case QEMU_OPTION_no_reboot
:
5174 case QEMU_OPTION_no_shutdown
:
5177 case QEMU_OPTION_show_cursor
:
5180 case QEMU_OPTION_uuid
:
5181 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5182 fprintf(stderr
, "Fail to parse UUID string."
5183 " Wrong format.\n");
5188 case QEMU_OPTION_daemonize
:
5192 case QEMU_OPTION_option_rom
:
5193 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5194 fprintf(stderr
, "Too many option ROMs\n");
5197 option_rom
[nb_option_roms
] = optarg
;
5200 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5201 case QEMU_OPTION_semihosting
:
5202 semihosting_enabled
= 1;
5205 case QEMU_OPTION_tdf
:
5208 case QEMU_OPTION_kvm_shadow_memory
:
5209 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
5211 case QEMU_OPTION_mempath
:
5215 case QEMU_OPTION_mem_prealloc
:
5216 mem_prealloc
= !mem_prealloc
;
5219 case QEMU_OPTION_name
:
5222 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5223 case QEMU_OPTION_prom_env
:
5224 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5225 fprintf(stderr
, "Too many prom variables\n");
5228 prom_envs
[nb_prom_envs
] = optarg
;
5232 case QEMU_OPTION_cpu_vendor
:
5233 cpu_vendor_string
= optarg
;
5236 case QEMU_OPTION_old_param
:
5240 case QEMU_OPTION_clock
:
5241 configure_alarms(optarg
);
5243 case QEMU_OPTION_startdate
:
5246 time_t rtc_start_date
;
5247 if (!strcmp(optarg
, "now")) {
5248 rtc_date_offset
= -1;
5250 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
5258 } else if (sscanf(optarg
, "%d-%d-%d",
5261 &tm
.tm_mday
) == 3) {
5270 rtc_start_date
= mktimegm(&tm
);
5271 if (rtc_start_date
== -1) {
5273 fprintf(stderr
, "Invalid date format. Valid format are:\n"
5274 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5277 rtc_date_offset
= time(NULL
) - rtc_start_date
;
5281 case QEMU_OPTION_tb_size
:
5282 tb_size
= strtol(optarg
, NULL
, 0);
5286 case QEMU_OPTION_icount
:
5288 if (strcmp(optarg
, "auto") == 0) {
5289 icount_time_shift
= -1;
5291 icount_time_shift
= strtol(optarg
, NULL
, 0);
5294 case QEMU_OPTION_incoming
:
5296 saved_incoming
= incoming
;
5299 case QEMU_OPTION_chroot
:
5300 chroot_dir
= optarg
;
5302 case QEMU_OPTION_runas
:
5305 case QEMU_OPTION_nvram
:
5310 case QEMU_OPTION_xen_domid
:
5311 xen_domid
= atoi(optarg
);
5313 case QEMU_OPTION_xen_create
:
5314 xen_mode
= XEN_CREATE
;
5316 case QEMU_OPTION_xen_attach
:
5317 xen_mode
= XEN_ATTACH
;
5324 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5325 if (kvm_allowed
&& kqemu_allowed
) {
5327 "You can not enable both KVM and kqemu at the same time\n");
5332 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5333 if (smp_cpus
> machine
->max_cpus
) {
5334 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5335 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5341 if (serial_device_index
== 0)
5342 serial_devices
[0] = "stdio";
5343 if (parallel_device_index
== 0)
5344 parallel_devices
[0] = "null";
5345 if (strncmp(monitor_device
, "vc", 2) == 0)
5346 monitor_device
= "stdio";
5353 if (pipe(fds
) == -1)
5364 len
= read(fds
[0], &status
, 1);
5365 if (len
== -1 && (errno
== EINTR
))
5370 else if (status
== 1) {
5371 fprintf(stderr
, "Could not acquire pidfile\n");
5388 signal(SIGTSTP
, SIG_IGN
);
5389 signal(SIGTTOU
, SIG_IGN
);
5390 signal(SIGTTIN
, SIG_IGN
);
5394 if (kvm_enabled()) {
5395 if (kvm_qemu_init() < 0) {
5396 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
5397 #ifdef NO_CPU_EMULATION
5398 fprintf(stderr
, "Compiled with --disable-cpu-emulation, exiting.\n");
5406 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5409 write(fds
[1], &status
, 1);
5411 fprintf(stderr
, "Could not acquire pid file\n");
5420 linux_boot
= (kernel_filename
!= NULL
);
5421 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5423 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5424 fprintf(stderr
, "-append only allowed with -kernel option\n");
5428 if (!linux_boot
&& initrd_filename
!= NULL
) {
5429 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5433 /* boot to floppy or the default cd if no hard disk defined yet */
5434 if (!boot_devices
[0]) {
5435 boot_devices
= "cad";
5437 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5440 if (init_timer_alarm() < 0) {
5441 fprintf(stderr
, "could not initialize alarm timer\n");
5444 if (use_icount
&& icount_time_shift
< 0) {
5446 /* 125MIPS seems a reasonable initial guess at the guest speed.
5447 It will be corrected fairly quickly anyway. */
5448 icount_time_shift
= 3;
5449 init_icount_adjust();
5456 /* init network clients */
5457 if (nb_net_clients
== 0) {
5458 /* if no clients, we use a default config */
5459 net_clients
[nb_net_clients
++] = "nic";
5461 net_clients
[nb_net_clients
++] = "user";
5465 for(i
= 0;i
< nb_net_clients
; i
++) {
5466 if (net_client_parse(net_clients
[i
]) < 0)
5472 /* XXX: this should be moved in the PC machine instantiation code */
5473 if (net_boot
!= 0) {
5475 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
5476 const char *model
= nd_table
[i
].model
;
5478 if (net_boot
& (1 << i
)) {
5481 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
5482 if (get_image_size(buf
) > 0) {
5483 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5484 fprintf(stderr
, "Too many option ROMs\n");
5487 option_rom
[nb_option_roms
] = strdup(buf
);
5494 fprintf(stderr
, "No valid PXE rom found for network device\n");
5500 /* init the bluetooth world */
5501 for (i
= 0; i
< nb_bt_opts
; i
++)
5502 if (bt_parse(bt_opts
[i
]))
5506 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5508 /* init the memory */
5509 if (kvm_enabled()) {
5510 if (kvm_qemu_create_context() < 0) {
5511 fprintf(stderr
, "Could not create KVM context\n");
5517 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5518 guest ram allocation. It needs to go away. */
5519 if (kqemu_allowed
) {
5520 kqemu_phys_ram_size
= ram_size
+ VGA_RAM_SIZE
+ 4 * 1024 * 1024;
5521 kqemu_phys_ram_base
= qemu_vmalloc(kqemu_phys_ram_size
);
5522 if (!kqemu_phys_ram_base
) {
5523 fprintf(stderr
, "Could not allocate physical memory\n");
5529 /* init the dynamic translator */
5530 cpu_exec_init_all(tb_size
* 1024 * 1024);
5535 /* we always create the cdrom drive, even if no disk is there */
5537 if (nb_drives_opt
< MAX_DRIVES
)
5538 drive_add(NULL
, CDROM_ALIAS
);
5540 /* we always create at least one floppy */
5542 if (nb_drives_opt
< MAX_DRIVES
)
5543 drive_add(NULL
, FD_ALIAS
, 0);
5545 /* we always create one sd slot, even if no card is in it */
5547 if (nb_drives_opt
< MAX_DRIVES
)
5548 drive_add(NULL
, SD_ALIAS
);
5550 /* open the virtual block devices
5551 * note that migration with device
5552 * hot add/remove is broken.
5554 for(i
= 0; i
< nb_drives_opt
; i
++)
5555 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
5558 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
5559 register_savevm_live("ram", 0, 3, ram_save_live
, NULL
, ram_load
, NULL
);
5562 /* must be after terminal init, SDL library changes signal handlers */
5566 /* Maintain compatibility with multiple stdio monitors */
5567 if (!strcmp(monitor_device
,"stdio")) {
5568 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5569 const char *devname
= serial_devices
[i
];
5570 if (devname
&& !strcmp(devname
,"mon:stdio")) {
5571 monitor_device
= NULL
;
5573 } else if (devname
&& !strcmp(devname
,"stdio")) {
5574 monitor_device
= NULL
;
5575 serial_devices
[i
] = "mon:stdio";
5581 if (nb_numa_nodes
> 0) {
5584 if (nb_numa_nodes
> smp_cpus
) {
5585 nb_numa_nodes
= smp_cpus
;
5588 /* If no memory size if given for any node, assume the default case
5589 * and distribute the available memory equally across all nodes
5591 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5592 if (node_mem
[i
] != 0)
5595 if (i
== nb_numa_nodes
) {
5596 uint64_t usedmem
= 0;
5598 /* On Linux, the each node's border has to be 8MB aligned,
5599 * the final node gets the rest.
5601 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
5602 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
5603 usedmem
+= node_mem
[i
];
5605 node_mem
[i
] = ram_size
- usedmem
;
5608 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5609 if (node_cpumask
[i
] != 0)
5612 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5613 * must cope with this anyway, because there are BIOSes out there in
5614 * real machines which also use this scheme.
5616 if (i
== nb_numa_nodes
) {
5617 for (i
= 0; i
< smp_cpus
; i
++) {
5618 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
5624 if (kvm_enabled()) {
5627 ret
= kvm_init(smp_cpus
);
5629 fprintf(stderr
, "failed to initialize KVM\n");
5635 if (monitor_device
) {
5636 monitor_hd
= qemu_chr_open("monitor", monitor_device
, NULL
);
5638 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
5643 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5644 const char *devname
= serial_devices
[i
];
5645 if (devname
&& strcmp(devname
, "none")) {
5647 snprintf(label
, sizeof(label
), "serial%d", i
);
5648 serial_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5649 if (!serial_hds
[i
]) {
5650 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
5657 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
5658 const char *devname
= parallel_devices
[i
];
5659 if (devname
&& strcmp(devname
, "none")) {
5661 snprintf(label
, sizeof(label
), "parallel%d", i
);
5662 parallel_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5663 if (!parallel_hds
[i
]) {
5664 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
5671 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
5672 const char *devname
= virtio_consoles
[i
];
5673 if (devname
&& strcmp(devname
, "none")) {
5675 snprintf(label
, sizeof(label
), "virtcon%d", i
);
5676 virtcon_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5677 if (!virtcon_hds
[i
]) {
5678 fprintf(stderr
, "qemu: could not open virtio console '%s'\n",
5688 machine
->init(ram_size
, vga_ram_size
, boot_devices
,
5689 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
5692 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
5693 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5694 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
5700 current_machine
= machine
;
5702 /* Set KVM's vcpu state to qemu's initial CPUState. */
5703 if (kvm_enabled()) {
5706 ret
= kvm_sync_vcpus();
5708 fprintf(stderr
, "failed to initialize vcpus\n");
5713 /* init USB devices */
5715 for(i
= 0; i
< usb_devices_index
; i
++) {
5716 if (usb_device_add(usb_devices
[i
], 0) < 0) {
5717 fprintf(stderr
, "Warning: could not add USB device %s\n",
5724 dumb_display_init();
5725 /* just use the first displaystate for the moment */
5730 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
5734 #if defined(CONFIG_CURSES)
5736 /* At the moment curses cannot be used with other displays */
5737 curses_display_init(ds
, full_screen
);
5741 if (vnc_display
!= NULL
) {
5742 vnc_display_init(ds
);
5743 if (vnc_display_open(ds
, vnc_display
) < 0)
5746 #if defined(CONFIG_SDL)
5747 if (sdl
|| !vnc_display
)
5748 sdl_display_init(ds
, full_screen
, no_frame
);
5749 #elif defined(CONFIG_COCOA)
5750 if (sdl
|| !vnc_display
)
5751 cocoa_display_init(ds
, full_screen
);
5757 dcl
= ds
->listeners
;
5758 while (dcl
!= NULL
) {
5759 if (dcl
->dpy_refresh
!= NULL
) {
5760 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
5761 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
5766 if (nographic
|| (vnc_display
&& !sdl
)) {
5767 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
5768 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
5771 text_consoles_set_display(display_state
);
5772 qemu_chr_initial_reset();
5774 if (monitor_device
&& monitor_hd
)
5775 monitor_init(monitor_hd
, MONITOR_USE_READLINE
| MONITOR_IS_DEFAULT
);
5777 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5778 const char *devname
= serial_devices
[i
];
5779 if (devname
&& strcmp(devname
, "none")) {
5781 snprintf(label
, sizeof(label
), "serial%d", i
);
5782 if (strstart(devname
, "vc", 0))
5783 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
5787 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
5788 const char *devname
= parallel_devices
[i
];
5789 if (devname
&& strcmp(devname
, "none")) {
5791 snprintf(label
, sizeof(label
), "parallel%d", i
);
5792 if (strstart(devname
, "vc", 0))
5793 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
5797 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
5798 const char *devname
= virtio_consoles
[i
];
5799 if (virtcon_hds
[i
] && devname
) {
5801 snprintf(label
, sizeof(label
), "virtcon%d", i
);
5802 if (strstart(devname
, "vc", 0))
5803 qemu_chr_printf(virtcon_hds
[i
], "virtio console%d\r\n", i
);
5807 #ifdef CONFIG_GDBSTUB
5808 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
5809 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
5816 do_loadvm(cur_mon
, loadvm
);
5819 autostart
= 0; /* fixme how to deal with -daemonize */
5820 qemu_start_incoming_migration(incoming
);
5832 len
= write(fds
[1], &status
, 1);
5833 if (len
== -1 && (errno
== EINTR
))
5840 TFR(fd
= open("/dev/null", O_RDWR
));
5846 pwd
= getpwnam(run_as
);
5848 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
5854 if (chroot(chroot_dir
) < 0) {
5855 fprintf(stderr
, "chroot failed\n");
5862 if (setgid(pwd
->pw_gid
) < 0) {
5863 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
5866 if (setuid(pwd
->pw_uid
) < 0) {
5867 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
5870 if (setuid(0) != -1) {
5871 fprintf(stderr
, "Dropping privileges failed\n");