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_TIMER_REALTIME 0
680 #define QEMU_TIMER_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_TIMER_REALTIME
:
1029 return get_clock() / 1000000;
1031 case QEMU_TIMER_VIRTUAL
:
1033 return cpu_get_icount();
1035 return cpu_get_clock();
1040 static void init_timers(void)
1043 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1044 vm_clock
= qemu_new_clock(QEMU_TIMER_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_TIMER_VIRTUAL
],
1127 qemu_get_clock(vm_clock
))) ||
1128 qemu_timer_expired(active_timers
[QEMU_TIMER_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_TIMER_VIRTUAL
]) {
1149 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1150 qemu_get_clock(vm_clock
);
1152 /* To avoid problems with overflow limit this to 2^32. */
1162 #if defined(__linux__) || defined(_WIN32)
1163 static uint64_t qemu_next_deadline_dyntick(void)
1171 delta
= (qemu_next_deadline() + 999) / 1000;
1173 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1174 rtdelta
= (active_timers
[QEMU_TIMER_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_TIMER_REALTIME
] &&
1357 !active_timers
[QEMU_TIMER_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
;
1471 uint64_t nearest_delta_us
;
1473 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1474 !active_timers
[QEMU_TIMER_VIRTUAL
])
1477 nearest_delta_us
= qemu_next_deadline_dyntick();
1478 nearest_delta_us
/= 1000;
1480 timeKillEvent(data
->timerId
);
1482 data
->timerId
= timeSetEvent(1,
1486 TIME_ONESHOT
| TIME_PERIODIC
);
1488 if (!data
->timerId
) {
1489 fprintf(stderr
, "Failed to re-arm win32 alarm timer %ld\n",
1492 timeEndPeriod(data
->period
);
1499 static int init_timer_alarm(void)
1501 struct qemu_alarm_timer
*t
= NULL
;
1504 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1505 t
= &alarm_timers
[i
];
1525 static void quit_timers(void)
1527 alarm_timer
->stop(alarm_timer
);
1531 /***********************************************************/
1532 /* host time/date access */
1533 void qemu_get_timedate(struct tm
*tm
, int offset
)
1540 if (rtc_date_offset
== -1) {
1544 ret
= localtime(&ti
);
1546 ti
-= rtc_date_offset
;
1550 memcpy(tm
, ret
, sizeof(struct tm
));
1553 int qemu_timedate_diff(struct tm
*tm
)
1557 if (rtc_date_offset
== -1)
1559 seconds
= mktimegm(tm
);
1561 seconds
= mktime(tm
);
1563 seconds
= mktimegm(tm
) + rtc_date_offset
;
1565 return seconds
- time(NULL
);
1569 static void socket_cleanup(void)
1574 static int socket_init(void)
1579 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1581 err
= WSAGetLastError();
1582 fprintf(stderr
, "WSAStartup: %d\n", err
);
1585 atexit(socket_cleanup
);
1590 /***********************************************************/
1591 /* Bluetooth support */
1594 static struct HCIInfo
*hci_table
[MAX_NICS
];
1596 static struct bt_vlan_s
{
1597 struct bt_scatternet_s net
;
1599 struct bt_vlan_s
*next
;
1602 /* find or alloc a new bluetooth "VLAN" */
1603 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1605 struct bt_vlan_s
**pvlan
, *vlan
;
1606 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1610 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1612 pvlan
= &first_bt_vlan
;
1613 while (*pvlan
!= NULL
)
1614 pvlan
= &(*pvlan
)->next
;
1619 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1623 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1628 static struct HCIInfo null_hci
= {
1629 .cmd_send
= null_hci_send
,
1630 .sco_send
= null_hci_send
,
1631 .acl_send
= null_hci_send
,
1632 .bdaddr_set
= null_hci_addr_set
,
1635 struct HCIInfo
*qemu_next_hci(void)
1637 if (cur_hci
== nb_hcis
)
1640 return hci_table
[cur_hci
++];
1643 static struct HCIInfo
*hci_init(const char *str
)
1646 struct bt_scatternet_s
*vlan
= 0;
1648 if (!strcmp(str
, "null"))
1651 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
1653 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
1654 else if (!strncmp(str
, "hci", 3)) {
1657 if (!strncmp(str
+ 3, ",vlan=", 6)) {
1658 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
1663 vlan
= qemu_find_bt_vlan(0);
1665 return bt_new_hci(vlan
);
1668 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
1673 static int bt_hci_parse(const char *str
)
1675 struct HCIInfo
*hci
;
1678 if (nb_hcis
>= MAX_NICS
) {
1679 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
1683 hci
= hci_init(str
);
1692 bdaddr
.b
[5] = 0x56 + nb_hcis
;
1693 hci
->bdaddr_set(hci
, bdaddr
.b
);
1695 hci_table
[nb_hcis
++] = hci
;
1700 static void bt_vhci_add(int vlan_id
)
1702 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
1705 fprintf(stderr
, "qemu: warning: adding a VHCI to "
1706 "an empty scatternet %i\n", vlan_id
);
1708 bt_vhci_init(bt_new_hci(vlan
));
1711 static struct bt_device_s
*bt_device_add(const char *opt
)
1713 struct bt_scatternet_s
*vlan
;
1715 char *endp
= strstr(opt
, ",vlan=");
1716 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
1719 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
1722 vlan_id
= strtol(endp
+ 6, &endp
, 0);
1724 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
1729 vlan
= qemu_find_bt_vlan(vlan_id
);
1732 fprintf(stderr
, "qemu: warning: adding a slave device to "
1733 "an empty scatternet %i\n", vlan_id
);
1735 if (!strcmp(devname
, "keyboard"))
1736 return bt_keyboard_init(vlan
);
1738 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
1742 static int bt_parse(const char *opt
)
1744 const char *endp
, *p
;
1747 if (strstart(opt
, "hci", &endp
)) {
1748 if (!*endp
|| *endp
== ',') {
1750 if (!strstart(endp
, ",vlan=", 0))
1753 return bt_hci_parse(opt
);
1755 } else if (strstart(opt
, "vhci", &endp
)) {
1756 if (!*endp
|| *endp
== ',') {
1758 if (strstart(endp
, ",vlan=", &p
)) {
1759 vlan
= strtol(p
, (char **) &endp
, 0);
1761 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
1765 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
1774 } else if (strstart(opt
, "device:", &endp
))
1775 return !bt_device_add(endp
);
1777 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
1781 /***********************************************************/
1782 /* QEMU Block devices */
1784 #define HD_ALIAS "index=%d,media=disk"
1785 #define CDROM_ALIAS "index=2,media=cdrom"
1786 #define FD_ALIAS "index=%d,if=floppy"
1787 #define PFLASH_ALIAS "if=pflash"
1788 #define MTD_ALIAS "if=mtd"
1789 #define SD_ALIAS "index=0,if=sd"
1791 QemuOpts
*drive_add(const char *file
, const char *fmt
, ...)
1798 vsnprintf(optstr
, sizeof(optstr
), fmt
, ap
);
1801 opts
= qemu_opts_parse(&qemu_drive_opts
, optstr
, NULL
);
1803 fprintf(stderr
, "%s: huh? duplicate? (%s)\n",
1804 __FUNCTION__
, optstr
);
1808 qemu_opt_set(opts
, "file", file
);
1812 DriveInfo
*drive_get(BlockInterfaceType type
, int bus
, int unit
)
1816 /* seek interface, bus and unit */
1818 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1819 if (dinfo
->type
== type
&&
1820 dinfo
->bus
== bus
&&
1821 dinfo
->unit
== unit
)
1828 DriveInfo
*drive_get_by_id(const char *id
)
1832 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1833 if (strcmp(id
, dinfo
->id
))
1840 int drive_get_max_bus(BlockInterfaceType type
)
1846 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1847 if(dinfo
->type
== type
&&
1848 dinfo
->bus
> max_bus
)
1849 max_bus
= dinfo
->bus
;
1854 const char *drive_get_serial(BlockDriverState
*bdrv
)
1858 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1859 if (dinfo
->bdrv
== bdrv
)
1860 return dinfo
->serial
;
1866 BlockInterfaceErrorAction
drive_get_onerror(BlockDriverState
*bdrv
)
1870 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1871 if (dinfo
->bdrv
== bdrv
)
1872 return dinfo
->onerror
;
1875 return BLOCK_ERR_STOP_ENOSPC
;
1878 static void bdrv_format_print(void *opaque
, const char *name
)
1880 fprintf(stderr
, " %s", name
);
1883 void drive_uninit(BlockDriverState
*bdrv
)
1887 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1888 if (dinfo
->bdrv
!= bdrv
)
1890 qemu_opts_del(dinfo
->opts
);
1891 QTAILQ_REMOVE(&drives
, dinfo
, next
);
1897 DriveInfo
*drive_init(QemuOpts
*opts
, void *opaque
,
1901 const char *file
= NULL
;
1904 const char *mediastr
= "";
1905 BlockInterfaceType type
;
1906 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
1907 int bus_id
, unit_id
;
1908 int cyls
, heads
, secs
, translation
;
1909 BlockDriver
*drv
= NULL
;
1910 QEMUMachine
*machine
= opaque
;
1915 int bdrv_flags
, onerror
;
1916 const char *devaddr
;
1922 translation
= BIOS_ATA_TRANSLATION_AUTO
;
1925 if (machine
&& machine
->use_scsi
) {
1927 max_devs
= MAX_SCSI_DEVS
;
1928 pstrcpy(devname
, sizeof(devname
), "scsi");
1931 max_devs
= MAX_IDE_DEVS
;
1932 pstrcpy(devname
, sizeof(devname
), "ide");
1936 /* extract parameters */
1937 bus_id
= qemu_opt_get_number(opts
, "bus", 0);
1938 unit_id
= qemu_opt_get_number(opts
, "unit", -1);
1939 index
= qemu_opt_get_number(opts
, "index", -1);
1941 cyls
= qemu_opt_get_number(opts
, "cyls", 0);
1942 heads
= qemu_opt_get_number(opts
, "heads", 0);
1943 secs
= qemu_opt_get_number(opts
, "secs", 0);
1945 snapshot
= qemu_opt_get_bool(opts
, "snapshot", 0);
1947 file
= qemu_opt_get(opts
, "file");
1948 serial
= qemu_opt_get(opts
, "serial");
1950 if ((buf
= qemu_opt_get(opts
, "if")) != NULL
) {
1951 pstrcpy(devname
, sizeof(devname
), buf
);
1952 if (!strcmp(buf
, "ide")) {
1954 max_devs
= MAX_IDE_DEVS
;
1955 } else if (!strcmp(buf
, "scsi")) {
1957 max_devs
= MAX_SCSI_DEVS
;
1958 } else if (!strcmp(buf
, "floppy")) {
1961 } else if (!strcmp(buf
, "pflash")) {
1964 } else if (!strcmp(buf
, "mtd")) {
1967 } else if (!strcmp(buf
, "sd")) {
1970 } else if (!strcmp(buf
, "virtio")) {
1973 } else if (!strcmp(buf
, "xen")) {
1976 } else if (!strcmp(buf
, "none")) {
1980 fprintf(stderr
, "qemu: unsupported bus type '%s'\n", buf
);
1985 if (cyls
|| heads
|| secs
) {
1986 if (cyls
< 1 || cyls
> 16383) {
1987 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", buf
);
1990 if (heads
< 1 || heads
> 16) {
1991 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", buf
);
1994 if (secs
< 1 || secs
> 63) {
1995 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", buf
);
2000 if ((buf
= qemu_opt_get(opts
, "trans")) != NULL
) {
2003 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2007 if (!strcmp(buf
, "none"))
2008 translation
= BIOS_ATA_TRANSLATION_NONE
;
2009 else if (!strcmp(buf
, "lba"))
2010 translation
= BIOS_ATA_TRANSLATION_LBA
;
2011 else if (!strcmp(buf
, "auto"))
2012 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2014 fprintf(stderr
, "qemu: '%s' invalid translation type\n", buf
);
2019 if ((buf
= qemu_opt_get(opts
, "media")) != NULL
) {
2020 if (!strcmp(buf
, "disk")) {
2022 } else if (!strcmp(buf
, "cdrom")) {
2023 if (cyls
|| secs
|| heads
) {
2025 "qemu: '%s' invalid physical CHS format\n", buf
);
2028 media
= MEDIA_CDROM
;
2030 fprintf(stderr
, "qemu: '%s' invalid media\n", buf
);
2035 if ((buf
= qemu_opt_get(opts
, "cache")) != NULL
) {
2036 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2038 else if (!strcmp(buf
, "writethrough"))
2040 else if (!strcmp(buf
, "writeback"))
2043 fprintf(stderr
, "qemu: invalid cache option\n");
2048 #ifdef CONFIG_LINUX_AIO
2049 if ((buf
= qemu_opt_get(opts
, "aio")) != NULL
) {
2050 if (!strcmp(buf
, "threads"))
2052 else if (!strcmp(buf
, "native"))
2055 fprintf(stderr
, "qemu: invalid aio option\n");
2061 if ((buf
= qemu_opt_get(opts
, "format")) != NULL
) {
2062 if (strcmp(buf
, "?") == 0) {
2063 fprintf(stderr
, "qemu: Supported formats:");
2064 bdrv_iterate_format(bdrv_format_print
, NULL
);
2065 fprintf(stderr
, "\n");
2068 drv
= bdrv_find_format(buf
);
2070 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2075 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2076 if ((buf
= qemu_opt_get(opts
, "werror")) != NULL
) {
2077 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2078 fprintf(stderr
, "werror is no supported by this format\n");
2081 if (!strcmp(buf
, "ignore"))
2082 onerror
= BLOCK_ERR_IGNORE
;
2083 else if (!strcmp(buf
, "enospc"))
2084 onerror
= BLOCK_ERR_STOP_ENOSPC
;
2085 else if (!strcmp(buf
, "stop"))
2086 onerror
= BLOCK_ERR_STOP_ANY
;
2087 else if (!strcmp(buf
, "report"))
2088 onerror
= BLOCK_ERR_REPORT
;
2090 fprintf(stderr
, "qemu: '%s' invalid write error action\n", buf
);
2095 if ((devaddr
= qemu_opt_get(opts
, "addr")) != NULL
) {
2096 if (type
!= IF_VIRTIO
) {
2097 fprintf(stderr
, "addr is not supported\n");
2102 /* compute bus and unit according index */
2105 if (bus_id
!= 0 || unit_id
!= -1) {
2107 "qemu: index cannot be used with bus and unit\n");
2115 unit_id
= index
% max_devs
;
2116 bus_id
= index
/ max_devs
;
2120 /* if user doesn't specify a unit_id,
2121 * try to find the first free
2124 if (unit_id
== -1) {
2126 while (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2128 if (max_devs
&& unit_id
>= max_devs
) {
2129 unit_id
-= max_devs
;
2137 if (max_devs
&& unit_id
>= max_devs
) {
2138 fprintf(stderr
, "qemu: unit %d too big (max is %d)\n",
2139 unit_id
, max_devs
- 1);
2144 * ignore multiple definitions
2147 if (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2154 dinfo
= qemu_mallocz(sizeof(*dinfo
));
2155 if ((buf
= qemu_opts_id(opts
)) != NULL
) {
2156 dinfo
->id
= qemu_strdup(buf
);
2158 /* no id supplied -> create one */
2159 dinfo
->id
= qemu_mallocz(32);
2160 if (type
== IF_IDE
|| type
== IF_SCSI
)
2161 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2163 snprintf(dinfo
->id
, 32, "%s%i%s%i",
2164 devname
, bus_id
, mediastr
, unit_id
);
2166 snprintf(dinfo
->id
, 32, "%s%s%i",
2167 devname
, mediastr
, unit_id
);
2169 dinfo
->bdrv
= bdrv_new(dinfo
->id
);
2170 dinfo
->devaddr
= devaddr
;
2172 dinfo
->bus
= bus_id
;
2173 dinfo
->unit
= unit_id
;
2174 dinfo
->onerror
= onerror
;
2177 strncpy(dinfo
->serial
, serial
, sizeof(serial
));
2178 QTAILQ_INSERT_TAIL(&drives
, dinfo
, next
);
2188 bdrv_set_geometry_hint(dinfo
->bdrv
, cyls
, heads
, secs
);
2189 bdrv_set_translation_hint(dinfo
->bdrv
, translation
);
2193 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_CDROM
);
2198 /* FIXME: This isn't really a floppy, but it's a reasonable
2201 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_FLOPPY
);
2207 /* add virtio block device */
2208 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
2209 qemu_opt_set(opts
, "driver", "virtio-blk-pci");
2210 qemu_opt_set(opts
, "drive", dinfo
->id
);
2212 qemu_opt_set(opts
, "addr", devaddr
);
2223 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2224 cache
= 2; /* always use write-back with snapshot */
2226 if (cache
== 0) /* no caching */
2227 bdrv_flags
|= BDRV_O_NOCACHE
;
2228 else if (cache
== 2) /* write-back */
2229 bdrv_flags
|= BDRV_O_CACHE_WB
;
2232 bdrv_flags
|= BDRV_O_NATIVE_AIO
;
2234 bdrv_flags
&= ~BDRV_O_NATIVE_AIO
;
2237 if (bdrv_open2(dinfo
->bdrv
, file
, bdrv_flags
, drv
) < 0) {
2238 fprintf(stderr
, "qemu: could not open disk image %s\n",
2243 if (bdrv_key_required(dinfo
->bdrv
))
2249 static int drive_init_func(QemuOpts
*opts
, void *opaque
)
2251 QEMUMachine
*machine
= opaque
;
2252 int fatal_error
= 0;
2254 if (drive_init(opts
, machine
, &fatal_error
) == NULL
) {
2261 static int drive_enable_snapshot(QemuOpts
*opts
, void *opaque
)
2263 if (NULL
== qemu_opt_get(opts
, "snapshot")) {
2264 qemu_opt_set(opts
, "snapshot", "on");
2269 void qemu_register_boot_set(QEMUBootSetHandler
*func
, void *opaque
)
2271 boot_set_handler
= func
;
2272 boot_set_opaque
= opaque
;
2275 int qemu_boot_set(const char *boot_devices
)
2277 if (!boot_set_handler
) {
2280 return boot_set_handler(boot_set_opaque
, boot_devices
);
2283 static int parse_bootdevices(char *devices
)
2285 /* We just do some generic consistency checks */
2289 for (p
= devices
; *p
!= '\0'; p
++) {
2290 /* Allowed boot devices are:
2291 * a-b: floppy disk drives
2292 * c-f: IDE disk drives
2293 * g-m: machine implementation dependant drives
2294 * n-p: network devices
2295 * It's up to each machine implementation to check if the given boot
2296 * devices match the actual hardware implementation and firmware
2299 if (*p
< 'a' || *p
> 'p') {
2300 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
2303 if (bitmap
& (1 << (*p
- 'a'))) {
2304 fprintf(stderr
, "Boot device '%c' was given twice\n", *p
);
2307 bitmap
|= 1 << (*p
- 'a');
2312 static void restore_boot_devices(void *opaque
)
2314 char *standard_boot_devices
= opaque
;
2316 qemu_boot_set(standard_boot_devices
);
2318 qemu_unregister_reset(restore_boot_devices
, standard_boot_devices
);
2319 qemu_free(standard_boot_devices
);
2322 static void numa_add(const char *optarg
)
2326 unsigned long long value
, endvalue
;
2329 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2330 if (!strcmp(option
, "node")) {
2331 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2332 nodenr
= nb_numa_nodes
;
2334 nodenr
= strtoull(option
, NULL
, 10);
2337 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2338 node_mem
[nodenr
] = 0;
2340 value
= strtoull(option
, &endptr
, 0);
2342 case 0: case 'M': case 'm':
2349 node_mem
[nodenr
] = value
;
2351 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2352 node_cpumask
[nodenr
] = 0;
2354 value
= strtoull(option
, &endptr
, 10);
2357 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2359 if (*endptr
== '-') {
2360 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2361 if (endvalue
>= 63) {
2364 "only 63 CPUs in NUMA mode supported.\n");
2366 value
= (1 << (endvalue
+ 1)) - (1 << value
);
2371 node_cpumask
[nodenr
] = value
;
2378 static void smp_parse(const char *optarg
)
2380 int smp
, sockets
= 0, threads
= 0, cores
= 0;
2384 smp
= strtoul(optarg
, &endptr
, 10);
2385 if (endptr
!= optarg
) {
2386 if (*endptr
== ',') {
2390 if (get_param_value(option
, 128, "sockets", endptr
) != 0)
2391 sockets
= strtoull(option
, NULL
, 10);
2392 if (get_param_value(option
, 128, "cores", endptr
) != 0)
2393 cores
= strtoull(option
, NULL
, 10);
2394 if (get_param_value(option
, 128, "threads", endptr
) != 0)
2395 threads
= strtoull(option
, NULL
, 10);
2396 if (get_param_value(option
, 128, "maxcpus", endptr
) != 0)
2397 max_cpus
= strtoull(option
, NULL
, 10);
2399 /* compute missing values, prefer sockets over cores over threads */
2400 if (smp
== 0 || sockets
== 0) {
2401 sockets
= sockets
> 0 ? sockets
: 1;
2402 cores
= cores
> 0 ? cores
: 1;
2403 threads
= threads
> 0 ? threads
: 1;
2405 smp
= cores
* threads
* sockets
;
2407 sockets
= smp
/ (cores
* threads
);
2411 threads
= threads
> 0 ? threads
: 1;
2412 cores
= smp
/ (sockets
* threads
);
2415 sockets
= smp
/ (cores
* threads
);
2417 threads
= smp
/ (cores
* sockets
);
2422 smp_cores
= cores
> 0 ? cores
: 1;
2423 smp_threads
= threads
> 0 ? threads
: 1;
2425 max_cpus
= smp_cpus
;
2428 /***********************************************************/
2431 static void usb_msd_password_cb(void *opaque
, int err
)
2433 USBDevice
*dev
= opaque
;
2436 usb_device_attach(dev
);
2438 dev
->info
->handle_destroy(dev
);
2447 .qdev
= "QEMU USB Mouse",
2450 .qdev
= "QEMU USB Tablet",
2453 .qdev
= "QEMU USB Keyboard",
2455 .name
= "wacom-tablet",
2456 .qdev
= "QEMU PenPartner Tablet",
2460 static int usb_device_add(const char *devname
, int is_hotplug
)
2463 USBBus
*bus
= usb_bus_find(-1 /* any */);
2464 USBDevice
*dev
= NULL
;
2470 /* simple devices which don't need extra care */
2471 for (i
= 0; i
< ARRAY_SIZE(usbdevs
); i
++) {
2472 if (strcmp(devname
, usbdevs
[i
].name
) != 0)
2474 dev
= usb_create_simple(bus
, usbdevs
[i
].qdev
);
2478 /* the other ones */
2479 if (strstart(devname
, "host:", &p
)) {
2480 dev
= usb_host_device_open(p
);
2481 } else if (strstart(devname
, "disk:", &p
)) {
2482 BlockDriverState
*bs
;
2484 dev
= usb_msd_init(p
);
2487 bs
= usb_msd_get_bdrv(dev
);
2488 if (bdrv_key_required(bs
)) {
2491 monitor_read_bdrv_key_start(cur_mon
, bs
, usb_msd_password_cb
,
2496 } else if (strstart(devname
, "serial:", &p
)) {
2497 dev
= usb_serial_init(p
);
2498 #ifdef CONFIG_BRLAPI
2499 } else if (!strcmp(devname
, "braille")) {
2500 dev
= usb_baum_init();
2502 } else if (strstart(devname
, "net:", &p
)) {
2505 if (net_client_init(NULL
, "nic", p
) < 0)
2507 nd_table
[nic
].model
= "usb";
2508 dev
= usb_net_init(&nd_table
[nic
]);
2509 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2510 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2511 bt_new_hci(qemu_find_bt_vlan(0)));
2522 static int usb_device_del(const char *devname
)
2527 if (strstart(devname
, "host:", &p
))
2528 return usb_host_device_close(p
);
2533 p
= strchr(devname
, '.');
2536 bus_num
= strtoul(devname
, NULL
, 0);
2537 addr
= strtoul(p
+ 1, NULL
, 0);
2539 return usb_device_delete_addr(bus_num
, addr
);
2542 static int usb_parse(const char *cmdline
)
2544 return usb_device_add(cmdline
, 0);
2547 void do_usb_add(Monitor
*mon
, const QDict
*qdict
)
2549 usb_device_add(qdict_get_str(qdict
, "devname"), 1);
2552 void do_usb_del(Monitor
*mon
, const QDict
*qdict
)
2554 usb_device_del(qdict_get_str(qdict
, "devname"));
2557 /***********************************************************/
2558 /* PCMCIA/Cardbus */
2560 static struct pcmcia_socket_entry_s
{
2561 PCMCIASocket
*socket
;
2562 struct pcmcia_socket_entry_s
*next
;
2563 } *pcmcia_sockets
= 0;
2565 void pcmcia_socket_register(PCMCIASocket
*socket
)
2567 struct pcmcia_socket_entry_s
*entry
;
2569 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2570 entry
->socket
= socket
;
2571 entry
->next
= pcmcia_sockets
;
2572 pcmcia_sockets
= entry
;
2575 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2577 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2579 ptr
= &pcmcia_sockets
;
2580 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2581 if (entry
->socket
== socket
) {
2587 void pcmcia_info(Monitor
*mon
)
2589 struct pcmcia_socket_entry_s
*iter
;
2591 if (!pcmcia_sockets
)
2592 monitor_printf(mon
, "No PCMCIA sockets\n");
2594 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2595 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2596 iter
->socket
->attached
? iter
->socket
->card_string
:
2600 /***********************************************************/
2601 /* register display */
2603 struct DisplayAllocator default_allocator
= {
2604 defaultallocator_create_displaysurface
,
2605 defaultallocator_resize_displaysurface
,
2606 defaultallocator_free_displaysurface
2609 void register_displaystate(DisplayState
*ds
)
2619 DisplayState
*get_displaystate(void)
2621 return display_state
;
2624 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
2626 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
2627 return ds
->allocator
;
2632 static void dumb_display_init(void)
2634 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
2635 ds
->allocator
= &default_allocator
;
2636 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
2637 register_displaystate(ds
);
2640 /***********************************************************/
2643 typedef struct IOHandlerRecord
{
2645 IOCanRWHandler
*fd_read_poll
;
2647 IOHandler
*fd_write
;
2650 /* temporary data */
2652 struct IOHandlerRecord
*next
;
2655 static IOHandlerRecord
*first_io_handler
;
2657 /* XXX: fd_read_poll should be suppressed, but an API change is
2658 necessary in the character devices to suppress fd_can_read(). */
2659 int qemu_set_fd_handler2(int fd
,
2660 IOCanRWHandler
*fd_read_poll
,
2662 IOHandler
*fd_write
,
2665 IOHandlerRecord
**pioh
, *ioh
;
2667 if (!fd_read
&& !fd_write
) {
2668 pioh
= &first_io_handler
;
2673 if (ioh
->fd
== fd
) {
2680 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
2684 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
2685 ioh
->next
= first_io_handler
;
2686 first_io_handler
= ioh
;
2689 ioh
->fd_read_poll
= fd_read_poll
;
2690 ioh
->fd_read
= fd_read
;
2691 ioh
->fd_write
= fd_write
;
2692 ioh
->opaque
= opaque
;
2698 int qemu_set_fd_handler(int fd
,
2700 IOHandler
*fd_write
,
2703 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
2707 /***********************************************************/
2708 /* Polling handling */
2710 typedef struct PollingEntry
{
2713 struct PollingEntry
*next
;
2716 static PollingEntry
*first_polling_entry
;
2718 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
2720 PollingEntry
**ppe
, *pe
;
2721 pe
= qemu_mallocz(sizeof(PollingEntry
));
2723 pe
->opaque
= opaque
;
2724 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
2729 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
2731 PollingEntry
**ppe
, *pe
;
2732 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
2734 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
2742 /***********************************************************/
2743 /* Wait objects support */
2744 typedef struct WaitObjects
{
2746 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
2747 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
2748 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
2751 static WaitObjects wait_objects
= {0};
2753 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2755 WaitObjects
*w
= &wait_objects
;
2757 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
2759 w
->events
[w
->num
] = handle
;
2760 w
->func
[w
->num
] = func
;
2761 w
->opaque
[w
->num
] = opaque
;
2766 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2769 WaitObjects
*w
= &wait_objects
;
2772 for (i
= 0; i
< w
->num
; i
++) {
2773 if (w
->events
[i
] == handle
)
2776 w
->events
[i
] = w
->events
[i
+ 1];
2777 w
->func
[i
] = w
->func
[i
+ 1];
2778 w
->opaque
[i
] = w
->opaque
[i
+ 1];
2786 /***********************************************************/
2787 /* ram save/restore */
2789 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2790 #define RAM_SAVE_FLAG_COMPRESS 0x02
2791 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2792 #define RAM_SAVE_FLAG_PAGE 0x08
2793 #define RAM_SAVE_FLAG_EOS 0x10
2795 static int is_dup_page(uint8_t *page
, uint8_t ch
)
2797 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
2798 uint32_t *array
= (uint32_t *)page
;
2801 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
2802 if (array
[i
] != val
)
2809 static int ram_save_block(QEMUFile
*f
)
2811 static ram_addr_t current_addr
= 0;
2812 ram_addr_t saved_addr
= current_addr
;
2813 ram_addr_t addr
= 0;
2816 while (addr
< last_ram_offset
) {
2817 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
2820 cpu_physical_memory_reset_dirty(current_addr
,
2821 current_addr
+ TARGET_PAGE_SIZE
,
2822 MIGRATION_DIRTY_FLAG
);
2824 p
= qemu_get_ram_ptr(current_addr
);
2826 if (is_dup_page(p
, *p
)) {
2827 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
2828 qemu_put_byte(f
, *p
);
2830 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
2831 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
2837 addr
+= TARGET_PAGE_SIZE
;
2838 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
2844 static uint64_t bytes_transferred
= 0;
2846 static ram_addr_t
ram_save_remaining(void)
2849 ram_addr_t count
= 0;
2851 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2852 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2859 uint64_t ram_bytes_remaining(void)
2861 return ram_save_remaining() * TARGET_PAGE_SIZE
;
2864 uint64_t ram_bytes_transferred(void)
2866 return bytes_transferred
;
2869 uint64_t ram_bytes_total(void)
2871 return last_ram_offset
;
2874 static int ram_save_live(QEMUFile
*f
, int stage
, void *opaque
)
2877 uint64_t bytes_transferred_last
;
2879 uint64_t expected_time
= 0;
2881 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX
) != 0) {
2882 qemu_file_set_error(f
);
2887 /* Make sure all dirty bits are set */
2888 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2889 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2890 cpu_physical_memory_set_dirty(addr
);
2893 /* Enable dirty memory tracking */
2894 cpu_physical_memory_set_dirty_tracking(1);
2896 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
2899 bytes_transferred_last
= bytes_transferred
;
2900 bwidth
= get_clock();
2902 while (!qemu_file_rate_limit(f
)) {
2905 ret
= ram_save_block(f
);
2906 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
2907 if (ret
== 0) /* no more blocks */
2911 bwidth
= get_clock() - bwidth
;
2912 bwidth
= (bytes_transferred
- bytes_transferred_last
) / bwidth
;
2914 /* if we haven't transferred anything this round, force expected_time to a
2915 * a very high value, but without crashing */
2919 /* try transferring iterative blocks of memory */
2923 /* flush all remaining blocks regardless of rate limiting */
2924 while (ram_save_block(f
) != 0) {
2925 bytes_transferred
+= TARGET_PAGE_SIZE
;
2927 cpu_physical_memory_set_dirty_tracking(0);
2930 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
2932 expected_time
= ram_save_remaining() * TARGET_PAGE_SIZE
/ bwidth
;
2934 return (stage
== 2) && (expected_time
<= migrate_max_downtime());
2937 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
2942 if (version_id
!= 3)
2946 addr
= qemu_get_be64(f
);
2948 flags
= addr
& ~TARGET_PAGE_MASK
;
2949 addr
&= TARGET_PAGE_MASK
;
2951 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
2952 if (addr
!= last_ram_offset
)
2956 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
2957 uint8_t ch
= qemu_get_byte(f
);
2958 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
2961 (!kvm_enabled() || kvm_has_sync_mmu())) {
2962 madvise(qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
, MADV_DONTNEED
);
2965 } else if (flags
& RAM_SAVE_FLAG_PAGE
)
2966 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
2967 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
2972 void qemu_service_io(void)
2974 qemu_notify_event();
2977 /***********************************************************/
2978 /* bottom halves (can be seen as timers which expire ASAP) */
2989 static QEMUBH
*first_bh
= NULL
;
2991 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
2994 bh
= qemu_mallocz(sizeof(QEMUBH
));
2996 bh
->opaque
= opaque
;
2997 bh
->next
= first_bh
;
3002 int qemu_bh_poll(void)
3008 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3009 if (!bh
->deleted
&& bh
->scheduled
) {
3018 /* remove deleted bhs */
3032 void qemu_bh_schedule_idle(QEMUBH
*bh
)
3040 void qemu_bh_schedule(QEMUBH
*bh
)
3046 /* stop the currently executing CPU to execute the BH ASAP */
3047 qemu_notify_event();
3050 void qemu_bh_cancel(QEMUBH
*bh
)
3055 void qemu_bh_delete(QEMUBH
*bh
)
3061 static void qemu_bh_update_timeout(int *timeout
)
3065 for (bh
= first_bh
; bh
; bh
= bh
->next
) {
3066 if (!bh
->deleted
&& bh
->scheduled
) {
3068 /* idle bottom halves will be polled at least
3070 *timeout
= MIN(10, *timeout
);
3072 /* non-idle bottom halves will be executed
3081 /***********************************************************/
3082 /* machine registration */
3084 static QEMUMachine
*first_machine
= NULL
;
3085 QEMUMachine
*current_machine
= NULL
;
3087 int qemu_register_machine(QEMUMachine
*m
)
3090 pm
= &first_machine
;
3098 static QEMUMachine
*find_machine(const char *name
)
3102 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3103 if (!strcmp(m
->name
, name
))
3105 if (m
->alias
&& !strcmp(m
->alias
, name
))
3111 static QEMUMachine
*find_default_machine(void)
3115 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3116 if (m
->is_default
) {
3123 /***********************************************************/
3124 /* main execution loop */
3126 static void gui_update(void *opaque
)
3128 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3129 DisplayState
*ds
= opaque
;
3130 DisplayChangeListener
*dcl
= ds
->listeners
;
3134 while (dcl
!= NULL
) {
3135 if (dcl
->gui_timer_interval
&&
3136 dcl
->gui_timer_interval
< interval
)
3137 interval
= dcl
->gui_timer_interval
;
3140 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3143 static void nographic_update(void *opaque
)
3145 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3147 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3150 struct vm_change_state_entry
{
3151 VMChangeStateHandler
*cb
;
3153 QLIST_ENTRY (vm_change_state_entry
) entries
;
3156 static QLIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3158 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3161 VMChangeStateEntry
*e
;
3163 e
= qemu_mallocz(sizeof (*e
));
3167 QLIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3171 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3173 QLIST_REMOVE (e
, entries
);
3177 static void vm_state_notify(int running
, int reason
)
3179 VMChangeStateEntry
*e
;
3181 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3182 e
->cb(e
->opaque
, running
, reason
);
3186 static void resume_all_vcpus(void);
3187 static void pause_all_vcpus(void);
3194 vm_state_notify(1, 0);
3195 qemu_rearm_alarm_timer(alarm_timer
);
3200 /* reset/shutdown handler */
3202 typedef struct QEMUResetEntry
{
3203 QTAILQ_ENTRY(QEMUResetEntry
) entry
;
3204 QEMUResetHandler
*func
;
3208 static QTAILQ_HEAD(reset_handlers
, QEMUResetEntry
) reset_handlers
=
3209 QTAILQ_HEAD_INITIALIZER(reset_handlers
);
3210 static int reset_requested
;
3211 static int shutdown_requested
;
3212 static int powerdown_requested
;
3213 static int debug_requested
;
3214 static int vmstop_requested
;
3216 int qemu_shutdown_requested(void)
3218 int r
= shutdown_requested
;
3219 shutdown_requested
= 0;
3223 int qemu_reset_requested(void)
3225 int r
= reset_requested
;
3226 reset_requested
= 0;
3230 int qemu_powerdown_requested(void)
3232 int r
= powerdown_requested
;
3233 powerdown_requested
= 0;
3237 static int qemu_debug_requested(void)
3239 int r
= debug_requested
;
3240 debug_requested
= 0;
3244 static int qemu_vmstop_requested(void)
3246 int r
= vmstop_requested
;
3247 vmstop_requested
= 0;
3251 static void do_vm_stop(int reason
)
3254 cpu_disable_ticks();
3257 vm_state_notify(0, reason
);
3261 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3263 QEMUResetEntry
*re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3266 re
->opaque
= opaque
;
3267 QTAILQ_INSERT_TAIL(&reset_handlers
, re
, entry
);
3270 void qemu_unregister_reset(QEMUResetHandler
*func
, void *opaque
)
3274 QTAILQ_FOREACH(re
, &reset_handlers
, entry
) {
3275 if (re
->func
== func
&& re
->opaque
== opaque
) {
3276 QTAILQ_REMOVE(&reset_handlers
, re
, entry
);
3283 void qemu_system_reset(void)
3285 QEMUResetEntry
*re
, *nre
;
3287 /* reset all devices */
3288 QTAILQ_FOREACH_SAFE(re
, &reset_handlers
, entry
, nre
) {
3289 re
->func(re
->opaque
);
3293 void qemu_system_reset_request(void)
3296 shutdown_requested
= 1;
3298 reset_requested
= 1;
3300 qemu_notify_event();
3303 void qemu_system_shutdown_request(void)
3305 shutdown_requested
= 1;
3306 qemu_notify_event();
3309 void qemu_system_powerdown_request(void)
3311 powerdown_requested
= 1;
3312 qemu_notify_event();
3315 #ifdef CONFIG_IOTHREAD
3316 static void qemu_system_vmstop_request(int reason
)
3318 vmstop_requested
= reason
;
3319 qemu_notify_event();
3324 static int io_thread_fd
= -1;
3326 static void qemu_event_increment(void)
3328 static const char byte
= 0;
3330 if (io_thread_fd
== -1)
3333 write(io_thread_fd
, &byte
, sizeof(byte
));
3336 static void qemu_event_read(void *opaque
)
3338 int fd
= (unsigned long)opaque
;
3341 /* Drain the notify pipe */
3344 len
= read(fd
, buffer
, sizeof(buffer
));
3345 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
3348 static int qemu_event_init(void)
3357 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3361 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3365 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3366 (void *)(unsigned long)fds
[0]);
3368 io_thread_fd
= fds
[1];
3377 HANDLE qemu_event_handle
;
3379 static void dummy_event_handler(void *opaque
)
3383 static int qemu_event_init(void)
3385 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3386 if (!qemu_event_handle
) {
3387 fprintf(stderr
, "Failed CreateEvent: %ld\n", GetLastError());
3390 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3394 static void qemu_event_increment(void)
3396 if (!SetEvent(qemu_event_handle
)) {
3397 fprintf(stderr
, "qemu_event_increment: SetEvent failed: %ld\n",
3404 static int cpu_can_run(CPUState
*env
)
3413 #ifndef CONFIG_IOTHREAD
3414 static int qemu_init_main_loop(void)
3416 return qemu_event_init();
3419 void qemu_init_vcpu(void *_env
)
3421 CPUState
*env
= _env
;
3425 env
->nr_cores
= smp_cores
;
3426 env
->nr_threads
= smp_threads
;
3430 int qemu_cpu_self(void *env
)
3435 static void resume_all_vcpus(void)
3439 static void pause_all_vcpus(void)
3443 void qemu_cpu_kick(void *env
)
3448 void qemu_notify_event(void)
3450 CPUState
*env
= cpu_single_env
;
3457 #define qemu_mutex_lock_iothread() do { } while (0)
3458 #define qemu_mutex_unlock_iothread() do { } while (0)
3460 void vm_stop(int reason
)
3465 #else /* CONFIG_IOTHREAD */
3467 #include "qemu-thread.h"
3469 QemuMutex qemu_global_mutex
;
3470 static QemuMutex qemu_fair_mutex
;
3472 static QemuThread io_thread
;
3474 static QemuThread
*tcg_cpu_thread
;
3475 static QemuCond
*tcg_halt_cond
;
3477 static int qemu_system_ready
;
3479 static QemuCond qemu_cpu_cond
;
3481 static QemuCond qemu_system_cond
;
3482 static QemuCond qemu_pause_cond
;
3484 static void block_io_signals(void);
3485 static void unblock_io_signals(void);
3486 static int tcg_has_work(void);
3488 static int qemu_init_main_loop(void)
3492 ret
= qemu_event_init();
3496 qemu_cond_init(&qemu_pause_cond
);
3497 qemu_mutex_init(&qemu_fair_mutex
);
3498 qemu_mutex_init(&qemu_global_mutex
);
3499 qemu_mutex_lock(&qemu_global_mutex
);
3501 unblock_io_signals();
3502 qemu_thread_self(&io_thread
);
3507 static void qemu_wait_io_event(CPUState
*env
)
3509 while (!tcg_has_work())
3510 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3512 qemu_mutex_unlock(&qemu_global_mutex
);
3515 * Users of qemu_global_mutex can be starved, having no chance
3516 * to acquire it since this path will get to it first.
3517 * So use another lock to provide fairness.
3519 qemu_mutex_lock(&qemu_fair_mutex
);
3520 qemu_mutex_unlock(&qemu_fair_mutex
);
3522 qemu_mutex_lock(&qemu_global_mutex
);
3526 qemu_cond_signal(&qemu_pause_cond
);
3530 static int qemu_cpu_exec(CPUState
*env
);
3532 static void *kvm_cpu_thread_fn(void *arg
)
3534 CPUState
*env
= arg
;
3537 qemu_thread_self(env
->thread
);
3541 /* signal CPU creation */
3542 qemu_mutex_lock(&qemu_global_mutex
);
3544 qemu_cond_signal(&qemu_cpu_cond
);
3546 /* and wait for machine initialization */
3547 while (!qemu_system_ready
)
3548 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3551 if (cpu_can_run(env
))
3553 qemu_wait_io_event(env
);
3559 static void tcg_cpu_exec(void);
3561 static void *tcg_cpu_thread_fn(void *arg
)
3563 CPUState
*env
= arg
;
3566 qemu_thread_self(env
->thread
);
3568 /* signal CPU creation */
3569 qemu_mutex_lock(&qemu_global_mutex
);
3570 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
3572 qemu_cond_signal(&qemu_cpu_cond
);
3574 /* and wait for machine initialization */
3575 while (!qemu_system_ready
)
3576 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3580 qemu_wait_io_event(cur_cpu
);
3586 void qemu_cpu_kick(void *_env
)
3588 CPUState
*env
= _env
;
3589 qemu_cond_broadcast(env
->halt_cond
);
3591 qemu_thread_signal(env
->thread
, SIGUSR1
);
3594 int qemu_cpu_self(void *env
)
3596 return (cpu_single_env
!= NULL
);
3599 static void cpu_signal(int sig
)
3602 cpu_exit(cpu_single_env
);
3605 static void block_io_signals(void)
3608 struct sigaction sigact
;
3611 sigaddset(&set
, SIGUSR2
);
3612 sigaddset(&set
, SIGIO
);
3613 sigaddset(&set
, SIGALRM
);
3614 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3617 sigaddset(&set
, SIGUSR1
);
3618 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3620 memset(&sigact
, 0, sizeof(sigact
));
3621 sigact
.sa_handler
= cpu_signal
;
3622 sigaction(SIGUSR1
, &sigact
, NULL
);
3625 static void unblock_io_signals(void)
3630 sigaddset(&set
, SIGUSR2
);
3631 sigaddset(&set
, SIGIO
);
3632 sigaddset(&set
, SIGALRM
);
3633 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3636 sigaddset(&set
, SIGUSR1
);
3637 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3640 static void qemu_signal_lock(unsigned int msecs
)
3642 qemu_mutex_lock(&qemu_fair_mutex
);
3644 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
3645 qemu_thread_signal(tcg_cpu_thread
, SIGUSR1
);
3646 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
3649 qemu_mutex_unlock(&qemu_fair_mutex
);
3652 static void qemu_mutex_lock_iothread(void)
3654 if (kvm_enabled()) {
3655 qemu_mutex_lock(&qemu_fair_mutex
);
3656 qemu_mutex_lock(&qemu_global_mutex
);
3657 qemu_mutex_unlock(&qemu_fair_mutex
);
3659 qemu_signal_lock(100);
3662 static void qemu_mutex_unlock_iothread(void)
3664 qemu_mutex_unlock(&qemu_global_mutex
);
3667 static int all_vcpus_paused(void)
3669 CPUState
*penv
= first_cpu
;
3674 penv
= (CPUState
*)penv
->next_cpu
;
3680 static void pause_all_vcpus(void)
3682 CPUState
*penv
= first_cpu
;
3686 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3687 qemu_cpu_kick(penv
);
3688 penv
= (CPUState
*)penv
->next_cpu
;
3691 while (!all_vcpus_paused()) {
3692 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
3695 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3696 penv
= (CPUState
*)penv
->next_cpu
;
3701 static void resume_all_vcpus(void)
3703 CPUState
*penv
= first_cpu
;
3708 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3709 qemu_cpu_kick(penv
);
3710 penv
= (CPUState
*)penv
->next_cpu
;
3714 static void tcg_init_vcpu(void *_env
)
3716 CPUState
*env
= _env
;
3717 /* share a single thread for all cpus with TCG */
3718 if (!tcg_cpu_thread
) {
3719 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3720 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3721 qemu_cond_init(env
->halt_cond
);
3722 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
3723 while (env
->created
== 0)
3724 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3725 tcg_cpu_thread
= env
->thread
;
3726 tcg_halt_cond
= env
->halt_cond
;
3728 env
->thread
= tcg_cpu_thread
;
3729 env
->halt_cond
= tcg_halt_cond
;
3733 static void kvm_start_vcpu(CPUState
*env
)
3735 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3736 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3737 qemu_cond_init(env
->halt_cond
);
3738 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
3739 while (env
->created
== 0)
3740 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3743 void qemu_init_vcpu(void *_env
)
3745 CPUState
*env
= _env
;
3748 kvm_start_vcpu(env
);
3751 env
->nr_cores
= smp_cores
;
3752 env
->nr_threads
= smp_threads
;
3755 void qemu_notify_event(void)
3757 qemu_event_increment();
3760 void vm_stop(int reason
)
3763 qemu_thread_self(&me
);
3765 if (!qemu_thread_equal(&me
, &io_thread
)) {
3766 qemu_system_vmstop_request(reason
);
3768 * FIXME: should not return to device code in case
3769 * vm_stop() has been requested.
3771 if (cpu_single_env
) {
3772 cpu_exit(cpu_single_env
);
3773 cpu_single_env
->stop
= 1;
3784 static void host_main_loop_wait(int *timeout
)
3790 /* XXX: need to suppress polling by better using win32 events */
3792 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
3793 ret
|= pe
->func(pe
->opaque
);
3797 WaitObjects
*w
= &wait_objects
;
3799 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
3800 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
3801 if (w
->func
[ret
- WAIT_OBJECT_0
])
3802 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
3804 /* Check for additional signaled events */
3805 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
3807 /* Check if event is signaled */
3808 ret2
= WaitForSingleObject(w
->events
[i
], 0);
3809 if(ret2
== WAIT_OBJECT_0
) {
3811 w
->func
[i
](w
->opaque
[i
]);
3812 } else if (ret2
== WAIT_TIMEOUT
) {
3814 err
= GetLastError();
3815 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
3818 } else if (ret
== WAIT_TIMEOUT
) {
3820 err
= GetLastError();
3821 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
3828 static void host_main_loop_wait(int *timeout
)
3833 void main_loop_wait(int timeout
)
3835 IOHandlerRecord
*ioh
;
3836 fd_set rfds
, wfds
, xfds
;
3840 qemu_bh_update_timeout(&timeout
);
3842 host_main_loop_wait(&timeout
);
3844 /* poll any events */
3845 /* XXX: separate device handlers from system ones */
3850 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3854 (!ioh
->fd_read_poll
||
3855 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
3856 FD_SET(ioh
->fd
, &rfds
);
3860 if (ioh
->fd_write
) {
3861 FD_SET(ioh
->fd
, &wfds
);
3867 tv
.tv_sec
= timeout
/ 1000;
3868 tv
.tv_usec
= (timeout
% 1000) * 1000;
3870 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
3872 qemu_mutex_unlock_iothread();
3873 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
3874 qemu_mutex_lock_iothread();
3876 IOHandlerRecord
**pioh
;
3878 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3879 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
3880 ioh
->fd_read(ioh
->opaque
);
3882 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
3883 ioh
->fd_write(ioh
->opaque
);
3887 /* remove deleted IO handlers */
3888 pioh
= &first_io_handler
;
3899 slirp_select_poll(&rfds
, &wfds
, &xfds
, (ret
< 0));
3901 /* rearm timer, if not periodic */
3902 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
3903 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
3904 qemu_rearm_alarm_timer(alarm_timer
);
3907 /* vm time timers */
3909 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
3910 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
3911 qemu_get_clock(vm_clock
));
3914 /* real time timers */
3915 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
3916 qemu_get_clock(rt_clock
));
3918 /* Check bottom-halves last in case any of the earlier events triggered
3924 static int qemu_cpu_exec(CPUState
*env
)
3927 #ifdef CONFIG_PROFILER
3931 #ifdef CONFIG_PROFILER
3932 ti
= profile_getclock();
3937 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
3938 env
->icount_decr
.u16
.low
= 0;
3939 env
->icount_extra
= 0;
3940 count
= qemu_next_deadline();
3941 count
= (count
+ (1 << icount_time_shift
) - 1)
3942 >> icount_time_shift
;
3943 qemu_icount
+= count
;
3944 decr
= (count
> 0xffff) ? 0xffff : count
;
3946 env
->icount_decr
.u16
.low
= decr
;
3947 env
->icount_extra
= count
;
3949 ret
= cpu_exec(env
);
3950 #ifdef CONFIG_PROFILER
3951 qemu_time
+= profile_getclock() - ti
;
3954 /* Fold pending instructions back into the
3955 instruction counter, and clear the interrupt flag. */
3956 qemu_icount
-= (env
->icount_decr
.u16
.low
3957 + env
->icount_extra
);
3958 env
->icount_decr
.u32
= 0;
3959 env
->icount_extra
= 0;
3964 static void tcg_cpu_exec(void)
3968 if (next_cpu
== NULL
)
3969 next_cpu
= first_cpu
;
3970 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
3971 CPUState
*env
= cur_cpu
= next_cpu
;
3975 if (timer_alarm_pending
) {
3976 timer_alarm_pending
= 0;
3979 if (cpu_can_run(env
))
3980 ret
= qemu_cpu_exec(env
);
3981 if (ret
== EXCP_DEBUG
) {
3982 gdb_set_stop_cpu(env
);
3983 debug_requested
= 1;
3989 static int cpu_has_work(CPUState
*env
)
3997 if (qemu_cpu_has_work(env
))
4002 static int tcg_has_work(void)
4006 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4007 if (cpu_has_work(env
))
4012 static int qemu_calculate_timeout(void)
4014 #ifndef CONFIG_IOTHREAD
4019 else if (tcg_has_work())
4021 else if (!use_icount
)
4024 /* XXX: use timeout computed from timers */
4027 /* Advance virtual time to the next event. */
4028 if (use_icount
== 1) {
4029 /* When not using an adaptive execution frequency
4030 we tend to get badly out of sync with real time,
4031 so just delay for a reasonable amount of time. */
4034 delta
= cpu_get_icount() - cpu_get_clock();
4037 /* If virtual time is ahead of real time then just
4039 timeout
= (delta
/ 1000000) + 1;
4041 /* Wait for either IO to occur or the next
4043 add
= qemu_next_deadline();
4044 /* We advance the timer before checking for IO.
4045 Limit the amount we advance so that early IO
4046 activity won't get the guest too far ahead. */
4050 add
= (add
+ (1 << icount_time_shift
) - 1)
4051 >> icount_time_shift
;
4053 timeout
= delta
/ 1000000;
4060 #else /* CONFIG_IOTHREAD */
4065 static int vm_can_run(void)
4067 if (powerdown_requested
)
4069 if (reset_requested
)
4071 if (shutdown_requested
)
4073 if (debug_requested
)
4078 qemu_irq qemu_system_powerdown
;
4080 static void main_loop(void)
4084 #ifdef CONFIG_IOTHREAD
4085 qemu_system_ready
= 1;
4086 qemu_cond_broadcast(&qemu_system_cond
);
4091 #ifdef CONFIG_PROFILER
4094 #ifndef CONFIG_IOTHREAD
4097 #ifdef CONFIG_PROFILER
4098 ti
= profile_getclock();
4100 main_loop_wait(qemu_calculate_timeout());
4101 #ifdef CONFIG_PROFILER
4102 dev_time
+= profile_getclock() - ti
;
4104 } while (vm_can_run());
4106 if (qemu_debug_requested())
4107 vm_stop(EXCP_DEBUG
);
4108 if (qemu_shutdown_requested()) {
4115 if (qemu_reset_requested()) {
4117 qemu_system_reset();
4120 if (qemu_powerdown_requested()) {
4121 qemu_irq_raise(qemu_system_powerdown
);
4123 if ((r
= qemu_vmstop_requested()))
4129 static void version(void)
4131 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4134 static void help(int exitcode
)
4137 printf("usage: %s [options] [disk_image]\n"
4139 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4141 #define DEF(option, opt_arg, opt_enum, opt_help) \
4143 #define DEFHEADING(text) stringify(text) "\n"
4144 #include "qemu-options.h"
4149 "During emulation, the following keys are useful:\n"
4150 "ctrl-alt-f toggle full screen\n"
4151 "ctrl-alt-n switch to virtual console 'n'\n"
4152 "ctrl-alt toggle mouse and keyboard grab\n"
4154 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4159 DEFAULT_NETWORK_SCRIPT
,
4160 DEFAULT_NETWORK_DOWN_SCRIPT
,
4162 DEFAULT_GDBSTUB_PORT
,
4167 #define HAS_ARG 0x0001
4170 #define DEF(option, opt_arg, opt_enum, opt_help) \
4172 #define DEFHEADING(text)
4173 #include "qemu-options.h"
4179 typedef struct QEMUOption
{
4185 static const QEMUOption qemu_options
[] = {
4186 { "h", 0, QEMU_OPTION_h
},
4187 #define DEF(option, opt_arg, opt_enum, opt_help) \
4188 { option, opt_arg, opt_enum },
4189 #define DEFHEADING(text)
4190 #include "qemu-options.h"
4198 struct soundhw soundhw
[] = {
4199 #ifdef HAS_AUDIO_CHOICE
4200 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4206 { .init_isa
= pcspk_audio_init
}
4213 "Creative Sound Blaster 16",
4216 { .init_isa
= SB16_init
}
4220 #ifdef CONFIG_CS4231A
4226 { .init_isa
= cs4231a_init
}
4234 "Yamaha YMF262 (OPL3)",
4236 "Yamaha YM3812 (OPL2)",
4240 { .init_isa
= Adlib_init
}
4247 "Gravis Ultrasound GF1",
4250 { .init_isa
= GUS_init
}
4257 "Intel 82801AA AC97 Audio",
4260 { .init_pci
= ac97_init
}
4264 #ifdef CONFIG_ES1370
4267 "ENSONIQ AudioPCI ES1370",
4270 { .init_pci
= es1370_init
}
4274 #endif /* HAS_AUDIO_CHOICE */
4276 { NULL
, NULL
, 0, 0, { NULL
} }
4279 static void select_soundhw (const char *optarg
)
4283 if (*optarg
== '?') {
4286 printf ("Valid sound card names (comma separated):\n");
4287 for (c
= soundhw
; c
->name
; ++c
) {
4288 printf ("%-11s %s\n", c
->name
, c
->descr
);
4290 printf ("\n-soundhw all will enable all of the above\n");
4291 exit (*optarg
!= '?');
4299 if (!strcmp (optarg
, "all")) {
4300 for (c
= soundhw
; c
->name
; ++c
) {
4308 e
= strchr (p
, ',');
4309 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4311 for (c
= soundhw
; c
->name
; ++c
) {
4312 if (!strncmp (c
->name
, p
, l
) && !c
->name
[l
]) {
4321 "Unknown sound card name (too big to show)\n");
4324 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4329 p
+= l
+ (e
!= NULL
);
4333 goto show_valid_cards
;
4338 static void select_vgahw (const char *p
)
4342 vga_interface_type
= VGA_NONE
;
4343 if (strstart(p
, "std", &opts
)) {
4344 vga_interface_type
= VGA_STD
;
4345 } else if (strstart(p
, "cirrus", &opts
)) {
4346 vga_interface_type
= VGA_CIRRUS
;
4347 } else if (strstart(p
, "vmware", &opts
)) {
4348 vga_interface_type
= VGA_VMWARE
;
4349 } else if (strstart(p
, "xenfb", &opts
)) {
4350 vga_interface_type
= VGA_XENFB
;
4351 } else if (!strstart(p
, "none", &opts
)) {
4353 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4357 const char *nextopt
;
4359 if (strstart(opts
, ",retrace=", &nextopt
)) {
4361 if (strstart(opts
, "dumb", &nextopt
))
4362 vga_retrace_method
= VGA_RETRACE_DUMB
;
4363 else if (strstart(opts
, "precise", &nextopt
))
4364 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4365 else goto invalid_vga
;
4366 } else goto invalid_vga
;
4372 static int balloon_parse(const char *arg
)
4376 if (strcmp(arg
, "none") == 0) {
4380 if (!strncmp(arg
, "virtio", 6)) {
4381 if (arg
[6] == ',') {
4382 /* have params -> parse them */
4383 opts
= qemu_opts_parse(&qemu_device_opts
, arg
+7, NULL
);
4387 /* create empty opts */
4388 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4390 qemu_opt_set(opts
, "driver", "virtio-balloon-pci");
4399 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4401 exit(STATUS_CONTROL_C_EXIT
);
4406 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4410 if(strlen(str
) != 36)
4413 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4414 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4415 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4421 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4427 #define MAX_NET_CLIENTS 32
4431 static void termsig_handler(int signal
)
4433 qemu_system_shutdown_request();
4436 static void sigchld_handler(int signal
)
4438 waitpid(-1, NULL
, WNOHANG
);
4441 static void sighandler_setup(void)
4443 struct sigaction act
;
4445 memset(&act
, 0, sizeof(act
));
4446 act
.sa_handler
= termsig_handler
;
4447 sigaction(SIGINT
, &act
, NULL
);
4448 sigaction(SIGHUP
, &act
, NULL
);
4449 sigaction(SIGTERM
, &act
, NULL
);
4451 act
.sa_handler
= sigchld_handler
;
4452 act
.sa_flags
= SA_NOCLDSTOP
;
4453 sigaction(SIGCHLD
, &act
, NULL
);
4459 /* Look for support files in the same directory as the executable. */
4460 static char *find_datadir(const char *argv0
)
4466 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
4473 while (p
!= buf
&& *p
!= '\\')
4476 if (access(buf
, R_OK
) == 0) {
4477 return qemu_strdup(buf
);
4483 /* Find a likely location for support files using the location of the binary.
4484 For installed binaries this will be "$bindir/../share/qemu". When
4485 running from the build tree this will be "$bindir/../pc-bios". */
4486 #define SHARE_SUFFIX "/share/qemu"
4487 #define BUILD_SUFFIX "/pc-bios"
4488 static char *find_datadir(const char *argv0
)
4496 #if defined(__linux__)
4499 len
= readlink("/proc/self/exe", buf
, sizeof(buf
) - 1);
4505 #elif defined(__FreeBSD__)
4508 len
= readlink("/proc/curproc/file", buf
, sizeof(buf
) - 1);
4515 /* If we don't have any way of figuring out the actual executable
4516 location then try argv[0]. */
4518 p
= realpath(argv0
, buf
);
4526 max_len
= strlen(dir
) +
4527 MAX(strlen(SHARE_SUFFIX
), strlen(BUILD_SUFFIX
)) + 1;
4528 res
= qemu_mallocz(max_len
);
4529 snprintf(res
, max_len
, "%s%s", dir
, SHARE_SUFFIX
);
4530 if (access(res
, R_OK
)) {
4531 snprintf(res
, max_len
, "%s%s", dir
, BUILD_SUFFIX
);
4532 if (access(res
, R_OK
)) {
4544 char *qemu_find_file(int type
, const char *name
)
4550 /* If name contains path separators then try it as a straight path. */
4551 if ((strchr(name
, '/') || strchr(name
, '\\'))
4552 && access(name
, R_OK
) == 0) {
4553 return qemu_strdup(name
);
4556 case QEMU_FILE_TYPE_BIOS
:
4559 case QEMU_FILE_TYPE_KEYMAP
:
4560 subdir
= "keymaps/";
4565 len
= strlen(data_dir
) + strlen(name
) + strlen(subdir
) + 2;
4566 buf
= qemu_mallocz(len
);
4567 snprintf(buf
, len
, "%s/%s%s", data_dir
, subdir
, name
);
4568 if (access(buf
, R_OK
)) {
4575 static int device_init_func(QemuOpts
*opts
, void *opaque
)
4579 dev
= qdev_device_add(opts
);
4585 struct device_config
{
4587 DEV_USB
, /* -usbdevice */
4590 const char *cmdline
;
4591 QTAILQ_ENTRY(device_config
) next
;
4593 QTAILQ_HEAD(, device_config
) device_configs
= QTAILQ_HEAD_INITIALIZER(device_configs
);
4595 static void add_device_config(int type
, const char *cmdline
)
4597 struct device_config
*conf
;
4599 conf
= qemu_mallocz(sizeof(*conf
));
4601 conf
->cmdline
= cmdline
;
4602 QTAILQ_INSERT_TAIL(&device_configs
, conf
, next
);
4605 static int foreach_device_config(int type
, int (*func
)(const char *cmdline
))
4607 struct device_config
*conf
;
4610 QTAILQ_FOREACH(conf
, &device_configs
, next
) {
4611 if (conf
->type
!= type
)
4613 rc
= func(conf
->cmdline
);
4620 int main(int argc
, char **argv
, char **envp
)
4622 const char *gdbstub_dev
= NULL
;
4623 uint32_t boot_devices_bitmap
= 0;
4625 int snapshot
, linux_boot
, net_boot
;
4626 const char *initrd_filename
;
4627 const char *kernel_filename
, *kernel_cmdline
;
4628 char boot_devices
[33] = "cad"; /* default to HD->floppy->CD-ROM */
4630 DisplayChangeListener
*dcl
;
4631 int cyls
, heads
, secs
, translation
;
4632 const char *net_clients
[MAX_NET_CLIENTS
];
4634 QemuOpts
*hda_opts
= NULL
, *opts
;
4636 const char *r
, *optarg
;
4637 CharDriverState
*monitor_hds
[MAX_MONITOR_DEVICES
];
4638 const char *monitor_devices
[MAX_MONITOR_DEVICES
];
4639 int monitor_device_index
;
4640 const char *serial_devices
[MAX_SERIAL_PORTS
];
4641 int serial_device_index
;
4642 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
4643 int parallel_device_index
;
4644 const char *virtio_consoles
[MAX_VIRTIO_CONSOLES
];
4645 int virtio_console_index
;
4646 const char *loadvm
= NULL
;
4647 QEMUMachine
*machine
;
4648 const char *cpu_model
;
4653 const char *pid_file
= NULL
;
4654 const char *incoming
= NULL
;
4657 struct passwd
*pwd
= NULL
;
4658 const char *chroot_dir
= NULL
;
4659 const char *run_as
= NULL
;
4662 int show_vnc_port
= 0;
4664 qemu_errors_to_file(stderr
);
4665 qemu_cache_utils_init(envp
);
4667 QLIST_INIT (&vm_change_state_head
);
4670 struct sigaction act
;
4671 sigfillset(&act
.sa_mask
);
4673 act
.sa_handler
= SIG_IGN
;
4674 sigaction(SIGPIPE
, &act
, NULL
);
4677 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4678 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4679 QEMU to run on a single CPU */
4684 h
= GetCurrentProcess();
4685 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4686 for(i
= 0; i
< 32; i
++) {
4687 if (mask
& (1 << i
))
4692 SetProcessAffinityMask(h
, mask
);
4698 module_call_init(MODULE_INIT_MACHINE
);
4699 machine
= find_default_machine();
4701 initrd_filename
= NULL
;
4704 kernel_filename
= NULL
;
4705 kernel_cmdline
= "";
4706 cyls
= heads
= secs
= 0;
4707 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4709 serial_devices
[0] = "vc:80Cx24C";
4710 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
4711 serial_devices
[i
] = NULL
;
4712 serial_device_index
= 0;
4714 parallel_devices
[0] = "vc:80Cx24C";
4715 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
4716 parallel_devices
[i
] = NULL
;
4717 parallel_device_index
= 0;
4719 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++)
4720 virtio_consoles
[i
] = NULL
;
4721 virtio_console_index
= 0;
4723 monitor_devices
[0] = "vc:80Cx24C";
4724 for (i
= 1; i
< MAX_MONITOR_DEVICES
; i
++) {
4725 monitor_devices
[i
] = NULL
;
4727 monitor_device_index
= 0;
4729 for (i
= 0; i
< MAX_NODES
; i
++) {
4731 node_cpumask
[i
] = 0;
4747 hda_opts
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
4749 const QEMUOption
*popt
;
4752 /* Treat --foo the same as -foo. */
4755 popt
= qemu_options
;
4758 fprintf(stderr
, "%s: invalid option -- '%s'\n",
4762 if (!strcmp(popt
->name
, r
+ 1))
4766 if (popt
->flags
& HAS_ARG
) {
4767 if (optind
>= argc
) {
4768 fprintf(stderr
, "%s: option '%s' requires an argument\n",
4772 optarg
= argv
[optind
++];
4777 switch(popt
->index
) {
4779 machine
= find_machine(optarg
);
4782 printf("Supported machines are:\n");
4783 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
4785 printf("%-10s %s (alias of %s)\n",
4786 m
->alias
, m
->desc
, m
->name
);
4787 printf("%-10s %s%s\n",
4789 m
->is_default
? " (default)" : "");
4791 exit(*optarg
!= '?');
4794 case QEMU_OPTION_cpu
:
4795 /* hw initialization will check this */
4796 if (*optarg
== '?') {
4797 /* XXX: implement xxx_cpu_list for targets that still miss it */
4798 #if defined(cpu_list)
4799 cpu_list(stdout
, &fprintf
);
4806 case QEMU_OPTION_initrd
:
4807 initrd_filename
= optarg
;
4809 case QEMU_OPTION_hda
:
4811 hda_opts
= drive_add(optarg
, HD_ALIAS
, 0);
4813 hda_opts
= drive_add(optarg
, HD_ALIAS
4814 ",cyls=%d,heads=%d,secs=%d%s",
4815 0, cyls
, heads
, secs
,
4816 translation
== BIOS_ATA_TRANSLATION_LBA
?
4818 translation
== BIOS_ATA_TRANSLATION_NONE
?
4819 ",trans=none" : "");
4821 case QEMU_OPTION_hdb
:
4822 case QEMU_OPTION_hdc
:
4823 case QEMU_OPTION_hdd
:
4824 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
4826 case QEMU_OPTION_drive
:
4827 drive_add(NULL
, "%s", optarg
);
4829 case QEMU_OPTION_set
:
4830 if (qemu_set_option(optarg
) != 0)
4833 case QEMU_OPTION_mtdblock
:
4834 drive_add(optarg
, MTD_ALIAS
);
4836 case QEMU_OPTION_sd
:
4837 drive_add(optarg
, SD_ALIAS
);
4839 case QEMU_OPTION_pflash
:
4840 drive_add(optarg
, PFLASH_ALIAS
);
4842 case QEMU_OPTION_snapshot
:
4845 case QEMU_OPTION_hdachs
:
4849 cyls
= strtol(p
, (char **)&p
, 0);
4850 if (cyls
< 1 || cyls
> 16383)
4855 heads
= strtol(p
, (char **)&p
, 0);
4856 if (heads
< 1 || heads
> 16)
4861 secs
= strtol(p
, (char **)&p
, 0);
4862 if (secs
< 1 || secs
> 63)
4866 if (!strcmp(p
, "none"))
4867 translation
= BIOS_ATA_TRANSLATION_NONE
;
4868 else if (!strcmp(p
, "lba"))
4869 translation
= BIOS_ATA_TRANSLATION_LBA
;
4870 else if (!strcmp(p
, "auto"))
4871 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4874 } else if (*p
!= '\0') {
4876 fprintf(stderr
, "qemu: invalid physical CHS format\n");
4879 if (hda_opts
!= NULL
) {
4881 snprintf(num
, sizeof(num
), "%d", cyls
);
4882 qemu_opt_set(hda_opts
, "cyls", num
);
4883 snprintf(num
, sizeof(num
), "%d", heads
);
4884 qemu_opt_set(hda_opts
, "heads", num
);
4885 snprintf(num
, sizeof(num
), "%d", secs
);
4886 qemu_opt_set(hda_opts
, "secs", num
);
4887 if (translation
== BIOS_ATA_TRANSLATION_LBA
)
4888 qemu_opt_set(hda_opts
, "trans", "lba");
4889 if (translation
== BIOS_ATA_TRANSLATION_NONE
)
4890 qemu_opt_set(hda_opts
, "trans", "none");
4894 case QEMU_OPTION_numa
:
4895 if (nb_numa_nodes
>= MAX_NODES
) {
4896 fprintf(stderr
, "qemu: too many NUMA nodes\n");
4901 case QEMU_OPTION_nographic
:
4902 display_type
= DT_NOGRAPHIC
;
4904 #ifdef CONFIG_CURSES
4905 case QEMU_OPTION_curses
:
4906 display_type
= DT_CURSES
;
4909 case QEMU_OPTION_portrait
:
4912 case QEMU_OPTION_kernel
:
4913 kernel_filename
= optarg
;
4915 case QEMU_OPTION_append
:
4916 kernel_cmdline
= optarg
;
4918 case QEMU_OPTION_cdrom
:
4919 drive_add(optarg
, CDROM_ALIAS
);
4921 case QEMU_OPTION_boot
:
4923 static const char * const params
[] = {
4924 "order", "once", "menu", NULL
4926 char buf
[sizeof(boot_devices
)];
4927 char *standard_boot_devices
;
4930 if (!strchr(optarg
, '=')) {
4932 pstrcpy(buf
, sizeof(buf
), optarg
);
4933 } else if (check_params(buf
, sizeof(buf
), params
, optarg
) < 0) {
4935 "qemu: unknown boot parameter '%s' in '%s'\n",
4941 get_param_value(buf
, sizeof(buf
), "order", optarg
)) {
4942 boot_devices_bitmap
= parse_bootdevices(buf
);
4943 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
4946 if (get_param_value(buf
, sizeof(buf
),
4948 boot_devices_bitmap
|= parse_bootdevices(buf
);
4949 standard_boot_devices
= qemu_strdup(boot_devices
);
4950 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
4951 qemu_register_reset(restore_boot_devices
,
4952 standard_boot_devices
);
4954 if (get_param_value(buf
, sizeof(buf
),
4956 if (!strcmp(buf
, "on")) {
4958 } else if (!strcmp(buf
, "off")) {
4962 "qemu: invalid option value '%s'\n",
4970 case QEMU_OPTION_fda
:
4971 case QEMU_OPTION_fdb
:
4972 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
4975 case QEMU_OPTION_no_fd_bootchk
:
4979 case QEMU_OPTION_net
:
4980 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
4981 fprintf(stderr
, "qemu: too many network clients\n");
4984 net_clients
[nb_net_clients
] = optarg
;
4988 case QEMU_OPTION_tftp
:
4989 legacy_tftp_prefix
= optarg
;
4991 case QEMU_OPTION_bootp
:
4992 legacy_bootp_filename
= optarg
;
4995 case QEMU_OPTION_smb
:
4996 net_slirp_smb(optarg
);
4999 case QEMU_OPTION_redir
:
5000 net_slirp_redir(optarg
);
5003 case QEMU_OPTION_bt
:
5004 add_device_config(DEV_BT
, optarg
);
5007 case QEMU_OPTION_audio_help
:
5011 case QEMU_OPTION_soundhw
:
5012 select_soundhw (optarg
);
5018 case QEMU_OPTION_version
:
5022 case QEMU_OPTION_m
: {
5026 value
= strtoul(optarg
, &ptr
, 10);
5028 case 0: case 'M': case 'm':
5035 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5039 /* On 32-bit hosts, QEMU is limited by virtual address space */
5040 if (value
> (2047 << 20) && HOST_LONG_BITS
== 32) {
5041 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5044 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5045 fprintf(stderr
, "qemu: ram size too large\n");
5054 const CPULogItem
*item
;
5056 mask
= cpu_str_to_log_mask(optarg
);
5058 printf("Log items (comma separated):\n");
5059 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5060 printf("%-10s %s\n", item
->name
, item
->help
);
5068 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5070 case QEMU_OPTION_gdb
:
5071 gdbstub_dev
= optarg
;
5076 case QEMU_OPTION_bios
:
5079 case QEMU_OPTION_singlestep
:
5087 keyboard_layout
= optarg
;
5090 case QEMU_OPTION_localtime
:
5093 case QEMU_OPTION_vga
:
5094 select_vgahw (optarg
);
5096 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5102 w
= strtol(p
, (char **)&p
, 10);
5105 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5111 h
= strtol(p
, (char **)&p
, 10);
5116 depth
= strtol(p
, (char **)&p
, 10);
5117 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5118 depth
!= 24 && depth
!= 32)
5120 } else if (*p
== '\0') {
5121 depth
= graphic_depth
;
5128 graphic_depth
= depth
;
5132 case QEMU_OPTION_echr
:
5135 term_escape_char
= strtol(optarg
, &r
, 0);
5137 printf("Bad argument to echr\n");
5140 case QEMU_OPTION_monitor
:
5141 if (monitor_device_index
>= MAX_MONITOR_DEVICES
) {
5142 fprintf(stderr
, "qemu: too many monitor devices\n");
5145 monitor_devices
[monitor_device_index
] = optarg
;
5146 monitor_device_index
++;
5148 case QEMU_OPTION_chardev
:
5149 opts
= qemu_opts_parse(&qemu_chardev_opts
, optarg
, "backend");
5151 fprintf(stderr
, "parse error: %s\n", optarg
);
5154 if (qemu_chr_open_opts(opts
, NULL
) == NULL
) {
5158 case QEMU_OPTION_serial
:
5159 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
5160 fprintf(stderr
, "qemu: too many serial ports\n");
5163 serial_devices
[serial_device_index
] = optarg
;
5164 serial_device_index
++;
5166 case QEMU_OPTION_watchdog
:
5169 "qemu: only one watchdog option may be given\n");
5174 case QEMU_OPTION_watchdog_action
:
5175 if (select_watchdog_action(optarg
) == -1) {
5176 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5180 case QEMU_OPTION_virtiocon
:
5181 if (virtio_console_index
>= MAX_VIRTIO_CONSOLES
) {
5182 fprintf(stderr
, "qemu: too many virtio consoles\n");
5185 virtio_consoles
[virtio_console_index
] = optarg
;
5186 virtio_console_index
++;
5188 case QEMU_OPTION_parallel
:
5189 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
5190 fprintf(stderr
, "qemu: too many parallel ports\n");
5193 parallel_devices
[parallel_device_index
] = optarg
;
5194 parallel_device_index
++;
5196 case QEMU_OPTION_loadvm
:
5199 case QEMU_OPTION_full_screen
:
5203 case QEMU_OPTION_no_frame
:
5206 case QEMU_OPTION_alt_grab
:
5209 case QEMU_OPTION_no_quit
:
5212 case QEMU_OPTION_sdl
:
5213 display_type
= DT_SDL
;
5216 case QEMU_OPTION_pidfile
:
5220 case QEMU_OPTION_win2k_hack
:
5221 win2k_install_hack
= 1;
5223 case QEMU_OPTION_rtc_td_hack
:
5226 case QEMU_OPTION_acpitable
:
5227 if(acpi_table_add(optarg
) < 0) {
5228 fprintf(stderr
, "Wrong acpi table provided\n");
5232 case QEMU_OPTION_smbios
:
5233 if(smbios_entry_add(optarg
) < 0) {
5234 fprintf(stderr
, "Wrong smbios provided\n");
5240 case QEMU_OPTION_enable_kvm
:
5244 case QEMU_OPTION_usb
:
5247 case QEMU_OPTION_usbdevice
:
5249 add_device_config(DEV_USB
, optarg
);
5251 case QEMU_OPTION_device
:
5252 opts
= qemu_opts_parse(&qemu_device_opts
, optarg
, "driver");
5254 fprintf(stderr
, "parse error: %s\n", optarg
);
5258 case QEMU_OPTION_smp
:
5261 fprintf(stderr
, "Invalid number of CPUs\n");
5264 if (max_cpus
< smp_cpus
) {
5265 fprintf(stderr
, "maxcpus must be equal to or greater than "
5269 if (max_cpus
> 255) {
5270 fprintf(stderr
, "Unsupported number of maxcpus\n");
5274 case QEMU_OPTION_vnc
:
5275 display_type
= DT_VNC
;
5276 vnc_display
= optarg
;
5279 case QEMU_OPTION_no_acpi
:
5282 case QEMU_OPTION_no_hpet
:
5285 case QEMU_OPTION_balloon
:
5286 if (balloon_parse(optarg
) < 0) {
5287 fprintf(stderr
, "Unknown -balloon argument %s\n", optarg
);
5292 case QEMU_OPTION_no_reboot
:
5295 case QEMU_OPTION_no_shutdown
:
5298 case QEMU_OPTION_show_cursor
:
5301 case QEMU_OPTION_uuid
:
5302 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5303 fprintf(stderr
, "Fail to parse UUID string."
5304 " Wrong format.\n");
5309 case QEMU_OPTION_daemonize
:
5313 case QEMU_OPTION_option_rom
:
5314 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5315 fprintf(stderr
, "Too many option ROMs\n");
5318 option_rom
[nb_option_roms
] = optarg
;
5321 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5322 case QEMU_OPTION_semihosting
:
5323 semihosting_enabled
= 1;
5326 case QEMU_OPTION_name
:
5327 qemu_name
= qemu_strdup(optarg
);
5329 char *p
= strchr(qemu_name
, ',');
5332 if (strncmp(p
, "process=", 8)) {
5333 fprintf(stderr
, "Unknown subargument %s to -name", p
);
5341 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5342 case QEMU_OPTION_prom_env
:
5343 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5344 fprintf(stderr
, "Too many prom variables\n");
5347 prom_envs
[nb_prom_envs
] = optarg
;
5352 case QEMU_OPTION_old_param
:
5356 case QEMU_OPTION_clock
:
5357 configure_alarms(optarg
);
5359 case QEMU_OPTION_startdate
:
5362 time_t rtc_start_date
;
5363 if (!strcmp(optarg
, "now")) {
5364 rtc_date_offset
= -1;
5366 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
5374 } else if (sscanf(optarg
, "%d-%d-%d",
5377 &tm
.tm_mday
) == 3) {
5386 rtc_start_date
= mktimegm(&tm
);
5387 if (rtc_start_date
== -1) {
5389 fprintf(stderr
, "Invalid date format. Valid format are:\n"
5390 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5393 rtc_date_offset
= time(NULL
) - rtc_start_date
;
5397 case QEMU_OPTION_tb_size
:
5398 tb_size
= strtol(optarg
, NULL
, 0);
5402 case QEMU_OPTION_icount
:
5404 if (strcmp(optarg
, "auto") == 0) {
5405 icount_time_shift
= -1;
5407 icount_time_shift
= strtol(optarg
, NULL
, 0);
5410 case QEMU_OPTION_incoming
:
5414 case QEMU_OPTION_chroot
:
5415 chroot_dir
= optarg
;
5417 case QEMU_OPTION_runas
:
5422 case QEMU_OPTION_xen_domid
:
5423 xen_domid
= atoi(optarg
);
5425 case QEMU_OPTION_xen_create
:
5426 xen_mode
= XEN_CREATE
;
5428 case QEMU_OPTION_xen_attach
:
5429 xen_mode
= XEN_ATTACH
;
5436 /* If no data_dir is specified then try to find it relative to the
5439 data_dir
= find_datadir(argv
[0]);
5441 /* If all else fails use the install patch specified when building. */
5443 data_dir
= CONFIG_QEMU_SHAREDIR
;
5447 * Default to max_cpus = smp_cpus, in case the user doesn't
5448 * specify a max_cpus value.
5451 max_cpus
= smp_cpus
;
5453 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5454 if (smp_cpus
> machine
->max_cpus
) {
5455 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5456 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5461 if (display_type
== DT_NOGRAPHIC
) {
5462 if (serial_device_index
== 0)
5463 serial_devices
[0] = "stdio";
5464 if (parallel_device_index
== 0)
5465 parallel_devices
[0] = "null";
5466 if (strncmp(monitor_devices
[0], "vc", 2) == 0) {
5467 monitor_devices
[0] = "stdio";
5475 if (pipe(fds
) == -1)
5486 len
= read(fds
[0], &status
, 1);
5487 if (len
== -1 && (errno
== EINTR
))
5492 else if (status
== 1) {
5493 fprintf(stderr
, "Could not acquire pidfile\n");
5510 signal(SIGTSTP
, SIG_IGN
);
5511 signal(SIGTTOU
, SIG_IGN
);
5512 signal(SIGTTIN
, SIG_IGN
);
5515 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5518 write(fds
[1], &status
, 1);
5520 fprintf(stderr
, "Could not acquire pid file\n");
5525 if (kvm_enabled()) {
5528 ret
= kvm_init(smp_cpus
);
5530 fprintf(stderr
, "failed to initialize KVM\n");
5535 if (qemu_init_main_loop()) {
5536 fprintf(stderr
, "qemu_init_main_loop failed\n");
5539 linux_boot
= (kernel_filename
!= NULL
);
5541 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5542 fprintf(stderr
, "-append only allowed with -kernel option\n");
5546 if (!linux_boot
&& initrd_filename
!= NULL
) {
5547 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5552 /* Win32 doesn't support line-buffering and requires size >= 2 */
5553 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5557 if (init_timer_alarm() < 0) {
5558 fprintf(stderr
, "could not initialize alarm timer\n");
5561 if (use_icount
&& icount_time_shift
< 0) {
5563 /* 125MIPS seems a reasonable initial guess at the guest speed.
5564 It will be corrected fairly quickly anyway. */
5565 icount_time_shift
= 3;
5566 init_icount_adjust();
5573 /* init network clients */
5574 if (nb_net_clients
== 0) {
5575 /* if no clients, we use a default config */
5576 net_clients
[nb_net_clients
++] = "nic";
5578 net_clients
[nb_net_clients
++] = "user";
5582 for(i
= 0;i
< nb_net_clients
; i
++) {
5583 if (net_client_parse(net_clients
[i
]) < 0)
5587 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5588 net_set_boot_mask(net_boot
);
5592 /* init the bluetooth world */
5593 if (foreach_device_config(DEV_BT
, bt_parse
))
5596 /* init the memory */
5598 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5600 /* init the dynamic translator */
5601 cpu_exec_init_all(tb_size
* 1024 * 1024);
5605 /* we always create the cdrom drive, even if no disk is there */
5606 drive_add(NULL
, CDROM_ALIAS
);
5608 /* we always create at least one floppy */
5609 drive_add(NULL
, FD_ALIAS
, 0);
5611 /* we always create one sd slot, even if no card is in it */
5612 drive_add(NULL
, SD_ALIAS
);
5614 /* open the virtual block devices */
5616 qemu_opts_foreach(&qemu_drive_opts
, drive_enable_snapshot
, NULL
, 0);
5617 if (qemu_opts_foreach(&qemu_drive_opts
, drive_init_func
, machine
, 1) != 0)
5620 vmstate_register(0, &vmstate_timers
,&timers_state
);
5621 register_savevm_live("ram", 0, 3, ram_save_live
, NULL
, ram_load
, NULL
);
5623 /* Maintain compatibility with multiple stdio monitors */
5624 if (!strcmp(monitor_devices
[0],"stdio")) {
5625 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5626 const char *devname
= serial_devices
[i
];
5627 if (devname
&& !strcmp(devname
,"mon:stdio")) {
5628 monitor_devices
[0] = NULL
;
5630 } else if (devname
&& !strcmp(devname
,"stdio")) {
5631 monitor_devices
[0] = NULL
;
5632 serial_devices
[i
] = "mon:stdio";
5638 if (nb_numa_nodes
> 0) {
5641 if (nb_numa_nodes
> smp_cpus
) {
5642 nb_numa_nodes
= smp_cpus
;
5645 /* If no memory size if given for any node, assume the default case
5646 * and distribute the available memory equally across all nodes
5648 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5649 if (node_mem
[i
] != 0)
5652 if (i
== nb_numa_nodes
) {
5653 uint64_t usedmem
= 0;
5655 /* On Linux, the each node's border has to be 8MB aligned,
5656 * the final node gets the rest.
5658 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
5659 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
5660 usedmem
+= node_mem
[i
];
5662 node_mem
[i
] = ram_size
- usedmem
;
5665 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5666 if (node_cpumask
[i
] != 0)
5669 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5670 * must cope with this anyway, because there are BIOSes out there in
5671 * real machines which also use this scheme.
5673 if (i
== nb_numa_nodes
) {
5674 for (i
= 0; i
< smp_cpus
; i
++) {
5675 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
5680 for (i
= 0; i
< MAX_MONITOR_DEVICES
; i
++) {
5681 const char *devname
= monitor_devices
[i
];
5682 if (devname
&& strcmp(devname
, "none")) {
5685 snprintf(label
, sizeof(label
), "monitor");
5687 snprintf(label
, sizeof(label
), "monitor%d", i
);
5689 monitor_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5690 if (!monitor_hds
[i
]) {
5691 fprintf(stderr
, "qemu: could not open monitor device '%s'\n",
5698 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5699 const char *devname
= serial_devices
[i
];
5700 if (devname
&& strcmp(devname
, "none")) {
5702 snprintf(label
, sizeof(label
), "serial%d", i
);
5703 serial_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5704 if (!serial_hds
[i
]) {
5705 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
5712 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
5713 const char *devname
= parallel_devices
[i
];
5714 if (devname
&& strcmp(devname
, "none")) {
5716 snprintf(label
, sizeof(label
), "parallel%d", i
);
5717 parallel_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5718 if (!parallel_hds
[i
]) {
5719 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
5726 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
5727 const char *devname
= virtio_consoles
[i
];
5728 if (devname
&& strcmp(devname
, "none")) {
5730 snprintf(label
, sizeof(label
), "virtcon%d", i
);
5731 virtcon_hds
[i
] = qemu_chr_open(label
, devname
, NULL
);
5732 if (!virtcon_hds
[i
]) {
5733 fprintf(stderr
, "qemu: could not open virtio console '%s'\n",
5740 module_call_init(MODULE_INIT_DEVICE
);
5743 i
= select_watchdog(watchdog
);
5745 exit (i
== 1 ? 1 : 0);
5748 if (machine
->compat_props
) {
5749 qdev_prop_register_compat(machine
->compat_props
);
5751 machine
->init(ram_size
, boot_devices
,
5752 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
5756 /* must be after terminal init, SDL library changes signal handlers */
5760 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
5761 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5762 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
5768 current_machine
= machine
;
5770 /* init USB devices */
5772 foreach_device_config(DEV_USB
, usb_parse
);
5775 /* init generic devices */
5776 if (qemu_opts_foreach(&qemu_device_opts
, device_init_func
, NULL
, 1) != 0)
5780 dumb_display_init();
5781 /* just use the first displaystate for the moment */
5784 if (display_type
== DT_DEFAULT
) {
5785 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5786 display_type
= DT_SDL
;
5788 display_type
= DT_VNC
;
5789 vnc_display
= "localhost:0,to=99";
5795 switch (display_type
) {
5798 #if defined(CONFIG_CURSES)
5800 curses_display_init(ds
, full_screen
);
5803 #if defined(CONFIG_SDL)
5805 sdl_display_init(ds
, full_screen
, no_frame
);
5807 #elif defined(CONFIG_COCOA)
5809 cocoa_display_init(ds
, full_screen
);
5813 vnc_display_init(ds
);
5814 if (vnc_display_open(ds
, vnc_display
) < 0)
5817 if (show_vnc_port
) {
5818 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
5826 dcl
= ds
->listeners
;
5827 while (dcl
!= NULL
) {
5828 if (dcl
->dpy_refresh
!= NULL
) {
5829 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
5830 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
5835 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
5836 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
5837 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
5840 text_consoles_set_display(display_state
);
5841 qemu_chr_initial_reset();
5843 for (i
= 0; i
< MAX_MONITOR_DEVICES
; i
++) {
5844 if (monitor_devices
[i
] && monitor_hds
[i
]) {
5845 monitor_init(monitor_hds
[i
],
5846 MONITOR_USE_READLINE
|
5847 ((i
== 0) ? MONITOR_IS_DEFAULT
: 0));
5851 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
5852 const char *devname
= serial_devices
[i
];
5853 if (devname
&& strcmp(devname
, "none")) {
5854 if (strstart(devname
, "vc", 0))
5855 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
5859 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
5860 const char *devname
= parallel_devices
[i
];
5861 if (devname
&& strcmp(devname
, "none")) {
5862 if (strstart(devname
, "vc", 0))
5863 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
5867 for(i
= 0; i
< MAX_VIRTIO_CONSOLES
; i
++) {
5868 const char *devname
= virtio_consoles
[i
];
5869 if (virtcon_hds
[i
] && devname
) {
5870 if (strstart(devname
, "vc", 0))
5871 qemu_chr_printf(virtcon_hds
[i
], "virtio console%d\r\n", i
);
5875 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
5876 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
5882 if (load_vmstate(cur_mon
, loadvm
) < 0) {
5888 qemu_start_incoming_migration(incoming
);
5889 } else if (autostart
) {
5899 len
= write(fds
[1], &status
, 1);
5900 if (len
== -1 && (errno
== EINTR
))
5907 TFR(fd
= open("/dev/null", O_RDWR
));
5913 pwd
= getpwnam(run_as
);
5915 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
5921 if (chroot(chroot_dir
) < 0) {
5922 fprintf(stderr
, "chroot failed\n");
5929 if (setgid(pwd
->pw_gid
) < 0) {
5930 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
5933 if (setuid(pwd
->pw_uid
) < 0) {
5934 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
5937 if (setuid(0) != -1) {
5938 fprintf(stderr
, "Dropping privileges failed\n");