replace qemu_kvm_cpu_env
[qemu-kvm/fedora.git] / vl.c
blobb3df596df7c4c99ab66e585d973ffd500455649a
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 HOST_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 #if defined(__NetBSD__)
48 #include <net/if_tap.h>
49 #endif
50 #ifdef __linux__
51 #include <linux/if_tun.h>
52 #endif
53 #include <arpa/inet.h>
54 #include <dirent.h>
55 #include <netdb.h>
56 #include <sys/select.h>
57 #ifdef HOST_BSD
58 #include <sys/stat.h>
59 #if defined(__FreeBSD__) || defined(__DragonFly__)
60 #include <libutil.h>
61 #else
62 #include <util.h>
63 #endif
64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65 #include <freebsd/stdlib.h>
66 #else
67 #ifdef __linux__
68 #include <pty.h>
69 #include <malloc.h>
70 #include <linux/rtc.h>
71 #include <sys/prctl.h>
73 /* For the benefit of older linux systems which don't supply it,
74 we use a local copy of hpet.h. */
75 /* #include <linux/hpet.h> */
76 #include "hpet.h"
78 #include <linux/ppdev.h>
79 #include <linux/parport.h>
80 #endif
81 #ifdef __sun__
82 #include <sys/stat.h>
83 #include <sys/ethernet.h>
84 #include <sys/sockio.h>
85 #include <netinet/arp.h>
86 #include <netinet/in.h>
87 #include <netinet/in_systm.h>
88 #include <netinet/ip.h>
89 #include <netinet/ip_icmp.h> // must come after ip.h
90 #include <netinet/udp.h>
91 #include <netinet/tcp.h>
92 #include <net/if.h>
93 #include <syslog.h>
94 #include <stropts.h>
95 #endif
96 #endif
97 #endif
99 #if defined(__OpenBSD__)
100 #include <util.h>
101 #endif
103 #if defined(CONFIG_VDE)
104 #include <libvdeplug.h>
105 #endif
107 #ifdef _WIN32
108 #include <windows.h>
109 #include <malloc.h>
110 #include <sys/timeb.h>
111 #include <mmsystem.h>
112 #define getopt_long_only getopt_long
113 #define memalign(align, size) malloc(size)
114 #endif
116 #ifdef CONFIG_SDL
117 #if defined(__APPLE__) || defined(main)
118 #include <SDL.h>
119 int qemu_main(int argc, char **argv, char **envp);
120 int main(int argc, char **argv)
122 return qemu_main(argc, argv, NULL);
124 #undef main
125 #define main qemu_main
126 #endif
127 #endif /* CONFIG_SDL */
129 #ifdef CONFIG_COCOA
130 #undef main
131 #define main qemu_main
132 #endif /* CONFIG_COCOA */
134 #include "hw/hw.h"
135 #include "hw/boards.h"
136 #include "hw/usb.h"
137 #include "hw/pcmcia.h"
138 #include "hw/pc.h"
139 #include "hw/audiodev.h"
140 #include "hw/isa.h"
141 #include "hw/baum.h"
142 #include "hw/bt.h"
143 #include "hw/watchdog.h"
144 #include "hw/smbios.h"
145 #include "hw/xen.h"
146 #include "bt-host.h"
147 #include "net.h"
148 #include "monitor.h"
149 #include "console.h"
150 #include "sysemu.h"
151 #include "gdbstub.h"
152 #include "qemu-timer.h"
153 #include "qemu-char.h"
154 #include "cache-utils.h"
155 #include "block.h"
156 #include "dma.h"
157 #include "audio/audio.h"
158 #include "migration.h"
159 #include "kvm.h"
160 #include "balloon.h"
161 #include "qemu-option.h"
162 #include "qemu-kvm.h"
163 #include "hw/device-assignment.h"
165 #include "disas.h"
167 #include "exec-all.h"
169 #include "qemu_socket.h"
171 #include "slirp/libslirp.h"
173 //#define DEBUG_NET
174 //#define DEBUG_SLIRP
176 #define DEFAULT_RAM_SIZE 128
178 /* Max number of USB devices that can be specified on the commandline. */
179 #define MAX_USB_CMDLINE 8
181 /* Max number of bluetooth switches on the commandline. */
182 #define MAX_BT_CMDLINE 10
184 static const char *data_dir;
185 const char *bios_name = NULL;
186 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
187 to store the VM snapshots */
188 DriveInfo drives_table[MAX_DRIVES+1];
189 int nb_drives;
190 int extboot_drive = -1;
191 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
192 static DisplayState *display_state;
193 DisplayType display_type = DT_DEFAULT;
194 const char* keyboard_layout = NULL;
195 int64_t ticks_per_sec;
196 ram_addr_t ram_size;
197 int nb_nics;
198 NICInfo nd_table[MAX_NICS];
199 int vm_running;
200 static int autostart;
201 static int rtc_utc = 1;
202 static int rtc_date_offset = -1; /* -1 means no change */
203 int cirrus_vga_enabled = 1;
204 int std_vga_enabled = 0;
205 int vmsvga_enabled = 0;
206 int xenfb_enabled = 0;
207 #ifdef TARGET_SPARC
208 int graphic_width = 1024;
209 int graphic_height = 768;
210 int graphic_depth = 8;
211 #else
212 int graphic_width = 800;
213 int graphic_height = 600;
214 int graphic_depth = 15;
215 #endif
216 static int full_screen = 0;
217 #ifdef CONFIG_SDL
218 static int no_frame = 0;
219 #endif
220 int no_quit = 0;
221 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
222 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
223 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
224 #ifdef TARGET_I386
225 int win2k_install_hack = 0;
226 int rtc_td_hack = 0;
227 #endif
228 int usb_enabled = 0;
229 int singlestep = 0;
230 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
231 int assigned_devices_index;
232 int smp_cpus = 1;
233 const char *vnc_display;
234 int acpi_enabled = 1;
235 #ifdef TARGET_I386
236 int no_hpet = 0;
237 #endif
238 int virtio_balloon = 1;
239 const char *virtio_balloon_devaddr;
240 int fd_bootchk = 1;
241 int no_reboot = 0;
242 int no_shutdown = 0;
243 int cursor_hide = 1;
244 int graphic_rotate = 0;
245 uint8_t irq0override = 1;
246 #ifndef _WIN32
247 int daemonize = 0;
248 #endif
249 WatchdogTimerModel *watchdog = NULL;
250 int watchdog_action = WDT_RESET;
251 const char *option_rom[MAX_OPTION_ROMS];
252 int nb_option_roms;
253 int semihosting_enabled = 0;
254 int time_drift_fix = 0;
255 unsigned int kvm_shadow_memory = 0;
256 const char *mem_path = NULL;
257 #ifdef MAP_POPULATE
258 int mem_prealloc = 1; /* force preallocation of physical target memory */
259 #endif
260 #ifdef TARGET_ARM
261 int old_param = 0;
262 #endif
263 const char *qemu_name;
264 int alt_grab = 0;
265 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
266 unsigned int nb_prom_envs = 0;
267 const char *prom_envs[MAX_PROM_ENVS];
268 #endif
269 int nb_drives_opt;
270 const char *nvram = NULL;
271 struct drive_opt drives_opt[MAX_DRIVES];
273 int nb_numa_nodes;
274 uint64_t node_mem[MAX_NODES];
275 uint64_t node_cpumask[MAX_NODES];
277 static CPUState *cur_cpu;
278 static CPUState *next_cpu;
279 static int timer_alarm_pending = 1;
280 /* Conversion factor from emulated instructions to virtual clock ticks. */
281 static int icount_time_shift;
282 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
283 #define MAX_ICOUNT_SHIFT 10
284 /* Compensate for varying guest execution speed. */
285 static int64_t qemu_icount_bias;
286 static QEMUTimer *icount_rt_timer;
287 static QEMUTimer *icount_vm_timer;
288 static QEMUTimer *nographic_timer;
290 uint8_t qemu_uuid[16];
292 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
293 struct timeval *tv)
295 int ret;
297 /* KVM holds a mutex while QEMU code is running, we need hooks to
298 release the mutex whenever QEMU code sleeps. */
300 kvm_sleep_begin();
302 ret = select(max_fd, rfds, wfds, xfds, tv);
304 kvm_sleep_end();
306 return ret;
310 /***********************************************************/
311 /* x86 ISA bus support */
313 target_phys_addr_t isa_mem_base = 0;
314 PicState2 *isa_pic;
316 /***********************************************************/
317 void hw_error(const char *fmt, ...)
319 va_list ap;
320 CPUState *env;
322 va_start(ap, fmt);
323 fprintf(stderr, "qemu: hardware error: ");
324 vfprintf(stderr, fmt, ap);
325 fprintf(stderr, "\n");
326 for(env = first_cpu; env != NULL; env = env->next_cpu) {
327 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
328 #ifdef TARGET_I386
329 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
330 #else
331 cpu_dump_state(env, stderr, fprintf, 0);
332 #endif
334 va_end(ap);
335 abort();
338 static void set_proc_name(const char *s)
340 #ifdef __linux__
341 char name[16];
342 if (!s)
343 return;
344 name[sizeof(name) - 1] = 0;
345 strncpy(name, s, sizeof(name));
346 /* Could rewrite argv[0] too, but that's a bit more complicated.
347 This simple way is enough for `top'. */
348 prctl(PR_SET_NAME, name);
349 #endif
352 /***************/
353 /* ballooning */
355 static QEMUBalloonEvent *qemu_balloon_event;
356 void *qemu_balloon_event_opaque;
358 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
360 qemu_balloon_event = func;
361 qemu_balloon_event_opaque = opaque;
364 void qemu_balloon(ram_addr_t target)
366 if (qemu_balloon_event)
367 qemu_balloon_event(qemu_balloon_event_opaque, target);
370 ram_addr_t qemu_balloon_status(void)
372 if (qemu_balloon_event)
373 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
374 return 0;
377 /***********************************************************/
378 /* keyboard/mouse */
380 static QEMUPutKBDEvent *qemu_put_kbd_event;
381 static void *qemu_put_kbd_event_opaque;
382 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
383 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
385 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
387 qemu_put_kbd_event_opaque = opaque;
388 qemu_put_kbd_event = func;
391 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
392 void *opaque, int absolute,
393 const char *name)
395 QEMUPutMouseEntry *s, *cursor;
397 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
399 s->qemu_put_mouse_event = func;
400 s->qemu_put_mouse_event_opaque = opaque;
401 s->qemu_put_mouse_event_absolute = absolute;
402 s->qemu_put_mouse_event_name = qemu_strdup(name);
403 s->next = NULL;
405 if (!qemu_put_mouse_event_head) {
406 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
407 return s;
410 cursor = qemu_put_mouse_event_head;
411 while (cursor->next != NULL)
412 cursor = cursor->next;
414 cursor->next = s;
415 qemu_put_mouse_event_current = s;
417 return s;
420 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
422 QEMUPutMouseEntry *prev = NULL, *cursor;
424 if (!qemu_put_mouse_event_head || entry == NULL)
425 return;
427 cursor = qemu_put_mouse_event_head;
428 while (cursor != NULL && cursor != entry) {
429 prev = cursor;
430 cursor = cursor->next;
433 if (cursor == NULL) // does not exist or list empty
434 return;
435 else if (prev == NULL) { // entry is head
436 qemu_put_mouse_event_head = cursor->next;
437 if (qemu_put_mouse_event_current == entry)
438 qemu_put_mouse_event_current = cursor->next;
439 qemu_free(entry->qemu_put_mouse_event_name);
440 qemu_free(entry);
441 return;
444 prev->next = entry->next;
446 if (qemu_put_mouse_event_current == entry)
447 qemu_put_mouse_event_current = prev;
449 qemu_free(entry->qemu_put_mouse_event_name);
450 qemu_free(entry);
453 void kbd_put_keycode(int keycode)
455 if (qemu_put_kbd_event) {
456 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
460 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
462 QEMUPutMouseEvent *mouse_event;
463 void *mouse_event_opaque;
464 int width;
466 if (!qemu_put_mouse_event_current) {
467 return;
470 mouse_event =
471 qemu_put_mouse_event_current->qemu_put_mouse_event;
472 mouse_event_opaque =
473 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
475 if (mouse_event) {
476 if (graphic_rotate) {
477 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
478 width = 0x7fff;
479 else
480 width = graphic_width - 1;
481 mouse_event(mouse_event_opaque,
482 width - dy, dx, dz, buttons_state);
483 } else
484 mouse_event(mouse_event_opaque,
485 dx, dy, dz, buttons_state);
489 int kbd_mouse_is_absolute(void)
491 if (!qemu_put_mouse_event_current)
492 return 0;
494 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
497 void do_info_mice(Monitor *mon)
499 QEMUPutMouseEntry *cursor;
500 int index = 0;
502 if (!qemu_put_mouse_event_head) {
503 monitor_printf(mon, "No mouse devices connected\n");
504 return;
507 monitor_printf(mon, "Mouse devices available:\n");
508 cursor = qemu_put_mouse_event_head;
509 while (cursor != NULL) {
510 monitor_printf(mon, "%c Mouse #%d: %s\n",
511 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
512 index, cursor->qemu_put_mouse_event_name);
513 index++;
514 cursor = cursor->next;
518 void do_mouse_set(Monitor *mon, int index)
520 QEMUPutMouseEntry *cursor;
521 int i = 0;
523 if (!qemu_put_mouse_event_head) {
524 monitor_printf(mon, "No mouse devices connected\n");
525 return;
528 cursor = qemu_put_mouse_event_head;
529 while (cursor != NULL && index != i) {
530 i++;
531 cursor = cursor->next;
534 if (cursor != NULL)
535 qemu_put_mouse_event_current = cursor;
536 else
537 monitor_printf(mon, "Mouse at given index not found\n");
540 /* compute with 96 bit intermediate result: (a*b)/c */
541 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
543 union {
544 uint64_t ll;
545 struct {
546 #ifdef WORDS_BIGENDIAN
547 uint32_t high, low;
548 #else
549 uint32_t low, high;
550 #endif
551 } l;
552 } u, res;
553 uint64_t rl, rh;
555 u.ll = a;
556 rl = (uint64_t)u.l.low * (uint64_t)b;
557 rh = (uint64_t)u.l.high * (uint64_t)b;
558 rh += (rl >> 32);
559 res.l.high = rh / c;
560 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
561 return res.ll;
564 /***********************************************************/
565 /* real time host monotonic timer */
567 #define QEMU_TIMER_BASE 1000000000LL
569 #ifdef WIN32
571 static int64_t clock_freq;
573 static void init_get_clock(void)
575 LARGE_INTEGER freq;
576 int ret;
577 ret = QueryPerformanceFrequency(&freq);
578 if (ret == 0) {
579 fprintf(stderr, "Could not calibrate ticks\n");
580 exit(1);
582 clock_freq = freq.QuadPart;
585 static int64_t get_clock(void)
587 LARGE_INTEGER ti;
588 QueryPerformanceCounter(&ti);
589 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
592 #else
594 static int use_rt_clock;
596 static void init_get_clock(void)
598 use_rt_clock = 0;
599 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
600 || defined(__DragonFly__)
602 struct timespec ts;
603 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
604 use_rt_clock = 1;
607 #endif
610 static int64_t get_clock(void)
612 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
613 || defined(__DragonFly__)
614 if (use_rt_clock) {
615 struct timespec ts;
616 clock_gettime(CLOCK_MONOTONIC, &ts);
617 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
618 } else
619 #endif
621 /* XXX: using gettimeofday leads to problems if the date
622 changes, so it should be avoided. */
623 struct timeval tv;
624 gettimeofday(&tv, NULL);
625 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
628 #endif
630 /* Return the virtual CPU time, based on the instruction counter. */
631 static int64_t cpu_get_icount(void)
633 int64_t icount;
634 CPUState *env = cpu_single_env;;
635 icount = qemu_icount;
636 if (env) {
637 if (!can_do_io(env))
638 fprintf(stderr, "Bad clock read\n");
639 icount -= (env->icount_decr.u16.low + env->icount_extra);
641 return qemu_icount_bias + (icount << icount_time_shift);
644 /***********************************************************/
645 /* guest cycle counter */
647 static int64_t cpu_ticks_prev;
648 static int64_t cpu_ticks_offset;
649 static int64_t cpu_clock_offset;
650 static int cpu_ticks_enabled;
652 /* return the host CPU cycle counter and handle stop/restart */
653 int64_t cpu_get_ticks(void)
655 if (use_icount) {
656 return cpu_get_icount();
658 if (!cpu_ticks_enabled) {
659 return cpu_ticks_offset;
660 } else {
661 int64_t ticks;
662 ticks = cpu_get_real_ticks();
663 if (cpu_ticks_prev > ticks) {
664 /* Note: non increasing ticks may happen if the host uses
665 software suspend */
666 cpu_ticks_offset += cpu_ticks_prev - ticks;
668 cpu_ticks_prev = ticks;
669 return ticks + cpu_ticks_offset;
673 /* return the host CPU monotonic timer and handle stop/restart */
674 static int64_t cpu_get_clock(void)
676 int64_t ti;
677 if (!cpu_ticks_enabled) {
678 return cpu_clock_offset;
679 } else {
680 ti = get_clock();
681 return ti + cpu_clock_offset;
685 /* enable cpu_get_ticks() */
686 void cpu_enable_ticks(void)
688 if (!cpu_ticks_enabled) {
689 cpu_ticks_offset -= cpu_get_real_ticks();
690 cpu_clock_offset -= get_clock();
691 cpu_ticks_enabled = 1;
695 /* disable cpu_get_ticks() : the clock is stopped. You must not call
696 cpu_get_ticks() after that. */
697 void cpu_disable_ticks(void)
699 if (cpu_ticks_enabled) {
700 cpu_ticks_offset = cpu_get_ticks();
701 cpu_clock_offset = cpu_get_clock();
702 cpu_ticks_enabled = 0;
706 /***********************************************************/
707 /* timers */
709 #define QEMU_TIMER_REALTIME 0
710 #define QEMU_TIMER_VIRTUAL 1
712 struct QEMUClock {
713 int type;
714 /* XXX: add frequency */
717 struct QEMUTimer {
718 QEMUClock *clock;
719 int64_t expire_time;
720 QEMUTimerCB *cb;
721 void *opaque;
722 struct QEMUTimer *next;
725 struct qemu_alarm_timer {
726 char const *name;
727 unsigned int flags;
729 int (*start)(struct qemu_alarm_timer *t);
730 void (*stop)(struct qemu_alarm_timer *t);
731 void (*rearm)(struct qemu_alarm_timer *t);
732 void *priv;
735 #define ALARM_FLAG_DYNTICKS 0x1
736 #define ALARM_FLAG_EXPIRED 0x2
738 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
740 return t && (t->flags & ALARM_FLAG_DYNTICKS);
743 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
745 if (!alarm_has_dynticks(t))
746 return;
748 t->rearm(t);
751 /* TODO: MIN_TIMER_REARM_US should be optimized */
752 #define MIN_TIMER_REARM_US 250
754 static struct qemu_alarm_timer *alarm_timer;
756 #ifdef _WIN32
758 struct qemu_alarm_win32 {
759 MMRESULT timerId;
760 unsigned int period;
761 } alarm_win32_data = {0, -1};
763 static int win32_start_timer(struct qemu_alarm_timer *t);
764 static void win32_stop_timer(struct qemu_alarm_timer *t);
765 static void win32_rearm_timer(struct qemu_alarm_timer *t);
767 #else
769 static int unix_start_timer(struct qemu_alarm_timer *t);
770 static void unix_stop_timer(struct qemu_alarm_timer *t);
772 #ifdef __linux__
774 static int dynticks_start_timer(struct qemu_alarm_timer *t);
775 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
776 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
778 static int hpet_start_timer(struct qemu_alarm_timer *t);
779 static void hpet_stop_timer(struct qemu_alarm_timer *t);
781 static int rtc_start_timer(struct qemu_alarm_timer *t);
782 static void rtc_stop_timer(struct qemu_alarm_timer *t);
784 #endif /* __linux__ */
786 #endif /* _WIN32 */
788 /* Correlation between real and virtual time is always going to be
789 fairly approximate, so ignore small variation.
790 When the guest is idle real and virtual time will be aligned in
791 the IO wait loop. */
792 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
794 static void icount_adjust(void)
796 int64_t cur_time;
797 int64_t cur_icount;
798 int64_t delta;
799 static int64_t last_delta;
800 /* If the VM is not running, then do nothing. */
801 if (!vm_running)
802 return;
804 cur_time = cpu_get_clock();
805 cur_icount = qemu_get_clock(vm_clock);
806 delta = cur_icount - cur_time;
807 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
808 if (delta > 0
809 && last_delta + ICOUNT_WOBBLE < delta * 2
810 && icount_time_shift > 0) {
811 /* The guest is getting too far ahead. Slow time down. */
812 icount_time_shift--;
814 if (delta < 0
815 && last_delta - ICOUNT_WOBBLE > delta * 2
816 && icount_time_shift < MAX_ICOUNT_SHIFT) {
817 /* The guest is getting too far behind. Speed time up. */
818 icount_time_shift++;
820 last_delta = delta;
821 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
824 static void icount_adjust_rt(void * opaque)
826 qemu_mod_timer(icount_rt_timer,
827 qemu_get_clock(rt_clock) + 1000);
828 icount_adjust();
831 static void icount_adjust_vm(void * opaque)
833 qemu_mod_timer(icount_vm_timer,
834 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
835 icount_adjust();
838 static void init_icount_adjust(void)
840 /* Have both realtime and virtual time triggers for speed adjustment.
841 The realtime trigger catches emulated time passing too slowly,
842 the virtual time trigger catches emulated time passing too fast.
843 Realtime triggers occur even when idle, so use them less frequently
844 than VM triggers. */
845 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
846 qemu_mod_timer(icount_rt_timer,
847 qemu_get_clock(rt_clock) + 1000);
848 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
849 qemu_mod_timer(icount_vm_timer,
850 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
853 static struct qemu_alarm_timer alarm_timers[] = {
854 #ifndef _WIN32
855 #ifdef __linux__
856 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
857 dynticks_stop_timer, dynticks_rearm_timer, NULL},
858 /* HPET - if available - is preferred */
859 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
860 /* ...otherwise try RTC */
861 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
862 #endif
863 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
864 #else
865 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
866 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
867 {"win32", 0, win32_start_timer,
868 win32_stop_timer, NULL, &alarm_win32_data},
869 #endif
870 {NULL, }
873 static void show_available_alarms(void)
875 int i;
877 printf("Available alarm timers, in order of precedence:\n");
878 for (i = 0; alarm_timers[i].name; i++)
879 printf("%s\n", alarm_timers[i].name);
882 static void configure_alarms(char const *opt)
884 int i;
885 int cur = 0;
886 int count = ARRAY_SIZE(alarm_timers) - 1;
887 char *arg;
888 char *name;
889 struct qemu_alarm_timer tmp;
891 if (!strcmp(opt, "?")) {
892 show_available_alarms();
893 exit(0);
896 arg = strdup(opt);
898 /* Reorder the array */
899 name = strtok(arg, ",");
900 while (name) {
901 for (i = 0; i < count && alarm_timers[i].name; i++) {
902 if (!strcmp(alarm_timers[i].name, name))
903 break;
906 if (i == count) {
907 fprintf(stderr, "Unknown clock %s\n", name);
908 goto next;
911 if (i < cur)
912 /* Ignore */
913 goto next;
915 /* Swap */
916 tmp = alarm_timers[i];
917 alarm_timers[i] = alarm_timers[cur];
918 alarm_timers[cur] = tmp;
920 cur++;
921 next:
922 name = strtok(NULL, ",");
925 free(arg);
927 if (cur) {
928 /* Disable remaining timers */
929 for (i = cur; i < count; i++)
930 alarm_timers[i].name = NULL;
931 } else {
932 show_available_alarms();
933 exit(1);
937 QEMUClock *rt_clock;
938 QEMUClock *vm_clock;
940 static QEMUTimer *active_timers[2];
942 static QEMUClock *qemu_new_clock(int type)
944 QEMUClock *clock;
945 clock = qemu_mallocz(sizeof(QEMUClock));
946 clock->type = type;
947 return clock;
950 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
952 QEMUTimer *ts;
954 ts = qemu_mallocz(sizeof(QEMUTimer));
955 ts->clock = clock;
956 ts->cb = cb;
957 ts->opaque = opaque;
958 return ts;
961 void qemu_free_timer(QEMUTimer *ts)
963 qemu_free(ts);
966 /* stop a timer, but do not dealloc it */
967 void qemu_del_timer(QEMUTimer *ts)
969 QEMUTimer **pt, *t;
971 /* NOTE: this code must be signal safe because
972 qemu_timer_expired() can be called from a signal. */
973 pt = &active_timers[ts->clock->type];
974 for(;;) {
975 t = *pt;
976 if (!t)
977 break;
978 if (t == ts) {
979 *pt = t->next;
980 break;
982 pt = &t->next;
986 /* modify the current timer so that it will be fired when current_time
987 >= expire_time. The corresponding callback will be called. */
988 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
990 QEMUTimer **pt, *t;
992 qemu_del_timer(ts);
994 /* add the timer in the sorted list */
995 /* NOTE: this code must be signal safe because
996 qemu_timer_expired() can be called from a signal. */
997 pt = &active_timers[ts->clock->type];
998 for(;;) {
999 t = *pt;
1000 if (!t)
1001 break;
1002 if (t->expire_time > expire_time)
1003 break;
1004 pt = &t->next;
1006 ts->expire_time = expire_time;
1007 ts->next = *pt;
1008 *pt = ts;
1010 /* Rearm if necessary */
1011 if (pt == &active_timers[ts->clock->type]) {
1012 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1013 qemu_rearm_alarm_timer(alarm_timer);
1015 /* Interrupt execution to force deadline recalculation. */
1016 if (use_icount)
1017 qemu_notify_event();
1021 int qemu_timer_pending(QEMUTimer *ts)
1023 QEMUTimer *t;
1024 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1025 if (t == ts)
1026 return 1;
1028 return 0;
1031 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1033 if (!timer_head)
1034 return 0;
1035 return (timer_head->expire_time <= current_time);
1038 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1040 QEMUTimer *ts;
1042 for(;;) {
1043 ts = *ptimer_head;
1044 if (!ts || ts->expire_time > current_time)
1045 break;
1046 /* remove timer from the list before calling the callback */
1047 *ptimer_head = ts->next;
1048 ts->next = NULL;
1050 /* run the callback (the timer list can be modified) */
1051 ts->cb(ts->opaque);
1055 int64_t qemu_get_clock(QEMUClock *clock)
1057 switch(clock->type) {
1058 case QEMU_TIMER_REALTIME:
1059 return get_clock() / 1000000;
1060 default:
1061 case QEMU_TIMER_VIRTUAL:
1062 if (use_icount) {
1063 return cpu_get_icount();
1064 } else {
1065 return cpu_get_clock();
1070 static void init_timers(void)
1072 init_get_clock();
1073 ticks_per_sec = QEMU_TIMER_BASE;
1074 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1075 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1078 /* save a timer */
1079 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1081 uint64_t expire_time;
1083 if (qemu_timer_pending(ts)) {
1084 expire_time = ts->expire_time;
1085 } else {
1086 expire_time = -1;
1088 qemu_put_be64(f, expire_time);
1091 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1093 uint64_t expire_time;
1095 expire_time = qemu_get_be64(f);
1096 if (expire_time != -1) {
1097 qemu_mod_timer(ts, expire_time);
1098 } else {
1099 qemu_del_timer(ts);
1103 static void timer_save(QEMUFile *f, void *opaque)
1105 if (cpu_ticks_enabled) {
1106 hw_error("cannot save state if virtual timers are running");
1108 qemu_put_be64(f, cpu_ticks_offset);
1109 qemu_put_be64(f, ticks_per_sec);
1110 qemu_put_be64(f, cpu_clock_offset);
1113 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1115 if (version_id != 1 && version_id != 2)
1116 return -EINVAL;
1117 if (cpu_ticks_enabled) {
1118 return -EINVAL;
1120 cpu_ticks_offset=qemu_get_be64(f);
1121 ticks_per_sec=qemu_get_be64(f);
1122 if (version_id == 2) {
1123 cpu_clock_offset=qemu_get_be64(f);
1125 return 0;
1128 static void qemu_event_increment(void);
1130 #ifdef _WIN32
1131 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1132 DWORD_PTR dwUser, DWORD_PTR dw1,
1133 DWORD_PTR dw2)
1134 #else
1135 static void host_alarm_handler(int host_signum)
1136 #endif
1138 #if 0
1139 #define DISP_FREQ 1000
1141 static int64_t delta_min = INT64_MAX;
1142 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1143 static int count;
1144 ti = qemu_get_clock(vm_clock);
1145 if (last_clock != 0) {
1146 delta = ti - last_clock;
1147 if (delta < delta_min)
1148 delta_min = delta;
1149 if (delta > delta_max)
1150 delta_max = delta;
1151 delta_cum += delta;
1152 if (++count == DISP_FREQ) {
1153 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1154 muldiv64(delta_min, 1000000, ticks_per_sec),
1155 muldiv64(delta_max, 1000000, ticks_per_sec),
1156 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1157 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1158 count = 0;
1159 delta_min = INT64_MAX;
1160 delta_max = 0;
1161 delta_cum = 0;
1164 last_clock = ti;
1166 #endif
1167 if (alarm_has_dynticks(alarm_timer) ||
1168 (!use_icount &&
1169 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1170 qemu_get_clock(vm_clock))) ||
1171 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1172 qemu_get_clock(rt_clock))) {
1173 qemu_event_increment();
1174 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1176 #ifndef CONFIG_IOTHREAD
1177 if (next_cpu) {
1178 /* stop the currently executing cpu because a timer occured */
1179 cpu_exit(next_cpu);
1180 #ifdef CONFIG_KQEMU
1181 if (next_cpu->kqemu_enabled) {
1182 kqemu_cpu_interrupt(next_cpu);
1184 #endif
1186 #endif
1187 timer_alarm_pending = 1;
1188 qemu_notify_event();
1192 static int64_t qemu_next_deadline(void)
1194 int64_t delta;
1196 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1197 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1198 qemu_get_clock(vm_clock);
1199 } else {
1200 /* To avoid problems with overflow limit this to 2^32. */
1201 delta = INT32_MAX;
1204 if (delta < 0)
1205 delta = 0;
1207 return delta;
1210 #if defined(__linux__) || defined(_WIN32)
1211 static uint64_t qemu_next_deadline_dyntick(void)
1213 int64_t delta;
1214 int64_t rtdelta;
1216 if (use_icount)
1217 delta = INT32_MAX;
1218 else
1219 delta = (qemu_next_deadline() + 999) / 1000;
1221 if (active_timers[QEMU_TIMER_REALTIME]) {
1222 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1223 qemu_get_clock(rt_clock))*1000;
1224 if (rtdelta < delta)
1225 delta = rtdelta;
1228 if (delta < MIN_TIMER_REARM_US)
1229 delta = MIN_TIMER_REARM_US;
1231 return delta;
1233 #endif
1235 #ifndef _WIN32
1237 /* Sets a specific flag */
1238 static int fcntl_setfl(int fd, int flag)
1240 int flags;
1242 flags = fcntl(fd, F_GETFL);
1243 if (flags == -1)
1244 return -errno;
1246 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1247 return -errno;
1249 return 0;
1252 #if defined(__linux__)
1254 #define RTC_FREQ 1024
1256 static void enable_sigio_timer(int fd)
1258 struct sigaction act;
1260 /* timer signal */
1261 sigfillset(&act.sa_mask);
1262 act.sa_flags = 0;
1263 act.sa_handler = host_alarm_handler;
1265 sigaction(SIGIO, &act, NULL);
1266 fcntl_setfl(fd, O_ASYNC);
1267 fcntl(fd, F_SETOWN, getpid());
1270 static int hpet_start_timer(struct qemu_alarm_timer *t)
1272 struct hpet_info info;
1273 int r, fd;
1275 fd = open("/dev/hpet", O_RDONLY);
1276 if (fd < 0)
1277 return -1;
1279 /* Set frequency */
1280 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1281 if (r < 0) {
1282 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1283 "error, but for better emulation accuracy type:\n"
1284 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1285 goto fail;
1288 /* Check capabilities */
1289 r = ioctl(fd, HPET_INFO, &info);
1290 if (r < 0)
1291 goto fail;
1293 /* Enable periodic mode */
1294 r = ioctl(fd, HPET_EPI, 0);
1295 if (info.hi_flags && (r < 0))
1296 goto fail;
1298 /* Enable interrupt */
1299 r = ioctl(fd, HPET_IE_ON, 0);
1300 if (r < 0)
1301 goto fail;
1303 enable_sigio_timer(fd);
1304 t->priv = (void *)(long)fd;
1306 return 0;
1307 fail:
1308 close(fd);
1309 return -1;
1312 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1314 int fd = (long)t->priv;
1316 close(fd);
1319 static int rtc_start_timer(struct qemu_alarm_timer *t)
1321 int rtc_fd;
1322 unsigned long current_rtc_freq = 0;
1324 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1325 if (rtc_fd < 0)
1326 return -1;
1327 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1328 if (current_rtc_freq != RTC_FREQ &&
1329 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1330 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1331 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1332 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1333 goto fail;
1335 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1336 fail:
1337 close(rtc_fd);
1338 return -1;
1341 enable_sigio_timer(rtc_fd);
1343 t->priv = (void *)(long)rtc_fd;
1345 return 0;
1348 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1350 int rtc_fd = (long)t->priv;
1352 close(rtc_fd);
1355 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1357 struct sigevent ev;
1358 timer_t host_timer;
1359 struct sigaction act;
1361 sigfillset(&act.sa_mask);
1362 act.sa_flags = 0;
1363 act.sa_handler = host_alarm_handler;
1365 sigaction(SIGALRM, &act, NULL);
1368 * Initialize ev struct to 0 to avoid valgrind complaining
1369 * about uninitialized data in timer_create call
1371 memset(&ev, 0, sizeof(ev));
1372 ev.sigev_value.sival_int = 0;
1373 ev.sigev_notify = SIGEV_SIGNAL;
1374 ev.sigev_signo = SIGALRM;
1376 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1377 perror("timer_create");
1379 /* disable dynticks */
1380 fprintf(stderr, "Dynamic Ticks disabled\n");
1382 return -1;
1385 t->priv = (void *)(long)host_timer;
1387 return 0;
1390 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1392 timer_t host_timer = (timer_t)(long)t->priv;
1394 timer_delete(host_timer);
1397 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1399 timer_t host_timer = (timer_t)(long)t->priv;
1400 struct itimerspec timeout;
1401 int64_t nearest_delta_us = INT64_MAX;
1402 int64_t current_us;
1404 if (!active_timers[QEMU_TIMER_REALTIME] &&
1405 !active_timers[QEMU_TIMER_VIRTUAL])
1406 return;
1408 nearest_delta_us = qemu_next_deadline_dyntick();
1410 /* check whether a timer is already running */
1411 if (timer_gettime(host_timer, &timeout)) {
1412 perror("gettime");
1413 fprintf(stderr, "Internal timer error: aborting\n");
1414 exit(1);
1416 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1417 if (current_us && current_us <= nearest_delta_us)
1418 return;
1420 timeout.it_interval.tv_sec = 0;
1421 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1422 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1423 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1424 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1425 perror("settime");
1426 fprintf(stderr, "Internal timer error: aborting\n");
1427 exit(1);
1431 #endif /* defined(__linux__) */
1433 static int unix_start_timer(struct qemu_alarm_timer *t)
1435 struct sigaction act;
1436 struct itimerval itv;
1437 int err;
1439 /* timer signal */
1440 sigfillset(&act.sa_mask);
1441 act.sa_flags = 0;
1442 act.sa_handler = host_alarm_handler;
1444 sigaction(SIGALRM, &act, NULL);
1446 itv.it_interval.tv_sec = 0;
1447 /* for i386 kernel 2.6 to get 1 ms */
1448 itv.it_interval.tv_usec = 999;
1449 itv.it_value.tv_sec = 0;
1450 itv.it_value.tv_usec = 10 * 1000;
1452 err = setitimer(ITIMER_REAL, &itv, NULL);
1453 if (err)
1454 return -1;
1456 return 0;
1459 static void unix_stop_timer(struct qemu_alarm_timer *t)
1461 struct itimerval itv;
1463 memset(&itv, 0, sizeof(itv));
1464 setitimer(ITIMER_REAL, &itv, NULL);
1467 #endif /* !defined(_WIN32) */
1470 #ifdef _WIN32
1472 static int win32_start_timer(struct qemu_alarm_timer *t)
1474 TIMECAPS tc;
1475 struct qemu_alarm_win32 *data = t->priv;
1476 UINT flags;
1478 memset(&tc, 0, sizeof(tc));
1479 timeGetDevCaps(&tc, sizeof(tc));
1481 if (data->period < tc.wPeriodMin)
1482 data->period = tc.wPeriodMin;
1484 timeBeginPeriod(data->period);
1486 flags = TIME_CALLBACK_FUNCTION;
1487 if (alarm_has_dynticks(t))
1488 flags |= TIME_ONESHOT;
1489 else
1490 flags |= TIME_PERIODIC;
1492 data->timerId = timeSetEvent(1, // interval (ms)
1493 data->period, // resolution
1494 host_alarm_handler, // function
1495 (DWORD)t, // parameter
1496 flags);
1498 if (!data->timerId) {
1499 perror("Failed to initialize win32 alarm timer");
1500 timeEndPeriod(data->period);
1501 return -1;
1504 return 0;
1507 static void win32_stop_timer(struct qemu_alarm_timer *t)
1509 struct qemu_alarm_win32 *data = t->priv;
1511 timeKillEvent(data->timerId);
1512 timeEndPeriod(data->period);
1515 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1517 struct qemu_alarm_win32 *data = t->priv;
1518 uint64_t nearest_delta_us;
1520 if (!active_timers[QEMU_TIMER_REALTIME] &&
1521 !active_timers[QEMU_TIMER_VIRTUAL])
1522 return;
1524 nearest_delta_us = qemu_next_deadline_dyntick();
1525 nearest_delta_us /= 1000;
1527 timeKillEvent(data->timerId);
1529 data->timerId = timeSetEvent(1,
1530 data->period,
1531 host_alarm_handler,
1532 (DWORD)t,
1533 TIME_ONESHOT | TIME_PERIODIC);
1535 if (!data->timerId) {
1536 perror("Failed to re-arm win32 alarm timer");
1538 timeEndPeriod(data->period);
1539 exit(1);
1543 #endif /* _WIN32 */
1545 static int init_timer_alarm(void)
1547 struct qemu_alarm_timer *t = NULL;
1548 int i, err = -1;
1550 for (i = 0; alarm_timers[i].name; i++) {
1551 t = &alarm_timers[i];
1553 err = t->start(t);
1554 if (!err)
1555 break;
1558 if (err) {
1559 err = -ENOENT;
1560 goto fail;
1563 alarm_timer = t;
1565 return 0;
1567 fail:
1568 return err;
1571 static void quit_timers(void)
1573 alarm_timer->stop(alarm_timer);
1574 alarm_timer = NULL;
1577 /***********************************************************/
1578 /* host time/date access */
1579 void qemu_get_timedate(struct tm *tm, int offset)
1581 time_t ti;
1582 struct tm *ret;
1584 time(&ti);
1585 ti += offset;
1586 if (rtc_date_offset == -1) {
1587 if (rtc_utc)
1588 ret = gmtime(&ti);
1589 else
1590 ret = localtime(&ti);
1591 } else {
1592 ti -= rtc_date_offset;
1593 ret = gmtime(&ti);
1596 memcpy(tm, ret, sizeof(struct tm));
1599 int qemu_timedate_diff(struct tm *tm)
1601 time_t seconds;
1603 if (rtc_date_offset == -1)
1604 if (rtc_utc)
1605 seconds = mktimegm(tm);
1606 else
1607 seconds = mktime(tm);
1608 else
1609 seconds = mktimegm(tm) + rtc_date_offset;
1611 return seconds - time(NULL);
1614 #ifdef _WIN32
1615 static void socket_cleanup(void)
1617 WSACleanup();
1620 static int socket_init(void)
1622 WSADATA Data;
1623 int ret, err;
1625 ret = WSAStartup(MAKEWORD(2,2), &Data);
1626 if (ret != 0) {
1627 err = WSAGetLastError();
1628 fprintf(stderr, "WSAStartup: %d\n", err);
1629 return -1;
1631 atexit(socket_cleanup);
1632 return 0;
1634 #endif
1636 int get_next_param_value(char *buf, int buf_size,
1637 const char *tag, const char **pstr)
1639 const char *p;
1640 char option[128];
1642 p = *pstr;
1643 for(;;) {
1644 p = get_opt_name(option, sizeof(option), p, '=');
1645 if (*p != '=')
1646 break;
1647 p++;
1648 if (!strcmp(tag, option)) {
1649 *pstr = get_opt_value(buf, buf_size, p);
1650 if (**pstr == ',') {
1651 (*pstr)++;
1653 return strlen(buf);
1654 } else {
1655 p = get_opt_value(NULL, 0, p);
1657 if (*p != ',')
1658 break;
1659 p++;
1661 return 0;
1664 int get_param_value(char *buf, int buf_size,
1665 const char *tag, const char *str)
1667 return get_next_param_value(buf, buf_size, tag, &str);
1670 int check_params(char *buf, int buf_size,
1671 const char * const *params, const char *str)
1673 const char *p;
1674 int i;
1676 p = str;
1677 while (*p != '\0') {
1678 p = get_opt_name(buf, buf_size, p, '=');
1679 if (*p != '=') {
1680 return -1;
1682 p++;
1683 for (i = 0; params[i] != NULL; i++) {
1684 if (!strcmp(params[i], buf)) {
1685 break;
1688 if (params[i] == NULL) {
1689 return -1;
1691 p = get_opt_value(NULL, 0, p);
1692 if (*p != ',') {
1693 break;
1695 p++;
1697 return 0;
1700 /***********************************************************/
1701 /* Bluetooth support */
1702 static int nb_hcis;
1703 static int cur_hci;
1704 static struct HCIInfo *hci_table[MAX_NICS];
1706 static struct bt_vlan_s {
1707 struct bt_scatternet_s net;
1708 int id;
1709 struct bt_vlan_s *next;
1710 } *first_bt_vlan;
1712 /* find or alloc a new bluetooth "VLAN" */
1713 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1715 struct bt_vlan_s **pvlan, *vlan;
1716 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1717 if (vlan->id == id)
1718 return &vlan->net;
1720 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1721 vlan->id = id;
1722 pvlan = &first_bt_vlan;
1723 while (*pvlan != NULL)
1724 pvlan = &(*pvlan)->next;
1725 *pvlan = vlan;
1726 return &vlan->net;
1729 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1733 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1735 return -ENOTSUP;
1738 static struct HCIInfo null_hci = {
1739 .cmd_send = null_hci_send,
1740 .sco_send = null_hci_send,
1741 .acl_send = null_hci_send,
1742 .bdaddr_set = null_hci_addr_set,
1745 struct HCIInfo *qemu_next_hci(void)
1747 if (cur_hci == nb_hcis)
1748 return &null_hci;
1750 return hci_table[cur_hci++];
1753 static struct HCIInfo *hci_init(const char *str)
1755 char *endp;
1756 struct bt_scatternet_s *vlan = 0;
1758 if (!strcmp(str, "null"))
1759 /* null */
1760 return &null_hci;
1761 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1762 /* host[:hciN] */
1763 return bt_host_hci(str[4] ? str + 5 : "hci0");
1764 else if (!strncmp(str, "hci", 3)) {
1765 /* hci[,vlan=n] */
1766 if (str[3]) {
1767 if (!strncmp(str + 3, ",vlan=", 6)) {
1768 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1769 if (*endp)
1770 vlan = 0;
1772 } else
1773 vlan = qemu_find_bt_vlan(0);
1774 if (vlan)
1775 return bt_new_hci(vlan);
1778 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1780 return 0;
1783 static int bt_hci_parse(const char *str)
1785 struct HCIInfo *hci;
1786 bdaddr_t bdaddr;
1788 if (nb_hcis >= MAX_NICS) {
1789 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1790 return -1;
1793 hci = hci_init(str);
1794 if (!hci)
1795 return -1;
1797 bdaddr.b[0] = 0x52;
1798 bdaddr.b[1] = 0x54;
1799 bdaddr.b[2] = 0x00;
1800 bdaddr.b[3] = 0x12;
1801 bdaddr.b[4] = 0x34;
1802 bdaddr.b[5] = 0x56 + nb_hcis;
1803 hci->bdaddr_set(hci, bdaddr.b);
1805 hci_table[nb_hcis++] = hci;
1807 return 0;
1810 static void bt_vhci_add(int vlan_id)
1812 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1814 if (!vlan->slave)
1815 fprintf(stderr, "qemu: warning: adding a VHCI to "
1816 "an empty scatternet %i\n", vlan_id);
1818 bt_vhci_init(bt_new_hci(vlan));
1821 static struct bt_device_s *bt_device_add(const char *opt)
1823 struct bt_scatternet_s *vlan;
1824 int vlan_id = 0;
1825 char *endp = strstr(opt, ",vlan=");
1826 int len = (endp ? endp - opt : strlen(opt)) + 1;
1827 char devname[10];
1829 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1831 if (endp) {
1832 vlan_id = strtol(endp + 6, &endp, 0);
1833 if (*endp) {
1834 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1835 return 0;
1839 vlan = qemu_find_bt_vlan(vlan_id);
1841 if (!vlan->slave)
1842 fprintf(stderr, "qemu: warning: adding a slave device to "
1843 "an empty scatternet %i\n", vlan_id);
1845 if (!strcmp(devname, "keyboard"))
1846 return bt_keyboard_init(vlan);
1848 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1849 return 0;
1852 static int bt_parse(const char *opt)
1854 const char *endp, *p;
1855 int vlan;
1857 if (strstart(opt, "hci", &endp)) {
1858 if (!*endp || *endp == ',') {
1859 if (*endp)
1860 if (!strstart(endp, ",vlan=", 0))
1861 opt = endp + 1;
1863 return bt_hci_parse(opt);
1865 } else if (strstart(opt, "vhci", &endp)) {
1866 if (!*endp || *endp == ',') {
1867 if (*endp) {
1868 if (strstart(endp, ",vlan=", &p)) {
1869 vlan = strtol(p, (char **) &endp, 0);
1870 if (*endp) {
1871 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1872 return 1;
1874 } else {
1875 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1876 return 1;
1878 } else
1879 vlan = 0;
1881 bt_vhci_add(vlan);
1882 return 0;
1884 } else if (strstart(opt, "device:", &endp))
1885 return !bt_device_add(endp);
1887 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1888 return 1;
1891 /***********************************************************/
1892 /* QEMU Block devices */
1894 #define HD_ALIAS "index=%d,media=disk"
1895 #define CDROM_ALIAS "index=2,media=cdrom"
1896 #define FD_ALIAS "index=%d,if=floppy"
1897 #define PFLASH_ALIAS "if=pflash"
1898 #define MTD_ALIAS "if=mtd"
1899 #define SD_ALIAS "index=0,if=sd"
1901 static int drive_opt_get_free_idx(void)
1903 int index;
1905 for (index = 0; index < MAX_DRIVES; index++)
1906 if (!drives_opt[index].used) {
1907 drives_opt[index].used = 1;
1908 return index;
1911 return -1;
1914 static int drive_get_free_idx(void)
1916 int index;
1918 for (index = 0; index < MAX_DRIVES; index++)
1919 if (!drives_table[index].used) {
1920 drives_table[index].used = 1;
1921 return index;
1924 return -1;
1927 int drive_add(const char *file, const char *fmt, ...)
1929 va_list ap;
1930 int index = drive_opt_get_free_idx();
1932 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
1933 fprintf(stderr, "qemu: too many drives\n");
1934 return -1;
1937 drives_opt[index].file = file;
1938 va_start(ap, fmt);
1939 vsnprintf(drives_opt[index].opt,
1940 sizeof(drives_opt[0].opt), fmt, ap);
1941 va_end(ap);
1943 nb_drives_opt++;
1944 return index;
1947 void drive_remove(int index)
1949 drives_opt[index].used = 0;
1950 nb_drives_opt--;
1953 int drive_get_index(BlockInterfaceType type, int bus, int unit)
1955 int index;
1957 /* seek interface, bus and unit */
1959 for (index = 0; index < MAX_DRIVES; index++)
1960 if (drives_table[index].type == type &&
1961 drives_table[index].bus == bus &&
1962 drives_table[index].unit == unit &&
1963 drives_table[index].used)
1964 return index;
1966 return -1;
1969 int drive_get_max_bus(BlockInterfaceType type)
1971 int max_bus;
1972 int index;
1974 max_bus = -1;
1975 for (index = 0; index < nb_drives; index++) {
1976 if(drives_table[index].type == type &&
1977 drives_table[index].bus > max_bus)
1978 max_bus = drives_table[index].bus;
1980 return max_bus;
1983 const char *drive_get_serial(BlockDriverState *bdrv)
1985 int index;
1987 for (index = 0; index < nb_drives; index++)
1988 if (drives_table[index].bdrv == bdrv)
1989 return drives_table[index].serial;
1991 return "\0";
1994 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1996 int index;
1998 for (index = 0; index < nb_drives; index++)
1999 if (drives_table[index].bdrv == bdrv)
2000 return drives_table[index].onerror;
2002 return BLOCK_ERR_STOP_ENOSPC;
2005 static void bdrv_format_print(void *opaque, const char *name)
2007 fprintf(stderr, " %s", name);
2010 void drive_uninit(BlockDriverState *bdrv)
2012 int i;
2014 for (i = 0; i < MAX_DRIVES; i++)
2015 if (drives_table[i].bdrv == bdrv) {
2016 drives_table[i].bdrv = NULL;
2017 drives_table[i].used = 0;
2018 drive_remove(drives_table[i].drive_opt_idx);
2019 nb_drives--;
2020 break;
2024 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2026 char buf[128];
2027 char file[1024];
2028 char devname[128];
2029 char serial[21];
2030 const char *mediastr = "";
2031 BlockInterfaceType type;
2032 enum { MEDIA_DISK, MEDIA_CDROM } media;
2033 int bus_id, unit_id;
2034 int cyls, heads, secs, translation;
2035 BlockDriverState *bdrv;
2036 BlockDriver *drv = NULL;
2037 QEMUMachine *machine = opaque;
2038 int max_devs;
2039 int index;
2040 int cache;
2041 int bdrv_flags, onerror;
2042 const char *devaddr;
2043 int drives_table_idx;
2044 char *str = arg->opt;
2045 static const char * const params[] = { "bus", "unit", "if", "index",
2046 "cyls", "heads", "secs", "trans",
2047 "media", "snapshot", "file",
2048 "cache", "format", "serial",
2049 "werror", "addr",
2050 "boot",
2051 NULL };
2053 if (check_params(buf, sizeof(buf), params, str) < 0) {
2054 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2055 buf, str);
2056 return -1;
2059 file[0] = 0;
2060 cyls = heads = secs = 0;
2061 bus_id = 0;
2062 unit_id = -1;
2063 translation = BIOS_ATA_TRANSLATION_AUTO;
2064 index = -1;
2065 cache = 1;
2067 if (machine->use_scsi) {
2068 type = IF_SCSI;
2069 max_devs = MAX_SCSI_DEVS;
2070 pstrcpy(devname, sizeof(devname), "scsi");
2071 } else {
2072 type = IF_IDE;
2073 max_devs = MAX_IDE_DEVS;
2074 pstrcpy(devname, sizeof(devname), "ide");
2076 media = MEDIA_DISK;
2078 /* extract parameters */
2080 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2081 bus_id = strtol(buf, NULL, 0);
2082 if (bus_id < 0) {
2083 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2084 return -1;
2088 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2089 unit_id = strtol(buf, NULL, 0);
2090 if (unit_id < 0) {
2091 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2092 return -1;
2096 if (get_param_value(buf, sizeof(buf), "if", str)) {
2097 pstrcpy(devname, sizeof(devname), buf);
2098 if (!strcmp(buf, "ide")) {
2099 type = IF_IDE;
2100 max_devs = MAX_IDE_DEVS;
2101 } else if (!strcmp(buf, "scsi")) {
2102 type = IF_SCSI;
2103 max_devs = MAX_SCSI_DEVS;
2104 } else if (!strcmp(buf, "floppy")) {
2105 type = IF_FLOPPY;
2106 max_devs = 0;
2107 } else if (!strcmp(buf, "pflash")) {
2108 type = IF_PFLASH;
2109 max_devs = 0;
2110 } else if (!strcmp(buf, "mtd")) {
2111 type = IF_MTD;
2112 max_devs = 0;
2113 } else if (!strcmp(buf, "sd")) {
2114 type = IF_SD;
2115 max_devs = 0;
2116 } else if (!strcmp(buf, "virtio")) {
2117 type = IF_VIRTIO;
2118 max_devs = 0;
2119 } else if (!strcmp(buf, "xen")) {
2120 type = IF_XEN;
2121 max_devs = 0;
2122 } else {
2123 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2124 return -1;
2128 if (get_param_value(buf, sizeof(buf), "index", str)) {
2129 index = strtol(buf, NULL, 0);
2130 if (index < 0) {
2131 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2132 return -1;
2136 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2137 cyls = strtol(buf, NULL, 0);
2140 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2141 heads = strtol(buf, NULL, 0);
2144 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2145 secs = strtol(buf, NULL, 0);
2148 if (cyls || heads || secs) {
2149 if (cyls < 1 || cyls > 16383) {
2150 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2151 return -1;
2153 if (heads < 1 || heads > 16) {
2154 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2155 return -1;
2157 if (secs < 1 || secs > 63) {
2158 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2159 return -1;
2163 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2164 if (!cyls) {
2165 fprintf(stderr,
2166 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2167 str);
2168 return -1;
2170 if (!strcmp(buf, "none"))
2171 translation = BIOS_ATA_TRANSLATION_NONE;
2172 else if (!strcmp(buf, "lba"))
2173 translation = BIOS_ATA_TRANSLATION_LBA;
2174 else if (!strcmp(buf, "auto"))
2175 translation = BIOS_ATA_TRANSLATION_AUTO;
2176 else {
2177 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2178 return -1;
2182 if (get_param_value(buf, sizeof(buf), "media", str)) {
2183 if (!strcmp(buf, "disk")) {
2184 media = MEDIA_DISK;
2185 } else if (!strcmp(buf, "cdrom")) {
2186 if (cyls || secs || heads) {
2187 fprintf(stderr,
2188 "qemu: '%s' invalid physical CHS format\n", str);
2189 return -1;
2191 media = MEDIA_CDROM;
2192 } else {
2193 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2194 return -1;
2198 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2199 if (!strcmp(buf, "on"))
2200 snapshot = 1;
2201 else if (!strcmp(buf, "off"))
2202 snapshot = 0;
2203 else {
2204 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2205 return -1;
2209 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2210 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2211 cache = 0;
2212 else if (!strcmp(buf, "writethrough"))
2213 cache = 1;
2214 else if (!strcmp(buf, "writeback"))
2215 cache = 2;
2216 else {
2217 fprintf(stderr, "qemu: invalid cache option\n");
2218 return -1;
2222 if (get_param_value(buf, sizeof(buf), "format", str)) {
2223 if (strcmp(buf, "?") == 0) {
2224 fprintf(stderr, "qemu: Supported formats:");
2225 bdrv_iterate_format(bdrv_format_print, NULL);
2226 fprintf(stderr, "\n");
2227 return -1;
2229 drv = bdrv_find_format(buf);
2230 if (!drv) {
2231 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2232 return -1;
2236 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2237 if (!strcmp(buf, "on")) {
2238 if (extboot_drive != -1) {
2239 fprintf(stderr, "qemu: two bootable drives specified\n");
2240 return -1;
2242 extboot_drive = nb_drives;
2243 } else if (strcmp(buf, "off")) {
2244 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2245 return -1;
2249 if (arg->file == NULL)
2250 get_param_value(file, sizeof(file), "file", str);
2251 else
2252 pstrcpy(file, sizeof(file), arg->file);
2254 if (!get_param_value(serial, sizeof(serial), "serial", str))
2255 memset(serial, 0, sizeof(serial));
2257 onerror = BLOCK_ERR_STOP_ENOSPC;
2258 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2259 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2260 fprintf(stderr, "werror is no supported by this format\n");
2261 return -1;
2263 if (!strcmp(buf, "ignore"))
2264 onerror = BLOCK_ERR_IGNORE;
2265 else if (!strcmp(buf, "enospc"))
2266 onerror = BLOCK_ERR_STOP_ENOSPC;
2267 else if (!strcmp(buf, "stop"))
2268 onerror = BLOCK_ERR_STOP_ANY;
2269 else if (!strcmp(buf, "report"))
2270 onerror = BLOCK_ERR_REPORT;
2271 else {
2272 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2273 return -1;
2277 devaddr = NULL;
2278 if (get_param_value(buf, sizeof(buf), "addr", str)) {
2279 if (type != IF_VIRTIO) {
2280 fprintf(stderr, "addr is not supported by in '%s'\n", str);
2281 return -1;
2283 devaddr = strdup(buf);
2286 /* compute bus and unit according index */
2288 if (index != -1) {
2289 if (bus_id != 0 || unit_id != -1) {
2290 fprintf(stderr,
2291 "qemu: '%s' index cannot be used with bus and unit\n", str);
2292 return -1;
2294 if (max_devs == 0)
2296 unit_id = index;
2297 bus_id = 0;
2298 } else {
2299 unit_id = index % max_devs;
2300 bus_id = index / max_devs;
2304 /* if user doesn't specify a unit_id,
2305 * try to find the first free
2308 if (unit_id == -1) {
2309 unit_id = 0;
2310 while (drive_get_index(type, bus_id, unit_id) != -1) {
2311 unit_id++;
2312 if (max_devs && unit_id >= max_devs) {
2313 unit_id -= max_devs;
2314 bus_id++;
2319 /* check unit id */
2321 if (max_devs && unit_id >= max_devs) {
2322 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2323 str, unit_id, max_devs - 1);
2324 return -1;
2328 * ignore multiple definitions
2331 if (drive_get_index(type, bus_id, unit_id) != -1)
2332 return -2;
2334 /* init */
2336 if (type == IF_IDE || type == IF_SCSI)
2337 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2338 if (max_devs)
2339 snprintf(buf, sizeof(buf), "%s%i%s%i",
2340 devname, bus_id, mediastr, unit_id);
2341 else
2342 snprintf(buf, sizeof(buf), "%s%s%i",
2343 devname, mediastr, unit_id);
2344 bdrv = bdrv_new(buf);
2345 drives_table_idx = drive_get_free_idx();
2346 drives_table[drives_table_idx].bdrv = bdrv;
2347 drives_table[drives_table_idx].devaddr = devaddr;
2348 drives_table[drives_table_idx].type = type;
2349 drives_table[drives_table_idx].bus = bus_id;
2350 drives_table[drives_table_idx].unit = unit_id;
2351 drives_table[drives_table_idx].onerror = onerror;
2352 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2353 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2354 nb_drives++;
2356 switch(type) {
2357 case IF_IDE:
2358 case IF_SCSI:
2359 case IF_XEN:
2360 switch(media) {
2361 case MEDIA_DISK:
2362 if (cyls != 0) {
2363 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2364 bdrv_set_translation_hint(bdrv, translation);
2366 break;
2367 case MEDIA_CDROM:
2368 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2369 break;
2371 break;
2372 case IF_SD:
2373 /* FIXME: This isn't really a floppy, but it's a reasonable
2374 approximation. */
2375 case IF_FLOPPY:
2376 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2377 break;
2378 case IF_PFLASH:
2379 case IF_MTD:
2380 case IF_VIRTIO:
2381 break;
2382 case IF_COUNT:
2383 abort();
2385 if (!file[0])
2386 return -2;
2387 bdrv_flags = 0;
2388 if (snapshot) {
2389 bdrv_flags |= BDRV_O_SNAPSHOT;
2390 cache = 2; /* always use write-back with snapshot */
2392 if (cache == 0) /* no caching */
2393 bdrv_flags |= BDRV_O_NOCACHE;
2394 else if (cache == 2) /* write-back */
2395 bdrv_flags |= BDRV_O_CACHE_WB;
2396 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2397 fprintf(stderr, "qemu: could not open disk image %s\n",
2398 file);
2399 return -1;
2401 if (bdrv_key_required(bdrv))
2402 autostart = 0;
2403 return drives_table_idx;
2406 static void numa_add(const char *optarg)
2408 char option[128];
2409 char *endptr;
2410 unsigned long long value, endvalue;
2411 int nodenr;
2413 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2414 if (!strcmp(option, "node")) {
2415 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2416 nodenr = nb_numa_nodes;
2417 } else {
2418 nodenr = strtoull(option, NULL, 10);
2421 if (get_param_value(option, 128, "mem", optarg) == 0) {
2422 node_mem[nodenr] = 0;
2423 } else {
2424 value = strtoull(option, &endptr, 0);
2425 switch (*endptr) {
2426 case 0: case 'M': case 'm':
2427 value <<= 20;
2428 break;
2429 case 'G': case 'g':
2430 value <<= 30;
2431 break;
2433 node_mem[nodenr] = value;
2435 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2436 node_cpumask[nodenr] = 0;
2437 } else {
2438 value = strtoull(option, &endptr, 10);
2439 if (value >= 64) {
2440 value = 63;
2441 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2442 } else {
2443 if (*endptr == '-') {
2444 endvalue = strtoull(endptr+1, &endptr, 10);
2445 if (endvalue >= 63) {
2446 endvalue = 62;
2447 fprintf(stderr,
2448 "only 63 CPUs in NUMA mode supported.\n");
2450 value = (1 << (endvalue + 1)) - (1 << value);
2451 } else {
2452 value = 1 << value;
2455 node_cpumask[nodenr] = value;
2457 nb_numa_nodes++;
2459 return;
2462 /***********************************************************/
2463 /* USB devices */
2465 static USBPort *used_usb_ports;
2466 static USBPort *free_usb_ports;
2468 /* ??? Maybe change this to register a hub to keep track of the topology. */
2469 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2470 usb_attachfn attach)
2472 port->opaque = opaque;
2473 port->index = index;
2474 port->attach = attach;
2475 port->next = free_usb_ports;
2476 free_usb_ports = port;
2479 int usb_device_add_dev(USBDevice *dev)
2481 USBPort *port;
2483 /* Find a USB port to add the device to. */
2484 port = free_usb_ports;
2485 if (!port->next) {
2486 USBDevice *hub;
2488 /* Create a new hub and chain it on. */
2489 free_usb_ports = NULL;
2490 port->next = used_usb_ports;
2491 used_usb_ports = port;
2493 hub = usb_hub_init(VM_USB_HUB_SIZE);
2494 usb_attach(port, hub);
2495 port = free_usb_ports;
2498 free_usb_ports = port->next;
2499 port->next = used_usb_ports;
2500 used_usb_ports = port;
2501 usb_attach(port, dev);
2502 return 0;
2505 static void usb_msd_password_cb(void *opaque, int err)
2507 USBDevice *dev = opaque;
2509 if (!err)
2510 usb_device_add_dev(dev);
2511 else
2512 dev->handle_destroy(dev);
2515 static int usb_device_add(const char *devname, int is_hotplug)
2517 const char *p;
2518 USBDevice *dev;
2520 if (!free_usb_ports)
2521 return -1;
2523 if (strstart(devname, "host:", &p)) {
2524 dev = usb_host_device_open(p);
2525 } else if (!strcmp(devname, "mouse")) {
2526 dev = usb_mouse_init();
2527 } else if (!strcmp(devname, "tablet")) {
2528 dev = usb_tablet_init();
2529 } else if (!strcmp(devname, "keyboard")) {
2530 dev = usb_keyboard_init();
2531 } else if (strstart(devname, "disk:", &p)) {
2532 BlockDriverState *bs;
2534 dev = usb_msd_init(p);
2535 if (!dev)
2536 return -1;
2537 bs = usb_msd_get_bdrv(dev);
2538 if (bdrv_key_required(bs)) {
2539 autostart = 0;
2540 if (is_hotplug) {
2541 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2542 dev);
2543 return 0;
2546 } else if (!strcmp(devname, "wacom-tablet")) {
2547 dev = usb_wacom_init();
2548 } else if (strstart(devname, "serial:", &p)) {
2549 dev = usb_serial_init(p);
2550 #ifdef CONFIG_BRLAPI
2551 } else if (!strcmp(devname, "braille")) {
2552 dev = usb_baum_init();
2553 #endif
2554 } else if (strstart(devname, "net:", &p)) {
2555 int nic = nb_nics;
2557 if (net_client_init(NULL, "nic", p) < 0)
2558 return -1;
2559 nd_table[nic].model = "usb";
2560 dev = usb_net_init(&nd_table[nic]);
2561 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2562 dev = usb_bt_init(devname[2] ? hci_init(p) :
2563 bt_new_hci(qemu_find_bt_vlan(0)));
2564 } else {
2565 return -1;
2567 if (!dev)
2568 return -1;
2570 return usb_device_add_dev(dev);
2573 int usb_device_del_addr(int bus_num, int addr)
2575 USBPort *port;
2576 USBPort **lastp;
2577 USBDevice *dev;
2579 if (!used_usb_ports)
2580 return -1;
2582 if (bus_num != 0)
2583 return -1;
2585 lastp = &used_usb_ports;
2586 port = used_usb_ports;
2587 while (port && port->dev->addr != addr) {
2588 lastp = &port->next;
2589 port = port->next;
2592 if (!port)
2593 return -1;
2595 dev = port->dev;
2596 *lastp = port->next;
2597 usb_attach(port, NULL);
2598 dev->handle_destroy(dev);
2599 port->next = free_usb_ports;
2600 free_usb_ports = port;
2601 return 0;
2604 static int usb_device_del(const char *devname)
2606 int bus_num, addr;
2607 const char *p;
2609 if (strstart(devname, "host:", &p))
2610 return usb_host_device_close(p);
2612 if (!used_usb_ports)
2613 return -1;
2615 p = strchr(devname, '.');
2616 if (!p)
2617 return -1;
2618 bus_num = strtoul(devname, NULL, 0);
2619 addr = strtoul(p + 1, NULL, 0);
2621 return usb_device_del_addr(bus_num, addr);
2624 void do_usb_add(Monitor *mon, const char *devname)
2626 usb_device_add(devname, 1);
2629 void do_usb_del(Monitor *mon, const char *devname)
2631 usb_device_del(devname);
2634 void usb_info(Monitor *mon)
2636 USBDevice *dev;
2637 USBPort *port;
2638 const char *speed_str;
2640 if (!usb_enabled) {
2641 monitor_printf(mon, "USB support not enabled\n");
2642 return;
2645 for (port = used_usb_ports; port; port = port->next) {
2646 dev = port->dev;
2647 if (!dev)
2648 continue;
2649 switch(dev->speed) {
2650 case USB_SPEED_LOW:
2651 speed_str = "1.5";
2652 break;
2653 case USB_SPEED_FULL:
2654 speed_str = "12";
2655 break;
2656 case USB_SPEED_HIGH:
2657 speed_str = "480";
2658 break;
2659 default:
2660 speed_str = "?";
2661 break;
2663 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2664 0, dev->addr, speed_str, dev->devname);
2668 /***********************************************************/
2669 /* PCMCIA/Cardbus */
2671 static struct pcmcia_socket_entry_s {
2672 PCMCIASocket *socket;
2673 struct pcmcia_socket_entry_s *next;
2674 } *pcmcia_sockets = 0;
2676 void pcmcia_socket_register(PCMCIASocket *socket)
2678 struct pcmcia_socket_entry_s *entry;
2680 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2681 entry->socket = socket;
2682 entry->next = pcmcia_sockets;
2683 pcmcia_sockets = entry;
2686 void pcmcia_socket_unregister(PCMCIASocket *socket)
2688 struct pcmcia_socket_entry_s *entry, **ptr;
2690 ptr = &pcmcia_sockets;
2691 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2692 if (entry->socket == socket) {
2693 *ptr = entry->next;
2694 qemu_free(entry);
2698 void pcmcia_info(Monitor *mon)
2700 struct pcmcia_socket_entry_s *iter;
2702 if (!pcmcia_sockets)
2703 monitor_printf(mon, "No PCMCIA sockets\n");
2705 for (iter = pcmcia_sockets; iter; iter = iter->next)
2706 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2707 iter->socket->attached ? iter->socket->card_string :
2708 "Empty");
2711 /***********************************************************/
2712 /* register display */
2714 struct DisplayAllocator default_allocator = {
2715 defaultallocator_create_displaysurface,
2716 defaultallocator_resize_displaysurface,
2717 defaultallocator_free_displaysurface
2720 void register_displaystate(DisplayState *ds)
2722 DisplayState **s;
2723 s = &display_state;
2724 while (*s != NULL)
2725 s = &(*s)->next;
2726 ds->next = NULL;
2727 *s = ds;
2730 DisplayState *get_displaystate(void)
2732 return display_state;
2735 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2737 if(ds->allocator == &default_allocator) ds->allocator = da;
2738 return ds->allocator;
2741 /* dumb display */
2743 static void dumb_display_init(void)
2745 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2746 ds->allocator = &default_allocator;
2747 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2748 register_displaystate(ds);
2751 /***********************************************************/
2752 /* I/O handling */
2754 typedef struct IOHandlerRecord {
2755 int fd;
2756 IOCanRWHandler *fd_read_poll;
2757 IOHandler *fd_read;
2758 IOHandler *fd_write;
2759 int deleted;
2760 void *opaque;
2761 /* temporary data */
2762 struct pollfd *ufd;
2763 struct IOHandlerRecord *next;
2764 } IOHandlerRecord;
2766 static IOHandlerRecord *first_io_handler;
2768 /* XXX: fd_read_poll should be suppressed, but an API change is
2769 necessary in the character devices to suppress fd_can_read(). */
2770 int qemu_set_fd_handler2(int fd,
2771 IOCanRWHandler *fd_read_poll,
2772 IOHandler *fd_read,
2773 IOHandler *fd_write,
2774 void *opaque)
2776 IOHandlerRecord **pioh, *ioh;
2778 if (!fd_read && !fd_write) {
2779 pioh = &first_io_handler;
2780 for(;;) {
2781 ioh = *pioh;
2782 if (ioh == NULL)
2783 break;
2784 if (ioh->fd == fd) {
2785 ioh->deleted = 1;
2786 break;
2788 pioh = &ioh->next;
2790 } else {
2791 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2792 if (ioh->fd == fd)
2793 goto found;
2795 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2796 ioh->next = first_io_handler;
2797 first_io_handler = ioh;
2798 found:
2799 ioh->fd = fd;
2800 ioh->fd_read_poll = fd_read_poll;
2801 ioh->fd_read = fd_read;
2802 ioh->fd_write = fd_write;
2803 ioh->opaque = opaque;
2804 ioh->deleted = 0;
2806 qemu_notify_event();
2807 return 0;
2810 int qemu_set_fd_handler(int fd,
2811 IOHandler *fd_read,
2812 IOHandler *fd_write,
2813 void *opaque)
2815 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2818 #ifdef _WIN32
2819 /***********************************************************/
2820 /* Polling handling */
2822 typedef struct PollingEntry {
2823 PollingFunc *func;
2824 void *opaque;
2825 struct PollingEntry *next;
2826 } PollingEntry;
2828 static PollingEntry *first_polling_entry;
2830 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2832 PollingEntry **ppe, *pe;
2833 pe = qemu_mallocz(sizeof(PollingEntry));
2834 pe->func = func;
2835 pe->opaque = opaque;
2836 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2837 *ppe = pe;
2838 return 0;
2841 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2843 PollingEntry **ppe, *pe;
2844 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2845 pe = *ppe;
2846 if (pe->func == func && pe->opaque == opaque) {
2847 *ppe = pe->next;
2848 qemu_free(pe);
2849 break;
2854 /***********************************************************/
2855 /* Wait objects support */
2856 typedef struct WaitObjects {
2857 int num;
2858 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2859 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2860 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2861 } WaitObjects;
2863 static WaitObjects wait_objects = {0};
2865 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2867 WaitObjects *w = &wait_objects;
2869 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2870 return -1;
2871 w->events[w->num] = handle;
2872 w->func[w->num] = func;
2873 w->opaque[w->num] = opaque;
2874 w->num++;
2875 return 0;
2878 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2880 int i, found;
2881 WaitObjects *w = &wait_objects;
2883 found = 0;
2884 for (i = 0; i < w->num; i++) {
2885 if (w->events[i] == handle)
2886 found = 1;
2887 if (found) {
2888 w->events[i] = w->events[i + 1];
2889 w->func[i] = w->func[i + 1];
2890 w->opaque[i] = w->opaque[i + 1];
2893 if (found)
2894 w->num--;
2896 #endif
2898 /***********************************************************/
2899 /* ram save/restore */
2901 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2903 int v;
2905 v = qemu_get_byte(f);
2906 switch(v) {
2907 case 0:
2908 if (qemu_get_buffer(f, buf, len) != len)
2909 return -EIO;
2910 break;
2911 case 1:
2912 v = qemu_get_byte(f);
2913 memset(buf, v, len);
2914 break;
2915 default:
2916 return -EINVAL;
2919 if (qemu_file_has_error(f))
2920 return -EIO;
2922 return 0;
2925 static int ram_load_v1(QEMUFile *f, void *opaque)
2927 int ret;
2928 ram_addr_t i;
2930 if (qemu_get_be32(f) != last_ram_offset)
2931 return -EINVAL;
2932 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2933 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
2934 continue;
2935 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2936 if (ret)
2937 return ret;
2939 return 0;
2942 #define BDRV_HASH_BLOCK_SIZE 1024
2943 #define IOBUF_SIZE 4096
2944 #define RAM_CBLOCK_MAGIC 0xfabe
2946 typedef struct RamDecompressState {
2947 z_stream zstream;
2948 QEMUFile *f;
2949 uint8_t buf[IOBUF_SIZE];
2950 } RamDecompressState;
2952 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2954 int ret;
2955 memset(s, 0, sizeof(*s));
2956 s->f = f;
2957 ret = inflateInit(&s->zstream);
2958 if (ret != Z_OK)
2959 return -1;
2960 return 0;
2963 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2965 int ret, clen;
2967 s->zstream.avail_out = len;
2968 s->zstream.next_out = buf;
2969 while (s->zstream.avail_out > 0) {
2970 if (s->zstream.avail_in == 0) {
2971 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
2972 return -1;
2973 clen = qemu_get_be16(s->f);
2974 if (clen > IOBUF_SIZE)
2975 return -1;
2976 qemu_get_buffer(s->f, s->buf, clen);
2977 s->zstream.avail_in = clen;
2978 s->zstream.next_in = s->buf;
2980 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
2981 if (ret != Z_OK && ret != Z_STREAM_END) {
2982 return -1;
2985 return 0;
2988 static void ram_decompress_close(RamDecompressState *s)
2990 inflateEnd(&s->zstream);
2993 #define RAM_SAVE_FLAG_FULL 0x01
2994 #define RAM_SAVE_FLAG_COMPRESS 0x02
2995 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2996 #define RAM_SAVE_FLAG_PAGE 0x08
2997 #define RAM_SAVE_FLAG_EOS 0x10
2999 static int is_dup_page(uint8_t *page, uint8_t ch)
3001 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3002 uint32_t *array = (uint32_t *)page;
3003 int i;
3005 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3006 if (array[i] != val)
3007 return 0;
3010 return 1;
3013 static int ram_save_block(QEMUFile *f)
3015 static ram_addr_t current_addr = 0;
3016 ram_addr_t saved_addr = current_addr;
3017 ram_addr_t addr = 0;
3018 int found = 0;
3020 while (addr < last_ram_offset) {
3021 if (kvm_enabled() && current_addr == 0) {
3022 int r;
3023 r = kvm_update_dirty_pages_log();
3024 if (r) {
3025 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3026 qemu_file_set_error(f);
3027 return 0;
3030 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3031 uint8_t *p;
3033 cpu_physical_memory_reset_dirty(current_addr,
3034 current_addr + TARGET_PAGE_SIZE,
3035 MIGRATION_DIRTY_FLAG);
3037 p = qemu_get_ram_ptr(current_addr);
3039 if (is_dup_page(p, *p)) {
3040 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3041 qemu_put_byte(f, *p);
3042 } else {
3043 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3044 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3047 found = 1;
3048 break;
3050 addr += TARGET_PAGE_SIZE;
3051 current_addr = (saved_addr + addr) % last_ram_offset;
3054 return found;
3057 static uint64_t bytes_transferred = 0;
3059 static ram_addr_t ram_save_remaining(void)
3061 ram_addr_t addr;
3062 ram_addr_t count = 0;
3064 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3065 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3066 count++;
3069 return count;
3072 uint64_t ram_bytes_remaining(void)
3074 return ram_save_remaining() * TARGET_PAGE_SIZE;
3077 uint64_t ram_bytes_transferred(void)
3079 return bytes_transferred;
3082 uint64_t ram_bytes_total(void)
3084 return last_ram_offset;
3087 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3089 ram_addr_t addr;
3090 uint64_t bytes_transferred_last;
3091 double bwidth = 0;
3092 uint64_t expected_time = 0;
3094 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3095 qemu_file_set_error(f);
3096 return 0;
3099 if (stage == 1) {
3100 /* Make sure all dirty bits are set */
3101 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3102 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3103 cpu_physical_memory_set_dirty(addr);
3106 /* Enable dirty memory tracking */
3107 cpu_physical_memory_set_dirty_tracking(1);
3109 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3112 bytes_transferred_last = bytes_transferred;
3113 bwidth = get_clock();
3115 while (!qemu_file_rate_limit(f)) {
3116 int ret;
3118 ret = ram_save_block(f);
3119 bytes_transferred += ret * TARGET_PAGE_SIZE;
3120 if (ret == 0) /* no more blocks */
3121 break;
3124 bwidth = get_clock() - bwidth;
3125 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3127 /* if we haven't transferred anything this round, force expected_time to a
3128 * a very high value, but without crashing */
3129 if (bwidth == 0)
3130 bwidth = 0.000001;
3132 /* try transferring iterative blocks of memory */
3134 if (stage == 3) {
3136 /* flush all remaining blocks regardless of rate limiting */
3137 while (ram_save_block(f) != 0) {
3138 bytes_transferred += TARGET_PAGE_SIZE;
3140 cpu_physical_memory_set_dirty_tracking(0);
3143 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3145 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3147 return (stage == 2) && (expected_time <= migrate_max_downtime());
3150 static int ram_load_dead(QEMUFile *f, void *opaque)
3152 RamDecompressState s1, *s = &s1;
3153 uint8_t buf[10];
3154 ram_addr_t i;
3156 if (ram_decompress_open(s, f) < 0)
3157 return -EINVAL;
3158 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3159 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3160 continue;
3161 if (ram_decompress_buf(s, buf, 1) < 0) {
3162 fprintf(stderr, "Error while reading ram block header\n");
3163 goto error;
3165 if (buf[0] == 0) {
3166 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3167 BDRV_HASH_BLOCK_SIZE) < 0) {
3168 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3169 goto error;
3171 } else {
3172 error:
3173 printf("Error block header\n");
3174 return -EINVAL;
3177 ram_decompress_close(s);
3179 return 0;
3182 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3184 ram_addr_t addr;
3185 int flags;
3187 if (version_id == 1)
3188 return ram_load_v1(f, opaque);
3190 if (version_id == 2) {
3191 if (qemu_get_be32(f) != last_ram_offset)
3192 return -EINVAL;
3193 return ram_load_dead(f, opaque);
3196 if (version_id != 3)
3197 return -EINVAL;
3199 do {
3200 addr = qemu_get_be64(f);
3202 flags = addr & ~TARGET_PAGE_MASK;
3203 addr &= TARGET_PAGE_MASK;
3205 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3206 if (addr != last_ram_offset)
3207 return -EINVAL;
3210 if (flags & RAM_SAVE_FLAG_FULL) {
3211 if (ram_load_dead(f, opaque) < 0)
3212 return -EINVAL;
3215 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3216 uint8_t ch = qemu_get_byte(f);
3217 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3218 #ifndef _WIN32
3219 if (ch == 0 &&
3220 (!kvm_enabled() || kvm_has_sync_mmu())) {
3221 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3223 #endif
3224 } else if (flags & RAM_SAVE_FLAG_PAGE)
3225 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3226 } while (!(flags & RAM_SAVE_FLAG_EOS));
3228 return 0;
3231 void qemu_service_io(void)
3233 qemu_notify_event();
3236 /***********************************************************/
3237 /* bottom halves (can be seen as timers which expire ASAP) */
3239 struct QEMUBH {
3240 QEMUBHFunc *cb;
3241 void *opaque;
3242 int scheduled;
3243 int idle;
3244 int deleted;
3245 QEMUBH *next;
3248 static QEMUBH *first_bh = NULL;
3250 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3252 QEMUBH *bh;
3253 bh = qemu_mallocz(sizeof(QEMUBH));
3254 bh->cb = cb;
3255 bh->opaque = opaque;
3256 bh->next = first_bh;
3257 first_bh = bh;
3258 return bh;
3261 int qemu_bh_poll(void)
3263 QEMUBH *bh, **bhp;
3264 int ret;
3266 ret = 0;
3267 for (bh = first_bh; bh; bh = bh->next) {
3268 if (!bh->deleted && bh->scheduled) {
3269 bh->scheduled = 0;
3270 if (!bh->idle)
3271 ret = 1;
3272 bh->idle = 0;
3273 bh->cb(bh->opaque);
3277 /* remove deleted bhs */
3278 bhp = &first_bh;
3279 while (*bhp) {
3280 bh = *bhp;
3281 if (bh->deleted) {
3282 *bhp = bh->next;
3283 qemu_free(bh);
3284 } else
3285 bhp = &bh->next;
3288 return ret;
3291 void qemu_bh_schedule_idle(QEMUBH *bh)
3293 if (bh->scheduled)
3294 return;
3295 bh->scheduled = 1;
3296 bh->idle = 1;
3299 void qemu_bh_schedule(QEMUBH *bh)
3301 if (bh->scheduled)
3302 return;
3303 bh->scheduled = 1;
3304 bh->idle = 0;
3305 /* stop the currently executing CPU to execute the BH ASAP */
3306 qemu_notify_event();
3309 void qemu_bh_cancel(QEMUBH *bh)
3311 bh->scheduled = 0;
3314 void qemu_bh_delete(QEMUBH *bh)
3316 bh->scheduled = 0;
3317 bh->deleted = 1;
3320 static void qemu_bh_update_timeout(int *timeout)
3322 QEMUBH *bh;
3324 for (bh = first_bh; bh; bh = bh->next) {
3325 if (!bh->deleted && bh->scheduled) {
3326 if (bh->idle) {
3327 /* idle bottom halves will be polled at least
3328 * every 10ms */
3329 *timeout = MIN(10, *timeout);
3330 } else {
3331 /* non-idle bottom halves will be executed
3332 * immediately */
3333 *timeout = 0;
3334 break;
3340 /***********************************************************/
3341 /* machine registration */
3343 static QEMUMachine *first_machine = NULL;
3344 QEMUMachine *current_machine = NULL;
3346 int qemu_register_machine(QEMUMachine *m)
3348 QEMUMachine **pm;
3349 pm = &first_machine;
3350 while (*pm != NULL)
3351 pm = &(*pm)->next;
3352 m->next = NULL;
3353 *pm = m;
3354 return 0;
3357 static QEMUMachine *find_machine(const char *name)
3359 QEMUMachine *m;
3361 for(m = first_machine; m != NULL; m = m->next) {
3362 if (!strcmp(m->name, name))
3363 return m;
3365 return NULL;
3368 static QEMUMachine *find_default_machine(void)
3370 QEMUMachine *m;
3372 for(m = first_machine; m != NULL; m = m->next) {
3373 if (m->is_default) {
3374 return m;
3377 return NULL;
3380 /***********************************************************/
3381 /* main execution loop */
3383 static void gui_update(void *opaque)
3385 uint64_t interval = GUI_REFRESH_INTERVAL;
3386 DisplayState *ds = opaque;
3387 DisplayChangeListener *dcl = ds->listeners;
3389 dpy_refresh(ds);
3391 while (dcl != NULL) {
3392 if (dcl->gui_timer_interval &&
3393 dcl->gui_timer_interval < interval)
3394 interval = dcl->gui_timer_interval;
3395 dcl = dcl->next;
3397 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3400 static void nographic_update(void *opaque)
3402 uint64_t interval = GUI_REFRESH_INTERVAL;
3404 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3407 struct vm_change_state_entry {
3408 VMChangeStateHandler *cb;
3409 void *opaque;
3410 LIST_ENTRY (vm_change_state_entry) entries;
3413 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3415 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3416 void *opaque)
3418 VMChangeStateEntry *e;
3420 e = qemu_mallocz(sizeof (*e));
3422 e->cb = cb;
3423 e->opaque = opaque;
3424 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3425 return e;
3428 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3430 LIST_REMOVE (e, entries);
3431 qemu_free (e);
3434 static void vm_state_notify(int running, int reason)
3436 VMChangeStateEntry *e;
3438 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3439 e->cb(e->opaque, running, reason);
3443 static void resume_all_vcpus(void);
3444 static void pause_all_vcpus(void);
3446 void vm_start(void)
3448 if (!vm_running) {
3449 cpu_enable_ticks();
3450 vm_running = 1;
3451 vm_state_notify(1, 0);
3452 qemu_rearm_alarm_timer(alarm_timer);
3453 resume_all_vcpus();
3457 /* reset/shutdown handler */
3459 typedef struct QEMUResetEntry {
3460 QEMUResetHandler *func;
3461 void *opaque;
3462 struct QEMUResetEntry *next;
3463 } QEMUResetEntry;
3465 static QEMUResetEntry *first_reset_entry;
3466 static int reset_requested;
3467 static int shutdown_requested;
3468 static int powerdown_requested;
3469 static int debug_requested;
3470 static int vmstop_requested;
3472 int qemu_no_shutdown(void)
3474 int r = no_shutdown;
3475 no_shutdown = 0;
3476 return r;
3479 int qemu_shutdown_requested(void)
3481 int r = shutdown_requested;
3482 shutdown_requested = 0;
3483 return r;
3486 int qemu_reset_requested(void)
3488 int r = reset_requested;
3489 reset_requested = 0;
3490 return r;
3493 int qemu_powerdown_requested(void)
3495 int r = powerdown_requested;
3496 powerdown_requested = 0;
3497 return r;
3500 static int qemu_debug_requested(void)
3502 int r = debug_requested;
3503 debug_requested = 0;
3504 return r;
3507 static int qemu_vmstop_requested(void)
3509 int r = vmstop_requested;
3510 vmstop_requested = 0;
3511 return r;
3514 static void do_vm_stop(int reason)
3516 if (vm_running) {
3517 cpu_disable_ticks();
3518 vm_running = 0;
3519 pause_all_vcpus();
3520 vm_state_notify(0, reason);
3524 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3526 QEMUResetEntry **pre, *re;
3528 pre = &first_reset_entry;
3529 while (*pre != NULL)
3530 pre = &(*pre)->next;
3531 re = qemu_mallocz(sizeof(QEMUResetEntry));
3532 re->func = func;
3533 re->opaque = opaque;
3534 re->next = NULL;
3535 *pre = re;
3538 void qemu_system_reset(void)
3540 QEMUResetEntry *re;
3542 /* reset all devices */
3543 for(re = first_reset_entry; re != NULL; re = re->next) {
3544 re->func(re->opaque);
3548 void qemu_system_reset_request(void)
3550 if (no_reboot) {
3551 shutdown_requested = 1;
3552 } else {
3553 reset_requested = 1;
3555 if (cpu_single_env) {
3556 qemu_kvm_cpu_stop(cpu_single_env);
3558 qemu_notify_event();
3561 void qemu_system_shutdown_request(void)
3563 shutdown_requested = 1;
3564 qemu_notify_event();
3567 void qemu_system_powerdown_request(void)
3569 powerdown_requested = 1;
3570 qemu_notify_event();
3573 #ifdef CONFIG_IOTHREAD
3574 static void qemu_system_vmstop_request(int reason)
3576 vmstop_requested = reason;
3577 qemu_notify_event();
3579 #endif
3581 #ifndef _WIN32
3582 static int io_thread_fd = -1;
3584 static void qemu_event_increment(void)
3586 static const char byte = 0;
3588 if (io_thread_fd == -1)
3589 return;
3591 write(io_thread_fd, &byte, sizeof(byte));
3594 static void qemu_event_read(void *opaque)
3596 int fd = (unsigned long)opaque;
3597 ssize_t len;
3599 /* Drain the notify pipe */
3600 do {
3601 char buffer[512];
3602 len = read(fd, buffer, sizeof(buffer));
3603 } while ((len == -1 && errno == EINTR) || len > 0);
3606 static int qemu_event_init(void)
3608 int err;
3609 int fds[2];
3611 err = pipe(fds);
3612 if (err == -1)
3613 return -errno;
3615 err = fcntl_setfl(fds[0], O_NONBLOCK);
3616 if (err < 0)
3617 goto fail;
3619 err = fcntl_setfl(fds[1], O_NONBLOCK);
3620 if (err < 0)
3621 goto fail;
3623 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3624 (void *)(unsigned long)fds[0]);
3626 io_thread_fd = fds[1];
3627 return 0;
3629 fail:
3630 close(fds[0]);
3631 close(fds[1]);
3632 return err;
3634 #else
3635 HANDLE qemu_event_handle;
3637 static void dummy_event_handler(void *opaque)
3641 static int qemu_event_init(void)
3643 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3644 if (!qemu_event_handle) {
3645 perror("Failed CreateEvent");
3646 return -1;
3648 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3649 return 0;
3652 static void qemu_event_increment(void)
3654 SetEvent(qemu_event_handle);
3656 #endif
3658 static int cpu_can_run(CPUState *env)
3660 if (env->stop)
3661 return 0;
3662 if (env->stopped)
3663 return 0;
3664 return 1;
3667 #ifndef CONFIG_IOTHREAD
3668 static int qemu_init_main_loop(void)
3670 return qemu_event_init();
3673 void qemu_init_vcpu(void *_env)
3675 CPUState *env = _env;
3677 if (kvm_enabled())
3678 kvm_init_vcpu(env);
3679 return;
3682 int qemu_cpu_self(void *env)
3684 return 1;
3687 static void resume_all_vcpus(void)
3691 static void pause_all_vcpus(void)
3695 void qemu_cpu_kick(void *env)
3697 return;
3700 void qemu_notify_event(void)
3702 CPUState *env = cpu_single_env;
3704 if (kvm_enabled()) {
3705 qemu_kvm_notify_work();
3706 return;
3708 if (env) {
3709 cpu_exit(env);
3710 #ifdef USE_KQEMU
3711 if (env->kqemu_enabled)
3712 kqemu_cpu_interrupt(env);
3713 #endif
3717 #define qemu_mutex_lock_iothread() do { } while (0)
3718 #define qemu_mutex_unlock_iothread() do { } while (0)
3720 void vm_stop(int reason)
3722 do_vm_stop(reason);
3725 #else /* CONFIG_IOTHREAD */
3727 #include "qemu-thread.h"
3729 QemuMutex qemu_global_mutex;
3730 static QemuMutex qemu_fair_mutex;
3732 static QemuThread io_thread;
3734 static QemuThread *tcg_cpu_thread;
3735 static QemuCond *tcg_halt_cond;
3737 static int qemu_system_ready;
3738 /* cpu creation */
3739 static QemuCond qemu_cpu_cond;
3740 /* system init */
3741 static QemuCond qemu_system_cond;
3742 static QemuCond qemu_pause_cond;
3744 static void block_io_signals(void);
3745 static void unblock_io_signals(void);
3746 static int tcg_has_work(void);
3748 static int qemu_init_main_loop(void)
3750 int ret;
3752 ret = qemu_event_init();
3753 if (ret)
3754 return ret;
3756 qemu_cond_init(&qemu_pause_cond);
3757 qemu_mutex_init(&qemu_fair_mutex);
3758 qemu_mutex_init(&qemu_global_mutex);
3759 qemu_mutex_lock(&qemu_global_mutex);
3761 unblock_io_signals();
3762 qemu_thread_self(&io_thread);
3764 return 0;
3767 static void qemu_wait_io_event(CPUState *env)
3769 while (!tcg_has_work())
3770 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3772 qemu_mutex_unlock(&qemu_global_mutex);
3775 * Users of qemu_global_mutex can be starved, having no chance
3776 * to acquire it since this path will get to it first.
3777 * So use another lock to provide fairness.
3779 qemu_mutex_lock(&qemu_fair_mutex);
3780 qemu_mutex_unlock(&qemu_fair_mutex);
3782 qemu_mutex_lock(&qemu_global_mutex);
3783 if (env->stop) {
3784 env->stop = 0;
3785 env->stopped = 1;
3786 qemu_cond_signal(&qemu_pause_cond);
3790 static int qemu_cpu_exec(CPUState *env);
3792 static void *kvm_cpu_thread_fn(void *arg)
3794 CPUState *env = arg;
3796 block_io_signals();
3797 qemu_thread_self(env->thread);
3799 /* signal CPU creation */
3800 qemu_mutex_lock(&qemu_global_mutex);
3801 env->created = 1;
3802 qemu_cond_signal(&qemu_cpu_cond);
3804 /* and wait for machine initialization */
3805 while (!qemu_system_ready)
3806 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3808 while (1) {
3809 if (cpu_can_run(env))
3810 qemu_cpu_exec(env);
3811 qemu_wait_io_event(env);
3814 return NULL;
3817 static void tcg_cpu_exec(void);
3819 static void *tcg_cpu_thread_fn(void *arg)
3821 CPUState *env = arg;
3823 block_io_signals();
3824 qemu_thread_self(env->thread);
3826 /* signal CPU creation */
3827 qemu_mutex_lock(&qemu_global_mutex);
3828 for (env = first_cpu; env != NULL; env = env->next_cpu)
3829 env->created = 1;
3830 qemu_cond_signal(&qemu_cpu_cond);
3832 /* and wait for machine initialization */
3833 while (!qemu_system_ready)
3834 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3836 while (1) {
3837 tcg_cpu_exec();
3838 qemu_wait_io_event(cur_cpu);
3841 return NULL;
3844 void qemu_cpu_kick(void *_env)
3846 CPUState *env = _env;
3847 qemu_cond_broadcast(env->halt_cond);
3848 if (kvm_enabled())
3849 qemu_thread_signal(env->thread, SIGUSR1);
3852 int qemu_cpu_self(void *env)
3854 return (cpu_single_env != NULL);
3857 static void cpu_signal(int sig)
3859 if (cpu_single_env)
3860 cpu_exit(cpu_single_env);
3863 static void block_io_signals(void)
3865 sigset_t set;
3866 struct sigaction sigact;
3868 sigemptyset(&set);
3869 sigaddset(&set, SIGUSR2);
3870 sigaddset(&set, SIGIO);
3871 sigaddset(&set, SIGALRM);
3872 pthread_sigmask(SIG_BLOCK, &set, NULL);
3874 sigemptyset(&set);
3875 sigaddset(&set, SIGUSR1);
3876 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3878 memset(&sigact, 0, sizeof(sigact));
3879 sigact.sa_handler = cpu_signal;
3880 sigaction(SIGUSR1, &sigact, NULL);
3883 static void unblock_io_signals(void)
3885 sigset_t set;
3887 sigemptyset(&set);
3888 sigaddset(&set, SIGUSR2);
3889 sigaddset(&set, SIGIO);
3890 sigaddset(&set, SIGALRM);
3891 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3893 sigemptyset(&set);
3894 sigaddset(&set, SIGUSR1);
3895 pthread_sigmask(SIG_BLOCK, &set, NULL);
3898 static void qemu_signal_lock(unsigned int msecs)
3900 qemu_mutex_lock(&qemu_fair_mutex);
3902 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3903 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3904 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3905 break;
3907 qemu_mutex_unlock(&qemu_fair_mutex);
3910 static void qemu_mutex_lock_iothread(void)
3912 if (kvm_enabled()) {
3913 qemu_mutex_lock(&qemu_fair_mutex);
3914 qemu_mutex_lock(&qemu_global_mutex);
3915 qemu_mutex_unlock(&qemu_fair_mutex);
3916 } else
3917 qemu_signal_lock(100);
3920 static void qemu_mutex_unlock_iothread(void)
3922 qemu_mutex_unlock(&qemu_global_mutex);
3925 static int all_vcpus_paused(void)
3927 CPUState *penv = first_cpu;
3929 while (penv) {
3930 if (!penv->stopped)
3931 return 0;
3932 penv = (CPUState *)penv->next_cpu;
3935 return 1;
3938 static void pause_all_vcpus(void)
3940 CPUState *penv = first_cpu;
3942 while (penv) {
3943 penv->stop = 1;
3944 qemu_thread_signal(penv->thread, SIGUSR1);
3945 qemu_cpu_kick(penv);
3946 penv = (CPUState *)penv->next_cpu;
3949 while (!all_vcpus_paused()) {
3950 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3951 penv = first_cpu;
3952 while (penv) {
3953 qemu_thread_signal(penv->thread, SIGUSR1);
3954 penv = (CPUState *)penv->next_cpu;
3959 static void resume_all_vcpus(void)
3961 CPUState *penv = first_cpu;
3963 while (penv) {
3964 penv->stop = 0;
3965 penv->stopped = 0;
3966 qemu_thread_signal(penv->thread, SIGUSR1);
3967 qemu_cpu_kick(penv);
3968 penv = (CPUState *)penv->next_cpu;
3972 static void tcg_init_vcpu(void *_env)
3974 CPUState *env = _env;
3975 /* share a single thread for all cpus with TCG */
3976 if (!tcg_cpu_thread) {
3977 env->thread = qemu_mallocz(sizeof(QemuThread));
3978 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3979 qemu_cond_init(env->halt_cond);
3980 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3981 while (env->created == 0)
3982 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3983 tcg_cpu_thread = env->thread;
3984 tcg_halt_cond = env->halt_cond;
3985 } else {
3986 env->thread = tcg_cpu_thread;
3987 env->halt_cond = tcg_halt_cond;
3991 static void kvm_start_vcpu(CPUState *env)
3993 kvm_init_vcpu(env);
3994 env->thread = qemu_mallocz(sizeof(QemuThread));
3995 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3996 qemu_cond_init(env->halt_cond);
3997 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3998 while (env->created == 0)
3999 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4002 void qemu_init_vcpu(void *_env)
4004 CPUState *env = _env;
4006 if (kvm_enabled())
4007 kvm_start_vcpu(env);
4008 else
4009 tcg_init_vcpu(env);
4012 void qemu_notify_event(void)
4014 qemu_event_increment();
4017 void vm_stop(int reason)
4019 QemuThread me;
4020 qemu_thread_self(&me);
4022 if (!qemu_thread_equal(&me, &io_thread)) {
4023 qemu_system_vmstop_request(reason);
4025 * FIXME: should not return to device code in case
4026 * vm_stop() has been requested.
4028 if (cpu_single_env) {
4029 cpu_exit(cpu_single_env);
4030 cpu_single_env->stop = 1;
4032 return;
4034 do_vm_stop(reason);
4037 #endif
4040 #ifdef _WIN32
4041 static void host_main_loop_wait(int *timeout)
4043 int ret, ret2, i;
4044 PollingEntry *pe;
4047 /* XXX: need to suppress polling by better using win32 events */
4048 ret = 0;
4049 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4050 ret |= pe->func(pe->opaque);
4052 if (ret == 0) {
4053 int err;
4054 WaitObjects *w = &wait_objects;
4056 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4057 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4058 if (w->func[ret - WAIT_OBJECT_0])
4059 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4061 /* Check for additional signaled events */
4062 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4064 /* Check if event is signaled */
4065 ret2 = WaitForSingleObject(w->events[i], 0);
4066 if(ret2 == WAIT_OBJECT_0) {
4067 if (w->func[i])
4068 w->func[i](w->opaque[i]);
4069 } else if (ret2 == WAIT_TIMEOUT) {
4070 } else {
4071 err = GetLastError();
4072 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4075 } else if (ret == WAIT_TIMEOUT) {
4076 } else {
4077 err = GetLastError();
4078 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4082 *timeout = 0;
4084 #else
4085 static void host_main_loop_wait(int *timeout)
4088 #endif
4090 void main_loop_wait(int timeout)
4092 IOHandlerRecord *ioh;
4093 fd_set rfds, wfds, xfds;
4094 int ret, nfds;
4095 struct timeval tv;
4097 qemu_bh_update_timeout(&timeout);
4099 host_main_loop_wait(&timeout);
4101 /* poll any events */
4102 /* XXX: separate device handlers from system ones */
4103 nfds = -1;
4104 FD_ZERO(&rfds);
4105 FD_ZERO(&wfds);
4106 FD_ZERO(&xfds);
4107 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4108 if (ioh->deleted)
4109 continue;
4110 if (ioh->fd_read &&
4111 (!ioh->fd_read_poll ||
4112 ioh->fd_read_poll(ioh->opaque) != 0)) {
4113 FD_SET(ioh->fd, &rfds);
4114 if (ioh->fd > nfds)
4115 nfds = ioh->fd;
4117 if (ioh->fd_write) {
4118 FD_SET(ioh->fd, &wfds);
4119 if (ioh->fd > nfds)
4120 nfds = ioh->fd;
4124 tv.tv_sec = timeout / 1000;
4125 tv.tv_usec = (timeout % 1000) * 1000;
4127 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4129 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4130 if (ret > 0) {
4131 IOHandlerRecord **pioh;
4133 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4134 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4135 ioh->fd_read(ioh->opaque);
4136 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
4137 FD_CLR(ioh->fd, &rfds);
4139 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4140 ioh->fd_write(ioh->opaque);
4144 /* remove deleted IO handlers */
4145 pioh = &first_io_handler;
4146 while (*pioh) {
4147 ioh = *pioh;
4148 if (ioh->deleted) {
4149 *pioh = ioh->next;
4150 qemu_free(ioh);
4151 } else
4152 pioh = &ioh->next;
4156 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4158 /* rearm timer, if not periodic */
4159 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4160 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4161 qemu_rearm_alarm_timer(alarm_timer);
4164 /* vm time timers */
4165 if (vm_running) {
4166 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4167 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4168 qemu_get_clock(vm_clock));
4171 /* real time timers */
4172 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4173 qemu_get_clock(rt_clock));
4175 /* Check bottom-halves last in case any of the earlier events triggered
4176 them. */
4177 qemu_bh_poll();
4181 static int qemu_cpu_exec(CPUState *env)
4183 int ret;
4184 #ifdef CONFIG_PROFILER
4185 int64_t ti;
4186 #endif
4188 #ifdef CONFIG_PROFILER
4189 ti = profile_getclock();
4190 #endif
4191 if (use_icount) {
4192 int64_t count;
4193 int decr;
4194 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4195 env->icount_decr.u16.low = 0;
4196 env->icount_extra = 0;
4197 count = qemu_next_deadline();
4198 count = (count + (1 << icount_time_shift) - 1)
4199 >> icount_time_shift;
4200 qemu_icount += count;
4201 decr = (count > 0xffff) ? 0xffff : count;
4202 count -= decr;
4203 env->icount_decr.u16.low = decr;
4204 env->icount_extra = count;
4206 ret = cpu_exec(env);
4207 #ifdef CONFIG_PROFILER
4208 qemu_time += profile_getclock() - ti;
4209 #endif
4210 if (use_icount) {
4211 /* Fold pending instructions back into the
4212 instruction counter, and clear the interrupt flag. */
4213 qemu_icount -= (env->icount_decr.u16.low
4214 + env->icount_extra);
4215 env->icount_decr.u32 = 0;
4216 env->icount_extra = 0;
4218 return ret;
4221 static void tcg_cpu_exec(void)
4223 int ret = 0;
4225 if (next_cpu == NULL)
4226 next_cpu = first_cpu;
4227 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4228 CPUState *env = cur_cpu = next_cpu;
4230 if (!vm_running)
4231 break;
4232 if (timer_alarm_pending) {
4233 timer_alarm_pending = 0;
4234 break;
4236 if (cpu_can_run(env))
4237 ret = qemu_cpu_exec(env);
4238 if (ret == EXCP_DEBUG) {
4239 gdb_set_stop_cpu(env);
4240 debug_requested = 1;
4241 break;
4246 static int cpu_has_work(CPUState *env)
4248 if (env->stop)
4249 return 1;
4250 if (env->stopped)
4251 return 0;
4252 if (!env->halted)
4253 return 1;
4254 if (qemu_cpu_has_work(env))
4255 return 1;
4256 return 0;
4259 static int tcg_has_work(void)
4261 CPUState *env;
4263 for (env = first_cpu; env != NULL; env = env->next_cpu)
4264 if (cpu_has_work(env))
4265 return 1;
4266 return 0;
4269 static int qemu_calculate_timeout(void)
4271 #ifndef CONFIG_IOTHREAD
4272 int timeout;
4274 if (!vm_running)
4275 timeout = 5000;
4276 else if (tcg_has_work())
4277 timeout = 0;
4278 else if (!use_icount)
4279 timeout = 5000;
4280 else {
4281 /* XXX: use timeout computed from timers */
4282 int64_t add;
4283 int64_t delta;
4284 /* Advance virtual time to the next event. */
4285 if (use_icount == 1) {
4286 /* When not using an adaptive execution frequency
4287 we tend to get badly out of sync with real time,
4288 so just delay for a reasonable amount of time. */
4289 delta = 0;
4290 } else {
4291 delta = cpu_get_icount() - cpu_get_clock();
4293 if (delta > 0) {
4294 /* If virtual time is ahead of real time then just
4295 wait for IO. */
4296 timeout = (delta / 1000000) + 1;
4297 } else {
4298 /* Wait for either IO to occur or the next
4299 timer event. */
4300 add = qemu_next_deadline();
4301 /* We advance the timer before checking for IO.
4302 Limit the amount we advance so that early IO
4303 activity won't get the guest too far ahead. */
4304 if (add > 10000000)
4305 add = 10000000;
4306 delta += add;
4307 add = (add + (1 << icount_time_shift) - 1)
4308 >> icount_time_shift;
4309 qemu_icount += add;
4310 timeout = delta / 1000000;
4311 if (timeout < 0)
4312 timeout = 0;
4316 return timeout;
4317 #else /* CONFIG_IOTHREAD */
4318 return 1000;
4319 #endif
4322 static int vm_can_run(void)
4324 if (powerdown_requested)
4325 return 0;
4326 if (reset_requested)
4327 return 0;
4328 if (shutdown_requested)
4329 return 0;
4330 if (debug_requested)
4331 return 0;
4332 return 1;
4335 static void main_loop(void)
4337 int r;
4339 if (kvm_enabled()) {
4340 kvm_main_loop();
4341 cpu_disable_ticks();
4342 return;
4345 #ifdef CONFIG_IOTHREAD
4346 qemu_system_ready = 1;
4347 qemu_cond_broadcast(&qemu_system_cond);
4348 #endif
4350 for (;;) {
4351 do {
4352 #ifdef CONFIG_PROFILER
4353 int64_t ti;
4354 #endif
4355 #ifndef CONFIG_IOTHREAD
4356 tcg_cpu_exec();
4357 #endif
4358 #ifdef CONFIG_PROFILER
4359 ti = profile_getclock();
4360 #endif
4361 main_loop_wait(qemu_calculate_timeout());
4362 #ifdef CONFIG_PROFILER
4363 dev_time += profile_getclock() - ti;
4364 #endif
4365 } while (vm_can_run());
4367 if (qemu_debug_requested())
4368 vm_stop(EXCP_DEBUG);
4369 if (qemu_shutdown_requested()) {
4370 if (no_shutdown) {
4371 vm_stop(0);
4372 no_shutdown = 0;
4373 } else
4374 break;
4376 if (qemu_reset_requested()) {
4377 pause_all_vcpus();
4378 qemu_system_reset();
4379 resume_all_vcpus();
4381 if (qemu_powerdown_requested())
4382 qemu_system_powerdown();
4383 if ((r = qemu_vmstop_requested()))
4384 vm_stop(r);
4386 pause_all_vcpus();
4389 static void version(void)
4391 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4394 static void help(int exitcode)
4396 version();
4397 printf("usage: %s [options] [disk_image]\n"
4398 "\n"
4399 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4400 "\n"
4401 #define DEF(option, opt_arg, opt_enum, opt_help) \
4402 opt_help
4403 #define DEFHEADING(text) stringify(text) "\n"
4404 #include "qemu-options.h"
4405 #undef DEF
4406 #undef DEFHEADING
4407 #undef GEN_DOCS
4408 "\n"
4409 "During emulation, the following keys are useful:\n"
4410 "ctrl-alt-f toggle full screen\n"
4411 "ctrl-alt-n switch to virtual console 'n'\n"
4412 "ctrl-alt toggle mouse and keyboard grab\n"
4413 "\n"
4414 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4416 "qemu",
4417 DEFAULT_RAM_SIZE,
4418 #ifndef _WIN32
4419 DEFAULT_NETWORK_SCRIPT,
4420 DEFAULT_NETWORK_DOWN_SCRIPT,
4421 #endif
4422 DEFAULT_GDBSTUB_PORT,
4423 "/tmp/qemu.log");
4424 exit(exitcode);
4427 #define HAS_ARG 0x0001
4429 enum {
4430 #define DEF(option, opt_arg, opt_enum, opt_help) \
4431 opt_enum,
4432 #define DEFHEADING(text)
4433 #include "qemu-options.h"
4434 #undef DEF
4435 #undef DEFHEADING
4436 #undef GEN_DOCS
4439 typedef struct QEMUOption {
4440 const char *name;
4441 int flags;
4442 int index;
4443 } QEMUOption;
4445 static const QEMUOption qemu_options[] = {
4446 { "h", 0, QEMU_OPTION_h },
4447 #define DEF(option, opt_arg, opt_enum, opt_help) \
4448 { option, opt_arg, opt_enum },
4449 #define DEFHEADING(text)
4450 #include "qemu-options.h"
4451 #undef DEF
4452 #undef DEFHEADING
4453 #undef GEN_DOCS
4454 { NULL },
4457 #ifdef HAS_AUDIO
4458 struct soundhw soundhw[] = {
4459 #ifdef HAS_AUDIO_CHOICE
4460 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4462 "pcspk",
4463 "PC speaker",
4466 { .init_isa = pcspk_audio_init }
4468 #endif
4470 #ifdef CONFIG_SB16
4472 "sb16",
4473 "Creative Sound Blaster 16",
4476 { .init_isa = SB16_init }
4478 #endif
4480 #ifdef CONFIG_CS4231A
4482 "cs4231a",
4483 "CS4231A",
4486 { .init_isa = cs4231a_init }
4488 #endif
4490 #ifdef CONFIG_ADLIB
4492 "adlib",
4493 #ifdef HAS_YMF262
4494 "Yamaha YMF262 (OPL3)",
4495 #else
4496 "Yamaha YM3812 (OPL2)",
4497 #endif
4500 { .init_isa = Adlib_init }
4502 #endif
4504 #ifdef CONFIG_GUS
4506 "gus",
4507 "Gravis Ultrasound GF1",
4510 { .init_isa = GUS_init }
4512 #endif
4514 #ifdef CONFIG_AC97
4516 "ac97",
4517 "Intel 82801AA AC97 Audio",
4520 { .init_pci = ac97_init }
4522 #endif
4524 #ifdef CONFIG_ES1370
4526 "es1370",
4527 "ENSONIQ AudioPCI ES1370",
4530 { .init_pci = es1370_init }
4532 #endif
4534 #endif /* HAS_AUDIO_CHOICE */
4536 { NULL, NULL, 0, 0, { NULL } }
4539 static void select_soundhw (const char *optarg)
4541 struct soundhw *c;
4543 if (*optarg == '?') {
4544 show_valid_cards:
4546 printf ("Valid sound card names (comma separated):\n");
4547 for (c = soundhw; c->name; ++c) {
4548 printf ("%-11s %s\n", c->name, c->descr);
4550 printf ("\n-soundhw all will enable all of the above\n");
4551 exit (*optarg != '?');
4553 else {
4554 size_t l;
4555 const char *p;
4556 char *e;
4557 int bad_card = 0;
4559 if (!strcmp (optarg, "all")) {
4560 for (c = soundhw; c->name; ++c) {
4561 c->enabled = 1;
4563 return;
4566 p = optarg;
4567 while (*p) {
4568 e = strchr (p, ',');
4569 l = !e ? strlen (p) : (size_t) (e - p);
4571 for (c = soundhw; c->name; ++c) {
4572 if (!strncmp (c->name, p, l)) {
4573 c->enabled = 1;
4574 break;
4578 if (!c->name) {
4579 if (l > 80) {
4580 fprintf (stderr,
4581 "Unknown sound card name (too big to show)\n");
4583 else {
4584 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4585 (int) l, p);
4587 bad_card = 1;
4589 p += l + (e != NULL);
4592 if (bad_card)
4593 goto show_valid_cards;
4596 #endif
4598 static void select_vgahw (const char *p)
4600 const char *opts;
4602 cirrus_vga_enabled = 0;
4603 std_vga_enabled = 0;
4604 vmsvga_enabled = 0;
4605 xenfb_enabled = 0;
4606 if (strstart(p, "std", &opts)) {
4607 std_vga_enabled = 1;
4608 } else if (strstart(p, "cirrus", &opts)) {
4609 cirrus_vga_enabled = 1;
4610 } else if (strstart(p, "vmware", &opts)) {
4611 vmsvga_enabled = 1;
4612 } else if (strstart(p, "xenfb", &opts)) {
4613 xenfb_enabled = 1;
4614 } else if (!strstart(p, "none", &opts)) {
4615 invalid_vga:
4616 fprintf(stderr, "Unknown vga type: %s\n", p);
4617 exit(1);
4619 while (*opts) {
4620 const char *nextopt;
4622 if (strstart(opts, ",retrace=", &nextopt)) {
4623 opts = nextopt;
4624 if (strstart(opts, "dumb", &nextopt))
4625 vga_retrace_method = VGA_RETRACE_DUMB;
4626 else if (strstart(opts, "precise", &nextopt))
4627 vga_retrace_method = VGA_RETRACE_PRECISE;
4628 else goto invalid_vga;
4629 } else goto invalid_vga;
4630 opts = nextopt;
4634 #ifdef TARGET_I386
4635 static int balloon_parse(const char *arg)
4637 char buf[128];
4638 const char *p;
4640 if (!strcmp(arg, "none")) {
4641 virtio_balloon = 0;
4642 } else if (!strncmp(arg, "virtio", 6)) {
4643 virtio_balloon = 1;
4644 if (arg[6] == ',') {
4645 p = arg + 7;
4646 if (get_param_value(buf, sizeof(buf), "addr", p)) {
4647 virtio_balloon_devaddr = strdup(buf);
4650 } else {
4651 return -1;
4653 return 0;
4655 #endif
4657 #ifdef _WIN32
4658 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4660 exit(STATUS_CONTROL_C_EXIT);
4661 return TRUE;
4663 #endif
4665 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4667 int ret;
4669 if(strlen(str) != 36)
4670 return -1;
4672 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4673 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4674 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4676 if(ret != 16)
4677 return -1;
4679 #ifdef TARGET_I386
4680 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4681 #endif
4683 return 0;
4686 #define MAX_NET_CLIENTS 32
4688 #ifndef _WIN32
4690 static void termsig_handler(int signal)
4692 qemu_system_shutdown_request();
4695 static void sigchld_handler(int signal)
4697 waitpid(-1, NULL, WNOHANG);
4700 static void sighandler_setup(void)
4702 struct sigaction act;
4704 memset(&act, 0, sizeof(act));
4705 act.sa_handler = termsig_handler;
4706 sigaction(SIGINT, &act, NULL);
4707 sigaction(SIGHUP, &act, NULL);
4708 sigaction(SIGTERM, &act, NULL);
4710 act.sa_handler = sigchld_handler;
4711 act.sa_flags = SA_NOCLDSTOP;
4712 sigaction(SIGCHLD, &act, NULL);
4715 #endif
4717 #ifdef _WIN32
4718 /* Look for support files in the same directory as the executable. */
4719 static char *find_datadir(const char *argv0)
4721 char *p;
4722 char buf[MAX_PATH];
4723 DWORD len;
4725 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4726 if (len == 0) {
4727 return NULL;
4730 buf[len] = 0;
4731 p = buf + len - 1;
4732 while (p != buf && *p != '\\')
4733 p--;
4734 *p = 0;
4735 if (access(buf, R_OK) == 0) {
4736 return qemu_strdup(buf);
4738 return NULL;
4740 #else /* !_WIN32 */
4742 /* Find a likely location for support files using the location of the binary.
4743 For installed binaries this will be "$bindir/../share/qemu". When
4744 running from the build tree this will be "$bindir/../pc-bios". */
4745 #define SHARE_SUFFIX "/share/qemu"
4746 #define BUILD_SUFFIX "/pc-bios"
4747 static char *find_datadir(const char *argv0)
4749 char *dir;
4750 char *p = NULL;
4751 char *res;
4752 #ifdef PATH_MAX
4753 char buf[PATH_MAX];
4754 #endif
4755 size_t max_len;
4757 #if defined(__linux__)
4759 int len;
4760 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4761 if (len > 0) {
4762 buf[len] = 0;
4763 p = buf;
4766 #elif defined(__FreeBSD__)
4768 int len;
4769 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4770 if (len > 0) {
4771 buf[len] = 0;
4772 p = buf;
4775 #endif
4776 /* If we don't have any way of figuring out the actual executable
4777 location then try argv[0]. */
4778 if (!p) {
4779 #ifdef PATH_MAX
4780 p = buf;
4781 #endif
4782 p = realpath(argv0, p);
4783 if (!p) {
4784 return NULL;
4787 dir = dirname(p);
4788 dir = dirname(dir);
4790 max_len = strlen(dir) +
4791 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4792 res = qemu_mallocz(max_len);
4793 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4794 if (access(res, R_OK)) {
4795 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4796 if (access(res, R_OK)) {
4797 qemu_free(res);
4798 res = NULL;
4801 #ifndef PATH_MAX
4802 free(p);
4803 #endif
4804 return res;
4806 #undef SHARE_SUFFIX
4807 #undef BUILD_SUFFIX
4808 #endif
4810 char *qemu_find_file(int type, const char *name)
4812 int len;
4813 const char *subdir;
4814 char *buf;
4816 /* If name contains path separators then try it as a straight path. */
4817 if ((strchr(name, '/') || strchr(name, '\\'))
4818 && access(name, R_OK) == 0) {
4819 return strdup(name);
4821 switch (type) {
4822 case QEMU_FILE_TYPE_BIOS:
4823 subdir = "";
4824 break;
4825 case QEMU_FILE_TYPE_KEYMAP:
4826 subdir = "keymaps/";
4827 break;
4828 default:
4829 abort();
4831 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4832 buf = qemu_mallocz(len);
4833 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4834 if (access(buf, R_OK)) {
4835 qemu_free(buf);
4836 return NULL;
4838 return buf;
4841 int main(int argc, char **argv, char **envp)
4843 const char *gdbstub_dev = NULL;
4844 uint32_t boot_devices_bitmap = 0;
4845 int i;
4846 int snapshot, linux_boot, net_boot;
4847 const char *initrd_filename;
4848 const char *kernel_filename, *kernel_cmdline;
4849 const char *boot_devices = "";
4850 DisplayState *ds;
4851 DisplayChangeListener *dcl;
4852 int cyls, heads, secs, translation;
4853 const char *net_clients[MAX_NET_CLIENTS];
4854 int nb_net_clients;
4855 const char *bt_opts[MAX_BT_CMDLINE];
4856 int nb_bt_opts;
4857 int hda_index;
4858 int optind;
4859 const char *r, *optarg;
4860 CharDriverState *monitor_hd = NULL;
4861 const char *monitor_device;
4862 const char *serial_devices[MAX_SERIAL_PORTS];
4863 int serial_device_index;
4864 const char *parallel_devices[MAX_PARALLEL_PORTS];
4865 int parallel_device_index;
4866 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4867 int virtio_console_index;
4868 const char *loadvm = NULL;
4869 QEMUMachine *machine;
4870 const char *cpu_model;
4871 const char *usb_devices[MAX_USB_CMDLINE];
4872 int usb_devices_index;
4873 #ifndef _WIN32
4874 int fds[2];
4875 #endif
4876 int tb_size;
4877 const char *pid_file = NULL;
4878 const char *incoming = NULL;
4879 #ifndef _WIN32
4880 int fd = 0;
4881 struct passwd *pwd = NULL;
4882 const char *chroot_dir = NULL;
4883 const char *run_as = NULL;
4884 #endif
4885 CPUState *env;
4886 int show_vnc_port = 0;
4888 qemu_cache_utils_init(envp);
4890 LIST_INIT (&vm_change_state_head);
4891 #ifndef _WIN32
4893 struct sigaction act;
4894 sigfillset(&act.sa_mask);
4895 act.sa_flags = 0;
4896 act.sa_handler = SIG_IGN;
4897 sigaction(SIGPIPE, &act, NULL);
4899 #else
4900 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4901 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4902 QEMU to run on a single CPU */
4904 HANDLE h;
4905 DWORD mask, smask;
4906 int i;
4907 h = GetCurrentProcess();
4908 if (GetProcessAffinityMask(h, &mask, &smask)) {
4909 for(i = 0; i < 32; i++) {
4910 if (mask & (1 << i))
4911 break;
4913 if (i != 32) {
4914 mask = 1 << i;
4915 SetProcessAffinityMask(h, mask);
4919 #endif
4921 module_call_init(MODULE_INIT_MACHINE);
4922 machine = find_default_machine();
4923 cpu_model = NULL;
4924 initrd_filename = NULL;
4925 ram_size = 0;
4926 snapshot = 0;
4927 kernel_filename = NULL;
4928 kernel_cmdline = "";
4929 cyls = heads = secs = 0;
4930 translation = BIOS_ATA_TRANSLATION_AUTO;
4931 monitor_device = "vc:80Cx24C";
4933 serial_devices[0] = "vc:80Cx24C";
4934 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4935 serial_devices[i] = NULL;
4936 serial_device_index = 0;
4938 parallel_devices[0] = "vc:80Cx24C";
4939 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4940 parallel_devices[i] = NULL;
4941 parallel_device_index = 0;
4943 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4944 virtio_consoles[i] = NULL;
4945 virtio_console_index = 0;
4947 for (i = 0; i < MAX_NODES; i++) {
4948 node_mem[i] = 0;
4949 node_cpumask[i] = 0;
4952 usb_devices_index = 0;
4953 assigned_devices_index = 0;
4955 nb_net_clients = 0;
4956 nb_bt_opts = 0;
4957 nb_drives = 0;
4958 nb_drives_opt = 0;
4959 nb_numa_nodes = 0;
4960 hda_index = -1;
4962 nb_nics = 0;
4964 tb_size = 0;
4965 autostart= 1;
4967 register_watchdogs();
4969 optind = 1;
4970 for(;;) {
4971 if (optind >= argc)
4972 break;
4973 r = argv[optind];
4974 if (r[0] != '-') {
4975 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4976 } else {
4977 const QEMUOption *popt;
4979 optind++;
4980 /* Treat --foo the same as -foo. */
4981 if (r[1] == '-')
4982 r++;
4983 popt = qemu_options;
4984 for(;;) {
4985 if (!popt->name) {
4986 fprintf(stderr, "%s: invalid option -- '%s'\n",
4987 argv[0], r);
4988 exit(1);
4990 if (!strcmp(popt->name, r + 1))
4991 break;
4992 popt++;
4994 if (popt->flags & HAS_ARG) {
4995 if (optind >= argc) {
4996 fprintf(stderr, "%s: option '%s' requires an argument\n",
4997 argv[0], r);
4998 exit(1);
5000 optarg = argv[optind++];
5001 } else {
5002 optarg = NULL;
5005 switch(popt->index) {
5006 case QEMU_OPTION_M:
5007 machine = find_machine(optarg);
5008 if (!machine) {
5009 QEMUMachine *m;
5010 printf("Supported machines are:\n");
5011 for(m = first_machine; m != NULL; m = m->next) {
5012 printf("%-10s %s%s\n",
5013 m->name, m->desc,
5014 m->is_default ? " (default)" : "");
5016 exit(*optarg != '?');
5018 break;
5019 case QEMU_OPTION_cpu:
5020 /* hw initialization will check this */
5021 if (*optarg == '?') {
5022 /* XXX: implement xxx_cpu_list for targets that still miss it */
5023 #if defined(cpu_list)
5024 cpu_list(stdout, &fprintf);
5025 #endif
5026 exit(0);
5027 } else {
5028 cpu_model = optarg;
5030 break;
5031 case QEMU_OPTION_initrd:
5032 initrd_filename = optarg;
5033 break;
5034 case QEMU_OPTION_hda:
5035 if (cyls == 0)
5036 hda_index = drive_add(optarg, HD_ALIAS, 0);
5037 else
5038 hda_index = drive_add(optarg, HD_ALIAS
5039 ",cyls=%d,heads=%d,secs=%d%s",
5040 0, cyls, heads, secs,
5041 translation == BIOS_ATA_TRANSLATION_LBA ?
5042 ",trans=lba" :
5043 translation == BIOS_ATA_TRANSLATION_NONE ?
5044 ",trans=none" : "");
5045 break;
5046 case QEMU_OPTION_hdb:
5047 case QEMU_OPTION_hdc:
5048 case QEMU_OPTION_hdd:
5049 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5050 break;
5051 case QEMU_OPTION_drive:
5052 drive_add(NULL, "%s", optarg);
5053 break;
5054 case QEMU_OPTION_mtdblock:
5055 drive_add(optarg, MTD_ALIAS);
5056 break;
5057 case QEMU_OPTION_sd:
5058 drive_add(optarg, SD_ALIAS);
5059 break;
5060 case QEMU_OPTION_pflash:
5061 drive_add(optarg, PFLASH_ALIAS);
5062 break;
5063 case QEMU_OPTION_snapshot:
5064 snapshot = 1;
5065 break;
5066 case QEMU_OPTION_hdachs:
5068 const char *p;
5069 p = optarg;
5070 cyls = strtol(p, (char **)&p, 0);
5071 if (cyls < 1 || cyls > 16383)
5072 goto chs_fail;
5073 if (*p != ',')
5074 goto chs_fail;
5075 p++;
5076 heads = strtol(p, (char **)&p, 0);
5077 if (heads < 1 || heads > 16)
5078 goto chs_fail;
5079 if (*p != ',')
5080 goto chs_fail;
5081 p++;
5082 secs = strtol(p, (char **)&p, 0);
5083 if (secs < 1 || secs > 63)
5084 goto chs_fail;
5085 if (*p == ',') {
5086 p++;
5087 if (!strcmp(p, "none"))
5088 translation = BIOS_ATA_TRANSLATION_NONE;
5089 else if (!strcmp(p, "lba"))
5090 translation = BIOS_ATA_TRANSLATION_LBA;
5091 else if (!strcmp(p, "auto"))
5092 translation = BIOS_ATA_TRANSLATION_AUTO;
5093 else
5094 goto chs_fail;
5095 } else if (*p != '\0') {
5096 chs_fail:
5097 fprintf(stderr, "qemu: invalid physical CHS format\n");
5098 exit(1);
5100 if (hda_index != -1)
5101 snprintf(drives_opt[hda_index].opt,
5102 sizeof(drives_opt[hda_index].opt),
5103 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5104 0, cyls, heads, secs,
5105 translation == BIOS_ATA_TRANSLATION_LBA ?
5106 ",trans=lba" :
5107 translation == BIOS_ATA_TRANSLATION_NONE ?
5108 ",trans=none" : "");
5110 break;
5111 case QEMU_OPTION_numa:
5112 if (nb_numa_nodes >= MAX_NODES) {
5113 fprintf(stderr, "qemu: too many NUMA nodes\n");
5114 exit(1);
5116 numa_add(optarg);
5117 break;
5118 case QEMU_OPTION_nographic:
5119 display_type = DT_NOGRAPHIC;
5120 break;
5121 #ifdef CONFIG_CURSES
5122 case QEMU_OPTION_curses:
5123 display_type = DT_CURSES;
5124 break;
5125 #endif
5126 case QEMU_OPTION_portrait:
5127 graphic_rotate = 1;
5128 break;
5129 case QEMU_OPTION_kernel:
5130 kernel_filename = optarg;
5131 break;
5132 case QEMU_OPTION_append:
5133 kernel_cmdline = optarg;
5134 break;
5135 case QEMU_OPTION_cdrom:
5136 drive_add(optarg, CDROM_ALIAS);
5137 break;
5138 case QEMU_OPTION_boot:
5139 boot_devices = optarg;
5140 /* We just do some generic consistency checks */
5142 /* Could easily be extended to 64 devices if needed */
5143 const char *p;
5145 boot_devices_bitmap = 0;
5146 for (p = boot_devices; *p != '\0'; p++) {
5147 /* Allowed boot devices are:
5148 * a b : floppy disk drives
5149 * c ... f : IDE disk drives
5150 * g ... m : machine implementation dependant drives
5151 * n ... p : network devices
5152 * It's up to each machine implementation to check
5153 * if the given boot devices match the actual hardware
5154 * implementation and firmware features.
5156 if (*p < 'a' || *p > 'q') {
5157 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5158 exit(1);
5160 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5161 fprintf(stderr,
5162 "Boot device '%c' was given twice\n",*p);
5163 exit(1);
5165 boot_devices_bitmap |= 1 << (*p - 'a');
5168 break;
5169 case QEMU_OPTION_fda:
5170 case QEMU_OPTION_fdb:
5171 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5172 break;
5173 #ifdef TARGET_I386
5174 case QEMU_OPTION_no_fd_bootchk:
5175 fd_bootchk = 0;
5176 break;
5177 #endif
5178 case QEMU_OPTION_net:
5179 if (nb_net_clients >= MAX_NET_CLIENTS) {
5180 fprintf(stderr, "qemu: too many network clients\n");
5181 exit(1);
5183 net_clients[nb_net_clients] = optarg;
5184 nb_net_clients++;
5185 break;
5186 #ifdef CONFIG_SLIRP
5187 case QEMU_OPTION_tftp:
5188 legacy_tftp_prefix = optarg;
5189 break;
5190 case QEMU_OPTION_bootp:
5191 legacy_bootp_filename = optarg;
5192 break;
5193 #ifndef _WIN32
5194 case QEMU_OPTION_smb:
5195 net_slirp_smb(optarg);
5196 break;
5197 #endif
5198 case QEMU_OPTION_redir:
5199 net_slirp_redir(optarg);
5200 break;
5201 #endif
5202 case QEMU_OPTION_bt:
5203 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5204 fprintf(stderr, "qemu: too many bluetooth options\n");
5205 exit(1);
5207 bt_opts[nb_bt_opts++] = optarg;
5208 break;
5209 #ifdef HAS_AUDIO
5210 case QEMU_OPTION_audio_help:
5211 AUD_help ();
5212 exit (0);
5213 break;
5214 case QEMU_OPTION_soundhw:
5215 select_soundhw (optarg);
5216 break;
5217 #endif
5218 case QEMU_OPTION_h:
5219 help(0);
5220 break;
5221 case QEMU_OPTION_version:
5222 version();
5223 exit(0);
5224 break;
5225 case QEMU_OPTION_m: {
5226 uint64_t value;
5227 char *ptr;
5229 value = strtoul(optarg, &ptr, 10);
5230 switch (*ptr) {
5231 case 0: case 'M': case 'm':
5232 value <<= 20;
5233 break;
5234 case 'G': case 'g':
5235 value <<= 30;
5236 break;
5237 default:
5238 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5239 exit(1);
5242 /* On 32-bit hosts, QEMU is limited by virtual address space */
5243 if (value > (2047 << 20)
5244 #ifndef CONFIG_KQEMU
5245 && HOST_LONG_BITS == 32
5246 #endif
5248 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5249 exit(1);
5251 if (value != (uint64_t)(ram_addr_t)value) {
5252 fprintf(stderr, "qemu: ram size too large\n");
5253 exit(1);
5255 ram_size = value;
5256 break;
5258 case QEMU_OPTION_d:
5260 int mask;
5261 const CPULogItem *item;
5263 mask = cpu_str_to_log_mask(optarg);
5264 if (!mask) {
5265 printf("Log items (comma separated):\n");
5266 for(item = cpu_log_items; item->mask != 0; item++) {
5267 printf("%-10s %s\n", item->name, item->help);
5269 exit(1);
5271 cpu_set_log(mask);
5273 break;
5274 case QEMU_OPTION_s:
5275 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5276 break;
5277 case QEMU_OPTION_gdb:
5278 gdbstub_dev = optarg;
5279 break;
5280 case QEMU_OPTION_L:
5281 data_dir = optarg;
5282 break;
5283 case QEMU_OPTION_bios:
5284 bios_name = optarg;
5285 break;
5286 case QEMU_OPTION_singlestep:
5287 singlestep = 1;
5288 break;
5289 case QEMU_OPTION_S:
5290 autostart = 0;
5291 break;
5292 #ifndef _WIN32
5293 case QEMU_OPTION_k:
5294 keyboard_layout = optarg;
5295 break;
5296 #endif
5297 case QEMU_OPTION_localtime:
5298 rtc_utc = 0;
5299 break;
5300 case QEMU_OPTION_vga:
5301 select_vgahw (optarg);
5302 break;
5303 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5304 case QEMU_OPTION_g:
5306 const char *p;
5307 int w, h, depth;
5308 p = optarg;
5309 w = strtol(p, (char **)&p, 10);
5310 if (w <= 0) {
5311 graphic_error:
5312 fprintf(stderr, "qemu: invalid resolution or depth\n");
5313 exit(1);
5315 if (*p != 'x')
5316 goto graphic_error;
5317 p++;
5318 h = strtol(p, (char **)&p, 10);
5319 if (h <= 0)
5320 goto graphic_error;
5321 if (*p == 'x') {
5322 p++;
5323 depth = strtol(p, (char **)&p, 10);
5324 if (depth != 8 && depth != 15 && depth != 16 &&
5325 depth != 24 && depth != 32)
5326 goto graphic_error;
5327 } else if (*p == '\0') {
5328 depth = graphic_depth;
5329 } else {
5330 goto graphic_error;
5333 graphic_width = w;
5334 graphic_height = h;
5335 graphic_depth = depth;
5337 break;
5338 #endif
5339 case QEMU_OPTION_echr:
5341 char *r;
5342 term_escape_char = strtol(optarg, &r, 0);
5343 if (r == optarg)
5344 printf("Bad argument to echr\n");
5345 break;
5347 case QEMU_OPTION_monitor:
5348 monitor_device = optarg;
5349 break;
5350 case QEMU_OPTION_serial:
5351 if (serial_device_index >= MAX_SERIAL_PORTS) {
5352 fprintf(stderr, "qemu: too many serial ports\n");
5353 exit(1);
5355 serial_devices[serial_device_index] = optarg;
5356 serial_device_index++;
5357 break;
5358 case QEMU_OPTION_watchdog:
5359 i = select_watchdog(optarg);
5360 if (i > 0)
5361 exit (i == 1 ? 1 : 0);
5362 break;
5363 case QEMU_OPTION_watchdog_action:
5364 if (select_watchdog_action(optarg) == -1) {
5365 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5366 exit(1);
5368 break;
5369 case QEMU_OPTION_virtiocon:
5370 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5371 fprintf(stderr, "qemu: too many virtio consoles\n");
5372 exit(1);
5374 virtio_consoles[virtio_console_index] = optarg;
5375 virtio_console_index++;
5376 break;
5377 case QEMU_OPTION_parallel:
5378 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5379 fprintf(stderr, "qemu: too many parallel ports\n");
5380 exit(1);
5382 parallel_devices[parallel_device_index] = optarg;
5383 parallel_device_index++;
5384 break;
5385 case QEMU_OPTION_loadvm:
5386 loadvm = optarg;
5387 break;
5388 case QEMU_OPTION_full_screen:
5389 full_screen = 1;
5390 break;
5391 #ifdef CONFIG_SDL
5392 case QEMU_OPTION_no_frame:
5393 no_frame = 1;
5394 break;
5395 case QEMU_OPTION_alt_grab:
5396 alt_grab = 1;
5397 break;
5398 case QEMU_OPTION_no_quit:
5399 no_quit = 1;
5400 break;
5401 case QEMU_OPTION_sdl:
5402 display_type = DT_SDL;
5403 break;
5404 #endif
5405 case QEMU_OPTION_pidfile:
5406 pid_file = optarg;
5407 break;
5408 #ifdef TARGET_I386
5409 case QEMU_OPTION_win2k_hack:
5410 win2k_install_hack = 1;
5411 break;
5412 case QEMU_OPTION_rtc_td_hack:
5413 rtc_td_hack = 1;
5414 break;
5415 case QEMU_OPTION_acpitable:
5416 if(acpi_table_add(optarg) < 0) {
5417 fprintf(stderr, "Wrong acpi table provided\n");
5418 exit(1);
5420 break;
5421 case QEMU_OPTION_smbios:
5422 if(smbios_entry_add(optarg) < 0) {
5423 fprintf(stderr, "Wrong smbios provided\n");
5424 exit(1);
5426 break;
5427 #endif
5428 #ifdef CONFIG_KQEMU
5429 case QEMU_OPTION_enable_kqemu:
5430 kqemu_allowed = 1;
5431 break;
5432 case QEMU_OPTION_kernel_kqemu:
5433 kqemu_allowed = 2;
5434 break;
5435 #endif
5436 #ifdef CONFIG_KVM
5437 #ifdef KVM_UPSTREAM
5438 case QEMU_OPTION_enable_kvm:
5439 kvm_allowed = 1;
5440 #ifdef CONFIG_KQEMU
5441 kqemu_allowed = 0;
5442 #endif
5443 #endif
5444 break;
5445 case QEMU_OPTION_no_kvm:
5446 kvm_allowed = 0;
5447 break;
5448 case QEMU_OPTION_no_kvm_irqchip: {
5449 kvm_irqchip = 0;
5450 kvm_pit = 0;
5451 break;
5453 case QEMU_OPTION_no_kvm_pit: {
5454 kvm_pit = 0;
5455 break;
5457 case QEMU_OPTION_no_kvm_pit_reinjection: {
5458 kvm_pit_reinject = 0;
5459 break;
5461 case QEMU_OPTION_enable_nesting: {
5462 kvm_nested = 1;
5463 break;
5465 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5466 case QEMU_OPTION_pcidevice:
5467 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5468 fprintf(stderr, "Too many assigned devices\n");
5469 exit(1);
5471 assigned_devices[assigned_devices_index] = optarg;
5472 assigned_devices_index++;
5473 break;
5474 #endif
5475 #endif
5476 case QEMU_OPTION_usb:
5477 usb_enabled = 1;
5478 break;
5479 case QEMU_OPTION_usbdevice:
5480 usb_enabled = 1;
5481 if (usb_devices_index >= MAX_USB_CMDLINE) {
5482 fprintf(stderr, "Too many USB devices\n");
5483 exit(1);
5485 usb_devices[usb_devices_index] = optarg;
5486 usb_devices_index++;
5487 break;
5488 case QEMU_OPTION_smp:
5489 smp_cpus = atoi(optarg);
5490 if (smp_cpus < 1) {
5491 fprintf(stderr, "Invalid number of CPUs\n");
5492 exit(1);
5494 break;
5495 case QEMU_OPTION_vnc:
5496 display_type = DT_VNC;
5497 vnc_display = optarg;
5498 break;
5499 #ifdef TARGET_I386
5500 case QEMU_OPTION_no_acpi:
5501 acpi_enabled = 0;
5502 break;
5503 case QEMU_OPTION_no_hpet:
5504 no_hpet = 1;
5505 break;
5506 case QEMU_OPTION_balloon:
5507 if (balloon_parse(optarg) < 0) {
5508 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5509 exit(1);
5511 break;
5512 #endif
5513 case QEMU_OPTION_no_reboot:
5514 no_reboot = 1;
5515 break;
5516 case QEMU_OPTION_no_shutdown:
5517 no_shutdown = 1;
5518 break;
5519 case QEMU_OPTION_show_cursor:
5520 cursor_hide = 0;
5521 break;
5522 case QEMU_OPTION_uuid:
5523 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5524 fprintf(stderr, "Fail to parse UUID string."
5525 " Wrong format.\n");
5526 exit(1);
5528 break;
5529 #ifndef _WIN32
5530 case QEMU_OPTION_daemonize:
5531 daemonize = 1;
5532 break;
5533 #endif
5534 case QEMU_OPTION_option_rom:
5535 if (nb_option_roms >= MAX_OPTION_ROMS) {
5536 fprintf(stderr, "Too many option ROMs\n");
5537 exit(1);
5539 option_rom[nb_option_roms] = optarg;
5540 nb_option_roms++;
5541 break;
5542 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5543 case QEMU_OPTION_semihosting:
5544 semihosting_enabled = 1;
5545 break;
5546 #endif
5547 case QEMU_OPTION_tdf:
5548 time_drift_fix = 1;
5549 break;
5550 case QEMU_OPTION_kvm_shadow_memory:
5551 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5552 break;
5553 case QEMU_OPTION_mempath:
5554 mem_path = optarg;
5555 break;
5556 #ifdef MAP_POPULATE
5557 case QEMU_OPTION_mem_prealloc:
5558 mem_prealloc = !mem_prealloc;
5559 break;
5560 #endif
5561 case QEMU_OPTION_name:
5562 qemu_name = qemu_strdup(optarg);
5564 char *p = strchr(qemu_name, ',');
5565 if (p != NULL) {
5566 *p++ = 0;
5567 if (strncmp(p, "process=", 8)) {
5568 fprintf(stderr, "Unknown subargument %s to -name", p);
5569 exit(1);
5571 p += 8;
5572 set_proc_name(p);
5575 break;
5576 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5577 case QEMU_OPTION_prom_env:
5578 if (nb_prom_envs >= MAX_PROM_ENVS) {
5579 fprintf(stderr, "Too many prom variables\n");
5580 exit(1);
5582 prom_envs[nb_prom_envs] = optarg;
5583 nb_prom_envs++;
5584 break;
5585 #endif
5586 #ifdef TARGET_ARM
5587 case QEMU_OPTION_old_param:
5588 old_param = 1;
5589 break;
5590 #endif
5591 case QEMU_OPTION_clock:
5592 configure_alarms(optarg);
5593 break;
5594 case QEMU_OPTION_startdate:
5596 struct tm tm;
5597 time_t rtc_start_date;
5598 if (!strcmp(optarg, "now")) {
5599 rtc_date_offset = -1;
5600 } else {
5601 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5602 &tm.tm_year,
5603 &tm.tm_mon,
5604 &tm.tm_mday,
5605 &tm.tm_hour,
5606 &tm.tm_min,
5607 &tm.tm_sec) == 6) {
5608 /* OK */
5609 } else if (sscanf(optarg, "%d-%d-%d",
5610 &tm.tm_year,
5611 &tm.tm_mon,
5612 &tm.tm_mday) == 3) {
5613 tm.tm_hour = 0;
5614 tm.tm_min = 0;
5615 tm.tm_sec = 0;
5616 } else {
5617 goto date_fail;
5619 tm.tm_year -= 1900;
5620 tm.tm_mon--;
5621 rtc_start_date = mktimegm(&tm);
5622 if (rtc_start_date == -1) {
5623 date_fail:
5624 fprintf(stderr, "Invalid date format. Valid format are:\n"
5625 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5626 exit(1);
5628 rtc_date_offset = time(NULL) - rtc_start_date;
5631 break;
5632 case QEMU_OPTION_tb_size:
5633 tb_size = strtol(optarg, NULL, 0);
5634 if (tb_size < 0)
5635 tb_size = 0;
5636 break;
5637 case QEMU_OPTION_icount:
5638 use_icount = 1;
5639 if (strcmp(optarg, "auto") == 0) {
5640 icount_time_shift = -1;
5641 } else {
5642 icount_time_shift = strtol(optarg, NULL, 0);
5644 break;
5645 case QEMU_OPTION_incoming:
5646 incoming = optarg;
5647 break;
5648 #ifndef _WIN32
5649 case QEMU_OPTION_chroot:
5650 chroot_dir = optarg;
5651 break;
5652 case QEMU_OPTION_runas:
5653 run_as = optarg;
5654 break;
5655 case QEMU_OPTION_nvram:
5656 nvram = optarg;
5657 break;
5658 #endif
5659 #ifdef CONFIG_XEN
5660 case QEMU_OPTION_xen_domid:
5661 xen_domid = atoi(optarg);
5662 break;
5663 case QEMU_OPTION_xen_create:
5664 xen_mode = XEN_CREATE;
5665 break;
5666 case QEMU_OPTION_xen_attach:
5667 xen_mode = XEN_ATTACH;
5668 break;
5669 #endif
5674 /* If no data_dir is specified then try to find it relative to the
5675 executable path. */
5676 if (!data_dir) {
5677 data_dir = find_datadir(argv[0]);
5679 /* If all else fails use the install patch specified when building. */
5680 if (!data_dir) {
5681 data_dir = CONFIG_QEMU_SHAREDIR;
5684 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5685 if (kvm_allowed && kqemu_allowed) {
5686 fprintf(stderr,
5687 "You can not enable both KVM and kqemu at the same time\n");
5688 exit(1);
5690 #endif
5692 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5693 if (smp_cpus > machine->max_cpus) {
5694 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5695 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5696 machine->max_cpus);
5697 exit(1);
5700 if (display_type == DT_NOGRAPHIC) {
5701 if (serial_device_index == 0)
5702 serial_devices[0] = "stdio";
5703 if (parallel_device_index == 0)
5704 parallel_devices[0] = "null";
5705 if (strncmp(monitor_device, "vc", 2) == 0)
5706 monitor_device = "stdio";
5709 #ifndef _WIN32
5710 if (daemonize) {
5711 pid_t pid;
5713 if (pipe(fds) == -1)
5714 exit(1);
5716 pid = fork();
5717 if (pid > 0) {
5718 uint8_t status;
5719 ssize_t len;
5721 close(fds[1]);
5723 again:
5724 len = read(fds[0], &status, 1);
5725 if (len == -1 && (errno == EINTR))
5726 goto again;
5728 if (len != 1)
5729 exit(1);
5730 else if (status == 1) {
5731 fprintf(stderr, "Could not acquire pidfile\n");
5732 exit(1);
5733 } else
5734 exit(0);
5735 } else if (pid < 0)
5736 exit(1);
5738 setsid();
5740 pid = fork();
5741 if (pid > 0)
5742 exit(0);
5743 else if (pid < 0)
5744 exit(1);
5746 umask(027);
5748 signal(SIGTSTP, SIG_IGN);
5749 signal(SIGTTOU, SIG_IGN);
5750 signal(SIGTTIN, SIG_IGN);
5753 #ifdef CONFIG_KVM
5754 if (kvm_enabled()) {
5755 if (kvm_init(smp_cpus) < 0) {
5756 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5757 #ifdef NO_CPU_EMULATION
5758 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5759 exit(1);
5760 #endif
5761 kvm_allowed = 0;
5764 #endif
5766 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5767 if (daemonize) {
5768 uint8_t status = 1;
5769 write(fds[1], &status, 1);
5770 } else
5771 fprintf(stderr, "Could not acquire pid file\n");
5772 exit(1);
5774 #endif
5776 #ifdef CONFIG_KQEMU
5777 if (smp_cpus > 1)
5778 kqemu_allowed = 0;
5779 #endif
5780 if (qemu_init_main_loop()) {
5781 fprintf(stderr, "qemu_init_main_loop failed\n");
5782 exit(1);
5784 linux_boot = (kernel_filename != NULL);
5786 if (!linux_boot && *kernel_cmdline != '\0') {
5787 fprintf(stderr, "-append only allowed with -kernel option\n");
5788 exit(1);
5791 if (!linux_boot && initrd_filename != NULL) {
5792 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5793 exit(1);
5796 /* boot to floppy or the default cd if no hard disk defined yet */
5797 if (!boot_devices[0]) {
5798 boot_devices = "cad";
5800 setvbuf(stdout, NULL, _IOLBF, 0);
5802 init_timers();
5803 if (init_timer_alarm() < 0) {
5804 fprintf(stderr, "could not initialize alarm timer\n");
5805 exit(1);
5807 if (use_icount && icount_time_shift < 0) {
5808 use_icount = 2;
5809 /* 125MIPS seems a reasonable initial guess at the guest speed.
5810 It will be corrected fairly quickly anyway. */
5811 icount_time_shift = 3;
5812 init_icount_adjust();
5815 #ifdef _WIN32
5816 socket_init();
5817 #endif
5819 /* init network clients */
5820 if (nb_net_clients == 0) {
5821 /* if no clients, we use a default config */
5822 net_clients[nb_net_clients++] = "nic";
5823 #ifdef CONFIG_SLIRP
5824 net_clients[nb_net_clients++] = "user";
5825 #endif
5828 for(i = 0;i < nb_net_clients; i++) {
5829 if (net_client_parse(net_clients[i]) < 0)
5830 exit(1);
5833 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5834 net_set_boot_mask(net_boot);
5836 net_client_check();
5838 /* init the bluetooth world */
5839 for (i = 0; i < nb_bt_opts; i++)
5840 if (bt_parse(bt_opts[i]))
5841 exit(1);
5843 /* init the memory */
5844 if (ram_size == 0)
5845 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5847 if (kvm_enabled()) {
5848 if (kvm_qemu_create_context() < 0) {
5849 fprintf(stderr, "Could not create KVM context\n");
5850 exit(1);
5854 #ifdef CONFIG_KQEMU
5855 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5856 guest ram allocation. It needs to go away. */
5857 if (kqemu_allowed) {
5858 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
5859 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5860 if (!kqemu_phys_ram_base) {
5861 fprintf(stderr, "Could not allocate physical memory\n");
5862 exit(1);
5865 #endif
5867 /* init the dynamic translator */
5868 cpu_exec_init_all(tb_size * 1024 * 1024);
5870 bdrv_init();
5872 /* we always create the cdrom drive, even if no disk is there */
5874 if (nb_drives_opt < MAX_DRIVES)
5875 drive_add(NULL, CDROM_ALIAS);
5877 /* we always create at least one floppy */
5879 if (nb_drives_opt < MAX_DRIVES)
5880 drive_add(NULL, FD_ALIAS, 0);
5882 /* we always create one sd slot, even if no card is in it */
5884 if (nb_drives_opt < MAX_DRIVES)
5885 drive_add(NULL, SD_ALIAS);
5887 /* open the virtual block devices
5888 * note that migration with device
5889 * hot add/remove is broken.
5891 for(i = 0; i < nb_drives_opt; i++)
5892 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5893 exit(1);
5895 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5896 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5898 #ifndef _WIN32
5899 /* must be after terminal init, SDL library changes signal handlers */
5900 sighandler_setup();
5901 #endif
5903 /* Maintain compatibility with multiple stdio monitors */
5904 if (!strcmp(monitor_device,"stdio")) {
5905 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5906 const char *devname = serial_devices[i];
5907 if (devname && !strcmp(devname,"mon:stdio")) {
5908 monitor_device = NULL;
5909 break;
5910 } else if (devname && !strcmp(devname,"stdio")) {
5911 monitor_device = NULL;
5912 serial_devices[i] = "mon:stdio";
5913 break;
5918 if (nb_numa_nodes > 0) {
5919 int i;
5921 if (nb_numa_nodes > smp_cpus) {
5922 nb_numa_nodes = smp_cpus;
5925 /* If no memory size if given for any node, assume the default case
5926 * and distribute the available memory equally across all nodes
5928 for (i = 0; i < nb_numa_nodes; i++) {
5929 if (node_mem[i] != 0)
5930 break;
5932 if (i == nb_numa_nodes) {
5933 uint64_t usedmem = 0;
5935 /* On Linux, the each node's border has to be 8MB aligned,
5936 * the final node gets the rest.
5938 for (i = 0; i < nb_numa_nodes - 1; i++) {
5939 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5940 usedmem += node_mem[i];
5942 node_mem[i] = ram_size - usedmem;
5945 for (i = 0; i < nb_numa_nodes; i++) {
5946 if (node_cpumask[i] != 0)
5947 break;
5949 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5950 * must cope with this anyway, because there are BIOSes out there in
5951 * real machines which also use this scheme.
5953 if (i == nb_numa_nodes) {
5954 for (i = 0; i < smp_cpus; i++) {
5955 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5960 #ifdef KVM_UPSTREAM
5961 if (kvm_enabled()) {
5962 int ret;
5964 ret = kvm_init(smp_cpus);
5965 if (ret < 0) {
5966 fprintf(stderr, "failed to initialize KVM\n");
5967 exit(1);
5970 #endif
5972 if (monitor_device) {
5973 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5974 if (!monitor_hd) {
5975 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5976 exit(1);
5980 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5981 const char *devname = serial_devices[i];
5982 if (devname && strcmp(devname, "none")) {
5983 char label[32];
5984 snprintf(label, sizeof(label), "serial%d", i);
5985 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5986 if (!serial_hds[i]) {
5987 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5988 devname);
5989 exit(1);
5994 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5995 const char *devname = parallel_devices[i];
5996 if (devname && strcmp(devname, "none")) {
5997 char label[32];
5998 snprintf(label, sizeof(label), "parallel%d", i);
5999 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
6000 if (!parallel_hds[i]) {
6001 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6002 devname);
6003 exit(1);
6008 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6009 const char *devname = virtio_consoles[i];
6010 if (devname && strcmp(devname, "none")) {
6011 char label[32];
6012 snprintf(label, sizeof(label), "virtcon%d", i);
6013 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
6014 if (!virtcon_hds[i]) {
6015 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
6016 devname);
6017 exit(1);
6022 module_call_init(MODULE_INIT_DEVICE);
6024 if (kvm_enabled()) {
6025 kvm_init_ap();
6026 #ifdef CONFIG_KVM
6027 if (kvm_irqchip) {
6028 if (!qemu_kvm_has_gsi_routing()) {
6029 irq0override = 0;
6030 #ifdef TARGET_I386
6031 /* if kernel can't do irq routing, interrupt source
6032 * override 0->2 can not be set up as required by hpet,
6033 * so disable hpet.
6035 no_hpet=1;
6036 } else if (!qemu_kvm_has_pit_state2()) {
6037 no_hpet=1;
6039 #else
6041 #endif
6043 #endif
6046 machine->init(ram_size, boot_devices,
6047 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6050 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6051 for (i = 0; i < nb_numa_nodes; i++) {
6052 if (node_cpumask[i] & (1 << env->cpu_index)) {
6053 env->numa_node = i;
6058 current_machine = machine;
6060 /* init USB devices */
6061 if (usb_enabled) {
6062 for(i = 0; i < usb_devices_index; i++) {
6063 if (usb_device_add(usb_devices[i], 0) < 0) {
6064 fprintf(stderr, "Warning: could not add USB device %s\n",
6065 usb_devices[i]);
6070 if (!display_state)
6071 dumb_display_init();
6072 /* just use the first displaystate for the moment */
6073 ds = display_state;
6075 if (display_type == DT_DEFAULT) {
6076 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6077 display_type = DT_SDL;
6078 #else
6079 display_type = DT_VNC;
6080 vnc_display = "localhost:0,to=99";
6081 show_vnc_port = 1;
6082 #endif
6086 switch (display_type) {
6087 case DT_NOGRAPHIC:
6088 break;
6089 #if defined(CONFIG_CURSES)
6090 case DT_CURSES:
6091 curses_display_init(ds, full_screen);
6092 break;
6093 #endif
6094 #if defined(CONFIG_SDL)
6095 case DT_SDL:
6096 sdl_display_init(ds, full_screen, no_frame);
6097 break;
6098 #elif defined(CONFIG_COCOA)
6099 case DT_SDL:
6100 cocoa_display_init(ds, full_screen);
6101 break;
6102 #endif
6103 case DT_VNC:
6104 vnc_display_init(ds);
6105 if (vnc_display_open(ds, vnc_display) < 0)
6106 exit(1);
6108 if (show_vnc_port) {
6109 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6111 break;
6112 default:
6113 break;
6115 dpy_resize(ds);
6117 dcl = ds->listeners;
6118 while (dcl != NULL) {
6119 if (dcl->dpy_refresh != NULL) {
6120 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6121 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6123 dcl = dcl->next;
6126 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6127 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6128 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6131 text_consoles_set_display(display_state);
6132 qemu_chr_initial_reset();
6134 if (monitor_device && monitor_hd)
6135 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6137 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6138 const char *devname = serial_devices[i];
6139 if (devname && strcmp(devname, "none")) {
6140 if (strstart(devname, "vc", 0))
6141 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6145 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6146 const char *devname = parallel_devices[i];
6147 if (devname && strcmp(devname, "none")) {
6148 if (strstart(devname, "vc", 0))
6149 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6153 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6154 const char *devname = virtio_consoles[i];
6155 if (virtcon_hds[i] && devname) {
6156 if (strstart(devname, "vc", 0))
6157 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6161 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6162 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6163 gdbstub_dev);
6164 exit(1);
6167 if (loadvm)
6168 do_loadvm(cur_mon, loadvm);
6170 if (incoming) {
6171 autostart = 0; /* fixme how to deal with -daemonize */
6172 qemu_start_incoming_migration(incoming);
6175 if (autostart)
6176 vm_start();
6178 #ifndef _WIN32
6179 if (daemonize) {
6180 uint8_t status = 0;
6181 ssize_t len;
6183 again1:
6184 len = write(fds[1], &status, 1);
6185 if (len == -1 && (errno == EINTR))
6186 goto again1;
6188 if (len != 1)
6189 exit(1);
6191 chdir("/");
6192 TFR(fd = open("/dev/null", O_RDWR));
6193 if (fd == -1)
6194 exit(1);
6197 if (run_as) {
6198 pwd = getpwnam(run_as);
6199 if (!pwd) {
6200 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6201 exit(1);
6205 if (chroot_dir) {
6206 if (chroot(chroot_dir) < 0) {
6207 fprintf(stderr, "chroot failed\n");
6208 exit(1);
6210 chdir("/");
6213 if (run_as) {
6214 if (setgid(pwd->pw_gid) < 0) {
6215 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6216 exit(1);
6218 if (setuid(pwd->pw_uid) < 0) {
6219 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6220 exit(1);
6222 if (setuid(0) != -1) {
6223 fprintf(stderr, "Dropping privileges failed\n");
6224 exit(1);
6228 if (daemonize) {
6229 dup2(fd, 0);
6230 dup2(fd, 1);
6231 dup2(fd, 2);
6233 close(fd);
6235 #endif
6237 main_loop();
6238 quit_timers();
6239 net_cleanup();
6241 return 0;