centralize handling of -icount
[qemu/cris-port.git] / vl.c
blob793832856417146cb3d9862b85aaf61a063e7a5f
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"
161 #include "disas.h"
163 #include "exec-all.h"
165 #include "qemu_socket.h"
167 #include "slirp/libslirp.h"
169 #include "qemu-queue.h"
171 //#define DEBUG_NET
172 //#define DEBUG_SLIRP
174 #define DEFAULT_RAM_SIZE 128
176 #define MAX_VIRTIO_CONSOLES 1
178 static const char *data_dir;
179 const char *bios_name = NULL;
180 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
181 to store the VM snapshots */
182 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
183 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
184 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
185 DisplayType display_type = DT_DEFAULT;
186 const char* keyboard_layout = NULL;
187 ram_addr_t ram_size;
188 const char *mem_path = NULL;
189 #ifdef MAP_POPULATE
190 int mem_prealloc = 0; /* force preallocation of physical target memory */
191 #endif
192 int nb_nics;
193 NICInfo nd_table[MAX_NICS];
194 int vm_running;
195 int autostart;
196 static int rtc_utc = 1;
197 static int rtc_date_offset = -1; /* -1 means no change */
198 QEMUClock *rtc_clock;
199 int vga_interface_type = VGA_NONE;
200 #ifdef TARGET_SPARC
201 int graphic_width = 1024;
202 int graphic_height = 768;
203 int graphic_depth = 8;
204 #else
205 int graphic_width = 800;
206 int graphic_height = 600;
207 int graphic_depth = 15;
208 #endif
209 static int full_screen = 0;
210 #ifdef CONFIG_SDL
211 static int no_frame = 0;
212 #endif
213 int no_quit = 0;
214 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
215 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
216 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
217 #ifdef TARGET_I386
218 int win2k_install_hack = 0;
219 int rtc_td_hack = 0;
220 #endif
221 int usb_enabled = 0;
222 int singlestep = 0;
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 int no_hpet = 0;
230 int fd_bootchk = 1;
231 int no_reboot = 0;
232 int no_shutdown = 0;
233 int cursor_hide = 1;
234 int graphic_rotate = 0;
235 uint8_t irq0override = 1;
236 #ifndef _WIN32
237 int daemonize = 0;
238 #endif
239 const char *watchdog;
240 const char *option_rom[MAX_OPTION_ROMS];
241 int nb_option_roms;
242 int semihosting_enabled = 0;
243 #ifdef TARGET_ARM
244 int old_param = 0;
245 #endif
246 const char *qemu_name;
247 int alt_grab = 0;
248 int ctrl_grab = 0;
249 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
250 unsigned int nb_prom_envs = 0;
251 const char *prom_envs[MAX_PROM_ENVS];
252 #endif
253 int boot_menu;
255 int nb_numa_nodes;
256 uint64_t node_mem[MAX_NODES];
257 uint64_t node_cpumask[MAX_NODES];
259 static CPUState *cur_cpu;
260 static CPUState *next_cpu;
261 /* Conversion factor from emulated instructions to virtual clock ticks. */
262 static int icount_time_shift;
263 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
264 #define MAX_ICOUNT_SHIFT 10
265 /* Compensate for varying guest execution speed. */
266 static int64_t qemu_icount_bias;
267 static QEMUTimer *icount_rt_timer;
268 static QEMUTimer *icount_vm_timer;
269 static QEMUTimer *nographic_timer;
271 uint8_t qemu_uuid[16];
273 static QEMUBootSetHandler *boot_set_handler;
274 static void *boot_set_opaque;
276 #ifdef SIGRTMIN
277 #define SIG_IPI (SIGRTMIN+4)
278 #else
279 #define SIG_IPI SIGUSR1
280 #endif
282 static int default_serial = 1;
283 static int default_parallel = 1;
284 static int default_virtcon = 1;
285 static int default_monitor = 1;
286 static int default_vga = 1;
287 static int default_floppy = 1;
288 static int default_cdrom = 1;
289 static int default_sdcard = 1;
291 static struct {
292 const char *driver;
293 int *flag;
294 } default_list[] = {
295 { .driver = "isa-serial", .flag = &default_serial },
296 { .driver = "isa-parallel", .flag = &default_parallel },
297 { .driver = "isa-fdc", .flag = &default_floppy },
298 { .driver = "ide-drive", .flag = &default_cdrom },
299 { .driver = "virtio-serial-pci", .flag = &default_virtcon },
300 { .driver = "virtio-serial-s390", .flag = &default_virtcon },
301 { .driver = "virtio-serial", .flag = &default_virtcon },
302 { .driver = "VGA", .flag = &default_vga },
303 { .driver = "cirrus-vga", .flag = &default_vga },
304 { .driver = "vmware-svga", .flag = &default_vga },
307 static int default_driver_check(QemuOpts *opts, void *opaque)
309 const char *driver = qemu_opt_get(opts, "driver");
310 int i;
312 if (!driver)
313 return 0;
314 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
315 if (strcmp(default_list[i].driver, driver) != 0)
316 continue;
317 *(default_list[i].flag) = 0;
319 return 0;
322 /***********************************************************/
323 /* x86 ISA bus support */
325 target_phys_addr_t isa_mem_base = 0;
326 PicState2 *isa_pic;
328 /***********************************************************/
329 void hw_error(const char *fmt, ...)
331 va_list ap;
332 CPUState *env;
334 va_start(ap, fmt);
335 fprintf(stderr, "qemu: hardware error: ");
336 vfprintf(stderr, fmt, ap);
337 fprintf(stderr, "\n");
338 for(env = first_cpu; env != NULL; env = env->next_cpu) {
339 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
340 #ifdef TARGET_I386
341 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
342 #else
343 cpu_dump_state(env, stderr, fprintf, 0);
344 #endif
346 va_end(ap);
347 abort();
350 static void set_proc_name(const char *s)
352 #if defined(__linux__) && defined(PR_SET_NAME)
353 char name[16];
354 if (!s)
355 return;
356 name[sizeof(name) - 1] = 0;
357 strncpy(name, s, sizeof(name));
358 /* Could rewrite argv[0] too, but that's a bit more complicated.
359 This simple way is enough for `top'. */
360 prctl(PR_SET_NAME, name);
361 #endif
364 /***************/
365 /* ballooning */
367 static QEMUBalloonEvent *qemu_balloon_event;
368 void *qemu_balloon_event_opaque;
370 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
372 qemu_balloon_event = func;
373 qemu_balloon_event_opaque = opaque;
376 int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
378 if (qemu_balloon_event) {
379 qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
380 return 1;
381 } else {
382 return 0;
386 int qemu_balloon_status(MonitorCompletion cb, void *opaque)
388 if (qemu_balloon_event) {
389 qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
390 return 1;
391 } else {
392 return 0;
397 /***********************************************************/
398 /* real time host monotonic timer */
400 /* compute with 96 bit intermediate result: (a*b)/c */
401 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
403 union {
404 uint64_t ll;
405 struct {
406 #ifdef HOST_WORDS_BIGENDIAN
407 uint32_t high, low;
408 #else
409 uint32_t low, high;
410 #endif
411 } l;
412 } u, res;
413 uint64_t rl, rh;
415 u.ll = a;
416 rl = (uint64_t)u.l.low * (uint64_t)b;
417 rh = (uint64_t)u.l.high * (uint64_t)b;
418 rh += (rl >> 32);
419 res.l.high = rh / c;
420 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
421 return res.ll;
424 static int64_t get_clock_realtime(void)
426 struct timeval tv;
428 gettimeofday(&tv, NULL);
429 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
432 #ifdef WIN32
434 static int64_t clock_freq;
436 static void init_get_clock(void)
438 LARGE_INTEGER freq;
439 int ret;
440 ret = QueryPerformanceFrequency(&freq);
441 if (ret == 0) {
442 fprintf(stderr, "Could not calibrate ticks\n");
443 exit(1);
445 clock_freq = freq.QuadPart;
448 static int64_t get_clock(void)
450 LARGE_INTEGER ti;
451 QueryPerformanceCounter(&ti);
452 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
455 #else
457 static int use_rt_clock;
459 static void init_get_clock(void)
461 use_rt_clock = 0;
462 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
463 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
465 struct timespec ts;
466 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
467 use_rt_clock = 1;
470 #endif
473 static int64_t get_clock(void)
475 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
476 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
477 if (use_rt_clock) {
478 struct timespec ts;
479 clock_gettime(CLOCK_MONOTONIC, &ts);
480 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
481 } else
482 #endif
484 /* XXX: using gettimeofday leads to problems if the date
485 changes, so it should be avoided. */
486 return get_clock_realtime();
489 #endif
491 /* Return the virtual CPU time, based on the instruction counter. */
492 static int64_t cpu_get_icount(void)
494 int64_t icount;
495 CPUState *env = cpu_single_env;;
496 icount = qemu_icount;
497 if (env) {
498 if (!can_do_io(env))
499 fprintf(stderr, "Bad clock read\n");
500 icount -= (env->icount_decr.u16.low + env->icount_extra);
502 return qemu_icount_bias + (icount << icount_time_shift);
505 /***********************************************************/
506 /* guest cycle counter */
508 typedef struct TimersState {
509 int64_t cpu_ticks_prev;
510 int64_t cpu_ticks_offset;
511 int64_t cpu_clock_offset;
512 int32_t cpu_ticks_enabled;
513 int64_t dummy;
514 } TimersState;
516 TimersState timers_state;
518 /* return the host CPU cycle counter and handle stop/restart */
519 int64_t cpu_get_ticks(void)
521 if (use_icount) {
522 return cpu_get_icount();
524 if (!timers_state.cpu_ticks_enabled) {
525 return timers_state.cpu_ticks_offset;
526 } else {
527 int64_t ticks;
528 ticks = cpu_get_real_ticks();
529 if (timers_state.cpu_ticks_prev > ticks) {
530 /* Note: non increasing ticks may happen if the host uses
531 software suspend */
532 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
534 timers_state.cpu_ticks_prev = ticks;
535 return ticks + timers_state.cpu_ticks_offset;
539 /* return the host CPU monotonic timer and handle stop/restart */
540 static int64_t cpu_get_clock(void)
542 int64_t ti;
543 if (!timers_state.cpu_ticks_enabled) {
544 return timers_state.cpu_clock_offset;
545 } else {
546 ti = get_clock();
547 return ti + timers_state.cpu_clock_offset;
551 /* enable cpu_get_ticks() */
552 void cpu_enable_ticks(void)
554 if (!timers_state.cpu_ticks_enabled) {
555 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
556 timers_state.cpu_clock_offset -= get_clock();
557 timers_state.cpu_ticks_enabled = 1;
561 /* disable cpu_get_ticks() : the clock is stopped. You must not call
562 cpu_get_ticks() after that. */
563 void cpu_disable_ticks(void)
565 if (timers_state.cpu_ticks_enabled) {
566 timers_state.cpu_ticks_offset = cpu_get_ticks();
567 timers_state.cpu_clock_offset = cpu_get_clock();
568 timers_state.cpu_ticks_enabled = 0;
572 /***********************************************************/
573 /* timers */
575 #define QEMU_CLOCK_REALTIME 0
576 #define QEMU_CLOCK_VIRTUAL 1
577 #define QEMU_CLOCK_HOST 2
579 struct QEMUClock {
580 int type;
581 int enabled;
582 /* XXX: add frequency */
585 struct QEMUTimer {
586 QEMUClock *clock;
587 int64_t expire_time;
588 QEMUTimerCB *cb;
589 void *opaque;
590 struct QEMUTimer *next;
593 struct qemu_alarm_timer {
594 char const *name;
595 int (*start)(struct qemu_alarm_timer *t);
596 void (*stop)(struct qemu_alarm_timer *t);
597 void (*rearm)(struct qemu_alarm_timer *t);
598 void *priv;
600 char expired;
601 char pending;
604 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
606 return !!t->rearm;
609 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
611 if (!alarm_has_dynticks(t))
612 return;
614 t->rearm(t);
617 /* TODO: MIN_TIMER_REARM_US should be optimized */
618 #define MIN_TIMER_REARM_US 250
620 static struct qemu_alarm_timer *alarm_timer;
622 #ifdef _WIN32
624 struct qemu_alarm_win32 {
625 MMRESULT timerId;
626 unsigned int period;
627 } alarm_win32_data = {0, 0};
629 static int win32_start_timer(struct qemu_alarm_timer *t);
630 static void win32_stop_timer(struct qemu_alarm_timer *t);
631 static void win32_rearm_timer(struct qemu_alarm_timer *t);
633 #else
635 static int unix_start_timer(struct qemu_alarm_timer *t);
636 static void unix_stop_timer(struct qemu_alarm_timer *t);
638 #ifdef __linux__
640 static int dynticks_start_timer(struct qemu_alarm_timer *t);
641 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
642 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
644 static int hpet_start_timer(struct qemu_alarm_timer *t);
645 static void hpet_stop_timer(struct qemu_alarm_timer *t);
647 static int rtc_start_timer(struct qemu_alarm_timer *t);
648 static void rtc_stop_timer(struct qemu_alarm_timer *t);
650 #endif /* __linux__ */
652 #endif /* _WIN32 */
654 /* Correlation between real and virtual time is always going to be
655 fairly approximate, so ignore small variation.
656 When the guest is idle real and virtual time will be aligned in
657 the IO wait loop. */
658 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
660 static void icount_adjust(void)
662 int64_t cur_time;
663 int64_t cur_icount;
664 int64_t delta;
665 static int64_t last_delta;
666 /* If the VM is not running, then do nothing. */
667 if (!vm_running)
668 return;
670 cur_time = cpu_get_clock();
671 cur_icount = qemu_get_clock(vm_clock);
672 delta = cur_icount - cur_time;
673 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
674 if (delta > 0
675 && last_delta + ICOUNT_WOBBLE < delta * 2
676 && icount_time_shift > 0) {
677 /* The guest is getting too far ahead. Slow time down. */
678 icount_time_shift--;
680 if (delta < 0
681 && last_delta - ICOUNT_WOBBLE > delta * 2
682 && icount_time_shift < MAX_ICOUNT_SHIFT) {
683 /* The guest is getting too far behind. Speed time up. */
684 icount_time_shift++;
686 last_delta = delta;
687 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
690 static void icount_adjust_rt(void * opaque)
692 qemu_mod_timer(icount_rt_timer,
693 qemu_get_clock(rt_clock) + 1000);
694 icount_adjust();
697 static void icount_adjust_vm(void * opaque)
699 qemu_mod_timer(icount_vm_timer,
700 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
701 icount_adjust();
704 static void configure_icount(const char *option)
706 if (!option)
707 return;
709 if (strcmp(option, "auto") != 0) {
710 icount_time_shift = strtol(option, NULL, 0);
711 use_icount = 1;
712 return;
715 use_icount = 2;
717 /* 125MIPS seems a reasonable initial guess at the guest speed.
718 It will be corrected fairly quickly anyway. */
719 icount_time_shift = 3;
721 /* Have both realtime and virtual time triggers for speed adjustment.
722 The realtime trigger catches emulated time passing too slowly,
723 the virtual time trigger catches emulated time passing too fast.
724 Realtime triggers occur even when idle, so use them less frequently
725 than VM triggers. */
726 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
727 qemu_mod_timer(icount_rt_timer,
728 qemu_get_clock(rt_clock) + 1000);
729 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
730 qemu_mod_timer(icount_vm_timer,
731 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
734 static struct qemu_alarm_timer alarm_timers[] = {
735 #ifndef _WIN32
736 #ifdef __linux__
737 {"dynticks", dynticks_start_timer,
738 dynticks_stop_timer, dynticks_rearm_timer, NULL},
739 /* HPET - if available - is preferred */
740 {"hpet", hpet_start_timer, hpet_stop_timer, NULL, NULL},
741 /* ...otherwise try RTC */
742 {"rtc", rtc_start_timer, rtc_stop_timer, NULL, NULL},
743 #endif
744 {"unix", unix_start_timer, unix_stop_timer, NULL, NULL},
745 #else
746 {"dynticks", win32_start_timer,
747 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
748 {"win32", win32_start_timer,
749 win32_stop_timer, NULL, &alarm_win32_data},
750 #endif
751 {NULL, }
754 static void show_available_alarms(void)
756 int i;
758 printf("Available alarm timers, in order of precedence:\n");
759 for (i = 0; alarm_timers[i].name; i++)
760 printf("%s\n", alarm_timers[i].name);
763 static void configure_alarms(char const *opt)
765 int i;
766 int cur = 0;
767 int count = ARRAY_SIZE(alarm_timers) - 1;
768 char *arg;
769 char *name;
770 struct qemu_alarm_timer tmp;
772 if (!strcmp(opt, "?")) {
773 show_available_alarms();
774 exit(0);
777 arg = qemu_strdup(opt);
779 /* Reorder the array */
780 name = strtok(arg, ",");
781 while (name) {
782 for (i = 0; i < count && alarm_timers[i].name; i++) {
783 if (!strcmp(alarm_timers[i].name, name))
784 break;
787 if (i == count) {
788 fprintf(stderr, "Unknown clock %s\n", name);
789 goto next;
792 if (i < cur)
793 /* Ignore */
794 goto next;
796 /* Swap */
797 tmp = alarm_timers[i];
798 alarm_timers[i] = alarm_timers[cur];
799 alarm_timers[cur] = tmp;
801 cur++;
802 next:
803 name = strtok(NULL, ",");
806 qemu_free(arg);
808 if (cur) {
809 /* Disable remaining timers */
810 for (i = cur; i < count; i++)
811 alarm_timers[i].name = NULL;
812 } else {
813 show_available_alarms();
814 exit(1);
818 #define QEMU_NUM_CLOCKS 3
820 QEMUClock *rt_clock;
821 QEMUClock *vm_clock;
822 QEMUClock *host_clock;
824 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
826 static QEMUClock *qemu_new_clock(int type)
828 QEMUClock *clock;
829 clock = qemu_mallocz(sizeof(QEMUClock));
830 clock->type = type;
831 clock->enabled = 1;
832 return clock;
835 static void qemu_clock_enable(QEMUClock *clock, int enabled)
837 clock->enabled = enabled;
840 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
842 QEMUTimer *ts;
844 ts = qemu_mallocz(sizeof(QEMUTimer));
845 ts->clock = clock;
846 ts->cb = cb;
847 ts->opaque = opaque;
848 return ts;
851 void qemu_free_timer(QEMUTimer *ts)
853 qemu_free(ts);
856 /* stop a timer, but do not dealloc it */
857 void qemu_del_timer(QEMUTimer *ts)
859 QEMUTimer **pt, *t;
861 /* NOTE: this code must be signal safe because
862 qemu_timer_expired() can be called from a signal. */
863 pt = &active_timers[ts->clock->type];
864 for(;;) {
865 t = *pt;
866 if (!t)
867 break;
868 if (t == ts) {
869 *pt = t->next;
870 break;
872 pt = &t->next;
876 /* modify the current timer so that it will be fired when current_time
877 >= expire_time. The corresponding callback will be called. */
878 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
880 QEMUTimer **pt, *t;
882 qemu_del_timer(ts);
884 /* add the timer in the sorted list */
885 /* NOTE: this code must be signal safe because
886 qemu_timer_expired() can be called from a signal. */
887 pt = &active_timers[ts->clock->type];
888 for(;;) {
889 t = *pt;
890 if (!t)
891 break;
892 if (t->expire_time > expire_time)
893 break;
894 pt = &t->next;
896 ts->expire_time = expire_time;
897 ts->next = *pt;
898 *pt = ts;
900 /* Rearm if necessary */
901 if (pt == &active_timers[ts->clock->type]) {
902 if (!alarm_timer->pending) {
903 qemu_rearm_alarm_timer(alarm_timer);
905 /* Interrupt execution to force deadline recalculation. */
906 if (use_icount)
907 qemu_notify_event();
911 int qemu_timer_pending(QEMUTimer *ts)
913 QEMUTimer *t;
914 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
915 if (t == ts)
916 return 1;
918 return 0;
921 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
923 if (!timer_head)
924 return 0;
925 return (timer_head->expire_time <= current_time);
928 static void qemu_run_timers(QEMUClock *clock)
930 QEMUTimer **ptimer_head, *ts;
931 int64_t current_time;
933 if (!clock->enabled)
934 return;
936 current_time = qemu_get_clock (clock);
937 ptimer_head = &active_timers[clock->type];
938 for(;;) {
939 ts = *ptimer_head;
940 if (!ts || ts->expire_time > current_time)
941 break;
942 /* remove timer from the list before calling the callback */
943 *ptimer_head = ts->next;
944 ts->next = NULL;
946 /* run the callback (the timer list can be modified) */
947 ts->cb(ts->opaque);
951 int64_t qemu_get_clock(QEMUClock *clock)
953 switch(clock->type) {
954 case QEMU_CLOCK_REALTIME:
955 return get_clock() / 1000000;
956 default:
957 case QEMU_CLOCK_VIRTUAL:
958 if (use_icount) {
959 return cpu_get_icount();
960 } else {
961 return cpu_get_clock();
963 case QEMU_CLOCK_HOST:
964 return get_clock_realtime();
968 int64_t qemu_get_clock_ns(QEMUClock *clock)
970 switch(clock->type) {
971 case QEMU_CLOCK_REALTIME:
972 return get_clock();
973 default:
974 case QEMU_CLOCK_VIRTUAL:
975 if (use_icount) {
976 return cpu_get_icount();
977 } else {
978 return cpu_get_clock();
980 case QEMU_CLOCK_HOST:
981 return get_clock_realtime();
985 static void init_clocks(void)
987 init_get_clock();
988 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
989 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
990 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
992 rtc_clock = host_clock;
995 /* save a timer */
996 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
998 uint64_t expire_time;
1000 if (qemu_timer_pending(ts)) {
1001 expire_time = ts->expire_time;
1002 } else {
1003 expire_time = -1;
1005 qemu_put_be64(f, expire_time);
1008 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1010 uint64_t expire_time;
1012 expire_time = qemu_get_be64(f);
1013 if (expire_time != -1) {
1014 qemu_mod_timer(ts, expire_time);
1015 } else {
1016 qemu_del_timer(ts);
1020 static const VMStateDescription vmstate_timers = {
1021 .name = "timer",
1022 .version_id = 2,
1023 .minimum_version_id = 1,
1024 .minimum_version_id_old = 1,
1025 .fields = (VMStateField []) {
1026 VMSTATE_INT64(cpu_ticks_offset, TimersState),
1027 VMSTATE_INT64(dummy, TimersState),
1028 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1029 VMSTATE_END_OF_LIST()
1033 static void qemu_run_all_timers(void)
1035 /* rearm timer, if not periodic */
1036 if (alarm_timer->expired) {
1037 alarm_timer->expired = 0;
1038 qemu_rearm_alarm_timer(alarm_timer);
1041 alarm_timer->pending = 0;
1043 /* vm time timers */
1044 if (vm_running) {
1045 qemu_run_timers(vm_clock);
1048 qemu_run_timers(rt_clock);
1049 qemu_run_timers(host_clock);
1052 #ifdef _WIN32
1053 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1054 DWORD_PTR dwUser, DWORD_PTR dw1,
1055 DWORD_PTR dw2)
1056 #else
1057 static void host_alarm_handler(int host_signum)
1058 #endif
1060 struct qemu_alarm_timer *t = alarm_timer;
1061 if (!t)
1062 return;
1064 #if 0
1065 #define DISP_FREQ 1000
1067 static int64_t delta_min = INT64_MAX;
1068 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1069 static int count;
1070 ti = qemu_get_clock(vm_clock);
1071 if (last_clock != 0) {
1072 delta = ti - last_clock;
1073 if (delta < delta_min)
1074 delta_min = delta;
1075 if (delta > delta_max)
1076 delta_max = delta;
1077 delta_cum += delta;
1078 if (++count == DISP_FREQ) {
1079 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1080 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1081 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1082 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1083 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1084 count = 0;
1085 delta_min = INT64_MAX;
1086 delta_max = 0;
1087 delta_cum = 0;
1090 last_clock = ti;
1092 #endif
1093 if (alarm_has_dynticks(t) ||
1094 (!use_icount &&
1095 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1096 qemu_get_clock(vm_clock))) ||
1097 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1098 qemu_get_clock(rt_clock)) ||
1099 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1100 qemu_get_clock(host_clock))) {
1102 t->expired = alarm_has_dynticks(t);
1103 t->pending = 1;
1104 qemu_notify_event();
1108 static int64_t qemu_next_deadline(void)
1110 /* To avoid problems with overflow limit this to 2^32. */
1111 int64_t delta = INT32_MAX;
1113 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1114 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1115 qemu_get_clock(vm_clock);
1117 if (active_timers[QEMU_CLOCK_HOST]) {
1118 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1119 qemu_get_clock(host_clock);
1120 if (hdelta < delta)
1121 delta = hdelta;
1124 if (delta < 0)
1125 delta = 0;
1127 return delta;
1130 #if defined(__linux__)
1131 static uint64_t qemu_next_deadline_dyntick(void)
1133 int64_t delta;
1134 int64_t rtdelta;
1136 if (use_icount)
1137 delta = INT32_MAX;
1138 else
1139 delta = (qemu_next_deadline() + 999) / 1000;
1141 if (active_timers[QEMU_CLOCK_REALTIME]) {
1142 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1143 qemu_get_clock(rt_clock))*1000;
1144 if (rtdelta < delta)
1145 delta = rtdelta;
1148 if (delta < MIN_TIMER_REARM_US)
1149 delta = MIN_TIMER_REARM_US;
1151 return delta;
1153 #endif
1155 #ifndef _WIN32
1157 /* Sets a specific flag */
1158 static int fcntl_setfl(int fd, int flag)
1160 int flags;
1162 flags = fcntl(fd, F_GETFL);
1163 if (flags == -1)
1164 return -errno;
1166 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1167 return -errno;
1169 return 0;
1172 #if defined(__linux__)
1174 #define RTC_FREQ 1024
1176 static void enable_sigio_timer(int fd)
1178 struct sigaction act;
1180 /* timer signal */
1181 sigfillset(&act.sa_mask);
1182 act.sa_flags = 0;
1183 act.sa_handler = host_alarm_handler;
1185 sigaction(SIGIO, &act, NULL);
1186 fcntl_setfl(fd, O_ASYNC);
1187 fcntl(fd, F_SETOWN, getpid());
1190 static int hpet_start_timer(struct qemu_alarm_timer *t)
1192 struct hpet_info info;
1193 int r, fd;
1195 fd = qemu_open("/dev/hpet", O_RDONLY);
1196 if (fd < 0)
1197 return -1;
1199 /* Set frequency */
1200 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1201 if (r < 0) {
1202 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1203 "error, but for better emulation accuracy type:\n"
1204 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1205 goto fail;
1208 /* Check capabilities */
1209 r = ioctl(fd, HPET_INFO, &info);
1210 if (r < 0)
1211 goto fail;
1213 /* Enable periodic mode */
1214 r = ioctl(fd, HPET_EPI, 0);
1215 if (info.hi_flags && (r < 0))
1216 goto fail;
1218 /* Enable interrupt */
1219 r = ioctl(fd, HPET_IE_ON, 0);
1220 if (r < 0)
1221 goto fail;
1223 enable_sigio_timer(fd);
1224 t->priv = (void *)(long)fd;
1226 return 0;
1227 fail:
1228 close(fd);
1229 return -1;
1232 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1234 int fd = (long)t->priv;
1236 close(fd);
1239 static int rtc_start_timer(struct qemu_alarm_timer *t)
1241 int rtc_fd;
1242 unsigned long current_rtc_freq = 0;
1244 TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
1245 if (rtc_fd < 0)
1246 return -1;
1247 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1248 if (current_rtc_freq != RTC_FREQ &&
1249 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1250 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1251 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1252 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1253 goto fail;
1255 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1256 fail:
1257 close(rtc_fd);
1258 return -1;
1261 enable_sigio_timer(rtc_fd);
1263 t->priv = (void *)(long)rtc_fd;
1265 return 0;
1268 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1270 int rtc_fd = (long)t->priv;
1272 close(rtc_fd);
1275 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1277 struct sigevent ev;
1278 timer_t host_timer;
1279 struct sigaction act;
1281 sigfillset(&act.sa_mask);
1282 act.sa_flags = 0;
1283 act.sa_handler = host_alarm_handler;
1285 sigaction(SIGALRM, &act, NULL);
1288 * Initialize ev struct to 0 to avoid valgrind complaining
1289 * about uninitialized data in timer_create call
1291 memset(&ev, 0, sizeof(ev));
1292 ev.sigev_value.sival_int = 0;
1293 ev.sigev_notify = SIGEV_SIGNAL;
1294 ev.sigev_signo = SIGALRM;
1296 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1297 perror("timer_create");
1299 /* disable dynticks */
1300 fprintf(stderr, "Dynamic Ticks disabled\n");
1302 return -1;
1305 t->priv = (void *)(long)host_timer;
1307 return 0;
1310 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1312 timer_t host_timer = (timer_t)(long)t->priv;
1314 timer_delete(host_timer);
1317 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1319 timer_t host_timer = (timer_t)(long)t->priv;
1320 struct itimerspec timeout;
1321 int64_t nearest_delta_us = INT64_MAX;
1322 int64_t current_us;
1324 assert(alarm_has_dynticks(t));
1325 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1326 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1327 !active_timers[QEMU_CLOCK_HOST])
1328 return;
1330 nearest_delta_us = qemu_next_deadline_dyntick();
1332 /* check whether a timer is already running */
1333 if (timer_gettime(host_timer, &timeout)) {
1334 perror("gettime");
1335 fprintf(stderr, "Internal timer error: aborting\n");
1336 exit(1);
1338 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1339 if (current_us && current_us <= nearest_delta_us)
1340 return;
1342 timeout.it_interval.tv_sec = 0;
1343 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1344 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1345 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1346 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1347 perror("settime");
1348 fprintf(stderr, "Internal timer error: aborting\n");
1349 exit(1);
1353 #endif /* defined(__linux__) */
1355 static int unix_start_timer(struct qemu_alarm_timer *t)
1357 struct sigaction act;
1358 struct itimerval itv;
1359 int err;
1361 /* timer signal */
1362 sigfillset(&act.sa_mask);
1363 act.sa_flags = 0;
1364 act.sa_handler = host_alarm_handler;
1366 sigaction(SIGALRM, &act, NULL);
1368 itv.it_interval.tv_sec = 0;
1369 /* for i386 kernel 2.6 to get 1 ms */
1370 itv.it_interval.tv_usec = 999;
1371 itv.it_value.tv_sec = 0;
1372 itv.it_value.tv_usec = 10 * 1000;
1374 err = setitimer(ITIMER_REAL, &itv, NULL);
1375 if (err)
1376 return -1;
1378 return 0;
1381 static void unix_stop_timer(struct qemu_alarm_timer *t)
1383 struct itimerval itv;
1385 memset(&itv, 0, sizeof(itv));
1386 setitimer(ITIMER_REAL, &itv, NULL);
1389 #endif /* !defined(_WIN32) */
1392 #ifdef _WIN32
1394 static int win32_start_timer(struct qemu_alarm_timer *t)
1396 TIMECAPS tc;
1397 struct qemu_alarm_win32 *data = t->priv;
1398 UINT flags;
1400 memset(&tc, 0, sizeof(tc));
1401 timeGetDevCaps(&tc, sizeof(tc));
1403 data->period = tc.wPeriodMin;
1404 timeBeginPeriod(data->period);
1406 flags = TIME_CALLBACK_FUNCTION;
1407 if (alarm_has_dynticks(t))
1408 flags |= TIME_ONESHOT;
1409 else
1410 flags |= TIME_PERIODIC;
1412 data->timerId = timeSetEvent(1, // interval (ms)
1413 data->period, // resolution
1414 host_alarm_handler, // function
1415 (DWORD)t, // parameter
1416 flags);
1418 if (!data->timerId) {
1419 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1420 GetLastError());
1421 timeEndPeriod(data->period);
1422 return -1;
1425 return 0;
1428 static void win32_stop_timer(struct qemu_alarm_timer *t)
1430 struct qemu_alarm_win32 *data = t->priv;
1432 timeKillEvent(data->timerId);
1433 timeEndPeriod(data->period);
1436 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1438 struct qemu_alarm_win32 *data = t->priv;
1440 assert(alarm_has_dynticks(t));
1441 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1442 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1443 !active_timers[QEMU_CLOCK_HOST])
1444 return;
1446 timeKillEvent(data->timerId);
1448 data->timerId = timeSetEvent(1,
1449 data->period,
1450 host_alarm_handler,
1451 (DWORD)t,
1452 TIME_ONESHOT | TIME_CALLBACK_FUNCTION);
1454 if (!data->timerId) {
1455 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1456 GetLastError());
1458 timeEndPeriod(data->period);
1459 exit(1);
1463 #endif /* _WIN32 */
1465 static void alarm_timer_on_change_state_rearm(void *opaque, int running, int reason)
1467 if (running)
1468 qemu_rearm_alarm_timer((struct qemu_alarm_timer *) opaque);
1471 static int init_timer_alarm(void)
1473 struct qemu_alarm_timer *t = NULL;
1474 int i, err = -1;
1476 for (i = 0; alarm_timers[i].name; i++) {
1477 t = &alarm_timers[i];
1479 err = t->start(t);
1480 if (!err)
1481 break;
1484 if (err) {
1485 err = -ENOENT;
1486 goto fail;
1489 /* first event is at time 0 */
1490 t->pending = 1;
1491 alarm_timer = t;
1492 qemu_add_vm_change_state_handler(alarm_timer_on_change_state_rearm, t);
1494 return 0;
1496 fail:
1497 return err;
1500 static void quit_timers(void)
1502 struct qemu_alarm_timer *t = alarm_timer;
1503 alarm_timer = NULL;
1504 t->stop(t);
1507 /***********************************************************/
1508 /* host time/date access */
1509 void qemu_get_timedate(struct tm *tm, int offset)
1511 time_t ti;
1512 struct tm *ret;
1514 time(&ti);
1515 ti += offset;
1516 if (rtc_date_offset == -1) {
1517 if (rtc_utc)
1518 ret = gmtime(&ti);
1519 else
1520 ret = localtime(&ti);
1521 } else {
1522 ti -= rtc_date_offset;
1523 ret = gmtime(&ti);
1526 memcpy(tm, ret, sizeof(struct tm));
1529 int qemu_timedate_diff(struct tm *tm)
1531 time_t seconds;
1533 if (rtc_date_offset == -1)
1534 if (rtc_utc)
1535 seconds = mktimegm(tm);
1536 else
1537 seconds = mktime(tm);
1538 else
1539 seconds = mktimegm(tm) + rtc_date_offset;
1541 return seconds - time(NULL);
1544 void rtc_change_mon_event(struct tm *tm)
1546 QObject *data;
1548 data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
1549 monitor_protocol_event(QEVENT_RTC_CHANGE, data);
1550 qobject_decref(data);
1553 static void configure_rtc_date_offset(const char *startdate, int legacy)
1555 time_t rtc_start_date;
1556 struct tm tm;
1558 if (!strcmp(startdate, "now") && legacy) {
1559 rtc_date_offset = -1;
1560 } else {
1561 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1562 &tm.tm_year,
1563 &tm.tm_mon,
1564 &tm.tm_mday,
1565 &tm.tm_hour,
1566 &tm.tm_min,
1567 &tm.tm_sec) == 6) {
1568 /* OK */
1569 } else if (sscanf(startdate, "%d-%d-%d",
1570 &tm.tm_year,
1571 &tm.tm_mon,
1572 &tm.tm_mday) == 3) {
1573 tm.tm_hour = 0;
1574 tm.tm_min = 0;
1575 tm.tm_sec = 0;
1576 } else {
1577 goto date_fail;
1579 tm.tm_year -= 1900;
1580 tm.tm_mon--;
1581 rtc_start_date = mktimegm(&tm);
1582 if (rtc_start_date == -1) {
1583 date_fail:
1584 fprintf(stderr, "Invalid date format. Valid formats are:\n"
1585 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1586 exit(1);
1588 rtc_date_offset = time(NULL) - rtc_start_date;
1592 static void configure_rtc(QemuOpts *opts)
1594 const char *value;
1596 value = qemu_opt_get(opts, "base");
1597 if (value) {
1598 if (!strcmp(value, "utc")) {
1599 rtc_utc = 1;
1600 } else if (!strcmp(value, "localtime")) {
1601 rtc_utc = 0;
1602 } else {
1603 configure_rtc_date_offset(value, 0);
1606 value = qemu_opt_get(opts, "clock");
1607 if (value) {
1608 if (!strcmp(value, "host")) {
1609 rtc_clock = host_clock;
1610 } else if (!strcmp(value, "vm")) {
1611 rtc_clock = vm_clock;
1612 } else {
1613 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1614 exit(1);
1617 #ifdef CONFIG_TARGET_I386
1618 value = qemu_opt_get(opts, "driftfix");
1619 if (value) {
1620 if (!strcmp(buf, "slew")) {
1621 rtc_td_hack = 1;
1622 } else if (!strcmp(buf, "none")) {
1623 rtc_td_hack = 0;
1624 } else {
1625 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1626 exit(1);
1629 #endif
1632 #ifdef _WIN32
1633 static void socket_cleanup(void)
1635 WSACleanup();
1638 static int socket_init(void)
1640 WSADATA Data;
1641 int ret, err;
1643 ret = WSAStartup(MAKEWORD(2,2), &Data);
1644 if (ret != 0) {
1645 err = WSAGetLastError();
1646 fprintf(stderr, "WSAStartup: %d\n", err);
1647 return -1;
1649 atexit(socket_cleanup);
1650 return 0;
1652 #endif
1654 /***********************************************************/
1655 /* Bluetooth support */
1656 static int nb_hcis;
1657 static int cur_hci;
1658 static struct HCIInfo *hci_table[MAX_NICS];
1660 static struct bt_vlan_s {
1661 struct bt_scatternet_s net;
1662 int id;
1663 struct bt_vlan_s *next;
1664 } *first_bt_vlan;
1666 /* find or alloc a new bluetooth "VLAN" */
1667 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1669 struct bt_vlan_s **pvlan, *vlan;
1670 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1671 if (vlan->id == id)
1672 return &vlan->net;
1674 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1675 vlan->id = id;
1676 pvlan = &first_bt_vlan;
1677 while (*pvlan != NULL)
1678 pvlan = &(*pvlan)->next;
1679 *pvlan = vlan;
1680 return &vlan->net;
1683 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1687 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1689 return -ENOTSUP;
1692 static struct HCIInfo null_hci = {
1693 .cmd_send = null_hci_send,
1694 .sco_send = null_hci_send,
1695 .acl_send = null_hci_send,
1696 .bdaddr_set = null_hci_addr_set,
1699 struct HCIInfo *qemu_next_hci(void)
1701 if (cur_hci == nb_hcis)
1702 return &null_hci;
1704 return hci_table[cur_hci++];
1707 static struct HCIInfo *hci_init(const char *str)
1709 char *endp;
1710 struct bt_scatternet_s *vlan = 0;
1712 if (!strcmp(str, "null"))
1713 /* null */
1714 return &null_hci;
1715 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1716 /* host[:hciN] */
1717 return bt_host_hci(str[4] ? str + 5 : "hci0");
1718 else if (!strncmp(str, "hci", 3)) {
1719 /* hci[,vlan=n] */
1720 if (str[3]) {
1721 if (!strncmp(str + 3, ",vlan=", 6)) {
1722 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1723 if (*endp)
1724 vlan = 0;
1726 } else
1727 vlan = qemu_find_bt_vlan(0);
1728 if (vlan)
1729 return bt_new_hci(vlan);
1732 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1734 return 0;
1737 static int bt_hci_parse(const char *str)
1739 struct HCIInfo *hci;
1740 bdaddr_t bdaddr;
1742 if (nb_hcis >= MAX_NICS) {
1743 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1744 return -1;
1747 hci = hci_init(str);
1748 if (!hci)
1749 return -1;
1751 bdaddr.b[0] = 0x52;
1752 bdaddr.b[1] = 0x54;
1753 bdaddr.b[2] = 0x00;
1754 bdaddr.b[3] = 0x12;
1755 bdaddr.b[4] = 0x34;
1756 bdaddr.b[5] = 0x56 + nb_hcis;
1757 hci->bdaddr_set(hci, bdaddr.b);
1759 hci_table[nb_hcis++] = hci;
1761 return 0;
1764 static void bt_vhci_add(int vlan_id)
1766 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1768 if (!vlan->slave)
1769 fprintf(stderr, "qemu: warning: adding a VHCI to "
1770 "an empty scatternet %i\n", vlan_id);
1772 bt_vhci_init(bt_new_hci(vlan));
1775 static struct bt_device_s *bt_device_add(const char *opt)
1777 struct bt_scatternet_s *vlan;
1778 int vlan_id = 0;
1779 char *endp = strstr(opt, ",vlan=");
1780 int len = (endp ? endp - opt : strlen(opt)) + 1;
1781 char devname[10];
1783 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1785 if (endp) {
1786 vlan_id = strtol(endp + 6, &endp, 0);
1787 if (*endp) {
1788 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1789 return 0;
1793 vlan = qemu_find_bt_vlan(vlan_id);
1795 if (!vlan->slave)
1796 fprintf(stderr, "qemu: warning: adding a slave device to "
1797 "an empty scatternet %i\n", vlan_id);
1799 if (!strcmp(devname, "keyboard"))
1800 return bt_keyboard_init(vlan);
1802 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1803 return 0;
1806 static int bt_parse(const char *opt)
1808 const char *endp, *p;
1809 int vlan;
1811 if (strstart(opt, "hci", &endp)) {
1812 if (!*endp || *endp == ',') {
1813 if (*endp)
1814 if (!strstart(endp, ",vlan=", 0))
1815 opt = endp + 1;
1817 return bt_hci_parse(opt);
1819 } else if (strstart(opt, "vhci", &endp)) {
1820 if (!*endp || *endp == ',') {
1821 if (*endp) {
1822 if (strstart(endp, ",vlan=", &p)) {
1823 vlan = strtol(p, (char **) &endp, 0);
1824 if (*endp) {
1825 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1826 return 1;
1828 } else {
1829 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1830 return 1;
1832 } else
1833 vlan = 0;
1835 bt_vhci_add(vlan);
1836 return 0;
1838 } else if (strstart(opt, "device:", &endp))
1839 return !bt_device_add(endp);
1841 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1842 return 1;
1845 /***********************************************************/
1846 /* QEMU Block devices */
1848 #define HD_ALIAS "index=%d,media=disk"
1849 #define CDROM_ALIAS "index=2,media=cdrom"
1850 #define FD_ALIAS "index=%d,if=floppy"
1851 #define PFLASH_ALIAS "if=pflash"
1852 #define MTD_ALIAS "if=mtd"
1853 #define SD_ALIAS "index=0,if=sd"
1855 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1857 va_list ap;
1858 char optstr[1024];
1859 QemuOpts *opts;
1861 va_start(ap, fmt);
1862 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1863 va_end(ap);
1865 opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
1866 if (!opts) {
1867 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1868 __FUNCTION__, optstr);
1869 return NULL;
1871 if (file)
1872 qemu_opt_set(opts, "file", file);
1873 return opts;
1876 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1878 DriveInfo *dinfo;
1880 /* seek interface, bus and unit */
1882 QTAILQ_FOREACH(dinfo, &drives, next) {
1883 if (dinfo->type == type &&
1884 dinfo->bus == bus &&
1885 dinfo->unit == unit)
1886 return dinfo;
1889 return NULL;
1892 DriveInfo *drive_get_by_id(const char *id)
1894 DriveInfo *dinfo;
1896 QTAILQ_FOREACH(dinfo, &drives, next) {
1897 if (strcmp(id, dinfo->id))
1898 continue;
1899 return dinfo;
1901 return NULL;
1904 int drive_get_max_bus(BlockInterfaceType type)
1906 int max_bus;
1907 DriveInfo *dinfo;
1909 max_bus = -1;
1910 QTAILQ_FOREACH(dinfo, &drives, next) {
1911 if(dinfo->type == type &&
1912 dinfo->bus > max_bus)
1913 max_bus = dinfo->bus;
1915 return max_bus;
1918 const char *drive_get_serial(BlockDriverState *bdrv)
1920 DriveInfo *dinfo;
1922 QTAILQ_FOREACH(dinfo, &drives, next) {
1923 if (dinfo->bdrv == bdrv)
1924 return dinfo->serial;
1927 return "\0";
1930 BlockInterfaceErrorAction drive_get_on_error(
1931 BlockDriverState *bdrv, int is_read)
1933 DriveInfo *dinfo;
1935 QTAILQ_FOREACH(dinfo, &drives, next) {
1936 if (dinfo->bdrv == bdrv)
1937 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
1940 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
1943 static void bdrv_format_print(void *opaque, const char *name)
1945 fprintf(stderr, " %s", name);
1948 void drive_uninit(DriveInfo *dinfo)
1950 qemu_opts_del(dinfo->opts);
1951 bdrv_delete(dinfo->bdrv);
1952 QTAILQ_REMOVE(&drives, dinfo, next);
1953 qemu_free(dinfo);
1956 static int parse_block_error_action(const char *buf, int is_read)
1958 if (!strcmp(buf, "ignore")) {
1959 return BLOCK_ERR_IGNORE;
1960 } else if (!is_read && !strcmp(buf, "enospc")) {
1961 return BLOCK_ERR_STOP_ENOSPC;
1962 } else if (!strcmp(buf, "stop")) {
1963 return BLOCK_ERR_STOP_ANY;
1964 } else if (!strcmp(buf, "report")) {
1965 return BLOCK_ERR_REPORT;
1966 } else {
1967 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
1968 buf, is_read ? "read" : "write");
1969 return -1;
1973 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1974 int *fatal_error)
1976 const char *buf;
1977 const char *file = NULL;
1978 char devname[128];
1979 const char *serial;
1980 const char *mediastr = "";
1981 BlockInterfaceType type;
1982 enum { MEDIA_DISK, MEDIA_CDROM } media;
1983 int bus_id, unit_id;
1984 int cyls, heads, secs, translation;
1985 BlockDriver *drv = NULL;
1986 QEMUMachine *machine = opaque;
1987 int max_devs;
1988 int index;
1989 int cache;
1990 int aio = 0;
1991 int ro = 0;
1992 int bdrv_flags;
1993 int on_read_error, on_write_error;
1994 const char *devaddr;
1995 DriveInfo *dinfo;
1996 int snapshot = 0;
1998 *fatal_error = 1;
2000 translation = BIOS_ATA_TRANSLATION_AUTO;
2001 cache = 1;
2003 if (machine && machine->use_scsi) {
2004 type = IF_SCSI;
2005 max_devs = MAX_SCSI_DEVS;
2006 pstrcpy(devname, sizeof(devname), "scsi");
2007 } else {
2008 type = IF_IDE;
2009 max_devs = MAX_IDE_DEVS;
2010 pstrcpy(devname, sizeof(devname), "ide");
2012 media = MEDIA_DISK;
2014 /* extract parameters */
2015 bus_id = qemu_opt_get_number(opts, "bus", 0);
2016 unit_id = qemu_opt_get_number(opts, "unit", -1);
2017 index = qemu_opt_get_number(opts, "index", -1);
2019 cyls = qemu_opt_get_number(opts, "cyls", 0);
2020 heads = qemu_opt_get_number(opts, "heads", 0);
2021 secs = qemu_opt_get_number(opts, "secs", 0);
2023 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
2024 ro = qemu_opt_get_bool(opts, "readonly", 0);
2026 file = qemu_opt_get(opts, "file");
2027 serial = qemu_opt_get(opts, "serial");
2029 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
2030 pstrcpy(devname, sizeof(devname), buf);
2031 if (!strcmp(buf, "ide")) {
2032 type = IF_IDE;
2033 max_devs = MAX_IDE_DEVS;
2034 } else if (!strcmp(buf, "scsi")) {
2035 type = IF_SCSI;
2036 max_devs = MAX_SCSI_DEVS;
2037 } else if (!strcmp(buf, "floppy")) {
2038 type = IF_FLOPPY;
2039 max_devs = 0;
2040 } else if (!strcmp(buf, "pflash")) {
2041 type = IF_PFLASH;
2042 max_devs = 0;
2043 } else if (!strcmp(buf, "mtd")) {
2044 type = IF_MTD;
2045 max_devs = 0;
2046 } else if (!strcmp(buf, "sd")) {
2047 type = IF_SD;
2048 max_devs = 0;
2049 } else if (!strcmp(buf, "virtio")) {
2050 type = IF_VIRTIO;
2051 max_devs = 0;
2052 } else if (!strcmp(buf, "xen")) {
2053 type = IF_XEN;
2054 max_devs = 0;
2055 } else if (!strcmp(buf, "none")) {
2056 type = IF_NONE;
2057 max_devs = 0;
2058 } else {
2059 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
2060 return NULL;
2064 if (cyls || heads || secs) {
2065 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
2066 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2067 return NULL;
2069 if (heads < 1 || (type == IF_IDE && heads > 16)) {
2070 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2071 return NULL;
2073 if (secs < 1 || (type == IF_IDE && secs > 63)) {
2074 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2075 return NULL;
2079 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2080 if (!cyls) {
2081 fprintf(stderr,
2082 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2083 buf);
2084 return NULL;
2086 if (!strcmp(buf, "none"))
2087 translation = BIOS_ATA_TRANSLATION_NONE;
2088 else if (!strcmp(buf, "lba"))
2089 translation = BIOS_ATA_TRANSLATION_LBA;
2090 else if (!strcmp(buf, "auto"))
2091 translation = BIOS_ATA_TRANSLATION_AUTO;
2092 else {
2093 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2094 return NULL;
2098 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2099 if (!strcmp(buf, "disk")) {
2100 media = MEDIA_DISK;
2101 } else if (!strcmp(buf, "cdrom")) {
2102 if (cyls || secs || heads) {
2103 fprintf(stderr,
2104 "qemu: '%s' invalid physical CHS format\n", buf);
2105 return NULL;
2107 media = MEDIA_CDROM;
2108 } else {
2109 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2110 return NULL;
2114 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2115 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2116 cache = 0;
2117 else if (!strcmp(buf, "writethrough"))
2118 cache = 1;
2119 else if (!strcmp(buf, "writeback"))
2120 cache = 2;
2121 else {
2122 fprintf(stderr, "qemu: invalid cache option\n");
2123 return NULL;
2127 #ifdef CONFIG_LINUX_AIO
2128 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2129 if (!strcmp(buf, "threads"))
2130 aio = 0;
2131 else if (!strcmp(buf, "native"))
2132 aio = 1;
2133 else {
2134 fprintf(stderr, "qemu: invalid aio option\n");
2135 return NULL;
2138 #endif
2140 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2141 if (strcmp(buf, "?") == 0) {
2142 fprintf(stderr, "qemu: Supported formats:");
2143 bdrv_iterate_format(bdrv_format_print, NULL);
2144 fprintf(stderr, "\n");
2145 return NULL;
2147 drv = bdrv_find_whitelisted_format(buf);
2148 if (!drv) {
2149 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2150 return NULL;
2154 on_write_error = BLOCK_ERR_STOP_ENOSPC;
2155 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2156 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2157 fprintf(stderr, "werror is no supported by this format\n");
2158 return NULL;
2161 on_write_error = parse_block_error_action(buf, 0);
2162 if (on_write_error < 0) {
2163 return NULL;
2167 on_read_error = BLOCK_ERR_REPORT;
2168 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2169 if (type != IF_IDE && type != IF_VIRTIO) {
2170 fprintf(stderr, "rerror is no supported by this format\n");
2171 return NULL;
2174 on_read_error = parse_block_error_action(buf, 1);
2175 if (on_read_error < 0) {
2176 return NULL;
2180 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2181 if (type != IF_VIRTIO) {
2182 fprintf(stderr, "addr is not supported\n");
2183 return NULL;
2187 /* compute bus and unit according index */
2189 if (index != -1) {
2190 if (bus_id != 0 || unit_id != -1) {
2191 fprintf(stderr,
2192 "qemu: index cannot be used with bus and unit\n");
2193 return NULL;
2195 if (max_devs == 0)
2197 unit_id = index;
2198 bus_id = 0;
2199 } else {
2200 unit_id = index % max_devs;
2201 bus_id = index / max_devs;
2205 /* if user doesn't specify a unit_id,
2206 * try to find the first free
2209 if (unit_id == -1) {
2210 unit_id = 0;
2211 while (drive_get(type, bus_id, unit_id) != NULL) {
2212 unit_id++;
2213 if (max_devs && unit_id >= max_devs) {
2214 unit_id -= max_devs;
2215 bus_id++;
2220 /* check unit id */
2222 if (max_devs && unit_id >= max_devs) {
2223 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2224 unit_id, max_devs - 1);
2225 return NULL;
2229 * ignore multiple definitions
2232 if (drive_get(type, bus_id, unit_id) != NULL) {
2233 *fatal_error = 0;
2234 return NULL;
2237 /* init */
2239 dinfo = qemu_mallocz(sizeof(*dinfo));
2240 if ((buf = qemu_opts_id(opts)) != NULL) {
2241 dinfo->id = qemu_strdup(buf);
2242 } else {
2243 /* no id supplied -> create one */
2244 dinfo->id = qemu_mallocz(32);
2245 if (type == IF_IDE || type == IF_SCSI)
2246 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2247 if (max_devs)
2248 snprintf(dinfo->id, 32, "%s%i%s%i",
2249 devname, bus_id, mediastr, unit_id);
2250 else
2251 snprintf(dinfo->id, 32, "%s%s%i",
2252 devname, mediastr, unit_id);
2254 dinfo->bdrv = bdrv_new(dinfo->id);
2255 dinfo->devaddr = devaddr;
2256 dinfo->type = type;
2257 dinfo->bus = bus_id;
2258 dinfo->unit = unit_id;
2259 dinfo->on_read_error = on_read_error;
2260 dinfo->on_write_error = on_write_error;
2261 dinfo->opts = opts;
2262 if (serial)
2263 strncpy(dinfo->serial, serial, sizeof(serial));
2264 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2266 switch(type) {
2267 case IF_IDE:
2268 case IF_SCSI:
2269 case IF_XEN:
2270 case IF_NONE:
2271 switch(media) {
2272 case MEDIA_DISK:
2273 if (cyls != 0) {
2274 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2275 bdrv_set_translation_hint(dinfo->bdrv, translation);
2277 break;
2278 case MEDIA_CDROM:
2279 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2280 break;
2282 break;
2283 case IF_SD:
2284 /* FIXME: This isn't really a floppy, but it's a reasonable
2285 approximation. */
2286 case IF_FLOPPY:
2287 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2288 break;
2289 case IF_PFLASH:
2290 case IF_MTD:
2291 break;
2292 case IF_VIRTIO:
2293 /* add virtio block device */
2294 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2295 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2296 qemu_opt_set(opts, "drive", dinfo->id);
2297 if (devaddr)
2298 qemu_opt_set(opts, "addr", devaddr);
2299 break;
2300 case IF_COUNT:
2301 abort();
2303 if (!file) {
2304 *fatal_error = 0;
2305 return NULL;
2307 bdrv_flags = 0;
2308 if (snapshot) {
2309 bdrv_flags |= BDRV_O_SNAPSHOT;
2310 cache = 2; /* always use write-back with snapshot */
2312 if (cache == 0) /* no caching */
2313 bdrv_flags |= BDRV_O_NOCACHE;
2314 else if (cache == 2) /* write-back */
2315 bdrv_flags |= BDRV_O_CACHE_WB;
2317 if (aio == 1) {
2318 bdrv_flags |= BDRV_O_NATIVE_AIO;
2319 } else {
2320 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2323 if (ro == 1) {
2324 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
2325 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
2326 return NULL;
2330 * cdrom is read-only. Set it now, after above interface checking
2331 * since readonly attribute not explicitly required, so no error.
2333 if (media == MEDIA_CDROM) {
2334 ro = 1;
2336 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
2338 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2339 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2340 file, strerror(errno));
2341 return NULL;
2344 if (bdrv_key_required(dinfo->bdrv))
2345 autostart = 0;
2346 *fatal_error = 0;
2347 return dinfo;
2350 static int drive_init_func(QemuOpts *opts, void *opaque)
2352 QEMUMachine *machine = opaque;
2353 int fatal_error = 0;
2355 if (drive_init(opts, machine, &fatal_error) == NULL) {
2356 if (fatal_error)
2357 return 1;
2359 return 0;
2362 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2364 if (NULL == qemu_opt_get(opts, "snapshot")) {
2365 qemu_opt_set(opts, "snapshot", "on");
2367 return 0;
2370 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2372 boot_set_handler = func;
2373 boot_set_opaque = opaque;
2376 int qemu_boot_set(const char *boot_devices)
2378 if (!boot_set_handler) {
2379 return -EINVAL;
2381 return boot_set_handler(boot_set_opaque, boot_devices);
2384 static int parse_bootdevices(char *devices)
2386 /* We just do some generic consistency checks */
2387 const char *p;
2388 int bitmap = 0;
2390 for (p = devices; *p != '\0'; p++) {
2391 /* Allowed boot devices are:
2392 * a-b: floppy disk drives
2393 * c-f: IDE disk drives
2394 * g-m: machine implementation dependant drives
2395 * n-p: network devices
2396 * It's up to each machine implementation to check if the given boot
2397 * devices match the actual hardware implementation and firmware
2398 * features.
2400 if (*p < 'a' || *p > 'p') {
2401 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2402 exit(1);
2404 if (bitmap & (1 << (*p - 'a'))) {
2405 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2406 exit(1);
2408 bitmap |= 1 << (*p - 'a');
2410 return bitmap;
2413 static void restore_boot_devices(void *opaque)
2415 char *standard_boot_devices = opaque;
2417 qemu_boot_set(standard_boot_devices);
2419 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2420 qemu_free(standard_boot_devices);
2423 static void numa_add(const char *optarg)
2425 char option[128];
2426 char *endptr;
2427 unsigned long long value, endvalue;
2428 int nodenr;
2430 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2431 if (!strcmp(option, "node")) {
2432 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2433 nodenr = nb_numa_nodes;
2434 } else {
2435 nodenr = strtoull(option, NULL, 10);
2438 if (get_param_value(option, 128, "mem", optarg) == 0) {
2439 node_mem[nodenr] = 0;
2440 } else {
2441 value = strtoull(option, &endptr, 0);
2442 switch (*endptr) {
2443 case 0: case 'M': case 'm':
2444 value <<= 20;
2445 break;
2446 case 'G': case 'g':
2447 value <<= 30;
2448 break;
2450 node_mem[nodenr] = value;
2452 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2453 node_cpumask[nodenr] = 0;
2454 } else {
2455 value = strtoull(option, &endptr, 10);
2456 if (value >= 64) {
2457 value = 63;
2458 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2459 } else {
2460 if (*endptr == '-') {
2461 endvalue = strtoull(endptr+1, &endptr, 10);
2462 if (endvalue >= 63) {
2463 endvalue = 62;
2464 fprintf(stderr,
2465 "only 63 CPUs in NUMA mode supported.\n");
2467 value = (2ULL << endvalue) - (1ULL << value);
2468 } else {
2469 value = 1ULL << value;
2472 node_cpumask[nodenr] = value;
2474 nb_numa_nodes++;
2476 return;
2479 static void smp_parse(const char *optarg)
2481 int smp, sockets = 0, threads = 0, cores = 0;
2482 char *endptr;
2483 char option[128];
2485 smp = strtoul(optarg, &endptr, 10);
2486 if (endptr != optarg) {
2487 if (*endptr == ',') {
2488 endptr++;
2491 if (get_param_value(option, 128, "sockets", endptr) != 0)
2492 sockets = strtoull(option, NULL, 10);
2493 if (get_param_value(option, 128, "cores", endptr) != 0)
2494 cores = strtoull(option, NULL, 10);
2495 if (get_param_value(option, 128, "threads", endptr) != 0)
2496 threads = strtoull(option, NULL, 10);
2497 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2498 max_cpus = strtoull(option, NULL, 10);
2500 /* compute missing values, prefer sockets over cores over threads */
2501 if (smp == 0 || sockets == 0) {
2502 sockets = sockets > 0 ? sockets : 1;
2503 cores = cores > 0 ? cores : 1;
2504 threads = threads > 0 ? threads : 1;
2505 if (smp == 0) {
2506 smp = cores * threads * sockets;
2508 } else {
2509 if (cores == 0) {
2510 threads = threads > 0 ? threads : 1;
2511 cores = smp / (sockets * threads);
2512 } else {
2513 if (sockets) {
2514 threads = smp / (cores * sockets);
2518 smp_cpus = smp;
2519 smp_cores = cores > 0 ? cores : 1;
2520 smp_threads = threads > 0 ? threads : 1;
2521 if (max_cpus == 0)
2522 max_cpus = smp_cpus;
2525 /***********************************************************/
2526 /* USB devices */
2528 static int usb_device_add(const char *devname, int is_hotplug)
2530 const char *p;
2531 USBDevice *dev = NULL;
2533 if (!usb_enabled)
2534 return -1;
2536 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2537 dev = usbdevice_create(devname);
2538 if (dev)
2539 goto done;
2541 /* the other ones */
2542 if (strstart(devname, "host:", &p)) {
2543 dev = usb_host_device_open(p);
2544 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2545 dev = usb_bt_init(devname[2] ? hci_init(p) :
2546 bt_new_hci(qemu_find_bt_vlan(0)));
2547 } else {
2548 return -1;
2550 if (!dev)
2551 return -1;
2553 done:
2554 return 0;
2557 static int usb_device_del(const char *devname)
2559 int bus_num, addr;
2560 const char *p;
2562 if (strstart(devname, "host:", &p))
2563 return usb_host_device_close(p);
2565 if (!usb_enabled)
2566 return -1;
2568 p = strchr(devname, '.');
2569 if (!p)
2570 return -1;
2571 bus_num = strtoul(devname, NULL, 0);
2572 addr = strtoul(p + 1, NULL, 0);
2574 return usb_device_delete_addr(bus_num, addr);
2577 static int usb_parse(const char *cmdline)
2579 int r;
2580 r = usb_device_add(cmdline, 0);
2581 if (r < 0) {
2582 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
2584 return r;
2587 void do_usb_add(Monitor *mon, const QDict *qdict)
2589 const char *devname = qdict_get_str(qdict, "devname");
2590 if (usb_device_add(devname, 1) < 0) {
2591 error_report("could not add USB device '%s'", devname);
2595 void do_usb_del(Monitor *mon, const QDict *qdict)
2597 const char *devname = qdict_get_str(qdict, "devname");
2598 if (usb_device_del(devname) < 0) {
2599 error_report("could not delete USB device '%s'", devname);
2603 /***********************************************************/
2604 /* PCMCIA/Cardbus */
2606 static struct pcmcia_socket_entry_s {
2607 PCMCIASocket *socket;
2608 struct pcmcia_socket_entry_s *next;
2609 } *pcmcia_sockets = 0;
2611 void pcmcia_socket_register(PCMCIASocket *socket)
2613 struct pcmcia_socket_entry_s *entry;
2615 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2616 entry->socket = socket;
2617 entry->next = pcmcia_sockets;
2618 pcmcia_sockets = entry;
2621 void pcmcia_socket_unregister(PCMCIASocket *socket)
2623 struct pcmcia_socket_entry_s *entry, **ptr;
2625 ptr = &pcmcia_sockets;
2626 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2627 if (entry->socket == socket) {
2628 *ptr = entry->next;
2629 qemu_free(entry);
2633 void pcmcia_info(Monitor *mon)
2635 struct pcmcia_socket_entry_s *iter;
2637 if (!pcmcia_sockets)
2638 monitor_printf(mon, "No PCMCIA sockets\n");
2640 for (iter = pcmcia_sockets; iter; iter = iter->next)
2641 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2642 iter->socket->attached ? iter->socket->card_string :
2643 "Empty");
2646 /***********************************************************/
2647 /* I/O handling */
2649 typedef struct IOHandlerRecord {
2650 int fd;
2651 IOCanRWHandler *fd_read_poll;
2652 IOHandler *fd_read;
2653 IOHandler *fd_write;
2654 int deleted;
2655 void *opaque;
2656 /* temporary data */
2657 struct pollfd *ufd;
2658 struct IOHandlerRecord *next;
2659 } IOHandlerRecord;
2661 static IOHandlerRecord *first_io_handler;
2663 /* XXX: fd_read_poll should be suppressed, but an API change is
2664 necessary in the character devices to suppress fd_can_read(). */
2665 int qemu_set_fd_handler2(int fd,
2666 IOCanRWHandler *fd_read_poll,
2667 IOHandler *fd_read,
2668 IOHandler *fd_write,
2669 void *opaque)
2671 IOHandlerRecord **pioh, *ioh;
2673 if (!fd_read && !fd_write) {
2674 pioh = &first_io_handler;
2675 for(;;) {
2676 ioh = *pioh;
2677 if (ioh == NULL)
2678 break;
2679 if (ioh->fd == fd) {
2680 ioh->deleted = 1;
2681 break;
2683 pioh = &ioh->next;
2685 } else {
2686 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2687 if (ioh->fd == fd)
2688 goto found;
2690 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2691 ioh->next = first_io_handler;
2692 first_io_handler = ioh;
2693 found:
2694 ioh->fd = fd;
2695 ioh->fd_read_poll = fd_read_poll;
2696 ioh->fd_read = fd_read;
2697 ioh->fd_write = fd_write;
2698 ioh->opaque = opaque;
2699 ioh->deleted = 0;
2701 return 0;
2704 int qemu_set_fd_handler(int fd,
2705 IOHandler *fd_read,
2706 IOHandler *fd_write,
2707 void *opaque)
2709 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2712 #ifdef _WIN32
2713 /***********************************************************/
2714 /* Polling handling */
2716 typedef struct PollingEntry {
2717 PollingFunc *func;
2718 void *opaque;
2719 struct PollingEntry *next;
2720 } PollingEntry;
2722 static PollingEntry *first_polling_entry;
2724 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2726 PollingEntry **ppe, *pe;
2727 pe = qemu_mallocz(sizeof(PollingEntry));
2728 pe->func = func;
2729 pe->opaque = opaque;
2730 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2731 *ppe = pe;
2732 return 0;
2735 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2737 PollingEntry **ppe, *pe;
2738 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2739 pe = *ppe;
2740 if (pe->func == func && pe->opaque == opaque) {
2741 *ppe = pe->next;
2742 qemu_free(pe);
2743 break;
2748 /***********************************************************/
2749 /* Wait objects support */
2750 typedef struct WaitObjects {
2751 int num;
2752 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2753 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2754 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2755 } WaitObjects;
2757 static WaitObjects wait_objects = {0};
2759 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2761 WaitObjects *w = &wait_objects;
2763 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2764 return -1;
2765 w->events[w->num] = handle;
2766 w->func[w->num] = func;
2767 w->opaque[w->num] = opaque;
2768 w->num++;
2769 return 0;
2772 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2774 int i, found;
2775 WaitObjects *w = &wait_objects;
2777 found = 0;
2778 for (i = 0; i < w->num; i++) {
2779 if (w->events[i] == handle)
2780 found = 1;
2781 if (found) {
2782 w->events[i] = w->events[i + 1];
2783 w->func[i] = w->func[i + 1];
2784 w->opaque[i] = w->opaque[i + 1];
2787 if (found)
2788 w->num--;
2790 #endif
2792 /***********************************************************/
2793 /* ram save/restore */
2795 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2796 #define RAM_SAVE_FLAG_COMPRESS 0x02
2797 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2798 #define RAM_SAVE_FLAG_PAGE 0x08
2799 #define RAM_SAVE_FLAG_EOS 0x10
2801 static int is_dup_page(uint8_t *page, uint8_t ch)
2803 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2804 uint32_t *array = (uint32_t *)page;
2805 int i;
2807 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2808 if (array[i] != val)
2809 return 0;
2812 return 1;
2815 static int ram_save_block(QEMUFile *f)
2817 static ram_addr_t current_addr = 0;
2818 ram_addr_t saved_addr = current_addr;
2819 ram_addr_t addr = 0;
2820 int found = 0;
2822 while (addr < last_ram_offset) {
2823 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2824 uint8_t *p;
2826 cpu_physical_memory_reset_dirty(current_addr,
2827 current_addr + TARGET_PAGE_SIZE,
2828 MIGRATION_DIRTY_FLAG);
2830 p = qemu_get_ram_ptr(current_addr);
2832 if (is_dup_page(p, *p)) {
2833 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2834 qemu_put_byte(f, *p);
2835 } else {
2836 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2837 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2840 found = 1;
2841 break;
2843 addr += TARGET_PAGE_SIZE;
2844 current_addr = (saved_addr + addr) % last_ram_offset;
2847 return found;
2850 static uint64_t bytes_transferred;
2852 static ram_addr_t ram_save_remaining(void)
2854 ram_addr_t addr;
2855 ram_addr_t count = 0;
2857 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2858 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2859 count++;
2862 return count;
2865 uint64_t ram_bytes_remaining(void)
2867 return ram_save_remaining() * TARGET_PAGE_SIZE;
2870 uint64_t ram_bytes_transferred(void)
2872 return bytes_transferred;
2875 uint64_t ram_bytes_total(void)
2877 return last_ram_offset;
2880 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
2882 ram_addr_t addr;
2883 uint64_t bytes_transferred_last;
2884 double bwidth = 0;
2885 uint64_t expected_time = 0;
2887 if (stage < 0) {
2888 cpu_physical_memory_set_dirty_tracking(0);
2889 return 0;
2892 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2893 qemu_file_set_error(f);
2894 return 0;
2897 if (stage == 1) {
2898 bytes_transferred = 0;
2900 /* Make sure all dirty bits are set */
2901 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2902 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2903 cpu_physical_memory_set_dirty(addr);
2906 /* Enable dirty memory tracking */
2907 cpu_physical_memory_set_dirty_tracking(1);
2909 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2912 bytes_transferred_last = bytes_transferred;
2913 bwidth = qemu_get_clock_ns(rt_clock);
2915 while (!qemu_file_rate_limit(f)) {
2916 int ret;
2918 ret = ram_save_block(f);
2919 bytes_transferred += ret * TARGET_PAGE_SIZE;
2920 if (ret == 0) /* no more blocks */
2921 break;
2924 bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
2925 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2927 /* if we haven't transferred anything this round, force expected_time to a
2928 * a very high value, but without crashing */
2929 if (bwidth == 0)
2930 bwidth = 0.000001;
2932 /* try transferring iterative blocks of memory */
2933 if (stage == 3) {
2934 /* flush all remaining blocks regardless of rate limiting */
2935 while (ram_save_block(f) != 0) {
2936 bytes_transferred += TARGET_PAGE_SIZE;
2938 cpu_physical_memory_set_dirty_tracking(0);
2941 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2943 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2945 return (stage == 2) && (expected_time <= migrate_max_downtime());
2948 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2950 ram_addr_t addr;
2951 int flags;
2953 if (version_id != 3)
2954 return -EINVAL;
2956 do {
2957 addr = qemu_get_be64(f);
2959 flags = addr & ~TARGET_PAGE_MASK;
2960 addr &= TARGET_PAGE_MASK;
2962 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2963 if (addr != last_ram_offset)
2964 return -EINVAL;
2967 if (flags & RAM_SAVE_FLAG_COMPRESS) {
2968 uint8_t ch = qemu_get_byte(f);
2969 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
2970 #ifndef _WIN32
2971 if (ch == 0 &&
2972 (!kvm_enabled() || kvm_has_sync_mmu())) {
2973 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
2975 #endif
2976 } else if (flags & RAM_SAVE_FLAG_PAGE) {
2977 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
2979 if (qemu_file_has_error(f)) {
2980 return -EIO;
2982 } while (!(flags & RAM_SAVE_FLAG_EOS));
2984 return 0;
2987 void qemu_service_io(void)
2989 qemu_notify_event();
2992 /***********************************************************/
2993 /* machine registration */
2995 static QEMUMachine *first_machine = NULL;
2996 QEMUMachine *current_machine = NULL;
2998 int qemu_register_machine(QEMUMachine *m)
3000 QEMUMachine **pm;
3001 pm = &first_machine;
3002 while (*pm != NULL)
3003 pm = &(*pm)->next;
3004 m->next = NULL;
3005 *pm = m;
3006 return 0;
3009 static QEMUMachine *find_machine(const char *name)
3011 QEMUMachine *m;
3013 for(m = first_machine; m != NULL; m = m->next) {
3014 if (!strcmp(m->name, name))
3015 return m;
3016 if (m->alias && !strcmp(m->alias, name))
3017 return m;
3019 return NULL;
3022 static QEMUMachine *find_default_machine(void)
3024 QEMUMachine *m;
3026 for(m = first_machine; m != NULL; m = m->next) {
3027 if (m->is_default) {
3028 return m;
3031 return NULL;
3034 /***********************************************************/
3035 /* main execution loop */
3037 static void gui_update(void *opaque)
3039 uint64_t interval = GUI_REFRESH_INTERVAL;
3040 DisplayState *ds = opaque;
3041 DisplayChangeListener *dcl = ds->listeners;
3043 qemu_flush_coalesced_mmio_buffer();
3044 dpy_refresh(ds);
3046 while (dcl != NULL) {
3047 if (dcl->gui_timer_interval &&
3048 dcl->gui_timer_interval < interval)
3049 interval = dcl->gui_timer_interval;
3050 dcl = dcl->next;
3052 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3055 static void nographic_update(void *opaque)
3057 uint64_t interval = GUI_REFRESH_INTERVAL;
3059 qemu_flush_coalesced_mmio_buffer();
3060 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3063 void cpu_synchronize_all_states(void)
3065 CPUState *cpu;
3067 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3068 cpu_synchronize_state(cpu);
3072 void cpu_synchronize_all_post_reset(void)
3074 CPUState *cpu;
3076 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3077 cpu_synchronize_post_reset(cpu);
3081 void cpu_synchronize_all_post_init(void)
3083 CPUState *cpu;
3085 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3086 cpu_synchronize_post_init(cpu);
3090 struct vm_change_state_entry {
3091 VMChangeStateHandler *cb;
3092 void *opaque;
3093 QLIST_ENTRY (vm_change_state_entry) entries;
3096 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3098 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3099 void *opaque)
3101 VMChangeStateEntry *e;
3103 e = qemu_mallocz(sizeof (*e));
3105 e->cb = cb;
3106 e->opaque = opaque;
3107 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3108 return e;
3111 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3113 QLIST_REMOVE (e, entries);
3114 qemu_free (e);
3117 static void vm_state_notify(int running, int reason)
3119 VMChangeStateEntry *e;
3121 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3122 e->cb(e->opaque, running, reason);
3126 static void resume_all_vcpus(void);
3127 static void pause_all_vcpus(void);
3129 void vm_start(void)
3131 if (!vm_running) {
3132 cpu_enable_ticks();
3133 vm_running = 1;
3134 vm_state_notify(1, 0);
3135 resume_all_vcpus();
3139 /* reset/shutdown handler */
3141 typedef struct QEMUResetEntry {
3142 QTAILQ_ENTRY(QEMUResetEntry) entry;
3143 QEMUResetHandler *func;
3144 void *opaque;
3145 } QEMUResetEntry;
3147 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3148 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3149 static int reset_requested;
3150 static int shutdown_requested;
3151 static int powerdown_requested;
3152 static int debug_requested;
3153 static int vmstop_requested;
3155 int qemu_shutdown_requested(void)
3157 int r = shutdown_requested;
3158 shutdown_requested = 0;
3159 return r;
3162 int qemu_reset_requested(void)
3164 int r = reset_requested;
3165 reset_requested = 0;
3166 return r;
3169 int qemu_powerdown_requested(void)
3171 int r = powerdown_requested;
3172 powerdown_requested = 0;
3173 return r;
3176 static int qemu_debug_requested(void)
3178 int r = debug_requested;
3179 debug_requested = 0;
3180 return r;
3183 static int qemu_vmstop_requested(void)
3185 int r = vmstop_requested;
3186 vmstop_requested = 0;
3187 return r;
3190 static void do_vm_stop(int reason)
3192 if (vm_running) {
3193 cpu_disable_ticks();
3194 vm_running = 0;
3195 pause_all_vcpus();
3196 vm_state_notify(0, reason);
3197 monitor_protocol_event(QEVENT_STOP, NULL);
3201 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3203 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3205 re->func = func;
3206 re->opaque = opaque;
3207 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3210 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3212 QEMUResetEntry *re;
3214 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3215 if (re->func == func && re->opaque == opaque) {
3216 QTAILQ_REMOVE(&reset_handlers, re, entry);
3217 qemu_free(re);
3218 return;
3223 void qemu_system_reset(void)
3225 QEMUResetEntry *re, *nre;
3227 /* reset all devices */
3228 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3229 re->func(re->opaque);
3231 monitor_protocol_event(QEVENT_RESET, NULL);
3232 cpu_synchronize_all_post_reset();
3235 void qemu_system_reset_request(void)
3237 if (no_reboot) {
3238 shutdown_requested = 1;
3239 } else {
3240 reset_requested = 1;
3242 qemu_notify_event();
3245 void qemu_system_shutdown_request(void)
3247 shutdown_requested = 1;
3248 qemu_notify_event();
3251 void qemu_system_powerdown_request(void)
3253 powerdown_requested = 1;
3254 qemu_notify_event();
3257 #ifdef CONFIG_IOTHREAD
3258 static void qemu_system_vmstop_request(int reason)
3260 vmstop_requested = reason;
3261 qemu_notify_event();
3263 #endif
3265 #ifndef _WIN32
3266 static int io_thread_fd = -1;
3268 static void qemu_event_increment(void)
3270 /* Write 8 bytes to be compatible with eventfd. */
3271 static uint64_t val = 1;
3272 ssize_t ret;
3274 if (io_thread_fd == -1)
3275 return;
3277 do {
3278 ret = write(io_thread_fd, &val, sizeof(val));
3279 } while (ret < 0 && errno == EINTR);
3281 /* EAGAIN is fine, a read must be pending. */
3282 if (ret < 0 && errno != EAGAIN) {
3283 fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
3284 strerror(errno));
3285 exit (1);
3289 static void qemu_event_read(void *opaque)
3291 int fd = (unsigned long)opaque;
3292 ssize_t len;
3293 char buffer[512];
3295 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
3296 do {
3297 len = read(fd, buffer, sizeof(buffer));
3298 } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
3301 static int qemu_event_init(void)
3303 int err;
3304 int fds[2];
3306 err = qemu_eventfd(fds);
3307 if (err == -1)
3308 return -errno;
3310 err = fcntl_setfl(fds[0], O_NONBLOCK);
3311 if (err < 0)
3312 goto fail;
3314 err = fcntl_setfl(fds[1], O_NONBLOCK);
3315 if (err < 0)
3316 goto fail;
3318 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3319 (void *)(unsigned long)fds[0]);
3321 io_thread_fd = fds[1];
3322 return 0;
3324 fail:
3325 close(fds[0]);
3326 close(fds[1]);
3327 return err;
3329 #else
3330 HANDLE qemu_event_handle;
3332 static void dummy_event_handler(void *opaque)
3336 static int qemu_event_init(void)
3338 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3339 if (!qemu_event_handle) {
3340 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3341 return -1;
3343 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3344 return 0;
3347 static void qemu_event_increment(void)
3349 if (!SetEvent(qemu_event_handle)) {
3350 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3351 GetLastError());
3352 exit (1);
3355 #endif
3357 static int cpu_can_run(CPUState *env)
3359 if (env->stop)
3360 return 0;
3361 if (env->stopped)
3362 return 0;
3363 if (!vm_running)
3364 return 0;
3365 return 1;
3368 #ifndef CONFIG_IOTHREAD
3369 static int qemu_init_main_loop(void)
3371 return qemu_event_init();
3374 void qemu_init_vcpu(void *_env)
3376 CPUState *env = _env;
3378 env->nr_cores = smp_cores;
3379 env->nr_threads = smp_threads;
3380 if (kvm_enabled())
3381 kvm_init_vcpu(env);
3382 return;
3385 int qemu_cpu_self(void *env)
3387 return 1;
3390 static void resume_all_vcpus(void)
3394 static void pause_all_vcpus(void)
3398 void qemu_cpu_kick(void *env)
3400 return;
3403 void qemu_notify_event(void)
3405 CPUState *env = cpu_single_env;
3407 qemu_event_increment ();
3408 if (env) {
3409 cpu_exit(env);
3411 if (next_cpu && env != next_cpu) {
3412 cpu_exit(next_cpu);
3416 void qemu_mutex_lock_iothread(void) {}
3417 void qemu_mutex_unlock_iothread(void) {}
3419 void vm_stop(int reason)
3421 do_vm_stop(reason);
3424 #else /* CONFIG_IOTHREAD */
3426 #include "qemu-thread.h"
3428 QemuMutex qemu_global_mutex;
3429 static QemuMutex qemu_fair_mutex;
3431 static QemuThread io_thread;
3433 static QemuThread *tcg_cpu_thread;
3434 static QemuCond *tcg_halt_cond;
3436 static int qemu_system_ready;
3437 /* cpu creation */
3438 static QemuCond qemu_cpu_cond;
3439 /* system init */
3440 static QemuCond qemu_system_cond;
3441 static QemuCond qemu_pause_cond;
3443 static void tcg_block_io_signals(void);
3444 static void kvm_block_io_signals(CPUState *env);
3445 static void unblock_io_signals(void);
3446 static int tcg_has_work(void);
3447 static int cpu_has_work(CPUState *env);
3449 static int qemu_init_main_loop(void)
3451 int ret;
3453 ret = qemu_event_init();
3454 if (ret)
3455 return ret;
3457 qemu_cond_init(&qemu_pause_cond);
3458 qemu_mutex_init(&qemu_fair_mutex);
3459 qemu_mutex_init(&qemu_global_mutex);
3460 qemu_mutex_lock(&qemu_global_mutex);
3462 unblock_io_signals();
3463 qemu_thread_self(&io_thread);
3465 return 0;
3468 static void qemu_wait_io_event_common(CPUState *env)
3470 if (env->stop) {
3471 env->stop = 0;
3472 env->stopped = 1;
3473 qemu_cond_signal(&qemu_pause_cond);
3477 static void qemu_wait_io_event(CPUState *env)
3479 while (!tcg_has_work())
3480 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3482 qemu_mutex_unlock(&qemu_global_mutex);
3485 * Users of qemu_global_mutex can be starved, having no chance
3486 * to acquire it since this path will get to it first.
3487 * So use another lock to provide fairness.
3489 qemu_mutex_lock(&qemu_fair_mutex);
3490 qemu_mutex_unlock(&qemu_fair_mutex);
3492 qemu_mutex_lock(&qemu_global_mutex);
3493 qemu_wait_io_event_common(env);
3496 static void qemu_kvm_eat_signal(CPUState *env, int timeout)
3498 struct timespec ts;
3499 int r, e;
3500 siginfo_t siginfo;
3501 sigset_t waitset;
3503 ts.tv_sec = timeout / 1000;
3504 ts.tv_nsec = (timeout % 1000) * 1000000;
3506 sigemptyset(&waitset);
3507 sigaddset(&waitset, SIG_IPI);
3509 qemu_mutex_unlock(&qemu_global_mutex);
3510 r = sigtimedwait(&waitset, &siginfo, &ts);
3511 e = errno;
3512 qemu_mutex_lock(&qemu_global_mutex);
3514 if (r == -1 && !(e == EAGAIN || e == EINTR)) {
3515 fprintf(stderr, "sigtimedwait: %s\n", strerror(e));
3516 exit(1);
3520 static void qemu_kvm_wait_io_event(CPUState *env)
3522 while (!cpu_has_work(env))
3523 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3525 qemu_kvm_eat_signal(env, 0);
3526 qemu_wait_io_event_common(env);
3529 static int qemu_cpu_exec(CPUState *env);
3531 static void *kvm_cpu_thread_fn(void *arg)
3533 CPUState *env = arg;
3535 qemu_thread_self(env->thread);
3536 if (kvm_enabled())
3537 kvm_init_vcpu(env);
3539 kvm_block_io_signals(env);
3541 /* signal CPU creation */
3542 qemu_mutex_lock(&qemu_global_mutex);
3543 env->created = 1;
3544 qemu_cond_signal(&qemu_cpu_cond);
3546 /* and wait for machine initialization */
3547 while (!qemu_system_ready)
3548 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3550 while (1) {
3551 if (cpu_can_run(env))
3552 qemu_cpu_exec(env);
3553 qemu_kvm_wait_io_event(env);
3556 return NULL;
3559 static void tcg_cpu_exec(void);
3561 static void *tcg_cpu_thread_fn(void *arg)
3563 CPUState *env = arg;
3565 tcg_block_io_signals();
3566 qemu_thread_self(env->thread);
3568 /* signal CPU creation */
3569 qemu_mutex_lock(&qemu_global_mutex);
3570 for (env = first_cpu; env != NULL; env = env->next_cpu)
3571 env->created = 1;
3572 qemu_cond_signal(&qemu_cpu_cond);
3574 /* and wait for machine initialization */
3575 while (!qemu_system_ready)
3576 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3578 while (1) {
3579 tcg_cpu_exec();
3580 qemu_wait_io_event(cur_cpu);
3583 return NULL;
3586 void qemu_cpu_kick(void *_env)
3588 CPUState *env = _env;
3589 qemu_cond_broadcast(env->halt_cond);
3590 if (kvm_enabled())
3591 qemu_thread_signal(env->thread, SIG_IPI);
3594 int qemu_cpu_self(void *_env)
3596 CPUState *env = _env;
3597 QemuThread this;
3599 qemu_thread_self(&this);
3601 return qemu_thread_equal(&this, env->thread);
3604 static void cpu_signal(int sig)
3606 if (cpu_single_env)
3607 cpu_exit(cpu_single_env);
3610 static void tcg_block_io_signals(void)
3612 sigset_t set;
3613 struct sigaction sigact;
3615 sigemptyset(&set);
3616 sigaddset(&set, SIGUSR2);
3617 sigaddset(&set, SIGIO);
3618 sigaddset(&set, SIGALRM);
3619 sigaddset(&set, SIGCHLD);
3620 pthread_sigmask(SIG_BLOCK, &set, NULL);
3622 sigemptyset(&set);
3623 sigaddset(&set, SIG_IPI);
3624 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3626 memset(&sigact, 0, sizeof(sigact));
3627 sigact.sa_handler = cpu_signal;
3628 sigaction(SIG_IPI, &sigact, NULL);
3631 static void dummy_signal(int sig)
3635 static void kvm_block_io_signals(CPUState *env)
3637 int r;
3638 sigset_t set;
3639 struct sigaction sigact;
3641 sigemptyset(&set);
3642 sigaddset(&set, SIGUSR2);
3643 sigaddset(&set, SIGIO);
3644 sigaddset(&set, SIGALRM);
3645 sigaddset(&set, SIGCHLD);
3646 sigaddset(&set, SIG_IPI);
3647 pthread_sigmask(SIG_BLOCK, &set, NULL);
3649 pthread_sigmask(SIG_BLOCK, NULL, &set);
3650 sigdelset(&set, SIG_IPI);
3652 memset(&sigact, 0, sizeof(sigact));
3653 sigact.sa_handler = dummy_signal;
3654 sigaction(SIG_IPI, &sigact, NULL);
3656 r = kvm_set_signal_mask(env, &set);
3657 if (r) {
3658 fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(r));
3659 exit(1);
3663 static void unblock_io_signals(void)
3665 sigset_t set;
3667 sigemptyset(&set);
3668 sigaddset(&set, SIGUSR2);
3669 sigaddset(&set, SIGIO);
3670 sigaddset(&set, SIGALRM);
3671 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3673 sigemptyset(&set);
3674 sigaddset(&set, SIG_IPI);
3675 pthread_sigmask(SIG_BLOCK, &set, NULL);
3678 static void qemu_signal_lock(unsigned int msecs)
3680 qemu_mutex_lock(&qemu_fair_mutex);
3682 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3683 qemu_thread_signal(tcg_cpu_thread, SIG_IPI);
3684 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3685 break;
3687 qemu_mutex_unlock(&qemu_fair_mutex);
3690 void qemu_mutex_lock_iothread(void)
3692 if (kvm_enabled()) {
3693 qemu_mutex_lock(&qemu_fair_mutex);
3694 qemu_mutex_lock(&qemu_global_mutex);
3695 qemu_mutex_unlock(&qemu_fair_mutex);
3696 } else
3697 qemu_signal_lock(100);
3700 void qemu_mutex_unlock_iothread(void)
3702 qemu_mutex_unlock(&qemu_global_mutex);
3705 static int all_vcpus_paused(void)
3707 CPUState *penv = first_cpu;
3709 while (penv) {
3710 if (!penv->stopped)
3711 return 0;
3712 penv = (CPUState *)penv->next_cpu;
3715 return 1;
3718 static void pause_all_vcpus(void)
3720 CPUState *penv = first_cpu;
3722 while (penv) {
3723 penv->stop = 1;
3724 qemu_thread_signal(penv->thread, SIG_IPI);
3725 qemu_cpu_kick(penv);
3726 penv = (CPUState *)penv->next_cpu;
3729 while (!all_vcpus_paused()) {
3730 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3731 penv = first_cpu;
3732 while (penv) {
3733 qemu_thread_signal(penv->thread, SIG_IPI);
3734 penv = (CPUState *)penv->next_cpu;
3739 static void resume_all_vcpus(void)
3741 CPUState *penv = first_cpu;
3743 while (penv) {
3744 penv->stop = 0;
3745 penv->stopped = 0;
3746 qemu_thread_signal(penv->thread, SIG_IPI);
3747 qemu_cpu_kick(penv);
3748 penv = (CPUState *)penv->next_cpu;
3752 static void tcg_init_vcpu(void *_env)
3754 CPUState *env = _env;
3755 /* share a single thread for all cpus with TCG */
3756 if (!tcg_cpu_thread) {
3757 env->thread = qemu_mallocz(sizeof(QemuThread));
3758 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3759 qemu_cond_init(env->halt_cond);
3760 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3761 while (env->created == 0)
3762 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3763 tcg_cpu_thread = env->thread;
3764 tcg_halt_cond = env->halt_cond;
3765 } else {
3766 env->thread = tcg_cpu_thread;
3767 env->halt_cond = tcg_halt_cond;
3771 static void kvm_start_vcpu(CPUState *env)
3773 env->thread = qemu_mallocz(sizeof(QemuThread));
3774 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3775 qemu_cond_init(env->halt_cond);
3776 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3777 while (env->created == 0)
3778 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3781 void qemu_init_vcpu(void *_env)
3783 CPUState *env = _env;
3785 env->nr_cores = smp_cores;
3786 env->nr_threads = smp_threads;
3787 if (kvm_enabled())
3788 kvm_start_vcpu(env);
3789 else
3790 tcg_init_vcpu(env);
3793 void qemu_notify_event(void)
3795 qemu_event_increment();
3798 void vm_stop(int reason)
3800 QemuThread me;
3801 qemu_thread_self(&me);
3803 if (!qemu_thread_equal(&me, &io_thread)) {
3804 qemu_system_vmstop_request(reason);
3806 * FIXME: should not return to device code in case
3807 * vm_stop() has been requested.
3809 if (cpu_single_env) {
3810 cpu_exit(cpu_single_env);
3811 cpu_single_env->stop = 1;
3813 return;
3815 do_vm_stop(reason);
3818 #endif
3821 #ifdef _WIN32
3822 static void host_main_loop_wait(int *timeout)
3824 int ret, ret2, i;
3825 PollingEntry *pe;
3828 /* XXX: need to suppress polling by better using win32 events */
3829 ret = 0;
3830 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3831 ret |= pe->func(pe->opaque);
3833 if (ret == 0) {
3834 int err;
3835 WaitObjects *w = &wait_objects;
3837 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3838 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3839 if (w->func[ret - WAIT_OBJECT_0])
3840 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3842 /* Check for additional signaled events */
3843 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3845 /* Check if event is signaled */
3846 ret2 = WaitForSingleObject(w->events[i], 0);
3847 if(ret2 == WAIT_OBJECT_0) {
3848 if (w->func[i])
3849 w->func[i](w->opaque[i]);
3850 } else if (ret2 == WAIT_TIMEOUT) {
3851 } else {
3852 err = GetLastError();
3853 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3856 } else if (ret == WAIT_TIMEOUT) {
3857 } else {
3858 err = GetLastError();
3859 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3863 *timeout = 0;
3865 #else
3866 static void host_main_loop_wait(int *timeout)
3869 #endif
3871 void main_loop_wait(int timeout)
3873 IOHandlerRecord *ioh;
3874 fd_set rfds, wfds, xfds;
3875 int ret, nfds;
3876 struct timeval tv;
3878 qemu_bh_update_timeout(&timeout);
3880 host_main_loop_wait(&timeout);
3882 /* poll any events */
3883 /* XXX: separate device handlers from system ones */
3884 nfds = -1;
3885 FD_ZERO(&rfds);
3886 FD_ZERO(&wfds);
3887 FD_ZERO(&xfds);
3888 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3889 if (ioh->deleted)
3890 continue;
3891 if (ioh->fd_read &&
3892 (!ioh->fd_read_poll ||
3893 ioh->fd_read_poll(ioh->opaque) != 0)) {
3894 FD_SET(ioh->fd, &rfds);
3895 if (ioh->fd > nfds)
3896 nfds = ioh->fd;
3898 if (ioh->fd_write) {
3899 FD_SET(ioh->fd, &wfds);
3900 if (ioh->fd > nfds)
3901 nfds = ioh->fd;
3905 tv.tv_sec = timeout / 1000;
3906 tv.tv_usec = (timeout % 1000) * 1000;
3908 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3910 qemu_mutex_unlock_iothread();
3911 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3912 qemu_mutex_lock_iothread();
3913 if (ret > 0) {
3914 IOHandlerRecord **pioh;
3916 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3917 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3918 ioh->fd_read(ioh->opaque);
3920 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3921 ioh->fd_write(ioh->opaque);
3925 /* remove deleted IO handlers */
3926 pioh = &first_io_handler;
3927 while (*pioh) {
3928 ioh = *pioh;
3929 if (ioh->deleted) {
3930 *pioh = ioh->next;
3931 qemu_free(ioh);
3932 } else
3933 pioh = &ioh->next;
3937 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3939 qemu_run_all_timers();
3941 /* Check bottom-halves last in case any of the earlier events triggered
3942 them. */
3943 qemu_bh_poll();
3947 static int qemu_cpu_exec(CPUState *env)
3949 int ret;
3950 #ifdef CONFIG_PROFILER
3951 int64_t ti;
3952 #endif
3954 #ifdef CONFIG_PROFILER
3955 ti = profile_getclock();
3956 #endif
3957 if (use_icount) {
3958 int64_t count;
3959 int decr;
3960 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3961 env->icount_decr.u16.low = 0;
3962 env->icount_extra = 0;
3963 count = qemu_next_deadline();
3964 count = (count + (1 << icount_time_shift) - 1)
3965 >> icount_time_shift;
3966 qemu_icount += count;
3967 decr = (count > 0xffff) ? 0xffff : count;
3968 count -= decr;
3969 env->icount_decr.u16.low = decr;
3970 env->icount_extra = count;
3972 ret = cpu_exec(env);
3973 #ifdef CONFIG_PROFILER
3974 qemu_time += profile_getclock() - ti;
3975 #endif
3976 if (use_icount) {
3977 /* Fold pending instructions back into the
3978 instruction counter, and clear the interrupt flag. */
3979 qemu_icount -= (env->icount_decr.u16.low
3980 + env->icount_extra);
3981 env->icount_decr.u32 = 0;
3982 env->icount_extra = 0;
3984 return ret;
3987 static void tcg_cpu_exec(void)
3989 int ret = 0;
3991 if (next_cpu == NULL)
3992 next_cpu = first_cpu;
3993 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3994 CPUState *env = cur_cpu = next_cpu;
3996 qemu_clock_enable(vm_clock,
3997 (cur_cpu->singlestep_enabled & SSTEP_NOTIMER) == 0);
3999 if (alarm_timer->pending)
4000 break;
4001 if (cpu_can_run(env))
4002 ret = qemu_cpu_exec(env);
4003 else if (env->stop)
4004 break;
4006 if (ret == EXCP_DEBUG) {
4007 gdb_set_stop_cpu(env);
4008 debug_requested = 1;
4009 break;
4014 static int cpu_has_work(CPUState *env)
4016 if (env->stop)
4017 return 1;
4018 if (env->stopped)
4019 return 0;
4020 if (!env->halted)
4021 return 1;
4022 if (qemu_cpu_has_work(env))
4023 return 1;
4024 return 0;
4027 static int tcg_has_work(void)
4029 CPUState *env;
4031 for (env = first_cpu; env != NULL; env = env->next_cpu)
4032 if (cpu_has_work(env))
4033 return 1;
4034 return 0;
4037 static int qemu_calculate_timeout(void)
4039 #ifndef CONFIG_IOTHREAD
4040 int timeout;
4042 if (!vm_running)
4043 timeout = 5000;
4044 else if (tcg_has_work())
4045 timeout = 0;
4046 else if (!use_icount)
4047 timeout = 5000;
4048 else {
4049 /* XXX: use timeout computed from timers */
4050 int64_t add;
4051 int64_t delta;
4052 /* Advance virtual time to the next event. */
4053 if (use_icount == 1) {
4054 /* When not using an adaptive execution frequency
4055 we tend to get badly out of sync with real time,
4056 so just delay for a reasonable amount of time. */
4057 delta = 0;
4058 } else {
4059 delta = cpu_get_icount() - cpu_get_clock();
4061 if (delta > 0) {
4062 /* If virtual time is ahead of real time then just
4063 wait for IO. */
4064 timeout = (delta / 1000000) + 1;
4065 } else {
4066 /* Wait for either IO to occur or the next
4067 timer event. */
4068 add = qemu_next_deadline();
4069 /* We advance the timer before checking for IO.
4070 Limit the amount we advance so that early IO
4071 activity won't get the guest too far ahead. */
4072 if (add > 10000000)
4073 add = 10000000;
4074 delta += add;
4075 add = (add + (1 << icount_time_shift) - 1)
4076 >> icount_time_shift;
4077 qemu_icount += add;
4078 timeout = delta / 1000000;
4079 if (timeout < 0)
4080 timeout = 0;
4084 return timeout;
4085 #else /* CONFIG_IOTHREAD */
4086 return 1000;
4087 #endif
4090 static int vm_can_run(void)
4092 if (powerdown_requested)
4093 return 0;
4094 if (reset_requested)
4095 return 0;
4096 if (shutdown_requested)
4097 return 0;
4098 if (debug_requested)
4099 return 0;
4100 return 1;
4103 qemu_irq qemu_system_powerdown;
4105 static void main_loop(void)
4107 int r;
4109 #ifdef CONFIG_IOTHREAD
4110 qemu_system_ready = 1;
4111 qemu_cond_broadcast(&qemu_system_cond);
4112 #endif
4114 for (;;) {
4115 do {
4116 #ifdef CONFIG_PROFILER
4117 int64_t ti;
4118 #endif
4119 #ifndef CONFIG_IOTHREAD
4120 tcg_cpu_exec();
4121 #endif
4122 #ifdef CONFIG_PROFILER
4123 ti = profile_getclock();
4124 #endif
4125 main_loop_wait(qemu_calculate_timeout());
4126 #ifdef CONFIG_PROFILER
4127 dev_time += profile_getclock() - ti;
4128 #endif
4129 } while (vm_can_run());
4131 if (qemu_debug_requested()) {
4132 vm_stop(EXCP_DEBUG);
4134 if (qemu_shutdown_requested()) {
4135 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
4136 if (no_shutdown) {
4137 vm_stop(0);
4138 no_shutdown = 0;
4139 } else
4140 break;
4142 if (qemu_reset_requested()) {
4143 pause_all_vcpus();
4144 qemu_system_reset();
4145 resume_all_vcpus();
4147 if (qemu_powerdown_requested()) {
4148 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
4149 qemu_irq_raise(qemu_system_powerdown);
4151 if ((r = qemu_vmstop_requested())) {
4152 vm_stop(r);
4155 pause_all_vcpus();
4158 static void version(void)
4160 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4163 static void help(int exitcode)
4165 const char *options_help =
4166 #define DEF(option, opt_arg, opt_enum, opt_help) \
4167 opt_help
4168 #define DEFHEADING(text) stringify(text) "\n"
4169 #include "qemu-options.h"
4170 #undef DEF
4171 #undef DEFHEADING
4172 #undef GEN_DOCS
4174 version();
4175 printf("usage: %s [options] [disk_image]\n"
4176 "\n"
4177 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4178 "\n"
4179 "%s\n"
4180 "During emulation, the following keys are useful:\n"
4181 "ctrl-alt-f toggle full screen\n"
4182 "ctrl-alt-n switch to virtual console 'n'\n"
4183 "ctrl-alt toggle mouse and keyboard grab\n"
4184 "\n"
4185 "When using -nographic, press 'ctrl-a h' to get some help.\n",
4186 "qemu",
4187 options_help);
4188 exit(exitcode);
4191 #define HAS_ARG 0x0001
4193 enum {
4194 #define DEF(option, opt_arg, opt_enum, opt_help) \
4195 opt_enum,
4196 #define DEFHEADING(text)
4197 #include "qemu-options.h"
4198 #undef DEF
4199 #undef DEFHEADING
4200 #undef GEN_DOCS
4203 typedef struct QEMUOption {
4204 const char *name;
4205 int flags;
4206 int index;
4207 } QEMUOption;
4209 static const QEMUOption qemu_options[] = {
4210 { "h", 0, QEMU_OPTION_h },
4211 #define DEF(option, opt_arg, opt_enum, opt_help) \
4212 { option, opt_arg, opt_enum },
4213 #define DEFHEADING(text)
4214 #include "qemu-options.h"
4215 #undef DEF
4216 #undef DEFHEADING
4217 #undef GEN_DOCS
4218 { NULL },
4221 #ifdef HAS_AUDIO
4222 struct soundhw soundhw[] = {
4223 #ifdef HAS_AUDIO_CHOICE
4224 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4226 "pcspk",
4227 "PC speaker",
4230 { .init_isa = pcspk_audio_init }
4232 #endif
4234 #ifdef CONFIG_SB16
4236 "sb16",
4237 "Creative Sound Blaster 16",
4240 { .init_isa = SB16_init }
4242 #endif
4244 #ifdef CONFIG_CS4231A
4246 "cs4231a",
4247 "CS4231A",
4250 { .init_isa = cs4231a_init }
4252 #endif
4254 #ifdef CONFIG_ADLIB
4256 "adlib",
4257 #ifdef HAS_YMF262
4258 "Yamaha YMF262 (OPL3)",
4259 #else
4260 "Yamaha YM3812 (OPL2)",
4261 #endif
4264 { .init_isa = Adlib_init }
4266 #endif
4268 #ifdef CONFIG_GUS
4270 "gus",
4271 "Gravis Ultrasound GF1",
4274 { .init_isa = GUS_init }
4276 #endif
4278 #ifdef CONFIG_AC97
4280 "ac97",
4281 "Intel 82801AA AC97 Audio",
4284 { .init_pci = ac97_init }
4286 #endif
4288 #ifdef CONFIG_ES1370
4290 "es1370",
4291 "ENSONIQ AudioPCI ES1370",
4294 { .init_pci = es1370_init }
4296 #endif
4298 #endif /* HAS_AUDIO_CHOICE */
4300 { NULL, NULL, 0, 0, { NULL } }
4303 static void select_soundhw (const char *optarg)
4305 struct soundhw *c;
4307 if (*optarg == '?') {
4308 show_valid_cards:
4310 printf ("Valid sound card names (comma separated):\n");
4311 for (c = soundhw; c->name; ++c) {
4312 printf ("%-11s %s\n", c->name, c->descr);
4314 printf ("\n-soundhw all will enable all of the above\n");
4315 exit (*optarg != '?');
4317 else {
4318 size_t l;
4319 const char *p;
4320 char *e;
4321 int bad_card = 0;
4323 if (!strcmp (optarg, "all")) {
4324 for (c = soundhw; c->name; ++c) {
4325 c->enabled = 1;
4327 return;
4330 p = optarg;
4331 while (*p) {
4332 e = strchr (p, ',');
4333 l = !e ? strlen (p) : (size_t) (e - p);
4335 for (c = soundhw; c->name; ++c) {
4336 if (!strncmp (c->name, p, l) && !c->name[l]) {
4337 c->enabled = 1;
4338 break;
4342 if (!c->name) {
4343 if (l > 80) {
4344 fprintf (stderr,
4345 "Unknown sound card name (too big to show)\n");
4347 else {
4348 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4349 (int) l, p);
4351 bad_card = 1;
4353 p += l + (e != NULL);
4356 if (bad_card)
4357 goto show_valid_cards;
4360 #endif
4362 static void select_vgahw (const char *p)
4364 const char *opts;
4366 default_vga = 0;
4367 vga_interface_type = VGA_NONE;
4368 if (strstart(p, "std", &opts)) {
4369 vga_interface_type = VGA_STD;
4370 } else if (strstart(p, "cirrus", &opts)) {
4371 vga_interface_type = VGA_CIRRUS;
4372 } else if (strstart(p, "vmware", &opts)) {
4373 vga_interface_type = VGA_VMWARE;
4374 } else if (strstart(p, "xenfb", &opts)) {
4375 vga_interface_type = VGA_XENFB;
4376 } else if (!strstart(p, "none", &opts)) {
4377 invalid_vga:
4378 fprintf(stderr, "Unknown vga type: %s\n", p);
4379 exit(1);
4381 while (*opts) {
4382 const char *nextopt;
4384 if (strstart(opts, ",retrace=", &nextopt)) {
4385 opts = nextopt;
4386 if (strstart(opts, "dumb", &nextopt))
4387 vga_retrace_method = VGA_RETRACE_DUMB;
4388 else if (strstart(opts, "precise", &nextopt))
4389 vga_retrace_method = VGA_RETRACE_PRECISE;
4390 else goto invalid_vga;
4391 } else goto invalid_vga;
4392 opts = nextopt;
4396 #ifdef TARGET_I386
4397 static int balloon_parse(const char *arg)
4399 QemuOpts *opts;
4401 if (strcmp(arg, "none") == 0) {
4402 return 0;
4405 if (!strncmp(arg, "virtio", 6)) {
4406 if (arg[6] == ',') {
4407 /* have params -> parse them */
4408 opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
4409 if (!opts)
4410 return -1;
4411 } else {
4412 /* create empty opts */
4413 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4415 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4416 return 0;
4419 return -1;
4421 #endif
4423 #ifdef _WIN32
4424 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4426 exit(STATUS_CONTROL_C_EXIT);
4427 return TRUE;
4429 #endif
4431 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4433 int ret;
4435 if(strlen(str) != 36)
4436 return -1;
4438 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4439 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4440 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4442 if(ret != 16)
4443 return -1;
4445 #ifdef TARGET_I386
4446 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4447 #endif
4449 return 0;
4452 #ifndef _WIN32
4454 static void termsig_handler(int signal)
4456 qemu_system_shutdown_request();
4459 static void sigchld_handler(int signal)
4461 waitpid(-1, NULL, WNOHANG);
4464 static void sighandler_setup(void)
4466 struct sigaction act;
4468 memset(&act, 0, sizeof(act));
4469 act.sa_handler = termsig_handler;
4470 sigaction(SIGINT, &act, NULL);
4471 sigaction(SIGHUP, &act, NULL);
4472 sigaction(SIGTERM, &act, NULL);
4474 act.sa_handler = sigchld_handler;
4475 act.sa_flags = SA_NOCLDSTOP;
4476 sigaction(SIGCHLD, &act, NULL);
4479 #endif
4481 #ifdef _WIN32
4482 /* Look for support files in the same directory as the executable. */
4483 static char *find_datadir(const char *argv0)
4485 char *p;
4486 char buf[MAX_PATH];
4487 DWORD len;
4489 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4490 if (len == 0) {
4491 return NULL;
4494 buf[len] = 0;
4495 p = buf + len - 1;
4496 while (p != buf && *p != '\\')
4497 p--;
4498 *p = 0;
4499 if (access(buf, R_OK) == 0) {
4500 return qemu_strdup(buf);
4502 return NULL;
4504 #else /* !_WIN32 */
4506 /* Find a likely location for support files using the location of the binary.
4507 For installed binaries this will be "$bindir/../share/qemu". When
4508 running from the build tree this will be "$bindir/../pc-bios". */
4509 #define SHARE_SUFFIX "/share/qemu"
4510 #define BUILD_SUFFIX "/pc-bios"
4511 static char *find_datadir(const char *argv0)
4513 char *dir;
4514 char *p = NULL;
4515 char *res;
4516 char buf[PATH_MAX];
4517 size_t max_len;
4519 #if defined(__linux__)
4521 int len;
4522 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4523 if (len > 0) {
4524 buf[len] = 0;
4525 p = buf;
4528 #elif defined(__FreeBSD__)
4530 int len;
4531 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4532 if (len > 0) {
4533 buf[len] = 0;
4534 p = buf;
4537 #endif
4538 /* If we don't have any way of figuring out the actual executable
4539 location then try argv[0]. */
4540 if (!p) {
4541 p = realpath(argv0, buf);
4542 if (!p) {
4543 return NULL;
4546 dir = dirname(p);
4547 dir = dirname(dir);
4549 max_len = strlen(dir) +
4550 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4551 res = qemu_mallocz(max_len);
4552 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4553 if (access(res, R_OK)) {
4554 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4555 if (access(res, R_OK)) {
4556 qemu_free(res);
4557 res = NULL;
4561 return res;
4563 #undef SHARE_SUFFIX
4564 #undef BUILD_SUFFIX
4565 #endif
4567 char *qemu_find_file(int type, const char *name)
4569 int len;
4570 const char *subdir;
4571 char *buf;
4573 /* If name contains path separators then try it as a straight path. */
4574 if ((strchr(name, '/') || strchr(name, '\\'))
4575 && access(name, R_OK) == 0) {
4576 return qemu_strdup(name);
4578 switch (type) {
4579 case QEMU_FILE_TYPE_BIOS:
4580 subdir = "";
4581 break;
4582 case QEMU_FILE_TYPE_KEYMAP:
4583 subdir = "keymaps/";
4584 break;
4585 default:
4586 abort();
4588 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4589 buf = qemu_mallocz(len);
4590 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4591 if (access(buf, R_OK)) {
4592 qemu_free(buf);
4593 return NULL;
4595 return buf;
4598 static int device_help_func(QemuOpts *opts, void *opaque)
4600 return qdev_device_help(opts);
4603 static int device_init_func(QemuOpts *opts, void *opaque)
4605 DeviceState *dev;
4607 dev = qdev_device_add(opts);
4608 if (!dev)
4609 return -1;
4610 return 0;
4613 static int chardev_init_func(QemuOpts *opts, void *opaque)
4615 CharDriverState *chr;
4617 chr = qemu_chr_open_opts(opts, NULL);
4618 if (!chr)
4619 return -1;
4620 return 0;
4623 static int mon_init_func(QemuOpts *opts, void *opaque)
4625 CharDriverState *chr;
4626 const char *chardev;
4627 const char *mode;
4628 int flags;
4630 mode = qemu_opt_get(opts, "mode");
4631 if (mode == NULL) {
4632 mode = "readline";
4634 if (strcmp(mode, "readline") == 0) {
4635 flags = MONITOR_USE_READLINE;
4636 } else if (strcmp(mode, "control") == 0) {
4637 flags = MONITOR_USE_CONTROL;
4638 } else {
4639 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4640 exit(1);
4643 if (qemu_opt_get_bool(opts, "default", 0))
4644 flags |= MONITOR_IS_DEFAULT;
4646 chardev = qemu_opt_get(opts, "chardev");
4647 chr = qemu_chr_find(chardev);
4648 if (chr == NULL) {
4649 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4650 exit(1);
4653 monitor_init(chr, flags);
4654 return 0;
4657 static void monitor_parse(const char *optarg, const char *mode)
4659 static int monitor_device_index = 0;
4660 QemuOpts *opts;
4661 const char *p;
4662 char label[32];
4663 int def = 0;
4665 if (strstart(optarg, "chardev:", &p)) {
4666 snprintf(label, sizeof(label), "%s", p);
4667 } else {
4668 if (monitor_device_index) {
4669 snprintf(label, sizeof(label), "monitor%d",
4670 monitor_device_index);
4671 } else {
4672 snprintf(label, sizeof(label), "monitor");
4673 def = 1;
4675 opts = qemu_chr_parse_compat(label, optarg);
4676 if (!opts) {
4677 fprintf(stderr, "parse error: %s\n", optarg);
4678 exit(1);
4682 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4683 if (!opts) {
4684 fprintf(stderr, "duplicate chardev: %s\n", label);
4685 exit(1);
4687 qemu_opt_set(opts, "mode", mode);
4688 qemu_opt_set(opts, "chardev", label);
4689 if (def)
4690 qemu_opt_set(opts, "default", "on");
4691 monitor_device_index++;
4694 struct device_config {
4695 enum {
4696 DEV_USB, /* -usbdevice */
4697 DEV_BT, /* -bt */
4698 DEV_SERIAL, /* -serial */
4699 DEV_PARALLEL, /* -parallel */
4700 DEV_VIRTCON, /* -virtioconsole */
4701 DEV_DEBUGCON, /* -debugcon */
4702 } type;
4703 const char *cmdline;
4704 QTAILQ_ENTRY(device_config) next;
4706 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4708 static void add_device_config(int type, const char *cmdline)
4710 struct device_config *conf;
4712 conf = qemu_mallocz(sizeof(*conf));
4713 conf->type = type;
4714 conf->cmdline = cmdline;
4715 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4718 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4720 struct device_config *conf;
4721 int rc;
4723 QTAILQ_FOREACH(conf, &device_configs, next) {
4724 if (conf->type != type)
4725 continue;
4726 rc = func(conf->cmdline);
4727 if (0 != rc)
4728 return rc;
4730 return 0;
4733 static int serial_parse(const char *devname)
4735 static int index = 0;
4736 char label[32];
4738 if (strcmp(devname, "none") == 0)
4739 return 0;
4740 if (index == MAX_SERIAL_PORTS) {
4741 fprintf(stderr, "qemu: too many serial ports\n");
4742 exit(1);
4744 snprintf(label, sizeof(label), "serial%d", index);
4745 serial_hds[index] = qemu_chr_open(label, devname, NULL);
4746 if (!serial_hds[index]) {
4747 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4748 devname, strerror(errno));
4749 return -1;
4751 index++;
4752 return 0;
4755 static int parallel_parse(const char *devname)
4757 static int index = 0;
4758 char label[32];
4760 if (strcmp(devname, "none") == 0)
4761 return 0;
4762 if (index == MAX_PARALLEL_PORTS) {
4763 fprintf(stderr, "qemu: too many parallel ports\n");
4764 exit(1);
4766 snprintf(label, sizeof(label), "parallel%d", index);
4767 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4768 if (!parallel_hds[index]) {
4769 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4770 devname, strerror(errno));
4771 return -1;
4773 index++;
4774 return 0;
4777 static int virtcon_parse(const char *devname)
4779 static int index = 0;
4780 char label[32];
4781 QemuOpts *bus_opts, *dev_opts;
4783 if (strcmp(devname, "none") == 0)
4784 return 0;
4785 if (index == MAX_VIRTIO_CONSOLES) {
4786 fprintf(stderr, "qemu: too many virtio consoles\n");
4787 exit(1);
4790 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4791 qemu_opt_set(bus_opts, "driver", "virtio-serial");
4793 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4794 qemu_opt_set(dev_opts, "driver", "virtconsole");
4796 snprintf(label, sizeof(label), "virtcon%d", index);
4797 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
4798 if (!virtcon_hds[index]) {
4799 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
4800 devname, strerror(errno));
4801 return -1;
4803 qemu_opt_set(dev_opts, "chardev", label);
4805 index++;
4806 return 0;
4809 static int debugcon_parse(const char *devname)
4811 QemuOpts *opts;
4813 if (!qemu_chr_open("debugcon", devname, NULL)) {
4814 exit(1);
4816 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
4817 if (!opts) {
4818 fprintf(stderr, "qemu: already have a debugcon device\n");
4819 exit(1);
4821 qemu_opt_set(opts, "driver", "isa-debugcon");
4822 qemu_opt_set(opts, "chardev", "debugcon");
4823 return 0;
4826 static const QEMUOption *lookup_opt(int argc, char **argv,
4827 const char **poptarg, int *poptind)
4829 const QEMUOption *popt;
4830 int optind = *poptind;
4831 char *r = argv[optind];
4832 const char *optarg;
4834 loc_set_cmdline(argv, optind, 1);
4835 optind++;
4836 /* Treat --foo the same as -foo. */
4837 if (r[1] == '-')
4838 r++;
4839 popt = qemu_options;
4840 for(;;) {
4841 if (!popt->name) {
4842 error_report("invalid option");
4843 exit(1);
4845 if (!strcmp(popt->name, r + 1))
4846 break;
4847 popt++;
4849 if (popt->flags & HAS_ARG) {
4850 if (optind >= argc) {
4851 error_report("requires an argument");
4852 exit(1);
4854 optarg = argv[optind++];
4855 loc_set_cmdline(argv, optind - 2, 2);
4856 } else {
4857 optarg = NULL;
4860 *poptarg = optarg;
4861 *poptind = optind;
4863 return popt;
4866 int main(int argc, char **argv, char **envp)
4868 const char *gdbstub_dev = NULL;
4869 uint32_t boot_devices_bitmap = 0;
4870 int i;
4871 int snapshot, linux_boot, net_boot;
4872 const char *icount_option = NULL;
4873 const char *initrd_filename;
4874 const char *kernel_filename, *kernel_cmdline;
4875 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4876 DisplayState *ds;
4877 DisplayChangeListener *dcl;
4878 int cyls, heads, secs, translation;
4879 QemuOpts *hda_opts = NULL, *opts;
4880 int optind;
4881 const char *optarg;
4882 const char *loadvm = NULL;
4883 QEMUMachine *machine;
4884 const char *cpu_model;
4885 #ifndef _WIN32
4886 int fds[2];
4887 #endif
4888 int tb_size;
4889 const char *pid_file = NULL;
4890 const char *incoming = NULL;
4891 #ifndef _WIN32
4892 int fd = 0;
4893 struct passwd *pwd = NULL;
4894 const char *chroot_dir = NULL;
4895 const char *run_as = NULL;
4896 #endif
4897 CPUState *env;
4898 int show_vnc_port = 0;
4899 int defconfig = 1;
4901 error_set_progname(argv[0]);
4903 init_clocks();
4905 qemu_cache_utils_init(envp);
4907 QLIST_INIT (&vm_change_state_head);
4908 #ifndef _WIN32
4910 struct sigaction act;
4911 sigfillset(&act.sa_mask);
4912 act.sa_flags = 0;
4913 act.sa_handler = SIG_IGN;
4914 sigaction(SIGPIPE, &act, NULL);
4916 #else
4917 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4918 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4919 QEMU to run on a single CPU */
4921 HANDLE h;
4922 DWORD mask, smask;
4923 int i;
4924 h = GetCurrentProcess();
4925 if (GetProcessAffinityMask(h, &mask, &smask)) {
4926 for(i = 0; i < 32; i++) {
4927 if (mask & (1 << i))
4928 break;
4930 if (i != 32) {
4931 mask = 1 << i;
4932 SetProcessAffinityMask(h, mask);
4936 #endif
4938 module_call_init(MODULE_INIT_MACHINE);
4939 machine = find_default_machine();
4940 cpu_model = NULL;
4941 initrd_filename = NULL;
4942 ram_size = 0;
4943 snapshot = 0;
4944 kernel_filename = NULL;
4945 kernel_cmdline = "";
4946 cyls = heads = secs = 0;
4947 translation = BIOS_ATA_TRANSLATION_AUTO;
4949 for (i = 0; i < MAX_NODES; i++) {
4950 node_mem[i] = 0;
4951 node_cpumask[i] = 0;
4954 nb_numa_nodes = 0;
4955 nb_nics = 0;
4957 tb_size = 0;
4958 autostart= 1;
4960 /* first pass of option parsing */
4961 optind = 1;
4962 while (optind < argc) {
4963 if (argv[optind][0] != '-') {
4964 /* disk image */
4965 optind++;
4966 continue;
4967 } else {
4968 const QEMUOption *popt;
4970 popt = lookup_opt(argc, argv, &optarg, &optind);
4971 switch (popt->index) {
4972 case QEMU_OPTION_nodefconfig:
4973 defconfig=0;
4974 break;
4979 if (defconfig) {
4980 const char *fname;
4981 FILE *fp;
4983 fname = CONFIG_QEMU_CONFDIR "/qemu.conf";
4984 fp = fopen(fname, "r");
4985 if (fp) {
4986 if (qemu_config_parse(fp, fname) != 0) {
4987 exit(1);
4989 fclose(fp);
4992 fname = CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf";
4993 fp = fopen(fname, "r");
4994 if (fp) {
4995 if (qemu_config_parse(fp, fname) != 0) {
4996 exit(1);
4998 fclose(fp);
5001 #if defined(cpudef_setup)
5002 cpudef_setup(); /* parse cpu definitions in target config file */
5003 #endif
5005 /* second pass of option parsing */
5006 optind = 1;
5007 for(;;) {
5008 if (optind >= argc)
5009 break;
5010 if (argv[optind][0] != '-') {
5011 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
5012 } else {
5013 const QEMUOption *popt;
5015 popt = lookup_opt(argc, argv, &optarg, &optind);
5016 switch(popt->index) {
5017 case QEMU_OPTION_M:
5018 machine = find_machine(optarg);
5019 if (!machine) {
5020 QEMUMachine *m;
5021 printf("Supported machines are:\n");
5022 for(m = first_machine; m != NULL; m = m->next) {
5023 if (m->alias)
5024 printf("%-10s %s (alias of %s)\n",
5025 m->alias, m->desc, m->name);
5026 printf("%-10s %s%s\n",
5027 m->name, m->desc,
5028 m->is_default ? " (default)" : "");
5030 exit(*optarg != '?');
5032 break;
5033 case QEMU_OPTION_cpu:
5034 /* hw initialization will check this */
5035 if (*optarg == '?') {
5036 /* XXX: implement xxx_cpu_list for targets that still miss it */
5037 #if defined(cpu_list_id)
5038 cpu_list_id(stdout, &fprintf, optarg);
5039 #elif defined(cpu_list)
5040 cpu_list(stdout, &fprintf); /* deprecated */
5041 #endif
5042 exit(0);
5043 } else {
5044 cpu_model = optarg;
5046 break;
5047 case QEMU_OPTION_initrd:
5048 initrd_filename = optarg;
5049 break;
5050 case QEMU_OPTION_hda:
5051 if (cyls == 0)
5052 hda_opts = drive_add(optarg, HD_ALIAS, 0);
5053 else
5054 hda_opts = drive_add(optarg, HD_ALIAS
5055 ",cyls=%d,heads=%d,secs=%d%s",
5056 0, cyls, heads, secs,
5057 translation == BIOS_ATA_TRANSLATION_LBA ?
5058 ",trans=lba" :
5059 translation == BIOS_ATA_TRANSLATION_NONE ?
5060 ",trans=none" : "");
5061 break;
5062 case QEMU_OPTION_hdb:
5063 case QEMU_OPTION_hdc:
5064 case QEMU_OPTION_hdd:
5065 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5066 break;
5067 case QEMU_OPTION_drive:
5068 drive_add(NULL, "%s", optarg);
5069 break;
5070 case QEMU_OPTION_set:
5071 if (qemu_set_option(optarg) != 0)
5072 exit(1);
5073 break;
5074 case QEMU_OPTION_global:
5075 if (qemu_global_option(optarg) != 0)
5076 exit(1);
5077 break;
5078 case QEMU_OPTION_mtdblock:
5079 drive_add(optarg, MTD_ALIAS);
5080 break;
5081 case QEMU_OPTION_sd:
5082 drive_add(optarg, SD_ALIAS);
5083 break;
5084 case QEMU_OPTION_pflash:
5085 drive_add(optarg, PFLASH_ALIAS);
5086 break;
5087 case QEMU_OPTION_snapshot:
5088 snapshot = 1;
5089 break;
5090 case QEMU_OPTION_hdachs:
5092 const char *p;
5093 p = optarg;
5094 cyls = strtol(p, (char **)&p, 0);
5095 if (cyls < 1 || cyls > 16383)
5096 goto chs_fail;
5097 if (*p != ',')
5098 goto chs_fail;
5099 p++;
5100 heads = strtol(p, (char **)&p, 0);
5101 if (heads < 1 || heads > 16)
5102 goto chs_fail;
5103 if (*p != ',')
5104 goto chs_fail;
5105 p++;
5106 secs = strtol(p, (char **)&p, 0);
5107 if (secs < 1 || secs > 63)
5108 goto chs_fail;
5109 if (*p == ',') {
5110 p++;
5111 if (!strcmp(p, "none"))
5112 translation = BIOS_ATA_TRANSLATION_NONE;
5113 else if (!strcmp(p, "lba"))
5114 translation = BIOS_ATA_TRANSLATION_LBA;
5115 else if (!strcmp(p, "auto"))
5116 translation = BIOS_ATA_TRANSLATION_AUTO;
5117 else
5118 goto chs_fail;
5119 } else if (*p != '\0') {
5120 chs_fail:
5121 fprintf(stderr, "qemu: invalid physical CHS format\n");
5122 exit(1);
5124 if (hda_opts != NULL) {
5125 char num[16];
5126 snprintf(num, sizeof(num), "%d", cyls);
5127 qemu_opt_set(hda_opts, "cyls", num);
5128 snprintf(num, sizeof(num), "%d", heads);
5129 qemu_opt_set(hda_opts, "heads", num);
5130 snprintf(num, sizeof(num), "%d", secs);
5131 qemu_opt_set(hda_opts, "secs", num);
5132 if (translation == BIOS_ATA_TRANSLATION_LBA)
5133 qemu_opt_set(hda_opts, "trans", "lba");
5134 if (translation == BIOS_ATA_TRANSLATION_NONE)
5135 qemu_opt_set(hda_opts, "trans", "none");
5138 break;
5139 case QEMU_OPTION_numa:
5140 if (nb_numa_nodes >= MAX_NODES) {
5141 fprintf(stderr, "qemu: too many NUMA nodes\n");
5142 exit(1);
5144 numa_add(optarg);
5145 break;
5146 case QEMU_OPTION_nographic:
5147 display_type = DT_NOGRAPHIC;
5148 break;
5149 #ifdef CONFIG_CURSES
5150 case QEMU_OPTION_curses:
5151 display_type = DT_CURSES;
5152 break;
5153 #endif
5154 case QEMU_OPTION_portrait:
5155 graphic_rotate = 1;
5156 break;
5157 case QEMU_OPTION_kernel:
5158 kernel_filename = optarg;
5159 break;
5160 case QEMU_OPTION_append:
5161 kernel_cmdline = optarg;
5162 break;
5163 case QEMU_OPTION_cdrom:
5164 drive_add(optarg, CDROM_ALIAS);
5165 break;
5166 case QEMU_OPTION_boot:
5168 static const char * const params[] = {
5169 "order", "once", "menu", NULL
5171 char buf[sizeof(boot_devices)];
5172 char *standard_boot_devices;
5173 int legacy = 0;
5175 if (!strchr(optarg, '=')) {
5176 legacy = 1;
5177 pstrcpy(buf, sizeof(buf), optarg);
5178 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5179 fprintf(stderr,
5180 "qemu: unknown boot parameter '%s' in '%s'\n",
5181 buf, optarg);
5182 exit(1);
5185 if (legacy ||
5186 get_param_value(buf, sizeof(buf), "order", optarg)) {
5187 boot_devices_bitmap = parse_bootdevices(buf);
5188 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5190 if (!legacy) {
5191 if (get_param_value(buf, sizeof(buf),
5192 "once", optarg)) {
5193 boot_devices_bitmap |= parse_bootdevices(buf);
5194 standard_boot_devices = qemu_strdup(boot_devices);
5195 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5196 qemu_register_reset(restore_boot_devices,
5197 standard_boot_devices);
5199 if (get_param_value(buf, sizeof(buf),
5200 "menu", optarg)) {
5201 if (!strcmp(buf, "on")) {
5202 boot_menu = 1;
5203 } else if (!strcmp(buf, "off")) {
5204 boot_menu = 0;
5205 } else {
5206 fprintf(stderr,
5207 "qemu: invalid option value '%s'\n",
5208 buf);
5209 exit(1);
5214 break;
5215 case QEMU_OPTION_fda:
5216 case QEMU_OPTION_fdb:
5217 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5218 break;
5219 #ifdef TARGET_I386
5220 case QEMU_OPTION_no_fd_bootchk:
5221 fd_bootchk = 0;
5222 break;
5223 #endif
5224 case QEMU_OPTION_netdev:
5225 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
5226 exit(1);
5228 break;
5229 case QEMU_OPTION_net:
5230 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
5231 exit(1);
5233 break;
5234 #ifdef CONFIG_SLIRP
5235 case QEMU_OPTION_tftp:
5236 legacy_tftp_prefix = optarg;
5237 break;
5238 case QEMU_OPTION_bootp:
5239 legacy_bootp_filename = optarg;
5240 break;
5241 #ifndef _WIN32
5242 case QEMU_OPTION_smb:
5243 if (net_slirp_smb(optarg) < 0)
5244 exit(1);
5245 break;
5246 #endif
5247 case QEMU_OPTION_redir:
5248 if (net_slirp_redir(optarg) < 0)
5249 exit(1);
5250 break;
5251 #endif
5252 case QEMU_OPTION_bt:
5253 add_device_config(DEV_BT, optarg);
5254 break;
5255 #ifdef HAS_AUDIO
5256 case QEMU_OPTION_audio_help:
5257 AUD_help ();
5258 exit (0);
5259 break;
5260 case QEMU_OPTION_soundhw:
5261 select_soundhw (optarg);
5262 break;
5263 #endif
5264 case QEMU_OPTION_h:
5265 help(0);
5266 break;
5267 case QEMU_OPTION_version:
5268 version();
5269 exit(0);
5270 break;
5271 case QEMU_OPTION_m: {
5272 uint64_t value;
5273 char *ptr;
5275 value = strtoul(optarg, &ptr, 10);
5276 switch (*ptr) {
5277 case 0: case 'M': case 'm':
5278 value <<= 20;
5279 break;
5280 case 'G': case 'g':
5281 value <<= 30;
5282 break;
5283 default:
5284 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5285 exit(1);
5288 /* On 32-bit hosts, QEMU is limited by virtual address space */
5289 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5290 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5291 exit(1);
5293 if (value != (uint64_t)(ram_addr_t)value) {
5294 fprintf(stderr, "qemu: ram size too large\n");
5295 exit(1);
5297 ram_size = value;
5298 break;
5300 case QEMU_OPTION_mempath:
5301 mem_path = optarg;
5302 break;
5303 #ifdef MAP_POPULATE
5304 case QEMU_OPTION_mem_prealloc:
5305 mem_prealloc = 1;
5306 break;
5307 #endif
5308 case QEMU_OPTION_d:
5310 int mask;
5311 const CPULogItem *item;
5313 mask = cpu_str_to_log_mask(optarg);
5314 if (!mask) {
5315 printf("Log items (comma separated):\n");
5316 for(item = cpu_log_items; item->mask != 0; item++) {
5317 printf("%-10s %s\n", item->name, item->help);
5319 exit(1);
5321 cpu_set_log(mask);
5323 break;
5324 case QEMU_OPTION_s:
5325 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5326 break;
5327 case QEMU_OPTION_gdb:
5328 gdbstub_dev = optarg;
5329 break;
5330 case QEMU_OPTION_L:
5331 data_dir = optarg;
5332 break;
5333 case QEMU_OPTION_bios:
5334 bios_name = optarg;
5335 break;
5336 case QEMU_OPTION_singlestep:
5337 singlestep = 1;
5338 break;
5339 case QEMU_OPTION_S:
5340 autostart = 0;
5341 break;
5342 case QEMU_OPTION_k:
5343 keyboard_layout = optarg;
5344 break;
5345 case QEMU_OPTION_localtime:
5346 rtc_utc = 0;
5347 break;
5348 case QEMU_OPTION_vga:
5349 select_vgahw (optarg);
5350 break;
5351 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5352 case QEMU_OPTION_g:
5354 const char *p;
5355 int w, h, depth;
5356 p = optarg;
5357 w = strtol(p, (char **)&p, 10);
5358 if (w <= 0) {
5359 graphic_error:
5360 fprintf(stderr, "qemu: invalid resolution or depth\n");
5361 exit(1);
5363 if (*p != 'x')
5364 goto graphic_error;
5365 p++;
5366 h = strtol(p, (char **)&p, 10);
5367 if (h <= 0)
5368 goto graphic_error;
5369 if (*p == 'x') {
5370 p++;
5371 depth = strtol(p, (char **)&p, 10);
5372 if (depth != 8 && depth != 15 && depth != 16 &&
5373 depth != 24 && depth != 32)
5374 goto graphic_error;
5375 } else if (*p == '\0') {
5376 depth = graphic_depth;
5377 } else {
5378 goto graphic_error;
5381 graphic_width = w;
5382 graphic_height = h;
5383 graphic_depth = depth;
5385 break;
5386 #endif
5387 case QEMU_OPTION_echr:
5389 char *r;
5390 term_escape_char = strtol(optarg, &r, 0);
5391 if (r == optarg)
5392 printf("Bad argument to echr\n");
5393 break;
5395 case QEMU_OPTION_monitor:
5396 monitor_parse(optarg, "readline");
5397 default_monitor = 0;
5398 break;
5399 case QEMU_OPTION_qmp:
5400 monitor_parse(optarg, "control");
5401 default_monitor = 0;
5402 break;
5403 case QEMU_OPTION_mon:
5404 opts = qemu_opts_parse(&qemu_mon_opts, optarg, 1);
5405 if (!opts) {
5406 fprintf(stderr, "parse error: %s\n", optarg);
5407 exit(1);
5409 default_monitor = 0;
5410 break;
5411 case QEMU_OPTION_chardev:
5412 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, 1);
5413 if (!opts) {
5414 fprintf(stderr, "parse error: %s\n", optarg);
5415 exit(1);
5417 break;
5418 case QEMU_OPTION_serial:
5419 add_device_config(DEV_SERIAL, optarg);
5420 default_serial = 0;
5421 if (strncmp(optarg, "mon:", 4) == 0) {
5422 default_monitor = 0;
5424 break;
5425 case QEMU_OPTION_watchdog:
5426 if (watchdog) {
5427 fprintf(stderr,
5428 "qemu: only one watchdog option may be given\n");
5429 return 1;
5431 watchdog = optarg;
5432 break;
5433 case QEMU_OPTION_watchdog_action:
5434 if (select_watchdog_action(optarg) == -1) {
5435 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5436 exit(1);
5438 break;
5439 case QEMU_OPTION_virtiocon:
5440 add_device_config(DEV_VIRTCON, optarg);
5441 default_virtcon = 0;
5442 if (strncmp(optarg, "mon:", 4) == 0) {
5443 default_monitor = 0;
5445 break;
5446 case QEMU_OPTION_parallel:
5447 add_device_config(DEV_PARALLEL, optarg);
5448 default_parallel = 0;
5449 if (strncmp(optarg, "mon:", 4) == 0) {
5450 default_monitor = 0;
5452 break;
5453 case QEMU_OPTION_debugcon:
5454 add_device_config(DEV_DEBUGCON, optarg);
5455 break;
5456 case QEMU_OPTION_loadvm:
5457 loadvm = optarg;
5458 break;
5459 case QEMU_OPTION_full_screen:
5460 full_screen = 1;
5461 break;
5462 #ifdef CONFIG_SDL
5463 case QEMU_OPTION_no_frame:
5464 no_frame = 1;
5465 break;
5466 case QEMU_OPTION_alt_grab:
5467 alt_grab = 1;
5468 break;
5469 case QEMU_OPTION_ctrl_grab:
5470 ctrl_grab = 1;
5471 break;
5472 case QEMU_OPTION_no_quit:
5473 no_quit = 1;
5474 break;
5475 case QEMU_OPTION_sdl:
5476 display_type = DT_SDL;
5477 break;
5478 #endif
5479 case QEMU_OPTION_pidfile:
5480 pid_file = optarg;
5481 break;
5482 #ifdef TARGET_I386
5483 case QEMU_OPTION_win2k_hack:
5484 win2k_install_hack = 1;
5485 break;
5486 case QEMU_OPTION_rtc_td_hack:
5487 rtc_td_hack = 1;
5488 break;
5489 case QEMU_OPTION_acpitable:
5490 if(acpi_table_add(optarg) < 0) {
5491 fprintf(stderr, "Wrong acpi table provided\n");
5492 exit(1);
5494 break;
5495 case QEMU_OPTION_smbios:
5496 if(smbios_entry_add(optarg) < 0) {
5497 fprintf(stderr, "Wrong smbios provided\n");
5498 exit(1);
5500 break;
5501 #endif
5502 #ifdef CONFIG_KVM
5503 case QEMU_OPTION_enable_kvm:
5504 kvm_allowed = 1;
5505 break;
5506 #endif
5507 case QEMU_OPTION_usb:
5508 usb_enabled = 1;
5509 break;
5510 case QEMU_OPTION_usbdevice:
5511 usb_enabled = 1;
5512 add_device_config(DEV_USB, optarg);
5513 break;
5514 case QEMU_OPTION_device:
5515 if (!qemu_opts_parse(&qemu_device_opts, optarg, 1)) {
5516 exit(1);
5518 break;
5519 case QEMU_OPTION_smp:
5520 smp_parse(optarg);
5521 if (smp_cpus < 1) {
5522 fprintf(stderr, "Invalid number of CPUs\n");
5523 exit(1);
5525 if (max_cpus < smp_cpus) {
5526 fprintf(stderr, "maxcpus must be equal to or greater than "
5527 "smp\n");
5528 exit(1);
5530 if (max_cpus > 255) {
5531 fprintf(stderr, "Unsupported number of maxcpus\n");
5532 exit(1);
5534 break;
5535 case QEMU_OPTION_vnc:
5536 display_type = DT_VNC;
5537 vnc_display = optarg;
5538 break;
5539 #ifdef TARGET_I386
5540 case QEMU_OPTION_no_acpi:
5541 acpi_enabled = 0;
5542 break;
5543 case QEMU_OPTION_no_hpet:
5544 no_hpet = 1;
5545 break;
5546 case QEMU_OPTION_balloon:
5547 if (balloon_parse(optarg) < 0) {
5548 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5549 exit(1);
5551 break;
5552 #endif
5553 case QEMU_OPTION_no_reboot:
5554 no_reboot = 1;
5555 break;
5556 case QEMU_OPTION_no_shutdown:
5557 no_shutdown = 1;
5558 break;
5559 case QEMU_OPTION_show_cursor:
5560 cursor_hide = 0;
5561 break;
5562 case QEMU_OPTION_uuid:
5563 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5564 fprintf(stderr, "Fail to parse UUID string."
5565 " Wrong format.\n");
5566 exit(1);
5568 break;
5569 #ifndef _WIN32
5570 case QEMU_OPTION_daemonize:
5571 daemonize = 1;
5572 break;
5573 #endif
5574 case QEMU_OPTION_option_rom:
5575 if (nb_option_roms >= MAX_OPTION_ROMS) {
5576 fprintf(stderr, "Too many option ROMs\n");
5577 exit(1);
5579 option_rom[nb_option_roms] = optarg;
5580 nb_option_roms++;
5581 break;
5582 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5583 case QEMU_OPTION_semihosting:
5584 semihosting_enabled = 1;
5585 break;
5586 #endif
5587 case QEMU_OPTION_name:
5588 qemu_name = qemu_strdup(optarg);
5590 char *p = strchr(qemu_name, ',');
5591 if (p != NULL) {
5592 *p++ = 0;
5593 if (strncmp(p, "process=", 8)) {
5594 fprintf(stderr, "Unknown subargument %s to -name", p);
5595 exit(1);
5597 p += 8;
5598 set_proc_name(p);
5601 break;
5602 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5603 case QEMU_OPTION_prom_env:
5604 if (nb_prom_envs >= MAX_PROM_ENVS) {
5605 fprintf(stderr, "Too many prom variables\n");
5606 exit(1);
5608 prom_envs[nb_prom_envs] = optarg;
5609 nb_prom_envs++;
5610 break;
5611 #endif
5612 #ifdef TARGET_ARM
5613 case QEMU_OPTION_old_param:
5614 old_param = 1;
5615 break;
5616 #endif
5617 case QEMU_OPTION_clock:
5618 configure_alarms(optarg);
5619 break;
5620 case QEMU_OPTION_startdate:
5621 configure_rtc_date_offset(optarg, 1);
5622 break;
5623 case QEMU_OPTION_rtc:
5624 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, 0);
5625 if (!opts) {
5626 fprintf(stderr, "parse error: %s\n", optarg);
5627 exit(1);
5629 configure_rtc(opts);
5630 break;
5631 case QEMU_OPTION_tb_size:
5632 tb_size = strtol(optarg, NULL, 0);
5633 if (tb_size < 0)
5634 tb_size = 0;
5635 break;
5636 case QEMU_OPTION_icount:
5637 icount_option = optarg;
5638 break;
5639 case QEMU_OPTION_incoming:
5640 incoming = optarg;
5641 break;
5642 case QEMU_OPTION_nodefaults:
5643 default_serial = 0;
5644 default_parallel = 0;
5645 default_virtcon = 0;
5646 default_monitor = 0;
5647 default_vga = 0;
5648 default_net = 0;
5649 default_floppy = 0;
5650 default_cdrom = 0;
5651 default_sdcard = 0;
5652 break;
5653 #ifndef _WIN32
5654 case QEMU_OPTION_chroot:
5655 chroot_dir = optarg;
5656 break;
5657 case QEMU_OPTION_runas:
5658 run_as = optarg;
5659 break;
5660 #endif
5661 #ifdef CONFIG_XEN
5662 case QEMU_OPTION_xen_domid:
5663 xen_domid = atoi(optarg);
5664 break;
5665 case QEMU_OPTION_xen_create:
5666 xen_mode = XEN_CREATE;
5667 break;
5668 case QEMU_OPTION_xen_attach:
5669 xen_mode = XEN_ATTACH;
5670 break;
5671 #endif
5672 case QEMU_OPTION_readconfig:
5674 FILE *fp;
5675 fp = fopen(optarg, "r");
5676 if (fp == NULL) {
5677 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5678 exit(1);
5680 if (qemu_config_parse(fp, optarg) != 0) {
5681 exit(1);
5683 fclose(fp);
5684 break;
5686 case QEMU_OPTION_writeconfig:
5688 FILE *fp;
5689 if (strcmp(optarg, "-") == 0) {
5690 fp = stdout;
5691 } else {
5692 fp = fopen(optarg, "w");
5693 if (fp == NULL) {
5694 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5695 exit(1);
5698 qemu_config_write(fp);
5699 fclose(fp);
5700 break;
5705 loc_set_none();
5707 /* If no data_dir is specified then try to find it relative to the
5708 executable path. */
5709 if (!data_dir) {
5710 data_dir = find_datadir(argv[0]);
5712 /* If all else fails use the install patch specified when building. */
5713 if (!data_dir) {
5714 data_dir = CONFIG_QEMU_SHAREDIR;
5718 * Default to max_cpus = smp_cpus, in case the user doesn't
5719 * specify a max_cpus value.
5721 if (!max_cpus)
5722 max_cpus = smp_cpus;
5724 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5725 if (smp_cpus > machine->max_cpus) {
5726 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5727 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5728 machine->max_cpus);
5729 exit(1);
5732 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5733 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
5735 if (machine->no_serial) {
5736 default_serial = 0;
5738 if (machine->no_parallel) {
5739 default_parallel = 0;
5741 if (!machine->use_virtcon) {
5742 default_virtcon = 0;
5744 if (machine->no_vga) {
5745 default_vga = 0;
5747 if (machine->no_floppy) {
5748 default_floppy = 0;
5750 if (machine->no_cdrom) {
5751 default_cdrom = 0;
5753 if (machine->no_sdcard) {
5754 default_sdcard = 0;
5757 if (display_type == DT_NOGRAPHIC) {
5758 if (default_parallel)
5759 add_device_config(DEV_PARALLEL, "null");
5760 if (default_serial && default_monitor) {
5761 add_device_config(DEV_SERIAL, "mon:stdio");
5762 } else if (default_virtcon && default_monitor) {
5763 add_device_config(DEV_VIRTCON, "mon:stdio");
5764 } else {
5765 if (default_serial)
5766 add_device_config(DEV_SERIAL, "stdio");
5767 if (default_virtcon)
5768 add_device_config(DEV_VIRTCON, "stdio");
5769 if (default_monitor)
5770 monitor_parse("stdio", "readline");
5772 } else {
5773 if (default_serial)
5774 add_device_config(DEV_SERIAL, "vc:80Cx24C");
5775 if (default_parallel)
5776 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
5777 if (default_monitor)
5778 monitor_parse("vc:80Cx24C", "readline");
5779 if (default_virtcon)
5780 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
5782 if (default_vga)
5783 vga_interface_type = VGA_CIRRUS;
5785 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5786 exit(1);
5788 #ifndef _WIN32
5789 if (daemonize) {
5790 pid_t pid;
5792 if (pipe(fds) == -1)
5793 exit(1);
5795 pid = fork();
5796 if (pid > 0) {
5797 uint8_t status;
5798 ssize_t len;
5800 close(fds[1]);
5802 again:
5803 len = read(fds[0], &status, 1);
5804 if (len == -1 && (errno == EINTR))
5805 goto again;
5807 if (len != 1)
5808 exit(1);
5809 else if (status == 1) {
5810 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5811 exit(1);
5812 } else
5813 exit(0);
5814 } else if (pid < 0)
5815 exit(1);
5817 close(fds[0]);
5818 qemu_set_cloexec(fds[1]);
5820 setsid();
5822 pid = fork();
5823 if (pid > 0)
5824 exit(0);
5825 else if (pid < 0)
5826 exit(1);
5828 umask(027);
5830 signal(SIGTSTP, SIG_IGN);
5831 signal(SIGTTOU, SIG_IGN);
5832 signal(SIGTTIN, SIG_IGN);
5834 #endif
5836 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5837 #ifndef _WIN32
5838 if (daemonize) {
5839 uint8_t status = 1;
5840 if (write(fds[1], &status, 1) != 1) {
5841 perror("daemonize. Writing to pipe\n");
5843 } else
5844 #endif
5845 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5846 exit(1);
5849 if (kvm_enabled()) {
5850 int ret;
5852 ret = kvm_init(smp_cpus);
5853 if (ret < 0) {
5854 fprintf(stderr, "failed to initialize KVM\n");
5855 exit(1);
5859 if (qemu_init_main_loop()) {
5860 fprintf(stderr, "qemu_init_main_loop failed\n");
5861 exit(1);
5863 linux_boot = (kernel_filename != NULL);
5865 if (!linux_boot && *kernel_cmdline != '\0') {
5866 fprintf(stderr, "-append only allowed with -kernel option\n");
5867 exit(1);
5870 if (!linux_boot && initrd_filename != NULL) {
5871 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5872 exit(1);
5875 #ifndef _WIN32
5876 /* Win32 doesn't support line-buffering and requires size >= 2 */
5877 setvbuf(stdout, NULL, _IOLBF, 0);
5878 #endif
5880 if (init_timer_alarm() < 0) {
5881 fprintf(stderr, "could not initialize alarm timer\n");
5882 exit(1);
5884 configure_icount(icount_option);
5886 #ifdef _WIN32
5887 socket_init();
5888 #endif
5890 if (net_init_clients() < 0) {
5891 exit(1);
5894 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5895 net_set_boot_mask(net_boot);
5897 /* init the bluetooth world */
5898 if (foreach_device_config(DEV_BT, bt_parse))
5899 exit(1);
5901 /* init the memory */
5902 if (ram_size == 0)
5903 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5905 /* init the dynamic translator */
5906 cpu_exec_init_all(tb_size * 1024 * 1024);
5908 bdrv_init_with_whitelist();
5910 blk_mig_init();
5912 if (default_cdrom) {
5913 /* we always create the cdrom drive, even if no disk is there */
5914 drive_add(NULL, CDROM_ALIAS);
5917 if (default_floppy) {
5918 /* we always create at least one floppy */
5919 drive_add(NULL, FD_ALIAS, 0);
5922 if (default_sdcard) {
5923 /* we always create one sd slot, even if no card is in it */
5924 drive_add(NULL, SD_ALIAS);
5927 /* open the virtual block devices */
5928 if (snapshot)
5929 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5930 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5931 exit(1);
5933 vmstate_register(0, &vmstate_timers ,&timers_state);
5934 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
5935 ram_load, NULL);
5937 if (nb_numa_nodes > 0) {
5938 int i;
5940 if (nb_numa_nodes > smp_cpus) {
5941 nb_numa_nodes = smp_cpus;
5944 /* If no memory size if given for any node, assume the default case
5945 * and distribute the available memory equally across all nodes
5947 for (i = 0; i < nb_numa_nodes; i++) {
5948 if (node_mem[i] != 0)
5949 break;
5951 if (i == nb_numa_nodes) {
5952 uint64_t usedmem = 0;
5954 /* On Linux, the each node's border has to be 8MB aligned,
5955 * the final node gets the rest.
5957 for (i = 0; i < nb_numa_nodes - 1; i++) {
5958 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5959 usedmem += node_mem[i];
5961 node_mem[i] = ram_size - usedmem;
5964 for (i = 0; i < nb_numa_nodes; i++) {
5965 if (node_cpumask[i] != 0)
5966 break;
5968 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5969 * must cope with this anyway, because there are BIOSes out there in
5970 * real machines which also use this scheme.
5972 if (i == nb_numa_nodes) {
5973 for (i = 0; i < smp_cpus; i++) {
5974 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5979 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
5980 exit(1);
5981 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
5982 exit(1);
5983 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
5984 exit(1);
5985 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
5986 exit(1);
5988 module_call_init(MODULE_INIT_DEVICE);
5990 if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
5991 exit(0);
5993 if (watchdog) {
5994 i = select_watchdog(watchdog);
5995 if (i > 0)
5996 exit (i == 1 ? 1 : 0);
5999 if (machine->compat_props) {
6000 qdev_prop_register_global_list(machine->compat_props);
6002 qemu_add_globals();
6004 machine->init(ram_size, boot_devices,
6005 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6007 cpu_synchronize_all_post_init();
6009 #ifndef _WIN32
6010 /* must be after terminal init, SDL library changes signal handlers */
6011 sighandler_setup();
6012 #endif
6014 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6015 for (i = 0; i < nb_numa_nodes; i++) {
6016 if (node_cpumask[i] & (1 << env->cpu_index)) {
6017 env->numa_node = i;
6022 current_machine = machine;
6024 /* init USB devices */
6025 if (usb_enabled) {
6026 if (foreach_device_config(DEV_USB, usb_parse) < 0)
6027 exit(1);
6030 /* init generic devices */
6031 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
6032 exit(1);
6034 net_check_clients();
6036 /* just use the first displaystate for the moment */
6037 ds = get_displaystate();
6039 if (display_type == DT_DEFAULT) {
6040 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6041 display_type = DT_SDL;
6042 #else
6043 display_type = DT_VNC;
6044 vnc_display = "localhost:0,to=99";
6045 show_vnc_port = 1;
6046 #endif
6050 switch (display_type) {
6051 case DT_NOGRAPHIC:
6052 break;
6053 #if defined(CONFIG_CURSES)
6054 case DT_CURSES:
6055 curses_display_init(ds, full_screen);
6056 break;
6057 #endif
6058 #if defined(CONFIG_SDL)
6059 case DT_SDL:
6060 sdl_display_init(ds, full_screen, no_frame);
6061 break;
6062 #elif defined(CONFIG_COCOA)
6063 case DT_SDL:
6064 cocoa_display_init(ds, full_screen);
6065 break;
6066 #endif
6067 case DT_VNC:
6068 vnc_display_init(ds);
6069 if (vnc_display_open(ds, vnc_display) < 0)
6070 exit(1);
6072 if (show_vnc_port) {
6073 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6075 break;
6076 default:
6077 break;
6079 dpy_resize(ds);
6081 dcl = ds->listeners;
6082 while (dcl != NULL) {
6083 if (dcl->dpy_refresh != NULL) {
6084 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6085 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6087 dcl = dcl->next;
6090 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6091 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6092 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6095 text_consoles_set_display(ds);
6097 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
6098 exit(1);
6100 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6101 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6102 gdbstub_dev);
6103 exit(1);
6106 qdev_machine_creation_done();
6108 if (rom_load_all() != 0) {
6109 fprintf(stderr, "rom loading failed\n");
6110 exit(1);
6113 qemu_system_reset();
6114 if (loadvm) {
6115 if (load_vmstate(loadvm) < 0) {
6116 autostart = 0;
6120 if (incoming) {
6121 qemu_start_incoming_migration(incoming);
6122 } else if (autostart) {
6123 vm_start();
6126 #ifndef _WIN32
6127 if (daemonize) {
6128 uint8_t status = 0;
6129 ssize_t len;
6131 again1:
6132 len = write(fds[1], &status, 1);
6133 if (len == -1 && (errno == EINTR))
6134 goto again1;
6136 if (len != 1)
6137 exit(1);
6139 if (chdir("/")) {
6140 perror("not able to chdir to /");
6141 exit(1);
6143 TFR(fd = qemu_open("/dev/null", O_RDWR));
6144 if (fd == -1)
6145 exit(1);
6148 if (run_as) {
6149 pwd = getpwnam(run_as);
6150 if (!pwd) {
6151 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6152 exit(1);
6156 if (chroot_dir) {
6157 if (chroot(chroot_dir) < 0) {
6158 fprintf(stderr, "chroot failed\n");
6159 exit(1);
6161 if (chdir("/")) {
6162 perror("not able to chdir to /");
6163 exit(1);
6167 if (run_as) {
6168 if (setgid(pwd->pw_gid) < 0) {
6169 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6170 exit(1);
6172 if (setuid(pwd->pw_uid) < 0) {
6173 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6174 exit(1);
6176 if (setuid(0) != -1) {
6177 fprintf(stderr, "Dropping privileges failed\n");
6178 exit(1);
6182 if (daemonize) {
6183 dup2(fd, 0);
6184 dup2(fd, 1);
6185 dup2(fd, 2);
6187 close(fd);
6189 #endif
6191 main_loop();
6192 quit_timers();
6193 net_cleanup();
6195 return 0;