Add io memory to test device
[qemu-kvm/amd-iommu.git] / vl.c
blob729c95589e24507ed8434ea797898bf985e62ddd
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 int nb_nics;
191 NICInfo nd_table[MAX_NICS];
192 int vm_running;
193 int autostart;
194 static int rtc_utc = 1;
195 static int rtc_date_offset = -1; /* -1 means no change */
196 QEMUClock *rtc_clock;
197 int vga_interface_type = VGA_NONE;
198 #ifdef TARGET_SPARC
199 int graphic_width = 1024;
200 int graphic_height = 768;
201 int graphic_depth = 8;
202 #else
203 int graphic_width = 800;
204 int graphic_height = 600;
205 int graphic_depth = 15;
206 #endif
207 static int full_screen = 0;
208 #ifdef CONFIG_SDL
209 static int no_frame = 0;
210 #endif
211 int no_quit = 0;
212 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
213 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
214 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
215 #ifdef TARGET_I386
216 int win2k_install_hack = 0;
217 int rtc_td_hack = 0;
218 #endif
219 int usb_enabled = 0;
220 int singlestep = 0;
221 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
222 int assigned_devices_index;
223 int smp_cpus = 1;
224 int max_cpus = 0;
225 int smp_cores = 1;
226 int smp_threads = 1;
227 const char *vnc_display;
228 int acpi_enabled = 1;
229 #ifdef TARGET_I386
230 int no_hpet = 0;
231 #endif
232 int fd_bootchk = 1;
233 int no_reboot = 0;
234 int no_shutdown = 0;
235 int cursor_hide = 1;
236 int graphic_rotate = 0;
237 uint8_t irq0override = 1;
238 #ifndef _WIN32
239 int daemonize = 0;
240 #endif
241 const char *watchdog;
242 const char *option_rom[MAX_OPTION_ROMS];
243 int nb_option_roms;
244 int semihosting_enabled = 0;
245 int time_drift_fix = 0;
246 unsigned int kvm_shadow_memory = 0;
247 const char *mem_path = NULL;
248 #ifdef MAP_POPULATE
249 int mem_prealloc = 1; /* force preallocation of physical target memory */
250 #endif
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 static void configure_rtc_date_offset(const char *startdate, int legacy)
1506 time_t rtc_start_date;
1507 struct tm tm;
1509 if (!strcmp(startdate, "now") && legacy) {
1510 rtc_date_offset = -1;
1511 } else {
1512 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1513 &tm.tm_year,
1514 &tm.tm_mon,
1515 &tm.tm_mday,
1516 &tm.tm_hour,
1517 &tm.tm_min,
1518 &tm.tm_sec) == 6) {
1519 /* OK */
1520 } else if (sscanf(startdate, "%d-%d-%d",
1521 &tm.tm_year,
1522 &tm.tm_mon,
1523 &tm.tm_mday) == 3) {
1524 tm.tm_hour = 0;
1525 tm.tm_min = 0;
1526 tm.tm_sec = 0;
1527 } else {
1528 goto date_fail;
1530 tm.tm_year -= 1900;
1531 tm.tm_mon--;
1532 rtc_start_date = mktimegm(&tm);
1533 if (rtc_start_date == -1) {
1534 date_fail:
1535 fprintf(stderr, "Invalid date format. Valid formats are:\n"
1536 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1537 exit(1);
1539 rtc_date_offset = time(NULL) - rtc_start_date;
1543 static void configure_rtc(QemuOpts *opts)
1545 const char *value;
1547 value = qemu_opt_get(opts, "base");
1548 if (value) {
1549 if (!strcmp(value, "utc")) {
1550 rtc_utc = 1;
1551 } else if (!strcmp(value, "localtime")) {
1552 rtc_utc = 0;
1553 } else {
1554 configure_rtc_date_offset(value, 0);
1557 value = qemu_opt_get(opts, "clock");
1558 if (value) {
1559 if (!strcmp(value, "host")) {
1560 rtc_clock = host_clock;
1561 } else if (!strcmp(value, "vm")) {
1562 rtc_clock = vm_clock;
1563 } else {
1564 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1565 exit(1);
1568 #ifdef CONFIG_TARGET_I386
1569 value = qemu_opt_get(opts, "driftfix");
1570 if (value) {
1571 if (!strcmp(buf, "slew")) {
1572 rtc_td_hack = 1;
1573 } else if (!strcmp(buf, "none")) {
1574 rtc_td_hack = 0;
1575 } else {
1576 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1577 exit(1);
1580 #endif
1583 #ifdef _WIN32
1584 static void socket_cleanup(void)
1586 WSACleanup();
1589 static int socket_init(void)
1591 WSADATA Data;
1592 int ret, err;
1594 ret = WSAStartup(MAKEWORD(2,2), &Data);
1595 if (ret != 0) {
1596 err = WSAGetLastError();
1597 fprintf(stderr, "WSAStartup: %d\n", err);
1598 return -1;
1600 atexit(socket_cleanup);
1601 return 0;
1603 #endif
1605 /***********************************************************/
1606 /* Bluetooth support */
1607 static int nb_hcis;
1608 static int cur_hci;
1609 static struct HCIInfo *hci_table[MAX_NICS];
1611 static struct bt_vlan_s {
1612 struct bt_scatternet_s net;
1613 int id;
1614 struct bt_vlan_s *next;
1615 } *first_bt_vlan;
1617 /* find or alloc a new bluetooth "VLAN" */
1618 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1620 struct bt_vlan_s **pvlan, *vlan;
1621 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1622 if (vlan->id == id)
1623 return &vlan->net;
1625 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1626 vlan->id = id;
1627 pvlan = &first_bt_vlan;
1628 while (*pvlan != NULL)
1629 pvlan = &(*pvlan)->next;
1630 *pvlan = vlan;
1631 return &vlan->net;
1634 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1638 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1640 return -ENOTSUP;
1643 static struct HCIInfo null_hci = {
1644 .cmd_send = null_hci_send,
1645 .sco_send = null_hci_send,
1646 .acl_send = null_hci_send,
1647 .bdaddr_set = null_hci_addr_set,
1650 struct HCIInfo *qemu_next_hci(void)
1652 if (cur_hci == nb_hcis)
1653 return &null_hci;
1655 return hci_table[cur_hci++];
1658 static struct HCIInfo *hci_init(const char *str)
1660 char *endp;
1661 struct bt_scatternet_s *vlan = 0;
1663 if (!strcmp(str, "null"))
1664 /* null */
1665 return &null_hci;
1666 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1667 /* host[:hciN] */
1668 return bt_host_hci(str[4] ? str + 5 : "hci0");
1669 else if (!strncmp(str, "hci", 3)) {
1670 /* hci[,vlan=n] */
1671 if (str[3]) {
1672 if (!strncmp(str + 3, ",vlan=", 6)) {
1673 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1674 if (*endp)
1675 vlan = 0;
1677 } else
1678 vlan = qemu_find_bt_vlan(0);
1679 if (vlan)
1680 return bt_new_hci(vlan);
1683 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1685 return 0;
1688 static int bt_hci_parse(const char *str)
1690 struct HCIInfo *hci;
1691 bdaddr_t bdaddr;
1693 if (nb_hcis >= MAX_NICS) {
1694 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1695 return -1;
1698 hci = hci_init(str);
1699 if (!hci)
1700 return -1;
1702 bdaddr.b[0] = 0x52;
1703 bdaddr.b[1] = 0x54;
1704 bdaddr.b[2] = 0x00;
1705 bdaddr.b[3] = 0x12;
1706 bdaddr.b[4] = 0x34;
1707 bdaddr.b[5] = 0x56 + nb_hcis;
1708 hci->bdaddr_set(hci, bdaddr.b);
1710 hci_table[nb_hcis++] = hci;
1712 return 0;
1715 static void bt_vhci_add(int vlan_id)
1717 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1719 if (!vlan->slave)
1720 fprintf(stderr, "qemu: warning: adding a VHCI to "
1721 "an empty scatternet %i\n", vlan_id);
1723 bt_vhci_init(bt_new_hci(vlan));
1726 static struct bt_device_s *bt_device_add(const char *opt)
1728 struct bt_scatternet_s *vlan;
1729 int vlan_id = 0;
1730 char *endp = strstr(opt, ",vlan=");
1731 int len = (endp ? endp - opt : strlen(opt)) + 1;
1732 char devname[10];
1734 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1736 if (endp) {
1737 vlan_id = strtol(endp + 6, &endp, 0);
1738 if (*endp) {
1739 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1740 return 0;
1744 vlan = qemu_find_bt_vlan(vlan_id);
1746 if (!vlan->slave)
1747 fprintf(stderr, "qemu: warning: adding a slave device to "
1748 "an empty scatternet %i\n", vlan_id);
1750 if (!strcmp(devname, "keyboard"))
1751 return bt_keyboard_init(vlan);
1753 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1754 return 0;
1757 static int bt_parse(const char *opt)
1759 const char *endp, *p;
1760 int vlan;
1762 if (strstart(opt, "hci", &endp)) {
1763 if (!*endp || *endp == ',') {
1764 if (*endp)
1765 if (!strstart(endp, ",vlan=", 0))
1766 opt = endp + 1;
1768 return bt_hci_parse(opt);
1770 } else if (strstart(opt, "vhci", &endp)) {
1771 if (!*endp || *endp == ',') {
1772 if (*endp) {
1773 if (strstart(endp, ",vlan=", &p)) {
1774 vlan = strtol(p, (char **) &endp, 0);
1775 if (*endp) {
1776 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1777 return 1;
1779 } else {
1780 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1781 return 1;
1783 } else
1784 vlan = 0;
1786 bt_vhci_add(vlan);
1787 return 0;
1789 } else if (strstart(opt, "device:", &endp))
1790 return !bt_device_add(endp);
1792 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1793 return 1;
1796 /***********************************************************/
1797 /* QEMU Block devices */
1799 #define HD_ALIAS "index=%d,media=disk"
1800 #define CDROM_ALIAS "index=2,media=cdrom"
1801 #define FD_ALIAS "index=%d,if=floppy"
1802 #define PFLASH_ALIAS "if=pflash"
1803 #define MTD_ALIAS "if=mtd"
1804 #define SD_ALIAS "index=0,if=sd"
1806 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1808 va_list ap;
1809 char optstr[1024];
1810 QemuOpts *opts;
1812 va_start(ap, fmt);
1813 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1814 va_end(ap);
1816 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1817 if (!opts) {
1818 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1819 __FUNCTION__, optstr);
1820 return NULL;
1822 if (file)
1823 qemu_opt_set(opts, "file", file);
1824 return opts;
1827 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1829 DriveInfo *dinfo;
1831 /* seek interface, bus and unit */
1833 QTAILQ_FOREACH(dinfo, &drives, next) {
1834 if (dinfo->type == type &&
1835 dinfo->bus == bus &&
1836 dinfo->unit == unit)
1837 return dinfo;
1840 return NULL;
1843 DriveInfo *drive_get_by_id(const char *id)
1845 DriveInfo *dinfo;
1847 QTAILQ_FOREACH(dinfo, &drives, next) {
1848 if (strcmp(id, dinfo->id))
1849 continue;
1850 return dinfo;
1852 return NULL;
1855 int drive_get_max_bus(BlockInterfaceType type)
1857 int max_bus;
1858 DriveInfo *dinfo;
1860 max_bus = -1;
1861 QTAILQ_FOREACH(dinfo, &drives, next) {
1862 if(dinfo->type == type &&
1863 dinfo->bus > max_bus)
1864 max_bus = dinfo->bus;
1866 return max_bus;
1869 const char *drive_get_serial(BlockDriverState *bdrv)
1871 DriveInfo *dinfo;
1873 QTAILQ_FOREACH(dinfo, &drives, next) {
1874 if (dinfo->bdrv == bdrv)
1875 return dinfo->serial;
1878 return "\0";
1881 BlockInterfaceErrorAction drive_get_on_error(
1882 BlockDriverState *bdrv, int is_read)
1884 DriveInfo *dinfo;
1886 QTAILQ_FOREACH(dinfo, &drives, next) {
1887 if (dinfo->bdrv == bdrv)
1888 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
1891 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
1894 static void bdrv_format_print(void *opaque, const char *name)
1896 fprintf(stderr, " %s", name);
1899 void drive_uninit(DriveInfo *dinfo)
1901 qemu_opts_del(dinfo->opts);
1902 bdrv_delete(dinfo->bdrv);
1903 QTAILQ_REMOVE(&drives, dinfo, next);
1904 qemu_free(dinfo);
1907 static int parse_block_error_action(const char *buf, int is_read)
1909 if (!strcmp(buf, "ignore")) {
1910 return BLOCK_ERR_IGNORE;
1911 } else if (!is_read && !strcmp(buf, "enospc")) {
1912 return BLOCK_ERR_STOP_ENOSPC;
1913 } else if (!strcmp(buf, "stop")) {
1914 return BLOCK_ERR_STOP_ANY;
1915 } else if (!strcmp(buf, "report")) {
1916 return BLOCK_ERR_REPORT;
1917 } else {
1918 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
1919 buf, is_read ? "read" : "write");
1920 return -1;
1924 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1925 int *fatal_error)
1927 const char *buf;
1928 const char *file = NULL;
1929 char devname[128];
1930 const char *serial;
1931 const char *mediastr = "";
1932 BlockInterfaceType type;
1933 enum { MEDIA_DISK, MEDIA_CDROM } media;
1934 int bus_id, unit_id;
1935 int cyls, heads, secs, translation;
1936 BlockDriver *drv = NULL;
1937 QEMUMachine *machine = opaque;
1938 int max_devs;
1939 int index;
1940 int cache;
1941 int aio = 0;
1942 int ro = 0;
1943 int bdrv_flags;
1944 int on_read_error, on_write_error;
1945 const char *devaddr;
1946 DriveInfo *dinfo;
1947 int is_extboot = 0;
1948 int snapshot = 0;
1950 *fatal_error = 1;
1952 translation = BIOS_ATA_TRANSLATION_AUTO;
1953 cache = 1;
1955 if (machine && machine->use_scsi) {
1956 type = IF_SCSI;
1957 max_devs = MAX_SCSI_DEVS;
1958 pstrcpy(devname, sizeof(devname), "scsi");
1959 } else {
1960 type = IF_IDE;
1961 max_devs = MAX_IDE_DEVS;
1962 pstrcpy(devname, sizeof(devname), "ide");
1964 media = MEDIA_DISK;
1966 /* extract parameters */
1967 bus_id = qemu_opt_get_number(opts, "bus", 0);
1968 unit_id = qemu_opt_get_number(opts, "unit", -1);
1969 index = qemu_opt_get_number(opts, "index", -1);
1971 cyls = qemu_opt_get_number(opts, "cyls", 0);
1972 heads = qemu_opt_get_number(opts, "heads", 0);
1973 secs = qemu_opt_get_number(opts, "secs", 0);
1975 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1976 ro = qemu_opt_get_bool(opts, "readonly", 0);
1978 file = qemu_opt_get(opts, "file");
1979 serial = qemu_opt_get(opts, "serial");
1981 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1982 pstrcpy(devname, sizeof(devname), buf);
1983 if (!strcmp(buf, "ide")) {
1984 type = IF_IDE;
1985 max_devs = MAX_IDE_DEVS;
1986 } else if (!strcmp(buf, "scsi")) {
1987 type = IF_SCSI;
1988 max_devs = MAX_SCSI_DEVS;
1989 } else if (!strcmp(buf, "floppy")) {
1990 type = IF_FLOPPY;
1991 max_devs = 0;
1992 } else if (!strcmp(buf, "pflash")) {
1993 type = IF_PFLASH;
1994 max_devs = 0;
1995 } else if (!strcmp(buf, "mtd")) {
1996 type = IF_MTD;
1997 max_devs = 0;
1998 } else if (!strcmp(buf, "sd")) {
1999 type = IF_SD;
2000 max_devs = 0;
2001 } else if (!strcmp(buf, "virtio")) {
2002 type = IF_VIRTIO;
2003 max_devs = 0;
2004 } else if (!strcmp(buf, "xen")) {
2005 type = IF_XEN;
2006 max_devs = 0;
2007 } else if (!strcmp(buf, "none")) {
2008 type = IF_NONE;
2009 max_devs = 0;
2010 } else {
2011 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
2012 return NULL;
2016 if (cyls || heads || secs) {
2017 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
2018 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2019 return NULL;
2021 if (heads < 1 || (type == IF_IDE && heads > 16)) {
2022 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2023 return NULL;
2025 if (secs < 1 || (type == IF_IDE && secs > 63)) {
2026 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2027 return NULL;
2031 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2032 if (!cyls) {
2033 fprintf(stderr,
2034 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2035 buf);
2036 return NULL;
2038 if (!strcmp(buf, "none"))
2039 translation = BIOS_ATA_TRANSLATION_NONE;
2040 else if (!strcmp(buf, "lba"))
2041 translation = BIOS_ATA_TRANSLATION_LBA;
2042 else if (!strcmp(buf, "auto"))
2043 translation = BIOS_ATA_TRANSLATION_AUTO;
2044 else {
2045 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2046 return NULL;
2050 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2051 if (!strcmp(buf, "disk")) {
2052 media = MEDIA_DISK;
2053 } else if (!strcmp(buf, "cdrom")) {
2054 if (cyls || secs || heads) {
2055 fprintf(stderr,
2056 "qemu: '%s' invalid physical CHS format\n", buf);
2057 return NULL;
2059 media = MEDIA_CDROM;
2060 } else {
2061 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2062 return NULL;
2066 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2067 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2068 cache = 0;
2069 else if (!strcmp(buf, "writethrough"))
2070 cache = 1;
2071 else if (!strcmp(buf, "writeback"))
2072 cache = 2;
2073 else {
2074 fprintf(stderr, "qemu: invalid cache option\n");
2075 return NULL;
2079 #ifdef CONFIG_LINUX_AIO
2080 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2081 if (!strcmp(buf, "threads"))
2082 aio = 0;
2083 else if (!strcmp(buf, "native"))
2084 aio = 1;
2085 else {
2086 fprintf(stderr, "qemu: invalid aio option\n");
2087 return NULL;
2090 #endif
2092 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2093 if (strcmp(buf, "?") == 0) {
2094 fprintf(stderr, "qemu: Supported formats:");
2095 bdrv_iterate_format(bdrv_format_print, NULL);
2096 fprintf(stderr, "\n");
2097 return NULL;
2099 drv = bdrv_find_whitelisted_format(buf);
2100 if (!drv) {
2101 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2102 return NULL;
2106 is_extboot = qemu_opt_get_bool(opts, "boot", 0);
2107 if (is_extboot && extboot_drive) {
2108 fprintf(stderr, "qemu: two bootable drives specified\n");
2109 return NULL;
2112 on_write_error = BLOCK_ERR_STOP_ENOSPC;
2113 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2114 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2115 fprintf(stderr, "werror is no supported by this format\n");
2116 return NULL;
2119 on_write_error = parse_block_error_action(buf, 0);
2120 if (on_write_error < 0) {
2121 return NULL;
2125 on_read_error = BLOCK_ERR_REPORT;
2126 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2127 if (type != IF_IDE && type != IF_VIRTIO) {
2128 fprintf(stderr, "rerror is no supported by this format\n");
2129 return NULL;
2132 on_read_error = parse_block_error_action(buf, 1);
2133 if (on_read_error < 0) {
2134 return NULL;
2138 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2139 if (type != IF_VIRTIO) {
2140 fprintf(stderr, "addr is not supported\n");
2141 return NULL;
2145 /* compute bus and unit according index */
2147 if (index != -1) {
2148 if (bus_id != 0 || unit_id != -1) {
2149 fprintf(stderr,
2150 "qemu: index cannot be used with bus and unit\n");
2151 return NULL;
2153 if (max_devs == 0)
2155 unit_id = index;
2156 bus_id = 0;
2157 } else {
2158 unit_id = index % max_devs;
2159 bus_id = index / max_devs;
2163 /* if user doesn't specify a unit_id,
2164 * try to find the first free
2167 if (unit_id == -1) {
2168 unit_id = 0;
2169 while (drive_get(type, bus_id, unit_id) != NULL) {
2170 unit_id++;
2171 if (max_devs && unit_id >= max_devs) {
2172 unit_id -= max_devs;
2173 bus_id++;
2178 /* check unit id */
2180 if (max_devs && unit_id >= max_devs) {
2181 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2182 unit_id, max_devs - 1);
2183 return NULL;
2187 * ignore multiple definitions
2190 if (drive_get(type, bus_id, unit_id) != NULL) {
2191 *fatal_error = 0;
2192 return NULL;
2195 /* init */
2197 dinfo = qemu_mallocz(sizeof(*dinfo));
2198 if ((buf = qemu_opts_id(opts)) != NULL) {
2199 dinfo->id = qemu_strdup(buf);
2200 } else {
2201 /* no id supplied -> create one */
2202 dinfo->id = qemu_mallocz(32);
2203 if (type == IF_IDE || type == IF_SCSI)
2204 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2205 if (max_devs)
2206 snprintf(dinfo->id, 32, "%s%i%s%i",
2207 devname, bus_id, mediastr, unit_id);
2208 else
2209 snprintf(dinfo->id, 32, "%s%s%i",
2210 devname, mediastr, unit_id);
2212 dinfo->bdrv = bdrv_new(dinfo->id);
2213 dinfo->devaddr = devaddr;
2214 dinfo->type = type;
2215 dinfo->bus = bus_id;
2216 dinfo->unit = unit_id;
2217 dinfo->on_read_error = on_read_error;
2218 dinfo->on_write_error = on_write_error;
2219 dinfo->opts = opts;
2220 if (serial)
2221 strncpy(dinfo->serial, serial, sizeof(serial));
2222 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2223 if (is_extboot) {
2224 extboot_drive = dinfo;
2227 switch(type) {
2228 case IF_IDE:
2229 case IF_SCSI:
2230 case IF_XEN:
2231 case IF_NONE:
2232 switch(media) {
2233 case MEDIA_DISK:
2234 if (cyls != 0) {
2235 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2236 bdrv_set_translation_hint(dinfo->bdrv, translation);
2238 break;
2239 case MEDIA_CDROM:
2240 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2241 break;
2243 break;
2244 case IF_SD:
2245 /* FIXME: This isn't really a floppy, but it's a reasonable
2246 approximation. */
2247 case IF_FLOPPY:
2248 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2249 break;
2250 case IF_PFLASH:
2251 case IF_MTD:
2252 break;
2253 case IF_VIRTIO:
2254 /* add virtio block device */
2255 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2256 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2257 qemu_opt_set(opts, "drive", dinfo->id);
2258 if (devaddr)
2259 qemu_opt_set(opts, "addr", devaddr);
2260 break;
2261 case IF_COUNT:
2262 abort();
2264 if (!file) {
2265 *fatal_error = 0;
2266 return NULL;
2268 bdrv_flags = 0;
2269 if (snapshot) {
2270 bdrv_flags |= BDRV_O_SNAPSHOT;
2271 cache = 2; /* always use write-back with snapshot */
2273 if (cache == 0) /* no caching */
2274 bdrv_flags |= BDRV_O_NOCACHE;
2275 else if (cache == 2) /* write-back */
2276 bdrv_flags |= BDRV_O_CACHE_WB;
2278 if (aio == 1) {
2279 bdrv_flags |= BDRV_O_NATIVE_AIO;
2280 } else {
2281 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2284 if (ro == 1) {
2285 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
2286 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
2287 return NULL;
2291 * cdrom is read-only. Set it now, after above interface checking
2292 * since readonly attribute not explicitly required, so no error.
2294 if (media == MEDIA_CDROM) {
2295 ro = 1;
2297 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
2299 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2300 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2301 file, strerror(errno));
2302 return NULL;
2305 if (bdrv_key_required(dinfo->bdrv))
2306 autostart = 0;
2307 *fatal_error = 0;
2308 return dinfo;
2311 static int drive_init_func(QemuOpts *opts, void *opaque)
2313 QEMUMachine *machine = opaque;
2314 int fatal_error = 0;
2316 if (drive_init(opts, machine, &fatal_error) == NULL) {
2317 if (fatal_error)
2318 return 1;
2320 return 0;
2323 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2325 if (NULL == qemu_opt_get(opts, "snapshot")) {
2326 qemu_opt_set(opts, "snapshot", "on");
2328 return 0;
2331 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2333 boot_set_handler = func;
2334 boot_set_opaque = opaque;
2337 int qemu_boot_set(const char *boot_devices)
2339 if (!boot_set_handler) {
2340 return -EINVAL;
2342 return boot_set_handler(boot_set_opaque, boot_devices);
2345 static int parse_bootdevices(char *devices)
2347 /* We just do some generic consistency checks */
2348 const char *p;
2349 int bitmap = 0;
2351 for (p = devices; *p != '\0'; p++) {
2352 /* Allowed boot devices are:
2353 * a-b: floppy disk drives
2354 * c-f: IDE disk drives
2355 * g-m: machine implementation dependant drives
2356 * n-p: network devices
2357 * It's up to each machine implementation to check if the given boot
2358 * devices match the actual hardware implementation and firmware
2359 * features.
2361 if (*p < 'a' || *p > 'p') {
2362 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2363 exit(1);
2365 if (bitmap & (1 << (*p - 'a'))) {
2366 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2367 exit(1);
2369 bitmap |= 1 << (*p - 'a');
2371 return bitmap;
2374 static void restore_boot_devices(void *opaque)
2376 char *standard_boot_devices = opaque;
2378 qemu_boot_set(standard_boot_devices);
2380 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2381 qemu_free(standard_boot_devices);
2384 static void numa_add(const char *optarg)
2386 char option[128];
2387 char *endptr;
2388 unsigned long long value, endvalue;
2389 int nodenr;
2391 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2392 if (!strcmp(option, "node")) {
2393 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2394 nodenr = nb_numa_nodes;
2395 } else {
2396 nodenr = strtoull(option, NULL, 10);
2399 if (get_param_value(option, 128, "mem", optarg) == 0) {
2400 node_mem[nodenr] = 0;
2401 } else {
2402 value = strtoull(option, &endptr, 0);
2403 switch (*endptr) {
2404 case 0: case 'M': case 'm':
2405 value <<= 20;
2406 break;
2407 case 'G': case 'g':
2408 value <<= 30;
2409 break;
2411 node_mem[nodenr] = value;
2413 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2414 node_cpumask[nodenr] = 0;
2415 } else {
2416 value = strtoull(option, &endptr, 10);
2417 if (value >= 64) {
2418 value = 63;
2419 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2420 } else {
2421 if (*endptr == '-') {
2422 endvalue = strtoull(endptr+1, &endptr, 10);
2423 if (endvalue >= 63) {
2424 endvalue = 62;
2425 fprintf(stderr,
2426 "only 63 CPUs in NUMA mode supported.\n");
2428 value = (2ULL << endvalue) - (1ULL << value);
2429 } else {
2430 value = 1ULL << value;
2433 node_cpumask[nodenr] = value;
2435 nb_numa_nodes++;
2437 return;
2440 static void smp_parse(const char *optarg)
2442 int smp, sockets = 0, threads = 0, cores = 0;
2443 char *endptr;
2444 char option[128];
2446 smp = strtoul(optarg, &endptr, 10);
2447 if (endptr != optarg) {
2448 if (*endptr == ',') {
2449 endptr++;
2452 if (get_param_value(option, 128, "sockets", endptr) != 0)
2453 sockets = strtoull(option, NULL, 10);
2454 if (get_param_value(option, 128, "cores", endptr) != 0)
2455 cores = strtoull(option, NULL, 10);
2456 if (get_param_value(option, 128, "threads", endptr) != 0)
2457 threads = strtoull(option, NULL, 10);
2458 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2459 max_cpus = strtoull(option, NULL, 10);
2461 /* compute missing values, prefer sockets over cores over threads */
2462 if (smp == 0 || sockets == 0) {
2463 sockets = sockets > 0 ? sockets : 1;
2464 cores = cores > 0 ? cores : 1;
2465 threads = threads > 0 ? threads : 1;
2466 if (smp == 0) {
2467 smp = cores * threads * sockets;
2469 } else {
2470 if (cores == 0) {
2471 threads = threads > 0 ? threads : 1;
2472 cores = smp / (sockets * threads);
2473 } else {
2474 if (sockets) {
2475 threads = smp / (cores * sockets);
2479 smp_cpus = smp;
2480 smp_cores = cores > 0 ? cores : 1;
2481 smp_threads = threads > 0 ? threads : 1;
2482 if (max_cpus == 0)
2483 max_cpus = smp_cpus;
2486 /***********************************************************/
2487 /* USB devices */
2489 static int usb_device_add(const char *devname, int is_hotplug)
2491 const char *p;
2492 USBDevice *dev = NULL;
2494 if (!usb_enabled)
2495 return -1;
2497 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2498 dev = usbdevice_create(devname);
2499 if (dev)
2500 goto done;
2502 /* the other ones */
2503 if (strstart(devname, "host:", &p)) {
2504 dev = usb_host_device_open(p);
2505 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2506 dev = usb_bt_init(devname[2] ? hci_init(p) :
2507 bt_new_hci(qemu_find_bt_vlan(0)));
2508 } else {
2509 return -1;
2511 if (!dev)
2512 return -1;
2514 done:
2515 return 0;
2518 static int usb_device_del(const char *devname)
2520 int bus_num, addr;
2521 const char *p;
2523 if (strstart(devname, "host:", &p))
2524 return usb_host_device_close(p);
2526 if (!usb_enabled)
2527 return -1;
2529 p = strchr(devname, '.');
2530 if (!p)
2531 return -1;
2532 bus_num = strtoul(devname, NULL, 0);
2533 addr = strtoul(p + 1, NULL, 0);
2535 return usb_device_delete_addr(bus_num, addr);
2538 static int usb_parse(const char *cmdline)
2540 int r;
2541 r = usb_device_add(cmdline, 0);
2542 if (r < 0) {
2543 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
2545 return r;
2548 void do_usb_add(Monitor *mon, const QDict *qdict)
2550 const char *devname = qdict_get_str(qdict, "devname");
2551 if (usb_device_add(devname, 1) < 0) {
2552 qemu_error("could not add USB device '%s'\n", devname);
2556 void do_usb_del(Monitor *mon, const QDict *qdict)
2558 const char *devname = qdict_get_str(qdict, "devname");
2559 if (usb_device_del(devname) < 0) {
2560 qemu_error("could not delete USB device '%s'\n", devname);
2564 /***********************************************************/
2565 /* PCMCIA/Cardbus */
2567 static struct pcmcia_socket_entry_s {
2568 PCMCIASocket *socket;
2569 struct pcmcia_socket_entry_s *next;
2570 } *pcmcia_sockets = 0;
2572 void pcmcia_socket_register(PCMCIASocket *socket)
2574 struct pcmcia_socket_entry_s *entry;
2576 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2577 entry->socket = socket;
2578 entry->next = pcmcia_sockets;
2579 pcmcia_sockets = entry;
2582 void pcmcia_socket_unregister(PCMCIASocket *socket)
2584 struct pcmcia_socket_entry_s *entry, **ptr;
2586 ptr = &pcmcia_sockets;
2587 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2588 if (entry->socket == socket) {
2589 *ptr = entry->next;
2590 qemu_free(entry);
2594 void pcmcia_info(Monitor *mon)
2596 struct pcmcia_socket_entry_s *iter;
2598 if (!pcmcia_sockets)
2599 monitor_printf(mon, "No PCMCIA sockets\n");
2601 for (iter = pcmcia_sockets; iter; iter = iter->next)
2602 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2603 iter->socket->attached ? iter->socket->card_string :
2604 "Empty");
2607 /***********************************************************/
2608 /* I/O handling */
2610 typedef struct IOHandlerRecord {
2611 int fd;
2612 IOCanRWHandler *fd_read_poll;
2613 IOHandler *fd_read;
2614 IOHandler *fd_write;
2615 int deleted;
2616 void *opaque;
2617 /* temporary data */
2618 struct pollfd *ufd;
2619 struct IOHandlerRecord *next;
2620 } IOHandlerRecord;
2622 static IOHandlerRecord *first_io_handler;
2624 /* XXX: fd_read_poll should be suppressed, but an API change is
2625 necessary in the character devices to suppress fd_can_read(). */
2626 int qemu_set_fd_handler2(int fd,
2627 IOCanRWHandler *fd_read_poll,
2628 IOHandler *fd_read,
2629 IOHandler *fd_write,
2630 void *opaque)
2632 IOHandlerRecord **pioh, *ioh;
2634 if (!fd_read && !fd_write) {
2635 pioh = &first_io_handler;
2636 for(;;) {
2637 ioh = *pioh;
2638 if (ioh == NULL)
2639 break;
2640 if (ioh->fd == fd) {
2641 ioh->deleted = 1;
2642 break;
2644 pioh = &ioh->next;
2646 } else {
2647 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2648 if (ioh->fd == fd)
2649 goto found;
2651 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2652 ioh->next = first_io_handler;
2653 first_io_handler = ioh;
2654 found:
2655 ioh->fd = fd;
2656 ioh->fd_read_poll = fd_read_poll;
2657 ioh->fd_read = fd_read;
2658 ioh->fd_write = fd_write;
2659 ioh->opaque = opaque;
2660 ioh->deleted = 0;
2662 qemu_notify_event();
2663 return 0;
2666 int qemu_set_fd_handler(int fd,
2667 IOHandler *fd_read,
2668 IOHandler *fd_write,
2669 void *opaque)
2671 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2674 #ifdef _WIN32
2675 /***********************************************************/
2676 /* Polling handling */
2678 typedef struct PollingEntry {
2679 PollingFunc *func;
2680 void *opaque;
2681 struct PollingEntry *next;
2682 } PollingEntry;
2684 static PollingEntry *first_polling_entry;
2686 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2688 PollingEntry **ppe, *pe;
2689 pe = qemu_mallocz(sizeof(PollingEntry));
2690 pe->func = func;
2691 pe->opaque = opaque;
2692 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2693 *ppe = pe;
2694 return 0;
2697 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2699 PollingEntry **ppe, *pe;
2700 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2701 pe = *ppe;
2702 if (pe->func == func && pe->opaque == opaque) {
2703 *ppe = pe->next;
2704 qemu_free(pe);
2705 break;
2710 /***********************************************************/
2711 /* Wait objects support */
2712 typedef struct WaitObjects {
2713 int num;
2714 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2715 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2716 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2717 } WaitObjects;
2719 static WaitObjects wait_objects = {0};
2721 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2723 WaitObjects *w = &wait_objects;
2725 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2726 return -1;
2727 w->events[w->num] = handle;
2728 w->func[w->num] = func;
2729 w->opaque[w->num] = opaque;
2730 w->num++;
2731 return 0;
2734 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2736 int i, found;
2737 WaitObjects *w = &wait_objects;
2739 found = 0;
2740 for (i = 0; i < w->num; i++) {
2741 if (w->events[i] == handle)
2742 found = 1;
2743 if (found) {
2744 w->events[i] = w->events[i + 1];
2745 w->func[i] = w->func[i + 1];
2746 w->opaque[i] = w->opaque[i + 1];
2749 if (found)
2750 w->num--;
2752 #endif
2754 /***********************************************************/
2755 /* ram save/restore */
2757 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2758 #define RAM_SAVE_FLAG_COMPRESS 0x02
2759 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2760 #define RAM_SAVE_FLAG_PAGE 0x08
2761 #define RAM_SAVE_FLAG_EOS 0x10
2763 static int is_dup_page(uint8_t *page, uint8_t ch)
2765 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2766 uint32_t *array = (uint32_t *)page;
2767 int i;
2769 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2770 if (array[i] != val)
2771 return 0;
2774 return 1;
2777 static int ram_save_block(QEMUFile *f)
2779 static ram_addr_t current_addr = 0;
2780 ram_addr_t saved_addr = current_addr;
2781 ram_addr_t addr = 0;
2782 int found = 0;
2784 while (addr < last_ram_offset) {
2785 if (kvm_enabled() && current_addr == 0) {
2786 int r;
2787 r = kvm_update_dirty_pages_log();
2788 if (r) {
2789 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
2790 qemu_file_set_error(f);
2791 return 0;
2794 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2795 uint8_t *p;
2797 cpu_physical_memory_reset_dirty(current_addr,
2798 current_addr + TARGET_PAGE_SIZE,
2799 MIGRATION_DIRTY_FLAG);
2801 p = qemu_get_ram_ptr(current_addr);
2803 if (is_dup_page(p, *p)) {
2804 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2805 qemu_put_byte(f, *p);
2806 } else {
2807 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2808 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2811 found = 1;
2812 break;
2814 addr += TARGET_PAGE_SIZE;
2815 current_addr = (saved_addr + addr) % last_ram_offset;
2818 return found;
2821 static uint64_t bytes_transferred;
2823 static ram_addr_t ram_save_remaining(void)
2825 ram_addr_t addr;
2826 ram_addr_t count = 0;
2828 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2829 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2830 count++;
2833 return count;
2836 uint64_t ram_bytes_remaining(void)
2838 return ram_save_remaining() * TARGET_PAGE_SIZE;
2841 uint64_t ram_bytes_transferred(void)
2843 return bytes_transferred;
2846 uint64_t ram_bytes_total(void)
2848 return last_ram_offset;
2851 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
2853 ram_addr_t addr;
2854 uint64_t bytes_transferred_last;
2855 double bwidth = 0;
2856 uint64_t expected_time = 0;
2858 if (stage < 0) {
2859 cpu_physical_memory_set_dirty_tracking(0);
2860 return 0;
2863 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2864 qemu_file_set_error(f);
2865 return 0;
2868 if (stage == 1) {
2869 bytes_transferred = 0;
2871 /* Make sure all dirty bits are set */
2872 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2873 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2874 cpu_physical_memory_set_dirty(addr);
2877 /* Enable dirty memory tracking */
2878 cpu_physical_memory_set_dirty_tracking(1);
2880 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2883 bytes_transferred_last = bytes_transferred;
2884 bwidth = qemu_get_clock_ns(rt_clock);
2886 while (!qemu_file_rate_limit(f)) {
2887 int ret;
2889 ret = ram_save_block(f);
2890 bytes_transferred += ret * TARGET_PAGE_SIZE;
2891 if (ret == 0) /* no more blocks */
2892 break;
2895 bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
2896 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2898 /* if we haven't transferred anything this round, force expected_time to a
2899 * a very high value, but without crashing */
2900 if (bwidth == 0)
2901 bwidth = 0.000001;
2903 /* try transferring iterative blocks of memory */
2904 if (stage == 3) {
2905 /* flush all remaining blocks regardless of rate limiting */
2906 while (ram_save_block(f) != 0) {
2907 bytes_transferred += TARGET_PAGE_SIZE;
2909 cpu_physical_memory_set_dirty_tracking(0);
2912 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2914 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2916 return (stage == 2) && (expected_time <= migrate_max_downtime());
2919 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2921 ram_addr_t addr;
2922 int flags;
2924 if (version_id != 3)
2925 return -EINVAL;
2927 do {
2928 addr = qemu_get_be64(f);
2930 flags = addr & ~TARGET_PAGE_MASK;
2931 addr &= TARGET_PAGE_MASK;
2933 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2934 if (addr != last_ram_offset)
2935 return -EINVAL;
2938 if (flags & RAM_SAVE_FLAG_COMPRESS) {
2939 uint8_t ch = qemu_get_byte(f);
2940 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
2941 #ifndef _WIN32
2942 if (ch == 0 &&
2943 (!kvm_enabled() || kvm_has_sync_mmu())) {
2944 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
2946 #endif
2947 } else if (flags & RAM_SAVE_FLAG_PAGE) {
2948 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
2950 if (qemu_file_has_error(f)) {
2951 return -EIO;
2953 } while (!(flags & RAM_SAVE_FLAG_EOS));
2955 return 0;
2958 void qemu_service_io(void)
2960 qemu_notify_event();
2963 /***********************************************************/
2964 /* machine registration */
2966 static QEMUMachine *first_machine = NULL;
2967 QEMUMachine *current_machine = NULL;
2969 int qemu_register_machine(QEMUMachine *m)
2971 QEMUMachine **pm;
2972 pm = &first_machine;
2973 while (*pm != NULL)
2974 pm = &(*pm)->next;
2975 m->next = NULL;
2976 *pm = m;
2977 return 0;
2980 static QEMUMachine *find_machine(const char *name)
2982 QEMUMachine *m;
2984 for(m = first_machine; m != NULL; m = m->next) {
2985 if (!strcmp(m->name, name))
2986 return m;
2987 if (m->alias && !strcmp(m->alias, name))
2988 return m;
2990 return NULL;
2993 static QEMUMachine *find_default_machine(void)
2995 QEMUMachine *m;
2997 for(m = first_machine; m != NULL; m = m->next) {
2998 if (m->is_default) {
2999 return m;
3002 return NULL;
3005 /***********************************************************/
3006 /* main execution loop */
3008 static void gui_update(void *opaque)
3010 uint64_t interval = GUI_REFRESH_INTERVAL;
3011 DisplayState *ds = opaque;
3012 DisplayChangeListener *dcl = ds->listeners;
3014 qemu_flush_coalesced_mmio_buffer();
3015 dpy_refresh(ds);
3017 while (dcl != NULL) {
3018 if (dcl->gui_timer_interval &&
3019 dcl->gui_timer_interval < interval)
3020 interval = dcl->gui_timer_interval;
3021 dcl = dcl->next;
3023 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3026 static void nographic_update(void *opaque)
3028 uint64_t interval = GUI_REFRESH_INTERVAL;
3030 qemu_flush_coalesced_mmio_buffer();
3031 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3034 struct vm_change_state_entry {
3035 VMChangeStateHandler *cb;
3036 void *opaque;
3037 QLIST_ENTRY (vm_change_state_entry) entries;
3040 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3042 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3043 void *opaque)
3045 VMChangeStateEntry *e;
3047 e = qemu_mallocz(sizeof (*e));
3049 e->cb = cb;
3050 e->opaque = opaque;
3051 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3052 return e;
3055 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3057 QLIST_REMOVE (e, entries);
3058 qemu_free (e);
3061 static void vm_state_notify(int running, int reason)
3063 VMChangeStateEntry *e;
3065 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3066 e->cb(e->opaque, running, reason);
3070 static void resume_all_vcpus(void);
3071 static void pause_all_vcpus(void);
3073 void vm_start(void)
3075 if (!vm_running) {
3076 cpu_enable_ticks();
3077 vm_running = 1;
3078 vm_state_notify(1, 0);
3079 qemu_rearm_alarm_timer(alarm_timer);
3080 resume_all_vcpus();
3084 /* reset/shutdown handler */
3086 typedef struct QEMUResetEntry {
3087 QTAILQ_ENTRY(QEMUResetEntry) entry;
3088 QEMUResetHandler *func;
3089 void *opaque;
3090 } QEMUResetEntry;
3092 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3093 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3094 static int reset_requested;
3095 static int shutdown_requested;
3096 static int powerdown_requested;
3097 static int debug_requested;
3098 static int vmstop_requested;
3100 int qemu_no_shutdown(void)
3102 int r = no_shutdown;
3103 no_shutdown = 0;
3104 return r;
3107 int qemu_shutdown_requested(void)
3109 int r = shutdown_requested;
3110 shutdown_requested = 0;
3111 return r;
3114 int qemu_reset_requested(void)
3116 int r = reset_requested;
3117 reset_requested = 0;
3118 return r;
3121 int qemu_powerdown_requested(void)
3123 int r = powerdown_requested;
3124 powerdown_requested = 0;
3125 return r;
3128 static int qemu_debug_requested(void)
3130 int r = debug_requested;
3131 debug_requested = 0;
3132 return r;
3135 static int qemu_vmstop_requested(void)
3137 int r = vmstop_requested;
3138 vmstop_requested = 0;
3139 return r;
3142 static void do_vm_stop(int reason)
3144 if (vm_running) {
3145 cpu_disable_ticks();
3146 vm_running = 0;
3147 pause_all_vcpus();
3148 vm_state_notify(0, reason);
3152 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3154 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3156 re->func = func;
3157 re->opaque = opaque;
3158 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3161 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3163 QEMUResetEntry *re;
3165 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3166 if (re->func == func && re->opaque == opaque) {
3167 QTAILQ_REMOVE(&reset_handlers, re, entry);
3168 qemu_free(re);
3169 return;
3174 void qemu_system_reset(void)
3176 QEMUResetEntry *re, *nre;
3178 /* reset all devices */
3179 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3180 re->func(re->opaque);
3184 void qemu_system_reset_request(void)
3186 if (no_reboot) {
3187 shutdown_requested = 1;
3188 } else {
3189 reset_requested = 1;
3191 if (cpu_single_env) {
3192 cpu_single_env->stopped = 1;
3194 qemu_notify_event();
3197 void qemu_system_shutdown_request(void)
3199 shutdown_requested = 1;
3200 qemu_notify_event();
3203 void qemu_system_powerdown_request(void)
3205 powerdown_requested = 1;
3206 qemu_notify_event();
3209 #ifdef CONFIG_IOTHREAD
3210 static void qemu_system_vmstop_request(int reason)
3212 vmstop_requested = reason;
3213 qemu_notify_event();
3215 #endif
3217 #ifndef _WIN32
3218 static int io_thread_fd = -1;
3220 static void qemu_event_increment(void)
3222 /* Write 8 bytes to be compatible with eventfd. */
3223 static uint64_t val = 1;
3224 ssize_t ret;
3226 if (io_thread_fd == -1)
3227 return;
3229 do {
3230 ret = write(io_thread_fd, &val, sizeof(val));
3231 } while (ret < 0 && errno == EINTR);
3233 /* EAGAIN is fine, a read must be pending. */
3234 if (ret < 0 && errno != EAGAIN) {
3235 fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
3236 strerror(errno));
3237 exit (1);
3241 static void qemu_event_read(void *opaque)
3243 int fd = (unsigned long)opaque;
3244 ssize_t len;
3245 char buffer[512];
3247 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
3248 do {
3249 len = read(fd, buffer, sizeof(buffer));
3250 } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
3253 static int qemu_event_init(void)
3255 int err;
3256 int fds[2];
3258 err = qemu_eventfd(fds);
3259 if (err == -1)
3260 return -errno;
3262 err = fcntl_setfl(fds[0], O_NONBLOCK);
3263 if (err < 0)
3264 goto fail;
3266 err = fcntl_setfl(fds[1], O_NONBLOCK);
3267 if (err < 0)
3268 goto fail;
3270 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3271 (void *)(unsigned long)fds[0]);
3273 io_thread_fd = fds[1];
3274 return 0;
3276 fail:
3277 close(fds[0]);
3278 close(fds[1]);
3279 return err;
3281 #else
3282 HANDLE qemu_event_handle;
3284 static void dummy_event_handler(void *opaque)
3288 static int qemu_event_init(void)
3290 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3291 if (!qemu_event_handle) {
3292 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3293 return -1;
3295 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3296 return 0;
3299 static void qemu_event_increment(void)
3301 if (!SetEvent(qemu_event_handle)) {
3302 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3303 GetLastError());
3304 exit (1);
3307 #endif
3309 static int cpu_can_run(CPUState *env)
3311 if (env->stop)
3312 return 0;
3313 if (env->stopped)
3314 return 0;
3315 if (!vm_running)
3316 return 0;
3317 return 1;
3320 #ifndef CONFIG_IOTHREAD
3321 static int qemu_init_main_loop(void)
3323 return qemu_event_init();
3326 void qemu_init_vcpu(void *_env)
3328 CPUState *env = _env;
3330 env->nr_cores = smp_cores;
3331 env->nr_threads = smp_threads;
3332 if (kvm_enabled())
3333 kvm_init_vcpu(env);
3334 return;
3337 int qemu_cpu_self(void *env)
3339 return 1;
3342 static void resume_all_vcpus(void)
3346 static void pause_all_vcpus(void)
3350 void qemu_cpu_kick(void *env)
3352 return;
3355 void qemu_notify_event(void)
3357 CPUState *env = cpu_single_env;
3359 if (kvm_enabled()) {
3360 qemu_kvm_notify_work();
3361 return;
3363 if (env) {
3364 cpu_exit(env);
3368 #if defined(KVM_UPSTREAM) || !defined(CONFIG_KVM)
3369 void qemu_mutex_lock_iothread(void) {}
3370 void qemu_mutex_unlock_iothread(void) {}
3371 #endif
3373 void vm_stop(int reason)
3375 do_vm_stop(reason);
3378 #else /* CONFIG_IOTHREAD */
3380 #include "qemu-thread.h"
3382 QemuMutex qemu_global_mutex;
3383 static QemuMutex qemu_fair_mutex;
3385 static QemuThread io_thread;
3387 static QemuThread *tcg_cpu_thread;
3388 static QemuCond *tcg_halt_cond;
3390 static int qemu_system_ready;
3391 /* cpu creation */
3392 static QemuCond qemu_cpu_cond;
3393 /* system init */
3394 static QemuCond qemu_system_cond;
3395 static QemuCond qemu_pause_cond;
3397 static void tcg_block_io_signals(void);
3398 static void kvm_block_io_signals(CPUState *env);
3399 static void unblock_io_signals(void);
3400 static int tcg_has_work(void);
3401 static int cpu_has_work(CPUState *env);
3403 static int qemu_init_main_loop(void)
3405 int ret;
3407 ret = qemu_event_init();
3408 if (ret)
3409 return ret;
3411 qemu_cond_init(&qemu_pause_cond);
3412 qemu_mutex_init(&qemu_fair_mutex);
3413 qemu_mutex_init(&qemu_global_mutex);
3414 qemu_mutex_lock(&qemu_global_mutex);
3416 unblock_io_signals();
3417 qemu_thread_self(&io_thread);
3419 return 0;
3422 static void qemu_wait_io_event_common(CPUState *env)
3424 if (env->stop) {
3425 env->stop = 0;
3426 env->stopped = 1;
3427 qemu_cond_signal(&qemu_pause_cond);
3431 static void qemu_wait_io_event(CPUState *env)
3433 while (!tcg_has_work())
3434 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3436 qemu_mutex_unlock(&qemu_global_mutex);
3439 * Users of qemu_global_mutex can be starved, having no chance
3440 * to acquire it since this path will get to it first.
3441 * So use another lock to provide fairness.
3443 qemu_mutex_lock(&qemu_fair_mutex);
3444 qemu_mutex_unlock(&qemu_fair_mutex);
3446 qemu_mutex_lock(&qemu_global_mutex);
3447 qemu_wait_io_event_common(env);
3450 static void qemu_kvm_eat_signal(CPUState *env, int timeout)
3452 struct timespec ts;
3453 int r, e;
3454 siginfo_t siginfo;
3455 sigset_t waitset;
3457 ts.tv_sec = timeout / 1000;
3458 ts.tv_nsec = (timeout % 1000) * 1000000;
3460 sigemptyset(&waitset);
3461 sigaddset(&waitset, SIG_IPI);
3463 qemu_mutex_unlock(&qemu_global_mutex);
3464 r = sigtimedwait(&waitset, &siginfo, &ts);
3465 e = errno;
3466 qemu_mutex_lock(&qemu_global_mutex);
3468 if (r == -1 && !(e == EAGAIN || e == EINTR)) {
3469 fprintf(stderr, "sigtimedwait: %s\n", strerror(e));
3470 exit(1);
3474 static void qemu_kvm_wait_io_event(CPUState *env)
3476 while (!cpu_has_work(env))
3477 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3479 qemu_kvm_eat_signal(env, 0);
3480 qemu_wait_io_event_common(env);
3483 static int qemu_cpu_exec(CPUState *env);
3485 static void *kvm_cpu_thread_fn(void *arg)
3487 CPUState *env = arg;
3489 qemu_thread_self(env->thread);
3490 if (kvm_enabled())
3491 kvm_init_vcpu(env);
3493 kvm_block_io_signals(env);
3495 /* signal CPU creation */
3496 qemu_mutex_lock(&qemu_global_mutex);
3497 env->created = 1;
3498 qemu_cond_signal(&qemu_cpu_cond);
3500 /* and wait for machine initialization */
3501 while (!qemu_system_ready)
3502 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3504 while (1) {
3505 if (cpu_can_run(env))
3506 qemu_cpu_exec(env);
3507 qemu_kvm_wait_io_event(env);
3510 return NULL;
3513 static void tcg_cpu_exec(void);
3515 static void *tcg_cpu_thread_fn(void *arg)
3517 CPUState *env = arg;
3519 tcg_block_io_signals();
3520 qemu_thread_self(env->thread);
3522 /* signal CPU creation */
3523 qemu_mutex_lock(&qemu_global_mutex);
3524 for (env = first_cpu; env != NULL; env = env->next_cpu)
3525 env->created = 1;
3526 qemu_cond_signal(&qemu_cpu_cond);
3528 /* and wait for machine initialization */
3529 while (!qemu_system_ready)
3530 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3532 while (1) {
3533 tcg_cpu_exec();
3534 qemu_wait_io_event(cur_cpu);
3537 return NULL;
3540 void qemu_cpu_kick(void *_env)
3542 CPUState *env = _env;
3543 qemu_cond_broadcast(env->halt_cond);
3544 if (kvm_enabled())
3545 qemu_thread_signal(env->thread, SIG_IPI);
3548 int qemu_cpu_self(void *_env)
3550 CPUState *env = _env;
3551 QemuThread this;
3553 qemu_thread_self(&this);
3555 return qemu_thread_equal(&this, env->thread);
3558 static void cpu_signal(int sig)
3560 if (cpu_single_env)
3561 cpu_exit(cpu_single_env);
3564 static void tcg_block_io_signals(void)
3566 sigset_t set;
3567 struct sigaction sigact;
3569 sigemptyset(&set);
3570 sigaddset(&set, SIGUSR2);
3571 sigaddset(&set, SIGIO);
3572 sigaddset(&set, SIGALRM);
3573 sigaddset(&set, SIGCHLD);
3574 pthread_sigmask(SIG_BLOCK, &set, NULL);
3576 sigemptyset(&set);
3577 sigaddset(&set, SIG_IPI);
3578 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3580 memset(&sigact, 0, sizeof(sigact));
3581 sigact.sa_handler = cpu_signal;
3582 sigaction(SIG_IPI, &sigact, NULL);
3585 static void dummy_signal(int sig)
3589 static void kvm_block_io_signals(CPUState *env)
3591 int r;
3592 sigset_t set;
3593 struct sigaction sigact;
3595 sigemptyset(&set);
3596 sigaddset(&set, SIGUSR2);
3597 sigaddset(&set, SIGIO);
3598 sigaddset(&set, SIGALRM);
3599 sigaddset(&set, SIGCHLD);
3600 sigaddset(&set, SIG_IPI);
3601 pthread_sigmask(SIG_BLOCK, &set, NULL);
3603 pthread_sigmask(SIG_BLOCK, NULL, &set);
3604 sigdelset(&set, SIG_IPI);
3606 memset(&sigact, 0, sizeof(sigact));
3607 sigact.sa_handler = dummy_signal;
3608 sigaction(SIG_IPI, &sigact, NULL);
3610 r = kvm_set_signal_mask(env, &set);
3611 if (r) {
3612 fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(r));
3613 exit(1);
3617 static void unblock_io_signals(void)
3619 sigset_t set;
3621 sigemptyset(&set);
3622 sigaddset(&set, SIGUSR2);
3623 sigaddset(&set, SIGIO);
3624 sigaddset(&set, SIGALRM);
3625 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3627 sigemptyset(&set);
3628 sigaddset(&set, SIG_IPI);
3629 pthread_sigmask(SIG_BLOCK, &set, NULL);
3632 static void qemu_signal_lock(unsigned int msecs)
3634 qemu_mutex_lock(&qemu_fair_mutex);
3636 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3637 qemu_thread_signal(tcg_cpu_thread, SIG_IPI);
3638 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3639 break;
3641 qemu_mutex_unlock(&qemu_fair_mutex);
3644 void qemu_mutex_lock_iothread(void)
3646 if (kvm_enabled()) {
3647 qemu_mutex_lock(&qemu_fair_mutex);
3648 qemu_mutex_lock(&qemu_global_mutex);
3649 qemu_mutex_unlock(&qemu_fair_mutex);
3650 } else
3651 qemu_signal_lock(100);
3654 void qemu_mutex_unlock_iothread(void)
3656 qemu_mutex_unlock(&qemu_global_mutex);
3659 static int all_vcpus_paused(void)
3661 CPUState *penv = first_cpu;
3663 while (penv) {
3664 if (!penv->stopped)
3665 return 0;
3666 penv = (CPUState *)penv->next_cpu;
3669 return 1;
3672 static void pause_all_vcpus(void)
3674 CPUState *penv = first_cpu;
3676 while (penv) {
3677 penv->stop = 1;
3678 qemu_thread_signal(penv->thread, SIG_IPI);
3679 qemu_cpu_kick(penv);
3680 penv = (CPUState *)penv->next_cpu;
3683 while (!all_vcpus_paused()) {
3684 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3685 penv = first_cpu;
3686 while (penv) {
3687 qemu_thread_signal(penv->thread, SIG_IPI);
3688 penv = (CPUState *)penv->next_cpu;
3693 static void resume_all_vcpus(void)
3695 CPUState *penv = first_cpu;
3697 while (penv) {
3698 penv->stop = 0;
3699 penv->stopped = 0;
3700 qemu_thread_signal(penv->thread, SIG_IPI);
3701 qemu_cpu_kick(penv);
3702 penv = (CPUState *)penv->next_cpu;
3706 static void tcg_init_vcpu(void *_env)
3708 CPUState *env = _env;
3709 /* share a single thread for all cpus with TCG */
3710 if (!tcg_cpu_thread) {
3711 env->thread = qemu_mallocz(sizeof(QemuThread));
3712 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3713 qemu_cond_init(env->halt_cond);
3714 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3715 while (env->created == 0)
3716 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3717 tcg_cpu_thread = env->thread;
3718 tcg_halt_cond = env->halt_cond;
3719 } else {
3720 env->thread = tcg_cpu_thread;
3721 env->halt_cond = tcg_halt_cond;
3725 static void kvm_start_vcpu(CPUState *env)
3727 env->thread = qemu_mallocz(sizeof(QemuThread));
3728 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3729 qemu_cond_init(env->halt_cond);
3730 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3731 while (env->created == 0)
3732 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3735 void qemu_init_vcpu(void *_env)
3737 CPUState *env = _env;
3739 env->nr_cores = smp_cores;
3740 env->nr_threads = smp_threads;
3741 if (kvm_enabled())
3742 kvm_start_vcpu(env);
3743 else
3744 tcg_init_vcpu(env);
3747 void qemu_notify_event(void)
3749 qemu_event_increment();
3752 void vm_stop(int reason)
3754 QemuThread me;
3755 qemu_thread_self(&me);
3757 if (!qemu_thread_equal(&me, &io_thread)) {
3758 qemu_system_vmstop_request(reason);
3760 * FIXME: should not return to device code in case
3761 * vm_stop() has been requested.
3763 if (cpu_single_env) {
3764 cpu_exit(cpu_single_env);
3765 cpu_single_env->stop = 1;
3767 return;
3769 do_vm_stop(reason);
3772 #endif
3775 #ifdef _WIN32
3776 static void host_main_loop_wait(int *timeout)
3778 int ret, ret2, i;
3779 PollingEntry *pe;
3782 /* XXX: need to suppress polling by better using win32 events */
3783 ret = 0;
3784 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3785 ret |= pe->func(pe->opaque);
3787 if (ret == 0) {
3788 int err;
3789 WaitObjects *w = &wait_objects;
3791 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3792 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3793 if (w->func[ret - WAIT_OBJECT_0])
3794 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3796 /* Check for additional signaled events */
3797 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3799 /* Check if event is signaled */
3800 ret2 = WaitForSingleObject(w->events[i], 0);
3801 if(ret2 == WAIT_OBJECT_0) {
3802 if (w->func[i])
3803 w->func[i](w->opaque[i]);
3804 } else if (ret2 == WAIT_TIMEOUT) {
3805 } else {
3806 err = GetLastError();
3807 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3810 } else if (ret == WAIT_TIMEOUT) {
3811 } else {
3812 err = GetLastError();
3813 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3817 *timeout = 0;
3819 #else
3820 static void host_main_loop_wait(int *timeout)
3823 #endif
3825 void main_loop_wait(int timeout)
3827 IOHandlerRecord *ioh;
3828 fd_set rfds, wfds, xfds;
3829 int ret, nfds;
3830 struct timeval tv;
3832 qemu_bh_update_timeout(&timeout);
3834 host_main_loop_wait(&timeout);
3836 /* poll any events */
3837 /* XXX: separate device handlers from system ones */
3838 nfds = -1;
3839 FD_ZERO(&rfds);
3840 FD_ZERO(&wfds);
3841 FD_ZERO(&xfds);
3842 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3843 if (ioh->deleted)
3844 continue;
3845 if (ioh->fd_read &&
3846 (!ioh->fd_read_poll ||
3847 ioh->fd_read_poll(ioh->opaque) != 0)) {
3848 FD_SET(ioh->fd, &rfds);
3849 if (ioh->fd > nfds)
3850 nfds = ioh->fd;
3852 if (ioh->fd_write) {
3853 FD_SET(ioh->fd, &wfds);
3854 if (ioh->fd > nfds)
3855 nfds = ioh->fd;
3859 tv.tv_sec = timeout / 1000;
3860 tv.tv_usec = (timeout % 1000) * 1000;
3862 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3864 qemu_mutex_unlock_iothread();
3865 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3866 qemu_mutex_lock_iothread();
3867 if (ret > 0) {
3868 IOHandlerRecord **pioh;
3870 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3871 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3872 ioh->fd_read(ioh->opaque);
3873 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3874 FD_CLR(ioh->fd, &rfds);
3876 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3877 ioh->fd_write(ioh->opaque);
3881 /* remove deleted IO handlers */
3882 pioh = &first_io_handler;
3883 while (*pioh) {
3884 ioh = *pioh;
3885 if (ioh->deleted) {
3886 *pioh = ioh->next;
3887 qemu_free(ioh);
3888 } else
3889 pioh = &ioh->next;
3893 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3895 /* rearm timer, if not periodic */
3896 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3897 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3898 qemu_rearm_alarm_timer(alarm_timer);
3901 /* vm time timers */
3902 if (vm_running) {
3903 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3904 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3905 qemu_get_clock(vm_clock));
3908 /* real time timers */
3909 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3910 qemu_get_clock(rt_clock));
3912 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3913 qemu_get_clock(host_clock));
3915 /* Check bottom-halves last in case any of the earlier events triggered
3916 them. */
3917 qemu_bh_poll();
3921 static int qemu_cpu_exec(CPUState *env)
3923 int ret;
3924 #ifdef CONFIG_PROFILER
3925 int64_t ti;
3926 #endif
3928 #ifdef CONFIG_PROFILER
3929 ti = profile_getclock();
3930 #endif
3931 if (use_icount) {
3932 int64_t count;
3933 int decr;
3934 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3935 env->icount_decr.u16.low = 0;
3936 env->icount_extra = 0;
3937 count = qemu_next_deadline();
3938 count = (count + (1 << icount_time_shift) - 1)
3939 >> icount_time_shift;
3940 qemu_icount += count;
3941 decr = (count > 0xffff) ? 0xffff : count;
3942 count -= decr;
3943 env->icount_decr.u16.low = decr;
3944 env->icount_extra = count;
3946 ret = cpu_exec(env);
3947 #ifdef CONFIG_PROFILER
3948 qemu_time += profile_getclock() - ti;
3949 #endif
3950 if (use_icount) {
3951 /* Fold pending instructions back into the
3952 instruction counter, and clear the interrupt flag. */
3953 qemu_icount -= (env->icount_decr.u16.low
3954 + env->icount_extra);
3955 env->icount_decr.u32 = 0;
3956 env->icount_extra = 0;
3958 return ret;
3961 static void tcg_cpu_exec(void)
3963 int ret = 0;
3965 if (next_cpu == NULL)
3966 next_cpu = first_cpu;
3967 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3968 CPUState *env = cur_cpu = next_cpu;
3970 if (timer_alarm_pending) {
3971 timer_alarm_pending = 0;
3972 break;
3974 if (cpu_can_run(env))
3975 ret = qemu_cpu_exec(env);
3976 else if (env->stop)
3977 break;
3979 if (ret == EXCP_DEBUG) {
3980 gdb_set_stop_cpu(env);
3981 debug_requested = 1;
3982 break;
3987 static int cpu_has_work(CPUState *env)
3989 if (env->stop)
3990 return 1;
3991 if (env->stopped)
3992 return 0;
3993 if (!env->halted)
3994 return 1;
3995 if (qemu_cpu_has_work(env))
3996 return 1;
3997 return 0;
4000 static int tcg_has_work(void)
4002 CPUState *env;
4004 for (env = first_cpu; env != NULL; env = env->next_cpu)
4005 if (cpu_has_work(env))
4006 return 1;
4007 return 0;
4010 static int qemu_calculate_timeout(void)
4012 #ifndef CONFIG_IOTHREAD
4013 int timeout;
4015 if (!vm_running)
4016 timeout = 5000;
4017 else if (tcg_has_work())
4018 timeout = 0;
4019 else if (!use_icount)
4020 timeout = 5000;
4021 else {
4022 /* XXX: use timeout computed from timers */
4023 int64_t add;
4024 int64_t delta;
4025 /* Advance virtual time to the next event. */
4026 if (use_icount == 1) {
4027 /* When not using an adaptive execution frequency
4028 we tend to get badly out of sync with real time,
4029 so just delay for a reasonable amount of time. */
4030 delta = 0;
4031 } else {
4032 delta = cpu_get_icount() - cpu_get_clock();
4034 if (delta > 0) {
4035 /* If virtual time is ahead of real time then just
4036 wait for IO. */
4037 timeout = (delta / 1000000) + 1;
4038 } else {
4039 /* Wait for either IO to occur or the next
4040 timer event. */
4041 add = qemu_next_deadline();
4042 /* We advance the timer before checking for IO.
4043 Limit the amount we advance so that early IO
4044 activity won't get the guest too far ahead. */
4045 if (add > 10000000)
4046 add = 10000000;
4047 delta += add;
4048 add = (add + (1 << icount_time_shift) - 1)
4049 >> icount_time_shift;
4050 qemu_icount += add;
4051 timeout = delta / 1000000;
4052 if (timeout < 0)
4053 timeout = 0;
4057 return timeout;
4058 #else /* CONFIG_IOTHREAD */
4059 return 1000;
4060 #endif
4063 static int vm_can_run(void)
4065 if (powerdown_requested)
4066 return 0;
4067 if (reset_requested)
4068 return 0;
4069 if (shutdown_requested)
4070 return 0;
4071 if (debug_requested)
4072 return 0;
4073 return 1;
4076 qemu_irq qemu_system_powerdown;
4078 static void main_loop(void)
4080 int r;
4082 if (kvm_enabled()) {
4083 kvm_main_loop();
4084 cpu_disable_ticks();
4085 return;
4088 #ifdef CONFIG_IOTHREAD
4089 qemu_system_ready = 1;
4090 qemu_cond_broadcast(&qemu_system_cond);
4091 #endif
4093 for (;;) {
4094 do {
4095 #ifdef CONFIG_PROFILER
4096 int64_t ti;
4097 #endif
4098 #ifndef CONFIG_IOTHREAD
4099 tcg_cpu_exec();
4100 #endif
4101 #ifdef CONFIG_PROFILER
4102 ti = profile_getclock();
4103 #endif
4104 main_loop_wait(qemu_calculate_timeout());
4105 #ifdef CONFIG_PROFILER
4106 dev_time += profile_getclock() - ti;
4107 #endif
4108 } while (vm_can_run());
4110 if (qemu_debug_requested()) {
4111 monitor_protocol_event(QEVENT_DEBUG, NULL);
4112 vm_stop(EXCP_DEBUG);
4114 if (qemu_shutdown_requested()) {
4115 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
4116 if (no_shutdown) {
4117 vm_stop(0);
4118 no_shutdown = 0;
4119 } else
4120 break;
4122 if (qemu_reset_requested()) {
4123 monitor_protocol_event(QEVENT_RESET, NULL);
4124 pause_all_vcpus();
4125 qemu_system_reset();
4126 resume_all_vcpus();
4128 if (qemu_powerdown_requested()) {
4129 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
4130 qemu_irq_raise(qemu_system_powerdown);
4132 if ((r = qemu_vmstop_requested())) {
4133 monitor_protocol_event(QEVENT_STOP, NULL);
4134 vm_stop(r);
4137 pause_all_vcpus();
4140 static void version(void)
4142 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4145 static void help(int exitcode)
4147 const char *options_help =
4148 #define DEF(option, opt_arg, opt_enum, opt_help) \
4149 opt_help
4150 #define DEFHEADING(text) stringify(text) "\n"
4151 #include "qemu-options.h"
4152 #undef DEF
4153 #undef DEFHEADING
4154 #undef GEN_DOCS
4156 version();
4157 printf("usage: %s [options] [disk_image]\n"
4158 "\n"
4159 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4160 "\n"
4161 "%s\n"
4162 "During emulation, the following keys are useful:\n"
4163 "ctrl-alt-f toggle full screen\n"
4164 "ctrl-alt-n switch to virtual console 'n'\n"
4165 "ctrl-alt toggle mouse and keyboard grab\n"
4166 "\n"
4167 "When using -nographic, press 'ctrl-a h' to get some help.\n",
4168 "qemu",
4169 options_help);
4170 exit(exitcode);
4173 #define HAS_ARG 0x0001
4175 enum {
4176 #define DEF(option, opt_arg, opt_enum, opt_help) \
4177 opt_enum,
4178 #define DEFHEADING(text)
4179 #include "qemu-options.h"
4180 #undef DEF
4181 #undef DEFHEADING
4182 #undef GEN_DOCS
4185 typedef struct QEMUOption {
4186 const char *name;
4187 int flags;
4188 int index;
4189 } QEMUOption;
4191 static const QEMUOption qemu_options[] = {
4192 { "h", 0, QEMU_OPTION_h },
4193 #define DEF(option, opt_arg, opt_enum, opt_help) \
4194 { option, opt_arg, opt_enum },
4195 #define DEFHEADING(text)
4196 #include "qemu-options.h"
4197 #undef DEF
4198 #undef DEFHEADING
4199 #undef GEN_DOCS
4200 { NULL },
4203 #ifdef HAS_AUDIO
4204 struct soundhw soundhw[] = {
4205 #ifdef HAS_AUDIO_CHOICE
4206 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4208 "pcspk",
4209 "PC speaker",
4212 { .init_isa = pcspk_audio_init }
4214 #endif
4216 #ifdef CONFIG_SB16
4218 "sb16",
4219 "Creative Sound Blaster 16",
4222 { .init_isa = SB16_init }
4224 #endif
4226 #ifdef CONFIG_CS4231A
4228 "cs4231a",
4229 "CS4231A",
4232 { .init_isa = cs4231a_init }
4234 #endif
4236 #ifdef CONFIG_ADLIB
4238 "adlib",
4239 #ifdef HAS_YMF262
4240 "Yamaha YMF262 (OPL3)",
4241 #else
4242 "Yamaha YM3812 (OPL2)",
4243 #endif
4246 { .init_isa = Adlib_init }
4248 #endif
4250 #ifdef CONFIG_GUS
4252 "gus",
4253 "Gravis Ultrasound GF1",
4256 { .init_isa = GUS_init }
4258 #endif
4260 #ifdef CONFIG_AC97
4262 "ac97",
4263 "Intel 82801AA AC97 Audio",
4266 { .init_pci = ac97_init }
4268 #endif
4270 #ifdef CONFIG_ES1370
4272 "es1370",
4273 "ENSONIQ AudioPCI ES1370",
4276 { .init_pci = es1370_init }
4278 #endif
4280 #endif /* HAS_AUDIO_CHOICE */
4282 { NULL, NULL, 0, 0, { NULL } }
4285 static void select_soundhw (const char *optarg)
4287 struct soundhw *c;
4289 if (*optarg == '?') {
4290 show_valid_cards:
4292 printf ("Valid sound card names (comma separated):\n");
4293 for (c = soundhw; c->name; ++c) {
4294 printf ("%-11s %s\n", c->name, c->descr);
4296 printf ("\n-soundhw all will enable all of the above\n");
4297 exit (*optarg != '?');
4299 else {
4300 size_t l;
4301 const char *p;
4302 char *e;
4303 int bad_card = 0;
4305 if (!strcmp (optarg, "all")) {
4306 for (c = soundhw; c->name; ++c) {
4307 c->enabled = 1;
4309 return;
4312 p = optarg;
4313 while (*p) {
4314 e = strchr (p, ',');
4315 l = !e ? strlen (p) : (size_t) (e - p);
4317 for (c = soundhw; c->name; ++c) {
4318 if (!strncmp (c->name, p, l) && !c->name[l]) {
4319 c->enabled = 1;
4320 break;
4324 if (!c->name) {
4325 if (l > 80) {
4326 fprintf (stderr,
4327 "Unknown sound card name (too big to show)\n");
4329 else {
4330 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4331 (int) l, p);
4333 bad_card = 1;
4335 p += l + (e != NULL);
4338 if (bad_card)
4339 goto show_valid_cards;
4342 #endif
4344 static void select_vgahw (const char *p)
4346 const char *opts;
4348 default_vga = 0;
4349 vga_interface_type = VGA_NONE;
4350 if (strstart(p, "std", &opts)) {
4351 vga_interface_type = VGA_STD;
4352 } else if (strstart(p, "cirrus", &opts)) {
4353 vga_interface_type = VGA_CIRRUS;
4354 } else if (strstart(p, "vmware", &opts)) {
4355 vga_interface_type = VGA_VMWARE;
4356 } else if (strstart(p, "xenfb", &opts)) {
4357 vga_interface_type = VGA_XENFB;
4358 } else if (!strstart(p, "none", &opts)) {
4359 invalid_vga:
4360 fprintf(stderr, "Unknown vga type: %s\n", p);
4361 exit(1);
4363 while (*opts) {
4364 const char *nextopt;
4366 if (strstart(opts, ",retrace=", &nextopt)) {
4367 opts = nextopt;
4368 if (strstart(opts, "dumb", &nextopt))
4369 vga_retrace_method = VGA_RETRACE_DUMB;
4370 else if (strstart(opts, "precise", &nextopt))
4371 vga_retrace_method = VGA_RETRACE_PRECISE;
4372 else goto invalid_vga;
4373 } else goto invalid_vga;
4374 opts = nextopt;
4378 #ifdef TARGET_I386
4379 static int balloon_parse(const char *arg)
4381 QemuOpts *opts;
4383 if (strcmp(arg, "none") == 0) {
4384 return 0;
4387 if (!strncmp(arg, "virtio", 6)) {
4388 if (arg[6] == ',') {
4389 /* have params -> parse them */
4390 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4391 if (!opts)
4392 return -1;
4393 } else {
4394 /* create empty opts */
4395 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4397 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4398 return 0;
4401 return -1;
4403 #endif
4405 #ifdef _WIN32
4406 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4408 exit(STATUS_CONTROL_C_EXIT);
4409 return TRUE;
4411 #endif
4413 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4415 int ret;
4417 if(strlen(str) != 36)
4418 return -1;
4420 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4421 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4422 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4424 if(ret != 16)
4425 return -1;
4427 #ifdef TARGET_I386
4428 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4429 #endif
4431 return 0;
4434 #ifndef _WIN32
4436 static void termsig_handler(int signal)
4438 qemu_system_shutdown_request();
4441 static void sigchld_handler(int signal)
4443 waitpid(-1, NULL, WNOHANG);
4446 static void sighandler_setup(void)
4448 struct sigaction act;
4450 memset(&act, 0, sizeof(act));
4451 act.sa_handler = termsig_handler;
4452 sigaction(SIGINT, &act, NULL);
4453 sigaction(SIGHUP, &act, NULL);
4454 sigaction(SIGTERM, &act, NULL);
4456 act.sa_handler = sigchld_handler;
4457 act.sa_flags = SA_NOCLDSTOP;
4458 sigaction(SIGCHLD, &act, NULL);
4461 #endif
4463 #ifdef _WIN32
4464 /* Look for support files in the same directory as the executable. */
4465 static char *find_datadir(const char *argv0)
4467 char *p;
4468 char buf[MAX_PATH];
4469 DWORD len;
4471 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4472 if (len == 0) {
4473 return NULL;
4476 buf[len] = 0;
4477 p = buf + len - 1;
4478 while (p != buf && *p != '\\')
4479 p--;
4480 *p = 0;
4481 if (access(buf, R_OK) == 0) {
4482 return qemu_strdup(buf);
4484 return NULL;
4486 #else /* !_WIN32 */
4488 /* Find a likely location for support files using the location of the binary.
4489 For installed binaries this will be "$bindir/../share/qemu". When
4490 running from the build tree this will be "$bindir/../pc-bios". */
4491 #define SHARE_SUFFIX "/share/qemu"
4492 #define BUILD_SUFFIX "/pc-bios"
4493 static char *find_datadir(const char *argv0)
4495 char *dir;
4496 char *p = NULL;
4497 char *res;
4498 char buf[PATH_MAX];
4499 size_t max_len;
4501 #if defined(__linux__)
4503 int len;
4504 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4505 if (len > 0) {
4506 buf[len] = 0;
4507 p = buf;
4510 #elif defined(__FreeBSD__)
4512 int len;
4513 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4514 if (len > 0) {
4515 buf[len] = 0;
4516 p = buf;
4519 #endif
4520 /* If we don't have any way of figuring out the actual executable
4521 location then try argv[0]. */
4522 if (!p) {
4523 p = realpath(argv0, buf);
4524 if (!p) {
4525 return NULL;
4528 dir = dirname(p);
4529 dir = dirname(dir);
4531 max_len = strlen(dir) +
4532 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4533 res = qemu_mallocz(max_len);
4534 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4535 if (access(res, R_OK)) {
4536 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4537 if (access(res, R_OK)) {
4538 qemu_free(res);
4539 res = NULL;
4543 return res;
4545 #undef SHARE_SUFFIX
4546 #undef BUILD_SUFFIX
4547 #endif
4549 char *qemu_find_file(int type, const char *name)
4551 int len;
4552 const char *subdir;
4553 char *buf;
4555 /* If name contains path separators then try it as a straight path. */
4556 if ((strchr(name, '/') || strchr(name, '\\'))
4557 && access(name, R_OK) == 0) {
4558 return qemu_strdup(name);
4560 switch (type) {
4561 case QEMU_FILE_TYPE_BIOS:
4562 subdir = "";
4563 break;
4564 case QEMU_FILE_TYPE_KEYMAP:
4565 subdir = "keymaps/";
4566 break;
4567 default:
4568 abort();
4570 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4571 buf = qemu_mallocz(len);
4572 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4573 if (access(buf, R_OK)) {
4574 qemu_free(buf);
4575 return NULL;
4577 return buf;
4580 static int device_help_func(QemuOpts *opts, void *opaque)
4582 return qdev_device_help(opts);
4585 static int device_init_func(QemuOpts *opts, void *opaque)
4587 DeviceState *dev;
4589 dev = qdev_device_add(opts);
4590 if (!dev)
4591 return -1;
4592 return 0;
4595 static int chardev_init_func(QemuOpts *opts, void *opaque)
4597 CharDriverState *chr;
4599 chr = qemu_chr_open_opts(opts, NULL);
4600 if (!chr)
4601 return -1;
4602 return 0;
4605 static int mon_init_func(QemuOpts *opts, void *opaque)
4607 CharDriverState *chr;
4608 const char *chardev;
4609 const char *mode;
4610 int flags;
4612 mode = qemu_opt_get(opts, "mode");
4613 if (mode == NULL) {
4614 mode = "readline";
4616 if (strcmp(mode, "readline") == 0) {
4617 flags = MONITOR_USE_READLINE;
4618 } else if (strcmp(mode, "control") == 0) {
4619 flags = MONITOR_USE_CONTROL;
4620 } else {
4621 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4622 exit(1);
4625 if (qemu_opt_get_bool(opts, "default", 0))
4626 flags |= MONITOR_IS_DEFAULT;
4628 chardev = qemu_opt_get(opts, "chardev");
4629 chr = qemu_chr_find(chardev);
4630 if (chr == NULL) {
4631 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4632 exit(1);
4635 monitor_init(chr, flags);
4636 return 0;
4639 static void monitor_parse(const char *optarg, const char *mode)
4641 static int monitor_device_index = 0;
4642 QemuOpts *opts;
4643 const char *p;
4644 char label[32];
4645 int def = 0;
4647 if (strstart(optarg, "chardev:", &p)) {
4648 snprintf(label, sizeof(label), "%s", p);
4649 } else {
4650 if (monitor_device_index) {
4651 snprintf(label, sizeof(label), "monitor%d",
4652 monitor_device_index);
4653 } else {
4654 snprintf(label, sizeof(label), "monitor");
4655 def = 1;
4657 opts = qemu_chr_parse_compat(label, optarg);
4658 if (!opts) {
4659 fprintf(stderr, "parse error: %s\n", optarg);
4660 exit(1);
4664 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4665 if (!opts) {
4666 fprintf(stderr, "duplicate chardev: %s\n", label);
4667 exit(1);
4669 qemu_opt_set(opts, "mode", mode);
4670 qemu_opt_set(opts, "chardev", label);
4671 if (def)
4672 qemu_opt_set(opts, "default", "on");
4673 monitor_device_index++;
4676 struct device_config {
4677 enum {
4678 DEV_USB, /* -usbdevice */
4679 DEV_BT, /* -bt */
4680 DEV_SERIAL, /* -serial */
4681 DEV_PARALLEL, /* -parallel */
4682 DEV_VIRTCON, /* -virtioconsole */
4683 DEV_DEBUGCON, /* -debugcon */
4684 } type;
4685 const char *cmdline;
4686 QTAILQ_ENTRY(device_config) next;
4688 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4690 static void add_device_config(int type, const char *cmdline)
4692 struct device_config *conf;
4694 conf = qemu_mallocz(sizeof(*conf));
4695 conf->type = type;
4696 conf->cmdline = cmdline;
4697 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4700 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4702 struct device_config *conf;
4703 int rc;
4705 QTAILQ_FOREACH(conf, &device_configs, next) {
4706 if (conf->type != type)
4707 continue;
4708 rc = func(conf->cmdline);
4709 if (0 != rc)
4710 return rc;
4712 return 0;
4715 static int serial_parse(const char *devname)
4717 static int index = 0;
4718 char label[32];
4720 if (strcmp(devname, "none") == 0)
4721 return 0;
4722 if (index == MAX_SERIAL_PORTS) {
4723 fprintf(stderr, "qemu: too many serial ports\n");
4724 exit(1);
4726 snprintf(label, sizeof(label), "serial%d", index);
4727 serial_hds[index] = qemu_chr_open(label, devname, NULL);
4728 if (!serial_hds[index]) {
4729 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4730 devname, strerror(errno));
4731 return -1;
4733 index++;
4734 return 0;
4737 static int parallel_parse(const char *devname)
4739 static int index = 0;
4740 char label[32];
4742 if (strcmp(devname, "none") == 0)
4743 return 0;
4744 if (index == MAX_PARALLEL_PORTS) {
4745 fprintf(stderr, "qemu: too many parallel ports\n");
4746 exit(1);
4748 snprintf(label, sizeof(label), "parallel%d", index);
4749 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4750 if (!parallel_hds[index]) {
4751 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4752 devname, strerror(errno));
4753 return -1;
4755 index++;
4756 return 0;
4759 static int virtcon_parse(const char *devname)
4761 static int index = 0;
4762 char label[32];
4763 QemuOpts *bus_opts, *dev_opts;
4765 if (strcmp(devname, "none") == 0)
4766 return 0;
4767 if (index == MAX_VIRTIO_CONSOLES) {
4768 fprintf(stderr, "qemu: too many virtio consoles\n");
4769 exit(1);
4772 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4773 qemu_opt_set(bus_opts, "driver", "virtio-serial");
4775 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4776 qemu_opt_set(dev_opts, "driver", "virtconsole");
4778 snprintf(label, sizeof(label), "virtcon%d", index);
4779 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
4780 if (!virtcon_hds[index]) {
4781 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
4782 devname, strerror(errno));
4783 return -1;
4785 qemu_opt_set(dev_opts, "chardev", label);
4787 index++;
4788 return 0;
4791 static int debugcon_parse(const char *devname)
4793 QemuOpts *opts;
4795 if (!qemu_chr_open("debugcon", devname, NULL)) {
4796 exit(1);
4798 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
4799 if (!opts) {
4800 fprintf(stderr, "qemu: already have a debugcon device\n");
4801 exit(1);
4803 qemu_opt_set(opts, "driver", "isa-debugcon");
4804 qemu_opt_set(opts, "chardev", "debugcon");
4805 return 0;
4808 static const QEMUOption *lookup_opt(int argc, char **argv,
4809 const char **poptarg, int *poptind)
4811 const QEMUOption *popt;
4812 int optind = *poptind;
4813 char *r = argv[optind];
4814 const char *optarg;
4816 optind++;
4817 /* Treat --foo the same as -foo. */
4818 if (r[1] == '-')
4819 r++;
4820 popt = qemu_options;
4821 for(;;) {
4822 if (!popt->name) {
4823 fprintf(stderr, "%s: invalid option -- '%s'\n",
4824 argv[0], r);
4825 exit(1);
4827 if (!strcmp(popt->name, r + 1))
4828 break;
4829 popt++;
4831 if (popt->flags & HAS_ARG) {
4832 if (optind >= argc) {
4833 fprintf(stderr, "%s: option '%s' requires an argument\n",
4834 argv[0], r);
4835 exit(1);
4837 optarg = argv[optind++];
4838 } else {
4839 optarg = NULL;
4842 *poptarg = optarg;
4843 *poptind = optind;
4845 return popt;
4848 int main(int argc, char **argv, char **envp)
4850 const char *gdbstub_dev = NULL;
4851 uint32_t boot_devices_bitmap = 0;
4852 int i;
4853 int snapshot, linux_boot, net_boot;
4854 const char *initrd_filename;
4855 const char *kernel_filename, *kernel_cmdline;
4856 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4857 DisplayState *ds;
4858 DisplayChangeListener *dcl;
4859 int cyls, heads, secs, translation;
4860 QemuOpts *hda_opts = NULL, *opts;
4861 int optind;
4862 const char *optarg;
4863 const char *loadvm = NULL;
4864 QEMUMachine *machine;
4865 const char *cpu_model;
4866 #ifndef _WIN32
4867 int fds[2];
4868 #endif
4869 int tb_size;
4870 const char *pid_file = NULL;
4871 const char *incoming = NULL;
4872 #ifndef _WIN32
4873 int fd = 0;
4874 struct passwd *pwd = NULL;
4875 const char *chroot_dir = NULL;
4876 const char *run_as = NULL;
4877 #endif
4878 CPUState *env;
4879 int show_vnc_port = 0;
4880 int defconfig = 1;
4882 init_clocks();
4884 qemu_errors_to_file(stderr);
4885 qemu_cache_utils_init(envp);
4887 QLIST_INIT (&vm_change_state_head);
4888 #ifndef _WIN32
4890 struct sigaction act;
4891 sigfillset(&act.sa_mask);
4892 act.sa_flags = 0;
4893 act.sa_handler = SIG_IGN;
4894 sigaction(SIGPIPE, &act, NULL);
4896 #else
4897 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4898 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4899 QEMU to run on a single CPU */
4901 HANDLE h;
4902 DWORD mask, smask;
4903 int i;
4904 h = GetCurrentProcess();
4905 if (GetProcessAffinityMask(h, &mask, &smask)) {
4906 for(i = 0; i < 32; i++) {
4907 if (mask & (1 << i))
4908 break;
4910 if (i != 32) {
4911 mask = 1 << i;
4912 SetProcessAffinityMask(h, mask);
4916 #endif
4918 module_call_init(MODULE_INIT_MACHINE);
4919 machine = find_default_machine();
4920 cpu_model = NULL;
4921 initrd_filename = NULL;
4922 ram_size = 0;
4923 snapshot = 0;
4924 kernel_filename = NULL;
4925 kernel_cmdline = "";
4926 cyls = heads = secs = 0;
4927 translation = BIOS_ATA_TRANSLATION_AUTO;
4929 for (i = 0; i < MAX_NODES; i++) {
4930 node_mem[i] = 0;
4931 node_cpumask[i] = 0;
4934 assigned_devices_index = 0;
4936 nb_numa_nodes = 0;
4937 nb_nics = 0;
4939 tb_size = 0;
4940 autostart= 1;
4942 /* first pass of option parsing */
4943 optind = 1;
4944 while (optind < argc) {
4945 if (argv[optind][0] != '-') {
4946 /* disk image */
4947 optind++;
4948 continue;
4949 } else {
4950 const QEMUOption *popt;
4952 popt = lookup_opt(argc, argv, &optarg, &optind);
4953 switch (popt->index) {
4954 case QEMU_OPTION_nodefconfig:
4955 defconfig=0;
4956 break;
4961 if (defconfig) {
4962 FILE *fp;
4963 fp = fopen(CONFIG_QEMU_CONFDIR "/qemu.conf", "r");
4964 if (fp) {
4965 if (qemu_config_parse(fp) != 0) {
4966 exit(1);
4968 fclose(fp);
4971 fp = fopen(CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf", "r");
4972 if (fp) {
4973 if (qemu_config_parse(fp) != 0) {
4974 exit(1);
4976 fclose(fp);
4979 #if defined(cpudef_setup)
4980 cpudef_setup(); /* parse cpu definitions in target config file */
4981 #endif
4983 /* second pass of option parsing */
4984 optind = 1;
4985 for(;;) {
4986 if (optind >= argc)
4987 break;
4988 if (argv[optind][0] != '-') {
4989 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4990 } else {
4991 const QEMUOption *popt;
4993 popt = lookup_opt(argc, argv, &optarg, &optind);
4994 switch(popt->index) {
4995 case QEMU_OPTION_M:
4996 machine = find_machine(optarg);
4997 if (!machine) {
4998 QEMUMachine *m;
4999 printf("Supported machines are:\n");
5000 for(m = first_machine; m != NULL; m = m->next) {
5001 if (m->alias)
5002 printf("%-10s %s (alias of %s)\n",
5003 m->alias, m->desc, m->name);
5004 printf("%-10s %s%s\n",
5005 m->name, m->desc,
5006 m->is_default ? " (default)" : "");
5008 exit(*optarg != '?');
5010 break;
5011 case QEMU_OPTION_cpu:
5012 /* hw initialization will check this */
5013 if (*optarg == '?') {
5014 /* XXX: implement xxx_cpu_list for targets that still miss it */
5015 #if defined(cpu_list_id)
5016 cpu_list_id(stdout, &fprintf, optarg);
5017 #elif defined(cpu_list)
5018 cpu_list(stdout, &fprintf); /* deprecated */
5019 #endif
5020 exit(0);
5021 } else {
5022 cpu_model = optarg;
5024 break;
5025 case QEMU_OPTION_initrd:
5026 initrd_filename = optarg;
5027 break;
5028 case QEMU_OPTION_hda:
5029 if (cyls == 0)
5030 hda_opts = drive_add(optarg, HD_ALIAS, 0);
5031 else
5032 hda_opts = drive_add(optarg, HD_ALIAS
5033 ",cyls=%d,heads=%d,secs=%d%s",
5034 0, cyls, heads, secs,
5035 translation == BIOS_ATA_TRANSLATION_LBA ?
5036 ",trans=lba" :
5037 translation == BIOS_ATA_TRANSLATION_NONE ?
5038 ",trans=none" : "");
5039 break;
5040 case QEMU_OPTION_hdb:
5041 case QEMU_OPTION_hdc:
5042 case QEMU_OPTION_hdd:
5043 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5044 break;
5045 case QEMU_OPTION_drive:
5046 drive_add(NULL, "%s", optarg);
5047 break;
5048 case QEMU_OPTION_set:
5049 if (qemu_set_option(optarg) != 0)
5050 exit(1);
5051 break;
5052 case QEMU_OPTION_global:
5053 if (qemu_global_option(optarg) != 0)
5054 exit(1);
5055 break;
5056 case QEMU_OPTION_mtdblock:
5057 drive_add(optarg, MTD_ALIAS);
5058 break;
5059 case QEMU_OPTION_sd:
5060 drive_add(optarg, SD_ALIAS);
5061 break;
5062 case QEMU_OPTION_pflash:
5063 drive_add(optarg, PFLASH_ALIAS);
5064 break;
5065 case QEMU_OPTION_snapshot:
5066 snapshot = 1;
5067 break;
5068 case QEMU_OPTION_hdachs:
5070 const char *p;
5071 p = optarg;
5072 cyls = strtol(p, (char **)&p, 0);
5073 if (cyls < 1 || cyls > 16383)
5074 goto chs_fail;
5075 if (*p != ',')
5076 goto chs_fail;
5077 p++;
5078 heads = strtol(p, (char **)&p, 0);
5079 if (heads < 1 || heads > 16)
5080 goto chs_fail;
5081 if (*p != ',')
5082 goto chs_fail;
5083 p++;
5084 secs = strtol(p, (char **)&p, 0);
5085 if (secs < 1 || secs > 63)
5086 goto chs_fail;
5087 if (*p == ',') {
5088 p++;
5089 if (!strcmp(p, "none"))
5090 translation = BIOS_ATA_TRANSLATION_NONE;
5091 else if (!strcmp(p, "lba"))
5092 translation = BIOS_ATA_TRANSLATION_LBA;
5093 else if (!strcmp(p, "auto"))
5094 translation = BIOS_ATA_TRANSLATION_AUTO;
5095 else
5096 goto chs_fail;
5097 } else if (*p != '\0') {
5098 chs_fail:
5099 fprintf(stderr, "qemu: invalid physical CHS format\n");
5100 exit(1);
5102 if (hda_opts != NULL) {
5103 char num[16];
5104 snprintf(num, sizeof(num), "%d", cyls);
5105 qemu_opt_set(hda_opts, "cyls", num);
5106 snprintf(num, sizeof(num), "%d", heads);
5107 qemu_opt_set(hda_opts, "heads", num);
5108 snprintf(num, sizeof(num), "%d", secs);
5109 qemu_opt_set(hda_opts, "secs", num);
5110 if (translation == BIOS_ATA_TRANSLATION_LBA)
5111 qemu_opt_set(hda_opts, "trans", "lba");
5112 if (translation == BIOS_ATA_TRANSLATION_NONE)
5113 qemu_opt_set(hda_opts, "trans", "none");
5116 break;
5117 case QEMU_OPTION_numa:
5118 if (nb_numa_nodes >= MAX_NODES) {
5119 fprintf(stderr, "qemu: too many NUMA nodes\n");
5120 exit(1);
5122 numa_add(optarg);
5123 break;
5124 case QEMU_OPTION_nographic:
5125 display_type = DT_NOGRAPHIC;
5126 break;
5127 #ifdef CONFIG_CURSES
5128 case QEMU_OPTION_curses:
5129 display_type = DT_CURSES;
5130 break;
5131 #endif
5132 case QEMU_OPTION_portrait:
5133 graphic_rotate = 1;
5134 break;
5135 case QEMU_OPTION_kernel:
5136 kernel_filename = optarg;
5137 break;
5138 case QEMU_OPTION_append:
5139 kernel_cmdline = optarg;
5140 break;
5141 case QEMU_OPTION_cdrom:
5142 drive_add(optarg, CDROM_ALIAS);
5143 break;
5144 case QEMU_OPTION_boot:
5146 static const char * const params[] = {
5147 "order", "once", "menu", NULL
5149 char buf[sizeof(boot_devices)];
5150 char *standard_boot_devices;
5151 int legacy = 0;
5153 if (!strchr(optarg, '=')) {
5154 legacy = 1;
5155 pstrcpy(buf, sizeof(buf), optarg);
5156 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5157 fprintf(stderr,
5158 "qemu: unknown boot parameter '%s' in '%s'\n",
5159 buf, optarg);
5160 exit(1);
5163 if (legacy ||
5164 get_param_value(buf, sizeof(buf), "order", optarg)) {
5165 boot_devices_bitmap = parse_bootdevices(buf);
5166 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5168 if (!legacy) {
5169 if (get_param_value(buf, sizeof(buf),
5170 "once", optarg)) {
5171 boot_devices_bitmap |= parse_bootdevices(buf);
5172 standard_boot_devices = qemu_strdup(boot_devices);
5173 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5174 qemu_register_reset(restore_boot_devices,
5175 standard_boot_devices);
5177 if (get_param_value(buf, sizeof(buf),
5178 "menu", optarg)) {
5179 if (!strcmp(buf, "on")) {
5180 boot_menu = 1;
5181 } else if (!strcmp(buf, "off")) {
5182 boot_menu = 0;
5183 } else {
5184 fprintf(stderr,
5185 "qemu: invalid option value '%s'\n",
5186 buf);
5187 exit(1);
5192 break;
5193 case QEMU_OPTION_fda:
5194 case QEMU_OPTION_fdb:
5195 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5196 break;
5197 #ifdef TARGET_I386
5198 case QEMU_OPTION_no_fd_bootchk:
5199 fd_bootchk = 0;
5200 break;
5201 #endif
5202 case QEMU_OPTION_netdev:
5203 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
5204 exit(1);
5206 break;
5207 case QEMU_OPTION_net:
5208 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
5209 exit(1);
5211 break;
5212 #ifdef CONFIG_SLIRP
5213 case QEMU_OPTION_tftp:
5214 legacy_tftp_prefix = optarg;
5215 break;
5216 case QEMU_OPTION_bootp:
5217 legacy_bootp_filename = optarg;
5218 break;
5219 #ifndef _WIN32
5220 case QEMU_OPTION_smb:
5221 if (net_slirp_smb(optarg) < 0)
5222 exit(1);
5223 break;
5224 #endif
5225 case QEMU_OPTION_redir:
5226 if (net_slirp_redir(optarg) < 0)
5227 exit(1);
5228 break;
5229 #endif
5230 case QEMU_OPTION_bt:
5231 add_device_config(DEV_BT, optarg);
5232 break;
5233 #ifdef HAS_AUDIO
5234 case QEMU_OPTION_audio_help:
5235 AUD_help ();
5236 exit (0);
5237 break;
5238 case QEMU_OPTION_soundhw:
5239 select_soundhw (optarg);
5240 break;
5241 #endif
5242 case QEMU_OPTION_h:
5243 help(0);
5244 break;
5245 case QEMU_OPTION_version:
5246 version();
5247 exit(0);
5248 break;
5249 case QEMU_OPTION_m: {
5250 uint64_t value;
5251 char *ptr;
5253 value = strtoul(optarg, &ptr, 10);
5254 switch (*ptr) {
5255 case 0: case 'M': case 'm':
5256 value <<= 20;
5257 break;
5258 case 'G': case 'g':
5259 value <<= 30;
5260 break;
5261 default:
5262 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5263 exit(1);
5266 /* On 32-bit hosts, QEMU is limited by virtual address space */
5267 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5268 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5269 exit(1);
5271 if (value != (uint64_t)(ram_addr_t)value) {
5272 fprintf(stderr, "qemu: ram size too large\n");
5273 exit(1);
5275 ram_size = value;
5276 break;
5278 case QEMU_OPTION_d:
5280 int mask;
5281 const CPULogItem *item;
5283 mask = cpu_str_to_log_mask(optarg);
5284 if (!mask) {
5285 printf("Log items (comma separated):\n");
5286 for(item = cpu_log_items; item->mask != 0; item++) {
5287 printf("%-10s %s\n", item->name, item->help);
5289 exit(1);
5291 cpu_set_log(mask);
5293 break;
5294 case QEMU_OPTION_s:
5295 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5296 break;
5297 case QEMU_OPTION_gdb:
5298 gdbstub_dev = optarg;
5299 break;
5300 case QEMU_OPTION_L:
5301 data_dir = optarg;
5302 break;
5303 case QEMU_OPTION_bios:
5304 bios_name = optarg;
5305 break;
5306 case QEMU_OPTION_singlestep:
5307 singlestep = 1;
5308 break;
5309 case QEMU_OPTION_S:
5310 autostart = 0;
5311 break;
5312 case QEMU_OPTION_k:
5313 keyboard_layout = optarg;
5314 break;
5315 case QEMU_OPTION_localtime:
5316 rtc_utc = 0;
5317 break;
5318 case QEMU_OPTION_vga:
5319 select_vgahw (optarg);
5320 break;
5321 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5322 case QEMU_OPTION_g:
5324 const char *p;
5325 int w, h, depth;
5326 p = optarg;
5327 w = strtol(p, (char **)&p, 10);
5328 if (w <= 0) {
5329 graphic_error:
5330 fprintf(stderr, "qemu: invalid resolution or depth\n");
5331 exit(1);
5333 if (*p != 'x')
5334 goto graphic_error;
5335 p++;
5336 h = strtol(p, (char **)&p, 10);
5337 if (h <= 0)
5338 goto graphic_error;
5339 if (*p == 'x') {
5340 p++;
5341 depth = strtol(p, (char **)&p, 10);
5342 if (depth != 8 && depth != 15 && depth != 16 &&
5343 depth != 24 && depth != 32)
5344 goto graphic_error;
5345 } else if (*p == '\0') {
5346 depth = graphic_depth;
5347 } else {
5348 goto graphic_error;
5351 graphic_width = w;
5352 graphic_height = h;
5353 graphic_depth = depth;
5355 break;
5356 #endif
5357 case QEMU_OPTION_echr:
5359 char *r;
5360 term_escape_char = strtol(optarg, &r, 0);
5361 if (r == optarg)
5362 printf("Bad argument to echr\n");
5363 break;
5365 case QEMU_OPTION_monitor:
5366 monitor_parse(optarg, "readline");
5367 default_monitor = 0;
5368 break;
5369 case QEMU_OPTION_qmp:
5370 monitor_parse(optarg, "control");
5371 default_monitor = 0;
5372 break;
5373 case QEMU_OPTION_mon:
5374 opts = qemu_opts_parse(&qemu_mon_opts, optarg, "chardev");
5375 if (!opts) {
5376 fprintf(stderr, "parse error: %s\n", optarg);
5377 exit(1);
5379 default_monitor = 0;
5380 break;
5381 case QEMU_OPTION_chardev:
5382 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5383 if (!opts) {
5384 fprintf(stderr, "parse error: %s\n", optarg);
5385 exit(1);
5387 break;
5388 case QEMU_OPTION_serial:
5389 add_device_config(DEV_SERIAL, optarg);
5390 default_serial = 0;
5391 break;
5392 case QEMU_OPTION_watchdog:
5393 if (watchdog) {
5394 fprintf(stderr,
5395 "qemu: only one watchdog option may be given\n");
5396 return 1;
5398 watchdog = optarg;
5399 break;
5400 case QEMU_OPTION_watchdog_action:
5401 if (select_watchdog_action(optarg) == -1) {
5402 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5403 exit(1);
5405 break;
5406 case QEMU_OPTION_virtiocon:
5407 add_device_config(DEV_VIRTCON, optarg);
5408 default_virtcon = 0;
5409 break;
5410 case QEMU_OPTION_parallel:
5411 add_device_config(DEV_PARALLEL, optarg);
5412 default_parallel = 0;
5413 break;
5414 case QEMU_OPTION_debugcon:
5415 add_device_config(DEV_DEBUGCON, optarg);
5416 break;
5417 case QEMU_OPTION_loadvm:
5418 loadvm = optarg;
5419 break;
5420 case QEMU_OPTION_full_screen:
5421 full_screen = 1;
5422 break;
5423 #ifdef CONFIG_SDL
5424 case QEMU_OPTION_no_frame:
5425 no_frame = 1;
5426 break;
5427 case QEMU_OPTION_alt_grab:
5428 alt_grab = 1;
5429 break;
5430 case QEMU_OPTION_ctrl_grab:
5431 ctrl_grab = 1;
5432 break;
5433 case QEMU_OPTION_no_quit:
5434 no_quit = 1;
5435 break;
5436 case QEMU_OPTION_sdl:
5437 display_type = DT_SDL;
5438 break;
5439 #endif
5440 case QEMU_OPTION_pidfile:
5441 pid_file = optarg;
5442 break;
5443 #ifdef TARGET_I386
5444 case QEMU_OPTION_win2k_hack:
5445 win2k_install_hack = 1;
5446 break;
5447 case QEMU_OPTION_rtc_td_hack:
5448 rtc_td_hack = 1;
5449 break;
5450 case QEMU_OPTION_acpitable:
5451 if(acpi_table_add(optarg) < 0) {
5452 fprintf(stderr, "Wrong acpi table provided\n");
5453 exit(1);
5455 break;
5456 case QEMU_OPTION_smbios:
5457 if(smbios_entry_add(optarg) < 0) {
5458 fprintf(stderr, "Wrong smbios provided\n");
5459 exit(1);
5461 break;
5462 #endif
5463 #ifdef CONFIG_KVM
5464 #ifdef KVM_UPSTREAM
5465 case QEMU_OPTION_enable_kvm:
5466 kvm_allowed = 1;
5467 #endif
5468 break;
5469 case QEMU_OPTION_no_kvm:
5470 kvm_allowed = 0;
5471 break;
5472 case QEMU_OPTION_no_kvm_irqchip: {
5473 kvm_irqchip = 0;
5474 kvm_pit = 0;
5475 break;
5477 case QEMU_OPTION_no_kvm_pit: {
5478 kvm_pit = 0;
5479 break;
5481 case QEMU_OPTION_no_kvm_pit_reinjection: {
5482 kvm_pit_reinject = 0;
5483 break;
5485 case QEMU_OPTION_enable_nesting: {
5486 kvm_nested = 1;
5487 break;
5489 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5490 case QEMU_OPTION_pcidevice:
5491 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5492 fprintf(stderr, "Too many assigned devices\n");
5493 exit(1);
5495 assigned_devices[assigned_devices_index] = optarg;
5496 assigned_devices_index++;
5497 break;
5498 #endif
5499 #endif
5500 case QEMU_OPTION_usb:
5501 usb_enabled = 1;
5502 break;
5503 case QEMU_OPTION_usbdevice:
5504 usb_enabled = 1;
5505 add_device_config(DEV_USB, optarg);
5506 break;
5507 case QEMU_OPTION_device:
5508 if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5509 exit(1);
5511 break;
5512 case QEMU_OPTION_smp:
5513 smp_parse(optarg);
5514 if (smp_cpus < 1) {
5515 fprintf(stderr, "Invalid number of CPUs\n");
5516 exit(1);
5518 if (max_cpus < smp_cpus) {
5519 fprintf(stderr, "maxcpus must be equal to or greater than "
5520 "smp\n");
5521 exit(1);
5523 if (max_cpus > 255) {
5524 fprintf(stderr, "Unsupported number of maxcpus\n");
5525 exit(1);
5527 break;
5528 case QEMU_OPTION_vnc:
5529 display_type = DT_VNC;
5530 vnc_display = optarg;
5531 break;
5532 #ifdef TARGET_I386
5533 case QEMU_OPTION_no_acpi:
5534 acpi_enabled = 0;
5535 break;
5536 case QEMU_OPTION_no_hpet:
5537 no_hpet = 1;
5538 break;
5539 case QEMU_OPTION_balloon:
5540 if (balloon_parse(optarg) < 0) {
5541 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5542 exit(1);
5544 break;
5545 #endif
5546 case QEMU_OPTION_no_reboot:
5547 no_reboot = 1;
5548 break;
5549 case QEMU_OPTION_no_shutdown:
5550 no_shutdown = 1;
5551 break;
5552 case QEMU_OPTION_show_cursor:
5553 cursor_hide = 0;
5554 break;
5555 case QEMU_OPTION_uuid:
5556 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5557 fprintf(stderr, "Fail to parse UUID string."
5558 " Wrong format.\n");
5559 exit(1);
5561 break;
5562 #ifndef _WIN32
5563 case QEMU_OPTION_daemonize:
5564 daemonize = 1;
5565 break;
5566 #endif
5567 case QEMU_OPTION_option_rom:
5568 if (nb_option_roms >= MAX_OPTION_ROMS) {
5569 fprintf(stderr, "Too many option ROMs\n");
5570 exit(1);
5572 option_rom[nb_option_roms] = optarg;
5573 nb_option_roms++;
5574 break;
5575 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5576 case QEMU_OPTION_semihosting:
5577 semihosting_enabled = 1;
5578 break;
5579 #endif
5580 case QEMU_OPTION_tdf:
5581 time_drift_fix = 1;
5582 break;
5583 case QEMU_OPTION_kvm_shadow_memory:
5584 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5585 break;
5586 case QEMU_OPTION_mempath:
5587 mem_path = optarg;
5588 break;
5589 #ifdef MAP_POPULATE
5590 case QEMU_OPTION_mem_prealloc:
5591 mem_prealloc = !mem_prealloc;
5592 break;
5593 #endif
5594 case QEMU_OPTION_name:
5595 qemu_name = qemu_strdup(optarg);
5597 char *p = strchr(qemu_name, ',');
5598 if (p != NULL) {
5599 *p++ = 0;
5600 if (strncmp(p, "process=", 8)) {
5601 fprintf(stderr, "Unknown subargument %s to -name", p);
5602 exit(1);
5604 p += 8;
5605 set_proc_name(p);
5608 break;
5609 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5610 case QEMU_OPTION_prom_env:
5611 if (nb_prom_envs >= MAX_PROM_ENVS) {
5612 fprintf(stderr, "Too many prom variables\n");
5613 exit(1);
5615 prom_envs[nb_prom_envs] = optarg;
5616 nb_prom_envs++;
5617 break;
5618 #endif
5619 #ifdef TARGET_ARM
5620 case QEMU_OPTION_old_param:
5621 old_param = 1;
5622 break;
5623 #endif
5624 case QEMU_OPTION_clock:
5625 configure_alarms(optarg);
5626 break;
5627 case QEMU_OPTION_startdate:
5628 configure_rtc_date_offset(optarg, 1);
5629 break;
5630 case QEMU_OPTION_rtc:
5631 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5632 if (!opts) {
5633 fprintf(stderr, "parse error: %s\n", optarg);
5634 exit(1);
5636 configure_rtc(opts);
5637 break;
5638 case QEMU_OPTION_tb_size:
5639 tb_size = strtol(optarg, NULL, 0);
5640 if (tb_size < 0)
5641 tb_size = 0;
5642 break;
5643 case QEMU_OPTION_icount:
5644 use_icount = 1;
5645 if (strcmp(optarg, "auto") == 0) {
5646 icount_time_shift = -1;
5647 } else {
5648 icount_time_shift = strtol(optarg, NULL, 0);
5650 break;
5651 case QEMU_OPTION_incoming:
5652 incoming = optarg;
5653 break;
5654 case QEMU_OPTION_nodefaults:
5655 default_serial = 0;
5656 default_parallel = 0;
5657 default_virtcon = 0;
5658 default_monitor = 0;
5659 default_vga = 0;
5660 default_net = 0;
5661 default_floppy = 0;
5662 default_cdrom = 0;
5663 default_sdcard = 0;
5664 break;
5665 #ifndef _WIN32
5666 case QEMU_OPTION_chroot:
5667 chroot_dir = optarg;
5668 break;
5669 case QEMU_OPTION_runas:
5670 run_as = optarg;
5671 break;
5672 case QEMU_OPTION_nvram:
5673 nvram = optarg;
5674 break;
5675 #endif
5676 #ifdef CONFIG_XEN
5677 case QEMU_OPTION_xen_domid:
5678 xen_domid = atoi(optarg);
5679 break;
5680 case QEMU_OPTION_xen_create:
5681 xen_mode = XEN_CREATE;
5682 break;
5683 case QEMU_OPTION_xen_attach:
5684 xen_mode = XEN_ATTACH;
5685 break;
5686 #endif
5687 case QEMU_OPTION_readconfig:
5689 FILE *fp;
5690 fp = fopen(optarg, "r");
5691 if (fp == NULL) {
5692 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5693 exit(1);
5695 if (qemu_config_parse(fp) != 0) {
5696 exit(1);
5698 fclose(fp);
5699 break;
5701 case QEMU_OPTION_writeconfig:
5703 FILE *fp;
5704 if (strcmp(optarg, "-") == 0) {
5705 fp = stdout;
5706 } else {
5707 fp = fopen(optarg, "w");
5708 if (fp == NULL) {
5709 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5710 exit(1);
5713 qemu_config_write(fp);
5714 fclose(fp);
5715 break;
5721 /* If no data_dir is specified then try to find it relative to the
5722 executable path. */
5723 if (!data_dir) {
5724 data_dir = find_datadir(argv[0]);
5726 /* If all else fails use the install patch specified when building. */
5727 if (!data_dir) {
5728 data_dir = CONFIG_QEMU_SHAREDIR;
5732 * Default to max_cpus = smp_cpus, in case the user doesn't
5733 * specify a max_cpus value.
5735 if (!max_cpus)
5736 max_cpus = smp_cpus;
5738 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5739 if (smp_cpus > machine->max_cpus) {
5740 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5741 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5742 machine->max_cpus);
5743 exit(1);
5746 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5747 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
5749 if (machine->no_serial) {
5750 default_serial = 0;
5752 if (machine->no_parallel) {
5753 default_parallel = 0;
5755 if (!machine->use_virtcon) {
5756 default_virtcon = 0;
5758 if (machine->no_vga) {
5759 default_vga = 0;
5761 if (machine->no_floppy) {
5762 default_floppy = 0;
5764 if (machine->no_cdrom) {
5765 default_cdrom = 0;
5767 if (machine->no_sdcard) {
5768 default_sdcard = 0;
5771 if (display_type == DT_NOGRAPHIC) {
5772 if (default_parallel)
5773 add_device_config(DEV_PARALLEL, "null");
5774 if (default_serial && default_monitor) {
5775 add_device_config(DEV_SERIAL, "mon:stdio");
5776 } else if (default_virtcon && default_monitor) {
5777 add_device_config(DEV_VIRTCON, "mon:stdio");
5778 } else {
5779 if (default_serial)
5780 add_device_config(DEV_SERIAL, "stdio");
5781 if (default_virtcon)
5782 add_device_config(DEV_VIRTCON, "stdio");
5783 if (default_monitor)
5784 monitor_parse("stdio", "readline");
5786 } else {
5787 if (default_serial)
5788 add_device_config(DEV_SERIAL, "vc:80Cx24C");
5789 if (default_parallel)
5790 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
5791 if (default_monitor)
5792 monitor_parse("vc:80Cx24C", "readline");
5793 if (default_virtcon)
5794 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
5796 if (default_vga)
5797 vga_interface_type = VGA_CIRRUS;
5799 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5800 exit(1);
5802 #ifndef _WIN32
5803 if (daemonize) {
5804 pid_t pid;
5806 if (pipe(fds) == -1)
5807 exit(1);
5809 pid = fork();
5810 if (pid > 0) {
5811 uint8_t status;
5812 ssize_t len;
5814 close(fds[1]);
5816 again:
5817 len = read(fds[0], &status, 1);
5818 if (len == -1 && (errno == EINTR))
5819 goto again;
5821 if (len != 1)
5822 exit(1);
5823 else if (status == 1) {
5824 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5825 exit(1);
5826 } else
5827 exit(0);
5828 } else if (pid < 0)
5829 exit(1);
5831 close(fds[0]);
5832 qemu_set_cloexec(fds[1]);
5834 setsid();
5836 pid = fork();
5837 if (pid > 0)
5838 exit(0);
5839 else if (pid < 0)
5840 exit(1);
5842 umask(027);
5844 signal(SIGTSTP, SIG_IGN);
5845 signal(SIGTTOU, SIG_IGN);
5846 signal(SIGTTIN, SIG_IGN);
5848 #endif
5850 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5851 #ifndef _WIN32
5852 if (daemonize) {
5853 uint8_t status = 1;
5854 if (write(fds[1], &status, 1) != 1) {
5855 perror("daemonize. Writing to pipe\n");
5857 } else
5858 #endif
5859 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5860 exit(1);
5863 if (kvm_enabled()) {
5864 int ret;
5866 ret = kvm_init(smp_cpus);
5867 if (ret < 0) {
5868 #if defined(KVM_UPSTREAM) || defined(CONFIG_NO_CPU_EMULATION)
5869 fprintf(stderr, "failed to initialize KVM\n");
5870 exit(1);
5871 #endif
5872 #ifdef CONFIG_KVM
5873 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5874 kvm_allowed = 0;
5875 #endif
5879 if (qemu_init_main_loop()) {
5880 fprintf(stderr, "qemu_init_main_loop failed\n");
5881 exit(1);
5883 linux_boot = (kernel_filename != NULL);
5885 if (!linux_boot && *kernel_cmdline != '\0') {
5886 fprintf(stderr, "-append only allowed with -kernel option\n");
5887 exit(1);
5890 if (!linux_boot && initrd_filename != NULL) {
5891 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5892 exit(1);
5895 #ifndef _WIN32
5896 /* Win32 doesn't support line-buffering and requires size >= 2 */
5897 setvbuf(stdout, NULL, _IOLBF, 0);
5898 #endif
5900 if (init_timer_alarm() < 0) {
5901 fprintf(stderr, "could not initialize alarm timer\n");
5902 exit(1);
5904 if (use_icount && icount_time_shift < 0) {
5905 use_icount = 2;
5906 /* 125MIPS seems a reasonable initial guess at the guest speed.
5907 It will be corrected fairly quickly anyway. */
5908 icount_time_shift = 3;
5909 init_icount_adjust();
5912 #ifdef _WIN32
5913 socket_init();
5914 #endif
5916 if (net_init_clients() < 0) {
5917 exit(1);
5920 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5921 net_set_boot_mask(net_boot);
5923 /* init the bluetooth world */
5924 if (foreach_device_config(DEV_BT, bt_parse))
5925 exit(1);
5927 /* init the memory */
5928 if (ram_size == 0)
5929 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5931 /* init the dynamic translator */
5932 cpu_exec_init_all(tb_size * 1024 * 1024);
5934 bdrv_init_with_whitelist();
5936 blk_mig_init();
5938 if (default_cdrom) {
5939 /* we always create the cdrom drive, even if no disk is there */
5940 drive_add(NULL, CDROM_ALIAS);
5943 if (default_floppy) {
5944 /* we always create at least one floppy */
5945 drive_add(NULL, FD_ALIAS, 0);
5948 if (default_sdcard) {
5949 /* we always create one sd slot, even if no card is in it */
5950 drive_add(NULL, SD_ALIAS);
5953 /* open the virtual block devices */
5954 if (snapshot)
5955 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5956 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5957 exit(1);
5959 vmstate_register(0, &vmstate_timers ,&timers_state);
5960 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
5961 ram_load, NULL);
5963 if (nb_numa_nodes > 0) {
5964 int i;
5966 if (nb_numa_nodes > smp_cpus) {
5967 nb_numa_nodes = smp_cpus;
5970 /* If no memory size if given for any node, assume the default case
5971 * and distribute the available memory equally across all nodes
5973 for (i = 0; i < nb_numa_nodes; i++) {
5974 if (node_mem[i] != 0)
5975 break;
5977 if (i == nb_numa_nodes) {
5978 uint64_t usedmem = 0;
5980 /* On Linux, the each node's border has to be 8MB aligned,
5981 * the final node gets the rest.
5983 for (i = 0; i < nb_numa_nodes - 1; i++) {
5984 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5985 usedmem += node_mem[i];
5987 node_mem[i] = ram_size - usedmem;
5990 for (i = 0; i < nb_numa_nodes; i++) {
5991 if (node_cpumask[i] != 0)
5992 break;
5994 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5995 * must cope with this anyway, because there are BIOSes out there in
5996 * real machines which also use this scheme.
5998 if (i == nb_numa_nodes) {
5999 for (i = 0; i < smp_cpus; i++) {
6000 node_cpumask[i % nb_numa_nodes] |= 1 << i;
6005 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
6006 exit(1);
6007 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
6008 exit(1);
6009 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
6010 exit(1);
6011 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
6012 exit(1);
6014 module_call_init(MODULE_INIT_DEVICE);
6016 if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
6017 exit(0);
6019 if (watchdog) {
6020 i = select_watchdog(watchdog);
6021 if (i > 0)
6022 exit (i == 1 ? 1 : 0);
6025 if (machine->compat_props) {
6026 qdev_prop_register_global_list(machine->compat_props);
6028 qemu_add_globals();
6030 machine->init(ram_size, boot_devices,
6031 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6034 #ifndef _WIN32
6035 /* must be after terminal init, SDL library changes signal handlers */
6036 sighandler_setup();
6037 #endif
6039 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6040 for (i = 0; i < nb_numa_nodes; i++) {
6041 if (node_cpumask[i] & (1 << env->cpu_index)) {
6042 env->numa_node = i;
6047 current_machine = machine;
6049 /* init USB devices */
6050 if (usb_enabled) {
6051 if (foreach_device_config(DEV_USB, usb_parse) < 0)
6052 exit(1);
6055 /* init generic devices */
6056 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
6057 exit(1);
6059 net_check_clients();
6061 /* just use the first displaystate for the moment */
6062 ds = get_displaystate();
6064 if (display_type == DT_DEFAULT) {
6065 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6066 display_type = DT_SDL;
6067 #else
6068 display_type = DT_VNC;
6069 vnc_display = "localhost:0,to=99";
6070 show_vnc_port = 1;
6071 #endif
6075 switch (display_type) {
6076 case DT_NOGRAPHIC:
6077 break;
6078 #if defined(CONFIG_CURSES)
6079 case DT_CURSES:
6080 curses_display_init(ds, full_screen);
6081 break;
6082 #endif
6083 #if defined(CONFIG_SDL)
6084 case DT_SDL:
6085 sdl_display_init(ds, full_screen, no_frame);
6086 break;
6087 #elif defined(CONFIG_COCOA)
6088 case DT_SDL:
6089 cocoa_display_init(ds, full_screen);
6090 break;
6091 #endif
6092 case DT_VNC:
6093 vnc_display_init(ds);
6094 if (vnc_display_open(ds, vnc_display) < 0)
6095 exit(1);
6097 if (show_vnc_port) {
6098 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6100 break;
6101 default:
6102 break;
6104 dpy_resize(ds);
6106 dcl = ds->listeners;
6107 while (dcl != NULL) {
6108 if (dcl->dpy_refresh != NULL) {
6109 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6110 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6112 dcl = dcl->next;
6115 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6116 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6117 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6120 text_consoles_set_display(ds);
6122 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
6123 exit(1);
6125 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6126 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6127 gdbstub_dev);
6128 exit(1);
6131 qdev_machine_creation_done();
6133 if (rom_load_all() != 0) {
6134 fprintf(stderr, "rom loading failed\n");
6135 exit(1);
6138 qemu_system_reset();
6139 if (loadvm) {
6140 if (load_vmstate(cur_mon, loadvm) < 0) {
6141 autostart = 0;
6145 if (incoming) {
6146 qemu_start_incoming_migration(incoming);
6147 } else if (autostart) {
6148 vm_start();
6151 #ifndef _WIN32
6152 if (daemonize) {
6153 uint8_t status = 0;
6154 ssize_t len;
6156 again1:
6157 len = write(fds[1], &status, 1);
6158 if (len == -1 && (errno == EINTR))
6159 goto again1;
6161 if (len != 1)
6162 exit(1);
6164 if (chdir("/")) {
6165 perror("not able to chdir to /");
6166 exit(1);
6168 TFR(fd = qemu_open("/dev/null", O_RDWR));
6169 if (fd == -1)
6170 exit(1);
6173 if (run_as) {
6174 pwd = getpwnam(run_as);
6175 if (!pwd) {
6176 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6177 exit(1);
6181 if (chroot_dir) {
6182 if (chroot(chroot_dir) < 0) {
6183 fprintf(stderr, "chroot failed\n");
6184 exit(1);
6186 if (chdir("/")) {
6187 perror("not able to chdir to /");
6188 exit(1);
6192 if (run_as) {
6193 if (setgid(pwd->pw_gid) < 0) {
6194 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6195 exit(1);
6197 if (setuid(pwd->pw_uid) < 0) {
6198 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6199 exit(1);
6201 if (setuid(0) != -1) {
6202 fprintf(stderr, "Dropping privileges failed\n");
6203 exit(1);
6207 if (daemonize) {
6208 dup2(fd, 0);
6209 dup2(fd, 1);
6210 dup2(fd, 2);
6212 close(fd);
6214 #endif
6216 main_loop();
6217 quit_timers();
6218 net_cleanup();
6220 return 0;