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)
3230 kvm_update_dirty_pages_log(); /* FIXME: propagate errors */
3231 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
3234 cpu_physical_memory_reset_dirty(current_addr
,
3235 current_addr
+ TARGET_PAGE_SIZE
,
3236 MIGRATION_DIRTY_FLAG
);
3238 ch
= *(phys_ram_base
+ current_addr
);
3240 if (is_dup_page(phys_ram_base
+ current_addr
, ch
)) {
3241 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
3242 qemu_put_byte(f
, ch
);
3244 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
3245 qemu_put_buffer(f
, phys_ram_base
+ current_addr
, TARGET_PAGE_SIZE
);
3251 addr
+= TARGET_PAGE_SIZE
;
3252 current_addr
= (saved_addr
+ addr
) % phys_ram_size
;
3258 static ram_addr_t ram_save_threshold
= 10;
3260 static ram_addr_t
ram_save_remaining(void)
3263 ram_addr_t count
= 0;
3265 for (addr
= 0; addr
< phys_ram_size
; addr
+= TARGET_PAGE_SIZE
) {
3266 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3273 static int ram_save_live(QEMUFile
*f
, int stage
, void *opaque
)
3278 /* Make sure all dirty bits are set */
3279 for (addr
= 0; addr
< phys_ram_size
; addr
+= TARGET_PAGE_SIZE
) {
3280 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3281 cpu_physical_memory_set_dirty(addr
);
3284 /* Enable dirty memory tracking */
3285 cpu_physical_memory_set_dirty_tracking(1);
3287 qemu_put_be64(f
, phys_ram_size
| RAM_SAVE_FLAG_MEM_SIZE
);
3290 while (!qemu_file_rate_limit(f
)) {
3293 ret
= ram_save_block(f
);
3294 if (ret
== 0) /* no more blocks */
3298 /* try transferring iterative blocks of memory */
3302 /* flush all remaining blocks regardless of rate limiting */
3303 while (ram_save_block(f
) != 0);
3304 cpu_physical_memory_set_dirty_tracking(0);
3307 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3309 return (stage
== 2) && (ram_save_remaining() < ram_save_threshold
);
3312 static int ram_load_dead(QEMUFile
*f
, void *opaque
)
3314 RamDecompressState s1
, *s
= &s1
;
3318 if (ram_decompress_open(s
, f
) < 0)
3320 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
3321 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3323 if (ram_decompress_buf(s
, buf
, 1) < 0) {
3324 fprintf(stderr
, "Error while reading ram block header\n");
3328 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
3329 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
3334 printf("Error block header\n");
3338 ram_decompress_close(s
);
3343 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
3348 if (version_id
== 1)
3349 return ram_load_v1(f
, opaque
);
3351 if (version_id
== 2) {
3352 if (qemu_get_be32(f
) != phys_ram_size
)
3354 return ram_load_dead(f
, opaque
);
3357 if (version_id
!= 3)
3361 addr
= qemu_get_be64(f
);
3363 flags
= addr
& ~TARGET_PAGE_MASK
;
3364 addr
&= TARGET_PAGE_MASK
;
3366 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
3367 if (addr
!= phys_ram_size
)
3371 if (flags
& RAM_SAVE_FLAG_FULL
) {
3372 if (ram_load_dead(f
, opaque
) < 0)
3376 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
3377 uint8_t ch
= qemu_get_byte(f
);
3378 memset(phys_ram_base
+ addr
, ch
, TARGET_PAGE_SIZE
);
3379 } else if (flags
& RAM_SAVE_FLAG_PAGE
)
3380 qemu_get_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
3381 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
3386 void qemu_service_io(void)
3388 CPUState
*env
= cpu_single_env
;
3392 if (env
->kqemu_enabled
) {
3393 kqemu_cpu_interrupt(env
);
3399 /***********************************************************/
3400 /* bottom halves (can be seen as timers which expire ASAP) */
3411 static QEMUBH
*first_bh
= NULL
;
3413 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
3416 bh
= qemu_mallocz(sizeof(QEMUBH
));
3418 bh
->opaque
= opaque
;
3419 bh
->next
= first_bh
;
3424 int qemu_bh_poll(void)
3430 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3431 if (!bh
->deleted
&& bh
->scheduled
) {
3440 /* remove deleted bhs */
3454 void qemu_bh_schedule_idle(QEMUBH
*bh
)
3462 void qemu_bh_schedule(QEMUBH
*bh
)
3464 CPUState
*env
= cpu_single_env
;
3469 /* stop the currently executing CPU to execute the BH ASAP */
3476 void qemu_bh_cancel(QEMUBH
*bh
)
3481 void qemu_bh_delete(QEMUBH
*bh
)
3487 static void qemu_bh_update_timeout(int *timeout
)
3491 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3492 if (!bh
->deleted
&& bh
->scheduled
) {
3494 /* idle bottom halves will be polled at least
3496 *timeout
= MIN(10, *timeout
);
3498 /* non-idle bottom halves will be executed
3507 /***********************************************************/
3508 /* machine registration */
3510 static QEMUMachine
*first_machine
= NULL
;
3511 QEMUMachine
*current_machine
= NULL
;
3513 int qemu_register_machine(QEMUMachine
*m
)
3516 pm
= &first_machine
;
3524 static QEMUMachine
*find_machine(const char *name
)
3528 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3529 if (!strcmp(m
->name
, name
))
3535 /***********************************************************/
3536 /* main execution loop */
3538 static void gui_update(void *opaque
)
3540 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3541 DisplayState
*ds
= opaque
;
3542 DisplayChangeListener
*dcl
= ds
->listeners
;
3546 while (dcl
!= NULL
) {
3547 if (dcl
->gui_timer_interval
&&
3548 dcl
->gui_timer_interval
< interval
)
3549 interval
= dcl
->gui_timer_interval
;
3552 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3555 static void nographic_update(void *opaque
)
3557 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3559 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3562 struct vm_change_state_entry
{
3563 VMChangeStateHandler
*cb
;
3565 LIST_ENTRY (vm_change_state_entry
) entries
;
3568 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3570 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3573 VMChangeStateEntry
*e
;
3575 e
= qemu_mallocz(sizeof (*e
));
3579 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3583 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3585 LIST_REMOVE (e
, entries
);
3589 static void vm_state_notify(int running
, int reason
)
3591 VMChangeStateEntry
*e
;
3593 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3594 e
->cb(e
->opaque
, running
, reason
);
3603 vm_state_notify(1, 0);
3605 qemu_kvm_resume_all_threads();
3606 qemu_rearm_alarm_timer(alarm_timer
);
3610 void vm_stop(int reason
)
3613 cpu_disable_ticks();
3616 qemu_kvm_pause_all_threads();
3617 vm_state_notify(0, reason
);
3621 /* reset/shutdown handler */
3623 typedef struct QEMUResetEntry
{
3624 QEMUResetHandler
*func
;
3626 struct QEMUResetEntry
*next
;
3629 static QEMUResetEntry
*first_reset_entry
;
3630 static int reset_requested
;
3631 static int shutdown_requested
;
3632 static int powerdown_requested
;
3634 int qemu_shutdown_requested(void)
3636 int r
= shutdown_requested
;
3637 shutdown_requested
= 0;
3641 int qemu_reset_requested(void)
3643 int r
= reset_requested
;
3644 reset_requested
= 0;
3648 int qemu_powerdown_requested(void)
3650 int r
= powerdown_requested
;
3651 powerdown_requested
= 0;
3655 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3657 QEMUResetEntry
**pre
, *re
;
3659 pre
= &first_reset_entry
;
3660 while (*pre
!= NULL
)
3661 pre
= &(*pre
)->next
;
3662 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3664 re
->opaque
= opaque
;
3669 void qemu_system_reset(void)
3673 /* reset all devices */
3674 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
3675 re
->func(re
->opaque
);
3679 void qemu_system_reset_request(void)
3682 shutdown_requested
= 1;
3684 reset_requested
= 1;
3686 if (cpu_single_env
) {
3687 qemu_kvm_cpu_stop(cpu_single_env
);
3688 cpu_exit(cpu_single_env
);
3692 void qemu_system_shutdown_request(void)
3694 shutdown_requested
= 1;
3696 cpu_exit(cpu_single_env
);
3699 void qemu_system_powerdown_request(void)
3701 powerdown_requested
= 1;
3703 cpu_exit(cpu_single_env
);
3706 static int qemu_select(int max_fd
, fd_set
*rfds
, fd_set
*wfds
, fd_set
*xfds
,
3711 /* KVM holds a mutex while QEMU code is running, we need hooks to
3712 release the mutex whenever QEMU code sleeps. */
3716 ret
= select(max_fd
, rfds
, wfds
, xfds
, tv
);
3724 static void host_main_loop_wait(int *timeout
)
3730 /* XXX: need to suppress polling by better using win32 events */
3732 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
3733 ret
|= pe
->func(pe
->opaque
);
3737 WaitObjects
*w
= &wait_objects
;
3739 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
3740 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
3741 if (w
->func
[ret
- WAIT_OBJECT_0
])
3742 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
3744 /* Check for additional signaled events */
3745 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
3747 /* Check if event is signaled */
3748 ret2
= WaitForSingleObject(w
->events
[i
], 0);
3749 if(ret2
== WAIT_OBJECT_0
) {
3751 w
->func
[i
](w
->opaque
[i
]);
3752 } else if (ret2
== WAIT_TIMEOUT
) {
3754 err
= GetLastError();
3755 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
3758 } else if (ret
== WAIT_TIMEOUT
) {
3760 err
= GetLastError();
3761 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
3768 static void host_main_loop_wait(int *timeout
)
3773 void main_loop_wait(int timeout
)
3775 IOHandlerRecord
*ioh
;
3776 fd_set rfds
, wfds
, xfds
;
3780 qemu_bh_update_timeout(&timeout
);
3782 host_main_loop_wait(&timeout
);
3784 /* poll any events */
3785 /* XXX: separate device handlers from system ones */
3790 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3794 (!ioh
->fd_read_poll
||
3795 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
3796 FD_SET(ioh
->fd
, &rfds
);
3800 if (ioh
->fd_write
) {
3801 FD_SET(ioh
->fd
, &wfds
);
3807 tv
.tv_sec
= timeout
/ 1000;
3808 tv
.tv_usec
= (timeout
% 1000) * 1000;
3810 #if defined(CONFIG_SLIRP)
3811 if (slirp_is_inited()) {
3812 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
3815 ret
= qemu_select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
3817 IOHandlerRecord
**pioh
;
3819 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3820 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
3821 ioh
->fd_read(ioh
->opaque
);
3822 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
3823 FD_CLR(ioh
->fd
, &rfds
);
3825 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
3826 ioh
->fd_write(ioh
->opaque
);
3830 /* remove deleted IO handlers */
3831 pioh
= &first_io_handler
;
3841 #if defined(CONFIG_SLIRP)
3842 if (slirp_is_inited()) {
3848 slirp_select_poll(&rfds
, &wfds
, &xfds
);
3852 /* vm time timers */
3853 if (vm_running
&& (!cur_cpu
3854 || likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
))))
3855 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
3856 qemu_get_clock(vm_clock
));
3858 /* real time timers */
3859 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
3860 qemu_get_clock(rt_clock
));
3862 /* Check bottom-halves last in case any of the earlier events triggered
3868 static int main_loop(void)
3871 #ifdef CONFIG_PROFILER
3877 if (kvm_enabled()) {
3879 cpu_disable_ticks();
3883 cur_cpu
= first_cpu
;
3884 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
3891 #ifdef CONFIG_PROFILER
3892 ti
= profile_getclock();
3897 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
3898 env
->icount_decr
.u16
.low
= 0;
3899 env
->icount_extra
= 0;
3900 count
= qemu_next_deadline();
3901 count
= (count
+ (1 << icount_time_shift
) - 1)
3902 >> icount_time_shift
;
3903 qemu_icount
+= count
;
3904 decr
= (count
> 0xffff) ? 0xffff : count
;
3906 env
->icount_decr
.u16
.low
= decr
;
3907 env
->icount_extra
= count
;
3909 ret
= cpu_exec(env
);
3910 #ifdef CONFIG_PROFILER
3911 qemu_time
+= profile_getclock() - ti
;
3914 /* Fold pending instructions back into the
3915 instruction counter, and clear the interrupt flag. */
3916 qemu_icount
-= (env
->icount_decr
.u16
.low
3917 + env
->icount_extra
);
3918 env
->icount_decr
.u32
= 0;
3919 env
->icount_extra
= 0;
3921 next_cpu
= env
->next_cpu
?: first_cpu
;
3922 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
3923 ret
= EXCP_INTERRUPT
;
3927 if (ret
== EXCP_HLT
) {
3928 /* Give the next CPU a chance to run. */
3932 if (ret
!= EXCP_HALTED
)
3934 /* all CPUs are halted ? */
3940 if (shutdown_requested
) {
3941 ret
= EXCP_INTERRUPT
;
3949 if (reset_requested
) {
3950 reset_requested
= 0;
3951 qemu_system_reset();
3952 ret
= EXCP_INTERRUPT
;
3954 if (powerdown_requested
) {
3955 powerdown_requested
= 0;
3956 qemu_system_powerdown();
3957 ret
= EXCP_INTERRUPT
;
3959 #ifdef CONFIG_GDBSTUB
3960 if (unlikely(ret
== EXCP_DEBUG
)) {
3961 gdb_set_stop_cpu(cur_cpu
);
3962 vm_stop(EXCP_DEBUG
);
3965 /* If all cpus are halted then wait until the next IRQ */
3966 /* XXX: use timeout computed from timers */
3967 if (ret
== EXCP_HALTED
) {
3971 /* Advance virtual time to the next event. */
3972 if (use_icount
== 1) {
3973 /* When not using an adaptive execution frequency
3974 we tend to get badly out of sync with real time,
3975 so just delay for a reasonable amount of time. */
3978 delta
= cpu_get_icount() - cpu_get_clock();
3981 /* If virtual time is ahead of real time then just
3983 timeout
= (delta
/ 1000000) + 1;
3985 /* Wait for either IO to occur or the next
3987 add
= qemu_next_deadline();
3988 /* We advance the timer before checking for IO.
3989 Limit the amount we advance so that early IO
3990 activity won't get the guest too far ahead. */
3994 add
= (add
+ (1 << icount_time_shift
) - 1)
3995 >> icount_time_shift
;
3997 timeout
= delta
/ 1000000;
4008 if (shutdown_requested
) {
4009 ret
= EXCP_INTERRUPT
;
4014 #ifdef CONFIG_PROFILER
4015 ti
= profile_getclock();
4017 main_loop_wait(timeout
);
4018 #ifdef CONFIG_PROFILER
4019 dev_time
+= profile_getclock() - ti
;
4022 cpu_disable_ticks();
4026 static void help(int exitcode
)
4028 printf("QEMU PC emulator version " QEMU_VERSION
" (" KVM_VERSION
")"
4029 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
4030 "usage: %s [options] [disk_image]\n"
4032 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4034 #define DEF(option, opt_arg, opt_enum, opt_help) \
4036 #define DEFHEADING(text) stringify(text) "\n"
4037 #include "qemu-options.h"
4042 "During emulation, the following keys are useful:\n"
4043 "ctrl-alt-f toggle full screen\n"
4044 "ctrl-alt-n switch to virtual console 'n'\n"
4045 "ctrl-alt toggle mouse and keyboard grab\n"
4047 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4052 DEFAULT_NETWORK_SCRIPT
,
4053 DEFAULT_NETWORK_DOWN_SCRIPT
,
4055 DEFAULT_GDBSTUB_PORT
,
4060 #define HAS_ARG 0x0001
4063 #define DEF(option, opt_arg, opt_enum, opt_help) \
4065 #define DEFHEADING(text)
4066 #include "qemu-options.h"
4072 typedef struct QEMUOption
{
4078 static const QEMUOption qemu_options
[] = {
4079 { "h", 0, QEMU_OPTION_h
},
4080 #define DEF(option, opt_arg, opt_enum, opt_help) \
4081 { option, opt_arg, opt_enum },
4082 #define DEFHEADING(text)
4083 #include "qemu-options.h"
4091 struct soundhw soundhw
[] = {
4092 #ifdef HAS_AUDIO_CHOICE
4093 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4099 { .init_isa
= pcspk_audio_init
}
4106 "Creative Sound Blaster 16",
4109 { .init_isa
= SB16_init
}
4113 #ifdef CONFIG_CS4231A
4119 { .init_isa
= cs4231a_init
}
4127 "Yamaha YMF262 (OPL3)",
4129 "Yamaha YM3812 (OPL2)",
4133 { .init_isa
= Adlib_init
}
4140 "Gravis Ultrasound GF1",
4143 { .init_isa
= GUS_init
}
4150 "Intel 82801AA AC97 Audio",
4153 { .init_pci
= ac97_init
}
4157 #ifdef CONFIG_ES1370
4160 "ENSONIQ AudioPCI ES1370",
4163 { .init_pci
= es1370_init
}
4167 #endif /* HAS_AUDIO_CHOICE */
4169 { NULL
, NULL
, 0, 0, { NULL
} }
4172 static void select_soundhw (const char *optarg
)
4176 if (*optarg
== '?') {
4179 printf ("Valid sound card names (comma separated):\n");
4180 for (c
= soundhw
; c
->name
; ++c
) {
4181 printf ("%-11s %s\n", c
->name
, c
->descr
);
4183 printf ("\n-soundhw all will enable all of the above\n");
4184 exit (*optarg
!= '?');
4192 if (!strcmp (optarg
, "all")) {
4193 for (c
= soundhw
; c
->name
; ++c
) {
4201 e
= strchr (p
, ',');
4202 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4204 for (c
= soundhw
; c
->name
; ++c
) {
4205 if (!strncmp (c
->name
, p
, l
)) {
4214 "Unknown sound card name (too big to show)\n");
4217 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4222 p
+= l
+ (e
!= NULL
);
4226 goto show_valid_cards
;
4231 static void select_vgahw (const char *p
)
4235 if (strstart(p
, "std", &opts
)) {
4236 std_vga_enabled
= 1;
4237 cirrus_vga_enabled
= 0;
4239 } else if (strstart(p
, "cirrus", &opts
)) {
4240 cirrus_vga_enabled
= 1;
4241 std_vga_enabled
= 0;
4243 } else if (strstart(p
, "vmware", &opts
)) {
4244 cirrus_vga_enabled
= 0;
4245 std_vga_enabled
= 0;
4247 } else if (strstart(p
, "none", &opts
)) {
4248 cirrus_vga_enabled
= 0;
4249 std_vga_enabled
= 0;
4253 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4257 const char *nextopt
;
4259 if (strstart(opts
, ",retrace=", &nextopt
)) {
4261 if (strstart(opts
, "dumb", &nextopt
))
4262 vga_retrace_method
= VGA_RETRACE_DUMB
;
4263 else if (strstart(opts
, "precise", &nextopt
))
4264 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4265 else goto invalid_vga
;
4266 } else goto invalid_vga
;
4272 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4274 exit(STATUS_CONTROL_C_EXIT
);
4279 static int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4283 if(strlen(str
) != 36)
4286 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4287 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4288 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4296 #define MAX_NET_CLIENTS 32
4298 static int saved_argc
;
4299 static char **saved_argv
;
4300 static const char *saved_incoming
;
4302 void qemu_get_launch_info(int *argc
, char ***argv
, int *opt_daemonize
, const char **opt_incoming
)
4306 *opt_daemonize
= daemonize
;
4307 *opt_incoming
= saved_incoming
;
4312 #define HUGETLBFS_MAGIC 0x958458f6
4314 static long gethugepagesize(const char *path
)
4320 ret
= statfs(path
, &fs
);
4321 } while (ret
!= 0 && errno
== EINTR
);
4328 if (fs
.f_type
!= HUGETLBFS_MAGIC
)
4329 fprintf(stderr
, "Warning: path not on HugeTLBFS: %s\n", path
);
4334 static void *alloc_mem_area(size_t memory
, unsigned long *len
, const char *path
)
4343 if (!kvm_has_sync_mmu()) {
4344 fprintf(stderr
, "host lacks mmu notifiers, disabling --mem-path\n");
4348 if (asprintf(&filename
, "%s/kvm.XXXXXX", path
) == -1)
4351 hpagesize
= gethugepagesize(path
);
4355 fd
= mkstemp(filename
);
4364 memory
= (memory
+hpagesize
-1) & ~(hpagesize
-1);
4367 * ftruncate is not supported by hugetlbfs in older
4368 * hosts, so don't bother checking for errors.
4369 * If anything goes wrong with it under other filesystems,
4372 ftruncate(fd
, memory
);
4375 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4376 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4377 * to sidestep this quirk.
4379 flags
= mem_prealloc
? MAP_POPULATE
|MAP_SHARED
: MAP_PRIVATE
;
4380 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, flags
, fd
, 0);
4382 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
, fd
, 0);
4384 if (area
== MAP_FAILED
) {
4385 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4394 static void *qemu_alloc_physram(unsigned long memory
)
4398 unsigned long map_len
= memory
;
4401 area
= alloc_mem_area(memory
, &map_len
, mem_path
);
4404 area
= qemu_vmalloc(memory
);
4406 if (kvm_setup_guest_memory(area
, map_len
))
4414 static void termsig_handler(int signal
)
4416 qemu_system_shutdown_request();
4419 static void termsig_setup(void)
4421 struct sigaction act
;
4423 memset(&act
, 0, sizeof(act
));
4424 act
.sa_handler
= termsig_handler
;
4425 sigaction(SIGINT
, &act
, NULL
);
4426 sigaction(SIGHUP
, &act
, NULL
);
4427 sigaction(SIGTERM
, &act
, NULL
);
4432 int main(int argc
, char **argv
, char **envp
)
4434 #ifdef CONFIG_GDBSTUB
4435 const char *gdbstub_dev
= NULL
;
4437 uint32_t boot_devices_bitmap
= 0;
4439 int snapshot
, linux_boot
, net_boot
;
4440 const char *initrd_filename
;
4441 const char *kernel_filename
, *kernel_cmdline
;
4442 const char *boot_devices
= "";
4444 DisplayChangeListener
*dcl
;
4445 int cyls
, heads
, secs
, translation
;
4446 const char *net_clients
[MAX_NET_CLIENTS
];
4448 const char *bt_opts
[MAX_BT_CMDLINE
];
4452 const char *r
, *optarg
;
4453 CharDriverState
*monitor_hd
= NULL
;
4454 const char *monitor_device
;
4455 const char *serial_devices
[MAX_SERIAL_PORTS
];
4456 int serial_device_index
;
4457 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
4458 int parallel_device_index
;
4459 const char *virtio_consoles
[MAX_VIRTIO_CONSOLES
];
4460 int virtio_console_index
;
4461 const char *loadvm
= NULL
;
4462 QEMUMachine
*machine
;
4463 const char *cpu_model
;
4464 const char *usb_devices
[MAX_USB_CMDLINE
];
4465 int usb_devices_index
;
4470 const char *pid_file
= NULL
;
4471 const char *incoming
= NULL
;
4474 struct passwd
*pwd
= NULL
;
4475 const char *chroot_dir
= NULL
;
4476 const char *run_as
= NULL
;
4479 qemu_cache_utils_init(envp
);
4481 LIST_INIT (&vm_change_state_head
);
4484 struct sigaction act
;
4485 sigfillset(&act
.sa_mask
);
4487 act
.sa_handler
= SIG_IGN
;
4488 sigaction(SIGPIPE
, &act
, NULL
);
4491 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4492 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4493 QEMU to run on a single CPU */
4498 h
= GetCurrentProcess();
4499 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4500 for(i
= 0; i
< 32; i
++) {
4501 if (mask
& (1 << i
))
4506 SetProcessAffinityMask(h
, mask
);
4512 register_machines();
4513 machine
= first_machine
;
4515 initrd_filename
= NULL
;
4517 vga_ram_size
= VGA_RAM_SIZE
;
4521 kernel_filename
= NULL
;
4522 kernel_cmdline
= "";
4523 cyls
= heads
= secs
= 0;
4524 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4525 monitor_device
= "vc:80Cx24C";
4527 serial_devices
[0] = "vc:80Cx24C";
4528 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
4529 serial_devices
[i
] = NULL
;
4530 serial_device_index
= 0;
4532 parallel_devices
[0] = "vc:80Cx24C";
4533 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
4534 parallel_devices
[i
] = NULL
;
4535 parallel_device_index
= 0;
4537 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++)
4538 virtio_consoles
[i
] = NULL
;
4539 virtio_console_index
= 0;
4541 usb_devices_index
= 0;
4542 assigned_devices_index
= 0;
4561 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
4563 const QEMUOption
*popt
;
4566 /* Treat --foo the same as -foo. */
4569 popt
= qemu_options
;
4572 fprintf(stderr
, "%s: invalid option -- '%s'\n",
4576 if (!strcmp(popt
->name
, r
+ 1))
4580 if (popt
->flags
& HAS_ARG
) {
4581 if (optind
>= argc
) {
4582 fprintf(stderr
, "%s: option '%s' requires an argument\n",
4586 optarg
= argv
[optind
++];
4591 switch(popt
->index
) {
4593 machine
= find_machine(optarg
);
4596 printf("Supported machines are:\n");
4597 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
4598 printf("%-10s %s%s\n",
4600 m
== first_machine
? " (default)" : "");
4602 exit(*optarg
!= '?');
4605 case QEMU_OPTION_cpu
:
4606 /* hw initialization will check this */
4607 if (*optarg
== '?') {
4608 /* XXX: implement xxx_cpu_list for targets that still miss it */
4609 #if defined(cpu_list)
4610 cpu_list(stdout
, &fprintf
);
4617 case QEMU_OPTION_initrd
:
4618 initrd_filename
= optarg
;
4620 case QEMU_OPTION_hda
:
4622 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
4624 hda_index
= drive_add(optarg
, HD_ALIAS
4625 ",cyls=%d,heads=%d,secs=%d%s",
4626 0, cyls
, heads
, secs
,
4627 translation
== BIOS_ATA_TRANSLATION_LBA
?
4629 translation
== BIOS_ATA_TRANSLATION_NONE
?
4630 ",trans=none" : "");
4632 case QEMU_OPTION_hdb
:
4633 case QEMU_OPTION_hdc
:
4634 case QEMU_OPTION_hdd
:
4635 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
4637 case QEMU_OPTION_drive
:
4638 drive_add(NULL
, "%s", optarg
);
4640 case QEMU_OPTION_mtdblock
:
4641 drive_add(optarg
, MTD_ALIAS
);
4643 case QEMU_OPTION_sd
:
4644 drive_add(optarg
, SD_ALIAS
);
4646 case QEMU_OPTION_pflash
:
4647 drive_add(optarg
, PFLASH_ALIAS
);
4649 case QEMU_OPTION_snapshot
:
4652 case QEMU_OPTION_hdachs
:
4656 cyls
= strtol(p
, (char **)&p
, 0);
4657 if (cyls
< 1 || cyls
> 16383)
4662 heads
= strtol(p
, (char **)&p
, 0);
4663 if (heads
< 1 || heads
> 16)
4668 secs
= strtol(p
, (char **)&p
, 0);
4669 if (secs
< 1 || secs
> 63)
4673 if (!strcmp(p
, "none"))
4674 translation
= BIOS_ATA_TRANSLATION_NONE
;
4675 else if (!strcmp(p
, "lba"))
4676 translation
= BIOS_ATA_TRANSLATION_LBA
;
4677 else if (!strcmp(p
, "auto"))
4678 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4681 } else if (*p
!= '\0') {
4683 fprintf(stderr
, "qemu: invalid physical CHS format\n");
4686 if (hda_index
!= -1)
4687 snprintf(drives_opt
[hda_index
].opt
,
4688 sizeof(drives_opt
[hda_index
].opt
),
4689 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
4690 0, cyls
, heads
, secs
,
4691 translation
== BIOS_ATA_TRANSLATION_LBA
?
4693 translation
== BIOS_ATA_TRANSLATION_NONE
?
4694 ",trans=none" : "");
4697 case QEMU_OPTION_nographic
:
4700 #ifdef CONFIG_CURSES
4701 case QEMU_OPTION_curses
:
4705 case QEMU_OPTION_portrait
:
4708 case QEMU_OPTION_kernel
:
4709 kernel_filename
= optarg
;
4711 case QEMU_OPTION_append
:
4712 kernel_cmdline
= optarg
;
4714 case QEMU_OPTION_cdrom
:
4715 drive_add(optarg
, CDROM_ALIAS
);
4717 case QEMU_OPTION_boot
:
4718 boot_devices
= optarg
;
4719 /* We just do some generic consistency checks */
4721 /* Could easily be extended to 64 devices if needed */
4724 boot_devices_bitmap
= 0;
4725 for (p
= boot_devices
; *p
!= '\0'; p
++) {
4726 /* Allowed boot devices are:
4727 * a b : floppy disk drives
4728 * c ... f : IDE disk drives
4729 * g ... m : machine implementation dependant drives
4730 * n ... p : network devices
4731 * It's up to each machine implementation to check
4732 * if the given boot devices match the actual hardware
4733 * implementation and firmware features.
4735 if (*p
< 'a' || *p
> 'q') {
4736 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
4739 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
4741 "Boot device '%c' was given twice\n",*p
);
4744 boot_devices_bitmap
|= 1 << (*p
- 'a');
4748 case QEMU_OPTION_fda
:
4749 case QEMU_OPTION_fdb
:
4750 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
4753 case QEMU_OPTION_no_fd_bootchk
:
4757 case QEMU_OPTION_net
:
4758 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
4759 fprintf(stderr
, "qemu: too many network clients\n");
4762 net_clients
[nb_net_clients
] = optarg
;
4766 case QEMU_OPTION_tftp
:
4767 tftp_prefix
= optarg
;
4769 case QEMU_OPTION_bootp
:
4770 bootp_filename
= optarg
;
4773 case QEMU_OPTION_smb
:
4774 net_slirp_smb(optarg
);
4777 case QEMU_OPTION_redir
:
4778 net_slirp_redir(optarg
);
4781 case QEMU_OPTION_bt
:
4782 if (nb_bt_opts
>= MAX_BT_CMDLINE
) {
4783 fprintf(stderr
, "qemu: too many bluetooth options\n");
4786 bt_opts
[nb_bt_opts
++] = optarg
;
4789 case QEMU_OPTION_audio_help
:
4793 case QEMU_OPTION_soundhw
:
4794 select_soundhw (optarg
);
4800 case QEMU_OPTION_m
: {
4804 value
= strtoul(optarg
, &ptr
, 10);
4806 case 0: case 'M': case 'm':
4813 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
4817 /* On 32-bit hosts, QEMU is limited by virtual address space */
4818 if (value
> (2047 << 20)
4820 && HOST_LONG_BITS
== 32
4823 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
4826 if (value
!= (uint64_t)(ram_addr_t
)value
) {
4827 fprintf(stderr
, "qemu: ram size too large\n");
4836 const CPULogItem
*item
;
4838 mask
= cpu_str_to_log_mask(optarg
);
4840 printf("Log items (comma separated):\n");
4841 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
4842 printf("%-10s %s\n", item
->name
, item
->help
);
4849 #ifdef CONFIG_GDBSTUB
4851 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
4853 case QEMU_OPTION_gdb
:
4854 gdbstub_dev
= optarg
;
4860 case QEMU_OPTION_bios
:
4863 case QEMU_OPTION_singlestep
:
4871 keyboard_layout
= optarg
;
4874 case QEMU_OPTION_localtime
:
4877 case QEMU_OPTION_vga
:
4878 select_vgahw (optarg
);
4880 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4886 w
= strtol(p
, (char **)&p
, 10);
4889 fprintf(stderr
, "qemu: invalid resolution or depth\n");
4895 h
= strtol(p
, (char **)&p
, 10);
4900 depth
= strtol(p
, (char **)&p
, 10);
4901 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
4902 depth
!= 24 && depth
!= 32)
4904 } else if (*p
== '\0') {
4905 depth
= graphic_depth
;
4912 graphic_depth
= depth
;
4916 case QEMU_OPTION_echr
:
4919 term_escape_char
= strtol(optarg
, &r
, 0);
4921 printf("Bad argument to echr\n");
4924 case QEMU_OPTION_monitor
:
4925 monitor_device
= optarg
;
4927 case QEMU_OPTION_serial
:
4928 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
4929 fprintf(stderr
, "qemu: too many serial ports\n");
4932 serial_devices
[serial_device_index
] = optarg
;
4933 serial_device_index
++;
4935 case QEMU_OPTION_virtiocon
:
4936 if (virtio_console_index
>= MAX_VIRTIO_CONSOLES
) {
4937 fprintf(stderr
, "qemu: too many virtio consoles\n");
4940 virtio_consoles
[virtio_console_index
] = optarg
;
4941 virtio_console_index
++;
4943 case QEMU_OPTION_parallel
:
4944 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
4945 fprintf(stderr
, "qemu: too many parallel ports\n");
4948 parallel_devices
[parallel_device_index
] = optarg
;
4949 parallel_device_index
++;
4951 case QEMU_OPTION_loadvm
:
4954 case QEMU_OPTION_full_screen
:
4958 case QEMU_OPTION_no_frame
:
4961 case QEMU_OPTION_alt_grab
:
4964 case QEMU_OPTION_no_quit
:
4967 case QEMU_OPTION_sdl
:
4971 case QEMU_OPTION_pidfile
:
4975 case QEMU_OPTION_win2k_hack
:
4976 win2k_install_hack
= 1;
4978 case QEMU_OPTION_rtc_td_hack
:
4981 case QEMU_OPTION_acpitable
:
4982 if(acpi_table_add(optarg
) < 0) {
4983 fprintf(stderr
, "Wrong acpi table provided\n");
4989 case QEMU_OPTION_no_kqemu
:
4992 case QEMU_OPTION_kernel_kqemu
:
4997 case QEMU_OPTION_enable_kvm
:
5005 case QEMU_OPTION_no_kvm
:
5008 case QEMU_OPTION_no_kvm_irqchip
: {
5013 case QEMU_OPTION_no_kvm_pit
: {
5017 case QEMU_OPTION_no_kvm_pit_reinjection
: {
5018 kvm_pit_reinject
= 0;
5021 case QEMU_OPTION_enable_nesting
: {
5025 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5026 case QEMU_OPTION_pcidevice
:
5027 if (assigned_devices_index
>= MAX_DEV_ASSIGN_CMDLINE
) {
5028 fprintf(stderr
, "Too many assigned devices\n");
5031 assigned_devices
[assigned_devices_index
] = optarg
;
5032 assigned_devices_index
++;
5036 case QEMU_OPTION_usb
:
5039 case QEMU_OPTION_usbdevice
:
5041 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
5042 fprintf(stderr
, "Too many USB devices\n");
5045 usb_devices
[usb_devices_index
] = optarg
;
5046 usb_devices_index
++;
5048 case QEMU_OPTION_smp
:
5049 smp_cpus
= atoi(optarg
);
5051 fprintf(stderr
, "Invalid number of CPUs\n");
5055 case QEMU_OPTION_vnc
:
5056 vnc_display
= optarg
;
5059 case QEMU_OPTION_no_acpi
:
5062 case QEMU_OPTION_no_hpet
:
5066 case QEMU_OPTION_no_reboot
:
5069 case QEMU_OPTION_no_shutdown
:
5072 case QEMU_OPTION_show_cursor
:
5075 case QEMU_OPTION_uuid
:
5076 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5077 fprintf(stderr
, "Fail to parse UUID string."
5078 " Wrong format.\n");
5083 case QEMU_OPTION_daemonize
:
5087 case QEMU_OPTION_option_rom
:
5088 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5089 fprintf(stderr
, "Too many option ROMs\n");
5092 option_rom
[nb_option_roms
] = optarg
;
5095 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5096 case QEMU_OPTION_semihosting
:
5097 semihosting_enabled
= 1;
5100 case QEMU_OPTION_tdf
:
5103 case QEMU_OPTION_kvm_shadow_memory
:
5104 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
5106 case QEMU_OPTION_mempath
:
5110 case QEMU_OPTION_mem_prealloc
:
5111 mem_prealloc
= !mem_prealloc
;
5114 case QEMU_OPTION_name
:
5117 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5118 case QEMU_OPTION_prom_env
:
5119 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5120 fprintf(stderr
, "Too many prom variables\n");
5123 prom_envs
[nb_prom_envs
] = optarg
;
5127 case QEMU_OPTION_cpu_vendor
:
5128 cpu_vendor_string
= optarg
;
5131 case QEMU_OPTION_old_param
:
5135 case QEMU_OPTION_clock
:
5136 configure_alarms(optarg
);
5138 case QEMU_OPTION_startdate
:
5141 time_t rtc_start_date
;
5142 if (!strcmp(optarg
, "now")) {
5143 rtc_date_offset
= -1;
5145 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
5153 } else if (sscanf(optarg
, "%d-%d-%d",
5156 &tm
.tm_mday
) == 3) {
5165 rtc_start_date
= mktimegm(&tm
);
5166 if (rtc_start_date
== -1) {
5168 fprintf(stderr
, "Invalid date format. Valid format are:\n"
5169 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5172 rtc_date_offset
= time(NULL
) - rtc_start_date
;
5176 case QEMU_OPTION_tb_size
:
5177 tb_size
= strtol(optarg
, NULL
, 0);
5181 case QEMU_OPTION_icount
:
5183 if (strcmp(optarg
, "auto") == 0) {
5184 icount_time_shift
= -1;
5186 icount_time_shift
= strtol(optarg
, NULL
, 0);
5189 case QEMU_OPTION_incoming
:
5191 saved_incoming
= incoming
;
5194 case QEMU_OPTION_chroot
:
5195 chroot_dir
= optarg
;
5197 case QEMU_OPTION_runas
:
5200 case QEMU_OPTION_nvram
:
5208 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5209 if (kvm_allowed
&& kqemu_allowed
) {
5211 "You can not enable both KVM and kqemu at the same time\n");
5216 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5217 if (smp_cpus
> machine
->max_cpus
) {
5218 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5219 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5225 if (serial_device_index
== 0)
5226 serial_devices
[0] = "stdio";
5227 if (parallel_device_index
== 0)
5228 parallel_devices
[0] = "null";
5229 if (strncmp(monitor_device
, "vc", 2) == 0)
5230 monitor_device
= "stdio";
5237 if (pipe(fds
) == -1)
5248 len
= read(fds
[0], &status
, 1);
5249 if (len
== -1 && (errno
== EINTR
))
5254 else if (status
== 1) {
5255 fprintf(stderr
, "Could not acquire pidfile\n");
5272 signal(SIGTSTP
, SIG_IGN
);
5273 signal(SIGTTOU
, SIG_IGN
);
5274 signal(SIGTTIN
, SIG_IGN
);
5278 if (kvm_enabled()) {
5279 if (kvm_qemu_init() < 0) {
5280 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
5281 #ifdef NO_CPU_EMULATION
5282 fprintf(stderr
, "Compiled with --disable-cpu-emulation, exiting.\n");
5290 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5293 write(fds
[1], &status
, 1);
5295 fprintf(stderr
, "Could not acquire pid file\n");
5304 linux_boot
= (kernel_filename
!= NULL
);
5305 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5307 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5308 fprintf(stderr
, "-append only allowed with -kernel option\n");
5312 if (!linux_boot
&& initrd_filename
!= NULL
) {
5313 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5317 /* boot to floppy or the default cd if no hard disk defined yet */
5318 if (!boot_devices
[0]) {
5319 boot_devices
= "cad";
5321 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5324 if (init_timer_alarm() < 0) {
5325 fprintf(stderr
, "could not initialize alarm timer\n");
5328 if (use_icount
&& icount_time_shift
< 0) {
5330 /* 125MIPS seems a reasonable initial guess at the guest speed.
5331 It will be corrected fairly quickly anyway. */
5332 icount_time_shift
= 3;
5333 init_icount_adjust();
5340 /* init network clients */
5341 if (nb_net_clients
== 0) {
5342 /* if no clients, we use a default config */
5343 net_clients
[nb_net_clients
++] = "nic";
5345 net_clients
[nb_net_clients
++] = "user";
5349 for(i
= 0;i
< nb_net_clients
; i
++) {
5350 if (net_client_parse(net_clients
[i
]) < 0)
5356 /* XXX: this should be moved in the PC machine instantiation code */
5357 if (net_boot
!= 0) {
5359 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
5360 const char *model
= nd_table
[i
].model
;
5362 if (net_boot
& (1 << i
)) {
5365 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
5366 if (get_image_size(buf
) > 0) {
5367 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5368 fprintf(stderr
, "Too many option ROMs\n");
5371 option_rom
[nb_option_roms
] = strdup(buf
);
5378 fprintf(stderr
, "No valid PXE rom found for network device\n");
5384 /* init the bluetooth world */
5385 for (i
= 0; i
< nb_bt_opts
; i
++)
5386 if (bt_parse(bt_opts
[i
]))
5389 /* init the memory */
5390 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
5392 if (machine
->ram_require
& RAMSIZE_FIXED
) {
5394 if (ram_size
< phys_ram_size
) {
5395 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
5396 machine
->name
, (unsigned long long) phys_ram_size
);
5400 phys_ram_size
= ram_size
;
5402 ram_size
= phys_ram_size
;
5405 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5407 phys_ram_size
+= ram_size
;
5410 /* Initialize kvm */
5411 #if defined(TARGET_I386) || defined(TARGET_X86_64)
5412 #define KVM_EXTRA_PAGES 3
5414 #define KVM_EXTRA_PAGES 0
5416 if (kvm_enabled()) {
5417 phys_ram_size
+= KVM_EXTRA_PAGES
* TARGET_PAGE_SIZE
;
5418 if (kvm_qemu_create_context() < 0) {
5419 fprintf(stderr
, "Could not create KVM context\n");
5424 phys_ram_base
= qemu_alloc_physram(phys_ram_size
);
5425 if (!phys_ram_base
) {
5426 fprintf(stderr
, "Could not allocate physical memory\n");
5430 /* init the dynamic translator */
5431 cpu_exec_init_all(tb_size
* 1024 * 1024);
5436 /* we always create the cdrom drive, even if no disk is there */
5438 if (nb_drives_opt
< MAX_DRIVES
)
5439 drive_add(NULL
, CDROM_ALIAS
);
5441 /* we always create at least one floppy */
5443 if (nb_drives_opt
< MAX_DRIVES
)
5444 drive_add(NULL
, FD_ALIAS
, 0);
5446 /* we always create one sd slot, even if no card is in it */
5448 if (nb_drives_opt
< MAX_DRIVES
)
5449 drive_add(NULL
, SD_ALIAS
);
5451 /* open the virtual block devices
5452 * note that migration with device
5453 * hot add/remove is broken.
5455 for(i
= 0; i
< nb_drives_opt
; i
++)
5456 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
5459 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
5460 register_savevm_live("ram", 0, 3, ram_save_live
, NULL
, ram_load
, NULL
);
5463 /* must be after terminal init, SDL library changes signal handlers */
5467 /* Maintain compatibility with multiple stdio monitors */
5468 if (!strcmp(monitor_device
,"stdio")) {
5469 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5470 const char *devname
= serial_devices
[i
];
5471 if (devname
&& !strcmp(devname
,"mon:stdio")) {
5472 monitor_device
= NULL
;
5474 } else if (devname
&& !strcmp(devname
,"stdio")) {
5475 monitor_device
= NULL
;
5476 serial_devices
[i
] = "mon:stdio";
5483 if (kvm_enabled()) {
5486 ret
= kvm_init(smp_cpus
);
5488 fprintf(stderr
, "failed to initialize KVM\n");
5494 if (monitor_device
) {
5495 monitor_hd
= qemu_chr_open("monitor", monitor_device
, NULL
);
5497 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
5502 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5503 const char *devname
= serial_devices
[i
];
5504 if (devname
&& strcmp(devname
, "none")) {
5506 snprintf(label
, sizeof(label
), "serial%d", i
);
5507 serial_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5508 if (!serial_hds
[i
]) {
5509 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
5516 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
5517 const char *devname
= parallel_devices
[i
];
5518 if (devname
&& strcmp(devname
, "none")) {
5520 snprintf(label
, sizeof(label
), "parallel%d", i
);
5521 parallel_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5522 if (!parallel_hds
[i
]) {
5523 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
5530 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
5531 const char *devname
= virtio_consoles
[i
];
5532 if (devname
&& strcmp(devname
, "none")) {
5534 snprintf(label
, sizeof(label
), "virtcon%d", i
);
5535 virtcon_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5536 if (!virtcon_hds
[i
]) {
5537 fprintf(stderr
, "qemu: could not open virtio console '%s'\n",
5547 machine
->init(ram_size
, vga_ram_size
, boot_devices
,
5548 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
5550 current_machine
= machine
;
5552 /* Set KVM's vcpu state to qemu's initial CPUState. */
5553 if (kvm_enabled()) {
5556 ret
= kvm_sync_vcpus();
5558 fprintf(stderr
, "failed to initialize vcpus\n");
5563 /* init USB devices */
5565 for(i
= 0; i
< usb_devices_index
; i
++) {
5566 if (usb_device_add(usb_devices
[i
], 0) < 0) {
5567 fprintf(stderr
, "Warning: could not add USB device %s\n",
5574 dumb_display_init();
5575 /* just use the first displaystate for the moment */
5580 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
5584 #if defined(CONFIG_CURSES)
5586 /* At the moment curses cannot be used with other displays */
5587 curses_display_init(ds
, full_screen
);
5591 if (vnc_display
!= NULL
) {
5592 vnc_display_init(ds
);
5593 if (vnc_display_open(ds
, vnc_display
) < 0)
5596 #if defined(CONFIG_SDL)
5597 if (sdl
|| !vnc_display
)
5598 sdl_display_init(ds
, full_screen
, no_frame
);
5599 #elif defined(CONFIG_COCOA)
5600 if (sdl
|| !vnc_display
)
5601 cocoa_display_init(ds
, full_screen
);
5607 dcl
= ds
->listeners
;
5608 while (dcl
!= NULL
) {
5609 if (dcl
->dpy_refresh
!= NULL
) {
5610 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
5611 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
5616 if (nographic
|| (vnc_display
&& !sdl
)) {
5617 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
5618 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
5621 text_consoles_set_display(display_state
);
5622 qemu_chr_initial_reset();
5624 if (monitor_device
&& monitor_hd
)
5625 monitor_init(monitor_hd
, MONITOR_USE_READLINE
| MONITOR_IS_DEFAULT
);
5627 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5628 const char *devname
= serial_devices
[i
];
5629 if (devname
&& strcmp(devname
, "none")) {
5631 snprintf(label
, sizeof(label
), "serial%d", i
);
5632 if (strstart(devname
, "vc", 0))
5633 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
5637 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
5638 const char *devname
= parallel_devices
[i
];
5639 if (devname
&& strcmp(devname
, "none")) {
5641 snprintf(label
, sizeof(label
), "parallel%d", i
);
5642 if (strstart(devname
, "vc", 0))
5643 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
5647 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
5648 const char *devname
= virtio_consoles
[i
];
5649 if (virtcon_hds
[i
] && devname
) {
5651 snprintf(label
, sizeof(label
), "virtcon%d", i
);
5652 if (strstart(devname
, "vc", 0))
5653 qemu_chr_printf(virtcon_hds
[i
], "virtio console%d\r\n", i
);
5657 #ifdef CONFIG_GDBSTUB
5658 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
5659 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
5666 do_loadvm(cur_mon
, loadvm
);
5669 autostart
= 0; /* fixme how to deal with -daemonize */
5670 qemu_start_incoming_migration(incoming
);
5682 len
= write(fds
[1], &status
, 1);
5683 if (len
== -1 && (errno
== EINTR
))
5690 TFR(fd
= open("/dev/null", O_RDWR
));
5696 pwd
= getpwnam(run_as
);
5698 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
5704 if (chroot(chroot_dir
) < 0) {
5705 fprintf(stderr
, "chroot failed\n");
5712 if (setgid(pwd
->pw_gid
) < 0) {
5713 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
5716 if (setuid(pwd
->pw_uid
) < 0) {
5717 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
5720 if (setuid(0) != -1) {
5721 fprintf(stderr
, "Dropping privileges failed\n");