mips-malta: fix reset
[qemu/stefanha.git] / vl.c
blobfff8e8d4686a32d6c6f9cd418c779ae52a13bec8
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(__DragonFly__)
54 #include <libutil.h>
55 #else
56 #include <util.h>
57 #endif
58 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
59 #include <freebsd/stdlib.h>
60 #else
61 #ifdef __linux__
62 #include <pty.h>
63 #include <malloc.h>
64 #include <linux/rtc.h>
65 #include <sys/prctl.h>
67 /* For the benefit of older linux systems which don't supply it,
68 we use a local copy of hpet.h. */
69 /* #include <linux/hpet.h> */
70 #include "hpet.h"
72 #include <linux/ppdev.h>
73 #include <linux/parport.h>
74 #endif
75 #ifdef __sun__
76 #include <sys/stat.h>
77 #include <sys/ethernet.h>
78 #include <sys/sockio.h>
79 #include <netinet/arp.h>
80 #include <netinet/in.h>
81 #include <netinet/in_systm.h>
82 #include <netinet/ip.h>
83 #include <netinet/ip_icmp.h> // must come after ip.h
84 #include <netinet/udp.h>
85 #include <netinet/tcp.h>
86 #include <net/if.h>
87 #include <syslog.h>
88 #include <stropts.h>
89 /* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
90 discussion about Solaris header problems */
91 extern int madvise(caddr_t, size_t, int);
92 #endif
93 #endif
94 #endif
96 #if defined(__OpenBSD__)
97 #include <util.h>
98 #endif
100 #if defined(CONFIG_VDE)
101 #include <libvdeplug.h>
102 #endif
104 #ifdef _WIN32
105 #include <windows.h>
106 #include <mmsystem.h>
107 #endif
109 #ifdef CONFIG_SDL
110 #if defined(__APPLE__) || defined(main)
111 #include <SDL.h>
112 int qemu_main(int argc, char **argv, char **envp);
113 int main(int argc, char **argv)
115 return qemu_main(argc, argv, NULL);
117 #undef main
118 #define main qemu_main
119 #endif
120 #endif /* CONFIG_SDL */
122 #ifdef CONFIG_COCOA
123 #undef main
124 #define main qemu_main
125 #endif /* CONFIG_COCOA */
127 #include "hw/hw.h"
128 #include "hw/boards.h"
129 #include "hw/usb.h"
130 #include "hw/pcmcia.h"
131 #include "hw/pc.h"
132 #include "hw/audiodev.h"
133 #include "hw/isa.h"
134 #include "hw/baum.h"
135 #include "hw/bt.h"
136 #include "hw/watchdog.h"
137 #include "hw/smbios.h"
138 #include "hw/xen.h"
139 #include "hw/qdev.h"
140 #include "hw/loader.h"
141 #include "bt-host.h"
142 #include "net.h"
143 #include "monitor.h"
144 #include "console.h"
145 #include "sysemu.h"
146 #include "gdbstub.h"
147 #include "qemu-timer.h"
148 #include "qemu-char.h"
149 #include "cache-utils.h"
150 #include "block.h"
151 #include "dma.h"
152 #include "audio/audio.h"
153 #include "migration.h"
154 #include "kvm.h"
155 #include "balloon.h"
156 #include "qemu-option.h"
157 #include "qemu-config.h"
159 #include "disas.h"
161 #include "exec-all.h"
163 #include "qemu_socket.h"
165 #include "slirp/libslirp.h"
167 #include "qemu-queue.h"
169 //#define DEBUG_NET
170 //#define DEBUG_SLIRP
172 #define DEFAULT_RAM_SIZE 128
174 /* Maximum number of monitor devices */
175 #define MAX_MONITOR_DEVICES 10
177 static const char *data_dir;
178 const char *bios_name = NULL;
179 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
180 to store the VM snapshots */
181 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
182 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
183 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
184 static DisplayState *display_state;
185 DisplayType display_type = DT_DEFAULT;
186 const char* keyboard_layout = NULL;
187 ram_addr_t ram_size;
188 int nb_nics;
189 NICInfo nd_table[MAX_NICS];
190 int vm_running;
191 int autostart;
192 static int rtc_utc = 1;
193 static int rtc_date_offset = -1; /* -1 means no change */
194 QEMUClock *rtc_clock;
195 int vga_interface_type = VGA_CIRRUS;
196 #ifdef TARGET_SPARC
197 int graphic_width = 1024;
198 int graphic_height = 768;
199 int graphic_depth = 8;
200 #else
201 int graphic_width = 800;
202 int graphic_height = 600;
203 int graphic_depth = 15;
204 #endif
205 static int full_screen = 0;
206 #ifdef CONFIG_SDL
207 static int no_frame = 0;
208 #endif
209 int no_quit = 0;
210 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
211 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
212 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
213 #ifdef TARGET_I386
214 int win2k_install_hack = 0;
215 int rtc_td_hack = 0;
216 #endif
217 int usb_enabled = 0;
218 int singlestep = 0;
219 int smp_cpus = 1;
220 int max_cpus = 0;
221 int smp_cores = 1;
222 int smp_threads = 1;
223 const char *vnc_display;
224 int acpi_enabled = 1;
225 int no_hpet = 0;
226 int fd_bootchk = 1;
227 int no_reboot = 0;
228 int no_shutdown = 0;
229 int cursor_hide = 1;
230 int graphic_rotate = 0;
231 uint8_t irq0override = 1;
232 #ifndef _WIN32
233 int daemonize = 0;
234 #endif
235 const char *watchdog;
236 const char *option_rom[MAX_OPTION_ROMS];
237 int nb_option_roms;
238 int semihosting_enabled = 0;
239 #ifdef TARGET_ARM
240 int old_param = 0;
241 #endif
242 const char *qemu_name;
243 int alt_grab = 0;
244 int ctrl_grab = 0;
245 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
246 unsigned int nb_prom_envs = 0;
247 const char *prom_envs[MAX_PROM_ENVS];
248 #endif
249 int boot_menu;
251 int nb_numa_nodes;
252 uint64_t node_mem[MAX_NODES];
253 uint64_t node_cpumask[MAX_NODES];
255 static CPUState *cur_cpu;
256 static CPUState *next_cpu;
257 static int timer_alarm_pending = 1;
258 /* Conversion factor from emulated instructions to virtual clock ticks. */
259 static int icount_time_shift;
260 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
261 #define MAX_ICOUNT_SHIFT 10
262 /* Compensate for varying guest execution speed. */
263 static int64_t qemu_icount_bias;
264 static QEMUTimer *icount_rt_timer;
265 static QEMUTimer *icount_vm_timer;
266 static QEMUTimer *nographic_timer;
268 uint8_t qemu_uuid[16];
270 static QEMUBootSetHandler *boot_set_handler;
271 static void *boot_set_opaque;
273 /***********************************************************/
274 /* x86 ISA bus support */
276 target_phys_addr_t isa_mem_base = 0;
277 PicState2 *isa_pic;
279 /***********************************************************/
280 void hw_error(const char *fmt, ...)
282 va_list ap;
283 CPUState *env;
285 va_start(ap, fmt);
286 fprintf(stderr, "qemu: hardware error: ");
287 vfprintf(stderr, fmt, ap);
288 fprintf(stderr, "\n");
289 for(env = first_cpu; env != NULL; env = env->next_cpu) {
290 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
291 #ifdef TARGET_I386
292 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
293 #else
294 cpu_dump_state(env, stderr, fprintf, 0);
295 #endif
297 va_end(ap);
298 abort();
301 static void set_proc_name(const char *s)
303 #if defined(__linux__) && defined(PR_SET_NAME)
304 char name[16];
305 if (!s)
306 return;
307 name[sizeof(name) - 1] = 0;
308 strncpy(name, s, sizeof(name));
309 /* Could rewrite argv[0] too, but that's a bit more complicated.
310 This simple way is enough for `top'. */
311 prctl(PR_SET_NAME, name);
312 #endif
315 /***************/
316 /* ballooning */
318 static QEMUBalloonEvent *qemu_balloon_event;
319 void *qemu_balloon_event_opaque;
321 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
323 qemu_balloon_event = func;
324 qemu_balloon_event_opaque = opaque;
327 void qemu_balloon(ram_addr_t target)
329 if (qemu_balloon_event)
330 qemu_balloon_event(qemu_balloon_event_opaque, target);
333 ram_addr_t qemu_balloon_status(void)
335 if (qemu_balloon_event)
336 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
337 return 0;
340 /***********************************************************/
341 /* keyboard/mouse */
343 static QEMUPutKBDEvent *qemu_put_kbd_event;
344 static void *qemu_put_kbd_event_opaque;
345 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
346 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
348 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
350 qemu_put_kbd_event_opaque = opaque;
351 qemu_put_kbd_event = func;
354 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
355 void *opaque, int absolute,
356 const char *name)
358 QEMUPutMouseEntry *s, *cursor;
360 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
362 s->qemu_put_mouse_event = func;
363 s->qemu_put_mouse_event_opaque = opaque;
364 s->qemu_put_mouse_event_absolute = absolute;
365 s->qemu_put_mouse_event_name = qemu_strdup(name);
366 s->next = NULL;
368 if (!qemu_put_mouse_event_head) {
369 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
370 return s;
373 cursor = qemu_put_mouse_event_head;
374 while (cursor->next != NULL)
375 cursor = cursor->next;
377 cursor->next = s;
378 qemu_put_mouse_event_current = s;
380 return s;
383 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
385 QEMUPutMouseEntry *prev = NULL, *cursor;
387 if (!qemu_put_mouse_event_head || entry == NULL)
388 return;
390 cursor = qemu_put_mouse_event_head;
391 while (cursor != NULL && cursor != entry) {
392 prev = cursor;
393 cursor = cursor->next;
396 if (cursor == NULL) // does not exist or list empty
397 return;
398 else if (prev == NULL) { // entry is head
399 qemu_put_mouse_event_head = cursor->next;
400 if (qemu_put_mouse_event_current == entry)
401 qemu_put_mouse_event_current = cursor->next;
402 qemu_free(entry->qemu_put_mouse_event_name);
403 qemu_free(entry);
404 return;
407 prev->next = entry->next;
409 if (qemu_put_mouse_event_current == entry)
410 qemu_put_mouse_event_current = prev;
412 qemu_free(entry->qemu_put_mouse_event_name);
413 qemu_free(entry);
416 void kbd_put_keycode(int keycode)
418 if (qemu_put_kbd_event) {
419 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
423 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
425 QEMUPutMouseEvent *mouse_event;
426 void *mouse_event_opaque;
427 int width;
429 if (!qemu_put_mouse_event_current) {
430 return;
433 mouse_event =
434 qemu_put_mouse_event_current->qemu_put_mouse_event;
435 mouse_event_opaque =
436 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
438 if (mouse_event) {
439 if (graphic_rotate) {
440 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
441 width = 0x7fff;
442 else
443 width = graphic_width - 1;
444 mouse_event(mouse_event_opaque,
445 width - dy, dx, dz, buttons_state);
446 } else
447 mouse_event(mouse_event_opaque,
448 dx, dy, dz, buttons_state);
452 int kbd_mouse_is_absolute(void)
454 if (!qemu_put_mouse_event_current)
455 return 0;
457 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
460 void do_info_mice(Monitor *mon)
462 QEMUPutMouseEntry *cursor;
463 int index = 0;
465 if (!qemu_put_mouse_event_head) {
466 monitor_printf(mon, "No mouse devices connected\n");
467 return;
470 monitor_printf(mon, "Mouse devices available:\n");
471 cursor = qemu_put_mouse_event_head;
472 while (cursor != NULL) {
473 monitor_printf(mon, "%c Mouse #%d: %s\n",
474 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
475 index, cursor->qemu_put_mouse_event_name);
476 index++;
477 cursor = cursor->next;
481 void do_mouse_set(Monitor *mon, const QDict *qdict)
483 QEMUPutMouseEntry *cursor;
484 int i = 0;
485 int index = qdict_get_int(qdict, "index");
487 if (!qemu_put_mouse_event_head) {
488 monitor_printf(mon, "No mouse devices connected\n");
489 return;
492 cursor = qemu_put_mouse_event_head;
493 while (cursor != NULL && index != i) {
494 i++;
495 cursor = cursor->next;
498 if (cursor != NULL)
499 qemu_put_mouse_event_current = cursor;
500 else
501 monitor_printf(mon, "Mouse at given index not found\n");
504 /* compute with 96 bit intermediate result: (a*b)/c */
505 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
507 union {
508 uint64_t ll;
509 struct {
510 #ifdef HOST_WORDS_BIGENDIAN
511 uint32_t high, low;
512 #else
513 uint32_t low, high;
514 #endif
515 } l;
516 } u, res;
517 uint64_t rl, rh;
519 u.ll = a;
520 rl = (uint64_t)u.l.low * (uint64_t)b;
521 rh = (uint64_t)u.l.high * (uint64_t)b;
522 rh += (rl >> 32);
523 res.l.high = rh / c;
524 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
525 return res.ll;
528 /***********************************************************/
529 /* real time host monotonic timer */
531 static int64_t get_clock_realtime(void)
533 struct timeval tv;
535 gettimeofday(&tv, NULL);
536 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
539 #ifdef WIN32
541 static int64_t clock_freq;
543 static void init_get_clock(void)
545 LARGE_INTEGER freq;
546 int ret;
547 ret = QueryPerformanceFrequency(&freq);
548 if (ret == 0) {
549 fprintf(stderr, "Could not calibrate ticks\n");
550 exit(1);
552 clock_freq = freq.QuadPart;
555 static int64_t get_clock(void)
557 LARGE_INTEGER ti;
558 QueryPerformanceCounter(&ti);
559 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
562 #else
564 static int use_rt_clock;
566 static void init_get_clock(void)
568 use_rt_clock = 0;
569 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
570 || defined(__DragonFly__)
572 struct timespec ts;
573 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
574 use_rt_clock = 1;
577 #endif
580 static int64_t get_clock(void)
582 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
583 || defined(__DragonFly__)
584 if (use_rt_clock) {
585 struct timespec ts;
586 clock_gettime(CLOCK_MONOTONIC, &ts);
587 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
588 } else
589 #endif
591 /* XXX: using gettimeofday leads to problems if the date
592 changes, so it should be avoided. */
593 return get_clock_realtime();
596 #endif
598 /* Return the virtual CPU time, based on the instruction counter. */
599 static int64_t cpu_get_icount(void)
601 int64_t icount;
602 CPUState *env = cpu_single_env;;
603 icount = qemu_icount;
604 if (env) {
605 if (!can_do_io(env))
606 fprintf(stderr, "Bad clock read\n");
607 icount -= (env->icount_decr.u16.low + env->icount_extra);
609 return qemu_icount_bias + (icount << icount_time_shift);
612 /***********************************************************/
613 /* guest cycle counter */
615 typedef struct TimersState {
616 int64_t cpu_ticks_prev;
617 int64_t cpu_ticks_offset;
618 int64_t cpu_clock_offset;
619 int32_t cpu_ticks_enabled;
620 int64_t dummy;
621 } TimersState;
623 TimersState timers_state;
625 /* return the host CPU cycle counter and handle stop/restart */
626 int64_t cpu_get_ticks(void)
628 if (use_icount) {
629 return cpu_get_icount();
631 if (!timers_state.cpu_ticks_enabled) {
632 return timers_state.cpu_ticks_offset;
633 } else {
634 int64_t ticks;
635 ticks = cpu_get_real_ticks();
636 if (timers_state.cpu_ticks_prev > ticks) {
637 /* Note: non increasing ticks may happen if the host uses
638 software suspend */
639 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
641 timers_state.cpu_ticks_prev = ticks;
642 return ticks + timers_state.cpu_ticks_offset;
646 /* return the host CPU monotonic timer and handle stop/restart */
647 static int64_t cpu_get_clock(void)
649 int64_t ti;
650 if (!timers_state.cpu_ticks_enabled) {
651 return timers_state.cpu_clock_offset;
652 } else {
653 ti = get_clock();
654 return ti + timers_state.cpu_clock_offset;
658 /* enable cpu_get_ticks() */
659 void cpu_enable_ticks(void)
661 if (!timers_state.cpu_ticks_enabled) {
662 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
663 timers_state.cpu_clock_offset -= get_clock();
664 timers_state.cpu_ticks_enabled = 1;
668 /* disable cpu_get_ticks() : the clock is stopped. You must not call
669 cpu_get_ticks() after that. */
670 void cpu_disable_ticks(void)
672 if (timers_state.cpu_ticks_enabled) {
673 timers_state.cpu_ticks_offset = cpu_get_ticks();
674 timers_state.cpu_clock_offset = cpu_get_clock();
675 timers_state.cpu_ticks_enabled = 0;
679 /***********************************************************/
680 /* timers */
682 #define QEMU_CLOCK_REALTIME 0
683 #define QEMU_CLOCK_VIRTUAL 1
684 #define QEMU_CLOCK_HOST 2
686 struct QEMUClock {
687 int type;
688 /* XXX: add frequency */
691 struct QEMUTimer {
692 QEMUClock *clock;
693 int64_t expire_time;
694 QEMUTimerCB *cb;
695 void *opaque;
696 struct QEMUTimer *next;
699 struct qemu_alarm_timer {
700 char const *name;
701 unsigned int flags;
703 int (*start)(struct qemu_alarm_timer *t);
704 void (*stop)(struct qemu_alarm_timer *t);
705 void (*rearm)(struct qemu_alarm_timer *t);
706 void *priv;
709 #define ALARM_FLAG_DYNTICKS 0x1
710 #define ALARM_FLAG_EXPIRED 0x2
712 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
714 return t && (t->flags & ALARM_FLAG_DYNTICKS);
717 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
719 if (!alarm_has_dynticks(t))
720 return;
722 t->rearm(t);
725 /* TODO: MIN_TIMER_REARM_US should be optimized */
726 #define MIN_TIMER_REARM_US 250
728 static struct qemu_alarm_timer *alarm_timer;
730 #ifdef _WIN32
732 struct qemu_alarm_win32 {
733 MMRESULT timerId;
734 unsigned int period;
735 } alarm_win32_data = {0, -1};
737 static int win32_start_timer(struct qemu_alarm_timer *t);
738 static void win32_stop_timer(struct qemu_alarm_timer *t);
739 static void win32_rearm_timer(struct qemu_alarm_timer *t);
741 #else
743 static int unix_start_timer(struct qemu_alarm_timer *t);
744 static void unix_stop_timer(struct qemu_alarm_timer *t);
746 #ifdef __linux__
748 static int dynticks_start_timer(struct qemu_alarm_timer *t);
749 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
750 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
752 static int hpet_start_timer(struct qemu_alarm_timer *t);
753 static void hpet_stop_timer(struct qemu_alarm_timer *t);
755 static int rtc_start_timer(struct qemu_alarm_timer *t);
756 static void rtc_stop_timer(struct qemu_alarm_timer *t);
758 #endif /* __linux__ */
760 #endif /* _WIN32 */
762 /* Correlation between real and virtual time is always going to be
763 fairly approximate, so ignore small variation.
764 When the guest is idle real and virtual time will be aligned in
765 the IO wait loop. */
766 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
768 static void icount_adjust(void)
770 int64_t cur_time;
771 int64_t cur_icount;
772 int64_t delta;
773 static int64_t last_delta;
774 /* If the VM is not running, then do nothing. */
775 if (!vm_running)
776 return;
778 cur_time = cpu_get_clock();
779 cur_icount = qemu_get_clock(vm_clock);
780 delta = cur_icount - cur_time;
781 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
782 if (delta > 0
783 && last_delta + ICOUNT_WOBBLE < delta * 2
784 && icount_time_shift > 0) {
785 /* The guest is getting too far ahead. Slow time down. */
786 icount_time_shift--;
788 if (delta < 0
789 && last_delta - ICOUNT_WOBBLE > delta * 2
790 && icount_time_shift < MAX_ICOUNT_SHIFT) {
791 /* The guest is getting too far behind. Speed time up. */
792 icount_time_shift++;
794 last_delta = delta;
795 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
798 static void icount_adjust_rt(void * opaque)
800 qemu_mod_timer(icount_rt_timer,
801 qemu_get_clock(rt_clock) + 1000);
802 icount_adjust();
805 static void icount_adjust_vm(void * opaque)
807 qemu_mod_timer(icount_vm_timer,
808 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
809 icount_adjust();
812 static void init_icount_adjust(void)
814 /* Have both realtime and virtual time triggers for speed adjustment.
815 The realtime trigger catches emulated time passing too slowly,
816 the virtual time trigger catches emulated time passing too fast.
817 Realtime triggers occur even when idle, so use them less frequently
818 than VM triggers. */
819 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
820 qemu_mod_timer(icount_rt_timer,
821 qemu_get_clock(rt_clock) + 1000);
822 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
823 qemu_mod_timer(icount_vm_timer,
824 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
827 static struct qemu_alarm_timer alarm_timers[] = {
828 #ifndef _WIN32
829 #ifdef __linux__
830 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
831 dynticks_stop_timer, dynticks_rearm_timer, NULL},
832 /* HPET - if available - is preferred */
833 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
834 /* ...otherwise try RTC */
835 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
836 #endif
837 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
838 #else
839 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
840 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
841 {"win32", 0, win32_start_timer,
842 win32_stop_timer, NULL, &alarm_win32_data},
843 #endif
844 {NULL, }
847 static void show_available_alarms(void)
849 int i;
851 printf("Available alarm timers, in order of precedence:\n");
852 for (i = 0; alarm_timers[i].name; i++)
853 printf("%s\n", alarm_timers[i].name);
856 static void configure_alarms(char const *opt)
858 int i;
859 int cur = 0;
860 int count = ARRAY_SIZE(alarm_timers) - 1;
861 char *arg;
862 char *name;
863 struct qemu_alarm_timer tmp;
865 if (!strcmp(opt, "?")) {
866 show_available_alarms();
867 exit(0);
870 arg = qemu_strdup(opt);
872 /* Reorder the array */
873 name = strtok(arg, ",");
874 while (name) {
875 for (i = 0; i < count && alarm_timers[i].name; i++) {
876 if (!strcmp(alarm_timers[i].name, name))
877 break;
880 if (i == count) {
881 fprintf(stderr, "Unknown clock %s\n", name);
882 goto next;
885 if (i < cur)
886 /* Ignore */
887 goto next;
889 /* Swap */
890 tmp = alarm_timers[i];
891 alarm_timers[i] = alarm_timers[cur];
892 alarm_timers[cur] = tmp;
894 cur++;
895 next:
896 name = strtok(NULL, ",");
899 qemu_free(arg);
901 if (cur) {
902 /* Disable remaining timers */
903 for (i = cur; i < count; i++)
904 alarm_timers[i].name = NULL;
905 } else {
906 show_available_alarms();
907 exit(1);
911 #define QEMU_NUM_CLOCKS 3
913 QEMUClock *rt_clock;
914 QEMUClock *vm_clock;
915 QEMUClock *host_clock;
917 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
919 static QEMUClock *qemu_new_clock(int type)
921 QEMUClock *clock;
922 clock = qemu_mallocz(sizeof(QEMUClock));
923 clock->type = type;
924 return clock;
927 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
929 QEMUTimer *ts;
931 ts = qemu_mallocz(sizeof(QEMUTimer));
932 ts->clock = clock;
933 ts->cb = cb;
934 ts->opaque = opaque;
935 return ts;
938 void qemu_free_timer(QEMUTimer *ts)
940 qemu_free(ts);
943 /* stop a timer, but do not dealloc it */
944 void qemu_del_timer(QEMUTimer *ts)
946 QEMUTimer **pt, *t;
948 /* NOTE: this code must be signal safe because
949 qemu_timer_expired() can be called from a signal. */
950 pt = &active_timers[ts->clock->type];
951 for(;;) {
952 t = *pt;
953 if (!t)
954 break;
955 if (t == ts) {
956 *pt = t->next;
957 break;
959 pt = &t->next;
963 /* modify the current timer so that it will be fired when current_time
964 >= expire_time. The corresponding callback will be called. */
965 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
967 QEMUTimer **pt, *t;
969 qemu_del_timer(ts);
971 /* add the timer in the sorted list */
972 /* NOTE: this code must be signal safe because
973 qemu_timer_expired() can be called from a signal. */
974 pt = &active_timers[ts->clock->type];
975 for(;;) {
976 t = *pt;
977 if (!t)
978 break;
979 if (t->expire_time > expire_time)
980 break;
981 pt = &t->next;
983 ts->expire_time = expire_time;
984 ts->next = *pt;
985 *pt = ts;
987 /* Rearm if necessary */
988 if (pt == &active_timers[ts->clock->type]) {
989 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
990 qemu_rearm_alarm_timer(alarm_timer);
992 /* Interrupt execution to force deadline recalculation. */
993 if (use_icount)
994 qemu_notify_event();
998 int qemu_timer_pending(QEMUTimer *ts)
1000 QEMUTimer *t;
1001 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1002 if (t == ts)
1003 return 1;
1005 return 0;
1008 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1010 if (!timer_head)
1011 return 0;
1012 return (timer_head->expire_time <= current_time);
1015 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1017 QEMUTimer *ts;
1019 for(;;) {
1020 ts = *ptimer_head;
1021 if (!ts || ts->expire_time > current_time)
1022 break;
1023 /* remove timer from the list before calling the callback */
1024 *ptimer_head = ts->next;
1025 ts->next = NULL;
1027 /* run the callback (the timer list can be modified) */
1028 ts->cb(ts->opaque);
1032 int64_t qemu_get_clock(QEMUClock *clock)
1034 switch(clock->type) {
1035 case QEMU_CLOCK_REALTIME:
1036 return get_clock() / 1000000;
1037 default:
1038 case QEMU_CLOCK_VIRTUAL:
1039 if (use_icount) {
1040 return cpu_get_icount();
1041 } else {
1042 return cpu_get_clock();
1044 case QEMU_CLOCK_HOST:
1045 return get_clock_realtime();
1049 static void init_clocks(void)
1051 init_get_clock();
1052 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
1053 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
1054 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
1056 rtc_clock = host_clock;
1059 /* save a timer */
1060 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1062 uint64_t expire_time;
1064 if (qemu_timer_pending(ts)) {
1065 expire_time = ts->expire_time;
1066 } else {
1067 expire_time = -1;
1069 qemu_put_be64(f, expire_time);
1072 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1074 uint64_t expire_time;
1076 expire_time = qemu_get_be64(f);
1077 if (expire_time != -1) {
1078 qemu_mod_timer(ts, expire_time);
1079 } else {
1080 qemu_del_timer(ts);
1084 static const VMStateDescription vmstate_timers = {
1085 .name = "timer",
1086 .version_id = 2,
1087 .minimum_version_id = 1,
1088 .minimum_version_id_old = 1,
1089 .fields = (VMStateField []) {
1090 VMSTATE_INT64(cpu_ticks_offset, TimersState),
1091 VMSTATE_INT64(dummy, TimersState),
1092 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1093 VMSTATE_END_OF_LIST()
1097 static void qemu_event_increment(void);
1099 #ifdef _WIN32
1100 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1101 DWORD_PTR dwUser, DWORD_PTR dw1,
1102 DWORD_PTR dw2)
1103 #else
1104 static void host_alarm_handler(int host_signum)
1105 #endif
1107 #if 0
1108 #define DISP_FREQ 1000
1110 static int64_t delta_min = INT64_MAX;
1111 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1112 static int count;
1113 ti = qemu_get_clock(vm_clock);
1114 if (last_clock != 0) {
1115 delta = ti - last_clock;
1116 if (delta < delta_min)
1117 delta_min = delta;
1118 if (delta > delta_max)
1119 delta_max = delta;
1120 delta_cum += delta;
1121 if (++count == DISP_FREQ) {
1122 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1123 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1124 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1125 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1126 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1127 count = 0;
1128 delta_min = INT64_MAX;
1129 delta_max = 0;
1130 delta_cum = 0;
1133 last_clock = ti;
1135 #endif
1136 if (alarm_has_dynticks(alarm_timer) ||
1137 (!use_icount &&
1138 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1139 qemu_get_clock(vm_clock))) ||
1140 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1141 qemu_get_clock(rt_clock)) ||
1142 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1143 qemu_get_clock(host_clock))) {
1144 qemu_event_increment();
1145 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1147 #ifndef CONFIG_IOTHREAD
1148 if (next_cpu) {
1149 /* stop the currently executing cpu because a timer occured */
1150 cpu_exit(next_cpu);
1152 #endif
1153 timer_alarm_pending = 1;
1154 qemu_notify_event();
1158 static int64_t qemu_next_deadline(void)
1160 /* To avoid problems with overflow limit this to 2^32. */
1161 int64_t delta = INT32_MAX;
1163 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1164 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1165 qemu_get_clock(vm_clock);
1167 if (active_timers[QEMU_CLOCK_HOST]) {
1168 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1169 qemu_get_clock(host_clock);
1170 if (hdelta < delta)
1171 delta = hdelta;
1174 if (delta < 0)
1175 delta = 0;
1177 return delta;
1180 #if defined(__linux__)
1181 static uint64_t qemu_next_deadline_dyntick(void)
1183 int64_t delta;
1184 int64_t rtdelta;
1186 if (use_icount)
1187 delta = INT32_MAX;
1188 else
1189 delta = (qemu_next_deadline() + 999) / 1000;
1191 if (active_timers[QEMU_CLOCK_REALTIME]) {
1192 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1193 qemu_get_clock(rt_clock))*1000;
1194 if (rtdelta < delta)
1195 delta = rtdelta;
1198 if (delta < MIN_TIMER_REARM_US)
1199 delta = MIN_TIMER_REARM_US;
1201 return delta;
1203 #endif
1205 #ifndef _WIN32
1207 /* Sets a specific flag */
1208 static int fcntl_setfl(int fd, int flag)
1210 int flags;
1212 flags = fcntl(fd, F_GETFL);
1213 if (flags == -1)
1214 return -errno;
1216 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1217 return -errno;
1219 return 0;
1222 #if defined(__linux__)
1224 #define RTC_FREQ 1024
1226 static void enable_sigio_timer(int fd)
1228 struct sigaction act;
1230 /* timer signal */
1231 sigfillset(&act.sa_mask);
1232 act.sa_flags = 0;
1233 act.sa_handler = host_alarm_handler;
1235 sigaction(SIGIO, &act, NULL);
1236 fcntl_setfl(fd, O_ASYNC);
1237 fcntl(fd, F_SETOWN, getpid());
1240 static int hpet_start_timer(struct qemu_alarm_timer *t)
1242 struct hpet_info info;
1243 int r, fd;
1245 fd = open("/dev/hpet", O_RDONLY);
1246 if (fd < 0)
1247 return -1;
1249 /* Set frequency */
1250 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1251 if (r < 0) {
1252 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1253 "error, but for better emulation accuracy type:\n"
1254 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1255 goto fail;
1258 /* Check capabilities */
1259 r = ioctl(fd, HPET_INFO, &info);
1260 if (r < 0)
1261 goto fail;
1263 /* Enable periodic mode */
1264 r = ioctl(fd, HPET_EPI, 0);
1265 if (info.hi_flags && (r < 0))
1266 goto fail;
1268 /* Enable interrupt */
1269 r = ioctl(fd, HPET_IE_ON, 0);
1270 if (r < 0)
1271 goto fail;
1273 enable_sigio_timer(fd);
1274 t->priv = (void *)(long)fd;
1276 return 0;
1277 fail:
1278 close(fd);
1279 return -1;
1282 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1284 int fd = (long)t->priv;
1286 close(fd);
1289 static int rtc_start_timer(struct qemu_alarm_timer *t)
1291 int rtc_fd;
1292 unsigned long current_rtc_freq = 0;
1294 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1295 if (rtc_fd < 0)
1296 return -1;
1297 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1298 if (current_rtc_freq != RTC_FREQ &&
1299 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1300 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1301 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1302 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1303 goto fail;
1305 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1306 fail:
1307 close(rtc_fd);
1308 return -1;
1311 enable_sigio_timer(rtc_fd);
1313 t->priv = (void *)(long)rtc_fd;
1315 return 0;
1318 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1320 int rtc_fd = (long)t->priv;
1322 close(rtc_fd);
1325 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1327 struct sigevent ev;
1328 timer_t host_timer;
1329 struct sigaction act;
1331 sigfillset(&act.sa_mask);
1332 act.sa_flags = 0;
1333 act.sa_handler = host_alarm_handler;
1335 sigaction(SIGALRM, &act, NULL);
1338 * Initialize ev struct to 0 to avoid valgrind complaining
1339 * about uninitialized data in timer_create call
1341 memset(&ev, 0, sizeof(ev));
1342 ev.sigev_value.sival_int = 0;
1343 ev.sigev_notify = SIGEV_SIGNAL;
1344 ev.sigev_signo = SIGALRM;
1346 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1347 perror("timer_create");
1349 /* disable dynticks */
1350 fprintf(stderr, "Dynamic Ticks disabled\n");
1352 return -1;
1355 t->priv = (void *)(long)host_timer;
1357 return 0;
1360 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1362 timer_t host_timer = (timer_t)(long)t->priv;
1364 timer_delete(host_timer);
1367 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1369 timer_t host_timer = (timer_t)(long)t->priv;
1370 struct itimerspec timeout;
1371 int64_t nearest_delta_us = INT64_MAX;
1372 int64_t current_us;
1374 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1375 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1376 !active_timers[QEMU_CLOCK_HOST])
1377 return;
1379 nearest_delta_us = qemu_next_deadline_dyntick();
1381 /* check whether a timer is already running */
1382 if (timer_gettime(host_timer, &timeout)) {
1383 perror("gettime");
1384 fprintf(stderr, "Internal timer error: aborting\n");
1385 exit(1);
1387 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1388 if (current_us && current_us <= nearest_delta_us)
1389 return;
1391 timeout.it_interval.tv_sec = 0;
1392 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1393 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1394 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1395 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1396 perror("settime");
1397 fprintf(stderr, "Internal timer error: aborting\n");
1398 exit(1);
1402 #endif /* defined(__linux__) */
1404 static int unix_start_timer(struct qemu_alarm_timer *t)
1406 struct sigaction act;
1407 struct itimerval itv;
1408 int err;
1410 /* timer signal */
1411 sigfillset(&act.sa_mask);
1412 act.sa_flags = 0;
1413 act.sa_handler = host_alarm_handler;
1415 sigaction(SIGALRM, &act, NULL);
1417 itv.it_interval.tv_sec = 0;
1418 /* for i386 kernel 2.6 to get 1 ms */
1419 itv.it_interval.tv_usec = 999;
1420 itv.it_value.tv_sec = 0;
1421 itv.it_value.tv_usec = 10 * 1000;
1423 err = setitimer(ITIMER_REAL, &itv, NULL);
1424 if (err)
1425 return -1;
1427 return 0;
1430 static void unix_stop_timer(struct qemu_alarm_timer *t)
1432 struct itimerval itv;
1434 memset(&itv, 0, sizeof(itv));
1435 setitimer(ITIMER_REAL, &itv, NULL);
1438 #endif /* !defined(_WIN32) */
1441 #ifdef _WIN32
1443 static int win32_start_timer(struct qemu_alarm_timer *t)
1445 TIMECAPS tc;
1446 struct qemu_alarm_win32 *data = t->priv;
1447 UINT flags;
1449 memset(&tc, 0, sizeof(tc));
1450 timeGetDevCaps(&tc, sizeof(tc));
1452 if (data->period < tc.wPeriodMin)
1453 data->period = tc.wPeriodMin;
1455 timeBeginPeriod(data->period);
1457 flags = TIME_CALLBACK_FUNCTION;
1458 if (alarm_has_dynticks(t))
1459 flags |= TIME_ONESHOT;
1460 else
1461 flags |= TIME_PERIODIC;
1463 data->timerId = timeSetEvent(1, // interval (ms)
1464 data->period, // resolution
1465 host_alarm_handler, // function
1466 (DWORD)t, // parameter
1467 flags);
1469 if (!data->timerId) {
1470 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1471 GetLastError());
1472 timeEndPeriod(data->period);
1473 return -1;
1476 return 0;
1479 static void win32_stop_timer(struct qemu_alarm_timer *t)
1481 struct qemu_alarm_win32 *data = t->priv;
1483 timeKillEvent(data->timerId);
1484 timeEndPeriod(data->period);
1487 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1489 struct qemu_alarm_win32 *data = t->priv;
1491 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1492 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1493 !active_timers[QEMU_CLOCK_HOST])
1494 return;
1496 timeKillEvent(data->timerId);
1498 data->timerId = timeSetEvent(1,
1499 data->period,
1500 host_alarm_handler,
1501 (DWORD)t,
1502 TIME_ONESHOT | TIME_PERIODIC);
1504 if (!data->timerId) {
1505 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1506 GetLastError());
1508 timeEndPeriod(data->period);
1509 exit(1);
1513 #endif /* _WIN32 */
1515 static int init_timer_alarm(void)
1517 struct qemu_alarm_timer *t = NULL;
1518 int i, err = -1;
1520 for (i = 0; alarm_timers[i].name; i++) {
1521 t = &alarm_timers[i];
1523 err = t->start(t);
1524 if (!err)
1525 break;
1528 if (err) {
1529 err = -ENOENT;
1530 goto fail;
1533 alarm_timer = t;
1535 return 0;
1537 fail:
1538 return err;
1541 static void quit_timers(void)
1543 alarm_timer->stop(alarm_timer);
1544 alarm_timer = NULL;
1547 /***********************************************************/
1548 /* host time/date access */
1549 void qemu_get_timedate(struct tm *tm, int offset)
1551 time_t ti;
1552 struct tm *ret;
1554 time(&ti);
1555 ti += offset;
1556 if (rtc_date_offset == -1) {
1557 if (rtc_utc)
1558 ret = gmtime(&ti);
1559 else
1560 ret = localtime(&ti);
1561 } else {
1562 ti -= rtc_date_offset;
1563 ret = gmtime(&ti);
1566 memcpy(tm, ret, sizeof(struct tm));
1569 int qemu_timedate_diff(struct tm *tm)
1571 time_t seconds;
1573 if (rtc_date_offset == -1)
1574 if (rtc_utc)
1575 seconds = mktimegm(tm);
1576 else
1577 seconds = mktime(tm);
1578 else
1579 seconds = mktimegm(tm) + rtc_date_offset;
1581 return seconds - time(NULL);
1584 static void configure_rtc_date_offset(const char *startdate, int legacy)
1586 time_t rtc_start_date;
1587 struct tm tm;
1589 if (!strcmp(startdate, "now") && legacy) {
1590 rtc_date_offset = -1;
1591 } else {
1592 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1593 &tm.tm_year,
1594 &tm.tm_mon,
1595 &tm.tm_mday,
1596 &tm.tm_hour,
1597 &tm.tm_min,
1598 &tm.tm_sec) == 6) {
1599 /* OK */
1600 } else if (sscanf(startdate, "%d-%d-%d",
1601 &tm.tm_year,
1602 &tm.tm_mon,
1603 &tm.tm_mday) == 3) {
1604 tm.tm_hour = 0;
1605 tm.tm_min = 0;
1606 tm.tm_sec = 0;
1607 } else {
1608 goto date_fail;
1610 tm.tm_year -= 1900;
1611 tm.tm_mon--;
1612 rtc_start_date = mktimegm(&tm);
1613 if (rtc_start_date == -1) {
1614 date_fail:
1615 fprintf(stderr, "Invalid date format. Valid formats are:\n"
1616 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1617 exit(1);
1619 rtc_date_offset = time(NULL) - rtc_start_date;
1623 static void configure_rtc(QemuOpts *opts)
1625 const char *value;
1627 value = qemu_opt_get(opts, "base");
1628 if (value) {
1629 if (!strcmp(value, "utc")) {
1630 rtc_utc = 1;
1631 } else if (!strcmp(value, "localtime")) {
1632 rtc_utc = 0;
1633 } else {
1634 configure_rtc_date_offset(value, 0);
1637 value = qemu_opt_get(opts, "clock");
1638 if (value) {
1639 if (!strcmp(value, "host")) {
1640 rtc_clock = host_clock;
1641 } else if (!strcmp(value, "vm")) {
1642 rtc_clock = vm_clock;
1643 } else {
1644 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1645 exit(1);
1648 #ifdef CONFIG_TARGET_I386
1649 value = qemu_opt_get(opts, "driftfix");
1650 if (value) {
1651 if (!strcmp(buf, "slew")) {
1652 rtc_td_hack = 1;
1653 } else if (!strcmp(buf, "none")) {
1654 rtc_td_hack = 0;
1655 } else {
1656 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1657 exit(1);
1660 #endif
1663 #ifdef _WIN32
1664 static void socket_cleanup(void)
1666 WSACleanup();
1669 static int socket_init(void)
1671 WSADATA Data;
1672 int ret, err;
1674 ret = WSAStartup(MAKEWORD(2,2), &Data);
1675 if (ret != 0) {
1676 err = WSAGetLastError();
1677 fprintf(stderr, "WSAStartup: %d\n", err);
1678 return -1;
1680 atexit(socket_cleanup);
1681 return 0;
1683 #endif
1685 /***********************************************************/
1686 /* Bluetooth support */
1687 static int nb_hcis;
1688 static int cur_hci;
1689 static struct HCIInfo *hci_table[MAX_NICS];
1691 static struct bt_vlan_s {
1692 struct bt_scatternet_s net;
1693 int id;
1694 struct bt_vlan_s *next;
1695 } *first_bt_vlan;
1697 /* find or alloc a new bluetooth "VLAN" */
1698 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1700 struct bt_vlan_s **pvlan, *vlan;
1701 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1702 if (vlan->id == id)
1703 return &vlan->net;
1705 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1706 vlan->id = id;
1707 pvlan = &first_bt_vlan;
1708 while (*pvlan != NULL)
1709 pvlan = &(*pvlan)->next;
1710 *pvlan = vlan;
1711 return &vlan->net;
1714 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1718 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1720 return -ENOTSUP;
1723 static struct HCIInfo null_hci = {
1724 .cmd_send = null_hci_send,
1725 .sco_send = null_hci_send,
1726 .acl_send = null_hci_send,
1727 .bdaddr_set = null_hci_addr_set,
1730 struct HCIInfo *qemu_next_hci(void)
1732 if (cur_hci == nb_hcis)
1733 return &null_hci;
1735 return hci_table[cur_hci++];
1738 static struct HCIInfo *hci_init(const char *str)
1740 char *endp;
1741 struct bt_scatternet_s *vlan = 0;
1743 if (!strcmp(str, "null"))
1744 /* null */
1745 return &null_hci;
1746 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1747 /* host[:hciN] */
1748 return bt_host_hci(str[4] ? str + 5 : "hci0");
1749 else if (!strncmp(str, "hci", 3)) {
1750 /* hci[,vlan=n] */
1751 if (str[3]) {
1752 if (!strncmp(str + 3, ",vlan=", 6)) {
1753 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1754 if (*endp)
1755 vlan = 0;
1757 } else
1758 vlan = qemu_find_bt_vlan(0);
1759 if (vlan)
1760 return bt_new_hci(vlan);
1763 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1765 return 0;
1768 static int bt_hci_parse(const char *str)
1770 struct HCIInfo *hci;
1771 bdaddr_t bdaddr;
1773 if (nb_hcis >= MAX_NICS) {
1774 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1775 return -1;
1778 hci = hci_init(str);
1779 if (!hci)
1780 return -1;
1782 bdaddr.b[0] = 0x52;
1783 bdaddr.b[1] = 0x54;
1784 bdaddr.b[2] = 0x00;
1785 bdaddr.b[3] = 0x12;
1786 bdaddr.b[4] = 0x34;
1787 bdaddr.b[5] = 0x56 + nb_hcis;
1788 hci->bdaddr_set(hci, bdaddr.b);
1790 hci_table[nb_hcis++] = hci;
1792 return 0;
1795 static void bt_vhci_add(int vlan_id)
1797 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1799 if (!vlan->slave)
1800 fprintf(stderr, "qemu: warning: adding a VHCI to "
1801 "an empty scatternet %i\n", vlan_id);
1803 bt_vhci_init(bt_new_hci(vlan));
1806 static struct bt_device_s *bt_device_add(const char *opt)
1808 struct bt_scatternet_s *vlan;
1809 int vlan_id = 0;
1810 char *endp = strstr(opt, ",vlan=");
1811 int len = (endp ? endp - opt : strlen(opt)) + 1;
1812 char devname[10];
1814 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1816 if (endp) {
1817 vlan_id = strtol(endp + 6, &endp, 0);
1818 if (*endp) {
1819 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1820 return 0;
1824 vlan = qemu_find_bt_vlan(vlan_id);
1826 if (!vlan->slave)
1827 fprintf(stderr, "qemu: warning: adding a slave device to "
1828 "an empty scatternet %i\n", vlan_id);
1830 if (!strcmp(devname, "keyboard"))
1831 return bt_keyboard_init(vlan);
1833 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1834 return 0;
1837 static int bt_parse(const char *opt)
1839 const char *endp, *p;
1840 int vlan;
1842 if (strstart(opt, "hci", &endp)) {
1843 if (!*endp || *endp == ',') {
1844 if (*endp)
1845 if (!strstart(endp, ",vlan=", 0))
1846 opt = endp + 1;
1848 return bt_hci_parse(opt);
1850 } else if (strstart(opt, "vhci", &endp)) {
1851 if (!*endp || *endp == ',') {
1852 if (*endp) {
1853 if (strstart(endp, ",vlan=", &p)) {
1854 vlan = strtol(p, (char **) &endp, 0);
1855 if (*endp) {
1856 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1857 return 1;
1859 } else {
1860 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1861 return 1;
1863 } else
1864 vlan = 0;
1866 bt_vhci_add(vlan);
1867 return 0;
1869 } else if (strstart(opt, "device:", &endp))
1870 return !bt_device_add(endp);
1872 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1873 return 1;
1876 /***********************************************************/
1877 /* QEMU Block devices */
1879 #define HD_ALIAS "index=%d,media=disk"
1880 #define CDROM_ALIAS "index=2,media=cdrom"
1881 #define FD_ALIAS "index=%d,if=floppy"
1882 #define PFLASH_ALIAS "if=pflash"
1883 #define MTD_ALIAS "if=mtd"
1884 #define SD_ALIAS "index=0,if=sd"
1886 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1888 va_list ap;
1889 char optstr[1024];
1890 QemuOpts *opts;
1892 va_start(ap, fmt);
1893 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1894 va_end(ap);
1896 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1897 if (!opts) {
1898 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1899 __FUNCTION__, optstr);
1900 return NULL;
1902 if (file)
1903 qemu_opt_set(opts, "file", file);
1904 return opts;
1907 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1909 DriveInfo *dinfo;
1911 /* seek interface, bus and unit */
1913 QTAILQ_FOREACH(dinfo, &drives, next) {
1914 if (dinfo->type == type &&
1915 dinfo->bus == bus &&
1916 dinfo->unit == unit)
1917 return dinfo;
1920 return NULL;
1923 DriveInfo *drive_get_by_id(const char *id)
1925 DriveInfo *dinfo;
1927 QTAILQ_FOREACH(dinfo, &drives, next) {
1928 if (strcmp(id, dinfo->id))
1929 continue;
1930 return dinfo;
1932 return NULL;
1935 int drive_get_max_bus(BlockInterfaceType type)
1937 int max_bus;
1938 DriveInfo *dinfo;
1940 max_bus = -1;
1941 QTAILQ_FOREACH(dinfo, &drives, next) {
1942 if(dinfo->type == type &&
1943 dinfo->bus > max_bus)
1944 max_bus = dinfo->bus;
1946 return max_bus;
1949 const char *drive_get_serial(BlockDriverState *bdrv)
1951 DriveInfo *dinfo;
1953 QTAILQ_FOREACH(dinfo, &drives, next) {
1954 if (dinfo->bdrv == bdrv)
1955 return dinfo->serial;
1958 return "\0";
1961 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1963 DriveInfo *dinfo;
1965 QTAILQ_FOREACH(dinfo, &drives, next) {
1966 if (dinfo->bdrv == bdrv)
1967 return dinfo->onerror;
1970 return BLOCK_ERR_STOP_ENOSPC;
1973 static void bdrv_format_print(void *opaque, const char *name)
1975 fprintf(stderr, " %s", name);
1978 void drive_uninit(DriveInfo *dinfo)
1980 qemu_opts_del(dinfo->opts);
1981 bdrv_delete(dinfo->bdrv);
1982 QTAILQ_REMOVE(&drives, dinfo, next);
1983 qemu_free(dinfo);
1986 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1987 int *fatal_error)
1989 const char *buf;
1990 const char *file = NULL;
1991 char devname[128];
1992 const char *serial;
1993 const char *mediastr = "";
1994 BlockInterfaceType type;
1995 enum { MEDIA_DISK, MEDIA_CDROM } media;
1996 int bus_id, unit_id;
1997 int cyls, heads, secs, translation;
1998 BlockDriver *drv = NULL;
1999 QEMUMachine *machine = opaque;
2000 int max_devs;
2001 int index;
2002 int cache;
2003 int aio = 0;
2004 int ro = 0;
2005 int bdrv_flags, onerror;
2006 const char *devaddr;
2007 DriveInfo *dinfo;
2008 int snapshot = 0;
2010 *fatal_error = 1;
2012 translation = BIOS_ATA_TRANSLATION_AUTO;
2013 cache = 1;
2015 if (machine && machine->use_scsi) {
2016 type = IF_SCSI;
2017 max_devs = MAX_SCSI_DEVS;
2018 pstrcpy(devname, sizeof(devname), "scsi");
2019 } else {
2020 type = IF_IDE;
2021 max_devs = MAX_IDE_DEVS;
2022 pstrcpy(devname, sizeof(devname), "ide");
2024 media = MEDIA_DISK;
2026 /* extract parameters */
2027 bus_id = qemu_opt_get_number(opts, "bus", 0);
2028 unit_id = qemu_opt_get_number(opts, "unit", -1);
2029 index = qemu_opt_get_number(opts, "index", -1);
2031 cyls = qemu_opt_get_number(opts, "cyls", 0);
2032 heads = qemu_opt_get_number(opts, "heads", 0);
2033 secs = qemu_opt_get_number(opts, "secs", 0);
2035 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
2036 ro = qemu_opt_get_bool(opts, "readonly", 0);
2038 file = qemu_opt_get(opts, "file");
2039 serial = qemu_opt_get(opts, "serial");
2041 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
2042 pstrcpy(devname, sizeof(devname), buf);
2043 if (!strcmp(buf, "ide")) {
2044 type = IF_IDE;
2045 max_devs = MAX_IDE_DEVS;
2046 } else if (!strcmp(buf, "scsi")) {
2047 type = IF_SCSI;
2048 max_devs = MAX_SCSI_DEVS;
2049 } else if (!strcmp(buf, "floppy")) {
2050 type = IF_FLOPPY;
2051 max_devs = 0;
2052 } else if (!strcmp(buf, "pflash")) {
2053 type = IF_PFLASH;
2054 max_devs = 0;
2055 } else if (!strcmp(buf, "mtd")) {
2056 type = IF_MTD;
2057 max_devs = 0;
2058 } else if (!strcmp(buf, "sd")) {
2059 type = IF_SD;
2060 max_devs = 0;
2061 } else if (!strcmp(buf, "virtio")) {
2062 type = IF_VIRTIO;
2063 max_devs = 0;
2064 } else if (!strcmp(buf, "xen")) {
2065 type = IF_XEN;
2066 max_devs = 0;
2067 } else if (!strcmp(buf, "none")) {
2068 type = IF_NONE;
2069 max_devs = 0;
2070 } else {
2071 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
2072 return NULL;
2076 if (cyls || heads || secs) {
2077 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
2078 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2079 return NULL;
2081 if (heads < 1 || (type == IF_IDE && heads > 16)) {
2082 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2083 return NULL;
2085 if (secs < 1 || (type == IF_IDE && secs > 63)) {
2086 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2087 return NULL;
2091 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2092 if (!cyls) {
2093 fprintf(stderr,
2094 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2095 buf);
2096 return NULL;
2098 if (!strcmp(buf, "none"))
2099 translation = BIOS_ATA_TRANSLATION_NONE;
2100 else if (!strcmp(buf, "lba"))
2101 translation = BIOS_ATA_TRANSLATION_LBA;
2102 else if (!strcmp(buf, "auto"))
2103 translation = BIOS_ATA_TRANSLATION_AUTO;
2104 else {
2105 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2106 return NULL;
2110 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2111 if (!strcmp(buf, "disk")) {
2112 media = MEDIA_DISK;
2113 } else if (!strcmp(buf, "cdrom")) {
2114 if (cyls || secs || heads) {
2115 fprintf(stderr,
2116 "qemu: '%s' invalid physical CHS format\n", buf);
2117 return NULL;
2119 media = MEDIA_CDROM;
2120 } else {
2121 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2122 return NULL;
2126 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2127 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2128 cache = 0;
2129 else if (!strcmp(buf, "writethrough"))
2130 cache = 1;
2131 else if (!strcmp(buf, "writeback"))
2132 cache = 2;
2133 else {
2134 fprintf(stderr, "qemu: invalid cache option\n");
2135 return NULL;
2139 #ifdef CONFIG_LINUX_AIO
2140 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2141 if (!strcmp(buf, "threads"))
2142 aio = 0;
2143 else if (!strcmp(buf, "native"))
2144 aio = 1;
2145 else {
2146 fprintf(stderr, "qemu: invalid aio option\n");
2147 return NULL;
2150 #endif
2152 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2153 if (strcmp(buf, "?") == 0) {
2154 fprintf(stderr, "qemu: Supported formats:");
2155 bdrv_iterate_format(bdrv_format_print, NULL);
2156 fprintf(stderr, "\n");
2157 return NULL;
2159 drv = bdrv_find_whitelisted_format(buf);
2160 if (!drv) {
2161 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2162 return NULL;
2166 onerror = BLOCK_ERR_STOP_ENOSPC;
2167 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2168 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2169 fprintf(stderr, "werror is no supported by this format\n");
2170 return NULL;
2172 if (!strcmp(buf, "ignore"))
2173 onerror = BLOCK_ERR_IGNORE;
2174 else if (!strcmp(buf, "enospc"))
2175 onerror = BLOCK_ERR_STOP_ENOSPC;
2176 else if (!strcmp(buf, "stop"))
2177 onerror = BLOCK_ERR_STOP_ANY;
2178 else if (!strcmp(buf, "report"))
2179 onerror = BLOCK_ERR_REPORT;
2180 else {
2181 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2182 return NULL;
2186 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2187 if (type != IF_VIRTIO) {
2188 fprintf(stderr, "addr is not supported\n");
2189 return NULL;
2193 /* compute bus and unit according index */
2195 if (index != -1) {
2196 if (bus_id != 0 || unit_id != -1) {
2197 fprintf(stderr,
2198 "qemu: index cannot be used with bus and unit\n");
2199 return NULL;
2201 if (max_devs == 0)
2203 unit_id = index;
2204 bus_id = 0;
2205 } else {
2206 unit_id = index % max_devs;
2207 bus_id = index / max_devs;
2211 /* if user doesn't specify a unit_id,
2212 * try to find the first free
2215 if (unit_id == -1) {
2216 unit_id = 0;
2217 while (drive_get(type, bus_id, unit_id) != NULL) {
2218 unit_id++;
2219 if (max_devs && unit_id >= max_devs) {
2220 unit_id -= max_devs;
2221 bus_id++;
2226 /* check unit id */
2228 if (max_devs && unit_id >= max_devs) {
2229 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2230 unit_id, max_devs - 1);
2231 return NULL;
2235 * ignore multiple definitions
2238 if (drive_get(type, bus_id, unit_id) != NULL) {
2239 *fatal_error = 0;
2240 return NULL;
2243 /* init */
2245 dinfo = qemu_mallocz(sizeof(*dinfo));
2246 if ((buf = qemu_opts_id(opts)) != NULL) {
2247 dinfo->id = qemu_strdup(buf);
2248 } else {
2249 /* no id supplied -> create one */
2250 dinfo->id = qemu_mallocz(32);
2251 if (type == IF_IDE || type == IF_SCSI)
2252 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2253 if (max_devs)
2254 snprintf(dinfo->id, 32, "%s%i%s%i",
2255 devname, bus_id, mediastr, unit_id);
2256 else
2257 snprintf(dinfo->id, 32, "%s%s%i",
2258 devname, mediastr, unit_id);
2260 dinfo->bdrv = bdrv_new(dinfo->id);
2261 dinfo->devaddr = devaddr;
2262 dinfo->type = type;
2263 dinfo->bus = bus_id;
2264 dinfo->unit = unit_id;
2265 dinfo->onerror = onerror;
2266 dinfo->opts = opts;
2267 if (serial)
2268 strncpy(dinfo->serial, serial, sizeof(serial));
2269 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2271 switch(type) {
2272 case IF_IDE:
2273 case IF_SCSI:
2274 case IF_XEN:
2275 case IF_NONE:
2276 switch(media) {
2277 case MEDIA_DISK:
2278 if (cyls != 0) {
2279 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2280 bdrv_set_translation_hint(dinfo->bdrv, translation);
2282 break;
2283 case MEDIA_CDROM:
2284 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2285 break;
2287 break;
2288 case IF_SD:
2289 /* FIXME: This isn't really a floppy, but it's a reasonable
2290 approximation. */
2291 case IF_FLOPPY:
2292 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2293 break;
2294 case IF_PFLASH:
2295 case IF_MTD:
2296 break;
2297 case IF_VIRTIO:
2298 /* add virtio block device */
2299 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2300 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2301 qemu_opt_set(opts, "drive", dinfo->id);
2302 if (devaddr)
2303 qemu_opt_set(opts, "addr", devaddr);
2304 break;
2305 case IF_COUNT:
2306 abort();
2308 if (!file) {
2309 *fatal_error = 0;
2310 return NULL;
2312 bdrv_flags = 0;
2313 if (snapshot) {
2314 bdrv_flags |= BDRV_O_SNAPSHOT;
2315 cache = 2; /* always use write-back with snapshot */
2317 if (cache == 0) /* no caching */
2318 bdrv_flags |= BDRV_O_NOCACHE;
2319 else if (cache == 2) /* write-back */
2320 bdrv_flags |= BDRV_O_CACHE_WB;
2322 if (aio == 1) {
2323 bdrv_flags |= BDRV_O_NATIVE_AIO;
2324 } else {
2325 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2328 if (ro == 1) {
2329 if (type == IF_IDE) {
2330 fprintf(stderr, "qemu: readonly flag not supported for drive with ide interface\n");
2331 return NULL;
2333 (void)bdrv_set_read_only(dinfo->bdrv, 1);
2336 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2337 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2338 file, strerror(errno));
2339 return NULL;
2342 if (bdrv_key_required(dinfo->bdrv))
2343 autostart = 0;
2344 *fatal_error = 0;
2345 return dinfo;
2348 static int drive_init_func(QemuOpts *opts, void *opaque)
2350 QEMUMachine *machine = opaque;
2351 int fatal_error = 0;
2353 if (drive_init(opts, machine, &fatal_error) == NULL) {
2354 if (fatal_error)
2355 return 1;
2357 return 0;
2360 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2362 if (NULL == qemu_opt_get(opts, "snapshot")) {
2363 qemu_opt_set(opts, "snapshot", "on");
2365 return 0;
2368 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2370 boot_set_handler = func;
2371 boot_set_opaque = opaque;
2374 int qemu_boot_set(const char *boot_devices)
2376 if (!boot_set_handler) {
2377 return -EINVAL;
2379 return boot_set_handler(boot_set_opaque, boot_devices);
2382 static int parse_bootdevices(char *devices)
2384 /* We just do some generic consistency checks */
2385 const char *p;
2386 int bitmap = 0;
2388 for (p = devices; *p != '\0'; p++) {
2389 /* Allowed boot devices are:
2390 * a-b: floppy disk drives
2391 * c-f: IDE disk drives
2392 * g-m: machine implementation dependant drives
2393 * n-p: network devices
2394 * It's up to each machine implementation to check if the given boot
2395 * devices match the actual hardware implementation and firmware
2396 * features.
2398 if (*p < 'a' || *p > 'p') {
2399 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2400 exit(1);
2402 if (bitmap & (1 << (*p - 'a'))) {
2403 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2404 exit(1);
2406 bitmap |= 1 << (*p - 'a');
2408 return bitmap;
2411 static void restore_boot_devices(void *opaque)
2413 char *standard_boot_devices = opaque;
2415 qemu_boot_set(standard_boot_devices);
2417 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2418 qemu_free(standard_boot_devices);
2421 static void numa_add(const char *optarg)
2423 char option[128];
2424 char *endptr;
2425 unsigned long long value, endvalue;
2426 int nodenr;
2428 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2429 if (!strcmp(option, "node")) {
2430 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2431 nodenr = nb_numa_nodes;
2432 } else {
2433 nodenr = strtoull(option, NULL, 10);
2436 if (get_param_value(option, 128, "mem", optarg) == 0) {
2437 node_mem[nodenr] = 0;
2438 } else {
2439 value = strtoull(option, &endptr, 0);
2440 switch (*endptr) {
2441 case 0: case 'M': case 'm':
2442 value <<= 20;
2443 break;
2444 case 'G': case 'g':
2445 value <<= 30;
2446 break;
2448 node_mem[nodenr] = value;
2450 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2451 node_cpumask[nodenr] = 0;
2452 } else {
2453 value = strtoull(option, &endptr, 10);
2454 if (value >= 64) {
2455 value = 63;
2456 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2457 } else {
2458 if (*endptr == '-') {
2459 endvalue = strtoull(endptr+1, &endptr, 10);
2460 if (endvalue >= 63) {
2461 endvalue = 62;
2462 fprintf(stderr,
2463 "only 63 CPUs in NUMA mode supported.\n");
2465 value = (1 << (endvalue + 1)) - (1 << value);
2466 } else {
2467 value = 1 << value;
2470 node_cpumask[nodenr] = value;
2472 nb_numa_nodes++;
2474 return;
2477 static void smp_parse(const char *optarg)
2479 int smp, sockets = 0, threads = 0, cores = 0;
2480 char *endptr;
2481 char option[128];
2483 smp = strtoul(optarg, &endptr, 10);
2484 if (endptr != optarg) {
2485 if (*endptr == ',') {
2486 endptr++;
2489 if (get_param_value(option, 128, "sockets", endptr) != 0)
2490 sockets = strtoull(option, NULL, 10);
2491 if (get_param_value(option, 128, "cores", endptr) != 0)
2492 cores = strtoull(option, NULL, 10);
2493 if (get_param_value(option, 128, "threads", endptr) != 0)
2494 threads = strtoull(option, NULL, 10);
2495 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2496 max_cpus = strtoull(option, NULL, 10);
2498 /* compute missing values, prefer sockets over cores over threads */
2499 if (smp == 0 || sockets == 0) {
2500 sockets = sockets > 0 ? sockets : 1;
2501 cores = cores > 0 ? cores : 1;
2502 threads = threads > 0 ? threads : 1;
2503 if (smp == 0) {
2504 smp = cores * threads * sockets;
2505 } else {
2506 sockets = smp / (cores * threads);
2508 } else {
2509 if (cores == 0) {
2510 threads = threads > 0 ? threads : 1;
2511 cores = smp / (sockets * threads);
2512 } else {
2513 if (sockets == 0) {
2514 sockets = smp / (cores * threads);
2515 } else {
2516 threads = smp / (cores * sockets);
2520 smp_cpus = smp;
2521 smp_cores = cores > 0 ? cores : 1;
2522 smp_threads = threads > 0 ? threads : 1;
2523 if (max_cpus == 0)
2524 max_cpus = smp_cpus;
2527 /***********************************************************/
2528 /* USB devices */
2530 static int usb_device_add(const char *devname, int is_hotplug)
2532 const char *p;
2533 USBDevice *dev = NULL;
2535 if (!usb_enabled)
2536 return -1;
2538 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2539 dev = usbdevice_create(devname);
2540 if (dev)
2541 goto done;
2543 /* the other ones */
2544 if (strstart(devname, "host:", &p)) {
2545 dev = usb_host_device_open(p);
2546 } else if (strstart(devname, "net:", &p)) {
2547 QemuOpts *opts;
2548 int idx;
2550 opts = qemu_opts_parse(&qemu_net_opts, p, NULL);
2551 if (!opts) {
2552 return -1;
2555 qemu_opt_set(opts, "type", "nic");
2556 qemu_opt_set(opts, "model", "usb");
2558 idx = net_client_init(NULL, opts, 0);
2559 if (idx == -1) {
2560 return -1;
2563 dev = usb_net_init(&nd_table[idx]);
2564 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2565 dev = usb_bt_init(devname[2] ? hci_init(p) :
2566 bt_new_hci(qemu_find_bt_vlan(0)));
2567 } else {
2568 return -1;
2570 if (!dev)
2571 return -1;
2573 done:
2574 return 0;
2577 static int usb_device_del(const char *devname)
2579 int bus_num, addr;
2580 const char *p;
2582 if (strstart(devname, "host:", &p))
2583 return usb_host_device_close(p);
2585 if (!usb_enabled)
2586 return -1;
2588 p = strchr(devname, '.');
2589 if (!p)
2590 return -1;
2591 bus_num = strtoul(devname, NULL, 0);
2592 addr = strtoul(p + 1, NULL, 0);
2594 return usb_device_delete_addr(bus_num, addr);
2597 static int usb_parse(const char *cmdline)
2599 return usb_device_add(cmdline, 0);
2602 void do_usb_add(Monitor *mon, const QDict *qdict)
2604 usb_device_add(qdict_get_str(qdict, "devname"), 1);
2607 void do_usb_del(Monitor *mon, const QDict *qdict)
2609 usb_device_del(qdict_get_str(qdict, "devname"));
2612 /***********************************************************/
2613 /* PCMCIA/Cardbus */
2615 static struct pcmcia_socket_entry_s {
2616 PCMCIASocket *socket;
2617 struct pcmcia_socket_entry_s *next;
2618 } *pcmcia_sockets = 0;
2620 void pcmcia_socket_register(PCMCIASocket *socket)
2622 struct pcmcia_socket_entry_s *entry;
2624 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2625 entry->socket = socket;
2626 entry->next = pcmcia_sockets;
2627 pcmcia_sockets = entry;
2630 void pcmcia_socket_unregister(PCMCIASocket *socket)
2632 struct pcmcia_socket_entry_s *entry, **ptr;
2634 ptr = &pcmcia_sockets;
2635 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2636 if (entry->socket == socket) {
2637 *ptr = entry->next;
2638 qemu_free(entry);
2642 void pcmcia_info(Monitor *mon)
2644 struct pcmcia_socket_entry_s *iter;
2646 if (!pcmcia_sockets)
2647 monitor_printf(mon, "No PCMCIA sockets\n");
2649 for (iter = pcmcia_sockets; iter; iter = iter->next)
2650 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2651 iter->socket->attached ? iter->socket->card_string :
2652 "Empty");
2655 /***********************************************************/
2656 /* register display */
2658 struct DisplayAllocator default_allocator = {
2659 defaultallocator_create_displaysurface,
2660 defaultallocator_resize_displaysurface,
2661 defaultallocator_free_displaysurface
2664 void register_displaystate(DisplayState *ds)
2666 DisplayState **s;
2667 s = &display_state;
2668 while (*s != NULL)
2669 s = &(*s)->next;
2670 ds->next = NULL;
2671 *s = ds;
2674 DisplayState *get_displaystate(void)
2676 return display_state;
2679 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2681 if(ds->allocator == &default_allocator) ds->allocator = da;
2682 return ds->allocator;
2685 /* dumb display */
2687 static void dumb_display_init(void)
2689 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2690 ds->allocator = &default_allocator;
2691 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2692 register_displaystate(ds);
2695 /***********************************************************/
2696 /* I/O handling */
2698 typedef struct IOHandlerRecord {
2699 int fd;
2700 IOCanRWHandler *fd_read_poll;
2701 IOHandler *fd_read;
2702 IOHandler *fd_write;
2703 int deleted;
2704 void *opaque;
2705 /* temporary data */
2706 struct pollfd *ufd;
2707 struct IOHandlerRecord *next;
2708 } IOHandlerRecord;
2710 static IOHandlerRecord *first_io_handler;
2712 /* XXX: fd_read_poll should be suppressed, but an API change is
2713 necessary in the character devices to suppress fd_can_read(). */
2714 int qemu_set_fd_handler2(int fd,
2715 IOCanRWHandler *fd_read_poll,
2716 IOHandler *fd_read,
2717 IOHandler *fd_write,
2718 void *opaque)
2720 IOHandlerRecord **pioh, *ioh;
2722 if (!fd_read && !fd_write) {
2723 pioh = &first_io_handler;
2724 for(;;) {
2725 ioh = *pioh;
2726 if (ioh == NULL)
2727 break;
2728 if (ioh->fd == fd) {
2729 ioh->deleted = 1;
2730 break;
2732 pioh = &ioh->next;
2734 } else {
2735 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2736 if (ioh->fd == fd)
2737 goto found;
2739 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2740 ioh->next = first_io_handler;
2741 first_io_handler = ioh;
2742 found:
2743 ioh->fd = fd;
2744 ioh->fd_read_poll = fd_read_poll;
2745 ioh->fd_read = fd_read;
2746 ioh->fd_write = fd_write;
2747 ioh->opaque = opaque;
2748 ioh->deleted = 0;
2750 return 0;
2753 int qemu_set_fd_handler(int fd,
2754 IOHandler *fd_read,
2755 IOHandler *fd_write,
2756 void *opaque)
2758 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2761 #ifdef _WIN32
2762 /***********************************************************/
2763 /* Polling handling */
2765 typedef struct PollingEntry {
2766 PollingFunc *func;
2767 void *opaque;
2768 struct PollingEntry *next;
2769 } PollingEntry;
2771 static PollingEntry *first_polling_entry;
2773 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2775 PollingEntry **ppe, *pe;
2776 pe = qemu_mallocz(sizeof(PollingEntry));
2777 pe->func = func;
2778 pe->opaque = opaque;
2779 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2780 *ppe = pe;
2781 return 0;
2784 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2786 PollingEntry **ppe, *pe;
2787 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2788 pe = *ppe;
2789 if (pe->func == func && pe->opaque == opaque) {
2790 *ppe = pe->next;
2791 qemu_free(pe);
2792 break;
2797 /***********************************************************/
2798 /* Wait objects support */
2799 typedef struct WaitObjects {
2800 int num;
2801 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2802 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2803 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2804 } WaitObjects;
2806 static WaitObjects wait_objects = {0};
2808 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2810 WaitObjects *w = &wait_objects;
2812 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2813 return -1;
2814 w->events[w->num] = handle;
2815 w->func[w->num] = func;
2816 w->opaque[w->num] = opaque;
2817 w->num++;
2818 return 0;
2821 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2823 int i, found;
2824 WaitObjects *w = &wait_objects;
2826 found = 0;
2827 for (i = 0; i < w->num; i++) {
2828 if (w->events[i] == handle)
2829 found = 1;
2830 if (found) {
2831 w->events[i] = w->events[i + 1];
2832 w->func[i] = w->func[i + 1];
2833 w->opaque[i] = w->opaque[i + 1];
2836 if (found)
2837 w->num--;
2839 #endif
2841 /***********************************************************/
2842 /* ram save/restore */
2844 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2845 #define RAM_SAVE_FLAG_COMPRESS 0x02
2846 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2847 #define RAM_SAVE_FLAG_PAGE 0x08
2848 #define RAM_SAVE_FLAG_EOS 0x10
2850 static int is_dup_page(uint8_t *page, uint8_t ch)
2852 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2853 uint32_t *array = (uint32_t *)page;
2854 int i;
2856 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2857 if (array[i] != val)
2858 return 0;
2861 return 1;
2864 static int ram_save_block(QEMUFile *f)
2866 static ram_addr_t current_addr = 0;
2867 ram_addr_t saved_addr = current_addr;
2868 ram_addr_t addr = 0;
2869 int found = 0;
2871 while (addr < last_ram_offset) {
2872 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2873 uint8_t *p;
2875 cpu_physical_memory_reset_dirty(current_addr,
2876 current_addr + TARGET_PAGE_SIZE,
2877 MIGRATION_DIRTY_FLAG);
2879 p = qemu_get_ram_ptr(current_addr);
2881 if (is_dup_page(p, *p)) {
2882 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2883 qemu_put_byte(f, *p);
2884 } else {
2885 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2886 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2889 found = 1;
2890 break;
2892 addr += TARGET_PAGE_SIZE;
2893 current_addr = (saved_addr + addr) % last_ram_offset;
2896 return found;
2899 static uint64_t bytes_transferred = 0;
2901 static ram_addr_t ram_save_remaining(void)
2903 ram_addr_t addr;
2904 ram_addr_t count = 0;
2906 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2907 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2908 count++;
2911 return count;
2914 uint64_t ram_bytes_remaining(void)
2916 return ram_save_remaining() * TARGET_PAGE_SIZE;
2919 uint64_t ram_bytes_transferred(void)
2921 return bytes_transferred;
2924 uint64_t ram_bytes_total(void)
2926 return last_ram_offset;
2929 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
2931 ram_addr_t addr;
2932 uint64_t bytes_transferred_last;
2933 double bwidth = 0;
2934 uint64_t expected_time = 0;
2936 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2937 qemu_file_set_error(f);
2938 return 0;
2941 if (stage == 1) {
2942 /* Make sure all dirty bits are set */
2943 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2944 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2945 cpu_physical_memory_set_dirty(addr);
2948 /* Enable dirty memory tracking */
2949 cpu_physical_memory_set_dirty_tracking(1);
2951 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2954 bytes_transferred_last = bytes_transferred;
2955 bwidth = get_clock();
2957 while (!qemu_file_rate_limit(f)) {
2958 int ret;
2960 ret = ram_save_block(f);
2961 bytes_transferred += ret * TARGET_PAGE_SIZE;
2962 if (ret == 0) /* no more blocks */
2963 break;
2966 bwidth = get_clock() - bwidth;
2967 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2969 /* if we haven't transferred anything this round, force expected_time to a
2970 * a very high value, but without crashing */
2971 if (bwidth == 0)
2972 bwidth = 0.000001;
2974 /* try transferring iterative blocks of memory */
2976 if (stage == 3) {
2978 /* flush all remaining blocks regardless of rate limiting */
2979 while (ram_save_block(f) != 0) {
2980 bytes_transferred += TARGET_PAGE_SIZE;
2982 cpu_physical_memory_set_dirty_tracking(0);
2985 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2987 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2989 return (stage == 2) && (expected_time <= migrate_max_downtime());
2992 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2994 ram_addr_t addr;
2995 int flags;
2997 if (version_id != 3)
2998 return -EINVAL;
3000 do {
3001 addr = qemu_get_be64(f);
3003 flags = addr & ~TARGET_PAGE_MASK;
3004 addr &= TARGET_PAGE_MASK;
3006 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3007 if (addr != last_ram_offset)
3008 return -EINVAL;
3011 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3012 uint8_t ch = qemu_get_byte(f);
3013 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3014 #ifndef _WIN32
3015 if (ch == 0 &&
3016 (!kvm_enabled() || kvm_has_sync_mmu())) {
3017 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3019 #endif
3020 } else if (flags & RAM_SAVE_FLAG_PAGE)
3021 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3022 } while (!(flags & RAM_SAVE_FLAG_EOS));
3024 return 0;
3027 void qemu_service_io(void)
3029 qemu_notify_event();
3032 /***********************************************************/
3033 /* machine registration */
3035 static QEMUMachine *first_machine = NULL;
3036 QEMUMachine *current_machine = NULL;
3038 int qemu_register_machine(QEMUMachine *m)
3040 QEMUMachine **pm;
3041 pm = &first_machine;
3042 while (*pm != NULL)
3043 pm = &(*pm)->next;
3044 m->next = NULL;
3045 *pm = m;
3046 return 0;
3049 static QEMUMachine *find_machine(const char *name)
3051 QEMUMachine *m;
3053 for(m = first_machine; m != NULL; m = m->next) {
3054 if (!strcmp(m->name, name))
3055 return m;
3056 if (m->alias && !strcmp(m->alias, name))
3057 return m;
3059 return NULL;
3062 static QEMUMachine *find_default_machine(void)
3064 QEMUMachine *m;
3066 for(m = first_machine; m != NULL; m = m->next) {
3067 if (m->is_default) {
3068 return m;
3071 return NULL;
3074 /***********************************************************/
3075 /* main execution loop */
3077 static void gui_update(void *opaque)
3079 uint64_t interval = GUI_REFRESH_INTERVAL;
3080 DisplayState *ds = opaque;
3081 DisplayChangeListener *dcl = ds->listeners;
3083 dpy_refresh(ds);
3085 while (dcl != NULL) {
3086 if (dcl->gui_timer_interval &&
3087 dcl->gui_timer_interval < interval)
3088 interval = dcl->gui_timer_interval;
3089 dcl = dcl->next;
3091 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3094 static void nographic_update(void *opaque)
3096 uint64_t interval = GUI_REFRESH_INTERVAL;
3098 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3101 struct vm_change_state_entry {
3102 VMChangeStateHandler *cb;
3103 void *opaque;
3104 QLIST_ENTRY (vm_change_state_entry) entries;
3107 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3109 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3110 void *opaque)
3112 VMChangeStateEntry *e;
3114 e = qemu_mallocz(sizeof (*e));
3116 e->cb = cb;
3117 e->opaque = opaque;
3118 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3119 return e;
3122 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3124 QLIST_REMOVE (e, entries);
3125 qemu_free (e);
3128 static void vm_state_notify(int running, int reason)
3130 VMChangeStateEntry *e;
3132 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3133 e->cb(e->opaque, running, reason);
3137 static void resume_all_vcpus(void);
3138 static void pause_all_vcpus(void);
3140 void vm_start(void)
3142 if (!vm_running) {
3143 cpu_enable_ticks();
3144 vm_running = 1;
3145 vm_state_notify(1, 0);
3146 qemu_rearm_alarm_timer(alarm_timer);
3147 resume_all_vcpus();
3151 /* reset/shutdown handler */
3153 typedef struct QEMUResetEntry {
3154 QTAILQ_ENTRY(QEMUResetEntry) entry;
3155 QEMUResetHandler *func;
3156 void *opaque;
3157 } QEMUResetEntry;
3159 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3160 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3161 static int reset_requested;
3162 static int shutdown_requested;
3163 static int powerdown_requested;
3164 static int debug_requested;
3165 static int vmstop_requested;
3167 int qemu_shutdown_requested(void)
3169 int r = shutdown_requested;
3170 shutdown_requested = 0;
3171 return r;
3174 int qemu_reset_requested(void)
3176 int r = reset_requested;
3177 reset_requested = 0;
3178 return r;
3181 int qemu_powerdown_requested(void)
3183 int r = powerdown_requested;
3184 powerdown_requested = 0;
3185 return r;
3188 static int qemu_debug_requested(void)
3190 int r = debug_requested;
3191 debug_requested = 0;
3192 return r;
3195 static int qemu_vmstop_requested(void)
3197 int r = vmstop_requested;
3198 vmstop_requested = 0;
3199 return r;
3202 static void do_vm_stop(int reason)
3204 if (vm_running) {
3205 cpu_disable_ticks();
3206 vm_running = 0;
3207 pause_all_vcpus();
3208 vm_state_notify(0, reason);
3212 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3214 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3216 re->func = func;
3217 re->opaque = opaque;
3218 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3221 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3223 QEMUResetEntry *re;
3225 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3226 if (re->func == func && re->opaque == opaque) {
3227 QTAILQ_REMOVE(&reset_handlers, re, entry);
3228 qemu_free(re);
3229 return;
3234 void qemu_system_reset(void)
3236 QEMUResetEntry *re, *nre;
3238 /* reset all devices */
3239 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3240 re->func(re->opaque);
3244 void qemu_system_reset_request(void)
3246 if (no_reboot) {
3247 shutdown_requested = 1;
3248 } else {
3249 reset_requested = 1;
3251 qemu_notify_event();
3254 void qemu_system_shutdown_request(void)
3256 shutdown_requested = 1;
3257 qemu_notify_event();
3260 void qemu_system_powerdown_request(void)
3262 powerdown_requested = 1;
3263 qemu_notify_event();
3266 #ifdef CONFIG_IOTHREAD
3267 static void qemu_system_vmstop_request(int reason)
3269 vmstop_requested = reason;
3270 qemu_notify_event();
3272 #endif
3274 #ifndef _WIN32
3275 static int io_thread_fd = -1;
3277 static void qemu_event_increment(void)
3279 static const char byte = 0;
3281 if (io_thread_fd == -1)
3282 return;
3284 write(io_thread_fd, &byte, sizeof(byte));
3287 static void qemu_event_read(void *opaque)
3289 int fd = (unsigned long)opaque;
3290 ssize_t len;
3292 /* Drain the notify pipe */
3293 do {
3294 char buffer[512];
3295 len = read(fd, buffer, sizeof(buffer));
3296 } while ((len == -1 && errno == EINTR) || len > 0);
3299 static int qemu_event_init(void)
3301 int err;
3302 int fds[2];
3304 err = pipe(fds);
3305 if (err == -1)
3306 return -errno;
3308 err = fcntl_setfl(fds[0], O_NONBLOCK);
3309 if (err < 0)
3310 goto fail;
3312 err = fcntl_setfl(fds[1], O_NONBLOCK);
3313 if (err < 0)
3314 goto fail;
3316 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3317 (void *)(unsigned long)fds[0]);
3319 io_thread_fd = fds[1];
3320 return 0;
3322 fail:
3323 close(fds[0]);
3324 close(fds[1]);
3325 return err;
3327 #else
3328 HANDLE qemu_event_handle;
3330 static void dummy_event_handler(void *opaque)
3334 static int qemu_event_init(void)
3336 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3337 if (!qemu_event_handle) {
3338 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3339 return -1;
3341 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3342 return 0;
3345 static void qemu_event_increment(void)
3347 if (!SetEvent(qemu_event_handle)) {
3348 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3349 GetLastError());
3350 exit (1);
3353 #endif
3355 static int cpu_can_run(CPUState *env)
3357 if (env->stop)
3358 return 0;
3359 if (env->stopped)
3360 return 0;
3361 return 1;
3364 #ifndef CONFIG_IOTHREAD
3365 static int qemu_init_main_loop(void)
3367 return qemu_event_init();
3370 void qemu_init_vcpu(void *_env)
3372 CPUState *env = _env;
3374 if (kvm_enabled())
3375 kvm_init_vcpu(env);
3376 env->nr_cores = smp_cores;
3377 env->nr_threads = smp_threads;
3378 return;
3381 int qemu_cpu_self(void *env)
3383 return 1;
3386 static void resume_all_vcpus(void)
3390 static void pause_all_vcpus(void)
3394 void qemu_cpu_kick(void *env)
3396 return;
3399 void qemu_notify_event(void)
3401 CPUState *env = cpu_single_env;
3403 if (env) {
3404 cpu_exit(env);
3408 void qemu_mutex_lock_iothread(void) {}
3409 void qemu_mutex_unlock_iothread(void) {}
3411 void vm_stop(int reason)
3413 do_vm_stop(reason);
3416 #else /* CONFIG_IOTHREAD */
3418 #include "qemu-thread.h"
3420 QemuMutex qemu_global_mutex;
3421 static QemuMutex qemu_fair_mutex;
3423 static QemuThread io_thread;
3425 static QemuThread *tcg_cpu_thread;
3426 static QemuCond *tcg_halt_cond;
3428 static int qemu_system_ready;
3429 /* cpu creation */
3430 static QemuCond qemu_cpu_cond;
3431 /* system init */
3432 static QemuCond qemu_system_cond;
3433 static QemuCond qemu_pause_cond;
3435 static void block_io_signals(void);
3436 static void unblock_io_signals(void);
3437 static int tcg_has_work(void);
3439 static int qemu_init_main_loop(void)
3441 int ret;
3443 ret = qemu_event_init();
3444 if (ret)
3445 return ret;
3447 qemu_cond_init(&qemu_pause_cond);
3448 qemu_mutex_init(&qemu_fair_mutex);
3449 qemu_mutex_init(&qemu_global_mutex);
3450 qemu_mutex_lock(&qemu_global_mutex);
3452 unblock_io_signals();
3453 qemu_thread_self(&io_thread);
3455 return 0;
3458 static void qemu_wait_io_event(CPUState *env)
3460 while (!tcg_has_work())
3461 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3463 qemu_mutex_unlock(&qemu_global_mutex);
3466 * Users of qemu_global_mutex can be starved, having no chance
3467 * to acquire it since this path will get to it first.
3468 * So use another lock to provide fairness.
3470 qemu_mutex_lock(&qemu_fair_mutex);
3471 qemu_mutex_unlock(&qemu_fair_mutex);
3473 qemu_mutex_lock(&qemu_global_mutex);
3474 if (env->stop) {
3475 env->stop = 0;
3476 env->stopped = 1;
3477 qemu_cond_signal(&qemu_pause_cond);
3481 static int qemu_cpu_exec(CPUState *env);
3483 static void *kvm_cpu_thread_fn(void *arg)
3485 CPUState *env = arg;
3487 block_io_signals();
3488 qemu_thread_self(env->thread);
3489 if (kvm_enabled())
3490 kvm_init_vcpu(env);
3492 /* signal CPU creation */
3493 qemu_mutex_lock(&qemu_global_mutex);
3494 env->created = 1;
3495 qemu_cond_signal(&qemu_cpu_cond);
3497 /* and wait for machine initialization */
3498 while (!qemu_system_ready)
3499 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3501 while (1) {
3502 if (cpu_can_run(env))
3503 qemu_cpu_exec(env);
3504 qemu_wait_io_event(env);
3507 return NULL;
3510 static void tcg_cpu_exec(void);
3512 static void *tcg_cpu_thread_fn(void *arg)
3514 CPUState *env = arg;
3516 block_io_signals();
3517 qemu_thread_self(env->thread);
3519 /* signal CPU creation */
3520 qemu_mutex_lock(&qemu_global_mutex);
3521 for (env = first_cpu; env != NULL; env = env->next_cpu)
3522 env->created = 1;
3523 qemu_cond_signal(&qemu_cpu_cond);
3525 /* and wait for machine initialization */
3526 while (!qemu_system_ready)
3527 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3529 while (1) {
3530 tcg_cpu_exec();
3531 qemu_wait_io_event(cur_cpu);
3534 return NULL;
3537 void qemu_cpu_kick(void *_env)
3539 CPUState *env = _env;
3540 qemu_cond_broadcast(env->halt_cond);
3541 if (kvm_enabled())
3542 qemu_thread_signal(env->thread, SIGUSR1);
3545 int qemu_cpu_self(void *_env)
3547 CPUState *env = _env;
3548 QemuThread this;
3550 qemu_thread_self(&this);
3552 return qemu_thread_equal(&this, env->thread);
3555 static void cpu_signal(int sig)
3557 if (cpu_single_env)
3558 cpu_exit(cpu_single_env);
3561 static void block_io_signals(void)
3563 sigset_t set;
3564 struct sigaction sigact;
3566 sigemptyset(&set);
3567 sigaddset(&set, SIGUSR2);
3568 sigaddset(&set, SIGIO);
3569 sigaddset(&set, SIGALRM);
3570 pthread_sigmask(SIG_BLOCK, &set, NULL);
3572 sigemptyset(&set);
3573 sigaddset(&set, SIGUSR1);
3574 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3576 memset(&sigact, 0, sizeof(sigact));
3577 sigact.sa_handler = cpu_signal;
3578 sigaction(SIGUSR1, &sigact, NULL);
3581 static void unblock_io_signals(void)
3583 sigset_t set;
3585 sigemptyset(&set);
3586 sigaddset(&set, SIGUSR2);
3587 sigaddset(&set, SIGIO);
3588 sigaddset(&set, SIGALRM);
3589 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3591 sigemptyset(&set);
3592 sigaddset(&set, SIGUSR1);
3593 pthread_sigmask(SIG_BLOCK, &set, NULL);
3596 static void qemu_signal_lock(unsigned int msecs)
3598 qemu_mutex_lock(&qemu_fair_mutex);
3600 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3601 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3602 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3603 break;
3605 qemu_mutex_unlock(&qemu_fair_mutex);
3608 void qemu_mutex_lock_iothread(void)
3610 if (kvm_enabled()) {
3611 qemu_mutex_lock(&qemu_fair_mutex);
3612 qemu_mutex_lock(&qemu_global_mutex);
3613 qemu_mutex_unlock(&qemu_fair_mutex);
3614 } else
3615 qemu_signal_lock(100);
3618 void qemu_mutex_unlock_iothread(void)
3620 qemu_mutex_unlock(&qemu_global_mutex);
3623 static int all_vcpus_paused(void)
3625 CPUState *penv = first_cpu;
3627 while (penv) {
3628 if (!penv->stopped)
3629 return 0;
3630 penv = (CPUState *)penv->next_cpu;
3633 return 1;
3636 static void pause_all_vcpus(void)
3638 CPUState *penv = first_cpu;
3640 while (penv) {
3641 penv->stop = 1;
3642 qemu_thread_signal(penv->thread, SIGUSR1);
3643 qemu_cpu_kick(penv);
3644 penv = (CPUState *)penv->next_cpu;
3647 while (!all_vcpus_paused()) {
3648 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3649 penv = first_cpu;
3650 while (penv) {
3651 qemu_thread_signal(penv->thread, SIGUSR1);
3652 penv = (CPUState *)penv->next_cpu;
3657 static void resume_all_vcpus(void)
3659 CPUState *penv = first_cpu;
3661 while (penv) {
3662 penv->stop = 0;
3663 penv->stopped = 0;
3664 qemu_thread_signal(penv->thread, SIGUSR1);
3665 qemu_cpu_kick(penv);
3666 penv = (CPUState *)penv->next_cpu;
3670 static void tcg_init_vcpu(void *_env)
3672 CPUState *env = _env;
3673 /* share a single thread for all cpus with TCG */
3674 if (!tcg_cpu_thread) {
3675 env->thread = qemu_mallocz(sizeof(QemuThread));
3676 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3677 qemu_cond_init(env->halt_cond);
3678 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3679 while (env->created == 0)
3680 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3681 tcg_cpu_thread = env->thread;
3682 tcg_halt_cond = env->halt_cond;
3683 } else {
3684 env->thread = tcg_cpu_thread;
3685 env->halt_cond = tcg_halt_cond;
3689 static void kvm_start_vcpu(CPUState *env)
3691 env->thread = qemu_mallocz(sizeof(QemuThread));
3692 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3693 qemu_cond_init(env->halt_cond);
3694 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3695 while (env->created == 0)
3696 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3699 void qemu_init_vcpu(void *_env)
3701 CPUState *env = _env;
3703 if (kvm_enabled())
3704 kvm_start_vcpu(env);
3705 else
3706 tcg_init_vcpu(env);
3707 env->nr_cores = smp_cores;
3708 env->nr_threads = smp_threads;
3711 void qemu_notify_event(void)
3713 qemu_event_increment();
3716 void vm_stop(int reason)
3718 QemuThread me;
3719 qemu_thread_self(&me);
3721 if (!qemu_thread_equal(&me, &io_thread)) {
3722 qemu_system_vmstop_request(reason);
3724 * FIXME: should not return to device code in case
3725 * vm_stop() has been requested.
3727 if (cpu_single_env) {
3728 cpu_exit(cpu_single_env);
3729 cpu_single_env->stop = 1;
3731 return;
3733 do_vm_stop(reason);
3736 #endif
3739 #ifdef _WIN32
3740 static void host_main_loop_wait(int *timeout)
3742 int ret, ret2, i;
3743 PollingEntry *pe;
3746 /* XXX: need to suppress polling by better using win32 events */
3747 ret = 0;
3748 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3749 ret |= pe->func(pe->opaque);
3751 if (ret == 0) {
3752 int err;
3753 WaitObjects *w = &wait_objects;
3755 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3756 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3757 if (w->func[ret - WAIT_OBJECT_0])
3758 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3760 /* Check for additional signaled events */
3761 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3763 /* Check if event is signaled */
3764 ret2 = WaitForSingleObject(w->events[i], 0);
3765 if(ret2 == WAIT_OBJECT_0) {
3766 if (w->func[i])
3767 w->func[i](w->opaque[i]);
3768 } else if (ret2 == WAIT_TIMEOUT) {
3769 } else {
3770 err = GetLastError();
3771 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3774 } else if (ret == WAIT_TIMEOUT) {
3775 } else {
3776 err = GetLastError();
3777 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3781 *timeout = 0;
3783 #else
3784 static void host_main_loop_wait(int *timeout)
3787 #endif
3789 void main_loop_wait(int timeout)
3791 IOHandlerRecord *ioh;
3792 fd_set rfds, wfds, xfds;
3793 int ret, nfds;
3794 struct timeval tv;
3796 qemu_bh_update_timeout(&timeout);
3798 host_main_loop_wait(&timeout);
3800 /* poll any events */
3801 /* XXX: separate device handlers from system ones */
3802 nfds = -1;
3803 FD_ZERO(&rfds);
3804 FD_ZERO(&wfds);
3805 FD_ZERO(&xfds);
3806 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3807 if (ioh->deleted)
3808 continue;
3809 if (ioh->fd_read &&
3810 (!ioh->fd_read_poll ||
3811 ioh->fd_read_poll(ioh->opaque) != 0)) {
3812 FD_SET(ioh->fd, &rfds);
3813 if (ioh->fd > nfds)
3814 nfds = ioh->fd;
3816 if (ioh->fd_write) {
3817 FD_SET(ioh->fd, &wfds);
3818 if (ioh->fd > nfds)
3819 nfds = ioh->fd;
3823 tv.tv_sec = timeout / 1000;
3824 tv.tv_usec = (timeout % 1000) * 1000;
3826 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3828 qemu_mutex_unlock_iothread();
3829 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3830 qemu_mutex_lock_iothread();
3831 if (ret > 0) {
3832 IOHandlerRecord **pioh;
3834 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3835 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3836 ioh->fd_read(ioh->opaque);
3838 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3839 ioh->fd_write(ioh->opaque);
3843 /* remove deleted IO handlers */
3844 pioh = &first_io_handler;
3845 while (*pioh) {
3846 ioh = *pioh;
3847 if (ioh->deleted) {
3848 *pioh = ioh->next;
3849 qemu_free(ioh);
3850 } else
3851 pioh = &ioh->next;
3855 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3857 /* rearm timer, if not periodic */
3858 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3859 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3860 qemu_rearm_alarm_timer(alarm_timer);
3863 /* vm time timers */
3864 if (vm_running) {
3865 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3866 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3867 qemu_get_clock(vm_clock));
3870 /* real time timers */
3871 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3872 qemu_get_clock(rt_clock));
3874 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3875 qemu_get_clock(host_clock));
3877 /* Check bottom-halves last in case any of the earlier events triggered
3878 them. */
3879 qemu_bh_poll();
3883 static int qemu_cpu_exec(CPUState *env)
3885 int ret;
3886 #ifdef CONFIG_PROFILER
3887 int64_t ti;
3888 #endif
3890 #ifdef CONFIG_PROFILER
3891 ti = profile_getclock();
3892 #endif
3893 if (use_icount) {
3894 int64_t count;
3895 int decr;
3896 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3897 env->icount_decr.u16.low = 0;
3898 env->icount_extra = 0;
3899 count = qemu_next_deadline();
3900 count = (count + (1 << icount_time_shift) - 1)
3901 >> icount_time_shift;
3902 qemu_icount += count;
3903 decr = (count > 0xffff) ? 0xffff : count;
3904 count -= decr;
3905 env->icount_decr.u16.low = decr;
3906 env->icount_extra = count;
3908 ret = cpu_exec(env);
3909 #ifdef CONFIG_PROFILER
3910 qemu_time += profile_getclock() - ti;
3911 #endif
3912 if (use_icount) {
3913 /* Fold pending instructions back into the
3914 instruction counter, and clear the interrupt flag. */
3915 qemu_icount -= (env->icount_decr.u16.low
3916 + env->icount_extra);
3917 env->icount_decr.u32 = 0;
3918 env->icount_extra = 0;
3920 return ret;
3923 static void tcg_cpu_exec(void)
3925 int ret = 0;
3927 if (next_cpu == NULL)
3928 next_cpu = first_cpu;
3929 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3930 CPUState *env = cur_cpu = next_cpu;
3932 if (!vm_running)
3933 break;
3934 if (timer_alarm_pending) {
3935 timer_alarm_pending = 0;
3936 break;
3938 if (cpu_can_run(env))
3939 ret = qemu_cpu_exec(env);
3940 if (ret == EXCP_DEBUG) {
3941 gdb_set_stop_cpu(env);
3942 debug_requested = 1;
3943 break;
3948 static int cpu_has_work(CPUState *env)
3950 if (env->stop)
3951 return 1;
3952 if (env->stopped)
3953 return 0;
3954 if (!env->halted)
3955 return 1;
3956 if (qemu_cpu_has_work(env))
3957 return 1;
3958 return 0;
3961 static int tcg_has_work(void)
3963 CPUState *env;
3965 for (env = first_cpu; env != NULL; env = env->next_cpu)
3966 if (cpu_has_work(env))
3967 return 1;
3968 return 0;
3971 static int qemu_calculate_timeout(void)
3973 #ifndef CONFIG_IOTHREAD
3974 int timeout;
3976 if (!vm_running)
3977 timeout = 5000;
3978 else if (tcg_has_work())
3979 timeout = 0;
3980 else if (!use_icount)
3981 timeout = 5000;
3982 else {
3983 /* XXX: use timeout computed from timers */
3984 int64_t add;
3985 int64_t delta;
3986 /* Advance virtual time to the next event. */
3987 if (use_icount == 1) {
3988 /* When not using an adaptive execution frequency
3989 we tend to get badly out of sync with real time,
3990 so just delay for a reasonable amount of time. */
3991 delta = 0;
3992 } else {
3993 delta = cpu_get_icount() - cpu_get_clock();
3995 if (delta > 0) {
3996 /* If virtual time is ahead of real time then just
3997 wait for IO. */
3998 timeout = (delta / 1000000) + 1;
3999 } else {
4000 /* Wait for either IO to occur or the next
4001 timer event. */
4002 add = qemu_next_deadline();
4003 /* We advance the timer before checking for IO.
4004 Limit the amount we advance so that early IO
4005 activity won't get the guest too far ahead. */
4006 if (add > 10000000)
4007 add = 10000000;
4008 delta += add;
4009 add = (add + (1 << icount_time_shift) - 1)
4010 >> icount_time_shift;
4011 qemu_icount += add;
4012 timeout = delta / 1000000;
4013 if (timeout < 0)
4014 timeout = 0;
4018 return timeout;
4019 #else /* CONFIG_IOTHREAD */
4020 return 1000;
4021 #endif
4024 static int vm_can_run(void)
4026 if (powerdown_requested)
4027 return 0;
4028 if (reset_requested)
4029 return 0;
4030 if (shutdown_requested)
4031 return 0;
4032 if (debug_requested)
4033 return 0;
4034 return 1;
4037 qemu_irq qemu_system_powerdown;
4039 static void main_loop(void)
4041 int r;
4043 #ifdef CONFIG_IOTHREAD
4044 qemu_system_ready = 1;
4045 qemu_cond_broadcast(&qemu_system_cond);
4046 #endif
4048 for (;;) {
4049 do {
4050 #ifdef CONFIG_PROFILER
4051 int64_t ti;
4052 #endif
4053 #ifndef CONFIG_IOTHREAD
4054 tcg_cpu_exec();
4055 #endif
4056 #ifdef CONFIG_PROFILER
4057 ti = profile_getclock();
4058 #endif
4059 main_loop_wait(qemu_calculate_timeout());
4060 #ifdef CONFIG_PROFILER
4061 dev_time += profile_getclock() - ti;
4062 #endif
4063 } while (vm_can_run());
4065 if (qemu_debug_requested())
4066 vm_stop(EXCP_DEBUG);
4067 if (qemu_shutdown_requested()) {
4068 if (no_shutdown) {
4069 vm_stop(0);
4070 no_shutdown = 0;
4071 } else
4072 break;
4074 if (qemu_reset_requested()) {
4075 pause_all_vcpus();
4076 qemu_system_reset();
4077 resume_all_vcpus();
4079 if (qemu_powerdown_requested()) {
4080 qemu_irq_raise(qemu_system_powerdown);
4082 if ((r = qemu_vmstop_requested()))
4083 vm_stop(r);
4085 pause_all_vcpus();
4088 static void version(void)
4090 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4093 static void help(int exitcode)
4095 version();
4096 printf("usage: %s [options] [disk_image]\n"
4097 "\n"
4098 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4099 "\n"
4100 #define DEF(option, opt_arg, opt_enum, opt_help) \
4101 opt_help
4102 #define DEFHEADING(text) stringify(text) "\n"
4103 #include "qemu-options.h"
4104 #undef DEF
4105 #undef DEFHEADING
4106 #undef GEN_DOCS
4107 "\n"
4108 "During emulation, the following keys are useful:\n"
4109 "ctrl-alt-f toggle full screen\n"
4110 "ctrl-alt-n switch to virtual console 'n'\n"
4111 "ctrl-alt toggle mouse and keyboard grab\n"
4112 "\n"
4113 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4115 "qemu",
4116 DEFAULT_RAM_SIZE,
4117 #ifndef _WIN32
4118 DEFAULT_NETWORK_SCRIPT,
4119 DEFAULT_NETWORK_DOWN_SCRIPT,
4120 #endif
4121 DEFAULT_GDBSTUB_PORT,
4122 "/tmp/qemu.log");
4123 exit(exitcode);
4126 #define HAS_ARG 0x0001
4128 enum {
4129 #define DEF(option, opt_arg, opt_enum, opt_help) \
4130 opt_enum,
4131 #define DEFHEADING(text)
4132 #include "qemu-options.h"
4133 #undef DEF
4134 #undef DEFHEADING
4135 #undef GEN_DOCS
4138 typedef struct QEMUOption {
4139 const char *name;
4140 int flags;
4141 int index;
4142 } QEMUOption;
4144 static const QEMUOption qemu_options[] = {
4145 { "h", 0, QEMU_OPTION_h },
4146 #define DEF(option, opt_arg, opt_enum, opt_help) \
4147 { option, opt_arg, opt_enum },
4148 #define DEFHEADING(text)
4149 #include "qemu-options.h"
4150 #undef DEF
4151 #undef DEFHEADING
4152 #undef GEN_DOCS
4153 { NULL },
4156 #ifdef HAS_AUDIO
4157 struct soundhw soundhw[] = {
4158 #ifdef HAS_AUDIO_CHOICE
4159 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4161 "pcspk",
4162 "PC speaker",
4165 { .init_isa = pcspk_audio_init }
4167 #endif
4169 #ifdef CONFIG_SB16
4171 "sb16",
4172 "Creative Sound Blaster 16",
4175 { .init_isa = SB16_init }
4177 #endif
4179 #ifdef CONFIG_CS4231A
4181 "cs4231a",
4182 "CS4231A",
4185 { .init_isa = cs4231a_init }
4187 #endif
4189 #ifdef CONFIG_ADLIB
4191 "adlib",
4192 #ifdef HAS_YMF262
4193 "Yamaha YMF262 (OPL3)",
4194 #else
4195 "Yamaha YM3812 (OPL2)",
4196 #endif
4199 { .init_isa = Adlib_init }
4201 #endif
4203 #ifdef CONFIG_GUS
4205 "gus",
4206 "Gravis Ultrasound GF1",
4209 { .init_isa = GUS_init }
4211 #endif
4213 #ifdef CONFIG_AC97
4215 "ac97",
4216 "Intel 82801AA AC97 Audio",
4219 { .init_pci = ac97_init }
4221 #endif
4223 #ifdef CONFIG_ES1370
4225 "es1370",
4226 "ENSONIQ AudioPCI ES1370",
4229 { .init_pci = es1370_init }
4231 #endif
4233 #endif /* HAS_AUDIO_CHOICE */
4235 { NULL, NULL, 0, 0, { NULL } }
4238 static void select_soundhw (const char *optarg)
4240 struct soundhw *c;
4242 if (*optarg == '?') {
4243 show_valid_cards:
4245 printf ("Valid sound card names (comma separated):\n");
4246 for (c = soundhw; c->name; ++c) {
4247 printf ("%-11s %s\n", c->name, c->descr);
4249 printf ("\n-soundhw all will enable all of the above\n");
4250 exit (*optarg != '?');
4252 else {
4253 size_t l;
4254 const char *p;
4255 char *e;
4256 int bad_card = 0;
4258 if (!strcmp (optarg, "all")) {
4259 for (c = soundhw; c->name; ++c) {
4260 c->enabled = 1;
4262 return;
4265 p = optarg;
4266 while (*p) {
4267 e = strchr (p, ',');
4268 l = !e ? strlen (p) : (size_t) (e - p);
4270 for (c = soundhw; c->name; ++c) {
4271 if (!strncmp (c->name, p, l) && !c->name[l]) {
4272 c->enabled = 1;
4273 break;
4277 if (!c->name) {
4278 if (l > 80) {
4279 fprintf (stderr,
4280 "Unknown sound card name (too big to show)\n");
4282 else {
4283 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4284 (int) l, p);
4286 bad_card = 1;
4288 p += l + (e != NULL);
4291 if (bad_card)
4292 goto show_valid_cards;
4295 #endif
4297 static void select_vgahw (const char *p)
4299 const char *opts;
4301 vga_interface_type = VGA_NONE;
4302 if (strstart(p, "std", &opts)) {
4303 vga_interface_type = VGA_STD;
4304 } else if (strstart(p, "cirrus", &opts)) {
4305 vga_interface_type = VGA_CIRRUS;
4306 } else if (strstart(p, "vmware", &opts)) {
4307 vga_interface_type = VGA_VMWARE;
4308 } else if (strstart(p, "xenfb", &opts)) {
4309 vga_interface_type = VGA_XENFB;
4310 } else if (!strstart(p, "none", &opts)) {
4311 invalid_vga:
4312 fprintf(stderr, "Unknown vga type: %s\n", p);
4313 exit(1);
4315 while (*opts) {
4316 const char *nextopt;
4318 if (strstart(opts, ",retrace=", &nextopt)) {
4319 opts = nextopt;
4320 if (strstart(opts, "dumb", &nextopt))
4321 vga_retrace_method = VGA_RETRACE_DUMB;
4322 else if (strstart(opts, "precise", &nextopt))
4323 vga_retrace_method = VGA_RETRACE_PRECISE;
4324 else goto invalid_vga;
4325 } else goto invalid_vga;
4326 opts = nextopt;
4330 #ifdef TARGET_I386
4331 static int balloon_parse(const char *arg)
4333 QemuOpts *opts;
4335 if (strcmp(arg, "none") == 0) {
4336 return 0;
4339 if (!strncmp(arg, "virtio", 6)) {
4340 if (arg[6] == ',') {
4341 /* have params -> parse them */
4342 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4343 if (!opts)
4344 return -1;
4345 } else {
4346 /* create empty opts */
4347 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4349 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4350 return 0;
4353 return -1;
4355 #endif
4357 #ifdef _WIN32
4358 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4360 exit(STATUS_CONTROL_C_EXIT);
4361 return TRUE;
4363 #endif
4365 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4367 int ret;
4369 if(strlen(str) != 36)
4370 return -1;
4372 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4373 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4374 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4376 if(ret != 16)
4377 return -1;
4379 #ifdef TARGET_I386
4380 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4381 #endif
4383 return 0;
4386 #ifndef _WIN32
4388 static void termsig_handler(int signal)
4390 qemu_system_shutdown_request();
4393 static void sigchld_handler(int signal)
4395 waitpid(-1, NULL, WNOHANG);
4398 static void sighandler_setup(void)
4400 struct sigaction act;
4402 memset(&act, 0, sizeof(act));
4403 act.sa_handler = termsig_handler;
4404 sigaction(SIGINT, &act, NULL);
4405 sigaction(SIGHUP, &act, NULL);
4406 sigaction(SIGTERM, &act, NULL);
4408 act.sa_handler = sigchld_handler;
4409 act.sa_flags = SA_NOCLDSTOP;
4410 sigaction(SIGCHLD, &act, NULL);
4413 #endif
4415 #ifdef _WIN32
4416 /* Look for support files in the same directory as the executable. */
4417 static char *find_datadir(const char *argv0)
4419 char *p;
4420 char buf[MAX_PATH];
4421 DWORD len;
4423 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4424 if (len == 0) {
4425 return NULL;
4428 buf[len] = 0;
4429 p = buf + len - 1;
4430 while (p != buf && *p != '\\')
4431 p--;
4432 *p = 0;
4433 if (access(buf, R_OK) == 0) {
4434 return qemu_strdup(buf);
4436 return NULL;
4438 #else /* !_WIN32 */
4440 /* Find a likely location for support files using the location of the binary.
4441 For installed binaries this will be "$bindir/../share/qemu". When
4442 running from the build tree this will be "$bindir/../pc-bios". */
4443 #define SHARE_SUFFIX "/share/qemu"
4444 #define BUILD_SUFFIX "/pc-bios"
4445 static char *find_datadir(const char *argv0)
4447 char *dir;
4448 char *p = NULL;
4449 char *res;
4450 char buf[PATH_MAX];
4451 size_t max_len;
4453 #if defined(__linux__)
4455 int len;
4456 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4457 if (len > 0) {
4458 buf[len] = 0;
4459 p = buf;
4462 #elif defined(__FreeBSD__)
4464 int len;
4465 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4466 if (len > 0) {
4467 buf[len] = 0;
4468 p = buf;
4471 #endif
4472 /* If we don't have any way of figuring out the actual executable
4473 location then try argv[0]. */
4474 if (!p) {
4475 p = realpath(argv0, buf);
4476 if (!p) {
4477 return NULL;
4480 dir = dirname(p);
4481 dir = dirname(dir);
4483 max_len = strlen(dir) +
4484 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4485 res = qemu_mallocz(max_len);
4486 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4487 if (access(res, R_OK)) {
4488 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4489 if (access(res, R_OK)) {
4490 qemu_free(res);
4491 res = NULL;
4495 return res;
4497 #undef SHARE_SUFFIX
4498 #undef BUILD_SUFFIX
4499 #endif
4501 char *qemu_find_file(int type, const char *name)
4503 int len;
4504 const char *subdir;
4505 char *buf;
4507 /* If name contains path separators then try it as a straight path. */
4508 if ((strchr(name, '/') || strchr(name, '\\'))
4509 && access(name, R_OK) == 0) {
4510 return qemu_strdup(name);
4512 switch (type) {
4513 case QEMU_FILE_TYPE_BIOS:
4514 subdir = "";
4515 break;
4516 case QEMU_FILE_TYPE_KEYMAP:
4517 subdir = "keymaps/";
4518 break;
4519 default:
4520 abort();
4522 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4523 buf = qemu_mallocz(len);
4524 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4525 if (access(buf, R_OK)) {
4526 qemu_free(buf);
4527 return NULL;
4529 return buf;
4532 static int device_init_func(QemuOpts *opts, void *opaque)
4534 DeviceState *dev;
4536 dev = qdev_device_add(opts);
4537 if (!dev)
4538 return -1;
4539 return 0;
4542 struct device_config {
4543 enum {
4544 DEV_USB, /* -usbdevice */
4545 DEV_BT, /* -bt */
4546 } type;
4547 const char *cmdline;
4548 QTAILQ_ENTRY(device_config) next;
4550 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4552 static void add_device_config(int type, const char *cmdline)
4554 struct device_config *conf;
4556 conf = qemu_mallocz(sizeof(*conf));
4557 conf->type = type;
4558 conf->cmdline = cmdline;
4559 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4562 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4564 struct device_config *conf;
4565 int rc;
4567 QTAILQ_FOREACH(conf, &device_configs, next) {
4568 if (conf->type != type)
4569 continue;
4570 rc = func(conf->cmdline);
4571 if (0 != rc)
4572 return rc;
4574 return 0;
4577 int main(int argc, char **argv, char **envp)
4579 const char *gdbstub_dev = NULL;
4580 uint32_t boot_devices_bitmap = 0;
4581 int i;
4582 int snapshot, linux_boot, net_boot;
4583 const char *initrd_filename;
4584 const char *kernel_filename, *kernel_cmdline;
4585 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4586 DisplayState *ds;
4587 DisplayChangeListener *dcl;
4588 int cyls, heads, secs, translation;
4589 QemuOpts *hda_opts = NULL, *opts;
4590 int optind;
4591 const char *r, *optarg;
4592 CharDriverState *monitor_hds[MAX_MONITOR_DEVICES];
4593 const char *monitor_devices[MAX_MONITOR_DEVICES];
4594 int monitor_device_index;
4595 const char *serial_devices[MAX_SERIAL_PORTS];
4596 int serial_device_index;
4597 const char *parallel_devices[MAX_PARALLEL_PORTS];
4598 int parallel_device_index;
4599 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4600 int virtio_console_index;
4601 const char *loadvm = NULL;
4602 QEMUMachine *machine;
4603 const char *cpu_model;
4604 #ifndef _WIN32
4605 int fds[2];
4606 #endif
4607 int tb_size;
4608 const char *pid_file = NULL;
4609 const char *incoming = NULL;
4610 #ifndef _WIN32
4611 int fd = 0;
4612 struct passwd *pwd = NULL;
4613 const char *chroot_dir = NULL;
4614 const char *run_as = NULL;
4615 #endif
4616 CPUState *env;
4617 int show_vnc_port = 0;
4619 init_clocks();
4621 qemu_errors_to_file(stderr);
4622 qemu_cache_utils_init(envp);
4624 QLIST_INIT (&vm_change_state_head);
4625 #ifndef _WIN32
4627 struct sigaction act;
4628 sigfillset(&act.sa_mask);
4629 act.sa_flags = 0;
4630 act.sa_handler = SIG_IGN;
4631 sigaction(SIGPIPE, &act, NULL);
4633 #else
4634 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4635 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4636 QEMU to run on a single CPU */
4638 HANDLE h;
4639 DWORD mask, smask;
4640 int i;
4641 h = GetCurrentProcess();
4642 if (GetProcessAffinityMask(h, &mask, &smask)) {
4643 for(i = 0; i < 32; i++) {
4644 if (mask & (1 << i))
4645 break;
4647 if (i != 32) {
4648 mask = 1 << i;
4649 SetProcessAffinityMask(h, mask);
4653 #endif
4655 module_call_init(MODULE_INIT_MACHINE);
4656 machine = find_default_machine();
4657 cpu_model = NULL;
4658 initrd_filename = NULL;
4659 ram_size = 0;
4660 snapshot = 0;
4661 kernel_filename = NULL;
4662 kernel_cmdline = "";
4663 cyls = heads = secs = 0;
4664 translation = BIOS_ATA_TRANSLATION_AUTO;
4666 serial_devices[0] = "vc:80Cx24C";
4667 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4668 serial_devices[i] = NULL;
4669 serial_device_index = 0;
4671 parallel_devices[0] = "vc:80Cx24C";
4672 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4673 parallel_devices[i] = NULL;
4674 parallel_device_index = 0;
4676 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4677 virtio_consoles[i] = NULL;
4678 virtio_console_index = 0;
4680 monitor_devices[0] = "vc:80Cx24C";
4681 for (i = 1; i < MAX_MONITOR_DEVICES; i++) {
4682 monitor_devices[i] = NULL;
4684 monitor_device_index = 0;
4686 for (i = 0; i < MAX_NODES; i++) {
4687 node_mem[i] = 0;
4688 node_cpumask[i] = 0;
4691 nb_numa_nodes = 0;
4692 nb_nics = 0;
4694 tb_size = 0;
4695 autostart= 1;
4697 optind = 1;
4698 for(;;) {
4699 if (optind >= argc)
4700 break;
4701 r = argv[optind];
4702 if (r[0] != '-') {
4703 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4704 } else {
4705 const QEMUOption *popt;
4707 optind++;
4708 /* Treat --foo the same as -foo. */
4709 if (r[1] == '-')
4710 r++;
4711 popt = qemu_options;
4712 for(;;) {
4713 if (!popt->name) {
4714 fprintf(stderr, "%s: invalid option -- '%s'\n",
4715 argv[0], r);
4716 exit(1);
4718 if (!strcmp(popt->name, r + 1))
4719 break;
4720 popt++;
4722 if (popt->flags & HAS_ARG) {
4723 if (optind >= argc) {
4724 fprintf(stderr, "%s: option '%s' requires an argument\n",
4725 argv[0], r);
4726 exit(1);
4728 optarg = argv[optind++];
4729 } else {
4730 optarg = NULL;
4733 switch(popt->index) {
4734 case QEMU_OPTION_M:
4735 machine = find_machine(optarg);
4736 if (!machine) {
4737 QEMUMachine *m;
4738 printf("Supported machines are:\n");
4739 for(m = first_machine; m != NULL; m = m->next) {
4740 if (m->alias)
4741 printf("%-10s %s (alias of %s)\n",
4742 m->alias, m->desc, m->name);
4743 printf("%-10s %s%s\n",
4744 m->name, m->desc,
4745 m->is_default ? " (default)" : "");
4747 exit(*optarg != '?');
4749 break;
4750 case QEMU_OPTION_cpu:
4751 /* hw initialization will check this */
4752 if (*optarg == '?') {
4753 /* XXX: implement xxx_cpu_list for targets that still miss it */
4754 #if defined(cpu_list)
4755 cpu_list(stdout, &fprintf);
4756 #endif
4757 exit(0);
4758 } else {
4759 cpu_model = optarg;
4761 break;
4762 case QEMU_OPTION_initrd:
4763 initrd_filename = optarg;
4764 break;
4765 case QEMU_OPTION_hda:
4766 if (cyls == 0)
4767 hda_opts = drive_add(optarg, HD_ALIAS, 0);
4768 else
4769 hda_opts = drive_add(optarg, HD_ALIAS
4770 ",cyls=%d,heads=%d,secs=%d%s",
4771 0, cyls, heads, secs,
4772 translation == BIOS_ATA_TRANSLATION_LBA ?
4773 ",trans=lba" :
4774 translation == BIOS_ATA_TRANSLATION_NONE ?
4775 ",trans=none" : "");
4776 break;
4777 case QEMU_OPTION_hdb:
4778 case QEMU_OPTION_hdc:
4779 case QEMU_OPTION_hdd:
4780 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4781 break;
4782 case QEMU_OPTION_drive:
4783 drive_add(NULL, "%s", optarg);
4784 break;
4785 case QEMU_OPTION_set:
4786 if (qemu_set_option(optarg) != 0)
4787 exit(1);
4788 break;
4789 case QEMU_OPTION_mtdblock:
4790 drive_add(optarg, MTD_ALIAS);
4791 break;
4792 case QEMU_OPTION_sd:
4793 drive_add(optarg, SD_ALIAS);
4794 break;
4795 case QEMU_OPTION_pflash:
4796 drive_add(optarg, PFLASH_ALIAS);
4797 break;
4798 case QEMU_OPTION_snapshot:
4799 snapshot = 1;
4800 break;
4801 case QEMU_OPTION_hdachs:
4803 const char *p;
4804 p = optarg;
4805 cyls = strtol(p, (char **)&p, 0);
4806 if (cyls < 1 || cyls > 16383)
4807 goto chs_fail;
4808 if (*p != ',')
4809 goto chs_fail;
4810 p++;
4811 heads = strtol(p, (char **)&p, 0);
4812 if (heads < 1 || heads > 16)
4813 goto chs_fail;
4814 if (*p != ',')
4815 goto chs_fail;
4816 p++;
4817 secs = strtol(p, (char **)&p, 0);
4818 if (secs < 1 || secs > 63)
4819 goto chs_fail;
4820 if (*p == ',') {
4821 p++;
4822 if (!strcmp(p, "none"))
4823 translation = BIOS_ATA_TRANSLATION_NONE;
4824 else if (!strcmp(p, "lba"))
4825 translation = BIOS_ATA_TRANSLATION_LBA;
4826 else if (!strcmp(p, "auto"))
4827 translation = BIOS_ATA_TRANSLATION_AUTO;
4828 else
4829 goto chs_fail;
4830 } else if (*p != '\0') {
4831 chs_fail:
4832 fprintf(stderr, "qemu: invalid physical CHS format\n");
4833 exit(1);
4835 if (hda_opts != NULL) {
4836 char num[16];
4837 snprintf(num, sizeof(num), "%d", cyls);
4838 qemu_opt_set(hda_opts, "cyls", num);
4839 snprintf(num, sizeof(num), "%d", heads);
4840 qemu_opt_set(hda_opts, "heads", num);
4841 snprintf(num, sizeof(num), "%d", secs);
4842 qemu_opt_set(hda_opts, "secs", num);
4843 if (translation == BIOS_ATA_TRANSLATION_LBA)
4844 qemu_opt_set(hda_opts, "trans", "lba");
4845 if (translation == BIOS_ATA_TRANSLATION_NONE)
4846 qemu_opt_set(hda_opts, "trans", "none");
4849 break;
4850 case QEMU_OPTION_numa:
4851 if (nb_numa_nodes >= MAX_NODES) {
4852 fprintf(stderr, "qemu: too many NUMA nodes\n");
4853 exit(1);
4855 numa_add(optarg);
4856 break;
4857 case QEMU_OPTION_nographic:
4858 display_type = DT_NOGRAPHIC;
4859 break;
4860 #ifdef CONFIG_CURSES
4861 case QEMU_OPTION_curses:
4862 display_type = DT_CURSES;
4863 break;
4864 #endif
4865 case QEMU_OPTION_portrait:
4866 graphic_rotate = 1;
4867 break;
4868 case QEMU_OPTION_kernel:
4869 kernel_filename = optarg;
4870 break;
4871 case QEMU_OPTION_append:
4872 kernel_cmdline = optarg;
4873 break;
4874 case QEMU_OPTION_cdrom:
4875 drive_add(optarg, CDROM_ALIAS);
4876 break;
4877 case QEMU_OPTION_boot:
4879 static const char * const params[] = {
4880 "order", "once", "menu", NULL
4882 char buf[sizeof(boot_devices)];
4883 char *standard_boot_devices;
4884 int legacy = 0;
4886 if (!strchr(optarg, '=')) {
4887 legacy = 1;
4888 pstrcpy(buf, sizeof(buf), optarg);
4889 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4890 fprintf(stderr,
4891 "qemu: unknown boot parameter '%s' in '%s'\n",
4892 buf, optarg);
4893 exit(1);
4896 if (legacy ||
4897 get_param_value(buf, sizeof(buf), "order", optarg)) {
4898 boot_devices_bitmap = parse_bootdevices(buf);
4899 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4901 if (!legacy) {
4902 if (get_param_value(buf, sizeof(buf),
4903 "once", optarg)) {
4904 boot_devices_bitmap |= parse_bootdevices(buf);
4905 standard_boot_devices = qemu_strdup(boot_devices);
4906 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4907 qemu_register_reset(restore_boot_devices,
4908 standard_boot_devices);
4910 if (get_param_value(buf, sizeof(buf),
4911 "menu", optarg)) {
4912 if (!strcmp(buf, "on")) {
4913 boot_menu = 1;
4914 } else if (!strcmp(buf, "off")) {
4915 boot_menu = 0;
4916 } else {
4917 fprintf(stderr,
4918 "qemu: invalid option value '%s'\n",
4919 buf);
4920 exit(1);
4925 break;
4926 case QEMU_OPTION_fda:
4927 case QEMU_OPTION_fdb:
4928 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4929 break;
4930 #ifdef TARGET_I386
4931 case QEMU_OPTION_no_fd_bootchk:
4932 fd_bootchk = 0;
4933 break;
4934 #endif
4935 case QEMU_OPTION_netdev:
4936 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
4937 exit(1);
4939 break;
4940 case QEMU_OPTION_net:
4941 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
4942 exit(1);
4944 break;
4945 #ifdef CONFIG_SLIRP
4946 case QEMU_OPTION_tftp:
4947 legacy_tftp_prefix = optarg;
4948 break;
4949 case QEMU_OPTION_bootp:
4950 legacy_bootp_filename = optarg;
4951 break;
4952 #ifndef _WIN32
4953 case QEMU_OPTION_smb:
4954 if (net_slirp_smb(optarg) < 0)
4955 exit(1);
4956 break;
4957 #endif
4958 case QEMU_OPTION_redir:
4959 if (net_slirp_redir(optarg) < 0)
4960 exit(1);
4961 break;
4962 #endif
4963 case QEMU_OPTION_bt:
4964 add_device_config(DEV_BT, optarg);
4965 break;
4966 #ifdef HAS_AUDIO
4967 case QEMU_OPTION_audio_help:
4968 AUD_help ();
4969 exit (0);
4970 break;
4971 case QEMU_OPTION_soundhw:
4972 select_soundhw (optarg);
4973 break;
4974 #endif
4975 case QEMU_OPTION_h:
4976 help(0);
4977 break;
4978 case QEMU_OPTION_version:
4979 version();
4980 exit(0);
4981 break;
4982 case QEMU_OPTION_m: {
4983 uint64_t value;
4984 char *ptr;
4986 value = strtoul(optarg, &ptr, 10);
4987 switch (*ptr) {
4988 case 0: case 'M': case 'm':
4989 value <<= 20;
4990 break;
4991 case 'G': case 'g':
4992 value <<= 30;
4993 break;
4994 default:
4995 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4996 exit(1);
4999 /* On 32-bit hosts, QEMU is limited by virtual address space */
5000 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5001 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5002 exit(1);
5004 if (value != (uint64_t)(ram_addr_t)value) {
5005 fprintf(stderr, "qemu: ram size too large\n");
5006 exit(1);
5008 ram_size = value;
5009 break;
5011 case QEMU_OPTION_d:
5013 int mask;
5014 const CPULogItem *item;
5016 mask = cpu_str_to_log_mask(optarg);
5017 if (!mask) {
5018 printf("Log items (comma separated):\n");
5019 for(item = cpu_log_items; item->mask != 0; item++) {
5020 printf("%-10s %s\n", item->name, item->help);
5022 exit(1);
5024 cpu_set_log(mask);
5026 break;
5027 case QEMU_OPTION_s:
5028 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5029 break;
5030 case QEMU_OPTION_gdb:
5031 gdbstub_dev = optarg;
5032 break;
5033 case QEMU_OPTION_L:
5034 data_dir = optarg;
5035 break;
5036 case QEMU_OPTION_bios:
5037 bios_name = optarg;
5038 break;
5039 case QEMU_OPTION_singlestep:
5040 singlestep = 1;
5041 break;
5042 case QEMU_OPTION_S:
5043 autostart = 0;
5044 break;
5045 #ifndef _WIN32
5046 case QEMU_OPTION_k:
5047 keyboard_layout = optarg;
5048 break;
5049 #endif
5050 case QEMU_OPTION_localtime:
5051 rtc_utc = 0;
5052 break;
5053 case QEMU_OPTION_vga:
5054 select_vgahw (optarg);
5055 break;
5056 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5057 case QEMU_OPTION_g:
5059 const char *p;
5060 int w, h, depth;
5061 p = optarg;
5062 w = strtol(p, (char **)&p, 10);
5063 if (w <= 0) {
5064 graphic_error:
5065 fprintf(stderr, "qemu: invalid resolution or depth\n");
5066 exit(1);
5068 if (*p != 'x')
5069 goto graphic_error;
5070 p++;
5071 h = strtol(p, (char **)&p, 10);
5072 if (h <= 0)
5073 goto graphic_error;
5074 if (*p == 'x') {
5075 p++;
5076 depth = strtol(p, (char **)&p, 10);
5077 if (depth != 8 && depth != 15 && depth != 16 &&
5078 depth != 24 && depth != 32)
5079 goto graphic_error;
5080 } else if (*p == '\0') {
5081 depth = graphic_depth;
5082 } else {
5083 goto graphic_error;
5086 graphic_width = w;
5087 graphic_height = h;
5088 graphic_depth = depth;
5090 break;
5091 #endif
5092 case QEMU_OPTION_echr:
5094 char *r;
5095 term_escape_char = strtol(optarg, &r, 0);
5096 if (r == optarg)
5097 printf("Bad argument to echr\n");
5098 break;
5100 case QEMU_OPTION_monitor:
5101 if (monitor_device_index >= MAX_MONITOR_DEVICES) {
5102 fprintf(stderr, "qemu: too many monitor devices\n");
5103 exit(1);
5105 monitor_devices[monitor_device_index] = optarg;
5106 monitor_device_index++;
5107 break;
5108 case QEMU_OPTION_chardev:
5109 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5110 if (!opts) {
5111 fprintf(stderr, "parse error: %s\n", optarg);
5112 exit(1);
5114 if (qemu_chr_open_opts(opts, NULL) == NULL) {
5115 exit(1);
5117 break;
5118 case QEMU_OPTION_serial:
5119 if (serial_device_index >= MAX_SERIAL_PORTS) {
5120 fprintf(stderr, "qemu: too many serial ports\n");
5121 exit(1);
5123 serial_devices[serial_device_index] = optarg;
5124 serial_device_index++;
5125 break;
5126 case QEMU_OPTION_watchdog:
5127 if (watchdog) {
5128 fprintf(stderr,
5129 "qemu: only one watchdog option may be given\n");
5130 return 1;
5132 watchdog = optarg;
5133 break;
5134 case QEMU_OPTION_watchdog_action:
5135 if (select_watchdog_action(optarg) == -1) {
5136 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5137 exit(1);
5139 break;
5140 case QEMU_OPTION_virtiocon:
5141 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5142 fprintf(stderr, "qemu: too many virtio consoles\n");
5143 exit(1);
5145 virtio_consoles[virtio_console_index] = optarg;
5146 virtio_console_index++;
5147 break;
5148 case QEMU_OPTION_parallel:
5149 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5150 fprintf(stderr, "qemu: too many parallel ports\n");
5151 exit(1);
5153 parallel_devices[parallel_device_index] = optarg;
5154 parallel_device_index++;
5155 break;
5156 case QEMU_OPTION_loadvm:
5157 loadvm = optarg;
5158 break;
5159 case QEMU_OPTION_full_screen:
5160 full_screen = 1;
5161 break;
5162 #ifdef CONFIG_SDL
5163 case QEMU_OPTION_no_frame:
5164 no_frame = 1;
5165 break;
5166 case QEMU_OPTION_alt_grab:
5167 alt_grab = 1;
5168 break;
5169 case QEMU_OPTION_ctrl_grab:
5170 ctrl_grab = 1;
5171 break;
5172 case QEMU_OPTION_no_quit:
5173 no_quit = 1;
5174 break;
5175 case QEMU_OPTION_sdl:
5176 display_type = DT_SDL;
5177 break;
5178 #endif
5179 case QEMU_OPTION_pidfile:
5180 pid_file = optarg;
5181 break;
5182 #ifdef TARGET_I386
5183 case QEMU_OPTION_win2k_hack:
5184 win2k_install_hack = 1;
5185 break;
5186 case QEMU_OPTION_rtc_td_hack:
5187 rtc_td_hack = 1;
5188 break;
5189 case QEMU_OPTION_acpitable:
5190 if(acpi_table_add(optarg) < 0) {
5191 fprintf(stderr, "Wrong acpi table provided\n");
5192 exit(1);
5194 break;
5195 case QEMU_OPTION_smbios:
5196 if(smbios_entry_add(optarg) < 0) {
5197 fprintf(stderr, "Wrong smbios provided\n");
5198 exit(1);
5200 break;
5201 #endif
5202 #ifdef CONFIG_KVM
5203 case QEMU_OPTION_enable_kvm:
5204 kvm_allowed = 1;
5205 break;
5206 #endif
5207 case QEMU_OPTION_usb:
5208 usb_enabled = 1;
5209 break;
5210 case QEMU_OPTION_usbdevice:
5211 usb_enabled = 1;
5212 add_device_config(DEV_USB, optarg);
5213 break;
5214 case QEMU_OPTION_device:
5215 if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5216 exit(1);
5218 break;
5219 case QEMU_OPTION_smp:
5220 smp_parse(optarg);
5221 if (smp_cpus < 1) {
5222 fprintf(stderr, "Invalid number of CPUs\n");
5223 exit(1);
5225 if (max_cpus < smp_cpus) {
5226 fprintf(stderr, "maxcpus must be equal to or greater than "
5227 "smp\n");
5228 exit(1);
5230 if (max_cpus > 255) {
5231 fprintf(stderr, "Unsupported number of maxcpus\n");
5232 exit(1);
5234 break;
5235 case QEMU_OPTION_vnc:
5236 display_type = DT_VNC;
5237 vnc_display = optarg;
5238 break;
5239 #ifdef TARGET_I386
5240 case QEMU_OPTION_no_acpi:
5241 acpi_enabled = 0;
5242 break;
5243 case QEMU_OPTION_no_hpet:
5244 no_hpet = 1;
5245 break;
5246 case QEMU_OPTION_balloon:
5247 if (balloon_parse(optarg) < 0) {
5248 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5249 exit(1);
5251 break;
5252 #endif
5253 case QEMU_OPTION_no_reboot:
5254 no_reboot = 1;
5255 break;
5256 case QEMU_OPTION_no_shutdown:
5257 no_shutdown = 1;
5258 break;
5259 case QEMU_OPTION_show_cursor:
5260 cursor_hide = 0;
5261 break;
5262 case QEMU_OPTION_uuid:
5263 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5264 fprintf(stderr, "Fail to parse UUID string."
5265 " Wrong format.\n");
5266 exit(1);
5268 break;
5269 #ifndef _WIN32
5270 case QEMU_OPTION_daemonize:
5271 daemonize = 1;
5272 break;
5273 #endif
5274 case QEMU_OPTION_option_rom:
5275 if (nb_option_roms >= MAX_OPTION_ROMS) {
5276 fprintf(stderr, "Too many option ROMs\n");
5277 exit(1);
5279 option_rom[nb_option_roms] = optarg;
5280 nb_option_roms++;
5281 break;
5282 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5283 case QEMU_OPTION_semihosting:
5284 semihosting_enabled = 1;
5285 break;
5286 #endif
5287 case QEMU_OPTION_name:
5288 qemu_name = qemu_strdup(optarg);
5290 char *p = strchr(qemu_name, ',');
5291 if (p != NULL) {
5292 *p++ = 0;
5293 if (strncmp(p, "process=", 8)) {
5294 fprintf(stderr, "Unknown subargument %s to -name", p);
5295 exit(1);
5297 p += 8;
5298 set_proc_name(p);
5301 break;
5302 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5303 case QEMU_OPTION_prom_env:
5304 if (nb_prom_envs >= MAX_PROM_ENVS) {
5305 fprintf(stderr, "Too many prom variables\n");
5306 exit(1);
5308 prom_envs[nb_prom_envs] = optarg;
5309 nb_prom_envs++;
5310 break;
5311 #endif
5312 #ifdef TARGET_ARM
5313 case QEMU_OPTION_old_param:
5314 old_param = 1;
5315 break;
5316 #endif
5317 case QEMU_OPTION_clock:
5318 configure_alarms(optarg);
5319 break;
5320 case QEMU_OPTION_startdate:
5321 configure_rtc_date_offset(optarg, 1);
5322 break;
5323 case QEMU_OPTION_rtc:
5324 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5325 if (!opts) {
5326 fprintf(stderr, "parse error: %s\n", optarg);
5327 exit(1);
5329 configure_rtc(opts);
5330 break;
5331 case QEMU_OPTION_tb_size:
5332 tb_size = strtol(optarg, NULL, 0);
5333 if (tb_size < 0)
5334 tb_size = 0;
5335 break;
5336 case QEMU_OPTION_icount:
5337 use_icount = 1;
5338 if (strcmp(optarg, "auto") == 0) {
5339 icount_time_shift = -1;
5340 } else {
5341 icount_time_shift = strtol(optarg, NULL, 0);
5343 break;
5344 case QEMU_OPTION_incoming:
5345 incoming = optarg;
5346 break;
5347 #ifndef _WIN32
5348 case QEMU_OPTION_chroot:
5349 chroot_dir = optarg;
5350 break;
5351 case QEMU_OPTION_runas:
5352 run_as = optarg;
5353 break;
5354 #endif
5355 #ifdef CONFIG_XEN
5356 case QEMU_OPTION_xen_domid:
5357 xen_domid = atoi(optarg);
5358 break;
5359 case QEMU_OPTION_xen_create:
5360 xen_mode = XEN_CREATE;
5361 break;
5362 case QEMU_OPTION_xen_attach:
5363 xen_mode = XEN_ATTACH;
5364 break;
5365 #endif
5366 case QEMU_OPTION_readconfig:
5368 FILE *fp;
5369 fp = fopen(optarg, "r");
5370 if (fp == NULL) {
5371 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5372 exit(1);
5374 if (qemu_config_parse(fp) != 0) {
5375 exit(1);
5377 fclose(fp);
5378 break;
5380 case QEMU_OPTION_writeconfig:
5382 FILE *fp;
5383 if (strcmp(optarg, "-") == 0) {
5384 fp = stdout;
5385 } else {
5386 fp = fopen(optarg, "w");
5387 if (fp == NULL) {
5388 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5389 exit(1);
5392 qemu_config_write(fp);
5393 fclose(fp);
5394 break;
5400 /* If no data_dir is specified then try to find it relative to the
5401 executable path. */
5402 if (!data_dir) {
5403 data_dir = find_datadir(argv[0]);
5405 /* If all else fails use the install patch specified when building. */
5406 if (!data_dir) {
5407 data_dir = CONFIG_QEMU_SHAREDIR;
5411 * Default to max_cpus = smp_cpus, in case the user doesn't
5412 * specify a max_cpus value.
5414 if (!max_cpus)
5415 max_cpus = smp_cpus;
5417 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5418 if (smp_cpus > machine->max_cpus) {
5419 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5420 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5421 machine->max_cpus);
5422 exit(1);
5425 if (display_type == DT_NOGRAPHIC) {
5426 if (serial_device_index == 0)
5427 serial_devices[0] = "stdio";
5428 if (parallel_device_index == 0)
5429 parallel_devices[0] = "null";
5430 if (strncmp(monitor_devices[0], "vc", 2) == 0) {
5431 monitor_devices[0] = "stdio";
5435 #ifndef _WIN32
5436 if (daemonize) {
5437 pid_t pid;
5439 if (pipe(fds) == -1)
5440 exit(1);
5442 pid = fork();
5443 if (pid > 0) {
5444 uint8_t status;
5445 ssize_t len;
5447 close(fds[1]);
5449 again:
5450 len = read(fds[0], &status, 1);
5451 if (len == -1 && (errno == EINTR))
5452 goto again;
5454 if (len != 1)
5455 exit(1);
5456 else if (status == 1) {
5457 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5458 exit(1);
5459 } else
5460 exit(0);
5461 } else if (pid < 0)
5462 exit(1);
5464 setsid();
5466 pid = fork();
5467 if (pid > 0)
5468 exit(0);
5469 else if (pid < 0)
5470 exit(1);
5472 umask(027);
5474 signal(SIGTSTP, SIG_IGN);
5475 signal(SIGTTOU, SIG_IGN);
5476 signal(SIGTTIN, SIG_IGN);
5479 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5480 if (daemonize) {
5481 uint8_t status = 1;
5482 write(fds[1], &status, 1);
5483 } else
5484 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5485 exit(1);
5487 #endif
5489 if (kvm_enabled()) {
5490 int ret;
5492 ret = kvm_init(smp_cpus);
5493 if (ret < 0) {
5494 fprintf(stderr, "failed to initialize KVM\n");
5495 exit(1);
5499 if (qemu_init_main_loop()) {
5500 fprintf(stderr, "qemu_init_main_loop failed\n");
5501 exit(1);
5503 linux_boot = (kernel_filename != NULL);
5505 if (!linux_boot && *kernel_cmdline != '\0') {
5506 fprintf(stderr, "-append only allowed with -kernel option\n");
5507 exit(1);
5510 if (!linux_boot && initrd_filename != NULL) {
5511 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5512 exit(1);
5515 #ifndef _WIN32
5516 /* Win32 doesn't support line-buffering and requires size >= 2 */
5517 setvbuf(stdout, NULL, _IOLBF, 0);
5518 #endif
5520 if (init_timer_alarm() < 0) {
5521 fprintf(stderr, "could not initialize alarm timer\n");
5522 exit(1);
5524 if (use_icount && icount_time_shift < 0) {
5525 use_icount = 2;
5526 /* 125MIPS seems a reasonable initial guess at the guest speed.
5527 It will be corrected fairly quickly anyway. */
5528 icount_time_shift = 3;
5529 init_icount_adjust();
5532 #ifdef _WIN32
5533 socket_init();
5534 #endif
5536 if (net_init_clients() < 0) {
5537 exit(1);
5540 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5541 net_set_boot_mask(net_boot);
5543 /* init the bluetooth world */
5544 if (foreach_device_config(DEV_BT, bt_parse))
5545 exit(1);
5547 /* init the memory */
5548 if (ram_size == 0)
5549 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5551 /* init the dynamic translator */
5552 cpu_exec_init_all(tb_size * 1024 * 1024);
5554 bdrv_init_with_whitelist();
5556 /* we always create the cdrom drive, even if no disk is there */
5557 drive_add(NULL, CDROM_ALIAS);
5559 /* we always create at least one floppy */
5560 drive_add(NULL, FD_ALIAS, 0);
5562 /* we always create one sd slot, even if no card is in it */
5563 drive_add(NULL, SD_ALIAS);
5565 /* open the virtual block devices */
5566 if (snapshot)
5567 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5568 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5569 exit(1);
5571 vmstate_register(0, &vmstate_timers ,&timers_state);
5572 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5574 /* Maintain compatibility with multiple stdio monitors */
5575 if (!strcmp(monitor_devices[0],"stdio")) {
5576 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5577 const char *devname = serial_devices[i];
5578 if (devname && !strcmp(devname,"mon:stdio")) {
5579 monitor_devices[0] = NULL;
5580 break;
5581 } else if (devname && !strcmp(devname,"stdio")) {
5582 monitor_devices[0] = NULL;
5583 serial_devices[i] = "mon:stdio";
5584 break;
5589 if (nb_numa_nodes > 0) {
5590 int i;
5592 if (nb_numa_nodes > smp_cpus) {
5593 nb_numa_nodes = smp_cpus;
5596 /* If no memory size if given for any node, assume the default case
5597 * and distribute the available memory equally across all nodes
5599 for (i = 0; i < nb_numa_nodes; i++) {
5600 if (node_mem[i] != 0)
5601 break;
5603 if (i == nb_numa_nodes) {
5604 uint64_t usedmem = 0;
5606 /* On Linux, the each node's border has to be 8MB aligned,
5607 * the final node gets the rest.
5609 for (i = 0; i < nb_numa_nodes - 1; i++) {
5610 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5611 usedmem += node_mem[i];
5613 node_mem[i] = ram_size - usedmem;
5616 for (i = 0; i < nb_numa_nodes; i++) {
5617 if (node_cpumask[i] != 0)
5618 break;
5620 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5621 * must cope with this anyway, because there are BIOSes out there in
5622 * real machines which also use this scheme.
5624 if (i == nb_numa_nodes) {
5625 for (i = 0; i < smp_cpus; i++) {
5626 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5631 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5632 const char *devname = monitor_devices[i];
5633 if (devname && strcmp(devname, "none")) {
5634 char label[32];
5635 if (i == 0) {
5636 snprintf(label, sizeof(label), "monitor");
5637 } else {
5638 snprintf(label, sizeof(label), "monitor%d", i);
5640 monitor_hds[i] = qemu_chr_open(label, devname, NULL);
5641 if (!monitor_hds[i]) {
5642 fprintf(stderr, "qemu: could not open monitor device '%s'\n",
5643 devname);
5644 exit(1);
5649 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5650 const char *devname = serial_devices[i];
5651 if (devname && strcmp(devname, "none")) {
5652 char label[32];
5653 snprintf(label, sizeof(label), "serial%d", i);
5654 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5655 if (!serial_hds[i]) {
5656 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
5657 devname, strerror(errno));
5658 exit(1);
5663 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5664 const char *devname = parallel_devices[i];
5665 if (devname && strcmp(devname, "none")) {
5666 char label[32];
5667 snprintf(label, sizeof(label), "parallel%d", i);
5668 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5669 if (!parallel_hds[i]) {
5670 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
5671 devname, strerror(errno));
5672 exit(1);
5677 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5678 const char *devname = virtio_consoles[i];
5679 if (devname && strcmp(devname, "none")) {
5680 char label[32];
5681 snprintf(label, sizeof(label), "virtcon%d", i);
5682 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5683 if (!virtcon_hds[i]) {
5684 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
5685 devname, strerror(errno));
5686 exit(1);
5691 module_call_init(MODULE_INIT_DEVICE);
5693 if (watchdog) {
5694 i = select_watchdog(watchdog);
5695 if (i > 0)
5696 exit (i == 1 ? 1 : 0);
5699 if (machine->compat_props) {
5700 qdev_prop_register_compat(machine->compat_props);
5702 machine->init(ram_size, boot_devices,
5703 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5706 #ifndef _WIN32
5707 /* must be after terminal init, SDL library changes signal handlers */
5708 sighandler_setup();
5709 #endif
5711 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5712 for (i = 0; i < nb_numa_nodes; i++) {
5713 if (node_cpumask[i] & (1 << env->cpu_index)) {
5714 env->numa_node = i;
5719 current_machine = machine;
5721 /* init USB devices */
5722 if (usb_enabled) {
5723 if (foreach_device_config(DEV_USB, usb_parse) < 0)
5724 exit(1);
5727 /* init generic devices */
5728 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5729 exit(1);
5731 if (!display_state)
5732 dumb_display_init();
5733 /* just use the first displaystate for the moment */
5734 ds = display_state;
5736 if (display_type == DT_DEFAULT) {
5737 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5738 display_type = DT_SDL;
5739 #else
5740 display_type = DT_VNC;
5741 vnc_display = "localhost:0,to=99";
5742 show_vnc_port = 1;
5743 #endif
5747 switch (display_type) {
5748 case DT_NOGRAPHIC:
5749 break;
5750 #if defined(CONFIG_CURSES)
5751 case DT_CURSES:
5752 curses_display_init(ds, full_screen);
5753 break;
5754 #endif
5755 #if defined(CONFIG_SDL)
5756 case DT_SDL:
5757 sdl_display_init(ds, full_screen, no_frame);
5758 break;
5759 #elif defined(CONFIG_COCOA)
5760 case DT_SDL:
5761 cocoa_display_init(ds, full_screen);
5762 break;
5763 #endif
5764 case DT_VNC:
5765 vnc_display_init(ds);
5766 if (vnc_display_open(ds, vnc_display) < 0)
5767 exit(1);
5769 if (show_vnc_port) {
5770 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5772 break;
5773 default:
5774 break;
5776 dpy_resize(ds);
5778 dcl = ds->listeners;
5779 while (dcl != NULL) {
5780 if (dcl->dpy_refresh != NULL) {
5781 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5782 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5784 dcl = dcl->next;
5787 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5788 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5789 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5792 text_consoles_set_display(display_state);
5793 qemu_chr_initial_reset();
5795 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5796 if (monitor_devices[i] && monitor_hds[i]) {
5797 monitor_init(monitor_hds[i],
5798 MONITOR_USE_READLINE |
5799 ((i == 0) ? MONITOR_IS_DEFAULT : 0));
5803 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5804 const char *devname = serial_devices[i];
5805 if (devname && strcmp(devname, "none")) {
5806 if (strstart(devname, "vc", 0))
5807 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5811 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5812 const char *devname = parallel_devices[i];
5813 if (devname && strcmp(devname, "none")) {
5814 if (strstart(devname, "vc", 0))
5815 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5819 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5820 const char *devname = virtio_consoles[i];
5821 if (virtcon_hds[i] && devname) {
5822 if (strstart(devname, "vc", 0))
5823 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5827 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5828 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5829 gdbstub_dev);
5830 exit(1);
5833 qdev_machine_creation_done();
5835 rom_load_all();
5837 qemu_system_reset();
5838 if (loadvm) {
5839 if (load_vmstate(cur_mon, loadvm) < 0) {
5840 autostart = 0;
5844 if (incoming) {
5845 qemu_start_incoming_migration(incoming);
5846 } else if (autostart) {
5847 vm_start();
5850 #ifndef _WIN32
5851 if (daemonize) {
5852 uint8_t status = 0;
5853 ssize_t len;
5855 again1:
5856 len = write(fds[1], &status, 1);
5857 if (len == -1 && (errno == EINTR))
5858 goto again1;
5860 if (len != 1)
5861 exit(1);
5863 chdir("/");
5864 TFR(fd = open("/dev/null", O_RDWR));
5865 if (fd == -1)
5866 exit(1);
5869 if (run_as) {
5870 pwd = getpwnam(run_as);
5871 if (!pwd) {
5872 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5873 exit(1);
5877 if (chroot_dir) {
5878 if (chroot(chroot_dir) < 0) {
5879 fprintf(stderr, "chroot failed\n");
5880 exit(1);
5882 chdir("/");
5885 if (run_as) {
5886 if (setgid(pwd->pw_gid) < 0) {
5887 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5888 exit(1);
5890 if (setuid(pwd->pw_uid) < 0) {
5891 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5892 exit(1);
5894 if (setuid(0) != -1) {
5895 fprintf(stderr, "Dropping privileges failed\n");
5896 exit(1);
5900 if (daemonize) {
5901 dup2(fd, 0);
5902 dup2(fd, 1);
5903 dup2(fd, 2);
5905 close(fd);
5907 #endif
5909 main_loop();
5910 quit_timers();
5911 net_cleanup();
5913 return 0;