4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
33 /* Needed early for HOST_BSD etc. */
34 #include "config-host.h"
38 #include <sys/times.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
46 #include <netinet/in.h>
48 #if defined(__NetBSD__)
49 #include <net/if_tap.h>
52 #include <linux/if_tun.h>
54 #include <arpa/inet.h>
57 #include <sys/select.h>
60 #if defined(__FreeBSD__) || defined(__DragonFly__)
65 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
66 #include <freebsd/stdlib.h>
71 #include <linux/rtc.h>
73 /* For the benefit of older linux systems which don't supply it,
74 we use a local copy of hpet.h. */
75 /* #include <linux/hpet.h> */
78 #include <linux/ppdev.h>
79 #include <linux/parport.h>
83 #include <sys/ethernet.h>
84 #include <sys/sockio.h>
85 #include <netinet/arp.h>
86 #include <netinet/in.h>
87 #include <netinet/in_systm.h>
88 #include <netinet/ip.h>
89 #include <netinet/ip_icmp.h> // must come after ip.h
90 #include <netinet/udp.h>
91 #include <netinet/tcp.h>
99 #if defined(__OpenBSD__)
103 #if defined(CONFIG_VDE)
104 #include <libvdeplug.h>
110 #include <sys/timeb.h>
111 #include <mmsystem.h>
112 #define getopt_long_only getopt_long
113 #define memalign(align, size) malloc(size)
119 int qemu_main(int argc
, char **argv
, char **envp
);
120 int main(int argc
, char **argv
)
122 qemu_main(argc
, argv
, NULL
);
125 #define main qemu_main
127 #endif /* CONFIG_SDL */
131 #define main qemu_main
132 #endif /* CONFIG_COCOA */
135 #include "hw/boards.h"
137 #include "hw/pcmcia.h"
139 #include "hw/audiodev.h"
149 #include "qemu-timer.h"
150 #include "qemu-char.h"
151 #include "cache-utils.h"
154 #include "audio/audio.h"
155 #include "migration.h"
158 #include "qemu-kvm.h"
159 #include "hw/device-assignment.h"
163 #include "exec-all.h"
165 #include "qemu_socket.h"
167 #if defined(CONFIG_SLIRP)
168 #include "libslirp.h"
171 //#define DEBUG_UNUSED_IOPORT
172 //#define DEBUG_IOPORT
174 //#define DEBUG_SLIRP
178 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
180 # define LOG_IOPORT(...) do { } while (0)
183 #define DEFAULT_RAM_SIZE 128
185 /* Max number of USB devices that can be specified on the commandline. */
186 #define MAX_USB_CMDLINE 8
188 /* Max number of bluetooth switches on the commandline. */
189 #define MAX_BT_CMDLINE 10
191 /* XXX: use a two level table to limit memory usage */
192 #define MAX_IOPORTS 65536
194 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
195 const char *bios_name
= NULL
;
196 static void *ioport_opaque
[MAX_IOPORTS
];
197 static IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
198 static IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
199 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
200 to store the VM snapshots */
201 DriveInfo drives_table
[MAX_DRIVES
+1];
203 int extboot_drive
= -1;
204 static int vga_ram_size
;
205 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
206 static DisplayState
*display_state
;
210 const char* keyboard_layout
= NULL
;
211 int64_t ticks_per_sec
;
214 NICInfo nd_table
[MAX_NICS
];
216 static int autostart
;
217 static int rtc_utc
= 1;
218 static int rtc_date_offset
= -1; /* -1 means no change */
219 int cirrus_vga_enabled
= 1;
220 int std_vga_enabled
= 0;
221 int vmsvga_enabled
= 0;
223 int graphic_width
= 1024;
224 int graphic_height
= 768;
225 int graphic_depth
= 8;
227 int graphic_width
= 800;
228 int graphic_height
= 600;
229 int graphic_depth
= 15;
231 static int full_screen
= 0;
233 static int no_frame
= 0;
236 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
237 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
238 CharDriverState
*virtcon_hds
[MAX_VIRTIO_CONSOLES
];
240 int win2k_install_hack
= 0;
244 const char *assigned_devices
[MAX_DEV_ASSIGN_CMDLINE
];
245 int assigned_devices_index
;
247 const char *vnc_display
;
248 int acpi_enabled
= 1;
254 int graphic_rotate
= 0;
256 const char *incoming
;
257 const char *option_rom
[MAX_OPTION_ROMS
];
259 int semihosting_enabled
= 0;
260 int time_drift_fix
= 0;
261 unsigned int kvm_shadow_memory
= 0;
262 const char *mem_path
= NULL
;
264 int mem_prealloc
= 1; /* force preallocation of physical target memory */
267 const char *cpu_vendor_string
;
271 const char *qemu_name
;
273 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
274 unsigned int nb_prom_envs
= 0;
275 const char *prom_envs
[MAX_PROM_ENVS
];
278 const char *nvram
= NULL
;
279 struct drive_opt drives_opt
[MAX_DRIVES
];
281 static CPUState
*cur_cpu
;
282 static CPUState
*next_cpu
;
283 static int event_pending
= 1;
284 /* Conversion factor from emulated instructions to virtual clock ticks. */
285 static int icount_time_shift
;
286 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
287 #define MAX_ICOUNT_SHIFT 10
288 /* Compensate for varying guest execution speed. */
289 static int64_t qemu_icount_bias
;
290 static QEMUTimer
*icount_rt_timer
;
291 static QEMUTimer
*icount_vm_timer
;
292 static QEMUTimer
*nographic_timer
;
294 uint8_t qemu_uuid
[16];
296 /* KVM runs the main loop in a separate thread. If we update one of the lists
297 * that are polled before or after select(), we need to make sure to break out
298 * of the select() to ensure the new item is serviced.
300 static void main_loop_break(void)
303 qemu_kvm_notify_work();
306 /***********************************************************/
307 /* x86 ISA bus support */
309 target_phys_addr_t isa_mem_base
= 0;
312 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
313 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
315 static uint32_t ioport_read(int index
, uint32_t address
)
317 static IOPortReadFunc
*default_func
[3] = {
318 default_ioport_readb
,
319 default_ioport_readw
,
322 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
324 func
= default_func
[index
];
325 return func(ioport_opaque
[address
], address
);
328 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
330 static IOPortWriteFunc
*default_func
[3] = {
331 default_ioport_writeb
,
332 default_ioport_writew
,
333 default_ioport_writel
335 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
337 func
= default_func
[index
];
338 func(ioport_opaque
[address
], address
, data
);
341 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
343 #ifdef DEBUG_UNUSED_IOPORT
344 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
349 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
351 #ifdef DEBUG_UNUSED_IOPORT
352 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
356 /* default is to make two byte accesses */
357 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
360 data
= ioport_read(0, address
);
361 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
362 data
|= ioport_read(0, address
) << 8;
366 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
368 ioport_write(0, address
, data
& 0xff);
369 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
370 ioport_write(0, address
, (data
>> 8) & 0xff);
373 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
375 #ifdef DEBUG_UNUSED_IOPORT
376 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
381 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
383 #ifdef DEBUG_UNUSED_IOPORT
384 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
388 /* size is the word size in byte */
389 int register_ioport_read(int start
, int length
, int size
,
390 IOPortReadFunc
*func
, void *opaque
)
396 } else if (size
== 2) {
398 } else if (size
== 4) {
401 hw_error("register_ioport_read: invalid size");
404 for(i
= start
; i
< start
+ length
; i
+= size
) {
405 ioport_read_table
[bsize
][i
] = func
;
406 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
407 hw_error("register_ioport_read: invalid opaque");
408 ioport_opaque
[i
] = opaque
;
413 /* size is the word size in byte */
414 int register_ioport_write(int start
, int length
, int size
,
415 IOPortWriteFunc
*func
, void *opaque
)
421 } else if (size
== 2) {
423 } else if (size
== 4) {
426 hw_error("register_ioport_write: invalid size");
429 for(i
= start
; i
< start
+ length
; i
+= size
) {
430 ioport_write_table
[bsize
][i
] = func
;
431 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
432 hw_error("register_ioport_write: invalid opaque");
433 ioport_opaque
[i
] = opaque
;
438 void isa_unassign_ioport(int start
, int length
)
442 for(i
= start
; i
< start
+ length
; i
++) {
443 ioport_read_table
[0][i
] = default_ioport_readb
;
444 ioport_read_table
[1][i
] = default_ioport_readw
;
445 ioport_read_table
[2][i
] = default_ioport_readl
;
447 ioport_write_table
[0][i
] = default_ioport_writeb
;
448 ioport_write_table
[1][i
] = default_ioport_writew
;
449 ioport_write_table
[2][i
] = default_ioport_writel
;
451 ioport_opaque
[i
] = NULL
;
455 /***********************************************************/
457 void cpu_outb(CPUState
*env
, int addr
, int val
)
459 LOG_IOPORT("outb: %04x %02x\n", addr
, val
);
460 ioport_write(0, addr
, val
);
463 env
->last_io_time
= cpu_get_time_fast();
467 void cpu_outw(CPUState
*env
, int addr
, int val
)
469 LOG_IOPORT("outw: %04x %04x\n", addr
, val
);
470 ioport_write(1, addr
, val
);
473 env
->last_io_time
= cpu_get_time_fast();
477 void cpu_outl(CPUState
*env
, int addr
, int val
)
479 LOG_IOPORT("outl: %04x %08x\n", addr
, val
);
480 ioport_write(2, addr
, val
);
483 env
->last_io_time
= cpu_get_time_fast();
487 int cpu_inb(CPUState
*env
, int addr
)
490 val
= ioport_read(0, addr
);
491 LOG_IOPORT("inb : %04x %02x\n", addr
, val
);
494 env
->last_io_time
= cpu_get_time_fast();
499 int cpu_inw(CPUState
*env
, int addr
)
502 val
= ioport_read(1, addr
);
503 LOG_IOPORT("inw : %04x %04x\n", addr
, val
);
506 env
->last_io_time
= cpu_get_time_fast();
511 int cpu_inl(CPUState
*env
, int addr
)
514 val
= ioport_read(2, addr
);
515 LOG_IOPORT("inl : %04x %08x\n", addr
, val
);
518 env
->last_io_time
= cpu_get_time_fast();
523 /***********************************************************/
524 void hw_error(const char *fmt
, ...)
530 fprintf(stderr
, "qemu: hardware error: ");
531 vfprintf(stderr
, fmt
, ap
);
532 fprintf(stderr
, "\n");
533 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
534 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
536 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
538 cpu_dump_state(env
, stderr
, fprintf
, 0);
548 static QEMUBalloonEvent
*qemu_balloon_event
;
549 void *qemu_balloon_event_opaque
;
551 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
553 qemu_balloon_event
= func
;
554 qemu_balloon_event_opaque
= opaque
;
557 void qemu_balloon(ram_addr_t target
)
559 if (qemu_balloon_event
)
560 qemu_balloon_event(qemu_balloon_event_opaque
, target
);
563 ram_addr_t
qemu_balloon_status(void)
565 if (qemu_balloon_event
)
566 return qemu_balloon_event(qemu_balloon_event_opaque
, 0);
570 /***********************************************************/
573 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
574 static void *qemu_put_kbd_event_opaque
;
575 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
576 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
578 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
580 qemu_put_kbd_event_opaque
= opaque
;
581 qemu_put_kbd_event
= func
;
584 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
585 void *opaque
, int absolute
,
588 QEMUPutMouseEntry
*s
, *cursor
;
590 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
592 s
->qemu_put_mouse_event
= func
;
593 s
->qemu_put_mouse_event_opaque
= opaque
;
594 s
->qemu_put_mouse_event_absolute
= absolute
;
595 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
598 if (!qemu_put_mouse_event_head
) {
599 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
603 cursor
= qemu_put_mouse_event_head
;
604 while (cursor
->next
!= NULL
)
605 cursor
= cursor
->next
;
608 qemu_put_mouse_event_current
= s
;
613 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
615 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
617 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
620 cursor
= qemu_put_mouse_event_head
;
621 while (cursor
!= NULL
&& cursor
!= entry
) {
623 cursor
= cursor
->next
;
626 if (cursor
== NULL
) // does not exist or list empty
628 else if (prev
== NULL
) { // entry is head
629 qemu_put_mouse_event_head
= cursor
->next
;
630 if (qemu_put_mouse_event_current
== entry
)
631 qemu_put_mouse_event_current
= cursor
->next
;
632 qemu_free(entry
->qemu_put_mouse_event_name
);
637 prev
->next
= entry
->next
;
639 if (qemu_put_mouse_event_current
== entry
)
640 qemu_put_mouse_event_current
= prev
;
642 qemu_free(entry
->qemu_put_mouse_event_name
);
646 void kbd_put_keycode(int keycode
)
648 if (qemu_put_kbd_event
) {
649 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
653 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
655 QEMUPutMouseEvent
*mouse_event
;
656 void *mouse_event_opaque
;
659 if (!qemu_put_mouse_event_current
) {
664 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
666 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
669 if (graphic_rotate
) {
670 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
673 width
= graphic_width
- 1;
674 mouse_event(mouse_event_opaque
,
675 width
- dy
, dx
, dz
, buttons_state
);
677 mouse_event(mouse_event_opaque
,
678 dx
, dy
, dz
, buttons_state
);
682 int kbd_mouse_is_absolute(void)
684 if (!qemu_put_mouse_event_current
)
687 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
690 void do_info_mice(Monitor
*mon
)
692 QEMUPutMouseEntry
*cursor
;
695 if (!qemu_put_mouse_event_head
) {
696 monitor_printf(mon
, "No mouse devices connected\n");
700 monitor_printf(mon
, "Mouse devices available:\n");
701 cursor
= qemu_put_mouse_event_head
;
702 while (cursor
!= NULL
) {
703 monitor_printf(mon
, "%c Mouse #%d: %s\n",
704 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
705 index
, cursor
->qemu_put_mouse_event_name
);
707 cursor
= cursor
->next
;
711 void do_mouse_set(Monitor
*mon
, int index
)
713 QEMUPutMouseEntry
*cursor
;
716 if (!qemu_put_mouse_event_head
) {
717 monitor_printf(mon
, "No mouse devices connected\n");
721 cursor
= qemu_put_mouse_event_head
;
722 while (cursor
!= NULL
&& index
!= i
) {
724 cursor
= cursor
->next
;
728 qemu_put_mouse_event_current
= cursor
;
730 monitor_printf(mon
, "Mouse at given index not found\n");
733 /* compute with 96 bit intermediate result: (a*b)/c */
734 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
739 #ifdef WORDS_BIGENDIAN
749 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
750 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
753 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
757 /***********************************************************/
758 /* real time host monotonic timer */
760 #define QEMU_TIMER_BASE 1000000000LL
764 static int64_t clock_freq
;
766 static void init_get_clock(void)
770 ret
= QueryPerformanceFrequency(&freq
);
772 fprintf(stderr
, "Could not calibrate ticks\n");
775 clock_freq
= freq
.QuadPart
;
778 static int64_t get_clock(void)
781 QueryPerformanceCounter(&ti
);
782 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
787 static int use_rt_clock
;
789 static void init_get_clock(void)
792 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
793 || defined(__DragonFly__)
796 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
803 static int64_t get_clock(void)
805 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
806 || defined(__DragonFly__)
809 clock_gettime(CLOCK_MONOTONIC
, &ts
);
810 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
814 /* XXX: using gettimeofday leads to problems if the date
815 changes, so it should be avoided. */
817 gettimeofday(&tv
, NULL
);
818 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
823 /* Return the virtual CPU time, based on the instruction counter. */
824 static int64_t cpu_get_icount(void)
827 CPUState
*env
= cpu_single_env
;;
828 icount
= qemu_icount
;
831 fprintf(stderr
, "Bad clock read\n");
832 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
834 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
837 /***********************************************************/
838 /* guest cycle counter */
840 static int64_t cpu_ticks_prev
;
841 static int64_t cpu_ticks_offset
;
842 static int64_t cpu_clock_offset
;
843 static int cpu_ticks_enabled
;
845 /* return the host CPU cycle counter and handle stop/restart */
846 int64_t cpu_get_ticks(void)
849 return cpu_get_icount();
851 if (!cpu_ticks_enabled
) {
852 return cpu_ticks_offset
;
855 ticks
= cpu_get_real_ticks();
856 if (cpu_ticks_prev
> ticks
) {
857 /* Note: non increasing ticks may happen if the host uses
859 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
861 cpu_ticks_prev
= ticks
;
862 return ticks
+ cpu_ticks_offset
;
866 /* return the host CPU monotonic timer and handle stop/restart */
867 static int64_t cpu_get_clock(void)
870 if (!cpu_ticks_enabled
) {
871 return cpu_clock_offset
;
874 return ti
+ cpu_clock_offset
;
878 /* enable cpu_get_ticks() */
879 void cpu_enable_ticks(void)
881 if (!cpu_ticks_enabled
) {
882 cpu_ticks_offset
-= cpu_get_real_ticks();
883 cpu_clock_offset
-= get_clock();
884 cpu_ticks_enabled
= 1;
888 /* disable cpu_get_ticks() : the clock is stopped. You must not call
889 cpu_get_ticks() after that. */
890 void cpu_disable_ticks(void)
892 if (cpu_ticks_enabled
) {
893 cpu_ticks_offset
= cpu_get_ticks();
894 cpu_clock_offset
= cpu_get_clock();
895 cpu_ticks_enabled
= 0;
899 /***********************************************************/
902 #define QEMU_TIMER_REALTIME 0
903 #define QEMU_TIMER_VIRTUAL 1
907 /* XXX: add frequency */
915 struct QEMUTimer
*next
;
918 struct qemu_alarm_timer
{
922 int (*start
)(struct qemu_alarm_timer
*t
);
923 void (*stop
)(struct qemu_alarm_timer
*t
);
924 void (*rearm
)(struct qemu_alarm_timer
*t
);
928 #define ALARM_FLAG_DYNTICKS 0x1
929 #define ALARM_FLAG_EXPIRED 0x2
931 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
933 return t
->flags
& ALARM_FLAG_DYNTICKS
;
936 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
938 if (!alarm_has_dynticks(t
))
944 /* TODO: MIN_TIMER_REARM_US should be optimized */
945 #define MIN_TIMER_REARM_US 250
947 static struct qemu_alarm_timer
*alarm_timer
;
949 static int alarm_timer_rfd
, alarm_timer_wfd
;
954 struct qemu_alarm_win32
{
958 } alarm_win32_data
= {0, NULL
, -1};
960 static int win32_start_timer(struct qemu_alarm_timer
*t
);
961 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
962 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
966 static int unix_start_timer(struct qemu_alarm_timer
*t
);
967 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
971 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
972 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
973 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
975 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
976 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
978 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
979 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
981 #endif /* __linux__ */
985 /* Correlation between real and virtual time is always going to be
986 fairly approximate, so ignore small variation.
987 When the guest is idle real and virtual time will be aligned in
989 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
991 static void icount_adjust(void)
996 static int64_t last_delta
;
997 /* If the VM is not running, then do nothing. */
1001 cur_time
= cpu_get_clock();
1002 cur_icount
= qemu_get_clock(vm_clock
);
1003 delta
= cur_icount
- cur_time
;
1004 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1006 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
1007 && icount_time_shift
> 0) {
1008 /* The guest is getting too far ahead. Slow time down. */
1009 icount_time_shift
--;
1012 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
1013 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
1014 /* The guest is getting too far behind. Speed time up. */
1015 icount_time_shift
++;
1018 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
1021 static void icount_adjust_rt(void * opaque
)
1023 qemu_mod_timer(icount_rt_timer
,
1024 qemu_get_clock(rt_clock
) + 1000);
1028 static void icount_adjust_vm(void * opaque
)
1030 qemu_mod_timer(icount_vm_timer
,
1031 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1035 static void init_icount_adjust(void)
1037 /* Have both realtime and virtual time triggers for speed adjustment.
1038 The realtime trigger catches emulated time passing too slowly,
1039 the virtual time trigger catches emulated time passing too fast.
1040 Realtime triggers occur even when idle, so use them less frequently
1041 than VM triggers. */
1042 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
1043 qemu_mod_timer(icount_rt_timer
,
1044 qemu_get_clock(rt_clock
) + 1000);
1045 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
1046 qemu_mod_timer(icount_vm_timer
,
1047 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1050 static struct qemu_alarm_timer alarm_timers
[] = {
1053 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
1054 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
1055 /* HPET - if available - is preferred */
1056 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
1057 /* ...otherwise try RTC */
1058 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1060 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1062 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1063 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1064 {"win32", 0, win32_start_timer
,
1065 win32_stop_timer
, NULL
, &alarm_win32_data
},
1070 static void show_available_alarms(void)
1074 printf("Available alarm timers, in order of precedence:\n");
1075 for (i
= 0; alarm_timers
[i
].name
; i
++)
1076 printf("%s\n", alarm_timers
[i
].name
);
1079 static void configure_alarms(char const *opt
)
1083 int count
= ARRAY_SIZE(alarm_timers
) - 1;
1086 struct qemu_alarm_timer tmp
;
1088 if (!strcmp(opt
, "?")) {
1089 show_available_alarms();
1095 /* Reorder the array */
1096 name
= strtok(arg
, ",");
1098 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1099 if (!strcmp(alarm_timers
[i
].name
, name
))
1104 fprintf(stderr
, "Unknown clock %s\n", name
);
1113 tmp
= alarm_timers
[i
];
1114 alarm_timers
[i
] = alarm_timers
[cur
];
1115 alarm_timers
[cur
] = tmp
;
1119 name
= strtok(NULL
, ",");
1125 /* Disable remaining timers */
1126 for (i
= cur
; i
< count
; i
++)
1127 alarm_timers
[i
].name
= NULL
;
1129 show_available_alarms();
1134 QEMUClock
*rt_clock
;
1135 QEMUClock
*vm_clock
;
1137 static QEMUTimer
*active_timers
[2];
1139 static QEMUClock
*qemu_new_clock(int type
)
1142 clock
= qemu_mallocz(sizeof(QEMUClock
));
1147 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1151 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1154 ts
->opaque
= opaque
;
1158 void qemu_free_timer(QEMUTimer
*ts
)
1163 /* stop a timer, but do not dealloc it */
1164 void qemu_del_timer(QEMUTimer
*ts
)
1168 /* NOTE: this code must be signal safe because
1169 qemu_timer_expired() can be called from a signal. */
1170 pt
= &active_timers
[ts
->clock
->type
];
1183 /* modify the current timer so that it will be fired when current_time
1184 >= expire_time. The corresponding callback will be called. */
1185 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1191 /* add the timer in the sorted list */
1192 /* NOTE: this code must be signal safe because
1193 qemu_timer_expired() can be called from a signal. */
1194 pt
= &active_timers
[ts
->clock
->type
];
1199 if (t
->expire_time
> expire_time
)
1203 ts
->expire_time
= expire_time
;
1207 /* Rearm if necessary */
1208 if (pt
== &active_timers
[ts
->clock
->type
]) {
1209 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1210 qemu_rearm_alarm_timer(alarm_timer
);
1212 /* Interrupt execution to force deadline recalculation. */
1213 if (use_icount
&& cpu_single_env
) {
1214 cpu_exit(cpu_single_env
);
1219 int qemu_timer_pending(QEMUTimer
*ts
)
1222 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1229 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1233 return (timer_head
->expire_time
<= current_time
);
1236 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1242 if (!ts
|| ts
->expire_time
> current_time
)
1244 /* remove timer from the list before calling the callback */
1245 *ptimer_head
= ts
->next
;
1248 /* run the callback (the timer list can be modified) */
1253 int64_t qemu_get_clock(QEMUClock
*clock
)
1255 switch(clock
->type
) {
1256 case QEMU_TIMER_REALTIME
:
1257 return get_clock() / 1000000;
1259 case QEMU_TIMER_VIRTUAL
:
1261 return cpu_get_icount();
1263 return cpu_get_clock();
1268 static void init_timers(void)
1271 ticks_per_sec
= QEMU_TIMER_BASE
;
1272 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1273 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1277 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1279 uint64_t expire_time
;
1281 if (qemu_timer_pending(ts
)) {
1282 expire_time
= ts
->expire_time
;
1286 qemu_put_be64(f
, expire_time
);
1289 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1291 uint64_t expire_time
;
1293 expire_time
= qemu_get_be64(f
);
1294 if (expire_time
!= -1) {
1295 qemu_mod_timer(ts
, expire_time
);
1301 static void timer_save(QEMUFile
*f
, void *opaque
)
1303 if (cpu_ticks_enabled
) {
1304 hw_error("cannot save state if virtual timers are running");
1306 qemu_put_be64(f
, cpu_ticks_offset
);
1307 qemu_put_be64(f
, ticks_per_sec
);
1308 qemu_put_be64(f
, cpu_clock_offset
);
1311 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1313 if (version_id
!= 1 && version_id
!= 2)
1315 if (cpu_ticks_enabled
) {
1318 cpu_ticks_offset
=qemu_get_be64(f
);
1319 ticks_per_sec
=qemu_get_be64(f
);
1320 if (version_id
== 2) {
1321 cpu_clock_offset
=qemu_get_be64(f
);
1327 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1328 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
1330 static void host_alarm_handler(int host_signum
)
1334 #define DISP_FREQ 1000
1336 static int64_t delta_min
= INT64_MAX
;
1337 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1339 ti
= qemu_get_clock(vm_clock
);
1340 if (last_clock
!= 0) {
1341 delta
= ti
- last_clock
;
1342 if (delta
< delta_min
)
1344 if (delta
> delta_max
)
1347 if (++count
== DISP_FREQ
) {
1348 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1349 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1350 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1351 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1352 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1354 delta_min
= INT64_MAX
;
1363 alarm_has_dynticks(alarm_timer
) ||
1365 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1366 qemu_get_clock(vm_clock
))) ||
1367 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1368 qemu_get_clock(rt_clock
))) {
1369 CPUState
*env
= next_cpu
;
1372 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1373 SetEvent(data
->host_alarm
);
1375 static const char byte
= 0;
1376 write(alarm_timer_wfd
, &byte
, sizeof(byte
));
1378 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1381 /* stop the currently executing cpu because a timer occured */
1384 if (env
->kqemu_enabled
) {
1385 kqemu_cpu_interrupt(env
);
1393 static int64_t qemu_next_deadline(void)
1397 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1398 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1399 qemu_get_clock(vm_clock
);
1401 /* To avoid problems with overflow limit this to 2^32. */
1411 #if defined(__linux__) || defined(_WIN32)
1412 static uint64_t qemu_next_deadline_dyntick(void)
1420 delta
= (qemu_next_deadline() + 999) / 1000;
1422 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1423 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1424 qemu_get_clock(rt_clock
))*1000;
1425 if (rtdelta
< delta
)
1429 if (delta
< MIN_TIMER_REARM_US
)
1430 delta
= MIN_TIMER_REARM_US
;
1438 /* Sets a specific flag */
1439 static int fcntl_setfl(int fd
, int flag
)
1443 flags
= fcntl(fd
, F_GETFL
);
1447 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1453 #if defined(__linux__)
1455 #define RTC_FREQ 1024
1457 static void enable_sigio_timer(int fd
)
1459 struct sigaction act
;
1462 sigfillset(&act
.sa_mask
);
1464 act
.sa_handler
= host_alarm_handler
;
1466 sigaction(SIGIO
, &act
, NULL
);
1467 fcntl_setfl(fd
, O_ASYNC
);
1468 fcntl(fd
, F_SETOWN
, getpid());
1471 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1473 struct hpet_info info
;
1476 fd
= open("/dev/hpet", O_RDONLY
);
1481 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1483 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1484 "error, but for better emulation accuracy type:\n"
1485 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1489 /* Check capabilities */
1490 r
= ioctl(fd
, HPET_INFO
, &info
);
1494 /* Enable periodic mode */
1495 r
= ioctl(fd
, HPET_EPI
, 0);
1496 if (info
.hi_flags
&& (r
< 0))
1499 /* Enable interrupt */
1500 r
= ioctl(fd
, HPET_IE_ON
, 0);
1504 enable_sigio_timer(fd
);
1505 t
->priv
= (void *)(long)fd
;
1513 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1515 int fd
= (long)t
->priv
;
1520 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1523 unsigned long current_rtc_freq
= 0;
1525 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1528 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1529 if (current_rtc_freq
!= RTC_FREQ
&&
1530 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1531 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1532 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1533 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1536 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1542 enable_sigio_timer(rtc_fd
);
1544 t
->priv
= (void *)(long)rtc_fd
;
1549 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1551 int rtc_fd
= (long)t
->priv
;
1556 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1560 struct sigaction act
;
1562 sigfillset(&act
.sa_mask
);
1564 act
.sa_handler
= host_alarm_handler
;
1566 sigaction(SIGALRM
, &act
, NULL
);
1568 ev
.sigev_value
.sival_int
= 0;
1569 ev
.sigev_notify
= SIGEV_SIGNAL
;
1570 ev
.sigev_signo
= SIGALRM
;
1572 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1573 perror("timer_create");
1575 /* disable dynticks */
1576 fprintf(stderr
, "Dynamic Ticks disabled\n");
1581 t
->priv
= (void *)(long)host_timer
;
1586 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1588 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1590 timer_delete(host_timer
);
1593 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1595 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1596 struct itimerspec timeout
;
1597 int64_t nearest_delta_us
= INT64_MAX
;
1600 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1601 !active_timers
[QEMU_TIMER_VIRTUAL
])
1604 nearest_delta_us
= qemu_next_deadline_dyntick();
1606 /* check whether a timer is already running */
1607 if (timer_gettime(host_timer
, &timeout
)) {
1609 fprintf(stderr
, "Internal timer error: aborting\n");
1612 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1613 if (current_us
&& current_us
<= nearest_delta_us
)
1616 timeout
.it_interval
.tv_sec
= 0;
1617 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1618 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1619 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1620 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1622 fprintf(stderr
, "Internal timer error: aborting\n");
1627 #endif /* defined(__linux__) */
1629 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1631 struct sigaction act
;
1632 struct itimerval itv
;
1636 sigfillset(&act
.sa_mask
);
1638 act
.sa_handler
= host_alarm_handler
;
1640 sigaction(SIGALRM
, &act
, NULL
);
1642 itv
.it_interval
.tv_sec
= 0;
1643 /* for i386 kernel 2.6 to get 1 ms */
1644 itv
.it_interval
.tv_usec
= 999;
1645 itv
.it_value
.tv_sec
= 0;
1646 itv
.it_value
.tv_usec
= 10 * 1000;
1648 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1655 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1657 struct itimerval itv
;
1659 memset(&itv
, 0, sizeof(itv
));
1660 setitimer(ITIMER_REAL
, &itv
, NULL
);
1663 #endif /* !defined(_WIN32) */
1665 static void try_to_rearm_timer(void *opaque
)
1667 struct qemu_alarm_timer
*t
= opaque
;
1671 /* Drain the notify pipe */
1674 len
= read(alarm_timer_rfd
, buffer
, sizeof(buffer
));
1675 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
1678 if (t
->flags
& ALARM_FLAG_EXPIRED
) {
1679 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
1680 qemu_rearm_alarm_timer(alarm_timer
);
1686 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1689 struct qemu_alarm_win32
*data
= t
->priv
;
1692 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1693 if (!data
->host_alarm
) {
1694 perror("Failed CreateEvent");
1698 memset(&tc
, 0, sizeof(tc
));
1699 timeGetDevCaps(&tc
, sizeof(tc
));
1701 if (data
->period
< tc
.wPeriodMin
)
1702 data
->period
= tc
.wPeriodMin
;
1704 timeBeginPeriod(data
->period
);
1706 flags
= TIME_CALLBACK_FUNCTION
;
1707 if (alarm_has_dynticks(t
))
1708 flags
|= TIME_ONESHOT
;
1710 flags
|= TIME_PERIODIC
;
1712 data
->timerId
= timeSetEvent(1, // interval (ms)
1713 data
->period
, // resolution
1714 host_alarm_handler
, // function
1715 (DWORD
)t
, // parameter
1718 if (!data
->timerId
) {
1719 perror("Failed to initialize win32 alarm timer");
1721 timeEndPeriod(data
->period
);
1722 CloseHandle(data
->host_alarm
);
1726 qemu_add_wait_object(data
->host_alarm
, try_to_rearm_timer
, t
);
1731 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1733 struct qemu_alarm_win32
*data
= t
->priv
;
1735 timeKillEvent(data
->timerId
);
1736 timeEndPeriod(data
->period
);
1738 CloseHandle(data
->host_alarm
);
1741 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1743 struct qemu_alarm_win32
*data
= t
->priv
;
1744 uint64_t nearest_delta_us
;
1746 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1747 !active_timers
[QEMU_TIMER_VIRTUAL
])
1750 nearest_delta_us
= qemu_next_deadline_dyntick();
1751 nearest_delta_us
/= 1000;
1753 timeKillEvent(data
->timerId
);
1755 data
->timerId
= timeSetEvent(1,
1759 TIME_ONESHOT
| TIME_PERIODIC
);
1761 if (!data
->timerId
) {
1762 perror("Failed to re-arm win32 alarm timer");
1764 timeEndPeriod(data
->period
);
1765 CloseHandle(data
->host_alarm
);
1772 static int init_timer_alarm(void)
1774 struct qemu_alarm_timer
*t
= NULL
;
1784 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
1788 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
1792 alarm_timer_rfd
= fds
[0];
1793 alarm_timer_wfd
= fds
[1];
1796 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1797 t
= &alarm_timers
[i
];
1810 qemu_set_fd_handler2(alarm_timer_rfd
, NULL
,
1811 try_to_rearm_timer
, NULL
, t
);
1826 static void quit_timers(void)
1828 alarm_timer
->stop(alarm_timer
);
1832 /***********************************************************/
1833 /* host time/date access */
1834 void qemu_get_timedate(struct tm
*tm
, int offset
)
1841 if (rtc_date_offset
== -1) {
1845 ret
= localtime(&ti
);
1847 ti
-= rtc_date_offset
;
1851 memcpy(tm
, ret
, sizeof(struct tm
));
1854 int qemu_timedate_diff(struct tm
*tm
)
1858 if (rtc_date_offset
== -1)
1860 seconds
= mktimegm(tm
);
1862 seconds
= mktime(tm
);
1864 seconds
= mktimegm(tm
) + rtc_date_offset
;
1866 return seconds
- time(NULL
);
1870 static void socket_cleanup(void)
1875 static int socket_init(void)
1880 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1882 err
= WSAGetLastError();
1883 fprintf(stderr
, "WSAStartup: %d\n", err
);
1886 atexit(socket_cleanup
);
1891 const char *get_opt_name(char *buf
, int buf_size
, const char *p
)
1896 while (*p
!= '\0' && *p
!= '=') {
1897 if (q
&& (q
- buf
) < buf_size
- 1)
1907 const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
1912 while (*p
!= '\0') {
1914 if (*(p
+ 1) != ',')
1918 if (q
&& (q
- buf
) < buf_size
- 1)
1928 int get_param_value(char *buf
, int buf_size
,
1929 const char *tag
, const char *str
)
1936 p
= get_opt_name(option
, sizeof(option
), p
);
1940 if (!strcmp(tag
, option
)) {
1941 (void)get_opt_value(buf
, buf_size
, p
);
1944 p
= get_opt_value(NULL
, 0, p
);
1953 int check_params(char *buf
, int buf_size
,
1954 const char * const *params
, const char *str
)
1961 p
= get_opt_name(buf
, buf_size
, p
);
1965 for(i
= 0; params
[i
] != NULL
; i
++)
1966 if (!strcmp(params
[i
], buf
))
1968 if (params
[i
] == NULL
)
1970 p
= get_opt_value(NULL
, 0, p
);
1978 /***********************************************************/
1979 /* Bluetooth support */
1982 static struct HCIInfo
*hci_table
[MAX_NICS
];
1984 static struct bt_vlan_s
{
1985 struct bt_scatternet_s net
;
1987 struct bt_vlan_s
*next
;
1990 /* find or alloc a new bluetooth "VLAN" */
1991 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1993 struct bt_vlan_s
**pvlan
, *vlan
;
1994 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1998 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
2000 pvlan
= &first_bt_vlan
;
2001 while (*pvlan
!= NULL
)
2002 pvlan
= &(*pvlan
)->next
;
2007 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
2011 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
2016 static struct HCIInfo null_hci
= {
2017 .cmd_send
= null_hci_send
,
2018 .sco_send
= null_hci_send
,
2019 .acl_send
= null_hci_send
,
2020 .bdaddr_set
= null_hci_addr_set
,
2023 struct HCIInfo
*qemu_next_hci(void)
2025 if (cur_hci
== nb_hcis
)
2028 return hci_table
[cur_hci
++];
2031 static struct HCIInfo
*hci_init(const char *str
)
2034 struct bt_scatternet_s
*vlan
= 0;
2036 if (!strcmp(str
, "null"))
2039 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
2041 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
2042 else if (!strncmp(str
, "hci", 3)) {
2045 if (!strncmp(str
+ 3, ",vlan=", 6)) {
2046 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
2051 vlan
= qemu_find_bt_vlan(0);
2053 return bt_new_hci(vlan
);
2056 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
2061 static int bt_hci_parse(const char *str
)
2063 struct HCIInfo
*hci
;
2066 if (nb_hcis
>= MAX_NICS
) {
2067 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
2071 hci
= hci_init(str
);
2080 bdaddr
.b
[5] = 0x56 + nb_hcis
;
2081 hci
->bdaddr_set(hci
, bdaddr
.b
);
2083 hci_table
[nb_hcis
++] = hci
;
2088 static void bt_vhci_add(int vlan_id
)
2090 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
2093 fprintf(stderr
, "qemu: warning: adding a VHCI to "
2094 "an empty scatternet %i\n", vlan_id
);
2096 bt_vhci_init(bt_new_hci(vlan
));
2099 static struct bt_device_s
*bt_device_add(const char *opt
)
2101 struct bt_scatternet_s
*vlan
;
2103 char *endp
= strstr(opt
, ",vlan=");
2104 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
2107 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
2110 vlan_id
= strtol(endp
+ 6, &endp
, 0);
2112 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
2117 vlan
= qemu_find_bt_vlan(vlan_id
);
2120 fprintf(stderr
, "qemu: warning: adding a slave device to "
2121 "an empty scatternet %i\n", vlan_id
);
2123 if (!strcmp(devname
, "keyboard"))
2124 return bt_keyboard_init(vlan
);
2126 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
2130 static int bt_parse(const char *opt
)
2132 const char *endp
, *p
;
2135 if (strstart(opt
, "hci", &endp
)) {
2136 if (!*endp
|| *endp
== ',') {
2138 if (!strstart(endp
, ",vlan=", 0))
2141 return bt_hci_parse(opt
);
2143 } else if (strstart(opt
, "vhci", &endp
)) {
2144 if (!*endp
|| *endp
== ',') {
2146 if (strstart(endp
, ",vlan=", &p
)) {
2147 vlan
= strtol(p
, (char **) &endp
, 0);
2149 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
2153 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
2162 } else if (strstart(opt
, "device:", &endp
))
2163 return !bt_device_add(endp
);
2165 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
2169 /***********************************************************/
2170 /* QEMU Block devices */
2172 #define HD_ALIAS "index=%d,media=disk"
2173 #define CDROM_ALIAS "index=2,media=cdrom"
2174 #define FD_ALIAS "index=%d,if=floppy"
2175 #define PFLASH_ALIAS "if=pflash"
2176 #define MTD_ALIAS "if=mtd"
2177 #define SD_ALIAS "index=0,if=sd"
2179 static int drive_opt_get_free_idx(void)
2183 for (index
= 0; index
< MAX_DRIVES
; index
++)
2184 if (!drives_opt
[index
].used
) {
2185 drives_opt
[index
].used
= 1;
2192 static int drive_get_free_idx(void)
2196 for (index
= 0; index
< MAX_DRIVES
; index
++)
2197 if (!drives_table
[index
].used
) {
2198 drives_table
[index
].used
= 1;
2205 int drive_add(const char *file
, const char *fmt
, ...)
2208 int index
= drive_opt_get_free_idx();
2210 if (nb_drives_opt
>= MAX_DRIVES
|| index
== -1) {
2211 fprintf(stderr
, "qemu: too many drives\n");
2215 drives_opt
[index
].file
= file
;
2217 vsnprintf(drives_opt
[index
].opt
,
2218 sizeof(drives_opt
[0].opt
), fmt
, ap
);
2225 void drive_remove(int index
)
2227 drives_opt
[index
].used
= 0;
2231 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
2235 /* seek interface, bus and unit */
2237 for (index
= 0; index
< MAX_DRIVES
; index
++)
2238 if (drives_table
[index
].type
== type
&&
2239 drives_table
[index
].bus
== bus
&&
2240 drives_table
[index
].unit
== unit
&&
2241 drives_table
[index
].used
)
2247 int drive_get_max_bus(BlockInterfaceType type
)
2253 for (index
= 0; index
< nb_drives
; index
++) {
2254 if(drives_table
[index
].type
== type
&&
2255 drives_table
[index
].bus
> max_bus
)
2256 max_bus
= drives_table
[index
].bus
;
2261 const char *drive_get_serial(BlockDriverState
*bdrv
)
2265 for (index
= 0; index
< nb_drives
; index
++)
2266 if (drives_table
[index
].bdrv
== bdrv
)
2267 return drives_table
[index
].serial
;
2272 BlockInterfaceErrorAction
drive_get_onerror(BlockDriverState
*bdrv
)
2276 for (index
= 0; index
< nb_drives
; index
++)
2277 if (drives_table
[index
].bdrv
== bdrv
)
2278 return drives_table
[index
].onerror
;
2280 return BLOCK_ERR_STOP_ENOSPC
;
2283 static void bdrv_format_print(void *opaque
, const char *name
)
2285 fprintf(stderr
, " %s", name
);
2288 void drive_uninit(BlockDriverState
*bdrv
)
2292 for (i
= 0; i
< MAX_DRIVES
; i
++)
2293 if (drives_table
[i
].bdrv
== bdrv
) {
2294 drives_table
[i
].bdrv
= NULL
;
2295 drives_table
[i
].used
= 0;
2296 drive_remove(drives_table
[i
].drive_opt_idx
);
2302 int drive_init(struct drive_opt
*arg
, int snapshot
, void *opaque
)
2308 const char *mediastr
= "";
2309 BlockInterfaceType type
;
2310 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
2311 int bus_id
, unit_id
;
2312 int cyls
, heads
, secs
, translation
;
2313 BlockDriverState
*bdrv
;
2314 BlockDriver
*drv
= NULL
;
2315 QEMUMachine
*machine
= opaque
;
2319 int bdrv_flags
, onerror
;
2320 int drives_table_idx
;
2321 char *str
= arg
->opt
;
2322 static const char * const params
[] = { "bus", "unit", "if", "index",
2323 "cyls", "heads", "secs", "trans",
2324 "media", "snapshot", "file",
2325 "cache", "format", "serial", "werror",
2328 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
2329 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
2335 cyls
= heads
= secs
= 0;
2338 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2342 if (machine
->use_scsi
) {
2344 max_devs
= MAX_SCSI_DEVS
;
2345 pstrcpy(devname
, sizeof(devname
), "scsi");
2348 max_devs
= MAX_IDE_DEVS
;
2349 pstrcpy(devname
, sizeof(devname
), "ide");
2353 /* extract parameters */
2355 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
2356 bus_id
= strtol(buf
, NULL
, 0);
2358 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
2363 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
2364 unit_id
= strtol(buf
, NULL
, 0);
2366 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
2371 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
2372 pstrcpy(devname
, sizeof(devname
), buf
);
2373 if (!strcmp(buf
, "ide")) {
2375 max_devs
= MAX_IDE_DEVS
;
2376 } else if (!strcmp(buf
, "scsi")) {
2378 max_devs
= MAX_SCSI_DEVS
;
2379 } else if (!strcmp(buf
, "floppy")) {
2382 } else if (!strcmp(buf
, "pflash")) {
2385 } else if (!strcmp(buf
, "mtd")) {
2388 } else if (!strcmp(buf
, "sd")) {
2391 } else if (!strcmp(buf
, "virtio")) {
2395 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
2400 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
2401 index
= strtol(buf
, NULL
, 0);
2403 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
2408 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
2409 cyls
= strtol(buf
, NULL
, 0);
2412 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
2413 heads
= strtol(buf
, NULL
, 0);
2416 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
2417 secs
= strtol(buf
, NULL
, 0);
2420 if (cyls
|| heads
|| secs
) {
2421 if (cyls
< 1 || cyls
> 16383) {
2422 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
2425 if (heads
< 1 || heads
> 16) {
2426 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
2429 if (secs
< 1 || secs
> 63) {
2430 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
2435 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
2438 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2442 if (!strcmp(buf
, "none"))
2443 translation
= BIOS_ATA_TRANSLATION_NONE
;
2444 else if (!strcmp(buf
, "lba"))
2445 translation
= BIOS_ATA_TRANSLATION_LBA
;
2446 else if (!strcmp(buf
, "auto"))
2447 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2449 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
2454 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
2455 if (!strcmp(buf
, "disk")) {
2457 } else if (!strcmp(buf
, "cdrom")) {
2458 if (cyls
|| secs
|| heads
) {
2460 "qemu: '%s' invalid physical CHS format\n", str
);
2463 media
= MEDIA_CDROM
;
2465 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
2470 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
2471 if (!strcmp(buf
, "on"))
2473 else if (!strcmp(buf
, "off"))
2476 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
2481 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
2482 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2484 else if (!strcmp(buf
, "writethrough"))
2486 else if (!strcmp(buf
, "writeback"))
2489 fprintf(stderr
, "qemu: invalid cache option\n");
2494 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
2495 if (strcmp(buf
, "?") == 0) {
2496 fprintf(stderr
, "qemu: Supported formats:");
2497 bdrv_iterate_format(bdrv_format_print
, NULL
);
2498 fprintf(stderr
, "\n");
2501 drv
= bdrv_find_format(buf
);
2503 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2508 if (get_param_value(buf
, sizeof(buf
), "boot", str
)) {
2509 if (!strcmp(buf
, "on")) {
2510 if (extboot_drive
!= -1) {
2511 fprintf(stderr
, "qemu: two bootable drives specified\n");
2514 extboot_drive
= nb_drives
;
2515 } else if (strcmp(buf
, "off")) {
2516 fprintf(stderr
, "qemu: '%s' invalid boot option\n", str
);
2521 if (arg
->file
== NULL
)
2522 get_param_value(file
, sizeof(file
), "file", str
);
2524 pstrcpy(file
, sizeof(file
), arg
->file
);
2526 if (!get_param_value(serial
, sizeof(serial
), "serial", str
))
2527 memset(serial
, 0, sizeof(serial
));
2529 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2530 if (get_param_value(buf
, sizeof(serial
), "werror", str
)) {
2531 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2532 fprintf(stderr
, "werror is no supported by this format\n");
2535 if (!strcmp(buf
, "ignore"))
2536 onerror
= BLOCK_ERR_IGNORE
;
2537 else if (!strcmp(buf
, "enospc"))
2538 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2539 else if (!strcmp(buf
, "stop"))
2540 onerror
= BLOCK_ERR_STOP_ANY
;
2541 else if (!strcmp(buf
, "report"))
2542 onerror
= BLOCK_ERR_REPORT
;
2544 fprintf(stderr
, "qemu: '%s' invalid write error action\n", buf
);
2549 /* compute bus and unit according index */
2552 if (bus_id
!= 0 || unit_id
!= -1) {
2554 "qemu: '%s' index cannot be used with bus and unit\n", str
);
2562 unit_id
= index
% max_devs
;
2563 bus_id
= index
/ max_devs
;
2567 /* if user doesn't specify a unit_id,
2568 * try to find the first free
2571 if (unit_id
== -1) {
2573 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
2575 if (max_devs
&& unit_id
>= max_devs
) {
2576 unit_id
-= max_devs
;
2584 if (max_devs
&& unit_id
>= max_devs
) {
2585 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
2586 str
, unit_id
, max_devs
- 1);
2591 * ignore multiple definitions
2594 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
2599 if (type
== IF_IDE
|| type
== IF_SCSI
)
2600 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2602 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
2603 devname
, bus_id
, mediastr
, unit_id
);
2605 snprintf(buf
, sizeof(buf
), "%s%s%i",
2606 devname
, mediastr
, unit_id
);
2607 bdrv
= bdrv_new(buf
);
2608 drives_table_idx
= drive_get_free_idx();
2609 drives_table
[drives_table_idx
].bdrv
= bdrv
;
2610 drives_table
[drives_table_idx
].type
= type
;
2611 drives_table
[drives_table_idx
].bus
= bus_id
;
2612 drives_table
[drives_table_idx
].unit
= unit_id
;
2613 drives_table
[drives_table_idx
].onerror
= onerror
;
2614 drives_table
[drives_table_idx
].drive_opt_idx
= arg
- drives_opt
;
2615 strncpy(drives_table
[drives_table_idx
].serial
, serial
, sizeof(serial
));
2624 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
2625 bdrv_set_translation_hint(bdrv
, translation
);
2629 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
2634 /* FIXME: This isn't really a floppy, but it's a reasonable
2637 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
2648 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2649 cache
= 2; /* always use write-back with snapshot */
2651 if (cache
== 0) /* no caching */
2652 bdrv_flags
|= BDRV_O_NOCACHE
;
2653 else if (cache
== 2) /* write-back */
2654 bdrv_flags
|= BDRV_O_CACHE_WB
;
2655 else if (cache
== 3) /* not specified */
2656 bdrv_flags
|= BDRV_O_CACHE_DEF
;
2657 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0) {
2658 fprintf(stderr
, "qemu: could not open disk image %s\n",
2662 if (bdrv_key_required(bdrv
))
2664 return drives_table_idx
;
2667 /***********************************************************/
2670 static USBPort
*used_usb_ports
;
2671 static USBPort
*free_usb_ports
;
2673 /* ??? Maybe change this to register a hub to keep track of the topology. */
2674 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
2675 usb_attachfn attach
)
2677 port
->opaque
= opaque
;
2678 port
->index
= index
;
2679 port
->attach
= attach
;
2680 port
->next
= free_usb_ports
;
2681 free_usb_ports
= port
;
2684 int usb_device_add_dev(USBDevice
*dev
)
2688 /* Find a USB port to add the device to. */
2689 port
= free_usb_ports
;
2693 /* Create a new hub and chain it on. */
2694 free_usb_ports
= NULL
;
2695 port
->next
= used_usb_ports
;
2696 used_usb_ports
= port
;
2698 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
2699 usb_attach(port
, hub
);
2700 port
= free_usb_ports
;
2703 free_usb_ports
= port
->next
;
2704 port
->next
= used_usb_ports
;
2705 used_usb_ports
= port
;
2706 usb_attach(port
, dev
);
2710 static void usb_msd_password_cb(void *opaque
, int err
)
2712 USBDevice
*dev
= opaque
;
2715 usb_device_add_dev(dev
);
2717 dev
->handle_destroy(dev
);
2720 static int usb_device_add(const char *devname
, int is_hotplug
)
2725 if (!free_usb_ports
)
2728 if (strstart(devname
, "host:", &p
)) {
2729 dev
= usb_host_device_open(p
);
2730 } else if (!strcmp(devname
, "mouse")) {
2731 dev
= usb_mouse_init();
2732 } else if (!strcmp(devname
, "tablet")) {
2733 dev
= usb_tablet_init();
2734 } else if (!strcmp(devname
, "keyboard")) {
2735 dev
= usb_keyboard_init();
2736 } else if (strstart(devname
, "disk:", &p
)) {
2737 BlockDriverState
*bs
;
2739 dev
= usb_msd_init(p
);
2742 bs
= usb_msd_get_bdrv(dev
);
2743 if (bdrv_key_required(bs
)) {
2746 monitor_read_bdrv_key_start(cur_mon
, bs
, usb_msd_password_cb
,
2751 } else if (!strcmp(devname
, "wacom-tablet")) {
2752 dev
= usb_wacom_init();
2753 } else if (strstart(devname
, "serial:", &p
)) {
2754 dev
= usb_serial_init(p
);
2755 #ifdef CONFIG_BRLAPI
2756 } else if (!strcmp(devname
, "braille")) {
2757 dev
= usb_baum_init();
2759 } else if (strstart(devname
, "net:", &p
)) {
2762 if (net_client_init("nic", p
) < 0)
2764 nd_table
[nic
].model
= "usb";
2765 dev
= usb_net_init(&nd_table
[nic
]);
2766 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2767 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2768 bt_new_hci(qemu_find_bt_vlan(0)));
2775 return usb_device_add_dev(dev
);
2778 int usb_device_del_addr(int bus_num
, int addr
)
2784 if (!used_usb_ports
)
2790 lastp
= &used_usb_ports
;
2791 port
= used_usb_ports
;
2792 while (port
&& port
->dev
->addr
!= addr
) {
2793 lastp
= &port
->next
;
2801 *lastp
= port
->next
;
2802 usb_attach(port
, NULL
);
2803 dev
->handle_destroy(dev
);
2804 port
->next
= free_usb_ports
;
2805 free_usb_ports
= port
;
2809 static int usb_device_del(const char *devname
)
2814 if (strstart(devname
, "host:", &p
))
2815 return usb_host_device_close(p
);
2817 if (!used_usb_ports
)
2820 p
= strchr(devname
, '.');
2823 bus_num
= strtoul(devname
, NULL
, 0);
2824 addr
= strtoul(p
+ 1, NULL
, 0);
2826 return usb_device_del_addr(bus_num
, addr
);
2829 void do_usb_add(Monitor
*mon
, const char *devname
)
2831 usb_device_add(devname
, 1);
2834 void do_usb_del(Monitor
*mon
, const char *devname
)
2836 usb_device_del(devname
);
2839 void usb_info(Monitor
*mon
)
2843 const char *speed_str
;
2846 monitor_printf(mon
, "USB support not enabled\n");
2850 for (port
= used_usb_ports
; port
; port
= port
->next
) {
2854 switch(dev
->speed
) {
2858 case USB_SPEED_FULL
:
2861 case USB_SPEED_HIGH
:
2868 monitor_printf(mon
, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2869 0, dev
->addr
, speed_str
, dev
->devname
);
2873 /***********************************************************/
2874 /* PCMCIA/Cardbus */
2876 static struct pcmcia_socket_entry_s
{
2877 struct pcmcia_socket_s
*socket
;
2878 struct pcmcia_socket_entry_s
*next
;
2879 } *pcmcia_sockets
= 0;
2881 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
2883 struct pcmcia_socket_entry_s
*entry
;
2885 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2886 entry
->socket
= socket
;
2887 entry
->next
= pcmcia_sockets
;
2888 pcmcia_sockets
= entry
;
2891 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
2893 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2895 ptr
= &pcmcia_sockets
;
2896 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2897 if (entry
->socket
== socket
) {
2903 void pcmcia_info(Monitor
*mon
)
2905 struct pcmcia_socket_entry_s
*iter
;
2907 if (!pcmcia_sockets
)
2908 monitor_printf(mon
, "No PCMCIA sockets\n");
2910 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2911 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2912 iter
->socket
->attached
? iter
->socket
->card_string
:
2916 /***********************************************************/
2917 /* register display */
2919 struct DisplayAllocator default_allocator
= {
2920 defaultallocator_create_displaysurface
,
2921 defaultallocator_resize_displaysurface
,
2922 defaultallocator_free_displaysurface
2925 void register_displaystate(DisplayState
*ds
)
2935 DisplayState
*get_displaystate(void)
2937 return display_state
;
2940 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
2942 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
2943 return ds
->allocator
;
2948 static void dumb_display_init(void)
2950 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
2951 ds
->allocator
= &default_allocator
;
2952 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
2953 register_displaystate(ds
);
2956 /***********************************************************/
2959 typedef struct IOHandlerRecord
{
2961 IOCanRWHandler
*fd_read_poll
;
2963 IOHandler
*fd_write
;
2966 /* temporary data */
2968 struct IOHandlerRecord
*next
;
2971 static IOHandlerRecord
*first_io_handler
;
2973 /* XXX: fd_read_poll should be suppressed, but an API change is
2974 necessary in the character devices to suppress fd_can_read(). */
2975 int qemu_set_fd_handler2(int fd
,
2976 IOCanRWHandler
*fd_read_poll
,
2978 IOHandler
*fd_write
,
2981 IOHandlerRecord
**pioh
, *ioh
;
2983 if (!fd_read
&& !fd_write
) {
2984 pioh
= &first_io_handler
;
2989 if (ioh
->fd
== fd
) {
2996 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3000 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
3001 ioh
->next
= first_io_handler
;
3002 first_io_handler
= ioh
;
3005 ioh
->fd_read_poll
= fd_read_poll
;
3006 ioh
->fd_read
= fd_read
;
3007 ioh
->fd_write
= fd_write
;
3008 ioh
->opaque
= opaque
;
3015 int qemu_set_fd_handler(int fd
,
3017 IOHandler
*fd_write
,
3020 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
3024 /***********************************************************/
3025 /* Polling handling */
3027 typedef struct PollingEntry
{
3030 struct PollingEntry
*next
;
3033 static PollingEntry
*first_polling_entry
;
3035 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
3037 PollingEntry
**ppe
, *pe
;
3038 pe
= qemu_mallocz(sizeof(PollingEntry
));
3040 pe
->opaque
= opaque
;
3041 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
3046 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
3048 PollingEntry
**ppe
, *pe
;
3049 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
3051 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
3059 /***********************************************************/
3060 /* Wait objects support */
3061 typedef struct WaitObjects
{
3063 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
3064 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
3065 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
3068 static WaitObjects wait_objects
= {0};
3070 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
3072 WaitObjects
*w
= &wait_objects
;
3074 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
3076 w
->events
[w
->num
] = handle
;
3077 w
->func
[w
->num
] = func
;
3078 w
->opaque
[w
->num
] = opaque
;
3083 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
3086 WaitObjects
*w
= &wait_objects
;
3089 for (i
= 0; i
< w
->num
; i
++) {
3090 if (w
->events
[i
] == handle
)
3093 w
->events
[i
] = w
->events
[i
+ 1];
3094 w
->func
[i
] = w
->func
[i
+ 1];
3095 w
->opaque
[i
] = w
->opaque
[i
+ 1];
3103 /***********************************************************/
3104 /* ram save/restore */
3106 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
3110 v
= qemu_get_byte(f
);
3113 if (qemu_get_buffer(f
, buf
, len
) != len
)
3117 v
= qemu_get_byte(f
);
3118 memset(buf
, v
, len
);
3124 if (qemu_file_has_error(f
))
3130 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
3135 if (qemu_get_be32(f
) != phys_ram_size
)
3137 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
3138 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3140 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
3147 #define BDRV_HASH_BLOCK_SIZE 1024
3148 #define IOBUF_SIZE 4096
3149 #define RAM_CBLOCK_MAGIC 0xfabe
3151 typedef struct RamDecompressState
{
3154 uint8_t buf
[IOBUF_SIZE
];
3155 } RamDecompressState
;
3157 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
3160 memset(s
, 0, sizeof(*s
));
3162 ret
= inflateInit(&s
->zstream
);
3168 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
3172 s
->zstream
.avail_out
= len
;
3173 s
->zstream
.next_out
= buf
;
3174 while (s
->zstream
.avail_out
> 0) {
3175 if (s
->zstream
.avail_in
== 0) {
3176 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
3178 clen
= qemu_get_be16(s
->f
);
3179 if (clen
> IOBUF_SIZE
)
3181 qemu_get_buffer(s
->f
, s
->buf
, clen
);
3182 s
->zstream
.avail_in
= clen
;
3183 s
->zstream
.next_in
= s
->buf
;
3185 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
3186 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
3193 static void ram_decompress_close(RamDecompressState
*s
)
3195 inflateEnd(&s
->zstream
);
3198 #define RAM_SAVE_FLAG_FULL 0x01
3199 #define RAM_SAVE_FLAG_COMPRESS 0x02
3200 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3201 #define RAM_SAVE_FLAG_PAGE 0x08
3202 #define RAM_SAVE_FLAG_EOS 0x10
3204 static int is_dup_page(uint8_t *page
, uint8_t ch
)
3206 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
3207 uint32_t *array
= (uint32_t *)page
;
3210 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
3211 if (array
[i
] != val
)
3218 static int ram_save_block(QEMUFile
*f
)
3220 static ram_addr_t current_addr
= 0;
3221 ram_addr_t saved_addr
= current_addr
;
3222 ram_addr_t addr
= 0;
3225 while (addr
< phys_ram_size
) {
3226 if (kvm_enabled() && current_addr
== 0)
3227 kvm_update_dirty_pages_log(); /* FIXME: propagate errors */
3228 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
3231 cpu_physical_memory_reset_dirty(current_addr
,
3232 current_addr
+ TARGET_PAGE_SIZE
,
3233 MIGRATION_DIRTY_FLAG
);
3235 ch
= *(phys_ram_base
+ current_addr
);
3237 if (is_dup_page(phys_ram_base
+ current_addr
, ch
)) {
3238 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
3239 qemu_put_byte(f
, ch
);
3241 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
3242 qemu_put_buffer(f
, phys_ram_base
+ current_addr
, TARGET_PAGE_SIZE
);
3248 addr
+= TARGET_PAGE_SIZE
;
3249 current_addr
= (saved_addr
+ addr
) % phys_ram_size
;
3255 static ram_addr_t ram_save_threshold
= 10;
3257 static ram_addr_t
ram_save_remaining(void)
3260 ram_addr_t count
= 0;
3262 for (addr
= 0; addr
< phys_ram_size
; addr
+= TARGET_PAGE_SIZE
) {
3263 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3270 static int ram_save_live(QEMUFile
*f
, int stage
, void *opaque
)
3275 /* Make sure all dirty bits are set */
3276 for (addr
= 0; addr
< phys_ram_size
; addr
+= TARGET_PAGE_SIZE
) {
3277 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3278 cpu_physical_memory_set_dirty(addr
);
3281 /* Enable dirty memory tracking */
3282 cpu_physical_memory_set_dirty_tracking(1);
3284 qemu_put_be64(f
, phys_ram_size
| RAM_SAVE_FLAG_MEM_SIZE
);
3287 while (!qemu_file_rate_limit(f
)) {
3290 ret
= ram_save_block(f
);
3291 if (ret
== 0) /* no more blocks */
3295 /* try transferring iterative blocks of memory */
3298 cpu_physical_memory_set_dirty_tracking(0);
3300 /* flush all remaining blocks regardless of rate limiting */
3301 while (ram_save_block(f
) != 0);
3304 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3306 return (stage
== 2) && (ram_save_remaining() < ram_save_threshold
);
3309 static int ram_load_dead(QEMUFile
*f
, void *opaque
)
3311 RamDecompressState s1
, *s
= &s1
;
3315 if (ram_decompress_open(s
, f
) < 0)
3317 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
3318 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3320 if (ram_decompress_buf(s
, buf
, 1) < 0) {
3321 fprintf(stderr
, "Error while reading ram block header\n");
3325 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
3326 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
3331 printf("Error block header\n");
3335 ram_decompress_close(s
);
3340 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
3345 if (version_id
== 1)
3346 return ram_load_v1(f
, opaque
);
3348 if (version_id
== 2) {
3349 if (qemu_get_be32(f
) != phys_ram_size
)
3351 return ram_load_dead(f
, opaque
);
3354 if (version_id
!= 3)
3358 addr
= qemu_get_be64(f
);
3360 flags
= addr
& ~TARGET_PAGE_MASK
;
3361 addr
&= TARGET_PAGE_MASK
;
3363 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
3364 if (addr
!= phys_ram_size
)
3368 if (flags
& RAM_SAVE_FLAG_FULL
) {
3369 if (ram_load_dead(f
, opaque
) < 0)
3373 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
3374 uint8_t ch
= qemu_get_byte(f
);
3375 memset(phys_ram_base
+ addr
, ch
, TARGET_PAGE_SIZE
);
3376 } else if (flags
& RAM_SAVE_FLAG_PAGE
)
3377 qemu_get_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
3378 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
3383 void qemu_service_io(void)
3385 CPUState
*env
= cpu_single_env
;
3389 if (env
->kqemu_enabled
) {
3390 kqemu_cpu_interrupt(env
);
3396 /***********************************************************/
3397 /* bottom halves (can be seen as timers which expire ASAP) */
3408 static QEMUBH
*first_bh
= NULL
;
3410 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
3413 bh
= qemu_mallocz(sizeof(QEMUBH
));
3415 bh
->opaque
= opaque
;
3416 bh
->next
= first_bh
;
3421 int qemu_bh_poll(void)
3427 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3428 if (!bh
->deleted
&& bh
->scheduled
) {
3437 /* remove deleted bhs */
3451 void qemu_bh_schedule_idle(QEMUBH
*bh
)
3459 void qemu_bh_schedule(QEMUBH
*bh
)
3461 CPUState
*env
= cpu_single_env
;
3466 /* stop the currently executing CPU to execute the BH ASAP */
3473 void qemu_bh_cancel(QEMUBH
*bh
)
3478 void qemu_bh_delete(QEMUBH
*bh
)
3484 static void qemu_bh_update_timeout(int *timeout
)
3488 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3489 if (!bh
->deleted
&& bh
->scheduled
) {
3491 /* idle bottom halves will be polled at least
3493 *timeout
= MIN(10, *timeout
);
3495 /* non-idle bottom halves will be executed
3504 /***********************************************************/
3505 /* machine registration */
3507 static QEMUMachine
*first_machine
= NULL
;
3508 QEMUMachine
*current_machine
= NULL
;
3510 int qemu_register_machine(QEMUMachine
*m
)
3513 pm
= &first_machine
;
3521 static QEMUMachine
*find_machine(const char *name
)
3525 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3526 if (!strcmp(m
->name
, name
))
3532 /***********************************************************/
3533 /* main execution loop */
3535 static void gui_update(void *opaque
)
3537 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3538 DisplayState
*ds
= opaque
;
3539 DisplayChangeListener
*dcl
= ds
->listeners
;
3543 while (dcl
!= NULL
) {
3544 if (dcl
->gui_timer_interval
&&
3545 dcl
->gui_timer_interval
< interval
)
3546 interval
= dcl
->gui_timer_interval
;
3549 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3552 static void nographic_update(void *opaque
)
3554 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3556 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3559 struct vm_change_state_entry
{
3560 VMChangeStateHandler
*cb
;
3562 LIST_ENTRY (vm_change_state_entry
) entries
;
3565 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3567 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3570 VMChangeStateEntry
*e
;
3572 e
= qemu_mallocz(sizeof (*e
));
3576 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3580 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3582 LIST_REMOVE (e
, entries
);
3586 static void vm_state_notify(int running
, int reason
)
3588 VMChangeStateEntry
*e
;
3590 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3591 e
->cb(e
->opaque
, running
, reason
);
3600 vm_state_notify(1, 0);
3602 qemu_kvm_resume_all_threads();
3603 qemu_rearm_alarm_timer(alarm_timer
);
3607 void vm_stop(int reason
)
3610 cpu_disable_ticks();
3613 qemu_kvm_pause_all_threads();
3614 vm_state_notify(0, reason
);
3618 /* reset/shutdown handler */
3620 typedef struct QEMUResetEntry
{
3621 QEMUResetHandler
*func
;
3623 struct QEMUResetEntry
*next
;
3626 static QEMUResetEntry
*first_reset_entry
;
3627 static int reset_requested
;
3628 static int shutdown_requested
;
3629 static int powerdown_requested
;
3631 int qemu_shutdown_requested(void)
3633 int r
= shutdown_requested
;
3634 shutdown_requested
= 0;
3638 int qemu_reset_requested(void)
3640 int r
= reset_requested
;
3641 reset_requested
= 0;
3645 int qemu_powerdown_requested(void)
3647 int r
= powerdown_requested
;
3648 powerdown_requested
= 0;
3652 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3654 QEMUResetEntry
**pre
, *re
;
3656 pre
= &first_reset_entry
;
3657 while (*pre
!= NULL
)
3658 pre
= &(*pre
)->next
;
3659 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3661 re
->opaque
= opaque
;
3666 void qemu_system_reset(void)
3670 /* reset all devices */
3671 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
3672 re
->func(re
->opaque
);
3676 void qemu_system_reset_request(void)
3679 shutdown_requested
= 1;
3681 reset_requested
= 1;
3683 if (cpu_single_env
) {
3684 qemu_kvm_cpu_stop(cpu_single_env
);
3685 cpu_exit(cpu_single_env
);
3689 void qemu_system_shutdown_request(void)
3691 shutdown_requested
= 1;
3693 cpu_exit(cpu_single_env
);
3696 void qemu_system_powerdown_request(void)
3698 powerdown_requested
= 1;
3700 cpu_exit(cpu_single_env
);
3703 static int qemu_select(int max_fd
, fd_set
*rfds
, fd_set
*wfds
, fd_set
*xfds
,
3708 /* KVM holds a mutex while QEMU code is running, we need hooks to
3709 release the mutex whenever QEMU code sleeps. */
3713 ret
= select(max_fd
, rfds
, wfds
, xfds
, tv
);
3721 static void host_main_loop_wait(int *timeout
)
3727 /* XXX: need to suppress polling by better using win32 events */
3729 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
3730 ret
|= pe
->func(pe
->opaque
);
3734 WaitObjects
*w
= &wait_objects
;
3736 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
3737 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
3738 if (w
->func
[ret
- WAIT_OBJECT_0
])
3739 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
3741 /* Check for additional signaled events */
3742 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
3744 /* Check if event is signaled */
3745 ret2
= WaitForSingleObject(w
->events
[i
], 0);
3746 if(ret2
== WAIT_OBJECT_0
) {
3748 w
->func
[i
](w
->opaque
[i
]);
3749 } else if (ret2
== WAIT_TIMEOUT
) {
3751 err
= GetLastError();
3752 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
3755 } else if (ret
== WAIT_TIMEOUT
) {
3757 err
= GetLastError();
3758 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
3765 static void host_main_loop_wait(int *timeout
)
3770 void main_loop_wait(int timeout
)
3772 IOHandlerRecord
*ioh
;
3773 fd_set rfds
, wfds
, xfds
;
3777 qemu_bh_update_timeout(&timeout
);
3779 host_main_loop_wait(&timeout
);
3781 /* poll any events */
3782 /* XXX: separate device handlers from system ones */
3787 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3791 (!ioh
->fd_read_poll
||
3792 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
3793 FD_SET(ioh
->fd
, &rfds
);
3797 if (ioh
->fd_write
) {
3798 FD_SET(ioh
->fd
, &wfds
);
3804 tv
.tv_sec
= timeout
/ 1000;
3805 tv
.tv_usec
= (timeout
% 1000) * 1000;
3807 #if defined(CONFIG_SLIRP)
3808 if (slirp_is_inited()) {
3809 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
3812 ret
= qemu_select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
3814 IOHandlerRecord
**pioh
;
3816 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3817 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
3818 ioh
->fd_read(ioh
->opaque
);
3819 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
3820 FD_CLR(ioh
->fd
, &rfds
);
3822 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
3823 ioh
->fd_write(ioh
->opaque
);
3827 /* remove deleted IO handlers */
3828 pioh
= &first_io_handler
;
3838 #if defined(CONFIG_SLIRP)
3839 if (slirp_is_inited()) {
3845 slirp_select_poll(&rfds
, &wfds
, &xfds
);
3849 /* vm time timers */
3850 if (vm_running
&& (!cur_cpu
3851 || likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
))))
3852 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
3853 qemu_get_clock(vm_clock
));
3855 /* real time timers */
3856 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
3857 qemu_get_clock(rt_clock
));
3859 /* Check bottom-halves last in case any of the earlier events triggered
3865 static int main_loop(void)
3868 #ifdef CONFIG_PROFILER
3874 if (kvm_enabled()) {
3876 cpu_disable_ticks();
3880 cur_cpu
= first_cpu
;
3881 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
3888 #ifdef CONFIG_PROFILER
3889 ti
= profile_getclock();
3894 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
3895 env
->icount_decr
.u16
.low
= 0;
3896 env
->icount_extra
= 0;
3897 count
= qemu_next_deadline();
3898 count
= (count
+ (1 << icount_time_shift
) - 1)
3899 >> icount_time_shift
;
3900 qemu_icount
+= count
;
3901 decr
= (count
> 0xffff) ? 0xffff : count
;
3903 env
->icount_decr
.u16
.low
= decr
;
3904 env
->icount_extra
= count
;
3906 ret
= cpu_exec(env
);
3907 #ifdef CONFIG_PROFILER
3908 qemu_time
+= profile_getclock() - ti
;
3911 /* Fold pending instructions back into the
3912 instruction counter, and clear the interrupt flag. */
3913 qemu_icount
-= (env
->icount_decr
.u16
.low
3914 + env
->icount_extra
);
3915 env
->icount_decr
.u32
= 0;
3916 env
->icount_extra
= 0;
3918 next_cpu
= env
->next_cpu
?: first_cpu
;
3919 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
3920 ret
= EXCP_INTERRUPT
;
3924 if (ret
== EXCP_HLT
) {
3925 /* Give the next CPU a chance to run. */
3929 if (ret
!= EXCP_HALTED
)
3931 /* all CPUs are halted ? */
3937 if (shutdown_requested
) {
3938 ret
= EXCP_INTERRUPT
;
3946 if (reset_requested
) {
3947 reset_requested
= 0;
3948 qemu_system_reset();
3950 kvm_load_registers(env
);
3951 ret
= EXCP_INTERRUPT
;
3953 if (powerdown_requested
) {
3954 powerdown_requested
= 0;
3955 qemu_system_powerdown();
3956 ret
= EXCP_INTERRUPT
;
3958 #ifdef CONFIG_GDBSTUB
3959 if (unlikely(ret
== EXCP_DEBUG
)) {
3960 gdb_set_stop_cpu(cur_cpu
);
3961 vm_stop(EXCP_DEBUG
);
3964 /* If all cpus are halted then wait until the next IRQ */
3965 /* XXX: use timeout computed from timers */
3966 if (ret
== EXCP_HALTED
) {
3970 /* Advance virtual time to the next event. */
3971 if (use_icount
== 1) {
3972 /* When not using an adaptive execution frequency
3973 we tend to get badly out of sync with real time,
3974 so just delay for a reasonable amount of time. */
3977 delta
= cpu_get_icount() - cpu_get_clock();
3980 /* If virtual time is ahead of real time then just
3982 timeout
= (delta
/ 1000000) + 1;
3984 /* Wait for either IO to occur or the next
3986 add
= qemu_next_deadline();
3987 /* We advance the timer before checking for IO.
3988 Limit the amount we advance so that early IO
3989 activity won't get the guest too far ahead. */
3993 add
= (add
+ (1 << icount_time_shift
) - 1)
3994 >> icount_time_shift
;
3996 timeout
= delta
/ 1000000;
4007 if (shutdown_requested
) {
4008 ret
= EXCP_INTERRUPT
;
4013 #ifdef CONFIG_PROFILER
4014 ti
= profile_getclock();
4016 main_loop_wait(timeout
);
4017 #ifdef CONFIG_PROFILER
4018 dev_time
+= profile_getclock() - ti
;
4021 cpu_disable_ticks();
4025 static void help(int exitcode
)
4027 printf("QEMU PC emulator version " QEMU_VERSION
" (" KVM_VERSION
")"
4028 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
4029 "usage: %s [options] [disk_image]\n"
4031 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4033 #define DEF(option, opt_arg, opt_enum, opt_help) \
4035 #define DEFHEADING(text) stringify(text) "\n"
4036 #include "qemu-options.h"
4041 "During emulation, the following keys are useful:\n"
4042 "ctrl-alt-f toggle full screen\n"
4043 "ctrl-alt-n switch to virtual console 'n'\n"
4044 "ctrl-alt toggle mouse and keyboard grab\n"
4046 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4051 DEFAULT_NETWORK_SCRIPT
,
4052 DEFAULT_NETWORK_DOWN_SCRIPT
,
4054 DEFAULT_GDBSTUB_PORT
,
4059 #define HAS_ARG 0x0001
4062 #define DEF(option, opt_arg, opt_enum, opt_help) \
4064 #define DEFHEADING(text)
4065 #include "qemu-options.h"
4071 typedef struct QEMUOption
{
4077 static const QEMUOption qemu_options
[] = {
4078 { "h", 0, QEMU_OPTION_h
},
4079 #define DEF(option, opt_arg, opt_enum, opt_help) \
4080 { option, opt_arg, opt_enum },
4081 #define DEFHEADING(text)
4082 #include "qemu-options.h"
4090 struct soundhw soundhw
[] = {
4091 #ifdef HAS_AUDIO_CHOICE
4092 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4098 { .init_isa
= pcspk_audio_init
}
4105 "Creative Sound Blaster 16",
4108 { .init_isa
= SB16_init
}
4112 #ifdef CONFIG_CS4231A
4118 { .init_isa
= cs4231a_init
}
4126 "Yamaha YMF262 (OPL3)",
4128 "Yamaha YM3812 (OPL2)",
4132 { .init_isa
= Adlib_init
}
4139 "Gravis Ultrasound GF1",
4142 { .init_isa
= GUS_init
}
4149 "Intel 82801AA AC97 Audio",
4152 { .init_pci
= ac97_init
}
4156 #ifdef CONFIG_ES1370
4159 "ENSONIQ AudioPCI ES1370",
4162 { .init_pci
= es1370_init
}
4166 #endif /* HAS_AUDIO_CHOICE */
4168 { NULL
, NULL
, 0, 0, { NULL
} }
4171 static void select_soundhw (const char *optarg
)
4175 if (*optarg
== '?') {
4178 printf ("Valid sound card names (comma separated):\n");
4179 for (c
= soundhw
; c
->name
; ++c
) {
4180 printf ("%-11s %s\n", c
->name
, c
->descr
);
4182 printf ("\n-soundhw all will enable all of the above\n");
4183 exit (*optarg
!= '?');
4191 if (!strcmp (optarg
, "all")) {
4192 for (c
= soundhw
; c
->name
; ++c
) {
4200 e
= strchr (p
, ',');
4201 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4203 for (c
= soundhw
; c
->name
; ++c
) {
4204 if (!strncmp (c
->name
, p
, l
)) {
4213 "Unknown sound card name (too big to show)\n");
4216 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4221 p
+= l
+ (e
!= NULL
);
4225 goto show_valid_cards
;
4230 static void select_vgahw (const char *p
)
4234 if (strstart(p
, "std", &opts
)) {
4235 std_vga_enabled
= 1;
4236 cirrus_vga_enabled
= 0;
4238 } else if (strstart(p
, "cirrus", &opts
)) {
4239 cirrus_vga_enabled
= 1;
4240 std_vga_enabled
= 0;
4242 } else if (strstart(p
, "vmware", &opts
)) {
4243 cirrus_vga_enabled
= 0;
4244 std_vga_enabled
= 0;
4246 } else if (strstart(p
, "none", &opts
)) {
4247 cirrus_vga_enabled
= 0;
4248 std_vga_enabled
= 0;
4252 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4256 const char *nextopt
;
4258 if (strstart(opts
, ",retrace=", &nextopt
)) {
4260 if (strstart(opts
, "dumb", &nextopt
))
4261 vga_retrace_method
= VGA_RETRACE_DUMB
;
4262 else if (strstart(opts
, "precise", &nextopt
))
4263 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4264 else goto invalid_vga
;
4265 } else goto invalid_vga
;
4271 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4273 exit(STATUS_CONTROL_C_EXIT
);
4278 static int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4282 if(strlen(str
) != 36)
4285 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4286 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4287 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4295 #define MAX_NET_CLIENTS 32
4297 static int saved_argc
;
4298 static char **saved_argv
;
4300 void qemu_get_launch_info(int *argc
, char ***argv
, int *opt_daemonize
, const char **opt_incoming
)
4304 *opt_daemonize
= daemonize
;
4305 *opt_incoming
= incoming
;
4310 #define HUGETLBFS_MAGIC 0x958458f6
4312 static long gethugepagesize(const char *path
)
4318 ret
= statfs(path
, &fs
);
4319 } while (ret
!= 0 && errno
== EINTR
);
4326 if (fs
.f_type
!= HUGETLBFS_MAGIC
)
4327 fprintf(stderr
, "Warning: path not on HugeTLBFS: %s\n", path
);
4332 static void *alloc_mem_area(size_t memory
, unsigned long *len
, const char *path
)
4341 if (!kvm_has_sync_mmu()) {
4342 fprintf(stderr
, "host lacks mmu notifiers, disabling --mem-path\n");
4346 if (asprintf(&filename
, "%s/kvm.XXXXXX", path
) == -1)
4349 hpagesize
= gethugepagesize(path
);
4353 fd
= mkstemp(filename
);
4362 memory
= (memory
+hpagesize
-1) & ~(hpagesize
-1);
4365 * ftruncate is not supported by hugetlbfs in older
4366 * hosts, so don't bother checking for errors.
4367 * If anything goes wrong with it under other filesystems,
4370 ftruncate(fd
, memory
);
4373 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4374 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4375 * to sidestep this quirk.
4377 flags
= mem_prealloc
? MAP_POPULATE
|MAP_SHARED
: MAP_PRIVATE
;
4378 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, flags
, fd
, 0);
4380 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
, fd
, 0);
4382 if (area
== MAP_FAILED
) {
4383 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4392 static void *qemu_alloc_physram(unsigned long memory
)
4396 unsigned long map_len
= memory
;
4399 area
= alloc_mem_area(memory
, &map_len
, mem_path
);
4402 area
= qemu_vmalloc(memory
);
4404 if (kvm_setup_guest_memory(area
, map_len
))
4412 static void termsig_handler(int signal
)
4414 qemu_system_shutdown_request();
4417 static void termsig_setup(void)
4419 struct sigaction act
;
4421 memset(&act
, 0, sizeof(act
));
4422 act
.sa_handler
= termsig_handler
;
4423 sigaction(SIGINT
, &act
, NULL
);
4424 sigaction(SIGHUP
, &act
, NULL
);
4425 sigaction(SIGTERM
, &act
, NULL
);
4430 int main(int argc
, char **argv
, char **envp
)
4432 #ifdef CONFIG_GDBSTUB
4434 const char *gdbstub_port
;
4436 uint32_t boot_devices_bitmap
= 0;
4438 int snapshot
, linux_boot
, net_boot
;
4439 const char *initrd_filename
;
4440 const char *kernel_filename
, *kernel_cmdline
;
4441 const char *boot_devices
= "";
4443 DisplayChangeListener
*dcl
;
4444 int cyls
, heads
, secs
, translation
;
4445 const char *net_clients
[MAX_NET_CLIENTS
];
4447 const char *bt_opts
[MAX_BT_CMDLINE
];
4451 const char *r
, *optarg
;
4452 CharDriverState
*monitor_hd
= NULL
;
4453 const char *monitor_device
;
4454 const char *serial_devices
[MAX_SERIAL_PORTS
];
4455 int serial_device_index
;
4456 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
4457 int parallel_device_index
;
4458 const char *virtio_consoles
[MAX_VIRTIO_CONSOLES
];
4459 int virtio_console_index
;
4460 const char *loadvm
= NULL
;
4461 QEMUMachine
*machine
;
4462 const char *cpu_model
;
4463 const char *usb_devices
[MAX_USB_CMDLINE
];
4464 int usb_devices_index
;
4467 const char *pid_file
= NULL
;
4468 const char *incoming
= NULL
;
4470 struct passwd
*pwd
= NULL
;
4471 const char *chroot_dir
= NULL
;
4472 const char *run_as
= NULL
;
4474 qemu_cache_utils_init(envp
);
4476 LIST_INIT (&vm_change_state_head
);
4479 struct sigaction act
;
4480 sigfillset(&act
.sa_mask
);
4482 act
.sa_handler
= SIG_IGN
;
4483 sigaction(SIGPIPE
, &act
, NULL
);
4486 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4487 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4488 QEMU to run on a single CPU */
4493 h
= GetCurrentProcess();
4494 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4495 for(i
= 0; i
< 32; i
++) {
4496 if (mask
& (1 << i
))
4501 SetProcessAffinityMask(h
, mask
);
4507 register_machines();
4508 machine
= first_machine
;
4510 initrd_filename
= NULL
;
4512 vga_ram_size
= VGA_RAM_SIZE
;
4513 #ifdef CONFIG_GDBSTUB
4515 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
4520 kernel_filename
= NULL
;
4521 kernel_cmdline
= "";
4522 cyls
= heads
= secs
= 0;
4523 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4524 monitor_device
= "vc:80Cx24C";
4526 serial_devices
[0] = "vc:80Cx24C";
4527 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
4528 serial_devices
[i
] = NULL
;
4529 serial_device_index
= 0;
4531 parallel_devices
[0] = "vc:80Cx24C";
4532 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
4533 parallel_devices
[i
] = NULL
;
4534 parallel_device_index
= 0;
4536 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++)
4537 virtio_consoles
[i
] = NULL
;
4538 virtio_console_index
= 0;
4540 usb_devices_index
= 0;
4541 assigned_devices_index
= 0;
4560 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
4562 const QEMUOption
*popt
;
4565 /* Treat --foo the same as -foo. */
4568 popt
= qemu_options
;
4571 fprintf(stderr
, "%s: invalid option -- '%s'\n",
4575 if (!strcmp(popt
->name
, r
+ 1))
4579 if (popt
->flags
& HAS_ARG
) {
4580 if (optind
>= argc
) {
4581 fprintf(stderr
, "%s: option '%s' requires an argument\n",
4585 optarg
= argv
[optind
++];
4590 switch(popt
->index
) {
4592 machine
= find_machine(optarg
);
4595 printf("Supported machines are:\n");
4596 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
4597 printf("%-10s %s%s\n",
4599 m
== first_machine
? " (default)" : "");
4601 exit(*optarg
!= '?');
4604 case QEMU_OPTION_cpu
:
4605 /* hw initialization will check this */
4606 if (*optarg
== '?') {
4607 /* XXX: implement xxx_cpu_list for targets that still miss it */
4608 #if defined(cpu_list)
4609 cpu_list(stdout
, &fprintf
);
4616 case QEMU_OPTION_initrd
:
4617 initrd_filename
= optarg
;
4619 case QEMU_OPTION_hda
:
4621 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
4623 hda_index
= drive_add(optarg
, HD_ALIAS
4624 ",cyls=%d,heads=%d,secs=%d%s",
4625 0, cyls
, heads
, secs
,
4626 translation
== BIOS_ATA_TRANSLATION_LBA
?
4628 translation
== BIOS_ATA_TRANSLATION_NONE
?
4629 ",trans=none" : "");
4631 case QEMU_OPTION_hdb
:
4632 case QEMU_OPTION_hdc
:
4633 case QEMU_OPTION_hdd
:
4634 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
4636 case QEMU_OPTION_drive
:
4637 drive_add(NULL
, "%s", optarg
);
4639 case QEMU_OPTION_mtdblock
:
4640 drive_add(optarg
, MTD_ALIAS
);
4642 case QEMU_OPTION_sd
:
4643 drive_add(optarg
, SD_ALIAS
);
4645 case QEMU_OPTION_pflash
:
4646 drive_add(optarg
, PFLASH_ALIAS
);
4648 case QEMU_OPTION_snapshot
:
4651 case QEMU_OPTION_hdachs
:
4655 cyls
= strtol(p
, (char **)&p
, 0);
4656 if (cyls
< 1 || cyls
> 16383)
4661 heads
= strtol(p
, (char **)&p
, 0);
4662 if (heads
< 1 || heads
> 16)
4667 secs
= strtol(p
, (char **)&p
, 0);
4668 if (secs
< 1 || secs
> 63)
4672 if (!strcmp(p
, "none"))
4673 translation
= BIOS_ATA_TRANSLATION_NONE
;
4674 else if (!strcmp(p
, "lba"))
4675 translation
= BIOS_ATA_TRANSLATION_LBA
;
4676 else if (!strcmp(p
, "auto"))
4677 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4680 } else if (*p
!= '\0') {
4682 fprintf(stderr
, "qemu: invalid physical CHS format\n");
4685 if (hda_index
!= -1)
4686 snprintf(drives_opt
[hda_index
].opt
,
4687 sizeof(drives_opt
[hda_index
].opt
),
4688 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
4689 0, cyls
, heads
, secs
,
4690 translation
== BIOS_ATA_TRANSLATION_LBA
?
4692 translation
== BIOS_ATA_TRANSLATION_NONE
?
4693 ",trans=none" : "");
4696 case QEMU_OPTION_nographic
:
4699 #ifdef CONFIG_CURSES
4700 case QEMU_OPTION_curses
:
4704 case QEMU_OPTION_portrait
:
4707 case QEMU_OPTION_kernel
:
4708 kernel_filename
= optarg
;
4710 case QEMU_OPTION_append
:
4711 kernel_cmdline
= optarg
;
4713 case QEMU_OPTION_cdrom
:
4714 drive_add(optarg
, CDROM_ALIAS
);
4716 case QEMU_OPTION_boot
:
4717 boot_devices
= optarg
;
4718 /* We just do some generic consistency checks */
4720 /* Could easily be extended to 64 devices if needed */
4723 boot_devices_bitmap
= 0;
4724 for (p
= boot_devices
; *p
!= '\0'; p
++) {
4725 /* Allowed boot devices are:
4726 * a b : floppy disk drives
4727 * c ... f : IDE disk drives
4728 * g ... m : machine implementation dependant drives
4729 * n ... p : network devices
4730 * It's up to each machine implementation to check
4731 * if the given boot devices match the actual hardware
4732 * implementation and firmware features.
4734 if (*p
< 'a' || *p
> 'q') {
4735 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
4738 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
4740 "Boot device '%c' was given twice\n",*p
);
4743 boot_devices_bitmap
|= 1 << (*p
- 'a');
4747 case QEMU_OPTION_fda
:
4748 case QEMU_OPTION_fdb
:
4749 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
4752 case QEMU_OPTION_no_fd_bootchk
:
4756 case QEMU_OPTION_net
:
4757 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
4758 fprintf(stderr
, "qemu: too many network clients\n");
4761 net_clients
[nb_net_clients
] = optarg
;
4765 case QEMU_OPTION_tftp
:
4766 tftp_prefix
= optarg
;
4768 case QEMU_OPTION_bootp
:
4769 bootp_filename
= optarg
;
4772 case QEMU_OPTION_smb
:
4773 net_slirp_smb(optarg
);
4776 case QEMU_OPTION_redir
:
4777 net_slirp_redir(optarg
);
4780 case QEMU_OPTION_bt
:
4781 if (nb_bt_opts
>= MAX_BT_CMDLINE
) {
4782 fprintf(stderr
, "qemu: too many bluetooth options\n");
4785 bt_opts
[nb_bt_opts
++] = optarg
;
4788 case QEMU_OPTION_audio_help
:
4792 case QEMU_OPTION_soundhw
:
4793 select_soundhw (optarg
);
4799 case QEMU_OPTION_m
: {
4803 value
= strtoul(optarg
, &ptr
, 10);
4805 case 0: case 'M': case 'm':
4812 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
4816 /* On 32-bit hosts, QEMU is limited by virtual address space */
4817 if (value
> (2047 << 20)
4819 && HOST_LONG_BITS
== 32
4822 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
4825 if (value
!= (uint64_t)(ram_addr_t
)value
) {
4826 fprintf(stderr
, "qemu: ram size too large\n");
4835 const CPULogItem
*item
;
4837 mask
= cpu_str_to_log_mask(optarg
);
4839 printf("Log items (comma separated):\n");
4840 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
4841 printf("%-10s %s\n", item
->name
, item
->help
);
4848 #ifdef CONFIG_GDBSTUB
4853 gdbstub_port
= optarg
;
4859 case QEMU_OPTION_bios
:
4867 keyboard_layout
= optarg
;
4870 case QEMU_OPTION_localtime
:
4873 case QEMU_OPTION_vga
:
4874 select_vgahw (optarg
);
4876 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4882 w
= strtol(p
, (char **)&p
, 10);
4885 fprintf(stderr
, "qemu: invalid resolution or depth\n");
4891 h
= strtol(p
, (char **)&p
, 10);
4896 depth
= strtol(p
, (char **)&p
, 10);
4897 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
4898 depth
!= 24 && depth
!= 32)
4900 } else if (*p
== '\0') {
4901 depth
= graphic_depth
;
4908 graphic_depth
= depth
;
4912 case QEMU_OPTION_echr
:
4915 term_escape_char
= strtol(optarg
, &r
, 0);
4917 printf("Bad argument to echr\n");
4920 case QEMU_OPTION_monitor
:
4921 monitor_device
= optarg
;
4923 case QEMU_OPTION_serial
:
4924 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
4925 fprintf(stderr
, "qemu: too many serial ports\n");
4928 serial_devices
[serial_device_index
] = optarg
;
4929 serial_device_index
++;
4931 case QEMU_OPTION_virtiocon
:
4932 if (virtio_console_index
>= MAX_VIRTIO_CONSOLES
) {
4933 fprintf(stderr
, "qemu: too many virtio consoles\n");
4936 virtio_consoles
[virtio_console_index
] = optarg
;
4937 virtio_console_index
++;
4939 case QEMU_OPTION_parallel
:
4940 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
4941 fprintf(stderr
, "qemu: too many parallel ports\n");
4944 parallel_devices
[parallel_device_index
] = optarg
;
4945 parallel_device_index
++;
4947 case QEMU_OPTION_loadvm
:
4950 case QEMU_OPTION_full_screen
:
4954 case QEMU_OPTION_no_frame
:
4957 case QEMU_OPTION_alt_grab
:
4960 case QEMU_OPTION_no_quit
:
4963 case QEMU_OPTION_sdl
:
4967 case QEMU_OPTION_pidfile
:
4971 case QEMU_OPTION_win2k_hack
:
4972 win2k_install_hack
= 1;
4974 case QEMU_OPTION_rtc_td_hack
:
4977 case QEMU_OPTION_acpitable
:
4978 if(acpi_table_add(optarg
) < 0) {
4979 fprintf(stderr
, "Wrong acpi table provided\n");
4985 case QEMU_OPTION_no_kqemu
:
4988 case QEMU_OPTION_kernel_kqemu
:
4993 case QEMU_OPTION_enable_kvm
:
5001 case QEMU_OPTION_no_kvm
:
5004 case QEMU_OPTION_no_kvm_irqchip
: {
5009 case QEMU_OPTION_no_kvm_pit
: {
5013 case QEMU_OPTION_no_kvm_pit_reinjection
: {
5014 kvm_pit_reinject
= 0;
5017 case QEMU_OPTION_enable_nesting
: {
5021 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5022 case QEMU_OPTION_pcidevice
:
5023 if (assigned_devices_index
>= MAX_DEV_ASSIGN_CMDLINE
) {
5024 fprintf(stderr
, "Too many assigned devices\n");
5027 assigned_devices
[assigned_devices_index
] = optarg
;
5028 assigned_devices_index
++;
5032 case QEMU_OPTION_usb
:
5035 case QEMU_OPTION_usbdevice
:
5037 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
5038 fprintf(stderr
, "Too many USB devices\n");
5041 usb_devices
[usb_devices_index
] = optarg
;
5042 usb_devices_index
++;
5044 case QEMU_OPTION_smp
:
5045 smp_cpus
= atoi(optarg
);
5047 fprintf(stderr
, "Invalid number of CPUs\n");
5051 case QEMU_OPTION_vnc
:
5052 vnc_display
= optarg
;
5055 case QEMU_OPTION_no_acpi
:
5058 case QEMU_OPTION_no_hpet
:
5062 case QEMU_OPTION_no_reboot
:
5065 case QEMU_OPTION_no_shutdown
:
5068 case QEMU_OPTION_show_cursor
:
5071 case QEMU_OPTION_uuid
:
5072 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5073 fprintf(stderr
, "Fail to parse UUID string."
5074 " Wrong format.\n");
5079 case QEMU_OPTION_daemonize
:
5083 case QEMU_OPTION_option_rom
:
5084 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5085 fprintf(stderr
, "Too many option ROMs\n");
5088 option_rom
[nb_option_roms
] = optarg
;
5091 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5092 case QEMU_OPTION_semihosting
:
5093 semihosting_enabled
= 1;
5096 case QEMU_OPTION_tdf
:
5099 case QEMU_OPTION_kvm_shadow_memory
:
5100 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
5102 case QEMU_OPTION_mempath
:
5106 case QEMU_OPTION_mem_prealloc
:
5107 mem_prealloc
= !mem_prealloc
;
5110 case QEMU_OPTION_name
:
5113 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5114 case QEMU_OPTION_prom_env
:
5115 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5116 fprintf(stderr
, "Too many prom variables\n");
5119 prom_envs
[nb_prom_envs
] = optarg
;
5123 case QEMU_OPTION_cpu_vendor
:
5124 cpu_vendor_string
= optarg
;
5127 case QEMU_OPTION_old_param
:
5131 case QEMU_OPTION_clock
:
5132 configure_alarms(optarg
);
5134 case QEMU_OPTION_startdate
:
5137 time_t rtc_start_date
;
5138 if (!strcmp(optarg
, "now")) {
5139 rtc_date_offset
= -1;
5141 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
5149 } else if (sscanf(optarg
, "%d-%d-%d",
5152 &tm
.tm_mday
) == 3) {
5161 rtc_start_date
= mktimegm(&tm
);
5162 if (rtc_start_date
== -1) {
5164 fprintf(stderr
, "Invalid date format. Valid format are:\n"
5165 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5168 rtc_date_offset
= time(NULL
) - rtc_start_date
;
5172 case QEMU_OPTION_tb_size
:
5173 tb_size
= strtol(optarg
, NULL
, 0);
5177 case QEMU_OPTION_icount
:
5179 if (strcmp(optarg
, "auto") == 0) {
5180 icount_time_shift
= -1;
5182 icount_time_shift
= strtol(optarg
, NULL
, 0);
5185 case QEMU_OPTION_incoming
:
5189 case QEMU_OPTION_chroot
:
5190 chroot_dir
= optarg
;
5192 case QEMU_OPTION_runas
:
5195 case QEMU_OPTION_nvram
:
5203 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5204 if (kvm_allowed
&& kqemu_allowed
) {
5206 "You can not enable both KVM and kqemu at the same time\n");
5211 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5212 if (smp_cpus
> machine
->max_cpus
) {
5213 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5214 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5220 if (serial_device_index
== 0)
5221 serial_devices
[0] = "stdio";
5222 if (parallel_device_index
== 0)
5223 parallel_devices
[0] = "null";
5224 if (strncmp(monitor_device
, "vc", 2) == 0)
5225 monitor_device
= "stdio";
5232 if (pipe(fds
) == -1)
5243 len
= read(fds
[0], &status
, 1);
5244 if (len
== -1 && (errno
== EINTR
))
5249 else if (status
== 1) {
5250 fprintf(stderr
, "Could not acquire pidfile\n");
5267 signal(SIGTSTP
, SIG_IGN
);
5268 signal(SIGTTOU
, SIG_IGN
);
5269 signal(SIGTTIN
, SIG_IGN
);
5274 if (kvm_enabled()) {
5275 if (kvm_qemu_init() < 0) {
5276 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
5277 #ifdef NO_CPU_EMULATION
5278 fprintf(stderr
, "Compiled with --disable-cpu-emulation, exiting.\n");
5286 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5289 write(fds
[1], &status
, 1);
5291 fprintf(stderr
, "Could not acquire pid file\n");
5299 linux_boot
= (kernel_filename
!= NULL
);
5300 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5302 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5303 fprintf(stderr
, "-append only allowed with -kernel option\n");
5307 if (!linux_boot
&& initrd_filename
!= NULL
) {
5308 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5312 /* boot to floppy or the default cd if no hard disk defined yet */
5313 if (!boot_devices
[0]) {
5314 boot_devices
= "cad";
5316 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5319 if (init_timer_alarm() < 0) {
5320 fprintf(stderr
, "could not initialize alarm timer\n");
5323 if (use_icount
&& icount_time_shift
< 0) {
5325 /* 125MIPS seems a reasonable initial guess at the guest speed.
5326 It will be corrected fairly quickly anyway. */
5327 icount_time_shift
= 3;
5328 init_icount_adjust();
5335 /* init network clients */
5336 if (nb_net_clients
== 0) {
5337 /* if no clients, we use a default config */
5338 net_clients
[nb_net_clients
++] = "nic";
5340 net_clients
[nb_net_clients
++] = "user";
5344 for(i
= 0;i
< nb_net_clients
; i
++) {
5345 if (net_client_parse(net_clients
[i
]) < 0)
5351 /* XXX: this should be moved in the PC machine instantiation code */
5352 if (net_boot
!= 0) {
5354 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
5355 const char *model
= nd_table
[i
].model
;
5357 if (net_boot
& (1 << i
)) {
5360 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
5361 if (get_image_size(buf
) > 0) {
5362 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5363 fprintf(stderr
, "Too many option ROMs\n");
5366 option_rom
[nb_option_roms
] = strdup(buf
);
5373 fprintf(stderr
, "No valid PXE rom found for network device\n");
5379 /* init the bluetooth world */
5380 for (i
= 0; i
< nb_bt_opts
; i
++)
5381 if (bt_parse(bt_opts
[i
]))
5384 /* init the memory */
5385 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
5387 if (machine
->ram_require
& RAMSIZE_FIXED
) {
5389 if (ram_size
< phys_ram_size
) {
5390 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
5391 machine
->name
, (unsigned long long) phys_ram_size
);
5395 phys_ram_size
= ram_size
;
5397 ram_size
= phys_ram_size
;
5400 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5402 phys_ram_size
+= ram_size
;
5405 /* Initialize kvm */
5406 #if defined(TARGET_I386) || defined(TARGET_X86_64)
5407 #define KVM_EXTRA_PAGES 3
5409 #define KVM_EXTRA_PAGES 0
5411 if (kvm_enabled()) {
5412 phys_ram_size
+= KVM_EXTRA_PAGES
* TARGET_PAGE_SIZE
;
5413 if (kvm_qemu_create_context() < 0) {
5414 fprintf(stderr
, "Could not create KVM context\n");
5419 phys_ram_base
= qemu_alloc_physram(phys_ram_size
);
5420 if (!phys_ram_base
) {
5421 fprintf(stderr
, "Could not allocate physical memory\n");
5425 /* init the dynamic translator */
5426 cpu_exec_init_all(tb_size
* 1024 * 1024);
5431 /* we always create the cdrom drive, even if no disk is there */
5433 if (nb_drives_opt
< MAX_DRIVES
)
5434 drive_add(NULL
, CDROM_ALIAS
);
5436 /* we always create at least one floppy */
5438 if (nb_drives_opt
< MAX_DRIVES
)
5439 drive_add(NULL
, FD_ALIAS
, 0);
5441 /* we always create one sd slot, even if no card is in it */
5443 if (nb_drives_opt
< MAX_DRIVES
)
5444 drive_add(NULL
, SD_ALIAS
);
5446 /* open the virtual block devices
5447 * note that migration with device
5448 * hot add/remove is broken.
5450 for(i
= 0; i
< nb_drives_opt
; i
++)
5451 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
5454 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
5455 register_savevm_live("ram", 0, 3, ram_save_live
, NULL
, ram_load
, NULL
);
5458 /* must be after terminal init, SDL library changes signal handlers */
5462 /* Maintain compatibility with multiple stdio monitors */
5463 if (!strcmp(monitor_device
,"stdio")) {
5464 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5465 const char *devname
= serial_devices
[i
];
5466 if (devname
&& !strcmp(devname
,"mon:stdio")) {
5467 monitor_device
= NULL
;
5469 } else if (devname
&& !strcmp(devname
,"stdio")) {
5470 monitor_device
= NULL
;
5471 serial_devices
[i
] = "mon:stdio";
5478 if (kvm_enabled()) {
5481 ret
= kvm_init(smp_cpus
);
5483 fprintf(stderr
, "failed to initialize KVM\n");
5489 if (monitor_device
) {
5490 monitor_hd
= qemu_chr_open("monitor", monitor_device
, NULL
);
5492 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
5497 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5498 const char *devname
= serial_devices
[i
];
5499 if (devname
&& strcmp(devname
, "none")) {
5501 snprintf(label
, sizeof(label
), "serial%d", i
);
5502 serial_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5503 if (!serial_hds
[i
]) {
5504 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
5511 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
5512 const char *devname
= parallel_devices
[i
];
5513 if (devname
&& strcmp(devname
, "none")) {
5515 snprintf(label
, sizeof(label
), "parallel%d", i
);
5516 parallel_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5517 if (!parallel_hds
[i
]) {
5518 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
5525 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
5526 const char *devname
= virtio_consoles
[i
];
5527 if (devname
&& strcmp(devname
, "none")) {
5529 snprintf(label
, sizeof(label
), "virtcon%d", i
);
5530 virtcon_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5531 if (!virtcon_hds
[i
]) {
5532 fprintf(stderr
, "qemu: could not open virtio console '%s'\n",
5542 machine
->init(ram_size
, vga_ram_size
, boot_devices
,
5543 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
5545 current_machine
= machine
;
5547 /* Set KVM's vcpu state to qemu's initial CPUState. */
5548 if (kvm_enabled()) {
5551 ret
= kvm_sync_vcpus();
5553 fprintf(stderr
, "failed to initialize vcpus\n");
5558 /* init USB devices */
5560 for(i
= 0; i
< usb_devices_index
; i
++) {
5561 if (usb_device_add(usb_devices
[i
], 0) < 0) {
5562 fprintf(stderr
, "Warning: could not add USB device %s\n",
5569 dumb_display_init();
5570 /* just use the first displaystate for the moment */
5575 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
5579 #if defined(CONFIG_CURSES)
5581 /* At the moment curses cannot be used with other displays */
5582 curses_display_init(ds
, full_screen
);
5586 if (vnc_display
!= NULL
) {
5587 vnc_display_init(ds
);
5588 if (vnc_display_open(ds
, vnc_display
) < 0)
5591 #if defined(CONFIG_SDL)
5592 if (sdl
|| !vnc_display
)
5593 sdl_display_init(ds
, full_screen
, no_frame
);
5594 #elif defined(CONFIG_COCOA)
5595 if (sdl
|| !vnc_display
)
5596 cocoa_display_init(ds
, full_screen
);
5602 dcl
= ds
->listeners
;
5603 while (dcl
!= NULL
) {
5604 if (dcl
->dpy_refresh
!= NULL
) {
5605 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
5606 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
5611 if (nographic
|| (vnc_display
&& !sdl
)) {
5612 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
5613 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
5616 text_consoles_set_display(display_state
);
5617 qemu_chr_initial_reset();
5619 if (monitor_device
&& monitor_hd
)
5620 monitor_init(monitor_hd
, MONITOR_USE_READLINE
| MONITOR_IS_DEFAULT
);
5622 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5623 const char *devname
= serial_devices
[i
];
5624 if (devname
&& strcmp(devname
, "none")) {
5626 snprintf(label
, sizeof(label
), "serial%d", i
);
5627 if (strstart(devname
, "vc", 0))
5628 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
5632 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
5633 const char *devname
= parallel_devices
[i
];
5634 if (devname
&& strcmp(devname
, "none")) {
5636 snprintf(label
, sizeof(label
), "parallel%d", i
);
5637 if (strstart(devname
, "vc", 0))
5638 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
5642 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
5643 const char *devname
= virtio_consoles
[i
];
5644 if (virtcon_hds
[i
] && devname
) {
5646 snprintf(label
, sizeof(label
), "virtcon%d", i
);
5647 if (strstart(devname
, "vc", 0))
5648 qemu_chr_printf(virtcon_hds
[i
], "virtio console%d\r\n", i
);
5652 #ifdef CONFIG_GDBSTUB
5654 /* XXX: use standard host:port notation and modify options
5656 if (gdbserver_start(gdbstub_port
) < 0) {
5657 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
5665 do_loadvm(cur_mon
, loadvm
);
5668 autostart
= 0; /* fixme how to deal with -daemonize */
5669 qemu_start_incoming_migration(incoming
);
5680 len
= write(fds
[1], &status
, 1);
5681 if (len
== -1 && (errno
== EINTR
))
5688 TFR(fd
= open("/dev/null", O_RDWR
));
5695 pwd
= getpwnam(run_as
);
5697 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
5703 if (chroot(chroot_dir
) < 0) {
5704 fprintf(stderr
, "chroot failed\n");
5711 if (setgid(pwd
->pw_gid
) < 0) {
5712 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
5715 if (setuid(pwd
->pw_uid
) < 0) {
5716 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
5719 if (setuid(0) != -1) {
5720 fprintf(stderr
, "Dropping privileges failed\n");