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 #define MAX_VIRTIO_CONSOLES 1
178 static const char *data_dir
;
179 const char *bios_name
= NULL
;
180 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
181 to store the VM snapshots */
182 struct drivelist drives
= QTAILQ_HEAD_INITIALIZER(drives
);
183 struct driveoptlist driveopts
= QTAILQ_HEAD_INITIALIZER(driveopts
);
184 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
185 DisplayType display_type
= DT_DEFAULT
;
186 const char* keyboard_layout
= NULL
;
188 const char *mem_path
= NULL
;
190 int mem_prealloc
= 0; /* force preallocation of physical target memory */
193 NICInfo nd_table
[MAX_NICS
];
196 static int rtc_utc
= 1;
197 static int rtc_date_offset
= -1; /* -1 means no change */
198 QEMUClock
*rtc_clock
;
199 int vga_interface_type
= VGA_NONE
;
201 int graphic_width
= 1024;
202 int graphic_height
= 768;
203 int graphic_depth
= 8;
205 int graphic_width
= 800;
206 int graphic_height
= 600;
207 int graphic_depth
= 15;
209 static int full_screen
= 0;
211 static int no_frame
= 0;
214 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
215 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
216 CharDriverState
*virtcon_hds
[MAX_VIRTIO_CONSOLES
];
218 int win2k_install_hack
= 0;
227 const char *vnc_display
;
228 int acpi_enabled
= 1;
234 int graphic_rotate
= 0;
235 uint8_t irq0override
= 1;
239 const char *watchdog
;
240 const char *option_rom
[MAX_OPTION_ROMS
];
242 int semihosting_enabled
= 0;
246 const char *qemu_name
;
249 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
250 unsigned int nb_prom_envs
= 0;
251 const char *prom_envs
[MAX_PROM_ENVS
];
256 uint64_t node_mem
[MAX_NODES
];
257 uint64_t node_cpumask
[MAX_NODES
];
259 static CPUState
*cur_cpu
;
260 static CPUState
*next_cpu
;
261 /* Conversion factor from emulated instructions to virtual clock ticks. */
262 static int icount_time_shift
;
263 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
264 #define MAX_ICOUNT_SHIFT 10
265 /* Compensate for varying guest execution speed. */
266 static int64_t qemu_icount_bias
;
267 static QEMUTimer
*icount_rt_timer
;
268 static QEMUTimer
*icount_vm_timer
;
269 static QEMUTimer
*nographic_timer
;
271 uint8_t qemu_uuid
[16];
273 static QEMUBootSetHandler
*boot_set_handler
;
274 static void *boot_set_opaque
;
277 #define SIG_IPI (SIGRTMIN+4)
279 #define SIG_IPI SIGUSR1
282 static int default_serial
= 1;
283 static int default_parallel
= 1;
284 static int default_virtcon
= 1;
285 static int default_monitor
= 1;
286 static int default_vga
= 1;
287 static int default_floppy
= 1;
288 static int default_cdrom
= 1;
289 static int default_sdcard
= 1;
295 { .driver
= "isa-serial", .flag
= &default_serial
},
296 { .driver
= "isa-parallel", .flag
= &default_parallel
},
297 { .driver
= "isa-fdc", .flag
= &default_floppy
},
298 { .driver
= "ide-drive", .flag
= &default_cdrom
},
299 { .driver
= "virtio-serial-pci", .flag
= &default_virtcon
},
300 { .driver
= "virtio-serial-s390", .flag
= &default_virtcon
},
301 { .driver
= "virtio-serial", .flag
= &default_virtcon
},
302 { .driver
= "VGA", .flag
= &default_vga
},
303 { .driver
= "cirrus-vga", .flag
= &default_vga
},
304 { .driver
= "vmware-svga", .flag
= &default_vga
},
307 static int default_driver_check(QemuOpts
*opts
, void *opaque
)
309 const char *driver
= qemu_opt_get(opts
, "driver");
314 for (i
= 0; i
< ARRAY_SIZE(default_list
); i
++) {
315 if (strcmp(default_list
[i
].driver
, driver
) != 0)
317 *(default_list
[i
].flag
) = 0;
322 /***********************************************************/
323 /* x86 ISA bus support */
325 target_phys_addr_t isa_mem_base
= 0;
328 /***********************************************************/
329 void hw_error(const char *fmt
, ...)
335 fprintf(stderr
, "qemu: hardware error: ");
336 vfprintf(stderr
, fmt
, ap
);
337 fprintf(stderr
, "\n");
338 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
339 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
341 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
343 cpu_dump_state(env
, stderr
, fprintf
, 0);
350 static void set_proc_name(const char *s
)
352 #if defined(__linux__) && defined(PR_SET_NAME)
356 name
[sizeof(name
) - 1] = 0;
357 strncpy(name
, s
, sizeof(name
));
358 /* Could rewrite argv[0] too, but that's a bit more complicated.
359 This simple way is enough for `top'. */
360 prctl(PR_SET_NAME
, name
);
367 static QEMUBalloonEvent
*qemu_balloon_event
;
368 void *qemu_balloon_event_opaque
;
370 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
372 qemu_balloon_event
= func
;
373 qemu_balloon_event_opaque
= opaque
;
376 int qemu_balloon(ram_addr_t target
, MonitorCompletion cb
, void *opaque
)
378 if (qemu_balloon_event
) {
379 qemu_balloon_event(qemu_balloon_event_opaque
, target
, cb
, opaque
);
386 int qemu_balloon_status(MonitorCompletion cb
, void *opaque
)
388 if (qemu_balloon_event
) {
389 qemu_balloon_event(qemu_balloon_event_opaque
, 0, cb
, opaque
);
397 /***********************************************************/
398 /* real time host monotonic timer */
400 /* compute with 96 bit intermediate result: (a*b)/c */
401 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
406 #ifdef HOST_WORDS_BIGENDIAN
416 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
417 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
420 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
424 static int64_t get_clock_realtime(void)
428 gettimeofday(&tv
, NULL
);
429 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
434 static int64_t clock_freq
;
436 static void init_get_clock(void)
440 ret
= QueryPerformanceFrequency(&freq
);
442 fprintf(stderr
, "Could not calibrate ticks\n");
445 clock_freq
= freq
.QuadPart
;
448 static int64_t get_clock(void)
451 QueryPerformanceCounter(&ti
);
452 return muldiv64(ti
.QuadPart
, get_ticks_per_sec(), clock_freq
);
457 static int use_rt_clock
;
459 static void init_get_clock(void)
462 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
463 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
466 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
473 static int64_t get_clock(void)
475 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
476 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
479 clock_gettime(CLOCK_MONOTONIC
, &ts
);
480 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
484 /* XXX: using gettimeofday leads to problems if the date
485 changes, so it should be avoided. */
486 return get_clock_realtime();
491 /* Return the virtual CPU time, based on the instruction counter. */
492 static int64_t cpu_get_icount(void)
495 CPUState
*env
= cpu_single_env
;;
496 icount
= qemu_icount
;
499 fprintf(stderr
, "Bad clock read\n");
500 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
502 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
505 /***********************************************************/
506 /* guest cycle counter */
508 typedef struct TimersState
{
509 int64_t cpu_ticks_prev
;
510 int64_t cpu_ticks_offset
;
511 int64_t cpu_clock_offset
;
512 int32_t cpu_ticks_enabled
;
516 TimersState timers_state
;
518 /* return the host CPU cycle counter and handle stop/restart */
519 int64_t cpu_get_ticks(void)
522 return cpu_get_icount();
524 if (!timers_state
.cpu_ticks_enabled
) {
525 return timers_state
.cpu_ticks_offset
;
528 ticks
= cpu_get_real_ticks();
529 if (timers_state
.cpu_ticks_prev
> ticks
) {
530 /* Note: non increasing ticks may happen if the host uses
532 timers_state
.cpu_ticks_offset
+= timers_state
.cpu_ticks_prev
- ticks
;
534 timers_state
.cpu_ticks_prev
= ticks
;
535 return ticks
+ timers_state
.cpu_ticks_offset
;
539 /* return the host CPU monotonic timer and handle stop/restart */
540 static int64_t cpu_get_clock(void)
543 if (!timers_state
.cpu_ticks_enabled
) {
544 return timers_state
.cpu_clock_offset
;
547 return ti
+ timers_state
.cpu_clock_offset
;
551 #ifndef CONFIG_IOTHREAD
552 static int64_t qemu_icount_delta(void)
555 return 5000 * (int64_t) 1000000;
556 } else if (use_icount
== 1) {
557 /* When not using an adaptive execution frequency
558 we tend to get badly out of sync with real time,
559 so just delay for a reasonable amount of time. */
562 return cpu_get_icount() - cpu_get_clock();
567 /* enable cpu_get_ticks() */
568 void cpu_enable_ticks(void)
570 if (!timers_state
.cpu_ticks_enabled
) {
571 timers_state
.cpu_ticks_offset
-= cpu_get_real_ticks();
572 timers_state
.cpu_clock_offset
-= get_clock();
573 timers_state
.cpu_ticks_enabled
= 1;
577 /* disable cpu_get_ticks() : the clock is stopped. You must not call
578 cpu_get_ticks() after that. */
579 void cpu_disable_ticks(void)
581 if (timers_state
.cpu_ticks_enabled
) {
582 timers_state
.cpu_ticks_offset
= cpu_get_ticks();
583 timers_state
.cpu_clock_offset
= cpu_get_clock();
584 timers_state
.cpu_ticks_enabled
= 0;
588 /***********************************************************/
591 #define QEMU_CLOCK_REALTIME 0
592 #define QEMU_CLOCK_VIRTUAL 1
593 #define QEMU_CLOCK_HOST 2
598 /* XXX: add frequency */
606 struct QEMUTimer
*next
;
609 struct qemu_alarm_timer
{
611 int (*start
)(struct qemu_alarm_timer
*t
);
612 void (*stop
)(struct qemu_alarm_timer
*t
);
613 void (*rearm
)(struct qemu_alarm_timer
*t
);
620 static struct qemu_alarm_timer
*alarm_timer
;
622 static inline int qemu_alarm_pending(void)
624 return alarm_timer
->pending
;
627 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
632 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
634 if (!alarm_has_dynticks(t
))
640 /* TODO: MIN_TIMER_REARM_US should be optimized */
641 #define MIN_TIMER_REARM_US 250
645 struct qemu_alarm_win32
{
648 } alarm_win32_data
= {0, 0};
650 static int win32_start_timer(struct qemu_alarm_timer
*t
);
651 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
652 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
656 static int unix_start_timer(struct qemu_alarm_timer
*t
);
657 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
661 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
662 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
663 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
665 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
666 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
668 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
669 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
671 #endif /* __linux__ */
675 /* Correlation between real and virtual time is always going to be
676 fairly approximate, so ignore small variation.
677 When the guest is idle real and virtual time will be aligned in
679 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
681 static void icount_adjust(void)
686 static int64_t last_delta
;
687 /* If the VM is not running, then do nothing. */
691 cur_time
= cpu_get_clock();
692 cur_icount
= qemu_get_clock(vm_clock
);
693 delta
= cur_icount
- cur_time
;
694 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
696 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
697 && icount_time_shift
> 0) {
698 /* The guest is getting too far ahead. Slow time down. */
702 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
703 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
704 /* The guest is getting too far behind. Speed time up. */
708 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
711 static void icount_adjust_rt(void * opaque
)
713 qemu_mod_timer(icount_rt_timer
,
714 qemu_get_clock(rt_clock
) + 1000);
718 static void icount_adjust_vm(void * opaque
)
720 qemu_mod_timer(icount_vm_timer
,
721 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
725 static void configure_icount(const char *option
)
730 if (strcmp(option
, "auto") != 0) {
731 icount_time_shift
= strtol(option
, NULL
, 0);
738 /* 125MIPS seems a reasonable initial guess at the guest speed.
739 It will be corrected fairly quickly anyway. */
740 icount_time_shift
= 3;
742 /* Have both realtime and virtual time triggers for speed adjustment.
743 The realtime trigger catches emulated time passing too slowly,
744 the virtual time trigger catches emulated time passing too fast.
745 Realtime triggers occur even when idle, so use them less frequently
747 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
748 qemu_mod_timer(icount_rt_timer
,
749 qemu_get_clock(rt_clock
) + 1000);
750 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
751 qemu_mod_timer(icount_vm_timer
,
752 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
755 static int64_t qemu_icount_round(int64_t count
)
757 return (count
+ (1 << icount_time_shift
) - 1) >> icount_time_shift
;
760 static struct qemu_alarm_timer alarm_timers
[] = {
763 {"dynticks", dynticks_start_timer
,
764 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
765 /* HPET - if available - is preferred */
766 {"hpet", hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
767 /* ...otherwise try RTC */
768 {"rtc", rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
770 {"unix", unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
772 {"dynticks", win32_start_timer
,
773 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
774 {"win32", win32_start_timer
,
775 win32_stop_timer
, NULL
, &alarm_win32_data
},
780 static void show_available_alarms(void)
784 printf("Available alarm timers, in order of precedence:\n");
785 for (i
= 0; alarm_timers
[i
].name
; i
++)
786 printf("%s\n", alarm_timers
[i
].name
);
789 static void configure_alarms(char const *opt
)
793 int count
= ARRAY_SIZE(alarm_timers
) - 1;
796 struct qemu_alarm_timer tmp
;
798 if (!strcmp(opt
, "?")) {
799 show_available_alarms();
803 arg
= qemu_strdup(opt
);
805 /* Reorder the array */
806 name
= strtok(arg
, ",");
808 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
809 if (!strcmp(alarm_timers
[i
].name
, name
))
814 fprintf(stderr
, "Unknown clock %s\n", name
);
823 tmp
= alarm_timers
[i
];
824 alarm_timers
[i
] = alarm_timers
[cur
];
825 alarm_timers
[cur
] = tmp
;
829 name
= strtok(NULL
, ",");
835 /* Disable remaining timers */
836 for (i
= cur
; i
< count
; i
++)
837 alarm_timers
[i
].name
= NULL
;
839 show_available_alarms();
844 #define QEMU_NUM_CLOCKS 3
848 QEMUClock
*host_clock
;
850 static QEMUTimer
*active_timers
[QEMU_NUM_CLOCKS
];
852 static QEMUClock
*qemu_new_clock(int type
)
855 clock
= qemu_mallocz(sizeof(QEMUClock
));
861 static void qemu_clock_enable(QEMUClock
*clock
, int enabled
)
863 clock
->enabled
= enabled
;
866 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
870 ts
= qemu_mallocz(sizeof(QEMUTimer
));
877 void qemu_free_timer(QEMUTimer
*ts
)
882 /* stop a timer, but do not dealloc it */
883 void qemu_del_timer(QEMUTimer
*ts
)
887 /* NOTE: this code must be signal safe because
888 qemu_timer_expired() can be called from a signal. */
889 pt
= &active_timers
[ts
->clock
->type
];
902 /* modify the current timer so that it will be fired when current_time
903 >= expire_time. The corresponding callback will be called. */
904 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
910 /* add the timer in the sorted list */
911 /* NOTE: this code must be signal safe because
912 qemu_timer_expired() can be called from a signal. */
913 pt
= &active_timers
[ts
->clock
->type
];
918 if (t
->expire_time
> expire_time
)
922 ts
->expire_time
= expire_time
;
926 /* Rearm if necessary */
927 if (pt
== &active_timers
[ts
->clock
->type
]) {
928 if (!alarm_timer
->pending
) {
929 qemu_rearm_alarm_timer(alarm_timer
);
931 /* Interrupt execution to force deadline recalculation. */
937 int qemu_timer_pending(QEMUTimer
*ts
)
940 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
947 int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
951 return (timer_head
->expire_time
<= current_time
);
954 static void qemu_run_timers(QEMUClock
*clock
)
956 QEMUTimer
**ptimer_head
, *ts
;
957 int64_t current_time
;
962 current_time
= qemu_get_clock (clock
);
963 ptimer_head
= &active_timers
[clock
->type
];
966 if (!ts
|| ts
->expire_time
> current_time
)
968 /* remove timer from the list before calling the callback */
969 *ptimer_head
= ts
->next
;
972 /* run the callback (the timer list can be modified) */
977 int64_t qemu_get_clock(QEMUClock
*clock
)
979 switch(clock
->type
) {
980 case QEMU_CLOCK_REALTIME
:
981 return get_clock() / 1000000;
983 case QEMU_CLOCK_VIRTUAL
:
985 return cpu_get_icount();
987 return cpu_get_clock();
989 case QEMU_CLOCK_HOST
:
990 return get_clock_realtime();
994 int64_t qemu_get_clock_ns(QEMUClock
*clock
)
996 switch(clock
->type
) {
997 case QEMU_CLOCK_REALTIME
:
1000 case QEMU_CLOCK_VIRTUAL
:
1002 return cpu_get_icount();
1004 return cpu_get_clock();
1006 case QEMU_CLOCK_HOST
:
1007 return get_clock_realtime();
1011 static void init_clocks(void)
1014 rt_clock
= qemu_new_clock(QEMU_CLOCK_REALTIME
);
1015 vm_clock
= qemu_new_clock(QEMU_CLOCK_VIRTUAL
);
1016 host_clock
= qemu_new_clock(QEMU_CLOCK_HOST
);
1018 rtc_clock
= host_clock
;
1022 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1024 uint64_t expire_time
;
1026 if (qemu_timer_pending(ts
)) {
1027 expire_time
= ts
->expire_time
;
1031 qemu_put_be64(f
, expire_time
);
1034 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1036 uint64_t expire_time
;
1038 expire_time
= qemu_get_be64(f
);
1039 if (expire_time
!= -1) {
1040 qemu_mod_timer(ts
, expire_time
);
1046 static const VMStateDescription vmstate_timers
= {
1049 .minimum_version_id
= 1,
1050 .minimum_version_id_old
= 1,
1051 .fields
= (VMStateField
[]) {
1052 VMSTATE_INT64(cpu_ticks_offset
, TimersState
),
1053 VMSTATE_INT64(dummy
, TimersState
),
1054 VMSTATE_INT64_V(cpu_clock_offset
, TimersState
, 2),
1055 VMSTATE_END_OF_LIST()
1059 static void qemu_run_all_timers(void)
1061 /* rearm timer, if not periodic */
1062 if (alarm_timer
->expired
) {
1063 alarm_timer
->expired
= 0;
1064 qemu_rearm_alarm_timer(alarm_timer
);
1067 alarm_timer
->pending
= 0;
1069 /* vm time timers */
1071 qemu_run_timers(vm_clock
);
1074 qemu_run_timers(rt_clock
);
1075 qemu_run_timers(host_clock
);
1079 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1080 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1083 static void host_alarm_handler(int host_signum
)
1086 struct qemu_alarm_timer
*t
= alarm_timer
;
1091 #define DISP_FREQ 1000
1093 static int64_t delta_min
= INT64_MAX
;
1094 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1096 ti
= qemu_get_clock(vm_clock
);
1097 if (last_clock
!= 0) {
1098 delta
= ti
- last_clock
;
1099 if (delta
< delta_min
)
1101 if (delta
> delta_max
)
1104 if (++count
== DISP_FREQ
) {
1105 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1106 muldiv64(delta_min
, 1000000, get_ticks_per_sec()),
1107 muldiv64(delta_max
, 1000000, get_ticks_per_sec()),
1108 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, get_ticks_per_sec()),
1109 (double)get_ticks_per_sec() / ((double)delta_cum
/ DISP_FREQ
));
1111 delta_min
= INT64_MAX
;
1119 if (alarm_has_dynticks(t
) ||
1121 qemu_timer_expired(active_timers
[QEMU_CLOCK_VIRTUAL
],
1122 qemu_get_clock(vm_clock
))) ||
1123 qemu_timer_expired(active_timers
[QEMU_CLOCK_REALTIME
],
1124 qemu_get_clock(rt_clock
)) ||
1125 qemu_timer_expired(active_timers
[QEMU_CLOCK_HOST
],
1126 qemu_get_clock(host_clock
))) {
1128 t
->expired
= alarm_has_dynticks(t
);
1130 qemu_notify_event();
1134 static int64_t qemu_next_deadline(void)
1136 /* To avoid problems with overflow limit this to 2^32. */
1137 int64_t delta
= INT32_MAX
;
1139 if (active_timers
[QEMU_CLOCK_VIRTUAL
]) {
1140 delta
= active_timers
[QEMU_CLOCK_VIRTUAL
]->expire_time
-
1141 qemu_get_clock(vm_clock
);
1143 if (active_timers
[QEMU_CLOCK_HOST
]) {
1144 int64_t hdelta
= active_timers
[QEMU_CLOCK_HOST
]->expire_time
-
1145 qemu_get_clock(host_clock
);
1156 #if defined(__linux__)
1157 static uint64_t qemu_next_deadline_dyntick(void)
1165 delta
= (qemu_next_deadline() + 999) / 1000;
1167 if (active_timers
[QEMU_CLOCK_REALTIME
]) {
1168 rtdelta
= (active_timers
[QEMU_CLOCK_REALTIME
]->expire_time
-
1169 qemu_get_clock(rt_clock
))*1000;
1170 if (rtdelta
< delta
)
1174 if (delta
< MIN_TIMER_REARM_US
)
1175 delta
= MIN_TIMER_REARM_US
;
1183 /* Sets a specific flag */
1184 static int fcntl_setfl(int fd
, int flag
)
1188 flags
= fcntl(fd
, F_GETFL
);
1192 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1198 #if defined(__linux__)
1200 #define RTC_FREQ 1024
1202 static void enable_sigio_timer(int fd
)
1204 struct sigaction act
;
1207 sigfillset(&act
.sa_mask
);
1209 act
.sa_handler
= host_alarm_handler
;
1211 sigaction(SIGIO
, &act
, NULL
);
1212 fcntl_setfl(fd
, O_ASYNC
);
1213 fcntl(fd
, F_SETOWN
, getpid());
1216 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1218 struct hpet_info info
;
1221 fd
= qemu_open("/dev/hpet", O_RDONLY
);
1226 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1228 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1229 "error, but for better emulation accuracy type:\n"
1230 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1234 /* Check capabilities */
1235 r
= ioctl(fd
, HPET_INFO
, &info
);
1239 /* Enable periodic mode */
1240 r
= ioctl(fd
, HPET_EPI
, 0);
1241 if (info
.hi_flags
&& (r
< 0))
1244 /* Enable interrupt */
1245 r
= ioctl(fd
, HPET_IE_ON
, 0);
1249 enable_sigio_timer(fd
);
1250 t
->priv
= (void *)(long)fd
;
1258 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1260 int fd
= (long)t
->priv
;
1265 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1268 unsigned long current_rtc_freq
= 0;
1270 TFR(rtc_fd
= qemu_open("/dev/rtc", O_RDONLY
));
1273 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1274 if (current_rtc_freq
!= RTC_FREQ
&&
1275 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1276 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1277 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1278 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1281 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1287 enable_sigio_timer(rtc_fd
);
1289 t
->priv
= (void *)(long)rtc_fd
;
1294 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1296 int rtc_fd
= (long)t
->priv
;
1301 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1305 struct sigaction act
;
1307 sigfillset(&act
.sa_mask
);
1309 act
.sa_handler
= host_alarm_handler
;
1311 sigaction(SIGALRM
, &act
, NULL
);
1314 * Initialize ev struct to 0 to avoid valgrind complaining
1315 * about uninitialized data in timer_create call
1317 memset(&ev
, 0, sizeof(ev
));
1318 ev
.sigev_value
.sival_int
= 0;
1319 ev
.sigev_notify
= SIGEV_SIGNAL
;
1320 ev
.sigev_signo
= SIGALRM
;
1322 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1323 perror("timer_create");
1325 /* disable dynticks */
1326 fprintf(stderr
, "Dynamic Ticks disabled\n");
1331 t
->priv
= (void *)(long)host_timer
;
1336 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1338 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1340 timer_delete(host_timer
);
1343 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1345 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1346 struct itimerspec timeout
;
1347 int64_t nearest_delta_us
= INT64_MAX
;
1350 assert(alarm_has_dynticks(t
));
1351 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1352 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1353 !active_timers
[QEMU_CLOCK_HOST
])
1356 nearest_delta_us
= qemu_next_deadline_dyntick();
1358 /* check whether a timer is already running */
1359 if (timer_gettime(host_timer
, &timeout
)) {
1361 fprintf(stderr
, "Internal timer error: aborting\n");
1364 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1365 if (current_us
&& current_us
<= nearest_delta_us
)
1368 timeout
.it_interval
.tv_sec
= 0;
1369 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1370 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1371 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1372 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1374 fprintf(stderr
, "Internal timer error: aborting\n");
1379 #endif /* defined(__linux__) */
1381 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1383 struct sigaction act
;
1384 struct itimerval itv
;
1388 sigfillset(&act
.sa_mask
);
1390 act
.sa_handler
= host_alarm_handler
;
1392 sigaction(SIGALRM
, &act
, NULL
);
1394 itv
.it_interval
.tv_sec
= 0;
1395 /* for i386 kernel 2.6 to get 1 ms */
1396 itv
.it_interval
.tv_usec
= 999;
1397 itv
.it_value
.tv_sec
= 0;
1398 itv
.it_value
.tv_usec
= 10 * 1000;
1400 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1407 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1409 struct itimerval itv
;
1411 memset(&itv
, 0, sizeof(itv
));
1412 setitimer(ITIMER_REAL
, &itv
, NULL
);
1415 #endif /* !defined(_WIN32) */
1420 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1423 struct qemu_alarm_win32
*data
= t
->priv
;
1426 memset(&tc
, 0, sizeof(tc
));
1427 timeGetDevCaps(&tc
, sizeof(tc
));
1429 data
->period
= tc
.wPeriodMin
;
1430 timeBeginPeriod(data
->period
);
1432 flags
= TIME_CALLBACK_FUNCTION
;
1433 if (alarm_has_dynticks(t
))
1434 flags
|= TIME_ONESHOT
;
1436 flags
|= TIME_PERIODIC
;
1438 data
->timerId
= timeSetEvent(1, // interval (ms)
1439 data
->period
, // resolution
1440 host_alarm_handler
, // function
1441 (DWORD
)t
, // parameter
1444 if (!data
->timerId
) {
1445 fprintf(stderr
, "Failed to initialize win32 alarm timer: %ld\n",
1447 timeEndPeriod(data
->period
);
1454 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1456 struct qemu_alarm_win32
*data
= t
->priv
;
1458 timeKillEvent(data
->timerId
);
1459 timeEndPeriod(data
->period
);
1462 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1464 struct qemu_alarm_win32
*data
= t
->priv
;
1466 assert(alarm_has_dynticks(t
));
1467 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1468 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1469 !active_timers
[QEMU_CLOCK_HOST
])
1472 timeKillEvent(data
->timerId
);
1474 data
->timerId
= timeSetEvent(1,
1478 TIME_ONESHOT
| TIME_CALLBACK_FUNCTION
);
1480 if (!data
->timerId
) {
1481 fprintf(stderr
, "Failed to re-arm win32 alarm timer %ld\n",
1484 timeEndPeriod(data
->period
);
1491 static void alarm_timer_on_change_state_rearm(void *opaque
, int running
, int reason
)
1494 qemu_rearm_alarm_timer((struct qemu_alarm_timer
*) opaque
);
1497 static int init_timer_alarm(void)
1499 struct qemu_alarm_timer
*t
= NULL
;
1502 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1503 t
= &alarm_timers
[i
];
1515 /* first event is at time 0 */
1518 qemu_add_vm_change_state_handler(alarm_timer_on_change_state_rearm
, t
);
1526 static void quit_timers(void)
1528 struct qemu_alarm_timer
*t
= alarm_timer
;
1533 /***********************************************************/
1534 /* host time/date access */
1535 void qemu_get_timedate(struct tm
*tm
, int offset
)
1542 if (rtc_date_offset
== -1) {
1546 ret
= localtime(&ti
);
1548 ti
-= rtc_date_offset
;
1552 memcpy(tm
, ret
, sizeof(struct tm
));
1555 int qemu_timedate_diff(struct tm
*tm
)
1559 if (rtc_date_offset
== -1)
1561 seconds
= mktimegm(tm
);
1563 seconds
= mktime(tm
);
1565 seconds
= mktimegm(tm
) + rtc_date_offset
;
1567 return seconds
- time(NULL
);
1570 void rtc_change_mon_event(struct tm
*tm
)
1574 data
= qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm
));
1575 monitor_protocol_event(QEVENT_RTC_CHANGE
, data
);
1576 qobject_decref(data
);
1579 static void configure_rtc_date_offset(const char *startdate
, int legacy
)
1581 time_t rtc_start_date
;
1584 if (!strcmp(startdate
, "now") && legacy
) {
1585 rtc_date_offset
= -1;
1587 if (sscanf(startdate
, "%d-%d-%dT%d:%d:%d",
1595 } else if (sscanf(startdate
, "%d-%d-%d",
1598 &tm
.tm_mday
) == 3) {
1607 rtc_start_date
= mktimegm(&tm
);
1608 if (rtc_start_date
== -1) {
1610 fprintf(stderr
, "Invalid date format. Valid formats are:\n"
1611 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1614 rtc_date_offset
= time(NULL
) - rtc_start_date
;
1618 static void configure_rtc(QemuOpts
*opts
)
1622 value
= qemu_opt_get(opts
, "base");
1624 if (!strcmp(value
, "utc")) {
1626 } else if (!strcmp(value
, "localtime")) {
1629 configure_rtc_date_offset(value
, 0);
1632 value
= qemu_opt_get(opts
, "clock");
1634 if (!strcmp(value
, "host")) {
1635 rtc_clock
= host_clock
;
1636 } else if (!strcmp(value
, "vm")) {
1637 rtc_clock
= vm_clock
;
1639 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1643 #ifdef CONFIG_TARGET_I386
1644 value
= qemu_opt_get(opts
, "driftfix");
1646 if (!strcmp(buf
, "slew")) {
1648 } else if (!strcmp(buf
, "none")) {
1651 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1659 static void socket_cleanup(void)
1664 static int socket_init(void)
1669 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1671 err
= WSAGetLastError();
1672 fprintf(stderr
, "WSAStartup: %d\n", err
);
1675 atexit(socket_cleanup
);
1680 /***********************************************************/
1681 /* Bluetooth support */
1684 static struct HCIInfo
*hci_table
[MAX_NICS
];
1686 static struct bt_vlan_s
{
1687 struct bt_scatternet_s net
;
1689 struct bt_vlan_s
*next
;
1692 /* find or alloc a new bluetooth "VLAN" */
1693 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1695 struct bt_vlan_s
**pvlan
, *vlan
;
1696 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1700 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1702 pvlan
= &first_bt_vlan
;
1703 while (*pvlan
!= NULL
)
1704 pvlan
= &(*pvlan
)->next
;
1709 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1713 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1718 static struct HCIInfo null_hci
= {
1719 .cmd_send
= null_hci_send
,
1720 .sco_send
= null_hci_send
,
1721 .acl_send
= null_hci_send
,
1722 .bdaddr_set
= null_hci_addr_set
,
1725 struct HCIInfo
*qemu_next_hci(void)
1727 if (cur_hci
== nb_hcis
)
1730 return hci_table
[cur_hci
++];
1733 static struct HCIInfo
*hci_init(const char *str
)
1736 struct bt_scatternet_s
*vlan
= 0;
1738 if (!strcmp(str
, "null"))
1741 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
1743 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
1744 else if (!strncmp(str
, "hci", 3)) {
1747 if (!strncmp(str
+ 3, ",vlan=", 6)) {
1748 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
1753 vlan
= qemu_find_bt_vlan(0);
1755 return bt_new_hci(vlan
);
1758 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
1763 static int bt_hci_parse(const char *str
)
1765 struct HCIInfo
*hci
;
1768 if (nb_hcis
>= MAX_NICS
) {
1769 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
1773 hci
= hci_init(str
);
1782 bdaddr
.b
[5] = 0x56 + nb_hcis
;
1783 hci
->bdaddr_set(hci
, bdaddr
.b
);
1785 hci_table
[nb_hcis
++] = hci
;
1790 static void bt_vhci_add(int vlan_id
)
1792 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
1795 fprintf(stderr
, "qemu: warning: adding a VHCI to "
1796 "an empty scatternet %i\n", vlan_id
);
1798 bt_vhci_init(bt_new_hci(vlan
));
1801 static struct bt_device_s
*bt_device_add(const char *opt
)
1803 struct bt_scatternet_s
*vlan
;
1805 char *endp
= strstr(opt
, ",vlan=");
1806 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
1809 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
1812 vlan_id
= strtol(endp
+ 6, &endp
, 0);
1814 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
1819 vlan
= qemu_find_bt_vlan(vlan_id
);
1822 fprintf(stderr
, "qemu: warning: adding a slave device to "
1823 "an empty scatternet %i\n", vlan_id
);
1825 if (!strcmp(devname
, "keyboard"))
1826 return bt_keyboard_init(vlan
);
1828 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
1832 static int bt_parse(const char *opt
)
1834 const char *endp
, *p
;
1837 if (strstart(opt
, "hci", &endp
)) {
1838 if (!*endp
|| *endp
== ',') {
1840 if (!strstart(endp
, ",vlan=", 0))
1843 return bt_hci_parse(opt
);
1845 } else if (strstart(opt
, "vhci", &endp
)) {
1846 if (!*endp
|| *endp
== ',') {
1848 if (strstart(endp
, ",vlan=", &p
)) {
1849 vlan
= strtol(p
, (char **) &endp
, 0);
1851 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
1855 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
1864 } else if (strstart(opt
, "device:", &endp
))
1865 return !bt_device_add(endp
);
1867 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
1871 /***********************************************************/
1872 /* QEMU Block devices */
1874 #define HD_ALIAS "index=%d,media=disk"
1875 #define CDROM_ALIAS "index=2,media=cdrom"
1876 #define FD_ALIAS "index=%d,if=floppy"
1877 #define PFLASH_ALIAS "if=pflash"
1878 #define MTD_ALIAS "if=mtd"
1879 #define SD_ALIAS "index=0,if=sd"
1881 QemuOpts
*drive_add(const char *file
, const char *fmt
, ...)
1888 vsnprintf(optstr
, sizeof(optstr
), fmt
, ap
);
1891 opts
= qemu_opts_parse(&qemu_drive_opts
, optstr
, 0);
1893 fprintf(stderr
, "%s: huh? duplicate? (%s)\n",
1894 __FUNCTION__
, optstr
);
1898 qemu_opt_set(opts
, "file", file
);
1902 DriveInfo
*drive_get(BlockInterfaceType type
, int bus
, int unit
)
1906 /* seek interface, bus and unit */
1908 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1909 if (dinfo
->type
== type
&&
1910 dinfo
->bus
== bus
&&
1911 dinfo
->unit
== unit
)
1918 DriveInfo
*drive_get_by_id(const char *id
)
1922 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1923 if (strcmp(id
, dinfo
->id
))
1930 int drive_get_max_bus(BlockInterfaceType type
)
1936 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1937 if(dinfo
->type
== type
&&
1938 dinfo
->bus
> max_bus
)
1939 max_bus
= dinfo
->bus
;
1944 const char *drive_get_serial(BlockDriverState
*bdrv
)
1948 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1949 if (dinfo
->bdrv
== bdrv
)
1950 return dinfo
->serial
;
1956 BlockInterfaceErrorAction
drive_get_on_error(
1957 BlockDriverState
*bdrv
, int is_read
)
1961 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1962 if (dinfo
->bdrv
== bdrv
)
1963 return is_read
? dinfo
->on_read_error
: dinfo
->on_write_error
;
1966 return is_read
? BLOCK_ERR_REPORT
: BLOCK_ERR_STOP_ENOSPC
;
1969 static void bdrv_format_print(void *opaque
, const char *name
)
1971 fprintf(stderr
, " %s", name
);
1974 void drive_uninit(DriveInfo
*dinfo
)
1976 qemu_opts_del(dinfo
->opts
);
1977 bdrv_delete(dinfo
->bdrv
);
1978 QTAILQ_REMOVE(&drives
, dinfo
, next
);
1982 static int parse_block_error_action(const char *buf
, int is_read
)
1984 if (!strcmp(buf
, "ignore")) {
1985 return BLOCK_ERR_IGNORE
;
1986 } else if (!is_read
&& !strcmp(buf
, "enospc")) {
1987 return BLOCK_ERR_STOP_ENOSPC
;
1988 } else if (!strcmp(buf
, "stop")) {
1989 return BLOCK_ERR_STOP_ANY
;
1990 } else if (!strcmp(buf
, "report")) {
1991 return BLOCK_ERR_REPORT
;
1993 fprintf(stderr
, "qemu: '%s' invalid %s error action\n",
1994 buf
, is_read
? "read" : "write");
1999 DriveInfo
*drive_init(QemuOpts
*opts
, void *opaque
,
2003 const char *file
= NULL
;
2006 const char *mediastr
= "";
2007 BlockInterfaceType type
;
2008 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
2009 int bus_id
, unit_id
;
2010 int cyls
, heads
, secs
, translation
;
2011 BlockDriver
*drv
= NULL
;
2012 QEMUMachine
*machine
= opaque
;
2019 int on_read_error
, on_write_error
;
2020 const char *devaddr
;
2026 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2029 if (machine
&& machine
->use_scsi
) {
2031 max_devs
= MAX_SCSI_DEVS
;
2032 pstrcpy(devname
, sizeof(devname
), "scsi");
2035 max_devs
= MAX_IDE_DEVS
;
2036 pstrcpy(devname
, sizeof(devname
), "ide");
2040 /* extract parameters */
2041 bus_id
= qemu_opt_get_number(opts
, "bus", 0);
2042 unit_id
= qemu_opt_get_number(opts
, "unit", -1);
2043 index
= qemu_opt_get_number(opts
, "index", -1);
2045 cyls
= qemu_opt_get_number(opts
, "cyls", 0);
2046 heads
= qemu_opt_get_number(opts
, "heads", 0);
2047 secs
= qemu_opt_get_number(opts
, "secs", 0);
2049 snapshot
= qemu_opt_get_bool(opts
, "snapshot", 0);
2050 ro
= qemu_opt_get_bool(opts
, "readonly", 0);
2052 file
= qemu_opt_get(opts
, "file");
2053 serial
= qemu_opt_get(opts
, "serial");
2055 if ((buf
= qemu_opt_get(opts
, "if")) != NULL
) {
2056 pstrcpy(devname
, sizeof(devname
), buf
);
2057 if (!strcmp(buf
, "ide")) {
2059 max_devs
= MAX_IDE_DEVS
;
2060 } else if (!strcmp(buf
, "scsi")) {
2062 max_devs
= MAX_SCSI_DEVS
;
2063 } else if (!strcmp(buf
, "floppy")) {
2066 } else if (!strcmp(buf
, "pflash")) {
2069 } else if (!strcmp(buf
, "mtd")) {
2072 } else if (!strcmp(buf
, "sd")) {
2075 } else if (!strcmp(buf
, "virtio")) {
2078 } else if (!strcmp(buf
, "xen")) {
2081 } else if (!strcmp(buf
, "none")) {
2085 fprintf(stderr
, "qemu: unsupported bus type '%s'\n", buf
);
2090 if (cyls
|| heads
|| secs
) {
2091 if (cyls
< 1 || (type
== IF_IDE
&& cyls
> 16383)) {
2092 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", buf
);
2095 if (heads
< 1 || (type
== IF_IDE
&& heads
> 16)) {
2096 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", buf
);
2099 if (secs
< 1 || (type
== IF_IDE
&& secs
> 63)) {
2100 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", buf
);
2105 if ((buf
= qemu_opt_get(opts
, "trans")) != NULL
) {
2108 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2112 if (!strcmp(buf
, "none"))
2113 translation
= BIOS_ATA_TRANSLATION_NONE
;
2114 else if (!strcmp(buf
, "lba"))
2115 translation
= BIOS_ATA_TRANSLATION_LBA
;
2116 else if (!strcmp(buf
, "auto"))
2117 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2119 fprintf(stderr
, "qemu: '%s' invalid translation type\n", buf
);
2124 if ((buf
= qemu_opt_get(opts
, "media")) != NULL
) {
2125 if (!strcmp(buf
, "disk")) {
2127 } else if (!strcmp(buf
, "cdrom")) {
2128 if (cyls
|| secs
|| heads
) {
2130 "qemu: '%s' invalid physical CHS format\n", buf
);
2133 media
= MEDIA_CDROM
;
2135 fprintf(stderr
, "qemu: '%s' invalid media\n", buf
);
2140 if ((buf
= qemu_opt_get(opts
, "cache")) != NULL
) {
2141 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2143 else if (!strcmp(buf
, "writethrough"))
2145 else if (!strcmp(buf
, "writeback"))
2148 fprintf(stderr
, "qemu: invalid cache option\n");
2153 #ifdef CONFIG_LINUX_AIO
2154 if ((buf
= qemu_opt_get(opts
, "aio")) != NULL
) {
2155 if (!strcmp(buf
, "threads"))
2157 else if (!strcmp(buf
, "native"))
2160 fprintf(stderr
, "qemu: invalid aio option\n");
2166 if ((buf
= qemu_opt_get(opts
, "format")) != NULL
) {
2167 if (strcmp(buf
, "?") == 0) {
2168 fprintf(stderr
, "qemu: Supported formats:");
2169 bdrv_iterate_format(bdrv_format_print
, NULL
);
2170 fprintf(stderr
, "\n");
2173 drv
= bdrv_find_whitelisted_format(buf
);
2175 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2180 on_write_error
= BLOCK_ERR_STOP_ENOSPC
;
2181 if ((buf
= qemu_opt_get(opts
, "werror")) != NULL
) {
2182 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2183 fprintf(stderr
, "werror is no supported by this format\n");
2187 on_write_error
= parse_block_error_action(buf
, 0);
2188 if (on_write_error
< 0) {
2193 on_read_error
= BLOCK_ERR_REPORT
;
2194 if ((buf
= qemu_opt_get(opts
, "rerror")) != NULL
) {
2195 if (type
!= IF_IDE
&& type
!= IF_VIRTIO
) {
2196 fprintf(stderr
, "rerror is no supported by this format\n");
2200 on_read_error
= parse_block_error_action(buf
, 1);
2201 if (on_read_error
< 0) {
2206 if ((devaddr
= qemu_opt_get(opts
, "addr")) != NULL
) {
2207 if (type
!= IF_VIRTIO
) {
2208 fprintf(stderr
, "addr is not supported\n");
2213 /* compute bus and unit according index */
2216 if (bus_id
!= 0 || unit_id
!= -1) {
2218 "qemu: index cannot be used with bus and unit\n");
2226 unit_id
= index
% max_devs
;
2227 bus_id
= index
/ max_devs
;
2231 /* if user doesn't specify a unit_id,
2232 * try to find the first free
2235 if (unit_id
== -1) {
2237 while (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2239 if (max_devs
&& unit_id
>= max_devs
) {
2240 unit_id
-= max_devs
;
2248 if (max_devs
&& unit_id
>= max_devs
) {
2249 fprintf(stderr
, "qemu: unit %d too big (max is %d)\n",
2250 unit_id
, max_devs
- 1);
2255 * ignore multiple definitions
2258 if (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2265 dinfo
= qemu_mallocz(sizeof(*dinfo
));
2266 if ((buf
= qemu_opts_id(opts
)) != NULL
) {
2267 dinfo
->id
= qemu_strdup(buf
);
2269 /* no id supplied -> create one */
2270 dinfo
->id
= qemu_mallocz(32);
2271 if (type
== IF_IDE
|| type
== IF_SCSI
)
2272 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2274 snprintf(dinfo
->id
, 32, "%s%i%s%i",
2275 devname
, bus_id
, mediastr
, unit_id
);
2277 snprintf(dinfo
->id
, 32, "%s%s%i",
2278 devname
, mediastr
, unit_id
);
2280 dinfo
->bdrv
= bdrv_new(dinfo
->id
);
2281 dinfo
->devaddr
= devaddr
;
2283 dinfo
->bus
= bus_id
;
2284 dinfo
->unit
= unit_id
;
2285 dinfo
->on_read_error
= on_read_error
;
2286 dinfo
->on_write_error
= on_write_error
;
2289 strncpy(dinfo
->serial
, serial
, sizeof(serial
));
2290 QTAILQ_INSERT_TAIL(&drives
, dinfo
, next
);
2300 bdrv_set_geometry_hint(dinfo
->bdrv
, cyls
, heads
, secs
);
2301 bdrv_set_translation_hint(dinfo
->bdrv
, translation
);
2305 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_CDROM
);
2310 /* FIXME: This isn't really a floppy, but it's a reasonable
2313 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_FLOPPY
);
2319 /* add virtio block device */
2320 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
2321 qemu_opt_set(opts
, "driver", "virtio-blk-pci");
2322 qemu_opt_set(opts
, "drive", dinfo
->id
);
2324 qemu_opt_set(opts
, "addr", devaddr
);
2335 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2336 cache
= 2; /* always use write-back with snapshot */
2338 if (cache
== 0) /* no caching */
2339 bdrv_flags
|= BDRV_O_NOCACHE
;
2340 else if (cache
== 2) /* write-back */
2341 bdrv_flags
|= BDRV_O_CACHE_WB
;
2344 bdrv_flags
|= BDRV_O_NATIVE_AIO
;
2346 bdrv_flags
&= ~BDRV_O_NATIVE_AIO
;
2350 if (type
!= IF_SCSI
&& type
!= IF_VIRTIO
&& type
!= IF_FLOPPY
) {
2351 fprintf(stderr
, "qemu: readonly flag not supported for drive with this interface\n");
2356 * cdrom is read-only. Set it now, after above interface checking
2357 * since readonly attribute not explicitly required, so no error.
2359 if (media
== MEDIA_CDROM
) {
2362 bdrv_flags
|= ro
? 0 : BDRV_O_RDWR
;
2364 if (bdrv_open2(dinfo
->bdrv
, file
, bdrv_flags
, drv
) < 0) {
2365 fprintf(stderr
, "qemu: could not open disk image %s: %s\n",
2366 file
, strerror(errno
));
2370 if (bdrv_key_required(dinfo
->bdrv
))
2376 static int drive_init_func(QemuOpts
*opts
, void *opaque
)
2378 QEMUMachine
*machine
= opaque
;
2379 int fatal_error
= 0;
2381 if (drive_init(opts
, machine
, &fatal_error
) == NULL
) {
2388 static int drive_enable_snapshot(QemuOpts
*opts
, void *opaque
)
2390 if (NULL
== qemu_opt_get(opts
, "snapshot")) {
2391 qemu_opt_set(opts
, "snapshot", "on");
2396 void qemu_register_boot_set(QEMUBootSetHandler
*func
, void *opaque
)
2398 boot_set_handler
= func
;
2399 boot_set_opaque
= opaque
;
2402 int qemu_boot_set(const char *boot_devices
)
2404 if (!boot_set_handler
) {
2407 return boot_set_handler(boot_set_opaque
, boot_devices
);
2410 static int parse_bootdevices(char *devices
)
2412 /* We just do some generic consistency checks */
2416 for (p
= devices
; *p
!= '\0'; p
++) {
2417 /* Allowed boot devices are:
2418 * a-b: floppy disk drives
2419 * c-f: IDE disk drives
2420 * g-m: machine implementation dependant drives
2421 * n-p: network devices
2422 * It's up to each machine implementation to check if the given boot
2423 * devices match the actual hardware implementation and firmware
2426 if (*p
< 'a' || *p
> 'p') {
2427 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
2430 if (bitmap
& (1 << (*p
- 'a'))) {
2431 fprintf(stderr
, "Boot device '%c' was given twice\n", *p
);
2434 bitmap
|= 1 << (*p
- 'a');
2439 static void restore_boot_devices(void *opaque
)
2441 char *standard_boot_devices
= opaque
;
2443 qemu_boot_set(standard_boot_devices
);
2445 qemu_unregister_reset(restore_boot_devices
, standard_boot_devices
);
2446 qemu_free(standard_boot_devices
);
2449 static void numa_add(const char *optarg
)
2453 unsigned long long value
, endvalue
;
2456 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2457 if (!strcmp(option
, "node")) {
2458 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2459 nodenr
= nb_numa_nodes
;
2461 nodenr
= strtoull(option
, NULL
, 10);
2464 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2465 node_mem
[nodenr
] = 0;
2467 value
= strtoull(option
, &endptr
, 0);
2469 case 0: case 'M': case 'm':
2476 node_mem
[nodenr
] = value
;
2478 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2479 node_cpumask
[nodenr
] = 0;
2481 value
= strtoull(option
, &endptr
, 10);
2484 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2486 if (*endptr
== '-') {
2487 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2488 if (endvalue
>= 63) {
2491 "only 63 CPUs in NUMA mode supported.\n");
2493 value
= (2ULL << endvalue
) - (1ULL << value
);
2495 value
= 1ULL << value
;
2498 node_cpumask
[nodenr
] = value
;
2505 static void smp_parse(const char *optarg
)
2507 int smp
, sockets
= 0, threads
= 0, cores
= 0;
2511 smp
= strtoul(optarg
, &endptr
, 10);
2512 if (endptr
!= optarg
) {
2513 if (*endptr
== ',') {
2517 if (get_param_value(option
, 128, "sockets", endptr
) != 0)
2518 sockets
= strtoull(option
, NULL
, 10);
2519 if (get_param_value(option
, 128, "cores", endptr
) != 0)
2520 cores
= strtoull(option
, NULL
, 10);
2521 if (get_param_value(option
, 128, "threads", endptr
) != 0)
2522 threads
= strtoull(option
, NULL
, 10);
2523 if (get_param_value(option
, 128, "maxcpus", endptr
) != 0)
2524 max_cpus
= strtoull(option
, NULL
, 10);
2526 /* compute missing values, prefer sockets over cores over threads */
2527 if (smp
== 0 || sockets
== 0) {
2528 sockets
= sockets
> 0 ? sockets
: 1;
2529 cores
= cores
> 0 ? cores
: 1;
2530 threads
= threads
> 0 ? threads
: 1;
2532 smp
= cores
* threads
* sockets
;
2536 threads
= threads
> 0 ? threads
: 1;
2537 cores
= smp
/ (sockets
* threads
);
2540 threads
= smp
/ (cores
* sockets
);
2545 smp_cores
= cores
> 0 ? cores
: 1;
2546 smp_threads
= threads
> 0 ? threads
: 1;
2548 max_cpus
= smp_cpus
;
2551 /***********************************************************/
2554 static int usb_device_add(const char *devname
, int is_hotplug
)
2557 USBDevice
*dev
= NULL
;
2562 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2563 dev
= usbdevice_create(devname
);
2567 /* the other ones */
2568 if (strstart(devname
, "host:", &p
)) {
2569 dev
= usb_host_device_open(p
);
2570 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2571 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2572 bt_new_hci(qemu_find_bt_vlan(0)));
2583 static int usb_device_del(const char *devname
)
2588 if (strstart(devname
, "host:", &p
))
2589 return usb_host_device_close(p
);
2594 p
= strchr(devname
, '.');
2597 bus_num
= strtoul(devname
, NULL
, 0);
2598 addr
= strtoul(p
+ 1, NULL
, 0);
2600 return usb_device_delete_addr(bus_num
, addr
);
2603 static int usb_parse(const char *cmdline
)
2606 r
= usb_device_add(cmdline
, 0);
2608 fprintf(stderr
, "qemu: could not add USB device '%s'\n", cmdline
);
2613 void do_usb_add(Monitor
*mon
, const QDict
*qdict
)
2615 const char *devname
= qdict_get_str(qdict
, "devname");
2616 if (usb_device_add(devname
, 1) < 0) {
2617 error_report("could not add USB device '%s'", devname
);
2621 void do_usb_del(Monitor
*mon
, const QDict
*qdict
)
2623 const char *devname
= qdict_get_str(qdict
, "devname");
2624 if (usb_device_del(devname
) < 0) {
2625 error_report("could not delete USB device '%s'", devname
);
2629 /***********************************************************/
2630 /* PCMCIA/Cardbus */
2632 static struct pcmcia_socket_entry_s
{
2633 PCMCIASocket
*socket
;
2634 struct pcmcia_socket_entry_s
*next
;
2635 } *pcmcia_sockets
= 0;
2637 void pcmcia_socket_register(PCMCIASocket
*socket
)
2639 struct pcmcia_socket_entry_s
*entry
;
2641 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2642 entry
->socket
= socket
;
2643 entry
->next
= pcmcia_sockets
;
2644 pcmcia_sockets
= entry
;
2647 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2649 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2651 ptr
= &pcmcia_sockets
;
2652 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2653 if (entry
->socket
== socket
) {
2659 void pcmcia_info(Monitor
*mon
)
2661 struct pcmcia_socket_entry_s
*iter
;
2663 if (!pcmcia_sockets
)
2664 monitor_printf(mon
, "No PCMCIA sockets\n");
2666 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2667 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2668 iter
->socket
->attached
? iter
->socket
->card_string
:
2672 /***********************************************************/
2675 typedef struct IOHandlerRecord
{
2677 IOCanRWHandler
*fd_read_poll
;
2679 IOHandler
*fd_write
;
2682 /* temporary data */
2684 struct IOHandlerRecord
*next
;
2687 static IOHandlerRecord
*first_io_handler
;
2689 /* XXX: fd_read_poll should be suppressed, but an API change is
2690 necessary in the character devices to suppress fd_can_read(). */
2691 int qemu_set_fd_handler2(int fd
,
2692 IOCanRWHandler
*fd_read_poll
,
2694 IOHandler
*fd_write
,
2697 IOHandlerRecord
**pioh
, *ioh
;
2699 if (!fd_read
&& !fd_write
) {
2700 pioh
= &first_io_handler
;
2705 if (ioh
->fd
== fd
) {
2712 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
2716 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
2717 ioh
->next
= first_io_handler
;
2718 first_io_handler
= ioh
;
2721 ioh
->fd_read_poll
= fd_read_poll
;
2722 ioh
->fd_read
= fd_read
;
2723 ioh
->fd_write
= fd_write
;
2724 ioh
->opaque
= opaque
;
2730 int qemu_set_fd_handler(int fd
,
2732 IOHandler
*fd_write
,
2735 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
2739 /***********************************************************/
2740 /* Polling handling */
2742 typedef struct PollingEntry
{
2745 struct PollingEntry
*next
;
2748 static PollingEntry
*first_polling_entry
;
2750 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
2752 PollingEntry
**ppe
, *pe
;
2753 pe
= qemu_mallocz(sizeof(PollingEntry
));
2755 pe
->opaque
= opaque
;
2756 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
2761 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
2763 PollingEntry
**ppe
, *pe
;
2764 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
2766 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
2774 /***********************************************************/
2775 /* Wait objects support */
2776 typedef struct WaitObjects
{
2778 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
2779 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
2780 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
2783 static WaitObjects wait_objects
= {0};
2785 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2787 WaitObjects
*w
= &wait_objects
;
2789 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
2791 w
->events
[w
->num
] = handle
;
2792 w
->func
[w
->num
] = func
;
2793 w
->opaque
[w
->num
] = opaque
;
2798 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2801 WaitObjects
*w
= &wait_objects
;
2804 for (i
= 0; i
< w
->num
; i
++) {
2805 if (w
->events
[i
] == handle
)
2808 w
->events
[i
] = w
->events
[i
+ 1];
2809 w
->func
[i
] = w
->func
[i
+ 1];
2810 w
->opaque
[i
] = w
->opaque
[i
+ 1];
2818 /***********************************************************/
2819 /* ram save/restore */
2821 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2822 #define RAM_SAVE_FLAG_COMPRESS 0x02
2823 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2824 #define RAM_SAVE_FLAG_PAGE 0x08
2825 #define RAM_SAVE_FLAG_EOS 0x10
2827 static int is_dup_page(uint8_t *page
, uint8_t ch
)
2829 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
2830 uint32_t *array
= (uint32_t *)page
;
2833 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
2834 if (array
[i
] != val
)
2841 static int ram_save_block(QEMUFile
*f
)
2843 static ram_addr_t current_addr
= 0;
2844 ram_addr_t saved_addr
= current_addr
;
2845 ram_addr_t addr
= 0;
2848 while (addr
< last_ram_offset
) {
2849 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
2852 cpu_physical_memory_reset_dirty(current_addr
,
2853 current_addr
+ TARGET_PAGE_SIZE
,
2854 MIGRATION_DIRTY_FLAG
);
2856 p
= qemu_get_ram_ptr(current_addr
);
2858 if (is_dup_page(p
, *p
)) {
2859 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
2860 qemu_put_byte(f
, *p
);
2862 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
2863 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
2869 addr
+= TARGET_PAGE_SIZE
;
2870 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
2876 static uint64_t bytes_transferred
;
2878 static ram_addr_t
ram_save_remaining(void)
2881 ram_addr_t count
= 0;
2883 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2884 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2891 uint64_t ram_bytes_remaining(void)
2893 return ram_save_remaining() * TARGET_PAGE_SIZE
;
2896 uint64_t ram_bytes_transferred(void)
2898 return bytes_transferred
;
2901 uint64_t ram_bytes_total(void)
2903 return last_ram_offset
;
2906 static int ram_save_live(Monitor
*mon
, QEMUFile
*f
, int stage
, void *opaque
)
2909 uint64_t bytes_transferred_last
;
2911 uint64_t expected_time
= 0;
2914 cpu_physical_memory_set_dirty_tracking(0);
2918 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX
) != 0) {
2919 qemu_file_set_error(f
);
2924 bytes_transferred
= 0;
2926 /* Make sure all dirty bits are set */
2927 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2928 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2929 cpu_physical_memory_set_dirty(addr
);
2932 /* Enable dirty memory tracking */
2933 cpu_physical_memory_set_dirty_tracking(1);
2935 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
2938 bytes_transferred_last
= bytes_transferred
;
2939 bwidth
= qemu_get_clock_ns(rt_clock
);
2941 while (!qemu_file_rate_limit(f
)) {
2944 ret
= ram_save_block(f
);
2945 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
2946 if (ret
== 0) /* no more blocks */
2950 bwidth
= qemu_get_clock_ns(rt_clock
) - bwidth
;
2951 bwidth
= (bytes_transferred
- bytes_transferred_last
) / bwidth
;
2953 /* if we haven't transferred anything this round, force expected_time to a
2954 * a very high value, but without crashing */
2958 /* try transferring iterative blocks of memory */
2960 /* flush all remaining blocks regardless of rate limiting */
2961 while (ram_save_block(f
) != 0) {
2962 bytes_transferred
+= TARGET_PAGE_SIZE
;
2964 cpu_physical_memory_set_dirty_tracking(0);
2967 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
2969 expected_time
= ram_save_remaining() * TARGET_PAGE_SIZE
/ bwidth
;
2971 return (stage
== 2) && (expected_time
<= migrate_max_downtime());
2974 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
2979 if (version_id
!= 3)
2983 addr
= qemu_get_be64(f
);
2985 flags
= addr
& ~TARGET_PAGE_MASK
;
2986 addr
&= TARGET_PAGE_MASK
;
2988 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
2989 if (addr
!= last_ram_offset
)
2993 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
2994 uint8_t ch
= qemu_get_byte(f
);
2995 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
2998 (!kvm_enabled() || kvm_has_sync_mmu())) {
2999 madvise(qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
, MADV_DONTNEED
);
3002 } else if (flags
& RAM_SAVE_FLAG_PAGE
) {
3003 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
3005 if (qemu_file_has_error(f
)) {
3008 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
3013 void qemu_service_io(void)
3015 qemu_notify_event();
3018 /***********************************************************/
3019 /* machine registration */
3021 static QEMUMachine
*first_machine
= NULL
;
3022 QEMUMachine
*current_machine
= NULL
;
3024 int qemu_register_machine(QEMUMachine
*m
)
3027 pm
= &first_machine
;
3035 static QEMUMachine
*find_machine(const char *name
)
3039 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3040 if (!strcmp(m
->name
, name
))
3042 if (m
->alias
&& !strcmp(m
->alias
, name
))
3048 static QEMUMachine
*find_default_machine(void)
3052 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3053 if (m
->is_default
) {
3060 /***********************************************************/
3061 /* main execution loop */
3063 static void gui_update(void *opaque
)
3065 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3066 DisplayState
*ds
= opaque
;
3067 DisplayChangeListener
*dcl
= ds
->listeners
;
3069 qemu_flush_coalesced_mmio_buffer();
3072 while (dcl
!= NULL
) {
3073 if (dcl
->gui_timer_interval
&&
3074 dcl
->gui_timer_interval
< interval
)
3075 interval
= dcl
->gui_timer_interval
;
3078 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3081 static void nographic_update(void *opaque
)
3083 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3085 qemu_flush_coalesced_mmio_buffer();
3086 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3089 void cpu_synchronize_all_states(void)
3093 for (cpu
= first_cpu
; cpu
; cpu
= cpu
->next_cpu
) {
3094 cpu_synchronize_state(cpu
);
3098 void cpu_synchronize_all_post_reset(void)
3102 for (cpu
= first_cpu
; cpu
; cpu
= cpu
->next_cpu
) {
3103 cpu_synchronize_post_reset(cpu
);
3107 void cpu_synchronize_all_post_init(void)
3111 for (cpu
= first_cpu
; cpu
; cpu
= cpu
->next_cpu
) {
3112 cpu_synchronize_post_init(cpu
);
3116 struct vm_change_state_entry
{
3117 VMChangeStateHandler
*cb
;
3119 QLIST_ENTRY (vm_change_state_entry
) entries
;
3122 static QLIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3124 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3127 VMChangeStateEntry
*e
;
3129 e
= qemu_mallocz(sizeof (*e
));
3133 QLIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3137 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3139 QLIST_REMOVE (e
, entries
);
3143 static void vm_state_notify(int running
, int reason
)
3145 VMChangeStateEntry
*e
;
3147 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3148 e
->cb(e
->opaque
, running
, reason
);
3152 static void resume_all_vcpus(void);
3153 static void pause_all_vcpus(void);
3160 vm_state_notify(1, 0);
3165 /* reset/shutdown handler */
3167 typedef struct QEMUResetEntry
{
3168 QTAILQ_ENTRY(QEMUResetEntry
) entry
;
3169 QEMUResetHandler
*func
;
3173 static QTAILQ_HEAD(reset_handlers
, QEMUResetEntry
) reset_handlers
=
3174 QTAILQ_HEAD_INITIALIZER(reset_handlers
);
3175 static int reset_requested
;
3176 static int shutdown_requested
;
3177 static int powerdown_requested
;
3178 static int debug_requested
;
3179 static int vmstop_requested
;
3181 int qemu_shutdown_requested(void)
3183 int r
= shutdown_requested
;
3184 shutdown_requested
= 0;
3188 int qemu_reset_requested(void)
3190 int r
= reset_requested
;
3191 reset_requested
= 0;
3195 int qemu_powerdown_requested(void)
3197 int r
= powerdown_requested
;
3198 powerdown_requested
= 0;
3202 static int qemu_debug_requested(void)
3204 int r
= debug_requested
;
3205 debug_requested
= 0;
3209 static int qemu_vmstop_requested(void)
3211 int r
= vmstop_requested
;
3212 vmstop_requested
= 0;
3216 static void do_vm_stop(int reason
)
3219 cpu_disable_ticks();
3222 vm_state_notify(0, reason
);
3223 monitor_protocol_event(QEVENT_STOP
, NULL
);
3227 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3229 QEMUResetEntry
*re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3232 re
->opaque
= opaque
;
3233 QTAILQ_INSERT_TAIL(&reset_handlers
, re
, entry
);
3236 void qemu_unregister_reset(QEMUResetHandler
*func
, void *opaque
)
3240 QTAILQ_FOREACH(re
, &reset_handlers
, entry
) {
3241 if (re
->func
== func
&& re
->opaque
== opaque
) {
3242 QTAILQ_REMOVE(&reset_handlers
, re
, entry
);
3249 void qemu_system_reset(void)
3251 QEMUResetEntry
*re
, *nre
;
3253 /* reset all devices */
3254 QTAILQ_FOREACH_SAFE(re
, &reset_handlers
, entry
, nre
) {
3255 re
->func(re
->opaque
);
3257 monitor_protocol_event(QEVENT_RESET
, NULL
);
3258 cpu_synchronize_all_post_reset();
3261 void qemu_system_reset_request(void)
3264 shutdown_requested
= 1;
3266 reset_requested
= 1;
3268 qemu_notify_event();
3271 void qemu_system_shutdown_request(void)
3273 shutdown_requested
= 1;
3274 qemu_notify_event();
3277 void qemu_system_powerdown_request(void)
3279 powerdown_requested
= 1;
3280 qemu_notify_event();
3283 #ifdef CONFIG_IOTHREAD
3284 static void qemu_system_vmstop_request(int reason
)
3286 vmstop_requested
= reason
;
3287 qemu_notify_event();
3292 static int io_thread_fd
= -1;
3294 static void qemu_event_increment(void)
3296 /* Write 8 bytes to be compatible with eventfd. */
3297 static uint64_t val
= 1;
3300 if (io_thread_fd
== -1)
3304 ret
= write(io_thread_fd
, &val
, sizeof(val
));
3305 } while (ret
< 0 && errno
== EINTR
);
3307 /* EAGAIN is fine, a read must be pending. */
3308 if (ret
< 0 && errno
!= EAGAIN
) {
3309 fprintf(stderr
, "qemu_event_increment: write() filed: %s\n",
3315 static void qemu_event_read(void *opaque
)
3317 int fd
= (unsigned long)opaque
;
3321 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
3323 len
= read(fd
, buffer
, sizeof(buffer
));
3324 } while ((len
== -1 && errno
== EINTR
) || len
== sizeof(buffer
));
3327 static int qemu_event_init(void)
3332 err
= qemu_eventfd(fds
);
3336 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3340 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3344 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3345 (void *)(unsigned long)fds
[0]);
3347 io_thread_fd
= fds
[1];
3356 HANDLE qemu_event_handle
;
3358 static void dummy_event_handler(void *opaque
)
3362 static int qemu_event_init(void)
3364 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3365 if (!qemu_event_handle
) {
3366 fprintf(stderr
, "Failed CreateEvent: %ld\n", GetLastError());
3369 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3373 static void qemu_event_increment(void)
3375 if (!SetEvent(qemu_event_handle
)) {
3376 fprintf(stderr
, "qemu_event_increment: SetEvent failed: %ld\n",
3383 static int cpu_can_run(CPUState
*env
)
3394 #ifndef CONFIG_IOTHREAD
3395 static int qemu_init_main_loop(void)
3397 return qemu_event_init();
3400 void qemu_init_vcpu(void *_env
)
3402 CPUState
*env
= _env
;
3404 env
->nr_cores
= smp_cores
;
3405 env
->nr_threads
= smp_threads
;
3411 int qemu_cpu_self(void *env
)
3416 static void resume_all_vcpus(void)
3420 static void pause_all_vcpus(void)
3424 void qemu_cpu_kick(void *env
)
3429 void qemu_notify_event(void)
3431 CPUState
*env
= cpu_single_env
;
3433 qemu_event_increment ();
3437 if (next_cpu
&& env
!= next_cpu
) {
3442 void qemu_mutex_lock_iothread(void) {}
3443 void qemu_mutex_unlock_iothread(void) {}
3445 void vm_stop(int reason
)
3450 #else /* CONFIG_IOTHREAD */
3452 #include "qemu-thread.h"
3454 QemuMutex qemu_global_mutex
;
3455 static QemuMutex qemu_fair_mutex
;
3457 static QemuThread io_thread
;
3459 static QemuThread
*tcg_cpu_thread
;
3460 static QemuCond
*tcg_halt_cond
;
3462 static int qemu_system_ready
;
3464 static QemuCond qemu_cpu_cond
;
3466 static QemuCond qemu_system_cond
;
3467 static QemuCond qemu_pause_cond
;
3469 static void tcg_block_io_signals(void);
3470 static void kvm_block_io_signals(CPUState
*env
);
3471 static void unblock_io_signals(void);
3472 static int tcg_has_work(void);
3473 static int cpu_has_work(CPUState
*env
);
3475 static int qemu_init_main_loop(void)
3479 ret
= qemu_event_init();
3483 qemu_cond_init(&qemu_pause_cond
);
3484 qemu_mutex_init(&qemu_fair_mutex
);
3485 qemu_mutex_init(&qemu_global_mutex
);
3486 qemu_mutex_lock(&qemu_global_mutex
);
3488 unblock_io_signals();
3489 qemu_thread_self(&io_thread
);
3494 static void qemu_wait_io_event_common(CPUState
*env
)
3499 qemu_cond_signal(&qemu_pause_cond
);
3503 static void qemu_wait_io_event(CPUState
*env
)
3505 while (!tcg_has_work())
3506 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3508 qemu_mutex_unlock(&qemu_global_mutex
);
3511 * Users of qemu_global_mutex can be starved, having no chance
3512 * to acquire it since this path will get to it first.
3513 * So use another lock to provide fairness.
3515 qemu_mutex_lock(&qemu_fair_mutex
);
3516 qemu_mutex_unlock(&qemu_fair_mutex
);
3518 qemu_mutex_lock(&qemu_global_mutex
);
3519 qemu_wait_io_event_common(env
);
3522 static void qemu_kvm_eat_signal(CPUState
*env
, int timeout
)
3529 ts
.tv_sec
= timeout
/ 1000;
3530 ts
.tv_nsec
= (timeout
% 1000) * 1000000;
3532 sigemptyset(&waitset
);
3533 sigaddset(&waitset
, SIG_IPI
);
3535 qemu_mutex_unlock(&qemu_global_mutex
);
3536 r
= sigtimedwait(&waitset
, &siginfo
, &ts
);
3538 qemu_mutex_lock(&qemu_global_mutex
);
3540 if (r
== -1 && !(e
== EAGAIN
|| e
== EINTR
)) {
3541 fprintf(stderr
, "sigtimedwait: %s\n", strerror(e
));
3546 static void qemu_kvm_wait_io_event(CPUState
*env
)
3548 while (!cpu_has_work(env
))
3549 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3551 qemu_kvm_eat_signal(env
, 0);
3552 qemu_wait_io_event_common(env
);
3555 static int qemu_cpu_exec(CPUState
*env
);
3557 static void *kvm_cpu_thread_fn(void *arg
)
3559 CPUState
*env
= arg
;
3561 qemu_thread_self(env
->thread
);
3565 kvm_block_io_signals(env
);
3567 /* signal CPU creation */
3568 qemu_mutex_lock(&qemu_global_mutex
);
3570 qemu_cond_signal(&qemu_cpu_cond
);
3572 /* and wait for machine initialization */
3573 while (!qemu_system_ready
)
3574 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3577 if (cpu_can_run(env
))
3579 qemu_kvm_wait_io_event(env
);
3585 static void tcg_cpu_exec(void);
3587 static void *tcg_cpu_thread_fn(void *arg
)
3589 CPUState
*env
= arg
;
3591 tcg_block_io_signals();
3592 qemu_thread_self(env
->thread
);
3594 /* signal CPU creation */
3595 qemu_mutex_lock(&qemu_global_mutex
);
3596 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
3598 qemu_cond_signal(&qemu_cpu_cond
);
3600 /* and wait for machine initialization */
3601 while (!qemu_system_ready
)
3602 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3606 qemu_wait_io_event(cur_cpu
);
3612 void qemu_cpu_kick(void *_env
)
3614 CPUState
*env
= _env
;
3615 qemu_cond_broadcast(env
->halt_cond
);
3617 qemu_thread_signal(env
->thread
, SIG_IPI
);
3620 int qemu_cpu_self(void *_env
)
3622 CPUState
*env
= _env
;
3625 qemu_thread_self(&this);
3627 return qemu_thread_equal(&this, env
->thread
);
3630 static void cpu_signal(int sig
)
3633 cpu_exit(cpu_single_env
);
3636 static void tcg_block_io_signals(void)
3639 struct sigaction sigact
;
3642 sigaddset(&set
, SIGUSR2
);
3643 sigaddset(&set
, SIGIO
);
3644 sigaddset(&set
, SIGALRM
);
3645 sigaddset(&set
, SIGCHLD
);
3646 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3649 sigaddset(&set
, SIG_IPI
);
3650 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3652 memset(&sigact
, 0, sizeof(sigact
));
3653 sigact
.sa_handler
= cpu_signal
;
3654 sigaction(SIG_IPI
, &sigact
, NULL
);
3657 static void dummy_signal(int sig
)
3661 static void kvm_block_io_signals(CPUState
*env
)
3665 struct sigaction sigact
;
3668 sigaddset(&set
, SIGUSR2
);
3669 sigaddset(&set
, SIGIO
);
3670 sigaddset(&set
, SIGALRM
);
3671 sigaddset(&set
, SIGCHLD
);
3672 sigaddset(&set
, SIG_IPI
);
3673 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3675 pthread_sigmask(SIG_BLOCK
, NULL
, &set
);
3676 sigdelset(&set
, SIG_IPI
);
3678 memset(&sigact
, 0, sizeof(sigact
));
3679 sigact
.sa_handler
= dummy_signal
;
3680 sigaction(SIG_IPI
, &sigact
, NULL
);
3682 r
= kvm_set_signal_mask(env
, &set
);
3684 fprintf(stderr
, "kvm_set_signal_mask: %s\n", strerror(r
));
3689 static void unblock_io_signals(void)
3694 sigaddset(&set
, SIGUSR2
);
3695 sigaddset(&set
, SIGIO
);
3696 sigaddset(&set
, SIGALRM
);
3697 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3700 sigaddset(&set
, SIG_IPI
);
3701 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3704 static void qemu_signal_lock(unsigned int msecs
)
3706 qemu_mutex_lock(&qemu_fair_mutex
);
3708 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
3709 qemu_thread_signal(tcg_cpu_thread
, SIG_IPI
);
3710 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
3713 qemu_mutex_unlock(&qemu_fair_mutex
);
3716 void qemu_mutex_lock_iothread(void)
3718 if (kvm_enabled()) {
3719 qemu_mutex_lock(&qemu_fair_mutex
);
3720 qemu_mutex_lock(&qemu_global_mutex
);
3721 qemu_mutex_unlock(&qemu_fair_mutex
);
3723 qemu_signal_lock(100);
3726 void qemu_mutex_unlock_iothread(void)
3728 qemu_mutex_unlock(&qemu_global_mutex
);
3731 static int all_vcpus_paused(void)
3733 CPUState
*penv
= first_cpu
;
3738 penv
= (CPUState
*)penv
->next_cpu
;
3744 static void pause_all_vcpus(void)
3746 CPUState
*penv
= first_cpu
;
3750 qemu_thread_signal(penv
->thread
, SIG_IPI
);
3751 qemu_cpu_kick(penv
);
3752 penv
= (CPUState
*)penv
->next_cpu
;
3755 while (!all_vcpus_paused()) {
3756 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
3759 qemu_thread_signal(penv
->thread
, SIG_IPI
);
3760 penv
= (CPUState
*)penv
->next_cpu
;
3765 static void resume_all_vcpus(void)
3767 CPUState
*penv
= first_cpu
;
3772 qemu_thread_signal(penv
->thread
, SIG_IPI
);
3773 qemu_cpu_kick(penv
);
3774 penv
= (CPUState
*)penv
->next_cpu
;
3778 static void tcg_init_vcpu(void *_env
)
3780 CPUState
*env
= _env
;
3781 /* share a single thread for all cpus with TCG */
3782 if (!tcg_cpu_thread
) {
3783 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3784 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3785 qemu_cond_init(env
->halt_cond
);
3786 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
3787 while (env
->created
== 0)
3788 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3789 tcg_cpu_thread
= env
->thread
;
3790 tcg_halt_cond
= env
->halt_cond
;
3792 env
->thread
= tcg_cpu_thread
;
3793 env
->halt_cond
= tcg_halt_cond
;
3797 static void kvm_start_vcpu(CPUState
*env
)
3799 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3800 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3801 qemu_cond_init(env
->halt_cond
);
3802 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
3803 while (env
->created
== 0)
3804 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3807 void qemu_init_vcpu(void *_env
)
3809 CPUState
*env
= _env
;
3811 env
->nr_cores
= smp_cores
;
3812 env
->nr_threads
= smp_threads
;
3814 kvm_start_vcpu(env
);
3819 void qemu_notify_event(void)
3821 qemu_event_increment();
3824 void vm_stop(int reason
)
3827 qemu_thread_self(&me
);
3829 if (!qemu_thread_equal(&me
, &io_thread
)) {
3830 qemu_system_vmstop_request(reason
);
3832 * FIXME: should not return to device code in case
3833 * vm_stop() has been requested.
3835 if (cpu_single_env
) {
3836 cpu_exit(cpu_single_env
);
3837 cpu_single_env
->stop
= 1;
3848 static void host_main_loop_wait(int *timeout
)
3854 /* XXX: need to suppress polling by better using win32 events */
3856 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
3857 ret
|= pe
->func(pe
->opaque
);
3861 WaitObjects
*w
= &wait_objects
;
3863 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
3864 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
3865 if (w
->func
[ret
- WAIT_OBJECT_0
])
3866 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
3868 /* Check for additional signaled events */
3869 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
3871 /* Check if event is signaled */
3872 ret2
= WaitForSingleObject(w
->events
[i
], 0);
3873 if(ret2
== WAIT_OBJECT_0
) {
3875 w
->func
[i
](w
->opaque
[i
]);
3876 } else if (ret2
== WAIT_TIMEOUT
) {
3878 err
= GetLastError();
3879 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
3882 } else if (ret
== WAIT_TIMEOUT
) {
3884 err
= GetLastError();
3885 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
3892 static void host_main_loop_wait(int *timeout
)
3897 void main_loop_wait(int timeout
)
3899 IOHandlerRecord
*ioh
;
3900 fd_set rfds
, wfds
, xfds
;
3904 qemu_bh_update_timeout(&timeout
);
3906 host_main_loop_wait(&timeout
);
3908 /* poll any events */
3909 /* XXX: separate device handlers from system ones */
3914 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3918 (!ioh
->fd_read_poll
||
3919 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
3920 FD_SET(ioh
->fd
, &rfds
);
3924 if (ioh
->fd_write
) {
3925 FD_SET(ioh
->fd
, &wfds
);
3931 tv
.tv_sec
= timeout
/ 1000;
3932 tv
.tv_usec
= (timeout
% 1000) * 1000;
3934 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
3936 qemu_mutex_unlock_iothread();
3937 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
3938 qemu_mutex_lock_iothread();
3940 IOHandlerRecord
**pioh
;
3942 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3943 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
3944 ioh
->fd_read(ioh
->opaque
);
3946 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
3947 ioh
->fd_write(ioh
->opaque
);
3951 /* remove deleted IO handlers */
3952 pioh
= &first_io_handler
;
3963 slirp_select_poll(&rfds
, &wfds
, &xfds
, (ret
< 0));
3965 qemu_run_all_timers();
3967 /* Check bottom-halves last in case any of the earlier events triggered
3973 static int qemu_cpu_exec(CPUState
*env
)
3976 #ifdef CONFIG_PROFILER
3980 #ifdef CONFIG_PROFILER
3981 ti
= profile_getclock();
3986 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
3987 env
->icount_decr
.u16
.low
= 0;
3988 env
->icount_extra
= 0;
3989 count
= qemu_icount_round (qemu_next_deadline());
3990 qemu_icount
+= count
;
3991 decr
= (count
> 0xffff) ? 0xffff : count
;
3993 env
->icount_decr
.u16
.low
= decr
;
3994 env
->icount_extra
= count
;
3996 ret
= cpu_exec(env
);
3997 #ifdef CONFIG_PROFILER
3998 qemu_time
+= profile_getclock() - ti
;
4001 /* Fold pending instructions back into the
4002 instruction counter, and clear the interrupt flag. */
4003 qemu_icount
-= (env
->icount_decr
.u16
.low
4004 + env
->icount_extra
);
4005 env
->icount_decr
.u32
= 0;
4006 env
->icount_extra
= 0;
4011 static void tcg_cpu_exec(void)
4015 if (next_cpu
== NULL
)
4016 next_cpu
= first_cpu
;
4017 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
4018 CPUState
*env
= cur_cpu
= next_cpu
;
4020 qemu_clock_enable(vm_clock
,
4021 (cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
) == 0);
4023 if (qemu_alarm_pending())
4025 if (cpu_can_run(env
))
4026 ret
= qemu_cpu_exec(env
);
4030 if (ret
== EXCP_DEBUG
) {
4031 gdb_set_stop_cpu(env
);
4032 debug_requested
= 1;
4038 static int cpu_has_work(CPUState
*env
)
4046 if (qemu_cpu_has_work(env
))
4051 static int tcg_has_work(void)
4055 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
4056 if (cpu_has_work(env
))
4061 static int qemu_calculate_timeout(void)
4063 #ifndef CONFIG_IOTHREAD
4068 else if (tcg_has_work())
4071 /* XXX: use timeout computed from timers */
4074 /* Advance virtual time to the next event. */
4075 delta
= qemu_icount_delta();
4077 /* If virtual time is ahead of real time then just
4079 timeout
= (delta
+ 999999) / 1000000;
4081 /* Wait for either IO to occur or the next
4083 add
= qemu_next_deadline();
4084 /* We advance the timer before checking for IO.
4085 Limit the amount we advance so that early IO
4086 activity won't get the guest too far ahead. */
4090 qemu_icount
+= qemu_icount_round (add
);
4091 timeout
= delta
/ 1000000;
4098 #else /* CONFIG_IOTHREAD */
4103 static int vm_can_run(void)
4105 if (powerdown_requested
)
4107 if (reset_requested
)
4109 if (shutdown_requested
)
4111 if (debug_requested
)
4116 qemu_irq qemu_system_powerdown
;
4118 static void main_loop(void)
4122 #ifdef CONFIG_IOTHREAD
4123 qemu_system_ready
= 1;
4124 qemu_cond_broadcast(&qemu_system_cond
);
4129 #ifdef CONFIG_PROFILER
4132 #ifndef CONFIG_IOTHREAD
4135 #ifdef CONFIG_PROFILER
4136 ti
= profile_getclock();
4138 main_loop_wait(qemu_calculate_timeout());
4139 #ifdef CONFIG_PROFILER
4140 dev_time
+= profile_getclock() - ti
;
4142 } while (vm_can_run());
4144 if (qemu_debug_requested()) {
4145 vm_stop(EXCP_DEBUG
);
4147 if (qemu_shutdown_requested()) {
4148 monitor_protocol_event(QEVENT_SHUTDOWN
, NULL
);
4155 if (qemu_reset_requested()) {
4157 qemu_system_reset();
4160 if (qemu_powerdown_requested()) {
4161 monitor_protocol_event(QEVENT_POWERDOWN
, NULL
);
4162 qemu_irq_raise(qemu_system_powerdown
);
4164 if ((r
= qemu_vmstop_requested())) {
4171 static void version(void)
4173 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4176 static void help(int exitcode
)
4178 const char *options_help
=
4179 #define DEF(option, opt_arg, opt_enum, opt_help) \
4181 #define DEFHEADING(text) stringify(text) "\n"
4182 #include "qemu-options.h"
4188 printf("usage: %s [options] [disk_image]\n"
4190 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4193 "During emulation, the following keys are useful:\n"
4194 "ctrl-alt-f toggle full screen\n"
4195 "ctrl-alt-n switch to virtual console 'n'\n"
4196 "ctrl-alt toggle mouse and keyboard grab\n"
4198 "When using -nographic, press 'ctrl-a h' to get some help.\n",
4204 #define HAS_ARG 0x0001
4207 #define DEF(option, opt_arg, opt_enum, opt_help) \
4209 #define DEFHEADING(text)
4210 #include "qemu-options.h"
4216 typedef struct QEMUOption
{
4222 static const QEMUOption qemu_options
[] = {
4223 { "h", 0, QEMU_OPTION_h
},
4224 #define DEF(option, opt_arg, opt_enum, opt_help) \
4225 { option, opt_arg, opt_enum },
4226 #define DEFHEADING(text)
4227 #include "qemu-options.h"
4235 struct soundhw soundhw
[] = {
4236 #ifdef HAS_AUDIO_CHOICE
4237 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4243 { .init_isa
= pcspk_audio_init
}
4250 "Creative Sound Blaster 16",
4253 { .init_isa
= SB16_init
}
4257 #ifdef CONFIG_CS4231A
4263 { .init_isa
= cs4231a_init
}
4271 "Yamaha YMF262 (OPL3)",
4273 "Yamaha YM3812 (OPL2)",
4277 { .init_isa
= Adlib_init
}
4284 "Gravis Ultrasound GF1",
4287 { .init_isa
= GUS_init
}
4294 "Intel 82801AA AC97 Audio",
4297 { .init_pci
= ac97_init
}
4301 #ifdef CONFIG_ES1370
4304 "ENSONIQ AudioPCI ES1370",
4307 { .init_pci
= es1370_init
}
4311 #endif /* HAS_AUDIO_CHOICE */
4313 { NULL
, NULL
, 0, 0, { NULL
} }
4316 static void select_soundhw (const char *optarg
)
4320 if (*optarg
== '?') {
4323 printf ("Valid sound card names (comma separated):\n");
4324 for (c
= soundhw
; c
->name
; ++c
) {
4325 printf ("%-11s %s\n", c
->name
, c
->descr
);
4327 printf ("\n-soundhw all will enable all of the above\n");
4328 exit (*optarg
!= '?');
4336 if (!strcmp (optarg
, "all")) {
4337 for (c
= soundhw
; c
->name
; ++c
) {
4345 e
= strchr (p
, ',');
4346 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4348 for (c
= soundhw
; c
->name
; ++c
) {
4349 if (!strncmp (c
->name
, p
, l
) && !c
->name
[l
]) {
4358 "Unknown sound card name (too big to show)\n");
4361 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4366 p
+= l
+ (e
!= NULL
);
4370 goto show_valid_cards
;
4375 static void select_vgahw (const char *p
)
4380 vga_interface_type
= VGA_NONE
;
4381 if (strstart(p
, "std", &opts
)) {
4382 vga_interface_type
= VGA_STD
;
4383 } else if (strstart(p
, "cirrus", &opts
)) {
4384 vga_interface_type
= VGA_CIRRUS
;
4385 } else if (strstart(p
, "vmware", &opts
)) {
4386 vga_interface_type
= VGA_VMWARE
;
4387 } else if (strstart(p
, "xenfb", &opts
)) {
4388 vga_interface_type
= VGA_XENFB
;
4389 } else if (!strstart(p
, "none", &opts
)) {
4391 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4395 const char *nextopt
;
4397 if (strstart(opts
, ",retrace=", &nextopt
)) {
4399 if (strstart(opts
, "dumb", &nextopt
))
4400 vga_retrace_method
= VGA_RETRACE_DUMB
;
4401 else if (strstart(opts
, "precise", &nextopt
))
4402 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4403 else goto invalid_vga
;
4404 } else goto invalid_vga
;
4410 static int balloon_parse(const char *arg
)
4414 if (strcmp(arg
, "none") == 0) {
4418 if (!strncmp(arg
, "virtio", 6)) {
4419 if (arg
[6] == ',') {
4420 /* have params -> parse them */
4421 opts
= qemu_opts_parse(&qemu_device_opts
, arg
+7, 0);
4425 /* create empty opts */
4426 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4428 qemu_opt_set(opts
, "driver", "virtio-balloon-pci");
4437 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4439 exit(STATUS_CONTROL_C_EXIT
);
4444 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4448 if(strlen(str
) != 36)
4451 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4452 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4453 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4459 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4467 static void termsig_handler(int signal
)
4469 qemu_system_shutdown_request();
4472 static void sigchld_handler(int signal
)
4474 waitpid(-1, NULL
, WNOHANG
);
4477 static void sighandler_setup(void)
4479 struct sigaction act
;
4481 memset(&act
, 0, sizeof(act
));
4482 act
.sa_handler
= termsig_handler
;
4483 sigaction(SIGINT
, &act
, NULL
);
4484 sigaction(SIGHUP
, &act
, NULL
);
4485 sigaction(SIGTERM
, &act
, NULL
);
4487 act
.sa_handler
= sigchld_handler
;
4488 act
.sa_flags
= SA_NOCLDSTOP
;
4489 sigaction(SIGCHLD
, &act
, NULL
);
4495 /* Look for support files in the same directory as the executable. */
4496 static char *find_datadir(const char *argv0
)
4502 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
4509 while (p
!= buf
&& *p
!= '\\')
4512 if (access(buf
, R_OK
) == 0) {
4513 return qemu_strdup(buf
);
4519 /* Find a likely location for support files using the location of the binary.
4520 For installed binaries this will be "$bindir/../share/qemu". When
4521 running from the build tree this will be "$bindir/../pc-bios". */
4522 #define SHARE_SUFFIX "/share/qemu"
4523 #define BUILD_SUFFIX "/pc-bios"
4524 static char *find_datadir(const char *argv0
)
4532 #if defined(__linux__)
4535 len
= readlink("/proc/self/exe", buf
, sizeof(buf
) - 1);
4541 #elif defined(__FreeBSD__)
4544 len
= readlink("/proc/curproc/file", buf
, sizeof(buf
) - 1);
4551 /* If we don't have any way of figuring out the actual executable
4552 location then try argv[0]. */
4554 p
= realpath(argv0
, buf
);
4562 max_len
= strlen(dir
) +
4563 MAX(strlen(SHARE_SUFFIX
), strlen(BUILD_SUFFIX
)) + 1;
4564 res
= qemu_mallocz(max_len
);
4565 snprintf(res
, max_len
, "%s%s", dir
, SHARE_SUFFIX
);
4566 if (access(res
, R_OK
)) {
4567 snprintf(res
, max_len
, "%s%s", dir
, BUILD_SUFFIX
);
4568 if (access(res
, R_OK
)) {
4580 char *qemu_find_file(int type
, const char *name
)
4586 /* If name contains path separators then try it as a straight path. */
4587 if ((strchr(name
, '/') || strchr(name
, '\\'))
4588 && access(name
, R_OK
) == 0) {
4589 return qemu_strdup(name
);
4592 case QEMU_FILE_TYPE_BIOS
:
4595 case QEMU_FILE_TYPE_KEYMAP
:
4596 subdir
= "keymaps/";
4601 len
= strlen(data_dir
) + strlen(name
) + strlen(subdir
) + 2;
4602 buf
= qemu_mallocz(len
);
4603 snprintf(buf
, len
, "%s/%s%s", data_dir
, subdir
, name
);
4604 if (access(buf
, R_OK
)) {
4611 static int device_help_func(QemuOpts
*opts
, void *opaque
)
4613 return qdev_device_help(opts
);
4616 static int device_init_func(QemuOpts
*opts
, void *opaque
)
4620 dev
= qdev_device_add(opts
);
4626 static int chardev_init_func(QemuOpts
*opts
, void *opaque
)
4628 CharDriverState
*chr
;
4630 chr
= qemu_chr_open_opts(opts
, NULL
);
4636 static int mon_init_func(QemuOpts
*opts
, void *opaque
)
4638 CharDriverState
*chr
;
4639 const char *chardev
;
4643 mode
= qemu_opt_get(opts
, "mode");
4647 if (strcmp(mode
, "readline") == 0) {
4648 flags
= MONITOR_USE_READLINE
;
4649 } else if (strcmp(mode
, "control") == 0) {
4650 flags
= MONITOR_USE_CONTROL
;
4652 fprintf(stderr
, "unknown monitor mode \"%s\"\n", mode
);
4656 if (qemu_opt_get_bool(opts
, "default", 0))
4657 flags
|= MONITOR_IS_DEFAULT
;
4659 chardev
= qemu_opt_get(opts
, "chardev");
4660 chr
= qemu_chr_find(chardev
);
4662 fprintf(stderr
, "chardev \"%s\" not found\n", chardev
);
4666 monitor_init(chr
, flags
);
4670 static void monitor_parse(const char *optarg
, const char *mode
)
4672 static int monitor_device_index
= 0;
4678 if (strstart(optarg
, "chardev:", &p
)) {
4679 snprintf(label
, sizeof(label
), "%s", p
);
4681 if (monitor_device_index
) {
4682 snprintf(label
, sizeof(label
), "monitor%d",
4683 monitor_device_index
);
4685 snprintf(label
, sizeof(label
), "monitor");
4688 opts
= qemu_chr_parse_compat(label
, optarg
);
4690 fprintf(stderr
, "parse error: %s\n", optarg
);
4695 opts
= qemu_opts_create(&qemu_mon_opts
, label
, 1);
4697 fprintf(stderr
, "duplicate chardev: %s\n", label
);
4700 qemu_opt_set(opts
, "mode", mode
);
4701 qemu_opt_set(opts
, "chardev", label
);
4703 qemu_opt_set(opts
, "default", "on");
4704 monitor_device_index
++;
4707 struct device_config
{
4709 DEV_USB
, /* -usbdevice */
4711 DEV_SERIAL
, /* -serial */
4712 DEV_PARALLEL
, /* -parallel */
4713 DEV_VIRTCON
, /* -virtioconsole */
4714 DEV_DEBUGCON
, /* -debugcon */
4716 const char *cmdline
;
4717 QTAILQ_ENTRY(device_config
) next
;
4719 QTAILQ_HEAD(, device_config
) device_configs
= QTAILQ_HEAD_INITIALIZER(device_configs
);
4721 static void add_device_config(int type
, const char *cmdline
)
4723 struct device_config
*conf
;
4725 conf
= qemu_mallocz(sizeof(*conf
));
4727 conf
->cmdline
= cmdline
;
4728 QTAILQ_INSERT_TAIL(&device_configs
, conf
, next
);
4731 static int foreach_device_config(int type
, int (*func
)(const char *cmdline
))
4733 struct device_config
*conf
;
4736 QTAILQ_FOREACH(conf
, &device_configs
, next
) {
4737 if (conf
->type
!= type
)
4739 rc
= func(conf
->cmdline
);
4746 static int serial_parse(const char *devname
)
4748 static int index
= 0;
4751 if (strcmp(devname
, "none") == 0)
4753 if (index
== MAX_SERIAL_PORTS
) {
4754 fprintf(stderr
, "qemu: too many serial ports\n");
4757 snprintf(label
, sizeof(label
), "serial%d", index
);
4758 serial_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4759 if (!serial_hds
[index
]) {
4760 fprintf(stderr
, "qemu: could not open serial device '%s': %s\n",
4761 devname
, strerror(errno
));
4768 static int parallel_parse(const char *devname
)
4770 static int index
= 0;
4773 if (strcmp(devname
, "none") == 0)
4775 if (index
== MAX_PARALLEL_PORTS
) {
4776 fprintf(stderr
, "qemu: too many parallel ports\n");
4779 snprintf(label
, sizeof(label
), "parallel%d", index
);
4780 parallel_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4781 if (!parallel_hds
[index
]) {
4782 fprintf(stderr
, "qemu: could not open parallel device '%s': %s\n",
4783 devname
, strerror(errno
));
4790 static int virtcon_parse(const char *devname
)
4792 static int index
= 0;
4794 QemuOpts
*bus_opts
, *dev_opts
;
4796 if (strcmp(devname
, "none") == 0)
4798 if (index
== MAX_VIRTIO_CONSOLES
) {
4799 fprintf(stderr
, "qemu: too many virtio consoles\n");
4803 bus_opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4804 qemu_opt_set(bus_opts
, "driver", "virtio-serial");
4806 dev_opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4807 qemu_opt_set(dev_opts
, "driver", "virtconsole");
4809 snprintf(label
, sizeof(label
), "virtcon%d", index
);
4810 virtcon_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4811 if (!virtcon_hds
[index
]) {
4812 fprintf(stderr
, "qemu: could not open virtio console '%s': %s\n",
4813 devname
, strerror(errno
));
4816 qemu_opt_set(dev_opts
, "chardev", label
);
4822 static int debugcon_parse(const char *devname
)
4826 if (!qemu_chr_open("debugcon", devname
, NULL
)) {
4829 opts
= qemu_opts_create(&qemu_device_opts
, "debugcon", 1);
4831 fprintf(stderr
, "qemu: already have a debugcon device\n");
4834 qemu_opt_set(opts
, "driver", "isa-debugcon");
4835 qemu_opt_set(opts
, "chardev", "debugcon");
4839 static const QEMUOption
*lookup_opt(int argc
, char **argv
,
4840 const char **poptarg
, int *poptind
)
4842 const QEMUOption
*popt
;
4843 int optind
= *poptind
;
4844 char *r
= argv
[optind
];
4847 loc_set_cmdline(argv
, optind
, 1);
4849 /* Treat --foo the same as -foo. */
4852 popt
= qemu_options
;
4855 error_report("invalid option");
4858 if (!strcmp(popt
->name
, r
+ 1))
4862 if (popt
->flags
& HAS_ARG
) {
4863 if (optind
>= argc
) {
4864 error_report("requires an argument");
4867 optarg
= argv
[optind
++];
4868 loc_set_cmdline(argv
, optind
- 2, 2);
4879 int main(int argc
, char **argv
, char **envp
)
4881 const char *gdbstub_dev
= NULL
;
4882 uint32_t boot_devices_bitmap
= 0;
4884 int snapshot
, linux_boot
, net_boot
;
4885 const char *icount_option
= NULL
;
4886 const char *initrd_filename
;
4887 const char *kernel_filename
, *kernel_cmdline
;
4888 char boot_devices
[33] = "cad"; /* default to HD->floppy->CD-ROM */
4890 DisplayChangeListener
*dcl
;
4891 int cyls
, heads
, secs
, translation
;
4892 QemuOpts
*hda_opts
= NULL
, *opts
;
4895 const char *loadvm
= NULL
;
4896 QEMUMachine
*machine
;
4897 const char *cpu_model
;
4902 const char *pid_file
= NULL
;
4903 const char *incoming
= NULL
;
4906 struct passwd
*pwd
= NULL
;
4907 const char *chroot_dir
= NULL
;
4908 const char *run_as
= NULL
;
4911 int show_vnc_port
= 0;
4914 error_set_progname(argv
[0]);
4918 qemu_cache_utils_init(envp
);
4920 QLIST_INIT (&vm_change_state_head
);
4923 struct sigaction act
;
4924 sigfillset(&act
.sa_mask
);
4926 act
.sa_handler
= SIG_IGN
;
4927 sigaction(SIGPIPE
, &act
, NULL
);
4930 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4931 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4932 QEMU to run on a single CPU */
4937 h
= GetCurrentProcess();
4938 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4939 for(i
= 0; i
< 32; i
++) {
4940 if (mask
& (1 << i
))
4945 SetProcessAffinityMask(h
, mask
);
4951 module_call_init(MODULE_INIT_MACHINE
);
4952 machine
= find_default_machine();
4954 initrd_filename
= NULL
;
4957 kernel_filename
= NULL
;
4958 kernel_cmdline
= "";
4959 cyls
= heads
= secs
= 0;
4960 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4962 for (i
= 0; i
< MAX_NODES
; i
++) {
4964 node_cpumask
[i
] = 0;
4973 /* first pass of option parsing */
4975 while (optind
< argc
) {
4976 if (argv
[optind
][0] != '-') {
4981 const QEMUOption
*popt
;
4983 popt
= lookup_opt(argc
, argv
, &optarg
, &optind
);
4984 switch (popt
->index
) {
4985 case QEMU_OPTION_nodefconfig
:
4996 fname
= CONFIG_QEMU_CONFDIR
"/qemu.conf";
4997 fp
= fopen(fname
, "r");
4999 if (qemu_config_parse(fp
, fname
) != 0) {
5005 fname
= CONFIG_QEMU_CONFDIR
"/target-" TARGET_ARCH
".conf";
5006 fp
= fopen(fname
, "r");
5008 if (qemu_config_parse(fp
, fname
) != 0) {
5014 #if defined(cpudef_setup)
5015 cpudef_setup(); /* parse cpu definitions in target config file */
5018 /* second pass of option parsing */
5023 if (argv
[optind
][0] != '-') {
5024 hda_opts
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
5026 const QEMUOption
*popt
;
5028 popt
= lookup_opt(argc
, argv
, &optarg
, &optind
);
5029 switch(popt
->index
) {
5031 machine
= find_machine(optarg
);
5034 printf("Supported machines are:\n");
5035 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5037 printf("%-10s %s (alias of %s)\n",
5038 m
->alias
, m
->desc
, m
->name
);
5039 printf("%-10s %s%s\n",
5041 m
->is_default
? " (default)" : "");
5043 exit(*optarg
!= '?');
5046 case QEMU_OPTION_cpu
:
5047 /* hw initialization will check this */
5048 if (*optarg
== '?') {
5049 /* XXX: implement xxx_cpu_list for targets that still miss it */
5050 #if defined(cpu_list_id)
5051 cpu_list_id(stdout
, &fprintf
, optarg
);
5052 #elif defined(cpu_list)
5053 cpu_list(stdout
, &fprintf
); /* deprecated */
5060 case QEMU_OPTION_initrd
:
5061 initrd_filename
= optarg
;
5063 case QEMU_OPTION_hda
:
5065 hda_opts
= drive_add(optarg
, HD_ALIAS
, 0);
5067 hda_opts
= drive_add(optarg
, HD_ALIAS
5068 ",cyls=%d,heads=%d,secs=%d%s",
5069 0, cyls
, heads
, secs
,
5070 translation
== BIOS_ATA_TRANSLATION_LBA
?
5072 translation
== BIOS_ATA_TRANSLATION_NONE
?
5073 ",trans=none" : "");
5075 case QEMU_OPTION_hdb
:
5076 case QEMU_OPTION_hdc
:
5077 case QEMU_OPTION_hdd
:
5078 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
5080 case QEMU_OPTION_drive
:
5081 drive_add(NULL
, "%s", optarg
);
5083 case QEMU_OPTION_set
:
5084 if (qemu_set_option(optarg
) != 0)
5087 case QEMU_OPTION_global
:
5088 if (qemu_global_option(optarg
) != 0)
5091 case QEMU_OPTION_mtdblock
:
5092 drive_add(optarg
, MTD_ALIAS
);
5094 case QEMU_OPTION_sd
:
5095 drive_add(optarg
, SD_ALIAS
);
5097 case QEMU_OPTION_pflash
:
5098 drive_add(optarg
, PFLASH_ALIAS
);
5100 case QEMU_OPTION_snapshot
:
5103 case QEMU_OPTION_hdachs
:
5107 cyls
= strtol(p
, (char **)&p
, 0);
5108 if (cyls
< 1 || cyls
> 16383)
5113 heads
= strtol(p
, (char **)&p
, 0);
5114 if (heads
< 1 || heads
> 16)
5119 secs
= strtol(p
, (char **)&p
, 0);
5120 if (secs
< 1 || secs
> 63)
5124 if (!strcmp(p
, "none"))
5125 translation
= BIOS_ATA_TRANSLATION_NONE
;
5126 else if (!strcmp(p
, "lba"))
5127 translation
= BIOS_ATA_TRANSLATION_LBA
;
5128 else if (!strcmp(p
, "auto"))
5129 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5132 } else if (*p
!= '\0') {
5134 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5137 if (hda_opts
!= NULL
) {
5139 snprintf(num
, sizeof(num
), "%d", cyls
);
5140 qemu_opt_set(hda_opts
, "cyls", num
);
5141 snprintf(num
, sizeof(num
), "%d", heads
);
5142 qemu_opt_set(hda_opts
, "heads", num
);
5143 snprintf(num
, sizeof(num
), "%d", secs
);
5144 qemu_opt_set(hda_opts
, "secs", num
);
5145 if (translation
== BIOS_ATA_TRANSLATION_LBA
)
5146 qemu_opt_set(hda_opts
, "trans", "lba");
5147 if (translation
== BIOS_ATA_TRANSLATION_NONE
)
5148 qemu_opt_set(hda_opts
, "trans", "none");
5152 case QEMU_OPTION_numa
:
5153 if (nb_numa_nodes
>= MAX_NODES
) {
5154 fprintf(stderr
, "qemu: too many NUMA nodes\n");
5159 case QEMU_OPTION_nographic
:
5160 display_type
= DT_NOGRAPHIC
;
5162 #ifdef CONFIG_CURSES
5163 case QEMU_OPTION_curses
:
5164 display_type
= DT_CURSES
;
5167 case QEMU_OPTION_portrait
:
5170 case QEMU_OPTION_kernel
:
5171 kernel_filename
= optarg
;
5173 case QEMU_OPTION_append
:
5174 kernel_cmdline
= optarg
;
5176 case QEMU_OPTION_cdrom
:
5177 drive_add(optarg
, CDROM_ALIAS
);
5179 case QEMU_OPTION_boot
:
5181 static const char * const params
[] = {
5182 "order", "once", "menu", NULL
5184 char buf
[sizeof(boot_devices
)];
5185 char *standard_boot_devices
;
5188 if (!strchr(optarg
, '=')) {
5190 pstrcpy(buf
, sizeof(buf
), optarg
);
5191 } else if (check_params(buf
, sizeof(buf
), params
, optarg
) < 0) {
5193 "qemu: unknown boot parameter '%s' in '%s'\n",
5199 get_param_value(buf
, sizeof(buf
), "order", optarg
)) {
5200 boot_devices_bitmap
= parse_bootdevices(buf
);
5201 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5204 if (get_param_value(buf
, sizeof(buf
),
5206 boot_devices_bitmap
|= parse_bootdevices(buf
);
5207 standard_boot_devices
= qemu_strdup(boot_devices
);
5208 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5209 qemu_register_reset(restore_boot_devices
,
5210 standard_boot_devices
);
5212 if (get_param_value(buf
, sizeof(buf
),
5214 if (!strcmp(buf
, "on")) {
5216 } else if (!strcmp(buf
, "off")) {
5220 "qemu: invalid option value '%s'\n",
5228 case QEMU_OPTION_fda
:
5229 case QEMU_OPTION_fdb
:
5230 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
5233 case QEMU_OPTION_no_fd_bootchk
:
5237 case QEMU_OPTION_netdev
:
5238 if (net_client_parse(&qemu_netdev_opts
, optarg
) == -1) {
5242 case QEMU_OPTION_net
:
5243 if (net_client_parse(&qemu_net_opts
, optarg
) == -1) {
5248 case QEMU_OPTION_tftp
:
5249 legacy_tftp_prefix
= optarg
;
5251 case QEMU_OPTION_bootp
:
5252 legacy_bootp_filename
= optarg
;
5255 case QEMU_OPTION_smb
:
5256 if (net_slirp_smb(optarg
) < 0)
5260 case QEMU_OPTION_redir
:
5261 if (net_slirp_redir(optarg
) < 0)
5265 case QEMU_OPTION_bt
:
5266 add_device_config(DEV_BT
, optarg
);
5269 case QEMU_OPTION_audio_help
:
5273 case QEMU_OPTION_soundhw
:
5274 select_soundhw (optarg
);
5280 case QEMU_OPTION_version
:
5284 case QEMU_OPTION_m
: {
5288 value
= strtoul(optarg
, &ptr
, 10);
5290 case 0: case 'M': case 'm':
5297 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5301 /* On 32-bit hosts, QEMU is limited by virtual address space */
5302 if (value
> (2047 << 20) && HOST_LONG_BITS
== 32) {
5303 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5306 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5307 fprintf(stderr
, "qemu: ram size too large\n");
5313 case QEMU_OPTION_mempath
:
5317 case QEMU_OPTION_mem_prealloc
:
5324 const CPULogItem
*item
;
5326 mask
= cpu_str_to_log_mask(optarg
);
5328 printf("Log items (comma separated):\n");
5329 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5330 printf("%-10s %s\n", item
->name
, item
->help
);
5338 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5340 case QEMU_OPTION_gdb
:
5341 gdbstub_dev
= optarg
;
5346 case QEMU_OPTION_bios
:
5349 case QEMU_OPTION_singlestep
:
5356 keyboard_layout
= optarg
;
5358 case QEMU_OPTION_localtime
:
5361 case QEMU_OPTION_vga
:
5362 select_vgahw (optarg
);
5364 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5370 w
= strtol(p
, (char **)&p
, 10);
5373 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5379 h
= strtol(p
, (char **)&p
, 10);
5384 depth
= strtol(p
, (char **)&p
, 10);
5385 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5386 depth
!= 24 && depth
!= 32)
5388 } else if (*p
== '\0') {
5389 depth
= graphic_depth
;
5396 graphic_depth
= depth
;
5400 case QEMU_OPTION_echr
:
5403 term_escape_char
= strtol(optarg
, &r
, 0);
5405 printf("Bad argument to echr\n");
5408 case QEMU_OPTION_monitor
:
5409 monitor_parse(optarg
, "readline");
5410 default_monitor
= 0;
5412 case QEMU_OPTION_qmp
:
5413 monitor_parse(optarg
, "control");
5414 default_monitor
= 0;
5416 case QEMU_OPTION_mon
:
5417 opts
= qemu_opts_parse(&qemu_mon_opts
, optarg
, 1);
5419 fprintf(stderr
, "parse error: %s\n", optarg
);
5422 default_monitor
= 0;
5424 case QEMU_OPTION_chardev
:
5425 opts
= qemu_opts_parse(&qemu_chardev_opts
, optarg
, 1);
5427 fprintf(stderr
, "parse error: %s\n", optarg
);
5431 case QEMU_OPTION_serial
:
5432 add_device_config(DEV_SERIAL
, optarg
);
5434 if (strncmp(optarg
, "mon:", 4) == 0) {
5435 default_monitor
= 0;
5438 case QEMU_OPTION_watchdog
:
5441 "qemu: only one watchdog option may be given\n");
5446 case QEMU_OPTION_watchdog_action
:
5447 if (select_watchdog_action(optarg
) == -1) {
5448 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5452 case QEMU_OPTION_virtiocon
:
5453 add_device_config(DEV_VIRTCON
, optarg
);
5454 default_virtcon
= 0;
5455 if (strncmp(optarg
, "mon:", 4) == 0) {
5456 default_monitor
= 0;
5459 case QEMU_OPTION_parallel
:
5460 add_device_config(DEV_PARALLEL
, optarg
);
5461 default_parallel
= 0;
5462 if (strncmp(optarg
, "mon:", 4) == 0) {
5463 default_monitor
= 0;
5466 case QEMU_OPTION_debugcon
:
5467 add_device_config(DEV_DEBUGCON
, optarg
);
5469 case QEMU_OPTION_loadvm
:
5472 case QEMU_OPTION_full_screen
:
5476 case QEMU_OPTION_no_frame
:
5479 case QEMU_OPTION_alt_grab
:
5482 case QEMU_OPTION_ctrl_grab
:
5485 case QEMU_OPTION_no_quit
:
5488 case QEMU_OPTION_sdl
:
5489 display_type
= DT_SDL
;
5492 case QEMU_OPTION_pidfile
:
5496 case QEMU_OPTION_win2k_hack
:
5497 win2k_install_hack
= 1;
5499 case QEMU_OPTION_rtc_td_hack
:
5502 case QEMU_OPTION_acpitable
:
5503 if(acpi_table_add(optarg
) < 0) {
5504 fprintf(stderr
, "Wrong acpi table provided\n");
5508 case QEMU_OPTION_smbios
:
5509 if(smbios_entry_add(optarg
) < 0) {
5510 fprintf(stderr
, "Wrong smbios provided\n");
5516 case QEMU_OPTION_enable_kvm
:
5520 case QEMU_OPTION_usb
:
5523 case QEMU_OPTION_usbdevice
:
5525 add_device_config(DEV_USB
, optarg
);
5527 case QEMU_OPTION_device
:
5528 if (!qemu_opts_parse(&qemu_device_opts
, optarg
, 1)) {
5532 case QEMU_OPTION_smp
:
5535 fprintf(stderr
, "Invalid number of CPUs\n");
5538 if (max_cpus
< smp_cpus
) {
5539 fprintf(stderr
, "maxcpus must be equal to or greater than "
5543 if (max_cpus
> 255) {
5544 fprintf(stderr
, "Unsupported number of maxcpus\n");
5548 case QEMU_OPTION_vnc
:
5549 display_type
= DT_VNC
;
5550 vnc_display
= optarg
;
5553 case QEMU_OPTION_no_acpi
:
5556 case QEMU_OPTION_no_hpet
:
5559 case QEMU_OPTION_balloon
:
5560 if (balloon_parse(optarg
) < 0) {
5561 fprintf(stderr
, "Unknown -balloon argument %s\n", optarg
);
5566 case QEMU_OPTION_no_reboot
:
5569 case QEMU_OPTION_no_shutdown
:
5572 case QEMU_OPTION_show_cursor
:
5575 case QEMU_OPTION_uuid
:
5576 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5577 fprintf(stderr
, "Fail to parse UUID string."
5578 " Wrong format.\n");
5583 case QEMU_OPTION_daemonize
:
5587 case QEMU_OPTION_option_rom
:
5588 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5589 fprintf(stderr
, "Too many option ROMs\n");
5592 option_rom
[nb_option_roms
] = optarg
;
5595 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5596 case QEMU_OPTION_semihosting
:
5597 semihosting_enabled
= 1;
5600 case QEMU_OPTION_name
:
5601 qemu_name
= qemu_strdup(optarg
);
5603 char *p
= strchr(qemu_name
, ',');
5606 if (strncmp(p
, "process=", 8)) {
5607 fprintf(stderr
, "Unknown subargument %s to -name", p
);
5615 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5616 case QEMU_OPTION_prom_env
:
5617 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5618 fprintf(stderr
, "Too many prom variables\n");
5621 prom_envs
[nb_prom_envs
] = optarg
;
5626 case QEMU_OPTION_old_param
:
5630 case QEMU_OPTION_clock
:
5631 configure_alarms(optarg
);
5633 case QEMU_OPTION_startdate
:
5634 configure_rtc_date_offset(optarg
, 1);
5636 case QEMU_OPTION_rtc
:
5637 opts
= qemu_opts_parse(&qemu_rtc_opts
, optarg
, 0);
5639 fprintf(stderr
, "parse error: %s\n", optarg
);
5642 configure_rtc(opts
);
5644 case QEMU_OPTION_tb_size
:
5645 tb_size
= strtol(optarg
, NULL
, 0);
5649 case QEMU_OPTION_icount
:
5650 icount_option
= optarg
;
5652 case QEMU_OPTION_incoming
:
5655 case QEMU_OPTION_nodefaults
:
5657 default_parallel
= 0;
5658 default_virtcon
= 0;
5659 default_monitor
= 0;
5667 case QEMU_OPTION_chroot
:
5668 chroot_dir
= optarg
;
5670 case QEMU_OPTION_runas
:
5675 case QEMU_OPTION_xen_domid
:
5676 xen_domid
= atoi(optarg
);
5678 case QEMU_OPTION_xen_create
:
5679 xen_mode
= XEN_CREATE
;
5681 case QEMU_OPTION_xen_attach
:
5682 xen_mode
= XEN_ATTACH
;
5685 case QEMU_OPTION_readconfig
:
5688 fp
= fopen(optarg
, "r");
5690 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5693 if (qemu_config_parse(fp
, optarg
) != 0) {
5699 case QEMU_OPTION_writeconfig
:
5702 if (strcmp(optarg
, "-") == 0) {
5705 fp
= fopen(optarg
, "w");
5707 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5711 qemu_config_write(fp
);
5720 /* If no data_dir is specified then try to find it relative to the
5723 data_dir
= find_datadir(argv
[0]);
5725 /* If all else fails use the install patch specified when building. */
5727 data_dir
= CONFIG_QEMU_SHAREDIR
;
5731 * Default to max_cpus = smp_cpus, in case the user doesn't
5732 * specify a max_cpus value.
5735 max_cpus
= smp_cpus
;
5737 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5738 if (smp_cpus
> machine
->max_cpus
) {
5739 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5740 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5745 qemu_opts_foreach(&qemu_device_opts
, default_driver_check
, NULL
, 0);
5746 qemu_opts_foreach(&qemu_global_opts
, default_driver_check
, NULL
, 0);
5748 if (machine
->no_serial
) {
5751 if (machine
->no_parallel
) {
5752 default_parallel
= 0;
5754 if (!machine
->use_virtcon
) {
5755 default_virtcon
= 0;
5757 if (machine
->no_vga
) {
5760 if (machine
->no_floppy
) {
5763 if (machine
->no_cdrom
) {
5766 if (machine
->no_sdcard
) {
5770 if (display_type
== DT_NOGRAPHIC
) {
5771 if (default_parallel
)
5772 add_device_config(DEV_PARALLEL
, "null");
5773 if (default_serial
&& default_monitor
) {
5774 add_device_config(DEV_SERIAL
, "mon:stdio");
5775 } else if (default_virtcon
&& default_monitor
) {
5776 add_device_config(DEV_VIRTCON
, "mon:stdio");
5779 add_device_config(DEV_SERIAL
, "stdio");
5780 if (default_virtcon
)
5781 add_device_config(DEV_VIRTCON
, "stdio");
5782 if (default_monitor
)
5783 monitor_parse("stdio", "readline");
5787 add_device_config(DEV_SERIAL
, "vc:80Cx24C");
5788 if (default_parallel
)
5789 add_device_config(DEV_PARALLEL
, "vc:80Cx24C");
5790 if (default_monitor
)
5791 monitor_parse("vc:80Cx24C", "readline");
5792 if (default_virtcon
)
5793 add_device_config(DEV_VIRTCON
, "vc:80Cx24C");
5796 vga_interface_type
= VGA_CIRRUS
;
5798 if (qemu_opts_foreach(&qemu_chardev_opts
, chardev_init_func
, NULL
, 1) != 0)
5805 if (pipe(fds
) == -1)
5816 len
= read(fds
[0], &status
, 1);
5817 if (len
== -1 && (errno
== EINTR
))
5822 else if (status
== 1) {
5823 fprintf(stderr
, "Could not acquire pidfile: %s\n", strerror(errno
));
5831 qemu_set_cloexec(fds
[1]);
5843 signal(SIGTSTP
, SIG_IGN
);
5844 signal(SIGTTOU
, SIG_IGN
);
5845 signal(SIGTTIN
, SIG_IGN
);
5849 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5853 if (write(fds
[1], &status
, 1) != 1) {
5854 perror("daemonize. Writing to pipe\n");
5858 fprintf(stderr
, "Could not acquire pid file: %s\n", strerror(errno
));
5862 if (kvm_enabled()) {
5865 ret
= kvm_init(smp_cpus
);
5867 fprintf(stderr
, "failed to initialize KVM\n");
5872 if (qemu_init_main_loop()) {
5873 fprintf(stderr
, "qemu_init_main_loop failed\n");
5876 linux_boot
= (kernel_filename
!= NULL
);
5878 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5879 fprintf(stderr
, "-append only allowed with -kernel option\n");
5883 if (!linux_boot
&& initrd_filename
!= NULL
) {
5884 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5889 /* Win32 doesn't support line-buffering and requires size >= 2 */
5890 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5893 if (init_timer_alarm() < 0) {
5894 fprintf(stderr
, "could not initialize alarm timer\n");
5897 configure_icount(icount_option
);
5903 if (net_init_clients() < 0) {
5907 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5908 net_set_boot_mask(net_boot
);
5910 /* init the bluetooth world */
5911 if (foreach_device_config(DEV_BT
, bt_parse
))
5914 /* init the memory */
5916 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5918 /* init the dynamic translator */
5919 cpu_exec_init_all(tb_size
* 1024 * 1024);
5921 bdrv_init_with_whitelist();
5925 if (default_cdrom
) {
5926 /* we always create the cdrom drive, even if no disk is there */
5927 drive_add(NULL
, CDROM_ALIAS
);
5930 if (default_floppy
) {
5931 /* we always create at least one floppy */
5932 drive_add(NULL
, FD_ALIAS
, 0);
5935 if (default_sdcard
) {
5936 /* we always create one sd slot, even if no card is in it */
5937 drive_add(NULL
, SD_ALIAS
);
5940 /* open the virtual block devices */
5942 qemu_opts_foreach(&qemu_drive_opts
, drive_enable_snapshot
, NULL
, 0);
5943 if (qemu_opts_foreach(&qemu_drive_opts
, drive_init_func
, machine
, 1) != 0)
5946 vmstate_register(0, &vmstate_timers
,&timers_state
);
5947 register_savevm_live("ram", 0, 3, NULL
, ram_save_live
, NULL
,
5950 if (nb_numa_nodes
> 0) {
5953 if (nb_numa_nodes
> smp_cpus
) {
5954 nb_numa_nodes
= smp_cpus
;
5957 /* If no memory size if given for any node, assume the default case
5958 * and distribute the available memory equally across all nodes
5960 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5961 if (node_mem
[i
] != 0)
5964 if (i
== nb_numa_nodes
) {
5965 uint64_t usedmem
= 0;
5967 /* On Linux, the each node's border has to be 8MB aligned,
5968 * the final node gets the rest.
5970 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
5971 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
5972 usedmem
+= node_mem
[i
];
5974 node_mem
[i
] = ram_size
- usedmem
;
5977 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5978 if (node_cpumask
[i
] != 0)
5981 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5982 * must cope with this anyway, because there are BIOSes out there in
5983 * real machines which also use this scheme.
5985 if (i
== nb_numa_nodes
) {
5986 for (i
= 0; i
< smp_cpus
; i
++) {
5987 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
5992 if (foreach_device_config(DEV_SERIAL
, serial_parse
) < 0)
5994 if (foreach_device_config(DEV_PARALLEL
, parallel_parse
) < 0)
5996 if (foreach_device_config(DEV_VIRTCON
, virtcon_parse
) < 0)
5998 if (foreach_device_config(DEV_DEBUGCON
, debugcon_parse
) < 0)
6001 module_call_init(MODULE_INIT_DEVICE
);
6003 if (qemu_opts_foreach(&qemu_device_opts
, device_help_func
, NULL
, 0) != 0)
6007 i
= select_watchdog(watchdog
);
6009 exit (i
== 1 ? 1 : 0);
6012 if (machine
->compat_props
) {
6013 qdev_prop_register_global_list(machine
->compat_props
);
6017 machine
->init(ram_size
, boot_devices
,
6018 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
6020 cpu_synchronize_all_post_init();
6023 /* must be after terminal init, SDL library changes signal handlers */
6027 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
6028 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6029 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
6035 current_machine
= machine
;
6037 /* init USB devices */
6039 if (foreach_device_config(DEV_USB
, usb_parse
) < 0)
6043 /* init generic devices */
6044 if (qemu_opts_foreach(&qemu_device_opts
, device_init_func
, NULL
, 1) != 0)
6047 net_check_clients();
6049 /* just use the first displaystate for the moment */
6050 ds
= get_displaystate();
6052 if (display_type
== DT_DEFAULT
) {
6053 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6054 display_type
= DT_SDL
;
6056 display_type
= DT_VNC
;
6057 vnc_display
= "localhost:0,to=99";
6063 switch (display_type
) {
6066 #if defined(CONFIG_CURSES)
6068 curses_display_init(ds
, full_screen
);
6071 #if defined(CONFIG_SDL)
6073 sdl_display_init(ds
, full_screen
, no_frame
);
6075 #elif defined(CONFIG_COCOA)
6077 cocoa_display_init(ds
, full_screen
);
6081 vnc_display_init(ds
);
6082 if (vnc_display_open(ds
, vnc_display
) < 0)
6085 if (show_vnc_port
) {
6086 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
6094 dcl
= ds
->listeners
;
6095 while (dcl
!= NULL
) {
6096 if (dcl
->dpy_refresh
!= NULL
) {
6097 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
6098 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
6103 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
6104 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
6105 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
6108 text_consoles_set_display(ds
);
6110 if (qemu_opts_foreach(&qemu_mon_opts
, mon_init_func
, NULL
, 1) != 0)
6113 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
6114 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
6119 qdev_machine_creation_done();
6121 if (rom_load_all() != 0) {
6122 fprintf(stderr
, "rom loading failed\n");
6126 qemu_system_reset();
6128 if (load_vmstate(loadvm
) < 0) {
6134 qemu_start_incoming_migration(incoming
);
6135 } else if (autostart
) {
6145 len
= write(fds
[1], &status
, 1);
6146 if (len
== -1 && (errno
== EINTR
))
6153 perror("not able to chdir to /");
6156 TFR(fd
= qemu_open("/dev/null", O_RDWR
));
6162 pwd
= getpwnam(run_as
);
6164 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
6170 if (chroot(chroot_dir
) < 0) {
6171 fprintf(stderr
, "chroot failed\n");
6175 perror("not able to chdir to /");
6181 if (setgid(pwd
->pw_gid
) < 0) {
6182 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
6185 if (setuid(pwd
->pw_uid
) < 0) {
6186 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
6189 if (setuid(0) != -1) {
6190 fprintf(stderr
, "Dropping privileges failed\n");