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_drive
= 1;
283 { .driver
= "isa-serial", .flag
= &default_serial
},
284 { .driver
= "isa-parallel", .flag
= &default_parallel
},
285 { .driver
= "virtio-console-pci", .flag
= &default_virtcon
},
286 { .driver
= "virtio-console-s390", .flag
= &default_virtcon
},
287 { .driver
= "VGA", .flag
= &default_vga
},
288 { .driver
= "Cirrus VGA", .flag
= &default_vga
},
289 { .driver
= "QEMUware SVGA", .flag
= &default_vga
},
292 static int default_driver_check(QemuOpts
*opts
, void *opaque
)
294 const char *driver
= qemu_opt_get(opts
, "driver");
299 for (i
= 0; i
< ARRAY_SIZE(default_list
); i
++) {
300 if (strcmp(default_list
[i
].driver
, driver
) != 0)
302 *(default_list
[i
].flag
) = 0;
307 /***********************************************************/
308 /* x86 ISA bus support */
310 target_phys_addr_t isa_mem_base
= 0;
313 /***********************************************************/
314 void hw_error(const char *fmt
, ...)
320 fprintf(stderr
, "qemu: hardware error: ");
321 vfprintf(stderr
, fmt
, ap
);
322 fprintf(stderr
, "\n");
323 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
324 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
326 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
328 cpu_dump_state(env
, stderr
, fprintf
, 0);
335 static void set_proc_name(const char *s
)
337 #if defined(__linux__) && defined(PR_SET_NAME)
341 name
[sizeof(name
) - 1] = 0;
342 strncpy(name
, s
, sizeof(name
));
343 /* Could rewrite argv[0] too, but that's a bit more complicated.
344 This simple way is enough for `top'. */
345 prctl(PR_SET_NAME
, name
);
352 static QEMUBalloonEvent
*qemu_balloon_event
;
353 void *qemu_balloon_event_opaque
;
355 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
357 qemu_balloon_event
= func
;
358 qemu_balloon_event_opaque
= opaque
;
361 void qemu_balloon(ram_addr_t target
)
363 if (qemu_balloon_event
)
364 qemu_balloon_event(qemu_balloon_event_opaque
, target
);
367 ram_addr_t
qemu_balloon_status(void)
369 if (qemu_balloon_event
)
370 return qemu_balloon_event(qemu_balloon_event_opaque
, 0);
374 /***********************************************************/
377 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
378 static void *qemu_put_kbd_event_opaque
;
379 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
380 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
382 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
384 qemu_put_kbd_event_opaque
= opaque
;
385 qemu_put_kbd_event
= func
;
388 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
389 void *opaque
, int absolute
,
392 QEMUPutMouseEntry
*s
, *cursor
;
394 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
396 s
->qemu_put_mouse_event
= func
;
397 s
->qemu_put_mouse_event_opaque
= opaque
;
398 s
->qemu_put_mouse_event_absolute
= absolute
;
399 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
402 if (!qemu_put_mouse_event_head
) {
403 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
407 cursor
= qemu_put_mouse_event_head
;
408 while (cursor
->next
!= NULL
)
409 cursor
= cursor
->next
;
412 qemu_put_mouse_event_current
= s
;
417 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
419 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
421 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
424 cursor
= qemu_put_mouse_event_head
;
425 while (cursor
!= NULL
&& cursor
!= entry
) {
427 cursor
= cursor
->next
;
430 if (cursor
== NULL
) // does not exist or list empty
432 else if (prev
== NULL
) { // entry is head
433 qemu_put_mouse_event_head
= cursor
->next
;
434 if (qemu_put_mouse_event_current
== entry
)
435 qemu_put_mouse_event_current
= cursor
->next
;
436 qemu_free(entry
->qemu_put_mouse_event_name
);
441 prev
->next
= entry
->next
;
443 if (qemu_put_mouse_event_current
== entry
)
444 qemu_put_mouse_event_current
= prev
;
446 qemu_free(entry
->qemu_put_mouse_event_name
);
450 void kbd_put_keycode(int keycode
)
452 if (qemu_put_kbd_event
) {
453 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
457 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
459 QEMUPutMouseEvent
*mouse_event
;
460 void *mouse_event_opaque
;
463 if (!qemu_put_mouse_event_current
) {
468 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
470 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
473 if (graphic_rotate
) {
474 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
477 width
= graphic_width
- 1;
478 mouse_event(mouse_event_opaque
,
479 width
- dy
, dx
, dz
, buttons_state
);
481 mouse_event(mouse_event_opaque
,
482 dx
, dy
, dz
, buttons_state
);
486 int kbd_mouse_is_absolute(void)
488 if (!qemu_put_mouse_event_current
)
491 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
494 static void info_mice_iter(QObject
*data
, void *opaque
)
497 Monitor
*mon
= opaque
;
499 mouse
= qobject_to_qdict(data
);
500 monitor_printf(mon
, "%c Mouse #%" PRId64
": %s\n",
501 (qdict_get_bool(mouse
, "current") ? '*' : ' '),
502 qdict_get_int(mouse
, "index"), qdict_get_str(mouse
, "name"));
505 void do_info_mice_print(Monitor
*mon
, const QObject
*data
)
509 mice_list
= qobject_to_qlist(data
);
510 if (qlist_empty(mice_list
)) {
511 monitor_printf(mon
, "No mouse devices connected\n");
515 qlist_iter(mice_list
, info_mice_iter
, mon
);
519 * do_info_mice(): Show VM mice information
521 * Each mouse is represented by a QDict, the returned QObject is a QList of
524 * The mouse QDict contains the following:
526 * - "name": mouse's name
527 * - "index": mouse's index
528 * - "current": true if this mouse is receiving events, false otherwise
532 * [ { "name": "QEMU Microsoft Mouse", "index": 0, "current": false },
533 * { "name": "QEMU PS/2 Mouse", "index": 1, "current": true } ]
535 void do_info_mice(Monitor
*mon
, QObject
**ret_data
)
537 QEMUPutMouseEntry
*cursor
;
541 mice_list
= qlist_new();
543 if (!qemu_put_mouse_event_head
) {
547 cursor
= qemu_put_mouse_event_head
;
548 while (cursor
!= NULL
) {
550 obj
= qobject_from_jsonf("{ 'name': %s, 'index': %d, 'current': %i }",
551 cursor
->qemu_put_mouse_event_name
,
552 index
, cursor
== qemu_put_mouse_event_current
);
553 qlist_append_obj(mice_list
, obj
);
555 cursor
= cursor
->next
;
559 *ret_data
= QOBJECT(mice_list
);
562 void do_mouse_set(Monitor
*mon
, const QDict
*qdict
)
564 QEMUPutMouseEntry
*cursor
;
566 int index
= qdict_get_int(qdict
, "index");
568 if (!qemu_put_mouse_event_head
) {
569 monitor_printf(mon
, "No mouse devices connected\n");
573 cursor
= qemu_put_mouse_event_head
;
574 while (cursor
!= NULL
&& index
!= i
) {
576 cursor
= cursor
->next
;
580 qemu_put_mouse_event_current
= cursor
;
582 monitor_printf(mon
, "Mouse at given index not found\n");
585 /* compute with 96 bit intermediate result: (a*b)/c */
586 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
591 #ifdef HOST_WORDS_BIGENDIAN
601 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
602 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
605 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
609 /***********************************************************/
610 /* real time host monotonic timer */
612 static int64_t get_clock_realtime(void)
616 gettimeofday(&tv
, NULL
);
617 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
622 static int64_t clock_freq
;
624 static void init_get_clock(void)
628 ret
= QueryPerformanceFrequency(&freq
);
630 fprintf(stderr
, "Could not calibrate ticks\n");
633 clock_freq
= freq
.QuadPart
;
636 static int64_t get_clock(void)
639 QueryPerformanceCounter(&ti
);
640 return muldiv64(ti
.QuadPart
, get_ticks_per_sec(), clock_freq
);
645 static int use_rt_clock
;
647 static void init_get_clock(void)
650 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
651 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
654 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
661 static int64_t get_clock(void)
663 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
664 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
667 clock_gettime(CLOCK_MONOTONIC
, &ts
);
668 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
672 /* XXX: using gettimeofday leads to problems if the date
673 changes, so it should be avoided. */
674 return get_clock_realtime();
679 /* Return the virtual CPU time, based on the instruction counter. */
680 static int64_t cpu_get_icount(void)
683 CPUState
*env
= cpu_single_env
;;
684 icount
= qemu_icount
;
687 fprintf(stderr
, "Bad clock read\n");
688 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
690 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
693 /***********************************************************/
694 /* guest cycle counter */
696 typedef struct TimersState
{
697 int64_t cpu_ticks_prev
;
698 int64_t cpu_ticks_offset
;
699 int64_t cpu_clock_offset
;
700 int32_t cpu_ticks_enabled
;
704 TimersState timers_state
;
706 /* return the host CPU cycle counter and handle stop/restart */
707 int64_t cpu_get_ticks(void)
710 return cpu_get_icount();
712 if (!timers_state
.cpu_ticks_enabled
) {
713 return timers_state
.cpu_ticks_offset
;
716 ticks
= cpu_get_real_ticks();
717 if (timers_state
.cpu_ticks_prev
> ticks
) {
718 /* Note: non increasing ticks may happen if the host uses
720 timers_state
.cpu_ticks_offset
+= timers_state
.cpu_ticks_prev
- ticks
;
722 timers_state
.cpu_ticks_prev
= ticks
;
723 return ticks
+ timers_state
.cpu_ticks_offset
;
727 /* return the host CPU monotonic timer and handle stop/restart */
728 static int64_t cpu_get_clock(void)
731 if (!timers_state
.cpu_ticks_enabled
) {
732 return timers_state
.cpu_clock_offset
;
735 return ti
+ timers_state
.cpu_clock_offset
;
739 /* enable cpu_get_ticks() */
740 void cpu_enable_ticks(void)
742 if (!timers_state
.cpu_ticks_enabled
) {
743 timers_state
.cpu_ticks_offset
-= cpu_get_real_ticks();
744 timers_state
.cpu_clock_offset
-= get_clock();
745 timers_state
.cpu_ticks_enabled
= 1;
749 /* disable cpu_get_ticks() : the clock is stopped. You must not call
750 cpu_get_ticks() after that. */
751 void cpu_disable_ticks(void)
753 if (timers_state
.cpu_ticks_enabled
) {
754 timers_state
.cpu_ticks_offset
= cpu_get_ticks();
755 timers_state
.cpu_clock_offset
= cpu_get_clock();
756 timers_state
.cpu_ticks_enabled
= 0;
760 /***********************************************************/
763 #define QEMU_CLOCK_REALTIME 0
764 #define QEMU_CLOCK_VIRTUAL 1
765 #define QEMU_CLOCK_HOST 2
769 /* XXX: add frequency */
777 struct QEMUTimer
*next
;
780 struct qemu_alarm_timer
{
784 int (*start
)(struct qemu_alarm_timer
*t
);
785 void (*stop
)(struct qemu_alarm_timer
*t
);
786 void (*rearm
)(struct qemu_alarm_timer
*t
);
790 #define ALARM_FLAG_DYNTICKS 0x1
791 #define ALARM_FLAG_EXPIRED 0x2
793 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
795 return t
&& (t
->flags
& ALARM_FLAG_DYNTICKS
);
798 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
800 if (!alarm_has_dynticks(t
))
806 /* TODO: MIN_TIMER_REARM_US should be optimized */
807 #define MIN_TIMER_REARM_US 250
809 static struct qemu_alarm_timer
*alarm_timer
;
813 struct qemu_alarm_win32
{
816 } alarm_win32_data
= {0, -1};
818 static int win32_start_timer(struct qemu_alarm_timer
*t
);
819 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
820 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
824 static int unix_start_timer(struct qemu_alarm_timer
*t
);
825 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
829 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
830 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
831 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
833 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
834 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
836 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
837 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
839 #endif /* __linux__ */
843 /* Correlation between real and virtual time is always going to be
844 fairly approximate, so ignore small variation.
845 When the guest is idle real and virtual time will be aligned in
847 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
849 static void icount_adjust(void)
854 static int64_t last_delta
;
855 /* If the VM is not running, then do nothing. */
859 cur_time
= cpu_get_clock();
860 cur_icount
= qemu_get_clock(vm_clock
);
861 delta
= cur_icount
- cur_time
;
862 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
864 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
865 && icount_time_shift
> 0) {
866 /* The guest is getting too far ahead. Slow time down. */
870 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
871 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
872 /* The guest is getting too far behind. Speed time up. */
876 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
879 static void icount_adjust_rt(void * opaque
)
881 qemu_mod_timer(icount_rt_timer
,
882 qemu_get_clock(rt_clock
) + 1000);
886 static void icount_adjust_vm(void * opaque
)
888 qemu_mod_timer(icount_vm_timer
,
889 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
893 static void init_icount_adjust(void)
895 /* Have both realtime and virtual time triggers for speed adjustment.
896 The realtime trigger catches emulated time passing too slowly,
897 the virtual time trigger catches emulated time passing too fast.
898 Realtime triggers occur even when idle, so use them less frequently
900 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
901 qemu_mod_timer(icount_rt_timer
,
902 qemu_get_clock(rt_clock
) + 1000);
903 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
904 qemu_mod_timer(icount_vm_timer
,
905 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
908 static struct qemu_alarm_timer alarm_timers
[] = {
911 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
912 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
913 /* HPET - if available - is preferred */
914 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
915 /* ...otherwise try RTC */
916 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
918 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
920 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
921 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
922 {"win32", 0, win32_start_timer
,
923 win32_stop_timer
, NULL
, &alarm_win32_data
},
928 static void show_available_alarms(void)
932 printf("Available alarm timers, in order of precedence:\n");
933 for (i
= 0; alarm_timers
[i
].name
; i
++)
934 printf("%s\n", alarm_timers
[i
].name
);
937 static void configure_alarms(char const *opt
)
941 int count
= ARRAY_SIZE(alarm_timers
) - 1;
944 struct qemu_alarm_timer tmp
;
946 if (!strcmp(opt
, "?")) {
947 show_available_alarms();
951 arg
= qemu_strdup(opt
);
953 /* Reorder the array */
954 name
= strtok(arg
, ",");
956 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
957 if (!strcmp(alarm_timers
[i
].name
, name
))
962 fprintf(stderr
, "Unknown clock %s\n", name
);
971 tmp
= alarm_timers
[i
];
972 alarm_timers
[i
] = alarm_timers
[cur
];
973 alarm_timers
[cur
] = tmp
;
977 name
= strtok(NULL
, ",");
983 /* Disable remaining timers */
984 for (i
= cur
; i
< count
; i
++)
985 alarm_timers
[i
].name
= NULL
;
987 show_available_alarms();
992 #define QEMU_NUM_CLOCKS 3
996 QEMUClock
*host_clock
;
998 static QEMUTimer
*active_timers
[QEMU_NUM_CLOCKS
];
1000 static QEMUClock
*qemu_new_clock(int type
)
1003 clock
= qemu_mallocz(sizeof(QEMUClock
));
1008 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1012 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1015 ts
->opaque
= opaque
;
1019 void qemu_free_timer(QEMUTimer
*ts
)
1024 /* stop a timer, but do not dealloc it */
1025 void qemu_del_timer(QEMUTimer
*ts
)
1029 /* NOTE: this code must be signal safe because
1030 qemu_timer_expired() can be called from a signal. */
1031 pt
= &active_timers
[ts
->clock
->type
];
1044 /* modify the current timer so that it will be fired when current_time
1045 >= expire_time. The corresponding callback will be called. */
1046 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1052 /* add the timer in the sorted list */
1053 /* NOTE: this code must be signal safe because
1054 qemu_timer_expired() can be called from a signal. */
1055 pt
= &active_timers
[ts
->clock
->type
];
1060 if (t
->expire_time
> expire_time
)
1064 ts
->expire_time
= expire_time
;
1068 /* Rearm if necessary */
1069 if (pt
== &active_timers
[ts
->clock
->type
]) {
1070 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1071 qemu_rearm_alarm_timer(alarm_timer
);
1073 /* Interrupt execution to force deadline recalculation. */
1075 qemu_notify_event();
1079 int qemu_timer_pending(QEMUTimer
*ts
)
1082 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1089 int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1093 return (timer_head
->expire_time
<= current_time
);
1096 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1102 if (!ts
|| ts
->expire_time
> current_time
)
1104 /* remove timer from the list before calling the callback */
1105 *ptimer_head
= ts
->next
;
1108 /* run the callback (the timer list can be modified) */
1113 int64_t qemu_get_clock(QEMUClock
*clock
)
1115 switch(clock
->type
) {
1116 case QEMU_CLOCK_REALTIME
:
1117 return get_clock() / 1000000;
1119 case QEMU_CLOCK_VIRTUAL
:
1121 return cpu_get_icount();
1123 return cpu_get_clock();
1125 case QEMU_CLOCK_HOST
:
1126 return get_clock_realtime();
1130 static void init_clocks(void)
1133 rt_clock
= qemu_new_clock(QEMU_CLOCK_REALTIME
);
1134 vm_clock
= qemu_new_clock(QEMU_CLOCK_VIRTUAL
);
1135 host_clock
= qemu_new_clock(QEMU_CLOCK_HOST
);
1137 rtc_clock
= host_clock
;
1141 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1143 uint64_t expire_time
;
1145 if (qemu_timer_pending(ts
)) {
1146 expire_time
= ts
->expire_time
;
1150 qemu_put_be64(f
, expire_time
);
1153 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1155 uint64_t expire_time
;
1157 expire_time
= qemu_get_be64(f
);
1158 if (expire_time
!= -1) {
1159 qemu_mod_timer(ts
, expire_time
);
1165 static const VMStateDescription vmstate_timers
= {
1168 .minimum_version_id
= 1,
1169 .minimum_version_id_old
= 1,
1170 .fields
= (VMStateField
[]) {
1171 VMSTATE_INT64(cpu_ticks_offset
, TimersState
),
1172 VMSTATE_INT64(dummy
, TimersState
),
1173 VMSTATE_INT64_V(cpu_clock_offset
, TimersState
, 2),
1174 VMSTATE_END_OF_LIST()
1178 static void qemu_event_increment(void);
1181 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1182 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1185 static void host_alarm_handler(int host_signum
)
1189 #define DISP_FREQ 1000
1191 static int64_t delta_min
= INT64_MAX
;
1192 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1194 ti
= qemu_get_clock(vm_clock
);
1195 if (last_clock
!= 0) {
1196 delta
= ti
- last_clock
;
1197 if (delta
< delta_min
)
1199 if (delta
> delta_max
)
1202 if (++count
== DISP_FREQ
) {
1203 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1204 muldiv64(delta_min
, 1000000, get_ticks_per_sec()),
1205 muldiv64(delta_max
, 1000000, get_ticks_per_sec()),
1206 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, get_ticks_per_sec()),
1207 (double)get_ticks_per_sec() / ((double)delta_cum
/ DISP_FREQ
));
1209 delta_min
= INT64_MAX
;
1217 if (alarm_has_dynticks(alarm_timer
) ||
1219 qemu_timer_expired(active_timers
[QEMU_CLOCK_VIRTUAL
],
1220 qemu_get_clock(vm_clock
))) ||
1221 qemu_timer_expired(active_timers
[QEMU_CLOCK_REALTIME
],
1222 qemu_get_clock(rt_clock
)) ||
1223 qemu_timer_expired(active_timers
[QEMU_CLOCK_HOST
],
1224 qemu_get_clock(host_clock
))) {
1225 qemu_event_increment();
1226 if (alarm_timer
) alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1228 #ifndef CONFIG_IOTHREAD
1230 /* stop the currently executing cpu because a timer occured */
1234 timer_alarm_pending
= 1;
1235 qemu_notify_event();
1239 static int64_t qemu_next_deadline(void)
1241 /* To avoid problems with overflow limit this to 2^32. */
1242 int64_t delta
= INT32_MAX
;
1244 if (active_timers
[QEMU_CLOCK_VIRTUAL
]) {
1245 delta
= active_timers
[QEMU_CLOCK_VIRTUAL
]->expire_time
-
1246 qemu_get_clock(vm_clock
);
1248 if (active_timers
[QEMU_CLOCK_HOST
]) {
1249 int64_t hdelta
= active_timers
[QEMU_CLOCK_HOST
]->expire_time
-
1250 qemu_get_clock(host_clock
);
1261 #if defined(__linux__)
1262 static uint64_t qemu_next_deadline_dyntick(void)
1270 delta
= (qemu_next_deadline() + 999) / 1000;
1272 if (active_timers
[QEMU_CLOCK_REALTIME
]) {
1273 rtdelta
= (active_timers
[QEMU_CLOCK_REALTIME
]->expire_time
-
1274 qemu_get_clock(rt_clock
))*1000;
1275 if (rtdelta
< delta
)
1279 if (delta
< MIN_TIMER_REARM_US
)
1280 delta
= MIN_TIMER_REARM_US
;
1288 /* Sets a specific flag */
1289 static int fcntl_setfl(int fd
, int flag
)
1293 flags
= fcntl(fd
, F_GETFL
);
1297 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1303 #if defined(__linux__)
1305 #define RTC_FREQ 1024
1307 static void enable_sigio_timer(int fd
)
1309 struct sigaction act
;
1312 sigfillset(&act
.sa_mask
);
1314 act
.sa_handler
= host_alarm_handler
;
1316 sigaction(SIGIO
, &act
, NULL
);
1317 fcntl_setfl(fd
, O_ASYNC
);
1318 fcntl(fd
, F_SETOWN
, getpid());
1321 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1323 struct hpet_info info
;
1326 fd
= qemu_open("/dev/hpet", O_RDONLY
);
1331 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1333 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1334 "error, but for better emulation accuracy type:\n"
1335 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1339 /* Check capabilities */
1340 r
= ioctl(fd
, HPET_INFO
, &info
);
1344 /* Enable periodic mode */
1345 r
= ioctl(fd
, HPET_EPI
, 0);
1346 if (info
.hi_flags
&& (r
< 0))
1349 /* Enable interrupt */
1350 r
= ioctl(fd
, HPET_IE_ON
, 0);
1354 enable_sigio_timer(fd
);
1355 t
->priv
= (void *)(long)fd
;
1363 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1365 int fd
= (long)t
->priv
;
1370 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1373 unsigned long current_rtc_freq
= 0;
1375 TFR(rtc_fd
= qemu_open("/dev/rtc", O_RDONLY
));
1378 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1379 if (current_rtc_freq
!= RTC_FREQ
&&
1380 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1381 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1382 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1383 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1386 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1392 enable_sigio_timer(rtc_fd
);
1394 t
->priv
= (void *)(long)rtc_fd
;
1399 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1401 int rtc_fd
= (long)t
->priv
;
1406 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1410 struct sigaction act
;
1412 sigfillset(&act
.sa_mask
);
1414 act
.sa_handler
= host_alarm_handler
;
1416 sigaction(SIGALRM
, &act
, NULL
);
1419 * Initialize ev struct to 0 to avoid valgrind complaining
1420 * about uninitialized data in timer_create call
1422 memset(&ev
, 0, sizeof(ev
));
1423 ev
.sigev_value
.sival_int
= 0;
1424 ev
.sigev_notify
= SIGEV_SIGNAL
;
1425 ev
.sigev_signo
= SIGALRM
;
1427 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1428 perror("timer_create");
1430 /* disable dynticks */
1431 fprintf(stderr
, "Dynamic Ticks disabled\n");
1436 t
->priv
= (void *)(long)host_timer
;
1441 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1443 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1445 timer_delete(host_timer
);
1448 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1450 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1451 struct itimerspec timeout
;
1452 int64_t nearest_delta_us
= INT64_MAX
;
1455 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1456 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1457 !active_timers
[QEMU_CLOCK_HOST
])
1460 nearest_delta_us
= qemu_next_deadline_dyntick();
1462 /* check whether a timer is already running */
1463 if (timer_gettime(host_timer
, &timeout
)) {
1465 fprintf(stderr
, "Internal timer error: aborting\n");
1468 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1469 if (current_us
&& current_us
<= nearest_delta_us
)
1472 timeout
.it_interval
.tv_sec
= 0;
1473 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1474 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1475 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1476 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1478 fprintf(stderr
, "Internal timer error: aborting\n");
1483 #endif /* defined(__linux__) */
1485 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1487 struct sigaction act
;
1488 struct itimerval itv
;
1492 sigfillset(&act
.sa_mask
);
1494 act
.sa_handler
= host_alarm_handler
;
1496 sigaction(SIGALRM
, &act
, NULL
);
1498 itv
.it_interval
.tv_sec
= 0;
1499 /* for i386 kernel 2.6 to get 1 ms */
1500 itv
.it_interval
.tv_usec
= 999;
1501 itv
.it_value
.tv_sec
= 0;
1502 itv
.it_value
.tv_usec
= 10 * 1000;
1504 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1511 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1513 struct itimerval itv
;
1515 memset(&itv
, 0, sizeof(itv
));
1516 setitimer(ITIMER_REAL
, &itv
, NULL
);
1519 #endif /* !defined(_WIN32) */
1524 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1527 struct qemu_alarm_win32
*data
= t
->priv
;
1530 memset(&tc
, 0, sizeof(tc
));
1531 timeGetDevCaps(&tc
, sizeof(tc
));
1533 if (data
->period
< tc
.wPeriodMin
)
1534 data
->period
= tc
.wPeriodMin
;
1536 timeBeginPeriod(data
->period
);
1538 flags
= TIME_CALLBACK_FUNCTION
;
1539 if (alarm_has_dynticks(t
))
1540 flags
|= TIME_ONESHOT
;
1542 flags
|= TIME_PERIODIC
;
1544 data
->timerId
= timeSetEvent(1, // interval (ms)
1545 data
->period
, // resolution
1546 host_alarm_handler
, // function
1547 (DWORD
)t
, // parameter
1550 if (!data
->timerId
) {
1551 fprintf(stderr
, "Failed to initialize win32 alarm timer: %ld\n",
1553 timeEndPeriod(data
->period
);
1560 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1562 struct qemu_alarm_win32
*data
= t
->priv
;
1564 timeKillEvent(data
->timerId
);
1565 timeEndPeriod(data
->period
);
1568 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1570 struct qemu_alarm_win32
*data
= t
->priv
;
1572 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1573 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1574 !active_timers
[QEMU_CLOCK_HOST
])
1577 timeKillEvent(data
->timerId
);
1579 data
->timerId
= timeSetEvent(1,
1583 TIME_ONESHOT
| TIME_PERIODIC
);
1585 if (!data
->timerId
) {
1586 fprintf(stderr
, "Failed to re-arm win32 alarm timer %ld\n",
1589 timeEndPeriod(data
->period
);
1596 static int init_timer_alarm(void)
1598 struct qemu_alarm_timer
*t
= NULL
;
1601 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1602 t
= &alarm_timers
[i
];
1622 static void quit_timers(void)
1624 alarm_timer
->stop(alarm_timer
);
1628 /***********************************************************/
1629 /* host time/date access */
1630 void qemu_get_timedate(struct tm
*tm
, int offset
)
1637 if (rtc_date_offset
== -1) {
1641 ret
= localtime(&ti
);
1643 ti
-= rtc_date_offset
;
1647 memcpy(tm
, ret
, sizeof(struct tm
));
1650 int qemu_timedate_diff(struct tm
*tm
)
1654 if (rtc_date_offset
== -1)
1656 seconds
= mktimegm(tm
);
1658 seconds
= mktime(tm
);
1660 seconds
= mktimegm(tm
) + rtc_date_offset
;
1662 return seconds
- time(NULL
);
1665 static void configure_rtc_date_offset(const char *startdate
, int legacy
)
1667 time_t rtc_start_date
;
1670 if (!strcmp(startdate
, "now") && legacy
) {
1671 rtc_date_offset
= -1;
1673 if (sscanf(startdate
, "%d-%d-%dT%d:%d:%d",
1681 } else if (sscanf(startdate
, "%d-%d-%d",
1684 &tm
.tm_mday
) == 3) {
1693 rtc_start_date
= mktimegm(&tm
);
1694 if (rtc_start_date
== -1) {
1696 fprintf(stderr
, "Invalid date format. Valid formats are:\n"
1697 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1700 rtc_date_offset
= time(NULL
) - rtc_start_date
;
1704 static void configure_rtc(QemuOpts
*opts
)
1708 value
= qemu_opt_get(opts
, "base");
1710 if (!strcmp(value
, "utc")) {
1712 } else if (!strcmp(value
, "localtime")) {
1715 configure_rtc_date_offset(value
, 0);
1718 value
= qemu_opt_get(opts
, "clock");
1720 if (!strcmp(value
, "host")) {
1721 rtc_clock
= host_clock
;
1722 } else if (!strcmp(value
, "vm")) {
1723 rtc_clock
= vm_clock
;
1725 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1729 #ifdef CONFIG_TARGET_I386
1730 value
= qemu_opt_get(opts
, "driftfix");
1732 if (!strcmp(buf
, "slew")) {
1734 } else if (!strcmp(buf
, "none")) {
1737 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1745 static void socket_cleanup(void)
1750 static int socket_init(void)
1755 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1757 err
= WSAGetLastError();
1758 fprintf(stderr
, "WSAStartup: %d\n", err
);
1761 atexit(socket_cleanup
);
1766 /***********************************************************/
1767 /* Bluetooth support */
1770 static struct HCIInfo
*hci_table
[MAX_NICS
];
1772 static struct bt_vlan_s
{
1773 struct bt_scatternet_s net
;
1775 struct bt_vlan_s
*next
;
1778 /* find or alloc a new bluetooth "VLAN" */
1779 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1781 struct bt_vlan_s
**pvlan
, *vlan
;
1782 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1786 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1788 pvlan
= &first_bt_vlan
;
1789 while (*pvlan
!= NULL
)
1790 pvlan
= &(*pvlan
)->next
;
1795 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1799 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1804 static struct HCIInfo null_hci
= {
1805 .cmd_send
= null_hci_send
,
1806 .sco_send
= null_hci_send
,
1807 .acl_send
= null_hci_send
,
1808 .bdaddr_set
= null_hci_addr_set
,
1811 struct HCIInfo
*qemu_next_hci(void)
1813 if (cur_hci
== nb_hcis
)
1816 return hci_table
[cur_hci
++];
1819 static struct HCIInfo
*hci_init(const char *str
)
1822 struct bt_scatternet_s
*vlan
= 0;
1824 if (!strcmp(str
, "null"))
1827 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
1829 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
1830 else if (!strncmp(str
, "hci", 3)) {
1833 if (!strncmp(str
+ 3, ",vlan=", 6)) {
1834 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
1839 vlan
= qemu_find_bt_vlan(0);
1841 return bt_new_hci(vlan
);
1844 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
1849 static int bt_hci_parse(const char *str
)
1851 struct HCIInfo
*hci
;
1854 if (nb_hcis
>= MAX_NICS
) {
1855 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
1859 hci
= hci_init(str
);
1868 bdaddr
.b
[5] = 0x56 + nb_hcis
;
1869 hci
->bdaddr_set(hci
, bdaddr
.b
);
1871 hci_table
[nb_hcis
++] = hci
;
1876 static void bt_vhci_add(int vlan_id
)
1878 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
1881 fprintf(stderr
, "qemu: warning: adding a VHCI to "
1882 "an empty scatternet %i\n", vlan_id
);
1884 bt_vhci_init(bt_new_hci(vlan
));
1887 static struct bt_device_s
*bt_device_add(const char *opt
)
1889 struct bt_scatternet_s
*vlan
;
1891 char *endp
= strstr(opt
, ",vlan=");
1892 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
1895 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
1898 vlan_id
= strtol(endp
+ 6, &endp
, 0);
1900 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
1905 vlan
= qemu_find_bt_vlan(vlan_id
);
1908 fprintf(stderr
, "qemu: warning: adding a slave device to "
1909 "an empty scatternet %i\n", vlan_id
);
1911 if (!strcmp(devname
, "keyboard"))
1912 return bt_keyboard_init(vlan
);
1914 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
1918 static int bt_parse(const char *opt
)
1920 const char *endp
, *p
;
1923 if (strstart(opt
, "hci", &endp
)) {
1924 if (!*endp
|| *endp
== ',') {
1926 if (!strstart(endp
, ",vlan=", 0))
1929 return bt_hci_parse(opt
);
1931 } else if (strstart(opt
, "vhci", &endp
)) {
1932 if (!*endp
|| *endp
== ',') {
1934 if (strstart(endp
, ",vlan=", &p
)) {
1935 vlan
= strtol(p
, (char **) &endp
, 0);
1937 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
1941 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
1950 } else if (strstart(opt
, "device:", &endp
))
1951 return !bt_device_add(endp
);
1953 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
1957 /***********************************************************/
1958 /* QEMU Block devices */
1960 #define HD_ALIAS "index=%d,media=disk"
1961 #define CDROM_ALIAS "index=2,media=cdrom"
1962 #define FD_ALIAS "index=%d,if=floppy"
1963 #define PFLASH_ALIAS "if=pflash"
1964 #define MTD_ALIAS "if=mtd"
1965 #define SD_ALIAS "index=0,if=sd"
1967 QemuOpts
*drive_add(const char *file
, const char *fmt
, ...)
1974 vsnprintf(optstr
, sizeof(optstr
), fmt
, ap
);
1977 opts
= qemu_opts_parse(&qemu_drive_opts
, optstr
, NULL
);
1979 fprintf(stderr
, "%s: huh? duplicate? (%s)\n",
1980 __FUNCTION__
, optstr
);
1984 qemu_opt_set(opts
, "file", file
);
1988 DriveInfo
*drive_get(BlockInterfaceType type
, int bus
, int unit
)
1992 /* seek interface, bus and unit */
1994 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1995 if (dinfo
->type
== type
&&
1996 dinfo
->bus
== bus
&&
1997 dinfo
->unit
== unit
)
2004 DriveInfo
*drive_get_by_id(const char *id
)
2008 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
2009 if (strcmp(id
, dinfo
->id
))
2016 int drive_get_max_bus(BlockInterfaceType type
)
2022 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
2023 if(dinfo
->type
== type
&&
2024 dinfo
->bus
> max_bus
)
2025 max_bus
= dinfo
->bus
;
2030 const char *drive_get_serial(BlockDriverState
*bdrv
)
2034 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
2035 if (dinfo
->bdrv
== bdrv
)
2036 return dinfo
->serial
;
2042 BlockInterfaceErrorAction
drive_get_on_error(
2043 BlockDriverState
*bdrv
, int is_read
)
2047 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
2048 if (dinfo
->bdrv
== bdrv
)
2049 return is_read
? dinfo
->on_read_error
: dinfo
->on_write_error
;
2052 return is_read
? BLOCK_ERR_REPORT
: BLOCK_ERR_STOP_ENOSPC
;
2055 static void bdrv_format_print(void *opaque
, const char *name
)
2057 fprintf(stderr
, " %s", name
);
2060 void drive_uninit(DriveInfo
*dinfo
)
2062 qemu_opts_del(dinfo
->opts
);
2063 bdrv_delete(dinfo
->bdrv
);
2064 QTAILQ_REMOVE(&drives
, dinfo
, next
);
2068 static int parse_block_error_action(const char *buf
, int is_read
)
2070 if (!strcmp(buf
, "ignore")) {
2071 return BLOCK_ERR_IGNORE
;
2072 } else if (!is_read
&& !strcmp(buf
, "enospc")) {
2073 return BLOCK_ERR_STOP_ENOSPC
;
2074 } else if (!strcmp(buf
, "stop")) {
2075 return BLOCK_ERR_STOP_ANY
;
2076 } else if (!strcmp(buf
, "report")) {
2077 return BLOCK_ERR_REPORT
;
2079 fprintf(stderr
, "qemu: '%s' invalid %s error action\n",
2080 buf
, is_read
? "read" : "write");
2085 DriveInfo
*drive_init(QemuOpts
*opts
, void *opaque
,
2089 const char *file
= NULL
;
2092 const char *mediastr
= "";
2093 BlockInterfaceType type
;
2094 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
2095 int bus_id
, unit_id
;
2096 int cyls
, heads
, secs
, translation
;
2097 BlockDriver
*drv
= NULL
;
2098 QEMUMachine
*machine
= opaque
;
2105 int on_read_error
, on_write_error
;
2106 const char *devaddr
;
2112 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2115 if (machine
&& machine
->use_scsi
) {
2117 max_devs
= MAX_SCSI_DEVS
;
2118 pstrcpy(devname
, sizeof(devname
), "scsi");
2121 max_devs
= MAX_IDE_DEVS
;
2122 pstrcpy(devname
, sizeof(devname
), "ide");
2126 /* extract parameters */
2127 bus_id
= qemu_opt_get_number(opts
, "bus", 0);
2128 unit_id
= qemu_opt_get_number(opts
, "unit", -1);
2129 index
= qemu_opt_get_number(opts
, "index", -1);
2131 cyls
= qemu_opt_get_number(opts
, "cyls", 0);
2132 heads
= qemu_opt_get_number(opts
, "heads", 0);
2133 secs
= qemu_opt_get_number(opts
, "secs", 0);
2135 snapshot
= qemu_opt_get_bool(opts
, "snapshot", 0);
2136 ro
= qemu_opt_get_bool(opts
, "readonly", 0);
2138 file
= qemu_opt_get(opts
, "file");
2139 serial
= qemu_opt_get(opts
, "serial");
2141 if ((buf
= qemu_opt_get(opts
, "if")) != NULL
) {
2142 pstrcpy(devname
, sizeof(devname
), buf
);
2143 if (!strcmp(buf
, "ide")) {
2145 max_devs
= MAX_IDE_DEVS
;
2146 } else if (!strcmp(buf
, "scsi")) {
2148 max_devs
= MAX_SCSI_DEVS
;
2149 } else if (!strcmp(buf
, "floppy")) {
2152 } else if (!strcmp(buf
, "pflash")) {
2155 } else if (!strcmp(buf
, "mtd")) {
2158 } else if (!strcmp(buf
, "sd")) {
2161 } else if (!strcmp(buf
, "virtio")) {
2164 } else if (!strcmp(buf
, "xen")) {
2167 } else if (!strcmp(buf
, "none")) {
2171 fprintf(stderr
, "qemu: unsupported bus type '%s'\n", buf
);
2176 if (cyls
|| heads
|| secs
) {
2177 if (cyls
< 1 || (type
== IF_IDE
&& cyls
> 16383)) {
2178 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", buf
);
2181 if (heads
< 1 || (type
== IF_IDE
&& heads
> 16)) {
2182 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", buf
);
2185 if (secs
< 1 || (type
== IF_IDE
&& secs
> 63)) {
2186 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", buf
);
2191 if ((buf
= qemu_opt_get(opts
, "trans")) != NULL
) {
2194 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2198 if (!strcmp(buf
, "none"))
2199 translation
= BIOS_ATA_TRANSLATION_NONE
;
2200 else if (!strcmp(buf
, "lba"))
2201 translation
= BIOS_ATA_TRANSLATION_LBA
;
2202 else if (!strcmp(buf
, "auto"))
2203 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2205 fprintf(stderr
, "qemu: '%s' invalid translation type\n", buf
);
2210 if ((buf
= qemu_opt_get(opts
, "media")) != NULL
) {
2211 if (!strcmp(buf
, "disk")) {
2213 } else if (!strcmp(buf
, "cdrom")) {
2214 if (cyls
|| secs
|| heads
) {
2216 "qemu: '%s' invalid physical CHS format\n", buf
);
2219 media
= MEDIA_CDROM
;
2221 fprintf(stderr
, "qemu: '%s' invalid media\n", buf
);
2226 if ((buf
= qemu_opt_get(opts
, "cache")) != NULL
) {
2227 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2229 else if (!strcmp(buf
, "writethrough"))
2231 else if (!strcmp(buf
, "writeback"))
2234 fprintf(stderr
, "qemu: invalid cache option\n");
2239 #ifdef CONFIG_LINUX_AIO
2240 if ((buf
= qemu_opt_get(opts
, "aio")) != NULL
) {
2241 if (!strcmp(buf
, "threads"))
2243 else if (!strcmp(buf
, "native"))
2246 fprintf(stderr
, "qemu: invalid aio option\n");
2252 if ((buf
= qemu_opt_get(opts
, "format")) != NULL
) {
2253 if (strcmp(buf
, "?") == 0) {
2254 fprintf(stderr
, "qemu: Supported formats:");
2255 bdrv_iterate_format(bdrv_format_print
, NULL
);
2256 fprintf(stderr
, "\n");
2259 drv
= bdrv_find_whitelisted_format(buf
);
2261 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2266 on_write_error
= BLOCK_ERR_STOP_ENOSPC
;
2267 if ((buf
= qemu_opt_get(opts
, "werror")) != NULL
) {
2268 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2269 fprintf(stderr
, "werror is no supported by this format\n");
2273 on_write_error
= parse_block_error_action(buf
, 0);
2274 if (on_write_error
< 0) {
2279 on_read_error
= BLOCK_ERR_REPORT
;
2280 if ((buf
= qemu_opt_get(opts
, "rerror")) != NULL
) {
2281 if (type
!= IF_IDE
&& type
!= IF_VIRTIO
) {
2282 fprintf(stderr
, "rerror is no supported by this format\n");
2286 on_read_error
= parse_block_error_action(buf
, 1);
2287 if (on_read_error
< 0) {
2292 if ((devaddr
= qemu_opt_get(opts
, "addr")) != NULL
) {
2293 if (type
!= IF_VIRTIO
) {
2294 fprintf(stderr
, "addr is not supported\n");
2299 /* compute bus and unit according index */
2302 if (bus_id
!= 0 || unit_id
!= -1) {
2304 "qemu: index cannot be used with bus and unit\n");
2312 unit_id
= index
% max_devs
;
2313 bus_id
= index
/ max_devs
;
2317 /* if user doesn't specify a unit_id,
2318 * try to find the first free
2321 if (unit_id
== -1) {
2323 while (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2325 if (max_devs
&& unit_id
>= max_devs
) {
2326 unit_id
-= max_devs
;
2334 if (max_devs
&& unit_id
>= max_devs
) {
2335 fprintf(stderr
, "qemu: unit %d too big (max is %d)\n",
2336 unit_id
, max_devs
- 1);
2341 * ignore multiple definitions
2344 if (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2351 dinfo
= qemu_mallocz(sizeof(*dinfo
));
2352 if ((buf
= qemu_opts_id(opts
)) != NULL
) {
2353 dinfo
->id
= qemu_strdup(buf
);
2355 /* no id supplied -> create one */
2356 dinfo
->id
= qemu_mallocz(32);
2357 if (type
== IF_IDE
|| type
== IF_SCSI
)
2358 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2360 snprintf(dinfo
->id
, 32, "%s%i%s%i",
2361 devname
, bus_id
, mediastr
, unit_id
);
2363 snprintf(dinfo
->id
, 32, "%s%s%i",
2364 devname
, mediastr
, unit_id
);
2366 dinfo
->bdrv
= bdrv_new(dinfo
->id
);
2367 dinfo
->devaddr
= devaddr
;
2369 dinfo
->bus
= bus_id
;
2370 dinfo
->unit
= unit_id
;
2371 dinfo
->on_read_error
= on_read_error
;
2372 dinfo
->on_write_error
= on_write_error
;
2375 strncpy(dinfo
->serial
, serial
, sizeof(serial
));
2376 QTAILQ_INSERT_TAIL(&drives
, dinfo
, next
);
2386 bdrv_set_geometry_hint(dinfo
->bdrv
, cyls
, heads
, secs
);
2387 bdrv_set_translation_hint(dinfo
->bdrv
, translation
);
2391 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_CDROM
);
2396 /* FIXME: This isn't really a floppy, but it's a reasonable
2399 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_FLOPPY
);
2405 /* add virtio block device */
2406 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
2407 qemu_opt_set(opts
, "driver", "virtio-blk-pci");
2408 qemu_opt_set(opts
, "drive", dinfo
->id
);
2410 qemu_opt_set(opts
, "addr", devaddr
);
2421 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2422 cache
= 2; /* always use write-back with snapshot */
2424 if (cache
== 0) /* no caching */
2425 bdrv_flags
|= BDRV_O_NOCACHE
;
2426 else if (cache
== 2) /* write-back */
2427 bdrv_flags
|= BDRV_O_CACHE_WB
;
2430 bdrv_flags
|= BDRV_O_NATIVE_AIO
;
2432 bdrv_flags
&= ~BDRV_O_NATIVE_AIO
;
2436 if (type
== IF_IDE
) {
2437 fprintf(stderr
, "qemu: readonly flag not supported for drive with ide interface\n");
2440 (void)bdrv_set_read_only(dinfo
->bdrv
, 1);
2443 if (bdrv_open2(dinfo
->bdrv
, file
, bdrv_flags
, drv
) < 0) {
2444 fprintf(stderr
, "qemu: could not open disk image %s: %s\n",
2445 file
, strerror(errno
));
2449 if (bdrv_key_required(dinfo
->bdrv
))
2455 static int drive_init_func(QemuOpts
*opts
, void *opaque
)
2457 QEMUMachine
*machine
= opaque
;
2458 int fatal_error
= 0;
2460 if (drive_init(opts
, machine
, &fatal_error
) == NULL
) {
2467 static int drive_enable_snapshot(QemuOpts
*opts
, void *opaque
)
2469 if (NULL
== qemu_opt_get(opts
, "snapshot")) {
2470 qemu_opt_set(opts
, "snapshot", "on");
2475 void qemu_register_boot_set(QEMUBootSetHandler
*func
, void *opaque
)
2477 boot_set_handler
= func
;
2478 boot_set_opaque
= opaque
;
2481 int qemu_boot_set(const char *boot_devices
)
2483 if (!boot_set_handler
) {
2486 return boot_set_handler(boot_set_opaque
, boot_devices
);
2489 static int parse_bootdevices(char *devices
)
2491 /* We just do some generic consistency checks */
2495 for (p
= devices
; *p
!= '\0'; p
++) {
2496 /* Allowed boot devices are:
2497 * a-b: floppy disk drives
2498 * c-f: IDE disk drives
2499 * g-m: machine implementation dependant drives
2500 * n-p: network devices
2501 * It's up to each machine implementation to check if the given boot
2502 * devices match the actual hardware implementation and firmware
2505 if (*p
< 'a' || *p
> 'p') {
2506 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
2509 if (bitmap
& (1 << (*p
- 'a'))) {
2510 fprintf(stderr
, "Boot device '%c' was given twice\n", *p
);
2513 bitmap
|= 1 << (*p
- 'a');
2518 static void restore_boot_devices(void *opaque
)
2520 char *standard_boot_devices
= opaque
;
2522 qemu_boot_set(standard_boot_devices
);
2524 qemu_unregister_reset(restore_boot_devices
, standard_boot_devices
);
2525 qemu_free(standard_boot_devices
);
2528 static void numa_add(const char *optarg
)
2532 unsigned long long value
, endvalue
;
2535 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2536 if (!strcmp(option
, "node")) {
2537 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2538 nodenr
= nb_numa_nodes
;
2540 nodenr
= strtoull(option
, NULL
, 10);
2543 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2544 node_mem
[nodenr
] = 0;
2546 value
= strtoull(option
, &endptr
, 0);
2548 case 0: case 'M': case 'm':
2555 node_mem
[nodenr
] = value
;
2557 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2558 node_cpumask
[nodenr
] = 0;
2560 value
= strtoull(option
, &endptr
, 10);
2563 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2565 if (*endptr
== '-') {
2566 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2567 if (endvalue
>= 63) {
2570 "only 63 CPUs in NUMA mode supported.\n");
2572 value
= (1 << (endvalue
+ 1)) - (1 << value
);
2577 node_cpumask
[nodenr
] = value
;
2584 static void smp_parse(const char *optarg
)
2586 int smp
, sockets
= 0, threads
= 0, cores
= 0;
2590 smp
= strtoul(optarg
, &endptr
, 10);
2591 if (endptr
!= optarg
) {
2592 if (*endptr
== ',') {
2596 if (get_param_value(option
, 128, "sockets", endptr
) != 0)
2597 sockets
= strtoull(option
, NULL
, 10);
2598 if (get_param_value(option
, 128, "cores", endptr
) != 0)
2599 cores
= strtoull(option
, NULL
, 10);
2600 if (get_param_value(option
, 128, "threads", endptr
) != 0)
2601 threads
= strtoull(option
, NULL
, 10);
2602 if (get_param_value(option
, 128, "maxcpus", endptr
) != 0)
2603 max_cpus
= strtoull(option
, NULL
, 10);
2605 /* compute missing values, prefer sockets over cores over threads */
2606 if (smp
== 0 || sockets
== 0) {
2607 sockets
= sockets
> 0 ? sockets
: 1;
2608 cores
= cores
> 0 ? cores
: 1;
2609 threads
= threads
> 0 ? threads
: 1;
2611 smp
= cores
* threads
* sockets
;
2613 sockets
= smp
/ (cores
* threads
);
2617 threads
= threads
> 0 ? threads
: 1;
2618 cores
= smp
/ (sockets
* threads
);
2621 sockets
= smp
/ (cores
* threads
);
2623 threads
= smp
/ (cores
* sockets
);
2628 smp_cores
= cores
> 0 ? cores
: 1;
2629 smp_threads
= threads
> 0 ? threads
: 1;
2631 max_cpus
= smp_cpus
;
2634 /***********************************************************/
2637 static int usb_device_add(const char *devname
, int is_hotplug
)
2640 USBDevice
*dev
= NULL
;
2645 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2646 dev
= usbdevice_create(devname
);
2650 /* the other ones */
2651 if (strstart(devname
, "host:", &p
)) {
2652 dev
= usb_host_device_open(p
);
2653 } else if (strstart(devname
, "net:", &p
)) {
2657 opts
= qemu_opts_parse(&qemu_net_opts
, p
, NULL
);
2662 qemu_opt_set(opts
, "type", "nic");
2663 qemu_opt_set(opts
, "model", "usb");
2665 idx
= net_client_init(NULL
, opts
, 0);
2670 dev
= usb_net_init(&nd_table
[idx
]);
2671 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2672 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2673 bt_new_hci(qemu_find_bt_vlan(0)));
2684 static int usb_device_del(const char *devname
)
2689 if (strstart(devname
, "host:", &p
))
2690 return usb_host_device_close(p
);
2695 p
= strchr(devname
, '.');
2698 bus_num
= strtoul(devname
, NULL
, 0);
2699 addr
= strtoul(p
+ 1, NULL
, 0);
2701 return usb_device_delete_addr(bus_num
, addr
);
2704 static int usb_parse(const char *cmdline
)
2706 return usb_device_add(cmdline
, 0);
2709 void do_usb_add(Monitor
*mon
, const QDict
*qdict
)
2711 usb_device_add(qdict_get_str(qdict
, "devname"), 1);
2714 void do_usb_del(Monitor
*mon
, const QDict
*qdict
)
2716 usb_device_del(qdict_get_str(qdict
, "devname"));
2719 /***********************************************************/
2720 /* PCMCIA/Cardbus */
2722 static struct pcmcia_socket_entry_s
{
2723 PCMCIASocket
*socket
;
2724 struct pcmcia_socket_entry_s
*next
;
2725 } *pcmcia_sockets
= 0;
2727 void pcmcia_socket_register(PCMCIASocket
*socket
)
2729 struct pcmcia_socket_entry_s
*entry
;
2731 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2732 entry
->socket
= socket
;
2733 entry
->next
= pcmcia_sockets
;
2734 pcmcia_sockets
= entry
;
2737 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2739 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2741 ptr
= &pcmcia_sockets
;
2742 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2743 if (entry
->socket
== socket
) {
2749 void pcmcia_info(Monitor
*mon
)
2751 struct pcmcia_socket_entry_s
*iter
;
2753 if (!pcmcia_sockets
)
2754 monitor_printf(mon
, "No PCMCIA sockets\n");
2756 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2757 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2758 iter
->socket
->attached
? iter
->socket
->card_string
:
2762 /***********************************************************/
2763 /* register display */
2765 struct DisplayAllocator default_allocator
= {
2766 defaultallocator_create_displaysurface
,
2767 defaultallocator_resize_displaysurface
,
2768 defaultallocator_free_displaysurface
2771 void register_displaystate(DisplayState
*ds
)
2781 DisplayState
*get_displaystate(void)
2783 return display_state
;
2786 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
2788 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
2789 return ds
->allocator
;
2794 static void dumb_display_init(void)
2796 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
2797 ds
->allocator
= &default_allocator
;
2798 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
2799 register_displaystate(ds
);
2802 /***********************************************************/
2805 typedef struct IOHandlerRecord
{
2807 IOCanRWHandler
*fd_read_poll
;
2809 IOHandler
*fd_write
;
2812 /* temporary data */
2814 struct IOHandlerRecord
*next
;
2817 static IOHandlerRecord
*first_io_handler
;
2819 /* XXX: fd_read_poll should be suppressed, but an API change is
2820 necessary in the character devices to suppress fd_can_read(). */
2821 int qemu_set_fd_handler2(int fd
,
2822 IOCanRWHandler
*fd_read_poll
,
2824 IOHandler
*fd_write
,
2827 IOHandlerRecord
**pioh
, *ioh
;
2829 if (!fd_read
&& !fd_write
) {
2830 pioh
= &first_io_handler
;
2835 if (ioh
->fd
== fd
) {
2842 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
2846 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
2847 ioh
->next
= first_io_handler
;
2848 first_io_handler
= ioh
;
2851 ioh
->fd_read_poll
= fd_read_poll
;
2852 ioh
->fd_read
= fd_read
;
2853 ioh
->fd_write
= fd_write
;
2854 ioh
->opaque
= opaque
;
2860 int qemu_set_fd_handler(int fd
,
2862 IOHandler
*fd_write
,
2865 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
2869 /***********************************************************/
2870 /* Polling handling */
2872 typedef struct PollingEntry
{
2875 struct PollingEntry
*next
;
2878 static PollingEntry
*first_polling_entry
;
2880 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
2882 PollingEntry
**ppe
, *pe
;
2883 pe
= qemu_mallocz(sizeof(PollingEntry
));
2885 pe
->opaque
= opaque
;
2886 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
2891 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
2893 PollingEntry
**ppe
, *pe
;
2894 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
2896 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
2904 /***********************************************************/
2905 /* Wait objects support */
2906 typedef struct WaitObjects
{
2908 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
2909 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
2910 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
2913 static WaitObjects wait_objects
= {0};
2915 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2917 WaitObjects
*w
= &wait_objects
;
2919 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
2921 w
->events
[w
->num
] = handle
;
2922 w
->func
[w
->num
] = func
;
2923 w
->opaque
[w
->num
] = opaque
;
2928 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2931 WaitObjects
*w
= &wait_objects
;
2934 for (i
= 0; i
< w
->num
; i
++) {
2935 if (w
->events
[i
] == handle
)
2938 w
->events
[i
] = w
->events
[i
+ 1];
2939 w
->func
[i
] = w
->func
[i
+ 1];
2940 w
->opaque
[i
] = w
->opaque
[i
+ 1];
2948 /***********************************************************/
2949 /* ram save/restore */
2951 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2952 #define RAM_SAVE_FLAG_COMPRESS 0x02
2953 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2954 #define RAM_SAVE_FLAG_PAGE 0x08
2955 #define RAM_SAVE_FLAG_EOS 0x10
2957 static int is_dup_page(uint8_t *page
, uint8_t ch
)
2959 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
2960 uint32_t *array
= (uint32_t *)page
;
2963 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
2964 if (array
[i
] != val
)
2971 static int ram_save_block(QEMUFile
*f
)
2973 static ram_addr_t current_addr
= 0;
2974 ram_addr_t saved_addr
= current_addr
;
2975 ram_addr_t addr
= 0;
2978 while (addr
< last_ram_offset
) {
2979 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
2982 cpu_physical_memory_reset_dirty(current_addr
,
2983 current_addr
+ TARGET_PAGE_SIZE
,
2984 MIGRATION_DIRTY_FLAG
);
2986 p
= qemu_get_ram_ptr(current_addr
);
2988 if (is_dup_page(p
, *p
)) {
2989 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
2990 qemu_put_byte(f
, *p
);
2992 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
2993 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
2999 addr
+= TARGET_PAGE_SIZE
;
3000 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
3006 static uint64_t bytes_transferred
;
3008 static ram_addr_t
ram_save_remaining(void)
3011 ram_addr_t count
= 0;
3013 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3014 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3021 uint64_t ram_bytes_remaining(void)
3023 return ram_save_remaining() * TARGET_PAGE_SIZE
;
3026 uint64_t ram_bytes_transferred(void)
3028 return bytes_transferred
;
3031 uint64_t ram_bytes_total(void)
3033 return last_ram_offset
;
3036 static int ram_save_live(Monitor
*mon
, QEMUFile
*f
, int stage
, void *opaque
)
3039 uint64_t bytes_transferred_last
;
3041 uint64_t expected_time
= 0;
3044 cpu_physical_memory_set_dirty_tracking(0);
3048 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX
) != 0) {
3049 qemu_file_set_error(f
);
3054 bytes_transferred
= 0;
3056 /* Make sure all dirty bits are set */
3057 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
3058 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
3059 cpu_physical_memory_set_dirty(addr
);
3062 /* Enable dirty memory tracking */
3063 cpu_physical_memory_set_dirty_tracking(1);
3065 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
3068 bytes_transferred_last
= bytes_transferred
;
3069 bwidth
= get_clock();
3071 while (!qemu_file_rate_limit(f
)) {
3074 ret
= ram_save_block(f
);
3075 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
3076 if (ret
== 0) /* no more blocks */
3080 bwidth
= get_clock() - bwidth
;
3081 bwidth
= (bytes_transferred
- bytes_transferred_last
) / bwidth
;
3083 /* if we haven't transferred anything this round, force expected_time to a
3084 * a very high value, but without crashing */
3088 /* try transferring iterative blocks of memory */
3090 /* flush all remaining blocks regardless of rate limiting */
3091 while (ram_save_block(f
) != 0) {
3092 bytes_transferred
+= TARGET_PAGE_SIZE
;
3094 cpu_physical_memory_set_dirty_tracking(0);
3097 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3099 expected_time
= ram_save_remaining() * TARGET_PAGE_SIZE
/ bwidth
;
3101 return (stage
== 2) && (expected_time
<= migrate_max_downtime());
3104 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
3109 if (version_id
!= 3)
3113 addr
= qemu_get_be64(f
);
3115 flags
= addr
& ~TARGET_PAGE_MASK
;
3116 addr
&= TARGET_PAGE_MASK
;
3118 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
3119 if (addr
!= last_ram_offset
)
3123 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
3124 uint8_t ch
= qemu_get_byte(f
);
3125 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
3128 (!kvm_enabled() || kvm_has_sync_mmu())) {
3129 madvise(qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
, MADV_DONTNEED
);
3132 } else if (flags
& RAM_SAVE_FLAG_PAGE
) {
3133 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
3135 if (qemu_file_has_error(f
)) {
3138 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
3143 void qemu_service_io(void)
3145 qemu_notify_event();
3148 /***********************************************************/
3149 /* machine registration */
3151 static QEMUMachine
*first_machine
= NULL
;
3152 QEMUMachine
*current_machine
= NULL
;
3154 int qemu_register_machine(QEMUMachine
*m
)
3157 pm
= &first_machine
;
3165 static QEMUMachine
*find_machine(const char *name
)
3169 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3170 if (!strcmp(m
->name
, name
))
3172 if (m
->alias
&& !strcmp(m
->alias
, name
))
3178 static QEMUMachine
*find_default_machine(void)
3182 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3183 if (m
->is_default
) {
3190 /***********************************************************/
3191 /* main execution loop */
3193 static void gui_update(void *opaque
)
3195 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3196 DisplayState
*ds
= opaque
;
3197 DisplayChangeListener
*dcl
= ds
->listeners
;
3201 while (dcl
!= NULL
) {
3202 if (dcl
->gui_timer_interval
&&
3203 dcl
->gui_timer_interval
< interval
)
3204 interval
= dcl
->gui_timer_interval
;
3207 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3210 static void nographic_update(void *opaque
)
3212 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3214 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3217 struct vm_change_state_entry
{
3218 VMChangeStateHandler
*cb
;
3220 QLIST_ENTRY (vm_change_state_entry
) entries
;
3223 static QLIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3225 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3228 VMChangeStateEntry
*e
;
3230 e
= qemu_mallocz(sizeof (*e
));
3234 QLIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3238 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3240 QLIST_REMOVE (e
, entries
);
3244 static void vm_state_notify(int running
, int reason
)
3246 VMChangeStateEntry
*e
;
3248 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3249 e
->cb(e
->opaque
, running
, reason
);
3253 static void resume_all_vcpus(void);
3254 static void pause_all_vcpus(void);
3261 vm_state_notify(1, 0);
3262 qemu_rearm_alarm_timer(alarm_timer
);
3267 /* reset/shutdown handler */
3269 typedef struct QEMUResetEntry
{
3270 QTAILQ_ENTRY(QEMUResetEntry
) entry
;
3271 QEMUResetHandler
*func
;
3275 static QTAILQ_HEAD(reset_handlers
, QEMUResetEntry
) reset_handlers
=
3276 QTAILQ_HEAD_INITIALIZER(reset_handlers
);
3277 static int reset_requested
;
3278 static int shutdown_requested
;
3279 static int powerdown_requested
;
3280 static int debug_requested
;
3281 static int vmstop_requested
;
3283 int qemu_shutdown_requested(void)
3285 int r
= shutdown_requested
;
3286 shutdown_requested
= 0;
3290 int qemu_reset_requested(void)
3292 int r
= reset_requested
;
3293 reset_requested
= 0;
3297 int qemu_powerdown_requested(void)
3299 int r
= powerdown_requested
;
3300 powerdown_requested
= 0;
3304 static int qemu_debug_requested(void)
3306 int r
= debug_requested
;
3307 debug_requested
= 0;
3311 static int qemu_vmstop_requested(void)
3313 int r
= vmstop_requested
;
3314 vmstop_requested
= 0;
3318 static void do_vm_stop(int reason
)
3321 cpu_disable_ticks();
3324 vm_state_notify(0, reason
);
3328 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3330 QEMUResetEntry
*re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3333 re
->opaque
= opaque
;
3334 QTAILQ_INSERT_TAIL(&reset_handlers
, re
, entry
);
3337 void qemu_unregister_reset(QEMUResetHandler
*func
, void *opaque
)
3341 QTAILQ_FOREACH(re
, &reset_handlers
, entry
) {
3342 if (re
->func
== func
&& re
->opaque
== opaque
) {
3343 QTAILQ_REMOVE(&reset_handlers
, re
, entry
);
3350 void qemu_system_reset(void)
3352 QEMUResetEntry
*re
, *nre
;
3354 /* reset all devices */
3355 QTAILQ_FOREACH_SAFE(re
, &reset_handlers
, entry
, nre
) {
3356 re
->func(re
->opaque
);
3360 void qemu_system_reset_request(void)
3363 shutdown_requested
= 1;
3365 reset_requested
= 1;
3367 qemu_notify_event();
3370 void qemu_system_shutdown_request(void)
3372 shutdown_requested
= 1;
3373 qemu_notify_event();
3376 void qemu_system_powerdown_request(void)
3378 powerdown_requested
= 1;
3379 qemu_notify_event();
3382 #ifdef CONFIG_IOTHREAD
3383 static void qemu_system_vmstop_request(int reason
)
3385 vmstop_requested
= reason
;
3386 qemu_notify_event();
3391 static int io_thread_fd
= -1;
3393 static void qemu_event_increment(void)
3395 static const char byte
= 0;
3397 if (io_thread_fd
== -1)
3400 write(io_thread_fd
, &byte
, sizeof(byte
));
3403 static void qemu_event_read(void *opaque
)
3405 int fd
= (unsigned long)opaque
;
3408 /* Drain the notify pipe */
3411 len
= read(fd
, buffer
, sizeof(buffer
));
3412 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
3415 static int qemu_event_init(void)
3420 err
= qemu_pipe(fds
);
3424 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3428 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3432 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3433 (void *)(unsigned long)fds
[0]);
3435 io_thread_fd
= fds
[1];
3444 HANDLE qemu_event_handle
;
3446 static void dummy_event_handler(void *opaque
)
3450 static int qemu_event_init(void)
3452 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3453 if (!qemu_event_handle
) {
3454 fprintf(stderr
, "Failed CreateEvent: %ld\n", GetLastError());
3457 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3461 static void qemu_event_increment(void)
3463 if (!SetEvent(qemu_event_handle
)) {
3464 fprintf(stderr
, "qemu_event_increment: SetEvent failed: %ld\n",
3471 static int cpu_can_run(CPUState
*env
)
3480 #ifndef CONFIG_IOTHREAD
3481 static int qemu_init_main_loop(void)
3483 return qemu_event_init();
3486 void qemu_init_vcpu(void *_env
)
3488 CPUState
*env
= _env
;
3492 env
->nr_cores
= smp_cores
;
3493 env
->nr_threads
= smp_threads
;
3497 int qemu_cpu_self(void *env
)
3502 static void resume_all_vcpus(void)
3506 static void pause_all_vcpus(void)
3510 void qemu_cpu_kick(void *env
)
3515 void qemu_notify_event(void)
3517 CPUState
*env
= cpu_single_env
;
3524 void qemu_mutex_lock_iothread(void) {}
3525 void qemu_mutex_unlock_iothread(void) {}
3527 void vm_stop(int reason
)
3532 #else /* CONFIG_IOTHREAD */
3534 #include "qemu-thread.h"
3536 QemuMutex qemu_global_mutex
;
3537 static QemuMutex qemu_fair_mutex
;
3539 static QemuThread io_thread
;
3541 static QemuThread
*tcg_cpu_thread
;
3542 static QemuCond
*tcg_halt_cond
;
3544 static int qemu_system_ready
;
3546 static QemuCond qemu_cpu_cond
;
3548 static QemuCond qemu_system_cond
;
3549 static QemuCond qemu_pause_cond
;
3551 static void block_io_signals(void);
3552 static void unblock_io_signals(void);
3553 static int tcg_has_work(void);
3555 static int qemu_init_main_loop(void)
3559 ret
= qemu_event_init();
3563 qemu_cond_init(&qemu_pause_cond
);
3564 qemu_mutex_init(&qemu_fair_mutex
);
3565 qemu_mutex_init(&qemu_global_mutex
);
3566 qemu_mutex_lock(&qemu_global_mutex
);
3568 unblock_io_signals();
3569 qemu_thread_self(&io_thread
);
3574 static void qemu_wait_io_event(CPUState
*env
)
3576 while (!tcg_has_work())
3577 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3579 qemu_mutex_unlock(&qemu_global_mutex
);
3582 * Users of qemu_global_mutex can be starved, having no chance
3583 * to acquire it since this path will get to it first.
3584 * So use another lock to provide fairness.
3586 qemu_mutex_lock(&qemu_fair_mutex
);
3587 qemu_mutex_unlock(&qemu_fair_mutex
);
3589 qemu_mutex_lock(&qemu_global_mutex
);
3593 qemu_cond_signal(&qemu_pause_cond
);
3597 static int qemu_cpu_exec(CPUState
*env
);
3599 static void *kvm_cpu_thread_fn(void *arg
)
3601 CPUState
*env
= arg
;
3604 qemu_thread_self(env
->thread
);
3608 /* signal CPU creation */
3609 qemu_mutex_lock(&qemu_global_mutex
);
3611 qemu_cond_signal(&qemu_cpu_cond
);
3613 /* and wait for machine initialization */
3614 while (!qemu_system_ready
)
3615 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3618 if (cpu_can_run(env
))
3620 qemu_wait_io_event(env
);
3626 static void tcg_cpu_exec(void);
3628 static void *tcg_cpu_thread_fn(void *arg
)
3630 CPUState
*env
= arg
;
3633 qemu_thread_self(env
->thread
);
3635 /* signal CPU creation */
3636 qemu_mutex_lock(&qemu_global_mutex
);
3637 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
3639 qemu_cond_signal(&qemu_cpu_cond
);
3641 /* and wait for machine initialization */
3642 while (!qemu_system_ready
)
3643 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3647 qemu_wait_io_event(cur_cpu
);
3653 void qemu_cpu_kick(void *_env
)
3655 CPUState
*env
= _env
;
3656 qemu_cond_broadcast(env
->halt_cond
);
3658 qemu_thread_signal(env
->thread
, SIGUSR1
);
3661 int qemu_cpu_self(void *_env
)
3663 CPUState
*env
= _env
;
3666 qemu_thread_self(&this);
3668 return qemu_thread_equal(&this, env
->thread
);
3671 static void cpu_signal(int sig
)
3674 cpu_exit(cpu_single_env
);
3677 static void block_io_signals(void)
3680 struct sigaction sigact
;
3683 sigaddset(&set
, SIGUSR2
);
3684 sigaddset(&set
, SIGIO
);
3685 sigaddset(&set
, SIGALRM
);
3686 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3689 sigaddset(&set
, SIGUSR1
);
3690 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3692 memset(&sigact
, 0, sizeof(sigact
));
3693 sigact
.sa_handler
= cpu_signal
;
3694 sigaction(SIGUSR1
, &sigact
, NULL
);
3697 static void unblock_io_signals(void)
3702 sigaddset(&set
, SIGUSR2
);
3703 sigaddset(&set
, SIGIO
);
3704 sigaddset(&set
, SIGALRM
);
3705 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3708 sigaddset(&set
, SIGUSR1
);
3709 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3712 static void qemu_signal_lock(unsigned int msecs
)
3714 qemu_mutex_lock(&qemu_fair_mutex
);
3716 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
3717 qemu_thread_signal(tcg_cpu_thread
, SIGUSR1
);
3718 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
3721 qemu_mutex_unlock(&qemu_fair_mutex
);
3724 void qemu_mutex_lock_iothread(void)
3726 if (kvm_enabled()) {
3727 qemu_mutex_lock(&qemu_fair_mutex
);
3728 qemu_mutex_lock(&qemu_global_mutex
);
3729 qemu_mutex_unlock(&qemu_fair_mutex
);
3731 qemu_signal_lock(100);
3734 void qemu_mutex_unlock_iothread(void)
3736 qemu_mutex_unlock(&qemu_global_mutex
);
3739 static int all_vcpus_paused(void)
3741 CPUState
*penv
= first_cpu
;
3746 penv
= (CPUState
*)penv
->next_cpu
;
3752 static void pause_all_vcpus(void)
3754 CPUState
*penv
= first_cpu
;
3758 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3759 qemu_cpu_kick(penv
);
3760 penv
= (CPUState
*)penv
->next_cpu
;
3763 while (!all_vcpus_paused()) {
3764 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
3767 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3768 penv
= (CPUState
*)penv
->next_cpu
;
3773 static void resume_all_vcpus(void)
3775 CPUState
*penv
= first_cpu
;
3780 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3781 qemu_cpu_kick(penv
);
3782 penv
= (CPUState
*)penv
->next_cpu
;
3786 static void tcg_init_vcpu(void *_env
)
3788 CPUState
*env
= _env
;
3789 /* share a single thread for all cpus with TCG */
3790 if (!tcg_cpu_thread
) {
3791 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3792 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3793 qemu_cond_init(env
->halt_cond
);
3794 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
3795 while (env
->created
== 0)
3796 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3797 tcg_cpu_thread
= env
->thread
;
3798 tcg_halt_cond
= env
->halt_cond
;
3800 env
->thread
= tcg_cpu_thread
;
3801 env
->halt_cond
= tcg_halt_cond
;
3805 static void kvm_start_vcpu(CPUState
*env
)
3807 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3808 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3809 qemu_cond_init(env
->halt_cond
);
3810 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
3811 while (env
->created
== 0)
3812 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3815 void qemu_init_vcpu(void *_env
)
3817 CPUState
*env
= _env
;
3820 kvm_start_vcpu(env
);
3823 env
->nr_cores
= smp_cores
;
3824 env
->nr_threads
= smp_threads
;
3827 void qemu_notify_event(void)
3829 qemu_event_increment();
3832 void vm_stop(int reason
)
3835 qemu_thread_self(&me
);
3837 if (!qemu_thread_equal(&me
, &io_thread
)) {
3838 qemu_system_vmstop_request(reason
);
3840 * FIXME: should not return to device code in case
3841 * vm_stop() has been requested.
3843 if (cpu_single_env
) {
3844 cpu_exit(cpu_single_env
);
3845 cpu_single_env
->stop
= 1;
3856 static void host_main_loop_wait(int *timeout
)
3862 /* XXX: need to suppress polling by better using win32 events */
3864 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
3865 ret
|= pe
->func(pe
->opaque
);
3869 WaitObjects
*w
= &wait_objects
;
3871 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
3872 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
3873 if (w
->func
[ret
- WAIT_OBJECT_0
])
3874 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
3876 /* Check for additional signaled events */
3877 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
3879 /* Check if event is signaled */
3880 ret2
= WaitForSingleObject(w
->events
[i
], 0);
3881 if(ret2
== WAIT_OBJECT_0
) {
3883 w
->func
[i
](w
->opaque
[i
]);
3884 } else if (ret2
== WAIT_TIMEOUT
) {
3886 err
= GetLastError();
3887 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
3890 } else if (ret
== WAIT_TIMEOUT
) {
3892 err
= GetLastError();
3893 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
3900 static void host_main_loop_wait(int *timeout
)
3905 void main_loop_wait(int timeout
)
3907 IOHandlerRecord
*ioh
;
3908 fd_set rfds
, wfds
, xfds
;
3912 qemu_bh_update_timeout(&timeout
);
3914 host_main_loop_wait(&timeout
);
3916 /* poll any events */
3917 /* XXX: separate device handlers from system ones */
3922 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3926 (!ioh
->fd_read_poll
||
3927 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
3928 FD_SET(ioh
->fd
, &rfds
);
3932 if (ioh
->fd_write
) {
3933 FD_SET(ioh
->fd
, &wfds
);
3939 tv
.tv_sec
= timeout
/ 1000;
3940 tv
.tv_usec
= (timeout
% 1000) * 1000;
3942 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
3944 qemu_mutex_unlock_iothread();
3945 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
3946 qemu_mutex_lock_iothread();
3948 IOHandlerRecord
**pioh
;
3950 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3951 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
3952 ioh
->fd_read(ioh
->opaque
);
3954 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
3955 ioh
->fd_write(ioh
->opaque
);
3959 /* remove deleted IO handlers */
3960 pioh
= &first_io_handler
;
3971 slirp_select_poll(&rfds
, &wfds
, &xfds
, (ret
< 0));
3973 /* rearm timer, if not periodic */
3974 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
3975 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
3976 qemu_rearm_alarm_timer(alarm_timer
);
3979 /* vm time timers */
3981 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
3982 qemu_run_timers(&active_timers
[QEMU_CLOCK_VIRTUAL
],
3983 qemu_get_clock(vm_clock
));
3986 /* real time timers */
3987 qemu_run_timers(&active_timers
[QEMU_CLOCK_REALTIME
],
3988 qemu_get_clock(rt_clock
));
3990 qemu_run_timers(&active_timers
[QEMU_CLOCK_HOST
],
3991 qemu_get_clock(host_clock
));
3993 /* Check bottom-halves last in case any of the earlier events triggered
3999 static int qemu_cpu_exec(CPUState
*env
)
4002 #ifdef CONFIG_PROFILER
4006 #ifdef CONFIG_PROFILER
4007 ti
= profile_getclock();
4012 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
4013 env
->icount_decr
.u16
.low
= 0;
4014 env
->icount_extra
= 0;
4015 count
= qemu_next_deadline();
4016 count
= (count
+ (1 << icount_time_shift
) - 1)
4017 >> icount_time_shift
;
4018 qemu_icount
+= count
;
4019 decr
= (count
> 0xffff) ? 0xffff : count
;
4021 env
->icount_decr
.u16
.low
= decr
;
4022 env
->icount_extra
= count
;
4024 ret
= cpu_exec(env
);
4025 #ifdef CONFIG_PROFILER
4026 qemu_time
+= profile_getclock() - ti
;
4029 /* Fold pending instructions back into the
4030 instruction counter, and clear the interrupt flag. */
4031 qemu_icount
-= (env
->icount_decr
.u16
.low
4032 + env
->icount_extra
);
4033 env
->icount_decr
.u32
= 0;
4034 env
->icount_extra
= 0;
4039 static void tcg_cpu_exec(void)
4043 if (next_cpu
== NULL
)
4044 next_cpu
= first_cpu
;
4045 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
4046 CPUState
*env
= cur_cpu
= next_cpu
;
4050 if (timer_alarm_pending
) {
4051 timer_alarm_pending
= 0;
4054 if (cpu_can_run(env
))
4055 ret
= qemu_cpu_exec(env
);
4056 if (ret
== EXCP_DEBUG
) {
4057 gdb_set_stop_cpu(env
);
4058 debug_requested
= 1;
4064 static int cpu_has_work(CPUState
*env
)
4072 if (qemu_cpu_has_work(env
))
4077 static int tcg_has_work(void)
4081 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4082 if (cpu_has_work(env
))
4087 static int qemu_calculate_timeout(void)
4089 #ifndef CONFIG_IOTHREAD
4094 else if (tcg_has_work())
4096 else if (!use_icount
)
4099 /* XXX: use timeout computed from timers */
4102 /* Advance virtual time to the next event. */
4103 if (use_icount
== 1) {
4104 /* When not using an adaptive execution frequency
4105 we tend to get badly out of sync with real time,
4106 so just delay for a reasonable amount of time. */
4109 delta
= cpu_get_icount() - cpu_get_clock();
4112 /* If virtual time is ahead of real time then just
4114 timeout
= (delta
/ 1000000) + 1;
4116 /* Wait for either IO to occur or the next
4118 add
= qemu_next_deadline();
4119 /* We advance the timer before checking for IO.
4120 Limit the amount we advance so that early IO
4121 activity won't get the guest too far ahead. */
4125 add
= (add
+ (1 << icount_time_shift
) - 1)
4126 >> icount_time_shift
;
4128 timeout
= delta
/ 1000000;
4135 #else /* CONFIG_IOTHREAD */
4140 static int vm_can_run(void)
4142 if (powerdown_requested
)
4144 if (reset_requested
)
4146 if (shutdown_requested
)
4148 if (debug_requested
)
4153 qemu_irq qemu_system_powerdown
;
4155 static void main_loop(void)
4159 #ifdef CONFIG_IOTHREAD
4160 qemu_system_ready
= 1;
4161 qemu_cond_broadcast(&qemu_system_cond
);
4166 #ifdef CONFIG_PROFILER
4169 #ifndef CONFIG_IOTHREAD
4172 #ifdef CONFIG_PROFILER
4173 ti
= profile_getclock();
4175 main_loop_wait(qemu_calculate_timeout());
4176 #ifdef CONFIG_PROFILER
4177 dev_time
+= profile_getclock() - ti
;
4179 } while (vm_can_run());
4181 if (qemu_debug_requested()) {
4182 monitor_protocol_event(QEVENT_DEBUG
, NULL
);
4183 vm_stop(EXCP_DEBUG
);
4185 if (qemu_shutdown_requested()) {
4186 monitor_protocol_event(QEVENT_SHUTDOWN
, NULL
);
4193 if (qemu_reset_requested()) {
4194 monitor_protocol_event(QEVENT_RESET
, NULL
);
4196 qemu_system_reset();
4199 if (qemu_powerdown_requested()) {
4200 monitor_protocol_event(QEVENT_POWERDOWN
, NULL
);
4201 qemu_irq_raise(qemu_system_powerdown
);
4203 if ((r
= qemu_vmstop_requested())) {
4204 monitor_protocol_event(QEVENT_STOP
, NULL
);
4211 static void version(void)
4213 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4216 static void help(int exitcode
)
4219 printf("usage: %s [options] [disk_image]\n"
4221 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4223 #define DEF(option, opt_arg, opt_enum, opt_help) \
4225 #define DEFHEADING(text) stringify(text) "\n"
4226 #include "qemu-options.h"
4231 "During emulation, the following keys are useful:\n"
4232 "ctrl-alt-f toggle full screen\n"
4233 "ctrl-alt-n switch to virtual console 'n'\n"
4234 "ctrl-alt toggle mouse and keyboard grab\n"
4236 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4241 DEFAULT_NETWORK_SCRIPT
,
4242 DEFAULT_NETWORK_DOWN_SCRIPT
,
4244 DEFAULT_GDBSTUB_PORT
,
4249 #define HAS_ARG 0x0001
4252 #define DEF(option, opt_arg, opt_enum, opt_help) \
4254 #define DEFHEADING(text)
4255 #include "qemu-options.h"
4261 typedef struct QEMUOption
{
4267 static const QEMUOption qemu_options
[] = {
4268 { "h", 0, QEMU_OPTION_h
},
4269 #define DEF(option, opt_arg, opt_enum, opt_help) \
4270 { option, opt_arg, opt_enum },
4271 #define DEFHEADING(text)
4272 #include "qemu-options.h"
4280 struct soundhw soundhw
[] = {
4281 #ifdef HAS_AUDIO_CHOICE
4282 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4288 { .init_isa
= pcspk_audio_init
}
4295 "Creative Sound Blaster 16",
4298 { .init_isa
= SB16_init
}
4302 #ifdef CONFIG_CS4231A
4308 { .init_isa
= cs4231a_init
}
4316 "Yamaha YMF262 (OPL3)",
4318 "Yamaha YM3812 (OPL2)",
4322 { .init_isa
= Adlib_init
}
4329 "Gravis Ultrasound GF1",
4332 { .init_isa
= GUS_init
}
4339 "Intel 82801AA AC97 Audio",
4342 { .init_pci
= ac97_init
}
4346 #ifdef CONFIG_ES1370
4349 "ENSONIQ AudioPCI ES1370",
4352 { .init_pci
= es1370_init
}
4356 #endif /* HAS_AUDIO_CHOICE */
4358 { NULL
, NULL
, 0, 0, { NULL
} }
4361 static void select_soundhw (const char *optarg
)
4365 if (*optarg
== '?') {
4368 printf ("Valid sound card names (comma separated):\n");
4369 for (c
= soundhw
; c
->name
; ++c
) {
4370 printf ("%-11s %s\n", c
->name
, c
->descr
);
4372 printf ("\n-soundhw all will enable all of the above\n");
4373 exit (*optarg
!= '?');
4381 if (!strcmp (optarg
, "all")) {
4382 for (c
= soundhw
; c
->name
; ++c
) {
4390 e
= strchr (p
, ',');
4391 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4393 for (c
= soundhw
; c
->name
; ++c
) {
4394 if (!strncmp (c
->name
, p
, l
) && !c
->name
[l
]) {
4403 "Unknown sound card name (too big to show)\n");
4406 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4411 p
+= l
+ (e
!= NULL
);
4415 goto show_valid_cards
;
4420 static void select_vgahw (const char *p
)
4425 vga_interface_type
= VGA_NONE
;
4426 if (strstart(p
, "std", &opts
)) {
4427 vga_interface_type
= VGA_STD
;
4428 } else if (strstart(p
, "cirrus", &opts
)) {
4429 vga_interface_type
= VGA_CIRRUS
;
4430 } else if (strstart(p
, "vmware", &opts
)) {
4431 vga_interface_type
= VGA_VMWARE
;
4432 } else if (strstart(p
, "xenfb", &opts
)) {
4433 vga_interface_type
= VGA_XENFB
;
4434 } else if (!strstart(p
, "none", &opts
)) {
4436 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4440 const char *nextopt
;
4442 if (strstart(opts
, ",retrace=", &nextopt
)) {
4444 if (strstart(opts
, "dumb", &nextopt
))
4445 vga_retrace_method
= VGA_RETRACE_DUMB
;
4446 else if (strstart(opts
, "precise", &nextopt
))
4447 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4448 else goto invalid_vga
;
4449 } else goto invalid_vga
;
4455 static int balloon_parse(const char *arg
)
4459 if (strcmp(arg
, "none") == 0) {
4463 if (!strncmp(arg
, "virtio", 6)) {
4464 if (arg
[6] == ',') {
4465 /* have params -> parse them */
4466 opts
= qemu_opts_parse(&qemu_device_opts
, arg
+7, NULL
);
4470 /* create empty opts */
4471 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4473 qemu_opt_set(opts
, "driver", "virtio-balloon-pci");
4482 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4484 exit(STATUS_CONTROL_C_EXIT
);
4489 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4493 if(strlen(str
) != 36)
4496 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4497 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4498 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4504 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4512 static void termsig_handler(int signal
)
4514 qemu_system_shutdown_request();
4517 static void sigchld_handler(int signal
)
4519 waitpid(-1, NULL
, WNOHANG
);
4522 static void sighandler_setup(void)
4524 struct sigaction act
;
4526 memset(&act
, 0, sizeof(act
));
4527 act
.sa_handler
= termsig_handler
;
4528 sigaction(SIGINT
, &act
, NULL
);
4529 sigaction(SIGHUP
, &act
, NULL
);
4530 sigaction(SIGTERM
, &act
, NULL
);
4532 act
.sa_handler
= sigchld_handler
;
4533 act
.sa_flags
= SA_NOCLDSTOP
;
4534 sigaction(SIGCHLD
, &act
, NULL
);
4540 /* Look for support files in the same directory as the executable. */
4541 static char *find_datadir(const char *argv0
)
4547 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
4554 while (p
!= buf
&& *p
!= '\\')
4557 if (access(buf
, R_OK
) == 0) {
4558 return qemu_strdup(buf
);
4564 /* Find a likely location for support files using the location of the binary.
4565 For installed binaries this will be "$bindir/../share/qemu". When
4566 running from the build tree this will be "$bindir/../pc-bios". */
4567 #define SHARE_SUFFIX "/share/qemu"
4568 #define BUILD_SUFFIX "/pc-bios"
4569 static char *find_datadir(const char *argv0
)
4577 #if defined(__linux__)
4580 len
= readlink("/proc/self/exe", buf
, sizeof(buf
) - 1);
4586 #elif defined(__FreeBSD__)
4589 len
= readlink("/proc/curproc/file", buf
, sizeof(buf
) - 1);
4596 /* If we don't have any way of figuring out the actual executable
4597 location then try argv[0]. */
4599 p
= realpath(argv0
, buf
);
4607 max_len
= strlen(dir
) +
4608 MAX(strlen(SHARE_SUFFIX
), strlen(BUILD_SUFFIX
)) + 1;
4609 res
= qemu_mallocz(max_len
);
4610 snprintf(res
, max_len
, "%s%s", dir
, SHARE_SUFFIX
);
4611 if (access(res
, R_OK
)) {
4612 snprintf(res
, max_len
, "%s%s", dir
, BUILD_SUFFIX
);
4613 if (access(res
, R_OK
)) {
4625 char *qemu_find_file(int type
, const char *name
)
4631 /* If name contains path separators then try it as a straight path. */
4632 if ((strchr(name
, '/') || strchr(name
, '\\'))
4633 && access(name
, R_OK
) == 0) {
4634 return qemu_strdup(name
);
4637 case QEMU_FILE_TYPE_BIOS
:
4640 case QEMU_FILE_TYPE_KEYMAP
:
4641 subdir
= "keymaps/";
4646 len
= strlen(data_dir
) + strlen(name
) + strlen(subdir
) + 2;
4647 buf
= qemu_mallocz(len
);
4648 snprintf(buf
, len
, "%s/%s%s", data_dir
, subdir
, name
);
4649 if (access(buf
, R_OK
)) {
4656 static int device_init_func(QemuOpts
*opts
, void *opaque
)
4660 dev
= qdev_device_add(opts
);
4666 static int chardev_init_func(QemuOpts
*opts
, void *opaque
)
4668 CharDriverState
*chr
;
4670 chr
= qemu_chr_open_opts(opts
, NULL
);
4676 static int mon_init_func(QemuOpts
*opts
, void *opaque
)
4678 CharDriverState
*chr
;
4679 const char *chardev
;
4683 mode
= qemu_opt_get(opts
, "mode");
4687 if (strcmp(mode
, "readline") == 0) {
4688 flags
= MONITOR_USE_READLINE
;
4689 } else if (strcmp(mode
, "control") == 0) {
4690 flags
= MONITOR_USE_CONTROL
;
4692 fprintf(stderr
, "unknown monitor mode \"%s\"\n", mode
);
4696 if (qemu_opt_get_bool(opts
, "default", 0))
4697 flags
|= MONITOR_IS_DEFAULT
;
4699 chardev
= qemu_opt_get(opts
, "chardev");
4700 chr
= qemu_chr_find(chardev
);
4702 fprintf(stderr
, "chardev \"%s\" not found\n", chardev
);
4706 monitor_init(chr
, flags
);
4710 static void monitor_parse(const char *optarg
, const char *mode
)
4712 static int monitor_device_index
= 0;
4718 if (strstart(optarg
, "chardev:", &p
)) {
4719 snprintf(label
, sizeof(label
), "%s", p
);
4721 if (monitor_device_index
) {
4722 snprintf(label
, sizeof(label
), "monitor%d",
4723 monitor_device_index
);
4725 snprintf(label
, sizeof(label
), "monitor");
4728 opts
= qemu_chr_parse_compat(label
, optarg
);
4730 fprintf(stderr
, "parse error: %s\n", optarg
);
4735 opts
= qemu_opts_create(&qemu_mon_opts
, label
, 1);
4737 fprintf(stderr
, "duplicate chardev: %s\n", label
);
4740 qemu_opt_set(opts
, "mode", mode
);
4741 qemu_opt_set(opts
, "chardev", label
);
4743 qemu_opt_set(opts
, "default", "on");
4744 monitor_device_index
++;
4747 struct device_config
{
4749 DEV_USB
, /* -usbdevice */
4751 DEV_SERIAL
, /* -serial */
4752 DEV_PARALLEL
, /* -parallel */
4753 DEV_VIRTCON
, /* -virtioconsole */
4755 const char *cmdline
;
4756 QTAILQ_ENTRY(device_config
) next
;
4758 QTAILQ_HEAD(, device_config
) device_configs
= QTAILQ_HEAD_INITIALIZER(device_configs
);
4760 static void add_device_config(int type
, const char *cmdline
)
4762 struct device_config
*conf
;
4764 conf
= qemu_mallocz(sizeof(*conf
));
4766 conf
->cmdline
= cmdline
;
4767 QTAILQ_INSERT_TAIL(&device_configs
, conf
, next
);
4770 static int foreach_device_config(int type
, int (*func
)(const char *cmdline
))
4772 struct device_config
*conf
;
4775 QTAILQ_FOREACH(conf
, &device_configs
, next
) {
4776 if (conf
->type
!= type
)
4778 rc
= func(conf
->cmdline
);
4785 static int serial_parse(const char *devname
)
4787 static int index
= 0;
4790 if (strcmp(devname
, "none") == 0)
4792 if (index
== MAX_SERIAL_PORTS
) {
4793 fprintf(stderr
, "qemu: too many serial ports\n");
4796 snprintf(label
, sizeof(label
), "serial%d", index
);
4797 serial_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4798 if (!serial_hds
[index
]) {
4799 fprintf(stderr
, "qemu: could not open serial device '%s': %s\n",
4800 devname
, strerror(errno
));
4807 static int parallel_parse(const char *devname
)
4809 static int index
= 0;
4812 if (strcmp(devname
, "none") == 0)
4814 if (index
== MAX_PARALLEL_PORTS
) {
4815 fprintf(stderr
, "qemu: too many parallel ports\n");
4818 snprintf(label
, sizeof(label
), "parallel%d", index
);
4819 parallel_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4820 if (!parallel_hds
[index
]) {
4821 fprintf(stderr
, "qemu: could not open parallel device '%s': %s\n",
4822 devname
, strerror(errno
));
4829 static int virtcon_parse(const char *devname
)
4831 static int index
= 0;
4834 if (strcmp(devname
, "none") == 0)
4836 if (index
== MAX_VIRTIO_CONSOLES
) {
4837 fprintf(stderr
, "qemu: too many virtio consoles\n");
4840 snprintf(label
, sizeof(label
), "virtcon%d", index
);
4841 virtcon_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4842 if (!virtcon_hds
[index
]) {
4843 fprintf(stderr
, "qemu: could not open virtio console '%s': %s\n",
4844 devname
, strerror(errno
));
4851 int main(int argc
, char **argv
, char **envp
)
4853 const char *gdbstub_dev
= NULL
;
4854 uint32_t boot_devices_bitmap
= 0;
4856 int snapshot
, linux_boot
, net_boot
;
4857 const char *initrd_filename
;
4858 const char *kernel_filename
, *kernel_cmdline
;
4859 char boot_devices
[33] = "cad"; /* default to HD->floppy->CD-ROM */
4861 DisplayChangeListener
*dcl
;
4862 int cyls
, heads
, secs
, translation
;
4863 QemuOpts
*hda_opts
= NULL
, *opts
;
4865 const char *r
, *optarg
;
4866 const char *loadvm
= NULL
;
4867 QEMUMachine
*machine
;
4868 const char *cpu_model
;
4873 const char *pid_file
= NULL
;
4874 const char *incoming
= NULL
;
4877 struct passwd
*pwd
= NULL
;
4878 const char *chroot_dir
= NULL
;
4879 const char *run_as
= NULL
;
4882 int show_vnc_port
= 0;
4886 qemu_errors_to_file(stderr
);
4887 qemu_cache_utils_init(envp
);
4889 QLIST_INIT (&vm_change_state_head
);
4892 struct sigaction act
;
4893 sigfillset(&act
.sa_mask
);
4895 act
.sa_handler
= SIG_IGN
;
4896 sigaction(SIGPIPE
, &act
, NULL
);
4899 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4900 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4901 QEMU to run on a single CPU */
4906 h
= GetCurrentProcess();
4907 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4908 for(i
= 0; i
< 32; i
++) {
4909 if (mask
& (1 << i
))
4914 SetProcessAffinityMask(h
, mask
);
4920 module_call_init(MODULE_INIT_MACHINE
);
4921 machine
= find_default_machine();
4923 initrd_filename
= NULL
;
4926 kernel_filename
= NULL
;
4927 kernel_cmdline
= "";
4928 cyls
= heads
= secs
= 0;
4929 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4931 for (i
= 0; i
< MAX_NODES
; i
++) {
4933 node_cpumask
[i
] = 0;
4948 hda_opts
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
4950 const QEMUOption
*popt
;
4953 /* Treat --foo the same as -foo. */
4956 popt
= qemu_options
;
4959 fprintf(stderr
, "%s: invalid option -- '%s'\n",
4963 if (!strcmp(popt
->name
, r
+ 1))
4967 if (popt
->flags
& HAS_ARG
) {
4968 if (optind
>= argc
) {
4969 fprintf(stderr
, "%s: option '%s' requires an argument\n",
4973 optarg
= argv
[optind
++];
4978 switch(popt
->index
) {
4980 machine
= find_machine(optarg
);
4983 printf("Supported machines are:\n");
4984 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
4986 printf("%-10s %s (alias of %s)\n",
4987 m
->alias
, m
->desc
, m
->name
);
4988 printf("%-10s %s%s\n",
4990 m
->is_default
? " (default)" : "");
4992 exit(*optarg
!= '?');
4995 case QEMU_OPTION_cpu
:
4996 /* hw initialization will check this */
4997 if (*optarg
== '?') {
4998 /* XXX: implement xxx_cpu_list for targets that still miss it */
4999 #if defined(cpu_list)
5000 cpu_list(stdout
, &fprintf
);
5007 case QEMU_OPTION_initrd
:
5008 initrd_filename
= optarg
;
5010 case QEMU_OPTION_hda
:
5012 hda_opts
= drive_add(optarg
, HD_ALIAS
, 0);
5014 hda_opts
= drive_add(optarg
, HD_ALIAS
5015 ",cyls=%d,heads=%d,secs=%d%s",
5016 0, cyls
, heads
, secs
,
5017 translation
== BIOS_ATA_TRANSLATION_LBA
?
5019 translation
== BIOS_ATA_TRANSLATION_NONE
?
5020 ",trans=none" : "");
5022 case QEMU_OPTION_hdb
:
5023 case QEMU_OPTION_hdc
:
5024 case QEMU_OPTION_hdd
:
5025 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
5027 case QEMU_OPTION_drive
:
5028 drive_add(NULL
, "%s", optarg
);
5030 case QEMU_OPTION_set
:
5031 if (qemu_set_option(optarg
) != 0)
5034 case QEMU_OPTION_global
:
5035 if (qemu_global_option(optarg
) != 0)
5038 case QEMU_OPTION_mtdblock
:
5039 drive_add(optarg
, MTD_ALIAS
);
5041 case QEMU_OPTION_sd
:
5042 drive_add(optarg
, SD_ALIAS
);
5044 case QEMU_OPTION_pflash
:
5045 drive_add(optarg
, PFLASH_ALIAS
);
5047 case QEMU_OPTION_snapshot
:
5050 case QEMU_OPTION_hdachs
:
5054 cyls
= strtol(p
, (char **)&p
, 0);
5055 if (cyls
< 1 || cyls
> 16383)
5060 heads
= strtol(p
, (char **)&p
, 0);
5061 if (heads
< 1 || heads
> 16)
5066 secs
= strtol(p
, (char **)&p
, 0);
5067 if (secs
< 1 || secs
> 63)
5071 if (!strcmp(p
, "none"))
5072 translation
= BIOS_ATA_TRANSLATION_NONE
;
5073 else if (!strcmp(p
, "lba"))
5074 translation
= BIOS_ATA_TRANSLATION_LBA
;
5075 else if (!strcmp(p
, "auto"))
5076 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5079 } else if (*p
!= '\0') {
5081 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5084 if (hda_opts
!= NULL
) {
5086 snprintf(num
, sizeof(num
), "%d", cyls
);
5087 qemu_opt_set(hda_opts
, "cyls", num
);
5088 snprintf(num
, sizeof(num
), "%d", heads
);
5089 qemu_opt_set(hda_opts
, "heads", num
);
5090 snprintf(num
, sizeof(num
), "%d", secs
);
5091 qemu_opt_set(hda_opts
, "secs", num
);
5092 if (translation
== BIOS_ATA_TRANSLATION_LBA
)
5093 qemu_opt_set(hda_opts
, "trans", "lba");
5094 if (translation
== BIOS_ATA_TRANSLATION_NONE
)
5095 qemu_opt_set(hda_opts
, "trans", "none");
5099 case QEMU_OPTION_numa
:
5100 if (nb_numa_nodes
>= MAX_NODES
) {
5101 fprintf(stderr
, "qemu: too many NUMA nodes\n");
5106 case QEMU_OPTION_nographic
:
5107 display_type
= DT_NOGRAPHIC
;
5109 #ifdef CONFIG_CURSES
5110 case QEMU_OPTION_curses
:
5111 display_type
= DT_CURSES
;
5114 case QEMU_OPTION_portrait
:
5117 case QEMU_OPTION_kernel
:
5118 kernel_filename
= optarg
;
5120 case QEMU_OPTION_append
:
5121 kernel_cmdline
= optarg
;
5123 case QEMU_OPTION_cdrom
:
5124 drive_add(optarg
, CDROM_ALIAS
);
5126 case QEMU_OPTION_boot
:
5128 static const char * const params
[] = {
5129 "order", "once", "menu", NULL
5131 char buf
[sizeof(boot_devices
)];
5132 char *standard_boot_devices
;
5135 if (!strchr(optarg
, '=')) {
5137 pstrcpy(buf
, sizeof(buf
), optarg
);
5138 } else if (check_params(buf
, sizeof(buf
), params
, optarg
) < 0) {
5140 "qemu: unknown boot parameter '%s' in '%s'\n",
5146 get_param_value(buf
, sizeof(buf
), "order", optarg
)) {
5147 boot_devices_bitmap
= parse_bootdevices(buf
);
5148 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5151 if (get_param_value(buf
, sizeof(buf
),
5153 boot_devices_bitmap
|= parse_bootdevices(buf
);
5154 standard_boot_devices
= qemu_strdup(boot_devices
);
5155 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5156 qemu_register_reset(restore_boot_devices
,
5157 standard_boot_devices
);
5159 if (get_param_value(buf
, sizeof(buf
),
5161 if (!strcmp(buf
, "on")) {
5163 } else if (!strcmp(buf
, "off")) {
5167 "qemu: invalid option value '%s'\n",
5175 case QEMU_OPTION_fda
:
5176 case QEMU_OPTION_fdb
:
5177 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
5180 case QEMU_OPTION_no_fd_bootchk
:
5184 case QEMU_OPTION_netdev
:
5185 if (net_client_parse(&qemu_netdev_opts
, optarg
) == -1) {
5189 case QEMU_OPTION_net
:
5190 if (net_client_parse(&qemu_net_opts
, optarg
) == -1) {
5195 case QEMU_OPTION_tftp
:
5196 legacy_tftp_prefix
= optarg
;
5198 case QEMU_OPTION_bootp
:
5199 legacy_bootp_filename
= optarg
;
5202 case QEMU_OPTION_smb
:
5203 if (net_slirp_smb(optarg
) < 0)
5207 case QEMU_OPTION_redir
:
5208 if (net_slirp_redir(optarg
) < 0)
5212 case QEMU_OPTION_bt
:
5213 add_device_config(DEV_BT
, optarg
);
5216 case QEMU_OPTION_audio_help
:
5220 case QEMU_OPTION_soundhw
:
5221 select_soundhw (optarg
);
5227 case QEMU_OPTION_version
:
5231 case QEMU_OPTION_m
: {
5235 value
= strtoul(optarg
, &ptr
, 10);
5237 case 0: case 'M': case 'm':
5244 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5248 /* On 32-bit hosts, QEMU is limited by virtual address space */
5249 if (value
> (2047 << 20) && HOST_LONG_BITS
== 32) {
5250 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5253 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5254 fprintf(stderr
, "qemu: ram size too large\n");
5263 const CPULogItem
*item
;
5265 mask
= cpu_str_to_log_mask(optarg
);
5267 printf("Log items (comma separated):\n");
5268 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5269 printf("%-10s %s\n", item
->name
, item
->help
);
5277 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5279 case QEMU_OPTION_gdb
:
5280 gdbstub_dev
= optarg
;
5285 case QEMU_OPTION_bios
:
5288 case QEMU_OPTION_singlestep
:
5295 keyboard_layout
= optarg
;
5297 case QEMU_OPTION_localtime
:
5300 case QEMU_OPTION_vga
:
5301 select_vgahw (optarg
);
5303 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5309 w
= strtol(p
, (char **)&p
, 10);
5312 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5318 h
= strtol(p
, (char **)&p
, 10);
5323 depth
= strtol(p
, (char **)&p
, 10);
5324 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5325 depth
!= 24 && depth
!= 32)
5327 } else if (*p
== '\0') {
5328 depth
= graphic_depth
;
5335 graphic_depth
= depth
;
5339 case QEMU_OPTION_echr
:
5342 term_escape_char
= strtol(optarg
, &r
, 0);
5344 printf("Bad argument to echr\n");
5347 case QEMU_OPTION_monitor
:
5348 monitor_parse(optarg
, "readline");
5349 default_monitor
= 0;
5351 case QEMU_OPTION_qmp
:
5352 monitor_parse(optarg
, "control");
5353 default_monitor
= 0;
5355 case QEMU_OPTION_mon
:
5356 opts
= qemu_opts_parse(&qemu_mon_opts
, optarg
, "chardev");
5358 fprintf(stderr
, "parse error: %s\n", optarg
);
5361 default_monitor
= 0;
5363 case QEMU_OPTION_chardev
:
5364 opts
= qemu_opts_parse(&qemu_chardev_opts
, optarg
, "backend");
5366 fprintf(stderr
, "parse error: %s\n", optarg
);
5370 case QEMU_OPTION_serial
:
5371 add_device_config(DEV_SERIAL
, optarg
);
5374 case QEMU_OPTION_watchdog
:
5377 "qemu: only one watchdog option may be given\n");
5382 case QEMU_OPTION_watchdog_action
:
5383 if (select_watchdog_action(optarg
) == -1) {
5384 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5388 case QEMU_OPTION_virtiocon
:
5389 add_device_config(DEV_VIRTCON
, optarg
);
5390 default_virtcon
= 0;
5392 case QEMU_OPTION_parallel
:
5393 add_device_config(DEV_PARALLEL
, optarg
);
5394 default_parallel
= 0;
5396 case QEMU_OPTION_loadvm
:
5399 case QEMU_OPTION_full_screen
:
5403 case QEMU_OPTION_no_frame
:
5406 case QEMU_OPTION_alt_grab
:
5409 case QEMU_OPTION_ctrl_grab
:
5412 case QEMU_OPTION_no_quit
:
5415 case QEMU_OPTION_sdl
:
5416 display_type
= DT_SDL
;
5419 case QEMU_OPTION_pidfile
:
5423 case QEMU_OPTION_win2k_hack
:
5424 win2k_install_hack
= 1;
5426 case QEMU_OPTION_rtc_td_hack
:
5429 case QEMU_OPTION_acpitable
:
5430 if(acpi_table_add(optarg
) < 0) {
5431 fprintf(stderr
, "Wrong acpi table provided\n");
5435 case QEMU_OPTION_smbios
:
5436 if(smbios_entry_add(optarg
) < 0) {
5437 fprintf(stderr
, "Wrong smbios provided\n");
5443 case QEMU_OPTION_enable_kvm
:
5447 case QEMU_OPTION_usb
:
5450 case QEMU_OPTION_usbdevice
:
5452 add_device_config(DEV_USB
, optarg
);
5454 case QEMU_OPTION_device
:
5455 if (!qemu_opts_parse(&qemu_device_opts
, optarg
, "driver")) {
5459 case QEMU_OPTION_smp
:
5462 fprintf(stderr
, "Invalid number of CPUs\n");
5465 if (max_cpus
< smp_cpus
) {
5466 fprintf(stderr
, "maxcpus must be equal to or greater than "
5470 if (max_cpus
> 255) {
5471 fprintf(stderr
, "Unsupported number of maxcpus\n");
5475 case QEMU_OPTION_vnc
:
5476 display_type
= DT_VNC
;
5477 vnc_display
= optarg
;
5480 case QEMU_OPTION_no_acpi
:
5483 case QEMU_OPTION_no_hpet
:
5486 case QEMU_OPTION_balloon
:
5487 if (balloon_parse(optarg
) < 0) {
5488 fprintf(stderr
, "Unknown -balloon argument %s\n", optarg
);
5493 case QEMU_OPTION_no_reboot
:
5496 case QEMU_OPTION_no_shutdown
:
5499 case QEMU_OPTION_show_cursor
:
5502 case QEMU_OPTION_uuid
:
5503 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5504 fprintf(stderr
, "Fail to parse UUID string."
5505 " Wrong format.\n");
5510 case QEMU_OPTION_daemonize
:
5514 case QEMU_OPTION_option_rom
:
5515 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5516 fprintf(stderr
, "Too many option ROMs\n");
5519 option_rom
[nb_option_roms
] = optarg
;
5522 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5523 case QEMU_OPTION_semihosting
:
5524 semihosting_enabled
= 1;
5527 case QEMU_OPTION_name
:
5528 qemu_name
= qemu_strdup(optarg
);
5530 char *p
= strchr(qemu_name
, ',');
5533 if (strncmp(p
, "process=", 8)) {
5534 fprintf(stderr
, "Unknown subargument %s to -name", p
);
5542 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5543 case QEMU_OPTION_prom_env
:
5544 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5545 fprintf(stderr
, "Too many prom variables\n");
5548 prom_envs
[nb_prom_envs
] = optarg
;
5553 case QEMU_OPTION_old_param
:
5557 case QEMU_OPTION_clock
:
5558 configure_alarms(optarg
);
5560 case QEMU_OPTION_startdate
:
5561 configure_rtc_date_offset(optarg
, 1);
5563 case QEMU_OPTION_rtc
:
5564 opts
= qemu_opts_parse(&qemu_rtc_opts
, optarg
, NULL
);
5566 fprintf(stderr
, "parse error: %s\n", optarg
);
5569 configure_rtc(opts
);
5571 case QEMU_OPTION_tb_size
:
5572 tb_size
= strtol(optarg
, NULL
, 0);
5576 case QEMU_OPTION_icount
:
5578 if (strcmp(optarg
, "auto") == 0) {
5579 icount_time_shift
= -1;
5581 icount_time_shift
= strtol(optarg
, NULL
, 0);
5584 case QEMU_OPTION_incoming
:
5587 case QEMU_OPTION_nodefaults
:
5589 default_parallel
= 0;
5590 default_virtcon
= 0;
5591 default_monitor
= 0;
5597 case QEMU_OPTION_chroot
:
5598 chroot_dir
= optarg
;
5600 case QEMU_OPTION_runas
:
5605 case QEMU_OPTION_xen_domid
:
5606 xen_domid
= atoi(optarg
);
5608 case QEMU_OPTION_xen_create
:
5609 xen_mode
= XEN_CREATE
;
5611 case QEMU_OPTION_xen_attach
:
5612 xen_mode
= XEN_ATTACH
;
5615 case QEMU_OPTION_readconfig
:
5618 fp
= fopen(optarg
, "r");
5620 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5623 if (qemu_config_parse(fp
) != 0) {
5629 case QEMU_OPTION_writeconfig
:
5632 if (strcmp(optarg
, "-") == 0) {
5635 fp
= fopen(optarg
, "w");
5637 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5641 qemu_config_write(fp
);
5649 /* If no data_dir is specified then try to find it relative to the
5652 data_dir
= find_datadir(argv
[0]);
5654 /* If all else fails use the install patch specified when building. */
5656 data_dir
= CONFIG_QEMU_SHAREDIR
;
5660 * Default to max_cpus = smp_cpus, in case the user doesn't
5661 * specify a max_cpus value.
5664 max_cpus
= smp_cpus
;
5666 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5667 if (smp_cpus
> machine
->max_cpus
) {
5668 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5669 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5674 qemu_opts_foreach(&qemu_device_opts
, default_driver_check
, NULL
, 0);
5676 if (machine
->no_serial
) {
5679 if (machine
->no_parallel
) {
5680 default_parallel
= 0;
5682 if (!machine
->use_virtcon
) {
5683 default_virtcon
= 0;
5685 if (machine
->no_vga
) {
5689 if (display_type
== DT_NOGRAPHIC
) {
5690 if (default_parallel
)
5691 add_device_config(DEV_PARALLEL
, "null");
5692 if (default_serial
&& default_monitor
) {
5693 add_device_config(DEV_SERIAL
, "mon:stdio");
5694 } else if (default_virtcon
&& default_monitor
) {
5695 add_device_config(DEV_VIRTCON
, "mon:stdio");
5698 add_device_config(DEV_SERIAL
, "stdio");
5699 if (default_virtcon
)
5700 add_device_config(DEV_VIRTCON
, "stdio");
5701 if (default_monitor
)
5702 monitor_parse("stdio", "readline");
5706 add_device_config(DEV_SERIAL
, "vc:80Cx24C");
5707 if (default_parallel
)
5708 add_device_config(DEV_PARALLEL
, "vc:80Cx24C");
5709 if (default_monitor
)
5710 monitor_parse("vc:80Cx24C", "readline");
5711 if (default_virtcon
)
5712 add_device_config(DEV_VIRTCON
, "vc:80Cx24C");
5715 vga_interface_type
= VGA_CIRRUS
;
5717 if (qemu_opts_foreach(&qemu_chardev_opts
, chardev_init_func
, NULL
, 1) != 0)
5724 if (pipe(fds
) == -1)
5735 len
= read(fds
[0], &status
, 1);
5736 if (len
== -1 && (errno
== EINTR
))
5741 else if (status
== 1) {
5742 fprintf(stderr
, "Could not acquire pidfile: %s\n", strerror(errno
));
5750 qemu_set_cloexec(fds
[1]);
5762 signal(SIGTSTP
, SIG_IGN
);
5763 signal(SIGTTOU
, SIG_IGN
);
5764 signal(SIGTTIN
, SIG_IGN
);
5767 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5770 write(fds
[1], &status
, 1);
5772 fprintf(stderr
, "Could not acquire pid file: %s\n", strerror(errno
));
5777 if (kvm_enabled()) {
5780 ret
= kvm_init(smp_cpus
);
5782 fprintf(stderr
, "failed to initialize KVM\n");
5787 if (qemu_init_main_loop()) {
5788 fprintf(stderr
, "qemu_init_main_loop failed\n");
5791 linux_boot
= (kernel_filename
!= NULL
);
5793 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5794 fprintf(stderr
, "-append only allowed with -kernel option\n");
5798 if (!linux_boot
&& initrd_filename
!= NULL
) {
5799 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5804 /* Win32 doesn't support line-buffering and requires size >= 2 */
5805 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5808 if (init_timer_alarm() < 0) {
5809 fprintf(stderr
, "could not initialize alarm timer\n");
5812 if (use_icount
&& icount_time_shift
< 0) {
5814 /* 125MIPS seems a reasonable initial guess at the guest speed.
5815 It will be corrected fairly quickly anyway. */
5816 icount_time_shift
= 3;
5817 init_icount_adjust();
5824 if (net_init_clients() < 0) {
5828 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5829 net_set_boot_mask(net_boot
);
5831 /* init the bluetooth world */
5832 if (foreach_device_config(DEV_BT
, bt_parse
))
5835 /* init the memory */
5837 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5839 /* init the dynamic translator */
5840 cpu_exec_init_all(tb_size
* 1024 * 1024);
5842 bdrv_init_with_whitelist();
5846 if (default_drive
) {
5847 /* we always create the cdrom drive, even if no disk is there */
5848 drive_add(NULL
, CDROM_ALIAS
);
5850 /* we always create at least one floppy */
5851 drive_add(NULL
, FD_ALIAS
, 0);
5853 /* we always create one sd slot, even if no card is in it */
5854 drive_add(NULL
, SD_ALIAS
);
5857 /* open the virtual block devices */
5859 qemu_opts_foreach(&qemu_drive_opts
, drive_enable_snapshot
, NULL
, 0);
5860 if (qemu_opts_foreach(&qemu_drive_opts
, drive_init_func
, machine
, 1) != 0)
5863 vmstate_register(0, &vmstate_timers
,&timers_state
);
5864 register_savevm_live("ram", 0, 3, NULL
, ram_save_live
, NULL
,
5867 if (nb_numa_nodes
> 0) {
5870 if (nb_numa_nodes
> smp_cpus
) {
5871 nb_numa_nodes
= smp_cpus
;
5874 /* If no memory size if given for any node, assume the default case
5875 * and distribute the available memory equally across all nodes
5877 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5878 if (node_mem
[i
] != 0)
5881 if (i
== nb_numa_nodes
) {
5882 uint64_t usedmem
= 0;
5884 /* On Linux, the each node's border has to be 8MB aligned,
5885 * the final node gets the rest.
5887 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
5888 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
5889 usedmem
+= node_mem
[i
];
5891 node_mem
[i
] = ram_size
- usedmem
;
5894 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5895 if (node_cpumask
[i
] != 0)
5898 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5899 * must cope with this anyway, because there are BIOSes out there in
5900 * real machines which also use this scheme.
5902 if (i
== nb_numa_nodes
) {
5903 for (i
= 0; i
< smp_cpus
; i
++) {
5904 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
5909 if (foreach_device_config(DEV_SERIAL
, serial_parse
) < 0)
5911 if (foreach_device_config(DEV_PARALLEL
, parallel_parse
) < 0)
5913 if (foreach_device_config(DEV_VIRTCON
, virtcon_parse
) < 0)
5916 module_call_init(MODULE_INIT_DEVICE
);
5919 i
= select_watchdog(watchdog
);
5921 exit (i
== 1 ? 1 : 0);
5924 if (machine
->compat_props
) {
5925 qdev_prop_register_global_list(machine
->compat_props
);
5929 machine
->init(ram_size
, boot_devices
,
5930 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
5934 /* must be after terminal init, SDL library changes signal handlers */
5938 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
5939 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5940 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
5946 current_machine
= machine
;
5948 /* init USB devices */
5950 if (foreach_device_config(DEV_USB
, usb_parse
) < 0)
5954 /* init generic devices */
5955 if (qemu_opts_foreach(&qemu_device_opts
, device_init_func
, NULL
, 1) != 0)
5959 dumb_display_init();
5960 /* just use the first displaystate for the moment */
5963 if (display_type
== DT_DEFAULT
) {
5964 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5965 display_type
= DT_SDL
;
5967 display_type
= DT_VNC
;
5968 vnc_display
= "localhost:0,to=99";
5974 switch (display_type
) {
5977 #if defined(CONFIG_CURSES)
5979 curses_display_init(ds
, full_screen
);
5982 #if defined(CONFIG_SDL)
5984 sdl_display_init(ds
, full_screen
, no_frame
);
5986 #elif defined(CONFIG_COCOA)
5988 cocoa_display_init(ds
, full_screen
);
5992 vnc_display_init(ds
);
5993 if (vnc_display_open(ds
, vnc_display
) < 0)
5996 if (show_vnc_port
) {
5997 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
6005 dcl
= ds
->listeners
;
6006 while (dcl
!= NULL
) {
6007 if (dcl
->dpy_refresh
!= NULL
) {
6008 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
6009 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
6014 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
6015 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
6016 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
6019 text_consoles_set_display(display_state
);
6021 if (qemu_opts_foreach(&qemu_mon_opts
, mon_init_func
, NULL
, 1) != 0)
6024 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
6025 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
6030 qdev_machine_creation_done();
6034 qemu_system_reset();
6036 if (load_vmstate(cur_mon
, loadvm
) < 0) {
6042 qemu_start_incoming_migration(incoming
);
6043 } else if (autostart
) {
6053 len
= write(fds
[1], &status
, 1);
6054 if (len
== -1 && (errno
== EINTR
))
6061 TFR(fd
= qemu_open("/dev/null", O_RDWR
));
6067 pwd
= getpwnam(run_as
);
6069 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
6075 if (chroot(chroot_dir
) < 0) {
6076 fprintf(stderr
, "chroot failed\n");
6083 if (setgid(pwd
->pw_gid
) < 0) {
6084 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
6087 if (setuid(pwd
->pw_uid
) < 0) {
6088 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
6091 if (setuid(0) != -1) {
6092 fprintf(stderr
, "Dropping privileges failed\n");