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;
245 const char *assigned_devices
[MAX_DEV_ASSIGN_CMDLINE
];
246 int assigned_devices_index
;
248 const char *vnc_display
;
249 int acpi_enabled
= 1;
255 int graphic_rotate
= 0;
259 const char *option_rom
[MAX_OPTION_ROMS
];
261 int semihosting_enabled
= 0;
262 int time_drift_fix
= 0;
263 unsigned int kvm_shadow_memory
= 0;
264 const char *mem_path
= NULL
;
266 int mem_prealloc
= 1; /* force preallocation of physical target memory */
269 const char *cpu_vendor_string
;
273 const char *qemu_name
;
275 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
276 unsigned int nb_prom_envs
= 0;
277 const char *prom_envs
[MAX_PROM_ENVS
];
280 const char *nvram
= NULL
;
281 struct drive_opt drives_opt
[MAX_DRIVES
];
283 static CPUState
*cur_cpu
;
284 static CPUState
*next_cpu
;
285 static int event_pending
= 1;
286 /* Conversion factor from emulated instructions to virtual clock ticks. */
287 static int icount_time_shift
;
288 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
289 #define MAX_ICOUNT_SHIFT 10
290 /* Compensate for varying guest execution speed. */
291 static int64_t qemu_icount_bias
;
292 static QEMUTimer
*icount_rt_timer
;
293 static QEMUTimer
*icount_vm_timer
;
294 static QEMUTimer
*nographic_timer
;
296 uint8_t qemu_uuid
[16];
298 /* KVM runs the main loop in a separate thread. If we update one of the lists
299 * that are polled before or after select(), we need to make sure to break out
300 * of the select() to ensure the new item is serviced.
302 static void main_loop_break(void)
305 qemu_kvm_notify_work();
308 /***********************************************************/
309 /* x86 ISA bus support */
311 target_phys_addr_t isa_mem_base
= 0;
314 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
315 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
317 static uint32_t ioport_read(int index
, uint32_t address
)
319 static IOPortReadFunc
*default_func
[3] = {
320 default_ioport_readb
,
321 default_ioport_readw
,
324 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
326 func
= default_func
[index
];
327 return func(ioport_opaque
[address
], address
);
330 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
332 static IOPortWriteFunc
*default_func
[3] = {
333 default_ioport_writeb
,
334 default_ioport_writew
,
335 default_ioport_writel
337 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
339 func
= default_func
[index
];
340 func(ioport_opaque
[address
], address
, data
);
343 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
345 #ifdef DEBUG_UNUSED_IOPORT
346 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
351 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
353 #ifdef DEBUG_UNUSED_IOPORT
354 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
358 /* default is to make two byte accesses */
359 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
362 data
= ioport_read(0, address
);
363 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
364 data
|= ioport_read(0, address
) << 8;
368 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
370 ioport_write(0, address
, data
& 0xff);
371 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
372 ioport_write(0, address
, (data
>> 8) & 0xff);
375 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
377 #ifdef DEBUG_UNUSED_IOPORT
378 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
383 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
385 #ifdef DEBUG_UNUSED_IOPORT
386 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
390 /* size is the word size in byte */
391 int register_ioport_read(int start
, int length
, int size
,
392 IOPortReadFunc
*func
, void *opaque
)
398 } else if (size
== 2) {
400 } else if (size
== 4) {
403 hw_error("register_ioport_read: invalid size");
406 for(i
= start
; i
< start
+ length
; i
+= size
) {
407 ioport_read_table
[bsize
][i
] = func
;
408 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
409 hw_error("register_ioport_read: invalid opaque");
410 ioport_opaque
[i
] = opaque
;
415 /* size is the word size in byte */
416 int register_ioport_write(int start
, int length
, int size
,
417 IOPortWriteFunc
*func
, void *opaque
)
423 } else if (size
== 2) {
425 } else if (size
== 4) {
428 hw_error("register_ioport_write: invalid size");
431 for(i
= start
; i
< start
+ length
; i
+= size
) {
432 ioport_write_table
[bsize
][i
] = func
;
433 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
434 hw_error("register_ioport_write: invalid opaque");
435 ioport_opaque
[i
] = opaque
;
440 void isa_unassign_ioport(int start
, int length
)
444 for(i
= start
; i
< start
+ length
; i
++) {
445 ioport_read_table
[0][i
] = default_ioport_readb
;
446 ioport_read_table
[1][i
] = default_ioport_readw
;
447 ioport_read_table
[2][i
] = default_ioport_readl
;
449 ioport_write_table
[0][i
] = default_ioport_writeb
;
450 ioport_write_table
[1][i
] = default_ioport_writew
;
451 ioport_write_table
[2][i
] = default_ioport_writel
;
453 ioport_opaque
[i
] = NULL
;
457 /***********************************************************/
459 void cpu_outb(CPUState
*env
, int addr
, int val
)
461 LOG_IOPORT("outb: %04x %02x\n", addr
, val
);
462 ioport_write(0, addr
, val
);
465 env
->last_io_time
= cpu_get_time_fast();
469 void cpu_outw(CPUState
*env
, int addr
, int val
)
471 LOG_IOPORT("outw: %04x %04x\n", addr
, val
);
472 ioport_write(1, addr
, val
);
475 env
->last_io_time
= cpu_get_time_fast();
479 void cpu_outl(CPUState
*env
, int addr
, int val
)
481 LOG_IOPORT("outl: %04x %08x\n", addr
, val
);
482 ioport_write(2, addr
, val
);
485 env
->last_io_time
= cpu_get_time_fast();
489 int cpu_inb(CPUState
*env
, int addr
)
492 val
= ioport_read(0, addr
);
493 LOG_IOPORT("inb : %04x %02x\n", addr
, val
);
496 env
->last_io_time
= cpu_get_time_fast();
501 int cpu_inw(CPUState
*env
, int addr
)
504 val
= ioport_read(1, addr
);
505 LOG_IOPORT("inw : %04x %04x\n", addr
, val
);
508 env
->last_io_time
= cpu_get_time_fast();
513 int cpu_inl(CPUState
*env
, int addr
)
516 val
= ioport_read(2, addr
);
517 LOG_IOPORT("inl : %04x %08x\n", addr
, val
);
520 env
->last_io_time
= cpu_get_time_fast();
525 /***********************************************************/
526 void hw_error(const char *fmt
, ...)
532 fprintf(stderr
, "qemu: hardware error: ");
533 vfprintf(stderr
, fmt
, ap
);
534 fprintf(stderr
, "\n");
535 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
536 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
538 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
540 cpu_dump_state(env
, stderr
, fprintf
, 0);
550 static QEMUBalloonEvent
*qemu_balloon_event
;
551 void *qemu_balloon_event_opaque
;
553 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
555 qemu_balloon_event
= func
;
556 qemu_balloon_event_opaque
= opaque
;
559 void qemu_balloon(ram_addr_t target
)
561 if (qemu_balloon_event
)
562 qemu_balloon_event(qemu_balloon_event_opaque
, target
);
565 ram_addr_t
qemu_balloon_status(void)
567 if (qemu_balloon_event
)
568 return qemu_balloon_event(qemu_balloon_event_opaque
, 0);
572 /***********************************************************/
575 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
576 static void *qemu_put_kbd_event_opaque
;
577 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
578 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
580 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
582 qemu_put_kbd_event_opaque
= opaque
;
583 qemu_put_kbd_event
= func
;
586 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
587 void *opaque
, int absolute
,
590 QEMUPutMouseEntry
*s
, *cursor
;
592 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
594 s
->qemu_put_mouse_event
= func
;
595 s
->qemu_put_mouse_event_opaque
= opaque
;
596 s
->qemu_put_mouse_event_absolute
= absolute
;
597 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
600 if (!qemu_put_mouse_event_head
) {
601 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
605 cursor
= qemu_put_mouse_event_head
;
606 while (cursor
->next
!= NULL
)
607 cursor
= cursor
->next
;
610 qemu_put_mouse_event_current
= s
;
615 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
617 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
619 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
622 cursor
= qemu_put_mouse_event_head
;
623 while (cursor
!= NULL
&& cursor
!= entry
) {
625 cursor
= cursor
->next
;
628 if (cursor
== NULL
) // does not exist or list empty
630 else if (prev
== NULL
) { // entry is head
631 qemu_put_mouse_event_head
= cursor
->next
;
632 if (qemu_put_mouse_event_current
== entry
)
633 qemu_put_mouse_event_current
= cursor
->next
;
634 qemu_free(entry
->qemu_put_mouse_event_name
);
639 prev
->next
= entry
->next
;
641 if (qemu_put_mouse_event_current
== entry
)
642 qemu_put_mouse_event_current
= prev
;
644 qemu_free(entry
->qemu_put_mouse_event_name
);
648 void kbd_put_keycode(int keycode
)
650 if (qemu_put_kbd_event
) {
651 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
655 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
657 QEMUPutMouseEvent
*mouse_event
;
658 void *mouse_event_opaque
;
661 if (!qemu_put_mouse_event_current
) {
666 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
668 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
671 if (graphic_rotate
) {
672 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
675 width
= graphic_width
- 1;
676 mouse_event(mouse_event_opaque
,
677 width
- dy
, dx
, dz
, buttons_state
);
679 mouse_event(mouse_event_opaque
,
680 dx
, dy
, dz
, buttons_state
);
684 int kbd_mouse_is_absolute(void)
686 if (!qemu_put_mouse_event_current
)
689 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
692 void do_info_mice(Monitor
*mon
)
694 QEMUPutMouseEntry
*cursor
;
697 if (!qemu_put_mouse_event_head
) {
698 monitor_printf(mon
, "No mouse devices connected\n");
702 monitor_printf(mon
, "Mouse devices available:\n");
703 cursor
= qemu_put_mouse_event_head
;
704 while (cursor
!= NULL
) {
705 monitor_printf(mon
, "%c Mouse #%d: %s\n",
706 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
707 index
, cursor
->qemu_put_mouse_event_name
);
709 cursor
= cursor
->next
;
713 void do_mouse_set(Monitor
*mon
, int index
)
715 QEMUPutMouseEntry
*cursor
;
718 if (!qemu_put_mouse_event_head
) {
719 monitor_printf(mon
, "No mouse devices connected\n");
723 cursor
= qemu_put_mouse_event_head
;
724 while (cursor
!= NULL
&& index
!= i
) {
726 cursor
= cursor
->next
;
730 qemu_put_mouse_event_current
= cursor
;
732 monitor_printf(mon
, "Mouse at given index not found\n");
735 /* compute with 96 bit intermediate result: (a*b)/c */
736 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
741 #ifdef WORDS_BIGENDIAN
751 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
752 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
755 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
759 /***********************************************************/
760 /* real time host monotonic timer */
762 #define QEMU_TIMER_BASE 1000000000LL
766 static int64_t clock_freq
;
768 static void init_get_clock(void)
772 ret
= QueryPerformanceFrequency(&freq
);
774 fprintf(stderr
, "Could not calibrate ticks\n");
777 clock_freq
= freq
.QuadPart
;
780 static int64_t get_clock(void)
783 QueryPerformanceCounter(&ti
);
784 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
789 static int use_rt_clock
;
791 static void init_get_clock(void)
794 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
795 || defined(__DragonFly__)
798 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
805 static int64_t get_clock(void)
807 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
808 || defined(__DragonFly__)
811 clock_gettime(CLOCK_MONOTONIC
, &ts
);
812 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
816 /* XXX: using gettimeofday leads to problems if the date
817 changes, so it should be avoided. */
819 gettimeofday(&tv
, NULL
);
820 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
825 /* Return the virtual CPU time, based on the instruction counter. */
826 static int64_t cpu_get_icount(void)
829 CPUState
*env
= cpu_single_env
;;
830 icount
= qemu_icount
;
833 fprintf(stderr
, "Bad clock read\n");
834 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
836 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
839 /***********************************************************/
840 /* guest cycle counter */
842 static int64_t cpu_ticks_prev
;
843 static int64_t cpu_ticks_offset
;
844 static int64_t cpu_clock_offset
;
845 static int cpu_ticks_enabled
;
847 /* return the host CPU cycle counter and handle stop/restart */
848 int64_t cpu_get_ticks(void)
851 return cpu_get_icount();
853 if (!cpu_ticks_enabled
) {
854 return cpu_ticks_offset
;
857 ticks
= cpu_get_real_ticks();
858 if (cpu_ticks_prev
> ticks
) {
859 /* Note: non increasing ticks may happen if the host uses
861 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
863 cpu_ticks_prev
= ticks
;
864 return ticks
+ cpu_ticks_offset
;
868 /* return the host CPU monotonic timer and handle stop/restart */
869 static int64_t cpu_get_clock(void)
872 if (!cpu_ticks_enabled
) {
873 return cpu_clock_offset
;
876 return ti
+ cpu_clock_offset
;
880 /* enable cpu_get_ticks() */
881 void cpu_enable_ticks(void)
883 if (!cpu_ticks_enabled
) {
884 cpu_ticks_offset
-= cpu_get_real_ticks();
885 cpu_clock_offset
-= get_clock();
886 cpu_ticks_enabled
= 1;
890 /* disable cpu_get_ticks() : the clock is stopped. You must not call
891 cpu_get_ticks() after that. */
892 void cpu_disable_ticks(void)
894 if (cpu_ticks_enabled
) {
895 cpu_ticks_offset
= cpu_get_ticks();
896 cpu_clock_offset
= cpu_get_clock();
897 cpu_ticks_enabled
= 0;
901 /***********************************************************/
904 #define QEMU_TIMER_REALTIME 0
905 #define QEMU_TIMER_VIRTUAL 1
909 /* XXX: add frequency */
917 struct QEMUTimer
*next
;
920 struct qemu_alarm_timer
{
924 int (*start
)(struct qemu_alarm_timer
*t
);
925 void (*stop
)(struct qemu_alarm_timer
*t
);
926 void (*rearm
)(struct qemu_alarm_timer
*t
);
930 #define ALARM_FLAG_DYNTICKS 0x1
931 #define ALARM_FLAG_EXPIRED 0x2
933 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
935 return t
->flags
& ALARM_FLAG_DYNTICKS
;
938 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
940 if (!alarm_has_dynticks(t
))
946 /* TODO: MIN_TIMER_REARM_US should be optimized */
947 #define MIN_TIMER_REARM_US 250
949 static struct qemu_alarm_timer
*alarm_timer
;
951 static int alarm_timer_rfd
, alarm_timer_wfd
;
956 struct qemu_alarm_win32
{
960 } alarm_win32_data
= {0, NULL
, -1};
962 static int win32_start_timer(struct qemu_alarm_timer
*t
);
963 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
964 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
968 static int unix_start_timer(struct qemu_alarm_timer
*t
);
969 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
973 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
974 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
975 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
977 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
978 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
980 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
981 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
983 #endif /* __linux__ */
987 /* Correlation between real and virtual time is always going to be
988 fairly approximate, so ignore small variation.
989 When the guest is idle real and virtual time will be aligned in
991 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
993 static void icount_adjust(void)
998 static int64_t last_delta
;
999 /* If the VM is not running, then do nothing. */
1003 cur_time
= cpu_get_clock();
1004 cur_icount
= qemu_get_clock(vm_clock
);
1005 delta
= cur_icount
- cur_time
;
1006 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1008 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
1009 && icount_time_shift
> 0) {
1010 /* The guest is getting too far ahead. Slow time down. */
1011 icount_time_shift
--;
1014 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
1015 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
1016 /* The guest is getting too far behind. Speed time up. */
1017 icount_time_shift
++;
1020 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
1023 static void icount_adjust_rt(void * opaque
)
1025 qemu_mod_timer(icount_rt_timer
,
1026 qemu_get_clock(rt_clock
) + 1000);
1030 static void icount_adjust_vm(void * opaque
)
1032 qemu_mod_timer(icount_vm_timer
,
1033 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1037 static void init_icount_adjust(void)
1039 /* Have both realtime and virtual time triggers for speed adjustment.
1040 The realtime trigger catches emulated time passing too slowly,
1041 the virtual time trigger catches emulated time passing too fast.
1042 Realtime triggers occur even when idle, so use them less frequently
1043 than VM triggers. */
1044 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
1045 qemu_mod_timer(icount_rt_timer
,
1046 qemu_get_clock(rt_clock
) + 1000);
1047 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
1048 qemu_mod_timer(icount_vm_timer
,
1049 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1052 static struct qemu_alarm_timer alarm_timers
[] = {
1055 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
1056 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
1057 /* HPET - if available - is preferred */
1058 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
1059 /* ...otherwise try RTC */
1060 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1062 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1064 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1065 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1066 {"win32", 0, win32_start_timer
,
1067 win32_stop_timer
, NULL
, &alarm_win32_data
},
1072 static void show_available_alarms(void)
1076 printf("Available alarm timers, in order of precedence:\n");
1077 for (i
= 0; alarm_timers
[i
].name
; i
++)
1078 printf("%s\n", alarm_timers
[i
].name
);
1081 static void configure_alarms(char const *opt
)
1085 int count
= ARRAY_SIZE(alarm_timers
) - 1;
1088 struct qemu_alarm_timer tmp
;
1090 if (!strcmp(opt
, "?")) {
1091 show_available_alarms();
1097 /* Reorder the array */
1098 name
= strtok(arg
, ",");
1100 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1101 if (!strcmp(alarm_timers
[i
].name
, name
))
1106 fprintf(stderr
, "Unknown clock %s\n", name
);
1115 tmp
= alarm_timers
[i
];
1116 alarm_timers
[i
] = alarm_timers
[cur
];
1117 alarm_timers
[cur
] = tmp
;
1121 name
= strtok(NULL
, ",");
1127 /* Disable remaining timers */
1128 for (i
= cur
; i
< count
; i
++)
1129 alarm_timers
[i
].name
= NULL
;
1131 show_available_alarms();
1136 QEMUClock
*rt_clock
;
1137 QEMUClock
*vm_clock
;
1139 static QEMUTimer
*active_timers
[2];
1141 static QEMUClock
*qemu_new_clock(int type
)
1144 clock
= qemu_mallocz(sizeof(QEMUClock
));
1149 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1153 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1156 ts
->opaque
= opaque
;
1160 void qemu_free_timer(QEMUTimer
*ts
)
1165 /* stop a timer, but do not dealloc it */
1166 void qemu_del_timer(QEMUTimer
*ts
)
1170 /* NOTE: this code must be signal safe because
1171 qemu_timer_expired() can be called from a signal. */
1172 pt
= &active_timers
[ts
->clock
->type
];
1185 /* modify the current timer so that it will be fired when current_time
1186 >= expire_time. The corresponding callback will be called. */
1187 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1193 /* add the timer in the sorted list */
1194 /* NOTE: this code must be signal safe because
1195 qemu_timer_expired() can be called from a signal. */
1196 pt
= &active_timers
[ts
->clock
->type
];
1201 if (t
->expire_time
> expire_time
)
1205 ts
->expire_time
= expire_time
;
1209 /* Rearm if necessary */
1210 if (pt
== &active_timers
[ts
->clock
->type
]) {
1211 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1212 qemu_rearm_alarm_timer(alarm_timer
);
1214 /* Interrupt execution to force deadline recalculation. */
1215 if (use_icount
&& cpu_single_env
) {
1216 cpu_exit(cpu_single_env
);
1221 int qemu_timer_pending(QEMUTimer
*ts
)
1224 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1231 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1235 return (timer_head
->expire_time
<= current_time
);
1238 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1244 if (!ts
|| ts
->expire_time
> current_time
)
1246 /* remove timer from the list before calling the callback */
1247 *ptimer_head
= ts
->next
;
1250 /* run the callback (the timer list can be modified) */
1255 int64_t qemu_get_clock(QEMUClock
*clock
)
1257 switch(clock
->type
) {
1258 case QEMU_TIMER_REALTIME
:
1259 return get_clock() / 1000000;
1261 case QEMU_TIMER_VIRTUAL
:
1263 return cpu_get_icount();
1265 return cpu_get_clock();
1270 static void init_timers(void)
1273 ticks_per_sec
= QEMU_TIMER_BASE
;
1274 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1275 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1279 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1281 uint64_t expire_time
;
1283 if (qemu_timer_pending(ts
)) {
1284 expire_time
= ts
->expire_time
;
1288 qemu_put_be64(f
, expire_time
);
1291 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1293 uint64_t expire_time
;
1295 expire_time
= qemu_get_be64(f
);
1296 if (expire_time
!= -1) {
1297 qemu_mod_timer(ts
, expire_time
);
1303 static void timer_save(QEMUFile
*f
, void *opaque
)
1305 if (cpu_ticks_enabled
) {
1306 hw_error("cannot save state if virtual timers are running");
1308 qemu_put_be64(f
, cpu_ticks_offset
);
1309 qemu_put_be64(f
, ticks_per_sec
);
1310 qemu_put_be64(f
, cpu_clock_offset
);
1313 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1315 if (version_id
!= 1 && version_id
!= 2)
1317 if (cpu_ticks_enabled
) {
1320 cpu_ticks_offset
=qemu_get_be64(f
);
1321 ticks_per_sec
=qemu_get_be64(f
);
1322 if (version_id
== 2) {
1323 cpu_clock_offset
=qemu_get_be64(f
);
1329 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1330 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1333 static void host_alarm_handler(int host_signum
)
1337 #define DISP_FREQ 1000
1339 static int64_t delta_min
= INT64_MAX
;
1340 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1342 ti
= qemu_get_clock(vm_clock
);
1343 if (last_clock
!= 0) {
1344 delta
= ti
- last_clock
;
1345 if (delta
< delta_min
)
1347 if (delta
> delta_max
)
1350 if (++count
== DISP_FREQ
) {
1351 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1352 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1353 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1354 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1355 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1357 delta_min
= INT64_MAX
;
1366 alarm_has_dynticks(alarm_timer
) ||
1368 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1369 qemu_get_clock(vm_clock
))) ||
1370 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1371 qemu_get_clock(rt_clock
))) {
1372 CPUState
*env
= next_cpu
;
1375 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1376 SetEvent(data
->host_alarm
);
1378 static const char byte
= 0;
1379 write(alarm_timer_wfd
, &byte
, sizeof(byte
));
1381 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1384 /* stop the currently executing cpu because a timer occured */
1387 if (env
->kqemu_enabled
) {
1388 kqemu_cpu_interrupt(env
);
1396 static int64_t qemu_next_deadline(void)
1400 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1401 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1402 qemu_get_clock(vm_clock
);
1404 /* To avoid problems with overflow limit this to 2^32. */
1414 #if defined(__linux__) || defined(_WIN32)
1415 static uint64_t qemu_next_deadline_dyntick(void)
1423 delta
= (qemu_next_deadline() + 999) / 1000;
1425 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1426 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1427 qemu_get_clock(rt_clock
))*1000;
1428 if (rtdelta
< delta
)
1432 if (delta
< MIN_TIMER_REARM_US
)
1433 delta
= MIN_TIMER_REARM_US
;
1441 /* Sets a specific flag */
1442 static int fcntl_setfl(int fd
, int flag
)
1446 flags
= fcntl(fd
, F_GETFL
);
1450 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1456 #if defined(__linux__)
1458 #define RTC_FREQ 1024
1460 static void enable_sigio_timer(int fd
)
1462 struct sigaction act
;
1465 sigfillset(&act
.sa_mask
);
1467 act
.sa_handler
= host_alarm_handler
;
1469 sigaction(SIGIO
, &act
, NULL
);
1470 fcntl_setfl(fd
, O_ASYNC
);
1471 fcntl(fd
, F_SETOWN
, getpid());
1474 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1476 struct hpet_info info
;
1479 fd
= open("/dev/hpet", O_RDONLY
);
1484 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1486 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1487 "error, but for better emulation accuracy type:\n"
1488 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1492 /* Check capabilities */
1493 r
= ioctl(fd
, HPET_INFO
, &info
);
1497 /* Enable periodic mode */
1498 r
= ioctl(fd
, HPET_EPI
, 0);
1499 if (info
.hi_flags
&& (r
< 0))
1502 /* Enable interrupt */
1503 r
= ioctl(fd
, HPET_IE_ON
, 0);
1507 enable_sigio_timer(fd
);
1508 t
->priv
= (void *)(long)fd
;
1516 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1518 int fd
= (long)t
->priv
;
1523 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1526 unsigned long current_rtc_freq
= 0;
1528 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1531 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1532 if (current_rtc_freq
!= RTC_FREQ
&&
1533 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1534 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1535 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1536 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1539 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1545 enable_sigio_timer(rtc_fd
);
1547 t
->priv
= (void *)(long)rtc_fd
;
1552 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1554 int rtc_fd
= (long)t
->priv
;
1559 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1563 struct sigaction act
;
1565 sigfillset(&act
.sa_mask
);
1567 act
.sa_handler
= host_alarm_handler
;
1569 sigaction(SIGALRM
, &act
, NULL
);
1571 ev
.sigev_value
.sival_int
= 0;
1572 ev
.sigev_notify
= SIGEV_SIGNAL
;
1573 ev
.sigev_signo
= SIGALRM
;
1575 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1576 perror("timer_create");
1578 /* disable dynticks */
1579 fprintf(stderr
, "Dynamic Ticks disabled\n");
1584 t
->priv
= (void *)(long)host_timer
;
1589 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1591 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1593 timer_delete(host_timer
);
1596 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1598 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1599 struct itimerspec timeout
;
1600 int64_t nearest_delta_us
= INT64_MAX
;
1603 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1604 !active_timers
[QEMU_TIMER_VIRTUAL
])
1607 nearest_delta_us
= qemu_next_deadline_dyntick();
1609 /* check whether a timer is already running */
1610 if (timer_gettime(host_timer
, &timeout
)) {
1612 fprintf(stderr
, "Internal timer error: aborting\n");
1615 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1616 if (current_us
&& current_us
<= nearest_delta_us
)
1619 timeout
.it_interval
.tv_sec
= 0;
1620 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1621 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1622 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1623 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1625 fprintf(stderr
, "Internal timer error: aborting\n");
1630 #endif /* defined(__linux__) */
1632 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1634 struct sigaction act
;
1635 struct itimerval itv
;
1639 sigfillset(&act
.sa_mask
);
1641 act
.sa_handler
= host_alarm_handler
;
1643 sigaction(SIGALRM
, &act
, NULL
);
1645 itv
.it_interval
.tv_sec
= 0;
1646 /* for i386 kernel 2.6 to get 1 ms */
1647 itv
.it_interval
.tv_usec
= 999;
1648 itv
.it_value
.tv_sec
= 0;
1649 itv
.it_value
.tv_usec
= 10 * 1000;
1651 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1658 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1660 struct itimerval itv
;
1662 memset(&itv
, 0, sizeof(itv
));
1663 setitimer(ITIMER_REAL
, &itv
, NULL
);
1666 #endif /* !defined(_WIN32) */
1668 static void try_to_rearm_timer(void *opaque
)
1670 struct qemu_alarm_timer
*t
= opaque
;
1674 /* Drain the notify pipe */
1677 len
= read(alarm_timer_rfd
, buffer
, sizeof(buffer
));
1678 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
1681 if (t
->flags
& ALARM_FLAG_EXPIRED
) {
1682 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
1683 qemu_rearm_alarm_timer(alarm_timer
);
1689 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1692 struct qemu_alarm_win32
*data
= t
->priv
;
1695 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1696 if (!data
->host_alarm
) {
1697 perror("Failed CreateEvent");
1701 memset(&tc
, 0, sizeof(tc
));
1702 timeGetDevCaps(&tc
, sizeof(tc
));
1704 if (data
->period
< tc
.wPeriodMin
)
1705 data
->period
= tc
.wPeriodMin
;
1707 timeBeginPeriod(data
->period
);
1709 flags
= TIME_CALLBACK_FUNCTION
;
1710 if (alarm_has_dynticks(t
))
1711 flags
|= TIME_ONESHOT
;
1713 flags
|= TIME_PERIODIC
;
1715 data
->timerId
= timeSetEvent(1, // interval (ms)
1716 data
->period
, // resolution
1717 host_alarm_handler
, // function
1718 (DWORD
)t
, // parameter
1721 if (!data
->timerId
) {
1722 perror("Failed to initialize win32 alarm timer");
1724 timeEndPeriod(data
->period
);
1725 CloseHandle(data
->host_alarm
);
1729 qemu_add_wait_object(data
->host_alarm
, try_to_rearm_timer
, t
);
1734 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1736 struct qemu_alarm_win32
*data
= t
->priv
;
1738 timeKillEvent(data
->timerId
);
1739 timeEndPeriod(data
->period
);
1741 CloseHandle(data
->host_alarm
);
1744 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1746 struct qemu_alarm_win32
*data
= t
->priv
;
1747 uint64_t nearest_delta_us
;
1749 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1750 !active_timers
[QEMU_TIMER_VIRTUAL
])
1753 nearest_delta_us
= qemu_next_deadline_dyntick();
1754 nearest_delta_us
/= 1000;
1756 timeKillEvent(data
->timerId
);
1758 data
->timerId
= timeSetEvent(1,
1762 TIME_ONESHOT
| TIME_PERIODIC
);
1764 if (!data
->timerId
) {
1765 perror("Failed to re-arm win32 alarm timer");
1767 timeEndPeriod(data
->period
);
1768 CloseHandle(data
->host_alarm
);
1775 static int init_timer_alarm(void)
1777 struct qemu_alarm_timer
*t
= NULL
;
1787 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
1791 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
1795 alarm_timer_rfd
= fds
[0];
1796 alarm_timer_wfd
= fds
[1];
1799 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1800 t
= &alarm_timers
[i
];
1813 qemu_set_fd_handler2(alarm_timer_rfd
, NULL
,
1814 try_to_rearm_timer
, NULL
, t
);
1829 static void quit_timers(void)
1831 alarm_timer
->stop(alarm_timer
);
1835 /***********************************************************/
1836 /* host time/date access */
1837 void qemu_get_timedate(struct tm
*tm
, int offset
)
1844 if (rtc_date_offset
== -1) {
1848 ret
= localtime(&ti
);
1850 ti
-= rtc_date_offset
;
1854 memcpy(tm
, ret
, sizeof(struct tm
));
1857 int qemu_timedate_diff(struct tm
*tm
)
1861 if (rtc_date_offset
== -1)
1863 seconds
= mktimegm(tm
);
1865 seconds
= mktime(tm
);
1867 seconds
= mktimegm(tm
) + rtc_date_offset
;
1869 return seconds
- time(NULL
);
1873 static void socket_cleanup(void)
1878 static int socket_init(void)
1883 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1885 err
= WSAGetLastError();
1886 fprintf(stderr
, "WSAStartup: %d\n", err
);
1889 atexit(socket_cleanup
);
1894 const char *get_opt_name(char *buf
, int buf_size
, const char *p
)
1899 while (*p
!= '\0' && *p
!= '=') {
1900 if (q
&& (q
- buf
) < buf_size
- 1)
1910 const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
1915 while (*p
!= '\0') {
1917 if (*(p
+ 1) != ',')
1921 if (q
&& (q
- buf
) < buf_size
- 1)
1931 int get_param_value(char *buf
, int buf_size
,
1932 const char *tag
, const char *str
)
1939 p
= get_opt_name(option
, sizeof(option
), p
);
1943 if (!strcmp(tag
, option
)) {
1944 (void)get_opt_value(buf
, buf_size
, p
);
1947 p
= get_opt_value(NULL
, 0, p
);
1956 int check_params(char *buf
, int buf_size
,
1957 const char * const *params
, const char *str
)
1964 p
= get_opt_name(buf
, buf_size
, p
);
1968 for(i
= 0; params
[i
] != NULL
; i
++)
1969 if (!strcmp(params
[i
], buf
))
1971 if (params
[i
] == NULL
)
1973 p
= get_opt_value(NULL
, 0, p
);
1981 /***********************************************************/
1982 /* Bluetooth support */
1985 static struct HCIInfo
*hci_table
[MAX_NICS
];
1987 static struct bt_vlan_s
{
1988 struct bt_scatternet_s net
;
1990 struct bt_vlan_s
*next
;
1993 /* find or alloc a new bluetooth "VLAN" */
1994 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1996 struct bt_vlan_s
**pvlan
, *vlan
;
1997 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
2001 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
2003 pvlan
= &first_bt_vlan
;
2004 while (*pvlan
!= NULL
)
2005 pvlan
= &(*pvlan
)->next
;
2010 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
2014 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
2019 static struct HCIInfo null_hci
= {
2020 .cmd_send
= null_hci_send
,
2021 .sco_send
= null_hci_send
,
2022 .acl_send
= null_hci_send
,
2023 .bdaddr_set
= null_hci_addr_set
,
2026 struct HCIInfo
*qemu_next_hci(void)
2028 if (cur_hci
== nb_hcis
)
2031 return hci_table
[cur_hci
++];
2034 static struct HCIInfo
*hci_init(const char *str
)
2037 struct bt_scatternet_s
*vlan
= 0;
2039 if (!strcmp(str
, "null"))
2042 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
2044 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
2045 else if (!strncmp(str
, "hci", 3)) {
2048 if (!strncmp(str
+ 3, ",vlan=", 6)) {
2049 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
2054 vlan
= qemu_find_bt_vlan(0);
2056 return bt_new_hci(vlan
);
2059 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
2064 static int bt_hci_parse(const char *str
)
2066 struct HCIInfo
*hci
;
2069 if (nb_hcis
>= MAX_NICS
) {
2070 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
2074 hci
= hci_init(str
);
2083 bdaddr
.b
[5] = 0x56 + nb_hcis
;
2084 hci
->bdaddr_set(hci
, bdaddr
.b
);
2086 hci_table
[nb_hcis
++] = hci
;
2091 static void bt_vhci_add(int vlan_id
)
2093 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
2096 fprintf(stderr
, "qemu: warning: adding a VHCI to "
2097 "an empty scatternet %i\n", vlan_id
);
2099 bt_vhci_init(bt_new_hci(vlan
));
2102 static struct bt_device_s
*bt_device_add(const char *opt
)
2104 struct bt_scatternet_s
*vlan
;
2106 char *endp
= strstr(opt
, ",vlan=");
2107 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
2110 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
2113 vlan_id
= strtol(endp
+ 6, &endp
, 0);
2115 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
2120 vlan
= qemu_find_bt_vlan(vlan_id
);
2123 fprintf(stderr
, "qemu: warning: adding a slave device to "
2124 "an empty scatternet %i\n", vlan_id
);
2126 if (!strcmp(devname
, "keyboard"))
2127 return bt_keyboard_init(vlan
);
2129 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
2133 static int bt_parse(const char *opt
)
2135 const char *endp
, *p
;
2138 if (strstart(opt
, "hci", &endp
)) {
2139 if (!*endp
|| *endp
== ',') {
2141 if (!strstart(endp
, ",vlan=", 0))
2144 return bt_hci_parse(opt
);
2146 } else if (strstart(opt
, "vhci", &endp
)) {
2147 if (!*endp
|| *endp
== ',') {
2149 if (strstart(endp
, ",vlan=", &p
)) {
2150 vlan
= strtol(p
, (char **) &endp
, 0);
2152 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
2156 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
2165 } else if (strstart(opt
, "device:", &endp
))
2166 return !bt_device_add(endp
);
2168 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
2172 /***********************************************************/
2173 /* QEMU Block devices */
2175 #define HD_ALIAS "index=%d,media=disk"
2176 #define CDROM_ALIAS "index=2,media=cdrom"
2177 #define FD_ALIAS "index=%d,if=floppy"
2178 #define PFLASH_ALIAS "if=pflash"
2179 #define MTD_ALIAS "if=mtd"
2180 #define SD_ALIAS "index=0,if=sd"
2182 static int drive_opt_get_free_idx(void)
2186 for (index
= 0; index
< MAX_DRIVES
; index
++)
2187 if (!drives_opt
[index
].used
) {
2188 drives_opt
[index
].used
= 1;
2195 static int drive_get_free_idx(void)
2199 for (index
= 0; index
< MAX_DRIVES
; index
++)
2200 if (!drives_table
[index
].used
) {
2201 drives_table
[index
].used
= 1;
2208 int drive_add(const char *file
, const char *fmt
, ...)
2211 int index
= drive_opt_get_free_idx();
2213 if (nb_drives_opt
>= MAX_DRIVES
|| index
== -1) {
2214 fprintf(stderr
, "qemu: too many drives\n");
2218 drives_opt
[index
].file
= file
;
2220 vsnprintf(drives_opt
[index
].opt
,
2221 sizeof(drives_opt
[0].opt
), fmt
, ap
);
2228 void drive_remove(int index
)
2230 drives_opt
[index
].used
= 0;
2234 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
2238 /* seek interface, bus and unit */
2240 for (index
= 0; index
< MAX_DRIVES
; index
++)
2241 if (drives_table
[index
].type
== type
&&
2242 drives_table
[index
].bus
== bus
&&
2243 drives_table
[index
].unit
== unit
&&
2244 drives_table
[index
].used
)
2250 int drive_get_max_bus(BlockInterfaceType type
)
2256 for (index
= 0; index
< nb_drives
; index
++) {
2257 if(drives_table
[index
].type
== type
&&
2258 drives_table
[index
].bus
> max_bus
)
2259 max_bus
= drives_table
[index
].bus
;
2264 const char *drive_get_serial(BlockDriverState
*bdrv
)
2268 for (index
= 0; index
< nb_drives
; index
++)
2269 if (drives_table
[index
].bdrv
== bdrv
)
2270 return drives_table
[index
].serial
;
2275 BlockInterfaceErrorAction
drive_get_onerror(BlockDriverState
*bdrv
)
2279 for (index
= 0; index
< nb_drives
; index
++)
2280 if (drives_table
[index
].bdrv
== bdrv
)
2281 return drives_table
[index
].onerror
;
2283 return BLOCK_ERR_STOP_ENOSPC
;
2286 static void bdrv_format_print(void *opaque
, const char *name
)
2288 fprintf(stderr
, " %s", name
);
2291 void drive_uninit(BlockDriverState
*bdrv
)
2295 for (i
= 0; i
< MAX_DRIVES
; i
++)
2296 if (drives_table
[i
].bdrv
== bdrv
) {
2297 drives_table
[i
].bdrv
= NULL
;
2298 drives_table
[i
].used
= 0;
2299 drive_remove(drives_table
[i
].drive_opt_idx
);
2305 int drive_init(struct drive_opt
*arg
, int snapshot
, void *opaque
)
2311 const char *mediastr
= "";
2312 BlockInterfaceType type
;
2313 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
2314 int bus_id
, unit_id
;
2315 int cyls
, heads
, secs
, translation
;
2316 BlockDriverState
*bdrv
;
2317 BlockDriver
*drv
= NULL
;
2318 QEMUMachine
*machine
= opaque
;
2322 int bdrv_flags
, onerror
;
2323 int drives_table_idx
;
2324 char *str
= arg
->opt
;
2325 static const char * const params
[] = { "bus", "unit", "if", "index",
2326 "cyls", "heads", "secs", "trans",
2327 "media", "snapshot", "file",
2328 "cache", "format", "serial", "werror",
2331 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
2332 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
2338 cyls
= heads
= secs
= 0;
2341 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2345 if (machine
->use_scsi
) {
2347 max_devs
= MAX_SCSI_DEVS
;
2348 pstrcpy(devname
, sizeof(devname
), "scsi");
2351 max_devs
= MAX_IDE_DEVS
;
2352 pstrcpy(devname
, sizeof(devname
), "ide");
2356 /* extract parameters */
2358 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
2359 bus_id
= strtol(buf
, NULL
, 0);
2361 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
2366 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
2367 unit_id
= strtol(buf
, NULL
, 0);
2369 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
2374 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
2375 pstrcpy(devname
, sizeof(devname
), buf
);
2376 if (!strcmp(buf
, "ide")) {
2378 max_devs
= MAX_IDE_DEVS
;
2379 } else if (!strcmp(buf
, "scsi")) {
2381 max_devs
= MAX_SCSI_DEVS
;
2382 } else if (!strcmp(buf
, "floppy")) {
2385 } else if (!strcmp(buf
, "pflash")) {
2388 } else if (!strcmp(buf
, "mtd")) {
2391 } else if (!strcmp(buf
, "sd")) {
2394 } else if (!strcmp(buf
, "virtio")) {
2398 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
2403 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
2404 index
= strtol(buf
, NULL
, 0);
2406 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
2411 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
2412 cyls
= strtol(buf
, NULL
, 0);
2415 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
2416 heads
= strtol(buf
, NULL
, 0);
2419 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
2420 secs
= strtol(buf
, NULL
, 0);
2423 if (cyls
|| heads
|| secs
) {
2424 if (cyls
< 1 || cyls
> 16383) {
2425 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
2428 if (heads
< 1 || heads
> 16) {
2429 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
2432 if (secs
< 1 || secs
> 63) {
2433 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
2438 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
2441 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2445 if (!strcmp(buf
, "none"))
2446 translation
= BIOS_ATA_TRANSLATION_NONE
;
2447 else if (!strcmp(buf
, "lba"))
2448 translation
= BIOS_ATA_TRANSLATION_LBA
;
2449 else if (!strcmp(buf
, "auto"))
2450 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2452 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
2457 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
2458 if (!strcmp(buf
, "disk")) {
2460 } else if (!strcmp(buf
, "cdrom")) {
2461 if (cyls
|| secs
|| heads
) {
2463 "qemu: '%s' invalid physical CHS format\n", str
);
2466 media
= MEDIA_CDROM
;
2468 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
2473 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
2474 if (!strcmp(buf
, "on"))
2476 else if (!strcmp(buf
, "off"))
2479 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
2484 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
2485 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2487 else if (!strcmp(buf
, "writethrough"))
2489 else if (!strcmp(buf
, "writeback"))
2492 fprintf(stderr
, "qemu: invalid cache option\n");
2497 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
2498 if (strcmp(buf
, "?") == 0) {
2499 fprintf(stderr
, "qemu: Supported formats:");
2500 bdrv_iterate_format(bdrv_format_print
, NULL
);
2501 fprintf(stderr
, "\n");
2504 drv
= bdrv_find_format(buf
);
2506 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2511 if (get_param_value(buf
, sizeof(buf
), "boot", str
)) {
2512 if (!strcmp(buf
, "on")) {
2513 if (extboot_drive
!= -1) {
2514 fprintf(stderr
, "qemu: two bootable drives specified\n");
2517 extboot_drive
= nb_drives
;
2518 } else if (strcmp(buf
, "off")) {
2519 fprintf(stderr
, "qemu: '%s' invalid boot option\n", str
);
2524 if (arg
->file
== NULL
)
2525 get_param_value(file
, sizeof(file
), "file", str
);
2527 pstrcpy(file
, sizeof(file
), arg
->file
);
2529 if (!get_param_value(serial
, sizeof(serial
), "serial", str
))
2530 memset(serial
, 0, sizeof(serial
));
2532 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2533 if (get_param_value(buf
, sizeof(serial
), "werror", str
)) {
2534 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2535 fprintf(stderr
, "werror is no supported by this format\n");
2538 if (!strcmp(buf
, "ignore"))
2539 onerror
= BLOCK_ERR_IGNORE
;
2540 else if (!strcmp(buf
, "enospc"))
2541 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2542 else if (!strcmp(buf
, "stop"))
2543 onerror
= BLOCK_ERR_STOP_ANY
;
2544 else if (!strcmp(buf
, "report"))
2545 onerror
= BLOCK_ERR_REPORT
;
2547 fprintf(stderr
, "qemu: '%s' invalid write error action\n", buf
);
2552 /* compute bus and unit according index */
2555 if (bus_id
!= 0 || unit_id
!= -1) {
2557 "qemu: '%s' index cannot be used with bus and unit\n", str
);
2565 unit_id
= index
% max_devs
;
2566 bus_id
= index
/ max_devs
;
2570 /* if user doesn't specify a unit_id,
2571 * try to find the first free
2574 if (unit_id
== -1) {
2576 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
2578 if (max_devs
&& unit_id
>= max_devs
) {
2579 unit_id
-= max_devs
;
2587 if (max_devs
&& unit_id
>= max_devs
) {
2588 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
2589 str
, unit_id
, max_devs
- 1);
2594 * ignore multiple definitions
2597 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
2602 if (type
== IF_IDE
|| type
== IF_SCSI
)
2603 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2605 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
2606 devname
, bus_id
, mediastr
, unit_id
);
2608 snprintf(buf
, sizeof(buf
), "%s%s%i",
2609 devname
, mediastr
, unit_id
);
2610 bdrv
= bdrv_new(buf
);
2611 drives_table_idx
= drive_get_free_idx();
2612 drives_table
[drives_table_idx
].bdrv
= bdrv
;
2613 drives_table
[drives_table_idx
].type
= type
;
2614 drives_table
[drives_table_idx
].bus
= bus_id
;
2615 drives_table
[drives_table_idx
].unit
= unit_id
;
2616 drives_table
[drives_table_idx
].onerror
= onerror
;
2617 drives_table
[drives_table_idx
].drive_opt_idx
= arg
- drives_opt
;
2618 strncpy(drives_table
[drives_table_idx
].serial
, serial
, sizeof(serial
));
2627 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
2628 bdrv_set_translation_hint(bdrv
, translation
);
2632 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
2637 /* FIXME: This isn't really a floppy, but it's a reasonable
2640 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
2651 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2652 cache
= 2; /* always use write-back with snapshot */
2654 if (cache
== 0) /* no caching */
2655 bdrv_flags
|= BDRV_O_NOCACHE
;
2656 else if (cache
== 2) /* write-back */
2657 bdrv_flags
|= BDRV_O_CACHE_WB
;
2658 else if (cache
== 3) /* not specified */
2659 bdrv_flags
|= BDRV_O_CACHE_DEF
;
2660 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0) {
2661 fprintf(stderr
, "qemu: could not open disk image %s\n",
2665 if (bdrv_key_required(bdrv
))
2667 return drives_table_idx
;
2670 /***********************************************************/
2673 static USBPort
*used_usb_ports
;
2674 static USBPort
*free_usb_ports
;
2676 /* ??? Maybe change this to register a hub to keep track of the topology. */
2677 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
2678 usb_attachfn attach
)
2680 port
->opaque
= opaque
;
2681 port
->index
= index
;
2682 port
->attach
= attach
;
2683 port
->next
= free_usb_ports
;
2684 free_usb_ports
= port
;
2687 int usb_device_add_dev(USBDevice
*dev
)
2691 /* Find a USB port to add the device to. */
2692 port
= free_usb_ports
;
2696 /* Create a new hub and chain it on. */
2697 free_usb_ports
= NULL
;
2698 port
->next
= used_usb_ports
;
2699 used_usb_ports
= port
;
2701 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
2702 usb_attach(port
, hub
);
2703 port
= free_usb_ports
;
2706 free_usb_ports
= port
->next
;
2707 port
->next
= used_usb_ports
;
2708 used_usb_ports
= port
;
2709 usb_attach(port
, dev
);
2713 static void usb_msd_password_cb(void *opaque
, int err
)
2715 USBDevice
*dev
= opaque
;
2718 usb_device_add_dev(dev
);
2720 dev
->handle_destroy(dev
);
2723 static int usb_device_add(const char *devname
, int is_hotplug
)
2728 if (!free_usb_ports
)
2731 if (strstart(devname
, "host:", &p
)) {
2732 dev
= usb_host_device_open(p
);
2733 } else if (!strcmp(devname
, "mouse")) {
2734 dev
= usb_mouse_init();
2735 } else if (!strcmp(devname
, "tablet")) {
2736 dev
= usb_tablet_init();
2737 } else if (!strcmp(devname
, "keyboard")) {
2738 dev
= usb_keyboard_init();
2739 } else if (strstart(devname
, "disk:", &p
)) {
2740 BlockDriverState
*bs
;
2742 dev
= usb_msd_init(p
);
2745 bs
= usb_msd_get_bdrv(dev
);
2746 if (bdrv_key_required(bs
)) {
2749 monitor_read_bdrv_key_start(cur_mon
, bs
, usb_msd_password_cb
,
2754 } else if (!strcmp(devname
, "wacom-tablet")) {
2755 dev
= usb_wacom_init();
2756 } else if (strstart(devname
, "serial:", &p
)) {
2757 dev
= usb_serial_init(p
);
2758 #ifdef CONFIG_BRLAPI
2759 } else if (!strcmp(devname
, "braille")) {
2760 dev
= usb_baum_init();
2762 } else if (strstart(devname
, "net:", &p
)) {
2765 if (net_client_init("nic", p
) < 0)
2767 nd_table
[nic
].model
= "usb";
2768 dev
= usb_net_init(&nd_table
[nic
]);
2769 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2770 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2771 bt_new_hci(qemu_find_bt_vlan(0)));
2778 return usb_device_add_dev(dev
);
2781 int usb_device_del_addr(int bus_num
, int addr
)
2787 if (!used_usb_ports
)
2793 lastp
= &used_usb_ports
;
2794 port
= used_usb_ports
;
2795 while (port
&& port
->dev
->addr
!= addr
) {
2796 lastp
= &port
->next
;
2804 *lastp
= port
->next
;
2805 usb_attach(port
, NULL
);
2806 dev
->handle_destroy(dev
);
2807 port
->next
= free_usb_ports
;
2808 free_usb_ports
= port
;
2812 static int usb_device_del(const char *devname
)
2817 if (strstart(devname
, "host:", &p
))
2818 return usb_host_device_close(p
);
2820 if (!used_usb_ports
)
2823 p
= strchr(devname
, '.');
2826 bus_num
= strtoul(devname
, NULL
, 0);
2827 addr
= strtoul(p
+ 1, NULL
, 0);
2829 return usb_device_del_addr(bus_num
, addr
);
2832 void do_usb_add(Monitor
*mon
, const char *devname
)
2834 usb_device_add(devname
, 1);
2837 void do_usb_del(Monitor
*mon
, const char *devname
)
2839 usb_device_del(devname
);
2842 void usb_info(Monitor
*mon
)
2846 const char *speed_str
;
2849 monitor_printf(mon
, "USB support not enabled\n");
2853 for (port
= used_usb_ports
; port
; port
= port
->next
) {
2857 switch(dev
->speed
) {
2861 case USB_SPEED_FULL
:
2864 case USB_SPEED_HIGH
:
2871 monitor_printf(mon
, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2872 0, dev
->addr
, speed_str
, dev
->devname
);
2876 /***********************************************************/
2877 /* PCMCIA/Cardbus */
2879 static struct pcmcia_socket_entry_s
{
2880 struct pcmcia_socket_s
*socket
;
2881 struct pcmcia_socket_entry_s
*next
;
2882 } *pcmcia_sockets
= 0;
2884 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
2886 struct pcmcia_socket_entry_s
*entry
;
2888 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2889 entry
->socket
= socket
;
2890 entry
->next
= pcmcia_sockets
;
2891 pcmcia_sockets
= entry
;
2894 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
2896 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2898 ptr
= &pcmcia_sockets
;
2899 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2900 if (entry
->socket
== socket
) {
2906 void pcmcia_info(Monitor
*mon
)
2908 struct pcmcia_socket_entry_s
*iter
;
2910 if (!pcmcia_sockets
)
2911 monitor_printf(mon
, "No PCMCIA sockets\n");
2913 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2914 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2915 iter
->socket
->attached
? iter
->socket
->card_string
:
2919 /***********************************************************/
2920 /* register display */
2922 struct DisplayAllocator default_allocator
= {
2923 defaultallocator_create_displaysurface
,
2924 defaultallocator_resize_displaysurface
,
2925 defaultallocator_free_displaysurface
2928 void register_displaystate(DisplayState
*ds
)
2938 DisplayState
*get_displaystate(void)
2940 return display_state
;
2943 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
2945 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
2946 return ds
->allocator
;
2951 static void dumb_display_init(void)
2953 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
2954 ds
->allocator
= &default_allocator
;
2955 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
2956 register_displaystate(ds
);
2959 /***********************************************************/
2962 typedef struct IOHandlerRecord
{
2964 IOCanRWHandler
*fd_read_poll
;
2966 IOHandler
*fd_write
;
2969 /* temporary data */
2971 struct IOHandlerRecord
*next
;
2974 static IOHandlerRecord
*first_io_handler
;
2976 /* XXX: fd_read_poll should be suppressed, but an API change is
2977 necessary in the character devices to suppress fd_can_read(). */
2978 int qemu_set_fd_handler2(int fd
,
2979 IOCanRWHandler
*fd_read_poll
,
2981 IOHandler
*fd_write
,
2984 IOHandlerRecord
**pioh
, *ioh
;
2986 if (!fd_read
&& !fd_write
) {
2987 pioh
= &first_io_handler
;
2992 if (ioh
->fd
== fd
) {
2999 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3003 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
3004 ioh
->next
= first_io_handler
;
3005 first_io_handler
= ioh
;
3008 ioh
->fd_read_poll
= fd_read_poll
;
3009 ioh
->fd_read
= fd_read
;
3010 ioh
->fd_write
= fd_write
;
3011 ioh
->opaque
= opaque
;
3018 int qemu_set_fd_handler(int fd
,
3020 IOHandler
*fd_write
,
3023 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
3027 /***********************************************************/
3028 /* Polling handling */
3030 typedef struct PollingEntry
{
3033 struct PollingEntry
*next
;
3036 static PollingEntry
*first_polling_entry
;
3038 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
3040 PollingEntry
**ppe
, *pe
;
3041 pe
= qemu_mallocz(sizeof(PollingEntry
));
3043 pe
->opaque
= opaque
;
3044 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
3049 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
3051 PollingEntry
**ppe
, *pe
;
3052 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
3054 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
3062 /***********************************************************/
3063 /* Wait objects support */
3064 typedef struct WaitObjects
{
3066 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
3067 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
3068 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
3071 static WaitObjects wait_objects
= {0};
3073 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
3075 WaitObjects
*w
= &wait_objects
;
3077 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
3079 w
->events
[w
->num
] = handle
;
3080 w
->func
[w
->num
] = func
;
3081 w
->opaque
[w
->num
] = opaque
;
3086 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
3089 WaitObjects
*w
= &wait_objects
;
3092 for (i
= 0; i
< w
->num
; i
++) {
3093 if (w
->events
[i
] == handle
)
3096 w
->events
[i
] = w
->events
[i
+ 1];
3097 w
->func
[i
] = w
->func
[i
+ 1];
3098 w
->opaque
[i
] = w
->opaque
[i
+ 1];
3106 /***********************************************************/
3107 /* ram save/restore */
3109 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
3113 v
= qemu_get_byte(f
);
3116 if (qemu_get_buffer(f
, buf
, len
) != len
)
3120 v
= qemu_get_byte(f
);
3121 memset(buf
, v
, len
);
3127 if (qemu_file_has_error(f
))
3133 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
3138 if (qemu_get_be32(f
) != phys_ram_size
)
3140 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
3141 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3143 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
3150 #define BDRV_HASH_BLOCK_SIZE 1024
3151 #define IOBUF_SIZE 4096
3152 #define RAM_CBLOCK_MAGIC 0xfabe
3154 typedef struct RamDecompressState
{
3157 uint8_t buf
[IOBUF_SIZE
];
3158 } RamDecompressState
;
3160 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
3163 memset(s
, 0, sizeof(*s
));
3165 ret
= inflateInit(&s
->zstream
);
3171 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
3175 s
->zstream
.avail_out
= len
;
3176 s
->zstream
.next_out
= buf
;
3177 while (s
->zstream
.avail_out
> 0) {
3178 if (s
->zstream
.avail_in
== 0) {
3179 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
3181 clen
= qemu_get_be16(s
->f
);
3182 if (clen
> IOBUF_SIZE
)
3184 qemu_get_buffer(s
->f
, s
->buf
, clen
);
3185 s
->zstream
.avail_in
= clen
;
3186 s
->zstream
.next_in
= s
->buf
;
3188 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
3189 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
3196 static void ram_decompress_close(RamDecompressState
*s
)
3198 inflateEnd(&s
->zstream
);
3201 #define RAM_SAVE_FLAG_FULL 0x01
3202 #define RAM_SAVE_FLAG_COMPRESS 0x02
3203 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3204 #define RAM_SAVE_FLAG_PAGE 0x08
3205 #define RAM_SAVE_FLAG_EOS 0x10
3207 static int is_dup_page(uint8_t *page
, uint8_t ch
)
3209 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
3210 uint32_t *array
= (uint32_t *)page
;
3213 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
3214 if (array
[i
] != val
)
3221 static int ram_save_block(QEMUFile
*f
)
3223 static ram_addr_t current_addr
= 0;
3224 ram_addr_t saved_addr
= current_addr
;
3225 ram_addr_t addr
= 0;
3228 while (addr
< phys_ram_size
) {
3229 if (kvm_enabled() && current_addr
== 0) {
3231 r
= kvm_update_dirty_pages_log();
3233 fprintf(stderr
, "%s: update dirty pages log failed %d\n", __FUNCTION__
, r
);
3234 qemu_file_set_error(f
);
3238 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
3241 cpu_physical_memory_reset_dirty(current_addr
,
3242 current_addr
+ TARGET_PAGE_SIZE
,
3243 MIGRATION_DIRTY_FLAG
);
3245 ch
= *(phys_ram_base
+ current_addr
);
3247 if (is_dup_page(phys_ram_base
+ current_addr
, ch
)) {
3248 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
3249 qemu_put_byte(f
, ch
);
3251 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
3252 qemu_put_buffer(f
, phys_ram_base
+ current_addr
, TARGET_PAGE_SIZE
);
3258 addr
+= TARGET_PAGE_SIZE
;
3259 current_addr
= (saved_addr
+ addr
) % phys_ram_size
;
3265 static ram_addr_t ram_save_threshold
= 10;
3267 static ram_addr_t
ram_save_remaining(void)
3270 ram_addr_t count
= 0;
3272 for (addr
= 0; addr
< phys_ram_size
; addr
+= TARGET_PAGE_SIZE
) {
3273 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3280 static int ram_save_live(QEMUFile
*f
, int stage
, void *opaque
)
3285 /* Make sure all dirty bits are set */
3286 for (addr
= 0; addr
< phys_ram_size
; addr
+= TARGET_PAGE_SIZE
) {
3287 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3288 cpu_physical_memory_set_dirty(addr
);
3291 /* Enable dirty memory tracking */
3292 cpu_physical_memory_set_dirty_tracking(1);
3294 qemu_put_be64(f
, phys_ram_size
| RAM_SAVE_FLAG_MEM_SIZE
);
3297 while (!qemu_file_rate_limit(f
)) {
3300 ret
= ram_save_block(f
);
3301 if (ret
== 0) /* no more blocks */
3305 /* try transferring iterative blocks of memory */
3309 /* flush all remaining blocks regardless of rate limiting */
3310 while (ram_save_block(f
) != 0);
3311 cpu_physical_memory_set_dirty_tracking(0);
3314 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3316 return (stage
== 2) && (ram_save_remaining() < ram_save_threshold
);
3319 static int ram_load_dead(QEMUFile
*f
, void *opaque
)
3321 RamDecompressState s1
, *s
= &s1
;
3325 if (ram_decompress_open(s
, f
) < 0)
3327 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
3328 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3330 if (ram_decompress_buf(s
, buf
, 1) < 0) {
3331 fprintf(stderr
, "Error while reading ram block header\n");
3335 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
3336 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
3341 printf("Error block header\n");
3345 ram_decompress_close(s
);
3350 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
3355 if (version_id
== 1)
3356 return ram_load_v1(f
, opaque
);
3358 if (version_id
== 2) {
3359 if (qemu_get_be32(f
) != phys_ram_size
)
3361 return ram_load_dead(f
, opaque
);
3364 if (version_id
!= 3)
3368 addr
= qemu_get_be64(f
);
3370 flags
= addr
& ~TARGET_PAGE_MASK
;
3371 addr
&= TARGET_PAGE_MASK
;
3373 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
3374 if (addr
!= phys_ram_size
)
3378 if (flags
& RAM_SAVE_FLAG_FULL
) {
3379 if (ram_load_dead(f
, opaque
) < 0)
3383 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
3384 uint8_t ch
= qemu_get_byte(f
);
3385 memset(phys_ram_base
+ addr
, ch
, TARGET_PAGE_SIZE
);
3386 } else if (flags
& RAM_SAVE_FLAG_PAGE
)
3387 qemu_get_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
3388 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
3393 void qemu_service_io(void)
3395 CPUState
*env
= cpu_single_env
;
3399 if (env
->kqemu_enabled
) {
3400 kqemu_cpu_interrupt(env
);
3406 /***********************************************************/
3407 /* bottom halves (can be seen as timers which expire ASAP) */
3418 static QEMUBH
*first_bh
= NULL
;
3420 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
3423 bh
= qemu_mallocz(sizeof(QEMUBH
));
3425 bh
->opaque
= opaque
;
3426 bh
->next
= first_bh
;
3431 int qemu_bh_poll(void)
3437 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3438 if (!bh
->deleted
&& bh
->scheduled
) {
3447 /* remove deleted bhs */
3461 void qemu_bh_schedule_idle(QEMUBH
*bh
)
3469 void qemu_bh_schedule(QEMUBH
*bh
)
3471 CPUState
*env
= cpu_single_env
;
3476 /* stop the currently executing CPU to execute the BH ASAP */
3483 void qemu_bh_cancel(QEMUBH
*bh
)
3488 void qemu_bh_delete(QEMUBH
*bh
)
3494 static void qemu_bh_update_timeout(int *timeout
)
3498 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3499 if (!bh
->deleted
&& bh
->scheduled
) {
3501 /* idle bottom halves will be polled at least
3503 *timeout
= MIN(10, *timeout
);
3505 /* non-idle bottom halves will be executed
3514 /***********************************************************/
3515 /* machine registration */
3517 static QEMUMachine
*first_machine
= NULL
;
3518 QEMUMachine
*current_machine
= NULL
;
3520 int qemu_register_machine(QEMUMachine
*m
)
3523 pm
= &first_machine
;
3531 static QEMUMachine
*find_machine(const char *name
)
3535 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3536 if (!strcmp(m
->name
, name
))
3542 /***********************************************************/
3543 /* main execution loop */
3545 static void gui_update(void *opaque
)
3547 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3548 DisplayState
*ds
= opaque
;
3549 DisplayChangeListener
*dcl
= ds
->listeners
;
3553 while (dcl
!= NULL
) {
3554 if (dcl
->gui_timer_interval
&&
3555 dcl
->gui_timer_interval
< interval
)
3556 interval
= dcl
->gui_timer_interval
;
3559 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3562 static void nographic_update(void *opaque
)
3564 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3566 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3569 struct vm_change_state_entry
{
3570 VMChangeStateHandler
*cb
;
3572 LIST_ENTRY (vm_change_state_entry
) entries
;
3575 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3577 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3580 VMChangeStateEntry
*e
;
3582 e
= qemu_mallocz(sizeof (*e
));
3586 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3590 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3592 LIST_REMOVE (e
, entries
);
3596 static void vm_state_notify(int running
, int reason
)
3598 VMChangeStateEntry
*e
;
3600 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3601 e
->cb(e
->opaque
, running
, reason
);
3610 vm_state_notify(1, 0);
3612 qemu_kvm_resume_all_threads();
3613 qemu_rearm_alarm_timer(alarm_timer
);
3617 void vm_stop(int reason
)
3620 cpu_disable_ticks();
3623 qemu_kvm_pause_all_threads();
3624 vm_state_notify(0, reason
);
3628 /* reset/shutdown handler */
3630 typedef struct QEMUResetEntry
{
3631 QEMUResetHandler
*func
;
3633 struct QEMUResetEntry
*next
;
3636 static QEMUResetEntry
*first_reset_entry
;
3637 static int reset_requested
;
3638 static int shutdown_requested
;
3639 static int powerdown_requested
;
3641 int qemu_shutdown_requested(void)
3643 int r
= shutdown_requested
;
3644 shutdown_requested
= 0;
3648 int qemu_reset_requested(void)
3650 int r
= reset_requested
;
3651 reset_requested
= 0;
3655 int qemu_powerdown_requested(void)
3657 int r
= powerdown_requested
;
3658 powerdown_requested
= 0;
3662 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3664 QEMUResetEntry
**pre
, *re
;
3666 pre
= &first_reset_entry
;
3667 while (*pre
!= NULL
)
3668 pre
= &(*pre
)->next
;
3669 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3671 re
->opaque
= opaque
;
3676 void qemu_system_reset(void)
3680 /* reset all devices */
3681 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
3682 re
->func(re
->opaque
);
3686 void qemu_system_reset_request(void)
3689 shutdown_requested
= 1;
3691 reset_requested
= 1;
3693 if (cpu_single_env
) {
3694 qemu_kvm_cpu_stop(cpu_single_env
);
3695 cpu_exit(cpu_single_env
);
3699 void qemu_system_shutdown_request(void)
3701 shutdown_requested
= 1;
3703 cpu_exit(cpu_single_env
);
3706 void qemu_system_powerdown_request(void)
3708 powerdown_requested
= 1;
3710 cpu_exit(cpu_single_env
);
3713 static int qemu_select(int max_fd
, fd_set
*rfds
, fd_set
*wfds
, fd_set
*xfds
,
3718 /* KVM holds a mutex while QEMU code is running, we need hooks to
3719 release the mutex whenever QEMU code sleeps. */
3723 ret
= select(max_fd
, rfds
, wfds
, xfds
, tv
);
3731 static void host_main_loop_wait(int *timeout
)
3737 /* XXX: need to suppress polling by better using win32 events */
3739 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
3740 ret
|= pe
->func(pe
->opaque
);
3744 WaitObjects
*w
= &wait_objects
;
3746 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
3747 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
3748 if (w
->func
[ret
- WAIT_OBJECT_0
])
3749 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
3751 /* Check for additional signaled events */
3752 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
3754 /* Check if event is signaled */
3755 ret2
= WaitForSingleObject(w
->events
[i
], 0);
3756 if(ret2
== WAIT_OBJECT_0
) {
3758 w
->func
[i
](w
->opaque
[i
]);
3759 } else if (ret2
== WAIT_TIMEOUT
) {
3761 err
= GetLastError();
3762 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
3765 } else if (ret
== WAIT_TIMEOUT
) {
3767 err
= GetLastError();
3768 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
3775 static void host_main_loop_wait(int *timeout
)
3780 void main_loop_wait(int timeout
)
3782 IOHandlerRecord
*ioh
;
3783 fd_set rfds
, wfds
, xfds
;
3787 qemu_bh_update_timeout(&timeout
);
3789 host_main_loop_wait(&timeout
);
3791 /* poll any events */
3792 /* XXX: separate device handlers from system ones */
3797 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3801 (!ioh
->fd_read_poll
||
3802 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
3803 FD_SET(ioh
->fd
, &rfds
);
3807 if (ioh
->fd_write
) {
3808 FD_SET(ioh
->fd
, &wfds
);
3814 tv
.tv_sec
= timeout
/ 1000;
3815 tv
.tv_usec
= (timeout
% 1000) * 1000;
3817 #if defined(CONFIG_SLIRP)
3818 if (slirp_is_inited()) {
3819 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
3822 ret
= qemu_select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
3824 IOHandlerRecord
**pioh
;
3826 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3827 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
3828 ioh
->fd_read(ioh
->opaque
);
3829 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
3830 FD_CLR(ioh
->fd
, &rfds
);
3832 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
3833 ioh
->fd_write(ioh
->opaque
);
3837 /* remove deleted IO handlers */
3838 pioh
= &first_io_handler
;
3848 #if defined(CONFIG_SLIRP)
3849 if (slirp_is_inited()) {
3855 slirp_select_poll(&rfds
, &wfds
, &xfds
);
3859 /* vm time timers */
3860 if (vm_running
&& (!cur_cpu
3861 || likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
))))
3862 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
3863 qemu_get_clock(vm_clock
));
3865 /* real time timers */
3866 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
3867 qemu_get_clock(rt_clock
));
3869 /* Check bottom-halves last in case any of the earlier events triggered
3875 static int main_loop(void)
3878 #ifdef CONFIG_PROFILER
3884 if (kvm_enabled()) {
3886 cpu_disable_ticks();
3890 cur_cpu
= first_cpu
;
3891 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
3898 #ifdef CONFIG_PROFILER
3899 ti
= profile_getclock();
3904 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
3905 env
->icount_decr
.u16
.low
= 0;
3906 env
->icount_extra
= 0;
3907 count
= qemu_next_deadline();
3908 count
= (count
+ (1 << icount_time_shift
) - 1)
3909 >> icount_time_shift
;
3910 qemu_icount
+= count
;
3911 decr
= (count
> 0xffff) ? 0xffff : count
;
3913 env
->icount_decr
.u16
.low
= decr
;
3914 env
->icount_extra
= count
;
3916 ret
= cpu_exec(env
);
3917 #ifdef CONFIG_PROFILER
3918 qemu_time
+= profile_getclock() - ti
;
3921 /* Fold pending instructions back into the
3922 instruction counter, and clear the interrupt flag. */
3923 qemu_icount
-= (env
->icount_decr
.u16
.low
3924 + env
->icount_extra
);
3925 env
->icount_decr
.u32
= 0;
3926 env
->icount_extra
= 0;
3928 next_cpu
= env
->next_cpu
?: first_cpu
;
3929 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
3930 ret
= EXCP_INTERRUPT
;
3934 if (ret
== EXCP_HLT
) {
3935 /* Give the next CPU a chance to run. */
3939 if (ret
!= EXCP_HALTED
)
3941 /* all CPUs are halted ? */
3947 if (shutdown_requested
) {
3948 ret
= EXCP_INTERRUPT
;
3956 if (reset_requested
) {
3957 reset_requested
= 0;
3958 qemu_system_reset();
3959 ret
= EXCP_INTERRUPT
;
3961 if (powerdown_requested
) {
3962 powerdown_requested
= 0;
3963 qemu_system_powerdown();
3964 ret
= EXCP_INTERRUPT
;
3966 #ifdef CONFIG_GDBSTUB
3967 if (unlikely(ret
== EXCP_DEBUG
)) {
3968 gdb_set_stop_cpu(cur_cpu
);
3969 vm_stop(EXCP_DEBUG
);
3972 /* If all cpus are halted then wait until the next IRQ */
3973 /* XXX: use timeout computed from timers */
3974 if (ret
== EXCP_HALTED
) {
3978 /* Advance virtual time to the next event. */
3979 if (use_icount
== 1) {
3980 /* When not using an adaptive execution frequency
3981 we tend to get badly out of sync with real time,
3982 so just delay for a reasonable amount of time. */
3985 delta
= cpu_get_icount() - cpu_get_clock();
3988 /* If virtual time is ahead of real time then just
3990 timeout
= (delta
/ 1000000) + 1;
3992 /* Wait for either IO to occur or the next
3994 add
= qemu_next_deadline();
3995 /* We advance the timer before checking for IO.
3996 Limit the amount we advance so that early IO
3997 activity won't get the guest too far ahead. */
4001 add
= (add
+ (1 << icount_time_shift
) - 1)
4002 >> icount_time_shift
;
4004 timeout
= delta
/ 1000000;
4015 if (shutdown_requested
) {
4016 ret
= EXCP_INTERRUPT
;
4021 #ifdef CONFIG_PROFILER
4022 ti
= profile_getclock();
4024 main_loop_wait(timeout
);
4025 #ifdef CONFIG_PROFILER
4026 dev_time
+= profile_getclock() - ti
;
4029 cpu_disable_ticks();
4033 static void help(int exitcode
)
4035 printf("QEMU PC emulator version " QEMU_VERSION
" (" KVM_VERSION
")"
4036 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
4037 "usage: %s [options] [disk_image]\n"
4039 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4041 #define DEF(option, opt_arg, opt_enum, opt_help) \
4043 #define DEFHEADING(text) stringify(text) "\n"
4044 #include "qemu-options.h"
4049 "During emulation, the following keys are useful:\n"
4050 "ctrl-alt-f toggle full screen\n"
4051 "ctrl-alt-n switch to virtual console 'n'\n"
4052 "ctrl-alt toggle mouse and keyboard grab\n"
4054 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4059 DEFAULT_NETWORK_SCRIPT
,
4060 DEFAULT_NETWORK_DOWN_SCRIPT
,
4062 DEFAULT_GDBSTUB_PORT
,
4067 #define HAS_ARG 0x0001
4070 #define DEF(option, opt_arg, opt_enum, opt_help) \
4072 #define DEFHEADING(text)
4073 #include "qemu-options.h"
4079 typedef struct QEMUOption
{
4085 static const QEMUOption qemu_options
[] = {
4086 { "h", 0, QEMU_OPTION_h
},
4087 #define DEF(option, opt_arg, opt_enum, opt_help) \
4088 { option, opt_arg, opt_enum },
4089 #define DEFHEADING(text)
4090 #include "qemu-options.h"
4098 struct soundhw soundhw
[] = {
4099 #ifdef HAS_AUDIO_CHOICE
4100 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4106 { .init_isa
= pcspk_audio_init
}
4113 "Creative Sound Blaster 16",
4116 { .init_isa
= SB16_init
}
4120 #ifdef CONFIG_CS4231A
4126 { .init_isa
= cs4231a_init
}
4134 "Yamaha YMF262 (OPL3)",
4136 "Yamaha YM3812 (OPL2)",
4140 { .init_isa
= Adlib_init
}
4147 "Gravis Ultrasound GF1",
4150 { .init_isa
= GUS_init
}
4157 "Intel 82801AA AC97 Audio",
4160 { .init_pci
= ac97_init
}
4164 #ifdef CONFIG_ES1370
4167 "ENSONIQ AudioPCI ES1370",
4170 { .init_pci
= es1370_init
}
4174 #endif /* HAS_AUDIO_CHOICE */
4176 { NULL
, NULL
, 0, 0, { NULL
} }
4179 static void select_soundhw (const char *optarg
)
4183 if (*optarg
== '?') {
4186 printf ("Valid sound card names (comma separated):\n");
4187 for (c
= soundhw
; c
->name
; ++c
) {
4188 printf ("%-11s %s\n", c
->name
, c
->descr
);
4190 printf ("\n-soundhw all will enable all of the above\n");
4191 exit (*optarg
!= '?');
4199 if (!strcmp (optarg
, "all")) {
4200 for (c
= soundhw
; c
->name
; ++c
) {
4208 e
= strchr (p
, ',');
4209 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4211 for (c
= soundhw
; c
->name
; ++c
) {
4212 if (!strncmp (c
->name
, p
, l
)) {
4221 "Unknown sound card name (too big to show)\n");
4224 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4229 p
+= l
+ (e
!= NULL
);
4233 goto show_valid_cards
;
4238 static void select_vgahw (const char *p
)
4242 if (strstart(p
, "std", &opts
)) {
4243 std_vga_enabled
= 1;
4244 cirrus_vga_enabled
= 0;
4246 } else if (strstart(p
, "cirrus", &opts
)) {
4247 cirrus_vga_enabled
= 1;
4248 std_vga_enabled
= 0;
4250 } else if (strstart(p
, "vmware", &opts
)) {
4251 cirrus_vga_enabled
= 0;
4252 std_vga_enabled
= 0;
4254 } else if (strstart(p
, "none", &opts
)) {
4255 cirrus_vga_enabled
= 0;
4256 std_vga_enabled
= 0;
4260 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4264 const char *nextopt
;
4266 if (strstart(opts
, ",retrace=", &nextopt
)) {
4268 if (strstart(opts
, "dumb", &nextopt
))
4269 vga_retrace_method
= VGA_RETRACE_DUMB
;
4270 else if (strstart(opts
, "precise", &nextopt
))
4271 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4272 else goto invalid_vga
;
4273 } else goto invalid_vga
;
4279 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4281 exit(STATUS_CONTROL_C_EXIT
);
4286 static int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4290 if(strlen(str
) != 36)
4293 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4294 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4295 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4303 #define MAX_NET_CLIENTS 32
4305 static int saved_argc
;
4306 static char **saved_argv
;
4307 static const char *saved_incoming
;
4309 void qemu_get_launch_info(int *argc
, char ***argv
, int *opt_daemonize
, const char **opt_incoming
)
4313 *opt_daemonize
= daemonize
;
4314 *opt_incoming
= saved_incoming
;
4319 #define HUGETLBFS_MAGIC 0x958458f6
4321 static long gethugepagesize(const char *path
)
4327 ret
= statfs(path
, &fs
);
4328 } while (ret
!= 0 && errno
== EINTR
);
4335 if (fs
.f_type
!= HUGETLBFS_MAGIC
)
4336 fprintf(stderr
, "Warning: path not on HugeTLBFS: %s\n", path
);
4341 static void *alloc_mem_area(size_t memory
, unsigned long *len
, const char *path
)
4350 if (!kvm_has_sync_mmu()) {
4351 fprintf(stderr
, "host lacks mmu notifiers, disabling --mem-path\n");
4355 if (asprintf(&filename
, "%s/kvm.XXXXXX", path
) == -1)
4358 hpagesize
= gethugepagesize(path
);
4362 fd
= mkstemp(filename
);
4371 memory
= (memory
+hpagesize
-1) & ~(hpagesize
-1);
4374 * ftruncate is not supported by hugetlbfs in older
4375 * hosts, so don't bother checking for errors.
4376 * If anything goes wrong with it under other filesystems,
4379 ftruncate(fd
, memory
);
4382 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4383 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4384 * to sidestep this quirk.
4386 flags
= mem_prealloc
? MAP_POPULATE
|MAP_SHARED
: MAP_PRIVATE
;
4387 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, flags
, fd
, 0);
4389 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
, fd
, 0);
4391 if (area
== MAP_FAILED
) {
4392 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4401 static void *qemu_alloc_physram(unsigned long memory
)
4405 unsigned long map_len
= memory
;
4408 area
= alloc_mem_area(memory
, &map_len
, mem_path
);
4411 area
= qemu_vmalloc(memory
);
4413 if (kvm_setup_guest_memory(area
, map_len
))
4421 static void termsig_handler(int signal
)
4423 qemu_system_shutdown_request();
4426 static void termsig_setup(void)
4428 struct sigaction act
;
4430 memset(&act
, 0, sizeof(act
));
4431 act
.sa_handler
= termsig_handler
;
4432 sigaction(SIGINT
, &act
, NULL
);
4433 sigaction(SIGHUP
, &act
, NULL
);
4434 sigaction(SIGTERM
, &act
, NULL
);
4439 int main(int argc
, char **argv
, char **envp
)
4441 #ifdef CONFIG_GDBSTUB
4442 const char *gdbstub_dev
= NULL
;
4444 uint32_t boot_devices_bitmap
= 0;
4446 int snapshot
, linux_boot
, net_boot
;
4447 const char *initrd_filename
;
4448 const char *kernel_filename
, *kernel_cmdline
;
4449 const char *boot_devices
= "";
4451 DisplayChangeListener
*dcl
;
4452 int cyls
, heads
, secs
, translation
;
4453 const char *net_clients
[MAX_NET_CLIENTS
];
4455 const char *bt_opts
[MAX_BT_CMDLINE
];
4459 const char *r
, *optarg
;
4460 CharDriverState
*monitor_hd
= NULL
;
4461 const char *monitor_device
;
4462 const char *serial_devices
[MAX_SERIAL_PORTS
];
4463 int serial_device_index
;
4464 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
4465 int parallel_device_index
;
4466 const char *virtio_consoles
[MAX_VIRTIO_CONSOLES
];
4467 int virtio_console_index
;
4468 const char *loadvm
= NULL
;
4469 QEMUMachine
*machine
;
4470 const char *cpu_model
;
4471 const char *usb_devices
[MAX_USB_CMDLINE
];
4472 int usb_devices_index
;
4477 const char *pid_file
= NULL
;
4478 const char *incoming
= NULL
;
4481 struct passwd
*pwd
= NULL
;
4482 const char *chroot_dir
= NULL
;
4483 const char *run_as
= NULL
;
4486 qemu_cache_utils_init(envp
);
4488 LIST_INIT (&vm_change_state_head
);
4491 struct sigaction act
;
4492 sigfillset(&act
.sa_mask
);
4494 act
.sa_handler
= SIG_IGN
;
4495 sigaction(SIGPIPE
, &act
, NULL
);
4498 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4499 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4500 QEMU to run on a single CPU */
4505 h
= GetCurrentProcess();
4506 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4507 for(i
= 0; i
< 32; i
++) {
4508 if (mask
& (1 << i
))
4513 SetProcessAffinityMask(h
, mask
);
4519 register_machines();
4520 machine
= first_machine
;
4522 initrd_filename
= NULL
;
4524 vga_ram_size
= VGA_RAM_SIZE
;
4528 kernel_filename
= NULL
;
4529 kernel_cmdline
= "";
4530 cyls
= heads
= secs
= 0;
4531 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4532 monitor_device
= "vc:80Cx24C";
4534 serial_devices
[0] = "vc:80Cx24C";
4535 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
4536 serial_devices
[i
] = NULL
;
4537 serial_device_index
= 0;
4539 parallel_devices
[0] = "vc:80Cx24C";
4540 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
4541 parallel_devices
[i
] = NULL
;
4542 parallel_device_index
= 0;
4544 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++)
4545 virtio_consoles
[i
] = NULL
;
4546 virtio_console_index
= 0;
4548 usb_devices_index
= 0;
4549 assigned_devices_index
= 0;
4568 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
4570 const QEMUOption
*popt
;
4573 /* Treat --foo the same as -foo. */
4576 popt
= qemu_options
;
4579 fprintf(stderr
, "%s: invalid option -- '%s'\n",
4583 if (!strcmp(popt
->name
, r
+ 1))
4587 if (popt
->flags
& HAS_ARG
) {
4588 if (optind
>= argc
) {
4589 fprintf(stderr
, "%s: option '%s' requires an argument\n",
4593 optarg
= argv
[optind
++];
4598 switch(popt
->index
) {
4600 machine
= find_machine(optarg
);
4603 printf("Supported machines are:\n");
4604 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
4605 printf("%-10s %s%s\n",
4607 m
== first_machine
? " (default)" : "");
4609 exit(*optarg
!= '?');
4612 case QEMU_OPTION_cpu
:
4613 /* hw initialization will check this */
4614 if (*optarg
== '?') {
4615 /* XXX: implement xxx_cpu_list for targets that still miss it */
4616 #if defined(cpu_list)
4617 cpu_list(stdout
, &fprintf
);
4624 case QEMU_OPTION_initrd
:
4625 initrd_filename
= optarg
;
4627 case QEMU_OPTION_hda
:
4629 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
4631 hda_index
= drive_add(optarg
, HD_ALIAS
4632 ",cyls=%d,heads=%d,secs=%d%s",
4633 0, cyls
, heads
, secs
,
4634 translation
== BIOS_ATA_TRANSLATION_LBA
?
4636 translation
== BIOS_ATA_TRANSLATION_NONE
?
4637 ",trans=none" : "");
4639 case QEMU_OPTION_hdb
:
4640 case QEMU_OPTION_hdc
:
4641 case QEMU_OPTION_hdd
:
4642 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
4644 case QEMU_OPTION_drive
:
4645 drive_add(NULL
, "%s", optarg
);
4647 case QEMU_OPTION_mtdblock
:
4648 drive_add(optarg
, MTD_ALIAS
);
4650 case QEMU_OPTION_sd
:
4651 drive_add(optarg
, SD_ALIAS
);
4653 case QEMU_OPTION_pflash
:
4654 drive_add(optarg
, PFLASH_ALIAS
);
4656 case QEMU_OPTION_snapshot
:
4659 case QEMU_OPTION_hdachs
:
4663 cyls
= strtol(p
, (char **)&p
, 0);
4664 if (cyls
< 1 || cyls
> 16383)
4669 heads
= strtol(p
, (char **)&p
, 0);
4670 if (heads
< 1 || heads
> 16)
4675 secs
= strtol(p
, (char **)&p
, 0);
4676 if (secs
< 1 || secs
> 63)
4680 if (!strcmp(p
, "none"))
4681 translation
= BIOS_ATA_TRANSLATION_NONE
;
4682 else if (!strcmp(p
, "lba"))
4683 translation
= BIOS_ATA_TRANSLATION_LBA
;
4684 else if (!strcmp(p
, "auto"))
4685 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4688 } else if (*p
!= '\0') {
4690 fprintf(stderr
, "qemu: invalid physical CHS format\n");
4693 if (hda_index
!= -1)
4694 snprintf(drives_opt
[hda_index
].opt
,
4695 sizeof(drives_opt
[hda_index
].opt
),
4696 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
4697 0, cyls
, heads
, secs
,
4698 translation
== BIOS_ATA_TRANSLATION_LBA
?
4700 translation
== BIOS_ATA_TRANSLATION_NONE
?
4701 ",trans=none" : "");
4704 case QEMU_OPTION_nographic
:
4707 #ifdef CONFIG_CURSES
4708 case QEMU_OPTION_curses
:
4712 case QEMU_OPTION_portrait
:
4715 case QEMU_OPTION_kernel
:
4716 kernel_filename
= optarg
;
4718 case QEMU_OPTION_append
:
4719 kernel_cmdline
= optarg
;
4721 case QEMU_OPTION_cdrom
:
4722 drive_add(optarg
, CDROM_ALIAS
);
4724 case QEMU_OPTION_boot
:
4725 boot_devices
= optarg
;
4726 /* We just do some generic consistency checks */
4728 /* Could easily be extended to 64 devices if needed */
4731 boot_devices_bitmap
= 0;
4732 for (p
= boot_devices
; *p
!= '\0'; p
++) {
4733 /* Allowed boot devices are:
4734 * a b : floppy disk drives
4735 * c ... f : IDE disk drives
4736 * g ... m : machine implementation dependant drives
4737 * n ... p : network devices
4738 * It's up to each machine implementation to check
4739 * if the given boot devices match the actual hardware
4740 * implementation and firmware features.
4742 if (*p
< 'a' || *p
> 'q') {
4743 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
4746 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
4748 "Boot device '%c' was given twice\n",*p
);
4751 boot_devices_bitmap
|= 1 << (*p
- 'a');
4755 case QEMU_OPTION_fda
:
4756 case QEMU_OPTION_fdb
:
4757 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
4760 case QEMU_OPTION_no_fd_bootchk
:
4764 case QEMU_OPTION_net
:
4765 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
4766 fprintf(stderr
, "qemu: too many network clients\n");
4769 net_clients
[nb_net_clients
] = optarg
;
4773 case QEMU_OPTION_tftp
:
4774 tftp_prefix
= optarg
;
4776 case QEMU_OPTION_bootp
:
4777 bootp_filename
= optarg
;
4780 case QEMU_OPTION_smb
:
4781 net_slirp_smb(optarg
);
4784 case QEMU_OPTION_redir
:
4785 net_slirp_redir(optarg
);
4788 case QEMU_OPTION_bt
:
4789 if (nb_bt_opts
>= MAX_BT_CMDLINE
) {
4790 fprintf(stderr
, "qemu: too many bluetooth options\n");
4793 bt_opts
[nb_bt_opts
++] = optarg
;
4796 case QEMU_OPTION_audio_help
:
4800 case QEMU_OPTION_soundhw
:
4801 select_soundhw (optarg
);
4807 case QEMU_OPTION_m
: {
4811 value
= strtoul(optarg
, &ptr
, 10);
4813 case 0: case 'M': case 'm':
4820 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
4824 /* On 32-bit hosts, QEMU is limited by virtual address space */
4825 if (value
> (2047 << 20)
4827 && HOST_LONG_BITS
== 32
4830 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
4833 if (value
!= (uint64_t)(ram_addr_t
)value
) {
4834 fprintf(stderr
, "qemu: ram size too large\n");
4843 const CPULogItem
*item
;
4845 mask
= cpu_str_to_log_mask(optarg
);
4847 printf("Log items (comma separated):\n");
4848 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
4849 printf("%-10s %s\n", item
->name
, item
->help
);
4856 #ifdef CONFIG_GDBSTUB
4858 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
4860 case QEMU_OPTION_gdb
:
4861 gdbstub_dev
= optarg
;
4867 case QEMU_OPTION_bios
:
4870 case QEMU_OPTION_singlestep
:
4878 keyboard_layout
= optarg
;
4881 case QEMU_OPTION_localtime
:
4884 case QEMU_OPTION_vga
:
4885 select_vgahw (optarg
);
4887 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4893 w
= strtol(p
, (char **)&p
, 10);
4896 fprintf(stderr
, "qemu: invalid resolution or depth\n");
4902 h
= strtol(p
, (char **)&p
, 10);
4907 depth
= strtol(p
, (char **)&p
, 10);
4908 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
4909 depth
!= 24 && depth
!= 32)
4911 } else if (*p
== '\0') {
4912 depth
= graphic_depth
;
4919 graphic_depth
= depth
;
4923 case QEMU_OPTION_echr
:
4926 term_escape_char
= strtol(optarg
, &r
, 0);
4928 printf("Bad argument to echr\n");
4931 case QEMU_OPTION_monitor
:
4932 monitor_device
= optarg
;
4934 case QEMU_OPTION_serial
:
4935 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
4936 fprintf(stderr
, "qemu: too many serial ports\n");
4939 serial_devices
[serial_device_index
] = optarg
;
4940 serial_device_index
++;
4942 case QEMU_OPTION_virtiocon
:
4943 if (virtio_console_index
>= MAX_VIRTIO_CONSOLES
) {
4944 fprintf(stderr
, "qemu: too many virtio consoles\n");
4947 virtio_consoles
[virtio_console_index
] = optarg
;
4948 virtio_console_index
++;
4950 case QEMU_OPTION_parallel
:
4951 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
4952 fprintf(stderr
, "qemu: too many parallel ports\n");
4955 parallel_devices
[parallel_device_index
] = optarg
;
4956 parallel_device_index
++;
4958 case QEMU_OPTION_loadvm
:
4961 case QEMU_OPTION_full_screen
:
4965 case QEMU_OPTION_no_frame
:
4968 case QEMU_OPTION_alt_grab
:
4971 case QEMU_OPTION_no_quit
:
4974 case QEMU_OPTION_sdl
:
4978 case QEMU_OPTION_pidfile
:
4982 case QEMU_OPTION_win2k_hack
:
4983 win2k_install_hack
= 1;
4985 case QEMU_OPTION_rtc_td_hack
:
4988 case QEMU_OPTION_acpitable
:
4989 if(acpi_table_add(optarg
) < 0) {
4990 fprintf(stderr
, "Wrong acpi table provided\n");
4996 case QEMU_OPTION_no_kqemu
:
4999 case QEMU_OPTION_kernel_kqemu
:
5004 case QEMU_OPTION_enable_kvm
:
5012 case QEMU_OPTION_no_kvm
:
5015 case QEMU_OPTION_no_kvm_irqchip
: {
5020 case QEMU_OPTION_no_kvm_pit
: {
5024 case QEMU_OPTION_no_kvm_pit_reinjection
: {
5025 kvm_pit_reinject
= 0;
5028 case QEMU_OPTION_enable_nesting
: {
5032 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5033 case QEMU_OPTION_pcidevice
:
5034 if (assigned_devices_index
>= MAX_DEV_ASSIGN_CMDLINE
) {
5035 fprintf(stderr
, "Too many assigned devices\n");
5038 assigned_devices
[assigned_devices_index
] = optarg
;
5039 assigned_devices_index
++;
5043 case QEMU_OPTION_usb
:
5046 case QEMU_OPTION_usbdevice
:
5048 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
5049 fprintf(stderr
, "Too many USB devices\n");
5052 usb_devices
[usb_devices_index
] = optarg
;
5053 usb_devices_index
++;
5055 case QEMU_OPTION_smp
:
5056 smp_cpus
= atoi(optarg
);
5058 fprintf(stderr
, "Invalid number of CPUs\n");
5062 case QEMU_OPTION_vnc
:
5063 vnc_display
= optarg
;
5066 case QEMU_OPTION_no_acpi
:
5069 case QEMU_OPTION_no_hpet
:
5073 case QEMU_OPTION_no_reboot
:
5076 case QEMU_OPTION_no_shutdown
:
5079 case QEMU_OPTION_show_cursor
:
5082 case QEMU_OPTION_uuid
:
5083 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5084 fprintf(stderr
, "Fail to parse UUID string."
5085 " Wrong format.\n");
5090 case QEMU_OPTION_daemonize
:
5094 case QEMU_OPTION_option_rom
:
5095 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5096 fprintf(stderr
, "Too many option ROMs\n");
5099 option_rom
[nb_option_roms
] = optarg
;
5102 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5103 case QEMU_OPTION_semihosting
:
5104 semihosting_enabled
= 1;
5107 case QEMU_OPTION_tdf
:
5110 case QEMU_OPTION_kvm_shadow_memory
:
5111 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
5113 case QEMU_OPTION_mempath
:
5117 case QEMU_OPTION_mem_prealloc
:
5118 mem_prealloc
= !mem_prealloc
;
5121 case QEMU_OPTION_name
:
5124 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5125 case QEMU_OPTION_prom_env
:
5126 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5127 fprintf(stderr
, "Too many prom variables\n");
5130 prom_envs
[nb_prom_envs
] = optarg
;
5134 case QEMU_OPTION_cpu_vendor
:
5135 cpu_vendor_string
= optarg
;
5138 case QEMU_OPTION_old_param
:
5142 case QEMU_OPTION_clock
:
5143 configure_alarms(optarg
);
5145 case QEMU_OPTION_startdate
:
5148 time_t rtc_start_date
;
5149 if (!strcmp(optarg
, "now")) {
5150 rtc_date_offset
= -1;
5152 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
5160 } else if (sscanf(optarg
, "%d-%d-%d",
5163 &tm
.tm_mday
) == 3) {
5172 rtc_start_date
= mktimegm(&tm
);
5173 if (rtc_start_date
== -1) {
5175 fprintf(stderr
, "Invalid date format. Valid format are:\n"
5176 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5179 rtc_date_offset
= time(NULL
) - rtc_start_date
;
5183 case QEMU_OPTION_tb_size
:
5184 tb_size
= strtol(optarg
, NULL
, 0);
5188 case QEMU_OPTION_icount
:
5190 if (strcmp(optarg
, "auto") == 0) {
5191 icount_time_shift
= -1;
5193 icount_time_shift
= strtol(optarg
, NULL
, 0);
5196 case QEMU_OPTION_incoming
:
5198 saved_incoming
= incoming
;
5201 case QEMU_OPTION_chroot
:
5202 chroot_dir
= optarg
;
5204 case QEMU_OPTION_runas
:
5207 case QEMU_OPTION_nvram
:
5215 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5216 if (kvm_allowed
&& kqemu_allowed
) {
5218 "You can not enable both KVM and kqemu at the same time\n");
5223 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5224 if (smp_cpus
> machine
->max_cpus
) {
5225 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5226 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5232 if (serial_device_index
== 0)
5233 serial_devices
[0] = "stdio";
5234 if (parallel_device_index
== 0)
5235 parallel_devices
[0] = "null";
5236 if (strncmp(monitor_device
, "vc", 2) == 0)
5237 monitor_device
= "stdio";
5244 if (pipe(fds
) == -1)
5255 len
= read(fds
[0], &status
, 1);
5256 if (len
== -1 && (errno
== EINTR
))
5261 else if (status
== 1) {
5262 fprintf(stderr
, "Could not acquire pidfile\n");
5279 signal(SIGTSTP
, SIG_IGN
);
5280 signal(SIGTTOU
, SIG_IGN
);
5281 signal(SIGTTIN
, SIG_IGN
);
5285 if (kvm_enabled()) {
5286 if (kvm_qemu_init() < 0) {
5287 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
5288 #ifdef NO_CPU_EMULATION
5289 fprintf(stderr
, "Compiled with --disable-cpu-emulation, exiting.\n");
5297 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5300 write(fds
[1], &status
, 1);
5302 fprintf(stderr
, "Could not acquire pid file\n");
5311 linux_boot
= (kernel_filename
!= NULL
);
5312 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5314 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5315 fprintf(stderr
, "-append only allowed with -kernel option\n");
5319 if (!linux_boot
&& initrd_filename
!= NULL
) {
5320 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5324 /* boot to floppy or the default cd if no hard disk defined yet */
5325 if (!boot_devices
[0]) {
5326 boot_devices
= "cad";
5328 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5331 if (init_timer_alarm() < 0) {
5332 fprintf(stderr
, "could not initialize alarm timer\n");
5335 if (use_icount
&& icount_time_shift
< 0) {
5337 /* 125MIPS seems a reasonable initial guess at the guest speed.
5338 It will be corrected fairly quickly anyway. */
5339 icount_time_shift
= 3;
5340 init_icount_adjust();
5347 /* init network clients */
5348 if (nb_net_clients
== 0) {
5349 /* if no clients, we use a default config */
5350 net_clients
[nb_net_clients
++] = "nic";
5352 net_clients
[nb_net_clients
++] = "user";
5356 for(i
= 0;i
< nb_net_clients
; i
++) {
5357 if (net_client_parse(net_clients
[i
]) < 0)
5363 /* XXX: this should be moved in the PC machine instantiation code */
5364 if (net_boot
!= 0) {
5366 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
5367 const char *model
= nd_table
[i
].model
;
5369 if (net_boot
& (1 << i
)) {
5372 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
5373 if (get_image_size(buf
) > 0) {
5374 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5375 fprintf(stderr
, "Too many option ROMs\n");
5378 option_rom
[nb_option_roms
] = strdup(buf
);
5385 fprintf(stderr
, "No valid PXE rom found for network device\n");
5391 /* init the bluetooth world */
5392 for (i
= 0; i
< nb_bt_opts
; i
++)
5393 if (bt_parse(bt_opts
[i
]))
5396 /* init the memory */
5397 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
5399 if (machine
->ram_require
& RAMSIZE_FIXED
) {
5401 if (ram_size
< phys_ram_size
) {
5402 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
5403 machine
->name
, (unsigned long long) phys_ram_size
);
5407 phys_ram_size
= ram_size
;
5409 ram_size
= phys_ram_size
;
5412 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5414 phys_ram_size
+= ram_size
;
5417 /* Initialize kvm */
5418 #if defined(TARGET_I386) || defined(TARGET_X86_64)
5419 #define KVM_EXTRA_PAGES 3
5421 #define KVM_EXTRA_PAGES 0
5423 if (kvm_enabled()) {
5424 phys_ram_size
+= KVM_EXTRA_PAGES
* TARGET_PAGE_SIZE
;
5425 if (kvm_qemu_create_context() < 0) {
5426 fprintf(stderr
, "Could not create KVM context\n");
5431 phys_ram_base
= qemu_alloc_physram(phys_ram_size
);
5432 if (!phys_ram_base
) {
5433 fprintf(stderr
, "Could not allocate physical memory\n");
5437 /* init the dynamic translator */
5438 cpu_exec_init_all(tb_size
* 1024 * 1024);
5443 /* we always create the cdrom drive, even if no disk is there */
5445 if (nb_drives_opt
< MAX_DRIVES
)
5446 drive_add(NULL
, CDROM_ALIAS
);
5448 /* we always create at least one floppy */
5450 if (nb_drives_opt
< MAX_DRIVES
)
5451 drive_add(NULL
, FD_ALIAS
, 0);
5453 /* we always create one sd slot, even if no card is in it */
5455 if (nb_drives_opt
< MAX_DRIVES
)
5456 drive_add(NULL
, SD_ALIAS
);
5458 /* open the virtual block devices
5459 * note that migration with device
5460 * hot add/remove is broken.
5462 for(i
= 0; i
< nb_drives_opt
; i
++)
5463 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
5466 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
5467 register_savevm_live("ram", 0, 3, ram_save_live
, NULL
, ram_load
, NULL
);
5470 /* must be after terminal init, SDL library changes signal handlers */
5474 /* Maintain compatibility with multiple stdio monitors */
5475 if (!strcmp(monitor_device
,"stdio")) {
5476 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5477 const char *devname
= serial_devices
[i
];
5478 if (devname
&& !strcmp(devname
,"mon:stdio")) {
5479 monitor_device
= NULL
;
5481 } else if (devname
&& !strcmp(devname
,"stdio")) {
5482 monitor_device
= NULL
;
5483 serial_devices
[i
] = "mon:stdio";
5490 if (kvm_enabled()) {
5493 ret
= kvm_init(smp_cpus
);
5495 fprintf(stderr
, "failed to initialize KVM\n");
5501 if (monitor_device
) {
5502 monitor_hd
= qemu_chr_open("monitor", monitor_device
, NULL
);
5504 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
5509 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5510 const char *devname
= serial_devices
[i
];
5511 if (devname
&& strcmp(devname
, "none")) {
5513 snprintf(label
, sizeof(label
), "serial%d", i
);
5514 serial_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5515 if (!serial_hds
[i
]) {
5516 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
5523 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
5524 const char *devname
= parallel_devices
[i
];
5525 if (devname
&& strcmp(devname
, "none")) {
5527 snprintf(label
, sizeof(label
), "parallel%d", i
);
5528 parallel_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5529 if (!parallel_hds
[i
]) {
5530 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
5537 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
5538 const char *devname
= virtio_consoles
[i
];
5539 if (devname
&& strcmp(devname
, "none")) {
5541 snprintf(label
, sizeof(label
), "virtcon%d", i
);
5542 virtcon_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5543 if (!virtcon_hds
[i
]) {
5544 fprintf(stderr
, "qemu: could not open virtio console '%s'\n",
5554 machine
->init(ram_size
, vga_ram_size
, boot_devices
,
5555 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
5557 current_machine
= machine
;
5559 /* Set KVM's vcpu state to qemu's initial CPUState. */
5560 if (kvm_enabled()) {
5563 ret
= kvm_sync_vcpus();
5565 fprintf(stderr
, "failed to initialize vcpus\n");
5570 /* init USB devices */
5572 for(i
= 0; i
< usb_devices_index
; i
++) {
5573 if (usb_device_add(usb_devices
[i
], 0) < 0) {
5574 fprintf(stderr
, "Warning: could not add USB device %s\n",
5581 dumb_display_init();
5582 /* just use the first displaystate for the moment */
5587 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
5591 #if defined(CONFIG_CURSES)
5593 /* At the moment curses cannot be used with other displays */
5594 curses_display_init(ds
, full_screen
);
5598 if (vnc_display
!= NULL
) {
5599 vnc_display_init(ds
);
5600 if (vnc_display_open(ds
, vnc_display
) < 0)
5603 #if defined(CONFIG_SDL)
5604 if (sdl
|| !vnc_display
)
5605 sdl_display_init(ds
, full_screen
, no_frame
);
5606 #elif defined(CONFIG_COCOA)
5607 if (sdl
|| !vnc_display
)
5608 cocoa_display_init(ds
, full_screen
);
5614 dcl
= ds
->listeners
;
5615 while (dcl
!= NULL
) {
5616 if (dcl
->dpy_refresh
!= NULL
) {
5617 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
5618 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
5623 if (nographic
|| (vnc_display
&& !sdl
)) {
5624 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
5625 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
5628 text_consoles_set_display(display_state
);
5629 qemu_chr_initial_reset();
5631 if (monitor_device
&& monitor_hd
)
5632 monitor_init(monitor_hd
, MONITOR_USE_READLINE
| MONITOR_IS_DEFAULT
);
5634 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5635 const char *devname
= serial_devices
[i
];
5636 if (devname
&& strcmp(devname
, "none")) {
5638 snprintf(label
, sizeof(label
), "serial%d", i
);
5639 if (strstart(devname
, "vc", 0))
5640 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
5644 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
5645 const char *devname
= parallel_devices
[i
];
5646 if (devname
&& strcmp(devname
, "none")) {
5648 snprintf(label
, sizeof(label
), "parallel%d", i
);
5649 if (strstart(devname
, "vc", 0))
5650 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
5654 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
5655 const char *devname
= virtio_consoles
[i
];
5656 if (virtcon_hds
[i
] && devname
) {
5658 snprintf(label
, sizeof(label
), "virtcon%d", i
);
5659 if (strstart(devname
, "vc", 0))
5660 qemu_chr_printf(virtcon_hds
[i
], "virtio console%d\r\n", i
);
5664 #ifdef CONFIG_GDBSTUB
5665 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
5666 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
5673 do_loadvm(cur_mon
, loadvm
);
5676 autostart
= 0; /* fixme how to deal with -daemonize */
5677 qemu_start_incoming_migration(incoming
);
5689 len
= write(fds
[1], &status
, 1);
5690 if (len
== -1 && (errno
== EINTR
))
5697 TFR(fd
= open("/dev/null", O_RDWR
));
5703 pwd
= getpwnam(run_as
);
5705 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
5711 if (chroot(chroot_dir
) < 0) {
5712 fprintf(stderr
, "chroot failed\n");
5719 if (setgid(pwd
->pw_gid
) < 0) {
5720 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
5723 if (setuid(pwd
->pw_uid
) < 0) {
5724 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
5727 if (setuid(0) != -1) {
5728 fprintf(stderr
, "Dropping privileges failed\n");