Fix signature of new_vlan_client
[qemu.git] / vl.c
blobac9ff5251d933392f9c31003a20b72cf4f8c48fc
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 bdrv_flags, onerror;
2005 const char *devaddr;
2006 DriveInfo *dinfo;
2007 int snapshot = 0;
2009 *fatal_error = 1;
2011 translation = BIOS_ATA_TRANSLATION_AUTO;
2012 cache = 1;
2014 if (machine && machine->use_scsi) {
2015 type = IF_SCSI;
2016 max_devs = MAX_SCSI_DEVS;
2017 pstrcpy(devname, sizeof(devname), "scsi");
2018 } else {
2019 type = IF_IDE;
2020 max_devs = MAX_IDE_DEVS;
2021 pstrcpy(devname, sizeof(devname), "ide");
2023 media = MEDIA_DISK;
2025 /* extract parameters */
2026 bus_id = qemu_opt_get_number(opts, "bus", 0);
2027 unit_id = qemu_opt_get_number(opts, "unit", -1);
2028 index = qemu_opt_get_number(opts, "index", -1);
2030 cyls = qemu_opt_get_number(opts, "cyls", 0);
2031 heads = qemu_opt_get_number(opts, "heads", 0);
2032 secs = qemu_opt_get_number(opts, "secs", 0);
2034 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
2036 file = qemu_opt_get(opts, "file");
2037 serial = qemu_opt_get(opts, "serial");
2039 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
2040 pstrcpy(devname, sizeof(devname), buf);
2041 if (!strcmp(buf, "ide")) {
2042 type = IF_IDE;
2043 max_devs = MAX_IDE_DEVS;
2044 } else if (!strcmp(buf, "scsi")) {
2045 type = IF_SCSI;
2046 max_devs = MAX_SCSI_DEVS;
2047 } else if (!strcmp(buf, "floppy")) {
2048 type = IF_FLOPPY;
2049 max_devs = 0;
2050 } else if (!strcmp(buf, "pflash")) {
2051 type = IF_PFLASH;
2052 max_devs = 0;
2053 } else if (!strcmp(buf, "mtd")) {
2054 type = IF_MTD;
2055 max_devs = 0;
2056 } else if (!strcmp(buf, "sd")) {
2057 type = IF_SD;
2058 max_devs = 0;
2059 } else if (!strcmp(buf, "virtio")) {
2060 type = IF_VIRTIO;
2061 max_devs = 0;
2062 } else if (!strcmp(buf, "xen")) {
2063 type = IF_XEN;
2064 max_devs = 0;
2065 } else if (!strcmp(buf, "none")) {
2066 type = IF_NONE;
2067 max_devs = 0;
2068 } else {
2069 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
2070 return NULL;
2074 if (cyls || heads || secs) {
2075 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
2076 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2077 return NULL;
2079 if (heads < 1 || (type == IF_IDE && heads > 16)) {
2080 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2081 return NULL;
2083 if (secs < 1 || (type == IF_IDE && secs > 63)) {
2084 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2085 return NULL;
2089 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2090 if (!cyls) {
2091 fprintf(stderr,
2092 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2093 buf);
2094 return NULL;
2096 if (!strcmp(buf, "none"))
2097 translation = BIOS_ATA_TRANSLATION_NONE;
2098 else if (!strcmp(buf, "lba"))
2099 translation = BIOS_ATA_TRANSLATION_LBA;
2100 else if (!strcmp(buf, "auto"))
2101 translation = BIOS_ATA_TRANSLATION_AUTO;
2102 else {
2103 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2104 return NULL;
2108 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2109 if (!strcmp(buf, "disk")) {
2110 media = MEDIA_DISK;
2111 } else if (!strcmp(buf, "cdrom")) {
2112 if (cyls || secs || heads) {
2113 fprintf(stderr,
2114 "qemu: '%s' invalid physical CHS format\n", buf);
2115 return NULL;
2117 media = MEDIA_CDROM;
2118 } else {
2119 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2120 return NULL;
2124 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2125 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2126 cache = 0;
2127 else if (!strcmp(buf, "writethrough"))
2128 cache = 1;
2129 else if (!strcmp(buf, "writeback"))
2130 cache = 2;
2131 else {
2132 fprintf(stderr, "qemu: invalid cache option\n");
2133 return NULL;
2137 #ifdef CONFIG_LINUX_AIO
2138 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2139 if (!strcmp(buf, "threads"))
2140 aio = 0;
2141 else if (!strcmp(buf, "native"))
2142 aio = 1;
2143 else {
2144 fprintf(stderr, "qemu: invalid aio option\n");
2145 return NULL;
2148 #endif
2150 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2151 if (strcmp(buf, "?") == 0) {
2152 fprintf(stderr, "qemu: Supported formats:");
2153 bdrv_iterate_format(bdrv_format_print, NULL);
2154 fprintf(stderr, "\n");
2155 return NULL;
2157 drv = bdrv_find_format(buf);
2158 if (!drv) {
2159 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2160 return NULL;
2164 onerror = BLOCK_ERR_STOP_ENOSPC;
2165 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2166 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2167 fprintf(stderr, "werror is no supported by this format\n");
2168 return NULL;
2170 if (!strcmp(buf, "ignore"))
2171 onerror = BLOCK_ERR_IGNORE;
2172 else if (!strcmp(buf, "enospc"))
2173 onerror = BLOCK_ERR_STOP_ENOSPC;
2174 else if (!strcmp(buf, "stop"))
2175 onerror = BLOCK_ERR_STOP_ANY;
2176 else if (!strcmp(buf, "report"))
2177 onerror = BLOCK_ERR_REPORT;
2178 else {
2179 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2180 return NULL;
2184 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2185 if (type != IF_VIRTIO) {
2186 fprintf(stderr, "addr is not supported\n");
2187 return NULL;
2191 /* compute bus and unit according index */
2193 if (index != -1) {
2194 if (bus_id != 0 || unit_id != -1) {
2195 fprintf(stderr,
2196 "qemu: index cannot be used with bus and unit\n");
2197 return NULL;
2199 if (max_devs == 0)
2201 unit_id = index;
2202 bus_id = 0;
2203 } else {
2204 unit_id = index % max_devs;
2205 bus_id = index / max_devs;
2209 /* if user doesn't specify a unit_id,
2210 * try to find the first free
2213 if (unit_id == -1) {
2214 unit_id = 0;
2215 while (drive_get(type, bus_id, unit_id) != NULL) {
2216 unit_id++;
2217 if (max_devs && unit_id >= max_devs) {
2218 unit_id -= max_devs;
2219 bus_id++;
2224 /* check unit id */
2226 if (max_devs && unit_id >= max_devs) {
2227 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2228 unit_id, max_devs - 1);
2229 return NULL;
2233 * ignore multiple definitions
2236 if (drive_get(type, bus_id, unit_id) != NULL) {
2237 *fatal_error = 0;
2238 return NULL;
2241 /* init */
2243 dinfo = qemu_mallocz(sizeof(*dinfo));
2244 if ((buf = qemu_opts_id(opts)) != NULL) {
2245 dinfo->id = qemu_strdup(buf);
2246 } else {
2247 /* no id supplied -> create one */
2248 dinfo->id = qemu_mallocz(32);
2249 if (type == IF_IDE || type == IF_SCSI)
2250 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2251 if (max_devs)
2252 snprintf(dinfo->id, 32, "%s%i%s%i",
2253 devname, bus_id, mediastr, unit_id);
2254 else
2255 snprintf(dinfo->id, 32, "%s%s%i",
2256 devname, mediastr, unit_id);
2258 dinfo->bdrv = bdrv_new(dinfo->id);
2259 dinfo->devaddr = devaddr;
2260 dinfo->type = type;
2261 dinfo->bus = bus_id;
2262 dinfo->unit = unit_id;
2263 dinfo->onerror = onerror;
2264 dinfo->opts = opts;
2265 if (serial)
2266 strncpy(dinfo->serial, serial, sizeof(serial));
2267 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2269 switch(type) {
2270 case IF_IDE:
2271 case IF_SCSI:
2272 case IF_XEN:
2273 case IF_NONE:
2274 switch(media) {
2275 case MEDIA_DISK:
2276 if (cyls != 0) {
2277 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2278 bdrv_set_translation_hint(dinfo->bdrv, translation);
2280 break;
2281 case MEDIA_CDROM:
2282 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2283 break;
2285 break;
2286 case IF_SD:
2287 /* FIXME: This isn't really a floppy, but it's a reasonable
2288 approximation. */
2289 case IF_FLOPPY:
2290 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2291 break;
2292 case IF_PFLASH:
2293 case IF_MTD:
2294 break;
2295 case IF_VIRTIO:
2296 /* add virtio block device */
2297 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2298 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2299 qemu_opt_set(opts, "drive", dinfo->id);
2300 if (devaddr)
2301 qemu_opt_set(opts, "addr", devaddr);
2302 break;
2303 case IF_COUNT:
2304 abort();
2306 if (!file) {
2307 *fatal_error = 0;
2308 return NULL;
2310 bdrv_flags = 0;
2311 if (snapshot) {
2312 bdrv_flags |= BDRV_O_SNAPSHOT;
2313 cache = 2; /* always use write-back with snapshot */
2315 if (cache == 0) /* no caching */
2316 bdrv_flags |= BDRV_O_NOCACHE;
2317 else if (cache == 2) /* write-back */
2318 bdrv_flags |= BDRV_O_CACHE_WB;
2320 if (aio == 1) {
2321 bdrv_flags |= BDRV_O_NATIVE_AIO;
2322 } else {
2323 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2326 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2327 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2328 file, strerror(errno));
2329 return NULL;
2332 if (bdrv_key_required(dinfo->bdrv))
2333 autostart = 0;
2334 *fatal_error = 0;
2335 return dinfo;
2338 static int drive_init_func(QemuOpts *opts, void *opaque)
2340 QEMUMachine *machine = opaque;
2341 int fatal_error = 0;
2343 if (drive_init(opts, machine, &fatal_error) == NULL) {
2344 if (fatal_error)
2345 return 1;
2347 return 0;
2350 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2352 if (NULL == qemu_opt_get(opts, "snapshot")) {
2353 qemu_opt_set(opts, "snapshot", "on");
2355 return 0;
2358 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2360 boot_set_handler = func;
2361 boot_set_opaque = opaque;
2364 int qemu_boot_set(const char *boot_devices)
2366 if (!boot_set_handler) {
2367 return -EINVAL;
2369 return boot_set_handler(boot_set_opaque, boot_devices);
2372 static int parse_bootdevices(char *devices)
2374 /* We just do some generic consistency checks */
2375 const char *p;
2376 int bitmap = 0;
2378 for (p = devices; *p != '\0'; p++) {
2379 /* Allowed boot devices are:
2380 * a-b: floppy disk drives
2381 * c-f: IDE disk drives
2382 * g-m: machine implementation dependant drives
2383 * n-p: network devices
2384 * It's up to each machine implementation to check if the given boot
2385 * devices match the actual hardware implementation and firmware
2386 * features.
2388 if (*p < 'a' || *p > 'p') {
2389 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2390 exit(1);
2392 if (bitmap & (1 << (*p - 'a'))) {
2393 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2394 exit(1);
2396 bitmap |= 1 << (*p - 'a');
2398 return bitmap;
2401 static void restore_boot_devices(void *opaque)
2403 char *standard_boot_devices = opaque;
2405 qemu_boot_set(standard_boot_devices);
2407 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2408 qemu_free(standard_boot_devices);
2411 static void numa_add(const char *optarg)
2413 char option[128];
2414 char *endptr;
2415 unsigned long long value, endvalue;
2416 int nodenr;
2418 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2419 if (!strcmp(option, "node")) {
2420 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2421 nodenr = nb_numa_nodes;
2422 } else {
2423 nodenr = strtoull(option, NULL, 10);
2426 if (get_param_value(option, 128, "mem", optarg) == 0) {
2427 node_mem[nodenr] = 0;
2428 } else {
2429 value = strtoull(option, &endptr, 0);
2430 switch (*endptr) {
2431 case 0: case 'M': case 'm':
2432 value <<= 20;
2433 break;
2434 case 'G': case 'g':
2435 value <<= 30;
2436 break;
2438 node_mem[nodenr] = value;
2440 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2441 node_cpumask[nodenr] = 0;
2442 } else {
2443 value = strtoull(option, &endptr, 10);
2444 if (value >= 64) {
2445 value = 63;
2446 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2447 } else {
2448 if (*endptr == '-') {
2449 endvalue = strtoull(endptr+1, &endptr, 10);
2450 if (endvalue >= 63) {
2451 endvalue = 62;
2452 fprintf(stderr,
2453 "only 63 CPUs in NUMA mode supported.\n");
2455 value = (1 << (endvalue + 1)) - (1 << value);
2456 } else {
2457 value = 1 << value;
2460 node_cpumask[nodenr] = value;
2462 nb_numa_nodes++;
2464 return;
2467 static void smp_parse(const char *optarg)
2469 int smp, sockets = 0, threads = 0, cores = 0;
2470 char *endptr;
2471 char option[128];
2473 smp = strtoul(optarg, &endptr, 10);
2474 if (endptr != optarg) {
2475 if (*endptr == ',') {
2476 endptr++;
2479 if (get_param_value(option, 128, "sockets", endptr) != 0)
2480 sockets = strtoull(option, NULL, 10);
2481 if (get_param_value(option, 128, "cores", endptr) != 0)
2482 cores = strtoull(option, NULL, 10);
2483 if (get_param_value(option, 128, "threads", endptr) != 0)
2484 threads = strtoull(option, NULL, 10);
2485 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2486 max_cpus = strtoull(option, NULL, 10);
2488 /* compute missing values, prefer sockets over cores over threads */
2489 if (smp == 0 || sockets == 0) {
2490 sockets = sockets > 0 ? sockets : 1;
2491 cores = cores > 0 ? cores : 1;
2492 threads = threads > 0 ? threads : 1;
2493 if (smp == 0) {
2494 smp = cores * threads * sockets;
2495 } else {
2496 sockets = smp / (cores * threads);
2498 } else {
2499 if (cores == 0) {
2500 threads = threads > 0 ? threads : 1;
2501 cores = smp / (sockets * threads);
2502 } else {
2503 if (sockets == 0) {
2504 sockets = smp / (cores * threads);
2505 } else {
2506 threads = smp / (cores * sockets);
2510 smp_cpus = smp;
2511 smp_cores = cores > 0 ? cores : 1;
2512 smp_threads = threads > 0 ? threads : 1;
2513 if (max_cpus == 0)
2514 max_cpus = smp_cpus;
2517 /***********************************************************/
2518 /* USB devices */
2520 static void usb_msd_password_cb(void *opaque, int err)
2522 USBDevice *dev = opaque;
2524 if (!err)
2525 usb_device_attach(dev);
2526 else
2527 dev->info->handle_destroy(dev);
2530 static struct {
2531 const char *name;
2532 const char *qdev;
2533 } usbdevs[] = {
2535 .name = "mouse",
2536 .qdev = "QEMU USB Mouse",
2538 .name = "tablet",
2539 .qdev = "QEMU USB Tablet",
2541 .name = "keyboard",
2542 .qdev = "QEMU USB Keyboard",
2544 .name = "wacom-tablet",
2545 .qdev = "QEMU PenPartner Tablet",
2549 static int usb_device_add(const char *devname, int is_hotplug)
2551 const char *p;
2552 USBBus *bus = usb_bus_find(-1 /* any */);
2553 USBDevice *dev = NULL;
2554 int i;
2556 if (!usb_enabled)
2557 return -1;
2559 /* simple devices which don't need extra care */
2560 for (i = 0; i < ARRAY_SIZE(usbdevs); i++) {
2561 if (strcmp(devname, usbdevs[i].name) != 0)
2562 continue;
2563 dev = usb_create_simple(bus, usbdevs[i].qdev);
2564 goto done;
2567 /* the other ones */
2568 if (strstart(devname, "host:", &p)) {
2569 dev = usb_host_device_open(p);
2570 } else if (strstart(devname, "disk:", &p)) {
2571 BlockDriverState *bs;
2573 dev = usb_msd_init(p);
2574 if (!dev)
2575 return -1;
2576 bs = usb_msd_get_bdrv(dev);
2577 if (bdrv_key_required(bs)) {
2578 autostart = 0;
2579 if (is_hotplug) {
2580 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2581 dev);
2582 return 0;
2585 } else if (strstart(devname, "serial:", &p)) {
2586 dev = usb_serial_init(p);
2587 #ifdef CONFIG_BRLAPI
2588 } else if (!strcmp(devname, "braille")) {
2589 dev = usb_baum_init();
2590 #endif
2591 } else if (strstart(devname, "net:", &p)) {
2592 QemuOpts *opts;
2593 int idx;
2595 opts = qemu_opts_parse(&qemu_net_opts, p, NULL);
2596 if (!opts) {
2597 return -1;
2600 qemu_opt_set(opts, "type", "nic");
2601 qemu_opt_set(opts, "model", "usb");
2603 idx = net_client_init(NULL, opts, 0);
2604 if (idx == -1) {
2605 return -1;
2608 dev = usb_net_init(&nd_table[idx]);
2609 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2610 dev = usb_bt_init(devname[2] ? hci_init(p) :
2611 bt_new_hci(qemu_find_bt_vlan(0)));
2612 } else {
2613 return -1;
2615 if (!dev)
2616 return -1;
2618 done:
2619 return 0;
2622 static int usb_device_del(const char *devname)
2624 int bus_num, addr;
2625 const char *p;
2627 if (strstart(devname, "host:", &p))
2628 return usb_host_device_close(p);
2630 if (!usb_enabled)
2631 return -1;
2633 p = strchr(devname, '.');
2634 if (!p)
2635 return -1;
2636 bus_num = strtoul(devname, NULL, 0);
2637 addr = strtoul(p + 1, NULL, 0);
2639 return usb_device_delete_addr(bus_num, addr);
2642 static int usb_parse(const char *cmdline)
2644 return usb_device_add(cmdline, 0);
2647 void do_usb_add(Monitor *mon, const QDict *qdict)
2649 usb_device_add(qdict_get_str(qdict, "devname"), 1);
2652 void do_usb_del(Monitor *mon, const QDict *qdict)
2654 usb_device_del(qdict_get_str(qdict, "devname"));
2657 /***********************************************************/
2658 /* PCMCIA/Cardbus */
2660 static struct pcmcia_socket_entry_s {
2661 PCMCIASocket *socket;
2662 struct pcmcia_socket_entry_s *next;
2663 } *pcmcia_sockets = 0;
2665 void pcmcia_socket_register(PCMCIASocket *socket)
2667 struct pcmcia_socket_entry_s *entry;
2669 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2670 entry->socket = socket;
2671 entry->next = pcmcia_sockets;
2672 pcmcia_sockets = entry;
2675 void pcmcia_socket_unregister(PCMCIASocket *socket)
2677 struct pcmcia_socket_entry_s *entry, **ptr;
2679 ptr = &pcmcia_sockets;
2680 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2681 if (entry->socket == socket) {
2682 *ptr = entry->next;
2683 qemu_free(entry);
2687 void pcmcia_info(Monitor *mon)
2689 struct pcmcia_socket_entry_s *iter;
2691 if (!pcmcia_sockets)
2692 monitor_printf(mon, "No PCMCIA sockets\n");
2694 for (iter = pcmcia_sockets; iter; iter = iter->next)
2695 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2696 iter->socket->attached ? iter->socket->card_string :
2697 "Empty");
2700 /***********************************************************/
2701 /* register display */
2703 struct DisplayAllocator default_allocator = {
2704 defaultallocator_create_displaysurface,
2705 defaultallocator_resize_displaysurface,
2706 defaultallocator_free_displaysurface
2709 void register_displaystate(DisplayState *ds)
2711 DisplayState **s;
2712 s = &display_state;
2713 while (*s != NULL)
2714 s = &(*s)->next;
2715 ds->next = NULL;
2716 *s = ds;
2719 DisplayState *get_displaystate(void)
2721 return display_state;
2724 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2726 if(ds->allocator == &default_allocator) ds->allocator = da;
2727 return ds->allocator;
2730 /* dumb display */
2732 static void dumb_display_init(void)
2734 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2735 ds->allocator = &default_allocator;
2736 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2737 register_displaystate(ds);
2740 /***********************************************************/
2741 /* I/O handling */
2743 typedef struct IOHandlerRecord {
2744 int fd;
2745 IOCanRWHandler *fd_read_poll;
2746 IOHandler *fd_read;
2747 IOHandler *fd_write;
2748 int deleted;
2749 void *opaque;
2750 /* temporary data */
2751 struct pollfd *ufd;
2752 struct IOHandlerRecord *next;
2753 } IOHandlerRecord;
2755 static IOHandlerRecord *first_io_handler;
2757 /* XXX: fd_read_poll should be suppressed, but an API change is
2758 necessary in the character devices to suppress fd_can_read(). */
2759 int qemu_set_fd_handler2(int fd,
2760 IOCanRWHandler *fd_read_poll,
2761 IOHandler *fd_read,
2762 IOHandler *fd_write,
2763 void *opaque)
2765 IOHandlerRecord **pioh, *ioh;
2767 if (!fd_read && !fd_write) {
2768 pioh = &first_io_handler;
2769 for(;;) {
2770 ioh = *pioh;
2771 if (ioh == NULL)
2772 break;
2773 if (ioh->fd == fd) {
2774 ioh->deleted = 1;
2775 break;
2777 pioh = &ioh->next;
2779 } else {
2780 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2781 if (ioh->fd == fd)
2782 goto found;
2784 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2785 ioh->next = first_io_handler;
2786 first_io_handler = ioh;
2787 found:
2788 ioh->fd = fd;
2789 ioh->fd_read_poll = fd_read_poll;
2790 ioh->fd_read = fd_read;
2791 ioh->fd_write = fd_write;
2792 ioh->opaque = opaque;
2793 ioh->deleted = 0;
2795 return 0;
2798 int qemu_set_fd_handler(int fd,
2799 IOHandler *fd_read,
2800 IOHandler *fd_write,
2801 void *opaque)
2803 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2806 #ifdef _WIN32
2807 /***********************************************************/
2808 /* Polling handling */
2810 typedef struct PollingEntry {
2811 PollingFunc *func;
2812 void *opaque;
2813 struct PollingEntry *next;
2814 } PollingEntry;
2816 static PollingEntry *first_polling_entry;
2818 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2820 PollingEntry **ppe, *pe;
2821 pe = qemu_mallocz(sizeof(PollingEntry));
2822 pe->func = func;
2823 pe->opaque = opaque;
2824 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2825 *ppe = pe;
2826 return 0;
2829 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2831 PollingEntry **ppe, *pe;
2832 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2833 pe = *ppe;
2834 if (pe->func == func && pe->opaque == opaque) {
2835 *ppe = pe->next;
2836 qemu_free(pe);
2837 break;
2842 /***********************************************************/
2843 /* Wait objects support */
2844 typedef struct WaitObjects {
2845 int num;
2846 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2847 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2848 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2849 } WaitObjects;
2851 static WaitObjects wait_objects = {0};
2853 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2855 WaitObjects *w = &wait_objects;
2857 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2858 return -1;
2859 w->events[w->num] = handle;
2860 w->func[w->num] = func;
2861 w->opaque[w->num] = opaque;
2862 w->num++;
2863 return 0;
2866 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2868 int i, found;
2869 WaitObjects *w = &wait_objects;
2871 found = 0;
2872 for (i = 0; i < w->num; i++) {
2873 if (w->events[i] == handle)
2874 found = 1;
2875 if (found) {
2876 w->events[i] = w->events[i + 1];
2877 w->func[i] = w->func[i + 1];
2878 w->opaque[i] = w->opaque[i + 1];
2881 if (found)
2882 w->num--;
2884 #endif
2886 /***********************************************************/
2887 /* ram save/restore */
2889 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2890 #define RAM_SAVE_FLAG_COMPRESS 0x02
2891 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2892 #define RAM_SAVE_FLAG_PAGE 0x08
2893 #define RAM_SAVE_FLAG_EOS 0x10
2895 static int is_dup_page(uint8_t *page, uint8_t ch)
2897 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2898 uint32_t *array = (uint32_t *)page;
2899 int i;
2901 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2902 if (array[i] != val)
2903 return 0;
2906 return 1;
2909 static int ram_save_block(QEMUFile *f)
2911 static ram_addr_t current_addr = 0;
2912 ram_addr_t saved_addr = current_addr;
2913 ram_addr_t addr = 0;
2914 int found = 0;
2916 while (addr < last_ram_offset) {
2917 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2918 uint8_t *p;
2920 cpu_physical_memory_reset_dirty(current_addr,
2921 current_addr + TARGET_PAGE_SIZE,
2922 MIGRATION_DIRTY_FLAG);
2924 p = qemu_get_ram_ptr(current_addr);
2926 if (is_dup_page(p, *p)) {
2927 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2928 qemu_put_byte(f, *p);
2929 } else {
2930 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2931 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2934 found = 1;
2935 break;
2937 addr += TARGET_PAGE_SIZE;
2938 current_addr = (saved_addr + addr) % last_ram_offset;
2941 return found;
2944 static uint64_t bytes_transferred = 0;
2946 static ram_addr_t ram_save_remaining(void)
2948 ram_addr_t addr;
2949 ram_addr_t count = 0;
2951 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2952 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2953 count++;
2956 return count;
2959 uint64_t ram_bytes_remaining(void)
2961 return ram_save_remaining() * TARGET_PAGE_SIZE;
2964 uint64_t ram_bytes_transferred(void)
2966 return bytes_transferred;
2969 uint64_t ram_bytes_total(void)
2971 return last_ram_offset;
2974 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
2976 ram_addr_t addr;
2977 uint64_t bytes_transferred_last;
2978 double bwidth = 0;
2979 uint64_t expected_time = 0;
2981 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2982 qemu_file_set_error(f);
2983 return 0;
2986 if (stage == 1) {
2987 /* Make sure all dirty bits are set */
2988 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2989 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2990 cpu_physical_memory_set_dirty(addr);
2993 /* Enable dirty memory tracking */
2994 cpu_physical_memory_set_dirty_tracking(1);
2996 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2999 bytes_transferred_last = bytes_transferred;
3000 bwidth = get_clock();
3002 while (!qemu_file_rate_limit(f)) {
3003 int ret;
3005 ret = ram_save_block(f);
3006 bytes_transferred += ret * TARGET_PAGE_SIZE;
3007 if (ret == 0) /* no more blocks */
3008 break;
3011 bwidth = get_clock() - bwidth;
3012 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3014 /* if we haven't transferred anything this round, force expected_time to a
3015 * a very high value, but without crashing */
3016 if (bwidth == 0)
3017 bwidth = 0.000001;
3019 /* try transferring iterative blocks of memory */
3021 if (stage == 3) {
3023 /* flush all remaining blocks regardless of rate limiting */
3024 while (ram_save_block(f) != 0) {
3025 bytes_transferred += TARGET_PAGE_SIZE;
3027 cpu_physical_memory_set_dirty_tracking(0);
3030 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3032 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3034 return (stage == 2) && (expected_time <= migrate_max_downtime());
3037 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3039 ram_addr_t addr;
3040 int flags;
3042 if (version_id != 3)
3043 return -EINVAL;
3045 do {
3046 addr = qemu_get_be64(f);
3048 flags = addr & ~TARGET_PAGE_MASK;
3049 addr &= TARGET_PAGE_MASK;
3051 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3052 if (addr != last_ram_offset)
3053 return -EINVAL;
3056 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3057 uint8_t ch = qemu_get_byte(f);
3058 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3059 #ifndef _WIN32
3060 if (ch == 0 &&
3061 (!kvm_enabled() || kvm_has_sync_mmu())) {
3062 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3064 #endif
3065 } else if (flags & RAM_SAVE_FLAG_PAGE)
3066 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3067 } while (!(flags & RAM_SAVE_FLAG_EOS));
3069 return 0;
3072 void qemu_service_io(void)
3074 qemu_notify_event();
3077 /***********************************************************/
3078 /* machine registration */
3080 static QEMUMachine *first_machine = NULL;
3081 QEMUMachine *current_machine = NULL;
3083 int qemu_register_machine(QEMUMachine *m)
3085 QEMUMachine **pm;
3086 pm = &first_machine;
3087 while (*pm != NULL)
3088 pm = &(*pm)->next;
3089 m->next = NULL;
3090 *pm = m;
3091 return 0;
3094 static QEMUMachine *find_machine(const char *name)
3096 QEMUMachine *m;
3098 for(m = first_machine; m != NULL; m = m->next) {
3099 if (!strcmp(m->name, name))
3100 return m;
3101 if (m->alias && !strcmp(m->alias, name))
3102 return m;
3104 return NULL;
3107 static QEMUMachine *find_default_machine(void)
3109 QEMUMachine *m;
3111 for(m = first_machine; m != NULL; m = m->next) {
3112 if (m->is_default) {
3113 return m;
3116 return NULL;
3119 /***********************************************************/
3120 /* main execution loop */
3122 static void gui_update(void *opaque)
3124 uint64_t interval = GUI_REFRESH_INTERVAL;
3125 DisplayState *ds = opaque;
3126 DisplayChangeListener *dcl = ds->listeners;
3128 dpy_refresh(ds);
3130 while (dcl != NULL) {
3131 if (dcl->gui_timer_interval &&
3132 dcl->gui_timer_interval < interval)
3133 interval = dcl->gui_timer_interval;
3134 dcl = dcl->next;
3136 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3139 static void nographic_update(void *opaque)
3141 uint64_t interval = GUI_REFRESH_INTERVAL;
3143 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3146 struct vm_change_state_entry {
3147 VMChangeStateHandler *cb;
3148 void *opaque;
3149 QLIST_ENTRY (vm_change_state_entry) entries;
3152 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3154 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3155 void *opaque)
3157 VMChangeStateEntry *e;
3159 e = qemu_mallocz(sizeof (*e));
3161 e->cb = cb;
3162 e->opaque = opaque;
3163 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3164 return e;
3167 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3169 QLIST_REMOVE (e, entries);
3170 qemu_free (e);
3173 static void vm_state_notify(int running, int reason)
3175 VMChangeStateEntry *e;
3177 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3178 e->cb(e->opaque, running, reason);
3182 static void resume_all_vcpus(void);
3183 static void pause_all_vcpus(void);
3185 void vm_start(void)
3187 if (!vm_running) {
3188 cpu_enable_ticks();
3189 vm_running = 1;
3190 vm_state_notify(1, 0);
3191 qemu_rearm_alarm_timer(alarm_timer);
3192 resume_all_vcpus();
3196 /* reset/shutdown handler */
3198 typedef struct QEMUResetEntry {
3199 QTAILQ_ENTRY(QEMUResetEntry) entry;
3200 QEMUResetHandler *func;
3201 void *opaque;
3202 } QEMUResetEntry;
3204 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3205 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3206 static int reset_requested;
3207 static int shutdown_requested;
3208 static int powerdown_requested;
3209 static int debug_requested;
3210 static int vmstop_requested;
3212 int qemu_shutdown_requested(void)
3214 int r = shutdown_requested;
3215 shutdown_requested = 0;
3216 return r;
3219 int qemu_reset_requested(void)
3221 int r = reset_requested;
3222 reset_requested = 0;
3223 return r;
3226 int qemu_powerdown_requested(void)
3228 int r = powerdown_requested;
3229 powerdown_requested = 0;
3230 return r;
3233 static int qemu_debug_requested(void)
3235 int r = debug_requested;
3236 debug_requested = 0;
3237 return r;
3240 static int qemu_vmstop_requested(void)
3242 int r = vmstop_requested;
3243 vmstop_requested = 0;
3244 return r;
3247 static void do_vm_stop(int reason)
3249 if (vm_running) {
3250 cpu_disable_ticks();
3251 vm_running = 0;
3252 pause_all_vcpus();
3253 vm_state_notify(0, reason);
3257 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3259 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3261 re->func = func;
3262 re->opaque = opaque;
3263 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3266 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3268 QEMUResetEntry *re;
3270 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3271 if (re->func == func && re->opaque == opaque) {
3272 QTAILQ_REMOVE(&reset_handlers, re, entry);
3273 qemu_free(re);
3274 return;
3279 void qemu_system_reset(void)
3281 QEMUResetEntry *re, *nre;
3283 /* reset all devices */
3284 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3285 re->func(re->opaque);
3289 void qemu_system_reset_request(void)
3291 if (no_reboot) {
3292 shutdown_requested = 1;
3293 } else {
3294 reset_requested = 1;
3296 qemu_notify_event();
3299 void qemu_system_shutdown_request(void)
3301 shutdown_requested = 1;
3302 qemu_notify_event();
3305 void qemu_system_powerdown_request(void)
3307 powerdown_requested = 1;
3308 qemu_notify_event();
3311 #ifdef CONFIG_IOTHREAD
3312 static void qemu_system_vmstop_request(int reason)
3314 vmstop_requested = reason;
3315 qemu_notify_event();
3317 #endif
3319 #ifndef _WIN32
3320 static int io_thread_fd = -1;
3322 static void qemu_event_increment(void)
3324 static const char byte = 0;
3326 if (io_thread_fd == -1)
3327 return;
3329 write(io_thread_fd, &byte, sizeof(byte));
3332 static void qemu_event_read(void *opaque)
3334 int fd = (unsigned long)opaque;
3335 ssize_t len;
3337 /* Drain the notify pipe */
3338 do {
3339 char buffer[512];
3340 len = read(fd, buffer, sizeof(buffer));
3341 } while ((len == -1 && errno == EINTR) || len > 0);
3344 static int qemu_event_init(void)
3346 int err;
3347 int fds[2];
3349 err = pipe(fds);
3350 if (err == -1)
3351 return -errno;
3353 err = fcntl_setfl(fds[0], O_NONBLOCK);
3354 if (err < 0)
3355 goto fail;
3357 err = fcntl_setfl(fds[1], O_NONBLOCK);
3358 if (err < 0)
3359 goto fail;
3361 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3362 (void *)(unsigned long)fds[0]);
3364 io_thread_fd = fds[1];
3365 return 0;
3367 fail:
3368 close(fds[0]);
3369 close(fds[1]);
3370 return err;
3372 #else
3373 HANDLE qemu_event_handle;
3375 static void dummy_event_handler(void *opaque)
3379 static int qemu_event_init(void)
3381 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3382 if (!qemu_event_handle) {
3383 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3384 return -1;
3386 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3387 return 0;
3390 static void qemu_event_increment(void)
3392 if (!SetEvent(qemu_event_handle)) {
3393 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3394 GetLastError());
3395 exit (1);
3398 #endif
3400 static int cpu_can_run(CPUState *env)
3402 if (env->stop)
3403 return 0;
3404 if (env->stopped)
3405 return 0;
3406 return 1;
3409 #ifndef CONFIG_IOTHREAD
3410 static int qemu_init_main_loop(void)
3412 return qemu_event_init();
3415 void qemu_init_vcpu(void *_env)
3417 CPUState *env = _env;
3419 if (kvm_enabled())
3420 kvm_init_vcpu(env);
3421 env->nr_cores = smp_cores;
3422 env->nr_threads = smp_threads;
3423 return;
3426 int qemu_cpu_self(void *env)
3428 return 1;
3431 static void resume_all_vcpus(void)
3435 static void pause_all_vcpus(void)
3439 void qemu_cpu_kick(void *env)
3441 return;
3444 void qemu_notify_event(void)
3446 CPUState *env = cpu_single_env;
3448 if (env) {
3449 cpu_exit(env);
3453 void qemu_mutex_lock_iothread(void) {}
3454 void qemu_mutex_unlock_iothread(void) {}
3456 void vm_stop(int reason)
3458 do_vm_stop(reason);
3461 #else /* CONFIG_IOTHREAD */
3463 #include "qemu-thread.h"
3465 QemuMutex qemu_global_mutex;
3466 static QemuMutex qemu_fair_mutex;
3468 static QemuThread io_thread;
3470 static QemuThread *tcg_cpu_thread;
3471 static QemuCond *tcg_halt_cond;
3473 static int qemu_system_ready;
3474 /* cpu creation */
3475 static QemuCond qemu_cpu_cond;
3476 /* system init */
3477 static QemuCond qemu_system_cond;
3478 static QemuCond qemu_pause_cond;
3480 static void block_io_signals(void);
3481 static void unblock_io_signals(void);
3482 static int tcg_has_work(void);
3484 static int qemu_init_main_loop(void)
3486 int ret;
3488 ret = qemu_event_init();
3489 if (ret)
3490 return ret;
3492 qemu_cond_init(&qemu_pause_cond);
3493 qemu_mutex_init(&qemu_fair_mutex);
3494 qemu_mutex_init(&qemu_global_mutex);
3495 qemu_mutex_lock(&qemu_global_mutex);
3497 unblock_io_signals();
3498 qemu_thread_self(&io_thread);
3500 return 0;
3503 static void qemu_wait_io_event(CPUState *env)
3505 while (!tcg_has_work())
3506 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3508 qemu_mutex_unlock(&qemu_global_mutex);
3511 * Users of qemu_global_mutex can be starved, having no chance
3512 * to acquire it since this path will get to it first.
3513 * So use another lock to provide fairness.
3515 qemu_mutex_lock(&qemu_fair_mutex);
3516 qemu_mutex_unlock(&qemu_fair_mutex);
3518 qemu_mutex_lock(&qemu_global_mutex);
3519 if (env->stop) {
3520 env->stop = 0;
3521 env->stopped = 1;
3522 qemu_cond_signal(&qemu_pause_cond);
3526 static int qemu_cpu_exec(CPUState *env);
3528 static void *kvm_cpu_thread_fn(void *arg)
3530 CPUState *env = arg;
3532 block_io_signals();
3533 qemu_thread_self(env->thread);
3534 if (kvm_enabled())
3535 kvm_init_vcpu(env);
3537 /* signal CPU creation */
3538 qemu_mutex_lock(&qemu_global_mutex);
3539 env->created = 1;
3540 qemu_cond_signal(&qemu_cpu_cond);
3542 /* and wait for machine initialization */
3543 while (!qemu_system_ready)
3544 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3546 while (1) {
3547 if (cpu_can_run(env))
3548 qemu_cpu_exec(env);
3549 qemu_wait_io_event(env);
3552 return NULL;
3555 static void tcg_cpu_exec(void);
3557 static void *tcg_cpu_thread_fn(void *arg)
3559 CPUState *env = arg;
3561 block_io_signals();
3562 qemu_thread_self(env->thread);
3564 /* signal CPU creation */
3565 qemu_mutex_lock(&qemu_global_mutex);
3566 for (env = first_cpu; env != NULL; env = env->next_cpu)
3567 env->created = 1;
3568 qemu_cond_signal(&qemu_cpu_cond);
3570 /* and wait for machine initialization */
3571 while (!qemu_system_ready)
3572 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3574 while (1) {
3575 tcg_cpu_exec();
3576 qemu_wait_io_event(cur_cpu);
3579 return NULL;
3582 void qemu_cpu_kick(void *_env)
3584 CPUState *env = _env;
3585 qemu_cond_broadcast(env->halt_cond);
3586 if (kvm_enabled())
3587 qemu_thread_signal(env->thread, SIGUSR1);
3590 int qemu_cpu_self(void *_env)
3592 CPUState *env = _env;
3593 QemuThread this;
3595 qemu_thread_self(&this);
3597 return qemu_thread_equal(&this, env->thread);
3600 static void cpu_signal(int sig)
3602 if (cpu_single_env)
3603 cpu_exit(cpu_single_env);
3606 static void block_io_signals(void)
3608 sigset_t set;
3609 struct sigaction sigact;
3611 sigemptyset(&set);
3612 sigaddset(&set, SIGUSR2);
3613 sigaddset(&set, SIGIO);
3614 sigaddset(&set, SIGALRM);
3615 pthread_sigmask(SIG_BLOCK, &set, NULL);
3617 sigemptyset(&set);
3618 sigaddset(&set, SIGUSR1);
3619 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3621 memset(&sigact, 0, sizeof(sigact));
3622 sigact.sa_handler = cpu_signal;
3623 sigaction(SIGUSR1, &sigact, NULL);
3626 static void unblock_io_signals(void)
3628 sigset_t set;
3630 sigemptyset(&set);
3631 sigaddset(&set, SIGUSR2);
3632 sigaddset(&set, SIGIO);
3633 sigaddset(&set, SIGALRM);
3634 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3636 sigemptyset(&set);
3637 sigaddset(&set, SIGUSR1);
3638 pthread_sigmask(SIG_BLOCK, &set, NULL);
3641 static void qemu_signal_lock(unsigned int msecs)
3643 qemu_mutex_lock(&qemu_fair_mutex);
3645 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3646 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3647 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3648 break;
3650 qemu_mutex_unlock(&qemu_fair_mutex);
3653 void qemu_mutex_lock_iothread(void)
3655 if (kvm_enabled()) {
3656 qemu_mutex_lock(&qemu_fair_mutex);
3657 qemu_mutex_lock(&qemu_global_mutex);
3658 qemu_mutex_unlock(&qemu_fair_mutex);
3659 } else
3660 qemu_signal_lock(100);
3663 void qemu_mutex_unlock_iothread(void)
3665 qemu_mutex_unlock(&qemu_global_mutex);
3668 static int all_vcpus_paused(void)
3670 CPUState *penv = first_cpu;
3672 while (penv) {
3673 if (!penv->stopped)
3674 return 0;
3675 penv = (CPUState *)penv->next_cpu;
3678 return 1;
3681 static void pause_all_vcpus(void)
3683 CPUState *penv = first_cpu;
3685 while (penv) {
3686 penv->stop = 1;
3687 qemu_thread_signal(penv->thread, SIGUSR1);
3688 qemu_cpu_kick(penv);
3689 penv = (CPUState *)penv->next_cpu;
3692 while (!all_vcpus_paused()) {
3693 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3694 penv = first_cpu;
3695 while (penv) {
3696 qemu_thread_signal(penv->thread, SIGUSR1);
3697 penv = (CPUState *)penv->next_cpu;
3702 static void resume_all_vcpus(void)
3704 CPUState *penv = first_cpu;
3706 while (penv) {
3707 penv->stop = 0;
3708 penv->stopped = 0;
3709 qemu_thread_signal(penv->thread, SIGUSR1);
3710 qemu_cpu_kick(penv);
3711 penv = (CPUState *)penv->next_cpu;
3715 static void tcg_init_vcpu(void *_env)
3717 CPUState *env = _env;
3718 /* share a single thread for all cpus with TCG */
3719 if (!tcg_cpu_thread) {
3720 env->thread = qemu_mallocz(sizeof(QemuThread));
3721 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3722 qemu_cond_init(env->halt_cond);
3723 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3724 while (env->created == 0)
3725 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3726 tcg_cpu_thread = env->thread;
3727 tcg_halt_cond = env->halt_cond;
3728 } else {
3729 env->thread = tcg_cpu_thread;
3730 env->halt_cond = tcg_halt_cond;
3734 static void kvm_start_vcpu(CPUState *env)
3736 env->thread = qemu_mallocz(sizeof(QemuThread));
3737 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3738 qemu_cond_init(env->halt_cond);
3739 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3740 while (env->created == 0)
3741 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3744 void qemu_init_vcpu(void *_env)
3746 CPUState *env = _env;
3748 if (kvm_enabled())
3749 kvm_start_vcpu(env);
3750 else
3751 tcg_init_vcpu(env);
3752 env->nr_cores = smp_cores;
3753 env->nr_threads = smp_threads;
3756 void qemu_notify_event(void)
3758 qemu_event_increment();
3761 void vm_stop(int reason)
3763 QemuThread me;
3764 qemu_thread_self(&me);
3766 if (!qemu_thread_equal(&me, &io_thread)) {
3767 qemu_system_vmstop_request(reason);
3769 * FIXME: should not return to device code in case
3770 * vm_stop() has been requested.
3772 if (cpu_single_env) {
3773 cpu_exit(cpu_single_env);
3774 cpu_single_env->stop = 1;
3776 return;
3778 do_vm_stop(reason);
3781 #endif
3784 #ifdef _WIN32
3785 static void host_main_loop_wait(int *timeout)
3787 int ret, ret2, i;
3788 PollingEntry *pe;
3791 /* XXX: need to suppress polling by better using win32 events */
3792 ret = 0;
3793 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3794 ret |= pe->func(pe->opaque);
3796 if (ret == 0) {
3797 int err;
3798 WaitObjects *w = &wait_objects;
3800 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3801 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3802 if (w->func[ret - WAIT_OBJECT_0])
3803 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3805 /* Check for additional signaled events */
3806 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3808 /* Check if event is signaled */
3809 ret2 = WaitForSingleObject(w->events[i], 0);
3810 if(ret2 == WAIT_OBJECT_0) {
3811 if (w->func[i])
3812 w->func[i](w->opaque[i]);
3813 } else if (ret2 == WAIT_TIMEOUT) {
3814 } else {
3815 err = GetLastError();
3816 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3819 } else if (ret == WAIT_TIMEOUT) {
3820 } else {
3821 err = GetLastError();
3822 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3826 *timeout = 0;
3828 #else
3829 static void host_main_loop_wait(int *timeout)
3832 #endif
3834 void main_loop_wait(int timeout)
3836 IOHandlerRecord *ioh;
3837 fd_set rfds, wfds, xfds;
3838 int ret, nfds;
3839 struct timeval tv;
3841 qemu_bh_update_timeout(&timeout);
3843 host_main_loop_wait(&timeout);
3845 /* poll any events */
3846 /* XXX: separate device handlers from system ones */
3847 nfds = -1;
3848 FD_ZERO(&rfds);
3849 FD_ZERO(&wfds);
3850 FD_ZERO(&xfds);
3851 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3852 if (ioh->deleted)
3853 continue;
3854 if (ioh->fd_read &&
3855 (!ioh->fd_read_poll ||
3856 ioh->fd_read_poll(ioh->opaque) != 0)) {
3857 FD_SET(ioh->fd, &rfds);
3858 if (ioh->fd > nfds)
3859 nfds = ioh->fd;
3861 if (ioh->fd_write) {
3862 FD_SET(ioh->fd, &wfds);
3863 if (ioh->fd > nfds)
3864 nfds = ioh->fd;
3868 tv.tv_sec = timeout / 1000;
3869 tv.tv_usec = (timeout % 1000) * 1000;
3871 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3873 qemu_mutex_unlock_iothread();
3874 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3875 qemu_mutex_lock_iothread();
3876 if (ret > 0) {
3877 IOHandlerRecord **pioh;
3879 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3880 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3881 ioh->fd_read(ioh->opaque);
3883 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3884 ioh->fd_write(ioh->opaque);
3888 /* remove deleted IO handlers */
3889 pioh = &first_io_handler;
3890 while (*pioh) {
3891 ioh = *pioh;
3892 if (ioh->deleted) {
3893 *pioh = ioh->next;
3894 qemu_free(ioh);
3895 } else
3896 pioh = &ioh->next;
3900 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3902 /* rearm timer, if not periodic */
3903 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3904 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3905 qemu_rearm_alarm_timer(alarm_timer);
3908 /* vm time timers */
3909 if (vm_running) {
3910 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3911 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3912 qemu_get_clock(vm_clock));
3915 /* real time timers */
3916 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3917 qemu_get_clock(rt_clock));
3919 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3920 qemu_get_clock(host_clock));
3922 /* Check bottom-halves last in case any of the earlier events triggered
3923 them. */
3924 qemu_bh_poll();
3928 static int qemu_cpu_exec(CPUState *env)
3930 int ret;
3931 #ifdef CONFIG_PROFILER
3932 int64_t ti;
3933 #endif
3935 #ifdef CONFIG_PROFILER
3936 ti = profile_getclock();
3937 #endif
3938 if (use_icount) {
3939 int64_t count;
3940 int decr;
3941 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3942 env->icount_decr.u16.low = 0;
3943 env->icount_extra = 0;
3944 count = qemu_next_deadline();
3945 count = (count + (1 << icount_time_shift) - 1)
3946 >> icount_time_shift;
3947 qemu_icount += count;
3948 decr = (count > 0xffff) ? 0xffff : count;
3949 count -= decr;
3950 env->icount_decr.u16.low = decr;
3951 env->icount_extra = count;
3953 ret = cpu_exec(env);
3954 #ifdef CONFIG_PROFILER
3955 qemu_time += profile_getclock() - ti;
3956 #endif
3957 if (use_icount) {
3958 /* Fold pending instructions back into the
3959 instruction counter, and clear the interrupt flag. */
3960 qemu_icount -= (env->icount_decr.u16.low
3961 + env->icount_extra);
3962 env->icount_decr.u32 = 0;
3963 env->icount_extra = 0;
3965 return ret;
3968 static void tcg_cpu_exec(void)
3970 int ret = 0;
3972 if (next_cpu == NULL)
3973 next_cpu = first_cpu;
3974 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3975 CPUState *env = cur_cpu = next_cpu;
3977 if (!vm_running)
3978 break;
3979 if (timer_alarm_pending) {
3980 timer_alarm_pending = 0;
3981 break;
3983 if (cpu_can_run(env))
3984 ret = qemu_cpu_exec(env);
3985 if (ret == EXCP_DEBUG) {
3986 gdb_set_stop_cpu(env);
3987 debug_requested = 1;
3988 break;
3993 static int cpu_has_work(CPUState *env)
3995 if (env->stop)
3996 return 1;
3997 if (env->stopped)
3998 return 0;
3999 if (!env->halted)
4000 return 1;
4001 if (qemu_cpu_has_work(env))
4002 return 1;
4003 return 0;
4006 static int tcg_has_work(void)
4008 CPUState *env;
4010 for (env = first_cpu; env != NULL; env = env->next_cpu)
4011 if (cpu_has_work(env))
4012 return 1;
4013 return 0;
4016 static int qemu_calculate_timeout(void)
4018 #ifndef CONFIG_IOTHREAD
4019 int timeout;
4021 if (!vm_running)
4022 timeout = 5000;
4023 else if (tcg_has_work())
4024 timeout = 0;
4025 else if (!use_icount)
4026 timeout = 5000;
4027 else {
4028 /* XXX: use timeout computed from timers */
4029 int64_t add;
4030 int64_t delta;
4031 /* Advance virtual time to the next event. */
4032 if (use_icount == 1) {
4033 /* When not using an adaptive execution frequency
4034 we tend to get badly out of sync with real time,
4035 so just delay for a reasonable amount of time. */
4036 delta = 0;
4037 } else {
4038 delta = cpu_get_icount() - cpu_get_clock();
4040 if (delta > 0) {
4041 /* If virtual time is ahead of real time then just
4042 wait for IO. */
4043 timeout = (delta / 1000000) + 1;
4044 } else {
4045 /* Wait for either IO to occur or the next
4046 timer event. */
4047 add = qemu_next_deadline();
4048 /* We advance the timer before checking for IO.
4049 Limit the amount we advance so that early IO
4050 activity won't get the guest too far ahead. */
4051 if (add > 10000000)
4052 add = 10000000;
4053 delta += add;
4054 add = (add + (1 << icount_time_shift) - 1)
4055 >> icount_time_shift;
4056 qemu_icount += add;
4057 timeout = delta / 1000000;
4058 if (timeout < 0)
4059 timeout = 0;
4063 return timeout;
4064 #else /* CONFIG_IOTHREAD */
4065 return 1000;
4066 #endif
4069 static int vm_can_run(void)
4071 if (powerdown_requested)
4072 return 0;
4073 if (reset_requested)
4074 return 0;
4075 if (shutdown_requested)
4076 return 0;
4077 if (debug_requested)
4078 return 0;
4079 return 1;
4082 qemu_irq qemu_system_powerdown;
4084 static void main_loop(void)
4086 int r;
4088 #ifdef CONFIG_IOTHREAD
4089 qemu_system_ready = 1;
4090 qemu_cond_broadcast(&qemu_system_cond);
4091 #endif
4093 for (;;) {
4094 do {
4095 #ifdef CONFIG_PROFILER
4096 int64_t ti;
4097 #endif
4098 #ifndef CONFIG_IOTHREAD
4099 tcg_cpu_exec();
4100 #endif
4101 #ifdef CONFIG_PROFILER
4102 ti = profile_getclock();
4103 #endif
4104 main_loop_wait(qemu_calculate_timeout());
4105 #ifdef CONFIG_PROFILER
4106 dev_time += profile_getclock() - ti;
4107 #endif
4108 } while (vm_can_run());
4110 if (qemu_debug_requested())
4111 vm_stop(EXCP_DEBUG);
4112 if (qemu_shutdown_requested()) {
4113 if (no_shutdown) {
4114 vm_stop(0);
4115 no_shutdown = 0;
4116 } else
4117 break;
4119 if (qemu_reset_requested()) {
4120 pause_all_vcpus();
4121 qemu_system_reset();
4122 resume_all_vcpus();
4124 if (qemu_powerdown_requested()) {
4125 qemu_irq_raise(qemu_system_powerdown);
4127 if ((r = qemu_vmstop_requested()))
4128 vm_stop(r);
4130 pause_all_vcpus();
4133 static void version(void)
4135 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4138 static void help(int exitcode)
4140 version();
4141 printf("usage: %s [options] [disk_image]\n"
4142 "\n"
4143 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4144 "\n"
4145 #define DEF(option, opt_arg, opt_enum, opt_help) \
4146 opt_help
4147 #define DEFHEADING(text) stringify(text) "\n"
4148 #include "qemu-options.h"
4149 #undef DEF
4150 #undef DEFHEADING
4151 #undef GEN_DOCS
4152 "\n"
4153 "During emulation, the following keys are useful:\n"
4154 "ctrl-alt-f toggle full screen\n"
4155 "ctrl-alt-n switch to virtual console 'n'\n"
4156 "ctrl-alt toggle mouse and keyboard grab\n"
4157 "\n"
4158 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4160 "qemu",
4161 DEFAULT_RAM_SIZE,
4162 #ifndef _WIN32
4163 DEFAULT_NETWORK_SCRIPT,
4164 DEFAULT_NETWORK_DOWN_SCRIPT,
4165 #endif
4166 DEFAULT_GDBSTUB_PORT,
4167 "/tmp/qemu.log");
4168 exit(exitcode);
4171 #define HAS_ARG 0x0001
4173 enum {
4174 #define DEF(option, opt_arg, opt_enum, opt_help) \
4175 opt_enum,
4176 #define DEFHEADING(text)
4177 #include "qemu-options.h"
4178 #undef DEF
4179 #undef DEFHEADING
4180 #undef GEN_DOCS
4183 typedef struct QEMUOption {
4184 const char *name;
4185 int flags;
4186 int index;
4187 } QEMUOption;
4189 static const QEMUOption qemu_options[] = {
4190 { "h", 0, QEMU_OPTION_h },
4191 #define DEF(option, opt_arg, opt_enum, opt_help) \
4192 { option, opt_arg, opt_enum },
4193 #define DEFHEADING(text)
4194 #include "qemu-options.h"
4195 #undef DEF
4196 #undef DEFHEADING
4197 #undef GEN_DOCS
4198 { NULL },
4201 #ifdef HAS_AUDIO
4202 struct soundhw soundhw[] = {
4203 #ifdef HAS_AUDIO_CHOICE
4204 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4206 "pcspk",
4207 "PC speaker",
4210 { .init_isa = pcspk_audio_init }
4212 #endif
4214 #ifdef CONFIG_SB16
4216 "sb16",
4217 "Creative Sound Blaster 16",
4220 { .init_isa = SB16_init }
4222 #endif
4224 #ifdef CONFIG_CS4231A
4226 "cs4231a",
4227 "CS4231A",
4230 { .init_isa = cs4231a_init }
4232 #endif
4234 #ifdef CONFIG_ADLIB
4236 "adlib",
4237 #ifdef HAS_YMF262
4238 "Yamaha YMF262 (OPL3)",
4239 #else
4240 "Yamaha YM3812 (OPL2)",
4241 #endif
4244 { .init_isa = Adlib_init }
4246 #endif
4248 #ifdef CONFIG_GUS
4250 "gus",
4251 "Gravis Ultrasound GF1",
4254 { .init_isa = GUS_init }
4256 #endif
4258 #ifdef CONFIG_AC97
4260 "ac97",
4261 "Intel 82801AA AC97 Audio",
4264 { .init_pci = ac97_init }
4266 #endif
4268 #ifdef CONFIG_ES1370
4270 "es1370",
4271 "ENSONIQ AudioPCI ES1370",
4274 { .init_pci = es1370_init }
4276 #endif
4278 #endif /* HAS_AUDIO_CHOICE */
4280 { NULL, NULL, 0, 0, { NULL } }
4283 static void select_soundhw (const char *optarg)
4285 struct soundhw *c;
4287 if (*optarg == '?') {
4288 show_valid_cards:
4290 printf ("Valid sound card names (comma separated):\n");
4291 for (c = soundhw; c->name; ++c) {
4292 printf ("%-11s %s\n", c->name, c->descr);
4294 printf ("\n-soundhw all will enable all of the above\n");
4295 exit (*optarg != '?');
4297 else {
4298 size_t l;
4299 const char *p;
4300 char *e;
4301 int bad_card = 0;
4303 if (!strcmp (optarg, "all")) {
4304 for (c = soundhw; c->name; ++c) {
4305 c->enabled = 1;
4307 return;
4310 p = optarg;
4311 while (*p) {
4312 e = strchr (p, ',');
4313 l = !e ? strlen (p) : (size_t) (e - p);
4315 for (c = soundhw; c->name; ++c) {
4316 if (!strncmp (c->name, p, l) && !c->name[l]) {
4317 c->enabled = 1;
4318 break;
4322 if (!c->name) {
4323 if (l > 80) {
4324 fprintf (stderr,
4325 "Unknown sound card name (too big to show)\n");
4327 else {
4328 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4329 (int) l, p);
4331 bad_card = 1;
4333 p += l + (e != NULL);
4336 if (bad_card)
4337 goto show_valid_cards;
4340 #endif
4342 static void select_vgahw (const char *p)
4344 const char *opts;
4346 vga_interface_type = VGA_NONE;
4347 if (strstart(p, "std", &opts)) {
4348 vga_interface_type = VGA_STD;
4349 } else if (strstart(p, "cirrus", &opts)) {
4350 vga_interface_type = VGA_CIRRUS;
4351 } else if (strstart(p, "vmware", &opts)) {
4352 vga_interface_type = VGA_VMWARE;
4353 } else if (strstart(p, "xenfb", &opts)) {
4354 vga_interface_type = VGA_XENFB;
4355 } else if (!strstart(p, "none", &opts)) {
4356 invalid_vga:
4357 fprintf(stderr, "Unknown vga type: %s\n", p);
4358 exit(1);
4360 while (*opts) {
4361 const char *nextopt;
4363 if (strstart(opts, ",retrace=", &nextopt)) {
4364 opts = nextopt;
4365 if (strstart(opts, "dumb", &nextopt))
4366 vga_retrace_method = VGA_RETRACE_DUMB;
4367 else if (strstart(opts, "precise", &nextopt))
4368 vga_retrace_method = VGA_RETRACE_PRECISE;
4369 else goto invalid_vga;
4370 } else goto invalid_vga;
4371 opts = nextopt;
4375 #ifdef TARGET_I386
4376 static int balloon_parse(const char *arg)
4378 QemuOpts *opts;
4380 if (strcmp(arg, "none") == 0) {
4381 return 0;
4384 if (!strncmp(arg, "virtio", 6)) {
4385 if (arg[6] == ',') {
4386 /* have params -> parse them */
4387 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4388 if (!opts)
4389 return -1;
4390 } else {
4391 /* create empty opts */
4392 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4394 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4395 return 0;
4398 return -1;
4400 #endif
4402 #ifdef _WIN32
4403 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4405 exit(STATUS_CONTROL_C_EXIT);
4406 return TRUE;
4408 #endif
4410 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4412 int ret;
4414 if(strlen(str) != 36)
4415 return -1;
4417 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4418 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4419 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4421 if(ret != 16)
4422 return -1;
4424 #ifdef TARGET_I386
4425 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4426 #endif
4428 return 0;
4431 #ifndef _WIN32
4433 static void termsig_handler(int signal)
4435 qemu_system_shutdown_request();
4438 static void sigchld_handler(int signal)
4440 waitpid(-1, NULL, WNOHANG);
4443 static void sighandler_setup(void)
4445 struct sigaction act;
4447 memset(&act, 0, sizeof(act));
4448 act.sa_handler = termsig_handler;
4449 sigaction(SIGINT, &act, NULL);
4450 sigaction(SIGHUP, &act, NULL);
4451 sigaction(SIGTERM, &act, NULL);
4453 act.sa_handler = sigchld_handler;
4454 act.sa_flags = SA_NOCLDSTOP;
4455 sigaction(SIGCHLD, &act, NULL);
4458 #endif
4460 #ifdef _WIN32
4461 /* Look for support files in the same directory as the executable. */
4462 static char *find_datadir(const char *argv0)
4464 char *p;
4465 char buf[MAX_PATH];
4466 DWORD len;
4468 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4469 if (len == 0) {
4470 return NULL;
4473 buf[len] = 0;
4474 p = buf + len - 1;
4475 while (p != buf && *p != '\\')
4476 p--;
4477 *p = 0;
4478 if (access(buf, R_OK) == 0) {
4479 return qemu_strdup(buf);
4481 return NULL;
4483 #else /* !_WIN32 */
4485 /* Find a likely location for support files using the location of the binary.
4486 For installed binaries this will be "$bindir/../share/qemu". When
4487 running from the build tree this will be "$bindir/../pc-bios". */
4488 #define SHARE_SUFFIX "/share/qemu"
4489 #define BUILD_SUFFIX "/pc-bios"
4490 static char *find_datadir(const char *argv0)
4492 char *dir;
4493 char *p = NULL;
4494 char *res;
4495 char buf[PATH_MAX];
4496 size_t max_len;
4498 #if defined(__linux__)
4500 int len;
4501 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4502 if (len > 0) {
4503 buf[len] = 0;
4504 p = buf;
4507 #elif defined(__FreeBSD__)
4509 int len;
4510 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4511 if (len > 0) {
4512 buf[len] = 0;
4513 p = buf;
4516 #endif
4517 /* If we don't have any way of figuring out the actual executable
4518 location then try argv[0]. */
4519 if (!p) {
4520 p = realpath(argv0, buf);
4521 if (!p) {
4522 return NULL;
4525 dir = dirname(p);
4526 dir = dirname(dir);
4528 max_len = strlen(dir) +
4529 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4530 res = qemu_mallocz(max_len);
4531 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4532 if (access(res, R_OK)) {
4533 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4534 if (access(res, R_OK)) {
4535 qemu_free(res);
4536 res = NULL;
4540 return res;
4542 #undef SHARE_SUFFIX
4543 #undef BUILD_SUFFIX
4544 #endif
4546 char *qemu_find_file(int type, const char *name)
4548 int len;
4549 const char *subdir;
4550 char *buf;
4552 /* If name contains path separators then try it as a straight path. */
4553 if ((strchr(name, '/') || strchr(name, '\\'))
4554 && access(name, R_OK) == 0) {
4555 return qemu_strdup(name);
4557 switch (type) {
4558 case QEMU_FILE_TYPE_BIOS:
4559 subdir = "";
4560 break;
4561 case QEMU_FILE_TYPE_KEYMAP:
4562 subdir = "keymaps/";
4563 break;
4564 default:
4565 abort();
4567 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4568 buf = qemu_mallocz(len);
4569 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4570 if (access(buf, R_OK)) {
4571 qemu_free(buf);
4572 return NULL;
4574 return buf;
4577 static int device_init_func(QemuOpts *opts, void *opaque)
4579 DeviceState *dev;
4581 dev = qdev_device_add(opts);
4582 if (!dev)
4583 return -1;
4584 return 0;
4587 struct device_config {
4588 enum {
4589 DEV_USB, /* -usbdevice */
4590 DEV_BT, /* -bt */
4591 } type;
4592 const char *cmdline;
4593 QTAILQ_ENTRY(device_config) next;
4595 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4597 static void add_device_config(int type, const char *cmdline)
4599 struct device_config *conf;
4601 conf = qemu_mallocz(sizeof(*conf));
4602 conf->type = type;
4603 conf->cmdline = cmdline;
4604 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4607 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4609 struct device_config *conf;
4610 int rc;
4612 QTAILQ_FOREACH(conf, &device_configs, next) {
4613 if (conf->type != type)
4614 continue;
4615 rc = func(conf->cmdline);
4616 if (0 != rc)
4617 return rc;
4619 return 0;
4622 int main(int argc, char **argv, char **envp)
4624 const char *gdbstub_dev = NULL;
4625 uint32_t boot_devices_bitmap = 0;
4626 int i;
4627 int snapshot, linux_boot, net_boot;
4628 const char *initrd_filename;
4629 const char *kernel_filename, *kernel_cmdline;
4630 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4631 DisplayState *ds;
4632 DisplayChangeListener *dcl;
4633 int cyls, heads, secs, translation;
4634 QemuOpts *hda_opts = NULL, *opts;
4635 int optind;
4636 const char *r, *optarg;
4637 CharDriverState *monitor_hds[MAX_MONITOR_DEVICES];
4638 const char *monitor_devices[MAX_MONITOR_DEVICES];
4639 int monitor_device_index;
4640 const char *serial_devices[MAX_SERIAL_PORTS];
4641 int serial_device_index;
4642 const char *parallel_devices[MAX_PARALLEL_PORTS];
4643 int parallel_device_index;
4644 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4645 int virtio_console_index;
4646 const char *loadvm = NULL;
4647 QEMUMachine *machine;
4648 const char *cpu_model;
4649 #ifndef _WIN32
4650 int fds[2];
4651 #endif
4652 int tb_size;
4653 const char *pid_file = NULL;
4654 const char *incoming = NULL;
4655 #ifndef _WIN32
4656 int fd = 0;
4657 struct passwd *pwd = NULL;
4658 const char *chroot_dir = NULL;
4659 const char *run_as = NULL;
4660 #endif
4661 CPUState *env;
4662 int show_vnc_port = 0;
4664 init_clocks();
4666 qemu_errors_to_file(stderr);
4667 qemu_cache_utils_init(envp);
4669 QLIST_INIT (&vm_change_state_head);
4670 #ifndef _WIN32
4672 struct sigaction act;
4673 sigfillset(&act.sa_mask);
4674 act.sa_flags = 0;
4675 act.sa_handler = SIG_IGN;
4676 sigaction(SIGPIPE, &act, NULL);
4678 #else
4679 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4680 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4681 QEMU to run on a single CPU */
4683 HANDLE h;
4684 DWORD mask, smask;
4685 int i;
4686 h = GetCurrentProcess();
4687 if (GetProcessAffinityMask(h, &mask, &smask)) {
4688 for(i = 0; i < 32; i++) {
4689 if (mask & (1 << i))
4690 break;
4692 if (i != 32) {
4693 mask = 1 << i;
4694 SetProcessAffinityMask(h, mask);
4698 #endif
4700 module_call_init(MODULE_INIT_MACHINE);
4701 machine = find_default_machine();
4702 cpu_model = NULL;
4703 initrd_filename = NULL;
4704 ram_size = 0;
4705 snapshot = 0;
4706 kernel_filename = NULL;
4707 kernel_cmdline = "";
4708 cyls = heads = secs = 0;
4709 translation = BIOS_ATA_TRANSLATION_AUTO;
4711 serial_devices[0] = "vc:80Cx24C";
4712 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4713 serial_devices[i] = NULL;
4714 serial_device_index = 0;
4716 parallel_devices[0] = "vc:80Cx24C";
4717 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4718 parallel_devices[i] = NULL;
4719 parallel_device_index = 0;
4721 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4722 virtio_consoles[i] = NULL;
4723 virtio_console_index = 0;
4725 monitor_devices[0] = "vc:80Cx24C";
4726 for (i = 1; i < MAX_MONITOR_DEVICES; i++) {
4727 monitor_devices[i] = NULL;
4729 monitor_device_index = 0;
4731 for (i = 0; i < MAX_NODES; i++) {
4732 node_mem[i] = 0;
4733 node_cpumask[i] = 0;
4736 nb_numa_nodes = 0;
4737 nb_nics = 0;
4739 tb_size = 0;
4740 autostart= 1;
4742 optind = 1;
4743 for(;;) {
4744 if (optind >= argc)
4745 break;
4746 r = argv[optind];
4747 if (r[0] != '-') {
4748 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4749 } else {
4750 const QEMUOption *popt;
4752 optind++;
4753 /* Treat --foo the same as -foo. */
4754 if (r[1] == '-')
4755 r++;
4756 popt = qemu_options;
4757 for(;;) {
4758 if (!popt->name) {
4759 fprintf(stderr, "%s: invalid option -- '%s'\n",
4760 argv[0], r);
4761 exit(1);
4763 if (!strcmp(popt->name, r + 1))
4764 break;
4765 popt++;
4767 if (popt->flags & HAS_ARG) {
4768 if (optind >= argc) {
4769 fprintf(stderr, "%s: option '%s' requires an argument\n",
4770 argv[0], r);
4771 exit(1);
4773 optarg = argv[optind++];
4774 } else {
4775 optarg = NULL;
4778 switch(popt->index) {
4779 case QEMU_OPTION_M:
4780 machine = find_machine(optarg);
4781 if (!machine) {
4782 QEMUMachine *m;
4783 printf("Supported machines are:\n");
4784 for(m = first_machine; m != NULL; m = m->next) {
4785 if (m->alias)
4786 printf("%-10s %s (alias of %s)\n",
4787 m->alias, m->desc, m->name);
4788 printf("%-10s %s%s\n",
4789 m->name, m->desc,
4790 m->is_default ? " (default)" : "");
4792 exit(*optarg != '?');
4794 break;
4795 case QEMU_OPTION_cpu:
4796 /* hw initialization will check this */
4797 if (*optarg == '?') {
4798 /* XXX: implement xxx_cpu_list for targets that still miss it */
4799 #if defined(cpu_list)
4800 cpu_list(stdout, &fprintf);
4801 #endif
4802 exit(0);
4803 } else {
4804 cpu_model = optarg;
4806 break;
4807 case QEMU_OPTION_initrd:
4808 initrd_filename = optarg;
4809 break;
4810 case QEMU_OPTION_hda:
4811 if (cyls == 0)
4812 hda_opts = drive_add(optarg, HD_ALIAS, 0);
4813 else
4814 hda_opts = drive_add(optarg, HD_ALIAS
4815 ",cyls=%d,heads=%d,secs=%d%s",
4816 0, cyls, heads, secs,
4817 translation == BIOS_ATA_TRANSLATION_LBA ?
4818 ",trans=lba" :
4819 translation == BIOS_ATA_TRANSLATION_NONE ?
4820 ",trans=none" : "");
4821 break;
4822 case QEMU_OPTION_hdb:
4823 case QEMU_OPTION_hdc:
4824 case QEMU_OPTION_hdd:
4825 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4826 break;
4827 case QEMU_OPTION_drive:
4828 drive_add(NULL, "%s", optarg);
4829 break;
4830 case QEMU_OPTION_set:
4831 if (qemu_set_option(optarg) != 0)
4832 exit(1);
4833 break;
4834 case QEMU_OPTION_mtdblock:
4835 drive_add(optarg, MTD_ALIAS);
4836 break;
4837 case QEMU_OPTION_sd:
4838 drive_add(optarg, SD_ALIAS);
4839 break;
4840 case QEMU_OPTION_pflash:
4841 drive_add(optarg, PFLASH_ALIAS);
4842 break;
4843 case QEMU_OPTION_snapshot:
4844 snapshot = 1;
4845 break;
4846 case QEMU_OPTION_hdachs:
4848 const char *p;
4849 p = optarg;
4850 cyls = strtol(p, (char **)&p, 0);
4851 if (cyls < 1 || cyls > 16383)
4852 goto chs_fail;
4853 if (*p != ',')
4854 goto chs_fail;
4855 p++;
4856 heads = strtol(p, (char **)&p, 0);
4857 if (heads < 1 || heads > 16)
4858 goto chs_fail;
4859 if (*p != ',')
4860 goto chs_fail;
4861 p++;
4862 secs = strtol(p, (char **)&p, 0);
4863 if (secs < 1 || secs > 63)
4864 goto chs_fail;
4865 if (*p == ',') {
4866 p++;
4867 if (!strcmp(p, "none"))
4868 translation = BIOS_ATA_TRANSLATION_NONE;
4869 else if (!strcmp(p, "lba"))
4870 translation = BIOS_ATA_TRANSLATION_LBA;
4871 else if (!strcmp(p, "auto"))
4872 translation = BIOS_ATA_TRANSLATION_AUTO;
4873 else
4874 goto chs_fail;
4875 } else if (*p != '\0') {
4876 chs_fail:
4877 fprintf(stderr, "qemu: invalid physical CHS format\n");
4878 exit(1);
4880 if (hda_opts != NULL) {
4881 char num[16];
4882 snprintf(num, sizeof(num), "%d", cyls);
4883 qemu_opt_set(hda_opts, "cyls", num);
4884 snprintf(num, sizeof(num), "%d", heads);
4885 qemu_opt_set(hda_opts, "heads", num);
4886 snprintf(num, sizeof(num), "%d", secs);
4887 qemu_opt_set(hda_opts, "secs", num);
4888 if (translation == BIOS_ATA_TRANSLATION_LBA)
4889 qemu_opt_set(hda_opts, "trans", "lba");
4890 if (translation == BIOS_ATA_TRANSLATION_NONE)
4891 qemu_opt_set(hda_opts, "trans", "none");
4894 break;
4895 case QEMU_OPTION_numa:
4896 if (nb_numa_nodes >= MAX_NODES) {
4897 fprintf(stderr, "qemu: too many NUMA nodes\n");
4898 exit(1);
4900 numa_add(optarg);
4901 break;
4902 case QEMU_OPTION_nographic:
4903 display_type = DT_NOGRAPHIC;
4904 break;
4905 #ifdef CONFIG_CURSES
4906 case QEMU_OPTION_curses:
4907 display_type = DT_CURSES;
4908 break;
4909 #endif
4910 case QEMU_OPTION_portrait:
4911 graphic_rotate = 1;
4912 break;
4913 case QEMU_OPTION_kernel:
4914 kernel_filename = optarg;
4915 break;
4916 case QEMU_OPTION_append:
4917 kernel_cmdline = optarg;
4918 break;
4919 case QEMU_OPTION_cdrom:
4920 drive_add(optarg, CDROM_ALIAS);
4921 break;
4922 case QEMU_OPTION_boot:
4924 static const char * const params[] = {
4925 "order", "once", "menu", NULL
4927 char buf[sizeof(boot_devices)];
4928 char *standard_boot_devices;
4929 int legacy = 0;
4931 if (!strchr(optarg, '=')) {
4932 legacy = 1;
4933 pstrcpy(buf, sizeof(buf), optarg);
4934 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4935 fprintf(stderr,
4936 "qemu: unknown boot parameter '%s' in '%s'\n",
4937 buf, optarg);
4938 exit(1);
4941 if (legacy ||
4942 get_param_value(buf, sizeof(buf), "order", optarg)) {
4943 boot_devices_bitmap = parse_bootdevices(buf);
4944 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4946 if (!legacy) {
4947 if (get_param_value(buf, sizeof(buf),
4948 "once", optarg)) {
4949 boot_devices_bitmap |= parse_bootdevices(buf);
4950 standard_boot_devices = qemu_strdup(boot_devices);
4951 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4952 qemu_register_reset(restore_boot_devices,
4953 standard_boot_devices);
4955 if (get_param_value(buf, sizeof(buf),
4956 "menu", optarg)) {
4957 if (!strcmp(buf, "on")) {
4958 boot_menu = 1;
4959 } else if (!strcmp(buf, "off")) {
4960 boot_menu = 0;
4961 } else {
4962 fprintf(stderr,
4963 "qemu: invalid option value '%s'\n",
4964 buf);
4965 exit(1);
4970 break;
4971 case QEMU_OPTION_fda:
4972 case QEMU_OPTION_fdb:
4973 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4974 break;
4975 #ifdef TARGET_I386
4976 case QEMU_OPTION_no_fd_bootchk:
4977 fd_bootchk = 0;
4978 break;
4979 #endif
4980 case QEMU_OPTION_netdev:
4981 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
4982 exit(1);
4984 break;
4985 case QEMU_OPTION_net:
4986 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
4987 exit(1);
4989 break;
4990 #ifdef CONFIG_SLIRP
4991 case QEMU_OPTION_tftp:
4992 legacy_tftp_prefix = optarg;
4993 break;
4994 case QEMU_OPTION_bootp:
4995 legacy_bootp_filename = optarg;
4996 break;
4997 #ifndef _WIN32
4998 case QEMU_OPTION_smb:
4999 if (net_slirp_smb(optarg) < 0)
5000 exit(1);
5001 break;
5002 #endif
5003 case QEMU_OPTION_redir:
5004 if (net_slirp_redir(optarg) < 0)
5005 exit(1);
5006 break;
5007 #endif
5008 case QEMU_OPTION_bt:
5009 add_device_config(DEV_BT, optarg);
5010 break;
5011 #ifdef HAS_AUDIO
5012 case QEMU_OPTION_audio_help:
5013 AUD_help ();
5014 exit (0);
5015 break;
5016 case QEMU_OPTION_soundhw:
5017 select_soundhw (optarg);
5018 break;
5019 #endif
5020 case QEMU_OPTION_h:
5021 help(0);
5022 break;
5023 case QEMU_OPTION_version:
5024 version();
5025 exit(0);
5026 break;
5027 case QEMU_OPTION_m: {
5028 uint64_t value;
5029 char *ptr;
5031 value = strtoul(optarg, &ptr, 10);
5032 switch (*ptr) {
5033 case 0: case 'M': case 'm':
5034 value <<= 20;
5035 break;
5036 case 'G': case 'g':
5037 value <<= 30;
5038 break;
5039 default:
5040 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5041 exit(1);
5044 /* On 32-bit hosts, QEMU is limited by virtual address space */
5045 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5046 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5047 exit(1);
5049 if (value != (uint64_t)(ram_addr_t)value) {
5050 fprintf(stderr, "qemu: ram size too large\n");
5051 exit(1);
5053 ram_size = value;
5054 break;
5056 case QEMU_OPTION_d:
5058 int mask;
5059 const CPULogItem *item;
5061 mask = cpu_str_to_log_mask(optarg);
5062 if (!mask) {
5063 printf("Log items (comma separated):\n");
5064 for(item = cpu_log_items; item->mask != 0; item++) {
5065 printf("%-10s %s\n", item->name, item->help);
5067 exit(1);
5069 cpu_set_log(mask);
5071 break;
5072 case QEMU_OPTION_s:
5073 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5074 break;
5075 case QEMU_OPTION_gdb:
5076 gdbstub_dev = optarg;
5077 break;
5078 case QEMU_OPTION_L:
5079 data_dir = optarg;
5080 break;
5081 case QEMU_OPTION_bios:
5082 bios_name = optarg;
5083 break;
5084 case QEMU_OPTION_singlestep:
5085 singlestep = 1;
5086 break;
5087 case QEMU_OPTION_S:
5088 autostart = 0;
5089 break;
5090 #ifndef _WIN32
5091 case QEMU_OPTION_k:
5092 keyboard_layout = optarg;
5093 break;
5094 #endif
5095 case QEMU_OPTION_localtime:
5096 rtc_utc = 0;
5097 break;
5098 case QEMU_OPTION_vga:
5099 select_vgahw (optarg);
5100 break;
5101 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5102 case QEMU_OPTION_g:
5104 const char *p;
5105 int w, h, depth;
5106 p = optarg;
5107 w = strtol(p, (char **)&p, 10);
5108 if (w <= 0) {
5109 graphic_error:
5110 fprintf(stderr, "qemu: invalid resolution or depth\n");
5111 exit(1);
5113 if (*p != 'x')
5114 goto graphic_error;
5115 p++;
5116 h = strtol(p, (char **)&p, 10);
5117 if (h <= 0)
5118 goto graphic_error;
5119 if (*p == 'x') {
5120 p++;
5121 depth = strtol(p, (char **)&p, 10);
5122 if (depth != 8 && depth != 15 && depth != 16 &&
5123 depth != 24 && depth != 32)
5124 goto graphic_error;
5125 } else if (*p == '\0') {
5126 depth = graphic_depth;
5127 } else {
5128 goto graphic_error;
5131 graphic_width = w;
5132 graphic_height = h;
5133 graphic_depth = depth;
5135 break;
5136 #endif
5137 case QEMU_OPTION_echr:
5139 char *r;
5140 term_escape_char = strtol(optarg, &r, 0);
5141 if (r == optarg)
5142 printf("Bad argument to echr\n");
5143 break;
5145 case QEMU_OPTION_monitor:
5146 if (monitor_device_index >= MAX_MONITOR_DEVICES) {
5147 fprintf(stderr, "qemu: too many monitor devices\n");
5148 exit(1);
5150 monitor_devices[monitor_device_index] = optarg;
5151 monitor_device_index++;
5152 break;
5153 case QEMU_OPTION_chardev:
5154 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5155 if (!opts) {
5156 fprintf(stderr, "parse error: %s\n", optarg);
5157 exit(1);
5159 if (qemu_chr_open_opts(opts, NULL) == NULL) {
5160 exit(1);
5162 break;
5163 case QEMU_OPTION_serial:
5164 if (serial_device_index >= MAX_SERIAL_PORTS) {
5165 fprintf(stderr, "qemu: too many serial ports\n");
5166 exit(1);
5168 serial_devices[serial_device_index] = optarg;
5169 serial_device_index++;
5170 break;
5171 case QEMU_OPTION_watchdog:
5172 if (watchdog) {
5173 fprintf(stderr,
5174 "qemu: only one watchdog option may be given\n");
5175 return 1;
5177 watchdog = optarg;
5178 break;
5179 case QEMU_OPTION_watchdog_action:
5180 if (select_watchdog_action(optarg) == -1) {
5181 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5182 exit(1);
5184 break;
5185 case QEMU_OPTION_virtiocon:
5186 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5187 fprintf(stderr, "qemu: too many virtio consoles\n");
5188 exit(1);
5190 virtio_consoles[virtio_console_index] = optarg;
5191 virtio_console_index++;
5192 break;
5193 case QEMU_OPTION_parallel:
5194 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5195 fprintf(stderr, "qemu: too many parallel ports\n");
5196 exit(1);
5198 parallel_devices[parallel_device_index] = optarg;
5199 parallel_device_index++;
5200 break;
5201 case QEMU_OPTION_loadvm:
5202 loadvm = optarg;
5203 break;
5204 case QEMU_OPTION_full_screen:
5205 full_screen = 1;
5206 break;
5207 #ifdef CONFIG_SDL
5208 case QEMU_OPTION_no_frame:
5209 no_frame = 1;
5210 break;
5211 case QEMU_OPTION_alt_grab:
5212 alt_grab = 1;
5213 break;
5214 case QEMU_OPTION_ctrl_grab:
5215 ctrl_grab = 1;
5216 break;
5217 case QEMU_OPTION_no_quit:
5218 no_quit = 1;
5219 break;
5220 case QEMU_OPTION_sdl:
5221 display_type = DT_SDL;
5222 break;
5223 #endif
5224 case QEMU_OPTION_pidfile:
5225 pid_file = optarg;
5226 break;
5227 #ifdef TARGET_I386
5228 case QEMU_OPTION_win2k_hack:
5229 win2k_install_hack = 1;
5230 break;
5231 case QEMU_OPTION_rtc_td_hack:
5232 rtc_td_hack = 1;
5233 break;
5234 case QEMU_OPTION_acpitable:
5235 if(acpi_table_add(optarg) < 0) {
5236 fprintf(stderr, "Wrong acpi table provided\n");
5237 exit(1);
5239 break;
5240 case QEMU_OPTION_smbios:
5241 if(smbios_entry_add(optarg) < 0) {
5242 fprintf(stderr, "Wrong smbios provided\n");
5243 exit(1);
5245 break;
5246 #endif
5247 #ifdef CONFIG_KVM
5248 case QEMU_OPTION_enable_kvm:
5249 kvm_allowed = 1;
5250 break;
5251 #endif
5252 case QEMU_OPTION_usb:
5253 usb_enabled = 1;
5254 break;
5255 case QEMU_OPTION_usbdevice:
5256 usb_enabled = 1;
5257 add_device_config(DEV_USB, optarg);
5258 break;
5259 case QEMU_OPTION_device:
5260 if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5261 exit(1);
5263 break;
5264 case QEMU_OPTION_smp:
5265 smp_parse(optarg);
5266 if (smp_cpus < 1) {
5267 fprintf(stderr, "Invalid number of CPUs\n");
5268 exit(1);
5270 if (max_cpus < smp_cpus) {
5271 fprintf(stderr, "maxcpus must be equal to or greater than "
5272 "smp\n");
5273 exit(1);
5275 if (max_cpus > 255) {
5276 fprintf(stderr, "Unsupported number of maxcpus\n");
5277 exit(1);
5279 break;
5280 case QEMU_OPTION_vnc:
5281 display_type = DT_VNC;
5282 vnc_display = optarg;
5283 break;
5284 #ifdef TARGET_I386
5285 case QEMU_OPTION_no_acpi:
5286 acpi_enabled = 0;
5287 break;
5288 case QEMU_OPTION_no_hpet:
5289 no_hpet = 1;
5290 break;
5291 case QEMU_OPTION_balloon:
5292 if (balloon_parse(optarg) < 0) {
5293 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5294 exit(1);
5296 break;
5297 #endif
5298 case QEMU_OPTION_no_reboot:
5299 no_reboot = 1;
5300 break;
5301 case QEMU_OPTION_no_shutdown:
5302 no_shutdown = 1;
5303 break;
5304 case QEMU_OPTION_show_cursor:
5305 cursor_hide = 0;
5306 break;
5307 case QEMU_OPTION_uuid:
5308 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5309 fprintf(stderr, "Fail to parse UUID string."
5310 " Wrong format.\n");
5311 exit(1);
5313 break;
5314 #ifndef _WIN32
5315 case QEMU_OPTION_daemonize:
5316 daemonize = 1;
5317 break;
5318 #endif
5319 case QEMU_OPTION_option_rom:
5320 if (nb_option_roms >= MAX_OPTION_ROMS) {
5321 fprintf(stderr, "Too many option ROMs\n");
5322 exit(1);
5324 option_rom[nb_option_roms] = optarg;
5325 nb_option_roms++;
5326 break;
5327 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5328 case QEMU_OPTION_semihosting:
5329 semihosting_enabled = 1;
5330 break;
5331 #endif
5332 case QEMU_OPTION_name:
5333 qemu_name = qemu_strdup(optarg);
5335 char *p = strchr(qemu_name, ',');
5336 if (p != NULL) {
5337 *p++ = 0;
5338 if (strncmp(p, "process=", 8)) {
5339 fprintf(stderr, "Unknown subargument %s to -name", p);
5340 exit(1);
5342 p += 8;
5343 set_proc_name(p);
5346 break;
5347 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5348 case QEMU_OPTION_prom_env:
5349 if (nb_prom_envs >= MAX_PROM_ENVS) {
5350 fprintf(stderr, "Too many prom variables\n");
5351 exit(1);
5353 prom_envs[nb_prom_envs] = optarg;
5354 nb_prom_envs++;
5355 break;
5356 #endif
5357 #ifdef TARGET_ARM
5358 case QEMU_OPTION_old_param:
5359 old_param = 1;
5360 break;
5361 #endif
5362 case QEMU_OPTION_clock:
5363 configure_alarms(optarg);
5364 break;
5365 case QEMU_OPTION_startdate:
5366 configure_rtc_date_offset(optarg, 1);
5367 break;
5368 case QEMU_OPTION_rtc:
5369 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5370 if (!opts) {
5371 fprintf(stderr, "parse error: %s\n", optarg);
5372 exit(1);
5374 configure_rtc(opts);
5375 break;
5376 case QEMU_OPTION_tb_size:
5377 tb_size = strtol(optarg, NULL, 0);
5378 if (tb_size < 0)
5379 tb_size = 0;
5380 break;
5381 case QEMU_OPTION_icount:
5382 use_icount = 1;
5383 if (strcmp(optarg, "auto") == 0) {
5384 icount_time_shift = -1;
5385 } else {
5386 icount_time_shift = strtol(optarg, NULL, 0);
5388 break;
5389 case QEMU_OPTION_incoming:
5390 incoming = optarg;
5391 break;
5392 #ifndef _WIN32
5393 case QEMU_OPTION_chroot:
5394 chroot_dir = optarg;
5395 break;
5396 case QEMU_OPTION_runas:
5397 run_as = optarg;
5398 break;
5399 #endif
5400 #ifdef CONFIG_XEN
5401 case QEMU_OPTION_xen_domid:
5402 xen_domid = atoi(optarg);
5403 break;
5404 case QEMU_OPTION_xen_create:
5405 xen_mode = XEN_CREATE;
5406 break;
5407 case QEMU_OPTION_xen_attach:
5408 xen_mode = XEN_ATTACH;
5409 break;
5410 #endif
5415 /* If no data_dir is specified then try to find it relative to the
5416 executable path. */
5417 if (!data_dir) {
5418 data_dir = find_datadir(argv[0]);
5420 /* If all else fails use the install patch specified when building. */
5421 if (!data_dir) {
5422 data_dir = CONFIG_QEMU_SHAREDIR;
5426 * Default to max_cpus = smp_cpus, in case the user doesn't
5427 * specify a max_cpus value.
5429 if (!max_cpus)
5430 max_cpus = smp_cpus;
5432 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5433 if (smp_cpus > machine->max_cpus) {
5434 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5435 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5436 machine->max_cpus);
5437 exit(1);
5440 if (display_type == DT_NOGRAPHIC) {
5441 if (serial_device_index == 0)
5442 serial_devices[0] = "stdio";
5443 if (parallel_device_index == 0)
5444 parallel_devices[0] = "null";
5445 if (strncmp(monitor_devices[0], "vc", 2) == 0) {
5446 monitor_devices[0] = "stdio";
5450 #ifndef _WIN32
5451 if (daemonize) {
5452 pid_t pid;
5454 if (pipe(fds) == -1)
5455 exit(1);
5457 pid = fork();
5458 if (pid > 0) {
5459 uint8_t status;
5460 ssize_t len;
5462 close(fds[1]);
5464 again:
5465 len = read(fds[0], &status, 1);
5466 if (len == -1 && (errno == EINTR))
5467 goto again;
5469 if (len != 1)
5470 exit(1);
5471 else if (status == 1) {
5472 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5473 exit(1);
5474 } else
5475 exit(0);
5476 } else if (pid < 0)
5477 exit(1);
5479 setsid();
5481 pid = fork();
5482 if (pid > 0)
5483 exit(0);
5484 else if (pid < 0)
5485 exit(1);
5487 umask(027);
5489 signal(SIGTSTP, SIG_IGN);
5490 signal(SIGTTOU, SIG_IGN);
5491 signal(SIGTTIN, SIG_IGN);
5494 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5495 if (daemonize) {
5496 uint8_t status = 1;
5497 write(fds[1], &status, 1);
5498 } else
5499 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5500 exit(1);
5502 #endif
5504 if (kvm_enabled()) {
5505 int ret;
5507 ret = kvm_init(smp_cpus);
5508 if (ret < 0) {
5509 fprintf(stderr, "failed to initialize KVM\n");
5510 exit(1);
5514 if (qemu_init_main_loop()) {
5515 fprintf(stderr, "qemu_init_main_loop failed\n");
5516 exit(1);
5518 linux_boot = (kernel_filename != NULL);
5520 if (!linux_boot && *kernel_cmdline != '\0') {
5521 fprintf(stderr, "-append only allowed with -kernel option\n");
5522 exit(1);
5525 if (!linux_boot && initrd_filename != NULL) {
5526 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5527 exit(1);
5530 #ifndef _WIN32
5531 /* Win32 doesn't support line-buffering and requires size >= 2 */
5532 setvbuf(stdout, NULL, _IOLBF, 0);
5533 #endif
5535 if (init_timer_alarm() < 0) {
5536 fprintf(stderr, "could not initialize alarm timer\n");
5537 exit(1);
5539 if (use_icount && icount_time_shift < 0) {
5540 use_icount = 2;
5541 /* 125MIPS seems a reasonable initial guess at the guest speed.
5542 It will be corrected fairly quickly anyway. */
5543 icount_time_shift = 3;
5544 init_icount_adjust();
5547 #ifdef _WIN32
5548 socket_init();
5549 #endif
5551 if (net_init_clients() < 0) {
5552 exit(1);
5555 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5556 net_set_boot_mask(net_boot);
5558 /* init the bluetooth world */
5559 if (foreach_device_config(DEV_BT, bt_parse))
5560 exit(1);
5562 /* init the memory */
5563 if (ram_size == 0)
5564 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5566 /* init the dynamic translator */
5567 cpu_exec_init_all(tb_size * 1024 * 1024);
5569 bdrv_init();
5571 /* we always create the cdrom drive, even if no disk is there */
5572 drive_add(NULL, CDROM_ALIAS);
5574 /* we always create at least one floppy */
5575 drive_add(NULL, FD_ALIAS, 0);
5577 /* we always create one sd slot, even if no card is in it */
5578 drive_add(NULL, SD_ALIAS);
5580 /* open the virtual block devices */
5581 if (snapshot)
5582 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5583 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5584 exit(1);
5586 vmstate_register(0, &vmstate_timers ,&timers_state);
5587 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5589 /* Maintain compatibility with multiple stdio monitors */
5590 if (!strcmp(monitor_devices[0],"stdio")) {
5591 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5592 const char *devname = serial_devices[i];
5593 if (devname && !strcmp(devname,"mon:stdio")) {
5594 monitor_devices[0] = NULL;
5595 break;
5596 } else if (devname && !strcmp(devname,"stdio")) {
5597 monitor_devices[0] = NULL;
5598 serial_devices[i] = "mon:stdio";
5599 break;
5604 if (nb_numa_nodes > 0) {
5605 int i;
5607 if (nb_numa_nodes > smp_cpus) {
5608 nb_numa_nodes = smp_cpus;
5611 /* If no memory size if given for any node, assume the default case
5612 * and distribute the available memory equally across all nodes
5614 for (i = 0; i < nb_numa_nodes; i++) {
5615 if (node_mem[i] != 0)
5616 break;
5618 if (i == nb_numa_nodes) {
5619 uint64_t usedmem = 0;
5621 /* On Linux, the each node's border has to be 8MB aligned,
5622 * the final node gets the rest.
5624 for (i = 0; i < nb_numa_nodes - 1; i++) {
5625 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5626 usedmem += node_mem[i];
5628 node_mem[i] = ram_size - usedmem;
5631 for (i = 0; i < nb_numa_nodes; i++) {
5632 if (node_cpumask[i] != 0)
5633 break;
5635 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5636 * must cope with this anyway, because there are BIOSes out there in
5637 * real machines which also use this scheme.
5639 if (i == nb_numa_nodes) {
5640 for (i = 0; i < smp_cpus; i++) {
5641 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5646 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5647 const char *devname = monitor_devices[i];
5648 if (devname && strcmp(devname, "none")) {
5649 char label[32];
5650 if (i == 0) {
5651 snprintf(label, sizeof(label), "monitor");
5652 } else {
5653 snprintf(label, sizeof(label), "monitor%d", i);
5655 monitor_hds[i] = qemu_chr_open(label, devname, NULL);
5656 if (!monitor_hds[i]) {
5657 fprintf(stderr, "qemu: could not open monitor device '%s'\n",
5658 devname);
5659 exit(1);
5664 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5665 const char *devname = serial_devices[i];
5666 if (devname && strcmp(devname, "none")) {
5667 char label[32];
5668 snprintf(label, sizeof(label), "serial%d", i);
5669 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5670 if (!serial_hds[i]) {
5671 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
5672 devname, strerror(errno));
5673 exit(1);
5678 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5679 const char *devname = parallel_devices[i];
5680 if (devname && strcmp(devname, "none")) {
5681 char label[32];
5682 snprintf(label, sizeof(label), "parallel%d", i);
5683 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5684 if (!parallel_hds[i]) {
5685 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
5686 devname, strerror(errno));
5687 exit(1);
5692 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5693 const char *devname = virtio_consoles[i];
5694 if (devname && strcmp(devname, "none")) {
5695 char label[32];
5696 snprintf(label, sizeof(label), "virtcon%d", i);
5697 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5698 if (!virtcon_hds[i]) {
5699 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
5700 devname, strerror(errno));
5701 exit(1);
5706 module_call_init(MODULE_INIT_DEVICE);
5708 if (watchdog) {
5709 i = select_watchdog(watchdog);
5710 if (i > 0)
5711 exit (i == 1 ? 1 : 0);
5714 if (machine->compat_props) {
5715 qdev_prop_register_compat(machine->compat_props);
5717 machine->init(ram_size, boot_devices,
5718 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5721 #ifndef _WIN32
5722 /* must be after terminal init, SDL library changes signal handlers */
5723 sighandler_setup();
5724 #endif
5726 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5727 for (i = 0; i < nb_numa_nodes; i++) {
5728 if (node_cpumask[i] & (1 << env->cpu_index)) {
5729 env->numa_node = i;
5734 current_machine = machine;
5736 /* init USB devices */
5737 if (usb_enabled) {
5738 if (foreach_device_config(DEV_USB, usb_parse) < 0)
5739 exit(1);
5742 /* init generic devices */
5743 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5744 exit(1);
5746 if (!display_state)
5747 dumb_display_init();
5748 /* just use the first displaystate for the moment */
5749 ds = display_state;
5751 if (display_type == DT_DEFAULT) {
5752 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5753 display_type = DT_SDL;
5754 #else
5755 display_type = DT_VNC;
5756 vnc_display = "localhost:0,to=99";
5757 show_vnc_port = 1;
5758 #endif
5762 switch (display_type) {
5763 case DT_NOGRAPHIC:
5764 break;
5765 #if defined(CONFIG_CURSES)
5766 case DT_CURSES:
5767 curses_display_init(ds, full_screen);
5768 break;
5769 #endif
5770 #if defined(CONFIG_SDL)
5771 case DT_SDL:
5772 sdl_display_init(ds, full_screen, no_frame);
5773 break;
5774 #elif defined(CONFIG_COCOA)
5775 case DT_SDL:
5776 cocoa_display_init(ds, full_screen);
5777 break;
5778 #endif
5779 case DT_VNC:
5780 vnc_display_init(ds);
5781 if (vnc_display_open(ds, vnc_display) < 0)
5782 exit(1);
5784 if (show_vnc_port) {
5785 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5787 break;
5788 default:
5789 break;
5791 dpy_resize(ds);
5793 dcl = ds->listeners;
5794 while (dcl != NULL) {
5795 if (dcl->dpy_refresh != NULL) {
5796 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5797 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5799 dcl = dcl->next;
5802 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5803 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5804 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5807 text_consoles_set_display(display_state);
5808 qemu_chr_initial_reset();
5810 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5811 if (monitor_devices[i] && monitor_hds[i]) {
5812 monitor_init(monitor_hds[i],
5813 MONITOR_USE_READLINE |
5814 ((i == 0) ? MONITOR_IS_DEFAULT : 0));
5818 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5819 const char *devname = serial_devices[i];
5820 if (devname && strcmp(devname, "none")) {
5821 if (strstart(devname, "vc", 0))
5822 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5826 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5827 const char *devname = parallel_devices[i];
5828 if (devname && strcmp(devname, "none")) {
5829 if (strstart(devname, "vc", 0))
5830 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5834 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5835 const char *devname = virtio_consoles[i];
5836 if (virtcon_hds[i] && devname) {
5837 if (strstart(devname, "vc", 0))
5838 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5842 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5843 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5844 gdbstub_dev);
5845 exit(1);
5848 qdev_machine_creation_done();
5850 rom_load_all();
5852 if (loadvm) {
5853 if (load_vmstate(cur_mon, loadvm) < 0) {
5854 autostart = 0;
5858 if (incoming) {
5859 qemu_start_incoming_migration(incoming);
5860 } else if (autostart) {
5861 vm_start();
5864 #ifndef _WIN32
5865 if (daemonize) {
5866 uint8_t status = 0;
5867 ssize_t len;
5869 again1:
5870 len = write(fds[1], &status, 1);
5871 if (len == -1 && (errno == EINTR))
5872 goto again1;
5874 if (len != 1)
5875 exit(1);
5877 chdir("/");
5878 TFR(fd = open("/dev/null", O_RDWR));
5879 if (fd == -1)
5880 exit(1);
5883 if (run_as) {
5884 pwd = getpwnam(run_as);
5885 if (!pwd) {
5886 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5887 exit(1);
5891 if (chroot_dir) {
5892 if (chroot(chroot_dir) < 0) {
5893 fprintf(stderr, "chroot failed\n");
5894 exit(1);
5896 chdir("/");
5899 if (run_as) {
5900 if (setgid(pwd->pw_gid) < 0) {
5901 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5902 exit(1);
5904 if (setuid(pwd->pw_uid) < 0) {
5905 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5906 exit(1);
5908 if (setuid(0) != -1) {
5909 fprintf(stderr, "Dropping privileges failed\n");
5910 exit(1);
5914 if (daemonize) {
5915 dup2(fd, 0);
5916 dup2(fd, 1);
5917 dup2(fd, 2);
5919 close(fd);
5921 #endif
5923 main_loop();
5924 quit_timers();
5925 net_cleanup();
5927 return 0;