4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
32 /* Needed early for HOST_BSD etc. */
33 #include "config-host.h"
38 #include <sys/times.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
47 #if defined(__NetBSD__)
48 #include <net/if_tap.h>
51 #include <linux/if_tun.h>
53 #include <arpa/inet.h>
56 #include <sys/select.h>
59 #if defined(__FreeBSD__) || defined(__DragonFly__)
64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65 #include <freebsd/stdlib.h>
70 #include <linux/rtc.h>
72 /* For the benefit of older linux systems which don't supply it,
73 we use a local copy of hpet.h. */
74 /* #include <linux/hpet.h> */
77 #include <linux/ppdev.h>
78 #include <linux/parport.h>
82 #include <sys/ethernet.h>
83 #include <sys/sockio.h>
84 #include <netinet/arp.h>
85 #include <netinet/in.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip_icmp.h> // must come after ip.h
89 #include <netinet/udp.h>
90 #include <netinet/tcp.h>
98 #if defined(__OpenBSD__)
102 #if defined(CONFIG_VDE)
103 #include <libvdeplug.h>
109 #include <sys/timeb.h>
110 #include <mmsystem.h>
111 #define getopt_long_only getopt_long
112 #define memalign(align, size) malloc(size)
116 #if defined(__APPLE__) || defined(main)
118 int qemu_main(int argc
, char **argv
, char **envp
);
119 int main(int argc
, char **argv
)
121 return qemu_main(argc
, argv
, NULL
);
124 #define main qemu_main
126 #endif /* CONFIG_SDL */
130 #define main qemu_main
131 #endif /* CONFIG_COCOA */
134 #include "hw/boards.h"
136 #include "hw/pcmcia.h"
138 #include "hw/audiodev.h"
142 #include "hw/watchdog.h"
143 #include "hw/smbios.h"
151 #include "qemu-timer.h"
152 #include "qemu-char.h"
153 #include "cache-utils.h"
156 #include "audio/audio.h"
157 #include "migration.h"
160 #include "qemu-option.h"
161 #include "qemu-kvm.h"
162 #include "hw/device-assignment.h"
166 #include "exec-all.h"
168 #include "qemu_socket.h"
170 #include "slirp/libslirp.h"
172 //#define DEBUG_UNUSED_IOPORT
173 //#define DEBUG_IOPORT
175 //#define DEBUG_SLIRP
179 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
181 # define LOG_IOPORT(...) do { } while (0)
184 #define DEFAULT_RAM_SIZE 128
186 /* Max number of USB devices that can be specified on the commandline. */
187 #define MAX_USB_CMDLINE 8
189 /* Max number of bluetooth switches on the commandline. */
190 #define MAX_BT_CMDLINE 10
192 /* XXX: use a two level table to limit memory usage */
193 #define MAX_IOPORTS 65536
195 static const char *data_dir
;
196 const char *bios_name
= NULL
;
197 static void *ioport_opaque
[MAX_IOPORTS
];
198 static IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
199 static IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
200 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
201 to store the VM snapshots */
202 DriveInfo drives_table
[MAX_DRIVES
+1];
204 int extboot_drive
= -1;
205 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
206 static DisplayState
*display_state
;
207 DisplayType display_type
= DT_DEFAULT
;
208 const char* keyboard_layout
= NULL
;
209 int64_t ticks_per_sec
;
212 NICInfo nd_table
[MAX_NICS
];
214 static int autostart
;
215 static int rtc_utc
= 1;
216 static int rtc_date_offset
= -1; /* -1 means no change */
217 int cirrus_vga_enabled
= 1;
218 int std_vga_enabled
= 0;
219 int vmsvga_enabled
= 0;
220 int xenfb_enabled
= 0;
222 int graphic_width
= 1024;
223 int graphic_height
= 768;
224 int graphic_depth
= 8;
226 int graphic_width
= 800;
227 int graphic_height
= 600;
228 int graphic_depth
= 15;
230 static int full_screen
= 0;
232 static int no_frame
= 0;
235 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
236 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
237 CharDriverState
*virtcon_hds
[MAX_VIRTIO_CONSOLES
];
239 int win2k_install_hack
= 0;
244 const char *assigned_devices
[MAX_DEV_ASSIGN_CMDLINE
];
245 int assigned_devices_index
;
247 const char *vnc_display
;
248 int acpi_enabled
= 1;
250 int no_virtio_balloon
= 0;
255 int graphic_rotate
= 0;
259 WatchdogTimerModel
*watchdog
= NULL
;
260 int watchdog_action
= WDT_RESET
;
261 const char *option_rom
[MAX_OPTION_ROMS
];
263 int semihosting_enabled
= 0;
264 int time_drift_fix
= 0;
265 unsigned int kvm_shadow_memory
= 0;
266 const char *mem_path
= NULL
;
268 int mem_prealloc
= 1; /* force preallocation of physical target memory */
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
];
284 uint64_t node_mem
[MAX_NODES
];
285 uint64_t node_cpumask
[MAX_NODES
];
287 static CPUState
*cur_cpu
;
288 static CPUState
*next_cpu
;
289 static int timer_alarm_pending
= 1;
290 /* Conversion factor from emulated instructions to virtual clock ticks. */
291 static int icount_time_shift
;
292 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
293 #define MAX_ICOUNT_SHIFT 10
294 /* Compensate for varying guest execution speed. */
295 static int64_t qemu_icount_bias
;
296 static QEMUTimer
*icount_rt_timer
;
297 static QEMUTimer
*icount_vm_timer
;
298 static QEMUTimer
*nographic_timer
;
300 uint8_t qemu_uuid
[16];
302 static int qemu_select(int max_fd
, fd_set
*rfds
, fd_set
*wfds
, fd_set
*xfds
,
307 /* KVM holds a mutex while QEMU code is running, we need hooks to
308 release the mutex whenever QEMU code sleeps. */
312 ret
= select(max_fd
, rfds
, wfds
, xfds
, tv
);
320 /***********************************************************/
321 /* x86 ISA bus support */
323 target_phys_addr_t isa_mem_base
= 0;
326 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
327 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
329 static uint32_t ioport_read(int index
, uint32_t address
)
331 static IOPortReadFunc
*default_func
[3] = {
332 default_ioport_readb
,
333 default_ioport_readw
,
336 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
338 func
= default_func
[index
];
339 return func(ioport_opaque
[address
], address
);
342 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
344 static IOPortWriteFunc
*default_func
[3] = {
345 default_ioport_writeb
,
346 default_ioport_writew
,
347 default_ioport_writel
349 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
351 func
= default_func
[index
];
352 func(ioport_opaque
[address
], address
, data
);
355 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
357 #ifdef DEBUG_UNUSED_IOPORT
358 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
363 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
365 #ifdef DEBUG_UNUSED_IOPORT
366 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
370 /* default is to make two byte accesses */
371 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
374 data
= ioport_read(0, address
);
375 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
376 data
|= ioport_read(0, address
) << 8;
380 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
382 ioport_write(0, address
, data
& 0xff);
383 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
384 ioport_write(0, address
, (data
>> 8) & 0xff);
387 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
389 #ifdef DEBUG_UNUSED_IOPORT
390 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
395 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
397 #ifdef DEBUG_UNUSED_IOPORT
398 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
402 /* size is the word size in byte */
403 int register_ioport_read(int start
, int length
, int size
,
404 IOPortReadFunc
*func
, void *opaque
)
410 } else if (size
== 2) {
412 } else if (size
== 4) {
415 hw_error("register_ioport_read: invalid size");
418 for(i
= start
; i
< start
+ length
; i
+= size
) {
419 ioport_read_table
[bsize
][i
] = func
;
420 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
421 hw_error("register_ioport_read: invalid opaque");
422 ioport_opaque
[i
] = opaque
;
427 /* size is the word size in byte */
428 int register_ioport_write(int start
, int length
, int size
,
429 IOPortWriteFunc
*func
, void *opaque
)
435 } else if (size
== 2) {
437 } else if (size
== 4) {
440 hw_error("register_ioport_write: invalid size");
443 for(i
= start
; i
< start
+ length
; i
+= size
) {
444 ioport_write_table
[bsize
][i
] = func
;
445 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
446 hw_error("register_ioport_write: invalid opaque");
447 ioport_opaque
[i
] = opaque
;
452 void isa_unassign_ioport(int start
, int length
)
456 for(i
= start
; i
< start
+ length
; i
++) {
457 ioport_read_table
[0][i
] = default_ioport_readb
;
458 ioport_read_table
[1][i
] = default_ioport_readw
;
459 ioport_read_table
[2][i
] = default_ioport_readl
;
461 ioport_write_table
[0][i
] = default_ioport_writeb
;
462 ioport_write_table
[1][i
] = default_ioport_writew
;
463 ioport_write_table
[2][i
] = default_ioport_writel
;
465 ioport_opaque
[i
] = NULL
;
469 /***********************************************************/
471 void cpu_outb(CPUState
*env
, int addr
, int val
)
473 LOG_IOPORT("outb: %04x %02x\n", addr
, val
);
474 ioport_write(0, addr
, val
);
477 env
->last_io_time
= cpu_get_time_fast();
481 void cpu_outw(CPUState
*env
, int addr
, int val
)
483 LOG_IOPORT("outw: %04x %04x\n", addr
, val
);
484 ioport_write(1, addr
, val
);
487 env
->last_io_time
= cpu_get_time_fast();
491 void cpu_outl(CPUState
*env
, int addr
, int val
)
493 LOG_IOPORT("outl: %04x %08x\n", addr
, val
);
494 ioport_write(2, addr
, val
);
497 env
->last_io_time
= cpu_get_time_fast();
501 int cpu_inb(CPUState
*env
, int addr
)
504 val
= ioport_read(0, addr
);
505 LOG_IOPORT("inb : %04x %02x\n", addr
, val
);
508 env
->last_io_time
= cpu_get_time_fast();
513 int cpu_inw(CPUState
*env
, int addr
)
516 val
= ioport_read(1, addr
);
517 LOG_IOPORT("inw : %04x %04x\n", addr
, val
);
520 env
->last_io_time
= cpu_get_time_fast();
525 int cpu_inl(CPUState
*env
, int addr
)
528 val
= ioport_read(2, addr
);
529 LOG_IOPORT("inl : %04x %08x\n", addr
, val
);
532 env
->last_io_time
= cpu_get_time_fast();
537 /***********************************************************/
538 void hw_error(const char *fmt
, ...)
544 fprintf(stderr
, "qemu: hardware error: ");
545 vfprintf(stderr
, fmt
, ap
);
546 fprintf(stderr
, "\n");
547 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
548 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
550 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
552 cpu_dump_state(env
, stderr
, fprintf
, 0);
562 static QEMUBalloonEvent
*qemu_balloon_event
;
563 void *qemu_balloon_event_opaque
;
565 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
567 qemu_balloon_event
= func
;
568 qemu_balloon_event_opaque
= opaque
;
571 void qemu_balloon(ram_addr_t target
)
573 if (qemu_balloon_event
)
574 qemu_balloon_event(qemu_balloon_event_opaque
, target
);
577 ram_addr_t
qemu_balloon_status(void)
579 if (qemu_balloon_event
)
580 return qemu_balloon_event(qemu_balloon_event_opaque
, 0);
584 /***********************************************************/
587 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
588 static void *qemu_put_kbd_event_opaque
;
589 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
590 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
592 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
594 qemu_put_kbd_event_opaque
= opaque
;
595 qemu_put_kbd_event
= func
;
598 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
599 void *opaque
, int absolute
,
602 QEMUPutMouseEntry
*s
, *cursor
;
604 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
606 s
->qemu_put_mouse_event
= func
;
607 s
->qemu_put_mouse_event_opaque
= opaque
;
608 s
->qemu_put_mouse_event_absolute
= absolute
;
609 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
612 if (!qemu_put_mouse_event_head
) {
613 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
617 cursor
= qemu_put_mouse_event_head
;
618 while (cursor
->next
!= NULL
)
619 cursor
= cursor
->next
;
622 qemu_put_mouse_event_current
= s
;
627 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
629 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
631 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
634 cursor
= qemu_put_mouse_event_head
;
635 while (cursor
!= NULL
&& cursor
!= entry
) {
637 cursor
= cursor
->next
;
640 if (cursor
== NULL
) // does not exist or list empty
642 else if (prev
== NULL
) { // entry is head
643 qemu_put_mouse_event_head
= cursor
->next
;
644 if (qemu_put_mouse_event_current
== entry
)
645 qemu_put_mouse_event_current
= cursor
->next
;
646 qemu_free(entry
->qemu_put_mouse_event_name
);
651 prev
->next
= entry
->next
;
653 if (qemu_put_mouse_event_current
== entry
)
654 qemu_put_mouse_event_current
= prev
;
656 qemu_free(entry
->qemu_put_mouse_event_name
);
660 void kbd_put_keycode(int keycode
)
662 if (qemu_put_kbd_event
) {
663 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
667 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
669 QEMUPutMouseEvent
*mouse_event
;
670 void *mouse_event_opaque
;
673 if (!qemu_put_mouse_event_current
) {
678 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
680 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
683 if (graphic_rotate
) {
684 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
687 width
= graphic_width
- 1;
688 mouse_event(mouse_event_opaque
,
689 width
- dy
, dx
, dz
, buttons_state
);
691 mouse_event(mouse_event_opaque
,
692 dx
, dy
, dz
, buttons_state
);
696 int kbd_mouse_is_absolute(void)
698 if (!qemu_put_mouse_event_current
)
701 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
704 void do_info_mice(Monitor
*mon
)
706 QEMUPutMouseEntry
*cursor
;
709 if (!qemu_put_mouse_event_head
) {
710 monitor_printf(mon
, "No mouse devices connected\n");
714 monitor_printf(mon
, "Mouse devices available:\n");
715 cursor
= qemu_put_mouse_event_head
;
716 while (cursor
!= NULL
) {
717 monitor_printf(mon
, "%c Mouse #%d: %s\n",
718 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
719 index
, cursor
->qemu_put_mouse_event_name
);
721 cursor
= cursor
->next
;
725 void do_mouse_set(Monitor
*mon
, int index
)
727 QEMUPutMouseEntry
*cursor
;
730 if (!qemu_put_mouse_event_head
) {
731 monitor_printf(mon
, "No mouse devices connected\n");
735 cursor
= qemu_put_mouse_event_head
;
736 while (cursor
!= NULL
&& index
!= i
) {
738 cursor
= cursor
->next
;
742 qemu_put_mouse_event_current
= cursor
;
744 monitor_printf(mon
, "Mouse at given index not found\n");
747 /* compute with 96 bit intermediate result: (a*b)/c */
748 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
753 #ifdef WORDS_BIGENDIAN
763 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
764 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
767 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
771 /***********************************************************/
772 /* real time host monotonic timer */
774 #define QEMU_TIMER_BASE 1000000000LL
778 static int64_t clock_freq
;
780 static void init_get_clock(void)
784 ret
= QueryPerformanceFrequency(&freq
);
786 fprintf(stderr
, "Could not calibrate ticks\n");
789 clock_freq
= freq
.QuadPart
;
792 static int64_t get_clock(void)
795 QueryPerformanceCounter(&ti
);
796 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
801 static int use_rt_clock
;
803 static void init_get_clock(void)
806 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
807 || defined(__DragonFly__)
810 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
817 static int64_t get_clock(void)
819 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
820 || defined(__DragonFly__)
823 clock_gettime(CLOCK_MONOTONIC
, &ts
);
824 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
828 /* XXX: using gettimeofday leads to problems if the date
829 changes, so it should be avoided. */
831 gettimeofday(&tv
, NULL
);
832 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
837 /* Return the virtual CPU time, based on the instruction counter. */
838 static int64_t cpu_get_icount(void)
841 CPUState
*env
= cpu_single_env
;;
842 icount
= qemu_icount
;
845 fprintf(stderr
, "Bad clock read\n");
846 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
848 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
851 /***********************************************************/
852 /* guest cycle counter */
854 static int64_t cpu_ticks_prev
;
855 static int64_t cpu_ticks_offset
;
856 static int64_t cpu_clock_offset
;
857 static int cpu_ticks_enabled
;
859 /* return the host CPU cycle counter and handle stop/restart */
860 int64_t cpu_get_ticks(void)
863 return cpu_get_icount();
865 if (!cpu_ticks_enabled
) {
866 return cpu_ticks_offset
;
869 ticks
= cpu_get_real_ticks();
870 if (cpu_ticks_prev
> ticks
) {
871 /* Note: non increasing ticks may happen if the host uses
873 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
875 cpu_ticks_prev
= ticks
;
876 return ticks
+ cpu_ticks_offset
;
880 /* return the host CPU monotonic timer and handle stop/restart */
881 static int64_t cpu_get_clock(void)
884 if (!cpu_ticks_enabled
) {
885 return cpu_clock_offset
;
888 return ti
+ cpu_clock_offset
;
892 /* enable cpu_get_ticks() */
893 void cpu_enable_ticks(void)
895 if (!cpu_ticks_enabled
) {
896 cpu_ticks_offset
-= cpu_get_real_ticks();
897 cpu_clock_offset
-= get_clock();
898 cpu_ticks_enabled
= 1;
902 /* disable cpu_get_ticks() : the clock is stopped. You must not call
903 cpu_get_ticks() after that. */
904 void cpu_disable_ticks(void)
906 if (cpu_ticks_enabled
) {
907 cpu_ticks_offset
= cpu_get_ticks();
908 cpu_clock_offset
= cpu_get_clock();
909 cpu_ticks_enabled
= 0;
913 /***********************************************************/
916 #define QEMU_TIMER_REALTIME 0
917 #define QEMU_TIMER_VIRTUAL 1
921 /* XXX: add frequency */
929 struct QEMUTimer
*next
;
932 struct qemu_alarm_timer
{
936 int (*start
)(struct qemu_alarm_timer
*t
);
937 void (*stop
)(struct qemu_alarm_timer
*t
);
938 void (*rearm
)(struct qemu_alarm_timer
*t
);
942 #define ALARM_FLAG_DYNTICKS 0x1
943 #define ALARM_FLAG_EXPIRED 0x2
945 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
947 return t
&& (t
->flags
& ALARM_FLAG_DYNTICKS
);
950 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
952 if (!alarm_has_dynticks(t
))
958 /* TODO: MIN_TIMER_REARM_US should be optimized */
959 #define MIN_TIMER_REARM_US 250
961 static struct qemu_alarm_timer
*alarm_timer
;
965 struct qemu_alarm_win32
{
968 } alarm_win32_data
= {0, -1};
970 static int win32_start_timer(struct qemu_alarm_timer
*t
);
971 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
972 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
976 static int unix_start_timer(struct qemu_alarm_timer
*t
);
977 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
981 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
982 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
983 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
985 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
986 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
988 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
989 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
991 #endif /* __linux__ */
995 /* Correlation between real and virtual time is always going to be
996 fairly approximate, so ignore small variation.
997 When the guest is idle real and virtual time will be aligned in
999 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
1001 static void icount_adjust(void)
1006 static int64_t last_delta
;
1007 /* If the VM is not running, then do nothing. */
1011 cur_time
= cpu_get_clock();
1012 cur_icount
= qemu_get_clock(vm_clock
);
1013 delta
= cur_icount
- cur_time
;
1014 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1016 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
1017 && icount_time_shift
> 0) {
1018 /* The guest is getting too far ahead. Slow time down. */
1019 icount_time_shift
--;
1022 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
1023 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
1024 /* The guest is getting too far behind. Speed time up. */
1025 icount_time_shift
++;
1028 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
1031 static void icount_adjust_rt(void * opaque
)
1033 qemu_mod_timer(icount_rt_timer
,
1034 qemu_get_clock(rt_clock
) + 1000);
1038 static void icount_adjust_vm(void * opaque
)
1040 qemu_mod_timer(icount_vm_timer
,
1041 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1045 static void init_icount_adjust(void)
1047 /* Have both realtime and virtual time triggers for speed adjustment.
1048 The realtime trigger catches emulated time passing too slowly,
1049 the virtual time trigger catches emulated time passing too fast.
1050 Realtime triggers occur even when idle, so use them less frequently
1051 than VM triggers. */
1052 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
1053 qemu_mod_timer(icount_rt_timer
,
1054 qemu_get_clock(rt_clock
) + 1000);
1055 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
1056 qemu_mod_timer(icount_vm_timer
,
1057 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1060 static struct qemu_alarm_timer alarm_timers
[] = {
1063 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
1064 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
1065 /* HPET - if available - is preferred */
1066 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
1067 /* ...otherwise try RTC */
1068 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1070 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1072 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1073 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1074 {"win32", 0, win32_start_timer
,
1075 win32_stop_timer
, NULL
, &alarm_win32_data
},
1080 static void show_available_alarms(void)
1084 printf("Available alarm timers, in order of precedence:\n");
1085 for (i
= 0; alarm_timers
[i
].name
; i
++)
1086 printf("%s\n", alarm_timers
[i
].name
);
1089 static void configure_alarms(char const *opt
)
1093 int count
= ARRAY_SIZE(alarm_timers
) - 1;
1096 struct qemu_alarm_timer tmp
;
1098 if (!strcmp(opt
, "?")) {
1099 show_available_alarms();
1105 /* Reorder the array */
1106 name
= strtok(arg
, ",");
1108 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1109 if (!strcmp(alarm_timers
[i
].name
, name
))
1114 fprintf(stderr
, "Unknown clock %s\n", name
);
1123 tmp
= alarm_timers
[i
];
1124 alarm_timers
[i
] = alarm_timers
[cur
];
1125 alarm_timers
[cur
] = tmp
;
1129 name
= strtok(NULL
, ",");
1135 /* Disable remaining timers */
1136 for (i
= cur
; i
< count
; i
++)
1137 alarm_timers
[i
].name
= NULL
;
1139 show_available_alarms();
1144 QEMUClock
*rt_clock
;
1145 QEMUClock
*vm_clock
;
1147 static QEMUTimer
*active_timers
[2];
1149 static QEMUClock
*qemu_new_clock(int type
)
1152 clock
= qemu_mallocz(sizeof(QEMUClock
));
1157 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1161 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1164 ts
->opaque
= opaque
;
1168 void qemu_free_timer(QEMUTimer
*ts
)
1173 /* stop a timer, but do not dealloc it */
1174 void qemu_del_timer(QEMUTimer
*ts
)
1178 /* NOTE: this code must be signal safe because
1179 qemu_timer_expired() can be called from a signal. */
1180 pt
= &active_timers
[ts
->clock
->type
];
1193 /* modify the current timer so that it will be fired when current_time
1194 >= expire_time. The corresponding callback will be called. */
1195 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1201 /* add the timer in the sorted list */
1202 /* NOTE: this code must be signal safe because
1203 qemu_timer_expired() can be called from a signal. */
1204 pt
= &active_timers
[ts
->clock
->type
];
1209 if (t
->expire_time
> expire_time
)
1213 ts
->expire_time
= expire_time
;
1217 /* Rearm if necessary */
1218 if (pt
== &active_timers
[ts
->clock
->type
]) {
1219 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1220 qemu_rearm_alarm_timer(alarm_timer
);
1222 /* Interrupt execution to force deadline recalculation. */
1224 qemu_notify_event();
1228 int qemu_timer_pending(QEMUTimer
*ts
)
1231 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1238 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1242 return (timer_head
->expire_time
<= current_time
);
1245 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1251 if (!ts
|| ts
->expire_time
> current_time
)
1253 /* remove timer from the list before calling the callback */
1254 *ptimer_head
= ts
->next
;
1257 /* run the callback (the timer list can be modified) */
1262 int64_t qemu_get_clock(QEMUClock
*clock
)
1264 switch(clock
->type
) {
1265 case QEMU_TIMER_REALTIME
:
1266 return get_clock() / 1000000;
1268 case QEMU_TIMER_VIRTUAL
:
1270 return cpu_get_icount();
1272 return cpu_get_clock();
1277 static void init_timers(void)
1280 ticks_per_sec
= QEMU_TIMER_BASE
;
1281 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1282 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1286 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1288 uint64_t expire_time
;
1290 if (qemu_timer_pending(ts
)) {
1291 expire_time
= ts
->expire_time
;
1295 qemu_put_be64(f
, expire_time
);
1298 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1300 uint64_t expire_time
;
1302 expire_time
= qemu_get_be64(f
);
1303 if (expire_time
!= -1) {
1304 qemu_mod_timer(ts
, expire_time
);
1310 static void timer_save(QEMUFile
*f
, void *opaque
)
1312 if (cpu_ticks_enabled
) {
1313 hw_error("cannot save state if virtual timers are running");
1315 qemu_put_be64(f
, cpu_ticks_offset
);
1316 qemu_put_be64(f
, ticks_per_sec
);
1317 qemu_put_be64(f
, cpu_clock_offset
);
1320 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1322 if (version_id
!= 1 && version_id
!= 2)
1324 if (cpu_ticks_enabled
) {
1327 cpu_ticks_offset
=qemu_get_be64(f
);
1328 ticks_per_sec
=qemu_get_be64(f
);
1329 if (version_id
== 2) {
1330 cpu_clock_offset
=qemu_get_be64(f
);
1335 static void qemu_event_increment(void);
1338 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1339 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1342 static void host_alarm_handler(int host_signum
)
1346 #define DISP_FREQ 1000
1348 static int64_t delta_min
= INT64_MAX
;
1349 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1351 ti
= qemu_get_clock(vm_clock
);
1352 if (last_clock
!= 0) {
1353 delta
= ti
- last_clock
;
1354 if (delta
< delta_min
)
1356 if (delta
> delta_max
)
1359 if (++count
== DISP_FREQ
) {
1360 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1361 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1362 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1363 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1364 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1366 delta_min
= INT64_MAX
;
1374 if (alarm_has_dynticks(alarm_timer
) ||
1376 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1377 qemu_get_clock(vm_clock
))) ||
1378 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1379 qemu_get_clock(rt_clock
))) {
1380 qemu_event_increment();
1381 if (alarm_timer
) alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1383 #ifndef CONFIG_IOTHREAD
1385 /* stop the currently executing cpu because a timer occured */
1388 if (next_cpu
->kqemu_enabled
) {
1389 kqemu_cpu_interrupt(next_cpu
);
1394 timer_alarm_pending
= 1;
1395 qemu_notify_event();
1399 static int64_t qemu_next_deadline(void)
1403 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1404 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1405 qemu_get_clock(vm_clock
);
1407 /* To avoid problems with overflow limit this to 2^32. */
1417 #if defined(__linux__) || defined(_WIN32)
1418 static uint64_t qemu_next_deadline_dyntick(void)
1426 delta
= (qemu_next_deadline() + 999) / 1000;
1428 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1429 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1430 qemu_get_clock(rt_clock
))*1000;
1431 if (rtdelta
< delta
)
1435 if (delta
< MIN_TIMER_REARM_US
)
1436 delta
= MIN_TIMER_REARM_US
;
1444 /* Sets a specific flag */
1445 static int fcntl_setfl(int fd
, int flag
)
1449 flags
= fcntl(fd
, F_GETFL
);
1453 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1459 #if defined(__linux__)
1461 #define RTC_FREQ 1024
1463 static void enable_sigio_timer(int fd
)
1465 struct sigaction act
;
1468 sigfillset(&act
.sa_mask
);
1470 act
.sa_handler
= host_alarm_handler
;
1472 sigaction(SIGIO
, &act
, NULL
);
1473 fcntl_setfl(fd
, O_ASYNC
);
1474 fcntl(fd
, F_SETOWN
, getpid());
1477 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1479 struct hpet_info info
;
1482 fd
= open("/dev/hpet", O_RDONLY
);
1487 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1489 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1490 "error, but for better emulation accuracy type:\n"
1491 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1495 /* Check capabilities */
1496 r
= ioctl(fd
, HPET_INFO
, &info
);
1500 /* Enable periodic mode */
1501 r
= ioctl(fd
, HPET_EPI
, 0);
1502 if (info
.hi_flags
&& (r
< 0))
1505 /* Enable interrupt */
1506 r
= ioctl(fd
, HPET_IE_ON
, 0);
1510 enable_sigio_timer(fd
);
1511 t
->priv
= (void *)(long)fd
;
1519 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1521 int fd
= (long)t
->priv
;
1526 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1529 unsigned long current_rtc_freq
= 0;
1531 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1534 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1535 if (current_rtc_freq
!= RTC_FREQ
&&
1536 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1537 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1538 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1539 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1542 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1548 enable_sigio_timer(rtc_fd
);
1550 t
->priv
= (void *)(long)rtc_fd
;
1555 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1557 int rtc_fd
= (long)t
->priv
;
1562 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1566 struct sigaction act
;
1568 sigfillset(&act
.sa_mask
);
1570 act
.sa_handler
= host_alarm_handler
;
1572 sigaction(SIGALRM
, &act
, NULL
);
1575 * Initialize ev struct to 0 to avoid valgrind complaining
1576 * about uninitialized data in timer_create call
1578 memset(&ev
, 0, sizeof(ev
));
1579 ev
.sigev_value
.sival_int
= 0;
1580 ev
.sigev_notify
= SIGEV_SIGNAL
;
1581 ev
.sigev_signo
= SIGALRM
;
1583 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1584 perror("timer_create");
1586 /* disable dynticks */
1587 fprintf(stderr
, "Dynamic Ticks disabled\n");
1592 t
->priv
= (void *)(long)host_timer
;
1597 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1599 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1601 timer_delete(host_timer
);
1604 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1606 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1607 struct itimerspec timeout
;
1608 int64_t nearest_delta_us
= INT64_MAX
;
1611 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1612 !active_timers
[QEMU_TIMER_VIRTUAL
])
1615 nearest_delta_us
= qemu_next_deadline_dyntick();
1617 /* check whether a timer is already running */
1618 if (timer_gettime(host_timer
, &timeout
)) {
1620 fprintf(stderr
, "Internal timer error: aborting\n");
1623 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1624 if (current_us
&& current_us
<= nearest_delta_us
)
1627 timeout
.it_interval
.tv_sec
= 0;
1628 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1629 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1630 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1631 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1633 fprintf(stderr
, "Internal timer error: aborting\n");
1638 #endif /* defined(__linux__) */
1640 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1642 struct sigaction act
;
1643 struct itimerval itv
;
1647 sigfillset(&act
.sa_mask
);
1649 act
.sa_handler
= host_alarm_handler
;
1651 sigaction(SIGALRM
, &act
, NULL
);
1653 itv
.it_interval
.tv_sec
= 0;
1654 /* for i386 kernel 2.6 to get 1 ms */
1655 itv
.it_interval
.tv_usec
= 999;
1656 itv
.it_value
.tv_sec
= 0;
1657 itv
.it_value
.tv_usec
= 10 * 1000;
1659 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1666 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1668 struct itimerval itv
;
1670 memset(&itv
, 0, sizeof(itv
));
1671 setitimer(ITIMER_REAL
, &itv
, NULL
);
1674 #endif /* !defined(_WIN32) */
1679 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1682 struct qemu_alarm_win32
*data
= t
->priv
;
1685 memset(&tc
, 0, sizeof(tc
));
1686 timeGetDevCaps(&tc
, sizeof(tc
));
1688 if (data
->period
< tc
.wPeriodMin
)
1689 data
->period
= tc
.wPeriodMin
;
1691 timeBeginPeriod(data
->period
);
1693 flags
= TIME_CALLBACK_FUNCTION
;
1694 if (alarm_has_dynticks(t
))
1695 flags
|= TIME_ONESHOT
;
1697 flags
|= TIME_PERIODIC
;
1699 data
->timerId
= timeSetEvent(1, // interval (ms)
1700 data
->period
, // resolution
1701 host_alarm_handler
, // function
1702 (DWORD
)t
, // parameter
1705 if (!data
->timerId
) {
1706 perror("Failed to initialize win32 alarm timer");
1707 timeEndPeriod(data
->period
);
1714 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1716 struct qemu_alarm_win32
*data
= t
->priv
;
1718 timeKillEvent(data
->timerId
);
1719 timeEndPeriod(data
->period
);
1722 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1724 struct qemu_alarm_win32
*data
= t
->priv
;
1725 uint64_t nearest_delta_us
;
1727 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1728 !active_timers
[QEMU_TIMER_VIRTUAL
])
1731 nearest_delta_us
= qemu_next_deadline_dyntick();
1732 nearest_delta_us
/= 1000;
1734 timeKillEvent(data
->timerId
);
1736 data
->timerId
= timeSetEvent(1,
1740 TIME_ONESHOT
| TIME_PERIODIC
);
1742 if (!data
->timerId
) {
1743 perror("Failed to re-arm win32 alarm timer");
1745 timeEndPeriod(data
->period
);
1752 static int init_timer_alarm(void)
1754 struct qemu_alarm_timer
*t
= NULL
;
1757 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1758 t
= &alarm_timers
[i
];
1778 static void quit_timers(void)
1780 alarm_timer
->stop(alarm_timer
);
1784 /***********************************************************/
1785 /* host time/date access */
1786 void qemu_get_timedate(struct tm
*tm
, int offset
)
1793 if (rtc_date_offset
== -1) {
1797 ret
= localtime(&ti
);
1799 ti
-= rtc_date_offset
;
1803 memcpy(tm
, ret
, sizeof(struct tm
));
1806 int qemu_timedate_diff(struct tm
*tm
)
1810 if (rtc_date_offset
== -1)
1812 seconds
= mktimegm(tm
);
1814 seconds
= mktime(tm
);
1816 seconds
= mktimegm(tm
) + rtc_date_offset
;
1818 return seconds
- time(NULL
);
1822 static void socket_cleanup(void)
1827 static int socket_init(void)
1832 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1834 err
= WSAGetLastError();
1835 fprintf(stderr
, "WSAStartup: %d\n", err
);
1838 atexit(socket_cleanup
);
1843 int get_next_param_value(char *buf
, int buf_size
,
1844 const char *tag
, const char **pstr
)
1851 p
= get_opt_name(option
, sizeof(option
), p
, '=');
1855 if (!strcmp(tag
, option
)) {
1856 *pstr
= get_opt_value(buf
, buf_size
, p
);
1857 if (**pstr
== ',') {
1862 p
= get_opt_value(NULL
, 0, p
);
1871 int get_param_value(char *buf
, int buf_size
,
1872 const char *tag
, const char *str
)
1874 return get_next_param_value(buf
, buf_size
, tag
, &str
);
1877 int check_params(char *buf
, int buf_size
,
1878 const char * const *params
, const char *str
)
1884 while (*p
!= '\0') {
1885 p
= get_opt_name(buf
, buf_size
, p
, '=');
1890 for (i
= 0; params
[i
] != NULL
; i
++) {
1891 if (!strcmp(params
[i
], buf
)) {
1895 if (params
[i
] == NULL
) {
1898 p
= get_opt_value(NULL
, 0, p
);
1907 /***********************************************************/
1908 /* Bluetooth support */
1911 static struct HCIInfo
*hci_table
[MAX_NICS
];
1913 static struct bt_vlan_s
{
1914 struct bt_scatternet_s net
;
1916 struct bt_vlan_s
*next
;
1919 /* find or alloc a new bluetooth "VLAN" */
1920 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1922 struct bt_vlan_s
**pvlan
, *vlan
;
1923 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1927 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1929 pvlan
= &first_bt_vlan
;
1930 while (*pvlan
!= NULL
)
1931 pvlan
= &(*pvlan
)->next
;
1936 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1940 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1945 static struct HCIInfo null_hci
= {
1946 .cmd_send
= null_hci_send
,
1947 .sco_send
= null_hci_send
,
1948 .acl_send
= null_hci_send
,
1949 .bdaddr_set
= null_hci_addr_set
,
1952 struct HCIInfo
*qemu_next_hci(void)
1954 if (cur_hci
== nb_hcis
)
1957 return hci_table
[cur_hci
++];
1960 static struct HCIInfo
*hci_init(const char *str
)
1963 struct bt_scatternet_s
*vlan
= 0;
1965 if (!strcmp(str
, "null"))
1968 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
1970 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
1971 else if (!strncmp(str
, "hci", 3)) {
1974 if (!strncmp(str
+ 3, ",vlan=", 6)) {
1975 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
1980 vlan
= qemu_find_bt_vlan(0);
1982 return bt_new_hci(vlan
);
1985 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
1990 static int bt_hci_parse(const char *str
)
1992 struct HCIInfo
*hci
;
1995 if (nb_hcis
>= MAX_NICS
) {
1996 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
2000 hci
= hci_init(str
);
2009 bdaddr
.b
[5] = 0x56 + nb_hcis
;
2010 hci
->bdaddr_set(hci
, bdaddr
.b
);
2012 hci_table
[nb_hcis
++] = hci
;
2017 static void bt_vhci_add(int vlan_id
)
2019 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
2022 fprintf(stderr
, "qemu: warning: adding a VHCI to "
2023 "an empty scatternet %i\n", vlan_id
);
2025 bt_vhci_init(bt_new_hci(vlan
));
2028 static struct bt_device_s
*bt_device_add(const char *opt
)
2030 struct bt_scatternet_s
*vlan
;
2032 char *endp
= strstr(opt
, ",vlan=");
2033 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
2036 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
2039 vlan_id
= strtol(endp
+ 6, &endp
, 0);
2041 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
2046 vlan
= qemu_find_bt_vlan(vlan_id
);
2049 fprintf(stderr
, "qemu: warning: adding a slave device to "
2050 "an empty scatternet %i\n", vlan_id
);
2052 if (!strcmp(devname
, "keyboard"))
2053 return bt_keyboard_init(vlan
);
2055 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
2059 static int bt_parse(const char *opt
)
2061 const char *endp
, *p
;
2064 if (strstart(opt
, "hci", &endp
)) {
2065 if (!*endp
|| *endp
== ',') {
2067 if (!strstart(endp
, ",vlan=", 0))
2070 return bt_hci_parse(opt
);
2072 } else if (strstart(opt
, "vhci", &endp
)) {
2073 if (!*endp
|| *endp
== ',') {
2075 if (strstart(endp
, ",vlan=", &p
)) {
2076 vlan
= strtol(p
, (char **) &endp
, 0);
2078 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
2082 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
2091 } else if (strstart(opt
, "device:", &endp
))
2092 return !bt_device_add(endp
);
2094 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
2098 /***********************************************************/
2099 /* QEMU Block devices */
2101 #define HD_ALIAS "index=%d,media=disk"
2102 #define CDROM_ALIAS "index=2,media=cdrom"
2103 #define FD_ALIAS "index=%d,if=floppy"
2104 #define PFLASH_ALIAS "if=pflash"
2105 #define MTD_ALIAS "if=mtd"
2106 #define SD_ALIAS "index=0,if=sd"
2108 static int drive_opt_get_free_idx(void)
2112 for (index
= 0; index
< MAX_DRIVES
; index
++)
2113 if (!drives_opt
[index
].used
) {
2114 drives_opt
[index
].used
= 1;
2121 static int drive_get_free_idx(void)
2125 for (index
= 0; index
< MAX_DRIVES
; index
++)
2126 if (!drives_table
[index
].used
) {
2127 drives_table
[index
].used
= 1;
2134 int drive_add(const char *file
, const char *fmt
, ...)
2137 int index
= drive_opt_get_free_idx();
2139 if (nb_drives_opt
>= MAX_DRIVES
|| index
== -1) {
2140 fprintf(stderr
, "qemu: too many drives\n");
2144 drives_opt
[index
].file
= file
;
2146 vsnprintf(drives_opt
[index
].opt
,
2147 sizeof(drives_opt
[0].opt
), fmt
, ap
);
2154 void drive_remove(int index
)
2156 drives_opt
[index
].used
= 0;
2160 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
2164 /* seek interface, bus and unit */
2166 for (index
= 0; index
< MAX_DRIVES
; index
++)
2167 if (drives_table
[index
].type
== type
&&
2168 drives_table
[index
].bus
== bus
&&
2169 drives_table
[index
].unit
== unit
&&
2170 drives_table
[index
].used
)
2176 int drive_get_max_bus(BlockInterfaceType type
)
2182 for (index
= 0; index
< nb_drives
; index
++) {
2183 if(drives_table
[index
].type
== type
&&
2184 drives_table
[index
].bus
> max_bus
)
2185 max_bus
= drives_table
[index
].bus
;
2190 const char *drive_get_serial(BlockDriverState
*bdrv
)
2194 for (index
= 0; index
< nb_drives
; index
++)
2195 if (drives_table
[index
].bdrv
== bdrv
)
2196 return drives_table
[index
].serial
;
2201 BlockInterfaceErrorAction
drive_get_onerror(BlockDriverState
*bdrv
)
2205 for (index
= 0; index
< nb_drives
; index
++)
2206 if (drives_table
[index
].bdrv
== bdrv
)
2207 return drives_table
[index
].onerror
;
2209 return BLOCK_ERR_STOP_ENOSPC
;
2212 static void bdrv_format_print(void *opaque
, const char *name
)
2214 fprintf(stderr
, " %s", name
);
2217 void drive_uninit(BlockDriverState
*bdrv
)
2221 for (i
= 0; i
< MAX_DRIVES
; i
++)
2222 if (drives_table
[i
].bdrv
== bdrv
) {
2223 drives_table
[i
].bdrv
= NULL
;
2224 drives_table
[i
].used
= 0;
2225 drive_remove(drives_table
[i
].drive_opt_idx
);
2231 int drive_init(struct drive_opt
*arg
, int snapshot
, void *opaque
)
2237 const char *mediastr
= "";
2238 BlockInterfaceType type
;
2239 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
2240 int bus_id
, unit_id
;
2241 int cyls
, heads
, secs
, translation
;
2242 BlockDriverState
*bdrv
;
2243 BlockDriver
*drv
= NULL
;
2244 QEMUMachine
*machine
= opaque
;
2248 int bdrv_flags
, onerror
;
2249 const char *devaddr
;
2250 int drives_table_idx
;
2251 char *str
= arg
->opt
;
2252 static const char * const params
[] = { "bus", "unit", "if", "index",
2253 "cyls", "heads", "secs", "trans",
2254 "media", "snapshot", "file",
2255 "cache", "format", "serial",
2260 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
2261 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
2267 cyls
= heads
= secs
= 0;
2270 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2274 if (machine
->use_scsi
) {
2276 max_devs
= MAX_SCSI_DEVS
;
2277 pstrcpy(devname
, sizeof(devname
), "scsi");
2280 max_devs
= MAX_IDE_DEVS
;
2281 pstrcpy(devname
, sizeof(devname
), "ide");
2285 /* extract parameters */
2287 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
2288 bus_id
= strtol(buf
, NULL
, 0);
2290 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
2295 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
2296 unit_id
= strtol(buf
, NULL
, 0);
2298 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
2303 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
2304 pstrcpy(devname
, sizeof(devname
), buf
);
2305 if (!strcmp(buf
, "ide")) {
2307 max_devs
= MAX_IDE_DEVS
;
2308 } else if (!strcmp(buf
, "scsi")) {
2310 max_devs
= MAX_SCSI_DEVS
;
2311 } else if (!strcmp(buf
, "floppy")) {
2314 } else if (!strcmp(buf
, "pflash")) {
2317 } else if (!strcmp(buf
, "mtd")) {
2320 } else if (!strcmp(buf
, "sd")) {
2323 } else if (!strcmp(buf
, "virtio")) {
2326 } else if (!strcmp(buf
, "xen")) {
2330 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
2335 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
2336 index
= strtol(buf
, NULL
, 0);
2338 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
2343 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
2344 cyls
= strtol(buf
, NULL
, 0);
2347 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
2348 heads
= strtol(buf
, NULL
, 0);
2351 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
2352 secs
= strtol(buf
, NULL
, 0);
2355 if (cyls
|| heads
|| secs
) {
2356 if (cyls
< 1 || cyls
> 16383) {
2357 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
2360 if (heads
< 1 || heads
> 16) {
2361 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
2364 if (secs
< 1 || secs
> 63) {
2365 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
2370 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
2373 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2377 if (!strcmp(buf
, "none"))
2378 translation
= BIOS_ATA_TRANSLATION_NONE
;
2379 else if (!strcmp(buf
, "lba"))
2380 translation
= BIOS_ATA_TRANSLATION_LBA
;
2381 else if (!strcmp(buf
, "auto"))
2382 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2384 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
2389 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
2390 if (!strcmp(buf
, "disk")) {
2392 } else if (!strcmp(buf
, "cdrom")) {
2393 if (cyls
|| secs
|| heads
) {
2395 "qemu: '%s' invalid physical CHS format\n", str
);
2398 media
= MEDIA_CDROM
;
2400 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
2405 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
2406 if (!strcmp(buf
, "on"))
2408 else if (!strcmp(buf
, "off"))
2411 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
2416 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
2417 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2419 else if (!strcmp(buf
, "writethrough"))
2421 else if (!strcmp(buf
, "writeback"))
2424 fprintf(stderr
, "qemu: invalid cache option\n");
2429 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
2430 if (strcmp(buf
, "?") == 0) {
2431 fprintf(stderr
, "qemu: Supported formats:");
2432 bdrv_iterate_format(bdrv_format_print
, NULL
);
2433 fprintf(stderr
, "\n");
2436 drv
= bdrv_find_format(buf
);
2438 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2443 if (get_param_value(buf
, sizeof(buf
), "boot", str
)) {
2444 if (!strcmp(buf
, "on")) {
2445 if (extboot_drive
!= -1) {
2446 fprintf(stderr
, "qemu: two bootable drives specified\n");
2449 extboot_drive
= nb_drives
;
2450 } else if (strcmp(buf
, "off")) {
2451 fprintf(stderr
, "qemu: '%s' invalid boot option\n", str
);
2456 if (arg
->file
== NULL
)
2457 get_param_value(file
, sizeof(file
), "file", str
);
2459 pstrcpy(file
, sizeof(file
), arg
->file
);
2461 if (!get_param_value(serial
, sizeof(serial
), "serial", str
))
2462 memset(serial
, 0, sizeof(serial
));
2464 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2465 if (get_param_value(buf
, sizeof(serial
), "werror", str
)) {
2466 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2467 fprintf(stderr
, "werror is no supported by this format\n");
2470 if (!strcmp(buf
, "ignore"))
2471 onerror
= BLOCK_ERR_IGNORE
;
2472 else if (!strcmp(buf
, "enospc"))
2473 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2474 else if (!strcmp(buf
, "stop"))
2475 onerror
= BLOCK_ERR_STOP_ANY
;
2476 else if (!strcmp(buf
, "report"))
2477 onerror
= BLOCK_ERR_REPORT
;
2479 fprintf(stderr
, "qemu: '%s' invalid write error action\n", buf
);
2485 if (get_param_value(buf
, sizeof(buf
), "addr", str
)) {
2486 if (type
!= IF_VIRTIO
) {
2487 fprintf(stderr
, "addr is not supported by in '%s'\n", str
);
2490 devaddr
= strdup(buf
);
2493 /* compute bus and unit according index */
2496 if (bus_id
!= 0 || unit_id
!= -1) {
2498 "qemu: '%s' index cannot be used with bus and unit\n", str
);
2506 unit_id
= index
% max_devs
;
2507 bus_id
= index
/ max_devs
;
2511 /* if user doesn't specify a unit_id,
2512 * try to find the first free
2515 if (unit_id
== -1) {
2517 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
2519 if (max_devs
&& unit_id
>= max_devs
) {
2520 unit_id
-= max_devs
;
2528 if (max_devs
&& unit_id
>= max_devs
) {
2529 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
2530 str
, unit_id
, max_devs
- 1);
2535 * ignore multiple definitions
2538 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
2543 if (type
== IF_IDE
|| type
== IF_SCSI
)
2544 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2546 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
2547 devname
, bus_id
, mediastr
, unit_id
);
2549 snprintf(buf
, sizeof(buf
), "%s%s%i",
2550 devname
, mediastr
, unit_id
);
2551 bdrv
= bdrv_new(buf
);
2552 drives_table_idx
= drive_get_free_idx();
2553 drives_table
[drives_table_idx
].bdrv
= bdrv
;
2554 drives_table
[drives_table_idx
].devaddr
= devaddr
;
2555 drives_table
[drives_table_idx
].type
= type
;
2556 drives_table
[drives_table_idx
].bus
= bus_id
;
2557 drives_table
[drives_table_idx
].unit
= unit_id
;
2558 drives_table
[drives_table_idx
].onerror
= onerror
;
2559 drives_table
[drives_table_idx
].drive_opt_idx
= arg
- drives_opt
;
2560 strncpy(drives_table
[drives_table_idx
].serial
, serial
, sizeof(serial
));
2570 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
2571 bdrv_set_translation_hint(bdrv
, translation
);
2575 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
2580 /* FIXME: This isn't really a floppy, but it's a reasonable
2583 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
2596 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2597 cache
= 2; /* always use write-back with snapshot */
2599 if (cache
== 0) /* no caching */
2600 bdrv_flags
|= BDRV_O_NOCACHE
;
2601 else if (cache
== 2) /* write-back */
2602 bdrv_flags
|= BDRV_O_CACHE_WB
;
2603 else if (cache
== 3) /* not specified */
2604 bdrv_flags
|= BDRV_O_CACHE_DEF
;
2605 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0) {
2606 fprintf(stderr
, "qemu: could not open disk image %s\n",
2610 if (bdrv_key_required(bdrv
))
2612 return drives_table_idx
;
2615 static void numa_add(const char *optarg
)
2619 unsigned long long value
, endvalue
;
2622 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2623 if (!strcmp(option
, "node")) {
2624 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2625 nodenr
= nb_numa_nodes
;
2627 nodenr
= strtoull(option
, NULL
, 10);
2630 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2631 node_mem
[nodenr
] = 0;
2633 value
= strtoull(option
, &endptr
, 0);
2635 case 0: case 'M': case 'm':
2642 node_mem
[nodenr
] = value
;
2644 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2645 node_cpumask
[nodenr
] = 0;
2647 value
= strtoull(option
, &endptr
, 10);
2650 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2652 if (*endptr
== '-') {
2653 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2654 if (endvalue
>= 63) {
2657 "only 63 CPUs in NUMA mode supported.\n");
2659 value
= (1 << (endvalue
+ 1)) - (1 << value
);
2664 node_cpumask
[nodenr
] = value
;
2671 /***********************************************************/
2674 static USBPort
*used_usb_ports
;
2675 static USBPort
*free_usb_ports
;
2677 /* ??? Maybe change this to register a hub to keep track of the topology. */
2678 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
2679 usb_attachfn attach
)
2681 port
->opaque
= opaque
;
2682 port
->index
= index
;
2683 port
->attach
= attach
;
2684 port
->next
= free_usb_ports
;
2685 free_usb_ports
= port
;
2688 int usb_device_add_dev(USBDevice
*dev
)
2692 /* Find a USB port to add the device to. */
2693 port
= free_usb_ports
;
2697 /* Create a new hub and chain it on. */
2698 free_usb_ports
= NULL
;
2699 port
->next
= used_usb_ports
;
2700 used_usb_ports
= port
;
2702 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
2703 usb_attach(port
, hub
);
2704 port
= free_usb_ports
;
2707 free_usb_ports
= port
->next
;
2708 port
->next
= used_usb_ports
;
2709 used_usb_ports
= port
;
2710 usb_attach(port
, dev
);
2714 static void usb_msd_password_cb(void *opaque
, int err
)
2716 USBDevice
*dev
= opaque
;
2719 usb_device_add_dev(dev
);
2721 dev
->handle_destroy(dev
);
2724 static int usb_device_add(const char *devname
, int is_hotplug
)
2729 if (!free_usb_ports
)
2732 if (strstart(devname
, "host:", &p
)) {
2733 dev
= usb_host_device_open(p
);
2734 } else if (!strcmp(devname
, "mouse")) {
2735 dev
= usb_mouse_init();
2736 } else if (!strcmp(devname
, "tablet")) {
2737 dev
= usb_tablet_init();
2738 } else if (!strcmp(devname
, "keyboard")) {
2739 dev
= usb_keyboard_init();
2740 } else if (strstart(devname
, "disk:", &p
)) {
2741 BlockDriverState
*bs
;
2743 dev
= usb_msd_init(p
);
2746 bs
= usb_msd_get_bdrv(dev
);
2747 if (bdrv_key_required(bs
)) {
2750 monitor_read_bdrv_key_start(cur_mon
, bs
, usb_msd_password_cb
,
2755 } else if (!strcmp(devname
, "wacom-tablet")) {
2756 dev
= usb_wacom_init();
2757 } else if (strstart(devname
, "serial:", &p
)) {
2758 dev
= usb_serial_init(p
);
2759 #ifdef CONFIG_BRLAPI
2760 } else if (!strcmp(devname
, "braille")) {
2761 dev
= usb_baum_init();
2763 } else if (strstart(devname
, "net:", &p
)) {
2766 if (net_client_init(NULL
, "nic", p
) < 0)
2768 nd_table
[nic
].model
= "usb";
2769 dev
= usb_net_init(&nd_table
[nic
]);
2770 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2771 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2772 bt_new_hci(qemu_find_bt_vlan(0)));
2779 return usb_device_add_dev(dev
);
2782 int usb_device_del_addr(int bus_num
, int addr
)
2788 if (!used_usb_ports
)
2794 lastp
= &used_usb_ports
;
2795 port
= used_usb_ports
;
2796 while (port
&& port
->dev
->addr
!= addr
) {
2797 lastp
= &port
->next
;
2805 *lastp
= port
->next
;
2806 usb_attach(port
, NULL
);
2807 dev
->handle_destroy(dev
);
2808 port
->next
= free_usb_ports
;
2809 free_usb_ports
= port
;
2813 static int usb_device_del(const char *devname
)
2818 if (strstart(devname
, "host:", &p
))
2819 return usb_host_device_close(p
);
2821 if (!used_usb_ports
)
2824 p
= strchr(devname
, '.');
2827 bus_num
= strtoul(devname
, NULL
, 0);
2828 addr
= strtoul(p
+ 1, NULL
, 0);
2830 return usb_device_del_addr(bus_num
, addr
);
2833 void do_usb_add(Monitor
*mon
, const char *devname
)
2835 usb_device_add(devname
, 1);
2838 void do_usb_del(Monitor
*mon
, const char *devname
)
2840 usb_device_del(devname
);
2843 void usb_info(Monitor
*mon
)
2847 const char *speed_str
;
2850 monitor_printf(mon
, "USB support not enabled\n");
2854 for (port
= used_usb_ports
; port
; port
= port
->next
) {
2858 switch(dev
->speed
) {
2862 case USB_SPEED_FULL
:
2865 case USB_SPEED_HIGH
:
2872 monitor_printf(mon
, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2873 0, dev
->addr
, speed_str
, dev
->devname
);
2877 /***********************************************************/
2878 /* PCMCIA/Cardbus */
2880 static struct pcmcia_socket_entry_s
{
2881 PCMCIASocket
*socket
;
2882 struct pcmcia_socket_entry_s
*next
;
2883 } *pcmcia_sockets
= 0;
2885 void pcmcia_socket_register(PCMCIASocket
*socket
)
2887 struct pcmcia_socket_entry_s
*entry
;
2889 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2890 entry
->socket
= socket
;
2891 entry
->next
= pcmcia_sockets
;
2892 pcmcia_sockets
= entry
;
2895 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2897 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2899 ptr
= &pcmcia_sockets
;
2900 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2901 if (entry
->socket
== socket
) {
2907 void pcmcia_info(Monitor
*mon
)
2909 struct pcmcia_socket_entry_s
*iter
;
2911 if (!pcmcia_sockets
)
2912 monitor_printf(mon
, "No PCMCIA sockets\n");
2914 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2915 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2916 iter
->socket
->attached
? iter
->socket
->card_string
:
2920 /***********************************************************/
2921 /* register display */
2923 struct DisplayAllocator default_allocator
= {
2924 defaultallocator_create_displaysurface
,
2925 defaultallocator_resize_displaysurface
,
2926 defaultallocator_free_displaysurface
2929 void register_displaystate(DisplayState
*ds
)
2939 DisplayState
*get_displaystate(void)
2941 return display_state
;
2944 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
2946 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
2947 return ds
->allocator
;
2952 static void dumb_display_init(void)
2954 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
2955 ds
->allocator
= &default_allocator
;
2956 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
2957 register_displaystate(ds
);
2960 /***********************************************************/
2963 typedef struct IOHandlerRecord
{
2965 IOCanRWHandler
*fd_read_poll
;
2967 IOHandler
*fd_write
;
2970 /* temporary data */
2972 struct IOHandlerRecord
*next
;
2975 static IOHandlerRecord
*first_io_handler
;
2977 /* XXX: fd_read_poll should be suppressed, but an API change is
2978 necessary in the character devices to suppress fd_can_read(). */
2979 int qemu_set_fd_handler2(int fd
,
2980 IOCanRWHandler
*fd_read_poll
,
2982 IOHandler
*fd_write
,
2985 IOHandlerRecord
**pioh
, *ioh
;
2987 if (!fd_read
&& !fd_write
) {
2988 pioh
= &first_io_handler
;
2993 if (ioh
->fd
== fd
) {
3000 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3004 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
3005 ioh
->next
= first_io_handler
;
3006 first_io_handler
= ioh
;
3009 ioh
->fd_read_poll
= fd_read_poll
;
3010 ioh
->fd_read
= fd_read
;
3011 ioh
->fd_write
= fd_write
;
3012 ioh
->opaque
= opaque
;
3015 qemu_notify_event();
3019 int qemu_set_fd_handler(int fd
,
3021 IOHandler
*fd_write
,
3024 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
3028 /***********************************************************/
3029 /* Polling handling */
3031 typedef struct PollingEntry
{
3034 struct PollingEntry
*next
;
3037 static PollingEntry
*first_polling_entry
;
3039 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
3041 PollingEntry
**ppe
, *pe
;
3042 pe
= qemu_mallocz(sizeof(PollingEntry
));
3044 pe
->opaque
= opaque
;
3045 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
3050 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
3052 PollingEntry
**ppe
, *pe
;
3053 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
3055 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
3063 /***********************************************************/
3064 /* Wait objects support */
3065 typedef struct WaitObjects
{
3067 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
3068 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
3069 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
3072 static WaitObjects wait_objects
= {0};
3074 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
3076 WaitObjects
*w
= &wait_objects
;
3078 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
3080 w
->events
[w
->num
] = handle
;
3081 w
->func
[w
->num
] = func
;
3082 w
->opaque
[w
->num
] = opaque
;
3087 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
3090 WaitObjects
*w
= &wait_objects
;
3093 for (i
= 0; i
< w
->num
; i
++) {
3094 if (w
->events
[i
] == handle
)
3097 w
->events
[i
] = w
->events
[i
+ 1];
3098 w
->func
[i
] = w
->func
[i
+ 1];
3099 w
->opaque
[i
] = w
->opaque
[i
+ 1];
3107 /***********************************************************/
3108 /* ram save/restore */
3110 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
3114 v
= qemu_get_byte(f
);
3117 if (qemu_get_buffer(f
, buf
, len
) != len
)
3121 v
= qemu_get_byte(f
);
3122 memset(buf
, v
, len
);
3128 if (qemu_file_has_error(f
))
3134 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
3139 if (qemu_get_be32(f
) != last_ram_offset
)
3141 for(i
= 0; i
< last_ram_offset
; i
+= TARGET_PAGE_SIZE
) {
3142 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3144 ret
= ram_get_page(f
, qemu_get_ram_ptr(i
), TARGET_PAGE_SIZE
);
3151 #define BDRV_HASH_BLOCK_SIZE 1024
3152 #define IOBUF_SIZE 4096
3153 #define RAM_CBLOCK_MAGIC 0xfabe
3155 typedef struct RamDecompressState
{
3158 uint8_t buf
[IOBUF_SIZE
];
3159 } RamDecompressState
;
3161 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
3164 memset(s
, 0, sizeof(*s
));
3166 ret
= inflateInit(&s
->zstream
);
3172 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
3176 s
->zstream
.avail_out
= len
;
3177 s
->zstream
.next_out
= buf
;
3178 while (s
->zstream
.avail_out
> 0) {
3179 if (s
->zstream
.avail_in
== 0) {
3180 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
3182 clen
= qemu_get_be16(s
->f
);
3183 if (clen
> IOBUF_SIZE
)
3185 qemu_get_buffer(s
->f
, s
->buf
, clen
);
3186 s
->zstream
.avail_in
= clen
;
3187 s
->zstream
.next_in
= s
->buf
;
3189 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
3190 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
3197 static void ram_decompress_close(RamDecompressState
*s
)
3199 inflateEnd(&s
->zstream
);
3202 #define RAM_SAVE_FLAG_FULL 0x01
3203 #define RAM_SAVE_FLAG_COMPRESS 0x02
3204 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3205 #define RAM_SAVE_FLAG_PAGE 0x08
3206 #define RAM_SAVE_FLAG_EOS 0x10
3208 static int is_dup_page(uint8_t *page
, uint8_t ch
)
3210 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
3211 uint32_t *array
= (uint32_t *)page
;
3214 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
3215 if (array
[i
] != val
)
3222 static int ram_save_block(QEMUFile
*f
)
3224 static ram_addr_t current_addr
= 0;
3225 ram_addr_t saved_addr
= current_addr
;
3226 ram_addr_t addr
= 0;
3229 while (addr
< last_ram_offset
) {
3230 if (kvm_enabled() && current_addr
== 0) {
3232 r
= kvm_update_dirty_pages_log();
3234 fprintf(stderr
, "%s: update dirty pages log failed %d\n", __FUNCTION__
, r
);
3235 qemu_file_set_error(f
);
3239 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
3242 cpu_physical_memory_reset_dirty(current_addr
,
3243 current_addr
+ TARGET_PAGE_SIZE
,
3244 MIGRATION_DIRTY_FLAG
);
3246 p
= qemu_get_ram_ptr(current_addr
);
3248 if (is_dup_page(p
, *p
)) {
3249 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
3250 qemu_put_byte(f
, *p
);
3252 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
3253 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
3259 addr
+= TARGET_PAGE_SIZE
;
3260 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
3266 static uint64_t bytes_transferred
= 0;
3268 static ram_addr_t
ram_save_remaining(void)
3271 ram_addr_t count
= 0;
3273 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3274 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3281 uint64_t ram_bytes_remaining(void)
3283 return ram_save_remaining() * TARGET_PAGE_SIZE
;
3286 uint64_t ram_bytes_transferred(void)
3288 return bytes_transferred
;
3291 uint64_t ram_bytes_total(void)
3293 return last_ram_offset
;
3296 static int ram_save_live(QEMUFile
*f
, int stage
, void *opaque
)
3299 uint64_t bytes_transferred_last
;
3301 uint64_t expected_time
= 0;
3303 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX
) != 0) {
3304 qemu_file_set_error(f
);
3309 /* Make sure all dirty bits are set */
3310 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3311 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3312 cpu_physical_memory_set_dirty(addr
);
3315 /* Enable dirty memory tracking */
3316 cpu_physical_memory_set_dirty_tracking(1);
3318 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
3321 bytes_transferred_last
= bytes_transferred
;
3322 bwidth
= get_clock();
3324 while (!qemu_file_rate_limit(f
)) {
3327 ret
= ram_save_block(f
);
3328 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
3329 if (ret
== 0) /* no more blocks */
3333 bwidth
= get_clock() - bwidth
;
3334 bwidth
= (bytes_transferred
- bytes_transferred_last
) / bwidth
;
3336 /* if we haven't transferred anything this round, force expected_time to a
3337 * a very high value, but without crashing */
3341 /* try transferring iterative blocks of memory */
3345 /* flush all remaining blocks regardless of rate limiting */
3346 while (ram_save_block(f
) != 0) {
3347 bytes_transferred
+= TARGET_PAGE_SIZE
;
3349 cpu_physical_memory_set_dirty_tracking(0);
3352 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3354 expected_time
= ram_save_remaining() * TARGET_PAGE_SIZE
/ bwidth
;
3356 return (stage
== 2) && (expected_time
<= migrate_max_downtime());
3359 static int ram_load_dead(QEMUFile
*f
, void *opaque
)
3361 RamDecompressState s1
, *s
= &s1
;
3365 if (ram_decompress_open(s
, f
) < 0)
3367 for(i
= 0; i
< last_ram_offset
; i
+= BDRV_HASH_BLOCK_SIZE
) {
3368 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3370 if (ram_decompress_buf(s
, buf
, 1) < 0) {
3371 fprintf(stderr
, "Error while reading ram block header\n");
3375 if (ram_decompress_buf(s
, qemu_get_ram_ptr(i
),
3376 BDRV_HASH_BLOCK_SIZE
) < 0) {
3377 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
3382 printf("Error block header\n");
3386 ram_decompress_close(s
);
3391 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
3396 if (version_id
== 1)
3397 return ram_load_v1(f
, opaque
);
3399 if (version_id
== 2) {
3400 if (qemu_get_be32(f
) != last_ram_offset
)
3402 return ram_load_dead(f
, opaque
);
3405 if (version_id
!= 3)
3409 addr
= qemu_get_be64(f
);
3411 flags
= addr
& ~TARGET_PAGE_MASK
;
3412 addr
&= TARGET_PAGE_MASK
;
3414 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
3415 if (addr
!= last_ram_offset
)
3419 if (flags
& RAM_SAVE_FLAG_FULL
) {
3420 if (ram_load_dead(f
, opaque
) < 0)
3424 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
3425 uint8_t ch
= qemu_get_byte(f
);
3426 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
3429 (!kvm_enabled() || kvm_has_sync_mmu())) {
3430 madvise(qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
, MADV_DONTNEED
);
3433 } else if (flags
& RAM_SAVE_FLAG_PAGE
)
3434 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
3435 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
3440 void qemu_service_io(void)
3442 qemu_notify_event();
3445 /***********************************************************/
3446 /* bottom halves (can be seen as timers which expire ASAP) */
3457 static QEMUBH
*first_bh
= NULL
;
3459 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
3462 bh
= qemu_mallocz(sizeof(QEMUBH
));
3464 bh
->opaque
= opaque
;
3465 bh
->next
= first_bh
;
3470 int qemu_bh_poll(void)
3476 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3477 if (!bh
->deleted
&& bh
->scheduled
) {
3486 /* remove deleted bhs */
3500 void qemu_bh_schedule_idle(QEMUBH
*bh
)
3508 void qemu_bh_schedule(QEMUBH
*bh
)
3514 /* stop the currently executing CPU to execute the BH ASAP */
3515 qemu_notify_event();
3518 void qemu_bh_cancel(QEMUBH
*bh
)
3523 void qemu_bh_delete(QEMUBH
*bh
)
3529 static void qemu_bh_update_timeout(int *timeout
)
3533 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3534 if (!bh
->deleted
&& bh
->scheduled
) {
3536 /* idle bottom halves will be polled at least
3538 *timeout
= MIN(10, *timeout
);
3540 /* non-idle bottom halves will be executed
3549 /***********************************************************/
3550 /* machine registration */
3552 static QEMUMachine
*first_machine
= NULL
;
3553 QEMUMachine
*current_machine
= NULL
;
3555 int qemu_register_machine(QEMUMachine
*m
)
3558 pm
= &first_machine
;
3566 static QEMUMachine
*find_machine(const char *name
)
3570 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3571 if (!strcmp(m
->name
, name
))
3577 static QEMUMachine
*find_default_machine(void)
3581 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3582 if (m
->is_default
) {
3589 /***********************************************************/
3590 /* main execution loop */
3592 static void gui_update(void *opaque
)
3594 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3595 DisplayState
*ds
= opaque
;
3596 DisplayChangeListener
*dcl
= ds
->listeners
;
3600 while (dcl
!= NULL
) {
3601 if (dcl
->gui_timer_interval
&&
3602 dcl
->gui_timer_interval
< interval
)
3603 interval
= dcl
->gui_timer_interval
;
3606 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3609 static void nographic_update(void *opaque
)
3611 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3613 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3616 struct vm_change_state_entry
{
3617 VMChangeStateHandler
*cb
;
3619 LIST_ENTRY (vm_change_state_entry
) entries
;
3622 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3624 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3627 VMChangeStateEntry
*e
;
3629 e
= qemu_mallocz(sizeof (*e
));
3633 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3637 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3639 LIST_REMOVE (e
, entries
);
3643 static void vm_state_notify(int running
, int reason
)
3645 VMChangeStateEntry
*e
;
3647 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3648 e
->cb(e
->opaque
, running
, reason
);
3652 static void resume_all_vcpus(void);
3653 static void pause_all_vcpus(void);
3660 vm_state_notify(1, 0);
3661 qemu_rearm_alarm_timer(alarm_timer
);
3666 /* reset/shutdown handler */
3668 typedef struct QEMUResetEntry
{
3669 QEMUResetHandler
*func
;
3672 struct QEMUResetEntry
*next
;
3675 static QEMUResetEntry
*first_reset_entry
;
3676 static int reset_requested
;
3677 static int shutdown_requested
;
3678 static int powerdown_requested
;
3679 static int debug_requested
;
3680 static int vmstop_requested
;
3682 int qemu_no_shutdown(void)
3684 int r
= no_shutdown
;
3689 int qemu_shutdown_requested(void)
3691 int r
= shutdown_requested
;
3692 shutdown_requested
= 0;
3696 int qemu_reset_requested(void)
3698 int r
= reset_requested
;
3699 reset_requested
= 0;
3703 int qemu_powerdown_requested(void)
3705 int r
= powerdown_requested
;
3706 powerdown_requested
= 0;
3710 static int qemu_debug_requested(void)
3712 int r
= debug_requested
;
3713 debug_requested
= 0;
3717 static int qemu_vmstop_requested(void)
3719 int r
= vmstop_requested
;
3720 vmstop_requested
= 0;
3724 static void do_vm_stop(int reason
)
3727 cpu_disable_ticks();
3730 vm_state_notify(0, reason
);
3734 void qemu_register_reset(QEMUResetHandler
*func
, int order
, void *opaque
)
3736 QEMUResetEntry
**pre
, *re
;
3738 pre
= &first_reset_entry
;
3739 while (*pre
!= NULL
&& (*pre
)->order
>= order
) {
3740 pre
= &(*pre
)->next
;
3742 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3744 re
->opaque
= opaque
;
3750 void qemu_system_reset(void)
3754 /* reset all devices */
3755 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
3756 re
->func(re
->opaque
);
3760 void qemu_system_reset_request(void)
3763 shutdown_requested
= 1;
3765 reset_requested
= 1;
3767 if (cpu_single_env
) {
3768 qemu_kvm_cpu_stop(cpu_single_env
);
3770 qemu_notify_event();
3773 void qemu_system_shutdown_request(void)
3775 shutdown_requested
= 1;
3776 qemu_notify_event();
3779 void qemu_system_powerdown_request(void)
3781 powerdown_requested
= 1;
3782 qemu_notify_event();
3785 #ifdef CONFIG_IOTHREAD
3786 static void qemu_system_vmstop_request(int reason
)
3788 vmstop_requested
= reason
;
3789 qemu_notify_event();
3794 static int io_thread_fd
= -1;
3796 static void qemu_event_increment(void)
3798 static const char byte
= 0;
3800 if (io_thread_fd
== -1)
3803 write(io_thread_fd
, &byte
, sizeof(byte
));
3806 static void qemu_event_read(void *opaque
)
3808 int fd
= (unsigned long)opaque
;
3811 /* Drain the notify pipe */
3814 len
= read(fd
, buffer
, sizeof(buffer
));
3815 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
3818 static int qemu_event_init(void)
3827 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3831 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3835 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3836 (void *)(unsigned long)fds
[0]);
3838 io_thread_fd
= fds
[1];
3847 HANDLE qemu_event_handle
;
3849 static void dummy_event_handler(void *opaque
)
3853 static int qemu_event_init(void)
3855 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3856 if (!qemu_event_handle
) {
3857 perror("Failed CreateEvent");
3860 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3864 static void qemu_event_increment(void)
3866 SetEvent(qemu_event_handle
);
3870 static int cpu_can_run(CPUState
*env
)
3879 #ifndef CONFIG_IOTHREAD
3880 static int qemu_init_main_loop(void)
3882 return qemu_event_init();
3885 void qemu_init_vcpu(void *_env
)
3887 CPUState
*env
= _env
;
3894 int qemu_cpu_self(void *env
)
3899 static void resume_all_vcpus(void)
3903 static void pause_all_vcpus(void)
3907 void qemu_cpu_kick(void *env
)
3912 void qemu_notify_event(void)
3914 CPUState
*env
= cpu_single_env
;
3916 if (kvm_enabled()) {
3917 qemu_kvm_notify_work();
3923 if (env
->kqemu_enabled
)
3924 kqemu_cpu_interrupt(env
);
3929 #define qemu_mutex_lock_iothread() do { } while (0)
3930 #define qemu_mutex_unlock_iothread() do { } while (0)
3932 void vm_stop(int reason
)
3937 #else /* CONFIG_IOTHREAD */
3939 #include "qemu-thread.h"
3941 QemuMutex qemu_global_mutex
;
3942 static QemuMutex qemu_fair_mutex
;
3944 static QemuThread io_thread
;
3946 static QemuThread
*tcg_cpu_thread
;
3947 static QemuCond
*tcg_halt_cond
;
3949 static int qemu_system_ready
;
3951 static QemuCond qemu_cpu_cond
;
3953 static QemuCond qemu_system_cond
;
3954 static QemuCond qemu_pause_cond
;
3956 static void block_io_signals(void);
3957 static void unblock_io_signals(void);
3958 static int tcg_has_work(void);
3960 static int qemu_init_main_loop(void)
3964 ret
= qemu_event_init();
3968 qemu_cond_init(&qemu_pause_cond
);
3969 qemu_mutex_init(&qemu_fair_mutex
);
3970 qemu_mutex_init(&qemu_global_mutex
);
3971 qemu_mutex_lock(&qemu_global_mutex
);
3973 unblock_io_signals();
3974 qemu_thread_self(&io_thread
);
3979 static void qemu_wait_io_event(CPUState
*env
)
3981 while (!tcg_has_work())
3982 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3984 qemu_mutex_unlock(&qemu_global_mutex
);
3987 * Users of qemu_global_mutex can be starved, having no chance
3988 * to acquire it since this path will get to it first.
3989 * So use another lock to provide fairness.
3991 qemu_mutex_lock(&qemu_fair_mutex
);
3992 qemu_mutex_unlock(&qemu_fair_mutex
);
3994 qemu_mutex_lock(&qemu_global_mutex
);
3998 qemu_cond_signal(&qemu_pause_cond
);
4002 static int qemu_cpu_exec(CPUState
*env
);
4004 static void *kvm_cpu_thread_fn(void *arg
)
4006 CPUState
*env
= arg
;
4009 qemu_thread_self(env
->thread
);
4011 /* signal CPU creation */
4012 qemu_mutex_lock(&qemu_global_mutex
);
4014 qemu_cond_signal(&qemu_cpu_cond
);
4016 /* and wait for machine initialization */
4017 while (!qemu_system_ready
)
4018 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
4021 if (cpu_can_run(env
))
4023 qemu_wait_io_event(env
);
4029 static void tcg_cpu_exec(void);
4031 static void *tcg_cpu_thread_fn(void *arg
)
4033 CPUState
*env
= arg
;
4036 qemu_thread_self(env
->thread
);
4038 /* signal CPU creation */
4039 qemu_mutex_lock(&qemu_global_mutex
);
4040 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4042 qemu_cond_signal(&qemu_cpu_cond
);
4044 /* and wait for machine initialization */
4045 while (!qemu_system_ready
)
4046 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
4050 qemu_wait_io_event(cur_cpu
);
4056 void qemu_cpu_kick(void *_env
)
4058 CPUState
*env
= _env
;
4059 qemu_cond_broadcast(env
->halt_cond
);
4061 qemu_thread_signal(env
->thread
, SIGUSR1
);
4064 int qemu_cpu_self(void *env
)
4066 return (cpu_single_env
!= NULL
);
4069 static void cpu_signal(int sig
)
4072 cpu_exit(cpu_single_env
);
4075 static void block_io_signals(void)
4078 struct sigaction sigact
;
4081 sigaddset(&set
, SIGUSR2
);
4082 sigaddset(&set
, SIGIO
);
4083 sigaddset(&set
, SIGALRM
);
4084 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
4087 sigaddset(&set
, SIGUSR1
);
4088 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
4090 memset(&sigact
, 0, sizeof(sigact
));
4091 sigact
.sa_handler
= cpu_signal
;
4092 sigaction(SIGUSR1
, &sigact
, NULL
);
4095 static void unblock_io_signals(void)
4100 sigaddset(&set
, SIGUSR2
);
4101 sigaddset(&set
, SIGIO
);
4102 sigaddset(&set
, SIGALRM
);
4103 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
4106 sigaddset(&set
, SIGUSR1
);
4107 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
4110 static void qemu_signal_lock(unsigned int msecs
)
4112 qemu_mutex_lock(&qemu_fair_mutex
);
4114 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
4115 qemu_thread_signal(tcg_cpu_thread
, SIGUSR1
);
4116 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
4119 qemu_mutex_unlock(&qemu_fair_mutex
);
4122 static void qemu_mutex_lock_iothread(void)
4124 if (kvm_enabled()) {
4125 qemu_mutex_lock(&qemu_fair_mutex
);
4126 qemu_mutex_lock(&qemu_global_mutex
);
4127 qemu_mutex_unlock(&qemu_fair_mutex
);
4129 qemu_signal_lock(100);
4132 static void qemu_mutex_unlock_iothread(void)
4134 qemu_mutex_unlock(&qemu_global_mutex
);
4137 static int all_vcpus_paused(void)
4139 CPUState
*penv
= first_cpu
;
4144 penv
= (CPUState
*)penv
->next_cpu
;
4150 static void pause_all_vcpus(void)
4152 CPUState
*penv
= first_cpu
;
4156 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4157 qemu_cpu_kick(penv
);
4158 penv
= (CPUState
*)penv
->next_cpu
;
4161 while (!all_vcpus_paused()) {
4162 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
4165 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4166 penv
= (CPUState
*)penv
->next_cpu
;
4171 static void resume_all_vcpus(void)
4173 CPUState
*penv
= first_cpu
;
4178 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4179 qemu_cpu_kick(penv
);
4180 penv
= (CPUState
*)penv
->next_cpu
;
4184 static void tcg_init_vcpu(void *_env
)
4186 CPUState
*env
= _env
;
4187 /* share a single thread for all cpus with TCG */
4188 if (!tcg_cpu_thread
) {
4189 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
4190 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
4191 qemu_cond_init(env
->halt_cond
);
4192 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
4193 while (env
->created
== 0)
4194 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
4195 tcg_cpu_thread
= env
->thread
;
4196 tcg_halt_cond
= env
->halt_cond
;
4198 env
->thread
= tcg_cpu_thread
;
4199 env
->halt_cond
= tcg_halt_cond
;
4203 static void kvm_start_vcpu(CPUState
*env
)
4206 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
4207 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
4208 qemu_cond_init(env
->halt_cond
);
4209 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
4210 while (env
->created
== 0)
4211 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
4214 void qemu_init_vcpu(void *_env
)
4216 CPUState
*env
= _env
;
4219 kvm_start_vcpu(env
);
4224 void qemu_notify_event(void)
4226 qemu_event_increment();
4229 void vm_stop(int reason
)
4232 qemu_thread_self(&me
);
4234 if (!qemu_thread_equal(&me
, &io_thread
)) {
4235 qemu_system_vmstop_request(reason
);
4237 * FIXME: should not return to device code in case
4238 * vm_stop() has been requested.
4240 if (cpu_single_env
) {
4241 cpu_exit(cpu_single_env
);
4242 cpu_single_env
->stop
= 1;
4253 static void host_main_loop_wait(int *timeout
)
4259 /* XXX: need to suppress polling by better using win32 events */
4261 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
4262 ret
|= pe
->func(pe
->opaque
);
4266 WaitObjects
*w
= &wait_objects
;
4268 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
4269 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
4270 if (w
->func
[ret
- WAIT_OBJECT_0
])
4271 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
4273 /* Check for additional signaled events */
4274 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
4276 /* Check if event is signaled */
4277 ret2
= WaitForSingleObject(w
->events
[i
], 0);
4278 if(ret2
== WAIT_OBJECT_0
) {
4280 w
->func
[i
](w
->opaque
[i
]);
4281 } else if (ret2
== WAIT_TIMEOUT
) {
4283 err
= GetLastError();
4284 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
4287 } else if (ret
== WAIT_TIMEOUT
) {
4289 err
= GetLastError();
4290 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
4297 static void host_main_loop_wait(int *timeout
)
4302 void main_loop_wait(int timeout
)
4304 IOHandlerRecord
*ioh
;
4305 fd_set rfds
, wfds
, xfds
;
4309 qemu_bh_update_timeout(&timeout
);
4311 host_main_loop_wait(&timeout
);
4313 /* poll any events */
4314 /* XXX: separate device handlers from system ones */
4319 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4323 (!ioh
->fd_read_poll
||
4324 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
4325 FD_SET(ioh
->fd
, &rfds
);
4329 if (ioh
->fd_write
) {
4330 FD_SET(ioh
->fd
, &wfds
);
4336 tv
.tv_sec
= timeout
/ 1000;
4337 tv
.tv_usec
= (timeout
% 1000) * 1000;
4339 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
4341 ret
= qemu_select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
4343 IOHandlerRecord
**pioh
;
4345 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4346 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
4347 ioh
->fd_read(ioh
->opaque
);
4348 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
4349 FD_CLR(ioh
->fd
, &rfds
);
4351 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
4352 ioh
->fd_write(ioh
->opaque
);
4356 /* remove deleted IO handlers */
4357 pioh
= &first_io_handler
;
4368 slirp_select_poll(&rfds
, &wfds
, &xfds
, (ret
< 0));
4370 /* rearm timer, if not periodic */
4371 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
4372 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
4373 qemu_rearm_alarm_timer(alarm_timer
);
4376 /* vm time timers */
4378 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
4379 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
4380 qemu_get_clock(vm_clock
));
4383 /* real time timers */
4384 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
4385 qemu_get_clock(rt_clock
));
4387 /* Check bottom-halves last in case any of the earlier events triggered
4393 static int qemu_cpu_exec(CPUState
*env
)
4396 #ifdef CONFIG_PROFILER
4400 #ifdef CONFIG_PROFILER
4401 ti
= profile_getclock();
4406 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
4407 env
->icount_decr
.u16
.low
= 0;
4408 env
->icount_extra
= 0;
4409 count
= qemu_next_deadline();
4410 count
= (count
+ (1 << icount_time_shift
) - 1)
4411 >> icount_time_shift
;
4412 qemu_icount
+= count
;
4413 decr
= (count
> 0xffff) ? 0xffff : count
;
4415 env
->icount_decr
.u16
.low
= decr
;
4416 env
->icount_extra
= count
;
4418 ret
= cpu_exec(env
);
4419 #ifdef CONFIG_PROFILER
4420 qemu_time
+= profile_getclock() - ti
;
4423 /* Fold pending instructions back into the
4424 instruction counter, and clear the interrupt flag. */
4425 qemu_icount
-= (env
->icount_decr
.u16
.low
4426 + env
->icount_extra
);
4427 env
->icount_decr
.u32
= 0;
4428 env
->icount_extra
= 0;
4433 static void tcg_cpu_exec(void)
4437 if (next_cpu
== NULL
)
4438 next_cpu
= first_cpu
;
4439 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
4440 CPUState
*env
= cur_cpu
= next_cpu
;
4444 if (timer_alarm_pending
) {
4445 timer_alarm_pending
= 0;
4448 if (cpu_can_run(env
))
4449 ret
= qemu_cpu_exec(env
);
4450 if (ret
== EXCP_DEBUG
) {
4451 gdb_set_stop_cpu(env
);
4452 debug_requested
= 1;
4458 static int cpu_has_work(CPUState
*env
)
4466 if (qemu_cpu_has_work(env
))
4471 static int tcg_has_work(void)
4475 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4476 if (cpu_has_work(env
))
4481 static int qemu_calculate_timeout(void)
4483 #ifndef CONFIG_IOTHREAD
4488 else if (tcg_has_work())
4490 else if (!use_icount
)
4493 /* XXX: use timeout computed from timers */
4496 /* Advance virtual time to the next event. */
4497 if (use_icount
== 1) {
4498 /* When not using an adaptive execution frequency
4499 we tend to get badly out of sync with real time,
4500 so just delay for a reasonable amount of time. */
4503 delta
= cpu_get_icount() - cpu_get_clock();
4506 /* If virtual time is ahead of real time then just
4508 timeout
= (delta
/ 1000000) + 1;
4510 /* Wait for either IO to occur or the next
4512 add
= qemu_next_deadline();
4513 /* We advance the timer before checking for IO.
4514 Limit the amount we advance so that early IO
4515 activity won't get the guest too far ahead. */
4519 add
= (add
+ (1 << icount_time_shift
) - 1)
4520 >> icount_time_shift
;
4522 timeout
= delta
/ 1000000;
4529 #else /* CONFIG_IOTHREAD */
4534 static int vm_can_run(void)
4536 if (powerdown_requested
)
4538 if (reset_requested
)
4540 if (shutdown_requested
)
4542 if (debug_requested
)
4547 static void main_loop(void)
4551 if (kvm_enabled()) {
4553 cpu_disable_ticks();
4557 #ifdef CONFIG_IOTHREAD
4558 qemu_system_ready
= 1;
4559 qemu_cond_broadcast(&qemu_system_cond
);
4564 #ifdef CONFIG_PROFILER
4567 #ifndef CONFIG_IOTHREAD
4570 #ifdef CONFIG_PROFILER
4571 ti
= profile_getclock();
4573 main_loop_wait(qemu_calculate_timeout());
4574 #ifdef CONFIG_PROFILER
4575 dev_time
+= profile_getclock() - ti
;
4577 } while (vm_can_run());
4579 if (qemu_debug_requested())
4580 vm_stop(EXCP_DEBUG
);
4581 if (qemu_shutdown_requested()) {
4588 if (qemu_reset_requested()) {
4590 qemu_system_reset();
4593 if (qemu_powerdown_requested())
4594 qemu_system_powerdown();
4595 if ((r
= qemu_vmstop_requested()))
4601 static void version(void)
4603 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4606 static void help(int exitcode
)
4609 printf("usage: %s [options] [disk_image]\n"
4611 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4613 #define DEF(option, opt_arg, opt_enum, opt_help) \
4615 #define DEFHEADING(text) stringify(text) "\n"
4616 #include "qemu-options.h"
4621 "During emulation, the following keys are useful:\n"
4622 "ctrl-alt-f toggle full screen\n"
4623 "ctrl-alt-n switch to virtual console 'n'\n"
4624 "ctrl-alt toggle mouse and keyboard grab\n"
4626 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4631 DEFAULT_NETWORK_SCRIPT
,
4632 DEFAULT_NETWORK_DOWN_SCRIPT
,
4634 DEFAULT_GDBSTUB_PORT
,
4639 #define HAS_ARG 0x0001
4642 #define DEF(option, opt_arg, opt_enum, opt_help) \
4644 #define DEFHEADING(text)
4645 #include "qemu-options.h"
4651 typedef struct QEMUOption
{
4657 static const QEMUOption qemu_options
[] = {
4658 { "h", 0, QEMU_OPTION_h
},
4659 #define DEF(option, opt_arg, opt_enum, opt_help) \
4660 { option, opt_arg, opt_enum },
4661 #define DEFHEADING(text)
4662 #include "qemu-options.h"
4670 struct soundhw soundhw
[] = {
4671 #ifdef HAS_AUDIO_CHOICE
4672 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4678 { .init_isa
= pcspk_audio_init
}
4685 "Creative Sound Blaster 16",
4688 { .init_isa
= SB16_init
}
4692 #ifdef CONFIG_CS4231A
4698 { .init_isa
= cs4231a_init
}
4706 "Yamaha YMF262 (OPL3)",
4708 "Yamaha YM3812 (OPL2)",
4712 { .init_isa
= Adlib_init
}
4719 "Gravis Ultrasound GF1",
4722 { .init_isa
= GUS_init
}
4729 "Intel 82801AA AC97 Audio",
4732 { .init_pci
= ac97_init
}
4736 #ifdef CONFIG_ES1370
4739 "ENSONIQ AudioPCI ES1370",
4742 { .init_pci
= es1370_init
}
4746 #endif /* HAS_AUDIO_CHOICE */
4748 { NULL
, NULL
, 0, 0, { NULL
} }
4751 static void select_soundhw (const char *optarg
)
4755 if (*optarg
== '?') {
4758 printf ("Valid sound card names (comma separated):\n");
4759 for (c
= soundhw
; c
->name
; ++c
) {
4760 printf ("%-11s %s\n", c
->name
, c
->descr
);
4762 printf ("\n-soundhw all will enable all of the above\n");
4763 exit (*optarg
!= '?');
4771 if (!strcmp (optarg
, "all")) {
4772 for (c
= soundhw
; c
->name
; ++c
) {
4780 e
= strchr (p
, ',');
4781 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4783 for (c
= soundhw
; c
->name
; ++c
) {
4784 if (!strncmp (c
->name
, p
, l
)) {
4793 "Unknown sound card name (too big to show)\n");
4796 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4801 p
+= l
+ (e
!= NULL
);
4805 goto show_valid_cards
;
4810 static void select_vgahw (const char *p
)
4814 cirrus_vga_enabled
= 0;
4815 std_vga_enabled
= 0;
4818 if (strstart(p
, "std", &opts
)) {
4819 std_vga_enabled
= 1;
4820 } else if (strstart(p
, "cirrus", &opts
)) {
4821 cirrus_vga_enabled
= 1;
4822 } else if (strstart(p
, "vmware", &opts
)) {
4824 } else if (strstart(p
, "xenfb", &opts
)) {
4826 } else if (!strstart(p
, "none", &opts
)) {
4828 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4832 const char *nextopt
;
4834 if (strstart(opts
, ",retrace=", &nextopt
)) {
4836 if (strstart(opts
, "dumb", &nextopt
))
4837 vga_retrace_method
= VGA_RETRACE_DUMB
;
4838 else if (strstart(opts
, "precise", &nextopt
))
4839 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4840 else goto invalid_vga
;
4841 } else goto invalid_vga
;
4847 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4849 exit(STATUS_CONTROL_C_EXIT
);
4854 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4858 if(strlen(str
) != 36)
4861 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4862 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4863 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4869 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4875 #define MAX_NET_CLIENTS 32
4879 static void termsig_handler(int signal
)
4881 qemu_system_shutdown_request();
4884 static void sigchld_handler(int signal
)
4886 waitpid(-1, NULL
, WNOHANG
);
4889 static void sighandler_setup(void)
4891 struct sigaction act
;
4893 memset(&act
, 0, sizeof(act
));
4894 act
.sa_handler
= termsig_handler
;
4895 sigaction(SIGINT
, &act
, NULL
);
4896 sigaction(SIGHUP
, &act
, NULL
);
4897 sigaction(SIGTERM
, &act
, NULL
);
4899 act
.sa_handler
= sigchld_handler
;
4900 act
.sa_flags
= SA_NOCLDSTOP
;
4901 sigaction(SIGCHLD
, &act
, NULL
);
4907 /* Look for support files in the same directory as the executable. */
4908 static char *find_datadir(const char *argv0
)
4914 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
4921 while (p
!= buf
&& *p
!= '\\')
4924 if (access(buf
, R_OK
) == 0) {
4925 return qemu_strdup(buf
);
4931 /* Find a likely location for support files using the location of the binary.
4932 For installed binaries this will be "$bindir/../share/qemu". When
4933 running from the build tree this will be "$bindir/../pc-bios". */
4934 #define SHARE_SUFFIX "/share/qemu"
4935 #define BUILD_SUFFIX "/pc-bios"
4936 static char *find_datadir(const char *argv0
)
4946 #if defined(__linux__)
4949 len
= readlink("/proc/self/exe", buf
, sizeof(buf
) - 1);
4955 #elif defined(__FreeBSD__)
4958 len
= readlink("/proc/curproc/file", buf
, sizeof(buf
) - 1);
4965 /* If we don't have any way of figuring out the actual executable
4966 location then try argv[0]. */
4971 p
= realpath(argv0
, p
);
4979 max_len
= strlen(dir
) +
4980 MAX(strlen(SHARE_SUFFIX
), strlen(BUILD_SUFFIX
)) + 1;
4981 res
= qemu_mallocz(max_len
);
4982 snprintf(res
, max_len
, "%s%s", dir
, SHARE_SUFFIX
);
4983 if (access(res
, R_OK
)) {
4984 snprintf(res
, max_len
, "%s%s", dir
, BUILD_SUFFIX
);
4985 if (access(res
, R_OK
)) {
4999 char *qemu_find_file(int type
, const char *name
)
5005 /* If name contains path separators then try it as a straight path. */
5006 if ((strchr(name
, '/') || strchr(name
, '\\'))
5007 && access(name
, R_OK
) == 0) {
5008 return strdup(name
);
5011 case QEMU_FILE_TYPE_BIOS
:
5014 case QEMU_FILE_TYPE_KEYMAP
:
5015 subdir
= "keymaps/";
5020 len
= strlen(data_dir
) + strlen(name
) + strlen(subdir
) + 2;
5021 buf
= qemu_mallocz(len
);
5022 snprintf(buf
, len
, "%s/%s%s", data_dir
, subdir
, name
);
5023 if (access(buf
, R_OK
)) {
5030 int main(int argc
, char **argv
, char **envp
)
5032 const char *gdbstub_dev
= NULL
;
5033 uint32_t boot_devices_bitmap
= 0;
5035 int snapshot
, linux_boot
, net_boot
;
5036 const char *initrd_filename
;
5037 const char *kernel_filename
, *kernel_cmdline
;
5038 const char *boot_devices
= "";
5040 DisplayChangeListener
*dcl
;
5041 int cyls
, heads
, secs
, translation
;
5042 const char *net_clients
[MAX_NET_CLIENTS
];
5044 const char *bt_opts
[MAX_BT_CMDLINE
];
5048 const char *r
, *optarg
;
5049 CharDriverState
*monitor_hd
= NULL
;
5050 const char *monitor_device
;
5051 const char *serial_devices
[MAX_SERIAL_PORTS
];
5052 int serial_device_index
;
5053 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
5054 int parallel_device_index
;
5055 const char *virtio_consoles
[MAX_VIRTIO_CONSOLES
];
5056 int virtio_console_index
;
5057 const char *loadvm
= NULL
;
5058 QEMUMachine
*machine
;
5059 const char *cpu_model
;
5060 const char *usb_devices
[MAX_USB_CMDLINE
];
5061 int usb_devices_index
;
5066 const char *pid_file
= NULL
;
5067 const char *incoming
= NULL
;
5070 struct passwd
*pwd
= NULL
;
5071 const char *chroot_dir
= NULL
;
5072 const char *run_as
= NULL
;
5075 int show_vnc_port
= 0;
5077 qemu_cache_utils_init(envp
);
5079 LIST_INIT (&vm_change_state_head
);
5082 struct sigaction act
;
5083 sigfillset(&act
.sa_mask
);
5085 act
.sa_handler
= SIG_IGN
;
5086 sigaction(SIGPIPE
, &act
, NULL
);
5089 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
5090 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5091 QEMU to run on a single CPU */
5096 h
= GetCurrentProcess();
5097 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
5098 for(i
= 0; i
< 32; i
++) {
5099 if (mask
& (1 << i
))
5104 SetProcessAffinityMask(h
, mask
);
5110 module_call_init(MODULE_INIT_MACHINE
);
5111 machine
= find_default_machine();
5113 initrd_filename
= NULL
;
5116 kernel_filename
= NULL
;
5117 kernel_cmdline
= "";
5118 cyls
= heads
= secs
= 0;
5119 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5120 monitor_device
= "vc:80Cx24C";
5122 serial_devices
[0] = "vc:80Cx24C";
5123 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
5124 serial_devices
[i
] = NULL
;
5125 serial_device_index
= 0;
5127 parallel_devices
[0] = "vc:80Cx24C";
5128 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
5129 parallel_devices
[i
] = NULL
;
5130 parallel_device_index
= 0;
5132 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++)
5133 virtio_consoles
[i
] = NULL
;
5134 virtio_console_index
= 0;
5136 for (i
= 0; i
< MAX_NODES
; i
++) {
5138 node_cpumask
[i
] = 0;
5141 usb_devices_index
= 0;
5142 assigned_devices_index
= 0;
5156 register_watchdogs();
5164 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
5166 const QEMUOption
*popt
;
5169 /* Treat --foo the same as -foo. */
5172 popt
= qemu_options
;
5175 fprintf(stderr
, "%s: invalid option -- '%s'\n",
5179 if (!strcmp(popt
->name
, r
+ 1))
5183 if (popt
->flags
& HAS_ARG
) {
5184 if (optind
>= argc
) {
5185 fprintf(stderr
, "%s: option '%s' requires an argument\n",
5189 optarg
= argv
[optind
++];
5194 switch(popt
->index
) {
5196 machine
= find_machine(optarg
);
5199 printf("Supported machines are:\n");
5200 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5201 printf("%-10s %s%s\n",
5203 m
->is_default
? " (default)" : "");
5205 exit(*optarg
!= '?');
5208 case QEMU_OPTION_cpu
:
5209 /* hw initialization will check this */
5210 if (*optarg
== '?') {
5211 /* XXX: implement xxx_cpu_list for targets that still miss it */
5212 #if defined(cpu_list)
5213 cpu_list(stdout
, &fprintf
);
5220 case QEMU_OPTION_initrd
:
5221 initrd_filename
= optarg
;
5223 case QEMU_OPTION_hda
:
5225 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
5227 hda_index
= drive_add(optarg
, HD_ALIAS
5228 ",cyls=%d,heads=%d,secs=%d%s",
5229 0, cyls
, heads
, secs
,
5230 translation
== BIOS_ATA_TRANSLATION_LBA
?
5232 translation
== BIOS_ATA_TRANSLATION_NONE
?
5233 ",trans=none" : "");
5235 case QEMU_OPTION_hdb
:
5236 case QEMU_OPTION_hdc
:
5237 case QEMU_OPTION_hdd
:
5238 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
5240 case QEMU_OPTION_drive
:
5241 drive_add(NULL
, "%s", optarg
);
5243 case QEMU_OPTION_mtdblock
:
5244 drive_add(optarg
, MTD_ALIAS
);
5246 case QEMU_OPTION_sd
:
5247 drive_add(optarg
, SD_ALIAS
);
5249 case QEMU_OPTION_pflash
:
5250 drive_add(optarg
, PFLASH_ALIAS
);
5252 case QEMU_OPTION_snapshot
:
5255 case QEMU_OPTION_hdachs
:
5259 cyls
= strtol(p
, (char **)&p
, 0);
5260 if (cyls
< 1 || cyls
> 16383)
5265 heads
= strtol(p
, (char **)&p
, 0);
5266 if (heads
< 1 || heads
> 16)
5271 secs
= strtol(p
, (char **)&p
, 0);
5272 if (secs
< 1 || secs
> 63)
5276 if (!strcmp(p
, "none"))
5277 translation
= BIOS_ATA_TRANSLATION_NONE
;
5278 else if (!strcmp(p
, "lba"))
5279 translation
= BIOS_ATA_TRANSLATION_LBA
;
5280 else if (!strcmp(p
, "auto"))
5281 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5284 } else if (*p
!= '\0') {
5286 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5289 if (hda_index
!= -1)
5290 snprintf(drives_opt
[hda_index
].opt
,
5291 sizeof(drives_opt
[hda_index
].opt
),
5292 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
5293 0, cyls
, heads
, secs
,
5294 translation
== BIOS_ATA_TRANSLATION_LBA
?
5296 translation
== BIOS_ATA_TRANSLATION_NONE
?
5297 ",trans=none" : "");
5300 case QEMU_OPTION_numa
:
5301 if (nb_numa_nodes
>= MAX_NODES
) {
5302 fprintf(stderr
, "qemu: too many NUMA nodes\n");
5307 case QEMU_OPTION_nographic
:
5308 display_type
= DT_NOGRAPHIC
;
5310 #ifdef CONFIG_CURSES
5311 case QEMU_OPTION_curses
:
5312 display_type
= DT_CURSES
;
5315 case QEMU_OPTION_portrait
:
5318 case QEMU_OPTION_kernel
:
5319 kernel_filename
= optarg
;
5321 case QEMU_OPTION_append
:
5322 kernel_cmdline
= optarg
;
5324 case QEMU_OPTION_cdrom
:
5325 drive_add(optarg
, CDROM_ALIAS
);
5327 case QEMU_OPTION_boot
:
5328 boot_devices
= optarg
;
5329 /* We just do some generic consistency checks */
5331 /* Could easily be extended to 64 devices if needed */
5334 boot_devices_bitmap
= 0;
5335 for (p
= boot_devices
; *p
!= '\0'; p
++) {
5336 /* Allowed boot devices are:
5337 * a b : floppy disk drives
5338 * c ... f : IDE disk drives
5339 * g ... m : machine implementation dependant drives
5340 * n ... p : network devices
5341 * It's up to each machine implementation to check
5342 * if the given boot devices match the actual hardware
5343 * implementation and firmware features.
5345 if (*p
< 'a' || *p
> 'q') {
5346 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
5349 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
5351 "Boot device '%c' was given twice\n",*p
);
5354 boot_devices_bitmap
|= 1 << (*p
- 'a');
5358 case QEMU_OPTION_fda
:
5359 case QEMU_OPTION_fdb
:
5360 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
5363 case QEMU_OPTION_no_fd_bootchk
:
5367 case QEMU_OPTION_net
:
5368 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
5369 fprintf(stderr
, "qemu: too many network clients\n");
5372 net_clients
[nb_net_clients
] = optarg
;
5376 case QEMU_OPTION_tftp
:
5377 legacy_tftp_prefix
= optarg
;
5379 case QEMU_OPTION_bootp
:
5380 legacy_bootp_filename
= optarg
;
5383 case QEMU_OPTION_smb
:
5384 net_slirp_smb(optarg
);
5387 case QEMU_OPTION_redir
:
5388 net_slirp_redir(optarg
);
5391 case QEMU_OPTION_bt
:
5392 if (nb_bt_opts
>= MAX_BT_CMDLINE
) {
5393 fprintf(stderr
, "qemu: too many bluetooth options\n");
5396 bt_opts
[nb_bt_opts
++] = optarg
;
5399 case QEMU_OPTION_audio_help
:
5403 case QEMU_OPTION_soundhw
:
5404 select_soundhw (optarg
);
5410 case QEMU_OPTION_version
:
5414 case QEMU_OPTION_m
: {
5418 value
= strtoul(optarg
, &ptr
, 10);
5420 case 0: case 'M': case 'm':
5427 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5431 /* On 32-bit hosts, QEMU is limited by virtual address space */
5432 if (value
> (2047 << 20)
5433 #ifndef CONFIG_KQEMU
5434 && HOST_LONG_BITS
== 32
5437 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5440 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5441 fprintf(stderr
, "qemu: ram size too large\n");
5450 const CPULogItem
*item
;
5452 mask
= cpu_str_to_log_mask(optarg
);
5454 printf("Log items (comma separated):\n");
5455 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5456 printf("%-10s %s\n", item
->name
, item
->help
);
5464 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5466 case QEMU_OPTION_gdb
:
5467 gdbstub_dev
= optarg
;
5472 case QEMU_OPTION_bios
:
5475 case QEMU_OPTION_singlestep
:
5483 keyboard_layout
= optarg
;
5486 case QEMU_OPTION_localtime
:
5489 case QEMU_OPTION_vga
:
5490 select_vgahw (optarg
);
5492 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5498 w
= strtol(p
, (char **)&p
, 10);
5501 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5507 h
= strtol(p
, (char **)&p
, 10);
5512 depth
= strtol(p
, (char **)&p
, 10);
5513 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5514 depth
!= 24 && depth
!= 32)
5516 } else if (*p
== '\0') {
5517 depth
= graphic_depth
;
5524 graphic_depth
= depth
;
5528 case QEMU_OPTION_echr
:
5531 term_escape_char
= strtol(optarg
, &r
, 0);
5533 printf("Bad argument to echr\n");
5536 case QEMU_OPTION_monitor
:
5537 monitor_device
= optarg
;
5539 case QEMU_OPTION_serial
:
5540 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
5541 fprintf(stderr
, "qemu: too many serial ports\n");
5544 serial_devices
[serial_device_index
] = optarg
;
5545 serial_device_index
++;
5547 case QEMU_OPTION_watchdog
:
5548 i
= select_watchdog(optarg
);
5550 exit (i
== 1 ? 1 : 0);
5552 case QEMU_OPTION_watchdog_action
:
5553 if (select_watchdog_action(optarg
) == -1) {
5554 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5558 case QEMU_OPTION_virtiocon
:
5559 if (virtio_console_index
>= MAX_VIRTIO_CONSOLES
) {
5560 fprintf(stderr
, "qemu: too many virtio consoles\n");
5563 virtio_consoles
[virtio_console_index
] = optarg
;
5564 virtio_console_index
++;
5566 case QEMU_OPTION_parallel
:
5567 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
5568 fprintf(stderr
, "qemu: too many parallel ports\n");
5571 parallel_devices
[parallel_device_index
] = optarg
;
5572 parallel_device_index
++;
5574 case QEMU_OPTION_loadvm
:
5577 case QEMU_OPTION_full_screen
:
5581 case QEMU_OPTION_no_frame
:
5584 case QEMU_OPTION_alt_grab
:
5587 case QEMU_OPTION_no_quit
:
5590 case QEMU_OPTION_sdl
:
5591 display_type
= DT_SDL
;
5594 case QEMU_OPTION_pidfile
:
5598 case QEMU_OPTION_win2k_hack
:
5599 win2k_install_hack
= 1;
5601 case QEMU_OPTION_rtc_td_hack
:
5604 case QEMU_OPTION_acpitable
:
5605 if(acpi_table_add(optarg
) < 0) {
5606 fprintf(stderr
, "Wrong acpi table provided\n");
5610 case QEMU_OPTION_smbios
:
5611 if(smbios_entry_add(optarg
) < 0) {
5612 fprintf(stderr
, "Wrong smbios provided\n");
5618 case QEMU_OPTION_no_kqemu
:
5621 case QEMU_OPTION_kernel_kqemu
:
5626 case QEMU_OPTION_enable_kvm
:
5634 case QEMU_OPTION_no_kvm
:
5637 case QEMU_OPTION_no_kvm_irqchip
: {
5642 case QEMU_OPTION_no_kvm_pit
: {
5646 case QEMU_OPTION_no_kvm_pit_reinjection
: {
5647 kvm_pit_reinject
= 0;
5650 case QEMU_OPTION_enable_nesting
: {
5654 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5655 case QEMU_OPTION_pcidevice
:
5656 if (assigned_devices_index
>= MAX_DEV_ASSIGN_CMDLINE
) {
5657 fprintf(stderr
, "Too many assigned devices\n");
5660 assigned_devices
[assigned_devices_index
] = optarg
;
5661 assigned_devices_index
++;
5665 case QEMU_OPTION_usb
:
5668 case QEMU_OPTION_usbdevice
:
5670 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
5671 fprintf(stderr
, "Too many USB devices\n");
5674 usb_devices
[usb_devices_index
] = optarg
;
5675 usb_devices_index
++;
5677 case QEMU_OPTION_smp
:
5678 smp_cpus
= atoi(optarg
);
5680 fprintf(stderr
, "Invalid number of CPUs\n");
5684 case QEMU_OPTION_vnc
:
5685 display_type
= DT_VNC
;
5686 vnc_display
= optarg
;
5689 case QEMU_OPTION_no_acpi
:
5692 case QEMU_OPTION_no_hpet
:
5695 case QEMU_OPTION_no_virtio_balloon
:
5696 no_virtio_balloon
= 1;
5699 case QEMU_OPTION_no_reboot
:
5702 case QEMU_OPTION_no_shutdown
:
5705 case QEMU_OPTION_show_cursor
:
5708 case QEMU_OPTION_uuid
:
5709 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5710 fprintf(stderr
, "Fail to parse UUID string."
5711 " Wrong format.\n");
5716 case QEMU_OPTION_daemonize
:
5720 case QEMU_OPTION_option_rom
:
5721 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5722 fprintf(stderr
, "Too many option ROMs\n");
5725 option_rom
[nb_option_roms
] = optarg
;
5728 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5729 case QEMU_OPTION_semihosting
:
5730 semihosting_enabled
= 1;
5733 case QEMU_OPTION_tdf
:
5736 case QEMU_OPTION_kvm_shadow_memory
:
5737 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
5739 case QEMU_OPTION_mempath
:
5743 case QEMU_OPTION_mem_prealloc
:
5744 mem_prealloc
= !mem_prealloc
;
5747 case QEMU_OPTION_name
:
5750 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5751 case QEMU_OPTION_prom_env
:
5752 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5753 fprintf(stderr
, "Too many prom variables\n");
5756 prom_envs
[nb_prom_envs
] = optarg
;
5761 case QEMU_OPTION_old_param
:
5765 case QEMU_OPTION_clock
:
5766 configure_alarms(optarg
);
5768 case QEMU_OPTION_startdate
:
5771 time_t rtc_start_date
;
5772 if (!strcmp(optarg
, "now")) {
5773 rtc_date_offset
= -1;
5775 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
5783 } else if (sscanf(optarg
, "%d-%d-%d",
5786 &tm
.tm_mday
) == 3) {
5795 rtc_start_date
= mktimegm(&tm
);
5796 if (rtc_start_date
== -1) {
5798 fprintf(stderr
, "Invalid date format. Valid format are:\n"
5799 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5802 rtc_date_offset
= time(NULL
) - rtc_start_date
;
5806 case QEMU_OPTION_tb_size
:
5807 tb_size
= strtol(optarg
, NULL
, 0);
5811 case QEMU_OPTION_icount
:
5813 if (strcmp(optarg
, "auto") == 0) {
5814 icount_time_shift
= -1;
5816 icount_time_shift
= strtol(optarg
, NULL
, 0);
5819 case QEMU_OPTION_incoming
:
5823 case QEMU_OPTION_chroot
:
5824 chroot_dir
= optarg
;
5826 case QEMU_OPTION_runas
:
5829 case QEMU_OPTION_nvram
:
5834 case QEMU_OPTION_xen_domid
:
5835 xen_domid
= atoi(optarg
);
5837 case QEMU_OPTION_xen_create
:
5838 xen_mode
= XEN_CREATE
;
5840 case QEMU_OPTION_xen_attach
:
5841 xen_mode
= XEN_ATTACH
;
5848 /* If no data_dir is specified then try to find it relative to the
5851 data_dir
= find_datadir(argv
[0]);
5853 /* If all else fails use the install patch specified when building. */
5855 data_dir
= CONFIG_QEMU_SHAREDIR
;
5858 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5859 if (kvm_allowed
&& kqemu_allowed
) {
5861 "You can not enable both KVM and kqemu at the same time\n");
5866 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5867 if (smp_cpus
> machine
->max_cpus
) {
5868 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5869 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5874 if (display_type
== DT_NOGRAPHIC
) {
5875 if (serial_device_index
== 0)
5876 serial_devices
[0] = "stdio";
5877 if (parallel_device_index
== 0)
5878 parallel_devices
[0] = "null";
5879 if (strncmp(monitor_device
, "vc", 2) == 0)
5880 monitor_device
= "stdio";
5887 if (pipe(fds
) == -1)
5898 len
= read(fds
[0], &status
, 1);
5899 if (len
== -1 && (errno
== EINTR
))
5904 else if (status
== 1) {
5905 fprintf(stderr
, "Could not acquire pidfile\n");
5922 signal(SIGTSTP
, SIG_IGN
);
5923 signal(SIGTTOU
, SIG_IGN
);
5924 signal(SIGTTIN
, SIG_IGN
);
5928 if (kvm_enabled()) {
5929 if (kvm_qemu_init() < 0) {
5930 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
5931 #ifdef NO_CPU_EMULATION
5932 fprintf(stderr
, "Compiled with --disable-cpu-emulation, exiting.\n");
5940 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5943 write(fds
[1], &status
, 1);
5945 fprintf(stderr
, "Could not acquire pid file\n");
5954 if (qemu_init_main_loop()) {
5955 fprintf(stderr
, "qemu_init_main_loop failed\n");
5958 linux_boot
= (kernel_filename
!= NULL
);
5960 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5961 fprintf(stderr
, "-append only allowed with -kernel option\n");
5965 if (!linux_boot
&& initrd_filename
!= NULL
) {
5966 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5970 /* boot to floppy or the default cd if no hard disk defined yet */
5971 if (!boot_devices
[0]) {
5972 boot_devices
= "cad";
5974 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5977 if (init_timer_alarm() < 0) {
5978 fprintf(stderr
, "could not initialize alarm timer\n");
5981 if (use_icount
&& icount_time_shift
< 0) {
5983 /* 125MIPS seems a reasonable initial guess at the guest speed.
5984 It will be corrected fairly quickly anyway. */
5985 icount_time_shift
= 3;
5986 init_icount_adjust();
5993 /* init network clients */
5994 if (nb_net_clients
== 0) {
5995 /* if no clients, we use a default config */
5996 net_clients
[nb_net_clients
++] = "nic";
5998 net_clients
[nb_net_clients
++] = "user";
6002 for(i
= 0;i
< nb_net_clients
; i
++) {
6003 if (net_client_parse(net_clients
[i
]) < 0)
6007 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
6008 net_set_boot_mask(net_boot
);
6012 /* init the bluetooth world */
6013 for (i
= 0; i
< nb_bt_opts
; i
++)
6014 if (bt_parse(bt_opts
[i
]))
6017 /* init the memory */
6019 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
6021 if (kvm_enabled()) {
6022 if (kvm_qemu_create_context() < 0) {
6023 fprintf(stderr
, "Could not create KVM context\n");
6029 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
6030 guest ram allocation. It needs to go away. */
6031 if (kqemu_allowed
) {
6032 kqemu_phys_ram_size
= ram_size
+ 8 * 1024 * 1024 + 4 * 1024 * 1024;
6033 kqemu_phys_ram_base
= qemu_vmalloc(kqemu_phys_ram_size
);
6034 if (!kqemu_phys_ram_base
) {
6035 fprintf(stderr
, "Could not allocate physical memory\n");
6041 /* init the dynamic translator */
6042 cpu_exec_init_all(tb_size
* 1024 * 1024);
6046 /* we always create the cdrom drive, even if no disk is there */
6048 if (nb_drives_opt
< MAX_DRIVES
)
6049 drive_add(NULL
, CDROM_ALIAS
);
6051 /* we always create at least one floppy */
6053 if (nb_drives_opt
< MAX_DRIVES
)
6054 drive_add(NULL
, FD_ALIAS
, 0);
6056 /* we always create one sd slot, even if no card is in it */
6058 if (nb_drives_opt
< MAX_DRIVES
)
6059 drive_add(NULL
, SD_ALIAS
);
6061 /* open the virtual block devices
6062 * note that migration with device
6063 * hot add/remove is broken.
6065 for(i
= 0; i
< nb_drives_opt
; i
++)
6066 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
6069 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
6070 register_savevm_live("ram", 0, 3, ram_save_live
, NULL
, ram_load
, NULL
);
6073 /* must be after terminal init, SDL library changes signal handlers */
6077 /* Maintain compatibility with multiple stdio monitors */
6078 if (!strcmp(monitor_device
,"stdio")) {
6079 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6080 const char *devname
= serial_devices
[i
];
6081 if (devname
&& !strcmp(devname
,"mon:stdio")) {
6082 monitor_device
= NULL
;
6084 } else if (devname
&& !strcmp(devname
,"stdio")) {
6085 monitor_device
= NULL
;
6086 serial_devices
[i
] = "mon:stdio";
6092 if (nb_numa_nodes
> 0) {
6095 if (nb_numa_nodes
> smp_cpus
) {
6096 nb_numa_nodes
= smp_cpus
;
6099 /* If no memory size if given for any node, assume the default case
6100 * and distribute the available memory equally across all nodes
6102 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6103 if (node_mem
[i
] != 0)
6106 if (i
== nb_numa_nodes
) {
6107 uint64_t usedmem
= 0;
6109 /* On Linux, the each node's border has to be 8MB aligned,
6110 * the final node gets the rest.
6112 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
6113 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
6114 usedmem
+= node_mem
[i
];
6116 node_mem
[i
] = ram_size
- usedmem
;
6119 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6120 if (node_cpumask
[i
] != 0)
6123 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6124 * must cope with this anyway, because there are BIOSes out there in
6125 * real machines which also use this scheme.
6127 if (i
== nb_numa_nodes
) {
6128 for (i
= 0; i
< smp_cpus
; i
++) {
6129 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
6135 if (kvm_enabled()) {
6138 ret
= kvm_init(smp_cpus
);
6140 fprintf(stderr
, "failed to initialize KVM\n");
6146 if (monitor_device
) {
6147 monitor_hd
= qemu_chr_open("monitor", monitor_device
, NULL
);
6149 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
6154 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6155 const char *devname
= serial_devices
[i
];
6156 if (devname
&& strcmp(devname
, "none")) {
6158 snprintf(label
, sizeof(label
), "serial%d", i
);
6159 serial_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6160 if (!serial_hds
[i
]) {
6161 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
6168 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
6169 const char *devname
= parallel_devices
[i
];
6170 if (devname
&& strcmp(devname
, "none")) {
6172 snprintf(label
, sizeof(label
), "parallel%d", i
);
6173 parallel_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6174 if (!parallel_hds
[i
]) {
6175 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
6182 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
6183 const char *devname
= virtio_consoles
[i
];
6184 if (devname
&& strcmp(devname
, "none")) {
6186 snprintf(label
, sizeof(label
), "virtcon%d", i
);
6187 virtcon_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6188 if (!virtcon_hds
[i
]) {
6189 fprintf(stderr
, "qemu: could not open virtio console '%s'\n",
6196 module_call_init(MODULE_INIT_DEVICE
);
6201 machine
->init(ram_size
, boot_devices
,
6202 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
6205 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
6206 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6207 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
6213 current_machine
= machine
;
6215 /* Set KVM's vcpu state to qemu's initial CPUState. */
6216 if (kvm_enabled()) {
6219 ret
= kvm_sync_vcpus();
6221 fprintf(stderr
, "failed to initialize vcpus\n");
6226 /* init USB devices */
6228 for(i
= 0; i
< usb_devices_index
; i
++) {
6229 if (usb_device_add(usb_devices
[i
], 0) < 0) {
6230 fprintf(stderr
, "Warning: could not add USB device %s\n",
6237 dumb_display_init();
6238 /* just use the first displaystate for the moment */
6241 if (display_type
== DT_DEFAULT
) {
6242 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6243 display_type
= DT_SDL
;
6245 display_type
= DT_VNC
;
6246 vnc_display
= "localhost:0,to=99";
6252 switch (display_type
) {
6255 #if defined(CONFIG_CURSES)
6257 curses_display_init(ds
, full_screen
);
6260 #if defined(CONFIG_SDL)
6262 sdl_display_init(ds
, full_screen
, no_frame
);
6264 #elif defined(CONFIG_COCOA)
6266 cocoa_display_init(ds
, full_screen
);
6270 vnc_display_init(ds
);
6271 if (vnc_display_open(ds
, vnc_display
) < 0)
6274 if (show_vnc_port
) {
6275 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
6283 dcl
= ds
->listeners
;
6284 while (dcl
!= NULL
) {
6285 if (dcl
->dpy_refresh
!= NULL
) {
6286 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
6287 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
6292 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
6293 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
6294 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
6297 text_consoles_set_display(display_state
);
6298 qemu_chr_initial_reset();
6300 if (monitor_device
&& monitor_hd
)
6301 monitor_init(monitor_hd
, MONITOR_USE_READLINE
| MONITOR_IS_DEFAULT
);
6303 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6304 const char *devname
= serial_devices
[i
];
6305 if (devname
&& strcmp(devname
, "none")) {
6306 if (strstart(devname
, "vc", 0))
6307 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
6311 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
6312 const char *devname
= parallel_devices
[i
];
6313 if (devname
&& strcmp(devname
, "none")) {
6314 if (strstart(devname
, "vc", 0))
6315 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
6319 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
6320 const char *devname
= virtio_consoles
[i
];
6321 if (virtcon_hds
[i
] && devname
) {
6322 if (strstart(devname
, "vc", 0))
6323 qemu_chr_printf(virtcon_hds
[i
], "virtio console%d\r\n", i
);
6327 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
6328 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
6334 do_loadvm(cur_mon
, loadvm
);
6337 autostart
= 0; /* fixme how to deal with -daemonize */
6338 qemu_start_incoming_migration(incoming
);
6350 len
= write(fds
[1], &status
, 1);
6351 if (len
== -1 && (errno
== EINTR
))
6358 TFR(fd
= open("/dev/null", O_RDWR
));
6364 pwd
= getpwnam(run_as
);
6366 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
6372 if (chroot(chroot_dir
) < 0) {
6373 fprintf(stderr
, "chroot failed\n");
6380 if (setgid(pwd
->pw_gid
) < 0) {
6381 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
6384 if (setuid(pwd
->pw_uid
) < 0) {
6385 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
6388 if (setuid(0) != -1) {
6389 fprintf(stderr
, "Dropping privileges failed\n");