add "xchg ax, reg" emulator test
[qemu-kvm/amd-iommu.git] / vl.c
blob9b6915b6561b5281ca310fe89b1dde33a91d1710
1 /*
2 * QEMU System Emulator
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
22 * THE SOFTWARE.
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
35 #ifndef _WIN32
36 #include <libgen.h>
37 #include <pwd.h>
38 #include <sys/times.h>
39 #include <sys/wait.h>
40 #include <termios.h>
41 #include <sys/mman.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <net/if.h>
47 #include <arpa/inet.h>
48 #include <dirent.h>
49 #include <netdb.h>
50 #include <sys/select.h>
51 #ifdef CONFIG_BSD
52 #include <sys/stat.h>
53 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
54 #include <libutil.h>
55 #else
56 #include <util.h>
57 #endif
58 #else
59 #ifdef __linux__
60 #include <pty.h>
61 #include <malloc.h>
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> */
68 #include "hpet.h"
70 #include <linux/ppdev.h>
71 #include <linux/parport.h>
72 #endif
73 #ifdef __sun__
74 #include <sys/stat.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>
84 #include <net/if.h>
85 #include <syslog.h>
86 #include <stropts.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);
90 #endif
91 #endif
92 #endif
94 #if defined(__OpenBSD__)
95 #include <util.h>
96 #endif
98 #if defined(CONFIG_VDE)
99 #include <libvdeplug.h>
100 #endif
102 #ifdef _WIN32
103 #include <windows.h>
104 #include <mmsystem.h>
105 #endif
107 #ifdef CONFIG_SDL
108 #if defined(__APPLE__) || defined(main)
109 #include <SDL.h>
110 int qemu_main(int argc, char **argv, char **envp);
111 int main(int argc, char **argv)
113 return qemu_main(argc, argv, NULL);
115 #undef main
116 #define main qemu_main
117 #endif
118 #endif /* CONFIG_SDL */
120 #ifdef CONFIG_COCOA
121 #undef main
122 #define main qemu_main
123 #endif /* CONFIG_COCOA */
125 #include "hw/hw.h"
126 #include "hw/boards.h"
127 #include "hw/usb.h"
128 #include "hw/pcmcia.h"
129 #include "hw/pc.h"
130 #include "hw/audiodev.h"
131 #include "hw/isa.h"
132 #include "hw/baum.h"
133 #include "hw/bt.h"
134 #include "hw/watchdog.h"
135 #include "hw/smbios.h"
136 #include "hw/xen.h"
137 #include "hw/qdev.h"
138 #include "hw/loader.h"
139 #include "bt-host.h"
140 #include "net.h"
141 #include "net/slirp.h"
142 #include "monitor.h"
143 #include "console.h"
144 #include "sysemu.h"
145 #include "gdbstub.h"
146 #include "qemu-timer.h"
147 #include "qemu-char.h"
148 #include "cache-utils.h"
149 #include "block.h"
150 #include "block_int.h"
151 #include "block-migration.h"
152 #include "dma.h"
153 #include "audio/audio.h"
154 #include "migration.h"
155 #include "kvm.h"
156 #include "balloon.h"
157 #include "qemu-option.h"
158 #include "qemu-config.h"
159 #include "qemu-objects.h"
160 #include "hw/device-assignment.h"
162 #include "disas.h"
164 #include "exec-all.h"
166 #include "qemu_socket.h"
168 #include "slirp/libslirp.h"
170 #include "qemu-queue.h"
172 //#define DEBUG_NET
173 //#define DEBUG_SLIRP
175 #define DEFAULT_RAM_SIZE 128
177 #define MAX_VIRTIO_CONSOLES 1
179 static const char *data_dir;
180 const char *bios_name = NULL;
181 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
182 to store the VM snapshots */
183 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
184 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
185 DriveInfo *extboot_drive = NULL;
186 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
187 DisplayType display_type = DT_DEFAULT;
188 const char* keyboard_layout = NULL;
189 ram_addr_t ram_size;
190 const char *mem_path = NULL;
191 #ifdef MAP_POPULATE
192 int mem_prealloc = 0; /* force preallocation of physical target memory */
193 #endif
194 int nb_nics;
195 NICInfo nd_table[MAX_NICS];
196 int vm_running;
197 int autostart;
198 static int rtc_utc = 1;
199 static int rtc_date_offset = -1; /* -1 means no change */
200 QEMUClock *rtc_clock;
201 int vga_interface_type = VGA_NONE;
202 #ifdef TARGET_SPARC
203 int graphic_width = 1024;
204 int graphic_height = 768;
205 int graphic_depth = 8;
206 #else
207 int graphic_width = 800;
208 int graphic_height = 600;
209 int graphic_depth = 15;
210 #endif
211 static int full_screen = 0;
212 #ifdef CONFIG_SDL
213 static int no_frame = 0;
214 #endif
215 int no_quit = 0;
216 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
217 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
218 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
219 #ifdef TARGET_I386
220 int win2k_install_hack = 0;
221 int rtc_td_hack = 0;
222 #endif
223 int usb_enabled = 0;
224 int singlestep = 0;
225 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
226 int assigned_devices_index;
227 int smp_cpus = 1;
228 int max_cpus = 0;
229 int smp_cores = 1;
230 int smp_threads = 1;
231 const char *vnc_display;
232 int acpi_enabled = 1;
233 #ifdef TARGET_I386
234 int no_hpet = 0;
235 #endif
236 int fd_bootchk = 1;
237 int no_reboot = 0;
238 int no_shutdown = 0;
239 int cursor_hide = 1;
240 int graphic_rotate = 0;
241 uint8_t irq0override = 1;
242 #ifndef _WIN32
243 int daemonize = 0;
244 #endif
245 const char *watchdog;
246 const char *option_rom[MAX_OPTION_ROMS];
247 int nb_option_roms;
248 int semihosting_enabled = 0;
249 int time_drift_fix = 0;
250 unsigned int kvm_shadow_memory = 0;
251 #ifdef TARGET_ARM
252 int old_param = 0;
253 #endif
254 const char *qemu_name;
255 int alt_grab = 0;
256 int ctrl_grab = 0;
257 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
258 unsigned int nb_prom_envs = 0;
259 const char *prom_envs[MAX_PROM_ENVS];
260 #endif
261 const char *nvram = NULL;
262 int boot_menu;
264 int nb_numa_nodes;
265 uint64_t node_mem[MAX_NODES];
266 uint64_t node_cpumask[MAX_NODES];
268 static CPUState *cur_cpu;
269 static CPUState *next_cpu;
270 static int timer_alarm_pending = 1;
271 /* Conversion factor from emulated instructions to virtual clock ticks. */
272 static int icount_time_shift;
273 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
274 #define MAX_ICOUNT_SHIFT 10
275 /* Compensate for varying guest execution speed. */
276 static int64_t qemu_icount_bias;
277 static QEMUTimer *icount_rt_timer;
278 static QEMUTimer *icount_vm_timer;
279 static QEMUTimer *nographic_timer;
281 uint8_t qemu_uuid[16];
283 static QEMUBootSetHandler *boot_set_handler;
284 static void *boot_set_opaque;
286 #ifdef SIGRTMIN
287 #define SIG_IPI (SIGRTMIN+4)
288 #else
289 #define SIG_IPI SIGUSR1
290 #endif
292 static int default_serial = 1;
293 static int default_parallel = 1;
294 static int default_virtcon = 1;
295 static int default_monitor = 1;
296 static int default_vga = 1;
297 static int default_floppy = 1;
298 static int default_cdrom = 1;
299 static int default_sdcard = 1;
301 static struct {
302 const char *driver;
303 int *flag;
304 } default_list[] = {
305 { .driver = "isa-serial", .flag = &default_serial },
306 { .driver = "isa-parallel", .flag = &default_parallel },
307 { .driver = "isa-fdc", .flag = &default_floppy },
308 { .driver = "ide-drive", .flag = &default_cdrom },
309 { .driver = "virtio-serial-pci", .flag = &default_virtcon },
310 { .driver = "virtio-serial-s390", .flag = &default_virtcon },
311 { .driver = "virtio-serial", .flag = &default_virtcon },
312 { .driver = "VGA", .flag = &default_vga },
313 { .driver = "cirrus-vga", .flag = &default_vga },
314 { .driver = "vmware-svga", .flag = &default_vga },
317 static int default_driver_check(QemuOpts *opts, void *opaque)
319 const char *driver = qemu_opt_get(opts, "driver");
320 int i;
322 if (!driver)
323 return 0;
324 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
325 if (strcmp(default_list[i].driver, driver) != 0)
326 continue;
327 *(default_list[i].flag) = 0;
329 return 0;
332 /***********************************************************/
333 /* x86 ISA bus support */
335 target_phys_addr_t isa_mem_base = 0;
336 PicState2 *isa_pic;
338 /***********************************************************/
339 void hw_error(const char *fmt, ...)
341 va_list ap;
342 CPUState *env;
344 va_start(ap, fmt);
345 fprintf(stderr, "qemu: hardware error: ");
346 vfprintf(stderr, fmt, ap);
347 fprintf(stderr, "\n");
348 for(env = first_cpu; env != NULL; env = env->next_cpu) {
349 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
350 #ifdef TARGET_I386
351 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
352 #else
353 cpu_dump_state(env, stderr, fprintf, 0);
354 #endif
356 va_end(ap);
357 abort();
360 static void set_proc_name(const char *s)
362 #if defined(__linux__) && defined(PR_SET_NAME)
363 char name[16];
364 if (!s)
365 return;
366 name[sizeof(name) - 1] = 0;
367 strncpy(name, s, sizeof(name));
368 /* Could rewrite argv[0] too, but that's a bit more complicated.
369 This simple way is enough for `top'. */
370 prctl(PR_SET_NAME, name);
371 #endif
374 /***************/
375 /* ballooning */
377 static QEMUBalloonEvent *qemu_balloon_event;
378 void *qemu_balloon_event_opaque;
380 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
382 qemu_balloon_event = func;
383 qemu_balloon_event_opaque = opaque;
386 int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
388 if (qemu_balloon_event) {
389 qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
390 return 1;
391 } else {
392 return 0;
396 int qemu_balloon_status(MonitorCompletion cb, void *opaque)
398 if (qemu_balloon_event) {
399 qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
400 return 1;
401 } else {
402 return 0;
407 /***********************************************************/
408 /* real time host monotonic timer */
410 /* compute with 96 bit intermediate result: (a*b)/c */
411 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
413 union {
414 uint64_t ll;
415 struct {
416 #ifdef HOST_WORDS_BIGENDIAN
417 uint32_t high, low;
418 #else
419 uint32_t low, high;
420 #endif
421 } l;
422 } u, res;
423 uint64_t rl, rh;
425 u.ll = a;
426 rl = (uint64_t)u.l.low * (uint64_t)b;
427 rh = (uint64_t)u.l.high * (uint64_t)b;
428 rh += (rl >> 32);
429 res.l.high = rh / c;
430 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
431 return res.ll;
434 static int64_t get_clock_realtime(void)
436 struct timeval tv;
438 gettimeofday(&tv, NULL);
439 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
442 #ifdef WIN32
444 static int64_t clock_freq;
446 static void init_get_clock(void)
448 LARGE_INTEGER freq;
449 int ret;
450 ret = QueryPerformanceFrequency(&freq);
451 if (ret == 0) {
452 fprintf(stderr, "Could not calibrate ticks\n");
453 exit(1);
455 clock_freq = freq.QuadPart;
458 static int64_t get_clock(void)
460 LARGE_INTEGER ti;
461 QueryPerformanceCounter(&ti);
462 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
465 #else
467 static int use_rt_clock;
469 static void init_get_clock(void)
471 use_rt_clock = 0;
472 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
473 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
475 struct timespec ts;
476 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
477 use_rt_clock = 1;
480 #endif
483 static int64_t get_clock(void)
485 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
486 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
487 if (use_rt_clock) {
488 struct timespec ts;
489 clock_gettime(CLOCK_MONOTONIC, &ts);
490 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
491 } else
492 #endif
494 /* XXX: using gettimeofday leads to problems if the date
495 changes, so it should be avoided. */
496 return get_clock_realtime();
499 #endif
501 /* Return the virtual CPU time, based on the instruction counter. */
502 static int64_t cpu_get_icount(void)
504 int64_t icount;
505 CPUState *env = cpu_single_env;;
506 icount = qemu_icount;
507 if (env) {
508 if (!can_do_io(env))
509 fprintf(stderr, "Bad clock read\n");
510 icount -= (env->icount_decr.u16.low + env->icount_extra);
512 return qemu_icount_bias + (icount << icount_time_shift);
515 /***********************************************************/
516 /* guest cycle counter */
518 typedef struct TimersState {
519 int64_t cpu_ticks_prev;
520 int64_t cpu_ticks_offset;
521 int64_t cpu_clock_offset;
522 int32_t cpu_ticks_enabled;
523 int64_t dummy;
524 } TimersState;
526 TimersState timers_state;
528 /* return the host CPU cycle counter and handle stop/restart */
529 int64_t cpu_get_ticks(void)
531 if (use_icount) {
532 return cpu_get_icount();
534 if (!timers_state.cpu_ticks_enabled) {
535 return timers_state.cpu_ticks_offset;
536 } else {
537 int64_t ticks;
538 ticks = cpu_get_real_ticks();
539 if (timers_state.cpu_ticks_prev > ticks) {
540 /* Note: non increasing ticks may happen if the host uses
541 software suspend */
542 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
544 timers_state.cpu_ticks_prev = ticks;
545 return ticks + timers_state.cpu_ticks_offset;
549 /* return the host CPU monotonic timer and handle stop/restart */
550 static int64_t cpu_get_clock(void)
552 int64_t ti;
553 if (!timers_state.cpu_ticks_enabled) {
554 return timers_state.cpu_clock_offset;
555 } else {
556 ti = get_clock();
557 return ti + timers_state.cpu_clock_offset;
561 /* enable cpu_get_ticks() */
562 void cpu_enable_ticks(void)
564 if (!timers_state.cpu_ticks_enabled) {
565 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
566 timers_state.cpu_clock_offset -= get_clock();
567 timers_state.cpu_ticks_enabled = 1;
571 /* disable cpu_get_ticks() : the clock is stopped. You must not call
572 cpu_get_ticks() after that. */
573 void cpu_disable_ticks(void)
575 if (timers_state.cpu_ticks_enabled) {
576 timers_state.cpu_ticks_offset = cpu_get_ticks();
577 timers_state.cpu_clock_offset = cpu_get_clock();
578 timers_state.cpu_ticks_enabled = 0;
582 /***********************************************************/
583 /* timers */
585 #define QEMU_CLOCK_REALTIME 0
586 #define QEMU_CLOCK_VIRTUAL 1
587 #define QEMU_CLOCK_HOST 2
589 struct QEMUClock {
590 int type;
591 /* XXX: add frequency */
594 struct QEMUTimer {
595 QEMUClock *clock;
596 int64_t expire_time;
597 QEMUTimerCB *cb;
598 void *opaque;
599 struct QEMUTimer *next;
602 struct qemu_alarm_timer {
603 char const *name;
604 unsigned int flags;
606 int (*start)(struct qemu_alarm_timer *t);
607 void (*stop)(struct qemu_alarm_timer *t);
608 void (*rearm)(struct qemu_alarm_timer *t);
609 void *priv;
612 #define ALARM_FLAG_DYNTICKS 0x1
613 #define ALARM_FLAG_EXPIRED 0x2
615 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
617 return t && (t->flags & ALARM_FLAG_DYNTICKS);
620 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
622 if (!alarm_has_dynticks(t))
623 return;
625 t->rearm(t);
628 /* TODO: MIN_TIMER_REARM_US should be optimized */
629 #define MIN_TIMER_REARM_US 250
631 static struct qemu_alarm_timer *alarm_timer;
633 #ifdef _WIN32
635 struct qemu_alarm_win32 {
636 MMRESULT timerId;
637 unsigned int period;
638 } alarm_win32_data = {0, -1};
640 static int win32_start_timer(struct qemu_alarm_timer *t);
641 static void win32_stop_timer(struct qemu_alarm_timer *t);
642 static void win32_rearm_timer(struct qemu_alarm_timer *t);
644 #else
646 static int unix_start_timer(struct qemu_alarm_timer *t);
647 static void unix_stop_timer(struct qemu_alarm_timer *t);
649 #ifdef __linux__
651 static int dynticks_start_timer(struct qemu_alarm_timer *t);
652 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
653 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
655 static int hpet_start_timer(struct qemu_alarm_timer *t);
656 static void hpet_stop_timer(struct qemu_alarm_timer *t);
658 static int rtc_start_timer(struct qemu_alarm_timer *t);
659 static void rtc_stop_timer(struct qemu_alarm_timer *t);
661 #endif /* __linux__ */
663 #endif /* _WIN32 */
665 /* Correlation between real and virtual time is always going to be
666 fairly approximate, so ignore small variation.
667 When the guest is idle real and virtual time will be aligned in
668 the IO wait loop. */
669 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
671 static void icount_adjust(void)
673 int64_t cur_time;
674 int64_t cur_icount;
675 int64_t delta;
676 static int64_t last_delta;
677 /* If the VM is not running, then do nothing. */
678 if (!vm_running)
679 return;
681 cur_time = cpu_get_clock();
682 cur_icount = qemu_get_clock(vm_clock);
683 delta = cur_icount - cur_time;
684 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
685 if (delta > 0
686 && last_delta + ICOUNT_WOBBLE < delta * 2
687 && icount_time_shift > 0) {
688 /* The guest is getting too far ahead. Slow time down. */
689 icount_time_shift--;
691 if (delta < 0
692 && last_delta - ICOUNT_WOBBLE > delta * 2
693 && icount_time_shift < MAX_ICOUNT_SHIFT) {
694 /* The guest is getting too far behind. Speed time up. */
695 icount_time_shift++;
697 last_delta = delta;
698 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
701 static void icount_adjust_rt(void * opaque)
703 qemu_mod_timer(icount_rt_timer,
704 qemu_get_clock(rt_clock) + 1000);
705 icount_adjust();
708 static void icount_adjust_vm(void * opaque)
710 qemu_mod_timer(icount_vm_timer,
711 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
712 icount_adjust();
715 static void init_icount_adjust(void)
717 /* Have both realtime and virtual time triggers for speed adjustment.
718 The realtime trigger catches emulated time passing too slowly,
719 the virtual time trigger catches emulated time passing too fast.
720 Realtime triggers occur even when idle, so use them less frequently
721 than VM triggers. */
722 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
723 qemu_mod_timer(icount_rt_timer,
724 qemu_get_clock(rt_clock) + 1000);
725 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
726 qemu_mod_timer(icount_vm_timer,
727 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
730 static struct qemu_alarm_timer alarm_timers[] = {
731 #ifndef _WIN32
732 #ifdef __linux__
733 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
734 dynticks_stop_timer, dynticks_rearm_timer, NULL},
735 /* HPET - if available - is preferred */
736 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
737 /* ...otherwise try RTC */
738 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
739 #endif
740 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
741 #else
742 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
743 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
744 {"win32", 0, win32_start_timer,
745 win32_stop_timer, NULL, &alarm_win32_data},
746 #endif
747 {NULL, }
750 static void show_available_alarms(void)
752 int i;
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)
761 int i;
762 int cur = 0;
763 int count = ARRAY_SIZE(alarm_timers) - 1;
764 char *arg;
765 char *name;
766 struct qemu_alarm_timer tmp;
768 if (!strcmp(opt, "?")) {
769 show_available_alarms();
770 exit(0);
773 arg = qemu_strdup(opt);
775 /* Reorder the array */
776 name = strtok(arg, ",");
777 while (name) {
778 for (i = 0; i < count && alarm_timers[i].name; i++) {
779 if (!strcmp(alarm_timers[i].name, name))
780 break;
783 if (i == count) {
784 fprintf(stderr, "Unknown clock %s\n", name);
785 goto next;
788 if (i < cur)
789 /* Ignore */
790 goto next;
792 /* Swap */
793 tmp = alarm_timers[i];
794 alarm_timers[i] = alarm_timers[cur];
795 alarm_timers[cur] = tmp;
797 cur++;
798 next:
799 name = strtok(NULL, ",");
802 qemu_free(arg);
804 if (cur) {
805 /* Disable remaining timers */
806 for (i = cur; i < count; i++)
807 alarm_timers[i].name = NULL;
808 } else {
809 show_available_alarms();
810 exit(1);
814 #define QEMU_NUM_CLOCKS 3
816 QEMUClock *rt_clock;
817 QEMUClock *vm_clock;
818 QEMUClock *host_clock;
820 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
822 static QEMUClock *qemu_new_clock(int type)
824 QEMUClock *clock;
825 clock = qemu_mallocz(sizeof(QEMUClock));
826 clock->type = type;
827 return clock;
830 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
832 QEMUTimer *ts;
834 ts = qemu_mallocz(sizeof(QEMUTimer));
835 ts->clock = clock;
836 ts->cb = cb;
837 ts->opaque = opaque;
838 return ts;
841 void qemu_free_timer(QEMUTimer *ts)
843 qemu_free(ts);
846 /* stop a timer, but do not dealloc it */
847 void qemu_del_timer(QEMUTimer *ts)
849 QEMUTimer **pt, *t;
851 /* NOTE: this code must be signal safe because
852 qemu_timer_expired() can be called from a signal. */
853 pt = &active_timers[ts->clock->type];
854 for(;;) {
855 t = *pt;
856 if (!t)
857 break;
858 if (t == ts) {
859 *pt = t->next;
860 break;
862 pt = &t->next;
866 /* modify the current timer so that it will be fired when current_time
867 >= expire_time. The corresponding callback will be called. */
868 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
870 QEMUTimer **pt, *t;
872 qemu_del_timer(ts);
874 /* add the timer in the sorted list */
875 /* NOTE: this code must be signal safe because
876 qemu_timer_expired() can be called from a signal. */
877 pt = &active_timers[ts->clock->type];
878 for(;;) {
879 t = *pt;
880 if (!t)
881 break;
882 if (t->expire_time > expire_time)
883 break;
884 pt = &t->next;
886 ts->expire_time = expire_time;
887 ts->next = *pt;
888 *pt = ts;
890 /* Rearm if necessary */
891 if (pt == &active_timers[ts->clock->type]) {
892 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
893 qemu_rearm_alarm_timer(alarm_timer);
895 /* Interrupt execution to force deadline recalculation. */
896 if (use_icount)
897 qemu_notify_event();
901 int qemu_timer_pending(QEMUTimer *ts)
903 QEMUTimer *t;
904 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
905 if (t == ts)
906 return 1;
908 return 0;
911 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
913 if (!timer_head)
914 return 0;
915 return (timer_head->expire_time <= current_time);
918 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
920 QEMUTimer *ts;
922 for(;;) {
923 ts = *ptimer_head;
924 if (!ts || ts->expire_time > current_time)
925 break;
926 /* remove timer from the list before calling the callback */
927 *ptimer_head = ts->next;
928 ts->next = NULL;
930 /* run the callback (the timer list can be modified) */
931 ts->cb(ts->opaque);
935 int64_t qemu_get_clock(QEMUClock *clock)
937 switch(clock->type) {
938 case QEMU_CLOCK_REALTIME:
939 return get_clock() / 1000000;
940 default:
941 case QEMU_CLOCK_VIRTUAL:
942 if (use_icount) {
943 return cpu_get_icount();
944 } else {
945 return cpu_get_clock();
947 case QEMU_CLOCK_HOST:
948 return get_clock_realtime();
952 int64_t qemu_get_clock_ns(QEMUClock *clock)
954 switch(clock->type) {
955 case QEMU_CLOCK_REALTIME:
956 return get_clock();
957 default:
958 case QEMU_CLOCK_VIRTUAL:
959 if (use_icount) {
960 return cpu_get_icount();
961 } else {
962 return cpu_get_clock();
964 case QEMU_CLOCK_HOST:
965 return get_clock_realtime();
969 static void init_clocks(void)
971 init_get_clock();
972 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
973 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
974 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
976 rtc_clock = host_clock;
979 /* save a timer */
980 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
982 uint64_t expire_time;
984 if (qemu_timer_pending(ts)) {
985 expire_time = ts->expire_time;
986 } else {
987 expire_time = -1;
989 qemu_put_be64(f, expire_time);
992 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
994 uint64_t expire_time;
996 expire_time = qemu_get_be64(f);
997 if (expire_time != -1) {
998 qemu_mod_timer(ts, expire_time);
999 } else {
1000 qemu_del_timer(ts);
1004 static const VMStateDescription vmstate_timers = {
1005 .name = "timer",
1006 .version_id = 2,
1007 .minimum_version_id = 1,
1008 .minimum_version_id_old = 1,
1009 .fields = (VMStateField []) {
1010 VMSTATE_INT64(cpu_ticks_offset, TimersState),
1011 VMSTATE_INT64(dummy, TimersState),
1012 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1013 VMSTATE_END_OF_LIST()
1017 static void qemu_event_increment(void);
1019 #ifdef _WIN32
1020 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1021 DWORD_PTR dwUser, DWORD_PTR dw1,
1022 DWORD_PTR dw2)
1023 #else
1024 static void host_alarm_handler(int host_signum)
1025 #endif
1027 #if 0
1028 #define DISP_FREQ 1000
1030 static int64_t delta_min = INT64_MAX;
1031 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1032 static int count;
1033 ti = qemu_get_clock(vm_clock);
1034 if (last_clock != 0) {
1035 delta = ti - last_clock;
1036 if (delta < delta_min)
1037 delta_min = delta;
1038 if (delta > delta_max)
1039 delta_max = delta;
1040 delta_cum += delta;
1041 if (++count == DISP_FREQ) {
1042 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1043 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1044 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1045 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1046 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1047 count = 0;
1048 delta_min = INT64_MAX;
1049 delta_max = 0;
1050 delta_cum = 0;
1053 last_clock = ti;
1055 #endif
1056 if (alarm_has_dynticks(alarm_timer) ||
1057 (!use_icount &&
1058 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1059 qemu_get_clock(vm_clock))) ||
1060 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1061 qemu_get_clock(rt_clock)) ||
1062 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1063 qemu_get_clock(host_clock))) {
1064 qemu_event_increment();
1065 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1067 #ifndef CONFIG_IOTHREAD
1068 if (next_cpu) {
1069 /* stop the currently executing cpu because a timer occured */
1070 cpu_exit(next_cpu);
1072 #endif
1073 timer_alarm_pending = 1;
1074 qemu_notify_event();
1078 static int64_t qemu_next_deadline(void)
1080 /* To avoid problems with overflow limit this to 2^32. */
1081 int64_t delta = INT32_MAX;
1083 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1084 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1085 qemu_get_clock(vm_clock);
1087 if (active_timers[QEMU_CLOCK_HOST]) {
1088 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1089 qemu_get_clock(host_clock);
1090 if (hdelta < delta)
1091 delta = hdelta;
1094 if (delta < 0)
1095 delta = 0;
1097 return delta;
1100 #if defined(__linux__)
1101 static uint64_t qemu_next_deadline_dyntick(void)
1103 int64_t delta;
1104 int64_t rtdelta;
1106 if (use_icount)
1107 delta = INT32_MAX;
1108 else
1109 delta = (qemu_next_deadline() + 999) / 1000;
1111 if (active_timers[QEMU_CLOCK_REALTIME]) {
1112 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1113 qemu_get_clock(rt_clock))*1000;
1114 if (rtdelta < delta)
1115 delta = rtdelta;
1118 if (delta < MIN_TIMER_REARM_US)
1119 delta = MIN_TIMER_REARM_US;
1121 return delta;
1123 #endif
1125 #ifndef _WIN32
1127 /* Sets a specific flag */
1128 static int fcntl_setfl(int fd, int flag)
1130 int flags;
1132 flags = fcntl(fd, F_GETFL);
1133 if (flags == -1)
1134 return -errno;
1136 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1137 return -errno;
1139 return 0;
1142 #if defined(__linux__)
1144 #define RTC_FREQ 1024
1146 static void enable_sigio_timer(int fd)
1148 struct sigaction act;
1150 /* timer signal */
1151 sigfillset(&act.sa_mask);
1152 act.sa_flags = 0;
1153 act.sa_handler = host_alarm_handler;
1155 sigaction(SIGIO, &act, NULL);
1156 fcntl_setfl(fd, O_ASYNC);
1157 fcntl(fd, F_SETOWN, getpid());
1160 static int hpet_start_timer(struct qemu_alarm_timer *t)
1162 struct hpet_info info;
1163 int r, fd;
1165 fd = qemu_open("/dev/hpet", O_RDONLY);
1166 if (fd < 0)
1167 return -1;
1169 /* Set frequency */
1170 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1171 if (r < 0) {
1172 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1173 "error, but for better emulation accuracy type:\n"
1174 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1175 goto fail;
1178 /* Check capabilities */
1179 r = ioctl(fd, HPET_INFO, &info);
1180 if (r < 0)
1181 goto fail;
1183 /* Enable periodic mode */
1184 r = ioctl(fd, HPET_EPI, 0);
1185 if (info.hi_flags && (r < 0))
1186 goto fail;
1188 /* Enable interrupt */
1189 r = ioctl(fd, HPET_IE_ON, 0);
1190 if (r < 0)
1191 goto fail;
1193 enable_sigio_timer(fd);
1194 t->priv = (void *)(long)fd;
1196 return 0;
1197 fail:
1198 close(fd);
1199 return -1;
1202 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1204 int fd = (long)t->priv;
1206 close(fd);
1209 static int rtc_start_timer(struct qemu_alarm_timer *t)
1211 int rtc_fd;
1212 unsigned long current_rtc_freq = 0;
1214 TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
1215 if (rtc_fd < 0)
1216 return -1;
1217 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1218 if (current_rtc_freq != RTC_FREQ &&
1219 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1220 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1221 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1222 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1223 goto fail;
1225 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1226 fail:
1227 close(rtc_fd);
1228 return -1;
1231 enable_sigio_timer(rtc_fd);
1233 t->priv = (void *)(long)rtc_fd;
1235 return 0;
1238 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1240 int rtc_fd = (long)t->priv;
1242 close(rtc_fd);
1245 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1247 struct sigevent ev;
1248 timer_t host_timer;
1249 struct sigaction act;
1251 sigfillset(&act.sa_mask);
1252 act.sa_flags = 0;
1253 act.sa_handler = host_alarm_handler;
1255 sigaction(SIGALRM, &act, NULL);
1258 * Initialize ev struct to 0 to avoid valgrind complaining
1259 * about uninitialized data in timer_create call
1261 memset(&ev, 0, sizeof(ev));
1262 ev.sigev_value.sival_int = 0;
1263 ev.sigev_notify = SIGEV_SIGNAL;
1264 ev.sigev_signo = SIGALRM;
1266 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1267 perror("timer_create");
1269 /* disable dynticks */
1270 fprintf(stderr, "Dynamic Ticks disabled\n");
1272 return -1;
1275 t->priv = (void *)(long)host_timer;
1277 return 0;
1280 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1282 timer_t host_timer = (timer_t)(long)t->priv;
1284 timer_delete(host_timer);
1287 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1289 timer_t host_timer = (timer_t)(long)t->priv;
1290 struct itimerspec timeout;
1291 int64_t nearest_delta_us = INT64_MAX;
1292 int64_t current_us;
1294 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1295 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1296 !active_timers[QEMU_CLOCK_HOST])
1297 return;
1299 nearest_delta_us = qemu_next_deadline_dyntick();
1301 /* check whether a timer is already running */
1302 if (timer_gettime(host_timer, &timeout)) {
1303 perror("gettime");
1304 fprintf(stderr, "Internal timer error: aborting\n");
1305 exit(1);
1307 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1308 if (current_us && current_us <= nearest_delta_us)
1309 return;
1311 timeout.it_interval.tv_sec = 0;
1312 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1313 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1314 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1315 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1316 perror("settime");
1317 fprintf(stderr, "Internal timer error: aborting\n");
1318 exit(1);
1322 #endif /* defined(__linux__) */
1324 static int unix_start_timer(struct qemu_alarm_timer *t)
1326 struct sigaction act;
1327 struct itimerval itv;
1328 int err;
1330 /* timer signal */
1331 sigfillset(&act.sa_mask);
1332 act.sa_flags = 0;
1333 act.sa_handler = host_alarm_handler;
1335 sigaction(SIGALRM, &act, NULL);
1337 itv.it_interval.tv_sec = 0;
1338 /* for i386 kernel 2.6 to get 1 ms */
1339 itv.it_interval.tv_usec = 999;
1340 itv.it_value.tv_sec = 0;
1341 itv.it_value.tv_usec = 10 * 1000;
1343 err = setitimer(ITIMER_REAL, &itv, NULL);
1344 if (err)
1345 return -1;
1347 return 0;
1350 static void unix_stop_timer(struct qemu_alarm_timer *t)
1352 struct itimerval itv;
1354 memset(&itv, 0, sizeof(itv));
1355 setitimer(ITIMER_REAL, &itv, NULL);
1358 #endif /* !defined(_WIN32) */
1361 #ifdef _WIN32
1363 static int win32_start_timer(struct qemu_alarm_timer *t)
1365 TIMECAPS tc;
1366 struct qemu_alarm_win32 *data = t->priv;
1367 UINT flags;
1369 memset(&tc, 0, sizeof(tc));
1370 timeGetDevCaps(&tc, sizeof(tc));
1372 if (data->period < tc.wPeriodMin)
1373 data->period = tc.wPeriodMin;
1375 timeBeginPeriod(data->period);
1377 flags = TIME_CALLBACK_FUNCTION;
1378 if (alarm_has_dynticks(t))
1379 flags |= TIME_ONESHOT;
1380 else
1381 flags |= TIME_PERIODIC;
1383 data->timerId = timeSetEvent(1, // interval (ms)
1384 data->period, // resolution
1385 host_alarm_handler, // function
1386 (DWORD)t, // parameter
1387 flags);
1389 if (!data->timerId) {
1390 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1391 GetLastError());
1392 timeEndPeriod(data->period);
1393 return -1;
1396 return 0;
1399 static void win32_stop_timer(struct qemu_alarm_timer *t)
1401 struct qemu_alarm_win32 *data = t->priv;
1403 timeKillEvent(data->timerId);
1404 timeEndPeriod(data->period);
1407 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1409 struct qemu_alarm_win32 *data = t->priv;
1411 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1412 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1413 !active_timers[QEMU_CLOCK_HOST])
1414 return;
1416 timeKillEvent(data->timerId);
1418 data->timerId = timeSetEvent(1,
1419 data->period,
1420 host_alarm_handler,
1421 (DWORD)t,
1422 TIME_ONESHOT | TIME_PERIODIC);
1424 if (!data->timerId) {
1425 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1426 GetLastError());
1428 timeEndPeriod(data->period);
1429 exit(1);
1433 #endif /* _WIN32 */
1435 static int init_timer_alarm(void)
1437 struct qemu_alarm_timer *t = NULL;
1438 int i, err = -1;
1440 for (i = 0; alarm_timers[i].name; i++) {
1441 t = &alarm_timers[i];
1443 err = t->start(t);
1444 if (!err)
1445 break;
1448 if (err) {
1449 err = -ENOENT;
1450 goto fail;
1453 alarm_timer = t;
1455 return 0;
1457 fail:
1458 return err;
1461 static void quit_timers(void)
1463 alarm_timer->stop(alarm_timer);
1464 alarm_timer = NULL;
1467 /***********************************************************/
1468 /* host time/date access */
1469 void qemu_get_timedate(struct tm *tm, int offset)
1471 time_t ti;
1472 struct tm *ret;
1474 time(&ti);
1475 ti += offset;
1476 if (rtc_date_offset == -1) {
1477 if (rtc_utc)
1478 ret = gmtime(&ti);
1479 else
1480 ret = localtime(&ti);
1481 } else {
1482 ti -= rtc_date_offset;
1483 ret = gmtime(&ti);
1486 memcpy(tm, ret, sizeof(struct tm));
1489 int qemu_timedate_diff(struct tm *tm)
1491 time_t seconds;
1493 if (rtc_date_offset == -1)
1494 if (rtc_utc)
1495 seconds = mktimegm(tm);
1496 else
1497 seconds = mktime(tm);
1498 else
1499 seconds = mktimegm(tm) + rtc_date_offset;
1501 return seconds - time(NULL);
1504 void rtc_change_mon_event(struct tm *tm)
1506 QObject *data;
1508 data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
1509 monitor_protocol_event(QEVENT_RTC_CHANGE, data);
1510 qobject_decref(data);
1513 static void configure_rtc_date_offset(const char *startdate, int legacy)
1515 time_t rtc_start_date;
1516 struct tm tm;
1518 if (!strcmp(startdate, "now") && legacy) {
1519 rtc_date_offset = -1;
1520 } else {
1521 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1522 &tm.tm_year,
1523 &tm.tm_mon,
1524 &tm.tm_mday,
1525 &tm.tm_hour,
1526 &tm.tm_min,
1527 &tm.tm_sec) == 6) {
1528 /* OK */
1529 } else if (sscanf(startdate, "%d-%d-%d",
1530 &tm.tm_year,
1531 &tm.tm_mon,
1532 &tm.tm_mday) == 3) {
1533 tm.tm_hour = 0;
1534 tm.tm_min = 0;
1535 tm.tm_sec = 0;
1536 } else {
1537 goto date_fail;
1539 tm.tm_year -= 1900;
1540 tm.tm_mon--;
1541 rtc_start_date = mktimegm(&tm);
1542 if (rtc_start_date == -1) {
1543 date_fail:
1544 fprintf(stderr, "Invalid date format. Valid formats are:\n"
1545 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1546 exit(1);
1548 rtc_date_offset = time(NULL) - rtc_start_date;
1552 static void configure_rtc(QemuOpts *opts)
1554 const char *value;
1556 value = qemu_opt_get(opts, "base");
1557 if (value) {
1558 if (!strcmp(value, "utc")) {
1559 rtc_utc = 1;
1560 } else if (!strcmp(value, "localtime")) {
1561 rtc_utc = 0;
1562 } else {
1563 configure_rtc_date_offset(value, 0);
1566 value = qemu_opt_get(opts, "clock");
1567 if (value) {
1568 if (!strcmp(value, "host")) {
1569 rtc_clock = host_clock;
1570 } else if (!strcmp(value, "vm")) {
1571 rtc_clock = vm_clock;
1572 } else {
1573 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1574 exit(1);
1577 #ifdef CONFIG_TARGET_I386
1578 value = qemu_opt_get(opts, "driftfix");
1579 if (value) {
1580 if (!strcmp(buf, "slew")) {
1581 rtc_td_hack = 1;
1582 } else if (!strcmp(buf, "none")) {
1583 rtc_td_hack = 0;
1584 } else {
1585 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1586 exit(1);
1589 #endif
1592 #ifdef _WIN32
1593 static void socket_cleanup(void)
1595 WSACleanup();
1598 static int socket_init(void)
1600 WSADATA Data;
1601 int ret, err;
1603 ret = WSAStartup(MAKEWORD(2,2), &Data);
1604 if (ret != 0) {
1605 err = WSAGetLastError();
1606 fprintf(stderr, "WSAStartup: %d\n", err);
1607 return -1;
1609 atexit(socket_cleanup);
1610 return 0;
1612 #endif
1614 /***********************************************************/
1615 /* Bluetooth support */
1616 static int nb_hcis;
1617 static int cur_hci;
1618 static struct HCIInfo *hci_table[MAX_NICS];
1620 static struct bt_vlan_s {
1621 struct bt_scatternet_s net;
1622 int id;
1623 struct bt_vlan_s *next;
1624 } *first_bt_vlan;
1626 /* find or alloc a new bluetooth "VLAN" */
1627 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1629 struct bt_vlan_s **pvlan, *vlan;
1630 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1631 if (vlan->id == id)
1632 return &vlan->net;
1634 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1635 vlan->id = id;
1636 pvlan = &first_bt_vlan;
1637 while (*pvlan != NULL)
1638 pvlan = &(*pvlan)->next;
1639 *pvlan = vlan;
1640 return &vlan->net;
1643 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1647 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1649 return -ENOTSUP;
1652 static struct HCIInfo null_hci = {
1653 .cmd_send = null_hci_send,
1654 .sco_send = null_hci_send,
1655 .acl_send = null_hci_send,
1656 .bdaddr_set = null_hci_addr_set,
1659 struct HCIInfo *qemu_next_hci(void)
1661 if (cur_hci == nb_hcis)
1662 return &null_hci;
1664 return hci_table[cur_hci++];
1667 static struct HCIInfo *hci_init(const char *str)
1669 char *endp;
1670 struct bt_scatternet_s *vlan = 0;
1672 if (!strcmp(str, "null"))
1673 /* null */
1674 return &null_hci;
1675 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1676 /* host[:hciN] */
1677 return bt_host_hci(str[4] ? str + 5 : "hci0");
1678 else if (!strncmp(str, "hci", 3)) {
1679 /* hci[,vlan=n] */
1680 if (str[3]) {
1681 if (!strncmp(str + 3, ",vlan=", 6)) {
1682 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1683 if (*endp)
1684 vlan = 0;
1686 } else
1687 vlan = qemu_find_bt_vlan(0);
1688 if (vlan)
1689 return bt_new_hci(vlan);
1692 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1694 return 0;
1697 static int bt_hci_parse(const char *str)
1699 struct HCIInfo *hci;
1700 bdaddr_t bdaddr;
1702 if (nb_hcis >= MAX_NICS) {
1703 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1704 return -1;
1707 hci = hci_init(str);
1708 if (!hci)
1709 return -1;
1711 bdaddr.b[0] = 0x52;
1712 bdaddr.b[1] = 0x54;
1713 bdaddr.b[2] = 0x00;
1714 bdaddr.b[3] = 0x12;
1715 bdaddr.b[4] = 0x34;
1716 bdaddr.b[5] = 0x56 + nb_hcis;
1717 hci->bdaddr_set(hci, bdaddr.b);
1719 hci_table[nb_hcis++] = hci;
1721 return 0;
1724 static void bt_vhci_add(int vlan_id)
1726 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1728 if (!vlan->slave)
1729 fprintf(stderr, "qemu: warning: adding a VHCI to "
1730 "an empty scatternet %i\n", vlan_id);
1732 bt_vhci_init(bt_new_hci(vlan));
1735 static struct bt_device_s *bt_device_add(const char *opt)
1737 struct bt_scatternet_s *vlan;
1738 int vlan_id = 0;
1739 char *endp = strstr(opt, ",vlan=");
1740 int len = (endp ? endp - opt : strlen(opt)) + 1;
1741 char devname[10];
1743 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1745 if (endp) {
1746 vlan_id = strtol(endp + 6, &endp, 0);
1747 if (*endp) {
1748 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1749 return 0;
1753 vlan = qemu_find_bt_vlan(vlan_id);
1755 if (!vlan->slave)
1756 fprintf(stderr, "qemu: warning: adding a slave device to "
1757 "an empty scatternet %i\n", vlan_id);
1759 if (!strcmp(devname, "keyboard"))
1760 return bt_keyboard_init(vlan);
1762 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1763 return 0;
1766 static int bt_parse(const char *opt)
1768 const char *endp, *p;
1769 int vlan;
1771 if (strstart(opt, "hci", &endp)) {
1772 if (!*endp || *endp == ',') {
1773 if (*endp)
1774 if (!strstart(endp, ",vlan=", 0))
1775 opt = endp + 1;
1777 return bt_hci_parse(opt);
1779 } else if (strstart(opt, "vhci", &endp)) {
1780 if (!*endp || *endp == ',') {
1781 if (*endp) {
1782 if (strstart(endp, ",vlan=", &p)) {
1783 vlan = strtol(p, (char **) &endp, 0);
1784 if (*endp) {
1785 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1786 return 1;
1788 } else {
1789 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1790 return 1;
1792 } else
1793 vlan = 0;
1795 bt_vhci_add(vlan);
1796 return 0;
1798 } else if (strstart(opt, "device:", &endp))
1799 return !bt_device_add(endp);
1801 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1802 return 1;
1805 /***********************************************************/
1806 /* QEMU Block devices */
1808 #define HD_ALIAS "index=%d,media=disk"
1809 #define CDROM_ALIAS "index=2,media=cdrom"
1810 #define FD_ALIAS "index=%d,if=floppy"
1811 #define PFLASH_ALIAS "if=pflash"
1812 #define MTD_ALIAS "if=mtd"
1813 #define SD_ALIAS "index=0,if=sd"
1815 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1817 va_list ap;
1818 char optstr[1024];
1819 QemuOpts *opts;
1821 va_start(ap, fmt);
1822 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1823 va_end(ap);
1825 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1826 if (!opts) {
1827 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1828 __FUNCTION__, optstr);
1829 return NULL;
1831 if (file)
1832 qemu_opt_set(opts, "file", file);
1833 return opts;
1836 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1838 DriveInfo *dinfo;
1840 /* seek interface, bus and unit */
1842 QTAILQ_FOREACH(dinfo, &drives, next) {
1843 if (dinfo->type == type &&
1844 dinfo->bus == bus &&
1845 dinfo->unit == unit)
1846 return dinfo;
1849 return NULL;
1852 DriveInfo *drive_get_by_id(const char *id)
1854 DriveInfo *dinfo;
1856 QTAILQ_FOREACH(dinfo, &drives, next) {
1857 if (strcmp(id, dinfo->id))
1858 continue;
1859 return dinfo;
1861 return NULL;
1864 int drive_get_max_bus(BlockInterfaceType type)
1866 int max_bus;
1867 DriveInfo *dinfo;
1869 max_bus = -1;
1870 QTAILQ_FOREACH(dinfo, &drives, next) {
1871 if(dinfo->type == type &&
1872 dinfo->bus > max_bus)
1873 max_bus = dinfo->bus;
1875 return max_bus;
1878 const char *drive_get_serial(BlockDriverState *bdrv)
1880 DriveInfo *dinfo;
1882 QTAILQ_FOREACH(dinfo, &drives, next) {
1883 if (dinfo->bdrv == bdrv)
1884 return dinfo->serial;
1887 return "\0";
1890 BlockInterfaceErrorAction drive_get_on_error(
1891 BlockDriverState *bdrv, int is_read)
1893 DriveInfo *dinfo;
1895 QTAILQ_FOREACH(dinfo, &drives, next) {
1896 if (dinfo->bdrv == bdrv)
1897 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
1900 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
1903 static void bdrv_format_print(void *opaque, const char *name)
1905 fprintf(stderr, " %s", name);
1908 void drive_uninit(DriveInfo *dinfo)
1910 qemu_opts_del(dinfo->opts);
1911 bdrv_delete(dinfo->bdrv);
1912 QTAILQ_REMOVE(&drives, dinfo, next);
1913 qemu_free(dinfo);
1916 static int parse_block_error_action(const char *buf, int is_read)
1918 if (!strcmp(buf, "ignore")) {
1919 return BLOCK_ERR_IGNORE;
1920 } else if (!is_read && !strcmp(buf, "enospc")) {
1921 return BLOCK_ERR_STOP_ENOSPC;
1922 } else if (!strcmp(buf, "stop")) {
1923 return BLOCK_ERR_STOP_ANY;
1924 } else if (!strcmp(buf, "report")) {
1925 return BLOCK_ERR_REPORT;
1926 } else {
1927 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
1928 buf, is_read ? "read" : "write");
1929 return -1;
1933 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1934 int *fatal_error)
1936 const char *buf;
1937 const char *file = NULL;
1938 char devname[128];
1939 const char *serial;
1940 const char *mediastr = "";
1941 BlockInterfaceType type;
1942 enum { MEDIA_DISK, MEDIA_CDROM } media;
1943 int bus_id, unit_id;
1944 int cyls, heads, secs, translation;
1945 BlockDriver *drv = NULL;
1946 QEMUMachine *machine = opaque;
1947 int max_devs;
1948 int index;
1949 int cache;
1950 int aio = 0;
1951 int ro = 0;
1952 int bdrv_flags;
1953 int on_read_error, on_write_error;
1954 const char *devaddr;
1955 DriveInfo *dinfo;
1956 int is_extboot = 0;
1957 int snapshot = 0;
1959 *fatal_error = 1;
1961 translation = BIOS_ATA_TRANSLATION_AUTO;
1962 cache = 1;
1964 if (machine && machine->use_scsi) {
1965 type = IF_SCSI;
1966 max_devs = MAX_SCSI_DEVS;
1967 pstrcpy(devname, sizeof(devname), "scsi");
1968 } else {
1969 type = IF_IDE;
1970 max_devs = MAX_IDE_DEVS;
1971 pstrcpy(devname, sizeof(devname), "ide");
1973 media = MEDIA_DISK;
1975 /* extract parameters */
1976 bus_id = qemu_opt_get_number(opts, "bus", 0);
1977 unit_id = qemu_opt_get_number(opts, "unit", -1);
1978 index = qemu_opt_get_number(opts, "index", -1);
1980 cyls = qemu_opt_get_number(opts, "cyls", 0);
1981 heads = qemu_opt_get_number(opts, "heads", 0);
1982 secs = qemu_opt_get_number(opts, "secs", 0);
1984 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1985 ro = qemu_opt_get_bool(opts, "readonly", 0);
1987 file = qemu_opt_get(opts, "file");
1988 serial = qemu_opt_get(opts, "serial");
1990 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1991 pstrcpy(devname, sizeof(devname), buf);
1992 if (!strcmp(buf, "ide")) {
1993 type = IF_IDE;
1994 max_devs = MAX_IDE_DEVS;
1995 } else if (!strcmp(buf, "scsi")) {
1996 type = IF_SCSI;
1997 max_devs = MAX_SCSI_DEVS;
1998 } else if (!strcmp(buf, "floppy")) {
1999 type = IF_FLOPPY;
2000 max_devs = 0;
2001 } else if (!strcmp(buf, "pflash")) {
2002 type = IF_PFLASH;
2003 max_devs = 0;
2004 } else if (!strcmp(buf, "mtd")) {
2005 type = IF_MTD;
2006 max_devs = 0;
2007 } else if (!strcmp(buf, "sd")) {
2008 type = IF_SD;
2009 max_devs = 0;
2010 } else if (!strcmp(buf, "virtio")) {
2011 type = IF_VIRTIO;
2012 max_devs = 0;
2013 } else if (!strcmp(buf, "xen")) {
2014 type = IF_XEN;
2015 max_devs = 0;
2016 } else if (!strcmp(buf, "none")) {
2017 type = IF_NONE;
2018 max_devs = 0;
2019 } else {
2020 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
2021 return NULL;
2025 if (cyls || heads || secs) {
2026 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
2027 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2028 return NULL;
2030 if (heads < 1 || (type == IF_IDE && heads > 16)) {
2031 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2032 return NULL;
2034 if (secs < 1 || (type == IF_IDE && secs > 63)) {
2035 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2036 return NULL;
2040 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2041 if (!cyls) {
2042 fprintf(stderr,
2043 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2044 buf);
2045 return NULL;
2047 if (!strcmp(buf, "none"))
2048 translation = BIOS_ATA_TRANSLATION_NONE;
2049 else if (!strcmp(buf, "lba"))
2050 translation = BIOS_ATA_TRANSLATION_LBA;
2051 else if (!strcmp(buf, "auto"))
2052 translation = BIOS_ATA_TRANSLATION_AUTO;
2053 else {
2054 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2055 return NULL;
2059 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2060 if (!strcmp(buf, "disk")) {
2061 media = MEDIA_DISK;
2062 } else if (!strcmp(buf, "cdrom")) {
2063 if (cyls || secs || heads) {
2064 fprintf(stderr,
2065 "qemu: '%s' invalid physical CHS format\n", buf);
2066 return NULL;
2068 media = MEDIA_CDROM;
2069 } else {
2070 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2071 return NULL;
2075 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2076 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2077 cache = 0;
2078 else if (!strcmp(buf, "writethrough"))
2079 cache = 1;
2080 else if (!strcmp(buf, "writeback"))
2081 cache = 2;
2082 else {
2083 fprintf(stderr, "qemu: invalid cache option\n");
2084 return NULL;
2088 #ifdef CONFIG_LINUX_AIO
2089 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2090 if (!strcmp(buf, "threads"))
2091 aio = 0;
2092 else if (!strcmp(buf, "native"))
2093 aio = 1;
2094 else {
2095 fprintf(stderr, "qemu: invalid aio option\n");
2096 return NULL;
2099 #endif
2101 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2102 if (strcmp(buf, "?") == 0) {
2103 fprintf(stderr, "qemu: Supported formats:");
2104 bdrv_iterate_format(bdrv_format_print, NULL);
2105 fprintf(stderr, "\n");
2106 return NULL;
2108 drv = bdrv_find_whitelisted_format(buf);
2109 if (!drv) {
2110 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2111 return NULL;
2115 is_extboot = qemu_opt_get_bool(opts, "boot", 0);
2116 if (is_extboot && extboot_drive) {
2117 fprintf(stderr, "qemu: two bootable drives specified\n");
2118 return NULL;
2121 on_write_error = BLOCK_ERR_STOP_ENOSPC;
2122 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2123 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2124 fprintf(stderr, "werror is no supported by this format\n");
2125 return NULL;
2128 on_write_error = parse_block_error_action(buf, 0);
2129 if (on_write_error < 0) {
2130 return NULL;
2134 on_read_error = BLOCK_ERR_REPORT;
2135 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2136 if (type != IF_IDE && type != IF_VIRTIO) {
2137 fprintf(stderr, "rerror is no supported by this format\n");
2138 return NULL;
2141 on_read_error = parse_block_error_action(buf, 1);
2142 if (on_read_error < 0) {
2143 return NULL;
2147 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2148 if (type != IF_VIRTIO) {
2149 fprintf(stderr, "addr is not supported\n");
2150 return NULL;
2154 /* compute bus and unit according index */
2156 if (index != -1) {
2157 if (bus_id != 0 || unit_id != -1) {
2158 fprintf(stderr,
2159 "qemu: index cannot be used with bus and unit\n");
2160 return NULL;
2162 if (max_devs == 0)
2164 unit_id = index;
2165 bus_id = 0;
2166 } else {
2167 unit_id = index % max_devs;
2168 bus_id = index / max_devs;
2172 /* if user doesn't specify a unit_id,
2173 * try to find the first free
2176 if (unit_id == -1) {
2177 unit_id = 0;
2178 while (drive_get(type, bus_id, unit_id) != NULL) {
2179 unit_id++;
2180 if (max_devs && unit_id >= max_devs) {
2181 unit_id -= max_devs;
2182 bus_id++;
2187 /* check unit id */
2189 if (max_devs && unit_id >= max_devs) {
2190 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2191 unit_id, max_devs - 1);
2192 return NULL;
2196 * ignore multiple definitions
2199 if (drive_get(type, bus_id, unit_id) != NULL) {
2200 *fatal_error = 0;
2201 return NULL;
2204 /* init */
2206 dinfo = qemu_mallocz(sizeof(*dinfo));
2207 if ((buf = qemu_opts_id(opts)) != NULL) {
2208 dinfo->id = qemu_strdup(buf);
2209 } else {
2210 /* no id supplied -> create one */
2211 dinfo->id = qemu_mallocz(32);
2212 if (type == IF_IDE || type == IF_SCSI)
2213 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2214 if (max_devs)
2215 snprintf(dinfo->id, 32, "%s%i%s%i",
2216 devname, bus_id, mediastr, unit_id);
2217 else
2218 snprintf(dinfo->id, 32, "%s%s%i",
2219 devname, mediastr, unit_id);
2221 dinfo->bdrv = bdrv_new(dinfo->id);
2222 dinfo->devaddr = devaddr;
2223 dinfo->type = type;
2224 dinfo->bus = bus_id;
2225 dinfo->unit = unit_id;
2226 dinfo->on_read_error = on_read_error;
2227 dinfo->on_write_error = on_write_error;
2228 dinfo->opts = opts;
2229 if (serial)
2230 strncpy(dinfo->serial, serial, sizeof(serial));
2231 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2232 if (is_extboot) {
2233 extboot_drive = dinfo;
2236 switch(type) {
2237 case IF_IDE:
2238 case IF_SCSI:
2239 case IF_XEN:
2240 case IF_NONE:
2241 switch(media) {
2242 case MEDIA_DISK:
2243 if (cyls != 0) {
2244 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2245 bdrv_set_translation_hint(dinfo->bdrv, translation);
2247 break;
2248 case MEDIA_CDROM:
2249 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2250 break;
2252 break;
2253 case IF_SD:
2254 /* FIXME: This isn't really a floppy, but it's a reasonable
2255 approximation. */
2256 case IF_FLOPPY:
2257 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2258 break;
2259 case IF_PFLASH:
2260 case IF_MTD:
2261 break;
2262 case IF_VIRTIO:
2263 /* add virtio block device */
2264 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2265 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2266 qemu_opt_set(opts, "drive", dinfo->id);
2267 if (devaddr)
2268 qemu_opt_set(opts, "addr", devaddr);
2269 break;
2270 case IF_COUNT:
2271 abort();
2273 if (!file) {
2274 *fatal_error = 0;
2275 return NULL;
2277 bdrv_flags = 0;
2278 if (snapshot) {
2279 bdrv_flags |= BDRV_O_SNAPSHOT;
2280 cache = 2; /* always use write-back with snapshot */
2282 if (cache == 0) /* no caching */
2283 bdrv_flags |= BDRV_O_NOCACHE;
2284 else if (cache == 2) /* write-back */
2285 bdrv_flags |= BDRV_O_CACHE_WB;
2287 if (aio == 1) {
2288 bdrv_flags |= BDRV_O_NATIVE_AIO;
2289 } else {
2290 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2293 if (ro == 1) {
2294 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
2295 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
2296 return NULL;
2300 * cdrom is read-only. Set it now, after above interface checking
2301 * since readonly attribute not explicitly required, so no error.
2303 if (media == MEDIA_CDROM) {
2304 ro = 1;
2306 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
2308 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2309 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2310 file, strerror(errno));
2311 return NULL;
2314 if (bdrv_key_required(dinfo->bdrv))
2315 autostart = 0;
2316 *fatal_error = 0;
2317 return dinfo;
2320 static int drive_init_func(QemuOpts *opts, void *opaque)
2322 QEMUMachine *machine = opaque;
2323 int fatal_error = 0;
2325 if (drive_init(opts, machine, &fatal_error) == NULL) {
2326 if (fatal_error)
2327 return 1;
2329 return 0;
2332 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2334 if (NULL == qemu_opt_get(opts, "snapshot")) {
2335 qemu_opt_set(opts, "snapshot", "on");
2337 return 0;
2340 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2342 boot_set_handler = func;
2343 boot_set_opaque = opaque;
2346 int qemu_boot_set(const char *boot_devices)
2348 if (!boot_set_handler) {
2349 return -EINVAL;
2351 return boot_set_handler(boot_set_opaque, boot_devices);
2354 static int parse_bootdevices(char *devices)
2356 /* We just do some generic consistency checks */
2357 const char *p;
2358 int bitmap = 0;
2360 for (p = devices; *p != '\0'; p++) {
2361 /* Allowed boot devices are:
2362 * a-b: floppy disk drives
2363 * c-f: IDE disk drives
2364 * g-m: machine implementation dependant drives
2365 * n-p: network devices
2366 * It's up to each machine implementation to check if the given boot
2367 * devices match the actual hardware implementation and firmware
2368 * features.
2370 if (*p < 'a' || *p > 'p') {
2371 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2372 exit(1);
2374 if (bitmap & (1 << (*p - 'a'))) {
2375 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2376 exit(1);
2378 bitmap |= 1 << (*p - 'a');
2380 return bitmap;
2383 static void restore_boot_devices(void *opaque)
2385 char *standard_boot_devices = opaque;
2387 qemu_boot_set(standard_boot_devices);
2389 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2390 qemu_free(standard_boot_devices);
2393 static void numa_add(const char *optarg)
2395 char option[128];
2396 char *endptr;
2397 unsigned long long value, endvalue;
2398 int nodenr;
2400 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2401 if (!strcmp(option, "node")) {
2402 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2403 nodenr = nb_numa_nodes;
2404 } else {
2405 nodenr = strtoull(option, NULL, 10);
2408 if (get_param_value(option, 128, "mem", optarg) == 0) {
2409 node_mem[nodenr] = 0;
2410 } else {
2411 value = strtoull(option, &endptr, 0);
2412 switch (*endptr) {
2413 case 0: case 'M': case 'm':
2414 value <<= 20;
2415 break;
2416 case 'G': case 'g':
2417 value <<= 30;
2418 break;
2420 node_mem[nodenr] = value;
2422 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2423 node_cpumask[nodenr] = 0;
2424 } else {
2425 value = strtoull(option, &endptr, 10);
2426 if (value >= 64) {
2427 value = 63;
2428 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2429 } else {
2430 if (*endptr == '-') {
2431 endvalue = strtoull(endptr+1, &endptr, 10);
2432 if (endvalue >= 63) {
2433 endvalue = 62;
2434 fprintf(stderr,
2435 "only 63 CPUs in NUMA mode supported.\n");
2437 value = (2ULL << endvalue) - (1ULL << value);
2438 } else {
2439 value = 1ULL << value;
2442 node_cpumask[nodenr] = value;
2444 nb_numa_nodes++;
2446 return;
2449 static void smp_parse(const char *optarg)
2451 int smp, sockets = 0, threads = 0, cores = 0;
2452 char *endptr;
2453 char option[128];
2455 smp = strtoul(optarg, &endptr, 10);
2456 if (endptr != optarg) {
2457 if (*endptr == ',') {
2458 endptr++;
2461 if (get_param_value(option, 128, "sockets", endptr) != 0)
2462 sockets = strtoull(option, NULL, 10);
2463 if (get_param_value(option, 128, "cores", endptr) != 0)
2464 cores = strtoull(option, NULL, 10);
2465 if (get_param_value(option, 128, "threads", endptr) != 0)
2466 threads = strtoull(option, NULL, 10);
2467 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2468 max_cpus = strtoull(option, NULL, 10);
2470 /* compute missing values, prefer sockets over cores over threads */
2471 if (smp == 0 || sockets == 0) {
2472 sockets = sockets > 0 ? sockets : 1;
2473 cores = cores > 0 ? cores : 1;
2474 threads = threads > 0 ? threads : 1;
2475 if (smp == 0) {
2476 smp = cores * threads * sockets;
2478 } else {
2479 if (cores == 0) {
2480 threads = threads > 0 ? threads : 1;
2481 cores = smp / (sockets * threads);
2482 } else {
2483 if (sockets) {
2484 threads = smp / (cores * sockets);
2488 smp_cpus = smp;
2489 smp_cores = cores > 0 ? cores : 1;
2490 smp_threads = threads > 0 ? threads : 1;
2491 if (max_cpus == 0)
2492 max_cpus = smp_cpus;
2495 /***********************************************************/
2496 /* USB devices */
2498 static int usb_device_add(const char *devname, int is_hotplug)
2500 const char *p;
2501 USBDevice *dev = NULL;
2503 if (!usb_enabled)
2504 return -1;
2506 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2507 dev = usbdevice_create(devname);
2508 if (dev)
2509 goto done;
2511 /* the other ones */
2512 if (strstart(devname, "host:", &p)) {
2513 dev = usb_host_device_open(p);
2514 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2515 dev = usb_bt_init(devname[2] ? hci_init(p) :
2516 bt_new_hci(qemu_find_bt_vlan(0)));
2517 } else {
2518 return -1;
2520 if (!dev)
2521 return -1;
2523 done:
2524 return 0;
2527 static int usb_device_del(const char *devname)
2529 int bus_num, addr;
2530 const char *p;
2532 if (strstart(devname, "host:", &p))
2533 return usb_host_device_close(p);
2535 if (!usb_enabled)
2536 return -1;
2538 p = strchr(devname, '.');
2539 if (!p)
2540 return -1;
2541 bus_num = strtoul(devname, NULL, 0);
2542 addr = strtoul(p + 1, NULL, 0);
2544 return usb_device_delete_addr(bus_num, addr);
2547 static int usb_parse(const char *cmdline)
2549 int r;
2550 r = usb_device_add(cmdline, 0);
2551 if (r < 0) {
2552 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
2554 return r;
2557 void do_usb_add(Monitor *mon, const QDict *qdict)
2559 const char *devname = qdict_get_str(qdict, "devname");
2560 if (usb_device_add(devname, 1) < 0) {
2561 qemu_error("could not add USB device '%s'\n", devname);
2565 void do_usb_del(Monitor *mon, const QDict *qdict)
2567 const char *devname = qdict_get_str(qdict, "devname");
2568 if (usb_device_del(devname) < 0) {
2569 qemu_error("could not delete USB device '%s'\n", devname);
2573 /***********************************************************/
2574 /* PCMCIA/Cardbus */
2576 static struct pcmcia_socket_entry_s {
2577 PCMCIASocket *socket;
2578 struct pcmcia_socket_entry_s *next;
2579 } *pcmcia_sockets = 0;
2581 void pcmcia_socket_register(PCMCIASocket *socket)
2583 struct pcmcia_socket_entry_s *entry;
2585 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2586 entry->socket = socket;
2587 entry->next = pcmcia_sockets;
2588 pcmcia_sockets = entry;
2591 void pcmcia_socket_unregister(PCMCIASocket *socket)
2593 struct pcmcia_socket_entry_s *entry, **ptr;
2595 ptr = &pcmcia_sockets;
2596 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2597 if (entry->socket == socket) {
2598 *ptr = entry->next;
2599 qemu_free(entry);
2603 void pcmcia_info(Monitor *mon)
2605 struct pcmcia_socket_entry_s *iter;
2607 if (!pcmcia_sockets)
2608 monitor_printf(mon, "No PCMCIA sockets\n");
2610 for (iter = pcmcia_sockets; iter; iter = iter->next)
2611 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2612 iter->socket->attached ? iter->socket->card_string :
2613 "Empty");
2616 /***********************************************************/
2617 /* I/O handling */
2619 typedef struct IOHandlerRecord {
2620 int fd;
2621 IOCanRWHandler *fd_read_poll;
2622 IOHandler *fd_read;
2623 IOHandler *fd_write;
2624 int deleted;
2625 void *opaque;
2626 /* temporary data */
2627 struct pollfd *ufd;
2628 struct IOHandlerRecord *next;
2629 } IOHandlerRecord;
2631 static IOHandlerRecord *first_io_handler;
2633 /* XXX: fd_read_poll should be suppressed, but an API change is
2634 necessary in the character devices to suppress fd_can_read(). */
2635 int qemu_set_fd_handler2(int fd,
2636 IOCanRWHandler *fd_read_poll,
2637 IOHandler *fd_read,
2638 IOHandler *fd_write,
2639 void *opaque)
2641 IOHandlerRecord **pioh, *ioh;
2643 if (!fd_read && !fd_write) {
2644 pioh = &first_io_handler;
2645 for(;;) {
2646 ioh = *pioh;
2647 if (ioh == NULL)
2648 break;
2649 if (ioh->fd == fd) {
2650 ioh->deleted = 1;
2651 break;
2653 pioh = &ioh->next;
2655 } else {
2656 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2657 if (ioh->fd == fd)
2658 goto found;
2660 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2661 ioh->next = first_io_handler;
2662 first_io_handler = ioh;
2663 found:
2664 ioh->fd = fd;
2665 ioh->fd_read_poll = fd_read_poll;
2666 ioh->fd_read = fd_read;
2667 ioh->fd_write = fd_write;
2668 ioh->opaque = opaque;
2669 ioh->deleted = 0;
2671 qemu_notify_event();
2672 return 0;
2675 int qemu_set_fd_handler(int fd,
2676 IOHandler *fd_read,
2677 IOHandler *fd_write,
2678 void *opaque)
2680 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2683 #ifdef _WIN32
2684 /***********************************************************/
2685 /* Polling handling */
2687 typedef struct PollingEntry {
2688 PollingFunc *func;
2689 void *opaque;
2690 struct PollingEntry *next;
2691 } PollingEntry;
2693 static PollingEntry *first_polling_entry;
2695 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2697 PollingEntry **ppe, *pe;
2698 pe = qemu_mallocz(sizeof(PollingEntry));
2699 pe->func = func;
2700 pe->opaque = opaque;
2701 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2702 *ppe = pe;
2703 return 0;
2706 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2708 PollingEntry **ppe, *pe;
2709 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2710 pe = *ppe;
2711 if (pe->func == func && pe->opaque == opaque) {
2712 *ppe = pe->next;
2713 qemu_free(pe);
2714 break;
2719 /***********************************************************/
2720 /* Wait objects support */
2721 typedef struct WaitObjects {
2722 int num;
2723 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2724 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2725 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2726 } WaitObjects;
2728 static WaitObjects wait_objects = {0};
2730 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2732 WaitObjects *w = &wait_objects;
2734 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2735 return -1;
2736 w->events[w->num] = handle;
2737 w->func[w->num] = func;
2738 w->opaque[w->num] = opaque;
2739 w->num++;
2740 return 0;
2743 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2745 int i, found;
2746 WaitObjects *w = &wait_objects;
2748 found = 0;
2749 for (i = 0; i < w->num; i++) {
2750 if (w->events[i] == handle)
2751 found = 1;
2752 if (found) {
2753 w->events[i] = w->events[i + 1];
2754 w->func[i] = w->func[i + 1];
2755 w->opaque[i] = w->opaque[i + 1];
2758 if (found)
2759 w->num--;
2761 #endif
2763 /***********************************************************/
2764 /* ram save/restore */
2766 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2767 #define RAM_SAVE_FLAG_COMPRESS 0x02
2768 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2769 #define RAM_SAVE_FLAG_PAGE 0x08
2770 #define RAM_SAVE_FLAG_EOS 0x10
2772 static int is_dup_page(uint8_t *page, uint8_t ch)
2774 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2775 uint32_t *array = (uint32_t *)page;
2776 int i;
2778 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2779 if (array[i] != val)
2780 return 0;
2783 return 1;
2786 static int ram_save_block(QEMUFile *f)
2788 static ram_addr_t current_addr = 0;
2789 ram_addr_t saved_addr = current_addr;
2790 ram_addr_t addr = 0;
2791 int found = 0;
2793 while (addr < last_ram_offset) {
2794 if (kvm_enabled() && current_addr == 0) {
2795 int r;
2796 r = kvm_update_dirty_pages_log();
2797 if (r) {
2798 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
2799 qemu_file_set_error(f);
2800 return 0;
2803 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2804 uint8_t *p;
2806 cpu_physical_memory_reset_dirty(current_addr,
2807 current_addr + TARGET_PAGE_SIZE,
2808 MIGRATION_DIRTY_FLAG);
2810 p = qemu_get_ram_ptr(current_addr);
2812 if (is_dup_page(p, *p)) {
2813 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2814 qemu_put_byte(f, *p);
2815 } else {
2816 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2817 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2820 found = 1;
2821 break;
2823 addr += TARGET_PAGE_SIZE;
2824 current_addr = (saved_addr + addr) % last_ram_offset;
2827 return found;
2830 static uint64_t bytes_transferred;
2832 static ram_addr_t ram_save_remaining(void)
2834 ram_addr_t addr;
2835 ram_addr_t count = 0;
2837 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2838 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2839 count++;
2842 return count;
2845 uint64_t ram_bytes_remaining(void)
2847 return ram_save_remaining() * TARGET_PAGE_SIZE;
2850 uint64_t ram_bytes_transferred(void)
2852 return bytes_transferred;
2855 uint64_t ram_bytes_total(void)
2857 return last_ram_offset;
2860 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
2862 ram_addr_t addr;
2863 uint64_t bytes_transferred_last;
2864 double bwidth = 0;
2865 uint64_t expected_time = 0;
2867 if (stage < 0) {
2868 cpu_physical_memory_set_dirty_tracking(0);
2869 return 0;
2872 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2873 qemu_file_set_error(f);
2874 return 0;
2877 if (stage == 1) {
2878 bytes_transferred = 0;
2880 /* Make sure all dirty bits are set */
2881 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2882 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2883 cpu_physical_memory_set_dirty(addr);
2886 /* Enable dirty memory tracking */
2887 cpu_physical_memory_set_dirty_tracking(1);
2889 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2892 bytes_transferred_last = bytes_transferred;
2893 bwidth = qemu_get_clock_ns(rt_clock);
2895 while (!qemu_file_rate_limit(f)) {
2896 int ret;
2898 ret = ram_save_block(f);
2899 bytes_transferred += ret * TARGET_PAGE_SIZE;
2900 if (ret == 0) /* no more blocks */
2901 break;
2904 bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
2905 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2907 /* if we haven't transferred anything this round, force expected_time to a
2908 * a very high value, but without crashing */
2909 if (bwidth == 0)
2910 bwidth = 0.000001;
2912 /* try transferring iterative blocks of memory */
2913 if (stage == 3) {
2914 /* flush all remaining blocks regardless of rate limiting */
2915 while (ram_save_block(f) != 0) {
2916 bytes_transferred += TARGET_PAGE_SIZE;
2918 cpu_physical_memory_set_dirty_tracking(0);
2921 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2923 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2925 return (stage == 2) && (expected_time <= migrate_max_downtime());
2928 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2930 ram_addr_t addr;
2931 int flags;
2933 if (version_id != 3)
2934 return -EINVAL;
2936 do {
2937 addr = qemu_get_be64(f);
2939 flags = addr & ~TARGET_PAGE_MASK;
2940 addr &= TARGET_PAGE_MASK;
2942 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2943 if (addr != last_ram_offset)
2944 return -EINVAL;
2947 if (flags & RAM_SAVE_FLAG_COMPRESS) {
2948 uint8_t ch = qemu_get_byte(f);
2949 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
2950 #ifndef _WIN32
2951 if (ch == 0 &&
2952 (!kvm_enabled() || kvm_has_sync_mmu())) {
2953 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
2955 #endif
2956 } else if (flags & RAM_SAVE_FLAG_PAGE) {
2957 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
2959 if (qemu_file_has_error(f)) {
2960 return -EIO;
2962 } while (!(flags & RAM_SAVE_FLAG_EOS));
2964 return 0;
2967 void qemu_service_io(void)
2969 qemu_notify_event();
2972 /***********************************************************/
2973 /* machine registration */
2975 static QEMUMachine *first_machine = NULL;
2976 QEMUMachine *current_machine = NULL;
2978 int qemu_register_machine(QEMUMachine *m)
2980 QEMUMachine **pm;
2981 pm = &first_machine;
2982 while (*pm != NULL)
2983 pm = &(*pm)->next;
2984 m->next = NULL;
2985 *pm = m;
2986 return 0;
2989 static QEMUMachine *find_machine(const char *name)
2991 QEMUMachine *m;
2993 for(m = first_machine; m != NULL; m = m->next) {
2994 if (!strcmp(m->name, name))
2995 return m;
2996 if (m->alias && !strcmp(m->alias, name))
2997 return m;
2999 return NULL;
3002 static QEMUMachine *find_default_machine(void)
3004 QEMUMachine *m;
3006 for(m = first_machine; m != NULL; m = m->next) {
3007 if (m->is_default) {
3008 return m;
3011 return NULL;
3014 /***********************************************************/
3015 /* main execution loop */
3017 static void gui_update(void *opaque)
3019 uint64_t interval = GUI_REFRESH_INTERVAL;
3020 DisplayState *ds = opaque;
3021 DisplayChangeListener *dcl = ds->listeners;
3023 qemu_flush_coalesced_mmio_buffer();
3024 dpy_refresh(ds);
3026 while (dcl != NULL) {
3027 if (dcl->gui_timer_interval &&
3028 dcl->gui_timer_interval < interval)
3029 interval = dcl->gui_timer_interval;
3030 dcl = dcl->next;
3032 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3035 static void nographic_update(void *opaque)
3037 uint64_t interval = GUI_REFRESH_INTERVAL;
3039 qemu_flush_coalesced_mmio_buffer();
3040 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3043 void cpu_synchronize_all_states(void)
3045 CPUState *cpu;
3047 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3048 cpu_synchronize_state(cpu);
3052 void cpu_synchronize_all_post_reset(void)
3054 CPUState *cpu;
3056 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3057 cpu_synchronize_post_reset(cpu);
3061 void cpu_synchronize_all_post_init(void)
3063 CPUState *cpu;
3065 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3066 cpu_synchronize_post_init(cpu);
3070 struct vm_change_state_entry {
3071 VMChangeStateHandler *cb;
3072 void *opaque;
3073 QLIST_ENTRY (vm_change_state_entry) entries;
3076 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3078 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3079 void *opaque)
3081 VMChangeStateEntry *e;
3083 e = qemu_mallocz(sizeof (*e));
3085 e->cb = cb;
3086 e->opaque = opaque;
3087 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3088 return e;
3091 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3093 QLIST_REMOVE (e, entries);
3094 qemu_free (e);
3097 static void vm_state_notify(int running, int reason)
3099 VMChangeStateEntry *e;
3101 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3102 e->cb(e->opaque, running, reason);
3106 static void resume_all_vcpus(void);
3107 static void pause_all_vcpus(void);
3109 void vm_start(void)
3111 if (!vm_running) {
3112 cpu_enable_ticks();
3113 vm_running = 1;
3114 vm_state_notify(1, 0);
3115 qemu_rearm_alarm_timer(alarm_timer);
3116 resume_all_vcpus();
3120 /* reset/shutdown handler */
3122 typedef struct QEMUResetEntry {
3123 QTAILQ_ENTRY(QEMUResetEntry) entry;
3124 QEMUResetHandler *func;
3125 void *opaque;
3126 } QEMUResetEntry;
3128 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3129 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3130 static int reset_requested;
3131 static int shutdown_requested;
3132 static int powerdown_requested;
3133 static int debug_requested;
3134 static int vmstop_requested;
3136 int qemu_no_shutdown(void)
3138 int r = no_shutdown;
3139 no_shutdown = 0;
3140 return r;
3143 int qemu_shutdown_requested(void)
3145 int r = shutdown_requested;
3146 shutdown_requested = 0;
3147 return r;
3150 int qemu_reset_requested(void)
3152 int r = reset_requested;
3153 reset_requested = 0;
3154 return r;
3157 int qemu_powerdown_requested(void)
3159 int r = powerdown_requested;
3160 powerdown_requested = 0;
3161 return r;
3164 static int qemu_debug_requested(void)
3166 int r = debug_requested;
3167 debug_requested = 0;
3168 return r;
3171 static int qemu_vmstop_requested(void)
3173 int r = vmstop_requested;
3174 vmstop_requested = 0;
3175 return r;
3178 static void do_vm_stop(int reason)
3180 if (vm_running) {
3181 cpu_disable_ticks();
3182 vm_running = 0;
3183 pause_all_vcpus();
3184 vm_state_notify(0, reason);
3185 monitor_protocol_event(QEVENT_STOP, NULL);
3189 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3191 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3193 re->func = func;
3194 re->opaque = opaque;
3195 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3198 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3200 QEMUResetEntry *re;
3202 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3203 if (re->func == func && re->opaque == opaque) {
3204 QTAILQ_REMOVE(&reset_handlers, re, entry);
3205 qemu_free(re);
3206 return;
3211 void qemu_system_reset(void)
3213 QEMUResetEntry *re, *nre;
3215 /* reset all devices */
3216 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3217 re->func(re->opaque);
3219 monitor_protocol_event(QEVENT_RESET, NULL);
3220 cpu_synchronize_all_post_reset();
3223 void qemu_system_reset_request(void)
3225 if (no_reboot) {
3226 shutdown_requested = 1;
3227 } else {
3228 reset_requested = 1;
3230 if (cpu_single_env) {
3231 cpu_single_env->stopped = 1;
3233 qemu_notify_event();
3236 void qemu_system_shutdown_request(void)
3238 shutdown_requested = 1;
3239 qemu_notify_event();
3242 void qemu_system_powerdown_request(void)
3244 powerdown_requested = 1;
3245 qemu_notify_event();
3248 #ifdef CONFIG_IOTHREAD
3249 static void qemu_system_vmstop_request(int reason)
3251 vmstop_requested = reason;
3252 qemu_notify_event();
3254 #endif
3256 #ifndef _WIN32
3257 static int io_thread_fd = -1;
3259 static void qemu_event_increment(void)
3261 /* Write 8 bytes to be compatible with eventfd. */
3262 static uint64_t val = 1;
3263 ssize_t ret;
3265 if (io_thread_fd == -1)
3266 return;
3268 do {
3269 ret = write(io_thread_fd, &val, sizeof(val));
3270 } while (ret < 0 && errno == EINTR);
3272 /* EAGAIN is fine, a read must be pending. */
3273 if (ret < 0 && errno != EAGAIN) {
3274 fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
3275 strerror(errno));
3276 exit (1);
3280 static void qemu_event_read(void *opaque)
3282 int fd = (unsigned long)opaque;
3283 ssize_t len;
3284 char buffer[512];
3286 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
3287 do {
3288 len = read(fd, buffer, sizeof(buffer));
3289 } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
3292 static int qemu_event_init(void)
3294 int err;
3295 int fds[2];
3297 err = qemu_eventfd(fds);
3298 if (err == -1)
3299 return -errno;
3301 err = fcntl_setfl(fds[0], O_NONBLOCK);
3302 if (err < 0)
3303 goto fail;
3305 err = fcntl_setfl(fds[1], O_NONBLOCK);
3306 if (err < 0)
3307 goto fail;
3309 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3310 (void *)(unsigned long)fds[0]);
3312 io_thread_fd = fds[1];
3313 return 0;
3315 fail:
3316 close(fds[0]);
3317 close(fds[1]);
3318 return err;
3320 #else
3321 HANDLE qemu_event_handle;
3323 static void dummy_event_handler(void *opaque)
3327 static int qemu_event_init(void)
3329 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3330 if (!qemu_event_handle) {
3331 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3332 return -1;
3334 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3335 return 0;
3338 static void qemu_event_increment(void)
3340 if (!SetEvent(qemu_event_handle)) {
3341 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3342 GetLastError());
3343 exit (1);
3346 #endif
3348 static int cpu_can_run(CPUState *env)
3350 if (env->stop)
3351 return 0;
3352 if (env->stopped)
3353 return 0;
3354 if (!vm_running)
3355 return 0;
3356 return 1;
3359 #ifndef CONFIG_IOTHREAD
3360 static int qemu_init_main_loop(void)
3362 return qemu_event_init();
3365 void qemu_init_vcpu(void *_env)
3367 CPUState *env = _env;
3369 env->nr_cores = smp_cores;
3370 env->nr_threads = smp_threads;
3371 if (kvm_enabled())
3372 kvm_init_vcpu(env);
3373 return;
3376 int qemu_cpu_self(void *env)
3378 return 1;
3381 static void resume_all_vcpus(void)
3385 static void pause_all_vcpus(void)
3389 void qemu_cpu_kick(void *env)
3391 return;
3394 void qemu_notify_event(void)
3396 CPUState *env = cpu_single_env;
3398 if (kvm_enabled()) {
3399 qemu_kvm_notify_work();
3400 return;
3402 if (env) {
3403 cpu_exit(env);
3407 #if defined(KVM_UPSTREAM) || !defined(CONFIG_KVM)
3408 void qemu_mutex_lock_iothread(void) {}
3409 void qemu_mutex_unlock_iothread(void) {}
3410 #endif
3412 void vm_stop(int reason)
3414 do_vm_stop(reason);
3417 #else /* CONFIG_IOTHREAD */
3419 #include "qemu-thread.h"
3421 QemuMutex qemu_global_mutex;
3422 static QemuMutex qemu_fair_mutex;
3424 static QemuThread io_thread;
3426 static QemuThread *tcg_cpu_thread;
3427 static QemuCond *tcg_halt_cond;
3429 static int qemu_system_ready;
3430 /* cpu creation */
3431 static QemuCond qemu_cpu_cond;
3432 /* system init */
3433 static QemuCond qemu_system_cond;
3434 static QemuCond qemu_pause_cond;
3436 static void tcg_block_io_signals(void);
3437 static void kvm_block_io_signals(CPUState *env);
3438 static void unblock_io_signals(void);
3439 static int tcg_has_work(void);
3440 static int cpu_has_work(CPUState *env);
3442 static int qemu_init_main_loop(void)
3444 int ret;
3446 ret = qemu_event_init();
3447 if (ret)
3448 return ret;
3450 qemu_cond_init(&qemu_pause_cond);
3451 qemu_mutex_init(&qemu_fair_mutex);
3452 qemu_mutex_init(&qemu_global_mutex);
3453 qemu_mutex_lock(&qemu_global_mutex);
3455 unblock_io_signals();
3456 qemu_thread_self(&io_thread);
3458 return 0;
3461 static void qemu_wait_io_event_common(CPUState *env)
3463 if (env->stop) {
3464 env->stop = 0;
3465 env->stopped = 1;
3466 qemu_cond_signal(&qemu_pause_cond);
3470 static void qemu_wait_io_event(CPUState *env)
3472 while (!tcg_has_work())
3473 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3475 qemu_mutex_unlock(&qemu_global_mutex);
3478 * Users of qemu_global_mutex can be starved, having no chance
3479 * to acquire it since this path will get to it first.
3480 * So use another lock to provide fairness.
3482 qemu_mutex_lock(&qemu_fair_mutex);
3483 qemu_mutex_unlock(&qemu_fair_mutex);
3485 qemu_mutex_lock(&qemu_global_mutex);
3486 qemu_wait_io_event_common(env);
3489 static void qemu_kvm_eat_signal(CPUState *env, int timeout)
3491 struct timespec ts;
3492 int r, e;
3493 siginfo_t siginfo;
3494 sigset_t waitset;
3496 ts.tv_sec = timeout / 1000;
3497 ts.tv_nsec = (timeout % 1000) * 1000000;
3499 sigemptyset(&waitset);
3500 sigaddset(&waitset, SIG_IPI);
3502 qemu_mutex_unlock(&qemu_global_mutex);
3503 r = sigtimedwait(&waitset, &siginfo, &ts);
3504 e = errno;
3505 qemu_mutex_lock(&qemu_global_mutex);
3507 if (r == -1 && !(e == EAGAIN || e == EINTR)) {
3508 fprintf(stderr, "sigtimedwait: %s\n", strerror(e));
3509 exit(1);
3513 static void qemu_kvm_wait_io_event(CPUState *env)
3515 while (!cpu_has_work(env))
3516 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3518 qemu_kvm_eat_signal(env, 0);
3519 qemu_wait_io_event_common(env);
3522 static int qemu_cpu_exec(CPUState *env);
3524 static void *kvm_cpu_thread_fn(void *arg)
3526 CPUState *env = arg;
3528 qemu_thread_self(env->thread);
3529 if (kvm_enabled())
3530 kvm_init_vcpu(env);
3532 kvm_block_io_signals(env);
3534 /* signal CPU creation */
3535 qemu_mutex_lock(&qemu_global_mutex);
3536 env->created = 1;
3537 qemu_cond_signal(&qemu_cpu_cond);
3539 /* and wait for machine initialization */
3540 while (!qemu_system_ready)
3541 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3543 while (1) {
3544 if (cpu_can_run(env))
3545 qemu_cpu_exec(env);
3546 qemu_kvm_wait_io_event(env);
3549 return NULL;
3552 static void tcg_cpu_exec(void);
3554 static void *tcg_cpu_thread_fn(void *arg)
3556 CPUState *env = arg;
3558 tcg_block_io_signals();
3559 qemu_thread_self(env->thread);
3561 /* signal CPU creation */
3562 qemu_mutex_lock(&qemu_global_mutex);
3563 for (env = first_cpu; env != NULL; env = env->next_cpu)
3564 env->created = 1;
3565 qemu_cond_signal(&qemu_cpu_cond);
3567 /* and wait for machine initialization */
3568 while (!qemu_system_ready)
3569 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3571 while (1) {
3572 tcg_cpu_exec();
3573 qemu_wait_io_event(cur_cpu);
3576 return NULL;
3579 void qemu_cpu_kick(void *_env)
3581 CPUState *env = _env;
3582 qemu_cond_broadcast(env->halt_cond);
3583 if (kvm_enabled())
3584 qemu_thread_signal(env->thread, SIG_IPI);
3587 int qemu_cpu_self(void *_env)
3589 CPUState *env = _env;
3590 QemuThread this;
3592 qemu_thread_self(&this);
3594 return qemu_thread_equal(&this, env->thread);
3597 static void cpu_signal(int sig)
3599 if (cpu_single_env)
3600 cpu_exit(cpu_single_env);
3603 static void tcg_block_io_signals(void)
3605 sigset_t set;
3606 struct sigaction sigact;
3608 sigemptyset(&set);
3609 sigaddset(&set, SIGUSR2);
3610 sigaddset(&set, SIGIO);
3611 sigaddset(&set, SIGALRM);
3612 sigaddset(&set, SIGCHLD);
3613 pthread_sigmask(SIG_BLOCK, &set, NULL);
3615 sigemptyset(&set);
3616 sigaddset(&set, SIG_IPI);
3617 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3619 memset(&sigact, 0, sizeof(sigact));
3620 sigact.sa_handler = cpu_signal;
3621 sigaction(SIG_IPI, &sigact, NULL);
3624 static void dummy_signal(int sig)
3628 static void kvm_block_io_signals(CPUState *env)
3630 int r;
3631 sigset_t set;
3632 struct sigaction sigact;
3634 sigemptyset(&set);
3635 sigaddset(&set, SIGUSR2);
3636 sigaddset(&set, SIGIO);
3637 sigaddset(&set, SIGALRM);
3638 sigaddset(&set, SIGCHLD);
3639 sigaddset(&set, SIG_IPI);
3640 pthread_sigmask(SIG_BLOCK, &set, NULL);
3642 pthread_sigmask(SIG_BLOCK, NULL, &set);
3643 sigdelset(&set, SIG_IPI);
3645 memset(&sigact, 0, sizeof(sigact));
3646 sigact.sa_handler = dummy_signal;
3647 sigaction(SIG_IPI, &sigact, NULL);
3649 r = kvm_set_signal_mask(env, &set);
3650 if (r) {
3651 fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(r));
3652 exit(1);
3656 static void unblock_io_signals(void)
3658 sigset_t set;
3660 sigemptyset(&set);
3661 sigaddset(&set, SIGUSR2);
3662 sigaddset(&set, SIGIO);
3663 sigaddset(&set, SIGALRM);
3664 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3666 sigemptyset(&set);
3667 sigaddset(&set, SIG_IPI);
3668 pthread_sigmask(SIG_BLOCK, &set, NULL);
3671 static void qemu_signal_lock(unsigned int msecs)
3673 qemu_mutex_lock(&qemu_fair_mutex);
3675 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3676 qemu_thread_signal(tcg_cpu_thread, SIG_IPI);
3677 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3678 break;
3680 qemu_mutex_unlock(&qemu_fair_mutex);
3683 void qemu_mutex_lock_iothread(void)
3685 if (kvm_enabled()) {
3686 qemu_mutex_lock(&qemu_fair_mutex);
3687 qemu_mutex_lock(&qemu_global_mutex);
3688 qemu_mutex_unlock(&qemu_fair_mutex);
3689 } else
3690 qemu_signal_lock(100);
3693 void qemu_mutex_unlock_iothread(void)
3695 qemu_mutex_unlock(&qemu_global_mutex);
3698 static int all_vcpus_paused(void)
3700 CPUState *penv = first_cpu;
3702 while (penv) {
3703 if (!penv->stopped)
3704 return 0;
3705 penv = (CPUState *)penv->next_cpu;
3708 return 1;
3711 static void pause_all_vcpus(void)
3713 CPUState *penv = first_cpu;
3715 while (penv) {
3716 penv->stop = 1;
3717 qemu_thread_signal(penv->thread, SIG_IPI);
3718 qemu_cpu_kick(penv);
3719 penv = (CPUState *)penv->next_cpu;
3722 while (!all_vcpus_paused()) {
3723 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3724 penv = first_cpu;
3725 while (penv) {
3726 qemu_thread_signal(penv->thread, SIG_IPI);
3727 penv = (CPUState *)penv->next_cpu;
3732 static void resume_all_vcpus(void)
3734 CPUState *penv = first_cpu;
3736 while (penv) {
3737 penv->stop = 0;
3738 penv->stopped = 0;
3739 qemu_thread_signal(penv->thread, SIG_IPI);
3740 qemu_cpu_kick(penv);
3741 penv = (CPUState *)penv->next_cpu;
3745 static void tcg_init_vcpu(void *_env)
3747 CPUState *env = _env;
3748 /* share a single thread for all cpus with TCG */
3749 if (!tcg_cpu_thread) {
3750 env->thread = qemu_mallocz(sizeof(QemuThread));
3751 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3752 qemu_cond_init(env->halt_cond);
3753 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3754 while (env->created == 0)
3755 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3756 tcg_cpu_thread = env->thread;
3757 tcg_halt_cond = env->halt_cond;
3758 } else {
3759 env->thread = tcg_cpu_thread;
3760 env->halt_cond = tcg_halt_cond;
3764 static void kvm_start_vcpu(CPUState *env)
3766 env->thread = qemu_mallocz(sizeof(QemuThread));
3767 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3768 qemu_cond_init(env->halt_cond);
3769 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3770 while (env->created == 0)
3771 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3774 void qemu_init_vcpu(void *_env)
3776 CPUState *env = _env;
3778 env->nr_cores = smp_cores;
3779 env->nr_threads = smp_threads;
3780 if (kvm_enabled())
3781 kvm_start_vcpu(env);
3782 else
3783 tcg_init_vcpu(env);
3786 void qemu_notify_event(void)
3788 qemu_event_increment();
3791 void vm_stop(int reason)
3793 QemuThread me;
3794 qemu_thread_self(&me);
3796 if (!qemu_thread_equal(&me, &io_thread)) {
3797 qemu_system_vmstop_request(reason);
3799 * FIXME: should not return to device code in case
3800 * vm_stop() has been requested.
3802 if (cpu_single_env) {
3803 cpu_exit(cpu_single_env);
3804 cpu_single_env->stop = 1;
3806 return;
3808 do_vm_stop(reason);
3811 #endif
3814 #ifdef _WIN32
3815 static void host_main_loop_wait(int *timeout)
3817 int ret, ret2, i;
3818 PollingEntry *pe;
3821 /* XXX: need to suppress polling by better using win32 events */
3822 ret = 0;
3823 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3824 ret |= pe->func(pe->opaque);
3826 if (ret == 0) {
3827 int err;
3828 WaitObjects *w = &wait_objects;
3830 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3831 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3832 if (w->func[ret - WAIT_OBJECT_0])
3833 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3835 /* Check for additional signaled events */
3836 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3838 /* Check if event is signaled */
3839 ret2 = WaitForSingleObject(w->events[i], 0);
3840 if(ret2 == WAIT_OBJECT_0) {
3841 if (w->func[i])
3842 w->func[i](w->opaque[i]);
3843 } else if (ret2 == WAIT_TIMEOUT) {
3844 } else {
3845 err = GetLastError();
3846 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3849 } else if (ret == WAIT_TIMEOUT) {
3850 } else {
3851 err = GetLastError();
3852 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3856 *timeout = 0;
3858 #else
3859 static void host_main_loop_wait(int *timeout)
3862 #endif
3864 void main_loop_wait(int timeout)
3866 IOHandlerRecord *ioh;
3867 fd_set rfds, wfds, xfds;
3868 int ret, nfds;
3869 struct timeval tv;
3871 qemu_bh_update_timeout(&timeout);
3873 host_main_loop_wait(&timeout);
3875 /* poll any events */
3876 /* XXX: separate device handlers from system ones */
3877 nfds = -1;
3878 FD_ZERO(&rfds);
3879 FD_ZERO(&wfds);
3880 FD_ZERO(&xfds);
3881 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3882 if (ioh->deleted)
3883 continue;
3884 if (ioh->fd_read &&
3885 (!ioh->fd_read_poll ||
3886 ioh->fd_read_poll(ioh->opaque) != 0)) {
3887 FD_SET(ioh->fd, &rfds);
3888 if (ioh->fd > nfds)
3889 nfds = ioh->fd;
3891 if (ioh->fd_write) {
3892 FD_SET(ioh->fd, &wfds);
3893 if (ioh->fd > nfds)
3894 nfds = ioh->fd;
3898 tv.tv_sec = timeout / 1000;
3899 tv.tv_usec = (timeout % 1000) * 1000;
3901 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3903 qemu_mutex_unlock_iothread();
3904 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3905 qemu_mutex_lock_iothread();
3906 if (ret > 0) {
3907 IOHandlerRecord **pioh;
3909 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3910 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3911 ioh->fd_read(ioh->opaque);
3912 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3913 FD_CLR(ioh->fd, &rfds);
3915 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3916 ioh->fd_write(ioh->opaque);
3920 /* remove deleted IO handlers */
3921 pioh = &first_io_handler;
3922 while (*pioh) {
3923 ioh = *pioh;
3924 if (ioh->deleted) {
3925 *pioh = ioh->next;
3926 qemu_free(ioh);
3927 } else
3928 pioh = &ioh->next;
3932 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3934 /* rearm timer, if not periodic */
3935 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3936 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3937 qemu_rearm_alarm_timer(alarm_timer);
3940 /* vm time timers */
3941 if (vm_running) {
3942 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3943 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3944 qemu_get_clock(vm_clock));
3947 /* real time timers */
3948 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3949 qemu_get_clock(rt_clock));
3951 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3952 qemu_get_clock(host_clock));
3954 /* Check bottom-halves last in case any of the earlier events triggered
3955 them. */
3956 qemu_bh_poll();
3960 static int qemu_cpu_exec(CPUState *env)
3962 int ret;
3963 #ifdef CONFIG_PROFILER
3964 int64_t ti;
3965 #endif
3967 #ifdef CONFIG_PROFILER
3968 ti = profile_getclock();
3969 #endif
3970 if (use_icount) {
3971 int64_t count;
3972 int decr;
3973 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3974 env->icount_decr.u16.low = 0;
3975 env->icount_extra = 0;
3976 count = qemu_next_deadline();
3977 count = (count + (1 << icount_time_shift) - 1)
3978 >> icount_time_shift;
3979 qemu_icount += count;
3980 decr = (count > 0xffff) ? 0xffff : count;
3981 count -= decr;
3982 env->icount_decr.u16.low = decr;
3983 env->icount_extra = count;
3985 ret = cpu_exec(env);
3986 #ifdef CONFIG_PROFILER
3987 qemu_time += profile_getclock() - ti;
3988 #endif
3989 if (use_icount) {
3990 /* Fold pending instructions back into the
3991 instruction counter, and clear the interrupt flag. */
3992 qemu_icount -= (env->icount_decr.u16.low
3993 + env->icount_extra);
3994 env->icount_decr.u32 = 0;
3995 env->icount_extra = 0;
3997 return ret;
4000 static void tcg_cpu_exec(void)
4002 int ret = 0;
4004 if (next_cpu == NULL)
4005 next_cpu = first_cpu;
4006 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4007 CPUState *env = cur_cpu = next_cpu;
4009 if (timer_alarm_pending) {
4010 timer_alarm_pending = 0;
4011 break;
4013 if (cpu_can_run(env))
4014 ret = qemu_cpu_exec(env);
4015 else if (env->stop)
4016 break;
4018 if (ret == EXCP_DEBUG) {
4019 gdb_set_stop_cpu(env);
4020 debug_requested = 1;
4021 break;
4026 static int cpu_has_work(CPUState *env)
4028 if (env->stop)
4029 return 1;
4030 if (env->stopped)
4031 return 0;
4032 if (!env->halted)
4033 return 1;
4034 if (qemu_cpu_has_work(env))
4035 return 1;
4036 return 0;
4039 static int tcg_has_work(void)
4041 CPUState *env;
4043 for (env = first_cpu; env != NULL; env = env->next_cpu)
4044 if (cpu_has_work(env))
4045 return 1;
4046 return 0;
4049 static int qemu_calculate_timeout(void)
4051 #ifndef CONFIG_IOTHREAD
4052 int timeout;
4054 if (!vm_running)
4055 timeout = 5000;
4056 else if (tcg_has_work())
4057 timeout = 0;
4058 else if (!use_icount)
4059 timeout = 5000;
4060 else {
4061 /* XXX: use timeout computed from timers */
4062 int64_t add;
4063 int64_t delta;
4064 /* Advance virtual time to the next event. */
4065 if (use_icount == 1) {
4066 /* When not using an adaptive execution frequency
4067 we tend to get badly out of sync with real time,
4068 so just delay for a reasonable amount of time. */
4069 delta = 0;
4070 } else {
4071 delta = cpu_get_icount() - cpu_get_clock();
4073 if (delta > 0) {
4074 /* If virtual time is ahead of real time then just
4075 wait for IO. */
4076 timeout = (delta / 1000000) + 1;
4077 } else {
4078 /* Wait for either IO to occur or the next
4079 timer event. */
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. */
4084 if (add > 10000000)
4085 add = 10000000;
4086 delta += add;
4087 add = (add + (1 << icount_time_shift) - 1)
4088 >> icount_time_shift;
4089 qemu_icount += add;
4090 timeout = delta / 1000000;
4091 if (timeout < 0)
4092 timeout = 0;
4096 return timeout;
4097 #else /* CONFIG_IOTHREAD */
4098 return 1000;
4099 #endif
4102 static int vm_can_run(void)
4104 if (powerdown_requested)
4105 return 0;
4106 if (reset_requested)
4107 return 0;
4108 if (shutdown_requested)
4109 return 0;
4110 if (debug_requested)
4111 return 0;
4112 return 1;
4115 qemu_irq qemu_system_powerdown;
4117 static void main_loop(void)
4119 int r;
4121 if (kvm_enabled()) {
4122 kvm_main_loop();
4123 cpu_disable_ticks();
4124 return;
4127 #ifdef CONFIG_IOTHREAD
4128 qemu_system_ready = 1;
4129 qemu_cond_broadcast(&qemu_system_cond);
4130 #endif
4132 for (;;) {
4133 do {
4134 #ifdef CONFIG_PROFILER
4135 int64_t ti;
4136 #endif
4137 #ifndef CONFIG_IOTHREAD
4138 tcg_cpu_exec();
4139 #endif
4140 #ifdef CONFIG_PROFILER
4141 ti = profile_getclock();
4142 #endif
4143 main_loop_wait(qemu_calculate_timeout());
4144 #ifdef CONFIG_PROFILER
4145 dev_time += profile_getclock() - ti;
4146 #endif
4147 } while (vm_can_run());
4149 if (qemu_debug_requested()) {
4150 vm_stop(EXCP_DEBUG);
4152 if (qemu_shutdown_requested()) {
4153 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
4154 if (no_shutdown) {
4155 vm_stop(0);
4156 no_shutdown = 0;
4157 } else
4158 break;
4160 if (qemu_reset_requested()) {
4161 pause_all_vcpus();
4162 qemu_system_reset();
4163 resume_all_vcpus();
4165 if (qemu_powerdown_requested()) {
4166 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
4167 qemu_irq_raise(qemu_system_powerdown);
4169 if ((r = qemu_vmstop_requested())) {
4170 vm_stop(r);
4173 pause_all_vcpus();
4176 static void version(void)
4178 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4181 static void help(int exitcode)
4183 const char *options_help =
4184 #define DEF(option, opt_arg, opt_enum, opt_help) \
4185 opt_help
4186 #define DEFHEADING(text) stringify(text) "\n"
4187 #include "qemu-options.h"
4188 #undef DEF
4189 #undef DEFHEADING
4190 #undef GEN_DOCS
4192 version();
4193 printf("usage: %s [options] [disk_image]\n"
4194 "\n"
4195 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4196 "\n"
4197 "%s\n"
4198 "During emulation, the following keys are useful:\n"
4199 "ctrl-alt-f toggle full screen\n"
4200 "ctrl-alt-n switch to virtual console 'n'\n"
4201 "ctrl-alt toggle mouse and keyboard grab\n"
4202 "\n"
4203 "When using -nographic, press 'ctrl-a h' to get some help.\n",
4204 "qemu",
4205 options_help);
4206 exit(exitcode);
4209 #define HAS_ARG 0x0001
4211 enum {
4212 #define DEF(option, opt_arg, opt_enum, opt_help) \
4213 opt_enum,
4214 #define DEFHEADING(text)
4215 #include "qemu-options.h"
4216 #undef DEF
4217 #undef DEFHEADING
4218 #undef GEN_DOCS
4221 typedef struct QEMUOption {
4222 const char *name;
4223 int flags;
4224 int index;
4225 } QEMUOption;
4227 static const QEMUOption qemu_options[] = {
4228 { "h", 0, QEMU_OPTION_h },
4229 #define DEF(option, opt_arg, opt_enum, opt_help) \
4230 { option, opt_arg, opt_enum },
4231 #define DEFHEADING(text)
4232 #include "qemu-options.h"
4233 #undef DEF
4234 #undef DEFHEADING
4235 #undef GEN_DOCS
4236 { NULL },
4239 #ifdef HAS_AUDIO
4240 struct soundhw soundhw[] = {
4241 #ifdef HAS_AUDIO_CHOICE
4242 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4244 "pcspk",
4245 "PC speaker",
4248 { .init_isa = pcspk_audio_init }
4250 #endif
4252 #ifdef CONFIG_SB16
4254 "sb16",
4255 "Creative Sound Blaster 16",
4258 { .init_isa = SB16_init }
4260 #endif
4262 #ifdef CONFIG_CS4231A
4264 "cs4231a",
4265 "CS4231A",
4268 { .init_isa = cs4231a_init }
4270 #endif
4272 #ifdef CONFIG_ADLIB
4274 "adlib",
4275 #ifdef HAS_YMF262
4276 "Yamaha YMF262 (OPL3)",
4277 #else
4278 "Yamaha YM3812 (OPL2)",
4279 #endif
4282 { .init_isa = Adlib_init }
4284 #endif
4286 #ifdef CONFIG_GUS
4288 "gus",
4289 "Gravis Ultrasound GF1",
4292 { .init_isa = GUS_init }
4294 #endif
4296 #ifdef CONFIG_AC97
4298 "ac97",
4299 "Intel 82801AA AC97 Audio",
4302 { .init_pci = ac97_init }
4304 #endif
4306 #ifdef CONFIG_ES1370
4308 "es1370",
4309 "ENSONIQ AudioPCI ES1370",
4312 { .init_pci = es1370_init }
4314 #endif
4316 #endif /* HAS_AUDIO_CHOICE */
4318 { NULL, NULL, 0, 0, { NULL } }
4321 static void select_soundhw (const char *optarg)
4323 struct soundhw *c;
4325 if (*optarg == '?') {
4326 show_valid_cards:
4328 printf ("Valid sound card names (comma separated):\n");
4329 for (c = soundhw; c->name; ++c) {
4330 printf ("%-11s %s\n", c->name, c->descr);
4332 printf ("\n-soundhw all will enable all of the above\n");
4333 exit (*optarg != '?');
4335 else {
4336 size_t l;
4337 const char *p;
4338 char *e;
4339 int bad_card = 0;
4341 if (!strcmp (optarg, "all")) {
4342 for (c = soundhw; c->name; ++c) {
4343 c->enabled = 1;
4345 return;
4348 p = optarg;
4349 while (*p) {
4350 e = strchr (p, ',');
4351 l = !e ? strlen (p) : (size_t) (e - p);
4353 for (c = soundhw; c->name; ++c) {
4354 if (!strncmp (c->name, p, l) && !c->name[l]) {
4355 c->enabled = 1;
4356 break;
4360 if (!c->name) {
4361 if (l > 80) {
4362 fprintf (stderr,
4363 "Unknown sound card name (too big to show)\n");
4365 else {
4366 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4367 (int) l, p);
4369 bad_card = 1;
4371 p += l + (e != NULL);
4374 if (bad_card)
4375 goto show_valid_cards;
4378 #endif
4380 static void select_vgahw (const char *p)
4382 const char *opts;
4384 default_vga = 0;
4385 vga_interface_type = VGA_NONE;
4386 if (strstart(p, "std", &opts)) {
4387 vga_interface_type = VGA_STD;
4388 } else if (strstart(p, "cirrus", &opts)) {
4389 vga_interface_type = VGA_CIRRUS;
4390 } else if (strstart(p, "vmware", &opts)) {
4391 vga_interface_type = VGA_VMWARE;
4392 } else if (strstart(p, "xenfb", &opts)) {
4393 vga_interface_type = VGA_XENFB;
4394 } else if (!strstart(p, "none", &opts)) {
4395 invalid_vga:
4396 fprintf(stderr, "Unknown vga type: %s\n", p);
4397 exit(1);
4399 while (*opts) {
4400 const char *nextopt;
4402 if (strstart(opts, ",retrace=", &nextopt)) {
4403 opts = nextopt;
4404 if (strstart(opts, "dumb", &nextopt))
4405 vga_retrace_method = VGA_RETRACE_DUMB;
4406 else if (strstart(opts, "precise", &nextopt))
4407 vga_retrace_method = VGA_RETRACE_PRECISE;
4408 else goto invalid_vga;
4409 } else goto invalid_vga;
4410 opts = nextopt;
4414 #ifdef TARGET_I386
4415 static int balloon_parse(const char *arg)
4417 QemuOpts *opts;
4419 if (strcmp(arg, "none") == 0) {
4420 return 0;
4423 if (!strncmp(arg, "virtio", 6)) {
4424 if (arg[6] == ',') {
4425 /* have params -> parse them */
4426 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4427 if (!opts)
4428 return -1;
4429 } else {
4430 /* create empty opts */
4431 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4433 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4434 return 0;
4437 return -1;
4439 #endif
4441 #ifdef _WIN32
4442 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4444 exit(STATUS_CONTROL_C_EXIT);
4445 return TRUE;
4447 #endif
4449 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4451 int ret;
4453 if(strlen(str) != 36)
4454 return -1;
4456 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4457 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4458 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4460 if(ret != 16)
4461 return -1;
4463 #ifdef TARGET_I386
4464 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4465 #endif
4467 return 0;
4470 #ifndef _WIN32
4472 static void termsig_handler(int signal)
4474 qemu_system_shutdown_request();
4477 static void sigchld_handler(int signal)
4479 waitpid(-1, NULL, WNOHANG);
4482 static void sighandler_setup(void)
4484 struct sigaction act;
4486 memset(&act, 0, sizeof(act));
4487 act.sa_handler = termsig_handler;
4488 sigaction(SIGINT, &act, NULL);
4489 sigaction(SIGHUP, &act, NULL);
4490 sigaction(SIGTERM, &act, NULL);
4492 act.sa_handler = sigchld_handler;
4493 act.sa_flags = SA_NOCLDSTOP;
4494 sigaction(SIGCHLD, &act, NULL);
4497 #endif
4499 #ifdef _WIN32
4500 /* Look for support files in the same directory as the executable. */
4501 static char *find_datadir(const char *argv0)
4503 char *p;
4504 char buf[MAX_PATH];
4505 DWORD len;
4507 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4508 if (len == 0) {
4509 return NULL;
4512 buf[len] = 0;
4513 p = buf + len - 1;
4514 while (p != buf && *p != '\\')
4515 p--;
4516 *p = 0;
4517 if (access(buf, R_OK) == 0) {
4518 return qemu_strdup(buf);
4520 return NULL;
4522 #else /* !_WIN32 */
4524 /* Find a likely location for support files using the location of the binary.
4525 For installed binaries this will be "$bindir/../share/qemu". When
4526 running from the build tree this will be "$bindir/../pc-bios". */
4527 #define SHARE_SUFFIX "/share/qemu"
4528 #define BUILD_SUFFIX "/pc-bios"
4529 static char *find_datadir(const char *argv0)
4531 char *dir;
4532 char *p = NULL;
4533 char *res;
4534 char buf[PATH_MAX];
4535 size_t max_len;
4537 #if defined(__linux__)
4539 int len;
4540 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4541 if (len > 0) {
4542 buf[len] = 0;
4543 p = buf;
4546 #elif defined(__FreeBSD__)
4548 int len;
4549 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4550 if (len > 0) {
4551 buf[len] = 0;
4552 p = buf;
4555 #endif
4556 /* If we don't have any way of figuring out the actual executable
4557 location then try argv[0]. */
4558 if (!p) {
4559 p = realpath(argv0, buf);
4560 if (!p) {
4561 return NULL;
4564 dir = dirname(p);
4565 dir = dirname(dir);
4567 max_len = strlen(dir) +
4568 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4569 res = qemu_mallocz(max_len);
4570 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4571 if (access(res, R_OK)) {
4572 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4573 if (access(res, R_OK)) {
4574 qemu_free(res);
4575 res = NULL;
4579 return res;
4581 #undef SHARE_SUFFIX
4582 #undef BUILD_SUFFIX
4583 #endif
4585 char *qemu_find_file(int type, const char *name)
4587 int len;
4588 const char *subdir;
4589 char *buf;
4591 /* If name contains path separators then try it as a straight path. */
4592 if ((strchr(name, '/') || strchr(name, '\\'))
4593 && access(name, R_OK) == 0) {
4594 return qemu_strdup(name);
4596 switch (type) {
4597 case QEMU_FILE_TYPE_BIOS:
4598 subdir = "";
4599 break;
4600 case QEMU_FILE_TYPE_KEYMAP:
4601 subdir = "keymaps/";
4602 break;
4603 default:
4604 abort();
4606 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4607 buf = qemu_mallocz(len);
4608 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4609 if (access(buf, R_OK)) {
4610 qemu_free(buf);
4611 return NULL;
4613 return buf;
4616 static int device_help_func(QemuOpts *opts, void *opaque)
4618 return qdev_device_help(opts);
4621 static int device_init_func(QemuOpts *opts, void *opaque)
4623 DeviceState *dev;
4625 dev = qdev_device_add(opts);
4626 if (!dev)
4627 return -1;
4628 return 0;
4631 static int chardev_init_func(QemuOpts *opts, void *opaque)
4633 CharDriverState *chr;
4635 chr = qemu_chr_open_opts(opts, NULL);
4636 if (!chr)
4637 return -1;
4638 return 0;
4641 static int mon_init_func(QemuOpts *opts, void *opaque)
4643 CharDriverState *chr;
4644 const char *chardev;
4645 const char *mode;
4646 int flags;
4648 mode = qemu_opt_get(opts, "mode");
4649 if (mode == NULL) {
4650 mode = "readline";
4652 if (strcmp(mode, "readline") == 0) {
4653 flags = MONITOR_USE_READLINE;
4654 } else if (strcmp(mode, "control") == 0) {
4655 flags = MONITOR_USE_CONTROL;
4656 } else {
4657 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4658 exit(1);
4661 if (qemu_opt_get_bool(opts, "default", 0))
4662 flags |= MONITOR_IS_DEFAULT;
4664 chardev = qemu_opt_get(opts, "chardev");
4665 chr = qemu_chr_find(chardev);
4666 if (chr == NULL) {
4667 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4668 exit(1);
4671 monitor_init(chr, flags);
4672 return 0;
4675 static void monitor_parse(const char *optarg, const char *mode)
4677 static int monitor_device_index = 0;
4678 QemuOpts *opts;
4679 const char *p;
4680 char label[32];
4681 int def = 0;
4683 if (strstart(optarg, "chardev:", &p)) {
4684 snprintf(label, sizeof(label), "%s", p);
4685 } else {
4686 if (monitor_device_index) {
4687 snprintf(label, sizeof(label), "monitor%d",
4688 monitor_device_index);
4689 } else {
4690 snprintf(label, sizeof(label), "monitor");
4691 def = 1;
4693 opts = qemu_chr_parse_compat(label, optarg);
4694 if (!opts) {
4695 fprintf(stderr, "parse error: %s\n", optarg);
4696 exit(1);
4700 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4701 if (!opts) {
4702 fprintf(stderr, "duplicate chardev: %s\n", label);
4703 exit(1);
4705 qemu_opt_set(opts, "mode", mode);
4706 qemu_opt_set(opts, "chardev", label);
4707 if (def)
4708 qemu_opt_set(opts, "default", "on");
4709 monitor_device_index++;
4712 struct device_config {
4713 enum {
4714 DEV_USB, /* -usbdevice */
4715 DEV_BT, /* -bt */
4716 DEV_SERIAL, /* -serial */
4717 DEV_PARALLEL, /* -parallel */
4718 DEV_VIRTCON, /* -virtioconsole */
4719 DEV_DEBUGCON, /* -debugcon */
4720 } type;
4721 const char *cmdline;
4722 QTAILQ_ENTRY(device_config) next;
4724 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4726 static void add_device_config(int type, const char *cmdline)
4728 struct device_config *conf;
4730 conf = qemu_mallocz(sizeof(*conf));
4731 conf->type = type;
4732 conf->cmdline = cmdline;
4733 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4736 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4738 struct device_config *conf;
4739 int rc;
4741 QTAILQ_FOREACH(conf, &device_configs, next) {
4742 if (conf->type != type)
4743 continue;
4744 rc = func(conf->cmdline);
4745 if (0 != rc)
4746 return rc;
4748 return 0;
4751 static int serial_parse(const char *devname)
4753 static int index = 0;
4754 char label[32];
4756 if (strcmp(devname, "none") == 0)
4757 return 0;
4758 if (index == MAX_SERIAL_PORTS) {
4759 fprintf(stderr, "qemu: too many serial ports\n");
4760 exit(1);
4762 snprintf(label, sizeof(label), "serial%d", index);
4763 serial_hds[index] = qemu_chr_open(label, devname, NULL);
4764 if (!serial_hds[index]) {
4765 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4766 devname, strerror(errno));
4767 return -1;
4769 index++;
4770 return 0;
4773 static int parallel_parse(const char *devname)
4775 static int index = 0;
4776 char label[32];
4778 if (strcmp(devname, "none") == 0)
4779 return 0;
4780 if (index == MAX_PARALLEL_PORTS) {
4781 fprintf(stderr, "qemu: too many parallel ports\n");
4782 exit(1);
4784 snprintf(label, sizeof(label), "parallel%d", index);
4785 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4786 if (!parallel_hds[index]) {
4787 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4788 devname, strerror(errno));
4789 return -1;
4791 index++;
4792 return 0;
4795 static int virtcon_parse(const char *devname)
4797 static int index = 0;
4798 char label[32];
4799 QemuOpts *bus_opts, *dev_opts;
4801 if (strcmp(devname, "none") == 0)
4802 return 0;
4803 if (index == MAX_VIRTIO_CONSOLES) {
4804 fprintf(stderr, "qemu: too many virtio consoles\n");
4805 exit(1);
4808 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4809 qemu_opt_set(bus_opts, "driver", "virtio-serial");
4811 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4812 qemu_opt_set(dev_opts, "driver", "virtconsole");
4814 snprintf(label, sizeof(label), "virtcon%d", index);
4815 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
4816 if (!virtcon_hds[index]) {
4817 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
4818 devname, strerror(errno));
4819 return -1;
4821 qemu_opt_set(dev_opts, "chardev", label);
4823 index++;
4824 return 0;
4827 static int debugcon_parse(const char *devname)
4829 QemuOpts *opts;
4831 if (!qemu_chr_open("debugcon", devname, NULL)) {
4832 exit(1);
4834 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
4835 if (!opts) {
4836 fprintf(stderr, "qemu: already have a debugcon device\n");
4837 exit(1);
4839 qemu_opt_set(opts, "driver", "isa-debugcon");
4840 qemu_opt_set(opts, "chardev", "debugcon");
4841 return 0;
4844 static const QEMUOption *lookup_opt(int argc, char **argv,
4845 const char **poptarg, int *poptind)
4847 const QEMUOption *popt;
4848 int optind = *poptind;
4849 char *r = argv[optind];
4850 const char *optarg;
4852 optind++;
4853 /* Treat --foo the same as -foo. */
4854 if (r[1] == '-')
4855 r++;
4856 popt = qemu_options;
4857 for(;;) {
4858 if (!popt->name) {
4859 fprintf(stderr, "%s: invalid option -- '%s'\n",
4860 argv[0], r);
4861 exit(1);
4863 if (!strcmp(popt->name, r + 1))
4864 break;
4865 popt++;
4867 if (popt->flags & HAS_ARG) {
4868 if (optind >= argc) {
4869 fprintf(stderr, "%s: option '%s' requires an argument\n",
4870 argv[0], r);
4871 exit(1);
4873 optarg = argv[optind++];
4874 } else {
4875 optarg = NULL;
4878 *poptarg = optarg;
4879 *poptind = optind;
4881 return popt;
4884 int main(int argc, char **argv, char **envp)
4886 const char *gdbstub_dev = NULL;
4887 uint32_t boot_devices_bitmap = 0;
4888 int i;
4889 int snapshot, linux_boot, net_boot;
4890 const char *initrd_filename;
4891 const char *kernel_filename, *kernel_cmdline;
4892 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4893 DisplayState *ds;
4894 DisplayChangeListener *dcl;
4895 int cyls, heads, secs, translation;
4896 QemuOpts *hda_opts = NULL, *opts;
4897 int optind;
4898 const char *optarg;
4899 const char *loadvm = NULL;
4900 QEMUMachine *machine;
4901 const char *cpu_model;
4902 #ifndef _WIN32
4903 int fds[2];
4904 #endif
4905 int tb_size;
4906 const char *pid_file = NULL;
4907 const char *incoming = NULL;
4908 #ifndef _WIN32
4909 int fd = 0;
4910 struct passwd *pwd = NULL;
4911 const char *chroot_dir = NULL;
4912 const char *run_as = NULL;
4913 #endif
4914 CPUState *env;
4915 int show_vnc_port = 0;
4916 int defconfig = 1;
4918 init_clocks();
4920 qemu_errors_to_file(stderr);
4921 qemu_cache_utils_init(envp);
4923 QLIST_INIT (&vm_change_state_head);
4924 #ifndef _WIN32
4926 struct sigaction act;
4927 sigfillset(&act.sa_mask);
4928 act.sa_flags = 0;
4929 act.sa_handler = SIG_IGN;
4930 sigaction(SIGPIPE, &act, NULL);
4932 #else
4933 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4934 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4935 QEMU to run on a single CPU */
4937 HANDLE h;
4938 DWORD mask, smask;
4939 int i;
4940 h = GetCurrentProcess();
4941 if (GetProcessAffinityMask(h, &mask, &smask)) {
4942 for(i = 0; i < 32; i++) {
4943 if (mask & (1 << i))
4944 break;
4946 if (i != 32) {
4947 mask = 1 << i;
4948 SetProcessAffinityMask(h, mask);
4952 #endif
4954 module_call_init(MODULE_INIT_MACHINE);
4955 machine = find_default_machine();
4956 cpu_model = NULL;
4957 initrd_filename = NULL;
4958 ram_size = 0;
4959 snapshot = 0;
4960 kernel_filename = NULL;
4961 kernel_cmdline = "";
4962 cyls = heads = secs = 0;
4963 translation = BIOS_ATA_TRANSLATION_AUTO;
4965 for (i = 0; i < MAX_NODES; i++) {
4966 node_mem[i] = 0;
4967 node_cpumask[i] = 0;
4970 assigned_devices_index = 0;
4972 nb_numa_nodes = 0;
4973 nb_nics = 0;
4975 tb_size = 0;
4976 autostart= 1;
4978 /* first pass of option parsing */
4979 optind = 1;
4980 while (optind < argc) {
4981 if (argv[optind][0] != '-') {
4982 /* disk image */
4983 optind++;
4984 continue;
4985 } else {
4986 const QEMUOption *popt;
4988 popt = lookup_opt(argc, argv, &optarg, &optind);
4989 switch (popt->index) {
4990 case QEMU_OPTION_nodefconfig:
4991 defconfig=0;
4992 break;
4997 if (defconfig) {
4998 FILE *fp;
4999 fp = fopen(CONFIG_QEMU_CONFDIR "/qemu.conf", "r");
5000 if (fp) {
5001 if (qemu_config_parse(fp) != 0) {
5002 exit(1);
5004 fclose(fp);
5007 fp = fopen(CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf", "r");
5008 if (fp) {
5009 if (qemu_config_parse(fp) != 0) {
5010 exit(1);
5012 fclose(fp);
5015 #if defined(cpudef_setup)
5016 cpudef_setup(); /* parse cpu definitions in target config file */
5017 #endif
5019 /* second pass of option parsing */
5020 optind = 1;
5021 for(;;) {
5022 if (optind >= argc)
5023 break;
5024 if (argv[optind][0] != '-') {
5025 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
5026 } else {
5027 const QEMUOption *popt;
5029 popt = lookup_opt(argc, argv, &optarg, &optind);
5030 switch(popt->index) {
5031 case QEMU_OPTION_M:
5032 machine = find_machine(optarg);
5033 if (!machine) {
5034 QEMUMachine *m;
5035 printf("Supported machines are:\n");
5036 for(m = first_machine; m != NULL; m = m->next) {
5037 if (m->alias)
5038 printf("%-10s %s (alias of %s)\n",
5039 m->alias, m->desc, m->name);
5040 printf("%-10s %s%s\n",
5041 m->name, m->desc,
5042 m->is_default ? " (default)" : "");
5044 exit(*optarg != '?');
5046 break;
5047 case QEMU_OPTION_cpu:
5048 /* hw initialization will check this */
5049 if (*optarg == '?') {
5050 /* XXX: implement xxx_cpu_list for targets that still miss it */
5051 #if defined(cpu_list_id)
5052 cpu_list_id(stdout, &fprintf, optarg);
5053 #elif defined(cpu_list)
5054 cpu_list(stdout, &fprintf); /* deprecated */
5055 #endif
5056 exit(0);
5057 } else {
5058 cpu_model = optarg;
5060 break;
5061 case QEMU_OPTION_initrd:
5062 initrd_filename = optarg;
5063 break;
5064 case QEMU_OPTION_hda:
5065 if (cyls == 0)
5066 hda_opts = drive_add(optarg, HD_ALIAS, 0);
5067 else
5068 hda_opts = drive_add(optarg, HD_ALIAS
5069 ",cyls=%d,heads=%d,secs=%d%s",
5070 0, cyls, heads, secs,
5071 translation == BIOS_ATA_TRANSLATION_LBA ?
5072 ",trans=lba" :
5073 translation == BIOS_ATA_TRANSLATION_NONE ?
5074 ",trans=none" : "");
5075 break;
5076 case QEMU_OPTION_hdb:
5077 case QEMU_OPTION_hdc:
5078 case QEMU_OPTION_hdd:
5079 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5080 break;
5081 case QEMU_OPTION_drive:
5082 drive_add(NULL, "%s", optarg);
5083 break;
5084 case QEMU_OPTION_set:
5085 if (qemu_set_option(optarg) != 0)
5086 exit(1);
5087 break;
5088 case QEMU_OPTION_global:
5089 if (qemu_global_option(optarg) != 0)
5090 exit(1);
5091 break;
5092 case QEMU_OPTION_mtdblock:
5093 drive_add(optarg, MTD_ALIAS);
5094 break;
5095 case QEMU_OPTION_sd:
5096 drive_add(optarg, SD_ALIAS);
5097 break;
5098 case QEMU_OPTION_pflash:
5099 drive_add(optarg, PFLASH_ALIAS);
5100 break;
5101 case QEMU_OPTION_snapshot:
5102 snapshot = 1;
5103 break;
5104 case QEMU_OPTION_hdachs:
5106 const char *p;
5107 p = optarg;
5108 cyls = strtol(p, (char **)&p, 0);
5109 if (cyls < 1 || cyls > 16383)
5110 goto chs_fail;
5111 if (*p != ',')
5112 goto chs_fail;
5113 p++;
5114 heads = strtol(p, (char **)&p, 0);
5115 if (heads < 1 || heads > 16)
5116 goto chs_fail;
5117 if (*p != ',')
5118 goto chs_fail;
5119 p++;
5120 secs = strtol(p, (char **)&p, 0);
5121 if (secs < 1 || secs > 63)
5122 goto chs_fail;
5123 if (*p == ',') {
5124 p++;
5125 if (!strcmp(p, "none"))
5126 translation = BIOS_ATA_TRANSLATION_NONE;
5127 else if (!strcmp(p, "lba"))
5128 translation = BIOS_ATA_TRANSLATION_LBA;
5129 else if (!strcmp(p, "auto"))
5130 translation = BIOS_ATA_TRANSLATION_AUTO;
5131 else
5132 goto chs_fail;
5133 } else if (*p != '\0') {
5134 chs_fail:
5135 fprintf(stderr, "qemu: invalid physical CHS format\n");
5136 exit(1);
5138 if (hda_opts != NULL) {
5139 char num[16];
5140 snprintf(num, sizeof(num), "%d", cyls);
5141 qemu_opt_set(hda_opts, "cyls", num);
5142 snprintf(num, sizeof(num), "%d", heads);
5143 qemu_opt_set(hda_opts, "heads", num);
5144 snprintf(num, sizeof(num), "%d", secs);
5145 qemu_opt_set(hda_opts, "secs", num);
5146 if (translation == BIOS_ATA_TRANSLATION_LBA)
5147 qemu_opt_set(hda_opts, "trans", "lba");
5148 if (translation == BIOS_ATA_TRANSLATION_NONE)
5149 qemu_opt_set(hda_opts, "trans", "none");
5152 break;
5153 case QEMU_OPTION_numa:
5154 if (nb_numa_nodes >= MAX_NODES) {
5155 fprintf(stderr, "qemu: too many NUMA nodes\n");
5156 exit(1);
5158 numa_add(optarg);
5159 break;
5160 case QEMU_OPTION_nographic:
5161 display_type = DT_NOGRAPHIC;
5162 break;
5163 #ifdef CONFIG_CURSES
5164 case QEMU_OPTION_curses:
5165 display_type = DT_CURSES;
5166 break;
5167 #endif
5168 case QEMU_OPTION_portrait:
5169 graphic_rotate = 1;
5170 break;
5171 case QEMU_OPTION_kernel:
5172 kernel_filename = optarg;
5173 break;
5174 case QEMU_OPTION_append:
5175 kernel_cmdline = optarg;
5176 break;
5177 case QEMU_OPTION_cdrom:
5178 drive_add(optarg, CDROM_ALIAS);
5179 break;
5180 case QEMU_OPTION_boot:
5182 static const char * const params[] = {
5183 "order", "once", "menu", NULL
5185 char buf[sizeof(boot_devices)];
5186 char *standard_boot_devices;
5187 int legacy = 0;
5189 if (!strchr(optarg, '=')) {
5190 legacy = 1;
5191 pstrcpy(buf, sizeof(buf), optarg);
5192 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5193 fprintf(stderr,
5194 "qemu: unknown boot parameter '%s' in '%s'\n",
5195 buf, optarg);
5196 exit(1);
5199 if (legacy ||
5200 get_param_value(buf, sizeof(buf), "order", optarg)) {
5201 boot_devices_bitmap = parse_bootdevices(buf);
5202 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5204 if (!legacy) {
5205 if (get_param_value(buf, sizeof(buf),
5206 "once", optarg)) {
5207 boot_devices_bitmap |= parse_bootdevices(buf);
5208 standard_boot_devices = qemu_strdup(boot_devices);
5209 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5210 qemu_register_reset(restore_boot_devices,
5211 standard_boot_devices);
5213 if (get_param_value(buf, sizeof(buf),
5214 "menu", optarg)) {
5215 if (!strcmp(buf, "on")) {
5216 boot_menu = 1;
5217 } else if (!strcmp(buf, "off")) {
5218 boot_menu = 0;
5219 } else {
5220 fprintf(stderr,
5221 "qemu: invalid option value '%s'\n",
5222 buf);
5223 exit(1);
5228 break;
5229 case QEMU_OPTION_fda:
5230 case QEMU_OPTION_fdb:
5231 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5232 break;
5233 #ifdef TARGET_I386
5234 case QEMU_OPTION_no_fd_bootchk:
5235 fd_bootchk = 0;
5236 break;
5237 #endif
5238 case QEMU_OPTION_netdev:
5239 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
5240 exit(1);
5242 break;
5243 case QEMU_OPTION_net:
5244 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
5245 exit(1);
5247 break;
5248 #ifdef CONFIG_SLIRP
5249 case QEMU_OPTION_tftp:
5250 legacy_tftp_prefix = optarg;
5251 break;
5252 case QEMU_OPTION_bootp:
5253 legacy_bootp_filename = optarg;
5254 break;
5255 #ifndef _WIN32
5256 case QEMU_OPTION_smb:
5257 if (net_slirp_smb(optarg) < 0)
5258 exit(1);
5259 break;
5260 #endif
5261 case QEMU_OPTION_redir:
5262 if (net_slirp_redir(optarg) < 0)
5263 exit(1);
5264 break;
5265 #endif
5266 case QEMU_OPTION_bt:
5267 add_device_config(DEV_BT, optarg);
5268 break;
5269 #ifdef HAS_AUDIO
5270 case QEMU_OPTION_audio_help:
5271 AUD_help ();
5272 exit (0);
5273 break;
5274 case QEMU_OPTION_soundhw:
5275 select_soundhw (optarg);
5276 break;
5277 #endif
5278 case QEMU_OPTION_h:
5279 help(0);
5280 break;
5281 case QEMU_OPTION_version:
5282 version();
5283 exit(0);
5284 break;
5285 case QEMU_OPTION_m: {
5286 uint64_t value;
5287 char *ptr;
5289 value = strtoul(optarg, &ptr, 10);
5290 switch (*ptr) {
5291 case 0: case 'M': case 'm':
5292 value <<= 20;
5293 break;
5294 case 'G': case 'g':
5295 value <<= 30;
5296 break;
5297 default:
5298 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5299 exit(1);
5302 /* On 32-bit hosts, QEMU is limited by virtual address space */
5303 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5304 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5305 exit(1);
5307 if (value != (uint64_t)(ram_addr_t)value) {
5308 fprintf(stderr, "qemu: ram size too large\n");
5309 exit(1);
5311 ram_size = value;
5312 break;
5314 case QEMU_OPTION_mempath:
5315 mem_path = optarg;
5316 break;
5317 #ifdef MAP_POPULATE
5318 case QEMU_OPTION_mem_prealloc:
5319 mem_prealloc = 1;
5320 break;
5321 #endif
5322 case QEMU_OPTION_d:
5324 int mask;
5325 const CPULogItem *item;
5327 mask = cpu_str_to_log_mask(optarg);
5328 if (!mask) {
5329 printf("Log items (comma separated):\n");
5330 for(item = cpu_log_items; item->mask != 0; item++) {
5331 printf("%-10s %s\n", item->name, item->help);
5333 exit(1);
5335 cpu_set_log(mask);
5337 break;
5338 case QEMU_OPTION_s:
5339 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5340 break;
5341 case QEMU_OPTION_gdb:
5342 gdbstub_dev = optarg;
5343 break;
5344 case QEMU_OPTION_L:
5345 data_dir = optarg;
5346 break;
5347 case QEMU_OPTION_bios:
5348 bios_name = optarg;
5349 break;
5350 case QEMU_OPTION_singlestep:
5351 singlestep = 1;
5352 break;
5353 case QEMU_OPTION_S:
5354 autostart = 0;
5355 break;
5356 case QEMU_OPTION_k:
5357 keyboard_layout = optarg;
5358 break;
5359 case QEMU_OPTION_localtime:
5360 rtc_utc = 0;
5361 break;
5362 case QEMU_OPTION_vga:
5363 select_vgahw (optarg);
5364 break;
5365 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5366 case QEMU_OPTION_g:
5368 const char *p;
5369 int w, h, depth;
5370 p = optarg;
5371 w = strtol(p, (char **)&p, 10);
5372 if (w <= 0) {
5373 graphic_error:
5374 fprintf(stderr, "qemu: invalid resolution or depth\n");
5375 exit(1);
5377 if (*p != 'x')
5378 goto graphic_error;
5379 p++;
5380 h = strtol(p, (char **)&p, 10);
5381 if (h <= 0)
5382 goto graphic_error;
5383 if (*p == 'x') {
5384 p++;
5385 depth = strtol(p, (char **)&p, 10);
5386 if (depth != 8 && depth != 15 && depth != 16 &&
5387 depth != 24 && depth != 32)
5388 goto graphic_error;
5389 } else if (*p == '\0') {
5390 depth = graphic_depth;
5391 } else {
5392 goto graphic_error;
5395 graphic_width = w;
5396 graphic_height = h;
5397 graphic_depth = depth;
5399 break;
5400 #endif
5401 case QEMU_OPTION_echr:
5403 char *r;
5404 term_escape_char = strtol(optarg, &r, 0);
5405 if (r == optarg)
5406 printf("Bad argument to echr\n");
5407 break;
5409 case QEMU_OPTION_monitor:
5410 monitor_parse(optarg, "readline");
5411 default_monitor = 0;
5412 break;
5413 case QEMU_OPTION_qmp:
5414 monitor_parse(optarg, "control");
5415 default_monitor = 0;
5416 break;
5417 case QEMU_OPTION_mon:
5418 opts = qemu_opts_parse(&qemu_mon_opts, optarg, "chardev");
5419 if (!opts) {
5420 fprintf(stderr, "parse error: %s\n", optarg);
5421 exit(1);
5423 default_monitor = 0;
5424 break;
5425 case QEMU_OPTION_chardev:
5426 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5427 if (!opts) {
5428 fprintf(stderr, "parse error: %s\n", optarg);
5429 exit(1);
5431 break;
5432 case QEMU_OPTION_serial:
5433 add_device_config(DEV_SERIAL, optarg);
5434 default_serial = 0;
5435 if (strncmp(optarg, "mon:", 4) == 0) {
5436 default_monitor = 0;
5438 break;
5439 case QEMU_OPTION_watchdog:
5440 if (watchdog) {
5441 fprintf(stderr,
5442 "qemu: only one watchdog option may be given\n");
5443 return 1;
5445 watchdog = optarg;
5446 break;
5447 case QEMU_OPTION_watchdog_action:
5448 if (select_watchdog_action(optarg) == -1) {
5449 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5450 exit(1);
5452 break;
5453 case QEMU_OPTION_virtiocon:
5454 add_device_config(DEV_VIRTCON, optarg);
5455 default_virtcon = 0;
5456 if (strncmp(optarg, "mon:", 4) == 0) {
5457 default_monitor = 0;
5459 break;
5460 case QEMU_OPTION_parallel:
5461 add_device_config(DEV_PARALLEL, optarg);
5462 default_parallel = 0;
5463 if (strncmp(optarg, "mon:", 4) == 0) {
5464 default_monitor = 0;
5466 break;
5467 case QEMU_OPTION_debugcon:
5468 add_device_config(DEV_DEBUGCON, optarg);
5469 break;
5470 case QEMU_OPTION_loadvm:
5471 loadvm = optarg;
5472 break;
5473 case QEMU_OPTION_full_screen:
5474 full_screen = 1;
5475 break;
5476 #ifdef CONFIG_SDL
5477 case QEMU_OPTION_no_frame:
5478 no_frame = 1;
5479 break;
5480 case QEMU_OPTION_alt_grab:
5481 alt_grab = 1;
5482 break;
5483 case QEMU_OPTION_ctrl_grab:
5484 ctrl_grab = 1;
5485 break;
5486 case QEMU_OPTION_no_quit:
5487 no_quit = 1;
5488 break;
5489 case QEMU_OPTION_sdl:
5490 display_type = DT_SDL;
5491 break;
5492 #endif
5493 case QEMU_OPTION_pidfile:
5494 pid_file = optarg;
5495 break;
5496 #ifdef TARGET_I386
5497 case QEMU_OPTION_win2k_hack:
5498 win2k_install_hack = 1;
5499 break;
5500 case QEMU_OPTION_rtc_td_hack:
5501 rtc_td_hack = 1;
5502 break;
5503 case QEMU_OPTION_acpitable:
5504 if(acpi_table_add(optarg) < 0) {
5505 fprintf(stderr, "Wrong acpi table provided\n");
5506 exit(1);
5508 break;
5509 case QEMU_OPTION_smbios:
5510 if(smbios_entry_add(optarg) < 0) {
5511 fprintf(stderr, "Wrong smbios provided\n");
5512 exit(1);
5514 break;
5515 #endif
5516 #ifdef CONFIG_KVM
5517 #ifdef KVM_UPSTREAM
5518 case QEMU_OPTION_enable_kvm:
5519 kvm_allowed = 1;
5520 #endif
5521 break;
5522 case QEMU_OPTION_no_kvm:
5523 kvm_allowed = 0;
5524 break;
5525 case QEMU_OPTION_no_kvm_irqchip: {
5526 kvm_irqchip = 0;
5527 kvm_pit = 0;
5528 break;
5530 case QEMU_OPTION_no_kvm_pit: {
5531 kvm_pit = 0;
5532 break;
5534 case QEMU_OPTION_no_kvm_pit_reinjection: {
5535 kvm_pit_reinject = 0;
5536 break;
5538 case QEMU_OPTION_enable_nesting: {
5539 kvm_nested = 1;
5540 break;
5542 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5543 case QEMU_OPTION_pcidevice:
5544 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5545 fprintf(stderr, "Too many assigned devices\n");
5546 exit(1);
5548 assigned_devices[assigned_devices_index] = optarg;
5549 assigned_devices_index++;
5550 break;
5551 #endif
5552 #endif
5553 case QEMU_OPTION_usb:
5554 usb_enabled = 1;
5555 break;
5556 case QEMU_OPTION_usbdevice:
5557 usb_enabled = 1;
5558 add_device_config(DEV_USB, optarg);
5559 break;
5560 case QEMU_OPTION_device:
5561 if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5562 exit(1);
5564 break;
5565 case QEMU_OPTION_smp:
5566 smp_parse(optarg);
5567 if (smp_cpus < 1) {
5568 fprintf(stderr, "Invalid number of CPUs\n");
5569 exit(1);
5571 if (max_cpus < smp_cpus) {
5572 fprintf(stderr, "maxcpus must be equal to or greater than "
5573 "smp\n");
5574 exit(1);
5576 if (max_cpus > 255) {
5577 fprintf(stderr, "Unsupported number of maxcpus\n");
5578 exit(1);
5580 break;
5581 case QEMU_OPTION_vnc:
5582 display_type = DT_VNC;
5583 vnc_display = optarg;
5584 break;
5585 #ifdef TARGET_I386
5586 case QEMU_OPTION_no_acpi:
5587 acpi_enabled = 0;
5588 break;
5589 case QEMU_OPTION_no_hpet:
5590 no_hpet = 1;
5591 break;
5592 case QEMU_OPTION_balloon:
5593 if (balloon_parse(optarg) < 0) {
5594 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5595 exit(1);
5597 break;
5598 #endif
5599 case QEMU_OPTION_no_reboot:
5600 no_reboot = 1;
5601 break;
5602 case QEMU_OPTION_no_shutdown:
5603 no_shutdown = 1;
5604 break;
5605 case QEMU_OPTION_show_cursor:
5606 cursor_hide = 0;
5607 break;
5608 case QEMU_OPTION_uuid:
5609 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5610 fprintf(stderr, "Fail to parse UUID string."
5611 " Wrong format.\n");
5612 exit(1);
5614 break;
5615 #ifndef _WIN32
5616 case QEMU_OPTION_daemonize:
5617 daemonize = 1;
5618 break;
5619 #endif
5620 case QEMU_OPTION_option_rom:
5621 if (nb_option_roms >= MAX_OPTION_ROMS) {
5622 fprintf(stderr, "Too many option ROMs\n");
5623 exit(1);
5625 option_rom[nb_option_roms] = optarg;
5626 nb_option_roms++;
5627 break;
5628 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5629 case QEMU_OPTION_semihosting:
5630 semihosting_enabled = 1;
5631 break;
5632 #endif
5633 case QEMU_OPTION_tdf:
5634 time_drift_fix = 1;
5635 break;
5636 case QEMU_OPTION_kvm_shadow_memory:
5637 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5638 break;
5639 case QEMU_OPTION_name:
5640 qemu_name = qemu_strdup(optarg);
5642 char *p = strchr(qemu_name, ',');
5643 if (p != NULL) {
5644 *p++ = 0;
5645 if (strncmp(p, "process=", 8)) {
5646 fprintf(stderr, "Unknown subargument %s to -name", p);
5647 exit(1);
5649 p += 8;
5650 set_proc_name(p);
5653 break;
5654 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5655 case QEMU_OPTION_prom_env:
5656 if (nb_prom_envs >= MAX_PROM_ENVS) {
5657 fprintf(stderr, "Too many prom variables\n");
5658 exit(1);
5660 prom_envs[nb_prom_envs] = optarg;
5661 nb_prom_envs++;
5662 break;
5663 #endif
5664 #ifdef TARGET_ARM
5665 case QEMU_OPTION_old_param:
5666 old_param = 1;
5667 break;
5668 #endif
5669 case QEMU_OPTION_clock:
5670 configure_alarms(optarg);
5671 break;
5672 case QEMU_OPTION_startdate:
5673 configure_rtc_date_offset(optarg, 1);
5674 break;
5675 case QEMU_OPTION_rtc:
5676 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5677 if (!opts) {
5678 fprintf(stderr, "parse error: %s\n", optarg);
5679 exit(1);
5681 configure_rtc(opts);
5682 break;
5683 case QEMU_OPTION_tb_size:
5684 tb_size = strtol(optarg, NULL, 0);
5685 if (tb_size < 0)
5686 tb_size = 0;
5687 break;
5688 case QEMU_OPTION_icount:
5689 use_icount = 1;
5690 if (strcmp(optarg, "auto") == 0) {
5691 icount_time_shift = -1;
5692 } else {
5693 icount_time_shift = strtol(optarg, NULL, 0);
5695 break;
5696 case QEMU_OPTION_incoming:
5697 incoming = optarg;
5698 break;
5699 case QEMU_OPTION_nodefaults:
5700 default_serial = 0;
5701 default_parallel = 0;
5702 default_virtcon = 0;
5703 default_monitor = 0;
5704 default_vga = 0;
5705 default_net = 0;
5706 default_floppy = 0;
5707 default_cdrom = 0;
5708 default_sdcard = 0;
5709 break;
5710 #ifndef _WIN32
5711 case QEMU_OPTION_chroot:
5712 chroot_dir = optarg;
5713 break;
5714 case QEMU_OPTION_runas:
5715 run_as = optarg;
5716 break;
5717 case QEMU_OPTION_nvram:
5718 nvram = optarg;
5719 break;
5720 #endif
5721 #ifdef CONFIG_XEN
5722 case QEMU_OPTION_xen_domid:
5723 xen_domid = atoi(optarg);
5724 break;
5725 case QEMU_OPTION_xen_create:
5726 xen_mode = XEN_CREATE;
5727 break;
5728 case QEMU_OPTION_xen_attach:
5729 xen_mode = XEN_ATTACH;
5730 break;
5731 #endif
5732 case QEMU_OPTION_readconfig:
5734 FILE *fp;
5735 fp = fopen(optarg, "r");
5736 if (fp == NULL) {
5737 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5738 exit(1);
5740 if (qemu_config_parse(fp) != 0) {
5741 exit(1);
5743 fclose(fp);
5744 break;
5746 case QEMU_OPTION_writeconfig:
5748 FILE *fp;
5749 if (strcmp(optarg, "-") == 0) {
5750 fp = stdout;
5751 } else {
5752 fp = fopen(optarg, "w");
5753 if (fp == NULL) {
5754 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5755 exit(1);
5758 qemu_config_write(fp);
5759 fclose(fp);
5760 break;
5766 /* If no data_dir is specified then try to find it relative to the
5767 executable path. */
5768 if (!data_dir) {
5769 data_dir = find_datadir(argv[0]);
5771 /* If all else fails use the install patch specified when building. */
5772 if (!data_dir) {
5773 data_dir = CONFIG_QEMU_SHAREDIR;
5777 * Default to max_cpus = smp_cpus, in case the user doesn't
5778 * specify a max_cpus value.
5780 if (!max_cpus)
5781 max_cpus = smp_cpus;
5783 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5784 if (smp_cpus > machine->max_cpus) {
5785 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5786 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5787 machine->max_cpus);
5788 exit(1);
5791 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5792 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
5794 if (machine->no_serial) {
5795 default_serial = 0;
5797 if (machine->no_parallel) {
5798 default_parallel = 0;
5800 if (!machine->use_virtcon) {
5801 default_virtcon = 0;
5803 if (machine->no_vga) {
5804 default_vga = 0;
5806 if (machine->no_floppy) {
5807 default_floppy = 0;
5809 if (machine->no_cdrom) {
5810 default_cdrom = 0;
5812 if (machine->no_sdcard) {
5813 default_sdcard = 0;
5816 if (display_type == DT_NOGRAPHIC) {
5817 if (default_parallel)
5818 add_device_config(DEV_PARALLEL, "null");
5819 if (default_serial && default_monitor) {
5820 add_device_config(DEV_SERIAL, "mon:stdio");
5821 } else if (default_virtcon && default_monitor) {
5822 add_device_config(DEV_VIRTCON, "mon:stdio");
5823 } else {
5824 if (default_serial)
5825 add_device_config(DEV_SERIAL, "stdio");
5826 if (default_virtcon)
5827 add_device_config(DEV_VIRTCON, "stdio");
5828 if (default_monitor)
5829 monitor_parse("stdio", "readline");
5831 } else {
5832 if (default_serial)
5833 add_device_config(DEV_SERIAL, "vc:80Cx24C");
5834 if (default_parallel)
5835 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
5836 if (default_monitor)
5837 monitor_parse("vc:80Cx24C", "readline");
5838 if (default_virtcon)
5839 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
5841 if (default_vga)
5842 vga_interface_type = VGA_CIRRUS;
5844 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5845 exit(1);
5847 #ifndef _WIN32
5848 if (daemonize) {
5849 pid_t pid;
5851 if (pipe(fds) == -1)
5852 exit(1);
5854 pid = fork();
5855 if (pid > 0) {
5856 uint8_t status;
5857 ssize_t len;
5859 close(fds[1]);
5861 again:
5862 len = read(fds[0], &status, 1);
5863 if (len == -1 && (errno == EINTR))
5864 goto again;
5866 if (len != 1)
5867 exit(1);
5868 else if (status == 1) {
5869 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5870 exit(1);
5871 } else
5872 exit(0);
5873 } else if (pid < 0)
5874 exit(1);
5876 close(fds[0]);
5877 qemu_set_cloexec(fds[1]);
5879 setsid();
5881 pid = fork();
5882 if (pid > 0)
5883 exit(0);
5884 else if (pid < 0)
5885 exit(1);
5887 umask(027);
5889 signal(SIGTSTP, SIG_IGN);
5890 signal(SIGTTOU, SIG_IGN);
5891 signal(SIGTTIN, SIG_IGN);
5893 #endif
5895 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5896 #ifndef _WIN32
5897 if (daemonize) {
5898 uint8_t status = 1;
5899 if (write(fds[1], &status, 1) != 1) {
5900 perror("daemonize. Writing to pipe\n");
5902 } else
5903 #endif
5904 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5905 exit(1);
5908 if (kvm_enabled()) {
5909 int ret;
5911 ret = kvm_init(smp_cpus);
5912 if (ret < 0) {
5913 #if defined(KVM_UPSTREAM) || defined(CONFIG_NO_CPU_EMULATION)
5914 fprintf(stderr, "failed to initialize KVM\n");
5915 exit(1);
5916 #endif
5917 #ifdef CONFIG_KVM
5918 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5919 kvm_allowed = 0;
5920 #endif
5924 if (qemu_init_main_loop()) {
5925 fprintf(stderr, "qemu_init_main_loop failed\n");
5926 exit(1);
5928 linux_boot = (kernel_filename != NULL);
5930 if (!linux_boot && *kernel_cmdline != '\0') {
5931 fprintf(stderr, "-append only allowed with -kernel option\n");
5932 exit(1);
5935 if (!linux_boot && initrd_filename != NULL) {
5936 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5937 exit(1);
5940 #ifndef _WIN32
5941 /* Win32 doesn't support line-buffering and requires size >= 2 */
5942 setvbuf(stdout, NULL, _IOLBF, 0);
5943 #endif
5945 if (init_timer_alarm() < 0) {
5946 fprintf(stderr, "could not initialize alarm timer\n");
5947 exit(1);
5949 if (use_icount && icount_time_shift < 0) {
5950 use_icount = 2;
5951 /* 125MIPS seems a reasonable initial guess at the guest speed.
5952 It will be corrected fairly quickly anyway. */
5953 icount_time_shift = 3;
5954 init_icount_adjust();
5957 #ifdef _WIN32
5958 socket_init();
5959 #endif
5961 if (net_init_clients() < 0) {
5962 exit(1);
5965 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5966 net_set_boot_mask(net_boot);
5968 /* init the bluetooth world */
5969 if (foreach_device_config(DEV_BT, bt_parse))
5970 exit(1);
5972 /* init the memory */
5973 if (ram_size == 0)
5974 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5976 /* init the dynamic translator */
5977 cpu_exec_init_all(tb_size * 1024 * 1024);
5979 bdrv_init_with_whitelist();
5981 blk_mig_init();
5983 if (default_cdrom) {
5984 /* we always create the cdrom drive, even if no disk is there */
5985 drive_add(NULL, CDROM_ALIAS);
5988 if (default_floppy) {
5989 /* we always create at least one floppy */
5990 drive_add(NULL, FD_ALIAS, 0);
5993 if (default_sdcard) {
5994 /* we always create one sd slot, even if no card is in it */
5995 drive_add(NULL, SD_ALIAS);
5998 /* open the virtual block devices */
5999 if (snapshot)
6000 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
6001 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
6002 exit(1);
6004 vmstate_register(0, &vmstate_timers ,&timers_state);
6005 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
6006 ram_load, NULL);
6008 if (nb_numa_nodes > 0) {
6009 int i;
6011 if (nb_numa_nodes > smp_cpus) {
6012 nb_numa_nodes = smp_cpus;
6015 /* If no memory size if given for any node, assume the default case
6016 * and distribute the available memory equally across all nodes
6018 for (i = 0; i < nb_numa_nodes; i++) {
6019 if (node_mem[i] != 0)
6020 break;
6022 if (i == nb_numa_nodes) {
6023 uint64_t usedmem = 0;
6025 /* On Linux, the each node's border has to be 8MB aligned,
6026 * the final node gets the rest.
6028 for (i = 0; i < nb_numa_nodes - 1; i++) {
6029 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
6030 usedmem += node_mem[i];
6032 node_mem[i] = ram_size - usedmem;
6035 for (i = 0; i < nb_numa_nodes; i++) {
6036 if (node_cpumask[i] != 0)
6037 break;
6039 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6040 * must cope with this anyway, because there are BIOSes out there in
6041 * real machines which also use this scheme.
6043 if (i == nb_numa_nodes) {
6044 for (i = 0; i < smp_cpus; i++) {
6045 node_cpumask[i % nb_numa_nodes] |= 1 << i;
6050 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
6051 exit(1);
6052 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
6053 exit(1);
6054 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
6055 exit(1);
6056 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
6057 exit(1);
6059 module_call_init(MODULE_INIT_DEVICE);
6061 if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
6062 exit(0);
6064 if (watchdog) {
6065 i = select_watchdog(watchdog);
6066 if (i > 0)
6067 exit (i == 1 ? 1 : 0);
6070 if (machine->compat_props) {
6071 qdev_prop_register_global_list(machine->compat_props);
6073 qemu_add_globals();
6075 machine->init(ram_size, boot_devices,
6076 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6078 cpu_synchronize_all_post_init();
6080 #ifndef _WIN32
6081 /* must be after terminal init, SDL library changes signal handlers */
6082 sighandler_setup();
6083 #endif
6085 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6086 for (i = 0; i < nb_numa_nodes; i++) {
6087 if (node_cpumask[i] & (1 << env->cpu_index)) {
6088 env->numa_node = i;
6093 current_machine = machine;
6095 /* init USB devices */
6096 if (usb_enabled) {
6097 if (foreach_device_config(DEV_USB, usb_parse) < 0)
6098 exit(1);
6101 /* init generic devices */
6102 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
6103 exit(1);
6105 net_check_clients();
6107 /* just use the first displaystate for the moment */
6108 ds = get_displaystate();
6110 if (display_type == DT_DEFAULT) {
6111 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6112 display_type = DT_SDL;
6113 #else
6114 display_type = DT_VNC;
6115 vnc_display = "localhost:0,to=99";
6116 show_vnc_port = 1;
6117 #endif
6121 switch (display_type) {
6122 case DT_NOGRAPHIC:
6123 break;
6124 #if defined(CONFIG_CURSES)
6125 case DT_CURSES:
6126 curses_display_init(ds, full_screen);
6127 break;
6128 #endif
6129 #if defined(CONFIG_SDL)
6130 case DT_SDL:
6131 sdl_display_init(ds, full_screen, no_frame);
6132 break;
6133 #elif defined(CONFIG_COCOA)
6134 case DT_SDL:
6135 cocoa_display_init(ds, full_screen);
6136 break;
6137 #endif
6138 case DT_VNC:
6139 vnc_display_init(ds);
6140 if (vnc_display_open(ds, vnc_display) < 0)
6141 exit(1);
6143 if (show_vnc_port) {
6144 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6146 break;
6147 default:
6148 break;
6150 dpy_resize(ds);
6152 dcl = ds->listeners;
6153 while (dcl != NULL) {
6154 if (dcl->dpy_refresh != NULL) {
6155 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6156 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6158 dcl = dcl->next;
6161 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6162 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6163 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6166 text_consoles_set_display(ds);
6168 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
6169 exit(1);
6171 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6172 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6173 gdbstub_dev);
6174 exit(1);
6177 qdev_machine_creation_done();
6179 if (rom_load_all() != 0) {
6180 fprintf(stderr, "rom loading failed\n");
6181 exit(1);
6184 qemu_system_reset();
6185 if (loadvm) {
6186 if (load_vmstate(cur_mon, loadvm) < 0) {
6187 autostart = 0;
6191 if (incoming) {
6192 qemu_start_incoming_migration(incoming);
6193 } else if (autostart) {
6194 vm_start();
6197 #ifndef _WIN32
6198 if (daemonize) {
6199 uint8_t status = 0;
6200 ssize_t len;
6202 again1:
6203 len = write(fds[1], &status, 1);
6204 if (len == -1 && (errno == EINTR))
6205 goto again1;
6207 if (len != 1)
6208 exit(1);
6210 if (chdir("/")) {
6211 perror("not able to chdir to /");
6212 exit(1);
6214 TFR(fd = qemu_open("/dev/null", O_RDWR));
6215 if (fd == -1)
6216 exit(1);
6219 if (run_as) {
6220 pwd = getpwnam(run_as);
6221 if (!pwd) {
6222 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6223 exit(1);
6227 if (chroot_dir) {
6228 if (chroot(chroot_dir) < 0) {
6229 fprintf(stderr, "chroot failed\n");
6230 exit(1);
6232 if (chdir("/")) {
6233 perror("not able to chdir to /");
6234 exit(1);
6238 if (run_as) {
6239 if (setgid(pwd->pw_gid) < 0) {
6240 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6241 exit(1);
6243 if (setuid(pwd->pw_uid) < 0) {
6244 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6245 exit(1);
6247 if (setuid(0) != -1) {
6248 fprintf(stderr, "Dropping privileges failed\n");
6249 exit(1);
6253 if (daemonize) {
6254 dup2(fd, 0);
6255 dup2(fd, 1);
6256 dup2(fd, 2);
6258 close(fd);
6260 #endif
6262 main_loop();
6263 quit_timers();
6264 net_cleanup();
6266 return 0;