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"
163 #include "exec-all.h"
165 #include "qemu_socket.h"
167 #include "slirp/libslirp.h"
169 #include "qemu-queue.h"
172 //#define DEBUG_SLIRP
174 #define DEFAULT_RAM_SIZE 128
176 static const char *data_dir
;
177 const char *bios_name
= NULL
;
178 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
179 to store the VM snapshots */
180 struct drivelist drives
= QTAILQ_HEAD_INITIALIZER(drives
);
181 struct driveoptlist driveopts
= QTAILQ_HEAD_INITIALIZER(driveopts
);
182 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
183 static DisplayState
*display_state
;
184 DisplayType display_type
= DT_DEFAULT
;
185 const char* keyboard_layout
= NULL
;
188 NICInfo nd_table
[MAX_NICS
];
191 static int rtc_utc
= 1;
192 static int rtc_date_offset
= -1; /* -1 means no change */
193 QEMUClock
*rtc_clock
;
194 int vga_interface_type
= VGA_NONE
;
196 int graphic_width
= 1024;
197 int graphic_height
= 768;
198 int graphic_depth
= 8;
200 int graphic_width
= 800;
201 int graphic_height
= 600;
202 int graphic_depth
= 15;
204 static int full_screen
= 0;
206 static int no_frame
= 0;
209 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
210 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
211 CharDriverState
*virtcon_hds
[MAX_VIRTIO_CONSOLES
];
213 int win2k_install_hack
= 0;
222 const char *vnc_display
;
223 int acpi_enabled
= 1;
229 int graphic_rotate
= 0;
230 uint8_t irq0override
= 1;
234 const char *watchdog
;
235 const char *option_rom
[MAX_OPTION_ROMS
];
237 int semihosting_enabled
= 0;
241 const char *qemu_name
;
244 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
245 unsigned int nb_prom_envs
= 0;
246 const char *prom_envs
[MAX_PROM_ENVS
];
251 uint64_t node_mem
[MAX_NODES
];
252 uint64_t node_cpumask
[MAX_NODES
];
254 static CPUState
*cur_cpu
;
255 static CPUState
*next_cpu
;
256 static int timer_alarm_pending
= 1;
257 /* Conversion factor from emulated instructions to virtual clock ticks. */
258 static int icount_time_shift
;
259 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
260 #define MAX_ICOUNT_SHIFT 10
261 /* Compensate for varying guest execution speed. */
262 static int64_t qemu_icount_bias
;
263 static QEMUTimer
*icount_rt_timer
;
264 static QEMUTimer
*icount_vm_timer
;
265 static QEMUTimer
*nographic_timer
;
267 uint8_t qemu_uuid
[16];
269 static QEMUBootSetHandler
*boot_set_handler
;
270 static void *boot_set_opaque
;
272 static int default_serial
= 1;
273 static int default_parallel
= 1;
274 static int default_virtcon
= 1;
275 static int default_monitor
= 1;
276 static int default_vga
= 1;
277 static int default_floppy
= 1;
278 static int default_cdrom
= 1;
279 static int default_sdcard
= 1;
285 { .driver
= "isa-serial", .flag
= &default_serial
},
286 { .driver
= "isa-parallel", .flag
= &default_parallel
},
287 { .driver
= "isa-fdc", .flag
= &default_floppy
},
288 { .driver
= "ide-drive", .flag
= &default_cdrom
},
289 { .driver
= "virtio-console-pci", .flag
= &default_virtcon
},
290 { .driver
= "virtio-console-s390", .flag
= &default_virtcon
},
291 { .driver
= "VGA", .flag
= &default_vga
},
292 { .driver
= "cirrus-vga", .flag
= &default_vga
},
293 { .driver
= "vmware-svga", .flag
= &default_vga
},
296 static int default_driver_check(QemuOpts
*opts
, void *opaque
)
298 const char *driver
= qemu_opt_get(opts
, "driver");
303 for (i
= 0; i
< ARRAY_SIZE(default_list
); i
++) {
304 if (strcmp(default_list
[i
].driver
, driver
) != 0)
306 *(default_list
[i
].flag
) = 0;
311 /***********************************************************/
312 /* x86 ISA bus support */
314 target_phys_addr_t isa_mem_base
= 0;
317 /***********************************************************/
318 void hw_error(const char *fmt
, ...)
324 fprintf(stderr
, "qemu: hardware error: ");
325 vfprintf(stderr
, fmt
, ap
);
326 fprintf(stderr
, "\n");
327 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
328 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
330 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
332 cpu_dump_state(env
, stderr
, fprintf
, 0);
339 static void set_proc_name(const char *s
)
341 #if defined(__linux__) && defined(PR_SET_NAME)
345 name
[sizeof(name
) - 1] = 0;
346 strncpy(name
, s
, sizeof(name
));
347 /* Could rewrite argv[0] too, but that's a bit more complicated.
348 This simple way is enough for `top'. */
349 prctl(PR_SET_NAME
, name
);
356 static QEMUBalloonEvent
*qemu_balloon_event
;
357 void *qemu_balloon_event_opaque
;
359 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
361 qemu_balloon_event
= func
;
362 qemu_balloon_event_opaque
= opaque
;
365 void qemu_balloon(ram_addr_t target
)
367 if (qemu_balloon_event
)
368 qemu_balloon_event(qemu_balloon_event_opaque
, target
);
371 ram_addr_t
qemu_balloon_status(void)
373 if (qemu_balloon_event
)
374 return qemu_balloon_event(qemu_balloon_event_opaque
, 0);
378 /***********************************************************/
381 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
382 static void *qemu_put_kbd_event_opaque
;
383 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
384 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
386 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
388 qemu_put_kbd_event_opaque
= opaque
;
389 qemu_put_kbd_event
= func
;
392 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
393 void *opaque
, int absolute
,
396 QEMUPutMouseEntry
*s
, *cursor
;
398 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
400 s
->qemu_put_mouse_event
= func
;
401 s
->qemu_put_mouse_event_opaque
= opaque
;
402 s
->qemu_put_mouse_event_absolute
= absolute
;
403 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
406 if (!qemu_put_mouse_event_head
) {
407 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
411 cursor
= qemu_put_mouse_event_head
;
412 while (cursor
->next
!= NULL
)
413 cursor
= cursor
->next
;
416 qemu_put_mouse_event_current
= s
;
421 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
423 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
425 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
428 cursor
= qemu_put_mouse_event_head
;
429 while (cursor
!= NULL
&& cursor
!= entry
) {
431 cursor
= cursor
->next
;
434 if (cursor
== NULL
) // does not exist or list empty
436 else if (prev
== NULL
) { // entry is head
437 qemu_put_mouse_event_head
= cursor
->next
;
438 if (qemu_put_mouse_event_current
== entry
)
439 qemu_put_mouse_event_current
= cursor
->next
;
440 qemu_free(entry
->qemu_put_mouse_event_name
);
445 prev
->next
= entry
->next
;
447 if (qemu_put_mouse_event_current
== entry
)
448 qemu_put_mouse_event_current
= prev
;
450 qemu_free(entry
->qemu_put_mouse_event_name
);
454 void kbd_put_keycode(int keycode
)
456 if (qemu_put_kbd_event
) {
457 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
461 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
463 QEMUPutMouseEvent
*mouse_event
;
464 void *mouse_event_opaque
;
467 if (!qemu_put_mouse_event_current
) {
472 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
474 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
477 if (graphic_rotate
) {
478 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
481 width
= graphic_width
- 1;
482 mouse_event(mouse_event_opaque
,
483 width
- dy
, dx
, dz
, buttons_state
);
485 mouse_event(mouse_event_opaque
,
486 dx
, dy
, dz
, buttons_state
);
490 int kbd_mouse_is_absolute(void)
492 if (!qemu_put_mouse_event_current
)
495 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
498 static void info_mice_iter(QObject
*data
, void *opaque
)
501 Monitor
*mon
= opaque
;
503 mouse
= qobject_to_qdict(data
);
504 monitor_printf(mon
, "%c Mouse #%" PRId64
": %s\n",
505 (qdict_get_bool(mouse
, "current") ? '*' : ' '),
506 qdict_get_int(mouse
, "index"), qdict_get_str(mouse
, "name"));
509 void do_info_mice_print(Monitor
*mon
, const QObject
*data
)
513 mice_list
= qobject_to_qlist(data
);
514 if (qlist_empty(mice_list
)) {
515 monitor_printf(mon
, "No mouse devices connected\n");
519 qlist_iter(mice_list
, info_mice_iter
, mon
);
523 * do_info_mice(): Show VM mice information
525 * Each mouse is represented by a QDict, the returned QObject is a QList of
528 * The mouse QDict contains the following:
530 * - "name": mouse's name
531 * - "index": mouse's index
532 * - "current": true if this mouse is receiving events, false otherwise
536 * [ { "name": "QEMU Microsoft Mouse", "index": 0, "current": false },
537 * { "name": "QEMU PS/2 Mouse", "index": 1, "current": true } ]
539 void do_info_mice(Monitor
*mon
, QObject
**ret_data
)
541 QEMUPutMouseEntry
*cursor
;
545 mice_list
= qlist_new();
547 if (!qemu_put_mouse_event_head
) {
551 cursor
= qemu_put_mouse_event_head
;
552 while (cursor
!= NULL
) {
554 obj
= qobject_from_jsonf("{ 'name': %s, 'index': %d, 'current': %i }",
555 cursor
->qemu_put_mouse_event_name
,
556 index
, cursor
== qemu_put_mouse_event_current
);
557 qlist_append_obj(mice_list
, obj
);
559 cursor
= cursor
->next
;
563 *ret_data
= QOBJECT(mice_list
);
566 void do_mouse_set(Monitor
*mon
, const QDict
*qdict
)
568 QEMUPutMouseEntry
*cursor
;
570 int index
= qdict_get_int(qdict
, "index");
572 if (!qemu_put_mouse_event_head
) {
573 monitor_printf(mon
, "No mouse devices connected\n");
577 cursor
= qemu_put_mouse_event_head
;
578 while (cursor
!= NULL
&& index
!= i
) {
580 cursor
= cursor
->next
;
584 qemu_put_mouse_event_current
= cursor
;
586 monitor_printf(mon
, "Mouse at given index not found\n");
589 /* compute with 96 bit intermediate result: (a*b)/c */
590 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
595 #ifdef HOST_WORDS_BIGENDIAN
605 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
606 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
609 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
613 /***********************************************************/
614 /* real time host monotonic timer */
616 static int64_t get_clock_realtime(void)
620 gettimeofday(&tv
, NULL
);
621 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
626 static int64_t clock_freq
;
628 static void init_get_clock(void)
632 ret
= QueryPerformanceFrequency(&freq
);
634 fprintf(stderr
, "Could not calibrate ticks\n");
637 clock_freq
= freq
.QuadPart
;
640 static int64_t get_clock(void)
643 QueryPerformanceCounter(&ti
);
644 return muldiv64(ti
.QuadPart
, get_ticks_per_sec(), clock_freq
);
649 static int use_rt_clock
;
651 static void init_get_clock(void)
654 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
655 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
658 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
665 static int64_t get_clock(void)
667 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
668 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
671 clock_gettime(CLOCK_MONOTONIC
, &ts
);
672 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
676 /* XXX: using gettimeofday leads to problems if the date
677 changes, so it should be avoided. */
678 return get_clock_realtime();
683 /* Return the virtual CPU time, based on the instruction counter. */
684 static int64_t cpu_get_icount(void)
687 CPUState
*env
= cpu_single_env
;;
688 icount
= qemu_icount
;
691 fprintf(stderr
, "Bad clock read\n");
692 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
694 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
697 /***********************************************************/
698 /* guest cycle counter */
700 typedef struct TimersState
{
701 int64_t cpu_ticks_prev
;
702 int64_t cpu_ticks_offset
;
703 int64_t cpu_clock_offset
;
704 int32_t cpu_ticks_enabled
;
708 TimersState timers_state
;
710 /* return the host CPU cycle counter and handle stop/restart */
711 int64_t cpu_get_ticks(void)
714 return cpu_get_icount();
716 if (!timers_state
.cpu_ticks_enabled
) {
717 return timers_state
.cpu_ticks_offset
;
720 ticks
= cpu_get_real_ticks();
721 if (timers_state
.cpu_ticks_prev
> ticks
) {
722 /* Note: non increasing ticks may happen if the host uses
724 timers_state
.cpu_ticks_offset
+= timers_state
.cpu_ticks_prev
- ticks
;
726 timers_state
.cpu_ticks_prev
= ticks
;
727 return ticks
+ timers_state
.cpu_ticks_offset
;
731 /* return the host CPU monotonic timer and handle stop/restart */
732 static int64_t cpu_get_clock(void)
735 if (!timers_state
.cpu_ticks_enabled
) {
736 return timers_state
.cpu_clock_offset
;
739 return ti
+ timers_state
.cpu_clock_offset
;
743 /* enable cpu_get_ticks() */
744 void cpu_enable_ticks(void)
746 if (!timers_state
.cpu_ticks_enabled
) {
747 timers_state
.cpu_ticks_offset
-= cpu_get_real_ticks();
748 timers_state
.cpu_clock_offset
-= get_clock();
749 timers_state
.cpu_ticks_enabled
= 1;
753 /* disable cpu_get_ticks() : the clock is stopped. You must not call
754 cpu_get_ticks() after that. */
755 void cpu_disable_ticks(void)
757 if (timers_state
.cpu_ticks_enabled
) {
758 timers_state
.cpu_ticks_offset
= cpu_get_ticks();
759 timers_state
.cpu_clock_offset
= cpu_get_clock();
760 timers_state
.cpu_ticks_enabled
= 0;
764 /***********************************************************/
767 #define QEMU_CLOCK_REALTIME 0
768 #define QEMU_CLOCK_VIRTUAL 1
769 #define QEMU_CLOCK_HOST 2
773 /* XXX: add frequency */
781 struct QEMUTimer
*next
;
784 struct qemu_alarm_timer
{
788 int (*start
)(struct qemu_alarm_timer
*t
);
789 void (*stop
)(struct qemu_alarm_timer
*t
);
790 void (*rearm
)(struct qemu_alarm_timer
*t
);
794 #define ALARM_FLAG_DYNTICKS 0x1
795 #define ALARM_FLAG_EXPIRED 0x2
797 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
799 return t
&& (t
->flags
& ALARM_FLAG_DYNTICKS
);
802 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
804 if (!alarm_has_dynticks(t
))
810 /* TODO: MIN_TIMER_REARM_US should be optimized */
811 #define MIN_TIMER_REARM_US 250
813 static struct qemu_alarm_timer
*alarm_timer
;
817 struct qemu_alarm_win32
{
820 } alarm_win32_data
= {0, -1};
822 static int win32_start_timer(struct qemu_alarm_timer
*t
);
823 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
824 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
828 static int unix_start_timer(struct qemu_alarm_timer
*t
);
829 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
833 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
834 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
835 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
837 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
838 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
840 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
841 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
843 #endif /* __linux__ */
847 /* Correlation between real and virtual time is always going to be
848 fairly approximate, so ignore small variation.
849 When the guest is idle real and virtual time will be aligned in
851 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
853 static void icount_adjust(void)
858 static int64_t last_delta
;
859 /* If the VM is not running, then do nothing. */
863 cur_time
= cpu_get_clock();
864 cur_icount
= qemu_get_clock(vm_clock
);
865 delta
= cur_icount
- cur_time
;
866 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
868 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
869 && icount_time_shift
> 0) {
870 /* The guest is getting too far ahead. Slow time down. */
874 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
875 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
876 /* The guest is getting too far behind. Speed time up. */
880 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
883 static void icount_adjust_rt(void * opaque
)
885 qemu_mod_timer(icount_rt_timer
,
886 qemu_get_clock(rt_clock
) + 1000);
890 static void icount_adjust_vm(void * opaque
)
892 qemu_mod_timer(icount_vm_timer
,
893 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
897 static void init_icount_adjust(void)
899 /* Have both realtime and virtual time triggers for speed adjustment.
900 The realtime trigger catches emulated time passing too slowly,
901 the virtual time trigger catches emulated time passing too fast.
902 Realtime triggers occur even when idle, so use them less frequently
904 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
905 qemu_mod_timer(icount_rt_timer
,
906 qemu_get_clock(rt_clock
) + 1000);
907 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
908 qemu_mod_timer(icount_vm_timer
,
909 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
912 static struct qemu_alarm_timer alarm_timers
[] = {
915 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
916 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
917 /* HPET - if available - is preferred */
918 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
919 /* ...otherwise try RTC */
920 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
922 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
924 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
925 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
926 {"win32", 0, win32_start_timer
,
927 win32_stop_timer
, NULL
, &alarm_win32_data
},
932 static void show_available_alarms(void)
936 printf("Available alarm timers, in order of precedence:\n");
937 for (i
= 0; alarm_timers
[i
].name
; i
++)
938 printf("%s\n", alarm_timers
[i
].name
);
941 static void configure_alarms(char const *opt
)
945 int count
= ARRAY_SIZE(alarm_timers
) - 1;
948 struct qemu_alarm_timer tmp
;
950 if (!strcmp(opt
, "?")) {
951 show_available_alarms();
955 arg
= qemu_strdup(opt
);
957 /* Reorder the array */
958 name
= strtok(arg
, ",");
960 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
961 if (!strcmp(alarm_timers
[i
].name
, name
))
966 fprintf(stderr
, "Unknown clock %s\n", name
);
975 tmp
= alarm_timers
[i
];
976 alarm_timers
[i
] = alarm_timers
[cur
];
977 alarm_timers
[cur
] = tmp
;
981 name
= strtok(NULL
, ",");
987 /* Disable remaining timers */
988 for (i
= cur
; i
< count
; i
++)
989 alarm_timers
[i
].name
= NULL
;
991 show_available_alarms();
996 #define QEMU_NUM_CLOCKS 3
1000 QEMUClock
*host_clock
;
1002 static QEMUTimer
*active_timers
[QEMU_NUM_CLOCKS
];
1004 static QEMUClock
*qemu_new_clock(int type
)
1007 clock
= qemu_mallocz(sizeof(QEMUClock
));
1012 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1016 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1019 ts
->opaque
= opaque
;
1023 void qemu_free_timer(QEMUTimer
*ts
)
1028 /* stop a timer, but do not dealloc it */
1029 void qemu_del_timer(QEMUTimer
*ts
)
1033 /* NOTE: this code must be signal safe because
1034 qemu_timer_expired() can be called from a signal. */
1035 pt
= &active_timers
[ts
->clock
->type
];
1048 /* modify the current timer so that it will be fired when current_time
1049 >= expire_time. The corresponding callback will be called. */
1050 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1056 /* add the timer in the sorted list */
1057 /* NOTE: this code must be signal safe because
1058 qemu_timer_expired() can be called from a signal. */
1059 pt
= &active_timers
[ts
->clock
->type
];
1064 if (t
->expire_time
> expire_time
)
1068 ts
->expire_time
= expire_time
;
1072 /* Rearm if necessary */
1073 if (pt
== &active_timers
[ts
->clock
->type
]) {
1074 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1075 qemu_rearm_alarm_timer(alarm_timer
);
1077 /* Interrupt execution to force deadline recalculation. */
1079 qemu_notify_event();
1083 int qemu_timer_pending(QEMUTimer
*ts
)
1086 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1093 int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1097 return (timer_head
->expire_time
<= current_time
);
1100 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1106 if (!ts
|| ts
->expire_time
> current_time
)
1108 /* remove timer from the list before calling the callback */
1109 *ptimer_head
= ts
->next
;
1112 /* run the callback (the timer list can be modified) */
1117 int64_t qemu_get_clock(QEMUClock
*clock
)
1119 switch(clock
->type
) {
1120 case QEMU_CLOCK_REALTIME
:
1121 return get_clock() / 1000000;
1123 case QEMU_CLOCK_VIRTUAL
:
1125 return cpu_get_icount();
1127 return cpu_get_clock();
1129 case QEMU_CLOCK_HOST
:
1130 return get_clock_realtime();
1134 static void init_clocks(void)
1137 rt_clock
= qemu_new_clock(QEMU_CLOCK_REALTIME
);
1138 vm_clock
= qemu_new_clock(QEMU_CLOCK_VIRTUAL
);
1139 host_clock
= qemu_new_clock(QEMU_CLOCK_HOST
);
1141 rtc_clock
= host_clock
;
1145 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1147 uint64_t expire_time
;
1149 if (qemu_timer_pending(ts
)) {
1150 expire_time
= ts
->expire_time
;
1154 qemu_put_be64(f
, expire_time
);
1157 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1159 uint64_t expire_time
;
1161 expire_time
= qemu_get_be64(f
);
1162 if (expire_time
!= -1) {
1163 qemu_mod_timer(ts
, expire_time
);
1169 static const VMStateDescription vmstate_timers
= {
1172 .minimum_version_id
= 1,
1173 .minimum_version_id_old
= 1,
1174 .fields
= (VMStateField
[]) {
1175 VMSTATE_INT64(cpu_ticks_offset
, TimersState
),
1176 VMSTATE_INT64(dummy
, TimersState
),
1177 VMSTATE_INT64_V(cpu_clock_offset
, TimersState
, 2),
1178 VMSTATE_END_OF_LIST()
1182 static void qemu_event_increment(void);
1185 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1186 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1189 static void host_alarm_handler(int host_signum
)
1193 #define DISP_FREQ 1000
1195 static int64_t delta_min
= INT64_MAX
;
1196 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1198 ti
= qemu_get_clock(vm_clock
);
1199 if (last_clock
!= 0) {
1200 delta
= ti
- last_clock
;
1201 if (delta
< delta_min
)
1203 if (delta
> delta_max
)
1206 if (++count
== DISP_FREQ
) {
1207 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1208 muldiv64(delta_min
, 1000000, get_ticks_per_sec()),
1209 muldiv64(delta_max
, 1000000, get_ticks_per_sec()),
1210 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, get_ticks_per_sec()),
1211 (double)get_ticks_per_sec() / ((double)delta_cum
/ DISP_FREQ
));
1213 delta_min
= INT64_MAX
;
1221 if (alarm_has_dynticks(alarm_timer
) ||
1223 qemu_timer_expired(active_timers
[QEMU_CLOCK_VIRTUAL
],
1224 qemu_get_clock(vm_clock
))) ||
1225 qemu_timer_expired(active_timers
[QEMU_CLOCK_REALTIME
],
1226 qemu_get_clock(rt_clock
)) ||
1227 qemu_timer_expired(active_timers
[QEMU_CLOCK_HOST
],
1228 qemu_get_clock(host_clock
))) {
1229 qemu_event_increment();
1230 if (alarm_timer
) alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1232 #ifndef CONFIG_IOTHREAD
1234 /* stop the currently executing cpu because a timer occured */
1238 timer_alarm_pending
= 1;
1239 qemu_notify_event();
1243 static int64_t qemu_next_deadline(void)
1245 /* To avoid problems with overflow limit this to 2^32. */
1246 int64_t delta
= INT32_MAX
;
1248 if (active_timers
[QEMU_CLOCK_VIRTUAL
]) {
1249 delta
= active_timers
[QEMU_CLOCK_VIRTUAL
]->expire_time
-
1250 qemu_get_clock(vm_clock
);
1252 if (active_timers
[QEMU_CLOCK_HOST
]) {
1253 int64_t hdelta
= active_timers
[QEMU_CLOCK_HOST
]->expire_time
-
1254 qemu_get_clock(host_clock
);
1265 #if defined(__linux__)
1266 static uint64_t qemu_next_deadline_dyntick(void)
1274 delta
= (qemu_next_deadline() + 999) / 1000;
1276 if (active_timers
[QEMU_CLOCK_REALTIME
]) {
1277 rtdelta
= (active_timers
[QEMU_CLOCK_REALTIME
]->expire_time
-
1278 qemu_get_clock(rt_clock
))*1000;
1279 if (rtdelta
< delta
)
1283 if (delta
< MIN_TIMER_REARM_US
)
1284 delta
= MIN_TIMER_REARM_US
;
1292 /* Sets a specific flag */
1293 static int fcntl_setfl(int fd
, int flag
)
1297 flags
= fcntl(fd
, F_GETFL
);
1301 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1307 #if defined(__linux__)
1309 #define RTC_FREQ 1024
1311 static void enable_sigio_timer(int fd
)
1313 struct sigaction act
;
1316 sigfillset(&act
.sa_mask
);
1318 act
.sa_handler
= host_alarm_handler
;
1320 sigaction(SIGIO
, &act
, NULL
);
1321 fcntl_setfl(fd
, O_ASYNC
);
1322 fcntl(fd
, F_SETOWN
, getpid());
1325 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1327 struct hpet_info info
;
1330 fd
= qemu_open("/dev/hpet", O_RDONLY
);
1335 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1337 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1338 "error, but for better emulation accuracy type:\n"
1339 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1343 /* Check capabilities */
1344 r
= ioctl(fd
, HPET_INFO
, &info
);
1348 /* Enable periodic mode */
1349 r
= ioctl(fd
, HPET_EPI
, 0);
1350 if (info
.hi_flags
&& (r
< 0))
1353 /* Enable interrupt */
1354 r
= ioctl(fd
, HPET_IE_ON
, 0);
1358 enable_sigio_timer(fd
);
1359 t
->priv
= (void *)(long)fd
;
1367 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1369 int fd
= (long)t
->priv
;
1374 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1377 unsigned long current_rtc_freq
= 0;
1379 TFR(rtc_fd
= qemu_open("/dev/rtc", O_RDONLY
));
1382 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1383 if (current_rtc_freq
!= RTC_FREQ
&&
1384 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1385 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1386 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1387 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1390 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1396 enable_sigio_timer(rtc_fd
);
1398 t
->priv
= (void *)(long)rtc_fd
;
1403 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1405 int rtc_fd
= (long)t
->priv
;
1410 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1414 struct sigaction act
;
1416 sigfillset(&act
.sa_mask
);
1418 act
.sa_handler
= host_alarm_handler
;
1420 sigaction(SIGALRM
, &act
, NULL
);
1423 * Initialize ev struct to 0 to avoid valgrind complaining
1424 * about uninitialized data in timer_create call
1426 memset(&ev
, 0, sizeof(ev
));
1427 ev
.sigev_value
.sival_int
= 0;
1428 ev
.sigev_notify
= SIGEV_SIGNAL
;
1429 ev
.sigev_signo
= SIGALRM
;
1431 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1432 perror("timer_create");
1434 /* disable dynticks */
1435 fprintf(stderr
, "Dynamic Ticks disabled\n");
1440 t
->priv
= (void *)(long)host_timer
;
1445 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1447 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1449 timer_delete(host_timer
);
1452 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1454 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1455 struct itimerspec timeout
;
1456 int64_t nearest_delta_us
= INT64_MAX
;
1459 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1460 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1461 !active_timers
[QEMU_CLOCK_HOST
])
1464 nearest_delta_us
= qemu_next_deadline_dyntick();
1466 /* check whether a timer is already running */
1467 if (timer_gettime(host_timer
, &timeout
)) {
1469 fprintf(stderr
, "Internal timer error: aborting\n");
1472 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1473 if (current_us
&& current_us
<= nearest_delta_us
)
1476 timeout
.it_interval
.tv_sec
= 0;
1477 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1478 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1479 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1480 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1482 fprintf(stderr
, "Internal timer error: aborting\n");
1487 #endif /* defined(__linux__) */
1489 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1491 struct sigaction act
;
1492 struct itimerval itv
;
1496 sigfillset(&act
.sa_mask
);
1498 act
.sa_handler
= host_alarm_handler
;
1500 sigaction(SIGALRM
, &act
, NULL
);
1502 itv
.it_interval
.tv_sec
= 0;
1503 /* for i386 kernel 2.6 to get 1 ms */
1504 itv
.it_interval
.tv_usec
= 999;
1505 itv
.it_value
.tv_sec
= 0;
1506 itv
.it_value
.tv_usec
= 10 * 1000;
1508 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1515 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1517 struct itimerval itv
;
1519 memset(&itv
, 0, sizeof(itv
));
1520 setitimer(ITIMER_REAL
, &itv
, NULL
);
1523 #endif /* !defined(_WIN32) */
1528 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1531 struct qemu_alarm_win32
*data
= t
->priv
;
1534 memset(&tc
, 0, sizeof(tc
));
1535 timeGetDevCaps(&tc
, sizeof(tc
));
1537 if (data
->period
< tc
.wPeriodMin
)
1538 data
->period
= tc
.wPeriodMin
;
1540 timeBeginPeriod(data
->period
);
1542 flags
= TIME_CALLBACK_FUNCTION
;
1543 if (alarm_has_dynticks(t
))
1544 flags
|= TIME_ONESHOT
;
1546 flags
|= TIME_PERIODIC
;
1548 data
->timerId
= timeSetEvent(1, // interval (ms)
1549 data
->period
, // resolution
1550 host_alarm_handler
, // function
1551 (DWORD
)t
, // parameter
1554 if (!data
->timerId
) {
1555 fprintf(stderr
, "Failed to initialize win32 alarm timer: %ld\n",
1557 timeEndPeriod(data
->period
);
1564 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1566 struct qemu_alarm_win32
*data
= t
->priv
;
1568 timeKillEvent(data
->timerId
);
1569 timeEndPeriod(data
->period
);
1572 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1574 struct qemu_alarm_win32
*data
= t
->priv
;
1576 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1577 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1578 !active_timers
[QEMU_CLOCK_HOST
])
1581 timeKillEvent(data
->timerId
);
1583 data
->timerId
= timeSetEvent(1,
1587 TIME_ONESHOT
| TIME_PERIODIC
);
1589 if (!data
->timerId
) {
1590 fprintf(stderr
, "Failed to re-arm win32 alarm timer %ld\n",
1593 timeEndPeriod(data
->period
);
1600 static int init_timer_alarm(void)
1602 struct qemu_alarm_timer
*t
= NULL
;
1605 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1606 t
= &alarm_timers
[i
];
1626 static void quit_timers(void)
1628 alarm_timer
->stop(alarm_timer
);
1632 /***********************************************************/
1633 /* host time/date access */
1634 void qemu_get_timedate(struct tm
*tm
, int offset
)
1641 if (rtc_date_offset
== -1) {
1645 ret
= localtime(&ti
);
1647 ti
-= rtc_date_offset
;
1651 memcpy(tm
, ret
, sizeof(struct tm
));
1654 int qemu_timedate_diff(struct tm
*tm
)
1658 if (rtc_date_offset
== -1)
1660 seconds
= mktimegm(tm
);
1662 seconds
= mktime(tm
);
1664 seconds
= mktimegm(tm
) + rtc_date_offset
;
1666 return seconds
- time(NULL
);
1669 static void configure_rtc_date_offset(const char *startdate
, int legacy
)
1671 time_t rtc_start_date
;
1674 if (!strcmp(startdate
, "now") && legacy
) {
1675 rtc_date_offset
= -1;
1677 if (sscanf(startdate
, "%d-%d-%dT%d:%d:%d",
1685 } else if (sscanf(startdate
, "%d-%d-%d",
1688 &tm
.tm_mday
) == 3) {
1697 rtc_start_date
= mktimegm(&tm
);
1698 if (rtc_start_date
== -1) {
1700 fprintf(stderr
, "Invalid date format. Valid formats are:\n"
1701 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1704 rtc_date_offset
= time(NULL
) - rtc_start_date
;
1708 static void configure_rtc(QemuOpts
*opts
)
1712 value
= qemu_opt_get(opts
, "base");
1714 if (!strcmp(value
, "utc")) {
1716 } else if (!strcmp(value
, "localtime")) {
1719 configure_rtc_date_offset(value
, 0);
1722 value
= qemu_opt_get(opts
, "clock");
1724 if (!strcmp(value
, "host")) {
1725 rtc_clock
= host_clock
;
1726 } else if (!strcmp(value
, "vm")) {
1727 rtc_clock
= vm_clock
;
1729 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1733 #ifdef CONFIG_TARGET_I386
1734 value
= qemu_opt_get(opts
, "driftfix");
1736 if (!strcmp(buf
, "slew")) {
1738 } else if (!strcmp(buf
, "none")) {
1741 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1749 static void socket_cleanup(void)
1754 static int socket_init(void)
1759 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1761 err
= WSAGetLastError();
1762 fprintf(stderr
, "WSAStartup: %d\n", err
);
1765 atexit(socket_cleanup
);
1770 /***********************************************************/
1771 /* Bluetooth support */
1774 static struct HCIInfo
*hci_table
[MAX_NICS
];
1776 static struct bt_vlan_s
{
1777 struct bt_scatternet_s net
;
1779 struct bt_vlan_s
*next
;
1782 /* find or alloc a new bluetooth "VLAN" */
1783 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1785 struct bt_vlan_s
**pvlan
, *vlan
;
1786 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1790 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1792 pvlan
= &first_bt_vlan
;
1793 while (*pvlan
!= NULL
)
1794 pvlan
= &(*pvlan
)->next
;
1799 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1803 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1808 static struct HCIInfo null_hci
= {
1809 .cmd_send
= null_hci_send
,
1810 .sco_send
= null_hci_send
,
1811 .acl_send
= null_hci_send
,
1812 .bdaddr_set
= null_hci_addr_set
,
1815 struct HCIInfo
*qemu_next_hci(void)
1817 if (cur_hci
== nb_hcis
)
1820 return hci_table
[cur_hci
++];
1823 static struct HCIInfo
*hci_init(const char *str
)
1826 struct bt_scatternet_s
*vlan
= 0;
1828 if (!strcmp(str
, "null"))
1831 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
1833 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
1834 else if (!strncmp(str
, "hci", 3)) {
1837 if (!strncmp(str
+ 3, ",vlan=", 6)) {
1838 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
1843 vlan
= qemu_find_bt_vlan(0);
1845 return bt_new_hci(vlan
);
1848 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
1853 static int bt_hci_parse(const char *str
)
1855 struct HCIInfo
*hci
;
1858 if (nb_hcis
>= MAX_NICS
) {
1859 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
1863 hci
= hci_init(str
);
1872 bdaddr
.b
[5] = 0x56 + nb_hcis
;
1873 hci
->bdaddr_set(hci
, bdaddr
.b
);
1875 hci_table
[nb_hcis
++] = hci
;
1880 static void bt_vhci_add(int vlan_id
)
1882 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
1885 fprintf(stderr
, "qemu: warning: adding a VHCI to "
1886 "an empty scatternet %i\n", vlan_id
);
1888 bt_vhci_init(bt_new_hci(vlan
));
1891 static struct bt_device_s
*bt_device_add(const char *opt
)
1893 struct bt_scatternet_s
*vlan
;
1895 char *endp
= strstr(opt
, ",vlan=");
1896 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
1899 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
1902 vlan_id
= strtol(endp
+ 6, &endp
, 0);
1904 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
1909 vlan
= qemu_find_bt_vlan(vlan_id
);
1912 fprintf(stderr
, "qemu: warning: adding a slave device to "
1913 "an empty scatternet %i\n", vlan_id
);
1915 if (!strcmp(devname
, "keyboard"))
1916 return bt_keyboard_init(vlan
);
1918 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
1922 static int bt_parse(const char *opt
)
1924 const char *endp
, *p
;
1927 if (strstart(opt
, "hci", &endp
)) {
1928 if (!*endp
|| *endp
== ',') {
1930 if (!strstart(endp
, ",vlan=", 0))
1933 return bt_hci_parse(opt
);
1935 } else if (strstart(opt
, "vhci", &endp
)) {
1936 if (!*endp
|| *endp
== ',') {
1938 if (strstart(endp
, ",vlan=", &p
)) {
1939 vlan
= strtol(p
, (char **) &endp
, 0);
1941 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
1945 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
1954 } else if (strstart(opt
, "device:", &endp
))
1955 return !bt_device_add(endp
);
1957 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
1961 /***********************************************************/
1962 /* QEMU Block devices */
1964 #define HD_ALIAS "index=%d,media=disk"
1965 #define CDROM_ALIAS "index=2,media=cdrom"
1966 #define FD_ALIAS "index=%d,if=floppy"
1967 #define PFLASH_ALIAS "if=pflash"
1968 #define MTD_ALIAS "if=mtd"
1969 #define SD_ALIAS "index=0,if=sd"
1971 QemuOpts
*drive_add(const char *file
, const char *fmt
, ...)
1978 vsnprintf(optstr
, sizeof(optstr
), fmt
, ap
);
1981 opts
= qemu_opts_parse(&qemu_drive_opts
, optstr
, NULL
);
1983 fprintf(stderr
, "%s: huh? duplicate? (%s)\n",
1984 __FUNCTION__
, optstr
);
1988 qemu_opt_set(opts
, "file", file
);
1992 DriveInfo
*drive_get(BlockInterfaceType type
, int bus
, int unit
)
1996 /* seek interface, bus and unit */
1998 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1999 if (dinfo
->type
== type
&&
2000 dinfo
->bus
== bus
&&
2001 dinfo
->unit
== unit
)
2008 DriveInfo
*drive_get_by_id(const char *id
)
2012 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
2013 if (strcmp(id
, dinfo
->id
))
2020 int drive_get_max_bus(BlockInterfaceType type
)
2026 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
2027 if(dinfo
->type
== type
&&
2028 dinfo
->bus
> max_bus
)
2029 max_bus
= dinfo
->bus
;
2034 const char *drive_get_serial(BlockDriverState
*bdrv
)
2038 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
2039 if (dinfo
->bdrv
== bdrv
)
2040 return dinfo
->serial
;
2046 BlockInterfaceErrorAction
drive_get_on_error(
2047 BlockDriverState
*bdrv
, int is_read
)
2051 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
2052 if (dinfo
->bdrv
== bdrv
)
2053 return is_read
? dinfo
->on_read_error
: dinfo
->on_write_error
;
2056 return is_read
? BLOCK_ERR_REPORT
: BLOCK_ERR_STOP_ENOSPC
;
2059 static void bdrv_format_print(void *opaque
, const char *name
)
2061 fprintf(stderr
, " %s", name
);
2064 void drive_uninit(DriveInfo
*dinfo
)
2066 qemu_opts_del(dinfo
->opts
);
2067 bdrv_delete(dinfo
->bdrv
);
2068 QTAILQ_REMOVE(&drives
, dinfo
, next
);
2072 static int parse_block_error_action(const char *buf
, int is_read
)
2074 if (!strcmp(buf
, "ignore")) {
2075 return BLOCK_ERR_IGNORE
;
2076 } else if (!is_read
&& !strcmp(buf
, "enospc")) {
2077 return BLOCK_ERR_STOP_ENOSPC
;
2078 } else if (!strcmp(buf
, "stop")) {
2079 return BLOCK_ERR_STOP_ANY
;
2080 } else if (!strcmp(buf
, "report")) {
2081 return BLOCK_ERR_REPORT
;
2083 fprintf(stderr
, "qemu: '%s' invalid %s error action\n",
2084 buf
, is_read
? "read" : "write");
2089 DriveInfo
*drive_init(QemuOpts
*opts
, void *opaque
,
2093 const char *file
= NULL
;
2096 const char *mediastr
= "";
2097 BlockInterfaceType type
;
2098 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
2099 int bus_id
, unit_id
;
2100 int cyls
, heads
, secs
, translation
;
2101 BlockDriver
*drv
= NULL
;
2102 QEMUMachine
*machine
= opaque
;
2109 int on_read_error
, on_write_error
;
2110 const char *devaddr
;
2116 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2119 if (machine
&& machine
->use_scsi
) {
2121 max_devs
= MAX_SCSI_DEVS
;
2122 pstrcpy(devname
, sizeof(devname
), "scsi");
2125 max_devs
= MAX_IDE_DEVS
;
2126 pstrcpy(devname
, sizeof(devname
), "ide");
2130 /* extract parameters */
2131 bus_id
= qemu_opt_get_number(opts
, "bus", 0);
2132 unit_id
= qemu_opt_get_number(opts
, "unit", -1);
2133 index
= qemu_opt_get_number(opts
, "index", -1);
2135 cyls
= qemu_opt_get_number(opts
, "cyls", 0);
2136 heads
= qemu_opt_get_number(opts
, "heads", 0);
2137 secs
= qemu_opt_get_number(opts
, "secs", 0);
2139 snapshot
= qemu_opt_get_bool(opts
, "snapshot", 0);
2140 ro
= qemu_opt_get_bool(opts
, "readonly", 0);
2142 file
= qemu_opt_get(opts
, "file");
2143 serial
= qemu_opt_get(opts
, "serial");
2145 if ((buf
= qemu_opt_get(opts
, "if")) != NULL
) {
2146 pstrcpy(devname
, sizeof(devname
), buf
);
2147 if (!strcmp(buf
, "ide")) {
2149 max_devs
= MAX_IDE_DEVS
;
2150 } else if (!strcmp(buf
, "scsi")) {
2152 max_devs
= MAX_SCSI_DEVS
;
2153 } else if (!strcmp(buf
, "floppy")) {
2156 } else if (!strcmp(buf
, "pflash")) {
2159 } else if (!strcmp(buf
, "mtd")) {
2162 } else if (!strcmp(buf
, "sd")) {
2165 } else if (!strcmp(buf
, "virtio")) {
2168 } else if (!strcmp(buf
, "xen")) {
2171 } else if (!strcmp(buf
, "none")) {
2175 fprintf(stderr
, "qemu: unsupported bus type '%s'\n", buf
);
2180 if (cyls
|| heads
|| secs
) {
2181 if (cyls
< 1 || (type
== IF_IDE
&& cyls
> 16383)) {
2182 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", buf
);
2185 if (heads
< 1 || (type
== IF_IDE
&& heads
> 16)) {
2186 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", buf
);
2189 if (secs
< 1 || (type
== IF_IDE
&& secs
> 63)) {
2190 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", buf
);
2195 if ((buf
= qemu_opt_get(opts
, "trans")) != NULL
) {
2198 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2202 if (!strcmp(buf
, "none"))
2203 translation
= BIOS_ATA_TRANSLATION_NONE
;
2204 else if (!strcmp(buf
, "lba"))
2205 translation
= BIOS_ATA_TRANSLATION_LBA
;
2206 else if (!strcmp(buf
, "auto"))
2207 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2209 fprintf(stderr
, "qemu: '%s' invalid translation type\n", buf
);
2214 if ((buf
= qemu_opt_get(opts
, "media")) != NULL
) {
2215 if (!strcmp(buf
, "disk")) {
2217 } else if (!strcmp(buf
, "cdrom")) {
2218 if (cyls
|| secs
|| heads
) {
2220 "qemu: '%s' invalid physical CHS format\n", buf
);
2223 media
= MEDIA_CDROM
;
2225 fprintf(stderr
, "qemu: '%s' invalid media\n", buf
);
2230 if ((buf
= qemu_opt_get(opts
, "cache")) != NULL
) {
2231 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2233 else if (!strcmp(buf
, "writethrough"))
2235 else if (!strcmp(buf
, "writeback"))
2238 fprintf(stderr
, "qemu: invalid cache option\n");
2243 #ifdef CONFIG_LINUX_AIO
2244 if ((buf
= qemu_opt_get(opts
, "aio")) != NULL
) {
2245 if (!strcmp(buf
, "threads"))
2247 else if (!strcmp(buf
, "native"))
2250 fprintf(stderr
, "qemu: invalid aio option\n");
2256 if ((buf
= qemu_opt_get(opts
, "format")) != NULL
) {
2257 if (strcmp(buf
, "?") == 0) {
2258 fprintf(stderr
, "qemu: Supported formats:");
2259 bdrv_iterate_format(bdrv_format_print
, NULL
);
2260 fprintf(stderr
, "\n");
2263 drv
= bdrv_find_whitelisted_format(buf
);
2265 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2270 on_write_error
= BLOCK_ERR_STOP_ENOSPC
;
2271 if ((buf
= qemu_opt_get(opts
, "werror")) != NULL
) {
2272 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2273 fprintf(stderr
, "werror is no supported by this format\n");
2277 on_write_error
= parse_block_error_action(buf
, 0);
2278 if (on_write_error
< 0) {
2283 on_read_error
= BLOCK_ERR_REPORT
;
2284 if ((buf
= qemu_opt_get(opts
, "rerror")) != NULL
) {
2285 if (type
!= IF_IDE
&& type
!= IF_VIRTIO
) {
2286 fprintf(stderr
, "rerror is no supported by this format\n");
2290 on_read_error
= parse_block_error_action(buf
, 1);
2291 if (on_read_error
< 0) {
2296 if ((devaddr
= qemu_opt_get(opts
, "addr")) != NULL
) {
2297 if (type
!= IF_VIRTIO
) {
2298 fprintf(stderr
, "addr is not supported\n");
2303 /* compute bus and unit according index */
2306 if (bus_id
!= 0 || unit_id
!= -1) {
2308 "qemu: index cannot be used with bus and unit\n");
2316 unit_id
= index
% max_devs
;
2317 bus_id
= index
/ max_devs
;
2321 /* if user doesn't specify a unit_id,
2322 * try to find the first free
2325 if (unit_id
== -1) {
2327 while (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2329 if (max_devs
&& unit_id
>= max_devs
) {
2330 unit_id
-= max_devs
;
2338 if (max_devs
&& unit_id
>= max_devs
) {
2339 fprintf(stderr
, "qemu: unit %d too big (max is %d)\n",
2340 unit_id
, max_devs
- 1);
2345 * ignore multiple definitions
2348 if (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2355 dinfo
= qemu_mallocz(sizeof(*dinfo
));
2356 if ((buf
= qemu_opts_id(opts
)) != NULL
) {
2357 dinfo
->id
= qemu_strdup(buf
);
2359 /* no id supplied -> create one */
2360 dinfo
->id
= qemu_mallocz(32);
2361 if (type
== IF_IDE
|| type
== IF_SCSI
)
2362 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2364 snprintf(dinfo
->id
, 32, "%s%i%s%i",
2365 devname
, bus_id
, mediastr
, unit_id
);
2367 snprintf(dinfo
->id
, 32, "%s%s%i",
2368 devname
, mediastr
, unit_id
);
2370 dinfo
->bdrv
= bdrv_new(dinfo
->id
);
2371 dinfo
->devaddr
= devaddr
;
2373 dinfo
->bus
= bus_id
;
2374 dinfo
->unit
= unit_id
;
2375 dinfo
->on_read_error
= on_read_error
;
2376 dinfo
->on_write_error
= on_write_error
;
2379 strncpy(dinfo
->serial
, serial
, sizeof(serial
));
2380 QTAILQ_INSERT_TAIL(&drives
, dinfo
, next
);
2390 bdrv_set_geometry_hint(dinfo
->bdrv
, cyls
, heads
, secs
);
2391 bdrv_set_translation_hint(dinfo
->bdrv
, translation
);
2395 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_CDROM
);
2400 /* FIXME: This isn't really a floppy, but it's a reasonable
2403 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_FLOPPY
);
2409 /* add virtio block device */
2410 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
2411 qemu_opt_set(opts
, "driver", "virtio-blk-pci");
2412 qemu_opt_set(opts
, "drive", dinfo
->id
);
2414 qemu_opt_set(opts
, "addr", devaddr
);
2425 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2426 cache
= 2; /* always use write-back with snapshot */
2428 if (cache
== 0) /* no caching */
2429 bdrv_flags
|= BDRV_O_NOCACHE
;
2430 else if (cache
== 2) /* write-back */
2431 bdrv_flags
|= BDRV_O_CACHE_WB
;
2434 bdrv_flags
|= BDRV_O_NATIVE_AIO
;
2436 bdrv_flags
&= ~BDRV_O_NATIVE_AIO
;
2440 if (type
== IF_IDE
) {
2441 fprintf(stderr
, "qemu: readonly flag not supported for drive with ide interface\n");
2444 (void)bdrv_set_read_only(dinfo
->bdrv
, 1);
2447 if (bdrv_open2(dinfo
->bdrv
, file
, bdrv_flags
, drv
) < 0) {
2448 fprintf(stderr
, "qemu: could not open disk image %s: %s\n",
2449 file
, strerror(errno
));
2453 if (bdrv_key_required(dinfo
->bdrv
))
2459 static int drive_init_func(QemuOpts
*opts
, void *opaque
)
2461 QEMUMachine
*machine
= opaque
;
2462 int fatal_error
= 0;
2464 if (drive_init(opts
, machine
, &fatal_error
) == NULL
) {
2471 static int drive_enable_snapshot(QemuOpts
*opts
, void *opaque
)
2473 if (NULL
== qemu_opt_get(opts
, "snapshot")) {
2474 qemu_opt_set(opts
, "snapshot", "on");
2479 void qemu_register_boot_set(QEMUBootSetHandler
*func
, void *opaque
)
2481 boot_set_handler
= func
;
2482 boot_set_opaque
= opaque
;
2485 int qemu_boot_set(const char *boot_devices
)
2487 if (!boot_set_handler
) {
2490 return boot_set_handler(boot_set_opaque
, boot_devices
);
2493 static int parse_bootdevices(char *devices
)
2495 /* We just do some generic consistency checks */
2499 for (p
= devices
; *p
!= '\0'; p
++) {
2500 /* Allowed boot devices are:
2501 * a-b: floppy disk drives
2502 * c-f: IDE disk drives
2503 * g-m: machine implementation dependant drives
2504 * n-p: network devices
2505 * It's up to each machine implementation to check if the given boot
2506 * devices match the actual hardware implementation and firmware
2509 if (*p
< 'a' || *p
> 'p') {
2510 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
2513 if (bitmap
& (1 << (*p
- 'a'))) {
2514 fprintf(stderr
, "Boot device '%c' was given twice\n", *p
);
2517 bitmap
|= 1 << (*p
- 'a');
2522 static void restore_boot_devices(void *opaque
)
2524 char *standard_boot_devices
= opaque
;
2526 qemu_boot_set(standard_boot_devices
);
2528 qemu_unregister_reset(restore_boot_devices
, standard_boot_devices
);
2529 qemu_free(standard_boot_devices
);
2532 static void numa_add(const char *optarg
)
2536 unsigned long long value
, endvalue
;
2539 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2540 if (!strcmp(option
, "node")) {
2541 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2542 nodenr
= nb_numa_nodes
;
2544 nodenr
= strtoull(option
, NULL
, 10);
2547 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2548 node_mem
[nodenr
] = 0;
2550 value
= strtoull(option
, &endptr
, 0);
2552 case 0: case 'M': case 'm':
2559 node_mem
[nodenr
] = value
;
2561 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2562 node_cpumask
[nodenr
] = 0;
2564 value
= strtoull(option
, &endptr
, 10);
2567 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2569 if (*endptr
== '-') {
2570 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2571 if (endvalue
>= 63) {
2574 "only 63 CPUs in NUMA mode supported.\n");
2576 value
= (1 << (endvalue
+ 1)) - (1 << value
);
2581 node_cpumask
[nodenr
] = value
;
2588 static void smp_parse(const char *optarg
)
2590 int smp
, sockets
= 0, threads
= 0, cores
= 0;
2594 smp
= strtoul(optarg
, &endptr
, 10);
2595 if (endptr
!= optarg
) {
2596 if (*endptr
== ',') {
2600 if (get_param_value(option
, 128, "sockets", endptr
) != 0)
2601 sockets
= strtoull(option
, NULL
, 10);
2602 if (get_param_value(option
, 128, "cores", endptr
) != 0)
2603 cores
= strtoull(option
, NULL
, 10);
2604 if (get_param_value(option
, 128, "threads", endptr
) != 0)
2605 threads
= strtoull(option
, NULL
, 10);
2606 if (get_param_value(option
, 128, "maxcpus", endptr
) != 0)
2607 max_cpus
= strtoull(option
, NULL
, 10);
2609 /* compute missing values, prefer sockets over cores over threads */
2610 if (smp
== 0 || sockets
== 0) {
2611 sockets
= sockets
> 0 ? sockets
: 1;
2612 cores
= cores
> 0 ? cores
: 1;
2613 threads
= threads
> 0 ? threads
: 1;
2615 smp
= cores
* threads
* sockets
;
2617 sockets
= smp
/ (cores
* threads
);
2621 threads
= threads
> 0 ? threads
: 1;
2622 cores
= smp
/ (sockets
* threads
);
2625 sockets
= smp
/ (cores
* threads
);
2627 threads
= smp
/ (cores
* sockets
);
2632 smp_cores
= cores
> 0 ? cores
: 1;
2633 smp_threads
= threads
> 0 ? threads
: 1;
2635 max_cpus
= smp_cpus
;
2638 /***********************************************************/
2641 static int usb_device_add(const char *devname
, int is_hotplug
)
2644 USBDevice
*dev
= NULL
;
2649 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2650 dev
= usbdevice_create(devname
);
2654 /* the other ones */
2655 if (strstart(devname
, "host:", &p
)) {
2656 dev
= usb_host_device_open(p
);
2657 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2658 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2659 bt_new_hci(qemu_find_bt_vlan(0)));
2670 static int usb_device_del(const char *devname
)
2675 if (strstart(devname
, "host:", &p
))
2676 return usb_host_device_close(p
);
2681 p
= strchr(devname
, '.');
2684 bus_num
= strtoul(devname
, NULL
, 0);
2685 addr
= strtoul(p
+ 1, NULL
, 0);
2687 return usb_device_delete_addr(bus_num
, addr
);
2690 static int usb_parse(const char *cmdline
)
2693 r
= usb_device_add(cmdline
, 0);
2695 fprintf(stderr
, "qemu: could not add USB device '%s'\n", cmdline
);
2700 void do_usb_add(Monitor
*mon
, const QDict
*qdict
)
2702 const char *devname
= qdict_get_str(qdict
, "devname");
2703 if (usb_device_add(devname
, 1) < 0) {
2704 qemu_error("could not add USB device '%s'\n", devname
);
2708 void do_usb_del(Monitor
*mon
, const QDict
*qdict
)
2710 const char *devname
= qdict_get_str(qdict
, "devname");
2711 if (usb_device_del(devname
) < 0) {
2712 qemu_error("could not delete USB device '%s'\n", devname
);
2716 /***********************************************************/
2717 /* PCMCIA/Cardbus */
2719 static struct pcmcia_socket_entry_s
{
2720 PCMCIASocket
*socket
;
2721 struct pcmcia_socket_entry_s
*next
;
2722 } *pcmcia_sockets
= 0;
2724 void pcmcia_socket_register(PCMCIASocket
*socket
)
2726 struct pcmcia_socket_entry_s
*entry
;
2728 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2729 entry
->socket
= socket
;
2730 entry
->next
= pcmcia_sockets
;
2731 pcmcia_sockets
= entry
;
2734 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2736 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2738 ptr
= &pcmcia_sockets
;
2739 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2740 if (entry
->socket
== socket
) {
2746 void pcmcia_info(Monitor
*mon
)
2748 struct pcmcia_socket_entry_s
*iter
;
2750 if (!pcmcia_sockets
)
2751 monitor_printf(mon
, "No PCMCIA sockets\n");
2753 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2754 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2755 iter
->socket
->attached
? iter
->socket
->card_string
:
2759 /***********************************************************/
2760 /* register display */
2762 struct DisplayAllocator default_allocator
= {
2763 defaultallocator_create_displaysurface
,
2764 defaultallocator_resize_displaysurface
,
2765 defaultallocator_free_displaysurface
2768 void register_displaystate(DisplayState
*ds
)
2778 DisplayState
*get_displaystate(void)
2780 return display_state
;
2783 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
2785 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
2786 return ds
->allocator
;
2791 static void dumb_display_init(void)
2793 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
2794 ds
->allocator
= &default_allocator
;
2795 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
2796 register_displaystate(ds
);
2799 /***********************************************************/
2802 typedef struct IOHandlerRecord
{
2804 IOCanRWHandler
*fd_read_poll
;
2806 IOHandler
*fd_write
;
2809 /* temporary data */
2811 struct IOHandlerRecord
*next
;
2814 static IOHandlerRecord
*first_io_handler
;
2816 /* XXX: fd_read_poll should be suppressed, but an API change is
2817 necessary in the character devices to suppress fd_can_read(). */
2818 int qemu_set_fd_handler2(int fd
,
2819 IOCanRWHandler
*fd_read_poll
,
2821 IOHandler
*fd_write
,
2824 IOHandlerRecord
**pioh
, *ioh
;
2826 if (!fd_read
&& !fd_write
) {
2827 pioh
= &first_io_handler
;
2832 if (ioh
->fd
== fd
) {
2839 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
2843 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
2844 ioh
->next
= first_io_handler
;
2845 first_io_handler
= ioh
;
2848 ioh
->fd_read_poll
= fd_read_poll
;
2849 ioh
->fd_read
= fd_read
;
2850 ioh
->fd_write
= fd_write
;
2851 ioh
->opaque
= opaque
;
2857 int qemu_set_fd_handler(int fd
,
2859 IOHandler
*fd_write
,
2862 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
2866 /***********************************************************/
2867 /* Polling handling */
2869 typedef struct PollingEntry
{
2872 struct PollingEntry
*next
;
2875 static PollingEntry
*first_polling_entry
;
2877 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
2879 PollingEntry
**ppe
, *pe
;
2880 pe
= qemu_mallocz(sizeof(PollingEntry
));
2882 pe
->opaque
= opaque
;
2883 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
2888 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
2890 PollingEntry
**ppe
, *pe
;
2891 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
2893 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
2901 /***********************************************************/
2902 /* Wait objects support */
2903 typedef struct WaitObjects
{
2905 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
2906 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
2907 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
2910 static WaitObjects wait_objects
= {0};
2912 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2914 WaitObjects
*w
= &wait_objects
;
2916 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
2918 w
->events
[w
->num
] = handle
;
2919 w
->func
[w
->num
] = func
;
2920 w
->opaque
[w
->num
] = opaque
;
2925 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2928 WaitObjects
*w
= &wait_objects
;
2931 for (i
= 0; i
< w
->num
; i
++) {
2932 if (w
->events
[i
] == handle
)
2935 w
->events
[i
] = w
->events
[i
+ 1];
2936 w
->func
[i
] = w
->func
[i
+ 1];
2937 w
->opaque
[i
] = w
->opaque
[i
+ 1];
2945 /***********************************************************/
2946 /* ram save/restore */
2948 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2949 #define RAM_SAVE_FLAG_COMPRESS 0x02
2950 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2951 #define RAM_SAVE_FLAG_PAGE 0x08
2952 #define RAM_SAVE_FLAG_EOS 0x10
2954 static int is_dup_page(uint8_t *page
, uint8_t ch
)
2956 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
2957 uint32_t *array
= (uint32_t *)page
;
2960 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
2961 if (array
[i
] != val
)
2968 static int ram_save_block(QEMUFile
*f
)
2970 static ram_addr_t current_addr
= 0;
2971 ram_addr_t saved_addr
= current_addr
;
2972 ram_addr_t addr
= 0;
2975 while (addr
< last_ram_offset
) {
2976 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
2979 cpu_physical_memory_reset_dirty(current_addr
,
2980 current_addr
+ TARGET_PAGE_SIZE
,
2981 MIGRATION_DIRTY_FLAG
);
2983 p
= qemu_get_ram_ptr(current_addr
);
2985 if (is_dup_page(p
, *p
)) {
2986 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
2987 qemu_put_byte(f
, *p
);
2989 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
2990 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
2996 addr
+= TARGET_PAGE_SIZE
;
2997 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
3003 static uint64_t bytes_transferred
;
3005 static ram_addr_t
ram_save_remaining(void)
3008 ram_addr_t count
= 0;
3010 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3011 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3018 uint64_t ram_bytes_remaining(void)
3020 return ram_save_remaining() * TARGET_PAGE_SIZE
;
3023 uint64_t ram_bytes_transferred(void)
3025 return bytes_transferred
;
3028 uint64_t ram_bytes_total(void)
3030 return last_ram_offset
;
3033 static int ram_save_live(Monitor
*mon
, QEMUFile
*f
, int stage
, void *opaque
)
3036 uint64_t bytes_transferred_last
;
3038 uint64_t expected_time
= 0;
3041 cpu_physical_memory_set_dirty_tracking(0);
3045 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX
) != 0) {
3046 qemu_file_set_error(f
);
3051 bytes_transferred
= 0;
3053 /* Make sure all dirty bits are set */
3054 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3055 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3056 cpu_physical_memory_set_dirty(addr
);
3059 /* Enable dirty memory tracking */
3060 cpu_physical_memory_set_dirty_tracking(1);
3062 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
3065 bytes_transferred_last
= bytes_transferred
;
3066 bwidth
= get_clock();
3068 while (!qemu_file_rate_limit(f
)) {
3071 ret
= ram_save_block(f
);
3072 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
3073 if (ret
== 0) /* no more blocks */
3077 bwidth
= get_clock() - bwidth
;
3078 bwidth
= (bytes_transferred
- bytes_transferred_last
) / bwidth
;
3080 /* if we haven't transferred anything this round, force expected_time to a
3081 * a very high value, but without crashing */
3085 /* try transferring iterative blocks of memory */
3087 /* flush all remaining blocks regardless of rate limiting */
3088 while (ram_save_block(f
) != 0) {
3089 bytes_transferred
+= TARGET_PAGE_SIZE
;
3091 cpu_physical_memory_set_dirty_tracking(0);
3094 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3096 expected_time
= ram_save_remaining() * TARGET_PAGE_SIZE
/ bwidth
;
3098 return (stage
== 2) && (expected_time
<= migrate_max_downtime());
3101 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
3106 if (version_id
!= 3)
3110 addr
= qemu_get_be64(f
);
3112 flags
= addr
& ~TARGET_PAGE_MASK
;
3113 addr
&= TARGET_PAGE_MASK
;
3115 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
3116 if (addr
!= last_ram_offset
)
3120 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
3121 uint8_t ch
= qemu_get_byte(f
);
3122 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
3125 (!kvm_enabled() || kvm_has_sync_mmu())) {
3126 madvise(qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
, MADV_DONTNEED
);
3129 } else if (flags
& RAM_SAVE_FLAG_PAGE
) {
3130 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
3132 if (qemu_file_has_error(f
)) {
3135 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
3140 void qemu_service_io(void)
3142 qemu_notify_event();
3145 /***********************************************************/
3146 /* machine registration */
3148 static QEMUMachine
*first_machine
= NULL
;
3149 QEMUMachine
*current_machine
= NULL
;
3151 int qemu_register_machine(QEMUMachine
*m
)
3154 pm
= &first_machine
;
3162 static QEMUMachine
*find_machine(const char *name
)
3166 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3167 if (!strcmp(m
->name
, name
))
3169 if (m
->alias
&& !strcmp(m
->alias
, name
))
3175 static QEMUMachine
*find_default_machine(void)
3179 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3180 if (m
->is_default
) {
3187 /***********************************************************/
3188 /* main execution loop */
3190 static void gui_update(void *opaque
)
3192 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3193 DisplayState
*ds
= opaque
;
3194 DisplayChangeListener
*dcl
= ds
->listeners
;
3198 while (dcl
!= NULL
) {
3199 if (dcl
->gui_timer_interval
&&
3200 dcl
->gui_timer_interval
< interval
)
3201 interval
= dcl
->gui_timer_interval
;
3204 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3207 static void nographic_update(void *opaque
)
3209 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3211 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3214 struct vm_change_state_entry
{
3215 VMChangeStateHandler
*cb
;
3217 QLIST_ENTRY (vm_change_state_entry
) entries
;
3220 static QLIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3222 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3225 VMChangeStateEntry
*e
;
3227 e
= qemu_mallocz(sizeof (*e
));
3231 QLIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3235 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3237 QLIST_REMOVE (e
, entries
);
3241 static void vm_state_notify(int running
, int reason
)
3243 VMChangeStateEntry
*e
;
3245 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3246 e
->cb(e
->opaque
, running
, reason
);
3250 static void resume_all_vcpus(void);
3251 static void pause_all_vcpus(void);
3258 vm_state_notify(1, 0);
3259 qemu_rearm_alarm_timer(alarm_timer
);
3264 /* reset/shutdown handler */
3266 typedef struct QEMUResetEntry
{
3267 QTAILQ_ENTRY(QEMUResetEntry
) entry
;
3268 QEMUResetHandler
*func
;
3272 static QTAILQ_HEAD(reset_handlers
, QEMUResetEntry
) reset_handlers
=
3273 QTAILQ_HEAD_INITIALIZER(reset_handlers
);
3274 static int reset_requested
;
3275 static int shutdown_requested
;
3276 static int powerdown_requested
;
3277 static int debug_requested
;
3278 static int vmstop_requested
;
3280 int qemu_shutdown_requested(void)
3282 int r
= shutdown_requested
;
3283 shutdown_requested
= 0;
3287 int qemu_reset_requested(void)
3289 int r
= reset_requested
;
3290 reset_requested
= 0;
3294 int qemu_powerdown_requested(void)
3296 int r
= powerdown_requested
;
3297 powerdown_requested
= 0;
3301 static int qemu_debug_requested(void)
3303 int r
= debug_requested
;
3304 debug_requested
= 0;
3308 static int qemu_vmstop_requested(void)
3310 int r
= vmstop_requested
;
3311 vmstop_requested
= 0;
3315 static void do_vm_stop(int reason
)
3318 cpu_disable_ticks();
3321 vm_state_notify(0, reason
);
3325 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3327 QEMUResetEntry
*re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3330 re
->opaque
= opaque
;
3331 QTAILQ_INSERT_TAIL(&reset_handlers
, re
, entry
);
3334 void qemu_unregister_reset(QEMUResetHandler
*func
, void *opaque
)
3338 QTAILQ_FOREACH(re
, &reset_handlers
, entry
) {
3339 if (re
->func
== func
&& re
->opaque
== opaque
) {
3340 QTAILQ_REMOVE(&reset_handlers
, re
, entry
);
3347 void qemu_system_reset(void)
3349 QEMUResetEntry
*re
, *nre
;
3351 /* reset all devices */
3352 QTAILQ_FOREACH_SAFE(re
, &reset_handlers
, entry
, nre
) {
3353 re
->func(re
->opaque
);
3357 void qemu_system_reset_request(void)
3360 shutdown_requested
= 1;
3362 reset_requested
= 1;
3364 qemu_notify_event();
3367 void qemu_system_shutdown_request(void)
3369 shutdown_requested
= 1;
3370 qemu_notify_event();
3373 void qemu_system_powerdown_request(void)
3375 powerdown_requested
= 1;
3376 qemu_notify_event();
3379 #ifdef CONFIG_IOTHREAD
3380 static void qemu_system_vmstop_request(int reason
)
3382 vmstop_requested
= reason
;
3383 qemu_notify_event();
3388 static int io_thread_fd
= -1;
3390 static void qemu_event_increment(void)
3392 static const char byte
= 0;
3394 if (io_thread_fd
== -1)
3397 write(io_thread_fd
, &byte
, sizeof(byte
));
3400 static void qemu_event_read(void *opaque
)
3402 int fd
= (unsigned long)opaque
;
3405 /* Drain the notify pipe */
3408 len
= read(fd
, buffer
, sizeof(buffer
));
3409 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
3412 static int qemu_event_init(void)
3417 err
= qemu_pipe(fds
);
3421 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3425 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3429 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3430 (void *)(unsigned long)fds
[0]);
3432 io_thread_fd
= fds
[1];
3441 HANDLE qemu_event_handle
;
3443 static void dummy_event_handler(void *opaque
)
3447 static int qemu_event_init(void)
3449 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3450 if (!qemu_event_handle
) {
3451 fprintf(stderr
, "Failed CreateEvent: %ld\n", GetLastError());
3454 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3458 static void qemu_event_increment(void)
3460 if (!SetEvent(qemu_event_handle
)) {
3461 fprintf(stderr
, "qemu_event_increment: SetEvent failed: %ld\n",
3468 static int cpu_can_run(CPUState
*env
)
3477 #ifndef CONFIG_IOTHREAD
3478 static int qemu_init_main_loop(void)
3480 return qemu_event_init();
3483 void qemu_init_vcpu(void *_env
)
3485 CPUState
*env
= _env
;
3487 env
->nr_cores
= smp_cores
;
3488 env
->nr_threads
= smp_threads
;
3494 int qemu_cpu_self(void *env
)
3499 static void resume_all_vcpus(void)
3503 static void pause_all_vcpus(void)
3507 void qemu_cpu_kick(void *env
)
3512 void qemu_notify_event(void)
3514 CPUState
*env
= cpu_single_env
;
3521 void qemu_mutex_lock_iothread(void) {}
3522 void qemu_mutex_unlock_iothread(void) {}
3524 void vm_stop(int reason
)
3529 #else /* CONFIG_IOTHREAD */
3531 #include "qemu-thread.h"
3533 QemuMutex qemu_global_mutex
;
3534 static QemuMutex qemu_fair_mutex
;
3536 static QemuThread io_thread
;
3538 static QemuThread
*tcg_cpu_thread
;
3539 static QemuCond
*tcg_halt_cond
;
3541 static int qemu_system_ready
;
3543 static QemuCond qemu_cpu_cond
;
3545 static QemuCond qemu_system_cond
;
3546 static QemuCond qemu_pause_cond
;
3548 static void block_io_signals(void);
3549 static void unblock_io_signals(void);
3550 static int tcg_has_work(void);
3552 static int qemu_init_main_loop(void)
3556 ret
= qemu_event_init();
3560 qemu_cond_init(&qemu_pause_cond
);
3561 qemu_mutex_init(&qemu_fair_mutex
);
3562 qemu_mutex_init(&qemu_global_mutex
);
3563 qemu_mutex_lock(&qemu_global_mutex
);
3565 unblock_io_signals();
3566 qemu_thread_self(&io_thread
);
3571 static void qemu_wait_io_event(CPUState
*env
)
3573 while (!tcg_has_work())
3574 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3576 qemu_mutex_unlock(&qemu_global_mutex
);
3579 * Users of qemu_global_mutex can be starved, having no chance
3580 * to acquire it since this path will get to it first.
3581 * So use another lock to provide fairness.
3583 qemu_mutex_lock(&qemu_fair_mutex
);
3584 qemu_mutex_unlock(&qemu_fair_mutex
);
3586 qemu_mutex_lock(&qemu_global_mutex
);
3590 qemu_cond_signal(&qemu_pause_cond
);
3594 static int qemu_cpu_exec(CPUState
*env
);
3596 static void *kvm_cpu_thread_fn(void *arg
)
3598 CPUState
*env
= arg
;
3601 qemu_thread_self(env
->thread
);
3605 /* signal CPU creation */
3606 qemu_mutex_lock(&qemu_global_mutex
);
3608 qemu_cond_signal(&qemu_cpu_cond
);
3610 /* and wait for machine initialization */
3611 while (!qemu_system_ready
)
3612 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3615 if (cpu_can_run(env
))
3617 qemu_wait_io_event(env
);
3623 static void tcg_cpu_exec(void);
3625 static void *tcg_cpu_thread_fn(void *arg
)
3627 CPUState
*env
= arg
;
3630 qemu_thread_self(env
->thread
);
3632 /* signal CPU creation */
3633 qemu_mutex_lock(&qemu_global_mutex
);
3634 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
3636 qemu_cond_signal(&qemu_cpu_cond
);
3638 /* and wait for machine initialization */
3639 while (!qemu_system_ready
)
3640 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3644 qemu_wait_io_event(cur_cpu
);
3650 void qemu_cpu_kick(void *_env
)
3652 CPUState
*env
= _env
;
3653 qemu_cond_broadcast(env
->halt_cond
);
3655 qemu_thread_signal(env
->thread
, SIGUSR1
);
3658 int qemu_cpu_self(void *_env
)
3660 CPUState
*env
= _env
;
3663 qemu_thread_self(&this);
3665 return qemu_thread_equal(&this, env
->thread
);
3668 static void cpu_signal(int sig
)
3671 cpu_exit(cpu_single_env
);
3674 static void block_io_signals(void)
3677 struct sigaction sigact
;
3680 sigaddset(&set
, SIGUSR2
);
3681 sigaddset(&set
, SIGIO
);
3682 sigaddset(&set
, SIGALRM
);
3683 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3686 sigaddset(&set
, SIGUSR1
);
3687 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3689 memset(&sigact
, 0, sizeof(sigact
));
3690 sigact
.sa_handler
= cpu_signal
;
3691 sigaction(SIGUSR1
, &sigact
, NULL
);
3694 static void unblock_io_signals(void)
3699 sigaddset(&set
, SIGUSR2
);
3700 sigaddset(&set
, SIGIO
);
3701 sigaddset(&set
, SIGALRM
);
3702 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3705 sigaddset(&set
, SIGUSR1
);
3706 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3709 static void qemu_signal_lock(unsigned int msecs
)
3711 qemu_mutex_lock(&qemu_fair_mutex
);
3713 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
3714 qemu_thread_signal(tcg_cpu_thread
, SIGUSR1
);
3715 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
3718 qemu_mutex_unlock(&qemu_fair_mutex
);
3721 void qemu_mutex_lock_iothread(void)
3723 if (kvm_enabled()) {
3724 qemu_mutex_lock(&qemu_fair_mutex
);
3725 qemu_mutex_lock(&qemu_global_mutex
);
3726 qemu_mutex_unlock(&qemu_fair_mutex
);
3728 qemu_signal_lock(100);
3731 void qemu_mutex_unlock_iothread(void)
3733 qemu_mutex_unlock(&qemu_global_mutex
);
3736 static int all_vcpus_paused(void)
3738 CPUState
*penv
= first_cpu
;
3743 penv
= (CPUState
*)penv
->next_cpu
;
3749 static void pause_all_vcpus(void)
3751 CPUState
*penv
= first_cpu
;
3755 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3756 qemu_cpu_kick(penv
);
3757 penv
= (CPUState
*)penv
->next_cpu
;
3760 while (!all_vcpus_paused()) {
3761 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
3764 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3765 penv
= (CPUState
*)penv
->next_cpu
;
3770 static void resume_all_vcpus(void)
3772 CPUState
*penv
= first_cpu
;
3777 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3778 qemu_cpu_kick(penv
);
3779 penv
= (CPUState
*)penv
->next_cpu
;
3783 static void tcg_init_vcpu(void *_env
)
3785 CPUState
*env
= _env
;
3786 /* share a single thread for all cpus with TCG */
3787 if (!tcg_cpu_thread
) {
3788 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3789 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3790 qemu_cond_init(env
->halt_cond
);
3791 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
3792 while (env
->created
== 0)
3793 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3794 tcg_cpu_thread
= env
->thread
;
3795 tcg_halt_cond
= env
->halt_cond
;
3797 env
->thread
= tcg_cpu_thread
;
3798 env
->halt_cond
= tcg_halt_cond
;
3802 static void kvm_start_vcpu(CPUState
*env
)
3804 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3805 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3806 qemu_cond_init(env
->halt_cond
);
3807 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
3808 while (env
->created
== 0)
3809 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3812 void qemu_init_vcpu(void *_env
)
3814 CPUState
*env
= _env
;
3816 env
->nr_cores
= smp_cores
;
3817 env
->nr_threads
= smp_threads
;
3819 kvm_start_vcpu(env
);
3824 void qemu_notify_event(void)
3826 qemu_event_increment();
3829 void vm_stop(int reason
)
3832 qemu_thread_self(&me
);
3834 if (!qemu_thread_equal(&me
, &io_thread
)) {
3835 qemu_system_vmstop_request(reason
);
3837 * FIXME: should not return to device code in case
3838 * vm_stop() has been requested.
3840 if (cpu_single_env
) {
3841 cpu_exit(cpu_single_env
);
3842 cpu_single_env
->stop
= 1;
3853 static void host_main_loop_wait(int *timeout
)
3859 /* XXX: need to suppress polling by better using win32 events */
3861 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
3862 ret
|= pe
->func(pe
->opaque
);
3866 WaitObjects
*w
= &wait_objects
;
3868 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
3869 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
3870 if (w
->func
[ret
- WAIT_OBJECT_0
])
3871 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
3873 /* Check for additional signaled events */
3874 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
3876 /* Check if event is signaled */
3877 ret2
= WaitForSingleObject(w
->events
[i
], 0);
3878 if(ret2
== WAIT_OBJECT_0
) {
3880 w
->func
[i
](w
->opaque
[i
]);
3881 } else if (ret2
== WAIT_TIMEOUT
) {
3883 err
= GetLastError();
3884 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
3887 } else if (ret
== WAIT_TIMEOUT
) {
3889 err
= GetLastError();
3890 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
3897 static void host_main_loop_wait(int *timeout
)
3902 void main_loop_wait(int timeout
)
3904 IOHandlerRecord
*ioh
;
3905 fd_set rfds
, wfds
, xfds
;
3909 qemu_bh_update_timeout(&timeout
);
3911 host_main_loop_wait(&timeout
);
3913 /* poll any events */
3914 /* XXX: separate device handlers from system ones */
3919 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3923 (!ioh
->fd_read_poll
||
3924 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
3925 FD_SET(ioh
->fd
, &rfds
);
3929 if (ioh
->fd_write
) {
3930 FD_SET(ioh
->fd
, &wfds
);
3936 tv
.tv_sec
= timeout
/ 1000;
3937 tv
.tv_usec
= (timeout
% 1000) * 1000;
3939 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
3941 qemu_mutex_unlock_iothread();
3942 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
3943 qemu_mutex_lock_iothread();
3945 IOHandlerRecord
**pioh
;
3947 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3948 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
3949 ioh
->fd_read(ioh
->opaque
);
3951 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
3952 ioh
->fd_write(ioh
->opaque
);
3956 /* remove deleted IO handlers */
3957 pioh
= &first_io_handler
;
3968 slirp_select_poll(&rfds
, &wfds
, &xfds
, (ret
< 0));
3970 /* rearm timer, if not periodic */
3971 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
3972 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
3973 qemu_rearm_alarm_timer(alarm_timer
);
3976 /* vm time timers */
3978 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
3979 qemu_run_timers(&active_timers
[QEMU_CLOCK_VIRTUAL
],
3980 qemu_get_clock(vm_clock
));
3983 /* real time timers */
3984 qemu_run_timers(&active_timers
[QEMU_CLOCK_REALTIME
],
3985 qemu_get_clock(rt_clock
));
3987 qemu_run_timers(&active_timers
[QEMU_CLOCK_HOST
],
3988 qemu_get_clock(host_clock
));
3990 /* Check bottom-halves last in case any of the earlier events triggered
3996 static int qemu_cpu_exec(CPUState
*env
)
3999 #ifdef CONFIG_PROFILER
4003 #ifdef CONFIG_PROFILER
4004 ti
= profile_getclock();
4009 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
4010 env
->icount_decr
.u16
.low
= 0;
4011 env
->icount_extra
= 0;
4012 count
= qemu_next_deadline();
4013 count
= (count
+ (1 << icount_time_shift
) - 1)
4014 >> icount_time_shift
;
4015 qemu_icount
+= count
;
4016 decr
= (count
> 0xffff) ? 0xffff : count
;
4018 env
->icount_decr
.u16
.low
= decr
;
4019 env
->icount_extra
= count
;
4021 ret
= cpu_exec(env
);
4022 #ifdef CONFIG_PROFILER
4023 qemu_time
+= profile_getclock() - ti
;
4026 /* Fold pending instructions back into the
4027 instruction counter, and clear the interrupt flag. */
4028 qemu_icount
-= (env
->icount_decr
.u16
.low
4029 + env
->icount_extra
);
4030 env
->icount_decr
.u32
= 0;
4031 env
->icount_extra
= 0;
4036 static void tcg_cpu_exec(void)
4040 if (next_cpu
== NULL
)
4041 next_cpu
= first_cpu
;
4042 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
4043 CPUState
*env
= cur_cpu
= next_cpu
;
4047 if (timer_alarm_pending
) {
4048 timer_alarm_pending
= 0;
4051 if (cpu_can_run(env
))
4052 ret
= qemu_cpu_exec(env
);
4053 if (ret
== EXCP_DEBUG
) {
4054 gdb_set_stop_cpu(env
);
4055 debug_requested
= 1;
4061 static int cpu_has_work(CPUState
*env
)
4069 if (qemu_cpu_has_work(env
))
4074 static int tcg_has_work(void)
4078 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4079 if (cpu_has_work(env
))
4084 static int qemu_calculate_timeout(void)
4086 #ifndef CONFIG_IOTHREAD
4091 else if (tcg_has_work())
4093 else if (!use_icount
)
4096 /* XXX: use timeout computed from timers */
4099 /* Advance virtual time to the next event. */
4100 if (use_icount
== 1) {
4101 /* When not using an adaptive execution frequency
4102 we tend to get badly out of sync with real time,
4103 so just delay for a reasonable amount of time. */
4106 delta
= cpu_get_icount() - cpu_get_clock();
4109 /* If virtual time is ahead of real time then just
4111 timeout
= (delta
/ 1000000) + 1;
4113 /* Wait for either IO to occur or the next
4115 add
= qemu_next_deadline();
4116 /* We advance the timer before checking for IO.
4117 Limit the amount we advance so that early IO
4118 activity won't get the guest too far ahead. */
4122 add
= (add
+ (1 << icount_time_shift
) - 1)
4123 >> icount_time_shift
;
4125 timeout
= delta
/ 1000000;
4132 #else /* CONFIG_IOTHREAD */
4137 static int vm_can_run(void)
4139 if (powerdown_requested
)
4141 if (reset_requested
)
4143 if (shutdown_requested
)
4145 if (debug_requested
)
4150 qemu_irq qemu_system_powerdown
;
4152 static void main_loop(void)
4156 #ifdef CONFIG_IOTHREAD
4157 qemu_system_ready
= 1;
4158 qemu_cond_broadcast(&qemu_system_cond
);
4163 #ifdef CONFIG_PROFILER
4166 #ifndef CONFIG_IOTHREAD
4169 #ifdef CONFIG_PROFILER
4170 ti
= profile_getclock();
4172 main_loop_wait(qemu_calculate_timeout());
4173 #ifdef CONFIG_PROFILER
4174 dev_time
+= profile_getclock() - ti
;
4176 } while (vm_can_run());
4178 if (qemu_debug_requested()) {
4179 monitor_protocol_event(QEVENT_DEBUG
, NULL
);
4180 vm_stop(EXCP_DEBUG
);
4182 if (qemu_shutdown_requested()) {
4183 monitor_protocol_event(QEVENT_SHUTDOWN
, NULL
);
4190 if (qemu_reset_requested()) {
4191 monitor_protocol_event(QEVENT_RESET
, NULL
);
4193 qemu_system_reset();
4196 if (qemu_powerdown_requested()) {
4197 monitor_protocol_event(QEVENT_POWERDOWN
, NULL
);
4198 qemu_irq_raise(qemu_system_powerdown
);
4200 if ((r
= qemu_vmstop_requested())) {
4201 monitor_protocol_event(QEVENT_STOP
, NULL
);
4208 static void version(void)
4210 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4213 static void help(int exitcode
)
4216 printf("usage: %s [options] [disk_image]\n"
4218 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4220 #define DEF(option, opt_arg, opt_enum, opt_help) \
4222 #define DEFHEADING(text) stringify(text) "\n"
4223 #include "qemu-options.h"
4228 "During emulation, the following keys are useful:\n"
4229 "ctrl-alt-f toggle full screen\n"
4230 "ctrl-alt-n switch to virtual console 'n'\n"
4231 "ctrl-alt toggle mouse and keyboard grab\n"
4233 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4238 DEFAULT_NETWORK_SCRIPT
,
4239 DEFAULT_NETWORK_DOWN_SCRIPT
,
4241 DEFAULT_GDBSTUB_PORT
,
4246 #define HAS_ARG 0x0001
4249 #define DEF(option, opt_arg, opt_enum, opt_help) \
4251 #define DEFHEADING(text)
4252 #include "qemu-options.h"
4258 typedef struct QEMUOption
{
4264 static const QEMUOption qemu_options
[] = {
4265 { "h", 0, QEMU_OPTION_h
},
4266 #define DEF(option, opt_arg, opt_enum, opt_help) \
4267 { option, opt_arg, opt_enum },
4268 #define DEFHEADING(text)
4269 #include "qemu-options.h"
4277 struct soundhw soundhw
[] = {
4278 #ifdef HAS_AUDIO_CHOICE
4279 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4285 { .init_isa
= pcspk_audio_init
}
4292 "Creative Sound Blaster 16",
4295 { .init_isa
= SB16_init
}
4299 #ifdef CONFIG_CS4231A
4305 { .init_isa
= cs4231a_init
}
4313 "Yamaha YMF262 (OPL3)",
4315 "Yamaha YM3812 (OPL2)",
4319 { .init_isa
= Adlib_init
}
4326 "Gravis Ultrasound GF1",
4329 { .init_isa
= GUS_init
}
4336 "Intel 82801AA AC97 Audio",
4339 { .init_pci
= ac97_init
}
4343 #ifdef CONFIG_ES1370
4346 "ENSONIQ AudioPCI ES1370",
4349 { .init_pci
= es1370_init
}
4353 #endif /* HAS_AUDIO_CHOICE */
4355 { NULL
, NULL
, 0, 0, { NULL
} }
4358 static void select_soundhw (const char *optarg
)
4362 if (*optarg
== '?') {
4365 printf ("Valid sound card names (comma separated):\n");
4366 for (c
= soundhw
; c
->name
; ++c
) {
4367 printf ("%-11s %s\n", c
->name
, c
->descr
);
4369 printf ("\n-soundhw all will enable all of the above\n");
4370 exit (*optarg
!= '?');
4378 if (!strcmp (optarg
, "all")) {
4379 for (c
= soundhw
; c
->name
; ++c
) {
4387 e
= strchr (p
, ',');
4388 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4390 for (c
= soundhw
; c
->name
; ++c
) {
4391 if (!strncmp (c
->name
, p
, l
) && !c
->name
[l
]) {
4400 "Unknown sound card name (too big to show)\n");
4403 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4408 p
+= l
+ (e
!= NULL
);
4412 goto show_valid_cards
;
4417 static void select_vgahw (const char *p
)
4422 vga_interface_type
= VGA_NONE
;
4423 if (strstart(p
, "std", &opts
)) {
4424 vga_interface_type
= VGA_STD
;
4425 } else if (strstart(p
, "cirrus", &opts
)) {
4426 vga_interface_type
= VGA_CIRRUS
;
4427 } else if (strstart(p
, "vmware", &opts
)) {
4428 vga_interface_type
= VGA_VMWARE
;
4429 } else if (strstart(p
, "xenfb", &opts
)) {
4430 vga_interface_type
= VGA_XENFB
;
4431 } else if (!strstart(p
, "none", &opts
)) {
4433 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4437 const char *nextopt
;
4439 if (strstart(opts
, ",retrace=", &nextopt
)) {
4441 if (strstart(opts
, "dumb", &nextopt
))
4442 vga_retrace_method
= VGA_RETRACE_DUMB
;
4443 else if (strstart(opts
, "precise", &nextopt
))
4444 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4445 else goto invalid_vga
;
4446 } else goto invalid_vga
;
4452 static int balloon_parse(const char *arg
)
4456 if (strcmp(arg
, "none") == 0) {
4460 if (!strncmp(arg
, "virtio", 6)) {
4461 if (arg
[6] == ',') {
4462 /* have params -> parse them */
4463 opts
= qemu_opts_parse(&qemu_device_opts
, arg
+7, NULL
);
4467 /* create empty opts */
4468 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4470 qemu_opt_set(opts
, "driver", "virtio-balloon-pci");
4479 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4481 exit(STATUS_CONTROL_C_EXIT
);
4486 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4490 if(strlen(str
) != 36)
4493 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4494 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4495 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4501 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4509 static void termsig_handler(int signal
)
4511 qemu_system_shutdown_request();
4514 static void sigchld_handler(int signal
)
4516 waitpid(-1, NULL
, WNOHANG
);
4519 static void sighandler_setup(void)
4521 struct sigaction act
;
4523 memset(&act
, 0, sizeof(act
));
4524 act
.sa_handler
= termsig_handler
;
4525 sigaction(SIGINT
, &act
, NULL
);
4526 sigaction(SIGHUP
, &act
, NULL
);
4527 sigaction(SIGTERM
, &act
, NULL
);
4529 act
.sa_handler
= sigchld_handler
;
4530 act
.sa_flags
= SA_NOCLDSTOP
;
4531 sigaction(SIGCHLD
, &act
, NULL
);
4537 /* Look for support files in the same directory as the executable. */
4538 static char *find_datadir(const char *argv0
)
4544 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
4551 while (p
!= buf
&& *p
!= '\\')
4554 if (access(buf
, R_OK
) == 0) {
4555 return qemu_strdup(buf
);
4561 /* Find a likely location for support files using the location of the binary.
4562 For installed binaries this will be "$bindir/../share/qemu". When
4563 running from the build tree this will be "$bindir/../pc-bios". */
4564 #define SHARE_SUFFIX "/share/qemu"
4565 #define BUILD_SUFFIX "/pc-bios"
4566 static char *find_datadir(const char *argv0
)
4574 #if defined(__linux__)
4577 len
= readlink("/proc/self/exe", buf
, sizeof(buf
) - 1);
4583 #elif defined(__FreeBSD__)
4586 len
= readlink("/proc/curproc/file", buf
, sizeof(buf
) - 1);
4593 /* If we don't have any way of figuring out the actual executable
4594 location then try argv[0]. */
4596 p
= realpath(argv0
, buf
);
4604 max_len
= strlen(dir
) +
4605 MAX(strlen(SHARE_SUFFIX
), strlen(BUILD_SUFFIX
)) + 1;
4606 res
= qemu_mallocz(max_len
);
4607 snprintf(res
, max_len
, "%s%s", dir
, SHARE_SUFFIX
);
4608 if (access(res
, R_OK
)) {
4609 snprintf(res
, max_len
, "%s%s", dir
, BUILD_SUFFIX
);
4610 if (access(res
, R_OK
)) {
4622 char *qemu_find_file(int type
, const char *name
)
4628 /* If name contains path separators then try it as a straight path. */
4629 if ((strchr(name
, '/') || strchr(name
, '\\'))
4630 && access(name
, R_OK
) == 0) {
4631 return qemu_strdup(name
);
4634 case QEMU_FILE_TYPE_BIOS
:
4637 case QEMU_FILE_TYPE_KEYMAP
:
4638 subdir
= "keymaps/";
4643 len
= strlen(data_dir
) + strlen(name
) + strlen(subdir
) + 2;
4644 buf
= qemu_mallocz(len
);
4645 snprintf(buf
, len
, "%s/%s%s", data_dir
, subdir
, name
);
4646 if (access(buf
, R_OK
)) {
4653 static int device_init_func(QemuOpts
*opts
, void *opaque
)
4657 dev
= qdev_device_add(opts
);
4663 static int chardev_init_func(QemuOpts
*opts
, void *opaque
)
4665 CharDriverState
*chr
;
4667 chr
= qemu_chr_open_opts(opts
, NULL
);
4673 static int mon_init_func(QemuOpts
*opts
, void *opaque
)
4675 CharDriverState
*chr
;
4676 const char *chardev
;
4680 mode
= qemu_opt_get(opts
, "mode");
4684 if (strcmp(mode
, "readline") == 0) {
4685 flags
= MONITOR_USE_READLINE
;
4686 } else if (strcmp(mode
, "control") == 0) {
4687 flags
= MONITOR_USE_CONTROL
;
4689 fprintf(stderr
, "unknown monitor mode \"%s\"\n", mode
);
4693 if (qemu_opt_get_bool(opts
, "default", 0))
4694 flags
|= MONITOR_IS_DEFAULT
;
4696 chardev
= qemu_opt_get(opts
, "chardev");
4697 chr
= qemu_chr_find(chardev
);
4699 fprintf(stderr
, "chardev \"%s\" not found\n", chardev
);
4703 monitor_init(chr
, flags
);
4707 static void monitor_parse(const char *optarg
, const char *mode
)
4709 static int monitor_device_index
= 0;
4715 if (strstart(optarg
, "chardev:", &p
)) {
4716 snprintf(label
, sizeof(label
), "%s", p
);
4718 if (monitor_device_index
) {
4719 snprintf(label
, sizeof(label
), "monitor%d",
4720 monitor_device_index
);
4722 snprintf(label
, sizeof(label
), "monitor");
4725 opts
= qemu_chr_parse_compat(label
, optarg
);
4727 fprintf(stderr
, "parse error: %s\n", optarg
);
4732 opts
= qemu_opts_create(&qemu_mon_opts
, label
, 1);
4734 fprintf(stderr
, "duplicate chardev: %s\n", label
);
4737 qemu_opt_set(opts
, "mode", mode
);
4738 qemu_opt_set(opts
, "chardev", label
);
4740 qemu_opt_set(opts
, "default", "on");
4741 monitor_device_index
++;
4744 struct device_config
{
4746 DEV_USB
, /* -usbdevice */
4748 DEV_SERIAL
, /* -serial */
4749 DEV_PARALLEL
, /* -parallel */
4750 DEV_VIRTCON
, /* -virtioconsole */
4751 DEV_DEBUGCON
, /* -debugcon */
4753 const char *cmdline
;
4754 QTAILQ_ENTRY(device_config
) next
;
4756 QTAILQ_HEAD(, device_config
) device_configs
= QTAILQ_HEAD_INITIALIZER(device_configs
);
4758 static void add_device_config(int type
, const char *cmdline
)
4760 struct device_config
*conf
;
4762 conf
= qemu_mallocz(sizeof(*conf
));
4764 conf
->cmdline
= cmdline
;
4765 QTAILQ_INSERT_TAIL(&device_configs
, conf
, next
);
4768 static int foreach_device_config(int type
, int (*func
)(const char *cmdline
))
4770 struct device_config
*conf
;
4773 QTAILQ_FOREACH(conf
, &device_configs
, next
) {
4774 if (conf
->type
!= type
)
4776 rc
= func(conf
->cmdline
);
4783 static int serial_parse(const char *devname
)
4785 static int index
= 0;
4788 if (strcmp(devname
, "none") == 0)
4790 if (index
== MAX_SERIAL_PORTS
) {
4791 fprintf(stderr
, "qemu: too many serial ports\n");
4794 snprintf(label
, sizeof(label
), "serial%d", index
);
4795 serial_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4796 if (!serial_hds
[index
]) {
4797 fprintf(stderr
, "qemu: could not open serial device '%s': %s\n",
4798 devname
, strerror(errno
));
4805 static int parallel_parse(const char *devname
)
4807 static int index
= 0;
4810 if (strcmp(devname
, "none") == 0)
4812 if (index
== MAX_PARALLEL_PORTS
) {
4813 fprintf(stderr
, "qemu: too many parallel ports\n");
4816 snprintf(label
, sizeof(label
), "parallel%d", index
);
4817 parallel_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4818 if (!parallel_hds
[index
]) {
4819 fprintf(stderr
, "qemu: could not open parallel device '%s': %s\n",
4820 devname
, strerror(errno
));
4827 static int virtcon_parse(const char *devname
)
4829 static int index
= 0;
4832 if (strcmp(devname
, "none") == 0)
4834 if (index
== MAX_VIRTIO_CONSOLES
) {
4835 fprintf(stderr
, "qemu: too many virtio consoles\n");
4838 snprintf(label
, sizeof(label
), "virtcon%d", index
);
4839 virtcon_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4840 if (!virtcon_hds
[index
]) {
4841 fprintf(stderr
, "qemu: could not open virtio console '%s': %s\n",
4842 devname
, strerror(errno
));
4849 static int debugcon_parse(const char *devname
)
4853 if (!qemu_chr_open("debugcon", devname
, NULL
)) {
4856 opts
= qemu_opts_create(&qemu_device_opts
, "debugcon", 1);
4858 fprintf(stderr
, "qemu: already have a debugcon device\n");
4861 qemu_opt_set(opts
, "driver", "isa-debugcon");
4862 qemu_opt_set(opts
, "chardev", "debugcon");
4866 int main(int argc
, char **argv
, char **envp
)
4868 const char *gdbstub_dev
= NULL
;
4869 uint32_t boot_devices_bitmap
= 0;
4871 int snapshot
, linux_boot
, net_boot
;
4872 const char *initrd_filename
;
4873 const char *kernel_filename
, *kernel_cmdline
;
4874 char boot_devices
[33] = "cad"; /* default to HD->floppy->CD-ROM */
4876 DisplayChangeListener
*dcl
;
4877 int cyls
, heads
, secs
, translation
;
4878 QemuOpts
*hda_opts
= NULL
, *opts
;
4880 const char *r
, *optarg
;
4881 const char *loadvm
= NULL
;
4882 QEMUMachine
*machine
;
4883 const char *cpu_model
;
4888 const char *pid_file
= NULL
;
4889 const char *incoming
= NULL
;
4892 struct passwd
*pwd
= NULL
;
4893 const char *chroot_dir
= NULL
;
4894 const char *run_as
= NULL
;
4897 int show_vnc_port
= 0;
4901 qemu_errors_to_file(stderr
);
4902 qemu_cache_utils_init(envp
);
4904 QLIST_INIT (&vm_change_state_head
);
4907 struct sigaction act
;
4908 sigfillset(&act
.sa_mask
);
4910 act
.sa_handler
= SIG_IGN
;
4911 sigaction(SIGPIPE
, &act
, NULL
);
4914 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4915 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4916 QEMU to run on a single CPU */
4921 h
= GetCurrentProcess();
4922 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4923 for(i
= 0; i
< 32; i
++) {
4924 if (mask
& (1 << i
))
4929 SetProcessAffinityMask(h
, mask
);
4935 module_call_init(MODULE_INIT_MACHINE
);
4936 machine
= find_default_machine();
4938 initrd_filename
= NULL
;
4941 kernel_filename
= NULL
;
4942 kernel_cmdline
= "";
4943 cyls
= heads
= secs
= 0;
4944 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4946 for (i
= 0; i
< MAX_NODES
; i
++) {
4948 node_cpumask
[i
] = 0;
4963 hda_opts
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
4965 const QEMUOption
*popt
;
4968 /* Treat --foo the same as -foo. */
4971 popt
= qemu_options
;
4974 fprintf(stderr
, "%s: invalid option -- '%s'\n",
4978 if (!strcmp(popt
->name
, r
+ 1))
4982 if (popt
->flags
& HAS_ARG
) {
4983 if (optind
>= argc
) {
4984 fprintf(stderr
, "%s: option '%s' requires an argument\n",
4988 optarg
= argv
[optind
++];
4993 switch(popt
->index
) {
4995 machine
= find_machine(optarg
);
4998 printf("Supported machines are:\n");
4999 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5001 printf("%-10s %s (alias of %s)\n",
5002 m
->alias
, m
->desc
, m
->name
);
5003 printf("%-10s %s%s\n",
5005 m
->is_default
? " (default)" : "");
5007 exit(*optarg
!= '?');
5010 case QEMU_OPTION_cpu
:
5011 /* hw initialization will check this */
5012 if (*optarg
== '?') {
5013 /* XXX: implement xxx_cpu_list for targets that still miss it */
5014 #if defined(cpu_list)
5015 cpu_list(stdout
, &fprintf
);
5022 case QEMU_OPTION_initrd
:
5023 initrd_filename
= optarg
;
5025 case QEMU_OPTION_hda
:
5027 hda_opts
= drive_add(optarg
, HD_ALIAS
, 0);
5029 hda_opts
= drive_add(optarg
, HD_ALIAS
5030 ",cyls=%d,heads=%d,secs=%d%s",
5031 0, cyls
, heads
, secs
,
5032 translation
== BIOS_ATA_TRANSLATION_LBA
?
5034 translation
== BIOS_ATA_TRANSLATION_NONE
?
5035 ",trans=none" : "");
5037 case QEMU_OPTION_hdb
:
5038 case QEMU_OPTION_hdc
:
5039 case QEMU_OPTION_hdd
:
5040 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
5042 case QEMU_OPTION_drive
:
5043 drive_add(NULL
, "%s", optarg
);
5045 case QEMU_OPTION_set
:
5046 if (qemu_set_option(optarg
) != 0)
5049 case QEMU_OPTION_global
:
5050 if (qemu_global_option(optarg
) != 0)
5053 case QEMU_OPTION_mtdblock
:
5054 drive_add(optarg
, MTD_ALIAS
);
5056 case QEMU_OPTION_sd
:
5057 drive_add(optarg
, SD_ALIAS
);
5059 case QEMU_OPTION_pflash
:
5060 drive_add(optarg
, PFLASH_ALIAS
);
5062 case QEMU_OPTION_snapshot
:
5065 case QEMU_OPTION_hdachs
:
5069 cyls
= strtol(p
, (char **)&p
, 0);
5070 if (cyls
< 1 || cyls
> 16383)
5075 heads
= strtol(p
, (char **)&p
, 0);
5076 if (heads
< 1 || heads
> 16)
5081 secs
= strtol(p
, (char **)&p
, 0);
5082 if (secs
< 1 || secs
> 63)
5086 if (!strcmp(p
, "none"))
5087 translation
= BIOS_ATA_TRANSLATION_NONE
;
5088 else if (!strcmp(p
, "lba"))
5089 translation
= BIOS_ATA_TRANSLATION_LBA
;
5090 else if (!strcmp(p
, "auto"))
5091 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5094 } else if (*p
!= '\0') {
5096 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5099 if (hda_opts
!= NULL
) {
5101 snprintf(num
, sizeof(num
), "%d", cyls
);
5102 qemu_opt_set(hda_opts
, "cyls", num
);
5103 snprintf(num
, sizeof(num
), "%d", heads
);
5104 qemu_opt_set(hda_opts
, "heads", num
);
5105 snprintf(num
, sizeof(num
), "%d", secs
);
5106 qemu_opt_set(hda_opts
, "secs", num
);
5107 if (translation
== BIOS_ATA_TRANSLATION_LBA
)
5108 qemu_opt_set(hda_opts
, "trans", "lba");
5109 if (translation
== BIOS_ATA_TRANSLATION_NONE
)
5110 qemu_opt_set(hda_opts
, "trans", "none");
5114 case QEMU_OPTION_numa
:
5115 if (nb_numa_nodes
>= MAX_NODES
) {
5116 fprintf(stderr
, "qemu: too many NUMA nodes\n");
5121 case QEMU_OPTION_nographic
:
5122 display_type
= DT_NOGRAPHIC
;
5124 #ifdef CONFIG_CURSES
5125 case QEMU_OPTION_curses
:
5126 display_type
= DT_CURSES
;
5129 case QEMU_OPTION_portrait
:
5132 case QEMU_OPTION_kernel
:
5133 kernel_filename
= optarg
;
5135 case QEMU_OPTION_append
:
5136 kernel_cmdline
= optarg
;
5138 case QEMU_OPTION_cdrom
:
5139 drive_add(optarg
, CDROM_ALIAS
);
5141 case QEMU_OPTION_boot
:
5143 static const char * const params
[] = {
5144 "order", "once", "menu", NULL
5146 char buf
[sizeof(boot_devices
)];
5147 char *standard_boot_devices
;
5150 if (!strchr(optarg
, '=')) {
5152 pstrcpy(buf
, sizeof(buf
), optarg
);
5153 } else if (check_params(buf
, sizeof(buf
), params
, optarg
) < 0) {
5155 "qemu: unknown boot parameter '%s' in '%s'\n",
5161 get_param_value(buf
, sizeof(buf
), "order", optarg
)) {
5162 boot_devices_bitmap
= parse_bootdevices(buf
);
5163 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5166 if (get_param_value(buf
, sizeof(buf
),
5168 boot_devices_bitmap
|= parse_bootdevices(buf
);
5169 standard_boot_devices
= qemu_strdup(boot_devices
);
5170 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5171 qemu_register_reset(restore_boot_devices
,
5172 standard_boot_devices
);
5174 if (get_param_value(buf
, sizeof(buf
),
5176 if (!strcmp(buf
, "on")) {
5178 } else if (!strcmp(buf
, "off")) {
5182 "qemu: invalid option value '%s'\n",
5190 case QEMU_OPTION_fda
:
5191 case QEMU_OPTION_fdb
:
5192 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
5195 case QEMU_OPTION_no_fd_bootchk
:
5199 case QEMU_OPTION_netdev
:
5200 if (net_client_parse(&qemu_netdev_opts
, optarg
) == -1) {
5204 case QEMU_OPTION_net
:
5205 if (net_client_parse(&qemu_net_opts
, optarg
) == -1) {
5210 case QEMU_OPTION_tftp
:
5211 legacy_tftp_prefix
= optarg
;
5213 case QEMU_OPTION_bootp
:
5214 legacy_bootp_filename
= optarg
;
5217 case QEMU_OPTION_smb
:
5218 if (net_slirp_smb(optarg
) < 0)
5222 case QEMU_OPTION_redir
:
5223 if (net_slirp_redir(optarg
) < 0)
5227 case QEMU_OPTION_bt
:
5228 add_device_config(DEV_BT
, optarg
);
5231 case QEMU_OPTION_audio_help
:
5235 case QEMU_OPTION_soundhw
:
5236 select_soundhw (optarg
);
5242 case QEMU_OPTION_version
:
5246 case QEMU_OPTION_m
: {
5250 value
= strtoul(optarg
, &ptr
, 10);
5252 case 0: case 'M': case 'm':
5259 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5263 /* On 32-bit hosts, QEMU is limited by virtual address space */
5264 if (value
> (2047 << 20) && HOST_LONG_BITS
== 32) {
5265 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5268 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5269 fprintf(stderr
, "qemu: ram size too large\n");
5278 const CPULogItem
*item
;
5280 mask
= cpu_str_to_log_mask(optarg
);
5282 printf("Log items (comma separated):\n");
5283 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5284 printf("%-10s %s\n", item
->name
, item
->help
);
5292 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5294 case QEMU_OPTION_gdb
:
5295 gdbstub_dev
= optarg
;
5300 case QEMU_OPTION_bios
:
5303 case QEMU_OPTION_singlestep
:
5310 keyboard_layout
= optarg
;
5312 case QEMU_OPTION_localtime
:
5315 case QEMU_OPTION_vga
:
5316 select_vgahw (optarg
);
5318 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5324 w
= strtol(p
, (char **)&p
, 10);
5327 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5333 h
= strtol(p
, (char **)&p
, 10);
5338 depth
= strtol(p
, (char **)&p
, 10);
5339 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5340 depth
!= 24 && depth
!= 32)
5342 } else if (*p
== '\0') {
5343 depth
= graphic_depth
;
5350 graphic_depth
= depth
;
5354 case QEMU_OPTION_echr
:
5357 term_escape_char
= strtol(optarg
, &r
, 0);
5359 printf("Bad argument to echr\n");
5362 case QEMU_OPTION_monitor
:
5363 monitor_parse(optarg
, "readline");
5364 default_monitor
= 0;
5366 case QEMU_OPTION_qmp
:
5367 monitor_parse(optarg
, "control");
5368 default_monitor
= 0;
5370 case QEMU_OPTION_mon
:
5371 opts
= qemu_opts_parse(&qemu_mon_opts
, optarg
, "chardev");
5373 fprintf(stderr
, "parse error: %s\n", optarg
);
5376 default_monitor
= 0;
5378 case QEMU_OPTION_chardev
:
5379 opts
= qemu_opts_parse(&qemu_chardev_opts
, optarg
, "backend");
5381 fprintf(stderr
, "parse error: %s\n", optarg
);
5385 case QEMU_OPTION_serial
:
5386 add_device_config(DEV_SERIAL
, optarg
);
5389 case QEMU_OPTION_watchdog
:
5392 "qemu: only one watchdog option may be given\n");
5397 case QEMU_OPTION_watchdog_action
:
5398 if (select_watchdog_action(optarg
) == -1) {
5399 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5403 case QEMU_OPTION_virtiocon
:
5404 add_device_config(DEV_VIRTCON
, optarg
);
5405 default_virtcon
= 0;
5407 case QEMU_OPTION_parallel
:
5408 add_device_config(DEV_PARALLEL
, optarg
);
5409 default_parallel
= 0;
5411 case QEMU_OPTION_debugcon
:
5412 add_device_config(DEV_DEBUGCON
, optarg
);
5414 case QEMU_OPTION_loadvm
:
5417 case QEMU_OPTION_full_screen
:
5421 case QEMU_OPTION_no_frame
:
5424 case QEMU_OPTION_alt_grab
:
5427 case QEMU_OPTION_ctrl_grab
:
5430 case QEMU_OPTION_no_quit
:
5433 case QEMU_OPTION_sdl
:
5434 display_type
= DT_SDL
;
5437 case QEMU_OPTION_pidfile
:
5441 case QEMU_OPTION_win2k_hack
:
5442 win2k_install_hack
= 1;
5444 case QEMU_OPTION_rtc_td_hack
:
5447 case QEMU_OPTION_acpitable
:
5448 if(acpi_table_add(optarg
) < 0) {
5449 fprintf(stderr
, "Wrong acpi table provided\n");
5453 case QEMU_OPTION_smbios
:
5454 if(smbios_entry_add(optarg
) < 0) {
5455 fprintf(stderr
, "Wrong smbios provided\n");
5461 case QEMU_OPTION_enable_kvm
:
5465 case QEMU_OPTION_usb
:
5468 case QEMU_OPTION_usbdevice
:
5470 add_device_config(DEV_USB
, optarg
);
5472 case QEMU_OPTION_device
:
5473 if (!qemu_opts_parse(&qemu_device_opts
, optarg
, "driver")) {
5477 case QEMU_OPTION_smp
:
5480 fprintf(stderr
, "Invalid number of CPUs\n");
5483 if (max_cpus
< smp_cpus
) {
5484 fprintf(stderr
, "maxcpus must be equal to or greater than "
5488 if (max_cpus
> 255) {
5489 fprintf(stderr
, "Unsupported number of maxcpus\n");
5493 case QEMU_OPTION_vnc
:
5494 display_type
= DT_VNC
;
5495 vnc_display
= optarg
;
5498 case QEMU_OPTION_no_acpi
:
5501 case QEMU_OPTION_no_hpet
:
5504 case QEMU_OPTION_balloon
:
5505 if (balloon_parse(optarg
) < 0) {
5506 fprintf(stderr
, "Unknown -balloon argument %s\n", optarg
);
5511 case QEMU_OPTION_no_reboot
:
5514 case QEMU_OPTION_no_shutdown
:
5517 case QEMU_OPTION_show_cursor
:
5520 case QEMU_OPTION_uuid
:
5521 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5522 fprintf(stderr
, "Fail to parse UUID string."
5523 " Wrong format.\n");
5528 case QEMU_OPTION_daemonize
:
5532 case QEMU_OPTION_option_rom
:
5533 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5534 fprintf(stderr
, "Too many option ROMs\n");
5537 option_rom
[nb_option_roms
] = optarg
;
5540 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5541 case QEMU_OPTION_semihosting
:
5542 semihosting_enabled
= 1;
5545 case QEMU_OPTION_name
:
5546 qemu_name
= qemu_strdup(optarg
);
5548 char *p
= strchr(qemu_name
, ',');
5551 if (strncmp(p
, "process=", 8)) {
5552 fprintf(stderr
, "Unknown subargument %s to -name", p
);
5560 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5561 case QEMU_OPTION_prom_env
:
5562 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5563 fprintf(stderr
, "Too many prom variables\n");
5566 prom_envs
[nb_prom_envs
] = optarg
;
5571 case QEMU_OPTION_old_param
:
5575 case QEMU_OPTION_clock
:
5576 configure_alarms(optarg
);
5578 case QEMU_OPTION_startdate
:
5579 configure_rtc_date_offset(optarg
, 1);
5581 case QEMU_OPTION_rtc
:
5582 opts
= qemu_opts_parse(&qemu_rtc_opts
, optarg
, NULL
);
5584 fprintf(stderr
, "parse error: %s\n", optarg
);
5587 configure_rtc(opts
);
5589 case QEMU_OPTION_tb_size
:
5590 tb_size
= strtol(optarg
, NULL
, 0);
5594 case QEMU_OPTION_icount
:
5596 if (strcmp(optarg
, "auto") == 0) {
5597 icount_time_shift
= -1;
5599 icount_time_shift
= strtol(optarg
, NULL
, 0);
5602 case QEMU_OPTION_incoming
:
5605 case QEMU_OPTION_nodefaults
:
5607 default_parallel
= 0;
5608 default_virtcon
= 0;
5609 default_monitor
= 0;
5617 case QEMU_OPTION_chroot
:
5618 chroot_dir
= optarg
;
5620 case QEMU_OPTION_runas
:
5625 case QEMU_OPTION_xen_domid
:
5626 xen_domid
= atoi(optarg
);
5628 case QEMU_OPTION_xen_create
:
5629 xen_mode
= XEN_CREATE
;
5631 case QEMU_OPTION_xen_attach
:
5632 xen_mode
= XEN_ATTACH
;
5635 case QEMU_OPTION_readconfig
:
5638 fp
= fopen(optarg
, "r");
5640 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5643 if (qemu_config_parse(fp
) != 0) {
5649 case QEMU_OPTION_writeconfig
:
5652 if (strcmp(optarg
, "-") == 0) {
5655 fp
= fopen(optarg
, "w");
5657 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5661 qemu_config_write(fp
);
5669 /* If no data_dir is specified then try to find it relative to the
5672 data_dir
= find_datadir(argv
[0]);
5674 /* If all else fails use the install patch specified when building. */
5676 data_dir
= CONFIG_QEMU_SHAREDIR
;
5680 * Default to max_cpus = smp_cpus, in case the user doesn't
5681 * specify a max_cpus value.
5684 max_cpus
= smp_cpus
;
5686 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5687 if (smp_cpus
> machine
->max_cpus
) {
5688 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5689 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5694 qemu_opts_foreach(&qemu_device_opts
, default_driver_check
, NULL
, 0);
5695 qemu_opts_foreach(&qemu_global_opts
, default_driver_check
, NULL
, 0);
5697 if (machine
->no_serial
) {
5700 if (machine
->no_parallel
) {
5701 default_parallel
= 0;
5703 if (!machine
->use_virtcon
) {
5704 default_virtcon
= 0;
5706 if (machine
->no_vga
) {
5709 if (machine
->no_floppy
) {
5712 if (machine
->no_cdrom
) {
5715 if (machine
->no_sdcard
) {
5719 if (display_type
== DT_NOGRAPHIC
) {
5720 if (default_parallel
)
5721 add_device_config(DEV_PARALLEL
, "null");
5722 if (default_serial
&& default_monitor
) {
5723 add_device_config(DEV_SERIAL
, "mon:stdio");
5724 } else if (default_virtcon
&& default_monitor
) {
5725 add_device_config(DEV_VIRTCON
, "mon:stdio");
5728 add_device_config(DEV_SERIAL
, "stdio");
5729 if (default_virtcon
)
5730 add_device_config(DEV_VIRTCON
, "stdio");
5731 if (default_monitor
)
5732 monitor_parse("stdio", "readline");
5736 add_device_config(DEV_SERIAL
, "vc:80Cx24C");
5737 if (default_parallel
)
5738 add_device_config(DEV_PARALLEL
, "vc:80Cx24C");
5739 if (default_monitor
)
5740 monitor_parse("vc:80Cx24C", "readline");
5741 if (default_virtcon
)
5742 add_device_config(DEV_VIRTCON
, "vc:80Cx24C");
5745 vga_interface_type
= VGA_CIRRUS
;
5747 if (qemu_opts_foreach(&qemu_chardev_opts
, chardev_init_func
, NULL
, 1) != 0)
5754 if (pipe(fds
) == -1)
5765 len
= read(fds
[0], &status
, 1);
5766 if (len
== -1 && (errno
== EINTR
))
5771 else if (status
== 1) {
5772 fprintf(stderr
, "Could not acquire pidfile: %s\n", strerror(errno
));
5780 qemu_set_cloexec(fds
[1]);
5792 signal(SIGTSTP
, SIG_IGN
);
5793 signal(SIGTTOU
, SIG_IGN
);
5794 signal(SIGTTIN
, SIG_IGN
);
5798 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5802 write(fds
[1], &status
, 1);
5805 fprintf(stderr
, "Could not acquire pid file: %s\n", strerror(errno
));
5809 if (kvm_enabled()) {
5812 ret
= kvm_init(smp_cpus
);
5814 fprintf(stderr
, "failed to initialize KVM\n");
5819 if (qemu_init_main_loop()) {
5820 fprintf(stderr
, "qemu_init_main_loop failed\n");
5823 linux_boot
= (kernel_filename
!= NULL
);
5825 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5826 fprintf(stderr
, "-append only allowed with -kernel option\n");
5830 if (!linux_boot
&& initrd_filename
!= NULL
) {
5831 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5836 /* Win32 doesn't support line-buffering and requires size >= 2 */
5837 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5840 if (init_timer_alarm() < 0) {
5841 fprintf(stderr
, "could not initialize alarm timer\n");
5844 if (use_icount
&& icount_time_shift
< 0) {
5846 /* 125MIPS seems a reasonable initial guess at the guest speed.
5847 It will be corrected fairly quickly anyway. */
5848 icount_time_shift
= 3;
5849 init_icount_adjust();
5856 if (net_init_clients() < 0) {
5860 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5861 net_set_boot_mask(net_boot
);
5863 /* init the bluetooth world */
5864 if (foreach_device_config(DEV_BT
, bt_parse
))
5867 /* init the memory */
5869 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5871 /* init the dynamic translator */
5872 cpu_exec_init_all(tb_size
* 1024 * 1024);
5874 bdrv_init_with_whitelist();
5878 if (default_cdrom
) {
5879 /* we always create the cdrom drive, even if no disk is there */
5880 drive_add(NULL
, CDROM_ALIAS
);
5883 if (default_floppy
) {
5884 /* we always create at least one floppy */
5885 drive_add(NULL
, FD_ALIAS
, 0);
5888 if (default_sdcard
) {
5889 /* we always create one sd slot, even if no card is in it */
5890 drive_add(NULL
, SD_ALIAS
);
5893 /* open the virtual block devices */
5895 qemu_opts_foreach(&qemu_drive_opts
, drive_enable_snapshot
, NULL
, 0);
5896 if (qemu_opts_foreach(&qemu_drive_opts
, drive_init_func
, machine
, 1) != 0)
5899 vmstate_register(0, &vmstate_timers
,&timers_state
);
5900 register_savevm_live("ram", 0, 3, NULL
, ram_save_live
, NULL
,
5903 if (nb_numa_nodes
> 0) {
5906 if (nb_numa_nodes
> smp_cpus
) {
5907 nb_numa_nodes
= smp_cpus
;
5910 /* If no memory size if given for any node, assume the default case
5911 * and distribute the available memory equally across all nodes
5913 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5914 if (node_mem
[i
] != 0)
5917 if (i
== nb_numa_nodes
) {
5918 uint64_t usedmem
= 0;
5920 /* On Linux, the each node's border has to be 8MB aligned,
5921 * the final node gets the rest.
5923 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
5924 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
5925 usedmem
+= node_mem
[i
];
5927 node_mem
[i
] = ram_size
- usedmem
;
5930 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5931 if (node_cpumask
[i
] != 0)
5934 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5935 * must cope with this anyway, because there are BIOSes out there in
5936 * real machines which also use this scheme.
5938 if (i
== nb_numa_nodes
) {
5939 for (i
= 0; i
< smp_cpus
; i
++) {
5940 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
5945 if (foreach_device_config(DEV_SERIAL
, serial_parse
) < 0)
5947 if (foreach_device_config(DEV_PARALLEL
, parallel_parse
) < 0)
5949 if (foreach_device_config(DEV_VIRTCON
, virtcon_parse
) < 0)
5951 if (foreach_device_config(DEV_DEBUGCON
, debugcon_parse
) < 0)
5954 module_call_init(MODULE_INIT_DEVICE
);
5957 i
= select_watchdog(watchdog
);
5959 exit (i
== 1 ? 1 : 0);
5962 if (machine
->compat_props
) {
5963 qdev_prop_register_global_list(machine
->compat_props
);
5967 machine
->init(ram_size
, boot_devices
,
5968 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
5972 /* must be after terminal init, SDL library changes signal handlers */
5976 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
5977 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5978 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
5984 current_machine
= machine
;
5986 /* init USB devices */
5988 if (foreach_device_config(DEV_USB
, usb_parse
) < 0)
5992 /* init generic devices */
5993 if (qemu_opts_foreach(&qemu_device_opts
, device_init_func
, NULL
, 1) != 0)
5997 dumb_display_init();
5998 /* just use the first displaystate for the moment */
6001 if (display_type
== DT_DEFAULT
) {
6002 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6003 display_type
= DT_SDL
;
6005 display_type
= DT_VNC
;
6006 vnc_display
= "localhost:0,to=99";
6012 switch (display_type
) {
6015 #if defined(CONFIG_CURSES)
6017 curses_display_init(ds
, full_screen
);
6020 #if defined(CONFIG_SDL)
6022 sdl_display_init(ds
, full_screen
, no_frame
);
6024 #elif defined(CONFIG_COCOA)
6026 cocoa_display_init(ds
, full_screen
);
6030 vnc_display_init(ds
);
6031 if (vnc_display_open(ds
, vnc_display
) < 0)
6034 if (show_vnc_port
) {
6035 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
6043 dcl
= ds
->listeners
;
6044 while (dcl
!= NULL
) {
6045 if (dcl
->dpy_refresh
!= NULL
) {
6046 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
6047 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
6052 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
6053 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
6054 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
6057 text_consoles_set_display(display_state
);
6059 if (qemu_opts_foreach(&qemu_mon_opts
, mon_init_func
, NULL
, 1) != 0)
6062 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
6063 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
6068 qdev_machine_creation_done();
6070 if (rom_load_all() != 0) {
6071 fprintf(stderr
, "rom loading failed\n");
6075 qemu_system_reset();
6077 if (load_vmstate(cur_mon
, loadvm
) < 0) {
6083 qemu_start_incoming_migration(incoming
);
6084 } else if (autostart
) {
6094 len
= write(fds
[1], &status
, 1);
6095 if (len
== -1 && (errno
== EINTR
))
6102 TFR(fd
= qemu_open("/dev/null", O_RDWR
));
6108 pwd
= getpwnam(run_as
);
6110 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
6116 if (chroot(chroot_dir
) < 0) {
6117 fprintf(stderr
, "chroot failed\n");
6124 if (setgid(pwd
->pw_gid
) < 0) {
6125 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
6128 if (setuid(pwd
->pw_uid
) < 0) {
6129 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
6132 if (setuid(0) != -1) {
6133 fprintf(stderr
, "Dropping privileges failed\n");