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"
34 /* Needed early to override system queue definitions on BSD */
35 #include "sys-queue.h"
40 #include <sys/times.h>
44 #include <sys/ioctl.h>
45 #include <sys/resource.h>
46 #include <sys/socket.h>
47 #include <netinet/in.h>
49 #if defined(__NetBSD__)
50 #include <net/if_tap.h>
53 #include <linux/if_tun.h>
55 #include <arpa/inet.h>
58 #include <sys/select.h>
61 #if defined(__FreeBSD__) || defined(__DragonFly__)
66 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
67 #include <freebsd/stdlib.h>
72 #include <linux/rtc.h>
73 #include <sys/prctl.h>
75 /* For the benefit of older linux systems which don't supply it,
76 we use a local copy of hpet.h. */
77 /* #include <linux/hpet.h> */
80 #include <linux/ppdev.h>
81 #include <linux/parport.h>
85 #include <sys/ethernet.h>
86 #include <sys/sockio.h>
87 #include <netinet/arp.h>
88 #include <netinet/in.h>
89 #include <netinet/in_systm.h>
90 #include <netinet/ip.h>
91 #include <netinet/ip_icmp.h> // must come after ip.h
92 #include <netinet/udp.h>
93 #include <netinet/tcp.h>
101 #if defined(__OpenBSD__)
105 #if defined(CONFIG_VDE)
106 #include <libvdeplug.h>
111 #include <mmsystem.h>
115 #if defined(__APPLE__) || defined(main)
117 int qemu_main(int argc
, char **argv
, char **envp
);
118 int main(int argc
, char **argv
)
120 return qemu_main(argc
, argv
, NULL
);
123 #define main qemu_main
125 #endif /* CONFIG_SDL */
129 #define main qemu_main
130 #endif /* CONFIG_COCOA */
133 #include "hw/boards.h"
135 #include "hw/pcmcia.h"
137 #include "hw/audiodev.h"
141 #include "hw/watchdog.h"
142 #include "hw/smbios.h"
151 #include "qemu-timer.h"
152 #include "qemu-char.h"
153 #include "cache-utils.h"
156 #include "audio/audio.h"
157 #include "migration.h"
160 #include "qemu-option.h"
161 #include "qemu-config.h"
165 #include "exec-all.h"
167 #include "qemu_socket.h"
169 #include "slirp/libslirp.h"
172 //#define DEBUG_SLIRP
174 #define DEFAULT_RAM_SIZE 128
176 /* Maximum number of monitor devices */
177 #define MAX_MONITOR_DEVICES 10
179 static const char *data_dir
;
180 const char *bios_name
= NULL
;
181 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
182 to store the VM snapshots */
183 struct drivelist drives
= TAILQ_HEAD_INITIALIZER(drives
);
184 struct driveoptlist driveopts
= TAILQ_HEAD_INITIALIZER(driveopts
);
185 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
186 static DisplayState
*display_state
;
187 DisplayType display_type
= DT_DEFAULT
;
188 const char* keyboard_layout
= NULL
;
191 NICInfo nd_table
[MAX_NICS
];
194 static int rtc_utc
= 1;
195 static int rtc_date_offset
= -1; /* -1 means no change */
196 int vga_interface_type
= VGA_CIRRUS
;
198 int graphic_width
= 1024;
199 int graphic_height
= 768;
200 int graphic_depth
= 8;
202 int graphic_width
= 800;
203 int graphic_height
= 600;
204 int graphic_depth
= 15;
206 static int full_screen
= 0;
208 static int no_frame
= 0;
211 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
212 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
213 CharDriverState
*virtcon_hds
[MAX_VIRTIO_CONSOLES
];
215 int win2k_install_hack
= 0;
224 const char *vnc_display
;
225 int acpi_enabled
= 1;
231 int graphic_rotate
= 0;
232 uint8_t irq0override
= 1;
236 const char *watchdog
;
237 const char *option_rom
[MAX_OPTION_ROMS
];
239 int semihosting_enabled
= 0;
243 const char *qemu_name
;
245 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
246 unsigned int nb_prom_envs
= 0;
247 const char *prom_envs
[MAX_PROM_ENVS
];
252 uint64_t node_mem
[MAX_NODES
];
253 uint64_t node_cpumask
[MAX_NODES
];
255 static CPUState
*cur_cpu
;
256 static CPUState
*next_cpu
;
257 static int timer_alarm_pending
= 1;
258 /* Conversion factor from emulated instructions to virtual clock ticks. */
259 static int icount_time_shift
;
260 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
261 #define MAX_ICOUNT_SHIFT 10
262 /* Compensate for varying guest execution speed. */
263 static int64_t qemu_icount_bias
;
264 static QEMUTimer
*icount_rt_timer
;
265 static QEMUTimer
*icount_vm_timer
;
266 static QEMUTimer
*nographic_timer
;
268 uint8_t qemu_uuid
[16];
270 static QEMUBootSetHandler
*boot_set_handler
;
271 static void *boot_set_opaque
;
273 /***********************************************************/
274 /* x86 ISA bus support */
276 target_phys_addr_t isa_mem_base
= 0;
279 /***********************************************************/
280 void hw_error(const char *fmt
, ...)
286 fprintf(stderr
, "qemu: hardware error: ");
287 vfprintf(stderr
, fmt
, ap
);
288 fprintf(stderr
, "\n");
289 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
290 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
292 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
294 cpu_dump_state(env
, stderr
, fprintf
, 0);
301 static void set_proc_name(const char *s
)
303 #if defined(__linux__) && defined(PR_SET_NAME)
307 name
[sizeof(name
) - 1] = 0;
308 strncpy(name
, s
, sizeof(name
));
309 /* Could rewrite argv[0] too, but that's a bit more complicated.
310 This simple way is enough for `top'. */
311 prctl(PR_SET_NAME
, name
);
318 static QEMUBalloonEvent
*qemu_balloon_event
;
319 void *qemu_balloon_event_opaque
;
321 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
323 qemu_balloon_event
= func
;
324 qemu_balloon_event_opaque
= opaque
;
327 void qemu_balloon(ram_addr_t target
)
329 if (qemu_balloon_event
)
330 qemu_balloon_event(qemu_balloon_event_opaque
, target
);
333 ram_addr_t
qemu_balloon_status(void)
335 if (qemu_balloon_event
)
336 return qemu_balloon_event(qemu_balloon_event_opaque
, 0);
340 /***********************************************************/
343 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
344 static void *qemu_put_kbd_event_opaque
;
345 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
346 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
348 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
350 qemu_put_kbd_event_opaque
= opaque
;
351 qemu_put_kbd_event
= func
;
354 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
355 void *opaque
, int absolute
,
358 QEMUPutMouseEntry
*s
, *cursor
;
360 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
362 s
->qemu_put_mouse_event
= func
;
363 s
->qemu_put_mouse_event_opaque
= opaque
;
364 s
->qemu_put_mouse_event_absolute
= absolute
;
365 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
368 if (!qemu_put_mouse_event_head
) {
369 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
373 cursor
= qemu_put_mouse_event_head
;
374 while (cursor
->next
!= NULL
)
375 cursor
= cursor
->next
;
378 qemu_put_mouse_event_current
= s
;
383 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
385 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
387 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
390 cursor
= qemu_put_mouse_event_head
;
391 while (cursor
!= NULL
&& cursor
!= entry
) {
393 cursor
= cursor
->next
;
396 if (cursor
== NULL
) // does not exist or list empty
398 else if (prev
== NULL
) { // entry is head
399 qemu_put_mouse_event_head
= cursor
->next
;
400 if (qemu_put_mouse_event_current
== entry
)
401 qemu_put_mouse_event_current
= cursor
->next
;
402 qemu_free(entry
->qemu_put_mouse_event_name
);
407 prev
->next
= entry
->next
;
409 if (qemu_put_mouse_event_current
== entry
)
410 qemu_put_mouse_event_current
= prev
;
412 qemu_free(entry
->qemu_put_mouse_event_name
);
416 void kbd_put_keycode(int keycode
)
418 if (qemu_put_kbd_event
) {
419 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
423 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
425 QEMUPutMouseEvent
*mouse_event
;
426 void *mouse_event_opaque
;
429 if (!qemu_put_mouse_event_current
) {
434 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
436 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
439 if (graphic_rotate
) {
440 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
443 width
= graphic_width
- 1;
444 mouse_event(mouse_event_opaque
,
445 width
- dy
, dx
, dz
, buttons_state
);
447 mouse_event(mouse_event_opaque
,
448 dx
, dy
, dz
, buttons_state
);
452 int kbd_mouse_is_absolute(void)
454 if (!qemu_put_mouse_event_current
)
457 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
460 void do_info_mice(Monitor
*mon
)
462 QEMUPutMouseEntry
*cursor
;
465 if (!qemu_put_mouse_event_head
) {
466 monitor_printf(mon
, "No mouse devices connected\n");
470 monitor_printf(mon
, "Mouse devices available:\n");
471 cursor
= qemu_put_mouse_event_head
;
472 while (cursor
!= NULL
) {
473 monitor_printf(mon
, "%c Mouse #%d: %s\n",
474 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
475 index
, cursor
->qemu_put_mouse_event_name
);
477 cursor
= cursor
->next
;
481 void do_mouse_set(Monitor
*mon
, const QDict
*qdict
)
483 QEMUPutMouseEntry
*cursor
;
485 int index
= qdict_get_int(qdict
, "index");
487 if (!qemu_put_mouse_event_head
) {
488 monitor_printf(mon
, "No mouse devices connected\n");
492 cursor
= qemu_put_mouse_event_head
;
493 while (cursor
!= NULL
&& index
!= i
) {
495 cursor
= cursor
->next
;
499 qemu_put_mouse_event_current
= cursor
;
501 monitor_printf(mon
, "Mouse at given index not found\n");
504 /* compute with 96 bit intermediate result: (a*b)/c */
505 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
510 #ifdef HOST_WORDS_BIGENDIAN
520 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
521 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
524 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
528 /***********************************************************/
529 /* real time host monotonic timer */
531 #define QEMU_TIMER_BASE 1000000000LL
535 static int64_t clock_freq
;
537 static void init_get_clock(void)
541 ret
= QueryPerformanceFrequency(&freq
);
543 fprintf(stderr
, "Could not calibrate ticks\n");
546 clock_freq
= freq
.QuadPart
;
549 static int64_t get_clock(void)
552 QueryPerformanceCounter(&ti
);
553 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
558 static int use_rt_clock
;
560 static void init_get_clock(void)
563 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
564 || defined(__DragonFly__)
567 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
574 static int64_t get_clock(void)
576 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
577 || defined(__DragonFly__)
580 clock_gettime(CLOCK_MONOTONIC
, &ts
);
581 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
585 /* XXX: using gettimeofday leads to problems if the date
586 changes, so it should be avoided. */
588 gettimeofday(&tv
, NULL
);
589 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
594 /* Return the virtual CPU time, based on the instruction counter. */
595 static int64_t cpu_get_icount(void)
598 CPUState
*env
= cpu_single_env
;;
599 icount
= qemu_icount
;
602 fprintf(stderr
, "Bad clock read\n");
603 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
605 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
608 /***********************************************************/
609 /* guest cycle counter */
611 typedef struct TimersState
{
612 int64_t cpu_ticks_prev
;
613 int64_t cpu_ticks_offset
;
614 int64_t cpu_clock_offset
;
615 int32_t cpu_ticks_enabled
;
616 int64_t ticks_per_sec
;
619 TimersState timers_state
;
621 /* return the host CPU cycle counter and handle stop/restart */
622 int64_t cpu_get_ticks(void)
625 return cpu_get_icount();
627 if (!timers_state
.cpu_ticks_enabled
) {
628 return timers_state
.cpu_ticks_offset
;
631 ticks
= cpu_get_real_ticks();
632 if (timers_state
.cpu_ticks_prev
> ticks
) {
633 /* Note: non increasing ticks may happen if the host uses
635 timers_state
.cpu_ticks_offset
+= timers_state
.cpu_ticks_prev
- ticks
;
637 timers_state
.cpu_ticks_prev
= ticks
;
638 return ticks
+ timers_state
.cpu_ticks_offset
;
642 /* return the host CPU monotonic timer and handle stop/restart */
643 static int64_t cpu_get_clock(void)
646 if (!timers_state
.cpu_ticks_enabled
) {
647 return timers_state
.cpu_clock_offset
;
650 return ti
+ timers_state
.cpu_clock_offset
;
654 /* enable cpu_get_ticks() */
655 void cpu_enable_ticks(void)
657 if (!timers_state
.cpu_ticks_enabled
) {
658 timers_state
.cpu_ticks_offset
-= cpu_get_real_ticks();
659 timers_state
.cpu_clock_offset
-= get_clock();
660 timers_state
.cpu_ticks_enabled
= 1;
664 /* disable cpu_get_ticks() : the clock is stopped. You must not call
665 cpu_get_ticks() after that. */
666 void cpu_disable_ticks(void)
668 if (timers_state
.cpu_ticks_enabled
) {
669 timers_state
.cpu_ticks_offset
= cpu_get_ticks();
670 timers_state
.cpu_clock_offset
= cpu_get_clock();
671 timers_state
.cpu_ticks_enabled
= 0;
675 /***********************************************************/
678 #define QEMU_TIMER_REALTIME 0
679 #define QEMU_TIMER_VIRTUAL 1
683 /* XXX: add frequency */
691 struct QEMUTimer
*next
;
694 struct qemu_alarm_timer
{
698 int (*start
)(struct qemu_alarm_timer
*t
);
699 void (*stop
)(struct qemu_alarm_timer
*t
);
700 void (*rearm
)(struct qemu_alarm_timer
*t
);
704 #define ALARM_FLAG_DYNTICKS 0x1
705 #define ALARM_FLAG_EXPIRED 0x2
707 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
709 return t
&& (t
->flags
& ALARM_FLAG_DYNTICKS
);
712 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
714 if (!alarm_has_dynticks(t
))
720 /* TODO: MIN_TIMER_REARM_US should be optimized */
721 #define MIN_TIMER_REARM_US 250
723 static struct qemu_alarm_timer
*alarm_timer
;
727 struct qemu_alarm_win32
{
730 } alarm_win32_data
= {0, -1};
732 static int win32_start_timer(struct qemu_alarm_timer
*t
);
733 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
734 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
738 static int unix_start_timer(struct qemu_alarm_timer
*t
);
739 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
743 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
744 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
745 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
747 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
748 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
750 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
751 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
753 #endif /* __linux__ */
757 /* Correlation between real and virtual time is always going to be
758 fairly approximate, so ignore small variation.
759 When the guest is idle real and virtual time will be aligned in
761 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
763 static void icount_adjust(void)
768 static int64_t last_delta
;
769 /* If the VM is not running, then do nothing. */
773 cur_time
= cpu_get_clock();
774 cur_icount
= qemu_get_clock(vm_clock
);
775 delta
= cur_icount
- cur_time
;
776 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
778 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
779 && icount_time_shift
> 0) {
780 /* The guest is getting too far ahead. Slow time down. */
784 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
785 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
786 /* The guest is getting too far behind. Speed time up. */
790 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
793 static void icount_adjust_rt(void * opaque
)
795 qemu_mod_timer(icount_rt_timer
,
796 qemu_get_clock(rt_clock
) + 1000);
800 static void icount_adjust_vm(void * opaque
)
802 qemu_mod_timer(icount_vm_timer
,
803 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
807 static void init_icount_adjust(void)
809 /* Have both realtime and virtual time triggers for speed adjustment.
810 The realtime trigger catches emulated time passing too slowly,
811 the virtual time trigger catches emulated time passing too fast.
812 Realtime triggers occur even when idle, so use them less frequently
814 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
815 qemu_mod_timer(icount_rt_timer
,
816 qemu_get_clock(rt_clock
) + 1000);
817 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
818 qemu_mod_timer(icount_vm_timer
,
819 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
822 static struct qemu_alarm_timer alarm_timers
[] = {
825 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
826 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
827 /* HPET - if available - is preferred */
828 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
829 /* ...otherwise try RTC */
830 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
832 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
834 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
835 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
836 {"win32", 0, win32_start_timer
,
837 win32_stop_timer
, NULL
, &alarm_win32_data
},
842 static void show_available_alarms(void)
846 printf("Available alarm timers, in order of precedence:\n");
847 for (i
= 0; alarm_timers
[i
].name
; i
++)
848 printf("%s\n", alarm_timers
[i
].name
);
851 static void configure_alarms(char const *opt
)
855 int count
= ARRAY_SIZE(alarm_timers
) - 1;
858 struct qemu_alarm_timer tmp
;
860 if (!strcmp(opt
, "?")) {
861 show_available_alarms();
865 arg
= qemu_strdup(opt
);
867 /* Reorder the array */
868 name
= strtok(arg
, ",");
870 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
871 if (!strcmp(alarm_timers
[i
].name
, name
))
876 fprintf(stderr
, "Unknown clock %s\n", name
);
885 tmp
= alarm_timers
[i
];
886 alarm_timers
[i
] = alarm_timers
[cur
];
887 alarm_timers
[cur
] = tmp
;
891 name
= strtok(NULL
, ",");
897 /* Disable remaining timers */
898 for (i
= cur
; i
< count
; i
++)
899 alarm_timers
[i
].name
= NULL
;
901 show_available_alarms();
909 static QEMUTimer
*active_timers
[2];
911 static QEMUClock
*qemu_new_clock(int type
)
914 clock
= qemu_mallocz(sizeof(QEMUClock
));
919 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
923 ts
= qemu_mallocz(sizeof(QEMUTimer
));
930 void qemu_free_timer(QEMUTimer
*ts
)
935 /* stop a timer, but do not dealloc it */
936 void qemu_del_timer(QEMUTimer
*ts
)
940 /* NOTE: this code must be signal safe because
941 qemu_timer_expired() can be called from a signal. */
942 pt
= &active_timers
[ts
->clock
->type
];
955 /* modify the current timer so that it will be fired when current_time
956 >= expire_time. The corresponding callback will be called. */
957 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
963 /* add the timer in the sorted list */
964 /* NOTE: this code must be signal safe because
965 qemu_timer_expired() can be called from a signal. */
966 pt
= &active_timers
[ts
->clock
->type
];
971 if (t
->expire_time
> expire_time
)
975 ts
->expire_time
= expire_time
;
979 /* Rearm if necessary */
980 if (pt
== &active_timers
[ts
->clock
->type
]) {
981 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
982 qemu_rearm_alarm_timer(alarm_timer
);
984 /* Interrupt execution to force deadline recalculation. */
990 int qemu_timer_pending(QEMUTimer
*ts
)
993 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1000 int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1004 return (timer_head
->expire_time
<= current_time
);
1007 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1013 if (!ts
|| ts
->expire_time
> current_time
)
1015 /* remove timer from the list before calling the callback */
1016 *ptimer_head
= ts
->next
;
1019 /* run the callback (the timer list can be modified) */
1024 int64_t qemu_get_clock(QEMUClock
*clock
)
1026 switch(clock
->type
) {
1027 case QEMU_TIMER_REALTIME
:
1028 return get_clock() / 1000000;
1030 case QEMU_TIMER_VIRTUAL
:
1032 return cpu_get_icount();
1034 return cpu_get_clock();
1039 int64_t get_ticks_per_sec(void)
1041 return timers_state
.ticks_per_sec
;
1044 static void init_timers(void)
1047 timers_state
.ticks_per_sec
= QEMU_TIMER_BASE
;
1048 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1049 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1053 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1055 uint64_t expire_time
;
1057 if (qemu_timer_pending(ts
)) {
1058 expire_time
= ts
->expire_time
;
1062 qemu_put_be64(f
, expire_time
);
1065 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1067 uint64_t expire_time
;
1069 expire_time
= qemu_get_be64(f
);
1070 if (expire_time
!= -1) {
1071 qemu_mod_timer(ts
, expire_time
);
1077 static const VMStateDescription vmstate_timers
= {
1080 .minimum_version_id
= 1,
1081 .minimum_version_id_old
= 1,
1082 .fields
= (VMStateField
[]) {
1083 VMSTATE_INT64(cpu_ticks_offset
, TimersState
),
1084 VMSTATE_INT64(ticks_per_sec
, TimersState
),
1085 VMSTATE_INT64_V(cpu_clock_offset
, TimersState
, 2),
1086 VMSTATE_END_OF_LIST()
1090 static void qemu_event_increment(void);
1093 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1094 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1097 static void host_alarm_handler(int host_signum
)
1101 #define DISP_FREQ 1000
1103 static int64_t delta_min
= INT64_MAX
;
1104 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1106 ti
= qemu_get_clock(vm_clock
);
1107 if (last_clock
!= 0) {
1108 delta
= ti
- last_clock
;
1109 if (delta
< delta_min
)
1111 if (delta
> delta_max
)
1114 if (++count
== DISP_FREQ
) {
1115 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1116 muldiv64(delta_min
, 1000000, get_ticks_per_sec()),
1117 muldiv64(delta_max
, 1000000, get_ticks_per_sec()),
1118 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, get_ticks_per_sec()),
1119 (double)get_ticks_per_sec() / ((double)delta_cum
/ DISP_FREQ
));
1121 delta_min
= INT64_MAX
;
1129 if (alarm_has_dynticks(alarm_timer
) ||
1131 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1132 qemu_get_clock(vm_clock
))) ||
1133 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1134 qemu_get_clock(rt_clock
))) {
1135 qemu_event_increment();
1136 if (alarm_timer
) alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1138 #ifndef CONFIG_IOTHREAD
1140 /* stop the currently executing cpu because a timer occured */
1144 timer_alarm_pending
= 1;
1145 qemu_notify_event();
1149 static int64_t qemu_next_deadline(void)
1153 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1154 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1155 qemu_get_clock(vm_clock
);
1157 /* To avoid problems with overflow limit this to 2^32. */
1167 #if defined(__linux__) || defined(_WIN32)
1168 static uint64_t qemu_next_deadline_dyntick(void)
1176 delta
= (qemu_next_deadline() + 999) / 1000;
1178 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1179 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1180 qemu_get_clock(rt_clock
))*1000;
1181 if (rtdelta
< delta
)
1185 if (delta
< MIN_TIMER_REARM_US
)
1186 delta
= MIN_TIMER_REARM_US
;
1194 /* Sets a specific flag */
1195 static int fcntl_setfl(int fd
, int flag
)
1199 flags
= fcntl(fd
, F_GETFL
);
1203 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1209 #if defined(__linux__)
1211 #define RTC_FREQ 1024
1213 static void enable_sigio_timer(int fd
)
1215 struct sigaction act
;
1218 sigfillset(&act
.sa_mask
);
1220 act
.sa_handler
= host_alarm_handler
;
1222 sigaction(SIGIO
, &act
, NULL
);
1223 fcntl_setfl(fd
, O_ASYNC
);
1224 fcntl(fd
, F_SETOWN
, getpid());
1227 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1229 struct hpet_info info
;
1232 fd
= open("/dev/hpet", O_RDONLY
);
1237 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1239 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1240 "error, but for better emulation accuracy type:\n"
1241 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1245 /* Check capabilities */
1246 r
= ioctl(fd
, HPET_INFO
, &info
);
1250 /* Enable periodic mode */
1251 r
= ioctl(fd
, HPET_EPI
, 0);
1252 if (info
.hi_flags
&& (r
< 0))
1255 /* Enable interrupt */
1256 r
= ioctl(fd
, HPET_IE_ON
, 0);
1260 enable_sigio_timer(fd
);
1261 t
->priv
= (void *)(long)fd
;
1269 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1271 int fd
= (long)t
->priv
;
1276 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1279 unsigned long current_rtc_freq
= 0;
1281 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1284 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1285 if (current_rtc_freq
!= RTC_FREQ
&&
1286 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1287 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1288 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1289 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1292 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1298 enable_sigio_timer(rtc_fd
);
1300 t
->priv
= (void *)(long)rtc_fd
;
1305 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1307 int rtc_fd
= (long)t
->priv
;
1312 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1316 struct sigaction act
;
1318 sigfillset(&act
.sa_mask
);
1320 act
.sa_handler
= host_alarm_handler
;
1322 sigaction(SIGALRM
, &act
, NULL
);
1325 * Initialize ev struct to 0 to avoid valgrind complaining
1326 * about uninitialized data in timer_create call
1328 memset(&ev
, 0, sizeof(ev
));
1329 ev
.sigev_value
.sival_int
= 0;
1330 ev
.sigev_notify
= SIGEV_SIGNAL
;
1331 ev
.sigev_signo
= SIGALRM
;
1333 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1334 perror("timer_create");
1336 /* disable dynticks */
1337 fprintf(stderr
, "Dynamic Ticks disabled\n");
1342 t
->priv
= (void *)(long)host_timer
;
1347 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1349 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1351 timer_delete(host_timer
);
1354 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1356 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1357 struct itimerspec timeout
;
1358 int64_t nearest_delta_us
= INT64_MAX
;
1361 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1362 !active_timers
[QEMU_TIMER_VIRTUAL
])
1365 nearest_delta_us
= qemu_next_deadline_dyntick();
1367 /* check whether a timer is already running */
1368 if (timer_gettime(host_timer
, &timeout
)) {
1370 fprintf(stderr
, "Internal timer error: aborting\n");
1373 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1374 if (current_us
&& current_us
<= nearest_delta_us
)
1377 timeout
.it_interval
.tv_sec
= 0;
1378 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1379 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1380 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1381 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1383 fprintf(stderr
, "Internal timer error: aborting\n");
1388 #endif /* defined(__linux__) */
1390 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1392 struct sigaction act
;
1393 struct itimerval itv
;
1397 sigfillset(&act
.sa_mask
);
1399 act
.sa_handler
= host_alarm_handler
;
1401 sigaction(SIGALRM
, &act
, NULL
);
1403 itv
.it_interval
.tv_sec
= 0;
1404 /* for i386 kernel 2.6 to get 1 ms */
1405 itv
.it_interval
.tv_usec
= 999;
1406 itv
.it_value
.tv_sec
= 0;
1407 itv
.it_value
.tv_usec
= 10 * 1000;
1409 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1416 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1418 struct itimerval itv
;
1420 memset(&itv
, 0, sizeof(itv
));
1421 setitimer(ITIMER_REAL
, &itv
, NULL
);
1424 #endif /* !defined(_WIN32) */
1429 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1432 struct qemu_alarm_win32
*data
= t
->priv
;
1435 memset(&tc
, 0, sizeof(tc
));
1436 timeGetDevCaps(&tc
, sizeof(tc
));
1438 if (data
->period
< tc
.wPeriodMin
)
1439 data
->period
= tc
.wPeriodMin
;
1441 timeBeginPeriod(data
->period
);
1443 flags
= TIME_CALLBACK_FUNCTION
;
1444 if (alarm_has_dynticks(t
))
1445 flags
|= TIME_ONESHOT
;
1447 flags
|= TIME_PERIODIC
;
1449 data
->timerId
= timeSetEvent(1, // interval (ms)
1450 data
->period
, // resolution
1451 host_alarm_handler
, // function
1452 (DWORD
)t
, // parameter
1455 if (!data
->timerId
) {
1456 perror("Failed to initialize win32 alarm timer");
1457 timeEndPeriod(data
->period
);
1464 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1466 struct qemu_alarm_win32
*data
= t
->priv
;
1468 timeKillEvent(data
->timerId
);
1469 timeEndPeriod(data
->period
);
1472 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1474 struct qemu_alarm_win32
*data
= t
->priv
;
1475 uint64_t nearest_delta_us
;
1477 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1478 !active_timers
[QEMU_TIMER_VIRTUAL
])
1481 nearest_delta_us
= qemu_next_deadline_dyntick();
1482 nearest_delta_us
/= 1000;
1484 timeKillEvent(data
->timerId
);
1486 data
->timerId
= timeSetEvent(1,
1490 TIME_ONESHOT
| TIME_PERIODIC
);
1492 if (!data
->timerId
) {
1493 perror("Failed to re-arm win32 alarm timer");
1495 timeEndPeriod(data
->period
);
1502 static int init_timer_alarm(void)
1504 struct qemu_alarm_timer
*t
= NULL
;
1507 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1508 t
= &alarm_timers
[i
];
1528 static void quit_timers(void)
1530 alarm_timer
->stop(alarm_timer
);
1534 /***********************************************************/
1535 /* host time/date access */
1536 void qemu_get_timedate(struct tm
*tm
, int offset
)
1543 if (rtc_date_offset
== -1) {
1547 ret
= localtime(&ti
);
1549 ti
-= rtc_date_offset
;
1553 memcpy(tm
, ret
, sizeof(struct tm
));
1556 int qemu_timedate_diff(struct tm
*tm
)
1560 if (rtc_date_offset
== -1)
1562 seconds
= mktimegm(tm
);
1564 seconds
= mktime(tm
);
1566 seconds
= mktimegm(tm
) + rtc_date_offset
;
1568 return seconds
- time(NULL
);
1572 static void socket_cleanup(void)
1577 static int socket_init(void)
1582 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1584 err
= WSAGetLastError();
1585 fprintf(stderr
, "WSAStartup: %d\n", err
);
1588 atexit(socket_cleanup
);
1593 /***********************************************************/
1594 /* Bluetooth support */
1597 static struct HCIInfo
*hci_table
[MAX_NICS
];
1599 static struct bt_vlan_s
{
1600 struct bt_scatternet_s net
;
1602 struct bt_vlan_s
*next
;
1605 /* find or alloc a new bluetooth "VLAN" */
1606 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1608 struct bt_vlan_s
**pvlan
, *vlan
;
1609 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1613 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1615 pvlan
= &first_bt_vlan
;
1616 while (*pvlan
!= NULL
)
1617 pvlan
= &(*pvlan
)->next
;
1622 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1626 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1631 static struct HCIInfo null_hci
= {
1632 .cmd_send
= null_hci_send
,
1633 .sco_send
= null_hci_send
,
1634 .acl_send
= null_hci_send
,
1635 .bdaddr_set
= null_hci_addr_set
,
1638 struct HCIInfo
*qemu_next_hci(void)
1640 if (cur_hci
== nb_hcis
)
1643 return hci_table
[cur_hci
++];
1646 static struct HCIInfo
*hci_init(const char *str
)
1649 struct bt_scatternet_s
*vlan
= 0;
1651 if (!strcmp(str
, "null"))
1654 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
1656 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
1657 else if (!strncmp(str
, "hci", 3)) {
1660 if (!strncmp(str
+ 3, ",vlan=", 6)) {
1661 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
1666 vlan
= qemu_find_bt_vlan(0);
1668 return bt_new_hci(vlan
);
1671 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
1676 static int bt_hci_parse(const char *str
)
1678 struct HCIInfo
*hci
;
1681 if (nb_hcis
>= MAX_NICS
) {
1682 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
1686 hci
= hci_init(str
);
1695 bdaddr
.b
[5] = 0x56 + nb_hcis
;
1696 hci
->bdaddr_set(hci
, bdaddr
.b
);
1698 hci_table
[nb_hcis
++] = hci
;
1703 static void bt_vhci_add(int vlan_id
)
1705 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
1708 fprintf(stderr
, "qemu: warning: adding a VHCI to "
1709 "an empty scatternet %i\n", vlan_id
);
1711 bt_vhci_init(bt_new_hci(vlan
));
1714 static struct bt_device_s
*bt_device_add(const char *opt
)
1716 struct bt_scatternet_s
*vlan
;
1718 char *endp
= strstr(opt
, ",vlan=");
1719 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
1722 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
1725 vlan_id
= strtol(endp
+ 6, &endp
, 0);
1727 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
1732 vlan
= qemu_find_bt_vlan(vlan_id
);
1735 fprintf(stderr
, "qemu: warning: adding a slave device to "
1736 "an empty scatternet %i\n", vlan_id
);
1738 if (!strcmp(devname
, "keyboard"))
1739 return bt_keyboard_init(vlan
);
1741 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
1745 static int bt_parse(const char *opt
)
1747 const char *endp
, *p
;
1750 if (strstart(opt
, "hci", &endp
)) {
1751 if (!*endp
|| *endp
== ',') {
1753 if (!strstart(endp
, ",vlan=", 0))
1756 return bt_hci_parse(opt
);
1758 } else if (strstart(opt
, "vhci", &endp
)) {
1759 if (!*endp
|| *endp
== ',') {
1761 if (strstart(endp
, ",vlan=", &p
)) {
1762 vlan
= strtol(p
, (char **) &endp
, 0);
1764 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
1768 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
1777 } else if (strstart(opt
, "device:", &endp
))
1778 return !bt_device_add(endp
);
1780 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
1784 /***********************************************************/
1785 /* QEMU Block devices */
1787 #define HD_ALIAS "index=%d,media=disk"
1788 #define CDROM_ALIAS "index=2,media=cdrom"
1789 #define FD_ALIAS "index=%d,if=floppy"
1790 #define PFLASH_ALIAS "if=pflash"
1791 #define MTD_ALIAS "if=mtd"
1792 #define SD_ALIAS "index=0,if=sd"
1794 QemuOpts
*drive_add(const char *file
, const char *fmt
, ...)
1801 vsnprintf(optstr
, sizeof(optstr
), fmt
, ap
);
1804 opts
= qemu_opts_parse(&qemu_drive_opts
, optstr
, NULL
);
1806 fprintf(stderr
, "%s: huh? duplicate? (%s)\n",
1807 __FUNCTION__
, optstr
);
1811 qemu_opt_set(opts
, "file", file
);
1815 DriveInfo
*drive_get(BlockInterfaceType type
, int bus
, int unit
)
1819 /* seek interface, bus and unit */
1821 TAILQ_FOREACH(dinfo
, &drives
, next
) {
1822 if (dinfo
->type
== type
&&
1823 dinfo
->bus
== bus
&&
1824 dinfo
->unit
== unit
)
1831 DriveInfo
*drive_get_by_id(const char *id
)
1835 TAILQ_FOREACH(dinfo
, &drives
, next
) {
1836 if (strcmp(id
, dinfo
->id
))
1843 int drive_get_max_bus(BlockInterfaceType type
)
1849 TAILQ_FOREACH(dinfo
, &drives
, next
) {
1850 if(dinfo
->type
== type
&&
1851 dinfo
->bus
> max_bus
)
1852 max_bus
= dinfo
->bus
;
1857 const char *drive_get_serial(BlockDriverState
*bdrv
)
1861 TAILQ_FOREACH(dinfo
, &drives
, next
) {
1862 if (dinfo
->bdrv
== bdrv
)
1863 return dinfo
->serial
;
1869 BlockInterfaceErrorAction
drive_get_onerror(BlockDriverState
*bdrv
)
1873 TAILQ_FOREACH(dinfo
, &drives
, next
) {
1874 if (dinfo
->bdrv
== bdrv
)
1875 return dinfo
->onerror
;
1878 return BLOCK_ERR_STOP_ENOSPC
;
1881 static void bdrv_format_print(void *opaque
, const char *name
)
1883 fprintf(stderr
, " %s", name
);
1886 void drive_uninit(BlockDriverState
*bdrv
)
1890 TAILQ_FOREACH(dinfo
, &drives
, next
) {
1891 if (dinfo
->bdrv
!= bdrv
)
1893 qemu_opts_del(dinfo
->opts
);
1894 TAILQ_REMOVE(&drives
, dinfo
, next
);
1900 DriveInfo
*drive_init(QemuOpts
*opts
, void *opaque
,
1904 const char *file
= NULL
;
1907 const char *mediastr
= "";
1908 BlockInterfaceType type
;
1909 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
1910 int bus_id
, unit_id
;
1911 int cyls
, heads
, secs
, translation
;
1912 BlockDriver
*drv
= NULL
;
1913 QEMUMachine
*machine
= opaque
;
1918 int bdrv_flags
, onerror
;
1919 const char *devaddr
;
1925 translation
= BIOS_ATA_TRANSLATION_AUTO
;
1928 if (machine
&& machine
->use_scsi
) {
1930 max_devs
= MAX_SCSI_DEVS
;
1931 pstrcpy(devname
, sizeof(devname
), "scsi");
1934 max_devs
= MAX_IDE_DEVS
;
1935 pstrcpy(devname
, sizeof(devname
), "ide");
1939 /* extract parameters */
1940 bus_id
= qemu_opt_get_number(opts
, "bus", 0);
1941 unit_id
= qemu_opt_get_number(opts
, "unit", -1);
1942 index
= qemu_opt_get_number(opts
, "index", -1);
1944 cyls
= qemu_opt_get_number(opts
, "cyls", 0);
1945 heads
= qemu_opt_get_number(opts
, "heads", 0);
1946 secs
= qemu_opt_get_number(opts
, "secs", 0);
1948 snapshot
= qemu_opt_get_bool(opts
, "snapshot", 0);
1950 file
= qemu_opt_get(opts
, "file");
1951 serial
= qemu_opt_get(opts
, "serial");
1953 if ((buf
= qemu_opt_get(opts
, "if")) != NULL
) {
1954 pstrcpy(devname
, sizeof(devname
), buf
);
1955 if (!strcmp(buf
, "ide")) {
1957 max_devs
= MAX_IDE_DEVS
;
1958 } else if (!strcmp(buf
, "scsi")) {
1960 max_devs
= MAX_SCSI_DEVS
;
1961 } else if (!strcmp(buf
, "floppy")) {
1964 } else if (!strcmp(buf
, "pflash")) {
1967 } else if (!strcmp(buf
, "mtd")) {
1970 } else if (!strcmp(buf
, "sd")) {
1973 } else if (!strcmp(buf
, "virtio")) {
1976 } else if (!strcmp(buf
, "xen")) {
1979 } else if (!strcmp(buf
, "none")) {
1983 fprintf(stderr
, "qemu: unsupported bus type '%s'\n", buf
);
1988 if (cyls
|| heads
|| secs
) {
1989 if (cyls
< 1 || cyls
> 16383) {
1990 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", buf
);
1993 if (heads
< 1 || heads
> 16) {
1994 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", buf
);
1997 if (secs
< 1 || secs
> 63) {
1998 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", buf
);
2003 if ((buf
= qemu_opt_get(opts
, "trans")) != NULL
) {
2006 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2010 if (!strcmp(buf
, "none"))
2011 translation
= BIOS_ATA_TRANSLATION_NONE
;
2012 else if (!strcmp(buf
, "lba"))
2013 translation
= BIOS_ATA_TRANSLATION_LBA
;
2014 else if (!strcmp(buf
, "auto"))
2015 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2017 fprintf(stderr
, "qemu: '%s' invalid translation type\n", buf
);
2022 if ((buf
= qemu_opt_get(opts
, "media")) != NULL
) {
2023 if (!strcmp(buf
, "disk")) {
2025 } else if (!strcmp(buf
, "cdrom")) {
2026 if (cyls
|| secs
|| heads
) {
2028 "qemu: '%s' invalid physical CHS format\n", buf
);
2031 media
= MEDIA_CDROM
;
2033 fprintf(stderr
, "qemu: '%s' invalid media\n", buf
);
2038 if ((buf
= qemu_opt_get(opts
, "cache")) != NULL
) {
2039 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2041 else if (!strcmp(buf
, "writethrough"))
2043 else if (!strcmp(buf
, "writeback"))
2046 fprintf(stderr
, "qemu: invalid cache option\n");
2051 #ifdef CONFIG_LINUX_AIO
2052 if ((buf
= qemu_opt_get(opts
, "aio")) != NULL
) {
2053 if (!strcmp(buf
, "threads"))
2055 else if (!strcmp(buf
, "native"))
2058 fprintf(stderr
, "qemu: invalid aio option\n");
2064 if ((buf
= qemu_opt_get(opts
, "format")) != NULL
) {
2065 if (strcmp(buf
, "?") == 0) {
2066 fprintf(stderr
, "qemu: Supported formats:");
2067 bdrv_iterate_format(bdrv_format_print
, NULL
);
2068 fprintf(stderr
, "\n");
2071 drv
= bdrv_find_format(buf
);
2073 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2078 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2079 if ((buf
= qemu_opt_get(opts
, "werror")) != NULL
) {
2080 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2081 fprintf(stderr
, "werror is no supported by this format\n");
2084 if (!strcmp(buf
, "ignore"))
2085 onerror
= BLOCK_ERR_IGNORE
;
2086 else if (!strcmp(buf
, "enospc"))
2087 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2088 else if (!strcmp(buf
, "stop"))
2089 onerror
= BLOCK_ERR_STOP_ANY
;
2090 else if (!strcmp(buf
, "report"))
2091 onerror
= BLOCK_ERR_REPORT
;
2093 fprintf(stderr
, "qemu: '%s' invalid write error action\n", buf
);
2098 if ((devaddr
= qemu_opt_get(opts
, "addr")) != NULL
) {
2099 if (type
!= IF_VIRTIO
) {
2100 fprintf(stderr
, "addr is not supported\n");
2105 /* compute bus and unit according index */
2108 if (bus_id
!= 0 || unit_id
!= -1) {
2110 "qemu: index cannot be used with bus and unit\n");
2118 unit_id
= index
% max_devs
;
2119 bus_id
= index
/ max_devs
;
2123 /* if user doesn't specify a unit_id,
2124 * try to find the first free
2127 if (unit_id
== -1) {
2129 while (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2131 if (max_devs
&& unit_id
>= max_devs
) {
2132 unit_id
-= max_devs
;
2140 if (max_devs
&& unit_id
>= max_devs
) {
2141 fprintf(stderr
, "qemu: unit %d too big (max is %d)\n",
2142 unit_id
, max_devs
- 1);
2147 * ignore multiple definitions
2150 if (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2157 dinfo
= qemu_mallocz(sizeof(*dinfo
));
2158 if ((buf
= qemu_opts_id(opts
)) != NULL
) {
2159 dinfo
->id
= qemu_strdup(buf
);
2161 /* no id supplied -> create one */
2162 dinfo
->id
= qemu_mallocz(32);
2163 if (type
== IF_IDE
|| type
== IF_SCSI
)
2164 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2166 snprintf(dinfo
->id
, 32, "%s%i%s%i",
2167 devname
, bus_id
, mediastr
, unit_id
);
2169 snprintf(dinfo
->id
, 32, "%s%s%i",
2170 devname
, mediastr
, unit_id
);
2172 dinfo
->bdrv
= bdrv_new(dinfo
->id
);
2173 dinfo
->devaddr
= devaddr
;
2175 dinfo
->bus
= bus_id
;
2176 dinfo
->unit
= unit_id
;
2177 dinfo
->onerror
= onerror
;
2180 strncpy(dinfo
->serial
, serial
, sizeof(serial
));
2181 TAILQ_INSERT_TAIL(&drives
, dinfo
, next
);
2190 bdrv_set_geometry_hint(dinfo
->bdrv
, cyls
, heads
, secs
);
2191 bdrv_set_translation_hint(dinfo
->bdrv
, translation
);
2195 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_CDROM
);
2200 /* FIXME: This isn't really a floppy, but it's a reasonable
2203 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_FLOPPY
);
2210 /* add virtio block device */
2211 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
2212 qemu_opt_set(opts
, "driver", "virtio-blk-pci");
2213 qemu_opt_set(opts
, "drive", dinfo
->id
);
2215 qemu_opt_set(opts
, "addr", devaddr
);
2226 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2227 cache
= 2; /* always use write-back with snapshot */
2229 if (cache
== 0) /* no caching */
2230 bdrv_flags
|= BDRV_O_NOCACHE
;
2231 else if (cache
== 2) /* write-back */
2232 bdrv_flags
|= BDRV_O_CACHE_WB
;
2235 bdrv_flags
|= BDRV_O_NATIVE_AIO
;
2237 bdrv_flags
&= ~BDRV_O_NATIVE_AIO
;
2240 if (bdrv_open2(dinfo
->bdrv
, file
, bdrv_flags
, drv
) < 0) {
2241 fprintf(stderr
, "qemu: could not open disk image %s\n",
2246 if (bdrv_key_required(dinfo
->bdrv
))
2252 static int drive_init_func(QemuOpts
*opts
, void *opaque
)
2254 QEMUMachine
*machine
= opaque
;
2255 int fatal_error
= 0;
2257 if (drive_init(opts
, machine
, &fatal_error
) == NULL
) {
2264 static int drive_enable_snapshot(QemuOpts
*opts
, void *opaque
)
2266 if (NULL
== qemu_opt_get(opts
, "snapshot")) {
2267 qemu_opt_set(opts
, "snapshot", "on");
2272 void qemu_register_boot_set(QEMUBootSetHandler
*func
, void *opaque
)
2274 boot_set_handler
= func
;
2275 boot_set_opaque
= opaque
;
2278 int qemu_boot_set(const char *boot_devices
)
2280 if (!boot_set_handler
) {
2283 return boot_set_handler(boot_set_opaque
, boot_devices
);
2286 static int parse_bootdevices(char *devices
)
2288 /* We just do some generic consistency checks */
2292 for (p
= devices
; *p
!= '\0'; p
++) {
2293 /* Allowed boot devices are:
2294 * a-b: floppy disk drives
2295 * c-f: IDE disk drives
2296 * g-m: machine implementation dependant drives
2297 * n-p: network devices
2298 * It's up to each machine implementation to check if the given boot
2299 * devices match the actual hardware implementation and firmware
2302 if (*p
< 'a' || *p
> 'p') {
2303 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
2306 if (bitmap
& (1 << (*p
- 'a'))) {
2307 fprintf(stderr
, "Boot device '%c' was given twice\n", *p
);
2310 bitmap
|= 1 << (*p
- 'a');
2315 static void restore_boot_devices(void *opaque
)
2317 char *standard_boot_devices
= opaque
;
2319 qemu_boot_set(standard_boot_devices
);
2321 qemu_unregister_reset(restore_boot_devices
, standard_boot_devices
);
2322 qemu_free(standard_boot_devices
);
2325 static void numa_add(const char *optarg
)
2329 unsigned long long value
, endvalue
;
2332 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2333 if (!strcmp(option
, "node")) {
2334 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2335 nodenr
= nb_numa_nodes
;
2337 nodenr
= strtoull(option
, NULL
, 10);
2340 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2341 node_mem
[nodenr
] = 0;
2343 value
= strtoull(option
, &endptr
, 0);
2345 case 0: case 'M': case 'm':
2352 node_mem
[nodenr
] = value
;
2354 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2355 node_cpumask
[nodenr
] = 0;
2357 value
= strtoull(option
, &endptr
, 10);
2360 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2362 if (*endptr
== '-') {
2363 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2364 if (endvalue
>= 63) {
2367 "only 63 CPUs in NUMA mode supported.\n");
2369 value
= (1 << (endvalue
+ 1)) - (1 << value
);
2374 node_cpumask
[nodenr
] = value
;
2381 static void smp_parse(const char *optarg
)
2383 int smp
, sockets
= 0, threads
= 0, cores
= 0;
2387 smp
= strtoul(optarg
, &endptr
, 10);
2388 if (endptr
!= optarg
) {
2389 if (*endptr
== ',') {
2393 if (get_param_value(option
, 128, "sockets", endptr
) != 0)
2394 sockets
= strtoull(option
, NULL
, 10);
2395 if (get_param_value(option
, 128, "cores", endptr
) != 0)
2396 cores
= strtoull(option
, NULL
, 10);
2397 if (get_param_value(option
, 128, "threads", endptr
) != 0)
2398 threads
= strtoull(option
, NULL
, 10);
2399 if (get_param_value(option
, 128, "maxcpus", endptr
) != 0)
2400 max_cpus
= strtoull(option
, NULL
, 10);
2402 /* compute missing values, prefer sockets over cores over threads */
2403 if (smp
== 0 || sockets
== 0) {
2404 sockets
= sockets
> 0 ? sockets
: 1;
2405 cores
= cores
> 0 ? cores
: 1;
2406 threads
= threads
> 0 ? threads
: 1;
2408 smp
= cores
* threads
* sockets
;
2410 sockets
= smp
/ (cores
* threads
);
2414 threads
= threads
> 0 ? threads
: 1;
2415 cores
= smp
/ (sockets
* threads
);
2418 sockets
= smp
/ (cores
* threads
);
2420 threads
= smp
/ (cores
* sockets
);
2425 smp_cores
= cores
> 0 ? cores
: 1;
2426 smp_threads
= threads
> 0 ? threads
: 1;
2428 max_cpus
= smp_cpus
;
2431 /***********************************************************/
2434 static void usb_msd_password_cb(void *opaque
, int err
)
2436 USBDevice
*dev
= opaque
;
2439 usb_device_attach(dev
);
2441 dev
->info
->handle_destroy(dev
);
2450 .qdev
= "QEMU USB Mouse",
2453 .qdev
= "QEMU USB Tablet",
2456 .qdev
= "QEMU USB Keyboard",
2458 .name
= "wacom-tablet",
2459 .qdev
= "QEMU PenPartner Tablet",
2463 static int usb_device_add(const char *devname
, int is_hotplug
)
2466 USBBus
*bus
= usb_bus_find(-1 /* any */);
2467 USBDevice
*dev
= NULL
;
2473 /* simple devices which don't need extra care */
2474 for (i
= 0; i
< ARRAY_SIZE(usbdevs
); i
++) {
2475 if (strcmp(devname
, usbdevs
[i
].name
) != 0)
2477 dev
= usb_create_simple(bus
, usbdevs
[i
].qdev
);
2481 /* the other ones */
2482 if (strstart(devname
, "host:", &p
)) {
2483 dev
= usb_host_device_open(p
);
2484 } else if (strstart(devname
, "disk:", &p
)) {
2485 BlockDriverState
*bs
;
2487 dev
= usb_msd_init(p
);
2490 bs
= usb_msd_get_bdrv(dev
);
2491 if (bdrv_key_required(bs
)) {
2494 monitor_read_bdrv_key_start(cur_mon
, bs
, usb_msd_password_cb
,
2499 } else if (strstart(devname
, "serial:", &p
)) {
2500 dev
= usb_serial_init(p
);
2501 #ifdef CONFIG_BRLAPI
2502 } else if (!strcmp(devname
, "braille")) {
2503 dev
= usb_baum_init();
2505 } else if (strstart(devname
, "net:", &p
)) {
2508 if (net_client_init(NULL
, "nic", p
) < 0)
2510 nd_table
[nic
].model
= "usb";
2511 dev
= usb_net_init(&nd_table
[nic
]);
2512 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2513 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2514 bt_new_hci(qemu_find_bt_vlan(0)));
2525 static int usb_device_del(const char *devname
)
2530 if (strstart(devname
, "host:", &p
))
2531 return usb_host_device_close(p
);
2536 p
= strchr(devname
, '.');
2539 bus_num
= strtoul(devname
, NULL
, 0);
2540 addr
= strtoul(p
+ 1, NULL
, 0);
2542 return usb_device_delete_addr(bus_num
, addr
);
2545 static int usb_parse(const char *cmdline
)
2547 return usb_device_add(cmdline
, 0);
2550 void do_usb_add(Monitor
*mon
, const QDict
*qdict
)
2552 usb_device_add(qdict_get_str(qdict
, "devname"), 1);
2555 void do_usb_del(Monitor
*mon
, const QDict
*qdict
)
2557 usb_device_del(qdict_get_str(qdict
, "devname"));
2560 /***********************************************************/
2561 /* PCMCIA/Cardbus */
2563 static struct pcmcia_socket_entry_s
{
2564 PCMCIASocket
*socket
;
2565 struct pcmcia_socket_entry_s
*next
;
2566 } *pcmcia_sockets
= 0;
2568 void pcmcia_socket_register(PCMCIASocket
*socket
)
2570 struct pcmcia_socket_entry_s
*entry
;
2572 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2573 entry
->socket
= socket
;
2574 entry
->next
= pcmcia_sockets
;
2575 pcmcia_sockets
= entry
;
2578 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2580 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2582 ptr
= &pcmcia_sockets
;
2583 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2584 if (entry
->socket
== socket
) {
2590 void pcmcia_info(Monitor
*mon
)
2592 struct pcmcia_socket_entry_s
*iter
;
2594 if (!pcmcia_sockets
)
2595 monitor_printf(mon
, "No PCMCIA sockets\n");
2597 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2598 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2599 iter
->socket
->attached
? iter
->socket
->card_string
:
2603 /***********************************************************/
2604 /* register display */
2606 struct DisplayAllocator default_allocator
= {
2607 defaultallocator_create_displaysurface
,
2608 defaultallocator_resize_displaysurface
,
2609 defaultallocator_free_displaysurface
2612 void register_displaystate(DisplayState
*ds
)
2622 DisplayState
*get_displaystate(void)
2624 return display_state
;
2627 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
2629 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
2630 return ds
->allocator
;
2635 static void dumb_display_init(void)
2637 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
2638 ds
->allocator
= &default_allocator
;
2639 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
2640 register_displaystate(ds
);
2643 /***********************************************************/
2646 typedef struct IOHandlerRecord
{
2648 IOCanRWHandler
*fd_read_poll
;
2650 IOHandler
*fd_write
;
2653 /* temporary data */
2655 struct IOHandlerRecord
*next
;
2658 static IOHandlerRecord
*first_io_handler
;
2660 /* XXX: fd_read_poll should be suppressed, but an API change is
2661 necessary in the character devices to suppress fd_can_read(). */
2662 int qemu_set_fd_handler2(int fd
,
2663 IOCanRWHandler
*fd_read_poll
,
2665 IOHandler
*fd_write
,
2668 IOHandlerRecord
**pioh
, *ioh
;
2670 if (!fd_read
&& !fd_write
) {
2671 pioh
= &first_io_handler
;
2676 if (ioh
->fd
== fd
) {
2683 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
2687 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
2688 ioh
->next
= first_io_handler
;
2689 first_io_handler
= ioh
;
2692 ioh
->fd_read_poll
= fd_read_poll
;
2693 ioh
->fd_read
= fd_read
;
2694 ioh
->fd_write
= fd_write
;
2695 ioh
->opaque
= opaque
;
2701 int qemu_set_fd_handler(int fd
,
2703 IOHandler
*fd_write
,
2706 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
2710 /***********************************************************/
2711 /* Polling handling */
2713 typedef struct PollingEntry
{
2716 struct PollingEntry
*next
;
2719 static PollingEntry
*first_polling_entry
;
2721 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
2723 PollingEntry
**ppe
, *pe
;
2724 pe
= qemu_mallocz(sizeof(PollingEntry
));
2726 pe
->opaque
= opaque
;
2727 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
2732 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
2734 PollingEntry
**ppe
, *pe
;
2735 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
2737 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
2745 /***********************************************************/
2746 /* Wait objects support */
2747 typedef struct WaitObjects
{
2749 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
2750 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
2751 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
2754 static WaitObjects wait_objects
= {0};
2756 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2758 WaitObjects
*w
= &wait_objects
;
2760 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
2762 w
->events
[w
->num
] = handle
;
2763 w
->func
[w
->num
] = func
;
2764 w
->opaque
[w
->num
] = opaque
;
2769 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2772 WaitObjects
*w
= &wait_objects
;
2775 for (i
= 0; i
< w
->num
; i
++) {
2776 if (w
->events
[i
] == handle
)
2779 w
->events
[i
] = w
->events
[i
+ 1];
2780 w
->func
[i
] = w
->func
[i
+ 1];
2781 w
->opaque
[i
] = w
->opaque
[i
+ 1];
2789 /***********************************************************/
2790 /* ram save/restore */
2792 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2793 #define RAM_SAVE_FLAG_COMPRESS 0x02
2794 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2795 #define RAM_SAVE_FLAG_PAGE 0x08
2796 #define RAM_SAVE_FLAG_EOS 0x10
2798 static int is_dup_page(uint8_t *page
, uint8_t ch
)
2800 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
2801 uint32_t *array
= (uint32_t *)page
;
2804 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
2805 if (array
[i
] != val
)
2812 static int ram_save_block(QEMUFile
*f
)
2814 static ram_addr_t current_addr
= 0;
2815 ram_addr_t saved_addr
= current_addr
;
2816 ram_addr_t addr
= 0;
2819 while (addr
< last_ram_offset
) {
2820 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
2823 cpu_physical_memory_reset_dirty(current_addr
,
2824 current_addr
+ TARGET_PAGE_SIZE
,
2825 MIGRATION_DIRTY_FLAG
);
2827 p
= qemu_get_ram_ptr(current_addr
);
2829 if (is_dup_page(p
, *p
)) {
2830 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
2831 qemu_put_byte(f
, *p
);
2833 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
2834 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
2840 addr
+= TARGET_PAGE_SIZE
;
2841 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
2847 static uint64_t bytes_transferred
= 0;
2849 static ram_addr_t
ram_save_remaining(void)
2852 ram_addr_t count
= 0;
2854 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2855 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2862 uint64_t ram_bytes_remaining(void)
2864 return ram_save_remaining() * TARGET_PAGE_SIZE
;
2867 uint64_t ram_bytes_transferred(void)
2869 return bytes_transferred
;
2872 uint64_t ram_bytes_total(void)
2874 return last_ram_offset
;
2877 static int ram_save_live(QEMUFile
*f
, int stage
, void *opaque
)
2880 uint64_t bytes_transferred_last
;
2882 uint64_t expected_time
= 0;
2884 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX
) != 0) {
2885 qemu_file_set_error(f
);
2890 /* Make sure all dirty bits are set */
2891 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2892 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2893 cpu_physical_memory_set_dirty(addr
);
2896 /* Enable dirty memory tracking */
2897 cpu_physical_memory_set_dirty_tracking(1);
2899 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
2902 bytes_transferred_last
= bytes_transferred
;
2903 bwidth
= get_clock();
2905 while (!qemu_file_rate_limit(f
)) {
2908 ret
= ram_save_block(f
);
2909 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
2910 if (ret
== 0) /* no more blocks */
2914 bwidth
= get_clock() - bwidth
;
2915 bwidth
= (bytes_transferred
- bytes_transferred_last
) / bwidth
;
2917 /* if we haven't transferred anything this round, force expected_time to a
2918 * a very high value, but without crashing */
2922 /* try transferring iterative blocks of memory */
2926 /* flush all remaining blocks regardless of rate limiting */
2927 while (ram_save_block(f
) != 0) {
2928 bytes_transferred
+= TARGET_PAGE_SIZE
;
2930 cpu_physical_memory_set_dirty_tracking(0);
2933 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
2935 expected_time
= ram_save_remaining() * TARGET_PAGE_SIZE
/ bwidth
;
2937 return (stage
== 2) && (expected_time
<= migrate_max_downtime());
2940 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
2945 if (version_id
!= 3)
2949 addr
= qemu_get_be64(f
);
2951 flags
= addr
& ~TARGET_PAGE_MASK
;
2952 addr
&= TARGET_PAGE_MASK
;
2954 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
2955 if (addr
!= last_ram_offset
)
2959 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
2960 uint8_t ch
= qemu_get_byte(f
);
2961 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
2964 (!kvm_enabled() || kvm_has_sync_mmu())) {
2965 madvise(qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
, MADV_DONTNEED
);
2968 } else if (flags
& RAM_SAVE_FLAG_PAGE
)
2969 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
2970 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
2975 void qemu_service_io(void)
2977 qemu_notify_event();
2980 /***********************************************************/
2981 /* bottom halves (can be seen as timers which expire ASAP) */
2992 static QEMUBH
*first_bh
= NULL
;
2994 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
2997 bh
= qemu_mallocz(sizeof(QEMUBH
));
2999 bh
->opaque
= opaque
;
3000 bh
->next
= first_bh
;
3005 int qemu_bh_poll(void)
3011 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3012 if (!bh
->deleted
&& bh
->scheduled
) {
3021 /* remove deleted bhs */
3035 void qemu_bh_schedule_idle(QEMUBH
*bh
)
3043 void qemu_bh_schedule(QEMUBH
*bh
)
3049 /* stop the currently executing CPU to execute the BH ASAP */
3050 qemu_notify_event();
3053 void qemu_bh_cancel(QEMUBH
*bh
)
3058 void qemu_bh_delete(QEMUBH
*bh
)
3064 static void qemu_bh_update_timeout(int *timeout
)
3068 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3069 if (!bh
->deleted
&& bh
->scheduled
) {
3071 /* idle bottom halves will be polled at least
3073 *timeout
= MIN(10, *timeout
);
3075 /* non-idle bottom halves will be executed
3084 /***********************************************************/
3085 /* machine registration */
3087 static QEMUMachine
*first_machine
= NULL
;
3088 QEMUMachine
*current_machine
= NULL
;
3090 int qemu_register_machine(QEMUMachine
*m
)
3093 pm
= &first_machine
;
3101 static QEMUMachine
*find_machine(const char *name
)
3105 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3106 if (!strcmp(m
->name
, name
))
3108 if (m
->alias
&& !strcmp(m
->alias
, name
))
3114 static QEMUMachine
*find_default_machine(void)
3118 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3119 if (m
->is_default
) {
3126 /***********************************************************/
3127 /* main execution loop */
3129 static void gui_update(void *opaque
)
3131 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3132 DisplayState
*ds
= opaque
;
3133 DisplayChangeListener
*dcl
= ds
->listeners
;
3137 while (dcl
!= NULL
) {
3138 if (dcl
->gui_timer_interval
&&
3139 dcl
->gui_timer_interval
< interval
)
3140 interval
= dcl
->gui_timer_interval
;
3143 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3146 static void nographic_update(void *opaque
)
3148 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3150 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3153 struct vm_change_state_entry
{
3154 VMChangeStateHandler
*cb
;
3156 LIST_ENTRY (vm_change_state_entry
) entries
;
3159 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3161 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3164 VMChangeStateEntry
*e
;
3166 e
= qemu_mallocz(sizeof (*e
));
3170 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3174 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3176 LIST_REMOVE (e
, entries
);
3180 static void vm_state_notify(int running
, int reason
)
3182 VMChangeStateEntry
*e
;
3184 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3185 e
->cb(e
->opaque
, running
, reason
);
3189 static void resume_all_vcpus(void);
3190 static void pause_all_vcpus(void);
3197 vm_state_notify(1, 0);
3198 qemu_rearm_alarm_timer(alarm_timer
);
3203 /* reset/shutdown handler */
3205 typedef struct QEMUResetEntry
{
3206 TAILQ_ENTRY(QEMUResetEntry
) entry
;
3207 QEMUResetHandler
*func
;
3211 static TAILQ_HEAD(reset_handlers
, QEMUResetEntry
) reset_handlers
=
3212 TAILQ_HEAD_INITIALIZER(reset_handlers
);
3213 static int reset_requested
;
3214 static int shutdown_requested
;
3215 static int powerdown_requested
;
3216 static int debug_requested
;
3217 static int vmstop_requested
;
3219 int qemu_shutdown_requested(void)
3221 int r
= shutdown_requested
;
3222 shutdown_requested
= 0;
3226 int qemu_reset_requested(void)
3228 int r
= reset_requested
;
3229 reset_requested
= 0;
3233 int qemu_powerdown_requested(void)
3235 int r
= powerdown_requested
;
3236 powerdown_requested
= 0;
3240 static int qemu_debug_requested(void)
3242 int r
= debug_requested
;
3243 debug_requested
= 0;
3247 static int qemu_vmstop_requested(void)
3249 int r
= vmstop_requested
;
3250 vmstop_requested
= 0;
3254 static void do_vm_stop(int reason
)
3257 cpu_disable_ticks();
3260 vm_state_notify(0, reason
);
3264 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3266 QEMUResetEntry
*re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3269 re
->opaque
= opaque
;
3270 TAILQ_INSERT_TAIL(&reset_handlers
, re
, entry
);
3273 void qemu_unregister_reset(QEMUResetHandler
*func
, void *opaque
)
3277 TAILQ_FOREACH(re
, &reset_handlers
, entry
) {
3278 if (re
->func
== func
&& re
->opaque
== opaque
) {
3279 TAILQ_REMOVE(&reset_handlers
, re
, entry
);
3286 void qemu_system_reset(void)
3288 QEMUResetEntry
*re
, *nre
;
3290 /* reset all devices */
3291 TAILQ_FOREACH_SAFE(re
, &reset_handlers
, entry
, nre
) {
3292 re
->func(re
->opaque
);
3296 void qemu_system_reset_request(void)
3299 shutdown_requested
= 1;
3301 reset_requested
= 1;
3303 qemu_notify_event();
3306 void qemu_system_shutdown_request(void)
3308 shutdown_requested
= 1;
3309 qemu_notify_event();
3312 void qemu_system_powerdown_request(void)
3314 powerdown_requested
= 1;
3315 qemu_notify_event();
3318 #ifdef CONFIG_IOTHREAD
3319 static void qemu_system_vmstop_request(int reason
)
3321 vmstop_requested
= reason
;
3322 qemu_notify_event();
3327 static int io_thread_fd
= -1;
3329 static void qemu_event_increment(void)
3331 static const char byte
= 0;
3333 if (io_thread_fd
== -1)
3336 write(io_thread_fd
, &byte
, sizeof(byte
));
3339 static void qemu_event_read(void *opaque
)
3341 int fd
= (unsigned long)opaque
;
3344 /* Drain the notify pipe */
3347 len
= read(fd
, buffer
, sizeof(buffer
));
3348 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
3351 static int qemu_event_init(void)
3360 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3364 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3368 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3369 (void *)(unsigned long)fds
[0]);
3371 io_thread_fd
= fds
[1];
3380 HANDLE qemu_event_handle
;
3382 static void dummy_event_handler(void *opaque
)
3386 static int qemu_event_init(void)
3388 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3389 if (!qemu_event_handle
) {
3390 perror("Failed CreateEvent");
3393 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3397 static void qemu_event_increment(void)
3399 SetEvent(qemu_event_handle
);
3403 static int cpu_can_run(CPUState
*env
)
3412 #ifndef CONFIG_IOTHREAD
3413 static int qemu_init_main_loop(void)
3415 return qemu_event_init();
3418 void qemu_init_vcpu(void *_env
)
3420 CPUState
*env
= _env
;
3424 env
->nr_cores
= smp_cores
;
3425 env
->nr_threads
= smp_threads
;
3429 int qemu_cpu_self(void *env
)
3434 static void resume_all_vcpus(void)
3438 static void pause_all_vcpus(void)
3442 void qemu_cpu_kick(void *env
)
3447 void qemu_notify_event(void)
3449 CPUState
*env
= cpu_single_env
;
3456 #define qemu_mutex_lock_iothread() do { } while (0)
3457 #define qemu_mutex_unlock_iothread() do { } while (0)
3459 void vm_stop(int reason
)
3464 #else /* CONFIG_IOTHREAD */
3466 #include "qemu-thread.h"
3468 QemuMutex qemu_global_mutex
;
3469 static QemuMutex qemu_fair_mutex
;
3471 static QemuThread io_thread
;
3473 static QemuThread
*tcg_cpu_thread
;
3474 static QemuCond
*tcg_halt_cond
;
3476 static int qemu_system_ready
;
3478 static QemuCond qemu_cpu_cond
;
3480 static QemuCond qemu_system_cond
;
3481 static QemuCond qemu_pause_cond
;
3483 static void block_io_signals(void);
3484 static void unblock_io_signals(void);
3485 static int tcg_has_work(void);
3487 static int qemu_init_main_loop(void)
3491 ret
= qemu_event_init();
3495 qemu_cond_init(&qemu_pause_cond
);
3496 qemu_mutex_init(&qemu_fair_mutex
);
3497 qemu_mutex_init(&qemu_global_mutex
);
3498 qemu_mutex_lock(&qemu_global_mutex
);
3500 unblock_io_signals();
3501 qemu_thread_self(&io_thread
);
3506 static void qemu_wait_io_event(CPUState
*env
)
3508 while (!tcg_has_work())
3509 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3511 qemu_mutex_unlock(&qemu_global_mutex
);
3514 * Users of qemu_global_mutex can be starved, having no chance
3515 * to acquire it since this path will get to it first.
3516 * So use another lock to provide fairness.
3518 qemu_mutex_lock(&qemu_fair_mutex
);
3519 qemu_mutex_unlock(&qemu_fair_mutex
);
3521 qemu_mutex_lock(&qemu_global_mutex
);
3525 qemu_cond_signal(&qemu_pause_cond
);
3529 static int qemu_cpu_exec(CPUState
*env
);
3531 static void *kvm_cpu_thread_fn(void *arg
)
3533 CPUState
*env
= arg
;
3536 qemu_thread_self(env
->thread
);
3540 /* signal CPU creation */
3541 qemu_mutex_lock(&qemu_global_mutex
);
3543 qemu_cond_signal(&qemu_cpu_cond
);
3545 /* and wait for machine initialization */
3546 while (!qemu_system_ready
)
3547 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3550 if (cpu_can_run(env
))
3552 qemu_wait_io_event(env
);
3558 static void tcg_cpu_exec(void);
3560 static void *tcg_cpu_thread_fn(void *arg
)
3562 CPUState
*env
= arg
;
3565 qemu_thread_self(env
->thread
);
3567 /* signal CPU creation */
3568 qemu_mutex_lock(&qemu_global_mutex
);
3569 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
3571 qemu_cond_signal(&qemu_cpu_cond
);
3573 /* and wait for machine initialization */
3574 while (!qemu_system_ready
)
3575 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3579 qemu_wait_io_event(cur_cpu
);
3585 void qemu_cpu_kick(void *_env
)
3587 CPUState
*env
= _env
;
3588 qemu_cond_broadcast(env
->halt_cond
);
3590 qemu_thread_signal(env
->thread
, SIGUSR1
);
3593 int qemu_cpu_self(void *env
)
3595 return (cpu_single_env
!= NULL
);
3598 static void cpu_signal(int sig
)
3601 cpu_exit(cpu_single_env
);
3604 static void block_io_signals(void)
3607 struct sigaction sigact
;
3610 sigaddset(&set
, SIGUSR2
);
3611 sigaddset(&set
, SIGIO
);
3612 sigaddset(&set
, SIGALRM
);
3613 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3616 sigaddset(&set
, SIGUSR1
);
3617 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3619 memset(&sigact
, 0, sizeof(sigact
));
3620 sigact
.sa_handler
= cpu_signal
;
3621 sigaction(SIGUSR1
, &sigact
, NULL
);
3624 static void unblock_io_signals(void)
3629 sigaddset(&set
, SIGUSR2
);
3630 sigaddset(&set
, SIGIO
);
3631 sigaddset(&set
, SIGALRM
);
3632 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3635 sigaddset(&set
, SIGUSR1
);
3636 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3639 static void qemu_signal_lock(unsigned int msecs
)
3641 qemu_mutex_lock(&qemu_fair_mutex
);
3643 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
3644 qemu_thread_signal(tcg_cpu_thread
, SIGUSR1
);
3645 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
3648 qemu_mutex_unlock(&qemu_fair_mutex
);
3651 static void qemu_mutex_lock_iothread(void)
3653 if (kvm_enabled()) {
3654 qemu_mutex_lock(&qemu_fair_mutex
);
3655 qemu_mutex_lock(&qemu_global_mutex
);
3656 qemu_mutex_unlock(&qemu_fair_mutex
);
3658 qemu_signal_lock(100);
3661 static void qemu_mutex_unlock_iothread(void)
3663 qemu_mutex_unlock(&qemu_global_mutex
);
3666 static int all_vcpus_paused(void)
3668 CPUState
*penv
= first_cpu
;
3673 penv
= (CPUState
*)penv
->next_cpu
;
3679 static void pause_all_vcpus(void)
3681 CPUState
*penv
= first_cpu
;
3685 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3686 qemu_cpu_kick(penv
);
3687 penv
= (CPUState
*)penv
->next_cpu
;
3690 while (!all_vcpus_paused()) {
3691 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
3694 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3695 penv
= (CPUState
*)penv
->next_cpu
;
3700 static void resume_all_vcpus(void)
3702 CPUState
*penv
= first_cpu
;
3707 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3708 qemu_cpu_kick(penv
);
3709 penv
= (CPUState
*)penv
->next_cpu
;
3713 static void tcg_init_vcpu(void *_env
)
3715 CPUState
*env
= _env
;
3716 /* share a single thread for all cpus with TCG */
3717 if (!tcg_cpu_thread
) {
3718 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3719 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3720 qemu_cond_init(env
->halt_cond
);
3721 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
3722 while (env
->created
== 0)
3723 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3724 tcg_cpu_thread
= env
->thread
;
3725 tcg_halt_cond
= env
->halt_cond
;
3727 env
->thread
= tcg_cpu_thread
;
3728 env
->halt_cond
= tcg_halt_cond
;
3732 static void kvm_start_vcpu(CPUState
*env
)
3734 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3735 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3736 qemu_cond_init(env
->halt_cond
);
3737 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
3738 while (env
->created
== 0)
3739 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3742 void qemu_init_vcpu(void *_env
)
3744 CPUState
*env
= _env
;
3747 kvm_start_vcpu(env
);
3750 env
->nr_cores
= smp_cores
;
3751 env
->nr_threads
= smp_threads
;
3754 void qemu_notify_event(void)
3756 qemu_event_increment();
3759 void vm_stop(int reason
)
3762 qemu_thread_self(&me
);
3764 if (!qemu_thread_equal(&me
, &io_thread
)) {
3765 qemu_system_vmstop_request(reason
);
3767 * FIXME: should not return to device code in case
3768 * vm_stop() has been requested.
3770 if (cpu_single_env
) {
3771 cpu_exit(cpu_single_env
);
3772 cpu_single_env
->stop
= 1;
3783 static void host_main_loop_wait(int *timeout
)
3789 /* XXX: need to suppress polling by better using win32 events */
3791 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
3792 ret
|= pe
->func(pe
->opaque
);
3796 WaitObjects
*w
= &wait_objects
;
3798 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
3799 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
3800 if (w
->func
[ret
- WAIT_OBJECT_0
])
3801 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
3803 /* Check for additional signaled events */
3804 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
3806 /* Check if event is signaled */
3807 ret2
= WaitForSingleObject(w
->events
[i
], 0);
3808 if(ret2
== WAIT_OBJECT_0
) {
3810 w
->func
[i
](w
->opaque
[i
]);
3811 } else if (ret2
== WAIT_TIMEOUT
) {
3813 err
= GetLastError();
3814 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
3817 } else if (ret
== WAIT_TIMEOUT
) {
3819 err
= GetLastError();
3820 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
3827 static void host_main_loop_wait(int *timeout
)
3832 void main_loop_wait(int timeout
)
3834 IOHandlerRecord
*ioh
;
3835 fd_set rfds
, wfds
, xfds
;
3839 qemu_bh_update_timeout(&timeout
);
3841 host_main_loop_wait(&timeout
);
3843 /* poll any events */
3844 /* XXX: separate device handlers from system ones */
3849 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3853 (!ioh
->fd_read_poll
||
3854 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
3855 FD_SET(ioh
->fd
, &rfds
);
3859 if (ioh
->fd_write
) {
3860 FD_SET(ioh
->fd
, &wfds
);
3866 tv
.tv_sec
= timeout
/ 1000;
3867 tv
.tv_usec
= (timeout
% 1000) * 1000;
3869 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
3871 qemu_mutex_unlock_iothread();
3872 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
3873 qemu_mutex_lock_iothread();
3875 IOHandlerRecord
**pioh
;
3877 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3878 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
3879 ioh
->fd_read(ioh
->opaque
);
3881 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
3882 ioh
->fd_write(ioh
->opaque
);
3886 /* remove deleted IO handlers */
3887 pioh
= &first_io_handler
;
3898 slirp_select_poll(&rfds
, &wfds
, &xfds
, (ret
< 0));
3900 /* rearm timer, if not periodic */
3901 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
3902 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
3903 qemu_rearm_alarm_timer(alarm_timer
);
3906 /* vm time timers */
3908 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
3909 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
3910 qemu_get_clock(vm_clock
));
3913 /* real time timers */
3914 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
3915 qemu_get_clock(rt_clock
));
3917 /* Check bottom-halves last in case any of the earlier events triggered
3923 static int qemu_cpu_exec(CPUState
*env
)
3926 #ifdef CONFIG_PROFILER
3930 #ifdef CONFIG_PROFILER
3931 ti
= profile_getclock();
3936 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
3937 env
->icount_decr
.u16
.low
= 0;
3938 env
->icount_extra
= 0;
3939 count
= qemu_next_deadline();
3940 count
= (count
+ (1 << icount_time_shift
) - 1)
3941 >> icount_time_shift
;
3942 qemu_icount
+= count
;
3943 decr
= (count
> 0xffff) ? 0xffff : count
;
3945 env
->icount_decr
.u16
.low
= decr
;
3946 env
->icount_extra
= count
;
3948 ret
= cpu_exec(env
);
3949 #ifdef CONFIG_PROFILER
3950 qemu_time
+= profile_getclock() - ti
;
3953 /* Fold pending instructions back into the
3954 instruction counter, and clear the interrupt flag. */
3955 qemu_icount
-= (env
->icount_decr
.u16
.low
3956 + env
->icount_extra
);
3957 env
->icount_decr
.u32
= 0;
3958 env
->icount_extra
= 0;
3963 static void tcg_cpu_exec(void)
3967 if (next_cpu
== NULL
)
3968 next_cpu
= first_cpu
;
3969 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
3970 CPUState
*env
= cur_cpu
= next_cpu
;
3974 if (timer_alarm_pending
) {
3975 timer_alarm_pending
= 0;
3978 if (cpu_can_run(env
))
3979 ret
= qemu_cpu_exec(env
);
3980 if (ret
== EXCP_DEBUG
) {
3981 gdb_set_stop_cpu(env
);
3982 debug_requested
= 1;
3988 static int cpu_has_work(CPUState
*env
)
3996 if (qemu_cpu_has_work(env
))
4001 static int tcg_has_work(void)
4005 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4006 if (cpu_has_work(env
))
4011 static int qemu_calculate_timeout(void)
4013 #ifndef CONFIG_IOTHREAD
4018 else if (tcg_has_work())
4020 else if (!use_icount
)
4023 /* XXX: use timeout computed from timers */
4026 /* Advance virtual time to the next event. */
4027 if (use_icount
== 1) {
4028 /* When not using an adaptive execution frequency
4029 we tend to get badly out of sync with real time,
4030 so just delay for a reasonable amount of time. */
4033 delta
= cpu_get_icount() - cpu_get_clock();
4036 /* If virtual time is ahead of real time then just
4038 timeout
= (delta
/ 1000000) + 1;
4040 /* Wait for either IO to occur or the next
4042 add
= qemu_next_deadline();
4043 /* We advance the timer before checking for IO.
4044 Limit the amount we advance so that early IO
4045 activity won't get the guest too far ahead. */
4049 add
= (add
+ (1 << icount_time_shift
) - 1)
4050 >> icount_time_shift
;
4052 timeout
= delta
/ 1000000;
4059 #else /* CONFIG_IOTHREAD */
4064 static int vm_can_run(void)
4066 if (powerdown_requested
)
4068 if (reset_requested
)
4070 if (shutdown_requested
)
4072 if (debug_requested
)
4077 qemu_irq qemu_system_powerdown
;
4079 static void main_loop(void)
4083 #ifdef CONFIG_IOTHREAD
4084 qemu_system_ready
= 1;
4085 qemu_cond_broadcast(&qemu_system_cond
);
4090 #ifdef CONFIG_PROFILER
4093 #ifndef CONFIG_IOTHREAD
4096 #ifdef CONFIG_PROFILER
4097 ti
= profile_getclock();
4099 main_loop_wait(qemu_calculate_timeout());
4100 #ifdef CONFIG_PROFILER
4101 dev_time
+= profile_getclock() - ti
;
4103 } while (vm_can_run());
4105 if (qemu_debug_requested())
4106 vm_stop(EXCP_DEBUG
);
4107 if (qemu_shutdown_requested()) {
4114 if (qemu_reset_requested()) {
4116 qemu_system_reset();
4119 if (qemu_powerdown_requested()) {
4120 qemu_irq_raise(qemu_system_powerdown
);
4122 if ((r
= qemu_vmstop_requested()))
4128 static void version(void)
4130 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4133 static void help(int exitcode
)
4136 printf("usage: %s [options] [disk_image]\n"
4138 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4140 #define DEF(option, opt_arg, opt_enum, opt_help) \
4142 #define DEFHEADING(text) stringify(text) "\n"
4143 #include "qemu-options.h"
4148 "During emulation, the following keys are useful:\n"
4149 "ctrl-alt-f toggle full screen\n"
4150 "ctrl-alt-n switch to virtual console 'n'\n"
4151 "ctrl-alt toggle mouse and keyboard grab\n"
4153 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4158 DEFAULT_NETWORK_SCRIPT
,
4159 DEFAULT_NETWORK_DOWN_SCRIPT
,
4161 DEFAULT_GDBSTUB_PORT
,
4166 #define HAS_ARG 0x0001
4169 #define DEF(option, opt_arg, opt_enum, opt_help) \
4171 #define DEFHEADING(text)
4172 #include "qemu-options.h"
4178 typedef struct QEMUOption
{
4184 static const QEMUOption qemu_options
[] = {
4185 { "h", 0, QEMU_OPTION_h
},
4186 #define DEF(option, opt_arg, opt_enum, opt_help) \
4187 { option, opt_arg, opt_enum },
4188 #define DEFHEADING(text)
4189 #include "qemu-options.h"
4197 struct soundhw soundhw
[] = {
4198 #ifdef HAS_AUDIO_CHOICE
4199 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4205 { .init_isa
= pcspk_audio_init
}
4212 "Creative Sound Blaster 16",
4215 { .init_isa
= SB16_init
}
4219 #ifdef CONFIG_CS4231A
4225 { .init_isa
= cs4231a_init
}
4233 "Yamaha YMF262 (OPL3)",
4235 "Yamaha YM3812 (OPL2)",
4239 { .init_isa
= Adlib_init
}
4246 "Gravis Ultrasound GF1",
4249 { .init_isa
= GUS_init
}
4256 "Intel 82801AA AC97 Audio",
4259 { .init_pci
= ac97_init
}
4263 #ifdef CONFIG_ES1370
4266 "ENSONIQ AudioPCI ES1370",
4269 { .init_pci
= es1370_init
}
4273 #endif /* HAS_AUDIO_CHOICE */
4275 { NULL
, NULL
, 0, 0, { NULL
} }
4278 static void select_soundhw (const char *optarg
)
4282 if (*optarg
== '?') {
4285 printf ("Valid sound card names (comma separated):\n");
4286 for (c
= soundhw
; c
->name
; ++c
) {
4287 printf ("%-11s %s\n", c
->name
, c
->descr
);
4289 printf ("\n-soundhw all will enable all of the above\n");
4290 exit (*optarg
!= '?');
4298 if (!strcmp (optarg
, "all")) {
4299 for (c
= soundhw
; c
->name
; ++c
) {
4307 e
= strchr (p
, ',');
4308 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4310 for (c
= soundhw
; c
->name
; ++c
) {
4311 if (!strncmp (c
->name
, p
, l
) && !c
->name
[l
]) {
4320 "Unknown sound card name (too big to show)\n");
4323 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4328 p
+= l
+ (e
!= NULL
);
4332 goto show_valid_cards
;
4337 static void select_vgahw (const char *p
)
4341 vga_interface_type
= VGA_NONE
;
4342 if (strstart(p
, "std", &opts
)) {
4343 vga_interface_type
= VGA_STD
;
4344 } else if (strstart(p
, "cirrus", &opts
)) {
4345 vga_interface_type
= VGA_CIRRUS
;
4346 } else if (strstart(p
, "vmware", &opts
)) {
4347 vga_interface_type
= VGA_VMWARE
;
4348 } else if (strstart(p
, "xenfb", &opts
)) {
4349 vga_interface_type
= VGA_XENFB
;
4350 } else if (!strstart(p
, "none", &opts
)) {
4352 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4356 const char *nextopt
;
4358 if (strstart(opts
, ",retrace=", &nextopt
)) {
4360 if (strstart(opts
, "dumb", &nextopt
))
4361 vga_retrace_method
= VGA_RETRACE_DUMB
;
4362 else if (strstart(opts
, "precise", &nextopt
))
4363 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4364 else goto invalid_vga
;
4365 } else goto invalid_vga
;
4371 static int balloon_parse(const char *arg
)
4375 if (strcmp(arg
, "none") == 0) {
4379 if (!strncmp(arg
, "virtio", 6)) {
4380 if (arg
[6] == ',') {
4381 /* have params -> parse them */
4382 opts
= qemu_opts_parse(&qemu_device_opts
, arg
+7, NULL
);
4386 /* create empty opts */
4387 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4389 qemu_opt_set(opts
, "driver", "virtio-balloon-pci");
4398 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4400 exit(STATUS_CONTROL_C_EXIT
);
4405 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4409 if(strlen(str
) != 36)
4412 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4413 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4414 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4420 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4426 #define MAX_NET_CLIENTS 32
4430 static void termsig_handler(int signal
)
4432 qemu_system_shutdown_request();
4435 static void sigchld_handler(int signal
)
4437 waitpid(-1, NULL
, WNOHANG
);
4440 static void sighandler_setup(void)
4442 struct sigaction act
;
4444 memset(&act
, 0, sizeof(act
));
4445 act
.sa_handler
= termsig_handler
;
4446 sigaction(SIGINT
, &act
, NULL
);
4447 sigaction(SIGHUP
, &act
, NULL
);
4448 sigaction(SIGTERM
, &act
, NULL
);
4450 act
.sa_handler
= sigchld_handler
;
4451 act
.sa_flags
= SA_NOCLDSTOP
;
4452 sigaction(SIGCHLD
, &act
, NULL
);
4458 /* Look for support files in the same directory as the executable. */
4459 static char *find_datadir(const char *argv0
)
4465 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
4472 while (p
!= buf
&& *p
!= '\\')
4475 if (access(buf
, R_OK
) == 0) {
4476 return qemu_strdup(buf
);
4482 /* Find a likely location for support files using the location of the binary.
4483 For installed binaries this will be "$bindir/../share/qemu". When
4484 running from the build tree this will be "$bindir/../pc-bios". */
4485 #define SHARE_SUFFIX "/share/qemu"
4486 #define BUILD_SUFFIX "/pc-bios"
4487 static char *find_datadir(const char *argv0
)
4495 #if defined(__linux__)
4498 len
= readlink("/proc/self/exe", buf
, sizeof(buf
) - 1);
4504 #elif defined(__FreeBSD__)
4507 len
= readlink("/proc/curproc/file", buf
, sizeof(buf
) - 1);
4514 /* If we don't have any way of figuring out the actual executable
4515 location then try argv[0]. */
4517 p
= realpath(argv0
, buf
);
4525 max_len
= strlen(dir
) +
4526 MAX(strlen(SHARE_SUFFIX
), strlen(BUILD_SUFFIX
)) + 1;
4527 res
= qemu_mallocz(max_len
);
4528 snprintf(res
, max_len
, "%s%s", dir
, SHARE_SUFFIX
);
4529 if (access(res
, R_OK
)) {
4530 snprintf(res
, max_len
, "%s%s", dir
, BUILD_SUFFIX
);
4531 if (access(res
, R_OK
)) {
4543 char *qemu_find_file(int type
, const char *name
)
4549 /* If name contains path separators then try it as a straight path. */
4550 if ((strchr(name
, '/') || strchr(name
, '\\'))
4551 && access(name
, R_OK
) == 0) {
4552 return qemu_strdup(name
);
4555 case QEMU_FILE_TYPE_BIOS
:
4558 case QEMU_FILE_TYPE_KEYMAP
:
4559 subdir
= "keymaps/";
4564 len
= strlen(data_dir
) + strlen(name
) + strlen(subdir
) + 2;
4565 buf
= qemu_mallocz(len
);
4566 snprintf(buf
, len
, "%s/%s%s", data_dir
, subdir
, name
);
4567 if (access(buf
, R_OK
)) {
4574 static int device_init_func(QemuOpts
*opts
, void *opaque
)
4578 dev
= qdev_device_add(opts
);
4584 struct device_config
{
4586 DEV_USB
, /* -usbdevice */
4589 const char *cmdline
;
4590 TAILQ_ENTRY(device_config
) next
;
4592 TAILQ_HEAD(, device_config
) device_configs
= TAILQ_HEAD_INITIALIZER(device_configs
);
4594 static void add_device_config(int type
, const char *cmdline
)
4596 struct device_config
*conf
;
4598 conf
= qemu_mallocz(sizeof(*conf
));
4600 conf
->cmdline
= cmdline
;
4601 TAILQ_INSERT_TAIL(&device_configs
, conf
, next
);
4604 static int foreach_device_config(int type
, int (*func
)(const char *cmdline
))
4606 struct device_config
*conf
;
4609 TAILQ_FOREACH(conf
, &device_configs
, next
) {
4610 if (conf
->type
!= type
)
4612 rc
= func(conf
->cmdline
);
4619 int main(int argc
, char **argv
, char **envp
)
4621 const char *gdbstub_dev
= NULL
;
4622 uint32_t boot_devices_bitmap
= 0;
4624 int snapshot
, linux_boot
, net_boot
;
4625 const char *initrd_filename
;
4626 const char *kernel_filename
, *kernel_cmdline
;
4627 char boot_devices
[33] = "cad"; /* default to HD->floppy->CD-ROM */
4629 DisplayChangeListener
*dcl
;
4630 int cyls
, heads
, secs
, translation
;
4631 const char *net_clients
[MAX_NET_CLIENTS
];
4633 QemuOpts
*hda_opts
= NULL
, *opts
;
4635 const char *r
, *optarg
;
4636 CharDriverState
*monitor_hds
[MAX_MONITOR_DEVICES
];
4637 const char *monitor_devices
[MAX_MONITOR_DEVICES
];
4638 int monitor_device_index
;
4639 const char *serial_devices
[MAX_SERIAL_PORTS
];
4640 int serial_device_index
;
4641 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
4642 int parallel_device_index
;
4643 const char *virtio_consoles
[MAX_VIRTIO_CONSOLES
];
4644 int virtio_console_index
;
4645 const char *loadvm
= NULL
;
4646 QEMUMachine
*machine
;
4647 const char *cpu_model
;
4652 const char *pid_file
= NULL
;
4653 const char *incoming
= NULL
;
4656 struct passwd
*pwd
= NULL
;
4657 const char *chroot_dir
= NULL
;
4658 const char *run_as
= NULL
;
4661 int show_vnc_port
= 0;
4663 qemu_errors_to_file(stderr
);
4664 qemu_cache_utils_init(envp
);
4666 LIST_INIT (&vm_change_state_head
);
4669 struct sigaction act
;
4670 sigfillset(&act
.sa_mask
);
4672 act
.sa_handler
= SIG_IGN
;
4673 sigaction(SIGPIPE
, &act
, NULL
);
4676 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4677 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4678 QEMU to run on a single CPU */
4683 h
= GetCurrentProcess();
4684 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4685 for(i
= 0; i
< 32; i
++) {
4686 if (mask
& (1 << i
))
4691 SetProcessAffinityMask(h
, mask
);
4697 module_call_init(MODULE_INIT_MACHINE
);
4698 machine
= find_default_machine();
4700 initrd_filename
= NULL
;
4703 kernel_filename
= NULL
;
4704 kernel_cmdline
= "";
4705 cyls
= heads
= secs
= 0;
4706 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4708 serial_devices
[0] = "vc:80Cx24C";
4709 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
4710 serial_devices
[i
] = NULL
;
4711 serial_device_index
= 0;
4713 parallel_devices
[0] = "vc:80Cx24C";
4714 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
4715 parallel_devices
[i
] = NULL
;
4716 parallel_device_index
= 0;
4718 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++)
4719 virtio_consoles
[i
] = NULL
;
4720 virtio_console_index
= 0;
4722 monitor_devices
[0] = "vc:80Cx24C";
4723 for (i
= 1; i
< MAX_MONITOR_DEVICES
; i
++) {
4724 monitor_devices
[i
] = NULL
;
4726 monitor_device_index
= 0;
4728 for (i
= 0; i
< MAX_NODES
; i
++) {
4730 node_cpumask
[i
] = 0;
4746 hda_opts
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
4748 const QEMUOption
*popt
;
4751 /* Treat --foo the same as -foo. */
4754 popt
= qemu_options
;
4757 fprintf(stderr
, "%s: invalid option -- '%s'\n",
4761 if (!strcmp(popt
->name
, r
+ 1))
4765 if (popt
->flags
& HAS_ARG
) {
4766 if (optind
>= argc
) {
4767 fprintf(stderr
, "%s: option '%s' requires an argument\n",
4771 optarg
= argv
[optind
++];
4776 switch(popt
->index
) {
4778 machine
= find_machine(optarg
);
4781 printf("Supported machines are:\n");
4782 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
4784 printf("%-10s %s (alias of %s)\n",
4785 m
->alias
, m
->desc
, m
->name
);
4786 printf("%-10s %s%s\n",
4788 m
->is_default
? " (default)" : "");
4790 exit(*optarg
!= '?');
4793 case QEMU_OPTION_cpu
:
4794 /* hw initialization will check this */
4795 if (*optarg
== '?') {
4796 /* XXX: implement xxx_cpu_list for targets that still miss it */
4797 #if defined(cpu_list)
4798 cpu_list(stdout
, &fprintf
);
4805 case QEMU_OPTION_initrd
:
4806 initrd_filename
= optarg
;
4808 case QEMU_OPTION_hda
:
4810 hda_opts
= drive_add(optarg
, HD_ALIAS
, 0);
4812 hda_opts
= drive_add(optarg
, HD_ALIAS
4813 ",cyls=%d,heads=%d,secs=%d%s",
4814 0, cyls
, heads
, secs
,
4815 translation
== BIOS_ATA_TRANSLATION_LBA
?
4817 translation
== BIOS_ATA_TRANSLATION_NONE
?
4818 ",trans=none" : "");
4820 case QEMU_OPTION_hdb
:
4821 case QEMU_OPTION_hdc
:
4822 case QEMU_OPTION_hdd
:
4823 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
4825 case QEMU_OPTION_drive
:
4826 drive_add(NULL
, "%s", optarg
);
4828 case QEMU_OPTION_set
:
4829 if (qemu_set_option(optarg
) != 0)
4832 case QEMU_OPTION_mtdblock
:
4833 drive_add(optarg
, MTD_ALIAS
);
4835 case QEMU_OPTION_sd
:
4836 drive_add(optarg
, SD_ALIAS
);
4838 case QEMU_OPTION_pflash
:
4839 drive_add(optarg
, PFLASH_ALIAS
);
4841 case QEMU_OPTION_snapshot
:
4844 case QEMU_OPTION_hdachs
:
4848 cyls
= strtol(p
, (char **)&p
, 0);
4849 if (cyls
< 1 || cyls
> 16383)
4854 heads
= strtol(p
, (char **)&p
, 0);
4855 if (heads
< 1 || heads
> 16)
4860 secs
= strtol(p
, (char **)&p
, 0);
4861 if (secs
< 1 || secs
> 63)
4865 if (!strcmp(p
, "none"))
4866 translation
= BIOS_ATA_TRANSLATION_NONE
;
4867 else if (!strcmp(p
, "lba"))
4868 translation
= BIOS_ATA_TRANSLATION_LBA
;
4869 else if (!strcmp(p
, "auto"))
4870 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4873 } else if (*p
!= '\0') {
4875 fprintf(stderr
, "qemu: invalid physical CHS format\n");
4878 if (hda_opts
!= NULL
) {
4880 snprintf(num
, sizeof(num
), "%d", cyls
);
4881 qemu_opt_set(hda_opts
, "cyls", num
);
4882 snprintf(num
, sizeof(num
), "%d", heads
);
4883 qemu_opt_set(hda_opts
, "heads", num
);
4884 snprintf(num
, sizeof(num
), "%d", secs
);
4885 qemu_opt_set(hda_opts
, "secs", num
);
4886 if (translation
== BIOS_ATA_TRANSLATION_LBA
)
4887 qemu_opt_set(hda_opts
, "trans", "lba");
4888 if (translation
== BIOS_ATA_TRANSLATION_NONE
)
4889 qemu_opt_set(hda_opts
, "trans", "none");
4893 case QEMU_OPTION_numa
:
4894 if (nb_numa_nodes
>= MAX_NODES
) {
4895 fprintf(stderr
, "qemu: too many NUMA nodes\n");
4900 case QEMU_OPTION_nographic
:
4901 display_type
= DT_NOGRAPHIC
;
4903 #ifdef CONFIG_CURSES
4904 case QEMU_OPTION_curses
:
4905 display_type
= DT_CURSES
;
4908 case QEMU_OPTION_portrait
:
4911 case QEMU_OPTION_kernel
:
4912 kernel_filename
= optarg
;
4914 case QEMU_OPTION_append
:
4915 kernel_cmdline
= optarg
;
4917 case QEMU_OPTION_cdrom
:
4918 drive_add(optarg
, CDROM_ALIAS
);
4920 case QEMU_OPTION_boot
:
4922 static const char * const params
[] = {
4923 "order", "once", "menu", NULL
4925 char buf
[sizeof(boot_devices
)];
4926 char *standard_boot_devices
;
4929 if (!strchr(optarg
, '=')) {
4931 pstrcpy(buf
, sizeof(buf
), optarg
);
4932 } else if (check_params(buf
, sizeof(buf
), params
, optarg
) < 0) {
4934 "qemu: unknown boot parameter '%s' in '%s'\n",
4940 get_param_value(buf
, sizeof(buf
), "order", optarg
)) {
4941 boot_devices_bitmap
= parse_bootdevices(buf
);
4942 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
4945 if (get_param_value(buf
, sizeof(buf
),
4947 boot_devices_bitmap
|= parse_bootdevices(buf
);
4948 standard_boot_devices
= qemu_strdup(boot_devices
);
4949 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
4950 qemu_register_reset(restore_boot_devices
,
4951 standard_boot_devices
);
4953 if (get_param_value(buf
, sizeof(buf
),
4955 if (!strcmp(buf
, "on")) {
4957 } else if (!strcmp(buf
, "off")) {
4961 "qemu: invalid option value '%s'\n",
4969 case QEMU_OPTION_fda
:
4970 case QEMU_OPTION_fdb
:
4971 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
4974 case QEMU_OPTION_no_fd_bootchk
:
4978 case QEMU_OPTION_net
:
4979 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
4980 fprintf(stderr
, "qemu: too many network clients\n");
4983 net_clients
[nb_net_clients
] = optarg
;
4987 case QEMU_OPTION_tftp
:
4988 legacy_tftp_prefix
= optarg
;
4990 case QEMU_OPTION_bootp
:
4991 legacy_bootp_filename
= optarg
;
4994 case QEMU_OPTION_smb
:
4995 net_slirp_smb(optarg
);
4998 case QEMU_OPTION_redir
:
4999 net_slirp_redir(optarg
);
5002 case QEMU_OPTION_bt
:
5003 add_device_config(DEV_BT
, optarg
);
5006 case QEMU_OPTION_audio_help
:
5010 case QEMU_OPTION_soundhw
:
5011 select_soundhw (optarg
);
5017 case QEMU_OPTION_version
:
5021 case QEMU_OPTION_m
: {
5025 value
= strtoul(optarg
, &ptr
, 10);
5027 case 0: case 'M': case 'm':
5034 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5038 /* On 32-bit hosts, QEMU is limited by virtual address space */
5039 if (value
> (2047 << 20) && HOST_LONG_BITS
== 32) {
5040 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5043 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5044 fprintf(stderr
, "qemu: ram size too large\n");
5053 const CPULogItem
*item
;
5055 mask
= cpu_str_to_log_mask(optarg
);
5057 printf("Log items (comma separated):\n");
5058 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5059 printf("%-10s %s\n", item
->name
, item
->help
);
5067 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5069 case QEMU_OPTION_gdb
:
5070 gdbstub_dev
= optarg
;
5075 case QEMU_OPTION_bios
:
5078 case QEMU_OPTION_singlestep
:
5086 keyboard_layout
= optarg
;
5089 case QEMU_OPTION_localtime
:
5092 case QEMU_OPTION_vga
:
5093 select_vgahw (optarg
);
5095 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5101 w
= strtol(p
, (char **)&p
, 10);
5104 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5110 h
= strtol(p
, (char **)&p
, 10);
5115 depth
= strtol(p
, (char **)&p
, 10);
5116 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5117 depth
!= 24 && depth
!= 32)
5119 } else if (*p
== '\0') {
5120 depth
= graphic_depth
;
5127 graphic_depth
= depth
;
5131 case QEMU_OPTION_echr
:
5134 term_escape_char
= strtol(optarg
, &r
, 0);
5136 printf("Bad argument to echr\n");
5139 case QEMU_OPTION_monitor
:
5140 if (monitor_device_index
>= MAX_MONITOR_DEVICES
) {
5141 fprintf(stderr
, "qemu: too many monitor devices\n");
5144 monitor_devices
[monitor_device_index
] = optarg
;
5145 monitor_device_index
++;
5147 case QEMU_OPTION_chardev
:
5148 opts
= qemu_opts_parse(&qemu_chardev_opts
, optarg
, "backend");
5150 fprintf(stderr
, "parse error: %s\n", optarg
);
5153 if (NULL
== qemu_chr_open_opts(opts
, NULL
)) {
5157 case QEMU_OPTION_serial
:
5158 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
5159 fprintf(stderr
, "qemu: too many serial ports\n");
5162 serial_devices
[serial_device_index
] = optarg
;
5163 serial_device_index
++;
5165 case QEMU_OPTION_watchdog
:
5168 "qemu: only one watchdog option may be given\n");
5173 case QEMU_OPTION_watchdog_action
:
5174 if (select_watchdog_action(optarg
) == -1) {
5175 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5179 case QEMU_OPTION_virtiocon
:
5180 if (virtio_console_index
>= MAX_VIRTIO_CONSOLES
) {
5181 fprintf(stderr
, "qemu: too many virtio consoles\n");
5184 virtio_consoles
[virtio_console_index
] = optarg
;
5185 virtio_console_index
++;
5187 case QEMU_OPTION_parallel
:
5188 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
5189 fprintf(stderr
, "qemu: too many parallel ports\n");
5192 parallel_devices
[parallel_device_index
] = optarg
;
5193 parallel_device_index
++;
5195 case QEMU_OPTION_loadvm
:
5198 case QEMU_OPTION_full_screen
:
5202 case QEMU_OPTION_no_frame
:
5205 case QEMU_OPTION_alt_grab
:
5208 case QEMU_OPTION_no_quit
:
5211 case QEMU_OPTION_sdl
:
5212 display_type
= DT_SDL
;
5215 case QEMU_OPTION_pidfile
:
5219 case QEMU_OPTION_win2k_hack
:
5220 win2k_install_hack
= 1;
5222 case QEMU_OPTION_rtc_td_hack
:
5225 case QEMU_OPTION_acpitable
:
5226 if(acpi_table_add(optarg
) < 0) {
5227 fprintf(stderr
, "Wrong acpi table provided\n");
5231 case QEMU_OPTION_smbios
:
5232 if(smbios_entry_add(optarg
) < 0) {
5233 fprintf(stderr
, "Wrong smbios provided\n");
5239 case QEMU_OPTION_enable_kvm
:
5243 case QEMU_OPTION_usb
:
5246 case QEMU_OPTION_usbdevice
:
5248 add_device_config(DEV_USB
, optarg
);
5250 case QEMU_OPTION_device
:
5251 opts
= qemu_opts_parse(&qemu_device_opts
, optarg
, "driver");
5253 fprintf(stderr
, "parse error: %s\n", optarg
);
5257 case QEMU_OPTION_smp
:
5260 fprintf(stderr
, "Invalid number of CPUs\n");
5263 if (max_cpus
< smp_cpus
) {
5264 fprintf(stderr
, "maxcpus must be equal to or greater than "
5268 if (max_cpus
> 255) {
5269 fprintf(stderr
, "Unsupported number of maxcpus\n");
5273 case QEMU_OPTION_vnc
:
5274 display_type
= DT_VNC
;
5275 vnc_display
= optarg
;
5278 case QEMU_OPTION_no_acpi
:
5281 case QEMU_OPTION_no_hpet
:
5284 case QEMU_OPTION_balloon
:
5285 if (balloon_parse(optarg
) < 0) {
5286 fprintf(stderr
, "Unknown -balloon argument %s\n", optarg
);
5291 case QEMU_OPTION_no_reboot
:
5294 case QEMU_OPTION_no_shutdown
:
5297 case QEMU_OPTION_show_cursor
:
5300 case QEMU_OPTION_uuid
:
5301 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5302 fprintf(stderr
, "Fail to parse UUID string."
5303 " Wrong format.\n");
5308 case QEMU_OPTION_daemonize
:
5312 case QEMU_OPTION_option_rom
:
5313 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5314 fprintf(stderr
, "Too many option ROMs\n");
5317 option_rom
[nb_option_roms
] = optarg
;
5320 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5321 case QEMU_OPTION_semihosting
:
5322 semihosting_enabled
= 1;
5325 case QEMU_OPTION_name
:
5326 qemu_name
= qemu_strdup(optarg
);
5328 char *p
= strchr(qemu_name
, ',');
5331 if (strncmp(p
, "process=", 8)) {
5332 fprintf(stderr
, "Unknown subargument %s to -name", p
);
5340 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5341 case QEMU_OPTION_prom_env
:
5342 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5343 fprintf(stderr
, "Too many prom variables\n");
5346 prom_envs
[nb_prom_envs
] = optarg
;
5351 case QEMU_OPTION_old_param
:
5355 case QEMU_OPTION_clock
:
5356 configure_alarms(optarg
);
5358 case QEMU_OPTION_startdate
:
5361 time_t rtc_start_date
;
5362 if (!strcmp(optarg
, "now")) {
5363 rtc_date_offset
= -1;
5365 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
5373 } else if (sscanf(optarg
, "%d-%d-%d",
5376 &tm
.tm_mday
) == 3) {
5385 rtc_start_date
= mktimegm(&tm
);
5386 if (rtc_start_date
== -1) {
5388 fprintf(stderr
, "Invalid date format. Valid format are:\n"
5389 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5392 rtc_date_offset
= time(NULL
) - rtc_start_date
;
5396 case QEMU_OPTION_tb_size
:
5397 tb_size
= strtol(optarg
, NULL
, 0);
5401 case QEMU_OPTION_icount
:
5403 if (strcmp(optarg
, "auto") == 0) {
5404 icount_time_shift
= -1;
5406 icount_time_shift
= strtol(optarg
, NULL
, 0);
5409 case QEMU_OPTION_incoming
:
5413 case QEMU_OPTION_chroot
:
5414 chroot_dir
= optarg
;
5416 case QEMU_OPTION_runas
:
5421 case QEMU_OPTION_xen_domid
:
5422 xen_domid
= atoi(optarg
);
5424 case QEMU_OPTION_xen_create
:
5425 xen_mode
= XEN_CREATE
;
5427 case QEMU_OPTION_xen_attach
:
5428 xen_mode
= XEN_ATTACH
;
5435 if (kvm_enabled()) {
5438 ret
= kvm_init(smp_cpus
);
5440 fprintf(stderr
, "failed to initialize KVM\n");
5445 /* If no data_dir is specified then try to find it relative to the
5448 data_dir
= find_datadir(argv
[0]);
5450 /* If all else fails use the install patch specified when building. */
5452 data_dir
= CONFIG_QEMU_SHAREDIR
;
5456 * Default to max_cpus = smp_cpus, in case the user doesn't
5457 * specify a max_cpus value.
5460 max_cpus
= smp_cpus
;
5462 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5463 if (smp_cpus
> machine
->max_cpus
) {
5464 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5465 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5470 if (display_type
== DT_NOGRAPHIC
) {
5471 if (serial_device_index
== 0)
5472 serial_devices
[0] = "stdio";
5473 if (parallel_device_index
== 0)
5474 parallel_devices
[0] = "null";
5475 if (strncmp(monitor_devices
[0], "vc", 2) == 0) {
5476 monitor_devices
[0] = "stdio";
5484 if (pipe(fds
) == -1)
5495 len
= read(fds
[0], &status
, 1);
5496 if (len
== -1 && (errno
== EINTR
))
5501 else if (status
== 1) {
5502 fprintf(stderr
, "Could not acquire pidfile\n");
5519 signal(SIGTSTP
, SIG_IGN
);
5520 signal(SIGTTOU
, SIG_IGN
);
5521 signal(SIGTTIN
, SIG_IGN
);
5524 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5527 write(fds
[1], &status
, 1);
5529 fprintf(stderr
, "Could not acquire pid file\n");
5534 if (qemu_init_main_loop()) {
5535 fprintf(stderr
, "qemu_init_main_loop failed\n");
5538 linux_boot
= (kernel_filename
!= NULL
);
5540 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5541 fprintf(stderr
, "-append only allowed with -kernel option\n");
5545 if (!linux_boot
&& initrd_filename
!= NULL
) {
5546 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5551 /* Win32 doesn't support line-buffering and requires size >= 2 */
5552 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5556 if (init_timer_alarm() < 0) {
5557 fprintf(stderr
, "could not initialize alarm timer\n");
5560 if (use_icount
&& icount_time_shift
< 0) {
5562 /* 125MIPS seems a reasonable initial guess at the guest speed.
5563 It will be corrected fairly quickly anyway. */
5564 icount_time_shift
= 3;
5565 init_icount_adjust();
5572 /* init network clients */
5573 if (nb_net_clients
== 0) {
5574 /* if no clients, we use a default config */
5575 net_clients
[nb_net_clients
++] = "nic";
5577 net_clients
[nb_net_clients
++] = "user";
5581 for(i
= 0;i
< nb_net_clients
; i
++) {
5582 if (net_client_parse(net_clients
[i
]) < 0)
5586 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5587 net_set_boot_mask(net_boot
);
5591 /* init the bluetooth world */
5592 if (foreach_device_config(DEV_BT
, bt_parse
))
5595 /* init the memory */
5597 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5599 /* init the dynamic translator */
5600 cpu_exec_init_all(tb_size
* 1024 * 1024);
5604 /* we always create the cdrom drive, even if no disk is there */
5605 drive_add(NULL
, CDROM_ALIAS
);
5607 /* we always create at least one floppy */
5608 drive_add(NULL
, FD_ALIAS
, 0);
5610 /* we always create one sd slot, even if no card is in it */
5611 drive_add(NULL
, SD_ALIAS
);
5613 /* open the virtual block devices */
5615 qemu_opts_foreach(&qemu_drive_opts
, drive_enable_snapshot
, NULL
, 0);
5616 if (qemu_opts_foreach(&qemu_drive_opts
, drive_init_func
, machine
, 1) != 0)
5619 vmstate_register(0, &vmstate_timers
,&timers_state
);
5620 register_savevm_live("ram", 0, 3, ram_save_live
, NULL
, ram_load
, NULL
);
5622 /* Maintain compatibility with multiple stdio monitors */
5623 if (!strcmp(monitor_devices
[0],"stdio")) {
5624 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5625 const char *devname
= serial_devices
[i
];
5626 if (devname
&& !strcmp(devname
,"mon:stdio")) {
5627 monitor_devices
[0] = NULL
;
5629 } else if (devname
&& !strcmp(devname
,"stdio")) {
5630 monitor_devices
[0] = NULL
;
5631 serial_devices
[i
] = "mon:stdio";
5637 if (nb_numa_nodes
> 0) {
5640 if (nb_numa_nodes
> smp_cpus
) {
5641 nb_numa_nodes
= smp_cpus
;
5644 /* If no memory size if given for any node, assume the default case
5645 * and distribute the available memory equally across all nodes
5647 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5648 if (node_mem
[i
] != 0)
5651 if (i
== nb_numa_nodes
) {
5652 uint64_t usedmem
= 0;
5654 /* On Linux, the each node's border has to be 8MB aligned,
5655 * the final node gets the rest.
5657 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
5658 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
5659 usedmem
+= node_mem
[i
];
5661 node_mem
[i
] = ram_size
- usedmem
;
5664 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5665 if (node_cpumask
[i
] != 0)
5668 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5669 * must cope with this anyway, because there are BIOSes out there in
5670 * real machines which also use this scheme.
5672 if (i
== nb_numa_nodes
) {
5673 for (i
= 0; i
< smp_cpus
; i
++) {
5674 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
5679 for (i
= 0; i
< MAX_MONITOR_DEVICES
; i
++) {
5680 const char *devname
= monitor_devices
[i
];
5681 if (devname
&& strcmp(devname
, "none")) {
5684 snprintf(label
, sizeof(label
), "monitor");
5686 snprintf(label
, sizeof(label
), "monitor%d", i
);
5688 monitor_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5689 if (!monitor_hds
[i
]) {
5690 fprintf(stderr
, "qemu: could not open monitor device '%s'\n",
5697 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5698 const char *devname
= serial_devices
[i
];
5699 if (devname
&& strcmp(devname
, "none")) {
5701 snprintf(label
, sizeof(label
), "serial%d", i
);
5702 serial_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5703 if (!serial_hds
[i
]) {
5704 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
5711 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
5712 const char *devname
= parallel_devices
[i
];
5713 if (devname
&& strcmp(devname
, "none")) {
5715 snprintf(label
, sizeof(label
), "parallel%d", i
);
5716 parallel_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5717 if (!parallel_hds
[i
]) {
5718 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
5725 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
5726 const char *devname
= virtio_consoles
[i
];
5727 if (devname
&& strcmp(devname
, "none")) {
5729 snprintf(label
, sizeof(label
), "virtcon%d", i
);
5730 virtcon_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5731 if (!virtcon_hds
[i
]) {
5732 fprintf(stderr
, "qemu: could not open virtio console '%s'\n",
5739 module_call_init(MODULE_INIT_DEVICE
);
5742 i
= select_watchdog(watchdog
);
5744 exit (i
== 1 ? 1 : 0);
5747 if (machine
->compat_props
) {
5748 qdev_prop_register_compat(machine
->compat_props
);
5750 machine
->init(ram_size
, boot_devices
,
5751 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
5755 /* must be after terminal init, SDL library changes signal handlers */
5759 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
5760 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5761 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
5767 current_machine
= machine
;
5769 /* init USB devices */
5771 foreach_device_config(DEV_USB
, usb_parse
);
5774 /* init generic devices */
5775 if (qemu_opts_foreach(&qemu_device_opts
, device_init_func
, NULL
, 1) != 0)
5779 dumb_display_init();
5780 /* just use the first displaystate for the moment */
5783 if (display_type
== DT_DEFAULT
) {
5784 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5785 display_type
= DT_SDL
;
5787 display_type
= DT_VNC
;
5788 vnc_display
= "localhost:0,to=99";
5794 switch (display_type
) {
5797 #if defined(CONFIG_CURSES)
5799 curses_display_init(ds
, full_screen
);
5802 #if defined(CONFIG_SDL)
5804 sdl_display_init(ds
, full_screen
, no_frame
);
5806 #elif defined(CONFIG_COCOA)
5808 cocoa_display_init(ds
, full_screen
);
5812 vnc_display_init(ds
);
5813 if (vnc_display_open(ds
, vnc_display
) < 0)
5816 if (show_vnc_port
) {
5817 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
5825 dcl
= ds
->listeners
;
5826 while (dcl
!= NULL
) {
5827 if (dcl
->dpy_refresh
!= NULL
) {
5828 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
5829 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
5834 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
5835 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
5836 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
5839 text_consoles_set_display(display_state
);
5840 qemu_chr_initial_reset();
5842 for (i
= 0; i
< MAX_MONITOR_DEVICES
; i
++) {
5843 if (monitor_devices
[i
] && monitor_hds
[i
]) {
5844 monitor_init(monitor_hds
[i
],
5845 MONITOR_USE_READLINE
|
5846 ((i
== 0) ? MONITOR_IS_DEFAULT
: 0));
5850 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5851 const char *devname
= serial_devices
[i
];
5852 if (devname
&& strcmp(devname
, "none")) {
5853 if (strstart(devname
, "vc", 0))
5854 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
5858 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
5859 const char *devname
= parallel_devices
[i
];
5860 if (devname
&& strcmp(devname
, "none")) {
5861 if (strstart(devname
, "vc", 0))
5862 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
5866 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
5867 const char *devname
= virtio_consoles
[i
];
5868 if (virtcon_hds
[i
] && devname
) {
5869 if (strstart(devname
, "vc", 0))
5870 qemu_chr_printf(virtcon_hds
[i
], "virtio console%d\r\n", i
);
5874 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
5875 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
5881 if (load_vmstate(cur_mon
, loadvm
) < 0) {
5887 qemu_start_incoming_migration(incoming
);
5888 } else if (autostart
) {
5898 len
= write(fds
[1], &status
, 1);
5899 if (len
== -1 && (errno
== EINTR
))
5906 TFR(fd
= open("/dev/null", O_RDWR
));
5912 pwd
= getpwnam(run_as
);
5914 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
5920 if (chroot(chroot_dir
) < 0) {
5921 fprintf(stderr
, "chroot failed\n");
5928 if (setgid(pwd
->pw_gid
) < 0) {
5929 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
5932 if (setuid(pwd
->pw_uid
) < 0) {
5933 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
5936 if (setuid(0) != -1) {
5937 fprintf(stderr
, "Dropping privileges failed\n");