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
)
2717 r
= usb_device_add(cmdline
, 0);
2719 fprintf(stderr
, "qemu: could not add USB device '%s'\n", cmdline
);
2724 void do_usb_add(Monitor
*mon
, const QDict
*qdict
)
2726 const char *devname
= qdict_get_str(qdict
, "devname");
2727 if (usb_device_add(devname
, 1) < 0) {
2728 qemu_error("could not add USB device '%s'\n", devname
);
2732 void do_usb_del(Monitor
*mon
, const QDict
*qdict
)
2734 const char *devname
= qdict_get_str(qdict
, "devname");
2735 if (usb_device_del(devname
) < 0) {
2736 qemu_error("could not delete USB device '%s'\n", devname
);
2740 /***********************************************************/
2741 /* PCMCIA/Cardbus */
2743 static struct pcmcia_socket_entry_s
{
2744 PCMCIASocket
*socket
;
2745 struct pcmcia_socket_entry_s
*next
;
2746 } *pcmcia_sockets
= 0;
2748 void pcmcia_socket_register(PCMCIASocket
*socket
)
2750 struct pcmcia_socket_entry_s
*entry
;
2752 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2753 entry
->socket
= socket
;
2754 entry
->next
= pcmcia_sockets
;
2755 pcmcia_sockets
= entry
;
2758 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2760 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2762 ptr
= &pcmcia_sockets
;
2763 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2764 if (entry
->socket
== socket
) {
2770 void pcmcia_info(Monitor
*mon
)
2772 struct pcmcia_socket_entry_s
*iter
;
2774 if (!pcmcia_sockets
)
2775 monitor_printf(mon
, "No PCMCIA sockets\n");
2777 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2778 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2779 iter
->socket
->attached
? iter
->socket
->card_string
:
2783 /***********************************************************/
2784 /* register display */
2786 struct DisplayAllocator default_allocator
= {
2787 defaultallocator_create_displaysurface
,
2788 defaultallocator_resize_displaysurface
,
2789 defaultallocator_free_displaysurface
2792 void register_displaystate(DisplayState
*ds
)
2802 DisplayState
*get_displaystate(void)
2804 return display_state
;
2807 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
2809 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
2810 return ds
->allocator
;
2815 static void dumb_display_init(void)
2817 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
2818 ds
->allocator
= &default_allocator
;
2819 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
2820 register_displaystate(ds
);
2823 /***********************************************************/
2826 typedef struct IOHandlerRecord
{
2828 IOCanRWHandler
*fd_read_poll
;
2830 IOHandler
*fd_write
;
2833 /* temporary data */
2835 struct IOHandlerRecord
*next
;
2838 static IOHandlerRecord
*first_io_handler
;
2840 /* XXX: fd_read_poll should be suppressed, but an API change is
2841 necessary in the character devices to suppress fd_can_read(). */
2842 int qemu_set_fd_handler2(int fd
,
2843 IOCanRWHandler
*fd_read_poll
,
2845 IOHandler
*fd_write
,
2848 IOHandlerRecord
**pioh
, *ioh
;
2850 if (!fd_read
&& !fd_write
) {
2851 pioh
= &first_io_handler
;
2856 if (ioh
->fd
== fd
) {
2863 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
2867 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
2868 ioh
->next
= first_io_handler
;
2869 first_io_handler
= ioh
;
2872 ioh
->fd_read_poll
= fd_read_poll
;
2873 ioh
->fd_read
= fd_read
;
2874 ioh
->fd_write
= fd_write
;
2875 ioh
->opaque
= opaque
;
2878 qemu_notify_event();
2882 int qemu_set_fd_handler(int fd
,
2884 IOHandler
*fd_write
,
2887 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
2891 /***********************************************************/
2892 /* Polling handling */
2894 typedef struct PollingEntry
{
2897 struct PollingEntry
*next
;
2900 static PollingEntry
*first_polling_entry
;
2902 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
2904 PollingEntry
**ppe
, *pe
;
2905 pe
= qemu_mallocz(sizeof(PollingEntry
));
2907 pe
->opaque
= opaque
;
2908 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
2913 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
2915 PollingEntry
**ppe
, *pe
;
2916 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
2918 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
2926 /***********************************************************/
2927 /* Wait objects support */
2928 typedef struct WaitObjects
{
2930 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
2931 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
2932 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
2935 static WaitObjects wait_objects
= {0};
2937 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2939 WaitObjects
*w
= &wait_objects
;
2941 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
2943 w
->events
[w
->num
] = handle
;
2944 w
->func
[w
->num
] = func
;
2945 w
->opaque
[w
->num
] = opaque
;
2950 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2953 WaitObjects
*w
= &wait_objects
;
2956 for (i
= 0; i
< w
->num
; i
++) {
2957 if (w
->events
[i
] == handle
)
2960 w
->events
[i
] = w
->events
[i
+ 1];
2961 w
->func
[i
] = w
->func
[i
+ 1];
2962 w
->opaque
[i
] = w
->opaque
[i
+ 1];
2970 /***********************************************************/
2971 /* ram save/restore */
2973 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2974 #define RAM_SAVE_FLAG_COMPRESS 0x02
2975 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2976 #define RAM_SAVE_FLAG_PAGE 0x08
2977 #define RAM_SAVE_FLAG_EOS 0x10
2979 static int is_dup_page(uint8_t *page
, uint8_t ch
)
2981 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
2982 uint32_t *array
= (uint32_t *)page
;
2985 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
2986 if (array
[i
] != val
)
2993 static int ram_save_block(QEMUFile
*f
)
2995 static ram_addr_t current_addr
= 0;
2996 ram_addr_t saved_addr
= current_addr
;
2997 ram_addr_t addr
= 0;
3000 while (addr
< last_ram_offset
) {
3001 if (kvm_enabled() && current_addr
== 0) {
3003 r
= kvm_update_dirty_pages_log();
3005 fprintf(stderr
, "%s: update dirty pages log failed %d\n", __FUNCTION__
, r
);
3006 qemu_file_set_error(f
);
3010 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
3013 cpu_physical_memory_reset_dirty(current_addr
,
3014 current_addr
+ TARGET_PAGE_SIZE
,
3015 MIGRATION_DIRTY_FLAG
);
3017 p
= qemu_get_ram_ptr(current_addr
);
3019 if (is_dup_page(p
, *p
)) {
3020 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
3021 qemu_put_byte(f
, *p
);
3023 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
3024 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
3030 addr
+= TARGET_PAGE_SIZE
;
3031 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
3037 static uint64_t bytes_transferred
;
3039 static ram_addr_t
ram_save_remaining(void)
3042 ram_addr_t count
= 0;
3044 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3045 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3052 uint64_t ram_bytes_remaining(void)
3054 return ram_save_remaining() * TARGET_PAGE_SIZE
;
3057 uint64_t ram_bytes_transferred(void)
3059 return bytes_transferred
;
3062 uint64_t ram_bytes_total(void)
3064 return last_ram_offset
;
3067 static int ram_save_live(Monitor
*mon
, QEMUFile
*f
, int stage
, void *opaque
)
3070 uint64_t bytes_transferred_last
;
3072 uint64_t expected_time
= 0;
3075 cpu_physical_memory_set_dirty_tracking(0);
3079 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX
) != 0) {
3080 qemu_file_set_error(f
);
3085 bytes_transferred
= 0;
3087 /* Make sure all dirty bits are set */
3088 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3089 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3090 cpu_physical_memory_set_dirty(addr
);
3093 /* Enable dirty memory tracking */
3094 cpu_physical_memory_set_dirty_tracking(1);
3096 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
3099 bytes_transferred_last
= bytes_transferred
;
3100 bwidth
= get_clock();
3102 while (!qemu_file_rate_limit(f
)) {
3105 ret
= ram_save_block(f
);
3106 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
3107 if (ret
== 0) /* no more blocks */
3111 bwidth
= get_clock() - bwidth
;
3112 bwidth
= (bytes_transferred
- bytes_transferred_last
) / bwidth
;
3114 /* if we haven't transferred anything this round, force expected_time to a
3115 * a very high value, but without crashing */
3119 /* try transferring iterative blocks of memory */
3121 /* flush all remaining blocks regardless of rate limiting */
3122 while (ram_save_block(f
) != 0) {
3123 bytes_transferred
+= TARGET_PAGE_SIZE
;
3125 cpu_physical_memory_set_dirty_tracking(0);
3128 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3130 expected_time
= ram_save_remaining() * TARGET_PAGE_SIZE
/ bwidth
;
3132 return (stage
== 2) && (expected_time
<= migrate_max_downtime());
3135 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
3140 if (version_id
!= 3)
3144 addr
= qemu_get_be64(f
);
3146 flags
= addr
& ~TARGET_PAGE_MASK
;
3147 addr
&= TARGET_PAGE_MASK
;
3149 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
3150 if (addr
!= last_ram_offset
)
3154 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
3155 uint8_t ch
= qemu_get_byte(f
);
3156 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
3159 (!kvm_enabled() || kvm_has_sync_mmu())) {
3160 madvise(qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
, MADV_DONTNEED
);
3163 } else if (flags
& RAM_SAVE_FLAG_PAGE
) {
3164 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
3166 if (qemu_file_has_error(f
)) {
3169 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
3174 void qemu_service_io(void)
3176 qemu_notify_event();
3179 /***********************************************************/
3180 /* machine registration */
3182 static QEMUMachine
*first_machine
= NULL
;
3183 QEMUMachine
*current_machine
= NULL
;
3185 int qemu_register_machine(QEMUMachine
*m
)
3188 pm
= &first_machine
;
3196 static QEMUMachine
*find_machine(const char *name
)
3200 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3201 if (!strcmp(m
->name
, name
))
3203 if (m
->alias
&& !strcmp(m
->alias
, name
))
3209 static QEMUMachine
*find_default_machine(void)
3213 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3214 if (m
->is_default
) {
3221 /***********************************************************/
3222 /* main execution loop */
3224 static void gui_update(void *opaque
)
3226 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3227 DisplayState
*ds
= opaque
;
3228 DisplayChangeListener
*dcl
= ds
->listeners
;
3232 while (dcl
!= NULL
) {
3233 if (dcl
->gui_timer_interval
&&
3234 dcl
->gui_timer_interval
< interval
)
3235 interval
= dcl
->gui_timer_interval
;
3238 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3241 static void nographic_update(void *opaque
)
3243 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3245 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3248 struct vm_change_state_entry
{
3249 VMChangeStateHandler
*cb
;
3251 QLIST_ENTRY (vm_change_state_entry
) entries
;
3254 static QLIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3256 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3259 VMChangeStateEntry
*e
;
3261 e
= qemu_mallocz(sizeof (*e
));
3265 QLIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3269 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3271 QLIST_REMOVE (e
, entries
);
3275 static void vm_state_notify(int running
, int reason
)
3277 VMChangeStateEntry
*e
;
3279 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3280 e
->cb(e
->opaque
, running
, reason
);
3284 static void resume_all_vcpus(void);
3285 static void pause_all_vcpus(void);
3292 vm_state_notify(1, 0);
3293 qemu_rearm_alarm_timer(alarm_timer
);
3298 /* reset/shutdown handler */
3300 typedef struct QEMUResetEntry
{
3301 QTAILQ_ENTRY(QEMUResetEntry
) entry
;
3302 QEMUResetHandler
*func
;
3306 static QTAILQ_HEAD(reset_handlers
, QEMUResetEntry
) reset_handlers
=
3307 QTAILQ_HEAD_INITIALIZER(reset_handlers
);
3308 static int reset_requested
;
3309 static int shutdown_requested
;
3310 static int powerdown_requested
;
3311 static int debug_requested
;
3312 static int vmstop_requested
;
3314 int qemu_no_shutdown(void)
3316 int r
= no_shutdown
;
3321 int qemu_shutdown_requested(void)
3323 int r
= shutdown_requested
;
3324 shutdown_requested
= 0;
3328 int qemu_reset_requested(void)
3330 int r
= reset_requested
;
3331 reset_requested
= 0;
3335 int qemu_powerdown_requested(void)
3337 int r
= powerdown_requested
;
3338 powerdown_requested
= 0;
3342 static int qemu_debug_requested(void)
3344 int r
= debug_requested
;
3345 debug_requested
= 0;
3349 static int qemu_vmstop_requested(void)
3351 int r
= vmstop_requested
;
3352 vmstop_requested
= 0;
3356 static void do_vm_stop(int reason
)
3359 cpu_disable_ticks();
3362 vm_state_notify(0, reason
);
3366 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3368 QEMUResetEntry
*re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3371 re
->opaque
= opaque
;
3372 QTAILQ_INSERT_TAIL(&reset_handlers
, re
, entry
);
3375 void qemu_unregister_reset(QEMUResetHandler
*func
, void *opaque
)
3379 QTAILQ_FOREACH(re
, &reset_handlers
, entry
) {
3380 if (re
->func
== func
&& re
->opaque
== opaque
) {
3381 QTAILQ_REMOVE(&reset_handlers
, re
, entry
);
3388 void qemu_system_reset(void)
3390 QEMUResetEntry
*re
, *nre
;
3392 /* reset all devices */
3393 QTAILQ_FOREACH_SAFE(re
, &reset_handlers
, entry
, nre
) {
3394 re
->func(re
->opaque
);
3398 void qemu_system_reset_request(void)
3401 shutdown_requested
= 1;
3403 reset_requested
= 1;
3405 if (cpu_single_env
) {
3406 cpu_single_env
->stopped
= 1;
3408 qemu_notify_event();
3411 void qemu_system_shutdown_request(void)
3413 shutdown_requested
= 1;
3414 qemu_notify_event();
3417 void qemu_system_powerdown_request(void)
3419 powerdown_requested
= 1;
3420 qemu_notify_event();
3423 #ifdef CONFIG_IOTHREAD
3424 static void qemu_system_vmstop_request(int reason
)
3426 vmstop_requested
= reason
;
3427 qemu_notify_event();
3432 static int io_thread_fd
= -1;
3434 static void qemu_event_increment(void)
3436 static const char byte
= 0;
3438 if (io_thread_fd
== -1)
3441 write(io_thread_fd
, &byte
, sizeof(byte
));
3444 static void qemu_event_read(void *opaque
)
3446 int fd
= (unsigned long)opaque
;
3449 /* Drain the notify pipe */
3452 len
= read(fd
, buffer
, sizeof(buffer
));
3453 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
3456 static int qemu_event_init(void)
3461 err
= qemu_pipe(fds
);
3465 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3469 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3473 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3474 (void *)(unsigned long)fds
[0]);
3476 io_thread_fd
= fds
[1];
3485 HANDLE qemu_event_handle
;
3487 static void dummy_event_handler(void *opaque
)
3491 static int qemu_event_init(void)
3493 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3494 if (!qemu_event_handle
) {
3495 fprintf(stderr
, "Failed CreateEvent: %ld\n", GetLastError());
3498 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3502 static void qemu_event_increment(void)
3504 if (!SetEvent(qemu_event_handle
)) {
3505 fprintf(stderr
, "qemu_event_increment: SetEvent failed: %ld\n",
3512 static int cpu_can_run(CPUState
*env
)
3521 #ifndef CONFIG_IOTHREAD
3522 static int qemu_init_main_loop(void)
3524 return qemu_event_init();
3527 void qemu_init_vcpu(void *_env
)
3529 CPUState
*env
= _env
;
3533 env
->nr_cores
= smp_cores
;
3534 env
->nr_threads
= smp_threads
;
3538 int qemu_cpu_self(void *env
)
3543 static void resume_all_vcpus(void)
3547 static void pause_all_vcpus(void)
3551 void qemu_cpu_kick(void *env
)
3556 void qemu_notify_event(void)
3558 CPUState
*env
= cpu_single_env
;
3560 if (kvm_enabled()) {
3561 qemu_kvm_notify_work();
3569 #if defined(KVM_UPSTREAM) || !defined(CONFIG_KVM)
3570 void qemu_mutex_lock_iothread(void) {}
3571 void qemu_mutex_unlock_iothread(void) {}
3574 void vm_stop(int reason
)
3579 #else /* CONFIG_IOTHREAD */
3581 #include "qemu-thread.h"
3583 QemuMutex qemu_global_mutex
;
3584 static QemuMutex qemu_fair_mutex
;
3586 static QemuThread io_thread
;
3588 static QemuThread
*tcg_cpu_thread
;
3589 static QemuCond
*tcg_halt_cond
;
3591 static int qemu_system_ready
;
3593 static QemuCond qemu_cpu_cond
;
3595 static QemuCond qemu_system_cond
;
3596 static QemuCond qemu_pause_cond
;
3598 static void block_io_signals(void);
3599 static void unblock_io_signals(void);
3600 static int tcg_has_work(void);
3602 static int qemu_init_main_loop(void)
3606 ret
= qemu_event_init();
3610 qemu_cond_init(&qemu_pause_cond
);
3611 qemu_mutex_init(&qemu_fair_mutex
);
3612 qemu_mutex_init(&qemu_global_mutex
);
3613 qemu_mutex_lock(&qemu_global_mutex
);
3615 unblock_io_signals();
3616 qemu_thread_self(&io_thread
);
3621 static void qemu_wait_io_event(CPUState
*env
)
3623 while (!tcg_has_work())
3624 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3626 qemu_mutex_unlock(&qemu_global_mutex
);
3629 * Users of qemu_global_mutex can be starved, having no chance
3630 * to acquire it since this path will get to it first.
3631 * So use another lock to provide fairness.
3633 qemu_mutex_lock(&qemu_fair_mutex
);
3634 qemu_mutex_unlock(&qemu_fair_mutex
);
3636 qemu_mutex_lock(&qemu_global_mutex
);
3640 qemu_cond_signal(&qemu_pause_cond
);
3644 static int qemu_cpu_exec(CPUState
*env
);
3646 static void *kvm_cpu_thread_fn(void *arg
)
3648 CPUState
*env
= arg
;
3651 qemu_thread_self(env
->thread
);
3655 /* signal CPU creation */
3656 qemu_mutex_lock(&qemu_global_mutex
);
3658 qemu_cond_signal(&qemu_cpu_cond
);
3660 /* and wait for machine initialization */
3661 while (!qemu_system_ready
)
3662 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3665 if (cpu_can_run(env
))
3667 qemu_wait_io_event(env
);
3673 static void tcg_cpu_exec(void);
3675 static void *tcg_cpu_thread_fn(void *arg
)
3677 CPUState
*env
= arg
;
3680 qemu_thread_self(env
->thread
);
3682 /* signal CPU creation */
3683 qemu_mutex_lock(&qemu_global_mutex
);
3684 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
3686 qemu_cond_signal(&qemu_cpu_cond
);
3688 /* and wait for machine initialization */
3689 while (!qemu_system_ready
)
3690 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3694 qemu_wait_io_event(cur_cpu
);
3700 void qemu_cpu_kick(void *_env
)
3702 CPUState
*env
= _env
;
3703 qemu_cond_broadcast(env
->halt_cond
);
3705 qemu_thread_signal(env
->thread
, SIGUSR1
);
3708 int qemu_cpu_self(void *_env
)
3710 CPUState
*env
= _env
;
3713 qemu_thread_self(&this);
3715 return qemu_thread_equal(&this, env
->thread
);
3718 static void cpu_signal(int sig
)
3721 cpu_exit(cpu_single_env
);
3724 static void block_io_signals(void)
3727 struct sigaction sigact
;
3730 sigaddset(&set
, SIGUSR2
);
3731 sigaddset(&set
, SIGIO
);
3732 sigaddset(&set
, SIGALRM
);
3733 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3736 sigaddset(&set
, SIGUSR1
);
3737 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3739 memset(&sigact
, 0, sizeof(sigact
));
3740 sigact
.sa_handler
= cpu_signal
;
3741 sigaction(SIGUSR1
, &sigact
, NULL
);
3744 static void unblock_io_signals(void)
3749 sigaddset(&set
, SIGUSR2
);
3750 sigaddset(&set
, SIGIO
);
3751 sigaddset(&set
, SIGALRM
);
3752 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3755 sigaddset(&set
, SIGUSR1
);
3756 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3759 static void qemu_signal_lock(unsigned int msecs
)
3761 qemu_mutex_lock(&qemu_fair_mutex
);
3763 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
3764 qemu_thread_signal(tcg_cpu_thread
, SIGUSR1
);
3765 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
3768 qemu_mutex_unlock(&qemu_fair_mutex
);
3771 void qemu_mutex_lock_iothread(void)
3773 if (kvm_enabled()) {
3774 qemu_mutex_lock(&qemu_fair_mutex
);
3775 qemu_mutex_lock(&qemu_global_mutex
);
3776 qemu_mutex_unlock(&qemu_fair_mutex
);
3778 qemu_signal_lock(100);
3781 void qemu_mutex_unlock_iothread(void)
3783 qemu_mutex_unlock(&qemu_global_mutex
);
3786 static int all_vcpus_paused(void)
3788 CPUState
*penv
= first_cpu
;
3793 penv
= (CPUState
*)penv
->next_cpu
;
3799 static void pause_all_vcpus(void)
3801 CPUState
*penv
= first_cpu
;
3805 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3806 qemu_cpu_kick(penv
);
3807 penv
= (CPUState
*)penv
->next_cpu
;
3810 while (!all_vcpus_paused()) {
3811 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
3814 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3815 penv
= (CPUState
*)penv
->next_cpu
;
3820 static void resume_all_vcpus(void)
3822 CPUState
*penv
= first_cpu
;
3827 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3828 qemu_cpu_kick(penv
);
3829 penv
= (CPUState
*)penv
->next_cpu
;
3833 static void tcg_init_vcpu(void *_env
)
3835 CPUState
*env
= _env
;
3836 /* share a single thread for all cpus with TCG */
3837 if (!tcg_cpu_thread
) {
3838 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3839 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3840 qemu_cond_init(env
->halt_cond
);
3841 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
3842 while (env
->created
== 0)
3843 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3844 tcg_cpu_thread
= env
->thread
;
3845 tcg_halt_cond
= env
->halt_cond
;
3847 env
->thread
= tcg_cpu_thread
;
3848 env
->halt_cond
= tcg_halt_cond
;
3852 static void kvm_start_vcpu(CPUState
*env
)
3854 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3855 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3856 qemu_cond_init(env
->halt_cond
);
3857 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
3858 while (env
->created
== 0)
3859 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3862 void qemu_init_vcpu(void *_env
)
3864 CPUState
*env
= _env
;
3867 kvm_start_vcpu(env
);
3870 env
->nr_cores
= smp_cores
;
3871 env
->nr_threads
= smp_threads
;
3874 void qemu_notify_event(void)
3876 qemu_event_increment();
3879 void vm_stop(int reason
)
3882 qemu_thread_self(&me
);
3884 if (!qemu_thread_equal(&me
, &io_thread
)) {
3885 qemu_system_vmstop_request(reason
);
3887 * FIXME: should not return to device code in case
3888 * vm_stop() has been requested.
3890 if (cpu_single_env
) {
3891 cpu_exit(cpu_single_env
);
3892 cpu_single_env
->stop
= 1;
3903 static void host_main_loop_wait(int *timeout
)
3909 /* XXX: need to suppress polling by better using win32 events */
3911 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
3912 ret
|= pe
->func(pe
->opaque
);
3916 WaitObjects
*w
= &wait_objects
;
3918 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
3919 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
3920 if (w
->func
[ret
- WAIT_OBJECT_0
])
3921 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
3923 /* Check for additional signaled events */
3924 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
3926 /* Check if event is signaled */
3927 ret2
= WaitForSingleObject(w
->events
[i
], 0);
3928 if(ret2
== WAIT_OBJECT_0
) {
3930 w
->func
[i
](w
->opaque
[i
]);
3931 } else if (ret2
== WAIT_TIMEOUT
) {
3933 err
= GetLastError();
3934 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
3937 } else if (ret
== WAIT_TIMEOUT
) {
3939 err
= GetLastError();
3940 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
3947 static void host_main_loop_wait(int *timeout
)
3952 void main_loop_wait(int timeout
)
3954 IOHandlerRecord
*ioh
;
3955 fd_set rfds
, wfds
, xfds
;
3959 qemu_bh_update_timeout(&timeout
);
3961 host_main_loop_wait(&timeout
);
3963 /* poll any events */
3964 /* XXX: separate device handlers from system ones */
3969 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3973 (!ioh
->fd_read_poll
||
3974 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
3975 FD_SET(ioh
->fd
, &rfds
);
3979 if (ioh
->fd_write
) {
3980 FD_SET(ioh
->fd
, &wfds
);
3986 tv
.tv_sec
= timeout
/ 1000;
3987 tv
.tv_usec
= (timeout
% 1000) * 1000;
3989 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
3991 qemu_mutex_unlock_iothread();
3992 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
3993 qemu_mutex_lock_iothread();
3995 IOHandlerRecord
**pioh
;
3997 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3998 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
3999 ioh
->fd_read(ioh
->opaque
);
4000 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
4001 FD_CLR(ioh
->fd
, &rfds
);
4003 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
4004 ioh
->fd_write(ioh
->opaque
);
4008 /* remove deleted IO handlers */
4009 pioh
= &first_io_handler
;
4020 slirp_select_poll(&rfds
, &wfds
, &xfds
, (ret
< 0));
4022 /* rearm timer, if not periodic */
4023 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
4024 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
4025 qemu_rearm_alarm_timer(alarm_timer
);
4028 /* vm time timers */
4030 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
4031 qemu_run_timers(&active_timers
[QEMU_CLOCK_VIRTUAL
],
4032 qemu_get_clock(vm_clock
));
4035 /* real time timers */
4036 qemu_run_timers(&active_timers
[QEMU_CLOCK_REALTIME
],
4037 qemu_get_clock(rt_clock
));
4039 qemu_run_timers(&active_timers
[QEMU_CLOCK_HOST
],
4040 qemu_get_clock(host_clock
));
4042 /* Check bottom-halves last in case any of the earlier events triggered
4048 static int qemu_cpu_exec(CPUState
*env
)
4051 #ifdef CONFIG_PROFILER
4055 #ifdef CONFIG_PROFILER
4056 ti
= profile_getclock();
4061 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
4062 env
->icount_decr
.u16
.low
= 0;
4063 env
->icount_extra
= 0;
4064 count
= qemu_next_deadline();
4065 count
= (count
+ (1 << icount_time_shift
) - 1)
4066 >> icount_time_shift
;
4067 qemu_icount
+= count
;
4068 decr
= (count
> 0xffff) ? 0xffff : count
;
4070 env
->icount_decr
.u16
.low
= decr
;
4071 env
->icount_extra
= count
;
4073 ret
= cpu_exec(env
);
4074 #ifdef CONFIG_PROFILER
4075 qemu_time
+= profile_getclock() - ti
;
4078 /* Fold pending instructions back into the
4079 instruction counter, and clear the interrupt flag. */
4080 qemu_icount
-= (env
->icount_decr
.u16
.low
4081 + env
->icount_extra
);
4082 env
->icount_decr
.u32
= 0;
4083 env
->icount_extra
= 0;
4088 static void tcg_cpu_exec(void)
4092 if (next_cpu
== NULL
)
4093 next_cpu
= first_cpu
;
4094 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
4095 CPUState
*env
= cur_cpu
= next_cpu
;
4099 if (timer_alarm_pending
) {
4100 timer_alarm_pending
= 0;
4103 if (cpu_can_run(env
))
4104 ret
= qemu_cpu_exec(env
);
4105 if (ret
== EXCP_DEBUG
) {
4106 gdb_set_stop_cpu(env
);
4107 debug_requested
= 1;
4113 static int cpu_has_work(CPUState
*env
)
4121 if (qemu_cpu_has_work(env
))
4126 static int tcg_has_work(void)
4130 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4131 if (cpu_has_work(env
))
4136 static int qemu_calculate_timeout(void)
4138 #ifndef CONFIG_IOTHREAD
4143 else if (tcg_has_work())
4145 else if (!use_icount
)
4148 /* XXX: use timeout computed from timers */
4151 /* Advance virtual time to the next event. */
4152 if (use_icount
== 1) {
4153 /* When not using an adaptive execution frequency
4154 we tend to get badly out of sync with real time,
4155 so just delay for a reasonable amount of time. */
4158 delta
= cpu_get_icount() - cpu_get_clock();
4161 /* If virtual time is ahead of real time then just
4163 timeout
= (delta
/ 1000000) + 1;
4165 /* Wait for either IO to occur or the next
4167 add
= qemu_next_deadline();
4168 /* We advance the timer before checking for IO.
4169 Limit the amount we advance so that early IO
4170 activity won't get the guest too far ahead. */
4174 add
= (add
+ (1 << icount_time_shift
) - 1)
4175 >> icount_time_shift
;
4177 timeout
= delta
/ 1000000;
4184 #else /* CONFIG_IOTHREAD */
4189 static int vm_can_run(void)
4191 if (powerdown_requested
)
4193 if (reset_requested
)
4195 if (shutdown_requested
)
4197 if (debug_requested
)
4202 qemu_irq qemu_system_powerdown
;
4204 static void main_loop(void)
4208 if (kvm_enabled()) {
4210 cpu_disable_ticks();
4214 #ifdef CONFIG_IOTHREAD
4215 qemu_system_ready
= 1;
4216 qemu_cond_broadcast(&qemu_system_cond
);
4221 #ifdef CONFIG_PROFILER
4224 #ifndef CONFIG_IOTHREAD
4227 #ifdef CONFIG_PROFILER
4228 ti
= profile_getclock();
4230 main_loop_wait(qemu_calculate_timeout());
4231 #ifdef CONFIG_PROFILER
4232 dev_time
+= profile_getclock() - ti
;
4234 } while (vm_can_run());
4236 if (qemu_debug_requested()) {
4237 monitor_protocol_event(QEVENT_DEBUG
, NULL
);
4238 vm_stop(EXCP_DEBUG
);
4240 if (qemu_shutdown_requested()) {
4241 monitor_protocol_event(QEVENT_SHUTDOWN
, NULL
);
4248 if (qemu_reset_requested()) {
4249 monitor_protocol_event(QEVENT_RESET
, NULL
);
4251 qemu_system_reset();
4254 if (qemu_powerdown_requested()) {
4255 monitor_protocol_event(QEVENT_POWERDOWN
, NULL
);
4256 qemu_irq_raise(qemu_system_powerdown
);
4258 if ((r
= qemu_vmstop_requested())) {
4259 monitor_protocol_event(QEVENT_STOP
, NULL
);
4266 static void version(void)
4268 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4271 static void help(int exitcode
)
4274 printf("usage: %s [options] [disk_image]\n"
4276 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4278 #define DEF(option, opt_arg, opt_enum, opt_help) \
4280 #define DEFHEADING(text) stringify(text) "\n"
4281 #include "qemu-options.h"
4286 "During emulation, the following keys are useful:\n"
4287 "ctrl-alt-f toggle full screen\n"
4288 "ctrl-alt-n switch to virtual console 'n'\n"
4289 "ctrl-alt toggle mouse and keyboard grab\n"
4291 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4296 DEFAULT_NETWORK_SCRIPT
,
4297 DEFAULT_NETWORK_DOWN_SCRIPT
,
4299 DEFAULT_GDBSTUB_PORT
,
4304 #define HAS_ARG 0x0001
4307 #define DEF(option, opt_arg, opt_enum, opt_help) \
4309 #define DEFHEADING(text)
4310 #include "qemu-options.h"
4316 typedef struct QEMUOption
{
4322 static const QEMUOption qemu_options
[] = {
4323 { "h", 0, QEMU_OPTION_h
},
4324 #define DEF(option, opt_arg, opt_enum, opt_help) \
4325 { option, opt_arg, opt_enum },
4326 #define DEFHEADING(text)
4327 #include "qemu-options.h"
4335 struct soundhw soundhw
[] = {
4336 #ifdef HAS_AUDIO_CHOICE
4337 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4343 { .init_isa
= pcspk_audio_init
}
4350 "Creative Sound Blaster 16",
4353 { .init_isa
= SB16_init
}
4357 #ifdef CONFIG_CS4231A
4363 { .init_isa
= cs4231a_init
}
4371 "Yamaha YMF262 (OPL3)",
4373 "Yamaha YM3812 (OPL2)",
4377 { .init_isa
= Adlib_init
}
4384 "Gravis Ultrasound GF1",
4387 { .init_isa
= GUS_init
}
4394 "Intel 82801AA AC97 Audio",
4397 { .init_pci
= ac97_init
}
4401 #ifdef CONFIG_ES1370
4404 "ENSONIQ AudioPCI ES1370",
4407 { .init_pci
= es1370_init
}
4411 #endif /* HAS_AUDIO_CHOICE */
4413 { NULL
, NULL
, 0, 0, { NULL
} }
4416 static void select_soundhw (const char *optarg
)
4420 if (*optarg
== '?') {
4423 printf ("Valid sound card names (comma separated):\n");
4424 for (c
= soundhw
; c
->name
; ++c
) {
4425 printf ("%-11s %s\n", c
->name
, c
->descr
);
4427 printf ("\n-soundhw all will enable all of the above\n");
4428 exit (*optarg
!= '?');
4436 if (!strcmp (optarg
, "all")) {
4437 for (c
= soundhw
; c
->name
; ++c
) {
4445 e
= strchr (p
, ',');
4446 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4448 for (c
= soundhw
; c
->name
; ++c
) {
4449 if (!strncmp (c
->name
, p
, l
) && !c
->name
[l
]) {
4458 "Unknown sound card name (too big to show)\n");
4461 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4466 p
+= l
+ (e
!= NULL
);
4470 goto show_valid_cards
;
4475 static void select_vgahw (const char *p
)
4480 vga_interface_type
= VGA_NONE
;
4481 if (strstart(p
, "std", &opts
)) {
4482 vga_interface_type
= VGA_STD
;
4483 } else if (strstart(p
, "cirrus", &opts
)) {
4484 vga_interface_type
= VGA_CIRRUS
;
4485 } else if (strstart(p
, "vmware", &opts
)) {
4486 vga_interface_type
= VGA_VMWARE
;
4487 } else if (strstart(p
, "xenfb", &opts
)) {
4488 vga_interface_type
= VGA_XENFB
;
4489 } else if (!strstart(p
, "none", &opts
)) {
4491 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4495 const char *nextopt
;
4497 if (strstart(opts
, ",retrace=", &nextopt
)) {
4499 if (strstart(opts
, "dumb", &nextopt
))
4500 vga_retrace_method
= VGA_RETRACE_DUMB
;
4501 else if (strstart(opts
, "precise", &nextopt
))
4502 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4503 else goto invalid_vga
;
4504 } else goto invalid_vga
;
4510 static int balloon_parse(const char *arg
)
4514 if (strcmp(arg
, "none") == 0) {
4518 if (!strncmp(arg
, "virtio", 6)) {
4519 if (arg
[6] == ',') {
4520 /* have params -> parse them */
4521 opts
= qemu_opts_parse(&qemu_device_opts
, arg
+7, NULL
);
4525 /* create empty opts */
4526 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4528 qemu_opt_set(opts
, "driver", "virtio-balloon-pci");
4537 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4539 exit(STATUS_CONTROL_C_EXIT
);
4544 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4548 if(strlen(str
) != 36)
4551 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4552 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4553 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4559 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4567 static void termsig_handler(int signal
)
4569 qemu_system_shutdown_request();
4572 static void sigchld_handler(int signal
)
4574 waitpid(-1, NULL
, WNOHANG
);
4577 static void sighandler_setup(void)
4579 struct sigaction act
;
4581 memset(&act
, 0, sizeof(act
));
4582 act
.sa_handler
= termsig_handler
;
4583 sigaction(SIGINT
, &act
, NULL
);
4584 sigaction(SIGHUP
, &act
, NULL
);
4585 sigaction(SIGTERM
, &act
, NULL
);
4587 act
.sa_handler
= sigchld_handler
;
4588 act
.sa_flags
= SA_NOCLDSTOP
;
4589 sigaction(SIGCHLD
, &act
, NULL
);
4595 /* Look for support files in the same directory as the executable. */
4596 static char *find_datadir(const char *argv0
)
4602 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
4609 while (p
!= buf
&& *p
!= '\\')
4612 if (access(buf
, R_OK
) == 0) {
4613 return qemu_strdup(buf
);
4619 /* Find a likely location for support files using the location of the binary.
4620 For installed binaries this will be "$bindir/../share/qemu". When
4621 running from the build tree this will be "$bindir/../pc-bios". */
4622 #define SHARE_SUFFIX "/share/qemu"
4623 #define BUILD_SUFFIX "/pc-bios"
4624 static char *find_datadir(const char *argv0
)
4632 #if defined(__linux__)
4635 len
= readlink("/proc/self/exe", buf
, sizeof(buf
) - 1);
4641 #elif defined(__FreeBSD__)
4644 len
= readlink("/proc/curproc/file", buf
, sizeof(buf
) - 1);
4651 /* If we don't have any way of figuring out the actual executable
4652 location then try argv[0]. */
4654 p
= realpath(argv0
, buf
);
4662 max_len
= strlen(dir
) +
4663 MAX(strlen(SHARE_SUFFIX
), strlen(BUILD_SUFFIX
)) + 1;
4664 res
= qemu_mallocz(max_len
);
4665 snprintf(res
, max_len
, "%s%s", dir
, SHARE_SUFFIX
);
4666 if (access(res
, R_OK
)) {
4667 snprintf(res
, max_len
, "%s%s", dir
, BUILD_SUFFIX
);
4668 if (access(res
, R_OK
)) {
4680 char *qemu_find_file(int type
, const char *name
)
4686 /* If name contains path separators then try it as a straight path. */
4687 if ((strchr(name
, '/') || strchr(name
, '\\'))
4688 && access(name
, R_OK
) == 0) {
4689 return qemu_strdup(name
);
4692 case QEMU_FILE_TYPE_BIOS
:
4695 case QEMU_FILE_TYPE_KEYMAP
:
4696 subdir
= "keymaps/";
4701 len
= strlen(data_dir
) + strlen(name
) + strlen(subdir
) + 2;
4702 buf
= qemu_mallocz(len
);
4703 snprintf(buf
, len
, "%s/%s%s", data_dir
, subdir
, name
);
4704 if (access(buf
, R_OK
)) {
4711 static int device_init_func(QemuOpts
*opts
, void *opaque
)
4715 dev
= qdev_device_add(opts
);
4721 static int chardev_init_func(QemuOpts
*opts
, void *opaque
)
4723 CharDriverState
*chr
;
4725 chr
= qemu_chr_open_opts(opts
, NULL
);
4731 static int mon_init_func(QemuOpts
*opts
, void *opaque
)
4733 CharDriverState
*chr
;
4734 const char *chardev
;
4738 mode
= qemu_opt_get(opts
, "mode");
4742 if (strcmp(mode
, "readline") == 0) {
4743 flags
= MONITOR_USE_READLINE
;
4744 } else if (strcmp(mode
, "control") == 0) {
4745 flags
= MONITOR_USE_CONTROL
;
4747 fprintf(stderr
, "unknown monitor mode \"%s\"\n", mode
);
4751 if (qemu_opt_get_bool(opts
, "default", 0))
4752 flags
|= MONITOR_IS_DEFAULT
;
4754 chardev
= qemu_opt_get(opts
, "chardev");
4755 chr
= qemu_chr_find(chardev
);
4757 fprintf(stderr
, "chardev \"%s\" not found\n", chardev
);
4761 monitor_init(chr
, flags
);
4765 static void monitor_parse(const char *optarg
, const char *mode
)
4767 static int monitor_device_index
= 0;
4773 if (strstart(optarg
, "chardev:", &p
)) {
4774 snprintf(label
, sizeof(label
), "%s", p
);
4776 if (monitor_device_index
) {
4777 snprintf(label
, sizeof(label
), "monitor%d",
4778 monitor_device_index
);
4780 snprintf(label
, sizeof(label
), "monitor");
4783 opts
= qemu_chr_parse_compat(label
, optarg
);
4785 fprintf(stderr
, "parse error: %s\n", optarg
);
4790 opts
= qemu_opts_create(&qemu_mon_opts
, label
, 1);
4792 fprintf(stderr
, "duplicate chardev: %s\n", label
);
4795 qemu_opt_set(opts
, "mode", mode
);
4796 qemu_opt_set(opts
, "chardev", label
);
4798 qemu_opt_set(opts
, "default", "on");
4799 monitor_device_index
++;
4802 struct device_config
{
4804 DEV_USB
, /* -usbdevice */
4806 DEV_SERIAL
, /* -serial */
4807 DEV_PARALLEL
, /* -parallel */
4808 DEV_VIRTCON
, /* -virtioconsole */
4809 DEV_DEBUGCON
, /* -debugcon */
4811 const char *cmdline
;
4812 QTAILQ_ENTRY(device_config
) next
;
4814 QTAILQ_HEAD(, device_config
) device_configs
= QTAILQ_HEAD_INITIALIZER(device_configs
);
4816 static void add_device_config(int type
, const char *cmdline
)
4818 struct device_config
*conf
;
4820 conf
= qemu_mallocz(sizeof(*conf
));
4822 conf
->cmdline
= cmdline
;
4823 QTAILQ_INSERT_TAIL(&device_configs
, conf
, next
);
4826 static int foreach_device_config(int type
, int (*func
)(const char *cmdline
))
4828 struct device_config
*conf
;
4831 QTAILQ_FOREACH(conf
, &device_configs
, next
) {
4832 if (conf
->type
!= type
)
4834 rc
= func(conf
->cmdline
);
4841 static int serial_parse(const char *devname
)
4843 static int index
= 0;
4846 if (strcmp(devname
, "none") == 0)
4848 if (index
== MAX_SERIAL_PORTS
) {
4849 fprintf(stderr
, "qemu: too many serial ports\n");
4852 snprintf(label
, sizeof(label
), "serial%d", index
);
4853 serial_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4854 if (!serial_hds
[index
]) {
4855 fprintf(stderr
, "qemu: could not open serial device '%s': %s\n",
4856 devname
, strerror(errno
));
4863 static int parallel_parse(const char *devname
)
4865 static int index
= 0;
4868 if (strcmp(devname
, "none") == 0)
4870 if (index
== MAX_PARALLEL_PORTS
) {
4871 fprintf(stderr
, "qemu: too many parallel ports\n");
4874 snprintf(label
, sizeof(label
), "parallel%d", index
);
4875 parallel_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4876 if (!parallel_hds
[index
]) {
4877 fprintf(stderr
, "qemu: could not open parallel device '%s': %s\n",
4878 devname
, strerror(errno
));
4885 static int virtcon_parse(const char *devname
)
4887 static int index
= 0;
4890 if (strcmp(devname
, "none") == 0)
4892 if (index
== MAX_VIRTIO_CONSOLES
) {
4893 fprintf(stderr
, "qemu: too many virtio consoles\n");
4896 snprintf(label
, sizeof(label
), "virtcon%d", index
);
4897 virtcon_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4898 if (!virtcon_hds
[index
]) {
4899 fprintf(stderr
, "qemu: could not open virtio console '%s': %s\n",
4900 devname
, strerror(errno
));
4907 static int debugcon_parse(const char *devname
)
4911 if (!qemu_chr_open("debugcon", devname
, NULL
)) {
4914 opts
= qemu_opts_create(&qemu_device_opts
, "debugcon", 1);
4916 fprintf(stderr
, "qemu: already have a debugcon device\n");
4919 qemu_opt_set(opts
, "driver", "isa-debugcon");
4920 qemu_opt_set(opts
, "chardev", "debugcon");
4924 int main(int argc
, char **argv
, char **envp
)
4926 const char *gdbstub_dev
= NULL
;
4927 uint32_t boot_devices_bitmap
= 0;
4929 int snapshot
, linux_boot
, net_boot
;
4930 const char *initrd_filename
;
4931 const char *kernel_filename
, *kernel_cmdline
;
4932 char boot_devices
[33] = "cad"; /* default to HD->floppy->CD-ROM */
4934 DisplayChangeListener
*dcl
;
4935 int cyls
, heads
, secs
, translation
;
4936 QemuOpts
*hda_opts
= NULL
, *opts
;
4938 const char *r
, *optarg
;
4939 const char *loadvm
= NULL
;
4940 QEMUMachine
*machine
;
4941 const char *cpu_model
;
4946 const char *pid_file
= NULL
;
4947 const char *incoming
= NULL
;
4950 struct passwd
*pwd
= NULL
;
4951 const char *chroot_dir
= NULL
;
4952 const char *run_as
= NULL
;
4955 int show_vnc_port
= 0;
4959 qemu_errors_to_file(stderr
);
4960 qemu_cache_utils_init(envp
);
4962 QLIST_INIT (&vm_change_state_head
);
4965 struct sigaction act
;
4966 sigfillset(&act
.sa_mask
);
4968 act
.sa_handler
= SIG_IGN
;
4969 sigaction(SIGPIPE
, &act
, NULL
);
4972 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4973 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4974 QEMU to run on a single CPU */
4979 h
= GetCurrentProcess();
4980 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4981 for(i
= 0; i
< 32; i
++) {
4982 if (mask
& (1 << i
))
4987 SetProcessAffinityMask(h
, mask
);
4993 module_call_init(MODULE_INIT_MACHINE
);
4994 machine
= find_default_machine();
4996 initrd_filename
= NULL
;
4999 kernel_filename
= NULL
;
5000 kernel_cmdline
= "";
5001 cyls
= heads
= secs
= 0;
5002 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5004 for (i
= 0; i
< MAX_NODES
; i
++) {
5006 node_cpumask
[i
] = 0;
5009 assigned_devices_index
= 0;
5023 hda_opts
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
5025 const QEMUOption
*popt
;
5028 /* Treat --foo the same as -foo. */
5031 popt
= qemu_options
;
5034 fprintf(stderr
, "%s: invalid option -- '%s'\n",
5038 if (!strcmp(popt
->name
, r
+ 1))
5042 if (popt
->flags
& HAS_ARG
) {
5043 if (optind
>= argc
) {
5044 fprintf(stderr
, "%s: option '%s' requires an argument\n",
5048 optarg
= argv
[optind
++];
5053 switch(popt
->index
) {
5055 machine
= find_machine(optarg
);
5058 printf("Supported machines are:\n");
5059 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5061 printf("%-10s %s (alias of %s)\n",
5062 m
->alias
, m
->desc
, m
->name
);
5063 printf("%-10s %s%s\n",
5065 m
->is_default
? " (default)" : "");
5067 exit(*optarg
!= '?');
5070 case QEMU_OPTION_cpu
:
5071 /* hw initialization will check this */
5072 if (*optarg
== '?') {
5073 /* XXX: implement xxx_cpu_list for targets that still miss it */
5074 #if defined(cpu_list)
5075 cpu_list(stdout
, &fprintf
);
5082 case QEMU_OPTION_initrd
:
5083 initrd_filename
= optarg
;
5085 case QEMU_OPTION_hda
:
5087 hda_opts
= drive_add(optarg
, HD_ALIAS
, 0);
5089 hda_opts
= drive_add(optarg
, HD_ALIAS
5090 ",cyls=%d,heads=%d,secs=%d%s",
5091 0, cyls
, heads
, secs
,
5092 translation
== BIOS_ATA_TRANSLATION_LBA
?
5094 translation
== BIOS_ATA_TRANSLATION_NONE
?
5095 ",trans=none" : "");
5097 case QEMU_OPTION_hdb
:
5098 case QEMU_OPTION_hdc
:
5099 case QEMU_OPTION_hdd
:
5100 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
5102 case QEMU_OPTION_drive
:
5103 drive_add(NULL
, "%s", optarg
);
5105 case QEMU_OPTION_set
:
5106 if (qemu_set_option(optarg
) != 0)
5109 case QEMU_OPTION_global
:
5110 if (qemu_global_option(optarg
) != 0)
5113 case QEMU_OPTION_mtdblock
:
5114 drive_add(optarg
, MTD_ALIAS
);
5116 case QEMU_OPTION_sd
:
5117 drive_add(optarg
, SD_ALIAS
);
5119 case QEMU_OPTION_pflash
:
5120 drive_add(optarg
, PFLASH_ALIAS
);
5122 case QEMU_OPTION_snapshot
:
5125 case QEMU_OPTION_hdachs
:
5129 cyls
= strtol(p
, (char **)&p
, 0);
5130 if (cyls
< 1 || cyls
> 16383)
5135 heads
= strtol(p
, (char **)&p
, 0);
5136 if (heads
< 1 || heads
> 16)
5141 secs
= strtol(p
, (char **)&p
, 0);
5142 if (secs
< 1 || secs
> 63)
5146 if (!strcmp(p
, "none"))
5147 translation
= BIOS_ATA_TRANSLATION_NONE
;
5148 else if (!strcmp(p
, "lba"))
5149 translation
= BIOS_ATA_TRANSLATION_LBA
;
5150 else if (!strcmp(p
, "auto"))
5151 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5154 } else if (*p
!= '\0') {
5156 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5159 if (hda_opts
!= NULL
) {
5161 snprintf(num
, sizeof(num
), "%d", cyls
);
5162 qemu_opt_set(hda_opts
, "cyls", num
);
5163 snprintf(num
, sizeof(num
), "%d", heads
);
5164 qemu_opt_set(hda_opts
, "heads", num
);
5165 snprintf(num
, sizeof(num
), "%d", secs
);
5166 qemu_opt_set(hda_opts
, "secs", num
);
5167 if (translation
== BIOS_ATA_TRANSLATION_LBA
)
5168 qemu_opt_set(hda_opts
, "trans", "lba");
5169 if (translation
== BIOS_ATA_TRANSLATION_NONE
)
5170 qemu_opt_set(hda_opts
, "trans", "none");
5174 case QEMU_OPTION_numa
:
5175 if (nb_numa_nodes
>= MAX_NODES
) {
5176 fprintf(stderr
, "qemu: too many NUMA nodes\n");
5181 case QEMU_OPTION_nographic
:
5182 display_type
= DT_NOGRAPHIC
;
5184 #ifdef CONFIG_CURSES
5185 case QEMU_OPTION_curses
:
5186 display_type
= DT_CURSES
;
5189 case QEMU_OPTION_portrait
:
5192 case QEMU_OPTION_kernel
:
5193 kernel_filename
= optarg
;
5195 case QEMU_OPTION_append
:
5196 kernel_cmdline
= optarg
;
5198 case QEMU_OPTION_cdrom
:
5199 drive_add(optarg
, CDROM_ALIAS
);
5201 case QEMU_OPTION_boot
:
5203 static const char * const params
[] = {
5204 "order", "once", "menu", NULL
5206 char buf
[sizeof(boot_devices
)];
5207 char *standard_boot_devices
;
5210 if (!strchr(optarg
, '=')) {
5212 pstrcpy(buf
, sizeof(buf
), optarg
);
5213 } else if (check_params(buf
, sizeof(buf
), params
, optarg
) < 0) {
5215 "qemu: unknown boot parameter '%s' in '%s'\n",
5221 get_param_value(buf
, sizeof(buf
), "order", optarg
)) {
5222 boot_devices_bitmap
= parse_bootdevices(buf
);
5223 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5226 if (get_param_value(buf
, sizeof(buf
),
5228 boot_devices_bitmap
|= parse_bootdevices(buf
);
5229 standard_boot_devices
= qemu_strdup(boot_devices
);
5230 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5231 qemu_register_reset(restore_boot_devices
,
5232 standard_boot_devices
);
5234 if (get_param_value(buf
, sizeof(buf
),
5236 if (!strcmp(buf
, "on")) {
5238 } else if (!strcmp(buf
, "off")) {
5242 "qemu: invalid option value '%s'\n",
5250 case QEMU_OPTION_fda
:
5251 case QEMU_OPTION_fdb
:
5252 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
5255 case QEMU_OPTION_no_fd_bootchk
:
5259 case QEMU_OPTION_netdev
:
5260 if (net_client_parse(&qemu_netdev_opts
, optarg
) == -1) {
5264 case QEMU_OPTION_net
:
5265 if (net_client_parse(&qemu_net_opts
, optarg
) == -1) {
5270 case QEMU_OPTION_tftp
:
5271 legacy_tftp_prefix
= optarg
;
5273 case QEMU_OPTION_bootp
:
5274 legacy_bootp_filename
= optarg
;
5277 case QEMU_OPTION_smb
:
5278 if (net_slirp_smb(optarg
) < 0)
5282 case QEMU_OPTION_redir
:
5283 if (net_slirp_redir(optarg
) < 0)
5287 case QEMU_OPTION_bt
:
5288 add_device_config(DEV_BT
, optarg
);
5291 case QEMU_OPTION_audio_help
:
5295 case QEMU_OPTION_soundhw
:
5296 select_soundhw (optarg
);
5302 case QEMU_OPTION_version
:
5306 case QEMU_OPTION_m
: {
5310 value
= strtoul(optarg
, &ptr
, 10);
5312 case 0: case 'M': case 'm':
5319 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5323 /* On 32-bit hosts, QEMU is limited by virtual address space */
5324 if (value
> (2047 << 20) && HOST_LONG_BITS
== 32) {
5325 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5328 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5329 fprintf(stderr
, "qemu: ram size too large\n");
5338 const CPULogItem
*item
;
5340 mask
= cpu_str_to_log_mask(optarg
);
5342 printf("Log items (comma separated):\n");
5343 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5344 printf("%-10s %s\n", item
->name
, item
->help
);
5352 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5354 case QEMU_OPTION_gdb
:
5355 gdbstub_dev
= optarg
;
5360 case QEMU_OPTION_bios
:
5363 case QEMU_OPTION_singlestep
:
5370 keyboard_layout
= optarg
;
5372 case QEMU_OPTION_localtime
:
5375 case QEMU_OPTION_vga
:
5376 select_vgahw (optarg
);
5378 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5384 w
= strtol(p
, (char **)&p
, 10);
5387 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5393 h
= strtol(p
, (char **)&p
, 10);
5398 depth
= strtol(p
, (char **)&p
, 10);
5399 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5400 depth
!= 24 && depth
!= 32)
5402 } else if (*p
== '\0') {
5403 depth
= graphic_depth
;
5410 graphic_depth
= depth
;
5414 case QEMU_OPTION_echr
:
5417 term_escape_char
= strtol(optarg
, &r
, 0);
5419 printf("Bad argument to echr\n");
5422 case QEMU_OPTION_monitor
:
5423 monitor_parse(optarg
, "readline");
5424 default_monitor
= 0;
5426 case QEMU_OPTION_qmp
:
5427 monitor_parse(optarg
, "control");
5428 default_monitor
= 0;
5430 case QEMU_OPTION_mon
:
5431 opts
= qemu_opts_parse(&qemu_mon_opts
, optarg
, "chardev");
5433 fprintf(stderr
, "parse error: %s\n", optarg
);
5436 default_monitor
= 0;
5438 case QEMU_OPTION_chardev
:
5439 opts
= qemu_opts_parse(&qemu_chardev_opts
, optarg
, "backend");
5441 fprintf(stderr
, "parse error: %s\n", optarg
);
5445 case QEMU_OPTION_serial
:
5446 add_device_config(DEV_SERIAL
, optarg
);
5449 case QEMU_OPTION_watchdog
:
5452 "qemu: only one watchdog option may be given\n");
5457 case QEMU_OPTION_watchdog_action
:
5458 if (select_watchdog_action(optarg
) == -1) {
5459 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5463 case QEMU_OPTION_virtiocon
:
5464 add_device_config(DEV_VIRTCON
, optarg
);
5465 default_virtcon
= 0;
5467 case QEMU_OPTION_parallel
:
5468 add_device_config(DEV_PARALLEL
, optarg
);
5469 default_parallel
= 0;
5471 case QEMU_OPTION_debugcon
:
5472 add_device_config(DEV_DEBUGCON
, optarg
);
5474 case QEMU_OPTION_loadvm
:
5477 case QEMU_OPTION_full_screen
:
5481 case QEMU_OPTION_no_frame
:
5484 case QEMU_OPTION_alt_grab
:
5487 case QEMU_OPTION_ctrl_grab
:
5490 case QEMU_OPTION_no_quit
:
5493 case QEMU_OPTION_sdl
:
5494 display_type
= DT_SDL
;
5497 case QEMU_OPTION_pidfile
:
5501 case QEMU_OPTION_win2k_hack
:
5502 win2k_install_hack
= 1;
5504 case QEMU_OPTION_rtc_td_hack
:
5507 case QEMU_OPTION_acpitable
:
5508 if(acpi_table_add(optarg
) < 0) {
5509 fprintf(stderr
, "Wrong acpi table provided\n");
5513 case QEMU_OPTION_smbios
:
5514 if(smbios_entry_add(optarg
) < 0) {
5515 fprintf(stderr
, "Wrong smbios provided\n");
5522 case QEMU_OPTION_enable_kvm
:
5526 case QEMU_OPTION_no_kvm
:
5529 case QEMU_OPTION_no_kvm_irqchip
: {
5534 case QEMU_OPTION_no_kvm_pit
: {
5538 case QEMU_OPTION_no_kvm_pit_reinjection
: {
5539 kvm_pit_reinject
= 0;
5542 case QEMU_OPTION_enable_nesting
: {
5546 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5547 case QEMU_OPTION_pcidevice
:
5548 if (assigned_devices_index
>= MAX_DEV_ASSIGN_CMDLINE
) {
5549 fprintf(stderr
, "Too many assigned devices\n");
5552 assigned_devices
[assigned_devices_index
] = optarg
;
5553 assigned_devices_index
++;
5557 case QEMU_OPTION_usb
:
5560 case QEMU_OPTION_usbdevice
:
5562 add_device_config(DEV_USB
, optarg
);
5564 case QEMU_OPTION_device
:
5565 if (!qemu_opts_parse(&qemu_device_opts
, optarg
, "driver")) {
5569 case QEMU_OPTION_smp
:
5572 fprintf(stderr
, "Invalid number of CPUs\n");
5575 if (max_cpus
< smp_cpus
) {
5576 fprintf(stderr
, "maxcpus must be equal to or greater than "
5580 if (max_cpus
> 255) {
5581 fprintf(stderr
, "Unsupported number of maxcpus\n");
5585 case QEMU_OPTION_vnc
:
5586 display_type
= DT_VNC
;
5587 vnc_display
= optarg
;
5590 case QEMU_OPTION_no_acpi
:
5593 case QEMU_OPTION_no_hpet
:
5596 case QEMU_OPTION_balloon
:
5597 if (balloon_parse(optarg
) < 0) {
5598 fprintf(stderr
, "Unknown -balloon argument %s\n", optarg
);
5603 case QEMU_OPTION_no_reboot
:
5606 case QEMU_OPTION_no_shutdown
:
5609 case QEMU_OPTION_show_cursor
:
5612 case QEMU_OPTION_uuid
:
5613 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5614 fprintf(stderr
, "Fail to parse UUID string."
5615 " Wrong format.\n");
5620 case QEMU_OPTION_daemonize
:
5624 case QEMU_OPTION_option_rom
:
5625 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5626 fprintf(stderr
, "Too many option ROMs\n");
5629 option_rom
[nb_option_roms
] = optarg
;
5632 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5633 case QEMU_OPTION_semihosting
:
5634 semihosting_enabled
= 1;
5637 case QEMU_OPTION_tdf
:
5640 case QEMU_OPTION_kvm_shadow_memory
:
5641 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
5643 case QEMU_OPTION_mempath
:
5647 case QEMU_OPTION_mem_prealloc
:
5648 mem_prealloc
= !mem_prealloc
;
5651 case QEMU_OPTION_name
:
5652 qemu_name
= qemu_strdup(optarg
);
5654 char *p
= strchr(qemu_name
, ',');
5657 if (strncmp(p
, "process=", 8)) {
5658 fprintf(stderr
, "Unknown subargument %s to -name", p
);
5666 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5667 case QEMU_OPTION_prom_env
:
5668 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5669 fprintf(stderr
, "Too many prom variables\n");
5672 prom_envs
[nb_prom_envs
] = optarg
;
5677 case QEMU_OPTION_old_param
:
5681 case QEMU_OPTION_clock
:
5682 configure_alarms(optarg
);
5684 case QEMU_OPTION_startdate
:
5685 configure_rtc_date_offset(optarg
, 1);
5687 case QEMU_OPTION_rtc
:
5688 opts
= qemu_opts_parse(&qemu_rtc_opts
, optarg
, NULL
);
5690 fprintf(stderr
, "parse error: %s\n", optarg
);
5693 configure_rtc(opts
);
5695 case QEMU_OPTION_tb_size
:
5696 tb_size
= strtol(optarg
, NULL
, 0);
5700 case QEMU_OPTION_icount
:
5702 if (strcmp(optarg
, "auto") == 0) {
5703 icount_time_shift
= -1;
5705 icount_time_shift
= strtol(optarg
, NULL
, 0);
5708 case QEMU_OPTION_incoming
:
5711 case QEMU_OPTION_nodefaults
:
5713 default_parallel
= 0;
5714 default_virtcon
= 0;
5715 default_monitor
= 0;
5723 case QEMU_OPTION_chroot
:
5724 chroot_dir
= optarg
;
5726 case QEMU_OPTION_runas
:
5729 case QEMU_OPTION_nvram
:
5734 case QEMU_OPTION_xen_domid
:
5735 xen_domid
= atoi(optarg
);
5737 case QEMU_OPTION_xen_create
:
5738 xen_mode
= XEN_CREATE
;
5740 case QEMU_OPTION_xen_attach
:
5741 xen_mode
= XEN_ATTACH
;
5744 case QEMU_OPTION_readconfig
:
5747 fp
= fopen(optarg
, "r");
5749 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5752 if (qemu_config_parse(fp
) != 0) {
5758 case QEMU_OPTION_writeconfig
:
5761 if (strcmp(optarg
, "-") == 0) {
5764 fp
= fopen(optarg
, "w");
5766 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5770 qemu_config_write(fp
);
5778 /* If no data_dir is specified then try to find it relative to the
5781 data_dir
= find_datadir(argv
[0]);
5783 /* If all else fails use the install patch specified when building. */
5785 data_dir
= CONFIG_QEMU_SHAREDIR
;
5789 * Default to max_cpus = smp_cpus, in case the user doesn't
5790 * specify a max_cpus value.
5793 max_cpus
= smp_cpus
;
5795 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5796 if (smp_cpus
> machine
->max_cpus
) {
5797 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5798 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5803 qemu_opts_foreach(&qemu_device_opts
, default_driver_check
, NULL
, 0);
5804 qemu_opts_foreach(&qemu_global_opts
, default_driver_check
, NULL
, 0);
5806 if (machine
->no_serial
) {
5809 if (machine
->no_parallel
) {
5810 default_parallel
= 0;
5812 if (!machine
->use_virtcon
) {
5813 default_virtcon
= 0;
5815 if (machine
->no_vga
) {
5818 if (machine
->no_floppy
) {
5821 if (machine
->no_cdrom
) {
5824 if (machine
->no_sdcard
) {
5828 if (display_type
== DT_NOGRAPHIC
) {
5829 if (default_parallel
)
5830 add_device_config(DEV_PARALLEL
, "null");
5831 if (default_serial
&& default_monitor
) {
5832 add_device_config(DEV_SERIAL
, "mon:stdio");
5833 } else if (default_virtcon
&& default_monitor
) {
5834 add_device_config(DEV_VIRTCON
, "mon:stdio");
5837 add_device_config(DEV_SERIAL
, "stdio");
5838 if (default_virtcon
)
5839 add_device_config(DEV_VIRTCON
, "stdio");
5840 if (default_monitor
)
5841 monitor_parse("stdio", "readline");
5845 add_device_config(DEV_SERIAL
, "vc:80Cx24C");
5846 if (default_parallel
)
5847 add_device_config(DEV_PARALLEL
, "vc:80Cx24C");
5848 if (default_monitor
)
5849 monitor_parse("vc:80Cx24C", "readline");
5850 if (default_virtcon
)
5851 add_device_config(DEV_VIRTCON
, "vc:80Cx24C");
5854 vga_interface_type
= VGA_CIRRUS
;
5856 if (qemu_opts_foreach(&qemu_chardev_opts
, chardev_init_func
, NULL
, 1) != 0)
5863 if (pipe(fds
) == -1)
5874 len
= read(fds
[0], &status
, 1);
5875 if (len
== -1 && (errno
== EINTR
))
5880 else if (status
== 1) {
5881 fprintf(stderr
, "Could not acquire pidfile: %s\n", strerror(errno
));
5889 qemu_set_cloexec(fds
[1]);
5901 signal(SIGTSTP
, SIG_IGN
);
5902 signal(SIGTTOU
, SIG_IGN
);
5903 signal(SIGTTIN
, SIG_IGN
);
5907 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5911 write(fds
[1], &status
, 1);
5914 fprintf(stderr
, "Could not acquire pid file: %s\n", strerror(errno
));
5918 if (kvm_enabled()) {
5921 ret
= kvm_init(smp_cpus
);
5923 #if defined(KVM_UPSTREAM) || defined(CONFIG_NO_CPU_EMULATION)
5924 fprintf(stderr
, "failed to initialize KVM\n");
5927 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
5932 if (qemu_init_main_loop()) {
5933 fprintf(stderr
, "qemu_init_main_loop failed\n");
5936 linux_boot
= (kernel_filename
!= NULL
);
5938 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5939 fprintf(stderr
, "-append only allowed with -kernel option\n");
5943 if (!linux_boot
&& initrd_filename
!= NULL
) {
5944 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5949 /* Win32 doesn't support line-buffering and requires size >= 2 */
5950 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5953 if (init_timer_alarm() < 0) {
5954 fprintf(stderr
, "could not initialize alarm timer\n");
5957 if (use_icount
&& icount_time_shift
< 0) {
5959 /* 125MIPS seems a reasonable initial guess at the guest speed.
5960 It will be corrected fairly quickly anyway. */
5961 icount_time_shift
= 3;
5962 init_icount_adjust();
5969 if (net_init_clients() < 0) {
5973 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5974 net_set_boot_mask(net_boot
);
5976 /* init the bluetooth world */
5977 if (foreach_device_config(DEV_BT
, bt_parse
))
5980 /* init the memory */
5982 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5984 /* init the dynamic translator */
5985 cpu_exec_init_all(tb_size
* 1024 * 1024);
5987 bdrv_init_with_whitelist();
5991 if (default_cdrom
) {
5992 /* we always create the cdrom drive, even if no disk is there */
5993 drive_add(NULL
, CDROM_ALIAS
);
5996 if (default_floppy
) {
5997 /* we always create at least one floppy */
5998 drive_add(NULL
, FD_ALIAS
, 0);
6001 if (default_sdcard
) {
6002 /* we always create one sd slot, even if no card is in it */
6003 drive_add(NULL
, SD_ALIAS
);
6006 /* open the virtual block devices */
6008 qemu_opts_foreach(&qemu_drive_opts
, drive_enable_snapshot
, NULL
, 0);
6009 if (qemu_opts_foreach(&qemu_drive_opts
, drive_init_func
, machine
, 1) != 0)
6012 vmstate_register(0, &vmstate_timers
,&timers_state
);
6013 register_savevm_live("ram", 0, 3, NULL
, ram_save_live
, NULL
,
6016 if (nb_numa_nodes
> 0) {
6019 if (nb_numa_nodes
> smp_cpus
) {
6020 nb_numa_nodes
= smp_cpus
;
6023 /* If no memory size if given for any node, assume the default case
6024 * and distribute the available memory equally across all nodes
6026 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6027 if (node_mem
[i
] != 0)
6030 if (i
== nb_numa_nodes
) {
6031 uint64_t usedmem
= 0;
6033 /* On Linux, the each node's border has to be 8MB aligned,
6034 * the final node gets the rest.
6036 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
6037 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
6038 usedmem
+= node_mem
[i
];
6040 node_mem
[i
] = ram_size
- usedmem
;
6043 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6044 if (node_cpumask
[i
] != 0)
6047 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6048 * must cope with this anyway, because there are BIOSes out there in
6049 * real machines which also use this scheme.
6051 if (i
== nb_numa_nodes
) {
6052 for (i
= 0; i
< smp_cpus
; i
++) {
6053 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
6058 if (foreach_device_config(DEV_SERIAL
, serial_parse
) < 0)
6060 if (foreach_device_config(DEV_PARALLEL
, parallel_parse
) < 0)
6062 if (foreach_device_config(DEV_VIRTCON
, virtcon_parse
) < 0)
6064 if (foreach_device_config(DEV_DEBUGCON
, debugcon_parse
) < 0)
6067 module_call_init(MODULE_INIT_DEVICE
);
6070 i
= select_watchdog(watchdog
);
6072 exit (i
== 1 ? 1 : 0);
6075 if (machine
->compat_props
) {
6076 qdev_prop_register_global_list(machine
->compat_props
);
6080 machine
->init(ram_size
, boot_devices
,
6081 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
6085 /* must be after terminal init, SDL library changes signal handlers */
6089 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
6090 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6091 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
6097 current_machine
= machine
;
6099 /* init USB devices */
6101 if (foreach_device_config(DEV_USB
, usb_parse
) < 0)
6105 /* init generic devices */
6106 if (qemu_opts_foreach(&qemu_device_opts
, device_init_func
, NULL
, 1) != 0)
6110 dumb_display_init();
6111 /* just use the first displaystate for the moment */
6114 if (display_type
== DT_DEFAULT
) {
6115 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6116 display_type
= DT_SDL
;
6118 display_type
= DT_VNC
;
6119 vnc_display
= "localhost:0,to=99";
6125 switch (display_type
) {
6128 #if defined(CONFIG_CURSES)
6130 curses_display_init(ds
, full_screen
);
6133 #if defined(CONFIG_SDL)
6135 sdl_display_init(ds
, full_screen
, no_frame
);
6137 #elif defined(CONFIG_COCOA)
6139 cocoa_display_init(ds
, full_screen
);
6143 vnc_display_init(ds
);
6144 if (vnc_display_open(ds
, vnc_display
) < 0)
6147 if (show_vnc_port
) {
6148 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
6156 dcl
= ds
->listeners
;
6157 while (dcl
!= NULL
) {
6158 if (dcl
->dpy_refresh
!= NULL
) {
6159 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
6160 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
6165 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
6166 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
6167 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
6170 text_consoles_set_display(display_state
);
6172 if (qemu_opts_foreach(&qemu_mon_opts
, mon_init_func
, NULL
, 1) != 0)
6175 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
6176 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
6181 qdev_machine_creation_done();
6183 if (rom_load_all() != 0) {
6184 fprintf(stderr
, "rom loading failed\n");
6188 qemu_system_reset();
6190 if (load_vmstate(cur_mon
, loadvm
) < 0) {
6196 qemu_start_incoming_migration(incoming
);
6197 } else if (autostart
) {
6207 len
= write(fds
[1], &status
, 1);
6208 if (len
== -1 && (errno
== EINTR
))
6215 TFR(fd
= qemu_open("/dev/null", O_RDWR
));
6221 pwd
= getpwnam(run_as
);
6223 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
6229 if (chroot(chroot_dir
) < 0) {
6230 fprintf(stderr
, "chroot failed\n");
6237 if (setgid(pwd
->pw_gid
) < 0) {
6238 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
6241 if (setuid(pwd
->pw_uid
) < 0) {
6242 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
6245 if (setuid(0) != -1) {
6246 fprintf(stderr
, "Dropping privileges failed\n");