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)
118 int qemu_main(int argc
, char **argv
, char **envp
);
119 int main(int argc
, char **argv
)
121 qemu_main(argc
, argv
, NULL
);
124 #define main qemu_main
126 #endif /* CONFIG_SDL */
130 #define main qemu_main
131 #endif /* CONFIG_COCOA */
134 #include "hw/boards.h"
136 #include "hw/pcmcia.h"
138 #include "hw/audiodev.h"
142 #include "hw/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 #if defined(CONFIG_SLIRP)
171 #include "libslirp.h"
174 //#define DEBUG_UNUSED_IOPORT
175 //#define DEBUG_IOPORT
177 //#define DEBUG_SLIRP
181 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
183 # define LOG_IOPORT(...) do { } while (0)
186 #define DEFAULT_RAM_SIZE 128
188 /* Max number of USB devices that can be specified on the commandline. */
189 #define MAX_USB_CMDLINE 8
191 /* Max number of bluetooth switches on the commandline. */
192 #define MAX_BT_CMDLINE 10
194 /* XXX: use a two level table to limit memory usage */
195 #define MAX_IOPORTS 65536
197 static const char *data_dir
;
198 const char *bios_name
= NULL
;
199 static void *ioport_opaque
[MAX_IOPORTS
];
200 static IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
201 static IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
202 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
203 to store the VM snapshots */
204 DriveInfo drives_table
[MAX_DRIVES
+1];
206 int extboot_drive
= -1;
207 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
208 static DisplayState
*display_state
;
209 DisplayType display_type
= DT_DEFAULT
;
210 const char* keyboard_layout
= NULL
;
211 int64_t ticks_per_sec
;
214 NICInfo nd_table
[MAX_NICS
];
216 static int autostart
;
217 static int rtc_utc
= 1;
218 static int rtc_date_offset
= -1; /* -1 means no change */
219 int cirrus_vga_enabled
= 1;
220 int std_vga_enabled
= 0;
221 int vmsvga_enabled
= 0;
222 int xenfb_enabled
= 0;
224 int graphic_width
= 1024;
225 int graphic_height
= 768;
226 int graphic_depth
= 8;
228 int graphic_width
= 800;
229 int graphic_height
= 600;
230 int graphic_depth
= 15;
232 static int full_screen
= 0;
234 static int no_frame
= 0;
237 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
238 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
239 CharDriverState
*virtcon_hds
[MAX_VIRTIO_CONSOLES
];
241 int win2k_install_hack
= 0;
246 const char *assigned_devices
[MAX_DEV_ASSIGN_CMDLINE
];
247 int assigned_devices_index
;
249 const char *vnc_display
;
250 int acpi_enabled
= 1;
256 int graphic_rotate
= 0;
260 WatchdogTimerModel
*watchdog
= NULL
;
261 int watchdog_action
= WDT_RESET
;
262 const char *option_rom
[MAX_OPTION_ROMS
];
264 int semihosting_enabled
= 0;
265 int time_drift_fix
= 0;
266 unsigned int kvm_shadow_memory
= 0;
267 const char *mem_path
= NULL
;
269 int mem_prealloc
= 1; /* force preallocation of physical target memory */
274 const char *qemu_name
;
276 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
277 unsigned int nb_prom_envs
= 0;
278 const char *prom_envs
[MAX_PROM_ENVS
];
281 const char *nvram
= NULL
;
282 struct drive_opt drives_opt
[MAX_DRIVES
];
285 uint64_t node_mem
[MAX_NODES
];
286 uint64_t node_cpumask
[MAX_NODES
];
288 static CPUState
*cur_cpu
;
289 static CPUState
*next_cpu
;
290 static int timer_alarm_pending
= 1;
291 /* Conversion factor from emulated instructions to virtual clock ticks. */
292 static int icount_time_shift
;
293 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
294 #define MAX_ICOUNT_SHIFT 10
295 /* Compensate for varying guest execution speed. */
296 static int64_t qemu_icount_bias
;
297 static QEMUTimer
*icount_rt_timer
;
298 static QEMUTimer
*icount_vm_timer
;
299 static QEMUTimer
*nographic_timer
;
301 uint8_t qemu_uuid
[16];
303 static int qemu_select(int max_fd
, fd_set
*rfds
, fd_set
*wfds
, fd_set
*xfds
,
308 /* KVM holds a mutex while QEMU code is running, we need hooks to
309 release the mutex whenever QEMU code sleeps. */
313 ret
= select(max_fd
, rfds
, wfds
, xfds
, tv
);
321 /***********************************************************/
322 /* x86 ISA bus support */
324 target_phys_addr_t isa_mem_base
= 0;
327 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
328 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
330 static uint32_t ioport_read(int index
, uint32_t address
)
332 static IOPortReadFunc
*default_func
[3] = {
333 default_ioport_readb
,
334 default_ioport_readw
,
337 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
339 func
= default_func
[index
];
340 return func(ioport_opaque
[address
], address
);
343 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
345 static IOPortWriteFunc
*default_func
[3] = {
346 default_ioport_writeb
,
347 default_ioport_writew
,
348 default_ioport_writel
350 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
352 func
= default_func
[index
];
353 func(ioport_opaque
[address
], address
, data
);
356 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
358 #ifdef DEBUG_UNUSED_IOPORT
359 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
364 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
366 #ifdef DEBUG_UNUSED_IOPORT
367 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
371 /* default is to make two byte accesses */
372 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
375 data
= ioport_read(0, address
);
376 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
377 data
|= ioport_read(0, address
) << 8;
381 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
383 ioport_write(0, address
, data
& 0xff);
384 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
385 ioport_write(0, address
, (data
>> 8) & 0xff);
388 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
390 #ifdef DEBUG_UNUSED_IOPORT
391 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
396 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
398 #ifdef DEBUG_UNUSED_IOPORT
399 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
403 /* size is the word size in byte */
404 int register_ioport_read(int start
, int length
, int size
,
405 IOPortReadFunc
*func
, void *opaque
)
411 } else if (size
== 2) {
413 } else if (size
== 4) {
416 hw_error("register_ioport_read: invalid size");
419 for(i
= start
; i
< start
+ length
; i
+= size
) {
420 ioport_read_table
[bsize
][i
] = func
;
421 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
422 hw_error("register_ioport_read: invalid opaque");
423 ioport_opaque
[i
] = opaque
;
428 /* size is the word size in byte */
429 int register_ioport_write(int start
, int length
, int size
,
430 IOPortWriteFunc
*func
, void *opaque
)
436 } else if (size
== 2) {
438 } else if (size
== 4) {
441 hw_error("register_ioport_write: invalid size");
444 for(i
= start
; i
< start
+ length
; i
+= size
) {
445 ioport_write_table
[bsize
][i
] = func
;
446 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
447 hw_error("register_ioport_write: invalid opaque");
448 ioport_opaque
[i
] = opaque
;
453 void isa_unassign_ioport(int start
, int length
)
457 for(i
= start
; i
< start
+ length
; i
++) {
458 ioport_read_table
[0][i
] = default_ioport_readb
;
459 ioport_read_table
[1][i
] = default_ioport_readw
;
460 ioport_read_table
[2][i
] = default_ioport_readl
;
462 ioport_write_table
[0][i
] = default_ioport_writeb
;
463 ioport_write_table
[1][i
] = default_ioport_writew
;
464 ioport_write_table
[2][i
] = default_ioport_writel
;
466 ioport_opaque
[i
] = NULL
;
470 /***********************************************************/
472 void cpu_outb(CPUState
*env
, int addr
, int val
)
474 LOG_IOPORT("outb: %04x %02x\n", addr
, val
);
475 ioport_write(0, addr
, val
);
478 env
->last_io_time
= cpu_get_time_fast();
482 void cpu_outw(CPUState
*env
, int addr
, int val
)
484 LOG_IOPORT("outw: %04x %04x\n", addr
, val
);
485 ioport_write(1, addr
, val
);
488 env
->last_io_time
= cpu_get_time_fast();
492 void cpu_outl(CPUState
*env
, int addr
, int val
)
494 LOG_IOPORT("outl: %04x %08x\n", addr
, val
);
495 ioport_write(2, addr
, val
);
498 env
->last_io_time
= cpu_get_time_fast();
502 int cpu_inb(CPUState
*env
, int addr
)
505 val
= ioport_read(0, addr
);
506 LOG_IOPORT("inb : %04x %02x\n", addr
, val
);
509 env
->last_io_time
= cpu_get_time_fast();
514 int cpu_inw(CPUState
*env
, int addr
)
517 val
= ioport_read(1, addr
);
518 LOG_IOPORT("inw : %04x %04x\n", addr
, val
);
521 env
->last_io_time
= cpu_get_time_fast();
526 int cpu_inl(CPUState
*env
, int addr
)
529 val
= ioport_read(2, addr
);
530 LOG_IOPORT("inl : %04x %08x\n", addr
, val
);
533 env
->last_io_time
= cpu_get_time_fast();
538 /***********************************************************/
539 void hw_error(const char *fmt
, ...)
545 fprintf(stderr
, "qemu: hardware error: ");
546 vfprintf(stderr
, fmt
, ap
);
547 fprintf(stderr
, "\n");
548 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
549 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
551 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
553 cpu_dump_state(env
, stderr
, fprintf
, 0);
563 static QEMUBalloonEvent
*qemu_balloon_event
;
564 void *qemu_balloon_event_opaque
;
566 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
568 qemu_balloon_event
= func
;
569 qemu_balloon_event_opaque
= opaque
;
572 void qemu_balloon(ram_addr_t target
)
574 if (qemu_balloon_event
)
575 qemu_balloon_event(qemu_balloon_event_opaque
, target
);
578 ram_addr_t
qemu_balloon_status(void)
580 if (qemu_balloon_event
)
581 return qemu_balloon_event(qemu_balloon_event_opaque
, 0);
585 /***********************************************************/
588 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
589 static void *qemu_put_kbd_event_opaque
;
590 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
591 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
593 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
595 qemu_put_kbd_event_opaque
= opaque
;
596 qemu_put_kbd_event
= func
;
599 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
600 void *opaque
, int absolute
,
603 QEMUPutMouseEntry
*s
, *cursor
;
605 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
607 s
->qemu_put_mouse_event
= func
;
608 s
->qemu_put_mouse_event_opaque
= opaque
;
609 s
->qemu_put_mouse_event_absolute
= absolute
;
610 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
613 if (!qemu_put_mouse_event_head
) {
614 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
618 cursor
= qemu_put_mouse_event_head
;
619 while (cursor
->next
!= NULL
)
620 cursor
= cursor
->next
;
623 qemu_put_mouse_event_current
= s
;
628 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
630 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
632 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
635 cursor
= qemu_put_mouse_event_head
;
636 while (cursor
!= NULL
&& cursor
!= entry
) {
638 cursor
= cursor
->next
;
641 if (cursor
== NULL
) // does not exist or list empty
643 else if (prev
== NULL
) { // entry is head
644 qemu_put_mouse_event_head
= cursor
->next
;
645 if (qemu_put_mouse_event_current
== entry
)
646 qemu_put_mouse_event_current
= cursor
->next
;
647 qemu_free(entry
->qemu_put_mouse_event_name
);
652 prev
->next
= entry
->next
;
654 if (qemu_put_mouse_event_current
== entry
)
655 qemu_put_mouse_event_current
= prev
;
657 qemu_free(entry
->qemu_put_mouse_event_name
);
661 void kbd_put_keycode(int keycode
)
663 if (qemu_put_kbd_event
) {
664 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
668 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
670 QEMUPutMouseEvent
*mouse_event
;
671 void *mouse_event_opaque
;
674 if (!qemu_put_mouse_event_current
) {
679 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
681 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
684 if (graphic_rotate
) {
685 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
688 width
= graphic_width
- 1;
689 mouse_event(mouse_event_opaque
,
690 width
- dy
, dx
, dz
, buttons_state
);
692 mouse_event(mouse_event_opaque
,
693 dx
, dy
, dz
, buttons_state
);
697 int kbd_mouse_is_absolute(void)
699 if (!qemu_put_mouse_event_current
)
702 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
705 void do_info_mice(Monitor
*mon
)
707 QEMUPutMouseEntry
*cursor
;
710 if (!qemu_put_mouse_event_head
) {
711 monitor_printf(mon
, "No mouse devices connected\n");
715 monitor_printf(mon
, "Mouse devices available:\n");
716 cursor
= qemu_put_mouse_event_head
;
717 while (cursor
!= NULL
) {
718 monitor_printf(mon
, "%c Mouse #%d: %s\n",
719 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
720 index
, cursor
->qemu_put_mouse_event_name
);
722 cursor
= cursor
->next
;
726 void do_mouse_set(Monitor
*mon
, int index
)
728 QEMUPutMouseEntry
*cursor
;
731 if (!qemu_put_mouse_event_head
) {
732 monitor_printf(mon
, "No mouse devices connected\n");
736 cursor
= qemu_put_mouse_event_head
;
737 while (cursor
!= NULL
&& index
!= i
) {
739 cursor
= cursor
->next
;
743 qemu_put_mouse_event_current
= cursor
;
745 monitor_printf(mon
, "Mouse at given index not found\n");
748 /* compute with 96 bit intermediate result: (a*b)/c */
749 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
754 #ifdef WORDS_BIGENDIAN
764 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
765 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
768 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
772 /***********************************************************/
773 /* real time host monotonic timer */
775 #define QEMU_TIMER_BASE 1000000000LL
779 static int64_t clock_freq
;
781 static void init_get_clock(void)
785 ret
= QueryPerformanceFrequency(&freq
);
787 fprintf(stderr
, "Could not calibrate ticks\n");
790 clock_freq
= freq
.QuadPart
;
793 static int64_t get_clock(void)
796 QueryPerformanceCounter(&ti
);
797 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
802 static int use_rt_clock
;
804 static void init_get_clock(void)
807 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
808 || defined(__DragonFly__)
811 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
818 static int64_t get_clock(void)
820 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
821 || defined(__DragonFly__)
824 clock_gettime(CLOCK_MONOTONIC
, &ts
);
825 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
829 /* XXX: using gettimeofday leads to problems if the date
830 changes, so it should be avoided. */
832 gettimeofday(&tv
, NULL
);
833 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
838 /* Return the virtual CPU time, based on the instruction counter. */
839 static int64_t cpu_get_icount(void)
842 CPUState
*env
= cpu_single_env
;;
843 icount
= qemu_icount
;
846 fprintf(stderr
, "Bad clock read\n");
847 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
849 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
852 /***********************************************************/
853 /* guest cycle counter */
855 static int64_t cpu_ticks_prev
;
856 static int64_t cpu_ticks_offset
;
857 static int64_t cpu_clock_offset
;
858 static int cpu_ticks_enabled
;
860 /* return the host CPU cycle counter and handle stop/restart */
861 int64_t cpu_get_ticks(void)
864 return cpu_get_icount();
866 if (!cpu_ticks_enabled
) {
867 return cpu_ticks_offset
;
870 ticks
= cpu_get_real_ticks();
871 if (cpu_ticks_prev
> ticks
) {
872 /* Note: non increasing ticks may happen if the host uses
874 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
876 cpu_ticks_prev
= ticks
;
877 return ticks
+ cpu_ticks_offset
;
881 /* return the host CPU monotonic timer and handle stop/restart */
882 static int64_t cpu_get_clock(void)
885 if (!cpu_ticks_enabled
) {
886 return cpu_clock_offset
;
889 return ti
+ cpu_clock_offset
;
893 /* enable cpu_get_ticks() */
894 void cpu_enable_ticks(void)
896 if (!cpu_ticks_enabled
) {
897 cpu_ticks_offset
-= cpu_get_real_ticks();
898 cpu_clock_offset
-= get_clock();
899 cpu_ticks_enabled
= 1;
903 /* disable cpu_get_ticks() : the clock is stopped. You must not call
904 cpu_get_ticks() after that. */
905 void cpu_disable_ticks(void)
907 if (cpu_ticks_enabled
) {
908 cpu_ticks_offset
= cpu_get_ticks();
909 cpu_clock_offset
= cpu_get_clock();
910 cpu_ticks_enabled
= 0;
914 /***********************************************************/
917 #define QEMU_TIMER_REALTIME 0
918 #define QEMU_TIMER_VIRTUAL 1
922 /* XXX: add frequency */
930 struct QEMUTimer
*next
;
933 struct qemu_alarm_timer
{
937 int (*start
)(struct qemu_alarm_timer
*t
);
938 void (*stop
)(struct qemu_alarm_timer
*t
);
939 void (*rearm
)(struct qemu_alarm_timer
*t
);
943 #define ALARM_FLAG_DYNTICKS 0x1
944 #define ALARM_FLAG_EXPIRED 0x2
946 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
948 return t
&& (t
->flags
& ALARM_FLAG_DYNTICKS
);
951 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
953 if (!alarm_has_dynticks(t
))
959 /* TODO: MIN_TIMER_REARM_US should be optimized */
960 #define MIN_TIMER_REARM_US 250
962 static struct qemu_alarm_timer
*alarm_timer
;
966 struct qemu_alarm_win32
{
969 } alarm_win32_data
= {0, -1};
971 static int win32_start_timer(struct qemu_alarm_timer
*t
);
972 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
973 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
977 static int unix_start_timer(struct qemu_alarm_timer
*t
);
978 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
982 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
983 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
984 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
986 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
987 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
989 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
990 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
992 #endif /* __linux__ */
996 /* Correlation between real and virtual time is always going to be
997 fairly approximate, so ignore small variation.
998 When the guest is idle real and virtual time will be aligned in
1000 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
1002 static void icount_adjust(void)
1007 static int64_t last_delta
;
1008 /* If the VM is not running, then do nothing. */
1012 cur_time
= cpu_get_clock();
1013 cur_icount
= qemu_get_clock(vm_clock
);
1014 delta
= cur_icount
- cur_time
;
1015 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1017 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
1018 && icount_time_shift
> 0) {
1019 /* The guest is getting too far ahead. Slow time down. */
1020 icount_time_shift
--;
1023 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
1024 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
1025 /* The guest is getting too far behind. Speed time up. */
1026 icount_time_shift
++;
1029 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
1032 static void icount_adjust_rt(void * opaque
)
1034 qemu_mod_timer(icount_rt_timer
,
1035 qemu_get_clock(rt_clock
) + 1000);
1039 static void icount_adjust_vm(void * opaque
)
1041 qemu_mod_timer(icount_vm_timer
,
1042 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1046 static void init_icount_adjust(void)
1048 /* Have both realtime and virtual time triggers for speed adjustment.
1049 The realtime trigger catches emulated time passing too slowly,
1050 the virtual time trigger catches emulated time passing too fast.
1051 Realtime triggers occur even when idle, so use them less frequently
1052 than VM triggers. */
1053 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
1054 qemu_mod_timer(icount_rt_timer
,
1055 qemu_get_clock(rt_clock
) + 1000);
1056 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
1057 qemu_mod_timer(icount_vm_timer
,
1058 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1061 static struct qemu_alarm_timer alarm_timers
[] = {
1064 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
1065 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
1066 /* HPET - if available - is preferred */
1067 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
1068 /* ...otherwise try RTC */
1069 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1071 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1073 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1074 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1075 {"win32", 0, win32_start_timer
,
1076 win32_stop_timer
, NULL
, &alarm_win32_data
},
1081 static void show_available_alarms(void)
1085 printf("Available alarm timers, in order of precedence:\n");
1086 for (i
= 0; alarm_timers
[i
].name
; i
++)
1087 printf("%s\n", alarm_timers
[i
].name
);
1090 static void configure_alarms(char const *opt
)
1094 int count
= ARRAY_SIZE(alarm_timers
) - 1;
1097 struct qemu_alarm_timer tmp
;
1099 if (!strcmp(opt
, "?")) {
1100 show_available_alarms();
1106 /* Reorder the array */
1107 name
= strtok(arg
, ",");
1109 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1110 if (!strcmp(alarm_timers
[i
].name
, name
))
1115 fprintf(stderr
, "Unknown clock %s\n", name
);
1124 tmp
= alarm_timers
[i
];
1125 alarm_timers
[i
] = alarm_timers
[cur
];
1126 alarm_timers
[cur
] = tmp
;
1130 name
= strtok(NULL
, ",");
1136 /* Disable remaining timers */
1137 for (i
= cur
; i
< count
; i
++)
1138 alarm_timers
[i
].name
= NULL
;
1140 show_available_alarms();
1145 QEMUClock
*rt_clock
;
1146 QEMUClock
*vm_clock
;
1148 static QEMUTimer
*active_timers
[2];
1150 static QEMUClock
*qemu_new_clock(int type
)
1153 clock
= qemu_mallocz(sizeof(QEMUClock
));
1158 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1162 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1165 ts
->opaque
= opaque
;
1169 void qemu_free_timer(QEMUTimer
*ts
)
1174 /* stop a timer, but do not dealloc it */
1175 void qemu_del_timer(QEMUTimer
*ts
)
1179 /* NOTE: this code must be signal safe because
1180 qemu_timer_expired() can be called from a signal. */
1181 pt
= &active_timers
[ts
->clock
->type
];
1194 /* modify the current timer so that it will be fired when current_time
1195 >= expire_time. The corresponding callback will be called. */
1196 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1202 /* add the timer in the sorted list */
1203 /* NOTE: this code must be signal safe because
1204 qemu_timer_expired() can be called from a signal. */
1205 pt
= &active_timers
[ts
->clock
->type
];
1210 if (t
->expire_time
> expire_time
)
1214 ts
->expire_time
= expire_time
;
1218 /* Rearm if necessary */
1219 if (pt
== &active_timers
[ts
->clock
->type
]) {
1220 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1221 qemu_rearm_alarm_timer(alarm_timer
);
1223 /* Interrupt execution to force deadline recalculation. */
1225 qemu_notify_event();
1229 int qemu_timer_pending(QEMUTimer
*ts
)
1232 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1239 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1243 return (timer_head
->expire_time
<= current_time
);
1246 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1252 if (!ts
|| ts
->expire_time
> current_time
)
1254 /* remove timer from the list before calling the callback */
1255 *ptimer_head
= ts
->next
;
1258 /* run the callback (the timer list can be modified) */
1263 int64_t qemu_get_clock(QEMUClock
*clock
)
1265 switch(clock
->type
) {
1266 case QEMU_TIMER_REALTIME
:
1267 return get_clock() / 1000000;
1269 case QEMU_TIMER_VIRTUAL
:
1271 return cpu_get_icount();
1273 return cpu_get_clock();
1278 static void init_timers(void)
1281 ticks_per_sec
= QEMU_TIMER_BASE
;
1282 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1283 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1287 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1289 uint64_t expire_time
;
1291 if (qemu_timer_pending(ts
)) {
1292 expire_time
= ts
->expire_time
;
1296 qemu_put_be64(f
, expire_time
);
1299 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1301 uint64_t expire_time
;
1303 expire_time
= qemu_get_be64(f
);
1304 if (expire_time
!= -1) {
1305 qemu_mod_timer(ts
, expire_time
);
1311 static void timer_save(QEMUFile
*f
, void *opaque
)
1313 if (cpu_ticks_enabled
) {
1314 hw_error("cannot save state if virtual timers are running");
1316 qemu_put_be64(f
, cpu_ticks_offset
);
1317 qemu_put_be64(f
, ticks_per_sec
);
1318 qemu_put_be64(f
, cpu_clock_offset
);
1321 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1323 if (version_id
!= 1 && version_id
!= 2)
1325 if (cpu_ticks_enabled
) {
1328 cpu_ticks_offset
=qemu_get_be64(f
);
1329 ticks_per_sec
=qemu_get_be64(f
);
1330 if (version_id
== 2) {
1331 cpu_clock_offset
=qemu_get_be64(f
);
1336 static void qemu_event_increment(void);
1339 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1340 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1343 static void host_alarm_handler(int host_signum
)
1347 #define DISP_FREQ 1000
1349 static int64_t delta_min
= INT64_MAX
;
1350 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1352 ti
= qemu_get_clock(vm_clock
);
1353 if (last_clock
!= 0) {
1354 delta
= ti
- last_clock
;
1355 if (delta
< delta_min
)
1357 if (delta
> delta_max
)
1360 if (++count
== DISP_FREQ
) {
1361 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1362 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1363 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1364 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1365 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1367 delta_min
= INT64_MAX
;
1375 if (alarm_has_dynticks(alarm_timer
) ||
1377 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1378 qemu_get_clock(vm_clock
))) ||
1379 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1380 qemu_get_clock(rt_clock
))) {
1381 qemu_event_increment();
1382 if (alarm_timer
) alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1384 #ifndef CONFIG_IOTHREAD
1386 /* stop the currently executing cpu because a timer occured */
1389 if (next_cpu
->kqemu_enabled
) {
1390 kqemu_cpu_interrupt(next_cpu
);
1395 timer_alarm_pending
= 1;
1396 qemu_notify_event();
1400 static int64_t qemu_next_deadline(void)
1404 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1405 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1406 qemu_get_clock(vm_clock
);
1408 /* To avoid problems with overflow limit this to 2^32. */
1418 #if defined(__linux__) || defined(_WIN32)
1419 static uint64_t qemu_next_deadline_dyntick(void)
1427 delta
= (qemu_next_deadline() + 999) / 1000;
1429 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1430 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1431 qemu_get_clock(rt_clock
))*1000;
1432 if (rtdelta
< delta
)
1436 if (delta
< MIN_TIMER_REARM_US
)
1437 delta
= MIN_TIMER_REARM_US
;
1445 /* Sets a specific flag */
1446 static int fcntl_setfl(int fd
, int flag
)
1450 flags
= fcntl(fd
, F_GETFL
);
1454 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1460 #if defined(__linux__)
1462 #define RTC_FREQ 1024
1464 static void enable_sigio_timer(int fd
)
1466 struct sigaction act
;
1469 sigfillset(&act
.sa_mask
);
1471 act
.sa_handler
= host_alarm_handler
;
1473 sigaction(SIGIO
, &act
, NULL
);
1474 fcntl_setfl(fd
, O_ASYNC
);
1475 fcntl(fd
, F_SETOWN
, getpid());
1478 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1480 struct hpet_info info
;
1483 fd
= open("/dev/hpet", O_RDONLY
);
1488 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1490 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1491 "error, but for better emulation accuracy type:\n"
1492 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1496 /* Check capabilities */
1497 r
= ioctl(fd
, HPET_INFO
, &info
);
1501 /* Enable periodic mode */
1502 r
= ioctl(fd
, HPET_EPI
, 0);
1503 if (info
.hi_flags
&& (r
< 0))
1506 /* Enable interrupt */
1507 r
= ioctl(fd
, HPET_IE_ON
, 0);
1511 enable_sigio_timer(fd
);
1512 t
->priv
= (void *)(long)fd
;
1520 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1522 int fd
= (long)t
->priv
;
1527 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1530 unsigned long current_rtc_freq
= 0;
1532 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1535 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1536 if (current_rtc_freq
!= RTC_FREQ
&&
1537 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1538 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1539 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1540 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1543 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1549 enable_sigio_timer(rtc_fd
);
1551 t
->priv
= (void *)(long)rtc_fd
;
1556 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1558 int rtc_fd
= (long)t
->priv
;
1563 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1567 struct sigaction act
;
1569 sigfillset(&act
.sa_mask
);
1571 act
.sa_handler
= host_alarm_handler
;
1573 sigaction(SIGALRM
, &act
, NULL
);
1576 * Initialize ev struct to 0 to avoid valgrind complaining
1577 * about uninitialized data in timer_create call
1579 memset(&ev
, 0, sizeof(ev
));
1580 ev
.sigev_value
.sival_int
= 0;
1581 ev
.sigev_notify
= SIGEV_SIGNAL
;
1582 ev
.sigev_signo
= SIGALRM
;
1584 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1585 perror("timer_create");
1587 /* disable dynticks */
1588 fprintf(stderr
, "Dynamic Ticks disabled\n");
1593 t
->priv
= (void *)(long)host_timer
;
1598 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1600 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1602 timer_delete(host_timer
);
1605 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1607 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1608 struct itimerspec timeout
;
1609 int64_t nearest_delta_us
= INT64_MAX
;
1612 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1613 !active_timers
[QEMU_TIMER_VIRTUAL
])
1616 nearest_delta_us
= qemu_next_deadline_dyntick();
1618 /* check whether a timer is already running */
1619 if (timer_gettime(host_timer
, &timeout
)) {
1621 fprintf(stderr
, "Internal timer error: aborting\n");
1624 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1625 if (current_us
&& current_us
<= nearest_delta_us
)
1628 timeout
.it_interval
.tv_sec
= 0;
1629 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1630 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1631 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1632 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1634 fprintf(stderr
, "Internal timer error: aborting\n");
1639 #endif /* defined(__linux__) */
1641 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1643 struct sigaction act
;
1644 struct itimerval itv
;
1648 sigfillset(&act
.sa_mask
);
1650 act
.sa_handler
= host_alarm_handler
;
1652 sigaction(SIGALRM
, &act
, NULL
);
1654 itv
.it_interval
.tv_sec
= 0;
1655 /* for i386 kernel 2.6 to get 1 ms */
1656 itv
.it_interval
.tv_usec
= 999;
1657 itv
.it_value
.tv_sec
= 0;
1658 itv
.it_value
.tv_usec
= 10 * 1000;
1660 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1667 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1669 struct itimerval itv
;
1671 memset(&itv
, 0, sizeof(itv
));
1672 setitimer(ITIMER_REAL
, &itv
, NULL
);
1675 #endif /* !defined(_WIN32) */
1680 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1683 struct qemu_alarm_win32
*data
= t
->priv
;
1686 memset(&tc
, 0, sizeof(tc
));
1687 timeGetDevCaps(&tc
, sizeof(tc
));
1689 if (data
->period
< tc
.wPeriodMin
)
1690 data
->period
= tc
.wPeriodMin
;
1692 timeBeginPeriod(data
->period
);
1694 flags
= TIME_CALLBACK_FUNCTION
;
1695 if (alarm_has_dynticks(t
))
1696 flags
|= TIME_ONESHOT
;
1698 flags
|= TIME_PERIODIC
;
1700 data
->timerId
= timeSetEvent(1, // interval (ms)
1701 data
->period
, // resolution
1702 host_alarm_handler
, // function
1703 (DWORD
)t
, // parameter
1706 if (!data
->timerId
) {
1707 perror("Failed to initialize win32 alarm timer");
1708 timeEndPeriod(data
->period
);
1715 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1717 struct qemu_alarm_win32
*data
= t
->priv
;
1719 timeKillEvent(data
->timerId
);
1720 timeEndPeriod(data
->period
);
1723 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1725 struct qemu_alarm_win32
*data
= t
->priv
;
1726 uint64_t nearest_delta_us
;
1728 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1729 !active_timers
[QEMU_TIMER_VIRTUAL
])
1732 nearest_delta_us
= qemu_next_deadline_dyntick();
1733 nearest_delta_us
/= 1000;
1735 timeKillEvent(data
->timerId
);
1737 data
->timerId
= timeSetEvent(1,
1741 TIME_ONESHOT
| TIME_PERIODIC
);
1743 if (!data
->timerId
) {
1744 perror("Failed to re-arm win32 alarm timer");
1746 timeEndPeriod(data
->period
);
1753 static int init_timer_alarm(void)
1755 struct qemu_alarm_timer
*t
= NULL
;
1758 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1759 t
= &alarm_timers
[i
];
1779 static void quit_timers(void)
1781 alarm_timer
->stop(alarm_timer
);
1785 /***********************************************************/
1786 /* host time/date access */
1787 void qemu_get_timedate(struct tm
*tm
, int offset
)
1794 if (rtc_date_offset
== -1) {
1798 ret
= localtime(&ti
);
1800 ti
-= rtc_date_offset
;
1804 memcpy(tm
, ret
, sizeof(struct tm
));
1807 int qemu_timedate_diff(struct tm
*tm
)
1811 if (rtc_date_offset
== -1)
1813 seconds
= mktimegm(tm
);
1815 seconds
= mktime(tm
);
1817 seconds
= mktimegm(tm
) + rtc_date_offset
;
1819 return seconds
- time(NULL
);
1823 static void socket_cleanup(void)
1828 static int socket_init(void)
1833 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1835 err
= WSAGetLastError();
1836 fprintf(stderr
, "WSAStartup: %d\n", err
);
1839 atexit(socket_cleanup
);
1844 int get_param_value(char *buf
, int buf_size
,
1845 const char *tag
, const char *str
)
1852 p
= get_opt_name(option
, sizeof(option
), p
, '=');
1856 if (!strcmp(tag
, option
)) {
1857 (void)get_opt_value(buf
, buf_size
, p
);
1860 p
= get_opt_value(NULL
, 0, p
);
1869 int check_params(char *buf
, int buf_size
,
1870 const char * const *params
, const char *str
)
1876 while (*p
!= '\0') {
1877 p
= get_opt_name(buf
, buf_size
, p
, '=');
1882 for (i
= 0; params
[i
] != NULL
; i
++) {
1883 if (!strcmp(params
[i
], buf
)) {
1887 if (params
[i
] == NULL
) {
1890 p
= get_opt_value(NULL
, 0, p
);
1899 /***********************************************************/
1900 /* Bluetooth support */
1903 static struct HCIInfo
*hci_table
[MAX_NICS
];
1905 static struct bt_vlan_s
{
1906 struct bt_scatternet_s net
;
1908 struct bt_vlan_s
*next
;
1911 /* find or alloc a new bluetooth "VLAN" */
1912 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1914 struct bt_vlan_s
**pvlan
, *vlan
;
1915 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1919 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1921 pvlan
= &first_bt_vlan
;
1922 while (*pvlan
!= NULL
)
1923 pvlan
= &(*pvlan
)->next
;
1928 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1932 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1937 static struct HCIInfo null_hci
= {
1938 .cmd_send
= null_hci_send
,
1939 .sco_send
= null_hci_send
,
1940 .acl_send
= null_hci_send
,
1941 .bdaddr_set
= null_hci_addr_set
,
1944 struct HCIInfo
*qemu_next_hci(void)
1946 if (cur_hci
== nb_hcis
)
1949 return hci_table
[cur_hci
++];
1952 static struct HCIInfo
*hci_init(const char *str
)
1955 struct bt_scatternet_s
*vlan
= 0;
1957 if (!strcmp(str
, "null"))
1960 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
1962 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
1963 else if (!strncmp(str
, "hci", 3)) {
1966 if (!strncmp(str
+ 3, ",vlan=", 6)) {
1967 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
1972 vlan
= qemu_find_bt_vlan(0);
1974 return bt_new_hci(vlan
);
1977 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
1982 static int bt_hci_parse(const char *str
)
1984 struct HCIInfo
*hci
;
1987 if (nb_hcis
>= MAX_NICS
) {
1988 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
1992 hci
= hci_init(str
);
2001 bdaddr
.b
[5] = 0x56 + nb_hcis
;
2002 hci
->bdaddr_set(hci
, bdaddr
.b
);
2004 hci_table
[nb_hcis
++] = hci
;
2009 static void bt_vhci_add(int vlan_id
)
2011 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
2014 fprintf(stderr
, "qemu: warning: adding a VHCI to "
2015 "an empty scatternet %i\n", vlan_id
);
2017 bt_vhci_init(bt_new_hci(vlan
));
2020 static struct bt_device_s
*bt_device_add(const char *opt
)
2022 struct bt_scatternet_s
*vlan
;
2024 char *endp
= strstr(opt
, ",vlan=");
2025 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
2028 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
2031 vlan_id
= strtol(endp
+ 6, &endp
, 0);
2033 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
2038 vlan
= qemu_find_bt_vlan(vlan_id
);
2041 fprintf(stderr
, "qemu: warning: adding a slave device to "
2042 "an empty scatternet %i\n", vlan_id
);
2044 if (!strcmp(devname
, "keyboard"))
2045 return bt_keyboard_init(vlan
);
2047 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
2051 static int bt_parse(const char *opt
)
2053 const char *endp
, *p
;
2056 if (strstart(opt
, "hci", &endp
)) {
2057 if (!*endp
|| *endp
== ',') {
2059 if (!strstart(endp
, ",vlan=", 0))
2062 return bt_hci_parse(opt
);
2064 } else if (strstart(opt
, "vhci", &endp
)) {
2065 if (!*endp
|| *endp
== ',') {
2067 if (strstart(endp
, ",vlan=", &p
)) {
2068 vlan
= strtol(p
, (char **) &endp
, 0);
2070 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
2074 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
2083 } else if (strstart(opt
, "device:", &endp
))
2084 return !bt_device_add(endp
);
2086 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
2090 /***********************************************************/
2091 /* QEMU Block devices */
2093 #define HD_ALIAS "index=%d,media=disk"
2094 #define CDROM_ALIAS "index=2,media=cdrom"
2095 #define FD_ALIAS "index=%d,if=floppy"
2096 #define PFLASH_ALIAS "if=pflash"
2097 #define MTD_ALIAS "if=mtd"
2098 #define SD_ALIAS "index=0,if=sd"
2100 static int drive_opt_get_free_idx(void)
2104 for (index
= 0; index
< MAX_DRIVES
; index
++)
2105 if (!drives_opt
[index
].used
) {
2106 drives_opt
[index
].used
= 1;
2113 static int drive_get_free_idx(void)
2117 for (index
= 0; index
< MAX_DRIVES
; index
++)
2118 if (!drives_table
[index
].used
) {
2119 drives_table
[index
].used
= 1;
2126 int drive_add(const char *file
, const char *fmt
, ...)
2129 int index
= drive_opt_get_free_idx();
2131 if (nb_drives_opt
>= MAX_DRIVES
|| index
== -1) {
2132 fprintf(stderr
, "qemu: too many drives\n");
2136 drives_opt
[index
].file
= file
;
2138 vsnprintf(drives_opt
[index
].opt
,
2139 sizeof(drives_opt
[0].opt
), fmt
, ap
);
2146 void drive_remove(int index
)
2148 drives_opt
[index
].used
= 0;
2152 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
2156 /* seek interface, bus and unit */
2158 for (index
= 0; index
< MAX_DRIVES
; index
++)
2159 if (drives_table
[index
].type
== type
&&
2160 drives_table
[index
].bus
== bus
&&
2161 drives_table
[index
].unit
== unit
&&
2162 drives_table
[index
].used
)
2168 int drive_get_max_bus(BlockInterfaceType type
)
2174 for (index
= 0; index
< nb_drives
; index
++) {
2175 if(drives_table
[index
].type
== type
&&
2176 drives_table
[index
].bus
> max_bus
)
2177 max_bus
= drives_table
[index
].bus
;
2182 const char *drive_get_serial(BlockDriverState
*bdrv
)
2186 for (index
= 0; index
< nb_drives
; index
++)
2187 if (drives_table
[index
].bdrv
== bdrv
)
2188 return drives_table
[index
].serial
;
2193 BlockInterfaceErrorAction
drive_get_onerror(BlockDriverState
*bdrv
)
2197 for (index
= 0; index
< nb_drives
; index
++)
2198 if (drives_table
[index
].bdrv
== bdrv
)
2199 return drives_table
[index
].onerror
;
2201 return BLOCK_ERR_STOP_ENOSPC
;
2204 static void bdrv_format_print(void *opaque
, const char *name
)
2206 fprintf(stderr
, " %s", name
);
2209 void drive_uninit(BlockDriverState
*bdrv
)
2213 for (i
= 0; i
< MAX_DRIVES
; i
++)
2214 if (drives_table
[i
].bdrv
== bdrv
) {
2215 drives_table
[i
].bdrv
= NULL
;
2216 drives_table
[i
].used
= 0;
2217 drive_remove(drives_table
[i
].drive_opt_idx
);
2223 int drive_init(struct drive_opt
*arg
, int snapshot
, void *opaque
)
2229 const char *mediastr
= "";
2230 BlockInterfaceType type
;
2231 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
2232 int bus_id
, unit_id
;
2233 int cyls
, heads
, secs
, translation
;
2234 BlockDriverState
*bdrv
;
2235 BlockDriver
*drv
= NULL
;
2236 QEMUMachine
*machine
= opaque
;
2240 int bdrv_flags
, onerror
;
2241 int drives_table_idx
;
2242 char *str
= arg
->opt
;
2243 static const char * const params
[] = { "bus", "unit", "if", "index",
2244 "cyls", "heads", "secs", "trans",
2245 "media", "snapshot", "file",
2246 "cache", "format", "serial", "werror",
2249 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
2250 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
2256 cyls
= heads
= secs
= 0;
2259 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2263 if (machine
->use_scsi
) {
2265 max_devs
= MAX_SCSI_DEVS
;
2266 pstrcpy(devname
, sizeof(devname
), "scsi");
2269 max_devs
= MAX_IDE_DEVS
;
2270 pstrcpy(devname
, sizeof(devname
), "ide");
2274 /* extract parameters */
2276 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
2277 bus_id
= strtol(buf
, NULL
, 0);
2279 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
2284 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
2285 unit_id
= strtol(buf
, NULL
, 0);
2287 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
2292 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
2293 pstrcpy(devname
, sizeof(devname
), buf
);
2294 if (!strcmp(buf
, "ide")) {
2296 max_devs
= MAX_IDE_DEVS
;
2297 } else if (!strcmp(buf
, "scsi")) {
2299 max_devs
= MAX_SCSI_DEVS
;
2300 } else if (!strcmp(buf
, "floppy")) {
2303 } else if (!strcmp(buf
, "pflash")) {
2306 } else if (!strcmp(buf
, "mtd")) {
2309 } else if (!strcmp(buf
, "sd")) {
2312 } else if (!strcmp(buf
, "virtio")) {
2315 } else if (!strcmp(buf
, "xen")) {
2319 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
2324 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
2325 index
= strtol(buf
, NULL
, 0);
2327 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
2332 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
2333 cyls
= strtol(buf
, NULL
, 0);
2336 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
2337 heads
= strtol(buf
, NULL
, 0);
2340 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
2341 secs
= strtol(buf
, NULL
, 0);
2344 if (cyls
|| heads
|| secs
) {
2345 if (cyls
< 1 || cyls
> 16383) {
2346 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
2349 if (heads
< 1 || heads
> 16) {
2350 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
2353 if (secs
< 1 || secs
> 63) {
2354 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
2359 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
2362 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2366 if (!strcmp(buf
, "none"))
2367 translation
= BIOS_ATA_TRANSLATION_NONE
;
2368 else if (!strcmp(buf
, "lba"))
2369 translation
= BIOS_ATA_TRANSLATION_LBA
;
2370 else if (!strcmp(buf
, "auto"))
2371 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2373 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
2378 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
2379 if (!strcmp(buf
, "disk")) {
2381 } else if (!strcmp(buf
, "cdrom")) {
2382 if (cyls
|| secs
|| heads
) {
2384 "qemu: '%s' invalid physical CHS format\n", str
);
2387 media
= MEDIA_CDROM
;
2389 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
2394 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
2395 if (!strcmp(buf
, "on"))
2397 else if (!strcmp(buf
, "off"))
2400 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
2405 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
2406 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2408 else if (!strcmp(buf
, "writethrough"))
2410 else if (!strcmp(buf
, "writeback"))
2413 fprintf(stderr
, "qemu: invalid cache option\n");
2418 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
2419 if (strcmp(buf
, "?") == 0) {
2420 fprintf(stderr
, "qemu: Supported formats:");
2421 bdrv_iterate_format(bdrv_format_print
, NULL
);
2422 fprintf(stderr
, "\n");
2425 drv
= bdrv_find_format(buf
);
2427 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2432 if (get_param_value(buf
, sizeof(buf
), "boot", str
)) {
2433 if (!strcmp(buf
, "on")) {
2434 if (extboot_drive
!= -1) {
2435 fprintf(stderr
, "qemu: two bootable drives specified\n");
2438 extboot_drive
= nb_drives
;
2439 } else if (strcmp(buf
, "off")) {
2440 fprintf(stderr
, "qemu: '%s' invalid boot option\n", str
);
2445 if (arg
->file
== NULL
)
2446 get_param_value(file
, sizeof(file
), "file", str
);
2448 pstrcpy(file
, sizeof(file
), arg
->file
);
2450 if (!get_param_value(serial
, sizeof(serial
), "serial", str
))
2451 memset(serial
, 0, sizeof(serial
));
2453 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2454 if (get_param_value(buf
, sizeof(serial
), "werror", str
)) {
2455 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2456 fprintf(stderr
, "werror is no supported by this format\n");
2459 if (!strcmp(buf
, "ignore"))
2460 onerror
= BLOCK_ERR_IGNORE
;
2461 else if (!strcmp(buf
, "enospc"))
2462 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2463 else if (!strcmp(buf
, "stop"))
2464 onerror
= BLOCK_ERR_STOP_ANY
;
2465 else if (!strcmp(buf
, "report"))
2466 onerror
= BLOCK_ERR_REPORT
;
2468 fprintf(stderr
, "qemu: '%s' invalid write error action\n", buf
);
2473 /* compute bus and unit according index */
2476 if (bus_id
!= 0 || unit_id
!= -1) {
2478 "qemu: '%s' index cannot be used with bus and unit\n", str
);
2486 unit_id
= index
% max_devs
;
2487 bus_id
= index
/ max_devs
;
2491 /* if user doesn't specify a unit_id,
2492 * try to find the first free
2495 if (unit_id
== -1) {
2497 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
2499 if (max_devs
&& unit_id
>= max_devs
) {
2500 unit_id
-= max_devs
;
2508 if (max_devs
&& unit_id
>= max_devs
) {
2509 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
2510 str
, unit_id
, max_devs
- 1);
2515 * ignore multiple definitions
2518 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
2523 if (type
== IF_IDE
|| type
== IF_SCSI
)
2524 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2526 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
2527 devname
, bus_id
, mediastr
, unit_id
);
2529 snprintf(buf
, sizeof(buf
), "%s%s%i",
2530 devname
, mediastr
, unit_id
);
2531 bdrv
= bdrv_new(buf
);
2532 drives_table_idx
= drive_get_free_idx();
2533 drives_table
[drives_table_idx
].bdrv
= bdrv
;
2534 drives_table
[drives_table_idx
].type
= type
;
2535 drives_table
[drives_table_idx
].bus
= bus_id
;
2536 drives_table
[drives_table_idx
].unit
= unit_id
;
2537 drives_table
[drives_table_idx
].onerror
= onerror
;
2538 drives_table
[drives_table_idx
].drive_opt_idx
= arg
- drives_opt
;
2539 strncpy(drives_table
[drives_table_idx
].serial
, serial
, sizeof(serial
));
2549 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
2550 bdrv_set_translation_hint(bdrv
, translation
);
2554 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
2559 /* FIXME: This isn't really a floppy, but it's a reasonable
2562 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
2575 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2576 cache
= 2; /* always use write-back with snapshot */
2578 if (cache
== 0) /* no caching */
2579 bdrv_flags
|= BDRV_O_NOCACHE
;
2580 else if (cache
== 2) /* write-back */
2581 bdrv_flags
|= BDRV_O_CACHE_WB
;
2582 else if (cache
== 3) /* not specified */
2583 bdrv_flags
|= BDRV_O_CACHE_DEF
;
2584 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0) {
2585 fprintf(stderr
, "qemu: could not open disk image %s\n",
2589 if (bdrv_key_required(bdrv
))
2591 return drives_table_idx
;
2594 static void numa_add(const char *optarg
)
2598 unsigned long long value
, endvalue
;
2601 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2602 if (!strcmp(option
, "node")) {
2603 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2604 nodenr
= nb_numa_nodes
;
2606 nodenr
= strtoull(option
, NULL
, 10);
2609 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2610 node_mem
[nodenr
] = 0;
2612 value
= strtoull(option
, &endptr
, 0);
2614 case 0: case 'M': case 'm':
2621 node_mem
[nodenr
] = value
;
2623 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2624 node_cpumask
[nodenr
] = 0;
2626 value
= strtoull(option
, &endptr
, 10);
2629 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2631 if (*endptr
== '-') {
2632 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2633 if (endvalue
>= 63) {
2636 "only 63 CPUs in NUMA mode supported.\n");
2638 value
= (1 << (endvalue
+ 1)) - (1 << value
);
2643 node_cpumask
[nodenr
] = value
;
2650 /***********************************************************/
2653 static USBPort
*used_usb_ports
;
2654 static USBPort
*free_usb_ports
;
2656 /* ??? Maybe change this to register a hub to keep track of the topology. */
2657 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
2658 usb_attachfn attach
)
2660 port
->opaque
= opaque
;
2661 port
->index
= index
;
2662 port
->attach
= attach
;
2663 port
->next
= free_usb_ports
;
2664 free_usb_ports
= port
;
2667 int usb_device_add_dev(USBDevice
*dev
)
2671 /* Find a USB port to add the device to. */
2672 port
= free_usb_ports
;
2676 /* Create a new hub and chain it on. */
2677 free_usb_ports
= NULL
;
2678 port
->next
= used_usb_ports
;
2679 used_usb_ports
= port
;
2681 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
2682 usb_attach(port
, hub
);
2683 port
= free_usb_ports
;
2686 free_usb_ports
= port
->next
;
2687 port
->next
= used_usb_ports
;
2688 used_usb_ports
= port
;
2689 usb_attach(port
, dev
);
2693 static void usb_msd_password_cb(void *opaque
, int err
)
2695 USBDevice
*dev
= opaque
;
2698 usb_device_add_dev(dev
);
2700 dev
->handle_destroy(dev
);
2703 static int usb_device_add(const char *devname
, int is_hotplug
)
2708 if (!free_usb_ports
)
2711 if (strstart(devname
, "host:", &p
)) {
2712 dev
= usb_host_device_open(p
);
2713 } else if (!strcmp(devname
, "mouse")) {
2714 dev
= usb_mouse_init();
2715 } else if (!strcmp(devname
, "tablet")) {
2716 dev
= usb_tablet_init();
2717 } else if (!strcmp(devname
, "keyboard")) {
2718 dev
= usb_keyboard_init();
2719 } else if (strstart(devname
, "disk:", &p
)) {
2720 BlockDriverState
*bs
;
2722 dev
= usb_msd_init(p
);
2725 bs
= usb_msd_get_bdrv(dev
);
2726 if (bdrv_key_required(bs
)) {
2729 monitor_read_bdrv_key_start(cur_mon
, bs
, usb_msd_password_cb
,
2734 } else if (!strcmp(devname
, "wacom-tablet")) {
2735 dev
= usb_wacom_init();
2736 } else if (strstart(devname
, "serial:", &p
)) {
2737 dev
= usb_serial_init(p
);
2738 #ifdef CONFIG_BRLAPI
2739 } else if (!strcmp(devname
, "braille")) {
2740 dev
= usb_baum_init();
2742 } else if (strstart(devname
, "net:", &p
)) {
2745 if (net_client_init(NULL
, "nic", p
) < 0)
2747 nd_table
[nic
].model
= "usb";
2748 dev
= usb_net_init(&nd_table
[nic
]);
2749 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2750 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2751 bt_new_hci(qemu_find_bt_vlan(0)));
2758 return usb_device_add_dev(dev
);
2761 int usb_device_del_addr(int bus_num
, int addr
)
2767 if (!used_usb_ports
)
2773 lastp
= &used_usb_ports
;
2774 port
= used_usb_ports
;
2775 while (port
&& port
->dev
->addr
!= addr
) {
2776 lastp
= &port
->next
;
2784 *lastp
= port
->next
;
2785 usb_attach(port
, NULL
);
2786 dev
->handle_destroy(dev
);
2787 port
->next
= free_usb_ports
;
2788 free_usb_ports
= port
;
2792 static int usb_device_del(const char *devname
)
2797 if (strstart(devname
, "host:", &p
))
2798 return usb_host_device_close(p
);
2800 if (!used_usb_ports
)
2803 p
= strchr(devname
, '.');
2806 bus_num
= strtoul(devname
, NULL
, 0);
2807 addr
= strtoul(p
+ 1, NULL
, 0);
2809 return usb_device_del_addr(bus_num
, addr
);
2812 void do_usb_add(Monitor
*mon
, const char *devname
)
2814 usb_device_add(devname
, 1);
2817 void do_usb_del(Monitor
*mon
, const char *devname
)
2819 usb_device_del(devname
);
2822 void usb_info(Monitor
*mon
)
2826 const char *speed_str
;
2829 monitor_printf(mon
, "USB support not enabled\n");
2833 for (port
= used_usb_ports
; port
; port
= port
->next
) {
2837 switch(dev
->speed
) {
2841 case USB_SPEED_FULL
:
2844 case USB_SPEED_HIGH
:
2851 monitor_printf(mon
, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2852 0, dev
->addr
, speed_str
, dev
->devname
);
2856 /***********************************************************/
2857 /* PCMCIA/Cardbus */
2859 static struct pcmcia_socket_entry_s
{
2860 PCMCIASocket
*socket
;
2861 struct pcmcia_socket_entry_s
*next
;
2862 } *pcmcia_sockets
= 0;
2864 void pcmcia_socket_register(PCMCIASocket
*socket
)
2866 struct pcmcia_socket_entry_s
*entry
;
2868 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2869 entry
->socket
= socket
;
2870 entry
->next
= pcmcia_sockets
;
2871 pcmcia_sockets
= entry
;
2874 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2876 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2878 ptr
= &pcmcia_sockets
;
2879 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2880 if (entry
->socket
== socket
) {
2886 void pcmcia_info(Monitor
*mon
)
2888 struct pcmcia_socket_entry_s
*iter
;
2890 if (!pcmcia_sockets
)
2891 monitor_printf(mon
, "No PCMCIA sockets\n");
2893 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2894 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2895 iter
->socket
->attached
? iter
->socket
->card_string
:
2899 /***********************************************************/
2900 /* register display */
2902 struct DisplayAllocator default_allocator
= {
2903 defaultallocator_create_displaysurface
,
2904 defaultallocator_resize_displaysurface
,
2905 defaultallocator_free_displaysurface
2908 void register_displaystate(DisplayState
*ds
)
2918 DisplayState
*get_displaystate(void)
2920 return display_state
;
2923 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
2925 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
2926 return ds
->allocator
;
2931 static void dumb_display_init(void)
2933 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
2934 ds
->allocator
= &default_allocator
;
2935 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
2936 register_displaystate(ds
);
2939 /***********************************************************/
2942 typedef struct IOHandlerRecord
{
2944 IOCanRWHandler
*fd_read_poll
;
2946 IOHandler
*fd_write
;
2949 /* temporary data */
2951 struct IOHandlerRecord
*next
;
2954 static IOHandlerRecord
*first_io_handler
;
2956 /* XXX: fd_read_poll should be suppressed, but an API change is
2957 necessary in the character devices to suppress fd_can_read(). */
2958 int qemu_set_fd_handler2(int fd
,
2959 IOCanRWHandler
*fd_read_poll
,
2961 IOHandler
*fd_write
,
2964 IOHandlerRecord
**pioh
, *ioh
;
2966 if (!fd_read
&& !fd_write
) {
2967 pioh
= &first_io_handler
;
2972 if (ioh
->fd
== fd
) {
2979 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
2983 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
2984 ioh
->next
= first_io_handler
;
2985 first_io_handler
= ioh
;
2988 ioh
->fd_read_poll
= fd_read_poll
;
2989 ioh
->fd_read
= fd_read
;
2990 ioh
->fd_write
= fd_write
;
2991 ioh
->opaque
= opaque
;
2994 qemu_notify_event();
2998 int qemu_set_fd_handler(int fd
,
3000 IOHandler
*fd_write
,
3003 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
3007 /***********************************************************/
3008 /* Polling handling */
3010 typedef struct PollingEntry
{
3013 struct PollingEntry
*next
;
3016 static PollingEntry
*first_polling_entry
;
3018 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
3020 PollingEntry
**ppe
, *pe
;
3021 pe
= qemu_mallocz(sizeof(PollingEntry
));
3023 pe
->opaque
= opaque
;
3024 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
3029 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
3031 PollingEntry
**ppe
, *pe
;
3032 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
3034 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
3042 /***********************************************************/
3043 /* Wait objects support */
3044 typedef struct WaitObjects
{
3046 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
3047 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
3048 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
3051 static WaitObjects wait_objects
= {0};
3053 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
3055 WaitObjects
*w
= &wait_objects
;
3057 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
3059 w
->events
[w
->num
] = handle
;
3060 w
->func
[w
->num
] = func
;
3061 w
->opaque
[w
->num
] = opaque
;
3066 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
3069 WaitObjects
*w
= &wait_objects
;
3072 for (i
= 0; i
< w
->num
; i
++) {
3073 if (w
->events
[i
] == handle
)
3076 w
->events
[i
] = w
->events
[i
+ 1];
3077 w
->func
[i
] = w
->func
[i
+ 1];
3078 w
->opaque
[i
] = w
->opaque
[i
+ 1];
3086 /***********************************************************/
3087 /* ram save/restore */
3089 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
3093 v
= qemu_get_byte(f
);
3096 if (qemu_get_buffer(f
, buf
, len
) != len
)
3100 v
= qemu_get_byte(f
);
3101 memset(buf
, v
, len
);
3107 if (qemu_file_has_error(f
))
3113 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
3118 if (qemu_get_be32(f
) != last_ram_offset
)
3120 for(i
= 0; i
< last_ram_offset
; i
+= TARGET_PAGE_SIZE
) {
3121 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3123 ret
= ram_get_page(f
, qemu_get_ram_ptr(i
), TARGET_PAGE_SIZE
);
3130 #define BDRV_HASH_BLOCK_SIZE 1024
3131 #define IOBUF_SIZE 4096
3132 #define RAM_CBLOCK_MAGIC 0xfabe
3134 typedef struct RamDecompressState
{
3137 uint8_t buf
[IOBUF_SIZE
];
3138 } RamDecompressState
;
3140 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
3143 memset(s
, 0, sizeof(*s
));
3145 ret
= inflateInit(&s
->zstream
);
3151 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
3155 s
->zstream
.avail_out
= len
;
3156 s
->zstream
.next_out
= buf
;
3157 while (s
->zstream
.avail_out
> 0) {
3158 if (s
->zstream
.avail_in
== 0) {
3159 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
3161 clen
= qemu_get_be16(s
->f
);
3162 if (clen
> IOBUF_SIZE
)
3164 qemu_get_buffer(s
->f
, s
->buf
, clen
);
3165 s
->zstream
.avail_in
= clen
;
3166 s
->zstream
.next_in
= s
->buf
;
3168 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
3169 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
3176 static void ram_decompress_close(RamDecompressState
*s
)
3178 inflateEnd(&s
->zstream
);
3181 #define RAM_SAVE_FLAG_FULL 0x01
3182 #define RAM_SAVE_FLAG_COMPRESS 0x02
3183 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3184 #define RAM_SAVE_FLAG_PAGE 0x08
3185 #define RAM_SAVE_FLAG_EOS 0x10
3187 static int is_dup_page(uint8_t *page
, uint8_t ch
)
3189 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
3190 uint32_t *array
= (uint32_t *)page
;
3193 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
3194 if (array
[i
] != val
)
3201 static int ram_save_block(QEMUFile
*f
)
3203 static ram_addr_t current_addr
= 0;
3204 ram_addr_t saved_addr
= current_addr
;
3205 ram_addr_t addr
= 0;
3208 while (addr
< last_ram_offset
) {
3209 if (kvm_enabled() && current_addr
== 0) {
3211 r
= kvm_update_dirty_pages_log();
3213 fprintf(stderr
, "%s: update dirty pages log failed %d\n", __FUNCTION__
, r
);
3214 qemu_file_set_error(f
);
3218 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
3221 cpu_physical_memory_reset_dirty(current_addr
,
3222 current_addr
+ TARGET_PAGE_SIZE
,
3223 MIGRATION_DIRTY_FLAG
);
3225 p
= qemu_get_ram_ptr(current_addr
);
3227 if (is_dup_page(p
, *p
)) {
3228 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
3229 qemu_put_byte(f
, *p
);
3231 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
3232 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
3238 addr
+= TARGET_PAGE_SIZE
;
3239 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
3245 static ram_addr_t ram_save_threshold
= 10;
3246 static uint64_t bytes_transferred
= 0;
3248 static ram_addr_t
ram_save_remaining(void)
3251 ram_addr_t count
= 0;
3253 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3254 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3261 uint64_t ram_bytes_remaining(void)
3263 return ram_save_remaining() * TARGET_PAGE_SIZE
;
3266 uint64_t ram_bytes_transferred(void)
3268 return bytes_transferred
;
3271 uint64_t ram_bytes_total(void)
3273 return last_ram_offset
;
3276 static int ram_save_live(QEMUFile
*f
, int stage
, void *opaque
)
3280 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX
) != 0) {
3281 qemu_file_set_error(f
);
3286 /* Make sure all dirty bits are set */
3287 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3288 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3289 cpu_physical_memory_set_dirty(addr
);
3292 /* Enable dirty memory tracking */
3293 cpu_physical_memory_set_dirty_tracking(1);
3295 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
3298 while (!qemu_file_rate_limit(f
)) {
3301 ret
= ram_save_block(f
);
3302 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
3303 if (ret
== 0) /* no more blocks */
3307 /* try transferring iterative blocks of memory */
3311 /* flush all remaining blocks regardless of rate limiting */
3312 while (ram_save_block(f
) != 0) {
3313 bytes_transferred
+= TARGET_PAGE_SIZE
;
3315 cpu_physical_memory_set_dirty_tracking(0);
3318 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3320 return (stage
== 2) && (ram_save_remaining() < ram_save_threshold
);
3323 static int ram_load_dead(QEMUFile
*f
, void *opaque
)
3325 RamDecompressState s1
, *s
= &s1
;
3329 if (ram_decompress_open(s
, f
) < 0)
3331 for(i
= 0; i
< last_ram_offset
; i
+= BDRV_HASH_BLOCK_SIZE
) {
3332 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3334 if (ram_decompress_buf(s
, buf
, 1) < 0) {
3335 fprintf(stderr
, "Error while reading ram block header\n");
3339 if (ram_decompress_buf(s
, qemu_get_ram_ptr(i
),
3340 BDRV_HASH_BLOCK_SIZE
) < 0) {
3341 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
3346 printf("Error block header\n");
3350 ram_decompress_close(s
);
3355 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
3360 if (version_id
== 1)
3361 return ram_load_v1(f
, opaque
);
3363 if (version_id
== 2) {
3364 if (qemu_get_be32(f
) != last_ram_offset
)
3366 return ram_load_dead(f
, opaque
);
3369 if (version_id
!= 3)
3373 addr
= qemu_get_be64(f
);
3375 flags
= addr
& ~TARGET_PAGE_MASK
;
3376 addr
&= TARGET_PAGE_MASK
;
3378 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
3379 if (addr
!= last_ram_offset
)
3383 if (flags
& RAM_SAVE_FLAG_FULL
) {
3384 if (ram_load_dead(f
, opaque
) < 0)
3388 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
3389 uint8_t ch
= qemu_get_byte(f
);
3390 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
3391 } else if (flags
& RAM_SAVE_FLAG_PAGE
)
3392 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
3393 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
3398 void qemu_service_io(void)
3400 qemu_notify_event();
3403 /***********************************************************/
3404 /* bottom halves (can be seen as timers which expire ASAP) */
3415 static QEMUBH
*first_bh
= NULL
;
3417 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
3420 bh
= qemu_mallocz(sizeof(QEMUBH
));
3422 bh
->opaque
= opaque
;
3423 bh
->next
= first_bh
;
3428 int qemu_bh_poll(void)
3434 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3435 if (!bh
->deleted
&& bh
->scheduled
) {
3444 /* remove deleted bhs */
3458 void qemu_bh_schedule_idle(QEMUBH
*bh
)
3466 void qemu_bh_schedule(QEMUBH
*bh
)
3472 /* stop the currently executing CPU to execute the BH ASAP */
3473 qemu_notify_event();
3476 void qemu_bh_cancel(QEMUBH
*bh
)
3481 void qemu_bh_delete(QEMUBH
*bh
)
3487 static void qemu_bh_update_timeout(int *timeout
)
3491 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3492 if (!bh
->deleted
&& bh
->scheduled
) {
3494 /* idle bottom halves will be polled at least
3496 *timeout
= MIN(10, *timeout
);
3498 /* non-idle bottom halves will be executed
3507 /***********************************************************/
3508 /* machine registration */
3510 static QEMUMachine
*first_machine
= NULL
;
3511 QEMUMachine
*current_machine
= NULL
;
3513 int qemu_register_machine(QEMUMachine
*m
)
3516 pm
= &first_machine
;
3524 static QEMUMachine
*find_machine(const char *name
)
3528 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3529 if (!strcmp(m
->name
, name
))
3535 static QEMUMachine
*find_default_machine(void)
3539 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3540 if (m
->is_default
) {
3547 /***********************************************************/
3548 /* main execution loop */
3550 static void gui_update(void *opaque
)
3552 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3553 DisplayState
*ds
= opaque
;
3554 DisplayChangeListener
*dcl
= ds
->listeners
;
3558 while (dcl
!= NULL
) {
3559 if (dcl
->gui_timer_interval
&&
3560 dcl
->gui_timer_interval
< interval
)
3561 interval
= dcl
->gui_timer_interval
;
3564 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3567 static void nographic_update(void *opaque
)
3569 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3571 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3574 struct vm_change_state_entry
{
3575 VMChangeStateHandler
*cb
;
3577 LIST_ENTRY (vm_change_state_entry
) entries
;
3580 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3582 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3585 VMChangeStateEntry
*e
;
3587 e
= qemu_mallocz(sizeof (*e
));
3591 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3595 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3597 LIST_REMOVE (e
, entries
);
3601 static void vm_state_notify(int running
, int reason
)
3603 VMChangeStateEntry
*e
;
3605 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3606 e
->cb(e
->opaque
, running
, reason
);
3610 static void resume_all_vcpus(void);
3611 static void pause_all_vcpus(void);
3618 vm_state_notify(1, 0);
3619 qemu_rearm_alarm_timer(alarm_timer
);
3624 /* reset/shutdown handler */
3626 typedef struct QEMUResetEntry
{
3627 QEMUResetHandler
*func
;
3630 struct QEMUResetEntry
*next
;
3633 static QEMUResetEntry
*first_reset_entry
;
3634 static int reset_requested
;
3635 static int shutdown_requested
;
3636 static int powerdown_requested
;
3637 static int debug_requested
;
3638 static int vmstop_requested
;
3640 int qemu_no_shutdown(void)
3642 int r
= no_shutdown
;
3647 int qemu_shutdown_requested(void)
3649 int r
= shutdown_requested
;
3650 shutdown_requested
= 0;
3654 int qemu_reset_requested(void)
3656 int r
= reset_requested
;
3657 reset_requested
= 0;
3661 int qemu_powerdown_requested(void)
3663 int r
= powerdown_requested
;
3664 powerdown_requested
= 0;
3668 static int qemu_debug_requested(void)
3670 int r
= debug_requested
;
3671 debug_requested
= 0;
3675 static int qemu_vmstop_requested(void)
3677 int r
= vmstop_requested
;
3678 vmstop_requested
= 0;
3682 static void do_vm_stop(int reason
)
3685 cpu_disable_ticks();
3688 vm_state_notify(0, reason
);
3692 void qemu_register_reset(QEMUResetHandler
*func
, int order
, void *opaque
)
3694 QEMUResetEntry
**pre
, *re
;
3696 pre
= &first_reset_entry
;
3697 while (*pre
!= NULL
&& (*pre
)->order
>= order
) {
3698 pre
= &(*pre
)->next
;
3700 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3702 re
->opaque
= opaque
;
3708 void qemu_system_reset(void)
3712 /* reset all devices */
3713 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
3714 re
->func(re
->opaque
);
3718 void qemu_system_reset_request(void)
3721 shutdown_requested
= 1;
3723 reset_requested
= 1;
3725 if (cpu_single_env
) {
3726 qemu_kvm_cpu_stop(cpu_single_env
);
3727 cpu_exit(cpu_single_env
);
3729 qemu_notify_event();
3732 void qemu_system_shutdown_request(void)
3734 shutdown_requested
= 1;
3735 qemu_notify_event();
3738 void qemu_system_powerdown_request(void)
3740 powerdown_requested
= 1;
3741 qemu_notify_event();
3744 #ifdef CONFIG_IOTHREAD
3745 static void qemu_system_vmstop_request(int reason
)
3747 vmstop_requested
= reason
;
3748 qemu_notify_event();
3753 static int io_thread_fd
= -1;
3755 static void qemu_event_increment(void)
3757 static const char byte
= 0;
3759 if (io_thread_fd
== -1)
3762 write(io_thread_fd
, &byte
, sizeof(byte
));
3765 static void qemu_event_read(void *opaque
)
3767 int fd
= (unsigned long)opaque
;
3770 /* Drain the notify pipe */
3773 len
= read(fd
, buffer
, sizeof(buffer
));
3774 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
3777 static int qemu_event_init(void)
3786 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3790 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3794 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3795 (void *)(unsigned long)fds
[0]);
3797 io_thread_fd
= fds
[1];
3806 HANDLE qemu_event_handle
;
3808 static void dummy_event_handler(void *opaque
)
3812 static int qemu_event_init(void)
3814 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3815 if (!qemu_event_handle
) {
3816 perror("Failed CreateEvent");
3819 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3823 static void qemu_event_increment(void)
3825 SetEvent(qemu_event_handle
);
3829 static int cpu_can_run(CPUState
*env
)
3838 #ifndef CONFIG_IOTHREAD
3839 static int qemu_init_main_loop(void)
3841 return qemu_event_init();
3844 void qemu_init_vcpu(void *_env
)
3846 CPUState
*env
= _env
;
3853 int qemu_cpu_self(void *env
)
3858 static void resume_all_vcpus(void)
3862 static void pause_all_vcpus(void)
3866 void qemu_cpu_kick(void *env
)
3871 void qemu_notify_event(void)
3873 CPUState
*env
= cpu_single_env
;
3875 if (kvm_enabled()) {
3876 qemu_kvm_notify_work();
3882 if (env
->kqemu_enabled
)
3883 kqemu_cpu_interrupt(env
);
3888 #define qemu_mutex_lock_iothread() do { } while (0)
3889 #define qemu_mutex_unlock_iothread() do { } while (0)
3891 void vm_stop(int reason
)
3896 #else /* CONFIG_IOTHREAD */
3898 #include "qemu-thread.h"
3900 QemuMutex qemu_global_mutex
;
3901 static QemuMutex qemu_fair_mutex
;
3903 static QemuThread io_thread
;
3905 static QemuThread
*tcg_cpu_thread
;
3906 static QemuCond
*tcg_halt_cond
;
3908 static int qemu_system_ready
;
3910 static QemuCond qemu_cpu_cond
;
3912 static QemuCond qemu_system_cond
;
3913 static QemuCond qemu_pause_cond
;
3915 static void block_io_signals(void);
3916 static void unblock_io_signals(void);
3917 static int tcg_has_work(void);
3919 static int qemu_init_main_loop(void)
3923 ret
= qemu_event_init();
3927 qemu_cond_init(&qemu_pause_cond
);
3928 qemu_mutex_init(&qemu_fair_mutex
);
3929 qemu_mutex_init(&qemu_global_mutex
);
3930 qemu_mutex_lock(&qemu_global_mutex
);
3932 unblock_io_signals();
3933 qemu_thread_self(&io_thread
);
3938 static void qemu_wait_io_event(CPUState
*env
)
3940 while (!tcg_has_work())
3941 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3943 qemu_mutex_unlock(&qemu_global_mutex
);
3946 * Users of qemu_global_mutex can be starved, having no chance
3947 * to acquire it since this path will get to it first.
3948 * So use another lock to provide fairness.
3950 qemu_mutex_lock(&qemu_fair_mutex
);
3951 qemu_mutex_unlock(&qemu_fair_mutex
);
3953 qemu_mutex_lock(&qemu_global_mutex
);
3957 qemu_cond_signal(&qemu_pause_cond
);
3961 static int qemu_cpu_exec(CPUState
*env
);
3963 static void *kvm_cpu_thread_fn(void *arg
)
3965 CPUState
*env
= arg
;
3968 qemu_thread_self(env
->thread
);
3970 /* signal CPU creation */
3971 qemu_mutex_lock(&qemu_global_mutex
);
3973 qemu_cond_signal(&qemu_cpu_cond
);
3975 /* and wait for machine initialization */
3976 while (!qemu_system_ready
)
3977 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3980 if (cpu_can_run(env
))
3982 qemu_wait_io_event(env
);
3988 static void tcg_cpu_exec(void);
3990 static void *tcg_cpu_thread_fn(void *arg
)
3992 CPUState
*env
= arg
;
3995 qemu_thread_self(env
->thread
);
3997 /* signal CPU creation */
3998 qemu_mutex_lock(&qemu_global_mutex
);
3999 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4001 qemu_cond_signal(&qemu_cpu_cond
);
4003 /* and wait for machine initialization */
4004 while (!qemu_system_ready
)
4005 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
4009 qemu_wait_io_event(cur_cpu
);
4015 void qemu_cpu_kick(void *_env
)
4017 CPUState
*env
= _env
;
4018 qemu_cond_broadcast(env
->halt_cond
);
4020 qemu_thread_signal(env
->thread
, SIGUSR1
);
4023 int qemu_cpu_self(void *env
)
4025 return (cpu_single_env
!= NULL
);
4028 static void cpu_signal(int sig
)
4031 cpu_exit(cpu_single_env
);
4034 static void block_io_signals(void)
4037 struct sigaction sigact
;
4040 sigaddset(&set
, SIGUSR2
);
4041 sigaddset(&set
, SIGIO
);
4042 sigaddset(&set
, SIGALRM
);
4043 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
4046 sigaddset(&set
, SIGUSR1
);
4047 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
4049 memset(&sigact
, 0, sizeof(sigact
));
4050 sigact
.sa_handler
= cpu_signal
;
4051 sigaction(SIGUSR1
, &sigact
, NULL
);
4054 static void unblock_io_signals(void)
4059 sigaddset(&set
, SIGUSR2
);
4060 sigaddset(&set
, SIGIO
);
4061 sigaddset(&set
, SIGALRM
);
4062 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
4065 sigaddset(&set
, SIGUSR1
);
4066 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
4069 static void qemu_signal_lock(unsigned int msecs
)
4071 qemu_mutex_lock(&qemu_fair_mutex
);
4073 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
4074 qemu_thread_signal(tcg_cpu_thread
, SIGUSR1
);
4075 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
4078 qemu_mutex_unlock(&qemu_fair_mutex
);
4081 static void qemu_mutex_lock_iothread(void)
4083 if (kvm_enabled()) {
4084 qemu_mutex_lock(&qemu_fair_mutex
);
4085 qemu_mutex_lock(&qemu_global_mutex
);
4086 qemu_mutex_unlock(&qemu_fair_mutex
);
4088 qemu_signal_lock(100);
4091 static void qemu_mutex_unlock_iothread(void)
4093 qemu_mutex_unlock(&qemu_global_mutex
);
4096 static int all_vcpus_paused(void)
4098 CPUState
*penv
= first_cpu
;
4103 penv
= (CPUState
*)penv
->next_cpu
;
4109 static void pause_all_vcpus(void)
4111 CPUState
*penv
= first_cpu
;
4115 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4116 qemu_cpu_kick(penv
);
4117 penv
= (CPUState
*)penv
->next_cpu
;
4120 while (!all_vcpus_paused()) {
4121 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
4124 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4125 penv
= (CPUState
*)penv
->next_cpu
;
4130 static void resume_all_vcpus(void)
4132 CPUState
*penv
= first_cpu
;
4137 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4138 qemu_cpu_kick(penv
);
4139 penv
= (CPUState
*)penv
->next_cpu
;
4143 static void tcg_init_vcpu(void *_env
)
4145 CPUState
*env
= _env
;
4146 /* share a single thread for all cpus with TCG */
4147 if (!tcg_cpu_thread
) {
4148 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
4149 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
4150 qemu_cond_init(env
->halt_cond
);
4151 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
4152 while (env
->created
== 0)
4153 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
4154 tcg_cpu_thread
= env
->thread
;
4155 tcg_halt_cond
= env
->halt_cond
;
4157 env
->thread
= tcg_cpu_thread
;
4158 env
->halt_cond
= tcg_halt_cond
;
4162 static void kvm_start_vcpu(CPUState
*env
)
4165 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
4166 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
4167 qemu_cond_init(env
->halt_cond
);
4168 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
4169 while (env
->created
== 0)
4170 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
4173 void qemu_init_vcpu(void *_env
)
4175 CPUState
*env
= _env
;
4178 kvm_start_vcpu(env
);
4183 void qemu_notify_event(void)
4185 qemu_event_increment();
4188 void vm_stop(int reason
)
4191 qemu_thread_self(&me
);
4193 if (!qemu_thread_equal(&me
, &io_thread
)) {
4194 qemu_system_vmstop_request(reason
);
4196 * FIXME: should not return to device code in case
4197 * vm_stop() has been requested.
4199 if (cpu_single_env
) {
4200 cpu_exit(cpu_single_env
);
4201 cpu_single_env
->stop
= 1;
4212 static void host_main_loop_wait(int *timeout
)
4218 /* XXX: need to suppress polling by better using win32 events */
4220 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
4221 ret
|= pe
->func(pe
->opaque
);
4225 WaitObjects
*w
= &wait_objects
;
4227 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
4228 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
4229 if (w
->func
[ret
- WAIT_OBJECT_0
])
4230 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
4232 /* Check for additional signaled events */
4233 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
4235 /* Check if event is signaled */
4236 ret2
= WaitForSingleObject(w
->events
[i
], 0);
4237 if(ret2
== WAIT_OBJECT_0
) {
4239 w
->func
[i
](w
->opaque
[i
]);
4240 } else if (ret2
== WAIT_TIMEOUT
) {
4242 err
= GetLastError();
4243 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
4246 } else if (ret
== WAIT_TIMEOUT
) {
4248 err
= GetLastError();
4249 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
4256 static void host_main_loop_wait(int *timeout
)
4261 void main_loop_wait(int timeout
)
4263 IOHandlerRecord
*ioh
;
4264 fd_set rfds
, wfds
, xfds
;
4268 qemu_bh_update_timeout(&timeout
);
4270 host_main_loop_wait(&timeout
);
4272 /* poll any events */
4273 /* XXX: separate device handlers from system ones */
4278 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4282 (!ioh
->fd_read_poll
||
4283 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
4284 FD_SET(ioh
->fd
, &rfds
);
4288 if (ioh
->fd_write
) {
4289 FD_SET(ioh
->fd
, &wfds
);
4295 tv
.tv_sec
= timeout
/ 1000;
4296 tv
.tv_usec
= (timeout
% 1000) * 1000;
4298 #if defined(CONFIG_SLIRP)
4299 if (slirp_is_inited()) {
4300 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
4303 ret
= qemu_select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
4305 IOHandlerRecord
**pioh
;
4307 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4308 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
4309 ioh
->fd_read(ioh
->opaque
);
4310 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
4311 FD_CLR(ioh
->fd
, &rfds
);
4313 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
4314 ioh
->fd_write(ioh
->opaque
);
4318 /* remove deleted IO handlers */
4319 pioh
= &first_io_handler
;
4329 #if defined(CONFIG_SLIRP)
4330 if (slirp_is_inited()) {
4336 slirp_select_poll(&rfds
, &wfds
, &xfds
);
4340 /* rearm timer, if not periodic */
4341 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
4342 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
4343 qemu_rearm_alarm_timer(alarm_timer
);
4346 /* vm time timers */
4348 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
4349 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
4350 qemu_get_clock(vm_clock
));
4353 /* real time timers */
4354 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
4355 qemu_get_clock(rt_clock
));
4357 /* Check bottom-halves last in case any of the earlier events triggered
4363 static int qemu_cpu_exec(CPUState
*env
)
4366 #ifdef CONFIG_PROFILER
4370 #ifdef CONFIG_PROFILER
4371 ti
= profile_getclock();
4376 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
4377 env
->icount_decr
.u16
.low
= 0;
4378 env
->icount_extra
= 0;
4379 count
= qemu_next_deadline();
4380 count
= (count
+ (1 << icount_time_shift
) - 1)
4381 >> icount_time_shift
;
4382 qemu_icount
+= count
;
4383 decr
= (count
> 0xffff) ? 0xffff : count
;
4385 env
->icount_decr
.u16
.low
= decr
;
4386 env
->icount_extra
= count
;
4388 ret
= cpu_exec(env
);
4389 #ifdef CONFIG_PROFILER
4390 qemu_time
+= profile_getclock() - ti
;
4393 /* Fold pending instructions back into the
4394 instruction counter, and clear the interrupt flag. */
4395 qemu_icount
-= (env
->icount_decr
.u16
.low
4396 + env
->icount_extra
);
4397 env
->icount_decr
.u32
= 0;
4398 env
->icount_extra
= 0;
4403 static void tcg_cpu_exec(void)
4407 if (next_cpu
== NULL
)
4408 next_cpu
= first_cpu
;
4409 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
4410 CPUState
*env
= cur_cpu
= next_cpu
;
4414 if (timer_alarm_pending
) {
4415 timer_alarm_pending
= 0;
4418 if (cpu_can_run(env
))
4419 ret
= qemu_cpu_exec(env
);
4420 if (ret
== EXCP_DEBUG
) {
4421 gdb_set_stop_cpu(env
);
4422 debug_requested
= 1;
4428 static int cpu_has_work(CPUState
*env
)
4436 if (qemu_cpu_has_work(env
))
4441 static int tcg_has_work(void)
4445 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4446 if (cpu_has_work(env
))
4451 static int qemu_calculate_timeout(void)
4453 #ifndef CONFIG_IOTHREAD
4458 else if (tcg_has_work())
4460 else if (!use_icount
)
4463 /* XXX: use timeout computed from timers */
4466 /* Advance virtual time to the next event. */
4467 if (use_icount
== 1) {
4468 /* When not using an adaptive execution frequency
4469 we tend to get badly out of sync with real time,
4470 so just delay for a reasonable amount of time. */
4473 delta
= cpu_get_icount() - cpu_get_clock();
4476 /* If virtual time is ahead of real time then just
4478 timeout
= (delta
/ 1000000) + 1;
4480 /* Wait for either IO to occur or the next
4482 add
= qemu_next_deadline();
4483 /* We advance the timer before checking for IO.
4484 Limit the amount we advance so that early IO
4485 activity won't get the guest too far ahead. */
4489 add
= (add
+ (1 << icount_time_shift
) - 1)
4490 >> icount_time_shift
;
4492 timeout
= delta
/ 1000000;
4499 #else /* CONFIG_IOTHREAD */
4504 static int vm_can_run(void)
4506 if (powerdown_requested
)
4508 if (reset_requested
)
4510 if (shutdown_requested
)
4512 if (debug_requested
)
4517 static void main_loop(void)
4521 if (kvm_enabled()) {
4523 cpu_disable_ticks();
4527 #ifdef CONFIG_IOTHREAD
4528 qemu_system_ready
= 1;
4529 qemu_cond_broadcast(&qemu_system_cond
);
4534 #ifdef CONFIG_PROFILER
4537 #ifndef CONFIG_IOTHREAD
4540 #ifdef CONFIG_PROFILER
4541 ti
= profile_getclock();
4543 main_loop_wait(qemu_calculate_timeout());
4544 #ifdef CONFIG_PROFILER
4545 dev_time
+= profile_getclock() - ti
;
4547 } while (vm_can_run());
4549 if (qemu_debug_requested())
4550 vm_stop(EXCP_DEBUG
);
4551 if (qemu_shutdown_requested()) {
4558 if (qemu_reset_requested()) {
4560 qemu_system_reset();
4563 if (qemu_powerdown_requested())
4564 qemu_system_powerdown();
4565 if ((r
= qemu_vmstop_requested()))
4571 static void version(void)
4573 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4576 static void help(int exitcode
)
4579 printf("usage: %s [options] [disk_image]\n"
4581 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4583 #define DEF(option, opt_arg, opt_enum, opt_help) \
4585 #define DEFHEADING(text) stringify(text) "\n"
4586 #include "qemu-options.h"
4591 "During emulation, the following keys are useful:\n"
4592 "ctrl-alt-f toggle full screen\n"
4593 "ctrl-alt-n switch to virtual console 'n'\n"
4594 "ctrl-alt toggle mouse and keyboard grab\n"
4596 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4601 DEFAULT_NETWORK_SCRIPT
,
4602 DEFAULT_NETWORK_DOWN_SCRIPT
,
4604 DEFAULT_GDBSTUB_PORT
,
4609 #define HAS_ARG 0x0001
4612 #define DEF(option, opt_arg, opt_enum, opt_help) \
4614 #define DEFHEADING(text)
4615 #include "qemu-options.h"
4621 typedef struct QEMUOption
{
4627 static const QEMUOption qemu_options
[] = {
4628 { "h", 0, QEMU_OPTION_h
},
4629 #define DEF(option, opt_arg, opt_enum, opt_help) \
4630 { option, opt_arg, opt_enum },
4631 #define DEFHEADING(text)
4632 #include "qemu-options.h"
4640 struct soundhw soundhw
[] = {
4641 #ifdef HAS_AUDIO_CHOICE
4642 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4648 { .init_isa
= pcspk_audio_init
}
4655 "Creative Sound Blaster 16",
4658 { .init_isa
= SB16_init
}
4662 #ifdef CONFIG_CS4231A
4668 { .init_isa
= cs4231a_init
}
4676 "Yamaha YMF262 (OPL3)",
4678 "Yamaha YM3812 (OPL2)",
4682 { .init_isa
= Adlib_init
}
4689 "Gravis Ultrasound GF1",
4692 { .init_isa
= GUS_init
}
4699 "Intel 82801AA AC97 Audio",
4702 { .init_pci
= ac97_init
}
4706 #ifdef CONFIG_ES1370
4709 "ENSONIQ AudioPCI ES1370",
4712 { .init_pci
= es1370_init
}
4716 #endif /* HAS_AUDIO_CHOICE */
4718 { NULL
, NULL
, 0, 0, { NULL
} }
4721 static void select_soundhw (const char *optarg
)
4725 if (*optarg
== '?') {
4728 printf ("Valid sound card names (comma separated):\n");
4729 for (c
= soundhw
; c
->name
; ++c
) {
4730 printf ("%-11s %s\n", c
->name
, c
->descr
);
4732 printf ("\n-soundhw all will enable all of the above\n");
4733 exit (*optarg
!= '?');
4741 if (!strcmp (optarg
, "all")) {
4742 for (c
= soundhw
; c
->name
; ++c
) {
4750 e
= strchr (p
, ',');
4751 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4753 for (c
= soundhw
; c
->name
; ++c
) {
4754 if (!strncmp (c
->name
, p
, l
)) {
4763 "Unknown sound card name (too big to show)\n");
4766 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4771 p
+= l
+ (e
!= NULL
);
4775 goto show_valid_cards
;
4780 static void select_vgahw (const char *p
)
4784 cirrus_vga_enabled
= 0;
4785 std_vga_enabled
= 0;
4788 if (strstart(p
, "std", &opts
)) {
4789 std_vga_enabled
= 1;
4790 } else if (strstart(p
, "cirrus", &opts
)) {
4791 cirrus_vga_enabled
= 1;
4792 } else if (strstart(p
, "vmware", &opts
)) {
4794 } else if (strstart(p
, "xenfb", &opts
)) {
4796 } else if (!strstart(p
, "none", &opts
)) {
4798 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4802 const char *nextopt
;
4804 if (strstart(opts
, ",retrace=", &nextopt
)) {
4806 if (strstart(opts
, "dumb", &nextopt
))
4807 vga_retrace_method
= VGA_RETRACE_DUMB
;
4808 else if (strstart(opts
, "precise", &nextopt
))
4809 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4810 else goto invalid_vga
;
4811 } else goto invalid_vga
;
4817 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4819 exit(STATUS_CONTROL_C_EXIT
);
4824 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4828 if(strlen(str
) != 36)
4831 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4832 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4833 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4839 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4845 #define MAX_NET_CLIENTS 32
4849 static void termsig_handler(int signal
)
4851 qemu_system_shutdown_request();
4854 static void sigchld_handler(int signal
)
4856 waitpid(-1, NULL
, WNOHANG
);
4859 static void sighandler_setup(void)
4861 struct sigaction act
;
4863 memset(&act
, 0, sizeof(act
));
4864 act
.sa_handler
= termsig_handler
;
4865 sigaction(SIGINT
, &act
, NULL
);
4866 sigaction(SIGHUP
, &act
, NULL
);
4867 sigaction(SIGTERM
, &act
, NULL
);
4869 act
.sa_handler
= sigchld_handler
;
4870 act
.sa_flags
= SA_NOCLDSTOP
;
4871 sigaction(SIGCHLD
, &act
, NULL
);
4877 /* Look for support files in the same directory as the executable. */
4878 static char *find_datadir(const char *argv0
)
4884 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
4891 while (p
!= buf
&& *p
!= '\\')
4894 if (access(buf
, R_OK
) == 0) {
4895 return qemu_strdup(buf
);
4901 /* Find a likely location for support files using the location of the binary.
4902 For installed binaries this will be "$bindir/../share/qemu". When
4903 running from the build tree this will be "$bindir/../pc-bios". */
4904 #define SHARE_SUFFIX "/share/qemu"
4905 #define BUILD_SUFFIX "/pc-bios"
4906 static char *find_datadir(const char *argv0
)
4916 #if defined(__linux__)
4919 len
= readlink("/proc/self/exe", buf
, sizeof(buf
) - 1);
4925 #elif defined(__FreeBSD__)
4928 len
= readlink("/proc/curproc/file", buf
, sizeof(buf
) - 1);
4935 /* If we don't have any way of figuring out the actual executable
4936 location then try argv[0]. */
4941 p
= realpath(argv0
, p
);
4949 max_len
= strlen(dir
) +
4950 MAX(strlen(SHARE_SUFFIX
), strlen(BUILD_SUFFIX
)) + 1;
4951 res
= qemu_mallocz(max_len
);
4952 snprintf(res
, max_len
, "%s%s", dir
, SHARE_SUFFIX
);
4953 if (access(res
, R_OK
)) {
4954 snprintf(res
, max_len
, "%s%s", dir
, BUILD_SUFFIX
);
4955 if (access(res
, R_OK
)) {
4969 char *qemu_find_file(int type
, const char *name
)
4975 /* If name contains path separators then try it as a straight path. */
4976 if ((strchr(name
, '/') || strchr(name
, '\\'))
4977 && access(name
, R_OK
) == 0) {
4978 return strdup(name
);
4981 case QEMU_FILE_TYPE_BIOS
:
4984 case QEMU_FILE_TYPE_KEYMAP
:
4985 subdir
= "keymaps/";
4990 len
= strlen(data_dir
) + strlen(name
) + strlen(subdir
) + 2;
4991 buf
= qemu_mallocz(len
);
4992 snprintf(buf
, len
, "%s/%s%s", data_dir
, subdir
, name
);
4993 if (access(buf
, R_OK
)) {
5000 int main(int argc
, char **argv
, char **envp
)
5002 const char *gdbstub_dev
= NULL
;
5003 uint32_t boot_devices_bitmap
= 0;
5005 int snapshot
, linux_boot
, net_boot
;
5006 const char *initrd_filename
;
5007 const char *kernel_filename
, *kernel_cmdline
;
5008 const char *boot_devices
= "";
5010 DisplayChangeListener
*dcl
;
5011 int cyls
, heads
, secs
, translation
;
5012 const char *net_clients
[MAX_NET_CLIENTS
];
5014 const char *bt_opts
[MAX_BT_CMDLINE
];
5018 const char *r
, *optarg
;
5019 CharDriverState
*monitor_hd
= NULL
;
5020 const char *monitor_device
;
5021 const char *serial_devices
[MAX_SERIAL_PORTS
];
5022 int serial_device_index
;
5023 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
5024 int parallel_device_index
;
5025 const char *virtio_consoles
[MAX_VIRTIO_CONSOLES
];
5026 int virtio_console_index
;
5027 const char *loadvm
= NULL
;
5028 QEMUMachine
*machine
;
5029 const char *cpu_model
;
5030 const char *usb_devices
[MAX_USB_CMDLINE
];
5031 int usb_devices_index
;
5036 const char *pid_file
= NULL
;
5037 const char *incoming
= NULL
;
5040 struct passwd
*pwd
= NULL
;
5041 const char *chroot_dir
= NULL
;
5042 const char *run_as
= NULL
;
5045 int show_vnc_port
= 0;
5047 qemu_cache_utils_init(envp
);
5049 LIST_INIT (&vm_change_state_head
);
5052 struct sigaction act
;
5053 sigfillset(&act
.sa_mask
);
5055 act
.sa_handler
= SIG_IGN
;
5056 sigaction(SIGPIPE
, &act
, NULL
);
5059 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
5060 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5061 QEMU to run on a single CPU */
5066 h
= GetCurrentProcess();
5067 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
5068 for(i
= 0; i
< 32; i
++) {
5069 if (mask
& (1 << i
))
5074 SetProcessAffinityMask(h
, mask
);
5080 module_call_init(MODULE_INIT_MACHINE
);
5081 machine
= find_default_machine();
5083 initrd_filename
= NULL
;
5086 kernel_filename
= NULL
;
5087 kernel_cmdline
= "";
5088 cyls
= heads
= secs
= 0;
5089 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5090 monitor_device
= "vc:80Cx24C";
5092 serial_devices
[0] = "vc:80Cx24C";
5093 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
5094 serial_devices
[i
] = NULL
;
5095 serial_device_index
= 0;
5097 parallel_devices
[0] = "vc:80Cx24C";
5098 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
5099 parallel_devices
[i
] = NULL
;
5100 parallel_device_index
= 0;
5102 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++)
5103 virtio_consoles
[i
] = NULL
;
5104 virtio_console_index
= 0;
5106 for (i
= 0; i
< MAX_NODES
; i
++) {
5108 node_cpumask
[i
] = 0;
5111 usb_devices_index
= 0;
5112 assigned_devices_index
= 0;
5126 register_watchdogs();
5134 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
5136 const QEMUOption
*popt
;
5139 /* Treat --foo the same as -foo. */
5142 popt
= qemu_options
;
5145 fprintf(stderr
, "%s: invalid option -- '%s'\n",
5149 if (!strcmp(popt
->name
, r
+ 1))
5153 if (popt
->flags
& HAS_ARG
) {
5154 if (optind
>= argc
) {
5155 fprintf(stderr
, "%s: option '%s' requires an argument\n",
5159 optarg
= argv
[optind
++];
5164 switch(popt
->index
) {
5166 machine
= find_machine(optarg
);
5169 printf("Supported machines are:\n");
5170 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5171 printf("%-10s %s%s\n",
5173 m
->is_default
? " (default)" : "");
5175 exit(*optarg
!= '?');
5178 case QEMU_OPTION_cpu
:
5179 /* hw initialization will check this */
5180 if (*optarg
== '?') {
5181 /* XXX: implement xxx_cpu_list for targets that still miss it */
5182 #if defined(cpu_list)
5183 cpu_list(stdout
, &fprintf
);
5190 case QEMU_OPTION_initrd
:
5191 initrd_filename
= optarg
;
5193 case QEMU_OPTION_hda
:
5195 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
5197 hda_index
= drive_add(optarg
, HD_ALIAS
5198 ",cyls=%d,heads=%d,secs=%d%s",
5199 0, cyls
, heads
, secs
,
5200 translation
== BIOS_ATA_TRANSLATION_LBA
?
5202 translation
== BIOS_ATA_TRANSLATION_NONE
?
5203 ",trans=none" : "");
5205 case QEMU_OPTION_hdb
:
5206 case QEMU_OPTION_hdc
:
5207 case QEMU_OPTION_hdd
:
5208 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
5210 case QEMU_OPTION_drive
:
5211 drive_add(NULL
, "%s", optarg
);
5213 case QEMU_OPTION_mtdblock
:
5214 drive_add(optarg
, MTD_ALIAS
);
5216 case QEMU_OPTION_sd
:
5217 drive_add(optarg
, SD_ALIAS
);
5219 case QEMU_OPTION_pflash
:
5220 drive_add(optarg
, PFLASH_ALIAS
);
5222 case QEMU_OPTION_snapshot
:
5225 case QEMU_OPTION_hdachs
:
5229 cyls
= strtol(p
, (char **)&p
, 0);
5230 if (cyls
< 1 || cyls
> 16383)
5235 heads
= strtol(p
, (char **)&p
, 0);
5236 if (heads
< 1 || heads
> 16)
5241 secs
= strtol(p
, (char **)&p
, 0);
5242 if (secs
< 1 || secs
> 63)
5246 if (!strcmp(p
, "none"))
5247 translation
= BIOS_ATA_TRANSLATION_NONE
;
5248 else if (!strcmp(p
, "lba"))
5249 translation
= BIOS_ATA_TRANSLATION_LBA
;
5250 else if (!strcmp(p
, "auto"))
5251 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5254 } else if (*p
!= '\0') {
5256 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5259 if (hda_index
!= -1)
5260 snprintf(drives_opt
[hda_index
].opt
,
5261 sizeof(drives_opt
[hda_index
].opt
),
5262 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
5263 0, cyls
, heads
, secs
,
5264 translation
== BIOS_ATA_TRANSLATION_LBA
?
5266 translation
== BIOS_ATA_TRANSLATION_NONE
?
5267 ",trans=none" : "");
5270 case QEMU_OPTION_numa
:
5271 if (nb_numa_nodes
>= MAX_NODES
) {
5272 fprintf(stderr
, "qemu: too many NUMA nodes\n");
5277 case QEMU_OPTION_nographic
:
5278 display_type
= DT_NOGRAPHIC
;
5280 #ifdef CONFIG_CURSES
5281 case QEMU_OPTION_curses
:
5282 display_type
= DT_CURSES
;
5285 case QEMU_OPTION_portrait
:
5288 case QEMU_OPTION_kernel
:
5289 kernel_filename
= optarg
;
5291 case QEMU_OPTION_append
:
5292 kernel_cmdline
= optarg
;
5294 case QEMU_OPTION_cdrom
:
5295 drive_add(optarg
, CDROM_ALIAS
);
5297 case QEMU_OPTION_boot
:
5298 boot_devices
= optarg
;
5299 /* We just do some generic consistency checks */
5301 /* Could easily be extended to 64 devices if needed */
5304 boot_devices_bitmap
= 0;
5305 for (p
= boot_devices
; *p
!= '\0'; p
++) {
5306 /* Allowed boot devices are:
5307 * a b : floppy disk drives
5308 * c ... f : IDE disk drives
5309 * g ... m : machine implementation dependant drives
5310 * n ... p : network devices
5311 * It's up to each machine implementation to check
5312 * if the given boot devices match the actual hardware
5313 * implementation and firmware features.
5315 if (*p
< 'a' || *p
> 'q') {
5316 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
5319 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
5321 "Boot device '%c' was given twice\n",*p
);
5324 boot_devices_bitmap
|= 1 << (*p
- 'a');
5328 case QEMU_OPTION_fda
:
5329 case QEMU_OPTION_fdb
:
5330 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
5333 case QEMU_OPTION_no_fd_bootchk
:
5337 case QEMU_OPTION_net
:
5338 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
5339 fprintf(stderr
, "qemu: too many network clients\n");
5342 net_clients
[nb_net_clients
] = optarg
;
5346 case QEMU_OPTION_tftp
:
5347 tftp_prefix
= optarg
;
5349 case QEMU_OPTION_bootp
:
5350 bootp_filename
= optarg
;
5353 case QEMU_OPTION_smb
:
5354 net_slirp_smb(optarg
);
5357 case QEMU_OPTION_redir
:
5358 net_slirp_redir(NULL
, optarg
, NULL
);
5361 case QEMU_OPTION_bt
:
5362 if (nb_bt_opts
>= MAX_BT_CMDLINE
) {
5363 fprintf(stderr
, "qemu: too many bluetooth options\n");
5366 bt_opts
[nb_bt_opts
++] = optarg
;
5369 case QEMU_OPTION_audio_help
:
5373 case QEMU_OPTION_soundhw
:
5374 select_soundhw (optarg
);
5380 case QEMU_OPTION_version
:
5384 case QEMU_OPTION_m
: {
5388 value
= strtoul(optarg
, &ptr
, 10);
5390 case 0: case 'M': case 'm':
5397 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5401 /* On 32-bit hosts, QEMU is limited by virtual address space */
5402 if (value
> (2047 << 20)
5403 #ifndef CONFIG_KQEMU
5404 && HOST_LONG_BITS
== 32
5407 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5410 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5411 fprintf(stderr
, "qemu: ram size too large\n");
5420 const CPULogItem
*item
;
5422 mask
= cpu_str_to_log_mask(optarg
);
5424 printf("Log items (comma separated):\n");
5425 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5426 printf("%-10s %s\n", item
->name
, item
->help
);
5434 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5436 case QEMU_OPTION_gdb
:
5437 gdbstub_dev
= optarg
;
5442 case QEMU_OPTION_bios
:
5445 case QEMU_OPTION_singlestep
:
5453 keyboard_layout
= optarg
;
5456 case QEMU_OPTION_localtime
:
5459 case QEMU_OPTION_vga
:
5460 select_vgahw (optarg
);
5462 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5468 w
= strtol(p
, (char **)&p
, 10);
5471 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5477 h
= strtol(p
, (char **)&p
, 10);
5482 depth
= strtol(p
, (char **)&p
, 10);
5483 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5484 depth
!= 24 && depth
!= 32)
5486 } else if (*p
== '\0') {
5487 depth
= graphic_depth
;
5494 graphic_depth
= depth
;
5498 case QEMU_OPTION_echr
:
5501 term_escape_char
= strtol(optarg
, &r
, 0);
5503 printf("Bad argument to echr\n");
5506 case QEMU_OPTION_monitor
:
5507 monitor_device
= optarg
;
5509 case QEMU_OPTION_serial
:
5510 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
5511 fprintf(stderr
, "qemu: too many serial ports\n");
5514 serial_devices
[serial_device_index
] = optarg
;
5515 serial_device_index
++;
5517 case QEMU_OPTION_watchdog
:
5518 i
= select_watchdog(optarg
);
5520 exit (i
== 1 ? 1 : 0);
5522 case QEMU_OPTION_watchdog_action
:
5523 if (select_watchdog_action(optarg
) == -1) {
5524 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5528 case QEMU_OPTION_virtiocon
:
5529 if (virtio_console_index
>= MAX_VIRTIO_CONSOLES
) {
5530 fprintf(stderr
, "qemu: too many virtio consoles\n");
5533 virtio_consoles
[virtio_console_index
] = optarg
;
5534 virtio_console_index
++;
5536 case QEMU_OPTION_parallel
:
5537 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
5538 fprintf(stderr
, "qemu: too many parallel ports\n");
5541 parallel_devices
[parallel_device_index
] = optarg
;
5542 parallel_device_index
++;
5544 case QEMU_OPTION_loadvm
:
5547 case QEMU_OPTION_full_screen
:
5551 case QEMU_OPTION_no_frame
:
5554 case QEMU_OPTION_alt_grab
:
5557 case QEMU_OPTION_no_quit
:
5560 case QEMU_OPTION_sdl
:
5561 display_type
= DT_SDL
;
5564 case QEMU_OPTION_pidfile
:
5568 case QEMU_OPTION_win2k_hack
:
5569 win2k_install_hack
= 1;
5571 case QEMU_OPTION_rtc_td_hack
:
5574 case QEMU_OPTION_acpitable
:
5575 if(acpi_table_add(optarg
) < 0) {
5576 fprintf(stderr
, "Wrong acpi table provided\n");
5580 case QEMU_OPTION_smbios
:
5581 if(smbios_entry_add(optarg
) < 0) {
5582 fprintf(stderr
, "Wrong smbios provided\n");
5588 case QEMU_OPTION_no_kqemu
:
5591 case QEMU_OPTION_kernel_kqemu
:
5596 case QEMU_OPTION_enable_kvm
:
5604 case QEMU_OPTION_no_kvm
:
5607 case QEMU_OPTION_no_kvm_irqchip
: {
5612 case QEMU_OPTION_no_kvm_pit
: {
5616 case QEMU_OPTION_no_kvm_pit_reinjection
: {
5617 kvm_pit_reinject
= 0;
5620 case QEMU_OPTION_enable_nesting
: {
5624 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5625 case QEMU_OPTION_pcidevice
:
5626 if (assigned_devices_index
>= MAX_DEV_ASSIGN_CMDLINE
) {
5627 fprintf(stderr
, "Too many assigned devices\n");
5630 assigned_devices
[assigned_devices_index
] = optarg
;
5631 assigned_devices_index
++;
5635 case QEMU_OPTION_usb
:
5638 case QEMU_OPTION_usbdevice
:
5640 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
5641 fprintf(stderr
, "Too many USB devices\n");
5644 usb_devices
[usb_devices_index
] = optarg
;
5645 usb_devices_index
++;
5647 case QEMU_OPTION_smp
:
5648 smp_cpus
= atoi(optarg
);
5650 fprintf(stderr
, "Invalid number of CPUs\n");
5654 case QEMU_OPTION_vnc
:
5655 display_type
= DT_VNC
;
5656 vnc_display
= optarg
;
5659 case QEMU_OPTION_no_acpi
:
5662 case QEMU_OPTION_no_hpet
:
5666 case QEMU_OPTION_no_reboot
:
5669 case QEMU_OPTION_no_shutdown
:
5672 case QEMU_OPTION_show_cursor
:
5675 case QEMU_OPTION_uuid
:
5676 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5677 fprintf(stderr
, "Fail to parse UUID string."
5678 " Wrong format.\n");
5683 case QEMU_OPTION_daemonize
:
5687 case QEMU_OPTION_option_rom
:
5688 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5689 fprintf(stderr
, "Too many option ROMs\n");
5692 option_rom
[nb_option_roms
] = optarg
;
5695 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5696 case QEMU_OPTION_semihosting
:
5697 semihosting_enabled
= 1;
5700 case QEMU_OPTION_tdf
:
5703 case QEMU_OPTION_kvm_shadow_memory
:
5704 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
5706 case QEMU_OPTION_mempath
:
5710 case QEMU_OPTION_mem_prealloc
:
5711 mem_prealloc
= !mem_prealloc
;
5714 case QEMU_OPTION_name
:
5717 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5718 case QEMU_OPTION_prom_env
:
5719 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5720 fprintf(stderr
, "Too many prom variables\n");
5723 prom_envs
[nb_prom_envs
] = optarg
;
5728 case QEMU_OPTION_old_param
:
5732 case QEMU_OPTION_clock
:
5733 configure_alarms(optarg
);
5735 case QEMU_OPTION_startdate
:
5738 time_t rtc_start_date
;
5739 if (!strcmp(optarg
, "now")) {
5740 rtc_date_offset
= -1;
5742 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
5750 } else if (sscanf(optarg
, "%d-%d-%d",
5753 &tm
.tm_mday
) == 3) {
5762 rtc_start_date
= mktimegm(&tm
);
5763 if (rtc_start_date
== -1) {
5765 fprintf(stderr
, "Invalid date format. Valid format are:\n"
5766 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5769 rtc_date_offset
= time(NULL
) - rtc_start_date
;
5773 case QEMU_OPTION_tb_size
:
5774 tb_size
= strtol(optarg
, NULL
, 0);
5778 case QEMU_OPTION_icount
:
5780 if (strcmp(optarg
, "auto") == 0) {
5781 icount_time_shift
= -1;
5783 icount_time_shift
= strtol(optarg
, NULL
, 0);
5786 case QEMU_OPTION_incoming
:
5790 case QEMU_OPTION_chroot
:
5791 chroot_dir
= optarg
;
5793 case QEMU_OPTION_runas
:
5796 case QEMU_OPTION_nvram
:
5801 case QEMU_OPTION_xen_domid
:
5802 xen_domid
= atoi(optarg
);
5804 case QEMU_OPTION_xen_create
:
5805 xen_mode
= XEN_CREATE
;
5807 case QEMU_OPTION_xen_attach
:
5808 xen_mode
= XEN_ATTACH
;
5815 /* If no data_dir is specified then try to find it relative to the
5818 data_dir
= find_datadir(argv
[0]);
5820 /* If all else fails use the install patch specified when building. */
5822 data_dir
= CONFIG_QEMU_SHAREDIR
;
5825 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5826 if (kvm_allowed
&& kqemu_allowed
) {
5828 "You can not enable both KVM and kqemu at the same time\n");
5833 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5834 if (smp_cpus
> machine
->max_cpus
) {
5835 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5836 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5841 if (display_type
== DT_NOGRAPHIC
) {
5842 if (serial_device_index
== 0)
5843 serial_devices
[0] = "stdio";
5844 if (parallel_device_index
== 0)
5845 parallel_devices
[0] = "null";
5846 if (strncmp(monitor_device
, "vc", 2) == 0)
5847 monitor_device
= "stdio";
5854 if (pipe(fds
) == -1)
5865 len
= read(fds
[0], &status
, 1);
5866 if (len
== -1 && (errno
== EINTR
))
5871 else if (status
== 1) {
5872 fprintf(stderr
, "Could not acquire pidfile\n");
5889 signal(SIGTSTP
, SIG_IGN
);
5890 signal(SIGTTOU
, SIG_IGN
);
5891 signal(SIGTTIN
, SIG_IGN
);
5895 if (kvm_enabled()) {
5896 if (kvm_qemu_init() < 0) {
5897 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
5898 #ifdef NO_CPU_EMULATION
5899 fprintf(stderr
, "Compiled with --disable-cpu-emulation, exiting.\n");
5907 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5910 write(fds
[1], &status
, 1);
5912 fprintf(stderr
, "Could not acquire pid file\n");
5921 if (qemu_init_main_loop()) {
5922 fprintf(stderr
, "qemu_init_main_loop failed\n");
5925 linux_boot
= (kernel_filename
!= NULL
);
5926 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5928 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5929 fprintf(stderr
, "-append only allowed with -kernel option\n");
5933 if (!linux_boot
&& initrd_filename
!= NULL
) {
5934 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5938 /* boot to floppy or the default cd if no hard disk defined yet */
5939 if (!boot_devices
[0]) {
5940 boot_devices
= "cad";
5942 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5945 if (init_timer_alarm() < 0) {
5946 fprintf(stderr
, "could not initialize alarm timer\n");
5949 if (use_icount
&& icount_time_shift
< 0) {
5951 /* 125MIPS seems a reasonable initial guess at the guest speed.
5952 It will be corrected fairly quickly anyway. */
5953 icount_time_shift
= 3;
5954 init_icount_adjust();
5961 /* init network clients */
5962 if (nb_net_clients
== 0) {
5963 /* if no clients, we use a default config */
5964 net_clients
[nb_net_clients
++] = "nic";
5966 net_clients
[nb_net_clients
++] = "user";
5970 for(i
= 0;i
< nb_net_clients
; i
++) {
5971 if (net_client_parse(net_clients
[i
]) < 0)
5977 /* XXX: this should be moved in the PC machine instantiation code */
5978 if (net_boot
!= 0) {
5980 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
5981 const char *model
= nd_table
[i
].model
;
5984 if (net_boot
& (1 << i
)) {
5987 snprintf(buf
, sizeof(buf
), "pxe-%s.bin", model
);
5988 filename
= qemu_find_file(QEMU_FILE_TYPE_BIOS
, buf
);
5989 if (filename
&& get_image_size(filename
) > 0) {
5990 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5991 fprintf(stderr
, "Too many option ROMs\n");
5994 option_rom
[nb_option_roms
] = qemu_strdup(buf
);
5999 qemu_free(filename
);
6004 fprintf(stderr
, "No valid PXE rom found for network device\n");
6010 /* init the bluetooth world */
6011 for (i
= 0; i
< nb_bt_opts
; i
++)
6012 if (bt_parse(bt_opts
[i
]))
6015 /* init the memory */
6017 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
6019 if (kvm_enabled()) {
6020 if (kvm_qemu_create_context() < 0) {
6021 fprintf(stderr
, "Could not create KVM context\n");
6027 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
6028 guest ram allocation. It needs to go away. */
6029 if (kqemu_allowed
) {
6030 kqemu_phys_ram_size
= ram_size
+ 8 * 1024 * 1024 + 4 * 1024 * 1024;
6031 kqemu_phys_ram_base
= qemu_vmalloc(kqemu_phys_ram_size
);
6032 if (!kqemu_phys_ram_base
) {
6033 fprintf(stderr
, "Could not allocate physical memory\n");
6039 /* init the dynamic translator */
6040 cpu_exec_init_all(tb_size
* 1024 * 1024);
6044 /* we always create the cdrom drive, even if no disk is there */
6046 if (nb_drives_opt
< MAX_DRIVES
)
6047 drive_add(NULL
, CDROM_ALIAS
);
6049 /* we always create at least one floppy */
6051 if (nb_drives_opt
< MAX_DRIVES
)
6052 drive_add(NULL
, FD_ALIAS
, 0);
6054 /* we always create one sd slot, even if no card is in it */
6056 if (nb_drives_opt
< MAX_DRIVES
)
6057 drive_add(NULL
, SD_ALIAS
);
6059 /* open the virtual block devices
6060 * note that migration with device
6061 * hot add/remove is broken.
6063 for(i
= 0; i
< nb_drives_opt
; i
++)
6064 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
6067 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
6068 register_savevm_live("ram", 0, 3, ram_save_live
, NULL
, ram_load
, NULL
);
6071 /* must be after terminal init, SDL library changes signal handlers */
6075 /* Maintain compatibility with multiple stdio monitors */
6076 if (!strcmp(monitor_device
,"stdio")) {
6077 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6078 const char *devname
= serial_devices
[i
];
6079 if (devname
&& !strcmp(devname
,"mon:stdio")) {
6080 monitor_device
= NULL
;
6082 } else if (devname
&& !strcmp(devname
,"stdio")) {
6083 monitor_device
= NULL
;
6084 serial_devices
[i
] = "mon:stdio";
6090 if (nb_numa_nodes
> 0) {
6093 if (nb_numa_nodes
> smp_cpus
) {
6094 nb_numa_nodes
= smp_cpus
;
6097 /* If no memory size if given for any node, assume the default case
6098 * and distribute the available memory equally across all nodes
6100 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6101 if (node_mem
[i
] != 0)
6104 if (i
== nb_numa_nodes
) {
6105 uint64_t usedmem
= 0;
6107 /* On Linux, the each node's border has to be 8MB aligned,
6108 * the final node gets the rest.
6110 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
6111 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
6112 usedmem
+= node_mem
[i
];
6114 node_mem
[i
] = ram_size
- usedmem
;
6117 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6118 if (node_cpumask
[i
] != 0)
6121 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6122 * must cope with this anyway, because there are BIOSes out there in
6123 * real machines which also use this scheme.
6125 if (i
== nb_numa_nodes
) {
6126 for (i
= 0; i
< smp_cpus
; i
++) {
6127 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
6133 if (kvm_enabled()) {
6136 ret
= kvm_init(smp_cpus
);
6138 fprintf(stderr
, "failed to initialize KVM\n");
6144 if (monitor_device
) {
6145 monitor_hd
= qemu_chr_open("monitor", monitor_device
, NULL
);
6147 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
6152 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6153 const char *devname
= serial_devices
[i
];
6154 if (devname
&& strcmp(devname
, "none")) {
6156 snprintf(label
, sizeof(label
), "serial%d", i
);
6157 serial_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6158 if (!serial_hds
[i
]) {
6159 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
6166 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
6167 const char *devname
= parallel_devices
[i
];
6168 if (devname
&& strcmp(devname
, "none")) {
6170 snprintf(label
, sizeof(label
), "parallel%d", i
);
6171 parallel_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6172 if (!parallel_hds
[i
]) {
6173 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
6180 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
6181 const char *devname
= virtio_consoles
[i
];
6182 if (devname
&& strcmp(devname
, "none")) {
6184 snprintf(label
, sizeof(label
), "virtcon%d", i
);
6185 virtcon_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6186 if (!virtcon_hds
[i
]) {
6187 fprintf(stderr
, "qemu: could not open virtio console '%s'\n",
6194 module_call_init(MODULE_INIT_DEVICE
);
6199 machine
->init(ram_size
, boot_devices
,
6200 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
6203 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
6204 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6205 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
6211 current_machine
= machine
;
6213 /* Set KVM's vcpu state to qemu's initial CPUState. */
6214 if (kvm_enabled()) {
6217 ret
= kvm_sync_vcpus();
6219 fprintf(stderr
, "failed to initialize vcpus\n");
6224 /* init USB devices */
6226 for(i
= 0; i
< usb_devices_index
; i
++) {
6227 if (usb_device_add(usb_devices
[i
], 0) < 0) {
6228 fprintf(stderr
, "Warning: could not add USB device %s\n",
6235 dumb_display_init();
6236 /* just use the first displaystate for the moment */
6239 if (display_type
== DT_DEFAULT
) {
6240 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6241 display_type
= DT_SDL
;
6243 display_type
= DT_VNC
;
6244 vnc_display
= "localhost:0,to=99";
6250 switch (display_type
) {
6253 #if defined(CONFIG_CURSES)
6255 curses_display_init(ds
, full_screen
);
6258 #if defined(CONFIG_SDL)
6260 sdl_display_init(ds
, full_screen
, no_frame
);
6262 #elif defined(CONFIG_COCOA)
6264 cocoa_display_init(ds
, full_screen
);
6268 vnc_display_init(ds
);
6269 if (vnc_display_open(ds
, vnc_display
) < 0)
6272 if (show_vnc_port
) {
6273 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
6281 dcl
= ds
->listeners
;
6282 while (dcl
!= NULL
) {
6283 if (dcl
->dpy_refresh
!= NULL
) {
6284 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
6285 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
6290 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
6291 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
6292 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
6295 text_consoles_set_display(display_state
);
6296 qemu_chr_initial_reset();
6298 if (monitor_device
&& monitor_hd
)
6299 monitor_init(monitor_hd
, MONITOR_USE_READLINE
| MONITOR_IS_DEFAULT
);
6301 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6302 const char *devname
= serial_devices
[i
];
6303 if (devname
&& strcmp(devname
, "none")) {
6305 snprintf(label
, sizeof(label
), "serial%d", i
);
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")) {
6315 snprintf(label
, sizeof(label
), "parallel%d", i
);
6316 if (strstart(devname
, "vc", 0))
6317 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
6321 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
6322 const char *devname
= virtio_consoles
[i
];
6323 if (virtcon_hds
[i
] && devname
) {
6325 snprintf(label
, sizeof(label
), "virtcon%d", i
);
6326 if (strstart(devname
, "vc", 0))
6327 qemu_chr_printf(virtcon_hds
[i
], "virtio console%d\r\n", i
);
6331 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
6332 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
6338 do_loadvm(cur_mon
, loadvm
);
6341 autostart
= 0; /* fixme how to deal with -daemonize */
6342 qemu_start_incoming_migration(incoming
);
6354 len
= write(fds
[1], &status
, 1);
6355 if (len
== -1 && (errno
== EINTR
))
6362 TFR(fd
= open("/dev/null", O_RDWR
));
6368 pwd
= getpwnam(run_as
);
6370 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
6376 if (chroot(chroot_dir
) < 0) {
6377 fprintf(stderr
, "chroot failed\n");
6384 if (setgid(pwd
->pw_gid
) < 0) {
6385 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
6388 if (setuid(pwd
->pw_uid
) < 0) {
6389 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
6392 if (setuid(0) != -1) {
6393 fprintf(stderr
, "Dropping privileges failed\n");