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 CONFIG_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 #include <arpa/inet.h>
50 #include <sys/select.h>
53 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
62 #include <linux/rtc.h>
63 #include <sys/prctl.h>
65 /* For the benefit of older linux systems which don't supply it,
66 we use a local copy of hpet.h. */
67 /* #include <linux/hpet.h> */
70 #include <linux/ppdev.h>
71 #include <linux/parport.h>
75 #include <sys/ethernet.h>
76 #include <sys/sockio.h>
77 #include <netinet/arp.h>
78 #include <netinet/in.h>
79 #include <netinet/in_systm.h>
80 #include <netinet/ip.h>
81 #include <netinet/ip_icmp.h> // must come after ip.h
82 #include <netinet/udp.h>
83 #include <netinet/tcp.h>
87 /* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
88 discussion about Solaris header problems */
89 extern int madvise(caddr_t
, size_t, int);
94 #if defined(__OpenBSD__)
98 #if defined(CONFIG_VDE)
99 #include <libvdeplug.h>
104 #include <mmsystem.h>
108 #if defined(__APPLE__) || defined(main)
110 int qemu_main(int argc
, char **argv
, char **envp
);
111 int main(int argc
, char **argv
)
113 return qemu_main(argc
, argv
, NULL
);
116 #define main qemu_main
118 #endif /* CONFIG_SDL */
122 #define main qemu_main
123 #endif /* CONFIG_COCOA */
126 #include "hw/boards.h"
128 #include "hw/pcmcia.h"
130 #include "hw/audiodev.h"
134 #include "hw/watchdog.h"
135 #include "hw/smbios.h"
138 #include "hw/loader.h"
141 #include "net/slirp.h"
146 #include "qemu-timer.h"
147 #include "qemu-char.h"
148 #include "cache-utils.h"
150 #include "block_int.h"
151 #include "block-migration.h"
153 #include "audio/audio.h"
154 #include "migration.h"
157 #include "qemu-option.h"
158 #include "qemu-config.h"
159 #include "qemu-objects.h"
160 #include "qemu-kvm.h"
161 #include "hw/device-assignment.h"
165 #include "exec-all.h"
167 #include "qemu_socket.h"
169 #include "slirp/libslirp.h"
171 #include "qemu-queue.h"
174 //#define DEBUG_SLIRP
176 #define DEFAULT_RAM_SIZE 128
178 static const char *data_dir
;
179 const char *bios_name
= NULL
;
180 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
181 to store the VM snapshots */
182 struct drivelist drives
= QTAILQ_HEAD_INITIALIZER(drives
);
183 struct driveoptlist driveopts
= QTAILQ_HEAD_INITIALIZER(driveopts
);
184 DriveInfo
*extboot_drive
= NULL
;
185 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
186 static DisplayState
*display_state
;
187 DisplayType display_type
= DT_DEFAULT
;
188 const char* keyboard_layout
= NULL
;
191 NICInfo nd_table
[MAX_NICS
];
194 static int rtc_utc
= 1;
195 static int rtc_date_offset
= -1; /* -1 means no change */
196 QEMUClock
*rtc_clock
;
197 int vga_interface_type
= VGA_NONE
;
199 int graphic_width
= 1024;
200 int graphic_height
= 768;
201 int graphic_depth
= 8;
203 int graphic_width
= 800;
204 int graphic_height
= 600;
205 int graphic_depth
= 15;
207 static int full_screen
= 0;
209 static int no_frame
= 0;
212 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
213 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
214 CharDriverState
*virtcon_hds
[MAX_VIRTIO_CONSOLES
];
216 int win2k_install_hack
= 0;
221 const char *assigned_devices
[MAX_DEV_ASSIGN_CMDLINE
];
222 int assigned_devices_index
;
227 const char *vnc_display
;
228 int acpi_enabled
= 1;
236 int graphic_rotate
= 0;
237 uint8_t irq0override
= 1;
241 const char *watchdog
;
242 const char *option_rom
[MAX_OPTION_ROMS
];
244 int semihosting_enabled
= 0;
245 int time_drift_fix
= 0;
246 unsigned int kvm_shadow_memory
= 0;
247 const char *mem_path
= NULL
;
249 int mem_prealloc
= 1; /* force preallocation of physical target memory */
254 const char *qemu_name
;
257 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
258 unsigned int nb_prom_envs
= 0;
259 const char *prom_envs
[MAX_PROM_ENVS
];
261 const char *nvram
= NULL
;
265 uint64_t node_mem
[MAX_NODES
];
266 uint64_t node_cpumask
[MAX_NODES
];
268 static CPUState
*cur_cpu
;
269 static CPUState
*next_cpu
;
270 static int timer_alarm_pending
= 1;
271 /* Conversion factor from emulated instructions to virtual clock ticks. */
272 static int icount_time_shift
;
273 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
274 #define MAX_ICOUNT_SHIFT 10
275 /* Compensate for varying guest execution speed. */
276 static int64_t qemu_icount_bias
;
277 static QEMUTimer
*icount_rt_timer
;
278 static QEMUTimer
*icount_vm_timer
;
279 static QEMUTimer
*nographic_timer
;
281 uint8_t qemu_uuid
[16];
283 static QEMUBootSetHandler
*boot_set_handler
;
284 static void *boot_set_opaque
;
286 static int default_serial
= 1;
287 static int default_parallel
= 1;
288 static int default_virtcon
= 1;
289 static int default_monitor
= 1;
290 static int default_vga
= 1;
291 static int default_floppy
= 1;
292 static int default_cdrom
= 1;
293 static int default_sdcard
= 1;
299 { .driver
= "isa-serial", .flag
= &default_serial
},
300 { .driver
= "isa-parallel", .flag
= &default_parallel
},
301 { .driver
= "isa-fdc", .flag
= &default_floppy
},
302 { .driver
= "ide-drive", .flag
= &default_cdrom
},
303 { .driver
= "virtio-console-pci", .flag
= &default_virtcon
},
304 { .driver
= "virtio-console-s390", .flag
= &default_virtcon
},
305 { .driver
= "VGA", .flag
= &default_vga
},
306 { .driver
= "cirrus-vga", .flag
= &default_vga
},
307 { .driver
= "vmware-svga", .flag
= &default_vga
},
310 static int default_driver_check(QemuOpts
*opts
, void *opaque
)
312 const char *driver
= qemu_opt_get(opts
, "driver");
317 for (i
= 0; i
< ARRAY_SIZE(default_list
); i
++) {
318 if (strcmp(default_list
[i
].driver
, driver
) != 0)
320 *(default_list
[i
].flag
) = 0;
325 /***********************************************************/
326 /* x86 ISA bus support */
328 target_phys_addr_t isa_mem_base
= 0;
331 /***********************************************************/
332 void hw_error(const char *fmt
, ...)
338 fprintf(stderr
, "qemu: hardware error: ");
339 vfprintf(stderr
, fmt
, ap
);
340 fprintf(stderr
, "\n");
341 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
342 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
344 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
346 cpu_dump_state(env
, stderr
, fprintf
, 0);
353 static void set_proc_name(const char *s
)
355 #if defined(__linux__) && defined(PR_SET_NAME)
359 name
[sizeof(name
) - 1] = 0;
360 strncpy(name
, s
, sizeof(name
));
361 /* Could rewrite argv[0] too, but that's a bit more complicated.
362 This simple way is enough for `top'. */
363 prctl(PR_SET_NAME
, name
);
370 static QEMUBalloonEvent
*qemu_balloon_event
;
371 void *qemu_balloon_event_opaque
;
373 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
375 qemu_balloon_event
= func
;
376 qemu_balloon_event_opaque
= opaque
;
379 void qemu_balloon(ram_addr_t target
)
381 if (qemu_balloon_event
)
382 qemu_balloon_event(qemu_balloon_event_opaque
, target
);
385 ram_addr_t
qemu_balloon_status(void)
387 if (qemu_balloon_event
)
388 return qemu_balloon_event(qemu_balloon_event_opaque
, 0);
392 /***********************************************************/
395 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
396 static void *qemu_put_kbd_event_opaque
;
397 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
398 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
400 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
402 qemu_put_kbd_event_opaque
= opaque
;
403 qemu_put_kbd_event
= func
;
406 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
407 void *opaque
, int absolute
,
410 QEMUPutMouseEntry
*s
, *cursor
;
412 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
414 s
->qemu_put_mouse_event
= func
;
415 s
->qemu_put_mouse_event_opaque
= opaque
;
416 s
->qemu_put_mouse_event_absolute
= absolute
;
417 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
420 if (!qemu_put_mouse_event_head
) {
421 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
425 cursor
= qemu_put_mouse_event_head
;
426 while (cursor
->next
!= NULL
)
427 cursor
= cursor
->next
;
430 qemu_put_mouse_event_current
= s
;
435 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
437 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
439 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
442 cursor
= qemu_put_mouse_event_head
;
443 while (cursor
!= NULL
&& cursor
!= entry
) {
445 cursor
= cursor
->next
;
448 if (cursor
== NULL
) // does not exist or list empty
450 else if (prev
== NULL
) { // entry is head
451 qemu_put_mouse_event_head
= cursor
->next
;
452 if (qemu_put_mouse_event_current
== entry
)
453 qemu_put_mouse_event_current
= cursor
->next
;
454 qemu_free(entry
->qemu_put_mouse_event_name
);
459 prev
->next
= entry
->next
;
461 if (qemu_put_mouse_event_current
== entry
)
462 qemu_put_mouse_event_current
= prev
;
464 qemu_free(entry
->qemu_put_mouse_event_name
);
468 void kbd_put_keycode(int keycode
)
470 if (qemu_put_kbd_event
) {
471 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
475 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
477 QEMUPutMouseEvent
*mouse_event
;
478 void *mouse_event_opaque
;
481 if (!qemu_put_mouse_event_current
) {
486 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
488 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
491 if (graphic_rotate
) {
492 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
495 width
= graphic_width
- 1;
496 mouse_event(mouse_event_opaque
,
497 width
- dy
, dx
, dz
, buttons_state
);
499 mouse_event(mouse_event_opaque
,
500 dx
, dy
, dz
, buttons_state
);
504 int kbd_mouse_is_absolute(void)
506 if (!qemu_put_mouse_event_current
)
509 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
512 static void info_mice_iter(QObject
*data
, void *opaque
)
515 Monitor
*mon
= opaque
;
517 mouse
= qobject_to_qdict(data
);
518 monitor_printf(mon
, "%c Mouse #%" PRId64
": %s\n",
519 (qdict_get_bool(mouse
, "current") ? '*' : ' '),
520 qdict_get_int(mouse
, "index"), qdict_get_str(mouse
, "name"));
523 void do_info_mice_print(Monitor
*mon
, const QObject
*data
)
527 mice_list
= qobject_to_qlist(data
);
528 if (qlist_empty(mice_list
)) {
529 monitor_printf(mon
, "No mouse devices connected\n");
533 qlist_iter(mice_list
, info_mice_iter
, mon
);
537 * do_info_mice(): Show VM mice information
539 * Each mouse is represented by a QDict, the returned QObject is a QList of
542 * The mouse QDict contains the following:
544 * - "name": mouse's name
545 * - "index": mouse's index
546 * - "current": true if this mouse is receiving events, false otherwise
550 * [ { "name": "QEMU Microsoft Mouse", "index": 0, "current": false },
551 * { "name": "QEMU PS/2 Mouse", "index": 1, "current": true } ]
553 void do_info_mice(Monitor
*mon
, QObject
**ret_data
)
555 QEMUPutMouseEntry
*cursor
;
559 mice_list
= qlist_new();
561 if (!qemu_put_mouse_event_head
) {
565 cursor
= qemu_put_mouse_event_head
;
566 while (cursor
!= NULL
) {
568 obj
= qobject_from_jsonf("{ 'name': %s, 'index': %d, 'current': %i }",
569 cursor
->qemu_put_mouse_event_name
,
570 index
, cursor
== qemu_put_mouse_event_current
);
571 qlist_append_obj(mice_list
, obj
);
573 cursor
= cursor
->next
;
577 *ret_data
= QOBJECT(mice_list
);
580 void do_mouse_set(Monitor
*mon
, const QDict
*qdict
)
582 QEMUPutMouseEntry
*cursor
;
584 int index
= qdict_get_int(qdict
, "index");
586 if (!qemu_put_mouse_event_head
) {
587 monitor_printf(mon
, "No mouse devices connected\n");
591 cursor
= qemu_put_mouse_event_head
;
592 while (cursor
!= NULL
&& index
!= i
) {
594 cursor
= cursor
->next
;
598 qemu_put_mouse_event_current
= cursor
;
600 monitor_printf(mon
, "Mouse at given index not found\n");
603 /* compute with 96 bit intermediate result: (a*b)/c */
604 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
609 #ifdef HOST_WORDS_BIGENDIAN
619 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
620 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
623 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
627 /***********************************************************/
628 /* real time host monotonic timer */
630 static int64_t get_clock_realtime(void)
634 gettimeofday(&tv
, NULL
);
635 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
640 static int64_t clock_freq
;
642 static void init_get_clock(void)
646 ret
= QueryPerformanceFrequency(&freq
);
648 fprintf(stderr
, "Could not calibrate ticks\n");
651 clock_freq
= freq
.QuadPart
;
654 static int64_t get_clock(void)
657 QueryPerformanceCounter(&ti
);
658 return muldiv64(ti
.QuadPart
, get_ticks_per_sec(), clock_freq
);
663 static int use_rt_clock
;
665 static void init_get_clock(void)
668 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
669 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
672 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
679 static int64_t get_clock(void)
681 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
682 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
685 clock_gettime(CLOCK_MONOTONIC
, &ts
);
686 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
690 /* XXX: using gettimeofday leads to problems if the date
691 changes, so it should be avoided. */
692 return get_clock_realtime();
697 /* Return the virtual CPU time, based on the instruction counter. */
698 static int64_t cpu_get_icount(void)
701 CPUState
*env
= cpu_single_env
;;
702 icount
= qemu_icount
;
705 fprintf(stderr
, "Bad clock read\n");
706 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
708 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
711 /***********************************************************/
712 /* guest cycle counter */
714 typedef struct TimersState
{
715 int64_t cpu_ticks_prev
;
716 int64_t cpu_ticks_offset
;
717 int64_t cpu_clock_offset
;
718 int32_t cpu_ticks_enabled
;
722 TimersState timers_state
;
724 /* return the host CPU cycle counter and handle stop/restart */
725 int64_t cpu_get_ticks(void)
728 return cpu_get_icount();
730 if (!timers_state
.cpu_ticks_enabled
) {
731 return timers_state
.cpu_ticks_offset
;
734 ticks
= cpu_get_real_ticks();
735 if (timers_state
.cpu_ticks_prev
> ticks
) {
736 /* Note: non increasing ticks may happen if the host uses
738 timers_state
.cpu_ticks_offset
+= timers_state
.cpu_ticks_prev
- ticks
;
740 timers_state
.cpu_ticks_prev
= ticks
;
741 return ticks
+ timers_state
.cpu_ticks_offset
;
745 /* return the host CPU monotonic timer and handle stop/restart */
746 static int64_t cpu_get_clock(void)
749 if (!timers_state
.cpu_ticks_enabled
) {
750 return timers_state
.cpu_clock_offset
;
753 return ti
+ timers_state
.cpu_clock_offset
;
757 /* enable cpu_get_ticks() */
758 void cpu_enable_ticks(void)
760 if (!timers_state
.cpu_ticks_enabled
) {
761 timers_state
.cpu_ticks_offset
-= cpu_get_real_ticks();
762 timers_state
.cpu_clock_offset
-= get_clock();
763 timers_state
.cpu_ticks_enabled
= 1;
767 /* disable cpu_get_ticks() : the clock is stopped. You must not call
768 cpu_get_ticks() after that. */
769 void cpu_disable_ticks(void)
771 if (timers_state
.cpu_ticks_enabled
) {
772 timers_state
.cpu_ticks_offset
= cpu_get_ticks();
773 timers_state
.cpu_clock_offset
= cpu_get_clock();
774 timers_state
.cpu_ticks_enabled
= 0;
778 /***********************************************************/
781 #define QEMU_CLOCK_REALTIME 0
782 #define QEMU_CLOCK_VIRTUAL 1
783 #define QEMU_CLOCK_HOST 2
787 /* XXX: add frequency */
795 struct QEMUTimer
*next
;
798 struct qemu_alarm_timer
{
802 int (*start
)(struct qemu_alarm_timer
*t
);
803 void (*stop
)(struct qemu_alarm_timer
*t
);
804 void (*rearm
)(struct qemu_alarm_timer
*t
);
808 #define ALARM_FLAG_DYNTICKS 0x1
809 #define ALARM_FLAG_EXPIRED 0x2
811 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
813 return t
&& (t
->flags
& ALARM_FLAG_DYNTICKS
);
816 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
818 if (!alarm_has_dynticks(t
))
824 /* TODO: MIN_TIMER_REARM_US should be optimized */
825 #define MIN_TIMER_REARM_US 250
827 static struct qemu_alarm_timer
*alarm_timer
;
831 struct qemu_alarm_win32
{
834 } alarm_win32_data
= {0, -1};
836 static int win32_start_timer(struct qemu_alarm_timer
*t
);
837 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
838 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
842 static int unix_start_timer(struct qemu_alarm_timer
*t
);
843 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
847 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
848 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
849 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
851 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
852 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
854 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
855 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
857 #endif /* __linux__ */
861 /* Correlation between real and virtual time is always going to be
862 fairly approximate, so ignore small variation.
863 When the guest is idle real and virtual time will be aligned in
865 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
867 static void icount_adjust(void)
872 static int64_t last_delta
;
873 /* If the VM is not running, then do nothing. */
877 cur_time
= cpu_get_clock();
878 cur_icount
= qemu_get_clock(vm_clock
);
879 delta
= cur_icount
- cur_time
;
880 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
882 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
883 && icount_time_shift
> 0) {
884 /* The guest is getting too far ahead. Slow time down. */
888 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
889 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
890 /* The guest is getting too far behind. Speed time up. */
894 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
897 static void icount_adjust_rt(void * opaque
)
899 qemu_mod_timer(icount_rt_timer
,
900 qemu_get_clock(rt_clock
) + 1000);
904 static void icount_adjust_vm(void * opaque
)
906 qemu_mod_timer(icount_vm_timer
,
907 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
911 static void init_icount_adjust(void)
913 /* Have both realtime and virtual time triggers for speed adjustment.
914 The realtime trigger catches emulated time passing too slowly,
915 the virtual time trigger catches emulated time passing too fast.
916 Realtime triggers occur even when idle, so use them less frequently
918 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
919 qemu_mod_timer(icount_rt_timer
,
920 qemu_get_clock(rt_clock
) + 1000);
921 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
922 qemu_mod_timer(icount_vm_timer
,
923 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
926 static struct qemu_alarm_timer alarm_timers
[] = {
929 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
930 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
931 /* HPET - if available - is preferred */
932 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
933 /* ...otherwise try RTC */
934 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
936 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
938 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
939 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
940 {"win32", 0, win32_start_timer
,
941 win32_stop_timer
, NULL
, &alarm_win32_data
},
946 static void show_available_alarms(void)
950 printf("Available alarm timers, in order of precedence:\n");
951 for (i
= 0; alarm_timers
[i
].name
; i
++)
952 printf("%s\n", alarm_timers
[i
].name
);
955 static void configure_alarms(char const *opt
)
959 int count
= ARRAY_SIZE(alarm_timers
) - 1;
962 struct qemu_alarm_timer tmp
;
964 if (!strcmp(opt
, "?")) {
965 show_available_alarms();
969 arg
= qemu_strdup(opt
);
971 /* Reorder the array */
972 name
= strtok(arg
, ",");
974 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
975 if (!strcmp(alarm_timers
[i
].name
, name
))
980 fprintf(stderr
, "Unknown clock %s\n", name
);
989 tmp
= alarm_timers
[i
];
990 alarm_timers
[i
] = alarm_timers
[cur
];
991 alarm_timers
[cur
] = tmp
;
995 name
= strtok(NULL
, ",");
1001 /* Disable remaining timers */
1002 for (i
= cur
; i
< count
; i
++)
1003 alarm_timers
[i
].name
= NULL
;
1005 show_available_alarms();
1010 #define QEMU_NUM_CLOCKS 3
1012 QEMUClock
*rt_clock
;
1013 QEMUClock
*vm_clock
;
1014 QEMUClock
*host_clock
;
1016 static QEMUTimer
*active_timers
[QEMU_NUM_CLOCKS
];
1018 static QEMUClock
*qemu_new_clock(int type
)
1021 clock
= qemu_mallocz(sizeof(QEMUClock
));
1026 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1030 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1033 ts
->opaque
= opaque
;
1037 void qemu_free_timer(QEMUTimer
*ts
)
1042 /* stop a timer, but do not dealloc it */
1043 void qemu_del_timer(QEMUTimer
*ts
)
1047 /* NOTE: this code must be signal safe because
1048 qemu_timer_expired() can be called from a signal. */
1049 pt
= &active_timers
[ts
->clock
->type
];
1062 /* modify the current timer so that it will be fired when current_time
1063 >= expire_time. The corresponding callback will be called. */
1064 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1070 /* add the timer in the sorted list */
1071 /* NOTE: this code must be signal safe because
1072 qemu_timer_expired() can be called from a signal. */
1073 pt
= &active_timers
[ts
->clock
->type
];
1078 if (t
->expire_time
> expire_time
)
1082 ts
->expire_time
= expire_time
;
1086 /* Rearm if necessary */
1087 if (pt
== &active_timers
[ts
->clock
->type
]) {
1088 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1089 qemu_rearm_alarm_timer(alarm_timer
);
1091 /* Interrupt execution to force deadline recalculation. */
1093 qemu_notify_event();
1097 int qemu_timer_pending(QEMUTimer
*ts
)
1100 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1107 int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1111 return (timer_head
->expire_time
<= current_time
);
1114 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1120 if (!ts
|| ts
->expire_time
> current_time
)
1122 /* remove timer from the list before calling the callback */
1123 *ptimer_head
= ts
->next
;
1126 /* run the callback (the timer list can be modified) */
1131 int64_t qemu_get_clock(QEMUClock
*clock
)
1133 switch(clock
->type
) {
1134 case QEMU_CLOCK_REALTIME
:
1135 return get_clock() / 1000000;
1137 case QEMU_CLOCK_VIRTUAL
:
1139 return cpu_get_icount();
1141 return cpu_get_clock();
1143 case QEMU_CLOCK_HOST
:
1144 return get_clock_realtime();
1148 static void init_clocks(void)
1151 rt_clock
= qemu_new_clock(QEMU_CLOCK_REALTIME
);
1152 vm_clock
= qemu_new_clock(QEMU_CLOCK_VIRTUAL
);
1153 host_clock
= qemu_new_clock(QEMU_CLOCK_HOST
);
1155 rtc_clock
= host_clock
;
1159 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1161 uint64_t expire_time
;
1163 if (qemu_timer_pending(ts
)) {
1164 expire_time
= ts
->expire_time
;
1168 qemu_put_be64(f
, expire_time
);
1171 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1173 uint64_t expire_time
;
1175 expire_time
= qemu_get_be64(f
);
1176 if (expire_time
!= -1) {
1177 qemu_mod_timer(ts
, expire_time
);
1183 static const VMStateDescription vmstate_timers
= {
1186 .minimum_version_id
= 1,
1187 .minimum_version_id_old
= 1,
1188 .fields
= (VMStateField
[]) {
1189 VMSTATE_INT64(cpu_ticks_offset
, TimersState
),
1190 VMSTATE_INT64(dummy
, TimersState
),
1191 VMSTATE_INT64_V(cpu_clock_offset
, TimersState
, 2),
1192 VMSTATE_END_OF_LIST()
1196 static void qemu_event_increment(void);
1199 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1200 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1203 static void host_alarm_handler(int host_signum
)
1207 #define DISP_FREQ 1000
1209 static int64_t delta_min
= INT64_MAX
;
1210 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1212 ti
= qemu_get_clock(vm_clock
);
1213 if (last_clock
!= 0) {
1214 delta
= ti
- last_clock
;
1215 if (delta
< delta_min
)
1217 if (delta
> delta_max
)
1220 if (++count
== DISP_FREQ
) {
1221 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1222 muldiv64(delta_min
, 1000000, get_ticks_per_sec()),
1223 muldiv64(delta_max
, 1000000, get_ticks_per_sec()),
1224 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, get_ticks_per_sec()),
1225 (double)get_ticks_per_sec() / ((double)delta_cum
/ DISP_FREQ
));
1227 delta_min
= INT64_MAX
;
1235 if (alarm_has_dynticks(alarm_timer
) ||
1237 qemu_timer_expired(active_timers
[QEMU_CLOCK_VIRTUAL
],
1238 qemu_get_clock(vm_clock
))) ||
1239 qemu_timer_expired(active_timers
[QEMU_CLOCK_REALTIME
],
1240 qemu_get_clock(rt_clock
)) ||
1241 qemu_timer_expired(active_timers
[QEMU_CLOCK_HOST
],
1242 qemu_get_clock(host_clock
))) {
1243 qemu_event_increment();
1244 if (alarm_timer
) alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1246 #ifndef CONFIG_IOTHREAD
1248 /* stop the currently executing cpu because a timer occured */
1252 timer_alarm_pending
= 1;
1253 qemu_notify_event();
1257 static int64_t qemu_next_deadline(void)
1259 /* To avoid problems with overflow limit this to 2^32. */
1260 int64_t delta
= INT32_MAX
;
1262 if (active_timers
[QEMU_CLOCK_VIRTUAL
]) {
1263 delta
= active_timers
[QEMU_CLOCK_VIRTUAL
]->expire_time
-
1264 qemu_get_clock(vm_clock
);
1266 if (active_timers
[QEMU_CLOCK_HOST
]) {
1267 int64_t hdelta
= active_timers
[QEMU_CLOCK_HOST
]->expire_time
-
1268 qemu_get_clock(host_clock
);
1279 #if defined(__linux__)
1280 static uint64_t qemu_next_deadline_dyntick(void)
1288 delta
= (qemu_next_deadline() + 999) / 1000;
1290 if (active_timers
[QEMU_CLOCK_REALTIME
]) {
1291 rtdelta
= (active_timers
[QEMU_CLOCK_REALTIME
]->expire_time
-
1292 qemu_get_clock(rt_clock
))*1000;
1293 if (rtdelta
< delta
)
1297 if (delta
< MIN_TIMER_REARM_US
)
1298 delta
= MIN_TIMER_REARM_US
;
1306 /* Sets a specific flag */
1307 static int fcntl_setfl(int fd
, int flag
)
1311 flags
= fcntl(fd
, F_GETFL
);
1315 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1321 #if defined(__linux__)
1323 #define RTC_FREQ 1024
1325 static void enable_sigio_timer(int fd
)
1327 struct sigaction act
;
1330 sigfillset(&act
.sa_mask
);
1332 act
.sa_handler
= host_alarm_handler
;
1334 sigaction(SIGIO
, &act
, NULL
);
1335 fcntl_setfl(fd
, O_ASYNC
);
1336 fcntl(fd
, F_SETOWN
, getpid());
1339 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1341 struct hpet_info info
;
1344 fd
= qemu_open("/dev/hpet", O_RDONLY
);
1349 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1351 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1352 "error, but for better emulation accuracy type:\n"
1353 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1357 /* Check capabilities */
1358 r
= ioctl(fd
, HPET_INFO
, &info
);
1362 /* Enable periodic mode */
1363 r
= ioctl(fd
, HPET_EPI
, 0);
1364 if (info
.hi_flags
&& (r
< 0))
1367 /* Enable interrupt */
1368 r
= ioctl(fd
, HPET_IE_ON
, 0);
1372 enable_sigio_timer(fd
);
1373 t
->priv
= (void *)(long)fd
;
1381 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1383 int fd
= (long)t
->priv
;
1388 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1391 unsigned long current_rtc_freq
= 0;
1393 TFR(rtc_fd
= qemu_open("/dev/rtc", O_RDONLY
));
1396 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1397 if (current_rtc_freq
!= RTC_FREQ
&&
1398 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1399 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1400 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1401 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1404 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1410 enable_sigio_timer(rtc_fd
);
1412 t
->priv
= (void *)(long)rtc_fd
;
1417 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1419 int rtc_fd
= (long)t
->priv
;
1424 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1428 struct sigaction act
;
1430 sigfillset(&act
.sa_mask
);
1432 act
.sa_handler
= host_alarm_handler
;
1434 sigaction(SIGALRM
, &act
, NULL
);
1437 * Initialize ev struct to 0 to avoid valgrind complaining
1438 * about uninitialized data in timer_create call
1440 memset(&ev
, 0, sizeof(ev
));
1441 ev
.sigev_value
.sival_int
= 0;
1442 ev
.sigev_notify
= SIGEV_SIGNAL
;
1443 ev
.sigev_signo
= SIGALRM
;
1445 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1446 perror("timer_create");
1448 /* disable dynticks */
1449 fprintf(stderr
, "Dynamic Ticks disabled\n");
1454 t
->priv
= (void *)(long)host_timer
;
1459 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1461 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1463 timer_delete(host_timer
);
1466 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1468 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1469 struct itimerspec timeout
;
1470 int64_t nearest_delta_us
= INT64_MAX
;
1473 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1474 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1475 !active_timers
[QEMU_CLOCK_HOST
])
1478 nearest_delta_us
= qemu_next_deadline_dyntick();
1480 /* check whether a timer is already running */
1481 if (timer_gettime(host_timer
, &timeout
)) {
1483 fprintf(stderr
, "Internal timer error: aborting\n");
1486 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1487 if (current_us
&& current_us
<= nearest_delta_us
)
1490 timeout
.it_interval
.tv_sec
= 0;
1491 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1492 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1493 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1494 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1496 fprintf(stderr
, "Internal timer error: aborting\n");
1501 #endif /* defined(__linux__) */
1503 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1505 struct sigaction act
;
1506 struct itimerval itv
;
1510 sigfillset(&act
.sa_mask
);
1512 act
.sa_handler
= host_alarm_handler
;
1514 sigaction(SIGALRM
, &act
, NULL
);
1516 itv
.it_interval
.tv_sec
= 0;
1517 /* for i386 kernel 2.6 to get 1 ms */
1518 itv
.it_interval
.tv_usec
= 999;
1519 itv
.it_value
.tv_sec
= 0;
1520 itv
.it_value
.tv_usec
= 10 * 1000;
1522 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1529 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1531 struct itimerval itv
;
1533 memset(&itv
, 0, sizeof(itv
));
1534 setitimer(ITIMER_REAL
, &itv
, NULL
);
1537 #endif /* !defined(_WIN32) */
1542 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1545 struct qemu_alarm_win32
*data
= t
->priv
;
1548 memset(&tc
, 0, sizeof(tc
));
1549 timeGetDevCaps(&tc
, sizeof(tc
));
1551 if (data
->period
< tc
.wPeriodMin
)
1552 data
->period
= tc
.wPeriodMin
;
1554 timeBeginPeriod(data
->period
);
1556 flags
= TIME_CALLBACK_FUNCTION
;
1557 if (alarm_has_dynticks(t
))
1558 flags
|= TIME_ONESHOT
;
1560 flags
|= TIME_PERIODIC
;
1562 data
->timerId
= timeSetEvent(1, // interval (ms)
1563 data
->period
, // resolution
1564 host_alarm_handler
, // function
1565 (DWORD
)t
, // parameter
1568 if (!data
->timerId
) {
1569 fprintf(stderr
, "Failed to initialize win32 alarm timer: %ld\n",
1571 timeEndPeriod(data
->period
);
1578 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1580 struct qemu_alarm_win32
*data
= t
->priv
;
1582 timeKillEvent(data
->timerId
);
1583 timeEndPeriod(data
->period
);
1586 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1588 struct qemu_alarm_win32
*data
= t
->priv
;
1590 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1591 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1592 !active_timers
[QEMU_CLOCK_HOST
])
1595 timeKillEvent(data
->timerId
);
1597 data
->timerId
= timeSetEvent(1,
1601 TIME_ONESHOT
| TIME_PERIODIC
);
1603 if (!data
->timerId
) {
1604 fprintf(stderr
, "Failed to re-arm win32 alarm timer %ld\n",
1607 timeEndPeriod(data
->period
);
1614 static int init_timer_alarm(void)
1616 struct qemu_alarm_timer
*t
= NULL
;
1619 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1620 t
= &alarm_timers
[i
];
1640 static void quit_timers(void)
1642 alarm_timer
->stop(alarm_timer
);
1646 /***********************************************************/
1647 /* host time/date access */
1648 void qemu_get_timedate(struct tm
*tm
, int offset
)
1655 if (rtc_date_offset
== -1) {
1659 ret
= localtime(&ti
);
1661 ti
-= rtc_date_offset
;
1665 memcpy(tm
, ret
, sizeof(struct tm
));
1668 int qemu_timedate_diff(struct tm
*tm
)
1672 if (rtc_date_offset
== -1)
1674 seconds
= mktimegm(tm
);
1676 seconds
= mktime(tm
);
1678 seconds
= mktimegm(tm
) + rtc_date_offset
;
1680 return seconds
- time(NULL
);
1683 static void configure_rtc_date_offset(const char *startdate
, int legacy
)
1685 time_t rtc_start_date
;
1688 if (!strcmp(startdate
, "now") && legacy
) {
1689 rtc_date_offset
= -1;
1691 if (sscanf(startdate
, "%d-%d-%dT%d:%d:%d",
1699 } else if (sscanf(startdate
, "%d-%d-%d",
1702 &tm
.tm_mday
) == 3) {
1711 rtc_start_date
= mktimegm(&tm
);
1712 if (rtc_start_date
== -1) {
1714 fprintf(stderr
, "Invalid date format. Valid formats are:\n"
1715 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1718 rtc_date_offset
= time(NULL
) - rtc_start_date
;
1722 static void configure_rtc(QemuOpts
*opts
)
1726 value
= qemu_opt_get(opts
, "base");
1728 if (!strcmp(value
, "utc")) {
1730 } else if (!strcmp(value
, "localtime")) {
1733 configure_rtc_date_offset(value
, 0);
1736 value
= qemu_opt_get(opts
, "clock");
1738 if (!strcmp(value
, "host")) {
1739 rtc_clock
= host_clock
;
1740 } else if (!strcmp(value
, "vm")) {
1741 rtc_clock
= vm_clock
;
1743 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1747 #ifdef CONFIG_TARGET_I386
1748 value
= qemu_opt_get(opts
, "driftfix");
1750 if (!strcmp(buf
, "slew")) {
1752 } else if (!strcmp(buf
, "none")) {
1755 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1763 static void socket_cleanup(void)
1768 static int socket_init(void)
1773 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1775 err
= WSAGetLastError();
1776 fprintf(stderr
, "WSAStartup: %d\n", err
);
1779 atexit(socket_cleanup
);
1784 /***********************************************************/
1785 /* Bluetooth support */
1788 static struct HCIInfo
*hci_table
[MAX_NICS
];
1790 static struct bt_vlan_s
{
1791 struct bt_scatternet_s net
;
1793 struct bt_vlan_s
*next
;
1796 /* find or alloc a new bluetooth "VLAN" */
1797 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1799 struct bt_vlan_s
**pvlan
, *vlan
;
1800 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1804 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1806 pvlan
= &first_bt_vlan
;
1807 while (*pvlan
!= NULL
)
1808 pvlan
= &(*pvlan
)->next
;
1813 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1817 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1822 static struct HCIInfo null_hci
= {
1823 .cmd_send
= null_hci_send
,
1824 .sco_send
= null_hci_send
,
1825 .acl_send
= null_hci_send
,
1826 .bdaddr_set
= null_hci_addr_set
,
1829 struct HCIInfo
*qemu_next_hci(void)
1831 if (cur_hci
== nb_hcis
)
1834 return hci_table
[cur_hci
++];
1837 static struct HCIInfo
*hci_init(const char *str
)
1840 struct bt_scatternet_s
*vlan
= 0;
1842 if (!strcmp(str
, "null"))
1845 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
1847 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
1848 else if (!strncmp(str
, "hci", 3)) {
1851 if (!strncmp(str
+ 3, ",vlan=", 6)) {
1852 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
1857 vlan
= qemu_find_bt_vlan(0);
1859 return bt_new_hci(vlan
);
1862 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
1867 static int bt_hci_parse(const char *str
)
1869 struct HCIInfo
*hci
;
1872 if (nb_hcis
>= MAX_NICS
) {
1873 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
1877 hci
= hci_init(str
);
1886 bdaddr
.b
[5] = 0x56 + nb_hcis
;
1887 hci
->bdaddr_set(hci
, bdaddr
.b
);
1889 hci_table
[nb_hcis
++] = hci
;
1894 static void bt_vhci_add(int vlan_id
)
1896 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
1899 fprintf(stderr
, "qemu: warning: adding a VHCI to "
1900 "an empty scatternet %i\n", vlan_id
);
1902 bt_vhci_init(bt_new_hci(vlan
));
1905 static struct bt_device_s
*bt_device_add(const char *opt
)
1907 struct bt_scatternet_s
*vlan
;
1909 char *endp
= strstr(opt
, ",vlan=");
1910 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
1913 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
1916 vlan_id
= strtol(endp
+ 6, &endp
, 0);
1918 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
1923 vlan
= qemu_find_bt_vlan(vlan_id
);
1926 fprintf(stderr
, "qemu: warning: adding a slave device to "
1927 "an empty scatternet %i\n", vlan_id
);
1929 if (!strcmp(devname
, "keyboard"))
1930 return bt_keyboard_init(vlan
);
1932 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
1936 static int bt_parse(const char *opt
)
1938 const char *endp
, *p
;
1941 if (strstart(opt
, "hci", &endp
)) {
1942 if (!*endp
|| *endp
== ',') {
1944 if (!strstart(endp
, ",vlan=", 0))
1947 return bt_hci_parse(opt
);
1949 } else if (strstart(opt
, "vhci", &endp
)) {
1950 if (!*endp
|| *endp
== ',') {
1952 if (strstart(endp
, ",vlan=", &p
)) {
1953 vlan
= strtol(p
, (char **) &endp
, 0);
1955 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
1959 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
1968 } else if (strstart(opt
, "device:", &endp
))
1969 return !bt_device_add(endp
);
1971 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
1975 /***********************************************************/
1976 /* QEMU Block devices */
1978 #define HD_ALIAS "index=%d,media=disk"
1979 #define CDROM_ALIAS "index=2,media=cdrom"
1980 #define FD_ALIAS "index=%d,if=floppy"
1981 #define PFLASH_ALIAS "if=pflash"
1982 #define MTD_ALIAS "if=mtd"
1983 #define SD_ALIAS "index=0,if=sd"
1985 QemuOpts
*drive_add(const char *file
, const char *fmt
, ...)
1992 vsnprintf(optstr
, sizeof(optstr
), fmt
, ap
);
1995 opts
= qemu_opts_parse(&qemu_drive_opts
, optstr
, NULL
);
1997 fprintf(stderr
, "%s: huh? duplicate? (%s)\n",
1998 __FUNCTION__
, optstr
);
2002 qemu_opt_set(opts
, "file", file
);
2006 DriveInfo
*drive_get(BlockInterfaceType type
, int bus
, int unit
)
2010 /* seek interface, bus and unit */
2012 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
2013 if (dinfo
->type
== type
&&
2014 dinfo
->bus
== bus
&&
2015 dinfo
->unit
== unit
)
2022 DriveInfo
*drive_get_by_id(const char *id
)
2026 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
2027 if (strcmp(id
, dinfo
->id
))
2034 int drive_get_max_bus(BlockInterfaceType type
)
2040 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
2041 if(dinfo
->type
== type
&&
2042 dinfo
->bus
> max_bus
)
2043 max_bus
= dinfo
->bus
;
2048 const char *drive_get_serial(BlockDriverState
*bdrv
)
2052 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
2053 if (dinfo
->bdrv
== bdrv
)
2054 return dinfo
->serial
;
2060 BlockInterfaceErrorAction
drive_get_on_error(
2061 BlockDriverState
*bdrv
, int is_read
)
2065 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
2066 if (dinfo
->bdrv
== bdrv
)
2067 return is_read
? dinfo
->on_read_error
: dinfo
->on_write_error
;
2070 return is_read
? BLOCK_ERR_REPORT
: BLOCK_ERR_STOP_ENOSPC
;
2073 static void bdrv_format_print(void *opaque
, const char *name
)
2075 fprintf(stderr
, " %s", name
);
2078 void drive_uninit(DriveInfo
*dinfo
)
2080 qemu_opts_del(dinfo
->opts
);
2081 bdrv_delete(dinfo
->bdrv
);
2082 QTAILQ_REMOVE(&drives
, dinfo
, next
);
2086 static int parse_block_error_action(const char *buf
, int is_read
)
2088 if (!strcmp(buf
, "ignore")) {
2089 return BLOCK_ERR_IGNORE
;
2090 } else if (!is_read
&& !strcmp(buf
, "enospc")) {
2091 return BLOCK_ERR_STOP_ENOSPC
;
2092 } else if (!strcmp(buf
, "stop")) {
2093 return BLOCK_ERR_STOP_ANY
;
2094 } else if (!strcmp(buf
, "report")) {
2095 return BLOCK_ERR_REPORT
;
2097 fprintf(stderr
, "qemu: '%s' invalid %s error action\n",
2098 buf
, is_read
? "read" : "write");
2103 DriveInfo
*drive_init(QemuOpts
*opts
, void *opaque
,
2107 const char *file
= NULL
;
2110 const char *mediastr
= "";
2111 BlockInterfaceType type
;
2112 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
2113 int bus_id
, unit_id
;
2114 int cyls
, heads
, secs
, translation
;
2115 BlockDriver
*drv
= NULL
;
2116 QEMUMachine
*machine
= opaque
;
2123 int on_read_error
, on_write_error
;
2124 const char *devaddr
;
2131 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2134 if (machine
&& machine
->use_scsi
) {
2136 max_devs
= MAX_SCSI_DEVS
;
2137 pstrcpy(devname
, sizeof(devname
), "scsi");
2140 max_devs
= MAX_IDE_DEVS
;
2141 pstrcpy(devname
, sizeof(devname
), "ide");
2145 /* extract parameters */
2146 bus_id
= qemu_opt_get_number(opts
, "bus", 0);
2147 unit_id
= qemu_opt_get_number(opts
, "unit", -1);
2148 index
= qemu_opt_get_number(opts
, "index", -1);
2150 cyls
= qemu_opt_get_number(opts
, "cyls", 0);
2151 heads
= qemu_opt_get_number(opts
, "heads", 0);
2152 secs
= qemu_opt_get_number(opts
, "secs", 0);
2154 snapshot
= qemu_opt_get_bool(opts
, "snapshot", 0);
2155 ro
= qemu_opt_get_bool(opts
, "readonly", 0);
2157 file
= qemu_opt_get(opts
, "file");
2158 serial
= qemu_opt_get(opts
, "serial");
2160 if ((buf
= qemu_opt_get(opts
, "if")) != NULL
) {
2161 pstrcpy(devname
, sizeof(devname
), buf
);
2162 if (!strcmp(buf
, "ide")) {
2164 max_devs
= MAX_IDE_DEVS
;
2165 } else if (!strcmp(buf
, "scsi")) {
2167 max_devs
= MAX_SCSI_DEVS
;
2168 } else if (!strcmp(buf
, "floppy")) {
2171 } else if (!strcmp(buf
, "pflash")) {
2174 } else if (!strcmp(buf
, "mtd")) {
2177 } else if (!strcmp(buf
, "sd")) {
2180 } else if (!strcmp(buf
, "virtio")) {
2183 } else if (!strcmp(buf
, "xen")) {
2186 } else if (!strcmp(buf
, "none")) {
2190 fprintf(stderr
, "qemu: unsupported bus type '%s'\n", buf
);
2195 if (cyls
|| heads
|| secs
) {
2196 if (cyls
< 1 || (type
== IF_IDE
&& cyls
> 16383)) {
2197 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", buf
);
2200 if (heads
< 1 || (type
== IF_IDE
&& heads
> 16)) {
2201 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", buf
);
2204 if (secs
< 1 || (type
== IF_IDE
&& secs
> 63)) {
2205 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", buf
);
2210 if ((buf
= qemu_opt_get(opts
, "trans")) != NULL
) {
2213 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2217 if (!strcmp(buf
, "none"))
2218 translation
= BIOS_ATA_TRANSLATION_NONE
;
2219 else if (!strcmp(buf
, "lba"))
2220 translation
= BIOS_ATA_TRANSLATION_LBA
;
2221 else if (!strcmp(buf
, "auto"))
2222 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2224 fprintf(stderr
, "qemu: '%s' invalid translation type\n", buf
);
2229 if ((buf
= qemu_opt_get(opts
, "media")) != NULL
) {
2230 if (!strcmp(buf
, "disk")) {
2232 } else if (!strcmp(buf
, "cdrom")) {
2233 if (cyls
|| secs
|| heads
) {
2235 "qemu: '%s' invalid physical CHS format\n", buf
);
2238 media
= MEDIA_CDROM
;
2240 fprintf(stderr
, "qemu: '%s' invalid media\n", buf
);
2245 if ((buf
= qemu_opt_get(opts
, "cache")) != NULL
) {
2246 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2248 else if (!strcmp(buf
, "writethrough"))
2250 else if (!strcmp(buf
, "writeback"))
2253 fprintf(stderr
, "qemu: invalid cache option\n");
2258 #ifdef CONFIG_LINUX_AIO
2259 if ((buf
= qemu_opt_get(opts
, "aio")) != NULL
) {
2260 if (!strcmp(buf
, "threads"))
2262 else if (!strcmp(buf
, "native"))
2265 fprintf(stderr
, "qemu: invalid aio option\n");
2271 if ((buf
= qemu_opt_get(opts
, "format")) != NULL
) {
2272 if (strcmp(buf
, "?") == 0) {
2273 fprintf(stderr
, "qemu: Supported formats:");
2274 bdrv_iterate_format(bdrv_format_print
, NULL
);
2275 fprintf(stderr
, "\n");
2278 drv
= bdrv_find_whitelisted_format(buf
);
2280 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2285 is_extboot
= qemu_opt_get_bool(opts
, "boot", 0);
2286 if (is_extboot
&& extboot_drive
) {
2287 fprintf(stderr
, "qemu: two bootable drives specified\n");
2291 on_write_error
= BLOCK_ERR_STOP_ENOSPC
;
2292 if ((buf
= qemu_opt_get(opts
, "werror")) != NULL
) {
2293 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2294 fprintf(stderr
, "werror is no supported by this format\n");
2298 on_write_error
= parse_block_error_action(buf
, 0);
2299 if (on_write_error
< 0) {
2304 on_read_error
= BLOCK_ERR_REPORT
;
2305 if ((buf
= qemu_opt_get(opts
, "rerror")) != NULL
) {
2306 if (type
!= IF_IDE
&& type
!= IF_VIRTIO
) {
2307 fprintf(stderr
, "rerror is no supported by this format\n");
2311 on_read_error
= parse_block_error_action(buf
, 1);
2312 if (on_read_error
< 0) {
2317 if ((devaddr
= qemu_opt_get(opts
, "addr")) != NULL
) {
2318 if (type
!= IF_VIRTIO
) {
2319 fprintf(stderr
, "addr is not supported\n");
2324 /* compute bus and unit according index */
2327 if (bus_id
!= 0 || unit_id
!= -1) {
2329 "qemu: index cannot be used with bus and unit\n");
2337 unit_id
= index
% max_devs
;
2338 bus_id
= index
/ max_devs
;
2342 /* if user doesn't specify a unit_id,
2343 * try to find the first free
2346 if (unit_id
== -1) {
2348 while (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2350 if (max_devs
&& unit_id
>= max_devs
) {
2351 unit_id
-= max_devs
;
2359 if (max_devs
&& unit_id
>= max_devs
) {
2360 fprintf(stderr
, "qemu: unit %d too big (max is %d)\n",
2361 unit_id
, max_devs
- 1);
2366 * ignore multiple definitions
2369 if (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2376 dinfo
= qemu_mallocz(sizeof(*dinfo
));
2377 if ((buf
= qemu_opts_id(opts
)) != NULL
) {
2378 dinfo
->id
= qemu_strdup(buf
);
2380 /* no id supplied -> create one */
2381 dinfo
->id
= qemu_mallocz(32);
2382 if (type
== IF_IDE
|| type
== IF_SCSI
)
2383 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2385 snprintf(dinfo
->id
, 32, "%s%i%s%i",
2386 devname
, bus_id
, mediastr
, unit_id
);
2388 snprintf(dinfo
->id
, 32, "%s%s%i",
2389 devname
, mediastr
, unit_id
);
2391 dinfo
->bdrv
= bdrv_new(dinfo
->id
);
2392 dinfo
->devaddr
= devaddr
;
2394 dinfo
->bus
= bus_id
;
2395 dinfo
->unit
= unit_id
;
2396 dinfo
->on_read_error
= on_read_error
;
2397 dinfo
->on_write_error
= on_write_error
;
2400 strncpy(dinfo
->serial
, serial
, sizeof(serial
));
2401 QTAILQ_INSERT_TAIL(&drives
, dinfo
, next
);
2403 extboot_drive
= dinfo
;
2414 bdrv_set_geometry_hint(dinfo
->bdrv
, cyls
, heads
, secs
);
2415 bdrv_set_translation_hint(dinfo
->bdrv
, translation
);
2419 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_CDROM
);
2424 /* FIXME: This isn't really a floppy, but it's a reasonable
2427 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_FLOPPY
);
2433 /* add virtio block device */
2434 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
2435 qemu_opt_set(opts
, "driver", "virtio-blk-pci");
2436 qemu_opt_set(opts
, "drive", dinfo
->id
);
2438 qemu_opt_set(opts
, "addr", devaddr
);
2449 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2450 cache
= 2; /* always use write-back with snapshot */
2452 if (cache
== 0) /* no caching */
2453 bdrv_flags
|= BDRV_O_NOCACHE
;
2454 else if (cache
== 2) /* write-back */
2455 bdrv_flags
|= BDRV_O_CACHE_WB
;
2458 bdrv_flags
|= BDRV_O_NATIVE_AIO
;
2460 bdrv_flags
&= ~BDRV_O_NATIVE_AIO
;
2464 if (type
== IF_IDE
) {
2465 fprintf(stderr
, "qemu: readonly flag not supported for drive with ide interface\n");
2468 (void)bdrv_set_read_only(dinfo
->bdrv
, 1);
2471 if (bdrv_open2(dinfo
->bdrv
, file
, bdrv_flags
, drv
) < 0) {
2472 fprintf(stderr
, "qemu: could not open disk image %s: %s\n",
2473 file
, strerror(errno
));
2477 if (bdrv_key_required(dinfo
->bdrv
))
2483 static int drive_init_func(QemuOpts
*opts
, void *opaque
)
2485 QEMUMachine
*machine
= opaque
;
2486 int fatal_error
= 0;
2488 if (drive_init(opts
, machine
, &fatal_error
) == NULL
) {
2495 static int drive_enable_snapshot(QemuOpts
*opts
, void *opaque
)
2497 if (NULL
== qemu_opt_get(opts
, "snapshot")) {
2498 qemu_opt_set(opts
, "snapshot", "on");
2503 void qemu_register_boot_set(QEMUBootSetHandler
*func
, void *opaque
)
2505 boot_set_handler
= func
;
2506 boot_set_opaque
= opaque
;
2509 int qemu_boot_set(const char *boot_devices
)
2511 if (!boot_set_handler
) {
2514 return boot_set_handler(boot_set_opaque
, boot_devices
);
2517 static int parse_bootdevices(char *devices
)
2519 /* We just do some generic consistency checks */
2523 for (p
= devices
; *p
!= '\0'; p
++) {
2524 /* Allowed boot devices are:
2525 * a-b: floppy disk drives
2526 * c-f: IDE disk drives
2527 * g-m: machine implementation dependant drives
2528 * n-p: network devices
2529 * It's up to each machine implementation to check if the given boot
2530 * devices match the actual hardware implementation and firmware
2533 if (*p
< 'a' || *p
> 'p') {
2534 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
2537 if (bitmap
& (1 << (*p
- 'a'))) {
2538 fprintf(stderr
, "Boot device '%c' was given twice\n", *p
);
2541 bitmap
|= 1 << (*p
- 'a');
2546 static void restore_boot_devices(void *opaque
)
2548 char *standard_boot_devices
= opaque
;
2550 qemu_boot_set(standard_boot_devices
);
2552 qemu_unregister_reset(restore_boot_devices
, standard_boot_devices
);
2553 qemu_free(standard_boot_devices
);
2556 static void numa_add(const char *optarg
)
2560 unsigned long long value
, endvalue
;
2563 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2564 if (!strcmp(option
, "node")) {
2565 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2566 nodenr
= nb_numa_nodes
;
2568 nodenr
= strtoull(option
, NULL
, 10);
2571 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2572 node_mem
[nodenr
] = 0;
2574 value
= strtoull(option
, &endptr
, 0);
2576 case 0: case 'M': case 'm':
2583 node_mem
[nodenr
] = value
;
2585 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2586 node_cpumask
[nodenr
] = 0;
2588 value
= strtoull(option
, &endptr
, 10);
2591 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2593 if (*endptr
== '-') {
2594 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2595 if (endvalue
>= 63) {
2598 "only 63 CPUs in NUMA mode supported.\n");
2600 value
= (1 << (endvalue
+ 1)) - (1 << value
);
2605 node_cpumask
[nodenr
] = value
;
2612 static void smp_parse(const char *optarg
)
2614 int smp
, sockets
= 0, threads
= 0, cores
= 0;
2618 smp
= strtoul(optarg
, &endptr
, 10);
2619 if (endptr
!= optarg
) {
2620 if (*endptr
== ',') {
2624 if (get_param_value(option
, 128, "sockets", endptr
) != 0)
2625 sockets
= strtoull(option
, NULL
, 10);
2626 if (get_param_value(option
, 128, "cores", endptr
) != 0)
2627 cores
= strtoull(option
, NULL
, 10);
2628 if (get_param_value(option
, 128, "threads", endptr
) != 0)
2629 threads
= strtoull(option
, NULL
, 10);
2630 if (get_param_value(option
, 128, "maxcpus", endptr
) != 0)
2631 max_cpus
= strtoull(option
, NULL
, 10);
2633 /* compute missing values, prefer sockets over cores over threads */
2634 if (smp
== 0 || sockets
== 0) {
2635 sockets
= sockets
> 0 ? sockets
: 1;
2636 cores
= cores
> 0 ? cores
: 1;
2637 threads
= threads
> 0 ? threads
: 1;
2639 smp
= cores
* threads
* sockets
;
2641 sockets
= smp
/ (cores
* threads
);
2645 threads
= threads
> 0 ? threads
: 1;
2646 cores
= smp
/ (sockets
* threads
);
2649 sockets
= smp
/ (cores
* threads
);
2651 threads
= smp
/ (cores
* sockets
);
2656 smp_cores
= cores
> 0 ? cores
: 1;
2657 smp_threads
= threads
> 0 ? threads
: 1;
2659 max_cpus
= smp_cpus
;
2662 /***********************************************************/
2665 static int usb_device_add(const char *devname
, int is_hotplug
)
2668 USBDevice
*dev
= NULL
;
2673 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2674 dev
= usbdevice_create(devname
);
2678 /* the other ones */
2679 if (strstart(devname
, "host:", &p
)) {
2680 dev
= usb_host_device_open(p
);
2681 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2682 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2683 bt_new_hci(qemu_find_bt_vlan(0)));
2694 static int usb_device_del(const char *devname
)
2699 if (strstart(devname
, "host:", &p
))
2700 return usb_host_device_close(p
);
2705 p
= strchr(devname
, '.');
2708 bus_num
= strtoul(devname
, NULL
, 0);
2709 addr
= strtoul(p
+ 1, NULL
, 0);
2711 return usb_device_delete_addr(bus_num
, addr
);
2714 static int usb_parse(const char *cmdline
)
2716 return usb_device_add(cmdline
, 0);
2719 void do_usb_add(Monitor
*mon
, const QDict
*qdict
)
2721 usb_device_add(qdict_get_str(qdict
, "devname"), 1);
2724 void do_usb_del(Monitor
*mon
, const QDict
*qdict
)
2726 usb_device_del(qdict_get_str(qdict
, "devname"));
2729 /***********************************************************/
2730 /* PCMCIA/Cardbus */
2732 static struct pcmcia_socket_entry_s
{
2733 PCMCIASocket
*socket
;
2734 struct pcmcia_socket_entry_s
*next
;
2735 } *pcmcia_sockets
= 0;
2737 void pcmcia_socket_register(PCMCIASocket
*socket
)
2739 struct pcmcia_socket_entry_s
*entry
;
2741 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2742 entry
->socket
= socket
;
2743 entry
->next
= pcmcia_sockets
;
2744 pcmcia_sockets
= entry
;
2747 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2749 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2751 ptr
= &pcmcia_sockets
;
2752 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2753 if (entry
->socket
== socket
) {
2759 void pcmcia_info(Monitor
*mon
)
2761 struct pcmcia_socket_entry_s
*iter
;
2763 if (!pcmcia_sockets
)
2764 monitor_printf(mon
, "No PCMCIA sockets\n");
2766 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2767 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2768 iter
->socket
->attached
? iter
->socket
->card_string
:
2772 /***********************************************************/
2773 /* register display */
2775 struct DisplayAllocator default_allocator
= {
2776 defaultallocator_create_displaysurface
,
2777 defaultallocator_resize_displaysurface
,
2778 defaultallocator_free_displaysurface
2781 void register_displaystate(DisplayState
*ds
)
2791 DisplayState
*get_displaystate(void)
2793 return display_state
;
2796 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
2798 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
2799 return ds
->allocator
;
2804 static void dumb_display_init(void)
2806 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
2807 ds
->allocator
= &default_allocator
;
2808 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
2809 register_displaystate(ds
);
2812 /***********************************************************/
2815 typedef struct IOHandlerRecord
{
2817 IOCanRWHandler
*fd_read_poll
;
2819 IOHandler
*fd_write
;
2822 /* temporary data */
2824 struct IOHandlerRecord
*next
;
2827 static IOHandlerRecord
*first_io_handler
;
2829 /* XXX: fd_read_poll should be suppressed, but an API change is
2830 necessary in the character devices to suppress fd_can_read(). */
2831 int qemu_set_fd_handler2(int fd
,
2832 IOCanRWHandler
*fd_read_poll
,
2834 IOHandler
*fd_write
,
2837 IOHandlerRecord
**pioh
, *ioh
;
2839 if (!fd_read
&& !fd_write
) {
2840 pioh
= &first_io_handler
;
2845 if (ioh
->fd
== fd
) {
2852 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
2856 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
2857 ioh
->next
= first_io_handler
;
2858 first_io_handler
= ioh
;
2861 ioh
->fd_read_poll
= fd_read_poll
;
2862 ioh
->fd_read
= fd_read
;
2863 ioh
->fd_write
= fd_write
;
2864 ioh
->opaque
= opaque
;
2867 qemu_notify_event();
2871 int qemu_set_fd_handler(int fd
,
2873 IOHandler
*fd_write
,
2876 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
2880 /***********************************************************/
2881 /* Polling handling */
2883 typedef struct PollingEntry
{
2886 struct PollingEntry
*next
;
2889 static PollingEntry
*first_polling_entry
;
2891 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
2893 PollingEntry
**ppe
, *pe
;
2894 pe
= qemu_mallocz(sizeof(PollingEntry
));
2896 pe
->opaque
= opaque
;
2897 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
2902 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
2904 PollingEntry
**ppe
, *pe
;
2905 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
2907 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
2915 /***********************************************************/
2916 /* Wait objects support */
2917 typedef struct WaitObjects
{
2919 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
2920 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
2921 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
2924 static WaitObjects wait_objects
= {0};
2926 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2928 WaitObjects
*w
= &wait_objects
;
2930 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
2932 w
->events
[w
->num
] = handle
;
2933 w
->func
[w
->num
] = func
;
2934 w
->opaque
[w
->num
] = opaque
;
2939 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2942 WaitObjects
*w
= &wait_objects
;
2945 for (i
= 0; i
< w
->num
; i
++) {
2946 if (w
->events
[i
] == handle
)
2949 w
->events
[i
] = w
->events
[i
+ 1];
2950 w
->func
[i
] = w
->func
[i
+ 1];
2951 w
->opaque
[i
] = w
->opaque
[i
+ 1];
2959 /***********************************************************/
2960 /* ram save/restore */
2962 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2963 #define RAM_SAVE_FLAG_COMPRESS 0x02
2964 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2965 #define RAM_SAVE_FLAG_PAGE 0x08
2966 #define RAM_SAVE_FLAG_EOS 0x10
2968 static int is_dup_page(uint8_t *page
, uint8_t ch
)
2970 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
2971 uint32_t *array
= (uint32_t *)page
;
2974 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
2975 if (array
[i
] != val
)
2982 static int ram_save_block(QEMUFile
*f
)
2984 static ram_addr_t current_addr
= 0;
2985 ram_addr_t saved_addr
= current_addr
;
2986 ram_addr_t addr
= 0;
2989 while (addr
< last_ram_offset
) {
2990 if (kvm_enabled() && current_addr
== 0) {
2992 r
= kvm_update_dirty_pages_log();
2994 fprintf(stderr
, "%s: update dirty pages log failed %d\n", __FUNCTION__
, r
);
2995 qemu_file_set_error(f
);
2999 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
3002 cpu_physical_memory_reset_dirty(current_addr
,
3003 current_addr
+ TARGET_PAGE_SIZE
,
3004 MIGRATION_DIRTY_FLAG
);
3006 p
= qemu_get_ram_ptr(current_addr
);
3008 if (is_dup_page(p
, *p
)) {
3009 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
3010 qemu_put_byte(f
, *p
);
3012 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
3013 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
3019 addr
+= TARGET_PAGE_SIZE
;
3020 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
3026 static uint64_t bytes_transferred
;
3028 static ram_addr_t
ram_save_remaining(void)
3031 ram_addr_t count
= 0;
3033 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3034 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3041 uint64_t ram_bytes_remaining(void)
3043 return ram_save_remaining() * TARGET_PAGE_SIZE
;
3046 uint64_t ram_bytes_transferred(void)
3048 return bytes_transferred
;
3051 uint64_t ram_bytes_total(void)
3053 return last_ram_offset
;
3056 static int ram_save_live(Monitor
*mon
, QEMUFile
*f
, int stage
, void *opaque
)
3059 uint64_t bytes_transferred_last
;
3061 uint64_t expected_time
= 0;
3064 cpu_physical_memory_set_dirty_tracking(0);
3068 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX
) != 0) {
3069 qemu_file_set_error(f
);
3074 bytes_transferred
= 0;
3076 /* Make sure all dirty bits are set */
3077 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3078 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3079 cpu_physical_memory_set_dirty(addr
);
3082 /* Enable dirty memory tracking */
3083 cpu_physical_memory_set_dirty_tracking(1);
3085 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
3088 bytes_transferred_last
= bytes_transferred
;
3089 bwidth
= get_clock();
3091 while (!qemu_file_rate_limit(f
)) {
3094 ret
= ram_save_block(f
);
3095 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
3096 if (ret
== 0) /* no more blocks */
3100 bwidth
= get_clock() - bwidth
;
3101 bwidth
= (bytes_transferred
- bytes_transferred_last
) / bwidth
;
3103 /* if we haven't transferred anything this round, force expected_time to a
3104 * a very high value, but without crashing */
3108 /* try transferring iterative blocks of memory */
3110 /* flush all remaining blocks regardless of rate limiting */
3111 while (ram_save_block(f
) != 0) {
3112 bytes_transferred
+= TARGET_PAGE_SIZE
;
3114 cpu_physical_memory_set_dirty_tracking(0);
3117 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3119 expected_time
= ram_save_remaining() * TARGET_PAGE_SIZE
/ bwidth
;
3121 return (stage
== 2) && (expected_time
<= migrate_max_downtime());
3124 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
3129 if (version_id
!= 3)
3133 addr
= qemu_get_be64(f
);
3135 flags
= addr
& ~TARGET_PAGE_MASK
;
3136 addr
&= TARGET_PAGE_MASK
;
3138 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
3139 if (addr
!= last_ram_offset
)
3143 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
3144 uint8_t ch
= qemu_get_byte(f
);
3145 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
3148 (!kvm_enabled() || kvm_has_sync_mmu())) {
3149 madvise(qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
, MADV_DONTNEED
);
3152 } else if (flags
& RAM_SAVE_FLAG_PAGE
) {
3153 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
3155 if (qemu_file_has_error(f
)) {
3158 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
3163 void qemu_service_io(void)
3165 qemu_notify_event();
3168 /***********************************************************/
3169 /* machine registration */
3171 static QEMUMachine
*first_machine
= NULL
;
3172 QEMUMachine
*current_machine
= NULL
;
3174 int qemu_register_machine(QEMUMachine
*m
)
3177 pm
= &first_machine
;
3185 static QEMUMachine
*find_machine(const char *name
)
3189 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3190 if (!strcmp(m
->name
, name
))
3192 if (m
->alias
&& !strcmp(m
->alias
, name
))
3198 static QEMUMachine
*find_default_machine(void)
3202 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3203 if (m
->is_default
) {
3210 /***********************************************************/
3211 /* main execution loop */
3213 static void gui_update(void *opaque
)
3215 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3216 DisplayState
*ds
= opaque
;
3217 DisplayChangeListener
*dcl
= ds
->listeners
;
3221 while (dcl
!= NULL
) {
3222 if (dcl
->gui_timer_interval
&&
3223 dcl
->gui_timer_interval
< interval
)
3224 interval
= dcl
->gui_timer_interval
;
3227 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3230 static void nographic_update(void *opaque
)
3232 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3234 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3237 struct vm_change_state_entry
{
3238 VMChangeStateHandler
*cb
;
3240 QLIST_ENTRY (vm_change_state_entry
) entries
;
3243 static QLIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3245 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3248 VMChangeStateEntry
*e
;
3250 e
= qemu_mallocz(sizeof (*e
));
3254 QLIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3258 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3260 QLIST_REMOVE (e
, entries
);
3264 static void vm_state_notify(int running
, int reason
)
3266 VMChangeStateEntry
*e
;
3268 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3269 e
->cb(e
->opaque
, running
, reason
);
3273 static void resume_all_vcpus(void);
3274 static void pause_all_vcpus(void);
3281 vm_state_notify(1, 0);
3282 qemu_rearm_alarm_timer(alarm_timer
);
3287 /* reset/shutdown handler */
3289 typedef struct QEMUResetEntry
{
3290 QTAILQ_ENTRY(QEMUResetEntry
) entry
;
3291 QEMUResetHandler
*func
;
3295 static QTAILQ_HEAD(reset_handlers
, QEMUResetEntry
) reset_handlers
=
3296 QTAILQ_HEAD_INITIALIZER(reset_handlers
);
3297 static int reset_requested
;
3298 static int shutdown_requested
;
3299 static int powerdown_requested
;
3300 static int debug_requested
;
3301 static int vmstop_requested
;
3303 int qemu_no_shutdown(void)
3305 int r
= no_shutdown
;
3310 int qemu_shutdown_requested(void)
3312 int r
= shutdown_requested
;
3313 shutdown_requested
= 0;
3317 int qemu_reset_requested(void)
3319 int r
= reset_requested
;
3320 reset_requested
= 0;
3324 int qemu_powerdown_requested(void)
3326 int r
= powerdown_requested
;
3327 powerdown_requested
= 0;
3331 static int qemu_debug_requested(void)
3333 int r
= debug_requested
;
3334 debug_requested
= 0;
3338 static int qemu_vmstop_requested(void)
3340 int r
= vmstop_requested
;
3341 vmstop_requested
= 0;
3345 static void do_vm_stop(int reason
)
3348 cpu_disable_ticks();
3351 vm_state_notify(0, reason
);
3355 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3357 QEMUResetEntry
*re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3360 re
->opaque
= opaque
;
3361 QTAILQ_INSERT_TAIL(&reset_handlers
, re
, entry
);
3364 void qemu_unregister_reset(QEMUResetHandler
*func
, void *opaque
)
3368 QTAILQ_FOREACH(re
, &reset_handlers
, entry
) {
3369 if (re
->func
== func
&& re
->opaque
== opaque
) {
3370 QTAILQ_REMOVE(&reset_handlers
, re
, entry
);
3377 void qemu_system_reset(void)
3379 QEMUResetEntry
*re
, *nre
;
3381 /* reset all devices */
3382 QTAILQ_FOREACH_SAFE(re
, &reset_handlers
, entry
, nre
) {
3383 re
->func(re
->opaque
);
3387 void qemu_system_reset_request(void)
3390 shutdown_requested
= 1;
3392 reset_requested
= 1;
3394 if (cpu_single_env
) {
3395 cpu_single_env
->stopped
= 1;
3397 qemu_notify_event();
3400 void qemu_system_shutdown_request(void)
3402 shutdown_requested
= 1;
3403 qemu_notify_event();
3406 void qemu_system_powerdown_request(void)
3408 powerdown_requested
= 1;
3409 qemu_notify_event();
3412 #ifdef CONFIG_IOTHREAD
3413 static void qemu_system_vmstop_request(int reason
)
3415 vmstop_requested
= reason
;
3416 qemu_notify_event();
3421 static int io_thread_fd
= -1;
3423 static void qemu_event_increment(void)
3425 static const char byte
= 0;
3427 if (io_thread_fd
== -1)
3430 write(io_thread_fd
, &byte
, sizeof(byte
));
3433 static void qemu_event_read(void *opaque
)
3435 int fd
= (unsigned long)opaque
;
3438 /* Drain the notify pipe */
3441 len
= read(fd
, buffer
, sizeof(buffer
));
3442 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
3445 static int qemu_event_init(void)
3450 err
= qemu_pipe(fds
);
3454 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3458 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3462 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3463 (void *)(unsigned long)fds
[0]);
3465 io_thread_fd
= fds
[1];
3474 HANDLE qemu_event_handle
;
3476 static void dummy_event_handler(void *opaque
)
3480 static int qemu_event_init(void)
3482 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3483 if (!qemu_event_handle
) {
3484 fprintf(stderr
, "Failed CreateEvent: %ld\n", GetLastError());
3487 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3491 static void qemu_event_increment(void)
3493 if (!SetEvent(qemu_event_handle
)) {
3494 fprintf(stderr
, "qemu_event_increment: SetEvent failed: %ld\n",
3501 static int cpu_can_run(CPUState
*env
)
3510 #ifndef CONFIG_IOTHREAD
3511 static int qemu_init_main_loop(void)
3513 return qemu_event_init();
3516 void qemu_init_vcpu(void *_env
)
3518 CPUState
*env
= _env
;
3522 env
->nr_cores
= smp_cores
;
3523 env
->nr_threads
= smp_threads
;
3527 int qemu_cpu_self(void *env
)
3532 static void resume_all_vcpus(void)
3536 static void pause_all_vcpus(void)
3540 void qemu_cpu_kick(void *env
)
3545 void qemu_notify_event(void)
3547 CPUState
*env
= cpu_single_env
;
3549 if (kvm_enabled()) {
3550 qemu_kvm_notify_work();
3558 #if defined(KVM_UPSTREAM) || !defined(CONFIG_KVM)
3559 void qemu_mutex_lock_iothread(void) {}
3560 void qemu_mutex_unlock_iothread(void) {}
3563 void vm_stop(int reason
)
3568 #else /* CONFIG_IOTHREAD */
3570 #include "qemu-thread.h"
3572 QemuMutex qemu_global_mutex
;
3573 static QemuMutex qemu_fair_mutex
;
3575 static QemuThread io_thread
;
3577 static QemuThread
*tcg_cpu_thread
;
3578 static QemuCond
*tcg_halt_cond
;
3580 static int qemu_system_ready
;
3582 static QemuCond qemu_cpu_cond
;
3584 static QemuCond qemu_system_cond
;
3585 static QemuCond qemu_pause_cond
;
3587 static void block_io_signals(void);
3588 static void unblock_io_signals(void);
3589 static int tcg_has_work(void);
3591 static int qemu_init_main_loop(void)
3595 ret
= qemu_event_init();
3599 qemu_cond_init(&qemu_pause_cond
);
3600 qemu_mutex_init(&qemu_fair_mutex
);
3601 qemu_mutex_init(&qemu_global_mutex
);
3602 qemu_mutex_lock(&qemu_global_mutex
);
3604 unblock_io_signals();
3605 qemu_thread_self(&io_thread
);
3610 static void qemu_wait_io_event(CPUState
*env
)
3612 while (!tcg_has_work())
3613 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3615 qemu_mutex_unlock(&qemu_global_mutex
);
3618 * Users of qemu_global_mutex can be starved, having no chance
3619 * to acquire it since this path will get to it first.
3620 * So use another lock to provide fairness.
3622 qemu_mutex_lock(&qemu_fair_mutex
);
3623 qemu_mutex_unlock(&qemu_fair_mutex
);
3625 qemu_mutex_lock(&qemu_global_mutex
);
3629 qemu_cond_signal(&qemu_pause_cond
);
3633 static int qemu_cpu_exec(CPUState
*env
);
3635 static void *kvm_cpu_thread_fn(void *arg
)
3637 CPUState
*env
= arg
;
3640 qemu_thread_self(env
->thread
);
3644 /* signal CPU creation */
3645 qemu_mutex_lock(&qemu_global_mutex
);
3647 qemu_cond_signal(&qemu_cpu_cond
);
3649 /* and wait for machine initialization */
3650 while (!qemu_system_ready
)
3651 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3654 if (cpu_can_run(env
))
3656 qemu_wait_io_event(env
);
3662 static void tcg_cpu_exec(void);
3664 static void *tcg_cpu_thread_fn(void *arg
)
3666 CPUState
*env
= arg
;
3669 qemu_thread_self(env
->thread
);
3671 /* signal CPU creation */
3672 qemu_mutex_lock(&qemu_global_mutex
);
3673 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
3675 qemu_cond_signal(&qemu_cpu_cond
);
3677 /* and wait for machine initialization */
3678 while (!qemu_system_ready
)
3679 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3683 qemu_wait_io_event(cur_cpu
);
3689 void qemu_cpu_kick(void *_env
)
3691 CPUState
*env
= _env
;
3692 qemu_cond_broadcast(env
->halt_cond
);
3694 qemu_thread_signal(env
->thread
, SIGUSR1
);
3697 int qemu_cpu_self(void *_env
)
3699 CPUState
*env
= _env
;
3702 qemu_thread_self(&this);
3704 return qemu_thread_equal(&this, env
->thread
);
3707 static void cpu_signal(int sig
)
3710 cpu_exit(cpu_single_env
);
3713 static void block_io_signals(void)
3716 struct sigaction sigact
;
3719 sigaddset(&set
, SIGUSR2
);
3720 sigaddset(&set
, SIGIO
);
3721 sigaddset(&set
, SIGALRM
);
3722 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3725 sigaddset(&set
, SIGUSR1
);
3726 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3728 memset(&sigact
, 0, sizeof(sigact
));
3729 sigact
.sa_handler
= cpu_signal
;
3730 sigaction(SIGUSR1
, &sigact
, NULL
);
3733 static void unblock_io_signals(void)
3738 sigaddset(&set
, SIGUSR2
);
3739 sigaddset(&set
, SIGIO
);
3740 sigaddset(&set
, SIGALRM
);
3741 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3744 sigaddset(&set
, SIGUSR1
);
3745 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3748 static void qemu_signal_lock(unsigned int msecs
)
3750 qemu_mutex_lock(&qemu_fair_mutex
);
3752 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
3753 qemu_thread_signal(tcg_cpu_thread
, SIGUSR1
);
3754 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
3757 qemu_mutex_unlock(&qemu_fair_mutex
);
3760 void qemu_mutex_lock_iothread(void)
3762 if (kvm_enabled()) {
3763 qemu_mutex_lock(&qemu_fair_mutex
);
3764 qemu_mutex_lock(&qemu_global_mutex
);
3765 qemu_mutex_unlock(&qemu_fair_mutex
);
3767 qemu_signal_lock(100);
3770 void qemu_mutex_unlock_iothread(void)
3772 qemu_mutex_unlock(&qemu_global_mutex
);
3775 static int all_vcpus_paused(void)
3777 CPUState
*penv
= first_cpu
;
3782 penv
= (CPUState
*)penv
->next_cpu
;
3788 static void pause_all_vcpus(void)
3790 CPUState
*penv
= first_cpu
;
3794 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3795 qemu_cpu_kick(penv
);
3796 penv
= (CPUState
*)penv
->next_cpu
;
3799 while (!all_vcpus_paused()) {
3800 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
3803 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3804 penv
= (CPUState
*)penv
->next_cpu
;
3809 static void resume_all_vcpus(void)
3811 CPUState
*penv
= first_cpu
;
3816 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3817 qemu_cpu_kick(penv
);
3818 penv
= (CPUState
*)penv
->next_cpu
;
3822 static void tcg_init_vcpu(void *_env
)
3824 CPUState
*env
= _env
;
3825 /* share a single thread for all cpus with TCG */
3826 if (!tcg_cpu_thread
) {
3827 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3828 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3829 qemu_cond_init(env
->halt_cond
);
3830 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
3831 while (env
->created
== 0)
3832 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3833 tcg_cpu_thread
= env
->thread
;
3834 tcg_halt_cond
= env
->halt_cond
;
3836 env
->thread
= tcg_cpu_thread
;
3837 env
->halt_cond
= tcg_halt_cond
;
3841 static void kvm_start_vcpu(CPUState
*env
)
3843 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3844 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3845 qemu_cond_init(env
->halt_cond
);
3846 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
3847 while (env
->created
== 0)
3848 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3851 void qemu_init_vcpu(void *_env
)
3853 CPUState
*env
= _env
;
3856 kvm_start_vcpu(env
);
3859 env
->nr_cores
= smp_cores
;
3860 env
->nr_threads
= smp_threads
;
3863 void qemu_notify_event(void)
3865 qemu_event_increment();
3868 void vm_stop(int reason
)
3871 qemu_thread_self(&me
);
3873 if (!qemu_thread_equal(&me
, &io_thread
)) {
3874 qemu_system_vmstop_request(reason
);
3876 * FIXME: should not return to device code in case
3877 * vm_stop() has been requested.
3879 if (cpu_single_env
) {
3880 cpu_exit(cpu_single_env
);
3881 cpu_single_env
->stop
= 1;
3892 static void host_main_loop_wait(int *timeout
)
3898 /* XXX: need to suppress polling by better using win32 events */
3900 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
3901 ret
|= pe
->func(pe
->opaque
);
3905 WaitObjects
*w
= &wait_objects
;
3907 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
3908 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
3909 if (w
->func
[ret
- WAIT_OBJECT_0
])
3910 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
3912 /* Check for additional signaled events */
3913 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
3915 /* Check if event is signaled */
3916 ret2
= WaitForSingleObject(w
->events
[i
], 0);
3917 if(ret2
== WAIT_OBJECT_0
) {
3919 w
->func
[i
](w
->opaque
[i
]);
3920 } else if (ret2
== WAIT_TIMEOUT
) {
3922 err
= GetLastError();
3923 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
3926 } else if (ret
== WAIT_TIMEOUT
) {
3928 err
= GetLastError();
3929 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
3936 static void host_main_loop_wait(int *timeout
)
3941 void main_loop_wait(int timeout
)
3943 IOHandlerRecord
*ioh
;
3944 fd_set rfds
, wfds
, xfds
;
3948 qemu_bh_update_timeout(&timeout
);
3950 host_main_loop_wait(&timeout
);
3952 /* poll any events */
3953 /* XXX: separate device handlers from system ones */
3958 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3962 (!ioh
->fd_read_poll
||
3963 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
3964 FD_SET(ioh
->fd
, &rfds
);
3968 if (ioh
->fd_write
) {
3969 FD_SET(ioh
->fd
, &wfds
);
3975 tv
.tv_sec
= timeout
/ 1000;
3976 tv
.tv_usec
= (timeout
% 1000) * 1000;
3978 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
3980 qemu_mutex_unlock_iothread();
3981 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
3982 qemu_mutex_lock_iothread();
3984 IOHandlerRecord
**pioh
;
3986 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3987 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
3988 ioh
->fd_read(ioh
->opaque
);
3989 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
3990 FD_CLR(ioh
->fd
, &rfds
);
3992 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
3993 ioh
->fd_write(ioh
->opaque
);
3997 /* remove deleted IO handlers */
3998 pioh
= &first_io_handler
;
4009 slirp_select_poll(&rfds
, &wfds
, &xfds
, (ret
< 0));
4011 /* rearm timer, if not periodic */
4012 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
4013 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
4014 qemu_rearm_alarm_timer(alarm_timer
);
4017 /* vm time timers */
4019 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
4020 qemu_run_timers(&active_timers
[QEMU_CLOCK_VIRTUAL
],
4021 qemu_get_clock(vm_clock
));
4024 /* real time timers */
4025 qemu_run_timers(&active_timers
[QEMU_CLOCK_REALTIME
],
4026 qemu_get_clock(rt_clock
));
4028 qemu_run_timers(&active_timers
[QEMU_CLOCK_HOST
],
4029 qemu_get_clock(host_clock
));
4031 /* Check bottom-halves last in case any of the earlier events triggered
4037 static int qemu_cpu_exec(CPUState
*env
)
4040 #ifdef CONFIG_PROFILER
4044 #ifdef CONFIG_PROFILER
4045 ti
= profile_getclock();
4050 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
4051 env
->icount_decr
.u16
.low
= 0;
4052 env
->icount_extra
= 0;
4053 count
= qemu_next_deadline();
4054 count
= (count
+ (1 << icount_time_shift
) - 1)
4055 >> icount_time_shift
;
4056 qemu_icount
+= count
;
4057 decr
= (count
> 0xffff) ? 0xffff : count
;
4059 env
->icount_decr
.u16
.low
= decr
;
4060 env
->icount_extra
= count
;
4062 ret
= cpu_exec(env
);
4063 #ifdef CONFIG_PROFILER
4064 qemu_time
+= profile_getclock() - ti
;
4067 /* Fold pending instructions back into the
4068 instruction counter, and clear the interrupt flag. */
4069 qemu_icount
-= (env
->icount_decr
.u16
.low
4070 + env
->icount_extra
);
4071 env
->icount_decr
.u32
= 0;
4072 env
->icount_extra
= 0;
4077 static void tcg_cpu_exec(void)
4081 if (next_cpu
== NULL
)
4082 next_cpu
= first_cpu
;
4083 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
4084 CPUState
*env
= cur_cpu
= next_cpu
;
4088 if (timer_alarm_pending
) {
4089 timer_alarm_pending
= 0;
4092 if (cpu_can_run(env
))
4093 ret
= qemu_cpu_exec(env
);
4094 if (ret
== EXCP_DEBUG
) {
4095 gdb_set_stop_cpu(env
);
4096 debug_requested
= 1;
4102 static int cpu_has_work(CPUState
*env
)
4110 if (qemu_cpu_has_work(env
))
4115 static int tcg_has_work(void)
4119 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4120 if (cpu_has_work(env
))
4125 static int qemu_calculate_timeout(void)
4127 #ifndef CONFIG_IOTHREAD
4132 else if (tcg_has_work())
4134 else if (!use_icount
)
4137 /* XXX: use timeout computed from timers */
4140 /* Advance virtual time to the next event. */
4141 if (use_icount
== 1) {
4142 /* When not using an adaptive execution frequency
4143 we tend to get badly out of sync with real time,
4144 so just delay for a reasonable amount of time. */
4147 delta
= cpu_get_icount() - cpu_get_clock();
4150 /* If virtual time is ahead of real time then just
4152 timeout
= (delta
/ 1000000) + 1;
4154 /* Wait for either IO to occur or the next
4156 add
= qemu_next_deadline();
4157 /* We advance the timer before checking for IO.
4158 Limit the amount we advance so that early IO
4159 activity won't get the guest too far ahead. */
4163 add
= (add
+ (1 << icount_time_shift
) - 1)
4164 >> icount_time_shift
;
4166 timeout
= delta
/ 1000000;
4173 #else /* CONFIG_IOTHREAD */
4178 static int vm_can_run(void)
4180 if (powerdown_requested
)
4182 if (reset_requested
)
4184 if (shutdown_requested
)
4186 if (debug_requested
)
4191 qemu_irq qemu_system_powerdown
;
4193 static void main_loop(void)
4197 if (kvm_enabled()) {
4199 cpu_disable_ticks();
4203 #ifdef CONFIG_IOTHREAD
4204 qemu_system_ready
= 1;
4205 qemu_cond_broadcast(&qemu_system_cond
);
4210 #ifdef CONFIG_PROFILER
4213 #ifndef CONFIG_IOTHREAD
4216 #ifdef CONFIG_PROFILER
4217 ti
= profile_getclock();
4219 main_loop_wait(qemu_calculate_timeout());
4220 #ifdef CONFIG_PROFILER
4221 dev_time
+= profile_getclock() - ti
;
4223 } while (vm_can_run());
4225 if (qemu_debug_requested()) {
4226 monitor_protocol_event(QEVENT_DEBUG
, NULL
);
4227 vm_stop(EXCP_DEBUG
);
4229 if (qemu_shutdown_requested()) {
4230 monitor_protocol_event(QEVENT_SHUTDOWN
, NULL
);
4237 if (qemu_reset_requested()) {
4238 monitor_protocol_event(QEVENT_RESET
, NULL
);
4240 qemu_system_reset();
4243 if (qemu_powerdown_requested()) {
4244 monitor_protocol_event(QEVENT_POWERDOWN
, NULL
);
4245 qemu_irq_raise(qemu_system_powerdown
);
4247 if ((r
= qemu_vmstop_requested())) {
4248 monitor_protocol_event(QEVENT_STOP
, NULL
);
4255 static void version(void)
4257 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4260 static void help(int exitcode
)
4263 printf("usage: %s [options] [disk_image]\n"
4265 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4267 #define DEF(option, opt_arg, opt_enum, opt_help) \
4269 #define DEFHEADING(text) stringify(text) "\n"
4270 #include "qemu-options.h"
4275 "During emulation, the following keys are useful:\n"
4276 "ctrl-alt-f toggle full screen\n"
4277 "ctrl-alt-n switch to virtual console 'n'\n"
4278 "ctrl-alt toggle mouse and keyboard grab\n"
4280 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4285 DEFAULT_NETWORK_SCRIPT
,
4286 DEFAULT_NETWORK_DOWN_SCRIPT
,
4288 DEFAULT_GDBSTUB_PORT
,
4293 #define HAS_ARG 0x0001
4296 #define DEF(option, opt_arg, opt_enum, opt_help) \
4298 #define DEFHEADING(text)
4299 #include "qemu-options.h"
4305 typedef struct QEMUOption
{
4311 static const QEMUOption qemu_options
[] = {
4312 { "h", 0, QEMU_OPTION_h
},
4313 #define DEF(option, opt_arg, opt_enum, opt_help) \
4314 { option, opt_arg, opt_enum },
4315 #define DEFHEADING(text)
4316 #include "qemu-options.h"
4324 struct soundhw soundhw
[] = {
4325 #ifdef HAS_AUDIO_CHOICE
4326 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4332 { .init_isa
= pcspk_audio_init
}
4339 "Creative Sound Blaster 16",
4342 { .init_isa
= SB16_init
}
4346 #ifdef CONFIG_CS4231A
4352 { .init_isa
= cs4231a_init
}
4360 "Yamaha YMF262 (OPL3)",
4362 "Yamaha YM3812 (OPL2)",
4366 { .init_isa
= Adlib_init
}
4373 "Gravis Ultrasound GF1",
4376 { .init_isa
= GUS_init
}
4383 "Intel 82801AA AC97 Audio",
4386 { .init_pci
= ac97_init
}
4390 #ifdef CONFIG_ES1370
4393 "ENSONIQ AudioPCI ES1370",
4396 { .init_pci
= es1370_init
}
4400 #endif /* HAS_AUDIO_CHOICE */
4402 { NULL
, NULL
, 0, 0, { NULL
} }
4405 static void select_soundhw (const char *optarg
)
4409 if (*optarg
== '?') {
4412 printf ("Valid sound card names (comma separated):\n");
4413 for (c
= soundhw
; c
->name
; ++c
) {
4414 printf ("%-11s %s\n", c
->name
, c
->descr
);
4416 printf ("\n-soundhw all will enable all of the above\n");
4417 exit (*optarg
!= '?');
4425 if (!strcmp (optarg
, "all")) {
4426 for (c
= soundhw
; c
->name
; ++c
) {
4434 e
= strchr (p
, ',');
4435 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4437 for (c
= soundhw
; c
->name
; ++c
) {
4438 if (!strncmp (c
->name
, p
, l
) && !c
->name
[l
]) {
4447 "Unknown sound card name (too big to show)\n");
4450 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4455 p
+= l
+ (e
!= NULL
);
4459 goto show_valid_cards
;
4464 static void select_vgahw (const char *p
)
4469 vga_interface_type
= VGA_NONE
;
4470 if (strstart(p
, "std", &opts
)) {
4471 vga_interface_type
= VGA_STD
;
4472 } else if (strstart(p
, "cirrus", &opts
)) {
4473 vga_interface_type
= VGA_CIRRUS
;
4474 } else if (strstart(p
, "vmware", &opts
)) {
4475 vga_interface_type
= VGA_VMWARE
;
4476 } else if (strstart(p
, "xenfb", &opts
)) {
4477 vga_interface_type
= VGA_XENFB
;
4478 } else if (!strstart(p
, "none", &opts
)) {
4480 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4484 const char *nextopt
;
4486 if (strstart(opts
, ",retrace=", &nextopt
)) {
4488 if (strstart(opts
, "dumb", &nextopt
))
4489 vga_retrace_method
= VGA_RETRACE_DUMB
;
4490 else if (strstart(opts
, "precise", &nextopt
))
4491 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4492 else goto invalid_vga
;
4493 } else goto invalid_vga
;
4499 static int balloon_parse(const char *arg
)
4503 if (strcmp(arg
, "none") == 0) {
4507 if (!strncmp(arg
, "virtio", 6)) {
4508 if (arg
[6] == ',') {
4509 /* have params -> parse them */
4510 opts
= qemu_opts_parse(&qemu_device_opts
, arg
+7, NULL
);
4514 /* create empty opts */
4515 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4517 qemu_opt_set(opts
, "driver", "virtio-balloon-pci");
4526 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4528 exit(STATUS_CONTROL_C_EXIT
);
4533 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4537 if(strlen(str
) != 36)
4540 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4541 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4542 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4548 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4556 static void termsig_handler(int signal
)
4558 qemu_system_shutdown_request();
4561 static void sigchld_handler(int signal
)
4563 waitpid(-1, NULL
, WNOHANG
);
4566 static void sighandler_setup(void)
4568 struct sigaction act
;
4570 memset(&act
, 0, sizeof(act
));
4571 act
.sa_handler
= termsig_handler
;
4572 sigaction(SIGINT
, &act
, NULL
);
4573 sigaction(SIGHUP
, &act
, NULL
);
4574 sigaction(SIGTERM
, &act
, NULL
);
4576 act
.sa_handler
= sigchld_handler
;
4577 act
.sa_flags
= SA_NOCLDSTOP
;
4578 sigaction(SIGCHLD
, &act
, NULL
);
4584 /* Look for support files in the same directory as the executable. */
4585 static char *find_datadir(const char *argv0
)
4591 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
4598 while (p
!= buf
&& *p
!= '\\')
4601 if (access(buf
, R_OK
) == 0) {
4602 return qemu_strdup(buf
);
4608 /* Find a likely location for support files using the location of the binary.
4609 For installed binaries this will be "$bindir/../share/qemu". When
4610 running from the build tree this will be "$bindir/../pc-bios". */
4611 #define SHARE_SUFFIX "/share/qemu"
4612 #define BUILD_SUFFIX "/pc-bios"
4613 static char *find_datadir(const char *argv0
)
4621 #if defined(__linux__)
4624 len
= readlink("/proc/self/exe", buf
, sizeof(buf
) - 1);
4630 #elif defined(__FreeBSD__)
4633 len
= readlink("/proc/curproc/file", buf
, sizeof(buf
) - 1);
4640 /* If we don't have any way of figuring out the actual executable
4641 location then try argv[0]. */
4643 p
= realpath(argv0
, buf
);
4651 max_len
= strlen(dir
) +
4652 MAX(strlen(SHARE_SUFFIX
), strlen(BUILD_SUFFIX
)) + 1;
4653 res
= qemu_mallocz(max_len
);
4654 snprintf(res
, max_len
, "%s%s", dir
, SHARE_SUFFIX
);
4655 if (access(res
, R_OK
)) {
4656 snprintf(res
, max_len
, "%s%s", dir
, BUILD_SUFFIX
);
4657 if (access(res
, R_OK
)) {
4669 char *qemu_find_file(int type
, const char *name
)
4675 /* If name contains path separators then try it as a straight path. */
4676 if ((strchr(name
, '/') || strchr(name
, '\\'))
4677 && access(name
, R_OK
) == 0) {
4678 return qemu_strdup(name
);
4681 case QEMU_FILE_TYPE_BIOS
:
4684 case QEMU_FILE_TYPE_KEYMAP
:
4685 subdir
= "keymaps/";
4690 len
= strlen(data_dir
) + strlen(name
) + strlen(subdir
) + 2;
4691 buf
= qemu_mallocz(len
);
4692 snprintf(buf
, len
, "%s/%s%s", data_dir
, subdir
, name
);
4693 if (access(buf
, R_OK
)) {
4700 static int device_init_func(QemuOpts
*opts
, void *opaque
)
4704 dev
= qdev_device_add(opts
);
4710 static int chardev_init_func(QemuOpts
*opts
, void *opaque
)
4712 CharDriverState
*chr
;
4714 chr
= qemu_chr_open_opts(opts
, NULL
);
4720 static int mon_init_func(QemuOpts
*opts
, void *opaque
)
4722 CharDriverState
*chr
;
4723 const char *chardev
;
4727 mode
= qemu_opt_get(opts
, "mode");
4731 if (strcmp(mode
, "readline") == 0) {
4732 flags
= MONITOR_USE_READLINE
;
4733 } else if (strcmp(mode
, "control") == 0) {
4734 flags
= MONITOR_USE_CONTROL
;
4736 fprintf(stderr
, "unknown monitor mode \"%s\"\n", mode
);
4740 if (qemu_opt_get_bool(opts
, "default", 0))
4741 flags
|= MONITOR_IS_DEFAULT
;
4743 chardev
= qemu_opt_get(opts
, "chardev");
4744 chr
= qemu_chr_find(chardev
);
4746 fprintf(stderr
, "chardev \"%s\" not found\n", chardev
);
4750 monitor_init(chr
, flags
);
4754 static void monitor_parse(const char *optarg
, const char *mode
)
4756 static int monitor_device_index
= 0;
4762 if (strstart(optarg
, "chardev:", &p
)) {
4763 snprintf(label
, sizeof(label
), "%s", p
);
4765 if (monitor_device_index
) {
4766 snprintf(label
, sizeof(label
), "monitor%d",
4767 monitor_device_index
);
4769 snprintf(label
, sizeof(label
), "monitor");
4772 opts
= qemu_chr_parse_compat(label
, optarg
);
4774 fprintf(stderr
, "parse error: %s\n", optarg
);
4779 opts
= qemu_opts_create(&qemu_mon_opts
, label
, 1);
4781 fprintf(stderr
, "duplicate chardev: %s\n", label
);
4784 qemu_opt_set(opts
, "mode", mode
);
4785 qemu_opt_set(opts
, "chardev", label
);
4787 qemu_opt_set(opts
, "default", "on");
4788 monitor_device_index
++;
4791 struct device_config
{
4793 DEV_USB
, /* -usbdevice */
4795 DEV_SERIAL
, /* -serial */
4796 DEV_PARALLEL
, /* -parallel */
4797 DEV_VIRTCON
, /* -virtioconsole */
4799 const char *cmdline
;
4800 QTAILQ_ENTRY(device_config
) next
;
4802 QTAILQ_HEAD(, device_config
) device_configs
= QTAILQ_HEAD_INITIALIZER(device_configs
);
4804 static void add_device_config(int type
, const char *cmdline
)
4806 struct device_config
*conf
;
4808 conf
= qemu_mallocz(sizeof(*conf
));
4810 conf
->cmdline
= cmdline
;
4811 QTAILQ_INSERT_TAIL(&device_configs
, conf
, next
);
4814 static int foreach_device_config(int type
, int (*func
)(const char *cmdline
))
4816 struct device_config
*conf
;
4819 QTAILQ_FOREACH(conf
, &device_configs
, next
) {
4820 if (conf
->type
!= type
)
4822 rc
= func(conf
->cmdline
);
4829 static int serial_parse(const char *devname
)
4831 static int index
= 0;
4834 if (strcmp(devname
, "none") == 0)
4836 if (index
== MAX_SERIAL_PORTS
) {
4837 fprintf(stderr
, "qemu: too many serial ports\n");
4840 snprintf(label
, sizeof(label
), "serial%d", index
);
4841 serial_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4842 if (!serial_hds
[index
]) {
4843 fprintf(stderr
, "qemu: could not open serial device '%s': %s\n",
4844 devname
, strerror(errno
));
4851 static int parallel_parse(const char *devname
)
4853 static int index
= 0;
4856 if (strcmp(devname
, "none") == 0)
4858 if (index
== MAX_PARALLEL_PORTS
) {
4859 fprintf(stderr
, "qemu: too many parallel ports\n");
4862 snprintf(label
, sizeof(label
), "parallel%d", index
);
4863 parallel_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4864 if (!parallel_hds
[index
]) {
4865 fprintf(stderr
, "qemu: could not open parallel device '%s': %s\n",
4866 devname
, strerror(errno
));
4873 static int virtcon_parse(const char *devname
)
4875 static int index
= 0;
4878 if (strcmp(devname
, "none") == 0)
4880 if (index
== MAX_VIRTIO_CONSOLES
) {
4881 fprintf(stderr
, "qemu: too many virtio consoles\n");
4884 snprintf(label
, sizeof(label
), "virtcon%d", index
);
4885 virtcon_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4886 if (!virtcon_hds
[index
]) {
4887 fprintf(stderr
, "qemu: could not open virtio console '%s': %s\n",
4888 devname
, strerror(errno
));
4895 int main(int argc
, char **argv
, char **envp
)
4897 const char *gdbstub_dev
= NULL
;
4898 uint32_t boot_devices_bitmap
= 0;
4900 int snapshot
, linux_boot
, net_boot
;
4901 const char *initrd_filename
;
4902 const char *kernel_filename
, *kernel_cmdline
;
4903 char boot_devices
[33] = "cad"; /* default to HD->floppy->CD-ROM */
4905 DisplayChangeListener
*dcl
;
4906 int cyls
, heads
, secs
, translation
;
4907 QemuOpts
*hda_opts
= NULL
, *opts
;
4909 const char *r
, *optarg
;
4910 const char *loadvm
= NULL
;
4911 QEMUMachine
*machine
;
4912 const char *cpu_model
;
4917 const char *pid_file
= NULL
;
4918 const char *incoming
= NULL
;
4921 struct passwd
*pwd
= NULL
;
4922 const char *chroot_dir
= NULL
;
4923 const char *run_as
= NULL
;
4926 int show_vnc_port
= 0;
4930 qemu_errors_to_file(stderr
);
4931 qemu_cache_utils_init(envp
);
4933 QLIST_INIT (&vm_change_state_head
);
4936 struct sigaction act
;
4937 sigfillset(&act
.sa_mask
);
4939 act
.sa_handler
= SIG_IGN
;
4940 sigaction(SIGPIPE
, &act
, NULL
);
4943 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4944 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4945 QEMU to run on a single CPU */
4950 h
= GetCurrentProcess();
4951 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4952 for(i
= 0; i
< 32; i
++) {
4953 if (mask
& (1 << i
))
4958 SetProcessAffinityMask(h
, mask
);
4964 module_call_init(MODULE_INIT_MACHINE
);
4965 machine
= find_default_machine();
4967 initrd_filename
= NULL
;
4970 kernel_filename
= NULL
;
4971 kernel_cmdline
= "";
4972 cyls
= heads
= secs
= 0;
4973 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4975 for (i
= 0; i
< MAX_NODES
; i
++) {
4977 node_cpumask
[i
] = 0;
4980 assigned_devices_index
= 0;
4994 hda_opts
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
4996 const QEMUOption
*popt
;
4999 /* Treat --foo the same as -foo. */
5002 popt
= qemu_options
;
5005 fprintf(stderr
, "%s: invalid option -- '%s'\n",
5009 if (!strcmp(popt
->name
, r
+ 1))
5013 if (popt
->flags
& HAS_ARG
) {
5014 if (optind
>= argc
) {
5015 fprintf(stderr
, "%s: option '%s' requires an argument\n",
5019 optarg
= argv
[optind
++];
5024 switch(popt
->index
) {
5026 machine
= find_machine(optarg
);
5029 printf("Supported machines are:\n");
5030 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5032 printf("%-10s %s (alias of %s)\n",
5033 m
->alias
, m
->desc
, m
->name
);
5034 printf("%-10s %s%s\n",
5036 m
->is_default
? " (default)" : "");
5038 exit(*optarg
!= '?');
5041 case QEMU_OPTION_cpu
:
5042 /* hw initialization will check this */
5043 if (*optarg
== '?') {
5044 /* XXX: implement xxx_cpu_list for targets that still miss it */
5045 #if defined(cpu_list)
5046 cpu_list(stdout
, &fprintf
);
5053 case QEMU_OPTION_initrd
:
5054 initrd_filename
= optarg
;
5056 case QEMU_OPTION_hda
:
5058 hda_opts
= drive_add(optarg
, HD_ALIAS
, 0);
5060 hda_opts
= drive_add(optarg
, HD_ALIAS
5061 ",cyls=%d,heads=%d,secs=%d%s",
5062 0, cyls
, heads
, secs
,
5063 translation
== BIOS_ATA_TRANSLATION_LBA
?
5065 translation
== BIOS_ATA_TRANSLATION_NONE
?
5066 ",trans=none" : "");
5068 case QEMU_OPTION_hdb
:
5069 case QEMU_OPTION_hdc
:
5070 case QEMU_OPTION_hdd
:
5071 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
5073 case QEMU_OPTION_drive
:
5074 drive_add(NULL
, "%s", optarg
);
5076 case QEMU_OPTION_set
:
5077 if (qemu_set_option(optarg
) != 0)
5080 case QEMU_OPTION_global
:
5081 if (qemu_global_option(optarg
) != 0)
5084 case QEMU_OPTION_mtdblock
:
5085 drive_add(optarg
, MTD_ALIAS
);
5087 case QEMU_OPTION_sd
:
5088 drive_add(optarg
, SD_ALIAS
);
5090 case QEMU_OPTION_pflash
:
5091 drive_add(optarg
, PFLASH_ALIAS
);
5093 case QEMU_OPTION_snapshot
:
5096 case QEMU_OPTION_hdachs
:
5100 cyls
= strtol(p
, (char **)&p
, 0);
5101 if (cyls
< 1 || cyls
> 16383)
5106 heads
= strtol(p
, (char **)&p
, 0);
5107 if (heads
< 1 || heads
> 16)
5112 secs
= strtol(p
, (char **)&p
, 0);
5113 if (secs
< 1 || secs
> 63)
5117 if (!strcmp(p
, "none"))
5118 translation
= BIOS_ATA_TRANSLATION_NONE
;
5119 else if (!strcmp(p
, "lba"))
5120 translation
= BIOS_ATA_TRANSLATION_LBA
;
5121 else if (!strcmp(p
, "auto"))
5122 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5125 } else if (*p
!= '\0') {
5127 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5130 if (hda_opts
!= NULL
) {
5132 snprintf(num
, sizeof(num
), "%d", cyls
);
5133 qemu_opt_set(hda_opts
, "cyls", num
);
5134 snprintf(num
, sizeof(num
), "%d", heads
);
5135 qemu_opt_set(hda_opts
, "heads", num
);
5136 snprintf(num
, sizeof(num
), "%d", secs
);
5137 qemu_opt_set(hda_opts
, "secs", num
);
5138 if (translation
== BIOS_ATA_TRANSLATION_LBA
)
5139 qemu_opt_set(hda_opts
, "trans", "lba");
5140 if (translation
== BIOS_ATA_TRANSLATION_NONE
)
5141 qemu_opt_set(hda_opts
, "trans", "none");
5145 case QEMU_OPTION_numa
:
5146 if (nb_numa_nodes
>= MAX_NODES
) {
5147 fprintf(stderr
, "qemu: too many NUMA nodes\n");
5152 case QEMU_OPTION_nographic
:
5153 display_type
= DT_NOGRAPHIC
;
5155 #ifdef CONFIG_CURSES
5156 case QEMU_OPTION_curses
:
5157 display_type
= DT_CURSES
;
5160 case QEMU_OPTION_portrait
:
5163 case QEMU_OPTION_kernel
:
5164 kernel_filename
= optarg
;
5166 case QEMU_OPTION_append
:
5167 kernel_cmdline
= optarg
;
5169 case QEMU_OPTION_cdrom
:
5170 drive_add(optarg
, CDROM_ALIAS
);
5172 case QEMU_OPTION_boot
:
5174 static const char * const params
[] = {
5175 "order", "once", "menu", NULL
5177 char buf
[sizeof(boot_devices
)];
5178 char *standard_boot_devices
;
5181 if (!strchr(optarg
, '=')) {
5183 pstrcpy(buf
, sizeof(buf
), optarg
);
5184 } else if (check_params(buf
, sizeof(buf
), params
, optarg
) < 0) {
5186 "qemu: unknown boot parameter '%s' in '%s'\n",
5192 get_param_value(buf
, sizeof(buf
), "order", optarg
)) {
5193 boot_devices_bitmap
= parse_bootdevices(buf
);
5194 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5197 if (get_param_value(buf
, sizeof(buf
),
5199 boot_devices_bitmap
|= parse_bootdevices(buf
);
5200 standard_boot_devices
= qemu_strdup(boot_devices
);
5201 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5202 qemu_register_reset(restore_boot_devices
,
5203 standard_boot_devices
);
5205 if (get_param_value(buf
, sizeof(buf
),
5207 if (!strcmp(buf
, "on")) {
5209 } else if (!strcmp(buf
, "off")) {
5213 "qemu: invalid option value '%s'\n",
5221 case QEMU_OPTION_fda
:
5222 case QEMU_OPTION_fdb
:
5223 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
5226 case QEMU_OPTION_no_fd_bootchk
:
5230 case QEMU_OPTION_netdev
:
5231 if (net_client_parse(&qemu_netdev_opts
, optarg
) == -1) {
5235 case QEMU_OPTION_net
:
5236 if (net_client_parse(&qemu_net_opts
, optarg
) == -1) {
5241 case QEMU_OPTION_tftp
:
5242 legacy_tftp_prefix
= optarg
;
5244 case QEMU_OPTION_bootp
:
5245 legacy_bootp_filename
= optarg
;
5248 case QEMU_OPTION_smb
:
5249 if (net_slirp_smb(optarg
) < 0)
5253 case QEMU_OPTION_redir
:
5254 if (net_slirp_redir(optarg
) < 0)
5258 case QEMU_OPTION_bt
:
5259 add_device_config(DEV_BT
, optarg
);
5262 case QEMU_OPTION_audio_help
:
5266 case QEMU_OPTION_soundhw
:
5267 select_soundhw (optarg
);
5273 case QEMU_OPTION_version
:
5277 case QEMU_OPTION_m
: {
5281 value
= strtoul(optarg
, &ptr
, 10);
5283 case 0: case 'M': case 'm':
5290 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5294 /* On 32-bit hosts, QEMU is limited by virtual address space */
5295 if (value
> (2047 << 20) && HOST_LONG_BITS
== 32) {
5296 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5299 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5300 fprintf(stderr
, "qemu: ram size too large\n");
5309 const CPULogItem
*item
;
5311 mask
= cpu_str_to_log_mask(optarg
);
5313 printf("Log items (comma separated):\n");
5314 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5315 printf("%-10s %s\n", item
->name
, item
->help
);
5323 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5325 case QEMU_OPTION_gdb
:
5326 gdbstub_dev
= optarg
;
5331 case QEMU_OPTION_bios
:
5334 case QEMU_OPTION_singlestep
:
5341 keyboard_layout
= optarg
;
5343 case QEMU_OPTION_localtime
:
5346 case QEMU_OPTION_vga
:
5347 select_vgahw (optarg
);
5349 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5355 w
= strtol(p
, (char **)&p
, 10);
5358 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5364 h
= strtol(p
, (char **)&p
, 10);
5369 depth
= strtol(p
, (char **)&p
, 10);
5370 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5371 depth
!= 24 && depth
!= 32)
5373 } else if (*p
== '\0') {
5374 depth
= graphic_depth
;
5381 graphic_depth
= depth
;
5385 case QEMU_OPTION_echr
:
5388 term_escape_char
= strtol(optarg
, &r
, 0);
5390 printf("Bad argument to echr\n");
5393 case QEMU_OPTION_monitor
:
5394 monitor_parse(optarg
, "readline");
5395 default_monitor
= 0;
5397 case QEMU_OPTION_qmp
:
5398 monitor_parse(optarg
, "control");
5399 default_monitor
= 0;
5401 case QEMU_OPTION_mon
:
5402 opts
= qemu_opts_parse(&qemu_mon_opts
, optarg
, "chardev");
5404 fprintf(stderr
, "parse error: %s\n", optarg
);
5407 default_monitor
= 0;
5409 case QEMU_OPTION_chardev
:
5410 opts
= qemu_opts_parse(&qemu_chardev_opts
, optarg
, "backend");
5412 fprintf(stderr
, "parse error: %s\n", optarg
);
5416 case QEMU_OPTION_serial
:
5417 add_device_config(DEV_SERIAL
, optarg
);
5420 case QEMU_OPTION_watchdog
:
5423 "qemu: only one watchdog option may be given\n");
5428 case QEMU_OPTION_watchdog_action
:
5429 if (select_watchdog_action(optarg
) == -1) {
5430 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5434 case QEMU_OPTION_virtiocon
:
5435 add_device_config(DEV_VIRTCON
, optarg
);
5436 default_virtcon
= 0;
5438 case QEMU_OPTION_parallel
:
5439 add_device_config(DEV_PARALLEL
, optarg
);
5440 default_parallel
= 0;
5442 case QEMU_OPTION_loadvm
:
5445 case QEMU_OPTION_full_screen
:
5449 case QEMU_OPTION_no_frame
:
5452 case QEMU_OPTION_alt_grab
:
5455 case QEMU_OPTION_ctrl_grab
:
5458 case QEMU_OPTION_no_quit
:
5461 case QEMU_OPTION_sdl
:
5462 display_type
= DT_SDL
;
5465 case QEMU_OPTION_pidfile
:
5469 case QEMU_OPTION_win2k_hack
:
5470 win2k_install_hack
= 1;
5472 case QEMU_OPTION_rtc_td_hack
:
5475 case QEMU_OPTION_acpitable
:
5476 if(acpi_table_add(optarg
) < 0) {
5477 fprintf(stderr
, "Wrong acpi table provided\n");
5481 case QEMU_OPTION_smbios
:
5482 if(smbios_entry_add(optarg
) < 0) {
5483 fprintf(stderr
, "Wrong smbios provided\n");
5490 case QEMU_OPTION_enable_kvm
:
5494 case QEMU_OPTION_no_kvm
:
5497 case QEMU_OPTION_no_kvm_irqchip
: {
5502 case QEMU_OPTION_no_kvm_pit
: {
5506 case QEMU_OPTION_no_kvm_pit_reinjection
: {
5507 kvm_pit_reinject
= 0;
5510 case QEMU_OPTION_enable_nesting
: {
5514 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5515 case QEMU_OPTION_pcidevice
:
5516 if (assigned_devices_index
>= MAX_DEV_ASSIGN_CMDLINE
) {
5517 fprintf(stderr
, "Too many assigned devices\n");
5520 assigned_devices
[assigned_devices_index
] = optarg
;
5521 assigned_devices_index
++;
5525 case QEMU_OPTION_usb
:
5528 case QEMU_OPTION_usbdevice
:
5530 add_device_config(DEV_USB
, optarg
);
5532 case QEMU_OPTION_device
:
5533 if (!qemu_opts_parse(&qemu_device_opts
, optarg
, "driver")) {
5537 case QEMU_OPTION_smp
:
5540 fprintf(stderr
, "Invalid number of CPUs\n");
5543 if (max_cpus
< smp_cpus
) {
5544 fprintf(stderr
, "maxcpus must be equal to or greater than "
5548 if (max_cpus
> 255) {
5549 fprintf(stderr
, "Unsupported number of maxcpus\n");
5553 case QEMU_OPTION_vnc
:
5554 display_type
= DT_VNC
;
5555 vnc_display
= optarg
;
5558 case QEMU_OPTION_no_acpi
:
5561 case QEMU_OPTION_no_hpet
:
5564 case QEMU_OPTION_balloon
:
5565 if (balloon_parse(optarg
) < 0) {
5566 fprintf(stderr
, "Unknown -balloon argument %s\n", optarg
);
5571 case QEMU_OPTION_no_reboot
:
5574 case QEMU_OPTION_no_shutdown
:
5577 case QEMU_OPTION_show_cursor
:
5580 case QEMU_OPTION_uuid
:
5581 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5582 fprintf(stderr
, "Fail to parse UUID string."
5583 " Wrong format.\n");
5588 case QEMU_OPTION_daemonize
:
5592 case QEMU_OPTION_option_rom
:
5593 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5594 fprintf(stderr
, "Too many option ROMs\n");
5597 option_rom
[nb_option_roms
] = optarg
;
5600 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5601 case QEMU_OPTION_semihosting
:
5602 semihosting_enabled
= 1;
5605 case QEMU_OPTION_tdf
:
5608 case QEMU_OPTION_kvm_shadow_memory
:
5609 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
5611 case QEMU_OPTION_mempath
:
5615 case QEMU_OPTION_mem_prealloc
:
5616 mem_prealloc
= !mem_prealloc
;
5619 case QEMU_OPTION_name
:
5620 qemu_name
= qemu_strdup(optarg
);
5622 char *p
= strchr(qemu_name
, ',');
5625 if (strncmp(p
, "process=", 8)) {
5626 fprintf(stderr
, "Unknown subargument %s to -name", p
);
5634 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5635 case QEMU_OPTION_prom_env
:
5636 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5637 fprintf(stderr
, "Too many prom variables\n");
5640 prom_envs
[nb_prom_envs
] = optarg
;
5645 case QEMU_OPTION_old_param
:
5649 case QEMU_OPTION_clock
:
5650 configure_alarms(optarg
);
5652 case QEMU_OPTION_startdate
:
5653 configure_rtc_date_offset(optarg
, 1);
5655 case QEMU_OPTION_rtc
:
5656 opts
= qemu_opts_parse(&qemu_rtc_opts
, optarg
, NULL
);
5658 fprintf(stderr
, "parse error: %s\n", optarg
);
5661 configure_rtc(opts
);
5663 case QEMU_OPTION_tb_size
:
5664 tb_size
= strtol(optarg
, NULL
, 0);
5668 case QEMU_OPTION_icount
:
5670 if (strcmp(optarg
, "auto") == 0) {
5671 icount_time_shift
= -1;
5673 icount_time_shift
= strtol(optarg
, NULL
, 0);
5676 case QEMU_OPTION_incoming
:
5679 case QEMU_OPTION_nodefaults
:
5681 default_parallel
= 0;
5682 default_virtcon
= 0;
5683 default_monitor
= 0;
5691 case QEMU_OPTION_chroot
:
5692 chroot_dir
= optarg
;
5694 case QEMU_OPTION_runas
:
5697 case QEMU_OPTION_nvram
:
5702 case QEMU_OPTION_xen_domid
:
5703 xen_domid
= atoi(optarg
);
5705 case QEMU_OPTION_xen_create
:
5706 xen_mode
= XEN_CREATE
;
5708 case QEMU_OPTION_xen_attach
:
5709 xen_mode
= XEN_ATTACH
;
5712 case QEMU_OPTION_readconfig
:
5715 fp
= fopen(optarg
, "r");
5717 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5720 if (qemu_config_parse(fp
) != 0) {
5726 case QEMU_OPTION_writeconfig
:
5729 if (strcmp(optarg
, "-") == 0) {
5732 fp
= fopen(optarg
, "w");
5734 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5738 qemu_config_write(fp
);
5746 /* If no data_dir is specified then try to find it relative to the
5749 data_dir
= find_datadir(argv
[0]);
5751 /* If all else fails use the install patch specified when building. */
5753 data_dir
= CONFIG_QEMU_SHAREDIR
;
5757 * Default to max_cpus = smp_cpus, in case the user doesn't
5758 * specify a max_cpus value.
5761 max_cpus
= smp_cpus
;
5763 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5764 if (smp_cpus
> machine
->max_cpus
) {
5765 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5766 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5771 qemu_opts_foreach(&qemu_device_opts
, default_driver_check
, NULL
, 0);
5772 qemu_opts_foreach(&qemu_global_opts
, default_driver_check
, NULL
, 0);
5774 if (machine
->no_serial
) {
5777 if (machine
->no_parallel
) {
5778 default_parallel
= 0;
5780 if (!machine
->use_virtcon
) {
5781 default_virtcon
= 0;
5783 if (machine
->no_vga
) {
5786 if (machine
->no_floppy
) {
5789 if (machine
->no_cdrom
) {
5792 if (machine
->no_sdcard
) {
5796 if (display_type
== DT_NOGRAPHIC
) {
5797 if (default_parallel
)
5798 add_device_config(DEV_PARALLEL
, "null");
5799 if (default_serial
&& default_monitor
) {
5800 add_device_config(DEV_SERIAL
, "mon:stdio");
5801 } else if (default_virtcon
&& default_monitor
) {
5802 add_device_config(DEV_VIRTCON
, "mon:stdio");
5805 add_device_config(DEV_SERIAL
, "stdio");
5806 if (default_virtcon
)
5807 add_device_config(DEV_VIRTCON
, "stdio");
5808 if (default_monitor
)
5809 monitor_parse("stdio", "readline");
5813 add_device_config(DEV_SERIAL
, "vc:80Cx24C");
5814 if (default_parallel
)
5815 add_device_config(DEV_PARALLEL
, "vc:80Cx24C");
5816 if (default_monitor
)
5817 monitor_parse("vc:80Cx24C", "readline");
5818 if (default_virtcon
)
5819 add_device_config(DEV_VIRTCON
, "vc:80Cx24C");
5822 vga_interface_type
= VGA_CIRRUS
;
5824 if (qemu_opts_foreach(&qemu_chardev_opts
, chardev_init_func
, NULL
, 1) != 0)
5831 if (pipe(fds
) == -1)
5842 len
= read(fds
[0], &status
, 1);
5843 if (len
== -1 && (errno
== EINTR
))
5848 else if (status
== 1) {
5849 fprintf(stderr
, "Could not acquire pidfile: %s\n", strerror(errno
));
5857 qemu_set_cloexec(fds
[1]);
5869 signal(SIGTSTP
, SIG_IGN
);
5870 signal(SIGTTOU
, SIG_IGN
);
5871 signal(SIGTTIN
, SIG_IGN
);
5874 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5877 write(fds
[1], &status
, 1);
5879 fprintf(stderr
, "Could not acquire pid file: %s\n", strerror(errno
));
5884 if (kvm_enabled()) {
5887 ret
= kvm_init(smp_cpus
);
5889 #if defined(KVM_UPSTREAM) || defined(CONFIG_NO_CPU_EMULATION)
5890 fprintf(stderr
, "failed to initialize KVM\n");
5893 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
5898 if (qemu_init_main_loop()) {
5899 fprintf(stderr
, "qemu_init_main_loop failed\n");
5902 linux_boot
= (kernel_filename
!= NULL
);
5904 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5905 fprintf(stderr
, "-append only allowed with -kernel option\n");
5909 if (!linux_boot
&& initrd_filename
!= NULL
) {
5910 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5915 /* Win32 doesn't support line-buffering and requires size >= 2 */
5916 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5919 if (init_timer_alarm() < 0) {
5920 fprintf(stderr
, "could not initialize alarm timer\n");
5923 if (use_icount
&& icount_time_shift
< 0) {
5925 /* 125MIPS seems a reasonable initial guess at the guest speed.
5926 It will be corrected fairly quickly anyway. */
5927 icount_time_shift
= 3;
5928 init_icount_adjust();
5935 if (net_init_clients() < 0) {
5939 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5940 net_set_boot_mask(net_boot
);
5942 /* init the bluetooth world */
5943 if (foreach_device_config(DEV_BT
, bt_parse
))
5946 /* init the memory */
5948 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5950 /* init the dynamic translator */
5951 cpu_exec_init_all(tb_size
* 1024 * 1024);
5953 bdrv_init_with_whitelist();
5957 if (default_cdrom
) {
5958 /* we always create the cdrom drive, even if no disk is there */
5959 drive_add(NULL
, CDROM_ALIAS
);
5962 if (default_floppy
) {
5963 /* we always create at least one floppy */
5964 drive_add(NULL
, FD_ALIAS
, 0);
5967 if (default_sdcard
) {
5968 /* we always create one sd slot, even if no card is in it */
5969 drive_add(NULL
, SD_ALIAS
);
5972 /* open the virtual block devices */
5974 qemu_opts_foreach(&qemu_drive_opts
, drive_enable_snapshot
, NULL
, 0);
5975 if (qemu_opts_foreach(&qemu_drive_opts
, drive_init_func
, machine
, 1) != 0)
5978 vmstate_register(0, &vmstate_timers
,&timers_state
);
5979 register_savevm_live("ram", 0, 3, NULL
, ram_save_live
, NULL
,
5982 if (nb_numa_nodes
> 0) {
5985 if (nb_numa_nodes
> smp_cpus
) {
5986 nb_numa_nodes
= smp_cpus
;
5989 /* If no memory size if given for any node, assume the default case
5990 * and distribute the available memory equally across all nodes
5992 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5993 if (node_mem
[i
] != 0)
5996 if (i
== nb_numa_nodes
) {
5997 uint64_t usedmem
= 0;
5999 /* On Linux, the each node's border has to be 8MB aligned,
6000 * the final node gets the rest.
6002 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
6003 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
6004 usedmem
+= node_mem
[i
];
6006 node_mem
[i
] = ram_size
- usedmem
;
6009 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6010 if (node_cpumask
[i
] != 0)
6013 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6014 * must cope with this anyway, because there are BIOSes out there in
6015 * real machines which also use this scheme.
6017 if (i
== nb_numa_nodes
) {
6018 for (i
= 0; i
< smp_cpus
; i
++) {
6019 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
6024 if (foreach_device_config(DEV_SERIAL
, serial_parse
) < 0)
6026 if (foreach_device_config(DEV_PARALLEL
, parallel_parse
) < 0)
6028 if (foreach_device_config(DEV_VIRTCON
, virtcon_parse
) < 0)
6031 module_call_init(MODULE_INIT_DEVICE
);
6034 i
= select_watchdog(watchdog
);
6036 exit (i
== 1 ? 1 : 0);
6039 if (machine
->compat_props
) {
6040 qdev_prop_register_global_list(machine
->compat_props
);
6044 machine
->init(ram_size
, boot_devices
,
6045 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
6049 /* must be after terminal init, SDL library changes signal handlers */
6053 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
6054 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6055 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
6061 current_machine
= machine
;
6063 /* init USB devices */
6065 if (foreach_device_config(DEV_USB
, usb_parse
) < 0)
6069 /* init generic devices */
6070 if (qemu_opts_foreach(&qemu_device_opts
, device_init_func
, NULL
, 1) != 0)
6074 dumb_display_init();
6075 /* just use the first displaystate for the moment */
6078 if (display_type
== DT_DEFAULT
) {
6079 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6080 display_type
= DT_SDL
;
6082 display_type
= DT_VNC
;
6083 vnc_display
= "localhost:0,to=99";
6089 switch (display_type
) {
6092 #if defined(CONFIG_CURSES)
6094 curses_display_init(ds
, full_screen
);
6097 #if defined(CONFIG_SDL)
6099 sdl_display_init(ds
, full_screen
, no_frame
);
6101 #elif defined(CONFIG_COCOA)
6103 cocoa_display_init(ds
, full_screen
);
6107 vnc_display_init(ds
);
6108 if (vnc_display_open(ds
, vnc_display
) < 0)
6111 if (show_vnc_port
) {
6112 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
6120 dcl
= ds
->listeners
;
6121 while (dcl
!= NULL
) {
6122 if (dcl
->dpy_refresh
!= NULL
) {
6123 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
6124 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
6129 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
6130 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
6131 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
6134 text_consoles_set_display(display_state
);
6136 if (qemu_opts_foreach(&qemu_mon_opts
, mon_init_func
, NULL
, 1) != 0)
6139 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
6140 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
6145 qdev_machine_creation_done();
6147 if (rom_load_all() != 0) {
6148 fprintf(stderr
, "rom loading failed\n");
6152 qemu_system_reset();
6154 if (load_vmstate(cur_mon
, loadvm
) < 0) {
6160 qemu_start_incoming_migration(incoming
);
6161 } else if (autostart
) {
6171 len
= write(fds
[1], &status
, 1);
6172 if (len
== -1 && (errno
== EINTR
))
6179 TFR(fd
= qemu_open("/dev/null", O_RDWR
));
6185 pwd
= getpwnam(run_as
);
6187 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
6193 if (chroot(chroot_dir
) < 0) {
6194 fprintf(stderr
, "chroot failed\n");
6201 if (setgid(pwd
->pw_gid
) < 0) {
6202 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
6205 if (setuid(pwd
->pw_uid
) < 0) {
6206 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
6209 if (setuid(0) != -1) {
6210 fprintf(stderr
, "Dropping privileges failed\n");