4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
32 /* Needed early for HOST_BSD etc. */
33 #include "config-host.h"
37 #include <sys/times.h>
41 #include <sys/ioctl.h>
42 #include <sys/resource.h>
43 #include <sys/socket.h>
45 #include <netinet/in.h>
47 #if defined(__NetBSD__)
48 #include <net/if_tap.h>
51 #include <linux/if_tun.h>
53 #include <arpa/inet.h>
56 #include <sys/select.h>
59 #if defined(__FreeBSD__) || defined(__DragonFly__)
64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65 #include <freebsd/stdlib.h>
70 #include <linux/rtc.h>
72 /* For the benefit of older linux systems which don't supply it,
73 we use a local copy of hpet.h. */
74 /* #include <linux/hpet.h> */
77 #include <linux/ppdev.h>
78 #include <linux/parport.h>
82 #include <sys/ethernet.h>
83 #include <sys/sockio.h>
84 #include <netinet/arp.h>
85 #include <netinet/in.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip_icmp.h> // must come after ip.h
89 #include <netinet/udp.h>
90 #include <netinet/tcp.h>
98 #if defined(__OpenBSD__)
102 #if defined(CONFIG_VDE)
103 #include <libvdeplug.h>
109 #include <sys/timeb.h>
110 #include <mmsystem.h>
111 #define getopt_long_only getopt_long
112 #define memalign(align, size) malloc(size)
118 int qemu_main(int argc
, char **argv
, char **envp
);
119 int main(int argc
, char **argv
)
121 qemu_main(argc
, argv
, NULL
);
124 #define main qemu_main
126 #endif /* CONFIG_SDL */
130 #define main qemu_main
131 #endif /* CONFIG_COCOA */
134 #include "hw/boards.h"
136 #include "hw/pcmcia.h"
138 #include "hw/audiodev.h"
142 #include "hw/smbios.h"
150 #include "qemu-timer.h"
151 #include "qemu-char.h"
152 #include "cache-utils.h"
155 #include "audio/audio.h"
156 #include "migration.h"
159 #include "qemu-kvm.h"
160 #include "hw/device-assignment.h"
164 #include "exec-all.h"
166 #include "qemu_socket.h"
168 #if defined(CONFIG_SLIRP)
169 #include "libslirp.h"
172 //#define DEBUG_UNUSED_IOPORT
173 //#define DEBUG_IOPORT
175 //#define DEBUG_SLIRP
179 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
181 # define LOG_IOPORT(...) do { } while (0)
184 #define DEFAULT_RAM_SIZE 128
186 /* Max number of USB devices that can be specified on the commandline. */
187 #define MAX_USB_CMDLINE 8
189 /* Max number of bluetooth switches on the commandline. */
190 #define MAX_BT_CMDLINE 10
192 /* XXX: use a two level table to limit memory usage */
193 #define MAX_IOPORTS 65536
195 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
196 const char *bios_name
= NULL
;
197 static void *ioport_opaque
[MAX_IOPORTS
];
198 static IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
199 static IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
200 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
201 to store the VM snapshots */
202 DriveInfo drives_table
[MAX_DRIVES
+1];
204 int extboot_drive
= -1;
205 static int vga_ram_size
;
206 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
207 static DisplayState
*display_state
;
211 const char* keyboard_layout
= NULL
;
212 int64_t ticks_per_sec
;
215 NICInfo nd_table
[MAX_NICS
];
217 static int autostart
;
218 static int rtc_utc
= 1;
219 static int rtc_date_offset
= -1; /* -1 means no change */
220 int cirrus_vga_enabled
= 1;
221 int std_vga_enabled
= 0;
222 int vmsvga_enabled
= 0;
223 int xenfb_enabled
= 0;
225 int graphic_width
= 1024;
226 int graphic_height
= 768;
227 int graphic_depth
= 8;
229 int graphic_width
= 800;
230 int graphic_height
= 600;
231 int graphic_depth
= 15;
233 static int full_screen
= 0;
235 static int no_frame
= 0;
238 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
239 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
240 CharDriverState
*virtcon_hds
[MAX_VIRTIO_CONSOLES
];
242 int win2k_install_hack
= 0;
247 const char *assigned_devices
[MAX_DEV_ASSIGN_CMDLINE
];
248 int assigned_devices_index
;
250 const char *vnc_display
;
251 int acpi_enabled
= 1;
257 int graphic_rotate
= 0;
261 const char *option_rom
[MAX_OPTION_ROMS
];
263 int semihosting_enabled
= 0;
264 int time_drift_fix
= 0;
265 unsigned int kvm_shadow_memory
= 0;
266 const char *mem_path
= NULL
;
268 int mem_prealloc
= 1; /* force preallocation of physical target memory */
271 const char *cpu_vendor_string
;
275 const char *qemu_name
;
277 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
278 unsigned int nb_prom_envs
= 0;
279 const char *prom_envs
[MAX_PROM_ENVS
];
282 const char *nvram
= NULL
;
283 struct drive_opt drives_opt
[MAX_DRIVES
];
286 uint64_t node_mem
[MAX_NODES
];
287 uint64_t node_cpumask
[MAX_NODES
];
289 static CPUState
*cur_cpu
;
290 static CPUState
*next_cpu
;
291 static int event_pending
= 1;
292 /* Conversion factor from emulated instructions to virtual clock ticks. */
293 static int icount_time_shift
;
294 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
295 #define MAX_ICOUNT_SHIFT 10
296 /* Compensate for varying guest execution speed. */
297 static int64_t qemu_icount_bias
;
298 static QEMUTimer
*icount_rt_timer
;
299 static QEMUTimer
*icount_vm_timer
;
300 static QEMUTimer
*nographic_timer
;
302 uint8_t qemu_uuid
[16];
304 /* KVM runs the main loop in a separate thread. If we update one of the lists
305 * that are polled before or after select(), we need to make sure to break out
306 * of the select() to ensure the new item is serviced.
308 static void main_loop_break(void)
311 qemu_kvm_notify_work();
314 /***********************************************************/
315 /* x86 ISA bus support */
317 target_phys_addr_t isa_mem_base
= 0;
320 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
321 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
323 static uint32_t ioport_read(int index
, uint32_t address
)
325 static IOPortReadFunc
*default_func
[3] = {
326 default_ioport_readb
,
327 default_ioport_readw
,
330 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
332 func
= default_func
[index
];
333 return func(ioport_opaque
[address
], address
);
336 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
338 static IOPortWriteFunc
*default_func
[3] = {
339 default_ioport_writeb
,
340 default_ioport_writew
,
341 default_ioport_writel
343 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
345 func
= default_func
[index
];
346 func(ioport_opaque
[address
], address
, data
);
349 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
351 #ifdef DEBUG_UNUSED_IOPORT
352 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
357 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
359 #ifdef DEBUG_UNUSED_IOPORT
360 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
364 /* default is to make two byte accesses */
365 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
368 data
= ioport_read(0, address
);
369 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
370 data
|= ioport_read(0, address
) << 8;
374 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
376 ioport_write(0, address
, data
& 0xff);
377 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
378 ioport_write(0, address
, (data
>> 8) & 0xff);
381 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
383 #ifdef DEBUG_UNUSED_IOPORT
384 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
389 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
391 #ifdef DEBUG_UNUSED_IOPORT
392 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
396 /* size is the word size in byte */
397 int register_ioport_read(int start
, int length
, int size
,
398 IOPortReadFunc
*func
, void *opaque
)
404 } else if (size
== 2) {
406 } else if (size
== 4) {
409 hw_error("register_ioport_read: invalid size");
412 for(i
= start
; i
< start
+ length
; i
+= size
) {
413 ioport_read_table
[bsize
][i
] = func
;
414 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
415 hw_error("register_ioport_read: invalid opaque");
416 ioport_opaque
[i
] = opaque
;
421 /* size is the word size in byte */
422 int register_ioport_write(int start
, int length
, int size
,
423 IOPortWriteFunc
*func
, void *opaque
)
429 } else if (size
== 2) {
431 } else if (size
== 4) {
434 hw_error("register_ioport_write: invalid size");
437 for(i
= start
; i
< start
+ length
; i
+= size
) {
438 ioport_write_table
[bsize
][i
] = func
;
439 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
440 hw_error("register_ioport_write: invalid opaque");
441 ioport_opaque
[i
] = opaque
;
446 void isa_unassign_ioport(int start
, int length
)
450 for(i
= start
; i
< start
+ length
; i
++) {
451 ioport_read_table
[0][i
] = default_ioport_readb
;
452 ioport_read_table
[1][i
] = default_ioport_readw
;
453 ioport_read_table
[2][i
] = default_ioport_readl
;
455 ioport_write_table
[0][i
] = default_ioport_writeb
;
456 ioport_write_table
[1][i
] = default_ioport_writew
;
457 ioport_write_table
[2][i
] = default_ioport_writel
;
459 ioport_opaque
[i
] = NULL
;
463 /***********************************************************/
465 void cpu_outb(CPUState
*env
, int addr
, int val
)
467 LOG_IOPORT("outb: %04x %02x\n", addr
, val
);
468 ioport_write(0, addr
, val
);
471 env
->last_io_time
= cpu_get_time_fast();
475 void cpu_outw(CPUState
*env
, int addr
, int val
)
477 LOG_IOPORT("outw: %04x %04x\n", addr
, val
);
478 ioport_write(1, addr
, val
);
481 env
->last_io_time
= cpu_get_time_fast();
485 void cpu_outl(CPUState
*env
, int addr
, int val
)
487 LOG_IOPORT("outl: %04x %08x\n", addr
, val
);
488 ioport_write(2, addr
, val
);
491 env
->last_io_time
= cpu_get_time_fast();
495 int cpu_inb(CPUState
*env
, int addr
)
498 val
= ioport_read(0, addr
);
499 LOG_IOPORT("inb : %04x %02x\n", addr
, val
);
502 env
->last_io_time
= cpu_get_time_fast();
507 int cpu_inw(CPUState
*env
, int addr
)
510 val
= ioport_read(1, addr
);
511 LOG_IOPORT("inw : %04x %04x\n", addr
, val
);
514 env
->last_io_time
= cpu_get_time_fast();
519 int cpu_inl(CPUState
*env
, int addr
)
522 val
= ioport_read(2, addr
);
523 LOG_IOPORT("inl : %04x %08x\n", addr
, val
);
526 env
->last_io_time
= cpu_get_time_fast();
531 /***********************************************************/
532 void hw_error(const char *fmt
, ...)
538 fprintf(stderr
, "qemu: hardware error: ");
539 vfprintf(stderr
, fmt
, ap
);
540 fprintf(stderr
, "\n");
541 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
542 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
544 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
546 cpu_dump_state(env
, stderr
, fprintf
, 0);
556 static QEMUBalloonEvent
*qemu_balloon_event
;
557 void *qemu_balloon_event_opaque
;
559 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
561 qemu_balloon_event
= func
;
562 qemu_balloon_event_opaque
= opaque
;
565 void qemu_balloon(ram_addr_t target
)
567 if (qemu_balloon_event
)
568 qemu_balloon_event(qemu_balloon_event_opaque
, target
);
571 ram_addr_t
qemu_balloon_status(void)
573 if (qemu_balloon_event
)
574 return qemu_balloon_event(qemu_balloon_event_opaque
, 0);
578 /***********************************************************/
581 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
582 static void *qemu_put_kbd_event_opaque
;
583 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
584 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
586 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
588 qemu_put_kbd_event_opaque
= opaque
;
589 qemu_put_kbd_event
= func
;
592 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
593 void *opaque
, int absolute
,
596 QEMUPutMouseEntry
*s
, *cursor
;
598 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
600 s
->qemu_put_mouse_event
= func
;
601 s
->qemu_put_mouse_event_opaque
= opaque
;
602 s
->qemu_put_mouse_event_absolute
= absolute
;
603 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
606 if (!qemu_put_mouse_event_head
) {
607 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
611 cursor
= qemu_put_mouse_event_head
;
612 while (cursor
->next
!= NULL
)
613 cursor
= cursor
->next
;
616 qemu_put_mouse_event_current
= s
;
621 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
623 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
625 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
628 cursor
= qemu_put_mouse_event_head
;
629 while (cursor
!= NULL
&& cursor
!= entry
) {
631 cursor
= cursor
->next
;
634 if (cursor
== NULL
) // does not exist or list empty
636 else if (prev
== NULL
) { // entry is head
637 qemu_put_mouse_event_head
= cursor
->next
;
638 if (qemu_put_mouse_event_current
== entry
)
639 qemu_put_mouse_event_current
= cursor
->next
;
640 qemu_free(entry
->qemu_put_mouse_event_name
);
645 prev
->next
= entry
->next
;
647 if (qemu_put_mouse_event_current
== entry
)
648 qemu_put_mouse_event_current
= prev
;
650 qemu_free(entry
->qemu_put_mouse_event_name
);
654 void kbd_put_keycode(int keycode
)
656 if (qemu_put_kbd_event
) {
657 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
661 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
663 QEMUPutMouseEvent
*mouse_event
;
664 void *mouse_event_opaque
;
667 if (!qemu_put_mouse_event_current
) {
672 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
674 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
677 if (graphic_rotate
) {
678 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
681 width
= graphic_width
- 1;
682 mouse_event(mouse_event_opaque
,
683 width
- dy
, dx
, dz
, buttons_state
);
685 mouse_event(mouse_event_opaque
,
686 dx
, dy
, dz
, buttons_state
);
690 int kbd_mouse_is_absolute(void)
692 if (!qemu_put_mouse_event_current
)
695 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
698 void do_info_mice(Monitor
*mon
)
700 QEMUPutMouseEntry
*cursor
;
703 if (!qemu_put_mouse_event_head
) {
704 monitor_printf(mon
, "No mouse devices connected\n");
708 monitor_printf(mon
, "Mouse devices available:\n");
709 cursor
= qemu_put_mouse_event_head
;
710 while (cursor
!= NULL
) {
711 monitor_printf(mon
, "%c Mouse #%d: %s\n",
712 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
713 index
, cursor
->qemu_put_mouse_event_name
);
715 cursor
= cursor
->next
;
719 void do_mouse_set(Monitor
*mon
, int index
)
721 QEMUPutMouseEntry
*cursor
;
724 if (!qemu_put_mouse_event_head
) {
725 monitor_printf(mon
, "No mouse devices connected\n");
729 cursor
= qemu_put_mouse_event_head
;
730 while (cursor
!= NULL
&& index
!= i
) {
732 cursor
= cursor
->next
;
736 qemu_put_mouse_event_current
= cursor
;
738 monitor_printf(mon
, "Mouse at given index not found\n");
741 /* compute with 96 bit intermediate result: (a*b)/c */
742 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
747 #ifdef WORDS_BIGENDIAN
757 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
758 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
761 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
765 /***********************************************************/
766 /* real time host monotonic timer */
768 #define QEMU_TIMER_BASE 1000000000LL
772 static int64_t clock_freq
;
774 static void init_get_clock(void)
778 ret
= QueryPerformanceFrequency(&freq
);
780 fprintf(stderr
, "Could not calibrate ticks\n");
783 clock_freq
= freq
.QuadPart
;
786 static int64_t get_clock(void)
789 QueryPerformanceCounter(&ti
);
790 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
795 static int use_rt_clock
;
797 static void init_get_clock(void)
800 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
801 || defined(__DragonFly__)
804 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
811 static int64_t get_clock(void)
813 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
814 || defined(__DragonFly__)
817 clock_gettime(CLOCK_MONOTONIC
, &ts
);
818 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
822 /* XXX: using gettimeofday leads to problems if the date
823 changes, so it should be avoided. */
825 gettimeofday(&tv
, NULL
);
826 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
831 /* Return the virtual CPU time, based on the instruction counter. */
832 static int64_t cpu_get_icount(void)
835 CPUState
*env
= cpu_single_env
;;
836 icount
= qemu_icount
;
839 fprintf(stderr
, "Bad clock read\n");
840 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
842 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
845 /***********************************************************/
846 /* guest cycle counter */
848 static int64_t cpu_ticks_prev
;
849 static int64_t cpu_ticks_offset
;
850 static int64_t cpu_clock_offset
;
851 static int cpu_ticks_enabled
;
853 /* return the host CPU cycle counter and handle stop/restart */
854 int64_t cpu_get_ticks(void)
857 return cpu_get_icount();
859 if (!cpu_ticks_enabled
) {
860 return cpu_ticks_offset
;
863 ticks
= cpu_get_real_ticks();
864 if (cpu_ticks_prev
> ticks
) {
865 /* Note: non increasing ticks may happen if the host uses
867 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
869 cpu_ticks_prev
= ticks
;
870 return ticks
+ cpu_ticks_offset
;
874 /* return the host CPU monotonic timer and handle stop/restart */
875 static int64_t cpu_get_clock(void)
878 if (!cpu_ticks_enabled
) {
879 return cpu_clock_offset
;
882 return ti
+ cpu_clock_offset
;
886 /* enable cpu_get_ticks() */
887 void cpu_enable_ticks(void)
889 if (!cpu_ticks_enabled
) {
890 cpu_ticks_offset
-= cpu_get_real_ticks();
891 cpu_clock_offset
-= get_clock();
892 cpu_ticks_enabled
= 1;
896 /* disable cpu_get_ticks() : the clock is stopped. You must not call
897 cpu_get_ticks() after that. */
898 void cpu_disable_ticks(void)
900 if (cpu_ticks_enabled
) {
901 cpu_ticks_offset
= cpu_get_ticks();
902 cpu_clock_offset
= cpu_get_clock();
903 cpu_ticks_enabled
= 0;
907 /***********************************************************/
910 #define QEMU_TIMER_REALTIME 0
911 #define QEMU_TIMER_VIRTUAL 1
915 /* XXX: add frequency */
923 struct QEMUTimer
*next
;
926 struct qemu_alarm_timer
{
930 int (*start
)(struct qemu_alarm_timer
*t
);
931 void (*stop
)(struct qemu_alarm_timer
*t
);
932 void (*rearm
)(struct qemu_alarm_timer
*t
);
936 #define ALARM_FLAG_DYNTICKS 0x1
937 #define ALARM_FLAG_EXPIRED 0x2
939 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
941 return t
->flags
& ALARM_FLAG_DYNTICKS
;
944 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
946 if (!alarm_has_dynticks(t
))
952 /* TODO: MIN_TIMER_REARM_US should be optimized */
953 #define MIN_TIMER_REARM_US 250
955 static struct qemu_alarm_timer
*alarm_timer
;
957 static int alarm_timer_rfd
, alarm_timer_wfd
;
962 struct qemu_alarm_win32
{
966 } alarm_win32_data
= {0, NULL
, -1};
968 static int win32_start_timer(struct qemu_alarm_timer
*t
);
969 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
970 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
974 static int unix_start_timer(struct qemu_alarm_timer
*t
);
975 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
979 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
980 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
981 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
983 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
984 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
986 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
987 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
989 #endif /* __linux__ */
993 /* Correlation between real and virtual time is always going to be
994 fairly approximate, so ignore small variation.
995 When the guest is idle real and virtual time will be aligned in
997 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
999 static void icount_adjust(void)
1004 static int64_t last_delta
;
1005 /* If the VM is not running, then do nothing. */
1009 cur_time
= cpu_get_clock();
1010 cur_icount
= qemu_get_clock(vm_clock
);
1011 delta
= cur_icount
- cur_time
;
1012 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1014 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
1015 && icount_time_shift
> 0) {
1016 /* The guest is getting too far ahead. Slow time down. */
1017 icount_time_shift
--;
1020 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
1021 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
1022 /* The guest is getting too far behind. Speed time up. */
1023 icount_time_shift
++;
1026 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
1029 static void icount_adjust_rt(void * opaque
)
1031 qemu_mod_timer(icount_rt_timer
,
1032 qemu_get_clock(rt_clock
) + 1000);
1036 static void icount_adjust_vm(void * opaque
)
1038 qemu_mod_timer(icount_vm_timer
,
1039 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1043 static void init_icount_adjust(void)
1045 /* Have both realtime and virtual time triggers for speed adjustment.
1046 The realtime trigger catches emulated time passing too slowly,
1047 the virtual time trigger catches emulated time passing too fast.
1048 Realtime triggers occur even when idle, so use them less frequently
1049 than VM triggers. */
1050 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
1051 qemu_mod_timer(icount_rt_timer
,
1052 qemu_get_clock(rt_clock
) + 1000);
1053 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
1054 qemu_mod_timer(icount_vm_timer
,
1055 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1058 static struct qemu_alarm_timer alarm_timers
[] = {
1061 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
1062 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
1063 /* HPET - if available - is preferred */
1064 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
1065 /* ...otherwise try RTC */
1066 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1068 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1070 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1071 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1072 {"win32", 0, win32_start_timer
,
1073 win32_stop_timer
, NULL
, &alarm_win32_data
},
1078 static void show_available_alarms(void)
1082 printf("Available alarm timers, in order of precedence:\n");
1083 for (i
= 0; alarm_timers
[i
].name
; i
++)
1084 printf("%s\n", alarm_timers
[i
].name
);
1087 static void configure_alarms(char const *opt
)
1091 int count
= ARRAY_SIZE(alarm_timers
) - 1;
1094 struct qemu_alarm_timer tmp
;
1096 if (!strcmp(opt
, "?")) {
1097 show_available_alarms();
1103 /* Reorder the array */
1104 name
= strtok(arg
, ",");
1106 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1107 if (!strcmp(alarm_timers
[i
].name
, name
))
1112 fprintf(stderr
, "Unknown clock %s\n", name
);
1121 tmp
= alarm_timers
[i
];
1122 alarm_timers
[i
] = alarm_timers
[cur
];
1123 alarm_timers
[cur
] = tmp
;
1127 name
= strtok(NULL
, ",");
1133 /* Disable remaining timers */
1134 for (i
= cur
; i
< count
; i
++)
1135 alarm_timers
[i
].name
= NULL
;
1137 show_available_alarms();
1142 QEMUClock
*rt_clock
;
1143 QEMUClock
*vm_clock
;
1145 static QEMUTimer
*active_timers
[2];
1147 static QEMUClock
*qemu_new_clock(int type
)
1150 clock
= qemu_mallocz(sizeof(QEMUClock
));
1155 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1159 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1162 ts
->opaque
= opaque
;
1166 void qemu_free_timer(QEMUTimer
*ts
)
1171 /* stop a timer, but do not dealloc it */
1172 void qemu_del_timer(QEMUTimer
*ts
)
1176 /* NOTE: this code must be signal safe because
1177 qemu_timer_expired() can be called from a signal. */
1178 pt
= &active_timers
[ts
->clock
->type
];
1191 /* modify the current timer so that it will be fired when current_time
1192 >= expire_time. The corresponding callback will be called. */
1193 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1199 /* add the timer in the sorted list */
1200 /* NOTE: this code must be signal safe because
1201 qemu_timer_expired() can be called from a signal. */
1202 pt
= &active_timers
[ts
->clock
->type
];
1207 if (t
->expire_time
> expire_time
)
1211 ts
->expire_time
= expire_time
;
1215 /* Rearm if necessary */
1216 if (pt
== &active_timers
[ts
->clock
->type
]) {
1217 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1218 qemu_rearm_alarm_timer(alarm_timer
);
1220 /* Interrupt execution to force deadline recalculation. */
1221 if (use_icount
&& cpu_single_env
) {
1222 cpu_exit(cpu_single_env
);
1227 int qemu_timer_pending(QEMUTimer
*ts
)
1230 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1237 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1241 return (timer_head
->expire_time
<= current_time
);
1244 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1250 if (!ts
|| ts
->expire_time
> current_time
)
1252 /* remove timer from the list before calling the callback */
1253 *ptimer_head
= ts
->next
;
1256 /* run the callback (the timer list can be modified) */
1261 int64_t qemu_get_clock(QEMUClock
*clock
)
1263 switch(clock
->type
) {
1264 case QEMU_TIMER_REALTIME
:
1265 return get_clock() / 1000000;
1267 case QEMU_TIMER_VIRTUAL
:
1269 return cpu_get_icount();
1271 return cpu_get_clock();
1276 static void init_timers(void)
1279 ticks_per_sec
= QEMU_TIMER_BASE
;
1280 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1281 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1285 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1287 uint64_t expire_time
;
1289 if (qemu_timer_pending(ts
)) {
1290 expire_time
= ts
->expire_time
;
1294 qemu_put_be64(f
, expire_time
);
1297 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1299 uint64_t expire_time
;
1301 expire_time
= qemu_get_be64(f
);
1302 if (expire_time
!= -1) {
1303 qemu_mod_timer(ts
, expire_time
);
1309 static void timer_save(QEMUFile
*f
, void *opaque
)
1311 if (cpu_ticks_enabled
) {
1312 hw_error("cannot save state if virtual timers are running");
1314 qemu_put_be64(f
, cpu_ticks_offset
);
1315 qemu_put_be64(f
, ticks_per_sec
);
1316 qemu_put_be64(f
, cpu_clock_offset
);
1319 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1321 if (version_id
!= 1 && version_id
!= 2)
1323 if (cpu_ticks_enabled
) {
1326 cpu_ticks_offset
=qemu_get_be64(f
);
1327 ticks_per_sec
=qemu_get_be64(f
);
1328 if (version_id
== 2) {
1329 cpu_clock_offset
=qemu_get_be64(f
);
1335 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1336 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1339 static void host_alarm_handler(int host_signum
)
1343 #define DISP_FREQ 1000
1345 static int64_t delta_min
= INT64_MAX
;
1346 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1348 ti
= qemu_get_clock(vm_clock
);
1349 if (last_clock
!= 0) {
1350 delta
= ti
- last_clock
;
1351 if (delta
< delta_min
)
1353 if (delta
> delta_max
)
1356 if (++count
== DISP_FREQ
) {
1357 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1358 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1359 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1360 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1361 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1363 delta_min
= INT64_MAX
;
1372 alarm_has_dynticks(alarm_timer
) ||
1374 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1375 qemu_get_clock(vm_clock
))) ||
1376 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1377 qemu_get_clock(rt_clock
))) {
1378 CPUState
*env
= next_cpu
;
1381 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1382 SetEvent(data
->host_alarm
);
1384 static const char byte
= 0;
1385 write(alarm_timer_wfd
, &byte
, sizeof(byte
));
1387 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1390 /* stop the currently executing cpu because a timer occured */
1393 if (env
->kqemu_enabled
) {
1394 kqemu_cpu_interrupt(env
);
1402 static int64_t qemu_next_deadline(void)
1406 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1407 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1408 qemu_get_clock(vm_clock
);
1410 /* To avoid problems with overflow limit this to 2^32. */
1420 #if defined(__linux__) || defined(_WIN32)
1421 static uint64_t qemu_next_deadline_dyntick(void)
1429 delta
= (qemu_next_deadline() + 999) / 1000;
1431 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1432 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1433 qemu_get_clock(rt_clock
))*1000;
1434 if (rtdelta
< delta
)
1438 if (delta
< MIN_TIMER_REARM_US
)
1439 delta
= MIN_TIMER_REARM_US
;
1447 /* Sets a specific flag */
1448 static int fcntl_setfl(int fd
, int flag
)
1452 flags
= fcntl(fd
, F_GETFL
);
1456 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1462 #if defined(__linux__)
1464 #define RTC_FREQ 1024
1466 static void enable_sigio_timer(int fd
)
1468 struct sigaction act
;
1471 sigfillset(&act
.sa_mask
);
1473 act
.sa_handler
= host_alarm_handler
;
1475 sigaction(SIGIO
, &act
, NULL
);
1476 fcntl_setfl(fd
, O_ASYNC
);
1477 fcntl(fd
, F_SETOWN
, getpid());
1480 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1482 struct hpet_info info
;
1485 fd
= open("/dev/hpet", O_RDONLY
);
1490 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1492 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1493 "error, but for better emulation accuracy type:\n"
1494 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1498 /* Check capabilities */
1499 r
= ioctl(fd
, HPET_INFO
, &info
);
1503 /* Enable periodic mode */
1504 r
= ioctl(fd
, HPET_EPI
, 0);
1505 if (info
.hi_flags
&& (r
< 0))
1508 /* Enable interrupt */
1509 r
= ioctl(fd
, HPET_IE_ON
, 0);
1513 enable_sigio_timer(fd
);
1514 t
->priv
= (void *)(long)fd
;
1522 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1524 int fd
= (long)t
->priv
;
1529 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1532 unsigned long current_rtc_freq
= 0;
1534 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1537 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1538 if (current_rtc_freq
!= RTC_FREQ
&&
1539 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1540 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1541 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1542 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1545 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1551 enable_sigio_timer(rtc_fd
);
1553 t
->priv
= (void *)(long)rtc_fd
;
1558 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1560 int rtc_fd
= (long)t
->priv
;
1565 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1569 struct sigaction act
;
1571 sigfillset(&act
.sa_mask
);
1573 act
.sa_handler
= host_alarm_handler
;
1575 sigaction(SIGALRM
, &act
, NULL
);
1577 ev
.sigev_value
.sival_int
= 0;
1578 ev
.sigev_notify
= SIGEV_SIGNAL
;
1579 ev
.sigev_signo
= SIGALRM
;
1581 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1582 perror("timer_create");
1584 /* disable dynticks */
1585 fprintf(stderr
, "Dynamic Ticks disabled\n");
1590 t
->priv
= (void *)(long)host_timer
;
1595 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1597 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1599 timer_delete(host_timer
);
1602 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1604 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1605 struct itimerspec timeout
;
1606 int64_t nearest_delta_us
= INT64_MAX
;
1609 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1610 !active_timers
[QEMU_TIMER_VIRTUAL
])
1613 nearest_delta_us
= qemu_next_deadline_dyntick();
1615 /* check whether a timer is already running */
1616 if (timer_gettime(host_timer
, &timeout
)) {
1618 fprintf(stderr
, "Internal timer error: aborting\n");
1621 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1622 if (current_us
&& current_us
<= nearest_delta_us
)
1625 timeout
.it_interval
.tv_sec
= 0;
1626 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1627 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1628 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1629 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1631 fprintf(stderr
, "Internal timer error: aborting\n");
1636 #endif /* defined(__linux__) */
1638 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1640 struct sigaction act
;
1641 struct itimerval itv
;
1645 sigfillset(&act
.sa_mask
);
1647 act
.sa_handler
= host_alarm_handler
;
1649 sigaction(SIGALRM
, &act
, NULL
);
1651 itv
.it_interval
.tv_sec
= 0;
1652 /* for i386 kernel 2.6 to get 1 ms */
1653 itv
.it_interval
.tv_usec
= 999;
1654 itv
.it_value
.tv_sec
= 0;
1655 itv
.it_value
.tv_usec
= 10 * 1000;
1657 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1664 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1666 struct itimerval itv
;
1668 memset(&itv
, 0, sizeof(itv
));
1669 setitimer(ITIMER_REAL
, &itv
, NULL
);
1672 #endif /* !defined(_WIN32) */
1674 static void try_to_rearm_timer(void *opaque
)
1676 struct qemu_alarm_timer
*t
= opaque
;
1680 /* Drain the notify pipe */
1683 len
= read(alarm_timer_rfd
, buffer
, sizeof(buffer
));
1684 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
1687 if (t
->flags
& ALARM_FLAG_EXPIRED
) {
1688 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
1689 qemu_rearm_alarm_timer(alarm_timer
);
1695 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1698 struct qemu_alarm_win32
*data
= t
->priv
;
1701 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1702 if (!data
->host_alarm
) {
1703 perror("Failed CreateEvent");
1707 memset(&tc
, 0, sizeof(tc
));
1708 timeGetDevCaps(&tc
, sizeof(tc
));
1710 if (data
->period
< tc
.wPeriodMin
)
1711 data
->period
= tc
.wPeriodMin
;
1713 timeBeginPeriod(data
->period
);
1715 flags
= TIME_CALLBACK_FUNCTION
;
1716 if (alarm_has_dynticks(t
))
1717 flags
|= TIME_ONESHOT
;
1719 flags
|= TIME_PERIODIC
;
1721 data
->timerId
= timeSetEvent(1, // interval (ms)
1722 data
->period
, // resolution
1723 host_alarm_handler
, // function
1724 (DWORD
)t
, // parameter
1727 if (!data
->timerId
) {
1728 perror("Failed to initialize win32 alarm timer");
1730 timeEndPeriod(data
->period
);
1731 CloseHandle(data
->host_alarm
);
1735 qemu_add_wait_object(data
->host_alarm
, try_to_rearm_timer
, t
);
1740 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1742 struct qemu_alarm_win32
*data
= t
->priv
;
1744 timeKillEvent(data
->timerId
);
1745 timeEndPeriod(data
->period
);
1747 CloseHandle(data
->host_alarm
);
1750 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1752 struct qemu_alarm_win32
*data
= t
->priv
;
1753 uint64_t nearest_delta_us
;
1755 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1756 !active_timers
[QEMU_TIMER_VIRTUAL
])
1759 nearest_delta_us
= qemu_next_deadline_dyntick();
1760 nearest_delta_us
/= 1000;
1762 timeKillEvent(data
->timerId
);
1764 data
->timerId
= timeSetEvent(1,
1768 TIME_ONESHOT
| TIME_PERIODIC
);
1770 if (!data
->timerId
) {
1771 perror("Failed to re-arm win32 alarm timer");
1773 timeEndPeriod(data
->period
);
1774 CloseHandle(data
->host_alarm
);
1781 static int init_timer_alarm(void)
1783 struct qemu_alarm_timer
*t
= NULL
;
1793 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
1797 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
1801 alarm_timer_rfd
= fds
[0];
1802 alarm_timer_wfd
= fds
[1];
1805 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1806 t
= &alarm_timers
[i
];
1819 qemu_set_fd_handler2(alarm_timer_rfd
, NULL
,
1820 try_to_rearm_timer
, NULL
, t
);
1835 static void quit_timers(void)
1837 alarm_timer
->stop(alarm_timer
);
1841 /***********************************************************/
1842 /* host time/date access */
1843 void qemu_get_timedate(struct tm
*tm
, int offset
)
1850 if (rtc_date_offset
== -1) {
1854 ret
= localtime(&ti
);
1856 ti
-= rtc_date_offset
;
1860 memcpy(tm
, ret
, sizeof(struct tm
));
1863 int qemu_timedate_diff(struct tm
*tm
)
1867 if (rtc_date_offset
== -1)
1869 seconds
= mktimegm(tm
);
1871 seconds
= mktime(tm
);
1873 seconds
= mktimegm(tm
) + rtc_date_offset
;
1875 return seconds
- time(NULL
);
1879 static void socket_cleanup(void)
1884 static int socket_init(void)
1889 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1891 err
= WSAGetLastError();
1892 fprintf(stderr
, "WSAStartup: %d\n", err
);
1895 atexit(socket_cleanup
);
1900 const char *get_opt_name(char *buf
, int buf_size
, const char *p
, char delim
)
1905 while (*p
!= '\0' && *p
!= delim
) {
1906 if (q
&& (q
- buf
) < buf_size
- 1)
1916 const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
1921 while (*p
!= '\0') {
1923 if (*(p
+ 1) != ',')
1927 if (q
&& (q
- buf
) < buf_size
- 1)
1937 int get_param_value(char *buf
, int buf_size
,
1938 const char *tag
, const char *str
)
1945 p
= get_opt_name(option
, sizeof(option
), p
, '=');
1949 if (!strcmp(tag
, option
)) {
1950 (void)get_opt_value(buf
, buf_size
, p
);
1953 p
= get_opt_value(NULL
, 0, p
);
1962 int check_params(char *buf
, int buf_size
,
1963 const char * const *params
, const char *str
)
1969 while (*p
!= '\0') {
1970 p
= get_opt_name(buf
, buf_size
, p
, '=');
1974 for(i
= 0; params
[i
] != NULL
; i
++)
1975 if (!strcmp(params
[i
], buf
))
1977 if (params
[i
] == NULL
)
1979 p
= get_opt_value(NULL
, 0, p
);
1987 /***********************************************************/
1988 /* Bluetooth support */
1991 static struct HCIInfo
*hci_table
[MAX_NICS
];
1993 static struct bt_vlan_s
{
1994 struct bt_scatternet_s net
;
1996 struct bt_vlan_s
*next
;
1999 /* find or alloc a new bluetooth "VLAN" */
2000 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
2002 struct bt_vlan_s
**pvlan
, *vlan
;
2003 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
2007 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
2009 pvlan
= &first_bt_vlan
;
2010 while (*pvlan
!= NULL
)
2011 pvlan
= &(*pvlan
)->next
;
2016 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
2020 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
2025 static struct HCIInfo null_hci
= {
2026 .cmd_send
= null_hci_send
,
2027 .sco_send
= null_hci_send
,
2028 .acl_send
= null_hci_send
,
2029 .bdaddr_set
= null_hci_addr_set
,
2032 struct HCIInfo
*qemu_next_hci(void)
2034 if (cur_hci
== nb_hcis
)
2037 return hci_table
[cur_hci
++];
2040 static struct HCIInfo
*hci_init(const char *str
)
2043 struct bt_scatternet_s
*vlan
= 0;
2045 if (!strcmp(str
, "null"))
2048 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
2050 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
2051 else if (!strncmp(str
, "hci", 3)) {
2054 if (!strncmp(str
+ 3, ",vlan=", 6)) {
2055 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
2060 vlan
= qemu_find_bt_vlan(0);
2062 return bt_new_hci(vlan
);
2065 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
2070 static int bt_hci_parse(const char *str
)
2072 struct HCIInfo
*hci
;
2075 if (nb_hcis
>= MAX_NICS
) {
2076 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
2080 hci
= hci_init(str
);
2089 bdaddr
.b
[5] = 0x56 + nb_hcis
;
2090 hci
->bdaddr_set(hci
, bdaddr
.b
);
2092 hci_table
[nb_hcis
++] = hci
;
2097 static void bt_vhci_add(int vlan_id
)
2099 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
2102 fprintf(stderr
, "qemu: warning: adding a VHCI to "
2103 "an empty scatternet %i\n", vlan_id
);
2105 bt_vhci_init(bt_new_hci(vlan
));
2108 static struct bt_device_s
*bt_device_add(const char *opt
)
2110 struct bt_scatternet_s
*vlan
;
2112 char *endp
= strstr(opt
, ",vlan=");
2113 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
2116 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
2119 vlan_id
= strtol(endp
+ 6, &endp
, 0);
2121 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
2126 vlan
= qemu_find_bt_vlan(vlan_id
);
2129 fprintf(stderr
, "qemu: warning: adding a slave device to "
2130 "an empty scatternet %i\n", vlan_id
);
2132 if (!strcmp(devname
, "keyboard"))
2133 return bt_keyboard_init(vlan
);
2135 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
2139 static int bt_parse(const char *opt
)
2141 const char *endp
, *p
;
2144 if (strstart(opt
, "hci", &endp
)) {
2145 if (!*endp
|| *endp
== ',') {
2147 if (!strstart(endp
, ",vlan=", 0))
2150 return bt_hci_parse(opt
);
2152 } else if (strstart(opt
, "vhci", &endp
)) {
2153 if (!*endp
|| *endp
== ',') {
2155 if (strstart(endp
, ",vlan=", &p
)) {
2156 vlan
= strtol(p
, (char **) &endp
, 0);
2158 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
2162 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
2171 } else if (strstart(opt
, "device:", &endp
))
2172 return !bt_device_add(endp
);
2174 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
2178 /***********************************************************/
2179 /* QEMU Block devices */
2181 #define HD_ALIAS "index=%d,media=disk"
2182 #define CDROM_ALIAS "index=2,media=cdrom"
2183 #define FD_ALIAS "index=%d,if=floppy"
2184 #define PFLASH_ALIAS "if=pflash"
2185 #define MTD_ALIAS "if=mtd"
2186 #define SD_ALIAS "index=0,if=sd"
2188 static int drive_opt_get_free_idx(void)
2192 for (index
= 0; index
< MAX_DRIVES
; index
++)
2193 if (!drives_opt
[index
].used
) {
2194 drives_opt
[index
].used
= 1;
2201 static int drive_get_free_idx(void)
2205 for (index
= 0; index
< MAX_DRIVES
; index
++)
2206 if (!drives_table
[index
].used
) {
2207 drives_table
[index
].used
= 1;
2214 int drive_add(const char *file
, const char *fmt
, ...)
2217 int index
= drive_opt_get_free_idx();
2219 if (nb_drives_opt
>= MAX_DRIVES
|| index
== -1) {
2220 fprintf(stderr
, "qemu: too many drives\n");
2224 drives_opt
[index
].file
= file
;
2226 vsnprintf(drives_opt
[index
].opt
,
2227 sizeof(drives_opt
[0].opt
), fmt
, ap
);
2234 void drive_remove(int index
)
2236 drives_opt
[index
].used
= 0;
2240 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
2244 /* seek interface, bus and unit */
2246 for (index
= 0; index
< MAX_DRIVES
; index
++)
2247 if (drives_table
[index
].type
== type
&&
2248 drives_table
[index
].bus
== bus
&&
2249 drives_table
[index
].unit
== unit
&&
2250 drives_table
[index
].used
)
2256 int drive_get_max_bus(BlockInterfaceType type
)
2262 for (index
= 0; index
< nb_drives
; index
++) {
2263 if(drives_table
[index
].type
== type
&&
2264 drives_table
[index
].bus
> max_bus
)
2265 max_bus
= drives_table
[index
].bus
;
2270 const char *drive_get_serial(BlockDriverState
*bdrv
)
2274 for (index
= 0; index
< nb_drives
; index
++)
2275 if (drives_table
[index
].bdrv
== bdrv
)
2276 return drives_table
[index
].serial
;
2281 BlockInterfaceErrorAction
drive_get_onerror(BlockDriverState
*bdrv
)
2285 for (index
= 0; index
< nb_drives
; index
++)
2286 if (drives_table
[index
].bdrv
== bdrv
)
2287 return drives_table
[index
].onerror
;
2289 return BLOCK_ERR_STOP_ENOSPC
;
2292 static void bdrv_format_print(void *opaque
, const char *name
)
2294 fprintf(stderr
, " %s", name
);
2297 void drive_uninit(BlockDriverState
*bdrv
)
2301 for (i
= 0; i
< MAX_DRIVES
; i
++)
2302 if (drives_table
[i
].bdrv
== bdrv
) {
2303 drives_table
[i
].bdrv
= NULL
;
2304 drives_table
[i
].used
= 0;
2305 drive_remove(drives_table
[i
].drive_opt_idx
);
2311 int drive_init(struct drive_opt
*arg
, int snapshot
, void *opaque
)
2317 const char *mediastr
= "";
2318 BlockInterfaceType type
;
2319 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
2320 int bus_id
, unit_id
;
2321 int cyls
, heads
, secs
, translation
;
2322 BlockDriverState
*bdrv
;
2323 BlockDriver
*drv
= NULL
;
2324 QEMUMachine
*machine
= opaque
;
2328 int bdrv_flags
, onerror
;
2329 int drives_table_idx
;
2330 char *str
= arg
->opt
;
2331 static const char * const params
[] = { "bus", "unit", "if", "index",
2332 "cyls", "heads", "secs", "trans",
2333 "media", "snapshot", "file",
2334 "cache", "format", "serial", "werror",
2337 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
2338 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
2344 cyls
= heads
= secs
= 0;
2347 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2351 if (machine
->use_scsi
) {
2353 max_devs
= MAX_SCSI_DEVS
;
2354 pstrcpy(devname
, sizeof(devname
), "scsi");
2357 max_devs
= MAX_IDE_DEVS
;
2358 pstrcpy(devname
, sizeof(devname
), "ide");
2362 /* extract parameters */
2364 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
2365 bus_id
= strtol(buf
, NULL
, 0);
2367 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
2372 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
2373 unit_id
= strtol(buf
, NULL
, 0);
2375 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
2380 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
2381 pstrcpy(devname
, sizeof(devname
), buf
);
2382 if (!strcmp(buf
, "ide")) {
2384 max_devs
= MAX_IDE_DEVS
;
2385 } else if (!strcmp(buf
, "scsi")) {
2387 max_devs
= MAX_SCSI_DEVS
;
2388 } else if (!strcmp(buf
, "floppy")) {
2391 } else if (!strcmp(buf
, "pflash")) {
2394 } else if (!strcmp(buf
, "mtd")) {
2397 } else if (!strcmp(buf
, "sd")) {
2400 } else if (!strcmp(buf
, "virtio")) {
2403 } else if (!strcmp(buf
, "xen")) {
2407 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
2412 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
2413 index
= strtol(buf
, NULL
, 0);
2415 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
2420 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
2421 cyls
= strtol(buf
, NULL
, 0);
2424 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
2425 heads
= strtol(buf
, NULL
, 0);
2428 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
2429 secs
= strtol(buf
, NULL
, 0);
2432 if (cyls
|| heads
|| secs
) {
2433 if (cyls
< 1 || cyls
> 16383) {
2434 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
2437 if (heads
< 1 || heads
> 16) {
2438 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
2441 if (secs
< 1 || secs
> 63) {
2442 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
2447 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
2450 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2454 if (!strcmp(buf
, "none"))
2455 translation
= BIOS_ATA_TRANSLATION_NONE
;
2456 else if (!strcmp(buf
, "lba"))
2457 translation
= BIOS_ATA_TRANSLATION_LBA
;
2458 else if (!strcmp(buf
, "auto"))
2459 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2461 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
2466 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
2467 if (!strcmp(buf
, "disk")) {
2469 } else if (!strcmp(buf
, "cdrom")) {
2470 if (cyls
|| secs
|| heads
) {
2472 "qemu: '%s' invalid physical CHS format\n", str
);
2475 media
= MEDIA_CDROM
;
2477 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
2482 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
2483 if (!strcmp(buf
, "on"))
2485 else if (!strcmp(buf
, "off"))
2488 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
2493 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
2494 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2496 else if (!strcmp(buf
, "writethrough"))
2498 else if (!strcmp(buf
, "writeback"))
2501 fprintf(stderr
, "qemu: invalid cache option\n");
2506 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
2507 if (strcmp(buf
, "?") == 0) {
2508 fprintf(stderr
, "qemu: Supported formats:");
2509 bdrv_iterate_format(bdrv_format_print
, NULL
);
2510 fprintf(stderr
, "\n");
2513 drv
= bdrv_find_format(buf
);
2515 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2520 if (get_param_value(buf
, sizeof(buf
), "boot", str
)) {
2521 if (!strcmp(buf
, "on")) {
2522 if (extboot_drive
!= -1) {
2523 fprintf(stderr
, "qemu: two bootable drives specified\n");
2526 extboot_drive
= nb_drives
;
2527 } else if (strcmp(buf
, "off")) {
2528 fprintf(stderr
, "qemu: '%s' invalid boot option\n", str
);
2533 if (arg
->file
== NULL
)
2534 get_param_value(file
, sizeof(file
), "file", str
);
2536 pstrcpy(file
, sizeof(file
), arg
->file
);
2538 if (!get_param_value(serial
, sizeof(serial
), "serial", str
))
2539 memset(serial
, 0, sizeof(serial
));
2541 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2542 if (get_param_value(buf
, sizeof(serial
), "werror", str
)) {
2543 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2544 fprintf(stderr
, "werror is no supported by this format\n");
2547 if (!strcmp(buf
, "ignore"))
2548 onerror
= BLOCK_ERR_IGNORE
;
2549 else if (!strcmp(buf
, "enospc"))
2550 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2551 else if (!strcmp(buf
, "stop"))
2552 onerror
= BLOCK_ERR_STOP_ANY
;
2553 else if (!strcmp(buf
, "report"))
2554 onerror
= BLOCK_ERR_REPORT
;
2556 fprintf(stderr
, "qemu: '%s' invalid write error action\n", buf
);
2561 /* compute bus and unit according index */
2564 if (bus_id
!= 0 || unit_id
!= -1) {
2566 "qemu: '%s' index cannot be used with bus and unit\n", str
);
2574 unit_id
= index
% max_devs
;
2575 bus_id
= index
/ max_devs
;
2579 /* if user doesn't specify a unit_id,
2580 * try to find the first free
2583 if (unit_id
== -1) {
2585 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
2587 if (max_devs
&& unit_id
>= max_devs
) {
2588 unit_id
-= max_devs
;
2596 if (max_devs
&& unit_id
>= max_devs
) {
2597 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
2598 str
, unit_id
, max_devs
- 1);
2603 * ignore multiple definitions
2606 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
2611 if (type
== IF_IDE
|| type
== IF_SCSI
)
2612 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2614 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
2615 devname
, bus_id
, mediastr
, unit_id
);
2617 snprintf(buf
, sizeof(buf
), "%s%s%i",
2618 devname
, mediastr
, unit_id
);
2619 bdrv
= bdrv_new(buf
);
2620 drives_table_idx
= drive_get_free_idx();
2621 drives_table
[drives_table_idx
].bdrv
= bdrv
;
2622 drives_table
[drives_table_idx
].type
= type
;
2623 drives_table
[drives_table_idx
].bus
= bus_id
;
2624 drives_table
[drives_table_idx
].unit
= unit_id
;
2625 drives_table
[drives_table_idx
].onerror
= onerror
;
2626 drives_table
[drives_table_idx
].drive_opt_idx
= arg
- drives_opt
;
2627 strncpy(drives_table
[drives_table_idx
].serial
, serial
, sizeof(serial
));
2637 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
2638 bdrv_set_translation_hint(bdrv
, translation
);
2642 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
2647 /* FIXME: This isn't really a floppy, but it's a reasonable
2650 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
2661 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2662 cache
= 2; /* always use write-back with snapshot */
2664 if (cache
== 0) /* no caching */
2665 bdrv_flags
|= BDRV_O_NOCACHE
;
2666 else if (cache
== 2) /* write-back */
2667 bdrv_flags
|= BDRV_O_CACHE_WB
;
2668 else if (cache
== 3) /* not specified */
2669 bdrv_flags
|= BDRV_O_CACHE_DEF
;
2670 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0) {
2671 fprintf(stderr
, "qemu: could not open disk image %s\n",
2675 if (bdrv_key_required(bdrv
))
2677 return drives_table_idx
;
2680 static void numa_add(const char *optarg
)
2684 unsigned long long value
, endvalue
;
2687 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2688 if (!strcmp(option
, "node")) {
2689 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2690 nodenr
= nb_numa_nodes
;
2692 nodenr
= strtoull(option
, NULL
, 10);
2695 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2696 node_mem
[nodenr
] = 0;
2698 value
= strtoull(option
, &endptr
, 0);
2700 case 0: case 'M': case 'm':
2707 node_mem
[nodenr
] = value
;
2709 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2710 node_cpumask
[nodenr
] = 0;
2712 value
= strtoull(option
, &endptr
, 10);
2715 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2717 if (*endptr
== '-') {
2718 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2719 if (endvalue
>= 63) {
2722 "only 63 CPUs in NUMA mode supported.\n");
2724 value
= (1 << (endvalue
+ 1)) - (1 << value
);
2729 node_cpumask
[nodenr
] = value
;
2736 /***********************************************************/
2739 static USBPort
*used_usb_ports
;
2740 static USBPort
*free_usb_ports
;
2742 /* ??? Maybe change this to register a hub to keep track of the topology. */
2743 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
2744 usb_attachfn attach
)
2746 port
->opaque
= opaque
;
2747 port
->index
= index
;
2748 port
->attach
= attach
;
2749 port
->next
= free_usb_ports
;
2750 free_usb_ports
= port
;
2753 int usb_device_add_dev(USBDevice
*dev
)
2757 /* Find a USB port to add the device to. */
2758 port
= free_usb_ports
;
2762 /* Create a new hub and chain it on. */
2763 free_usb_ports
= NULL
;
2764 port
->next
= used_usb_ports
;
2765 used_usb_ports
= port
;
2767 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
2768 usb_attach(port
, hub
);
2769 port
= free_usb_ports
;
2772 free_usb_ports
= port
->next
;
2773 port
->next
= used_usb_ports
;
2774 used_usb_ports
= port
;
2775 usb_attach(port
, dev
);
2779 static void usb_msd_password_cb(void *opaque
, int err
)
2781 USBDevice
*dev
= opaque
;
2784 usb_device_add_dev(dev
);
2786 dev
->handle_destroy(dev
);
2789 static int usb_device_add(const char *devname
, int is_hotplug
)
2794 if (!free_usb_ports
)
2797 if (strstart(devname
, "host:", &p
)) {
2798 dev
= usb_host_device_open(p
);
2799 } else if (!strcmp(devname
, "mouse")) {
2800 dev
= usb_mouse_init();
2801 } else if (!strcmp(devname
, "tablet")) {
2802 dev
= usb_tablet_init();
2803 } else if (!strcmp(devname
, "keyboard")) {
2804 dev
= usb_keyboard_init();
2805 } else if (strstart(devname
, "disk:", &p
)) {
2806 BlockDriverState
*bs
;
2808 dev
= usb_msd_init(p
);
2811 bs
= usb_msd_get_bdrv(dev
);
2812 if (bdrv_key_required(bs
)) {
2815 monitor_read_bdrv_key_start(cur_mon
, bs
, usb_msd_password_cb
,
2820 } else if (!strcmp(devname
, "wacom-tablet")) {
2821 dev
= usb_wacom_init();
2822 } else if (strstart(devname
, "serial:", &p
)) {
2823 dev
= usb_serial_init(p
);
2824 #ifdef CONFIG_BRLAPI
2825 } else if (!strcmp(devname
, "braille")) {
2826 dev
= usb_baum_init();
2828 } else if (strstart(devname
, "net:", &p
)) {
2831 if (net_client_init("nic", p
) < 0)
2833 nd_table
[nic
].model
= "usb";
2834 dev
= usb_net_init(&nd_table
[nic
]);
2835 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2836 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2837 bt_new_hci(qemu_find_bt_vlan(0)));
2844 return usb_device_add_dev(dev
);
2847 int usb_device_del_addr(int bus_num
, int addr
)
2853 if (!used_usb_ports
)
2859 lastp
= &used_usb_ports
;
2860 port
= used_usb_ports
;
2861 while (port
&& port
->dev
->addr
!= addr
) {
2862 lastp
= &port
->next
;
2870 *lastp
= port
->next
;
2871 usb_attach(port
, NULL
);
2872 dev
->handle_destroy(dev
);
2873 port
->next
= free_usb_ports
;
2874 free_usb_ports
= port
;
2878 static int usb_device_del(const char *devname
)
2883 if (strstart(devname
, "host:", &p
))
2884 return usb_host_device_close(p
);
2886 if (!used_usb_ports
)
2889 p
= strchr(devname
, '.');
2892 bus_num
= strtoul(devname
, NULL
, 0);
2893 addr
= strtoul(p
+ 1, NULL
, 0);
2895 return usb_device_del_addr(bus_num
, addr
);
2898 void do_usb_add(Monitor
*mon
, const char *devname
)
2900 usb_device_add(devname
, 1);
2903 void do_usb_del(Monitor
*mon
, const char *devname
)
2905 usb_device_del(devname
);
2908 void usb_info(Monitor
*mon
)
2912 const char *speed_str
;
2915 monitor_printf(mon
, "USB support not enabled\n");
2919 for (port
= used_usb_ports
; port
; port
= port
->next
) {
2923 switch(dev
->speed
) {
2927 case USB_SPEED_FULL
:
2930 case USB_SPEED_HIGH
:
2937 monitor_printf(mon
, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2938 0, dev
->addr
, speed_str
, dev
->devname
);
2942 /***********************************************************/
2943 /* PCMCIA/Cardbus */
2945 static struct pcmcia_socket_entry_s
{
2946 struct pcmcia_socket_s
*socket
;
2947 struct pcmcia_socket_entry_s
*next
;
2948 } *pcmcia_sockets
= 0;
2950 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
2952 struct pcmcia_socket_entry_s
*entry
;
2954 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2955 entry
->socket
= socket
;
2956 entry
->next
= pcmcia_sockets
;
2957 pcmcia_sockets
= entry
;
2960 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
2962 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2964 ptr
= &pcmcia_sockets
;
2965 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2966 if (entry
->socket
== socket
) {
2972 void pcmcia_info(Monitor
*mon
)
2974 struct pcmcia_socket_entry_s
*iter
;
2976 if (!pcmcia_sockets
)
2977 monitor_printf(mon
, "No PCMCIA sockets\n");
2979 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2980 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2981 iter
->socket
->attached
? iter
->socket
->card_string
:
2985 /***********************************************************/
2986 /* register display */
2988 struct DisplayAllocator default_allocator
= {
2989 defaultallocator_create_displaysurface
,
2990 defaultallocator_resize_displaysurface
,
2991 defaultallocator_free_displaysurface
2994 void register_displaystate(DisplayState
*ds
)
3004 DisplayState
*get_displaystate(void)
3006 return display_state
;
3009 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
3011 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
3012 return ds
->allocator
;
3017 static void dumb_display_init(void)
3019 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
3020 ds
->allocator
= &default_allocator
;
3021 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
3022 register_displaystate(ds
);
3025 /***********************************************************/
3028 typedef struct IOHandlerRecord
{
3030 IOCanRWHandler
*fd_read_poll
;
3032 IOHandler
*fd_write
;
3035 /* temporary data */
3037 struct IOHandlerRecord
*next
;
3040 static IOHandlerRecord
*first_io_handler
;
3042 /* XXX: fd_read_poll should be suppressed, but an API change is
3043 necessary in the character devices to suppress fd_can_read(). */
3044 int qemu_set_fd_handler2(int fd
,
3045 IOCanRWHandler
*fd_read_poll
,
3047 IOHandler
*fd_write
,
3050 IOHandlerRecord
**pioh
, *ioh
;
3052 if (!fd_read
&& !fd_write
) {
3053 pioh
= &first_io_handler
;
3058 if (ioh
->fd
== fd
) {
3065 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3069 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
3070 ioh
->next
= first_io_handler
;
3071 first_io_handler
= ioh
;
3074 ioh
->fd_read_poll
= fd_read_poll
;
3075 ioh
->fd_read
= fd_read
;
3076 ioh
->fd_write
= fd_write
;
3077 ioh
->opaque
= opaque
;
3084 int qemu_set_fd_handler(int fd
,
3086 IOHandler
*fd_write
,
3089 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
3093 /***********************************************************/
3094 /* Polling handling */
3096 typedef struct PollingEntry
{
3099 struct PollingEntry
*next
;
3102 static PollingEntry
*first_polling_entry
;
3104 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
3106 PollingEntry
**ppe
, *pe
;
3107 pe
= qemu_mallocz(sizeof(PollingEntry
));
3109 pe
->opaque
= opaque
;
3110 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
3115 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
3117 PollingEntry
**ppe
, *pe
;
3118 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
3120 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
3128 /***********************************************************/
3129 /* Wait objects support */
3130 typedef struct WaitObjects
{
3132 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
3133 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
3134 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
3137 static WaitObjects wait_objects
= {0};
3139 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
3141 WaitObjects
*w
= &wait_objects
;
3143 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
3145 w
->events
[w
->num
] = handle
;
3146 w
->func
[w
->num
] = func
;
3147 w
->opaque
[w
->num
] = opaque
;
3152 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
3155 WaitObjects
*w
= &wait_objects
;
3158 for (i
= 0; i
< w
->num
; i
++) {
3159 if (w
->events
[i
] == handle
)
3162 w
->events
[i
] = w
->events
[i
+ 1];
3163 w
->func
[i
] = w
->func
[i
+ 1];
3164 w
->opaque
[i
] = w
->opaque
[i
+ 1];
3172 /***********************************************************/
3173 /* ram save/restore */
3175 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
3179 v
= qemu_get_byte(f
);
3182 if (qemu_get_buffer(f
, buf
, len
) != len
)
3186 v
= qemu_get_byte(f
);
3187 memset(buf
, v
, len
);
3193 if (qemu_file_has_error(f
))
3199 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
3204 if (qemu_get_be32(f
) != last_ram_offset
)
3206 for(i
= 0; i
< last_ram_offset
; i
+= TARGET_PAGE_SIZE
) {
3207 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3209 ret
= ram_get_page(f
, qemu_get_ram_ptr(i
), TARGET_PAGE_SIZE
);
3216 #define BDRV_HASH_BLOCK_SIZE 1024
3217 #define IOBUF_SIZE 4096
3218 #define RAM_CBLOCK_MAGIC 0xfabe
3220 typedef struct RamDecompressState
{
3223 uint8_t buf
[IOBUF_SIZE
];
3224 } RamDecompressState
;
3226 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
3229 memset(s
, 0, sizeof(*s
));
3231 ret
= inflateInit(&s
->zstream
);
3237 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
3241 s
->zstream
.avail_out
= len
;
3242 s
->zstream
.next_out
= buf
;
3243 while (s
->zstream
.avail_out
> 0) {
3244 if (s
->zstream
.avail_in
== 0) {
3245 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
3247 clen
= qemu_get_be16(s
->f
);
3248 if (clen
> IOBUF_SIZE
)
3250 qemu_get_buffer(s
->f
, s
->buf
, clen
);
3251 s
->zstream
.avail_in
= clen
;
3252 s
->zstream
.next_in
= s
->buf
;
3254 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
3255 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
3262 static void ram_decompress_close(RamDecompressState
*s
)
3264 inflateEnd(&s
->zstream
);
3267 #define RAM_SAVE_FLAG_FULL 0x01
3268 #define RAM_SAVE_FLAG_COMPRESS 0x02
3269 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3270 #define RAM_SAVE_FLAG_PAGE 0x08
3271 #define RAM_SAVE_FLAG_EOS 0x10
3273 static int is_dup_page(uint8_t *page
, uint8_t ch
)
3275 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
3276 uint32_t *array
= (uint32_t *)page
;
3279 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
3280 if (array
[i
] != val
)
3287 static int ram_save_block(QEMUFile
*f
)
3289 static ram_addr_t current_addr
= 0;
3290 ram_addr_t saved_addr
= current_addr
;
3291 ram_addr_t addr
= 0;
3294 while (addr
< last_ram_offset
) {
3295 if (kvm_enabled() && current_addr
== 0) {
3297 r
= kvm_update_dirty_pages_log();
3299 fprintf(stderr
, "%s: update dirty pages log failed %d\n", __FUNCTION__
, r
);
3300 qemu_file_set_error(f
);
3304 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
3307 cpu_physical_memory_reset_dirty(current_addr
,
3308 current_addr
+ TARGET_PAGE_SIZE
,
3309 MIGRATION_DIRTY_FLAG
);
3311 p
= qemu_get_ram_ptr(current_addr
);
3313 if (is_dup_page(p
, *p
)) {
3314 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
3315 qemu_put_byte(f
, *p
);
3317 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
3318 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
3324 addr
+= TARGET_PAGE_SIZE
;
3325 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
3331 static ram_addr_t ram_save_threshold
= 10;
3333 static ram_addr_t
ram_save_remaining(void)
3336 ram_addr_t count
= 0;
3338 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3339 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3346 static int ram_save_live(QEMUFile
*f
, int stage
, void *opaque
)
3351 /* Make sure all dirty bits are set */
3352 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3353 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3354 cpu_physical_memory_set_dirty(addr
);
3357 /* Enable dirty memory tracking */
3358 cpu_physical_memory_set_dirty_tracking(1);
3360 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
3363 while (!qemu_file_rate_limit(f
)) {
3366 ret
= ram_save_block(f
);
3367 if (ret
== 0) /* no more blocks */
3371 /* try transferring iterative blocks of memory */
3375 /* flush all remaining blocks regardless of rate limiting */
3376 while (ram_save_block(f
) != 0);
3377 cpu_physical_memory_set_dirty_tracking(0);
3380 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3382 return (stage
== 2) && (ram_save_remaining() < ram_save_threshold
);
3385 static int ram_load_dead(QEMUFile
*f
, void *opaque
)
3387 RamDecompressState s1
, *s
= &s1
;
3391 if (ram_decompress_open(s
, f
) < 0)
3393 for(i
= 0; i
< last_ram_offset
; i
+= BDRV_HASH_BLOCK_SIZE
) {
3394 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3396 if (ram_decompress_buf(s
, buf
, 1) < 0) {
3397 fprintf(stderr
, "Error while reading ram block header\n");
3401 if (ram_decompress_buf(s
, qemu_get_ram_ptr(i
),
3402 BDRV_HASH_BLOCK_SIZE
) < 0) {
3403 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
3408 printf("Error block header\n");
3412 ram_decompress_close(s
);
3417 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
3422 if (version_id
== 1)
3423 return ram_load_v1(f
, opaque
);
3425 if (version_id
== 2) {
3426 if (qemu_get_be32(f
) != last_ram_offset
)
3428 return ram_load_dead(f
, opaque
);
3431 if (version_id
!= 3)
3435 addr
= qemu_get_be64(f
);
3437 flags
= addr
& ~TARGET_PAGE_MASK
;
3438 addr
&= TARGET_PAGE_MASK
;
3440 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
3441 if (addr
!= last_ram_offset
)
3445 if (flags
& RAM_SAVE_FLAG_FULL
) {
3446 if (ram_load_dead(f
, opaque
) < 0)
3450 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
3451 uint8_t ch
= qemu_get_byte(f
);
3452 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
3453 } else if (flags
& RAM_SAVE_FLAG_PAGE
)
3454 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
3455 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
3460 void qemu_service_io(void)
3462 CPUState
*env
= cpu_single_env
;
3466 if (env
->kqemu_enabled
) {
3467 kqemu_cpu_interrupt(env
);
3473 /***********************************************************/
3474 /* bottom halves (can be seen as timers which expire ASAP) */
3485 static QEMUBH
*first_bh
= NULL
;
3487 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
3490 bh
= qemu_mallocz(sizeof(QEMUBH
));
3492 bh
->opaque
= opaque
;
3493 bh
->next
= first_bh
;
3498 int qemu_bh_poll(void)
3504 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3505 if (!bh
->deleted
&& bh
->scheduled
) {
3514 /* remove deleted bhs */
3528 void qemu_bh_schedule_idle(QEMUBH
*bh
)
3536 void qemu_bh_schedule(QEMUBH
*bh
)
3538 CPUState
*env
= cpu_single_env
;
3543 /* stop the currently executing CPU to execute the BH ASAP */
3550 void qemu_bh_cancel(QEMUBH
*bh
)
3555 void qemu_bh_delete(QEMUBH
*bh
)
3561 static void qemu_bh_update_timeout(int *timeout
)
3565 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3566 if (!bh
->deleted
&& bh
->scheduled
) {
3568 /* idle bottom halves will be polled at least
3570 *timeout
= MIN(10, *timeout
);
3572 /* non-idle bottom halves will be executed
3581 /***********************************************************/
3582 /* machine registration */
3584 static QEMUMachine
*first_machine
= NULL
;
3585 QEMUMachine
*current_machine
= NULL
;
3587 int qemu_register_machine(QEMUMachine
*m
)
3590 pm
= &first_machine
;
3598 static QEMUMachine
*find_machine(const char *name
)
3602 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3603 if (!strcmp(m
->name
, name
))
3609 /***********************************************************/
3610 /* main execution loop */
3612 static void gui_update(void *opaque
)
3614 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3615 DisplayState
*ds
= opaque
;
3616 DisplayChangeListener
*dcl
= ds
->listeners
;
3620 while (dcl
!= NULL
) {
3621 if (dcl
->gui_timer_interval
&&
3622 dcl
->gui_timer_interval
< interval
)
3623 interval
= dcl
->gui_timer_interval
;
3626 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3629 static void nographic_update(void *opaque
)
3631 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3633 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3636 struct vm_change_state_entry
{
3637 VMChangeStateHandler
*cb
;
3639 LIST_ENTRY (vm_change_state_entry
) entries
;
3642 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3644 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3647 VMChangeStateEntry
*e
;
3649 e
= qemu_mallocz(sizeof (*e
));
3653 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3657 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3659 LIST_REMOVE (e
, entries
);
3663 static void vm_state_notify(int running
, int reason
)
3665 VMChangeStateEntry
*e
;
3667 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3668 e
->cb(e
->opaque
, running
, reason
);
3677 vm_state_notify(1, 0);
3679 qemu_kvm_resume_all_threads();
3680 qemu_rearm_alarm_timer(alarm_timer
);
3684 void vm_stop(int reason
)
3687 cpu_disable_ticks();
3690 qemu_kvm_pause_all_threads();
3691 vm_state_notify(0, reason
);
3695 /* reset/shutdown handler */
3697 typedef struct QEMUResetEntry
{
3698 QEMUResetHandler
*func
;
3700 struct QEMUResetEntry
*next
;
3703 static QEMUResetEntry
*first_reset_entry
;
3704 static int reset_requested
;
3705 static int shutdown_requested
;
3706 static int powerdown_requested
;
3708 int qemu_shutdown_requested(void)
3710 int r
= shutdown_requested
;
3711 shutdown_requested
= 0;
3715 int qemu_reset_requested(void)
3717 int r
= reset_requested
;
3718 reset_requested
= 0;
3722 int qemu_powerdown_requested(void)
3724 int r
= powerdown_requested
;
3725 powerdown_requested
= 0;
3729 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3731 QEMUResetEntry
**pre
, *re
;
3733 pre
= &first_reset_entry
;
3734 while (*pre
!= NULL
)
3735 pre
= &(*pre
)->next
;
3736 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3738 re
->opaque
= opaque
;
3743 void qemu_system_reset(void)
3747 /* reset all devices */
3748 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
3749 re
->func(re
->opaque
);
3755 void qemu_system_reset_request(void)
3758 shutdown_requested
= 1;
3760 reset_requested
= 1;
3762 if (cpu_single_env
) {
3763 qemu_kvm_cpu_stop(cpu_single_env
);
3764 cpu_exit(cpu_single_env
);
3768 void qemu_system_shutdown_request(void)
3770 shutdown_requested
= 1;
3772 cpu_exit(cpu_single_env
);
3775 void qemu_system_powerdown_request(void)
3777 powerdown_requested
= 1;
3779 cpu_exit(cpu_single_env
);
3782 static int qemu_select(int max_fd
, fd_set
*rfds
, fd_set
*wfds
, fd_set
*xfds
,
3787 /* KVM holds a mutex while QEMU code is running, we need hooks to
3788 release the mutex whenever QEMU code sleeps. */
3792 ret
= select(max_fd
, rfds
, wfds
, xfds
, tv
);
3800 static void host_main_loop_wait(int *timeout
)
3806 /* XXX: need to suppress polling by better using win32 events */
3808 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
3809 ret
|= pe
->func(pe
->opaque
);
3813 WaitObjects
*w
= &wait_objects
;
3815 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
3816 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
3817 if (w
->func
[ret
- WAIT_OBJECT_0
])
3818 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
3820 /* Check for additional signaled events */
3821 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
3823 /* Check if event is signaled */
3824 ret2
= WaitForSingleObject(w
->events
[i
], 0);
3825 if(ret2
== WAIT_OBJECT_0
) {
3827 w
->func
[i
](w
->opaque
[i
]);
3828 } else if (ret2
== WAIT_TIMEOUT
) {
3830 err
= GetLastError();
3831 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
3834 } else if (ret
== WAIT_TIMEOUT
) {
3836 err
= GetLastError();
3837 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
3844 static void host_main_loop_wait(int *timeout
)
3849 void main_loop_wait(int timeout
)
3851 IOHandlerRecord
*ioh
;
3852 fd_set rfds
, wfds
, xfds
;
3856 qemu_bh_update_timeout(&timeout
);
3858 host_main_loop_wait(&timeout
);
3860 /* poll any events */
3861 /* XXX: separate device handlers from system ones */
3866 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3870 (!ioh
->fd_read_poll
||
3871 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
3872 FD_SET(ioh
->fd
, &rfds
);
3876 if (ioh
->fd_write
) {
3877 FD_SET(ioh
->fd
, &wfds
);
3883 tv
.tv_sec
= timeout
/ 1000;
3884 tv
.tv_usec
= (timeout
% 1000) * 1000;
3886 #if defined(CONFIG_SLIRP)
3887 if (slirp_is_inited()) {
3888 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
3891 ret
= qemu_select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
3893 IOHandlerRecord
**pioh
;
3895 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3896 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
3897 ioh
->fd_read(ioh
->opaque
);
3898 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
3899 FD_CLR(ioh
->fd
, &rfds
);
3901 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
3902 ioh
->fd_write(ioh
->opaque
);
3906 /* remove deleted IO handlers */
3907 pioh
= &first_io_handler
;
3917 #if defined(CONFIG_SLIRP)
3918 if (slirp_is_inited()) {
3924 slirp_select_poll(&rfds
, &wfds
, &xfds
);
3928 /* vm time timers */
3929 if (vm_running
&& (!cur_cpu
3930 || likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
))))
3931 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
3932 qemu_get_clock(vm_clock
));
3934 /* real time timers */
3935 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
3936 qemu_get_clock(rt_clock
));
3938 /* Check bottom-halves last in case any of the earlier events triggered
3944 static int main_loop(void)
3947 #ifdef CONFIG_PROFILER
3953 if (kvm_enabled()) {
3955 cpu_disable_ticks();
3959 cur_cpu
= first_cpu
;
3960 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
3967 #ifdef CONFIG_PROFILER
3968 ti
= profile_getclock();
3973 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
3974 env
->icount_decr
.u16
.low
= 0;
3975 env
->icount_extra
= 0;
3976 count
= qemu_next_deadline();
3977 count
= (count
+ (1 << icount_time_shift
) - 1)
3978 >> icount_time_shift
;
3979 qemu_icount
+= count
;
3980 decr
= (count
> 0xffff) ? 0xffff : count
;
3982 env
->icount_decr
.u16
.low
= decr
;
3983 env
->icount_extra
= count
;
3985 ret
= cpu_exec(env
);
3986 #ifdef CONFIG_PROFILER
3987 qemu_time
+= profile_getclock() - ti
;
3990 /* Fold pending instructions back into the
3991 instruction counter, and clear the interrupt flag. */
3992 qemu_icount
-= (env
->icount_decr
.u16
.low
3993 + env
->icount_extra
);
3994 env
->icount_decr
.u32
= 0;
3995 env
->icount_extra
= 0;
3997 next_cpu
= env
->next_cpu
?: first_cpu
;
3998 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
3999 ret
= EXCP_INTERRUPT
;
4003 if (ret
== EXCP_HLT
) {
4004 /* Give the next CPU a chance to run. */
4008 if (ret
!= EXCP_HALTED
)
4010 /* all CPUs are halted ? */
4016 if (shutdown_requested
) {
4017 ret
= EXCP_INTERRUPT
;
4025 if (reset_requested
) {
4026 reset_requested
= 0;
4027 qemu_system_reset();
4028 ret
= EXCP_INTERRUPT
;
4030 if (powerdown_requested
) {
4031 powerdown_requested
= 0;
4032 qemu_system_powerdown();
4033 ret
= EXCP_INTERRUPT
;
4035 #ifdef CONFIG_GDBSTUB
4036 if (unlikely(ret
== EXCP_DEBUG
)) {
4037 gdb_set_stop_cpu(cur_cpu
);
4038 vm_stop(EXCP_DEBUG
);
4041 /* If all cpus are halted then wait until the next IRQ */
4042 /* XXX: use timeout computed from timers */
4043 if (ret
== EXCP_HALTED
) {
4047 /* Advance virtual time to the next event. */
4048 if (use_icount
== 1) {
4049 /* When not using an adaptive execution frequency
4050 we tend to get badly out of sync with real time,
4051 so just delay for a reasonable amount of time. */
4054 delta
= cpu_get_icount() - cpu_get_clock();
4057 /* If virtual time is ahead of real time then just
4059 timeout
= (delta
/ 1000000) + 1;
4061 /* Wait for either IO to occur or the next
4063 add
= qemu_next_deadline();
4064 /* We advance the timer before checking for IO.
4065 Limit the amount we advance so that early IO
4066 activity won't get the guest too far ahead. */
4070 add
= (add
+ (1 << icount_time_shift
) - 1)
4071 >> icount_time_shift
;
4073 timeout
= delta
/ 1000000;
4084 if (shutdown_requested
) {
4085 ret
= EXCP_INTERRUPT
;
4090 #ifdef CONFIG_PROFILER
4091 ti
= profile_getclock();
4093 main_loop_wait(timeout
);
4094 #ifdef CONFIG_PROFILER
4095 dev_time
+= profile_getclock() - ti
;
4098 cpu_disable_ticks();
4102 static void version(void)
4104 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4107 static void help(int exitcode
)
4110 printf("usage: %s [options] [disk_image]\n"
4112 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4114 #define DEF(option, opt_arg, opt_enum, opt_help) \
4116 #define DEFHEADING(text) stringify(text) "\n"
4117 #include "qemu-options.h"
4122 "During emulation, the following keys are useful:\n"
4123 "ctrl-alt-f toggle full screen\n"
4124 "ctrl-alt-n switch to virtual console 'n'\n"
4125 "ctrl-alt toggle mouse and keyboard grab\n"
4127 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4132 DEFAULT_NETWORK_SCRIPT
,
4133 DEFAULT_NETWORK_DOWN_SCRIPT
,
4135 DEFAULT_GDBSTUB_PORT
,
4140 #define HAS_ARG 0x0001
4143 #define DEF(option, opt_arg, opt_enum, opt_help) \
4145 #define DEFHEADING(text)
4146 #include "qemu-options.h"
4152 typedef struct QEMUOption
{
4158 static const QEMUOption qemu_options
[] = {
4159 { "h", 0, QEMU_OPTION_h
},
4160 #define DEF(option, opt_arg, opt_enum, opt_help) \
4161 { option, opt_arg, opt_enum },
4162 #define DEFHEADING(text)
4163 #include "qemu-options.h"
4171 struct soundhw soundhw
[] = {
4172 #ifdef HAS_AUDIO_CHOICE
4173 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4179 { .init_isa
= pcspk_audio_init
}
4186 "Creative Sound Blaster 16",
4189 { .init_isa
= SB16_init
}
4193 #ifdef CONFIG_CS4231A
4199 { .init_isa
= cs4231a_init
}
4207 "Yamaha YMF262 (OPL3)",
4209 "Yamaha YM3812 (OPL2)",
4213 { .init_isa
= Adlib_init
}
4220 "Gravis Ultrasound GF1",
4223 { .init_isa
= GUS_init
}
4230 "Intel 82801AA AC97 Audio",
4233 { .init_pci
= ac97_init
}
4237 #ifdef CONFIG_ES1370
4240 "ENSONIQ AudioPCI ES1370",
4243 { .init_pci
= es1370_init
}
4247 #endif /* HAS_AUDIO_CHOICE */
4249 { NULL
, NULL
, 0, 0, { NULL
} }
4252 static void select_soundhw (const char *optarg
)
4256 if (*optarg
== '?') {
4259 printf ("Valid sound card names (comma separated):\n");
4260 for (c
= soundhw
; c
->name
; ++c
) {
4261 printf ("%-11s %s\n", c
->name
, c
->descr
);
4263 printf ("\n-soundhw all will enable all of the above\n");
4264 exit (*optarg
!= '?');
4272 if (!strcmp (optarg
, "all")) {
4273 for (c
= soundhw
; c
->name
; ++c
) {
4281 e
= strchr (p
, ',');
4282 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4284 for (c
= soundhw
; c
->name
; ++c
) {
4285 if (!strncmp (c
->name
, p
, l
)) {
4294 "Unknown sound card name (too big to show)\n");
4297 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4302 p
+= l
+ (e
!= NULL
);
4306 goto show_valid_cards
;
4311 static void select_vgahw (const char *p
)
4315 cirrus_vga_enabled
= 0;
4316 std_vga_enabled
= 0;
4319 if (strstart(p
, "std", &opts
)) {
4320 std_vga_enabled
= 1;
4321 } else if (strstart(p
, "cirrus", &opts
)) {
4322 cirrus_vga_enabled
= 1;
4323 } else if (strstart(p
, "vmware", &opts
)) {
4325 } else if (strstart(p
, "xenfb", &opts
)) {
4327 } else if (!strstart(p
, "none", &opts
)) {
4329 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4333 const char *nextopt
;
4335 if (strstart(opts
, ",retrace=", &nextopt
)) {
4337 if (strstart(opts
, "dumb", &nextopt
))
4338 vga_retrace_method
= VGA_RETRACE_DUMB
;
4339 else if (strstart(opts
, "precise", &nextopt
))
4340 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4341 else goto invalid_vga
;
4342 } else goto invalid_vga
;
4348 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4350 exit(STATUS_CONTROL_C_EXIT
);
4355 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4359 if(strlen(str
) != 36)
4362 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4363 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4364 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4370 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4376 #define MAX_NET_CLIENTS 32
4380 #define HUGETLBFS_MAGIC 0x958458f6
4382 static long gethugepagesize(const char *path
)
4388 ret
= statfs(path
, &fs
);
4389 } while (ret
!= 0 && errno
== EINTR
);
4396 if (fs
.f_type
!= HUGETLBFS_MAGIC
)
4397 fprintf(stderr
, "Warning: path not on HugeTLBFS: %s\n", path
);
4402 static void *alloc_mem_area(size_t memory
, unsigned long *len
, const char *path
)
4411 if (!kvm_has_sync_mmu()) {
4412 fprintf(stderr
, "host lacks mmu notifiers, disabling --mem-path\n");
4416 if (asprintf(&filename
, "%s/kvm.XXXXXX", path
) == -1)
4419 hpagesize
= gethugepagesize(path
);
4423 fd
= mkstemp(filename
);
4432 memory
= (memory
+hpagesize
-1) & ~(hpagesize
-1);
4435 * ftruncate is not supported by hugetlbfs in older
4436 * hosts, so don't bother checking for errors.
4437 * If anything goes wrong with it under other filesystems,
4440 ftruncate(fd
, memory
);
4443 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4444 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4445 * to sidestep this quirk.
4447 flags
= mem_prealloc
? MAP_POPULATE
|MAP_SHARED
: MAP_PRIVATE
;
4448 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, flags
, fd
, 0);
4450 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
, fd
, 0);
4452 if (area
== MAP_FAILED
) {
4453 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4462 static void *qemu_alloc_physram(unsigned long memory
)
4466 unsigned long map_len
= memory
;
4469 area
= alloc_mem_area(memory
, &map_len
, mem_path
);
4472 area
= qemu_vmalloc(memory
);
4474 if (kvm_setup_guest_memory(area
, map_len
))
4482 static void termsig_handler(int signal
)
4484 qemu_system_shutdown_request();
4487 static void termsig_setup(void)
4489 struct sigaction act
;
4491 memset(&act
, 0, sizeof(act
));
4492 act
.sa_handler
= termsig_handler
;
4493 sigaction(SIGINT
, &act
, NULL
);
4494 sigaction(SIGHUP
, &act
, NULL
);
4495 sigaction(SIGTERM
, &act
, NULL
);
4500 int main(int argc
, char **argv
, char **envp
)
4502 #ifdef CONFIG_GDBSTUB
4503 const char *gdbstub_dev
= NULL
;
4505 uint32_t boot_devices_bitmap
= 0;
4507 int snapshot
, linux_boot
, net_boot
;
4508 const char *initrd_filename
;
4509 const char *kernel_filename
, *kernel_cmdline
;
4510 const char *boot_devices
= "";
4512 DisplayChangeListener
*dcl
;
4513 int cyls
, heads
, secs
, translation
;
4514 const char *net_clients
[MAX_NET_CLIENTS
];
4516 const char *bt_opts
[MAX_BT_CMDLINE
];
4520 const char *r
, *optarg
;
4521 CharDriverState
*monitor_hd
= NULL
;
4522 const char *monitor_device
;
4523 const char *serial_devices
[MAX_SERIAL_PORTS
];
4524 int serial_device_index
;
4525 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
4526 int parallel_device_index
;
4527 const char *virtio_consoles
[MAX_VIRTIO_CONSOLES
];
4528 int virtio_console_index
;
4529 const char *loadvm
= NULL
;
4530 QEMUMachine
*machine
;
4531 const char *cpu_model
;
4532 const char *usb_devices
[MAX_USB_CMDLINE
];
4533 int usb_devices_index
;
4538 const char *pid_file
= NULL
;
4539 const char *incoming
= NULL
;
4542 struct passwd
*pwd
= NULL
;
4543 const char *chroot_dir
= NULL
;
4544 const char *run_as
= NULL
;
4548 qemu_cache_utils_init(envp
);
4550 LIST_INIT (&vm_change_state_head
);
4553 struct sigaction act
;
4554 sigfillset(&act
.sa_mask
);
4556 act
.sa_handler
= SIG_IGN
;
4557 sigaction(SIGPIPE
, &act
, NULL
);
4560 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4561 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4562 QEMU to run on a single CPU */
4567 h
= GetCurrentProcess();
4568 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4569 for(i
= 0; i
< 32; i
++) {
4570 if (mask
& (1 << i
))
4575 SetProcessAffinityMask(h
, mask
);
4581 register_machines();
4582 machine
= first_machine
;
4584 initrd_filename
= NULL
;
4586 vga_ram_size
= VGA_RAM_SIZE
;
4590 kernel_filename
= NULL
;
4591 kernel_cmdline
= "";
4592 cyls
= heads
= secs
= 0;
4593 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4594 monitor_device
= "vc:80Cx24C";
4596 serial_devices
[0] = "vc:80Cx24C";
4597 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
4598 serial_devices
[i
] = NULL
;
4599 serial_device_index
= 0;
4601 parallel_devices
[0] = "vc:80Cx24C";
4602 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
4603 parallel_devices
[i
] = NULL
;
4604 parallel_device_index
= 0;
4606 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++)
4607 virtio_consoles
[i
] = NULL
;
4608 virtio_console_index
= 0;
4610 for (i
= 0; i
< MAX_NODES
; i
++) {
4612 node_cpumask
[i
] = 0;
4615 usb_devices_index
= 0;
4616 assigned_devices_index
= 0;
4636 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
4638 const QEMUOption
*popt
;
4641 /* Treat --foo the same as -foo. */
4644 popt
= qemu_options
;
4647 fprintf(stderr
, "%s: invalid option -- '%s'\n",
4651 if (!strcmp(popt
->name
, r
+ 1))
4655 if (popt
->flags
& HAS_ARG
) {
4656 if (optind
>= argc
) {
4657 fprintf(stderr
, "%s: option '%s' requires an argument\n",
4661 optarg
= argv
[optind
++];
4666 switch(popt
->index
) {
4668 machine
= find_machine(optarg
);
4671 printf("Supported machines are:\n");
4672 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
4673 printf("%-10s %s%s\n",
4675 m
== first_machine
? " (default)" : "");
4677 exit(*optarg
!= '?');
4680 case QEMU_OPTION_cpu
:
4681 /* hw initialization will check this */
4682 if (*optarg
== '?') {
4683 /* XXX: implement xxx_cpu_list for targets that still miss it */
4684 #if defined(cpu_list)
4685 cpu_list(stdout
, &fprintf
);
4692 case QEMU_OPTION_initrd
:
4693 initrd_filename
= optarg
;
4695 case QEMU_OPTION_hda
:
4697 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
4699 hda_index
= drive_add(optarg
, HD_ALIAS
4700 ",cyls=%d,heads=%d,secs=%d%s",
4701 0, cyls
, heads
, secs
,
4702 translation
== BIOS_ATA_TRANSLATION_LBA
?
4704 translation
== BIOS_ATA_TRANSLATION_NONE
?
4705 ",trans=none" : "");
4707 case QEMU_OPTION_hdb
:
4708 case QEMU_OPTION_hdc
:
4709 case QEMU_OPTION_hdd
:
4710 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
4712 case QEMU_OPTION_drive
:
4713 drive_add(NULL
, "%s", optarg
);
4715 case QEMU_OPTION_mtdblock
:
4716 drive_add(optarg
, MTD_ALIAS
);
4718 case QEMU_OPTION_sd
:
4719 drive_add(optarg
, SD_ALIAS
);
4721 case QEMU_OPTION_pflash
:
4722 drive_add(optarg
, PFLASH_ALIAS
);
4724 case QEMU_OPTION_snapshot
:
4727 case QEMU_OPTION_hdachs
:
4731 cyls
= strtol(p
, (char **)&p
, 0);
4732 if (cyls
< 1 || cyls
> 16383)
4737 heads
= strtol(p
, (char **)&p
, 0);
4738 if (heads
< 1 || heads
> 16)
4743 secs
= strtol(p
, (char **)&p
, 0);
4744 if (secs
< 1 || secs
> 63)
4748 if (!strcmp(p
, "none"))
4749 translation
= BIOS_ATA_TRANSLATION_NONE
;
4750 else if (!strcmp(p
, "lba"))
4751 translation
= BIOS_ATA_TRANSLATION_LBA
;
4752 else if (!strcmp(p
, "auto"))
4753 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4756 } else if (*p
!= '\0') {
4758 fprintf(stderr
, "qemu: invalid physical CHS format\n");
4761 if (hda_index
!= -1)
4762 snprintf(drives_opt
[hda_index
].opt
,
4763 sizeof(drives_opt
[hda_index
].opt
),
4764 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
4765 0, cyls
, heads
, secs
,
4766 translation
== BIOS_ATA_TRANSLATION_LBA
?
4768 translation
== BIOS_ATA_TRANSLATION_NONE
?
4769 ",trans=none" : "");
4772 case QEMU_OPTION_numa
:
4773 if (nb_numa_nodes
>= MAX_NODES
) {
4774 fprintf(stderr
, "qemu: too many NUMA nodes\n");
4779 case QEMU_OPTION_nographic
:
4782 #ifdef CONFIG_CURSES
4783 case QEMU_OPTION_curses
:
4787 case QEMU_OPTION_portrait
:
4790 case QEMU_OPTION_kernel
:
4791 kernel_filename
= optarg
;
4793 case QEMU_OPTION_append
:
4794 kernel_cmdline
= optarg
;
4796 case QEMU_OPTION_cdrom
:
4797 drive_add(optarg
, CDROM_ALIAS
);
4799 case QEMU_OPTION_boot
:
4800 boot_devices
= optarg
;
4801 /* We just do some generic consistency checks */
4803 /* Could easily be extended to 64 devices if needed */
4806 boot_devices_bitmap
= 0;
4807 for (p
= boot_devices
; *p
!= '\0'; p
++) {
4808 /* Allowed boot devices are:
4809 * a b : floppy disk drives
4810 * c ... f : IDE disk drives
4811 * g ... m : machine implementation dependant drives
4812 * n ... p : network devices
4813 * It's up to each machine implementation to check
4814 * if the given boot devices match the actual hardware
4815 * implementation and firmware features.
4817 if (*p
< 'a' || *p
> 'q') {
4818 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
4821 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
4823 "Boot device '%c' was given twice\n",*p
);
4826 boot_devices_bitmap
|= 1 << (*p
- 'a');
4830 case QEMU_OPTION_fda
:
4831 case QEMU_OPTION_fdb
:
4832 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
4835 case QEMU_OPTION_no_fd_bootchk
:
4839 case QEMU_OPTION_net
:
4840 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
4841 fprintf(stderr
, "qemu: too many network clients\n");
4844 net_clients
[nb_net_clients
] = optarg
;
4848 case QEMU_OPTION_tftp
:
4849 tftp_prefix
= optarg
;
4851 case QEMU_OPTION_bootp
:
4852 bootp_filename
= optarg
;
4855 case QEMU_OPTION_smb
:
4856 net_slirp_smb(optarg
);
4859 case QEMU_OPTION_redir
:
4860 net_slirp_redir(NULL
, optarg
);
4863 case QEMU_OPTION_bt
:
4864 if (nb_bt_opts
>= MAX_BT_CMDLINE
) {
4865 fprintf(stderr
, "qemu: too many bluetooth options\n");
4868 bt_opts
[nb_bt_opts
++] = optarg
;
4871 case QEMU_OPTION_audio_help
:
4875 case QEMU_OPTION_soundhw
:
4876 select_soundhw (optarg
);
4882 case QEMU_OPTION_version
:
4886 case QEMU_OPTION_m
: {
4890 value
= strtoul(optarg
, &ptr
, 10);
4892 case 0: case 'M': case 'm':
4899 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
4903 /* On 32-bit hosts, QEMU is limited by virtual address space */
4904 if (value
> (2047 << 20)
4905 #ifndef CONFIG_KQEMU
4906 && HOST_LONG_BITS
== 32
4909 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
4912 if (value
!= (uint64_t)(ram_addr_t
)value
) {
4913 fprintf(stderr
, "qemu: ram size too large\n");
4922 const CPULogItem
*item
;
4924 mask
= cpu_str_to_log_mask(optarg
);
4926 printf("Log items (comma separated):\n");
4927 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
4928 printf("%-10s %s\n", item
->name
, item
->help
);
4935 #ifdef CONFIG_GDBSTUB
4937 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
4939 case QEMU_OPTION_gdb
:
4940 gdbstub_dev
= optarg
;
4946 case QEMU_OPTION_bios
:
4949 case QEMU_OPTION_singlestep
:
4957 keyboard_layout
= optarg
;
4960 case QEMU_OPTION_localtime
:
4963 case QEMU_OPTION_vga
:
4964 select_vgahw (optarg
);
4966 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4972 w
= strtol(p
, (char **)&p
, 10);
4975 fprintf(stderr
, "qemu: invalid resolution or depth\n");
4981 h
= strtol(p
, (char **)&p
, 10);
4986 depth
= strtol(p
, (char **)&p
, 10);
4987 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
4988 depth
!= 24 && depth
!= 32)
4990 } else if (*p
== '\0') {
4991 depth
= graphic_depth
;
4998 graphic_depth
= depth
;
5002 case QEMU_OPTION_echr
:
5005 term_escape_char
= strtol(optarg
, &r
, 0);
5007 printf("Bad argument to echr\n");
5010 case QEMU_OPTION_monitor
:
5011 monitor_device
= optarg
;
5013 case QEMU_OPTION_serial
:
5014 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
5015 fprintf(stderr
, "qemu: too many serial ports\n");
5018 serial_devices
[serial_device_index
] = optarg
;
5019 serial_device_index
++;
5021 case QEMU_OPTION_virtiocon
:
5022 if (virtio_console_index
>= MAX_VIRTIO_CONSOLES
) {
5023 fprintf(stderr
, "qemu: too many virtio consoles\n");
5026 virtio_consoles
[virtio_console_index
] = optarg
;
5027 virtio_console_index
++;
5029 case QEMU_OPTION_parallel
:
5030 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
5031 fprintf(stderr
, "qemu: too many parallel ports\n");
5034 parallel_devices
[parallel_device_index
] = optarg
;
5035 parallel_device_index
++;
5037 case QEMU_OPTION_loadvm
:
5040 case QEMU_OPTION_full_screen
:
5044 case QEMU_OPTION_no_frame
:
5047 case QEMU_OPTION_alt_grab
:
5050 case QEMU_OPTION_no_quit
:
5053 case QEMU_OPTION_sdl
:
5057 case QEMU_OPTION_pidfile
:
5061 case QEMU_OPTION_win2k_hack
:
5062 win2k_install_hack
= 1;
5064 case QEMU_OPTION_rtc_td_hack
:
5067 case QEMU_OPTION_acpitable
:
5068 if(acpi_table_add(optarg
) < 0) {
5069 fprintf(stderr
, "Wrong acpi table provided\n");
5073 case QEMU_OPTION_smbios
:
5074 if(smbios_entry_add(optarg
) < 0) {
5075 fprintf(stderr
, "Wrong smbios provided\n");
5081 case QEMU_OPTION_no_kqemu
:
5084 case QEMU_OPTION_kernel_kqemu
:
5089 case QEMU_OPTION_enable_kvm
:
5097 case QEMU_OPTION_no_kvm
:
5100 case QEMU_OPTION_no_kvm_irqchip
: {
5105 case QEMU_OPTION_no_kvm_pit
: {
5109 case QEMU_OPTION_no_kvm_pit_reinjection
: {
5110 kvm_pit_reinject
= 0;
5113 case QEMU_OPTION_enable_nesting
: {
5117 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5118 case QEMU_OPTION_pcidevice
:
5119 if (assigned_devices_index
>= MAX_DEV_ASSIGN_CMDLINE
) {
5120 fprintf(stderr
, "Too many assigned devices\n");
5123 assigned_devices
[assigned_devices_index
] = optarg
;
5124 assigned_devices_index
++;
5128 case QEMU_OPTION_usb
:
5131 case QEMU_OPTION_usbdevice
:
5133 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
5134 fprintf(stderr
, "Too many USB devices\n");
5137 usb_devices
[usb_devices_index
] = optarg
;
5138 usb_devices_index
++;
5140 case QEMU_OPTION_smp
:
5141 smp_cpus
= atoi(optarg
);
5143 fprintf(stderr
, "Invalid number of CPUs\n");
5147 case QEMU_OPTION_vnc
:
5148 vnc_display
= optarg
;
5151 case QEMU_OPTION_no_acpi
:
5154 case QEMU_OPTION_no_hpet
:
5158 case QEMU_OPTION_no_reboot
:
5161 case QEMU_OPTION_no_shutdown
:
5164 case QEMU_OPTION_show_cursor
:
5167 case QEMU_OPTION_uuid
:
5168 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5169 fprintf(stderr
, "Fail to parse UUID string."
5170 " Wrong format.\n");
5175 case QEMU_OPTION_daemonize
:
5179 case QEMU_OPTION_option_rom
:
5180 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5181 fprintf(stderr
, "Too many option ROMs\n");
5184 option_rom
[nb_option_roms
] = optarg
;
5187 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5188 case QEMU_OPTION_semihosting
:
5189 semihosting_enabled
= 1;
5192 case QEMU_OPTION_tdf
:
5195 case QEMU_OPTION_kvm_shadow_memory
:
5196 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
5198 case QEMU_OPTION_mempath
:
5202 case QEMU_OPTION_mem_prealloc
:
5203 mem_prealloc
= !mem_prealloc
;
5206 case QEMU_OPTION_name
:
5209 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5210 case QEMU_OPTION_prom_env
:
5211 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5212 fprintf(stderr
, "Too many prom variables\n");
5215 prom_envs
[nb_prom_envs
] = optarg
;
5219 case QEMU_OPTION_cpu_vendor
:
5220 cpu_vendor_string
= optarg
;
5223 case QEMU_OPTION_old_param
:
5227 case QEMU_OPTION_clock
:
5228 configure_alarms(optarg
);
5230 case QEMU_OPTION_startdate
:
5233 time_t rtc_start_date
;
5234 if (!strcmp(optarg
, "now")) {
5235 rtc_date_offset
= -1;
5237 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
5245 } else if (sscanf(optarg
, "%d-%d-%d",
5248 &tm
.tm_mday
) == 3) {
5257 rtc_start_date
= mktimegm(&tm
);
5258 if (rtc_start_date
== -1) {
5260 fprintf(stderr
, "Invalid date format. Valid format are:\n"
5261 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5264 rtc_date_offset
= time(NULL
) - rtc_start_date
;
5268 case QEMU_OPTION_tb_size
:
5269 tb_size
= strtol(optarg
, NULL
, 0);
5273 case QEMU_OPTION_icount
:
5275 if (strcmp(optarg
, "auto") == 0) {
5276 icount_time_shift
= -1;
5278 icount_time_shift
= strtol(optarg
, NULL
, 0);
5281 case QEMU_OPTION_incoming
:
5285 case QEMU_OPTION_chroot
:
5286 chroot_dir
= optarg
;
5288 case QEMU_OPTION_runas
:
5291 case QEMU_OPTION_nvram
:
5296 case QEMU_OPTION_xen_domid
:
5297 xen_domid
= atoi(optarg
);
5299 case QEMU_OPTION_xen_create
:
5300 xen_mode
= XEN_CREATE
;
5302 case QEMU_OPTION_xen_attach
:
5303 xen_mode
= XEN_ATTACH
;
5310 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5311 if (kvm_allowed
&& kqemu_allowed
) {
5313 "You can not enable both KVM and kqemu at the same time\n");
5318 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5319 if (smp_cpus
> machine
->max_cpus
) {
5320 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5321 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5327 if (serial_device_index
== 0)
5328 serial_devices
[0] = "stdio";
5329 if (parallel_device_index
== 0)
5330 parallel_devices
[0] = "null";
5331 if (strncmp(monitor_device
, "vc", 2) == 0)
5332 monitor_device
= "stdio";
5339 if (pipe(fds
) == -1)
5350 len
= read(fds
[0], &status
, 1);
5351 if (len
== -1 && (errno
== EINTR
))
5356 else if (status
== 1) {
5357 fprintf(stderr
, "Could not acquire pidfile\n");
5374 signal(SIGTSTP
, SIG_IGN
);
5375 signal(SIGTTOU
, SIG_IGN
);
5376 signal(SIGTTIN
, SIG_IGN
);
5380 if (kvm_enabled()) {
5381 if (kvm_qemu_init() < 0) {
5382 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
5383 #ifdef NO_CPU_EMULATION
5384 fprintf(stderr
, "Compiled with --disable-cpu-emulation, exiting.\n");
5392 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5395 write(fds
[1], &status
, 1);
5397 fprintf(stderr
, "Could not acquire pid file\n");
5406 linux_boot
= (kernel_filename
!= NULL
);
5407 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5409 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5410 fprintf(stderr
, "-append only allowed with -kernel option\n");
5414 if (!linux_boot
&& initrd_filename
!= NULL
) {
5415 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5419 /* boot to floppy or the default cd if no hard disk defined yet */
5420 if (!boot_devices
[0]) {
5421 boot_devices
= "cad";
5423 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5426 if (init_timer_alarm() < 0) {
5427 fprintf(stderr
, "could not initialize alarm timer\n");
5430 if (use_icount
&& icount_time_shift
< 0) {
5432 /* 125MIPS seems a reasonable initial guess at the guest speed.
5433 It will be corrected fairly quickly anyway. */
5434 icount_time_shift
= 3;
5435 init_icount_adjust();
5442 /* init network clients */
5443 if (nb_net_clients
== 0) {
5444 /* if no clients, we use a default config */
5445 net_clients
[nb_net_clients
++] = "nic";
5447 net_clients
[nb_net_clients
++] = "user";
5451 for(i
= 0;i
< nb_net_clients
; i
++) {
5452 if (net_client_parse(net_clients
[i
]) < 0)
5458 /* XXX: this should be moved in the PC machine instantiation code */
5459 if (net_boot
!= 0) {
5461 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
5462 const char *model
= nd_table
[i
].model
;
5464 if (net_boot
& (1 << i
)) {
5467 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
5468 if (get_image_size(buf
) > 0) {
5469 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5470 fprintf(stderr
, "Too many option ROMs\n");
5473 option_rom
[nb_option_roms
] = strdup(buf
);
5480 fprintf(stderr
, "No valid PXE rom found for network device\n");
5486 /* init the bluetooth world */
5487 for (i
= 0; i
< nb_bt_opts
; i
++)
5488 if (bt_parse(bt_opts
[i
]))
5491 /* init the memory */
5493 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5495 if (kvm_enabled()) {
5496 if (kvm_qemu_create_context() < 0) {
5497 fprintf(stderr
, "Could not create KVM context\n");
5503 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5504 guest ram allocation. It needs to go away. */
5505 if (kqemu_allowed
) {
5506 kqemu_phys_ram_size
= ram_size
+ VGA_RAM_SIZE
+ 4 * 1024 * 1024;
5507 kqemu_phys_ram_base
= qemu_vmalloc(kqemu_phys_ram_size
);
5508 if (!kqemu_phys_ram_base
) {
5509 fprintf(stderr
, "Could not allocate physical memory\n");
5515 /* init the dynamic translator */
5516 cpu_exec_init_all(tb_size
* 1024 * 1024);
5521 /* we always create the cdrom drive, even if no disk is there */
5523 if (nb_drives_opt
< MAX_DRIVES
)
5524 drive_add(NULL
, CDROM_ALIAS
);
5526 /* we always create at least one floppy */
5528 if (nb_drives_opt
< MAX_DRIVES
)
5529 drive_add(NULL
, FD_ALIAS
, 0);
5531 /* we always create one sd slot, even if no card is in it */
5533 if (nb_drives_opt
< MAX_DRIVES
)
5534 drive_add(NULL
, SD_ALIAS
);
5536 /* open the virtual block devices
5537 * note that migration with device
5538 * hot add/remove is broken.
5540 for(i
= 0; i
< nb_drives_opt
; i
++)
5541 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
5544 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
5545 register_savevm_live("ram", 0, 3, ram_save_live
, NULL
, ram_load
, NULL
);
5548 /* must be after terminal init, SDL library changes signal handlers */
5552 /* Maintain compatibility with multiple stdio monitors */
5553 if (!strcmp(monitor_device
,"stdio")) {
5554 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5555 const char *devname
= serial_devices
[i
];
5556 if (devname
&& !strcmp(devname
,"mon:stdio")) {
5557 monitor_device
= NULL
;
5559 } else if (devname
&& !strcmp(devname
,"stdio")) {
5560 monitor_device
= NULL
;
5561 serial_devices
[i
] = "mon:stdio";
5567 if (nb_numa_nodes
> 0) {
5570 if (nb_numa_nodes
> smp_cpus
) {
5571 nb_numa_nodes
= smp_cpus
;
5574 /* If no memory size if given for any node, assume the default case
5575 * and distribute the available memory equally across all nodes
5577 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5578 if (node_mem
[i
] != 0)
5581 if (i
== nb_numa_nodes
) {
5582 uint64_t usedmem
= 0;
5584 /* On Linux, the each node's border has to be 8MB aligned,
5585 * the final node gets the rest.
5587 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
5588 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
5589 usedmem
+= node_mem
[i
];
5591 node_mem
[i
] = ram_size
- usedmem
;
5594 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5595 if (node_cpumask
[i
] != 0)
5598 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5599 * must cope with this anyway, because there are BIOSes out there in
5600 * real machines which also use this scheme.
5602 if (i
== nb_numa_nodes
) {
5603 for (i
= 0; i
< smp_cpus
; i
++) {
5604 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
5610 if (kvm_enabled()) {
5613 ret
= kvm_init(smp_cpus
);
5615 fprintf(stderr
, "failed to initialize KVM\n");
5621 if (monitor_device
) {
5622 monitor_hd
= qemu_chr_open("monitor", monitor_device
, NULL
);
5624 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
5629 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5630 const char *devname
= serial_devices
[i
];
5631 if (devname
&& strcmp(devname
, "none")) {
5633 snprintf(label
, sizeof(label
), "serial%d", i
);
5634 serial_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5635 if (!serial_hds
[i
]) {
5636 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
5643 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
5644 const char *devname
= parallel_devices
[i
];
5645 if (devname
&& strcmp(devname
, "none")) {
5647 snprintf(label
, sizeof(label
), "parallel%d", i
);
5648 parallel_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5649 if (!parallel_hds
[i
]) {
5650 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
5657 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
5658 const char *devname
= virtio_consoles
[i
];
5659 if (devname
&& strcmp(devname
, "none")) {
5661 snprintf(label
, sizeof(label
), "virtcon%d", i
);
5662 virtcon_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5663 if (!virtcon_hds
[i
]) {
5664 fprintf(stderr
, "qemu: could not open virtio console '%s'\n",
5674 machine
->init(ram_size
, vga_ram_size
, boot_devices
,
5675 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
5678 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
5679 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5680 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
5686 current_machine
= machine
;
5688 /* Set KVM's vcpu state to qemu's initial CPUState. */
5689 if (kvm_enabled()) {
5692 ret
= kvm_sync_vcpus();
5694 fprintf(stderr
, "failed to initialize vcpus\n");
5699 /* init USB devices */
5701 for(i
= 0; i
< usb_devices_index
; i
++) {
5702 if (usb_device_add(usb_devices
[i
], 0) < 0) {
5703 fprintf(stderr
, "Warning: could not add USB device %s\n",
5710 dumb_display_init();
5711 /* just use the first displaystate for the moment */
5716 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
5720 #if defined(CONFIG_CURSES)
5722 /* At the moment curses cannot be used with other displays */
5723 curses_display_init(ds
, full_screen
);
5727 if (vnc_display
!= NULL
) {
5728 vnc_display_init(ds
);
5729 if (vnc_display_open(ds
, vnc_display
) < 0)
5732 #if defined(CONFIG_SDL)
5733 if (sdl
|| !vnc_display
)
5734 sdl_display_init(ds
, full_screen
, no_frame
);
5735 #elif defined(CONFIG_COCOA)
5736 if (sdl
|| !vnc_display
)
5737 cocoa_display_init(ds
, full_screen
);
5743 dcl
= ds
->listeners
;
5744 while (dcl
!= NULL
) {
5745 if (dcl
->dpy_refresh
!= NULL
) {
5746 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
5747 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
5752 if (nographic
|| (vnc_display
&& !sdl
)) {
5753 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
5754 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
5757 text_consoles_set_display(display_state
);
5758 qemu_chr_initial_reset();
5760 if (monitor_device
&& monitor_hd
)
5761 monitor_init(monitor_hd
, MONITOR_USE_READLINE
| MONITOR_IS_DEFAULT
);
5763 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5764 const char *devname
= serial_devices
[i
];
5765 if (devname
&& strcmp(devname
, "none")) {
5767 snprintf(label
, sizeof(label
), "serial%d", i
);
5768 if (strstart(devname
, "vc", 0))
5769 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
5773 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
5774 const char *devname
= parallel_devices
[i
];
5775 if (devname
&& strcmp(devname
, "none")) {
5777 snprintf(label
, sizeof(label
), "parallel%d", i
);
5778 if (strstart(devname
, "vc", 0))
5779 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
5783 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
5784 const char *devname
= virtio_consoles
[i
];
5785 if (virtcon_hds
[i
] && devname
) {
5787 snprintf(label
, sizeof(label
), "virtcon%d", i
);
5788 if (strstart(devname
, "vc", 0))
5789 qemu_chr_printf(virtcon_hds
[i
], "virtio console%d\r\n", i
);
5793 #ifdef CONFIG_GDBSTUB
5794 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
5795 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
5802 do_loadvm(cur_mon
, loadvm
);
5805 autostart
= 0; /* fixme how to deal with -daemonize */
5806 qemu_start_incoming_migration(incoming
);
5818 len
= write(fds
[1], &status
, 1);
5819 if (len
== -1 && (errno
== EINTR
))
5826 TFR(fd
= open("/dev/null", O_RDWR
));
5832 pwd
= getpwnam(run_as
);
5834 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
5840 if (chroot(chroot_dir
) < 0) {
5841 fprintf(stderr
, "chroot failed\n");
5848 if (setgid(pwd
->pw_gid
) < 0) {
5849 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
5852 if (setuid(pwd
->pw_uid
) < 0) {
5853 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
5856 if (setuid(0) != -1) {
5857 fprintf(stderr
, "Dropping privileges failed\n");