4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
38 #include <sys/times.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
47 #include <arpa/inet.h>
50 #include <sys/select.h>
53 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
62 #include <linux/rtc.h>
63 #include <sys/prctl.h>
65 /* For the benefit of older linux systems which don't supply it,
66 we use a local copy of hpet.h. */
67 /* #include <linux/hpet.h> */
70 #include <linux/ppdev.h>
71 #include <linux/parport.h>
75 #include <sys/ethernet.h>
76 #include <sys/sockio.h>
77 #include <netinet/arp.h>
78 #include <netinet/in.h>
79 #include <netinet/in_systm.h>
80 #include <netinet/ip.h>
81 #include <netinet/ip_icmp.h> // must come after ip.h
82 #include <netinet/udp.h>
83 #include <netinet/tcp.h>
87 /* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
88 discussion about Solaris header problems */
89 extern int madvise(caddr_t
, size_t, int);
94 #if defined(__OpenBSD__)
98 #if defined(CONFIG_VDE)
99 #include <libvdeplug.h>
104 #include <mmsystem.h>
108 #if defined(__APPLE__) || defined(main)
110 int qemu_main(int argc
, char **argv
, char **envp
);
111 int main(int argc
, char **argv
)
113 return qemu_main(argc
, argv
, NULL
);
116 #define main qemu_main
118 #endif /* CONFIG_SDL */
122 #define main qemu_main
123 #endif /* CONFIG_COCOA */
126 #include "hw/boards.h"
128 #include "hw/pcmcia.h"
130 #include "hw/audiodev.h"
134 #include "hw/watchdog.h"
135 #include "hw/smbios.h"
138 #include "hw/loader.h"
141 #include "net/slirp.h"
146 #include "qemu-timer.h"
147 #include "qemu-char.h"
148 #include "cache-utils.h"
150 #include "block_int.h"
151 #include "block-migration.h"
153 #include "audio/audio.h"
154 #include "migration.h"
157 #include "qemu-option.h"
158 #include "qemu-config.h"
159 #include "qemu-objects.h"
163 #include "exec-all.h"
165 #include "qemu_socket.h"
167 #include "slirp/libslirp.h"
169 #include "qemu-queue.h"
172 //#define DEBUG_SLIRP
174 #define DEFAULT_RAM_SIZE 128
176 static const char *data_dir
;
177 const char *bios_name
= NULL
;
178 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
179 to store the VM snapshots */
180 struct drivelist drives
= QTAILQ_HEAD_INITIALIZER(drives
);
181 struct driveoptlist driveopts
= QTAILQ_HEAD_INITIALIZER(driveopts
);
182 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
183 static DisplayState
*display_state
;
184 DisplayType display_type
= DT_DEFAULT
;
185 const char* keyboard_layout
= NULL
;
188 NICInfo nd_table
[MAX_NICS
];
191 static int rtc_utc
= 1;
192 static int rtc_date_offset
= -1; /* -1 means no change */
193 QEMUClock
*rtc_clock
;
194 int vga_interface_type
= VGA_NONE
;
196 int graphic_width
= 1024;
197 int graphic_height
= 768;
198 int graphic_depth
= 8;
200 int graphic_width
= 800;
201 int graphic_height
= 600;
202 int graphic_depth
= 15;
204 static int full_screen
= 0;
206 static int no_frame
= 0;
209 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
210 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
211 CharDriverState
*virtcon_hds
[MAX_VIRTIO_CONSOLES
];
213 int win2k_install_hack
= 0;
222 const char *vnc_display
;
223 int acpi_enabled
= 1;
229 int graphic_rotate
= 0;
230 uint8_t irq0override
= 1;
234 const char *watchdog
;
235 const char *option_rom
[MAX_OPTION_ROMS
];
237 int semihosting_enabled
= 0;
241 const char *qemu_name
;
244 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
245 unsigned int nb_prom_envs
= 0;
246 const char *prom_envs
[MAX_PROM_ENVS
];
251 uint64_t node_mem
[MAX_NODES
];
252 uint64_t node_cpumask
[MAX_NODES
];
254 static CPUState
*cur_cpu
;
255 static CPUState
*next_cpu
;
256 static int timer_alarm_pending
= 1;
257 /* Conversion factor from emulated instructions to virtual clock ticks. */
258 static int icount_time_shift
;
259 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
260 #define MAX_ICOUNT_SHIFT 10
261 /* Compensate for varying guest execution speed. */
262 static int64_t qemu_icount_bias
;
263 static QEMUTimer
*icount_rt_timer
;
264 static QEMUTimer
*icount_vm_timer
;
265 static QEMUTimer
*nographic_timer
;
267 uint8_t qemu_uuid
[16];
269 static QEMUBootSetHandler
*boot_set_handler
;
270 static void *boot_set_opaque
;
272 static int default_serial
= 1;
273 static int default_parallel
= 1;
274 static int default_virtcon
= 1;
275 static int default_monitor
= 1;
276 static int default_vga
= 1;
277 static int default_floppy
= 1;
278 static int default_cdrom
= 1;
279 static int default_sdcard
= 1;
285 { .driver
= "isa-serial", .flag
= &default_serial
},
286 { .driver
= "isa-parallel", .flag
= &default_parallel
},
287 { .driver
= "isa-fdc", .flag
= &default_floppy
},
288 { .driver
= "ide-drive", .flag
= &default_cdrom
},
289 { .driver
= "virtio-console-pci", .flag
= &default_virtcon
},
290 { .driver
= "virtio-console-s390", .flag
= &default_virtcon
},
291 { .driver
= "VGA", .flag
= &default_vga
},
292 { .driver
= "cirrus-vga", .flag
= &default_vga
},
293 { .driver
= "vmware-svga", .flag
= &default_vga
},
296 static int default_driver_check(QemuOpts
*opts
, void *opaque
)
298 const char *driver
= qemu_opt_get(opts
, "driver");
303 for (i
= 0; i
< ARRAY_SIZE(default_list
); i
++) {
304 if (strcmp(default_list
[i
].driver
, driver
) != 0)
306 *(default_list
[i
].flag
) = 0;
311 /***********************************************************/
312 /* x86 ISA bus support */
314 target_phys_addr_t isa_mem_base
= 0;
317 /***********************************************************/
318 void hw_error(const char *fmt
, ...)
324 fprintf(stderr
, "qemu: hardware error: ");
325 vfprintf(stderr
, fmt
, ap
);
326 fprintf(stderr
, "\n");
327 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
328 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
330 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
332 cpu_dump_state(env
, stderr
, fprintf
, 0);
339 static void set_proc_name(const char *s
)
341 #if defined(__linux__) && defined(PR_SET_NAME)
345 name
[sizeof(name
) - 1] = 0;
346 strncpy(name
, s
, sizeof(name
));
347 /* Could rewrite argv[0] too, but that's a bit more complicated.
348 This simple way is enough for `top'. */
349 prctl(PR_SET_NAME
, name
);
356 static QEMUBalloonEvent
*qemu_balloon_event
;
357 void *qemu_balloon_event_opaque
;
359 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
361 qemu_balloon_event
= func
;
362 qemu_balloon_event_opaque
= opaque
;
365 void qemu_balloon(ram_addr_t target
)
367 if (qemu_balloon_event
)
368 qemu_balloon_event(qemu_balloon_event_opaque
, target
);
371 ram_addr_t
qemu_balloon_status(void)
373 if (qemu_balloon_event
)
374 return qemu_balloon_event(qemu_balloon_event_opaque
, 0);
379 /***********************************************************/
380 /* real time host monotonic timer */
382 /* compute with 96 bit intermediate result: (a*b)/c */
383 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
388 #ifdef HOST_WORDS_BIGENDIAN
398 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
399 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
402 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
406 static int64_t get_clock_realtime(void)
410 gettimeofday(&tv
, NULL
);
411 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
416 static int64_t clock_freq
;
418 static void init_get_clock(void)
422 ret
= QueryPerformanceFrequency(&freq
);
424 fprintf(stderr
, "Could not calibrate ticks\n");
427 clock_freq
= freq
.QuadPart
;
430 static int64_t get_clock(void)
433 QueryPerformanceCounter(&ti
);
434 return muldiv64(ti
.QuadPart
, get_ticks_per_sec(), clock_freq
);
439 static int use_rt_clock
;
441 static void init_get_clock(void)
444 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
445 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
448 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
455 static int64_t get_clock(void)
457 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
458 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
461 clock_gettime(CLOCK_MONOTONIC
, &ts
);
462 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
466 /* XXX: using gettimeofday leads to problems if the date
467 changes, so it should be avoided. */
468 return get_clock_realtime();
473 /* Return the virtual CPU time, based on the instruction counter. */
474 static int64_t cpu_get_icount(void)
477 CPUState
*env
= cpu_single_env
;;
478 icount
= qemu_icount
;
481 fprintf(stderr
, "Bad clock read\n");
482 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
484 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
487 /***********************************************************/
488 /* guest cycle counter */
490 typedef struct TimersState
{
491 int64_t cpu_ticks_prev
;
492 int64_t cpu_ticks_offset
;
493 int64_t cpu_clock_offset
;
494 int32_t cpu_ticks_enabled
;
498 TimersState timers_state
;
500 /* return the host CPU cycle counter and handle stop/restart */
501 int64_t cpu_get_ticks(void)
504 return cpu_get_icount();
506 if (!timers_state
.cpu_ticks_enabled
) {
507 return timers_state
.cpu_ticks_offset
;
510 ticks
= cpu_get_real_ticks();
511 if (timers_state
.cpu_ticks_prev
> ticks
) {
512 /* Note: non increasing ticks may happen if the host uses
514 timers_state
.cpu_ticks_offset
+= timers_state
.cpu_ticks_prev
- ticks
;
516 timers_state
.cpu_ticks_prev
= ticks
;
517 return ticks
+ timers_state
.cpu_ticks_offset
;
521 /* return the host CPU monotonic timer and handle stop/restart */
522 static int64_t cpu_get_clock(void)
525 if (!timers_state
.cpu_ticks_enabled
) {
526 return timers_state
.cpu_clock_offset
;
529 return ti
+ timers_state
.cpu_clock_offset
;
533 /* enable cpu_get_ticks() */
534 void cpu_enable_ticks(void)
536 if (!timers_state
.cpu_ticks_enabled
) {
537 timers_state
.cpu_ticks_offset
-= cpu_get_real_ticks();
538 timers_state
.cpu_clock_offset
-= get_clock();
539 timers_state
.cpu_ticks_enabled
= 1;
543 /* disable cpu_get_ticks() : the clock is stopped. You must not call
544 cpu_get_ticks() after that. */
545 void cpu_disable_ticks(void)
547 if (timers_state
.cpu_ticks_enabled
) {
548 timers_state
.cpu_ticks_offset
= cpu_get_ticks();
549 timers_state
.cpu_clock_offset
= cpu_get_clock();
550 timers_state
.cpu_ticks_enabled
= 0;
554 /***********************************************************/
557 #define QEMU_CLOCK_REALTIME 0
558 #define QEMU_CLOCK_VIRTUAL 1
559 #define QEMU_CLOCK_HOST 2
563 /* XXX: add frequency */
571 struct QEMUTimer
*next
;
574 struct qemu_alarm_timer
{
578 int (*start
)(struct qemu_alarm_timer
*t
);
579 void (*stop
)(struct qemu_alarm_timer
*t
);
580 void (*rearm
)(struct qemu_alarm_timer
*t
);
584 #define ALARM_FLAG_DYNTICKS 0x1
585 #define ALARM_FLAG_EXPIRED 0x2
587 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
589 return t
&& (t
->flags
& ALARM_FLAG_DYNTICKS
);
592 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
594 if (!alarm_has_dynticks(t
))
600 /* TODO: MIN_TIMER_REARM_US should be optimized */
601 #define MIN_TIMER_REARM_US 250
603 static struct qemu_alarm_timer
*alarm_timer
;
607 struct qemu_alarm_win32
{
610 } alarm_win32_data
= {0, -1};
612 static int win32_start_timer(struct qemu_alarm_timer
*t
);
613 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
614 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
618 static int unix_start_timer(struct qemu_alarm_timer
*t
);
619 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
623 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
624 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
625 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
627 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
628 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
630 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
631 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
633 #endif /* __linux__ */
637 /* Correlation between real and virtual time is always going to be
638 fairly approximate, so ignore small variation.
639 When the guest is idle real and virtual time will be aligned in
641 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
643 static void icount_adjust(void)
648 static int64_t last_delta
;
649 /* If the VM is not running, then do nothing. */
653 cur_time
= cpu_get_clock();
654 cur_icount
= qemu_get_clock(vm_clock
);
655 delta
= cur_icount
- cur_time
;
656 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
658 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
659 && icount_time_shift
> 0) {
660 /* The guest is getting too far ahead. Slow time down. */
664 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
665 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
666 /* The guest is getting too far behind. Speed time up. */
670 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
673 static void icount_adjust_rt(void * opaque
)
675 qemu_mod_timer(icount_rt_timer
,
676 qemu_get_clock(rt_clock
) + 1000);
680 static void icount_adjust_vm(void * opaque
)
682 qemu_mod_timer(icount_vm_timer
,
683 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
687 static void init_icount_adjust(void)
689 /* Have both realtime and virtual time triggers for speed adjustment.
690 The realtime trigger catches emulated time passing too slowly,
691 the virtual time trigger catches emulated time passing too fast.
692 Realtime triggers occur even when idle, so use them less frequently
694 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
695 qemu_mod_timer(icount_rt_timer
,
696 qemu_get_clock(rt_clock
) + 1000);
697 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
698 qemu_mod_timer(icount_vm_timer
,
699 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
702 static struct qemu_alarm_timer alarm_timers
[] = {
705 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
706 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
707 /* HPET - if available - is preferred */
708 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
709 /* ...otherwise try RTC */
710 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
712 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
714 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
715 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
716 {"win32", 0, win32_start_timer
,
717 win32_stop_timer
, NULL
, &alarm_win32_data
},
722 static void show_available_alarms(void)
726 printf("Available alarm timers, in order of precedence:\n");
727 for (i
= 0; alarm_timers
[i
].name
; i
++)
728 printf("%s\n", alarm_timers
[i
].name
);
731 static void configure_alarms(char const *opt
)
735 int count
= ARRAY_SIZE(alarm_timers
) - 1;
738 struct qemu_alarm_timer tmp
;
740 if (!strcmp(opt
, "?")) {
741 show_available_alarms();
745 arg
= qemu_strdup(opt
);
747 /* Reorder the array */
748 name
= strtok(arg
, ",");
750 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
751 if (!strcmp(alarm_timers
[i
].name
, name
))
756 fprintf(stderr
, "Unknown clock %s\n", name
);
765 tmp
= alarm_timers
[i
];
766 alarm_timers
[i
] = alarm_timers
[cur
];
767 alarm_timers
[cur
] = tmp
;
771 name
= strtok(NULL
, ",");
777 /* Disable remaining timers */
778 for (i
= cur
; i
< count
; i
++)
779 alarm_timers
[i
].name
= NULL
;
781 show_available_alarms();
786 #define QEMU_NUM_CLOCKS 3
790 QEMUClock
*host_clock
;
792 static QEMUTimer
*active_timers
[QEMU_NUM_CLOCKS
];
794 static QEMUClock
*qemu_new_clock(int type
)
797 clock
= qemu_mallocz(sizeof(QEMUClock
));
802 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
806 ts
= qemu_mallocz(sizeof(QEMUTimer
));
813 void qemu_free_timer(QEMUTimer
*ts
)
818 /* stop a timer, but do not dealloc it */
819 void qemu_del_timer(QEMUTimer
*ts
)
823 /* NOTE: this code must be signal safe because
824 qemu_timer_expired() can be called from a signal. */
825 pt
= &active_timers
[ts
->clock
->type
];
838 /* modify the current timer so that it will be fired when current_time
839 >= expire_time. The corresponding callback will be called. */
840 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
846 /* add the timer in the sorted list */
847 /* NOTE: this code must be signal safe because
848 qemu_timer_expired() can be called from a signal. */
849 pt
= &active_timers
[ts
->clock
->type
];
854 if (t
->expire_time
> expire_time
)
858 ts
->expire_time
= expire_time
;
862 /* Rearm if necessary */
863 if (pt
== &active_timers
[ts
->clock
->type
]) {
864 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
865 qemu_rearm_alarm_timer(alarm_timer
);
867 /* Interrupt execution to force deadline recalculation. */
873 int qemu_timer_pending(QEMUTimer
*ts
)
876 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
883 int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
887 return (timer_head
->expire_time
<= current_time
);
890 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
896 if (!ts
|| ts
->expire_time
> current_time
)
898 /* remove timer from the list before calling the callback */
899 *ptimer_head
= ts
->next
;
902 /* run the callback (the timer list can be modified) */
907 int64_t qemu_get_clock(QEMUClock
*clock
)
909 switch(clock
->type
) {
910 case QEMU_CLOCK_REALTIME
:
911 return get_clock() / 1000000;
913 case QEMU_CLOCK_VIRTUAL
:
915 return cpu_get_icount();
917 return cpu_get_clock();
919 case QEMU_CLOCK_HOST
:
920 return get_clock_realtime();
924 static void init_clocks(void)
927 rt_clock
= qemu_new_clock(QEMU_CLOCK_REALTIME
);
928 vm_clock
= qemu_new_clock(QEMU_CLOCK_VIRTUAL
);
929 host_clock
= qemu_new_clock(QEMU_CLOCK_HOST
);
931 rtc_clock
= host_clock
;
935 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
937 uint64_t expire_time
;
939 if (qemu_timer_pending(ts
)) {
940 expire_time
= ts
->expire_time
;
944 qemu_put_be64(f
, expire_time
);
947 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
949 uint64_t expire_time
;
951 expire_time
= qemu_get_be64(f
);
952 if (expire_time
!= -1) {
953 qemu_mod_timer(ts
, expire_time
);
959 static const VMStateDescription vmstate_timers
= {
962 .minimum_version_id
= 1,
963 .minimum_version_id_old
= 1,
964 .fields
= (VMStateField
[]) {
965 VMSTATE_INT64(cpu_ticks_offset
, TimersState
),
966 VMSTATE_INT64(dummy
, TimersState
),
967 VMSTATE_INT64_V(cpu_clock_offset
, TimersState
, 2),
968 VMSTATE_END_OF_LIST()
972 static void qemu_event_increment(void);
975 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
976 DWORD_PTR dwUser
, DWORD_PTR dw1
,
979 static void host_alarm_handler(int host_signum
)
983 #define DISP_FREQ 1000
985 static int64_t delta_min
= INT64_MAX
;
986 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
988 ti
= qemu_get_clock(vm_clock
);
989 if (last_clock
!= 0) {
990 delta
= ti
- last_clock
;
991 if (delta
< delta_min
)
993 if (delta
> delta_max
)
996 if (++count
== DISP_FREQ
) {
997 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
998 muldiv64(delta_min
, 1000000, get_ticks_per_sec()),
999 muldiv64(delta_max
, 1000000, get_ticks_per_sec()),
1000 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, get_ticks_per_sec()),
1001 (double)get_ticks_per_sec() / ((double)delta_cum
/ DISP_FREQ
));
1003 delta_min
= INT64_MAX
;
1011 if (alarm_has_dynticks(alarm_timer
) ||
1013 qemu_timer_expired(active_timers
[QEMU_CLOCK_VIRTUAL
],
1014 qemu_get_clock(vm_clock
))) ||
1015 qemu_timer_expired(active_timers
[QEMU_CLOCK_REALTIME
],
1016 qemu_get_clock(rt_clock
)) ||
1017 qemu_timer_expired(active_timers
[QEMU_CLOCK_HOST
],
1018 qemu_get_clock(host_clock
))) {
1019 qemu_event_increment();
1020 if (alarm_timer
) alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1022 #ifndef CONFIG_IOTHREAD
1024 /* stop the currently executing cpu because a timer occured */
1028 timer_alarm_pending
= 1;
1029 qemu_notify_event();
1033 static int64_t qemu_next_deadline(void)
1035 /* To avoid problems with overflow limit this to 2^32. */
1036 int64_t delta
= INT32_MAX
;
1038 if (active_timers
[QEMU_CLOCK_VIRTUAL
]) {
1039 delta
= active_timers
[QEMU_CLOCK_VIRTUAL
]->expire_time
-
1040 qemu_get_clock(vm_clock
);
1042 if (active_timers
[QEMU_CLOCK_HOST
]) {
1043 int64_t hdelta
= active_timers
[QEMU_CLOCK_HOST
]->expire_time
-
1044 qemu_get_clock(host_clock
);
1055 #if defined(__linux__)
1056 static uint64_t qemu_next_deadline_dyntick(void)
1064 delta
= (qemu_next_deadline() + 999) / 1000;
1066 if (active_timers
[QEMU_CLOCK_REALTIME
]) {
1067 rtdelta
= (active_timers
[QEMU_CLOCK_REALTIME
]->expire_time
-
1068 qemu_get_clock(rt_clock
))*1000;
1069 if (rtdelta
< delta
)
1073 if (delta
< MIN_TIMER_REARM_US
)
1074 delta
= MIN_TIMER_REARM_US
;
1082 /* Sets a specific flag */
1083 static int fcntl_setfl(int fd
, int flag
)
1087 flags
= fcntl(fd
, F_GETFL
);
1091 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1097 #if defined(__linux__)
1099 #define RTC_FREQ 1024
1101 static void enable_sigio_timer(int fd
)
1103 struct sigaction act
;
1106 sigfillset(&act
.sa_mask
);
1108 act
.sa_handler
= host_alarm_handler
;
1110 sigaction(SIGIO
, &act
, NULL
);
1111 fcntl_setfl(fd
, O_ASYNC
);
1112 fcntl(fd
, F_SETOWN
, getpid());
1115 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1117 struct hpet_info info
;
1120 fd
= qemu_open("/dev/hpet", O_RDONLY
);
1125 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1127 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1128 "error, but for better emulation accuracy type:\n"
1129 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1133 /* Check capabilities */
1134 r
= ioctl(fd
, HPET_INFO
, &info
);
1138 /* Enable periodic mode */
1139 r
= ioctl(fd
, HPET_EPI
, 0);
1140 if (info
.hi_flags
&& (r
< 0))
1143 /* Enable interrupt */
1144 r
= ioctl(fd
, HPET_IE_ON
, 0);
1148 enable_sigio_timer(fd
);
1149 t
->priv
= (void *)(long)fd
;
1157 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1159 int fd
= (long)t
->priv
;
1164 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1167 unsigned long current_rtc_freq
= 0;
1169 TFR(rtc_fd
= qemu_open("/dev/rtc", O_RDONLY
));
1172 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1173 if (current_rtc_freq
!= RTC_FREQ
&&
1174 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1175 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1176 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1177 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1180 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1186 enable_sigio_timer(rtc_fd
);
1188 t
->priv
= (void *)(long)rtc_fd
;
1193 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1195 int rtc_fd
= (long)t
->priv
;
1200 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1204 struct sigaction act
;
1206 sigfillset(&act
.sa_mask
);
1208 act
.sa_handler
= host_alarm_handler
;
1210 sigaction(SIGALRM
, &act
, NULL
);
1213 * Initialize ev struct to 0 to avoid valgrind complaining
1214 * about uninitialized data in timer_create call
1216 memset(&ev
, 0, sizeof(ev
));
1217 ev
.sigev_value
.sival_int
= 0;
1218 ev
.sigev_notify
= SIGEV_SIGNAL
;
1219 ev
.sigev_signo
= SIGALRM
;
1221 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1222 perror("timer_create");
1224 /* disable dynticks */
1225 fprintf(stderr
, "Dynamic Ticks disabled\n");
1230 t
->priv
= (void *)(long)host_timer
;
1235 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1237 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1239 timer_delete(host_timer
);
1242 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1244 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1245 struct itimerspec timeout
;
1246 int64_t nearest_delta_us
= INT64_MAX
;
1249 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1250 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1251 !active_timers
[QEMU_CLOCK_HOST
])
1254 nearest_delta_us
= qemu_next_deadline_dyntick();
1256 /* check whether a timer is already running */
1257 if (timer_gettime(host_timer
, &timeout
)) {
1259 fprintf(stderr
, "Internal timer error: aborting\n");
1262 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1263 if (current_us
&& current_us
<= nearest_delta_us
)
1266 timeout
.it_interval
.tv_sec
= 0;
1267 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1268 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1269 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1270 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1272 fprintf(stderr
, "Internal timer error: aborting\n");
1277 #endif /* defined(__linux__) */
1279 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1281 struct sigaction act
;
1282 struct itimerval itv
;
1286 sigfillset(&act
.sa_mask
);
1288 act
.sa_handler
= host_alarm_handler
;
1290 sigaction(SIGALRM
, &act
, NULL
);
1292 itv
.it_interval
.tv_sec
= 0;
1293 /* for i386 kernel 2.6 to get 1 ms */
1294 itv
.it_interval
.tv_usec
= 999;
1295 itv
.it_value
.tv_sec
= 0;
1296 itv
.it_value
.tv_usec
= 10 * 1000;
1298 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1305 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1307 struct itimerval itv
;
1309 memset(&itv
, 0, sizeof(itv
));
1310 setitimer(ITIMER_REAL
, &itv
, NULL
);
1313 #endif /* !defined(_WIN32) */
1318 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1321 struct qemu_alarm_win32
*data
= t
->priv
;
1324 memset(&tc
, 0, sizeof(tc
));
1325 timeGetDevCaps(&tc
, sizeof(tc
));
1327 if (data
->period
< tc
.wPeriodMin
)
1328 data
->period
= tc
.wPeriodMin
;
1330 timeBeginPeriod(data
->period
);
1332 flags
= TIME_CALLBACK_FUNCTION
;
1333 if (alarm_has_dynticks(t
))
1334 flags
|= TIME_ONESHOT
;
1336 flags
|= TIME_PERIODIC
;
1338 data
->timerId
= timeSetEvent(1, // interval (ms)
1339 data
->period
, // resolution
1340 host_alarm_handler
, // function
1341 (DWORD
)t
, // parameter
1344 if (!data
->timerId
) {
1345 fprintf(stderr
, "Failed to initialize win32 alarm timer: %ld\n",
1347 timeEndPeriod(data
->period
);
1354 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1356 struct qemu_alarm_win32
*data
= t
->priv
;
1358 timeKillEvent(data
->timerId
);
1359 timeEndPeriod(data
->period
);
1362 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1364 struct qemu_alarm_win32
*data
= t
->priv
;
1366 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1367 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1368 !active_timers
[QEMU_CLOCK_HOST
])
1371 timeKillEvent(data
->timerId
);
1373 data
->timerId
= timeSetEvent(1,
1377 TIME_ONESHOT
| TIME_PERIODIC
);
1379 if (!data
->timerId
) {
1380 fprintf(stderr
, "Failed to re-arm win32 alarm timer %ld\n",
1383 timeEndPeriod(data
->period
);
1390 static int init_timer_alarm(void)
1392 struct qemu_alarm_timer
*t
= NULL
;
1395 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1396 t
= &alarm_timers
[i
];
1416 static void quit_timers(void)
1418 alarm_timer
->stop(alarm_timer
);
1422 /***********************************************************/
1423 /* host time/date access */
1424 void qemu_get_timedate(struct tm
*tm
, int offset
)
1431 if (rtc_date_offset
== -1) {
1435 ret
= localtime(&ti
);
1437 ti
-= rtc_date_offset
;
1441 memcpy(tm
, ret
, sizeof(struct tm
));
1444 int qemu_timedate_diff(struct tm
*tm
)
1448 if (rtc_date_offset
== -1)
1450 seconds
= mktimegm(tm
);
1452 seconds
= mktime(tm
);
1454 seconds
= mktimegm(tm
) + rtc_date_offset
;
1456 return seconds
- time(NULL
);
1459 static void configure_rtc_date_offset(const char *startdate
, int legacy
)
1461 time_t rtc_start_date
;
1464 if (!strcmp(startdate
, "now") && legacy
) {
1465 rtc_date_offset
= -1;
1467 if (sscanf(startdate
, "%d-%d-%dT%d:%d:%d",
1475 } else if (sscanf(startdate
, "%d-%d-%d",
1478 &tm
.tm_mday
) == 3) {
1487 rtc_start_date
= mktimegm(&tm
);
1488 if (rtc_start_date
== -1) {
1490 fprintf(stderr
, "Invalid date format. Valid formats are:\n"
1491 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1494 rtc_date_offset
= time(NULL
) - rtc_start_date
;
1498 static void configure_rtc(QemuOpts
*opts
)
1502 value
= qemu_opt_get(opts
, "base");
1504 if (!strcmp(value
, "utc")) {
1506 } else if (!strcmp(value
, "localtime")) {
1509 configure_rtc_date_offset(value
, 0);
1512 value
= qemu_opt_get(opts
, "clock");
1514 if (!strcmp(value
, "host")) {
1515 rtc_clock
= host_clock
;
1516 } else if (!strcmp(value
, "vm")) {
1517 rtc_clock
= vm_clock
;
1519 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1523 #ifdef CONFIG_TARGET_I386
1524 value
= qemu_opt_get(opts
, "driftfix");
1526 if (!strcmp(buf
, "slew")) {
1528 } else if (!strcmp(buf
, "none")) {
1531 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1539 static void socket_cleanup(void)
1544 static int socket_init(void)
1549 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1551 err
= WSAGetLastError();
1552 fprintf(stderr
, "WSAStartup: %d\n", err
);
1555 atexit(socket_cleanup
);
1560 /***********************************************************/
1561 /* Bluetooth support */
1564 static struct HCIInfo
*hci_table
[MAX_NICS
];
1566 static struct bt_vlan_s
{
1567 struct bt_scatternet_s net
;
1569 struct bt_vlan_s
*next
;
1572 /* find or alloc a new bluetooth "VLAN" */
1573 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1575 struct bt_vlan_s
**pvlan
, *vlan
;
1576 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1580 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1582 pvlan
= &first_bt_vlan
;
1583 while (*pvlan
!= NULL
)
1584 pvlan
= &(*pvlan
)->next
;
1589 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1593 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1598 static struct HCIInfo null_hci
= {
1599 .cmd_send
= null_hci_send
,
1600 .sco_send
= null_hci_send
,
1601 .acl_send
= null_hci_send
,
1602 .bdaddr_set
= null_hci_addr_set
,
1605 struct HCIInfo
*qemu_next_hci(void)
1607 if (cur_hci
== nb_hcis
)
1610 return hci_table
[cur_hci
++];
1613 static struct HCIInfo
*hci_init(const char *str
)
1616 struct bt_scatternet_s
*vlan
= 0;
1618 if (!strcmp(str
, "null"))
1621 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
1623 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
1624 else if (!strncmp(str
, "hci", 3)) {
1627 if (!strncmp(str
+ 3, ",vlan=", 6)) {
1628 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
1633 vlan
= qemu_find_bt_vlan(0);
1635 return bt_new_hci(vlan
);
1638 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
1643 static int bt_hci_parse(const char *str
)
1645 struct HCIInfo
*hci
;
1648 if (nb_hcis
>= MAX_NICS
) {
1649 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
1653 hci
= hci_init(str
);
1662 bdaddr
.b
[5] = 0x56 + nb_hcis
;
1663 hci
->bdaddr_set(hci
, bdaddr
.b
);
1665 hci_table
[nb_hcis
++] = hci
;
1670 static void bt_vhci_add(int vlan_id
)
1672 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
1675 fprintf(stderr
, "qemu: warning: adding a VHCI to "
1676 "an empty scatternet %i\n", vlan_id
);
1678 bt_vhci_init(bt_new_hci(vlan
));
1681 static struct bt_device_s
*bt_device_add(const char *opt
)
1683 struct bt_scatternet_s
*vlan
;
1685 char *endp
= strstr(opt
, ",vlan=");
1686 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
1689 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
1692 vlan_id
= strtol(endp
+ 6, &endp
, 0);
1694 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
1699 vlan
= qemu_find_bt_vlan(vlan_id
);
1702 fprintf(stderr
, "qemu: warning: adding a slave device to "
1703 "an empty scatternet %i\n", vlan_id
);
1705 if (!strcmp(devname
, "keyboard"))
1706 return bt_keyboard_init(vlan
);
1708 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
1712 static int bt_parse(const char *opt
)
1714 const char *endp
, *p
;
1717 if (strstart(opt
, "hci", &endp
)) {
1718 if (!*endp
|| *endp
== ',') {
1720 if (!strstart(endp
, ",vlan=", 0))
1723 return bt_hci_parse(opt
);
1725 } else if (strstart(opt
, "vhci", &endp
)) {
1726 if (!*endp
|| *endp
== ',') {
1728 if (strstart(endp
, ",vlan=", &p
)) {
1729 vlan
= strtol(p
, (char **) &endp
, 0);
1731 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
1735 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
1744 } else if (strstart(opt
, "device:", &endp
))
1745 return !bt_device_add(endp
);
1747 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
1751 /***********************************************************/
1752 /* QEMU Block devices */
1754 #define HD_ALIAS "index=%d,media=disk"
1755 #define CDROM_ALIAS "index=2,media=cdrom"
1756 #define FD_ALIAS "index=%d,if=floppy"
1757 #define PFLASH_ALIAS "if=pflash"
1758 #define MTD_ALIAS "if=mtd"
1759 #define SD_ALIAS "index=0,if=sd"
1761 QemuOpts
*drive_add(const char *file
, const char *fmt
, ...)
1768 vsnprintf(optstr
, sizeof(optstr
), fmt
, ap
);
1771 opts
= qemu_opts_parse(&qemu_drive_opts
, optstr
, NULL
);
1773 fprintf(stderr
, "%s: huh? duplicate? (%s)\n",
1774 __FUNCTION__
, optstr
);
1778 qemu_opt_set(opts
, "file", file
);
1782 DriveInfo
*drive_get(BlockInterfaceType type
, int bus
, int unit
)
1786 /* seek interface, bus and unit */
1788 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1789 if (dinfo
->type
== type
&&
1790 dinfo
->bus
== bus
&&
1791 dinfo
->unit
== unit
)
1798 DriveInfo
*drive_get_by_id(const char *id
)
1802 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1803 if (strcmp(id
, dinfo
->id
))
1810 int drive_get_max_bus(BlockInterfaceType type
)
1816 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1817 if(dinfo
->type
== type
&&
1818 dinfo
->bus
> max_bus
)
1819 max_bus
= dinfo
->bus
;
1824 const char *drive_get_serial(BlockDriverState
*bdrv
)
1828 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1829 if (dinfo
->bdrv
== bdrv
)
1830 return dinfo
->serial
;
1836 BlockInterfaceErrorAction
drive_get_on_error(
1837 BlockDriverState
*bdrv
, int is_read
)
1841 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1842 if (dinfo
->bdrv
== bdrv
)
1843 return is_read
? dinfo
->on_read_error
: dinfo
->on_write_error
;
1846 return is_read
? BLOCK_ERR_REPORT
: BLOCK_ERR_STOP_ENOSPC
;
1849 static void bdrv_format_print(void *opaque
, const char *name
)
1851 fprintf(stderr
, " %s", name
);
1854 void drive_uninit(DriveInfo
*dinfo
)
1856 qemu_opts_del(dinfo
->opts
);
1857 bdrv_delete(dinfo
->bdrv
);
1858 QTAILQ_REMOVE(&drives
, dinfo
, next
);
1862 static int parse_block_error_action(const char *buf
, int is_read
)
1864 if (!strcmp(buf
, "ignore")) {
1865 return BLOCK_ERR_IGNORE
;
1866 } else if (!is_read
&& !strcmp(buf
, "enospc")) {
1867 return BLOCK_ERR_STOP_ENOSPC
;
1868 } else if (!strcmp(buf
, "stop")) {
1869 return BLOCK_ERR_STOP_ANY
;
1870 } else if (!strcmp(buf
, "report")) {
1871 return BLOCK_ERR_REPORT
;
1873 fprintf(stderr
, "qemu: '%s' invalid %s error action\n",
1874 buf
, is_read
? "read" : "write");
1879 DriveInfo
*drive_init(QemuOpts
*opts
, void *opaque
,
1883 const char *file
= NULL
;
1886 const char *mediastr
= "";
1887 BlockInterfaceType type
;
1888 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
1889 int bus_id
, unit_id
;
1890 int cyls
, heads
, secs
, translation
;
1891 BlockDriver
*drv
= NULL
;
1892 QEMUMachine
*machine
= opaque
;
1899 int on_read_error
, on_write_error
;
1900 const char *devaddr
;
1906 translation
= BIOS_ATA_TRANSLATION_AUTO
;
1909 if (machine
&& machine
->use_scsi
) {
1911 max_devs
= MAX_SCSI_DEVS
;
1912 pstrcpy(devname
, sizeof(devname
), "scsi");
1915 max_devs
= MAX_IDE_DEVS
;
1916 pstrcpy(devname
, sizeof(devname
), "ide");
1920 /* extract parameters */
1921 bus_id
= qemu_opt_get_number(opts
, "bus", 0);
1922 unit_id
= qemu_opt_get_number(opts
, "unit", -1);
1923 index
= qemu_opt_get_number(opts
, "index", -1);
1925 cyls
= qemu_opt_get_number(opts
, "cyls", 0);
1926 heads
= qemu_opt_get_number(opts
, "heads", 0);
1927 secs
= qemu_opt_get_number(opts
, "secs", 0);
1929 snapshot
= qemu_opt_get_bool(opts
, "snapshot", 0);
1930 ro
= qemu_opt_get_bool(opts
, "readonly", 0);
1932 file
= qemu_opt_get(opts
, "file");
1933 serial
= qemu_opt_get(opts
, "serial");
1935 if ((buf
= qemu_opt_get(opts
, "if")) != NULL
) {
1936 pstrcpy(devname
, sizeof(devname
), buf
);
1937 if (!strcmp(buf
, "ide")) {
1939 max_devs
= MAX_IDE_DEVS
;
1940 } else if (!strcmp(buf
, "scsi")) {
1942 max_devs
= MAX_SCSI_DEVS
;
1943 } else if (!strcmp(buf
, "floppy")) {
1946 } else if (!strcmp(buf
, "pflash")) {
1949 } else if (!strcmp(buf
, "mtd")) {
1952 } else if (!strcmp(buf
, "sd")) {
1955 } else if (!strcmp(buf
, "virtio")) {
1958 } else if (!strcmp(buf
, "xen")) {
1961 } else if (!strcmp(buf
, "none")) {
1965 fprintf(stderr
, "qemu: unsupported bus type '%s'\n", buf
);
1970 if (cyls
|| heads
|| secs
) {
1971 if (cyls
< 1 || (type
== IF_IDE
&& cyls
> 16383)) {
1972 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", buf
);
1975 if (heads
< 1 || (type
== IF_IDE
&& heads
> 16)) {
1976 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", buf
);
1979 if (secs
< 1 || (type
== IF_IDE
&& secs
> 63)) {
1980 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", buf
);
1985 if ((buf
= qemu_opt_get(opts
, "trans")) != NULL
) {
1988 "qemu: '%s' trans must be used with cyls,heads and secs\n",
1992 if (!strcmp(buf
, "none"))
1993 translation
= BIOS_ATA_TRANSLATION_NONE
;
1994 else if (!strcmp(buf
, "lba"))
1995 translation
= BIOS_ATA_TRANSLATION_LBA
;
1996 else if (!strcmp(buf
, "auto"))
1997 translation
= BIOS_ATA_TRANSLATION_AUTO
;
1999 fprintf(stderr
, "qemu: '%s' invalid translation type\n", buf
);
2004 if ((buf
= qemu_opt_get(opts
, "media")) != NULL
) {
2005 if (!strcmp(buf
, "disk")) {
2007 } else if (!strcmp(buf
, "cdrom")) {
2008 if (cyls
|| secs
|| heads
) {
2010 "qemu: '%s' invalid physical CHS format\n", buf
);
2013 media
= MEDIA_CDROM
;
2015 fprintf(stderr
, "qemu: '%s' invalid media\n", buf
);
2020 if ((buf
= qemu_opt_get(opts
, "cache")) != NULL
) {
2021 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2023 else if (!strcmp(buf
, "writethrough"))
2025 else if (!strcmp(buf
, "writeback"))
2028 fprintf(stderr
, "qemu: invalid cache option\n");
2033 #ifdef CONFIG_LINUX_AIO
2034 if ((buf
= qemu_opt_get(opts
, "aio")) != NULL
) {
2035 if (!strcmp(buf
, "threads"))
2037 else if (!strcmp(buf
, "native"))
2040 fprintf(stderr
, "qemu: invalid aio option\n");
2046 if ((buf
= qemu_opt_get(opts
, "format")) != NULL
) {
2047 if (strcmp(buf
, "?") == 0) {
2048 fprintf(stderr
, "qemu: Supported formats:");
2049 bdrv_iterate_format(bdrv_format_print
, NULL
);
2050 fprintf(stderr
, "\n");
2053 drv
= bdrv_find_whitelisted_format(buf
);
2055 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2060 on_write_error
= BLOCK_ERR_STOP_ENOSPC
;
2061 if ((buf
= qemu_opt_get(opts
, "werror")) != NULL
) {
2062 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2063 fprintf(stderr
, "werror is no supported by this format\n");
2067 on_write_error
= parse_block_error_action(buf
, 0);
2068 if (on_write_error
< 0) {
2073 on_read_error
= BLOCK_ERR_REPORT
;
2074 if ((buf
= qemu_opt_get(opts
, "rerror")) != NULL
) {
2075 if (type
!= IF_IDE
&& type
!= IF_VIRTIO
) {
2076 fprintf(stderr
, "rerror is no supported by this format\n");
2080 on_read_error
= parse_block_error_action(buf
, 1);
2081 if (on_read_error
< 0) {
2086 if ((devaddr
= qemu_opt_get(opts
, "addr")) != NULL
) {
2087 if (type
!= IF_VIRTIO
) {
2088 fprintf(stderr
, "addr is not supported\n");
2093 /* compute bus and unit according index */
2096 if (bus_id
!= 0 || unit_id
!= -1) {
2098 "qemu: index cannot be used with bus and unit\n");
2106 unit_id
= index
% max_devs
;
2107 bus_id
= index
/ max_devs
;
2111 /* if user doesn't specify a unit_id,
2112 * try to find the first free
2115 if (unit_id
== -1) {
2117 while (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2119 if (max_devs
&& unit_id
>= max_devs
) {
2120 unit_id
-= max_devs
;
2128 if (max_devs
&& unit_id
>= max_devs
) {
2129 fprintf(stderr
, "qemu: unit %d too big (max is %d)\n",
2130 unit_id
, max_devs
- 1);
2135 * ignore multiple definitions
2138 if (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2145 dinfo
= qemu_mallocz(sizeof(*dinfo
));
2146 if ((buf
= qemu_opts_id(opts
)) != NULL
) {
2147 dinfo
->id
= qemu_strdup(buf
);
2149 /* no id supplied -> create one */
2150 dinfo
->id
= qemu_mallocz(32);
2151 if (type
== IF_IDE
|| type
== IF_SCSI
)
2152 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2154 snprintf(dinfo
->id
, 32, "%s%i%s%i",
2155 devname
, bus_id
, mediastr
, unit_id
);
2157 snprintf(dinfo
->id
, 32, "%s%s%i",
2158 devname
, mediastr
, unit_id
);
2160 dinfo
->bdrv
= bdrv_new(dinfo
->id
);
2161 dinfo
->devaddr
= devaddr
;
2163 dinfo
->bus
= bus_id
;
2164 dinfo
->unit
= unit_id
;
2165 dinfo
->on_read_error
= on_read_error
;
2166 dinfo
->on_write_error
= on_write_error
;
2169 strncpy(dinfo
->serial
, serial
, sizeof(serial
));
2170 QTAILQ_INSERT_TAIL(&drives
, dinfo
, next
);
2180 bdrv_set_geometry_hint(dinfo
->bdrv
, cyls
, heads
, secs
);
2181 bdrv_set_translation_hint(dinfo
->bdrv
, translation
);
2185 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_CDROM
);
2190 /* FIXME: This isn't really a floppy, but it's a reasonable
2193 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_FLOPPY
);
2199 /* add virtio block device */
2200 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
2201 qemu_opt_set(opts
, "driver", "virtio-blk-pci");
2202 qemu_opt_set(opts
, "drive", dinfo
->id
);
2204 qemu_opt_set(opts
, "addr", devaddr
);
2215 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2216 cache
= 2; /* always use write-back with snapshot */
2218 if (cache
== 0) /* no caching */
2219 bdrv_flags
|= BDRV_O_NOCACHE
;
2220 else if (cache
== 2) /* write-back */
2221 bdrv_flags
|= BDRV_O_CACHE_WB
;
2224 bdrv_flags
|= BDRV_O_NATIVE_AIO
;
2226 bdrv_flags
&= ~BDRV_O_NATIVE_AIO
;
2230 if (type
!= IF_SCSI
&& type
!= IF_VIRTIO
&& type
!= IF_FLOPPY
) {
2231 fprintf(stderr
, "qemu: readonly flag not supported for drive with this interface\n");
2236 * cdrom is read-only. Set it now, after above interface checking
2237 * since readonly attribute not explicitly required, so no error.
2239 if (media
== MEDIA_CDROM
) {
2242 bdrv_flags
|= ro
? 0 : BDRV_O_RDWR
;
2244 if (bdrv_open2(dinfo
->bdrv
, file
, bdrv_flags
, drv
) < 0) {
2245 fprintf(stderr
, "qemu: could not open disk image %s: %s\n",
2246 file
, strerror(errno
));
2250 if (bdrv_key_required(dinfo
->bdrv
))
2256 static int drive_init_func(QemuOpts
*opts
, void *opaque
)
2258 QEMUMachine
*machine
= opaque
;
2259 int fatal_error
= 0;
2261 if (drive_init(opts
, machine
, &fatal_error
) == NULL
) {
2268 static int drive_enable_snapshot(QemuOpts
*opts
, void *opaque
)
2270 if (NULL
== qemu_opt_get(opts
, "snapshot")) {
2271 qemu_opt_set(opts
, "snapshot", "on");
2276 void qemu_register_boot_set(QEMUBootSetHandler
*func
, void *opaque
)
2278 boot_set_handler
= func
;
2279 boot_set_opaque
= opaque
;
2282 int qemu_boot_set(const char *boot_devices
)
2284 if (!boot_set_handler
) {
2287 return boot_set_handler(boot_set_opaque
, boot_devices
);
2290 static int parse_bootdevices(char *devices
)
2292 /* We just do some generic consistency checks */
2296 for (p
= devices
; *p
!= '\0'; p
++) {
2297 /* Allowed boot devices are:
2298 * a-b: floppy disk drives
2299 * c-f: IDE disk drives
2300 * g-m: machine implementation dependant drives
2301 * n-p: network devices
2302 * It's up to each machine implementation to check if the given boot
2303 * devices match the actual hardware implementation and firmware
2306 if (*p
< 'a' || *p
> 'p') {
2307 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
2310 if (bitmap
& (1 << (*p
- 'a'))) {
2311 fprintf(stderr
, "Boot device '%c' was given twice\n", *p
);
2314 bitmap
|= 1 << (*p
- 'a');
2319 static void restore_boot_devices(void *opaque
)
2321 char *standard_boot_devices
= opaque
;
2323 qemu_boot_set(standard_boot_devices
);
2325 qemu_unregister_reset(restore_boot_devices
, standard_boot_devices
);
2326 qemu_free(standard_boot_devices
);
2329 static void numa_add(const char *optarg
)
2333 unsigned long long value
, endvalue
;
2336 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2337 if (!strcmp(option
, "node")) {
2338 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2339 nodenr
= nb_numa_nodes
;
2341 nodenr
= strtoull(option
, NULL
, 10);
2344 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2345 node_mem
[nodenr
] = 0;
2347 value
= strtoull(option
, &endptr
, 0);
2349 case 0: case 'M': case 'm':
2356 node_mem
[nodenr
] = value
;
2358 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2359 node_cpumask
[nodenr
] = 0;
2361 value
= strtoull(option
, &endptr
, 10);
2364 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2366 if (*endptr
== '-') {
2367 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2368 if (endvalue
>= 63) {
2371 "only 63 CPUs in NUMA mode supported.\n");
2373 value
= (1 << (endvalue
+ 1)) - (1 << value
);
2378 node_cpumask
[nodenr
] = value
;
2385 static void smp_parse(const char *optarg
)
2387 int smp
, sockets
= 0, threads
= 0, cores
= 0;
2391 smp
= strtoul(optarg
, &endptr
, 10);
2392 if (endptr
!= optarg
) {
2393 if (*endptr
== ',') {
2397 if (get_param_value(option
, 128, "sockets", endptr
) != 0)
2398 sockets
= strtoull(option
, NULL
, 10);
2399 if (get_param_value(option
, 128, "cores", endptr
) != 0)
2400 cores
= strtoull(option
, NULL
, 10);
2401 if (get_param_value(option
, 128, "threads", endptr
) != 0)
2402 threads
= strtoull(option
, NULL
, 10);
2403 if (get_param_value(option
, 128, "maxcpus", endptr
) != 0)
2404 max_cpus
= strtoull(option
, NULL
, 10);
2406 /* compute missing values, prefer sockets over cores over threads */
2407 if (smp
== 0 || sockets
== 0) {
2408 sockets
= sockets
> 0 ? sockets
: 1;
2409 cores
= cores
> 0 ? cores
: 1;
2410 threads
= threads
> 0 ? threads
: 1;
2412 smp
= cores
* threads
* sockets
;
2416 threads
= threads
> 0 ? threads
: 1;
2417 cores
= smp
/ (sockets
* threads
);
2420 threads
= smp
/ (cores
* sockets
);
2425 smp_cores
= cores
> 0 ? cores
: 1;
2426 smp_threads
= threads
> 0 ? threads
: 1;
2428 max_cpus
= smp_cpus
;
2431 /***********************************************************/
2434 static int usb_device_add(const char *devname
, int is_hotplug
)
2437 USBDevice
*dev
= NULL
;
2442 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2443 dev
= usbdevice_create(devname
);
2447 /* the other ones */
2448 if (strstart(devname
, "host:", &p
)) {
2449 dev
= usb_host_device_open(p
);
2450 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2451 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2452 bt_new_hci(qemu_find_bt_vlan(0)));
2463 static int usb_device_del(const char *devname
)
2468 if (strstart(devname
, "host:", &p
))
2469 return usb_host_device_close(p
);
2474 p
= strchr(devname
, '.');
2477 bus_num
= strtoul(devname
, NULL
, 0);
2478 addr
= strtoul(p
+ 1, NULL
, 0);
2480 return usb_device_delete_addr(bus_num
, addr
);
2483 static int usb_parse(const char *cmdline
)
2486 r
= usb_device_add(cmdline
, 0);
2488 fprintf(stderr
, "qemu: could not add USB device '%s'\n", cmdline
);
2493 void do_usb_add(Monitor
*mon
, const QDict
*qdict
)
2495 const char *devname
= qdict_get_str(qdict
, "devname");
2496 if (usb_device_add(devname
, 1) < 0) {
2497 qemu_error("could not add USB device '%s'\n", devname
);
2501 void do_usb_del(Monitor
*mon
, const QDict
*qdict
)
2503 const char *devname
= qdict_get_str(qdict
, "devname");
2504 if (usb_device_del(devname
) < 0) {
2505 qemu_error("could not delete USB device '%s'\n", devname
);
2509 /***********************************************************/
2510 /* PCMCIA/Cardbus */
2512 static struct pcmcia_socket_entry_s
{
2513 PCMCIASocket
*socket
;
2514 struct pcmcia_socket_entry_s
*next
;
2515 } *pcmcia_sockets
= 0;
2517 void pcmcia_socket_register(PCMCIASocket
*socket
)
2519 struct pcmcia_socket_entry_s
*entry
;
2521 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2522 entry
->socket
= socket
;
2523 entry
->next
= pcmcia_sockets
;
2524 pcmcia_sockets
= entry
;
2527 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2529 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2531 ptr
= &pcmcia_sockets
;
2532 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2533 if (entry
->socket
== socket
) {
2539 void pcmcia_info(Monitor
*mon
)
2541 struct pcmcia_socket_entry_s
*iter
;
2543 if (!pcmcia_sockets
)
2544 monitor_printf(mon
, "No PCMCIA sockets\n");
2546 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2547 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2548 iter
->socket
->attached
? iter
->socket
->card_string
:
2552 /***********************************************************/
2553 /* register display */
2555 struct DisplayAllocator default_allocator
= {
2556 defaultallocator_create_displaysurface
,
2557 defaultallocator_resize_displaysurface
,
2558 defaultallocator_free_displaysurface
2561 void register_displaystate(DisplayState
*ds
)
2571 DisplayState
*get_displaystate(void)
2573 return display_state
;
2576 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
2578 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
2579 return ds
->allocator
;
2584 static void dumb_display_init(void)
2586 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
2587 ds
->allocator
= &default_allocator
;
2588 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
2589 register_displaystate(ds
);
2592 /***********************************************************/
2595 typedef struct IOHandlerRecord
{
2597 IOCanRWHandler
*fd_read_poll
;
2599 IOHandler
*fd_write
;
2602 /* temporary data */
2604 struct IOHandlerRecord
*next
;
2607 static IOHandlerRecord
*first_io_handler
;
2609 /* XXX: fd_read_poll should be suppressed, but an API change is
2610 necessary in the character devices to suppress fd_can_read(). */
2611 int qemu_set_fd_handler2(int fd
,
2612 IOCanRWHandler
*fd_read_poll
,
2614 IOHandler
*fd_write
,
2617 IOHandlerRecord
**pioh
, *ioh
;
2619 if (!fd_read
&& !fd_write
) {
2620 pioh
= &first_io_handler
;
2625 if (ioh
->fd
== fd
) {
2632 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
2636 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
2637 ioh
->next
= first_io_handler
;
2638 first_io_handler
= ioh
;
2641 ioh
->fd_read_poll
= fd_read_poll
;
2642 ioh
->fd_read
= fd_read
;
2643 ioh
->fd_write
= fd_write
;
2644 ioh
->opaque
= opaque
;
2650 int qemu_set_fd_handler(int fd
,
2652 IOHandler
*fd_write
,
2655 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
2659 /***********************************************************/
2660 /* Polling handling */
2662 typedef struct PollingEntry
{
2665 struct PollingEntry
*next
;
2668 static PollingEntry
*first_polling_entry
;
2670 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
2672 PollingEntry
**ppe
, *pe
;
2673 pe
= qemu_mallocz(sizeof(PollingEntry
));
2675 pe
->opaque
= opaque
;
2676 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
2681 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
2683 PollingEntry
**ppe
, *pe
;
2684 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
2686 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
2694 /***********************************************************/
2695 /* Wait objects support */
2696 typedef struct WaitObjects
{
2698 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
2699 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
2700 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
2703 static WaitObjects wait_objects
= {0};
2705 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2707 WaitObjects
*w
= &wait_objects
;
2709 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
2711 w
->events
[w
->num
] = handle
;
2712 w
->func
[w
->num
] = func
;
2713 w
->opaque
[w
->num
] = opaque
;
2718 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2721 WaitObjects
*w
= &wait_objects
;
2724 for (i
= 0; i
< w
->num
; i
++) {
2725 if (w
->events
[i
] == handle
)
2728 w
->events
[i
] = w
->events
[i
+ 1];
2729 w
->func
[i
] = w
->func
[i
+ 1];
2730 w
->opaque
[i
] = w
->opaque
[i
+ 1];
2738 /***********************************************************/
2739 /* ram save/restore */
2741 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2742 #define RAM_SAVE_FLAG_COMPRESS 0x02
2743 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2744 #define RAM_SAVE_FLAG_PAGE 0x08
2745 #define RAM_SAVE_FLAG_EOS 0x10
2747 static int is_dup_page(uint8_t *page
, uint8_t ch
)
2749 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
2750 uint32_t *array
= (uint32_t *)page
;
2753 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
2754 if (array
[i
] != val
)
2761 static int ram_save_block(QEMUFile
*f
)
2763 static ram_addr_t current_addr
= 0;
2764 ram_addr_t saved_addr
= current_addr
;
2765 ram_addr_t addr
= 0;
2768 while (addr
< last_ram_offset
) {
2769 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
2772 cpu_physical_memory_reset_dirty(current_addr
,
2773 current_addr
+ TARGET_PAGE_SIZE
,
2774 MIGRATION_DIRTY_FLAG
);
2776 p
= qemu_get_ram_ptr(current_addr
);
2778 if (is_dup_page(p
, *p
)) {
2779 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
2780 qemu_put_byte(f
, *p
);
2782 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
2783 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
2789 addr
+= TARGET_PAGE_SIZE
;
2790 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
2796 static uint64_t bytes_transferred
;
2798 static ram_addr_t
ram_save_remaining(void)
2801 ram_addr_t count
= 0;
2803 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2804 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2811 uint64_t ram_bytes_remaining(void)
2813 return ram_save_remaining() * TARGET_PAGE_SIZE
;
2816 uint64_t ram_bytes_transferred(void)
2818 return bytes_transferred
;
2821 uint64_t ram_bytes_total(void)
2823 return last_ram_offset
;
2826 static int ram_save_live(Monitor
*mon
, QEMUFile
*f
, int stage
, void *opaque
)
2829 uint64_t bytes_transferred_last
;
2831 uint64_t expected_time
= 0;
2834 cpu_physical_memory_set_dirty_tracking(0);
2838 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX
) != 0) {
2839 qemu_file_set_error(f
);
2844 bytes_transferred
= 0;
2846 /* Make sure all dirty bits are set */
2847 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2848 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2849 cpu_physical_memory_set_dirty(addr
);
2852 /* Enable dirty memory tracking */
2853 cpu_physical_memory_set_dirty_tracking(1);
2855 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
2858 bytes_transferred_last
= bytes_transferred
;
2859 bwidth
= get_clock();
2861 while (!qemu_file_rate_limit(f
)) {
2864 ret
= ram_save_block(f
);
2865 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
2866 if (ret
== 0) /* no more blocks */
2870 bwidth
= get_clock() - bwidth
;
2871 bwidth
= (bytes_transferred
- bytes_transferred_last
) / bwidth
;
2873 /* if we haven't transferred anything this round, force expected_time to a
2874 * a very high value, but without crashing */
2878 /* try transferring iterative blocks of memory */
2880 /* flush all remaining blocks regardless of rate limiting */
2881 while (ram_save_block(f
) != 0) {
2882 bytes_transferred
+= TARGET_PAGE_SIZE
;
2884 cpu_physical_memory_set_dirty_tracking(0);
2887 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
2889 expected_time
= ram_save_remaining() * TARGET_PAGE_SIZE
/ bwidth
;
2891 return (stage
== 2) && (expected_time
<= migrate_max_downtime());
2894 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
2899 if (version_id
!= 3)
2903 addr
= qemu_get_be64(f
);
2905 flags
= addr
& ~TARGET_PAGE_MASK
;
2906 addr
&= TARGET_PAGE_MASK
;
2908 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
2909 if (addr
!= last_ram_offset
)
2913 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
2914 uint8_t ch
= qemu_get_byte(f
);
2915 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
2918 (!kvm_enabled() || kvm_has_sync_mmu())) {
2919 madvise(qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
, MADV_DONTNEED
);
2922 } else if (flags
& RAM_SAVE_FLAG_PAGE
) {
2923 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
2925 if (qemu_file_has_error(f
)) {
2928 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
2933 void qemu_service_io(void)
2935 qemu_notify_event();
2938 /***********************************************************/
2939 /* machine registration */
2941 static QEMUMachine
*first_machine
= NULL
;
2942 QEMUMachine
*current_machine
= NULL
;
2944 int qemu_register_machine(QEMUMachine
*m
)
2947 pm
= &first_machine
;
2955 static QEMUMachine
*find_machine(const char *name
)
2959 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
2960 if (!strcmp(m
->name
, name
))
2962 if (m
->alias
&& !strcmp(m
->alias
, name
))
2968 static QEMUMachine
*find_default_machine(void)
2972 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
2973 if (m
->is_default
) {
2980 /***********************************************************/
2981 /* main execution loop */
2983 static void gui_update(void *opaque
)
2985 uint64_t interval
= GUI_REFRESH_INTERVAL
;
2986 DisplayState
*ds
= opaque
;
2987 DisplayChangeListener
*dcl
= ds
->listeners
;
2991 while (dcl
!= NULL
) {
2992 if (dcl
->gui_timer_interval
&&
2993 dcl
->gui_timer_interval
< interval
)
2994 interval
= dcl
->gui_timer_interval
;
2997 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3000 static void nographic_update(void *opaque
)
3002 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3004 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3007 struct vm_change_state_entry
{
3008 VMChangeStateHandler
*cb
;
3010 QLIST_ENTRY (vm_change_state_entry
) entries
;
3013 static QLIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3015 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3018 VMChangeStateEntry
*e
;
3020 e
= qemu_mallocz(sizeof (*e
));
3024 QLIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3028 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3030 QLIST_REMOVE (e
, entries
);
3034 static void vm_state_notify(int running
, int reason
)
3036 VMChangeStateEntry
*e
;
3038 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3039 e
->cb(e
->opaque
, running
, reason
);
3043 static void resume_all_vcpus(void);
3044 static void pause_all_vcpus(void);
3051 vm_state_notify(1, 0);
3052 qemu_rearm_alarm_timer(alarm_timer
);
3057 /* reset/shutdown handler */
3059 typedef struct QEMUResetEntry
{
3060 QTAILQ_ENTRY(QEMUResetEntry
) entry
;
3061 QEMUResetHandler
*func
;
3065 static QTAILQ_HEAD(reset_handlers
, QEMUResetEntry
) reset_handlers
=
3066 QTAILQ_HEAD_INITIALIZER(reset_handlers
);
3067 static int reset_requested
;
3068 static int shutdown_requested
;
3069 static int powerdown_requested
;
3070 static int debug_requested
;
3071 static int vmstop_requested
;
3073 int qemu_shutdown_requested(void)
3075 int r
= shutdown_requested
;
3076 shutdown_requested
= 0;
3080 int qemu_reset_requested(void)
3082 int r
= reset_requested
;
3083 reset_requested
= 0;
3087 int qemu_powerdown_requested(void)
3089 int r
= powerdown_requested
;
3090 powerdown_requested
= 0;
3094 static int qemu_debug_requested(void)
3096 int r
= debug_requested
;
3097 debug_requested
= 0;
3101 static int qemu_vmstop_requested(void)
3103 int r
= vmstop_requested
;
3104 vmstop_requested
= 0;
3108 static void do_vm_stop(int reason
)
3111 cpu_disable_ticks();
3114 vm_state_notify(0, reason
);
3118 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3120 QEMUResetEntry
*re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3123 re
->opaque
= opaque
;
3124 QTAILQ_INSERT_TAIL(&reset_handlers
, re
, entry
);
3127 void qemu_unregister_reset(QEMUResetHandler
*func
, void *opaque
)
3131 QTAILQ_FOREACH(re
, &reset_handlers
, entry
) {
3132 if (re
->func
== func
&& re
->opaque
== opaque
) {
3133 QTAILQ_REMOVE(&reset_handlers
, re
, entry
);
3140 void qemu_system_reset(void)
3142 QEMUResetEntry
*re
, *nre
;
3144 /* reset all devices */
3145 QTAILQ_FOREACH_SAFE(re
, &reset_handlers
, entry
, nre
) {
3146 re
->func(re
->opaque
);
3150 void qemu_system_reset_request(void)
3153 shutdown_requested
= 1;
3155 reset_requested
= 1;
3157 qemu_notify_event();
3160 void qemu_system_shutdown_request(void)
3162 shutdown_requested
= 1;
3163 qemu_notify_event();
3166 void qemu_system_powerdown_request(void)
3168 powerdown_requested
= 1;
3169 qemu_notify_event();
3172 #ifdef CONFIG_IOTHREAD
3173 static void qemu_system_vmstop_request(int reason
)
3175 vmstop_requested
= reason
;
3176 qemu_notify_event();
3181 static int io_thread_fd
= -1;
3183 static void qemu_event_increment(void)
3185 static const char byte
= 0;
3187 if (io_thread_fd
== -1)
3190 write(io_thread_fd
, &byte
, sizeof(byte
));
3193 static void qemu_event_read(void *opaque
)
3195 int fd
= (unsigned long)opaque
;
3198 /* Drain the notify pipe */
3201 len
= read(fd
, buffer
, sizeof(buffer
));
3202 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
3205 static int qemu_event_init(void)
3210 err
= qemu_pipe(fds
);
3214 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3218 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3222 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3223 (void *)(unsigned long)fds
[0]);
3225 io_thread_fd
= fds
[1];
3234 HANDLE qemu_event_handle
;
3236 static void dummy_event_handler(void *opaque
)
3240 static int qemu_event_init(void)
3242 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3243 if (!qemu_event_handle
) {
3244 fprintf(stderr
, "Failed CreateEvent: %ld\n", GetLastError());
3247 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3251 static void qemu_event_increment(void)
3253 if (!SetEvent(qemu_event_handle
)) {
3254 fprintf(stderr
, "qemu_event_increment: SetEvent failed: %ld\n",
3261 static int cpu_can_run(CPUState
*env
)
3270 #ifndef CONFIG_IOTHREAD
3271 static int qemu_init_main_loop(void)
3273 return qemu_event_init();
3276 void qemu_init_vcpu(void *_env
)
3278 CPUState
*env
= _env
;
3280 env
->nr_cores
= smp_cores
;
3281 env
->nr_threads
= smp_threads
;
3287 int qemu_cpu_self(void *env
)
3292 static void resume_all_vcpus(void)
3296 static void pause_all_vcpus(void)
3300 void qemu_cpu_kick(void *env
)
3305 void qemu_notify_event(void)
3307 CPUState
*env
= cpu_single_env
;
3314 void qemu_mutex_lock_iothread(void) {}
3315 void qemu_mutex_unlock_iothread(void) {}
3317 void vm_stop(int reason
)
3322 #else /* CONFIG_IOTHREAD */
3324 #include "qemu-thread.h"
3326 QemuMutex qemu_global_mutex
;
3327 static QemuMutex qemu_fair_mutex
;
3329 static QemuThread io_thread
;
3331 static QemuThread
*tcg_cpu_thread
;
3332 static QemuCond
*tcg_halt_cond
;
3334 static int qemu_system_ready
;
3336 static QemuCond qemu_cpu_cond
;
3338 static QemuCond qemu_system_cond
;
3339 static QemuCond qemu_pause_cond
;
3341 static void block_io_signals(void);
3342 static void unblock_io_signals(void);
3343 static int tcg_has_work(void);
3345 static int qemu_init_main_loop(void)
3349 ret
= qemu_event_init();
3353 qemu_cond_init(&qemu_pause_cond
);
3354 qemu_mutex_init(&qemu_fair_mutex
);
3355 qemu_mutex_init(&qemu_global_mutex
);
3356 qemu_mutex_lock(&qemu_global_mutex
);
3358 unblock_io_signals();
3359 qemu_thread_self(&io_thread
);
3364 static void qemu_wait_io_event(CPUState
*env
)
3366 while (!tcg_has_work())
3367 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3369 qemu_mutex_unlock(&qemu_global_mutex
);
3372 * Users of qemu_global_mutex can be starved, having no chance
3373 * to acquire it since this path will get to it first.
3374 * So use another lock to provide fairness.
3376 qemu_mutex_lock(&qemu_fair_mutex
);
3377 qemu_mutex_unlock(&qemu_fair_mutex
);
3379 qemu_mutex_lock(&qemu_global_mutex
);
3383 qemu_cond_signal(&qemu_pause_cond
);
3387 static int qemu_cpu_exec(CPUState
*env
);
3389 static void *kvm_cpu_thread_fn(void *arg
)
3391 CPUState
*env
= arg
;
3394 qemu_thread_self(env
->thread
);
3398 /* signal CPU creation */
3399 qemu_mutex_lock(&qemu_global_mutex
);
3401 qemu_cond_signal(&qemu_cpu_cond
);
3403 /* and wait for machine initialization */
3404 while (!qemu_system_ready
)
3405 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3408 if (cpu_can_run(env
))
3410 qemu_wait_io_event(env
);
3416 static void tcg_cpu_exec(void);
3418 static void *tcg_cpu_thread_fn(void *arg
)
3420 CPUState
*env
= arg
;
3423 qemu_thread_self(env
->thread
);
3425 /* signal CPU creation */
3426 qemu_mutex_lock(&qemu_global_mutex
);
3427 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
3429 qemu_cond_signal(&qemu_cpu_cond
);
3431 /* and wait for machine initialization */
3432 while (!qemu_system_ready
)
3433 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3437 qemu_wait_io_event(cur_cpu
);
3443 void qemu_cpu_kick(void *_env
)
3445 CPUState
*env
= _env
;
3446 qemu_cond_broadcast(env
->halt_cond
);
3448 qemu_thread_signal(env
->thread
, SIGUSR1
);
3451 int qemu_cpu_self(void *_env
)
3453 CPUState
*env
= _env
;
3456 qemu_thread_self(&this);
3458 return qemu_thread_equal(&this, env
->thread
);
3461 static void cpu_signal(int sig
)
3464 cpu_exit(cpu_single_env
);
3467 static void block_io_signals(void)
3470 struct sigaction sigact
;
3473 sigaddset(&set
, SIGUSR2
);
3474 sigaddset(&set
, SIGIO
);
3475 sigaddset(&set
, SIGALRM
);
3476 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3479 sigaddset(&set
, SIGUSR1
);
3480 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3482 memset(&sigact
, 0, sizeof(sigact
));
3483 sigact
.sa_handler
= cpu_signal
;
3484 sigaction(SIGUSR1
, &sigact
, NULL
);
3487 static void unblock_io_signals(void)
3492 sigaddset(&set
, SIGUSR2
);
3493 sigaddset(&set
, SIGIO
);
3494 sigaddset(&set
, SIGALRM
);
3495 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3498 sigaddset(&set
, SIGUSR1
);
3499 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3502 static void qemu_signal_lock(unsigned int msecs
)
3504 qemu_mutex_lock(&qemu_fair_mutex
);
3506 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
3507 qemu_thread_signal(tcg_cpu_thread
, SIGUSR1
);
3508 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
3511 qemu_mutex_unlock(&qemu_fair_mutex
);
3514 void qemu_mutex_lock_iothread(void)
3516 if (kvm_enabled()) {
3517 qemu_mutex_lock(&qemu_fair_mutex
);
3518 qemu_mutex_lock(&qemu_global_mutex
);
3519 qemu_mutex_unlock(&qemu_fair_mutex
);
3521 qemu_signal_lock(100);
3524 void qemu_mutex_unlock_iothread(void)
3526 qemu_mutex_unlock(&qemu_global_mutex
);
3529 static int all_vcpus_paused(void)
3531 CPUState
*penv
= first_cpu
;
3536 penv
= (CPUState
*)penv
->next_cpu
;
3542 static void pause_all_vcpus(void)
3544 CPUState
*penv
= first_cpu
;
3548 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3549 qemu_cpu_kick(penv
);
3550 penv
= (CPUState
*)penv
->next_cpu
;
3553 while (!all_vcpus_paused()) {
3554 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
3557 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3558 penv
= (CPUState
*)penv
->next_cpu
;
3563 static void resume_all_vcpus(void)
3565 CPUState
*penv
= first_cpu
;
3570 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3571 qemu_cpu_kick(penv
);
3572 penv
= (CPUState
*)penv
->next_cpu
;
3576 static void tcg_init_vcpu(void *_env
)
3578 CPUState
*env
= _env
;
3579 /* share a single thread for all cpus with TCG */
3580 if (!tcg_cpu_thread
) {
3581 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3582 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3583 qemu_cond_init(env
->halt_cond
);
3584 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
3585 while (env
->created
== 0)
3586 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3587 tcg_cpu_thread
= env
->thread
;
3588 tcg_halt_cond
= env
->halt_cond
;
3590 env
->thread
= tcg_cpu_thread
;
3591 env
->halt_cond
= tcg_halt_cond
;
3595 static void kvm_start_vcpu(CPUState
*env
)
3597 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3598 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3599 qemu_cond_init(env
->halt_cond
);
3600 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
3601 while (env
->created
== 0)
3602 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3605 void qemu_init_vcpu(void *_env
)
3607 CPUState
*env
= _env
;
3609 env
->nr_cores
= smp_cores
;
3610 env
->nr_threads
= smp_threads
;
3612 kvm_start_vcpu(env
);
3617 void qemu_notify_event(void)
3619 qemu_event_increment();
3622 void vm_stop(int reason
)
3625 qemu_thread_self(&me
);
3627 if (!qemu_thread_equal(&me
, &io_thread
)) {
3628 qemu_system_vmstop_request(reason
);
3630 * FIXME: should not return to device code in case
3631 * vm_stop() has been requested.
3633 if (cpu_single_env
) {
3634 cpu_exit(cpu_single_env
);
3635 cpu_single_env
->stop
= 1;
3646 static void host_main_loop_wait(int *timeout
)
3652 /* XXX: need to suppress polling by better using win32 events */
3654 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
3655 ret
|= pe
->func(pe
->opaque
);
3659 WaitObjects
*w
= &wait_objects
;
3661 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
3662 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
3663 if (w
->func
[ret
- WAIT_OBJECT_0
])
3664 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
3666 /* Check for additional signaled events */
3667 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
3669 /* Check if event is signaled */
3670 ret2
= WaitForSingleObject(w
->events
[i
], 0);
3671 if(ret2
== WAIT_OBJECT_0
) {
3673 w
->func
[i
](w
->opaque
[i
]);
3674 } else if (ret2
== WAIT_TIMEOUT
) {
3676 err
= GetLastError();
3677 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
3680 } else if (ret
== WAIT_TIMEOUT
) {
3682 err
= GetLastError();
3683 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
3690 static void host_main_loop_wait(int *timeout
)
3695 void main_loop_wait(int timeout
)
3697 IOHandlerRecord
*ioh
;
3698 fd_set rfds
, wfds
, xfds
;
3702 qemu_bh_update_timeout(&timeout
);
3704 host_main_loop_wait(&timeout
);
3706 /* poll any events */
3707 /* XXX: separate device handlers from system ones */
3712 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3716 (!ioh
->fd_read_poll
||
3717 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
3718 FD_SET(ioh
->fd
, &rfds
);
3722 if (ioh
->fd_write
) {
3723 FD_SET(ioh
->fd
, &wfds
);
3729 tv
.tv_sec
= timeout
/ 1000;
3730 tv
.tv_usec
= (timeout
% 1000) * 1000;
3732 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
3734 qemu_mutex_unlock_iothread();
3735 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
3736 qemu_mutex_lock_iothread();
3738 IOHandlerRecord
**pioh
;
3740 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3741 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
3742 ioh
->fd_read(ioh
->opaque
);
3744 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
3745 ioh
->fd_write(ioh
->opaque
);
3749 /* remove deleted IO handlers */
3750 pioh
= &first_io_handler
;
3761 slirp_select_poll(&rfds
, &wfds
, &xfds
, (ret
< 0));
3763 /* rearm timer, if not periodic */
3764 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
3765 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
3766 qemu_rearm_alarm_timer(alarm_timer
);
3769 /* vm time timers */
3771 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
3772 qemu_run_timers(&active_timers
[QEMU_CLOCK_VIRTUAL
],
3773 qemu_get_clock(vm_clock
));
3776 /* real time timers */
3777 qemu_run_timers(&active_timers
[QEMU_CLOCK_REALTIME
],
3778 qemu_get_clock(rt_clock
));
3780 qemu_run_timers(&active_timers
[QEMU_CLOCK_HOST
],
3781 qemu_get_clock(host_clock
));
3783 /* Check bottom-halves last in case any of the earlier events triggered
3789 static int qemu_cpu_exec(CPUState
*env
)
3792 #ifdef CONFIG_PROFILER
3796 #ifdef CONFIG_PROFILER
3797 ti
= profile_getclock();
3802 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
3803 env
->icount_decr
.u16
.low
= 0;
3804 env
->icount_extra
= 0;
3805 count
= qemu_next_deadline();
3806 count
= (count
+ (1 << icount_time_shift
) - 1)
3807 >> icount_time_shift
;
3808 qemu_icount
+= count
;
3809 decr
= (count
> 0xffff) ? 0xffff : count
;
3811 env
->icount_decr
.u16
.low
= decr
;
3812 env
->icount_extra
= count
;
3814 ret
= cpu_exec(env
);
3815 #ifdef CONFIG_PROFILER
3816 qemu_time
+= profile_getclock() - ti
;
3819 /* Fold pending instructions back into the
3820 instruction counter, and clear the interrupt flag. */
3821 qemu_icount
-= (env
->icount_decr
.u16
.low
3822 + env
->icount_extra
);
3823 env
->icount_decr
.u32
= 0;
3824 env
->icount_extra
= 0;
3829 static void tcg_cpu_exec(void)
3833 if (next_cpu
== NULL
)
3834 next_cpu
= first_cpu
;
3835 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
3836 CPUState
*env
= cur_cpu
= next_cpu
;
3840 if (timer_alarm_pending
) {
3841 timer_alarm_pending
= 0;
3844 if (cpu_can_run(env
))
3845 ret
= qemu_cpu_exec(env
);
3846 if (ret
== EXCP_DEBUG
) {
3847 gdb_set_stop_cpu(env
);
3848 debug_requested
= 1;
3854 static int cpu_has_work(CPUState
*env
)
3862 if (qemu_cpu_has_work(env
))
3867 static int tcg_has_work(void)
3871 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
3872 if (cpu_has_work(env
))
3877 static int qemu_calculate_timeout(void)
3879 #ifndef CONFIG_IOTHREAD
3884 else if (tcg_has_work())
3886 else if (!use_icount
)
3889 /* XXX: use timeout computed from timers */
3892 /* Advance virtual time to the next event. */
3893 if (use_icount
== 1) {
3894 /* When not using an adaptive execution frequency
3895 we tend to get badly out of sync with real time,
3896 so just delay for a reasonable amount of time. */
3899 delta
= cpu_get_icount() - cpu_get_clock();
3902 /* If virtual time is ahead of real time then just
3904 timeout
= (delta
/ 1000000) + 1;
3906 /* Wait for either IO to occur or the next
3908 add
= qemu_next_deadline();
3909 /* We advance the timer before checking for IO.
3910 Limit the amount we advance so that early IO
3911 activity won't get the guest too far ahead. */
3915 add
= (add
+ (1 << icount_time_shift
) - 1)
3916 >> icount_time_shift
;
3918 timeout
= delta
/ 1000000;
3925 #else /* CONFIG_IOTHREAD */
3930 static int vm_can_run(void)
3932 if (powerdown_requested
)
3934 if (reset_requested
)
3936 if (shutdown_requested
)
3938 if (debug_requested
)
3943 qemu_irq qemu_system_powerdown
;
3945 static void main_loop(void)
3949 #ifdef CONFIG_IOTHREAD
3950 qemu_system_ready
= 1;
3951 qemu_cond_broadcast(&qemu_system_cond
);
3956 #ifdef CONFIG_PROFILER
3959 #ifndef CONFIG_IOTHREAD
3962 #ifdef CONFIG_PROFILER
3963 ti
= profile_getclock();
3965 main_loop_wait(qemu_calculate_timeout());
3966 #ifdef CONFIG_PROFILER
3967 dev_time
+= profile_getclock() - ti
;
3969 } while (vm_can_run());
3971 if (qemu_debug_requested()) {
3972 monitor_protocol_event(QEVENT_DEBUG
, NULL
);
3973 vm_stop(EXCP_DEBUG
);
3975 if (qemu_shutdown_requested()) {
3976 monitor_protocol_event(QEVENT_SHUTDOWN
, NULL
);
3983 if (qemu_reset_requested()) {
3984 monitor_protocol_event(QEVENT_RESET
, NULL
);
3986 qemu_system_reset();
3989 if (qemu_powerdown_requested()) {
3990 monitor_protocol_event(QEVENT_POWERDOWN
, NULL
);
3991 qemu_irq_raise(qemu_system_powerdown
);
3993 if ((r
= qemu_vmstop_requested())) {
3994 monitor_protocol_event(QEVENT_STOP
, NULL
);
4001 static void version(void)
4003 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4006 static void help(int exitcode
)
4009 printf("usage: %s [options] [disk_image]\n"
4011 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4013 #define DEF(option, opt_arg, opt_enum, opt_help) \
4015 #define DEFHEADING(text) stringify(text) "\n"
4016 #include "qemu-options.h"
4021 "During emulation, the following keys are useful:\n"
4022 "ctrl-alt-f toggle full screen\n"
4023 "ctrl-alt-n switch to virtual console 'n'\n"
4024 "ctrl-alt toggle mouse and keyboard grab\n"
4026 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4031 DEFAULT_NETWORK_SCRIPT
,
4032 DEFAULT_NETWORK_DOWN_SCRIPT
,
4034 DEFAULT_GDBSTUB_PORT
,
4039 #define HAS_ARG 0x0001
4042 #define DEF(option, opt_arg, opt_enum, opt_help) \
4044 #define DEFHEADING(text)
4045 #include "qemu-options.h"
4051 typedef struct QEMUOption
{
4057 static const QEMUOption qemu_options
[] = {
4058 { "h", 0, QEMU_OPTION_h
},
4059 #define DEF(option, opt_arg, opt_enum, opt_help) \
4060 { option, opt_arg, opt_enum },
4061 #define DEFHEADING(text)
4062 #include "qemu-options.h"
4070 struct soundhw soundhw
[] = {
4071 #ifdef HAS_AUDIO_CHOICE
4072 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4078 { .init_isa
= pcspk_audio_init
}
4085 "Creative Sound Blaster 16",
4088 { .init_isa
= SB16_init
}
4092 #ifdef CONFIG_CS4231A
4098 { .init_isa
= cs4231a_init
}
4106 "Yamaha YMF262 (OPL3)",
4108 "Yamaha YM3812 (OPL2)",
4112 { .init_isa
= Adlib_init
}
4119 "Gravis Ultrasound GF1",
4122 { .init_isa
= GUS_init
}
4129 "Intel 82801AA AC97 Audio",
4132 { .init_pci
= ac97_init
}
4136 #ifdef CONFIG_ES1370
4139 "ENSONIQ AudioPCI ES1370",
4142 { .init_pci
= es1370_init
}
4146 #endif /* HAS_AUDIO_CHOICE */
4148 { NULL
, NULL
, 0, 0, { NULL
} }
4151 static void select_soundhw (const char *optarg
)
4155 if (*optarg
== '?') {
4158 printf ("Valid sound card names (comma separated):\n");
4159 for (c
= soundhw
; c
->name
; ++c
) {
4160 printf ("%-11s %s\n", c
->name
, c
->descr
);
4162 printf ("\n-soundhw all will enable all of the above\n");
4163 exit (*optarg
!= '?');
4171 if (!strcmp (optarg
, "all")) {
4172 for (c
= soundhw
; c
->name
; ++c
) {
4180 e
= strchr (p
, ',');
4181 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4183 for (c
= soundhw
; c
->name
; ++c
) {
4184 if (!strncmp (c
->name
, p
, l
) && !c
->name
[l
]) {
4193 "Unknown sound card name (too big to show)\n");
4196 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4201 p
+= l
+ (e
!= NULL
);
4205 goto show_valid_cards
;
4210 static void select_vgahw (const char *p
)
4215 vga_interface_type
= VGA_NONE
;
4216 if (strstart(p
, "std", &opts
)) {
4217 vga_interface_type
= VGA_STD
;
4218 } else if (strstart(p
, "cirrus", &opts
)) {
4219 vga_interface_type
= VGA_CIRRUS
;
4220 } else if (strstart(p
, "vmware", &opts
)) {
4221 vga_interface_type
= VGA_VMWARE
;
4222 } else if (strstart(p
, "xenfb", &opts
)) {
4223 vga_interface_type
= VGA_XENFB
;
4224 } else if (!strstart(p
, "none", &opts
)) {
4226 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4230 const char *nextopt
;
4232 if (strstart(opts
, ",retrace=", &nextopt
)) {
4234 if (strstart(opts
, "dumb", &nextopt
))
4235 vga_retrace_method
= VGA_RETRACE_DUMB
;
4236 else if (strstart(opts
, "precise", &nextopt
))
4237 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4238 else goto invalid_vga
;
4239 } else goto invalid_vga
;
4245 static int balloon_parse(const char *arg
)
4249 if (strcmp(arg
, "none") == 0) {
4253 if (!strncmp(arg
, "virtio", 6)) {
4254 if (arg
[6] == ',') {
4255 /* have params -> parse them */
4256 opts
= qemu_opts_parse(&qemu_device_opts
, arg
+7, NULL
);
4260 /* create empty opts */
4261 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4263 qemu_opt_set(opts
, "driver", "virtio-balloon-pci");
4272 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4274 exit(STATUS_CONTROL_C_EXIT
);
4279 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4283 if(strlen(str
) != 36)
4286 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4287 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4288 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4294 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4302 static void termsig_handler(int signal
)
4304 qemu_system_shutdown_request();
4307 static void sigchld_handler(int signal
)
4309 waitpid(-1, NULL
, WNOHANG
);
4312 static void sighandler_setup(void)
4314 struct sigaction act
;
4316 memset(&act
, 0, sizeof(act
));
4317 act
.sa_handler
= termsig_handler
;
4318 sigaction(SIGINT
, &act
, NULL
);
4319 sigaction(SIGHUP
, &act
, NULL
);
4320 sigaction(SIGTERM
, &act
, NULL
);
4322 act
.sa_handler
= sigchld_handler
;
4323 act
.sa_flags
= SA_NOCLDSTOP
;
4324 sigaction(SIGCHLD
, &act
, NULL
);
4330 /* Look for support files in the same directory as the executable. */
4331 static char *find_datadir(const char *argv0
)
4337 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
4344 while (p
!= buf
&& *p
!= '\\')
4347 if (access(buf
, R_OK
) == 0) {
4348 return qemu_strdup(buf
);
4354 /* Find a likely location for support files using the location of the binary.
4355 For installed binaries this will be "$bindir/../share/qemu". When
4356 running from the build tree this will be "$bindir/../pc-bios". */
4357 #define SHARE_SUFFIX "/share/qemu"
4358 #define BUILD_SUFFIX "/pc-bios"
4359 static char *find_datadir(const char *argv0
)
4367 #if defined(__linux__)
4370 len
= readlink("/proc/self/exe", buf
, sizeof(buf
) - 1);
4376 #elif defined(__FreeBSD__)
4379 len
= readlink("/proc/curproc/file", buf
, sizeof(buf
) - 1);
4386 /* If we don't have any way of figuring out the actual executable
4387 location then try argv[0]. */
4389 p
= realpath(argv0
, buf
);
4397 max_len
= strlen(dir
) +
4398 MAX(strlen(SHARE_SUFFIX
), strlen(BUILD_SUFFIX
)) + 1;
4399 res
= qemu_mallocz(max_len
);
4400 snprintf(res
, max_len
, "%s%s", dir
, SHARE_SUFFIX
);
4401 if (access(res
, R_OK
)) {
4402 snprintf(res
, max_len
, "%s%s", dir
, BUILD_SUFFIX
);
4403 if (access(res
, R_OK
)) {
4415 char *qemu_find_file(int type
, const char *name
)
4421 /* If name contains path separators then try it as a straight path. */
4422 if ((strchr(name
, '/') || strchr(name
, '\\'))
4423 && access(name
, R_OK
) == 0) {
4424 return qemu_strdup(name
);
4427 case QEMU_FILE_TYPE_BIOS
:
4430 case QEMU_FILE_TYPE_KEYMAP
:
4431 subdir
= "keymaps/";
4436 len
= strlen(data_dir
) + strlen(name
) + strlen(subdir
) + 2;
4437 buf
= qemu_mallocz(len
);
4438 snprintf(buf
, len
, "%s/%s%s", data_dir
, subdir
, name
);
4439 if (access(buf
, R_OK
)) {
4446 static int device_init_func(QemuOpts
*opts
, void *opaque
)
4450 dev
= qdev_device_add(opts
);
4456 static int chardev_init_func(QemuOpts
*opts
, void *opaque
)
4458 CharDriverState
*chr
;
4460 chr
= qemu_chr_open_opts(opts
, NULL
);
4466 static int mon_init_func(QemuOpts
*opts
, void *opaque
)
4468 CharDriverState
*chr
;
4469 const char *chardev
;
4473 mode
= qemu_opt_get(opts
, "mode");
4477 if (strcmp(mode
, "readline") == 0) {
4478 flags
= MONITOR_USE_READLINE
;
4479 } else if (strcmp(mode
, "control") == 0) {
4480 flags
= MONITOR_USE_CONTROL
;
4482 fprintf(stderr
, "unknown monitor mode \"%s\"\n", mode
);
4486 if (qemu_opt_get_bool(opts
, "default", 0))
4487 flags
|= MONITOR_IS_DEFAULT
;
4489 chardev
= qemu_opt_get(opts
, "chardev");
4490 chr
= qemu_chr_find(chardev
);
4492 fprintf(stderr
, "chardev \"%s\" not found\n", chardev
);
4496 monitor_init(chr
, flags
);
4500 static void monitor_parse(const char *optarg
, const char *mode
)
4502 static int monitor_device_index
= 0;
4508 if (strstart(optarg
, "chardev:", &p
)) {
4509 snprintf(label
, sizeof(label
), "%s", p
);
4511 if (monitor_device_index
) {
4512 snprintf(label
, sizeof(label
), "monitor%d",
4513 monitor_device_index
);
4515 snprintf(label
, sizeof(label
), "monitor");
4518 opts
= qemu_chr_parse_compat(label
, optarg
);
4520 fprintf(stderr
, "parse error: %s\n", optarg
);
4525 opts
= qemu_opts_create(&qemu_mon_opts
, label
, 1);
4527 fprintf(stderr
, "duplicate chardev: %s\n", label
);
4530 qemu_opt_set(opts
, "mode", mode
);
4531 qemu_opt_set(opts
, "chardev", label
);
4533 qemu_opt_set(opts
, "default", "on");
4534 monitor_device_index
++;
4537 struct device_config
{
4539 DEV_USB
, /* -usbdevice */
4541 DEV_SERIAL
, /* -serial */
4542 DEV_PARALLEL
, /* -parallel */
4543 DEV_VIRTCON
, /* -virtioconsole */
4544 DEV_DEBUGCON
, /* -debugcon */
4546 const char *cmdline
;
4547 QTAILQ_ENTRY(device_config
) next
;
4549 QTAILQ_HEAD(, device_config
) device_configs
= QTAILQ_HEAD_INITIALIZER(device_configs
);
4551 static void add_device_config(int type
, const char *cmdline
)
4553 struct device_config
*conf
;
4555 conf
= qemu_mallocz(sizeof(*conf
));
4557 conf
->cmdline
= cmdline
;
4558 QTAILQ_INSERT_TAIL(&device_configs
, conf
, next
);
4561 static int foreach_device_config(int type
, int (*func
)(const char *cmdline
))
4563 struct device_config
*conf
;
4566 QTAILQ_FOREACH(conf
, &device_configs
, next
) {
4567 if (conf
->type
!= type
)
4569 rc
= func(conf
->cmdline
);
4576 static int serial_parse(const char *devname
)
4578 static int index
= 0;
4581 if (strcmp(devname
, "none") == 0)
4583 if (index
== MAX_SERIAL_PORTS
) {
4584 fprintf(stderr
, "qemu: too many serial ports\n");
4587 snprintf(label
, sizeof(label
), "serial%d", index
);
4588 serial_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4589 if (!serial_hds
[index
]) {
4590 fprintf(stderr
, "qemu: could not open serial device '%s': %s\n",
4591 devname
, strerror(errno
));
4598 static int parallel_parse(const char *devname
)
4600 static int index
= 0;
4603 if (strcmp(devname
, "none") == 0)
4605 if (index
== MAX_PARALLEL_PORTS
) {
4606 fprintf(stderr
, "qemu: too many parallel ports\n");
4609 snprintf(label
, sizeof(label
), "parallel%d", index
);
4610 parallel_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4611 if (!parallel_hds
[index
]) {
4612 fprintf(stderr
, "qemu: could not open parallel device '%s': %s\n",
4613 devname
, strerror(errno
));
4620 static int virtcon_parse(const char *devname
)
4622 static int index
= 0;
4625 if (strcmp(devname
, "none") == 0)
4627 if (index
== MAX_VIRTIO_CONSOLES
) {
4628 fprintf(stderr
, "qemu: too many virtio consoles\n");
4631 snprintf(label
, sizeof(label
), "virtcon%d", index
);
4632 virtcon_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4633 if (!virtcon_hds
[index
]) {
4634 fprintf(stderr
, "qemu: could not open virtio console '%s': %s\n",
4635 devname
, strerror(errno
));
4642 static int debugcon_parse(const char *devname
)
4646 if (!qemu_chr_open("debugcon", devname
, NULL
)) {
4649 opts
= qemu_opts_create(&qemu_device_opts
, "debugcon", 1);
4651 fprintf(stderr
, "qemu: already have a debugcon device\n");
4654 qemu_opt_set(opts
, "driver", "isa-debugcon");
4655 qemu_opt_set(opts
, "chardev", "debugcon");
4659 int main(int argc
, char **argv
, char **envp
)
4661 const char *gdbstub_dev
= NULL
;
4662 uint32_t boot_devices_bitmap
= 0;
4664 int snapshot
, linux_boot
, net_boot
;
4665 const char *initrd_filename
;
4666 const char *kernel_filename
, *kernel_cmdline
;
4667 char boot_devices
[33] = "cad"; /* default to HD->floppy->CD-ROM */
4669 DisplayChangeListener
*dcl
;
4670 int cyls
, heads
, secs
, translation
;
4671 QemuOpts
*hda_opts
= NULL
, *opts
;
4673 const char *r
, *optarg
;
4674 const char *loadvm
= NULL
;
4675 QEMUMachine
*machine
;
4676 const char *cpu_model
;
4681 const char *pid_file
= NULL
;
4682 const char *incoming
= NULL
;
4685 struct passwd
*pwd
= NULL
;
4686 const char *chroot_dir
= NULL
;
4687 const char *run_as
= NULL
;
4690 int show_vnc_port
= 0;
4694 qemu_errors_to_file(stderr
);
4695 qemu_cache_utils_init(envp
);
4697 QLIST_INIT (&vm_change_state_head
);
4700 struct sigaction act
;
4701 sigfillset(&act
.sa_mask
);
4703 act
.sa_handler
= SIG_IGN
;
4704 sigaction(SIGPIPE
, &act
, NULL
);
4707 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4708 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4709 QEMU to run on a single CPU */
4714 h
= GetCurrentProcess();
4715 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4716 for(i
= 0; i
< 32; i
++) {
4717 if (mask
& (1 << i
))
4722 SetProcessAffinityMask(h
, mask
);
4728 module_call_init(MODULE_INIT_MACHINE
);
4729 machine
= find_default_machine();
4731 initrd_filename
= NULL
;
4734 kernel_filename
= NULL
;
4735 kernel_cmdline
= "";
4736 cyls
= heads
= secs
= 0;
4737 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4739 for (i
= 0; i
< MAX_NODES
; i
++) {
4741 node_cpumask
[i
] = 0;
4756 hda_opts
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
4758 const QEMUOption
*popt
;
4761 /* Treat --foo the same as -foo. */
4764 popt
= qemu_options
;
4767 fprintf(stderr
, "%s: invalid option -- '%s'\n",
4771 if (!strcmp(popt
->name
, r
+ 1))
4775 if (popt
->flags
& HAS_ARG
) {
4776 if (optind
>= argc
) {
4777 fprintf(stderr
, "%s: option '%s' requires an argument\n",
4781 optarg
= argv
[optind
++];
4786 switch(popt
->index
) {
4788 machine
= find_machine(optarg
);
4791 printf("Supported machines are:\n");
4792 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
4794 printf("%-10s %s (alias of %s)\n",
4795 m
->alias
, m
->desc
, m
->name
);
4796 printf("%-10s %s%s\n",
4798 m
->is_default
? " (default)" : "");
4800 exit(*optarg
!= '?');
4803 case QEMU_OPTION_cpu
:
4804 /* hw initialization will check this */
4805 if (*optarg
== '?') {
4806 /* XXX: implement xxx_cpu_list for targets that still miss it */
4807 #if defined(cpu_list)
4808 cpu_list(stdout
, &fprintf
);
4815 case QEMU_OPTION_initrd
:
4816 initrd_filename
= optarg
;
4818 case QEMU_OPTION_hda
:
4820 hda_opts
= drive_add(optarg
, HD_ALIAS
, 0);
4822 hda_opts
= drive_add(optarg
, HD_ALIAS
4823 ",cyls=%d,heads=%d,secs=%d%s",
4824 0, cyls
, heads
, secs
,
4825 translation
== BIOS_ATA_TRANSLATION_LBA
?
4827 translation
== BIOS_ATA_TRANSLATION_NONE
?
4828 ",trans=none" : "");
4830 case QEMU_OPTION_hdb
:
4831 case QEMU_OPTION_hdc
:
4832 case QEMU_OPTION_hdd
:
4833 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
4835 case QEMU_OPTION_drive
:
4836 drive_add(NULL
, "%s", optarg
);
4838 case QEMU_OPTION_set
:
4839 if (qemu_set_option(optarg
) != 0)
4842 case QEMU_OPTION_global
:
4843 if (qemu_global_option(optarg
) != 0)
4846 case QEMU_OPTION_mtdblock
:
4847 drive_add(optarg
, MTD_ALIAS
);
4849 case QEMU_OPTION_sd
:
4850 drive_add(optarg
, SD_ALIAS
);
4852 case QEMU_OPTION_pflash
:
4853 drive_add(optarg
, PFLASH_ALIAS
);
4855 case QEMU_OPTION_snapshot
:
4858 case QEMU_OPTION_hdachs
:
4862 cyls
= strtol(p
, (char **)&p
, 0);
4863 if (cyls
< 1 || cyls
> 16383)
4868 heads
= strtol(p
, (char **)&p
, 0);
4869 if (heads
< 1 || heads
> 16)
4874 secs
= strtol(p
, (char **)&p
, 0);
4875 if (secs
< 1 || secs
> 63)
4879 if (!strcmp(p
, "none"))
4880 translation
= BIOS_ATA_TRANSLATION_NONE
;
4881 else if (!strcmp(p
, "lba"))
4882 translation
= BIOS_ATA_TRANSLATION_LBA
;
4883 else if (!strcmp(p
, "auto"))
4884 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4887 } else if (*p
!= '\0') {
4889 fprintf(stderr
, "qemu: invalid physical CHS format\n");
4892 if (hda_opts
!= NULL
) {
4894 snprintf(num
, sizeof(num
), "%d", cyls
);
4895 qemu_opt_set(hda_opts
, "cyls", num
);
4896 snprintf(num
, sizeof(num
), "%d", heads
);
4897 qemu_opt_set(hda_opts
, "heads", num
);
4898 snprintf(num
, sizeof(num
), "%d", secs
);
4899 qemu_opt_set(hda_opts
, "secs", num
);
4900 if (translation
== BIOS_ATA_TRANSLATION_LBA
)
4901 qemu_opt_set(hda_opts
, "trans", "lba");
4902 if (translation
== BIOS_ATA_TRANSLATION_NONE
)
4903 qemu_opt_set(hda_opts
, "trans", "none");
4907 case QEMU_OPTION_numa
:
4908 if (nb_numa_nodes
>= MAX_NODES
) {
4909 fprintf(stderr
, "qemu: too many NUMA nodes\n");
4914 case QEMU_OPTION_nographic
:
4915 display_type
= DT_NOGRAPHIC
;
4917 #ifdef CONFIG_CURSES
4918 case QEMU_OPTION_curses
:
4919 display_type
= DT_CURSES
;
4922 case QEMU_OPTION_portrait
:
4925 case QEMU_OPTION_kernel
:
4926 kernel_filename
= optarg
;
4928 case QEMU_OPTION_append
:
4929 kernel_cmdline
= optarg
;
4931 case QEMU_OPTION_cdrom
:
4932 drive_add(optarg
, CDROM_ALIAS
);
4934 case QEMU_OPTION_boot
:
4936 static const char * const params
[] = {
4937 "order", "once", "menu", NULL
4939 char buf
[sizeof(boot_devices
)];
4940 char *standard_boot_devices
;
4943 if (!strchr(optarg
, '=')) {
4945 pstrcpy(buf
, sizeof(buf
), optarg
);
4946 } else if (check_params(buf
, sizeof(buf
), params
, optarg
) < 0) {
4948 "qemu: unknown boot parameter '%s' in '%s'\n",
4954 get_param_value(buf
, sizeof(buf
), "order", optarg
)) {
4955 boot_devices_bitmap
= parse_bootdevices(buf
);
4956 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
4959 if (get_param_value(buf
, sizeof(buf
),
4961 boot_devices_bitmap
|= parse_bootdevices(buf
);
4962 standard_boot_devices
= qemu_strdup(boot_devices
);
4963 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
4964 qemu_register_reset(restore_boot_devices
,
4965 standard_boot_devices
);
4967 if (get_param_value(buf
, sizeof(buf
),
4969 if (!strcmp(buf
, "on")) {
4971 } else if (!strcmp(buf
, "off")) {
4975 "qemu: invalid option value '%s'\n",
4983 case QEMU_OPTION_fda
:
4984 case QEMU_OPTION_fdb
:
4985 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
4988 case QEMU_OPTION_no_fd_bootchk
:
4992 case QEMU_OPTION_netdev
:
4993 if (net_client_parse(&qemu_netdev_opts
, optarg
) == -1) {
4997 case QEMU_OPTION_net
:
4998 if (net_client_parse(&qemu_net_opts
, optarg
) == -1) {
5003 case QEMU_OPTION_tftp
:
5004 legacy_tftp_prefix
= optarg
;
5006 case QEMU_OPTION_bootp
:
5007 legacy_bootp_filename
= optarg
;
5010 case QEMU_OPTION_smb
:
5011 if (net_slirp_smb(optarg
) < 0)
5015 case QEMU_OPTION_redir
:
5016 if (net_slirp_redir(optarg
) < 0)
5020 case QEMU_OPTION_bt
:
5021 add_device_config(DEV_BT
, optarg
);
5024 case QEMU_OPTION_audio_help
:
5028 case QEMU_OPTION_soundhw
:
5029 select_soundhw (optarg
);
5035 case QEMU_OPTION_version
:
5039 case QEMU_OPTION_m
: {
5043 value
= strtoul(optarg
, &ptr
, 10);
5045 case 0: case 'M': case 'm':
5052 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5056 /* On 32-bit hosts, QEMU is limited by virtual address space */
5057 if (value
> (2047 << 20) && HOST_LONG_BITS
== 32) {
5058 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5061 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5062 fprintf(stderr
, "qemu: ram size too large\n");
5071 const CPULogItem
*item
;
5073 mask
= cpu_str_to_log_mask(optarg
);
5075 printf("Log items (comma separated):\n");
5076 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5077 printf("%-10s %s\n", item
->name
, item
->help
);
5085 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5087 case QEMU_OPTION_gdb
:
5088 gdbstub_dev
= optarg
;
5093 case QEMU_OPTION_bios
:
5096 case QEMU_OPTION_singlestep
:
5103 keyboard_layout
= optarg
;
5105 case QEMU_OPTION_localtime
:
5108 case QEMU_OPTION_vga
:
5109 select_vgahw (optarg
);
5111 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5117 w
= strtol(p
, (char **)&p
, 10);
5120 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5126 h
= strtol(p
, (char **)&p
, 10);
5131 depth
= strtol(p
, (char **)&p
, 10);
5132 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5133 depth
!= 24 && depth
!= 32)
5135 } else if (*p
== '\0') {
5136 depth
= graphic_depth
;
5143 graphic_depth
= depth
;
5147 case QEMU_OPTION_echr
:
5150 term_escape_char
= strtol(optarg
, &r
, 0);
5152 printf("Bad argument to echr\n");
5155 case QEMU_OPTION_monitor
:
5156 monitor_parse(optarg
, "readline");
5157 default_monitor
= 0;
5159 case QEMU_OPTION_qmp
:
5160 monitor_parse(optarg
, "control");
5161 default_monitor
= 0;
5163 case QEMU_OPTION_mon
:
5164 opts
= qemu_opts_parse(&qemu_mon_opts
, optarg
, "chardev");
5166 fprintf(stderr
, "parse error: %s\n", optarg
);
5169 default_monitor
= 0;
5171 case QEMU_OPTION_chardev
:
5172 opts
= qemu_opts_parse(&qemu_chardev_opts
, optarg
, "backend");
5174 fprintf(stderr
, "parse error: %s\n", optarg
);
5178 case QEMU_OPTION_serial
:
5179 add_device_config(DEV_SERIAL
, optarg
);
5182 case QEMU_OPTION_watchdog
:
5185 "qemu: only one watchdog option may be given\n");
5190 case QEMU_OPTION_watchdog_action
:
5191 if (select_watchdog_action(optarg
) == -1) {
5192 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5196 case QEMU_OPTION_virtiocon
:
5197 add_device_config(DEV_VIRTCON
, optarg
);
5198 default_virtcon
= 0;
5200 case QEMU_OPTION_parallel
:
5201 add_device_config(DEV_PARALLEL
, optarg
);
5202 default_parallel
= 0;
5204 case QEMU_OPTION_debugcon
:
5205 add_device_config(DEV_DEBUGCON
, optarg
);
5207 case QEMU_OPTION_loadvm
:
5210 case QEMU_OPTION_full_screen
:
5214 case QEMU_OPTION_no_frame
:
5217 case QEMU_OPTION_alt_grab
:
5220 case QEMU_OPTION_ctrl_grab
:
5223 case QEMU_OPTION_no_quit
:
5226 case QEMU_OPTION_sdl
:
5227 display_type
= DT_SDL
;
5230 case QEMU_OPTION_pidfile
:
5234 case QEMU_OPTION_win2k_hack
:
5235 win2k_install_hack
= 1;
5237 case QEMU_OPTION_rtc_td_hack
:
5240 case QEMU_OPTION_acpitable
:
5241 if(acpi_table_add(optarg
) < 0) {
5242 fprintf(stderr
, "Wrong acpi table provided\n");
5246 case QEMU_OPTION_smbios
:
5247 if(smbios_entry_add(optarg
) < 0) {
5248 fprintf(stderr
, "Wrong smbios provided\n");
5254 case QEMU_OPTION_enable_kvm
:
5258 case QEMU_OPTION_usb
:
5261 case QEMU_OPTION_usbdevice
:
5263 add_device_config(DEV_USB
, optarg
);
5265 case QEMU_OPTION_device
:
5266 if (!qemu_opts_parse(&qemu_device_opts
, optarg
, "driver")) {
5270 case QEMU_OPTION_smp
:
5273 fprintf(stderr
, "Invalid number of CPUs\n");
5276 if (max_cpus
< smp_cpus
) {
5277 fprintf(stderr
, "maxcpus must be equal to or greater than "
5281 if (max_cpus
> 255) {
5282 fprintf(stderr
, "Unsupported number of maxcpus\n");
5286 case QEMU_OPTION_vnc
:
5287 display_type
= DT_VNC
;
5288 vnc_display
= optarg
;
5291 case QEMU_OPTION_no_acpi
:
5294 case QEMU_OPTION_no_hpet
:
5297 case QEMU_OPTION_balloon
:
5298 if (balloon_parse(optarg
) < 0) {
5299 fprintf(stderr
, "Unknown -balloon argument %s\n", optarg
);
5304 case QEMU_OPTION_no_reboot
:
5307 case QEMU_OPTION_no_shutdown
:
5310 case QEMU_OPTION_show_cursor
:
5313 case QEMU_OPTION_uuid
:
5314 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5315 fprintf(stderr
, "Fail to parse UUID string."
5316 " Wrong format.\n");
5321 case QEMU_OPTION_daemonize
:
5325 case QEMU_OPTION_option_rom
:
5326 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5327 fprintf(stderr
, "Too many option ROMs\n");
5330 option_rom
[nb_option_roms
] = optarg
;
5333 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5334 case QEMU_OPTION_semihosting
:
5335 semihosting_enabled
= 1;
5338 case QEMU_OPTION_name
:
5339 qemu_name
= qemu_strdup(optarg
);
5341 char *p
= strchr(qemu_name
, ',');
5344 if (strncmp(p
, "process=", 8)) {
5345 fprintf(stderr
, "Unknown subargument %s to -name", p
);
5353 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5354 case QEMU_OPTION_prom_env
:
5355 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5356 fprintf(stderr
, "Too many prom variables\n");
5359 prom_envs
[nb_prom_envs
] = optarg
;
5364 case QEMU_OPTION_old_param
:
5368 case QEMU_OPTION_clock
:
5369 configure_alarms(optarg
);
5371 case QEMU_OPTION_startdate
:
5372 configure_rtc_date_offset(optarg
, 1);
5374 case QEMU_OPTION_rtc
:
5375 opts
= qemu_opts_parse(&qemu_rtc_opts
, optarg
, NULL
);
5377 fprintf(stderr
, "parse error: %s\n", optarg
);
5380 configure_rtc(opts
);
5382 case QEMU_OPTION_tb_size
:
5383 tb_size
= strtol(optarg
, NULL
, 0);
5387 case QEMU_OPTION_icount
:
5389 if (strcmp(optarg
, "auto") == 0) {
5390 icount_time_shift
= -1;
5392 icount_time_shift
= strtol(optarg
, NULL
, 0);
5395 case QEMU_OPTION_incoming
:
5398 case QEMU_OPTION_nodefaults
:
5400 default_parallel
= 0;
5401 default_virtcon
= 0;
5402 default_monitor
= 0;
5410 case QEMU_OPTION_chroot
:
5411 chroot_dir
= optarg
;
5413 case QEMU_OPTION_runas
:
5418 case QEMU_OPTION_xen_domid
:
5419 xen_domid
= atoi(optarg
);
5421 case QEMU_OPTION_xen_create
:
5422 xen_mode
= XEN_CREATE
;
5424 case QEMU_OPTION_xen_attach
:
5425 xen_mode
= XEN_ATTACH
;
5428 case QEMU_OPTION_readconfig
:
5431 fp
= fopen(optarg
, "r");
5433 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5436 if (qemu_config_parse(fp
) != 0) {
5442 case QEMU_OPTION_writeconfig
:
5445 if (strcmp(optarg
, "-") == 0) {
5448 fp
= fopen(optarg
, "w");
5450 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5454 qemu_config_write(fp
);
5462 /* If no data_dir is specified then try to find it relative to the
5465 data_dir
= find_datadir(argv
[0]);
5467 /* If all else fails use the install patch specified when building. */
5469 data_dir
= CONFIG_QEMU_SHAREDIR
;
5473 * Default to max_cpus = smp_cpus, in case the user doesn't
5474 * specify a max_cpus value.
5477 max_cpus
= smp_cpus
;
5479 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5480 if (smp_cpus
> machine
->max_cpus
) {
5481 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5482 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5487 qemu_opts_foreach(&qemu_device_opts
, default_driver_check
, NULL
, 0);
5488 qemu_opts_foreach(&qemu_global_opts
, default_driver_check
, NULL
, 0);
5490 if (machine
->no_serial
) {
5493 if (machine
->no_parallel
) {
5494 default_parallel
= 0;
5496 if (!machine
->use_virtcon
) {
5497 default_virtcon
= 0;
5499 if (machine
->no_vga
) {
5502 if (machine
->no_floppy
) {
5505 if (machine
->no_cdrom
) {
5508 if (machine
->no_sdcard
) {
5512 if (display_type
== DT_NOGRAPHIC
) {
5513 if (default_parallel
)
5514 add_device_config(DEV_PARALLEL
, "null");
5515 if (default_serial
&& default_monitor
) {
5516 add_device_config(DEV_SERIAL
, "mon:stdio");
5517 } else if (default_virtcon
&& default_monitor
) {
5518 add_device_config(DEV_VIRTCON
, "mon:stdio");
5521 add_device_config(DEV_SERIAL
, "stdio");
5522 if (default_virtcon
)
5523 add_device_config(DEV_VIRTCON
, "stdio");
5524 if (default_monitor
)
5525 monitor_parse("stdio", "readline");
5529 add_device_config(DEV_SERIAL
, "vc:80Cx24C");
5530 if (default_parallel
)
5531 add_device_config(DEV_PARALLEL
, "vc:80Cx24C");
5532 if (default_monitor
)
5533 monitor_parse("vc:80Cx24C", "readline");
5534 if (default_virtcon
)
5535 add_device_config(DEV_VIRTCON
, "vc:80Cx24C");
5538 vga_interface_type
= VGA_CIRRUS
;
5540 if (qemu_opts_foreach(&qemu_chardev_opts
, chardev_init_func
, NULL
, 1) != 0)
5547 if (pipe(fds
) == -1)
5558 len
= read(fds
[0], &status
, 1);
5559 if (len
== -1 && (errno
== EINTR
))
5564 else if (status
== 1) {
5565 fprintf(stderr
, "Could not acquire pidfile: %s\n", strerror(errno
));
5573 qemu_set_cloexec(fds
[1]);
5585 signal(SIGTSTP
, SIG_IGN
);
5586 signal(SIGTTOU
, SIG_IGN
);
5587 signal(SIGTTIN
, SIG_IGN
);
5591 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5595 write(fds
[1], &status
, 1);
5598 fprintf(stderr
, "Could not acquire pid file: %s\n", strerror(errno
));
5602 if (kvm_enabled()) {
5605 ret
= kvm_init(smp_cpus
);
5607 fprintf(stderr
, "failed to initialize KVM\n");
5612 if (qemu_init_main_loop()) {
5613 fprintf(stderr
, "qemu_init_main_loop failed\n");
5616 linux_boot
= (kernel_filename
!= NULL
);
5618 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5619 fprintf(stderr
, "-append only allowed with -kernel option\n");
5623 if (!linux_boot
&& initrd_filename
!= NULL
) {
5624 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5629 /* Win32 doesn't support line-buffering and requires size >= 2 */
5630 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5633 if (init_timer_alarm() < 0) {
5634 fprintf(stderr
, "could not initialize alarm timer\n");
5637 if (use_icount
&& icount_time_shift
< 0) {
5639 /* 125MIPS seems a reasonable initial guess at the guest speed.
5640 It will be corrected fairly quickly anyway. */
5641 icount_time_shift
= 3;
5642 init_icount_adjust();
5649 if (net_init_clients() < 0) {
5653 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5654 net_set_boot_mask(net_boot
);
5656 /* init the bluetooth world */
5657 if (foreach_device_config(DEV_BT
, bt_parse
))
5660 /* init the memory */
5662 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5664 /* init the dynamic translator */
5665 cpu_exec_init_all(tb_size
* 1024 * 1024);
5667 bdrv_init_with_whitelist();
5671 if (default_cdrom
) {
5672 /* we always create the cdrom drive, even if no disk is there */
5673 drive_add(NULL
, CDROM_ALIAS
);
5676 if (default_floppy
) {
5677 /* we always create at least one floppy */
5678 drive_add(NULL
, FD_ALIAS
, 0);
5681 if (default_sdcard
) {
5682 /* we always create one sd slot, even if no card is in it */
5683 drive_add(NULL
, SD_ALIAS
);
5686 /* open the virtual block devices */
5688 qemu_opts_foreach(&qemu_drive_opts
, drive_enable_snapshot
, NULL
, 0);
5689 if (qemu_opts_foreach(&qemu_drive_opts
, drive_init_func
, machine
, 1) != 0)
5692 vmstate_register(0, &vmstate_timers
,&timers_state
);
5693 register_savevm_live("ram", 0, 3, NULL
, ram_save_live
, NULL
,
5696 if (nb_numa_nodes
> 0) {
5699 if (nb_numa_nodes
> smp_cpus
) {
5700 nb_numa_nodes
= smp_cpus
;
5703 /* If no memory size if given for any node, assume the default case
5704 * and distribute the available memory equally across all nodes
5706 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5707 if (node_mem
[i
] != 0)
5710 if (i
== nb_numa_nodes
) {
5711 uint64_t usedmem
= 0;
5713 /* On Linux, the each node's border has to be 8MB aligned,
5714 * the final node gets the rest.
5716 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
5717 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
5718 usedmem
+= node_mem
[i
];
5720 node_mem
[i
] = ram_size
- usedmem
;
5723 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5724 if (node_cpumask
[i
] != 0)
5727 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5728 * must cope with this anyway, because there are BIOSes out there in
5729 * real machines which also use this scheme.
5731 if (i
== nb_numa_nodes
) {
5732 for (i
= 0; i
< smp_cpus
; i
++) {
5733 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
5738 if (foreach_device_config(DEV_SERIAL
, serial_parse
) < 0)
5740 if (foreach_device_config(DEV_PARALLEL
, parallel_parse
) < 0)
5742 if (foreach_device_config(DEV_VIRTCON
, virtcon_parse
) < 0)
5744 if (foreach_device_config(DEV_DEBUGCON
, debugcon_parse
) < 0)
5747 module_call_init(MODULE_INIT_DEVICE
);
5750 i
= select_watchdog(watchdog
);
5752 exit (i
== 1 ? 1 : 0);
5755 if (machine
->compat_props
) {
5756 qdev_prop_register_global_list(machine
->compat_props
);
5760 machine
->init(ram_size
, boot_devices
,
5761 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
5765 /* must be after terminal init, SDL library changes signal handlers */
5769 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
5770 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5771 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
5777 current_machine
= machine
;
5779 /* init USB devices */
5781 if (foreach_device_config(DEV_USB
, usb_parse
) < 0)
5785 /* init generic devices */
5786 if (qemu_opts_foreach(&qemu_device_opts
, device_init_func
, NULL
, 1) != 0)
5790 dumb_display_init();
5791 /* just use the first displaystate for the moment */
5794 if (display_type
== DT_DEFAULT
) {
5795 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5796 display_type
= DT_SDL
;
5798 display_type
= DT_VNC
;
5799 vnc_display
= "localhost:0,to=99";
5805 switch (display_type
) {
5808 #if defined(CONFIG_CURSES)
5810 curses_display_init(ds
, full_screen
);
5813 #if defined(CONFIG_SDL)
5815 sdl_display_init(ds
, full_screen
, no_frame
);
5817 #elif defined(CONFIG_COCOA)
5819 cocoa_display_init(ds
, full_screen
);
5823 vnc_display_init(ds
);
5824 if (vnc_display_open(ds
, vnc_display
) < 0)
5827 if (show_vnc_port
) {
5828 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
5836 dcl
= ds
->listeners
;
5837 while (dcl
!= NULL
) {
5838 if (dcl
->dpy_refresh
!= NULL
) {
5839 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
5840 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
5845 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
5846 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
5847 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
5850 text_consoles_set_display(display_state
);
5852 if (qemu_opts_foreach(&qemu_mon_opts
, mon_init_func
, NULL
, 1) != 0)
5855 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
5856 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
5861 qdev_machine_creation_done();
5863 if (rom_load_all() != 0) {
5864 fprintf(stderr
, "rom loading failed\n");
5868 qemu_system_reset();
5870 if (load_vmstate(cur_mon
, loadvm
) < 0) {
5876 qemu_start_incoming_migration(incoming
);
5877 } else if (autostart
) {
5887 len
= write(fds
[1], &status
, 1);
5888 if (len
== -1 && (errno
== EINTR
))
5895 TFR(fd
= qemu_open("/dev/null", O_RDWR
));
5901 pwd
= getpwnam(run_as
);
5903 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
5909 if (chroot(chroot_dir
) < 0) {
5910 fprintf(stderr
, "chroot failed\n");
5917 if (setgid(pwd
->pw_gid
) < 0) {
5918 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
5921 if (setuid(pwd
->pw_uid
) < 0) {
5922 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
5925 if (setuid(0) != -1) {
5926 fprintf(stderr
, "Dropping privileges failed\n");