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 int64_t qemu_icount_round(int64_t count
)
727 return (count
+ (1 << icount_time_shift
) - 1) >> icount_time_shift
;
730 static struct qemu_alarm_timer alarm_timers
[] = {
733 {"dynticks", dynticks_start_timer
,
734 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
735 /* HPET - if available - is preferred */
736 {"hpet", hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
737 /* ...otherwise try RTC */
738 {"rtc", rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
740 {"unix", unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
742 {"dynticks", win32_start_timer
,
743 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
744 {"win32", win32_start_timer
,
745 win32_stop_timer
, NULL
, &alarm_win32_data
},
750 static void show_available_alarms(void)
754 printf("Available alarm timers, in order of precedence:\n");
755 for (i
= 0; alarm_timers
[i
].name
; i
++)
756 printf("%s\n", alarm_timers
[i
].name
);
759 static void configure_alarms(char const *opt
)
763 int count
= ARRAY_SIZE(alarm_timers
) - 1;
766 struct qemu_alarm_timer tmp
;
768 if (!strcmp(opt
, "?")) {
769 show_available_alarms();
773 arg
= qemu_strdup(opt
);
775 /* Reorder the array */
776 name
= strtok(arg
, ",");
778 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
779 if (!strcmp(alarm_timers
[i
].name
, name
))
784 fprintf(stderr
, "Unknown clock %s\n", name
);
793 tmp
= alarm_timers
[i
];
794 alarm_timers
[i
] = alarm_timers
[cur
];
795 alarm_timers
[cur
] = tmp
;
799 name
= strtok(NULL
, ",");
805 /* Disable remaining timers */
806 for (i
= cur
; i
< count
; i
++)
807 alarm_timers
[i
].name
= NULL
;
809 show_available_alarms();
814 #define QEMU_NUM_CLOCKS 3
818 QEMUClock
*host_clock
;
820 static QEMUTimer
*active_timers
[QEMU_NUM_CLOCKS
];
822 static QEMUClock
*qemu_new_clock(int type
)
825 clock
= qemu_mallocz(sizeof(QEMUClock
));
831 static void qemu_clock_enable(QEMUClock
*clock
, int enabled
)
833 clock
->enabled
= enabled
;
836 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
840 ts
= qemu_mallocz(sizeof(QEMUTimer
));
847 void qemu_free_timer(QEMUTimer
*ts
)
852 /* stop a timer, but do not dealloc it */
853 void qemu_del_timer(QEMUTimer
*ts
)
857 /* NOTE: this code must be signal safe because
858 qemu_timer_expired() can be called from a signal. */
859 pt
= &active_timers
[ts
->clock
->type
];
872 /* modify the current timer so that it will be fired when current_time
873 >= expire_time. The corresponding callback will be called. */
874 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
880 /* add the timer in the sorted list */
881 /* NOTE: this code must be signal safe because
882 qemu_timer_expired() can be called from a signal. */
883 pt
= &active_timers
[ts
->clock
->type
];
888 if (t
->expire_time
> expire_time
)
892 ts
->expire_time
= expire_time
;
896 /* Rearm if necessary */
897 if (pt
== &active_timers
[ts
->clock
->type
]) {
898 if (!alarm_timer
->pending
) {
899 qemu_rearm_alarm_timer(alarm_timer
);
901 /* Interrupt execution to force deadline recalculation. */
907 int qemu_timer_pending(QEMUTimer
*ts
)
910 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
917 int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
921 return (timer_head
->expire_time
<= current_time
);
924 static void qemu_run_timers(QEMUClock
*clock
)
926 QEMUTimer
**ptimer_head
, *ts
;
927 int64_t current_time
;
932 current_time
= qemu_get_clock (clock
);
933 ptimer_head
= &active_timers
[clock
->type
];
936 if (!ts
|| ts
->expire_time
> current_time
)
938 /* remove timer from the list before calling the callback */
939 *ptimer_head
= ts
->next
;
942 /* run the callback (the timer list can be modified) */
947 int64_t qemu_get_clock(QEMUClock
*clock
)
949 switch(clock
->type
) {
950 case QEMU_CLOCK_REALTIME
:
951 return get_clock() / 1000000;
953 case QEMU_CLOCK_VIRTUAL
:
955 return cpu_get_icount();
957 return cpu_get_clock();
959 case QEMU_CLOCK_HOST
:
960 return get_clock_realtime();
964 int64_t qemu_get_clock_ns(QEMUClock
*clock
)
966 switch(clock
->type
) {
967 case QEMU_CLOCK_REALTIME
:
970 case QEMU_CLOCK_VIRTUAL
:
972 return cpu_get_icount();
974 return cpu_get_clock();
976 case QEMU_CLOCK_HOST
:
977 return get_clock_realtime();
981 static void init_clocks(void)
984 rt_clock
= qemu_new_clock(QEMU_CLOCK_REALTIME
);
985 vm_clock
= qemu_new_clock(QEMU_CLOCK_VIRTUAL
);
986 host_clock
= qemu_new_clock(QEMU_CLOCK_HOST
);
988 rtc_clock
= host_clock
;
992 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
994 uint64_t expire_time
;
996 if (qemu_timer_pending(ts
)) {
997 expire_time
= ts
->expire_time
;
1001 qemu_put_be64(f
, expire_time
);
1004 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1006 uint64_t expire_time
;
1008 expire_time
= qemu_get_be64(f
);
1009 if (expire_time
!= -1) {
1010 qemu_mod_timer(ts
, expire_time
);
1016 static const VMStateDescription vmstate_timers
= {
1019 .minimum_version_id
= 1,
1020 .minimum_version_id_old
= 1,
1021 .fields
= (VMStateField
[]) {
1022 VMSTATE_INT64(cpu_ticks_offset
, TimersState
),
1023 VMSTATE_INT64(dummy
, TimersState
),
1024 VMSTATE_INT64_V(cpu_clock_offset
, TimersState
, 2),
1025 VMSTATE_END_OF_LIST()
1029 static void configure_icount(const char *option
)
1031 vmstate_register(0, &vmstate_timers
, &timers_state
);
1035 if (strcmp(option
, "auto") != 0) {
1036 icount_time_shift
= strtol(option
, NULL
, 0);
1043 /* 125MIPS seems a reasonable initial guess at the guest speed.
1044 It will be corrected fairly quickly anyway. */
1045 icount_time_shift
= 3;
1047 /* Have both realtime and virtual time triggers for speed adjustment.
1048 The realtime trigger catches emulated time passing too slowly,
1049 the virtual time trigger catches emulated time passing too fast.
1050 Realtime triggers occur even when idle, so use them less frequently
1051 than VM triggers. */
1052 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
1053 qemu_mod_timer(icount_rt_timer
,
1054 qemu_get_clock(rt_clock
) + 1000);
1055 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
1056 qemu_mod_timer(icount_vm_timer
,
1057 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
1060 static void qemu_run_all_timers(void)
1062 /* rearm timer, if not periodic */
1063 if (alarm_timer
->expired
) {
1064 alarm_timer
->expired
= 0;
1065 qemu_rearm_alarm_timer(alarm_timer
);
1068 alarm_timer
->pending
= 0;
1070 /* vm time timers */
1072 qemu_run_timers(vm_clock
);
1075 qemu_run_timers(rt_clock
);
1076 qemu_run_timers(host_clock
);
1080 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1081 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1084 static void host_alarm_handler(int host_signum
)
1087 struct qemu_alarm_timer
*t
= alarm_timer
;
1092 #define DISP_FREQ 1000
1094 static int64_t delta_min
= INT64_MAX
;
1095 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1097 ti
= qemu_get_clock(vm_clock
);
1098 if (last_clock
!= 0) {
1099 delta
= ti
- last_clock
;
1100 if (delta
< delta_min
)
1102 if (delta
> delta_max
)
1105 if (++count
== DISP_FREQ
) {
1106 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1107 muldiv64(delta_min
, 1000000, get_ticks_per_sec()),
1108 muldiv64(delta_max
, 1000000, get_ticks_per_sec()),
1109 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, get_ticks_per_sec()),
1110 (double)get_ticks_per_sec() / ((double)delta_cum
/ DISP_FREQ
));
1112 delta_min
= INT64_MAX
;
1120 if (alarm_has_dynticks(t
) ||
1122 qemu_timer_expired(active_timers
[QEMU_CLOCK_VIRTUAL
],
1123 qemu_get_clock(vm_clock
))) ||
1124 qemu_timer_expired(active_timers
[QEMU_CLOCK_REALTIME
],
1125 qemu_get_clock(rt_clock
)) ||
1126 qemu_timer_expired(active_timers
[QEMU_CLOCK_HOST
],
1127 qemu_get_clock(host_clock
))) {
1129 t
->expired
= alarm_has_dynticks(t
);
1131 qemu_notify_event();
1135 static int64_t qemu_next_deadline(void)
1137 /* To avoid problems with overflow limit this to 2^32. */
1138 int64_t delta
= INT32_MAX
;
1140 if (active_timers
[QEMU_CLOCK_VIRTUAL
]) {
1141 delta
= active_timers
[QEMU_CLOCK_VIRTUAL
]->expire_time
-
1142 qemu_get_clock(vm_clock
);
1144 if (active_timers
[QEMU_CLOCK_HOST
]) {
1145 int64_t hdelta
= active_timers
[QEMU_CLOCK_HOST
]->expire_time
-
1146 qemu_get_clock(host_clock
);
1157 #if defined(__linux__)
1158 static uint64_t qemu_next_deadline_dyntick(void)
1166 delta
= (qemu_next_deadline() + 999) / 1000;
1168 if (active_timers
[QEMU_CLOCK_REALTIME
]) {
1169 rtdelta
= (active_timers
[QEMU_CLOCK_REALTIME
]->expire_time
-
1170 qemu_get_clock(rt_clock
))*1000;
1171 if (rtdelta
< delta
)
1175 if (delta
< MIN_TIMER_REARM_US
)
1176 delta
= MIN_TIMER_REARM_US
;
1184 /* Sets a specific flag */
1185 static int fcntl_setfl(int fd
, int flag
)
1189 flags
= fcntl(fd
, F_GETFL
);
1193 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1199 #if defined(__linux__)
1201 #define RTC_FREQ 1024
1203 static void enable_sigio_timer(int fd
)
1205 struct sigaction act
;
1208 sigfillset(&act
.sa_mask
);
1210 act
.sa_handler
= host_alarm_handler
;
1212 sigaction(SIGIO
, &act
, NULL
);
1213 fcntl_setfl(fd
, O_ASYNC
);
1214 fcntl(fd
, F_SETOWN
, getpid());
1217 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1219 struct hpet_info info
;
1222 fd
= qemu_open("/dev/hpet", O_RDONLY
);
1227 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1229 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1230 "error, but for better emulation accuracy type:\n"
1231 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1235 /* Check capabilities */
1236 r
= ioctl(fd
, HPET_INFO
, &info
);
1240 /* Enable periodic mode */
1241 r
= ioctl(fd
, HPET_EPI
, 0);
1242 if (info
.hi_flags
&& (r
< 0))
1245 /* Enable interrupt */
1246 r
= ioctl(fd
, HPET_IE_ON
, 0);
1250 enable_sigio_timer(fd
);
1251 t
->priv
= (void *)(long)fd
;
1259 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1261 int fd
= (long)t
->priv
;
1266 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1269 unsigned long current_rtc_freq
= 0;
1271 TFR(rtc_fd
= qemu_open("/dev/rtc", O_RDONLY
));
1274 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1275 if (current_rtc_freq
!= RTC_FREQ
&&
1276 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1277 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1278 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1279 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1282 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1288 enable_sigio_timer(rtc_fd
);
1290 t
->priv
= (void *)(long)rtc_fd
;
1295 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1297 int rtc_fd
= (long)t
->priv
;
1302 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1306 struct sigaction act
;
1308 sigfillset(&act
.sa_mask
);
1310 act
.sa_handler
= host_alarm_handler
;
1312 sigaction(SIGALRM
, &act
, NULL
);
1315 * Initialize ev struct to 0 to avoid valgrind complaining
1316 * about uninitialized data in timer_create call
1318 memset(&ev
, 0, sizeof(ev
));
1319 ev
.sigev_value
.sival_int
= 0;
1320 ev
.sigev_notify
= SIGEV_SIGNAL
;
1321 ev
.sigev_signo
= SIGALRM
;
1323 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1324 perror("timer_create");
1326 /* disable dynticks */
1327 fprintf(stderr
, "Dynamic Ticks disabled\n");
1332 t
->priv
= (void *)(long)host_timer
;
1337 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1339 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1341 timer_delete(host_timer
);
1344 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1346 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1347 struct itimerspec timeout
;
1348 int64_t nearest_delta_us
= INT64_MAX
;
1351 assert(alarm_has_dynticks(t
));
1352 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1353 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1354 !active_timers
[QEMU_CLOCK_HOST
])
1357 nearest_delta_us
= qemu_next_deadline_dyntick();
1359 /* check whether a timer is already running */
1360 if (timer_gettime(host_timer
, &timeout
)) {
1362 fprintf(stderr
, "Internal timer error: aborting\n");
1365 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1366 if (current_us
&& current_us
<= nearest_delta_us
)
1369 timeout
.it_interval
.tv_sec
= 0;
1370 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1371 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1372 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1373 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1375 fprintf(stderr
, "Internal timer error: aborting\n");
1380 #endif /* defined(__linux__) */
1382 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1384 struct sigaction act
;
1385 struct itimerval itv
;
1389 sigfillset(&act
.sa_mask
);
1391 act
.sa_handler
= host_alarm_handler
;
1393 sigaction(SIGALRM
, &act
, NULL
);
1395 itv
.it_interval
.tv_sec
= 0;
1396 /* for i386 kernel 2.6 to get 1 ms */
1397 itv
.it_interval
.tv_usec
= 999;
1398 itv
.it_value
.tv_sec
= 0;
1399 itv
.it_value
.tv_usec
= 10 * 1000;
1401 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1408 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1410 struct itimerval itv
;
1412 memset(&itv
, 0, sizeof(itv
));
1413 setitimer(ITIMER_REAL
, &itv
, NULL
);
1416 #endif /* !defined(_WIN32) */
1421 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1424 struct qemu_alarm_win32
*data
= t
->priv
;
1427 memset(&tc
, 0, sizeof(tc
));
1428 timeGetDevCaps(&tc
, sizeof(tc
));
1430 data
->period
= tc
.wPeriodMin
;
1431 timeBeginPeriod(data
->period
);
1433 flags
= TIME_CALLBACK_FUNCTION
;
1434 if (alarm_has_dynticks(t
))
1435 flags
|= TIME_ONESHOT
;
1437 flags
|= TIME_PERIODIC
;
1439 data
->timerId
= timeSetEvent(1, // interval (ms)
1440 data
->period
, // resolution
1441 host_alarm_handler
, // function
1442 (DWORD
)t
, // parameter
1445 if (!data
->timerId
) {
1446 fprintf(stderr
, "Failed to initialize win32 alarm timer: %ld\n",
1448 timeEndPeriod(data
->period
);
1455 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1457 struct qemu_alarm_win32
*data
= t
->priv
;
1459 timeKillEvent(data
->timerId
);
1460 timeEndPeriod(data
->period
);
1463 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1465 struct qemu_alarm_win32
*data
= t
->priv
;
1467 assert(alarm_has_dynticks(t
));
1468 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1469 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1470 !active_timers
[QEMU_CLOCK_HOST
])
1473 timeKillEvent(data
->timerId
);
1475 data
->timerId
= timeSetEvent(1,
1479 TIME_ONESHOT
| TIME_CALLBACK_FUNCTION
);
1481 if (!data
->timerId
) {
1482 fprintf(stderr
, "Failed to re-arm win32 alarm timer %ld\n",
1485 timeEndPeriod(data
->period
);
1492 static void alarm_timer_on_change_state_rearm(void *opaque
, int running
, int reason
)
1495 qemu_rearm_alarm_timer((struct qemu_alarm_timer
*) opaque
);
1498 static int init_timer_alarm(void)
1500 struct qemu_alarm_timer
*t
= NULL
;
1503 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1504 t
= &alarm_timers
[i
];
1516 /* first event is at time 0 */
1519 qemu_add_vm_change_state_handler(alarm_timer_on_change_state_rearm
, t
);
1527 static void quit_timers(void)
1529 struct qemu_alarm_timer
*t
= alarm_timer
;
1534 /***********************************************************/
1535 /* host time/date access */
1536 void qemu_get_timedate(struct tm
*tm
, int offset
)
1543 if (rtc_date_offset
== -1) {
1547 ret
= localtime(&ti
);
1549 ti
-= rtc_date_offset
;
1553 memcpy(tm
, ret
, sizeof(struct tm
));
1556 int qemu_timedate_diff(struct tm
*tm
)
1560 if (rtc_date_offset
== -1)
1562 seconds
= mktimegm(tm
);
1564 seconds
= mktime(tm
);
1566 seconds
= mktimegm(tm
) + rtc_date_offset
;
1568 return seconds
- time(NULL
);
1571 void rtc_change_mon_event(struct tm
*tm
)
1575 data
= qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm
));
1576 monitor_protocol_event(QEVENT_RTC_CHANGE
, data
);
1577 qobject_decref(data
);
1580 static void configure_rtc_date_offset(const char *startdate
, int legacy
)
1582 time_t rtc_start_date
;
1585 if (!strcmp(startdate
, "now") && legacy
) {
1586 rtc_date_offset
= -1;
1588 if (sscanf(startdate
, "%d-%d-%dT%d:%d:%d",
1596 } else if (sscanf(startdate
, "%d-%d-%d",
1599 &tm
.tm_mday
) == 3) {
1608 rtc_start_date
= mktimegm(&tm
);
1609 if (rtc_start_date
== -1) {
1611 fprintf(stderr
, "Invalid date format. Valid formats are:\n"
1612 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1615 rtc_date_offset
= time(NULL
) - rtc_start_date
;
1619 static void configure_rtc(QemuOpts
*opts
)
1623 value
= qemu_opt_get(opts
, "base");
1625 if (!strcmp(value
, "utc")) {
1627 } else if (!strcmp(value
, "localtime")) {
1630 configure_rtc_date_offset(value
, 0);
1633 value
= qemu_opt_get(opts
, "clock");
1635 if (!strcmp(value
, "host")) {
1636 rtc_clock
= host_clock
;
1637 } else if (!strcmp(value
, "vm")) {
1638 rtc_clock
= vm_clock
;
1640 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1644 #ifdef CONFIG_TARGET_I386
1645 value
= qemu_opt_get(opts
, "driftfix");
1647 if (!strcmp(buf
, "slew")) {
1649 } else if (!strcmp(buf
, "none")) {
1652 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1660 static void socket_cleanup(void)
1665 static int socket_init(void)
1670 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1672 err
= WSAGetLastError();
1673 fprintf(stderr
, "WSAStartup: %d\n", err
);
1676 atexit(socket_cleanup
);
1681 /***********************************************************/
1682 /* Bluetooth support */
1685 static struct HCIInfo
*hci_table
[MAX_NICS
];
1687 static struct bt_vlan_s
{
1688 struct bt_scatternet_s net
;
1690 struct bt_vlan_s
*next
;
1693 /* find or alloc a new bluetooth "VLAN" */
1694 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1696 struct bt_vlan_s
**pvlan
, *vlan
;
1697 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1701 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1703 pvlan
= &first_bt_vlan
;
1704 while (*pvlan
!= NULL
)
1705 pvlan
= &(*pvlan
)->next
;
1710 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1714 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1719 static struct HCIInfo null_hci
= {
1720 .cmd_send
= null_hci_send
,
1721 .sco_send
= null_hci_send
,
1722 .acl_send
= null_hci_send
,
1723 .bdaddr_set
= null_hci_addr_set
,
1726 struct HCIInfo
*qemu_next_hci(void)
1728 if (cur_hci
== nb_hcis
)
1731 return hci_table
[cur_hci
++];
1734 static struct HCIInfo
*hci_init(const char *str
)
1737 struct bt_scatternet_s
*vlan
= 0;
1739 if (!strcmp(str
, "null"))
1742 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
1744 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
1745 else if (!strncmp(str
, "hci", 3)) {
1748 if (!strncmp(str
+ 3, ",vlan=", 6)) {
1749 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
1754 vlan
= qemu_find_bt_vlan(0);
1756 return bt_new_hci(vlan
);
1759 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
1764 static int bt_hci_parse(const char *str
)
1766 struct HCIInfo
*hci
;
1769 if (nb_hcis
>= MAX_NICS
) {
1770 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
1774 hci
= hci_init(str
);
1783 bdaddr
.b
[5] = 0x56 + nb_hcis
;
1784 hci
->bdaddr_set(hci
, bdaddr
.b
);
1786 hci_table
[nb_hcis
++] = hci
;
1791 static void bt_vhci_add(int vlan_id
)
1793 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
1796 fprintf(stderr
, "qemu: warning: adding a VHCI to "
1797 "an empty scatternet %i\n", vlan_id
);
1799 bt_vhci_init(bt_new_hci(vlan
));
1802 static struct bt_device_s
*bt_device_add(const char *opt
)
1804 struct bt_scatternet_s
*vlan
;
1806 char *endp
= strstr(opt
, ",vlan=");
1807 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
1810 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
1813 vlan_id
= strtol(endp
+ 6, &endp
, 0);
1815 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
1820 vlan
= qemu_find_bt_vlan(vlan_id
);
1823 fprintf(stderr
, "qemu: warning: adding a slave device to "
1824 "an empty scatternet %i\n", vlan_id
);
1826 if (!strcmp(devname
, "keyboard"))
1827 return bt_keyboard_init(vlan
);
1829 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
1833 static int bt_parse(const char *opt
)
1835 const char *endp
, *p
;
1838 if (strstart(opt
, "hci", &endp
)) {
1839 if (!*endp
|| *endp
== ',') {
1841 if (!strstart(endp
, ",vlan=", 0))
1844 return bt_hci_parse(opt
);
1846 } else if (strstart(opt
, "vhci", &endp
)) {
1847 if (!*endp
|| *endp
== ',') {
1849 if (strstart(endp
, ",vlan=", &p
)) {
1850 vlan
= strtol(p
, (char **) &endp
, 0);
1852 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
1856 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
1865 } else if (strstart(opt
, "device:", &endp
))
1866 return !bt_device_add(endp
);
1868 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
1872 /***********************************************************/
1873 /* QEMU Block devices */
1875 #define HD_ALIAS "index=%d,media=disk"
1876 #define CDROM_ALIAS "index=2,media=cdrom"
1877 #define FD_ALIAS "index=%d,if=floppy"
1878 #define PFLASH_ALIAS "if=pflash"
1879 #define MTD_ALIAS "if=mtd"
1880 #define SD_ALIAS "index=0,if=sd"
1882 QemuOpts
*drive_add(const char *file
, const char *fmt
, ...)
1889 vsnprintf(optstr
, sizeof(optstr
), fmt
, ap
);
1892 opts
= qemu_opts_parse(&qemu_drive_opts
, optstr
, 0);
1894 fprintf(stderr
, "%s: huh? duplicate? (%s)\n",
1895 __FUNCTION__
, optstr
);
1899 qemu_opt_set(opts
, "file", file
);
1903 DriveInfo
*drive_get(BlockInterfaceType type
, int bus
, int unit
)
1907 /* seek interface, bus and unit */
1909 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1910 if (dinfo
->type
== type
&&
1911 dinfo
->bus
== bus
&&
1912 dinfo
->unit
== unit
)
1919 DriveInfo
*drive_get_by_id(const char *id
)
1923 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1924 if (strcmp(id
, dinfo
->id
))
1931 int drive_get_max_bus(BlockInterfaceType type
)
1937 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1938 if(dinfo
->type
== type
&&
1939 dinfo
->bus
> max_bus
)
1940 max_bus
= dinfo
->bus
;
1945 const char *drive_get_serial(BlockDriverState
*bdrv
)
1949 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1950 if (dinfo
->bdrv
== bdrv
)
1951 return dinfo
->serial
;
1957 BlockInterfaceErrorAction
drive_get_on_error(
1958 BlockDriverState
*bdrv
, int is_read
)
1962 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1963 if (dinfo
->bdrv
== bdrv
)
1964 return is_read
? dinfo
->on_read_error
: dinfo
->on_write_error
;
1967 return is_read
? BLOCK_ERR_REPORT
: BLOCK_ERR_STOP_ENOSPC
;
1970 static void bdrv_format_print(void *opaque
, const char *name
)
1972 fprintf(stderr
, " %s", name
);
1975 void drive_uninit(DriveInfo
*dinfo
)
1977 qemu_opts_del(dinfo
->opts
);
1978 bdrv_delete(dinfo
->bdrv
);
1979 QTAILQ_REMOVE(&drives
, dinfo
, next
);
1983 static int parse_block_error_action(const char *buf
, int is_read
)
1985 if (!strcmp(buf
, "ignore")) {
1986 return BLOCK_ERR_IGNORE
;
1987 } else if (!is_read
&& !strcmp(buf
, "enospc")) {
1988 return BLOCK_ERR_STOP_ENOSPC
;
1989 } else if (!strcmp(buf
, "stop")) {
1990 return BLOCK_ERR_STOP_ANY
;
1991 } else if (!strcmp(buf
, "report")) {
1992 return BLOCK_ERR_REPORT
;
1994 fprintf(stderr
, "qemu: '%s' invalid %s error action\n",
1995 buf
, is_read
? "read" : "write");
2000 DriveInfo
*drive_init(QemuOpts
*opts
, void *opaque
,
2004 const char *file
= NULL
;
2007 const char *mediastr
= "";
2008 BlockInterfaceType type
;
2009 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
2010 int bus_id
, unit_id
;
2011 int cyls
, heads
, secs
, translation
;
2012 BlockDriver
*drv
= NULL
;
2013 QEMUMachine
*machine
= opaque
;
2020 int on_read_error
, on_write_error
;
2021 const char *devaddr
;
2027 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2030 if (machine
&& machine
->use_scsi
) {
2032 max_devs
= MAX_SCSI_DEVS
;
2033 pstrcpy(devname
, sizeof(devname
), "scsi");
2036 max_devs
= MAX_IDE_DEVS
;
2037 pstrcpy(devname
, sizeof(devname
), "ide");
2041 /* extract parameters */
2042 bus_id
= qemu_opt_get_number(opts
, "bus", 0);
2043 unit_id
= qemu_opt_get_number(opts
, "unit", -1);
2044 index
= qemu_opt_get_number(opts
, "index", -1);
2046 cyls
= qemu_opt_get_number(opts
, "cyls", 0);
2047 heads
= qemu_opt_get_number(opts
, "heads", 0);
2048 secs
= qemu_opt_get_number(opts
, "secs", 0);
2050 snapshot
= qemu_opt_get_bool(opts
, "snapshot", 0);
2051 ro
= qemu_opt_get_bool(opts
, "readonly", 0);
2053 file
= qemu_opt_get(opts
, "file");
2054 serial
= qemu_opt_get(opts
, "serial");
2056 if ((buf
= qemu_opt_get(opts
, "if")) != NULL
) {
2057 pstrcpy(devname
, sizeof(devname
), buf
);
2058 if (!strcmp(buf
, "ide")) {
2060 max_devs
= MAX_IDE_DEVS
;
2061 } else if (!strcmp(buf
, "scsi")) {
2063 max_devs
= MAX_SCSI_DEVS
;
2064 } else if (!strcmp(buf
, "floppy")) {
2067 } else if (!strcmp(buf
, "pflash")) {
2070 } else if (!strcmp(buf
, "mtd")) {
2073 } else if (!strcmp(buf
, "sd")) {
2076 } else if (!strcmp(buf
, "virtio")) {
2079 } else if (!strcmp(buf
, "xen")) {
2082 } else if (!strcmp(buf
, "none")) {
2086 fprintf(stderr
, "qemu: unsupported bus type '%s'\n", buf
);
2091 if (cyls
|| heads
|| secs
) {
2092 if (cyls
< 1 || (type
== IF_IDE
&& cyls
> 16383)) {
2093 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", buf
);
2096 if (heads
< 1 || (type
== IF_IDE
&& heads
> 16)) {
2097 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", buf
);
2100 if (secs
< 1 || (type
== IF_IDE
&& secs
> 63)) {
2101 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", buf
);
2106 if ((buf
= qemu_opt_get(opts
, "trans")) != NULL
) {
2109 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2113 if (!strcmp(buf
, "none"))
2114 translation
= BIOS_ATA_TRANSLATION_NONE
;
2115 else if (!strcmp(buf
, "lba"))
2116 translation
= BIOS_ATA_TRANSLATION_LBA
;
2117 else if (!strcmp(buf
, "auto"))
2118 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2120 fprintf(stderr
, "qemu: '%s' invalid translation type\n", buf
);
2125 if ((buf
= qemu_opt_get(opts
, "media")) != NULL
) {
2126 if (!strcmp(buf
, "disk")) {
2128 } else if (!strcmp(buf
, "cdrom")) {
2129 if (cyls
|| secs
|| heads
) {
2131 "qemu: '%s' invalid physical CHS format\n", buf
);
2134 media
= MEDIA_CDROM
;
2136 fprintf(stderr
, "qemu: '%s' invalid media\n", buf
);
2141 if ((buf
= qemu_opt_get(opts
, "cache")) != NULL
) {
2142 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2144 else if (!strcmp(buf
, "writethrough"))
2146 else if (!strcmp(buf
, "writeback"))
2149 fprintf(stderr
, "qemu: invalid cache option\n");
2154 #ifdef CONFIG_LINUX_AIO
2155 if ((buf
= qemu_opt_get(opts
, "aio")) != NULL
) {
2156 if (!strcmp(buf
, "threads"))
2158 else if (!strcmp(buf
, "native"))
2161 fprintf(stderr
, "qemu: invalid aio option\n");
2167 if ((buf
= qemu_opt_get(opts
, "format")) != NULL
) {
2168 if (strcmp(buf
, "?") == 0) {
2169 fprintf(stderr
, "qemu: Supported formats:");
2170 bdrv_iterate_format(bdrv_format_print
, NULL
);
2171 fprintf(stderr
, "\n");
2174 drv
= bdrv_find_whitelisted_format(buf
);
2176 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2181 on_write_error
= BLOCK_ERR_STOP_ENOSPC
;
2182 if ((buf
= qemu_opt_get(opts
, "werror")) != NULL
) {
2183 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2184 fprintf(stderr
, "werror is no supported by this format\n");
2188 on_write_error
= parse_block_error_action(buf
, 0);
2189 if (on_write_error
< 0) {
2194 on_read_error
= BLOCK_ERR_REPORT
;
2195 if ((buf
= qemu_opt_get(opts
, "rerror")) != NULL
) {
2196 if (type
!= IF_IDE
&& type
!= IF_VIRTIO
) {
2197 fprintf(stderr
, "rerror is no supported by this format\n");
2201 on_read_error
= parse_block_error_action(buf
, 1);
2202 if (on_read_error
< 0) {
2207 if ((devaddr
= qemu_opt_get(opts
, "addr")) != NULL
) {
2208 if (type
!= IF_VIRTIO
) {
2209 fprintf(stderr
, "addr is not supported\n");
2214 /* compute bus and unit according index */
2217 if (bus_id
!= 0 || unit_id
!= -1) {
2219 "qemu: index cannot be used with bus and unit\n");
2227 unit_id
= index
% max_devs
;
2228 bus_id
= index
/ max_devs
;
2232 /* if user doesn't specify a unit_id,
2233 * try to find the first free
2236 if (unit_id
== -1) {
2238 while (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2240 if (max_devs
&& unit_id
>= max_devs
) {
2241 unit_id
-= max_devs
;
2249 if (max_devs
&& unit_id
>= max_devs
) {
2250 fprintf(stderr
, "qemu: unit %d too big (max is %d)\n",
2251 unit_id
, max_devs
- 1);
2256 * ignore multiple definitions
2259 if (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2266 dinfo
= qemu_mallocz(sizeof(*dinfo
));
2267 if ((buf
= qemu_opts_id(opts
)) != NULL
) {
2268 dinfo
->id
= qemu_strdup(buf
);
2270 /* no id supplied -> create one */
2271 dinfo
->id
= qemu_mallocz(32);
2272 if (type
== IF_IDE
|| type
== IF_SCSI
)
2273 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2275 snprintf(dinfo
->id
, 32, "%s%i%s%i",
2276 devname
, bus_id
, mediastr
, unit_id
);
2278 snprintf(dinfo
->id
, 32, "%s%s%i",
2279 devname
, mediastr
, unit_id
);
2281 dinfo
->bdrv
= bdrv_new(dinfo
->id
);
2282 dinfo
->devaddr
= devaddr
;
2284 dinfo
->bus
= bus_id
;
2285 dinfo
->unit
= unit_id
;
2286 dinfo
->on_read_error
= on_read_error
;
2287 dinfo
->on_write_error
= on_write_error
;
2290 strncpy(dinfo
->serial
, serial
, sizeof(serial
));
2291 QTAILQ_INSERT_TAIL(&drives
, dinfo
, next
);
2301 bdrv_set_geometry_hint(dinfo
->bdrv
, cyls
, heads
, secs
);
2302 bdrv_set_translation_hint(dinfo
->bdrv
, translation
);
2306 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_CDROM
);
2311 /* FIXME: This isn't really a floppy, but it's a reasonable
2314 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_FLOPPY
);
2320 /* add virtio block device */
2321 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
2322 qemu_opt_set(opts
, "driver", "virtio-blk-pci");
2323 qemu_opt_set(opts
, "drive", dinfo
->id
);
2325 qemu_opt_set(opts
, "addr", devaddr
);
2336 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2337 cache
= 2; /* always use write-back with snapshot */
2339 if (cache
== 0) /* no caching */
2340 bdrv_flags
|= BDRV_O_NOCACHE
;
2341 else if (cache
== 2) /* write-back */
2342 bdrv_flags
|= BDRV_O_CACHE_WB
;
2345 bdrv_flags
|= BDRV_O_NATIVE_AIO
;
2347 bdrv_flags
&= ~BDRV_O_NATIVE_AIO
;
2351 if (type
!= IF_SCSI
&& type
!= IF_VIRTIO
&& type
!= IF_FLOPPY
) {
2352 fprintf(stderr
, "qemu: readonly flag not supported for drive with this interface\n");
2357 * cdrom is read-only. Set it now, after above interface checking
2358 * since readonly attribute not explicitly required, so no error.
2360 if (media
== MEDIA_CDROM
) {
2363 bdrv_flags
|= ro
? 0 : BDRV_O_RDWR
;
2365 if (bdrv_open2(dinfo
->bdrv
, file
, bdrv_flags
, drv
) < 0) {
2366 fprintf(stderr
, "qemu: could not open disk image %s: %s\n",
2367 file
, strerror(errno
));
2371 if (bdrv_key_required(dinfo
->bdrv
))
2377 static int drive_init_func(QemuOpts
*opts
, void *opaque
)
2379 QEMUMachine
*machine
= opaque
;
2380 int fatal_error
= 0;
2382 if (drive_init(opts
, machine
, &fatal_error
) == NULL
) {
2389 static int drive_enable_snapshot(QemuOpts
*opts
, void *opaque
)
2391 if (NULL
== qemu_opt_get(opts
, "snapshot")) {
2392 qemu_opt_set(opts
, "snapshot", "on");
2397 void qemu_register_boot_set(QEMUBootSetHandler
*func
, void *opaque
)
2399 boot_set_handler
= func
;
2400 boot_set_opaque
= opaque
;
2403 int qemu_boot_set(const char *boot_devices
)
2405 if (!boot_set_handler
) {
2408 return boot_set_handler(boot_set_opaque
, boot_devices
);
2411 static int parse_bootdevices(char *devices
)
2413 /* We just do some generic consistency checks */
2417 for (p
= devices
; *p
!= '\0'; p
++) {
2418 /* Allowed boot devices are:
2419 * a-b: floppy disk drives
2420 * c-f: IDE disk drives
2421 * g-m: machine implementation dependant drives
2422 * n-p: network devices
2423 * It's up to each machine implementation to check if the given boot
2424 * devices match the actual hardware implementation and firmware
2427 if (*p
< 'a' || *p
> 'p') {
2428 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
2431 if (bitmap
& (1 << (*p
- 'a'))) {
2432 fprintf(stderr
, "Boot device '%c' was given twice\n", *p
);
2435 bitmap
|= 1 << (*p
- 'a');
2440 static void restore_boot_devices(void *opaque
)
2442 char *standard_boot_devices
= opaque
;
2444 qemu_boot_set(standard_boot_devices
);
2446 qemu_unregister_reset(restore_boot_devices
, standard_boot_devices
);
2447 qemu_free(standard_boot_devices
);
2450 static void numa_add(const char *optarg
)
2454 unsigned long long value
, endvalue
;
2457 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2458 if (!strcmp(option
, "node")) {
2459 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2460 nodenr
= nb_numa_nodes
;
2462 nodenr
= strtoull(option
, NULL
, 10);
2465 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2466 node_mem
[nodenr
] = 0;
2468 value
= strtoull(option
, &endptr
, 0);
2470 case 0: case 'M': case 'm':
2477 node_mem
[nodenr
] = value
;
2479 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2480 node_cpumask
[nodenr
] = 0;
2482 value
= strtoull(option
, &endptr
, 10);
2485 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2487 if (*endptr
== '-') {
2488 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2489 if (endvalue
>= 63) {
2492 "only 63 CPUs in NUMA mode supported.\n");
2494 value
= (2ULL << endvalue
) - (1ULL << value
);
2496 value
= 1ULL << value
;
2499 node_cpumask
[nodenr
] = value
;
2506 static void smp_parse(const char *optarg
)
2508 int smp
, sockets
= 0, threads
= 0, cores
= 0;
2512 smp
= strtoul(optarg
, &endptr
, 10);
2513 if (endptr
!= optarg
) {
2514 if (*endptr
== ',') {
2518 if (get_param_value(option
, 128, "sockets", endptr
) != 0)
2519 sockets
= strtoull(option
, NULL
, 10);
2520 if (get_param_value(option
, 128, "cores", endptr
) != 0)
2521 cores
= strtoull(option
, NULL
, 10);
2522 if (get_param_value(option
, 128, "threads", endptr
) != 0)
2523 threads
= strtoull(option
, NULL
, 10);
2524 if (get_param_value(option
, 128, "maxcpus", endptr
) != 0)
2525 max_cpus
= strtoull(option
, NULL
, 10);
2527 /* compute missing values, prefer sockets over cores over threads */
2528 if (smp
== 0 || sockets
== 0) {
2529 sockets
= sockets
> 0 ? sockets
: 1;
2530 cores
= cores
> 0 ? cores
: 1;
2531 threads
= threads
> 0 ? threads
: 1;
2533 smp
= cores
* threads
* sockets
;
2537 threads
= threads
> 0 ? threads
: 1;
2538 cores
= smp
/ (sockets
* threads
);
2541 threads
= smp
/ (cores
* sockets
);
2546 smp_cores
= cores
> 0 ? cores
: 1;
2547 smp_threads
= threads
> 0 ? threads
: 1;
2549 max_cpus
= smp_cpus
;
2552 /***********************************************************/
2555 static int usb_device_add(const char *devname
, int is_hotplug
)
2558 USBDevice
*dev
= NULL
;
2563 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2564 dev
= usbdevice_create(devname
);
2568 /* the other ones */
2569 if (strstart(devname
, "host:", &p
)) {
2570 dev
= usb_host_device_open(p
);
2571 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2572 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2573 bt_new_hci(qemu_find_bt_vlan(0)));
2584 static int usb_device_del(const char *devname
)
2589 if (strstart(devname
, "host:", &p
))
2590 return usb_host_device_close(p
);
2595 p
= strchr(devname
, '.');
2598 bus_num
= strtoul(devname
, NULL
, 0);
2599 addr
= strtoul(p
+ 1, NULL
, 0);
2601 return usb_device_delete_addr(bus_num
, addr
);
2604 static int usb_parse(const char *cmdline
)
2607 r
= usb_device_add(cmdline
, 0);
2609 fprintf(stderr
, "qemu: could not add USB device '%s'\n", cmdline
);
2614 void do_usb_add(Monitor
*mon
, const QDict
*qdict
)
2616 const char *devname
= qdict_get_str(qdict
, "devname");
2617 if (usb_device_add(devname
, 1) < 0) {
2618 error_report("could not add USB device '%s'", devname
);
2622 void do_usb_del(Monitor
*mon
, const QDict
*qdict
)
2624 const char *devname
= qdict_get_str(qdict
, "devname");
2625 if (usb_device_del(devname
) < 0) {
2626 error_report("could not delete USB device '%s'", devname
);
2630 /***********************************************************/
2631 /* PCMCIA/Cardbus */
2633 static struct pcmcia_socket_entry_s
{
2634 PCMCIASocket
*socket
;
2635 struct pcmcia_socket_entry_s
*next
;
2636 } *pcmcia_sockets
= 0;
2638 void pcmcia_socket_register(PCMCIASocket
*socket
)
2640 struct pcmcia_socket_entry_s
*entry
;
2642 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2643 entry
->socket
= socket
;
2644 entry
->next
= pcmcia_sockets
;
2645 pcmcia_sockets
= entry
;
2648 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2650 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2652 ptr
= &pcmcia_sockets
;
2653 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2654 if (entry
->socket
== socket
) {
2660 void pcmcia_info(Monitor
*mon
)
2662 struct pcmcia_socket_entry_s
*iter
;
2664 if (!pcmcia_sockets
)
2665 monitor_printf(mon
, "No PCMCIA sockets\n");
2667 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2668 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2669 iter
->socket
->attached
? iter
->socket
->card_string
:
2673 /***********************************************************/
2676 typedef struct IOHandlerRecord
{
2678 IOCanRWHandler
*fd_read_poll
;
2680 IOHandler
*fd_write
;
2683 /* temporary data */
2685 struct IOHandlerRecord
*next
;
2688 static IOHandlerRecord
*first_io_handler
;
2690 /* XXX: fd_read_poll should be suppressed, but an API change is
2691 necessary in the character devices to suppress fd_can_read(). */
2692 int qemu_set_fd_handler2(int fd
,
2693 IOCanRWHandler
*fd_read_poll
,
2695 IOHandler
*fd_write
,
2698 IOHandlerRecord
**pioh
, *ioh
;
2700 if (!fd_read
&& !fd_write
) {
2701 pioh
= &first_io_handler
;
2706 if (ioh
->fd
== fd
) {
2713 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
2717 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
2718 ioh
->next
= first_io_handler
;
2719 first_io_handler
= ioh
;
2722 ioh
->fd_read_poll
= fd_read_poll
;
2723 ioh
->fd_read
= fd_read
;
2724 ioh
->fd_write
= fd_write
;
2725 ioh
->opaque
= opaque
;
2731 int qemu_set_fd_handler(int fd
,
2733 IOHandler
*fd_write
,
2736 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
2740 /***********************************************************/
2741 /* Polling handling */
2743 typedef struct PollingEntry
{
2746 struct PollingEntry
*next
;
2749 static PollingEntry
*first_polling_entry
;
2751 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
2753 PollingEntry
**ppe
, *pe
;
2754 pe
= qemu_mallocz(sizeof(PollingEntry
));
2756 pe
->opaque
= opaque
;
2757 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
2762 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
2764 PollingEntry
**ppe
, *pe
;
2765 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
2767 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
2775 /***********************************************************/
2776 /* Wait objects support */
2777 typedef struct WaitObjects
{
2779 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
2780 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
2781 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
2784 static WaitObjects wait_objects
= {0};
2786 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2788 WaitObjects
*w
= &wait_objects
;
2790 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
2792 w
->events
[w
->num
] = handle
;
2793 w
->func
[w
->num
] = func
;
2794 w
->opaque
[w
->num
] = opaque
;
2799 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2802 WaitObjects
*w
= &wait_objects
;
2805 for (i
= 0; i
< w
->num
; i
++) {
2806 if (w
->events
[i
] == handle
)
2809 w
->events
[i
] = w
->events
[i
+ 1];
2810 w
->func
[i
] = w
->func
[i
+ 1];
2811 w
->opaque
[i
] = w
->opaque
[i
+ 1];
2819 /***********************************************************/
2820 /* ram save/restore */
2822 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2823 #define RAM_SAVE_FLAG_COMPRESS 0x02
2824 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2825 #define RAM_SAVE_FLAG_PAGE 0x08
2826 #define RAM_SAVE_FLAG_EOS 0x10
2828 static int is_dup_page(uint8_t *page
, uint8_t ch
)
2830 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
2831 uint32_t *array
= (uint32_t *)page
;
2834 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
2835 if (array
[i
] != val
)
2842 static int ram_save_block(QEMUFile
*f
)
2844 static ram_addr_t current_addr
= 0;
2845 ram_addr_t saved_addr
= current_addr
;
2846 ram_addr_t addr
= 0;
2849 while (addr
< last_ram_offset
) {
2850 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
2853 cpu_physical_memory_reset_dirty(current_addr
,
2854 current_addr
+ TARGET_PAGE_SIZE
,
2855 MIGRATION_DIRTY_FLAG
);
2857 p
= qemu_get_ram_ptr(current_addr
);
2859 if (is_dup_page(p
, *p
)) {
2860 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
2861 qemu_put_byte(f
, *p
);
2863 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
2864 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
2870 addr
+= TARGET_PAGE_SIZE
;
2871 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
2877 static uint64_t bytes_transferred
;
2879 static ram_addr_t
ram_save_remaining(void)
2882 ram_addr_t count
= 0;
2884 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2885 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2892 uint64_t ram_bytes_remaining(void)
2894 return ram_save_remaining() * TARGET_PAGE_SIZE
;
2897 uint64_t ram_bytes_transferred(void)
2899 return bytes_transferred
;
2902 uint64_t ram_bytes_total(void)
2904 return last_ram_offset
;
2907 static int ram_save_live(Monitor
*mon
, QEMUFile
*f
, int stage
, void *opaque
)
2910 uint64_t bytes_transferred_last
;
2912 uint64_t expected_time
= 0;
2915 cpu_physical_memory_set_dirty_tracking(0);
2919 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX
) != 0) {
2920 qemu_file_set_error(f
);
2925 bytes_transferred
= 0;
2927 /* Make sure all dirty bits are set */
2928 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2929 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2930 cpu_physical_memory_set_dirty(addr
);
2933 /* Enable dirty memory tracking */
2934 cpu_physical_memory_set_dirty_tracking(1);
2936 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
2939 bytes_transferred_last
= bytes_transferred
;
2940 bwidth
= qemu_get_clock_ns(rt_clock
);
2942 while (!qemu_file_rate_limit(f
)) {
2945 ret
= ram_save_block(f
);
2946 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
2947 if (ret
== 0) /* no more blocks */
2951 bwidth
= qemu_get_clock_ns(rt_clock
) - bwidth
;
2952 bwidth
= (bytes_transferred
- bytes_transferred_last
) / bwidth
;
2954 /* if we haven't transferred anything this round, force expected_time to a
2955 * a very high value, but without crashing */
2959 /* try transferring iterative blocks of memory */
2961 /* flush all remaining blocks regardless of rate limiting */
2962 while (ram_save_block(f
) != 0) {
2963 bytes_transferred
+= TARGET_PAGE_SIZE
;
2965 cpu_physical_memory_set_dirty_tracking(0);
2968 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
2970 expected_time
= ram_save_remaining() * TARGET_PAGE_SIZE
/ bwidth
;
2972 return (stage
== 2) && (expected_time
<= migrate_max_downtime());
2975 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
2980 if (version_id
!= 3)
2984 addr
= qemu_get_be64(f
);
2986 flags
= addr
& ~TARGET_PAGE_MASK
;
2987 addr
&= TARGET_PAGE_MASK
;
2989 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
2990 if (addr
!= last_ram_offset
)
2994 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
2995 uint8_t ch
= qemu_get_byte(f
);
2996 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
2999 (!kvm_enabled() || kvm_has_sync_mmu())) {
3000 madvise(qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
, MADV_DONTNEED
);
3003 } else if (flags
& RAM_SAVE_FLAG_PAGE
) {
3004 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
3006 if (qemu_file_has_error(f
)) {
3009 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
3014 void qemu_service_io(void)
3016 qemu_notify_event();
3019 /***********************************************************/
3020 /* machine registration */
3022 static QEMUMachine
*first_machine
= NULL
;
3023 QEMUMachine
*current_machine
= NULL
;
3025 int qemu_register_machine(QEMUMachine
*m
)
3028 pm
= &first_machine
;
3036 static QEMUMachine
*find_machine(const char *name
)
3040 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3041 if (!strcmp(m
->name
, name
))
3043 if (m
->alias
&& !strcmp(m
->alias
, name
))
3049 static QEMUMachine
*find_default_machine(void)
3053 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3054 if (m
->is_default
) {
3061 /***********************************************************/
3062 /* main execution loop */
3064 static void gui_update(void *opaque
)
3066 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3067 DisplayState
*ds
= opaque
;
3068 DisplayChangeListener
*dcl
= ds
->listeners
;
3070 qemu_flush_coalesced_mmio_buffer();
3073 while (dcl
!= NULL
) {
3074 if (dcl
->gui_timer_interval
&&
3075 dcl
->gui_timer_interval
< interval
)
3076 interval
= dcl
->gui_timer_interval
;
3079 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3082 static void nographic_update(void *opaque
)
3084 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3086 qemu_flush_coalesced_mmio_buffer();
3087 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3090 void cpu_synchronize_all_states(void)
3094 for (cpu
= first_cpu
; cpu
; cpu
= cpu
->next_cpu
) {
3095 cpu_synchronize_state(cpu
);
3099 void cpu_synchronize_all_post_reset(void)
3103 for (cpu
= first_cpu
; cpu
; cpu
= cpu
->next_cpu
) {
3104 cpu_synchronize_post_reset(cpu
);
3108 void cpu_synchronize_all_post_init(void)
3112 for (cpu
= first_cpu
; cpu
; cpu
= cpu
->next_cpu
) {
3113 cpu_synchronize_post_init(cpu
);
3117 struct vm_change_state_entry
{
3118 VMChangeStateHandler
*cb
;
3120 QLIST_ENTRY (vm_change_state_entry
) entries
;
3123 static QLIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3125 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3128 VMChangeStateEntry
*e
;
3130 e
= qemu_mallocz(sizeof (*e
));
3134 QLIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3138 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3140 QLIST_REMOVE (e
, entries
);
3144 static void vm_state_notify(int running
, int reason
)
3146 VMChangeStateEntry
*e
;
3148 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3149 e
->cb(e
->opaque
, running
, reason
);
3153 static void resume_all_vcpus(void);
3154 static void pause_all_vcpus(void);
3161 vm_state_notify(1, 0);
3166 /* reset/shutdown handler */
3168 typedef struct QEMUResetEntry
{
3169 QTAILQ_ENTRY(QEMUResetEntry
) entry
;
3170 QEMUResetHandler
*func
;
3174 static QTAILQ_HEAD(reset_handlers
, QEMUResetEntry
) reset_handlers
=
3175 QTAILQ_HEAD_INITIALIZER(reset_handlers
);
3176 static int reset_requested
;
3177 static int shutdown_requested
;
3178 static int powerdown_requested
;
3179 static int debug_requested
;
3180 static int vmstop_requested
;
3182 int qemu_shutdown_requested(void)
3184 int r
= shutdown_requested
;
3185 shutdown_requested
= 0;
3189 int qemu_reset_requested(void)
3191 int r
= reset_requested
;
3192 reset_requested
= 0;
3196 int qemu_powerdown_requested(void)
3198 int r
= powerdown_requested
;
3199 powerdown_requested
= 0;
3203 static int qemu_debug_requested(void)
3205 int r
= debug_requested
;
3206 debug_requested
= 0;
3210 static int qemu_vmstop_requested(void)
3212 int r
= vmstop_requested
;
3213 vmstop_requested
= 0;
3217 static void do_vm_stop(int reason
)
3220 cpu_disable_ticks();
3223 vm_state_notify(0, reason
);
3224 monitor_protocol_event(QEVENT_STOP
, NULL
);
3228 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3230 QEMUResetEntry
*re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3233 re
->opaque
= opaque
;
3234 QTAILQ_INSERT_TAIL(&reset_handlers
, re
, entry
);
3237 void qemu_unregister_reset(QEMUResetHandler
*func
, void *opaque
)
3241 QTAILQ_FOREACH(re
, &reset_handlers
, entry
) {
3242 if (re
->func
== func
&& re
->opaque
== opaque
) {
3243 QTAILQ_REMOVE(&reset_handlers
, re
, entry
);
3250 void qemu_system_reset(void)
3252 QEMUResetEntry
*re
, *nre
;
3254 /* reset all devices */
3255 QTAILQ_FOREACH_SAFE(re
, &reset_handlers
, entry
, nre
) {
3256 re
->func(re
->opaque
);
3258 monitor_protocol_event(QEVENT_RESET
, NULL
);
3259 cpu_synchronize_all_post_reset();
3262 void qemu_system_reset_request(void)
3265 shutdown_requested
= 1;
3267 reset_requested
= 1;
3269 qemu_notify_event();
3272 void qemu_system_shutdown_request(void)
3274 shutdown_requested
= 1;
3275 qemu_notify_event();
3278 void qemu_system_powerdown_request(void)
3280 powerdown_requested
= 1;
3281 qemu_notify_event();
3284 static int cpu_can_run(CPUState
*env
)
3295 static int cpu_has_work(CPUState
*env
)
3303 if (qemu_cpu_has_work(env
))
3308 static int tcg_has_work(void)
3312 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
3313 if (cpu_has_work(env
))
3319 static int io_thread_fd
= -1;
3321 static void qemu_event_increment(void)
3323 /* Write 8 bytes to be compatible with eventfd. */
3324 static uint64_t val
= 1;
3327 if (io_thread_fd
== -1)
3331 ret
= write(io_thread_fd
, &val
, sizeof(val
));
3332 } while (ret
< 0 && errno
== EINTR
);
3334 /* EAGAIN is fine, a read must be pending. */
3335 if (ret
< 0 && errno
!= EAGAIN
) {
3336 fprintf(stderr
, "qemu_event_increment: write() filed: %s\n",
3342 static void qemu_event_read(void *opaque
)
3344 int fd
= (unsigned long)opaque
;
3348 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
3350 len
= read(fd
, buffer
, sizeof(buffer
));
3351 } while ((len
== -1 && errno
== EINTR
) || len
== sizeof(buffer
));
3354 static int qemu_event_init(void)
3359 err
= qemu_eventfd(fds
);
3363 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3367 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3371 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3372 (void *)(unsigned long)fds
[0]);
3374 io_thread_fd
= fds
[1];
3383 HANDLE qemu_event_handle
;
3385 static void dummy_event_handler(void *opaque
)
3389 static int qemu_event_init(void)
3391 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3392 if (!qemu_event_handle
) {
3393 fprintf(stderr
, "Failed CreateEvent: %ld\n", GetLastError());
3396 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3400 static void qemu_event_increment(void)
3402 if (!SetEvent(qemu_event_handle
)) {
3403 fprintf(stderr
, "qemu_event_increment: SetEvent failed: %ld\n",
3410 #ifndef CONFIG_IOTHREAD
3411 static int qemu_init_main_loop(void)
3413 return qemu_event_init();
3416 void qemu_init_vcpu(void *_env
)
3418 CPUState
*env
= _env
;
3420 env
->nr_cores
= smp_cores
;
3421 env
->nr_threads
= smp_threads
;
3427 int qemu_cpu_self(void *env
)
3432 static void resume_all_vcpus(void)
3436 static void pause_all_vcpus(void)
3440 void qemu_cpu_kick(void *env
)
3445 void qemu_notify_event(void)
3447 CPUState
*env
= cpu_single_env
;
3449 qemu_event_increment ();
3453 if (next_cpu
&& env
!= next_cpu
) {
3458 void qemu_mutex_lock_iothread(void) {}
3459 void qemu_mutex_unlock_iothread(void) {}
3461 void vm_stop(int reason
)
3466 #else /* CONFIG_IOTHREAD */
3468 #include "qemu-thread.h"
3470 QemuMutex qemu_global_mutex
;
3471 static QemuMutex qemu_fair_mutex
;
3473 static QemuThread io_thread
;
3475 static QemuThread
*tcg_cpu_thread
;
3476 static QemuCond
*tcg_halt_cond
;
3478 static int qemu_system_ready
;
3480 static QemuCond qemu_cpu_cond
;
3482 static QemuCond qemu_system_cond
;
3483 static QemuCond qemu_pause_cond
;
3485 static void tcg_block_io_signals(void);
3486 static void kvm_block_io_signals(CPUState
*env
);
3487 static void unblock_io_signals(void);
3489 static int qemu_init_main_loop(void)
3493 ret
= qemu_event_init();
3497 qemu_cond_init(&qemu_pause_cond
);
3498 qemu_mutex_init(&qemu_fair_mutex
);
3499 qemu_mutex_init(&qemu_global_mutex
);
3500 qemu_mutex_lock(&qemu_global_mutex
);
3502 unblock_io_signals();
3503 qemu_thread_self(&io_thread
);
3508 static void qemu_wait_io_event_common(CPUState
*env
)
3513 qemu_cond_signal(&qemu_pause_cond
);
3517 static void qemu_wait_io_event(CPUState
*env
)
3519 while (!tcg_has_work())
3520 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3522 qemu_mutex_unlock(&qemu_global_mutex
);
3525 * Users of qemu_global_mutex can be starved, having no chance
3526 * to acquire it since this path will get to it first.
3527 * So use another lock to provide fairness.
3529 qemu_mutex_lock(&qemu_fair_mutex
);
3530 qemu_mutex_unlock(&qemu_fair_mutex
);
3532 qemu_mutex_lock(&qemu_global_mutex
);
3533 qemu_wait_io_event_common(env
);
3536 static void qemu_kvm_eat_signal(CPUState
*env
, int timeout
)
3543 ts
.tv_sec
= timeout
/ 1000;
3544 ts
.tv_nsec
= (timeout
% 1000) * 1000000;
3546 sigemptyset(&waitset
);
3547 sigaddset(&waitset
, SIG_IPI
);
3549 qemu_mutex_unlock(&qemu_global_mutex
);
3550 r
= sigtimedwait(&waitset
, &siginfo
, &ts
);
3552 qemu_mutex_lock(&qemu_global_mutex
);
3554 if (r
== -1 && !(e
== EAGAIN
|| e
== EINTR
)) {
3555 fprintf(stderr
, "sigtimedwait: %s\n", strerror(e
));
3560 static void qemu_kvm_wait_io_event(CPUState
*env
)
3562 while (!cpu_has_work(env
))
3563 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3565 qemu_kvm_eat_signal(env
, 0);
3566 qemu_wait_io_event_common(env
);
3569 static int qemu_cpu_exec(CPUState
*env
);
3571 static void *kvm_cpu_thread_fn(void *arg
)
3573 CPUState
*env
= arg
;
3575 qemu_thread_self(env
->thread
);
3579 kvm_block_io_signals(env
);
3581 /* signal CPU creation */
3582 qemu_mutex_lock(&qemu_global_mutex
);
3584 qemu_cond_signal(&qemu_cpu_cond
);
3586 /* and wait for machine initialization */
3587 while (!qemu_system_ready
)
3588 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3591 if (cpu_can_run(env
))
3593 qemu_kvm_wait_io_event(env
);
3599 static void tcg_cpu_exec(void);
3601 static void *tcg_cpu_thread_fn(void *arg
)
3603 CPUState
*env
= arg
;
3605 tcg_block_io_signals();
3606 qemu_thread_self(env
->thread
);
3608 /* signal CPU creation */
3609 qemu_mutex_lock(&qemu_global_mutex
);
3610 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
3612 qemu_cond_signal(&qemu_cpu_cond
);
3614 /* and wait for machine initialization */
3615 while (!qemu_system_ready
)
3616 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3620 qemu_wait_io_event(cur_cpu
);
3626 void qemu_cpu_kick(void *_env
)
3628 CPUState
*env
= _env
;
3629 qemu_cond_broadcast(env
->halt_cond
);
3631 qemu_thread_signal(env
->thread
, SIG_IPI
);
3634 int qemu_cpu_self(void *_env
)
3636 CPUState
*env
= _env
;
3639 qemu_thread_self(&this);
3641 return qemu_thread_equal(&this, env
->thread
);
3644 static void cpu_signal(int sig
)
3647 cpu_exit(cpu_single_env
);
3650 static void tcg_block_io_signals(void)
3653 struct sigaction sigact
;
3656 sigaddset(&set
, SIGUSR2
);
3657 sigaddset(&set
, SIGIO
);
3658 sigaddset(&set
, SIGALRM
);
3659 sigaddset(&set
, SIGCHLD
);
3660 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3663 sigaddset(&set
, SIG_IPI
);
3664 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3666 memset(&sigact
, 0, sizeof(sigact
));
3667 sigact
.sa_handler
= cpu_signal
;
3668 sigaction(SIG_IPI
, &sigact
, NULL
);
3671 static void dummy_signal(int sig
)
3675 static void kvm_block_io_signals(CPUState
*env
)
3679 struct sigaction sigact
;
3682 sigaddset(&set
, SIGUSR2
);
3683 sigaddset(&set
, SIGIO
);
3684 sigaddset(&set
, SIGALRM
);
3685 sigaddset(&set
, SIGCHLD
);
3686 sigaddset(&set
, SIG_IPI
);
3687 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3689 pthread_sigmask(SIG_BLOCK
, NULL
, &set
);
3690 sigdelset(&set
, SIG_IPI
);
3692 memset(&sigact
, 0, sizeof(sigact
));
3693 sigact
.sa_handler
= dummy_signal
;
3694 sigaction(SIG_IPI
, &sigact
, NULL
);
3696 r
= kvm_set_signal_mask(env
, &set
);
3698 fprintf(stderr
, "kvm_set_signal_mask: %s\n", strerror(r
));
3703 static void unblock_io_signals(void)
3708 sigaddset(&set
, SIGUSR2
);
3709 sigaddset(&set
, SIGIO
);
3710 sigaddset(&set
, SIGALRM
);
3711 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3714 sigaddset(&set
, SIG_IPI
);
3715 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3718 static void qemu_signal_lock(unsigned int msecs
)
3720 qemu_mutex_lock(&qemu_fair_mutex
);
3722 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
3723 qemu_thread_signal(tcg_cpu_thread
, SIG_IPI
);
3724 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
3727 qemu_mutex_unlock(&qemu_fair_mutex
);
3730 void qemu_mutex_lock_iothread(void)
3732 if (kvm_enabled()) {
3733 qemu_mutex_lock(&qemu_fair_mutex
);
3734 qemu_mutex_lock(&qemu_global_mutex
);
3735 qemu_mutex_unlock(&qemu_fair_mutex
);
3737 qemu_signal_lock(100);
3740 void qemu_mutex_unlock_iothread(void)
3742 qemu_mutex_unlock(&qemu_global_mutex
);
3745 static int all_vcpus_paused(void)
3747 CPUState
*penv
= first_cpu
;
3752 penv
= (CPUState
*)penv
->next_cpu
;
3758 static void pause_all_vcpus(void)
3760 CPUState
*penv
= first_cpu
;
3764 qemu_thread_signal(penv
->thread
, SIG_IPI
);
3765 qemu_cpu_kick(penv
);
3766 penv
= (CPUState
*)penv
->next_cpu
;
3769 while (!all_vcpus_paused()) {
3770 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
3773 qemu_thread_signal(penv
->thread
, SIG_IPI
);
3774 penv
= (CPUState
*)penv
->next_cpu
;
3779 static void resume_all_vcpus(void)
3781 CPUState
*penv
= first_cpu
;
3786 qemu_thread_signal(penv
->thread
, SIG_IPI
);
3787 qemu_cpu_kick(penv
);
3788 penv
= (CPUState
*)penv
->next_cpu
;
3792 static void tcg_init_vcpu(void *_env
)
3794 CPUState
*env
= _env
;
3795 /* share a single thread for all cpus with TCG */
3796 if (!tcg_cpu_thread
) {
3797 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3798 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3799 qemu_cond_init(env
->halt_cond
);
3800 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
3801 while (env
->created
== 0)
3802 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3803 tcg_cpu_thread
= env
->thread
;
3804 tcg_halt_cond
= env
->halt_cond
;
3806 env
->thread
= tcg_cpu_thread
;
3807 env
->halt_cond
= tcg_halt_cond
;
3811 static void kvm_start_vcpu(CPUState
*env
)
3813 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3814 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3815 qemu_cond_init(env
->halt_cond
);
3816 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
3817 while (env
->created
== 0)
3818 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3821 void qemu_init_vcpu(void *_env
)
3823 CPUState
*env
= _env
;
3825 env
->nr_cores
= smp_cores
;
3826 env
->nr_threads
= smp_threads
;
3828 kvm_start_vcpu(env
);
3833 void qemu_notify_event(void)
3835 qemu_event_increment();
3838 static void qemu_system_vmstop_request(int reason
)
3840 vmstop_requested
= reason
;
3841 qemu_notify_event();
3844 void vm_stop(int reason
)
3847 qemu_thread_self(&me
);
3849 if (!qemu_thread_equal(&me
, &io_thread
)) {
3850 qemu_system_vmstop_request(reason
);
3852 * FIXME: should not return to device code in case
3853 * vm_stop() has been requested.
3855 if (cpu_single_env
) {
3856 cpu_exit(cpu_single_env
);
3857 cpu_single_env
->stop
= 1;
3868 static void host_main_loop_wait(int *timeout
)
3874 /* XXX: need to suppress polling by better using win32 events */
3876 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
3877 ret
|= pe
->func(pe
->opaque
);
3881 WaitObjects
*w
= &wait_objects
;
3883 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
3884 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
3885 if (w
->func
[ret
- WAIT_OBJECT_0
])
3886 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
3888 /* Check for additional signaled events */
3889 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
3891 /* Check if event is signaled */
3892 ret2
= WaitForSingleObject(w
->events
[i
], 0);
3893 if(ret2
== WAIT_OBJECT_0
) {
3895 w
->func
[i
](w
->opaque
[i
]);
3896 } else if (ret2
== WAIT_TIMEOUT
) {
3898 err
= GetLastError();
3899 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
3902 } else if (ret
== WAIT_TIMEOUT
) {
3904 err
= GetLastError();
3905 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
3912 static void host_main_loop_wait(int *timeout
)
3917 void main_loop_wait(int timeout
)
3919 IOHandlerRecord
*ioh
;
3920 fd_set rfds
, wfds
, xfds
;
3924 qemu_bh_update_timeout(&timeout
);
3926 host_main_loop_wait(&timeout
);
3928 /* poll any events */
3929 /* XXX: separate device handlers from system ones */
3934 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3938 (!ioh
->fd_read_poll
||
3939 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
3940 FD_SET(ioh
->fd
, &rfds
);
3944 if (ioh
->fd_write
) {
3945 FD_SET(ioh
->fd
, &wfds
);
3951 tv
.tv_sec
= timeout
/ 1000;
3952 tv
.tv_usec
= (timeout
% 1000) * 1000;
3954 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
3956 qemu_mutex_unlock_iothread();
3957 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
3958 qemu_mutex_lock_iothread();
3960 IOHandlerRecord
**pioh
;
3962 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3963 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
3964 ioh
->fd_read(ioh
->opaque
);
3966 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
3967 ioh
->fd_write(ioh
->opaque
);
3971 /* remove deleted IO handlers */
3972 pioh
= &first_io_handler
;
3983 slirp_select_poll(&rfds
, &wfds
, &xfds
, (ret
< 0));
3985 qemu_run_all_timers();
3987 /* Check bottom-halves last in case any of the earlier events triggered
3993 static int qemu_cpu_exec(CPUState
*env
)
3996 #ifdef CONFIG_PROFILER
4000 #ifdef CONFIG_PROFILER
4001 ti
= profile_getclock();
4006 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
4007 env
->icount_decr
.u16
.low
= 0;
4008 env
->icount_extra
= 0;
4009 count
= qemu_icount_round (qemu_next_deadline());
4010 qemu_icount
+= count
;
4011 decr
= (count
> 0xffff) ? 0xffff : count
;
4013 env
->icount_decr
.u16
.low
= decr
;
4014 env
->icount_extra
= count
;
4016 ret
= cpu_exec(env
);
4017 #ifdef CONFIG_PROFILER
4018 qemu_time
+= profile_getclock() - ti
;
4021 /* Fold pending instructions back into the
4022 instruction counter, and clear the interrupt flag. */
4023 qemu_icount
-= (env
->icount_decr
.u16
.low
4024 + env
->icount_extra
);
4025 env
->icount_decr
.u32
= 0;
4026 env
->icount_extra
= 0;
4031 static void tcg_cpu_exec(void)
4035 if (next_cpu
== NULL
)
4036 next_cpu
= first_cpu
;
4037 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
4038 CPUState
*env
= cur_cpu
= next_cpu
;
4040 qemu_clock_enable(vm_clock
,
4041 (cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
) == 0);
4043 if (qemu_alarm_pending())
4045 if (cpu_can_run(env
))
4046 ret
= qemu_cpu_exec(env
);
4050 if (ret
== EXCP_DEBUG
) {
4051 gdb_set_stop_cpu(env
);
4052 debug_requested
= 1;
4058 static int qemu_calculate_timeout(void)
4060 #ifndef CONFIG_IOTHREAD
4065 else if (tcg_has_work())
4068 /* XXX: use timeout computed from timers */
4071 /* Advance virtual time to the next event. */
4072 delta
= qemu_icount_delta();
4074 /* If virtual time is ahead of real time then just
4076 timeout
= (delta
+ 999999) / 1000000;
4078 /* Wait for either IO to occur or the next
4080 add
= qemu_next_deadline();
4081 /* We advance the timer before checking for IO.
4082 Limit the amount we advance so that early IO
4083 activity won't get the guest too far ahead. */
4087 qemu_icount
+= qemu_icount_round (add
);
4088 timeout
= delta
/ 1000000;
4095 #else /* CONFIG_IOTHREAD */
4100 static int vm_can_run(void)
4102 if (powerdown_requested
)
4104 if (reset_requested
)
4106 if (shutdown_requested
)
4108 if (debug_requested
)
4113 qemu_irq qemu_system_powerdown
;
4115 static void main_loop(void)
4119 #ifdef CONFIG_IOTHREAD
4120 qemu_system_ready
= 1;
4121 qemu_cond_broadcast(&qemu_system_cond
);
4126 #ifdef CONFIG_PROFILER
4129 #ifndef CONFIG_IOTHREAD
4132 #ifdef CONFIG_PROFILER
4133 ti
= profile_getclock();
4135 main_loop_wait(qemu_calculate_timeout());
4136 #ifdef CONFIG_PROFILER
4137 dev_time
+= profile_getclock() - ti
;
4139 } while (vm_can_run());
4141 if (qemu_debug_requested()) {
4142 vm_stop(EXCP_DEBUG
);
4144 if (qemu_shutdown_requested()) {
4145 monitor_protocol_event(QEVENT_SHUTDOWN
, NULL
);
4152 if (qemu_reset_requested()) {
4154 qemu_system_reset();
4157 if (qemu_powerdown_requested()) {
4158 monitor_protocol_event(QEVENT_POWERDOWN
, NULL
);
4159 qemu_irq_raise(qemu_system_powerdown
);
4161 if ((r
= qemu_vmstop_requested())) {
4168 static void version(void)
4170 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4173 static void help(int exitcode
)
4175 const char *options_help
=
4176 #define DEF(option, opt_arg, opt_enum, opt_help) \
4178 #define DEFHEADING(text) stringify(text) "\n"
4179 #include "qemu-options.h"
4185 printf("usage: %s [options] [disk_image]\n"
4187 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4190 "During emulation, the following keys are useful:\n"
4191 "ctrl-alt-f toggle full screen\n"
4192 "ctrl-alt-n switch to virtual console 'n'\n"
4193 "ctrl-alt toggle mouse and keyboard grab\n"
4195 "When using -nographic, press 'ctrl-a h' to get some help.\n",
4201 #define HAS_ARG 0x0001
4204 #define DEF(option, opt_arg, opt_enum, opt_help) \
4206 #define DEFHEADING(text)
4207 #include "qemu-options.h"
4213 typedef struct QEMUOption
{
4219 static const QEMUOption qemu_options
[] = {
4220 { "h", 0, QEMU_OPTION_h
},
4221 #define DEF(option, opt_arg, opt_enum, opt_help) \
4222 { option, opt_arg, opt_enum },
4223 #define DEFHEADING(text)
4224 #include "qemu-options.h"
4232 struct soundhw soundhw
[] = {
4233 #ifdef HAS_AUDIO_CHOICE
4234 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4240 { .init_isa
= pcspk_audio_init
}
4247 "Creative Sound Blaster 16",
4250 { .init_isa
= SB16_init
}
4254 #ifdef CONFIG_CS4231A
4260 { .init_isa
= cs4231a_init
}
4268 "Yamaha YMF262 (OPL3)",
4270 "Yamaha YM3812 (OPL2)",
4274 { .init_isa
= Adlib_init
}
4281 "Gravis Ultrasound GF1",
4284 { .init_isa
= GUS_init
}
4291 "Intel 82801AA AC97 Audio",
4294 { .init_pci
= ac97_init
}
4298 #ifdef CONFIG_ES1370
4301 "ENSONIQ AudioPCI ES1370",
4304 { .init_pci
= es1370_init
}
4308 #endif /* HAS_AUDIO_CHOICE */
4310 { NULL
, NULL
, 0, 0, { NULL
} }
4313 static void select_soundhw (const char *optarg
)
4317 if (*optarg
== '?') {
4320 printf ("Valid sound card names (comma separated):\n");
4321 for (c
= soundhw
; c
->name
; ++c
) {
4322 printf ("%-11s %s\n", c
->name
, c
->descr
);
4324 printf ("\n-soundhw all will enable all of the above\n");
4325 exit (*optarg
!= '?');
4333 if (!strcmp (optarg
, "all")) {
4334 for (c
= soundhw
; c
->name
; ++c
) {
4342 e
= strchr (p
, ',');
4343 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4345 for (c
= soundhw
; c
->name
; ++c
) {
4346 if (!strncmp (c
->name
, p
, l
) && !c
->name
[l
]) {
4355 "Unknown sound card name (too big to show)\n");
4358 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4363 p
+= l
+ (e
!= NULL
);
4367 goto show_valid_cards
;
4372 static void select_vgahw (const char *p
)
4377 vga_interface_type
= VGA_NONE
;
4378 if (strstart(p
, "std", &opts
)) {
4379 vga_interface_type
= VGA_STD
;
4380 } else if (strstart(p
, "cirrus", &opts
)) {
4381 vga_interface_type
= VGA_CIRRUS
;
4382 } else if (strstart(p
, "vmware", &opts
)) {
4383 vga_interface_type
= VGA_VMWARE
;
4384 } else if (strstart(p
, "xenfb", &opts
)) {
4385 vga_interface_type
= VGA_XENFB
;
4386 } else if (!strstart(p
, "none", &opts
)) {
4388 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4392 const char *nextopt
;
4394 if (strstart(opts
, ",retrace=", &nextopt
)) {
4396 if (strstart(opts
, "dumb", &nextopt
))
4397 vga_retrace_method
= VGA_RETRACE_DUMB
;
4398 else if (strstart(opts
, "precise", &nextopt
))
4399 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4400 else goto invalid_vga
;
4401 } else goto invalid_vga
;
4407 static int balloon_parse(const char *arg
)
4411 if (strcmp(arg
, "none") == 0) {
4415 if (!strncmp(arg
, "virtio", 6)) {
4416 if (arg
[6] == ',') {
4417 /* have params -> parse them */
4418 opts
= qemu_opts_parse(&qemu_device_opts
, arg
+7, 0);
4422 /* create empty opts */
4423 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4425 qemu_opt_set(opts
, "driver", "virtio-balloon-pci");
4434 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4436 exit(STATUS_CONTROL_C_EXIT
);
4441 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4445 if(strlen(str
) != 36)
4448 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4449 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4450 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4456 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4464 static void termsig_handler(int signal
)
4466 qemu_system_shutdown_request();
4469 static void sigchld_handler(int signal
)
4471 waitpid(-1, NULL
, WNOHANG
);
4474 static void sighandler_setup(void)
4476 struct sigaction act
;
4478 memset(&act
, 0, sizeof(act
));
4479 act
.sa_handler
= termsig_handler
;
4480 sigaction(SIGINT
, &act
, NULL
);
4481 sigaction(SIGHUP
, &act
, NULL
);
4482 sigaction(SIGTERM
, &act
, NULL
);
4484 act
.sa_handler
= sigchld_handler
;
4485 act
.sa_flags
= SA_NOCLDSTOP
;
4486 sigaction(SIGCHLD
, &act
, NULL
);
4492 /* Look for support files in the same directory as the executable. */
4493 static char *find_datadir(const char *argv0
)
4499 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
4506 while (p
!= buf
&& *p
!= '\\')
4509 if (access(buf
, R_OK
) == 0) {
4510 return qemu_strdup(buf
);
4516 /* Find a likely location for support files using the location of the binary.
4517 For installed binaries this will be "$bindir/../share/qemu". When
4518 running from the build tree this will be "$bindir/../pc-bios". */
4519 #define SHARE_SUFFIX "/share/qemu"
4520 #define BUILD_SUFFIX "/pc-bios"
4521 static char *find_datadir(const char *argv0
)
4529 #if defined(__linux__)
4532 len
= readlink("/proc/self/exe", buf
, sizeof(buf
) - 1);
4538 #elif defined(__FreeBSD__)
4541 len
= readlink("/proc/curproc/file", buf
, sizeof(buf
) - 1);
4548 /* If we don't have any way of figuring out the actual executable
4549 location then try argv[0]. */
4551 p
= realpath(argv0
, buf
);
4559 max_len
= strlen(dir
) +
4560 MAX(strlen(SHARE_SUFFIX
), strlen(BUILD_SUFFIX
)) + 1;
4561 res
= qemu_mallocz(max_len
);
4562 snprintf(res
, max_len
, "%s%s", dir
, SHARE_SUFFIX
);
4563 if (access(res
, R_OK
)) {
4564 snprintf(res
, max_len
, "%s%s", dir
, BUILD_SUFFIX
);
4565 if (access(res
, R_OK
)) {
4577 char *qemu_find_file(int type
, const char *name
)
4583 /* If name contains path separators then try it as a straight path. */
4584 if ((strchr(name
, '/') || strchr(name
, '\\'))
4585 && access(name
, R_OK
) == 0) {
4586 return qemu_strdup(name
);
4589 case QEMU_FILE_TYPE_BIOS
:
4592 case QEMU_FILE_TYPE_KEYMAP
:
4593 subdir
= "keymaps/";
4598 len
= strlen(data_dir
) + strlen(name
) + strlen(subdir
) + 2;
4599 buf
= qemu_mallocz(len
);
4600 snprintf(buf
, len
, "%s/%s%s", data_dir
, subdir
, name
);
4601 if (access(buf
, R_OK
)) {
4608 static int device_help_func(QemuOpts
*opts
, void *opaque
)
4610 return qdev_device_help(opts
);
4613 static int device_init_func(QemuOpts
*opts
, void *opaque
)
4617 dev
= qdev_device_add(opts
);
4623 static int chardev_init_func(QemuOpts
*opts
, void *opaque
)
4625 CharDriverState
*chr
;
4627 chr
= qemu_chr_open_opts(opts
, NULL
);
4633 static int mon_init_func(QemuOpts
*opts
, void *opaque
)
4635 CharDriverState
*chr
;
4636 const char *chardev
;
4640 mode
= qemu_opt_get(opts
, "mode");
4644 if (strcmp(mode
, "readline") == 0) {
4645 flags
= MONITOR_USE_READLINE
;
4646 } else if (strcmp(mode
, "control") == 0) {
4647 flags
= MONITOR_USE_CONTROL
;
4649 fprintf(stderr
, "unknown monitor mode \"%s\"\n", mode
);
4653 if (qemu_opt_get_bool(opts
, "default", 0))
4654 flags
|= MONITOR_IS_DEFAULT
;
4656 chardev
= qemu_opt_get(opts
, "chardev");
4657 chr
= qemu_chr_find(chardev
);
4659 fprintf(stderr
, "chardev \"%s\" not found\n", chardev
);
4663 monitor_init(chr
, flags
);
4667 static void monitor_parse(const char *optarg
, const char *mode
)
4669 static int monitor_device_index
= 0;
4675 if (strstart(optarg
, "chardev:", &p
)) {
4676 snprintf(label
, sizeof(label
), "%s", p
);
4678 if (monitor_device_index
) {
4679 snprintf(label
, sizeof(label
), "monitor%d",
4680 monitor_device_index
);
4682 snprintf(label
, sizeof(label
), "monitor");
4685 opts
= qemu_chr_parse_compat(label
, optarg
);
4687 fprintf(stderr
, "parse error: %s\n", optarg
);
4692 opts
= qemu_opts_create(&qemu_mon_opts
, label
, 1);
4694 fprintf(stderr
, "duplicate chardev: %s\n", label
);
4697 qemu_opt_set(opts
, "mode", mode
);
4698 qemu_opt_set(opts
, "chardev", label
);
4700 qemu_opt_set(opts
, "default", "on");
4701 monitor_device_index
++;
4704 struct device_config
{
4706 DEV_USB
, /* -usbdevice */
4708 DEV_SERIAL
, /* -serial */
4709 DEV_PARALLEL
, /* -parallel */
4710 DEV_VIRTCON
, /* -virtioconsole */
4711 DEV_DEBUGCON
, /* -debugcon */
4713 const char *cmdline
;
4714 QTAILQ_ENTRY(device_config
) next
;
4716 QTAILQ_HEAD(, device_config
) device_configs
= QTAILQ_HEAD_INITIALIZER(device_configs
);
4718 static void add_device_config(int type
, const char *cmdline
)
4720 struct device_config
*conf
;
4722 conf
= qemu_mallocz(sizeof(*conf
));
4724 conf
->cmdline
= cmdline
;
4725 QTAILQ_INSERT_TAIL(&device_configs
, conf
, next
);
4728 static int foreach_device_config(int type
, int (*func
)(const char *cmdline
))
4730 struct device_config
*conf
;
4733 QTAILQ_FOREACH(conf
, &device_configs
, next
) {
4734 if (conf
->type
!= type
)
4736 rc
= func(conf
->cmdline
);
4743 static int serial_parse(const char *devname
)
4745 static int index
= 0;
4748 if (strcmp(devname
, "none") == 0)
4750 if (index
== MAX_SERIAL_PORTS
) {
4751 fprintf(stderr
, "qemu: too many serial ports\n");
4754 snprintf(label
, sizeof(label
), "serial%d", index
);
4755 serial_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4756 if (!serial_hds
[index
]) {
4757 fprintf(stderr
, "qemu: could not open serial device '%s': %s\n",
4758 devname
, strerror(errno
));
4765 static int parallel_parse(const char *devname
)
4767 static int index
= 0;
4770 if (strcmp(devname
, "none") == 0)
4772 if (index
== MAX_PARALLEL_PORTS
) {
4773 fprintf(stderr
, "qemu: too many parallel ports\n");
4776 snprintf(label
, sizeof(label
), "parallel%d", index
);
4777 parallel_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4778 if (!parallel_hds
[index
]) {
4779 fprintf(stderr
, "qemu: could not open parallel device '%s': %s\n",
4780 devname
, strerror(errno
));
4787 static int virtcon_parse(const char *devname
)
4789 static int index
= 0;
4791 QemuOpts
*bus_opts
, *dev_opts
;
4793 if (strcmp(devname
, "none") == 0)
4795 if (index
== MAX_VIRTIO_CONSOLES
) {
4796 fprintf(stderr
, "qemu: too many virtio consoles\n");
4800 bus_opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4801 qemu_opt_set(bus_opts
, "driver", "virtio-serial");
4803 dev_opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4804 qemu_opt_set(dev_opts
, "driver", "virtconsole");
4806 snprintf(label
, sizeof(label
), "virtcon%d", index
);
4807 virtcon_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4808 if (!virtcon_hds
[index
]) {
4809 fprintf(stderr
, "qemu: could not open virtio console '%s': %s\n",
4810 devname
, strerror(errno
));
4813 qemu_opt_set(dev_opts
, "chardev", label
);
4819 static int debugcon_parse(const char *devname
)
4823 if (!qemu_chr_open("debugcon", devname
, NULL
)) {
4826 opts
= qemu_opts_create(&qemu_device_opts
, "debugcon", 1);
4828 fprintf(stderr
, "qemu: already have a debugcon device\n");
4831 qemu_opt_set(opts
, "driver", "isa-debugcon");
4832 qemu_opt_set(opts
, "chardev", "debugcon");
4836 static const QEMUOption
*lookup_opt(int argc
, char **argv
,
4837 const char **poptarg
, int *poptind
)
4839 const QEMUOption
*popt
;
4840 int optind
= *poptind
;
4841 char *r
= argv
[optind
];
4844 loc_set_cmdline(argv
, optind
, 1);
4846 /* Treat --foo the same as -foo. */
4849 popt
= qemu_options
;
4852 error_report("invalid option");
4855 if (!strcmp(popt
->name
, r
+ 1))
4859 if (popt
->flags
& HAS_ARG
) {
4860 if (optind
>= argc
) {
4861 error_report("requires an argument");
4864 optarg
= argv
[optind
++];
4865 loc_set_cmdline(argv
, optind
- 2, 2);
4876 int main(int argc
, char **argv
, char **envp
)
4878 const char *gdbstub_dev
= NULL
;
4879 uint32_t boot_devices_bitmap
= 0;
4881 int snapshot
, linux_boot
, net_boot
;
4882 const char *icount_option
= NULL
;
4883 const char *initrd_filename
;
4884 const char *kernel_filename
, *kernel_cmdline
;
4885 char boot_devices
[33] = "cad"; /* default to HD->floppy->CD-ROM */
4887 DisplayChangeListener
*dcl
;
4888 int cyls
, heads
, secs
, translation
;
4889 QemuOpts
*hda_opts
= NULL
, *opts
;
4892 const char *loadvm
= NULL
;
4893 QEMUMachine
*machine
;
4894 const char *cpu_model
;
4899 const char *pid_file
= NULL
;
4900 const char *incoming
= NULL
;
4903 struct passwd
*pwd
= NULL
;
4904 const char *chroot_dir
= NULL
;
4905 const char *run_as
= NULL
;
4908 int show_vnc_port
= 0;
4911 error_set_progname(argv
[0]);
4915 qemu_cache_utils_init(envp
);
4917 QLIST_INIT (&vm_change_state_head
);
4920 struct sigaction act
;
4921 sigfillset(&act
.sa_mask
);
4923 act
.sa_handler
= SIG_IGN
;
4924 sigaction(SIGPIPE
, &act
, NULL
);
4927 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4928 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4929 QEMU to run on a single CPU */
4934 h
= GetCurrentProcess();
4935 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4936 for(i
= 0; i
< 32; i
++) {
4937 if (mask
& (1 << i
))
4942 SetProcessAffinityMask(h
, mask
);
4948 module_call_init(MODULE_INIT_MACHINE
);
4949 machine
= find_default_machine();
4951 initrd_filename
= NULL
;
4954 kernel_filename
= NULL
;
4955 kernel_cmdline
= "";
4956 cyls
= heads
= secs
= 0;
4957 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4959 for (i
= 0; i
< MAX_NODES
; i
++) {
4961 node_cpumask
[i
] = 0;
4970 /* first pass of option parsing */
4972 while (optind
< argc
) {
4973 if (argv
[optind
][0] != '-') {
4978 const QEMUOption
*popt
;
4980 popt
= lookup_opt(argc
, argv
, &optarg
, &optind
);
4981 switch (popt
->index
) {
4982 case QEMU_OPTION_nodefconfig
:
4993 fname
= CONFIG_QEMU_CONFDIR
"/qemu.conf";
4994 fp
= fopen(fname
, "r");
4996 if (qemu_config_parse(fp
, fname
) != 0) {
5002 fname
= CONFIG_QEMU_CONFDIR
"/target-" TARGET_ARCH
".conf";
5003 fp
= fopen(fname
, "r");
5005 if (qemu_config_parse(fp
, fname
) != 0) {
5011 #if defined(cpudef_setup)
5012 cpudef_setup(); /* parse cpu definitions in target config file */
5015 /* second pass of option parsing */
5020 if (argv
[optind
][0] != '-') {
5021 hda_opts
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
5023 const QEMUOption
*popt
;
5025 popt
= lookup_opt(argc
, argv
, &optarg
, &optind
);
5026 switch(popt
->index
) {
5028 machine
= find_machine(optarg
);
5031 printf("Supported machines are:\n");
5032 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5034 printf("%-10s %s (alias of %s)\n",
5035 m
->alias
, m
->desc
, m
->name
);
5036 printf("%-10s %s%s\n",
5038 m
->is_default
? " (default)" : "");
5040 exit(*optarg
!= '?');
5043 case QEMU_OPTION_cpu
:
5044 /* hw initialization will check this */
5045 if (*optarg
== '?') {
5046 /* XXX: implement xxx_cpu_list for targets that still miss it */
5047 #if defined(cpu_list_id)
5048 cpu_list_id(stdout
, &fprintf
, optarg
);
5049 #elif defined(cpu_list)
5050 cpu_list(stdout
, &fprintf
); /* deprecated */
5057 case QEMU_OPTION_initrd
:
5058 initrd_filename
= optarg
;
5060 case QEMU_OPTION_hda
:
5062 hda_opts
= drive_add(optarg
, HD_ALIAS
, 0);
5064 hda_opts
= drive_add(optarg
, HD_ALIAS
5065 ",cyls=%d,heads=%d,secs=%d%s",
5066 0, cyls
, heads
, secs
,
5067 translation
== BIOS_ATA_TRANSLATION_LBA
?
5069 translation
== BIOS_ATA_TRANSLATION_NONE
?
5070 ",trans=none" : "");
5072 case QEMU_OPTION_hdb
:
5073 case QEMU_OPTION_hdc
:
5074 case QEMU_OPTION_hdd
:
5075 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
5077 case QEMU_OPTION_drive
:
5078 drive_add(NULL
, "%s", optarg
);
5080 case QEMU_OPTION_set
:
5081 if (qemu_set_option(optarg
) != 0)
5084 case QEMU_OPTION_global
:
5085 if (qemu_global_option(optarg
) != 0)
5088 case QEMU_OPTION_mtdblock
:
5089 drive_add(optarg
, MTD_ALIAS
);
5091 case QEMU_OPTION_sd
:
5092 drive_add(optarg
, SD_ALIAS
);
5094 case QEMU_OPTION_pflash
:
5095 drive_add(optarg
, PFLASH_ALIAS
);
5097 case QEMU_OPTION_snapshot
:
5100 case QEMU_OPTION_hdachs
:
5104 cyls
= strtol(p
, (char **)&p
, 0);
5105 if (cyls
< 1 || cyls
> 16383)
5110 heads
= strtol(p
, (char **)&p
, 0);
5111 if (heads
< 1 || heads
> 16)
5116 secs
= strtol(p
, (char **)&p
, 0);
5117 if (secs
< 1 || secs
> 63)
5121 if (!strcmp(p
, "none"))
5122 translation
= BIOS_ATA_TRANSLATION_NONE
;
5123 else if (!strcmp(p
, "lba"))
5124 translation
= BIOS_ATA_TRANSLATION_LBA
;
5125 else if (!strcmp(p
, "auto"))
5126 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5129 } else if (*p
!= '\0') {
5131 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5134 if (hda_opts
!= NULL
) {
5136 snprintf(num
, sizeof(num
), "%d", cyls
);
5137 qemu_opt_set(hda_opts
, "cyls", num
);
5138 snprintf(num
, sizeof(num
), "%d", heads
);
5139 qemu_opt_set(hda_opts
, "heads", num
);
5140 snprintf(num
, sizeof(num
), "%d", secs
);
5141 qemu_opt_set(hda_opts
, "secs", num
);
5142 if (translation
== BIOS_ATA_TRANSLATION_LBA
)
5143 qemu_opt_set(hda_opts
, "trans", "lba");
5144 if (translation
== BIOS_ATA_TRANSLATION_NONE
)
5145 qemu_opt_set(hda_opts
, "trans", "none");
5149 case QEMU_OPTION_numa
:
5150 if (nb_numa_nodes
>= MAX_NODES
) {
5151 fprintf(stderr
, "qemu: too many NUMA nodes\n");
5156 case QEMU_OPTION_nographic
:
5157 display_type
= DT_NOGRAPHIC
;
5159 #ifdef CONFIG_CURSES
5160 case QEMU_OPTION_curses
:
5161 display_type
= DT_CURSES
;
5164 case QEMU_OPTION_portrait
:
5167 case QEMU_OPTION_kernel
:
5168 kernel_filename
= optarg
;
5170 case QEMU_OPTION_append
:
5171 kernel_cmdline
= optarg
;
5173 case QEMU_OPTION_cdrom
:
5174 drive_add(optarg
, CDROM_ALIAS
);
5176 case QEMU_OPTION_boot
:
5178 static const char * const params
[] = {
5179 "order", "once", "menu", NULL
5181 char buf
[sizeof(boot_devices
)];
5182 char *standard_boot_devices
;
5185 if (!strchr(optarg
, '=')) {
5187 pstrcpy(buf
, sizeof(buf
), optarg
);
5188 } else if (check_params(buf
, sizeof(buf
), params
, optarg
) < 0) {
5190 "qemu: unknown boot parameter '%s' in '%s'\n",
5196 get_param_value(buf
, sizeof(buf
), "order", optarg
)) {
5197 boot_devices_bitmap
= parse_bootdevices(buf
);
5198 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5201 if (get_param_value(buf
, sizeof(buf
),
5203 boot_devices_bitmap
|= parse_bootdevices(buf
);
5204 standard_boot_devices
= qemu_strdup(boot_devices
);
5205 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5206 qemu_register_reset(restore_boot_devices
,
5207 standard_boot_devices
);
5209 if (get_param_value(buf
, sizeof(buf
),
5211 if (!strcmp(buf
, "on")) {
5213 } else if (!strcmp(buf
, "off")) {
5217 "qemu: invalid option value '%s'\n",
5225 case QEMU_OPTION_fda
:
5226 case QEMU_OPTION_fdb
:
5227 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
5230 case QEMU_OPTION_no_fd_bootchk
:
5234 case QEMU_OPTION_netdev
:
5235 if (net_client_parse(&qemu_netdev_opts
, optarg
) == -1) {
5239 case QEMU_OPTION_net
:
5240 if (net_client_parse(&qemu_net_opts
, optarg
) == -1) {
5245 case QEMU_OPTION_tftp
:
5246 legacy_tftp_prefix
= optarg
;
5248 case QEMU_OPTION_bootp
:
5249 legacy_bootp_filename
= optarg
;
5252 case QEMU_OPTION_smb
:
5253 if (net_slirp_smb(optarg
) < 0)
5257 case QEMU_OPTION_redir
:
5258 if (net_slirp_redir(optarg
) < 0)
5262 case QEMU_OPTION_bt
:
5263 add_device_config(DEV_BT
, optarg
);
5266 case QEMU_OPTION_audio_help
:
5270 case QEMU_OPTION_soundhw
:
5271 select_soundhw (optarg
);
5277 case QEMU_OPTION_version
:
5281 case QEMU_OPTION_m
: {
5285 value
= strtoul(optarg
, &ptr
, 10);
5287 case 0: case 'M': case 'm':
5294 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5298 /* On 32-bit hosts, QEMU is limited by virtual address space */
5299 if (value
> (2047 << 20) && HOST_LONG_BITS
== 32) {
5300 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5303 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5304 fprintf(stderr
, "qemu: ram size too large\n");
5310 case QEMU_OPTION_mempath
:
5314 case QEMU_OPTION_mem_prealloc
:
5321 const CPULogItem
*item
;
5323 mask
= cpu_str_to_log_mask(optarg
);
5325 printf("Log items (comma separated):\n");
5326 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5327 printf("%-10s %s\n", item
->name
, item
->help
);
5335 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5337 case QEMU_OPTION_gdb
:
5338 gdbstub_dev
= optarg
;
5343 case QEMU_OPTION_bios
:
5346 case QEMU_OPTION_singlestep
:
5353 keyboard_layout
= optarg
;
5355 case QEMU_OPTION_localtime
:
5358 case QEMU_OPTION_vga
:
5359 select_vgahw (optarg
);
5361 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5367 w
= strtol(p
, (char **)&p
, 10);
5370 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5376 h
= strtol(p
, (char **)&p
, 10);
5381 depth
= strtol(p
, (char **)&p
, 10);
5382 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5383 depth
!= 24 && depth
!= 32)
5385 } else if (*p
== '\0') {
5386 depth
= graphic_depth
;
5393 graphic_depth
= depth
;
5397 case QEMU_OPTION_echr
:
5400 term_escape_char
= strtol(optarg
, &r
, 0);
5402 printf("Bad argument to echr\n");
5405 case QEMU_OPTION_monitor
:
5406 monitor_parse(optarg
, "readline");
5407 default_monitor
= 0;
5409 case QEMU_OPTION_qmp
:
5410 monitor_parse(optarg
, "control");
5411 default_monitor
= 0;
5413 case QEMU_OPTION_mon
:
5414 opts
= qemu_opts_parse(&qemu_mon_opts
, optarg
, 1);
5416 fprintf(stderr
, "parse error: %s\n", optarg
);
5419 default_monitor
= 0;
5421 case QEMU_OPTION_chardev
:
5422 opts
= qemu_opts_parse(&qemu_chardev_opts
, optarg
, 1);
5424 fprintf(stderr
, "parse error: %s\n", optarg
);
5428 case QEMU_OPTION_serial
:
5429 add_device_config(DEV_SERIAL
, optarg
);
5431 if (strncmp(optarg
, "mon:", 4) == 0) {
5432 default_monitor
= 0;
5435 case QEMU_OPTION_watchdog
:
5438 "qemu: only one watchdog option may be given\n");
5443 case QEMU_OPTION_watchdog_action
:
5444 if (select_watchdog_action(optarg
) == -1) {
5445 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5449 case QEMU_OPTION_virtiocon
:
5450 add_device_config(DEV_VIRTCON
, optarg
);
5451 default_virtcon
= 0;
5452 if (strncmp(optarg
, "mon:", 4) == 0) {
5453 default_monitor
= 0;
5456 case QEMU_OPTION_parallel
:
5457 add_device_config(DEV_PARALLEL
, optarg
);
5458 default_parallel
= 0;
5459 if (strncmp(optarg
, "mon:", 4) == 0) {
5460 default_monitor
= 0;
5463 case QEMU_OPTION_debugcon
:
5464 add_device_config(DEV_DEBUGCON
, optarg
);
5466 case QEMU_OPTION_loadvm
:
5469 case QEMU_OPTION_full_screen
:
5473 case QEMU_OPTION_no_frame
:
5476 case QEMU_OPTION_alt_grab
:
5479 case QEMU_OPTION_ctrl_grab
:
5482 case QEMU_OPTION_no_quit
:
5485 case QEMU_OPTION_sdl
:
5486 display_type
= DT_SDL
;
5489 case QEMU_OPTION_pidfile
:
5493 case QEMU_OPTION_win2k_hack
:
5494 win2k_install_hack
= 1;
5496 case QEMU_OPTION_rtc_td_hack
:
5499 case QEMU_OPTION_acpitable
:
5500 if(acpi_table_add(optarg
) < 0) {
5501 fprintf(stderr
, "Wrong acpi table provided\n");
5505 case QEMU_OPTION_smbios
:
5506 if(smbios_entry_add(optarg
) < 0) {
5507 fprintf(stderr
, "Wrong smbios provided\n");
5513 case QEMU_OPTION_enable_kvm
:
5517 case QEMU_OPTION_usb
:
5520 case QEMU_OPTION_usbdevice
:
5522 add_device_config(DEV_USB
, optarg
);
5524 case QEMU_OPTION_device
:
5525 if (!qemu_opts_parse(&qemu_device_opts
, optarg
, 1)) {
5529 case QEMU_OPTION_smp
:
5532 fprintf(stderr
, "Invalid number of CPUs\n");
5535 if (max_cpus
< smp_cpus
) {
5536 fprintf(stderr
, "maxcpus must be equal to or greater than "
5540 if (max_cpus
> 255) {
5541 fprintf(stderr
, "Unsupported number of maxcpus\n");
5545 case QEMU_OPTION_vnc
:
5546 display_type
= DT_VNC
;
5547 vnc_display
= optarg
;
5550 case QEMU_OPTION_no_acpi
:
5553 case QEMU_OPTION_no_hpet
:
5556 case QEMU_OPTION_balloon
:
5557 if (balloon_parse(optarg
) < 0) {
5558 fprintf(stderr
, "Unknown -balloon argument %s\n", optarg
);
5563 case QEMU_OPTION_no_reboot
:
5566 case QEMU_OPTION_no_shutdown
:
5569 case QEMU_OPTION_show_cursor
:
5572 case QEMU_OPTION_uuid
:
5573 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5574 fprintf(stderr
, "Fail to parse UUID string."
5575 " Wrong format.\n");
5580 case QEMU_OPTION_daemonize
:
5584 case QEMU_OPTION_option_rom
:
5585 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5586 fprintf(stderr
, "Too many option ROMs\n");
5589 option_rom
[nb_option_roms
] = optarg
;
5592 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5593 case QEMU_OPTION_semihosting
:
5594 semihosting_enabled
= 1;
5597 case QEMU_OPTION_name
:
5598 qemu_name
= qemu_strdup(optarg
);
5600 char *p
= strchr(qemu_name
, ',');
5603 if (strncmp(p
, "process=", 8)) {
5604 fprintf(stderr
, "Unknown subargument %s to -name", p
);
5612 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5613 case QEMU_OPTION_prom_env
:
5614 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5615 fprintf(stderr
, "Too many prom variables\n");
5618 prom_envs
[nb_prom_envs
] = optarg
;
5623 case QEMU_OPTION_old_param
:
5627 case QEMU_OPTION_clock
:
5628 configure_alarms(optarg
);
5630 case QEMU_OPTION_startdate
:
5631 configure_rtc_date_offset(optarg
, 1);
5633 case QEMU_OPTION_rtc
:
5634 opts
= qemu_opts_parse(&qemu_rtc_opts
, optarg
, 0);
5636 fprintf(stderr
, "parse error: %s\n", optarg
);
5639 configure_rtc(opts
);
5641 case QEMU_OPTION_tb_size
:
5642 tb_size
= strtol(optarg
, NULL
, 0);
5646 case QEMU_OPTION_icount
:
5647 icount_option
= optarg
;
5649 case QEMU_OPTION_incoming
:
5652 case QEMU_OPTION_nodefaults
:
5654 default_parallel
= 0;
5655 default_virtcon
= 0;
5656 default_monitor
= 0;
5664 case QEMU_OPTION_chroot
:
5665 chroot_dir
= optarg
;
5667 case QEMU_OPTION_runas
:
5672 case QEMU_OPTION_xen_domid
:
5673 xen_domid
= atoi(optarg
);
5675 case QEMU_OPTION_xen_create
:
5676 xen_mode
= XEN_CREATE
;
5678 case QEMU_OPTION_xen_attach
:
5679 xen_mode
= XEN_ATTACH
;
5682 case QEMU_OPTION_readconfig
:
5685 fp
= fopen(optarg
, "r");
5687 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5690 if (qemu_config_parse(fp
, optarg
) != 0) {
5696 case QEMU_OPTION_writeconfig
:
5699 if (strcmp(optarg
, "-") == 0) {
5702 fp
= fopen(optarg
, "w");
5704 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5708 qemu_config_write(fp
);
5717 /* If no data_dir is specified then try to find it relative to the
5720 data_dir
= find_datadir(argv
[0]);
5722 /* If all else fails use the install patch specified when building. */
5724 data_dir
= CONFIG_QEMU_SHAREDIR
;
5728 * Default to max_cpus = smp_cpus, in case the user doesn't
5729 * specify a max_cpus value.
5732 max_cpus
= smp_cpus
;
5734 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5735 if (smp_cpus
> machine
->max_cpus
) {
5736 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5737 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5742 qemu_opts_foreach(&qemu_device_opts
, default_driver_check
, NULL
, 0);
5743 qemu_opts_foreach(&qemu_global_opts
, default_driver_check
, NULL
, 0);
5745 if (machine
->no_serial
) {
5748 if (machine
->no_parallel
) {
5749 default_parallel
= 0;
5751 if (!machine
->use_virtcon
) {
5752 default_virtcon
= 0;
5754 if (machine
->no_vga
) {
5757 if (machine
->no_floppy
) {
5760 if (machine
->no_cdrom
) {
5763 if (machine
->no_sdcard
) {
5767 if (display_type
== DT_NOGRAPHIC
) {
5768 if (default_parallel
)
5769 add_device_config(DEV_PARALLEL
, "null");
5770 if (default_serial
&& default_monitor
) {
5771 add_device_config(DEV_SERIAL
, "mon:stdio");
5772 } else if (default_virtcon
&& default_monitor
) {
5773 add_device_config(DEV_VIRTCON
, "mon:stdio");
5776 add_device_config(DEV_SERIAL
, "stdio");
5777 if (default_virtcon
)
5778 add_device_config(DEV_VIRTCON
, "stdio");
5779 if (default_monitor
)
5780 monitor_parse("stdio", "readline");
5784 add_device_config(DEV_SERIAL
, "vc:80Cx24C");
5785 if (default_parallel
)
5786 add_device_config(DEV_PARALLEL
, "vc:80Cx24C");
5787 if (default_monitor
)
5788 monitor_parse("vc:80Cx24C", "readline");
5789 if (default_virtcon
)
5790 add_device_config(DEV_VIRTCON
, "vc:80Cx24C");
5793 vga_interface_type
= VGA_CIRRUS
;
5795 if (qemu_opts_foreach(&qemu_chardev_opts
, chardev_init_func
, NULL
, 1) != 0)
5802 if (pipe(fds
) == -1)
5813 len
= read(fds
[0], &status
, 1);
5814 if (len
== -1 && (errno
== EINTR
))
5819 else if (status
== 1) {
5820 fprintf(stderr
, "Could not acquire pidfile: %s\n", strerror(errno
));
5828 qemu_set_cloexec(fds
[1]);
5840 signal(SIGTSTP
, SIG_IGN
);
5841 signal(SIGTTOU
, SIG_IGN
);
5842 signal(SIGTTIN
, SIG_IGN
);
5846 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5850 if (write(fds
[1], &status
, 1) != 1) {
5851 perror("daemonize. Writing to pipe\n");
5855 fprintf(stderr
, "Could not acquire pid file: %s\n", strerror(errno
));
5859 if (kvm_enabled()) {
5862 ret
= kvm_init(smp_cpus
);
5864 fprintf(stderr
, "failed to initialize KVM\n");
5869 if (qemu_init_main_loop()) {
5870 fprintf(stderr
, "qemu_init_main_loop failed\n");
5873 linux_boot
= (kernel_filename
!= NULL
);
5875 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5876 fprintf(stderr
, "-append only allowed with -kernel option\n");
5880 if (!linux_boot
&& initrd_filename
!= NULL
) {
5881 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5886 /* Win32 doesn't support line-buffering and requires size >= 2 */
5887 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5890 if (init_timer_alarm() < 0) {
5891 fprintf(stderr
, "could not initialize alarm timer\n");
5894 configure_icount(icount_option
);
5900 if (net_init_clients() < 0) {
5904 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5905 net_set_boot_mask(net_boot
);
5907 /* init the bluetooth world */
5908 if (foreach_device_config(DEV_BT
, bt_parse
))
5911 /* init the memory */
5913 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5915 /* init the dynamic translator */
5916 cpu_exec_init_all(tb_size
* 1024 * 1024);
5918 bdrv_init_with_whitelist();
5922 if (default_cdrom
) {
5923 /* we always create the cdrom drive, even if no disk is there */
5924 drive_add(NULL
, CDROM_ALIAS
);
5927 if (default_floppy
) {
5928 /* we always create at least one floppy */
5929 drive_add(NULL
, FD_ALIAS
, 0);
5932 if (default_sdcard
) {
5933 /* we always create one sd slot, even if no card is in it */
5934 drive_add(NULL
, SD_ALIAS
);
5937 /* open the virtual block devices */
5939 qemu_opts_foreach(&qemu_drive_opts
, drive_enable_snapshot
, NULL
, 0);
5940 if (qemu_opts_foreach(&qemu_drive_opts
, drive_init_func
, machine
, 1) != 0)
5943 register_savevm_live("ram", 0, 3, NULL
, ram_save_live
, NULL
,
5946 if (nb_numa_nodes
> 0) {
5949 if (nb_numa_nodes
> smp_cpus
) {
5950 nb_numa_nodes
= smp_cpus
;
5953 /* If no memory size if given for any node, assume the default case
5954 * and distribute the available memory equally across all nodes
5956 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5957 if (node_mem
[i
] != 0)
5960 if (i
== nb_numa_nodes
) {
5961 uint64_t usedmem
= 0;
5963 /* On Linux, the each node's border has to be 8MB aligned,
5964 * the final node gets the rest.
5966 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
5967 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
5968 usedmem
+= node_mem
[i
];
5970 node_mem
[i
] = ram_size
- usedmem
;
5973 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5974 if (node_cpumask
[i
] != 0)
5977 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5978 * must cope with this anyway, because there are BIOSes out there in
5979 * real machines which also use this scheme.
5981 if (i
== nb_numa_nodes
) {
5982 for (i
= 0; i
< smp_cpus
; i
++) {
5983 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
5988 if (foreach_device_config(DEV_SERIAL
, serial_parse
) < 0)
5990 if (foreach_device_config(DEV_PARALLEL
, parallel_parse
) < 0)
5992 if (foreach_device_config(DEV_VIRTCON
, virtcon_parse
) < 0)
5994 if (foreach_device_config(DEV_DEBUGCON
, debugcon_parse
) < 0)
5997 module_call_init(MODULE_INIT_DEVICE
);
5999 if (qemu_opts_foreach(&qemu_device_opts
, device_help_func
, NULL
, 0) != 0)
6003 i
= select_watchdog(watchdog
);
6005 exit (i
== 1 ? 1 : 0);
6008 if (machine
->compat_props
) {
6009 qdev_prop_register_global_list(machine
->compat_props
);
6013 machine
->init(ram_size
, boot_devices
,
6014 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
6016 cpu_synchronize_all_post_init();
6019 /* must be after terminal init, SDL library changes signal handlers */
6023 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
6024 for (i
= 0; i
< nb_numa_nodes
; i
++) {
6025 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
6031 current_machine
= machine
;
6033 /* init USB devices */
6035 if (foreach_device_config(DEV_USB
, usb_parse
) < 0)
6039 /* init generic devices */
6040 if (qemu_opts_foreach(&qemu_device_opts
, device_init_func
, NULL
, 1) != 0)
6043 net_check_clients();
6045 /* just use the first displaystate for the moment */
6046 ds
= get_displaystate();
6048 if (display_type
== DT_DEFAULT
) {
6049 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6050 display_type
= DT_SDL
;
6052 display_type
= DT_VNC
;
6053 vnc_display
= "localhost:0,to=99";
6059 switch (display_type
) {
6062 #if defined(CONFIG_CURSES)
6064 curses_display_init(ds
, full_screen
);
6067 #if defined(CONFIG_SDL)
6069 sdl_display_init(ds
, full_screen
, no_frame
);
6071 #elif defined(CONFIG_COCOA)
6073 cocoa_display_init(ds
, full_screen
);
6077 vnc_display_init(ds
);
6078 if (vnc_display_open(ds
, vnc_display
) < 0)
6081 if (show_vnc_port
) {
6082 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
6090 dcl
= ds
->listeners
;
6091 while (dcl
!= NULL
) {
6092 if (dcl
->dpy_refresh
!= NULL
) {
6093 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
6094 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
6099 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
6100 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
6101 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
6104 text_consoles_set_display(ds
);
6106 if (qemu_opts_foreach(&qemu_mon_opts
, mon_init_func
, NULL
, 1) != 0)
6109 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
6110 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
6115 qdev_machine_creation_done();
6117 if (rom_load_all() != 0) {
6118 fprintf(stderr
, "rom loading failed\n");
6122 qemu_system_reset();
6124 if (load_vmstate(loadvm
) < 0) {
6130 qemu_start_incoming_migration(incoming
);
6131 } else if (autostart
) {
6141 len
= write(fds
[1], &status
, 1);
6142 if (len
== -1 && (errno
== EINTR
))
6149 perror("not able to chdir to /");
6152 TFR(fd
= qemu_open("/dev/null", O_RDWR
));
6158 pwd
= getpwnam(run_as
);
6160 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
6166 if (chroot(chroot_dir
) < 0) {
6167 fprintf(stderr
, "chroot failed\n");
6171 perror("not able to chdir to /");
6177 if (setgid(pwd
->pw_gid
) < 0) {
6178 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
6181 if (setuid(pwd
->pw_uid
) < 0) {
6182 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
6185 if (setuid(0) != -1) {
6186 fprintf(stderr
, "Dropping privileges failed\n");