Fix error handling in msix vector add
[qemu-kvm/fedora.git] / vl.c
blob50316dcc1fb7cb14e5170f98811a6f909f0b2508
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"
34 /* Needed early to override system queue definitions on BSD */
35 #include "sys-queue.h"
37 #ifndef _WIN32
38 #include <libgen.h>
39 #include <pwd.h>
40 #include <sys/times.h>
41 #include <sys/wait.h>
42 #include <termios.h>
43 #include <sys/mman.h>
44 #include <sys/ioctl.h>
45 #include <sys/resource.h>
46 #include <sys/socket.h>
47 #include <netinet/in.h>
48 #include <net/if.h>
49 #if defined(__NetBSD__)
50 #include <net/if_tap.h>
51 #endif
52 #ifdef __linux__
53 #include <linux/if_tun.h>
54 #endif
55 #include <arpa/inet.h>
56 #include <dirent.h>
57 #include <netdb.h>
58 #include <sys/select.h>
59 #ifdef HOST_BSD
60 #include <sys/stat.h>
61 #if defined(__FreeBSD__) || defined(__DragonFly__)
62 #include <libutil.h>
63 #else
64 #include <util.h>
65 #endif
66 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
67 #include <freebsd/stdlib.h>
68 #else
69 #ifdef __linux__
70 #include <pty.h>
71 #include <malloc.h>
72 #include <linux/rtc.h>
73 #include <sys/prctl.h>
75 /* For the benefit of older linux systems which don't supply it,
76 we use a local copy of hpet.h. */
77 /* #include <linux/hpet.h> */
78 #include "hpet.h"
80 #include <linux/ppdev.h>
81 #include <linux/parport.h>
82 #endif
83 #ifdef __sun__
84 #include <sys/stat.h>
85 #include <sys/ethernet.h>
86 #include <sys/sockio.h>
87 #include <netinet/arp.h>
88 #include <netinet/in.h>
89 #include <netinet/in_systm.h>
90 #include <netinet/ip.h>
91 #include <netinet/ip_icmp.h> // must come after ip.h
92 #include <netinet/udp.h>
93 #include <netinet/tcp.h>
94 #include <net/if.h>
95 #include <syslog.h>
96 #include <stropts.h>
97 #endif
98 #endif
99 #endif
101 #if defined(__OpenBSD__)
102 #include <util.h>
103 #endif
105 #if defined(CONFIG_VDE)
106 #include <libvdeplug.h>
107 #endif
109 #ifdef _WIN32
110 #include <windows.h>
111 #include <malloc.h>
112 #include <sys/timeb.h>
113 #include <mmsystem.h>
114 #define getopt_long_only getopt_long
115 #define memalign(align, size) malloc(size)
116 #endif
118 #ifdef CONFIG_SDL
119 #if defined(__APPLE__) || defined(main)
120 #include <SDL.h>
121 int qemu_main(int argc, char **argv, char **envp);
122 int main(int argc, char **argv)
124 return qemu_main(argc, argv, NULL);
126 #undef main
127 #define main qemu_main
128 #endif
129 #endif /* CONFIG_SDL */
131 #ifdef CONFIG_COCOA
132 #undef main
133 #define main qemu_main
134 #endif /* CONFIG_COCOA */
136 #include "hw/hw.h"
137 #include "hw/boards.h"
138 #include "hw/usb.h"
139 #include "hw/pcmcia.h"
140 #include "hw/pc.h"
141 #include "hw/audiodev.h"
142 #include "hw/isa.h"
143 #include "hw/baum.h"
144 #include "hw/bt.h"
145 #include "hw/watchdog.h"
146 #include "hw/smbios.h"
147 #include "hw/xen.h"
148 #include "bt-host.h"
149 #include "net.h"
150 #include "monitor.h"
151 #include "console.h"
152 #include "sysemu.h"
153 #include "gdbstub.h"
154 #include "qemu-timer.h"
155 #include "qemu-char.h"
156 #include "cache-utils.h"
157 #include "block.h"
158 #include "dma.h"
159 #include "audio/audio.h"
160 #include "migration.h"
161 #include "kvm.h"
162 #include "balloon.h"
163 #include "qemu-option.h"
164 #include "qemu-kvm.h"
165 #include "hw/device-assignment.h"
167 #include "disas.h"
169 #include "exec-all.h"
171 #include "qemu_socket.h"
173 #include "slirp/libslirp.h"
175 //#define DEBUG_NET
176 //#define DEBUG_SLIRP
178 #define DEFAULT_RAM_SIZE 128
180 /* Max number of USB devices that can be specified on the commandline. */
181 #define MAX_USB_CMDLINE 8
183 /* Max number of bluetooth switches on the commandline. */
184 #define MAX_BT_CMDLINE 10
186 static const char *data_dir;
187 const char *bios_name = NULL;
188 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
189 to store the VM snapshots */
190 DriveInfo drives_table[MAX_DRIVES+1];
191 int nb_drives;
192 int extboot_drive = -1;
193 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
194 static DisplayState *display_state;
195 DisplayType display_type = DT_DEFAULT;
196 const char* keyboard_layout = NULL;
197 int64_t ticks_per_sec;
198 ram_addr_t ram_size;
199 int nb_nics;
200 NICInfo nd_table[MAX_NICS];
201 int vm_running;
202 static int autostart;
203 static int rtc_utc = 1;
204 static int rtc_date_offset = -1; /* -1 means no change */
205 int cirrus_vga_enabled = 1;
206 int std_vga_enabled = 0;
207 int vmsvga_enabled = 0;
208 int xenfb_enabled = 0;
209 #ifdef TARGET_SPARC
210 int graphic_width = 1024;
211 int graphic_height = 768;
212 int graphic_depth = 8;
213 #else
214 int graphic_width = 800;
215 int graphic_height = 600;
216 int graphic_depth = 15;
217 #endif
218 static int full_screen = 0;
219 #ifdef CONFIG_SDL
220 static int no_frame = 0;
221 #endif
222 int no_quit = 0;
223 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
224 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
225 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
226 #ifdef TARGET_I386
227 int win2k_install_hack = 0;
228 int rtc_td_hack = 0;
229 #endif
230 int usb_enabled = 0;
231 int singlestep = 0;
232 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
233 int assigned_devices_index;
234 int smp_cpus = 1;
235 const char *vnc_display;
236 int acpi_enabled = 1;
237 #ifdef TARGET_I386
238 int no_hpet = 0;
239 #endif
240 int virtio_balloon = 1;
241 const char *virtio_balloon_devaddr;
242 int fd_bootchk = 1;
243 int no_reboot = 0;
244 int no_shutdown = 0;
245 int cursor_hide = 1;
246 int graphic_rotate = 0;
247 uint8_t irq0override = 1;
248 #ifndef _WIN32
249 int daemonize = 0;
250 #endif
251 WatchdogTimerModel *watchdog = NULL;
252 int watchdog_action = WDT_RESET;
253 const char *option_rom[MAX_OPTION_ROMS];
254 int nb_option_roms;
255 int semihosting_enabled = 0;
256 int time_drift_fix = 0;
257 unsigned int kvm_shadow_memory = 0;
258 const char *mem_path = NULL;
259 #ifdef MAP_POPULATE
260 int mem_prealloc = 1; /* force preallocation of physical target memory */
261 #endif
262 #ifdef TARGET_ARM
263 int old_param = 0;
264 #endif
265 const char *qemu_name;
266 int alt_grab = 0;
267 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
268 unsigned int nb_prom_envs = 0;
269 const char *prom_envs[MAX_PROM_ENVS];
270 #endif
271 int nb_drives_opt;
272 const char *nvram = NULL;
273 struct drive_opt drives_opt[MAX_DRIVES];
274 int boot_menu;
276 int nb_numa_nodes;
277 uint64_t node_mem[MAX_NODES];
278 uint64_t node_cpumask[MAX_NODES];
280 static CPUState *cur_cpu;
281 static CPUState *next_cpu;
282 static int timer_alarm_pending = 1;
283 /* Conversion factor from emulated instructions to virtual clock ticks. */
284 static int icount_time_shift;
285 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
286 #define MAX_ICOUNT_SHIFT 10
287 /* Compensate for varying guest execution speed. */
288 static int64_t qemu_icount_bias;
289 static QEMUTimer *icount_rt_timer;
290 static QEMUTimer *icount_vm_timer;
291 static QEMUTimer *nographic_timer;
293 uint8_t qemu_uuid[16];
295 static QEMUBootSetHandler *boot_set_handler;
296 static void *boot_set_opaque;
298 /***********************************************************/
299 /* x86 ISA bus support */
301 target_phys_addr_t isa_mem_base = 0;
302 PicState2 *isa_pic;
304 /***********************************************************/
305 void hw_error(const char *fmt, ...)
307 va_list ap;
308 CPUState *env;
310 va_start(ap, fmt);
311 fprintf(stderr, "qemu: hardware error: ");
312 vfprintf(stderr, fmt, ap);
313 fprintf(stderr, "\n");
314 for(env = first_cpu; env != NULL; env = env->next_cpu) {
315 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
316 #ifdef TARGET_I386
317 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
318 #else
319 cpu_dump_state(env, stderr, fprintf, 0);
320 #endif
322 va_end(ap);
323 abort();
326 static void set_proc_name(const char *s)
328 #ifdef __linux__
329 char name[16];
330 if (!s)
331 return;
332 name[sizeof(name) - 1] = 0;
333 strncpy(name, s, sizeof(name));
334 /* Could rewrite argv[0] too, but that's a bit more complicated.
335 This simple way is enough for `top'. */
336 prctl(PR_SET_NAME, name);
337 #endif
340 /***************/
341 /* ballooning */
343 static QEMUBalloonEvent *qemu_balloon_event;
344 void *qemu_balloon_event_opaque;
346 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
348 qemu_balloon_event = func;
349 qemu_balloon_event_opaque = opaque;
352 void qemu_balloon(ram_addr_t target)
354 if (qemu_balloon_event)
355 qemu_balloon_event(qemu_balloon_event_opaque, target);
358 ram_addr_t qemu_balloon_status(void)
360 if (qemu_balloon_event)
361 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
362 return 0;
365 /***********************************************************/
366 /* keyboard/mouse */
368 static QEMUPutKBDEvent *qemu_put_kbd_event;
369 static void *qemu_put_kbd_event_opaque;
370 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
371 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
373 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
375 qemu_put_kbd_event_opaque = opaque;
376 qemu_put_kbd_event = func;
379 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
380 void *opaque, int absolute,
381 const char *name)
383 QEMUPutMouseEntry *s, *cursor;
385 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
387 s->qemu_put_mouse_event = func;
388 s->qemu_put_mouse_event_opaque = opaque;
389 s->qemu_put_mouse_event_absolute = absolute;
390 s->qemu_put_mouse_event_name = qemu_strdup(name);
391 s->next = NULL;
393 if (!qemu_put_mouse_event_head) {
394 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
395 return s;
398 cursor = qemu_put_mouse_event_head;
399 while (cursor->next != NULL)
400 cursor = cursor->next;
402 cursor->next = s;
403 qemu_put_mouse_event_current = s;
405 return s;
408 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
410 QEMUPutMouseEntry *prev = NULL, *cursor;
412 if (!qemu_put_mouse_event_head || entry == NULL)
413 return;
415 cursor = qemu_put_mouse_event_head;
416 while (cursor != NULL && cursor != entry) {
417 prev = cursor;
418 cursor = cursor->next;
421 if (cursor == NULL) // does not exist or list empty
422 return;
423 else if (prev == NULL) { // entry is head
424 qemu_put_mouse_event_head = cursor->next;
425 if (qemu_put_mouse_event_current == entry)
426 qemu_put_mouse_event_current = cursor->next;
427 qemu_free(entry->qemu_put_mouse_event_name);
428 qemu_free(entry);
429 return;
432 prev->next = entry->next;
434 if (qemu_put_mouse_event_current == entry)
435 qemu_put_mouse_event_current = prev;
437 qemu_free(entry->qemu_put_mouse_event_name);
438 qemu_free(entry);
441 void kbd_put_keycode(int keycode)
443 if (qemu_put_kbd_event) {
444 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
448 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
450 QEMUPutMouseEvent *mouse_event;
451 void *mouse_event_opaque;
452 int width;
454 if (!qemu_put_mouse_event_current) {
455 return;
458 mouse_event =
459 qemu_put_mouse_event_current->qemu_put_mouse_event;
460 mouse_event_opaque =
461 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
463 if (mouse_event) {
464 if (graphic_rotate) {
465 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
466 width = 0x7fff;
467 else
468 width = graphic_width - 1;
469 mouse_event(mouse_event_opaque,
470 width - dy, dx, dz, buttons_state);
471 } else
472 mouse_event(mouse_event_opaque,
473 dx, dy, dz, buttons_state);
477 int kbd_mouse_is_absolute(void)
479 if (!qemu_put_mouse_event_current)
480 return 0;
482 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
485 void do_info_mice(Monitor *mon)
487 QEMUPutMouseEntry *cursor;
488 int index = 0;
490 if (!qemu_put_mouse_event_head) {
491 monitor_printf(mon, "No mouse devices connected\n");
492 return;
495 monitor_printf(mon, "Mouse devices available:\n");
496 cursor = qemu_put_mouse_event_head;
497 while (cursor != NULL) {
498 monitor_printf(mon, "%c Mouse #%d: %s\n",
499 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
500 index, cursor->qemu_put_mouse_event_name);
501 index++;
502 cursor = cursor->next;
506 void do_mouse_set(Monitor *mon, int index)
508 QEMUPutMouseEntry *cursor;
509 int i = 0;
511 if (!qemu_put_mouse_event_head) {
512 monitor_printf(mon, "No mouse devices connected\n");
513 return;
516 cursor = qemu_put_mouse_event_head;
517 while (cursor != NULL && index != i) {
518 i++;
519 cursor = cursor->next;
522 if (cursor != NULL)
523 qemu_put_mouse_event_current = cursor;
524 else
525 monitor_printf(mon, "Mouse at given index not found\n");
528 /* compute with 96 bit intermediate result: (a*b)/c */
529 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
531 union {
532 uint64_t ll;
533 struct {
534 #ifdef WORDS_BIGENDIAN
535 uint32_t high, low;
536 #else
537 uint32_t low, high;
538 #endif
539 } l;
540 } u, res;
541 uint64_t rl, rh;
543 u.ll = a;
544 rl = (uint64_t)u.l.low * (uint64_t)b;
545 rh = (uint64_t)u.l.high * (uint64_t)b;
546 rh += (rl >> 32);
547 res.l.high = rh / c;
548 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
549 return res.ll;
552 /***********************************************************/
553 /* real time host monotonic timer */
555 #define QEMU_TIMER_BASE 1000000000LL
557 #ifdef WIN32
559 static int64_t clock_freq;
561 static void init_get_clock(void)
563 LARGE_INTEGER freq;
564 int ret;
565 ret = QueryPerformanceFrequency(&freq);
566 if (ret == 0) {
567 fprintf(stderr, "Could not calibrate ticks\n");
568 exit(1);
570 clock_freq = freq.QuadPart;
573 static int64_t get_clock(void)
575 LARGE_INTEGER ti;
576 QueryPerformanceCounter(&ti);
577 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
580 #else
582 static int use_rt_clock;
584 static void init_get_clock(void)
586 use_rt_clock = 0;
587 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
588 || defined(__DragonFly__)
590 struct timespec ts;
591 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
592 use_rt_clock = 1;
595 #endif
598 static int64_t get_clock(void)
600 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
601 || defined(__DragonFly__)
602 if (use_rt_clock) {
603 struct timespec ts;
604 clock_gettime(CLOCK_MONOTONIC, &ts);
605 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
606 } else
607 #endif
609 /* XXX: using gettimeofday leads to problems if the date
610 changes, so it should be avoided. */
611 struct timeval tv;
612 gettimeofday(&tv, NULL);
613 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
616 #endif
618 /* Return the virtual CPU time, based on the instruction counter. */
619 static int64_t cpu_get_icount(void)
621 int64_t icount;
622 CPUState *env = cpu_single_env;;
623 icount = qemu_icount;
624 if (env) {
625 if (!can_do_io(env))
626 fprintf(stderr, "Bad clock read\n");
627 icount -= (env->icount_decr.u16.low + env->icount_extra);
629 return qemu_icount_bias + (icount << icount_time_shift);
632 /***********************************************************/
633 /* guest cycle counter */
635 static int64_t cpu_ticks_prev;
636 static int64_t cpu_ticks_offset;
637 static int64_t cpu_clock_offset;
638 static int cpu_ticks_enabled;
640 /* return the host CPU cycle counter and handle stop/restart */
641 int64_t cpu_get_ticks(void)
643 if (use_icount) {
644 return cpu_get_icount();
646 if (!cpu_ticks_enabled) {
647 return cpu_ticks_offset;
648 } else {
649 int64_t ticks;
650 ticks = cpu_get_real_ticks();
651 if (cpu_ticks_prev > ticks) {
652 /* Note: non increasing ticks may happen if the host uses
653 software suspend */
654 cpu_ticks_offset += cpu_ticks_prev - ticks;
656 cpu_ticks_prev = ticks;
657 return ticks + cpu_ticks_offset;
661 /* return the host CPU monotonic timer and handle stop/restart */
662 static int64_t cpu_get_clock(void)
664 int64_t ti;
665 if (!cpu_ticks_enabled) {
666 return cpu_clock_offset;
667 } else {
668 ti = get_clock();
669 return ti + cpu_clock_offset;
673 /* enable cpu_get_ticks() */
674 void cpu_enable_ticks(void)
676 if (!cpu_ticks_enabled) {
677 cpu_ticks_offset -= cpu_get_real_ticks();
678 cpu_clock_offset -= get_clock();
679 cpu_ticks_enabled = 1;
683 /* disable cpu_get_ticks() : the clock is stopped. You must not call
684 cpu_get_ticks() after that. */
685 void cpu_disable_ticks(void)
687 if (cpu_ticks_enabled) {
688 cpu_ticks_offset = cpu_get_ticks();
689 cpu_clock_offset = cpu_get_clock();
690 cpu_ticks_enabled = 0;
694 /***********************************************************/
695 /* timers */
697 #define QEMU_TIMER_REALTIME 0
698 #define QEMU_TIMER_VIRTUAL 1
700 struct QEMUClock {
701 int type;
702 /* XXX: add frequency */
705 struct QEMUTimer {
706 QEMUClock *clock;
707 int64_t expire_time;
708 QEMUTimerCB *cb;
709 void *opaque;
710 struct QEMUTimer *next;
713 struct qemu_alarm_timer {
714 char const *name;
715 unsigned int flags;
717 int (*start)(struct qemu_alarm_timer *t);
718 void (*stop)(struct qemu_alarm_timer *t);
719 void (*rearm)(struct qemu_alarm_timer *t);
720 void *priv;
723 #define ALARM_FLAG_DYNTICKS 0x1
724 #define ALARM_FLAG_EXPIRED 0x2
726 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
728 return t && (t->flags & ALARM_FLAG_DYNTICKS);
731 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
733 if (!alarm_has_dynticks(t))
734 return;
736 t->rearm(t);
739 /* TODO: MIN_TIMER_REARM_US should be optimized */
740 #define MIN_TIMER_REARM_US 250
742 static struct qemu_alarm_timer *alarm_timer;
744 #ifdef _WIN32
746 struct qemu_alarm_win32 {
747 MMRESULT timerId;
748 unsigned int period;
749 } alarm_win32_data = {0, -1};
751 static int win32_start_timer(struct qemu_alarm_timer *t);
752 static void win32_stop_timer(struct qemu_alarm_timer *t);
753 static void win32_rearm_timer(struct qemu_alarm_timer *t);
755 #else
757 static int unix_start_timer(struct qemu_alarm_timer *t);
758 static void unix_stop_timer(struct qemu_alarm_timer *t);
760 #ifdef __linux__
762 static int dynticks_start_timer(struct qemu_alarm_timer *t);
763 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
764 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
766 static int hpet_start_timer(struct qemu_alarm_timer *t);
767 static void hpet_stop_timer(struct qemu_alarm_timer *t);
769 static int rtc_start_timer(struct qemu_alarm_timer *t);
770 static void rtc_stop_timer(struct qemu_alarm_timer *t);
772 #endif /* __linux__ */
774 #endif /* _WIN32 */
776 /* Correlation between real and virtual time is always going to be
777 fairly approximate, so ignore small variation.
778 When the guest is idle real and virtual time will be aligned in
779 the IO wait loop. */
780 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
782 static void icount_adjust(void)
784 int64_t cur_time;
785 int64_t cur_icount;
786 int64_t delta;
787 static int64_t last_delta;
788 /* If the VM is not running, then do nothing. */
789 if (!vm_running)
790 return;
792 cur_time = cpu_get_clock();
793 cur_icount = qemu_get_clock(vm_clock);
794 delta = cur_icount - cur_time;
795 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
796 if (delta > 0
797 && last_delta + ICOUNT_WOBBLE < delta * 2
798 && icount_time_shift > 0) {
799 /* The guest is getting too far ahead. Slow time down. */
800 icount_time_shift--;
802 if (delta < 0
803 && last_delta - ICOUNT_WOBBLE > delta * 2
804 && icount_time_shift < MAX_ICOUNT_SHIFT) {
805 /* The guest is getting too far behind. Speed time up. */
806 icount_time_shift++;
808 last_delta = delta;
809 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
812 static void icount_adjust_rt(void * opaque)
814 qemu_mod_timer(icount_rt_timer,
815 qemu_get_clock(rt_clock) + 1000);
816 icount_adjust();
819 static void icount_adjust_vm(void * opaque)
821 qemu_mod_timer(icount_vm_timer,
822 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
823 icount_adjust();
826 static void init_icount_adjust(void)
828 /* Have both realtime and virtual time triggers for speed adjustment.
829 The realtime trigger catches emulated time passing too slowly,
830 the virtual time trigger catches emulated time passing too fast.
831 Realtime triggers occur even when idle, so use them less frequently
832 than VM triggers. */
833 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
834 qemu_mod_timer(icount_rt_timer,
835 qemu_get_clock(rt_clock) + 1000);
836 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
837 qemu_mod_timer(icount_vm_timer,
838 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
841 static struct qemu_alarm_timer alarm_timers[] = {
842 #ifndef _WIN32
843 #ifdef __linux__
844 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
845 dynticks_stop_timer, dynticks_rearm_timer, NULL},
846 /* HPET - if available - is preferred */
847 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
848 /* ...otherwise try RTC */
849 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
850 #endif
851 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
852 #else
853 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
854 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
855 {"win32", 0, win32_start_timer,
856 win32_stop_timer, NULL, &alarm_win32_data},
857 #endif
858 {NULL, }
861 static void show_available_alarms(void)
863 int i;
865 printf("Available alarm timers, in order of precedence:\n");
866 for (i = 0; alarm_timers[i].name; i++)
867 printf("%s\n", alarm_timers[i].name);
870 static void configure_alarms(char const *opt)
872 int i;
873 int cur = 0;
874 int count = ARRAY_SIZE(alarm_timers) - 1;
875 char *arg;
876 char *name;
877 struct qemu_alarm_timer tmp;
879 if (!strcmp(opt, "?")) {
880 show_available_alarms();
881 exit(0);
884 arg = strdup(opt);
886 /* Reorder the array */
887 name = strtok(arg, ",");
888 while (name) {
889 for (i = 0; i < count && alarm_timers[i].name; i++) {
890 if (!strcmp(alarm_timers[i].name, name))
891 break;
894 if (i == count) {
895 fprintf(stderr, "Unknown clock %s\n", name);
896 goto next;
899 if (i < cur)
900 /* Ignore */
901 goto next;
903 /* Swap */
904 tmp = alarm_timers[i];
905 alarm_timers[i] = alarm_timers[cur];
906 alarm_timers[cur] = tmp;
908 cur++;
909 next:
910 name = strtok(NULL, ",");
913 free(arg);
915 if (cur) {
916 /* Disable remaining timers */
917 for (i = cur; i < count; i++)
918 alarm_timers[i].name = NULL;
919 } else {
920 show_available_alarms();
921 exit(1);
925 QEMUClock *rt_clock;
926 QEMUClock *vm_clock;
928 static QEMUTimer *active_timers[2];
930 static QEMUClock *qemu_new_clock(int type)
932 QEMUClock *clock;
933 clock = qemu_mallocz(sizeof(QEMUClock));
934 clock->type = type;
935 return clock;
938 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
940 QEMUTimer *ts;
942 ts = qemu_mallocz(sizeof(QEMUTimer));
943 ts->clock = clock;
944 ts->cb = cb;
945 ts->opaque = opaque;
946 return ts;
949 void qemu_free_timer(QEMUTimer *ts)
951 qemu_free(ts);
954 /* stop a timer, but do not dealloc it */
955 void qemu_del_timer(QEMUTimer *ts)
957 QEMUTimer **pt, *t;
959 /* NOTE: this code must be signal safe because
960 qemu_timer_expired() can be called from a signal. */
961 pt = &active_timers[ts->clock->type];
962 for(;;) {
963 t = *pt;
964 if (!t)
965 break;
966 if (t == ts) {
967 *pt = t->next;
968 break;
970 pt = &t->next;
974 /* modify the current timer so that it will be fired when current_time
975 >= expire_time. The corresponding callback will be called. */
976 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
978 QEMUTimer **pt, *t;
980 qemu_del_timer(ts);
982 /* add the timer in the sorted list */
983 /* NOTE: this code must be signal safe because
984 qemu_timer_expired() can be called from a signal. */
985 pt = &active_timers[ts->clock->type];
986 for(;;) {
987 t = *pt;
988 if (!t)
989 break;
990 if (t->expire_time > expire_time)
991 break;
992 pt = &t->next;
994 ts->expire_time = expire_time;
995 ts->next = *pt;
996 *pt = ts;
998 /* Rearm if necessary */
999 if (pt == &active_timers[ts->clock->type]) {
1000 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1001 qemu_rearm_alarm_timer(alarm_timer);
1003 /* Interrupt execution to force deadline recalculation. */
1004 if (use_icount)
1005 qemu_notify_event();
1009 int qemu_timer_pending(QEMUTimer *ts)
1011 QEMUTimer *t;
1012 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1013 if (t == ts)
1014 return 1;
1016 return 0;
1019 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1021 if (!timer_head)
1022 return 0;
1023 return (timer_head->expire_time <= current_time);
1026 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1028 QEMUTimer *ts;
1030 for(;;) {
1031 ts = *ptimer_head;
1032 if (!ts || ts->expire_time > current_time)
1033 break;
1034 /* remove timer from the list before calling the callback */
1035 *ptimer_head = ts->next;
1036 ts->next = NULL;
1038 /* run the callback (the timer list can be modified) */
1039 ts->cb(ts->opaque);
1043 int64_t qemu_get_clock(QEMUClock *clock)
1045 switch(clock->type) {
1046 case QEMU_TIMER_REALTIME:
1047 return get_clock() / 1000000;
1048 default:
1049 case QEMU_TIMER_VIRTUAL:
1050 if (use_icount) {
1051 return cpu_get_icount();
1052 } else {
1053 return cpu_get_clock();
1058 static void init_timers(void)
1060 init_get_clock();
1061 ticks_per_sec = QEMU_TIMER_BASE;
1062 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1063 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1066 /* save a timer */
1067 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1069 uint64_t expire_time;
1071 if (qemu_timer_pending(ts)) {
1072 expire_time = ts->expire_time;
1073 } else {
1074 expire_time = -1;
1076 qemu_put_be64(f, expire_time);
1079 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1081 uint64_t expire_time;
1083 expire_time = qemu_get_be64(f);
1084 if (expire_time != -1) {
1085 qemu_mod_timer(ts, expire_time);
1086 } else {
1087 qemu_del_timer(ts);
1091 static void timer_save(QEMUFile *f, void *opaque)
1093 if (cpu_ticks_enabled) {
1094 hw_error("cannot save state if virtual timers are running");
1096 qemu_put_be64(f, cpu_ticks_offset);
1097 qemu_put_be64(f, ticks_per_sec);
1098 qemu_put_be64(f, cpu_clock_offset);
1101 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1103 if (version_id != 1 && version_id != 2)
1104 return -EINVAL;
1105 if (cpu_ticks_enabled) {
1106 return -EINVAL;
1108 cpu_ticks_offset=qemu_get_be64(f);
1109 ticks_per_sec=qemu_get_be64(f);
1110 if (version_id == 2) {
1111 cpu_clock_offset=qemu_get_be64(f);
1113 return 0;
1116 static void qemu_event_increment(void);
1118 #ifdef _WIN32
1119 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1120 DWORD_PTR dwUser, DWORD_PTR dw1,
1121 DWORD_PTR dw2)
1122 #else
1123 static void host_alarm_handler(int host_signum)
1124 #endif
1126 #if 0
1127 #define DISP_FREQ 1000
1129 static int64_t delta_min = INT64_MAX;
1130 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1131 static int count;
1132 ti = qemu_get_clock(vm_clock);
1133 if (last_clock != 0) {
1134 delta = ti - last_clock;
1135 if (delta < delta_min)
1136 delta_min = delta;
1137 if (delta > delta_max)
1138 delta_max = delta;
1139 delta_cum += delta;
1140 if (++count == DISP_FREQ) {
1141 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1142 muldiv64(delta_min, 1000000, ticks_per_sec),
1143 muldiv64(delta_max, 1000000, ticks_per_sec),
1144 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1145 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1146 count = 0;
1147 delta_min = INT64_MAX;
1148 delta_max = 0;
1149 delta_cum = 0;
1152 last_clock = ti;
1154 #endif
1155 if (alarm_has_dynticks(alarm_timer) ||
1156 (!use_icount &&
1157 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1158 qemu_get_clock(vm_clock))) ||
1159 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1160 qemu_get_clock(rt_clock))) {
1161 qemu_event_increment();
1162 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1164 #ifndef CONFIG_IOTHREAD
1165 if (next_cpu) {
1166 /* stop the currently executing cpu because a timer occured */
1167 cpu_exit(next_cpu);
1168 #ifdef CONFIG_KQEMU
1169 if (next_cpu->kqemu_enabled) {
1170 kqemu_cpu_interrupt(next_cpu);
1172 #endif
1174 #endif
1175 timer_alarm_pending = 1;
1176 qemu_notify_event();
1180 static int64_t qemu_next_deadline(void)
1182 int64_t delta;
1184 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1185 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1186 qemu_get_clock(vm_clock);
1187 } else {
1188 /* To avoid problems with overflow limit this to 2^32. */
1189 delta = INT32_MAX;
1192 if (delta < 0)
1193 delta = 0;
1195 return delta;
1198 #if defined(__linux__) || defined(_WIN32)
1199 static uint64_t qemu_next_deadline_dyntick(void)
1201 int64_t delta;
1202 int64_t rtdelta;
1204 if (use_icount)
1205 delta = INT32_MAX;
1206 else
1207 delta = (qemu_next_deadline() + 999) / 1000;
1209 if (active_timers[QEMU_TIMER_REALTIME]) {
1210 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1211 qemu_get_clock(rt_clock))*1000;
1212 if (rtdelta < delta)
1213 delta = rtdelta;
1216 if (delta < MIN_TIMER_REARM_US)
1217 delta = MIN_TIMER_REARM_US;
1219 return delta;
1221 #endif
1223 #ifndef _WIN32
1225 /* Sets a specific flag */
1226 static int fcntl_setfl(int fd, int flag)
1228 int flags;
1230 flags = fcntl(fd, F_GETFL);
1231 if (flags == -1)
1232 return -errno;
1234 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1235 return -errno;
1237 return 0;
1240 #if defined(__linux__)
1242 #define RTC_FREQ 1024
1244 static void enable_sigio_timer(int fd)
1246 struct sigaction act;
1248 /* timer signal */
1249 sigfillset(&act.sa_mask);
1250 act.sa_flags = 0;
1251 act.sa_handler = host_alarm_handler;
1253 sigaction(SIGIO, &act, NULL);
1254 fcntl_setfl(fd, O_ASYNC);
1255 fcntl(fd, F_SETOWN, getpid());
1258 static int hpet_start_timer(struct qemu_alarm_timer *t)
1260 struct hpet_info info;
1261 int r, fd;
1263 fd = open("/dev/hpet", O_RDONLY);
1264 if (fd < 0)
1265 return -1;
1267 /* Set frequency */
1268 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1269 if (r < 0) {
1270 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1271 "error, but for better emulation accuracy type:\n"
1272 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1273 goto fail;
1276 /* Check capabilities */
1277 r = ioctl(fd, HPET_INFO, &info);
1278 if (r < 0)
1279 goto fail;
1281 /* Enable periodic mode */
1282 r = ioctl(fd, HPET_EPI, 0);
1283 if (info.hi_flags && (r < 0))
1284 goto fail;
1286 /* Enable interrupt */
1287 r = ioctl(fd, HPET_IE_ON, 0);
1288 if (r < 0)
1289 goto fail;
1291 enable_sigio_timer(fd);
1292 t->priv = (void *)(long)fd;
1294 return 0;
1295 fail:
1296 close(fd);
1297 return -1;
1300 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1302 int fd = (long)t->priv;
1304 close(fd);
1307 static int rtc_start_timer(struct qemu_alarm_timer *t)
1309 int rtc_fd;
1310 unsigned long current_rtc_freq = 0;
1312 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1313 if (rtc_fd < 0)
1314 return -1;
1315 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1316 if (current_rtc_freq != RTC_FREQ &&
1317 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1318 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1319 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1320 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1321 goto fail;
1323 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1324 fail:
1325 close(rtc_fd);
1326 return -1;
1329 enable_sigio_timer(rtc_fd);
1331 t->priv = (void *)(long)rtc_fd;
1333 return 0;
1336 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1338 int rtc_fd = (long)t->priv;
1340 close(rtc_fd);
1343 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1345 struct sigevent ev;
1346 timer_t host_timer;
1347 struct sigaction act;
1349 sigfillset(&act.sa_mask);
1350 act.sa_flags = 0;
1351 act.sa_handler = host_alarm_handler;
1353 sigaction(SIGALRM, &act, NULL);
1356 * Initialize ev struct to 0 to avoid valgrind complaining
1357 * about uninitialized data in timer_create call
1359 memset(&ev, 0, sizeof(ev));
1360 ev.sigev_value.sival_int = 0;
1361 ev.sigev_notify = SIGEV_SIGNAL;
1362 ev.sigev_signo = SIGALRM;
1364 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1365 perror("timer_create");
1367 /* disable dynticks */
1368 fprintf(stderr, "Dynamic Ticks disabled\n");
1370 return -1;
1373 t->priv = (void *)(long)host_timer;
1375 return 0;
1378 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1380 timer_t host_timer = (timer_t)(long)t->priv;
1382 timer_delete(host_timer);
1385 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1387 timer_t host_timer = (timer_t)(long)t->priv;
1388 struct itimerspec timeout;
1389 int64_t nearest_delta_us = INT64_MAX;
1390 int64_t current_us;
1392 if (!active_timers[QEMU_TIMER_REALTIME] &&
1393 !active_timers[QEMU_TIMER_VIRTUAL])
1394 return;
1396 nearest_delta_us = qemu_next_deadline_dyntick();
1398 /* check whether a timer is already running */
1399 if (timer_gettime(host_timer, &timeout)) {
1400 perror("gettime");
1401 fprintf(stderr, "Internal timer error: aborting\n");
1402 exit(1);
1404 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1405 if (current_us && current_us <= nearest_delta_us)
1406 return;
1408 timeout.it_interval.tv_sec = 0;
1409 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1410 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1411 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1412 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1413 perror("settime");
1414 fprintf(stderr, "Internal timer error: aborting\n");
1415 exit(1);
1419 #endif /* defined(__linux__) */
1421 static int unix_start_timer(struct qemu_alarm_timer *t)
1423 struct sigaction act;
1424 struct itimerval itv;
1425 int err;
1427 /* timer signal */
1428 sigfillset(&act.sa_mask);
1429 act.sa_flags = 0;
1430 act.sa_handler = host_alarm_handler;
1432 sigaction(SIGALRM, &act, NULL);
1434 itv.it_interval.tv_sec = 0;
1435 /* for i386 kernel 2.6 to get 1 ms */
1436 itv.it_interval.tv_usec = 999;
1437 itv.it_value.tv_sec = 0;
1438 itv.it_value.tv_usec = 10 * 1000;
1440 err = setitimer(ITIMER_REAL, &itv, NULL);
1441 if (err)
1442 return -1;
1444 return 0;
1447 static void unix_stop_timer(struct qemu_alarm_timer *t)
1449 struct itimerval itv;
1451 memset(&itv, 0, sizeof(itv));
1452 setitimer(ITIMER_REAL, &itv, NULL);
1455 #endif /* !defined(_WIN32) */
1458 #ifdef _WIN32
1460 static int win32_start_timer(struct qemu_alarm_timer *t)
1462 TIMECAPS tc;
1463 struct qemu_alarm_win32 *data = t->priv;
1464 UINT flags;
1466 memset(&tc, 0, sizeof(tc));
1467 timeGetDevCaps(&tc, sizeof(tc));
1469 if (data->period < tc.wPeriodMin)
1470 data->period = tc.wPeriodMin;
1472 timeBeginPeriod(data->period);
1474 flags = TIME_CALLBACK_FUNCTION;
1475 if (alarm_has_dynticks(t))
1476 flags |= TIME_ONESHOT;
1477 else
1478 flags |= TIME_PERIODIC;
1480 data->timerId = timeSetEvent(1, // interval (ms)
1481 data->period, // resolution
1482 host_alarm_handler, // function
1483 (DWORD)t, // parameter
1484 flags);
1486 if (!data->timerId) {
1487 perror("Failed to initialize win32 alarm timer");
1488 timeEndPeriod(data->period);
1489 return -1;
1492 return 0;
1495 static void win32_stop_timer(struct qemu_alarm_timer *t)
1497 struct qemu_alarm_win32 *data = t->priv;
1499 timeKillEvent(data->timerId);
1500 timeEndPeriod(data->period);
1503 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1505 struct qemu_alarm_win32 *data = t->priv;
1506 uint64_t nearest_delta_us;
1508 if (!active_timers[QEMU_TIMER_REALTIME] &&
1509 !active_timers[QEMU_TIMER_VIRTUAL])
1510 return;
1512 nearest_delta_us = qemu_next_deadline_dyntick();
1513 nearest_delta_us /= 1000;
1515 timeKillEvent(data->timerId);
1517 data->timerId = timeSetEvent(1,
1518 data->period,
1519 host_alarm_handler,
1520 (DWORD)t,
1521 TIME_ONESHOT | TIME_PERIODIC);
1523 if (!data->timerId) {
1524 perror("Failed to re-arm win32 alarm timer");
1526 timeEndPeriod(data->period);
1527 exit(1);
1531 #endif /* _WIN32 */
1533 static int init_timer_alarm(void)
1535 struct qemu_alarm_timer *t = NULL;
1536 int i, err = -1;
1538 for (i = 0; alarm_timers[i].name; i++) {
1539 t = &alarm_timers[i];
1541 err = t->start(t);
1542 if (!err)
1543 break;
1546 if (err) {
1547 err = -ENOENT;
1548 goto fail;
1551 alarm_timer = t;
1553 return 0;
1555 fail:
1556 return err;
1559 static void quit_timers(void)
1561 alarm_timer->stop(alarm_timer);
1562 alarm_timer = NULL;
1565 /***********************************************************/
1566 /* host time/date access */
1567 void qemu_get_timedate(struct tm *tm, int offset)
1569 time_t ti;
1570 struct tm *ret;
1572 time(&ti);
1573 ti += offset;
1574 if (rtc_date_offset == -1) {
1575 if (rtc_utc)
1576 ret = gmtime(&ti);
1577 else
1578 ret = localtime(&ti);
1579 } else {
1580 ti -= rtc_date_offset;
1581 ret = gmtime(&ti);
1584 memcpy(tm, ret, sizeof(struct tm));
1587 int qemu_timedate_diff(struct tm *tm)
1589 time_t seconds;
1591 if (rtc_date_offset == -1)
1592 if (rtc_utc)
1593 seconds = mktimegm(tm);
1594 else
1595 seconds = mktime(tm);
1596 else
1597 seconds = mktimegm(tm) + rtc_date_offset;
1599 return seconds - time(NULL);
1602 #ifdef _WIN32
1603 static void socket_cleanup(void)
1605 WSACleanup();
1608 static int socket_init(void)
1610 WSADATA Data;
1611 int ret, err;
1613 ret = WSAStartup(MAKEWORD(2,2), &Data);
1614 if (ret != 0) {
1615 err = WSAGetLastError();
1616 fprintf(stderr, "WSAStartup: %d\n", err);
1617 return -1;
1619 atexit(socket_cleanup);
1620 return 0;
1622 #endif
1624 int get_next_param_value(char *buf, int buf_size,
1625 const char *tag, const char **pstr)
1627 const char *p;
1628 char option[128];
1630 p = *pstr;
1631 for(;;) {
1632 p = get_opt_name(option, sizeof(option), p, '=');
1633 if (*p != '=')
1634 break;
1635 p++;
1636 if (!strcmp(tag, option)) {
1637 *pstr = get_opt_value(buf, buf_size, p);
1638 if (**pstr == ',') {
1639 (*pstr)++;
1641 return strlen(buf);
1642 } else {
1643 p = get_opt_value(NULL, 0, p);
1645 if (*p != ',')
1646 break;
1647 p++;
1649 return 0;
1652 int get_param_value(char *buf, int buf_size,
1653 const char *tag, const char *str)
1655 return get_next_param_value(buf, buf_size, tag, &str);
1658 int check_params(char *buf, int buf_size,
1659 const char * const *params, const char *str)
1661 const char *p;
1662 int i;
1664 p = str;
1665 while (*p != '\0') {
1666 p = get_opt_name(buf, buf_size, p, '=');
1667 if (*p != '=') {
1668 return -1;
1670 p++;
1671 for (i = 0; params[i] != NULL; i++) {
1672 if (!strcmp(params[i], buf)) {
1673 break;
1676 if (params[i] == NULL) {
1677 return -1;
1679 p = get_opt_value(NULL, 0, p);
1680 if (*p != ',') {
1681 break;
1683 p++;
1685 return 0;
1688 /***********************************************************/
1689 /* Bluetooth support */
1690 static int nb_hcis;
1691 static int cur_hci;
1692 static struct HCIInfo *hci_table[MAX_NICS];
1694 static struct bt_vlan_s {
1695 struct bt_scatternet_s net;
1696 int id;
1697 struct bt_vlan_s *next;
1698 } *first_bt_vlan;
1700 /* find or alloc a new bluetooth "VLAN" */
1701 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1703 struct bt_vlan_s **pvlan, *vlan;
1704 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1705 if (vlan->id == id)
1706 return &vlan->net;
1708 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1709 vlan->id = id;
1710 pvlan = &first_bt_vlan;
1711 while (*pvlan != NULL)
1712 pvlan = &(*pvlan)->next;
1713 *pvlan = vlan;
1714 return &vlan->net;
1717 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1721 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1723 return -ENOTSUP;
1726 static struct HCIInfo null_hci = {
1727 .cmd_send = null_hci_send,
1728 .sco_send = null_hci_send,
1729 .acl_send = null_hci_send,
1730 .bdaddr_set = null_hci_addr_set,
1733 struct HCIInfo *qemu_next_hci(void)
1735 if (cur_hci == nb_hcis)
1736 return &null_hci;
1738 return hci_table[cur_hci++];
1741 static struct HCIInfo *hci_init(const char *str)
1743 char *endp;
1744 struct bt_scatternet_s *vlan = 0;
1746 if (!strcmp(str, "null"))
1747 /* null */
1748 return &null_hci;
1749 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1750 /* host[:hciN] */
1751 return bt_host_hci(str[4] ? str + 5 : "hci0");
1752 else if (!strncmp(str, "hci", 3)) {
1753 /* hci[,vlan=n] */
1754 if (str[3]) {
1755 if (!strncmp(str + 3, ",vlan=", 6)) {
1756 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1757 if (*endp)
1758 vlan = 0;
1760 } else
1761 vlan = qemu_find_bt_vlan(0);
1762 if (vlan)
1763 return bt_new_hci(vlan);
1766 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1768 return 0;
1771 static int bt_hci_parse(const char *str)
1773 struct HCIInfo *hci;
1774 bdaddr_t bdaddr;
1776 if (nb_hcis >= MAX_NICS) {
1777 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1778 return -1;
1781 hci = hci_init(str);
1782 if (!hci)
1783 return -1;
1785 bdaddr.b[0] = 0x52;
1786 bdaddr.b[1] = 0x54;
1787 bdaddr.b[2] = 0x00;
1788 bdaddr.b[3] = 0x12;
1789 bdaddr.b[4] = 0x34;
1790 bdaddr.b[5] = 0x56 + nb_hcis;
1791 hci->bdaddr_set(hci, bdaddr.b);
1793 hci_table[nb_hcis++] = hci;
1795 return 0;
1798 static void bt_vhci_add(int vlan_id)
1800 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1802 if (!vlan->slave)
1803 fprintf(stderr, "qemu: warning: adding a VHCI to "
1804 "an empty scatternet %i\n", vlan_id);
1806 bt_vhci_init(bt_new_hci(vlan));
1809 static struct bt_device_s *bt_device_add(const char *opt)
1811 struct bt_scatternet_s *vlan;
1812 int vlan_id = 0;
1813 char *endp = strstr(opt, ",vlan=");
1814 int len = (endp ? endp - opt : strlen(opt)) + 1;
1815 char devname[10];
1817 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1819 if (endp) {
1820 vlan_id = strtol(endp + 6, &endp, 0);
1821 if (*endp) {
1822 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1823 return 0;
1827 vlan = qemu_find_bt_vlan(vlan_id);
1829 if (!vlan->slave)
1830 fprintf(stderr, "qemu: warning: adding a slave device to "
1831 "an empty scatternet %i\n", vlan_id);
1833 if (!strcmp(devname, "keyboard"))
1834 return bt_keyboard_init(vlan);
1836 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1837 return 0;
1840 static int bt_parse(const char *opt)
1842 const char *endp, *p;
1843 int vlan;
1845 if (strstart(opt, "hci", &endp)) {
1846 if (!*endp || *endp == ',') {
1847 if (*endp)
1848 if (!strstart(endp, ",vlan=", 0))
1849 opt = endp + 1;
1851 return bt_hci_parse(opt);
1853 } else if (strstart(opt, "vhci", &endp)) {
1854 if (!*endp || *endp == ',') {
1855 if (*endp) {
1856 if (strstart(endp, ",vlan=", &p)) {
1857 vlan = strtol(p, (char **) &endp, 0);
1858 if (*endp) {
1859 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1860 return 1;
1862 } else {
1863 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1864 return 1;
1866 } else
1867 vlan = 0;
1869 bt_vhci_add(vlan);
1870 return 0;
1872 } else if (strstart(opt, "device:", &endp))
1873 return !bt_device_add(endp);
1875 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1876 return 1;
1879 /***********************************************************/
1880 /* QEMU Block devices */
1882 #define HD_ALIAS "index=%d,media=disk"
1883 #define CDROM_ALIAS "index=2,media=cdrom"
1884 #define FD_ALIAS "index=%d,if=floppy"
1885 #define PFLASH_ALIAS "if=pflash"
1886 #define MTD_ALIAS "if=mtd"
1887 #define SD_ALIAS "index=0,if=sd"
1889 static int drive_opt_get_free_idx(void)
1891 int index;
1893 for (index = 0; index < MAX_DRIVES; index++)
1894 if (!drives_opt[index].used) {
1895 drives_opt[index].used = 1;
1896 return index;
1899 return -1;
1902 static int drive_get_free_idx(void)
1904 int index;
1906 for (index = 0; index < MAX_DRIVES; index++)
1907 if (!drives_table[index].used) {
1908 drives_table[index].used = 1;
1909 return index;
1912 return -1;
1915 int drive_add(const char *file, const char *fmt, ...)
1917 va_list ap;
1918 int index = drive_opt_get_free_idx();
1920 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
1921 fprintf(stderr, "qemu: too many drives\n");
1922 return -1;
1925 drives_opt[index].file = file;
1926 va_start(ap, fmt);
1927 vsnprintf(drives_opt[index].opt,
1928 sizeof(drives_opt[0].opt), fmt, ap);
1929 va_end(ap);
1931 nb_drives_opt++;
1932 return index;
1935 void drive_remove(int index)
1937 drives_opt[index].used = 0;
1938 nb_drives_opt--;
1941 int drive_get_index(BlockInterfaceType type, int bus, int unit)
1943 int index;
1945 /* seek interface, bus and unit */
1947 for (index = 0; index < MAX_DRIVES; index++)
1948 if (drives_table[index].type == type &&
1949 drives_table[index].bus == bus &&
1950 drives_table[index].unit == unit &&
1951 drives_table[index].used)
1952 return index;
1954 return -1;
1957 int drive_get_max_bus(BlockInterfaceType type)
1959 int max_bus;
1960 int index;
1962 max_bus = -1;
1963 for (index = 0; index < nb_drives; index++) {
1964 if(drives_table[index].type == type &&
1965 drives_table[index].bus > max_bus)
1966 max_bus = drives_table[index].bus;
1968 return max_bus;
1971 const char *drive_get_serial(BlockDriverState *bdrv)
1973 int index;
1975 for (index = 0; index < nb_drives; index++)
1976 if (drives_table[index].bdrv == bdrv)
1977 return drives_table[index].serial;
1979 return "\0";
1982 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1984 int index;
1986 for (index = 0; index < nb_drives; index++)
1987 if (drives_table[index].bdrv == bdrv)
1988 return drives_table[index].onerror;
1990 return BLOCK_ERR_STOP_ENOSPC;
1993 static void bdrv_format_print(void *opaque, const char *name)
1995 fprintf(stderr, " %s", name);
1998 void drive_uninit(BlockDriverState *bdrv)
2000 int i;
2002 for (i = 0; i < MAX_DRIVES; i++)
2003 if (drives_table[i].bdrv == bdrv) {
2004 drives_table[i].bdrv = NULL;
2005 drives_table[i].used = 0;
2006 drive_remove(drives_table[i].drive_opt_idx);
2007 nb_drives--;
2008 break;
2012 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2014 char buf[128];
2015 char file[1024];
2016 char devname[128];
2017 char serial[21];
2018 const char *mediastr = "";
2019 BlockInterfaceType type;
2020 enum { MEDIA_DISK, MEDIA_CDROM } media;
2021 int bus_id, unit_id;
2022 int cyls, heads, secs, translation;
2023 BlockDriverState *bdrv;
2024 BlockDriver *drv = NULL;
2025 QEMUMachine *machine = opaque;
2026 int max_devs;
2027 int index;
2028 int cache;
2029 int bdrv_flags, onerror;
2030 const char *devaddr;
2031 int drives_table_idx;
2032 char *str = arg->opt;
2033 static const char * const params[] = { "bus", "unit", "if", "index",
2034 "cyls", "heads", "secs", "trans",
2035 "media", "snapshot", "file",
2036 "cache", "format", "serial",
2037 "werror", "addr",
2038 "boot",
2039 NULL };
2041 if (check_params(buf, sizeof(buf), params, str) < 0) {
2042 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2043 buf, str);
2044 return -1;
2047 file[0] = 0;
2048 cyls = heads = secs = 0;
2049 bus_id = 0;
2050 unit_id = -1;
2051 translation = BIOS_ATA_TRANSLATION_AUTO;
2052 index = -1;
2053 cache = 1;
2055 if (machine->use_scsi) {
2056 type = IF_SCSI;
2057 max_devs = MAX_SCSI_DEVS;
2058 pstrcpy(devname, sizeof(devname), "scsi");
2059 } else {
2060 type = IF_IDE;
2061 max_devs = MAX_IDE_DEVS;
2062 pstrcpy(devname, sizeof(devname), "ide");
2064 media = MEDIA_DISK;
2066 /* extract parameters */
2068 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2069 bus_id = strtol(buf, NULL, 0);
2070 if (bus_id < 0) {
2071 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2072 return -1;
2076 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2077 unit_id = strtol(buf, NULL, 0);
2078 if (unit_id < 0) {
2079 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2080 return -1;
2084 if (get_param_value(buf, sizeof(buf), "if", str)) {
2085 pstrcpy(devname, sizeof(devname), buf);
2086 if (!strcmp(buf, "ide")) {
2087 type = IF_IDE;
2088 max_devs = MAX_IDE_DEVS;
2089 } else if (!strcmp(buf, "scsi")) {
2090 type = IF_SCSI;
2091 max_devs = MAX_SCSI_DEVS;
2092 } else if (!strcmp(buf, "floppy")) {
2093 type = IF_FLOPPY;
2094 max_devs = 0;
2095 } else if (!strcmp(buf, "pflash")) {
2096 type = IF_PFLASH;
2097 max_devs = 0;
2098 } else if (!strcmp(buf, "mtd")) {
2099 type = IF_MTD;
2100 max_devs = 0;
2101 } else if (!strcmp(buf, "sd")) {
2102 type = IF_SD;
2103 max_devs = 0;
2104 } else if (!strcmp(buf, "virtio")) {
2105 type = IF_VIRTIO;
2106 max_devs = 0;
2107 } else if (!strcmp(buf, "xen")) {
2108 type = IF_XEN;
2109 max_devs = 0;
2110 } else {
2111 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2112 return -1;
2116 if (get_param_value(buf, sizeof(buf), "index", str)) {
2117 index = strtol(buf, NULL, 0);
2118 if (index < 0) {
2119 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2120 return -1;
2124 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2125 cyls = strtol(buf, NULL, 0);
2128 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2129 heads = strtol(buf, NULL, 0);
2132 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2133 secs = strtol(buf, NULL, 0);
2136 if (cyls || heads || secs) {
2137 if (cyls < 1 || cyls > 16383) {
2138 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2139 return -1;
2141 if (heads < 1 || heads > 16) {
2142 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2143 return -1;
2145 if (secs < 1 || secs > 63) {
2146 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2147 return -1;
2151 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2152 if (!cyls) {
2153 fprintf(stderr,
2154 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2155 str);
2156 return -1;
2158 if (!strcmp(buf, "none"))
2159 translation = BIOS_ATA_TRANSLATION_NONE;
2160 else if (!strcmp(buf, "lba"))
2161 translation = BIOS_ATA_TRANSLATION_LBA;
2162 else if (!strcmp(buf, "auto"))
2163 translation = BIOS_ATA_TRANSLATION_AUTO;
2164 else {
2165 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2166 return -1;
2170 if (get_param_value(buf, sizeof(buf), "media", str)) {
2171 if (!strcmp(buf, "disk")) {
2172 media = MEDIA_DISK;
2173 } else if (!strcmp(buf, "cdrom")) {
2174 if (cyls || secs || heads) {
2175 fprintf(stderr,
2176 "qemu: '%s' invalid physical CHS format\n", str);
2177 return -1;
2179 media = MEDIA_CDROM;
2180 } else {
2181 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2182 return -1;
2186 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2187 if (!strcmp(buf, "on"))
2188 snapshot = 1;
2189 else if (!strcmp(buf, "off"))
2190 snapshot = 0;
2191 else {
2192 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2193 return -1;
2197 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2198 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2199 cache = 0;
2200 else if (!strcmp(buf, "writethrough"))
2201 cache = 1;
2202 else if (!strcmp(buf, "writeback"))
2203 cache = 2;
2204 else {
2205 fprintf(stderr, "qemu: invalid cache option\n");
2206 return -1;
2210 if (get_param_value(buf, sizeof(buf), "format", str)) {
2211 if (strcmp(buf, "?") == 0) {
2212 fprintf(stderr, "qemu: Supported formats:");
2213 bdrv_iterate_format(bdrv_format_print, NULL);
2214 fprintf(stderr, "\n");
2215 return -1;
2217 drv = bdrv_find_format(buf);
2218 if (!drv) {
2219 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2220 return -1;
2224 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2225 if (!strcmp(buf, "on")) {
2226 if (extboot_drive != -1) {
2227 fprintf(stderr, "qemu: two bootable drives specified\n");
2228 return -1;
2230 extboot_drive = nb_drives;
2231 } else if (strcmp(buf, "off")) {
2232 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2233 return -1;
2237 if (arg->file == NULL)
2238 get_param_value(file, sizeof(file), "file", str);
2239 else
2240 pstrcpy(file, sizeof(file), arg->file);
2242 if (!get_param_value(serial, sizeof(serial), "serial", str))
2243 memset(serial, 0, sizeof(serial));
2245 onerror = BLOCK_ERR_STOP_ENOSPC;
2246 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2247 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2248 fprintf(stderr, "werror is no supported by this format\n");
2249 return -1;
2251 if (!strcmp(buf, "ignore"))
2252 onerror = BLOCK_ERR_IGNORE;
2253 else if (!strcmp(buf, "enospc"))
2254 onerror = BLOCK_ERR_STOP_ENOSPC;
2255 else if (!strcmp(buf, "stop"))
2256 onerror = BLOCK_ERR_STOP_ANY;
2257 else if (!strcmp(buf, "report"))
2258 onerror = BLOCK_ERR_REPORT;
2259 else {
2260 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2261 return -1;
2265 devaddr = NULL;
2266 if (get_param_value(buf, sizeof(buf), "addr", str)) {
2267 if (type != IF_VIRTIO) {
2268 fprintf(stderr, "addr is not supported by in '%s'\n", str);
2269 return -1;
2271 devaddr = strdup(buf);
2274 /* compute bus and unit according index */
2276 if (index != -1) {
2277 if (bus_id != 0 || unit_id != -1) {
2278 fprintf(stderr,
2279 "qemu: '%s' index cannot be used with bus and unit\n", str);
2280 return -1;
2282 if (max_devs == 0)
2284 unit_id = index;
2285 bus_id = 0;
2286 } else {
2287 unit_id = index % max_devs;
2288 bus_id = index / max_devs;
2292 /* if user doesn't specify a unit_id,
2293 * try to find the first free
2296 if (unit_id == -1) {
2297 unit_id = 0;
2298 while (drive_get_index(type, bus_id, unit_id) != -1) {
2299 unit_id++;
2300 if (max_devs && unit_id >= max_devs) {
2301 unit_id -= max_devs;
2302 bus_id++;
2307 /* check unit id */
2309 if (max_devs && unit_id >= max_devs) {
2310 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2311 str, unit_id, max_devs - 1);
2312 return -1;
2316 * ignore multiple definitions
2319 if (drive_get_index(type, bus_id, unit_id) != -1)
2320 return -2;
2322 /* init */
2324 if (type == IF_IDE || type == IF_SCSI)
2325 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2326 if (max_devs)
2327 snprintf(buf, sizeof(buf), "%s%i%s%i",
2328 devname, bus_id, mediastr, unit_id);
2329 else
2330 snprintf(buf, sizeof(buf), "%s%s%i",
2331 devname, mediastr, unit_id);
2332 bdrv = bdrv_new(buf);
2333 drives_table_idx = drive_get_free_idx();
2334 drives_table[drives_table_idx].bdrv = bdrv;
2335 drives_table[drives_table_idx].devaddr = devaddr;
2336 drives_table[drives_table_idx].type = type;
2337 drives_table[drives_table_idx].bus = bus_id;
2338 drives_table[drives_table_idx].unit = unit_id;
2339 drives_table[drives_table_idx].onerror = onerror;
2340 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2341 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2342 nb_drives++;
2344 switch(type) {
2345 case IF_IDE:
2346 case IF_SCSI:
2347 case IF_XEN:
2348 switch(media) {
2349 case MEDIA_DISK:
2350 if (cyls != 0) {
2351 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2352 bdrv_set_translation_hint(bdrv, translation);
2354 break;
2355 case MEDIA_CDROM:
2356 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2357 break;
2359 break;
2360 case IF_SD:
2361 /* FIXME: This isn't really a floppy, but it's a reasonable
2362 approximation. */
2363 case IF_FLOPPY:
2364 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2365 break;
2366 case IF_PFLASH:
2367 case IF_MTD:
2368 case IF_VIRTIO:
2369 break;
2370 case IF_COUNT:
2371 abort();
2373 if (!file[0])
2374 return -2;
2375 bdrv_flags = 0;
2376 if (snapshot) {
2377 bdrv_flags |= BDRV_O_SNAPSHOT;
2378 cache = 2; /* always use write-back with snapshot */
2380 if (cache == 0) /* no caching */
2381 bdrv_flags |= BDRV_O_NOCACHE;
2382 else if (cache == 2) /* write-back */
2383 bdrv_flags |= BDRV_O_CACHE_WB;
2384 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2385 fprintf(stderr, "qemu: could not open disk image %s\n",
2386 file);
2387 return -1;
2389 if (bdrv_key_required(bdrv))
2390 autostart = 0;
2391 return drives_table_idx;
2394 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2396 boot_set_handler = func;
2397 boot_set_opaque = opaque;
2400 int qemu_boot_set(const char *boot_devices)
2402 if (!boot_set_handler) {
2403 return -EINVAL;
2405 return boot_set_handler(boot_set_opaque, boot_devices);
2408 static int parse_bootdevices(char *devices)
2410 /* We just do some generic consistency checks */
2411 const char *p;
2412 int bitmap = 0;
2414 for (p = devices; *p != '\0'; p++) {
2415 /* Allowed boot devices are:
2416 * a-b: floppy disk drives
2417 * c-f: IDE disk drives
2418 * g-m: machine implementation dependant drives
2419 * n-p: network devices
2420 * It's up to each machine implementation to check if the given boot
2421 * devices match the actual hardware implementation and firmware
2422 * features.
2424 if (*p < 'a' || *p > 'p') {
2425 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2426 exit(1);
2428 if (bitmap & (1 << (*p - 'a'))) {
2429 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2430 exit(1);
2432 bitmap |= 1 << (*p - 'a');
2434 return bitmap;
2437 static void restore_boot_devices(void *opaque)
2439 char *standard_boot_devices = opaque;
2441 qemu_boot_set(standard_boot_devices);
2443 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2444 qemu_free(standard_boot_devices);
2447 static void numa_add(const char *optarg)
2449 char option[128];
2450 char *endptr;
2451 unsigned long long value, endvalue;
2452 int nodenr;
2454 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2455 if (!strcmp(option, "node")) {
2456 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2457 nodenr = nb_numa_nodes;
2458 } else {
2459 nodenr = strtoull(option, NULL, 10);
2462 if (get_param_value(option, 128, "mem", optarg) == 0) {
2463 node_mem[nodenr] = 0;
2464 } else {
2465 value = strtoull(option, &endptr, 0);
2466 switch (*endptr) {
2467 case 0: case 'M': case 'm':
2468 value <<= 20;
2469 break;
2470 case 'G': case 'g':
2471 value <<= 30;
2472 break;
2474 node_mem[nodenr] = value;
2476 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2477 node_cpumask[nodenr] = 0;
2478 } else {
2479 value = strtoull(option, &endptr, 10);
2480 if (value >= 64) {
2481 value = 63;
2482 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2483 } else {
2484 if (*endptr == '-') {
2485 endvalue = strtoull(endptr+1, &endptr, 10);
2486 if (endvalue >= 63) {
2487 endvalue = 62;
2488 fprintf(stderr,
2489 "only 63 CPUs in NUMA mode supported.\n");
2491 value = (1 << (endvalue + 1)) - (1 << value);
2492 } else {
2493 value = 1 << value;
2496 node_cpumask[nodenr] = value;
2498 nb_numa_nodes++;
2500 return;
2503 /***********************************************************/
2504 /* USB devices */
2506 static USBPort *used_usb_ports;
2507 static USBPort *free_usb_ports;
2509 /* ??? Maybe change this to register a hub to keep track of the topology. */
2510 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2511 usb_attachfn attach)
2513 port->opaque = opaque;
2514 port->index = index;
2515 port->attach = attach;
2516 port->next = free_usb_ports;
2517 free_usb_ports = port;
2520 int usb_device_add_dev(USBDevice *dev)
2522 USBPort *port;
2524 /* Find a USB port to add the device to. */
2525 port = free_usb_ports;
2526 if (!port->next) {
2527 USBDevice *hub;
2529 /* Create a new hub and chain it on. */
2530 free_usb_ports = NULL;
2531 port->next = used_usb_ports;
2532 used_usb_ports = port;
2534 hub = usb_hub_init(VM_USB_HUB_SIZE);
2535 usb_attach(port, hub);
2536 port = free_usb_ports;
2539 free_usb_ports = port->next;
2540 port->next = used_usb_ports;
2541 used_usb_ports = port;
2542 usb_attach(port, dev);
2543 return 0;
2546 static void usb_msd_password_cb(void *opaque, int err)
2548 USBDevice *dev = opaque;
2550 if (!err)
2551 usb_device_add_dev(dev);
2552 else
2553 dev->handle_destroy(dev);
2556 static int usb_device_add(const char *devname, int is_hotplug)
2558 const char *p;
2559 USBDevice *dev;
2561 if (!free_usb_ports)
2562 return -1;
2564 if (strstart(devname, "host:", &p)) {
2565 dev = usb_host_device_open(p);
2566 } else if (!strcmp(devname, "mouse")) {
2567 dev = usb_mouse_init();
2568 } else if (!strcmp(devname, "tablet")) {
2569 dev = usb_tablet_init();
2570 } else if (!strcmp(devname, "keyboard")) {
2571 dev = usb_keyboard_init();
2572 } else if (strstart(devname, "disk:", &p)) {
2573 BlockDriverState *bs;
2575 dev = usb_msd_init(p);
2576 if (!dev)
2577 return -1;
2578 bs = usb_msd_get_bdrv(dev);
2579 if (bdrv_key_required(bs)) {
2580 autostart = 0;
2581 if (is_hotplug) {
2582 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2583 dev);
2584 return 0;
2587 } else if (!strcmp(devname, "wacom-tablet")) {
2588 dev = usb_wacom_init();
2589 } else if (strstart(devname, "serial:", &p)) {
2590 dev = usb_serial_init(p);
2591 #ifdef CONFIG_BRLAPI
2592 } else if (!strcmp(devname, "braille")) {
2593 dev = usb_baum_init();
2594 #endif
2595 } else if (strstart(devname, "net:", &p)) {
2596 int nic = nb_nics;
2598 if (net_client_init(NULL, "nic", p) < 0)
2599 return -1;
2600 nd_table[nic].model = "usb";
2601 dev = usb_net_init(&nd_table[nic]);
2602 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2603 dev = usb_bt_init(devname[2] ? hci_init(p) :
2604 bt_new_hci(qemu_find_bt_vlan(0)));
2605 } else {
2606 return -1;
2608 if (!dev)
2609 return -1;
2611 return usb_device_add_dev(dev);
2614 int usb_device_del_addr(int bus_num, int addr)
2616 USBPort *port;
2617 USBPort **lastp;
2618 USBDevice *dev;
2620 if (!used_usb_ports)
2621 return -1;
2623 if (bus_num != 0)
2624 return -1;
2626 lastp = &used_usb_ports;
2627 port = used_usb_ports;
2628 while (port && port->dev->addr != addr) {
2629 lastp = &port->next;
2630 port = port->next;
2633 if (!port)
2634 return -1;
2636 dev = port->dev;
2637 *lastp = port->next;
2638 usb_attach(port, NULL);
2639 dev->handle_destroy(dev);
2640 port->next = free_usb_ports;
2641 free_usb_ports = port;
2642 return 0;
2645 static int usb_device_del(const char *devname)
2647 int bus_num, addr;
2648 const char *p;
2650 if (strstart(devname, "host:", &p))
2651 return usb_host_device_close(p);
2653 if (!used_usb_ports)
2654 return -1;
2656 p = strchr(devname, '.');
2657 if (!p)
2658 return -1;
2659 bus_num = strtoul(devname, NULL, 0);
2660 addr = strtoul(p + 1, NULL, 0);
2662 return usb_device_del_addr(bus_num, addr);
2665 void do_usb_add(Monitor *mon, const char *devname)
2667 usb_device_add(devname, 1);
2670 void do_usb_del(Monitor *mon, const char *devname)
2672 usb_device_del(devname);
2675 void usb_info(Monitor *mon)
2677 USBDevice *dev;
2678 USBPort *port;
2679 const char *speed_str;
2681 if (!usb_enabled) {
2682 monitor_printf(mon, "USB support not enabled\n");
2683 return;
2686 for (port = used_usb_ports; port; port = port->next) {
2687 dev = port->dev;
2688 if (!dev)
2689 continue;
2690 switch(dev->speed) {
2691 case USB_SPEED_LOW:
2692 speed_str = "1.5";
2693 break;
2694 case USB_SPEED_FULL:
2695 speed_str = "12";
2696 break;
2697 case USB_SPEED_HIGH:
2698 speed_str = "480";
2699 break;
2700 default:
2701 speed_str = "?";
2702 break;
2704 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2705 0, dev->addr, speed_str, dev->devname);
2709 /***********************************************************/
2710 /* PCMCIA/Cardbus */
2712 static struct pcmcia_socket_entry_s {
2713 PCMCIASocket *socket;
2714 struct pcmcia_socket_entry_s *next;
2715 } *pcmcia_sockets = 0;
2717 void pcmcia_socket_register(PCMCIASocket *socket)
2719 struct pcmcia_socket_entry_s *entry;
2721 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2722 entry->socket = socket;
2723 entry->next = pcmcia_sockets;
2724 pcmcia_sockets = entry;
2727 void pcmcia_socket_unregister(PCMCIASocket *socket)
2729 struct pcmcia_socket_entry_s *entry, **ptr;
2731 ptr = &pcmcia_sockets;
2732 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2733 if (entry->socket == socket) {
2734 *ptr = entry->next;
2735 qemu_free(entry);
2739 void pcmcia_info(Monitor *mon)
2741 struct pcmcia_socket_entry_s *iter;
2743 if (!pcmcia_sockets)
2744 monitor_printf(mon, "No PCMCIA sockets\n");
2746 for (iter = pcmcia_sockets; iter; iter = iter->next)
2747 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2748 iter->socket->attached ? iter->socket->card_string :
2749 "Empty");
2752 /***********************************************************/
2753 /* register display */
2755 struct DisplayAllocator default_allocator = {
2756 defaultallocator_create_displaysurface,
2757 defaultallocator_resize_displaysurface,
2758 defaultallocator_free_displaysurface
2761 void register_displaystate(DisplayState *ds)
2763 DisplayState **s;
2764 s = &display_state;
2765 while (*s != NULL)
2766 s = &(*s)->next;
2767 ds->next = NULL;
2768 *s = ds;
2771 DisplayState *get_displaystate(void)
2773 return display_state;
2776 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2778 if(ds->allocator == &default_allocator) ds->allocator = da;
2779 return ds->allocator;
2782 /* dumb display */
2784 static void dumb_display_init(void)
2786 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2787 ds->allocator = &default_allocator;
2788 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2789 register_displaystate(ds);
2792 /***********************************************************/
2793 /* I/O handling */
2795 typedef struct IOHandlerRecord {
2796 int fd;
2797 IOCanRWHandler *fd_read_poll;
2798 IOHandler *fd_read;
2799 IOHandler *fd_write;
2800 int deleted;
2801 void *opaque;
2802 /* temporary data */
2803 struct pollfd *ufd;
2804 struct IOHandlerRecord *next;
2805 } IOHandlerRecord;
2807 static IOHandlerRecord *first_io_handler;
2809 /* XXX: fd_read_poll should be suppressed, but an API change is
2810 necessary in the character devices to suppress fd_can_read(). */
2811 int qemu_set_fd_handler2(int fd,
2812 IOCanRWHandler *fd_read_poll,
2813 IOHandler *fd_read,
2814 IOHandler *fd_write,
2815 void *opaque)
2817 IOHandlerRecord **pioh, *ioh;
2819 if (!fd_read && !fd_write) {
2820 pioh = &first_io_handler;
2821 for(;;) {
2822 ioh = *pioh;
2823 if (ioh == NULL)
2824 break;
2825 if (ioh->fd == fd) {
2826 ioh->deleted = 1;
2827 break;
2829 pioh = &ioh->next;
2831 } else {
2832 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2833 if (ioh->fd == fd)
2834 goto found;
2836 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2837 ioh->next = first_io_handler;
2838 first_io_handler = ioh;
2839 found:
2840 ioh->fd = fd;
2841 ioh->fd_read_poll = fd_read_poll;
2842 ioh->fd_read = fd_read;
2843 ioh->fd_write = fd_write;
2844 ioh->opaque = opaque;
2845 ioh->deleted = 0;
2847 qemu_notify_event();
2848 return 0;
2851 int qemu_set_fd_handler(int fd,
2852 IOHandler *fd_read,
2853 IOHandler *fd_write,
2854 void *opaque)
2856 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2859 #ifdef _WIN32
2860 /***********************************************************/
2861 /* Polling handling */
2863 typedef struct PollingEntry {
2864 PollingFunc *func;
2865 void *opaque;
2866 struct PollingEntry *next;
2867 } PollingEntry;
2869 static PollingEntry *first_polling_entry;
2871 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2873 PollingEntry **ppe, *pe;
2874 pe = qemu_mallocz(sizeof(PollingEntry));
2875 pe->func = func;
2876 pe->opaque = opaque;
2877 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2878 *ppe = pe;
2879 return 0;
2882 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2884 PollingEntry **ppe, *pe;
2885 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2886 pe = *ppe;
2887 if (pe->func == func && pe->opaque == opaque) {
2888 *ppe = pe->next;
2889 qemu_free(pe);
2890 break;
2895 /***********************************************************/
2896 /* Wait objects support */
2897 typedef struct WaitObjects {
2898 int num;
2899 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2900 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2901 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2902 } WaitObjects;
2904 static WaitObjects wait_objects = {0};
2906 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2908 WaitObjects *w = &wait_objects;
2910 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2911 return -1;
2912 w->events[w->num] = handle;
2913 w->func[w->num] = func;
2914 w->opaque[w->num] = opaque;
2915 w->num++;
2916 return 0;
2919 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2921 int i, found;
2922 WaitObjects *w = &wait_objects;
2924 found = 0;
2925 for (i = 0; i < w->num; i++) {
2926 if (w->events[i] == handle)
2927 found = 1;
2928 if (found) {
2929 w->events[i] = w->events[i + 1];
2930 w->func[i] = w->func[i + 1];
2931 w->opaque[i] = w->opaque[i + 1];
2934 if (found)
2935 w->num--;
2937 #endif
2939 /***********************************************************/
2940 /* ram save/restore */
2942 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2944 int v;
2946 v = qemu_get_byte(f);
2947 switch(v) {
2948 case 0:
2949 if (qemu_get_buffer(f, buf, len) != len)
2950 return -EIO;
2951 break;
2952 case 1:
2953 v = qemu_get_byte(f);
2954 memset(buf, v, len);
2955 break;
2956 default:
2957 return -EINVAL;
2960 if (qemu_file_has_error(f))
2961 return -EIO;
2963 return 0;
2966 static int ram_load_v1(QEMUFile *f, void *opaque)
2968 int ret;
2969 ram_addr_t i;
2971 if (qemu_get_be32(f) != last_ram_offset)
2972 return -EINVAL;
2973 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2974 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
2975 continue;
2976 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2977 if (ret)
2978 return ret;
2980 return 0;
2983 #define BDRV_HASH_BLOCK_SIZE 1024
2984 #define IOBUF_SIZE 4096
2985 #define RAM_CBLOCK_MAGIC 0xfabe
2987 typedef struct RamDecompressState {
2988 z_stream zstream;
2989 QEMUFile *f;
2990 uint8_t buf[IOBUF_SIZE];
2991 } RamDecompressState;
2993 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2995 int ret;
2996 memset(s, 0, sizeof(*s));
2997 s->f = f;
2998 ret = inflateInit(&s->zstream);
2999 if (ret != Z_OK)
3000 return -1;
3001 return 0;
3004 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3006 int ret, clen;
3008 s->zstream.avail_out = len;
3009 s->zstream.next_out = buf;
3010 while (s->zstream.avail_out > 0) {
3011 if (s->zstream.avail_in == 0) {
3012 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3013 return -1;
3014 clen = qemu_get_be16(s->f);
3015 if (clen > IOBUF_SIZE)
3016 return -1;
3017 qemu_get_buffer(s->f, s->buf, clen);
3018 s->zstream.avail_in = clen;
3019 s->zstream.next_in = s->buf;
3021 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3022 if (ret != Z_OK && ret != Z_STREAM_END) {
3023 return -1;
3026 return 0;
3029 static void ram_decompress_close(RamDecompressState *s)
3031 inflateEnd(&s->zstream);
3034 #define RAM_SAVE_FLAG_FULL 0x01
3035 #define RAM_SAVE_FLAG_COMPRESS 0x02
3036 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3037 #define RAM_SAVE_FLAG_PAGE 0x08
3038 #define RAM_SAVE_FLAG_EOS 0x10
3040 static int is_dup_page(uint8_t *page, uint8_t ch)
3042 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3043 uint32_t *array = (uint32_t *)page;
3044 int i;
3046 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3047 if (array[i] != val)
3048 return 0;
3051 return 1;
3054 static int ram_save_block(QEMUFile *f)
3056 static ram_addr_t current_addr = 0;
3057 ram_addr_t saved_addr = current_addr;
3058 ram_addr_t addr = 0;
3059 int found = 0;
3061 while (addr < last_ram_offset) {
3062 if (kvm_enabled() && current_addr == 0) {
3063 int r;
3064 r = kvm_update_dirty_pages_log();
3065 if (r) {
3066 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3067 qemu_file_set_error(f);
3068 return 0;
3071 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3072 uint8_t *p;
3074 cpu_physical_memory_reset_dirty(current_addr,
3075 current_addr + TARGET_PAGE_SIZE,
3076 MIGRATION_DIRTY_FLAG);
3078 p = qemu_get_ram_ptr(current_addr);
3080 if (is_dup_page(p, *p)) {
3081 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3082 qemu_put_byte(f, *p);
3083 } else {
3084 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3085 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3088 found = 1;
3089 break;
3091 addr += TARGET_PAGE_SIZE;
3092 current_addr = (saved_addr + addr) % last_ram_offset;
3095 return found;
3098 static uint64_t bytes_transferred = 0;
3100 static ram_addr_t ram_save_remaining(void)
3102 ram_addr_t addr;
3103 ram_addr_t count = 0;
3105 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3106 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3107 count++;
3110 return count;
3113 uint64_t ram_bytes_remaining(void)
3115 return ram_save_remaining() * TARGET_PAGE_SIZE;
3118 uint64_t ram_bytes_transferred(void)
3120 return bytes_transferred;
3123 uint64_t ram_bytes_total(void)
3125 return last_ram_offset;
3128 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3130 ram_addr_t addr;
3131 uint64_t bytes_transferred_last;
3132 double bwidth = 0;
3133 uint64_t expected_time = 0;
3135 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3136 qemu_file_set_error(f);
3137 return 0;
3140 if (stage == 1) {
3141 /* Make sure all dirty bits are set */
3142 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3143 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3144 cpu_physical_memory_set_dirty(addr);
3147 /* Enable dirty memory tracking */
3148 cpu_physical_memory_set_dirty_tracking(1);
3150 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3153 bytes_transferred_last = bytes_transferred;
3154 bwidth = get_clock();
3156 while (!qemu_file_rate_limit(f)) {
3157 int ret;
3159 ret = ram_save_block(f);
3160 bytes_transferred += ret * TARGET_PAGE_SIZE;
3161 if (ret == 0) /* no more blocks */
3162 break;
3165 bwidth = get_clock() - bwidth;
3166 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3168 /* if we haven't transferred anything this round, force expected_time to a
3169 * a very high value, but without crashing */
3170 if (bwidth == 0)
3171 bwidth = 0.000001;
3173 /* try transferring iterative blocks of memory */
3175 if (stage == 3) {
3177 /* flush all remaining blocks regardless of rate limiting */
3178 while (ram_save_block(f) != 0) {
3179 bytes_transferred += TARGET_PAGE_SIZE;
3181 cpu_physical_memory_set_dirty_tracking(0);
3184 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3186 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3188 return (stage == 2) && (expected_time <= migrate_max_downtime());
3191 static int ram_load_dead(QEMUFile *f, void *opaque)
3193 RamDecompressState s1, *s = &s1;
3194 uint8_t buf[10];
3195 ram_addr_t i;
3197 if (ram_decompress_open(s, f) < 0)
3198 return -EINVAL;
3199 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3200 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3201 continue;
3202 if (ram_decompress_buf(s, buf, 1) < 0) {
3203 fprintf(stderr, "Error while reading ram block header\n");
3204 goto error;
3206 if (buf[0] == 0) {
3207 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3208 BDRV_HASH_BLOCK_SIZE) < 0) {
3209 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3210 goto error;
3212 } else {
3213 error:
3214 printf("Error block header\n");
3215 return -EINVAL;
3218 ram_decompress_close(s);
3220 return 0;
3223 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3225 ram_addr_t addr;
3226 int flags;
3228 if (version_id == 1)
3229 return ram_load_v1(f, opaque);
3231 if (version_id == 2) {
3232 if (qemu_get_be32(f) != last_ram_offset)
3233 return -EINVAL;
3234 return ram_load_dead(f, opaque);
3237 if (version_id != 3)
3238 return -EINVAL;
3240 do {
3241 addr = qemu_get_be64(f);
3243 flags = addr & ~TARGET_PAGE_MASK;
3244 addr &= TARGET_PAGE_MASK;
3246 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3247 if (addr != last_ram_offset)
3248 return -EINVAL;
3251 if (flags & RAM_SAVE_FLAG_FULL) {
3252 if (ram_load_dead(f, opaque) < 0)
3253 return -EINVAL;
3256 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3257 uint8_t ch = qemu_get_byte(f);
3258 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3259 #ifndef _WIN32
3260 if (ch == 0 &&
3261 (!kvm_enabled() || kvm_has_sync_mmu())) {
3262 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3264 #endif
3265 } else if (flags & RAM_SAVE_FLAG_PAGE)
3266 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3267 } while (!(flags & RAM_SAVE_FLAG_EOS));
3269 return 0;
3272 void qemu_service_io(void)
3274 qemu_notify_event();
3277 /***********************************************************/
3278 /* bottom halves (can be seen as timers which expire ASAP) */
3280 struct QEMUBH {
3281 QEMUBHFunc *cb;
3282 void *opaque;
3283 int scheduled;
3284 int idle;
3285 int deleted;
3286 QEMUBH *next;
3289 static QEMUBH *first_bh = NULL;
3291 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3293 QEMUBH *bh;
3294 bh = qemu_mallocz(sizeof(QEMUBH));
3295 bh->cb = cb;
3296 bh->opaque = opaque;
3297 bh->next = first_bh;
3298 first_bh = bh;
3299 return bh;
3302 int qemu_bh_poll(void)
3304 QEMUBH *bh, **bhp;
3305 int ret;
3307 ret = 0;
3308 for (bh = first_bh; bh; bh = bh->next) {
3309 if (!bh->deleted && bh->scheduled) {
3310 bh->scheduled = 0;
3311 if (!bh->idle)
3312 ret = 1;
3313 bh->idle = 0;
3314 bh->cb(bh->opaque);
3318 /* remove deleted bhs */
3319 bhp = &first_bh;
3320 while (*bhp) {
3321 bh = *bhp;
3322 if (bh->deleted) {
3323 *bhp = bh->next;
3324 qemu_free(bh);
3325 } else
3326 bhp = &bh->next;
3329 return ret;
3332 void qemu_bh_schedule_idle(QEMUBH *bh)
3334 if (bh->scheduled)
3335 return;
3336 bh->scheduled = 1;
3337 bh->idle = 1;
3340 void qemu_bh_schedule(QEMUBH *bh)
3342 if (bh->scheduled)
3343 return;
3344 bh->scheduled = 1;
3345 bh->idle = 0;
3346 /* stop the currently executing CPU to execute the BH ASAP */
3347 qemu_notify_event();
3350 void qemu_bh_cancel(QEMUBH *bh)
3352 bh->scheduled = 0;
3355 void qemu_bh_delete(QEMUBH *bh)
3357 bh->scheduled = 0;
3358 bh->deleted = 1;
3361 static void qemu_bh_update_timeout(int *timeout)
3363 QEMUBH *bh;
3365 for (bh = first_bh; bh; bh = bh->next) {
3366 if (!bh->deleted && bh->scheduled) {
3367 if (bh->idle) {
3368 /* idle bottom halves will be polled at least
3369 * every 10ms */
3370 *timeout = MIN(10, *timeout);
3371 } else {
3372 /* non-idle bottom halves will be executed
3373 * immediately */
3374 *timeout = 0;
3375 break;
3381 /***********************************************************/
3382 /* machine registration */
3384 static QEMUMachine *first_machine = NULL;
3385 QEMUMachine *current_machine = NULL;
3387 int qemu_register_machine(QEMUMachine *m)
3389 QEMUMachine **pm;
3390 pm = &first_machine;
3391 while (*pm != NULL)
3392 pm = &(*pm)->next;
3393 m->next = NULL;
3394 *pm = m;
3395 return 0;
3398 static QEMUMachine *find_machine(const char *name)
3400 QEMUMachine *m;
3402 for(m = first_machine; m != NULL; m = m->next) {
3403 if (!strcmp(m->name, name))
3404 return m;
3405 if (m->alias && !strcmp(m->alias, name))
3406 return m;
3408 return NULL;
3411 static QEMUMachine *find_default_machine(void)
3413 QEMUMachine *m;
3415 for(m = first_machine; m != NULL; m = m->next) {
3416 if (m->is_default) {
3417 return m;
3420 return NULL;
3423 /***********************************************************/
3424 /* main execution loop */
3426 static void gui_update(void *opaque)
3428 uint64_t interval = GUI_REFRESH_INTERVAL;
3429 DisplayState *ds = opaque;
3430 DisplayChangeListener *dcl = ds->listeners;
3432 dpy_refresh(ds);
3434 while (dcl != NULL) {
3435 if (dcl->gui_timer_interval &&
3436 dcl->gui_timer_interval < interval)
3437 interval = dcl->gui_timer_interval;
3438 dcl = dcl->next;
3440 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3443 static void nographic_update(void *opaque)
3445 uint64_t interval = GUI_REFRESH_INTERVAL;
3447 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3450 struct vm_change_state_entry {
3451 VMChangeStateHandler *cb;
3452 void *opaque;
3453 LIST_ENTRY (vm_change_state_entry) entries;
3456 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3458 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3459 void *opaque)
3461 VMChangeStateEntry *e;
3463 e = qemu_mallocz(sizeof (*e));
3465 e->cb = cb;
3466 e->opaque = opaque;
3467 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3468 return e;
3471 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3473 LIST_REMOVE (e, entries);
3474 qemu_free (e);
3477 static void vm_state_notify(int running, int reason)
3479 VMChangeStateEntry *e;
3481 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3482 e->cb(e->opaque, running, reason);
3486 static void resume_all_vcpus(void);
3487 static void pause_all_vcpus(void);
3489 void vm_start(void)
3491 if (!vm_running) {
3492 cpu_enable_ticks();
3493 vm_running = 1;
3494 vm_state_notify(1, 0);
3495 qemu_rearm_alarm_timer(alarm_timer);
3496 resume_all_vcpus();
3500 /* reset/shutdown handler */
3502 typedef struct QEMUResetEntry {
3503 TAILQ_ENTRY(QEMUResetEntry) entry;
3504 QEMUResetHandler *func;
3505 void *opaque;
3506 } QEMUResetEntry;
3508 static TAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3509 TAILQ_HEAD_INITIALIZER(reset_handlers);
3510 static int reset_requested;
3511 static int shutdown_requested;
3512 static int powerdown_requested;
3513 static int debug_requested;
3514 static int vmstop_requested;
3516 int qemu_no_shutdown(void)
3518 int r = no_shutdown;
3519 no_shutdown = 0;
3520 return r;
3523 int qemu_shutdown_requested(void)
3525 int r = shutdown_requested;
3526 shutdown_requested = 0;
3527 return r;
3530 int qemu_reset_requested(void)
3532 int r = reset_requested;
3533 reset_requested = 0;
3534 return r;
3537 int qemu_powerdown_requested(void)
3539 int r = powerdown_requested;
3540 powerdown_requested = 0;
3541 return r;
3544 static int qemu_debug_requested(void)
3546 int r = debug_requested;
3547 debug_requested = 0;
3548 return r;
3551 static int qemu_vmstop_requested(void)
3553 int r = vmstop_requested;
3554 vmstop_requested = 0;
3555 return r;
3558 static void do_vm_stop(int reason)
3560 if (vm_running) {
3561 cpu_disable_ticks();
3562 vm_running = 0;
3563 pause_all_vcpus();
3564 vm_state_notify(0, reason);
3568 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3570 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3572 re->func = func;
3573 re->opaque = opaque;
3574 TAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3577 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3579 QEMUResetEntry *re;
3581 TAILQ_FOREACH(re, &reset_handlers, entry) {
3582 if (re->func == func && re->opaque == opaque) {
3583 TAILQ_REMOVE(&reset_handlers, re, entry);
3584 qemu_free(re);
3585 return;
3590 void qemu_system_reset(void)
3592 QEMUResetEntry *re, *nre;
3594 /* reset all devices */
3595 TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3596 re->func(re->opaque);
3600 void qemu_system_reset_request(void)
3602 if (no_reboot) {
3603 shutdown_requested = 1;
3604 } else {
3605 reset_requested = 1;
3607 if (cpu_single_env) {
3608 cpu_single_env->stopped = 1;
3610 qemu_notify_event();
3613 void qemu_system_shutdown_request(void)
3615 shutdown_requested = 1;
3616 qemu_notify_event();
3619 void qemu_system_powerdown_request(void)
3621 powerdown_requested = 1;
3622 qemu_notify_event();
3625 #ifdef CONFIG_IOTHREAD
3626 static void qemu_system_vmstop_request(int reason)
3628 vmstop_requested = reason;
3629 qemu_notify_event();
3631 #endif
3633 #ifndef _WIN32
3634 static int io_thread_fd = -1;
3636 static void qemu_event_increment(void)
3638 static const char byte = 0;
3640 if (io_thread_fd == -1)
3641 return;
3643 write(io_thread_fd, &byte, sizeof(byte));
3646 static void qemu_event_read(void *opaque)
3648 int fd = (unsigned long)opaque;
3649 ssize_t len;
3651 /* Drain the notify pipe */
3652 do {
3653 char buffer[512];
3654 len = read(fd, buffer, sizeof(buffer));
3655 } while ((len == -1 && errno == EINTR) || len > 0);
3658 static int qemu_event_init(void)
3660 int err;
3661 int fds[2];
3663 err = pipe(fds);
3664 if (err == -1)
3665 return -errno;
3667 err = fcntl_setfl(fds[0], O_NONBLOCK);
3668 if (err < 0)
3669 goto fail;
3671 err = fcntl_setfl(fds[1], O_NONBLOCK);
3672 if (err < 0)
3673 goto fail;
3675 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3676 (void *)(unsigned long)fds[0]);
3678 io_thread_fd = fds[1];
3679 return 0;
3681 fail:
3682 close(fds[0]);
3683 close(fds[1]);
3684 return err;
3686 #else
3687 HANDLE qemu_event_handle;
3689 static void dummy_event_handler(void *opaque)
3693 static int qemu_event_init(void)
3695 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3696 if (!qemu_event_handle) {
3697 perror("Failed CreateEvent");
3698 return -1;
3700 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3701 return 0;
3704 static void qemu_event_increment(void)
3706 SetEvent(qemu_event_handle);
3708 #endif
3710 static int cpu_can_run(CPUState *env)
3712 if (env->stop)
3713 return 0;
3714 if (env->stopped)
3715 return 0;
3716 return 1;
3719 #ifndef CONFIG_IOTHREAD
3720 static int qemu_init_main_loop(void)
3722 return qemu_event_init();
3725 void qemu_init_vcpu(void *_env)
3727 CPUState *env = _env;
3729 if (kvm_enabled())
3730 kvm_init_vcpu(env);
3731 return;
3734 int qemu_cpu_self(void *env)
3736 return 1;
3739 static void resume_all_vcpus(void)
3743 static void pause_all_vcpus(void)
3747 void qemu_cpu_kick(void *env)
3749 return;
3752 void qemu_notify_event(void)
3754 CPUState *env = cpu_single_env;
3756 if (kvm_enabled()) {
3757 qemu_kvm_notify_work();
3758 return;
3760 if (env) {
3761 cpu_exit(env);
3762 #ifdef USE_KQEMU
3763 if (env->kqemu_enabled)
3764 kqemu_cpu_interrupt(env);
3765 #endif
3769 #ifdef KVM_UPSTREAM
3770 #define qemu_mutex_lock_iothread() do { } while (0)
3771 #define qemu_mutex_unlock_iothread() do { } while (0)
3772 #endif
3774 void vm_stop(int reason)
3776 do_vm_stop(reason);
3779 #else /* CONFIG_IOTHREAD */
3781 #include "qemu-thread.h"
3783 QemuMutex qemu_global_mutex;
3784 static QemuMutex qemu_fair_mutex;
3786 static QemuThread io_thread;
3788 static QemuThread *tcg_cpu_thread;
3789 static QemuCond *tcg_halt_cond;
3791 static int qemu_system_ready;
3792 /* cpu creation */
3793 static QemuCond qemu_cpu_cond;
3794 /* system init */
3795 static QemuCond qemu_system_cond;
3796 static QemuCond qemu_pause_cond;
3798 static void block_io_signals(void);
3799 static void unblock_io_signals(void);
3800 static int tcg_has_work(void);
3802 static int qemu_init_main_loop(void)
3804 int ret;
3806 ret = qemu_event_init();
3807 if (ret)
3808 return ret;
3810 qemu_cond_init(&qemu_pause_cond);
3811 qemu_mutex_init(&qemu_fair_mutex);
3812 qemu_mutex_init(&qemu_global_mutex);
3813 qemu_mutex_lock(&qemu_global_mutex);
3815 unblock_io_signals();
3816 qemu_thread_self(&io_thread);
3818 return 0;
3821 static void qemu_wait_io_event(CPUState *env)
3823 while (!tcg_has_work())
3824 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3826 qemu_mutex_unlock(&qemu_global_mutex);
3829 * Users of qemu_global_mutex can be starved, having no chance
3830 * to acquire it since this path will get to it first.
3831 * So use another lock to provide fairness.
3833 qemu_mutex_lock(&qemu_fair_mutex);
3834 qemu_mutex_unlock(&qemu_fair_mutex);
3836 qemu_mutex_lock(&qemu_global_mutex);
3837 if (env->stop) {
3838 env->stop = 0;
3839 env->stopped = 1;
3840 qemu_cond_signal(&qemu_pause_cond);
3844 static int qemu_cpu_exec(CPUState *env);
3846 static void *kvm_cpu_thread_fn(void *arg)
3848 CPUState *env = arg;
3850 block_io_signals();
3851 qemu_thread_self(env->thread);
3853 /* signal CPU creation */
3854 qemu_mutex_lock(&qemu_global_mutex);
3855 env->created = 1;
3856 qemu_cond_signal(&qemu_cpu_cond);
3858 /* and wait for machine initialization */
3859 while (!qemu_system_ready)
3860 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3862 while (1) {
3863 if (cpu_can_run(env))
3864 qemu_cpu_exec(env);
3865 qemu_wait_io_event(env);
3868 return NULL;
3871 static void tcg_cpu_exec(void);
3873 static void *tcg_cpu_thread_fn(void *arg)
3875 CPUState *env = arg;
3877 block_io_signals();
3878 qemu_thread_self(env->thread);
3880 /* signal CPU creation */
3881 qemu_mutex_lock(&qemu_global_mutex);
3882 for (env = first_cpu; env != NULL; env = env->next_cpu)
3883 env->created = 1;
3884 qemu_cond_signal(&qemu_cpu_cond);
3886 /* and wait for machine initialization */
3887 while (!qemu_system_ready)
3888 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3890 while (1) {
3891 tcg_cpu_exec();
3892 qemu_wait_io_event(cur_cpu);
3895 return NULL;
3898 void qemu_cpu_kick(void *_env)
3900 CPUState *env = _env;
3901 qemu_cond_broadcast(env->halt_cond);
3902 if (kvm_enabled())
3903 qemu_thread_signal(env->thread, SIGUSR1);
3906 int qemu_cpu_self(void *env)
3908 return (cpu_single_env != NULL);
3911 static void cpu_signal(int sig)
3913 if (cpu_single_env)
3914 cpu_exit(cpu_single_env);
3917 static void block_io_signals(void)
3919 sigset_t set;
3920 struct sigaction sigact;
3922 sigemptyset(&set);
3923 sigaddset(&set, SIGUSR2);
3924 sigaddset(&set, SIGIO);
3925 sigaddset(&set, SIGALRM);
3926 pthread_sigmask(SIG_BLOCK, &set, NULL);
3928 sigemptyset(&set);
3929 sigaddset(&set, SIGUSR1);
3930 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3932 memset(&sigact, 0, sizeof(sigact));
3933 sigact.sa_handler = cpu_signal;
3934 sigaction(SIGUSR1, &sigact, NULL);
3937 static void unblock_io_signals(void)
3939 sigset_t set;
3941 sigemptyset(&set);
3942 sigaddset(&set, SIGUSR2);
3943 sigaddset(&set, SIGIO);
3944 sigaddset(&set, SIGALRM);
3945 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3947 sigemptyset(&set);
3948 sigaddset(&set, SIGUSR1);
3949 pthread_sigmask(SIG_BLOCK, &set, NULL);
3952 static void qemu_signal_lock(unsigned int msecs)
3954 qemu_mutex_lock(&qemu_fair_mutex);
3956 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3957 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3958 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3959 break;
3961 qemu_mutex_unlock(&qemu_fair_mutex);
3964 static void qemu_mutex_lock_iothread(void)
3966 if (kvm_enabled()) {
3967 qemu_mutex_lock(&qemu_fair_mutex);
3968 qemu_mutex_lock(&qemu_global_mutex);
3969 qemu_mutex_unlock(&qemu_fair_mutex);
3970 } else
3971 qemu_signal_lock(100);
3974 static void qemu_mutex_unlock_iothread(void)
3976 qemu_mutex_unlock(&qemu_global_mutex);
3979 static int all_vcpus_paused(void)
3981 CPUState *penv = first_cpu;
3983 while (penv) {
3984 if (!penv->stopped)
3985 return 0;
3986 penv = (CPUState *)penv->next_cpu;
3989 return 1;
3992 static void pause_all_vcpus(void)
3994 CPUState *penv = first_cpu;
3996 while (penv) {
3997 penv->stop = 1;
3998 qemu_thread_signal(penv->thread, SIGUSR1);
3999 qemu_cpu_kick(penv);
4000 penv = (CPUState *)penv->next_cpu;
4003 while (!all_vcpus_paused()) {
4004 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
4005 penv = first_cpu;
4006 while (penv) {
4007 qemu_thread_signal(penv->thread, SIGUSR1);
4008 penv = (CPUState *)penv->next_cpu;
4013 static void resume_all_vcpus(void)
4015 CPUState *penv = first_cpu;
4017 while (penv) {
4018 penv->stop = 0;
4019 penv->stopped = 0;
4020 qemu_thread_signal(penv->thread, SIGUSR1);
4021 qemu_cpu_kick(penv);
4022 penv = (CPUState *)penv->next_cpu;
4026 static void tcg_init_vcpu(void *_env)
4028 CPUState *env = _env;
4029 /* share a single thread for all cpus with TCG */
4030 if (!tcg_cpu_thread) {
4031 env->thread = qemu_mallocz(sizeof(QemuThread));
4032 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4033 qemu_cond_init(env->halt_cond);
4034 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
4035 while (env->created == 0)
4036 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4037 tcg_cpu_thread = env->thread;
4038 tcg_halt_cond = env->halt_cond;
4039 } else {
4040 env->thread = tcg_cpu_thread;
4041 env->halt_cond = tcg_halt_cond;
4045 static void kvm_start_vcpu(CPUState *env)
4047 kvm_init_vcpu(env);
4048 env->thread = qemu_mallocz(sizeof(QemuThread));
4049 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4050 qemu_cond_init(env->halt_cond);
4051 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
4052 while (env->created == 0)
4053 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4056 void qemu_init_vcpu(void *_env)
4058 CPUState *env = _env;
4060 if (kvm_enabled())
4061 kvm_start_vcpu(env);
4062 else
4063 tcg_init_vcpu(env);
4066 void qemu_notify_event(void)
4068 qemu_event_increment();
4071 void vm_stop(int reason)
4073 QemuThread me;
4074 qemu_thread_self(&me);
4076 if (!qemu_thread_equal(&me, &io_thread)) {
4077 qemu_system_vmstop_request(reason);
4079 * FIXME: should not return to device code in case
4080 * vm_stop() has been requested.
4082 if (cpu_single_env) {
4083 cpu_exit(cpu_single_env);
4084 cpu_single_env->stop = 1;
4086 return;
4088 do_vm_stop(reason);
4091 #endif
4094 #ifdef _WIN32
4095 static void host_main_loop_wait(int *timeout)
4097 int ret, ret2, i;
4098 PollingEntry *pe;
4101 /* XXX: need to suppress polling by better using win32 events */
4102 ret = 0;
4103 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4104 ret |= pe->func(pe->opaque);
4106 if (ret == 0) {
4107 int err;
4108 WaitObjects *w = &wait_objects;
4110 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4111 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4112 if (w->func[ret - WAIT_OBJECT_0])
4113 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4115 /* Check for additional signaled events */
4116 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4118 /* Check if event is signaled */
4119 ret2 = WaitForSingleObject(w->events[i], 0);
4120 if(ret2 == WAIT_OBJECT_0) {
4121 if (w->func[i])
4122 w->func[i](w->opaque[i]);
4123 } else if (ret2 == WAIT_TIMEOUT) {
4124 } else {
4125 err = GetLastError();
4126 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4129 } else if (ret == WAIT_TIMEOUT) {
4130 } else {
4131 err = GetLastError();
4132 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4136 *timeout = 0;
4138 #else
4139 static void host_main_loop_wait(int *timeout)
4142 #endif
4144 void main_loop_wait(int timeout)
4146 IOHandlerRecord *ioh;
4147 fd_set rfds, wfds, xfds;
4148 int ret, nfds;
4149 struct timeval tv;
4151 qemu_bh_update_timeout(&timeout);
4153 host_main_loop_wait(&timeout);
4155 /* poll any events */
4156 /* XXX: separate device handlers from system ones */
4157 nfds = -1;
4158 FD_ZERO(&rfds);
4159 FD_ZERO(&wfds);
4160 FD_ZERO(&xfds);
4161 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4162 if (ioh->deleted)
4163 continue;
4164 if (ioh->fd_read &&
4165 (!ioh->fd_read_poll ||
4166 ioh->fd_read_poll(ioh->opaque) != 0)) {
4167 FD_SET(ioh->fd, &rfds);
4168 if (ioh->fd > nfds)
4169 nfds = ioh->fd;
4171 if (ioh->fd_write) {
4172 FD_SET(ioh->fd, &wfds);
4173 if (ioh->fd > nfds)
4174 nfds = ioh->fd;
4178 tv.tv_sec = timeout / 1000;
4179 tv.tv_usec = (timeout % 1000) * 1000;
4181 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4183 qemu_mutex_unlock_iothread();
4184 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4185 qemu_mutex_lock_iothread();
4186 if (ret > 0) {
4187 IOHandlerRecord **pioh;
4189 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4190 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4191 ioh->fd_read(ioh->opaque);
4192 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
4193 FD_CLR(ioh->fd, &rfds);
4195 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4196 ioh->fd_write(ioh->opaque);
4200 /* remove deleted IO handlers */
4201 pioh = &first_io_handler;
4202 while (*pioh) {
4203 ioh = *pioh;
4204 if (ioh->deleted) {
4205 *pioh = ioh->next;
4206 qemu_free(ioh);
4207 } else
4208 pioh = &ioh->next;
4212 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4214 /* rearm timer, if not periodic */
4215 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4216 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4217 qemu_rearm_alarm_timer(alarm_timer);
4220 /* vm time timers */
4221 if (vm_running) {
4222 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4223 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4224 qemu_get_clock(vm_clock));
4227 /* real time timers */
4228 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4229 qemu_get_clock(rt_clock));
4231 /* Check bottom-halves last in case any of the earlier events triggered
4232 them. */
4233 qemu_bh_poll();
4237 static int qemu_cpu_exec(CPUState *env)
4239 int ret;
4240 #ifdef CONFIG_PROFILER
4241 int64_t ti;
4242 #endif
4244 #ifdef CONFIG_PROFILER
4245 ti = profile_getclock();
4246 #endif
4247 if (use_icount) {
4248 int64_t count;
4249 int decr;
4250 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4251 env->icount_decr.u16.low = 0;
4252 env->icount_extra = 0;
4253 count = qemu_next_deadline();
4254 count = (count + (1 << icount_time_shift) - 1)
4255 >> icount_time_shift;
4256 qemu_icount += count;
4257 decr = (count > 0xffff) ? 0xffff : count;
4258 count -= decr;
4259 env->icount_decr.u16.low = decr;
4260 env->icount_extra = count;
4262 ret = cpu_exec(env);
4263 #ifdef CONFIG_PROFILER
4264 qemu_time += profile_getclock() - ti;
4265 #endif
4266 if (use_icount) {
4267 /* Fold pending instructions back into the
4268 instruction counter, and clear the interrupt flag. */
4269 qemu_icount -= (env->icount_decr.u16.low
4270 + env->icount_extra);
4271 env->icount_decr.u32 = 0;
4272 env->icount_extra = 0;
4274 return ret;
4277 static void tcg_cpu_exec(void)
4279 int ret = 0;
4281 if (next_cpu == NULL)
4282 next_cpu = first_cpu;
4283 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4284 CPUState *env = cur_cpu = next_cpu;
4286 if (!vm_running)
4287 break;
4288 if (timer_alarm_pending) {
4289 timer_alarm_pending = 0;
4290 break;
4292 if (cpu_can_run(env))
4293 ret = qemu_cpu_exec(env);
4294 if (ret == EXCP_DEBUG) {
4295 gdb_set_stop_cpu(env);
4296 debug_requested = 1;
4297 break;
4302 static int cpu_has_work(CPUState *env)
4304 if (env->stop)
4305 return 1;
4306 if (env->stopped)
4307 return 0;
4308 if (!env->halted)
4309 return 1;
4310 if (qemu_cpu_has_work(env))
4311 return 1;
4312 return 0;
4315 static int tcg_has_work(void)
4317 CPUState *env;
4319 for (env = first_cpu; env != NULL; env = env->next_cpu)
4320 if (cpu_has_work(env))
4321 return 1;
4322 return 0;
4325 static int qemu_calculate_timeout(void)
4327 #ifndef CONFIG_IOTHREAD
4328 int timeout;
4330 if (!vm_running)
4331 timeout = 5000;
4332 else if (tcg_has_work())
4333 timeout = 0;
4334 else if (!use_icount)
4335 timeout = 5000;
4336 else {
4337 /* XXX: use timeout computed from timers */
4338 int64_t add;
4339 int64_t delta;
4340 /* Advance virtual time to the next event. */
4341 if (use_icount == 1) {
4342 /* When not using an adaptive execution frequency
4343 we tend to get badly out of sync with real time,
4344 so just delay for a reasonable amount of time. */
4345 delta = 0;
4346 } else {
4347 delta = cpu_get_icount() - cpu_get_clock();
4349 if (delta > 0) {
4350 /* If virtual time is ahead of real time then just
4351 wait for IO. */
4352 timeout = (delta / 1000000) + 1;
4353 } else {
4354 /* Wait for either IO to occur or the next
4355 timer event. */
4356 add = qemu_next_deadline();
4357 /* We advance the timer before checking for IO.
4358 Limit the amount we advance so that early IO
4359 activity won't get the guest too far ahead. */
4360 if (add > 10000000)
4361 add = 10000000;
4362 delta += add;
4363 add = (add + (1 << icount_time_shift) - 1)
4364 >> icount_time_shift;
4365 qemu_icount += add;
4366 timeout = delta / 1000000;
4367 if (timeout < 0)
4368 timeout = 0;
4372 return timeout;
4373 #else /* CONFIG_IOTHREAD */
4374 return 1000;
4375 #endif
4378 static int vm_can_run(void)
4380 if (powerdown_requested)
4381 return 0;
4382 if (reset_requested)
4383 return 0;
4384 if (shutdown_requested)
4385 return 0;
4386 if (debug_requested)
4387 return 0;
4388 return 1;
4391 static void main_loop(void)
4393 int r;
4395 if (kvm_enabled()) {
4396 kvm_main_loop();
4397 cpu_disable_ticks();
4398 return;
4401 #ifdef CONFIG_IOTHREAD
4402 qemu_system_ready = 1;
4403 qemu_cond_broadcast(&qemu_system_cond);
4404 #endif
4406 for (;;) {
4407 do {
4408 #ifdef CONFIG_PROFILER
4409 int64_t ti;
4410 #endif
4411 #ifndef CONFIG_IOTHREAD
4412 tcg_cpu_exec();
4413 #endif
4414 #ifdef CONFIG_PROFILER
4415 ti = profile_getclock();
4416 #endif
4417 main_loop_wait(qemu_calculate_timeout());
4418 #ifdef CONFIG_PROFILER
4419 dev_time += profile_getclock() - ti;
4420 #endif
4421 } while (vm_can_run());
4423 if (qemu_debug_requested())
4424 vm_stop(EXCP_DEBUG);
4425 if (qemu_shutdown_requested()) {
4426 if (no_shutdown) {
4427 vm_stop(0);
4428 no_shutdown = 0;
4429 } else
4430 break;
4432 if (qemu_reset_requested()) {
4433 pause_all_vcpus();
4434 qemu_system_reset();
4435 resume_all_vcpus();
4437 if (qemu_powerdown_requested())
4438 qemu_system_powerdown();
4439 if ((r = qemu_vmstop_requested()))
4440 vm_stop(r);
4442 pause_all_vcpus();
4445 static void version(void)
4447 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4450 static void help(int exitcode)
4452 version();
4453 printf("usage: %s [options] [disk_image]\n"
4454 "\n"
4455 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4456 "\n"
4457 #define DEF(option, opt_arg, opt_enum, opt_help) \
4458 opt_help
4459 #define DEFHEADING(text) stringify(text) "\n"
4460 #include "qemu-options.h"
4461 #undef DEF
4462 #undef DEFHEADING
4463 #undef GEN_DOCS
4464 "\n"
4465 "During emulation, the following keys are useful:\n"
4466 "ctrl-alt-f toggle full screen\n"
4467 "ctrl-alt-n switch to virtual console 'n'\n"
4468 "ctrl-alt toggle mouse and keyboard grab\n"
4469 "\n"
4470 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4472 "qemu",
4473 DEFAULT_RAM_SIZE,
4474 #ifndef _WIN32
4475 DEFAULT_NETWORK_SCRIPT,
4476 DEFAULT_NETWORK_DOWN_SCRIPT,
4477 #endif
4478 DEFAULT_GDBSTUB_PORT,
4479 "/tmp/qemu.log");
4480 exit(exitcode);
4483 #define HAS_ARG 0x0001
4485 enum {
4486 #define DEF(option, opt_arg, opt_enum, opt_help) \
4487 opt_enum,
4488 #define DEFHEADING(text)
4489 #include "qemu-options.h"
4490 #undef DEF
4491 #undef DEFHEADING
4492 #undef GEN_DOCS
4495 typedef struct QEMUOption {
4496 const char *name;
4497 int flags;
4498 int index;
4499 } QEMUOption;
4501 static const QEMUOption qemu_options[] = {
4502 { "h", 0, QEMU_OPTION_h },
4503 #define DEF(option, opt_arg, opt_enum, opt_help) \
4504 { option, opt_arg, opt_enum },
4505 #define DEFHEADING(text)
4506 #include "qemu-options.h"
4507 #undef DEF
4508 #undef DEFHEADING
4509 #undef GEN_DOCS
4510 { NULL },
4513 #ifdef HAS_AUDIO
4514 struct soundhw soundhw[] = {
4515 #ifdef HAS_AUDIO_CHOICE
4516 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4518 "pcspk",
4519 "PC speaker",
4522 { .init_isa = pcspk_audio_init }
4524 #endif
4526 #ifdef CONFIG_SB16
4528 "sb16",
4529 "Creative Sound Blaster 16",
4532 { .init_isa = SB16_init }
4534 #endif
4536 #ifdef CONFIG_CS4231A
4538 "cs4231a",
4539 "CS4231A",
4542 { .init_isa = cs4231a_init }
4544 #endif
4546 #ifdef CONFIG_ADLIB
4548 "adlib",
4549 #ifdef HAS_YMF262
4550 "Yamaha YMF262 (OPL3)",
4551 #else
4552 "Yamaha YM3812 (OPL2)",
4553 #endif
4556 { .init_isa = Adlib_init }
4558 #endif
4560 #ifdef CONFIG_GUS
4562 "gus",
4563 "Gravis Ultrasound GF1",
4566 { .init_isa = GUS_init }
4568 #endif
4570 #ifdef CONFIG_AC97
4572 "ac97",
4573 "Intel 82801AA AC97 Audio",
4576 { .init_pci = ac97_init }
4578 #endif
4580 #ifdef CONFIG_ES1370
4582 "es1370",
4583 "ENSONIQ AudioPCI ES1370",
4586 { .init_pci = es1370_init }
4588 #endif
4590 #endif /* HAS_AUDIO_CHOICE */
4592 { NULL, NULL, 0, 0, { NULL } }
4595 static void select_soundhw (const char *optarg)
4597 struct soundhw *c;
4599 if (*optarg == '?') {
4600 show_valid_cards:
4602 printf ("Valid sound card names (comma separated):\n");
4603 for (c = soundhw; c->name; ++c) {
4604 printf ("%-11s %s\n", c->name, c->descr);
4606 printf ("\n-soundhw all will enable all of the above\n");
4607 exit (*optarg != '?');
4609 else {
4610 size_t l;
4611 const char *p;
4612 char *e;
4613 int bad_card = 0;
4615 if (!strcmp (optarg, "all")) {
4616 for (c = soundhw; c->name; ++c) {
4617 c->enabled = 1;
4619 return;
4622 p = optarg;
4623 while (*p) {
4624 e = strchr (p, ',');
4625 l = !e ? strlen (p) : (size_t) (e - p);
4627 for (c = soundhw; c->name; ++c) {
4628 if (!strncmp (c->name, p, l)) {
4629 c->enabled = 1;
4630 break;
4634 if (!c->name) {
4635 if (l > 80) {
4636 fprintf (stderr,
4637 "Unknown sound card name (too big to show)\n");
4639 else {
4640 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4641 (int) l, p);
4643 bad_card = 1;
4645 p += l + (e != NULL);
4648 if (bad_card)
4649 goto show_valid_cards;
4652 #endif
4654 static void select_vgahw (const char *p)
4656 const char *opts;
4658 cirrus_vga_enabled = 0;
4659 std_vga_enabled = 0;
4660 vmsvga_enabled = 0;
4661 xenfb_enabled = 0;
4662 if (strstart(p, "std", &opts)) {
4663 std_vga_enabled = 1;
4664 } else if (strstart(p, "cirrus", &opts)) {
4665 cirrus_vga_enabled = 1;
4666 } else if (strstart(p, "vmware", &opts)) {
4667 vmsvga_enabled = 1;
4668 } else if (strstart(p, "xenfb", &opts)) {
4669 xenfb_enabled = 1;
4670 } else if (!strstart(p, "none", &opts)) {
4671 invalid_vga:
4672 fprintf(stderr, "Unknown vga type: %s\n", p);
4673 exit(1);
4675 while (*opts) {
4676 const char *nextopt;
4678 if (strstart(opts, ",retrace=", &nextopt)) {
4679 opts = nextopt;
4680 if (strstart(opts, "dumb", &nextopt))
4681 vga_retrace_method = VGA_RETRACE_DUMB;
4682 else if (strstart(opts, "precise", &nextopt))
4683 vga_retrace_method = VGA_RETRACE_PRECISE;
4684 else goto invalid_vga;
4685 } else goto invalid_vga;
4686 opts = nextopt;
4690 #ifdef TARGET_I386
4691 static int balloon_parse(const char *arg)
4693 char buf[128];
4694 const char *p;
4696 if (!strcmp(arg, "none")) {
4697 virtio_balloon = 0;
4698 } else if (!strncmp(arg, "virtio", 6)) {
4699 virtio_balloon = 1;
4700 if (arg[6] == ',') {
4701 p = arg + 7;
4702 if (get_param_value(buf, sizeof(buf), "addr", p)) {
4703 virtio_balloon_devaddr = strdup(buf);
4706 } else {
4707 return -1;
4709 return 0;
4711 #endif
4713 #ifdef _WIN32
4714 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4716 exit(STATUS_CONTROL_C_EXIT);
4717 return TRUE;
4719 #endif
4721 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4723 int ret;
4725 if(strlen(str) != 36)
4726 return -1;
4728 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4729 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4730 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4732 if(ret != 16)
4733 return -1;
4735 #ifdef TARGET_I386
4736 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4737 #endif
4739 return 0;
4742 #define MAX_NET_CLIENTS 32
4744 #ifndef _WIN32
4746 static void termsig_handler(int signal)
4748 qemu_system_shutdown_request();
4751 static void sigchld_handler(int signal)
4753 waitpid(-1, NULL, WNOHANG);
4756 static void sighandler_setup(void)
4758 struct sigaction act;
4760 memset(&act, 0, sizeof(act));
4761 act.sa_handler = termsig_handler;
4762 sigaction(SIGINT, &act, NULL);
4763 sigaction(SIGHUP, &act, NULL);
4764 sigaction(SIGTERM, &act, NULL);
4766 act.sa_handler = sigchld_handler;
4767 act.sa_flags = SA_NOCLDSTOP;
4768 sigaction(SIGCHLD, &act, NULL);
4771 #endif
4773 #ifdef _WIN32
4774 /* Look for support files in the same directory as the executable. */
4775 static char *find_datadir(const char *argv0)
4777 char *p;
4778 char buf[MAX_PATH];
4779 DWORD len;
4781 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4782 if (len == 0) {
4783 return NULL;
4786 buf[len] = 0;
4787 p = buf + len - 1;
4788 while (p != buf && *p != '\\')
4789 p--;
4790 *p = 0;
4791 if (access(buf, R_OK) == 0) {
4792 return qemu_strdup(buf);
4794 return NULL;
4796 #else /* !_WIN32 */
4798 /* Find a likely location for support files using the location of the binary.
4799 For installed binaries this will be "$bindir/../share/qemu". When
4800 running from the build tree this will be "$bindir/../pc-bios". */
4801 #define SHARE_SUFFIX "/share/qemu"
4802 #define BUILD_SUFFIX "/pc-bios"
4803 static char *find_datadir(const char *argv0)
4805 char *dir;
4806 char *p = NULL;
4807 char *res;
4808 #ifdef PATH_MAX
4809 char buf[PATH_MAX];
4810 #endif
4811 size_t max_len;
4813 #if defined(__linux__)
4815 int len;
4816 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4817 if (len > 0) {
4818 buf[len] = 0;
4819 p = buf;
4822 #elif defined(__FreeBSD__)
4824 int len;
4825 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4826 if (len > 0) {
4827 buf[len] = 0;
4828 p = buf;
4831 #endif
4832 /* If we don't have any way of figuring out the actual executable
4833 location then try argv[0]. */
4834 if (!p) {
4835 #ifdef PATH_MAX
4836 p = buf;
4837 #endif
4838 p = realpath(argv0, p);
4839 if (!p) {
4840 return NULL;
4843 dir = dirname(p);
4844 dir = dirname(dir);
4846 max_len = strlen(dir) +
4847 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4848 res = qemu_mallocz(max_len);
4849 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4850 if (access(res, R_OK)) {
4851 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4852 if (access(res, R_OK)) {
4853 qemu_free(res);
4854 res = NULL;
4857 #ifndef PATH_MAX
4858 free(p);
4859 #endif
4860 return res;
4862 #undef SHARE_SUFFIX
4863 #undef BUILD_SUFFIX
4864 #endif
4866 char *qemu_find_file(int type, const char *name)
4868 int len;
4869 const char *subdir;
4870 char *buf;
4872 /* If name contains path separators then try it as a straight path. */
4873 if ((strchr(name, '/') || strchr(name, '\\'))
4874 && access(name, R_OK) == 0) {
4875 return strdup(name);
4877 switch (type) {
4878 case QEMU_FILE_TYPE_BIOS:
4879 subdir = "";
4880 break;
4881 case QEMU_FILE_TYPE_KEYMAP:
4882 subdir = "keymaps/";
4883 break;
4884 default:
4885 abort();
4887 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4888 buf = qemu_mallocz(len);
4889 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4890 if (access(buf, R_OK)) {
4891 qemu_free(buf);
4892 return NULL;
4894 return buf;
4897 int main(int argc, char **argv, char **envp)
4899 const char *gdbstub_dev = NULL;
4900 uint32_t boot_devices_bitmap = 0;
4901 int i;
4902 int snapshot, linux_boot, net_boot;
4903 const char *initrd_filename;
4904 const char *kernel_filename, *kernel_cmdline;
4905 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4906 DisplayState *ds;
4907 DisplayChangeListener *dcl;
4908 int cyls, heads, secs, translation;
4909 const char *net_clients[MAX_NET_CLIENTS];
4910 int nb_net_clients;
4911 const char *bt_opts[MAX_BT_CMDLINE];
4912 int nb_bt_opts;
4913 int hda_index;
4914 int optind;
4915 const char *r, *optarg;
4916 CharDriverState *monitor_hd = NULL;
4917 const char *monitor_device;
4918 const char *serial_devices[MAX_SERIAL_PORTS];
4919 int serial_device_index;
4920 const char *parallel_devices[MAX_PARALLEL_PORTS];
4921 int parallel_device_index;
4922 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4923 int virtio_console_index;
4924 const char *loadvm = NULL;
4925 QEMUMachine *machine;
4926 const char *cpu_model;
4927 const char *usb_devices[MAX_USB_CMDLINE];
4928 int usb_devices_index;
4929 #ifndef _WIN32
4930 int fds[2];
4931 #endif
4932 int tb_size;
4933 const char *pid_file = NULL;
4934 const char *incoming = NULL;
4935 #ifndef _WIN32
4936 int fd = 0;
4937 struct passwd *pwd = NULL;
4938 const char *chroot_dir = NULL;
4939 const char *run_as = NULL;
4940 #endif
4941 CPUState *env;
4942 int show_vnc_port = 0;
4944 qemu_cache_utils_init(envp);
4946 LIST_INIT (&vm_change_state_head);
4947 #ifndef _WIN32
4949 struct sigaction act;
4950 sigfillset(&act.sa_mask);
4951 act.sa_flags = 0;
4952 act.sa_handler = SIG_IGN;
4953 sigaction(SIGPIPE, &act, NULL);
4955 #else
4956 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4957 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4958 QEMU to run on a single CPU */
4960 HANDLE h;
4961 DWORD mask, smask;
4962 int i;
4963 h = GetCurrentProcess();
4964 if (GetProcessAffinityMask(h, &mask, &smask)) {
4965 for(i = 0; i < 32; i++) {
4966 if (mask & (1 << i))
4967 break;
4969 if (i != 32) {
4970 mask = 1 << i;
4971 SetProcessAffinityMask(h, mask);
4975 #endif
4977 module_call_init(MODULE_INIT_MACHINE);
4978 machine = find_default_machine();
4979 cpu_model = NULL;
4980 initrd_filename = NULL;
4981 ram_size = 0;
4982 snapshot = 0;
4983 kernel_filename = NULL;
4984 kernel_cmdline = "";
4985 cyls = heads = secs = 0;
4986 translation = BIOS_ATA_TRANSLATION_AUTO;
4987 monitor_device = "vc:80Cx24C";
4989 serial_devices[0] = "vc:80Cx24C";
4990 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4991 serial_devices[i] = NULL;
4992 serial_device_index = 0;
4994 parallel_devices[0] = "vc:80Cx24C";
4995 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4996 parallel_devices[i] = NULL;
4997 parallel_device_index = 0;
4999 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
5000 virtio_consoles[i] = NULL;
5001 virtio_console_index = 0;
5003 for (i = 0; i < MAX_NODES; i++) {
5004 node_mem[i] = 0;
5005 node_cpumask[i] = 0;
5008 usb_devices_index = 0;
5009 assigned_devices_index = 0;
5011 nb_net_clients = 0;
5012 nb_bt_opts = 0;
5013 nb_drives = 0;
5014 nb_drives_opt = 0;
5015 nb_numa_nodes = 0;
5016 hda_index = -1;
5018 nb_nics = 0;
5020 tb_size = 0;
5021 autostart= 1;
5023 register_watchdogs();
5025 optind = 1;
5026 for(;;) {
5027 if (optind >= argc)
5028 break;
5029 r = argv[optind];
5030 if (r[0] != '-') {
5031 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5032 } else {
5033 const QEMUOption *popt;
5035 optind++;
5036 /* Treat --foo the same as -foo. */
5037 if (r[1] == '-')
5038 r++;
5039 popt = qemu_options;
5040 for(;;) {
5041 if (!popt->name) {
5042 fprintf(stderr, "%s: invalid option -- '%s'\n",
5043 argv[0], r);
5044 exit(1);
5046 if (!strcmp(popt->name, r + 1))
5047 break;
5048 popt++;
5050 if (popt->flags & HAS_ARG) {
5051 if (optind >= argc) {
5052 fprintf(stderr, "%s: option '%s' requires an argument\n",
5053 argv[0], r);
5054 exit(1);
5056 optarg = argv[optind++];
5057 } else {
5058 optarg = NULL;
5061 switch(popt->index) {
5062 case QEMU_OPTION_M:
5063 machine = find_machine(optarg);
5064 if (!machine) {
5065 QEMUMachine *m;
5066 printf("Supported machines are:\n");
5067 for(m = first_machine; m != NULL; m = m->next) {
5068 if (m->alias)
5069 printf("%-10s %s (alias of %s)\n",
5070 m->alias, m->desc, m->name);
5071 printf("%-10s %s%s\n",
5072 m->name, m->desc,
5073 m->is_default ? " (default)" : "");
5075 exit(*optarg != '?');
5077 break;
5078 case QEMU_OPTION_cpu:
5079 /* hw initialization will check this */
5080 if (*optarg == '?') {
5081 /* XXX: implement xxx_cpu_list for targets that still miss it */
5082 #if defined(cpu_list)
5083 cpu_list(stdout, &fprintf);
5084 #endif
5085 exit(0);
5086 } else {
5087 cpu_model = optarg;
5089 break;
5090 case QEMU_OPTION_initrd:
5091 initrd_filename = optarg;
5092 break;
5093 case QEMU_OPTION_hda:
5094 if (cyls == 0)
5095 hda_index = drive_add(optarg, HD_ALIAS, 0);
5096 else
5097 hda_index = drive_add(optarg, HD_ALIAS
5098 ",cyls=%d,heads=%d,secs=%d%s",
5099 0, cyls, heads, secs,
5100 translation == BIOS_ATA_TRANSLATION_LBA ?
5101 ",trans=lba" :
5102 translation == BIOS_ATA_TRANSLATION_NONE ?
5103 ",trans=none" : "");
5104 break;
5105 case QEMU_OPTION_hdb:
5106 case QEMU_OPTION_hdc:
5107 case QEMU_OPTION_hdd:
5108 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5109 break;
5110 case QEMU_OPTION_drive:
5111 drive_add(NULL, "%s", optarg);
5112 break;
5113 case QEMU_OPTION_mtdblock:
5114 drive_add(optarg, MTD_ALIAS);
5115 break;
5116 case QEMU_OPTION_sd:
5117 drive_add(optarg, SD_ALIAS);
5118 break;
5119 case QEMU_OPTION_pflash:
5120 drive_add(optarg, PFLASH_ALIAS);
5121 break;
5122 case QEMU_OPTION_snapshot:
5123 snapshot = 1;
5124 break;
5125 case QEMU_OPTION_hdachs:
5127 const char *p;
5128 p = optarg;
5129 cyls = strtol(p, (char **)&p, 0);
5130 if (cyls < 1 || cyls > 16383)
5131 goto chs_fail;
5132 if (*p != ',')
5133 goto chs_fail;
5134 p++;
5135 heads = strtol(p, (char **)&p, 0);
5136 if (heads < 1 || heads > 16)
5137 goto chs_fail;
5138 if (*p != ',')
5139 goto chs_fail;
5140 p++;
5141 secs = strtol(p, (char **)&p, 0);
5142 if (secs < 1 || secs > 63)
5143 goto chs_fail;
5144 if (*p == ',') {
5145 p++;
5146 if (!strcmp(p, "none"))
5147 translation = BIOS_ATA_TRANSLATION_NONE;
5148 else if (!strcmp(p, "lba"))
5149 translation = BIOS_ATA_TRANSLATION_LBA;
5150 else if (!strcmp(p, "auto"))
5151 translation = BIOS_ATA_TRANSLATION_AUTO;
5152 else
5153 goto chs_fail;
5154 } else if (*p != '\0') {
5155 chs_fail:
5156 fprintf(stderr, "qemu: invalid physical CHS format\n");
5157 exit(1);
5159 if (hda_index != -1)
5160 snprintf(drives_opt[hda_index].opt,
5161 sizeof(drives_opt[hda_index].opt),
5162 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5163 0, cyls, heads, secs,
5164 translation == BIOS_ATA_TRANSLATION_LBA ?
5165 ",trans=lba" :
5166 translation == BIOS_ATA_TRANSLATION_NONE ?
5167 ",trans=none" : "");
5169 break;
5170 case QEMU_OPTION_numa:
5171 if (nb_numa_nodes >= MAX_NODES) {
5172 fprintf(stderr, "qemu: too many NUMA nodes\n");
5173 exit(1);
5175 numa_add(optarg);
5176 break;
5177 case QEMU_OPTION_nographic:
5178 display_type = DT_NOGRAPHIC;
5179 break;
5180 #ifdef CONFIG_CURSES
5181 case QEMU_OPTION_curses:
5182 display_type = DT_CURSES;
5183 break;
5184 #endif
5185 case QEMU_OPTION_portrait:
5186 graphic_rotate = 1;
5187 break;
5188 case QEMU_OPTION_kernel:
5189 kernel_filename = optarg;
5190 break;
5191 case QEMU_OPTION_append:
5192 kernel_cmdline = optarg;
5193 break;
5194 case QEMU_OPTION_cdrom:
5195 drive_add(optarg, CDROM_ALIAS);
5196 break;
5197 case QEMU_OPTION_boot:
5199 static const char * const params[] = {
5200 "order", "once", "menu", NULL
5202 char buf[sizeof(boot_devices)];
5203 char *standard_boot_devices;
5204 int legacy = 0;
5206 if (!strchr(optarg, '=')) {
5207 legacy = 1;
5208 pstrcpy(buf, sizeof(buf), optarg);
5209 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5210 fprintf(stderr,
5211 "qemu: unknown boot parameter '%s' in '%s'\n",
5212 buf, optarg);
5213 exit(1);
5216 if (legacy ||
5217 get_param_value(buf, sizeof(buf), "order", optarg)) {
5218 boot_devices_bitmap = parse_bootdevices(buf);
5219 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5221 if (!legacy) {
5222 if (get_param_value(buf, sizeof(buf),
5223 "once", optarg)) {
5224 boot_devices_bitmap |= parse_bootdevices(buf);
5225 standard_boot_devices = qemu_strdup(boot_devices);
5226 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5227 qemu_register_reset(restore_boot_devices,
5228 standard_boot_devices);
5230 if (get_param_value(buf, sizeof(buf),
5231 "menu", optarg)) {
5232 if (!strcmp(buf, "on")) {
5233 boot_menu = 1;
5234 } else if (!strcmp(buf, "off")) {
5235 boot_menu = 0;
5236 } else {
5237 fprintf(stderr,
5238 "qemu: invalid option value '%s'\n",
5239 buf);
5240 exit(1);
5245 break;
5246 case QEMU_OPTION_fda:
5247 case QEMU_OPTION_fdb:
5248 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5249 break;
5250 #ifdef TARGET_I386
5251 case QEMU_OPTION_no_fd_bootchk:
5252 fd_bootchk = 0;
5253 break;
5254 #endif
5255 case QEMU_OPTION_net:
5256 if (nb_net_clients >= MAX_NET_CLIENTS) {
5257 fprintf(stderr, "qemu: too many network clients\n");
5258 exit(1);
5260 net_clients[nb_net_clients] = optarg;
5261 nb_net_clients++;
5262 break;
5263 #ifdef CONFIG_SLIRP
5264 case QEMU_OPTION_tftp:
5265 legacy_tftp_prefix = optarg;
5266 break;
5267 case QEMU_OPTION_bootp:
5268 legacy_bootp_filename = optarg;
5269 break;
5270 #ifndef _WIN32
5271 case QEMU_OPTION_smb:
5272 net_slirp_smb(optarg);
5273 break;
5274 #endif
5275 case QEMU_OPTION_redir:
5276 net_slirp_redir(optarg);
5277 break;
5278 #endif
5279 case QEMU_OPTION_bt:
5280 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5281 fprintf(stderr, "qemu: too many bluetooth options\n");
5282 exit(1);
5284 bt_opts[nb_bt_opts++] = optarg;
5285 break;
5286 #ifdef HAS_AUDIO
5287 case QEMU_OPTION_audio_help:
5288 AUD_help ();
5289 exit (0);
5290 break;
5291 case QEMU_OPTION_soundhw:
5292 select_soundhw (optarg);
5293 break;
5294 #endif
5295 case QEMU_OPTION_h:
5296 help(0);
5297 break;
5298 case QEMU_OPTION_version:
5299 version();
5300 exit(0);
5301 break;
5302 case QEMU_OPTION_m: {
5303 uint64_t value;
5304 char *ptr;
5306 value = strtoul(optarg, &ptr, 10);
5307 switch (*ptr) {
5308 case 0: case 'M': case 'm':
5309 value <<= 20;
5310 break;
5311 case 'G': case 'g':
5312 value <<= 30;
5313 break;
5314 default:
5315 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5316 exit(1);
5319 /* On 32-bit hosts, QEMU is limited by virtual address space */
5320 if (value > (2047 << 20)
5321 #ifndef CONFIG_KQEMU
5322 && HOST_LONG_BITS == 32
5323 #endif
5325 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5326 exit(1);
5328 if (value != (uint64_t)(ram_addr_t)value) {
5329 fprintf(stderr, "qemu: ram size too large\n");
5330 exit(1);
5332 ram_size = value;
5333 break;
5335 case QEMU_OPTION_d:
5337 int mask;
5338 const CPULogItem *item;
5340 mask = cpu_str_to_log_mask(optarg);
5341 if (!mask) {
5342 printf("Log items (comma separated):\n");
5343 for(item = cpu_log_items; item->mask != 0; item++) {
5344 printf("%-10s %s\n", item->name, item->help);
5346 exit(1);
5348 cpu_set_log(mask);
5350 break;
5351 case QEMU_OPTION_s:
5352 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5353 break;
5354 case QEMU_OPTION_gdb:
5355 gdbstub_dev = optarg;
5356 break;
5357 case QEMU_OPTION_L:
5358 data_dir = optarg;
5359 break;
5360 case QEMU_OPTION_bios:
5361 bios_name = optarg;
5362 break;
5363 case QEMU_OPTION_singlestep:
5364 singlestep = 1;
5365 break;
5366 case QEMU_OPTION_S:
5367 autostart = 0;
5368 break;
5369 #ifndef _WIN32
5370 case QEMU_OPTION_k:
5371 keyboard_layout = optarg;
5372 break;
5373 #endif
5374 case QEMU_OPTION_localtime:
5375 rtc_utc = 0;
5376 break;
5377 case QEMU_OPTION_vga:
5378 select_vgahw (optarg);
5379 break;
5380 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5381 case QEMU_OPTION_g:
5383 const char *p;
5384 int w, h, depth;
5385 p = optarg;
5386 w = strtol(p, (char **)&p, 10);
5387 if (w <= 0) {
5388 graphic_error:
5389 fprintf(stderr, "qemu: invalid resolution or depth\n");
5390 exit(1);
5392 if (*p != 'x')
5393 goto graphic_error;
5394 p++;
5395 h = strtol(p, (char **)&p, 10);
5396 if (h <= 0)
5397 goto graphic_error;
5398 if (*p == 'x') {
5399 p++;
5400 depth = strtol(p, (char **)&p, 10);
5401 if (depth != 8 && depth != 15 && depth != 16 &&
5402 depth != 24 && depth != 32)
5403 goto graphic_error;
5404 } else if (*p == '\0') {
5405 depth = graphic_depth;
5406 } else {
5407 goto graphic_error;
5410 graphic_width = w;
5411 graphic_height = h;
5412 graphic_depth = depth;
5414 break;
5415 #endif
5416 case QEMU_OPTION_echr:
5418 char *r;
5419 term_escape_char = strtol(optarg, &r, 0);
5420 if (r == optarg)
5421 printf("Bad argument to echr\n");
5422 break;
5424 case QEMU_OPTION_monitor:
5425 monitor_device = optarg;
5426 break;
5427 case QEMU_OPTION_serial:
5428 if (serial_device_index >= MAX_SERIAL_PORTS) {
5429 fprintf(stderr, "qemu: too many serial ports\n");
5430 exit(1);
5432 serial_devices[serial_device_index] = optarg;
5433 serial_device_index++;
5434 break;
5435 case QEMU_OPTION_watchdog:
5436 i = select_watchdog(optarg);
5437 if (i > 0)
5438 exit (i == 1 ? 1 : 0);
5439 break;
5440 case QEMU_OPTION_watchdog_action:
5441 if (select_watchdog_action(optarg) == -1) {
5442 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5443 exit(1);
5445 break;
5446 case QEMU_OPTION_virtiocon:
5447 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5448 fprintf(stderr, "qemu: too many virtio consoles\n");
5449 exit(1);
5451 virtio_consoles[virtio_console_index] = optarg;
5452 virtio_console_index++;
5453 break;
5454 case QEMU_OPTION_parallel:
5455 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5456 fprintf(stderr, "qemu: too many parallel ports\n");
5457 exit(1);
5459 parallel_devices[parallel_device_index] = optarg;
5460 parallel_device_index++;
5461 break;
5462 case QEMU_OPTION_loadvm:
5463 loadvm = optarg;
5464 break;
5465 case QEMU_OPTION_full_screen:
5466 full_screen = 1;
5467 break;
5468 #ifdef CONFIG_SDL
5469 case QEMU_OPTION_no_frame:
5470 no_frame = 1;
5471 break;
5472 case QEMU_OPTION_alt_grab:
5473 alt_grab = 1;
5474 break;
5475 case QEMU_OPTION_no_quit:
5476 no_quit = 1;
5477 break;
5478 case QEMU_OPTION_sdl:
5479 display_type = DT_SDL;
5480 break;
5481 #endif
5482 case QEMU_OPTION_pidfile:
5483 pid_file = optarg;
5484 break;
5485 #ifdef TARGET_I386
5486 case QEMU_OPTION_win2k_hack:
5487 win2k_install_hack = 1;
5488 break;
5489 case QEMU_OPTION_rtc_td_hack:
5490 rtc_td_hack = 1;
5491 break;
5492 case QEMU_OPTION_acpitable:
5493 if(acpi_table_add(optarg) < 0) {
5494 fprintf(stderr, "Wrong acpi table provided\n");
5495 exit(1);
5497 break;
5498 case QEMU_OPTION_smbios:
5499 if(smbios_entry_add(optarg) < 0) {
5500 fprintf(stderr, "Wrong smbios provided\n");
5501 exit(1);
5503 break;
5504 #endif
5505 #ifdef CONFIG_KQEMU
5506 case QEMU_OPTION_enable_kqemu:
5507 kqemu_allowed = 1;
5508 break;
5509 case QEMU_OPTION_kernel_kqemu:
5510 kqemu_allowed = 2;
5511 break;
5512 #endif
5513 #ifdef CONFIG_KVM
5514 #ifdef KVM_UPSTREAM
5515 case QEMU_OPTION_enable_kvm:
5516 kvm_allowed = 1;
5517 #ifdef CONFIG_KQEMU
5518 kqemu_allowed = 0;
5519 #endif
5520 #endif
5521 break;
5522 case QEMU_OPTION_no_kvm:
5523 kvm_allowed = 0;
5524 break;
5525 case QEMU_OPTION_no_kvm_irqchip: {
5526 kvm_irqchip = 0;
5527 kvm_pit = 0;
5528 break;
5530 case QEMU_OPTION_no_kvm_pit: {
5531 kvm_pit = 0;
5532 break;
5534 case QEMU_OPTION_no_kvm_pit_reinjection: {
5535 kvm_pit_reinject = 0;
5536 break;
5538 case QEMU_OPTION_enable_nesting: {
5539 kvm_nested = 1;
5540 break;
5542 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5543 case QEMU_OPTION_pcidevice:
5544 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5545 fprintf(stderr, "Too many assigned devices\n");
5546 exit(1);
5548 assigned_devices[assigned_devices_index] = optarg;
5549 assigned_devices_index++;
5550 break;
5551 #endif
5552 #endif
5553 case QEMU_OPTION_usb:
5554 usb_enabled = 1;
5555 break;
5556 case QEMU_OPTION_usbdevice:
5557 usb_enabled = 1;
5558 if (usb_devices_index >= MAX_USB_CMDLINE) {
5559 fprintf(stderr, "Too many USB devices\n");
5560 exit(1);
5562 usb_devices[usb_devices_index] = optarg;
5563 usb_devices_index++;
5564 break;
5565 case QEMU_OPTION_smp:
5566 smp_cpus = atoi(optarg);
5567 if (smp_cpus < 1) {
5568 fprintf(stderr, "Invalid number of CPUs\n");
5569 exit(1);
5571 break;
5572 case QEMU_OPTION_vnc:
5573 display_type = DT_VNC;
5574 vnc_display = optarg;
5575 break;
5576 #ifdef TARGET_I386
5577 case QEMU_OPTION_no_acpi:
5578 acpi_enabled = 0;
5579 break;
5580 case QEMU_OPTION_no_hpet:
5581 no_hpet = 1;
5582 break;
5583 case QEMU_OPTION_balloon:
5584 if (balloon_parse(optarg) < 0) {
5585 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5586 exit(1);
5588 break;
5589 #endif
5590 case QEMU_OPTION_no_reboot:
5591 no_reboot = 1;
5592 break;
5593 case QEMU_OPTION_no_shutdown:
5594 no_shutdown = 1;
5595 break;
5596 case QEMU_OPTION_show_cursor:
5597 cursor_hide = 0;
5598 break;
5599 case QEMU_OPTION_uuid:
5600 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5601 fprintf(stderr, "Fail to parse UUID string."
5602 " Wrong format.\n");
5603 exit(1);
5605 break;
5606 #ifndef _WIN32
5607 case QEMU_OPTION_daemonize:
5608 daemonize = 1;
5609 break;
5610 #endif
5611 case QEMU_OPTION_option_rom:
5612 if (nb_option_roms >= MAX_OPTION_ROMS) {
5613 fprintf(stderr, "Too many option ROMs\n");
5614 exit(1);
5616 option_rom[nb_option_roms] = optarg;
5617 nb_option_roms++;
5618 break;
5619 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5620 case QEMU_OPTION_semihosting:
5621 semihosting_enabled = 1;
5622 break;
5623 #endif
5624 case QEMU_OPTION_tdf:
5625 time_drift_fix = 1;
5626 break;
5627 case QEMU_OPTION_kvm_shadow_memory:
5628 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5629 break;
5630 case QEMU_OPTION_mempath:
5631 mem_path = optarg;
5632 break;
5633 #ifdef MAP_POPULATE
5634 case QEMU_OPTION_mem_prealloc:
5635 mem_prealloc = !mem_prealloc;
5636 break;
5637 #endif
5638 case QEMU_OPTION_name:
5639 qemu_name = qemu_strdup(optarg);
5641 char *p = strchr(qemu_name, ',');
5642 if (p != NULL) {
5643 *p++ = 0;
5644 if (strncmp(p, "process=", 8)) {
5645 fprintf(stderr, "Unknown subargument %s to -name", p);
5646 exit(1);
5648 p += 8;
5649 set_proc_name(p);
5652 break;
5653 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5654 case QEMU_OPTION_prom_env:
5655 if (nb_prom_envs >= MAX_PROM_ENVS) {
5656 fprintf(stderr, "Too many prom variables\n");
5657 exit(1);
5659 prom_envs[nb_prom_envs] = optarg;
5660 nb_prom_envs++;
5661 break;
5662 #endif
5663 #ifdef TARGET_ARM
5664 case QEMU_OPTION_old_param:
5665 old_param = 1;
5666 break;
5667 #endif
5668 case QEMU_OPTION_clock:
5669 configure_alarms(optarg);
5670 break;
5671 case QEMU_OPTION_startdate:
5673 struct tm tm;
5674 time_t rtc_start_date;
5675 if (!strcmp(optarg, "now")) {
5676 rtc_date_offset = -1;
5677 } else {
5678 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5679 &tm.tm_year,
5680 &tm.tm_mon,
5681 &tm.tm_mday,
5682 &tm.tm_hour,
5683 &tm.tm_min,
5684 &tm.tm_sec) == 6) {
5685 /* OK */
5686 } else if (sscanf(optarg, "%d-%d-%d",
5687 &tm.tm_year,
5688 &tm.tm_mon,
5689 &tm.tm_mday) == 3) {
5690 tm.tm_hour = 0;
5691 tm.tm_min = 0;
5692 tm.tm_sec = 0;
5693 } else {
5694 goto date_fail;
5696 tm.tm_year -= 1900;
5697 tm.tm_mon--;
5698 rtc_start_date = mktimegm(&tm);
5699 if (rtc_start_date == -1) {
5700 date_fail:
5701 fprintf(stderr, "Invalid date format. Valid format are:\n"
5702 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5703 exit(1);
5705 rtc_date_offset = time(NULL) - rtc_start_date;
5708 break;
5709 case QEMU_OPTION_tb_size:
5710 tb_size = strtol(optarg, NULL, 0);
5711 if (tb_size < 0)
5712 tb_size = 0;
5713 break;
5714 case QEMU_OPTION_icount:
5715 use_icount = 1;
5716 if (strcmp(optarg, "auto") == 0) {
5717 icount_time_shift = -1;
5718 } else {
5719 icount_time_shift = strtol(optarg, NULL, 0);
5721 break;
5722 case QEMU_OPTION_incoming:
5723 incoming = optarg;
5724 break;
5725 #ifndef _WIN32
5726 case QEMU_OPTION_chroot:
5727 chroot_dir = optarg;
5728 break;
5729 case QEMU_OPTION_runas:
5730 run_as = optarg;
5731 break;
5732 case QEMU_OPTION_nvram:
5733 nvram = optarg;
5734 break;
5735 #endif
5736 #ifdef CONFIG_XEN
5737 case QEMU_OPTION_xen_domid:
5738 xen_domid = atoi(optarg);
5739 break;
5740 case QEMU_OPTION_xen_create:
5741 xen_mode = XEN_CREATE;
5742 break;
5743 case QEMU_OPTION_xen_attach:
5744 xen_mode = XEN_ATTACH;
5745 break;
5746 #endif
5751 /* If no data_dir is specified then try to find it relative to the
5752 executable path. */
5753 if (!data_dir) {
5754 data_dir = find_datadir(argv[0]);
5756 /* If all else fails use the install patch specified when building. */
5757 if (!data_dir) {
5758 data_dir = CONFIG_QEMU_SHAREDIR;
5761 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5762 if (kvm_allowed && kqemu_allowed) {
5763 fprintf(stderr,
5764 "You can not enable both KVM and kqemu at the same time\n");
5765 exit(1);
5767 #endif
5769 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5770 if (smp_cpus > machine->max_cpus) {
5771 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5772 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5773 machine->max_cpus);
5774 exit(1);
5777 if (display_type == DT_NOGRAPHIC) {
5778 if (serial_device_index == 0)
5779 serial_devices[0] = "stdio";
5780 if (parallel_device_index == 0)
5781 parallel_devices[0] = "null";
5782 if (strncmp(monitor_device, "vc", 2) == 0)
5783 monitor_device = "stdio";
5786 #ifndef _WIN32
5787 if (daemonize) {
5788 pid_t pid;
5790 if (pipe(fds) == -1)
5791 exit(1);
5793 pid = fork();
5794 if (pid > 0) {
5795 uint8_t status;
5796 ssize_t len;
5798 close(fds[1]);
5800 again:
5801 len = read(fds[0], &status, 1);
5802 if (len == -1 && (errno == EINTR))
5803 goto again;
5805 if (len != 1)
5806 exit(1);
5807 else if (status == 1) {
5808 fprintf(stderr, "Could not acquire pidfile\n");
5809 exit(1);
5810 } else
5811 exit(0);
5812 } else if (pid < 0)
5813 exit(1);
5815 setsid();
5817 pid = fork();
5818 if (pid > 0)
5819 exit(0);
5820 else if (pid < 0)
5821 exit(1);
5823 umask(027);
5825 signal(SIGTSTP, SIG_IGN);
5826 signal(SIGTTOU, SIG_IGN);
5827 signal(SIGTTIN, SIG_IGN);
5830 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5831 if (daemonize) {
5832 uint8_t status = 1;
5833 write(fds[1], &status, 1);
5834 } else
5835 fprintf(stderr, "Could not acquire pid file\n");
5836 exit(1);
5838 #endif
5840 #ifdef CONFIG_KQEMU
5841 if (smp_cpus > 1)
5842 kqemu_allowed = 0;
5843 #endif
5844 if (qemu_init_main_loop()) {
5845 fprintf(stderr, "qemu_init_main_loop failed\n");
5846 exit(1);
5848 linux_boot = (kernel_filename != NULL);
5850 if (!linux_boot && *kernel_cmdline != '\0') {
5851 fprintf(stderr, "-append only allowed with -kernel option\n");
5852 exit(1);
5855 if (!linux_boot && initrd_filename != NULL) {
5856 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5857 exit(1);
5860 setvbuf(stdout, NULL, _IOLBF, 0);
5862 init_timers();
5863 if (init_timer_alarm() < 0) {
5864 fprintf(stderr, "could not initialize alarm timer\n");
5865 exit(1);
5867 if (use_icount && icount_time_shift < 0) {
5868 use_icount = 2;
5869 /* 125MIPS seems a reasonable initial guess at the guest speed.
5870 It will be corrected fairly quickly anyway. */
5871 icount_time_shift = 3;
5872 init_icount_adjust();
5875 #ifdef _WIN32
5876 socket_init();
5877 #endif
5879 /* init network clients */
5880 if (nb_net_clients == 0) {
5881 /* if no clients, we use a default config */
5882 net_clients[nb_net_clients++] = "nic";
5883 #ifdef CONFIG_SLIRP
5884 net_clients[nb_net_clients++] = "user";
5885 #endif
5888 for(i = 0;i < nb_net_clients; i++) {
5889 if (net_client_parse(net_clients[i]) < 0)
5890 exit(1);
5893 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5894 net_set_boot_mask(net_boot);
5896 net_client_check();
5898 /* init the bluetooth world */
5899 for (i = 0; i < nb_bt_opts; i++)
5900 if (bt_parse(bt_opts[i]))
5901 exit(1);
5903 /* init the memory */
5904 if (ram_size == 0)
5905 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5907 #ifdef CONFIG_KQEMU
5908 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5909 guest ram allocation. It needs to go away. */
5910 if (kqemu_allowed) {
5911 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
5912 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5913 if (!kqemu_phys_ram_base) {
5914 fprintf(stderr, "Could not allocate physical memory\n");
5915 exit(1);
5918 #endif
5920 /* init the dynamic translator */
5921 cpu_exec_init_all(tb_size * 1024 * 1024);
5923 bdrv_init();
5925 /* we always create the cdrom drive, even if no disk is there */
5927 if (nb_drives_opt < MAX_DRIVES)
5928 drive_add(NULL, CDROM_ALIAS);
5930 /* we always create at least one floppy */
5932 if (nb_drives_opt < MAX_DRIVES)
5933 drive_add(NULL, FD_ALIAS, 0);
5935 /* we always create one sd slot, even if no card is in it */
5937 if (nb_drives_opt < MAX_DRIVES)
5938 drive_add(NULL, SD_ALIAS);
5940 /* open the virtual block devices */
5942 for(i = 0; i < nb_drives_opt; i++)
5943 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5944 exit(1);
5946 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5947 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5949 #ifndef _WIN32
5950 /* must be after terminal init, SDL library changes signal handlers */
5951 sighandler_setup();
5952 #endif
5954 /* Maintain compatibility with multiple stdio monitors */
5955 if (!strcmp(monitor_device,"stdio")) {
5956 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5957 const char *devname = serial_devices[i];
5958 if (devname && !strcmp(devname,"mon:stdio")) {
5959 monitor_device = NULL;
5960 break;
5961 } else if (devname && !strcmp(devname,"stdio")) {
5962 monitor_device = NULL;
5963 serial_devices[i] = "mon:stdio";
5964 break;
5969 if (nb_numa_nodes > 0) {
5970 int i;
5972 if (nb_numa_nodes > smp_cpus) {
5973 nb_numa_nodes = smp_cpus;
5976 /* If no memory size if given for any node, assume the default case
5977 * and distribute the available memory equally across all nodes
5979 for (i = 0; i < nb_numa_nodes; i++) {
5980 if (node_mem[i] != 0)
5981 break;
5983 if (i == nb_numa_nodes) {
5984 uint64_t usedmem = 0;
5986 /* On Linux, the each node's border has to be 8MB aligned,
5987 * the final node gets the rest.
5989 for (i = 0; i < nb_numa_nodes - 1; i++) {
5990 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5991 usedmem += node_mem[i];
5993 node_mem[i] = ram_size - usedmem;
5996 for (i = 0; i < nb_numa_nodes; i++) {
5997 if (node_cpumask[i] != 0)
5998 break;
6000 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6001 * must cope with this anyway, because there are BIOSes out there in
6002 * real machines which also use this scheme.
6004 if (i == nb_numa_nodes) {
6005 for (i = 0; i < smp_cpus; i++) {
6006 node_cpumask[i % nb_numa_nodes] |= 1 << i;
6011 if (kvm_enabled()) {
6012 int ret;
6014 ret = kvm_init(smp_cpus);
6015 if (ret < 0) {
6016 #if defined(KVM_UPSTREAM) || defined(NO_CPU_EMULATION)
6017 fprintf(stderr, "failed to initialize KVM\n");
6018 exit(1);
6019 #endif
6020 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
6021 kvm_allowed = 0;
6025 if (monitor_device) {
6026 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
6027 if (!monitor_hd) {
6028 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6029 exit(1);
6033 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6034 const char *devname = serial_devices[i];
6035 if (devname && strcmp(devname, "none")) {
6036 char label[32];
6037 snprintf(label, sizeof(label), "serial%d", i);
6038 serial_hds[i] = qemu_chr_open(label, devname, NULL);
6039 if (!serial_hds[i]) {
6040 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6041 devname);
6042 exit(1);
6047 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6048 const char *devname = parallel_devices[i];
6049 if (devname && strcmp(devname, "none")) {
6050 char label[32];
6051 snprintf(label, sizeof(label), "parallel%d", i);
6052 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
6053 if (!parallel_hds[i]) {
6054 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6055 devname);
6056 exit(1);
6061 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6062 const char *devname = virtio_consoles[i];
6063 if (devname && strcmp(devname, "none")) {
6064 char label[32];
6065 snprintf(label, sizeof(label), "virtcon%d", i);
6066 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
6067 if (!virtcon_hds[i]) {
6068 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
6069 devname);
6070 exit(1);
6075 module_call_init(MODULE_INIT_DEVICE);
6077 if (machine->compat_props) {
6078 qdev_prop_register_compat(machine->compat_props);
6080 machine->init(ram_size, boot_devices,
6081 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6084 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6085 for (i = 0; i < nb_numa_nodes; i++) {
6086 if (node_cpumask[i] & (1 << env->cpu_index)) {
6087 env->numa_node = i;
6092 current_machine = machine;
6094 /* init USB devices */
6095 if (usb_enabled) {
6096 for(i = 0; i < usb_devices_index; i++) {
6097 if (usb_device_add(usb_devices[i], 0) < 0) {
6098 fprintf(stderr, "Warning: could not add USB device %s\n",
6099 usb_devices[i]);
6104 if (!display_state)
6105 dumb_display_init();
6106 /* just use the first displaystate for the moment */
6107 ds = display_state;
6109 if (display_type == DT_DEFAULT) {
6110 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6111 display_type = DT_SDL;
6112 #else
6113 display_type = DT_VNC;
6114 vnc_display = "localhost:0,to=99";
6115 show_vnc_port = 1;
6116 #endif
6120 switch (display_type) {
6121 case DT_NOGRAPHIC:
6122 break;
6123 #if defined(CONFIG_CURSES)
6124 case DT_CURSES:
6125 curses_display_init(ds, full_screen);
6126 break;
6127 #endif
6128 #if defined(CONFIG_SDL)
6129 case DT_SDL:
6130 sdl_display_init(ds, full_screen, no_frame);
6131 break;
6132 #elif defined(CONFIG_COCOA)
6133 case DT_SDL:
6134 cocoa_display_init(ds, full_screen);
6135 break;
6136 #endif
6137 case DT_VNC:
6138 vnc_display_init(ds);
6139 if (vnc_display_open(ds, vnc_display) < 0)
6140 exit(1);
6142 if (show_vnc_port) {
6143 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6145 break;
6146 default:
6147 break;
6149 dpy_resize(ds);
6151 dcl = ds->listeners;
6152 while (dcl != NULL) {
6153 if (dcl->dpy_refresh != NULL) {
6154 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6155 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6157 dcl = dcl->next;
6160 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6161 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6162 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6165 text_consoles_set_display(display_state);
6166 qemu_chr_initial_reset();
6168 if (monitor_device && monitor_hd)
6169 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6171 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6172 const char *devname = serial_devices[i];
6173 if (devname && strcmp(devname, "none")) {
6174 if (strstart(devname, "vc", 0))
6175 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6179 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6180 const char *devname = parallel_devices[i];
6181 if (devname && strcmp(devname, "none")) {
6182 if (strstart(devname, "vc", 0))
6183 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6187 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6188 const char *devname = virtio_consoles[i];
6189 if (virtcon_hds[i] && devname) {
6190 if (strstart(devname, "vc", 0))
6191 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6195 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6196 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6197 gdbstub_dev);
6198 exit(1);
6201 if (loadvm)
6202 do_loadvm(cur_mon, loadvm);
6204 if (incoming) {
6205 autostart = 0;
6206 qemu_start_incoming_migration(incoming);
6209 if (autostart)
6210 vm_start();
6212 #ifndef _WIN32
6213 if (daemonize) {
6214 uint8_t status = 0;
6215 ssize_t len;
6217 again1:
6218 len = write(fds[1], &status, 1);
6219 if (len == -1 && (errno == EINTR))
6220 goto again1;
6222 if (len != 1)
6223 exit(1);
6225 chdir("/");
6226 TFR(fd = open("/dev/null", O_RDWR));
6227 if (fd == -1)
6228 exit(1);
6231 if (run_as) {
6232 pwd = getpwnam(run_as);
6233 if (!pwd) {
6234 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6235 exit(1);
6239 if (chroot_dir) {
6240 if (chroot(chroot_dir) < 0) {
6241 fprintf(stderr, "chroot failed\n");
6242 exit(1);
6244 chdir("/");
6247 if (run_as) {
6248 if (setgid(pwd->pw_gid) < 0) {
6249 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6250 exit(1);
6252 if (setuid(pwd->pw_uid) < 0) {
6253 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6254 exit(1);
6256 if (setuid(0) != -1) {
6257 fprintf(stderr, "Dropping privileges failed\n");
6258 exit(1);
6262 if (daemonize) {
6263 dup2(fd, 0);
6264 dup2(fd, 1);
6265 dup2(fd, 2);
6267 close(fd);
6269 #endif
6271 main_loop();
6272 quit_timers();
6273 net_cleanup();
6275 return 0;