error: Replace qemu_error() by error_report()
[qemu/aliguori-queue.git] / vl.c
blob160f30a3205c237628224f0b2f33e2a3ce4ba667
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 static int timer_alarm_pending = 1;
262 /* Conversion factor from emulated instructions to virtual clock ticks. */
263 static int icount_time_shift;
264 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
265 #define MAX_ICOUNT_SHIFT 10
266 /* Compensate for varying guest execution speed. */
267 static int64_t qemu_icount_bias;
268 static QEMUTimer *icount_rt_timer;
269 static QEMUTimer *icount_vm_timer;
270 static QEMUTimer *nographic_timer;
272 uint8_t qemu_uuid[16];
274 static QEMUBootSetHandler *boot_set_handler;
275 static void *boot_set_opaque;
277 #ifdef SIGRTMIN
278 #define SIG_IPI (SIGRTMIN+4)
279 #else
280 #define SIG_IPI SIGUSR1
281 #endif
283 static int default_serial = 1;
284 static int default_parallel = 1;
285 static int default_virtcon = 1;
286 static int default_monitor = 1;
287 static int default_vga = 1;
288 static int default_floppy = 1;
289 static int default_cdrom = 1;
290 static int default_sdcard = 1;
292 static struct {
293 const char *driver;
294 int *flag;
295 } default_list[] = {
296 { .driver = "isa-serial", .flag = &default_serial },
297 { .driver = "isa-parallel", .flag = &default_parallel },
298 { .driver = "isa-fdc", .flag = &default_floppy },
299 { .driver = "ide-drive", .flag = &default_cdrom },
300 { .driver = "virtio-serial-pci", .flag = &default_virtcon },
301 { .driver = "virtio-serial-s390", .flag = &default_virtcon },
302 { .driver = "virtio-serial", .flag = &default_virtcon },
303 { .driver = "VGA", .flag = &default_vga },
304 { .driver = "cirrus-vga", .flag = &default_vga },
305 { .driver = "vmware-svga", .flag = &default_vga },
308 static int default_driver_check(QemuOpts *opts, void *opaque)
310 const char *driver = qemu_opt_get(opts, "driver");
311 int i;
313 if (!driver)
314 return 0;
315 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
316 if (strcmp(default_list[i].driver, driver) != 0)
317 continue;
318 *(default_list[i].flag) = 0;
320 return 0;
323 /***********************************************************/
324 /* x86 ISA bus support */
326 target_phys_addr_t isa_mem_base = 0;
327 PicState2 *isa_pic;
329 /***********************************************************/
330 void hw_error(const char *fmt, ...)
332 va_list ap;
333 CPUState *env;
335 va_start(ap, fmt);
336 fprintf(stderr, "qemu: hardware error: ");
337 vfprintf(stderr, fmt, ap);
338 fprintf(stderr, "\n");
339 for(env = first_cpu; env != NULL; env = env->next_cpu) {
340 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
341 #ifdef TARGET_I386
342 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
343 #else
344 cpu_dump_state(env, stderr, fprintf, 0);
345 #endif
347 va_end(ap);
348 abort();
351 static void set_proc_name(const char *s)
353 #if defined(__linux__) && defined(PR_SET_NAME)
354 char name[16];
355 if (!s)
356 return;
357 name[sizeof(name) - 1] = 0;
358 strncpy(name, s, sizeof(name));
359 /* Could rewrite argv[0] too, but that's a bit more complicated.
360 This simple way is enough for `top'. */
361 prctl(PR_SET_NAME, name);
362 #endif
365 /***************/
366 /* ballooning */
368 static QEMUBalloonEvent *qemu_balloon_event;
369 void *qemu_balloon_event_opaque;
371 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
373 qemu_balloon_event = func;
374 qemu_balloon_event_opaque = opaque;
377 int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
379 if (qemu_balloon_event) {
380 qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
381 return 1;
382 } else {
383 return 0;
387 int qemu_balloon_status(MonitorCompletion cb, void *opaque)
389 if (qemu_balloon_event) {
390 qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
391 return 1;
392 } else {
393 return 0;
398 /***********************************************************/
399 /* real time host monotonic timer */
401 /* compute with 96 bit intermediate result: (a*b)/c */
402 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
404 union {
405 uint64_t ll;
406 struct {
407 #ifdef HOST_WORDS_BIGENDIAN
408 uint32_t high, low;
409 #else
410 uint32_t low, high;
411 #endif
412 } l;
413 } u, res;
414 uint64_t rl, rh;
416 u.ll = a;
417 rl = (uint64_t)u.l.low * (uint64_t)b;
418 rh = (uint64_t)u.l.high * (uint64_t)b;
419 rh += (rl >> 32);
420 res.l.high = rh / c;
421 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
422 return res.ll;
425 static int64_t get_clock_realtime(void)
427 struct timeval tv;
429 gettimeofday(&tv, NULL);
430 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
433 #ifdef WIN32
435 static int64_t clock_freq;
437 static void init_get_clock(void)
439 LARGE_INTEGER freq;
440 int ret;
441 ret = QueryPerformanceFrequency(&freq);
442 if (ret == 0) {
443 fprintf(stderr, "Could not calibrate ticks\n");
444 exit(1);
446 clock_freq = freq.QuadPart;
449 static int64_t get_clock(void)
451 LARGE_INTEGER ti;
452 QueryPerformanceCounter(&ti);
453 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
456 #else
458 static int use_rt_clock;
460 static void init_get_clock(void)
462 use_rt_clock = 0;
463 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
464 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
466 struct timespec ts;
467 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
468 use_rt_clock = 1;
471 #endif
474 static int64_t get_clock(void)
476 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
477 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
478 if (use_rt_clock) {
479 struct timespec ts;
480 clock_gettime(CLOCK_MONOTONIC, &ts);
481 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
482 } else
483 #endif
485 /* XXX: using gettimeofday leads to problems if the date
486 changes, so it should be avoided. */
487 return get_clock_realtime();
490 #endif
492 /* Return the virtual CPU time, based on the instruction counter. */
493 static int64_t cpu_get_icount(void)
495 int64_t icount;
496 CPUState *env = cpu_single_env;;
497 icount = qemu_icount;
498 if (env) {
499 if (!can_do_io(env))
500 fprintf(stderr, "Bad clock read\n");
501 icount -= (env->icount_decr.u16.low + env->icount_extra);
503 return qemu_icount_bias + (icount << icount_time_shift);
506 /***********************************************************/
507 /* guest cycle counter */
509 typedef struct TimersState {
510 int64_t cpu_ticks_prev;
511 int64_t cpu_ticks_offset;
512 int64_t cpu_clock_offset;
513 int32_t cpu_ticks_enabled;
514 int64_t dummy;
515 } TimersState;
517 TimersState timers_state;
519 /* return the host CPU cycle counter and handle stop/restart */
520 int64_t cpu_get_ticks(void)
522 if (use_icount) {
523 return cpu_get_icount();
525 if (!timers_state.cpu_ticks_enabled) {
526 return timers_state.cpu_ticks_offset;
527 } else {
528 int64_t ticks;
529 ticks = cpu_get_real_ticks();
530 if (timers_state.cpu_ticks_prev > ticks) {
531 /* Note: non increasing ticks may happen if the host uses
532 software suspend */
533 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
535 timers_state.cpu_ticks_prev = ticks;
536 return ticks + timers_state.cpu_ticks_offset;
540 /* return the host CPU monotonic timer and handle stop/restart */
541 static int64_t cpu_get_clock(void)
543 int64_t ti;
544 if (!timers_state.cpu_ticks_enabled) {
545 return timers_state.cpu_clock_offset;
546 } else {
547 ti = get_clock();
548 return ti + timers_state.cpu_clock_offset;
552 /* enable cpu_get_ticks() */
553 void cpu_enable_ticks(void)
555 if (!timers_state.cpu_ticks_enabled) {
556 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
557 timers_state.cpu_clock_offset -= get_clock();
558 timers_state.cpu_ticks_enabled = 1;
562 /* disable cpu_get_ticks() : the clock is stopped. You must not call
563 cpu_get_ticks() after that. */
564 void cpu_disable_ticks(void)
566 if (timers_state.cpu_ticks_enabled) {
567 timers_state.cpu_ticks_offset = cpu_get_ticks();
568 timers_state.cpu_clock_offset = cpu_get_clock();
569 timers_state.cpu_ticks_enabled = 0;
573 /***********************************************************/
574 /* timers */
576 #define QEMU_CLOCK_REALTIME 0
577 #define QEMU_CLOCK_VIRTUAL 1
578 #define QEMU_CLOCK_HOST 2
580 struct QEMUClock {
581 int type;
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 unsigned int flags;
597 int (*start)(struct qemu_alarm_timer *t);
598 void (*stop)(struct qemu_alarm_timer *t);
599 void (*rearm)(struct qemu_alarm_timer *t);
600 void *priv;
603 #define ALARM_FLAG_DYNTICKS 0x1
604 #define ALARM_FLAG_EXPIRED 0x2
606 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
608 return t && (t->flags & ALARM_FLAG_DYNTICKS);
611 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
613 if (!alarm_has_dynticks(t))
614 return;
616 t->rearm(t);
619 /* TODO: MIN_TIMER_REARM_US should be optimized */
620 #define MIN_TIMER_REARM_US 250
622 static struct qemu_alarm_timer *alarm_timer;
624 #ifdef _WIN32
626 struct qemu_alarm_win32 {
627 MMRESULT timerId;
628 unsigned int period;
629 } alarm_win32_data = {0, -1};
631 static int win32_start_timer(struct qemu_alarm_timer *t);
632 static void win32_stop_timer(struct qemu_alarm_timer *t);
633 static void win32_rearm_timer(struct qemu_alarm_timer *t);
635 #else
637 static int unix_start_timer(struct qemu_alarm_timer *t);
638 static void unix_stop_timer(struct qemu_alarm_timer *t);
640 #ifdef __linux__
642 static int dynticks_start_timer(struct qemu_alarm_timer *t);
643 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
644 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
646 static int hpet_start_timer(struct qemu_alarm_timer *t);
647 static void hpet_stop_timer(struct qemu_alarm_timer *t);
649 static int rtc_start_timer(struct qemu_alarm_timer *t);
650 static void rtc_stop_timer(struct qemu_alarm_timer *t);
652 #endif /* __linux__ */
654 #endif /* _WIN32 */
656 /* Correlation between real and virtual time is always going to be
657 fairly approximate, so ignore small variation.
658 When the guest is idle real and virtual time will be aligned in
659 the IO wait loop. */
660 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
662 static void icount_adjust(void)
664 int64_t cur_time;
665 int64_t cur_icount;
666 int64_t delta;
667 static int64_t last_delta;
668 /* If the VM is not running, then do nothing. */
669 if (!vm_running)
670 return;
672 cur_time = cpu_get_clock();
673 cur_icount = qemu_get_clock(vm_clock);
674 delta = cur_icount - cur_time;
675 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
676 if (delta > 0
677 && last_delta + ICOUNT_WOBBLE < delta * 2
678 && icount_time_shift > 0) {
679 /* The guest is getting too far ahead. Slow time down. */
680 icount_time_shift--;
682 if (delta < 0
683 && last_delta - ICOUNT_WOBBLE > delta * 2
684 && icount_time_shift < MAX_ICOUNT_SHIFT) {
685 /* The guest is getting too far behind. Speed time up. */
686 icount_time_shift++;
688 last_delta = delta;
689 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
692 static void icount_adjust_rt(void * opaque)
694 qemu_mod_timer(icount_rt_timer,
695 qemu_get_clock(rt_clock) + 1000);
696 icount_adjust();
699 static void icount_adjust_vm(void * opaque)
701 qemu_mod_timer(icount_vm_timer,
702 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
703 icount_adjust();
706 static void init_icount_adjust(void)
708 /* Have both realtime and virtual time triggers for speed adjustment.
709 The realtime trigger catches emulated time passing too slowly,
710 the virtual time trigger catches emulated time passing too fast.
711 Realtime triggers occur even when idle, so use them less frequently
712 than VM triggers. */
713 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
714 qemu_mod_timer(icount_rt_timer,
715 qemu_get_clock(rt_clock) + 1000);
716 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
717 qemu_mod_timer(icount_vm_timer,
718 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
721 static struct qemu_alarm_timer alarm_timers[] = {
722 #ifndef _WIN32
723 #ifdef __linux__
724 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
725 dynticks_stop_timer, dynticks_rearm_timer, NULL},
726 /* HPET - if available - is preferred */
727 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
728 /* ...otherwise try RTC */
729 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
730 #endif
731 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
732 #else
733 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
734 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
735 {"win32", 0, win32_start_timer,
736 win32_stop_timer, NULL, &alarm_win32_data},
737 #endif
738 {NULL, }
741 static void show_available_alarms(void)
743 int i;
745 printf("Available alarm timers, in order of precedence:\n");
746 for (i = 0; alarm_timers[i].name; i++)
747 printf("%s\n", alarm_timers[i].name);
750 static void configure_alarms(char const *opt)
752 int i;
753 int cur = 0;
754 int count = ARRAY_SIZE(alarm_timers) - 1;
755 char *arg;
756 char *name;
757 struct qemu_alarm_timer tmp;
759 if (!strcmp(opt, "?")) {
760 show_available_alarms();
761 exit(0);
764 arg = qemu_strdup(opt);
766 /* Reorder the array */
767 name = strtok(arg, ",");
768 while (name) {
769 for (i = 0; i < count && alarm_timers[i].name; i++) {
770 if (!strcmp(alarm_timers[i].name, name))
771 break;
774 if (i == count) {
775 fprintf(stderr, "Unknown clock %s\n", name);
776 goto next;
779 if (i < cur)
780 /* Ignore */
781 goto next;
783 /* Swap */
784 tmp = alarm_timers[i];
785 alarm_timers[i] = alarm_timers[cur];
786 alarm_timers[cur] = tmp;
788 cur++;
789 next:
790 name = strtok(NULL, ",");
793 qemu_free(arg);
795 if (cur) {
796 /* Disable remaining timers */
797 for (i = cur; i < count; i++)
798 alarm_timers[i].name = NULL;
799 } else {
800 show_available_alarms();
801 exit(1);
805 #define QEMU_NUM_CLOCKS 3
807 QEMUClock *rt_clock;
808 QEMUClock *vm_clock;
809 QEMUClock *host_clock;
811 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
813 static QEMUClock *qemu_new_clock(int type)
815 QEMUClock *clock;
816 clock = qemu_mallocz(sizeof(QEMUClock));
817 clock->type = type;
818 return clock;
821 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
823 QEMUTimer *ts;
825 ts = qemu_mallocz(sizeof(QEMUTimer));
826 ts->clock = clock;
827 ts->cb = cb;
828 ts->opaque = opaque;
829 return ts;
832 void qemu_free_timer(QEMUTimer *ts)
834 qemu_free(ts);
837 /* stop a timer, but do not dealloc it */
838 void qemu_del_timer(QEMUTimer *ts)
840 QEMUTimer **pt, *t;
842 /* NOTE: this code must be signal safe because
843 qemu_timer_expired() can be called from a signal. */
844 pt = &active_timers[ts->clock->type];
845 for(;;) {
846 t = *pt;
847 if (!t)
848 break;
849 if (t == ts) {
850 *pt = t->next;
851 break;
853 pt = &t->next;
857 /* modify the current timer so that it will be fired when current_time
858 >= expire_time. The corresponding callback will be called. */
859 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
861 QEMUTimer **pt, *t;
863 qemu_del_timer(ts);
865 /* add the timer in the sorted list */
866 /* NOTE: this code must be signal safe because
867 qemu_timer_expired() can be called from a signal. */
868 pt = &active_timers[ts->clock->type];
869 for(;;) {
870 t = *pt;
871 if (!t)
872 break;
873 if (t->expire_time > expire_time)
874 break;
875 pt = &t->next;
877 ts->expire_time = expire_time;
878 ts->next = *pt;
879 *pt = ts;
881 /* Rearm if necessary */
882 if (pt == &active_timers[ts->clock->type]) {
883 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
884 qemu_rearm_alarm_timer(alarm_timer);
886 /* Interrupt execution to force deadline recalculation. */
887 if (use_icount)
888 qemu_notify_event();
892 int qemu_timer_pending(QEMUTimer *ts)
894 QEMUTimer *t;
895 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
896 if (t == ts)
897 return 1;
899 return 0;
902 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
904 if (!timer_head)
905 return 0;
906 return (timer_head->expire_time <= current_time);
909 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
911 QEMUTimer *ts;
913 for(;;) {
914 ts = *ptimer_head;
915 if (!ts || ts->expire_time > current_time)
916 break;
917 /* remove timer from the list before calling the callback */
918 *ptimer_head = ts->next;
919 ts->next = NULL;
921 /* run the callback (the timer list can be modified) */
922 ts->cb(ts->opaque);
926 int64_t qemu_get_clock(QEMUClock *clock)
928 switch(clock->type) {
929 case QEMU_CLOCK_REALTIME:
930 return get_clock() / 1000000;
931 default:
932 case QEMU_CLOCK_VIRTUAL:
933 if (use_icount) {
934 return cpu_get_icount();
935 } else {
936 return cpu_get_clock();
938 case QEMU_CLOCK_HOST:
939 return get_clock_realtime();
943 int64_t qemu_get_clock_ns(QEMUClock *clock)
945 switch(clock->type) {
946 case QEMU_CLOCK_REALTIME:
947 return get_clock();
948 default:
949 case QEMU_CLOCK_VIRTUAL:
950 if (use_icount) {
951 return cpu_get_icount();
952 } else {
953 return cpu_get_clock();
955 case QEMU_CLOCK_HOST:
956 return get_clock_realtime();
960 static void init_clocks(void)
962 init_get_clock();
963 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
964 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
965 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
967 rtc_clock = host_clock;
970 /* save a timer */
971 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
973 uint64_t expire_time;
975 if (qemu_timer_pending(ts)) {
976 expire_time = ts->expire_time;
977 } else {
978 expire_time = -1;
980 qemu_put_be64(f, expire_time);
983 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
985 uint64_t expire_time;
987 expire_time = qemu_get_be64(f);
988 if (expire_time != -1) {
989 qemu_mod_timer(ts, expire_time);
990 } else {
991 qemu_del_timer(ts);
995 static const VMStateDescription vmstate_timers = {
996 .name = "timer",
997 .version_id = 2,
998 .minimum_version_id = 1,
999 .minimum_version_id_old = 1,
1000 .fields = (VMStateField []) {
1001 VMSTATE_INT64(cpu_ticks_offset, TimersState),
1002 VMSTATE_INT64(dummy, TimersState),
1003 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1004 VMSTATE_END_OF_LIST()
1008 static void qemu_event_increment(void);
1010 #ifdef _WIN32
1011 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1012 DWORD_PTR dwUser, DWORD_PTR dw1,
1013 DWORD_PTR dw2)
1014 #else
1015 static void host_alarm_handler(int host_signum)
1016 #endif
1018 #if 0
1019 #define DISP_FREQ 1000
1021 static int64_t delta_min = INT64_MAX;
1022 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1023 static int count;
1024 ti = qemu_get_clock(vm_clock);
1025 if (last_clock != 0) {
1026 delta = ti - last_clock;
1027 if (delta < delta_min)
1028 delta_min = delta;
1029 if (delta > delta_max)
1030 delta_max = delta;
1031 delta_cum += delta;
1032 if (++count == DISP_FREQ) {
1033 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1034 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1035 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1036 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1037 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1038 count = 0;
1039 delta_min = INT64_MAX;
1040 delta_max = 0;
1041 delta_cum = 0;
1044 last_clock = ti;
1046 #endif
1047 if (alarm_has_dynticks(alarm_timer) ||
1048 (!use_icount &&
1049 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1050 qemu_get_clock(vm_clock))) ||
1051 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1052 qemu_get_clock(rt_clock)) ||
1053 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1054 qemu_get_clock(host_clock))) {
1055 qemu_event_increment();
1056 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1058 #ifndef CONFIG_IOTHREAD
1059 if (next_cpu) {
1060 /* stop the currently executing cpu because a timer occured */
1061 cpu_exit(next_cpu);
1063 #endif
1064 timer_alarm_pending = 1;
1065 qemu_notify_event();
1069 static int64_t qemu_next_deadline(void)
1071 /* To avoid problems with overflow limit this to 2^32. */
1072 int64_t delta = INT32_MAX;
1074 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1075 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1076 qemu_get_clock(vm_clock);
1078 if (active_timers[QEMU_CLOCK_HOST]) {
1079 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1080 qemu_get_clock(host_clock);
1081 if (hdelta < delta)
1082 delta = hdelta;
1085 if (delta < 0)
1086 delta = 0;
1088 return delta;
1091 #if defined(__linux__)
1092 static uint64_t qemu_next_deadline_dyntick(void)
1094 int64_t delta;
1095 int64_t rtdelta;
1097 if (use_icount)
1098 delta = INT32_MAX;
1099 else
1100 delta = (qemu_next_deadline() + 999) / 1000;
1102 if (active_timers[QEMU_CLOCK_REALTIME]) {
1103 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1104 qemu_get_clock(rt_clock))*1000;
1105 if (rtdelta < delta)
1106 delta = rtdelta;
1109 if (delta < MIN_TIMER_REARM_US)
1110 delta = MIN_TIMER_REARM_US;
1112 return delta;
1114 #endif
1116 #ifndef _WIN32
1118 /* Sets a specific flag */
1119 static int fcntl_setfl(int fd, int flag)
1121 int flags;
1123 flags = fcntl(fd, F_GETFL);
1124 if (flags == -1)
1125 return -errno;
1127 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1128 return -errno;
1130 return 0;
1133 #if defined(__linux__)
1135 #define RTC_FREQ 1024
1137 static void enable_sigio_timer(int fd)
1139 struct sigaction act;
1141 /* timer signal */
1142 sigfillset(&act.sa_mask);
1143 act.sa_flags = 0;
1144 act.sa_handler = host_alarm_handler;
1146 sigaction(SIGIO, &act, NULL);
1147 fcntl_setfl(fd, O_ASYNC);
1148 fcntl(fd, F_SETOWN, getpid());
1151 static int hpet_start_timer(struct qemu_alarm_timer *t)
1153 struct hpet_info info;
1154 int r, fd;
1156 fd = qemu_open("/dev/hpet", O_RDONLY);
1157 if (fd < 0)
1158 return -1;
1160 /* Set frequency */
1161 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1162 if (r < 0) {
1163 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1164 "error, but for better emulation accuracy type:\n"
1165 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1166 goto fail;
1169 /* Check capabilities */
1170 r = ioctl(fd, HPET_INFO, &info);
1171 if (r < 0)
1172 goto fail;
1174 /* Enable periodic mode */
1175 r = ioctl(fd, HPET_EPI, 0);
1176 if (info.hi_flags && (r < 0))
1177 goto fail;
1179 /* Enable interrupt */
1180 r = ioctl(fd, HPET_IE_ON, 0);
1181 if (r < 0)
1182 goto fail;
1184 enable_sigio_timer(fd);
1185 t->priv = (void *)(long)fd;
1187 return 0;
1188 fail:
1189 close(fd);
1190 return -1;
1193 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1195 int fd = (long)t->priv;
1197 close(fd);
1200 static int rtc_start_timer(struct qemu_alarm_timer *t)
1202 int rtc_fd;
1203 unsigned long current_rtc_freq = 0;
1205 TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
1206 if (rtc_fd < 0)
1207 return -1;
1208 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1209 if (current_rtc_freq != RTC_FREQ &&
1210 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1211 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1212 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1213 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1214 goto fail;
1216 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1217 fail:
1218 close(rtc_fd);
1219 return -1;
1222 enable_sigio_timer(rtc_fd);
1224 t->priv = (void *)(long)rtc_fd;
1226 return 0;
1229 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1231 int rtc_fd = (long)t->priv;
1233 close(rtc_fd);
1236 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1238 struct sigevent ev;
1239 timer_t host_timer;
1240 struct sigaction act;
1242 sigfillset(&act.sa_mask);
1243 act.sa_flags = 0;
1244 act.sa_handler = host_alarm_handler;
1246 sigaction(SIGALRM, &act, NULL);
1249 * Initialize ev struct to 0 to avoid valgrind complaining
1250 * about uninitialized data in timer_create call
1252 memset(&ev, 0, sizeof(ev));
1253 ev.sigev_value.sival_int = 0;
1254 ev.sigev_notify = SIGEV_SIGNAL;
1255 ev.sigev_signo = SIGALRM;
1257 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1258 perror("timer_create");
1260 /* disable dynticks */
1261 fprintf(stderr, "Dynamic Ticks disabled\n");
1263 return -1;
1266 t->priv = (void *)(long)host_timer;
1268 return 0;
1271 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1273 timer_t host_timer = (timer_t)(long)t->priv;
1275 timer_delete(host_timer);
1278 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1280 timer_t host_timer = (timer_t)(long)t->priv;
1281 struct itimerspec timeout;
1282 int64_t nearest_delta_us = INT64_MAX;
1283 int64_t current_us;
1285 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1286 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1287 !active_timers[QEMU_CLOCK_HOST])
1288 return;
1290 nearest_delta_us = qemu_next_deadline_dyntick();
1292 /* check whether a timer is already running */
1293 if (timer_gettime(host_timer, &timeout)) {
1294 perror("gettime");
1295 fprintf(stderr, "Internal timer error: aborting\n");
1296 exit(1);
1298 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1299 if (current_us && current_us <= nearest_delta_us)
1300 return;
1302 timeout.it_interval.tv_sec = 0;
1303 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1304 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1305 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1306 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1307 perror("settime");
1308 fprintf(stderr, "Internal timer error: aborting\n");
1309 exit(1);
1313 #endif /* defined(__linux__) */
1315 static int unix_start_timer(struct qemu_alarm_timer *t)
1317 struct sigaction act;
1318 struct itimerval itv;
1319 int err;
1321 /* timer signal */
1322 sigfillset(&act.sa_mask);
1323 act.sa_flags = 0;
1324 act.sa_handler = host_alarm_handler;
1326 sigaction(SIGALRM, &act, NULL);
1328 itv.it_interval.tv_sec = 0;
1329 /* for i386 kernel 2.6 to get 1 ms */
1330 itv.it_interval.tv_usec = 999;
1331 itv.it_value.tv_sec = 0;
1332 itv.it_value.tv_usec = 10 * 1000;
1334 err = setitimer(ITIMER_REAL, &itv, NULL);
1335 if (err)
1336 return -1;
1338 return 0;
1341 static void unix_stop_timer(struct qemu_alarm_timer *t)
1343 struct itimerval itv;
1345 memset(&itv, 0, sizeof(itv));
1346 setitimer(ITIMER_REAL, &itv, NULL);
1349 #endif /* !defined(_WIN32) */
1352 #ifdef _WIN32
1354 static int win32_start_timer(struct qemu_alarm_timer *t)
1356 TIMECAPS tc;
1357 struct qemu_alarm_win32 *data = t->priv;
1358 UINT flags;
1360 memset(&tc, 0, sizeof(tc));
1361 timeGetDevCaps(&tc, sizeof(tc));
1363 if (data->period < tc.wPeriodMin)
1364 data->period = tc.wPeriodMin;
1366 timeBeginPeriod(data->period);
1368 flags = TIME_CALLBACK_FUNCTION;
1369 if (alarm_has_dynticks(t))
1370 flags |= TIME_ONESHOT;
1371 else
1372 flags |= TIME_PERIODIC;
1374 data->timerId = timeSetEvent(1, // interval (ms)
1375 data->period, // resolution
1376 host_alarm_handler, // function
1377 (DWORD)t, // parameter
1378 flags);
1380 if (!data->timerId) {
1381 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1382 GetLastError());
1383 timeEndPeriod(data->period);
1384 return -1;
1387 return 0;
1390 static void win32_stop_timer(struct qemu_alarm_timer *t)
1392 struct qemu_alarm_win32 *data = t->priv;
1394 timeKillEvent(data->timerId);
1395 timeEndPeriod(data->period);
1398 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1400 struct qemu_alarm_win32 *data = t->priv;
1402 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1403 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1404 !active_timers[QEMU_CLOCK_HOST])
1405 return;
1407 timeKillEvent(data->timerId);
1409 data->timerId = timeSetEvent(1,
1410 data->period,
1411 host_alarm_handler,
1412 (DWORD)t,
1413 TIME_ONESHOT | TIME_PERIODIC);
1415 if (!data->timerId) {
1416 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1417 GetLastError());
1419 timeEndPeriod(data->period);
1420 exit(1);
1424 #endif /* _WIN32 */
1426 static int init_timer_alarm(void)
1428 struct qemu_alarm_timer *t = NULL;
1429 int i, err = -1;
1431 for (i = 0; alarm_timers[i].name; i++) {
1432 t = &alarm_timers[i];
1434 err = t->start(t);
1435 if (!err)
1436 break;
1439 if (err) {
1440 err = -ENOENT;
1441 goto fail;
1444 alarm_timer = t;
1446 return 0;
1448 fail:
1449 return err;
1452 static void quit_timers(void)
1454 alarm_timer->stop(alarm_timer);
1455 alarm_timer = NULL;
1458 /***********************************************************/
1459 /* host time/date access */
1460 void qemu_get_timedate(struct tm *tm, int offset)
1462 time_t ti;
1463 struct tm *ret;
1465 time(&ti);
1466 ti += offset;
1467 if (rtc_date_offset == -1) {
1468 if (rtc_utc)
1469 ret = gmtime(&ti);
1470 else
1471 ret = localtime(&ti);
1472 } else {
1473 ti -= rtc_date_offset;
1474 ret = gmtime(&ti);
1477 memcpy(tm, ret, sizeof(struct tm));
1480 int qemu_timedate_diff(struct tm *tm)
1482 time_t seconds;
1484 if (rtc_date_offset == -1)
1485 if (rtc_utc)
1486 seconds = mktimegm(tm);
1487 else
1488 seconds = mktime(tm);
1489 else
1490 seconds = mktimegm(tm) + rtc_date_offset;
1492 return seconds - time(NULL);
1495 void rtc_change_mon_event(struct tm *tm)
1497 QObject *data;
1499 data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
1500 monitor_protocol_event(QEVENT_RTC_CHANGE, data);
1501 qobject_decref(data);
1504 static void configure_rtc_date_offset(const char *startdate, int legacy)
1506 time_t rtc_start_date;
1507 struct tm tm;
1509 if (!strcmp(startdate, "now") && legacy) {
1510 rtc_date_offset = -1;
1511 } else {
1512 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1513 &tm.tm_year,
1514 &tm.tm_mon,
1515 &tm.tm_mday,
1516 &tm.tm_hour,
1517 &tm.tm_min,
1518 &tm.tm_sec) == 6) {
1519 /* OK */
1520 } else if (sscanf(startdate, "%d-%d-%d",
1521 &tm.tm_year,
1522 &tm.tm_mon,
1523 &tm.tm_mday) == 3) {
1524 tm.tm_hour = 0;
1525 tm.tm_min = 0;
1526 tm.tm_sec = 0;
1527 } else {
1528 goto date_fail;
1530 tm.tm_year -= 1900;
1531 tm.tm_mon--;
1532 rtc_start_date = mktimegm(&tm);
1533 if (rtc_start_date == -1) {
1534 date_fail:
1535 fprintf(stderr, "Invalid date format. Valid formats are:\n"
1536 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1537 exit(1);
1539 rtc_date_offset = time(NULL) - rtc_start_date;
1543 static void configure_rtc(QemuOpts *opts)
1545 const char *value;
1547 value = qemu_opt_get(opts, "base");
1548 if (value) {
1549 if (!strcmp(value, "utc")) {
1550 rtc_utc = 1;
1551 } else if (!strcmp(value, "localtime")) {
1552 rtc_utc = 0;
1553 } else {
1554 configure_rtc_date_offset(value, 0);
1557 value = qemu_opt_get(opts, "clock");
1558 if (value) {
1559 if (!strcmp(value, "host")) {
1560 rtc_clock = host_clock;
1561 } else if (!strcmp(value, "vm")) {
1562 rtc_clock = vm_clock;
1563 } else {
1564 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1565 exit(1);
1568 #ifdef CONFIG_TARGET_I386
1569 value = qemu_opt_get(opts, "driftfix");
1570 if (value) {
1571 if (!strcmp(buf, "slew")) {
1572 rtc_td_hack = 1;
1573 } else if (!strcmp(buf, "none")) {
1574 rtc_td_hack = 0;
1575 } else {
1576 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1577 exit(1);
1580 #endif
1583 #ifdef _WIN32
1584 static void socket_cleanup(void)
1586 WSACleanup();
1589 static int socket_init(void)
1591 WSADATA Data;
1592 int ret, err;
1594 ret = WSAStartup(MAKEWORD(2,2), &Data);
1595 if (ret != 0) {
1596 err = WSAGetLastError();
1597 fprintf(stderr, "WSAStartup: %d\n", err);
1598 return -1;
1600 atexit(socket_cleanup);
1601 return 0;
1603 #endif
1605 /***********************************************************/
1606 /* Bluetooth support */
1607 static int nb_hcis;
1608 static int cur_hci;
1609 static struct HCIInfo *hci_table[MAX_NICS];
1611 static struct bt_vlan_s {
1612 struct bt_scatternet_s net;
1613 int id;
1614 struct bt_vlan_s *next;
1615 } *first_bt_vlan;
1617 /* find or alloc a new bluetooth "VLAN" */
1618 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1620 struct bt_vlan_s **pvlan, *vlan;
1621 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1622 if (vlan->id == id)
1623 return &vlan->net;
1625 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1626 vlan->id = id;
1627 pvlan = &first_bt_vlan;
1628 while (*pvlan != NULL)
1629 pvlan = &(*pvlan)->next;
1630 *pvlan = vlan;
1631 return &vlan->net;
1634 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1638 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1640 return -ENOTSUP;
1643 static struct HCIInfo null_hci = {
1644 .cmd_send = null_hci_send,
1645 .sco_send = null_hci_send,
1646 .acl_send = null_hci_send,
1647 .bdaddr_set = null_hci_addr_set,
1650 struct HCIInfo *qemu_next_hci(void)
1652 if (cur_hci == nb_hcis)
1653 return &null_hci;
1655 return hci_table[cur_hci++];
1658 static struct HCIInfo *hci_init(const char *str)
1660 char *endp;
1661 struct bt_scatternet_s *vlan = 0;
1663 if (!strcmp(str, "null"))
1664 /* null */
1665 return &null_hci;
1666 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1667 /* host[:hciN] */
1668 return bt_host_hci(str[4] ? str + 5 : "hci0");
1669 else if (!strncmp(str, "hci", 3)) {
1670 /* hci[,vlan=n] */
1671 if (str[3]) {
1672 if (!strncmp(str + 3, ",vlan=", 6)) {
1673 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1674 if (*endp)
1675 vlan = 0;
1677 } else
1678 vlan = qemu_find_bt_vlan(0);
1679 if (vlan)
1680 return bt_new_hci(vlan);
1683 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1685 return 0;
1688 static int bt_hci_parse(const char *str)
1690 struct HCIInfo *hci;
1691 bdaddr_t bdaddr;
1693 if (nb_hcis >= MAX_NICS) {
1694 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1695 return -1;
1698 hci = hci_init(str);
1699 if (!hci)
1700 return -1;
1702 bdaddr.b[0] = 0x52;
1703 bdaddr.b[1] = 0x54;
1704 bdaddr.b[2] = 0x00;
1705 bdaddr.b[3] = 0x12;
1706 bdaddr.b[4] = 0x34;
1707 bdaddr.b[5] = 0x56 + nb_hcis;
1708 hci->bdaddr_set(hci, bdaddr.b);
1710 hci_table[nb_hcis++] = hci;
1712 return 0;
1715 static void bt_vhci_add(int vlan_id)
1717 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1719 if (!vlan->slave)
1720 fprintf(stderr, "qemu: warning: adding a VHCI to "
1721 "an empty scatternet %i\n", vlan_id);
1723 bt_vhci_init(bt_new_hci(vlan));
1726 static struct bt_device_s *bt_device_add(const char *opt)
1728 struct bt_scatternet_s *vlan;
1729 int vlan_id = 0;
1730 char *endp = strstr(opt, ",vlan=");
1731 int len = (endp ? endp - opt : strlen(opt)) + 1;
1732 char devname[10];
1734 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1736 if (endp) {
1737 vlan_id = strtol(endp + 6, &endp, 0);
1738 if (*endp) {
1739 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1740 return 0;
1744 vlan = qemu_find_bt_vlan(vlan_id);
1746 if (!vlan->slave)
1747 fprintf(stderr, "qemu: warning: adding a slave device to "
1748 "an empty scatternet %i\n", vlan_id);
1750 if (!strcmp(devname, "keyboard"))
1751 return bt_keyboard_init(vlan);
1753 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1754 return 0;
1757 static int bt_parse(const char *opt)
1759 const char *endp, *p;
1760 int vlan;
1762 if (strstart(opt, "hci", &endp)) {
1763 if (!*endp || *endp == ',') {
1764 if (*endp)
1765 if (!strstart(endp, ",vlan=", 0))
1766 opt = endp + 1;
1768 return bt_hci_parse(opt);
1770 } else if (strstart(opt, "vhci", &endp)) {
1771 if (!*endp || *endp == ',') {
1772 if (*endp) {
1773 if (strstart(endp, ",vlan=", &p)) {
1774 vlan = strtol(p, (char **) &endp, 0);
1775 if (*endp) {
1776 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1777 return 1;
1779 } else {
1780 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1781 return 1;
1783 } else
1784 vlan = 0;
1786 bt_vhci_add(vlan);
1787 return 0;
1789 } else if (strstart(opt, "device:", &endp))
1790 return !bt_device_add(endp);
1792 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1793 return 1;
1796 /***********************************************************/
1797 /* QEMU Block devices */
1799 #define HD_ALIAS "index=%d,media=disk"
1800 #define CDROM_ALIAS "index=2,media=cdrom"
1801 #define FD_ALIAS "index=%d,if=floppy"
1802 #define PFLASH_ALIAS "if=pflash"
1803 #define MTD_ALIAS "if=mtd"
1804 #define SD_ALIAS "index=0,if=sd"
1806 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1808 va_list ap;
1809 char optstr[1024];
1810 QemuOpts *opts;
1812 va_start(ap, fmt);
1813 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1814 va_end(ap);
1816 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1817 if (!opts) {
1818 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1819 __FUNCTION__, optstr);
1820 return NULL;
1822 if (file)
1823 qemu_opt_set(opts, "file", file);
1824 return opts;
1827 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1829 DriveInfo *dinfo;
1831 /* seek interface, bus and unit */
1833 QTAILQ_FOREACH(dinfo, &drives, next) {
1834 if (dinfo->type == type &&
1835 dinfo->bus == bus &&
1836 dinfo->unit == unit)
1837 return dinfo;
1840 return NULL;
1843 DriveInfo *drive_get_by_id(const char *id)
1845 DriveInfo *dinfo;
1847 QTAILQ_FOREACH(dinfo, &drives, next) {
1848 if (strcmp(id, dinfo->id))
1849 continue;
1850 return dinfo;
1852 return NULL;
1855 int drive_get_max_bus(BlockInterfaceType type)
1857 int max_bus;
1858 DriveInfo *dinfo;
1860 max_bus = -1;
1861 QTAILQ_FOREACH(dinfo, &drives, next) {
1862 if(dinfo->type == type &&
1863 dinfo->bus > max_bus)
1864 max_bus = dinfo->bus;
1866 return max_bus;
1869 const char *drive_get_serial(BlockDriverState *bdrv)
1871 DriveInfo *dinfo;
1873 QTAILQ_FOREACH(dinfo, &drives, next) {
1874 if (dinfo->bdrv == bdrv)
1875 return dinfo->serial;
1878 return "\0";
1881 BlockInterfaceErrorAction drive_get_on_error(
1882 BlockDriverState *bdrv, int is_read)
1884 DriveInfo *dinfo;
1886 QTAILQ_FOREACH(dinfo, &drives, next) {
1887 if (dinfo->bdrv == bdrv)
1888 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
1891 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
1894 static void bdrv_format_print(void *opaque, const char *name)
1896 fprintf(stderr, " %s", name);
1899 void drive_uninit(DriveInfo *dinfo)
1901 qemu_opts_del(dinfo->opts);
1902 bdrv_delete(dinfo->bdrv);
1903 QTAILQ_REMOVE(&drives, dinfo, next);
1904 qemu_free(dinfo);
1907 static int parse_block_error_action(const char *buf, int is_read)
1909 if (!strcmp(buf, "ignore")) {
1910 return BLOCK_ERR_IGNORE;
1911 } else if (!is_read && !strcmp(buf, "enospc")) {
1912 return BLOCK_ERR_STOP_ENOSPC;
1913 } else if (!strcmp(buf, "stop")) {
1914 return BLOCK_ERR_STOP_ANY;
1915 } else if (!strcmp(buf, "report")) {
1916 return BLOCK_ERR_REPORT;
1917 } else {
1918 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
1919 buf, is_read ? "read" : "write");
1920 return -1;
1924 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1925 int *fatal_error)
1927 const char *buf;
1928 const char *file = NULL;
1929 char devname[128];
1930 const char *serial;
1931 const char *mediastr = "";
1932 BlockInterfaceType type;
1933 enum { MEDIA_DISK, MEDIA_CDROM } media;
1934 int bus_id, unit_id;
1935 int cyls, heads, secs, translation;
1936 BlockDriver *drv = NULL;
1937 QEMUMachine *machine = opaque;
1938 int max_devs;
1939 int index;
1940 int cache;
1941 int aio = 0;
1942 int ro = 0;
1943 int bdrv_flags;
1944 int on_read_error, on_write_error;
1945 const char *devaddr;
1946 DriveInfo *dinfo;
1947 int snapshot = 0;
1949 *fatal_error = 1;
1951 translation = BIOS_ATA_TRANSLATION_AUTO;
1952 cache = 1;
1954 if (machine && machine->use_scsi) {
1955 type = IF_SCSI;
1956 max_devs = MAX_SCSI_DEVS;
1957 pstrcpy(devname, sizeof(devname), "scsi");
1958 } else {
1959 type = IF_IDE;
1960 max_devs = MAX_IDE_DEVS;
1961 pstrcpy(devname, sizeof(devname), "ide");
1963 media = MEDIA_DISK;
1965 /* extract parameters */
1966 bus_id = qemu_opt_get_number(opts, "bus", 0);
1967 unit_id = qemu_opt_get_number(opts, "unit", -1);
1968 index = qemu_opt_get_number(opts, "index", -1);
1970 cyls = qemu_opt_get_number(opts, "cyls", 0);
1971 heads = qemu_opt_get_number(opts, "heads", 0);
1972 secs = qemu_opt_get_number(opts, "secs", 0);
1974 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1975 ro = qemu_opt_get_bool(opts, "readonly", 0);
1977 file = qemu_opt_get(opts, "file");
1978 serial = qemu_opt_get(opts, "serial");
1980 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1981 pstrcpy(devname, sizeof(devname), buf);
1982 if (!strcmp(buf, "ide")) {
1983 type = IF_IDE;
1984 max_devs = MAX_IDE_DEVS;
1985 } else if (!strcmp(buf, "scsi")) {
1986 type = IF_SCSI;
1987 max_devs = MAX_SCSI_DEVS;
1988 } else if (!strcmp(buf, "floppy")) {
1989 type = IF_FLOPPY;
1990 max_devs = 0;
1991 } else if (!strcmp(buf, "pflash")) {
1992 type = IF_PFLASH;
1993 max_devs = 0;
1994 } else if (!strcmp(buf, "mtd")) {
1995 type = IF_MTD;
1996 max_devs = 0;
1997 } else if (!strcmp(buf, "sd")) {
1998 type = IF_SD;
1999 max_devs = 0;
2000 } else if (!strcmp(buf, "virtio")) {
2001 type = IF_VIRTIO;
2002 max_devs = 0;
2003 } else if (!strcmp(buf, "xen")) {
2004 type = IF_XEN;
2005 max_devs = 0;
2006 } else if (!strcmp(buf, "none")) {
2007 type = IF_NONE;
2008 max_devs = 0;
2009 } else {
2010 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
2011 return NULL;
2015 if (cyls || heads || secs) {
2016 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
2017 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2018 return NULL;
2020 if (heads < 1 || (type == IF_IDE && heads > 16)) {
2021 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2022 return NULL;
2024 if (secs < 1 || (type == IF_IDE && secs > 63)) {
2025 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2026 return NULL;
2030 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2031 if (!cyls) {
2032 fprintf(stderr,
2033 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2034 buf);
2035 return NULL;
2037 if (!strcmp(buf, "none"))
2038 translation = BIOS_ATA_TRANSLATION_NONE;
2039 else if (!strcmp(buf, "lba"))
2040 translation = BIOS_ATA_TRANSLATION_LBA;
2041 else if (!strcmp(buf, "auto"))
2042 translation = BIOS_ATA_TRANSLATION_AUTO;
2043 else {
2044 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2045 return NULL;
2049 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2050 if (!strcmp(buf, "disk")) {
2051 media = MEDIA_DISK;
2052 } else if (!strcmp(buf, "cdrom")) {
2053 if (cyls || secs || heads) {
2054 fprintf(stderr,
2055 "qemu: '%s' invalid physical CHS format\n", buf);
2056 return NULL;
2058 media = MEDIA_CDROM;
2059 } else {
2060 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2061 return NULL;
2065 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2066 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2067 cache = 0;
2068 else if (!strcmp(buf, "writethrough"))
2069 cache = 1;
2070 else if (!strcmp(buf, "writeback"))
2071 cache = 2;
2072 else {
2073 fprintf(stderr, "qemu: invalid cache option\n");
2074 return NULL;
2078 #ifdef CONFIG_LINUX_AIO
2079 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2080 if (!strcmp(buf, "threads"))
2081 aio = 0;
2082 else if (!strcmp(buf, "native"))
2083 aio = 1;
2084 else {
2085 fprintf(stderr, "qemu: invalid aio option\n");
2086 return NULL;
2089 #endif
2091 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2092 if (strcmp(buf, "?") == 0) {
2093 fprintf(stderr, "qemu: Supported formats:");
2094 bdrv_iterate_format(bdrv_format_print, NULL);
2095 fprintf(stderr, "\n");
2096 return NULL;
2098 drv = bdrv_find_whitelisted_format(buf);
2099 if (!drv) {
2100 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2101 return NULL;
2105 on_write_error = BLOCK_ERR_STOP_ENOSPC;
2106 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2107 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2108 fprintf(stderr, "werror is no supported by this format\n");
2109 return NULL;
2112 on_write_error = parse_block_error_action(buf, 0);
2113 if (on_write_error < 0) {
2114 return NULL;
2118 on_read_error = BLOCK_ERR_REPORT;
2119 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2120 if (type != IF_IDE && type != IF_VIRTIO) {
2121 fprintf(stderr, "rerror is no supported by this format\n");
2122 return NULL;
2125 on_read_error = parse_block_error_action(buf, 1);
2126 if (on_read_error < 0) {
2127 return NULL;
2131 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2132 if (type != IF_VIRTIO) {
2133 fprintf(stderr, "addr is not supported\n");
2134 return NULL;
2138 /* compute bus and unit according index */
2140 if (index != -1) {
2141 if (bus_id != 0 || unit_id != -1) {
2142 fprintf(stderr,
2143 "qemu: index cannot be used with bus and unit\n");
2144 return NULL;
2146 if (max_devs == 0)
2148 unit_id = index;
2149 bus_id = 0;
2150 } else {
2151 unit_id = index % max_devs;
2152 bus_id = index / max_devs;
2156 /* if user doesn't specify a unit_id,
2157 * try to find the first free
2160 if (unit_id == -1) {
2161 unit_id = 0;
2162 while (drive_get(type, bus_id, unit_id) != NULL) {
2163 unit_id++;
2164 if (max_devs && unit_id >= max_devs) {
2165 unit_id -= max_devs;
2166 bus_id++;
2171 /* check unit id */
2173 if (max_devs && unit_id >= max_devs) {
2174 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2175 unit_id, max_devs - 1);
2176 return NULL;
2180 * ignore multiple definitions
2183 if (drive_get(type, bus_id, unit_id) != NULL) {
2184 *fatal_error = 0;
2185 return NULL;
2188 /* init */
2190 dinfo = qemu_mallocz(sizeof(*dinfo));
2191 if ((buf = qemu_opts_id(opts)) != NULL) {
2192 dinfo->id = qemu_strdup(buf);
2193 } else {
2194 /* no id supplied -> create one */
2195 dinfo->id = qemu_mallocz(32);
2196 if (type == IF_IDE || type == IF_SCSI)
2197 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2198 if (max_devs)
2199 snprintf(dinfo->id, 32, "%s%i%s%i",
2200 devname, bus_id, mediastr, unit_id);
2201 else
2202 snprintf(dinfo->id, 32, "%s%s%i",
2203 devname, mediastr, unit_id);
2205 dinfo->bdrv = bdrv_new(dinfo->id);
2206 dinfo->devaddr = devaddr;
2207 dinfo->type = type;
2208 dinfo->bus = bus_id;
2209 dinfo->unit = unit_id;
2210 dinfo->on_read_error = on_read_error;
2211 dinfo->on_write_error = on_write_error;
2212 dinfo->opts = opts;
2213 if (serial)
2214 strncpy(dinfo->serial, serial, sizeof(serial));
2215 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2217 switch(type) {
2218 case IF_IDE:
2219 case IF_SCSI:
2220 case IF_XEN:
2221 case IF_NONE:
2222 switch(media) {
2223 case MEDIA_DISK:
2224 if (cyls != 0) {
2225 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2226 bdrv_set_translation_hint(dinfo->bdrv, translation);
2228 break;
2229 case MEDIA_CDROM:
2230 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2231 break;
2233 break;
2234 case IF_SD:
2235 /* FIXME: This isn't really a floppy, but it's a reasonable
2236 approximation. */
2237 case IF_FLOPPY:
2238 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2239 break;
2240 case IF_PFLASH:
2241 case IF_MTD:
2242 break;
2243 case IF_VIRTIO:
2244 /* add virtio block device */
2245 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2246 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2247 qemu_opt_set(opts, "drive", dinfo->id);
2248 if (devaddr)
2249 qemu_opt_set(opts, "addr", devaddr);
2250 break;
2251 case IF_COUNT:
2252 abort();
2254 if (!file) {
2255 *fatal_error = 0;
2256 return NULL;
2258 bdrv_flags = 0;
2259 if (snapshot) {
2260 bdrv_flags |= BDRV_O_SNAPSHOT;
2261 cache = 2; /* always use write-back with snapshot */
2263 if (cache == 0) /* no caching */
2264 bdrv_flags |= BDRV_O_NOCACHE;
2265 else if (cache == 2) /* write-back */
2266 bdrv_flags |= BDRV_O_CACHE_WB;
2268 if (aio == 1) {
2269 bdrv_flags |= BDRV_O_NATIVE_AIO;
2270 } else {
2271 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2274 if (ro == 1) {
2275 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
2276 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
2277 return NULL;
2281 * cdrom is read-only. Set it now, after above interface checking
2282 * since readonly attribute not explicitly required, so no error.
2284 if (media == MEDIA_CDROM) {
2285 ro = 1;
2287 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
2289 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2290 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2291 file, strerror(errno));
2292 return NULL;
2295 if (bdrv_key_required(dinfo->bdrv))
2296 autostart = 0;
2297 *fatal_error = 0;
2298 return dinfo;
2301 static int drive_init_func(QemuOpts *opts, void *opaque)
2303 QEMUMachine *machine = opaque;
2304 int fatal_error = 0;
2306 if (drive_init(opts, machine, &fatal_error) == NULL) {
2307 if (fatal_error)
2308 return 1;
2310 return 0;
2313 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2315 if (NULL == qemu_opt_get(opts, "snapshot")) {
2316 qemu_opt_set(opts, "snapshot", "on");
2318 return 0;
2321 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2323 boot_set_handler = func;
2324 boot_set_opaque = opaque;
2327 int qemu_boot_set(const char *boot_devices)
2329 if (!boot_set_handler) {
2330 return -EINVAL;
2332 return boot_set_handler(boot_set_opaque, boot_devices);
2335 static int parse_bootdevices(char *devices)
2337 /* We just do some generic consistency checks */
2338 const char *p;
2339 int bitmap = 0;
2341 for (p = devices; *p != '\0'; p++) {
2342 /* Allowed boot devices are:
2343 * a-b: floppy disk drives
2344 * c-f: IDE disk drives
2345 * g-m: machine implementation dependant drives
2346 * n-p: network devices
2347 * It's up to each machine implementation to check if the given boot
2348 * devices match the actual hardware implementation and firmware
2349 * features.
2351 if (*p < 'a' || *p > 'p') {
2352 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2353 exit(1);
2355 if (bitmap & (1 << (*p - 'a'))) {
2356 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2357 exit(1);
2359 bitmap |= 1 << (*p - 'a');
2361 return bitmap;
2364 static void restore_boot_devices(void *opaque)
2366 char *standard_boot_devices = opaque;
2368 qemu_boot_set(standard_boot_devices);
2370 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2371 qemu_free(standard_boot_devices);
2374 static void numa_add(const char *optarg)
2376 char option[128];
2377 char *endptr;
2378 unsigned long long value, endvalue;
2379 int nodenr;
2381 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2382 if (!strcmp(option, "node")) {
2383 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2384 nodenr = nb_numa_nodes;
2385 } else {
2386 nodenr = strtoull(option, NULL, 10);
2389 if (get_param_value(option, 128, "mem", optarg) == 0) {
2390 node_mem[nodenr] = 0;
2391 } else {
2392 value = strtoull(option, &endptr, 0);
2393 switch (*endptr) {
2394 case 0: case 'M': case 'm':
2395 value <<= 20;
2396 break;
2397 case 'G': case 'g':
2398 value <<= 30;
2399 break;
2401 node_mem[nodenr] = value;
2403 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2404 node_cpumask[nodenr] = 0;
2405 } else {
2406 value = strtoull(option, &endptr, 10);
2407 if (value >= 64) {
2408 value = 63;
2409 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2410 } else {
2411 if (*endptr == '-') {
2412 endvalue = strtoull(endptr+1, &endptr, 10);
2413 if (endvalue >= 63) {
2414 endvalue = 62;
2415 fprintf(stderr,
2416 "only 63 CPUs in NUMA mode supported.\n");
2418 value = (2ULL << endvalue) - (1ULL << value);
2419 } else {
2420 value = 1ULL << value;
2423 node_cpumask[nodenr] = value;
2425 nb_numa_nodes++;
2427 return;
2430 static void smp_parse(const char *optarg)
2432 int smp, sockets = 0, threads = 0, cores = 0;
2433 char *endptr;
2434 char option[128];
2436 smp = strtoul(optarg, &endptr, 10);
2437 if (endptr != optarg) {
2438 if (*endptr == ',') {
2439 endptr++;
2442 if (get_param_value(option, 128, "sockets", endptr) != 0)
2443 sockets = strtoull(option, NULL, 10);
2444 if (get_param_value(option, 128, "cores", endptr) != 0)
2445 cores = strtoull(option, NULL, 10);
2446 if (get_param_value(option, 128, "threads", endptr) != 0)
2447 threads = strtoull(option, NULL, 10);
2448 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2449 max_cpus = strtoull(option, NULL, 10);
2451 /* compute missing values, prefer sockets over cores over threads */
2452 if (smp == 0 || sockets == 0) {
2453 sockets = sockets > 0 ? sockets : 1;
2454 cores = cores > 0 ? cores : 1;
2455 threads = threads > 0 ? threads : 1;
2456 if (smp == 0) {
2457 smp = cores * threads * sockets;
2459 } else {
2460 if (cores == 0) {
2461 threads = threads > 0 ? threads : 1;
2462 cores = smp / (sockets * threads);
2463 } else {
2464 if (sockets) {
2465 threads = smp / (cores * sockets);
2469 smp_cpus = smp;
2470 smp_cores = cores > 0 ? cores : 1;
2471 smp_threads = threads > 0 ? threads : 1;
2472 if (max_cpus == 0)
2473 max_cpus = smp_cpus;
2476 /***********************************************************/
2477 /* USB devices */
2479 static int usb_device_add(const char *devname, int is_hotplug)
2481 const char *p;
2482 USBDevice *dev = NULL;
2484 if (!usb_enabled)
2485 return -1;
2487 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2488 dev = usbdevice_create(devname);
2489 if (dev)
2490 goto done;
2492 /* the other ones */
2493 if (strstart(devname, "host:", &p)) {
2494 dev = usb_host_device_open(p);
2495 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2496 dev = usb_bt_init(devname[2] ? hci_init(p) :
2497 bt_new_hci(qemu_find_bt_vlan(0)));
2498 } else {
2499 return -1;
2501 if (!dev)
2502 return -1;
2504 done:
2505 return 0;
2508 static int usb_device_del(const char *devname)
2510 int bus_num, addr;
2511 const char *p;
2513 if (strstart(devname, "host:", &p))
2514 return usb_host_device_close(p);
2516 if (!usb_enabled)
2517 return -1;
2519 p = strchr(devname, '.');
2520 if (!p)
2521 return -1;
2522 bus_num = strtoul(devname, NULL, 0);
2523 addr = strtoul(p + 1, NULL, 0);
2525 return usb_device_delete_addr(bus_num, addr);
2528 static int usb_parse(const char *cmdline)
2530 int r;
2531 r = usb_device_add(cmdline, 0);
2532 if (r < 0) {
2533 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
2535 return r;
2538 void do_usb_add(Monitor *mon, const QDict *qdict)
2540 const char *devname = qdict_get_str(qdict, "devname");
2541 if (usb_device_add(devname, 1) < 0) {
2542 error_report("could not add USB device '%s'", devname);
2546 void do_usb_del(Monitor *mon, const QDict *qdict)
2548 const char *devname = qdict_get_str(qdict, "devname");
2549 if (usb_device_del(devname) < 0) {
2550 error_report("could not delete USB device '%s'", devname);
2554 /***********************************************************/
2555 /* PCMCIA/Cardbus */
2557 static struct pcmcia_socket_entry_s {
2558 PCMCIASocket *socket;
2559 struct pcmcia_socket_entry_s *next;
2560 } *pcmcia_sockets = 0;
2562 void pcmcia_socket_register(PCMCIASocket *socket)
2564 struct pcmcia_socket_entry_s *entry;
2566 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2567 entry->socket = socket;
2568 entry->next = pcmcia_sockets;
2569 pcmcia_sockets = entry;
2572 void pcmcia_socket_unregister(PCMCIASocket *socket)
2574 struct pcmcia_socket_entry_s *entry, **ptr;
2576 ptr = &pcmcia_sockets;
2577 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2578 if (entry->socket == socket) {
2579 *ptr = entry->next;
2580 qemu_free(entry);
2584 void pcmcia_info(Monitor *mon)
2586 struct pcmcia_socket_entry_s *iter;
2588 if (!pcmcia_sockets)
2589 monitor_printf(mon, "No PCMCIA sockets\n");
2591 for (iter = pcmcia_sockets; iter; iter = iter->next)
2592 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2593 iter->socket->attached ? iter->socket->card_string :
2594 "Empty");
2597 /***********************************************************/
2598 /* I/O handling */
2600 typedef struct IOHandlerRecord {
2601 int fd;
2602 IOCanRWHandler *fd_read_poll;
2603 IOHandler *fd_read;
2604 IOHandler *fd_write;
2605 int deleted;
2606 void *opaque;
2607 /* temporary data */
2608 struct pollfd *ufd;
2609 struct IOHandlerRecord *next;
2610 } IOHandlerRecord;
2612 static IOHandlerRecord *first_io_handler;
2614 /* XXX: fd_read_poll should be suppressed, but an API change is
2615 necessary in the character devices to suppress fd_can_read(). */
2616 int qemu_set_fd_handler2(int fd,
2617 IOCanRWHandler *fd_read_poll,
2618 IOHandler *fd_read,
2619 IOHandler *fd_write,
2620 void *opaque)
2622 IOHandlerRecord **pioh, *ioh;
2624 if (!fd_read && !fd_write) {
2625 pioh = &first_io_handler;
2626 for(;;) {
2627 ioh = *pioh;
2628 if (ioh == NULL)
2629 break;
2630 if (ioh->fd == fd) {
2631 ioh->deleted = 1;
2632 break;
2634 pioh = &ioh->next;
2636 } else {
2637 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2638 if (ioh->fd == fd)
2639 goto found;
2641 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2642 ioh->next = first_io_handler;
2643 first_io_handler = ioh;
2644 found:
2645 ioh->fd = fd;
2646 ioh->fd_read_poll = fd_read_poll;
2647 ioh->fd_read = fd_read;
2648 ioh->fd_write = fd_write;
2649 ioh->opaque = opaque;
2650 ioh->deleted = 0;
2652 return 0;
2655 int qemu_set_fd_handler(int fd,
2656 IOHandler *fd_read,
2657 IOHandler *fd_write,
2658 void *opaque)
2660 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2663 #ifdef _WIN32
2664 /***********************************************************/
2665 /* Polling handling */
2667 typedef struct PollingEntry {
2668 PollingFunc *func;
2669 void *opaque;
2670 struct PollingEntry *next;
2671 } PollingEntry;
2673 static PollingEntry *first_polling_entry;
2675 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2677 PollingEntry **ppe, *pe;
2678 pe = qemu_mallocz(sizeof(PollingEntry));
2679 pe->func = func;
2680 pe->opaque = opaque;
2681 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2682 *ppe = pe;
2683 return 0;
2686 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2688 PollingEntry **ppe, *pe;
2689 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2690 pe = *ppe;
2691 if (pe->func == func && pe->opaque == opaque) {
2692 *ppe = pe->next;
2693 qemu_free(pe);
2694 break;
2699 /***********************************************************/
2700 /* Wait objects support */
2701 typedef struct WaitObjects {
2702 int num;
2703 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2704 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2705 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2706 } WaitObjects;
2708 static WaitObjects wait_objects = {0};
2710 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2712 WaitObjects *w = &wait_objects;
2714 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2715 return -1;
2716 w->events[w->num] = handle;
2717 w->func[w->num] = func;
2718 w->opaque[w->num] = opaque;
2719 w->num++;
2720 return 0;
2723 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2725 int i, found;
2726 WaitObjects *w = &wait_objects;
2728 found = 0;
2729 for (i = 0; i < w->num; i++) {
2730 if (w->events[i] == handle)
2731 found = 1;
2732 if (found) {
2733 w->events[i] = w->events[i + 1];
2734 w->func[i] = w->func[i + 1];
2735 w->opaque[i] = w->opaque[i + 1];
2738 if (found)
2739 w->num--;
2741 #endif
2743 /***********************************************************/
2744 /* ram save/restore */
2746 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2747 #define RAM_SAVE_FLAG_COMPRESS 0x02
2748 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2749 #define RAM_SAVE_FLAG_PAGE 0x08
2750 #define RAM_SAVE_FLAG_EOS 0x10
2752 static int is_dup_page(uint8_t *page, uint8_t ch)
2754 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2755 uint32_t *array = (uint32_t *)page;
2756 int i;
2758 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2759 if (array[i] != val)
2760 return 0;
2763 return 1;
2766 static int ram_save_block(QEMUFile *f)
2768 static ram_addr_t current_addr = 0;
2769 ram_addr_t saved_addr = current_addr;
2770 ram_addr_t addr = 0;
2771 int found = 0;
2773 while (addr < last_ram_offset) {
2774 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2775 uint8_t *p;
2777 cpu_physical_memory_reset_dirty(current_addr,
2778 current_addr + TARGET_PAGE_SIZE,
2779 MIGRATION_DIRTY_FLAG);
2781 p = qemu_get_ram_ptr(current_addr);
2783 if (is_dup_page(p, *p)) {
2784 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2785 qemu_put_byte(f, *p);
2786 } else {
2787 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2788 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2791 found = 1;
2792 break;
2794 addr += TARGET_PAGE_SIZE;
2795 current_addr = (saved_addr + addr) % last_ram_offset;
2798 return found;
2801 static uint64_t bytes_transferred;
2803 static ram_addr_t ram_save_remaining(void)
2805 ram_addr_t addr;
2806 ram_addr_t count = 0;
2808 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2809 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2810 count++;
2813 return count;
2816 uint64_t ram_bytes_remaining(void)
2818 return ram_save_remaining() * TARGET_PAGE_SIZE;
2821 uint64_t ram_bytes_transferred(void)
2823 return bytes_transferred;
2826 uint64_t ram_bytes_total(void)
2828 return last_ram_offset;
2831 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
2833 ram_addr_t addr;
2834 uint64_t bytes_transferred_last;
2835 double bwidth = 0;
2836 uint64_t expected_time = 0;
2838 if (stage < 0) {
2839 cpu_physical_memory_set_dirty_tracking(0);
2840 return 0;
2843 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2844 qemu_file_set_error(f);
2845 return 0;
2848 if (stage == 1) {
2849 bytes_transferred = 0;
2851 /* Make sure all dirty bits are set */
2852 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2853 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2854 cpu_physical_memory_set_dirty(addr);
2857 /* Enable dirty memory tracking */
2858 cpu_physical_memory_set_dirty_tracking(1);
2860 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2863 bytes_transferred_last = bytes_transferred;
2864 bwidth = qemu_get_clock_ns(rt_clock);
2866 while (!qemu_file_rate_limit(f)) {
2867 int ret;
2869 ret = ram_save_block(f);
2870 bytes_transferred += ret * TARGET_PAGE_SIZE;
2871 if (ret == 0) /* no more blocks */
2872 break;
2875 bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
2876 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2878 /* if we haven't transferred anything this round, force expected_time to a
2879 * a very high value, but without crashing */
2880 if (bwidth == 0)
2881 bwidth = 0.000001;
2883 /* try transferring iterative blocks of memory */
2884 if (stage == 3) {
2885 /* flush all remaining blocks regardless of rate limiting */
2886 while (ram_save_block(f) != 0) {
2887 bytes_transferred += TARGET_PAGE_SIZE;
2889 cpu_physical_memory_set_dirty_tracking(0);
2892 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2894 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2896 return (stage == 2) && (expected_time <= migrate_max_downtime());
2899 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2901 ram_addr_t addr;
2902 int flags;
2904 if (version_id != 3)
2905 return -EINVAL;
2907 do {
2908 addr = qemu_get_be64(f);
2910 flags = addr & ~TARGET_PAGE_MASK;
2911 addr &= TARGET_PAGE_MASK;
2913 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2914 if (addr != last_ram_offset)
2915 return -EINVAL;
2918 if (flags & RAM_SAVE_FLAG_COMPRESS) {
2919 uint8_t ch = qemu_get_byte(f);
2920 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
2921 #ifndef _WIN32
2922 if (ch == 0 &&
2923 (!kvm_enabled() || kvm_has_sync_mmu())) {
2924 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
2926 #endif
2927 } else if (flags & RAM_SAVE_FLAG_PAGE) {
2928 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
2930 if (qemu_file_has_error(f)) {
2931 return -EIO;
2933 } while (!(flags & RAM_SAVE_FLAG_EOS));
2935 return 0;
2938 void qemu_service_io(void)
2940 qemu_notify_event();
2943 /***********************************************************/
2944 /* machine registration */
2946 static QEMUMachine *first_machine = NULL;
2947 QEMUMachine *current_machine = NULL;
2949 int qemu_register_machine(QEMUMachine *m)
2951 QEMUMachine **pm;
2952 pm = &first_machine;
2953 while (*pm != NULL)
2954 pm = &(*pm)->next;
2955 m->next = NULL;
2956 *pm = m;
2957 return 0;
2960 static QEMUMachine *find_machine(const char *name)
2962 QEMUMachine *m;
2964 for(m = first_machine; m != NULL; m = m->next) {
2965 if (!strcmp(m->name, name))
2966 return m;
2967 if (m->alias && !strcmp(m->alias, name))
2968 return m;
2970 return NULL;
2973 static QEMUMachine *find_default_machine(void)
2975 QEMUMachine *m;
2977 for(m = first_machine; m != NULL; m = m->next) {
2978 if (m->is_default) {
2979 return m;
2982 return NULL;
2985 /***********************************************************/
2986 /* main execution loop */
2988 static void gui_update(void *opaque)
2990 uint64_t interval = GUI_REFRESH_INTERVAL;
2991 DisplayState *ds = opaque;
2992 DisplayChangeListener *dcl = ds->listeners;
2994 qemu_flush_coalesced_mmio_buffer();
2995 dpy_refresh(ds);
2997 while (dcl != NULL) {
2998 if (dcl->gui_timer_interval &&
2999 dcl->gui_timer_interval < interval)
3000 interval = dcl->gui_timer_interval;
3001 dcl = dcl->next;
3003 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3006 static void nographic_update(void *opaque)
3008 uint64_t interval = GUI_REFRESH_INTERVAL;
3010 qemu_flush_coalesced_mmio_buffer();
3011 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3014 void cpu_synchronize_all_states(void)
3016 CPUState *cpu;
3018 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3019 cpu_synchronize_state(cpu);
3023 void cpu_synchronize_all_post_reset(void)
3025 CPUState *cpu;
3027 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3028 cpu_synchronize_post_reset(cpu);
3032 void cpu_synchronize_all_post_init(void)
3034 CPUState *cpu;
3036 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3037 cpu_synchronize_post_init(cpu);
3041 struct vm_change_state_entry {
3042 VMChangeStateHandler *cb;
3043 void *opaque;
3044 QLIST_ENTRY (vm_change_state_entry) entries;
3047 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3049 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3050 void *opaque)
3052 VMChangeStateEntry *e;
3054 e = qemu_mallocz(sizeof (*e));
3056 e->cb = cb;
3057 e->opaque = opaque;
3058 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3059 return e;
3062 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3064 QLIST_REMOVE (e, entries);
3065 qemu_free (e);
3068 static void vm_state_notify(int running, int reason)
3070 VMChangeStateEntry *e;
3072 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3073 e->cb(e->opaque, running, reason);
3077 static void resume_all_vcpus(void);
3078 static void pause_all_vcpus(void);
3080 void vm_start(void)
3082 if (!vm_running) {
3083 cpu_enable_ticks();
3084 vm_running = 1;
3085 vm_state_notify(1, 0);
3086 qemu_rearm_alarm_timer(alarm_timer);
3087 resume_all_vcpus();
3091 /* reset/shutdown handler */
3093 typedef struct QEMUResetEntry {
3094 QTAILQ_ENTRY(QEMUResetEntry) entry;
3095 QEMUResetHandler *func;
3096 void *opaque;
3097 } QEMUResetEntry;
3099 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3100 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3101 static int reset_requested;
3102 static int shutdown_requested;
3103 static int powerdown_requested;
3104 static int debug_requested;
3105 static int vmstop_requested;
3107 int qemu_shutdown_requested(void)
3109 int r = shutdown_requested;
3110 shutdown_requested = 0;
3111 return r;
3114 int qemu_reset_requested(void)
3116 int r = reset_requested;
3117 reset_requested = 0;
3118 return r;
3121 int qemu_powerdown_requested(void)
3123 int r = powerdown_requested;
3124 powerdown_requested = 0;
3125 return r;
3128 static int qemu_debug_requested(void)
3130 int r = debug_requested;
3131 debug_requested = 0;
3132 return r;
3135 static int qemu_vmstop_requested(void)
3137 int r = vmstop_requested;
3138 vmstop_requested = 0;
3139 return r;
3142 static void do_vm_stop(int reason)
3144 if (vm_running) {
3145 cpu_disable_ticks();
3146 vm_running = 0;
3147 pause_all_vcpus();
3148 vm_state_notify(0, reason);
3149 monitor_protocol_event(QEVENT_STOP, NULL);
3153 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3155 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3157 re->func = func;
3158 re->opaque = opaque;
3159 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3162 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3164 QEMUResetEntry *re;
3166 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3167 if (re->func == func && re->opaque == opaque) {
3168 QTAILQ_REMOVE(&reset_handlers, re, entry);
3169 qemu_free(re);
3170 return;
3175 void qemu_system_reset(void)
3177 QEMUResetEntry *re, *nre;
3179 /* reset all devices */
3180 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3181 re->func(re->opaque);
3183 monitor_protocol_event(QEVENT_RESET, NULL);
3184 cpu_synchronize_all_post_reset();
3187 void qemu_system_reset_request(void)
3189 if (no_reboot) {
3190 shutdown_requested = 1;
3191 } else {
3192 reset_requested = 1;
3194 qemu_notify_event();
3197 void qemu_system_shutdown_request(void)
3199 shutdown_requested = 1;
3200 qemu_notify_event();
3203 void qemu_system_powerdown_request(void)
3205 powerdown_requested = 1;
3206 qemu_notify_event();
3209 #ifdef CONFIG_IOTHREAD
3210 static void qemu_system_vmstop_request(int reason)
3212 vmstop_requested = reason;
3213 qemu_notify_event();
3215 #endif
3217 #ifndef _WIN32
3218 static int io_thread_fd = -1;
3220 static void qemu_event_increment(void)
3222 /* Write 8 bytes to be compatible with eventfd. */
3223 static uint64_t val = 1;
3224 ssize_t ret;
3226 if (io_thread_fd == -1)
3227 return;
3229 do {
3230 ret = write(io_thread_fd, &val, sizeof(val));
3231 } while (ret < 0 && errno == EINTR);
3233 /* EAGAIN is fine, a read must be pending. */
3234 if (ret < 0 && errno != EAGAIN) {
3235 fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
3236 strerror(errno));
3237 exit (1);
3241 static void qemu_event_read(void *opaque)
3243 int fd = (unsigned long)opaque;
3244 ssize_t len;
3245 char buffer[512];
3247 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
3248 do {
3249 len = read(fd, buffer, sizeof(buffer));
3250 } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
3253 static int qemu_event_init(void)
3255 int err;
3256 int fds[2];
3258 err = qemu_eventfd(fds);
3259 if (err == -1)
3260 return -errno;
3262 err = fcntl_setfl(fds[0], O_NONBLOCK);
3263 if (err < 0)
3264 goto fail;
3266 err = fcntl_setfl(fds[1], O_NONBLOCK);
3267 if (err < 0)
3268 goto fail;
3270 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3271 (void *)(unsigned long)fds[0]);
3273 io_thread_fd = fds[1];
3274 return 0;
3276 fail:
3277 close(fds[0]);
3278 close(fds[1]);
3279 return err;
3281 #else
3282 HANDLE qemu_event_handle;
3284 static void dummy_event_handler(void *opaque)
3288 static int qemu_event_init(void)
3290 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3291 if (!qemu_event_handle) {
3292 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3293 return -1;
3295 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3296 return 0;
3299 static void qemu_event_increment(void)
3301 if (!SetEvent(qemu_event_handle)) {
3302 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3303 GetLastError());
3304 exit (1);
3307 #endif
3309 static int cpu_can_run(CPUState *env)
3311 if (env->stop)
3312 return 0;
3313 if (env->stopped)
3314 return 0;
3315 if (!vm_running)
3316 return 0;
3317 return 1;
3320 #ifndef CONFIG_IOTHREAD
3321 static int qemu_init_main_loop(void)
3323 return qemu_event_init();
3326 void qemu_init_vcpu(void *_env)
3328 CPUState *env = _env;
3330 env->nr_cores = smp_cores;
3331 env->nr_threads = smp_threads;
3332 if (kvm_enabled())
3333 kvm_init_vcpu(env);
3334 return;
3337 int qemu_cpu_self(void *env)
3339 return 1;
3342 static void resume_all_vcpus(void)
3346 static void pause_all_vcpus(void)
3350 void qemu_cpu_kick(void *env)
3352 return;
3355 void qemu_notify_event(void)
3357 CPUState *env = cpu_single_env;
3359 if (env) {
3360 cpu_exit(env);
3364 void qemu_mutex_lock_iothread(void) {}
3365 void qemu_mutex_unlock_iothread(void) {}
3367 void vm_stop(int reason)
3369 do_vm_stop(reason);
3372 #else /* CONFIG_IOTHREAD */
3374 #include "qemu-thread.h"
3376 QemuMutex qemu_global_mutex;
3377 static QemuMutex qemu_fair_mutex;
3379 static QemuThread io_thread;
3381 static QemuThread *tcg_cpu_thread;
3382 static QemuCond *tcg_halt_cond;
3384 static int qemu_system_ready;
3385 /* cpu creation */
3386 static QemuCond qemu_cpu_cond;
3387 /* system init */
3388 static QemuCond qemu_system_cond;
3389 static QemuCond qemu_pause_cond;
3391 static void tcg_block_io_signals(void);
3392 static void kvm_block_io_signals(CPUState *env);
3393 static void unblock_io_signals(void);
3394 static int tcg_has_work(void);
3395 static int cpu_has_work(CPUState *env);
3397 static int qemu_init_main_loop(void)
3399 int ret;
3401 ret = qemu_event_init();
3402 if (ret)
3403 return ret;
3405 qemu_cond_init(&qemu_pause_cond);
3406 qemu_mutex_init(&qemu_fair_mutex);
3407 qemu_mutex_init(&qemu_global_mutex);
3408 qemu_mutex_lock(&qemu_global_mutex);
3410 unblock_io_signals();
3411 qemu_thread_self(&io_thread);
3413 return 0;
3416 static void qemu_wait_io_event_common(CPUState *env)
3418 if (env->stop) {
3419 env->stop = 0;
3420 env->stopped = 1;
3421 qemu_cond_signal(&qemu_pause_cond);
3425 static void qemu_wait_io_event(CPUState *env)
3427 while (!tcg_has_work())
3428 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3430 qemu_mutex_unlock(&qemu_global_mutex);
3433 * Users of qemu_global_mutex can be starved, having no chance
3434 * to acquire it since this path will get to it first.
3435 * So use another lock to provide fairness.
3437 qemu_mutex_lock(&qemu_fair_mutex);
3438 qemu_mutex_unlock(&qemu_fair_mutex);
3440 qemu_mutex_lock(&qemu_global_mutex);
3441 qemu_wait_io_event_common(env);
3444 static void qemu_kvm_eat_signal(CPUState *env, int timeout)
3446 struct timespec ts;
3447 int r, e;
3448 siginfo_t siginfo;
3449 sigset_t waitset;
3451 ts.tv_sec = timeout / 1000;
3452 ts.tv_nsec = (timeout % 1000) * 1000000;
3454 sigemptyset(&waitset);
3455 sigaddset(&waitset, SIG_IPI);
3457 qemu_mutex_unlock(&qemu_global_mutex);
3458 r = sigtimedwait(&waitset, &siginfo, &ts);
3459 e = errno;
3460 qemu_mutex_lock(&qemu_global_mutex);
3462 if (r == -1 && !(e == EAGAIN || e == EINTR)) {
3463 fprintf(stderr, "sigtimedwait: %s\n", strerror(e));
3464 exit(1);
3468 static void qemu_kvm_wait_io_event(CPUState *env)
3470 while (!cpu_has_work(env))
3471 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3473 qemu_kvm_eat_signal(env, 0);
3474 qemu_wait_io_event_common(env);
3477 static int qemu_cpu_exec(CPUState *env);
3479 static void *kvm_cpu_thread_fn(void *arg)
3481 CPUState *env = arg;
3483 qemu_thread_self(env->thread);
3484 if (kvm_enabled())
3485 kvm_init_vcpu(env);
3487 kvm_block_io_signals(env);
3489 /* signal CPU creation */
3490 qemu_mutex_lock(&qemu_global_mutex);
3491 env->created = 1;
3492 qemu_cond_signal(&qemu_cpu_cond);
3494 /* and wait for machine initialization */
3495 while (!qemu_system_ready)
3496 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3498 while (1) {
3499 if (cpu_can_run(env))
3500 qemu_cpu_exec(env);
3501 qemu_kvm_wait_io_event(env);
3504 return NULL;
3507 static void tcg_cpu_exec(void);
3509 static void *tcg_cpu_thread_fn(void *arg)
3511 CPUState *env = arg;
3513 tcg_block_io_signals();
3514 qemu_thread_self(env->thread);
3516 /* signal CPU creation */
3517 qemu_mutex_lock(&qemu_global_mutex);
3518 for (env = first_cpu; env != NULL; env = env->next_cpu)
3519 env->created = 1;
3520 qemu_cond_signal(&qemu_cpu_cond);
3522 /* and wait for machine initialization */
3523 while (!qemu_system_ready)
3524 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3526 while (1) {
3527 tcg_cpu_exec();
3528 qemu_wait_io_event(cur_cpu);
3531 return NULL;
3534 void qemu_cpu_kick(void *_env)
3536 CPUState *env = _env;
3537 qemu_cond_broadcast(env->halt_cond);
3538 if (kvm_enabled())
3539 qemu_thread_signal(env->thread, SIG_IPI);
3542 int qemu_cpu_self(void *_env)
3544 CPUState *env = _env;
3545 QemuThread this;
3547 qemu_thread_self(&this);
3549 return qemu_thread_equal(&this, env->thread);
3552 static void cpu_signal(int sig)
3554 if (cpu_single_env)
3555 cpu_exit(cpu_single_env);
3558 static void tcg_block_io_signals(void)
3560 sigset_t set;
3561 struct sigaction sigact;
3563 sigemptyset(&set);
3564 sigaddset(&set, SIGUSR2);
3565 sigaddset(&set, SIGIO);
3566 sigaddset(&set, SIGALRM);
3567 sigaddset(&set, SIGCHLD);
3568 pthread_sigmask(SIG_BLOCK, &set, NULL);
3570 sigemptyset(&set);
3571 sigaddset(&set, SIG_IPI);
3572 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3574 memset(&sigact, 0, sizeof(sigact));
3575 sigact.sa_handler = cpu_signal;
3576 sigaction(SIG_IPI, &sigact, NULL);
3579 static void dummy_signal(int sig)
3583 static void kvm_block_io_signals(CPUState *env)
3585 int r;
3586 sigset_t set;
3587 struct sigaction sigact;
3589 sigemptyset(&set);
3590 sigaddset(&set, SIGUSR2);
3591 sigaddset(&set, SIGIO);
3592 sigaddset(&set, SIGALRM);
3593 sigaddset(&set, SIGCHLD);
3594 sigaddset(&set, SIG_IPI);
3595 pthread_sigmask(SIG_BLOCK, &set, NULL);
3597 pthread_sigmask(SIG_BLOCK, NULL, &set);
3598 sigdelset(&set, SIG_IPI);
3600 memset(&sigact, 0, sizeof(sigact));
3601 sigact.sa_handler = dummy_signal;
3602 sigaction(SIG_IPI, &sigact, NULL);
3604 r = kvm_set_signal_mask(env, &set);
3605 if (r) {
3606 fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(r));
3607 exit(1);
3611 static void unblock_io_signals(void)
3613 sigset_t set;
3615 sigemptyset(&set);
3616 sigaddset(&set, SIGUSR2);
3617 sigaddset(&set, SIGIO);
3618 sigaddset(&set, SIGALRM);
3619 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3621 sigemptyset(&set);
3622 sigaddset(&set, SIG_IPI);
3623 pthread_sigmask(SIG_BLOCK, &set, NULL);
3626 static void qemu_signal_lock(unsigned int msecs)
3628 qemu_mutex_lock(&qemu_fair_mutex);
3630 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3631 qemu_thread_signal(tcg_cpu_thread, SIG_IPI);
3632 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3633 break;
3635 qemu_mutex_unlock(&qemu_fair_mutex);
3638 void qemu_mutex_lock_iothread(void)
3640 if (kvm_enabled()) {
3641 qemu_mutex_lock(&qemu_fair_mutex);
3642 qemu_mutex_lock(&qemu_global_mutex);
3643 qemu_mutex_unlock(&qemu_fair_mutex);
3644 } else
3645 qemu_signal_lock(100);
3648 void qemu_mutex_unlock_iothread(void)
3650 qemu_mutex_unlock(&qemu_global_mutex);
3653 static int all_vcpus_paused(void)
3655 CPUState *penv = first_cpu;
3657 while (penv) {
3658 if (!penv->stopped)
3659 return 0;
3660 penv = (CPUState *)penv->next_cpu;
3663 return 1;
3666 static void pause_all_vcpus(void)
3668 CPUState *penv = first_cpu;
3670 while (penv) {
3671 penv->stop = 1;
3672 qemu_thread_signal(penv->thread, SIG_IPI);
3673 qemu_cpu_kick(penv);
3674 penv = (CPUState *)penv->next_cpu;
3677 while (!all_vcpus_paused()) {
3678 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3679 penv = first_cpu;
3680 while (penv) {
3681 qemu_thread_signal(penv->thread, SIG_IPI);
3682 penv = (CPUState *)penv->next_cpu;
3687 static void resume_all_vcpus(void)
3689 CPUState *penv = first_cpu;
3691 while (penv) {
3692 penv->stop = 0;
3693 penv->stopped = 0;
3694 qemu_thread_signal(penv->thread, SIG_IPI);
3695 qemu_cpu_kick(penv);
3696 penv = (CPUState *)penv->next_cpu;
3700 static void tcg_init_vcpu(void *_env)
3702 CPUState *env = _env;
3703 /* share a single thread for all cpus with TCG */
3704 if (!tcg_cpu_thread) {
3705 env->thread = qemu_mallocz(sizeof(QemuThread));
3706 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3707 qemu_cond_init(env->halt_cond);
3708 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3709 while (env->created == 0)
3710 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3711 tcg_cpu_thread = env->thread;
3712 tcg_halt_cond = env->halt_cond;
3713 } else {
3714 env->thread = tcg_cpu_thread;
3715 env->halt_cond = tcg_halt_cond;
3719 static void kvm_start_vcpu(CPUState *env)
3721 env->thread = qemu_mallocz(sizeof(QemuThread));
3722 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3723 qemu_cond_init(env->halt_cond);
3724 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3725 while (env->created == 0)
3726 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3729 void qemu_init_vcpu(void *_env)
3731 CPUState *env = _env;
3733 env->nr_cores = smp_cores;
3734 env->nr_threads = smp_threads;
3735 if (kvm_enabled())
3736 kvm_start_vcpu(env);
3737 else
3738 tcg_init_vcpu(env);
3741 void qemu_notify_event(void)
3743 qemu_event_increment();
3746 void vm_stop(int reason)
3748 QemuThread me;
3749 qemu_thread_self(&me);
3751 if (!qemu_thread_equal(&me, &io_thread)) {
3752 qemu_system_vmstop_request(reason);
3754 * FIXME: should not return to device code in case
3755 * vm_stop() has been requested.
3757 if (cpu_single_env) {
3758 cpu_exit(cpu_single_env);
3759 cpu_single_env->stop = 1;
3761 return;
3763 do_vm_stop(reason);
3766 #endif
3769 #ifdef _WIN32
3770 static void host_main_loop_wait(int *timeout)
3772 int ret, ret2, i;
3773 PollingEntry *pe;
3776 /* XXX: need to suppress polling by better using win32 events */
3777 ret = 0;
3778 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3779 ret |= pe->func(pe->opaque);
3781 if (ret == 0) {
3782 int err;
3783 WaitObjects *w = &wait_objects;
3785 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3786 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3787 if (w->func[ret - WAIT_OBJECT_0])
3788 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3790 /* Check for additional signaled events */
3791 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3793 /* Check if event is signaled */
3794 ret2 = WaitForSingleObject(w->events[i], 0);
3795 if(ret2 == WAIT_OBJECT_0) {
3796 if (w->func[i])
3797 w->func[i](w->opaque[i]);
3798 } else if (ret2 == WAIT_TIMEOUT) {
3799 } else {
3800 err = GetLastError();
3801 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3804 } else if (ret == WAIT_TIMEOUT) {
3805 } else {
3806 err = GetLastError();
3807 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3811 *timeout = 0;
3813 #else
3814 static void host_main_loop_wait(int *timeout)
3817 #endif
3819 void main_loop_wait(int timeout)
3821 IOHandlerRecord *ioh;
3822 fd_set rfds, wfds, xfds;
3823 int ret, nfds;
3824 struct timeval tv;
3826 qemu_bh_update_timeout(&timeout);
3828 host_main_loop_wait(&timeout);
3830 /* poll any events */
3831 /* XXX: separate device handlers from system ones */
3832 nfds = -1;
3833 FD_ZERO(&rfds);
3834 FD_ZERO(&wfds);
3835 FD_ZERO(&xfds);
3836 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3837 if (ioh->deleted)
3838 continue;
3839 if (ioh->fd_read &&
3840 (!ioh->fd_read_poll ||
3841 ioh->fd_read_poll(ioh->opaque) != 0)) {
3842 FD_SET(ioh->fd, &rfds);
3843 if (ioh->fd > nfds)
3844 nfds = ioh->fd;
3846 if (ioh->fd_write) {
3847 FD_SET(ioh->fd, &wfds);
3848 if (ioh->fd > nfds)
3849 nfds = ioh->fd;
3853 tv.tv_sec = timeout / 1000;
3854 tv.tv_usec = (timeout % 1000) * 1000;
3856 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3858 qemu_mutex_unlock_iothread();
3859 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3860 qemu_mutex_lock_iothread();
3861 if (ret > 0) {
3862 IOHandlerRecord **pioh;
3864 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3865 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3866 ioh->fd_read(ioh->opaque);
3868 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3869 ioh->fd_write(ioh->opaque);
3873 /* remove deleted IO handlers */
3874 pioh = &first_io_handler;
3875 while (*pioh) {
3876 ioh = *pioh;
3877 if (ioh->deleted) {
3878 *pioh = ioh->next;
3879 qemu_free(ioh);
3880 } else
3881 pioh = &ioh->next;
3885 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3887 /* rearm timer, if not periodic */
3888 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3889 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3890 qemu_rearm_alarm_timer(alarm_timer);
3893 /* vm time timers */
3894 if (vm_running) {
3895 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3896 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3897 qemu_get_clock(vm_clock));
3900 /* real time timers */
3901 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3902 qemu_get_clock(rt_clock));
3904 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3905 qemu_get_clock(host_clock));
3907 /* Check bottom-halves last in case any of the earlier events triggered
3908 them. */
3909 qemu_bh_poll();
3913 static int qemu_cpu_exec(CPUState *env)
3915 int ret;
3916 #ifdef CONFIG_PROFILER
3917 int64_t ti;
3918 #endif
3920 #ifdef CONFIG_PROFILER
3921 ti = profile_getclock();
3922 #endif
3923 if (use_icount) {
3924 int64_t count;
3925 int decr;
3926 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3927 env->icount_decr.u16.low = 0;
3928 env->icount_extra = 0;
3929 count = qemu_next_deadline();
3930 count = (count + (1 << icount_time_shift) - 1)
3931 >> icount_time_shift;
3932 qemu_icount += count;
3933 decr = (count > 0xffff) ? 0xffff : count;
3934 count -= decr;
3935 env->icount_decr.u16.low = decr;
3936 env->icount_extra = count;
3938 ret = cpu_exec(env);
3939 #ifdef CONFIG_PROFILER
3940 qemu_time += profile_getclock() - ti;
3941 #endif
3942 if (use_icount) {
3943 /* Fold pending instructions back into the
3944 instruction counter, and clear the interrupt flag. */
3945 qemu_icount -= (env->icount_decr.u16.low
3946 + env->icount_extra);
3947 env->icount_decr.u32 = 0;
3948 env->icount_extra = 0;
3950 return ret;
3953 static void tcg_cpu_exec(void)
3955 int ret = 0;
3957 if (next_cpu == NULL)
3958 next_cpu = first_cpu;
3959 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3960 CPUState *env = cur_cpu = next_cpu;
3962 if (timer_alarm_pending) {
3963 timer_alarm_pending = 0;
3964 break;
3966 if (cpu_can_run(env))
3967 ret = qemu_cpu_exec(env);
3968 else if (env->stop)
3969 break;
3971 if (ret == EXCP_DEBUG) {
3972 gdb_set_stop_cpu(env);
3973 debug_requested = 1;
3974 break;
3979 static int cpu_has_work(CPUState *env)
3981 if (env->stop)
3982 return 1;
3983 if (env->stopped)
3984 return 0;
3985 if (!env->halted)
3986 return 1;
3987 if (qemu_cpu_has_work(env))
3988 return 1;
3989 return 0;
3992 static int tcg_has_work(void)
3994 CPUState *env;
3996 for (env = first_cpu; env != NULL; env = env->next_cpu)
3997 if (cpu_has_work(env))
3998 return 1;
3999 return 0;
4002 static int qemu_calculate_timeout(void)
4004 #ifndef CONFIG_IOTHREAD
4005 int timeout;
4007 if (!vm_running)
4008 timeout = 5000;
4009 else if (tcg_has_work())
4010 timeout = 0;
4011 else if (!use_icount)
4012 timeout = 5000;
4013 else {
4014 /* XXX: use timeout computed from timers */
4015 int64_t add;
4016 int64_t delta;
4017 /* Advance virtual time to the next event. */
4018 if (use_icount == 1) {
4019 /* When not using an adaptive execution frequency
4020 we tend to get badly out of sync with real time,
4021 so just delay for a reasonable amount of time. */
4022 delta = 0;
4023 } else {
4024 delta = cpu_get_icount() - cpu_get_clock();
4026 if (delta > 0) {
4027 /* If virtual time is ahead of real time then just
4028 wait for IO. */
4029 timeout = (delta / 1000000) + 1;
4030 } else {
4031 /* Wait for either IO to occur or the next
4032 timer event. */
4033 add = qemu_next_deadline();
4034 /* We advance the timer before checking for IO.
4035 Limit the amount we advance so that early IO
4036 activity won't get the guest too far ahead. */
4037 if (add > 10000000)
4038 add = 10000000;
4039 delta += add;
4040 add = (add + (1 << icount_time_shift) - 1)
4041 >> icount_time_shift;
4042 qemu_icount += add;
4043 timeout = delta / 1000000;
4044 if (timeout < 0)
4045 timeout = 0;
4049 return timeout;
4050 #else /* CONFIG_IOTHREAD */
4051 return 1000;
4052 #endif
4055 static int vm_can_run(void)
4057 if (powerdown_requested)
4058 return 0;
4059 if (reset_requested)
4060 return 0;
4061 if (shutdown_requested)
4062 return 0;
4063 if (debug_requested)
4064 return 0;
4065 return 1;
4068 qemu_irq qemu_system_powerdown;
4070 static void main_loop(void)
4072 int r;
4074 #ifdef CONFIG_IOTHREAD
4075 qemu_system_ready = 1;
4076 qemu_cond_broadcast(&qemu_system_cond);
4077 #endif
4079 for (;;) {
4080 do {
4081 #ifdef CONFIG_PROFILER
4082 int64_t ti;
4083 #endif
4084 #ifndef CONFIG_IOTHREAD
4085 tcg_cpu_exec();
4086 #endif
4087 #ifdef CONFIG_PROFILER
4088 ti = profile_getclock();
4089 #endif
4090 main_loop_wait(qemu_calculate_timeout());
4091 #ifdef CONFIG_PROFILER
4092 dev_time += profile_getclock() - ti;
4093 #endif
4094 } while (vm_can_run());
4096 if (qemu_debug_requested()) {
4097 vm_stop(EXCP_DEBUG);
4099 if (qemu_shutdown_requested()) {
4100 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
4101 if (no_shutdown) {
4102 vm_stop(0);
4103 no_shutdown = 0;
4104 } else
4105 break;
4107 if (qemu_reset_requested()) {
4108 pause_all_vcpus();
4109 qemu_system_reset();
4110 resume_all_vcpus();
4112 if (qemu_powerdown_requested()) {
4113 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
4114 qemu_irq_raise(qemu_system_powerdown);
4116 if ((r = qemu_vmstop_requested())) {
4117 vm_stop(r);
4120 pause_all_vcpus();
4123 static void version(void)
4125 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4128 static void help(int exitcode)
4130 const char *options_help =
4131 #define DEF(option, opt_arg, opt_enum, opt_help) \
4132 opt_help
4133 #define DEFHEADING(text) stringify(text) "\n"
4134 #include "qemu-options.h"
4135 #undef DEF
4136 #undef DEFHEADING
4137 #undef GEN_DOCS
4139 version();
4140 printf("usage: %s [options] [disk_image]\n"
4141 "\n"
4142 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4143 "\n"
4144 "%s\n"
4145 "During emulation, the following keys are useful:\n"
4146 "ctrl-alt-f toggle full screen\n"
4147 "ctrl-alt-n switch to virtual console 'n'\n"
4148 "ctrl-alt toggle mouse and keyboard grab\n"
4149 "\n"
4150 "When using -nographic, press 'ctrl-a h' to get some help.\n",
4151 "qemu",
4152 options_help);
4153 exit(exitcode);
4156 #define HAS_ARG 0x0001
4158 enum {
4159 #define DEF(option, opt_arg, opt_enum, opt_help) \
4160 opt_enum,
4161 #define DEFHEADING(text)
4162 #include "qemu-options.h"
4163 #undef DEF
4164 #undef DEFHEADING
4165 #undef GEN_DOCS
4168 typedef struct QEMUOption {
4169 const char *name;
4170 int flags;
4171 int index;
4172 } QEMUOption;
4174 static const QEMUOption qemu_options[] = {
4175 { "h", 0, QEMU_OPTION_h },
4176 #define DEF(option, opt_arg, opt_enum, opt_help) \
4177 { option, opt_arg, opt_enum },
4178 #define DEFHEADING(text)
4179 #include "qemu-options.h"
4180 #undef DEF
4181 #undef DEFHEADING
4182 #undef GEN_DOCS
4183 { NULL },
4186 #ifdef HAS_AUDIO
4187 struct soundhw soundhw[] = {
4188 #ifdef HAS_AUDIO_CHOICE
4189 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4191 "pcspk",
4192 "PC speaker",
4195 { .init_isa = pcspk_audio_init }
4197 #endif
4199 #ifdef CONFIG_SB16
4201 "sb16",
4202 "Creative Sound Blaster 16",
4205 { .init_isa = SB16_init }
4207 #endif
4209 #ifdef CONFIG_CS4231A
4211 "cs4231a",
4212 "CS4231A",
4215 { .init_isa = cs4231a_init }
4217 #endif
4219 #ifdef CONFIG_ADLIB
4221 "adlib",
4222 #ifdef HAS_YMF262
4223 "Yamaha YMF262 (OPL3)",
4224 #else
4225 "Yamaha YM3812 (OPL2)",
4226 #endif
4229 { .init_isa = Adlib_init }
4231 #endif
4233 #ifdef CONFIG_GUS
4235 "gus",
4236 "Gravis Ultrasound GF1",
4239 { .init_isa = GUS_init }
4241 #endif
4243 #ifdef CONFIG_AC97
4245 "ac97",
4246 "Intel 82801AA AC97 Audio",
4249 { .init_pci = ac97_init }
4251 #endif
4253 #ifdef CONFIG_ES1370
4255 "es1370",
4256 "ENSONIQ AudioPCI ES1370",
4259 { .init_pci = es1370_init }
4261 #endif
4263 #endif /* HAS_AUDIO_CHOICE */
4265 { NULL, NULL, 0, 0, { NULL } }
4268 static void select_soundhw (const char *optarg)
4270 struct soundhw *c;
4272 if (*optarg == '?') {
4273 show_valid_cards:
4275 printf ("Valid sound card names (comma separated):\n");
4276 for (c = soundhw; c->name; ++c) {
4277 printf ("%-11s %s\n", c->name, c->descr);
4279 printf ("\n-soundhw all will enable all of the above\n");
4280 exit (*optarg != '?');
4282 else {
4283 size_t l;
4284 const char *p;
4285 char *e;
4286 int bad_card = 0;
4288 if (!strcmp (optarg, "all")) {
4289 for (c = soundhw; c->name; ++c) {
4290 c->enabled = 1;
4292 return;
4295 p = optarg;
4296 while (*p) {
4297 e = strchr (p, ',');
4298 l = !e ? strlen (p) : (size_t) (e - p);
4300 for (c = soundhw; c->name; ++c) {
4301 if (!strncmp (c->name, p, l) && !c->name[l]) {
4302 c->enabled = 1;
4303 break;
4307 if (!c->name) {
4308 if (l > 80) {
4309 fprintf (stderr,
4310 "Unknown sound card name (too big to show)\n");
4312 else {
4313 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4314 (int) l, p);
4316 bad_card = 1;
4318 p += l + (e != NULL);
4321 if (bad_card)
4322 goto show_valid_cards;
4325 #endif
4327 static void select_vgahw (const char *p)
4329 const char *opts;
4331 default_vga = 0;
4332 vga_interface_type = VGA_NONE;
4333 if (strstart(p, "std", &opts)) {
4334 vga_interface_type = VGA_STD;
4335 } else if (strstart(p, "cirrus", &opts)) {
4336 vga_interface_type = VGA_CIRRUS;
4337 } else if (strstart(p, "vmware", &opts)) {
4338 vga_interface_type = VGA_VMWARE;
4339 } else if (strstart(p, "xenfb", &opts)) {
4340 vga_interface_type = VGA_XENFB;
4341 } else if (!strstart(p, "none", &opts)) {
4342 invalid_vga:
4343 fprintf(stderr, "Unknown vga type: %s\n", p);
4344 exit(1);
4346 while (*opts) {
4347 const char *nextopt;
4349 if (strstart(opts, ",retrace=", &nextopt)) {
4350 opts = nextopt;
4351 if (strstart(opts, "dumb", &nextopt))
4352 vga_retrace_method = VGA_RETRACE_DUMB;
4353 else if (strstart(opts, "precise", &nextopt))
4354 vga_retrace_method = VGA_RETRACE_PRECISE;
4355 else goto invalid_vga;
4356 } else goto invalid_vga;
4357 opts = nextopt;
4361 #ifdef TARGET_I386
4362 static int balloon_parse(const char *arg)
4364 QemuOpts *opts;
4366 if (strcmp(arg, "none") == 0) {
4367 return 0;
4370 if (!strncmp(arg, "virtio", 6)) {
4371 if (arg[6] == ',') {
4372 /* have params -> parse them */
4373 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4374 if (!opts)
4375 return -1;
4376 } else {
4377 /* create empty opts */
4378 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4380 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4381 return 0;
4384 return -1;
4386 #endif
4388 #ifdef _WIN32
4389 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4391 exit(STATUS_CONTROL_C_EXIT);
4392 return TRUE;
4394 #endif
4396 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4398 int ret;
4400 if(strlen(str) != 36)
4401 return -1;
4403 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4404 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4405 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4407 if(ret != 16)
4408 return -1;
4410 #ifdef TARGET_I386
4411 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4412 #endif
4414 return 0;
4417 #ifndef _WIN32
4419 static void termsig_handler(int signal)
4421 qemu_system_shutdown_request();
4424 static void sigchld_handler(int signal)
4426 waitpid(-1, NULL, WNOHANG);
4429 static void sighandler_setup(void)
4431 struct sigaction act;
4433 memset(&act, 0, sizeof(act));
4434 act.sa_handler = termsig_handler;
4435 sigaction(SIGINT, &act, NULL);
4436 sigaction(SIGHUP, &act, NULL);
4437 sigaction(SIGTERM, &act, NULL);
4439 act.sa_handler = sigchld_handler;
4440 act.sa_flags = SA_NOCLDSTOP;
4441 sigaction(SIGCHLD, &act, NULL);
4444 #endif
4446 #ifdef _WIN32
4447 /* Look for support files in the same directory as the executable. */
4448 static char *find_datadir(const char *argv0)
4450 char *p;
4451 char buf[MAX_PATH];
4452 DWORD len;
4454 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4455 if (len == 0) {
4456 return NULL;
4459 buf[len] = 0;
4460 p = buf + len - 1;
4461 while (p != buf && *p != '\\')
4462 p--;
4463 *p = 0;
4464 if (access(buf, R_OK) == 0) {
4465 return qemu_strdup(buf);
4467 return NULL;
4469 #else /* !_WIN32 */
4471 /* Find a likely location for support files using the location of the binary.
4472 For installed binaries this will be "$bindir/../share/qemu". When
4473 running from the build tree this will be "$bindir/../pc-bios". */
4474 #define SHARE_SUFFIX "/share/qemu"
4475 #define BUILD_SUFFIX "/pc-bios"
4476 static char *find_datadir(const char *argv0)
4478 char *dir;
4479 char *p = NULL;
4480 char *res;
4481 char buf[PATH_MAX];
4482 size_t max_len;
4484 #if defined(__linux__)
4486 int len;
4487 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4488 if (len > 0) {
4489 buf[len] = 0;
4490 p = buf;
4493 #elif defined(__FreeBSD__)
4495 int len;
4496 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4497 if (len > 0) {
4498 buf[len] = 0;
4499 p = buf;
4502 #endif
4503 /* If we don't have any way of figuring out the actual executable
4504 location then try argv[0]. */
4505 if (!p) {
4506 p = realpath(argv0, buf);
4507 if (!p) {
4508 return NULL;
4511 dir = dirname(p);
4512 dir = dirname(dir);
4514 max_len = strlen(dir) +
4515 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4516 res = qemu_mallocz(max_len);
4517 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4518 if (access(res, R_OK)) {
4519 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4520 if (access(res, R_OK)) {
4521 qemu_free(res);
4522 res = NULL;
4526 return res;
4528 #undef SHARE_SUFFIX
4529 #undef BUILD_SUFFIX
4530 #endif
4532 char *qemu_find_file(int type, const char *name)
4534 int len;
4535 const char *subdir;
4536 char *buf;
4538 /* If name contains path separators then try it as a straight path. */
4539 if ((strchr(name, '/') || strchr(name, '\\'))
4540 && access(name, R_OK) == 0) {
4541 return qemu_strdup(name);
4543 switch (type) {
4544 case QEMU_FILE_TYPE_BIOS:
4545 subdir = "";
4546 break;
4547 case QEMU_FILE_TYPE_KEYMAP:
4548 subdir = "keymaps/";
4549 break;
4550 default:
4551 abort();
4553 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4554 buf = qemu_mallocz(len);
4555 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4556 if (access(buf, R_OK)) {
4557 qemu_free(buf);
4558 return NULL;
4560 return buf;
4563 static int device_help_func(QemuOpts *opts, void *opaque)
4565 return qdev_device_help(opts);
4568 static int device_init_func(QemuOpts *opts, void *opaque)
4570 DeviceState *dev;
4572 dev = qdev_device_add(opts);
4573 if (!dev)
4574 return -1;
4575 return 0;
4578 static int chardev_init_func(QemuOpts *opts, void *opaque)
4580 CharDriverState *chr;
4582 chr = qemu_chr_open_opts(opts, NULL);
4583 if (!chr)
4584 return -1;
4585 return 0;
4588 static int mon_init_func(QemuOpts *opts, void *opaque)
4590 CharDriverState *chr;
4591 const char *chardev;
4592 const char *mode;
4593 int flags;
4595 mode = qemu_opt_get(opts, "mode");
4596 if (mode == NULL) {
4597 mode = "readline";
4599 if (strcmp(mode, "readline") == 0) {
4600 flags = MONITOR_USE_READLINE;
4601 } else if (strcmp(mode, "control") == 0) {
4602 flags = MONITOR_USE_CONTROL;
4603 } else {
4604 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4605 exit(1);
4608 if (qemu_opt_get_bool(opts, "default", 0))
4609 flags |= MONITOR_IS_DEFAULT;
4611 chardev = qemu_opt_get(opts, "chardev");
4612 chr = qemu_chr_find(chardev);
4613 if (chr == NULL) {
4614 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4615 exit(1);
4618 monitor_init(chr, flags);
4619 return 0;
4622 static void monitor_parse(const char *optarg, const char *mode)
4624 static int monitor_device_index = 0;
4625 QemuOpts *opts;
4626 const char *p;
4627 char label[32];
4628 int def = 0;
4630 if (strstart(optarg, "chardev:", &p)) {
4631 snprintf(label, sizeof(label), "%s", p);
4632 } else {
4633 if (monitor_device_index) {
4634 snprintf(label, sizeof(label), "monitor%d",
4635 monitor_device_index);
4636 } else {
4637 snprintf(label, sizeof(label), "monitor");
4638 def = 1;
4640 opts = qemu_chr_parse_compat(label, optarg);
4641 if (!opts) {
4642 fprintf(stderr, "parse error: %s\n", optarg);
4643 exit(1);
4647 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4648 if (!opts) {
4649 fprintf(stderr, "duplicate chardev: %s\n", label);
4650 exit(1);
4652 qemu_opt_set(opts, "mode", mode);
4653 qemu_opt_set(opts, "chardev", label);
4654 if (def)
4655 qemu_opt_set(opts, "default", "on");
4656 monitor_device_index++;
4659 struct device_config {
4660 enum {
4661 DEV_USB, /* -usbdevice */
4662 DEV_BT, /* -bt */
4663 DEV_SERIAL, /* -serial */
4664 DEV_PARALLEL, /* -parallel */
4665 DEV_VIRTCON, /* -virtioconsole */
4666 DEV_DEBUGCON, /* -debugcon */
4667 } type;
4668 const char *cmdline;
4669 QTAILQ_ENTRY(device_config) next;
4671 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4673 static void add_device_config(int type, const char *cmdline)
4675 struct device_config *conf;
4677 conf = qemu_mallocz(sizeof(*conf));
4678 conf->type = type;
4679 conf->cmdline = cmdline;
4680 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4683 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4685 struct device_config *conf;
4686 int rc;
4688 QTAILQ_FOREACH(conf, &device_configs, next) {
4689 if (conf->type != type)
4690 continue;
4691 rc = func(conf->cmdline);
4692 if (0 != rc)
4693 return rc;
4695 return 0;
4698 static int serial_parse(const char *devname)
4700 static int index = 0;
4701 char label[32];
4703 if (strcmp(devname, "none") == 0)
4704 return 0;
4705 if (index == MAX_SERIAL_PORTS) {
4706 fprintf(stderr, "qemu: too many serial ports\n");
4707 exit(1);
4709 snprintf(label, sizeof(label), "serial%d", index);
4710 serial_hds[index] = qemu_chr_open(label, devname, NULL);
4711 if (!serial_hds[index]) {
4712 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4713 devname, strerror(errno));
4714 return -1;
4716 index++;
4717 return 0;
4720 static int parallel_parse(const char *devname)
4722 static int index = 0;
4723 char label[32];
4725 if (strcmp(devname, "none") == 0)
4726 return 0;
4727 if (index == MAX_PARALLEL_PORTS) {
4728 fprintf(stderr, "qemu: too many parallel ports\n");
4729 exit(1);
4731 snprintf(label, sizeof(label), "parallel%d", index);
4732 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4733 if (!parallel_hds[index]) {
4734 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4735 devname, strerror(errno));
4736 return -1;
4738 index++;
4739 return 0;
4742 static int virtcon_parse(const char *devname)
4744 static int index = 0;
4745 char label[32];
4746 QemuOpts *bus_opts, *dev_opts;
4748 if (strcmp(devname, "none") == 0)
4749 return 0;
4750 if (index == MAX_VIRTIO_CONSOLES) {
4751 fprintf(stderr, "qemu: too many virtio consoles\n");
4752 exit(1);
4755 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4756 qemu_opt_set(bus_opts, "driver", "virtio-serial");
4758 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4759 qemu_opt_set(dev_opts, "driver", "virtconsole");
4761 snprintf(label, sizeof(label), "virtcon%d", index);
4762 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
4763 if (!virtcon_hds[index]) {
4764 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
4765 devname, strerror(errno));
4766 return -1;
4768 qemu_opt_set(dev_opts, "chardev", label);
4770 index++;
4771 return 0;
4774 static int debugcon_parse(const char *devname)
4776 QemuOpts *opts;
4778 if (!qemu_chr_open("debugcon", devname, NULL)) {
4779 exit(1);
4781 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
4782 if (!opts) {
4783 fprintf(stderr, "qemu: already have a debugcon device\n");
4784 exit(1);
4786 qemu_opt_set(opts, "driver", "isa-debugcon");
4787 qemu_opt_set(opts, "chardev", "debugcon");
4788 return 0;
4791 static const QEMUOption *lookup_opt(int argc, char **argv,
4792 const char **poptarg, int *poptind)
4794 const QEMUOption *popt;
4795 int optind = *poptind;
4796 char *r = argv[optind];
4797 const char *optarg;
4799 optind++;
4800 /* Treat --foo the same as -foo. */
4801 if (r[1] == '-')
4802 r++;
4803 popt = qemu_options;
4804 for(;;) {
4805 if (!popt->name) {
4806 fprintf(stderr, "%s: invalid option -- '%s'\n",
4807 argv[0], r);
4808 exit(1);
4810 if (!strcmp(popt->name, r + 1))
4811 break;
4812 popt++;
4814 if (popt->flags & HAS_ARG) {
4815 if (optind >= argc) {
4816 fprintf(stderr, "%s: option '%s' requires an argument\n",
4817 argv[0], r);
4818 exit(1);
4820 optarg = argv[optind++];
4821 } else {
4822 optarg = NULL;
4825 *poptarg = optarg;
4826 *poptind = optind;
4828 return popt;
4831 int main(int argc, char **argv, char **envp)
4833 const char *gdbstub_dev = NULL;
4834 uint32_t boot_devices_bitmap = 0;
4835 int i;
4836 int snapshot, linux_boot, net_boot;
4837 const char *initrd_filename;
4838 const char *kernel_filename, *kernel_cmdline;
4839 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4840 DisplayState *ds;
4841 DisplayChangeListener *dcl;
4842 int cyls, heads, secs, translation;
4843 QemuOpts *hda_opts = NULL, *opts;
4844 int optind;
4845 const char *optarg;
4846 const char *loadvm = NULL;
4847 QEMUMachine *machine;
4848 const char *cpu_model;
4849 #ifndef _WIN32
4850 int fds[2];
4851 #endif
4852 int tb_size;
4853 const char *pid_file = NULL;
4854 const char *incoming = NULL;
4855 #ifndef _WIN32
4856 int fd = 0;
4857 struct passwd *pwd = NULL;
4858 const char *chroot_dir = NULL;
4859 const char *run_as = NULL;
4860 #endif
4861 CPUState *env;
4862 int show_vnc_port = 0;
4863 int defconfig = 1;
4865 init_clocks();
4867 qemu_cache_utils_init(envp);
4869 QLIST_INIT (&vm_change_state_head);
4870 #ifndef _WIN32
4872 struct sigaction act;
4873 sigfillset(&act.sa_mask);
4874 act.sa_flags = 0;
4875 act.sa_handler = SIG_IGN;
4876 sigaction(SIGPIPE, &act, NULL);
4878 #else
4879 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4880 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4881 QEMU to run on a single CPU */
4883 HANDLE h;
4884 DWORD mask, smask;
4885 int i;
4886 h = GetCurrentProcess();
4887 if (GetProcessAffinityMask(h, &mask, &smask)) {
4888 for(i = 0; i < 32; i++) {
4889 if (mask & (1 << i))
4890 break;
4892 if (i != 32) {
4893 mask = 1 << i;
4894 SetProcessAffinityMask(h, mask);
4898 #endif
4900 module_call_init(MODULE_INIT_MACHINE);
4901 machine = find_default_machine();
4902 cpu_model = NULL;
4903 initrd_filename = NULL;
4904 ram_size = 0;
4905 snapshot = 0;
4906 kernel_filename = NULL;
4907 kernel_cmdline = "";
4908 cyls = heads = secs = 0;
4909 translation = BIOS_ATA_TRANSLATION_AUTO;
4911 for (i = 0; i < MAX_NODES; i++) {
4912 node_mem[i] = 0;
4913 node_cpumask[i] = 0;
4916 nb_numa_nodes = 0;
4917 nb_nics = 0;
4919 tb_size = 0;
4920 autostart= 1;
4922 /* first pass of option parsing */
4923 optind = 1;
4924 while (optind < argc) {
4925 if (argv[optind][0] != '-') {
4926 /* disk image */
4927 optind++;
4928 continue;
4929 } else {
4930 const QEMUOption *popt;
4932 popt = lookup_opt(argc, argv, &optarg, &optind);
4933 switch (popt->index) {
4934 case QEMU_OPTION_nodefconfig:
4935 defconfig=0;
4936 break;
4941 if (defconfig) {
4942 FILE *fp;
4943 fp = fopen(CONFIG_QEMU_CONFDIR "/qemu.conf", "r");
4944 if (fp) {
4945 if (qemu_config_parse(fp) != 0) {
4946 exit(1);
4948 fclose(fp);
4951 fp = fopen(CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf", "r");
4952 if (fp) {
4953 if (qemu_config_parse(fp) != 0) {
4954 exit(1);
4956 fclose(fp);
4959 #if defined(cpudef_setup)
4960 cpudef_setup(); /* parse cpu definitions in target config file */
4961 #endif
4963 /* second pass of option parsing */
4964 optind = 1;
4965 for(;;) {
4966 if (optind >= argc)
4967 break;
4968 if (argv[optind][0] != '-') {
4969 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4970 } else {
4971 const QEMUOption *popt;
4973 popt = lookup_opt(argc, argv, &optarg, &optind);
4974 switch(popt->index) {
4975 case QEMU_OPTION_M:
4976 machine = find_machine(optarg);
4977 if (!machine) {
4978 QEMUMachine *m;
4979 printf("Supported machines are:\n");
4980 for(m = first_machine; m != NULL; m = m->next) {
4981 if (m->alias)
4982 printf("%-10s %s (alias of %s)\n",
4983 m->alias, m->desc, m->name);
4984 printf("%-10s %s%s\n",
4985 m->name, m->desc,
4986 m->is_default ? " (default)" : "");
4988 exit(*optarg != '?');
4990 break;
4991 case QEMU_OPTION_cpu:
4992 /* hw initialization will check this */
4993 if (*optarg == '?') {
4994 /* XXX: implement xxx_cpu_list for targets that still miss it */
4995 #if defined(cpu_list_id)
4996 cpu_list_id(stdout, &fprintf, optarg);
4997 #elif defined(cpu_list)
4998 cpu_list(stdout, &fprintf); /* deprecated */
4999 #endif
5000 exit(0);
5001 } else {
5002 cpu_model = optarg;
5004 break;
5005 case QEMU_OPTION_initrd:
5006 initrd_filename = optarg;
5007 break;
5008 case QEMU_OPTION_hda:
5009 if (cyls == 0)
5010 hda_opts = drive_add(optarg, HD_ALIAS, 0);
5011 else
5012 hda_opts = drive_add(optarg, HD_ALIAS
5013 ",cyls=%d,heads=%d,secs=%d%s",
5014 0, cyls, heads, secs,
5015 translation == BIOS_ATA_TRANSLATION_LBA ?
5016 ",trans=lba" :
5017 translation == BIOS_ATA_TRANSLATION_NONE ?
5018 ",trans=none" : "");
5019 break;
5020 case QEMU_OPTION_hdb:
5021 case QEMU_OPTION_hdc:
5022 case QEMU_OPTION_hdd:
5023 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5024 break;
5025 case QEMU_OPTION_drive:
5026 drive_add(NULL, "%s", optarg);
5027 break;
5028 case QEMU_OPTION_set:
5029 if (qemu_set_option(optarg) != 0)
5030 exit(1);
5031 break;
5032 case QEMU_OPTION_global:
5033 if (qemu_global_option(optarg) != 0)
5034 exit(1);
5035 break;
5036 case QEMU_OPTION_mtdblock:
5037 drive_add(optarg, MTD_ALIAS);
5038 break;
5039 case QEMU_OPTION_sd:
5040 drive_add(optarg, SD_ALIAS);
5041 break;
5042 case QEMU_OPTION_pflash:
5043 drive_add(optarg, PFLASH_ALIAS);
5044 break;
5045 case QEMU_OPTION_snapshot:
5046 snapshot = 1;
5047 break;
5048 case QEMU_OPTION_hdachs:
5050 const char *p;
5051 p = optarg;
5052 cyls = strtol(p, (char **)&p, 0);
5053 if (cyls < 1 || cyls > 16383)
5054 goto chs_fail;
5055 if (*p != ',')
5056 goto chs_fail;
5057 p++;
5058 heads = strtol(p, (char **)&p, 0);
5059 if (heads < 1 || heads > 16)
5060 goto chs_fail;
5061 if (*p != ',')
5062 goto chs_fail;
5063 p++;
5064 secs = strtol(p, (char **)&p, 0);
5065 if (secs < 1 || secs > 63)
5066 goto chs_fail;
5067 if (*p == ',') {
5068 p++;
5069 if (!strcmp(p, "none"))
5070 translation = BIOS_ATA_TRANSLATION_NONE;
5071 else if (!strcmp(p, "lba"))
5072 translation = BIOS_ATA_TRANSLATION_LBA;
5073 else if (!strcmp(p, "auto"))
5074 translation = BIOS_ATA_TRANSLATION_AUTO;
5075 else
5076 goto chs_fail;
5077 } else if (*p != '\0') {
5078 chs_fail:
5079 fprintf(stderr, "qemu: invalid physical CHS format\n");
5080 exit(1);
5082 if (hda_opts != NULL) {
5083 char num[16];
5084 snprintf(num, sizeof(num), "%d", cyls);
5085 qemu_opt_set(hda_opts, "cyls", num);
5086 snprintf(num, sizeof(num), "%d", heads);
5087 qemu_opt_set(hda_opts, "heads", num);
5088 snprintf(num, sizeof(num), "%d", secs);
5089 qemu_opt_set(hda_opts, "secs", num);
5090 if (translation == BIOS_ATA_TRANSLATION_LBA)
5091 qemu_opt_set(hda_opts, "trans", "lba");
5092 if (translation == BIOS_ATA_TRANSLATION_NONE)
5093 qemu_opt_set(hda_opts, "trans", "none");
5096 break;
5097 case QEMU_OPTION_numa:
5098 if (nb_numa_nodes >= MAX_NODES) {
5099 fprintf(stderr, "qemu: too many NUMA nodes\n");
5100 exit(1);
5102 numa_add(optarg);
5103 break;
5104 case QEMU_OPTION_nographic:
5105 display_type = DT_NOGRAPHIC;
5106 break;
5107 #ifdef CONFIG_CURSES
5108 case QEMU_OPTION_curses:
5109 display_type = DT_CURSES;
5110 break;
5111 #endif
5112 case QEMU_OPTION_portrait:
5113 graphic_rotate = 1;
5114 break;
5115 case QEMU_OPTION_kernel:
5116 kernel_filename = optarg;
5117 break;
5118 case QEMU_OPTION_append:
5119 kernel_cmdline = optarg;
5120 break;
5121 case QEMU_OPTION_cdrom:
5122 drive_add(optarg, CDROM_ALIAS);
5123 break;
5124 case QEMU_OPTION_boot:
5126 static const char * const params[] = {
5127 "order", "once", "menu", NULL
5129 char buf[sizeof(boot_devices)];
5130 char *standard_boot_devices;
5131 int legacy = 0;
5133 if (!strchr(optarg, '=')) {
5134 legacy = 1;
5135 pstrcpy(buf, sizeof(buf), optarg);
5136 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5137 fprintf(stderr,
5138 "qemu: unknown boot parameter '%s' in '%s'\n",
5139 buf, optarg);
5140 exit(1);
5143 if (legacy ||
5144 get_param_value(buf, sizeof(buf), "order", optarg)) {
5145 boot_devices_bitmap = parse_bootdevices(buf);
5146 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5148 if (!legacy) {
5149 if (get_param_value(buf, sizeof(buf),
5150 "once", optarg)) {
5151 boot_devices_bitmap |= parse_bootdevices(buf);
5152 standard_boot_devices = qemu_strdup(boot_devices);
5153 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5154 qemu_register_reset(restore_boot_devices,
5155 standard_boot_devices);
5157 if (get_param_value(buf, sizeof(buf),
5158 "menu", optarg)) {
5159 if (!strcmp(buf, "on")) {
5160 boot_menu = 1;
5161 } else if (!strcmp(buf, "off")) {
5162 boot_menu = 0;
5163 } else {
5164 fprintf(stderr,
5165 "qemu: invalid option value '%s'\n",
5166 buf);
5167 exit(1);
5172 break;
5173 case QEMU_OPTION_fda:
5174 case QEMU_OPTION_fdb:
5175 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5176 break;
5177 #ifdef TARGET_I386
5178 case QEMU_OPTION_no_fd_bootchk:
5179 fd_bootchk = 0;
5180 break;
5181 #endif
5182 case QEMU_OPTION_netdev:
5183 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
5184 exit(1);
5186 break;
5187 case QEMU_OPTION_net:
5188 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
5189 exit(1);
5191 break;
5192 #ifdef CONFIG_SLIRP
5193 case QEMU_OPTION_tftp:
5194 legacy_tftp_prefix = optarg;
5195 break;
5196 case QEMU_OPTION_bootp:
5197 legacy_bootp_filename = optarg;
5198 break;
5199 #ifndef _WIN32
5200 case QEMU_OPTION_smb:
5201 if (net_slirp_smb(optarg) < 0)
5202 exit(1);
5203 break;
5204 #endif
5205 case QEMU_OPTION_redir:
5206 if (net_slirp_redir(optarg) < 0)
5207 exit(1);
5208 break;
5209 #endif
5210 case QEMU_OPTION_bt:
5211 add_device_config(DEV_BT, optarg);
5212 break;
5213 #ifdef HAS_AUDIO
5214 case QEMU_OPTION_audio_help:
5215 AUD_help ();
5216 exit (0);
5217 break;
5218 case QEMU_OPTION_soundhw:
5219 select_soundhw (optarg);
5220 break;
5221 #endif
5222 case QEMU_OPTION_h:
5223 help(0);
5224 break;
5225 case QEMU_OPTION_version:
5226 version();
5227 exit(0);
5228 break;
5229 case QEMU_OPTION_m: {
5230 uint64_t value;
5231 char *ptr;
5233 value = strtoul(optarg, &ptr, 10);
5234 switch (*ptr) {
5235 case 0: case 'M': case 'm':
5236 value <<= 20;
5237 break;
5238 case 'G': case 'g':
5239 value <<= 30;
5240 break;
5241 default:
5242 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5243 exit(1);
5246 /* On 32-bit hosts, QEMU is limited by virtual address space */
5247 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5248 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5249 exit(1);
5251 if (value != (uint64_t)(ram_addr_t)value) {
5252 fprintf(stderr, "qemu: ram size too large\n");
5253 exit(1);
5255 ram_size = value;
5256 break;
5258 case QEMU_OPTION_mempath:
5259 mem_path = optarg;
5260 break;
5261 #ifdef MAP_POPULATE
5262 case QEMU_OPTION_mem_prealloc:
5263 mem_prealloc = 1;
5264 break;
5265 #endif
5266 case QEMU_OPTION_d:
5268 int mask;
5269 const CPULogItem *item;
5271 mask = cpu_str_to_log_mask(optarg);
5272 if (!mask) {
5273 printf("Log items (comma separated):\n");
5274 for(item = cpu_log_items; item->mask != 0; item++) {
5275 printf("%-10s %s\n", item->name, item->help);
5277 exit(1);
5279 cpu_set_log(mask);
5281 break;
5282 case QEMU_OPTION_s:
5283 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5284 break;
5285 case QEMU_OPTION_gdb:
5286 gdbstub_dev = optarg;
5287 break;
5288 case QEMU_OPTION_L:
5289 data_dir = optarg;
5290 break;
5291 case QEMU_OPTION_bios:
5292 bios_name = optarg;
5293 break;
5294 case QEMU_OPTION_singlestep:
5295 singlestep = 1;
5296 break;
5297 case QEMU_OPTION_S:
5298 autostart = 0;
5299 break;
5300 case QEMU_OPTION_k:
5301 keyboard_layout = optarg;
5302 break;
5303 case QEMU_OPTION_localtime:
5304 rtc_utc = 0;
5305 break;
5306 case QEMU_OPTION_vga:
5307 select_vgahw (optarg);
5308 break;
5309 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5310 case QEMU_OPTION_g:
5312 const char *p;
5313 int w, h, depth;
5314 p = optarg;
5315 w = strtol(p, (char **)&p, 10);
5316 if (w <= 0) {
5317 graphic_error:
5318 fprintf(stderr, "qemu: invalid resolution or depth\n");
5319 exit(1);
5321 if (*p != 'x')
5322 goto graphic_error;
5323 p++;
5324 h = strtol(p, (char **)&p, 10);
5325 if (h <= 0)
5326 goto graphic_error;
5327 if (*p == 'x') {
5328 p++;
5329 depth = strtol(p, (char **)&p, 10);
5330 if (depth != 8 && depth != 15 && depth != 16 &&
5331 depth != 24 && depth != 32)
5332 goto graphic_error;
5333 } else if (*p == '\0') {
5334 depth = graphic_depth;
5335 } else {
5336 goto graphic_error;
5339 graphic_width = w;
5340 graphic_height = h;
5341 graphic_depth = depth;
5343 break;
5344 #endif
5345 case QEMU_OPTION_echr:
5347 char *r;
5348 term_escape_char = strtol(optarg, &r, 0);
5349 if (r == optarg)
5350 printf("Bad argument to echr\n");
5351 break;
5353 case QEMU_OPTION_monitor:
5354 monitor_parse(optarg, "readline");
5355 default_monitor = 0;
5356 break;
5357 case QEMU_OPTION_qmp:
5358 monitor_parse(optarg, "control");
5359 default_monitor = 0;
5360 break;
5361 case QEMU_OPTION_mon:
5362 opts = qemu_opts_parse(&qemu_mon_opts, optarg, "chardev");
5363 if (!opts) {
5364 fprintf(stderr, "parse error: %s\n", optarg);
5365 exit(1);
5367 default_monitor = 0;
5368 break;
5369 case QEMU_OPTION_chardev:
5370 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5371 if (!opts) {
5372 fprintf(stderr, "parse error: %s\n", optarg);
5373 exit(1);
5375 break;
5376 case QEMU_OPTION_serial:
5377 add_device_config(DEV_SERIAL, optarg);
5378 default_serial = 0;
5379 break;
5380 case QEMU_OPTION_watchdog:
5381 if (watchdog) {
5382 fprintf(stderr,
5383 "qemu: only one watchdog option may be given\n");
5384 return 1;
5386 watchdog = optarg;
5387 break;
5388 case QEMU_OPTION_watchdog_action:
5389 if (select_watchdog_action(optarg) == -1) {
5390 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5391 exit(1);
5393 break;
5394 case QEMU_OPTION_virtiocon:
5395 add_device_config(DEV_VIRTCON, optarg);
5396 default_virtcon = 0;
5397 break;
5398 case QEMU_OPTION_parallel:
5399 add_device_config(DEV_PARALLEL, optarg);
5400 default_parallel = 0;
5401 break;
5402 case QEMU_OPTION_debugcon:
5403 add_device_config(DEV_DEBUGCON, optarg);
5404 break;
5405 case QEMU_OPTION_loadvm:
5406 loadvm = optarg;
5407 break;
5408 case QEMU_OPTION_full_screen:
5409 full_screen = 1;
5410 break;
5411 #ifdef CONFIG_SDL
5412 case QEMU_OPTION_no_frame:
5413 no_frame = 1;
5414 break;
5415 case QEMU_OPTION_alt_grab:
5416 alt_grab = 1;
5417 break;
5418 case QEMU_OPTION_ctrl_grab:
5419 ctrl_grab = 1;
5420 break;
5421 case QEMU_OPTION_no_quit:
5422 no_quit = 1;
5423 break;
5424 case QEMU_OPTION_sdl:
5425 display_type = DT_SDL;
5426 break;
5427 #endif
5428 case QEMU_OPTION_pidfile:
5429 pid_file = optarg;
5430 break;
5431 #ifdef TARGET_I386
5432 case QEMU_OPTION_win2k_hack:
5433 win2k_install_hack = 1;
5434 break;
5435 case QEMU_OPTION_rtc_td_hack:
5436 rtc_td_hack = 1;
5437 break;
5438 case QEMU_OPTION_acpitable:
5439 if(acpi_table_add(optarg) < 0) {
5440 fprintf(stderr, "Wrong acpi table provided\n");
5441 exit(1);
5443 break;
5444 case QEMU_OPTION_smbios:
5445 if(smbios_entry_add(optarg) < 0) {
5446 fprintf(stderr, "Wrong smbios provided\n");
5447 exit(1);
5449 break;
5450 #endif
5451 #ifdef CONFIG_KVM
5452 case QEMU_OPTION_enable_kvm:
5453 kvm_allowed = 1;
5454 break;
5455 #endif
5456 case QEMU_OPTION_usb:
5457 usb_enabled = 1;
5458 break;
5459 case QEMU_OPTION_usbdevice:
5460 usb_enabled = 1;
5461 add_device_config(DEV_USB, optarg);
5462 break;
5463 case QEMU_OPTION_device:
5464 if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5465 exit(1);
5467 break;
5468 case QEMU_OPTION_smp:
5469 smp_parse(optarg);
5470 if (smp_cpus < 1) {
5471 fprintf(stderr, "Invalid number of CPUs\n");
5472 exit(1);
5474 if (max_cpus < smp_cpus) {
5475 fprintf(stderr, "maxcpus must be equal to or greater than "
5476 "smp\n");
5477 exit(1);
5479 if (max_cpus > 255) {
5480 fprintf(stderr, "Unsupported number of maxcpus\n");
5481 exit(1);
5483 break;
5484 case QEMU_OPTION_vnc:
5485 display_type = DT_VNC;
5486 vnc_display = optarg;
5487 break;
5488 #ifdef TARGET_I386
5489 case QEMU_OPTION_no_acpi:
5490 acpi_enabled = 0;
5491 break;
5492 case QEMU_OPTION_no_hpet:
5493 no_hpet = 1;
5494 break;
5495 case QEMU_OPTION_balloon:
5496 if (balloon_parse(optarg) < 0) {
5497 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5498 exit(1);
5500 break;
5501 #endif
5502 case QEMU_OPTION_no_reboot:
5503 no_reboot = 1;
5504 break;
5505 case QEMU_OPTION_no_shutdown:
5506 no_shutdown = 1;
5507 break;
5508 case QEMU_OPTION_show_cursor:
5509 cursor_hide = 0;
5510 break;
5511 case QEMU_OPTION_uuid:
5512 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5513 fprintf(stderr, "Fail to parse UUID string."
5514 " Wrong format.\n");
5515 exit(1);
5517 break;
5518 #ifndef _WIN32
5519 case QEMU_OPTION_daemonize:
5520 daemonize = 1;
5521 break;
5522 #endif
5523 case QEMU_OPTION_option_rom:
5524 if (nb_option_roms >= MAX_OPTION_ROMS) {
5525 fprintf(stderr, "Too many option ROMs\n");
5526 exit(1);
5528 option_rom[nb_option_roms] = optarg;
5529 nb_option_roms++;
5530 break;
5531 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5532 case QEMU_OPTION_semihosting:
5533 semihosting_enabled = 1;
5534 break;
5535 #endif
5536 case QEMU_OPTION_name:
5537 qemu_name = qemu_strdup(optarg);
5539 char *p = strchr(qemu_name, ',');
5540 if (p != NULL) {
5541 *p++ = 0;
5542 if (strncmp(p, "process=", 8)) {
5543 fprintf(stderr, "Unknown subargument %s to -name", p);
5544 exit(1);
5546 p += 8;
5547 set_proc_name(p);
5550 break;
5551 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5552 case QEMU_OPTION_prom_env:
5553 if (nb_prom_envs >= MAX_PROM_ENVS) {
5554 fprintf(stderr, "Too many prom variables\n");
5555 exit(1);
5557 prom_envs[nb_prom_envs] = optarg;
5558 nb_prom_envs++;
5559 break;
5560 #endif
5561 #ifdef TARGET_ARM
5562 case QEMU_OPTION_old_param:
5563 old_param = 1;
5564 break;
5565 #endif
5566 case QEMU_OPTION_clock:
5567 configure_alarms(optarg);
5568 break;
5569 case QEMU_OPTION_startdate:
5570 configure_rtc_date_offset(optarg, 1);
5571 break;
5572 case QEMU_OPTION_rtc:
5573 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5574 if (!opts) {
5575 fprintf(stderr, "parse error: %s\n", optarg);
5576 exit(1);
5578 configure_rtc(opts);
5579 break;
5580 case QEMU_OPTION_tb_size:
5581 tb_size = strtol(optarg, NULL, 0);
5582 if (tb_size < 0)
5583 tb_size = 0;
5584 break;
5585 case QEMU_OPTION_icount:
5586 use_icount = 1;
5587 if (strcmp(optarg, "auto") == 0) {
5588 icount_time_shift = -1;
5589 } else {
5590 icount_time_shift = strtol(optarg, NULL, 0);
5592 break;
5593 case QEMU_OPTION_incoming:
5594 incoming = optarg;
5595 break;
5596 case QEMU_OPTION_nodefaults:
5597 default_serial = 0;
5598 default_parallel = 0;
5599 default_virtcon = 0;
5600 default_monitor = 0;
5601 default_vga = 0;
5602 default_net = 0;
5603 default_floppy = 0;
5604 default_cdrom = 0;
5605 default_sdcard = 0;
5606 break;
5607 #ifndef _WIN32
5608 case QEMU_OPTION_chroot:
5609 chroot_dir = optarg;
5610 break;
5611 case QEMU_OPTION_runas:
5612 run_as = optarg;
5613 break;
5614 #endif
5615 #ifdef CONFIG_XEN
5616 case QEMU_OPTION_xen_domid:
5617 xen_domid = atoi(optarg);
5618 break;
5619 case QEMU_OPTION_xen_create:
5620 xen_mode = XEN_CREATE;
5621 break;
5622 case QEMU_OPTION_xen_attach:
5623 xen_mode = XEN_ATTACH;
5624 break;
5625 #endif
5626 case QEMU_OPTION_readconfig:
5628 FILE *fp;
5629 fp = fopen(optarg, "r");
5630 if (fp == NULL) {
5631 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5632 exit(1);
5634 if (qemu_config_parse(fp) != 0) {
5635 exit(1);
5637 fclose(fp);
5638 break;
5640 case QEMU_OPTION_writeconfig:
5642 FILE *fp;
5643 if (strcmp(optarg, "-") == 0) {
5644 fp = stdout;
5645 } else {
5646 fp = fopen(optarg, "w");
5647 if (fp == NULL) {
5648 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5649 exit(1);
5652 qemu_config_write(fp);
5653 fclose(fp);
5654 break;
5660 /* If no data_dir is specified then try to find it relative to the
5661 executable path. */
5662 if (!data_dir) {
5663 data_dir = find_datadir(argv[0]);
5665 /* If all else fails use the install patch specified when building. */
5666 if (!data_dir) {
5667 data_dir = CONFIG_QEMU_SHAREDIR;
5671 * Default to max_cpus = smp_cpus, in case the user doesn't
5672 * specify a max_cpus value.
5674 if (!max_cpus)
5675 max_cpus = smp_cpus;
5677 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5678 if (smp_cpus > machine->max_cpus) {
5679 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5680 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5681 machine->max_cpus);
5682 exit(1);
5685 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5686 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
5688 if (machine->no_serial) {
5689 default_serial = 0;
5691 if (machine->no_parallel) {
5692 default_parallel = 0;
5694 if (!machine->use_virtcon) {
5695 default_virtcon = 0;
5697 if (machine->no_vga) {
5698 default_vga = 0;
5700 if (machine->no_floppy) {
5701 default_floppy = 0;
5703 if (machine->no_cdrom) {
5704 default_cdrom = 0;
5706 if (machine->no_sdcard) {
5707 default_sdcard = 0;
5710 if (display_type == DT_NOGRAPHIC) {
5711 if (default_parallel)
5712 add_device_config(DEV_PARALLEL, "null");
5713 if (default_serial && default_monitor) {
5714 add_device_config(DEV_SERIAL, "mon:stdio");
5715 } else if (default_virtcon && default_monitor) {
5716 add_device_config(DEV_VIRTCON, "mon:stdio");
5717 } else {
5718 if (default_serial)
5719 add_device_config(DEV_SERIAL, "stdio");
5720 if (default_virtcon)
5721 add_device_config(DEV_VIRTCON, "stdio");
5722 if (default_monitor)
5723 monitor_parse("stdio", "readline");
5725 } else {
5726 if (default_serial)
5727 add_device_config(DEV_SERIAL, "vc:80Cx24C");
5728 if (default_parallel)
5729 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
5730 if (default_monitor)
5731 monitor_parse("vc:80Cx24C", "readline");
5732 if (default_virtcon)
5733 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
5735 if (default_vga)
5736 vga_interface_type = VGA_CIRRUS;
5738 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5739 exit(1);
5741 #ifndef _WIN32
5742 if (daemonize) {
5743 pid_t pid;
5745 if (pipe(fds) == -1)
5746 exit(1);
5748 pid = fork();
5749 if (pid > 0) {
5750 uint8_t status;
5751 ssize_t len;
5753 close(fds[1]);
5755 again:
5756 len = read(fds[0], &status, 1);
5757 if (len == -1 && (errno == EINTR))
5758 goto again;
5760 if (len != 1)
5761 exit(1);
5762 else if (status == 1) {
5763 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5764 exit(1);
5765 } else
5766 exit(0);
5767 } else if (pid < 0)
5768 exit(1);
5770 close(fds[0]);
5771 qemu_set_cloexec(fds[1]);
5773 setsid();
5775 pid = fork();
5776 if (pid > 0)
5777 exit(0);
5778 else if (pid < 0)
5779 exit(1);
5781 umask(027);
5783 signal(SIGTSTP, SIG_IGN);
5784 signal(SIGTTOU, SIG_IGN);
5785 signal(SIGTTIN, SIG_IGN);
5787 #endif
5789 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5790 #ifndef _WIN32
5791 if (daemonize) {
5792 uint8_t status = 1;
5793 if (write(fds[1], &status, 1) != 1) {
5794 perror("daemonize. Writing to pipe\n");
5796 } else
5797 #endif
5798 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5799 exit(1);
5802 if (kvm_enabled()) {
5803 int ret;
5805 ret = kvm_init(smp_cpus);
5806 if (ret < 0) {
5807 fprintf(stderr, "failed to initialize KVM\n");
5808 exit(1);
5812 if (qemu_init_main_loop()) {
5813 fprintf(stderr, "qemu_init_main_loop failed\n");
5814 exit(1);
5816 linux_boot = (kernel_filename != NULL);
5818 if (!linux_boot && *kernel_cmdline != '\0') {
5819 fprintf(stderr, "-append only allowed with -kernel option\n");
5820 exit(1);
5823 if (!linux_boot && initrd_filename != NULL) {
5824 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5825 exit(1);
5828 #ifndef _WIN32
5829 /* Win32 doesn't support line-buffering and requires size >= 2 */
5830 setvbuf(stdout, NULL, _IOLBF, 0);
5831 #endif
5833 if (init_timer_alarm() < 0) {
5834 fprintf(stderr, "could not initialize alarm timer\n");
5835 exit(1);
5837 if (use_icount && icount_time_shift < 0) {
5838 use_icount = 2;
5839 /* 125MIPS seems a reasonable initial guess at the guest speed.
5840 It will be corrected fairly quickly anyway. */
5841 icount_time_shift = 3;
5842 init_icount_adjust();
5845 #ifdef _WIN32
5846 socket_init();
5847 #endif
5849 if (net_init_clients() < 0) {
5850 exit(1);
5853 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5854 net_set_boot_mask(net_boot);
5856 /* init the bluetooth world */
5857 if (foreach_device_config(DEV_BT, bt_parse))
5858 exit(1);
5860 /* init the memory */
5861 if (ram_size == 0)
5862 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5864 /* init the dynamic translator */
5865 cpu_exec_init_all(tb_size * 1024 * 1024);
5867 bdrv_init_with_whitelist();
5869 blk_mig_init();
5871 if (default_cdrom) {
5872 /* we always create the cdrom drive, even if no disk is there */
5873 drive_add(NULL, CDROM_ALIAS);
5876 if (default_floppy) {
5877 /* we always create at least one floppy */
5878 drive_add(NULL, FD_ALIAS, 0);
5881 if (default_sdcard) {
5882 /* we always create one sd slot, even if no card is in it */
5883 drive_add(NULL, SD_ALIAS);
5886 /* open the virtual block devices */
5887 if (snapshot)
5888 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5889 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5890 exit(1);
5892 vmstate_register(0, &vmstate_timers ,&timers_state);
5893 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
5894 ram_load, NULL);
5896 if (nb_numa_nodes > 0) {
5897 int i;
5899 if (nb_numa_nodes > smp_cpus) {
5900 nb_numa_nodes = smp_cpus;
5903 /* If no memory size if given for any node, assume the default case
5904 * and distribute the available memory equally across all nodes
5906 for (i = 0; i < nb_numa_nodes; i++) {
5907 if (node_mem[i] != 0)
5908 break;
5910 if (i == nb_numa_nodes) {
5911 uint64_t usedmem = 0;
5913 /* On Linux, the each node's border has to be 8MB aligned,
5914 * the final node gets the rest.
5916 for (i = 0; i < nb_numa_nodes - 1; i++) {
5917 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5918 usedmem += node_mem[i];
5920 node_mem[i] = ram_size - usedmem;
5923 for (i = 0; i < nb_numa_nodes; i++) {
5924 if (node_cpumask[i] != 0)
5925 break;
5927 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5928 * must cope with this anyway, because there are BIOSes out there in
5929 * real machines which also use this scheme.
5931 if (i == nb_numa_nodes) {
5932 for (i = 0; i < smp_cpus; i++) {
5933 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5938 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
5939 exit(1);
5940 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
5941 exit(1);
5942 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
5943 exit(1);
5944 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
5945 exit(1);
5947 module_call_init(MODULE_INIT_DEVICE);
5949 if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
5950 exit(0);
5952 if (watchdog) {
5953 i = select_watchdog(watchdog);
5954 if (i > 0)
5955 exit (i == 1 ? 1 : 0);
5958 if (machine->compat_props) {
5959 qdev_prop_register_global_list(machine->compat_props);
5961 qemu_add_globals();
5963 machine->init(ram_size, boot_devices,
5964 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5966 cpu_synchronize_all_post_init();
5968 #ifndef _WIN32
5969 /* must be after terminal init, SDL library changes signal handlers */
5970 sighandler_setup();
5971 #endif
5973 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5974 for (i = 0; i < nb_numa_nodes; i++) {
5975 if (node_cpumask[i] & (1 << env->cpu_index)) {
5976 env->numa_node = i;
5981 current_machine = machine;
5983 /* init USB devices */
5984 if (usb_enabled) {
5985 if (foreach_device_config(DEV_USB, usb_parse) < 0)
5986 exit(1);
5989 /* init generic devices */
5990 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5991 exit(1);
5993 net_check_clients();
5995 /* just use the first displaystate for the moment */
5996 ds = get_displaystate();
5998 if (display_type == DT_DEFAULT) {
5999 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6000 display_type = DT_SDL;
6001 #else
6002 display_type = DT_VNC;
6003 vnc_display = "localhost:0,to=99";
6004 show_vnc_port = 1;
6005 #endif
6009 switch (display_type) {
6010 case DT_NOGRAPHIC:
6011 break;
6012 #if defined(CONFIG_CURSES)
6013 case DT_CURSES:
6014 curses_display_init(ds, full_screen);
6015 break;
6016 #endif
6017 #if defined(CONFIG_SDL)
6018 case DT_SDL:
6019 sdl_display_init(ds, full_screen, no_frame);
6020 break;
6021 #elif defined(CONFIG_COCOA)
6022 case DT_SDL:
6023 cocoa_display_init(ds, full_screen);
6024 break;
6025 #endif
6026 case DT_VNC:
6027 vnc_display_init(ds);
6028 if (vnc_display_open(ds, vnc_display) < 0)
6029 exit(1);
6031 if (show_vnc_port) {
6032 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6034 break;
6035 default:
6036 break;
6038 dpy_resize(ds);
6040 dcl = ds->listeners;
6041 while (dcl != NULL) {
6042 if (dcl->dpy_refresh != NULL) {
6043 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6044 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6046 dcl = dcl->next;
6049 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6050 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6051 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6054 text_consoles_set_display(ds);
6056 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
6057 exit(1);
6059 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6060 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6061 gdbstub_dev);
6062 exit(1);
6065 qdev_machine_creation_done();
6067 if (rom_load_all() != 0) {
6068 fprintf(stderr, "rom loading failed\n");
6069 exit(1);
6072 qemu_system_reset();
6073 if (loadvm) {
6074 if (load_vmstate(loadvm) < 0) {
6075 autostart = 0;
6079 if (incoming) {
6080 qemu_start_incoming_migration(incoming);
6081 } else if (autostart) {
6082 vm_start();
6085 #ifndef _WIN32
6086 if (daemonize) {
6087 uint8_t status = 0;
6088 ssize_t len;
6090 again1:
6091 len = write(fds[1], &status, 1);
6092 if (len == -1 && (errno == EINTR))
6093 goto again1;
6095 if (len != 1)
6096 exit(1);
6098 if (chdir("/")) {
6099 perror("not able to chdir to /");
6100 exit(1);
6102 TFR(fd = qemu_open("/dev/null", O_RDWR));
6103 if (fd == -1)
6104 exit(1);
6107 if (run_as) {
6108 pwd = getpwnam(run_as);
6109 if (!pwd) {
6110 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6111 exit(1);
6115 if (chroot_dir) {
6116 if (chroot(chroot_dir) < 0) {
6117 fprintf(stderr, "chroot failed\n");
6118 exit(1);
6120 if (chdir("/")) {
6121 perror("not able to chdir to /");
6122 exit(1);
6126 if (run_as) {
6127 if (setgid(pwd->pw_gid) < 0) {
6128 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6129 exit(1);
6131 if (setuid(pwd->pw_uid) < 0) {
6132 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6133 exit(1);
6135 if (setuid(0) != -1) {
6136 fprintf(stderr, "Dropping privileges failed\n");
6137 exit(1);
6141 if (daemonize) {
6142 dup2(fd, 0);
6143 dup2(fd, 1);
6144 dup2(fd, 2);
6146 close(fd);
6148 #endif
6150 main_loop();
6151 quit_timers();
6152 net_cleanup();
6154 return 0;