4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
32 /* Needed early for HOST_BSD etc. */
33 #include "config-host.h"
38 #include <sys/times.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
47 #if defined(__NetBSD__)
48 #include <net/if_tap.h>
51 #include <linux/if_tun.h>
53 #include <arpa/inet.h>
56 #include <sys/select.h>
59 #if defined(__FreeBSD__) || defined(__DragonFly__)
64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65 #include <freebsd/stdlib.h>
70 #include <linux/rtc.h>
72 /* For the benefit of older linux systems which don't supply it,
73 we use a local copy of hpet.h. */
74 /* #include <linux/hpet.h> */
77 #include <linux/ppdev.h>
78 #include <linux/parport.h>
82 #include <sys/ethernet.h>
83 #include <sys/sockio.h>
84 #include <netinet/arp.h>
85 #include <netinet/in.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip_icmp.h> // must come after ip.h
89 #include <netinet/udp.h>
90 #include <netinet/tcp.h>
98 #if defined(__OpenBSD__)
102 #if defined(CONFIG_VDE)
103 #include <libvdeplug.h>
109 #include <sys/timeb.h>
110 #include <mmsystem.h>
111 #define getopt_long_only getopt_long
112 #define memalign(align, size) malloc(size)
116 #if defined(__APPLE__) || defined(main)
118 int qemu_main(int argc
, char **argv
, char **envp
);
119 int main(int argc
, char **argv
)
121 return qemu_main(argc
, argv
, NULL
);
124 #define main qemu_main
126 #endif /* CONFIG_SDL */
130 #define main qemu_main
131 #endif /* CONFIG_COCOA */
134 #include "hw/boards.h"
136 #include "hw/pcmcia.h"
138 #include "hw/audiodev.h"
142 #include "hw/watchdog.h"
143 #include "hw/smbios.h"
151 #include "qemu-timer.h"
152 #include "qemu-char.h"
153 #include "cache-utils.h"
156 #include "audio/audio.h"
157 #include "migration.h"
160 #include "qemu-option.h"
161 #include "qemu-kvm.h"
162 #include "hw/device-assignment.h"
166 #include "exec-all.h"
168 #include "qemu_socket.h"
170 #include "slirp/libslirp.h"
172 //#define DEBUG_UNUSED_IOPORT
173 //#define DEBUG_IOPORT
175 //#define DEBUG_SLIRP
179 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
181 # define LOG_IOPORT(...) do { } while (0)
184 #define DEFAULT_RAM_SIZE 128
186 /* Max number of USB devices that can be specified on the commandline. */
187 #define MAX_USB_CMDLINE 8
189 /* Max number of bluetooth switches on the commandline. */
190 #define MAX_BT_CMDLINE 10
192 /* XXX: use a two level table to limit memory usage */
193 #define MAX_IOPORTS 65536
195 static const char *data_dir
;
196 const char *bios_name
= NULL
;
197 static void *ioport_opaque
[MAX_IOPORTS
];
198 static IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
199 static IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
200 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
201 to store the VM snapshots */
202 DriveInfo drives_table
[MAX_DRIVES
+1];
204 int extboot_drive
= -1;
205 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
206 static DisplayState
*display_state
;
207 DisplayType display_type
= DT_DEFAULT
;
208 const char* keyboard_layout
= NULL
;
209 int64_t ticks_per_sec
;
212 NICInfo nd_table
[MAX_NICS
];
214 static int autostart
;
215 static int rtc_utc
= 1;
216 static int rtc_date_offset
= -1; /* -1 means no change */
217 int cirrus_vga_enabled
= 1;
218 int std_vga_enabled
= 0;
219 int vmsvga_enabled
= 0;
220 int xenfb_enabled
= 0;
222 int graphic_width
= 1024;
223 int graphic_height
= 768;
224 int graphic_depth
= 8;
226 int graphic_width
= 800;
227 int graphic_height
= 600;
228 int graphic_depth
= 15;
230 static int full_screen
= 0;
232 static int no_frame
= 0;
235 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
236 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
237 CharDriverState
*virtcon_hds
[MAX_VIRTIO_CONSOLES
];
239 int win2k_install_hack
= 0;
244 const char *assigned_devices
[MAX_DEV_ASSIGN_CMDLINE
];
245 int assigned_devices_index
;
247 const char *vnc_display
;
248 int acpi_enabled
= 1;
250 int virtio_balloon
= 1;
251 const char *virtio_balloon_devaddr
;
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_next_param_value(char *buf
, int buf_size
,
1845 const char *tag
, const char **pstr
)
1852 p
= get_opt_name(option
, sizeof(option
), p
, '=');
1856 if (!strcmp(tag
, option
)) {
1857 *pstr
= get_opt_value(buf
, buf_size
, p
);
1858 if (**pstr
== ',') {
1863 p
= get_opt_value(NULL
, 0, p
);
1872 int get_param_value(char *buf
, int buf_size
,
1873 const char *tag
, const char *str
)
1875 return get_next_param_value(buf
, buf_size
, tag
, &str
);
1878 int check_params(char *buf
, int buf_size
,
1879 const char * const *params
, const char *str
)
1885 while (*p
!= '\0') {
1886 p
= get_opt_name(buf
, buf_size
, p
, '=');
1891 for (i
= 0; params
[i
] != NULL
; i
++) {
1892 if (!strcmp(params
[i
], buf
)) {
1896 if (params
[i
] == NULL
) {
1899 p
= get_opt_value(NULL
, 0, p
);
1908 /***********************************************************/
1909 /* Bluetooth support */
1912 static struct HCIInfo
*hci_table
[MAX_NICS
];
1914 static struct bt_vlan_s
{
1915 struct bt_scatternet_s net
;
1917 struct bt_vlan_s
*next
;
1920 /* find or alloc a new bluetooth "VLAN" */
1921 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1923 struct bt_vlan_s
**pvlan
, *vlan
;
1924 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1928 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1930 pvlan
= &first_bt_vlan
;
1931 while (*pvlan
!= NULL
)
1932 pvlan
= &(*pvlan
)->next
;
1937 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1941 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1946 static struct HCIInfo null_hci
= {
1947 .cmd_send
= null_hci_send
,
1948 .sco_send
= null_hci_send
,
1949 .acl_send
= null_hci_send
,
1950 .bdaddr_set
= null_hci_addr_set
,
1953 struct HCIInfo
*qemu_next_hci(void)
1955 if (cur_hci
== nb_hcis
)
1958 return hci_table
[cur_hci
++];
1961 static struct HCIInfo
*hci_init(const char *str
)
1964 struct bt_scatternet_s
*vlan
= 0;
1966 if (!strcmp(str
, "null"))
1969 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
1971 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
1972 else if (!strncmp(str
, "hci", 3)) {
1975 if (!strncmp(str
+ 3, ",vlan=", 6)) {
1976 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
1981 vlan
= qemu_find_bt_vlan(0);
1983 return bt_new_hci(vlan
);
1986 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
1991 static int bt_hci_parse(const char *str
)
1993 struct HCIInfo
*hci
;
1996 if (nb_hcis
>= MAX_NICS
) {
1997 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
2001 hci
= hci_init(str
);
2010 bdaddr
.b
[5] = 0x56 + nb_hcis
;
2011 hci
->bdaddr_set(hci
, bdaddr
.b
);
2013 hci_table
[nb_hcis
++] = hci
;
2018 static void bt_vhci_add(int vlan_id
)
2020 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
2023 fprintf(stderr
, "qemu: warning: adding a VHCI to "
2024 "an empty scatternet %i\n", vlan_id
);
2026 bt_vhci_init(bt_new_hci(vlan
));
2029 static struct bt_device_s
*bt_device_add(const char *opt
)
2031 struct bt_scatternet_s
*vlan
;
2033 char *endp
= strstr(opt
, ",vlan=");
2034 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
2037 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
2040 vlan_id
= strtol(endp
+ 6, &endp
, 0);
2042 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
2047 vlan
= qemu_find_bt_vlan(vlan_id
);
2050 fprintf(stderr
, "qemu: warning: adding a slave device to "
2051 "an empty scatternet %i\n", vlan_id
);
2053 if (!strcmp(devname
, "keyboard"))
2054 return bt_keyboard_init(vlan
);
2056 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
2060 static int bt_parse(const char *opt
)
2062 const char *endp
, *p
;
2065 if (strstart(opt
, "hci", &endp
)) {
2066 if (!*endp
|| *endp
== ',') {
2068 if (!strstart(endp
, ",vlan=", 0))
2071 return bt_hci_parse(opt
);
2073 } else if (strstart(opt
, "vhci", &endp
)) {
2074 if (!*endp
|| *endp
== ',') {
2076 if (strstart(endp
, ",vlan=", &p
)) {
2077 vlan
= strtol(p
, (char **) &endp
, 0);
2079 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
2083 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
2092 } else if (strstart(opt
, "device:", &endp
))
2093 return !bt_device_add(endp
);
2095 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
2099 /***********************************************************/
2100 /* QEMU Block devices */
2102 #define HD_ALIAS "index=%d,media=disk"
2103 #define CDROM_ALIAS "index=2,media=cdrom"
2104 #define FD_ALIAS "index=%d,if=floppy"
2105 #define PFLASH_ALIAS "if=pflash"
2106 #define MTD_ALIAS "if=mtd"
2107 #define SD_ALIAS "index=0,if=sd"
2109 static int drive_opt_get_free_idx(void)
2113 for (index
= 0; index
< MAX_DRIVES
; index
++)
2114 if (!drives_opt
[index
].used
) {
2115 drives_opt
[index
].used
= 1;
2122 static int drive_get_free_idx(void)
2126 for (index
= 0; index
< MAX_DRIVES
; index
++)
2127 if (!drives_table
[index
].used
) {
2128 drives_table
[index
].used
= 1;
2135 int drive_add(const char *file
, const char *fmt
, ...)
2138 int index
= drive_opt_get_free_idx();
2140 if (nb_drives_opt
>= MAX_DRIVES
|| index
== -1) {
2141 fprintf(stderr
, "qemu: too many drives\n");
2145 drives_opt
[index
].file
= file
;
2147 vsnprintf(drives_opt
[index
].opt
,
2148 sizeof(drives_opt
[0].opt
), fmt
, ap
);
2155 void drive_remove(int index
)
2157 drives_opt
[index
].used
= 0;
2161 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
2165 /* seek interface, bus and unit */
2167 for (index
= 0; index
< MAX_DRIVES
; index
++)
2168 if (drives_table
[index
].type
== type
&&
2169 drives_table
[index
].bus
== bus
&&
2170 drives_table
[index
].unit
== unit
&&
2171 drives_table
[index
].used
)
2177 int drive_get_max_bus(BlockInterfaceType type
)
2183 for (index
= 0; index
< nb_drives
; index
++) {
2184 if(drives_table
[index
].type
== type
&&
2185 drives_table
[index
].bus
> max_bus
)
2186 max_bus
= drives_table
[index
].bus
;
2191 const char *drive_get_serial(BlockDriverState
*bdrv
)
2195 for (index
= 0; index
< nb_drives
; index
++)
2196 if (drives_table
[index
].bdrv
== bdrv
)
2197 return drives_table
[index
].serial
;
2202 BlockInterfaceErrorAction
drive_get_onerror(BlockDriverState
*bdrv
)
2206 for (index
= 0; index
< nb_drives
; index
++)
2207 if (drives_table
[index
].bdrv
== bdrv
)
2208 return drives_table
[index
].onerror
;
2210 return BLOCK_ERR_STOP_ENOSPC
;
2213 static void bdrv_format_print(void *opaque
, const char *name
)
2215 fprintf(stderr
, " %s", name
);
2218 void drive_uninit(BlockDriverState
*bdrv
)
2222 for (i
= 0; i
< MAX_DRIVES
; i
++)
2223 if (drives_table
[i
].bdrv
== bdrv
) {
2224 drives_table
[i
].bdrv
= NULL
;
2225 drives_table
[i
].used
= 0;
2226 drive_remove(drives_table
[i
].drive_opt_idx
);
2232 int drive_init(struct drive_opt
*arg
, int snapshot
, void *opaque
)
2238 const char *mediastr
= "";
2239 BlockInterfaceType type
;
2240 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
2241 int bus_id
, unit_id
;
2242 int cyls
, heads
, secs
, translation
;
2243 BlockDriverState
*bdrv
;
2244 BlockDriver
*drv
= NULL
;
2245 QEMUMachine
*machine
= opaque
;
2249 int bdrv_flags
, onerror
;
2250 const char *devaddr
;
2251 int drives_table_idx
;
2252 char *str
= arg
->opt
;
2253 static const char * const params
[] = { "bus", "unit", "if", "index",
2254 "cyls", "heads", "secs", "trans",
2255 "media", "snapshot", "file",
2256 "cache", "format", "serial",
2261 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
2262 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
2268 cyls
= heads
= secs
= 0;
2271 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2275 if (machine
->use_scsi
) {
2277 max_devs
= MAX_SCSI_DEVS
;
2278 pstrcpy(devname
, sizeof(devname
), "scsi");
2281 max_devs
= MAX_IDE_DEVS
;
2282 pstrcpy(devname
, sizeof(devname
), "ide");
2286 /* extract parameters */
2288 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
2289 bus_id
= strtol(buf
, NULL
, 0);
2291 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
2296 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
2297 unit_id
= strtol(buf
, NULL
, 0);
2299 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
2304 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
2305 pstrcpy(devname
, sizeof(devname
), buf
);
2306 if (!strcmp(buf
, "ide")) {
2308 max_devs
= MAX_IDE_DEVS
;
2309 } else if (!strcmp(buf
, "scsi")) {
2311 max_devs
= MAX_SCSI_DEVS
;
2312 } else if (!strcmp(buf
, "floppy")) {
2315 } else if (!strcmp(buf
, "pflash")) {
2318 } else if (!strcmp(buf
, "mtd")) {
2321 } else if (!strcmp(buf
, "sd")) {
2324 } else if (!strcmp(buf
, "virtio")) {
2327 } else if (!strcmp(buf
, "xen")) {
2331 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
2336 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
2337 index
= strtol(buf
, NULL
, 0);
2339 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
2344 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
2345 cyls
= strtol(buf
, NULL
, 0);
2348 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
2349 heads
= strtol(buf
, NULL
, 0);
2352 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
2353 secs
= strtol(buf
, NULL
, 0);
2356 if (cyls
|| heads
|| secs
) {
2357 if (cyls
< 1 || cyls
> 16383) {
2358 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
2361 if (heads
< 1 || heads
> 16) {
2362 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
2365 if (secs
< 1 || secs
> 63) {
2366 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
2371 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
2374 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2378 if (!strcmp(buf
, "none"))
2379 translation
= BIOS_ATA_TRANSLATION_NONE
;
2380 else if (!strcmp(buf
, "lba"))
2381 translation
= BIOS_ATA_TRANSLATION_LBA
;
2382 else if (!strcmp(buf
, "auto"))
2383 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2385 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
2390 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
2391 if (!strcmp(buf
, "disk")) {
2393 } else if (!strcmp(buf
, "cdrom")) {
2394 if (cyls
|| secs
|| heads
) {
2396 "qemu: '%s' invalid physical CHS format\n", str
);
2399 media
= MEDIA_CDROM
;
2401 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
2406 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
2407 if (!strcmp(buf
, "on"))
2409 else if (!strcmp(buf
, "off"))
2412 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
2417 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
2418 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2420 else if (!strcmp(buf
, "writethrough"))
2422 else if (!strcmp(buf
, "writeback"))
2425 fprintf(stderr
, "qemu: invalid cache option\n");
2430 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
2431 if (strcmp(buf
, "?") == 0) {
2432 fprintf(stderr
, "qemu: Supported formats:");
2433 bdrv_iterate_format(bdrv_format_print
, NULL
);
2434 fprintf(stderr
, "\n");
2437 drv
= bdrv_find_format(buf
);
2439 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2444 if (get_param_value(buf
, sizeof(buf
), "boot", str
)) {
2445 if (!strcmp(buf
, "on")) {
2446 if (extboot_drive
!= -1) {
2447 fprintf(stderr
, "qemu: two bootable drives specified\n");
2450 extboot_drive
= nb_drives
;
2451 } else if (strcmp(buf
, "off")) {
2452 fprintf(stderr
, "qemu: '%s' invalid boot option\n", str
);
2457 if (arg
->file
== NULL
)
2458 get_param_value(file
, sizeof(file
), "file", str
);
2460 pstrcpy(file
, sizeof(file
), arg
->file
);
2462 if (!get_param_value(serial
, sizeof(serial
), "serial", str
))
2463 memset(serial
, 0, sizeof(serial
));
2465 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2466 if (get_param_value(buf
, sizeof(serial
), "werror", str
)) {
2467 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2468 fprintf(stderr
, "werror is no supported by this format\n");
2471 if (!strcmp(buf
, "ignore"))
2472 onerror
= BLOCK_ERR_IGNORE
;
2473 else if (!strcmp(buf
, "enospc"))
2474 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2475 else if (!strcmp(buf
, "stop"))
2476 onerror
= BLOCK_ERR_STOP_ANY
;
2477 else if (!strcmp(buf
, "report"))
2478 onerror
= BLOCK_ERR_REPORT
;
2480 fprintf(stderr
, "qemu: '%s' invalid write error action\n", buf
);
2486 if (get_param_value(buf
, sizeof(buf
), "addr", str
)) {
2487 if (type
!= IF_VIRTIO
) {
2488 fprintf(stderr
, "addr is not supported by in '%s'\n", str
);
2491 devaddr
= strdup(buf
);
2494 /* compute bus and unit according index */
2497 if (bus_id
!= 0 || unit_id
!= -1) {
2499 "qemu: '%s' index cannot be used with bus and unit\n", str
);
2507 unit_id
= index
% max_devs
;
2508 bus_id
= index
/ max_devs
;
2512 /* if user doesn't specify a unit_id,
2513 * try to find the first free
2516 if (unit_id
== -1) {
2518 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
2520 if (max_devs
&& unit_id
>= max_devs
) {
2521 unit_id
-= max_devs
;
2529 if (max_devs
&& unit_id
>= max_devs
) {
2530 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
2531 str
, unit_id
, max_devs
- 1);
2536 * ignore multiple definitions
2539 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
2544 if (type
== IF_IDE
|| type
== IF_SCSI
)
2545 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2547 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
2548 devname
, bus_id
, mediastr
, unit_id
);
2550 snprintf(buf
, sizeof(buf
), "%s%s%i",
2551 devname
, mediastr
, unit_id
);
2552 bdrv
= bdrv_new(buf
);
2553 drives_table_idx
= drive_get_free_idx();
2554 drives_table
[drives_table_idx
].bdrv
= bdrv
;
2555 drives_table
[drives_table_idx
].devaddr
= devaddr
;
2556 drives_table
[drives_table_idx
].type
= type
;
2557 drives_table
[drives_table_idx
].bus
= bus_id
;
2558 drives_table
[drives_table_idx
].unit
= unit_id
;
2559 drives_table
[drives_table_idx
].onerror
= onerror
;
2560 drives_table
[drives_table_idx
].drive_opt_idx
= arg
- drives_opt
;
2561 strncpy(drives_table
[drives_table_idx
].serial
, serial
, sizeof(serial
));
2571 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
2572 bdrv_set_translation_hint(bdrv
, translation
);
2576 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
2581 /* FIXME: This isn't really a floppy, but it's a reasonable
2584 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
2597 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2598 cache
= 2; /* always use write-back with snapshot */
2600 if (cache
== 0) /* no caching */
2601 bdrv_flags
|= BDRV_O_NOCACHE
;
2602 else if (cache
== 2) /* write-back */
2603 bdrv_flags
|= BDRV_O_CACHE_WB
;
2604 else if (cache
== 3) /* not specified */
2605 bdrv_flags
|= BDRV_O_CACHE_DEF
;
2606 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0) {
2607 fprintf(stderr
, "qemu: could not open disk image %s\n",
2611 if (bdrv_key_required(bdrv
))
2613 return drives_table_idx
;
2616 static void numa_add(const char *optarg
)
2620 unsigned long long value
, endvalue
;
2623 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2624 if (!strcmp(option
, "node")) {
2625 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2626 nodenr
= nb_numa_nodes
;
2628 nodenr
= strtoull(option
, NULL
, 10);
2631 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2632 node_mem
[nodenr
] = 0;
2634 value
= strtoull(option
, &endptr
, 0);
2636 case 0: case 'M': case 'm':
2643 node_mem
[nodenr
] = value
;
2645 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2646 node_cpumask
[nodenr
] = 0;
2648 value
= strtoull(option
, &endptr
, 10);
2651 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2653 if (*endptr
== '-') {
2654 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2655 if (endvalue
>= 63) {
2658 "only 63 CPUs in NUMA mode supported.\n");
2660 value
= (1 << (endvalue
+ 1)) - (1 << value
);
2665 node_cpumask
[nodenr
] = value
;
2672 /***********************************************************/
2675 static USBPort
*used_usb_ports
;
2676 static USBPort
*free_usb_ports
;
2678 /* ??? Maybe change this to register a hub to keep track of the topology. */
2679 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
2680 usb_attachfn attach
)
2682 port
->opaque
= opaque
;
2683 port
->index
= index
;
2684 port
->attach
= attach
;
2685 port
->next
= free_usb_ports
;
2686 free_usb_ports
= port
;
2689 int usb_device_add_dev(USBDevice
*dev
)
2693 /* Find a USB port to add the device to. */
2694 port
= free_usb_ports
;
2698 /* Create a new hub and chain it on. */
2699 free_usb_ports
= NULL
;
2700 port
->next
= used_usb_ports
;
2701 used_usb_ports
= port
;
2703 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
2704 usb_attach(port
, hub
);
2705 port
= free_usb_ports
;
2708 free_usb_ports
= port
->next
;
2709 port
->next
= used_usb_ports
;
2710 used_usb_ports
= port
;
2711 usb_attach(port
, dev
);
2715 static void usb_msd_password_cb(void *opaque
, int err
)
2717 USBDevice
*dev
= opaque
;
2720 usb_device_add_dev(dev
);
2722 dev
->handle_destroy(dev
);
2725 static int usb_device_add(const char *devname
, int is_hotplug
)
2730 if (!free_usb_ports
)
2733 if (strstart(devname
, "host:", &p
)) {
2734 dev
= usb_host_device_open(p
);
2735 } else if (!strcmp(devname
, "mouse")) {
2736 dev
= usb_mouse_init();
2737 } else if (!strcmp(devname
, "tablet")) {
2738 dev
= usb_tablet_init();
2739 } else if (!strcmp(devname
, "keyboard")) {
2740 dev
= usb_keyboard_init();
2741 } else if (strstart(devname
, "disk:", &p
)) {
2742 BlockDriverState
*bs
;
2744 dev
= usb_msd_init(p
);
2747 bs
= usb_msd_get_bdrv(dev
);
2748 if (bdrv_key_required(bs
)) {
2751 monitor_read_bdrv_key_start(cur_mon
, bs
, usb_msd_password_cb
,
2756 } else if (!strcmp(devname
, "wacom-tablet")) {
2757 dev
= usb_wacom_init();
2758 } else if (strstart(devname
, "serial:", &p
)) {
2759 dev
= usb_serial_init(p
);
2760 #ifdef CONFIG_BRLAPI
2761 } else if (!strcmp(devname
, "braille")) {
2762 dev
= usb_baum_init();
2764 } else if (strstart(devname
, "net:", &p
)) {
2767 if (net_client_init(NULL
, "nic", p
) < 0)
2769 nd_table
[nic
].model
= "usb";
2770 dev
= usb_net_init(&nd_table
[nic
]);
2771 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2772 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2773 bt_new_hci(qemu_find_bt_vlan(0)));
2780 return usb_device_add_dev(dev
);
2783 int usb_device_del_addr(int bus_num
, int addr
)
2789 if (!used_usb_ports
)
2795 lastp
= &used_usb_ports
;
2796 port
= used_usb_ports
;
2797 while (port
&& port
->dev
->addr
!= addr
) {
2798 lastp
= &port
->next
;
2806 *lastp
= port
->next
;
2807 usb_attach(port
, NULL
);
2808 dev
->handle_destroy(dev
);
2809 port
->next
= free_usb_ports
;
2810 free_usb_ports
= port
;
2814 static int usb_device_del(const char *devname
)
2819 if (strstart(devname
, "host:", &p
))
2820 return usb_host_device_close(p
);
2822 if (!used_usb_ports
)
2825 p
= strchr(devname
, '.');
2828 bus_num
= strtoul(devname
, NULL
, 0);
2829 addr
= strtoul(p
+ 1, NULL
, 0);
2831 return usb_device_del_addr(bus_num
, addr
);
2834 void do_usb_add(Monitor
*mon
, const char *devname
)
2836 usb_device_add(devname
, 1);
2839 void do_usb_del(Monitor
*mon
, const char *devname
)
2841 usb_device_del(devname
);
2844 void usb_info(Monitor
*mon
)
2848 const char *speed_str
;
2851 monitor_printf(mon
, "USB support not enabled\n");
2855 for (port
= used_usb_ports
; port
; port
= port
->next
) {
2859 switch(dev
->speed
) {
2863 case USB_SPEED_FULL
:
2866 case USB_SPEED_HIGH
:
2873 monitor_printf(mon
, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2874 0, dev
->addr
, speed_str
, dev
->devname
);
2878 /***********************************************************/
2879 /* PCMCIA/Cardbus */
2881 static struct pcmcia_socket_entry_s
{
2882 PCMCIASocket
*socket
;
2883 struct pcmcia_socket_entry_s
*next
;
2884 } *pcmcia_sockets
= 0;
2886 void pcmcia_socket_register(PCMCIASocket
*socket
)
2888 struct pcmcia_socket_entry_s
*entry
;
2890 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2891 entry
->socket
= socket
;
2892 entry
->next
= pcmcia_sockets
;
2893 pcmcia_sockets
= entry
;
2896 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2898 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2900 ptr
= &pcmcia_sockets
;
2901 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2902 if (entry
->socket
== socket
) {
2908 void pcmcia_info(Monitor
*mon
)
2910 struct pcmcia_socket_entry_s
*iter
;
2912 if (!pcmcia_sockets
)
2913 monitor_printf(mon
, "No PCMCIA sockets\n");
2915 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2916 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2917 iter
->socket
->attached
? iter
->socket
->card_string
:
2921 /***********************************************************/
2922 /* register display */
2924 struct DisplayAllocator default_allocator
= {
2925 defaultallocator_create_displaysurface
,
2926 defaultallocator_resize_displaysurface
,
2927 defaultallocator_free_displaysurface
2930 void register_displaystate(DisplayState
*ds
)
2940 DisplayState
*get_displaystate(void)
2942 return display_state
;
2945 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
2947 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
2948 return ds
->allocator
;
2953 static void dumb_display_init(void)
2955 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
2956 ds
->allocator
= &default_allocator
;
2957 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
2958 register_displaystate(ds
);
2961 /***********************************************************/
2964 typedef struct IOHandlerRecord
{
2966 IOCanRWHandler
*fd_read_poll
;
2968 IOHandler
*fd_write
;
2971 /* temporary data */
2973 struct IOHandlerRecord
*next
;
2976 static IOHandlerRecord
*first_io_handler
;
2978 /* XXX: fd_read_poll should be suppressed, but an API change is
2979 necessary in the character devices to suppress fd_can_read(). */
2980 int qemu_set_fd_handler2(int fd
,
2981 IOCanRWHandler
*fd_read_poll
,
2983 IOHandler
*fd_write
,
2986 IOHandlerRecord
**pioh
, *ioh
;
2988 if (!fd_read
&& !fd_write
) {
2989 pioh
= &first_io_handler
;
2994 if (ioh
->fd
== fd
) {
3001 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3005 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
3006 ioh
->next
= first_io_handler
;
3007 first_io_handler
= ioh
;
3010 ioh
->fd_read_poll
= fd_read_poll
;
3011 ioh
->fd_read
= fd_read
;
3012 ioh
->fd_write
= fd_write
;
3013 ioh
->opaque
= opaque
;
3016 qemu_notify_event();
3020 int qemu_set_fd_handler(int fd
,
3022 IOHandler
*fd_write
,
3025 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
3029 /***********************************************************/
3030 /* Polling handling */
3032 typedef struct PollingEntry
{
3035 struct PollingEntry
*next
;
3038 static PollingEntry
*first_polling_entry
;
3040 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
3042 PollingEntry
**ppe
, *pe
;
3043 pe
= qemu_mallocz(sizeof(PollingEntry
));
3045 pe
->opaque
= opaque
;
3046 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
3051 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
3053 PollingEntry
**ppe
, *pe
;
3054 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
3056 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
3064 /***********************************************************/
3065 /* Wait objects support */
3066 typedef struct WaitObjects
{
3068 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
3069 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
3070 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
3073 static WaitObjects wait_objects
= {0};
3075 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
3077 WaitObjects
*w
= &wait_objects
;
3079 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
3081 w
->events
[w
->num
] = handle
;
3082 w
->func
[w
->num
] = func
;
3083 w
->opaque
[w
->num
] = opaque
;
3088 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
3091 WaitObjects
*w
= &wait_objects
;
3094 for (i
= 0; i
< w
->num
; i
++) {
3095 if (w
->events
[i
] == handle
)
3098 w
->events
[i
] = w
->events
[i
+ 1];
3099 w
->func
[i
] = w
->func
[i
+ 1];
3100 w
->opaque
[i
] = w
->opaque
[i
+ 1];
3108 /***********************************************************/
3109 /* ram save/restore */
3111 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
3115 v
= qemu_get_byte(f
);
3118 if (qemu_get_buffer(f
, buf
, len
) != len
)
3122 v
= qemu_get_byte(f
);
3123 memset(buf
, v
, len
);
3129 if (qemu_file_has_error(f
))
3135 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
3140 if (qemu_get_be32(f
) != last_ram_offset
)
3142 for(i
= 0; i
< last_ram_offset
; i
+= TARGET_PAGE_SIZE
) {
3143 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3145 ret
= ram_get_page(f
, qemu_get_ram_ptr(i
), TARGET_PAGE_SIZE
);
3152 #define BDRV_HASH_BLOCK_SIZE 1024
3153 #define IOBUF_SIZE 4096
3154 #define RAM_CBLOCK_MAGIC 0xfabe
3156 typedef struct RamDecompressState
{
3159 uint8_t buf
[IOBUF_SIZE
];
3160 } RamDecompressState
;
3162 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
3165 memset(s
, 0, sizeof(*s
));
3167 ret
= inflateInit(&s
->zstream
);
3173 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
3177 s
->zstream
.avail_out
= len
;
3178 s
->zstream
.next_out
= buf
;
3179 while (s
->zstream
.avail_out
> 0) {
3180 if (s
->zstream
.avail_in
== 0) {
3181 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
3183 clen
= qemu_get_be16(s
->f
);
3184 if (clen
> IOBUF_SIZE
)
3186 qemu_get_buffer(s
->f
, s
->buf
, clen
);
3187 s
->zstream
.avail_in
= clen
;
3188 s
->zstream
.next_in
= s
->buf
;
3190 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
3191 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
3198 static void ram_decompress_close(RamDecompressState
*s
)
3200 inflateEnd(&s
->zstream
);
3203 #define RAM_SAVE_FLAG_FULL 0x01
3204 #define RAM_SAVE_FLAG_COMPRESS 0x02
3205 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3206 #define RAM_SAVE_FLAG_PAGE 0x08
3207 #define RAM_SAVE_FLAG_EOS 0x10
3209 static int is_dup_page(uint8_t *page
, uint8_t ch
)
3211 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
3212 uint32_t *array
= (uint32_t *)page
;
3215 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
3216 if (array
[i
] != val
)
3223 static int ram_save_block(QEMUFile
*f
)
3225 static ram_addr_t current_addr
= 0;
3226 ram_addr_t saved_addr
= current_addr
;
3227 ram_addr_t addr
= 0;
3230 while (addr
< last_ram_offset
) {
3231 if (kvm_enabled() && current_addr
== 0) {
3233 r
= kvm_update_dirty_pages_log();
3235 fprintf(stderr
, "%s: update dirty pages log failed %d\n", __FUNCTION__
, r
);
3236 qemu_file_set_error(f
);
3240 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
3243 cpu_physical_memory_reset_dirty(current_addr
,
3244 current_addr
+ TARGET_PAGE_SIZE
,
3245 MIGRATION_DIRTY_FLAG
);
3247 p
= qemu_get_ram_ptr(current_addr
);
3249 if (is_dup_page(p
, *p
)) {
3250 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
3251 qemu_put_byte(f
, *p
);
3253 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
3254 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
3260 addr
+= TARGET_PAGE_SIZE
;
3261 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
3267 static uint64_t bytes_transferred
= 0;
3269 static ram_addr_t
ram_save_remaining(void)
3272 ram_addr_t count
= 0;
3274 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3275 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3282 uint64_t ram_bytes_remaining(void)
3284 return ram_save_remaining() * TARGET_PAGE_SIZE
;
3287 uint64_t ram_bytes_transferred(void)
3289 return bytes_transferred
;
3292 uint64_t ram_bytes_total(void)
3294 return last_ram_offset
;
3297 static int ram_save_live(QEMUFile
*f
, int stage
, void *opaque
)
3300 uint64_t bytes_transferred_last
;
3302 uint64_t expected_time
= 0;
3304 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX
) != 0) {
3305 qemu_file_set_error(f
);
3310 /* Make sure all dirty bits are set */
3311 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3312 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3313 cpu_physical_memory_set_dirty(addr
);
3316 /* Enable dirty memory tracking */
3317 cpu_physical_memory_set_dirty_tracking(1);
3319 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
3322 bytes_transferred_last
= bytes_transferred
;
3323 bwidth
= get_clock();
3325 while (!qemu_file_rate_limit(f
)) {
3328 ret
= ram_save_block(f
);
3329 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
3330 if (ret
== 0) /* no more blocks */
3334 bwidth
= get_clock() - bwidth
;
3335 bwidth
= (bytes_transferred
- bytes_transferred_last
) / bwidth
;
3337 /* if we haven't transferred anything this round, force expected_time to a
3338 * a very high value, but without crashing */
3342 /* try transferring iterative blocks of memory */
3346 /* flush all remaining blocks regardless of rate limiting */
3347 while (ram_save_block(f
) != 0) {
3348 bytes_transferred
+= TARGET_PAGE_SIZE
;
3350 cpu_physical_memory_set_dirty_tracking(0);
3353 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3355 expected_time
= ram_save_remaining() * TARGET_PAGE_SIZE
/ bwidth
;
3357 return (stage
== 2) && (expected_time
<= migrate_max_downtime());
3360 static int ram_load_dead(QEMUFile
*f
, void *opaque
)
3362 RamDecompressState s1
, *s
= &s1
;
3366 if (ram_decompress_open(s
, f
) < 0)
3368 for(i
= 0; i
< last_ram_offset
; i
+= BDRV_HASH_BLOCK_SIZE
) {
3369 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
3371 if (ram_decompress_buf(s
, buf
, 1) < 0) {
3372 fprintf(stderr
, "Error while reading ram block header\n");
3376 if (ram_decompress_buf(s
, qemu_get_ram_ptr(i
),
3377 BDRV_HASH_BLOCK_SIZE
) < 0) {
3378 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
3383 printf("Error block header\n");
3387 ram_decompress_close(s
);
3392 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
3397 if (version_id
== 1)
3398 return ram_load_v1(f
, opaque
);
3400 if (version_id
== 2) {
3401 if (qemu_get_be32(f
) != last_ram_offset
)
3403 return ram_load_dead(f
, opaque
);
3406 if (version_id
!= 3)
3410 addr
= qemu_get_be64(f
);
3412 flags
= addr
& ~TARGET_PAGE_MASK
;
3413 addr
&= TARGET_PAGE_MASK
;
3415 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
3416 if (addr
!= last_ram_offset
)
3420 if (flags
& RAM_SAVE_FLAG_FULL
) {
3421 if (ram_load_dead(f
, opaque
) < 0)
3425 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
3426 uint8_t ch
= qemu_get_byte(f
);
3427 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
3430 (!kvm_enabled() || kvm_has_sync_mmu())) {
3431 madvise(qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
, MADV_DONTNEED
);
3434 } else if (flags
& RAM_SAVE_FLAG_PAGE
)
3435 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
3436 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
3441 void qemu_service_io(void)
3443 qemu_notify_event();
3446 /***********************************************************/
3447 /* bottom halves (can be seen as timers which expire ASAP) */
3458 static QEMUBH
*first_bh
= NULL
;
3460 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
3463 bh
= qemu_mallocz(sizeof(QEMUBH
));
3465 bh
->opaque
= opaque
;
3466 bh
->next
= first_bh
;
3471 int qemu_bh_poll(void)
3477 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3478 if (!bh
->deleted
&& bh
->scheduled
) {
3487 /* remove deleted bhs */
3501 void qemu_bh_schedule_idle(QEMUBH
*bh
)
3509 void qemu_bh_schedule(QEMUBH
*bh
)
3515 /* stop the currently executing CPU to execute the BH ASAP */
3516 qemu_notify_event();
3519 void qemu_bh_cancel(QEMUBH
*bh
)
3524 void qemu_bh_delete(QEMUBH
*bh
)
3530 static void qemu_bh_update_timeout(int *timeout
)
3534 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3535 if (!bh
->deleted
&& bh
->scheduled
) {
3537 /* idle bottom halves will be polled at least
3539 *timeout
= MIN(10, *timeout
);
3541 /* non-idle bottom halves will be executed
3550 /***********************************************************/
3551 /* machine registration */
3553 static QEMUMachine
*first_machine
= NULL
;
3554 QEMUMachine
*current_machine
= NULL
;
3556 int qemu_register_machine(QEMUMachine
*m
)
3559 pm
= &first_machine
;
3567 static QEMUMachine
*find_machine(const char *name
)
3571 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3572 if (!strcmp(m
->name
, name
))
3578 static QEMUMachine
*find_default_machine(void)
3582 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3583 if (m
->is_default
) {
3590 /***********************************************************/
3591 /* main execution loop */
3593 static void gui_update(void *opaque
)
3595 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3596 DisplayState
*ds
= opaque
;
3597 DisplayChangeListener
*dcl
= ds
->listeners
;
3601 while (dcl
!= NULL
) {
3602 if (dcl
->gui_timer_interval
&&
3603 dcl
->gui_timer_interval
< interval
)
3604 interval
= dcl
->gui_timer_interval
;
3607 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3610 static void nographic_update(void *opaque
)
3612 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3614 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3617 struct vm_change_state_entry
{
3618 VMChangeStateHandler
*cb
;
3620 LIST_ENTRY (vm_change_state_entry
) entries
;
3623 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3625 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3628 VMChangeStateEntry
*e
;
3630 e
= qemu_mallocz(sizeof (*e
));
3634 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3638 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3640 LIST_REMOVE (e
, entries
);
3644 static void vm_state_notify(int running
, int reason
)
3646 VMChangeStateEntry
*e
;
3648 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3649 e
->cb(e
->opaque
, running
, reason
);
3653 static void resume_all_vcpus(void);
3654 static void pause_all_vcpus(void);
3661 vm_state_notify(1, 0);
3662 qemu_rearm_alarm_timer(alarm_timer
);
3667 /* reset/shutdown handler */
3669 typedef struct QEMUResetEntry
{
3670 QEMUResetHandler
*func
;
3672 struct QEMUResetEntry
*next
;
3675 static QEMUResetEntry
*first_reset_entry
;
3676 static int reset_requested
;
3677 static int shutdown_requested
;
3678 static int powerdown_requested
;
3679 static int debug_requested
;
3680 static int vmstop_requested
;
3682 int qemu_no_shutdown(void)
3684 int r
= no_shutdown
;
3689 int qemu_shutdown_requested(void)
3691 int r
= shutdown_requested
;
3692 shutdown_requested
= 0;
3696 int qemu_reset_requested(void)
3698 int r
= reset_requested
;
3699 reset_requested
= 0;
3703 int qemu_powerdown_requested(void)
3705 int r
= powerdown_requested
;
3706 powerdown_requested
= 0;
3710 static int qemu_debug_requested(void)
3712 int r
= debug_requested
;
3713 debug_requested
= 0;
3717 static int qemu_vmstop_requested(void)
3719 int r
= vmstop_requested
;
3720 vmstop_requested
= 0;
3724 static void do_vm_stop(int reason
)
3727 cpu_disable_ticks();
3730 vm_state_notify(0, reason
);
3734 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3736 QEMUResetEntry
**pre
, *re
;
3738 pre
= &first_reset_entry
;
3739 while (*pre
!= NULL
)
3740 pre
= &(*pre
)->next
;
3741 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3743 re
->opaque
= opaque
;
3748 void qemu_system_reset(void)
3752 /* reset all devices */
3753 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
3754 re
->func(re
->opaque
);
3758 void qemu_system_reset_request(void)
3761 shutdown_requested
= 1;
3763 reset_requested
= 1;
3765 if (cpu_single_env
) {
3766 qemu_kvm_cpu_stop(cpu_single_env
);
3768 qemu_notify_event();
3771 void qemu_system_shutdown_request(void)
3773 shutdown_requested
= 1;
3774 qemu_notify_event();
3777 void qemu_system_powerdown_request(void)
3779 powerdown_requested
= 1;
3780 qemu_notify_event();
3783 #ifdef CONFIG_IOTHREAD
3784 static void qemu_system_vmstop_request(int reason
)
3786 vmstop_requested
= reason
;
3787 qemu_notify_event();
3792 static int io_thread_fd
= -1;
3794 static void qemu_event_increment(void)
3796 static const char byte
= 0;
3798 if (io_thread_fd
== -1)
3801 write(io_thread_fd
, &byte
, sizeof(byte
));
3804 static void qemu_event_read(void *opaque
)
3806 int fd
= (unsigned long)opaque
;
3809 /* Drain the notify pipe */
3812 len
= read(fd
, buffer
, sizeof(buffer
));
3813 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
3816 static int qemu_event_init(void)
3825 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3829 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3833 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3834 (void *)(unsigned long)fds
[0]);
3836 io_thread_fd
= fds
[1];
3845 HANDLE qemu_event_handle
;
3847 static void dummy_event_handler(void *opaque
)
3851 static int qemu_event_init(void)
3853 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3854 if (!qemu_event_handle
) {
3855 perror("Failed CreateEvent");
3858 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3862 static void qemu_event_increment(void)
3864 SetEvent(qemu_event_handle
);
3868 static int cpu_can_run(CPUState
*env
)
3877 #ifndef CONFIG_IOTHREAD
3878 static int qemu_init_main_loop(void)
3880 return qemu_event_init();
3883 void qemu_init_vcpu(void *_env
)
3885 CPUState
*env
= _env
;
3892 int qemu_cpu_self(void *env
)
3897 static void resume_all_vcpus(void)
3901 static void pause_all_vcpus(void)
3905 void qemu_cpu_kick(void *env
)
3910 void qemu_notify_event(void)
3912 CPUState
*env
= cpu_single_env
;
3914 if (kvm_enabled()) {
3915 qemu_kvm_notify_work();
3921 if (env
->kqemu_enabled
)
3922 kqemu_cpu_interrupt(env
);
3927 #define qemu_mutex_lock_iothread() do { } while (0)
3928 #define qemu_mutex_unlock_iothread() do { } while (0)
3930 void vm_stop(int reason
)
3935 #else /* CONFIG_IOTHREAD */
3937 #include "qemu-thread.h"
3939 QemuMutex qemu_global_mutex
;
3940 static QemuMutex qemu_fair_mutex
;
3942 static QemuThread io_thread
;
3944 static QemuThread
*tcg_cpu_thread
;
3945 static QemuCond
*tcg_halt_cond
;
3947 static int qemu_system_ready
;
3949 static QemuCond qemu_cpu_cond
;
3951 static QemuCond qemu_system_cond
;
3952 static QemuCond qemu_pause_cond
;
3954 static void block_io_signals(void);
3955 static void unblock_io_signals(void);
3956 static int tcg_has_work(void);
3958 static int qemu_init_main_loop(void)
3962 ret
= qemu_event_init();
3966 qemu_cond_init(&qemu_pause_cond
);
3967 qemu_mutex_init(&qemu_fair_mutex
);
3968 qemu_mutex_init(&qemu_global_mutex
);
3969 qemu_mutex_lock(&qemu_global_mutex
);
3971 unblock_io_signals();
3972 qemu_thread_self(&io_thread
);
3977 static void qemu_wait_io_event(CPUState
*env
)
3979 while (!tcg_has_work())
3980 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3982 qemu_mutex_unlock(&qemu_global_mutex
);
3985 * Users of qemu_global_mutex can be starved, having no chance
3986 * to acquire it since this path will get to it first.
3987 * So use another lock to provide fairness.
3989 qemu_mutex_lock(&qemu_fair_mutex
);
3990 qemu_mutex_unlock(&qemu_fair_mutex
);
3992 qemu_mutex_lock(&qemu_global_mutex
);
3996 qemu_cond_signal(&qemu_pause_cond
);
4000 static int qemu_cpu_exec(CPUState
*env
);
4002 static void *kvm_cpu_thread_fn(void *arg
)
4004 CPUState
*env
= arg
;
4007 qemu_thread_self(env
->thread
);
4009 /* signal CPU creation */
4010 qemu_mutex_lock(&qemu_global_mutex
);
4012 qemu_cond_signal(&qemu_cpu_cond
);
4014 /* and wait for machine initialization */
4015 while (!qemu_system_ready
)
4016 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
4019 if (cpu_can_run(env
))
4021 qemu_wait_io_event(env
);
4027 static void tcg_cpu_exec(void);
4029 static void *tcg_cpu_thread_fn(void *arg
)
4031 CPUState
*env
= arg
;
4034 qemu_thread_self(env
->thread
);
4036 /* signal CPU creation */
4037 qemu_mutex_lock(&qemu_global_mutex
);
4038 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4040 qemu_cond_signal(&qemu_cpu_cond
);
4042 /* and wait for machine initialization */
4043 while (!qemu_system_ready
)
4044 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
4048 qemu_wait_io_event(cur_cpu
);
4054 void qemu_cpu_kick(void *_env
)
4056 CPUState
*env
= _env
;
4057 qemu_cond_broadcast(env
->halt_cond
);
4059 qemu_thread_signal(env
->thread
, SIGUSR1
);
4062 int qemu_cpu_self(void *env
)
4064 return (cpu_single_env
!= NULL
);
4067 static void cpu_signal(int sig
)
4070 cpu_exit(cpu_single_env
);
4073 static void block_io_signals(void)
4076 struct sigaction sigact
;
4079 sigaddset(&set
, SIGUSR2
);
4080 sigaddset(&set
, SIGIO
);
4081 sigaddset(&set
, SIGALRM
);
4082 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
4085 sigaddset(&set
, SIGUSR1
);
4086 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
4088 memset(&sigact
, 0, sizeof(sigact
));
4089 sigact
.sa_handler
= cpu_signal
;
4090 sigaction(SIGUSR1
, &sigact
, NULL
);
4093 static void unblock_io_signals(void)
4098 sigaddset(&set
, SIGUSR2
);
4099 sigaddset(&set
, SIGIO
);
4100 sigaddset(&set
, SIGALRM
);
4101 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
4104 sigaddset(&set
, SIGUSR1
);
4105 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
4108 static void qemu_signal_lock(unsigned int msecs
)
4110 qemu_mutex_lock(&qemu_fair_mutex
);
4112 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
4113 qemu_thread_signal(tcg_cpu_thread
, SIGUSR1
);
4114 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
4117 qemu_mutex_unlock(&qemu_fair_mutex
);
4120 static void qemu_mutex_lock_iothread(void)
4122 if (kvm_enabled()) {
4123 qemu_mutex_lock(&qemu_fair_mutex
);
4124 qemu_mutex_lock(&qemu_global_mutex
);
4125 qemu_mutex_unlock(&qemu_fair_mutex
);
4127 qemu_signal_lock(100);
4130 static void qemu_mutex_unlock_iothread(void)
4132 qemu_mutex_unlock(&qemu_global_mutex
);
4135 static int all_vcpus_paused(void)
4137 CPUState
*penv
= first_cpu
;
4142 penv
= (CPUState
*)penv
->next_cpu
;
4148 static void pause_all_vcpus(void)
4150 CPUState
*penv
= first_cpu
;
4154 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4155 qemu_cpu_kick(penv
);
4156 penv
= (CPUState
*)penv
->next_cpu
;
4159 while (!all_vcpus_paused()) {
4160 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
4163 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4164 penv
= (CPUState
*)penv
->next_cpu
;
4169 static void resume_all_vcpus(void)
4171 CPUState
*penv
= first_cpu
;
4176 qemu_thread_signal(penv
->thread
, SIGUSR1
);
4177 qemu_cpu_kick(penv
);
4178 penv
= (CPUState
*)penv
->next_cpu
;
4182 static void tcg_init_vcpu(void *_env
)
4184 CPUState
*env
= _env
;
4185 /* share a single thread for all cpus with TCG */
4186 if (!tcg_cpu_thread
) {
4187 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
4188 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
4189 qemu_cond_init(env
->halt_cond
);
4190 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
4191 while (env
->created
== 0)
4192 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
4193 tcg_cpu_thread
= env
->thread
;
4194 tcg_halt_cond
= env
->halt_cond
;
4196 env
->thread
= tcg_cpu_thread
;
4197 env
->halt_cond
= tcg_halt_cond
;
4201 static void kvm_start_vcpu(CPUState
*env
)
4204 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
4205 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
4206 qemu_cond_init(env
->halt_cond
);
4207 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
4208 while (env
->created
== 0)
4209 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
4212 void qemu_init_vcpu(void *_env
)
4214 CPUState
*env
= _env
;
4217 kvm_start_vcpu(env
);
4222 void qemu_notify_event(void)
4224 qemu_event_increment();
4227 void vm_stop(int reason
)
4230 qemu_thread_self(&me
);
4232 if (!qemu_thread_equal(&me
, &io_thread
)) {
4233 qemu_system_vmstop_request(reason
);
4235 * FIXME: should not return to device code in case
4236 * vm_stop() has been requested.
4238 if (cpu_single_env
) {
4239 cpu_exit(cpu_single_env
);
4240 cpu_single_env
->stop
= 1;
4251 static void host_main_loop_wait(int *timeout
)
4257 /* XXX: need to suppress polling by better using win32 events */
4259 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
4260 ret
|= pe
->func(pe
->opaque
);
4264 WaitObjects
*w
= &wait_objects
;
4266 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
4267 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
4268 if (w
->func
[ret
- WAIT_OBJECT_0
])
4269 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
4271 /* Check for additional signaled events */
4272 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
4274 /* Check if event is signaled */
4275 ret2
= WaitForSingleObject(w
->events
[i
], 0);
4276 if(ret2
== WAIT_OBJECT_0
) {
4278 w
->func
[i
](w
->opaque
[i
]);
4279 } else if (ret2
== WAIT_TIMEOUT
) {
4281 err
= GetLastError();
4282 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
4285 } else if (ret
== WAIT_TIMEOUT
) {
4287 err
= GetLastError();
4288 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
4295 static void host_main_loop_wait(int *timeout
)
4300 void main_loop_wait(int timeout
)
4302 IOHandlerRecord
*ioh
;
4303 fd_set rfds
, wfds
, xfds
;
4307 qemu_bh_update_timeout(&timeout
);
4309 host_main_loop_wait(&timeout
);
4311 /* poll any events */
4312 /* XXX: separate device handlers from system ones */
4317 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4321 (!ioh
->fd_read_poll
||
4322 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
4323 FD_SET(ioh
->fd
, &rfds
);
4327 if (ioh
->fd_write
) {
4328 FD_SET(ioh
->fd
, &wfds
);
4334 tv
.tv_sec
= timeout
/ 1000;
4335 tv
.tv_usec
= (timeout
% 1000) * 1000;
4337 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
4339 ret
= qemu_select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
4341 IOHandlerRecord
**pioh
;
4343 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4344 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
4345 ioh
->fd_read(ioh
->opaque
);
4346 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
4347 FD_CLR(ioh
->fd
, &rfds
);
4349 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
4350 ioh
->fd_write(ioh
->opaque
);
4354 /* remove deleted IO handlers */
4355 pioh
= &first_io_handler
;
4366 slirp_select_poll(&rfds
, &wfds
, &xfds
, (ret
< 0));
4368 /* rearm timer, if not periodic */
4369 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
4370 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
4371 qemu_rearm_alarm_timer(alarm_timer
);
4374 /* vm time timers */
4376 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
4377 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
4378 qemu_get_clock(vm_clock
));
4381 /* real time timers */
4382 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
4383 qemu_get_clock(rt_clock
));
4385 /* Check bottom-halves last in case any of the earlier events triggered
4391 static int qemu_cpu_exec(CPUState
*env
)
4394 #ifdef CONFIG_PROFILER
4398 #ifdef CONFIG_PROFILER
4399 ti
= profile_getclock();
4404 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
4405 env
->icount_decr
.u16
.low
= 0;
4406 env
->icount_extra
= 0;
4407 count
= qemu_next_deadline();
4408 count
= (count
+ (1 << icount_time_shift
) - 1)
4409 >> icount_time_shift
;
4410 qemu_icount
+= count
;
4411 decr
= (count
> 0xffff) ? 0xffff : count
;
4413 env
->icount_decr
.u16
.low
= decr
;
4414 env
->icount_extra
= count
;
4416 ret
= cpu_exec(env
);
4417 #ifdef CONFIG_PROFILER
4418 qemu_time
+= profile_getclock() - ti
;
4421 /* Fold pending instructions back into the
4422 instruction counter, and clear the interrupt flag. */
4423 qemu_icount
-= (env
->icount_decr
.u16
.low
4424 + env
->icount_extra
);
4425 env
->icount_decr
.u32
= 0;
4426 env
->icount_extra
= 0;
4431 static void tcg_cpu_exec(void)
4435 if (next_cpu
== NULL
)
4436 next_cpu
= first_cpu
;
4437 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
4438 CPUState
*env
= cur_cpu
= next_cpu
;
4442 if (timer_alarm_pending
) {
4443 timer_alarm_pending
= 0;
4446 if (cpu_can_run(env
))
4447 ret
= qemu_cpu_exec(env
);
4448 if (ret
== EXCP_DEBUG
) {
4449 gdb_set_stop_cpu(env
);
4450 debug_requested
= 1;
4456 static int cpu_has_work(CPUState
*env
)
4464 if (qemu_cpu_has_work(env
))
4469 static int tcg_has_work(void)
4473 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4474 if (cpu_has_work(env
))
4479 static int qemu_calculate_timeout(void)
4481 #ifndef CONFIG_IOTHREAD
4486 else if (tcg_has_work())
4488 else if (!use_icount
)
4491 /* XXX: use timeout computed from timers */
4494 /* Advance virtual time to the next event. */
4495 if (use_icount
== 1) {
4496 /* When not using an adaptive execution frequency
4497 we tend to get badly out of sync with real time,
4498 so just delay for a reasonable amount of time. */
4501 delta
= cpu_get_icount() - cpu_get_clock();
4504 /* If virtual time is ahead of real time then just
4506 timeout
= (delta
/ 1000000) + 1;
4508 /* Wait for either IO to occur or the next
4510 add
= qemu_next_deadline();
4511 /* We advance the timer before checking for IO.
4512 Limit the amount we advance so that early IO
4513 activity won't get the guest too far ahead. */
4517 add
= (add
+ (1 << icount_time_shift
) - 1)
4518 >> icount_time_shift
;
4520 timeout
= delta
/ 1000000;
4527 #else /* CONFIG_IOTHREAD */
4532 static int vm_can_run(void)
4534 if (powerdown_requested
)
4536 if (reset_requested
)
4538 if (shutdown_requested
)
4540 if (debug_requested
)
4545 static void main_loop(void)
4549 if (kvm_enabled()) {
4551 cpu_disable_ticks();
4555 #ifdef CONFIG_IOTHREAD
4556 qemu_system_ready
= 1;
4557 qemu_cond_broadcast(&qemu_system_cond
);
4562 #ifdef CONFIG_PROFILER
4565 #ifndef CONFIG_IOTHREAD
4568 #ifdef CONFIG_PROFILER
4569 ti
= profile_getclock();
4571 main_loop_wait(qemu_calculate_timeout());
4572 #ifdef CONFIG_PROFILER
4573 dev_time
+= profile_getclock() - ti
;
4575 } while (vm_can_run());
4577 if (qemu_debug_requested())
4578 vm_stop(EXCP_DEBUG
);
4579 if (qemu_shutdown_requested()) {
4586 if (qemu_reset_requested()) {
4588 qemu_system_reset();
4591 if (qemu_powerdown_requested())
4592 qemu_system_powerdown();
4593 if ((r
= qemu_vmstop_requested()))
4599 static void version(void)
4601 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4604 static void help(int exitcode
)
4607 printf("usage: %s [options] [disk_image]\n"
4609 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4611 #define DEF(option, opt_arg, opt_enum, opt_help) \
4613 #define DEFHEADING(text) stringify(text) "\n"
4614 #include "qemu-options.h"
4619 "During emulation, the following keys are useful:\n"
4620 "ctrl-alt-f toggle full screen\n"
4621 "ctrl-alt-n switch to virtual console 'n'\n"
4622 "ctrl-alt toggle mouse and keyboard grab\n"
4624 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4629 DEFAULT_NETWORK_SCRIPT
,
4630 DEFAULT_NETWORK_DOWN_SCRIPT
,
4632 DEFAULT_GDBSTUB_PORT
,
4637 #define HAS_ARG 0x0001
4640 #define DEF(option, opt_arg, opt_enum, opt_help) \
4642 #define DEFHEADING(text)
4643 #include "qemu-options.h"
4649 typedef struct QEMUOption
{
4655 static const QEMUOption qemu_options
[] = {
4656 { "h", 0, QEMU_OPTION_h
},
4657 #define DEF(option, opt_arg, opt_enum, opt_help) \
4658 { option, opt_arg, opt_enum },
4659 #define DEFHEADING(text)
4660 #include "qemu-options.h"
4668 struct soundhw soundhw
[] = {
4669 #ifdef HAS_AUDIO_CHOICE
4670 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4676 { .init_isa
= pcspk_audio_init
}
4683 "Creative Sound Blaster 16",
4686 { .init_isa
= SB16_init
}
4690 #ifdef CONFIG_CS4231A
4696 { .init_isa
= cs4231a_init
}
4704 "Yamaha YMF262 (OPL3)",
4706 "Yamaha YM3812 (OPL2)",
4710 { .init_isa
= Adlib_init
}
4717 "Gravis Ultrasound GF1",
4720 { .init_isa
= GUS_init
}
4727 "Intel 82801AA AC97 Audio",
4730 { .init_pci
= ac97_init
}
4734 #ifdef CONFIG_ES1370
4737 "ENSONIQ AudioPCI ES1370",
4740 { .init_pci
= es1370_init
}
4744 #endif /* HAS_AUDIO_CHOICE */
4746 { NULL
, NULL
, 0, 0, { NULL
} }
4749 static void select_soundhw (const char *optarg
)
4753 if (*optarg
== '?') {
4756 printf ("Valid sound card names (comma separated):\n");
4757 for (c
= soundhw
; c
->name
; ++c
) {
4758 printf ("%-11s %s\n", c
->name
, c
->descr
);
4760 printf ("\n-soundhw all will enable all of the above\n");
4761 exit (*optarg
!= '?');
4769 if (!strcmp (optarg
, "all")) {
4770 for (c
= soundhw
; c
->name
; ++c
) {
4778 e
= strchr (p
, ',');
4779 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4781 for (c
= soundhw
; c
->name
; ++c
) {
4782 if (!strncmp (c
->name
, p
, l
)) {
4791 "Unknown sound card name (too big to show)\n");
4794 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4799 p
+= l
+ (e
!= NULL
);
4803 goto show_valid_cards
;
4808 static void select_vgahw (const char *p
)
4812 cirrus_vga_enabled
= 0;
4813 std_vga_enabled
= 0;
4816 if (strstart(p
, "std", &opts
)) {
4817 std_vga_enabled
= 1;
4818 } else if (strstart(p
, "cirrus", &opts
)) {
4819 cirrus_vga_enabled
= 1;
4820 } else if (strstart(p
, "vmware", &opts
)) {
4822 } else if (strstart(p
, "xenfb", &opts
)) {
4824 } else if (!strstart(p
, "none", &opts
)) {
4826 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4830 const char *nextopt
;
4832 if (strstart(opts
, ",retrace=", &nextopt
)) {
4834 if (strstart(opts
, "dumb", &nextopt
))
4835 vga_retrace_method
= VGA_RETRACE_DUMB
;
4836 else if (strstart(opts
, "precise", &nextopt
))
4837 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4838 else goto invalid_vga
;
4839 } else goto invalid_vga
;
4845 static int balloon_parse(const char *arg
)
4850 if (!strcmp(arg
, "none")) {
4852 } else if (!strncmp(arg
, "virtio", 6)) {
4854 if (arg
[6] == ',') {
4856 if (get_param_value(buf
, sizeof(buf
), "addr", p
)) {
4857 virtio_balloon_devaddr
= strdup(buf
);
4868 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4870 exit(STATUS_CONTROL_C_EXIT
);
4875 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4879 if(strlen(str
) != 36)
4882 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4883 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4884 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4890 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4896 #define MAX_NET_CLIENTS 32
4900 static void termsig_handler(int signal
)
4902 qemu_system_shutdown_request();
4905 static void sigchld_handler(int signal
)
4907 waitpid(-1, NULL
, WNOHANG
);
4910 static void sighandler_setup(void)
4912 struct sigaction act
;
4914 memset(&act
, 0, sizeof(act
));
4915 act
.sa_handler
= termsig_handler
;
4916 sigaction(SIGINT
, &act
, NULL
);
4917 sigaction(SIGHUP
, &act
, NULL
);
4918 sigaction(SIGTERM
, &act
, NULL
);
4920 act
.sa_handler
= sigchld_handler
;
4921 act
.sa_flags
= SA_NOCLDSTOP
;
4922 sigaction(SIGCHLD
, &act
, NULL
);
4928 /* Look for support files in the same directory as the executable. */
4929 static char *find_datadir(const char *argv0
)
4935 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
4942 while (p
!= buf
&& *p
!= '\\')
4945 if (access(buf
, R_OK
) == 0) {
4946 return qemu_strdup(buf
);
4952 /* Find a likely location for support files using the location of the binary.
4953 For installed binaries this will be "$bindir/../share/qemu". When
4954 running from the build tree this will be "$bindir/../pc-bios". */
4955 #define SHARE_SUFFIX "/share/qemu"
4956 #define BUILD_SUFFIX "/pc-bios"
4957 static char *find_datadir(const char *argv0
)
4967 #if defined(__linux__)
4970 len
= readlink("/proc/self/exe", buf
, sizeof(buf
) - 1);
4976 #elif defined(__FreeBSD__)
4979 len
= readlink("/proc/curproc/file", buf
, sizeof(buf
) - 1);
4986 /* If we don't have any way of figuring out the actual executable
4987 location then try argv[0]. */
4992 p
= realpath(argv0
, p
);
5000 max_len
= strlen(dir
) +
5001 MAX(strlen(SHARE_SUFFIX
), strlen(BUILD_SUFFIX
)) + 1;
5002 res
= qemu_mallocz(max_len
);
5003 snprintf(res
, max_len
, "%s%s", dir
, SHARE_SUFFIX
);
5004 if (access(res
, R_OK
)) {
5005 snprintf(res
, max_len
, "%s%s", dir
, BUILD_SUFFIX
);
5006 if (access(res
, R_OK
)) {
5020 char *qemu_find_file(int type
, const char *name
)
5026 /* If name contains path separators then try it as a straight path. */
5027 if ((strchr(name
, '/') || strchr(name
, '\\'))
5028 && access(name
, R_OK
) == 0) {
5029 return strdup(name
);
5032 case QEMU_FILE_TYPE_BIOS
:
5035 case QEMU_FILE_TYPE_KEYMAP
:
5036 subdir
= "keymaps/";
5041 len
= strlen(data_dir
) + strlen(name
) + strlen(subdir
) + 2;
5042 buf
= qemu_mallocz(len
);
5043 snprintf(buf
, len
, "%s/%s%s", data_dir
, subdir
, name
);
5044 if (access(buf
, R_OK
)) {
5051 int main(int argc
, char **argv
, char **envp
)
5053 const char *gdbstub_dev
= NULL
;
5054 uint32_t boot_devices_bitmap
= 0;
5056 int snapshot
, linux_boot
, net_boot
;
5057 const char *initrd_filename
;
5058 const char *kernel_filename
, *kernel_cmdline
;
5059 const char *boot_devices
= "";
5061 DisplayChangeListener
*dcl
;
5062 int cyls
, heads
, secs
, translation
;
5063 const char *net_clients
[MAX_NET_CLIENTS
];
5065 const char *bt_opts
[MAX_BT_CMDLINE
];
5069 const char *r
, *optarg
;
5070 CharDriverState
*monitor_hd
= NULL
;
5071 const char *monitor_device
;
5072 const char *serial_devices
[MAX_SERIAL_PORTS
];
5073 int serial_device_index
;
5074 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
5075 int parallel_device_index
;
5076 const char *virtio_consoles
[MAX_VIRTIO_CONSOLES
];
5077 int virtio_console_index
;
5078 const char *loadvm
= NULL
;
5079 QEMUMachine
*machine
;
5080 const char *cpu_model
;
5081 const char *usb_devices
[MAX_USB_CMDLINE
];
5082 int usb_devices_index
;
5087 const char *pid_file
= NULL
;
5088 const char *incoming
= NULL
;
5091 struct passwd
*pwd
= NULL
;
5092 const char *chroot_dir
= NULL
;
5093 const char *run_as
= NULL
;
5096 int show_vnc_port
= 0;
5098 qemu_cache_utils_init(envp
);
5100 LIST_INIT (&vm_change_state_head
);
5103 struct sigaction act
;
5104 sigfillset(&act
.sa_mask
);
5106 act
.sa_handler
= SIG_IGN
;
5107 sigaction(SIGPIPE
, &act
, NULL
);
5110 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
5111 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5112 QEMU to run on a single CPU */
5117 h
= GetCurrentProcess();
5118 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
5119 for(i
= 0; i
< 32; i
++) {
5120 if (mask
& (1 << i
))
5125 SetProcessAffinityMask(h
, mask
);
5131 module_call_init(MODULE_INIT_MACHINE
);
5132 machine
= find_default_machine();
5134 initrd_filename
= NULL
;
5137 kernel_filename
= NULL
;
5138 kernel_cmdline
= "";
5139 cyls
= heads
= secs
= 0;
5140 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5141 monitor_device
= "vc:80Cx24C";
5143 serial_devices
[0] = "vc:80Cx24C";
5144 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
5145 serial_devices
[i
] = NULL
;
5146 serial_device_index
= 0;
5148 parallel_devices
[0] = "vc:80Cx24C";
5149 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
5150 parallel_devices
[i
] = NULL
;
5151 parallel_device_index
= 0;
5153 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++)
5154 virtio_consoles
[i
] = NULL
;
5155 virtio_console_index
= 0;
5157 for (i
= 0; i
< MAX_NODES
; i
++) {
5159 node_cpumask
[i
] = 0;
5162 usb_devices_index
= 0;
5163 assigned_devices_index
= 0;
5177 register_watchdogs();
5185 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
5187 const QEMUOption
*popt
;
5190 /* Treat --foo the same as -foo. */
5193 popt
= qemu_options
;
5196 fprintf(stderr
, "%s: invalid option -- '%s'\n",
5200 if (!strcmp(popt
->name
, r
+ 1))
5204 if (popt
->flags
& HAS_ARG
) {
5205 if (optind
>= argc
) {
5206 fprintf(stderr
, "%s: option '%s' requires an argument\n",
5210 optarg
= argv
[optind
++];
5215 switch(popt
->index
) {
5217 machine
= find_machine(optarg
);
5220 printf("Supported machines are:\n");
5221 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5222 printf("%-10s %s%s\n",
5224 m
->is_default
? " (default)" : "");
5226 exit(*optarg
!= '?');
5229 case QEMU_OPTION_cpu
:
5230 /* hw initialization will check this */
5231 if (*optarg
== '?') {
5232 /* XXX: implement xxx_cpu_list for targets that still miss it */
5233 #if defined(cpu_list)
5234 cpu_list(stdout
, &fprintf
);
5241 case QEMU_OPTION_initrd
:
5242 initrd_filename
= optarg
;
5244 case QEMU_OPTION_hda
:
5246 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
5248 hda_index
= drive_add(optarg
, HD_ALIAS
5249 ",cyls=%d,heads=%d,secs=%d%s",
5250 0, cyls
, heads
, secs
,
5251 translation
== BIOS_ATA_TRANSLATION_LBA
?
5253 translation
== BIOS_ATA_TRANSLATION_NONE
?
5254 ",trans=none" : "");
5256 case QEMU_OPTION_hdb
:
5257 case QEMU_OPTION_hdc
:
5258 case QEMU_OPTION_hdd
:
5259 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
5261 case QEMU_OPTION_drive
:
5262 drive_add(NULL
, "%s", optarg
);
5264 case QEMU_OPTION_mtdblock
:
5265 drive_add(optarg
, MTD_ALIAS
);
5267 case QEMU_OPTION_sd
:
5268 drive_add(optarg
, SD_ALIAS
);
5270 case QEMU_OPTION_pflash
:
5271 drive_add(optarg
, PFLASH_ALIAS
);
5273 case QEMU_OPTION_snapshot
:
5276 case QEMU_OPTION_hdachs
:
5280 cyls
= strtol(p
, (char **)&p
, 0);
5281 if (cyls
< 1 || cyls
> 16383)
5286 heads
= strtol(p
, (char **)&p
, 0);
5287 if (heads
< 1 || heads
> 16)
5292 secs
= strtol(p
, (char **)&p
, 0);
5293 if (secs
< 1 || secs
> 63)
5297 if (!strcmp(p
, "none"))
5298 translation
= BIOS_ATA_TRANSLATION_NONE
;
5299 else if (!strcmp(p
, "lba"))
5300 translation
= BIOS_ATA_TRANSLATION_LBA
;
5301 else if (!strcmp(p
, "auto"))
5302 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5305 } else if (*p
!= '\0') {
5307 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5310 if (hda_index
!= -1)
5311 snprintf(drives_opt
[hda_index
].opt
,
5312 sizeof(drives_opt
[hda_index
].opt
),
5313 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
5314 0, cyls
, heads
, secs
,
5315 translation
== BIOS_ATA_TRANSLATION_LBA
?
5317 translation
== BIOS_ATA_TRANSLATION_NONE
?
5318 ",trans=none" : "");
5321 case QEMU_OPTION_numa
:
5322 if (nb_numa_nodes
>= MAX_NODES
) {
5323 fprintf(stderr
, "qemu: too many NUMA nodes\n");
5328 case QEMU_OPTION_nographic
:
5329 display_type
= DT_NOGRAPHIC
;
5331 #ifdef CONFIG_CURSES
5332 case QEMU_OPTION_curses
:
5333 display_type
= DT_CURSES
;
5336 case QEMU_OPTION_portrait
:
5339 case QEMU_OPTION_kernel
:
5340 kernel_filename
= optarg
;
5342 case QEMU_OPTION_append
:
5343 kernel_cmdline
= optarg
;
5345 case QEMU_OPTION_cdrom
:
5346 drive_add(optarg
, CDROM_ALIAS
);
5348 case QEMU_OPTION_boot
:
5349 boot_devices
= optarg
;
5350 /* We just do some generic consistency checks */
5352 /* Could easily be extended to 64 devices if needed */
5355 boot_devices_bitmap
= 0;
5356 for (p
= boot_devices
; *p
!= '\0'; p
++) {
5357 /* Allowed boot devices are:
5358 * a b : floppy disk drives
5359 * c ... f : IDE disk drives
5360 * g ... m : machine implementation dependant drives
5361 * n ... p : network devices
5362 * It's up to each machine implementation to check
5363 * if the given boot devices match the actual hardware
5364 * implementation and firmware features.
5366 if (*p
< 'a' || *p
> 'q') {
5367 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
5370 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
5372 "Boot device '%c' was given twice\n",*p
);
5375 boot_devices_bitmap
|= 1 << (*p
- 'a');
5379 case QEMU_OPTION_fda
:
5380 case QEMU_OPTION_fdb
:
5381 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
5384 case QEMU_OPTION_no_fd_bootchk
:
5388 case QEMU_OPTION_net
:
5389 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
5390 fprintf(stderr
, "qemu: too many network clients\n");
5393 net_clients
[nb_net_clients
] = optarg
;
5397 case QEMU_OPTION_tftp
:
5398 legacy_tftp_prefix
= optarg
;
5400 case QEMU_OPTION_bootp
:
5401 legacy_bootp_filename
= optarg
;
5404 case QEMU_OPTION_smb
:
5405 net_slirp_smb(optarg
);
5408 case QEMU_OPTION_redir
:
5409 net_slirp_redir(optarg
);
5412 case QEMU_OPTION_bt
:
5413 if (nb_bt_opts
>= MAX_BT_CMDLINE
) {
5414 fprintf(stderr
, "qemu: too many bluetooth options\n");
5417 bt_opts
[nb_bt_opts
++] = optarg
;
5420 case QEMU_OPTION_audio_help
:
5424 case QEMU_OPTION_soundhw
:
5425 select_soundhw (optarg
);
5431 case QEMU_OPTION_version
:
5435 case QEMU_OPTION_m
: {
5439 value
= strtoul(optarg
, &ptr
, 10);
5441 case 0: case 'M': case 'm':
5448 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5452 /* On 32-bit hosts, QEMU is limited by virtual address space */
5453 if (value
> (2047 << 20)
5454 #ifndef CONFIG_KQEMU
5455 && HOST_LONG_BITS
== 32
5458 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5461 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5462 fprintf(stderr
, "qemu: ram size too large\n");
5471 const CPULogItem
*item
;
5473 mask
= cpu_str_to_log_mask(optarg
);
5475 printf("Log items (comma separated):\n");
5476 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5477 printf("%-10s %s\n", item
->name
, item
->help
);
5485 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5487 case QEMU_OPTION_gdb
:
5488 gdbstub_dev
= optarg
;
5493 case QEMU_OPTION_bios
:
5496 case QEMU_OPTION_singlestep
:
5504 keyboard_layout
= optarg
;
5507 case QEMU_OPTION_localtime
:
5510 case QEMU_OPTION_vga
:
5511 select_vgahw (optarg
);
5513 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5519 w
= strtol(p
, (char **)&p
, 10);
5522 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5528 h
= strtol(p
, (char **)&p
, 10);
5533 depth
= strtol(p
, (char **)&p
, 10);
5534 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5535 depth
!= 24 && depth
!= 32)
5537 } else if (*p
== '\0') {
5538 depth
= graphic_depth
;
5545 graphic_depth
= depth
;
5549 case QEMU_OPTION_echr
:
5552 term_escape_char
= strtol(optarg
, &r
, 0);
5554 printf("Bad argument to echr\n");
5557 case QEMU_OPTION_monitor
:
5558 monitor_device
= optarg
;
5560 case QEMU_OPTION_serial
:
5561 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
5562 fprintf(stderr
, "qemu: too many serial ports\n");
5565 serial_devices
[serial_device_index
] = optarg
;
5566 serial_device_index
++;
5568 case QEMU_OPTION_watchdog
:
5569 i
= select_watchdog(optarg
);
5571 exit (i
== 1 ? 1 : 0);
5573 case QEMU_OPTION_watchdog_action
:
5574 if (select_watchdog_action(optarg
) == -1) {
5575 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5579 case QEMU_OPTION_virtiocon
:
5580 if (virtio_console_index
>= MAX_VIRTIO_CONSOLES
) {
5581 fprintf(stderr
, "qemu: too many virtio consoles\n");
5584 virtio_consoles
[virtio_console_index
] = optarg
;
5585 virtio_console_index
++;
5587 case QEMU_OPTION_parallel
:
5588 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
5589 fprintf(stderr
, "qemu: too many parallel ports\n");
5592 parallel_devices
[parallel_device_index
] = optarg
;
5593 parallel_device_index
++;
5595 case QEMU_OPTION_loadvm
:
5598 case QEMU_OPTION_full_screen
:
5602 case QEMU_OPTION_no_frame
:
5605 case QEMU_OPTION_alt_grab
:
5608 case QEMU_OPTION_no_quit
:
5611 case QEMU_OPTION_sdl
:
5612 display_type
= DT_SDL
;
5615 case QEMU_OPTION_pidfile
:
5619 case QEMU_OPTION_win2k_hack
:
5620 win2k_install_hack
= 1;
5622 case QEMU_OPTION_rtc_td_hack
:
5625 case QEMU_OPTION_acpitable
:
5626 if(acpi_table_add(optarg
) < 0) {
5627 fprintf(stderr
, "Wrong acpi table provided\n");
5631 case QEMU_OPTION_smbios
:
5632 if(smbios_entry_add(optarg
) < 0) {
5633 fprintf(stderr
, "Wrong smbios provided\n");
5639 case QEMU_OPTION_no_kqemu
:
5642 case QEMU_OPTION_kernel_kqemu
:
5647 case QEMU_OPTION_enable_kvm
:
5655 case QEMU_OPTION_no_kvm
:
5658 case QEMU_OPTION_no_kvm_irqchip
: {
5663 case QEMU_OPTION_no_kvm_pit
: {
5667 case QEMU_OPTION_no_kvm_pit_reinjection
: {
5668 kvm_pit_reinject
= 0;
5671 case QEMU_OPTION_enable_nesting
: {
5675 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5676 case QEMU_OPTION_pcidevice
:
5677 if (assigned_devices_index
>= MAX_DEV_ASSIGN_CMDLINE
) {
5678 fprintf(stderr
, "Too many assigned devices\n");
5681 assigned_devices
[assigned_devices_index
] = optarg
;
5682 assigned_devices_index
++;
5686 case QEMU_OPTION_usb
:
5689 case QEMU_OPTION_usbdevice
:
5691 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
5692 fprintf(stderr
, "Too many USB devices\n");
5695 usb_devices
[usb_devices_index
] = optarg
;
5696 usb_devices_index
++;
5698 case QEMU_OPTION_smp
:
5699 smp_cpus
= atoi(optarg
);
5701 fprintf(stderr
, "Invalid number of CPUs\n");
5705 case QEMU_OPTION_vnc
:
5706 display_type
= DT_VNC
;
5707 vnc_display
= optarg
;
5710 case QEMU_OPTION_no_acpi
:
5713 case QEMU_OPTION_no_hpet
:
5716 case QEMU_OPTION_balloon
:
5717 if (balloon_parse(optarg
) < 0) {
5718 fprintf(stderr
, "Unknown -balloon argument %s\n", optarg
);
5723 case QEMU_OPTION_no_reboot
:
5726 case QEMU_OPTION_no_shutdown
:
5729 case QEMU_OPTION_show_cursor
:
5732 case QEMU_OPTION_uuid
:
5733 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5734 fprintf(stderr
, "Fail to parse UUID string."
5735 " Wrong format.\n");
5740 case QEMU_OPTION_daemonize
:
5744 case QEMU_OPTION_option_rom
:
5745 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5746 fprintf(stderr
, "Too many option ROMs\n");
5749 option_rom
[nb_option_roms
] = optarg
;
5752 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5753 case QEMU_OPTION_semihosting
:
5754 semihosting_enabled
= 1;
5757 case QEMU_OPTION_tdf
:
5760 case QEMU_OPTION_kvm_shadow_memory
:
5761 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
5763 case QEMU_OPTION_mempath
:
5767 case QEMU_OPTION_mem_prealloc
:
5768 mem_prealloc
= !mem_prealloc
;
5771 case QEMU_OPTION_name
:
5774 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5775 case QEMU_OPTION_prom_env
:
5776 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5777 fprintf(stderr
, "Too many prom variables\n");
5780 prom_envs
[nb_prom_envs
] = optarg
;
5785 case QEMU_OPTION_old_param
:
5789 case QEMU_OPTION_clock
:
5790 configure_alarms(optarg
);
5792 case QEMU_OPTION_startdate
:
5795 time_t rtc_start_date
;
5796 if (!strcmp(optarg
, "now")) {
5797 rtc_date_offset
= -1;
5799 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
5807 } else if (sscanf(optarg
, "%d-%d-%d",
5810 &tm
.tm_mday
) == 3) {
5819 rtc_start_date
= mktimegm(&tm
);
5820 if (rtc_start_date
== -1) {
5822 fprintf(stderr
, "Invalid date format. Valid format are:\n"
5823 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5826 rtc_date_offset
= time(NULL
) - rtc_start_date
;
5830 case QEMU_OPTION_tb_size
:
5831 tb_size
= strtol(optarg
, NULL
, 0);
5835 case QEMU_OPTION_icount
:
5837 if (strcmp(optarg
, "auto") == 0) {
5838 icount_time_shift
= -1;
5840 icount_time_shift
= strtol(optarg
, NULL
, 0);
5843 case QEMU_OPTION_incoming
:
5847 case QEMU_OPTION_chroot
:
5848 chroot_dir
= optarg
;
5850 case QEMU_OPTION_runas
:
5853 case QEMU_OPTION_nvram
:
5858 case QEMU_OPTION_xen_domid
:
5859 xen_domid
= atoi(optarg
);
5861 case QEMU_OPTION_xen_create
:
5862 xen_mode
= XEN_CREATE
;
5864 case QEMU_OPTION_xen_attach
:
5865 xen_mode
= XEN_ATTACH
;
5872 /* If no data_dir is specified then try to find it relative to the
5875 data_dir
= find_datadir(argv
[0]);
5877 /* If all else fails use the install patch specified when building. */
5879 data_dir
= CONFIG_QEMU_SHAREDIR
;
5882 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5883 if (kvm_allowed
&& kqemu_allowed
) {
5885 "You can not enable both KVM and kqemu at the same time\n");
5890 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5891 if (smp_cpus
> machine
->max_cpus
) {
5892 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5893 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5898 if (display_type
== DT_NOGRAPHIC
) {
5899 if (serial_device_index
== 0)
5900 serial_devices
[0] = "stdio";
5901 if (parallel_device_index
== 0)
5902 parallel_devices
[0] = "null";
5903 if (strncmp(monitor_device
, "vc", 2) == 0)
5904 monitor_device
= "stdio";
5911 if (pipe(fds
) == -1)
5922 len
= read(fds
[0], &status
, 1);
5923 if (len
== -1 && (errno
== EINTR
))
5928 else if (status
== 1) {
5929 fprintf(stderr
, "Could not acquire pidfile\n");
5946 signal(SIGTSTP
, SIG_IGN
);
5947 signal(SIGTTOU
, SIG_IGN
);
5948 signal(SIGTTIN
, SIG_IGN
);
5952 if (kvm_enabled()) {
5953 if (kvm_qemu_init() < 0) {
5954 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
5955 #ifdef NO_CPU_EMULATION
5956 fprintf(stderr
, "Compiled with --disable-cpu-emulation, exiting.\n");
5964 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5967 write(fds
[1], &status
, 1);
5969 fprintf(stderr
, "Could not acquire pid file\n");
5978 if (qemu_init_main_loop()) {
5979 fprintf(stderr
, "qemu_init_main_loop failed\n");
5982 linux_boot
= (kernel_filename
!= NULL
);
5984 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5985 fprintf(stderr
, "-append only allowed with -kernel option\n");
5989 if (!linux_boot
&& initrd_filename
!= NULL
) {
5990 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5994 /* boot to floppy or the default cd if no hard disk defined yet */
5995 if (!boot_devices
[0]) {
5996 boot_devices
= "cad";
5998 setvbuf(stdout
, NULL
, _IOLBF
, 0);
6001 if (init_timer_alarm() < 0) {
6002 fprintf(stderr
, "could not initialize alarm timer\n");
6005 if (use_icount
&& icount_time_shift
< 0) {
6007 /* 125MIPS seems a reasonable initial guess at the guest speed.
6008 It will be corrected fairly quickly anyway. */
6009 icount_time_shift
= 3;
6010 init_icount_adjust();
6017 /* init network clients */
6018 if (nb_net_clients
== 0) {
6019 /* if no clients, we use a default config */
6020 net_clients
[nb_net_clients
++] = "nic";
6022 net_clients
[nb_net_clients
++] = "user";
6026 for(i
= 0;i
< nb_net_clients
; i
++) {
6027 if (net_client_parse(net_clients
[i
]) < 0)
6031 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
6032 net_set_boot_mask(net_boot
);
6036 /* init the bluetooth world */
6037 for (i
= 0; i
< nb_bt_opts
; i
++)
6038 if (bt_parse(bt_opts
[i
]))
6041 /* init the memory */
6043 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
6045 if (kvm_enabled()) {
6046 if (kvm_qemu_create_context() < 0) {
6047 fprintf(stderr
, "Could not create KVM context\n");
6053 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
6054 guest ram allocation. It needs to go away. */
6055 if (kqemu_allowed
) {
6056 kqemu_phys_ram_size
= ram_size
+ 8 * 1024 * 1024 + 4 * 1024 * 1024;
6057 kqemu_phys_ram_base
= qemu_vmalloc(kqemu_phys_ram_size
);
6058 if (!kqemu_phys_ram_base
) {
6059 fprintf(stderr
, "Could not allocate physical memory\n");
6065 /* init the dynamic translator */
6066 cpu_exec_init_all(tb_size
* 1024 * 1024);
6070 /* we always create the cdrom drive, even if no disk is there */
6072 if (nb_drives_opt
< MAX_DRIVES
)
6073 drive_add(NULL
, CDROM_ALIAS
);
6075 /* we always create at least one floppy */
6077 if (nb_drives_opt
< MAX_DRIVES
)
6078 drive_add(NULL
, FD_ALIAS
, 0);
6080 /* we always create one sd slot, even if no card is in it */
6082 if (nb_drives_opt
< MAX_DRIVES
)
6083 drive_add(NULL
, SD_ALIAS
);
6085 /* open the virtual block devices
6086 * note that migration with device
6087 * hot add/remove is broken.
6089 for(i
= 0; i
< nb_drives_opt
; i
++)
6090 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
6093 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
6094 register_savevm_live("ram", 0, 3, ram_save_live
, NULL
, ram_load
, NULL
);
6097 /* must be after terminal init, SDL library changes signal handlers */
6101 /* Maintain compatibility with multiple stdio monitors */
6102 if (!strcmp(monitor_device
,"stdio")) {
6103 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6104 const char *devname
= serial_devices
[i
];
6105 if (devname
&& !strcmp(devname
,"mon:stdio")) {
6106 monitor_device
= NULL
;
6108 } else if (devname
&& !strcmp(devname
,"stdio")) {
6109 monitor_device
= NULL
;
6110 serial_devices
[i
] = "mon:stdio";
6116 if (nb_numa_nodes
> 0) {
6119 if (nb_numa_nodes
> smp_cpus
) {
6120 nb_numa_nodes
= smp_cpus
;
6123 /* If no memory size if given for any node, assume the default case
6124 * and distribute the available memory equally across all nodes
6126 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6127 if (node_mem
[i
] != 0)
6130 if (i
== nb_numa_nodes
) {
6131 uint64_t usedmem
= 0;
6133 /* On Linux, the each node's border has to be 8MB aligned,
6134 * the final node gets the rest.
6136 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
6137 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
6138 usedmem
+= node_mem
[i
];
6140 node_mem
[i
] = ram_size
- usedmem
;
6143 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6144 if (node_cpumask
[i
] != 0)
6147 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6148 * must cope with this anyway, because there are BIOSes out there in
6149 * real machines which also use this scheme.
6151 if (i
== nb_numa_nodes
) {
6152 for (i
= 0; i
< smp_cpus
; i
++) {
6153 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
6159 if (kvm_enabled()) {
6162 ret
= kvm_init(smp_cpus
);
6164 fprintf(stderr
, "failed to initialize KVM\n");
6170 if (monitor_device
) {
6171 monitor_hd
= qemu_chr_open("monitor", monitor_device
, NULL
);
6173 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
6178 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6179 const char *devname
= serial_devices
[i
];
6180 if (devname
&& strcmp(devname
, "none")) {
6182 snprintf(label
, sizeof(label
), "serial%d", i
);
6183 serial_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6184 if (!serial_hds
[i
]) {
6185 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
6192 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
6193 const char *devname
= parallel_devices
[i
];
6194 if (devname
&& strcmp(devname
, "none")) {
6196 snprintf(label
, sizeof(label
), "parallel%d", i
);
6197 parallel_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6198 if (!parallel_hds
[i
]) {
6199 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
6206 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
6207 const char *devname
= virtio_consoles
[i
];
6208 if (devname
&& strcmp(devname
, "none")) {
6210 snprintf(label
, sizeof(label
), "virtcon%d", i
);
6211 virtcon_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
6212 if (!virtcon_hds
[i
]) {
6213 fprintf(stderr
, "qemu: could not open virtio console '%s'\n",
6220 module_call_init(MODULE_INIT_DEVICE
);
6225 machine
->init(ram_size
, boot_devices
,
6226 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
6229 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
6230 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6231 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
6237 current_machine
= machine
;
6239 /* init USB devices */
6241 for(i
= 0; i
< usb_devices_index
; i
++) {
6242 if (usb_device_add(usb_devices
[i
], 0) < 0) {
6243 fprintf(stderr
, "Warning: could not add USB device %s\n",
6250 dumb_display_init();
6251 /* just use the first displaystate for the moment */
6254 if (display_type
== DT_DEFAULT
) {
6255 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6256 display_type
= DT_SDL
;
6258 display_type
= DT_VNC
;
6259 vnc_display
= "localhost:0,to=99";
6265 switch (display_type
) {
6268 #if defined(CONFIG_CURSES)
6270 curses_display_init(ds
, full_screen
);
6273 #if defined(CONFIG_SDL)
6275 sdl_display_init(ds
, full_screen
, no_frame
);
6277 #elif defined(CONFIG_COCOA)
6279 cocoa_display_init(ds
, full_screen
);
6283 vnc_display_init(ds
);
6284 if (vnc_display_open(ds
, vnc_display
) < 0)
6287 if (show_vnc_port
) {
6288 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
6296 dcl
= ds
->listeners
;
6297 while (dcl
!= NULL
) {
6298 if (dcl
->dpy_refresh
!= NULL
) {
6299 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
6300 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
6305 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
6306 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
6307 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
6310 text_consoles_set_display(display_state
);
6311 qemu_chr_initial_reset();
6313 if (monitor_device
&& monitor_hd
)
6314 monitor_init(monitor_hd
, MONITOR_USE_READLINE
| MONITOR_IS_DEFAULT
);
6316 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6317 const char *devname
= serial_devices
[i
];
6318 if (devname
&& strcmp(devname
, "none")) {
6319 if (strstart(devname
, "vc", 0))
6320 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
6324 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
6325 const char *devname
= parallel_devices
[i
];
6326 if (devname
&& strcmp(devname
, "none")) {
6327 if (strstart(devname
, "vc", 0))
6328 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
6332 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
6333 const char *devname
= virtio_consoles
[i
];
6334 if (virtcon_hds
[i
] && devname
) {
6335 if (strstart(devname
, "vc", 0))
6336 qemu_chr_printf(virtcon_hds
[i
], "virtio console%d\r\n", i
);
6340 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
6341 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
6347 do_loadvm(cur_mon
, loadvm
);
6350 autostart
= 0; /* fixme how to deal with -daemonize */
6351 qemu_start_incoming_migration(incoming
);
6363 len
= write(fds
[1], &status
, 1);
6364 if (len
== -1 && (errno
== EINTR
))
6371 TFR(fd
= open("/dev/null", O_RDWR
));
6377 pwd
= getpwnam(run_as
);
6379 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
6385 if (chroot(chroot_dir
) < 0) {
6386 fprintf(stderr
, "chroot failed\n");
6393 if (setgid(pwd
->pw_gid
) < 0) {
6394 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
6397 if (setuid(pwd
->pw_uid
) < 0) {
6398 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
6401 if (setuid(0) != -1) {
6402 fprintf(stderr
, "Dropping privileges failed\n");