Merge commit 'b8c0e7d7c4e9fe3ec00757053a33605eda1c5ac4' into upstream-merge
[qemu-kvm/fedora.git] / vl.c
blobfcdc42f075b8445f3f2e3634696ac9fef4b1f1ea
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];
272 int boot_menu;
274 int nb_numa_nodes;
275 uint64_t node_mem[MAX_NODES];
276 uint64_t node_cpumask[MAX_NODES];
278 static CPUState *cur_cpu;
279 static CPUState *next_cpu;
280 static int timer_alarm_pending = 1;
281 /* Conversion factor from emulated instructions to virtual clock ticks. */
282 static int icount_time_shift;
283 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
284 #define MAX_ICOUNT_SHIFT 10
285 /* Compensate for varying guest execution speed. */
286 static int64_t qemu_icount_bias;
287 static QEMUTimer *icount_rt_timer;
288 static QEMUTimer *icount_vm_timer;
289 static QEMUTimer *nographic_timer;
291 uint8_t qemu_uuid[16];
293 static QEMUBootSetHandler *boot_set_handler;
294 static void *boot_set_opaque;
296 /***********************************************************/
297 /* x86 ISA bus support */
299 target_phys_addr_t isa_mem_base = 0;
300 PicState2 *isa_pic;
302 /***********************************************************/
303 void hw_error(const char *fmt, ...)
305 va_list ap;
306 CPUState *env;
308 va_start(ap, fmt);
309 fprintf(stderr, "qemu: hardware error: ");
310 vfprintf(stderr, fmt, ap);
311 fprintf(stderr, "\n");
312 for(env = first_cpu; env != NULL; env = env->next_cpu) {
313 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
314 #ifdef TARGET_I386
315 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
316 #else
317 cpu_dump_state(env, stderr, fprintf, 0);
318 #endif
320 va_end(ap);
321 abort();
324 static void set_proc_name(const char *s)
326 #ifdef __linux__
327 char name[16];
328 if (!s)
329 return;
330 name[sizeof(name) - 1] = 0;
331 strncpy(name, s, sizeof(name));
332 /* Could rewrite argv[0] too, but that's a bit more complicated.
333 This simple way is enough for `top'. */
334 prctl(PR_SET_NAME, name);
335 #endif
338 /***************/
339 /* ballooning */
341 static QEMUBalloonEvent *qemu_balloon_event;
342 void *qemu_balloon_event_opaque;
344 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
346 qemu_balloon_event = func;
347 qemu_balloon_event_opaque = opaque;
350 void qemu_balloon(ram_addr_t target)
352 if (qemu_balloon_event)
353 qemu_balloon_event(qemu_balloon_event_opaque, target);
356 ram_addr_t qemu_balloon_status(void)
358 if (qemu_balloon_event)
359 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
360 return 0;
363 /***********************************************************/
364 /* keyboard/mouse */
366 static QEMUPutKBDEvent *qemu_put_kbd_event;
367 static void *qemu_put_kbd_event_opaque;
368 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
369 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
371 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
373 qemu_put_kbd_event_opaque = opaque;
374 qemu_put_kbd_event = func;
377 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
378 void *opaque, int absolute,
379 const char *name)
381 QEMUPutMouseEntry *s, *cursor;
383 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
385 s->qemu_put_mouse_event = func;
386 s->qemu_put_mouse_event_opaque = opaque;
387 s->qemu_put_mouse_event_absolute = absolute;
388 s->qemu_put_mouse_event_name = qemu_strdup(name);
389 s->next = NULL;
391 if (!qemu_put_mouse_event_head) {
392 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
393 return s;
396 cursor = qemu_put_mouse_event_head;
397 while (cursor->next != NULL)
398 cursor = cursor->next;
400 cursor->next = s;
401 qemu_put_mouse_event_current = s;
403 return s;
406 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
408 QEMUPutMouseEntry *prev = NULL, *cursor;
410 if (!qemu_put_mouse_event_head || entry == NULL)
411 return;
413 cursor = qemu_put_mouse_event_head;
414 while (cursor != NULL && cursor != entry) {
415 prev = cursor;
416 cursor = cursor->next;
419 if (cursor == NULL) // does not exist or list empty
420 return;
421 else if (prev == NULL) { // entry is head
422 qemu_put_mouse_event_head = cursor->next;
423 if (qemu_put_mouse_event_current == entry)
424 qemu_put_mouse_event_current = cursor->next;
425 qemu_free(entry->qemu_put_mouse_event_name);
426 qemu_free(entry);
427 return;
430 prev->next = entry->next;
432 if (qemu_put_mouse_event_current == entry)
433 qemu_put_mouse_event_current = prev;
435 qemu_free(entry->qemu_put_mouse_event_name);
436 qemu_free(entry);
439 void kbd_put_keycode(int keycode)
441 if (qemu_put_kbd_event) {
442 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
446 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
448 QEMUPutMouseEvent *mouse_event;
449 void *mouse_event_opaque;
450 int width;
452 if (!qemu_put_mouse_event_current) {
453 return;
456 mouse_event =
457 qemu_put_mouse_event_current->qemu_put_mouse_event;
458 mouse_event_opaque =
459 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
461 if (mouse_event) {
462 if (graphic_rotate) {
463 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
464 width = 0x7fff;
465 else
466 width = graphic_width - 1;
467 mouse_event(mouse_event_opaque,
468 width - dy, dx, dz, buttons_state);
469 } else
470 mouse_event(mouse_event_opaque,
471 dx, dy, dz, buttons_state);
475 int kbd_mouse_is_absolute(void)
477 if (!qemu_put_mouse_event_current)
478 return 0;
480 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
483 void do_info_mice(Monitor *mon)
485 QEMUPutMouseEntry *cursor;
486 int index = 0;
488 if (!qemu_put_mouse_event_head) {
489 monitor_printf(mon, "No mouse devices connected\n");
490 return;
493 monitor_printf(mon, "Mouse devices available:\n");
494 cursor = qemu_put_mouse_event_head;
495 while (cursor != NULL) {
496 monitor_printf(mon, "%c Mouse #%d: %s\n",
497 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
498 index, cursor->qemu_put_mouse_event_name);
499 index++;
500 cursor = cursor->next;
504 void do_mouse_set(Monitor *mon, int index)
506 QEMUPutMouseEntry *cursor;
507 int i = 0;
509 if (!qemu_put_mouse_event_head) {
510 monitor_printf(mon, "No mouse devices connected\n");
511 return;
514 cursor = qemu_put_mouse_event_head;
515 while (cursor != NULL && index != i) {
516 i++;
517 cursor = cursor->next;
520 if (cursor != NULL)
521 qemu_put_mouse_event_current = cursor;
522 else
523 monitor_printf(mon, "Mouse at given index not found\n");
526 /* compute with 96 bit intermediate result: (a*b)/c */
527 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
529 union {
530 uint64_t ll;
531 struct {
532 #ifdef WORDS_BIGENDIAN
533 uint32_t high, low;
534 #else
535 uint32_t low, high;
536 #endif
537 } l;
538 } u, res;
539 uint64_t rl, rh;
541 u.ll = a;
542 rl = (uint64_t)u.l.low * (uint64_t)b;
543 rh = (uint64_t)u.l.high * (uint64_t)b;
544 rh += (rl >> 32);
545 res.l.high = rh / c;
546 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
547 return res.ll;
550 /***********************************************************/
551 /* real time host monotonic timer */
553 #define QEMU_TIMER_BASE 1000000000LL
555 #ifdef WIN32
557 static int64_t clock_freq;
559 static void init_get_clock(void)
561 LARGE_INTEGER freq;
562 int ret;
563 ret = QueryPerformanceFrequency(&freq);
564 if (ret == 0) {
565 fprintf(stderr, "Could not calibrate ticks\n");
566 exit(1);
568 clock_freq = freq.QuadPart;
571 static int64_t get_clock(void)
573 LARGE_INTEGER ti;
574 QueryPerformanceCounter(&ti);
575 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
578 #else
580 static int use_rt_clock;
582 static void init_get_clock(void)
584 use_rt_clock = 0;
585 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
586 || defined(__DragonFly__)
588 struct timespec ts;
589 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
590 use_rt_clock = 1;
593 #endif
596 static int64_t get_clock(void)
598 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
599 || defined(__DragonFly__)
600 if (use_rt_clock) {
601 struct timespec ts;
602 clock_gettime(CLOCK_MONOTONIC, &ts);
603 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
604 } else
605 #endif
607 /* XXX: using gettimeofday leads to problems if the date
608 changes, so it should be avoided. */
609 struct timeval tv;
610 gettimeofday(&tv, NULL);
611 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
614 #endif
616 /* Return the virtual CPU time, based on the instruction counter. */
617 static int64_t cpu_get_icount(void)
619 int64_t icount;
620 CPUState *env = cpu_single_env;;
621 icount = qemu_icount;
622 if (env) {
623 if (!can_do_io(env))
624 fprintf(stderr, "Bad clock read\n");
625 icount -= (env->icount_decr.u16.low + env->icount_extra);
627 return qemu_icount_bias + (icount << icount_time_shift);
630 /***********************************************************/
631 /* guest cycle counter */
633 static int64_t cpu_ticks_prev;
634 static int64_t cpu_ticks_offset;
635 static int64_t cpu_clock_offset;
636 static int cpu_ticks_enabled;
638 /* return the host CPU cycle counter and handle stop/restart */
639 int64_t cpu_get_ticks(void)
641 if (use_icount) {
642 return cpu_get_icount();
644 if (!cpu_ticks_enabled) {
645 return cpu_ticks_offset;
646 } else {
647 int64_t ticks;
648 ticks = cpu_get_real_ticks();
649 if (cpu_ticks_prev > ticks) {
650 /* Note: non increasing ticks may happen if the host uses
651 software suspend */
652 cpu_ticks_offset += cpu_ticks_prev - ticks;
654 cpu_ticks_prev = ticks;
655 return ticks + cpu_ticks_offset;
659 /* return the host CPU monotonic timer and handle stop/restart */
660 static int64_t cpu_get_clock(void)
662 int64_t ti;
663 if (!cpu_ticks_enabled) {
664 return cpu_clock_offset;
665 } else {
666 ti = get_clock();
667 return ti + cpu_clock_offset;
671 /* enable cpu_get_ticks() */
672 void cpu_enable_ticks(void)
674 if (!cpu_ticks_enabled) {
675 cpu_ticks_offset -= cpu_get_real_ticks();
676 cpu_clock_offset -= get_clock();
677 cpu_ticks_enabled = 1;
681 /* disable cpu_get_ticks() : the clock is stopped. You must not call
682 cpu_get_ticks() after that. */
683 void cpu_disable_ticks(void)
685 if (cpu_ticks_enabled) {
686 cpu_ticks_offset = cpu_get_ticks();
687 cpu_clock_offset = cpu_get_clock();
688 cpu_ticks_enabled = 0;
692 /***********************************************************/
693 /* timers */
695 #define QEMU_TIMER_REALTIME 0
696 #define QEMU_TIMER_VIRTUAL 1
698 struct QEMUClock {
699 int type;
700 /* XXX: add frequency */
703 struct QEMUTimer {
704 QEMUClock *clock;
705 int64_t expire_time;
706 QEMUTimerCB *cb;
707 void *opaque;
708 struct QEMUTimer *next;
711 struct qemu_alarm_timer {
712 char const *name;
713 unsigned int flags;
715 int (*start)(struct qemu_alarm_timer *t);
716 void (*stop)(struct qemu_alarm_timer *t);
717 void (*rearm)(struct qemu_alarm_timer *t);
718 void *priv;
721 #define ALARM_FLAG_DYNTICKS 0x1
722 #define ALARM_FLAG_EXPIRED 0x2
724 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
726 return t && (t->flags & ALARM_FLAG_DYNTICKS);
729 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
731 if (!alarm_has_dynticks(t))
732 return;
734 t->rearm(t);
737 /* TODO: MIN_TIMER_REARM_US should be optimized */
738 #define MIN_TIMER_REARM_US 250
740 static struct qemu_alarm_timer *alarm_timer;
742 #ifdef _WIN32
744 struct qemu_alarm_win32 {
745 MMRESULT timerId;
746 unsigned int period;
747 } alarm_win32_data = {0, -1};
749 static int win32_start_timer(struct qemu_alarm_timer *t);
750 static void win32_stop_timer(struct qemu_alarm_timer *t);
751 static void win32_rearm_timer(struct qemu_alarm_timer *t);
753 #else
755 static int unix_start_timer(struct qemu_alarm_timer *t);
756 static void unix_stop_timer(struct qemu_alarm_timer *t);
758 #ifdef __linux__
760 static int dynticks_start_timer(struct qemu_alarm_timer *t);
761 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
762 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
764 static int hpet_start_timer(struct qemu_alarm_timer *t);
765 static void hpet_stop_timer(struct qemu_alarm_timer *t);
767 static int rtc_start_timer(struct qemu_alarm_timer *t);
768 static void rtc_stop_timer(struct qemu_alarm_timer *t);
770 #endif /* __linux__ */
772 #endif /* _WIN32 */
774 /* Correlation between real and virtual time is always going to be
775 fairly approximate, so ignore small variation.
776 When the guest is idle real and virtual time will be aligned in
777 the IO wait loop. */
778 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
780 static void icount_adjust(void)
782 int64_t cur_time;
783 int64_t cur_icount;
784 int64_t delta;
785 static int64_t last_delta;
786 /* If the VM is not running, then do nothing. */
787 if (!vm_running)
788 return;
790 cur_time = cpu_get_clock();
791 cur_icount = qemu_get_clock(vm_clock);
792 delta = cur_icount - cur_time;
793 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
794 if (delta > 0
795 && last_delta + ICOUNT_WOBBLE < delta * 2
796 && icount_time_shift > 0) {
797 /* The guest is getting too far ahead. Slow time down. */
798 icount_time_shift--;
800 if (delta < 0
801 && last_delta - ICOUNT_WOBBLE > delta * 2
802 && icount_time_shift < MAX_ICOUNT_SHIFT) {
803 /* The guest is getting too far behind. Speed time up. */
804 icount_time_shift++;
806 last_delta = delta;
807 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
810 static void icount_adjust_rt(void * opaque)
812 qemu_mod_timer(icount_rt_timer,
813 qemu_get_clock(rt_clock) + 1000);
814 icount_adjust();
817 static void icount_adjust_vm(void * opaque)
819 qemu_mod_timer(icount_vm_timer,
820 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
821 icount_adjust();
824 static void init_icount_adjust(void)
826 /* Have both realtime and virtual time triggers for speed adjustment.
827 The realtime trigger catches emulated time passing too slowly,
828 the virtual time trigger catches emulated time passing too fast.
829 Realtime triggers occur even when idle, so use them less frequently
830 than VM triggers. */
831 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
832 qemu_mod_timer(icount_rt_timer,
833 qemu_get_clock(rt_clock) + 1000);
834 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
835 qemu_mod_timer(icount_vm_timer,
836 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
839 static struct qemu_alarm_timer alarm_timers[] = {
840 #ifndef _WIN32
841 #ifdef __linux__
842 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
843 dynticks_stop_timer, dynticks_rearm_timer, NULL},
844 /* HPET - if available - is preferred */
845 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
846 /* ...otherwise try RTC */
847 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
848 #endif
849 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
850 #else
851 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
852 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
853 {"win32", 0, win32_start_timer,
854 win32_stop_timer, NULL, &alarm_win32_data},
855 #endif
856 {NULL, }
859 static void show_available_alarms(void)
861 int i;
863 printf("Available alarm timers, in order of precedence:\n");
864 for (i = 0; alarm_timers[i].name; i++)
865 printf("%s\n", alarm_timers[i].name);
868 static void configure_alarms(char const *opt)
870 int i;
871 int cur = 0;
872 int count = ARRAY_SIZE(alarm_timers) - 1;
873 char *arg;
874 char *name;
875 struct qemu_alarm_timer tmp;
877 if (!strcmp(opt, "?")) {
878 show_available_alarms();
879 exit(0);
882 arg = strdup(opt);
884 /* Reorder the array */
885 name = strtok(arg, ",");
886 while (name) {
887 for (i = 0; i < count && alarm_timers[i].name; i++) {
888 if (!strcmp(alarm_timers[i].name, name))
889 break;
892 if (i == count) {
893 fprintf(stderr, "Unknown clock %s\n", name);
894 goto next;
897 if (i < cur)
898 /* Ignore */
899 goto next;
901 /* Swap */
902 tmp = alarm_timers[i];
903 alarm_timers[i] = alarm_timers[cur];
904 alarm_timers[cur] = tmp;
906 cur++;
907 next:
908 name = strtok(NULL, ",");
911 free(arg);
913 if (cur) {
914 /* Disable remaining timers */
915 for (i = cur; i < count; i++)
916 alarm_timers[i].name = NULL;
917 } else {
918 show_available_alarms();
919 exit(1);
923 QEMUClock *rt_clock;
924 QEMUClock *vm_clock;
926 static QEMUTimer *active_timers[2];
928 static QEMUClock *qemu_new_clock(int type)
930 QEMUClock *clock;
931 clock = qemu_mallocz(sizeof(QEMUClock));
932 clock->type = type;
933 return clock;
936 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
938 QEMUTimer *ts;
940 ts = qemu_mallocz(sizeof(QEMUTimer));
941 ts->clock = clock;
942 ts->cb = cb;
943 ts->opaque = opaque;
944 return ts;
947 void qemu_free_timer(QEMUTimer *ts)
949 qemu_free(ts);
952 /* stop a timer, but do not dealloc it */
953 void qemu_del_timer(QEMUTimer *ts)
955 QEMUTimer **pt, *t;
957 /* NOTE: this code must be signal safe because
958 qemu_timer_expired() can be called from a signal. */
959 pt = &active_timers[ts->clock->type];
960 for(;;) {
961 t = *pt;
962 if (!t)
963 break;
964 if (t == ts) {
965 *pt = t->next;
966 break;
968 pt = &t->next;
972 /* modify the current timer so that it will be fired when current_time
973 >= expire_time. The corresponding callback will be called. */
974 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
976 QEMUTimer **pt, *t;
978 qemu_del_timer(ts);
980 /* add the timer in the sorted list */
981 /* NOTE: this code must be signal safe because
982 qemu_timer_expired() can be called from a signal. */
983 pt = &active_timers[ts->clock->type];
984 for(;;) {
985 t = *pt;
986 if (!t)
987 break;
988 if (t->expire_time > expire_time)
989 break;
990 pt = &t->next;
992 ts->expire_time = expire_time;
993 ts->next = *pt;
994 *pt = ts;
996 /* Rearm if necessary */
997 if (pt == &active_timers[ts->clock->type]) {
998 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
999 qemu_rearm_alarm_timer(alarm_timer);
1001 /* Interrupt execution to force deadline recalculation. */
1002 if (use_icount)
1003 qemu_notify_event();
1007 int qemu_timer_pending(QEMUTimer *ts)
1009 QEMUTimer *t;
1010 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1011 if (t == ts)
1012 return 1;
1014 return 0;
1017 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1019 if (!timer_head)
1020 return 0;
1021 return (timer_head->expire_time <= current_time);
1024 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1026 QEMUTimer *ts;
1028 for(;;) {
1029 ts = *ptimer_head;
1030 if (!ts || ts->expire_time > current_time)
1031 break;
1032 /* remove timer from the list before calling the callback */
1033 *ptimer_head = ts->next;
1034 ts->next = NULL;
1036 /* run the callback (the timer list can be modified) */
1037 ts->cb(ts->opaque);
1041 int64_t qemu_get_clock(QEMUClock *clock)
1043 switch(clock->type) {
1044 case QEMU_TIMER_REALTIME:
1045 return get_clock() / 1000000;
1046 default:
1047 case QEMU_TIMER_VIRTUAL:
1048 if (use_icount) {
1049 return cpu_get_icount();
1050 } else {
1051 return cpu_get_clock();
1056 static void init_timers(void)
1058 init_get_clock();
1059 ticks_per_sec = QEMU_TIMER_BASE;
1060 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1061 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1064 /* save a timer */
1065 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1067 uint64_t expire_time;
1069 if (qemu_timer_pending(ts)) {
1070 expire_time = ts->expire_time;
1071 } else {
1072 expire_time = -1;
1074 qemu_put_be64(f, expire_time);
1077 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1079 uint64_t expire_time;
1081 expire_time = qemu_get_be64(f);
1082 if (expire_time != -1) {
1083 qemu_mod_timer(ts, expire_time);
1084 } else {
1085 qemu_del_timer(ts);
1089 static void timer_save(QEMUFile *f, void *opaque)
1091 if (cpu_ticks_enabled) {
1092 hw_error("cannot save state if virtual timers are running");
1094 qemu_put_be64(f, cpu_ticks_offset);
1095 qemu_put_be64(f, ticks_per_sec);
1096 qemu_put_be64(f, cpu_clock_offset);
1099 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1101 if (version_id != 1 && version_id != 2)
1102 return -EINVAL;
1103 if (cpu_ticks_enabled) {
1104 return -EINVAL;
1106 cpu_ticks_offset=qemu_get_be64(f);
1107 ticks_per_sec=qemu_get_be64(f);
1108 if (version_id == 2) {
1109 cpu_clock_offset=qemu_get_be64(f);
1111 return 0;
1114 static void qemu_event_increment(void);
1116 #ifdef _WIN32
1117 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1118 DWORD_PTR dwUser, DWORD_PTR dw1,
1119 DWORD_PTR dw2)
1120 #else
1121 static void host_alarm_handler(int host_signum)
1122 #endif
1124 #if 0
1125 #define DISP_FREQ 1000
1127 static int64_t delta_min = INT64_MAX;
1128 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1129 static int count;
1130 ti = qemu_get_clock(vm_clock);
1131 if (last_clock != 0) {
1132 delta = ti - last_clock;
1133 if (delta < delta_min)
1134 delta_min = delta;
1135 if (delta > delta_max)
1136 delta_max = delta;
1137 delta_cum += delta;
1138 if (++count == DISP_FREQ) {
1139 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1140 muldiv64(delta_min, 1000000, ticks_per_sec),
1141 muldiv64(delta_max, 1000000, ticks_per_sec),
1142 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1143 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1144 count = 0;
1145 delta_min = INT64_MAX;
1146 delta_max = 0;
1147 delta_cum = 0;
1150 last_clock = ti;
1152 #endif
1153 if (alarm_has_dynticks(alarm_timer) ||
1154 (!use_icount &&
1155 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1156 qemu_get_clock(vm_clock))) ||
1157 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1158 qemu_get_clock(rt_clock))) {
1159 qemu_event_increment();
1160 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1162 #ifndef CONFIG_IOTHREAD
1163 if (next_cpu) {
1164 /* stop the currently executing cpu because a timer occured */
1165 cpu_exit(next_cpu);
1166 #ifdef CONFIG_KQEMU
1167 if (next_cpu->kqemu_enabled) {
1168 kqemu_cpu_interrupt(next_cpu);
1170 #endif
1172 #endif
1173 timer_alarm_pending = 1;
1174 qemu_notify_event();
1178 static int64_t qemu_next_deadline(void)
1180 int64_t delta;
1182 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1183 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1184 qemu_get_clock(vm_clock);
1185 } else {
1186 /* To avoid problems with overflow limit this to 2^32. */
1187 delta = INT32_MAX;
1190 if (delta < 0)
1191 delta = 0;
1193 return delta;
1196 #if defined(__linux__) || defined(_WIN32)
1197 static uint64_t qemu_next_deadline_dyntick(void)
1199 int64_t delta;
1200 int64_t rtdelta;
1202 if (use_icount)
1203 delta = INT32_MAX;
1204 else
1205 delta = (qemu_next_deadline() + 999) / 1000;
1207 if (active_timers[QEMU_TIMER_REALTIME]) {
1208 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1209 qemu_get_clock(rt_clock))*1000;
1210 if (rtdelta < delta)
1211 delta = rtdelta;
1214 if (delta < MIN_TIMER_REARM_US)
1215 delta = MIN_TIMER_REARM_US;
1217 return delta;
1219 #endif
1221 #ifndef _WIN32
1223 /* Sets a specific flag */
1224 static int fcntl_setfl(int fd, int flag)
1226 int flags;
1228 flags = fcntl(fd, F_GETFL);
1229 if (flags == -1)
1230 return -errno;
1232 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1233 return -errno;
1235 return 0;
1238 #if defined(__linux__)
1240 #define RTC_FREQ 1024
1242 static void enable_sigio_timer(int fd)
1244 struct sigaction act;
1246 /* timer signal */
1247 sigfillset(&act.sa_mask);
1248 act.sa_flags = 0;
1249 act.sa_handler = host_alarm_handler;
1251 sigaction(SIGIO, &act, NULL);
1252 fcntl_setfl(fd, O_ASYNC);
1253 fcntl(fd, F_SETOWN, getpid());
1256 static int hpet_start_timer(struct qemu_alarm_timer *t)
1258 struct hpet_info info;
1259 int r, fd;
1261 fd = open("/dev/hpet", O_RDONLY);
1262 if (fd < 0)
1263 return -1;
1265 /* Set frequency */
1266 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1267 if (r < 0) {
1268 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1269 "error, but for better emulation accuracy type:\n"
1270 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1271 goto fail;
1274 /* Check capabilities */
1275 r = ioctl(fd, HPET_INFO, &info);
1276 if (r < 0)
1277 goto fail;
1279 /* Enable periodic mode */
1280 r = ioctl(fd, HPET_EPI, 0);
1281 if (info.hi_flags && (r < 0))
1282 goto fail;
1284 /* Enable interrupt */
1285 r = ioctl(fd, HPET_IE_ON, 0);
1286 if (r < 0)
1287 goto fail;
1289 enable_sigio_timer(fd);
1290 t->priv = (void *)(long)fd;
1292 return 0;
1293 fail:
1294 close(fd);
1295 return -1;
1298 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1300 int fd = (long)t->priv;
1302 close(fd);
1305 static int rtc_start_timer(struct qemu_alarm_timer *t)
1307 int rtc_fd;
1308 unsigned long current_rtc_freq = 0;
1310 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1311 if (rtc_fd < 0)
1312 return -1;
1313 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1314 if (current_rtc_freq != RTC_FREQ &&
1315 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1316 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1317 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1318 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1319 goto fail;
1321 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1322 fail:
1323 close(rtc_fd);
1324 return -1;
1327 enable_sigio_timer(rtc_fd);
1329 t->priv = (void *)(long)rtc_fd;
1331 return 0;
1334 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1336 int rtc_fd = (long)t->priv;
1338 close(rtc_fd);
1341 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1343 struct sigevent ev;
1344 timer_t host_timer;
1345 struct sigaction act;
1347 sigfillset(&act.sa_mask);
1348 act.sa_flags = 0;
1349 act.sa_handler = host_alarm_handler;
1351 sigaction(SIGALRM, &act, NULL);
1354 * Initialize ev struct to 0 to avoid valgrind complaining
1355 * about uninitialized data in timer_create call
1357 memset(&ev, 0, sizeof(ev));
1358 ev.sigev_value.sival_int = 0;
1359 ev.sigev_notify = SIGEV_SIGNAL;
1360 ev.sigev_signo = SIGALRM;
1362 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1363 perror("timer_create");
1365 /* disable dynticks */
1366 fprintf(stderr, "Dynamic Ticks disabled\n");
1368 return -1;
1371 t->priv = (void *)(long)host_timer;
1373 return 0;
1376 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1378 timer_t host_timer = (timer_t)(long)t->priv;
1380 timer_delete(host_timer);
1383 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1385 timer_t host_timer = (timer_t)(long)t->priv;
1386 struct itimerspec timeout;
1387 int64_t nearest_delta_us = INT64_MAX;
1388 int64_t current_us;
1390 if (!active_timers[QEMU_TIMER_REALTIME] &&
1391 !active_timers[QEMU_TIMER_VIRTUAL])
1392 return;
1394 nearest_delta_us = qemu_next_deadline_dyntick();
1396 /* check whether a timer is already running */
1397 if (timer_gettime(host_timer, &timeout)) {
1398 perror("gettime");
1399 fprintf(stderr, "Internal timer error: aborting\n");
1400 exit(1);
1402 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1403 if (current_us && current_us <= nearest_delta_us)
1404 return;
1406 timeout.it_interval.tv_sec = 0;
1407 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1408 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1409 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1410 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1411 perror("settime");
1412 fprintf(stderr, "Internal timer error: aborting\n");
1413 exit(1);
1417 #endif /* defined(__linux__) */
1419 static int unix_start_timer(struct qemu_alarm_timer *t)
1421 struct sigaction act;
1422 struct itimerval itv;
1423 int err;
1425 /* timer signal */
1426 sigfillset(&act.sa_mask);
1427 act.sa_flags = 0;
1428 act.sa_handler = host_alarm_handler;
1430 sigaction(SIGALRM, &act, NULL);
1432 itv.it_interval.tv_sec = 0;
1433 /* for i386 kernel 2.6 to get 1 ms */
1434 itv.it_interval.tv_usec = 999;
1435 itv.it_value.tv_sec = 0;
1436 itv.it_value.tv_usec = 10 * 1000;
1438 err = setitimer(ITIMER_REAL, &itv, NULL);
1439 if (err)
1440 return -1;
1442 return 0;
1445 static void unix_stop_timer(struct qemu_alarm_timer *t)
1447 struct itimerval itv;
1449 memset(&itv, 0, sizeof(itv));
1450 setitimer(ITIMER_REAL, &itv, NULL);
1453 #endif /* !defined(_WIN32) */
1456 #ifdef _WIN32
1458 static int win32_start_timer(struct qemu_alarm_timer *t)
1460 TIMECAPS tc;
1461 struct qemu_alarm_win32 *data = t->priv;
1462 UINT flags;
1464 memset(&tc, 0, sizeof(tc));
1465 timeGetDevCaps(&tc, sizeof(tc));
1467 if (data->period < tc.wPeriodMin)
1468 data->period = tc.wPeriodMin;
1470 timeBeginPeriod(data->period);
1472 flags = TIME_CALLBACK_FUNCTION;
1473 if (alarm_has_dynticks(t))
1474 flags |= TIME_ONESHOT;
1475 else
1476 flags |= TIME_PERIODIC;
1478 data->timerId = timeSetEvent(1, // interval (ms)
1479 data->period, // resolution
1480 host_alarm_handler, // function
1481 (DWORD)t, // parameter
1482 flags);
1484 if (!data->timerId) {
1485 perror("Failed to initialize win32 alarm timer");
1486 timeEndPeriod(data->period);
1487 return -1;
1490 return 0;
1493 static void win32_stop_timer(struct qemu_alarm_timer *t)
1495 struct qemu_alarm_win32 *data = t->priv;
1497 timeKillEvent(data->timerId);
1498 timeEndPeriod(data->period);
1501 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1503 struct qemu_alarm_win32 *data = t->priv;
1504 uint64_t nearest_delta_us;
1506 if (!active_timers[QEMU_TIMER_REALTIME] &&
1507 !active_timers[QEMU_TIMER_VIRTUAL])
1508 return;
1510 nearest_delta_us = qemu_next_deadline_dyntick();
1511 nearest_delta_us /= 1000;
1513 timeKillEvent(data->timerId);
1515 data->timerId = timeSetEvent(1,
1516 data->period,
1517 host_alarm_handler,
1518 (DWORD)t,
1519 TIME_ONESHOT | TIME_PERIODIC);
1521 if (!data->timerId) {
1522 perror("Failed to re-arm win32 alarm timer");
1524 timeEndPeriod(data->period);
1525 exit(1);
1529 #endif /* _WIN32 */
1531 static int init_timer_alarm(void)
1533 struct qemu_alarm_timer *t = NULL;
1534 int i, err = -1;
1536 for (i = 0; alarm_timers[i].name; i++) {
1537 t = &alarm_timers[i];
1539 err = t->start(t);
1540 if (!err)
1541 break;
1544 if (err) {
1545 err = -ENOENT;
1546 goto fail;
1549 alarm_timer = t;
1551 return 0;
1553 fail:
1554 return err;
1557 static void quit_timers(void)
1559 alarm_timer->stop(alarm_timer);
1560 alarm_timer = NULL;
1563 /***********************************************************/
1564 /* host time/date access */
1565 void qemu_get_timedate(struct tm *tm, int offset)
1567 time_t ti;
1568 struct tm *ret;
1570 time(&ti);
1571 ti += offset;
1572 if (rtc_date_offset == -1) {
1573 if (rtc_utc)
1574 ret = gmtime(&ti);
1575 else
1576 ret = localtime(&ti);
1577 } else {
1578 ti -= rtc_date_offset;
1579 ret = gmtime(&ti);
1582 memcpy(tm, ret, sizeof(struct tm));
1585 int qemu_timedate_diff(struct tm *tm)
1587 time_t seconds;
1589 if (rtc_date_offset == -1)
1590 if (rtc_utc)
1591 seconds = mktimegm(tm);
1592 else
1593 seconds = mktime(tm);
1594 else
1595 seconds = mktimegm(tm) + rtc_date_offset;
1597 return seconds - time(NULL);
1600 #ifdef _WIN32
1601 static void socket_cleanup(void)
1603 WSACleanup();
1606 static int socket_init(void)
1608 WSADATA Data;
1609 int ret, err;
1611 ret = WSAStartup(MAKEWORD(2,2), &Data);
1612 if (ret != 0) {
1613 err = WSAGetLastError();
1614 fprintf(stderr, "WSAStartup: %d\n", err);
1615 return -1;
1617 atexit(socket_cleanup);
1618 return 0;
1620 #endif
1622 int get_next_param_value(char *buf, int buf_size,
1623 const char *tag, const char **pstr)
1625 const char *p;
1626 char option[128];
1628 p = *pstr;
1629 for(;;) {
1630 p = get_opt_name(option, sizeof(option), p, '=');
1631 if (*p != '=')
1632 break;
1633 p++;
1634 if (!strcmp(tag, option)) {
1635 *pstr = get_opt_value(buf, buf_size, p);
1636 if (**pstr == ',') {
1637 (*pstr)++;
1639 return strlen(buf);
1640 } else {
1641 p = get_opt_value(NULL, 0, p);
1643 if (*p != ',')
1644 break;
1645 p++;
1647 return 0;
1650 int get_param_value(char *buf, int buf_size,
1651 const char *tag, const char *str)
1653 return get_next_param_value(buf, buf_size, tag, &str);
1656 int check_params(char *buf, int buf_size,
1657 const char * const *params, const char *str)
1659 const char *p;
1660 int i;
1662 p = str;
1663 while (*p != '\0') {
1664 p = get_opt_name(buf, buf_size, p, '=');
1665 if (*p != '=') {
1666 return -1;
1668 p++;
1669 for (i = 0; params[i] != NULL; i++) {
1670 if (!strcmp(params[i], buf)) {
1671 break;
1674 if (params[i] == NULL) {
1675 return -1;
1677 p = get_opt_value(NULL, 0, p);
1678 if (*p != ',') {
1679 break;
1681 p++;
1683 return 0;
1686 /***********************************************************/
1687 /* Bluetooth support */
1688 static int nb_hcis;
1689 static int cur_hci;
1690 static struct HCIInfo *hci_table[MAX_NICS];
1692 static struct bt_vlan_s {
1693 struct bt_scatternet_s net;
1694 int id;
1695 struct bt_vlan_s *next;
1696 } *first_bt_vlan;
1698 /* find or alloc a new bluetooth "VLAN" */
1699 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1701 struct bt_vlan_s **pvlan, *vlan;
1702 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1703 if (vlan->id == id)
1704 return &vlan->net;
1706 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1707 vlan->id = id;
1708 pvlan = &first_bt_vlan;
1709 while (*pvlan != NULL)
1710 pvlan = &(*pvlan)->next;
1711 *pvlan = vlan;
1712 return &vlan->net;
1715 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1719 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1721 return -ENOTSUP;
1724 static struct HCIInfo null_hci = {
1725 .cmd_send = null_hci_send,
1726 .sco_send = null_hci_send,
1727 .acl_send = null_hci_send,
1728 .bdaddr_set = null_hci_addr_set,
1731 struct HCIInfo *qemu_next_hci(void)
1733 if (cur_hci == nb_hcis)
1734 return &null_hci;
1736 return hci_table[cur_hci++];
1739 static struct HCIInfo *hci_init(const char *str)
1741 char *endp;
1742 struct bt_scatternet_s *vlan = 0;
1744 if (!strcmp(str, "null"))
1745 /* null */
1746 return &null_hci;
1747 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1748 /* host[:hciN] */
1749 return bt_host_hci(str[4] ? str + 5 : "hci0");
1750 else if (!strncmp(str, "hci", 3)) {
1751 /* hci[,vlan=n] */
1752 if (str[3]) {
1753 if (!strncmp(str + 3, ",vlan=", 6)) {
1754 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1755 if (*endp)
1756 vlan = 0;
1758 } else
1759 vlan = qemu_find_bt_vlan(0);
1760 if (vlan)
1761 return bt_new_hci(vlan);
1764 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1766 return 0;
1769 static int bt_hci_parse(const char *str)
1771 struct HCIInfo *hci;
1772 bdaddr_t bdaddr;
1774 if (nb_hcis >= MAX_NICS) {
1775 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1776 return -1;
1779 hci = hci_init(str);
1780 if (!hci)
1781 return -1;
1783 bdaddr.b[0] = 0x52;
1784 bdaddr.b[1] = 0x54;
1785 bdaddr.b[2] = 0x00;
1786 bdaddr.b[3] = 0x12;
1787 bdaddr.b[4] = 0x34;
1788 bdaddr.b[5] = 0x56 + nb_hcis;
1789 hci->bdaddr_set(hci, bdaddr.b);
1791 hci_table[nb_hcis++] = hci;
1793 return 0;
1796 static void bt_vhci_add(int vlan_id)
1798 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1800 if (!vlan->slave)
1801 fprintf(stderr, "qemu: warning: adding a VHCI to "
1802 "an empty scatternet %i\n", vlan_id);
1804 bt_vhci_init(bt_new_hci(vlan));
1807 static struct bt_device_s *bt_device_add(const char *opt)
1809 struct bt_scatternet_s *vlan;
1810 int vlan_id = 0;
1811 char *endp = strstr(opt, ",vlan=");
1812 int len = (endp ? endp - opt : strlen(opt)) + 1;
1813 char devname[10];
1815 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1817 if (endp) {
1818 vlan_id = strtol(endp + 6, &endp, 0);
1819 if (*endp) {
1820 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1821 return 0;
1825 vlan = qemu_find_bt_vlan(vlan_id);
1827 if (!vlan->slave)
1828 fprintf(stderr, "qemu: warning: adding a slave device to "
1829 "an empty scatternet %i\n", vlan_id);
1831 if (!strcmp(devname, "keyboard"))
1832 return bt_keyboard_init(vlan);
1834 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1835 return 0;
1838 static int bt_parse(const char *opt)
1840 const char *endp, *p;
1841 int vlan;
1843 if (strstart(opt, "hci", &endp)) {
1844 if (!*endp || *endp == ',') {
1845 if (*endp)
1846 if (!strstart(endp, ",vlan=", 0))
1847 opt = endp + 1;
1849 return bt_hci_parse(opt);
1851 } else if (strstart(opt, "vhci", &endp)) {
1852 if (!*endp || *endp == ',') {
1853 if (*endp) {
1854 if (strstart(endp, ",vlan=", &p)) {
1855 vlan = strtol(p, (char **) &endp, 0);
1856 if (*endp) {
1857 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1858 return 1;
1860 } else {
1861 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1862 return 1;
1864 } else
1865 vlan = 0;
1867 bt_vhci_add(vlan);
1868 return 0;
1870 } else if (strstart(opt, "device:", &endp))
1871 return !bt_device_add(endp);
1873 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1874 return 1;
1877 /***********************************************************/
1878 /* QEMU Block devices */
1880 #define HD_ALIAS "index=%d,media=disk"
1881 #define CDROM_ALIAS "index=2,media=cdrom"
1882 #define FD_ALIAS "index=%d,if=floppy"
1883 #define PFLASH_ALIAS "if=pflash"
1884 #define MTD_ALIAS "if=mtd"
1885 #define SD_ALIAS "index=0,if=sd"
1887 static int drive_opt_get_free_idx(void)
1889 int index;
1891 for (index = 0; index < MAX_DRIVES; index++)
1892 if (!drives_opt[index].used) {
1893 drives_opt[index].used = 1;
1894 return index;
1897 return -1;
1900 static int drive_get_free_idx(void)
1902 int index;
1904 for (index = 0; index < MAX_DRIVES; index++)
1905 if (!drives_table[index].used) {
1906 drives_table[index].used = 1;
1907 return index;
1910 return -1;
1913 int drive_add(const char *file, const char *fmt, ...)
1915 va_list ap;
1916 int index = drive_opt_get_free_idx();
1918 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
1919 fprintf(stderr, "qemu: too many drives\n");
1920 return -1;
1923 drives_opt[index].file = file;
1924 va_start(ap, fmt);
1925 vsnprintf(drives_opt[index].opt,
1926 sizeof(drives_opt[0].opt), fmt, ap);
1927 va_end(ap);
1929 nb_drives_opt++;
1930 return index;
1933 void drive_remove(int index)
1935 drives_opt[index].used = 0;
1936 nb_drives_opt--;
1939 int drive_get_index(BlockInterfaceType type, int bus, int unit)
1941 int index;
1943 /* seek interface, bus and unit */
1945 for (index = 0; index < MAX_DRIVES; index++)
1946 if (drives_table[index].type == type &&
1947 drives_table[index].bus == bus &&
1948 drives_table[index].unit == unit &&
1949 drives_table[index].used)
1950 return index;
1952 return -1;
1955 int drive_get_max_bus(BlockInterfaceType type)
1957 int max_bus;
1958 int index;
1960 max_bus = -1;
1961 for (index = 0; index < nb_drives; index++) {
1962 if(drives_table[index].type == type &&
1963 drives_table[index].bus > max_bus)
1964 max_bus = drives_table[index].bus;
1966 return max_bus;
1969 const char *drive_get_serial(BlockDriverState *bdrv)
1971 int index;
1973 for (index = 0; index < nb_drives; index++)
1974 if (drives_table[index].bdrv == bdrv)
1975 return drives_table[index].serial;
1977 return "\0";
1980 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1982 int index;
1984 for (index = 0; index < nb_drives; index++)
1985 if (drives_table[index].bdrv == bdrv)
1986 return drives_table[index].onerror;
1988 return BLOCK_ERR_STOP_ENOSPC;
1991 static void bdrv_format_print(void *opaque, const char *name)
1993 fprintf(stderr, " %s", name);
1996 void drive_uninit(BlockDriverState *bdrv)
1998 int i;
2000 for (i = 0; i < MAX_DRIVES; i++)
2001 if (drives_table[i].bdrv == bdrv) {
2002 drives_table[i].bdrv = NULL;
2003 drives_table[i].used = 0;
2004 drive_remove(drives_table[i].drive_opt_idx);
2005 nb_drives--;
2006 break;
2010 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2012 char buf[128];
2013 char file[1024];
2014 char devname[128];
2015 char serial[21];
2016 const char *mediastr = "";
2017 BlockInterfaceType type;
2018 enum { MEDIA_DISK, MEDIA_CDROM } media;
2019 int bus_id, unit_id;
2020 int cyls, heads, secs, translation;
2021 BlockDriverState *bdrv;
2022 BlockDriver *drv = NULL;
2023 QEMUMachine *machine = opaque;
2024 int max_devs;
2025 int index;
2026 int cache;
2027 int bdrv_flags, onerror;
2028 const char *devaddr;
2029 int drives_table_idx;
2030 char *str = arg->opt;
2031 static const char * const params[] = { "bus", "unit", "if", "index",
2032 "cyls", "heads", "secs", "trans",
2033 "media", "snapshot", "file",
2034 "cache", "format", "serial",
2035 "werror", "addr",
2036 "boot",
2037 NULL };
2039 if (check_params(buf, sizeof(buf), params, str) < 0) {
2040 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2041 buf, str);
2042 return -1;
2045 file[0] = 0;
2046 cyls = heads = secs = 0;
2047 bus_id = 0;
2048 unit_id = -1;
2049 translation = BIOS_ATA_TRANSLATION_AUTO;
2050 index = -1;
2051 cache = 1;
2053 if (machine->use_scsi) {
2054 type = IF_SCSI;
2055 max_devs = MAX_SCSI_DEVS;
2056 pstrcpy(devname, sizeof(devname), "scsi");
2057 } else {
2058 type = IF_IDE;
2059 max_devs = MAX_IDE_DEVS;
2060 pstrcpy(devname, sizeof(devname), "ide");
2062 media = MEDIA_DISK;
2064 /* extract parameters */
2066 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2067 bus_id = strtol(buf, NULL, 0);
2068 if (bus_id < 0) {
2069 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2070 return -1;
2074 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2075 unit_id = strtol(buf, NULL, 0);
2076 if (unit_id < 0) {
2077 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2078 return -1;
2082 if (get_param_value(buf, sizeof(buf), "if", str)) {
2083 pstrcpy(devname, sizeof(devname), buf);
2084 if (!strcmp(buf, "ide")) {
2085 type = IF_IDE;
2086 max_devs = MAX_IDE_DEVS;
2087 } else if (!strcmp(buf, "scsi")) {
2088 type = IF_SCSI;
2089 max_devs = MAX_SCSI_DEVS;
2090 } else if (!strcmp(buf, "floppy")) {
2091 type = IF_FLOPPY;
2092 max_devs = 0;
2093 } else if (!strcmp(buf, "pflash")) {
2094 type = IF_PFLASH;
2095 max_devs = 0;
2096 } else if (!strcmp(buf, "mtd")) {
2097 type = IF_MTD;
2098 max_devs = 0;
2099 } else if (!strcmp(buf, "sd")) {
2100 type = IF_SD;
2101 max_devs = 0;
2102 } else if (!strcmp(buf, "virtio")) {
2103 type = IF_VIRTIO;
2104 max_devs = 0;
2105 } else if (!strcmp(buf, "xen")) {
2106 type = IF_XEN;
2107 max_devs = 0;
2108 } else {
2109 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2110 return -1;
2114 if (get_param_value(buf, sizeof(buf), "index", str)) {
2115 index = strtol(buf, NULL, 0);
2116 if (index < 0) {
2117 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2118 return -1;
2122 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2123 cyls = strtol(buf, NULL, 0);
2126 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2127 heads = strtol(buf, NULL, 0);
2130 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2131 secs = strtol(buf, NULL, 0);
2134 if (cyls || heads || secs) {
2135 if (cyls < 1 || cyls > 16383) {
2136 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2137 return -1;
2139 if (heads < 1 || heads > 16) {
2140 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2141 return -1;
2143 if (secs < 1 || secs > 63) {
2144 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2145 return -1;
2149 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2150 if (!cyls) {
2151 fprintf(stderr,
2152 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2153 str);
2154 return -1;
2156 if (!strcmp(buf, "none"))
2157 translation = BIOS_ATA_TRANSLATION_NONE;
2158 else if (!strcmp(buf, "lba"))
2159 translation = BIOS_ATA_TRANSLATION_LBA;
2160 else if (!strcmp(buf, "auto"))
2161 translation = BIOS_ATA_TRANSLATION_AUTO;
2162 else {
2163 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2164 return -1;
2168 if (get_param_value(buf, sizeof(buf), "media", str)) {
2169 if (!strcmp(buf, "disk")) {
2170 media = MEDIA_DISK;
2171 } else if (!strcmp(buf, "cdrom")) {
2172 if (cyls || secs || heads) {
2173 fprintf(stderr,
2174 "qemu: '%s' invalid physical CHS format\n", str);
2175 return -1;
2177 media = MEDIA_CDROM;
2178 } else {
2179 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2180 return -1;
2184 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2185 if (!strcmp(buf, "on"))
2186 snapshot = 1;
2187 else if (!strcmp(buf, "off"))
2188 snapshot = 0;
2189 else {
2190 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2191 return -1;
2195 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2196 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2197 cache = 0;
2198 else if (!strcmp(buf, "writethrough"))
2199 cache = 1;
2200 else if (!strcmp(buf, "writeback"))
2201 cache = 2;
2202 else {
2203 fprintf(stderr, "qemu: invalid cache option\n");
2204 return -1;
2208 if (get_param_value(buf, sizeof(buf), "format", str)) {
2209 if (strcmp(buf, "?") == 0) {
2210 fprintf(stderr, "qemu: Supported formats:");
2211 bdrv_iterate_format(bdrv_format_print, NULL);
2212 fprintf(stderr, "\n");
2213 return -1;
2215 drv = bdrv_find_format(buf);
2216 if (!drv) {
2217 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2218 return -1;
2222 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2223 if (!strcmp(buf, "on")) {
2224 if (extboot_drive != -1) {
2225 fprintf(stderr, "qemu: two bootable drives specified\n");
2226 return -1;
2228 extboot_drive = nb_drives;
2229 } else if (strcmp(buf, "off")) {
2230 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2231 return -1;
2235 if (arg->file == NULL)
2236 get_param_value(file, sizeof(file), "file", str);
2237 else
2238 pstrcpy(file, sizeof(file), arg->file);
2240 if (!get_param_value(serial, sizeof(serial), "serial", str))
2241 memset(serial, 0, sizeof(serial));
2243 onerror = BLOCK_ERR_STOP_ENOSPC;
2244 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2245 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2246 fprintf(stderr, "werror is no supported by this format\n");
2247 return -1;
2249 if (!strcmp(buf, "ignore"))
2250 onerror = BLOCK_ERR_IGNORE;
2251 else if (!strcmp(buf, "enospc"))
2252 onerror = BLOCK_ERR_STOP_ENOSPC;
2253 else if (!strcmp(buf, "stop"))
2254 onerror = BLOCK_ERR_STOP_ANY;
2255 else if (!strcmp(buf, "report"))
2256 onerror = BLOCK_ERR_REPORT;
2257 else {
2258 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2259 return -1;
2263 devaddr = NULL;
2264 if (get_param_value(buf, sizeof(buf), "addr", str)) {
2265 if (type != IF_VIRTIO) {
2266 fprintf(stderr, "addr is not supported by in '%s'\n", str);
2267 return -1;
2269 devaddr = strdup(buf);
2272 /* compute bus and unit according index */
2274 if (index != -1) {
2275 if (bus_id != 0 || unit_id != -1) {
2276 fprintf(stderr,
2277 "qemu: '%s' index cannot be used with bus and unit\n", str);
2278 return -1;
2280 if (max_devs == 0)
2282 unit_id = index;
2283 bus_id = 0;
2284 } else {
2285 unit_id = index % max_devs;
2286 bus_id = index / max_devs;
2290 /* if user doesn't specify a unit_id,
2291 * try to find the first free
2294 if (unit_id == -1) {
2295 unit_id = 0;
2296 while (drive_get_index(type, bus_id, unit_id) != -1) {
2297 unit_id++;
2298 if (max_devs && unit_id >= max_devs) {
2299 unit_id -= max_devs;
2300 bus_id++;
2305 /* check unit id */
2307 if (max_devs && unit_id >= max_devs) {
2308 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2309 str, unit_id, max_devs - 1);
2310 return -1;
2314 * ignore multiple definitions
2317 if (drive_get_index(type, bus_id, unit_id) != -1)
2318 return -2;
2320 /* init */
2322 if (type == IF_IDE || type == IF_SCSI)
2323 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2324 if (max_devs)
2325 snprintf(buf, sizeof(buf), "%s%i%s%i",
2326 devname, bus_id, mediastr, unit_id);
2327 else
2328 snprintf(buf, sizeof(buf), "%s%s%i",
2329 devname, mediastr, unit_id);
2330 bdrv = bdrv_new(buf);
2331 drives_table_idx = drive_get_free_idx();
2332 drives_table[drives_table_idx].bdrv = bdrv;
2333 drives_table[drives_table_idx].devaddr = devaddr;
2334 drives_table[drives_table_idx].type = type;
2335 drives_table[drives_table_idx].bus = bus_id;
2336 drives_table[drives_table_idx].unit = unit_id;
2337 drives_table[drives_table_idx].onerror = onerror;
2338 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2339 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2340 nb_drives++;
2342 switch(type) {
2343 case IF_IDE:
2344 case IF_SCSI:
2345 case IF_XEN:
2346 switch(media) {
2347 case MEDIA_DISK:
2348 if (cyls != 0) {
2349 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2350 bdrv_set_translation_hint(bdrv, translation);
2352 break;
2353 case MEDIA_CDROM:
2354 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2355 break;
2357 break;
2358 case IF_SD:
2359 /* FIXME: This isn't really a floppy, but it's a reasonable
2360 approximation. */
2361 case IF_FLOPPY:
2362 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2363 break;
2364 case IF_PFLASH:
2365 case IF_MTD:
2366 case IF_VIRTIO:
2367 break;
2368 case IF_COUNT:
2369 abort();
2371 if (!file[0])
2372 return -2;
2373 bdrv_flags = 0;
2374 if (snapshot) {
2375 bdrv_flags |= BDRV_O_SNAPSHOT;
2376 cache = 2; /* always use write-back with snapshot */
2378 if (cache == 0) /* no caching */
2379 bdrv_flags |= BDRV_O_NOCACHE;
2380 else if (cache == 2) /* write-back */
2381 bdrv_flags |= BDRV_O_CACHE_WB;
2382 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2383 fprintf(stderr, "qemu: could not open disk image %s\n",
2384 file);
2385 return -1;
2387 if (bdrv_key_required(bdrv))
2388 autostart = 0;
2389 return drives_table_idx;
2392 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2394 boot_set_handler = func;
2395 boot_set_opaque = opaque;
2398 int qemu_boot_set(const char *boot_devices)
2400 if (!boot_set_handler) {
2401 return -EINVAL;
2403 return boot_set_handler(boot_set_opaque, boot_devices);
2406 static int parse_bootdevices(char *devices)
2408 /* We just do some generic consistency checks */
2409 const char *p;
2410 int bitmap = 0;
2412 for (p = devices; *p != '\0'; p++) {
2413 /* Allowed boot devices are:
2414 * a-b: floppy disk drives
2415 * c-f: IDE disk drives
2416 * g-m: machine implementation dependant drives
2417 * n-p: network devices
2418 * It's up to each machine implementation to check if the given boot
2419 * devices match the actual hardware implementation and firmware
2420 * features.
2422 if (*p < 'a' || *p > 'p') {
2423 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2424 exit(1);
2426 if (bitmap & (1 << (*p - 'a'))) {
2427 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2428 exit(1);
2430 bitmap |= 1 << (*p - 'a');
2432 return bitmap;
2435 static void restore_boot_devices(void *opaque)
2437 char *standard_boot_devices = opaque;
2439 qemu_boot_set(standard_boot_devices);
2441 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2442 qemu_free(standard_boot_devices);
2445 static void numa_add(const char *optarg)
2447 char option[128];
2448 char *endptr;
2449 unsigned long long value, endvalue;
2450 int nodenr;
2452 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2453 if (!strcmp(option, "node")) {
2454 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2455 nodenr = nb_numa_nodes;
2456 } else {
2457 nodenr = strtoull(option, NULL, 10);
2460 if (get_param_value(option, 128, "mem", optarg) == 0) {
2461 node_mem[nodenr] = 0;
2462 } else {
2463 value = strtoull(option, &endptr, 0);
2464 switch (*endptr) {
2465 case 0: case 'M': case 'm':
2466 value <<= 20;
2467 break;
2468 case 'G': case 'g':
2469 value <<= 30;
2470 break;
2472 node_mem[nodenr] = value;
2474 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2475 node_cpumask[nodenr] = 0;
2476 } else {
2477 value = strtoull(option, &endptr, 10);
2478 if (value >= 64) {
2479 value = 63;
2480 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2481 } else {
2482 if (*endptr == '-') {
2483 endvalue = strtoull(endptr+1, &endptr, 10);
2484 if (endvalue >= 63) {
2485 endvalue = 62;
2486 fprintf(stderr,
2487 "only 63 CPUs in NUMA mode supported.\n");
2489 value = (1 << (endvalue + 1)) - (1 << value);
2490 } else {
2491 value = 1 << value;
2494 node_cpumask[nodenr] = value;
2496 nb_numa_nodes++;
2498 return;
2501 /***********************************************************/
2502 /* USB devices */
2504 static USBPort *used_usb_ports;
2505 static USBPort *free_usb_ports;
2507 /* ??? Maybe change this to register a hub to keep track of the topology. */
2508 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2509 usb_attachfn attach)
2511 port->opaque = opaque;
2512 port->index = index;
2513 port->attach = attach;
2514 port->next = free_usb_ports;
2515 free_usb_ports = port;
2518 int usb_device_add_dev(USBDevice *dev)
2520 USBPort *port;
2522 /* Find a USB port to add the device to. */
2523 port = free_usb_ports;
2524 if (!port->next) {
2525 USBDevice *hub;
2527 /* Create a new hub and chain it on. */
2528 free_usb_ports = NULL;
2529 port->next = used_usb_ports;
2530 used_usb_ports = port;
2532 hub = usb_hub_init(VM_USB_HUB_SIZE);
2533 usb_attach(port, hub);
2534 port = free_usb_ports;
2537 free_usb_ports = port->next;
2538 port->next = used_usb_ports;
2539 used_usb_ports = port;
2540 usb_attach(port, dev);
2541 return 0;
2544 static void usb_msd_password_cb(void *opaque, int err)
2546 USBDevice *dev = opaque;
2548 if (!err)
2549 usb_device_add_dev(dev);
2550 else
2551 dev->handle_destroy(dev);
2554 static int usb_device_add(const char *devname, int is_hotplug)
2556 const char *p;
2557 USBDevice *dev;
2559 if (!free_usb_ports)
2560 return -1;
2562 if (strstart(devname, "host:", &p)) {
2563 dev = usb_host_device_open(p);
2564 } else if (!strcmp(devname, "mouse")) {
2565 dev = usb_mouse_init();
2566 } else if (!strcmp(devname, "tablet")) {
2567 dev = usb_tablet_init();
2568 } else if (!strcmp(devname, "keyboard")) {
2569 dev = usb_keyboard_init();
2570 } else if (strstart(devname, "disk:", &p)) {
2571 BlockDriverState *bs;
2573 dev = usb_msd_init(p);
2574 if (!dev)
2575 return -1;
2576 bs = usb_msd_get_bdrv(dev);
2577 if (bdrv_key_required(bs)) {
2578 autostart = 0;
2579 if (is_hotplug) {
2580 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2581 dev);
2582 return 0;
2585 } else if (!strcmp(devname, "wacom-tablet")) {
2586 dev = usb_wacom_init();
2587 } else if (strstart(devname, "serial:", &p)) {
2588 dev = usb_serial_init(p);
2589 #ifdef CONFIG_BRLAPI
2590 } else if (!strcmp(devname, "braille")) {
2591 dev = usb_baum_init();
2592 #endif
2593 } else if (strstart(devname, "net:", &p)) {
2594 int nic = nb_nics;
2596 if (net_client_init(NULL, "nic", p) < 0)
2597 return -1;
2598 nd_table[nic].model = "usb";
2599 dev = usb_net_init(&nd_table[nic]);
2600 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2601 dev = usb_bt_init(devname[2] ? hci_init(p) :
2602 bt_new_hci(qemu_find_bt_vlan(0)));
2603 } else {
2604 return -1;
2606 if (!dev)
2607 return -1;
2609 return usb_device_add_dev(dev);
2612 int usb_device_del_addr(int bus_num, int addr)
2614 USBPort *port;
2615 USBPort **lastp;
2616 USBDevice *dev;
2618 if (!used_usb_ports)
2619 return -1;
2621 if (bus_num != 0)
2622 return -1;
2624 lastp = &used_usb_ports;
2625 port = used_usb_ports;
2626 while (port && port->dev->addr != addr) {
2627 lastp = &port->next;
2628 port = port->next;
2631 if (!port)
2632 return -1;
2634 dev = port->dev;
2635 *lastp = port->next;
2636 usb_attach(port, NULL);
2637 dev->handle_destroy(dev);
2638 port->next = free_usb_ports;
2639 free_usb_ports = port;
2640 return 0;
2643 static int usb_device_del(const char *devname)
2645 int bus_num, addr;
2646 const char *p;
2648 if (strstart(devname, "host:", &p))
2649 return usb_host_device_close(p);
2651 if (!used_usb_ports)
2652 return -1;
2654 p = strchr(devname, '.');
2655 if (!p)
2656 return -1;
2657 bus_num = strtoul(devname, NULL, 0);
2658 addr = strtoul(p + 1, NULL, 0);
2660 return usb_device_del_addr(bus_num, addr);
2663 void do_usb_add(Monitor *mon, const char *devname)
2665 usb_device_add(devname, 1);
2668 void do_usb_del(Monitor *mon, const char *devname)
2670 usb_device_del(devname);
2673 void usb_info(Monitor *mon)
2675 USBDevice *dev;
2676 USBPort *port;
2677 const char *speed_str;
2679 if (!usb_enabled) {
2680 monitor_printf(mon, "USB support not enabled\n");
2681 return;
2684 for (port = used_usb_ports; port; port = port->next) {
2685 dev = port->dev;
2686 if (!dev)
2687 continue;
2688 switch(dev->speed) {
2689 case USB_SPEED_LOW:
2690 speed_str = "1.5";
2691 break;
2692 case USB_SPEED_FULL:
2693 speed_str = "12";
2694 break;
2695 case USB_SPEED_HIGH:
2696 speed_str = "480";
2697 break;
2698 default:
2699 speed_str = "?";
2700 break;
2702 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2703 0, dev->addr, speed_str, dev->devname);
2707 /***********************************************************/
2708 /* PCMCIA/Cardbus */
2710 static struct pcmcia_socket_entry_s {
2711 PCMCIASocket *socket;
2712 struct pcmcia_socket_entry_s *next;
2713 } *pcmcia_sockets = 0;
2715 void pcmcia_socket_register(PCMCIASocket *socket)
2717 struct pcmcia_socket_entry_s *entry;
2719 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2720 entry->socket = socket;
2721 entry->next = pcmcia_sockets;
2722 pcmcia_sockets = entry;
2725 void pcmcia_socket_unregister(PCMCIASocket *socket)
2727 struct pcmcia_socket_entry_s *entry, **ptr;
2729 ptr = &pcmcia_sockets;
2730 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2731 if (entry->socket == socket) {
2732 *ptr = entry->next;
2733 qemu_free(entry);
2737 void pcmcia_info(Monitor *mon)
2739 struct pcmcia_socket_entry_s *iter;
2741 if (!pcmcia_sockets)
2742 monitor_printf(mon, "No PCMCIA sockets\n");
2744 for (iter = pcmcia_sockets; iter; iter = iter->next)
2745 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2746 iter->socket->attached ? iter->socket->card_string :
2747 "Empty");
2750 /***********************************************************/
2751 /* register display */
2753 struct DisplayAllocator default_allocator = {
2754 defaultallocator_create_displaysurface,
2755 defaultallocator_resize_displaysurface,
2756 defaultallocator_free_displaysurface
2759 void register_displaystate(DisplayState *ds)
2761 DisplayState **s;
2762 s = &display_state;
2763 while (*s != NULL)
2764 s = &(*s)->next;
2765 ds->next = NULL;
2766 *s = ds;
2769 DisplayState *get_displaystate(void)
2771 return display_state;
2774 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2776 if(ds->allocator == &default_allocator) ds->allocator = da;
2777 return ds->allocator;
2780 /* dumb display */
2782 static void dumb_display_init(void)
2784 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2785 ds->allocator = &default_allocator;
2786 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2787 register_displaystate(ds);
2790 /***********************************************************/
2791 /* I/O handling */
2793 typedef struct IOHandlerRecord {
2794 int fd;
2795 IOCanRWHandler *fd_read_poll;
2796 IOHandler *fd_read;
2797 IOHandler *fd_write;
2798 int deleted;
2799 void *opaque;
2800 /* temporary data */
2801 struct pollfd *ufd;
2802 struct IOHandlerRecord *next;
2803 } IOHandlerRecord;
2805 static IOHandlerRecord *first_io_handler;
2807 /* XXX: fd_read_poll should be suppressed, but an API change is
2808 necessary in the character devices to suppress fd_can_read(). */
2809 int qemu_set_fd_handler2(int fd,
2810 IOCanRWHandler *fd_read_poll,
2811 IOHandler *fd_read,
2812 IOHandler *fd_write,
2813 void *opaque)
2815 IOHandlerRecord **pioh, *ioh;
2817 if (!fd_read && !fd_write) {
2818 pioh = &first_io_handler;
2819 for(;;) {
2820 ioh = *pioh;
2821 if (ioh == NULL)
2822 break;
2823 if (ioh->fd == fd) {
2824 ioh->deleted = 1;
2825 break;
2827 pioh = &ioh->next;
2829 } else {
2830 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2831 if (ioh->fd == fd)
2832 goto found;
2834 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2835 ioh->next = first_io_handler;
2836 first_io_handler = ioh;
2837 found:
2838 ioh->fd = fd;
2839 ioh->fd_read_poll = fd_read_poll;
2840 ioh->fd_read = fd_read;
2841 ioh->fd_write = fd_write;
2842 ioh->opaque = opaque;
2843 ioh->deleted = 0;
2845 qemu_notify_event();
2846 return 0;
2849 int qemu_set_fd_handler(int fd,
2850 IOHandler *fd_read,
2851 IOHandler *fd_write,
2852 void *opaque)
2854 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2857 #ifdef _WIN32
2858 /***********************************************************/
2859 /* Polling handling */
2861 typedef struct PollingEntry {
2862 PollingFunc *func;
2863 void *opaque;
2864 struct PollingEntry *next;
2865 } PollingEntry;
2867 static PollingEntry *first_polling_entry;
2869 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2871 PollingEntry **ppe, *pe;
2872 pe = qemu_mallocz(sizeof(PollingEntry));
2873 pe->func = func;
2874 pe->opaque = opaque;
2875 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2876 *ppe = pe;
2877 return 0;
2880 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2882 PollingEntry **ppe, *pe;
2883 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2884 pe = *ppe;
2885 if (pe->func == func && pe->opaque == opaque) {
2886 *ppe = pe->next;
2887 qemu_free(pe);
2888 break;
2893 /***********************************************************/
2894 /* Wait objects support */
2895 typedef struct WaitObjects {
2896 int num;
2897 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2898 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2899 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2900 } WaitObjects;
2902 static WaitObjects wait_objects = {0};
2904 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2906 WaitObjects *w = &wait_objects;
2908 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2909 return -1;
2910 w->events[w->num] = handle;
2911 w->func[w->num] = func;
2912 w->opaque[w->num] = opaque;
2913 w->num++;
2914 return 0;
2917 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2919 int i, found;
2920 WaitObjects *w = &wait_objects;
2922 found = 0;
2923 for (i = 0; i < w->num; i++) {
2924 if (w->events[i] == handle)
2925 found = 1;
2926 if (found) {
2927 w->events[i] = w->events[i + 1];
2928 w->func[i] = w->func[i + 1];
2929 w->opaque[i] = w->opaque[i + 1];
2932 if (found)
2933 w->num--;
2935 #endif
2937 /***********************************************************/
2938 /* ram save/restore */
2940 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2942 int v;
2944 v = qemu_get_byte(f);
2945 switch(v) {
2946 case 0:
2947 if (qemu_get_buffer(f, buf, len) != len)
2948 return -EIO;
2949 break;
2950 case 1:
2951 v = qemu_get_byte(f);
2952 memset(buf, v, len);
2953 break;
2954 default:
2955 return -EINVAL;
2958 if (qemu_file_has_error(f))
2959 return -EIO;
2961 return 0;
2964 static int ram_load_v1(QEMUFile *f, void *opaque)
2966 int ret;
2967 ram_addr_t i;
2969 if (qemu_get_be32(f) != last_ram_offset)
2970 return -EINVAL;
2971 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2972 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
2973 continue;
2974 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2975 if (ret)
2976 return ret;
2978 return 0;
2981 #define BDRV_HASH_BLOCK_SIZE 1024
2982 #define IOBUF_SIZE 4096
2983 #define RAM_CBLOCK_MAGIC 0xfabe
2985 typedef struct RamDecompressState {
2986 z_stream zstream;
2987 QEMUFile *f;
2988 uint8_t buf[IOBUF_SIZE];
2989 } RamDecompressState;
2991 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2993 int ret;
2994 memset(s, 0, sizeof(*s));
2995 s->f = f;
2996 ret = inflateInit(&s->zstream);
2997 if (ret != Z_OK)
2998 return -1;
2999 return 0;
3002 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3004 int ret, clen;
3006 s->zstream.avail_out = len;
3007 s->zstream.next_out = buf;
3008 while (s->zstream.avail_out > 0) {
3009 if (s->zstream.avail_in == 0) {
3010 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3011 return -1;
3012 clen = qemu_get_be16(s->f);
3013 if (clen > IOBUF_SIZE)
3014 return -1;
3015 qemu_get_buffer(s->f, s->buf, clen);
3016 s->zstream.avail_in = clen;
3017 s->zstream.next_in = s->buf;
3019 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3020 if (ret != Z_OK && ret != Z_STREAM_END) {
3021 return -1;
3024 return 0;
3027 static void ram_decompress_close(RamDecompressState *s)
3029 inflateEnd(&s->zstream);
3032 #define RAM_SAVE_FLAG_FULL 0x01
3033 #define RAM_SAVE_FLAG_COMPRESS 0x02
3034 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3035 #define RAM_SAVE_FLAG_PAGE 0x08
3036 #define RAM_SAVE_FLAG_EOS 0x10
3038 static int is_dup_page(uint8_t *page, uint8_t ch)
3040 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3041 uint32_t *array = (uint32_t *)page;
3042 int i;
3044 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3045 if (array[i] != val)
3046 return 0;
3049 return 1;
3052 static int ram_save_block(QEMUFile *f)
3054 static ram_addr_t current_addr = 0;
3055 ram_addr_t saved_addr = current_addr;
3056 ram_addr_t addr = 0;
3057 int found = 0;
3059 while (addr < last_ram_offset) {
3060 if (kvm_enabled() && current_addr == 0) {
3061 int r;
3062 r = kvm_update_dirty_pages_log();
3063 if (r) {
3064 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3065 qemu_file_set_error(f);
3066 return 0;
3069 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3070 uint8_t *p;
3072 cpu_physical_memory_reset_dirty(current_addr,
3073 current_addr + TARGET_PAGE_SIZE,
3074 MIGRATION_DIRTY_FLAG);
3076 p = qemu_get_ram_ptr(current_addr);
3078 if (is_dup_page(p, *p)) {
3079 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3080 qemu_put_byte(f, *p);
3081 } else {
3082 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3083 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3086 found = 1;
3087 break;
3089 addr += TARGET_PAGE_SIZE;
3090 current_addr = (saved_addr + addr) % last_ram_offset;
3093 return found;
3096 static uint64_t bytes_transferred = 0;
3098 static ram_addr_t ram_save_remaining(void)
3100 ram_addr_t addr;
3101 ram_addr_t count = 0;
3103 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3104 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3105 count++;
3108 return count;
3111 uint64_t ram_bytes_remaining(void)
3113 return ram_save_remaining() * TARGET_PAGE_SIZE;
3116 uint64_t ram_bytes_transferred(void)
3118 return bytes_transferred;
3121 uint64_t ram_bytes_total(void)
3123 return last_ram_offset;
3126 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3128 ram_addr_t addr;
3129 uint64_t bytes_transferred_last;
3130 double bwidth = 0;
3131 uint64_t expected_time = 0;
3133 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3134 qemu_file_set_error(f);
3135 return 0;
3138 if (stage == 1) {
3139 /* Make sure all dirty bits are set */
3140 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3141 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3142 cpu_physical_memory_set_dirty(addr);
3145 /* Enable dirty memory tracking */
3146 cpu_physical_memory_set_dirty_tracking(1);
3148 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3151 bytes_transferred_last = bytes_transferred;
3152 bwidth = get_clock();
3154 while (!qemu_file_rate_limit(f)) {
3155 int ret;
3157 ret = ram_save_block(f);
3158 bytes_transferred += ret * TARGET_PAGE_SIZE;
3159 if (ret == 0) /* no more blocks */
3160 break;
3163 bwidth = get_clock() - bwidth;
3164 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3166 /* if we haven't transferred anything this round, force expected_time to a
3167 * a very high value, but without crashing */
3168 if (bwidth == 0)
3169 bwidth = 0.000001;
3171 /* try transferring iterative blocks of memory */
3173 if (stage == 3) {
3175 /* flush all remaining blocks regardless of rate limiting */
3176 while (ram_save_block(f) != 0) {
3177 bytes_transferred += TARGET_PAGE_SIZE;
3179 cpu_physical_memory_set_dirty_tracking(0);
3182 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3184 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3186 return (stage == 2) && (expected_time <= migrate_max_downtime());
3189 static int ram_load_dead(QEMUFile *f, void *opaque)
3191 RamDecompressState s1, *s = &s1;
3192 uint8_t buf[10];
3193 ram_addr_t i;
3195 if (ram_decompress_open(s, f) < 0)
3196 return -EINVAL;
3197 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3198 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3199 continue;
3200 if (ram_decompress_buf(s, buf, 1) < 0) {
3201 fprintf(stderr, "Error while reading ram block header\n");
3202 goto error;
3204 if (buf[0] == 0) {
3205 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3206 BDRV_HASH_BLOCK_SIZE) < 0) {
3207 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3208 goto error;
3210 } else {
3211 error:
3212 printf("Error block header\n");
3213 return -EINVAL;
3216 ram_decompress_close(s);
3218 return 0;
3221 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3223 ram_addr_t addr;
3224 int flags;
3226 if (version_id == 1)
3227 return ram_load_v1(f, opaque);
3229 if (version_id == 2) {
3230 if (qemu_get_be32(f) != last_ram_offset)
3231 return -EINVAL;
3232 return ram_load_dead(f, opaque);
3235 if (version_id != 3)
3236 return -EINVAL;
3238 do {
3239 addr = qemu_get_be64(f);
3241 flags = addr & ~TARGET_PAGE_MASK;
3242 addr &= TARGET_PAGE_MASK;
3244 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3245 if (addr != last_ram_offset)
3246 return -EINVAL;
3249 if (flags & RAM_SAVE_FLAG_FULL) {
3250 if (ram_load_dead(f, opaque) < 0)
3251 return -EINVAL;
3254 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3255 uint8_t ch = qemu_get_byte(f);
3256 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3257 #ifndef _WIN32
3258 if (ch == 0 &&
3259 (!kvm_enabled() || kvm_has_sync_mmu())) {
3260 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3262 #endif
3263 } else if (flags & RAM_SAVE_FLAG_PAGE)
3264 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3265 } while (!(flags & RAM_SAVE_FLAG_EOS));
3267 return 0;
3270 void qemu_service_io(void)
3272 qemu_notify_event();
3275 /***********************************************************/
3276 /* bottom halves (can be seen as timers which expire ASAP) */
3278 struct QEMUBH {
3279 QEMUBHFunc *cb;
3280 void *opaque;
3281 int scheduled;
3282 int idle;
3283 int deleted;
3284 QEMUBH *next;
3287 static QEMUBH *first_bh = NULL;
3289 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3291 QEMUBH *bh;
3292 bh = qemu_mallocz(sizeof(QEMUBH));
3293 bh->cb = cb;
3294 bh->opaque = opaque;
3295 bh->next = first_bh;
3296 first_bh = bh;
3297 return bh;
3300 int qemu_bh_poll(void)
3302 QEMUBH *bh, **bhp;
3303 int ret;
3305 ret = 0;
3306 for (bh = first_bh; bh; bh = bh->next) {
3307 if (!bh->deleted && bh->scheduled) {
3308 bh->scheduled = 0;
3309 if (!bh->idle)
3310 ret = 1;
3311 bh->idle = 0;
3312 bh->cb(bh->opaque);
3316 /* remove deleted bhs */
3317 bhp = &first_bh;
3318 while (*bhp) {
3319 bh = *bhp;
3320 if (bh->deleted) {
3321 *bhp = bh->next;
3322 qemu_free(bh);
3323 } else
3324 bhp = &bh->next;
3327 return ret;
3330 void qemu_bh_schedule_idle(QEMUBH *bh)
3332 if (bh->scheduled)
3333 return;
3334 bh->scheduled = 1;
3335 bh->idle = 1;
3338 void qemu_bh_schedule(QEMUBH *bh)
3340 if (bh->scheduled)
3341 return;
3342 bh->scheduled = 1;
3343 bh->idle = 0;
3344 /* stop the currently executing CPU to execute the BH ASAP */
3345 qemu_notify_event();
3348 void qemu_bh_cancel(QEMUBH *bh)
3350 bh->scheduled = 0;
3353 void qemu_bh_delete(QEMUBH *bh)
3355 bh->scheduled = 0;
3356 bh->deleted = 1;
3359 static void qemu_bh_update_timeout(int *timeout)
3361 QEMUBH *bh;
3363 for (bh = first_bh; bh; bh = bh->next) {
3364 if (!bh->deleted && bh->scheduled) {
3365 if (bh->idle) {
3366 /* idle bottom halves will be polled at least
3367 * every 10ms */
3368 *timeout = MIN(10, *timeout);
3369 } else {
3370 /* non-idle bottom halves will be executed
3371 * immediately */
3372 *timeout = 0;
3373 break;
3379 /***********************************************************/
3380 /* machine registration */
3382 static QEMUMachine *first_machine = NULL;
3383 QEMUMachine *current_machine = NULL;
3385 int qemu_register_machine(QEMUMachine *m)
3387 QEMUMachine **pm;
3388 pm = &first_machine;
3389 while (*pm != NULL)
3390 pm = &(*pm)->next;
3391 m->next = NULL;
3392 *pm = m;
3393 return 0;
3396 static QEMUMachine *find_machine(const char *name)
3398 QEMUMachine *m;
3400 for(m = first_machine; m != NULL; m = m->next) {
3401 if (!strcmp(m->name, name))
3402 return m;
3404 return NULL;
3407 static QEMUMachine *find_default_machine(void)
3409 QEMUMachine *m;
3411 for(m = first_machine; m != NULL; m = m->next) {
3412 if (m->is_default) {
3413 return m;
3416 return NULL;
3419 /***********************************************************/
3420 /* main execution loop */
3422 static void gui_update(void *opaque)
3424 uint64_t interval = GUI_REFRESH_INTERVAL;
3425 DisplayState *ds = opaque;
3426 DisplayChangeListener *dcl = ds->listeners;
3428 dpy_refresh(ds);
3430 while (dcl != NULL) {
3431 if (dcl->gui_timer_interval &&
3432 dcl->gui_timer_interval < interval)
3433 interval = dcl->gui_timer_interval;
3434 dcl = dcl->next;
3436 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3439 static void nographic_update(void *opaque)
3441 uint64_t interval = GUI_REFRESH_INTERVAL;
3443 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3446 struct vm_change_state_entry {
3447 VMChangeStateHandler *cb;
3448 void *opaque;
3449 LIST_ENTRY (vm_change_state_entry) entries;
3452 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3454 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3455 void *opaque)
3457 VMChangeStateEntry *e;
3459 e = qemu_mallocz(sizeof (*e));
3461 e->cb = cb;
3462 e->opaque = opaque;
3463 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3464 return e;
3467 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3469 LIST_REMOVE (e, entries);
3470 qemu_free (e);
3473 static void vm_state_notify(int running, int reason)
3475 VMChangeStateEntry *e;
3477 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3478 e->cb(e->opaque, running, reason);
3482 static void resume_all_vcpus(void);
3483 static void pause_all_vcpus(void);
3485 void vm_start(void)
3487 if (!vm_running) {
3488 cpu_enable_ticks();
3489 vm_running = 1;
3490 vm_state_notify(1, 0);
3491 qemu_rearm_alarm_timer(alarm_timer);
3492 resume_all_vcpus();
3496 /* reset/shutdown handler */
3498 typedef struct QEMUResetEntry {
3499 TAILQ_ENTRY(QEMUResetEntry) entry;
3500 QEMUResetHandler *func;
3501 void *opaque;
3502 } QEMUResetEntry;
3504 static TAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3505 TAILQ_HEAD_INITIALIZER(reset_handlers);
3506 static int reset_requested;
3507 static int shutdown_requested;
3508 static int powerdown_requested;
3509 static int debug_requested;
3510 static int vmstop_requested;
3512 int qemu_no_shutdown(void)
3514 int r = no_shutdown;
3515 no_shutdown = 0;
3516 return r;
3519 int qemu_shutdown_requested(void)
3521 int r = shutdown_requested;
3522 shutdown_requested = 0;
3523 return r;
3526 int qemu_reset_requested(void)
3528 int r = reset_requested;
3529 reset_requested = 0;
3530 return r;
3533 int qemu_powerdown_requested(void)
3535 int r = powerdown_requested;
3536 powerdown_requested = 0;
3537 return r;
3540 static int qemu_debug_requested(void)
3542 int r = debug_requested;
3543 debug_requested = 0;
3544 return r;
3547 static int qemu_vmstop_requested(void)
3549 int r = vmstop_requested;
3550 vmstop_requested = 0;
3551 return r;
3554 static void do_vm_stop(int reason)
3556 if (vm_running) {
3557 cpu_disable_ticks();
3558 vm_running = 0;
3559 pause_all_vcpus();
3560 vm_state_notify(0, reason);
3564 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3566 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3568 re->func = func;
3569 re->opaque = opaque;
3570 TAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3573 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3575 QEMUResetEntry *re;
3577 TAILQ_FOREACH(re, &reset_handlers, entry) {
3578 if (re->func == func && re->opaque == opaque) {
3579 TAILQ_REMOVE(&reset_handlers, re, entry);
3580 qemu_free(re);
3581 return;
3586 void qemu_system_reset(void)
3588 QEMUResetEntry *re, *nre;
3590 /* reset all devices */
3591 TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3592 re->func(re->opaque);
3596 void qemu_system_reset_request(void)
3598 if (no_reboot) {
3599 shutdown_requested = 1;
3600 } else {
3601 reset_requested = 1;
3603 if (cpu_single_env) {
3604 cpu_single_env->stopped = 1;
3606 qemu_notify_event();
3609 void qemu_system_shutdown_request(void)
3611 shutdown_requested = 1;
3612 qemu_notify_event();
3615 void qemu_system_powerdown_request(void)
3617 powerdown_requested = 1;
3618 qemu_notify_event();
3621 #ifdef CONFIG_IOTHREAD
3622 static void qemu_system_vmstop_request(int reason)
3624 vmstop_requested = reason;
3625 qemu_notify_event();
3627 #endif
3629 #ifndef _WIN32
3630 static int io_thread_fd = -1;
3632 static void qemu_event_increment(void)
3634 static const char byte = 0;
3636 if (io_thread_fd == -1)
3637 return;
3639 write(io_thread_fd, &byte, sizeof(byte));
3642 static void qemu_event_read(void *opaque)
3644 int fd = (unsigned long)opaque;
3645 ssize_t len;
3647 /* Drain the notify pipe */
3648 do {
3649 char buffer[512];
3650 len = read(fd, buffer, sizeof(buffer));
3651 } while ((len == -1 && errno == EINTR) || len > 0);
3654 static int qemu_event_init(void)
3656 int err;
3657 int fds[2];
3659 err = pipe(fds);
3660 if (err == -1)
3661 return -errno;
3663 err = fcntl_setfl(fds[0], O_NONBLOCK);
3664 if (err < 0)
3665 goto fail;
3667 err = fcntl_setfl(fds[1], O_NONBLOCK);
3668 if (err < 0)
3669 goto fail;
3671 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3672 (void *)(unsigned long)fds[0]);
3674 io_thread_fd = fds[1];
3675 return 0;
3677 fail:
3678 close(fds[0]);
3679 close(fds[1]);
3680 return err;
3682 #else
3683 HANDLE qemu_event_handle;
3685 static void dummy_event_handler(void *opaque)
3689 static int qemu_event_init(void)
3691 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3692 if (!qemu_event_handle) {
3693 perror("Failed CreateEvent");
3694 return -1;
3696 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3697 return 0;
3700 static void qemu_event_increment(void)
3702 SetEvent(qemu_event_handle);
3704 #endif
3706 static int cpu_can_run(CPUState *env)
3708 if (env->stop)
3709 return 0;
3710 if (env->stopped)
3711 return 0;
3712 return 1;
3715 #ifndef CONFIG_IOTHREAD
3716 static int qemu_init_main_loop(void)
3718 return qemu_event_init();
3721 void qemu_init_vcpu(void *_env)
3723 CPUState *env = _env;
3725 if (kvm_enabled())
3726 kvm_init_vcpu(env);
3727 return;
3730 int qemu_cpu_self(void *env)
3732 return 1;
3735 static void resume_all_vcpus(void)
3739 static void pause_all_vcpus(void)
3743 void qemu_cpu_kick(void *env)
3745 return;
3748 void qemu_notify_event(void)
3750 CPUState *env = cpu_single_env;
3752 if (kvm_enabled()) {
3753 qemu_kvm_notify_work();
3754 return;
3756 if (env) {
3757 cpu_exit(env);
3758 #ifdef USE_KQEMU
3759 if (env->kqemu_enabled)
3760 kqemu_cpu_interrupt(env);
3761 #endif
3765 #ifdef KVM_UPSTREAM
3766 #define qemu_mutex_lock_iothread() do { } while (0)
3767 #define qemu_mutex_unlock_iothread() do { } while (0)
3768 #endif
3770 void vm_stop(int reason)
3772 do_vm_stop(reason);
3775 #else /* CONFIG_IOTHREAD */
3777 #include "qemu-thread.h"
3779 QemuMutex qemu_global_mutex;
3780 static QemuMutex qemu_fair_mutex;
3782 static QemuThread io_thread;
3784 static QemuThread *tcg_cpu_thread;
3785 static QemuCond *tcg_halt_cond;
3787 static int qemu_system_ready;
3788 /* cpu creation */
3789 static QemuCond qemu_cpu_cond;
3790 /* system init */
3791 static QemuCond qemu_system_cond;
3792 static QemuCond qemu_pause_cond;
3794 static void block_io_signals(void);
3795 static void unblock_io_signals(void);
3796 static int tcg_has_work(void);
3798 static int qemu_init_main_loop(void)
3800 int ret;
3802 ret = qemu_event_init();
3803 if (ret)
3804 return ret;
3806 qemu_cond_init(&qemu_pause_cond);
3807 qemu_mutex_init(&qemu_fair_mutex);
3808 qemu_mutex_init(&qemu_global_mutex);
3809 qemu_mutex_lock(&qemu_global_mutex);
3811 unblock_io_signals();
3812 qemu_thread_self(&io_thread);
3814 return 0;
3817 static void qemu_wait_io_event(CPUState *env)
3819 while (!tcg_has_work())
3820 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3822 qemu_mutex_unlock(&qemu_global_mutex);
3825 * Users of qemu_global_mutex can be starved, having no chance
3826 * to acquire it since this path will get to it first.
3827 * So use another lock to provide fairness.
3829 qemu_mutex_lock(&qemu_fair_mutex);
3830 qemu_mutex_unlock(&qemu_fair_mutex);
3832 qemu_mutex_lock(&qemu_global_mutex);
3833 if (env->stop) {
3834 env->stop = 0;
3835 env->stopped = 1;
3836 qemu_cond_signal(&qemu_pause_cond);
3840 static int qemu_cpu_exec(CPUState *env);
3842 static void *kvm_cpu_thread_fn(void *arg)
3844 CPUState *env = arg;
3846 block_io_signals();
3847 qemu_thread_self(env->thread);
3849 /* signal CPU creation */
3850 qemu_mutex_lock(&qemu_global_mutex);
3851 env->created = 1;
3852 qemu_cond_signal(&qemu_cpu_cond);
3854 /* and wait for machine initialization */
3855 while (!qemu_system_ready)
3856 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3858 while (1) {
3859 if (cpu_can_run(env))
3860 qemu_cpu_exec(env);
3861 qemu_wait_io_event(env);
3864 return NULL;
3867 static void tcg_cpu_exec(void);
3869 static void *tcg_cpu_thread_fn(void *arg)
3871 CPUState *env = arg;
3873 block_io_signals();
3874 qemu_thread_self(env->thread);
3876 /* signal CPU creation */
3877 qemu_mutex_lock(&qemu_global_mutex);
3878 for (env = first_cpu; env != NULL; env = env->next_cpu)
3879 env->created = 1;
3880 qemu_cond_signal(&qemu_cpu_cond);
3882 /* and wait for machine initialization */
3883 while (!qemu_system_ready)
3884 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3886 while (1) {
3887 tcg_cpu_exec();
3888 qemu_wait_io_event(cur_cpu);
3891 return NULL;
3894 void qemu_cpu_kick(void *_env)
3896 CPUState *env = _env;
3897 qemu_cond_broadcast(env->halt_cond);
3898 if (kvm_enabled())
3899 qemu_thread_signal(env->thread, SIGUSR1);
3902 int qemu_cpu_self(void *env)
3904 return (cpu_single_env != NULL);
3907 static void cpu_signal(int sig)
3909 if (cpu_single_env)
3910 cpu_exit(cpu_single_env);
3913 static void block_io_signals(void)
3915 sigset_t set;
3916 struct sigaction sigact;
3918 sigemptyset(&set);
3919 sigaddset(&set, SIGUSR2);
3920 sigaddset(&set, SIGIO);
3921 sigaddset(&set, SIGALRM);
3922 pthread_sigmask(SIG_BLOCK, &set, NULL);
3924 sigemptyset(&set);
3925 sigaddset(&set, SIGUSR1);
3926 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3928 memset(&sigact, 0, sizeof(sigact));
3929 sigact.sa_handler = cpu_signal;
3930 sigaction(SIGUSR1, &sigact, NULL);
3933 static void unblock_io_signals(void)
3935 sigset_t set;
3937 sigemptyset(&set);
3938 sigaddset(&set, SIGUSR2);
3939 sigaddset(&set, SIGIO);
3940 sigaddset(&set, SIGALRM);
3941 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3943 sigemptyset(&set);
3944 sigaddset(&set, SIGUSR1);
3945 pthread_sigmask(SIG_BLOCK, &set, NULL);
3948 static void qemu_signal_lock(unsigned int msecs)
3950 qemu_mutex_lock(&qemu_fair_mutex);
3952 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3953 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3954 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3955 break;
3957 qemu_mutex_unlock(&qemu_fair_mutex);
3960 static void qemu_mutex_lock_iothread(void)
3962 if (kvm_enabled()) {
3963 qemu_mutex_lock(&qemu_fair_mutex);
3964 qemu_mutex_lock(&qemu_global_mutex);
3965 qemu_mutex_unlock(&qemu_fair_mutex);
3966 } else
3967 qemu_signal_lock(100);
3970 static void qemu_mutex_unlock_iothread(void)
3972 qemu_mutex_unlock(&qemu_global_mutex);
3975 static int all_vcpus_paused(void)
3977 CPUState *penv = first_cpu;
3979 while (penv) {
3980 if (!penv->stopped)
3981 return 0;
3982 penv = (CPUState *)penv->next_cpu;
3985 return 1;
3988 static void pause_all_vcpus(void)
3990 CPUState *penv = first_cpu;
3992 while (penv) {
3993 penv->stop = 1;
3994 qemu_thread_signal(penv->thread, SIGUSR1);
3995 qemu_cpu_kick(penv);
3996 penv = (CPUState *)penv->next_cpu;
3999 while (!all_vcpus_paused()) {
4000 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
4001 penv = first_cpu;
4002 while (penv) {
4003 qemu_thread_signal(penv->thread, SIGUSR1);
4004 penv = (CPUState *)penv->next_cpu;
4009 static void resume_all_vcpus(void)
4011 CPUState *penv = first_cpu;
4013 while (penv) {
4014 penv->stop = 0;
4015 penv->stopped = 0;
4016 qemu_thread_signal(penv->thread, SIGUSR1);
4017 qemu_cpu_kick(penv);
4018 penv = (CPUState *)penv->next_cpu;
4022 static void tcg_init_vcpu(void *_env)
4024 CPUState *env = _env;
4025 /* share a single thread for all cpus with TCG */
4026 if (!tcg_cpu_thread) {
4027 env->thread = qemu_mallocz(sizeof(QemuThread));
4028 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4029 qemu_cond_init(env->halt_cond);
4030 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
4031 while (env->created == 0)
4032 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4033 tcg_cpu_thread = env->thread;
4034 tcg_halt_cond = env->halt_cond;
4035 } else {
4036 env->thread = tcg_cpu_thread;
4037 env->halt_cond = tcg_halt_cond;
4041 static void kvm_start_vcpu(CPUState *env)
4043 kvm_init_vcpu(env);
4044 env->thread = qemu_mallocz(sizeof(QemuThread));
4045 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4046 qemu_cond_init(env->halt_cond);
4047 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
4048 while (env->created == 0)
4049 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4052 void qemu_init_vcpu(void *_env)
4054 CPUState *env = _env;
4056 if (kvm_enabled())
4057 kvm_start_vcpu(env);
4058 else
4059 tcg_init_vcpu(env);
4062 void qemu_notify_event(void)
4064 qemu_event_increment();
4067 void vm_stop(int reason)
4069 QemuThread me;
4070 qemu_thread_self(&me);
4072 if (!qemu_thread_equal(&me, &io_thread)) {
4073 qemu_system_vmstop_request(reason);
4075 * FIXME: should not return to device code in case
4076 * vm_stop() has been requested.
4078 if (cpu_single_env) {
4079 cpu_exit(cpu_single_env);
4080 cpu_single_env->stop = 1;
4082 return;
4084 do_vm_stop(reason);
4087 #endif
4090 #ifdef _WIN32
4091 static void host_main_loop_wait(int *timeout)
4093 int ret, ret2, i;
4094 PollingEntry *pe;
4097 /* XXX: need to suppress polling by better using win32 events */
4098 ret = 0;
4099 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4100 ret |= pe->func(pe->opaque);
4102 if (ret == 0) {
4103 int err;
4104 WaitObjects *w = &wait_objects;
4106 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4107 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4108 if (w->func[ret - WAIT_OBJECT_0])
4109 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4111 /* Check for additional signaled events */
4112 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4114 /* Check if event is signaled */
4115 ret2 = WaitForSingleObject(w->events[i], 0);
4116 if(ret2 == WAIT_OBJECT_0) {
4117 if (w->func[i])
4118 w->func[i](w->opaque[i]);
4119 } else if (ret2 == WAIT_TIMEOUT) {
4120 } else {
4121 err = GetLastError();
4122 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4125 } else if (ret == WAIT_TIMEOUT) {
4126 } else {
4127 err = GetLastError();
4128 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4132 *timeout = 0;
4134 #else
4135 static void host_main_loop_wait(int *timeout)
4138 #endif
4140 void main_loop_wait(int timeout)
4142 IOHandlerRecord *ioh;
4143 fd_set rfds, wfds, xfds;
4144 int ret, nfds;
4145 struct timeval tv;
4147 qemu_bh_update_timeout(&timeout);
4149 host_main_loop_wait(&timeout);
4151 /* poll any events */
4152 /* XXX: separate device handlers from system ones */
4153 nfds = -1;
4154 FD_ZERO(&rfds);
4155 FD_ZERO(&wfds);
4156 FD_ZERO(&xfds);
4157 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4158 if (ioh->deleted)
4159 continue;
4160 if (ioh->fd_read &&
4161 (!ioh->fd_read_poll ||
4162 ioh->fd_read_poll(ioh->opaque) != 0)) {
4163 FD_SET(ioh->fd, &rfds);
4164 if (ioh->fd > nfds)
4165 nfds = ioh->fd;
4167 if (ioh->fd_write) {
4168 FD_SET(ioh->fd, &wfds);
4169 if (ioh->fd > nfds)
4170 nfds = ioh->fd;
4174 tv.tv_sec = timeout / 1000;
4175 tv.tv_usec = (timeout % 1000) * 1000;
4177 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4179 qemu_mutex_unlock_iothread();
4180 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4181 qemu_mutex_lock_iothread();
4182 if (ret > 0) {
4183 IOHandlerRecord **pioh;
4185 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4186 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4187 ioh->fd_read(ioh->opaque);
4188 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
4189 FD_CLR(ioh->fd, &rfds);
4191 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4192 ioh->fd_write(ioh->opaque);
4196 /* remove deleted IO handlers */
4197 pioh = &first_io_handler;
4198 while (*pioh) {
4199 ioh = *pioh;
4200 if (ioh->deleted) {
4201 *pioh = ioh->next;
4202 qemu_free(ioh);
4203 } else
4204 pioh = &ioh->next;
4208 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4210 /* rearm timer, if not periodic */
4211 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4212 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4213 qemu_rearm_alarm_timer(alarm_timer);
4216 /* vm time timers */
4217 if (vm_running) {
4218 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4219 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4220 qemu_get_clock(vm_clock));
4223 /* real time timers */
4224 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4225 qemu_get_clock(rt_clock));
4227 /* Check bottom-halves last in case any of the earlier events triggered
4228 them. */
4229 qemu_bh_poll();
4233 static int qemu_cpu_exec(CPUState *env)
4235 int ret;
4236 #ifdef CONFIG_PROFILER
4237 int64_t ti;
4238 #endif
4240 #ifdef CONFIG_PROFILER
4241 ti = profile_getclock();
4242 #endif
4243 if (use_icount) {
4244 int64_t count;
4245 int decr;
4246 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4247 env->icount_decr.u16.low = 0;
4248 env->icount_extra = 0;
4249 count = qemu_next_deadline();
4250 count = (count + (1 << icount_time_shift) - 1)
4251 >> icount_time_shift;
4252 qemu_icount += count;
4253 decr = (count > 0xffff) ? 0xffff : count;
4254 count -= decr;
4255 env->icount_decr.u16.low = decr;
4256 env->icount_extra = count;
4258 ret = cpu_exec(env);
4259 #ifdef CONFIG_PROFILER
4260 qemu_time += profile_getclock() - ti;
4261 #endif
4262 if (use_icount) {
4263 /* Fold pending instructions back into the
4264 instruction counter, and clear the interrupt flag. */
4265 qemu_icount -= (env->icount_decr.u16.low
4266 + env->icount_extra);
4267 env->icount_decr.u32 = 0;
4268 env->icount_extra = 0;
4270 return ret;
4273 static void tcg_cpu_exec(void)
4275 int ret = 0;
4277 if (next_cpu == NULL)
4278 next_cpu = first_cpu;
4279 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4280 CPUState *env = cur_cpu = next_cpu;
4282 if (!vm_running)
4283 break;
4284 if (timer_alarm_pending) {
4285 timer_alarm_pending = 0;
4286 break;
4288 if (cpu_can_run(env))
4289 ret = qemu_cpu_exec(env);
4290 if (ret == EXCP_DEBUG) {
4291 gdb_set_stop_cpu(env);
4292 debug_requested = 1;
4293 break;
4298 static int cpu_has_work(CPUState *env)
4300 if (env->stop)
4301 return 1;
4302 if (env->stopped)
4303 return 0;
4304 if (!env->halted)
4305 return 1;
4306 if (qemu_cpu_has_work(env))
4307 return 1;
4308 return 0;
4311 static int tcg_has_work(void)
4313 CPUState *env;
4315 for (env = first_cpu; env != NULL; env = env->next_cpu)
4316 if (cpu_has_work(env))
4317 return 1;
4318 return 0;
4321 static int qemu_calculate_timeout(void)
4323 #ifndef CONFIG_IOTHREAD
4324 int timeout;
4326 if (!vm_running)
4327 timeout = 5000;
4328 else if (tcg_has_work())
4329 timeout = 0;
4330 else if (!use_icount)
4331 timeout = 5000;
4332 else {
4333 /* XXX: use timeout computed from timers */
4334 int64_t add;
4335 int64_t delta;
4336 /* Advance virtual time to the next event. */
4337 if (use_icount == 1) {
4338 /* When not using an adaptive execution frequency
4339 we tend to get badly out of sync with real time,
4340 so just delay for a reasonable amount of time. */
4341 delta = 0;
4342 } else {
4343 delta = cpu_get_icount() - cpu_get_clock();
4345 if (delta > 0) {
4346 /* If virtual time is ahead of real time then just
4347 wait for IO. */
4348 timeout = (delta / 1000000) + 1;
4349 } else {
4350 /* Wait for either IO to occur or the next
4351 timer event. */
4352 add = qemu_next_deadline();
4353 /* We advance the timer before checking for IO.
4354 Limit the amount we advance so that early IO
4355 activity won't get the guest too far ahead. */
4356 if (add > 10000000)
4357 add = 10000000;
4358 delta += add;
4359 add = (add + (1 << icount_time_shift) - 1)
4360 >> icount_time_shift;
4361 qemu_icount += add;
4362 timeout = delta / 1000000;
4363 if (timeout < 0)
4364 timeout = 0;
4368 return timeout;
4369 #else /* CONFIG_IOTHREAD */
4370 return 1000;
4371 #endif
4374 static int vm_can_run(void)
4376 if (powerdown_requested)
4377 return 0;
4378 if (reset_requested)
4379 return 0;
4380 if (shutdown_requested)
4381 return 0;
4382 if (debug_requested)
4383 return 0;
4384 return 1;
4387 static void main_loop(void)
4389 int r;
4391 if (kvm_enabled()) {
4392 kvm_main_loop();
4393 cpu_disable_ticks();
4394 return;
4397 #ifdef CONFIG_IOTHREAD
4398 qemu_system_ready = 1;
4399 qemu_cond_broadcast(&qemu_system_cond);
4400 #endif
4402 for (;;) {
4403 do {
4404 #ifdef CONFIG_PROFILER
4405 int64_t ti;
4406 #endif
4407 #ifndef CONFIG_IOTHREAD
4408 tcg_cpu_exec();
4409 #endif
4410 #ifdef CONFIG_PROFILER
4411 ti = profile_getclock();
4412 #endif
4413 main_loop_wait(qemu_calculate_timeout());
4414 #ifdef CONFIG_PROFILER
4415 dev_time += profile_getclock() - ti;
4416 #endif
4417 } while (vm_can_run());
4419 if (qemu_debug_requested())
4420 vm_stop(EXCP_DEBUG);
4421 if (qemu_shutdown_requested()) {
4422 if (no_shutdown) {
4423 vm_stop(0);
4424 no_shutdown = 0;
4425 } else
4426 break;
4428 if (qemu_reset_requested()) {
4429 pause_all_vcpus();
4430 qemu_system_reset();
4431 resume_all_vcpus();
4433 if (qemu_powerdown_requested())
4434 qemu_system_powerdown();
4435 if ((r = qemu_vmstop_requested()))
4436 vm_stop(r);
4438 pause_all_vcpus();
4441 static void version(void)
4443 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4446 static void help(int exitcode)
4448 version();
4449 printf("usage: %s [options] [disk_image]\n"
4450 "\n"
4451 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4452 "\n"
4453 #define DEF(option, opt_arg, opt_enum, opt_help) \
4454 opt_help
4455 #define DEFHEADING(text) stringify(text) "\n"
4456 #include "qemu-options.h"
4457 #undef DEF
4458 #undef DEFHEADING
4459 #undef GEN_DOCS
4460 "\n"
4461 "During emulation, the following keys are useful:\n"
4462 "ctrl-alt-f toggle full screen\n"
4463 "ctrl-alt-n switch to virtual console 'n'\n"
4464 "ctrl-alt toggle mouse and keyboard grab\n"
4465 "\n"
4466 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4468 "qemu",
4469 DEFAULT_RAM_SIZE,
4470 #ifndef _WIN32
4471 DEFAULT_NETWORK_SCRIPT,
4472 DEFAULT_NETWORK_DOWN_SCRIPT,
4473 #endif
4474 DEFAULT_GDBSTUB_PORT,
4475 "/tmp/qemu.log");
4476 exit(exitcode);
4479 #define HAS_ARG 0x0001
4481 enum {
4482 #define DEF(option, opt_arg, opt_enum, opt_help) \
4483 opt_enum,
4484 #define DEFHEADING(text)
4485 #include "qemu-options.h"
4486 #undef DEF
4487 #undef DEFHEADING
4488 #undef GEN_DOCS
4491 typedef struct QEMUOption {
4492 const char *name;
4493 int flags;
4494 int index;
4495 } QEMUOption;
4497 static const QEMUOption qemu_options[] = {
4498 { "h", 0, QEMU_OPTION_h },
4499 #define DEF(option, opt_arg, opt_enum, opt_help) \
4500 { option, opt_arg, opt_enum },
4501 #define DEFHEADING(text)
4502 #include "qemu-options.h"
4503 #undef DEF
4504 #undef DEFHEADING
4505 #undef GEN_DOCS
4506 { NULL },
4509 #ifdef HAS_AUDIO
4510 struct soundhw soundhw[] = {
4511 #ifdef HAS_AUDIO_CHOICE
4512 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4514 "pcspk",
4515 "PC speaker",
4518 { .init_isa = pcspk_audio_init }
4520 #endif
4522 #ifdef CONFIG_SB16
4524 "sb16",
4525 "Creative Sound Blaster 16",
4528 { .init_isa = SB16_init }
4530 #endif
4532 #ifdef CONFIG_CS4231A
4534 "cs4231a",
4535 "CS4231A",
4538 { .init_isa = cs4231a_init }
4540 #endif
4542 #ifdef CONFIG_ADLIB
4544 "adlib",
4545 #ifdef HAS_YMF262
4546 "Yamaha YMF262 (OPL3)",
4547 #else
4548 "Yamaha YM3812 (OPL2)",
4549 #endif
4552 { .init_isa = Adlib_init }
4554 #endif
4556 #ifdef CONFIG_GUS
4558 "gus",
4559 "Gravis Ultrasound GF1",
4562 { .init_isa = GUS_init }
4564 #endif
4566 #ifdef CONFIG_AC97
4568 "ac97",
4569 "Intel 82801AA AC97 Audio",
4572 { .init_pci = ac97_init }
4574 #endif
4576 #ifdef CONFIG_ES1370
4578 "es1370",
4579 "ENSONIQ AudioPCI ES1370",
4582 { .init_pci = es1370_init }
4584 #endif
4586 #endif /* HAS_AUDIO_CHOICE */
4588 { NULL, NULL, 0, 0, { NULL } }
4591 static void select_soundhw (const char *optarg)
4593 struct soundhw *c;
4595 if (*optarg == '?') {
4596 show_valid_cards:
4598 printf ("Valid sound card names (comma separated):\n");
4599 for (c = soundhw; c->name; ++c) {
4600 printf ("%-11s %s\n", c->name, c->descr);
4602 printf ("\n-soundhw all will enable all of the above\n");
4603 exit (*optarg != '?');
4605 else {
4606 size_t l;
4607 const char *p;
4608 char *e;
4609 int bad_card = 0;
4611 if (!strcmp (optarg, "all")) {
4612 for (c = soundhw; c->name; ++c) {
4613 c->enabled = 1;
4615 return;
4618 p = optarg;
4619 while (*p) {
4620 e = strchr (p, ',');
4621 l = !e ? strlen (p) : (size_t) (e - p);
4623 for (c = soundhw; c->name; ++c) {
4624 if (!strncmp (c->name, p, l)) {
4625 c->enabled = 1;
4626 break;
4630 if (!c->name) {
4631 if (l > 80) {
4632 fprintf (stderr,
4633 "Unknown sound card name (too big to show)\n");
4635 else {
4636 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4637 (int) l, p);
4639 bad_card = 1;
4641 p += l + (e != NULL);
4644 if (bad_card)
4645 goto show_valid_cards;
4648 #endif
4650 static void select_vgahw (const char *p)
4652 const char *opts;
4654 cirrus_vga_enabled = 0;
4655 std_vga_enabled = 0;
4656 vmsvga_enabled = 0;
4657 xenfb_enabled = 0;
4658 if (strstart(p, "std", &opts)) {
4659 std_vga_enabled = 1;
4660 } else if (strstart(p, "cirrus", &opts)) {
4661 cirrus_vga_enabled = 1;
4662 } else if (strstart(p, "vmware", &opts)) {
4663 vmsvga_enabled = 1;
4664 } else if (strstart(p, "xenfb", &opts)) {
4665 xenfb_enabled = 1;
4666 } else if (!strstart(p, "none", &opts)) {
4667 invalid_vga:
4668 fprintf(stderr, "Unknown vga type: %s\n", p);
4669 exit(1);
4671 while (*opts) {
4672 const char *nextopt;
4674 if (strstart(opts, ",retrace=", &nextopt)) {
4675 opts = nextopt;
4676 if (strstart(opts, "dumb", &nextopt))
4677 vga_retrace_method = VGA_RETRACE_DUMB;
4678 else if (strstart(opts, "precise", &nextopt))
4679 vga_retrace_method = VGA_RETRACE_PRECISE;
4680 else goto invalid_vga;
4681 } else goto invalid_vga;
4682 opts = nextopt;
4686 #ifdef TARGET_I386
4687 static int balloon_parse(const char *arg)
4689 char buf[128];
4690 const char *p;
4692 if (!strcmp(arg, "none")) {
4693 virtio_balloon = 0;
4694 } else if (!strncmp(arg, "virtio", 6)) {
4695 virtio_balloon = 1;
4696 if (arg[6] == ',') {
4697 p = arg + 7;
4698 if (get_param_value(buf, sizeof(buf), "addr", p)) {
4699 virtio_balloon_devaddr = strdup(buf);
4702 } else {
4703 return -1;
4705 return 0;
4707 #endif
4709 #ifdef _WIN32
4710 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4712 exit(STATUS_CONTROL_C_EXIT);
4713 return TRUE;
4715 #endif
4717 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4719 int ret;
4721 if(strlen(str) != 36)
4722 return -1;
4724 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4725 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4726 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4728 if(ret != 16)
4729 return -1;
4731 #ifdef TARGET_I386
4732 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4733 #endif
4735 return 0;
4738 #define MAX_NET_CLIENTS 32
4740 #ifndef _WIN32
4742 static void termsig_handler(int signal)
4744 qemu_system_shutdown_request();
4747 static void sigchld_handler(int signal)
4749 waitpid(-1, NULL, WNOHANG);
4752 static void sighandler_setup(void)
4754 struct sigaction act;
4756 memset(&act, 0, sizeof(act));
4757 act.sa_handler = termsig_handler;
4758 sigaction(SIGINT, &act, NULL);
4759 sigaction(SIGHUP, &act, NULL);
4760 sigaction(SIGTERM, &act, NULL);
4762 act.sa_handler = sigchld_handler;
4763 act.sa_flags = SA_NOCLDSTOP;
4764 sigaction(SIGCHLD, &act, NULL);
4767 #endif
4769 #ifdef _WIN32
4770 /* Look for support files in the same directory as the executable. */
4771 static char *find_datadir(const char *argv0)
4773 char *p;
4774 char buf[MAX_PATH];
4775 DWORD len;
4777 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4778 if (len == 0) {
4779 return NULL;
4782 buf[len] = 0;
4783 p = buf + len - 1;
4784 while (p != buf && *p != '\\')
4785 p--;
4786 *p = 0;
4787 if (access(buf, R_OK) == 0) {
4788 return qemu_strdup(buf);
4790 return NULL;
4792 #else /* !_WIN32 */
4794 /* Find a likely location for support files using the location of the binary.
4795 For installed binaries this will be "$bindir/../share/qemu". When
4796 running from the build tree this will be "$bindir/../pc-bios". */
4797 #define SHARE_SUFFIX "/share/qemu"
4798 #define BUILD_SUFFIX "/pc-bios"
4799 static char *find_datadir(const char *argv0)
4801 char *dir;
4802 char *p = NULL;
4803 char *res;
4804 #ifdef PATH_MAX
4805 char buf[PATH_MAX];
4806 #endif
4807 size_t max_len;
4809 #if defined(__linux__)
4811 int len;
4812 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4813 if (len > 0) {
4814 buf[len] = 0;
4815 p = buf;
4818 #elif defined(__FreeBSD__)
4820 int len;
4821 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4822 if (len > 0) {
4823 buf[len] = 0;
4824 p = buf;
4827 #endif
4828 /* If we don't have any way of figuring out the actual executable
4829 location then try argv[0]. */
4830 if (!p) {
4831 #ifdef PATH_MAX
4832 p = buf;
4833 #endif
4834 p = realpath(argv0, p);
4835 if (!p) {
4836 return NULL;
4839 dir = dirname(p);
4840 dir = dirname(dir);
4842 max_len = strlen(dir) +
4843 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4844 res = qemu_mallocz(max_len);
4845 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4846 if (access(res, R_OK)) {
4847 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4848 if (access(res, R_OK)) {
4849 qemu_free(res);
4850 res = NULL;
4853 #ifndef PATH_MAX
4854 free(p);
4855 #endif
4856 return res;
4858 #undef SHARE_SUFFIX
4859 #undef BUILD_SUFFIX
4860 #endif
4862 char *qemu_find_file(int type, const char *name)
4864 int len;
4865 const char *subdir;
4866 char *buf;
4868 /* If name contains path separators then try it as a straight path. */
4869 if ((strchr(name, '/') || strchr(name, '\\'))
4870 && access(name, R_OK) == 0) {
4871 return strdup(name);
4873 switch (type) {
4874 case QEMU_FILE_TYPE_BIOS:
4875 subdir = "";
4876 break;
4877 case QEMU_FILE_TYPE_KEYMAP:
4878 subdir = "keymaps/";
4879 break;
4880 default:
4881 abort();
4883 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4884 buf = qemu_mallocz(len);
4885 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4886 if (access(buf, R_OK)) {
4887 qemu_free(buf);
4888 return NULL;
4890 return buf;
4893 int main(int argc, char **argv, char **envp)
4895 const char *gdbstub_dev = NULL;
4896 uint32_t boot_devices_bitmap = 0;
4897 int i;
4898 int snapshot, linux_boot, net_boot;
4899 const char *initrd_filename;
4900 const char *kernel_filename, *kernel_cmdline;
4901 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4902 DisplayState *ds;
4903 DisplayChangeListener *dcl;
4904 int cyls, heads, secs, translation;
4905 const char *net_clients[MAX_NET_CLIENTS];
4906 int nb_net_clients;
4907 const char *bt_opts[MAX_BT_CMDLINE];
4908 int nb_bt_opts;
4909 int hda_index;
4910 int optind;
4911 const char *r, *optarg;
4912 CharDriverState *monitor_hd = NULL;
4913 const char *monitor_device;
4914 const char *serial_devices[MAX_SERIAL_PORTS];
4915 int serial_device_index;
4916 const char *parallel_devices[MAX_PARALLEL_PORTS];
4917 int parallel_device_index;
4918 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4919 int virtio_console_index;
4920 const char *loadvm = NULL;
4921 QEMUMachine *machine;
4922 const char *cpu_model;
4923 const char *usb_devices[MAX_USB_CMDLINE];
4924 int usb_devices_index;
4925 #ifndef _WIN32
4926 int fds[2];
4927 #endif
4928 int tb_size;
4929 const char *pid_file = NULL;
4930 const char *incoming = NULL;
4931 #ifndef _WIN32
4932 int fd = 0;
4933 struct passwd *pwd = NULL;
4934 const char *chroot_dir = NULL;
4935 const char *run_as = NULL;
4936 #endif
4937 CPUState *env;
4938 int show_vnc_port = 0;
4940 qemu_cache_utils_init(envp);
4942 LIST_INIT (&vm_change_state_head);
4943 #ifndef _WIN32
4945 struct sigaction act;
4946 sigfillset(&act.sa_mask);
4947 act.sa_flags = 0;
4948 act.sa_handler = SIG_IGN;
4949 sigaction(SIGPIPE, &act, NULL);
4951 #else
4952 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4953 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4954 QEMU to run on a single CPU */
4956 HANDLE h;
4957 DWORD mask, smask;
4958 int i;
4959 h = GetCurrentProcess();
4960 if (GetProcessAffinityMask(h, &mask, &smask)) {
4961 for(i = 0; i < 32; i++) {
4962 if (mask & (1 << i))
4963 break;
4965 if (i != 32) {
4966 mask = 1 << i;
4967 SetProcessAffinityMask(h, mask);
4971 #endif
4973 module_call_init(MODULE_INIT_MACHINE);
4974 machine = find_default_machine();
4975 cpu_model = NULL;
4976 initrd_filename = NULL;
4977 ram_size = 0;
4978 snapshot = 0;
4979 kernel_filename = NULL;
4980 kernel_cmdline = "";
4981 cyls = heads = secs = 0;
4982 translation = BIOS_ATA_TRANSLATION_AUTO;
4983 monitor_device = "vc:80Cx24C";
4985 serial_devices[0] = "vc:80Cx24C";
4986 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4987 serial_devices[i] = NULL;
4988 serial_device_index = 0;
4990 parallel_devices[0] = "vc:80Cx24C";
4991 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4992 parallel_devices[i] = NULL;
4993 parallel_device_index = 0;
4995 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4996 virtio_consoles[i] = NULL;
4997 virtio_console_index = 0;
4999 for (i = 0; i < MAX_NODES; i++) {
5000 node_mem[i] = 0;
5001 node_cpumask[i] = 0;
5004 usb_devices_index = 0;
5005 assigned_devices_index = 0;
5007 nb_net_clients = 0;
5008 nb_bt_opts = 0;
5009 nb_drives = 0;
5010 nb_drives_opt = 0;
5011 nb_numa_nodes = 0;
5012 hda_index = -1;
5014 nb_nics = 0;
5016 tb_size = 0;
5017 autostart= 1;
5019 register_watchdogs();
5021 optind = 1;
5022 for(;;) {
5023 if (optind >= argc)
5024 break;
5025 r = argv[optind];
5026 if (r[0] != '-') {
5027 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5028 } else {
5029 const QEMUOption *popt;
5031 optind++;
5032 /* Treat --foo the same as -foo. */
5033 if (r[1] == '-')
5034 r++;
5035 popt = qemu_options;
5036 for(;;) {
5037 if (!popt->name) {
5038 fprintf(stderr, "%s: invalid option -- '%s'\n",
5039 argv[0], r);
5040 exit(1);
5042 if (!strcmp(popt->name, r + 1))
5043 break;
5044 popt++;
5046 if (popt->flags & HAS_ARG) {
5047 if (optind >= argc) {
5048 fprintf(stderr, "%s: option '%s' requires an argument\n",
5049 argv[0], r);
5050 exit(1);
5052 optarg = argv[optind++];
5053 } else {
5054 optarg = NULL;
5057 switch(popt->index) {
5058 case QEMU_OPTION_M:
5059 machine = find_machine(optarg);
5060 if (!machine) {
5061 QEMUMachine *m;
5062 printf("Supported machines are:\n");
5063 for(m = first_machine; m != NULL; m = m->next) {
5064 printf("%-10s %s%s\n",
5065 m->name, m->desc,
5066 m->is_default ? " (default)" : "");
5068 exit(*optarg != '?');
5070 break;
5071 case QEMU_OPTION_cpu:
5072 /* hw initialization will check this */
5073 if (*optarg == '?') {
5074 /* XXX: implement xxx_cpu_list for targets that still miss it */
5075 #if defined(cpu_list)
5076 cpu_list(stdout, &fprintf);
5077 #endif
5078 exit(0);
5079 } else {
5080 cpu_model = optarg;
5082 break;
5083 case QEMU_OPTION_initrd:
5084 initrd_filename = optarg;
5085 break;
5086 case QEMU_OPTION_hda:
5087 if (cyls == 0)
5088 hda_index = drive_add(optarg, HD_ALIAS, 0);
5089 else
5090 hda_index = drive_add(optarg, HD_ALIAS
5091 ",cyls=%d,heads=%d,secs=%d%s",
5092 0, cyls, heads, secs,
5093 translation == BIOS_ATA_TRANSLATION_LBA ?
5094 ",trans=lba" :
5095 translation == BIOS_ATA_TRANSLATION_NONE ?
5096 ",trans=none" : "");
5097 break;
5098 case QEMU_OPTION_hdb:
5099 case QEMU_OPTION_hdc:
5100 case QEMU_OPTION_hdd:
5101 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5102 break;
5103 case QEMU_OPTION_drive:
5104 drive_add(NULL, "%s", optarg);
5105 break;
5106 case QEMU_OPTION_mtdblock:
5107 drive_add(optarg, MTD_ALIAS);
5108 break;
5109 case QEMU_OPTION_sd:
5110 drive_add(optarg, SD_ALIAS);
5111 break;
5112 case QEMU_OPTION_pflash:
5113 drive_add(optarg, PFLASH_ALIAS);
5114 break;
5115 case QEMU_OPTION_snapshot:
5116 snapshot = 1;
5117 break;
5118 case QEMU_OPTION_hdachs:
5120 const char *p;
5121 p = optarg;
5122 cyls = strtol(p, (char **)&p, 0);
5123 if (cyls < 1 || cyls > 16383)
5124 goto chs_fail;
5125 if (*p != ',')
5126 goto chs_fail;
5127 p++;
5128 heads = strtol(p, (char **)&p, 0);
5129 if (heads < 1 || heads > 16)
5130 goto chs_fail;
5131 if (*p != ',')
5132 goto chs_fail;
5133 p++;
5134 secs = strtol(p, (char **)&p, 0);
5135 if (secs < 1 || secs > 63)
5136 goto chs_fail;
5137 if (*p == ',') {
5138 p++;
5139 if (!strcmp(p, "none"))
5140 translation = BIOS_ATA_TRANSLATION_NONE;
5141 else if (!strcmp(p, "lba"))
5142 translation = BIOS_ATA_TRANSLATION_LBA;
5143 else if (!strcmp(p, "auto"))
5144 translation = BIOS_ATA_TRANSLATION_AUTO;
5145 else
5146 goto chs_fail;
5147 } else if (*p != '\0') {
5148 chs_fail:
5149 fprintf(stderr, "qemu: invalid physical CHS format\n");
5150 exit(1);
5152 if (hda_index != -1)
5153 snprintf(drives_opt[hda_index].opt,
5154 sizeof(drives_opt[hda_index].opt),
5155 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5156 0, cyls, heads, secs,
5157 translation == BIOS_ATA_TRANSLATION_LBA ?
5158 ",trans=lba" :
5159 translation == BIOS_ATA_TRANSLATION_NONE ?
5160 ",trans=none" : "");
5162 break;
5163 case QEMU_OPTION_numa:
5164 if (nb_numa_nodes >= MAX_NODES) {
5165 fprintf(stderr, "qemu: too many NUMA nodes\n");
5166 exit(1);
5168 numa_add(optarg);
5169 break;
5170 case QEMU_OPTION_nographic:
5171 display_type = DT_NOGRAPHIC;
5172 break;
5173 #ifdef CONFIG_CURSES
5174 case QEMU_OPTION_curses:
5175 display_type = DT_CURSES;
5176 break;
5177 #endif
5178 case QEMU_OPTION_portrait:
5179 graphic_rotate = 1;
5180 break;
5181 case QEMU_OPTION_kernel:
5182 kernel_filename = optarg;
5183 break;
5184 case QEMU_OPTION_append:
5185 kernel_cmdline = optarg;
5186 break;
5187 case QEMU_OPTION_cdrom:
5188 drive_add(optarg, CDROM_ALIAS);
5189 break;
5190 case QEMU_OPTION_boot:
5192 static const char * const params[] = {
5193 "order", "once", "menu", NULL
5195 char buf[sizeof(boot_devices)];
5196 char *standard_boot_devices;
5197 int legacy = 0;
5199 if (!strchr(optarg, '=')) {
5200 legacy = 1;
5201 pstrcpy(buf, sizeof(buf), optarg);
5202 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5203 fprintf(stderr,
5204 "qemu: unknown boot parameter '%s' in '%s'\n",
5205 buf, optarg);
5206 exit(1);
5209 if (legacy ||
5210 get_param_value(buf, sizeof(buf), "order", optarg)) {
5211 boot_devices_bitmap = parse_bootdevices(buf);
5212 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5214 if (!legacy) {
5215 if (get_param_value(buf, sizeof(buf),
5216 "once", optarg)) {
5217 boot_devices_bitmap |= parse_bootdevices(buf);
5218 standard_boot_devices = qemu_strdup(boot_devices);
5219 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5220 qemu_register_reset(restore_boot_devices,
5221 standard_boot_devices);
5223 if (get_param_value(buf, sizeof(buf),
5224 "menu", optarg)) {
5225 if (!strcmp(buf, "on")) {
5226 boot_menu = 1;
5227 } else if (!strcmp(buf, "off")) {
5228 boot_menu = 0;
5229 } else {
5230 fprintf(stderr,
5231 "qemu: invalid option value '%s'\n",
5232 buf);
5233 exit(1);
5238 break;
5239 case QEMU_OPTION_fda:
5240 case QEMU_OPTION_fdb:
5241 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5242 break;
5243 #ifdef TARGET_I386
5244 case QEMU_OPTION_no_fd_bootchk:
5245 fd_bootchk = 0;
5246 break;
5247 #endif
5248 case QEMU_OPTION_net:
5249 if (nb_net_clients >= MAX_NET_CLIENTS) {
5250 fprintf(stderr, "qemu: too many network clients\n");
5251 exit(1);
5253 net_clients[nb_net_clients] = optarg;
5254 nb_net_clients++;
5255 break;
5256 #ifdef CONFIG_SLIRP
5257 case QEMU_OPTION_tftp:
5258 legacy_tftp_prefix = optarg;
5259 break;
5260 case QEMU_OPTION_bootp:
5261 legacy_bootp_filename = optarg;
5262 break;
5263 #ifndef _WIN32
5264 case QEMU_OPTION_smb:
5265 net_slirp_smb(optarg);
5266 break;
5267 #endif
5268 case QEMU_OPTION_redir:
5269 net_slirp_redir(optarg);
5270 break;
5271 #endif
5272 case QEMU_OPTION_bt:
5273 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5274 fprintf(stderr, "qemu: too many bluetooth options\n");
5275 exit(1);
5277 bt_opts[nb_bt_opts++] = optarg;
5278 break;
5279 #ifdef HAS_AUDIO
5280 case QEMU_OPTION_audio_help:
5281 AUD_help ();
5282 exit (0);
5283 break;
5284 case QEMU_OPTION_soundhw:
5285 select_soundhw (optarg);
5286 break;
5287 #endif
5288 case QEMU_OPTION_h:
5289 help(0);
5290 break;
5291 case QEMU_OPTION_version:
5292 version();
5293 exit(0);
5294 break;
5295 case QEMU_OPTION_m: {
5296 uint64_t value;
5297 char *ptr;
5299 value = strtoul(optarg, &ptr, 10);
5300 switch (*ptr) {
5301 case 0: case 'M': case 'm':
5302 value <<= 20;
5303 break;
5304 case 'G': case 'g':
5305 value <<= 30;
5306 break;
5307 default:
5308 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5309 exit(1);
5312 /* On 32-bit hosts, QEMU is limited by virtual address space */
5313 if (value > (2047 << 20)
5314 #ifndef CONFIG_KQEMU
5315 && HOST_LONG_BITS == 32
5316 #endif
5318 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5319 exit(1);
5321 if (value != (uint64_t)(ram_addr_t)value) {
5322 fprintf(stderr, "qemu: ram size too large\n");
5323 exit(1);
5325 ram_size = value;
5326 break;
5328 case QEMU_OPTION_d:
5330 int mask;
5331 const CPULogItem *item;
5333 mask = cpu_str_to_log_mask(optarg);
5334 if (!mask) {
5335 printf("Log items (comma separated):\n");
5336 for(item = cpu_log_items; item->mask != 0; item++) {
5337 printf("%-10s %s\n", item->name, item->help);
5339 exit(1);
5341 cpu_set_log(mask);
5343 break;
5344 case QEMU_OPTION_s:
5345 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5346 break;
5347 case QEMU_OPTION_gdb:
5348 gdbstub_dev = optarg;
5349 break;
5350 case QEMU_OPTION_L:
5351 data_dir = optarg;
5352 break;
5353 case QEMU_OPTION_bios:
5354 bios_name = optarg;
5355 break;
5356 case QEMU_OPTION_singlestep:
5357 singlestep = 1;
5358 break;
5359 case QEMU_OPTION_S:
5360 autostart = 0;
5361 break;
5362 #ifndef _WIN32
5363 case QEMU_OPTION_k:
5364 keyboard_layout = optarg;
5365 break;
5366 #endif
5367 case QEMU_OPTION_localtime:
5368 rtc_utc = 0;
5369 break;
5370 case QEMU_OPTION_vga:
5371 select_vgahw (optarg);
5372 break;
5373 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5374 case QEMU_OPTION_g:
5376 const char *p;
5377 int w, h, depth;
5378 p = optarg;
5379 w = strtol(p, (char **)&p, 10);
5380 if (w <= 0) {
5381 graphic_error:
5382 fprintf(stderr, "qemu: invalid resolution or depth\n");
5383 exit(1);
5385 if (*p != 'x')
5386 goto graphic_error;
5387 p++;
5388 h = strtol(p, (char **)&p, 10);
5389 if (h <= 0)
5390 goto graphic_error;
5391 if (*p == 'x') {
5392 p++;
5393 depth = strtol(p, (char **)&p, 10);
5394 if (depth != 8 && depth != 15 && depth != 16 &&
5395 depth != 24 && depth != 32)
5396 goto graphic_error;
5397 } else if (*p == '\0') {
5398 depth = graphic_depth;
5399 } else {
5400 goto graphic_error;
5403 graphic_width = w;
5404 graphic_height = h;
5405 graphic_depth = depth;
5407 break;
5408 #endif
5409 case QEMU_OPTION_echr:
5411 char *r;
5412 term_escape_char = strtol(optarg, &r, 0);
5413 if (r == optarg)
5414 printf("Bad argument to echr\n");
5415 break;
5417 case QEMU_OPTION_monitor:
5418 monitor_device = optarg;
5419 break;
5420 case QEMU_OPTION_serial:
5421 if (serial_device_index >= MAX_SERIAL_PORTS) {
5422 fprintf(stderr, "qemu: too many serial ports\n");
5423 exit(1);
5425 serial_devices[serial_device_index] = optarg;
5426 serial_device_index++;
5427 break;
5428 case QEMU_OPTION_watchdog:
5429 i = select_watchdog(optarg);
5430 if (i > 0)
5431 exit (i == 1 ? 1 : 0);
5432 break;
5433 case QEMU_OPTION_watchdog_action:
5434 if (select_watchdog_action(optarg) == -1) {
5435 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5436 exit(1);
5438 break;
5439 case QEMU_OPTION_virtiocon:
5440 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5441 fprintf(stderr, "qemu: too many virtio consoles\n");
5442 exit(1);
5444 virtio_consoles[virtio_console_index] = optarg;
5445 virtio_console_index++;
5446 break;
5447 case QEMU_OPTION_parallel:
5448 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5449 fprintf(stderr, "qemu: too many parallel ports\n");
5450 exit(1);
5452 parallel_devices[parallel_device_index] = optarg;
5453 parallel_device_index++;
5454 break;
5455 case QEMU_OPTION_loadvm:
5456 loadvm = optarg;
5457 break;
5458 case QEMU_OPTION_full_screen:
5459 full_screen = 1;
5460 break;
5461 #ifdef CONFIG_SDL
5462 case QEMU_OPTION_no_frame:
5463 no_frame = 1;
5464 break;
5465 case QEMU_OPTION_alt_grab:
5466 alt_grab = 1;
5467 break;
5468 case QEMU_OPTION_no_quit:
5469 no_quit = 1;
5470 break;
5471 case QEMU_OPTION_sdl:
5472 display_type = DT_SDL;
5473 break;
5474 #endif
5475 case QEMU_OPTION_pidfile:
5476 pid_file = optarg;
5477 break;
5478 #ifdef TARGET_I386
5479 case QEMU_OPTION_win2k_hack:
5480 win2k_install_hack = 1;
5481 break;
5482 case QEMU_OPTION_rtc_td_hack:
5483 rtc_td_hack = 1;
5484 break;
5485 case QEMU_OPTION_acpitable:
5486 if(acpi_table_add(optarg) < 0) {
5487 fprintf(stderr, "Wrong acpi table provided\n");
5488 exit(1);
5490 break;
5491 case QEMU_OPTION_smbios:
5492 if(smbios_entry_add(optarg) < 0) {
5493 fprintf(stderr, "Wrong smbios provided\n");
5494 exit(1);
5496 break;
5497 #endif
5498 #ifdef CONFIG_KQEMU
5499 case QEMU_OPTION_enable_kqemu:
5500 kqemu_allowed = 1;
5501 break;
5502 case QEMU_OPTION_kernel_kqemu:
5503 kqemu_allowed = 2;
5504 break;
5505 #endif
5506 #ifdef CONFIG_KVM
5507 #ifdef KVM_UPSTREAM
5508 case QEMU_OPTION_enable_kvm:
5509 kvm_allowed = 1;
5510 #ifdef CONFIG_KQEMU
5511 kqemu_allowed = 0;
5512 #endif
5513 #endif
5514 break;
5515 case QEMU_OPTION_no_kvm:
5516 kvm_allowed = 0;
5517 break;
5518 case QEMU_OPTION_no_kvm_irqchip: {
5519 kvm_irqchip = 0;
5520 kvm_pit = 0;
5521 break;
5523 case QEMU_OPTION_no_kvm_pit: {
5524 kvm_pit = 0;
5525 break;
5527 case QEMU_OPTION_no_kvm_pit_reinjection: {
5528 kvm_pit_reinject = 0;
5529 break;
5531 case QEMU_OPTION_enable_nesting: {
5532 kvm_nested = 1;
5533 break;
5535 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5536 case QEMU_OPTION_pcidevice:
5537 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5538 fprintf(stderr, "Too many assigned devices\n");
5539 exit(1);
5541 assigned_devices[assigned_devices_index] = optarg;
5542 assigned_devices_index++;
5543 break;
5544 #endif
5545 #endif
5546 case QEMU_OPTION_usb:
5547 usb_enabled = 1;
5548 break;
5549 case QEMU_OPTION_usbdevice:
5550 usb_enabled = 1;
5551 if (usb_devices_index >= MAX_USB_CMDLINE) {
5552 fprintf(stderr, "Too many USB devices\n");
5553 exit(1);
5555 usb_devices[usb_devices_index] = optarg;
5556 usb_devices_index++;
5557 break;
5558 case QEMU_OPTION_smp:
5559 smp_cpus = atoi(optarg);
5560 if (smp_cpus < 1) {
5561 fprintf(stderr, "Invalid number of CPUs\n");
5562 exit(1);
5564 break;
5565 case QEMU_OPTION_vnc:
5566 display_type = DT_VNC;
5567 vnc_display = optarg;
5568 break;
5569 #ifdef TARGET_I386
5570 case QEMU_OPTION_no_acpi:
5571 acpi_enabled = 0;
5572 break;
5573 case QEMU_OPTION_no_hpet:
5574 no_hpet = 1;
5575 break;
5576 case QEMU_OPTION_balloon:
5577 if (balloon_parse(optarg) < 0) {
5578 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5579 exit(1);
5581 break;
5582 #endif
5583 case QEMU_OPTION_no_reboot:
5584 no_reboot = 1;
5585 break;
5586 case QEMU_OPTION_no_shutdown:
5587 no_shutdown = 1;
5588 break;
5589 case QEMU_OPTION_show_cursor:
5590 cursor_hide = 0;
5591 break;
5592 case QEMU_OPTION_uuid:
5593 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5594 fprintf(stderr, "Fail to parse UUID string."
5595 " Wrong format.\n");
5596 exit(1);
5598 break;
5599 #ifndef _WIN32
5600 case QEMU_OPTION_daemonize:
5601 daemonize = 1;
5602 break;
5603 #endif
5604 case QEMU_OPTION_option_rom:
5605 if (nb_option_roms >= MAX_OPTION_ROMS) {
5606 fprintf(stderr, "Too many option ROMs\n");
5607 exit(1);
5609 option_rom[nb_option_roms] = optarg;
5610 nb_option_roms++;
5611 break;
5612 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5613 case QEMU_OPTION_semihosting:
5614 semihosting_enabled = 1;
5615 break;
5616 #endif
5617 case QEMU_OPTION_tdf:
5618 time_drift_fix = 1;
5619 break;
5620 case QEMU_OPTION_kvm_shadow_memory:
5621 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5622 break;
5623 case QEMU_OPTION_mempath:
5624 mem_path = optarg;
5625 break;
5626 #ifdef MAP_POPULATE
5627 case QEMU_OPTION_mem_prealloc:
5628 mem_prealloc = !mem_prealloc;
5629 break;
5630 #endif
5631 case QEMU_OPTION_name:
5632 qemu_name = qemu_strdup(optarg);
5634 char *p = strchr(qemu_name, ',');
5635 if (p != NULL) {
5636 *p++ = 0;
5637 if (strncmp(p, "process=", 8)) {
5638 fprintf(stderr, "Unknown subargument %s to -name", p);
5639 exit(1);
5641 p += 8;
5642 set_proc_name(p);
5645 break;
5646 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5647 case QEMU_OPTION_prom_env:
5648 if (nb_prom_envs >= MAX_PROM_ENVS) {
5649 fprintf(stderr, "Too many prom variables\n");
5650 exit(1);
5652 prom_envs[nb_prom_envs] = optarg;
5653 nb_prom_envs++;
5654 break;
5655 #endif
5656 #ifdef TARGET_ARM
5657 case QEMU_OPTION_old_param:
5658 old_param = 1;
5659 break;
5660 #endif
5661 case QEMU_OPTION_clock:
5662 configure_alarms(optarg);
5663 break;
5664 case QEMU_OPTION_startdate:
5666 struct tm tm;
5667 time_t rtc_start_date;
5668 if (!strcmp(optarg, "now")) {
5669 rtc_date_offset = -1;
5670 } else {
5671 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5672 &tm.tm_year,
5673 &tm.tm_mon,
5674 &tm.tm_mday,
5675 &tm.tm_hour,
5676 &tm.tm_min,
5677 &tm.tm_sec) == 6) {
5678 /* OK */
5679 } else if (sscanf(optarg, "%d-%d-%d",
5680 &tm.tm_year,
5681 &tm.tm_mon,
5682 &tm.tm_mday) == 3) {
5683 tm.tm_hour = 0;
5684 tm.tm_min = 0;
5685 tm.tm_sec = 0;
5686 } else {
5687 goto date_fail;
5689 tm.tm_year -= 1900;
5690 tm.tm_mon--;
5691 rtc_start_date = mktimegm(&tm);
5692 if (rtc_start_date == -1) {
5693 date_fail:
5694 fprintf(stderr, "Invalid date format. Valid format are:\n"
5695 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5696 exit(1);
5698 rtc_date_offset = time(NULL) - rtc_start_date;
5701 break;
5702 case QEMU_OPTION_tb_size:
5703 tb_size = strtol(optarg, NULL, 0);
5704 if (tb_size < 0)
5705 tb_size = 0;
5706 break;
5707 case QEMU_OPTION_icount:
5708 use_icount = 1;
5709 if (strcmp(optarg, "auto") == 0) {
5710 icount_time_shift = -1;
5711 } else {
5712 icount_time_shift = strtol(optarg, NULL, 0);
5714 break;
5715 case QEMU_OPTION_incoming:
5716 incoming = optarg;
5717 break;
5718 #ifndef _WIN32
5719 case QEMU_OPTION_chroot:
5720 chroot_dir = optarg;
5721 break;
5722 case QEMU_OPTION_runas:
5723 run_as = optarg;
5724 break;
5725 case QEMU_OPTION_nvram:
5726 nvram = optarg;
5727 break;
5728 #endif
5729 #ifdef CONFIG_XEN
5730 case QEMU_OPTION_xen_domid:
5731 xen_domid = atoi(optarg);
5732 break;
5733 case QEMU_OPTION_xen_create:
5734 xen_mode = XEN_CREATE;
5735 break;
5736 case QEMU_OPTION_xen_attach:
5737 xen_mode = XEN_ATTACH;
5738 break;
5739 #endif
5744 /* If no data_dir is specified then try to find it relative to the
5745 executable path. */
5746 if (!data_dir) {
5747 data_dir = find_datadir(argv[0]);
5749 /* If all else fails use the install patch specified when building. */
5750 if (!data_dir) {
5751 data_dir = CONFIG_QEMU_SHAREDIR;
5754 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5755 if (kvm_allowed && kqemu_allowed) {
5756 fprintf(stderr,
5757 "You can not enable both KVM and kqemu at the same time\n");
5758 exit(1);
5760 #endif
5762 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5763 if (smp_cpus > machine->max_cpus) {
5764 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5765 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5766 machine->max_cpus);
5767 exit(1);
5770 if (display_type == DT_NOGRAPHIC) {
5771 if (serial_device_index == 0)
5772 serial_devices[0] = "stdio";
5773 if (parallel_device_index == 0)
5774 parallel_devices[0] = "null";
5775 if (strncmp(monitor_device, "vc", 2) == 0)
5776 monitor_device = "stdio";
5779 #ifndef _WIN32
5780 if (daemonize) {
5781 pid_t pid;
5783 if (pipe(fds) == -1)
5784 exit(1);
5786 pid = fork();
5787 if (pid > 0) {
5788 uint8_t status;
5789 ssize_t len;
5791 close(fds[1]);
5793 again:
5794 len = read(fds[0], &status, 1);
5795 if (len == -1 && (errno == EINTR))
5796 goto again;
5798 if (len != 1)
5799 exit(1);
5800 else if (status == 1) {
5801 fprintf(stderr, "Could not acquire pidfile\n");
5802 exit(1);
5803 } else
5804 exit(0);
5805 } else if (pid < 0)
5806 exit(1);
5808 setsid();
5810 pid = fork();
5811 if (pid > 0)
5812 exit(0);
5813 else if (pid < 0)
5814 exit(1);
5816 umask(027);
5818 signal(SIGTSTP, SIG_IGN);
5819 signal(SIGTTOU, SIG_IGN);
5820 signal(SIGTTIN, SIG_IGN);
5823 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5824 if (daemonize) {
5825 uint8_t status = 1;
5826 write(fds[1], &status, 1);
5827 } else
5828 fprintf(stderr, "Could not acquire pid file\n");
5829 exit(1);
5831 #endif
5833 #ifdef CONFIG_KQEMU
5834 if (smp_cpus > 1)
5835 kqemu_allowed = 0;
5836 #endif
5837 if (qemu_init_main_loop()) {
5838 fprintf(stderr, "qemu_init_main_loop failed\n");
5839 exit(1);
5841 linux_boot = (kernel_filename != NULL);
5843 if (!linux_boot && *kernel_cmdline != '\0') {
5844 fprintf(stderr, "-append only allowed with -kernel option\n");
5845 exit(1);
5848 if (!linux_boot && initrd_filename != NULL) {
5849 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5850 exit(1);
5853 setvbuf(stdout, NULL, _IOLBF, 0);
5855 init_timers();
5856 if (init_timer_alarm() < 0) {
5857 fprintf(stderr, "could not initialize alarm timer\n");
5858 exit(1);
5860 if (use_icount && icount_time_shift < 0) {
5861 use_icount = 2;
5862 /* 125MIPS seems a reasonable initial guess at the guest speed.
5863 It will be corrected fairly quickly anyway. */
5864 icount_time_shift = 3;
5865 init_icount_adjust();
5868 #ifdef _WIN32
5869 socket_init();
5870 #endif
5872 /* init network clients */
5873 if (nb_net_clients == 0) {
5874 /* if no clients, we use a default config */
5875 net_clients[nb_net_clients++] = "nic";
5876 #ifdef CONFIG_SLIRP
5877 net_clients[nb_net_clients++] = "user";
5878 #endif
5881 for(i = 0;i < nb_net_clients; i++) {
5882 if (net_client_parse(net_clients[i]) < 0)
5883 exit(1);
5886 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5887 net_set_boot_mask(net_boot);
5889 net_client_check();
5891 /* init the bluetooth world */
5892 for (i = 0; i < nb_bt_opts; i++)
5893 if (bt_parse(bt_opts[i]))
5894 exit(1);
5896 /* init the memory */
5897 if (ram_size == 0)
5898 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5900 #ifdef CONFIG_KQEMU
5901 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5902 guest ram allocation. It needs to go away. */
5903 if (kqemu_allowed) {
5904 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
5905 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5906 if (!kqemu_phys_ram_base) {
5907 fprintf(stderr, "Could not allocate physical memory\n");
5908 exit(1);
5911 #endif
5913 /* init the dynamic translator */
5914 cpu_exec_init_all(tb_size * 1024 * 1024);
5916 bdrv_init();
5918 /* we always create the cdrom drive, even if no disk is there */
5920 if (nb_drives_opt < MAX_DRIVES)
5921 drive_add(NULL, CDROM_ALIAS);
5923 /* we always create at least one floppy */
5925 if (nb_drives_opt < MAX_DRIVES)
5926 drive_add(NULL, FD_ALIAS, 0);
5928 /* we always create one sd slot, even if no card is in it */
5930 if (nb_drives_opt < MAX_DRIVES)
5931 drive_add(NULL, SD_ALIAS);
5933 /* open the virtual block devices */
5935 for(i = 0; i < nb_drives_opt; i++)
5936 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5937 exit(1);
5939 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5940 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5942 #ifndef _WIN32
5943 /* must be after terminal init, SDL library changes signal handlers */
5944 sighandler_setup();
5945 #endif
5947 /* Maintain compatibility with multiple stdio monitors */
5948 if (!strcmp(monitor_device,"stdio")) {
5949 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5950 const char *devname = serial_devices[i];
5951 if (devname && !strcmp(devname,"mon:stdio")) {
5952 monitor_device = NULL;
5953 break;
5954 } else if (devname && !strcmp(devname,"stdio")) {
5955 monitor_device = NULL;
5956 serial_devices[i] = "mon:stdio";
5957 break;
5962 if (nb_numa_nodes > 0) {
5963 int i;
5965 if (nb_numa_nodes > smp_cpus) {
5966 nb_numa_nodes = smp_cpus;
5969 /* If no memory size if given for any node, assume the default case
5970 * and distribute the available memory equally across all nodes
5972 for (i = 0; i < nb_numa_nodes; i++) {
5973 if (node_mem[i] != 0)
5974 break;
5976 if (i == nb_numa_nodes) {
5977 uint64_t usedmem = 0;
5979 /* On Linux, the each node's border has to be 8MB aligned,
5980 * the final node gets the rest.
5982 for (i = 0; i < nb_numa_nodes - 1; i++) {
5983 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5984 usedmem += node_mem[i];
5986 node_mem[i] = ram_size - usedmem;
5989 for (i = 0; i < nb_numa_nodes; i++) {
5990 if (node_cpumask[i] != 0)
5991 break;
5993 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5994 * must cope with this anyway, because there are BIOSes out there in
5995 * real machines which also use this scheme.
5997 if (i == nb_numa_nodes) {
5998 for (i = 0; i < smp_cpus; i++) {
5999 node_cpumask[i % nb_numa_nodes] |= 1 << i;
6004 if (kvm_enabled()) {
6005 int ret;
6007 ret = kvm_init(smp_cpus);
6008 if (ret < 0) {
6009 #if defined(KVM_UPSTREAM) || defined(NO_CPU_EMULATION)
6010 fprintf(stderr, "failed to initialize KVM\n");
6011 exit(1);
6012 #endif
6013 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
6014 kvm_allowed = 0;
6018 if (monitor_device) {
6019 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
6020 if (!monitor_hd) {
6021 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6022 exit(1);
6026 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6027 const char *devname = serial_devices[i];
6028 if (devname && strcmp(devname, "none")) {
6029 char label[32];
6030 snprintf(label, sizeof(label), "serial%d", i);
6031 serial_hds[i] = qemu_chr_open(label, devname, NULL);
6032 if (!serial_hds[i]) {
6033 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6034 devname);
6035 exit(1);
6040 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6041 const char *devname = parallel_devices[i];
6042 if (devname && strcmp(devname, "none")) {
6043 char label[32];
6044 snprintf(label, sizeof(label), "parallel%d", i);
6045 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
6046 if (!parallel_hds[i]) {
6047 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6048 devname);
6049 exit(1);
6054 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6055 const char *devname = virtio_consoles[i];
6056 if (devname && strcmp(devname, "none")) {
6057 char label[32];
6058 snprintf(label, sizeof(label), "virtcon%d", i);
6059 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
6060 if (!virtcon_hds[i]) {
6061 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
6062 devname);
6063 exit(1);
6068 module_call_init(MODULE_INIT_DEVICE);
6070 machine->init(ram_size, boot_devices,
6071 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6074 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6075 for (i = 0; i < nb_numa_nodes; i++) {
6076 if (node_cpumask[i] & (1 << env->cpu_index)) {
6077 env->numa_node = i;
6082 current_machine = machine;
6084 /* init USB devices */
6085 if (usb_enabled) {
6086 for(i = 0; i < usb_devices_index; i++) {
6087 if (usb_device_add(usb_devices[i], 0) < 0) {
6088 fprintf(stderr, "Warning: could not add USB device %s\n",
6089 usb_devices[i]);
6094 if (!display_state)
6095 dumb_display_init();
6096 /* just use the first displaystate for the moment */
6097 ds = display_state;
6099 if (display_type == DT_DEFAULT) {
6100 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6101 display_type = DT_SDL;
6102 #else
6103 display_type = DT_VNC;
6104 vnc_display = "localhost:0,to=99";
6105 show_vnc_port = 1;
6106 #endif
6110 switch (display_type) {
6111 case DT_NOGRAPHIC:
6112 break;
6113 #if defined(CONFIG_CURSES)
6114 case DT_CURSES:
6115 curses_display_init(ds, full_screen);
6116 break;
6117 #endif
6118 #if defined(CONFIG_SDL)
6119 case DT_SDL:
6120 sdl_display_init(ds, full_screen, no_frame);
6121 break;
6122 #elif defined(CONFIG_COCOA)
6123 case DT_SDL:
6124 cocoa_display_init(ds, full_screen);
6125 break;
6126 #endif
6127 case DT_VNC:
6128 vnc_display_init(ds);
6129 if (vnc_display_open(ds, vnc_display) < 0)
6130 exit(1);
6132 if (show_vnc_port) {
6133 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6135 break;
6136 default:
6137 break;
6139 dpy_resize(ds);
6141 dcl = ds->listeners;
6142 while (dcl != NULL) {
6143 if (dcl->dpy_refresh != NULL) {
6144 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6145 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6147 dcl = dcl->next;
6150 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6151 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6152 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6155 text_consoles_set_display(display_state);
6156 qemu_chr_initial_reset();
6158 if (monitor_device && monitor_hd)
6159 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6161 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6162 const char *devname = serial_devices[i];
6163 if (devname && strcmp(devname, "none")) {
6164 if (strstart(devname, "vc", 0))
6165 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6169 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6170 const char *devname = parallel_devices[i];
6171 if (devname && strcmp(devname, "none")) {
6172 if (strstart(devname, "vc", 0))
6173 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6177 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6178 const char *devname = virtio_consoles[i];
6179 if (virtcon_hds[i] && devname) {
6180 if (strstart(devname, "vc", 0))
6181 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6185 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6186 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6187 gdbstub_dev);
6188 exit(1);
6191 if (loadvm)
6192 do_loadvm(cur_mon, loadvm);
6194 if (incoming) {
6195 autostart = 0; /* fixme how to deal with -daemonize */
6196 qemu_start_incoming_migration(incoming);
6199 if (autostart)
6200 vm_start();
6202 #ifndef _WIN32
6203 if (daemonize) {
6204 uint8_t status = 0;
6205 ssize_t len;
6207 again1:
6208 len = write(fds[1], &status, 1);
6209 if (len == -1 && (errno == EINTR))
6210 goto again1;
6212 if (len != 1)
6213 exit(1);
6215 chdir("/");
6216 TFR(fd = open("/dev/null", O_RDWR));
6217 if (fd == -1)
6218 exit(1);
6221 if (run_as) {
6222 pwd = getpwnam(run_as);
6223 if (!pwd) {
6224 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6225 exit(1);
6229 if (chroot_dir) {
6230 if (chroot(chroot_dir) < 0) {
6231 fprintf(stderr, "chroot failed\n");
6232 exit(1);
6234 chdir("/");
6237 if (run_as) {
6238 if (setgid(pwd->pw_gid) < 0) {
6239 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6240 exit(1);
6242 if (setuid(pwd->pw_uid) < 0) {
6243 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6244 exit(1);
6246 if (setuid(0) != -1) {
6247 fprintf(stderr, "Dropping privileges failed\n");
6248 exit(1);
6252 if (daemonize) {
6253 dup2(fd, 0);
6254 dup2(fd, 1);
6255 dup2(fd, 2);
6257 close(fd);
6259 #endif
6261 main_loop();
6262 quit_timers();
6263 net_cleanup();
6265 return 0;