net: disable draining tap queue in one go
[qemu-kvm/fedora.git] / vl.c
blob9182d898efcafbd0d75c3005d86204ba2a20bb3b
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 int autostart;
203 static int rtc_utc = 1;
204 static int rtc_date_offset = -1; /* -1 means no change */
205 int vga_interface_type = VGA_CIRRUS;
206 #ifdef TARGET_SPARC
207 int graphic_width = 1024;
208 int graphic_height = 768;
209 int graphic_depth = 8;
210 #else
211 int graphic_width = 800;
212 int graphic_height = 600;
213 int graphic_depth = 15;
214 #endif
215 static int full_screen = 0;
216 #ifdef CONFIG_SDL
217 static int no_frame = 0;
218 #endif
219 int no_quit = 0;
220 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
221 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
222 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
223 #ifdef TARGET_I386
224 int win2k_install_hack = 0;
225 int rtc_td_hack = 0;
226 #endif
227 int usb_enabled = 0;
228 int singlestep = 0;
229 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
230 int assigned_devices_index;
231 int smp_cpus = 1;
232 const char *vnc_display;
233 int acpi_enabled = 1;
234 #ifdef TARGET_I386
235 int no_hpet = 0;
236 #endif
237 int virtio_balloon = 1;
238 const char *virtio_balloon_devaddr;
239 int fd_bootchk = 1;
240 int no_reboot = 0;
241 int no_shutdown = 0;
242 int cursor_hide = 1;
243 int graphic_rotate = 0;
244 uint8_t irq0override = 1;
245 #ifndef _WIN32
246 int daemonize = 0;
247 #endif
248 WatchdogTimerModel *watchdog = NULL;
249 int watchdog_action = WDT_RESET;
250 const char *option_rom[MAX_OPTION_ROMS];
251 int nb_option_roms;
252 int semihosting_enabled = 0;
253 int time_drift_fix = 0;
254 unsigned int kvm_shadow_memory = 0;
255 const char *mem_path = NULL;
256 #ifdef MAP_POPULATE
257 int mem_prealloc = 1; /* force preallocation of physical target memory */
258 #endif
259 #ifdef TARGET_ARM
260 int old_param = 0;
261 #endif
262 const char *qemu_name;
263 int alt_grab = 0;
264 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
265 unsigned int nb_prom_envs = 0;
266 const char *prom_envs[MAX_PROM_ENVS];
267 #endif
268 int nb_drives_opt;
269 const char *nvram = NULL;
270 struct drive_opt drives_opt[MAX_DRIVES];
271 int boot_menu;
273 int nb_numa_nodes;
274 uint64_t node_mem[MAX_NODES];
275 uint64_t node_cpumask[MAX_NODES];
277 static CPUState *cur_cpu;
278 static CPUState *next_cpu;
279 static int timer_alarm_pending = 1;
280 /* Conversion factor from emulated instructions to virtual clock ticks. */
281 static int icount_time_shift;
282 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
283 #define MAX_ICOUNT_SHIFT 10
284 /* Compensate for varying guest execution speed. */
285 static int64_t qemu_icount_bias;
286 static QEMUTimer *icount_rt_timer;
287 static QEMUTimer *icount_vm_timer;
288 static QEMUTimer *nographic_timer;
290 uint8_t qemu_uuid[16];
292 static QEMUBootSetHandler *boot_set_handler;
293 static void *boot_set_opaque;
295 /***********************************************************/
296 /* x86 ISA bus support */
298 target_phys_addr_t isa_mem_base = 0;
299 PicState2 *isa_pic;
301 /***********************************************************/
302 void hw_error(const char *fmt, ...)
304 va_list ap;
305 CPUState *env;
307 va_start(ap, fmt);
308 fprintf(stderr, "qemu: hardware error: ");
309 vfprintf(stderr, fmt, ap);
310 fprintf(stderr, "\n");
311 for(env = first_cpu; env != NULL; env = env->next_cpu) {
312 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
313 #ifdef TARGET_I386
314 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
315 #else
316 cpu_dump_state(env, stderr, fprintf, 0);
317 #endif
319 va_end(ap);
320 abort();
323 static void set_proc_name(const char *s)
325 #if defined(__linux__) && defined(PR_SET_NAME)
326 char name[16];
327 if (!s)
328 return;
329 name[sizeof(name) - 1] = 0;
330 strncpy(name, s, sizeof(name));
331 /* Could rewrite argv[0] too, but that's a bit more complicated.
332 This simple way is enough for `top'. */
333 prctl(PR_SET_NAME, name);
334 #endif
337 /***************/
338 /* ballooning */
340 static QEMUBalloonEvent *qemu_balloon_event;
341 void *qemu_balloon_event_opaque;
343 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
345 qemu_balloon_event = func;
346 qemu_balloon_event_opaque = opaque;
349 void qemu_balloon(ram_addr_t target)
351 if (qemu_balloon_event)
352 qemu_balloon_event(qemu_balloon_event_opaque, target);
355 ram_addr_t qemu_balloon_status(void)
357 if (qemu_balloon_event)
358 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
359 return 0;
362 /***********************************************************/
363 /* keyboard/mouse */
365 static QEMUPutKBDEvent *qemu_put_kbd_event;
366 static void *qemu_put_kbd_event_opaque;
367 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
368 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
370 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
372 qemu_put_kbd_event_opaque = opaque;
373 qemu_put_kbd_event = func;
376 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
377 void *opaque, int absolute,
378 const char *name)
380 QEMUPutMouseEntry *s, *cursor;
382 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
384 s->qemu_put_mouse_event = func;
385 s->qemu_put_mouse_event_opaque = opaque;
386 s->qemu_put_mouse_event_absolute = absolute;
387 s->qemu_put_mouse_event_name = qemu_strdup(name);
388 s->next = NULL;
390 if (!qemu_put_mouse_event_head) {
391 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
392 return s;
395 cursor = qemu_put_mouse_event_head;
396 while (cursor->next != NULL)
397 cursor = cursor->next;
399 cursor->next = s;
400 qemu_put_mouse_event_current = s;
402 return s;
405 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
407 QEMUPutMouseEntry *prev = NULL, *cursor;
409 if (!qemu_put_mouse_event_head || entry == NULL)
410 return;
412 cursor = qemu_put_mouse_event_head;
413 while (cursor != NULL && cursor != entry) {
414 prev = cursor;
415 cursor = cursor->next;
418 if (cursor == NULL) // does not exist or list empty
419 return;
420 else if (prev == NULL) { // entry is head
421 qemu_put_mouse_event_head = cursor->next;
422 if (qemu_put_mouse_event_current == entry)
423 qemu_put_mouse_event_current = cursor->next;
424 qemu_free(entry->qemu_put_mouse_event_name);
425 qemu_free(entry);
426 return;
429 prev->next = entry->next;
431 if (qemu_put_mouse_event_current == entry)
432 qemu_put_mouse_event_current = prev;
434 qemu_free(entry->qemu_put_mouse_event_name);
435 qemu_free(entry);
438 void kbd_put_keycode(int keycode)
440 if (qemu_put_kbd_event) {
441 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
445 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
447 QEMUPutMouseEvent *mouse_event;
448 void *mouse_event_opaque;
449 int width;
451 if (!qemu_put_mouse_event_current) {
452 return;
455 mouse_event =
456 qemu_put_mouse_event_current->qemu_put_mouse_event;
457 mouse_event_opaque =
458 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
460 if (mouse_event) {
461 if (graphic_rotate) {
462 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
463 width = 0x7fff;
464 else
465 width = graphic_width - 1;
466 mouse_event(mouse_event_opaque,
467 width - dy, dx, dz, buttons_state);
468 } else
469 mouse_event(mouse_event_opaque,
470 dx, dy, dz, buttons_state);
474 int kbd_mouse_is_absolute(void)
476 if (!qemu_put_mouse_event_current)
477 return 0;
479 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
482 void do_info_mice(Monitor *mon)
484 QEMUPutMouseEntry *cursor;
485 int index = 0;
487 if (!qemu_put_mouse_event_head) {
488 monitor_printf(mon, "No mouse devices connected\n");
489 return;
492 monitor_printf(mon, "Mouse devices available:\n");
493 cursor = qemu_put_mouse_event_head;
494 while (cursor != NULL) {
495 monitor_printf(mon, "%c Mouse #%d: %s\n",
496 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
497 index, cursor->qemu_put_mouse_event_name);
498 index++;
499 cursor = cursor->next;
503 void do_mouse_set(Monitor *mon, int index)
505 QEMUPutMouseEntry *cursor;
506 int i = 0;
508 if (!qemu_put_mouse_event_head) {
509 monitor_printf(mon, "No mouse devices connected\n");
510 return;
513 cursor = qemu_put_mouse_event_head;
514 while (cursor != NULL && index != i) {
515 i++;
516 cursor = cursor->next;
519 if (cursor != NULL)
520 qemu_put_mouse_event_current = cursor;
521 else
522 monitor_printf(mon, "Mouse at given index not found\n");
525 /* compute with 96 bit intermediate result: (a*b)/c */
526 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
528 union {
529 uint64_t ll;
530 struct {
531 #ifdef WORDS_BIGENDIAN
532 uint32_t high, low;
533 #else
534 uint32_t low, high;
535 #endif
536 } l;
537 } u, res;
538 uint64_t rl, rh;
540 u.ll = a;
541 rl = (uint64_t)u.l.low * (uint64_t)b;
542 rh = (uint64_t)u.l.high * (uint64_t)b;
543 rh += (rl >> 32);
544 res.l.high = rh / c;
545 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
546 return res.ll;
549 /***********************************************************/
550 /* real time host monotonic timer */
552 #define QEMU_TIMER_BASE 1000000000LL
554 #ifdef WIN32
556 static int64_t clock_freq;
558 static void init_get_clock(void)
560 LARGE_INTEGER freq;
561 int ret;
562 ret = QueryPerformanceFrequency(&freq);
563 if (ret == 0) {
564 fprintf(stderr, "Could not calibrate ticks\n");
565 exit(1);
567 clock_freq = freq.QuadPart;
570 static int64_t get_clock(void)
572 LARGE_INTEGER ti;
573 QueryPerformanceCounter(&ti);
574 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
577 #else
579 static int use_rt_clock;
581 static void init_get_clock(void)
583 use_rt_clock = 0;
584 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
585 || defined(__DragonFly__)
587 struct timespec ts;
588 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
589 use_rt_clock = 1;
592 #endif
595 static int64_t get_clock(void)
597 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
598 || defined(__DragonFly__)
599 if (use_rt_clock) {
600 struct timespec ts;
601 clock_gettime(CLOCK_MONOTONIC, &ts);
602 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
603 } else
604 #endif
606 /* XXX: using gettimeofday leads to problems if the date
607 changes, so it should be avoided. */
608 struct timeval tv;
609 gettimeofday(&tv, NULL);
610 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
613 #endif
615 /* Return the virtual CPU time, based on the instruction counter. */
616 static int64_t cpu_get_icount(void)
618 int64_t icount;
619 CPUState *env = cpu_single_env;;
620 icount = qemu_icount;
621 if (env) {
622 if (!can_do_io(env))
623 fprintf(stderr, "Bad clock read\n");
624 icount -= (env->icount_decr.u16.low + env->icount_extra);
626 return qemu_icount_bias + (icount << icount_time_shift);
629 /***********************************************************/
630 /* guest cycle counter */
632 static int64_t cpu_ticks_prev;
633 static int64_t cpu_ticks_offset;
634 static int64_t cpu_clock_offset;
635 static int cpu_ticks_enabled;
637 /* return the host CPU cycle counter and handle stop/restart */
638 int64_t cpu_get_ticks(void)
640 if (use_icount) {
641 return cpu_get_icount();
643 if (!cpu_ticks_enabled) {
644 return cpu_ticks_offset;
645 } else {
646 int64_t ticks;
647 ticks = cpu_get_real_ticks();
648 if (cpu_ticks_prev > ticks) {
649 /* Note: non increasing ticks may happen if the host uses
650 software suspend */
651 cpu_ticks_offset += cpu_ticks_prev - ticks;
653 cpu_ticks_prev = ticks;
654 return ticks + cpu_ticks_offset;
658 /* return the host CPU monotonic timer and handle stop/restart */
659 static int64_t cpu_get_clock(void)
661 int64_t ti;
662 if (!cpu_ticks_enabled) {
663 return cpu_clock_offset;
664 } else {
665 ti = get_clock();
666 return ti + cpu_clock_offset;
670 /* enable cpu_get_ticks() */
671 void cpu_enable_ticks(void)
673 if (!cpu_ticks_enabled) {
674 cpu_ticks_offset -= cpu_get_real_ticks();
675 cpu_clock_offset -= get_clock();
676 cpu_ticks_enabled = 1;
680 /* disable cpu_get_ticks() : the clock is stopped. You must not call
681 cpu_get_ticks() after that. */
682 void cpu_disable_ticks(void)
684 if (cpu_ticks_enabled) {
685 cpu_ticks_offset = cpu_get_ticks();
686 cpu_clock_offset = cpu_get_clock();
687 cpu_ticks_enabled = 0;
691 /***********************************************************/
692 /* timers */
694 #define QEMU_TIMER_REALTIME 0
695 #define QEMU_TIMER_VIRTUAL 1
697 struct QEMUClock {
698 int type;
699 /* XXX: add frequency */
702 struct QEMUTimer {
703 QEMUClock *clock;
704 int64_t expire_time;
705 QEMUTimerCB *cb;
706 void *opaque;
707 struct QEMUTimer *next;
710 struct qemu_alarm_timer {
711 char const *name;
712 unsigned int flags;
714 int (*start)(struct qemu_alarm_timer *t);
715 void (*stop)(struct qemu_alarm_timer *t);
716 void (*rearm)(struct qemu_alarm_timer *t);
717 void *priv;
720 #define ALARM_FLAG_DYNTICKS 0x1
721 #define ALARM_FLAG_EXPIRED 0x2
723 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
725 return t && (t->flags & ALARM_FLAG_DYNTICKS);
728 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
730 if (!alarm_has_dynticks(t))
731 return;
733 t->rearm(t);
736 /* TODO: MIN_TIMER_REARM_US should be optimized */
737 #define MIN_TIMER_REARM_US 250
739 static struct qemu_alarm_timer *alarm_timer;
741 #ifdef _WIN32
743 struct qemu_alarm_win32 {
744 MMRESULT timerId;
745 unsigned int period;
746 } alarm_win32_data = {0, -1};
748 static int win32_start_timer(struct qemu_alarm_timer *t);
749 static void win32_stop_timer(struct qemu_alarm_timer *t);
750 static void win32_rearm_timer(struct qemu_alarm_timer *t);
752 #else
754 static int unix_start_timer(struct qemu_alarm_timer *t);
755 static void unix_stop_timer(struct qemu_alarm_timer *t);
757 #ifdef __linux__
759 static int dynticks_start_timer(struct qemu_alarm_timer *t);
760 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
761 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
763 static int hpet_start_timer(struct qemu_alarm_timer *t);
764 static void hpet_stop_timer(struct qemu_alarm_timer *t);
766 static int rtc_start_timer(struct qemu_alarm_timer *t);
767 static void rtc_stop_timer(struct qemu_alarm_timer *t);
769 #endif /* __linux__ */
771 #endif /* _WIN32 */
773 /* Correlation between real and virtual time is always going to be
774 fairly approximate, so ignore small variation.
775 When the guest is idle real and virtual time will be aligned in
776 the IO wait loop. */
777 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
779 static void icount_adjust(void)
781 int64_t cur_time;
782 int64_t cur_icount;
783 int64_t delta;
784 static int64_t last_delta;
785 /* If the VM is not running, then do nothing. */
786 if (!vm_running)
787 return;
789 cur_time = cpu_get_clock();
790 cur_icount = qemu_get_clock(vm_clock);
791 delta = cur_icount - cur_time;
792 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
793 if (delta > 0
794 && last_delta + ICOUNT_WOBBLE < delta * 2
795 && icount_time_shift > 0) {
796 /* The guest is getting too far ahead. Slow time down. */
797 icount_time_shift--;
799 if (delta < 0
800 && last_delta - ICOUNT_WOBBLE > delta * 2
801 && icount_time_shift < MAX_ICOUNT_SHIFT) {
802 /* The guest is getting too far behind. Speed time up. */
803 icount_time_shift++;
805 last_delta = delta;
806 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
809 static void icount_adjust_rt(void * opaque)
811 qemu_mod_timer(icount_rt_timer,
812 qemu_get_clock(rt_clock) + 1000);
813 icount_adjust();
816 static void icount_adjust_vm(void * opaque)
818 qemu_mod_timer(icount_vm_timer,
819 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
820 icount_adjust();
823 static void init_icount_adjust(void)
825 /* Have both realtime and virtual time triggers for speed adjustment.
826 The realtime trigger catches emulated time passing too slowly,
827 the virtual time trigger catches emulated time passing too fast.
828 Realtime triggers occur even when idle, so use them less frequently
829 than VM triggers. */
830 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
831 qemu_mod_timer(icount_rt_timer,
832 qemu_get_clock(rt_clock) + 1000);
833 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
834 qemu_mod_timer(icount_vm_timer,
835 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
838 static struct qemu_alarm_timer alarm_timers[] = {
839 #ifndef _WIN32
840 #ifdef __linux__
841 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
842 dynticks_stop_timer, dynticks_rearm_timer, NULL},
843 /* HPET - if available - is preferred */
844 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
845 /* ...otherwise try RTC */
846 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
847 #endif
848 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
849 #else
850 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
851 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
852 {"win32", 0, win32_start_timer,
853 win32_stop_timer, NULL, &alarm_win32_data},
854 #endif
855 {NULL, }
858 static void show_available_alarms(void)
860 int i;
862 printf("Available alarm timers, in order of precedence:\n");
863 for (i = 0; alarm_timers[i].name; i++)
864 printf("%s\n", alarm_timers[i].name);
867 static void configure_alarms(char const *opt)
869 int i;
870 int cur = 0;
871 int count = ARRAY_SIZE(alarm_timers) - 1;
872 char *arg;
873 char *name;
874 struct qemu_alarm_timer tmp;
876 if (!strcmp(opt, "?")) {
877 show_available_alarms();
878 exit(0);
881 arg = strdup(opt);
883 /* Reorder the array */
884 name = strtok(arg, ",");
885 while (name) {
886 for (i = 0; i < count && alarm_timers[i].name; i++) {
887 if (!strcmp(alarm_timers[i].name, name))
888 break;
891 if (i == count) {
892 fprintf(stderr, "Unknown clock %s\n", name);
893 goto next;
896 if (i < cur)
897 /* Ignore */
898 goto next;
900 /* Swap */
901 tmp = alarm_timers[i];
902 alarm_timers[i] = alarm_timers[cur];
903 alarm_timers[cur] = tmp;
905 cur++;
906 next:
907 name = strtok(NULL, ",");
910 free(arg);
912 if (cur) {
913 /* Disable remaining timers */
914 for (i = cur; i < count; i++)
915 alarm_timers[i].name = NULL;
916 } else {
917 show_available_alarms();
918 exit(1);
922 QEMUClock *rt_clock;
923 QEMUClock *vm_clock;
925 static QEMUTimer *active_timers[2];
927 static QEMUClock *qemu_new_clock(int type)
929 QEMUClock *clock;
930 clock = qemu_mallocz(sizeof(QEMUClock));
931 clock->type = type;
932 return clock;
935 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
937 QEMUTimer *ts;
939 ts = qemu_mallocz(sizeof(QEMUTimer));
940 ts->clock = clock;
941 ts->cb = cb;
942 ts->opaque = opaque;
943 return ts;
946 void qemu_free_timer(QEMUTimer *ts)
948 qemu_free(ts);
951 /* stop a timer, but do not dealloc it */
952 void qemu_del_timer(QEMUTimer *ts)
954 QEMUTimer **pt, *t;
956 /* NOTE: this code must be signal safe because
957 qemu_timer_expired() can be called from a signal. */
958 pt = &active_timers[ts->clock->type];
959 for(;;) {
960 t = *pt;
961 if (!t)
962 break;
963 if (t == ts) {
964 *pt = t->next;
965 break;
967 pt = &t->next;
971 /* modify the current timer so that it will be fired when current_time
972 >= expire_time. The corresponding callback will be called. */
973 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
975 QEMUTimer **pt, *t;
977 qemu_del_timer(ts);
979 /* add the timer in the sorted list */
980 /* NOTE: this code must be signal safe because
981 qemu_timer_expired() can be called from a signal. */
982 pt = &active_timers[ts->clock->type];
983 for(;;) {
984 t = *pt;
985 if (!t)
986 break;
987 if (t->expire_time > expire_time)
988 break;
989 pt = &t->next;
991 ts->expire_time = expire_time;
992 ts->next = *pt;
993 *pt = ts;
995 /* Rearm if necessary */
996 if (pt == &active_timers[ts->clock->type]) {
997 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
998 qemu_rearm_alarm_timer(alarm_timer);
1000 /* Interrupt execution to force deadline recalculation. */
1001 if (use_icount)
1002 qemu_notify_event();
1006 int qemu_timer_pending(QEMUTimer *ts)
1008 QEMUTimer *t;
1009 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1010 if (t == ts)
1011 return 1;
1013 return 0;
1016 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1018 if (!timer_head)
1019 return 0;
1020 return (timer_head->expire_time <= current_time);
1023 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1025 QEMUTimer *ts;
1027 for(;;) {
1028 ts = *ptimer_head;
1029 if (!ts || ts->expire_time > current_time)
1030 break;
1031 /* remove timer from the list before calling the callback */
1032 *ptimer_head = ts->next;
1033 ts->next = NULL;
1035 /* run the callback (the timer list can be modified) */
1036 ts->cb(ts->opaque);
1040 int64_t qemu_get_clock(QEMUClock *clock)
1042 switch(clock->type) {
1043 case QEMU_TIMER_REALTIME:
1044 return get_clock() / 1000000;
1045 default:
1046 case QEMU_TIMER_VIRTUAL:
1047 if (use_icount) {
1048 return cpu_get_icount();
1049 } else {
1050 return cpu_get_clock();
1055 static void init_timers(void)
1057 init_get_clock();
1058 ticks_per_sec = QEMU_TIMER_BASE;
1059 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1060 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1063 /* save a timer */
1064 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1066 uint64_t expire_time;
1068 if (qemu_timer_pending(ts)) {
1069 expire_time = ts->expire_time;
1070 } else {
1071 expire_time = -1;
1073 qemu_put_be64(f, expire_time);
1076 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1078 uint64_t expire_time;
1080 expire_time = qemu_get_be64(f);
1081 if (expire_time != -1) {
1082 qemu_mod_timer(ts, expire_time);
1083 } else {
1084 qemu_del_timer(ts);
1088 static void timer_save(QEMUFile *f, void *opaque)
1090 if (cpu_ticks_enabled) {
1091 hw_error("cannot save state if virtual timers are running");
1093 qemu_put_be64(f, cpu_ticks_offset);
1094 qemu_put_be64(f, ticks_per_sec);
1095 qemu_put_be64(f, cpu_clock_offset);
1098 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1100 if (version_id != 1 && version_id != 2)
1101 return -EINVAL;
1102 if (cpu_ticks_enabled) {
1103 return -EINVAL;
1105 cpu_ticks_offset=qemu_get_be64(f);
1106 ticks_per_sec=qemu_get_be64(f);
1107 if (version_id == 2) {
1108 cpu_clock_offset=qemu_get_be64(f);
1110 return 0;
1113 static void qemu_event_increment(void);
1115 #ifdef _WIN32
1116 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1117 DWORD_PTR dwUser, DWORD_PTR dw1,
1118 DWORD_PTR dw2)
1119 #else
1120 static void host_alarm_handler(int host_signum)
1121 #endif
1123 #if 0
1124 #define DISP_FREQ 1000
1126 static int64_t delta_min = INT64_MAX;
1127 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1128 static int count;
1129 ti = qemu_get_clock(vm_clock);
1130 if (last_clock != 0) {
1131 delta = ti - last_clock;
1132 if (delta < delta_min)
1133 delta_min = delta;
1134 if (delta > delta_max)
1135 delta_max = delta;
1136 delta_cum += delta;
1137 if (++count == DISP_FREQ) {
1138 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1139 muldiv64(delta_min, 1000000, ticks_per_sec),
1140 muldiv64(delta_max, 1000000, ticks_per_sec),
1141 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1142 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1143 count = 0;
1144 delta_min = INT64_MAX;
1145 delta_max = 0;
1146 delta_cum = 0;
1149 last_clock = ti;
1151 #endif
1152 if (alarm_has_dynticks(alarm_timer) ||
1153 (!use_icount &&
1154 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1155 qemu_get_clock(vm_clock))) ||
1156 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1157 qemu_get_clock(rt_clock))) {
1158 qemu_event_increment();
1159 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1161 #ifndef CONFIG_IOTHREAD
1162 if (next_cpu) {
1163 /* stop the currently executing cpu because a timer occured */
1164 cpu_exit(next_cpu);
1165 #ifdef CONFIG_KQEMU
1166 if (next_cpu->kqemu_enabled) {
1167 kqemu_cpu_interrupt(next_cpu);
1169 #endif
1171 #endif
1172 timer_alarm_pending = 1;
1173 qemu_notify_event();
1177 static int64_t qemu_next_deadline(void)
1179 int64_t delta;
1181 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1182 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1183 qemu_get_clock(vm_clock);
1184 } else {
1185 /* To avoid problems with overflow limit this to 2^32. */
1186 delta = INT32_MAX;
1189 if (delta < 0)
1190 delta = 0;
1192 return delta;
1195 #if defined(__linux__) || defined(_WIN32)
1196 static uint64_t qemu_next_deadline_dyntick(void)
1198 int64_t delta;
1199 int64_t rtdelta;
1201 if (use_icount)
1202 delta = INT32_MAX;
1203 else
1204 delta = (qemu_next_deadline() + 999) / 1000;
1206 if (active_timers[QEMU_TIMER_REALTIME]) {
1207 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1208 qemu_get_clock(rt_clock))*1000;
1209 if (rtdelta < delta)
1210 delta = rtdelta;
1213 if (delta < MIN_TIMER_REARM_US)
1214 delta = MIN_TIMER_REARM_US;
1216 return delta;
1218 #endif
1220 #ifndef _WIN32
1222 /* Sets a specific flag */
1223 static int fcntl_setfl(int fd, int flag)
1225 int flags;
1227 flags = fcntl(fd, F_GETFL);
1228 if (flags == -1)
1229 return -errno;
1231 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1232 return -errno;
1234 return 0;
1237 #if defined(__linux__)
1239 #define RTC_FREQ 1024
1241 static void enable_sigio_timer(int fd)
1243 struct sigaction act;
1245 /* timer signal */
1246 sigfillset(&act.sa_mask);
1247 act.sa_flags = 0;
1248 act.sa_handler = host_alarm_handler;
1250 sigaction(SIGIO, &act, NULL);
1251 fcntl_setfl(fd, O_ASYNC);
1252 fcntl(fd, F_SETOWN, getpid());
1255 static int hpet_start_timer(struct qemu_alarm_timer *t)
1257 struct hpet_info info;
1258 int r, fd;
1260 fd = open("/dev/hpet", O_RDONLY);
1261 if (fd < 0)
1262 return -1;
1264 /* Set frequency */
1265 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1266 if (r < 0) {
1267 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1268 "error, but for better emulation accuracy type:\n"
1269 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1270 goto fail;
1273 /* Check capabilities */
1274 r = ioctl(fd, HPET_INFO, &info);
1275 if (r < 0)
1276 goto fail;
1278 /* Enable periodic mode */
1279 r = ioctl(fd, HPET_EPI, 0);
1280 if (info.hi_flags && (r < 0))
1281 goto fail;
1283 /* Enable interrupt */
1284 r = ioctl(fd, HPET_IE_ON, 0);
1285 if (r < 0)
1286 goto fail;
1288 enable_sigio_timer(fd);
1289 t->priv = (void *)(long)fd;
1291 return 0;
1292 fail:
1293 close(fd);
1294 return -1;
1297 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1299 int fd = (long)t->priv;
1301 close(fd);
1304 static int rtc_start_timer(struct qemu_alarm_timer *t)
1306 int rtc_fd;
1307 unsigned long current_rtc_freq = 0;
1309 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1310 if (rtc_fd < 0)
1311 return -1;
1312 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1313 if (current_rtc_freq != RTC_FREQ &&
1314 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1315 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1316 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1317 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1318 goto fail;
1320 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1321 fail:
1322 close(rtc_fd);
1323 return -1;
1326 enable_sigio_timer(rtc_fd);
1328 t->priv = (void *)(long)rtc_fd;
1330 return 0;
1333 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1335 int rtc_fd = (long)t->priv;
1337 close(rtc_fd);
1340 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1342 struct sigevent ev;
1343 timer_t host_timer;
1344 struct sigaction act;
1346 sigfillset(&act.sa_mask);
1347 act.sa_flags = 0;
1348 act.sa_handler = host_alarm_handler;
1350 sigaction(SIGALRM, &act, NULL);
1353 * Initialize ev struct to 0 to avoid valgrind complaining
1354 * about uninitialized data in timer_create call
1356 memset(&ev, 0, sizeof(ev));
1357 ev.sigev_value.sival_int = 0;
1358 ev.sigev_notify = SIGEV_SIGNAL;
1359 ev.sigev_signo = SIGALRM;
1361 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1362 perror("timer_create");
1364 /* disable dynticks */
1365 fprintf(stderr, "Dynamic Ticks disabled\n");
1367 return -1;
1370 t->priv = (void *)(long)host_timer;
1372 return 0;
1375 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1377 timer_t host_timer = (timer_t)(long)t->priv;
1379 timer_delete(host_timer);
1382 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1384 timer_t host_timer = (timer_t)(long)t->priv;
1385 struct itimerspec timeout;
1386 int64_t nearest_delta_us = INT64_MAX;
1387 int64_t current_us;
1389 if (!active_timers[QEMU_TIMER_REALTIME] &&
1390 !active_timers[QEMU_TIMER_VIRTUAL])
1391 return;
1393 nearest_delta_us = qemu_next_deadline_dyntick();
1395 /* check whether a timer is already running */
1396 if (timer_gettime(host_timer, &timeout)) {
1397 perror("gettime");
1398 fprintf(stderr, "Internal timer error: aborting\n");
1399 exit(1);
1401 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1402 if (current_us && current_us <= nearest_delta_us)
1403 return;
1405 timeout.it_interval.tv_sec = 0;
1406 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1407 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1408 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1409 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1410 perror("settime");
1411 fprintf(stderr, "Internal timer error: aborting\n");
1412 exit(1);
1416 #endif /* defined(__linux__) */
1418 static int unix_start_timer(struct qemu_alarm_timer *t)
1420 struct sigaction act;
1421 struct itimerval itv;
1422 int err;
1424 /* timer signal */
1425 sigfillset(&act.sa_mask);
1426 act.sa_flags = 0;
1427 act.sa_handler = host_alarm_handler;
1429 sigaction(SIGALRM, &act, NULL);
1431 itv.it_interval.tv_sec = 0;
1432 /* for i386 kernel 2.6 to get 1 ms */
1433 itv.it_interval.tv_usec = 999;
1434 itv.it_value.tv_sec = 0;
1435 itv.it_value.tv_usec = 10 * 1000;
1437 err = setitimer(ITIMER_REAL, &itv, NULL);
1438 if (err)
1439 return -1;
1441 return 0;
1444 static void unix_stop_timer(struct qemu_alarm_timer *t)
1446 struct itimerval itv;
1448 memset(&itv, 0, sizeof(itv));
1449 setitimer(ITIMER_REAL, &itv, NULL);
1452 #endif /* !defined(_WIN32) */
1455 #ifdef _WIN32
1457 static int win32_start_timer(struct qemu_alarm_timer *t)
1459 TIMECAPS tc;
1460 struct qemu_alarm_win32 *data = t->priv;
1461 UINT flags;
1463 memset(&tc, 0, sizeof(tc));
1464 timeGetDevCaps(&tc, sizeof(tc));
1466 if (data->period < tc.wPeriodMin)
1467 data->period = tc.wPeriodMin;
1469 timeBeginPeriod(data->period);
1471 flags = TIME_CALLBACK_FUNCTION;
1472 if (alarm_has_dynticks(t))
1473 flags |= TIME_ONESHOT;
1474 else
1475 flags |= TIME_PERIODIC;
1477 data->timerId = timeSetEvent(1, // interval (ms)
1478 data->period, // resolution
1479 host_alarm_handler, // function
1480 (DWORD)t, // parameter
1481 flags);
1483 if (!data->timerId) {
1484 perror("Failed to initialize win32 alarm timer");
1485 timeEndPeriod(data->period);
1486 return -1;
1489 return 0;
1492 static void win32_stop_timer(struct qemu_alarm_timer *t)
1494 struct qemu_alarm_win32 *data = t->priv;
1496 timeKillEvent(data->timerId);
1497 timeEndPeriod(data->period);
1500 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1502 struct qemu_alarm_win32 *data = t->priv;
1503 uint64_t nearest_delta_us;
1505 if (!active_timers[QEMU_TIMER_REALTIME] &&
1506 !active_timers[QEMU_TIMER_VIRTUAL])
1507 return;
1509 nearest_delta_us = qemu_next_deadline_dyntick();
1510 nearest_delta_us /= 1000;
1512 timeKillEvent(data->timerId);
1514 data->timerId = timeSetEvent(1,
1515 data->period,
1516 host_alarm_handler,
1517 (DWORD)t,
1518 TIME_ONESHOT | TIME_PERIODIC);
1520 if (!data->timerId) {
1521 perror("Failed to re-arm win32 alarm timer");
1523 timeEndPeriod(data->period);
1524 exit(1);
1528 #endif /* _WIN32 */
1530 static int init_timer_alarm(void)
1532 struct qemu_alarm_timer *t = NULL;
1533 int i, err = -1;
1535 for (i = 0; alarm_timers[i].name; i++) {
1536 t = &alarm_timers[i];
1538 err = t->start(t);
1539 if (!err)
1540 break;
1543 if (err) {
1544 err = -ENOENT;
1545 goto fail;
1548 alarm_timer = t;
1550 return 0;
1552 fail:
1553 return err;
1556 static void quit_timers(void)
1558 alarm_timer->stop(alarm_timer);
1559 alarm_timer = NULL;
1562 /***********************************************************/
1563 /* host time/date access */
1564 void qemu_get_timedate(struct tm *tm, int offset)
1566 time_t ti;
1567 struct tm *ret;
1569 time(&ti);
1570 ti += offset;
1571 if (rtc_date_offset == -1) {
1572 if (rtc_utc)
1573 ret = gmtime(&ti);
1574 else
1575 ret = localtime(&ti);
1576 } else {
1577 ti -= rtc_date_offset;
1578 ret = gmtime(&ti);
1581 memcpy(tm, ret, sizeof(struct tm));
1584 int qemu_timedate_diff(struct tm *tm)
1586 time_t seconds;
1588 if (rtc_date_offset == -1)
1589 if (rtc_utc)
1590 seconds = mktimegm(tm);
1591 else
1592 seconds = mktime(tm);
1593 else
1594 seconds = mktimegm(tm) + rtc_date_offset;
1596 return seconds - time(NULL);
1599 #ifdef _WIN32
1600 static void socket_cleanup(void)
1602 WSACleanup();
1605 static int socket_init(void)
1607 WSADATA Data;
1608 int ret, err;
1610 ret = WSAStartup(MAKEWORD(2,2), &Data);
1611 if (ret != 0) {
1612 err = WSAGetLastError();
1613 fprintf(stderr, "WSAStartup: %d\n", err);
1614 return -1;
1616 atexit(socket_cleanup);
1617 return 0;
1619 #endif
1621 int get_next_param_value(char *buf, int buf_size,
1622 const char *tag, const char **pstr)
1624 const char *p;
1625 char option[128];
1627 p = *pstr;
1628 for(;;) {
1629 p = get_opt_name(option, sizeof(option), p, '=');
1630 if (*p != '=')
1631 break;
1632 p++;
1633 if (!strcmp(tag, option)) {
1634 *pstr = get_opt_value(buf, buf_size, p);
1635 if (**pstr == ',') {
1636 (*pstr)++;
1638 return strlen(buf);
1639 } else {
1640 p = get_opt_value(NULL, 0, p);
1642 if (*p != ',')
1643 break;
1644 p++;
1646 return 0;
1649 int get_param_value(char *buf, int buf_size,
1650 const char *tag, const char *str)
1652 return get_next_param_value(buf, buf_size, tag, &str);
1655 int check_params(char *buf, int buf_size,
1656 const char * const *params, const char *str)
1658 const char *p;
1659 int i;
1661 p = str;
1662 while (*p != '\0') {
1663 p = get_opt_name(buf, buf_size, p, '=');
1664 if (*p != '=') {
1665 return -1;
1667 p++;
1668 for (i = 0; params[i] != NULL; i++) {
1669 if (!strcmp(params[i], buf)) {
1670 break;
1673 if (params[i] == NULL) {
1674 return -1;
1676 p = get_opt_value(NULL, 0, p);
1677 if (*p != ',') {
1678 break;
1680 p++;
1682 return 0;
1685 /***********************************************************/
1686 /* Bluetooth support */
1687 static int nb_hcis;
1688 static int cur_hci;
1689 static struct HCIInfo *hci_table[MAX_NICS];
1691 static struct bt_vlan_s {
1692 struct bt_scatternet_s net;
1693 int id;
1694 struct bt_vlan_s *next;
1695 } *first_bt_vlan;
1697 /* find or alloc a new bluetooth "VLAN" */
1698 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1700 struct bt_vlan_s **pvlan, *vlan;
1701 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1702 if (vlan->id == id)
1703 return &vlan->net;
1705 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1706 vlan->id = id;
1707 pvlan = &first_bt_vlan;
1708 while (*pvlan != NULL)
1709 pvlan = &(*pvlan)->next;
1710 *pvlan = vlan;
1711 return &vlan->net;
1714 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1718 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1720 return -ENOTSUP;
1723 static struct HCIInfo null_hci = {
1724 .cmd_send = null_hci_send,
1725 .sco_send = null_hci_send,
1726 .acl_send = null_hci_send,
1727 .bdaddr_set = null_hci_addr_set,
1730 struct HCIInfo *qemu_next_hci(void)
1732 if (cur_hci == nb_hcis)
1733 return &null_hci;
1735 return hci_table[cur_hci++];
1738 static struct HCIInfo *hci_init(const char *str)
1740 char *endp;
1741 struct bt_scatternet_s *vlan = 0;
1743 if (!strcmp(str, "null"))
1744 /* null */
1745 return &null_hci;
1746 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1747 /* host[:hciN] */
1748 return bt_host_hci(str[4] ? str + 5 : "hci0");
1749 else if (!strncmp(str, "hci", 3)) {
1750 /* hci[,vlan=n] */
1751 if (str[3]) {
1752 if (!strncmp(str + 3, ",vlan=", 6)) {
1753 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1754 if (*endp)
1755 vlan = 0;
1757 } else
1758 vlan = qemu_find_bt_vlan(0);
1759 if (vlan)
1760 return bt_new_hci(vlan);
1763 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1765 return 0;
1768 static int bt_hci_parse(const char *str)
1770 struct HCIInfo *hci;
1771 bdaddr_t bdaddr;
1773 if (nb_hcis >= MAX_NICS) {
1774 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1775 return -1;
1778 hci = hci_init(str);
1779 if (!hci)
1780 return -1;
1782 bdaddr.b[0] = 0x52;
1783 bdaddr.b[1] = 0x54;
1784 bdaddr.b[2] = 0x00;
1785 bdaddr.b[3] = 0x12;
1786 bdaddr.b[4] = 0x34;
1787 bdaddr.b[5] = 0x56 + nb_hcis;
1788 hci->bdaddr_set(hci, bdaddr.b);
1790 hci_table[nb_hcis++] = hci;
1792 return 0;
1795 static void bt_vhci_add(int vlan_id)
1797 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1799 if (!vlan->slave)
1800 fprintf(stderr, "qemu: warning: adding a VHCI to "
1801 "an empty scatternet %i\n", vlan_id);
1803 bt_vhci_init(bt_new_hci(vlan));
1806 static struct bt_device_s *bt_device_add(const char *opt)
1808 struct bt_scatternet_s *vlan;
1809 int vlan_id = 0;
1810 char *endp = strstr(opt, ",vlan=");
1811 int len = (endp ? endp - opt : strlen(opt)) + 1;
1812 char devname[10];
1814 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1816 if (endp) {
1817 vlan_id = strtol(endp + 6, &endp, 0);
1818 if (*endp) {
1819 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1820 return 0;
1824 vlan = qemu_find_bt_vlan(vlan_id);
1826 if (!vlan->slave)
1827 fprintf(stderr, "qemu: warning: adding a slave device to "
1828 "an empty scatternet %i\n", vlan_id);
1830 if (!strcmp(devname, "keyboard"))
1831 return bt_keyboard_init(vlan);
1833 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1834 return 0;
1837 static int bt_parse(const char *opt)
1839 const char *endp, *p;
1840 int vlan;
1842 if (strstart(opt, "hci", &endp)) {
1843 if (!*endp || *endp == ',') {
1844 if (*endp)
1845 if (!strstart(endp, ",vlan=", 0))
1846 opt = endp + 1;
1848 return bt_hci_parse(opt);
1850 } else if (strstart(opt, "vhci", &endp)) {
1851 if (!*endp || *endp == ',') {
1852 if (*endp) {
1853 if (strstart(endp, ",vlan=", &p)) {
1854 vlan = strtol(p, (char **) &endp, 0);
1855 if (*endp) {
1856 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1857 return 1;
1859 } else {
1860 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1861 return 1;
1863 } else
1864 vlan = 0;
1866 bt_vhci_add(vlan);
1867 return 0;
1869 } else if (strstart(opt, "device:", &endp))
1870 return !bt_device_add(endp);
1872 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1873 return 1;
1876 /***********************************************************/
1877 /* QEMU Block devices */
1879 #define HD_ALIAS "index=%d,media=disk"
1880 #define CDROM_ALIAS "index=2,media=cdrom"
1881 #define FD_ALIAS "index=%d,if=floppy"
1882 #define PFLASH_ALIAS "if=pflash"
1883 #define MTD_ALIAS "if=mtd"
1884 #define SD_ALIAS "index=0,if=sd"
1886 static int drive_opt_get_free_idx(void)
1888 int index;
1890 for (index = 0; index < MAX_DRIVES; index++)
1891 if (!drives_opt[index].used) {
1892 drives_opt[index].used = 1;
1893 return index;
1896 return -1;
1899 static int drive_get_free_idx(void)
1901 int index;
1903 for (index = 0; index < MAX_DRIVES; index++)
1904 if (!drives_table[index].used) {
1905 drives_table[index].used = 1;
1906 return index;
1909 return -1;
1912 int drive_add(const char *file, const char *fmt, ...)
1914 va_list ap;
1915 int index = drive_opt_get_free_idx();
1917 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
1918 fprintf(stderr, "qemu: too many drives\n");
1919 return -1;
1922 drives_opt[index].file = file;
1923 va_start(ap, fmt);
1924 vsnprintf(drives_opt[index].opt,
1925 sizeof(drives_opt[0].opt), fmt, ap);
1926 va_end(ap);
1928 nb_drives_opt++;
1929 return index;
1932 void drive_remove(int index)
1934 drives_opt[index].used = 0;
1935 nb_drives_opt--;
1938 int drive_get_index(BlockInterfaceType type, int bus, int unit)
1940 int index;
1942 /* seek interface, bus and unit */
1944 for (index = 0; index < MAX_DRIVES; index++)
1945 if (drives_table[index].type == type &&
1946 drives_table[index].bus == bus &&
1947 drives_table[index].unit == unit &&
1948 drives_table[index].used)
1949 return index;
1951 return -1;
1954 int drive_get_max_bus(BlockInterfaceType type)
1956 int max_bus;
1957 int index;
1959 max_bus = -1;
1960 for (index = 0; index < nb_drives; index++) {
1961 if(drives_table[index].type == type &&
1962 drives_table[index].bus > max_bus)
1963 max_bus = drives_table[index].bus;
1965 return max_bus;
1968 const char *drive_get_serial(BlockDriverState *bdrv)
1970 int index;
1972 for (index = 0; index < nb_drives; index++)
1973 if (drives_table[index].bdrv == bdrv)
1974 return drives_table[index].serial;
1976 return "\0";
1979 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1981 int index;
1983 for (index = 0; index < nb_drives; index++)
1984 if (drives_table[index].bdrv == bdrv)
1985 return drives_table[index].onerror;
1987 return BLOCK_ERR_STOP_ENOSPC;
1990 static void bdrv_format_print(void *opaque, const char *name)
1992 fprintf(stderr, " %s", name);
1995 void drive_uninit(BlockDriverState *bdrv)
1997 int i;
1999 for (i = 0; i < MAX_DRIVES; i++)
2000 if (drives_table[i].bdrv == bdrv) {
2001 drives_table[i].bdrv = NULL;
2002 drives_table[i].used = 0;
2003 drive_remove(drives_table[i].drive_opt_idx);
2004 nb_drives--;
2005 break;
2009 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2011 char buf[128];
2012 char file[1024];
2013 char devname[128];
2014 char serial[21];
2015 const char *mediastr = "";
2016 BlockInterfaceType type;
2017 enum { MEDIA_DISK, MEDIA_CDROM } media;
2018 int bus_id, unit_id;
2019 int cyls, heads, secs, translation;
2020 BlockDriverState *bdrv;
2021 BlockDriver *drv = NULL;
2022 QEMUMachine *machine = opaque;
2023 int max_devs;
2024 int index;
2025 int cache;
2026 int bdrv_flags, onerror;
2027 const char *devaddr;
2028 int drives_table_idx;
2029 char *str = arg->opt;
2030 static const char * const params[] = { "bus", "unit", "if", "index",
2031 "cyls", "heads", "secs", "trans",
2032 "media", "snapshot", "file",
2033 "cache", "format", "serial",
2034 "werror", "addr",
2035 "boot",
2036 NULL };
2038 if (check_params(buf, sizeof(buf), params, str) < 0) {
2039 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2040 buf, str);
2041 return -1;
2044 file[0] = 0;
2045 cyls = heads = secs = 0;
2046 bus_id = 0;
2047 unit_id = -1;
2048 translation = BIOS_ATA_TRANSLATION_AUTO;
2049 index = -1;
2050 cache = 1;
2052 if (machine->use_scsi) {
2053 type = IF_SCSI;
2054 max_devs = MAX_SCSI_DEVS;
2055 pstrcpy(devname, sizeof(devname), "scsi");
2056 } else {
2057 type = IF_IDE;
2058 max_devs = MAX_IDE_DEVS;
2059 pstrcpy(devname, sizeof(devname), "ide");
2061 media = MEDIA_DISK;
2063 /* extract parameters */
2065 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2066 bus_id = strtol(buf, NULL, 0);
2067 if (bus_id < 0) {
2068 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2069 return -1;
2073 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2074 unit_id = strtol(buf, NULL, 0);
2075 if (unit_id < 0) {
2076 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2077 return -1;
2081 if (get_param_value(buf, sizeof(buf), "if", str)) {
2082 pstrcpy(devname, sizeof(devname), buf);
2083 if (!strcmp(buf, "ide")) {
2084 type = IF_IDE;
2085 max_devs = MAX_IDE_DEVS;
2086 } else if (!strcmp(buf, "scsi")) {
2087 type = IF_SCSI;
2088 max_devs = MAX_SCSI_DEVS;
2089 } else if (!strcmp(buf, "floppy")) {
2090 type = IF_FLOPPY;
2091 max_devs = 0;
2092 } else if (!strcmp(buf, "pflash")) {
2093 type = IF_PFLASH;
2094 max_devs = 0;
2095 } else if (!strcmp(buf, "mtd")) {
2096 type = IF_MTD;
2097 max_devs = 0;
2098 } else if (!strcmp(buf, "sd")) {
2099 type = IF_SD;
2100 max_devs = 0;
2101 } else if (!strcmp(buf, "virtio")) {
2102 type = IF_VIRTIO;
2103 max_devs = 0;
2104 } else if (!strcmp(buf, "xen")) {
2105 type = IF_XEN;
2106 max_devs = 0;
2107 } else {
2108 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2109 return -1;
2113 if (get_param_value(buf, sizeof(buf), "index", str)) {
2114 index = strtol(buf, NULL, 0);
2115 if (index < 0) {
2116 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2117 return -1;
2121 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2122 cyls = strtol(buf, NULL, 0);
2125 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2126 heads = strtol(buf, NULL, 0);
2129 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2130 secs = strtol(buf, NULL, 0);
2133 if (cyls || heads || secs) {
2134 if (cyls < 1 || cyls > 16383) {
2135 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2136 return -1;
2138 if (heads < 1 || heads > 16) {
2139 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2140 return -1;
2142 if (secs < 1 || secs > 63) {
2143 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2144 return -1;
2148 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2149 if (!cyls) {
2150 fprintf(stderr,
2151 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2152 str);
2153 return -1;
2155 if (!strcmp(buf, "none"))
2156 translation = BIOS_ATA_TRANSLATION_NONE;
2157 else if (!strcmp(buf, "lba"))
2158 translation = BIOS_ATA_TRANSLATION_LBA;
2159 else if (!strcmp(buf, "auto"))
2160 translation = BIOS_ATA_TRANSLATION_AUTO;
2161 else {
2162 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2163 return -1;
2167 if (get_param_value(buf, sizeof(buf), "media", str)) {
2168 if (!strcmp(buf, "disk")) {
2169 media = MEDIA_DISK;
2170 } else if (!strcmp(buf, "cdrom")) {
2171 if (cyls || secs || heads) {
2172 fprintf(stderr,
2173 "qemu: '%s' invalid physical CHS format\n", str);
2174 return -1;
2176 media = MEDIA_CDROM;
2177 } else {
2178 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2179 return -1;
2183 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2184 if (!strcmp(buf, "on"))
2185 snapshot = 1;
2186 else if (!strcmp(buf, "off"))
2187 snapshot = 0;
2188 else {
2189 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2190 return -1;
2194 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2195 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2196 cache = 0;
2197 else if (!strcmp(buf, "writethrough"))
2198 cache = 1;
2199 else if (!strcmp(buf, "writeback"))
2200 cache = 2;
2201 else {
2202 fprintf(stderr, "qemu: invalid cache option\n");
2203 return -1;
2207 if (get_param_value(buf, sizeof(buf), "format", str)) {
2208 if (strcmp(buf, "?") == 0) {
2209 fprintf(stderr, "qemu: Supported formats:");
2210 bdrv_iterate_format(bdrv_format_print, NULL);
2211 fprintf(stderr, "\n");
2212 return -1;
2214 drv = bdrv_find_format(buf);
2215 if (!drv) {
2216 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2217 return -1;
2221 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2222 if (!strcmp(buf, "on")) {
2223 if (extboot_drive != -1) {
2224 fprintf(stderr, "qemu: two bootable drives specified\n");
2225 return -1;
2227 extboot_drive = nb_drives;
2228 } else if (strcmp(buf, "off")) {
2229 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2230 return -1;
2234 if (arg->file == NULL)
2235 get_param_value(file, sizeof(file), "file", str);
2236 else
2237 pstrcpy(file, sizeof(file), arg->file);
2239 if (!get_param_value(serial, sizeof(serial), "serial", str))
2240 memset(serial, 0, sizeof(serial));
2242 onerror = BLOCK_ERR_STOP_ENOSPC;
2243 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2244 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2245 fprintf(stderr, "werror is no supported by this format\n");
2246 return -1;
2248 if (!strcmp(buf, "ignore"))
2249 onerror = BLOCK_ERR_IGNORE;
2250 else if (!strcmp(buf, "enospc"))
2251 onerror = BLOCK_ERR_STOP_ENOSPC;
2252 else if (!strcmp(buf, "stop"))
2253 onerror = BLOCK_ERR_STOP_ANY;
2254 else if (!strcmp(buf, "report"))
2255 onerror = BLOCK_ERR_REPORT;
2256 else {
2257 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2258 return -1;
2262 devaddr = NULL;
2263 if (get_param_value(buf, sizeof(buf), "addr", str)) {
2264 if (type != IF_VIRTIO) {
2265 fprintf(stderr, "addr is not supported by in '%s'\n", str);
2266 return -1;
2268 devaddr = strdup(buf);
2271 /* compute bus and unit according index */
2273 if (index != -1) {
2274 if (bus_id != 0 || unit_id != -1) {
2275 fprintf(stderr,
2276 "qemu: '%s' index cannot be used with bus and unit\n", str);
2277 return -1;
2279 if (max_devs == 0)
2281 unit_id = index;
2282 bus_id = 0;
2283 } else {
2284 unit_id = index % max_devs;
2285 bus_id = index / max_devs;
2289 /* if user doesn't specify a unit_id,
2290 * try to find the first free
2293 if (unit_id == -1) {
2294 unit_id = 0;
2295 while (drive_get_index(type, bus_id, unit_id) != -1) {
2296 unit_id++;
2297 if (max_devs && unit_id >= max_devs) {
2298 unit_id -= max_devs;
2299 bus_id++;
2304 /* check unit id */
2306 if (max_devs && unit_id >= max_devs) {
2307 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2308 str, unit_id, max_devs - 1);
2309 return -1;
2313 * ignore multiple definitions
2316 if (drive_get_index(type, bus_id, unit_id) != -1)
2317 return -2;
2319 /* init */
2321 if (type == IF_IDE || type == IF_SCSI)
2322 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2323 if (max_devs)
2324 snprintf(buf, sizeof(buf), "%s%i%s%i",
2325 devname, bus_id, mediastr, unit_id);
2326 else
2327 snprintf(buf, sizeof(buf), "%s%s%i",
2328 devname, mediastr, unit_id);
2329 bdrv = bdrv_new(buf);
2330 drives_table_idx = drive_get_free_idx();
2331 drives_table[drives_table_idx].bdrv = bdrv;
2332 drives_table[drives_table_idx].devaddr = devaddr;
2333 drives_table[drives_table_idx].type = type;
2334 drives_table[drives_table_idx].bus = bus_id;
2335 drives_table[drives_table_idx].unit = unit_id;
2336 drives_table[drives_table_idx].onerror = onerror;
2337 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2338 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2339 nb_drives++;
2341 switch(type) {
2342 case IF_IDE:
2343 case IF_SCSI:
2344 case IF_XEN:
2345 switch(media) {
2346 case MEDIA_DISK:
2347 if (cyls != 0) {
2348 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2349 bdrv_set_translation_hint(bdrv, translation);
2351 break;
2352 case MEDIA_CDROM:
2353 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2354 break;
2356 break;
2357 case IF_SD:
2358 /* FIXME: This isn't really a floppy, but it's a reasonable
2359 approximation. */
2360 case IF_FLOPPY:
2361 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2362 break;
2363 case IF_PFLASH:
2364 case IF_MTD:
2365 case IF_VIRTIO:
2366 break;
2367 case IF_COUNT:
2368 abort();
2370 if (!file[0])
2371 return -2;
2372 bdrv_flags = 0;
2373 if (snapshot) {
2374 bdrv_flags |= BDRV_O_SNAPSHOT;
2375 cache = 2; /* always use write-back with snapshot */
2377 if (cache == 0) /* no caching */
2378 bdrv_flags |= BDRV_O_NOCACHE;
2379 else if (cache == 2) /* write-back */
2380 bdrv_flags |= BDRV_O_CACHE_WB;
2381 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2382 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2383 file, strerror(errno));
2384 return -1;
2386 if (bdrv_key_required(bdrv))
2387 autostart = 0;
2388 return drives_table_idx;
2391 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2393 boot_set_handler = func;
2394 boot_set_opaque = opaque;
2397 int qemu_boot_set(const char *boot_devices)
2399 if (!boot_set_handler) {
2400 return -EINVAL;
2402 return boot_set_handler(boot_set_opaque, boot_devices);
2405 static int parse_bootdevices(char *devices)
2407 /* We just do some generic consistency checks */
2408 const char *p;
2409 int bitmap = 0;
2411 for (p = devices; *p != '\0'; p++) {
2412 /* Allowed boot devices are:
2413 * a-b: floppy disk drives
2414 * c-f: IDE disk drives
2415 * g-m: machine implementation dependant drives
2416 * n-p: network devices
2417 * It's up to each machine implementation to check if the given boot
2418 * devices match the actual hardware implementation and firmware
2419 * features.
2421 if (*p < 'a' || *p > 'p') {
2422 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2423 exit(1);
2425 if (bitmap & (1 << (*p - 'a'))) {
2426 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2427 exit(1);
2429 bitmap |= 1 << (*p - 'a');
2431 return bitmap;
2434 static void restore_boot_devices(void *opaque)
2436 char *standard_boot_devices = opaque;
2438 qemu_boot_set(standard_boot_devices);
2440 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2441 qemu_free(standard_boot_devices);
2444 static void numa_add(const char *optarg)
2446 char option[128];
2447 char *endptr;
2448 unsigned long long value, endvalue;
2449 int nodenr;
2451 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2452 if (!strcmp(option, "node")) {
2453 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2454 nodenr = nb_numa_nodes;
2455 } else {
2456 nodenr = strtoull(option, NULL, 10);
2459 if (get_param_value(option, 128, "mem", optarg) == 0) {
2460 node_mem[nodenr] = 0;
2461 } else {
2462 value = strtoull(option, &endptr, 0);
2463 switch (*endptr) {
2464 case 0: case 'M': case 'm':
2465 value <<= 20;
2466 break;
2467 case 'G': case 'g':
2468 value <<= 30;
2469 break;
2471 node_mem[nodenr] = value;
2473 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2474 node_cpumask[nodenr] = 0;
2475 } else {
2476 value = strtoull(option, &endptr, 10);
2477 if (value >= 64) {
2478 value = 63;
2479 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2480 } else {
2481 if (*endptr == '-') {
2482 endvalue = strtoull(endptr+1, &endptr, 10);
2483 if (endvalue >= 63) {
2484 endvalue = 62;
2485 fprintf(stderr,
2486 "only 63 CPUs in NUMA mode supported.\n");
2488 value = (1 << (endvalue + 1)) - (1 << value);
2489 } else {
2490 value = 1 << value;
2493 node_cpumask[nodenr] = value;
2495 nb_numa_nodes++;
2497 return;
2500 /***********************************************************/
2501 /* USB devices */
2503 static USBPort *used_usb_ports;
2504 static USBPort *free_usb_ports;
2506 /* ??? Maybe change this to register a hub to keep track of the topology. */
2507 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2508 usb_attachfn attach)
2510 port->opaque = opaque;
2511 port->index = index;
2512 port->attach = attach;
2513 port->next = free_usb_ports;
2514 free_usb_ports = port;
2517 int usb_device_add_dev(USBDevice *dev)
2519 USBPort *port;
2521 /* Find a USB port to add the device to. */
2522 port = free_usb_ports;
2523 if (!port->next) {
2524 USBDevice *hub;
2526 /* Create a new hub and chain it on. */
2527 free_usb_ports = NULL;
2528 port->next = used_usb_ports;
2529 used_usb_ports = port;
2531 hub = usb_hub_init(VM_USB_HUB_SIZE);
2532 usb_attach(port, hub);
2533 port = free_usb_ports;
2536 free_usb_ports = port->next;
2537 port->next = used_usb_ports;
2538 used_usb_ports = port;
2539 usb_attach(port, dev);
2540 return 0;
2543 static void usb_msd_password_cb(void *opaque, int err)
2545 USBDevice *dev = opaque;
2547 if (!err)
2548 usb_device_add_dev(dev);
2549 else
2550 dev->handle_destroy(dev);
2553 static int usb_device_add(const char *devname, int is_hotplug)
2555 const char *p;
2556 USBDevice *dev;
2558 if (!free_usb_ports)
2559 return -1;
2561 if (strstart(devname, "host:", &p)) {
2562 dev = usb_host_device_open(p);
2563 } else if (!strcmp(devname, "mouse")) {
2564 dev = usb_mouse_init();
2565 } else if (!strcmp(devname, "tablet")) {
2566 dev = usb_tablet_init();
2567 } else if (!strcmp(devname, "keyboard")) {
2568 dev = usb_keyboard_init();
2569 } else if (strstart(devname, "disk:", &p)) {
2570 BlockDriverState *bs;
2572 dev = usb_msd_init(p);
2573 if (!dev)
2574 return -1;
2575 bs = usb_msd_get_bdrv(dev);
2576 if (bdrv_key_required(bs)) {
2577 autostart = 0;
2578 if (is_hotplug) {
2579 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2580 dev);
2581 return 0;
2584 } else if (!strcmp(devname, "wacom-tablet")) {
2585 dev = usb_wacom_init();
2586 } else if (strstart(devname, "serial:", &p)) {
2587 dev = usb_serial_init(p);
2588 #ifdef CONFIG_BRLAPI
2589 } else if (!strcmp(devname, "braille")) {
2590 dev = usb_baum_init();
2591 #endif
2592 } else if (strstart(devname, "net:", &p)) {
2593 int nic = nb_nics;
2595 if (net_client_init(NULL, "nic", p) < 0)
2596 return -1;
2597 nd_table[nic].model = qemu_strdup("usb");
2598 dev = usb_net_init(&nd_table[nic]);
2599 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2600 dev = usb_bt_init(devname[2] ? hci_init(p) :
2601 bt_new_hci(qemu_find_bt_vlan(0)));
2602 } else {
2603 return -1;
2605 if (!dev)
2606 return -1;
2608 return usb_device_add_dev(dev);
2611 int usb_device_del_addr(int bus_num, int addr)
2613 USBPort *port;
2614 USBPort **lastp;
2615 USBDevice *dev;
2617 if (!used_usb_ports)
2618 return -1;
2620 if (bus_num != 0)
2621 return -1;
2623 lastp = &used_usb_ports;
2624 port = used_usb_ports;
2625 while (port && port->dev->addr != addr) {
2626 lastp = &port->next;
2627 port = port->next;
2630 if (!port)
2631 return -1;
2633 dev = port->dev;
2634 *lastp = port->next;
2635 usb_attach(port, NULL);
2636 dev->handle_destroy(dev);
2637 port->next = free_usb_ports;
2638 free_usb_ports = port;
2639 return 0;
2642 static int usb_device_del(const char *devname)
2644 int bus_num, addr;
2645 const char *p;
2647 if (strstart(devname, "host:", &p))
2648 return usb_host_device_close(p);
2650 if (!used_usb_ports)
2651 return -1;
2653 p = strchr(devname, '.');
2654 if (!p)
2655 return -1;
2656 bus_num = strtoul(devname, NULL, 0);
2657 addr = strtoul(p + 1, NULL, 0);
2659 return usb_device_del_addr(bus_num, addr);
2662 void do_usb_add(Monitor *mon, const char *devname)
2664 usb_device_add(devname, 1);
2667 void do_usb_del(Monitor *mon, const char *devname)
2669 usb_device_del(devname);
2672 void usb_info(Monitor *mon)
2674 USBDevice *dev;
2675 USBPort *port;
2676 const char *speed_str;
2678 if (!usb_enabled) {
2679 monitor_printf(mon, "USB support not enabled\n");
2680 return;
2683 for (port = used_usb_ports; port; port = port->next) {
2684 dev = port->dev;
2685 if (!dev)
2686 continue;
2687 switch(dev->speed) {
2688 case USB_SPEED_LOW:
2689 speed_str = "1.5";
2690 break;
2691 case USB_SPEED_FULL:
2692 speed_str = "12";
2693 break;
2694 case USB_SPEED_HIGH:
2695 speed_str = "480";
2696 break;
2697 default:
2698 speed_str = "?";
2699 break;
2701 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2702 0, dev->addr, speed_str, dev->devname);
2706 /***********************************************************/
2707 /* PCMCIA/Cardbus */
2709 static struct pcmcia_socket_entry_s {
2710 PCMCIASocket *socket;
2711 struct pcmcia_socket_entry_s *next;
2712 } *pcmcia_sockets = 0;
2714 void pcmcia_socket_register(PCMCIASocket *socket)
2716 struct pcmcia_socket_entry_s *entry;
2718 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2719 entry->socket = socket;
2720 entry->next = pcmcia_sockets;
2721 pcmcia_sockets = entry;
2724 void pcmcia_socket_unregister(PCMCIASocket *socket)
2726 struct pcmcia_socket_entry_s *entry, **ptr;
2728 ptr = &pcmcia_sockets;
2729 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2730 if (entry->socket == socket) {
2731 *ptr = entry->next;
2732 qemu_free(entry);
2736 void pcmcia_info(Monitor *mon)
2738 struct pcmcia_socket_entry_s *iter;
2740 if (!pcmcia_sockets)
2741 monitor_printf(mon, "No PCMCIA sockets\n");
2743 for (iter = pcmcia_sockets; iter; iter = iter->next)
2744 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2745 iter->socket->attached ? iter->socket->card_string :
2746 "Empty");
2749 /***********************************************************/
2750 /* register display */
2752 struct DisplayAllocator default_allocator = {
2753 defaultallocator_create_displaysurface,
2754 defaultallocator_resize_displaysurface,
2755 defaultallocator_free_displaysurface
2758 void register_displaystate(DisplayState *ds)
2760 DisplayState **s;
2761 s = &display_state;
2762 while (*s != NULL)
2763 s = &(*s)->next;
2764 ds->next = NULL;
2765 *s = ds;
2768 DisplayState *get_displaystate(void)
2770 return display_state;
2773 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2775 if(ds->allocator == &default_allocator) ds->allocator = da;
2776 return ds->allocator;
2779 /* dumb display */
2781 static void dumb_display_init(void)
2783 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2784 ds->allocator = &default_allocator;
2785 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2786 register_displaystate(ds);
2789 /***********************************************************/
2790 /* I/O handling */
2792 typedef struct IOHandlerRecord {
2793 int fd;
2794 IOCanRWHandler *fd_read_poll;
2795 IOHandler *fd_read;
2796 IOHandler *fd_write;
2797 int deleted;
2798 void *opaque;
2799 /* temporary data */
2800 struct pollfd *ufd;
2801 struct IOHandlerRecord *next;
2802 } IOHandlerRecord;
2804 static IOHandlerRecord *first_io_handler;
2806 /* XXX: fd_read_poll should be suppressed, but an API change is
2807 necessary in the character devices to suppress fd_can_read(). */
2808 int qemu_set_fd_handler2(int fd,
2809 IOCanRWHandler *fd_read_poll,
2810 IOHandler *fd_read,
2811 IOHandler *fd_write,
2812 void *opaque)
2814 IOHandlerRecord **pioh, *ioh;
2816 if (!fd_read && !fd_write) {
2817 pioh = &first_io_handler;
2818 for(;;) {
2819 ioh = *pioh;
2820 if (ioh == NULL)
2821 break;
2822 if (ioh->fd == fd) {
2823 ioh->deleted = 1;
2824 break;
2826 pioh = &ioh->next;
2828 } else {
2829 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2830 if (ioh->fd == fd)
2831 goto found;
2833 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2834 ioh->next = first_io_handler;
2835 first_io_handler = ioh;
2836 found:
2837 ioh->fd = fd;
2838 ioh->fd_read_poll = fd_read_poll;
2839 ioh->fd_read = fd_read;
2840 ioh->fd_write = fd_write;
2841 ioh->opaque = opaque;
2842 ioh->deleted = 0;
2844 qemu_notify_event();
2845 return 0;
2848 int qemu_set_fd_handler(int fd,
2849 IOHandler *fd_read,
2850 IOHandler *fd_write,
2851 void *opaque)
2853 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2856 #ifdef _WIN32
2857 /***********************************************************/
2858 /* Polling handling */
2860 typedef struct PollingEntry {
2861 PollingFunc *func;
2862 void *opaque;
2863 struct PollingEntry *next;
2864 } PollingEntry;
2866 static PollingEntry *first_polling_entry;
2868 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2870 PollingEntry **ppe, *pe;
2871 pe = qemu_mallocz(sizeof(PollingEntry));
2872 pe->func = func;
2873 pe->opaque = opaque;
2874 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2875 *ppe = pe;
2876 return 0;
2879 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2881 PollingEntry **ppe, *pe;
2882 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2883 pe = *ppe;
2884 if (pe->func == func && pe->opaque == opaque) {
2885 *ppe = pe->next;
2886 qemu_free(pe);
2887 break;
2892 /***********************************************************/
2893 /* Wait objects support */
2894 typedef struct WaitObjects {
2895 int num;
2896 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2897 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2898 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2899 } WaitObjects;
2901 static WaitObjects wait_objects = {0};
2903 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2905 WaitObjects *w = &wait_objects;
2907 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2908 return -1;
2909 w->events[w->num] = handle;
2910 w->func[w->num] = func;
2911 w->opaque[w->num] = opaque;
2912 w->num++;
2913 return 0;
2916 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2918 int i, found;
2919 WaitObjects *w = &wait_objects;
2921 found = 0;
2922 for (i = 0; i < w->num; i++) {
2923 if (w->events[i] == handle)
2924 found = 1;
2925 if (found) {
2926 w->events[i] = w->events[i + 1];
2927 w->func[i] = w->func[i + 1];
2928 w->opaque[i] = w->opaque[i + 1];
2931 if (found)
2932 w->num--;
2934 #endif
2936 /***********************************************************/
2937 /* ram save/restore */
2939 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2941 int v;
2943 v = qemu_get_byte(f);
2944 switch(v) {
2945 case 0:
2946 if (qemu_get_buffer(f, buf, len) != len)
2947 return -EIO;
2948 break;
2949 case 1:
2950 v = qemu_get_byte(f);
2951 memset(buf, v, len);
2952 break;
2953 default:
2954 return -EINVAL;
2957 if (qemu_file_has_error(f))
2958 return -EIO;
2960 return 0;
2963 static int ram_load_v1(QEMUFile *f, void *opaque)
2965 int ret;
2966 ram_addr_t i;
2968 if (qemu_get_be32(f) != last_ram_offset)
2969 return -EINVAL;
2970 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2971 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
2972 continue;
2973 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2974 if (ret)
2975 return ret;
2977 return 0;
2980 #define BDRV_HASH_BLOCK_SIZE 1024
2981 #define IOBUF_SIZE 4096
2982 #define RAM_CBLOCK_MAGIC 0xfabe
2984 typedef struct RamDecompressState {
2985 z_stream zstream;
2986 QEMUFile *f;
2987 uint8_t buf[IOBUF_SIZE];
2988 } RamDecompressState;
2990 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2992 int ret;
2993 memset(s, 0, sizeof(*s));
2994 s->f = f;
2995 ret = inflateInit(&s->zstream);
2996 if (ret != Z_OK)
2997 return -1;
2998 return 0;
3001 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3003 int ret, clen;
3005 s->zstream.avail_out = len;
3006 s->zstream.next_out = buf;
3007 while (s->zstream.avail_out > 0) {
3008 if (s->zstream.avail_in == 0) {
3009 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3010 return -1;
3011 clen = qemu_get_be16(s->f);
3012 if (clen > IOBUF_SIZE)
3013 return -1;
3014 qemu_get_buffer(s->f, s->buf, clen);
3015 s->zstream.avail_in = clen;
3016 s->zstream.next_in = s->buf;
3018 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3019 if (ret != Z_OK && ret != Z_STREAM_END) {
3020 return -1;
3023 return 0;
3026 static void ram_decompress_close(RamDecompressState *s)
3028 inflateEnd(&s->zstream);
3031 #define RAM_SAVE_FLAG_FULL 0x01
3032 #define RAM_SAVE_FLAG_COMPRESS 0x02
3033 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3034 #define RAM_SAVE_FLAG_PAGE 0x08
3035 #define RAM_SAVE_FLAG_EOS 0x10
3037 static int is_dup_page(uint8_t *page, uint8_t ch)
3039 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3040 uint32_t *array = (uint32_t *)page;
3041 int i;
3043 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3044 if (array[i] != val)
3045 return 0;
3048 return 1;
3051 static int ram_save_block(QEMUFile *f)
3053 static ram_addr_t current_addr = 0;
3054 ram_addr_t saved_addr = current_addr;
3055 ram_addr_t addr = 0;
3056 int found = 0;
3058 while (addr < last_ram_offset) {
3059 if (kvm_enabled() && current_addr == 0) {
3060 int r;
3061 r = kvm_update_dirty_pages_log();
3062 if (r) {
3063 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3064 qemu_file_set_error(f);
3065 return 0;
3068 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3069 uint8_t *p;
3071 cpu_physical_memory_reset_dirty(current_addr,
3072 current_addr + TARGET_PAGE_SIZE,
3073 MIGRATION_DIRTY_FLAG);
3075 p = qemu_get_ram_ptr(current_addr);
3077 if (is_dup_page(p, *p)) {
3078 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3079 qemu_put_byte(f, *p);
3080 } else {
3081 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3082 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3085 found = 1;
3086 break;
3088 addr += TARGET_PAGE_SIZE;
3089 current_addr = (saved_addr + addr) % last_ram_offset;
3092 return found;
3095 static uint64_t bytes_transferred = 0;
3097 static ram_addr_t ram_save_remaining(void)
3099 ram_addr_t addr;
3100 ram_addr_t count = 0;
3102 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3103 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3104 count++;
3107 return count;
3110 uint64_t ram_bytes_remaining(void)
3112 return ram_save_remaining() * TARGET_PAGE_SIZE;
3115 uint64_t ram_bytes_transferred(void)
3117 return bytes_transferred;
3120 uint64_t ram_bytes_total(void)
3122 return last_ram_offset;
3125 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3127 ram_addr_t addr;
3128 uint64_t bytes_transferred_last;
3129 double bwidth = 0;
3130 uint64_t expected_time = 0;
3132 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3133 qemu_file_set_error(f);
3134 return 0;
3137 if (stage == 1) {
3138 /* Make sure all dirty bits are set */
3139 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3140 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3141 cpu_physical_memory_set_dirty(addr);
3144 /* Enable dirty memory tracking */
3145 cpu_physical_memory_set_dirty_tracking(1);
3147 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3150 bytes_transferred_last = bytes_transferred;
3151 bwidth = get_clock();
3153 while (!qemu_file_rate_limit(f)) {
3154 int ret;
3156 ret = ram_save_block(f);
3157 bytes_transferred += ret * TARGET_PAGE_SIZE;
3158 if (ret == 0) /* no more blocks */
3159 break;
3162 bwidth = get_clock() - bwidth;
3163 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3165 /* if we haven't transferred anything this round, force expected_time to a
3166 * a very high value, but without crashing */
3167 if (bwidth == 0)
3168 bwidth = 0.000001;
3170 /* try transferring iterative blocks of memory */
3172 if (stage == 3) {
3174 /* flush all remaining blocks regardless of rate limiting */
3175 while (ram_save_block(f) != 0) {
3176 bytes_transferred += TARGET_PAGE_SIZE;
3178 cpu_physical_memory_set_dirty_tracking(0);
3181 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3183 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3185 return (stage == 2) && (expected_time <= migrate_max_downtime());
3188 static int ram_load_dead(QEMUFile *f, void *opaque)
3190 RamDecompressState s1, *s = &s1;
3191 uint8_t buf[10];
3192 ram_addr_t i;
3194 if (ram_decompress_open(s, f) < 0)
3195 return -EINVAL;
3196 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3197 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3198 continue;
3199 if (ram_decompress_buf(s, buf, 1) < 0) {
3200 fprintf(stderr, "Error while reading ram block header\n");
3201 goto error;
3203 if (buf[0] == 0) {
3204 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3205 BDRV_HASH_BLOCK_SIZE) < 0) {
3206 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3207 goto error;
3209 } else {
3210 error:
3211 printf("Error block header\n");
3212 return -EINVAL;
3215 ram_decompress_close(s);
3217 return 0;
3220 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3222 ram_addr_t addr;
3223 int flags;
3225 if (version_id == 1)
3226 return ram_load_v1(f, opaque);
3228 if (version_id == 2) {
3229 if (qemu_get_be32(f) != last_ram_offset)
3230 return -EINVAL;
3231 return ram_load_dead(f, opaque);
3234 if (version_id != 3)
3235 return -EINVAL;
3237 do {
3238 addr = qemu_get_be64(f);
3240 flags = addr & ~TARGET_PAGE_MASK;
3241 addr &= TARGET_PAGE_MASK;
3243 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3244 if (addr != last_ram_offset)
3245 return -EINVAL;
3248 if (flags & RAM_SAVE_FLAG_FULL) {
3249 if (ram_load_dead(f, opaque) < 0)
3250 return -EINVAL;
3253 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3254 uint8_t ch = qemu_get_byte(f);
3255 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3256 #ifndef _WIN32
3257 if (ch == 0 &&
3258 (!kvm_enabled() || kvm_has_sync_mmu())) {
3259 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3261 #endif
3262 } else if (flags & RAM_SAVE_FLAG_PAGE)
3263 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3264 } while (!(flags & RAM_SAVE_FLAG_EOS));
3266 return 0;
3269 void qemu_service_io(void)
3271 qemu_notify_event();
3274 /***********************************************************/
3275 /* bottom halves (can be seen as timers which expire ASAP) */
3277 struct QEMUBH {
3278 QEMUBHFunc *cb;
3279 void *opaque;
3280 int scheduled;
3281 int idle;
3282 int deleted;
3283 QEMUBH *next;
3286 static QEMUBH *first_bh = NULL;
3288 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3290 QEMUBH *bh;
3291 bh = qemu_mallocz(sizeof(QEMUBH));
3292 bh->cb = cb;
3293 bh->opaque = opaque;
3294 bh->next = first_bh;
3295 first_bh = bh;
3296 return bh;
3299 int qemu_bh_poll(void)
3301 QEMUBH *bh, **bhp;
3302 int ret;
3304 ret = 0;
3305 for (bh = first_bh; bh; bh = bh->next) {
3306 if (!bh->deleted && bh->scheduled) {
3307 bh->scheduled = 0;
3308 if (!bh->idle)
3309 ret = 1;
3310 bh->idle = 0;
3311 bh->cb(bh->opaque);
3315 /* remove deleted bhs */
3316 bhp = &first_bh;
3317 while (*bhp) {
3318 bh = *bhp;
3319 if (bh->deleted) {
3320 *bhp = bh->next;
3321 qemu_free(bh);
3322 } else
3323 bhp = &bh->next;
3326 return ret;
3329 void qemu_bh_schedule_idle(QEMUBH *bh)
3331 if (bh->scheduled)
3332 return;
3333 bh->scheduled = 1;
3334 bh->idle = 1;
3337 void qemu_bh_schedule(QEMUBH *bh)
3339 if (bh->scheduled)
3340 return;
3341 bh->scheduled = 1;
3342 bh->idle = 0;
3343 /* stop the currently executing CPU to execute the BH ASAP */
3344 qemu_notify_event();
3347 void qemu_bh_cancel(QEMUBH *bh)
3349 bh->scheduled = 0;
3352 void qemu_bh_delete(QEMUBH *bh)
3354 bh->scheduled = 0;
3355 bh->deleted = 1;
3358 static void qemu_bh_update_timeout(int *timeout)
3360 QEMUBH *bh;
3362 for (bh = first_bh; bh; bh = bh->next) {
3363 if (!bh->deleted && bh->scheduled) {
3364 if (bh->idle) {
3365 /* idle bottom halves will be polled at least
3366 * every 10ms */
3367 *timeout = MIN(10, *timeout);
3368 } else {
3369 /* non-idle bottom halves will be executed
3370 * immediately */
3371 *timeout = 0;
3372 break;
3378 /***********************************************************/
3379 /* machine registration */
3381 static QEMUMachine *first_machine = NULL;
3382 QEMUMachine *current_machine = NULL;
3384 int qemu_register_machine(QEMUMachine *m)
3386 QEMUMachine **pm;
3387 pm = &first_machine;
3388 while (*pm != NULL)
3389 pm = &(*pm)->next;
3390 m->next = NULL;
3391 *pm = m;
3392 return 0;
3395 static QEMUMachine *find_machine(const char *name)
3397 QEMUMachine *m;
3399 for(m = first_machine; m != NULL; m = m->next) {
3400 if (!strcmp(m->name, name))
3401 return m;
3402 if (m->alias && !strcmp(m->alias, name))
3403 return m;
3405 return NULL;
3408 static QEMUMachine *find_default_machine(void)
3410 QEMUMachine *m;
3412 for(m = first_machine; m != NULL; m = m->next) {
3413 if (m->is_default) {
3414 return m;
3417 return NULL;
3420 /***********************************************************/
3421 /* main execution loop */
3423 static void gui_update(void *opaque)
3425 uint64_t interval = GUI_REFRESH_INTERVAL;
3426 DisplayState *ds = opaque;
3427 DisplayChangeListener *dcl = ds->listeners;
3429 dpy_refresh(ds);
3431 while (dcl != NULL) {
3432 if (dcl->gui_timer_interval &&
3433 dcl->gui_timer_interval < interval)
3434 interval = dcl->gui_timer_interval;
3435 dcl = dcl->next;
3437 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3440 static void nographic_update(void *opaque)
3442 uint64_t interval = GUI_REFRESH_INTERVAL;
3444 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3447 struct vm_change_state_entry {
3448 VMChangeStateHandler *cb;
3449 void *opaque;
3450 LIST_ENTRY (vm_change_state_entry) entries;
3453 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3455 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3456 void *opaque)
3458 VMChangeStateEntry *e;
3460 e = qemu_mallocz(sizeof (*e));
3462 e->cb = cb;
3463 e->opaque = opaque;
3464 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3465 return e;
3468 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3470 LIST_REMOVE (e, entries);
3471 qemu_free (e);
3474 static void vm_state_notify(int running, int reason)
3476 VMChangeStateEntry *e;
3478 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3479 e->cb(e->opaque, running, reason);
3483 static void resume_all_vcpus(void);
3484 static void pause_all_vcpus(void);
3486 void vm_start(void)
3488 if (!vm_running) {
3489 cpu_enable_ticks();
3490 vm_running = 1;
3491 vm_state_notify(1, 0);
3492 qemu_rearm_alarm_timer(alarm_timer);
3493 resume_all_vcpus();
3497 /* reset/shutdown handler */
3499 typedef struct QEMUResetEntry {
3500 TAILQ_ENTRY(QEMUResetEntry) entry;
3501 QEMUResetHandler *func;
3502 void *opaque;
3503 } QEMUResetEntry;
3505 static TAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3506 TAILQ_HEAD_INITIALIZER(reset_handlers);
3507 static int reset_requested;
3508 static int shutdown_requested;
3509 static int powerdown_requested;
3510 static int debug_requested;
3511 static int vmstop_requested;
3513 int qemu_no_shutdown(void)
3515 int r = no_shutdown;
3516 no_shutdown = 0;
3517 return r;
3520 int qemu_shutdown_requested(void)
3522 int r = shutdown_requested;
3523 shutdown_requested = 0;
3524 return r;
3527 int qemu_reset_requested(void)
3529 int r = reset_requested;
3530 reset_requested = 0;
3531 return r;
3534 int qemu_powerdown_requested(void)
3536 int r = powerdown_requested;
3537 powerdown_requested = 0;
3538 return r;
3541 static int qemu_debug_requested(void)
3543 int r = debug_requested;
3544 debug_requested = 0;
3545 return r;
3548 static int qemu_vmstop_requested(void)
3550 int r = vmstop_requested;
3551 vmstop_requested = 0;
3552 return r;
3555 static void do_vm_stop(int reason)
3557 if (vm_running) {
3558 cpu_disable_ticks();
3559 vm_running = 0;
3560 pause_all_vcpus();
3561 vm_state_notify(0, reason);
3565 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3567 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3569 re->func = func;
3570 re->opaque = opaque;
3571 TAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3574 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3576 QEMUResetEntry *re;
3578 TAILQ_FOREACH(re, &reset_handlers, entry) {
3579 if (re->func == func && re->opaque == opaque) {
3580 TAILQ_REMOVE(&reset_handlers, re, entry);
3581 qemu_free(re);
3582 return;
3587 void qemu_system_reset(void)
3589 QEMUResetEntry *re, *nre;
3591 /* reset all devices */
3592 TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3593 re->func(re->opaque);
3597 void qemu_system_reset_request(void)
3599 if (no_reboot) {
3600 shutdown_requested = 1;
3601 } else {
3602 reset_requested = 1;
3604 if (cpu_single_env) {
3605 cpu_single_env->stopped = 1;
3607 qemu_notify_event();
3610 void qemu_system_shutdown_request(void)
3612 shutdown_requested = 1;
3613 qemu_notify_event();
3616 void qemu_system_powerdown_request(void)
3618 powerdown_requested = 1;
3619 qemu_notify_event();
3622 #ifdef CONFIG_IOTHREAD
3623 static void qemu_system_vmstop_request(int reason)
3625 vmstop_requested = reason;
3626 qemu_notify_event();
3628 #endif
3630 #ifndef _WIN32
3631 static int io_thread_fd = -1;
3633 static void qemu_event_increment(void)
3635 static const char byte = 0;
3637 if (io_thread_fd == -1)
3638 return;
3640 write(io_thread_fd, &byte, sizeof(byte));
3643 static void qemu_event_read(void *opaque)
3645 int fd = (unsigned long)opaque;
3646 ssize_t len;
3648 /* Drain the notify pipe */
3649 do {
3650 char buffer[512];
3651 len = read(fd, buffer, sizeof(buffer));
3652 } while ((len == -1 && errno == EINTR) || len > 0);
3655 static int qemu_event_init(void)
3657 int err;
3658 int fds[2];
3660 err = pipe(fds);
3661 if (err == -1)
3662 return -errno;
3664 err = fcntl_setfl(fds[0], O_NONBLOCK);
3665 if (err < 0)
3666 goto fail;
3668 err = fcntl_setfl(fds[1], O_NONBLOCK);
3669 if (err < 0)
3670 goto fail;
3672 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3673 (void *)(unsigned long)fds[0]);
3675 io_thread_fd = fds[1];
3676 return 0;
3678 fail:
3679 close(fds[0]);
3680 close(fds[1]);
3681 return err;
3683 #else
3684 HANDLE qemu_event_handle;
3686 static void dummy_event_handler(void *opaque)
3690 static int qemu_event_init(void)
3692 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3693 if (!qemu_event_handle) {
3694 perror("Failed CreateEvent");
3695 return -1;
3697 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3698 return 0;
3701 static void qemu_event_increment(void)
3703 SetEvent(qemu_event_handle);
3705 #endif
3707 static int cpu_can_run(CPUState *env)
3709 if (env->stop)
3710 return 0;
3711 if (env->stopped)
3712 return 0;
3713 return 1;
3716 #ifndef CONFIG_IOTHREAD
3717 static int qemu_init_main_loop(void)
3719 return qemu_event_init();
3722 void qemu_init_vcpu(void *_env)
3724 CPUState *env = _env;
3726 if (kvm_enabled())
3727 kvm_init_vcpu(env);
3728 return;
3731 int qemu_cpu_self(void *env)
3733 return 1;
3736 static void resume_all_vcpus(void)
3740 static void pause_all_vcpus(void)
3744 void qemu_cpu_kick(void *env)
3746 return;
3749 void qemu_notify_event(void)
3751 CPUState *env = cpu_single_env;
3753 if (kvm_enabled()) {
3754 qemu_kvm_notify_work();
3755 return;
3757 if (env) {
3758 cpu_exit(env);
3759 #ifdef USE_KQEMU
3760 if (env->kqemu_enabled)
3761 kqemu_cpu_interrupt(env);
3762 #endif
3766 #ifdef KVM_UPSTREAM
3767 #define qemu_mutex_lock_iothread() do { } while (0)
3768 #define qemu_mutex_unlock_iothread() do { } while (0)
3769 #endif
3771 void vm_stop(int reason)
3773 do_vm_stop(reason);
3776 #else /* CONFIG_IOTHREAD */
3778 #include "qemu-thread.h"
3780 QemuMutex qemu_global_mutex;
3781 static QemuMutex qemu_fair_mutex;
3783 static QemuThread io_thread;
3785 static QemuThread *tcg_cpu_thread;
3786 static QemuCond *tcg_halt_cond;
3788 static int qemu_system_ready;
3789 /* cpu creation */
3790 static QemuCond qemu_cpu_cond;
3791 /* system init */
3792 static QemuCond qemu_system_cond;
3793 static QemuCond qemu_pause_cond;
3795 static void block_io_signals(void);
3796 static void unblock_io_signals(void);
3797 static int tcg_has_work(void);
3799 static int qemu_init_main_loop(void)
3801 int ret;
3803 ret = qemu_event_init();
3804 if (ret)
3805 return ret;
3807 qemu_cond_init(&qemu_pause_cond);
3808 qemu_mutex_init(&qemu_fair_mutex);
3809 qemu_mutex_init(&qemu_global_mutex);
3810 qemu_mutex_lock(&qemu_global_mutex);
3812 unblock_io_signals();
3813 qemu_thread_self(&io_thread);
3815 return 0;
3818 static void qemu_wait_io_event(CPUState *env)
3820 while (!tcg_has_work())
3821 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3823 qemu_mutex_unlock(&qemu_global_mutex);
3826 * Users of qemu_global_mutex can be starved, having no chance
3827 * to acquire it since this path will get to it first.
3828 * So use another lock to provide fairness.
3830 qemu_mutex_lock(&qemu_fair_mutex);
3831 qemu_mutex_unlock(&qemu_fair_mutex);
3833 qemu_mutex_lock(&qemu_global_mutex);
3834 if (env->stop) {
3835 env->stop = 0;
3836 env->stopped = 1;
3837 qemu_cond_signal(&qemu_pause_cond);
3841 static int qemu_cpu_exec(CPUState *env);
3843 static void *kvm_cpu_thread_fn(void *arg)
3845 CPUState *env = arg;
3847 block_io_signals();
3848 qemu_thread_self(env->thread);
3850 /* signal CPU creation */
3851 qemu_mutex_lock(&qemu_global_mutex);
3852 env->created = 1;
3853 qemu_cond_signal(&qemu_cpu_cond);
3855 /* and wait for machine initialization */
3856 while (!qemu_system_ready)
3857 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3859 while (1) {
3860 if (cpu_can_run(env))
3861 qemu_cpu_exec(env);
3862 qemu_wait_io_event(env);
3865 return NULL;
3868 static void tcg_cpu_exec(void);
3870 static void *tcg_cpu_thread_fn(void *arg)
3872 CPUState *env = arg;
3874 block_io_signals();
3875 qemu_thread_self(env->thread);
3877 /* signal CPU creation */
3878 qemu_mutex_lock(&qemu_global_mutex);
3879 for (env = first_cpu; env != NULL; env = env->next_cpu)
3880 env->created = 1;
3881 qemu_cond_signal(&qemu_cpu_cond);
3883 /* and wait for machine initialization */
3884 while (!qemu_system_ready)
3885 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3887 while (1) {
3888 tcg_cpu_exec();
3889 qemu_wait_io_event(cur_cpu);
3892 return NULL;
3895 void qemu_cpu_kick(void *_env)
3897 CPUState *env = _env;
3898 qemu_cond_broadcast(env->halt_cond);
3899 if (kvm_enabled())
3900 qemu_thread_signal(env->thread, SIGUSR1);
3903 int qemu_cpu_self(void *env)
3905 return (cpu_single_env != NULL);
3908 static void cpu_signal(int sig)
3910 if (cpu_single_env)
3911 cpu_exit(cpu_single_env);
3914 static void block_io_signals(void)
3916 sigset_t set;
3917 struct sigaction sigact;
3919 sigemptyset(&set);
3920 sigaddset(&set, SIGUSR2);
3921 sigaddset(&set, SIGIO);
3922 sigaddset(&set, SIGALRM);
3923 pthread_sigmask(SIG_BLOCK, &set, NULL);
3925 sigemptyset(&set);
3926 sigaddset(&set, SIGUSR1);
3927 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3929 memset(&sigact, 0, sizeof(sigact));
3930 sigact.sa_handler = cpu_signal;
3931 sigaction(SIGUSR1, &sigact, NULL);
3934 static void unblock_io_signals(void)
3936 sigset_t set;
3938 sigemptyset(&set);
3939 sigaddset(&set, SIGUSR2);
3940 sigaddset(&set, SIGIO);
3941 sigaddset(&set, SIGALRM);
3942 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3944 sigemptyset(&set);
3945 sigaddset(&set, SIGUSR1);
3946 pthread_sigmask(SIG_BLOCK, &set, NULL);
3949 static void qemu_signal_lock(unsigned int msecs)
3951 qemu_mutex_lock(&qemu_fair_mutex);
3953 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3954 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3955 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3956 break;
3958 qemu_mutex_unlock(&qemu_fair_mutex);
3961 static void qemu_mutex_lock_iothread(void)
3963 if (kvm_enabled()) {
3964 qemu_mutex_lock(&qemu_fair_mutex);
3965 qemu_mutex_lock(&qemu_global_mutex);
3966 qemu_mutex_unlock(&qemu_fair_mutex);
3967 } else
3968 qemu_signal_lock(100);
3971 static void qemu_mutex_unlock_iothread(void)
3973 qemu_mutex_unlock(&qemu_global_mutex);
3976 static int all_vcpus_paused(void)
3978 CPUState *penv = first_cpu;
3980 while (penv) {
3981 if (!penv->stopped)
3982 return 0;
3983 penv = (CPUState *)penv->next_cpu;
3986 return 1;
3989 static void pause_all_vcpus(void)
3991 CPUState *penv = first_cpu;
3993 while (penv) {
3994 penv->stop = 1;
3995 qemu_thread_signal(penv->thread, SIGUSR1);
3996 qemu_cpu_kick(penv);
3997 penv = (CPUState *)penv->next_cpu;
4000 while (!all_vcpus_paused()) {
4001 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
4002 penv = first_cpu;
4003 while (penv) {
4004 qemu_thread_signal(penv->thread, SIGUSR1);
4005 penv = (CPUState *)penv->next_cpu;
4010 static void resume_all_vcpus(void)
4012 CPUState *penv = first_cpu;
4014 while (penv) {
4015 penv->stop = 0;
4016 penv->stopped = 0;
4017 qemu_thread_signal(penv->thread, SIGUSR1);
4018 qemu_cpu_kick(penv);
4019 penv = (CPUState *)penv->next_cpu;
4023 static void tcg_init_vcpu(void *_env)
4025 CPUState *env = _env;
4026 /* share a single thread for all cpus with TCG */
4027 if (!tcg_cpu_thread) {
4028 env->thread = qemu_mallocz(sizeof(QemuThread));
4029 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4030 qemu_cond_init(env->halt_cond);
4031 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
4032 while (env->created == 0)
4033 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4034 tcg_cpu_thread = env->thread;
4035 tcg_halt_cond = env->halt_cond;
4036 } else {
4037 env->thread = tcg_cpu_thread;
4038 env->halt_cond = tcg_halt_cond;
4042 static void kvm_start_vcpu(CPUState *env)
4044 kvm_init_vcpu(env);
4045 env->thread = qemu_mallocz(sizeof(QemuThread));
4046 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4047 qemu_cond_init(env->halt_cond);
4048 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
4049 while (env->created == 0)
4050 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4053 void qemu_init_vcpu(void *_env)
4055 CPUState *env = _env;
4057 if (kvm_enabled())
4058 kvm_start_vcpu(env);
4059 else
4060 tcg_init_vcpu(env);
4063 void qemu_notify_event(void)
4065 qemu_event_increment();
4068 void vm_stop(int reason)
4070 QemuThread me;
4071 qemu_thread_self(&me);
4073 if (!qemu_thread_equal(&me, &io_thread)) {
4074 qemu_system_vmstop_request(reason);
4076 * FIXME: should not return to device code in case
4077 * vm_stop() has been requested.
4079 if (cpu_single_env) {
4080 cpu_exit(cpu_single_env);
4081 cpu_single_env->stop = 1;
4083 return;
4085 do_vm_stop(reason);
4088 #endif
4091 #ifdef _WIN32
4092 static void host_main_loop_wait(int *timeout)
4094 int ret, ret2, i;
4095 PollingEntry *pe;
4098 /* XXX: need to suppress polling by better using win32 events */
4099 ret = 0;
4100 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4101 ret |= pe->func(pe->opaque);
4103 if (ret == 0) {
4104 int err;
4105 WaitObjects *w = &wait_objects;
4107 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4108 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4109 if (w->func[ret - WAIT_OBJECT_0])
4110 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4112 /* Check for additional signaled events */
4113 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4115 /* Check if event is signaled */
4116 ret2 = WaitForSingleObject(w->events[i], 0);
4117 if(ret2 == WAIT_OBJECT_0) {
4118 if (w->func[i])
4119 w->func[i](w->opaque[i]);
4120 } else if (ret2 == WAIT_TIMEOUT) {
4121 } else {
4122 err = GetLastError();
4123 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4126 } else if (ret == WAIT_TIMEOUT) {
4127 } else {
4128 err = GetLastError();
4129 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4133 *timeout = 0;
4135 #else
4136 static void host_main_loop_wait(int *timeout)
4139 #endif
4141 void main_loop_wait(int timeout)
4143 IOHandlerRecord *ioh;
4144 fd_set rfds, wfds, xfds;
4145 int ret, nfds;
4146 struct timeval tv;
4148 qemu_bh_update_timeout(&timeout);
4150 host_main_loop_wait(&timeout);
4152 /* poll any events */
4153 /* XXX: separate device handlers from system ones */
4154 nfds = -1;
4155 FD_ZERO(&rfds);
4156 FD_ZERO(&wfds);
4157 FD_ZERO(&xfds);
4158 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4159 if (ioh->deleted)
4160 continue;
4161 if (ioh->fd_read &&
4162 (!ioh->fd_read_poll ||
4163 ioh->fd_read_poll(ioh->opaque) != 0)) {
4164 FD_SET(ioh->fd, &rfds);
4165 if (ioh->fd > nfds)
4166 nfds = ioh->fd;
4168 if (ioh->fd_write) {
4169 FD_SET(ioh->fd, &wfds);
4170 if (ioh->fd > nfds)
4171 nfds = ioh->fd;
4175 tv.tv_sec = timeout / 1000;
4176 tv.tv_usec = (timeout % 1000) * 1000;
4178 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4180 qemu_mutex_unlock_iothread();
4181 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4182 qemu_mutex_lock_iothread();
4183 if (ret > 0) {
4184 IOHandlerRecord **pioh;
4186 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4187 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4188 ioh->fd_read(ioh->opaque);
4189 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
4190 FD_CLR(ioh->fd, &rfds);
4192 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4193 ioh->fd_write(ioh->opaque);
4197 /* remove deleted IO handlers */
4198 pioh = &first_io_handler;
4199 while (*pioh) {
4200 ioh = *pioh;
4201 if (ioh->deleted) {
4202 *pioh = ioh->next;
4203 qemu_free(ioh);
4204 } else
4205 pioh = &ioh->next;
4209 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4211 /* rearm timer, if not periodic */
4212 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4213 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4214 qemu_rearm_alarm_timer(alarm_timer);
4217 /* vm time timers */
4218 if (vm_running) {
4219 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4220 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4221 qemu_get_clock(vm_clock));
4224 /* real time timers */
4225 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4226 qemu_get_clock(rt_clock));
4228 /* Check bottom-halves last in case any of the earlier events triggered
4229 them. */
4230 qemu_bh_poll();
4234 static int qemu_cpu_exec(CPUState *env)
4236 int ret;
4237 #ifdef CONFIG_PROFILER
4238 int64_t ti;
4239 #endif
4241 #ifdef CONFIG_PROFILER
4242 ti = profile_getclock();
4243 #endif
4244 if (use_icount) {
4245 int64_t count;
4246 int decr;
4247 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4248 env->icount_decr.u16.low = 0;
4249 env->icount_extra = 0;
4250 count = qemu_next_deadline();
4251 count = (count + (1 << icount_time_shift) - 1)
4252 >> icount_time_shift;
4253 qemu_icount += count;
4254 decr = (count > 0xffff) ? 0xffff : count;
4255 count -= decr;
4256 env->icount_decr.u16.low = decr;
4257 env->icount_extra = count;
4259 ret = cpu_exec(env);
4260 #ifdef CONFIG_PROFILER
4261 qemu_time += profile_getclock() - ti;
4262 #endif
4263 if (use_icount) {
4264 /* Fold pending instructions back into the
4265 instruction counter, and clear the interrupt flag. */
4266 qemu_icount -= (env->icount_decr.u16.low
4267 + env->icount_extra);
4268 env->icount_decr.u32 = 0;
4269 env->icount_extra = 0;
4271 return ret;
4274 static void tcg_cpu_exec(void)
4276 int ret = 0;
4278 if (next_cpu == NULL)
4279 next_cpu = first_cpu;
4280 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4281 CPUState *env = cur_cpu = next_cpu;
4283 if (!vm_running)
4284 break;
4285 if (timer_alarm_pending) {
4286 timer_alarm_pending = 0;
4287 break;
4289 if (cpu_can_run(env))
4290 ret = qemu_cpu_exec(env);
4291 if (ret == EXCP_DEBUG) {
4292 gdb_set_stop_cpu(env);
4293 debug_requested = 1;
4294 break;
4299 static int cpu_has_work(CPUState *env)
4301 if (env->stop)
4302 return 1;
4303 if (env->stopped)
4304 return 0;
4305 if (!env->halted)
4306 return 1;
4307 if (qemu_cpu_has_work(env))
4308 return 1;
4309 return 0;
4312 static int tcg_has_work(void)
4314 CPUState *env;
4316 for (env = first_cpu; env != NULL; env = env->next_cpu)
4317 if (cpu_has_work(env))
4318 return 1;
4319 return 0;
4322 static int qemu_calculate_timeout(void)
4324 #ifndef CONFIG_IOTHREAD
4325 int timeout;
4327 if (!vm_running)
4328 timeout = 5000;
4329 else if (tcg_has_work())
4330 timeout = 0;
4331 else if (!use_icount)
4332 timeout = 5000;
4333 else {
4334 /* XXX: use timeout computed from timers */
4335 int64_t add;
4336 int64_t delta;
4337 /* Advance virtual time to the next event. */
4338 if (use_icount == 1) {
4339 /* When not using an adaptive execution frequency
4340 we tend to get badly out of sync with real time,
4341 so just delay for a reasonable amount of time. */
4342 delta = 0;
4343 } else {
4344 delta = cpu_get_icount() - cpu_get_clock();
4346 if (delta > 0) {
4347 /* If virtual time is ahead of real time then just
4348 wait for IO. */
4349 timeout = (delta / 1000000) + 1;
4350 } else {
4351 /* Wait for either IO to occur or the next
4352 timer event. */
4353 add = qemu_next_deadline();
4354 /* We advance the timer before checking for IO.
4355 Limit the amount we advance so that early IO
4356 activity won't get the guest too far ahead. */
4357 if (add > 10000000)
4358 add = 10000000;
4359 delta += add;
4360 add = (add + (1 << icount_time_shift) - 1)
4361 >> icount_time_shift;
4362 qemu_icount += add;
4363 timeout = delta / 1000000;
4364 if (timeout < 0)
4365 timeout = 0;
4369 return timeout;
4370 #else /* CONFIG_IOTHREAD */
4371 return 1000;
4372 #endif
4375 static int vm_can_run(void)
4377 if (powerdown_requested)
4378 return 0;
4379 if (reset_requested)
4380 return 0;
4381 if (shutdown_requested)
4382 return 0;
4383 if (debug_requested)
4384 return 0;
4385 return 1;
4388 static void main_loop(void)
4390 int r;
4392 if (kvm_enabled()) {
4393 kvm_main_loop();
4394 cpu_disable_ticks();
4395 return;
4398 #ifdef CONFIG_IOTHREAD
4399 qemu_system_ready = 1;
4400 qemu_cond_broadcast(&qemu_system_cond);
4401 #endif
4403 for (;;) {
4404 do {
4405 #ifdef CONFIG_PROFILER
4406 int64_t ti;
4407 #endif
4408 #ifndef CONFIG_IOTHREAD
4409 tcg_cpu_exec();
4410 #endif
4411 #ifdef CONFIG_PROFILER
4412 ti = profile_getclock();
4413 #endif
4414 main_loop_wait(qemu_calculate_timeout());
4415 #ifdef CONFIG_PROFILER
4416 dev_time += profile_getclock() - ti;
4417 #endif
4418 } while (vm_can_run());
4420 if (qemu_debug_requested())
4421 vm_stop(EXCP_DEBUG);
4422 if (qemu_shutdown_requested()) {
4423 if (no_shutdown) {
4424 vm_stop(0);
4425 no_shutdown = 0;
4426 } else
4427 break;
4429 if (qemu_reset_requested()) {
4430 pause_all_vcpus();
4431 qemu_system_reset();
4432 resume_all_vcpus();
4434 if (qemu_powerdown_requested())
4435 qemu_system_powerdown();
4436 if ((r = qemu_vmstop_requested()))
4437 vm_stop(r);
4439 pause_all_vcpus();
4442 static void version(void)
4444 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4447 static void help(int exitcode)
4449 version();
4450 printf("usage: %s [options] [disk_image]\n"
4451 "\n"
4452 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4453 "\n"
4454 #define DEF(option, opt_arg, opt_enum, opt_help) \
4455 opt_help
4456 #define DEFHEADING(text) stringify(text) "\n"
4457 #include "qemu-options.h"
4458 #undef DEF
4459 #undef DEFHEADING
4460 #undef GEN_DOCS
4461 "\n"
4462 "During emulation, the following keys are useful:\n"
4463 "ctrl-alt-f toggle full screen\n"
4464 "ctrl-alt-n switch to virtual console 'n'\n"
4465 "ctrl-alt toggle mouse and keyboard grab\n"
4466 "\n"
4467 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4469 "qemu",
4470 DEFAULT_RAM_SIZE,
4471 #ifndef _WIN32
4472 DEFAULT_NETWORK_SCRIPT,
4473 DEFAULT_NETWORK_DOWN_SCRIPT,
4474 #endif
4475 DEFAULT_GDBSTUB_PORT,
4476 "/tmp/qemu.log");
4477 exit(exitcode);
4480 #define HAS_ARG 0x0001
4482 enum {
4483 #define DEF(option, opt_arg, opt_enum, opt_help) \
4484 opt_enum,
4485 #define DEFHEADING(text)
4486 #include "qemu-options.h"
4487 #undef DEF
4488 #undef DEFHEADING
4489 #undef GEN_DOCS
4492 typedef struct QEMUOption {
4493 const char *name;
4494 int flags;
4495 int index;
4496 } QEMUOption;
4498 static const QEMUOption qemu_options[] = {
4499 { "h", 0, QEMU_OPTION_h },
4500 #define DEF(option, opt_arg, opt_enum, opt_help) \
4501 { option, opt_arg, opt_enum },
4502 #define DEFHEADING(text)
4503 #include "qemu-options.h"
4504 #undef DEF
4505 #undef DEFHEADING
4506 #undef GEN_DOCS
4507 { NULL },
4510 #ifdef HAS_AUDIO
4511 struct soundhw soundhw[] = {
4512 #ifdef HAS_AUDIO_CHOICE
4513 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4515 "pcspk",
4516 "PC speaker",
4519 { .init_isa = pcspk_audio_init }
4521 #endif
4523 #ifdef CONFIG_SB16
4525 "sb16",
4526 "Creative Sound Blaster 16",
4529 { .init_isa = SB16_init }
4531 #endif
4533 #ifdef CONFIG_CS4231A
4535 "cs4231a",
4536 "CS4231A",
4539 { .init_isa = cs4231a_init }
4541 #endif
4543 #ifdef CONFIG_ADLIB
4545 "adlib",
4546 #ifdef HAS_YMF262
4547 "Yamaha YMF262 (OPL3)",
4548 #else
4549 "Yamaha YM3812 (OPL2)",
4550 #endif
4553 { .init_isa = Adlib_init }
4555 #endif
4557 #ifdef CONFIG_GUS
4559 "gus",
4560 "Gravis Ultrasound GF1",
4563 { .init_isa = GUS_init }
4565 #endif
4567 #ifdef CONFIG_AC97
4569 "ac97",
4570 "Intel 82801AA AC97 Audio",
4573 { .init_pci = ac97_init }
4575 #endif
4577 #ifdef CONFIG_ES1370
4579 "es1370",
4580 "ENSONIQ AudioPCI ES1370",
4583 { .init_pci = es1370_init }
4585 #endif
4587 #endif /* HAS_AUDIO_CHOICE */
4589 { NULL, NULL, 0, 0, { NULL } }
4592 static void select_soundhw (const char *optarg)
4594 struct soundhw *c;
4596 if (*optarg == '?') {
4597 show_valid_cards:
4599 printf ("Valid sound card names (comma separated):\n");
4600 for (c = soundhw; c->name; ++c) {
4601 printf ("%-11s %s\n", c->name, c->descr);
4603 printf ("\n-soundhw all will enable all of the above\n");
4604 exit (*optarg != '?');
4606 else {
4607 size_t l;
4608 const char *p;
4609 char *e;
4610 int bad_card = 0;
4612 if (!strcmp (optarg, "all")) {
4613 for (c = soundhw; c->name; ++c) {
4614 c->enabled = 1;
4616 return;
4619 p = optarg;
4620 while (*p) {
4621 e = strchr (p, ',');
4622 l = !e ? strlen (p) : (size_t) (e - p);
4624 for (c = soundhw; c->name; ++c) {
4625 if (!strncmp (c->name, p, l)) {
4626 c->enabled = 1;
4627 break;
4631 if (!c->name) {
4632 if (l > 80) {
4633 fprintf (stderr,
4634 "Unknown sound card name (too big to show)\n");
4636 else {
4637 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4638 (int) l, p);
4640 bad_card = 1;
4642 p += l + (e != NULL);
4645 if (bad_card)
4646 goto show_valid_cards;
4649 #endif
4651 static void select_vgahw (const char *p)
4653 const char *opts;
4655 vga_interface_type = VGA_NONE;
4656 if (strstart(p, "std", &opts)) {
4657 vga_interface_type = VGA_STD;
4658 } else if (strstart(p, "cirrus", &opts)) {
4659 vga_interface_type = VGA_CIRRUS;
4660 } else if (strstart(p, "vmware", &opts)) {
4661 vga_interface_type = VGA_VMWARE;
4662 } else if (strstart(p, "xenfb", &opts)) {
4663 vga_interface_type = VGA_XENFB;
4664 } else if (!strstart(p, "none", &opts)) {
4665 invalid_vga:
4666 fprintf(stderr, "Unknown vga type: %s\n", p);
4667 exit(1);
4669 while (*opts) {
4670 const char *nextopt;
4672 if (strstart(opts, ",retrace=", &nextopt)) {
4673 opts = nextopt;
4674 if (strstart(opts, "dumb", &nextopt))
4675 vga_retrace_method = VGA_RETRACE_DUMB;
4676 else if (strstart(opts, "precise", &nextopt))
4677 vga_retrace_method = VGA_RETRACE_PRECISE;
4678 else goto invalid_vga;
4679 } else goto invalid_vga;
4680 opts = nextopt;
4684 #ifdef TARGET_I386
4685 static int balloon_parse(const char *arg)
4687 char buf[128];
4688 const char *p;
4690 if (!strcmp(arg, "none")) {
4691 virtio_balloon = 0;
4692 } else if (!strncmp(arg, "virtio", 6)) {
4693 virtio_balloon = 1;
4694 if (arg[6] == ',') {
4695 p = arg + 7;
4696 if (get_param_value(buf, sizeof(buf), "addr", p)) {
4697 virtio_balloon_devaddr = strdup(buf);
4700 } else {
4701 return -1;
4703 return 0;
4705 #endif
4707 #ifdef _WIN32
4708 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4710 exit(STATUS_CONTROL_C_EXIT);
4711 return TRUE;
4713 #endif
4715 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4717 int ret;
4719 if(strlen(str) != 36)
4720 return -1;
4722 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4723 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4724 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4726 if(ret != 16)
4727 return -1;
4729 #ifdef TARGET_I386
4730 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4731 #endif
4733 return 0;
4736 #define MAX_NET_CLIENTS 32
4738 #ifndef _WIN32
4740 static void termsig_handler(int signal)
4742 qemu_system_shutdown_request();
4745 static void sigchld_handler(int signal)
4747 waitpid(-1, NULL, WNOHANG);
4750 static void sighandler_setup(void)
4752 struct sigaction act;
4754 memset(&act, 0, sizeof(act));
4755 act.sa_handler = termsig_handler;
4756 sigaction(SIGINT, &act, NULL);
4757 sigaction(SIGHUP, &act, NULL);
4758 sigaction(SIGTERM, &act, NULL);
4760 act.sa_handler = sigchld_handler;
4761 act.sa_flags = SA_NOCLDSTOP;
4762 sigaction(SIGCHLD, &act, NULL);
4765 #endif
4767 #ifdef _WIN32
4768 /* Look for support files in the same directory as the executable. */
4769 static char *find_datadir(const char *argv0)
4771 char *p;
4772 char buf[MAX_PATH];
4773 DWORD len;
4775 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4776 if (len == 0) {
4777 return NULL;
4780 buf[len] = 0;
4781 p = buf + len - 1;
4782 while (p != buf && *p != '\\')
4783 p--;
4784 *p = 0;
4785 if (access(buf, R_OK) == 0) {
4786 return qemu_strdup(buf);
4788 return NULL;
4790 #else /* !_WIN32 */
4792 /* Find a likely location for support files using the location of the binary.
4793 For installed binaries this will be "$bindir/../share/qemu". When
4794 running from the build tree this will be "$bindir/../pc-bios". */
4795 #define SHARE_SUFFIX "/share/qemu"
4796 #define BUILD_SUFFIX "/pc-bios"
4797 static char *find_datadir(const char *argv0)
4799 char *dir;
4800 char *p = NULL;
4801 char *res;
4802 #ifdef PATH_MAX
4803 char buf[PATH_MAX];
4804 #endif
4805 size_t max_len;
4807 #if defined(__linux__)
4809 int len;
4810 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4811 if (len > 0) {
4812 buf[len] = 0;
4813 p = buf;
4816 #elif defined(__FreeBSD__)
4818 int len;
4819 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4820 if (len > 0) {
4821 buf[len] = 0;
4822 p = buf;
4825 #endif
4826 /* If we don't have any way of figuring out the actual executable
4827 location then try argv[0]. */
4828 if (!p) {
4829 #ifdef PATH_MAX
4830 p = buf;
4831 #endif
4832 p = realpath(argv0, p);
4833 if (!p) {
4834 return NULL;
4837 dir = dirname(p);
4838 dir = dirname(dir);
4840 max_len = strlen(dir) +
4841 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4842 res = qemu_mallocz(max_len);
4843 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4844 if (access(res, R_OK)) {
4845 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4846 if (access(res, R_OK)) {
4847 qemu_free(res);
4848 res = NULL;
4851 #ifndef PATH_MAX
4852 free(p);
4853 #endif
4854 return res;
4856 #undef SHARE_SUFFIX
4857 #undef BUILD_SUFFIX
4858 #endif
4860 char *qemu_find_file(int type, const char *name)
4862 int len;
4863 const char *subdir;
4864 char *buf;
4866 /* If name contains path separators then try it as a straight path. */
4867 if ((strchr(name, '/') || strchr(name, '\\'))
4868 && access(name, R_OK) == 0) {
4869 return strdup(name);
4871 switch (type) {
4872 case QEMU_FILE_TYPE_BIOS:
4873 subdir = "";
4874 break;
4875 case QEMU_FILE_TYPE_KEYMAP:
4876 subdir = "keymaps/";
4877 break;
4878 default:
4879 abort();
4881 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4882 buf = qemu_mallocz(len);
4883 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4884 if (access(buf, R_OK)) {
4885 qemu_free(buf);
4886 return NULL;
4888 return buf;
4891 int main(int argc, char **argv, char **envp)
4893 const char *gdbstub_dev = NULL;
4894 uint32_t boot_devices_bitmap = 0;
4895 int i;
4896 int snapshot, linux_boot, net_boot;
4897 const char *initrd_filename;
4898 const char *kernel_filename, *kernel_cmdline;
4899 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4900 DisplayState *ds;
4901 DisplayChangeListener *dcl;
4902 int cyls, heads, secs, translation;
4903 const char *net_clients[MAX_NET_CLIENTS];
4904 int nb_net_clients;
4905 const char *bt_opts[MAX_BT_CMDLINE];
4906 int nb_bt_opts;
4907 int hda_index;
4908 int optind;
4909 const char *r, *optarg;
4910 CharDriverState *monitor_hd = NULL;
4911 const char *monitor_device;
4912 const char *serial_devices[MAX_SERIAL_PORTS];
4913 int serial_device_index;
4914 const char *parallel_devices[MAX_PARALLEL_PORTS];
4915 int parallel_device_index;
4916 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4917 int virtio_console_index;
4918 const char *loadvm = NULL;
4919 QEMUMachine *machine;
4920 const char *cpu_model;
4921 const char *usb_devices[MAX_USB_CMDLINE];
4922 int usb_devices_index;
4923 #ifndef _WIN32
4924 int fds[2];
4925 #endif
4926 int tb_size;
4927 const char *pid_file = NULL;
4928 const char *incoming = NULL;
4929 #ifndef _WIN32
4930 int fd = 0;
4931 struct passwd *pwd = NULL;
4932 const char *chroot_dir = NULL;
4933 const char *run_as = NULL;
4934 #endif
4935 CPUState *env;
4936 int show_vnc_port = 0;
4938 qemu_cache_utils_init(envp);
4940 LIST_INIT (&vm_change_state_head);
4941 #ifndef _WIN32
4943 struct sigaction act;
4944 sigfillset(&act.sa_mask);
4945 act.sa_flags = 0;
4946 act.sa_handler = SIG_IGN;
4947 sigaction(SIGPIPE, &act, NULL);
4949 #else
4950 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4951 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4952 QEMU to run on a single CPU */
4954 HANDLE h;
4955 DWORD mask, smask;
4956 int i;
4957 h = GetCurrentProcess();
4958 if (GetProcessAffinityMask(h, &mask, &smask)) {
4959 for(i = 0; i < 32; i++) {
4960 if (mask & (1 << i))
4961 break;
4963 if (i != 32) {
4964 mask = 1 << i;
4965 SetProcessAffinityMask(h, mask);
4969 #endif
4971 module_call_init(MODULE_INIT_MACHINE);
4972 machine = find_default_machine();
4973 cpu_model = NULL;
4974 initrd_filename = NULL;
4975 ram_size = 0;
4976 snapshot = 0;
4977 kernel_filename = NULL;
4978 kernel_cmdline = "";
4979 cyls = heads = secs = 0;
4980 translation = BIOS_ATA_TRANSLATION_AUTO;
4981 monitor_device = "vc:80Cx24C";
4983 serial_devices[0] = "vc:80Cx24C";
4984 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4985 serial_devices[i] = NULL;
4986 serial_device_index = 0;
4988 parallel_devices[0] = "vc:80Cx24C";
4989 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4990 parallel_devices[i] = NULL;
4991 parallel_device_index = 0;
4993 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4994 virtio_consoles[i] = NULL;
4995 virtio_console_index = 0;
4997 for (i = 0; i < MAX_NODES; i++) {
4998 node_mem[i] = 0;
4999 node_cpumask[i] = 0;
5002 usb_devices_index = 0;
5003 assigned_devices_index = 0;
5005 nb_net_clients = 0;
5006 nb_bt_opts = 0;
5007 nb_drives = 0;
5008 nb_drives_opt = 0;
5009 nb_numa_nodes = 0;
5010 hda_index = -1;
5012 nb_nics = 0;
5014 tb_size = 0;
5015 autostart= 1;
5017 register_watchdogs();
5019 optind = 1;
5020 for(;;) {
5021 if (optind >= argc)
5022 break;
5023 r = argv[optind];
5024 if (r[0] != '-') {
5025 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5026 } else {
5027 const QEMUOption *popt;
5029 optind++;
5030 /* Treat --foo the same as -foo. */
5031 if (r[1] == '-')
5032 r++;
5033 popt = qemu_options;
5034 for(;;) {
5035 if (!popt->name) {
5036 fprintf(stderr, "%s: invalid option -- '%s'\n",
5037 argv[0], r);
5038 exit(1);
5040 if (!strcmp(popt->name, r + 1))
5041 break;
5042 popt++;
5044 if (popt->flags & HAS_ARG) {
5045 if (optind >= argc) {
5046 fprintf(stderr, "%s: option '%s' requires an argument\n",
5047 argv[0], r);
5048 exit(1);
5050 optarg = argv[optind++];
5051 } else {
5052 optarg = NULL;
5055 switch(popt->index) {
5056 case QEMU_OPTION_M:
5057 machine = find_machine(optarg);
5058 if (!machine) {
5059 QEMUMachine *m;
5060 printf("Supported machines are:\n");
5061 for(m = first_machine; m != NULL; m = m->next) {
5062 if (m->alias)
5063 printf("%-10s %s (alias of %s)\n",
5064 m->alias, m->desc, m->name);
5065 printf("%-10s %s%s\n",
5066 m->name, m->desc,
5067 m->is_default ? " (default)" : "");
5069 exit(*optarg != '?');
5071 break;
5072 case QEMU_OPTION_cpu:
5073 /* hw initialization will check this */
5074 if (*optarg == '?') {
5075 /* XXX: implement xxx_cpu_list for targets that still miss it */
5076 #if defined(cpu_list)
5077 cpu_list(stdout, &fprintf);
5078 #endif
5079 exit(0);
5080 } else {
5081 cpu_model = optarg;
5083 break;
5084 case QEMU_OPTION_initrd:
5085 initrd_filename = optarg;
5086 break;
5087 case QEMU_OPTION_hda:
5088 if (cyls == 0)
5089 hda_index = drive_add(optarg, HD_ALIAS, 0);
5090 else
5091 hda_index = drive_add(optarg, HD_ALIAS
5092 ",cyls=%d,heads=%d,secs=%d%s",
5093 0, cyls, heads, secs,
5094 translation == BIOS_ATA_TRANSLATION_LBA ?
5095 ",trans=lba" :
5096 translation == BIOS_ATA_TRANSLATION_NONE ?
5097 ",trans=none" : "");
5098 break;
5099 case QEMU_OPTION_hdb:
5100 case QEMU_OPTION_hdc:
5101 case QEMU_OPTION_hdd:
5102 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5103 break;
5104 case QEMU_OPTION_drive:
5105 drive_add(NULL, "%s", optarg);
5106 break;
5107 case QEMU_OPTION_mtdblock:
5108 drive_add(optarg, MTD_ALIAS);
5109 break;
5110 case QEMU_OPTION_sd:
5111 drive_add(optarg, SD_ALIAS);
5112 break;
5113 case QEMU_OPTION_pflash:
5114 drive_add(optarg, PFLASH_ALIAS);
5115 break;
5116 case QEMU_OPTION_snapshot:
5117 snapshot = 1;
5118 break;
5119 case QEMU_OPTION_hdachs:
5121 const char *p;
5122 p = optarg;
5123 cyls = strtol(p, (char **)&p, 0);
5124 if (cyls < 1 || cyls > 16383)
5125 goto chs_fail;
5126 if (*p != ',')
5127 goto chs_fail;
5128 p++;
5129 heads = strtol(p, (char **)&p, 0);
5130 if (heads < 1 || heads > 16)
5131 goto chs_fail;
5132 if (*p != ',')
5133 goto chs_fail;
5134 p++;
5135 secs = strtol(p, (char **)&p, 0);
5136 if (secs < 1 || secs > 63)
5137 goto chs_fail;
5138 if (*p == ',') {
5139 p++;
5140 if (!strcmp(p, "none"))
5141 translation = BIOS_ATA_TRANSLATION_NONE;
5142 else if (!strcmp(p, "lba"))
5143 translation = BIOS_ATA_TRANSLATION_LBA;
5144 else if (!strcmp(p, "auto"))
5145 translation = BIOS_ATA_TRANSLATION_AUTO;
5146 else
5147 goto chs_fail;
5148 } else if (*p != '\0') {
5149 chs_fail:
5150 fprintf(stderr, "qemu: invalid physical CHS format\n");
5151 exit(1);
5153 if (hda_index != -1)
5154 snprintf(drives_opt[hda_index].opt,
5155 sizeof(drives_opt[hda_index].opt),
5156 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5157 0, cyls, heads, secs,
5158 translation == BIOS_ATA_TRANSLATION_LBA ?
5159 ",trans=lba" :
5160 translation == BIOS_ATA_TRANSLATION_NONE ?
5161 ",trans=none" : "");
5163 break;
5164 case QEMU_OPTION_numa:
5165 if (nb_numa_nodes >= MAX_NODES) {
5166 fprintf(stderr, "qemu: too many NUMA nodes\n");
5167 exit(1);
5169 numa_add(optarg);
5170 break;
5171 case QEMU_OPTION_nographic:
5172 display_type = DT_NOGRAPHIC;
5173 break;
5174 #ifdef CONFIG_CURSES
5175 case QEMU_OPTION_curses:
5176 display_type = DT_CURSES;
5177 break;
5178 #endif
5179 case QEMU_OPTION_portrait:
5180 graphic_rotate = 1;
5181 break;
5182 case QEMU_OPTION_kernel:
5183 kernel_filename = optarg;
5184 break;
5185 case QEMU_OPTION_append:
5186 kernel_cmdline = optarg;
5187 break;
5188 case QEMU_OPTION_cdrom:
5189 drive_add(optarg, CDROM_ALIAS);
5190 break;
5191 case QEMU_OPTION_boot:
5193 static const char * const params[] = {
5194 "order", "once", "menu", NULL
5196 char buf[sizeof(boot_devices)];
5197 char *standard_boot_devices;
5198 int legacy = 0;
5200 if (!strchr(optarg, '=')) {
5201 legacy = 1;
5202 pstrcpy(buf, sizeof(buf), optarg);
5203 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5204 fprintf(stderr,
5205 "qemu: unknown boot parameter '%s' in '%s'\n",
5206 buf, optarg);
5207 exit(1);
5210 if (legacy ||
5211 get_param_value(buf, sizeof(buf), "order", optarg)) {
5212 boot_devices_bitmap = parse_bootdevices(buf);
5213 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5215 if (!legacy) {
5216 if (get_param_value(buf, sizeof(buf),
5217 "once", optarg)) {
5218 boot_devices_bitmap |= parse_bootdevices(buf);
5219 standard_boot_devices = qemu_strdup(boot_devices);
5220 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5221 qemu_register_reset(restore_boot_devices,
5222 standard_boot_devices);
5224 if (get_param_value(buf, sizeof(buf),
5225 "menu", optarg)) {
5226 if (!strcmp(buf, "on")) {
5227 boot_menu = 1;
5228 } else if (!strcmp(buf, "off")) {
5229 boot_menu = 0;
5230 } else {
5231 fprintf(stderr,
5232 "qemu: invalid option value '%s'\n",
5233 buf);
5234 exit(1);
5239 break;
5240 case QEMU_OPTION_fda:
5241 case QEMU_OPTION_fdb:
5242 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5243 break;
5244 #ifdef TARGET_I386
5245 case QEMU_OPTION_no_fd_bootchk:
5246 fd_bootchk = 0;
5247 break;
5248 #endif
5249 case QEMU_OPTION_net:
5250 if (nb_net_clients >= MAX_NET_CLIENTS) {
5251 fprintf(stderr, "qemu: too many network clients\n");
5252 exit(1);
5254 net_clients[nb_net_clients] = optarg;
5255 nb_net_clients++;
5256 break;
5257 #ifdef CONFIG_SLIRP
5258 case QEMU_OPTION_tftp:
5259 legacy_tftp_prefix = optarg;
5260 break;
5261 case QEMU_OPTION_bootp:
5262 legacy_bootp_filename = optarg;
5263 break;
5264 #ifndef _WIN32
5265 case QEMU_OPTION_smb:
5266 net_slirp_smb(optarg);
5267 break;
5268 #endif
5269 case QEMU_OPTION_redir:
5270 net_slirp_redir(optarg);
5271 break;
5272 #endif
5273 case QEMU_OPTION_bt:
5274 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5275 fprintf(stderr, "qemu: too many bluetooth options\n");
5276 exit(1);
5278 bt_opts[nb_bt_opts++] = optarg;
5279 break;
5280 #ifdef HAS_AUDIO
5281 case QEMU_OPTION_audio_help:
5282 AUD_help ();
5283 exit (0);
5284 break;
5285 case QEMU_OPTION_soundhw:
5286 select_soundhw (optarg);
5287 break;
5288 #endif
5289 case QEMU_OPTION_h:
5290 help(0);
5291 break;
5292 case QEMU_OPTION_version:
5293 version();
5294 exit(0);
5295 break;
5296 case QEMU_OPTION_m: {
5297 uint64_t value;
5298 char *ptr;
5300 value = strtoul(optarg, &ptr, 10);
5301 switch (*ptr) {
5302 case 0: case 'M': case 'm':
5303 value <<= 20;
5304 break;
5305 case 'G': case 'g':
5306 value <<= 30;
5307 break;
5308 default:
5309 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5310 exit(1);
5313 /* On 32-bit hosts, QEMU is limited by virtual address space */
5314 if (value > (2047 << 20)
5315 #ifndef CONFIG_KQEMU
5316 && HOST_LONG_BITS == 32
5317 #endif
5319 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5320 exit(1);
5322 if (value != (uint64_t)(ram_addr_t)value) {
5323 fprintf(stderr, "qemu: ram size too large\n");
5324 exit(1);
5326 ram_size = value;
5327 break;
5329 case QEMU_OPTION_d:
5331 int mask;
5332 const CPULogItem *item;
5334 mask = cpu_str_to_log_mask(optarg);
5335 if (!mask) {
5336 printf("Log items (comma separated):\n");
5337 for(item = cpu_log_items; item->mask != 0; item++) {
5338 printf("%-10s %s\n", item->name, item->help);
5340 exit(1);
5342 cpu_set_log(mask);
5344 break;
5345 case QEMU_OPTION_s:
5346 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5347 break;
5348 case QEMU_OPTION_gdb:
5349 gdbstub_dev = optarg;
5350 break;
5351 case QEMU_OPTION_L:
5352 data_dir = optarg;
5353 break;
5354 case QEMU_OPTION_bios:
5355 bios_name = optarg;
5356 break;
5357 case QEMU_OPTION_singlestep:
5358 singlestep = 1;
5359 break;
5360 case QEMU_OPTION_S:
5361 autostart = 0;
5362 break;
5363 #ifndef _WIN32
5364 case QEMU_OPTION_k:
5365 keyboard_layout = optarg;
5366 break;
5367 #endif
5368 case QEMU_OPTION_localtime:
5369 rtc_utc = 0;
5370 break;
5371 case QEMU_OPTION_vga:
5372 select_vgahw (optarg);
5373 break;
5374 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5375 case QEMU_OPTION_g:
5377 const char *p;
5378 int w, h, depth;
5379 p = optarg;
5380 w = strtol(p, (char **)&p, 10);
5381 if (w <= 0) {
5382 graphic_error:
5383 fprintf(stderr, "qemu: invalid resolution or depth\n");
5384 exit(1);
5386 if (*p != 'x')
5387 goto graphic_error;
5388 p++;
5389 h = strtol(p, (char **)&p, 10);
5390 if (h <= 0)
5391 goto graphic_error;
5392 if (*p == 'x') {
5393 p++;
5394 depth = strtol(p, (char **)&p, 10);
5395 if (depth != 8 && depth != 15 && depth != 16 &&
5396 depth != 24 && depth != 32)
5397 goto graphic_error;
5398 } else if (*p == '\0') {
5399 depth = graphic_depth;
5400 } else {
5401 goto graphic_error;
5404 graphic_width = w;
5405 graphic_height = h;
5406 graphic_depth = depth;
5408 break;
5409 #endif
5410 case QEMU_OPTION_echr:
5412 char *r;
5413 term_escape_char = strtol(optarg, &r, 0);
5414 if (r == optarg)
5415 printf("Bad argument to echr\n");
5416 break;
5418 case QEMU_OPTION_monitor:
5419 monitor_device = optarg;
5420 break;
5421 case QEMU_OPTION_serial:
5422 if (serial_device_index >= MAX_SERIAL_PORTS) {
5423 fprintf(stderr, "qemu: too many serial ports\n");
5424 exit(1);
5426 serial_devices[serial_device_index] = optarg;
5427 serial_device_index++;
5428 break;
5429 case QEMU_OPTION_watchdog:
5430 i = select_watchdog(optarg);
5431 if (i > 0)
5432 exit (i == 1 ? 1 : 0);
5433 break;
5434 case QEMU_OPTION_watchdog_action:
5435 if (select_watchdog_action(optarg) == -1) {
5436 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5437 exit(1);
5439 break;
5440 case QEMU_OPTION_virtiocon:
5441 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5442 fprintf(stderr, "qemu: too many virtio consoles\n");
5443 exit(1);
5445 virtio_consoles[virtio_console_index] = optarg;
5446 virtio_console_index++;
5447 break;
5448 case QEMU_OPTION_parallel:
5449 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5450 fprintf(stderr, "qemu: too many parallel ports\n");
5451 exit(1);
5453 parallel_devices[parallel_device_index] = optarg;
5454 parallel_device_index++;
5455 break;
5456 case QEMU_OPTION_loadvm:
5457 loadvm = optarg;
5458 break;
5459 case QEMU_OPTION_full_screen:
5460 full_screen = 1;
5461 break;
5462 #ifdef CONFIG_SDL
5463 case QEMU_OPTION_no_frame:
5464 no_frame = 1;
5465 break;
5466 case QEMU_OPTION_alt_grab:
5467 alt_grab = 1;
5468 break;
5469 case QEMU_OPTION_no_quit:
5470 no_quit = 1;
5471 break;
5472 case QEMU_OPTION_sdl:
5473 display_type = DT_SDL;
5474 break;
5475 #endif
5476 case QEMU_OPTION_pidfile:
5477 pid_file = optarg;
5478 break;
5479 #ifdef TARGET_I386
5480 case QEMU_OPTION_win2k_hack:
5481 win2k_install_hack = 1;
5482 break;
5483 case QEMU_OPTION_rtc_td_hack:
5484 rtc_td_hack = 1;
5485 break;
5486 case QEMU_OPTION_acpitable:
5487 if(acpi_table_add(optarg) < 0) {
5488 fprintf(stderr, "Wrong acpi table provided\n");
5489 exit(1);
5491 break;
5492 case QEMU_OPTION_smbios:
5493 if(smbios_entry_add(optarg) < 0) {
5494 fprintf(stderr, "Wrong smbios provided\n");
5495 exit(1);
5497 break;
5498 #endif
5499 #ifdef CONFIG_KQEMU
5500 case QEMU_OPTION_enable_kqemu:
5501 kqemu_allowed = 1;
5502 break;
5503 case QEMU_OPTION_kernel_kqemu:
5504 kqemu_allowed = 2;
5505 break;
5506 #endif
5507 #ifdef CONFIG_KVM
5508 #ifdef KVM_UPSTREAM
5509 case QEMU_OPTION_enable_kvm:
5510 kvm_allowed = 1;
5511 #ifdef CONFIG_KQEMU
5512 kqemu_allowed = 0;
5513 #endif
5514 #endif
5515 break;
5516 case QEMU_OPTION_no_kvm:
5517 kvm_allowed = 0;
5518 break;
5519 case QEMU_OPTION_no_kvm_irqchip: {
5520 kvm_irqchip = 0;
5521 kvm_pit = 0;
5522 break;
5524 case QEMU_OPTION_no_kvm_pit: {
5525 kvm_pit = 0;
5526 break;
5528 case QEMU_OPTION_no_kvm_pit_reinjection: {
5529 kvm_pit_reinject = 0;
5530 break;
5532 case QEMU_OPTION_enable_nesting: {
5533 kvm_nested = 1;
5534 break;
5536 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5537 case QEMU_OPTION_pcidevice:
5538 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5539 fprintf(stderr, "Too many assigned devices\n");
5540 exit(1);
5542 assigned_devices[assigned_devices_index] = optarg;
5543 assigned_devices_index++;
5544 break;
5545 #endif
5546 #endif
5547 case QEMU_OPTION_usb:
5548 usb_enabled = 1;
5549 break;
5550 case QEMU_OPTION_usbdevice:
5551 usb_enabled = 1;
5552 if (usb_devices_index >= MAX_USB_CMDLINE) {
5553 fprintf(stderr, "Too many USB devices\n");
5554 exit(1);
5556 usb_devices[usb_devices_index] = optarg;
5557 usb_devices_index++;
5558 break;
5559 case QEMU_OPTION_smp:
5560 smp_cpus = atoi(optarg);
5561 if (smp_cpus < 1) {
5562 fprintf(stderr, "Invalid number of CPUs\n");
5563 exit(1);
5565 break;
5566 case QEMU_OPTION_vnc:
5567 display_type = DT_VNC;
5568 vnc_display = optarg;
5569 break;
5570 #ifdef TARGET_I386
5571 case QEMU_OPTION_no_acpi:
5572 acpi_enabled = 0;
5573 break;
5574 case QEMU_OPTION_no_hpet:
5575 no_hpet = 1;
5576 break;
5577 case QEMU_OPTION_balloon:
5578 if (balloon_parse(optarg) < 0) {
5579 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5580 exit(1);
5582 break;
5583 #endif
5584 case QEMU_OPTION_no_reboot:
5585 no_reboot = 1;
5586 break;
5587 case QEMU_OPTION_no_shutdown:
5588 no_shutdown = 1;
5589 break;
5590 case QEMU_OPTION_show_cursor:
5591 cursor_hide = 0;
5592 break;
5593 case QEMU_OPTION_uuid:
5594 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5595 fprintf(stderr, "Fail to parse UUID string."
5596 " Wrong format.\n");
5597 exit(1);
5599 break;
5600 #ifndef _WIN32
5601 case QEMU_OPTION_daemonize:
5602 daemonize = 1;
5603 break;
5604 #endif
5605 case QEMU_OPTION_option_rom:
5606 if (nb_option_roms >= MAX_OPTION_ROMS) {
5607 fprintf(stderr, "Too many option ROMs\n");
5608 exit(1);
5610 option_rom[nb_option_roms] = optarg;
5611 nb_option_roms++;
5612 break;
5613 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5614 case QEMU_OPTION_semihosting:
5615 semihosting_enabled = 1;
5616 break;
5617 #endif
5618 case QEMU_OPTION_tdf:
5619 time_drift_fix = 1;
5620 break;
5621 case QEMU_OPTION_kvm_shadow_memory:
5622 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5623 break;
5624 case QEMU_OPTION_mempath:
5625 mem_path = optarg;
5626 break;
5627 #ifdef MAP_POPULATE
5628 case QEMU_OPTION_mem_prealloc:
5629 mem_prealloc = !mem_prealloc;
5630 break;
5631 #endif
5632 case QEMU_OPTION_name:
5633 qemu_name = qemu_strdup(optarg);
5635 char *p = strchr(qemu_name, ',');
5636 if (p != NULL) {
5637 *p++ = 0;
5638 if (strncmp(p, "process=", 8)) {
5639 fprintf(stderr, "Unknown subargument %s to -name", p);
5640 exit(1);
5642 p += 8;
5643 set_proc_name(p);
5646 break;
5647 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5648 case QEMU_OPTION_prom_env:
5649 if (nb_prom_envs >= MAX_PROM_ENVS) {
5650 fprintf(stderr, "Too many prom variables\n");
5651 exit(1);
5653 prom_envs[nb_prom_envs] = optarg;
5654 nb_prom_envs++;
5655 break;
5656 #endif
5657 #ifdef TARGET_ARM
5658 case QEMU_OPTION_old_param:
5659 old_param = 1;
5660 break;
5661 #endif
5662 case QEMU_OPTION_clock:
5663 configure_alarms(optarg);
5664 break;
5665 case QEMU_OPTION_startdate:
5667 struct tm tm;
5668 time_t rtc_start_date;
5669 if (!strcmp(optarg, "now")) {
5670 rtc_date_offset = -1;
5671 } else {
5672 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5673 &tm.tm_year,
5674 &tm.tm_mon,
5675 &tm.tm_mday,
5676 &tm.tm_hour,
5677 &tm.tm_min,
5678 &tm.tm_sec) == 6) {
5679 /* OK */
5680 } else if (sscanf(optarg, "%d-%d-%d",
5681 &tm.tm_year,
5682 &tm.tm_mon,
5683 &tm.tm_mday) == 3) {
5684 tm.tm_hour = 0;
5685 tm.tm_min = 0;
5686 tm.tm_sec = 0;
5687 } else {
5688 goto date_fail;
5690 tm.tm_year -= 1900;
5691 tm.tm_mon--;
5692 rtc_start_date = mktimegm(&tm);
5693 if (rtc_start_date == -1) {
5694 date_fail:
5695 fprintf(stderr, "Invalid date format. Valid format are:\n"
5696 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5697 exit(1);
5699 rtc_date_offset = time(NULL) - rtc_start_date;
5702 break;
5703 case QEMU_OPTION_tb_size:
5704 tb_size = strtol(optarg, NULL, 0);
5705 if (tb_size < 0)
5706 tb_size = 0;
5707 break;
5708 case QEMU_OPTION_icount:
5709 use_icount = 1;
5710 if (strcmp(optarg, "auto") == 0) {
5711 icount_time_shift = -1;
5712 } else {
5713 icount_time_shift = strtol(optarg, NULL, 0);
5715 break;
5716 case QEMU_OPTION_incoming:
5717 incoming = optarg;
5718 break;
5719 #ifndef _WIN32
5720 case QEMU_OPTION_chroot:
5721 chroot_dir = optarg;
5722 break;
5723 case QEMU_OPTION_runas:
5724 run_as = optarg;
5725 break;
5726 case QEMU_OPTION_nvram:
5727 nvram = optarg;
5728 break;
5729 #endif
5730 #ifdef CONFIG_XEN
5731 case QEMU_OPTION_xen_domid:
5732 xen_domid = atoi(optarg);
5733 break;
5734 case QEMU_OPTION_xen_create:
5735 xen_mode = XEN_CREATE;
5736 break;
5737 case QEMU_OPTION_xen_attach:
5738 xen_mode = XEN_ATTACH;
5739 break;
5740 #endif
5745 /* If no data_dir is specified then try to find it relative to the
5746 executable path. */
5747 if (!data_dir) {
5748 data_dir = find_datadir(argv[0]);
5750 /* If all else fails use the install patch specified when building. */
5751 if (!data_dir) {
5752 data_dir = CONFIG_QEMU_SHAREDIR;
5755 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5756 if (kvm_allowed && kqemu_allowed) {
5757 fprintf(stderr,
5758 "You can not enable both KVM and kqemu at the same time\n");
5759 exit(1);
5761 #endif
5763 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5764 if (smp_cpus > machine->max_cpus) {
5765 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5766 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5767 machine->max_cpus);
5768 exit(1);
5771 if (display_type == DT_NOGRAPHIC) {
5772 if (serial_device_index == 0)
5773 serial_devices[0] = "stdio";
5774 if (parallel_device_index == 0)
5775 parallel_devices[0] = "null";
5776 if (strncmp(monitor_device, "vc", 2) == 0)
5777 monitor_device = "stdio";
5780 #ifndef _WIN32
5781 if (daemonize) {
5782 pid_t pid;
5784 if (pipe(fds) == -1)
5785 exit(1);
5787 pid = fork();
5788 if (pid > 0) {
5789 uint8_t status;
5790 ssize_t len;
5792 close(fds[1]);
5794 again:
5795 len = read(fds[0], &status, 1);
5796 if (len == -1 && (errno == EINTR))
5797 goto again;
5799 if (len != 1)
5800 exit(1);
5801 else if (status == 1) {
5802 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5803 exit(1);
5804 } else
5805 exit(0);
5806 } else if (pid < 0)
5807 exit(1);
5809 setsid();
5811 pid = fork();
5812 if (pid > 0)
5813 exit(0);
5814 else if (pid < 0)
5815 exit(1);
5817 umask(027);
5819 signal(SIGTSTP, SIG_IGN);
5820 signal(SIGTTOU, SIG_IGN);
5821 signal(SIGTTIN, SIG_IGN);
5824 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5825 if (daemonize) {
5826 uint8_t status = 1;
5827 write(fds[1], &status, 1);
5828 } else
5829 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5830 exit(1);
5832 #endif
5834 if (kvm_enabled()) {
5835 int ret;
5837 ret = kvm_init(smp_cpus);
5838 if (ret < 0) {
5839 #if defined(KVM_UPSTREAM) || defined(NO_CPU_EMULATION)
5840 fprintf(stderr, "failed to initialize KVM\n");
5841 exit(1);
5842 #endif
5843 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5844 kvm_allowed = 0;
5848 #ifdef CONFIG_KQEMU
5849 if (smp_cpus > 1)
5850 kqemu_allowed = 0;
5851 #endif
5852 if (qemu_init_main_loop()) {
5853 fprintf(stderr, "qemu_init_main_loop failed\n");
5854 exit(1);
5856 linux_boot = (kernel_filename != NULL);
5858 if (!linux_boot && *kernel_cmdline != '\0') {
5859 fprintf(stderr, "-append only allowed with -kernel option\n");
5860 exit(1);
5863 if (!linux_boot && initrd_filename != NULL) {
5864 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5865 exit(1);
5868 setvbuf(stdout, NULL, _IOLBF, 0);
5870 init_timers();
5871 if (init_timer_alarm() < 0) {
5872 fprintf(stderr, "could not initialize alarm timer\n");
5873 exit(1);
5875 if (use_icount && icount_time_shift < 0) {
5876 use_icount = 2;
5877 /* 125MIPS seems a reasonable initial guess at the guest speed.
5878 It will be corrected fairly quickly anyway. */
5879 icount_time_shift = 3;
5880 init_icount_adjust();
5883 #ifdef _WIN32
5884 socket_init();
5885 #endif
5887 /* init network clients */
5888 if (nb_net_clients == 0) {
5889 /* if no clients, we use a default config */
5890 net_clients[nb_net_clients++] = "nic";
5891 #ifdef CONFIG_SLIRP
5892 net_clients[nb_net_clients++] = "user";
5893 #endif
5896 for(i = 0;i < nb_net_clients; i++) {
5897 if (net_client_parse(net_clients[i]) < 0)
5898 exit(1);
5901 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5902 net_set_boot_mask(net_boot);
5904 net_client_check();
5906 /* init the bluetooth world */
5907 for (i = 0; i < nb_bt_opts; i++)
5908 if (bt_parse(bt_opts[i]))
5909 exit(1);
5911 /* init the memory */
5912 if (ram_size == 0)
5913 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5915 #ifdef CONFIG_KQEMU
5916 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5917 guest ram allocation. It needs to go away. */
5918 if (kqemu_allowed) {
5919 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
5920 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5921 if (!kqemu_phys_ram_base) {
5922 fprintf(stderr, "Could not allocate physical memory\n");
5923 exit(1);
5926 #endif
5928 /* init the dynamic translator */
5929 cpu_exec_init_all(tb_size * 1024 * 1024);
5931 bdrv_init();
5933 /* we always create the cdrom drive, even if no disk is there */
5935 if (nb_drives_opt < MAX_DRIVES)
5936 drive_add(NULL, CDROM_ALIAS);
5938 /* we always create at least one floppy */
5940 if (nb_drives_opt < MAX_DRIVES)
5941 drive_add(NULL, FD_ALIAS, 0);
5943 /* we always create one sd slot, even if no card is in it */
5945 if (nb_drives_opt < MAX_DRIVES)
5946 drive_add(NULL, SD_ALIAS);
5948 /* open the virtual block devices */
5950 for(i = 0; i < nb_drives_opt; i++)
5951 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5952 exit(1);
5954 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5955 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5957 #ifndef _WIN32
5958 /* must be after terminal init, SDL library changes signal handlers */
5959 sighandler_setup();
5960 #endif
5962 /* Maintain compatibility with multiple stdio monitors */
5963 if (!strcmp(monitor_device,"stdio")) {
5964 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5965 const char *devname = serial_devices[i];
5966 if (devname && !strcmp(devname,"mon:stdio")) {
5967 monitor_device = NULL;
5968 break;
5969 } else if (devname && !strcmp(devname,"stdio")) {
5970 monitor_device = NULL;
5971 serial_devices[i] = "mon:stdio";
5972 break;
5977 if (nb_numa_nodes > 0) {
5978 int i;
5980 if (nb_numa_nodes > smp_cpus) {
5981 nb_numa_nodes = smp_cpus;
5984 /* If no memory size if given for any node, assume the default case
5985 * and distribute the available memory equally across all nodes
5987 for (i = 0; i < nb_numa_nodes; i++) {
5988 if (node_mem[i] != 0)
5989 break;
5991 if (i == nb_numa_nodes) {
5992 uint64_t usedmem = 0;
5994 /* On Linux, the each node's border has to be 8MB aligned,
5995 * the final node gets the rest.
5997 for (i = 0; i < nb_numa_nodes - 1; i++) {
5998 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5999 usedmem += node_mem[i];
6001 node_mem[i] = ram_size - usedmem;
6004 for (i = 0; i < nb_numa_nodes; i++) {
6005 if (node_cpumask[i] != 0)
6006 break;
6008 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6009 * must cope with this anyway, because there are BIOSes out there in
6010 * real machines which also use this scheme.
6012 if (i == nb_numa_nodes) {
6013 for (i = 0; i < smp_cpus; i++) {
6014 node_cpumask[i % nb_numa_nodes] |= 1 << i;
6019 if (monitor_device) {
6020 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
6021 if (!monitor_hd) {
6022 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6023 exit(1);
6027 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6028 const char *devname = serial_devices[i];
6029 if (devname && strcmp(devname, "none")) {
6030 char label[32];
6031 snprintf(label, sizeof(label), "serial%d", i);
6032 serial_hds[i] = qemu_chr_open(label, devname, NULL);
6033 if (!serial_hds[i]) {
6034 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
6035 devname, strerror(errno));
6036 exit(1);
6041 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6042 const char *devname = parallel_devices[i];
6043 if (devname && strcmp(devname, "none")) {
6044 char label[32];
6045 snprintf(label, sizeof(label), "parallel%d", i);
6046 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
6047 if (!parallel_hds[i]) {
6048 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
6049 devname, strerror(errno));
6050 exit(1);
6055 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6056 const char *devname = virtio_consoles[i];
6057 if (devname && strcmp(devname, "none")) {
6058 char label[32];
6059 snprintf(label, sizeof(label), "virtcon%d", i);
6060 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
6061 if (!virtcon_hds[i]) {
6062 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
6063 devname, strerror(errno));
6064 exit(1);
6069 module_call_init(MODULE_INIT_DEVICE);
6071 if (machine->compat_props) {
6072 qdev_prop_register_compat(machine->compat_props);
6074 machine->init(ram_size, boot_devices,
6075 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6078 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6079 for (i = 0; i < nb_numa_nodes; i++) {
6080 if (node_cpumask[i] & (1 << env->cpu_index)) {
6081 env->numa_node = i;
6086 current_machine = machine;
6088 /* init USB devices */
6089 if (usb_enabled) {
6090 for(i = 0; i < usb_devices_index; i++) {
6091 if (usb_device_add(usb_devices[i], 0) < 0) {
6092 fprintf(stderr, "Warning: could not add USB device %s\n",
6093 usb_devices[i]);
6098 if (!display_state)
6099 dumb_display_init();
6100 /* just use the first displaystate for the moment */
6101 ds = display_state;
6103 if (display_type == DT_DEFAULT) {
6104 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6105 display_type = DT_SDL;
6106 #else
6107 display_type = DT_VNC;
6108 vnc_display = "localhost:0,to=99";
6109 show_vnc_port = 1;
6110 #endif
6114 switch (display_type) {
6115 case DT_NOGRAPHIC:
6116 break;
6117 #if defined(CONFIG_CURSES)
6118 case DT_CURSES:
6119 curses_display_init(ds, full_screen);
6120 break;
6121 #endif
6122 #if defined(CONFIG_SDL)
6123 case DT_SDL:
6124 sdl_display_init(ds, full_screen, no_frame);
6125 break;
6126 #elif defined(CONFIG_COCOA)
6127 case DT_SDL:
6128 cocoa_display_init(ds, full_screen);
6129 break;
6130 #endif
6131 case DT_VNC:
6132 vnc_display_init(ds);
6133 if (vnc_display_open(ds, vnc_display) < 0)
6134 exit(1);
6136 if (show_vnc_port) {
6137 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6139 break;
6140 default:
6141 break;
6143 dpy_resize(ds);
6145 dcl = ds->listeners;
6146 while (dcl != NULL) {
6147 if (dcl->dpy_refresh != NULL) {
6148 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6149 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6151 dcl = dcl->next;
6154 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6155 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6156 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6159 text_consoles_set_display(display_state);
6160 qemu_chr_initial_reset();
6162 if (monitor_device && monitor_hd)
6163 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6165 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6166 const char *devname = serial_devices[i];
6167 if (devname && strcmp(devname, "none")) {
6168 if (strstart(devname, "vc", 0))
6169 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6173 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6174 const char *devname = parallel_devices[i];
6175 if (devname && strcmp(devname, "none")) {
6176 if (strstart(devname, "vc", 0))
6177 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6181 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6182 const char *devname = virtio_consoles[i];
6183 if (virtcon_hds[i] && devname) {
6184 if (strstart(devname, "vc", 0))
6185 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6189 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6190 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6191 gdbstub_dev);
6192 exit(1);
6195 if (loadvm)
6196 do_loadvm(cur_mon, loadvm);
6198 if (incoming) {
6199 qemu_start_incoming_migration(incoming);
6200 } else if (autostart) {
6201 vm_start();
6204 #ifndef _WIN32
6205 if (daemonize) {
6206 uint8_t status = 0;
6207 ssize_t len;
6209 again1:
6210 len = write(fds[1], &status, 1);
6211 if (len == -1 && (errno == EINTR))
6212 goto again1;
6214 if (len != 1)
6215 exit(1);
6217 chdir("/");
6218 TFR(fd = open("/dev/null", O_RDWR));
6219 if (fd == -1)
6220 exit(1);
6223 if (run_as) {
6224 pwd = getpwnam(run_as);
6225 if (!pwd) {
6226 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6227 exit(1);
6231 if (chroot_dir) {
6232 if (chroot(chroot_dir) < 0) {
6233 fprintf(stderr, "chroot failed\n");
6234 exit(1);
6236 chdir("/");
6239 if (run_as) {
6240 if (setgid(pwd->pw_gid) < 0) {
6241 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6242 exit(1);
6244 if (setuid(pwd->pw_uid) < 0) {
6245 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6246 exit(1);
6248 if (setuid(0) != -1) {
6249 fprintf(stderr, "Dropping privileges failed\n");
6250 exit(1);
6254 if (daemonize) {
6255 dup2(fd, 0);
6256 dup2(fd, 1);
6257 dup2(fd, 2);
6259 close(fd);
6261 #endif
6263 main_loop();
6264 quit_timers();
6265 net_cleanup();
6267 return 0;