add new -mon switch
[qemu/kraxel.git] / vl.c
blobd90975fedd0e48be7932b460b9bca658764b6456
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 static const char *data_dir;
176 const char *bios_name = NULL;
177 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
178 to store the VM snapshots */
179 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
180 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
181 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
182 static DisplayState *display_state;
183 DisplayType display_type = DT_DEFAULT;
184 const char* keyboard_layout = NULL;
185 ram_addr_t ram_size;
186 int nb_nics;
187 NICInfo nd_table[MAX_NICS];
188 int vm_running;
189 int autostart;
190 static int rtc_utc = 1;
191 static int rtc_date_offset = -1; /* -1 means no change */
192 QEMUClock *rtc_clock;
193 int vga_interface_type = VGA_NONE;
194 #ifdef TARGET_SPARC
195 int graphic_width = 1024;
196 int graphic_height = 768;
197 int graphic_depth = 8;
198 #else
199 int graphic_width = 800;
200 int graphic_height = 600;
201 int graphic_depth = 15;
202 #endif
203 static int full_screen = 0;
204 #ifdef CONFIG_SDL
205 static int no_frame = 0;
206 #endif
207 int no_quit = 0;
208 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
209 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
210 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
211 #ifdef TARGET_I386
212 int win2k_install_hack = 0;
213 int rtc_td_hack = 0;
214 #endif
215 int usb_enabled = 0;
216 int singlestep = 0;
217 int smp_cpus = 1;
218 int max_cpus = 0;
219 int smp_cores = 1;
220 int smp_threads = 1;
221 const char *vnc_display;
222 int acpi_enabled = 1;
223 int no_hpet = 0;
224 int fd_bootchk = 1;
225 int no_reboot = 0;
226 int no_shutdown = 0;
227 int cursor_hide = 1;
228 int graphic_rotate = 0;
229 uint8_t irq0override = 1;
230 #ifndef _WIN32
231 int daemonize = 0;
232 #endif
233 const char *watchdog;
234 const char *option_rom[MAX_OPTION_ROMS];
235 int nb_option_roms;
236 int semihosting_enabled = 0;
237 #ifdef TARGET_ARM
238 int old_param = 0;
239 #endif
240 const char *qemu_name;
241 int alt_grab = 0;
242 int ctrl_grab = 0;
243 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
244 unsigned int nb_prom_envs = 0;
245 const char *prom_envs[MAX_PROM_ENVS];
246 #endif
247 int boot_menu;
249 int nb_numa_nodes;
250 uint64_t node_mem[MAX_NODES];
251 uint64_t node_cpumask[MAX_NODES];
253 static CPUState *cur_cpu;
254 static CPUState *next_cpu;
255 static int timer_alarm_pending = 1;
256 /* Conversion factor from emulated instructions to virtual clock ticks. */
257 static int icount_time_shift;
258 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
259 #define MAX_ICOUNT_SHIFT 10
260 /* Compensate for varying guest execution speed. */
261 static int64_t qemu_icount_bias;
262 static QEMUTimer *icount_rt_timer;
263 static QEMUTimer *icount_vm_timer;
264 static QEMUTimer *nographic_timer;
266 uint8_t qemu_uuid[16];
268 static QEMUBootSetHandler *boot_set_handler;
269 static void *boot_set_opaque;
271 static int default_serial = 1;
272 static int default_parallel = 1;
273 static int default_monitor = 1;
274 static int default_vga = 1;
275 static int default_drive = 1;
277 static struct {
278 const char *driver;
279 int *flag;
280 } default_list[] = {
281 { .driver = "isa-serial", .flag = &default_serial },
282 { .driver = "isa-parallel", .flag = &default_parallel },
283 { .driver = "VGA", .flag = &default_vga },
284 { .driver = "Cirrus VGA", .flag = &default_vga },
285 { .driver = "QEMUware SVGA", .flag = &default_vga },
288 static int default_driver_check(QemuOpts *opts, void *opaque)
290 const char *driver = qemu_opt_get(opts, "driver");
291 int i;
293 if (!driver)
294 return 0;
295 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
296 if (strcmp(default_list[i].driver, driver) != 0)
297 continue;
298 *(default_list[i].flag) = 0;
300 return 0;
303 /***********************************************************/
304 /* x86 ISA bus support */
306 target_phys_addr_t isa_mem_base = 0;
307 PicState2 *isa_pic;
309 /***********************************************************/
310 void hw_error(const char *fmt, ...)
312 va_list ap;
313 CPUState *env;
315 va_start(ap, fmt);
316 fprintf(stderr, "qemu: hardware error: ");
317 vfprintf(stderr, fmt, ap);
318 fprintf(stderr, "\n");
319 for(env = first_cpu; env != NULL; env = env->next_cpu) {
320 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
321 #ifdef TARGET_I386
322 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
323 #else
324 cpu_dump_state(env, stderr, fprintf, 0);
325 #endif
327 va_end(ap);
328 abort();
331 static void set_proc_name(const char *s)
333 #if defined(__linux__) && defined(PR_SET_NAME)
334 char name[16];
335 if (!s)
336 return;
337 name[sizeof(name) - 1] = 0;
338 strncpy(name, s, sizeof(name));
339 /* Could rewrite argv[0] too, but that's a bit more complicated.
340 This simple way is enough for `top'. */
341 prctl(PR_SET_NAME, name);
342 #endif
345 /***************/
346 /* ballooning */
348 static QEMUBalloonEvent *qemu_balloon_event;
349 void *qemu_balloon_event_opaque;
351 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
353 qemu_balloon_event = func;
354 qemu_balloon_event_opaque = opaque;
357 void qemu_balloon(ram_addr_t target)
359 if (qemu_balloon_event)
360 qemu_balloon_event(qemu_balloon_event_opaque, target);
363 ram_addr_t qemu_balloon_status(void)
365 if (qemu_balloon_event)
366 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
367 return 0;
370 /***********************************************************/
371 /* keyboard/mouse */
373 static QEMUPutKBDEvent *qemu_put_kbd_event;
374 static void *qemu_put_kbd_event_opaque;
375 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
376 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
378 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
380 qemu_put_kbd_event_opaque = opaque;
381 qemu_put_kbd_event = func;
384 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
385 void *opaque, int absolute,
386 const char *name)
388 QEMUPutMouseEntry *s, *cursor;
390 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
392 s->qemu_put_mouse_event = func;
393 s->qemu_put_mouse_event_opaque = opaque;
394 s->qemu_put_mouse_event_absolute = absolute;
395 s->qemu_put_mouse_event_name = qemu_strdup(name);
396 s->next = NULL;
398 if (!qemu_put_mouse_event_head) {
399 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
400 return s;
403 cursor = qemu_put_mouse_event_head;
404 while (cursor->next != NULL)
405 cursor = cursor->next;
407 cursor->next = s;
408 qemu_put_mouse_event_current = s;
410 return s;
413 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
415 QEMUPutMouseEntry *prev = NULL, *cursor;
417 if (!qemu_put_mouse_event_head || entry == NULL)
418 return;
420 cursor = qemu_put_mouse_event_head;
421 while (cursor != NULL && cursor != entry) {
422 prev = cursor;
423 cursor = cursor->next;
426 if (cursor == NULL) // does not exist or list empty
427 return;
428 else if (prev == NULL) { // entry is head
429 qemu_put_mouse_event_head = cursor->next;
430 if (qemu_put_mouse_event_current == entry)
431 qemu_put_mouse_event_current = cursor->next;
432 qemu_free(entry->qemu_put_mouse_event_name);
433 qemu_free(entry);
434 return;
437 prev->next = entry->next;
439 if (qemu_put_mouse_event_current == entry)
440 qemu_put_mouse_event_current = prev;
442 qemu_free(entry->qemu_put_mouse_event_name);
443 qemu_free(entry);
446 void kbd_put_keycode(int keycode)
448 if (qemu_put_kbd_event) {
449 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
453 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
455 QEMUPutMouseEvent *mouse_event;
456 void *mouse_event_opaque;
457 int width;
459 if (!qemu_put_mouse_event_current) {
460 return;
463 mouse_event =
464 qemu_put_mouse_event_current->qemu_put_mouse_event;
465 mouse_event_opaque =
466 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
468 if (mouse_event) {
469 if (graphic_rotate) {
470 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
471 width = 0x7fff;
472 else
473 width = graphic_width - 1;
474 mouse_event(mouse_event_opaque,
475 width - dy, dx, dz, buttons_state);
476 } else
477 mouse_event(mouse_event_opaque,
478 dx, dy, dz, buttons_state);
482 int kbd_mouse_is_absolute(void)
484 if (!qemu_put_mouse_event_current)
485 return 0;
487 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
490 void do_info_mice(Monitor *mon)
492 QEMUPutMouseEntry *cursor;
493 int index = 0;
495 if (!qemu_put_mouse_event_head) {
496 monitor_printf(mon, "No mouse devices connected\n");
497 return;
500 monitor_printf(mon, "Mouse devices available:\n");
501 cursor = qemu_put_mouse_event_head;
502 while (cursor != NULL) {
503 monitor_printf(mon, "%c Mouse #%d: %s\n",
504 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
505 index, cursor->qemu_put_mouse_event_name);
506 index++;
507 cursor = cursor->next;
511 void do_mouse_set(Monitor *mon, const QDict *qdict)
513 QEMUPutMouseEntry *cursor;
514 int i = 0;
515 int index = qdict_get_int(qdict, "index");
517 if (!qemu_put_mouse_event_head) {
518 monitor_printf(mon, "No mouse devices connected\n");
519 return;
522 cursor = qemu_put_mouse_event_head;
523 while (cursor != NULL && index != i) {
524 i++;
525 cursor = cursor->next;
528 if (cursor != NULL)
529 qemu_put_mouse_event_current = cursor;
530 else
531 monitor_printf(mon, "Mouse at given index not found\n");
534 /* compute with 96 bit intermediate result: (a*b)/c */
535 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
537 union {
538 uint64_t ll;
539 struct {
540 #ifdef HOST_WORDS_BIGENDIAN
541 uint32_t high, low;
542 #else
543 uint32_t low, high;
544 #endif
545 } l;
546 } u, res;
547 uint64_t rl, rh;
549 u.ll = a;
550 rl = (uint64_t)u.l.low * (uint64_t)b;
551 rh = (uint64_t)u.l.high * (uint64_t)b;
552 rh += (rl >> 32);
553 res.l.high = rh / c;
554 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
555 return res.ll;
558 /***********************************************************/
559 /* real time host monotonic timer */
561 static int64_t get_clock_realtime(void)
563 struct timeval tv;
565 gettimeofday(&tv, NULL);
566 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
569 #ifdef WIN32
571 static int64_t clock_freq;
573 static void init_get_clock(void)
575 LARGE_INTEGER freq;
576 int ret;
577 ret = QueryPerformanceFrequency(&freq);
578 if (ret == 0) {
579 fprintf(stderr, "Could not calibrate ticks\n");
580 exit(1);
582 clock_freq = freq.QuadPart;
585 static int64_t get_clock(void)
587 LARGE_INTEGER ti;
588 QueryPerformanceCounter(&ti);
589 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
592 #else
594 static int use_rt_clock;
596 static void init_get_clock(void)
598 use_rt_clock = 0;
599 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
600 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
602 struct timespec ts;
603 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
604 use_rt_clock = 1;
607 #endif
610 static int64_t get_clock(void)
612 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
613 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
614 if (use_rt_clock) {
615 struct timespec ts;
616 clock_gettime(CLOCK_MONOTONIC, &ts);
617 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
618 } else
619 #endif
621 /* XXX: using gettimeofday leads to problems if the date
622 changes, so it should be avoided. */
623 return get_clock_realtime();
626 #endif
628 /* Return the virtual CPU time, based on the instruction counter. */
629 static int64_t cpu_get_icount(void)
631 int64_t icount;
632 CPUState *env = cpu_single_env;;
633 icount = qemu_icount;
634 if (env) {
635 if (!can_do_io(env))
636 fprintf(stderr, "Bad clock read\n");
637 icount -= (env->icount_decr.u16.low + env->icount_extra);
639 return qemu_icount_bias + (icount << icount_time_shift);
642 /***********************************************************/
643 /* guest cycle counter */
645 typedef struct TimersState {
646 int64_t cpu_ticks_prev;
647 int64_t cpu_ticks_offset;
648 int64_t cpu_clock_offset;
649 int32_t cpu_ticks_enabled;
650 int64_t dummy;
651 } TimersState;
653 TimersState timers_state;
655 /* return the host CPU cycle counter and handle stop/restart */
656 int64_t cpu_get_ticks(void)
658 if (use_icount) {
659 return cpu_get_icount();
661 if (!timers_state.cpu_ticks_enabled) {
662 return timers_state.cpu_ticks_offset;
663 } else {
664 int64_t ticks;
665 ticks = cpu_get_real_ticks();
666 if (timers_state.cpu_ticks_prev > ticks) {
667 /* Note: non increasing ticks may happen if the host uses
668 software suspend */
669 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
671 timers_state.cpu_ticks_prev = ticks;
672 return ticks + timers_state.cpu_ticks_offset;
676 /* return the host CPU monotonic timer and handle stop/restart */
677 static int64_t cpu_get_clock(void)
679 int64_t ti;
680 if (!timers_state.cpu_ticks_enabled) {
681 return timers_state.cpu_clock_offset;
682 } else {
683 ti = get_clock();
684 return ti + timers_state.cpu_clock_offset;
688 /* enable cpu_get_ticks() */
689 void cpu_enable_ticks(void)
691 if (!timers_state.cpu_ticks_enabled) {
692 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
693 timers_state.cpu_clock_offset -= get_clock();
694 timers_state.cpu_ticks_enabled = 1;
698 /* disable cpu_get_ticks() : the clock is stopped. You must not call
699 cpu_get_ticks() after that. */
700 void cpu_disable_ticks(void)
702 if (timers_state.cpu_ticks_enabled) {
703 timers_state.cpu_ticks_offset = cpu_get_ticks();
704 timers_state.cpu_clock_offset = cpu_get_clock();
705 timers_state.cpu_ticks_enabled = 0;
709 /***********************************************************/
710 /* timers */
712 #define QEMU_CLOCK_REALTIME 0
713 #define QEMU_CLOCK_VIRTUAL 1
714 #define QEMU_CLOCK_HOST 2
716 struct QEMUClock {
717 int type;
718 /* XXX: add frequency */
721 struct QEMUTimer {
722 QEMUClock *clock;
723 int64_t expire_time;
724 QEMUTimerCB *cb;
725 void *opaque;
726 struct QEMUTimer *next;
729 struct qemu_alarm_timer {
730 char const *name;
731 unsigned int flags;
733 int (*start)(struct qemu_alarm_timer *t);
734 void (*stop)(struct qemu_alarm_timer *t);
735 void (*rearm)(struct qemu_alarm_timer *t);
736 void *priv;
739 #define ALARM_FLAG_DYNTICKS 0x1
740 #define ALARM_FLAG_EXPIRED 0x2
742 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
744 return t && (t->flags & ALARM_FLAG_DYNTICKS);
747 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
749 if (!alarm_has_dynticks(t))
750 return;
752 t->rearm(t);
755 /* TODO: MIN_TIMER_REARM_US should be optimized */
756 #define MIN_TIMER_REARM_US 250
758 static struct qemu_alarm_timer *alarm_timer;
760 #ifdef _WIN32
762 struct qemu_alarm_win32 {
763 MMRESULT timerId;
764 unsigned int period;
765 } alarm_win32_data = {0, -1};
767 static int win32_start_timer(struct qemu_alarm_timer *t);
768 static void win32_stop_timer(struct qemu_alarm_timer *t);
769 static void win32_rearm_timer(struct qemu_alarm_timer *t);
771 #else
773 static int unix_start_timer(struct qemu_alarm_timer *t);
774 static void unix_stop_timer(struct qemu_alarm_timer *t);
776 #ifdef __linux__
778 static int dynticks_start_timer(struct qemu_alarm_timer *t);
779 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
780 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
782 static int hpet_start_timer(struct qemu_alarm_timer *t);
783 static void hpet_stop_timer(struct qemu_alarm_timer *t);
785 static int rtc_start_timer(struct qemu_alarm_timer *t);
786 static void rtc_stop_timer(struct qemu_alarm_timer *t);
788 #endif /* __linux__ */
790 #endif /* _WIN32 */
792 /* Correlation between real and virtual time is always going to be
793 fairly approximate, so ignore small variation.
794 When the guest is idle real and virtual time will be aligned in
795 the IO wait loop. */
796 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
798 static void icount_adjust(void)
800 int64_t cur_time;
801 int64_t cur_icount;
802 int64_t delta;
803 static int64_t last_delta;
804 /* If the VM is not running, then do nothing. */
805 if (!vm_running)
806 return;
808 cur_time = cpu_get_clock();
809 cur_icount = qemu_get_clock(vm_clock);
810 delta = cur_icount - cur_time;
811 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
812 if (delta > 0
813 && last_delta + ICOUNT_WOBBLE < delta * 2
814 && icount_time_shift > 0) {
815 /* The guest is getting too far ahead. Slow time down. */
816 icount_time_shift--;
818 if (delta < 0
819 && last_delta - ICOUNT_WOBBLE > delta * 2
820 && icount_time_shift < MAX_ICOUNT_SHIFT) {
821 /* The guest is getting too far behind. Speed time up. */
822 icount_time_shift++;
824 last_delta = delta;
825 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
828 static void icount_adjust_rt(void * opaque)
830 qemu_mod_timer(icount_rt_timer,
831 qemu_get_clock(rt_clock) + 1000);
832 icount_adjust();
835 static void icount_adjust_vm(void * opaque)
837 qemu_mod_timer(icount_vm_timer,
838 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
839 icount_adjust();
842 static void init_icount_adjust(void)
844 /* Have both realtime and virtual time triggers for speed adjustment.
845 The realtime trigger catches emulated time passing too slowly,
846 the virtual time trigger catches emulated time passing too fast.
847 Realtime triggers occur even when idle, so use them less frequently
848 than VM triggers. */
849 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
850 qemu_mod_timer(icount_rt_timer,
851 qemu_get_clock(rt_clock) + 1000);
852 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
853 qemu_mod_timer(icount_vm_timer,
854 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
857 static struct qemu_alarm_timer alarm_timers[] = {
858 #ifndef _WIN32
859 #ifdef __linux__
860 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
861 dynticks_stop_timer, dynticks_rearm_timer, NULL},
862 /* HPET - if available - is preferred */
863 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
864 /* ...otherwise try RTC */
865 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
866 #endif
867 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
868 #else
869 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
870 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
871 {"win32", 0, win32_start_timer,
872 win32_stop_timer, NULL, &alarm_win32_data},
873 #endif
874 {NULL, }
877 static void show_available_alarms(void)
879 int i;
881 printf("Available alarm timers, in order of precedence:\n");
882 for (i = 0; alarm_timers[i].name; i++)
883 printf("%s\n", alarm_timers[i].name);
886 static void configure_alarms(char const *opt)
888 int i;
889 int cur = 0;
890 int count = ARRAY_SIZE(alarm_timers) - 1;
891 char *arg;
892 char *name;
893 struct qemu_alarm_timer tmp;
895 if (!strcmp(opt, "?")) {
896 show_available_alarms();
897 exit(0);
900 arg = qemu_strdup(opt);
902 /* Reorder the array */
903 name = strtok(arg, ",");
904 while (name) {
905 for (i = 0; i < count && alarm_timers[i].name; i++) {
906 if (!strcmp(alarm_timers[i].name, name))
907 break;
910 if (i == count) {
911 fprintf(stderr, "Unknown clock %s\n", name);
912 goto next;
915 if (i < cur)
916 /* Ignore */
917 goto next;
919 /* Swap */
920 tmp = alarm_timers[i];
921 alarm_timers[i] = alarm_timers[cur];
922 alarm_timers[cur] = tmp;
924 cur++;
925 next:
926 name = strtok(NULL, ",");
929 qemu_free(arg);
931 if (cur) {
932 /* Disable remaining timers */
933 for (i = cur; i < count; i++)
934 alarm_timers[i].name = NULL;
935 } else {
936 show_available_alarms();
937 exit(1);
941 #define QEMU_NUM_CLOCKS 3
943 QEMUClock *rt_clock;
944 QEMUClock *vm_clock;
945 QEMUClock *host_clock;
947 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
949 static QEMUClock *qemu_new_clock(int type)
951 QEMUClock *clock;
952 clock = qemu_mallocz(sizeof(QEMUClock));
953 clock->type = type;
954 return clock;
957 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
959 QEMUTimer *ts;
961 ts = qemu_mallocz(sizeof(QEMUTimer));
962 ts->clock = clock;
963 ts->cb = cb;
964 ts->opaque = opaque;
965 return ts;
968 void qemu_free_timer(QEMUTimer *ts)
970 qemu_free(ts);
973 /* stop a timer, but do not dealloc it */
974 void qemu_del_timer(QEMUTimer *ts)
976 QEMUTimer **pt, *t;
978 /* NOTE: this code must be signal safe because
979 qemu_timer_expired() can be called from a signal. */
980 pt = &active_timers[ts->clock->type];
981 for(;;) {
982 t = *pt;
983 if (!t)
984 break;
985 if (t == ts) {
986 *pt = t->next;
987 break;
989 pt = &t->next;
993 /* modify the current timer so that it will be fired when current_time
994 >= expire_time. The corresponding callback will be called. */
995 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
997 QEMUTimer **pt, *t;
999 qemu_del_timer(ts);
1001 /* add the timer in the sorted list */
1002 /* NOTE: this code must be signal safe because
1003 qemu_timer_expired() can be called from a signal. */
1004 pt = &active_timers[ts->clock->type];
1005 for(;;) {
1006 t = *pt;
1007 if (!t)
1008 break;
1009 if (t->expire_time > expire_time)
1010 break;
1011 pt = &t->next;
1013 ts->expire_time = expire_time;
1014 ts->next = *pt;
1015 *pt = ts;
1017 /* Rearm if necessary */
1018 if (pt == &active_timers[ts->clock->type]) {
1019 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1020 qemu_rearm_alarm_timer(alarm_timer);
1022 /* Interrupt execution to force deadline recalculation. */
1023 if (use_icount)
1024 qemu_notify_event();
1028 int qemu_timer_pending(QEMUTimer *ts)
1030 QEMUTimer *t;
1031 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1032 if (t == ts)
1033 return 1;
1035 return 0;
1038 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1040 if (!timer_head)
1041 return 0;
1042 return (timer_head->expire_time <= current_time);
1045 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1047 QEMUTimer *ts;
1049 for(;;) {
1050 ts = *ptimer_head;
1051 if (!ts || ts->expire_time > current_time)
1052 break;
1053 /* remove timer from the list before calling the callback */
1054 *ptimer_head = ts->next;
1055 ts->next = NULL;
1057 /* run the callback (the timer list can be modified) */
1058 ts->cb(ts->opaque);
1062 int64_t qemu_get_clock(QEMUClock *clock)
1064 switch(clock->type) {
1065 case QEMU_CLOCK_REALTIME:
1066 return get_clock() / 1000000;
1067 default:
1068 case QEMU_CLOCK_VIRTUAL:
1069 if (use_icount) {
1070 return cpu_get_icount();
1071 } else {
1072 return cpu_get_clock();
1074 case QEMU_CLOCK_HOST:
1075 return get_clock_realtime();
1079 static void init_clocks(void)
1081 init_get_clock();
1082 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
1083 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
1084 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
1086 rtc_clock = host_clock;
1089 /* save a timer */
1090 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1092 uint64_t expire_time;
1094 if (qemu_timer_pending(ts)) {
1095 expire_time = ts->expire_time;
1096 } else {
1097 expire_time = -1;
1099 qemu_put_be64(f, expire_time);
1102 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1104 uint64_t expire_time;
1106 expire_time = qemu_get_be64(f);
1107 if (expire_time != -1) {
1108 qemu_mod_timer(ts, expire_time);
1109 } else {
1110 qemu_del_timer(ts);
1114 static const VMStateDescription vmstate_timers = {
1115 .name = "timer",
1116 .version_id = 2,
1117 .minimum_version_id = 1,
1118 .minimum_version_id_old = 1,
1119 .fields = (VMStateField []) {
1120 VMSTATE_INT64(cpu_ticks_offset, TimersState),
1121 VMSTATE_INT64(dummy, TimersState),
1122 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1123 VMSTATE_END_OF_LIST()
1127 static void qemu_event_increment(void);
1129 #ifdef _WIN32
1130 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1131 DWORD_PTR dwUser, DWORD_PTR dw1,
1132 DWORD_PTR dw2)
1133 #else
1134 static void host_alarm_handler(int host_signum)
1135 #endif
1137 #if 0
1138 #define DISP_FREQ 1000
1140 static int64_t delta_min = INT64_MAX;
1141 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1142 static int count;
1143 ti = qemu_get_clock(vm_clock);
1144 if (last_clock != 0) {
1145 delta = ti - last_clock;
1146 if (delta < delta_min)
1147 delta_min = delta;
1148 if (delta > delta_max)
1149 delta_max = delta;
1150 delta_cum += delta;
1151 if (++count == DISP_FREQ) {
1152 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1153 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1154 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1155 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1156 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1157 count = 0;
1158 delta_min = INT64_MAX;
1159 delta_max = 0;
1160 delta_cum = 0;
1163 last_clock = ti;
1165 #endif
1166 if (alarm_has_dynticks(alarm_timer) ||
1167 (!use_icount &&
1168 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1169 qemu_get_clock(vm_clock))) ||
1170 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1171 qemu_get_clock(rt_clock)) ||
1172 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1173 qemu_get_clock(host_clock))) {
1174 qemu_event_increment();
1175 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1177 #ifndef CONFIG_IOTHREAD
1178 if (next_cpu) {
1179 /* stop the currently executing cpu because a timer occured */
1180 cpu_exit(next_cpu);
1182 #endif
1183 timer_alarm_pending = 1;
1184 qemu_notify_event();
1188 static int64_t qemu_next_deadline(void)
1190 /* To avoid problems with overflow limit this to 2^32. */
1191 int64_t delta = INT32_MAX;
1193 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1194 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1195 qemu_get_clock(vm_clock);
1197 if (active_timers[QEMU_CLOCK_HOST]) {
1198 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1199 qemu_get_clock(host_clock);
1200 if (hdelta < delta)
1201 delta = hdelta;
1204 if (delta < 0)
1205 delta = 0;
1207 return delta;
1210 #if defined(__linux__)
1211 static uint64_t qemu_next_deadline_dyntick(void)
1213 int64_t delta;
1214 int64_t rtdelta;
1216 if (use_icount)
1217 delta = INT32_MAX;
1218 else
1219 delta = (qemu_next_deadline() + 999) / 1000;
1221 if (active_timers[QEMU_CLOCK_REALTIME]) {
1222 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1223 qemu_get_clock(rt_clock))*1000;
1224 if (rtdelta < delta)
1225 delta = rtdelta;
1228 if (delta < MIN_TIMER_REARM_US)
1229 delta = MIN_TIMER_REARM_US;
1231 return delta;
1233 #endif
1235 #ifndef _WIN32
1237 /* Sets a specific flag */
1238 static int fcntl_setfl(int fd, int flag)
1240 int flags;
1242 flags = fcntl(fd, F_GETFL);
1243 if (flags == -1)
1244 return -errno;
1246 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1247 return -errno;
1249 return 0;
1252 #if defined(__linux__)
1254 #define RTC_FREQ 1024
1256 static void enable_sigio_timer(int fd)
1258 struct sigaction act;
1260 /* timer signal */
1261 sigfillset(&act.sa_mask);
1262 act.sa_flags = 0;
1263 act.sa_handler = host_alarm_handler;
1265 sigaction(SIGIO, &act, NULL);
1266 fcntl_setfl(fd, O_ASYNC);
1267 fcntl(fd, F_SETOWN, getpid());
1270 static int hpet_start_timer(struct qemu_alarm_timer *t)
1272 struct hpet_info info;
1273 int r, fd;
1275 fd = qemu_open("/dev/hpet", O_RDONLY);
1276 if (fd < 0)
1277 return -1;
1279 /* Set frequency */
1280 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1281 if (r < 0) {
1282 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1283 "error, but for better emulation accuracy type:\n"
1284 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1285 goto fail;
1288 /* Check capabilities */
1289 r = ioctl(fd, HPET_INFO, &info);
1290 if (r < 0)
1291 goto fail;
1293 /* Enable periodic mode */
1294 r = ioctl(fd, HPET_EPI, 0);
1295 if (info.hi_flags && (r < 0))
1296 goto fail;
1298 /* Enable interrupt */
1299 r = ioctl(fd, HPET_IE_ON, 0);
1300 if (r < 0)
1301 goto fail;
1303 enable_sigio_timer(fd);
1304 t->priv = (void *)(long)fd;
1306 return 0;
1307 fail:
1308 close(fd);
1309 return -1;
1312 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1314 int fd = (long)t->priv;
1316 close(fd);
1319 static int rtc_start_timer(struct qemu_alarm_timer *t)
1321 int rtc_fd;
1322 unsigned long current_rtc_freq = 0;
1324 TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
1325 if (rtc_fd < 0)
1326 return -1;
1327 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1328 if (current_rtc_freq != RTC_FREQ &&
1329 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1330 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1331 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1332 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1333 goto fail;
1335 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1336 fail:
1337 close(rtc_fd);
1338 return -1;
1341 enable_sigio_timer(rtc_fd);
1343 t->priv = (void *)(long)rtc_fd;
1345 return 0;
1348 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1350 int rtc_fd = (long)t->priv;
1352 close(rtc_fd);
1355 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1357 struct sigevent ev;
1358 timer_t host_timer;
1359 struct sigaction act;
1361 sigfillset(&act.sa_mask);
1362 act.sa_flags = 0;
1363 act.sa_handler = host_alarm_handler;
1365 sigaction(SIGALRM, &act, NULL);
1368 * Initialize ev struct to 0 to avoid valgrind complaining
1369 * about uninitialized data in timer_create call
1371 memset(&ev, 0, sizeof(ev));
1372 ev.sigev_value.sival_int = 0;
1373 ev.sigev_notify = SIGEV_SIGNAL;
1374 ev.sigev_signo = SIGALRM;
1376 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1377 perror("timer_create");
1379 /* disable dynticks */
1380 fprintf(stderr, "Dynamic Ticks disabled\n");
1382 return -1;
1385 t->priv = (void *)(long)host_timer;
1387 return 0;
1390 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1392 timer_t host_timer = (timer_t)(long)t->priv;
1394 timer_delete(host_timer);
1397 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1399 timer_t host_timer = (timer_t)(long)t->priv;
1400 struct itimerspec timeout;
1401 int64_t nearest_delta_us = INT64_MAX;
1402 int64_t current_us;
1404 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1405 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1406 !active_timers[QEMU_CLOCK_HOST])
1407 return;
1409 nearest_delta_us = qemu_next_deadline_dyntick();
1411 /* check whether a timer is already running */
1412 if (timer_gettime(host_timer, &timeout)) {
1413 perror("gettime");
1414 fprintf(stderr, "Internal timer error: aborting\n");
1415 exit(1);
1417 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1418 if (current_us && current_us <= nearest_delta_us)
1419 return;
1421 timeout.it_interval.tv_sec = 0;
1422 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1423 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1424 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1425 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1426 perror("settime");
1427 fprintf(stderr, "Internal timer error: aborting\n");
1428 exit(1);
1432 #endif /* defined(__linux__) */
1434 static int unix_start_timer(struct qemu_alarm_timer *t)
1436 struct sigaction act;
1437 struct itimerval itv;
1438 int err;
1440 /* timer signal */
1441 sigfillset(&act.sa_mask);
1442 act.sa_flags = 0;
1443 act.sa_handler = host_alarm_handler;
1445 sigaction(SIGALRM, &act, NULL);
1447 itv.it_interval.tv_sec = 0;
1448 /* for i386 kernel 2.6 to get 1 ms */
1449 itv.it_interval.tv_usec = 999;
1450 itv.it_value.tv_sec = 0;
1451 itv.it_value.tv_usec = 10 * 1000;
1453 err = setitimer(ITIMER_REAL, &itv, NULL);
1454 if (err)
1455 return -1;
1457 return 0;
1460 static void unix_stop_timer(struct qemu_alarm_timer *t)
1462 struct itimerval itv;
1464 memset(&itv, 0, sizeof(itv));
1465 setitimer(ITIMER_REAL, &itv, NULL);
1468 #endif /* !defined(_WIN32) */
1471 #ifdef _WIN32
1473 static int win32_start_timer(struct qemu_alarm_timer *t)
1475 TIMECAPS tc;
1476 struct qemu_alarm_win32 *data = t->priv;
1477 UINT flags;
1479 memset(&tc, 0, sizeof(tc));
1480 timeGetDevCaps(&tc, sizeof(tc));
1482 if (data->period < tc.wPeriodMin)
1483 data->period = tc.wPeriodMin;
1485 timeBeginPeriod(data->period);
1487 flags = TIME_CALLBACK_FUNCTION;
1488 if (alarm_has_dynticks(t))
1489 flags |= TIME_ONESHOT;
1490 else
1491 flags |= TIME_PERIODIC;
1493 data->timerId = timeSetEvent(1, // interval (ms)
1494 data->period, // resolution
1495 host_alarm_handler, // function
1496 (DWORD)t, // parameter
1497 flags);
1499 if (!data->timerId) {
1500 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1501 GetLastError());
1502 timeEndPeriod(data->period);
1503 return -1;
1506 return 0;
1509 static void win32_stop_timer(struct qemu_alarm_timer *t)
1511 struct qemu_alarm_win32 *data = t->priv;
1513 timeKillEvent(data->timerId);
1514 timeEndPeriod(data->period);
1517 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1519 struct qemu_alarm_win32 *data = t->priv;
1521 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1522 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1523 !active_timers[QEMU_CLOCK_HOST])
1524 return;
1526 timeKillEvent(data->timerId);
1528 data->timerId = timeSetEvent(1,
1529 data->period,
1530 host_alarm_handler,
1531 (DWORD)t,
1532 TIME_ONESHOT | TIME_PERIODIC);
1534 if (!data->timerId) {
1535 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1536 GetLastError());
1538 timeEndPeriod(data->period);
1539 exit(1);
1543 #endif /* _WIN32 */
1545 static int init_timer_alarm(void)
1547 struct qemu_alarm_timer *t = NULL;
1548 int i, err = -1;
1550 for (i = 0; alarm_timers[i].name; i++) {
1551 t = &alarm_timers[i];
1553 err = t->start(t);
1554 if (!err)
1555 break;
1558 if (err) {
1559 err = -ENOENT;
1560 goto fail;
1563 alarm_timer = t;
1565 return 0;
1567 fail:
1568 return err;
1571 static void quit_timers(void)
1573 alarm_timer->stop(alarm_timer);
1574 alarm_timer = NULL;
1577 /***********************************************************/
1578 /* host time/date access */
1579 void qemu_get_timedate(struct tm *tm, int offset)
1581 time_t ti;
1582 struct tm *ret;
1584 time(&ti);
1585 ti += offset;
1586 if (rtc_date_offset == -1) {
1587 if (rtc_utc)
1588 ret = gmtime(&ti);
1589 else
1590 ret = localtime(&ti);
1591 } else {
1592 ti -= rtc_date_offset;
1593 ret = gmtime(&ti);
1596 memcpy(tm, ret, sizeof(struct tm));
1599 int qemu_timedate_diff(struct tm *tm)
1601 time_t seconds;
1603 if (rtc_date_offset == -1)
1604 if (rtc_utc)
1605 seconds = mktimegm(tm);
1606 else
1607 seconds = mktime(tm);
1608 else
1609 seconds = mktimegm(tm) + rtc_date_offset;
1611 return seconds - time(NULL);
1614 static void configure_rtc_date_offset(const char *startdate, int legacy)
1616 time_t rtc_start_date;
1617 struct tm tm;
1619 if (!strcmp(startdate, "now") && legacy) {
1620 rtc_date_offset = -1;
1621 } else {
1622 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1623 &tm.tm_year,
1624 &tm.tm_mon,
1625 &tm.tm_mday,
1626 &tm.tm_hour,
1627 &tm.tm_min,
1628 &tm.tm_sec) == 6) {
1629 /* OK */
1630 } else if (sscanf(startdate, "%d-%d-%d",
1631 &tm.tm_year,
1632 &tm.tm_mon,
1633 &tm.tm_mday) == 3) {
1634 tm.tm_hour = 0;
1635 tm.tm_min = 0;
1636 tm.tm_sec = 0;
1637 } else {
1638 goto date_fail;
1640 tm.tm_year -= 1900;
1641 tm.tm_mon--;
1642 rtc_start_date = mktimegm(&tm);
1643 if (rtc_start_date == -1) {
1644 date_fail:
1645 fprintf(stderr, "Invalid date format. Valid formats are:\n"
1646 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1647 exit(1);
1649 rtc_date_offset = time(NULL) - rtc_start_date;
1653 static void configure_rtc(QemuOpts *opts)
1655 const char *value;
1657 value = qemu_opt_get(opts, "base");
1658 if (value) {
1659 if (!strcmp(value, "utc")) {
1660 rtc_utc = 1;
1661 } else if (!strcmp(value, "localtime")) {
1662 rtc_utc = 0;
1663 } else {
1664 configure_rtc_date_offset(value, 0);
1667 value = qemu_opt_get(opts, "clock");
1668 if (value) {
1669 if (!strcmp(value, "host")) {
1670 rtc_clock = host_clock;
1671 } else if (!strcmp(value, "vm")) {
1672 rtc_clock = vm_clock;
1673 } else {
1674 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1675 exit(1);
1678 #ifdef CONFIG_TARGET_I386
1679 value = qemu_opt_get(opts, "driftfix");
1680 if (value) {
1681 if (!strcmp(buf, "slew")) {
1682 rtc_td_hack = 1;
1683 } else if (!strcmp(buf, "none")) {
1684 rtc_td_hack = 0;
1685 } else {
1686 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1687 exit(1);
1690 #endif
1693 #ifdef _WIN32
1694 static void socket_cleanup(void)
1696 WSACleanup();
1699 static int socket_init(void)
1701 WSADATA Data;
1702 int ret, err;
1704 ret = WSAStartup(MAKEWORD(2,2), &Data);
1705 if (ret != 0) {
1706 err = WSAGetLastError();
1707 fprintf(stderr, "WSAStartup: %d\n", err);
1708 return -1;
1710 atexit(socket_cleanup);
1711 return 0;
1713 #endif
1715 /***********************************************************/
1716 /* Bluetooth support */
1717 static int nb_hcis;
1718 static int cur_hci;
1719 static struct HCIInfo *hci_table[MAX_NICS];
1721 static struct bt_vlan_s {
1722 struct bt_scatternet_s net;
1723 int id;
1724 struct bt_vlan_s *next;
1725 } *first_bt_vlan;
1727 /* find or alloc a new bluetooth "VLAN" */
1728 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1730 struct bt_vlan_s **pvlan, *vlan;
1731 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1732 if (vlan->id == id)
1733 return &vlan->net;
1735 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1736 vlan->id = id;
1737 pvlan = &first_bt_vlan;
1738 while (*pvlan != NULL)
1739 pvlan = &(*pvlan)->next;
1740 *pvlan = vlan;
1741 return &vlan->net;
1744 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1748 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1750 return -ENOTSUP;
1753 static struct HCIInfo null_hci = {
1754 .cmd_send = null_hci_send,
1755 .sco_send = null_hci_send,
1756 .acl_send = null_hci_send,
1757 .bdaddr_set = null_hci_addr_set,
1760 struct HCIInfo *qemu_next_hci(void)
1762 if (cur_hci == nb_hcis)
1763 return &null_hci;
1765 return hci_table[cur_hci++];
1768 static struct HCIInfo *hci_init(const char *str)
1770 char *endp;
1771 struct bt_scatternet_s *vlan = 0;
1773 if (!strcmp(str, "null"))
1774 /* null */
1775 return &null_hci;
1776 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1777 /* host[:hciN] */
1778 return bt_host_hci(str[4] ? str + 5 : "hci0");
1779 else if (!strncmp(str, "hci", 3)) {
1780 /* hci[,vlan=n] */
1781 if (str[3]) {
1782 if (!strncmp(str + 3, ",vlan=", 6)) {
1783 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1784 if (*endp)
1785 vlan = 0;
1787 } else
1788 vlan = qemu_find_bt_vlan(0);
1789 if (vlan)
1790 return bt_new_hci(vlan);
1793 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1795 return 0;
1798 static int bt_hci_parse(const char *str)
1800 struct HCIInfo *hci;
1801 bdaddr_t bdaddr;
1803 if (nb_hcis >= MAX_NICS) {
1804 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1805 return -1;
1808 hci = hci_init(str);
1809 if (!hci)
1810 return -1;
1812 bdaddr.b[0] = 0x52;
1813 bdaddr.b[1] = 0x54;
1814 bdaddr.b[2] = 0x00;
1815 bdaddr.b[3] = 0x12;
1816 bdaddr.b[4] = 0x34;
1817 bdaddr.b[5] = 0x56 + nb_hcis;
1818 hci->bdaddr_set(hci, bdaddr.b);
1820 hci_table[nb_hcis++] = hci;
1822 return 0;
1825 static void bt_vhci_add(int vlan_id)
1827 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1829 if (!vlan->slave)
1830 fprintf(stderr, "qemu: warning: adding a VHCI to "
1831 "an empty scatternet %i\n", vlan_id);
1833 bt_vhci_init(bt_new_hci(vlan));
1836 static struct bt_device_s *bt_device_add(const char *opt)
1838 struct bt_scatternet_s *vlan;
1839 int vlan_id = 0;
1840 char *endp = strstr(opt, ",vlan=");
1841 int len = (endp ? endp - opt : strlen(opt)) + 1;
1842 char devname[10];
1844 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1846 if (endp) {
1847 vlan_id = strtol(endp + 6, &endp, 0);
1848 if (*endp) {
1849 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1850 return 0;
1854 vlan = qemu_find_bt_vlan(vlan_id);
1856 if (!vlan->slave)
1857 fprintf(stderr, "qemu: warning: adding a slave device to "
1858 "an empty scatternet %i\n", vlan_id);
1860 if (!strcmp(devname, "keyboard"))
1861 return bt_keyboard_init(vlan);
1863 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1864 return 0;
1867 static int bt_parse(const char *opt)
1869 const char *endp, *p;
1870 int vlan;
1872 if (strstart(opt, "hci", &endp)) {
1873 if (!*endp || *endp == ',') {
1874 if (*endp)
1875 if (!strstart(endp, ",vlan=", 0))
1876 opt = endp + 1;
1878 return bt_hci_parse(opt);
1880 } else if (strstart(opt, "vhci", &endp)) {
1881 if (!*endp || *endp == ',') {
1882 if (*endp) {
1883 if (strstart(endp, ",vlan=", &p)) {
1884 vlan = strtol(p, (char **) &endp, 0);
1885 if (*endp) {
1886 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1887 return 1;
1889 } else {
1890 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1891 return 1;
1893 } else
1894 vlan = 0;
1896 bt_vhci_add(vlan);
1897 return 0;
1899 } else if (strstart(opt, "device:", &endp))
1900 return !bt_device_add(endp);
1902 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1903 return 1;
1906 /***********************************************************/
1907 /* QEMU Block devices */
1909 #define HD_ALIAS "index=%d,media=disk"
1910 #define CDROM_ALIAS "index=2,media=cdrom"
1911 #define FD_ALIAS "index=%d,if=floppy"
1912 #define PFLASH_ALIAS "if=pflash"
1913 #define MTD_ALIAS "if=mtd"
1914 #define SD_ALIAS "index=0,if=sd"
1916 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1918 va_list ap;
1919 char optstr[1024];
1920 QemuOpts *opts;
1922 va_start(ap, fmt);
1923 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1924 va_end(ap);
1926 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1927 if (!opts) {
1928 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1929 __FUNCTION__, optstr);
1930 return NULL;
1932 if (file)
1933 qemu_opt_set(opts, "file", file);
1934 return opts;
1937 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1939 DriveInfo *dinfo;
1941 /* seek interface, bus and unit */
1943 QTAILQ_FOREACH(dinfo, &drives, next) {
1944 if (dinfo->type == type &&
1945 dinfo->bus == bus &&
1946 dinfo->unit == unit)
1947 return dinfo;
1950 return NULL;
1953 DriveInfo *drive_get_by_id(const char *id)
1955 DriveInfo *dinfo;
1957 QTAILQ_FOREACH(dinfo, &drives, next) {
1958 if (strcmp(id, dinfo->id))
1959 continue;
1960 return dinfo;
1962 return NULL;
1965 int drive_get_max_bus(BlockInterfaceType type)
1967 int max_bus;
1968 DriveInfo *dinfo;
1970 max_bus = -1;
1971 QTAILQ_FOREACH(dinfo, &drives, next) {
1972 if(dinfo->type == type &&
1973 dinfo->bus > max_bus)
1974 max_bus = dinfo->bus;
1976 return max_bus;
1979 const char *drive_get_serial(BlockDriverState *bdrv)
1981 DriveInfo *dinfo;
1983 QTAILQ_FOREACH(dinfo, &drives, next) {
1984 if (dinfo->bdrv == bdrv)
1985 return dinfo->serial;
1988 return "\0";
1991 BlockInterfaceErrorAction drive_get_on_error(
1992 BlockDriverState *bdrv, int is_read)
1994 DriveInfo *dinfo;
1996 if (is_read) {
1997 return BLOCK_ERR_REPORT;
2000 QTAILQ_FOREACH(dinfo, &drives, next) {
2001 if (dinfo->bdrv == bdrv)
2002 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
2005 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
2008 static void bdrv_format_print(void *opaque, const char *name)
2010 fprintf(stderr, " %s", name);
2013 void drive_uninit(DriveInfo *dinfo)
2015 qemu_opts_del(dinfo->opts);
2016 bdrv_delete(dinfo->bdrv);
2017 QTAILQ_REMOVE(&drives, dinfo, next);
2018 qemu_free(dinfo);
2021 static int parse_block_error_action(const char *buf, int is_read)
2023 if (!strcmp(buf, "ignore")) {
2024 return BLOCK_ERR_IGNORE;
2025 } else if (!is_read && !strcmp(buf, "enospc")) {
2026 return BLOCK_ERR_STOP_ENOSPC;
2027 } else if (!strcmp(buf, "stop")) {
2028 return BLOCK_ERR_STOP_ANY;
2029 } else if (!strcmp(buf, "report")) {
2030 return BLOCK_ERR_REPORT;
2031 } else {
2032 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
2033 buf, is_read ? "read" : "write");
2034 return -1;
2038 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
2039 int *fatal_error)
2041 const char *buf;
2042 const char *file = NULL;
2043 char devname[128];
2044 const char *serial;
2045 const char *mediastr = "";
2046 BlockInterfaceType type;
2047 enum { MEDIA_DISK, MEDIA_CDROM } media;
2048 int bus_id, unit_id;
2049 int cyls, heads, secs, translation;
2050 BlockDriver *drv = NULL;
2051 QEMUMachine *machine = opaque;
2052 int max_devs;
2053 int index;
2054 int cache;
2055 int aio = 0;
2056 int ro = 0;
2057 int bdrv_flags;
2058 int on_read_error, on_write_error;
2059 const char *devaddr;
2060 DriveInfo *dinfo;
2061 int snapshot = 0;
2063 *fatal_error = 1;
2065 translation = BIOS_ATA_TRANSLATION_AUTO;
2066 cache = 1;
2068 if (machine && machine->use_scsi) {
2069 type = IF_SCSI;
2070 max_devs = MAX_SCSI_DEVS;
2071 pstrcpy(devname, sizeof(devname), "scsi");
2072 } else {
2073 type = IF_IDE;
2074 max_devs = MAX_IDE_DEVS;
2075 pstrcpy(devname, sizeof(devname), "ide");
2077 media = MEDIA_DISK;
2079 /* extract parameters */
2080 bus_id = qemu_opt_get_number(opts, "bus", 0);
2081 unit_id = qemu_opt_get_number(opts, "unit", -1);
2082 index = qemu_opt_get_number(opts, "index", -1);
2084 cyls = qemu_opt_get_number(opts, "cyls", 0);
2085 heads = qemu_opt_get_number(opts, "heads", 0);
2086 secs = qemu_opt_get_number(opts, "secs", 0);
2088 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
2089 ro = qemu_opt_get_bool(opts, "readonly", 0);
2091 file = qemu_opt_get(opts, "file");
2092 serial = qemu_opt_get(opts, "serial");
2094 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
2095 pstrcpy(devname, sizeof(devname), buf);
2096 if (!strcmp(buf, "ide")) {
2097 type = IF_IDE;
2098 max_devs = MAX_IDE_DEVS;
2099 } else if (!strcmp(buf, "scsi")) {
2100 type = IF_SCSI;
2101 max_devs = MAX_SCSI_DEVS;
2102 } else if (!strcmp(buf, "floppy")) {
2103 type = IF_FLOPPY;
2104 max_devs = 0;
2105 } else if (!strcmp(buf, "pflash")) {
2106 type = IF_PFLASH;
2107 max_devs = 0;
2108 } else if (!strcmp(buf, "mtd")) {
2109 type = IF_MTD;
2110 max_devs = 0;
2111 } else if (!strcmp(buf, "sd")) {
2112 type = IF_SD;
2113 max_devs = 0;
2114 } else if (!strcmp(buf, "virtio")) {
2115 type = IF_VIRTIO;
2116 max_devs = 0;
2117 } else if (!strcmp(buf, "xen")) {
2118 type = IF_XEN;
2119 max_devs = 0;
2120 } else if (!strcmp(buf, "none")) {
2121 type = IF_NONE;
2122 max_devs = 0;
2123 } else {
2124 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
2125 return NULL;
2129 if (cyls || heads || secs) {
2130 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
2131 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2132 return NULL;
2134 if (heads < 1 || (type == IF_IDE && heads > 16)) {
2135 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2136 return NULL;
2138 if (secs < 1 || (type == IF_IDE && secs > 63)) {
2139 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2140 return NULL;
2144 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2145 if (!cyls) {
2146 fprintf(stderr,
2147 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2148 buf);
2149 return NULL;
2151 if (!strcmp(buf, "none"))
2152 translation = BIOS_ATA_TRANSLATION_NONE;
2153 else if (!strcmp(buf, "lba"))
2154 translation = BIOS_ATA_TRANSLATION_LBA;
2155 else if (!strcmp(buf, "auto"))
2156 translation = BIOS_ATA_TRANSLATION_AUTO;
2157 else {
2158 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2159 return NULL;
2163 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2164 if (!strcmp(buf, "disk")) {
2165 media = MEDIA_DISK;
2166 } else if (!strcmp(buf, "cdrom")) {
2167 if (cyls || secs || heads) {
2168 fprintf(stderr,
2169 "qemu: '%s' invalid physical CHS format\n", buf);
2170 return NULL;
2172 media = MEDIA_CDROM;
2173 } else {
2174 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2175 return NULL;
2179 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2180 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2181 cache = 0;
2182 else if (!strcmp(buf, "writethrough"))
2183 cache = 1;
2184 else if (!strcmp(buf, "writeback"))
2185 cache = 2;
2186 else {
2187 fprintf(stderr, "qemu: invalid cache option\n");
2188 return NULL;
2192 #ifdef CONFIG_LINUX_AIO
2193 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2194 if (!strcmp(buf, "threads"))
2195 aio = 0;
2196 else if (!strcmp(buf, "native"))
2197 aio = 1;
2198 else {
2199 fprintf(stderr, "qemu: invalid aio option\n");
2200 return NULL;
2203 #endif
2205 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2206 if (strcmp(buf, "?") == 0) {
2207 fprintf(stderr, "qemu: Supported formats:");
2208 bdrv_iterate_format(bdrv_format_print, NULL);
2209 fprintf(stderr, "\n");
2210 return NULL;
2212 drv = bdrv_find_whitelisted_format(buf);
2213 if (!drv) {
2214 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2215 return NULL;
2219 on_write_error = BLOCK_ERR_STOP_ENOSPC;
2220 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2221 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2222 fprintf(stderr, "werror is no supported by this format\n");
2223 return NULL;
2226 on_write_error = parse_block_error_action(buf, 0);
2227 if (on_write_error < 0) {
2228 return NULL;
2232 on_read_error = BLOCK_ERR_REPORT;
2233 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2234 if (type != IF_IDE && type != IF_VIRTIO) {
2235 fprintf(stderr, "rerror is no supported by this format\n");
2236 return NULL;
2239 on_read_error = parse_block_error_action(buf, 1);
2240 if (on_read_error < 0) {
2241 return NULL;
2245 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2246 if (type != IF_VIRTIO) {
2247 fprintf(stderr, "addr is not supported\n");
2248 return NULL;
2252 /* compute bus and unit according index */
2254 if (index != -1) {
2255 if (bus_id != 0 || unit_id != -1) {
2256 fprintf(stderr,
2257 "qemu: index cannot be used with bus and unit\n");
2258 return NULL;
2260 if (max_devs == 0)
2262 unit_id = index;
2263 bus_id = 0;
2264 } else {
2265 unit_id = index % max_devs;
2266 bus_id = index / max_devs;
2270 /* if user doesn't specify a unit_id,
2271 * try to find the first free
2274 if (unit_id == -1) {
2275 unit_id = 0;
2276 while (drive_get(type, bus_id, unit_id) != NULL) {
2277 unit_id++;
2278 if (max_devs && unit_id >= max_devs) {
2279 unit_id -= max_devs;
2280 bus_id++;
2285 /* check unit id */
2287 if (max_devs && unit_id >= max_devs) {
2288 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2289 unit_id, max_devs - 1);
2290 return NULL;
2294 * ignore multiple definitions
2297 if (drive_get(type, bus_id, unit_id) != NULL) {
2298 *fatal_error = 0;
2299 return NULL;
2302 /* init */
2304 dinfo = qemu_mallocz(sizeof(*dinfo));
2305 if ((buf = qemu_opts_id(opts)) != NULL) {
2306 dinfo->id = qemu_strdup(buf);
2307 } else {
2308 /* no id supplied -> create one */
2309 dinfo->id = qemu_mallocz(32);
2310 if (type == IF_IDE || type == IF_SCSI)
2311 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2312 if (max_devs)
2313 snprintf(dinfo->id, 32, "%s%i%s%i",
2314 devname, bus_id, mediastr, unit_id);
2315 else
2316 snprintf(dinfo->id, 32, "%s%s%i",
2317 devname, mediastr, unit_id);
2319 dinfo->bdrv = bdrv_new(dinfo->id);
2320 dinfo->devaddr = devaddr;
2321 dinfo->type = type;
2322 dinfo->bus = bus_id;
2323 dinfo->unit = unit_id;
2324 dinfo->on_read_error = on_read_error;
2325 dinfo->on_write_error = on_write_error;
2326 dinfo->opts = opts;
2327 if (serial)
2328 strncpy(dinfo->serial, serial, sizeof(serial));
2329 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2331 switch(type) {
2332 case IF_IDE:
2333 case IF_SCSI:
2334 case IF_XEN:
2335 case IF_NONE:
2336 switch(media) {
2337 case MEDIA_DISK:
2338 if (cyls != 0) {
2339 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2340 bdrv_set_translation_hint(dinfo->bdrv, translation);
2342 break;
2343 case MEDIA_CDROM:
2344 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2345 break;
2347 break;
2348 case IF_SD:
2349 /* FIXME: This isn't really a floppy, but it's a reasonable
2350 approximation. */
2351 case IF_FLOPPY:
2352 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2353 break;
2354 case IF_PFLASH:
2355 case IF_MTD:
2356 break;
2357 case IF_VIRTIO:
2358 /* add virtio block device */
2359 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2360 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2361 qemu_opt_set(opts, "drive", dinfo->id);
2362 if (devaddr)
2363 qemu_opt_set(opts, "addr", devaddr);
2364 break;
2365 case IF_COUNT:
2366 abort();
2368 if (!file) {
2369 *fatal_error = 0;
2370 return NULL;
2372 bdrv_flags = 0;
2373 if (snapshot) {
2374 bdrv_flags |= BDRV_O_SNAPSHOT;
2375 cache = 2; /* always use write-back with snapshot */
2377 if (cache == 0) /* no caching */
2378 bdrv_flags |= BDRV_O_NOCACHE;
2379 else if (cache == 2) /* write-back */
2380 bdrv_flags |= BDRV_O_CACHE_WB;
2382 if (aio == 1) {
2383 bdrv_flags |= BDRV_O_NATIVE_AIO;
2384 } else {
2385 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2388 if (ro == 1) {
2389 if (type == IF_IDE) {
2390 fprintf(stderr, "qemu: readonly flag not supported for drive with ide interface\n");
2391 return NULL;
2393 (void)bdrv_set_read_only(dinfo->bdrv, 1);
2396 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2397 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2398 file, strerror(errno));
2399 return NULL;
2402 if (bdrv_key_required(dinfo->bdrv))
2403 autostart = 0;
2404 *fatal_error = 0;
2405 return dinfo;
2408 static int drive_init_func(QemuOpts *opts, void *opaque)
2410 QEMUMachine *machine = opaque;
2411 int fatal_error = 0;
2413 if (drive_init(opts, machine, &fatal_error) == NULL) {
2414 if (fatal_error)
2415 return 1;
2417 return 0;
2420 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2422 if (NULL == qemu_opt_get(opts, "snapshot")) {
2423 qemu_opt_set(opts, "snapshot", "on");
2425 return 0;
2428 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2430 boot_set_handler = func;
2431 boot_set_opaque = opaque;
2434 int qemu_boot_set(const char *boot_devices)
2436 if (!boot_set_handler) {
2437 return -EINVAL;
2439 return boot_set_handler(boot_set_opaque, boot_devices);
2442 static int parse_bootdevices(char *devices)
2444 /* We just do some generic consistency checks */
2445 const char *p;
2446 int bitmap = 0;
2448 for (p = devices; *p != '\0'; p++) {
2449 /* Allowed boot devices are:
2450 * a-b: floppy disk drives
2451 * c-f: IDE disk drives
2452 * g-m: machine implementation dependant drives
2453 * n-p: network devices
2454 * It's up to each machine implementation to check if the given boot
2455 * devices match the actual hardware implementation and firmware
2456 * features.
2458 if (*p < 'a' || *p > 'p') {
2459 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2460 exit(1);
2462 if (bitmap & (1 << (*p - 'a'))) {
2463 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2464 exit(1);
2466 bitmap |= 1 << (*p - 'a');
2468 return bitmap;
2471 static void restore_boot_devices(void *opaque)
2473 char *standard_boot_devices = opaque;
2475 qemu_boot_set(standard_boot_devices);
2477 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2478 qemu_free(standard_boot_devices);
2481 static void numa_add(const char *optarg)
2483 char option[128];
2484 char *endptr;
2485 unsigned long long value, endvalue;
2486 int nodenr;
2488 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2489 if (!strcmp(option, "node")) {
2490 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2491 nodenr = nb_numa_nodes;
2492 } else {
2493 nodenr = strtoull(option, NULL, 10);
2496 if (get_param_value(option, 128, "mem", optarg) == 0) {
2497 node_mem[nodenr] = 0;
2498 } else {
2499 value = strtoull(option, &endptr, 0);
2500 switch (*endptr) {
2501 case 0: case 'M': case 'm':
2502 value <<= 20;
2503 break;
2504 case 'G': case 'g':
2505 value <<= 30;
2506 break;
2508 node_mem[nodenr] = value;
2510 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2511 node_cpumask[nodenr] = 0;
2512 } else {
2513 value = strtoull(option, &endptr, 10);
2514 if (value >= 64) {
2515 value = 63;
2516 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2517 } else {
2518 if (*endptr == '-') {
2519 endvalue = strtoull(endptr+1, &endptr, 10);
2520 if (endvalue >= 63) {
2521 endvalue = 62;
2522 fprintf(stderr,
2523 "only 63 CPUs in NUMA mode supported.\n");
2525 value = (1 << (endvalue + 1)) - (1 << value);
2526 } else {
2527 value = 1 << value;
2530 node_cpumask[nodenr] = value;
2532 nb_numa_nodes++;
2534 return;
2537 static void smp_parse(const char *optarg)
2539 int smp, sockets = 0, threads = 0, cores = 0;
2540 char *endptr;
2541 char option[128];
2543 smp = strtoul(optarg, &endptr, 10);
2544 if (endptr != optarg) {
2545 if (*endptr == ',') {
2546 endptr++;
2549 if (get_param_value(option, 128, "sockets", endptr) != 0)
2550 sockets = strtoull(option, NULL, 10);
2551 if (get_param_value(option, 128, "cores", endptr) != 0)
2552 cores = strtoull(option, NULL, 10);
2553 if (get_param_value(option, 128, "threads", endptr) != 0)
2554 threads = strtoull(option, NULL, 10);
2555 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2556 max_cpus = strtoull(option, NULL, 10);
2558 /* compute missing values, prefer sockets over cores over threads */
2559 if (smp == 0 || sockets == 0) {
2560 sockets = sockets > 0 ? sockets : 1;
2561 cores = cores > 0 ? cores : 1;
2562 threads = threads > 0 ? threads : 1;
2563 if (smp == 0) {
2564 smp = cores * threads * sockets;
2565 } else {
2566 sockets = smp / (cores * threads);
2568 } else {
2569 if (cores == 0) {
2570 threads = threads > 0 ? threads : 1;
2571 cores = smp / (sockets * threads);
2572 } else {
2573 if (sockets == 0) {
2574 sockets = smp / (cores * threads);
2575 } else {
2576 threads = smp / (cores * sockets);
2580 smp_cpus = smp;
2581 smp_cores = cores > 0 ? cores : 1;
2582 smp_threads = threads > 0 ? threads : 1;
2583 if (max_cpus == 0)
2584 max_cpus = smp_cpus;
2587 /***********************************************************/
2588 /* USB devices */
2590 static int usb_device_add(const char *devname, int is_hotplug)
2592 const char *p;
2593 USBDevice *dev = NULL;
2595 if (!usb_enabled)
2596 return -1;
2598 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2599 dev = usbdevice_create(devname);
2600 if (dev)
2601 goto done;
2603 /* the other ones */
2604 if (strstart(devname, "host:", &p)) {
2605 dev = usb_host_device_open(p);
2606 } else if (strstart(devname, "net:", &p)) {
2607 QemuOpts *opts;
2608 int idx;
2610 opts = qemu_opts_parse(&qemu_net_opts, p, NULL);
2611 if (!opts) {
2612 return -1;
2615 qemu_opt_set(opts, "type", "nic");
2616 qemu_opt_set(opts, "model", "usb");
2618 idx = net_client_init(NULL, opts, 0);
2619 if (idx == -1) {
2620 return -1;
2623 dev = usb_net_init(&nd_table[idx]);
2624 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2625 dev = usb_bt_init(devname[2] ? hci_init(p) :
2626 bt_new_hci(qemu_find_bt_vlan(0)));
2627 } else {
2628 return -1;
2630 if (!dev)
2631 return -1;
2633 done:
2634 return 0;
2637 static int usb_device_del(const char *devname)
2639 int bus_num, addr;
2640 const char *p;
2642 if (strstart(devname, "host:", &p))
2643 return usb_host_device_close(p);
2645 if (!usb_enabled)
2646 return -1;
2648 p = strchr(devname, '.');
2649 if (!p)
2650 return -1;
2651 bus_num = strtoul(devname, NULL, 0);
2652 addr = strtoul(p + 1, NULL, 0);
2654 return usb_device_delete_addr(bus_num, addr);
2657 static int usb_parse(const char *cmdline)
2659 return usb_device_add(cmdline, 0);
2662 void do_usb_add(Monitor *mon, const QDict *qdict)
2664 usb_device_add(qdict_get_str(qdict, "devname"), 1);
2667 void do_usb_del(Monitor *mon, const QDict *qdict)
2669 usb_device_del(qdict_get_str(qdict, "devname"));
2672 /***********************************************************/
2673 /* PCMCIA/Cardbus */
2675 static struct pcmcia_socket_entry_s {
2676 PCMCIASocket *socket;
2677 struct pcmcia_socket_entry_s *next;
2678 } *pcmcia_sockets = 0;
2680 void pcmcia_socket_register(PCMCIASocket *socket)
2682 struct pcmcia_socket_entry_s *entry;
2684 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2685 entry->socket = socket;
2686 entry->next = pcmcia_sockets;
2687 pcmcia_sockets = entry;
2690 void pcmcia_socket_unregister(PCMCIASocket *socket)
2692 struct pcmcia_socket_entry_s *entry, **ptr;
2694 ptr = &pcmcia_sockets;
2695 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2696 if (entry->socket == socket) {
2697 *ptr = entry->next;
2698 qemu_free(entry);
2702 void pcmcia_info(Monitor *mon)
2704 struct pcmcia_socket_entry_s *iter;
2706 if (!pcmcia_sockets)
2707 monitor_printf(mon, "No PCMCIA sockets\n");
2709 for (iter = pcmcia_sockets; iter; iter = iter->next)
2710 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2711 iter->socket->attached ? iter->socket->card_string :
2712 "Empty");
2715 /***********************************************************/
2716 /* register display */
2718 struct DisplayAllocator default_allocator = {
2719 defaultallocator_create_displaysurface,
2720 defaultallocator_resize_displaysurface,
2721 defaultallocator_free_displaysurface
2724 void register_displaystate(DisplayState *ds)
2726 DisplayState **s;
2727 s = &display_state;
2728 while (*s != NULL)
2729 s = &(*s)->next;
2730 ds->next = NULL;
2731 *s = ds;
2734 DisplayState *get_displaystate(void)
2736 return display_state;
2739 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2741 if(ds->allocator == &default_allocator) ds->allocator = da;
2742 return ds->allocator;
2745 /* dumb display */
2747 static void dumb_display_init(void)
2749 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2750 ds->allocator = &default_allocator;
2751 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2752 register_displaystate(ds);
2755 /***********************************************************/
2756 /* I/O handling */
2758 typedef struct IOHandlerRecord {
2759 int fd;
2760 IOCanRWHandler *fd_read_poll;
2761 IOHandler *fd_read;
2762 IOHandler *fd_write;
2763 int deleted;
2764 void *opaque;
2765 /* temporary data */
2766 struct pollfd *ufd;
2767 struct IOHandlerRecord *next;
2768 } IOHandlerRecord;
2770 static IOHandlerRecord *first_io_handler;
2772 /* XXX: fd_read_poll should be suppressed, but an API change is
2773 necessary in the character devices to suppress fd_can_read(). */
2774 int qemu_set_fd_handler2(int fd,
2775 IOCanRWHandler *fd_read_poll,
2776 IOHandler *fd_read,
2777 IOHandler *fd_write,
2778 void *opaque)
2780 IOHandlerRecord **pioh, *ioh;
2782 if (!fd_read && !fd_write) {
2783 pioh = &first_io_handler;
2784 for(;;) {
2785 ioh = *pioh;
2786 if (ioh == NULL)
2787 break;
2788 if (ioh->fd == fd) {
2789 ioh->deleted = 1;
2790 break;
2792 pioh = &ioh->next;
2794 } else {
2795 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2796 if (ioh->fd == fd)
2797 goto found;
2799 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2800 ioh->next = first_io_handler;
2801 first_io_handler = ioh;
2802 found:
2803 ioh->fd = fd;
2804 ioh->fd_read_poll = fd_read_poll;
2805 ioh->fd_read = fd_read;
2806 ioh->fd_write = fd_write;
2807 ioh->opaque = opaque;
2808 ioh->deleted = 0;
2810 return 0;
2813 int qemu_set_fd_handler(int fd,
2814 IOHandler *fd_read,
2815 IOHandler *fd_write,
2816 void *opaque)
2818 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2821 #ifdef _WIN32
2822 /***********************************************************/
2823 /* Polling handling */
2825 typedef struct PollingEntry {
2826 PollingFunc *func;
2827 void *opaque;
2828 struct PollingEntry *next;
2829 } PollingEntry;
2831 static PollingEntry *first_polling_entry;
2833 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2835 PollingEntry **ppe, *pe;
2836 pe = qemu_mallocz(sizeof(PollingEntry));
2837 pe->func = func;
2838 pe->opaque = opaque;
2839 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2840 *ppe = pe;
2841 return 0;
2844 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2846 PollingEntry **ppe, *pe;
2847 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2848 pe = *ppe;
2849 if (pe->func == func && pe->opaque == opaque) {
2850 *ppe = pe->next;
2851 qemu_free(pe);
2852 break;
2857 /***********************************************************/
2858 /* Wait objects support */
2859 typedef struct WaitObjects {
2860 int num;
2861 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2862 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2863 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2864 } WaitObjects;
2866 static WaitObjects wait_objects = {0};
2868 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2870 WaitObjects *w = &wait_objects;
2872 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2873 return -1;
2874 w->events[w->num] = handle;
2875 w->func[w->num] = func;
2876 w->opaque[w->num] = opaque;
2877 w->num++;
2878 return 0;
2881 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2883 int i, found;
2884 WaitObjects *w = &wait_objects;
2886 found = 0;
2887 for (i = 0; i < w->num; i++) {
2888 if (w->events[i] == handle)
2889 found = 1;
2890 if (found) {
2891 w->events[i] = w->events[i + 1];
2892 w->func[i] = w->func[i + 1];
2893 w->opaque[i] = w->opaque[i + 1];
2896 if (found)
2897 w->num--;
2899 #endif
2901 /***********************************************************/
2902 /* ram save/restore */
2904 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2905 #define RAM_SAVE_FLAG_COMPRESS 0x02
2906 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2907 #define RAM_SAVE_FLAG_PAGE 0x08
2908 #define RAM_SAVE_FLAG_EOS 0x10
2910 static int is_dup_page(uint8_t *page, uint8_t ch)
2912 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2913 uint32_t *array = (uint32_t *)page;
2914 int i;
2916 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2917 if (array[i] != val)
2918 return 0;
2921 return 1;
2924 static int ram_save_block(QEMUFile *f)
2926 static ram_addr_t current_addr = 0;
2927 ram_addr_t saved_addr = current_addr;
2928 ram_addr_t addr = 0;
2929 int found = 0;
2931 while (addr < last_ram_offset) {
2932 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2933 uint8_t *p;
2935 cpu_physical_memory_reset_dirty(current_addr,
2936 current_addr + TARGET_PAGE_SIZE,
2937 MIGRATION_DIRTY_FLAG);
2939 p = qemu_get_ram_ptr(current_addr);
2941 if (is_dup_page(p, *p)) {
2942 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2943 qemu_put_byte(f, *p);
2944 } else {
2945 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2946 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2949 found = 1;
2950 break;
2952 addr += TARGET_PAGE_SIZE;
2953 current_addr = (saved_addr + addr) % last_ram_offset;
2956 return found;
2959 static uint64_t bytes_transferred;
2961 static ram_addr_t ram_save_remaining(void)
2963 ram_addr_t addr;
2964 ram_addr_t count = 0;
2966 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2967 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2968 count++;
2971 return count;
2974 uint64_t ram_bytes_remaining(void)
2976 return ram_save_remaining() * TARGET_PAGE_SIZE;
2979 uint64_t ram_bytes_transferred(void)
2981 return bytes_transferred;
2984 uint64_t ram_bytes_total(void)
2986 return last_ram_offset;
2989 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
2991 ram_addr_t addr;
2992 uint64_t bytes_transferred_last;
2993 double bwidth = 0;
2994 uint64_t expected_time = 0;
2996 if (stage < 0) {
2997 cpu_physical_memory_set_dirty_tracking(0);
2998 return 0;
3001 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3002 qemu_file_set_error(f);
3003 return 0;
3006 if (stage == 1) {
3007 bytes_transferred = 0;
3009 /* Make sure all dirty bits are set */
3010 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3011 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3012 cpu_physical_memory_set_dirty(addr);
3015 /* Enable dirty memory tracking */
3016 cpu_physical_memory_set_dirty_tracking(1);
3018 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3021 bytes_transferred_last = bytes_transferred;
3022 bwidth = get_clock();
3024 while (!qemu_file_rate_limit(f)) {
3025 int ret;
3027 ret = ram_save_block(f);
3028 bytes_transferred += ret * TARGET_PAGE_SIZE;
3029 if (ret == 0) /* no more blocks */
3030 break;
3033 bwidth = get_clock() - bwidth;
3034 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3036 /* if we haven't transferred anything this round, force expected_time to a
3037 * a very high value, but without crashing */
3038 if (bwidth == 0)
3039 bwidth = 0.000001;
3041 /* try transferring iterative blocks of memory */
3042 if (stage == 3) {
3043 /* flush all remaining blocks regardless of rate limiting */
3044 while (ram_save_block(f) != 0) {
3045 bytes_transferred += TARGET_PAGE_SIZE;
3047 cpu_physical_memory_set_dirty_tracking(0);
3050 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3052 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3054 return (stage == 2) && (expected_time <= migrate_max_downtime());
3057 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3059 ram_addr_t addr;
3060 int flags;
3062 if (version_id != 3)
3063 return -EINVAL;
3065 do {
3066 addr = qemu_get_be64(f);
3068 flags = addr & ~TARGET_PAGE_MASK;
3069 addr &= TARGET_PAGE_MASK;
3071 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3072 if (addr != last_ram_offset)
3073 return -EINVAL;
3076 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3077 uint8_t ch = qemu_get_byte(f);
3078 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3079 #ifndef _WIN32
3080 if (ch == 0 &&
3081 (!kvm_enabled() || kvm_has_sync_mmu())) {
3082 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3084 #endif
3085 } else if (flags & RAM_SAVE_FLAG_PAGE) {
3086 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3088 if (qemu_file_has_error(f)) {
3089 return -EIO;
3091 } while (!(flags & RAM_SAVE_FLAG_EOS));
3093 return 0;
3096 void qemu_service_io(void)
3098 qemu_notify_event();
3101 /***********************************************************/
3102 /* machine registration */
3104 static QEMUMachine *first_machine = NULL;
3105 QEMUMachine *current_machine = NULL;
3107 int qemu_register_machine(QEMUMachine *m)
3109 QEMUMachine **pm;
3110 pm = &first_machine;
3111 while (*pm != NULL)
3112 pm = &(*pm)->next;
3113 m->next = NULL;
3114 *pm = m;
3115 return 0;
3118 static QEMUMachine *find_machine(const char *name)
3120 QEMUMachine *m;
3122 for(m = first_machine; m != NULL; m = m->next) {
3123 if (!strcmp(m->name, name))
3124 return m;
3125 if (m->alias && !strcmp(m->alias, name))
3126 return m;
3128 return NULL;
3131 static QEMUMachine *find_default_machine(void)
3133 QEMUMachine *m;
3135 for(m = first_machine; m != NULL; m = m->next) {
3136 if (m->is_default) {
3137 return m;
3140 return NULL;
3143 /***********************************************************/
3144 /* main execution loop */
3146 static void gui_update(void *opaque)
3148 uint64_t interval = GUI_REFRESH_INTERVAL;
3149 DisplayState *ds = opaque;
3150 DisplayChangeListener *dcl = ds->listeners;
3152 dpy_refresh(ds);
3154 while (dcl != NULL) {
3155 if (dcl->gui_timer_interval &&
3156 dcl->gui_timer_interval < interval)
3157 interval = dcl->gui_timer_interval;
3158 dcl = dcl->next;
3160 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3163 static void nographic_update(void *opaque)
3165 uint64_t interval = GUI_REFRESH_INTERVAL;
3167 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3170 struct vm_change_state_entry {
3171 VMChangeStateHandler *cb;
3172 void *opaque;
3173 QLIST_ENTRY (vm_change_state_entry) entries;
3176 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3178 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3179 void *opaque)
3181 VMChangeStateEntry *e;
3183 e = qemu_mallocz(sizeof (*e));
3185 e->cb = cb;
3186 e->opaque = opaque;
3187 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3188 return e;
3191 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3193 QLIST_REMOVE (e, entries);
3194 qemu_free (e);
3197 static void vm_state_notify(int running, int reason)
3199 VMChangeStateEntry *e;
3201 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3202 e->cb(e->opaque, running, reason);
3206 static void resume_all_vcpus(void);
3207 static void pause_all_vcpus(void);
3209 void vm_start(void)
3211 if (!vm_running) {
3212 cpu_enable_ticks();
3213 vm_running = 1;
3214 vm_state_notify(1, 0);
3215 qemu_rearm_alarm_timer(alarm_timer);
3216 resume_all_vcpus();
3220 /* reset/shutdown handler */
3222 typedef struct QEMUResetEntry {
3223 QTAILQ_ENTRY(QEMUResetEntry) entry;
3224 QEMUResetHandler *func;
3225 void *opaque;
3226 } QEMUResetEntry;
3228 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3229 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3230 static int reset_requested;
3231 static int shutdown_requested;
3232 static int powerdown_requested;
3233 static int debug_requested;
3234 static int vmstop_requested;
3236 int qemu_shutdown_requested(void)
3238 int r = shutdown_requested;
3239 shutdown_requested = 0;
3240 return r;
3243 int qemu_reset_requested(void)
3245 int r = reset_requested;
3246 reset_requested = 0;
3247 return r;
3250 int qemu_powerdown_requested(void)
3252 int r = powerdown_requested;
3253 powerdown_requested = 0;
3254 return r;
3257 static int qemu_debug_requested(void)
3259 int r = debug_requested;
3260 debug_requested = 0;
3261 return r;
3264 static int qemu_vmstop_requested(void)
3266 int r = vmstop_requested;
3267 vmstop_requested = 0;
3268 return r;
3271 static void do_vm_stop(int reason)
3273 if (vm_running) {
3274 cpu_disable_ticks();
3275 vm_running = 0;
3276 pause_all_vcpus();
3277 vm_state_notify(0, reason);
3281 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3283 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3285 re->func = func;
3286 re->opaque = opaque;
3287 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3290 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3292 QEMUResetEntry *re;
3294 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3295 if (re->func == func && re->opaque == opaque) {
3296 QTAILQ_REMOVE(&reset_handlers, re, entry);
3297 qemu_free(re);
3298 return;
3303 void qemu_system_reset(void)
3305 QEMUResetEntry *re, *nre;
3307 /* reset all devices */
3308 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3309 re->func(re->opaque);
3313 void qemu_system_reset_request(void)
3315 if (no_reboot) {
3316 shutdown_requested = 1;
3317 } else {
3318 reset_requested = 1;
3320 qemu_notify_event();
3323 void qemu_system_shutdown_request(void)
3325 shutdown_requested = 1;
3326 qemu_notify_event();
3329 void qemu_system_powerdown_request(void)
3331 powerdown_requested = 1;
3332 qemu_notify_event();
3335 #ifdef CONFIG_IOTHREAD
3336 static void qemu_system_vmstop_request(int reason)
3338 vmstop_requested = reason;
3339 qemu_notify_event();
3341 #endif
3343 #ifndef _WIN32
3344 static int io_thread_fd = -1;
3346 static void qemu_event_increment(void)
3348 static const char byte = 0;
3350 if (io_thread_fd == -1)
3351 return;
3353 write(io_thread_fd, &byte, sizeof(byte));
3356 static void qemu_event_read(void *opaque)
3358 int fd = (unsigned long)opaque;
3359 ssize_t len;
3361 /* Drain the notify pipe */
3362 do {
3363 char buffer[512];
3364 len = read(fd, buffer, sizeof(buffer));
3365 } while ((len == -1 && errno == EINTR) || len > 0);
3368 static int qemu_event_init(void)
3370 int err;
3371 int fds[2];
3373 err = qemu_pipe(fds);
3374 if (err == -1)
3375 return -errno;
3377 err = fcntl_setfl(fds[0], O_NONBLOCK);
3378 if (err < 0)
3379 goto fail;
3381 err = fcntl_setfl(fds[1], O_NONBLOCK);
3382 if (err < 0)
3383 goto fail;
3385 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3386 (void *)(unsigned long)fds[0]);
3388 io_thread_fd = fds[1];
3389 return 0;
3391 fail:
3392 close(fds[0]);
3393 close(fds[1]);
3394 return err;
3396 #else
3397 HANDLE qemu_event_handle;
3399 static void dummy_event_handler(void *opaque)
3403 static int qemu_event_init(void)
3405 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3406 if (!qemu_event_handle) {
3407 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3408 return -1;
3410 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3411 return 0;
3414 static void qemu_event_increment(void)
3416 if (!SetEvent(qemu_event_handle)) {
3417 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3418 GetLastError());
3419 exit (1);
3422 #endif
3424 static int cpu_can_run(CPUState *env)
3426 if (env->stop)
3427 return 0;
3428 if (env->stopped)
3429 return 0;
3430 return 1;
3433 #ifndef CONFIG_IOTHREAD
3434 static int qemu_init_main_loop(void)
3436 return qemu_event_init();
3439 void qemu_init_vcpu(void *_env)
3441 CPUState *env = _env;
3443 if (kvm_enabled())
3444 kvm_init_vcpu(env);
3445 env->nr_cores = smp_cores;
3446 env->nr_threads = smp_threads;
3447 return;
3450 int qemu_cpu_self(void *env)
3452 return 1;
3455 static void resume_all_vcpus(void)
3459 static void pause_all_vcpus(void)
3463 void qemu_cpu_kick(void *env)
3465 return;
3468 void qemu_notify_event(void)
3470 CPUState *env = cpu_single_env;
3472 if (env) {
3473 cpu_exit(env);
3477 void qemu_mutex_lock_iothread(void) {}
3478 void qemu_mutex_unlock_iothread(void) {}
3480 void vm_stop(int reason)
3482 do_vm_stop(reason);
3485 #else /* CONFIG_IOTHREAD */
3487 #include "qemu-thread.h"
3489 QemuMutex qemu_global_mutex;
3490 static QemuMutex qemu_fair_mutex;
3492 static QemuThread io_thread;
3494 static QemuThread *tcg_cpu_thread;
3495 static QemuCond *tcg_halt_cond;
3497 static int qemu_system_ready;
3498 /* cpu creation */
3499 static QemuCond qemu_cpu_cond;
3500 /* system init */
3501 static QemuCond qemu_system_cond;
3502 static QemuCond qemu_pause_cond;
3504 static void block_io_signals(void);
3505 static void unblock_io_signals(void);
3506 static int tcg_has_work(void);
3508 static int qemu_init_main_loop(void)
3510 int ret;
3512 ret = qemu_event_init();
3513 if (ret)
3514 return ret;
3516 qemu_cond_init(&qemu_pause_cond);
3517 qemu_mutex_init(&qemu_fair_mutex);
3518 qemu_mutex_init(&qemu_global_mutex);
3519 qemu_mutex_lock(&qemu_global_mutex);
3521 unblock_io_signals();
3522 qemu_thread_self(&io_thread);
3524 return 0;
3527 static void qemu_wait_io_event(CPUState *env)
3529 while (!tcg_has_work())
3530 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3532 qemu_mutex_unlock(&qemu_global_mutex);
3535 * Users of qemu_global_mutex can be starved, having no chance
3536 * to acquire it since this path will get to it first.
3537 * So use another lock to provide fairness.
3539 qemu_mutex_lock(&qemu_fair_mutex);
3540 qemu_mutex_unlock(&qemu_fair_mutex);
3542 qemu_mutex_lock(&qemu_global_mutex);
3543 if (env->stop) {
3544 env->stop = 0;
3545 env->stopped = 1;
3546 qemu_cond_signal(&qemu_pause_cond);
3550 static int qemu_cpu_exec(CPUState *env);
3552 static void *kvm_cpu_thread_fn(void *arg)
3554 CPUState *env = arg;
3556 block_io_signals();
3557 qemu_thread_self(env->thread);
3558 if (kvm_enabled())
3559 kvm_init_vcpu(env);
3561 /* signal CPU creation */
3562 qemu_mutex_lock(&qemu_global_mutex);
3563 env->created = 1;
3564 qemu_cond_signal(&qemu_cpu_cond);
3566 /* and wait for machine initialization */
3567 while (!qemu_system_ready)
3568 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3570 while (1) {
3571 if (cpu_can_run(env))
3572 qemu_cpu_exec(env);
3573 qemu_wait_io_event(env);
3576 return NULL;
3579 static void tcg_cpu_exec(void);
3581 static void *tcg_cpu_thread_fn(void *arg)
3583 CPUState *env = arg;
3585 block_io_signals();
3586 qemu_thread_self(env->thread);
3588 /* signal CPU creation */
3589 qemu_mutex_lock(&qemu_global_mutex);
3590 for (env = first_cpu; env != NULL; env = env->next_cpu)
3591 env->created = 1;
3592 qemu_cond_signal(&qemu_cpu_cond);
3594 /* and wait for machine initialization */
3595 while (!qemu_system_ready)
3596 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3598 while (1) {
3599 tcg_cpu_exec();
3600 qemu_wait_io_event(cur_cpu);
3603 return NULL;
3606 void qemu_cpu_kick(void *_env)
3608 CPUState *env = _env;
3609 qemu_cond_broadcast(env->halt_cond);
3610 if (kvm_enabled())
3611 qemu_thread_signal(env->thread, SIGUSR1);
3614 int qemu_cpu_self(void *_env)
3616 CPUState *env = _env;
3617 QemuThread this;
3619 qemu_thread_self(&this);
3621 return qemu_thread_equal(&this, env->thread);
3624 static void cpu_signal(int sig)
3626 if (cpu_single_env)
3627 cpu_exit(cpu_single_env);
3630 static void block_io_signals(void)
3632 sigset_t set;
3633 struct sigaction sigact;
3635 sigemptyset(&set);
3636 sigaddset(&set, SIGUSR2);
3637 sigaddset(&set, SIGIO);
3638 sigaddset(&set, SIGALRM);
3639 pthread_sigmask(SIG_BLOCK, &set, NULL);
3641 sigemptyset(&set);
3642 sigaddset(&set, SIGUSR1);
3643 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3645 memset(&sigact, 0, sizeof(sigact));
3646 sigact.sa_handler = cpu_signal;
3647 sigaction(SIGUSR1, &sigact, NULL);
3650 static void unblock_io_signals(void)
3652 sigset_t set;
3654 sigemptyset(&set);
3655 sigaddset(&set, SIGUSR2);
3656 sigaddset(&set, SIGIO);
3657 sigaddset(&set, SIGALRM);
3658 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3660 sigemptyset(&set);
3661 sigaddset(&set, SIGUSR1);
3662 pthread_sigmask(SIG_BLOCK, &set, NULL);
3665 static void qemu_signal_lock(unsigned int msecs)
3667 qemu_mutex_lock(&qemu_fair_mutex);
3669 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3670 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3671 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3672 break;
3674 qemu_mutex_unlock(&qemu_fair_mutex);
3677 void qemu_mutex_lock_iothread(void)
3679 if (kvm_enabled()) {
3680 qemu_mutex_lock(&qemu_fair_mutex);
3681 qemu_mutex_lock(&qemu_global_mutex);
3682 qemu_mutex_unlock(&qemu_fair_mutex);
3683 } else
3684 qemu_signal_lock(100);
3687 void qemu_mutex_unlock_iothread(void)
3689 qemu_mutex_unlock(&qemu_global_mutex);
3692 static int all_vcpus_paused(void)
3694 CPUState *penv = first_cpu;
3696 while (penv) {
3697 if (!penv->stopped)
3698 return 0;
3699 penv = (CPUState *)penv->next_cpu;
3702 return 1;
3705 static void pause_all_vcpus(void)
3707 CPUState *penv = first_cpu;
3709 while (penv) {
3710 penv->stop = 1;
3711 qemu_thread_signal(penv->thread, SIGUSR1);
3712 qemu_cpu_kick(penv);
3713 penv = (CPUState *)penv->next_cpu;
3716 while (!all_vcpus_paused()) {
3717 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3718 penv = first_cpu;
3719 while (penv) {
3720 qemu_thread_signal(penv->thread, SIGUSR1);
3721 penv = (CPUState *)penv->next_cpu;
3726 static void resume_all_vcpus(void)
3728 CPUState *penv = first_cpu;
3730 while (penv) {
3731 penv->stop = 0;
3732 penv->stopped = 0;
3733 qemu_thread_signal(penv->thread, SIGUSR1);
3734 qemu_cpu_kick(penv);
3735 penv = (CPUState *)penv->next_cpu;
3739 static void tcg_init_vcpu(void *_env)
3741 CPUState *env = _env;
3742 /* share a single thread for all cpus with TCG */
3743 if (!tcg_cpu_thread) {
3744 env->thread = qemu_mallocz(sizeof(QemuThread));
3745 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3746 qemu_cond_init(env->halt_cond);
3747 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3748 while (env->created == 0)
3749 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3750 tcg_cpu_thread = env->thread;
3751 tcg_halt_cond = env->halt_cond;
3752 } else {
3753 env->thread = tcg_cpu_thread;
3754 env->halt_cond = tcg_halt_cond;
3758 static void kvm_start_vcpu(CPUState *env)
3760 env->thread = qemu_mallocz(sizeof(QemuThread));
3761 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3762 qemu_cond_init(env->halt_cond);
3763 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3764 while (env->created == 0)
3765 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3768 void qemu_init_vcpu(void *_env)
3770 CPUState *env = _env;
3772 if (kvm_enabled())
3773 kvm_start_vcpu(env);
3774 else
3775 tcg_init_vcpu(env);
3776 env->nr_cores = smp_cores;
3777 env->nr_threads = smp_threads;
3780 void qemu_notify_event(void)
3782 qemu_event_increment();
3785 void vm_stop(int reason)
3787 QemuThread me;
3788 qemu_thread_self(&me);
3790 if (!qemu_thread_equal(&me, &io_thread)) {
3791 qemu_system_vmstop_request(reason);
3793 * FIXME: should not return to device code in case
3794 * vm_stop() has been requested.
3796 if (cpu_single_env) {
3797 cpu_exit(cpu_single_env);
3798 cpu_single_env->stop = 1;
3800 return;
3802 do_vm_stop(reason);
3805 #endif
3808 #ifdef _WIN32
3809 static void host_main_loop_wait(int *timeout)
3811 int ret, ret2, i;
3812 PollingEntry *pe;
3815 /* XXX: need to suppress polling by better using win32 events */
3816 ret = 0;
3817 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3818 ret |= pe->func(pe->opaque);
3820 if (ret == 0) {
3821 int err;
3822 WaitObjects *w = &wait_objects;
3824 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3825 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3826 if (w->func[ret - WAIT_OBJECT_0])
3827 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3829 /* Check for additional signaled events */
3830 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3832 /* Check if event is signaled */
3833 ret2 = WaitForSingleObject(w->events[i], 0);
3834 if(ret2 == WAIT_OBJECT_0) {
3835 if (w->func[i])
3836 w->func[i](w->opaque[i]);
3837 } else if (ret2 == WAIT_TIMEOUT) {
3838 } else {
3839 err = GetLastError();
3840 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3843 } else if (ret == WAIT_TIMEOUT) {
3844 } else {
3845 err = GetLastError();
3846 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3850 *timeout = 0;
3852 #else
3853 static void host_main_loop_wait(int *timeout)
3856 #endif
3858 void main_loop_wait(int timeout)
3860 IOHandlerRecord *ioh;
3861 fd_set rfds, wfds, xfds;
3862 int ret, nfds;
3863 struct timeval tv;
3865 qemu_bh_update_timeout(&timeout);
3867 host_main_loop_wait(&timeout);
3869 /* poll any events */
3870 /* XXX: separate device handlers from system ones */
3871 nfds = -1;
3872 FD_ZERO(&rfds);
3873 FD_ZERO(&wfds);
3874 FD_ZERO(&xfds);
3875 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3876 if (ioh->deleted)
3877 continue;
3878 if (ioh->fd_read &&
3879 (!ioh->fd_read_poll ||
3880 ioh->fd_read_poll(ioh->opaque) != 0)) {
3881 FD_SET(ioh->fd, &rfds);
3882 if (ioh->fd > nfds)
3883 nfds = ioh->fd;
3885 if (ioh->fd_write) {
3886 FD_SET(ioh->fd, &wfds);
3887 if (ioh->fd > nfds)
3888 nfds = ioh->fd;
3892 tv.tv_sec = timeout / 1000;
3893 tv.tv_usec = (timeout % 1000) * 1000;
3895 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3897 qemu_mutex_unlock_iothread();
3898 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3899 qemu_mutex_lock_iothread();
3900 if (ret > 0) {
3901 IOHandlerRecord **pioh;
3903 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3904 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3905 ioh->fd_read(ioh->opaque);
3907 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3908 ioh->fd_write(ioh->opaque);
3912 /* remove deleted IO handlers */
3913 pioh = &first_io_handler;
3914 while (*pioh) {
3915 ioh = *pioh;
3916 if (ioh->deleted) {
3917 *pioh = ioh->next;
3918 qemu_free(ioh);
3919 } else
3920 pioh = &ioh->next;
3924 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3926 /* rearm timer, if not periodic */
3927 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3928 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3929 qemu_rearm_alarm_timer(alarm_timer);
3932 /* vm time timers */
3933 if (vm_running) {
3934 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3935 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3936 qemu_get_clock(vm_clock));
3939 /* real time timers */
3940 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3941 qemu_get_clock(rt_clock));
3943 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3944 qemu_get_clock(host_clock));
3946 /* Check bottom-halves last in case any of the earlier events triggered
3947 them. */
3948 qemu_bh_poll();
3952 static int qemu_cpu_exec(CPUState *env)
3954 int ret;
3955 #ifdef CONFIG_PROFILER
3956 int64_t ti;
3957 #endif
3959 #ifdef CONFIG_PROFILER
3960 ti = profile_getclock();
3961 #endif
3962 if (use_icount) {
3963 int64_t count;
3964 int decr;
3965 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3966 env->icount_decr.u16.low = 0;
3967 env->icount_extra = 0;
3968 count = qemu_next_deadline();
3969 count = (count + (1 << icount_time_shift) - 1)
3970 >> icount_time_shift;
3971 qemu_icount += count;
3972 decr = (count > 0xffff) ? 0xffff : count;
3973 count -= decr;
3974 env->icount_decr.u16.low = decr;
3975 env->icount_extra = count;
3977 ret = cpu_exec(env);
3978 #ifdef CONFIG_PROFILER
3979 qemu_time += profile_getclock() - ti;
3980 #endif
3981 if (use_icount) {
3982 /* Fold pending instructions back into the
3983 instruction counter, and clear the interrupt flag. */
3984 qemu_icount -= (env->icount_decr.u16.low
3985 + env->icount_extra);
3986 env->icount_decr.u32 = 0;
3987 env->icount_extra = 0;
3989 return ret;
3992 static void tcg_cpu_exec(void)
3994 int ret = 0;
3996 if (next_cpu == NULL)
3997 next_cpu = first_cpu;
3998 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3999 CPUState *env = cur_cpu = next_cpu;
4001 if (!vm_running)
4002 break;
4003 if (timer_alarm_pending) {
4004 timer_alarm_pending = 0;
4005 break;
4007 if (cpu_can_run(env))
4008 ret = qemu_cpu_exec(env);
4009 if (ret == EXCP_DEBUG) {
4010 gdb_set_stop_cpu(env);
4011 debug_requested = 1;
4012 break;
4017 static int cpu_has_work(CPUState *env)
4019 if (env->stop)
4020 return 1;
4021 if (env->stopped)
4022 return 0;
4023 if (!env->halted)
4024 return 1;
4025 if (qemu_cpu_has_work(env))
4026 return 1;
4027 return 0;
4030 static int tcg_has_work(void)
4032 CPUState *env;
4034 for (env = first_cpu; env != NULL; env = env->next_cpu)
4035 if (cpu_has_work(env))
4036 return 1;
4037 return 0;
4040 static int qemu_calculate_timeout(void)
4042 #ifndef CONFIG_IOTHREAD
4043 int timeout;
4045 if (!vm_running)
4046 timeout = 5000;
4047 else if (tcg_has_work())
4048 timeout = 0;
4049 else if (!use_icount)
4050 timeout = 5000;
4051 else {
4052 /* XXX: use timeout computed from timers */
4053 int64_t add;
4054 int64_t delta;
4055 /* Advance virtual time to the next event. */
4056 if (use_icount == 1) {
4057 /* When not using an adaptive execution frequency
4058 we tend to get badly out of sync with real time,
4059 so just delay for a reasonable amount of time. */
4060 delta = 0;
4061 } else {
4062 delta = cpu_get_icount() - cpu_get_clock();
4064 if (delta > 0) {
4065 /* If virtual time is ahead of real time then just
4066 wait for IO. */
4067 timeout = (delta / 1000000) + 1;
4068 } else {
4069 /* Wait for either IO to occur or the next
4070 timer event. */
4071 add = qemu_next_deadline();
4072 /* We advance the timer before checking for IO.
4073 Limit the amount we advance so that early IO
4074 activity won't get the guest too far ahead. */
4075 if (add > 10000000)
4076 add = 10000000;
4077 delta += add;
4078 add = (add + (1 << icount_time_shift) - 1)
4079 >> icount_time_shift;
4080 qemu_icount += add;
4081 timeout = delta / 1000000;
4082 if (timeout < 0)
4083 timeout = 0;
4087 return timeout;
4088 #else /* CONFIG_IOTHREAD */
4089 return 1000;
4090 #endif
4093 static int vm_can_run(void)
4095 if (powerdown_requested)
4096 return 0;
4097 if (reset_requested)
4098 return 0;
4099 if (shutdown_requested)
4100 return 0;
4101 if (debug_requested)
4102 return 0;
4103 return 1;
4106 qemu_irq qemu_system_powerdown;
4108 static void main_loop(void)
4110 int r;
4112 #ifdef CONFIG_IOTHREAD
4113 qemu_system_ready = 1;
4114 qemu_cond_broadcast(&qemu_system_cond);
4115 #endif
4117 for (;;) {
4118 do {
4119 #ifdef CONFIG_PROFILER
4120 int64_t ti;
4121 #endif
4122 #ifndef CONFIG_IOTHREAD
4123 tcg_cpu_exec();
4124 #endif
4125 #ifdef CONFIG_PROFILER
4126 ti = profile_getclock();
4127 #endif
4128 main_loop_wait(qemu_calculate_timeout());
4129 #ifdef CONFIG_PROFILER
4130 dev_time += profile_getclock() - ti;
4131 #endif
4132 } while (vm_can_run());
4134 if (qemu_debug_requested()) {
4135 monitor_protocol_event(QEVENT_DEBUG, NULL);
4136 vm_stop(EXCP_DEBUG);
4138 if (qemu_shutdown_requested()) {
4139 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
4140 if (no_shutdown) {
4141 vm_stop(0);
4142 no_shutdown = 0;
4143 } else
4144 break;
4146 if (qemu_reset_requested()) {
4147 monitor_protocol_event(QEVENT_RESET, NULL);
4148 pause_all_vcpus();
4149 qemu_system_reset();
4150 resume_all_vcpus();
4152 if (qemu_powerdown_requested()) {
4153 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
4154 qemu_irq_raise(qemu_system_powerdown);
4156 if ((r = qemu_vmstop_requested())) {
4157 monitor_protocol_event(QEVENT_STOP, NULL);
4158 vm_stop(r);
4161 pause_all_vcpus();
4164 static void version(void)
4166 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4169 static void help(int exitcode)
4171 version();
4172 printf("usage: %s [options] [disk_image]\n"
4173 "\n"
4174 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4175 "\n"
4176 #define DEF(option, opt_arg, opt_enum, opt_help) \
4177 opt_help
4178 #define DEFHEADING(text) stringify(text) "\n"
4179 #include "qemu-options.h"
4180 #undef DEF
4181 #undef DEFHEADING
4182 #undef GEN_DOCS
4183 "\n"
4184 "During emulation, the following keys are useful:\n"
4185 "ctrl-alt-f toggle full screen\n"
4186 "ctrl-alt-n switch to virtual console 'n'\n"
4187 "ctrl-alt toggle mouse and keyboard grab\n"
4188 "\n"
4189 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4191 "qemu",
4192 DEFAULT_RAM_SIZE,
4193 #ifndef _WIN32
4194 DEFAULT_NETWORK_SCRIPT,
4195 DEFAULT_NETWORK_DOWN_SCRIPT,
4196 #endif
4197 DEFAULT_GDBSTUB_PORT,
4198 "/tmp/qemu.log");
4199 exit(exitcode);
4202 #define HAS_ARG 0x0001
4204 enum {
4205 #define DEF(option, opt_arg, opt_enum, opt_help) \
4206 opt_enum,
4207 #define DEFHEADING(text)
4208 #include "qemu-options.h"
4209 #undef DEF
4210 #undef DEFHEADING
4211 #undef GEN_DOCS
4214 typedef struct QEMUOption {
4215 const char *name;
4216 int flags;
4217 int index;
4218 } QEMUOption;
4220 static const QEMUOption qemu_options[] = {
4221 { "h", 0, QEMU_OPTION_h },
4222 #define DEF(option, opt_arg, opt_enum, opt_help) \
4223 { option, opt_arg, opt_enum },
4224 #define DEFHEADING(text)
4225 #include "qemu-options.h"
4226 #undef DEF
4227 #undef DEFHEADING
4228 #undef GEN_DOCS
4229 { NULL },
4232 #ifdef HAS_AUDIO
4233 struct soundhw soundhw[] = {
4234 #ifdef HAS_AUDIO_CHOICE
4235 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4237 "pcspk",
4238 "PC speaker",
4241 { .init_isa = pcspk_audio_init }
4243 #endif
4245 #ifdef CONFIG_SB16
4247 "sb16",
4248 "Creative Sound Blaster 16",
4251 { .init_isa = SB16_init }
4253 #endif
4255 #ifdef CONFIG_CS4231A
4257 "cs4231a",
4258 "CS4231A",
4261 { .init_isa = cs4231a_init }
4263 #endif
4265 #ifdef CONFIG_ADLIB
4267 "adlib",
4268 #ifdef HAS_YMF262
4269 "Yamaha YMF262 (OPL3)",
4270 #else
4271 "Yamaha YM3812 (OPL2)",
4272 #endif
4275 { .init_isa = Adlib_init }
4277 #endif
4279 #ifdef CONFIG_GUS
4281 "gus",
4282 "Gravis Ultrasound GF1",
4285 { .init_isa = GUS_init }
4287 #endif
4289 #ifdef CONFIG_AC97
4291 "ac97",
4292 "Intel 82801AA AC97 Audio",
4295 { .init_pci = ac97_init }
4297 #endif
4299 #ifdef CONFIG_ES1370
4301 "es1370",
4302 "ENSONIQ AudioPCI ES1370",
4305 { .init_pci = es1370_init }
4307 #endif
4309 #endif /* HAS_AUDIO_CHOICE */
4311 { NULL, NULL, 0, 0, { NULL } }
4314 static void select_soundhw (const char *optarg)
4316 struct soundhw *c;
4318 if (*optarg == '?') {
4319 show_valid_cards:
4321 printf ("Valid sound card names (comma separated):\n");
4322 for (c = soundhw; c->name; ++c) {
4323 printf ("%-11s %s\n", c->name, c->descr);
4325 printf ("\n-soundhw all will enable all of the above\n");
4326 exit (*optarg != '?');
4328 else {
4329 size_t l;
4330 const char *p;
4331 char *e;
4332 int bad_card = 0;
4334 if (!strcmp (optarg, "all")) {
4335 for (c = soundhw; c->name; ++c) {
4336 c->enabled = 1;
4338 return;
4341 p = optarg;
4342 while (*p) {
4343 e = strchr (p, ',');
4344 l = !e ? strlen (p) : (size_t) (e - p);
4346 for (c = soundhw; c->name; ++c) {
4347 if (!strncmp (c->name, p, l) && !c->name[l]) {
4348 c->enabled = 1;
4349 break;
4353 if (!c->name) {
4354 if (l > 80) {
4355 fprintf (stderr,
4356 "Unknown sound card name (too big to show)\n");
4358 else {
4359 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4360 (int) l, p);
4362 bad_card = 1;
4364 p += l + (e != NULL);
4367 if (bad_card)
4368 goto show_valid_cards;
4371 #endif
4373 static void select_vgahw (const char *p)
4375 const char *opts;
4377 default_vga = 0;
4378 vga_interface_type = VGA_NONE;
4379 if (strstart(p, "std", &opts)) {
4380 vga_interface_type = VGA_STD;
4381 } else if (strstart(p, "cirrus", &opts)) {
4382 vga_interface_type = VGA_CIRRUS;
4383 } else if (strstart(p, "vmware", &opts)) {
4384 vga_interface_type = VGA_VMWARE;
4385 } else if (strstart(p, "xenfb", &opts)) {
4386 vga_interface_type = VGA_XENFB;
4387 } else if (!strstart(p, "none", &opts)) {
4388 invalid_vga:
4389 fprintf(stderr, "Unknown vga type: %s\n", p);
4390 exit(1);
4392 while (*opts) {
4393 const char *nextopt;
4395 if (strstart(opts, ",retrace=", &nextopt)) {
4396 opts = nextopt;
4397 if (strstart(opts, "dumb", &nextopt))
4398 vga_retrace_method = VGA_RETRACE_DUMB;
4399 else if (strstart(opts, "precise", &nextopt))
4400 vga_retrace_method = VGA_RETRACE_PRECISE;
4401 else goto invalid_vga;
4402 } else goto invalid_vga;
4403 opts = nextopt;
4407 #ifdef TARGET_I386
4408 static int balloon_parse(const char *arg)
4410 QemuOpts *opts;
4412 if (strcmp(arg, "none") == 0) {
4413 return 0;
4416 if (!strncmp(arg, "virtio", 6)) {
4417 if (arg[6] == ',') {
4418 /* have params -> parse them */
4419 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4420 if (!opts)
4421 return -1;
4422 } else {
4423 /* create empty opts */
4424 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4426 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4427 return 0;
4430 return -1;
4432 #endif
4434 #ifdef _WIN32
4435 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4437 exit(STATUS_CONTROL_C_EXIT);
4438 return TRUE;
4440 #endif
4442 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4444 int ret;
4446 if(strlen(str) != 36)
4447 return -1;
4449 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4450 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4451 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4453 if(ret != 16)
4454 return -1;
4456 #ifdef TARGET_I386
4457 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4458 #endif
4460 return 0;
4463 #ifndef _WIN32
4465 static void termsig_handler(int signal)
4467 qemu_system_shutdown_request();
4470 static void sigchld_handler(int signal)
4472 waitpid(-1, NULL, WNOHANG);
4475 static void sighandler_setup(void)
4477 struct sigaction act;
4479 memset(&act, 0, sizeof(act));
4480 act.sa_handler = termsig_handler;
4481 sigaction(SIGINT, &act, NULL);
4482 sigaction(SIGHUP, &act, NULL);
4483 sigaction(SIGTERM, &act, NULL);
4485 act.sa_handler = sigchld_handler;
4486 act.sa_flags = SA_NOCLDSTOP;
4487 sigaction(SIGCHLD, &act, NULL);
4490 #endif
4492 #ifdef _WIN32
4493 /* Look for support files in the same directory as the executable. */
4494 static char *find_datadir(const char *argv0)
4496 char *p;
4497 char buf[MAX_PATH];
4498 DWORD len;
4500 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4501 if (len == 0) {
4502 return NULL;
4505 buf[len] = 0;
4506 p = buf + len - 1;
4507 while (p != buf && *p != '\\')
4508 p--;
4509 *p = 0;
4510 if (access(buf, R_OK) == 0) {
4511 return qemu_strdup(buf);
4513 return NULL;
4515 #else /* !_WIN32 */
4517 /* Find a likely location for support files using the location of the binary.
4518 For installed binaries this will be "$bindir/../share/qemu". When
4519 running from the build tree this will be "$bindir/../pc-bios". */
4520 #define SHARE_SUFFIX "/share/qemu"
4521 #define BUILD_SUFFIX "/pc-bios"
4522 static char *find_datadir(const char *argv0)
4524 char *dir;
4525 char *p = NULL;
4526 char *res;
4527 char buf[PATH_MAX];
4528 size_t max_len;
4530 #if defined(__linux__)
4532 int len;
4533 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4534 if (len > 0) {
4535 buf[len] = 0;
4536 p = buf;
4539 #elif defined(__FreeBSD__)
4541 int len;
4542 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4543 if (len > 0) {
4544 buf[len] = 0;
4545 p = buf;
4548 #endif
4549 /* If we don't have any way of figuring out the actual executable
4550 location then try argv[0]. */
4551 if (!p) {
4552 p = realpath(argv0, buf);
4553 if (!p) {
4554 return NULL;
4557 dir = dirname(p);
4558 dir = dirname(dir);
4560 max_len = strlen(dir) +
4561 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4562 res = qemu_mallocz(max_len);
4563 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4564 if (access(res, R_OK)) {
4565 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4566 if (access(res, R_OK)) {
4567 qemu_free(res);
4568 res = NULL;
4572 return res;
4574 #undef SHARE_SUFFIX
4575 #undef BUILD_SUFFIX
4576 #endif
4578 char *qemu_find_file(int type, const char *name)
4580 int len;
4581 const char *subdir;
4582 char *buf;
4584 /* If name contains path separators then try it as a straight path. */
4585 if ((strchr(name, '/') || strchr(name, '\\'))
4586 && access(name, R_OK) == 0) {
4587 return qemu_strdup(name);
4589 switch (type) {
4590 case QEMU_FILE_TYPE_BIOS:
4591 subdir = "";
4592 break;
4593 case QEMU_FILE_TYPE_KEYMAP:
4594 subdir = "keymaps/";
4595 break;
4596 default:
4597 abort();
4599 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4600 buf = qemu_mallocz(len);
4601 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4602 if (access(buf, R_OK)) {
4603 qemu_free(buf);
4604 return NULL;
4606 return buf;
4609 static int device_init_func(QemuOpts *opts, void *opaque)
4611 DeviceState *dev;
4613 dev = qdev_device_add(opts);
4614 if (!dev)
4615 return -1;
4616 return 0;
4619 static int chardev_init_func(QemuOpts *opts, void *opaque)
4621 CharDriverState *chr;
4623 chr = qemu_chr_open_opts(opts, NULL);
4624 if (!chr)
4625 return -1;
4626 return 0;
4629 static int mon_init_func(QemuOpts *opts, void *opaque)
4631 CharDriverState *chr;
4632 const char *chardev;
4633 const char *mode;
4634 int flags;
4636 mode = qemu_opt_get(opts, "mode");
4637 if (mode == NULL) {
4638 mode = "readline";
4640 if (strcmp(mode, "readline") == 0) {
4641 flags = MONITOR_USE_READLINE;
4642 } else if (strcmp(mode, "control") == 0) {
4643 flags = MONITOR_USE_CONTROL;
4644 } else {
4645 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4646 exit(1);
4649 if (qemu_opt_get_bool(opts, "default", 0))
4650 flags |= MONITOR_IS_DEFAULT;
4652 chardev = qemu_opt_get(opts, "chardev");
4653 chr = qemu_chr_find(chardev);
4654 if (chr == NULL) {
4655 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4656 exit(1);
4659 monitor_init(chr, flags);
4660 return 0;
4663 static void monitor_parse(const char *optarg)
4665 static int monitor_device_index = 0;
4666 QemuOpts *opts;
4667 const char *p;
4668 char label[32];
4669 int def = 0;
4671 if (strstart(optarg, "chardev:", &p)) {
4672 snprintf(label, sizeof(label), "%s", p);
4673 } else {
4674 if (monitor_device_index) {
4675 snprintf(label, sizeof(label), "monitor%d",
4676 monitor_device_index);
4677 } else {
4678 snprintf(label, sizeof(label), "monitor");
4679 def = 1;
4681 opts = qemu_chr_parse_compat(label, optarg);
4682 if (!opts) {
4683 fprintf(stderr, "parse error: %s\n", optarg);
4684 exit(1);
4688 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4689 if (!opts) {
4690 fprintf(stderr, "duplicate chardev: %s\n", label);
4691 exit(1);
4693 qemu_opt_set(opts, "mode", "readline");
4694 qemu_opt_set(opts, "chardev", label);
4695 if (def)
4696 qemu_opt_set(opts, "default", "on");
4697 monitor_device_index++;
4700 struct device_config {
4701 enum {
4702 DEV_USB, /* -usbdevice */
4703 DEV_BT, /* -bt */
4704 DEV_SERIAL, /* -serial */
4705 DEV_PARALLEL, /* -parallel */
4706 } type;
4707 const char *cmdline;
4708 QTAILQ_ENTRY(device_config) next;
4710 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4712 static void add_device_config(int type, const char *cmdline)
4714 struct device_config *conf;
4716 conf = qemu_mallocz(sizeof(*conf));
4717 conf->type = type;
4718 conf->cmdline = cmdline;
4719 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4722 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4724 struct device_config *conf;
4725 int rc;
4727 QTAILQ_FOREACH(conf, &device_configs, next) {
4728 if (conf->type != type)
4729 continue;
4730 rc = func(conf->cmdline);
4731 if (0 != rc)
4732 return rc;
4734 return 0;
4737 static int serial_parse(const char *devname)
4739 static int index = 0;
4740 char label[32];
4742 if (strcmp(devname, "none") == 0)
4743 return 0;
4744 if (index == MAX_SERIAL_PORTS) {
4745 fprintf(stderr, "qemu: too many serial ports\n");
4746 exit(1);
4748 snprintf(label, sizeof(label), "serial%d", index);
4749 serial_hds[index] = qemu_chr_open(label, devname, NULL);
4750 if (!serial_hds[index]) {
4751 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4752 devname, strerror(errno));
4753 return -1;
4755 index++;
4756 return 0;
4759 static int parallel_parse(const char *devname)
4761 static int index = 0;
4762 char label[32];
4764 if (strcmp(devname, "none") == 0)
4765 return 0;
4766 if (index == MAX_PARALLEL_PORTS) {
4767 fprintf(stderr, "qemu: too many parallel ports\n");
4768 exit(1);
4770 snprintf(label, sizeof(label), "parallel%d", index);
4771 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4772 if (!parallel_hds[index]) {
4773 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4774 devname, strerror(errno));
4775 return -1;
4777 index++;
4778 return 0;
4781 int main(int argc, char **argv, char **envp)
4783 const char *gdbstub_dev = NULL;
4784 uint32_t boot_devices_bitmap = 0;
4785 int i;
4786 int snapshot, linux_boot, net_boot;
4787 const char *initrd_filename;
4788 const char *kernel_filename, *kernel_cmdline;
4789 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4790 DisplayState *ds;
4791 DisplayChangeListener *dcl;
4792 int cyls, heads, secs, translation;
4793 QemuOpts *hda_opts = NULL, *opts;
4794 int optind;
4795 const char *r, *optarg;
4796 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4797 int virtio_console_index;
4798 const char *loadvm = NULL;
4799 QEMUMachine *machine;
4800 const char *cpu_model;
4801 #ifndef _WIN32
4802 int fds[2];
4803 #endif
4804 int tb_size;
4805 const char *pid_file = NULL;
4806 const char *incoming = NULL;
4807 #ifndef _WIN32
4808 int fd = 0;
4809 struct passwd *pwd = NULL;
4810 const char *chroot_dir = NULL;
4811 const char *run_as = NULL;
4812 #endif
4813 CPUState *env;
4814 int show_vnc_port = 0;
4816 init_clocks();
4818 qemu_errors_to_file(stderr);
4819 qemu_cache_utils_init(envp);
4821 QLIST_INIT (&vm_change_state_head);
4822 #ifndef _WIN32
4824 struct sigaction act;
4825 sigfillset(&act.sa_mask);
4826 act.sa_flags = 0;
4827 act.sa_handler = SIG_IGN;
4828 sigaction(SIGPIPE, &act, NULL);
4830 #else
4831 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4832 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4833 QEMU to run on a single CPU */
4835 HANDLE h;
4836 DWORD mask, smask;
4837 int i;
4838 h = GetCurrentProcess();
4839 if (GetProcessAffinityMask(h, &mask, &smask)) {
4840 for(i = 0; i < 32; i++) {
4841 if (mask & (1 << i))
4842 break;
4844 if (i != 32) {
4845 mask = 1 << i;
4846 SetProcessAffinityMask(h, mask);
4850 #endif
4852 module_call_init(MODULE_INIT_MACHINE);
4853 machine = find_default_machine();
4854 cpu_model = NULL;
4855 initrd_filename = NULL;
4856 ram_size = 0;
4857 snapshot = 0;
4858 kernel_filename = NULL;
4859 kernel_cmdline = "";
4860 cyls = heads = secs = 0;
4861 translation = BIOS_ATA_TRANSLATION_AUTO;
4863 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4864 virtio_consoles[i] = NULL;
4865 virtio_console_index = 0;
4867 for (i = 0; i < MAX_NODES; i++) {
4868 node_mem[i] = 0;
4869 node_cpumask[i] = 0;
4872 nb_numa_nodes = 0;
4873 nb_nics = 0;
4875 tb_size = 0;
4876 autostart= 1;
4878 optind = 1;
4879 for(;;) {
4880 if (optind >= argc)
4881 break;
4882 r = argv[optind];
4883 if (r[0] != '-') {
4884 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4885 } else {
4886 const QEMUOption *popt;
4888 optind++;
4889 /* Treat --foo the same as -foo. */
4890 if (r[1] == '-')
4891 r++;
4892 popt = qemu_options;
4893 for(;;) {
4894 if (!popt->name) {
4895 fprintf(stderr, "%s: invalid option -- '%s'\n",
4896 argv[0], r);
4897 exit(1);
4899 if (!strcmp(popt->name, r + 1))
4900 break;
4901 popt++;
4903 if (popt->flags & HAS_ARG) {
4904 if (optind >= argc) {
4905 fprintf(stderr, "%s: option '%s' requires an argument\n",
4906 argv[0], r);
4907 exit(1);
4909 optarg = argv[optind++];
4910 } else {
4911 optarg = NULL;
4914 switch(popt->index) {
4915 case QEMU_OPTION_M:
4916 machine = find_machine(optarg);
4917 if (!machine) {
4918 QEMUMachine *m;
4919 printf("Supported machines are:\n");
4920 for(m = first_machine; m != NULL; m = m->next) {
4921 if (m->alias)
4922 printf("%-10s %s (alias of %s)\n",
4923 m->alias, m->desc, m->name);
4924 printf("%-10s %s%s\n",
4925 m->name, m->desc,
4926 m->is_default ? " (default)" : "");
4928 exit(*optarg != '?');
4930 break;
4931 case QEMU_OPTION_cpu:
4932 /* hw initialization will check this */
4933 if (*optarg == '?') {
4934 /* XXX: implement xxx_cpu_list for targets that still miss it */
4935 #if defined(cpu_list)
4936 cpu_list(stdout, &fprintf);
4937 #endif
4938 exit(0);
4939 } else {
4940 cpu_model = optarg;
4942 break;
4943 case QEMU_OPTION_initrd:
4944 initrd_filename = optarg;
4945 break;
4946 case QEMU_OPTION_hda:
4947 if (cyls == 0)
4948 hda_opts = drive_add(optarg, HD_ALIAS, 0);
4949 else
4950 hda_opts = drive_add(optarg, HD_ALIAS
4951 ",cyls=%d,heads=%d,secs=%d%s",
4952 0, cyls, heads, secs,
4953 translation == BIOS_ATA_TRANSLATION_LBA ?
4954 ",trans=lba" :
4955 translation == BIOS_ATA_TRANSLATION_NONE ?
4956 ",trans=none" : "");
4957 break;
4958 case QEMU_OPTION_hdb:
4959 case QEMU_OPTION_hdc:
4960 case QEMU_OPTION_hdd:
4961 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4962 break;
4963 case QEMU_OPTION_drive:
4964 drive_add(NULL, "%s", optarg);
4965 break;
4966 case QEMU_OPTION_set:
4967 if (qemu_set_option(optarg) != 0)
4968 exit(1);
4969 break;
4970 case QEMU_OPTION_global:
4971 if (qemu_global_option(optarg) != 0)
4972 exit(1);
4973 break;
4974 case QEMU_OPTION_mtdblock:
4975 drive_add(optarg, MTD_ALIAS);
4976 break;
4977 case QEMU_OPTION_sd:
4978 drive_add(optarg, SD_ALIAS);
4979 break;
4980 case QEMU_OPTION_pflash:
4981 drive_add(optarg, PFLASH_ALIAS);
4982 break;
4983 case QEMU_OPTION_snapshot:
4984 snapshot = 1;
4985 break;
4986 case QEMU_OPTION_hdachs:
4988 const char *p;
4989 p = optarg;
4990 cyls = strtol(p, (char **)&p, 0);
4991 if (cyls < 1 || cyls > 16383)
4992 goto chs_fail;
4993 if (*p != ',')
4994 goto chs_fail;
4995 p++;
4996 heads = strtol(p, (char **)&p, 0);
4997 if (heads < 1 || heads > 16)
4998 goto chs_fail;
4999 if (*p != ',')
5000 goto chs_fail;
5001 p++;
5002 secs = strtol(p, (char **)&p, 0);
5003 if (secs < 1 || secs > 63)
5004 goto chs_fail;
5005 if (*p == ',') {
5006 p++;
5007 if (!strcmp(p, "none"))
5008 translation = BIOS_ATA_TRANSLATION_NONE;
5009 else if (!strcmp(p, "lba"))
5010 translation = BIOS_ATA_TRANSLATION_LBA;
5011 else if (!strcmp(p, "auto"))
5012 translation = BIOS_ATA_TRANSLATION_AUTO;
5013 else
5014 goto chs_fail;
5015 } else if (*p != '\0') {
5016 chs_fail:
5017 fprintf(stderr, "qemu: invalid physical CHS format\n");
5018 exit(1);
5020 if (hda_opts != NULL) {
5021 char num[16];
5022 snprintf(num, sizeof(num), "%d", cyls);
5023 qemu_opt_set(hda_opts, "cyls", num);
5024 snprintf(num, sizeof(num), "%d", heads);
5025 qemu_opt_set(hda_opts, "heads", num);
5026 snprintf(num, sizeof(num), "%d", secs);
5027 qemu_opt_set(hda_opts, "secs", num);
5028 if (translation == BIOS_ATA_TRANSLATION_LBA)
5029 qemu_opt_set(hda_opts, "trans", "lba");
5030 if (translation == BIOS_ATA_TRANSLATION_NONE)
5031 qemu_opt_set(hda_opts, "trans", "none");
5034 break;
5035 case QEMU_OPTION_numa:
5036 if (nb_numa_nodes >= MAX_NODES) {
5037 fprintf(stderr, "qemu: too many NUMA nodes\n");
5038 exit(1);
5040 numa_add(optarg);
5041 break;
5042 case QEMU_OPTION_nographic:
5043 display_type = DT_NOGRAPHIC;
5044 break;
5045 #ifdef CONFIG_CURSES
5046 case QEMU_OPTION_curses:
5047 display_type = DT_CURSES;
5048 break;
5049 #endif
5050 case QEMU_OPTION_portrait:
5051 graphic_rotate = 1;
5052 break;
5053 case QEMU_OPTION_kernel:
5054 kernel_filename = optarg;
5055 break;
5056 case QEMU_OPTION_append:
5057 kernel_cmdline = optarg;
5058 break;
5059 case QEMU_OPTION_cdrom:
5060 drive_add(optarg, CDROM_ALIAS);
5061 break;
5062 case QEMU_OPTION_boot:
5064 static const char * const params[] = {
5065 "order", "once", "menu", NULL
5067 char buf[sizeof(boot_devices)];
5068 char *standard_boot_devices;
5069 int legacy = 0;
5071 if (!strchr(optarg, '=')) {
5072 legacy = 1;
5073 pstrcpy(buf, sizeof(buf), optarg);
5074 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5075 fprintf(stderr,
5076 "qemu: unknown boot parameter '%s' in '%s'\n",
5077 buf, optarg);
5078 exit(1);
5081 if (legacy ||
5082 get_param_value(buf, sizeof(buf), "order", optarg)) {
5083 boot_devices_bitmap = parse_bootdevices(buf);
5084 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5086 if (!legacy) {
5087 if (get_param_value(buf, sizeof(buf),
5088 "once", optarg)) {
5089 boot_devices_bitmap |= parse_bootdevices(buf);
5090 standard_boot_devices = qemu_strdup(boot_devices);
5091 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5092 qemu_register_reset(restore_boot_devices,
5093 standard_boot_devices);
5095 if (get_param_value(buf, sizeof(buf),
5096 "menu", optarg)) {
5097 if (!strcmp(buf, "on")) {
5098 boot_menu = 1;
5099 } else if (!strcmp(buf, "off")) {
5100 boot_menu = 0;
5101 } else {
5102 fprintf(stderr,
5103 "qemu: invalid option value '%s'\n",
5104 buf);
5105 exit(1);
5110 break;
5111 case QEMU_OPTION_fda:
5112 case QEMU_OPTION_fdb:
5113 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5114 break;
5115 #ifdef TARGET_I386
5116 case QEMU_OPTION_no_fd_bootchk:
5117 fd_bootchk = 0;
5118 break;
5119 #endif
5120 case QEMU_OPTION_netdev:
5121 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
5122 exit(1);
5124 break;
5125 case QEMU_OPTION_net:
5126 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
5127 exit(1);
5129 break;
5130 #ifdef CONFIG_SLIRP
5131 case QEMU_OPTION_tftp:
5132 legacy_tftp_prefix = optarg;
5133 break;
5134 case QEMU_OPTION_bootp:
5135 legacy_bootp_filename = optarg;
5136 break;
5137 #ifndef _WIN32
5138 case QEMU_OPTION_smb:
5139 if (net_slirp_smb(optarg) < 0)
5140 exit(1);
5141 break;
5142 #endif
5143 case QEMU_OPTION_redir:
5144 if (net_slirp_redir(optarg) < 0)
5145 exit(1);
5146 break;
5147 #endif
5148 case QEMU_OPTION_bt:
5149 add_device_config(DEV_BT, optarg);
5150 break;
5151 #ifdef HAS_AUDIO
5152 case QEMU_OPTION_audio_help:
5153 AUD_help ();
5154 exit (0);
5155 break;
5156 case QEMU_OPTION_soundhw:
5157 select_soundhw (optarg);
5158 break;
5159 #endif
5160 case QEMU_OPTION_h:
5161 help(0);
5162 break;
5163 case QEMU_OPTION_version:
5164 version();
5165 exit(0);
5166 break;
5167 case QEMU_OPTION_m: {
5168 uint64_t value;
5169 char *ptr;
5171 value = strtoul(optarg, &ptr, 10);
5172 switch (*ptr) {
5173 case 0: case 'M': case 'm':
5174 value <<= 20;
5175 break;
5176 case 'G': case 'g':
5177 value <<= 30;
5178 break;
5179 default:
5180 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5181 exit(1);
5184 /* On 32-bit hosts, QEMU is limited by virtual address space */
5185 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5186 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5187 exit(1);
5189 if (value != (uint64_t)(ram_addr_t)value) {
5190 fprintf(stderr, "qemu: ram size too large\n");
5191 exit(1);
5193 ram_size = value;
5194 break;
5196 case QEMU_OPTION_d:
5198 int mask;
5199 const CPULogItem *item;
5201 mask = cpu_str_to_log_mask(optarg);
5202 if (!mask) {
5203 printf("Log items (comma separated):\n");
5204 for(item = cpu_log_items; item->mask != 0; item++) {
5205 printf("%-10s %s\n", item->name, item->help);
5207 exit(1);
5209 cpu_set_log(mask);
5211 break;
5212 case QEMU_OPTION_s:
5213 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5214 break;
5215 case QEMU_OPTION_gdb:
5216 gdbstub_dev = optarg;
5217 break;
5218 case QEMU_OPTION_L:
5219 data_dir = optarg;
5220 break;
5221 case QEMU_OPTION_bios:
5222 bios_name = optarg;
5223 break;
5224 case QEMU_OPTION_singlestep:
5225 singlestep = 1;
5226 break;
5227 case QEMU_OPTION_S:
5228 autostart = 0;
5229 break;
5230 case QEMU_OPTION_k:
5231 keyboard_layout = optarg;
5232 break;
5233 case QEMU_OPTION_localtime:
5234 rtc_utc = 0;
5235 break;
5236 case QEMU_OPTION_vga:
5237 select_vgahw (optarg);
5238 break;
5239 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5240 case QEMU_OPTION_g:
5242 const char *p;
5243 int w, h, depth;
5244 p = optarg;
5245 w = strtol(p, (char **)&p, 10);
5246 if (w <= 0) {
5247 graphic_error:
5248 fprintf(stderr, "qemu: invalid resolution or depth\n");
5249 exit(1);
5251 if (*p != 'x')
5252 goto graphic_error;
5253 p++;
5254 h = strtol(p, (char **)&p, 10);
5255 if (h <= 0)
5256 goto graphic_error;
5257 if (*p == 'x') {
5258 p++;
5259 depth = strtol(p, (char **)&p, 10);
5260 if (depth != 8 && depth != 15 && depth != 16 &&
5261 depth != 24 && depth != 32)
5262 goto graphic_error;
5263 } else if (*p == '\0') {
5264 depth = graphic_depth;
5265 } else {
5266 goto graphic_error;
5269 graphic_width = w;
5270 graphic_height = h;
5271 graphic_depth = depth;
5273 break;
5274 #endif
5275 case QEMU_OPTION_echr:
5277 char *r;
5278 term_escape_char = strtol(optarg, &r, 0);
5279 if (r == optarg)
5280 printf("Bad argument to echr\n");
5281 break;
5283 case QEMU_OPTION_monitor:
5284 monitor_parse(optarg);
5285 default_monitor = 0;
5286 break;
5287 case QEMU_OPTION_mon:
5288 opts = qemu_opts_parse(&qemu_mon_opts, optarg, "chardev");
5289 if (!opts) {
5290 fprintf(stderr, "parse error: %s\n", optarg);
5291 exit(1);
5293 default_monitor = 0;
5294 break;
5295 case QEMU_OPTION_chardev:
5296 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5297 if (!opts) {
5298 fprintf(stderr, "parse error: %s\n", optarg);
5299 exit(1);
5301 break;
5302 case QEMU_OPTION_serial:
5303 add_device_config(DEV_SERIAL, optarg);
5304 default_serial = 0;
5305 break;
5306 case QEMU_OPTION_watchdog:
5307 if (watchdog) {
5308 fprintf(stderr,
5309 "qemu: only one watchdog option may be given\n");
5310 return 1;
5312 watchdog = optarg;
5313 break;
5314 case QEMU_OPTION_watchdog_action:
5315 if (select_watchdog_action(optarg) == -1) {
5316 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5317 exit(1);
5319 break;
5320 case QEMU_OPTION_virtiocon:
5321 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5322 fprintf(stderr, "qemu: too many virtio consoles\n");
5323 exit(1);
5325 virtio_consoles[virtio_console_index] = optarg;
5326 virtio_console_index++;
5327 break;
5328 case QEMU_OPTION_parallel:
5329 add_device_config(DEV_PARALLEL, optarg);
5330 default_parallel = 0;
5331 break;
5332 case QEMU_OPTION_loadvm:
5333 loadvm = optarg;
5334 break;
5335 case QEMU_OPTION_full_screen:
5336 full_screen = 1;
5337 break;
5338 #ifdef CONFIG_SDL
5339 case QEMU_OPTION_no_frame:
5340 no_frame = 1;
5341 break;
5342 case QEMU_OPTION_alt_grab:
5343 alt_grab = 1;
5344 break;
5345 case QEMU_OPTION_ctrl_grab:
5346 ctrl_grab = 1;
5347 break;
5348 case QEMU_OPTION_no_quit:
5349 no_quit = 1;
5350 break;
5351 case QEMU_OPTION_sdl:
5352 display_type = DT_SDL;
5353 break;
5354 #endif
5355 case QEMU_OPTION_pidfile:
5356 pid_file = optarg;
5357 break;
5358 #ifdef TARGET_I386
5359 case QEMU_OPTION_win2k_hack:
5360 win2k_install_hack = 1;
5361 break;
5362 case QEMU_OPTION_rtc_td_hack:
5363 rtc_td_hack = 1;
5364 break;
5365 case QEMU_OPTION_acpitable:
5366 if(acpi_table_add(optarg) < 0) {
5367 fprintf(stderr, "Wrong acpi table provided\n");
5368 exit(1);
5370 break;
5371 case QEMU_OPTION_smbios:
5372 if(smbios_entry_add(optarg) < 0) {
5373 fprintf(stderr, "Wrong smbios provided\n");
5374 exit(1);
5376 break;
5377 #endif
5378 #ifdef CONFIG_KVM
5379 case QEMU_OPTION_enable_kvm:
5380 kvm_allowed = 1;
5381 break;
5382 #endif
5383 case QEMU_OPTION_usb:
5384 usb_enabled = 1;
5385 break;
5386 case QEMU_OPTION_usbdevice:
5387 usb_enabled = 1;
5388 add_device_config(DEV_USB, optarg);
5389 break;
5390 case QEMU_OPTION_device:
5391 if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5392 exit(1);
5394 break;
5395 case QEMU_OPTION_smp:
5396 smp_parse(optarg);
5397 if (smp_cpus < 1) {
5398 fprintf(stderr, "Invalid number of CPUs\n");
5399 exit(1);
5401 if (max_cpus < smp_cpus) {
5402 fprintf(stderr, "maxcpus must be equal to or greater than "
5403 "smp\n");
5404 exit(1);
5406 if (max_cpus > 255) {
5407 fprintf(stderr, "Unsupported number of maxcpus\n");
5408 exit(1);
5410 break;
5411 case QEMU_OPTION_vnc:
5412 display_type = DT_VNC;
5413 vnc_display = optarg;
5414 break;
5415 #ifdef TARGET_I386
5416 case QEMU_OPTION_no_acpi:
5417 acpi_enabled = 0;
5418 break;
5419 case QEMU_OPTION_no_hpet:
5420 no_hpet = 1;
5421 break;
5422 case QEMU_OPTION_balloon:
5423 if (balloon_parse(optarg) < 0) {
5424 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5425 exit(1);
5427 break;
5428 #endif
5429 case QEMU_OPTION_no_reboot:
5430 no_reboot = 1;
5431 break;
5432 case QEMU_OPTION_no_shutdown:
5433 no_shutdown = 1;
5434 break;
5435 case QEMU_OPTION_show_cursor:
5436 cursor_hide = 0;
5437 break;
5438 case QEMU_OPTION_uuid:
5439 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5440 fprintf(stderr, "Fail to parse UUID string."
5441 " Wrong format.\n");
5442 exit(1);
5444 break;
5445 #ifndef _WIN32
5446 case QEMU_OPTION_daemonize:
5447 daemonize = 1;
5448 break;
5449 #endif
5450 case QEMU_OPTION_option_rom:
5451 if (nb_option_roms >= MAX_OPTION_ROMS) {
5452 fprintf(stderr, "Too many option ROMs\n");
5453 exit(1);
5455 option_rom[nb_option_roms] = optarg;
5456 nb_option_roms++;
5457 break;
5458 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5459 case QEMU_OPTION_semihosting:
5460 semihosting_enabled = 1;
5461 break;
5462 #endif
5463 case QEMU_OPTION_name:
5464 qemu_name = qemu_strdup(optarg);
5466 char *p = strchr(qemu_name, ',');
5467 if (p != NULL) {
5468 *p++ = 0;
5469 if (strncmp(p, "process=", 8)) {
5470 fprintf(stderr, "Unknown subargument %s to -name", p);
5471 exit(1);
5473 p += 8;
5474 set_proc_name(p);
5477 break;
5478 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5479 case QEMU_OPTION_prom_env:
5480 if (nb_prom_envs >= MAX_PROM_ENVS) {
5481 fprintf(stderr, "Too many prom variables\n");
5482 exit(1);
5484 prom_envs[nb_prom_envs] = optarg;
5485 nb_prom_envs++;
5486 break;
5487 #endif
5488 #ifdef TARGET_ARM
5489 case QEMU_OPTION_old_param:
5490 old_param = 1;
5491 break;
5492 #endif
5493 case QEMU_OPTION_clock:
5494 configure_alarms(optarg);
5495 break;
5496 case QEMU_OPTION_startdate:
5497 configure_rtc_date_offset(optarg, 1);
5498 break;
5499 case QEMU_OPTION_rtc:
5500 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5501 if (!opts) {
5502 fprintf(stderr, "parse error: %s\n", optarg);
5503 exit(1);
5505 configure_rtc(opts);
5506 break;
5507 case QEMU_OPTION_tb_size:
5508 tb_size = strtol(optarg, NULL, 0);
5509 if (tb_size < 0)
5510 tb_size = 0;
5511 break;
5512 case QEMU_OPTION_icount:
5513 use_icount = 1;
5514 if (strcmp(optarg, "auto") == 0) {
5515 icount_time_shift = -1;
5516 } else {
5517 icount_time_shift = strtol(optarg, NULL, 0);
5519 break;
5520 case QEMU_OPTION_incoming:
5521 incoming = optarg;
5522 break;
5523 case QEMU_OPTION_nodefaults:
5524 default_serial = 0;
5525 default_parallel = 0;
5526 default_monitor = 0;
5527 default_vga = 0;
5528 default_net = 0;
5529 default_drive = 0;
5530 break;
5531 #ifndef _WIN32
5532 case QEMU_OPTION_chroot:
5533 chroot_dir = optarg;
5534 break;
5535 case QEMU_OPTION_runas:
5536 run_as = optarg;
5537 break;
5538 #endif
5539 #ifdef CONFIG_XEN
5540 case QEMU_OPTION_xen_domid:
5541 xen_domid = atoi(optarg);
5542 break;
5543 case QEMU_OPTION_xen_create:
5544 xen_mode = XEN_CREATE;
5545 break;
5546 case QEMU_OPTION_xen_attach:
5547 xen_mode = XEN_ATTACH;
5548 break;
5549 #endif
5550 case QEMU_OPTION_readconfig:
5552 FILE *fp;
5553 fp = fopen(optarg, "r");
5554 if (fp == NULL) {
5555 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5556 exit(1);
5558 if (qemu_config_parse(fp) != 0) {
5559 exit(1);
5561 fclose(fp);
5562 break;
5564 case QEMU_OPTION_writeconfig:
5566 FILE *fp;
5567 if (strcmp(optarg, "-") == 0) {
5568 fp = stdout;
5569 } else {
5570 fp = fopen(optarg, "w");
5571 if (fp == NULL) {
5572 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5573 exit(1);
5576 qemu_config_write(fp);
5577 fclose(fp);
5578 break;
5584 /* If no data_dir is specified then try to find it relative to the
5585 executable path. */
5586 if (!data_dir) {
5587 data_dir = find_datadir(argv[0]);
5589 /* If all else fails use the install patch specified when building. */
5590 if (!data_dir) {
5591 data_dir = CONFIG_QEMU_SHAREDIR;
5595 * Default to max_cpus = smp_cpus, in case the user doesn't
5596 * specify a max_cpus value.
5598 if (!max_cpus)
5599 max_cpus = smp_cpus;
5601 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5602 if (smp_cpus > machine->max_cpus) {
5603 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5604 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5605 machine->max_cpus);
5606 exit(1);
5609 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5611 if (display_type == DT_NOGRAPHIC) {
5612 if (default_parallel)
5613 add_device_config(DEV_PARALLEL, "null");
5614 if (default_serial && default_monitor) {
5615 add_device_config(DEV_SERIAL, "mon:stdio");
5616 } else {
5617 if (default_serial)
5618 add_device_config(DEV_SERIAL, "stdio");
5619 if (default_monitor)
5620 monitor_parse("stdio");
5622 } else {
5623 if (default_serial)
5624 add_device_config(DEV_SERIAL, "vc:80Cx24C");
5625 if (default_parallel)
5626 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
5627 if (default_monitor)
5628 monitor_parse("vc:80Cx24C");
5630 if (default_vga)
5631 vga_interface_type = VGA_CIRRUS;
5633 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5634 exit(1);
5636 #ifndef _WIN32
5637 if (daemonize) {
5638 pid_t pid;
5640 if (pipe(fds) == -1)
5641 exit(1);
5643 pid = fork();
5644 if (pid > 0) {
5645 uint8_t status;
5646 ssize_t len;
5648 close(fds[1]);
5650 again:
5651 len = read(fds[0], &status, 1);
5652 if (len == -1 && (errno == EINTR))
5653 goto again;
5655 if (len != 1)
5656 exit(1);
5657 else if (status == 1) {
5658 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5659 exit(1);
5660 } else
5661 exit(0);
5662 } else if (pid < 0)
5663 exit(1);
5665 close(fds[0]);
5666 qemu_set_cloexec(fds[1]);
5668 setsid();
5670 pid = fork();
5671 if (pid > 0)
5672 exit(0);
5673 else if (pid < 0)
5674 exit(1);
5676 umask(027);
5678 signal(SIGTSTP, SIG_IGN);
5679 signal(SIGTTOU, SIG_IGN);
5680 signal(SIGTTIN, SIG_IGN);
5683 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5684 if (daemonize) {
5685 uint8_t status = 1;
5686 write(fds[1], &status, 1);
5687 } else
5688 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5689 exit(1);
5691 #endif
5693 if (kvm_enabled()) {
5694 int ret;
5696 ret = kvm_init(smp_cpus);
5697 if (ret < 0) {
5698 fprintf(stderr, "failed to initialize KVM\n");
5699 exit(1);
5703 if (qemu_init_main_loop()) {
5704 fprintf(stderr, "qemu_init_main_loop failed\n");
5705 exit(1);
5707 linux_boot = (kernel_filename != NULL);
5709 if (!linux_boot && *kernel_cmdline != '\0') {
5710 fprintf(stderr, "-append only allowed with -kernel option\n");
5711 exit(1);
5714 if (!linux_boot && initrd_filename != NULL) {
5715 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5716 exit(1);
5719 #ifndef _WIN32
5720 /* Win32 doesn't support line-buffering and requires size >= 2 */
5721 setvbuf(stdout, NULL, _IOLBF, 0);
5722 #endif
5724 if (init_timer_alarm() < 0) {
5725 fprintf(stderr, "could not initialize alarm timer\n");
5726 exit(1);
5728 if (use_icount && icount_time_shift < 0) {
5729 use_icount = 2;
5730 /* 125MIPS seems a reasonable initial guess at the guest speed.
5731 It will be corrected fairly quickly anyway. */
5732 icount_time_shift = 3;
5733 init_icount_adjust();
5736 #ifdef _WIN32
5737 socket_init();
5738 #endif
5740 if (net_init_clients() < 0) {
5741 exit(1);
5744 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5745 net_set_boot_mask(net_boot);
5747 /* init the bluetooth world */
5748 if (foreach_device_config(DEV_BT, bt_parse))
5749 exit(1);
5751 /* init the memory */
5752 if (ram_size == 0)
5753 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5755 /* init the dynamic translator */
5756 cpu_exec_init_all(tb_size * 1024 * 1024);
5758 bdrv_init_with_whitelist();
5760 blk_mig_init();
5762 if (default_drive) {
5763 /* we always create the cdrom drive, even if no disk is there */
5764 drive_add(NULL, CDROM_ALIAS);
5766 /* we always create at least one floppy */
5767 drive_add(NULL, FD_ALIAS, 0);
5769 /* we always create one sd slot, even if no card is in it */
5770 drive_add(NULL, SD_ALIAS);
5773 /* open the virtual block devices */
5774 if (snapshot)
5775 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5776 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5777 exit(1);
5779 vmstate_register(0, &vmstate_timers ,&timers_state);
5780 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
5781 ram_load, NULL);
5783 if (nb_numa_nodes > 0) {
5784 int i;
5786 if (nb_numa_nodes > smp_cpus) {
5787 nb_numa_nodes = smp_cpus;
5790 /* If no memory size if given for any node, assume the default case
5791 * and distribute the available memory equally across all nodes
5793 for (i = 0; i < nb_numa_nodes; i++) {
5794 if (node_mem[i] != 0)
5795 break;
5797 if (i == nb_numa_nodes) {
5798 uint64_t usedmem = 0;
5800 /* On Linux, the each node's border has to be 8MB aligned,
5801 * the final node gets the rest.
5803 for (i = 0; i < nb_numa_nodes - 1; i++) {
5804 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5805 usedmem += node_mem[i];
5807 node_mem[i] = ram_size - usedmem;
5810 for (i = 0; i < nb_numa_nodes; i++) {
5811 if (node_cpumask[i] != 0)
5812 break;
5814 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5815 * must cope with this anyway, because there are BIOSes out there in
5816 * real machines which also use this scheme.
5818 if (i == nb_numa_nodes) {
5819 for (i = 0; i < smp_cpus; i++) {
5820 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5825 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
5826 exit(1);
5827 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
5828 exit(1);
5830 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5831 const char *devname = virtio_consoles[i];
5832 if (devname && strcmp(devname, "none")) {
5833 char label[32];
5834 snprintf(label, sizeof(label), "virtcon%d", i);
5835 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5836 if (!virtcon_hds[i]) {
5837 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
5838 devname, strerror(errno));
5839 exit(1);
5844 module_call_init(MODULE_INIT_DEVICE);
5846 if (watchdog) {
5847 i = select_watchdog(watchdog);
5848 if (i > 0)
5849 exit (i == 1 ? 1 : 0);
5852 if (machine->compat_props) {
5853 qdev_prop_register_global_list(machine->compat_props);
5855 qemu_add_globals();
5857 machine->init(ram_size, boot_devices,
5858 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5861 #ifndef _WIN32
5862 /* must be after terminal init, SDL library changes signal handlers */
5863 sighandler_setup();
5864 #endif
5866 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5867 for (i = 0; i < nb_numa_nodes; i++) {
5868 if (node_cpumask[i] & (1 << env->cpu_index)) {
5869 env->numa_node = i;
5874 current_machine = machine;
5876 /* init USB devices */
5877 if (usb_enabled) {
5878 if (foreach_device_config(DEV_USB, usb_parse) < 0)
5879 exit(1);
5882 /* init generic devices */
5883 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5884 exit(1);
5886 if (!display_state)
5887 dumb_display_init();
5888 /* just use the first displaystate for the moment */
5889 ds = display_state;
5891 if (display_type == DT_DEFAULT) {
5892 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5893 display_type = DT_SDL;
5894 #else
5895 display_type = DT_VNC;
5896 vnc_display = "localhost:0,to=99";
5897 show_vnc_port = 1;
5898 #endif
5902 switch (display_type) {
5903 case DT_NOGRAPHIC:
5904 break;
5905 #if defined(CONFIG_CURSES)
5906 case DT_CURSES:
5907 curses_display_init(ds, full_screen);
5908 break;
5909 #endif
5910 #if defined(CONFIG_SDL)
5911 case DT_SDL:
5912 sdl_display_init(ds, full_screen, no_frame);
5913 break;
5914 #elif defined(CONFIG_COCOA)
5915 case DT_SDL:
5916 cocoa_display_init(ds, full_screen);
5917 break;
5918 #endif
5919 case DT_VNC:
5920 vnc_display_init(ds);
5921 if (vnc_display_open(ds, vnc_display) < 0)
5922 exit(1);
5924 if (show_vnc_port) {
5925 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5927 break;
5928 default:
5929 break;
5931 dpy_resize(ds);
5933 dcl = ds->listeners;
5934 while (dcl != NULL) {
5935 if (dcl->dpy_refresh != NULL) {
5936 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5937 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5939 dcl = dcl->next;
5942 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5943 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5944 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5947 text_consoles_set_display(display_state);
5949 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
5950 exit(1);
5952 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5953 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5954 gdbstub_dev);
5955 exit(1);
5958 qdev_machine_creation_done();
5960 rom_load_all();
5962 qemu_system_reset();
5963 if (loadvm) {
5964 if (load_vmstate(cur_mon, loadvm) < 0) {
5965 autostart = 0;
5969 if (incoming) {
5970 qemu_start_incoming_migration(incoming);
5971 } else if (autostart) {
5972 vm_start();
5975 #ifndef _WIN32
5976 if (daemonize) {
5977 uint8_t status = 0;
5978 ssize_t len;
5980 again1:
5981 len = write(fds[1], &status, 1);
5982 if (len == -1 && (errno == EINTR))
5983 goto again1;
5985 if (len != 1)
5986 exit(1);
5988 chdir("/");
5989 TFR(fd = qemu_open("/dev/null", O_RDWR));
5990 if (fd == -1)
5991 exit(1);
5994 if (run_as) {
5995 pwd = getpwnam(run_as);
5996 if (!pwd) {
5997 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5998 exit(1);
6002 if (chroot_dir) {
6003 if (chroot(chroot_dir) < 0) {
6004 fprintf(stderr, "chroot failed\n");
6005 exit(1);
6007 chdir("/");
6010 if (run_as) {
6011 if (setgid(pwd->pw_gid) < 0) {
6012 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6013 exit(1);
6015 if (setuid(pwd->pw_uid) < 0) {
6016 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6017 exit(1);
6019 if (setuid(0) != -1) {
6020 fprintf(stderr, "Dropping privileges failed\n");
6021 exit(1);
6025 if (daemonize) {
6026 dup2(fd, 0);
6027 dup2(fd, 1);
6028 dup2(fd, 2);
6030 close(fd);
6032 #endif
6034 main_loop();
6035 quit_timers();
6036 net_cleanup();
6038 return 0;