default devices: network
[qemu/mdroth.git] / vl.c
blob4825836266736a205465347aeb3bb47d13540f3f
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"
160 #include "disas.h"
162 #include "exec-all.h"
164 #include "qemu_socket.h"
166 #include "slirp/libslirp.h"
168 #include "qemu-queue.h"
170 //#define DEBUG_NET
171 //#define DEBUG_SLIRP
173 #define DEFAULT_RAM_SIZE 128
175 /* Maximum number of monitor devices */
176 #define MAX_MONITOR_DEVICES 10
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 static DisplayState *display_state;
186 DisplayType display_type = DT_DEFAULT;
187 const char* keyboard_layout = NULL;
188 ram_addr_t ram_size;
189 int nb_nics;
190 NICInfo nd_table[MAX_NICS];
191 int vm_running;
192 int autostart;
193 static int rtc_utc = 1;
194 static int rtc_date_offset = -1; /* -1 means no change */
195 QEMUClock *rtc_clock;
196 int vga_interface_type = VGA_NONE;
197 #ifdef TARGET_SPARC
198 int graphic_width = 1024;
199 int graphic_height = 768;
200 int graphic_depth = 8;
201 #else
202 int graphic_width = 800;
203 int graphic_height = 600;
204 int graphic_depth = 15;
205 #endif
206 static int full_screen = 0;
207 #ifdef CONFIG_SDL
208 static int no_frame = 0;
209 #endif
210 int no_quit = 0;
211 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
212 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
213 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
214 CharDriverState *monitor_hds[MAX_MONITOR_DEVICES];
215 #ifdef TARGET_I386
216 int win2k_install_hack = 0;
217 int rtc_td_hack = 0;
218 #endif
219 int usb_enabled = 0;
220 int singlestep = 0;
221 int smp_cpus = 1;
222 int max_cpus = 0;
223 int smp_cores = 1;
224 int smp_threads = 1;
225 const char *vnc_display;
226 int acpi_enabled = 1;
227 int no_hpet = 0;
228 int fd_bootchk = 1;
229 int no_reboot = 0;
230 int no_shutdown = 0;
231 int cursor_hide = 1;
232 int graphic_rotate = 0;
233 uint8_t irq0override = 1;
234 #ifndef _WIN32
235 int daemonize = 0;
236 #endif
237 const char *watchdog;
238 const char *option_rom[MAX_OPTION_ROMS];
239 int nb_option_roms;
240 int semihosting_enabled = 0;
241 #ifdef TARGET_ARM
242 int old_param = 0;
243 #endif
244 const char *qemu_name;
245 int alt_grab = 0;
246 int ctrl_grab = 0;
247 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
248 unsigned int nb_prom_envs = 0;
249 const char *prom_envs[MAX_PROM_ENVS];
250 #endif
251 int boot_menu;
253 int nb_numa_nodes;
254 uint64_t node_mem[MAX_NODES];
255 uint64_t node_cpumask[MAX_NODES];
257 static CPUState *cur_cpu;
258 static CPUState *next_cpu;
259 static int timer_alarm_pending = 1;
260 /* Conversion factor from emulated instructions to virtual clock ticks. */
261 static int icount_time_shift;
262 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
263 #define MAX_ICOUNT_SHIFT 10
264 /* Compensate for varying guest execution speed. */
265 static int64_t qemu_icount_bias;
266 static QEMUTimer *icount_rt_timer;
267 static QEMUTimer *icount_vm_timer;
268 static QEMUTimer *nographic_timer;
270 uint8_t qemu_uuid[16];
272 static QEMUBootSetHandler *boot_set_handler;
273 static void *boot_set_opaque;
275 static int default_serial = 1;
276 static int default_parallel = 1;
277 static int default_monitor = 1;
278 static int default_vga = 1;
280 static struct {
281 const char *driver;
282 int *flag;
283 } default_list[] = {
284 { .driver = "isa-serial", .flag = &default_serial },
285 { .driver = "isa-parallel", .flag = &default_parallel },
286 { .driver = "VGA", .flag = &default_vga },
287 { .driver = "Cirrus VGA", .flag = &default_vga },
288 { .driver = "QEMUware SVGA", .flag = &default_vga },
291 static int default_driver_check(QemuOpts *opts, void *opaque)
293 const char *driver = qemu_opt_get(opts, "driver");
294 int i;
296 if (!driver)
297 return 0;
298 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
299 if (strcmp(default_list[i].driver, driver) != 0)
300 continue;
301 *(default_list[i].flag) = 0;
303 return 0;
306 /***********************************************************/
307 /* x86 ISA bus support */
309 target_phys_addr_t isa_mem_base = 0;
310 PicState2 *isa_pic;
312 /***********************************************************/
313 void hw_error(const char *fmt, ...)
315 va_list ap;
316 CPUState *env;
318 va_start(ap, fmt);
319 fprintf(stderr, "qemu: hardware error: ");
320 vfprintf(stderr, fmt, ap);
321 fprintf(stderr, "\n");
322 for(env = first_cpu; env != NULL; env = env->next_cpu) {
323 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
324 #ifdef TARGET_I386
325 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
326 #else
327 cpu_dump_state(env, stderr, fprintf, 0);
328 #endif
330 va_end(ap);
331 abort();
334 static void set_proc_name(const char *s)
336 #if defined(__linux__) && defined(PR_SET_NAME)
337 char name[16];
338 if (!s)
339 return;
340 name[sizeof(name) - 1] = 0;
341 strncpy(name, s, sizeof(name));
342 /* Could rewrite argv[0] too, but that's a bit more complicated.
343 This simple way is enough for `top'. */
344 prctl(PR_SET_NAME, name);
345 #endif
348 /***************/
349 /* ballooning */
351 static QEMUBalloonEvent *qemu_balloon_event;
352 void *qemu_balloon_event_opaque;
354 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
356 qemu_balloon_event = func;
357 qemu_balloon_event_opaque = opaque;
360 void qemu_balloon(ram_addr_t target)
362 if (qemu_balloon_event)
363 qemu_balloon_event(qemu_balloon_event_opaque, target);
366 ram_addr_t qemu_balloon_status(void)
368 if (qemu_balloon_event)
369 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
370 return 0;
373 /***********************************************************/
374 /* keyboard/mouse */
376 static QEMUPutKBDEvent *qemu_put_kbd_event;
377 static void *qemu_put_kbd_event_opaque;
378 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
379 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
381 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
383 qemu_put_kbd_event_opaque = opaque;
384 qemu_put_kbd_event = func;
387 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
388 void *opaque, int absolute,
389 const char *name)
391 QEMUPutMouseEntry *s, *cursor;
393 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
395 s->qemu_put_mouse_event = func;
396 s->qemu_put_mouse_event_opaque = opaque;
397 s->qemu_put_mouse_event_absolute = absolute;
398 s->qemu_put_mouse_event_name = qemu_strdup(name);
399 s->next = NULL;
401 if (!qemu_put_mouse_event_head) {
402 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
403 return s;
406 cursor = qemu_put_mouse_event_head;
407 while (cursor->next != NULL)
408 cursor = cursor->next;
410 cursor->next = s;
411 qemu_put_mouse_event_current = s;
413 return s;
416 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
418 QEMUPutMouseEntry *prev = NULL, *cursor;
420 if (!qemu_put_mouse_event_head || entry == NULL)
421 return;
423 cursor = qemu_put_mouse_event_head;
424 while (cursor != NULL && cursor != entry) {
425 prev = cursor;
426 cursor = cursor->next;
429 if (cursor == NULL) // does not exist or list empty
430 return;
431 else if (prev == NULL) { // entry is head
432 qemu_put_mouse_event_head = cursor->next;
433 if (qemu_put_mouse_event_current == entry)
434 qemu_put_mouse_event_current = cursor->next;
435 qemu_free(entry->qemu_put_mouse_event_name);
436 qemu_free(entry);
437 return;
440 prev->next = entry->next;
442 if (qemu_put_mouse_event_current == entry)
443 qemu_put_mouse_event_current = prev;
445 qemu_free(entry->qemu_put_mouse_event_name);
446 qemu_free(entry);
449 void kbd_put_keycode(int keycode)
451 if (qemu_put_kbd_event) {
452 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
456 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
458 QEMUPutMouseEvent *mouse_event;
459 void *mouse_event_opaque;
460 int width;
462 if (!qemu_put_mouse_event_current) {
463 return;
466 mouse_event =
467 qemu_put_mouse_event_current->qemu_put_mouse_event;
468 mouse_event_opaque =
469 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
471 if (mouse_event) {
472 if (graphic_rotate) {
473 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
474 width = 0x7fff;
475 else
476 width = graphic_width - 1;
477 mouse_event(mouse_event_opaque,
478 width - dy, dx, dz, buttons_state);
479 } else
480 mouse_event(mouse_event_opaque,
481 dx, dy, dz, buttons_state);
485 int kbd_mouse_is_absolute(void)
487 if (!qemu_put_mouse_event_current)
488 return 0;
490 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
493 void do_info_mice(Monitor *mon)
495 QEMUPutMouseEntry *cursor;
496 int index = 0;
498 if (!qemu_put_mouse_event_head) {
499 monitor_printf(mon, "No mouse devices connected\n");
500 return;
503 monitor_printf(mon, "Mouse devices available:\n");
504 cursor = qemu_put_mouse_event_head;
505 while (cursor != NULL) {
506 monitor_printf(mon, "%c Mouse #%d: %s\n",
507 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
508 index, cursor->qemu_put_mouse_event_name);
509 index++;
510 cursor = cursor->next;
514 void do_mouse_set(Monitor *mon, const QDict *qdict)
516 QEMUPutMouseEntry *cursor;
517 int i = 0;
518 int index = qdict_get_int(qdict, "index");
520 if (!qemu_put_mouse_event_head) {
521 monitor_printf(mon, "No mouse devices connected\n");
522 return;
525 cursor = qemu_put_mouse_event_head;
526 while (cursor != NULL && index != i) {
527 i++;
528 cursor = cursor->next;
531 if (cursor != NULL)
532 qemu_put_mouse_event_current = cursor;
533 else
534 monitor_printf(mon, "Mouse at given index not found\n");
537 /* compute with 96 bit intermediate result: (a*b)/c */
538 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
540 union {
541 uint64_t ll;
542 struct {
543 #ifdef HOST_WORDS_BIGENDIAN
544 uint32_t high, low;
545 #else
546 uint32_t low, high;
547 #endif
548 } l;
549 } u, res;
550 uint64_t rl, rh;
552 u.ll = a;
553 rl = (uint64_t)u.l.low * (uint64_t)b;
554 rh = (uint64_t)u.l.high * (uint64_t)b;
555 rh += (rl >> 32);
556 res.l.high = rh / c;
557 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
558 return res.ll;
561 /***********************************************************/
562 /* real time host monotonic timer */
564 static int64_t get_clock_realtime(void)
566 struct timeval tv;
568 gettimeofday(&tv, NULL);
569 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
572 #ifdef WIN32
574 static int64_t clock_freq;
576 static void init_get_clock(void)
578 LARGE_INTEGER freq;
579 int ret;
580 ret = QueryPerformanceFrequency(&freq);
581 if (ret == 0) {
582 fprintf(stderr, "Could not calibrate ticks\n");
583 exit(1);
585 clock_freq = freq.QuadPart;
588 static int64_t get_clock(void)
590 LARGE_INTEGER ti;
591 QueryPerformanceCounter(&ti);
592 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
595 #else
597 static int use_rt_clock;
599 static void init_get_clock(void)
601 use_rt_clock = 0;
602 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
603 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
605 struct timespec ts;
606 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
607 use_rt_clock = 1;
610 #endif
613 static int64_t get_clock(void)
615 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
616 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
617 if (use_rt_clock) {
618 struct timespec ts;
619 clock_gettime(CLOCK_MONOTONIC, &ts);
620 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
621 } else
622 #endif
624 /* XXX: using gettimeofday leads to problems if the date
625 changes, so it should be avoided. */
626 return get_clock_realtime();
629 #endif
631 /* Return the virtual CPU time, based on the instruction counter. */
632 static int64_t cpu_get_icount(void)
634 int64_t icount;
635 CPUState *env = cpu_single_env;;
636 icount = qemu_icount;
637 if (env) {
638 if (!can_do_io(env))
639 fprintf(stderr, "Bad clock read\n");
640 icount -= (env->icount_decr.u16.low + env->icount_extra);
642 return qemu_icount_bias + (icount << icount_time_shift);
645 /***********************************************************/
646 /* guest cycle counter */
648 typedef struct TimersState {
649 int64_t cpu_ticks_prev;
650 int64_t cpu_ticks_offset;
651 int64_t cpu_clock_offset;
652 int32_t cpu_ticks_enabled;
653 int64_t dummy;
654 } TimersState;
656 TimersState timers_state;
658 /* return the host CPU cycle counter and handle stop/restart */
659 int64_t cpu_get_ticks(void)
661 if (use_icount) {
662 return cpu_get_icount();
664 if (!timers_state.cpu_ticks_enabled) {
665 return timers_state.cpu_ticks_offset;
666 } else {
667 int64_t ticks;
668 ticks = cpu_get_real_ticks();
669 if (timers_state.cpu_ticks_prev > ticks) {
670 /* Note: non increasing ticks may happen if the host uses
671 software suspend */
672 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
674 timers_state.cpu_ticks_prev = ticks;
675 return ticks + timers_state.cpu_ticks_offset;
679 /* return the host CPU monotonic timer and handle stop/restart */
680 static int64_t cpu_get_clock(void)
682 int64_t ti;
683 if (!timers_state.cpu_ticks_enabled) {
684 return timers_state.cpu_clock_offset;
685 } else {
686 ti = get_clock();
687 return ti + timers_state.cpu_clock_offset;
691 /* enable cpu_get_ticks() */
692 void cpu_enable_ticks(void)
694 if (!timers_state.cpu_ticks_enabled) {
695 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
696 timers_state.cpu_clock_offset -= get_clock();
697 timers_state.cpu_ticks_enabled = 1;
701 /* disable cpu_get_ticks() : the clock is stopped. You must not call
702 cpu_get_ticks() after that. */
703 void cpu_disable_ticks(void)
705 if (timers_state.cpu_ticks_enabled) {
706 timers_state.cpu_ticks_offset = cpu_get_ticks();
707 timers_state.cpu_clock_offset = cpu_get_clock();
708 timers_state.cpu_ticks_enabled = 0;
712 /***********************************************************/
713 /* timers */
715 #define QEMU_CLOCK_REALTIME 0
716 #define QEMU_CLOCK_VIRTUAL 1
717 #define QEMU_CLOCK_HOST 2
719 struct QEMUClock {
720 int type;
721 /* XXX: add frequency */
724 struct QEMUTimer {
725 QEMUClock *clock;
726 int64_t expire_time;
727 QEMUTimerCB *cb;
728 void *opaque;
729 struct QEMUTimer *next;
732 struct qemu_alarm_timer {
733 char const *name;
734 unsigned int flags;
736 int (*start)(struct qemu_alarm_timer *t);
737 void (*stop)(struct qemu_alarm_timer *t);
738 void (*rearm)(struct qemu_alarm_timer *t);
739 void *priv;
742 #define ALARM_FLAG_DYNTICKS 0x1
743 #define ALARM_FLAG_EXPIRED 0x2
745 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
747 return t && (t->flags & ALARM_FLAG_DYNTICKS);
750 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
752 if (!alarm_has_dynticks(t))
753 return;
755 t->rearm(t);
758 /* TODO: MIN_TIMER_REARM_US should be optimized */
759 #define MIN_TIMER_REARM_US 250
761 static struct qemu_alarm_timer *alarm_timer;
763 #ifdef _WIN32
765 struct qemu_alarm_win32 {
766 MMRESULT timerId;
767 unsigned int period;
768 } alarm_win32_data = {0, -1};
770 static int win32_start_timer(struct qemu_alarm_timer *t);
771 static void win32_stop_timer(struct qemu_alarm_timer *t);
772 static void win32_rearm_timer(struct qemu_alarm_timer *t);
774 #else
776 static int unix_start_timer(struct qemu_alarm_timer *t);
777 static void unix_stop_timer(struct qemu_alarm_timer *t);
779 #ifdef __linux__
781 static int dynticks_start_timer(struct qemu_alarm_timer *t);
782 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
783 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
785 static int hpet_start_timer(struct qemu_alarm_timer *t);
786 static void hpet_stop_timer(struct qemu_alarm_timer *t);
788 static int rtc_start_timer(struct qemu_alarm_timer *t);
789 static void rtc_stop_timer(struct qemu_alarm_timer *t);
791 #endif /* __linux__ */
793 #endif /* _WIN32 */
795 /* Correlation between real and virtual time is always going to be
796 fairly approximate, so ignore small variation.
797 When the guest is idle real and virtual time will be aligned in
798 the IO wait loop. */
799 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
801 static void icount_adjust(void)
803 int64_t cur_time;
804 int64_t cur_icount;
805 int64_t delta;
806 static int64_t last_delta;
807 /* If the VM is not running, then do nothing. */
808 if (!vm_running)
809 return;
811 cur_time = cpu_get_clock();
812 cur_icount = qemu_get_clock(vm_clock);
813 delta = cur_icount - cur_time;
814 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
815 if (delta > 0
816 && last_delta + ICOUNT_WOBBLE < delta * 2
817 && icount_time_shift > 0) {
818 /* The guest is getting too far ahead. Slow time down. */
819 icount_time_shift--;
821 if (delta < 0
822 && last_delta - ICOUNT_WOBBLE > delta * 2
823 && icount_time_shift < MAX_ICOUNT_SHIFT) {
824 /* The guest is getting too far behind. Speed time up. */
825 icount_time_shift++;
827 last_delta = delta;
828 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
831 static void icount_adjust_rt(void * opaque)
833 qemu_mod_timer(icount_rt_timer,
834 qemu_get_clock(rt_clock) + 1000);
835 icount_adjust();
838 static void icount_adjust_vm(void * opaque)
840 qemu_mod_timer(icount_vm_timer,
841 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
842 icount_adjust();
845 static void init_icount_adjust(void)
847 /* Have both realtime and virtual time triggers for speed adjustment.
848 The realtime trigger catches emulated time passing too slowly,
849 the virtual time trigger catches emulated time passing too fast.
850 Realtime triggers occur even when idle, so use them less frequently
851 than VM triggers. */
852 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
853 qemu_mod_timer(icount_rt_timer,
854 qemu_get_clock(rt_clock) + 1000);
855 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
856 qemu_mod_timer(icount_vm_timer,
857 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
860 static struct qemu_alarm_timer alarm_timers[] = {
861 #ifndef _WIN32
862 #ifdef __linux__
863 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
864 dynticks_stop_timer, dynticks_rearm_timer, NULL},
865 /* HPET - if available - is preferred */
866 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
867 /* ...otherwise try RTC */
868 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
869 #endif
870 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
871 #else
872 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
873 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
874 {"win32", 0, win32_start_timer,
875 win32_stop_timer, NULL, &alarm_win32_data},
876 #endif
877 {NULL, }
880 static void show_available_alarms(void)
882 int i;
884 printf("Available alarm timers, in order of precedence:\n");
885 for (i = 0; alarm_timers[i].name; i++)
886 printf("%s\n", alarm_timers[i].name);
889 static void configure_alarms(char const *opt)
891 int i;
892 int cur = 0;
893 int count = ARRAY_SIZE(alarm_timers) - 1;
894 char *arg;
895 char *name;
896 struct qemu_alarm_timer tmp;
898 if (!strcmp(opt, "?")) {
899 show_available_alarms();
900 exit(0);
903 arg = qemu_strdup(opt);
905 /* Reorder the array */
906 name = strtok(arg, ",");
907 while (name) {
908 for (i = 0; i < count && alarm_timers[i].name; i++) {
909 if (!strcmp(alarm_timers[i].name, name))
910 break;
913 if (i == count) {
914 fprintf(stderr, "Unknown clock %s\n", name);
915 goto next;
918 if (i < cur)
919 /* Ignore */
920 goto next;
922 /* Swap */
923 tmp = alarm_timers[i];
924 alarm_timers[i] = alarm_timers[cur];
925 alarm_timers[cur] = tmp;
927 cur++;
928 next:
929 name = strtok(NULL, ",");
932 qemu_free(arg);
934 if (cur) {
935 /* Disable remaining timers */
936 for (i = cur; i < count; i++)
937 alarm_timers[i].name = NULL;
938 } else {
939 show_available_alarms();
940 exit(1);
944 #define QEMU_NUM_CLOCKS 3
946 QEMUClock *rt_clock;
947 QEMUClock *vm_clock;
948 QEMUClock *host_clock;
950 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
952 static QEMUClock *qemu_new_clock(int type)
954 QEMUClock *clock;
955 clock = qemu_mallocz(sizeof(QEMUClock));
956 clock->type = type;
957 return clock;
960 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
962 QEMUTimer *ts;
964 ts = qemu_mallocz(sizeof(QEMUTimer));
965 ts->clock = clock;
966 ts->cb = cb;
967 ts->opaque = opaque;
968 return ts;
971 void qemu_free_timer(QEMUTimer *ts)
973 qemu_free(ts);
976 /* stop a timer, but do not dealloc it */
977 void qemu_del_timer(QEMUTimer *ts)
979 QEMUTimer **pt, *t;
981 /* NOTE: this code must be signal safe because
982 qemu_timer_expired() can be called from a signal. */
983 pt = &active_timers[ts->clock->type];
984 for(;;) {
985 t = *pt;
986 if (!t)
987 break;
988 if (t == ts) {
989 *pt = t->next;
990 break;
992 pt = &t->next;
996 /* modify the current timer so that it will be fired when current_time
997 >= expire_time. The corresponding callback will be called. */
998 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1000 QEMUTimer **pt, *t;
1002 qemu_del_timer(ts);
1004 /* add the timer in the sorted list */
1005 /* NOTE: this code must be signal safe because
1006 qemu_timer_expired() can be called from a signal. */
1007 pt = &active_timers[ts->clock->type];
1008 for(;;) {
1009 t = *pt;
1010 if (!t)
1011 break;
1012 if (t->expire_time > expire_time)
1013 break;
1014 pt = &t->next;
1016 ts->expire_time = expire_time;
1017 ts->next = *pt;
1018 *pt = ts;
1020 /* Rearm if necessary */
1021 if (pt == &active_timers[ts->clock->type]) {
1022 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1023 qemu_rearm_alarm_timer(alarm_timer);
1025 /* Interrupt execution to force deadline recalculation. */
1026 if (use_icount)
1027 qemu_notify_event();
1031 int qemu_timer_pending(QEMUTimer *ts)
1033 QEMUTimer *t;
1034 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1035 if (t == ts)
1036 return 1;
1038 return 0;
1041 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1043 if (!timer_head)
1044 return 0;
1045 return (timer_head->expire_time <= current_time);
1048 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1050 QEMUTimer *ts;
1052 for(;;) {
1053 ts = *ptimer_head;
1054 if (!ts || ts->expire_time > current_time)
1055 break;
1056 /* remove timer from the list before calling the callback */
1057 *ptimer_head = ts->next;
1058 ts->next = NULL;
1060 /* run the callback (the timer list can be modified) */
1061 ts->cb(ts->opaque);
1065 int64_t qemu_get_clock(QEMUClock *clock)
1067 switch(clock->type) {
1068 case QEMU_CLOCK_REALTIME:
1069 return get_clock() / 1000000;
1070 default:
1071 case QEMU_CLOCK_VIRTUAL:
1072 if (use_icount) {
1073 return cpu_get_icount();
1074 } else {
1075 return cpu_get_clock();
1077 case QEMU_CLOCK_HOST:
1078 return get_clock_realtime();
1082 static void init_clocks(void)
1084 init_get_clock();
1085 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
1086 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
1087 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
1089 rtc_clock = host_clock;
1092 /* save a timer */
1093 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1095 uint64_t expire_time;
1097 if (qemu_timer_pending(ts)) {
1098 expire_time = ts->expire_time;
1099 } else {
1100 expire_time = -1;
1102 qemu_put_be64(f, expire_time);
1105 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1107 uint64_t expire_time;
1109 expire_time = qemu_get_be64(f);
1110 if (expire_time != -1) {
1111 qemu_mod_timer(ts, expire_time);
1112 } else {
1113 qemu_del_timer(ts);
1117 static const VMStateDescription vmstate_timers = {
1118 .name = "timer",
1119 .version_id = 2,
1120 .minimum_version_id = 1,
1121 .minimum_version_id_old = 1,
1122 .fields = (VMStateField []) {
1123 VMSTATE_INT64(cpu_ticks_offset, TimersState),
1124 VMSTATE_INT64(dummy, TimersState),
1125 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1126 VMSTATE_END_OF_LIST()
1130 static void qemu_event_increment(void);
1132 #ifdef _WIN32
1133 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1134 DWORD_PTR dwUser, DWORD_PTR dw1,
1135 DWORD_PTR dw2)
1136 #else
1137 static void host_alarm_handler(int host_signum)
1138 #endif
1140 #if 0
1141 #define DISP_FREQ 1000
1143 static int64_t delta_min = INT64_MAX;
1144 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1145 static int count;
1146 ti = qemu_get_clock(vm_clock);
1147 if (last_clock != 0) {
1148 delta = ti - last_clock;
1149 if (delta < delta_min)
1150 delta_min = delta;
1151 if (delta > delta_max)
1152 delta_max = delta;
1153 delta_cum += delta;
1154 if (++count == DISP_FREQ) {
1155 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1156 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1157 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1158 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1159 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1160 count = 0;
1161 delta_min = INT64_MAX;
1162 delta_max = 0;
1163 delta_cum = 0;
1166 last_clock = ti;
1168 #endif
1169 if (alarm_has_dynticks(alarm_timer) ||
1170 (!use_icount &&
1171 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1172 qemu_get_clock(vm_clock))) ||
1173 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1174 qemu_get_clock(rt_clock)) ||
1175 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1176 qemu_get_clock(host_clock))) {
1177 qemu_event_increment();
1178 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1180 #ifndef CONFIG_IOTHREAD
1181 if (next_cpu) {
1182 /* stop the currently executing cpu because a timer occured */
1183 cpu_exit(next_cpu);
1185 #endif
1186 timer_alarm_pending = 1;
1187 qemu_notify_event();
1191 static int64_t qemu_next_deadline(void)
1193 /* To avoid problems with overflow limit this to 2^32. */
1194 int64_t delta = INT32_MAX;
1196 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1197 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1198 qemu_get_clock(vm_clock);
1200 if (active_timers[QEMU_CLOCK_HOST]) {
1201 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1202 qemu_get_clock(host_clock);
1203 if (hdelta < delta)
1204 delta = hdelta;
1207 if (delta < 0)
1208 delta = 0;
1210 return delta;
1213 #if defined(__linux__)
1214 static uint64_t qemu_next_deadline_dyntick(void)
1216 int64_t delta;
1217 int64_t rtdelta;
1219 if (use_icount)
1220 delta = INT32_MAX;
1221 else
1222 delta = (qemu_next_deadline() + 999) / 1000;
1224 if (active_timers[QEMU_CLOCK_REALTIME]) {
1225 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1226 qemu_get_clock(rt_clock))*1000;
1227 if (rtdelta < delta)
1228 delta = rtdelta;
1231 if (delta < MIN_TIMER_REARM_US)
1232 delta = MIN_TIMER_REARM_US;
1234 return delta;
1236 #endif
1238 #ifndef _WIN32
1240 /* Sets a specific flag */
1241 static int fcntl_setfl(int fd, int flag)
1243 int flags;
1245 flags = fcntl(fd, F_GETFL);
1246 if (flags == -1)
1247 return -errno;
1249 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1250 return -errno;
1252 return 0;
1255 #if defined(__linux__)
1257 #define RTC_FREQ 1024
1259 static void enable_sigio_timer(int fd)
1261 struct sigaction act;
1263 /* timer signal */
1264 sigfillset(&act.sa_mask);
1265 act.sa_flags = 0;
1266 act.sa_handler = host_alarm_handler;
1268 sigaction(SIGIO, &act, NULL);
1269 fcntl_setfl(fd, O_ASYNC);
1270 fcntl(fd, F_SETOWN, getpid());
1273 static int hpet_start_timer(struct qemu_alarm_timer *t)
1275 struct hpet_info info;
1276 int r, fd;
1278 fd = qemu_open("/dev/hpet", O_RDONLY);
1279 if (fd < 0)
1280 return -1;
1282 /* Set frequency */
1283 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1284 if (r < 0) {
1285 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1286 "error, but for better emulation accuracy type:\n"
1287 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1288 goto fail;
1291 /* Check capabilities */
1292 r = ioctl(fd, HPET_INFO, &info);
1293 if (r < 0)
1294 goto fail;
1296 /* Enable periodic mode */
1297 r = ioctl(fd, HPET_EPI, 0);
1298 if (info.hi_flags && (r < 0))
1299 goto fail;
1301 /* Enable interrupt */
1302 r = ioctl(fd, HPET_IE_ON, 0);
1303 if (r < 0)
1304 goto fail;
1306 enable_sigio_timer(fd);
1307 t->priv = (void *)(long)fd;
1309 return 0;
1310 fail:
1311 close(fd);
1312 return -1;
1315 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1317 int fd = (long)t->priv;
1319 close(fd);
1322 static int rtc_start_timer(struct qemu_alarm_timer *t)
1324 int rtc_fd;
1325 unsigned long current_rtc_freq = 0;
1327 TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
1328 if (rtc_fd < 0)
1329 return -1;
1330 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1331 if (current_rtc_freq != RTC_FREQ &&
1332 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1333 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1334 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1335 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1336 goto fail;
1338 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1339 fail:
1340 close(rtc_fd);
1341 return -1;
1344 enable_sigio_timer(rtc_fd);
1346 t->priv = (void *)(long)rtc_fd;
1348 return 0;
1351 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1353 int rtc_fd = (long)t->priv;
1355 close(rtc_fd);
1358 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1360 struct sigevent ev;
1361 timer_t host_timer;
1362 struct sigaction act;
1364 sigfillset(&act.sa_mask);
1365 act.sa_flags = 0;
1366 act.sa_handler = host_alarm_handler;
1368 sigaction(SIGALRM, &act, NULL);
1371 * Initialize ev struct to 0 to avoid valgrind complaining
1372 * about uninitialized data in timer_create call
1374 memset(&ev, 0, sizeof(ev));
1375 ev.sigev_value.sival_int = 0;
1376 ev.sigev_notify = SIGEV_SIGNAL;
1377 ev.sigev_signo = SIGALRM;
1379 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1380 perror("timer_create");
1382 /* disable dynticks */
1383 fprintf(stderr, "Dynamic Ticks disabled\n");
1385 return -1;
1388 t->priv = (void *)(long)host_timer;
1390 return 0;
1393 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1395 timer_t host_timer = (timer_t)(long)t->priv;
1397 timer_delete(host_timer);
1400 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1402 timer_t host_timer = (timer_t)(long)t->priv;
1403 struct itimerspec timeout;
1404 int64_t nearest_delta_us = INT64_MAX;
1405 int64_t current_us;
1407 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1408 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1409 !active_timers[QEMU_CLOCK_HOST])
1410 return;
1412 nearest_delta_us = qemu_next_deadline_dyntick();
1414 /* check whether a timer is already running */
1415 if (timer_gettime(host_timer, &timeout)) {
1416 perror("gettime");
1417 fprintf(stderr, "Internal timer error: aborting\n");
1418 exit(1);
1420 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1421 if (current_us && current_us <= nearest_delta_us)
1422 return;
1424 timeout.it_interval.tv_sec = 0;
1425 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1426 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1427 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1428 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1429 perror("settime");
1430 fprintf(stderr, "Internal timer error: aborting\n");
1431 exit(1);
1435 #endif /* defined(__linux__) */
1437 static int unix_start_timer(struct qemu_alarm_timer *t)
1439 struct sigaction act;
1440 struct itimerval itv;
1441 int err;
1443 /* timer signal */
1444 sigfillset(&act.sa_mask);
1445 act.sa_flags = 0;
1446 act.sa_handler = host_alarm_handler;
1448 sigaction(SIGALRM, &act, NULL);
1450 itv.it_interval.tv_sec = 0;
1451 /* for i386 kernel 2.6 to get 1 ms */
1452 itv.it_interval.tv_usec = 999;
1453 itv.it_value.tv_sec = 0;
1454 itv.it_value.tv_usec = 10 * 1000;
1456 err = setitimer(ITIMER_REAL, &itv, NULL);
1457 if (err)
1458 return -1;
1460 return 0;
1463 static void unix_stop_timer(struct qemu_alarm_timer *t)
1465 struct itimerval itv;
1467 memset(&itv, 0, sizeof(itv));
1468 setitimer(ITIMER_REAL, &itv, NULL);
1471 #endif /* !defined(_WIN32) */
1474 #ifdef _WIN32
1476 static int win32_start_timer(struct qemu_alarm_timer *t)
1478 TIMECAPS tc;
1479 struct qemu_alarm_win32 *data = t->priv;
1480 UINT flags;
1482 memset(&tc, 0, sizeof(tc));
1483 timeGetDevCaps(&tc, sizeof(tc));
1485 if (data->period < tc.wPeriodMin)
1486 data->period = tc.wPeriodMin;
1488 timeBeginPeriod(data->period);
1490 flags = TIME_CALLBACK_FUNCTION;
1491 if (alarm_has_dynticks(t))
1492 flags |= TIME_ONESHOT;
1493 else
1494 flags |= TIME_PERIODIC;
1496 data->timerId = timeSetEvent(1, // interval (ms)
1497 data->period, // resolution
1498 host_alarm_handler, // function
1499 (DWORD)t, // parameter
1500 flags);
1502 if (!data->timerId) {
1503 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1504 GetLastError());
1505 timeEndPeriod(data->period);
1506 return -1;
1509 return 0;
1512 static void win32_stop_timer(struct qemu_alarm_timer *t)
1514 struct qemu_alarm_win32 *data = t->priv;
1516 timeKillEvent(data->timerId);
1517 timeEndPeriod(data->period);
1520 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1522 struct qemu_alarm_win32 *data = t->priv;
1524 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1525 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1526 !active_timers[QEMU_CLOCK_HOST])
1527 return;
1529 timeKillEvent(data->timerId);
1531 data->timerId = timeSetEvent(1,
1532 data->period,
1533 host_alarm_handler,
1534 (DWORD)t,
1535 TIME_ONESHOT | TIME_PERIODIC);
1537 if (!data->timerId) {
1538 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1539 GetLastError());
1541 timeEndPeriod(data->period);
1542 exit(1);
1546 #endif /* _WIN32 */
1548 static int init_timer_alarm(void)
1550 struct qemu_alarm_timer *t = NULL;
1551 int i, err = -1;
1553 for (i = 0; alarm_timers[i].name; i++) {
1554 t = &alarm_timers[i];
1556 err = t->start(t);
1557 if (!err)
1558 break;
1561 if (err) {
1562 err = -ENOENT;
1563 goto fail;
1566 alarm_timer = t;
1568 return 0;
1570 fail:
1571 return err;
1574 static void quit_timers(void)
1576 alarm_timer->stop(alarm_timer);
1577 alarm_timer = NULL;
1580 /***********************************************************/
1581 /* host time/date access */
1582 void qemu_get_timedate(struct tm *tm, int offset)
1584 time_t ti;
1585 struct tm *ret;
1587 time(&ti);
1588 ti += offset;
1589 if (rtc_date_offset == -1) {
1590 if (rtc_utc)
1591 ret = gmtime(&ti);
1592 else
1593 ret = localtime(&ti);
1594 } else {
1595 ti -= rtc_date_offset;
1596 ret = gmtime(&ti);
1599 memcpy(tm, ret, sizeof(struct tm));
1602 int qemu_timedate_diff(struct tm *tm)
1604 time_t seconds;
1606 if (rtc_date_offset == -1)
1607 if (rtc_utc)
1608 seconds = mktimegm(tm);
1609 else
1610 seconds = mktime(tm);
1611 else
1612 seconds = mktimegm(tm) + rtc_date_offset;
1614 return seconds - time(NULL);
1617 static void configure_rtc_date_offset(const char *startdate, int legacy)
1619 time_t rtc_start_date;
1620 struct tm tm;
1622 if (!strcmp(startdate, "now") && legacy) {
1623 rtc_date_offset = -1;
1624 } else {
1625 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1626 &tm.tm_year,
1627 &tm.tm_mon,
1628 &tm.tm_mday,
1629 &tm.tm_hour,
1630 &tm.tm_min,
1631 &tm.tm_sec) == 6) {
1632 /* OK */
1633 } else if (sscanf(startdate, "%d-%d-%d",
1634 &tm.tm_year,
1635 &tm.tm_mon,
1636 &tm.tm_mday) == 3) {
1637 tm.tm_hour = 0;
1638 tm.tm_min = 0;
1639 tm.tm_sec = 0;
1640 } else {
1641 goto date_fail;
1643 tm.tm_year -= 1900;
1644 tm.tm_mon--;
1645 rtc_start_date = mktimegm(&tm);
1646 if (rtc_start_date == -1) {
1647 date_fail:
1648 fprintf(stderr, "Invalid date format. Valid formats are:\n"
1649 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1650 exit(1);
1652 rtc_date_offset = time(NULL) - rtc_start_date;
1656 static void configure_rtc(QemuOpts *opts)
1658 const char *value;
1660 value = qemu_opt_get(opts, "base");
1661 if (value) {
1662 if (!strcmp(value, "utc")) {
1663 rtc_utc = 1;
1664 } else if (!strcmp(value, "localtime")) {
1665 rtc_utc = 0;
1666 } else {
1667 configure_rtc_date_offset(value, 0);
1670 value = qemu_opt_get(opts, "clock");
1671 if (value) {
1672 if (!strcmp(value, "host")) {
1673 rtc_clock = host_clock;
1674 } else if (!strcmp(value, "vm")) {
1675 rtc_clock = vm_clock;
1676 } else {
1677 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1678 exit(1);
1681 #ifdef CONFIG_TARGET_I386
1682 value = qemu_opt_get(opts, "driftfix");
1683 if (value) {
1684 if (!strcmp(buf, "slew")) {
1685 rtc_td_hack = 1;
1686 } else if (!strcmp(buf, "none")) {
1687 rtc_td_hack = 0;
1688 } else {
1689 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1690 exit(1);
1693 #endif
1696 #ifdef _WIN32
1697 static void socket_cleanup(void)
1699 WSACleanup();
1702 static int socket_init(void)
1704 WSADATA Data;
1705 int ret, err;
1707 ret = WSAStartup(MAKEWORD(2,2), &Data);
1708 if (ret != 0) {
1709 err = WSAGetLastError();
1710 fprintf(stderr, "WSAStartup: %d\n", err);
1711 return -1;
1713 atexit(socket_cleanup);
1714 return 0;
1716 #endif
1718 /***********************************************************/
1719 /* Bluetooth support */
1720 static int nb_hcis;
1721 static int cur_hci;
1722 static struct HCIInfo *hci_table[MAX_NICS];
1724 static struct bt_vlan_s {
1725 struct bt_scatternet_s net;
1726 int id;
1727 struct bt_vlan_s *next;
1728 } *first_bt_vlan;
1730 /* find or alloc a new bluetooth "VLAN" */
1731 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1733 struct bt_vlan_s **pvlan, *vlan;
1734 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1735 if (vlan->id == id)
1736 return &vlan->net;
1738 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1739 vlan->id = id;
1740 pvlan = &first_bt_vlan;
1741 while (*pvlan != NULL)
1742 pvlan = &(*pvlan)->next;
1743 *pvlan = vlan;
1744 return &vlan->net;
1747 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1751 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1753 return -ENOTSUP;
1756 static struct HCIInfo null_hci = {
1757 .cmd_send = null_hci_send,
1758 .sco_send = null_hci_send,
1759 .acl_send = null_hci_send,
1760 .bdaddr_set = null_hci_addr_set,
1763 struct HCIInfo *qemu_next_hci(void)
1765 if (cur_hci == nb_hcis)
1766 return &null_hci;
1768 return hci_table[cur_hci++];
1771 static struct HCIInfo *hci_init(const char *str)
1773 char *endp;
1774 struct bt_scatternet_s *vlan = 0;
1776 if (!strcmp(str, "null"))
1777 /* null */
1778 return &null_hci;
1779 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1780 /* host[:hciN] */
1781 return bt_host_hci(str[4] ? str + 5 : "hci0");
1782 else if (!strncmp(str, "hci", 3)) {
1783 /* hci[,vlan=n] */
1784 if (str[3]) {
1785 if (!strncmp(str + 3, ",vlan=", 6)) {
1786 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1787 if (*endp)
1788 vlan = 0;
1790 } else
1791 vlan = qemu_find_bt_vlan(0);
1792 if (vlan)
1793 return bt_new_hci(vlan);
1796 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1798 return 0;
1801 static int bt_hci_parse(const char *str)
1803 struct HCIInfo *hci;
1804 bdaddr_t bdaddr;
1806 if (nb_hcis >= MAX_NICS) {
1807 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1808 return -1;
1811 hci = hci_init(str);
1812 if (!hci)
1813 return -1;
1815 bdaddr.b[0] = 0x52;
1816 bdaddr.b[1] = 0x54;
1817 bdaddr.b[2] = 0x00;
1818 bdaddr.b[3] = 0x12;
1819 bdaddr.b[4] = 0x34;
1820 bdaddr.b[5] = 0x56 + nb_hcis;
1821 hci->bdaddr_set(hci, bdaddr.b);
1823 hci_table[nb_hcis++] = hci;
1825 return 0;
1828 static void bt_vhci_add(int vlan_id)
1830 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1832 if (!vlan->slave)
1833 fprintf(stderr, "qemu: warning: adding a VHCI to "
1834 "an empty scatternet %i\n", vlan_id);
1836 bt_vhci_init(bt_new_hci(vlan));
1839 static struct bt_device_s *bt_device_add(const char *opt)
1841 struct bt_scatternet_s *vlan;
1842 int vlan_id = 0;
1843 char *endp = strstr(opt, ",vlan=");
1844 int len = (endp ? endp - opt : strlen(opt)) + 1;
1845 char devname[10];
1847 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1849 if (endp) {
1850 vlan_id = strtol(endp + 6, &endp, 0);
1851 if (*endp) {
1852 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1853 return 0;
1857 vlan = qemu_find_bt_vlan(vlan_id);
1859 if (!vlan->slave)
1860 fprintf(stderr, "qemu: warning: adding a slave device to "
1861 "an empty scatternet %i\n", vlan_id);
1863 if (!strcmp(devname, "keyboard"))
1864 return bt_keyboard_init(vlan);
1866 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1867 return 0;
1870 static int bt_parse(const char *opt)
1872 const char *endp, *p;
1873 int vlan;
1875 if (strstart(opt, "hci", &endp)) {
1876 if (!*endp || *endp == ',') {
1877 if (*endp)
1878 if (!strstart(endp, ",vlan=", 0))
1879 opt = endp + 1;
1881 return bt_hci_parse(opt);
1883 } else if (strstart(opt, "vhci", &endp)) {
1884 if (!*endp || *endp == ',') {
1885 if (*endp) {
1886 if (strstart(endp, ",vlan=", &p)) {
1887 vlan = strtol(p, (char **) &endp, 0);
1888 if (*endp) {
1889 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1890 return 1;
1892 } else {
1893 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1894 return 1;
1896 } else
1897 vlan = 0;
1899 bt_vhci_add(vlan);
1900 return 0;
1902 } else if (strstart(opt, "device:", &endp))
1903 return !bt_device_add(endp);
1905 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1906 return 1;
1909 /***********************************************************/
1910 /* QEMU Block devices */
1912 #define HD_ALIAS "index=%d,media=disk"
1913 #define CDROM_ALIAS "index=2,media=cdrom"
1914 #define FD_ALIAS "index=%d,if=floppy"
1915 #define PFLASH_ALIAS "if=pflash"
1916 #define MTD_ALIAS "if=mtd"
1917 #define SD_ALIAS "index=0,if=sd"
1919 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1921 va_list ap;
1922 char optstr[1024];
1923 QemuOpts *opts;
1925 va_start(ap, fmt);
1926 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1927 va_end(ap);
1929 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1930 if (!opts) {
1931 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1932 __FUNCTION__, optstr);
1933 return NULL;
1935 if (file)
1936 qemu_opt_set(opts, "file", file);
1937 return opts;
1940 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1942 DriveInfo *dinfo;
1944 /* seek interface, bus and unit */
1946 QTAILQ_FOREACH(dinfo, &drives, next) {
1947 if (dinfo->type == type &&
1948 dinfo->bus == bus &&
1949 dinfo->unit == unit)
1950 return dinfo;
1953 return NULL;
1956 DriveInfo *drive_get_by_id(const char *id)
1958 DriveInfo *dinfo;
1960 QTAILQ_FOREACH(dinfo, &drives, next) {
1961 if (strcmp(id, dinfo->id))
1962 continue;
1963 return dinfo;
1965 return NULL;
1968 int drive_get_max_bus(BlockInterfaceType type)
1970 int max_bus;
1971 DriveInfo *dinfo;
1973 max_bus = -1;
1974 QTAILQ_FOREACH(dinfo, &drives, next) {
1975 if(dinfo->type == type &&
1976 dinfo->bus > max_bus)
1977 max_bus = dinfo->bus;
1979 return max_bus;
1982 const char *drive_get_serial(BlockDriverState *bdrv)
1984 DriveInfo *dinfo;
1986 QTAILQ_FOREACH(dinfo, &drives, next) {
1987 if (dinfo->bdrv == bdrv)
1988 return dinfo->serial;
1991 return "\0";
1994 BlockInterfaceErrorAction drive_get_on_error(
1995 BlockDriverState *bdrv, int is_read)
1997 DriveInfo *dinfo;
1999 if (is_read) {
2000 return BLOCK_ERR_REPORT;
2003 QTAILQ_FOREACH(dinfo, &drives, next) {
2004 if (dinfo->bdrv == bdrv)
2005 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
2008 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
2011 static void bdrv_format_print(void *opaque, const char *name)
2013 fprintf(stderr, " %s", name);
2016 void drive_uninit(DriveInfo *dinfo)
2018 qemu_opts_del(dinfo->opts);
2019 bdrv_delete(dinfo->bdrv);
2020 QTAILQ_REMOVE(&drives, dinfo, next);
2021 qemu_free(dinfo);
2024 static int parse_block_error_action(const char *buf, int is_read)
2026 if (!strcmp(buf, "ignore")) {
2027 return BLOCK_ERR_IGNORE;
2028 } else if (!is_read && !strcmp(buf, "enospc")) {
2029 return BLOCK_ERR_STOP_ENOSPC;
2030 } else if (!strcmp(buf, "stop")) {
2031 return BLOCK_ERR_STOP_ANY;
2032 } else if (!strcmp(buf, "report")) {
2033 return BLOCK_ERR_REPORT;
2034 } else {
2035 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
2036 buf, is_read ? "read" : "write");
2037 return -1;
2041 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
2042 int *fatal_error)
2044 const char *buf;
2045 const char *file = NULL;
2046 char devname[128];
2047 const char *serial;
2048 const char *mediastr = "";
2049 BlockInterfaceType type;
2050 enum { MEDIA_DISK, MEDIA_CDROM } media;
2051 int bus_id, unit_id;
2052 int cyls, heads, secs, translation;
2053 BlockDriver *drv = NULL;
2054 QEMUMachine *machine = opaque;
2055 int max_devs;
2056 int index;
2057 int cache;
2058 int aio = 0;
2059 int ro = 0;
2060 int bdrv_flags;
2061 int on_read_error, on_write_error;
2062 const char *devaddr;
2063 DriveInfo *dinfo;
2064 int snapshot = 0;
2066 *fatal_error = 1;
2068 translation = BIOS_ATA_TRANSLATION_AUTO;
2069 cache = 1;
2071 if (machine && machine->use_scsi) {
2072 type = IF_SCSI;
2073 max_devs = MAX_SCSI_DEVS;
2074 pstrcpy(devname, sizeof(devname), "scsi");
2075 } else {
2076 type = IF_IDE;
2077 max_devs = MAX_IDE_DEVS;
2078 pstrcpy(devname, sizeof(devname), "ide");
2080 media = MEDIA_DISK;
2082 /* extract parameters */
2083 bus_id = qemu_opt_get_number(opts, "bus", 0);
2084 unit_id = qemu_opt_get_number(opts, "unit", -1);
2085 index = qemu_opt_get_number(opts, "index", -1);
2087 cyls = qemu_opt_get_number(opts, "cyls", 0);
2088 heads = qemu_opt_get_number(opts, "heads", 0);
2089 secs = qemu_opt_get_number(opts, "secs", 0);
2091 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
2092 ro = qemu_opt_get_bool(opts, "readonly", 0);
2094 file = qemu_opt_get(opts, "file");
2095 serial = qemu_opt_get(opts, "serial");
2097 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
2098 pstrcpy(devname, sizeof(devname), buf);
2099 if (!strcmp(buf, "ide")) {
2100 type = IF_IDE;
2101 max_devs = MAX_IDE_DEVS;
2102 } else if (!strcmp(buf, "scsi")) {
2103 type = IF_SCSI;
2104 max_devs = MAX_SCSI_DEVS;
2105 } else if (!strcmp(buf, "floppy")) {
2106 type = IF_FLOPPY;
2107 max_devs = 0;
2108 } else if (!strcmp(buf, "pflash")) {
2109 type = IF_PFLASH;
2110 max_devs = 0;
2111 } else if (!strcmp(buf, "mtd")) {
2112 type = IF_MTD;
2113 max_devs = 0;
2114 } else if (!strcmp(buf, "sd")) {
2115 type = IF_SD;
2116 max_devs = 0;
2117 } else if (!strcmp(buf, "virtio")) {
2118 type = IF_VIRTIO;
2119 max_devs = 0;
2120 } else if (!strcmp(buf, "xen")) {
2121 type = IF_XEN;
2122 max_devs = 0;
2123 } else if (!strcmp(buf, "none")) {
2124 type = IF_NONE;
2125 max_devs = 0;
2126 } else {
2127 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
2128 return NULL;
2132 if (cyls || heads || secs) {
2133 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
2134 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2135 return NULL;
2137 if (heads < 1 || (type == IF_IDE && heads > 16)) {
2138 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2139 return NULL;
2141 if (secs < 1 || (type == IF_IDE && secs > 63)) {
2142 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2143 return NULL;
2147 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2148 if (!cyls) {
2149 fprintf(stderr,
2150 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2151 buf);
2152 return NULL;
2154 if (!strcmp(buf, "none"))
2155 translation = BIOS_ATA_TRANSLATION_NONE;
2156 else if (!strcmp(buf, "lba"))
2157 translation = BIOS_ATA_TRANSLATION_LBA;
2158 else if (!strcmp(buf, "auto"))
2159 translation = BIOS_ATA_TRANSLATION_AUTO;
2160 else {
2161 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2162 return NULL;
2166 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2167 if (!strcmp(buf, "disk")) {
2168 media = MEDIA_DISK;
2169 } else if (!strcmp(buf, "cdrom")) {
2170 if (cyls || secs || heads) {
2171 fprintf(stderr,
2172 "qemu: '%s' invalid physical CHS format\n", buf);
2173 return NULL;
2175 media = MEDIA_CDROM;
2176 } else {
2177 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2178 return NULL;
2182 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2183 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2184 cache = 0;
2185 else if (!strcmp(buf, "writethrough"))
2186 cache = 1;
2187 else if (!strcmp(buf, "writeback"))
2188 cache = 2;
2189 else {
2190 fprintf(stderr, "qemu: invalid cache option\n");
2191 return NULL;
2195 #ifdef CONFIG_LINUX_AIO
2196 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2197 if (!strcmp(buf, "threads"))
2198 aio = 0;
2199 else if (!strcmp(buf, "native"))
2200 aio = 1;
2201 else {
2202 fprintf(stderr, "qemu: invalid aio option\n");
2203 return NULL;
2206 #endif
2208 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2209 if (strcmp(buf, "?") == 0) {
2210 fprintf(stderr, "qemu: Supported formats:");
2211 bdrv_iterate_format(bdrv_format_print, NULL);
2212 fprintf(stderr, "\n");
2213 return NULL;
2215 drv = bdrv_find_whitelisted_format(buf);
2216 if (!drv) {
2217 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2218 return NULL;
2222 on_write_error = BLOCK_ERR_STOP_ENOSPC;
2223 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2224 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2225 fprintf(stderr, "werror is no supported by this format\n");
2226 return NULL;
2229 on_write_error = parse_block_error_action(buf, 0);
2230 if (on_write_error < 0) {
2231 return NULL;
2235 on_read_error = BLOCK_ERR_REPORT;
2236 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2237 if (type != IF_IDE && type != IF_VIRTIO) {
2238 fprintf(stderr, "rerror is no supported by this format\n");
2239 return NULL;
2242 on_read_error = parse_block_error_action(buf, 1);
2243 if (on_read_error < 0) {
2244 return NULL;
2248 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2249 if (type != IF_VIRTIO) {
2250 fprintf(stderr, "addr is not supported\n");
2251 return NULL;
2255 /* compute bus and unit according index */
2257 if (index != -1) {
2258 if (bus_id != 0 || unit_id != -1) {
2259 fprintf(stderr,
2260 "qemu: index cannot be used with bus and unit\n");
2261 return NULL;
2263 if (max_devs == 0)
2265 unit_id = index;
2266 bus_id = 0;
2267 } else {
2268 unit_id = index % max_devs;
2269 bus_id = index / max_devs;
2273 /* if user doesn't specify a unit_id,
2274 * try to find the first free
2277 if (unit_id == -1) {
2278 unit_id = 0;
2279 while (drive_get(type, bus_id, unit_id) != NULL) {
2280 unit_id++;
2281 if (max_devs && unit_id >= max_devs) {
2282 unit_id -= max_devs;
2283 bus_id++;
2288 /* check unit id */
2290 if (max_devs && unit_id >= max_devs) {
2291 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2292 unit_id, max_devs - 1);
2293 return NULL;
2297 * ignore multiple definitions
2300 if (drive_get(type, bus_id, unit_id) != NULL) {
2301 *fatal_error = 0;
2302 return NULL;
2305 /* init */
2307 dinfo = qemu_mallocz(sizeof(*dinfo));
2308 if ((buf = qemu_opts_id(opts)) != NULL) {
2309 dinfo->id = qemu_strdup(buf);
2310 } else {
2311 /* no id supplied -> create one */
2312 dinfo->id = qemu_mallocz(32);
2313 if (type == IF_IDE || type == IF_SCSI)
2314 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2315 if (max_devs)
2316 snprintf(dinfo->id, 32, "%s%i%s%i",
2317 devname, bus_id, mediastr, unit_id);
2318 else
2319 snprintf(dinfo->id, 32, "%s%s%i",
2320 devname, mediastr, unit_id);
2322 dinfo->bdrv = bdrv_new(dinfo->id);
2323 dinfo->devaddr = devaddr;
2324 dinfo->type = type;
2325 dinfo->bus = bus_id;
2326 dinfo->unit = unit_id;
2327 dinfo->on_read_error = on_read_error;
2328 dinfo->on_write_error = on_write_error;
2329 dinfo->opts = opts;
2330 if (serial)
2331 strncpy(dinfo->serial, serial, sizeof(serial));
2332 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2334 switch(type) {
2335 case IF_IDE:
2336 case IF_SCSI:
2337 case IF_XEN:
2338 case IF_NONE:
2339 switch(media) {
2340 case MEDIA_DISK:
2341 if (cyls != 0) {
2342 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2343 bdrv_set_translation_hint(dinfo->bdrv, translation);
2345 break;
2346 case MEDIA_CDROM:
2347 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2348 break;
2350 break;
2351 case IF_SD:
2352 /* FIXME: This isn't really a floppy, but it's a reasonable
2353 approximation. */
2354 case IF_FLOPPY:
2355 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2356 break;
2357 case IF_PFLASH:
2358 case IF_MTD:
2359 break;
2360 case IF_VIRTIO:
2361 /* add virtio block device */
2362 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2363 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2364 qemu_opt_set(opts, "drive", dinfo->id);
2365 if (devaddr)
2366 qemu_opt_set(opts, "addr", devaddr);
2367 break;
2368 case IF_COUNT:
2369 abort();
2371 if (!file) {
2372 *fatal_error = 0;
2373 return NULL;
2375 bdrv_flags = 0;
2376 if (snapshot) {
2377 bdrv_flags |= BDRV_O_SNAPSHOT;
2378 cache = 2; /* always use write-back with snapshot */
2380 if (cache == 0) /* no caching */
2381 bdrv_flags |= BDRV_O_NOCACHE;
2382 else if (cache == 2) /* write-back */
2383 bdrv_flags |= BDRV_O_CACHE_WB;
2385 if (aio == 1) {
2386 bdrv_flags |= BDRV_O_NATIVE_AIO;
2387 } else {
2388 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2391 if (ro == 1) {
2392 if (type == IF_IDE) {
2393 fprintf(stderr, "qemu: readonly flag not supported for drive with ide interface\n");
2394 return NULL;
2396 (void)bdrv_set_read_only(dinfo->bdrv, 1);
2399 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2400 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2401 file, strerror(errno));
2402 return NULL;
2405 if (bdrv_key_required(dinfo->bdrv))
2406 autostart = 0;
2407 *fatal_error = 0;
2408 return dinfo;
2411 static int drive_init_func(QemuOpts *opts, void *opaque)
2413 QEMUMachine *machine = opaque;
2414 int fatal_error = 0;
2416 if (drive_init(opts, machine, &fatal_error) == NULL) {
2417 if (fatal_error)
2418 return 1;
2420 return 0;
2423 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2425 if (NULL == qemu_opt_get(opts, "snapshot")) {
2426 qemu_opt_set(opts, "snapshot", "on");
2428 return 0;
2431 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2433 boot_set_handler = func;
2434 boot_set_opaque = opaque;
2437 int qemu_boot_set(const char *boot_devices)
2439 if (!boot_set_handler) {
2440 return -EINVAL;
2442 return boot_set_handler(boot_set_opaque, boot_devices);
2445 static int parse_bootdevices(char *devices)
2447 /* We just do some generic consistency checks */
2448 const char *p;
2449 int bitmap = 0;
2451 for (p = devices; *p != '\0'; p++) {
2452 /* Allowed boot devices are:
2453 * a-b: floppy disk drives
2454 * c-f: IDE disk drives
2455 * g-m: machine implementation dependant drives
2456 * n-p: network devices
2457 * It's up to each machine implementation to check if the given boot
2458 * devices match the actual hardware implementation and firmware
2459 * features.
2461 if (*p < 'a' || *p > 'p') {
2462 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2463 exit(1);
2465 if (bitmap & (1 << (*p - 'a'))) {
2466 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2467 exit(1);
2469 bitmap |= 1 << (*p - 'a');
2471 return bitmap;
2474 static void restore_boot_devices(void *opaque)
2476 char *standard_boot_devices = opaque;
2478 qemu_boot_set(standard_boot_devices);
2480 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2481 qemu_free(standard_boot_devices);
2484 static void numa_add(const char *optarg)
2486 char option[128];
2487 char *endptr;
2488 unsigned long long value, endvalue;
2489 int nodenr;
2491 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2492 if (!strcmp(option, "node")) {
2493 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2494 nodenr = nb_numa_nodes;
2495 } else {
2496 nodenr = strtoull(option, NULL, 10);
2499 if (get_param_value(option, 128, "mem", optarg) == 0) {
2500 node_mem[nodenr] = 0;
2501 } else {
2502 value = strtoull(option, &endptr, 0);
2503 switch (*endptr) {
2504 case 0: case 'M': case 'm':
2505 value <<= 20;
2506 break;
2507 case 'G': case 'g':
2508 value <<= 30;
2509 break;
2511 node_mem[nodenr] = value;
2513 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2514 node_cpumask[nodenr] = 0;
2515 } else {
2516 value = strtoull(option, &endptr, 10);
2517 if (value >= 64) {
2518 value = 63;
2519 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2520 } else {
2521 if (*endptr == '-') {
2522 endvalue = strtoull(endptr+1, &endptr, 10);
2523 if (endvalue >= 63) {
2524 endvalue = 62;
2525 fprintf(stderr,
2526 "only 63 CPUs in NUMA mode supported.\n");
2528 value = (1 << (endvalue + 1)) - (1 << value);
2529 } else {
2530 value = 1 << value;
2533 node_cpumask[nodenr] = value;
2535 nb_numa_nodes++;
2537 return;
2540 static void smp_parse(const char *optarg)
2542 int smp, sockets = 0, threads = 0, cores = 0;
2543 char *endptr;
2544 char option[128];
2546 smp = strtoul(optarg, &endptr, 10);
2547 if (endptr != optarg) {
2548 if (*endptr == ',') {
2549 endptr++;
2552 if (get_param_value(option, 128, "sockets", endptr) != 0)
2553 sockets = strtoull(option, NULL, 10);
2554 if (get_param_value(option, 128, "cores", endptr) != 0)
2555 cores = strtoull(option, NULL, 10);
2556 if (get_param_value(option, 128, "threads", endptr) != 0)
2557 threads = strtoull(option, NULL, 10);
2558 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2559 max_cpus = strtoull(option, NULL, 10);
2561 /* compute missing values, prefer sockets over cores over threads */
2562 if (smp == 0 || sockets == 0) {
2563 sockets = sockets > 0 ? sockets : 1;
2564 cores = cores > 0 ? cores : 1;
2565 threads = threads > 0 ? threads : 1;
2566 if (smp == 0) {
2567 smp = cores * threads * sockets;
2568 } else {
2569 sockets = smp / (cores * threads);
2571 } else {
2572 if (cores == 0) {
2573 threads = threads > 0 ? threads : 1;
2574 cores = smp / (sockets * threads);
2575 } else {
2576 if (sockets == 0) {
2577 sockets = smp / (cores * threads);
2578 } else {
2579 threads = smp / (cores * sockets);
2583 smp_cpus = smp;
2584 smp_cores = cores > 0 ? cores : 1;
2585 smp_threads = threads > 0 ? threads : 1;
2586 if (max_cpus == 0)
2587 max_cpus = smp_cpus;
2590 /***********************************************************/
2591 /* USB devices */
2593 static int usb_device_add(const char *devname, int is_hotplug)
2595 const char *p;
2596 USBDevice *dev = NULL;
2598 if (!usb_enabled)
2599 return -1;
2601 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2602 dev = usbdevice_create(devname);
2603 if (dev)
2604 goto done;
2606 /* the other ones */
2607 if (strstart(devname, "host:", &p)) {
2608 dev = usb_host_device_open(p);
2609 } else if (strstart(devname, "net:", &p)) {
2610 QemuOpts *opts;
2611 int idx;
2613 opts = qemu_opts_parse(&qemu_net_opts, p, NULL);
2614 if (!opts) {
2615 return -1;
2618 qemu_opt_set(opts, "type", "nic");
2619 qemu_opt_set(opts, "model", "usb");
2621 idx = net_client_init(NULL, opts, 0);
2622 if (idx == -1) {
2623 return -1;
2626 dev = usb_net_init(&nd_table[idx]);
2627 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2628 dev = usb_bt_init(devname[2] ? hci_init(p) :
2629 bt_new_hci(qemu_find_bt_vlan(0)));
2630 } else {
2631 return -1;
2633 if (!dev)
2634 return -1;
2636 done:
2637 return 0;
2640 static int usb_device_del(const char *devname)
2642 int bus_num, addr;
2643 const char *p;
2645 if (strstart(devname, "host:", &p))
2646 return usb_host_device_close(p);
2648 if (!usb_enabled)
2649 return -1;
2651 p = strchr(devname, '.');
2652 if (!p)
2653 return -1;
2654 bus_num = strtoul(devname, NULL, 0);
2655 addr = strtoul(p + 1, NULL, 0);
2657 return usb_device_delete_addr(bus_num, addr);
2660 static int usb_parse(const char *cmdline)
2662 return usb_device_add(cmdline, 0);
2665 void do_usb_add(Monitor *mon, const QDict *qdict)
2667 usb_device_add(qdict_get_str(qdict, "devname"), 1);
2670 void do_usb_del(Monitor *mon, const QDict *qdict)
2672 usb_device_del(qdict_get_str(qdict, "devname"));
2675 /***********************************************************/
2676 /* PCMCIA/Cardbus */
2678 static struct pcmcia_socket_entry_s {
2679 PCMCIASocket *socket;
2680 struct pcmcia_socket_entry_s *next;
2681 } *pcmcia_sockets = 0;
2683 void pcmcia_socket_register(PCMCIASocket *socket)
2685 struct pcmcia_socket_entry_s *entry;
2687 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2688 entry->socket = socket;
2689 entry->next = pcmcia_sockets;
2690 pcmcia_sockets = entry;
2693 void pcmcia_socket_unregister(PCMCIASocket *socket)
2695 struct pcmcia_socket_entry_s *entry, **ptr;
2697 ptr = &pcmcia_sockets;
2698 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2699 if (entry->socket == socket) {
2700 *ptr = entry->next;
2701 qemu_free(entry);
2705 void pcmcia_info(Monitor *mon)
2707 struct pcmcia_socket_entry_s *iter;
2709 if (!pcmcia_sockets)
2710 monitor_printf(mon, "No PCMCIA sockets\n");
2712 for (iter = pcmcia_sockets; iter; iter = iter->next)
2713 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2714 iter->socket->attached ? iter->socket->card_string :
2715 "Empty");
2718 /***********************************************************/
2719 /* register display */
2721 struct DisplayAllocator default_allocator = {
2722 defaultallocator_create_displaysurface,
2723 defaultallocator_resize_displaysurface,
2724 defaultallocator_free_displaysurface
2727 void register_displaystate(DisplayState *ds)
2729 DisplayState **s;
2730 s = &display_state;
2731 while (*s != NULL)
2732 s = &(*s)->next;
2733 ds->next = NULL;
2734 *s = ds;
2737 DisplayState *get_displaystate(void)
2739 return display_state;
2742 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2744 if(ds->allocator == &default_allocator) ds->allocator = da;
2745 return ds->allocator;
2748 /* dumb display */
2750 static void dumb_display_init(void)
2752 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2753 ds->allocator = &default_allocator;
2754 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2755 register_displaystate(ds);
2758 /***********************************************************/
2759 /* I/O handling */
2761 typedef struct IOHandlerRecord {
2762 int fd;
2763 IOCanRWHandler *fd_read_poll;
2764 IOHandler *fd_read;
2765 IOHandler *fd_write;
2766 int deleted;
2767 void *opaque;
2768 /* temporary data */
2769 struct pollfd *ufd;
2770 struct IOHandlerRecord *next;
2771 } IOHandlerRecord;
2773 static IOHandlerRecord *first_io_handler;
2775 /* XXX: fd_read_poll should be suppressed, but an API change is
2776 necessary in the character devices to suppress fd_can_read(). */
2777 int qemu_set_fd_handler2(int fd,
2778 IOCanRWHandler *fd_read_poll,
2779 IOHandler *fd_read,
2780 IOHandler *fd_write,
2781 void *opaque)
2783 IOHandlerRecord **pioh, *ioh;
2785 if (!fd_read && !fd_write) {
2786 pioh = &first_io_handler;
2787 for(;;) {
2788 ioh = *pioh;
2789 if (ioh == NULL)
2790 break;
2791 if (ioh->fd == fd) {
2792 ioh->deleted = 1;
2793 break;
2795 pioh = &ioh->next;
2797 } else {
2798 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2799 if (ioh->fd == fd)
2800 goto found;
2802 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2803 ioh->next = first_io_handler;
2804 first_io_handler = ioh;
2805 found:
2806 ioh->fd = fd;
2807 ioh->fd_read_poll = fd_read_poll;
2808 ioh->fd_read = fd_read;
2809 ioh->fd_write = fd_write;
2810 ioh->opaque = opaque;
2811 ioh->deleted = 0;
2813 return 0;
2816 int qemu_set_fd_handler(int fd,
2817 IOHandler *fd_read,
2818 IOHandler *fd_write,
2819 void *opaque)
2821 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2824 #ifdef _WIN32
2825 /***********************************************************/
2826 /* Polling handling */
2828 typedef struct PollingEntry {
2829 PollingFunc *func;
2830 void *opaque;
2831 struct PollingEntry *next;
2832 } PollingEntry;
2834 static PollingEntry *first_polling_entry;
2836 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2838 PollingEntry **ppe, *pe;
2839 pe = qemu_mallocz(sizeof(PollingEntry));
2840 pe->func = func;
2841 pe->opaque = opaque;
2842 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2843 *ppe = pe;
2844 return 0;
2847 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2849 PollingEntry **ppe, *pe;
2850 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2851 pe = *ppe;
2852 if (pe->func == func && pe->opaque == opaque) {
2853 *ppe = pe->next;
2854 qemu_free(pe);
2855 break;
2860 /***********************************************************/
2861 /* Wait objects support */
2862 typedef struct WaitObjects {
2863 int num;
2864 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2865 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2866 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2867 } WaitObjects;
2869 static WaitObjects wait_objects = {0};
2871 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2873 WaitObjects *w = &wait_objects;
2875 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2876 return -1;
2877 w->events[w->num] = handle;
2878 w->func[w->num] = func;
2879 w->opaque[w->num] = opaque;
2880 w->num++;
2881 return 0;
2884 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2886 int i, found;
2887 WaitObjects *w = &wait_objects;
2889 found = 0;
2890 for (i = 0; i < w->num; i++) {
2891 if (w->events[i] == handle)
2892 found = 1;
2893 if (found) {
2894 w->events[i] = w->events[i + 1];
2895 w->func[i] = w->func[i + 1];
2896 w->opaque[i] = w->opaque[i + 1];
2899 if (found)
2900 w->num--;
2902 #endif
2904 /***********************************************************/
2905 /* ram save/restore */
2907 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2908 #define RAM_SAVE_FLAG_COMPRESS 0x02
2909 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2910 #define RAM_SAVE_FLAG_PAGE 0x08
2911 #define RAM_SAVE_FLAG_EOS 0x10
2913 static int is_dup_page(uint8_t *page, uint8_t ch)
2915 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2916 uint32_t *array = (uint32_t *)page;
2917 int i;
2919 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2920 if (array[i] != val)
2921 return 0;
2924 return 1;
2927 static int ram_save_block(QEMUFile *f)
2929 static ram_addr_t current_addr = 0;
2930 ram_addr_t saved_addr = current_addr;
2931 ram_addr_t addr = 0;
2932 int found = 0;
2934 while (addr < last_ram_offset) {
2935 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2936 uint8_t *p;
2938 cpu_physical_memory_reset_dirty(current_addr,
2939 current_addr + TARGET_PAGE_SIZE,
2940 MIGRATION_DIRTY_FLAG);
2942 p = qemu_get_ram_ptr(current_addr);
2944 if (is_dup_page(p, *p)) {
2945 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2946 qemu_put_byte(f, *p);
2947 } else {
2948 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2949 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2952 found = 1;
2953 break;
2955 addr += TARGET_PAGE_SIZE;
2956 current_addr = (saved_addr + addr) % last_ram_offset;
2959 return found;
2962 static uint64_t bytes_transferred;
2964 static ram_addr_t ram_save_remaining(void)
2966 ram_addr_t addr;
2967 ram_addr_t count = 0;
2969 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2970 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2971 count++;
2974 return count;
2977 uint64_t ram_bytes_remaining(void)
2979 return ram_save_remaining() * TARGET_PAGE_SIZE;
2982 uint64_t ram_bytes_transferred(void)
2984 return bytes_transferred;
2987 uint64_t ram_bytes_total(void)
2989 return last_ram_offset;
2992 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
2994 ram_addr_t addr;
2995 uint64_t bytes_transferred_last;
2996 double bwidth = 0;
2997 uint64_t expected_time = 0;
2999 if (stage < 0) {
3000 cpu_physical_memory_set_dirty_tracking(0);
3001 return 0;
3004 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3005 qemu_file_set_error(f);
3006 return 0;
3009 if (stage == 1) {
3010 bytes_transferred = 0;
3012 /* Make sure all dirty bits are set */
3013 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3014 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3015 cpu_physical_memory_set_dirty(addr);
3018 /* Enable dirty memory tracking */
3019 cpu_physical_memory_set_dirty_tracking(1);
3021 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3024 bytes_transferred_last = bytes_transferred;
3025 bwidth = get_clock();
3027 while (!qemu_file_rate_limit(f)) {
3028 int ret;
3030 ret = ram_save_block(f);
3031 bytes_transferred += ret * TARGET_PAGE_SIZE;
3032 if (ret == 0) /* no more blocks */
3033 break;
3036 bwidth = get_clock() - bwidth;
3037 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3039 /* if we haven't transferred anything this round, force expected_time to a
3040 * a very high value, but without crashing */
3041 if (bwidth == 0)
3042 bwidth = 0.000001;
3044 /* try transferring iterative blocks of memory */
3045 if (stage == 3) {
3046 /* flush all remaining blocks regardless of rate limiting */
3047 while (ram_save_block(f) != 0) {
3048 bytes_transferred += TARGET_PAGE_SIZE;
3050 cpu_physical_memory_set_dirty_tracking(0);
3053 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3055 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3057 return (stage == 2) && (expected_time <= migrate_max_downtime());
3060 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3062 ram_addr_t addr;
3063 int flags;
3065 if (version_id != 3)
3066 return -EINVAL;
3068 do {
3069 addr = qemu_get_be64(f);
3071 flags = addr & ~TARGET_PAGE_MASK;
3072 addr &= TARGET_PAGE_MASK;
3074 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3075 if (addr != last_ram_offset)
3076 return -EINVAL;
3079 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3080 uint8_t ch = qemu_get_byte(f);
3081 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3082 #ifndef _WIN32
3083 if (ch == 0 &&
3084 (!kvm_enabled() || kvm_has_sync_mmu())) {
3085 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3087 #endif
3088 } else if (flags & RAM_SAVE_FLAG_PAGE) {
3089 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3091 if (qemu_file_has_error(f)) {
3092 return -EIO;
3094 } while (!(flags & RAM_SAVE_FLAG_EOS));
3096 return 0;
3099 void qemu_service_io(void)
3101 qemu_notify_event();
3104 /***********************************************************/
3105 /* machine registration */
3107 static QEMUMachine *first_machine = NULL;
3108 QEMUMachine *current_machine = NULL;
3110 int qemu_register_machine(QEMUMachine *m)
3112 QEMUMachine **pm;
3113 pm = &first_machine;
3114 while (*pm != NULL)
3115 pm = &(*pm)->next;
3116 m->next = NULL;
3117 *pm = m;
3118 return 0;
3121 static QEMUMachine *find_machine(const char *name)
3123 QEMUMachine *m;
3125 for(m = first_machine; m != NULL; m = m->next) {
3126 if (!strcmp(m->name, name))
3127 return m;
3128 if (m->alias && !strcmp(m->alias, name))
3129 return m;
3131 return NULL;
3134 static QEMUMachine *find_default_machine(void)
3136 QEMUMachine *m;
3138 for(m = first_machine; m != NULL; m = m->next) {
3139 if (m->is_default) {
3140 return m;
3143 return NULL;
3146 /***********************************************************/
3147 /* main execution loop */
3149 static void gui_update(void *opaque)
3151 uint64_t interval = GUI_REFRESH_INTERVAL;
3152 DisplayState *ds = opaque;
3153 DisplayChangeListener *dcl = ds->listeners;
3155 dpy_refresh(ds);
3157 while (dcl != NULL) {
3158 if (dcl->gui_timer_interval &&
3159 dcl->gui_timer_interval < interval)
3160 interval = dcl->gui_timer_interval;
3161 dcl = dcl->next;
3163 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3166 static void nographic_update(void *opaque)
3168 uint64_t interval = GUI_REFRESH_INTERVAL;
3170 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3173 struct vm_change_state_entry {
3174 VMChangeStateHandler *cb;
3175 void *opaque;
3176 QLIST_ENTRY (vm_change_state_entry) entries;
3179 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3181 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3182 void *opaque)
3184 VMChangeStateEntry *e;
3186 e = qemu_mallocz(sizeof (*e));
3188 e->cb = cb;
3189 e->opaque = opaque;
3190 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3191 return e;
3194 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3196 QLIST_REMOVE (e, entries);
3197 qemu_free (e);
3200 static void vm_state_notify(int running, int reason)
3202 VMChangeStateEntry *e;
3204 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3205 e->cb(e->opaque, running, reason);
3209 static void resume_all_vcpus(void);
3210 static void pause_all_vcpus(void);
3212 void vm_start(void)
3214 if (!vm_running) {
3215 cpu_enable_ticks();
3216 vm_running = 1;
3217 vm_state_notify(1, 0);
3218 qemu_rearm_alarm_timer(alarm_timer);
3219 resume_all_vcpus();
3223 /* reset/shutdown handler */
3225 typedef struct QEMUResetEntry {
3226 QTAILQ_ENTRY(QEMUResetEntry) entry;
3227 QEMUResetHandler *func;
3228 void *opaque;
3229 } QEMUResetEntry;
3231 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3232 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3233 static int reset_requested;
3234 static int shutdown_requested;
3235 static int powerdown_requested;
3236 static int debug_requested;
3237 static int vmstop_requested;
3239 int qemu_shutdown_requested(void)
3241 int r = shutdown_requested;
3242 shutdown_requested = 0;
3243 return r;
3246 int qemu_reset_requested(void)
3248 int r = reset_requested;
3249 reset_requested = 0;
3250 return r;
3253 int qemu_powerdown_requested(void)
3255 int r = powerdown_requested;
3256 powerdown_requested = 0;
3257 return r;
3260 static int qemu_debug_requested(void)
3262 int r = debug_requested;
3263 debug_requested = 0;
3264 return r;
3267 static int qemu_vmstop_requested(void)
3269 int r = vmstop_requested;
3270 vmstop_requested = 0;
3271 return r;
3274 static void do_vm_stop(int reason)
3276 if (vm_running) {
3277 cpu_disable_ticks();
3278 vm_running = 0;
3279 pause_all_vcpus();
3280 vm_state_notify(0, reason);
3284 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3286 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3288 re->func = func;
3289 re->opaque = opaque;
3290 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3293 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3295 QEMUResetEntry *re;
3297 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3298 if (re->func == func && re->opaque == opaque) {
3299 QTAILQ_REMOVE(&reset_handlers, re, entry);
3300 qemu_free(re);
3301 return;
3306 void qemu_system_reset(void)
3308 QEMUResetEntry *re, *nre;
3310 /* reset all devices */
3311 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3312 re->func(re->opaque);
3316 void qemu_system_reset_request(void)
3318 if (no_reboot) {
3319 shutdown_requested = 1;
3320 } else {
3321 reset_requested = 1;
3323 qemu_notify_event();
3326 void qemu_system_shutdown_request(void)
3328 shutdown_requested = 1;
3329 qemu_notify_event();
3332 void qemu_system_powerdown_request(void)
3334 powerdown_requested = 1;
3335 qemu_notify_event();
3338 #ifdef CONFIG_IOTHREAD
3339 static void qemu_system_vmstop_request(int reason)
3341 vmstop_requested = reason;
3342 qemu_notify_event();
3344 #endif
3346 #ifndef _WIN32
3347 static int io_thread_fd = -1;
3349 static void qemu_event_increment(void)
3351 static const char byte = 0;
3353 if (io_thread_fd == -1)
3354 return;
3356 write(io_thread_fd, &byte, sizeof(byte));
3359 static void qemu_event_read(void *opaque)
3361 int fd = (unsigned long)opaque;
3362 ssize_t len;
3364 /* Drain the notify pipe */
3365 do {
3366 char buffer[512];
3367 len = read(fd, buffer, sizeof(buffer));
3368 } while ((len == -1 && errno == EINTR) || len > 0);
3371 static int qemu_event_init(void)
3373 int err;
3374 int fds[2];
3376 err = qemu_pipe(fds);
3377 if (err == -1)
3378 return -errno;
3380 err = fcntl_setfl(fds[0], O_NONBLOCK);
3381 if (err < 0)
3382 goto fail;
3384 err = fcntl_setfl(fds[1], O_NONBLOCK);
3385 if (err < 0)
3386 goto fail;
3388 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3389 (void *)(unsigned long)fds[0]);
3391 io_thread_fd = fds[1];
3392 return 0;
3394 fail:
3395 close(fds[0]);
3396 close(fds[1]);
3397 return err;
3399 #else
3400 HANDLE qemu_event_handle;
3402 static void dummy_event_handler(void *opaque)
3406 static int qemu_event_init(void)
3408 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3409 if (!qemu_event_handle) {
3410 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3411 return -1;
3413 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3414 return 0;
3417 static void qemu_event_increment(void)
3419 if (!SetEvent(qemu_event_handle)) {
3420 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3421 GetLastError());
3422 exit (1);
3425 #endif
3427 static int cpu_can_run(CPUState *env)
3429 if (env->stop)
3430 return 0;
3431 if (env->stopped)
3432 return 0;
3433 return 1;
3436 #ifndef CONFIG_IOTHREAD
3437 static int qemu_init_main_loop(void)
3439 return qemu_event_init();
3442 void qemu_init_vcpu(void *_env)
3444 CPUState *env = _env;
3446 if (kvm_enabled())
3447 kvm_init_vcpu(env);
3448 env->nr_cores = smp_cores;
3449 env->nr_threads = smp_threads;
3450 return;
3453 int qemu_cpu_self(void *env)
3455 return 1;
3458 static void resume_all_vcpus(void)
3462 static void pause_all_vcpus(void)
3466 void qemu_cpu_kick(void *env)
3468 return;
3471 void qemu_notify_event(void)
3473 CPUState *env = cpu_single_env;
3475 if (env) {
3476 cpu_exit(env);
3480 void qemu_mutex_lock_iothread(void) {}
3481 void qemu_mutex_unlock_iothread(void) {}
3483 void vm_stop(int reason)
3485 do_vm_stop(reason);
3488 #else /* CONFIG_IOTHREAD */
3490 #include "qemu-thread.h"
3492 QemuMutex qemu_global_mutex;
3493 static QemuMutex qemu_fair_mutex;
3495 static QemuThread io_thread;
3497 static QemuThread *tcg_cpu_thread;
3498 static QemuCond *tcg_halt_cond;
3500 static int qemu_system_ready;
3501 /* cpu creation */
3502 static QemuCond qemu_cpu_cond;
3503 /* system init */
3504 static QemuCond qemu_system_cond;
3505 static QemuCond qemu_pause_cond;
3507 static void block_io_signals(void);
3508 static void unblock_io_signals(void);
3509 static int tcg_has_work(void);
3511 static int qemu_init_main_loop(void)
3513 int ret;
3515 ret = qemu_event_init();
3516 if (ret)
3517 return ret;
3519 qemu_cond_init(&qemu_pause_cond);
3520 qemu_mutex_init(&qemu_fair_mutex);
3521 qemu_mutex_init(&qemu_global_mutex);
3522 qemu_mutex_lock(&qemu_global_mutex);
3524 unblock_io_signals();
3525 qemu_thread_self(&io_thread);
3527 return 0;
3530 static void qemu_wait_io_event(CPUState *env)
3532 while (!tcg_has_work())
3533 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3535 qemu_mutex_unlock(&qemu_global_mutex);
3538 * Users of qemu_global_mutex can be starved, having no chance
3539 * to acquire it since this path will get to it first.
3540 * So use another lock to provide fairness.
3542 qemu_mutex_lock(&qemu_fair_mutex);
3543 qemu_mutex_unlock(&qemu_fair_mutex);
3545 qemu_mutex_lock(&qemu_global_mutex);
3546 if (env->stop) {
3547 env->stop = 0;
3548 env->stopped = 1;
3549 qemu_cond_signal(&qemu_pause_cond);
3553 static int qemu_cpu_exec(CPUState *env);
3555 static void *kvm_cpu_thread_fn(void *arg)
3557 CPUState *env = arg;
3559 block_io_signals();
3560 qemu_thread_self(env->thread);
3561 if (kvm_enabled())
3562 kvm_init_vcpu(env);
3564 /* signal CPU creation */
3565 qemu_mutex_lock(&qemu_global_mutex);
3566 env->created = 1;
3567 qemu_cond_signal(&qemu_cpu_cond);
3569 /* and wait for machine initialization */
3570 while (!qemu_system_ready)
3571 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3573 while (1) {
3574 if (cpu_can_run(env))
3575 qemu_cpu_exec(env);
3576 qemu_wait_io_event(env);
3579 return NULL;
3582 static void tcg_cpu_exec(void);
3584 static void *tcg_cpu_thread_fn(void *arg)
3586 CPUState *env = arg;
3588 block_io_signals();
3589 qemu_thread_self(env->thread);
3591 /* signal CPU creation */
3592 qemu_mutex_lock(&qemu_global_mutex);
3593 for (env = first_cpu; env != NULL; env = env->next_cpu)
3594 env->created = 1;
3595 qemu_cond_signal(&qemu_cpu_cond);
3597 /* and wait for machine initialization */
3598 while (!qemu_system_ready)
3599 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3601 while (1) {
3602 tcg_cpu_exec();
3603 qemu_wait_io_event(cur_cpu);
3606 return NULL;
3609 void qemu_cpu_kick(void *_env)
3611 CPUState *env = _env;
3612 qemu_cond_broadcast(env->halt_cond);
3613 if (kvm_enabled())
3614 qemu_thread_signal(env->thread, SIGUSR1);
3617 int qemu_cpu_self(void *_env)
3619 CPUState *env = _env;
3620 QemuThread this;
3622 qemu_thread_self(&this);
3624 return qemu_thread_equal(&this, env->thread);
3627 static void cpu_signal(int sig)
3629 if (cpu_single_env)
3630 cpu_exit(cpu_single_env);
3633 static void block_io_signals(void)
3635 sigset_t set;
3636 struct sigaction sigact;
3638 sigemptyset(&set);
3639 sigaddset(&set, SIGUSR2);
3640 sigaddset(&set, SIGIO);
3641 sigaddset(&set, SIGALRM);
3642 pthread_sigmask(SIG_BLOCK, &set, NULL);
3644 sigemptyset(&set);
3645 sigaddset(&set, SIGUSR1);
3646 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3648 memset(&sigact, 0, sizeof(sigact));
3649 sigact.sa_handler = cpu_signal;
3650 sigaction(SIGUSR1, &sigact, NULL);
3653 static void unblock_io_signals(void)
3655 sigset_t set;
3657 sigemptyset(&set);
3658 sigaddset(&set, SIGUSR2);
3659 sigaddset(&set, SIGIO);
3660 sigaddset(&set, SIGALRM);
3661 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3663 sigemptyset(&set);
3664 sigaddset(&set, SIGUSR1);
3665 pthread_sigmask(SIG_BLOCK, &set, NULL);
3668 static void qemu_signal_lock(unsigned int msecs)
3670 qemu_mutex_lock(&qemu_fair_mutex);
3672 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3673 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3674 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3675 break;
3677 qemu_mutex_unlock(&qemu_fair_mutex);
3680 void qemu_mutex_lock_iothread(void)
3682 if (kvm_enabled()) {
3683 qemu_mutex_lock(&qemu_fair_mutex);
3684 qemu_mutex_lock(&qemu_global_mutex);
3685 qemu_mutex_unlock(&qemu_fair_mutex);
3686 } else
3687 qemu_signal_lock(100);
3690 void qemu_mutex_unlock_iothread(void)
3692 qemu_mutex_unlock(&qemu_global_mutex);
3695 static int all_vcpus_paused(void)
3697 CPUState *penv = first_cpu;
3699 while (penv) {
3700 if (!penv->stopped)
3701 return 0;
3702 penv = (CPUState *)penv->next_cpu;
3705 return 1;
3708 static void pause_all_vcpus(void)
3710 CPUState *penv = first_cpu;
3712 while (penv) {
3713 penv->stop = 1;
3714 qemu_thread_signal(penv->thread, SIGUSR1);
3715 qemu_cpu_kick(penv);
3716 penv = (CPUState *)penv->next_cpu;
3719 while (!all_vcpus_paused()) {
3720 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3721 penv = first_cpu;
3722 while (penv) {
3723 qemu_thread_signal(penv->thread, SIGUSR1);
3724 penv = (CPUState *)penv->next_cpu;
3729 static void resume_all_vcpus(void)
3731 CPUState *penv = first_cpu;
3733 while (penv) {
3734 penv->stop = 0;
3735 penv->stopped = 0;
3736 qemu_thread_signal(penv->thread, SIGUSR1);
3737 qemu_cpu_kick(penv);
3738 penv = (CPUState *)penv->next_cpu;
3742 static void tcg_init_vcpu(void *_env)
3744 CPUState *env = _env;
3745 /* share a single thread for all cpus with TCG */
3746 if (!tcg_cpu_thread) {
3747 env->thread = qemu_mallocz(sizeof(QemuThread));
3748 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3749 qemu_cond_init(env->halt_cond);
3750 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3751 while (env->created == 0)
3752 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3753 tcg_cpu_thread = env->thread;
3754 tcg_halt_cond = env->halt_cond;
3755 } else {
3756 env->thread = tcg_cpu_thread;
3757 env->halt_cond = tcg_halt_cond;
3761 static void kvm_start_vcpu(CPUState *env)
3763 env->thread = qemu_mallocz(sizeof(QemuThread));
3764 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3765 qemu_cond_init(env->halt_cond);
3766 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3767 while (env->created == 0)
3768 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3771 void qemu_init_vcpu(void *_env)
3773 CPUState *env = _env;
3775 if (kvm_enabled())
3776 kvm_start_vcpu(env);
3777 else
3778 tcg_init_vcpu(env);
3779 env->nr_cores = smp_cores;
3780 env->nr_threads = smp_threads;
3783 void qemu_notify_event(void)
3785 qemu_event_increment();
3788 void vm_stop(int reason)
3790 QemuThread me;
3791 qemu_thread_self(&me);
3793 if (!qemu_thread_equal(&me, &io_thread)) {
3794 qemu_system_vmstop_request(reason);
3796 * FIXME: should not return to device code in case
3797 * vm_stop() has been requested.
3799 if (cpu_single_env) {
3800 cpu_exit(cpu_single_env);
3801 cpu_single_env->stop = 1;
3803 return;
3805 do_vm_stop(reason);
3808 #endif
3811 #ifdef _WIN32
3812 static void host_main_loop_wait(int *timeout)
3814 int ret, ret2, i;
3815 PollingEntry *pe;
3818 /* XXX: need to suppress polling by better using win32 events */
3819 ret = 0;
3820 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3821 ret |= pe->func(pe->opaque);
3823 if (ret == 0) {
3824 int err;
3825 WaitObjects *w = &wait_objects;
3827 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3828 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3829 if (w->func[ret - WAIT_OBJECT_0])
3830 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3832 /* Check for additional signaled events */
3833 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3835 /* Check if event is signaled */
3836 ret2 = WaitForSingleObject(w->events[i], 0);
3837 if(ret2 == WAIT_OBJECT_0) {
3838 if (w->func[i])
3839 w->func[i](w->opaque[i]);
3840 } else if (ret2 == WAIT_TIMEOUT) {
3841 } else {
3842 err = GetLastError();
3843 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3846 } else if (ret == WAIT_TIMEOUT) {
3847 } else {
3848 err = GetLastError();
3849 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3853 *timeout = 0;
3855 #else
3856 static void host_main_loop_wait(int *timeout)
3859 #endif
3861 void main_loop_wait(int timeout)
3863 IOHandlerRecord *ioh;
3864 fd_set rfds, wfds, xfds;
3865 int ret, nfds;
3866 struct timeval tv;
3868 qemu_bh_update_timeout(&timeout);
3870 host_main_loop_wait(&timeout);
3872 /* poll any events */
3873 /* XXX: separate device handlers from system ones */
3874 nfds = -1;
3875 FD_ZERO(&rfds);
3876 FD_ZERO(&wfds);
3877 FD_ZERO(&xfds);
3878 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3879 if (ioh->deleted)
3880 continue;
3881 if (ioh->fd_read &&
3882 (!ioh->fd_read_poll ||
3883 ioh->fd_read_poll(ioh->opaque) != 0)) {
3884 FD_SET(ioh->fd, &rfds);
3885 if (ioh->fd > nfds)
3886 nfds = ioh->fd;
3888 if (ioh->fd_write) {
3889 FD_SET(ioh->fd, &wfds);
3890 if (ioh->fd > nfds)
3891 nfds = ioh->fd;
3895 tv.tv_sec = timeout / 1000;
3896 tv.tv_usec = (timeout % 1000) * 1000;
3898 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3900 qemu_mutex_unlock_iothread();
3901 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3902 qemu_mutex_lock_iothread();
3903 if (ret > 0) {
3904 IOHandlerRecord **pioh;
3906 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3907 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3908 ioh->fd_read(ioh->opaque);
3910 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3911 ioh->fd_write(ioh->opaque);
3915 /* remove deleted IO handlers */
3916 pioh = &first_io_handler;
3917 while (*pioh) {
3918 ioh = *pioh;
3919 if (ioh->deleted) {
3920 *pioh = ioh->next;
3921 qemu_free(ioh);
3922 } else
3923 pioh = &ioh->next;
3927 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3929 /* rearm timer, if not periodic */
3930 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3931 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3932 qemu_rearm_alarm_timer(alarm_timer);
3935 /* vm time timers */
3936 if (vm_running) {
3937 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3938 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3939 qemu_get_clock(vm_clock));
3942 /* real time timers */
3943 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3944 qemu_get_clock(rt_clock));
3946 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3947 qemu_get_clock(host_clock));
3949 /* Check bottom-halves last in case any of the earlier events triggered
3950 them. */
3951 qemu_bh_poll();
3955 static int qemu_cpu_exec(CPUState *env)
3957 int ret;
3958 #ifdef CONFIG_PROFILER
3959 int64_t ti;
3960 #endif
3962 #ifdef CONFIG_PROFILER
3963 ti = profile_getclock();
3964 #endif
3965 if (use_icount) {
3966 int64_t count;
3967 int decr;
3968 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3969 env->icount_decr.u16.low = 0;
3970 env->icount_extra = 0;
3971 count = qemu_next_deadline();
3972 count = (count + (1 << icount_time_shift) - 1)
3973 >> icount_time_shift;
3974 qemu_icount += count;
3975 decr = (count > 0xffff) ? 0xffff : count;
3976 count -= decr;
3977 env->icount_decr.u16.low = decr;
3978 env->icount_extra = count;
3980 ret = cpu_exec(env);
3981 #ifdef CONFIG_PROFILER
3982 qemu_time += profile_getclock() - ti;
3983 #endif
3984 if (use_icount) {
3985 /* Fold pending instructions back into the
3986 instruction counter, and clear the interrupt flag. */
3987 qemu_icount -= (env->icount_decr.u16.low
3988 + env->icount_extra);
3989 env->icount_decr.u32 = 0;
3990 env->icount_extra = 0;
3992 return ret;
3995 static void tcg_cpu_exec(void)
3997 int ret = 0;
3999 if (next_cpu == NULL)
4000 next_cpu = first_cpu;
4001 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4002 CPUState *env = cur_cpu = next_cpu;
4004 if (!vm_running)
4005 break;
4006 if (timer_alarm_pending) {
4007 timer_alarm_pending = 0;
4008 break;
4010 if (cpu_can_run(env))
4011 ret = qemu_cpu_exec(env);
4012 if (ret == EXCP_DEBUG) {
4013 gdb_set_stop_cpu(env);
4014 debug_requested = 1;
4015 break;
4020 static int cpu_has_work(CPUState *env)
4022 if (env->stop)
4023 return 1;
4024 if (env->stopped)
4025 return 0;
4026 if (!env->halted)
4027 return 1;
4028 if (qemu_cpu_has_work(env))
4029 return 1;
4030 return 0;
4033 static int tcg_has_work(void)
4035 CPUState *env;
4037 for (env = first_cpu; env != NULL; env = env->next_cpu)
4038 if (cpu_has_work(env))
4039 return 1;
4040 return 0;
4043 static int qemu_calculate_timeout(void)
4045 #ifndef CONFIG_IOTHREAD
4046 int timeout;
4048 if (!vm_running)
4049 timeout = 5000;
4050 else if (tcg_has_work())
4051 timeout = 0;
4052 else if (!use_icount)
4053 timeout = 5000;
4054 else {
4055 /* XXX: use timeout computed from timers */
4056 int64_t add;
4057 int64_t delta;
4058 /* Advance virtual time to the next event. */
4059 if (use_icount == 1) {
4060 /* When not using an adaptive execution frequency
4061 we tend to get badly out of sync with real time,
4062 so just delay for a reasonable amount of time. */
4063 delta = 0;
4064 } else {
4065 delta = cpu_get_icount() - cpu_get_clock();
4067 if (delta > 0) {
4068 /* If virtual time is ahead of real time then just
4069 wait for IO. */
4070 timeout = (delta / 1000000) + 1;
4071 } else {
4072 /* Wait for either IO to occur or the next
4073 timer event. */
4074 add = qemu_next_deadline();
4075 /* We advance the timer before checking for IO.
4076 Limit the amount we advance so that early IO
4077 activity won't get the guest too far ahead. */
4078 if (add > 10000000)
4079 add = 10000000;
4080 delta += add;
4081 add = (add + (1 << icount_time_shift) - 1)
4082 >> icount_time_shift;
4083 qemu_icount += add;
4084 timeout = delta / 1000000;
4085 if (timeout < 0)
4086 timeout = 0;
4090 return timeout;
4091 #else /* CONFIG_IOTHREAD */
4092 return 1000;
4093 #endif
4096 static int vm_can_run(void)
4098 if (powerdown_requested)
4099 return 0;
4100 if (reset_requested)
4101 return 0;
4102 if (shutdown_requested)
4103 return 0;
4104 if (debug_requested)
4105 return 0;
4106 return 1;
4109 qemu_irq qemu_system_powerdown;
4111 static void main_loop(void)
4113 int r;
4115 #ifdef CONFIG_IOTHREAD
4116 qemu_system_ready = 1;
4117 qemu_cond_broadcast(&qemu_system_cond);
4118 #endif
4120 for (;;) {
4121 do {
4122 #ifdef CONFIG_PROFILER
4123 int64_t ti;
4124 #endif
4125 #ifndef CONFIG_IOTHREAD
4126 tcg_cpu_exec();
4127 #endif
4128 #ifdef CONFIG_PROFILER
4129 ti = profile_getclock();
4130 #endif
4131 main_loop_wait(qemu_calculate_timeout());
4132 #ifdef CONFIG_PROFILER
4133 dev_time += profile_getclock() - ti;
4134 #endif
4135 } while (vm_can_run());
4137 if (qemu_debug_requested()) {
4138 monitor_protocol_event(QEVENT_DEBUG, NULL);
4139 vm_stop(EXCP_DEBUG);
4141 if (qemu_shutdown_requested()) {
4142 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
4143 if (no_shutdown) {
4144 vm_stop(0);
4145 no_shutdown = 0;
4146 } else
4147 break;
4149 if (qemu_reset_requested()) {
4150 monitor_protocol_event(QEVENT_RESET, NULL);
4151 pause_all_vcpus();
4152 qemu_system_reset();
4153 resume_all_vcpus();
4155 if (qemu_powerdown_requested()) {
4156 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
4157 qemu_irq_raise(qemu_system_powerdown);
4159 if ((r = qemu_vmstop_requested())) {
4160 monitor_protocol_event(QEVENT_STOP, NULL);
4161 vm_stop(r);
4164 pause_all_vcpus();
4167 static void version(void)
4169 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4172 static void help(int exitcode)
4174 version();
4175 printf("usage: %s [options] [disk_image]\n"
4176 "\n"
4177 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4178 "\n"
4179 #define DEF(option, opt_arg, opt_enum, opt_help) \
4180 opt_help
4181 #define DEFHEADING(text) stringify(text) "\n"
4182 #include "qemu-options.h"
4183 #undef DEF
4184 #undef DEFHEADING
4185 #undef GEN_DOCS
4186 "\n"
4187 "During emulation, the following keys are useful:\n"
4188 "ctrl-alt-f toggle full screen\n"
4189 "ctrl-alt-n switch to virtual console 'n'\n"
4190 "ctrl-alt toggle mouse and keyboard grab\n"
4191 "\n"
4192 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4194 "qemu",
4195 DEFAULT_RAM_SIZE,
4196 #ifndef _WIN32
4197 DEFAULT_NETWORK_SCRIPT,
4198 DEFAULT_NETWORK_DOWN_SCRIPT,
4199 #endif
4200 DEFAULT_GDBSTUB_PORT,
4201 "/tmp/qemu.log");
4202 exit(exitcode);
4205 #define HAS_ARG 0x0001
4207 enum {
4208 #define DEF(option, opt_arg, opt_enum, opt_help) \
4209 opt_enum,
4210 #define DEFHEADING(text)
4211 #include "qemu-options.h"
4212 #undef DEF
4213 #undef DEFHEADING
4214 #undef GEN_DOCS
4217 typedef struct QEMUOption {
4218 const char *name;
4219 int flags;
4220 int index;
4221 } QEMUOption;
4223 static const QEMUOption qemu_options[] = {
4224 { "h", 0, QEMU_OPTION_h },
4225 #define DEF(option, opt_arg, opt_enum, opt_help) \
4226 { option, opt_arg, opt_enum },
4227 #define DEFHEADING(text)
4228 #include "qemu-options.h"
4229 #undef DEF
4230 #undef DEFHEADING
4231 #undef GEN_DOCS
4232 { NULL },
4235 #ifdef HAS_AUDIO
4236 struct soundhw soundhw[] = {
4237 #ifdef HAS_AUDIO_CHOICE
4238 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4240 "pcspk",
4241 "PC speaker",
4244 { .init_isa = pcspk_audio_init }
4246 #endif
4248 #ifdef CONFIG_SB16
4250 "sb16",
4251 "Creative Sound Blaster 16",
4254 { .init_isa = SB16_init }
4256 #endif
4258 #ifdef CONFIG_CS4231A
4260 "cs4231a",
4261 "CS4231A",
4264 { .init_isa = cs4231a_init }
4266 #endif
4268 #ifdef CONFIG_ADLIB
4270 "adlib",
4271 #ifdef HAS_YMF262
4272 "Yamaha YMF262 (OPL3)",
4273 #else
4274 "Yamaha YM3812 (OPL2)",
4275 #endif
4278 { .init_isa = Adlib_init }
4280 #endif
4282 #ifdef CONFIG_GUS
4284 "gus",
4285 "Gravis Ultrasound GF1",
4288 { .init_isa = GUS_init }
4290 #endif
4292 #ifdef CONFIG_AC97
4294 "ac97",
4295 "Intel 82801AA AC97 Audio",
4298 { .init_pci = ac97_init }
4300 #endif
4302 #ifdef CONFIG_ES1370
4304 "es1370",
4305 "ENSONIQ AudioPCI ES1370",
4308 { .init_pci = es1370_init }
4310 #endif
4312 #endif /* HAS_AUDIO_CHOICE */
4314 { NULL, NULL, 0, 0, { NULL } }
4317 static void select_soundhw (const char *optarg)
4319 struct soundhw *c;
4321 if (*optarg == '?') {
4322 show_valid_cards:
4324 printf ("Valid sound card names (comma separated):\n");
4325 for (c = soundhw; c->name; ++c) {
4326 printf ("%-11s %s\n", c->name, c->descr);
4328 printf ("\n-soundhw all will enable all of the above\n");
4329 exit (*optarg != '?');
4331 else {
4332 size_t l;
4333 const char *p;
4334 char *e;
4335 int bad_card = 0;
4337 if (!strcmp (optarg, "all")) {
4338 for (c = soundhw; c->name; ++c) {
4339 c->enabled = 1;
4341 return;
4344 p = optarg;
4345 while (*p) {
4346 e = strchr (p, ',');
4347 l = !e ? strlen (p) : (size_t) (e - p);
4349 for (c = soundhw; c->name; ++c) {
4350 if (!strncmp (c->name, p, l) && !c->name[l]) {
4351 c->enabled = 1;
4352 break;
4356 if (!c->name) {
4357 if (l > 80) {
4358 fprintf (stderr,
4359 "Unknown sound card name (too big to show)\n");
4361 else {
4362 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4363 (int) l, p);
4365 bad_card = 1;
4367 p += l + (e != NULL);
4370 if (bad_card)
4371 goto show_valid_cards;
4374 #endif
4376 static void select_vgahw (const char *p)
4378 const char *opts;
4380 default_vga = 0;
4381 vga_interface_type = VGA_NONE;
4382 if (strstart(p, "std", &opts)) {
4383 vga_interface_type = VGA_STD;
4384 } else if (strstart(p, "cirrus", &opts)) {
4385 vga_interface_type = VGA_CIRRUS;
4386 } else if (strstart(p, "vmware", &opts)) {
4387 vga_interface_type = VGA_VMWARE;
4388 } else if (strstart(p, "xenfb", &opts)) {
4389 vga_interface_type = VGA_XENFB;
4390 } else if (!strstart(p, "none", &opts)) {
4391 invalid_vga:
4392 fprintf(stderr, "Unknown vga type: %s\n", p);
4393 exit(1);
4395 while (*opts) {
4396 const char *nextopt;
4398 if (strstart(opts, ",retrace=", &nextopt)) {
4399 opts = nextopt;
4400 if (strstart(opts, "dumb", &nextopt))
4401 vga_retrace_method = VGA_RETRACE_DUMB;
4402 else if (strstart(opts, "precise", &nextopt))
4403 vga_retrace_method = VGA_RETRACE_PRECISE;
4404 else goto invalid_vga;
4405 } else goto invalid_vga;
4406 opts = nextopt;
4410 #ifdef TARGET_I386
4411 static int balloon_parse(const char *arg)
4413 QemuOpts *opts;
4415 if (strcmp(arg, "none") == 0) {
4416 return 0;
4419 if (!strncmp(arg, "virtio", 6)) {
4420 if (arg[6] == ',') {
4421 /* have params -> parse them */
4422 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4423 if (!opts)
4424 return -1;
4425 } else {
4426 /* create empty opts */
4427 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4429 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4430 return 0;
4433 return -1;
4435 #endif
4437 #ifdef _WIN32
4438 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4440 exit(STATUS_CONTROL_C_EXIT);
4441 return TRUE;
4443 #endif
4445 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4447 int ret;
4449 if(strlen(str) != 36)
4450 return -1;
4452 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4453 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4454 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4456 if(ret != 16)
4457 return -1;
4459 #ifdef TARGET_I386
4460 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4461 #endif
4463 return 0;
4466 #ifndef _WIN32
4468 static void termsig_handler(int signal)
4470 qemu_system_shutdown_request();
4473 static void sigchld_handler(int signal)
4475 waitpid(-1, NULL, WNOHANG);
4478 static void sighandler_setup(void)
4480 struct sigaction act;
4482 memset(&act, 0, sizeof(act));
4483 act.sa_handler = termsig_handler;
4484 sigaction(SIGINT, &act, NULL);
4485 sigaction(SIGHUP, &act, NULL);
4486 sigaction(SIGTERM, &act, NULL);
4488 act.sa_handler = sigchld_handler;
4489 act.sa_flags = SA_NOCLDSTOP;
4490 sigaction(SIGCHLD, &act, NULL);
4493 #endif
4495 #ifdef _WIN32
4496 /* Look for support files in the same directory as the executable. */
4497 static char *find_datadir(const char *argv0)
4499 char *p;
4500 char buf[MAX_PATH];
4501 DWORD len;
4503 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4504 if (len == 0) {
4505 return NULL;
4508 buf[len] = 0;
4509 p = buf + len - 1;
4510 while (p != buf && *p != '\\')
4511 p--;
4512 *p = 0;
4513 if (access(buf, R_OK) == 0) {
4514 return qemu_strdup(buf);
4516 return NULL;
4518 #else /* !_WIN32 */
4520 /* Find a likely location for support files using the location of the binary.
4521 For installed binaries this will be "$bindir/../share/qemu". When
4522 running from the build tree this will be "$bindir/../pc-bios". */
4523 #define SHARE_SUFFIX "/share/qemu"
4524 #define BUILD_SUFFIX "/pc-bios"
4525 static char *find_datadir(const char *argv0)
4527 char *dir;
4528 char *p = NULL;
4529 char *res;
4530 char buf[PATH_MAX];
4531 size_t max_len;
4533 #if defined(__linux__)
4535 int len;
4536 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4537 if (len > 0) {
4538 buf[len] = 0;
4539 p = buf;
4542 #elif defined(__FreeBSD__)
4544 int len;
4545 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4546 if (len > 0) {
4547 buf[len] = 0;
4548 p = buf;
4551 #endif
4552 /* If we don't have any way of figuring out the actual executable
4553 location then try argv[0]. */
4554 if (!p) {
4555 p = realpath(argv0, buf);
4556 if (!p) {
4557 return NULL;
4560 dir = dirname(p);
4561 dir = dirname(dir);
4563 max_len = strlen(dir) +
4564 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4565 res = qemu_mallocz(max_len);
4566 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4567 if (access(res, R_OK)) {
4568 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4569 if (access(res, R_OK)) {
4570 qemu_free(res);
4571 res = NULL;
4575 return res;
4577 #undef SHARE_SUFFIX
4578 #undef BUILD_SUFFIX
4579 #endif
4581 char *qemu_find_file(int type, const char *name)
4583 int len;
4584 const char *subdir;
4585 char *buf;
4587 /* If name contains path separators then try it as a straight path. */
4588 if ((strchr(name, '/') || strchr(name, '\\'))
4589 && access(name, R_OK) == 0) {
4590 return qemu_strdup(name);
4592 switch (type) {
4593 case QEMU_FILE_TYPE_BIOS:
4594 subdir = "";
4595 break;
4596 case QEMU_FILE_TYPE_KEYMAP:
4597 subdir = "keymaps/";
4598 break;
4599 default:
4600 abort();
4602 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4603 buf = qemu_mallocz(len);
4604 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4605 if (access(buf, R_OK)) {
4606 qemu_free(buf);
4607 return NULL;
4609 return buf;
4612 static int device_init_func(QemuOpts *opts, void *opaque)
4614 DeviceState *dev;
4616 dev = qdev_device_add(opts);
4617 if (!dev)
4618 return -1;
4619 return 0;
4622 static int chardev_init_func(QemuOpts *opts, void *opaque)
4624 CharDriverState *chr;
4626 chr = qemu_chr_open_opts(opts, NULL);
4627 if (!chr)
4628 return -1;
4629 return 0;
4632 struct device_config {
4633 enum {
4634 DEV_USB, /* -usbdevice */
4635 DEV_BT, /* -bt */
4636 DEV_SERIAL, /* -serial */
4637 DEV_PARALLEL, /* -parallel */
4638 DEV_MONITOR, /* -monitor */
4639 } type;
4640 const char *cmdline;
4641 QTAILQ_ENTRY(device_config) next;
4643 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4645 static void add_device_config(int type, const char *cmdline)
4647 struct device_config *conf;
4649 conf = qemu_mallocz(sizeof(*conf));
4650 conf->type = type;
4651 conf->cmdline = cmdline;
4652 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4655 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4657 struct device_config *conf;
4658 int rc;
4660 QTAILQ_FOREACH(conf, &device_configs, next) {
4661 if (conf->type != type)
4662 continue;
4663 rc = func(conf->cmdline);
4664 if (0 != rc)
4665 return rc;
4667 return 0;
4670 static int serial_parse(const char *devname)
4672 static int index = 0;
4673 char label[32];
4675 if (strcmp(devname, "none") == 0)
4676 return 0;
4677 if (index == MAX_SERIAL_PORTS) {
4678 fprintf(stderr, "qemu: too many serial ports\n");
4679 exit(1);
4681 snprintf(label, sizeof(label), "serial%d", index);
4682 serial_hds[index] = qemu_chr_open(label, devname, NULL);
4683 if (!serial_hds[index]) {
4684 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4685 devname, strerror(errno));
4686 return -1;
4688 index++;
4689 return 0;
4692 static int parallel_parse(const char *devname)
4694 static int index = 0;
4695 char label[32];
4697 if (strcmp(devname, "none") == 0)
4698 return 0;
4699 if (index == MAX_PARALLEL_PORTS) {
4700 fprintf(stderr, "qemu: too many parallel ports\n");
4701 exit(1);
4703 snprintf(label, sizeof(label), "parallel%d", index);
4704 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4705 if (!parallel_hds[index]) {
4706 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4707 devname, strerror(errno));
4708 return -1;
4710 index++;
4711 return 0;
4714 static int monitor_parse(const char *devname)
4716 static int index = 0;
4717 char label[32];
4719 if (strcmp(devname, "none") == 0)
4720 return 0;
4721 if (index == MAX_MONITOR_DEVICES) {
4722 fprintf(stderr, "qemu: too many monitor devices\n");
4723 exit(1);
4725 if (index == 0) {
4726 snprintf(label, sizeof(label), "monitor");
4727 } else {
4728 snprintf(label, sizeof(label), "monitor%d", index);
4730 monitor_hds[index] = qemu_chr_open(label, devname, NULL);
4731 if (!monitor_hds[index]) {
4732 fprintf(stderr, "qemu: could not open monitor device '%s'\n",
4733 devname);
4734 return -1;
4736 index++;
4737 return 0;
4740 int main(int argc, char **argv, char **envp)
4742 const char *gdbstub_dev = NULL;
4743 uint32_t boot_devices_bitmap = 0;
4744 int i;
4745 int snapshot, linux_boot, net_boot;
4746 const char *initrd_filename;
4747 const char *kernel_filename, *kernel_cmdline;
4748 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4749 DisplayState *ds;
4750 DisplayChangeListener *dcl;
4751 int cyls, heads, secs, translation;
4752 QemuOpts *hda_opts = NULL, *opts;
4753 int optind;
4754 const char *r, *optarg;
4755 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4756 int virtio_console_index;
4757 const char *loadvm = NULL;
4758 QEMUMachine *machine;
4759 const char *cpu_model;
4760 #ifndef _WIN32
4761 int fds[2];
4762 #endif
4763 int tb_size;
4764 const char *pid_file = NULL;
4765 const char *incoming = NULL;
4766 #ifndef _WIN32
4767 int fd = 0;
4768 struct passwd *pwd = NULL;
4769 const char *chroot_dir = NULL;
4770 const char *run_as = NULL;
4771 #endif
4772 CPUState *env;
4773 int show_vnc_port = 0;
4775 init_clocks();
4777 qemu_errors_to_file(stderr);
4778 qemu_cache_utils_init(envp);
4780 QLIST_INIT (&vm_change_state_head);
4781 #ifndef _WIN32
4783 struct sigaction act;
4784 sigfillset(&act.sa_mask);
4785 act.sa_flags = 0;
4786 act.sa_handler = SIG_IGN;
4787 sigaction(SIGPIPE, &act, NULL);
4789 #else
4790 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4791 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4792 QEMU to run on a single CPU */
4794 HANDLE h;
4795 DWORD mask, smask;
4796 int i;
4797 h = GetCurrentProcess();
4798 if (GetProcessAffinityMask(h, &mask, &smask)) {
4799 for(i = 0; i < 32; i++) {
4800 if (mask & (1 << i))
4801 break;
4803 if (i != 32) {
4804 mask = 1 << i;
4805 SetProcessAffinityMask(h, mask);
4809 #endif
4811 module_call_init(MODULE_INIT_MACHINE);
4812 machine = find_default_machine();
4813 cpu_model = NULL;
4814 initrd_filename = NULL;
4815 ram_size = 0;
4816 snapshot = 0;
4817 kernel_filename = NULL;
4818 kernel_cmdline = "";
4819 cyls = heads = secs = 0;
4820 translation = BIOS_ATA_TRANSLATION_AUTO;
4822 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4823 virtio_consoles[i] = NULL;
4824 virtio_console_index = 0;
4826 for (i = 0; i < MAX_NODES; i++) {
4827 node_mem[i] = 0;
4828 node_cpumask[i] = 0;
4831 nb_numa_nodes = 0;
4832 nb_nics = 0;
4834 tb_size = 0;
4835 autostart= 1;
4837 optind = 1;
4838 for(;;) {
4839 if (optind >= argc)
4840 break;
4841 r = argv[optind];
4842 if (r[0] != '-') {
4843 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4844 } else {
4845 const QEMUOption *popt;
4847 optind++;
4848 /* Treat --foo the same as -foo. */
4849 if (r[1] == '-')
4850 r++;
4851 popt = qemu_options;
4852 for(;;) {
4853 if (!popt->name) {
4854 fprintf(stderr, "%s: invalid option -- '%s'\n",
4855 argv[0], r);
4856 exit(1);
4858 if (!strcmp(popt->name, r + 1))
4859 break;
4860 popt++;
4862 if (popt->flags & HAS_ARG) {
4863 if (optind >= argc) {
4864 fprintf(stderr, "%s: option '%s' requires an argument\n",
4865 argv[0], r);
4866 exit(1);
4868 optarg = argv[optind++];
4869 } else {
4870 optarg = NULL;
4873 switch(popt->index) {
4874 case QEMU_OPTION_M:
4875 machine = find_machine(optarg);
4876 if (!machine) {
4877 QEMUMachine *m;
4878 printf("Supported machines are:\n");
4879 for(m = first_machine; m != NULL; m = m->next) {
4880 if (m->alias)
4881 printf("%-10s %s (alias of %s)\n",
4882 m->alias, m->desc, m->name);
4883 printf("%-10s %s%s\n",
4884 m->name, m->desc,
4885 m->is_default ? " (default)" : "");
4887 exit(*optarg != '?');
4889 break;
4890 case QEMU_OPTION_cpu:
4891 /* hw initialization will check this */
4892 if (*optarg == '?') {
4893 /* XXX: implement xxx_cpu_list for targets that still miss it */
4894 #if defined(cpu_list)
4895 cpu_list(stdout, &fprintf);
4896 #endif
4897 exit(0);
4898 } else {
4899 cpu_model = optarg;
4901 break;
4902 case QEMU_OPTION_initrd:
4903 initrd_filename = optarg;
4904 break;
4905 case QEMU_OPTION_hda:
4906 if (cyls == 0)
4907 hda_opts = drive_add(optarg, HD_ALIAS, 0);
4908 else
4909 hda_opts = drive_add(optarg, HD_ALIAS
4910 ",cyls=%d,heads=%d,secs=%d%s",
4911 0, cyls, heads, secs,
4912 translation == BIOS_ATA_TRANSLATION_LBA ?
4913 ",trans=lba" :
4914 translation == BIOS_ATA_TRANSLATION_NONE ?
4915 ",trans=none" : "");
4916 break;
4917 case QEMU_OPTION_hdb:
4918 case QEMU_OPTION_hdc:
4919 case QEMU_OPTION_hdd:
4920 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4921 break;
4922 case QEMU_OPTION_drive:
4923 drive_add(NULL, "%s", optarg);
4924 break;
4925 case QEMU_OPTION_set:
4926 if (qemu_set_option(optarg) != 0)
4927 exit(1);
4928 break;
4929 case QEMU_OPTION_global:
4930 if (qemu_global_option(optarg) != 0)
4931 exit(1);
4932 break;
4933 case QEMU_OPTION_mtdblock:
4934 drive_add(optarg, MTD_ALIAS);
4935 break;
4936 case QEMU_OPTION_sd:
4937 drive_add(optarg, SD_ALIAS);
4938 break;
4939 case QEMU_OPTION_pflash:
4940 drive_add(optarg, PFLASH_ALIAS);
4941 break;
4942 case QEMU_OPTION_snapshot:
4943 snapshot = 1;
4944 break;
4945 case QEMU_OPTION_hdachs:
4947 const char *p;
4948 p = optarg;
4949 cyls = strtol(p, (char **)&p, 0);
4950 if (cyls < 1 || cyls > 16383)
4951 goto chs_fail;
4952 if (*p != ',')
4953 goto chs_fail;
4954 p++;
4955 heads = strtol(p, (char **)&p, 0);
4956 if (heads < 1 || heads > 16)
4957 goto chs_fail;
4958 if (*p != ',')
4959 goto chs_fail;
4960 p++;
4961 secs = strtol(p, (char **)&p, 0);
4962 if (secs < 1 || secs > 63)
4963 goto chs_fail;
4964 if (*p == ',') {
4965 p++;
4966 if (!strcmp(p, "none"))
4967 translation = BIOS_ATA_TRANSLATION_NONE;
4968 else if (!strcmp(p, "lba"))
4969 translation = BIOS_ATA_TRANSLATION_LBA;
4970 else if (!strcmp(p, "auto"))
4971 translation = BIOS_ATA_TRANSLATION_AUTO;
4972 else
4973 goto chs_fail;
4974 } else if (*p != '\0') {
4975 chs_fail:
4976 fprintf(stderr, "qemu: invalid physical CHS format\n");
4977 exit(1);
4979 if (hda_opts != NULL) {
4980 char num[16];
4981 snprintf(num, sizeof(num), "%d", cyls);
4982 qemu_opt_set(hda_opts, "cyls", num);
4983 snprintf(num, sizeof(num), "%d", heads);
4984 qemu_opt_set(hda_opts, "heads", num);
4985 snprintf(num, sizeof(num), "%d", secs);
4986 qemu_opt_set(hda_opts, "secs", num);
4987 if (translation == BIOS_ATA_TRANSLATION_LBA)
4988 qemu_opt_set(hda_opts, "trans", "lba");
4989 if (translation == BIOS_ATA_TRANSLATION_NONE)
4990 qemu_opt_set(hda_opts, "trans", "none");
4993 break;
4994 case QEMU_OPTION_numa:
4995 if (nb_numa_nodes >= MAX_NODES) {
4996 fprintf(stderr, "qemu: too many NUMA nodes\n");
4997 exit(1);
4999 numa_add(optarg);
5000 break;
5001 case QEMU_OPTION_nographic:
5002 display_type = DT_NOGRAPHIC;
5003 break;
5004 #ifdef CONFIG_CURSES
5005 case QEMU_OPTION_curses:
5006 display_type = DT_CURSES;
5007 break;
5008 #endif
5009 case QEMU_OPTION_portrait:
5010 graphic_rotate = 1;
5011 break;
5012 case QEMU_OPTION_kernel:
5013 kernel_filename = optarg;
5014 break;
5015 case QEMU_OPTION_append:
5016 kernel_cmdline = optarg;
5017 break;
5018 case QEMU_OPTION_cdrom:
5019 drive_add(optarg, CDROM_ALIAS);
5020 break;
5021 case QEMU_OPTION_boot:
5023 static const char * const params[] = {
5024 "order", "once", "menu", NULL
5026 char buf[sizeof(boot_devices)];
5027 char *standard_boot_devices;
5028 int legacy = 0;
5030 if (!strchr(optarg, '=')) {
5031 legacy = 1;
5032 pstrcpy(buf, sizeof(buf), optarg);
5033 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5034 fprintf(stderr,
5035 "qemu: unknown boot parameter '%s' in '%s'\n",
5036 buf, optarg);
5037 exit(1);
5040 if (legacy ||
5041 get_param_value(buf, sizeof(buf), "order", optarg)) {
5042 boot_devices_bitmap = parse_bootdevices(buf);
5043 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5045 if (!legacy) {
5046 if (get_param_value(buf, sizeof(buf),
5047 "once", optarg)) {
5048 boot_devices_bitmap |= parse_bootdevices(buf);
5049 standard_boot_devices = qemu_strdup(boot_devices);
5050 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5051 qemu_register_reset(restore_boot_devices,
5052 standard_boot_devices);
5054 if (get_param_value(buf, sizeof(buf),
5055 "menu", optarg)) {
5056 if (!strcmp(buf, "on")) {
5057 boot_menu = 1;
5058 } else if (!strcmp(buf, "off")) {
5059 boot_menu = 0;
5060 } else {
5061 fprintf(stderr,
5062 "qemu: invalid option value '%s'\n",
5063 buf);
5064 exit(1);
5069 break;
5070 case QEMU_OPTION_fda:
5071 case QEMU_OPTION_fdb:
5072 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5073 break;
5074 #ifdef TARGET_I386
5075 case QEMU_OPTION_no_fd_bootchk:
5076 fd_bootchk = 0;
5077 break;
5078 #endif
5079 case QEMU_OPTION_netdev:
5080 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
5081 exit(1);
5083 break;
5084 case QEMU_OPTION_net:
5085 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
5086 exit(1);
5088 break;
5089 #ifdef CONFIG_SLIRP
5090 case QEMU_OPTION_tftp:
5091 legacy_tftp_prefix = optarg;
5092 break;
5093 case QEMU_OPTION_bootp:
5094 legacy_bootp_filename = optarg;
5095 break;
5096 #ifndef _WIN32
5097 case QEMU_OPTION_smb:
5098 if (net_slirp_smb(optarg) < 0)
5099 exit(1);
5100 break;
5101 #endif
5102 case QEMU_OPTION_redir:
5103 if (net_slirp_redir(optarg) < 0)
5104 exit(1);
5105 break;
5106 #endif
5107 case QEMU_OPTION_bt:
5108 add_device_config(DEV_BT, optarg);
5109 break;
5110 #ifdef HAS_AUDIO
5111 case QEMU_OPTION_audio_help:
5112 AUD_help ();
5113 exit (0);
5114 break;
5115 case QEMU_OPTION_soundhw:
5116 select_soundhw (optarg);
5117 break;
5118 #endif
5119 case QEMU_OPTION_h:
5120 help(0);
5121 break;
5122 case QEMU_OPTION_version:
5123 version();
5124 exit(0);
5125 break;
5126 case QEMU_OPTION_m: {
5127 uint64_t value;
5128 char *ptr;
5130 value = strtoul(optarg, &ptr, 10);
5131 switch (*ptr) {
5132 case 0: case 'M': case 'm':
5133 value <<= 20;
5134 break;
5135 case 'G': case 'g':
5136 value <<= 30;
5137 break;
5138 default:
5139 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5140 exit(1);
5143 /* On 32-bit hosts, QEMU is limited by virtual address space */
5144 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5145 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5146 exit(1);
5148 if (value != (uint64_t)(ram_addr_t)value) {
5149 fprintf(stderr, "qemu: ram size too large\n");
5150 exit(1);
5152 ram_size = value;
5153 break;
5155 case QEMU_OPTION_d:
5157 int mask;
5158 const CPULogItem *item;
5160 mask = cpu_str_to_log_mask(optarg);
5161 if (!mask) {
5162 printf("Log items (comma separated):\n");
5163 for(item = cpu_log_items; item->mask != 0; item++) {
5164 printf("%-10s %s\n", item->name, item->help);
5166 exit(1);
5168 cpu_set_log(mask);
5170 break;
5171 case QEMU_OPTION_s:
5172 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5173 break;
5174 case QEMU_OPTION_gdb:
5175 gdbstub_dev = optarg;
5176 break;
5177 case QEMU_OPTION_L:
5178 data_dir = optarg;
5179 break;
5180 case QEMU_OPTION_bios:
5181 bios_name = optarg;
5182 break;
5183 case QEMU_OPTION_singlestep:
5184 singlestep = 1;
5185 break;
5186 case QEMU_OPTION_S:
5187 autostart = 0;
5188 break;
5189 case QEMU_OPTION_k:
5190 keyboard_layout = optarg;
5191 break;
5192 case QEMU_OPTION_localtime:
5193 rtc_utc = 0;
5194 break;
5195 case QEMU_OPTION_vga:
5196 select_vgahw (optarg);
5197 break;
5198 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5199 case QEMU_OPTION_g:
5201 const char *p;
5202 int w, h, depth;
5203 p = optarg;
5204 w = strtol(p, (char **)&p, 10);
5205 if (w <= 0) {
5206 graphic_error:
5207 fprintf(stderr, "qemu: invalid resolution or depth\n");
5208 exit(1);
5210 if (*p != 'x')
5211 goto graphic_error;
5212 p++;
5213 h = strtol(p, (char **)&p, 10);
5214 if (h <= 0)
5215 goto graphic_error;
5216 if (*p == 'x') {
5217 p++;
5218 depth = strtol(p, (char **)&p, 10);
5219 if (depth != 8 && depth != 15 && depth != 16 &&
5220 depth != 24 && depth != 32)
5221 goto graphic_error;
5222 } else if (*p == '\0') {
5223 depth = graphic_depth;
5224 } else {
5225 goto graphic_error;
5228 graphic_width = w;
5229 graphic_height = h;
5230 graphic_depth = depth;
5232 break;
5233 #endif
5234 case QEMU_OPTION_echr:
5236 char *r;
5237 term_escape_char = strtol(optarg, &r, 0);
5238 if (r == optarg)
5239 printf("Bad argument to echr\n");
5240 break;
5242 case QEMU_OPTION_monitor:
5243 add_device_config(DEV_MONITOR, optarg);
5244 default_monitor = 0;
5245 break;
5246 case QEMU_OPTION_chardev:
5247 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5248 if (!opts) {
5249 fprintf(stderr, "parse error: %s\n", optarg);
5250 exit(1);
5252 break;
5253 case QEMU_OPTION_serial:
5254 add_device_config(DEV_SERIAL, optarg);
5255 default_serial = 0;
5256 break;
5257 case QEMU_OPTION_watchdog:
5258 if (watchdog) {
5259 fprintf(stderr,
5260 "qemu: only one watchdog option may be given\n");
5261 return 1;
5263 watchdog = optarg;
5264 break;
5265 case QEMU_OPTION_watchdog_action:
5266 if (select_watchdog_action(optarg) == -1) {
5267 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5268 exit(1);
5270 break;
5271 case QEMU_OPTION_virtiocon:
5272 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5273 fprintf(stderr, "qemu: too many virtio consoles\n");
5274 exit(1);
5276 virtio_consoles[virtio_console_index] = optarg;
5277 virtio_console_index++;
5278 break;
5279 case QEMU_OPTION_parallel:
5280 add_device_config(DEV_PARALLEL, optarg);
5281 default_parallel = 0;
5282 break;
5283 case QEMU_OPTION_loadvm:
5284 loadvm = optarg;
5285 break;
5286 case QEMU_OPTION_full_screen:
5287 full_screen = 1;
5288 break;
5289 #ifdef CONFIG_SDL
5290 case QEMU_OPTION_no_frame:
5291 no_frame = 1;
5292 break;
5293 case QEMU_OPTION_alt_grab:
5294 alt_grab = 1;
5295 break;
5296 case QEMU_OPTION_ctrl_grab:
5297 ctrl_grab = 1;
5298 break;
5299 case QEMU_OPTION_no_quit:
5300 no_quit = 1;
5301 break;
5302 case QEMU_OPTION_sdl:
5303 display_type = DT_SDL;
5304 break;
5305 #endif
5306 case QEMU_OPTION_pidfile:
5307 pid_file = optarg;
5308 break;
5309 #ifdef TARGET_I386
5310 case QEMU_OPTION_win2k_hack:
5311 win2k_install_hack = 1;
5312 break;
5313 case QEMU_OPTION_rtc_td_hack:
5314 rtc_td_hack = 1;
5315 break;
5316 case QEMU_OPTION_acpitable:
5317 if(acpi_table_add(optarg) < 0) {
5318 fprintf(stderr, "Wrong acpi table provided\n");
5319 exit(1);
5321 break;
5322 case QEMU_OPTION_smbios:
5323 if(smbios_entry_add(optarg) < 0) {
5324 fprintf(stderr, "Wrong smbios provided\n");
5325 exit(1);
5327 break;
5328 #endif
5329 #ifdef CONFIG_KVM
5330 case QEMU_OPTION_enable_kvm:
5331 kvm_allowed = 1;
5332 break;
5333 #endif
5334 case QEMU_OPTION_usb:
5335 usb_enabled = 1;
5336 break;
5337 case QEMU_OPTION_usbdevice:
5338 usb_enabled = 1;
5339 add_device_config(DEV_USB, optarg);
5340 break;
5341 case QEMU_OPTION_device:
5342 if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5343 exit(1);
5345 break;
5346 case QEMU_OPTION_smp:
5347 smp_parse(optarg);
5348 if (smp_cpus < 1) {
5349 fprintf(stderr, "Invalid number of CPUs\n");
5350 exit(1);
5352 if (max_cpus < smp_cpus) {
5353 fprintf(stderr, "maxcpus must be equal to or greater than "
5354 "smp\n");
5355 exit(1);
5357 if (max_cpus > 255) {
5358 fprintf(stderr, "Unsupported number of maxcpus\n");
5359 exit(1);
5361 break;
5362 case QEMU_OPTION_vnc:
5363 display_type = DT_VNC;
5364 vnc_display = optarg;
5365 break;
5366 #ifdef TARGET_I386
5367 case QEMU_OPTION_no_acpi:
5368 acpi_enabled = 0;
5369 break;
5370 case QEMU_OPTION_no_hpet:
5371 no_hpet = 1;
5372 break;
5373 case QEMU_OPTION_balloon:
5374 if (balloon_parse(optarg) < 0) {
5375 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5376 exit(1);
5378 break;
5379 #endif
5380 case QEMU_OPTION_no_reboot:
5381 no_reboot = 1;
5382 break;
5383 case QEMU_OPTION_no_shutdown:
5384 no_shutdown = 1;
5385 break;
5386 case QEMU_OPTION_show_cursor:
5387 cursor_hide = 0;
5388 break;
5389 case QEMU_OPTION_uuid:
5390 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5391 fprintf(stderr, "Fail to parse UUID string."
5392 " Wrong format.\n");
5393 exit(1);
5395 break;
5396 #ifndef _WIN32
5397 case QEMU_OPTION_daemonize:
5398 daemonize = 1;
5399 break;
5400 #endif
5401 case QEMU_OPTION_option_rom:
5402 if (nb_option_roms >= MAX_OPTION_ROMS) {
5403 fprintf(stderr, "Too many option ROMs\n");
5404 exit(1);
5406 option_rom[nb_option_roms] = optarg;
5407 nb_option_roms++;
5408 break;
5409 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5410 case QEMU_OPTION_semihosting:
5411 semihosting_enabled = 1;
5412 break;
5413 #endif
5414 case QEMU_OPTION_name:
5415 qemu_name = qemu_strdup(optarg);
5417 char *p = strchr(qemu_name, ',');
5418 if (p != NULL) {
5419 *p++ = 0;
5420 if (strncmp(p, "process=", 8)) {
5421 fprintf(stderr, "Unknown subargument %s to -name", p);
5422 exit(1);
5424 p += 8;
5425 set_proc_name(p);
5428 break;
5429 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5430 case QEMU_OPTION_prom_env:
5431 if (nb_prom_envs >= MAX_PROM_ENVS) {
5432 fprintf(stderr, "Too many prom variables\n");
5433 exit(1);
5435 prom_envs[nb_prom_envs] = optarg;
5436 nb_prom_envs++;
5437 break;
5438 #endif
5439 #ifdef TARGET_ARM
5440 case QEMU_OPTION_old_param:
5441 old_param = 1;
5442 break;
5443 #endif
5444 case QEMU_OPTION_clock:
5445 configure_alarms(optarg);
5446 break;
5447 case QEMU_OPTION_startdate:
5448 configure_rtc_date_offset(optarg, 1);
5449 break;
5450 case QEMU_OPTION_rtc:
5451 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5452 if (!opts) {
5453 fprintf(stderr, "parse error: %s\n", optarg);
5454 exit(1);
5456 configure_rtc(opts);
5457 break;
5458 case QEMU_OPTION_tb_size:
5459 tb_size = strtol(optarg, NULL, 0);
5460 if (tb_size < 0)
5461 tb_size = 0;
5462 break;
5463 case QEMU_OPTION_icount:
5464 use_icount = 1;
5465 if (strcmp(optarg, "auto") == 0) {
5466 icount_time_shift = -1;
5467 } else {
5468 icount_time_shift = strtol(optarg, NULL, 0);
5470 break;
5471 case QEMU_OPTION_incoming:
5472 incoming = optarg;
5473 break;
5474 case QEMU_OPTION_nodefaults:
5475 default_serial = 0;
5476 default_parallel = 0;
5477 default_monitor = 0;
5478 default_vga = 0;
5479 default_net = 0;
5480 break;
5481 #ifndef _WIN32
5482 case QEMU_OPTION_chroot:
5483 chroot_dir = optarg;
5484 break;
5485 case QEMU_OPTION_runas:
5486 run_as = optarg;
5487 break;
5488 #endif
5489 #ifdef CONFIG_XEN
5490 case QEMU_OPTION_xen_domid:
5491 xen_domid = atoi(optarg);
5492 break;
5493 case QEMU_OPTION_xen_create:
5494 xen_mode = XEN_CREATE;
5495 break;
5496 case QEMU_OPTION_xen_attach:
5497 xen_mode = XEN_ATTACH;
5498 break;
5499 #endif
5500 case QEMU_OPTION_readconfig:
5502 FILE *fp;
5503 fp = fopen(optarg, "r");
5504 if (fp == NULL) {
5505 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5506 exit(1);
5508 if (qemu_config_parse(fp) != 0) {
5509 exit(1);
5511 fclose(fp);
5512 break;
5514 case QEMU_OPTION_writeconfig:
5516 FILE *fp;
5517 if (strcmp(optarg, "-") == 0) {
5518 fp = stdout;
5519 } else {
5520 fp = fopen(optarg, "w");
5521 if (fp == NULL) {
5522 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5523 exit(1);
5526 qemu_config_write(fp);
5527 fclose(fp);
5528 break;
5534 /* If no data_dir is specified then try to find it relative to the
5535 executable path. */
5536 if (!data_dir) {
5537 data_dir = find_datadir(argv[0]);
5539 /* If all else fails use the install patch specified when building. */
5540 if (!data_dir) {
5541 data_dir = CONFIG_QEMU_SHAREDIR;
5545 * Default to max_cpus = smp_cpus, in case the user doesn't
5546 * specify a max_cpus value.
5548 if (!max_cpus)
5549 max_cpus = smp_cpus;
5551 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5552 if (smp_cpus > machine->max_cpus) {
5553 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5554 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5555 machine->max_cpus);
5556 exit(1);
5559 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5561 if (display_type == DT_NOGRAPHIC) {
5562 if (default_parallel)
5563 add_device_config(DEV_PARALLEL, "null");
5564 if (default_serial && default_monitor) {
5565 add_device_config(DEV_SERIAL, "mon:stdio");
5566 } else {
5567 if (default_serial)
5568 add_device_config(DEV_SERIAL, "stdio");
5569 if (default_monitor)
5570 add_device_config(DEV_MONITOR, "stdio");
5572 } else {
5573 if (default_serial)
5574 add_device_config(DEV_SERIAL, "vc:80Cx24C");
5575 if (default_parallel)
5576 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
5577 if (default_monitor)
5578 add_device_config(DEV_MONITOR, "vc:80Cx24C");
5580 if (default_vga)
5581 vga_interface_type = VGA_CIRRUS;
5583 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5584 exit(1);
5586 #ifndef _WIN32
5587 if (daemonize) {
5588 pid_t pid;
5590 if (pipe(fds) == -1)
5591 exit(1);
5593 pid = fork();
5594 if (pid > 0) {
5595 uint8_t status;
5596 ssize_t len;
5598 close(fds[1]);
5600 again:
5601 len = read(fds[0], &status, 1);
5602 if (len == -1 && (errno == EINTR))
5603 goto again;
5605 if (len != 1)
5606 exit(1);
5607 else if (status == 1) {
5608 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5609 exit(1);
5610 } else
5611 exit(0);
5612 } else if (pid < 0)
5613 exit(1);
5615 close(fds[0]);
5616 qemu_set_cloexec(fds[1]);
5618 setsid();
5620 pid = fork();
5621 if (pid > 0)
5622 exit(0);
5623 else if (pid < 0)
5624 exit(1);
5626 umask(027);
5628 signal(SIGTSTP, SIG_IGN);
5629 signal(SIGTTOU, SIG_IGN);
5630 signal(SIGTTIN, SIG_IGN);
5633 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5634 if (daemonize) {
5635 uint8_t status = 1;
5636 write(fds[1], &status, 1);
5637 } else
5638 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5639 exit(1);
5641 #endif
5643 if (kvm_enabled()) {
5644 int ret;
5646 ret = kvm_init(smp_cpus);
5647 if (ret < 0) {
5648 fprintf(stderr, "failed to initialize KVM\n");
5649 exit(1);
5653 if (qemu_init_main_loop()) {
5654 fprintf(stderr, "qemu_init_main_loop failed\n");
5655 exit(1);
5657 linux_boot = (kernel_filename != NULL);
5659 if (!linux_boot && *kernel_cmdline != '\0') {
5660 fprintf(stderr, "-append only allowed with -kernel option\n");
5661 exit(1);
5664 if (!linux_boot && initrd_filename != NULL) {
5665 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5666 exit(1);
5669 #ifndef _WIN32
5670 /* Win32 doesn't support line-buffering and requires size >= 2 */
5671 setvbuf(stdout, NULL, _IOLBF, 0);
5672 #endif
5674 if (init_timer_alarm() < 0) {
5675 fprintf(stderr, "could not initialize alarm timer\n");
5676 exit(1);
5678 if (use_icount && icount_time_shift < 0) {
5679 use_icount = 2;
5680 /* 125MIPS seems a reasonable initial guess at the guest speed.
5681 It will be corrected fairly quickly anyway. */
5682 icount_time_shift = 3;
5683 init_icount_adjust();
5686 #ifdef _WIN32
5687 socket_init();
5688 #endif
5690 if (net_init_clients() < 0) {
5691 exit(1);
5694 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5695 net_set_boot_mask(net_boot);
5697 /* init the bluetooth world */
5698 if (foreach_device_config(DEV_BT, bt_parse))
5699 exit(1);
5701 /* init the memory */
5702 if (ram_size == 0)
5703 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5705 /* init the dynamic translator */
5706 cpu_exec_init_all(tb_size * 1024 * 1024);
5708 bdrv_init_with_whitelist();
5710 blk_mig_init();
5712 /* we always create the cdrom drive, even if no disk is there */
5713 drive_add(NULL, CDROM_ALIAS);
5715 /* we always create at least one floppy */
5716 drive_add(NULL, FD_ALIAS, 0);
5718 /* we always create one sd slot, even if no card is in it */
5719 drive_add(NULL, SD_ALIAS);
5721 /* open the virtual block devices */
5722 if (snapshot)
5723 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5724 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5725 exit(1);
5727 vmstate_register(0, &vmstate_timers ,&timers_state);
5728 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
5729 ram_load, NULL);
5731 if (nb_numa_nodes > 0) {
5732 int i;
5734 if (nb_numa_nodes > smp_cpus) {
5735 nb_numa_nodes = smp_cpus;
5738 /* If no memory size if given for any node, assume the default case
5739 * and distribute the available memory equally across all nodes
5741 for (i = 0; i < nb_numa_nodes; i++) {
5742 if (node_mem[i] != 0)
5743 break;
5745 if (i == nb_numa_nodes) {
5746 uint64_t usedmem = 0;
5748 /* On Linux, the each node's border has to be 8MB aligned,
5749 * the final node gets the rest.
5751 for (i = 0; i < nb_numa_nodes - 1; i++) {
5752 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5753 usedmem += node_mem[i];
5755 node_mem[i] = ram_size - usedmem;
5758 for (i = 0; i < nb_numa_nodes; i++) {
5759 if (node_cpumask[i] != 0)
5760 break;
5762 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5763 * must cope with this anyway, because there are BIOSes out there in
5764 * real machines which also use this scheme.
5766 if (i == nb_numa_nodes) {
5767 for (i = 0; i < smp_cpus; i++) {
5768 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5773 if (foreach_device_config(DEV_MONITOR, monitor_parse) < 0)
5774 exit(1);
5775 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
5776 exit(1);
5777 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
5778 exit(1);
5780 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5781 const char *devname = virtio_consoles[i];
5782 if (devname && strcmp(devname, "none")) {
5783 char label[32];
5784 snprintf(label, sizeof(label), "virtcon%d", i);
5785 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5786 if (!virtcon_hds[i]) {
5787 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
5788 devname, strerror(errno));
5789 exit(1);
5794 module_call_init(MODULE_INIT_DEVICE);
5796 if (watchdog) {
5797 i = select_watchdog(watchdog);
5798 if (i > 0)
5799 exit (i == 1 ? 1 : 0);
5802 if (machine->compat_props) {
5803 qdev_prop_register_global_list(machine->compat_props);
5805 qemu_add_globals();
5807 machine->init(ram_size, boot_devices,
5808 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5811 #ifndef _WIN32
5812 /* must be after terminal init, SDL library changes signal handlers */
5813 sighandler_setup();
5814 #endif
5816 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5817 for (i = 0; i < nb_numa_nodes; i++) {
5818 if (node_cpumask[i] & (1 << env->cpu_index)) {
5819 env->numa_node = i;
5824 current_machine = machine;
5826 /* init USB devices */
5827 if (usb_enabled) {
5828 if (foreach_device_config(DEV_USB, usb_parse) < 0)
5829 exit(1);
5832 /* init generic devices */
5833 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5834 exit(1);
5836 if (!display_state)
5837 dumb_display_init();
5838 /* just use the first displaystate for the moment */
5839 ds = display_state;
5841 if (display_type == DT_DEFAULT) {
5842 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5843 display_type = DT_SDL;
5844 #else
5845 display_type = DT_VNC;
5846 vnc_display = "localhost:0,to=99";
5847 show_vnc_port = 1;
5848 #endif
5852 switch (display_type) {
5853 case DT_NOGRAPHIC:
5854 break;
5855 #if defined(CONFIG_CURSES)
5856 case DT_CURSES:
5857 curses_display_init(ds, full_screen);
5858 break;
5859 #endif
5860 #if defined(CONFIG_SDL)
5861 case DT_SDL:
5862 sdl_display_init(ds, full_screen, no_frame);
5863 break;
5864 #elif defined(CONFIG_COCOA)
5865 case DT_SDL:
5866 cocoa_display_init(ds, full_screen);
5867 break;
5868 #endif
5869 case DT_VNC:
5870 vnc_display_init(ds);
5871 if (vnc_display_open(ds, vnc_display) < 0)
5872 exit(1);
5874 if (show_vnc_port) {
5875 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5877 break;
5878 default:
5879 break;
5881 dpy_resize(ds);
5883 dcl = ds->listeners;
5884 while (dcl != NULL) {
5885 if (dcl->dpy_refresh != NULL) {
5886 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5887 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5889 dcl = dcl->next;
5892 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5893 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5894 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5897 text_consoles_set_display(display_state);
5899 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5900 if (monitor_hds[i]) {
5901 monitor_init(monitor_hds[i],
5902 MONITOR_USE_READLINE |
5903 ((i == 0) ? MONITOR_IS_DEFAULT : 0));
5907 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5908 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5909 gdbstub_dev);
5910 exit(1);
5913 qdev_machine_creation_done();
5915 rom_load_all();
5917 qemu_system_reset();
5918 if (loadvm) {
5919 if (load_vmstate(cur_mon, loadvm) < 0) {
5920 autostart = 0;
5924 if (incoming) {
5925 qemu_start_incoming_migration(incoming);
5926 } else if (autostart) {
5927 vm_start();
5930 #ifndef _WIN32
5931 if (daemonize) {
5932 uint8_t status = 0;
5933 ssize_t len;
5935 again1:
5936 len = write(fds[1], &status, 1);
5937 if (len == -1 && (errno == EINTR))
5938 goto again1;
5940 if (len != 1)
5941 exit(1);
5943 chdir("/");
5944 TFR(fd = qemu_open("/dev/null", O_RDWR));
5945 if (fd == -1)
5946 exit(1);
5949 if (run_as) {
5950 pwd = getpwnam(run_as);
5951 if (!pwd) {
5952 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5953 exit(1);
5957 if (chroot_dir) {
5958 if (chroot(chroot_dir) < 0) {
5959 fprintf(stderr, "chroot failed\n");
5960 exit(1);
5962 chdir("/");
5965 if (run_as) {
5966 if (setgid(pwd->pw_gid) < 0) {
5967 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5968 exit(1);
5970 if (setuid(pwd->pw_uid) < 0) {
5971 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5972 exit(1);
5974 if (setuid(0) != -1) {
5975 fprintf(stderr, "Dropping privileges failed\n");
5976 exit(1);
5980 if (daemonize) {
5981 dup2(fd, 0);
5982 dup2(fd, 1);
5983 dup2(fd, 2);
5985 close(fd);
5987 #endif
5989 main_loop();
5990 quit_timers();
5991 net_cleanup();
5993 return 0;