4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
38 #include <sys/times.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
47 #if defined(__NetBSD__)
48 #include <net/if_tap.h>
51 #include <linux/if_tun.h>
53 #include <arpa/inet.h>
56 #include <sys/select.h>
59 #if defined(__FreeBSD__) || defined(__DragonFly__)
64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65 #include <freebsd/stdlib.h>
70 #include <linux/rtc.h>
71 #include <sys/prctl.h>
73 /* For the benefit of older linux systems which don't supply it,
74 we use a local copy of hpet.h. */
75 /* #include <linux/hpet.h> */
78 #include <linux/ppdev.h>
79 #include <linux/parport.h>
83 #include <sys/ethernet.h>
84 #include <sys/sockio.h>
85 #include <netinet/arp.h>
86 #include <netinet/in.h>
87 #include <netinet/in_systm.h>
88 #include <netinet/ip.h>
89 #include <netinet/ip_icmp.h> // must come after ip.h
90 #include <netinet/udp.h>
91 #include <netinet/tcp.h>
95 /* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
96 discussion about Solaris header problems */
97 extern int madvise(caddr_t
, size_t, int);
102 #if defined(__OpenBSD__)
106 #if defined(CONFIG_VDE)
107 #include <libvdeplug.h>
112 #include <mmsystem.h>
116 #if defined(__APPLE__) || defined(main)
118 int qemu_main(int argc
, char **argv
, char **envp
);
119 int main(int argc
, char **argv
)
121 return qemu_main(argc
, argv
, NULL
);
124 #define main qemu_main
126 #endif /* CONFIG_SDL */
130 #define main qemu_main
131 #endif /* CONFIG_COCOA */
134 #include "hw/boards.h"
136 #include "hw/pcmcia.h"
138 #include "hw/audiodev.h"
142 #include "hw/watchdog.h"
143 #include "hw/smbios.h"
152 #include "qemu-timer.h"
153 #include "qemu-char.h"
154 #include "cache-utils.h"
157 #include "audio/audio.h"
158 #include "migration.h"
161 #include "qemu-option.h"
162 #include "qemu-config.h"
166 #include "exec-all.h"
168 #include "qemu_socket.h"
170 #include "slirp/libslirp.h"
172 #include "qemu-queue.h"
175 //#define DEBUG_SLIRP
177 #define DEFAULT_RAM_SIZE 128
179 /* Maximum number of monitor devices */
180 #define MAX_MONITOR_DEVICES 10
182 static const char *data_dir
;
183 const char *bios_name
= NULL
;
184 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
185 to store the VM snapshots */
186 struct drivelist drives
= QTAILQ_HEAD_INITIALIZER(drives
);
187 struct driveoptlist driveopts
= QTAILQ_HEAD_INITIALIZER(driveopts
);
188 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
189 static DisplayState
*display_state
;
190 DisplayType display_type
= DT_DEFAULT
;
191 const char* keyboard_layout
= NULL
;
194 NICInfo nd_table
[MAX_NICS
];
197 static int rtc_utc
= 1;
198 static int rtc_date_offset
= -1; /* -1 means no change */
199 int vga_interface_type
= VGA_CIRRUS
;
201 int graphic_width
= 1024;
202 int graphic_height
= 768;
203 int graphic_depth
= 8;
205 int graphic_width
= 800;
206 int graphic_height
= 600;
207 int graphic_depth
= 15;
209 static int full_screen
= 0;
211 static int no_frame
= 0;
214 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
215 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
216 CharDriverState
*virtcon_hds
[MAX_VIRTIO_CONSOLES
];
218 int win2k_install_hack
= 0;
227 const char *vnc_display
;
228 int acpi_enabled
= 1;
234 int graphic_rotate
= 0;
235 uint8_t irq0override
= 1;
239 const char *watchdog
;
240 const char *option_rom
[MAX_OPTION_ROMS
];
242 int semihosting_enabled
= 0;
246 const char *qemu_name
;
248 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
249 unsigned int nb_prom_envs
= 0;
250 const char *prom_envs
[MAX_PROM_ENVS
];
255 uint64_t node_mem
[MAX_NODES
];
256 uint64_t node_cpumask
[MAX_NODES
];
258 static CPUState
*cur_cpu
;
259 static CPUState
*next_cpu
;
260 static int timer_alarm_pending
= 1;
261 /* Conversion factor from emulated instructions to virtual clock ticks. */
262 static int icount_time_shift
;
263 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
264 #define MAX_ICOUNT_SHIFT 10
265 /* Compensate for varying guest execution speed. */
266 static int64_t qemu_icount_bias
;
267 static QEMUTimer
*icount_rt_timer
;
268 static QEMUTimer
*icount_vm_timer
;
269 static QEMUTimer
*nographic_timer
;
271 uint8_t qemu_uuid
[16];
273 static QEMUBootSetHandler
*boot_set_handler
;
274 static void *boot_set_opaque
;
276 /***********************************************************/
277 /* x86 ISA bus support */
279 target_phys_addr_t isa_mem_base
= 0;
282 /***********************************************************/
283 void hw_error(const char *fmt
, ...)
289 fprintf(stderr
, "qemu: hardware error: ");
290 vfprintf(stderr
, fmt
, ap
);
291 fprintf(stderr
, "\n");
292 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
293 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
295 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
297 cpu_dump_state(env
, stderr
, fprintf
, 0);
304 static void set_proc_name(const char *s
)
306 #if defined(__linux__) && defined(PR_SET_NAME)
310 name
[sizeof(name
) - 1] = 0;
311 strncpy(name
, s
, sizeof(name
));
312 /* Could rewrite argv[0] too, but that's a bit more complicated.
313 This simple way is enough for `top'. */
314 prctl(PR_SET_NAME
, name
);
321 static QEMUBalloonEvent
*qemu_balloon_event
;
322 void *qemu_balloon_event_opaque
;
324 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
326 qemu_balloon_event
= func
;
327 qemu_balloon_event_opaque
= opaque
;
330 void qemu_balloon(ram_addr_t target
)
332 if (qemu_balloon_event
)
333 qemu_balloon_event(qemu_balloon_event_opaque
, target
);
336 ram_addr_t
qemu_balloon_status(void)
338 if (qemu_balloon_event
)
339 return qemu_balloon_event(qemu_balloon_event_opaque
, 0);
343 /***********************************************************/
346 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
347 static void *qemu_put_kbd_event_opaque
;
348 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
349 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
351 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
353 qemu_put_kbd_event_opaque
= opaque
;
354 qemu_put_kbd_event
= func
;
357 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
358 void *opaque
, int absolute
,
361 QEMUPutMouseEntry
*s
, *cursor
;
363 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
365 s
->qemu_put_mouse_event
= func
;
366 s
->qemu_put_mouse_event_opaque
= opaque
;
367 s
->qemu_put_mouse_event_absolute
= absolute
;
368 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
371 if (!qemu_put_mouse_event_head
) {
372 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
376 cursor
= qemu_put_mouse_event_head
;
377 while (cursor
->next
!= NULL
)
378 cursor
= cursor
->next
;
381 qemu_put_mouse_event_current
= s
;
386 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
388 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
390 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
393 cursor
= qemu_put_mouse_event_head
;
394 while (cursor
!= NULL
&& cursor
!= entry
) {
396 cursor
= cursor
->next
;
399 if (cursor
== NULL
) // does not exist or list empty
401 else if (prev
== NULL
) { // entry is head
402 qemu_put_mouse_event_head
= cursor
->next
;
403 if (qemu_put_mouse_event_current
== entry
)
404 qemu_put_mouse_event_current
= cursor
->next
;
405 qemu_free(entry
->qemu_put_mouse_event_name
);
410 prev
->next
= entry
->next
;
412 if (qemu_put_mouse_event_current
== entry
)
413 qemu_put_mouse_event_current
= prev
;
415 qemu_free(entry
->qemu_put_mouse_event_name
);
419 void kbd_put_keycode(int keycode
)
421 if (qemu_put_kbd_event
) {
422 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
426 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
428 QEMUPutMouseEvent
*mouse_event
;
429 void *mouse_event_opaque
;
432 if (!qemu_put_mouse_event_current
) {
437 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
439 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
442 if (graphic_rotate
) {
443 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
446 width
= graphic_width
- 1;
447 mouse_event(mouse_event_opaque
,
448 width
- dy
, dx
, dz
, buttons_state
);
450 mouse_event(mouse_event_opaque
,
451 dx
, dy
, dz
, buttons_state
);
455 int kbd_mouse_is_absolute(void)
457 if (!qemu_put_mouse_event_current
)
460 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
463 void do_info_mice(Monitor
*mon
)
465 QEMUPutMouseEntry
*cursor
;
468 if (!qemu_put_mouse_event_head
) {
469 monitor_printf(mon
, "No mouse devices connected\n");
473 monitor_printf(mon
, "Mouse devices available:\n");
474 cursor
= qemu_put_mouse_event_head
;
475 while (cursor
!= NULL
) {
476 monitor_printf(mon
, "%c Mouse #%d: %s\n",
477 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
478 index
, cursor
->qemu_put_mouse_event_name
);
480 cursor
= cursor
->next
;
484 void do_mouse_set(Monitor
*mon
, const QDict
*qdict
)
486 QEMUPutMouseEntry
*cursor
;
488 int index
= qdict_get_int(qdict
, "index");
490 if (!qemu_put_mouse_event_head
) {
491 monitor_printf(mon
, "No mouse devices connected\n");
495 cursor
= qemu_put_mouse_event_head
;
496 while (cursor
!= NULL
&& index
!= i
) {
498 cursor
= cursor
->next
;
502 qemu_put_mouse_event_current
= cursor
;
504 monitor_printf(mon
, "Mouse at given index not found\n");
507 /* compute with 96 bit intermediate result: (a*b)/c */
508 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
513 #ifdef HOST_WORDS_BIGENDIAN
523 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
524 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
527 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
531 /***********************************************************/
532 /* real time host monotonic timer */
536 static int64_t clock_freq
;
538 static void init_get_clock(void)
542 ret
= QueryPerformanceFrequency(&freq
);
544 fprintf(stderr
, "Could not calibrate ticks\n");
547 clock_freq
= freq
.QuadPart
;
550 static int64_t get_clock(void)
553 QueryPerformanceCounter(&ti
);
554 return muldiv64(ti
.QuadPart
, get_ticks_per_sec(), clock_freq
);
559 static int use_rt_clock
;
561 static void init_get_clock(void)
564 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
565 || defined(__DragonFly__)
568 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
575 static int64_t get_clock(void)
577 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
578 || defined(__DragonFly__)
581 clock_gettime(CLOCK_MONOTONIC
, &ts
);
582 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
586 /* XXX: using gettimeofday leads to problems if the date
587 changes, so it should be avoided. */
589 gettimeofday(&tv
, NULL
);
590 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
595 /* Return the virtual CPU time, based on the instruction counter. */
596 static int64_t cpu_get_icount(void)
599 CPUState
*env
= cpu_single_env
;;
600 icount
= qemu_icount
;
603 fprintf(stderr
, "Bad clock read\n");
604 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
606 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
609 /***********************************************************/
610 /* guest cycle counter */
612 typedef struct TimersState
{
613 int64_t cpu_ticks_prev
;
614 int64_t cpu_ticks_offset
;
615 int64_t cpu_clock_offset
;
616 int32_t cpu_ticks_enabled
;
620 TimersState timers_state
;
622 /* return the host CPU cycle counter and handle stop/restart */
623 int64_t cpu_get_ticks(void)
626 return cpu_get_icount();
628 if (!timers_state
.cpu_ticks_enabled
) {
629 return timers_state
.cpu_ticks_offset
;
632 ticks
= cpu_get_real_ticks();
633 if (timers_state
.cpu_ticks_prev
> ticks
) {
634 /* Note: non increasing ticks may happen if the host uses
636 timers_state
.cpu_ticks_offset
+= timers_state
.cpu_ticks_prev
- ticks
;
638 timers_state
.cpu_ticks_prev
= ticks
;
639 return ticks
+ timers_state
.cpu_ticks_offset
;
643 /* return the host CPU monotonic timer and handle stop/restart */
644 static int64_t cpu_get_clock(void)
647 if (!timers_state
.cpu_ticks_enabled
) {
648 return timers_state
.cpu_clock_offset
;
651 return ti
+ timers_state
.cpu_clock_offset
;
655 /* enable cpu_get_ticks() */
656 void cpu_enable_ticks(void)
658 if (!timers_state
.cpu_ticks_enabled
) {
659 timers_state
.cpu_ticks_offset
-= cpu_get_real_ticks();
660 timers_state
.cpu_clock_offset
-= get_clock();
661 timers_state
.cpu_ticks_enabled
= 1;
665 /* disable cpu_get_ticks() : the clock is stopped. You must not call
666 cpu_get_ticks() after that. */
667 void cpu_disable_ticks(void)
669 if (timers_state
.cpu_ticks_enabled
) {
670 timers_state
.cpu_ticks_offset
= cpu_get_ticks();
671 timers_state
.cpu_clock_offset
= cpu_get_clock();
672 timers_state
.cpu_ticks_enabled
= 0;
676 /***********************************************************/
679 #define QEMU_CLOCK_REALTIME 0
680 #define QEMU_CLOCK_VIRTUAL 1
684 /* XXX: add frequency */
692 struct QEMUTimer
*next
;
695 struct qemu_alarm_timer
{
699 int (*start
)(struct qemu_alarm_timer
*t
);
700 void (*stop
)(struct qemu_alarm_timer
*t
);
701 void (*rearm
)(struct qemu_alarm_timer
*t
);
705 #define ALARM_FLAG_DYNTICKS 0x1
706 #define ALARM_FLAG_EXPIRED 0x2
708 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
710 return t
&& (t
->flags
& ALARM_FLAG_DYNTICKS
);
713 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
715 if (!alarm_has_dynticks(t
))
721 /* TODO: MIN_TIMER_REARM_US should be optimized */
722 #define MIN_TIMER_REARM_US 250
724 static struct qemu_alarm_timer
*alarm_timer
;
728 struct qemu_alarm_win32
{
731 } alarm_win32_data
= {0, -1};
733 static int win32_start_timer(struct qemu_alarm_timer
*t
);
734 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
735 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
739 static int unix_start_timer(struct qemu_alarm_timer
*t
);
740 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
744 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
745 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
746 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
748 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
749 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
751 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
752 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
754 #endif /* __linux__ */
758 /* Correlation between real and virtual time is always going to be
759 fairly approximate, so ignore small variation.
760 When the guest is idle real and virtual time will be aligned in
762 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
764 static void icount_adjust(void)
769 static int64_t last_delta
;
770 /* If the VM is not running, then do nothing. */
774 cur_time
= cpu_get_clock();
775 cur_icount
= qemu_get_clock(vm_clock
);
776 delta
= cur_icount
- cur_time
;
777 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
779 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
780 && icount_time_shift
> 0) {
781 /* The guest is getting too far ahead. Slow time down. */
785 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
786 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
787 /* The guest is getting too far behind. Speed time up. */
791 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
794 static void icount_adjust_rt(void * opaque
)
796 qemu_mod_timer(icount_rt_timer
,
797 qemu_get_clock(rt_clock
) + 1000);
801 static void icount_adjust_vm(void * opaque
)
803 qemu_mod_timer(icount_vm_timer
,
804 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
808 static void init_icount_adjust(void)
810 /* Have both realtime and virtual time triggers for speed adjustment.
811 The realtime trigger catches emulated time passing too slowly,
812 the virtual time trigger catches emulated time passing too fast.
813 Realtime triggers occur even when idle, so use them less frequently
815 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
816 qemu_mod_timer(icount_rt_timer
,
817 qemu_get_clock(rt_clock
) + 1000);
818 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
819 qemu_mod_timer(icount_vm_timer
,
820 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
823 static struct qemu_alarm_timer alarm_timers
[] = {
826 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
827 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
828 /* HPET - if available - is preferred */
829 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
830 /* ...otherwise try RTC */
831 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
833 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
835 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
836 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
837 {"win32", 0, win32_start_timer
,
838 win32_stop_timer
, NULL
, &alarm_win32_data
},
843 static void show_available_alarms(void)
847 printf("Available alarm timers, in order of precedence:\n");
848 for (i
= 0; alarm_timers
[i
].name
; i
++)
849 printf("%s\n", alarm_timers
[i
].name
);
852 static void configure_alarms(char const *opt
)
856 int count
= ARRAY_SIZE(alarm_timers
) - 1;
859 struct qemu_alarm_timer tmp
;
861 if (!strcmp(opt
, "?")) {
862 show_available_alarms();
866 arg
= qemu_strdup(opt
);
868 /* Reorder the array */
869 name
= strtok(arg
, ",");
871 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
872 if (!strcmp(alarm_timers
[i
].name
, name
))
877 fprintf(stderr
, "Unknown clock %s\n", name
);
886 tmp
= alarm_timers
[i
];
887 alarm_timers
[i
] = alarm_timers
[cur
];
888 alarm_timers
[cur
] = tmp
;
892 name
= strtok(NULL
, ",");
898 /* Disable remaining timers */
899 for (i
= cur
; i
< count
; i
++)
900 alarm_timers
[i
].name
= NULL
;
902 show_available_alarms();
910 static QEMUTimer
*active_timers
[2];
912 static QEMUClock
*qemu_new_clock(int type
)
915 clock
= qemu_mallocz(sizeof(QEMUClock
));
920 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
924 ts
= qemu_mallocz(sizeof(QEMUTimer
));
931 void qemu_free_timer(QEMUTimer
*ts
)
936 /* stop a timer, but do not dealloc it */
937 void qemu_del_timer(QEMUTimer
*ts
)
941 /* NOTE: this code must be signal safe because
942 qemu_timer_expired() can be called from a signal. */
943 pt
= &active_timers
[ts
->clock
->type
];
956 /* modify the current timer so that it will be fired when current_time
957 >= expire_time. The corresponding callback will be called. */
958 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
964 /* add the timer in the sorted list */
965 /* NOTE: this code must be signal safe because
966 qemu_timer_expired() can be called from a signal. */
967 pt
= &active_timers
[ts
->clock
->type
];
972 if (t
->expire_time
> expire_time
)
976 ts
->expire_time
= expire_time
;
980 /* Rearm if necessary */
981 if (pt
== &active_timers
[ts
->clock
->type
]) {
982 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
983 qemu_rearm_alarm_timer(alarm_timer
);
985 /* Interrupt execution to force deadline recalculation. */
991 int qemu_timer_pending(QEMUTimer
*ts
)
994 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1001 int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1005 return (timer_head
->expire_time
<= current_time
);
1008 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1014 if (!ts
|| ts
->expire_time
> current_time
)
1016 /* remove timer from the list before calling the callback */
1017 *ptimer_head
= ts
->next
;
1020 /* run the callback (the timer list can be modified) */
1025 int64_t qemu_get_clock(QEMUClock
*clock
)
1027 switch(clock
->type
) {
1028 case QEMU_CLOCK_REALTIME
:
1029 return get_clock() / 1000000;
1031 case QEMU_CLOCK_VIRTUAL
:
1033 return cpu_get_icount();
1035 return cpu_get_clock();
1040 static void init_clocks(void)
1043 rt_clock
= qemu_new_clock(QEMU_CLOCK_REALTIME
);
1044 vm_clock
= qemu_new_clock(QEMU_CLOCK_VIRTUAL
);
1048 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1050 uint64_t expire_time
;
1052 if (qemu_timer_pending(ts
)) {
1053 expire_time
= ts
->expire_time
;
1057 qemu_put_be64(f
, expire_time
);
1060 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1062 uint64_t expire_time
;
1064 expire_time
= qemu_get_be64(f
);
1065 if (expire_time
!= -1) {
1066 qemu_mod_timer(ts
, expire_time
);
1072 static const VMStateDescription vmstate_timers
= {
1075 .minimum_version_id
= 1,
1076 .minimum_version_id_old
= 1,
1077 .fields
= (VMStateField
[]) {
1078 VMSTATE_INT64(cpu_ticks_offset
, TimersState
),
1079 VMSTATE_INT64(dummy
, TimersState
),
1080 VMSTATE_INT64_V(cpu_clock_offset
, TimersState
, 2),
1081 VMSTATE_END_OF_LIST()
1085 static void qemu_event_increment(void);
1088 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1089 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1092 static void host_alarm_handler(int host_signum
)
1096 #define DISP_FREQ 1000
1098 static int64_t delta_min
= INT64_MAX
;
1099 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1101 ti
= qemu_get_clock(vm_clock
);
1102 if (last_clock
!= 0) {
1103 delta
= ti
- last_clock
;
1104 if (delta
< delta_min
)
1106 if (delta
> delta_max
)
1109 if (++count
== DISP_FREQ
) {
1110 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1111 muldiv64(delta_min
, 1000000, get_ticks_per_sec()),
1112 muldiv64(delta_max
, 1000000, get_ticks_per_sec()),
1113 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, get_ticks_per_sec()),
1114 (double)get_ticks_per_sec() / ((double)delta_cum
/ DISP_FREQ
));
1116 delta_min
= INT64_MAX
;
1124 if (alarm_has_dynticks(alarm_timer
) ||
1126 qemu_timer_expired(active_timers
[QEMU_CLOCK_VIRTUAL
],
1127 qemu_get_clock(vm_clock
))) ||
1128 qemu_timer_expired(active_timers
[QEMU_CLOCK_REALTIME
],
1129 qemu_get_clock(rt_clock
))) {
1130 qemu_event_increment();
1131 if (alarm_timer
) alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1133 #ifndef CONFIG_IOTHREAD
1135 /* stop the currently executing cpu because a timer occured */
1139 timer_alarm_pending
= 1;
1140 qemu_notify_event();
1144 static int64_t qemu_next_deadline(void)
1148 if (active_timers
[QEMU_CLOCK_VIRTUAL
]) {
1149 delta
= active_timers
[QEMU_CLOCK_VIRTUAL
]->expire_time
-
1150 qemu_get_clock(vm_clock
);
1152 /* To avoid problems with overflow limit this to 2^32. */
1162 #if defined(__linux__)
1163 static uint64_t qemu_next_deadline_dyntick(void)
1171 delta
= (qemu_next_deadline() + 999) / 1000;
1173 if (active_timers
[QEMU_CLOCK_REALTIME
]) {
1174 rtdelta
= (active_timers
[QEMU_CLOCK_REALTIME
]->expire_time
-
1175 qemu_get_clock(rt_clock
))*1000;
1176 if (rtdelta
< delta
)
1180 if (delta
< MIN_TIMER_REARM_US
)
1181 delta
= MIN_TIMER_REARM_US
;
1189 /* Sets a specific flag */
1190 static int fcntl_setfl(int fd
, int flag
)
1194 flags
= fcntl(fd
, F_GETFL
);
1198 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1204 #if defined(__linux__)
1206 #define RTC_FREQ 1024
1208 static void enable_sigio_timer(int fd
)
1210 struct sigaction act
;
1213 sigfillset(&act
.sa_mask
);
1215 act
.sa_handler
= host_alarm_handler
;
1217 sigaction(SIGIO
, &act
, NULL
);
1218 fcntl_setfl(fd
, O_ASYNC
);
1219 fcntl(fd
, F_SETOWN
, getpid());
1222 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1224 struct hpet_info info
;
1227 fd
= open("/dev/hpet", O_RDONLY
);
1232 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1234 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1235 "error, but for better emulation accuracy type:\n"
1236 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1240 /* Check capabilities */
1241 r
= ioctl(fd
, HPET_INFO
, &info
);
1245 /* Enable periodic mode */
1246 r
= ioctl(fd
, HPET_EPI
, 0);
1247 if (info
.hi_flags
&& (r
< 0))
1250 /* Enable interrupt */
1251 r
= ioctl(fd
, HPET_IE_ON
, 0);
1255 enable_sigio_timer(fd
);
1256 t
->priv
= (void *)(long)fd
;
1264 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1266 int fd
= (long)t
->priv
;
1271 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1274 unsigned long current_rtc_freq
= 0;
1276 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1279 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1280 if (current_rtc_freq
!= RTC_FREQ
&&
1281 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1282 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1283 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1284 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1287 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1293 enable_sigio_timer(rtc_fd
);
1295 t
->priv
= (void *)(long)rtc_fd
;
1300 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1302 int rtc_fd
= (long)t
->priv
;
1307 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1311 struct sigaction act
;
1313 sigfillset(&act
.sa_mask
);
1315 act
.sa_handler
= host_alarm_handler
;
1317 sigaction(SIGALRM
, &act
, NULL
);
1320 * Initialize ev struct to 0 to avoid valgrind complaining
1321 * about uninitialized data in timer_create call
1323 memset(&ev
, 0, sizeof(ev
));
1324 ev
.sigev_value
.sival_int
= 0;
1325 ev
.sigev_notify
= SIGEV_SIGNAL
;
1326 ev
.sigev_signo
= SIGALRM
;
1328 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1329 perror("timer_create");
1331 /* disable dynticks */
1332 fprintf(stderr
, "Dynamic Ticks disabled\n");
1337 t
->priv
= (void *)(long)host_timer
;
1342 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1344 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1346 timer_delete(host_timer
);
1349 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1351 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1352 struct itimerspec timeout
;
1353 int64_t nearest_delta_us
= INT64_MAX
;
1356 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1357 !active_timers
[QEMU_CLOCK_VIRTUAL
])
1360 nearest_delta_us
= qemu_next_deadline_dyntick();
1362 /* check whether a timer is already running */
1363 if (timer_gettime(host_timer
, &timeout
)) {
1365 fprintf(stderr
, "Internal timer error: aborting\n");
1368 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1369 if (current_us
&& current_us
<= nearest_delta_us
)
1372 timeout
.it_interval
.tv_sec
= 0;
1373 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1374 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1375 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1376 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1378 fprintf(stderr
, "Internal timer error: aborting\n");
1383 #endif /* defined(__linux__) */
1385 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1387 struct sigaction act
;
1388 struct itimerval itv
;
1392 sigfillset(&act
.sa_mask
);
1394 act
.sa_handler
= host_alarm_handler
;
1396 sigaction(SIGALRM
, &act
, NULL
);
1398 itv
.it_interval
.tv_sec
= 0;
1399 /* for i386 kernel 2.6 to get 1 ms */
1400 itv
.it_interval
.tv_usec
= 999;
1401 itv
.it_value
.tv_sec
= 0;
1402 itv
.it_value
.tv_usec
= 10 * 1000;
1404 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1411 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1413 struct itimerval itv
;
1415 memset(&itv
, 0, sizeof(itv
));
1416 setitimer(ITIMER_REAL
, &itv
, NULL
);
1419 #endif /* !defined(_WIN32) */
1424 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1427 struct qemu_alarm_win32
*data
= t
->priv
;
1430 memset(&tc
, 0, sizeof(tc
));
1431 timeGetDevCaps(&tc
, sizeof(tc
));
1433 if (data
->period
< tc
.wPeriodMin
)
1434 data
->period
= tc
.wPeriodMin
;
1436 timeBeginPeriod(data
->period
);
1438 flags
= TIME_CALLBACK_FUNCTION
;
1439 if (alarm_has_dynticks(t
))
1440 flags
|= TIME_ONESHOT
;
1442 flags
|= TIME_PERIODIC
;
1444 data
->timerId
= timeSetEvent(1, // interval (ms)
1445 data
->period
, // resolution
1446 host_alarm_handler
, // function
1447 (DWORD
)t
, // parameter
1450 if (!data
->timerId
) {
1451 fprintf(stderr
, "Failed to initialize win32 alarm timer: %ld\n",
1453 timeEndPeriod(data
->period
);
1460 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1462 struct qemu_alarm_win32
*data
= t
->priv
;
1464 timeKillEvent(data
->timerId
);
1465 timeEndPeriod(data
->period
);
1468 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1470 struct qemu_alarm_win32
*data
= t
->priv
;
1472 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1473 !active_timers
[QEMU_CLOCK_VIRTUAL
])
1476 timeKillEvent(data
->timerId
);
1478 data
->timerId
= timeSetEvent(1,
1482 TIME_ONESHOT
| TIME_PERIODIC
);
1484 if (!data
->timerId
) {
1485 fprintf(stderr
, "Failed to re-arm win32 alarm timer %ld\n",
1488 timeEndPeriod(data
->period
);
1495 static int init_timer_alarm(void)
1497 struct qemu_alarm_timer
*t
= NULL
;
1500 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1501 t
= &alarm_timers
[i
];
1521 static void quit_timers(void)
1523 alarm_timer
->stop(alarm_timer
);
1527 /***********************************************************/
1528 /* host time/date access */
1529 void qemu_get_timedate(struct tm
*tm
, int offset
)
1536 if (rtc_date_offset
== -1) {
1540 ret
= localtime(&ti
);
1542 ti
-= rtc_date_offset
;
1546 memcpy(tm
, ret
, sizeof(struct tm
));
1549 int qemu_timedate_diff(struct tm
*tm
)
1553 if (rtc_date_offset
== -1)
1555 seconds
= mktimegm(tm
);
1557 seconds
= mktime(tm
);
1559 seconds
= mktimegm(tm
) + rtc_date_offset
;
1561 return seconds
- time(NULL
);
1565 static void socket_cleanup(void)
1570 static int socket_init(void)
1575 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1577 err
= WSAGetLastError();
1578 fprintf(stderr
, "WSAStartup: %d\n", err
);
1581 atexit(socket_cleanup
);
1586 /***********************************************************/
1587 /* Bluetooth support */
1590 static struct HCIInfo
*hci_table
[MAX_NICS
];
1592 static struct bt_vlan_s
{
1593 struct bt_scatternet_s net
;
1595 struct bt_vlan_s
*next
;
1598 /* find or alloc a new bluetooth "VLAN" */
1599 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1601 struct bt_vlan_s
**pvlan
, *vlan
;
1602 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1606 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1608 pvlan
= &first_bt_vlan
;
1609 while (*pvlan
!= NULL
)
1610 pvlan
= &(*pvlan
)->next
;
1615 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1619 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1624 static struct HCIInfo null_hci
= {
1625 .cmd_send
= null_hci_send
,
1626 .sco_send
= null_hci_send
,
1627 .acl_send
= null_hci_send
,
1628 .bdaddr_set
= null_hci_addr_set
,
1631 struct HCIInfo
*qemu_next_hci(void)
1633 if (cur_hci
== nb_hcis
)
1636 return hci_table
[cur_hci
++];
1639 static struct HCIInfo
*hci_init(const char *str
)
1642 struct bt_scatternet_s
*vlan
= 0;
1644 if (!strcmp(str
, "null"))
1647 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
1649 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
1650 else if (!strncmp(str
, "hci", 3)) {
1653 if (!strncmp(str
+ 3, ",vlan=", 6)) {
1654 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
1659 vlan
= qemu_find_bt_vlan(0);
1661 return bt_new_hci(vlan
);
1664 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
1669 static int bt_hci_parse(const char *str
)
1671 struct HCIInfo
*hci
;
1674 if (nb_hcis
>= MAX_NICS
) {
1675 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
1679 hci
= hci_init(str
);
1688 bdaddr
.b
[5] = 0x56 + nb_hcis
;
1689 hci
->bdaddr_set(hci
, bdaddr
.b
);
1691 hci_table
[nb_hcis
++] = hci
;
1696 static void bt_vhci_add(int vlan_id
)
1698 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
1701 fprintf(stderr
, "qemu: warning: adding a VHCI to "
1702 "an empty scatternet %i\n", vlan_id
);
1704 bt_vhci_init(bt_new_hci(vlan
));
1707 static struct bt_device_s
*bt_device_add(const char *opt
)
1709 struct bt_scatternet_s
*vlan
;
1711 char *endp
= strstr(opt
, ",vlan=");
1712 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
1715 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
1718 vlan_id
= strtol(endp
+ 6, &endp
, 0);
1720 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
1725 vlan
= qemu_find_bt_vlan(vlan_id
);
1728 fprintf(stderr
, "qemu: warning: adding a slave device to "
1729 "an empty scatternet %i\n", vlan_id
);
1731 if (!strcmp(devname
, "keyboard"))
1732 return bt_keyboard_init(vlan
);
1734 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
1738 static int bt_parse(const char *opt
)
1740 const char *endp
, *p
;
1743 if (strstart(opt
, "hci", &endp
)) {
1744 if (!*endp
|| *endp
== ',') {
1746 if (!strstart(endp
, ",vlan=", 0))
1749 return bt_hci_parse(opt
);
1751 } else if (strstart(opt
, "vhci", &endp
)) {
1752 if (!*endp
|| *endp
== ',') {
1754 if (strstart(endp
, ",vlan=", &p
)) {
1755 vlan
= strtol(p
, (char **) &endp
, 0);
1757 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
1761 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
1770 } else if (strstart(opt
, "device:", &endp
))
1771 return !bt_device_add(endp
);
1773 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
1777 /***********************************************************/
1778 /* QEMU Block devices */
1780 #define HD_ALIAS "index=%d,media=disk"
1781 #define CDROM_ALIAS "index=2,media=cdrom"
1782 #define FD_ALIAS "index=%d,if=floppy"
1783 #define PFLASH_ALIAS "if=pflash"
1784 #define MTD_ALIAS "if=mtd"
1785 #define SD_ALIAS "index=0,if=sd"
1787 QemuOpts
*drive_add(const char *file
, const char *fmt
, ...)
1794 vsnprintf(optstr
, sizeof(optstr
), fmt
, ap
);
1797 opts
= qemu_opts_parse(&qemu_drive_opts
, optstr
, NULL
);
1799 fprintf(stderr
, "%s: huh? duplicate? (%s)\n",
1800 __FUNCTION__
, optstr
);
1804 qemu_opt_set(opts
, "file", file
);
1808 DriveInfo
*drive_get(BlockInterfaceType type
, int bus
, int unit
)
1812 /* seek interface, bus and unit */
1814 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1815 if (dinfo
->type
== type
&&
1816 dinfo
->bus
== bus
&&
1817 dinfo
->unit
== unit
)
1824 DriveInfo
*drive_get_by_id(const char *id
)
1828 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1829 if (strcmp(id
, dinfo
->id
))
1836 int drive_get_max_bus(BlockInterfaceType type
)
1842 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1843 if(dinfo
->type
== type
&&
1844 dinfo
->bus
> max_bus
)
1845 max_bus
= dinfo
->bus
;
1850 const char *drive_get_serial(BlockDriverState
*bdrv
)
1854 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1855 if (dinfo
->bdrv
== bdrv
)
1856 return dinfo
->serial
;
1862 BlockInterfaceErrorAction
drive_get_onerror(BlockDriverState
*bdrv
)
1866 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1867 if (dinfo
->bdrv
== bdrv
)
1868 return dinfo
->onerror
;
1871 return BLOCK_ERR_STOP_ENOSPC
;
1874 static void bdrv_format_print(void *opaque
, const char *name
)
1876 fprintf(stderr
, " %s", name
);
1879 void drive_uninit(BlockDriverState
*bdrv
)
1883 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1884 if (dinfo
->bdrv
!= bdrv
)
1886 qemu_opts_del(dinfo
->opts
);
1887 QTAILQ_REMOVE(&drives
, dinfo
, next
);
1893 DriveInfo
*drive_init(QemuOpts
*opts
, void *opaque
,
1897 const char *file
= NULL
;
1900 const char *mediastr
= "";
1901 BlockInterfaceType type
;
1902 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
1903 int bus_id
, unit_id
;
1904 int cyls
, heads
, secs
, translation
;
1905 BlockDriver
*drv
= NULL
;
1906 QEMUMachine
*machine
= opaque
;
1911 int bdrv_flags
, onerror
;
1912 const char *devaddr
;
1918 translation
= BIOS_ATA_TRANSLATION_AUTO
;
1921 if (machine
&& machine
->use_scsi
) {
1923 max_devs
= MAX_SCSI_DEVS
;
1924 pstrcpy(devname
, sizeof(devname
), "scsi");
1927 max_devs
= MAX_IDE_DEVS
;
1928 pstrcpy(devname
, sizeof(devname
), "ide");
1932 /* extract parameters */
1933 bus_id
= qemu_opt_get_number(opts
, "bus", 0);
1934 unit_id
= qemu_opt_get_number(opts
, "unit", -1);
1935 index
= qemu_opt_get_number(opts
, "index", -1);
1937 cyls
= qemu_opt_get_number(opts
, "cyls", 0);
1938 heads
= qemu_opt_get_number(opts
, "heads", 0);
1939 secs
= qemu_opt_get_number(opts
, "secs", 0);
1941 snapshot
= qemu_opt_get_bool(opts
, "snapshot", 0);
1943 file
= qemu_opt_get(opts
, "file");
1944 serial
= qemu_opt_get(opts
, "serial");
1946 if ((buf
= qemu_opt_get(opts
, "if")) != NULL
) {
1947 pstrcpy(devname
, sizeof(devname
), buf
);
1948 if (!strcmp(buf
, "ide")) {
1950 max_devs
= MAX_IDE_DEVS
;
1951 } else if (!strcmp(buf
, "scsi")) {
1953 max_devs
= MAX_SCSI_DEVS
;
1954 } else if (!strcmp(buf
, "floppy")) {
1957 } else if (!strcmp(buf
, "pflash")) {
1960 } else if (!strcmp(buf
, "mtd")) {
1963 } else if (!strcmp(buf
, "sd")) {
1966 } else if (!strcmp(buf
, "virtio")) {
1969 } else if (!strcmp(buf
, "xen")) {
1972 } else if (!strcmp(buf
, "none")) {
1976 fprintf(stderr
, "qemu: unsupported bus type '%s'\n", buf
);
1981 if (cyls
|| heads
|| secs
) {
1982 if (cyls
< 1 || cyls
> 16383) {
1983 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", buf
);
1986 if (heads
< 1 || heads
> 16) {
1987 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", buf
);
1990 if (secs
< 1 || secs
> 63) {
1991 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", buf
);
1996 if ((buf
= qemu_opt_get(opts
, "trans")) != NULL
) {
1999 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2003 if (!strcmp(buf
, "none"))
2004 translation
= BIOS_ATA_TRANSLATION_NONE
;
2005 else if (!strcmp(buf
, "lba"))
2006 translation
= BIOS_ATA_TRANSLATION_LBA
;
2007 else if (!strcmp(buf
, "auto"))
2008 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2010 fprintf(stderr
, "qemu: '%s' invalid translation type\n", buf
);
2015 if ((buf
= qemu_opt_get(opts
, "media")) != NULL
) {
2016 if (!strcmp(buf
, "disk")) {
2018 } else if (!strcmp(buf
, "cdrom")) {
2019 if (cyls
|| secs
|| heads
) {
2021 "qemu: '%s' invalid physical CHS format\n", buf
);
2024 media
= MEDIA_CDROM
;
2026 fprintf(stderr
, "qemu: '%s' invalid media\n", buf
);
2031 if ((buf
= qemu_opt_get(opts
, "cache")) != NULL
) {
2032 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2034 else if (!strcmp(buf
, "writethrough"))
2036 else if (!strcmp(buf
, "writeback"))
2039 fprintf(stderr
, "qemu: invalid cache option\n");
2044 #ifdef CONFIG_LINUX_AIO
2045 if ((buf
= qemu_opt_get(opts
, "aio")) != NULL
) {
2046 if (!strcmp(buf
, "threads"))
2048 else if (!strcmp(buf
, "native"))
2051 fprintf(stderr
, "qemu: invalid aio option\n");
2057 if ((buf
= qemu_opt_get(opts
, "format")) != NULL
) {
2058 if (strcmp(buf
, "?") == 0) {
2059 fprintf(stderr
, "qemu: Supported formats:");
2060 bdrv_iterate_format(bdrv_format_print
, NULL
);
2061 fprintf(stderr
, "\n");
2064 drv
= bdrv_find_format(buf
);
2066 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2071 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2072 if ((buf
= qemu_opt_get(opts
, "werror")) != NULL
) {
2073 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2074 fprintf(stderr
, "werror is no supported by this format\n");
2077 if (!strcmp(buf
, "ignore"))
2078 onerror
= BLOCK_ERR_IGNORE
;
2079 else if (!strcmp(buf
, "enospc"))
2080 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2081 else if (!strcmp(buf
, "stop"))
2082 onerror
= BLOCK_ERR_STOP_ANY
;
2083 else if (!strcmp(buf
, "report"))
2084 onerror
= BLOCK_ERR_REPORT
;
2086 fprintf(stderr
, "qemu: '%s' invalid write error action\n", buf
);
2091 if ((devaddr
= qemu_opt_get(opts
, "addr")) != NULL
) {
2092 if (type
!= IF_VIRTIO
) {
2093 fprintf(stderr
, "addr is not supported\n");
2098 /* compute bus and unit according index */
2101 if (bus_id
!= 0 || unit_id
!= -1) {
2103 "qemu: index cannot be used with bus and unit\n");
2111 unit_id
= index
% max_devs
;
2112 bus_id
= index
/ max_devs
;
2116 /* if user doesn't specify a unit_id,
2117 * try to find the first free
2120 if (unit_id
== -1) {
2122 while (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2124 if (max_devs
&& unit_id
>= max_devs
) {
2125 unit_id
-= max_devs
;
2133 if (max_devs
&& unit_id
>= max_devs
) {
2134 fprintf(stderr
, "qemu: unit %d too big (max is %d)\n",
2135 unit_id
, max_devs
- 1);
2140 * ignore multiple definitions
2143 if (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2150 dinfo
= qemu_mallocz(sizeof(*dinfo
));
2151 if ((buf
= qemu_opts_id(opts
)) != NULL
) {
2152 dinfo
->id
= qemu_strdup(buf
);
2154 /* no id supplied -> create one */
2155 dinfo
->id
= qemu_mallocz(32);
2156 if (type
== IF_IDE
|| type
== IF_SCSI
)
2157 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2159 snprintf(dinfo
->id
, 32, "%s%i%s%i",
2160 devname
, bus_id
, mediastr
, unit_id
);
2162 snprintf(dinfo
->id
, 32, "%s%s%i",
2163 devname
, mediastr
, unit_id
);
2165 dinfo
->bdrv
= bdrv_new(dinfo
->id
);
2166 dinfo
->devaddr
= devaddr
;
2168 dinfo
->bus
= bus_id
;
2169 dinfo
->unit
= unit_id
;
2170 dinfo
->onerror
= onerror
;
2173 strncpy(dinfo
->serial
, serial
, sizeof(serial
));
2174 QTAILQ_INSERT_TAIL(&drives
, dinfo
, next
);
2184 bdrv_set_geometry_hint(dinfo
->bdrv
, cyls
, heads
, secs
);
2185 bdrv_set_translation_hint(dinfo
->bdrv
, translation
);
2189 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_CDROM
);
2194 /* FIXME: This isn't really a floppy, but it's a reasonable
2197 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_FLOPPY
);
2203 /* add virtio block device */
2204 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
2205 qemu_opt_set(opts
, "driver", "virtio-blk-pci");
2206 qemu_opt_set(opts
, "drive", dinfo
->id
);
2208 qemu_opt_set(opts
, "addr", devaddr
);
2219 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2220 cache
= 2; /* always use write-back with snapshot */
2222 if (cache
== 0) /* no caching */
2223 bdrv_flags
|= BDRV_O_NOCACHE
;
2224 else if (cache
== 2) /* write-back */
2225 bdrv_flags
|= BDRV_O_CACHE_WB
;
2228 bdrv_flags
|= BDRV_O_NATIVE_AIO
;
2230 bdrv_flags
&= ~BDRV_O_NATIVE_AIO
;
2233 if (bdrv_open2(dinfo
->bdrv
, file
, bdrv_flags
, drv
) < 0) {
2234 fprintf(stderr
, "qemu: could not open disk image %s\n",
2239 if (bdrv_key_required(dinfo
->bdrv
))
2245 static int drive_init_func(QemuOpts
*opts
, void *opaque
)
2247 QEMUMachine
*machine
= opaque
;
2248 int fatal_error
= 0;
2250 if (drive_init(opts
, machine
, &fatal_error
) == NULL
) {
2257 static int drive_enable_snapshot(QemuOpts
*opts
, void *opaque
)
2259 if (NULL
== qemu_opt_get(opts
, "snapshot")) {
2260 qemu_opt_set(opts
, "snapshot", "on");
2265 void qemu_register_boot_set(QEMUBootSetHandler
*func
, void *opaque
)
2267 boot_set_handler
= func
;
2268 boot_set_opaque
= opaque
;
2271 int qemu_boot_set(const char *boot_devices
)
2273 if (!boot_set_handler
) {
2276 return boot_set_handler(boot_set_opaque
, boot_devices
);
2279 static int parse_bootdevices(char *devices
)
2281 /* We just do some generic consistency checks */
2285 for (p
= devices
; *p
!= '\0'; p
++) {
2286 /* Allowed boot devices are:
2287 * a-b: floppy disk drives
2288 * c-f: IDE disk drives
2289 * g-m: machine implementation dependant drives
2290 * n-p: network devices
2291 * It's up to each machine implementation to check if the given boot
2292 * devices match the actual hardware implementation and firmware
2295 if (*p
< 'a' || *p
> 'p') {
2296 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
2299 if (bitmap
& (1 << (*p
- 'a'))) {
2300 fprintf(stderr
, "Boot device '%c' was given twice\n", *p
);
2303 bitmap
|= 1 << (*p
- 'a');
2308 static void restore_boot_devices(void *opaque
)
2310 char *standard_boot_devices
= opaque
;
2312 qemu_boot_set(standard_boot_devices
);
2314 qemu_unregister_reset(restore_boot_devices
, standard_boot_devices
);
2315 qemu_free(standard_boot_devices
);
2318 static void numa_add(const char *optarg
)
2322 unsigned long long value
, endvalue
;
2325 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2326 if (!strcmp(option
, "node")) {
2327 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2328 nodenr
= nb_numa_nodes
;
2330 nodenr
= strtoull(option
, NULL
, 10);
2333 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2334 node_mem
[nodenr
] = 0;
2336 value
= strtoull(option
, &endptr
, 0);
2338 case 0: case 'M': case 'm':
2345 node_mem
[nodenr
] = value
;
2347 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2348 node_cpumask
[nodenr
] = 0;
2350 value
= strtoull(option
, &endptr
, 10);
2353 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2355 if (*endptr
== '-') {
2356 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2357 if (endvalue
>= 63) {
2360 "only 63 CPUs in NUMA mode supported.\n");
2362 value
= (1 << (endvalue
+ 1)) - (1 << value
);
2367 node_cpumask
[nodenr
] = value
;
2374 static void smp_parse(const char *optarg
)
2376 int smp
, sockets
= 0, threads
= 0, cores
= 0;
2380 smp
= strtoul(optarg
, &endptr
, 10);
2381 if (endptr
!= optarg
) {
2382 if (*endptr
== ',') {
2386 if (get_param_value(option
, 128, "sockets", endptr
) != 0)
2387 sockets
= strtoull(option
, NULL
, 10);
2388 if (get_param_value(option
, 128, "cores", endptr
) != 0)
2389 cores
= strtoull(option
, NULL
, 10);
2390 if (get_param_value(option
, 128, "threads", endptr
) != 0)
2391 threads
= strtoull(option
, NULL
, 10);
2392 if (get_param_value(option
, 128, "maxcpus", endptr
) != 0)
2393 max_cpus
= strtoull(option
, NULL
, 10);
2395 /* compute missing values, prefer sockets over cores over threads */
2396 if (smp
== 0 || sockets
== 0) {
2397 sockets
= sockets
> 0 ? sockets
: 1;
2398 cores
= cores
> 0 ? cores
: 1;
2399 threads
= threads
> 0 ? threads
: 1;
2401 smp
= cores
* threads
* sockets
;
2403 sockets
= smp
/ (cores
* threads
);
2407 threads
= threads
> 0 ? threads
: 1;
2408 cores
= smp
/ (sockets
* threads
);
2411 sockets
= smp
/ (cores
* threads
);
2413 threads
= smp
/ (cores
* sockets
);
2418 smp_cores
= cores
> 0 ? cores
: 1;
2419 smp_threads
= threads
> 0 ? threads
: 1;
2421 max_cpus
= smp_cpus
;
2424 /***********************************************************/
2427 static void usb_msd_password_cb(void *opaque
, int err
)
2429 USBDevice
*dev
= opaque
;
2432 usb_device_attach(dev
);
2434 dev
->info
->handle_destroy(dev
);
2443 .qdev
= "QEMU USB Mouse",
2446 .qdev
= "QEMU USB Tablet",
2449 .qdev
= "QEMU USB Keyboard",
2451 .name
= "wacom-tablet",
2452 .qdev
= "QEMU PenPartner Tablet",
2456 static int usb_device_add(const char *devname
, int is_hotplug
)
2459 USBBus
*bus
= usb_bus_find(-1 /* any */);
2460 USBDevice
*dev
= NULL
;
2466 /* simple devices which don't need extra care */
2467 for (i
= 0; i
< ARRAY_SIZE(usbdevs
); i
++) {
2468 if (strcmp(devname
, usbdevs
[i
].name
) != 0)
2470 dev
= usb_create_simple(bus
, usbdevs
[i
].qdev
);
2474 /* the other ones */
2475 if (strstart(devname
, "host:", &p
)) {
2476 dev
= usb_host_device_open(p
);
2477 } else if (strstart(devname
, "disk:", &p
)) {
2478 BlockDriverState
*bs
;
2480 dev
= usb_msd_init(p
);
2483 bs
= usb_msd_get_bdrv(dev
);
2484 if (bdrv_key_required(bs
)) {
2487 monitor_read_bdrv_key_start(cur_mon
, bs
, usb_msd_password_cb
,
2492 } else if (strstart(devname
, "serial:", &p
)) {
2493 dev
= usb_serial_init(p
);
2494 #ifdef CONFIG_BRLAPI
2495 } else if (!strcmp(devname
, "braille")) {
2496 dev
= usb_baum_init();
2498 } else if (strstart(devname
, "net:", &p
)) {
2501 if (net_client_init(NULL
, "nic", p
) < 0)
2503 nd_table
[nic
].model
= "usb";
2504 dev
= usb_net_init(&nd_table
[nic
]);
2505 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2506 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2507 bt_new_hci(qemu_find_bt_vlan(0)));
2518 static int usb_device_del(const char *devname
)
2523 if (strstart(devname
, "host:", &p
))
2524 return usb_host_device_close(p
);
2529 p
= strchr(devname
, '.');
2532 bus_num
= strtoul(devname
, NULL
, 0);
2533 addr
= strtoul(p
+ 1, NULL
, 0);
2535 return usb_device_delete_addr(bus_num
, addr
);
2538 static int usb_parse(const char *cmdline
)
2540 return usb_device_add(cmdline
, 0);
2543 void do_usb_add(Monitor
*mon
, const QDict
*qdict
)
2545 usb_device_add(qdict_get_str(qdict
, "devname"), 1);
2548 void do_usb_del(Monitor
*mon
, const QDict
*qdict
)
2550 usb_device_del(qdict_get_str(qdict
, "devname"));
2553 /***********************************************************/
2554 /* PCMCIA/Cardbus */
2556 static struct pcmcia_socket_entry_s
{
2557 PCMCIASocket
*socket
;
2558 struct pcmcia_socket_entry_s
*next
;
2559 } *pcmcia_sockets
= 0;
2561 void pcmcia_socket_register(PCMCIASocket
*socket
)
2563 struct pcmcia_socket_entry_s
*entry
;
2565 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2566 entry
->socket
= socket
;
2567 entry
->next
= pcmcia_sockets
;
2568 pcmcia_sockets
= entry
;
2571 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2573 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2575 ptr
= &pcmcia_sockets
;
2576 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2577 if (entry
->socket
== socket
) {
2583 void pcmcia_info(Monitor
*mon
)
2585 struct pcmcia_socket_entry_s
*iter
;
2587 if (!pcmcia_sockets
)
2588 monitor_printf(mon
, "No PCMCIA sockets\n");
2590 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2591 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2592 iter
->socket
->attached
? iter
->socket
->card_string
:
2596 /***********************************************************/
2597 /* register display */
2599 struct DisplayAllocator default_allocator
= {
2600 defaultallocator_create_displaysurface
,
2601 defaultallocator_resize_displaysurface
,
2602 defaultallocator_free_displaysurface
2605 void register_displaystate(DisplayState
*ds
)
2615 DisplayState
*get_displaystate(void)
2617 return display_state
;
2620 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
2622 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
2623 return ds
->allocator
;
2628 static void dumb_display_init(void)
2630 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
2631 ds
->allocator
= &default_allocator
;
2632 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
2633 register_displaystate(ds
);
2636 /***********************************************************/
2639 typedef struct IOHandlerRecord
{
2641 IOCanRWHandler
*fd_read_poll
;
2643 IOHandler
*fd_write
;
2646 /* temporary data */
2648 struct IOHandlerRecord
*next
;
2651 static IOHandlerRecord
*first_io_handler
;
2653 /* XXX: fd_read_poll should be suppressed, but an API change is
2654 necessary in the character devices to suppress fd_can_read(). */
2655 int qemu_set_fd_handler2(int fd
,
2656 IOCanRWHandler
*fd_read_poll
,
2658 IOHandler
*fd_write
,
2661 IOHandlerRecord
**pioh
, *ioh
;
2663 if (!fd_read
&& !fd_write
) {
2664 pioh
= &first_io_handler
;
2669 if (ioh
->fd
== fd
) {
2676 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
2680 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
2681 ioh
->next
= first_io_handler
;
2682 first_io_handler
= ioh
;
2685 ioh
->fd_read_poll
= fd_read_poll
;
2686 ioh
->fd_read
= fd_read
;
2687 ioh
->fd_write
= fd_write
;
2688 ioh
->opaque
= opaque
;
2694 int qemu_set_fd_handler(int fd
,
2696 IOHandler
*fd_write
,
2699 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
2703 /***********************************************************/
2704 /* Polling handling */
2706 typedef struct PollingEntry
{
2709 struct PollingEntry
*next
;
2712 static PollingEntry
*first_polling_entry
;
2714 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
2716 PollingEntry
**ppe
, *pe
;
2717 pe
= qemu_mallocz(sizeof(PollingEntry
));
2719 pe
->opaque
= opaque
;
2720 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
2725 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
2727 PollingEntry
**ppe
, *pe
;
2728 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
2730 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
2738 /***********************************************************/
2739 /* Wait objects support */
2740 typedef struct WaitObjects
{
2742 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
2743 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
2744 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
2747 static WaitObjects wait_objects
= {0};
2749 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2751 WaitObjects
*w
= &wait_objects
;
2753 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
2755 w
->events
[w
->num
] = handle
;
2756 w
->func
[w
->num
] = func
;
2757 w
->opaque
[w
->num
] = opaque
;
2762 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2765 WaitObjects
*w
= &wait_objects
;
2768 for (i
= 0; i
< w
->num
; i
++) {
2769 if (w
->events
[i
] == handle
)
2772 w
->events
[i
] = w
->events
[i
+ 1];
2773 w
->func
[i
] = w
->func
[i
+ 1];
2774 w
->opaque
[i
] = w
->opaque
[i
+ 1];
2782 /***********************************************************/
2783 /* ram save/restore */
2785 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2786 #define RAM_SAVE_FLAG_COMPRESS 0x02
2787 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2788 #define RAM_SAVE_FLAG_PAGE 0x08
2789 #define RAM_SAVE_FLAG_EOS 0x10
2791 static int is_dup_page(uint8_t *page
, uint8_t ch
)
2793 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
2794 uint32_t *array
= (uint32_t *)page
;
2797 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
2798 if (array
[i
] != val
)
2805 static int ram_save_block(QEMUFile
*f
)
2807 static ram_addr_t current_addr
= 0;
2808 ram_addr_t saved_addr
= current_addr
;
2809 ram_addr_t addr
= 0;
2812 while (addr
< last_ram_offset
) {
2813 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
2816 cpu_physical_memory_reset_dirty(current_addr
,
2817 current_addr
+ TARGET_PAGE_SIZE
,
2818 MIGRATION_DIRTY_FLAG
);
2820 p
= qemu_get_ram_ptr(current_addr
);
2822 if (is_dup_page(p
, *p
)) {
2823 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
2824 qemu_put_byte(f
, *p
);
2826 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
2827 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
2833 addr
+= TARGET_PAGE_SIZE
;
2834 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
2840 static uint64_t bytes_transferred
= 0;
2842 static ram_addr_t
ram_save_remaining(void)
2845 ram_addr_t count
= 0;
2847 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2848 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2855 uint64_t ram_bytes_remaining(void)
2857 return ram_save_remaining() * TARGET_PAGE_SIZE
;
2860 uint64_t ram_bytes_transferred(void)
2862 return bytes_transferred
;
2865 uint64_t ram_bytes_total(void)
2867 return last_ram_offset
;
2870 static int ram_save_live(QEMUFile
*f
, int stage
, void *opaque
)
2873 uint64_t bytes_transferred_last
;
2875 uint64_t expected_time
= 0;
2877 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX
) != 0) {
2878 qemu_file_set_error(f
);
2883 /* Make sure all dirty bits are set */
2884 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2885 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2886 cpu_physical_memory_set_dirty(addr
);
2889 /* Enable dirty memory tracking */
2890 cpu_physical_memory_set_dirty_tracking(1);
2892 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
2895 bytes_transferred_last
= bytes_transferred
;
2896 bwidth
= get_clock();
2898 while (!qemu_file_rate_limit(f
)) {
2901 ret
= ram_save_block(f
);
2902 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
2903 if (ret
== 0) /* no more blocks */
2907 bwidth
= get_clock() - bwidth
;
2908 bwidth
= (bytes_transferred
- bytes_transferred_last
) / bwidth
;
2910 /* if we haven't transferred anything this round, force expected_time to a
2911 * a very high value, but without crashing */
2915 /* try transferring iterative blocks of memory */
2919 /* flush all remaining blocks regardless of rate limiting */
2920 while (ram_save_block(f
) != 0) {
2921 bytes_transferred
+= TARGET_PAGE_SIZE
;
2923 cpu_physical_memory_set_dirty_tracking(0);
2926 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
2928 expected_time
= ram_save_remaining() * TARGET_PAGE_SIZE
/ bwidth
;
2930 return (stage
== 2) && (expected_time
<= migrate_max_downtime());
2933 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
2938 if (version_id
!= 3)
2942 addr
= qemu_get_be64(f
);
2944 flags
= addr
& ~TARGET_PAGE_MASK
;
2945 addr
&= TARGET_PAGE_MASK
;
2947 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
2948 if (addr
!= last_ram_offset
)
2952 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
2953 uint8_t ch
= qemu_get_byte(f
);
2954 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
2957 (!kvm_enabled() || kvm_has_sync_mmu())) {
2958 madvise(qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
, MADV_DONTNEED
);
2961 } else if (flags
& RAM_SAVE_FLAG_PAGE
)
2962 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
2963 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
2968 void qemu_service_io(void)
2970 qemu_notify_event();
2973 /***********************************************************/
2974 /* bottom halves (can be seen as timers which expire ASAP) */
2985 static QEMUBH
*first_bh
= NULL
;
2987 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
2990 bh
= qemu_mallocz(sizeof(QEMUBH
));
2992 bh
->opaque
= opaque
;
2993 bh
->next
= first_bh
;
2998 int qemu_bh_poll(void)
3004 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3005 if (!bh
->deleted
&& bh
->scheduled
) {
3014 /* remove deleted bhs */
3028 void qemu_bh_schedule_idle(QEMUBH
*bh
)
3036 void qemu_bh_schedule(QEMUBH
*bh
)
3042 /* stop the currently executing CPU to execute the BH ASAP */
3043 qemu_notify_event();
3046 void qemu_bh_cancel(QEMUBH
*bh
)
3051 void qemu_bh_delete(QEMUBH
*bh
)
3057 static void qemu_bh_update_timeout(int *timeout
)
3061 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3062 if (!bh
->deleted
&& bh
->scheduled
) {
3064 /* idle bottom halves will be polled at least
3066 *timeout
= MIN(10, *timeout
);
3068 /* non-idle bottom halves will be executed
3077 /***********************************************************/
3078 /* machine registration */
3080 static QEMUMachine
*first_machine
= NULL
;
3081 QEMUMachine
*current_machine
= NULL
;
3083 int qemu_register_machine(QEMUMachine
*m
)
3086 pm
= &first_machine
;
3094 static QEMUMachine
*find_machine(const char *name
)
3098 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3099 if (!strcmp(m
->name
, name
))
3101 if (m
->alias
&& !strcmp(m
->alias
, name
))
3107 static QEMUMachine
*find_default_machine(void)
3111 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3112 if (m
->is_default
) {
3119 /***********************************************************/
3120 /* main execution loop */
3122 static void gui_update(void *opaque
)
3124 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3125 DisplayState
*ds
= opaque
;
3126 DisplayChangeListener
*dcl
= ds
->listeners
;
3130 while (dcl
!= NULL
) {
3131 if (dcl
->gui_timer_interval
&&
3132 dcl
->gui_timer_interval
< interval
)
3133 interval
= dcl
->gui_timer_interval
;
3136 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3139 static void nographic_update(void *opaque
)
3141 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3143 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3146 struct vm_change_state_entry
{
3147 VMChangeStateHandler
*cb
;
3149 QLIST_ENTRY (vm_change_state_entry
) entries
;
3152 static QLIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3154 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3157 VMChangeStateEntry
*e
;
3159 e
= qemu_mallocz(sizeof (*e
));
3163 QLIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3167 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3169 QLIST_REMOVE (e
, entries
);
3173 static void vm_state_notify(int running
, int reason
)
3175 VMChangeStateEntry
*e
;
3177 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3178 e
->cb(e
->opaque
, running
, reason
);
3182 static void resume_all_vcpus(void);
3183 static void pause_all_vcpus(void);
3190 vm_state_notify(1, 0);
3191 qemu_rearm_alarm_timer(alarm_timer
);
3196 /* reset/shutdown handler */
3198 typedef struct QEMUResetEntry
{
3199 QTAILQ_ENTRY(QEMUResetEntry
) entry
;
3200 QEMUResetHandler
*func
;
3204 static QTAILQ_HEAD(reset_handlers
, QEMUResetEntry
) reset_handlers
=
3205 QTAILQ_HEAD_INITIALIZER(reset_handlers
);
3206 static int reset_requested
;
3207 static int shutdown_requested
;
3208 static int powerdown_requested
;
3209 static int debug_requested
;
3210 static int vmstop_requested
;
3212 int qemu_shutdown_requested(void)
3214 int r
= shutdown_requested
;
3215 shutdown_requested
= 0;
3219 int qemu_reset_requested(void)
3221 int r
= reset_requested
;
3222 reset_requested
= 0;
3226 int qemu_powerdown_requested(void)
3228 int r
= powerdown_requested
;
3229 powerdown_requested
= 0;
3233 static int qemu_debug_requested(void)
3235 int r
= debug_requested
;
3236 debug_requested
= 0;
3240 static int qemu_vmstop_requested(void)
3242 int r
= vmstop_requested
;
3243 vmstop_requested
= 0;
3247 static void do_vm_stop(int reason
)
3250 cpu_disable_ticks();
3253 vm_state_notify(0, reason
);
3257 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3259 QEMUResetEntry
*re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3262 re
->opaque
= opaque
;
3263 QTAILQ_INSERT_TAIL(&reset_handlers
, re
, entry
);
3266 void qemu_unregister_reset(QEMUResetHandler
*func
, void *opaque
)
3270 QTAILQ_FOREACH(re
, &reset_handlers
, entry
) {
3271 if (re
->func
== func
&& re
->opaque
== opaque
) {
3272 QTAILQ_REMOVE(&reset_handlers
, re
, entry
);
3279 void qemu_system_reset(void)
3281 QEMUResetEntry
*re
, *nre
;
3283 /* reset all devices */
3284 QTAILQ_FOREACH_SAFE(re
, &reset_handlers
, entry
, nre
) {
3285 re
->func(re
->opaque
);
3289 void qemu_system_reset_request(void)
3292 shutdown_requested
= 1;
3294 reset_requested
= 1;
3296 qemu_notify_event();
3299 void qemu_system_shutdown_request(void)
3301 shutdown_requested
= 1;
3302 qemu_notify_event();
3305 void qemu_system_powerdown_request(void)
3307 powerdown_requested
= 1;
3308 qemu_notify_event();
3311 #ifdef CONFIG_IOTHREAD
3312 static void qemu_system_vmstop_request(int reason
)
3314 vmstop_requested
= reason
;
3315 qemu_notify_event();
3320 static int io_thread_fd
= -1;
3322 static void qemu_event_increment(void)
3324 static const char byte
= 0;
3326 if (io_thread_fd
== -1)
3329 write(io_thread_fd
, &byte
, sizeof(byte
));
3332 static void qemu_event_read(void *opaque
)
3334 int fd
= (unsigned long)opaque
;
3337 /* Drain the notify pipe */
3340 len
= read(fd
, buffer
, sizeof(buffer
));
3341 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
3344 static int qemu_event_init(void)
3353 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3357 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3361 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3362 (void *)(unsigned long)fds
[0]);
3364 io_thread_fd
= fds
[1];
3373 HANDLE qemu_event_handle
;
3375 static void dummy_event_handler(void *opaque
)
3379 static int qemu_event_init(void)
3381 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3382 if (!qemu_event_handle
) {
3383 fprintf(stderr
, "Failed CreateEvent: %ld\n", GetLastError());
3386 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3390 static void qemu_event_increment(void)
3392 if (!SetEvent(qemu_event_handle
)) {
3393 fprintf(stderr
, "qemu_event_increment: SetEvent failed: %ld\n",
3400 static int cpu_can_run(CPUState
*env
)
3409 #ifndef CONFIG_IOTHREAD
3410 static int qemu_init_main_loop(void)
3412 return qemu_event_init();
3415 void qemu_init_vcpu(void *_env
)
3417 CPUState
*env
= _env
;
3421 env
->nr_cores
= smp_cores
;
3422 env
->nr_threads
= smp_threads
;
3426 int qemu_cpu_self(void *env
)
3431 static void resume_all_vcpus(void)
3435 static void pause_all_vcpus(void)
3439 void qemu_cpu_kick(void *env
)
3444 void qemu_notify_event(void)
3446 CPUState
*env
= cpu_single_env
;
3453 #define qemu_mutex_lock_iothread() do { } while (0)
3454 #define qemu_mutex_unlock_iothread() do { } while (0)
3456 void vm_stop(int reason
)
3461 #else /* CONFIG_IOTHREAD */
3463 #include "qemu-thread.h"
3465 QemuMutex qemu_global_mutex
;
3466 static QemuMutex qemu_fair_mutex
;
3468 static QemuThread io_thread
;
3470 static QemuThread
*tcg_cpu_thread
;
3471 static QemuCond
*tcg_halt_cond
;
3473 static int qemu_system_ready
;
3475 static QemuCond qemu_cpu_cond
;
3477 static QemuCond qemu_system_cond
;
3478 static QemuCond qemu_pause_cond
;
3480 static void block_io_signals(void);
3481 static void unblock_io_signals(void);
3482 static int tcg_has_work(void);
3484 static int qemu_init_main_loop(void)
3488 ret
= qemu_event_init();
3492 qemu_cond_init(&qemu_pause_cond
);
3493 qemu_mutex_init(&qemu_fair_mutex
);
3494 qemu_mutex_init(&qemu_global_mutex
);
3495 qemu_mutex_lock(&qemu_global_mutex
);
3497 unblock_io_signals();
3498 qemu_thread_self(&io_thread
);
3503 static void qemu_wait_io_event(CPUState
*env
)
3505 while (!tcg_has_work())
3506 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3508 qemu_mutex_unlock(&qemu_global_mutex
);
3511 * Users of qemu_global_mutex can be starved, having no chance
3512 * to acquire it since this path will get to it first.
3513 * So use another lock to provide fairness.
3515 qemu_mutex_lock(&qemu_fair_mutex
);
3516 qemu_mutex_unlock(&qemu_fair_mutex
);
3518 qemu_mutex_lock(&qemu_global_mutex
);
3522 qemu_cond_signal(&qemu_pause_cond
);
3526 static int qemu_cpu_exec(CPUState
*env
);
3528 static void *kvm_cpu_thread_fn(void *arg
)
3530 CPUState
*env
= arg
;
3533 qemu_thread_self(env
->thread
);
3537 /* signal CPU creation */
3538 qemu_mutex_lock(&qemu_global_mutex
);
3540 qemu_cond_signal(&qemu_cpu_cond
);
3542 /* and wait for machine initialization */
3543 while (!qemu_system_ready
)
3544 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3547 if (cpu_can_run(env
))
3549 qemu_wait_io_event(env
);
3555 static void tcg_cpu_exec(void);
3557 static void *tcg_cpu_thread_fn(void *arg
)
3559 CPUState
*env
= arg
;
3562 qemu_thread_self(env
->thread
);
3564 /* signal CPU creation */
3565 qemu_mutex_lock(&qemu_global_mutex
);
3566 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
3568 qemu_cond_signal(&qemu_cpu_cond
);
3570 /* and wait for machine initialization */
3571 while (!qemu_system_ready
)
3572 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3576 qemu_wait_io_event(cur_cpu
);
3582 void qemu_cpu_kick(void *_env
)
3584 CPUState
*env
= _env
;
3585 qemu_cond_broadcast(env
->halt_cond
);
3587 qemu_thread_signal(env
->thread
, SIGUSR1
);
3590 int qemu_cpu_self(void *_env
)
3592 CPUState
*env
= _env
;
3595 qemu_thread_self(&this);
3597 return qemu_thread_equal(&this, env
->thread
);
3600 static void cpu_signal(int sig
)
3603 cpu_exit(cpu_single_env
);
3606 static void block_io_signals(void)
3609 struct sigaction sigact
;
3612 sigaddset(&set
, SIGUSR2
);
3613 sigaddset(&set
, SIGIO
);
3614 sigaddset(&set
, SIGALRM
);
3615 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3618 sigaddset(&set
, SIGUSR1
);
3619 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3621 memset(&sigact
, 0, sizeof(sigact
));
3622 sigact
.sa_handler
= cpu_signal
;
3623 sigaction(SIGUSR1
, &sigact
, NULL
);
3626 static void unblock_io_signals(void)
3631 sigaddset(&set
, SIGUSR2
);
3632 sigaddset(&set
, SIGIO
);
3633 sigaddset(&set
, SIGALRM
);
3634 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3637 sigaddset(&set
, SIGUSR1
);
3638 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3641 static void qemu_signal_lock(unsigned int msecs
)
3643 qemu_mutex_lock(&qemu_fair_mutex
);
3645 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
3646 qemu_thread_signal(tcg_cpu_thread
, SIGUSR1
);
3647 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
3650 qemu_mutex_unlock(&qemu_fair_mutex
);
3653 static void qemu_mutex_lock_iothread(void)
3655 if (kvm_enabled()) {
3656 qemu_mutex_lock(&qemu_fair_mutex
);
3657 qemu_mutex_lock(&qemu_global_mutex
);
3658 qemu_mutex_unlock(&qemu_fair_mutex
);
3660 qemu_signal_lock(100);
3663 static void qemu_mutex_unlock_iothread(void)
3665 qemu_mutex_unlock(&qemu_global_mutex
);
3668 static int all_vcpus_paused(void)
3670 CPUState
*penv
= first_cpu
;
3675 penv
= (CPUState
*)penv
->next_cpu
;
3681 static void pause_all_vcpus(void)
3683 CPUState
*penv
= first_cpu
;
3687 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3688 qemu_cpu_kick(penv
);
3689 penv
= (CPUState
*)penv
->next_cpu
;
3692 while (!all_vcpus_paused()) {
3693 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
3696 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3697 penv
= (CPUState
*)penv
->next_cpu
;
3702 static void resume_all_vcpus(void)
3704 CPUState
*penv
= first_cpu
;
3709 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3710 qemu_cpu_kick(penv
);
3711 penv
= (CPUState
*)penv
->next_cpu
;
3715 static void tcg_init_vcpu(void *_env
)
3717 CPUState
*env
= _env
;
3718 /* share a single thread for all cpus with TCG */
3719 if (!tcg_cpu_thread
) {
3720 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3721 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3722 qemu_cond_init(env
->halt_cond
);
3723 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
3724 while (env
->created
== 0)
3725 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3726 tcg_cpu_thread
= env
->thread
;
3727 tcg_halt_cond
= env
->halt_cond
;
3729 env
->thread
= tcg_cpu_thread
;
3730 env
->halt_cond
= tcg_halt_cond
;
3734 static void kvm_start_vcpu(CPUState
*env
)
3736 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3737 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3738 qemu_cond_init(env
->halt_cond
);
3739 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
3740 while (env
->created
== 0)
3741 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3744 void qemu_init_vcpu(void *_env
)
3746 CPUState
*env
= _env
;
3749 kvm_start_vcpu(env
);
3752 env
->nr_cores
= smp_cores
;
3753 env
->nr_threads
= smp_threads
;
3756 void qemu_notify_event(void)
3758 qemu_event_increment();
3761 void vm_stop(int reason
)
3764 qemu_thread_self(&me
);
3766 if (!qemu_thread_equal(&me
, &io_thread
)) {
3767 qemu_system_vmstop_request(reason
);
3769 * FIXME: should not return to device code in case
3770 * vm_stop() has been requested.
3772 if (cpu_single_env
) {
3773 cpu_exit(cpu_single_env
);
3774 cpu_single_env
->stop
= 1;
3785 static void host_main_loop_wait(int *timeout
)
3791 /* XXX: need to suppress polling by better using win32 events */
3793 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
3794 ret
|= pe
->func(pe
->opaque
);
3798 WaitObjects
*w
= &wait_objects
;
3800 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
3801 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
3802 if (w
->func
[ret
- WAIT_OBJECT_0
])
3803 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
3805 /* Check for additional signaled events */
3806 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
3808 /* Check if event is signaled */
3809 ret2
= WaitForSingleObject(w
->events
[i
], 0);
3810 if(ret2
== WAIT_OBJECT_0
) {
3812 w
->func
[i
](w
->opaque
[i
]);
3813 } else if (ret2
== WAIT_TIMEOUT
) {
3815 err
= GetLastError();
3816 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
3819 } else if (ret
== WAIT_TIMEOUT
) {
3821 err
= GetLastError();
3822 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
3829 static void host_main_loop_wait(int *timeout
)
3834 void main_loop_wait(int timeout
)
3836 IOHandlerRecord
*ioh
;
3837 fd_set rfds
, wfds
, xfds
;
3841 qemu_bh_update_timeout(&timeout
);
3843 host_main_loop_wait(&timeout
);
3845 /* poll any events */
3846 /* XXX: separate device handlers from system ones */
3851 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3855 (!ioh
->fd_read_poll
||
3856 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
3857 FD_SET(ioh
->fd
, &rfds
);
3861 if (ioh
->fd_write
) {
3862 FD_SET(ioh
->fd
, &wfds
);
3868 tv
.tv_sec
= timeout
/ 1000;
3869 tv
.tv_usec
= (timeout
% 1000) * 1000;
3871 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
3873 qemu_mutex_unlock_iothread();
3874 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
3875 qemu_mutex_lock_iothread();
3877 IOHandlerRecord
**pioh
;
3879 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3880 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
3881 ioh
->fd_read(ioh
->opaque
);
3883 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
3884 ioh
->fd_write(ioh
->opaque
);
3888 /* remove deleted IO handlers */
3889 pioh
= &first_io_handler
;
3900 slirp_select_poll(&rfds
, &wfds
, &xfds
, (ret
< 0));
3902 /* rearm timer, if not periodic */
3903 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
3904 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
3905 qemu_rearm_alarm_timer(alarm_timer
);
3908 /* vm time timers */
3910 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
3911 qemu_run_timers(&active_timers
[QEMU_CLOCK_VIRTUAL
],
3912 qemu_get_clock(vm_clock
));
3915 /* real time timers */
3916 qemu_run_timers(&active_timers
[QEMU_CLOCK_REALTIME
],
3917 qemu_get_clock(rt_clock
));
3919 /* Check bottom-halves last in case any of the earlier events triggered
3925 static int qemu_cpu_exec(CPUState
*env
)
3928 #ifdef CONFIG_PROFILER
3932 #ifdef CONFIG_PROFILER
3933 ti
= profile_getclock();
3938 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
3939 env
->icount_decr
.u16
.low
= 0;
3940 env
->icount_extra
= 0;
3941 count
= qemu_next_deadline();
3942 count
= (count
+ (1 << icount_time_shift
) - 1)
3943 >> icount_time_shift
;
3944 qemu_icount
+= count
;
3945 decr
= (count
> 0xffff) ? 0xffff : count
;
3947 env
->icount_decr
.u16
.low
= decr
;
3948 env
->icount_extra
= count
;
3950 ret
= cpu_exec(env
);
3951 #ifdef CONFIG_PROFILER
3952 qemu_time
+= profile_getclock() - ti
;
3955 /* Fold pending instructions back into the
3956 instruction counter, and clear the interrupt flag. */
3957 qemu_icount
-= (env
->icount_decr
.u16
.low
3958 + env
->icount_extra
);
3959 env
->icount_decr
.u32
= 0;
3960 env
->icount_extra
= 0;
3965 static void tcg_cpu_exec(void)
3969 if (next_cpu
== NULL
)
3970 next_cpu
= first_cpu
;
3971 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
3972 CPUState
*env
= cur_cpu
= next_cpu
;
3976 if (timer_alarm_pending
) {
3977 timer_alarm_pending
= 0;
3980 if (cpu_can_run(env
))
3981 ret
= qemu_cpu_exec(env
);
3982 if (ret
== EXCP_DEBUG
) {
3983 gdb_set_stop_cpu(env
);
3984 debug_requested
= 1;
3990 static int cpu_has_work(CPUState
*env
)
3998 if (qemu_cpu_has_work(env
))
4003 static int tcg_has_work(void)
4007 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4008 if (cpu_has_work(env
))
4013 static int qemu_calculate_timeout(void)
4015 #ifndef CONFIG_IOTHREAD
4020 else if (tcg_has_work())
4022 else if (!use_icount
)
4025 /* XXX: use timeout computed from timers */
4028 /* Advance virtual time to the next event. */
4029 if (use_icount
== 1) {
4030 /* When not using an adaptive execution frequency
4031 we tend to get badly out of sync with real time,
4032 so just delay for a reasonable amount of time. */
4035 delta
= cpu_get_icount() - cpu_get_clock();
4038 /* If virtual time is ahead of real time then just
4040 timeout
= (delta
/ 1000000) + 1;
4042 /* Wait for either IO to occur or the next
4044 add
= qemu_next_deadline();
4045 /* We advance the timer before checking for IO.
4046 Limit the amount we advance so that early IO
4047 activity won't get the guest too far ahead. */
4051 add
= (add
+ (1 << icount_time_shift
) - 1)
4052 >> icount_time_shift
;
4054 timeout
= delta
/ 1000000;
4061 #else /* CONFIG_IOTHREAD */
4066 static int vm_can_run(void)
4068 if (powerdown_requested
)
4070 if (reset_requested
)
4072 if (shutdown_requested
)
4074 if (debug_requested
)
4079 qemu_irq qemu_system_powerdown
;
4081 static void main_loop(void)
4085 #ifdef CONFIG_IOTHREAD
4086 qemu_system_ready
= 1;
4087 qemu_cond_broadcast(&qemu_system_cond
);
4092 #ifdef CONFIG_PROFILER
4095 #ifndef CONFIG_IOTHREAD
4098 #ifdef CONFIG_PROFILER
4099 ti
= profile_getclock();
4101 main_loop_wait(qemu_calculate_timeout());
4102 #ifdef CONFIG_PROFILER
4103 dev_time
+= profile_getclock() - ti
;
4105 } while (vm_can_run());
4107 if (qemu_debug_requested())
4108 vm_stop(EXCP_DEBUG
);
4109 if (qemu_shutdown_requested()) {
4116 if (qemu_reset_requested()) {
4118 qemu_system_reset();
4121 if (qemu_powerdown_requested()) {
4122 qemu_irq_raise(qemu_system_powerdown
);
4124 if ((r
= qemu_vmstop_requested()))
4130 static void version(void)
4132 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4135 static void help(int exitcode
)
4138 printf("usage: %s [options] [disk_image]\n"
4140 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4142 #define DEF(option, opt_arg, opt_enum, opt_help) \
4144 #define DEFHEADING(text) stringify(text) "\n"
4145 #include "qemu-options.h"
4150 "During emulation, the following keys are useful:\n"
4151 "ctrl-alt-f toggle full screen\n"
4152 "ctrl-alt-n switch to virtual console 'n'\n"
4153 "ctrl-alt toggle mouse and keyboard grab\n"
4155 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4160 DEFAULT_NETWORK_SCRIPT
,
4161 DEFAULT_NETWORK_DOWN_SCRIPT
,
4163 DEFAULT_GDBSTUB_PORT
,
4168 #define HAS_ARG 0x0001
4171 #define DEF(option, opt_arg, opt_enum, opt_help) \
4173 #define DEFHEADING(text)
4174 #include "qemu-options.h"
4180 typedef struct QEMUOption
{
4186 static const QEMUOption qemu_options
[] = {
4187 { "h", 0, QEMU_OPTION_h
},
4188 #define DEF(option, opt_arg, opt_enum, opt_help) \
4189 { option, opt_arg, opt_enum },
4190 #define DEFHEADING(text)
4191 #include "qemu-options.h"
4199 struct soundhw soundhw
[] = {
4200 #ifdef HAS_AUDIO_CHOICE
4201 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4207 { .init_isa
= pcspk_audio_init
}
4214 "Creative Sound Blaster 16",
4217 { .init_isa
= SB16_init
}
4221 #ifdef CONFIG_CS4231A
4227 { .init_isa
= cs4231a_init
}
4235 "Yamaha YMF262 (OPL3)",
4237 "Yamaha YM3812 (OPL2)",
4241 { .init_isa
= Adlib_init
}
4248 "Gravis Ultrasound GF1",
4251 { .init_isa
= GUS_init
}
4258 "Intel 82801AA AC97 Audio",
4261 { .init_pci
= ac97_init
}
4265 #ifdef CONFIG_ES1370
4268 "ENSONIQ AudioPCI ES1370",
4271 { .init_pci
= es1370_init
}
4275 #endif /* HAS_AUDIO_CHOICE */
4277 { NULL
, NULL
, 0, 0, { NULL
} }
4280 static void select_soundhw (const char *optarg
)
4284 if (*optarg
== '?') {
4287 printf ("Valid sound card names (comma separated):\n");
4288 for (c
= soundhw
; c
->name
; ++c
) {
4289 printf ("%-11s %s\n", c
->name
, c
->descr
);
4291 printf ("\n-soundhw all will enable all of the above\n");
4292 exit (*optarg
!= '?');
4300 if (!strcmp (optarg
, "all")) {
4301 for (c
= soundhw
; c
->name
; ++c
) {
4309 e
= strchr (p
, ',');
4310 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4312 for (c
= soundhw
; c
->name
; ++c
) {
4313 if (!strncmp (c
->name
, p
, l
) && !c
->name
[l
]) {
4322 "Unknown sound card name (too big to show)\n");
4325 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4330 p
+= l
+ (e
!= NULL
);
4334 goto show_valid_cards
;
4339 static void select_vgahw (const char *p
)
4343 vga_interface_type
= VGA_NONE
;
4344 if (strstart(p
, "std", &opts
)) {
4345 vga_interface_type
= VGA_STD
;
4346 } else if (strstart(p
, "cirrus", &opts
)) {
4347 vga_interface_type
= VGA_CIRRUS
;
4348 } else if (strstart(p
, "vmware", &opts
)) {
4349 vga_interface_type
= VGA_VMWARE
;
4350 } else if (strstart(p
, "xenfb", &opts
)) {
4351 vga_interface_type
= VGA_XENFB
;
4352 } else if (!strstart(p
, "none", &opts
)) {
4354 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4358 const char *nextopt
;
4360 if (strstart(opts
, ",retrace=", &nextopt
)) {
4362 if (strstart(opts
, "dumb", &nextopt
))
4363 vga_retrace_method
= VGA_RETRACE_DUMB
;
4364 else if (strstart(opts
, "precise", &nextopt
))
4365 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4366 else goto invalid_vga
;
4367 } else goto invalid_vga
;
4373 static int balloon_parse(const char *arg
)
4377 if (strcmp(arg
, "none") == 0) {
4381 if (!strncmp(arg
, "virtio", 6)) {
4382 if (arg
[6] == ',') {
4383 /* have params -> parse them */
4384 opts
= qemu_opts_parse(&qemu_device_opts
, arg
+7, NULL
);
4388 /* create empty opts */
4389 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4391 qemu_opt_set(opts
, "driver", "virtio-balloon-pci");
4400 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4402 exit(STATUS_CONTROL_C_EXIT
);
4407 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4411 if(strlen(str
) != 36)
4414 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4415 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4416 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4422 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4428 #define MAX_NET_CLIENTS 32
4432 static void termsig_handler(int signal
)
4434 qemu_system_shutdown_request();
4437 static void sigchld_handler(int signal
)
4439 waitpid(-1, NULL
, WNOHANG
);
4442 static void sighandler_setup(void)
4444 struct sigaction act
;
4446 memset(&act
, 0, sizeof(act
));
4447 act
.sa_handler
= termsig_handler
;
4448 sigaction(SIGINT
, &act
, NULL
);
4449 sigaction(SIGHUP
, &act
, NULL
);
4450 sigaction(SIGTERM
, &act
, NULL
);
4452 act
.sa_handler
= sigchld_handler
;
4453 act
.sa_flags
= SA_NOCLDSTOP
;
4454 sigaction(SIGCHLD
, &act
, NULL
);
4460 /* Look for support files in the same directory as the executable. */
4461 static char *find_datadir(const char *argv0
)
4467 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
4474 while (p
!= buf
&& *p
!= '\\')
4477 if (access(buf
, R_OK
) == 0) {
4478 return qemu_strdup(buf
);
4484 /* Find a likely location for support files using the location of the binary.
4485 For installed binaries this will be "$bindir/../share/qemu". When
4486 running from the build tree this will be "$bindir/../pc-bios". */
4487 #define SHARE_SUFFIX "/share/qemu"
4488 #define BUILD_SUFFIX "/pc-bios"
4489 static char *find_datadir(const char *argv0
)
4497 #if defined(__linux__)
4500 len
= readlink("/proc/self/exe", buf
, sizeof(buf
) - 1);
4506 #elif defined(__FreeBSD__)
4509 len
= readlink("/proc/curproc/file", buf
, sizeof(buf
) - 1);
4516 /* If we don't have any way of figuring out the actual executable
4517 location then try argv[0]. */
4519 p
= realpath(argv0
, buf
);
4527 max_len
= strlen(dir
) +
4528 MAX(strlen(SHARE_SUFFIX
), strlen(BUILD_SUFFIX
)) + 1;
4529 res
= qemu_mallocz(max_len
);
4530 snprintf(res
, max_len
, "%s%s", dir
, SHARE_SUFFIX
);
4531 if (access(res
, R_OK
)) {
4532 snprintf(res
, max_len
, "%s%s", dir
, BUILD_SUFFIX
);
4533 if (access(res
, R_OK
)) {
4545 char *qemu_find_file(int type
, const char *name
)
4551 /* If name contains path separators then try it as a straight path. */
4552 if ((strchr(name
, '/') || strchr(name
, '\\'))
4553 && access(name
, R_OK
) == 0) {
4554 return qemu_strdup(name
);
4557 case QEMU_FILE_TYPE_BIOS
:
4560 case QEMU_FILE_TYPE_KEYMAP
:
4561 subdir
= "keymaps/";
4566 len
= strlen(data_dir
) + strlen(name
) + strlen(subdir
) + 2;
4567 buf
= qemu_mallocz(len
);
4568 snprintf(buf
, len
, "%s/%s%s", data_dir
, subdir
, name
);
4569 if (access(buf
, R_OK
)) {
4576 static int device_init_func(QemuOpts
*opts
, void *opaque
)
4580 dev
= qdev_device_add(opts
);
4586 struct device_config
{
4588 DEV_USB
, /* -usbdevice */
4591 const char *cmdline
;
4592 QTAILQ_ENTRY(device_config
) next
;
4594 QTAILQ_HEAD(, device_config
) device_configs
= QTAILQ_HEAD_INITIALIZER(device_configs
);
4596 static void add_device_config(int type
, const char *cmdline
)
4598 struct device_config
*conf
;
4600 conf
= qemu_mallocz(sizeof(*conf
));
4602 conf
->cmdline
= cmdline
;
4603 QTAILQ_INSERT_TAIL(&device_configs
, conf
, next
);
4606 static int foreach_device_config(int type
, int (*func
)(const char *cmdline
))
4608 struct device_config
*conf
;
4611 QTAILQ_FOREACH(conf
, &device_configs
, next
) {
4612 if (conf
->type
!= type
)
4614 rc
= func(conf
->cmdline
);
4621 int main(int argc
, char **argv
, char **envp
)
4623 const char *gdbstub_dev
= NULL
;
4624 uint32_t boot_devices_bitmap
= 0;
4626 int snapshot
, linux_boot
, net_boot
;
4627 const char *initrd_filename
;
4628 const char *kernel_filename
, *kernel_cmdline
;
4629 char boot_devices
[33] = "cad"; /* default to HD->floppy->CD-ROM */
4631 DisplayChangeListener
*dcl
;
4632 int cyls
, heads
, secs
, translation
;
4633 const char *net_clients
[MAX_NET_CLIENTS
];
4635 QemuOpts
*hda_opts
= NULL
, *opts
;
4637 const char *r
, *optarg
;
4638 CharDriverState
*monitor_hds
[MAX_MONITOR_DEVICES
];
4639 const char *monitor_devices
[MAX_MONITOR_DEVICES
];
4640 int monitor_device_index
;
4641 const char *serial_devices
[MAX_SERIAL_PORTS
];
4642 int serial_device_index
;
4643 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
4644 int parallel_device_index
;
4645 const char *virtio_consoles
[MAX_VIRTIO_CONSOLES
];
4646 int virtio_console_index
;
4647 const char *loadvm
= NULL
;
4648 QEMUMachine
*machine
;
4649 const char *cpu_model
;
4654 const char *pid_file
= NULL
;
4655 const char *incoming
= NULL
;
4658 struct passwd
*pwd
= NULL
;
4659 const char *chroot_dir
= NULL
;
4660 const char *run_as
= NULL
;
4663 int show_vnc_port
= 0;
4665 qemu_errors_to_file(stderr
);
4666 qemu_cache_utils_init(envp
);
4668 QLIST_INIT (&vm_change_state_head
);
4671 struct sigaction act
;
4672 sigfillset(&act
.sa_mask
);
4674 act
.sa_handler
= SIG_IGN
;
4675 sigaction(SIGPIPE
, &act
, NULL
);
4678 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4679 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4680 QEMU to run on a single CPU */
4685 h
= GetCurrentProcess();
4686 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4687 for(i
= 0; i
< 32; i
++) {
4688 if (mask
& (1 << i
))
4693 SetProcessAffinityMask(h
, mask
);
4699 module_call_init(MODULE_INIT_MACHINE
);
4700 machine
= find_default_machine();
4702 initrd_filename
= NULL
;
4705 kernel_filename
= NULL
;
4706 kernel_cmdline
= "";
4707 cyls
= heads
= secs
= 0;
4708 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4710 serial_devices
[0] = "vc:80Cx24C";
4711 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
4712 serial_devices
[i
] = NULL
;
4713 serial_device_index
= 0;
4715 parallel_devices
[0] = "vc:80Cx24C";
4716 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
4717 parallel_devices
[i
] = NULL
;
4718 parallel_device_index
= 0;
4720 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++)
4721 virtio_consoles
[i
] = NULL
;
4722 virtio_console_index
= 0;
4724 monitor_devices
[0] = "vc:80Cx24C";
4725 for (i
= 1; i
< MAX_MONITOR_DEVICES
; i
++) {
4726 monitor_devices
[i
] = NULL
;
4728 monitor_device_index
= 0;
4730 for (i
= 0; i
< MAX_NODES
; i
++) {
4732 node_cpumask
[i
] = 0;
4748 hda_opts
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
4750 const QEMUOption
*popt
;
4753 /* Treat --foo the same as -foo. */
4756 popt
= qemu_options
;
4759 fprintf(stderr
, "%s: invalid option -- '%s'\n",
4763 if (!strcmp(popt
->name
, r
+ 1))
4767 if (popt
->flags
& HAS_ARG
) {
4768 if (optind
>= argc
) {
4769 fprintf(stderr
, "%s: option '%s' requires an argument\n",
4773 optarg
= argv
[optind
++];
4778 switch(popt
->index
) {
4780 machine
= find_machine(optarg
);
4783 printf("Supported machines are:\n");
4784 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
4786 printf("%-10s %s (alias of %s)\n",
4787 m
->alias
, m
->desc
, m
->name
);
4788 printf("%-10s %s%s\n",
4790 m
->is_default
? " (default)" : "");
4792 exit(*optarg
!= '?');
4795 case QEMU_OPTION_cpu
:
4796 /* hw initialization will check this */
4797 if (*optarg
== '?') {
4798 /* XXX: implement xxx_cpu_list for targets that still miss it */
4799 #if defined(cpu_list)
4800 cpu_list(stdout
, &fprintf
);
4807 case QEMU_OPTION_initrd
:
4808 initrd_filename
= optarg
;
4810 case QEMU_OPTION_hda
:
4812 hda_opts
= drive_add(optarg
, HD_ALIAS
, 0);
4814 hda_opts
= drive_add(optarg
, HD_ALIAS
4815 ",cyls=%d,heads=%d,secs=%d%s",
4816 0, cyls
, heads
, secs
,
4817 translation
== BIOS_ATA_TRANSLATION_LBA
?
4819 translation
== BIOS_ATA_TRANSLATION_NONE
?
4820 ",trans=none" : "");
4822 case QEMU_OPTION_hdb
:
4823 case QEMU_OPTION_hdc
:
4824 case QEMU_OPTION_hdd
:
4825 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
4827 case QEMU_OPTION_drive
:
4828 drive_add(NULL
, "%s", optarg
);
4830 case QEMU_OPTION_set
:
4831 if (qemu_set_option(optarg
) != 0)
4834 case QEMU_OPTION_mtdblock
:
4835 drive_add(optarg
, MTD_ALIAS
);
4837 case QEMU_OPTION_sd
:
4838 drive_add(optarg
, SD_ALIAS
);
4840 case QEMU_OPTION_pflash
:
4841 drive_add(optarg
, PFLASH_ALIAS
);
4843 case QEMU_OPTION_snapshot
:
4846 case QEMU_OPTION_hdachs
:
4850 cyls
= strtol(p
, (char **)&p
, 0);
4851 if (cyls
< 1 || cyls
> 16383)
4856 heads
= strtol(p
, (char **)&p
, 0);
4857 if (heads
< 1 || heads
> 16)
4862 secs
= strtol(p
, (char **)&p
, 0);
4863 if (secs
< 1 || secs
> 63)
4867 if (!strcmp(p
, "none"))
4868 translation
= BIOS_ATA_TRANSLATION_NONE
;
4869 else if (!strcmp(p
, "lba"))
4870 translation
= BIOS_ATA_TRANSLATION_LBA
;
4871 else if (!strcmp(p
, "auto"))
4872 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4875 } else if (*p
!= '\0') {
4877 fprintf(stderr
, "qemu: invalid physical CHS format\n");
4880 if (hda_opts
!= NULL
) {
4882 snprintf(num
, sizeof(num
), "%d", cyls
);
4883 qemu_opt_set(hda_opts
, "cyls", num
);
4884 snprintf(num
, sizeof(num
), "%d", heads
);
4885 qemu_opt_set(hda_opts
, "heads", num
);
4886 snprintf(num
, sizeof(num
), "%d", secs
);
4887 qemu_opt_set(hda_opts
, "secs", num
);
4888 if (translation
== BIOS_ATA_TRANSLATION_LBA
)
4889 qemu_opt_set(hda_opts
, "trans", "lba");
4890 if (translation
== BIOS_ATA_TRANSLATION_NONE
)
4891 qemu_opt_set(hda_opts
, "trans", "none");
4895 case QEMU_OPTION_numa
:
4896 if (nb_numa_nodes
>= MAX_NODES
) {
4897 fprintf(stderr
, "qemu: too many NUMA nodes\n");
4902 case QEMU_OPTION_nographic
:
4903 display_type
= DT_NOGRAPHIC
;
4905 #ifdef CONFIG_CURSES
4906 case QEMU_OPTION_curses
:
4907 display_type
= DT_CURSES
;
4910 case QEMU_OPTION_portrait
:
4913 case QEMU_OPTION_kernel
:
4914 kernel_filename
= optarg
;
4916 case QEMU_OPTION_append
:
4917 kernel_cmdline
= optarg
;
4919 case QEMU_OPTION_cdrom
:
4920 drive_add(optarg
, CDROM_ALIAS
);
4922 case QEMU_OPTION_boot
:
4924 static const char * const params
[] = {
4925 "order", "once", "menu", NULL
4927 char buf
[sizeof(boot_devices
)];
4928 char *standard_boot_devices
;
4931 if (!strchr(optarg
, '=')) {
4933 pstrcpy(buf
, sizeof(buf
), optarg
);
4934 } else if (check_params(buf
, sizeof(buf
), params
, optarg
) < 0) {
4936 "qemu: unknown boot parameter '%s' in '%s'\n",
4942 get_param_value(buf
, sizeof(buf
), "order", optarg
)) {
4943 boot_devices_bitmap
= parse_bootdevices(buf
);
4944 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
4947 if (get_param_value(buf
, sizeof(buf
),
4949 boot_devices_bitmap
|= parse_bootdevices(buf
);
4950 standard_boot_devices
= qemu_strdup(boot_devices
);
4951 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
4952 qemu_register_reset(restore_boot_devices
,
4953 standard_boot_devices
);
4955 if (get_param_value(buf
, sizeof(buf
),
4957 if (!strcmp(buf
, "on")) {
4959 } else if (!strcmp(buf
, "off")) {
4963 "qemu: invalid option value '%s'\n",
4971 case QEMU_OPTION_fda
:
4972 case QEMU_OPTION_fdb
:
4973 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
4976 case QEMU_OPTION_no_fd_bootchk
:
4980 case QEMU_OPTION_net
:
4981 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
4982 fprintf(stderr
, "qemu: too many network clients\n");
4985 net_clients
[nb_net_clients
] = optarg
;
4989 case QEMU_OPTION_tftp
:
4990 legacy_tftp_prefix
= optarg
;
4992 case QEMU_OPTION_bootp
:
4993 legacy_bootp_filename
= optarg
;
4996 case QEMU_OPTION_smb
:
4997 net_slirp_smb(optarg
);
5000 case QEMU_OPTION_redir
:
5001 net_slirp_redir(optarg
);
5004 case QEMU_OPTION_bt
:
5005 add_device_config(DEV_BT
, optarg
);
5008 case QEMU_OPTION_audio_help
:
5012 case QEMU_OPTION_soundhw
:
5013 select_soundhw (optarg
);
5019 case QEMU_OPTION_version
:
5023 case QEMU_OPTION_m
: {
5027 value
= strtoul(optarg
, &ptr
, 10);
5029 case 0: case 'M': case 'm':
5036 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5040 /* On 32-bit hosts, QEMU is limited by virtual address space */
5041 if (value
> (2047 << 20) && HOST_LONG_BITS
== 32) {
5042 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5045 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5046 fprintf(stderr
, "qemu: ram size too large\n");
5055 const CPULogItem
*item
;
5057 mask
= cpu_str_to_log_mask(optarg
);
5059 printf("Log items (comma separated):\n");
5060 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5061 printf("%-10s %s\n", item
->name
, item
->help
);
5069 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5071 case QEMU_OPTION_gdb
:
5072 gdbstub_dev
= optarg
;
5077 case QEMU_OPTION_bios
:
5080 case QEMU_OPTION_singlestep
:
5088 keyboard_layout
= optarg
;
5091 case QEMU_OPTION_localtime
:
5094 case QEMU_OPTION_vga
:
5095 select_vgahw (optarg
);
5097 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5103 w
= strtol(p
, (char **)&p
, 10);
5106 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5112 h
= strtol(p
, (char **)&p
, 10);
5117 depth
= strtol(p
, (char **)&p
, 10);
5118 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5119 depth
!= 24 && depth
!= 32)
5121 } else if (*p
== '\0') {
5122 depth
= graphic_depth
;
5129 graphic_depth
= depth
;
5133 case QEMU_OPTION_echr
:
5136 term_escape_char
= strtol(optarg
, &r
, 0);
5138 printf("Bad argument to echr\n");
5141 case QEMU_OPTION_monitor
:
5142 if (monitor_device_index
>= MAX_MONITOR_DEVICES
) {
5143 fprintf(stderr
, "qemu: too many monitor devices\n");
5146 monitor_devices
[monitor_device_index
] = optarg
;
5147 monitor_device_index
++;
5149 case QEMU_OPTION_chardev
:
5150 opts
= qemu_opts_parse(&qemu_chardev_opts
, optarg
, "backend");
5152 fprintf(stderr
, "parse error: %s\n", optarg
);
5155 if (qemu_chr_open_opts(opts
, NULL
) == NULL
) {
5159 case QEMU_OPTION_serial
:
5160 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
5161 fprintf(stderr
, "qemu: too many serial ports\n");
5164 serial_devices
[serial_device_index
] = optarg
;
5165 serial_device_index
++;
5167 case QEMU_OPTION_watchdog
:
5170 "qemu: only one watchdog option may be given\n");
5175 case QEMU_OPTION_watchdog_action
:
5176 if (select_watchdog_action(optarg
) == -1) {
5177 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5181 case QEMU_OPTION_virtiocon
:
5182 if (virtio_console_index
>= MAX_VIRTIO_CONSOLES
) {
5183 fprintf(stderr
, "qemu: too many virtio consoles\n");
5186 virtio_consoles
[virtio_console_index
] = optarg
;
5187 virtio_console_index
++;
5189 case QEMU_OPTION_parallel
:
5190 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
5191 fprintf(stderr
, "qemu: too many parallel ports\n");
5194 parallel_devices
[parallel_device_index
] = optarg
;
5195 parallel_device_index
++;
5197 case QEMU_OPTION_loadvm
:
5200 case QEMU_OPTION_full_screen
:
5204 case QEMU_OPTION_no_frame
:
5207 case QEMU_OPTION_alt_grab
:
5210 case QEMU_OPTION_no_quit
:
5213 case QEMU_OPTION_sdl
:
5214 display_type
= DT_SDL
;
5217 case QEMU_OPTION_pidfile
:
5221 case QEMU_OPTION_win2k_hack
:
5222 win2k_install_hack
= 1;
5224 case QEMU_OPTION_rtc_td_hack
:
5227 case QEMU_OPTION_acpitable
:
5228 if(acpi_table_add(optarg
) < 0) {
5229 fprintf(stderr
, "Wrong acpi table provided\n");
5233 case QEMU_OPTION_smbios
:
5234 if(smbios_entry_add(optarg
) < 0) {
5235 fprintf(stderr
, "Wrong smbios provided\n");
5241 case QEMU_OPTION_enable_kvm
:
5245 case QEMU_OPTION_usb
:
5248 case QEMU_OPTION_usbdevice
:
5250 add_device_config(DEV_USB
, optarg
);
5252 case QEMU_OPTION_device
:
5253 opts
= qemu_opts_parse(&qemu_device_opts
, optarg
, "driver");
5255 fprintf(stderr
, "parse error: %s\n", optarg
);
5259 case QEMU_OPTION_smp
:
5262 fprintf(stderr
, "Invalid number of CPUs\n");
5265 if (max_cpus
< smp_cpus
) {
5266 fprintf(stderr
, "maxcpus must be equal to or greater than "
5270 if (max_cpus
> 255) {
5271 fprintf(stderr
, "Unsupported number of maxcpus\n");
5275 case QEMU_OPTION_vnc
:
5276 display_type
= DT_VNC
;
5277 vnc_display
= optarg
;
5280 case QEMU_OPTION_no_acpi
:
5283 case QEMU_OPTION_no_hpet
:
5286 case QEMU_OPTION_balloon
:
5287 if (balloon_parse(optarg
) < 0) {
5288 fprintf(stderr
, "Unknown -balloon argument %s\n", optarg
);
5293 case QEMU_OPTION_no_reboot
:
5296 case QEMU_OPTION_no_shutdown
:
5299 case QEMU_OPTION_show_cursor
:
5302 case QEMU_OPTION_uuid
:
5303 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5304 fprintf(stderr
, "Fail to parse UUID string."
5305 " Wrong format.\n");
5310 case QEMU_OPTION_daemonize
:
5314 case QEMU_OPTION_option_rom
:
5315 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5316 fprintf(stderr
, "Too many option ROMs\n");
5319 option_rom
[nb_option_roms
] = optarg
;
5322 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5323 case QEMU_OPTION_semihosting
:
5324 semihosting_enabled
= 1;
5327 case QEMU_OPTION_name
:
5328 qemu_name
= qemu_strdup(optarg
);
5330 char *p
= strchr(qemu_name
, ',');
5333 if (strncmp(p
, "process=", 8)) {
5334 fprintf(stderr
, "Unknown subargument %s to -name", p
);
5342 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5343 case QEMU_OPTION_prom_env
:
5344 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5345 fprintf(stderr
, "Too many prom variables\n");
5348 prom_envs
[nb_prom_envs
] = optarg
;
5353 case QEMU_OPTION_old_param
:
5357 case QEMU_OPTION_clock
:
5358 configure_alarms(optarg
);
5360 case QEMU_OPTION_startdate
:
5363 time_t rtc_start_date
;
5364 if (!strcmp(optarg
, "now")) {
5365 rtc_date_offset
= -1;
5367 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
5375 } else if (sscanf(optarg
, "%d-%d-%d",
5378 &tm
.tm_mday
) == 3) {
5387 rtc_start_date
= mktimegm(&tm
);
5388 if (rtc_start_date
== -1) {
5390 fprintf(stderr
, "Invalid date format. Valid format are:\n"
5391 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5394 rtc_date_offset
= time(NULL
) - rtc_start_date
;
5398 case QEMU_OPTION_tb_size
:
5399 tb_size
= strtol(optarg
, NULL
, 0);
5403 case QEMU_OPTION_icount
:
5405 if (strcmp(optarg
, "auto") == 0) {
5406 icount_time_shift
= -1;
5408 icount_time_shift
= strtol(optarg
, NULL
, 0);
5411 case QEMU_OPTION_incoming
:
5415 case QEMU_OPTION_chroot
:
5416 chroot_dir
= optarg
;
5418 case QEMU_OPTION_runas
:
5423 case QEMU_OPTION_xen_domid
:
5424 xen_domid
= atoi(optarg
);
5426 case QEMU_OPTION_xen_create
:
5427 xen_mode
= XEN_CREATE
;
5429 case QEMU_OPTION_xen_attach
:
5430 xen_mode
= XEN_ATTACH
;
5437 /* If no data_dir is specified then try to find it relative to the
5440 data_dir
= find_datadir(argv
[0]);
5442 /* If all else fails use the install patch specified when building. */
5444 data_dir
= CONFIG_QEMU_SHAREDIR
;
5448 * Default to max_cpus = smp_cpus, in case the user doesn't
5449 * specify a max_cpus value.
5452 max_cpus
= smp_cpus
;
5454 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5455 if (smp_cpus
> machine
->max_cpus
) {
5456 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5457 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5462 if (display_type
== DT_NOGRAPHIC
) {
5463 if (serial_device_index
== 0)
5464 serial_devices
[0] = "stdio";
5465 if (parallel_device_index
== 0)
5466 parallel_devices
[0] = "null";
5467 if (strncmp(monitor_devices
[0], "vc", 2) == 0) {
5468 monitor_devices
[0] = "stdio";
5476 if (pipe(fds
) == -1)
5487 len
= read(fds
[0], &status
, 1);
5488 if (len
== -1 && (errno
== EINTR
))
5493 else if (status
== 1) {
5494 fprintf(stderr
, "Could not acquire pidfile\n");
5511 signal(SIGTSTP
, SIG_IGN
);
5512 signal(SIGTTOU
, SIG_IGN
);
5513 signal(SIGTTIN
, SIG_IGN
);
5516 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5519 write(fds
[1], &status
, 1);
5521 fprintf(stderr
, "Could not acquire pid file\n");
5526 if (kvm_enabled()) {
5529 ret
= kvm_init(smp_cpus
);
5531 fprintf(stderr
, "failed to initialize KVM\n");
5536 if (qemu_init_main_loop()) {
5537 fprintf(stderr
, "qemu_init_main_loop failed\n");
5540 linux_boot
= (kernel_filename
!= NULL
);
5542 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5543 fprintf(stderr
, "-append only allowed with -kernel option\n");
5547 if (!linux_boot
&& initrd_filename
!= NULL
) {
5548 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5553 /* Win32 doesn't support line-buffering and requires size >= 2 */
5554 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5558 if (init_timer_alarm() < 0) {
5559 fprintf(stderr
, "could not initialize alarm timer\n");
5562 if (use_icount
&& icount_time_shift
< 0) {
5564 /* 125MIPS seems a reasonable initial guess at the guest speed.
5565 It will be corrected fairly quickly anyway. */
5566 icount_time_shift
= 3;
5567 init_icount_adjust();
5574 /* init network clients */
5575 if (nb_net_clients
== 0) {
5576 /* if no clients, we use a default config */
5577 net_clients
[nb_net_clients
++] = "nic";
5579 net_clients
[nb_net_clients
++] = "user";
5583 for(i
= 0;i
< nb_net_clients
; i
++) {
5584 if (net_client_parse(net_clients
[i
]) < 0)
5588 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5589 net_set_boot_mask(net_boot
);
5593 /* init the bluetooth world */
5594 if (foreach_device_config(DEV_BT
, bt_parse
))
5597 /* init the memory */
5599 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5601 /* init the dynamic translator */
5602 cpu_exec_init_all(tb_size
* 1024 * 1024);
5606 /* we always create the cdrom drive, even if no disk is there */
5607 drive_add(NULL
, CDROM_ALIAS
);
5609 /* we always create at least one floppy */
5610 drive_add(NULL
, FD_ALIAS
, 0);
5612 /* we always create one sd slot, even if no card is in it */
5613 drive_add(NULL
, SD_ALIAS
);
5615 /* open the virtual block devices */
5617 qemu_opts_foreach(&qemu_drive_opts
, drive_enable_snapshot
, NULL
, 0);
5618 if (qemu_opts_foreach(&qemu_drive_opts
, drive_init_func
, machine
, 1) != 0)
5621 vmstate_register(0, &vmstate_timers
,&timers_state
);
5622 register_savevm_live("ram", 0, 3, ram_save_live
, NULL
, ram_load
, NULL
);
5624 /* Maintain compatibility with multiple stdio monitors */
5625 if (!strcmp(monitor_devices
[0],"stdio")) {
5626 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5627 const char *devname
= serial_devices
[i
];
5628 if (devname
&& !strcmp(devname
,"mon:stdio")) {
5629 monitor_devices
[0] = NULL
;
5631 } else if (devname
&& !strcmp(devname
,"stdio")) {
5632 monitor_devices
[0] = NULL
;
5633 serial_devices
[i
] = "mon:stdio";
5639 if (nb_numa_nodes
> 0) {
5642 if (nb_numa_nodes
> smp_cpus
) {
5643 nb_numa_nodes
= smp_cpus
;
5646 /* If no memory size if given for any node, assume the default case
5647 * and distribute the available memory equally across all nodes
5649 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5650 if (node_mem
[i
] != 0)
5653 if (i
== nb_numa_nodes
) {
5654 uint64_t usedmem
= 0;
5656 /* On Linux, the each node's border has to be 8MB aligned,
5657 * the final node gets the rest.
5659 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
5660 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
5661 usedmem
+= node_mem
[i
];
5663 node_mem
[i
] = ram_size
- usedmem
;
5666 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5667 if (node_cpumask
[i
] != 0)
5670 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5671 * must cope with this anyway, because there are BIOSes out there in
5672 * real machines which also use this scheme.
5674 if (i
== nb_numa_nodes
) {
5675 for (i
= 0; i
< smp_cpus
; i
++) {
5676 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
5681 for (i
= 0; i
< MAX_MONITOR_DEVICES
; i
++) {
5682 const char *devname
= monitor_devices
[i
];
5683 if (devname
&& strcmp(devname
, "none")) {
5686 snprintf(label
, sizeof(label
), "monitor");
5688 snprintf(label
, sizeof(label
), "monitor%d", i
);
5690 monitor_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5691 if (!monitor_hds
[i
]) {
5692 fprintf(stderr
, "qemu: could not open monitor device '%s'\n",
5699 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5700 const char *devname
= serial_devices
[i
];
5701 if (devname
&& strcmp(devname
, "none")) {
5703 snprintf(label
, sizeof(label
), "serial%d", i
);
5704 serial_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5705 if (!serial_hds
[i
]) {
5706 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
5713 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
5714 const char *devname
= parallel_devices
[i
];
5715 if (devname
&& strcmp(devname
, "none")) {
5717 snprintf(label
, sizeof(label
), "parallel%d", i
);
5718 parallel_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5719 if (!parallel_hds
[i
]) {
5720 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
5727 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
5728 const char *devname
= virtio_consoles
[i
];
5729 if (devname
&& strcmp(devname
, "none")) {
5731 snprintf(label
, sizeof(label
), "virtcon%d", i
);
5732 virtcon_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5733 if (!virtcon_hds
[i
]) {
5734 fprintf(stderr
, "qemu: could not open virtio console '%s'\n",
5741 module_call_init(MODULE_INIT_DEVICE
);
5744 i
= select_watchdog(watchdog
);
5746 exit (i
== 1 ? 1 : 0);
5749 if (machine
->compat_props
) {
5750 qdev_prop_register_compat(machine
->compat_props
);
5752 machine
->init(ram_size
, boot_devices
,
5753 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
5757 /* must be after terminal init, SDL library changes signal handlers */
5761 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
5762 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5763 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
5769 current_machine
= machine
;
5771 /* init USB devices */
5773 foreach_device_config(DEV_USB
, usb_parse
);
5776 /* init generic devices */
5777 if (qemu_opts_foreach(&qemu_device_opts
, device_init_func
, NULL
, 1) != 0)
5781 dumb_display_init();
5782 /* just use the first displaystate for the moment */
5785 if (display_type
== DT_DEFAULT
) {
5786 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5787 display_type
= DT_SDL
;
5789 display_type
= DT_VNC
;
5790 vnc_display
= "localhost:0,to=99";
5796 switch (display_type
) {
5799 #if defined(CONFIG_CURSES)
5801 curses_display_init(ds
, full_screen
);
5804 #if defined(CONFIG_SDL)
5806 sdl_display_init(ds
, full_screen
, no_frame
);
5808 #elif defined(CONFIG_COCOA)
5810 cocoa_display_init(ds
, full_screen
);
5814 vnc_display_init(ds
);
5815 if (vnc_display_open(ds
, vnc_display
) < 0)
5818 if (show_vnc_port
) {
5819 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
5827 dcl
= ds
->listeners
;
5828 while (dcl
!= NULL
) {
5829 if (dcl
->dpy_refresh
!= NULL
) {
5830 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
5831 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
5836 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
5837 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
5838 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
5841 text_consoles_set_display(display_state
);
5842 qemu_chr_initial_reset();
5844 for (i
= 0; i
< MAX_MONITOR_DEVICES
; i
++) {
5845 if (monitor_devices
[i
] && monitor_hds
[i
]) {
5846 monitor_init(monitor_hds
[i
],
5847 MONITOR_USE_READLINE
|
5848 ((i
== 0) ? MONITOR_IS_DEFAULT
: 0));
5852 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5853 const char *devname
= serial_devices
[i
];
5854 if (devname
&& strcmp(devname
, "none")) {
5855 if (strstart(devname
, "vc", 0))
5856 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
5860 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
5861 const char *devname
= parallel_devices
[i
];
5862 if (devname
&& strcmp(devname
, "none")) {
5863 if (strstart(devname
, "vc", 0))
5864 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
5868 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
5869 const char *devname
= virtio_consoles
[i
];
5870 if (virtcon_hds
[i
] && devname
) {
5871 if (strstart(devname
, "vc", 0))
5872 qemu_chr_printf(virtcon_hds
[i
], "virtio console%d\r\n", i
);
5876 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
5877 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
5883 if (load_vmstate(cur_mon
, loadvm
) < 0) {
5889 qemu_start_incoming_migration(incoming
);
5890 } else if (autostart
) {
5900 len
= write(fds
[1], &status
, 1);
5901 if (len
== -1 && (errno
== EINTR
))
5908 TFR(fd
= open("/dev/null", O_RDWR
));
5914 pwd
= getpwnam(run_as
);
5916 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
5922 if (chroot(chroot_dir
) < 0) {
5923 fprintf(stderr
, "chroot failed\n");
5930 if (setgid(pwd
->pw_gid
) < 0) {
5931 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
5934 if (setuid(pwd
->pw_uid
) < 0) {
5935 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
5938 if (setuid(0) != -1) {
5939 fprintf(stderr
, "Dropping privileges failed\n");