raw-posix: add Linux native AIO support
[qemu-kvm.git] / vl.c
blob10857941900b961dfaa6e997cf092cf051815505
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
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 CONFIG_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 <mmsystem.h>
112 #endif
114 #ifdef CONFIG_SDL
115 #if defined(__APPLE__) || defined(main)
116 #include <SDL.h>
117 int qemu_main(int argc, char **argv, char **envp);
118 int main(int argc, char **argv)
120 return qemu_main(argc, argv, NULL);
122 #undef main
123 #define main qemu_main
124 #endif
125 #endif /* CONFIG_SDL */
127 #ifdef CONFIG_COCOA
128 #undef main
129 #define main qemu_main
130 #endif /* CONFIG_COCOA */
132 #include "hw/hw.h"
133 #include "hw/boards.h"
134 #include "hw/usb.h"
135 #include "hw/pcmcia.h"
136 #include "hw/pc.h"
137 #include "hw/audiodev.h"
138 #include "hw/isa.h"
139 #include "hw/baum.h"
140 #include "hw/bt.h"
141 #include "hw/watchdog.h"
142 #include "hw/smbios.h"
143 #include "hw/xen.h"
144 #include "hw/qdev.h"
145 #include "bt-host.h"
146 #include "net.h"
147 #include "monitor.h"
148 #include "console.h"
149 #include "sysemu.h"
150 #include "gdbstub.h"
151 #include "qemu-timer.h"
152 #include "qemu-char.h"
153 #include "cache-utils.h"
154 #include "block.h"
155 #include "dma.h"
156 #include "audio/audio.h"
157 #include "migration.h"
158 #include "kvm.h"
159 #include "balloon.h"
160 #include "qemu-option.h"
161 #include "qemu-config.h"
163 #include "disas.h"
165 #include "exec-all.h"
167 #include "qemu_socket.h"
169 #include "slirp/libslirp.h"
171 //#define DEBUG_NET
172 //#define DEBUG_SLIRP
174 #define DEFAULT_RAM_SIZE 128
176 static const char *data_dir;
177 const char *bios_name = NULL;
178 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
179 to store the VM snapshots */
180 struct drivelist drives = TAILQ_HEAD_INITIALIZER(drives);
181 struct driveoptlist driveopts = TAILQ_HEAD_INITIALIZER(driveopts);
182 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
183 static DisplayState *display_state;
184 DisplayType display_type = DT_DEFAULT;
185 const char* keyboard_layout = NULL;
186 int64_t ticks_per_sec;
187 ram_addr_t ram_size;
188 int nb_nics;
189 NICInfo nd_table[MAX_NICS];
190 int vm_running;
191 int autostart;
192 static int rtc_utc = 1;
193 static int rtc_date_offset = -1; /* -1 means no change */
194 int vga_interface_type = VGA_CIRRUS;
195 #ifdef TARGET_SPARC
196 int graphic_width = 1024;
197 int graphic_height = 768;
198 int graphic_depth = 8;
199 #else
200 int graphic_width = 800;
201 int graphic_height = 600;
202 int graphic_depth = 15;
203 #endif
204 static int full_screen = 0;
205 #ifdef CONFIG_SDL
206 static int no_frame = 0;
207 #endif
208 int no_quit = 0;
209 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
210 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
211 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
212 #ifdef TARGET_I386
213 int win2k_install_hack = 0;
214 int rtc_td_hack = 0;
215 #endif
216 int usb_enabled = 0;
217 int singlestep = 0;
218 int smp_cpus = 1;
219 int max_cpus = 0;
220 int smp_cores = 1;
221 int smp_threads = 1;
222 const char *vnc_display;
223 int acpi_enabled = 1;
224 int no_hpet = 0;
225 int virtio_balloon = 1;
226 const char *virtio_balloon_devaddr;
227 int fd_bootchk = 1;
228 int no_reboot = 0;
229 int no_shutdown = 0;
230 int cursor_hide = 1;
231 int graphic_rotate = 0;
232 uint8_t irq0override = 1;
233 #ifndef _WIN32
234 int daemonize = 0;
235 #endif
236 WatchdogTimerModel *watchdog = NULL;
237 int watchdog_action = WDT_RESET;
238 const char *option_rom[MAX_OPTION_ROMS];
239 int nb_option_roms;
240 int semihosting_enabled = 0;
241 #ifdef TARGET_ARM
242 int old_param = 0;
243 #endif
244 const char *qemu_name;
245 int alt_grab = 0;
246 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
247 unsigned int nb_prom_envs = 0;
248 const char *prom_envs[MAX_PROM_ENVS];
249 #endif
250 int boot_menu;
252 int nb_numa_nodes;
253 uint64_t node_mem[MAX_NODES];
254 uint64_t node_cpumask[MAX_NODES];
256 static CPUState *cur_cpu;
257 static CPUState *next_cpu;
258 static int timer_alarm_pending = 1;
259 /* Conversion factor from emulated instructions to virtual clock ticks. */
260 static int icount_time_shift;
261 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
262 #define MAX_ICOUNT_SHIFT 10
263 /* Compensate for varying guest execution speed. */
264 static int64_t qemu_icount_bias;
265 static QEMUTimer *icount_rt_timer;
266 static QEMUTimer *icount_vm_timer;
267 static QEMUTimer *nographic_timer;
269 uint8_t qemu_uuid[16];
271 static QEMUBootSetHandler *boot_set_handler;
272 static void *boot_set_opaque;
274 /***********************************************************/
275 /* x86 ISA bus support */
277 target_phys_addr_t isa_mem_base = 0;
278 PicState2 *isa_pic;
280 /***********************************************************/
281 void hw_error(const char *fmt, ...)
283 va_list ap;
284 CPUState *env;
286 va_start(ap, fmt);
287 fprintf(stderr, "qemu: hardware error: ");
288 vfprintf(stderr, fmt, ap);
289 fprintf(stderr, "\n");
290 for(env = first_cpu; env != NULL; env = env->next_cpu) {
291 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
292 #ifdef TARGET_I386
293 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
294 #else
295 cpu_dump_state(env, stderr, fprintf, 0);
296 #endif
298 va_end(ap);
299 abort();
302 static void set_proc_name(const char *s)
304 #if defined(__linux__) && defined(PR_SET_NAME)
305 char name[16];
306 if (!s)
307 return;
308 name[sizeof(name) - 1] = 0;
309 strncpy(name, s, sizeof(name));
310 /* Could rewrite argv[0] too, but that's a bit more complicated.
311 This simple way is enough for `top'. */
312 prctl(PR_SET_NAME, name);
313 #endif
316 /***************/
317 /* ballooning */
319 static QEMUBalloonEvent *qemu_balloon_event;
320 void *qemu_balloon_event_opaque;
322 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
324 qemu_balloon_event = func;
325 qemu_balloon_event_opaque = opaque;
328 void qemu_balloon(ram_addr_t target)
330 if (qemu_balloon_event)
331 qemu_balloon_event(qemu_balloon_event_opaque, target);
334 ram_addr_t qemu_balloon_status(void)
336 if (qemu_balloon_event)
337 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
338 return 0;
341 /***********************************************************/
342 /* keyboard/mouse */
344 static QEMUPutKBDEvent *qemu_put_kbd_event;
345 static void *qemu_put_kbd_event_opaque;
346 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
347 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
349 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
351 qemu_put_kbd_event_opaque = opaque;
352 qemu_put_kbd_event = func;
355 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
356 void *opaque, int absolute,
357 const char *name)
359 QEMUPutMouseEntry *s, *cursor;
361 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
363 s->qemu_put_mouse_event = func;
364 s->qemu_put_mouse_event_opaque = opaque;
365 s->qemu_put_mouse_event_absolute = absolute;
366 s->qemu_put_mouse_event_name = qemu_strdup(name);
367 s->next = NULL;
369 if (!qemu_put_mouse_event_head) {
370 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
371 return s;
374 cursor = qemu_put_mouse_event_head;
375 while (cursor->next != NULL)
376 cursor = cursor->next;
378 cursor->next = s;
379 qemu_put_mouse_event_current = s;
381 return s;
384 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
386 QEMUPutMouseEntry *prev = NULL, *cursor;
388 if (!qemu_put_mouse_event_head || entry == NULL)
389 return;
391 cursor = qemu_put_mouse_event_head;
392 while (cursor != NULL && cursor != entry) {
393 prev = cursor;
394 cursor = cursor->next;
397 if (cursor == NULL) // does not exist or list empty
398 return;
399 else if (prev == NULL) { // entry is head
400 qemu_put_mouse_event_head = cursor->next;
401 if (qemu_put_mouse_event_current == entry)
402 qemu_put_mouse_event_current = cursor->next;
403 qemu_free(entry->qemu_put_mouse_event_name);
404 qemu_free(entry);
405 return;
408 prev->next = entry->next;
410 if (qemu_put_mouse_event_current == entry)
411 qemu_put_mouse_event_current = prev;
413 qemu_free(entry->qemu_put_mouse_event_name);
414 qemu_free(entry);
417 void kbd_put_keycode(int keycode)
419 if (qemu_put_kbd_event) {
420 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
424 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
426 QEMUPutMouseEvent *mouse_event;
427 void *mouse_event_opaque;
428 int width;
430 if (!qemu_put_mouse_event_current) {
431 return;
434 mouse_event =
435 qemu_put_mouse_event_current->qemu_put_mouse_event;
436 mouse_event_opaque =
437 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
439 if (mouse_event) {
440 if (graphic_rotate) {
441 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
442 width = 0x7fff;
443 else
444 width = graphic_width - 1;
445 mouse_event(mouse_event_opaque,
446 width - dy, dx, dz, buttons_state);
447 } else
448 mouse_event(mouse_event_opaque,
449 dx, dy, dz, buttons_state);
453 int kbd_mouse_is_absolute(void)
455 if (!qemu_put_mouse_event_current)
456 return 0;
458 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
461 void do_info_mice(Monitor *mon)
463 QEMUPutMouseEntry *cursor;
464 int index = 0;
466 if (!qemu_put_mouse_event_head) {
467 monitor_printf(mon, "No mouse devices connected\n");
468 return;
471 monitor_printf(mon, "Mouse devices available:\n");
472 cursor = qemu_put_mouse_event_head;
473 while (cursor != NULL) {
474 monitor_printf(mon, "%c Mouse #%d: %s\n",
475 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
476 index, cursor->qemu_put_mouse_event_name);
477 index++;
478 cursor = cursor->next;
482 void do_mouse_set(Monitor *mon, int index)
484 QEMUPutMouseEntry *cursor;
485 int i = 0;
487 if (!qemu_put_mouse_event_head) {
488 monitor_printf(mon, "No mouse devices connected\n");
489 return;
492 cursor = qemu_put_mouse_event_head;
493 while (cursor != NULL && index != i) {
494 i++;
495 cursor = cursor->next;
498 if (cursor != NULL)
499 qemu_put_mouse_event_current = cursor;
500 else
501 monitor_printf(mon, "Mouse at given index not found\n");
504 /* compute with 96 bit intermediate result: (a*b)/c */
505 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
507 union {
508 uint64_t ll;
509 struct {
510 #ifdef HOST_WORDS_BIGENDIAN
511 uint32_t high, low;
512 #else
513 uint32_t low, high;
514 #endif
515 } l;
516 } u, res;
517 uint64_t rl, rh;
519 u.ll = a;
520 rl = (uint64_t)u.l.low * (uint64_t)b;
521 rh = (uint64_t)u.l.high * (uint64_t)b;
522 rh += (rl >> 32);
523 res.l.high = rh / c;
524 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
525 return res.ll;
528 /***********************************************************/
529 /* real time host monotonic timer */
531 #define QEMU_TIMER_BASE 1000000000LL
533 #ifdef WIN32
535 static int64_t clock_freq;
537 static void init_get_clock(void)
539 LARGE_INTEGER freq;
540 int ret;
541 ret = QueryPerformanceFrequency(&freq);
542 if (ret == 0) {
543 fprintf(stderr, "Could not calibrate ticks\n");
544 exit(1);
546 clock_freq = freq.QuadPart;
549 static int64_t get_clock(void)
551 LARGE_INTEGER ti;
552 QueryPerformanceCounter(&ti);
553 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
556 #else
558 static int use_rt_clock;
560 static void init_get_clock(void)
562 use_rt_clock = 0;
563 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
564 || defined(__DragonFly__)
566 struct timespec ts;
567 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
568 use_rt_clock = 1;
571 #endif
574 static int64_t get_clock(void)
576 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
577 || defined(__DragonFly__)
578 if (use_rt_clock) {
579 struct timespec ts;
580 clock_gettime(CLOCK_MONOTONIC, &ts);
581 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
582 } else
583 #endif
585 /* XXX: using gettimeofday leads to problems if the date
586 changes, so it should be avoided. */
587 struct timeval tv;
588 gettimeofday(&tv, NULL);
589 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
592 #endif
594 /* Return the virtual CPU time, based on the instruction counter. */
595 static int64_t cpu_get_icount(void)
597 int64_t icount;
598 CPUState *env = cpu_single_env;;
599 icount = qemu_icount;
600 if (env) {
601 if (!can_do_io(env))
602 fprintf(stderr, "Bad clock read\n");
603 icount -= (env->icount_decr.u16.low + env->icount_extra);
605 return qemu_icount_bias + (icount << icount_time_shift);
608 /***********************************************************/
609 /* guest cycle counter */
611 static int64_t cpu_ticks_prev;
612 static int64_t cpu_ticks_offset;
613 static int64_t cpu_clock_offset;
614 static int cpu_ticks_enabled;
616 /* return the host CPU cycle counter and handle stop/restart */
617 int64_t cpu_get_ticks(void)
619 if (use_icount) {
620 return cpu_get_icount();
622 if (!cpu_ticks_enabled) {
623 return cpu_ticks_offset;
624 } else {
625 int64_t ticks;
626 ticks = cpu_get_real_ticks();
627 if (cpu_ticks_prev > ticks) {
628 /* Note: non increasing ticks may happen if the host uses
629 software suspend */
630 cpu_ticks_offset += cpu_ticks_prev - ticks;
632 cpu_ticks_prev = ticks;
633 return ticks + cpu_ticks_offset;
637 /* return the host CPU monotonic timer and handle stop/restart */
638 static int64_t cpu_get_clock(void)
640 int64_t ti;
641 if (!cpu_ticks_enabled) {
642 return cpu_clock_offset;
643 } else {
644 ti = get_clock();
645 return ti + cpu_clock_offset;
649 /* enable cpu_get_ticks() */
650 void cpu_enable_ticks(void)
652 if (!cpu_ticks_enabled) {
653 cpu_ticks_offset -= cpu_get_real_ticks();
654 cpu_clock_offset -= get_clock();
655 cpu_ticks_enabled = 1;
659 /* disable cpu_get_ticks() : the clock is stopped. You must not call
660 cpu_get_ticks() after that. */
661 void cpu_disable_ticks(void)
663 if (cpu_ticks_enabled) {
664 cpu_ticks_offset = cpu_get_ticks();
665 cpu_clock_offset = cpu_get_clock();
666 cpu_ticks_enabled = 0;
670 /***********************************************************/
671 /* timers */
673 #define QEMU_TIMER_REALTIME 0
674 #define QEMU_TIMER_VIRTUAL 1
676 struct QEMUClock {
677 int type;
678 /* XXX: add frequency */
681 struct QEMUTimer {
682 QEMUClock *clock;
683 int64_t expire_time;
684 QEMUTimerCB *cb;
685 void *opaque;
686 struct QEMUTimer *next;
689 struct qemu_alarm_timer {
690 char const *name;
691 unsigned int flags;
693 int (*start)(struct qemu_alarm_timer *t);
694 void (*stop)(struct qemu_alarm_timer *t);
695 void (*rearm)(struct qemu_alarm_timer *t);
696 void *priv;
699 #define ALARM_FLAG_DYNTICKS 0x1
700 #define ALARM_FLAG_EXPIRED 0x2
702 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
704 return t && (t->flags & ALARM_FLAG_DYNTICKS);
707 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
709 if (!alarm_has_dynticks(t))
710 return;
712 t->rearm(t);
715 /* TODO: MIN_TIMER_REARM_US should be optimized */
716 #define MIN_TIMER_REARM_US 250
718 static struct qemu_alarm_timer *alarm_timer;
720 #ifdef _WIN32
722 struct qemu_alarm_win32 {
723 MMRESULT timerId;
724 unsigned int period;
725 } alarm_win32_data = {0, -1};
727 static int win32_start_timer(struct qemu_alarm_timer *t);
728 static void win32_stop_timer(struct qemu_alarm_timer *t);
729 static void win32_rearm_timer(struct qemu_alarm_timer *t);
731 #else
733 static int unix_start_timer(struct qemu_alarm_timer *t);
734 static void unix_stop_timer(struct qemu_alarm_timer *t);
736 #ifdef __linux__
738 static int dynticks_start_timer(struct qemu_alarm_timer *t);
739 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
740 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
742 static int hpet_start_timer(struct qemu_alarm_timer *t);
743 static void hpet_stop_timer(struct qemu_alarm_timer *t);
745 static int rtc_start_timer(struct qemu_alarm_timer *t);
746 static void rtc_stop_timer(struct qemu_alarm_timer *t);
748 #endif /* __linux__ */
750 #endif /* _WIN32 */
752 /* Correlation between real and virtual time is always going to be
753 fairly approximate, so ignore small variation.
754 When the guest is idle real and virtual time will be aligned in
755 the IO wait loop. */
756 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
758 static void icount_adjust(void)
760 int64_t cur_time;
761 int64_t cur_icount;
762 int64_t delta;
763 static int64_t last_delta;
764 /* If the VM is not running, then do nothing. */
765 if (!vm_running)
766 return;
768 cur_time = cpu_get_clock();
769 cur_icount = qemu_get_clock(vm_clock);
770 delta = cur_icount - cur_time;
771 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
772 if (delta > 0
773 && last_delta + ICOUNT_WOBBLE < delta * 2
774 && icount_time_shift > 0) {
775 /* The guest is getting too far ahead. Slow time down. */
776 icount_time_shift--;
778 if (delta < 0
779 && last_delta - ICOUNT_WOBBLE > delta * 2
780 && icount_time_shift < MAX_ICOUNT_SHIFT) {
781 /* The guest is getting too far behind. Speed time up. */
782 icount_time_shift++;
784 last_delta = delta;
785 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
788 static void icount_adjust_rt(void * opaque)
790 qemu_mod_timer(icount_rt_timer,
791 qemu_get_clock(rt_clock) + 1000);
792 icount_adjust();
795 static void icount_adjust_vm(void * opaque)
797 qemu_mod_timer(icount_vm_timer,
798 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
799 icount_adjust();
802 static void init_icount_adjust(void)
804 /* Have both realtime and virtual time triggers for speed adjustment.
805 The realtime trigger catches emulated time passing too slowly,
806 the virtual time trigger catches emulated time passing too fast.
807 Realtime triggers occur even when idle, so use them less frequently
808 than VM triggers. */
809 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
810 qemu_mod_timer(icount_rt_timer,
811 qemu_get_clock(rt_clock) + 1000);
812 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
813 qemu_mod_timer(icount_vm_timer,
814 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
817 static struct qemu_alarm_timer alarm_timers[] = {
818 #ifndef _WIN32
819 #ifdef __linux__
820 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
821 dynticks_stop_timer, dynticks_rearm_timer, NULL},
822 /* HPET - if available - is preferred */
823 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
824 /* ...otherwise try RTC */
825 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
826 #endif
827 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
828 #else
829 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
830 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
831 {"win32", 0, win32_start_timer,
832 win32_stop_timer, NULL, &alarm_win32_data},
833 #endif
834 {NULL, }
837 static void show_available_alarms(void)
839 int i;
841 printf("Available alarm timers, in order of precedence:\n");
842 for (i = 0; alarm_timers[i].name; i++)
843 printf("%s\n", alarm_timers[i].name);
846 static void configure_alarms(char const *opt)
848 int i;
849 int cur = 0;
850 int count = ARRAY_SIZE(alarm_timers) - 1;
851 char *arg;
852 char *name;
853 struct qemu_alarm_timer tmp;
855 if (!strcmp(opt, "?")) {
856 show_available_alarms();
857 exit(0);
860 arg = strdup(opt);
862 /* Reorder the array */
863 name = strtok(arg, ",");
864 while (name) {
865 for (i = 0; i < count && alarm_timers[i].name; i++) {
866 if (!strcmp(alarm_timers[i].name, name))
867 break;
870 if (i == count) {
871 fprintf(stderr, "Unknown clock %s\n", name);
872 goto next;
875 if (i < cur)
876 /* Ignore */
877 goto next;
879 /* Swap */
880 tmp = alarm_timers[i];
881 alarm_timers[i] = alarm_timers[cur];
882 alarm_timers[cur] = tmp;
884 cur++;
885 next:
886 name = strtok(NULL, ",");
889 free(arg);
891 if (cur) {
892 /* Disable remaining timers */
893 for (i = cur; i < count; i++)
894 alarm_timers[i].name = NULL;
895 } else {
896 show_available_alarms();
897 exit(1);
901 QEMUClock *rt_clock;
902 QEMUClock *vm_clock;
904 static QEMUTimer *active_timers[2];
906 static QEMUClock *qemu_new_clock(int type)
908 QEMUClock *clock;
909 clock = qemu_mallocz(sizeof(QEMUClock));
910 clock->type = type;
911 return clock;
914 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
916 QEMUTimer *ts;
918 ts = qemu_mallocz(sizeof(QEMUTimer));
919 ts->clock = clock;
920 ts->cb = cb;
921 ts->opaque = opaque;
922 return ts;
925 void qemu_free_timer(QEMUTimer *ts)
927 qemu_free(ts);
930 /* stop a timer, but do not dealloc it */
931 void qemu_del_timer(QEMUTimer *ts)
933 QEMUTimer **pt, *t;
935 /* NOTE: this code must be signal safe because
936 qemu_timer_expired() can be called from a signal. */
937 pt = &active_timers[ts->clock->type];
938 for(;;) {
939 t = *pt;
940 if (!t)
941 break;
942 if (t == ts) {
943 *pt = t->next;
944 break;
946 pt = &t->next;
950 /* modify the current timer so that it will be fired when current_time
951 >= expire_time. The corresponding callback will be called. */
952 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
954 QEMUTimer **pt, *t;
956 qemu_del_timer(ts);
958 /* add the timer in the sorted list */
959 /* NOTE: this code must be signal safe because
960 qemu_timer_expired() can be called from a signal. */
961 pt = &active_timers[ts->clock->type];
962 for(;;) {
963 t = *pt;
964 if (!t)
965 break;
966 if (t->expire_time > expire_time)
967 break;
968 pt = &t->next;
970 ts->expire_time = expire_time;
971 ts->next = *pt;
972 *pt = ts;
974 /* Rearm if necessary */
975 if (pt == &active_timers[ts->clock->type]) {
976 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
977 qemu_rearm_alarm_timer(alarm_timer);
979 /* Interrupt execution to force deadline recalculation. */
980 if (use_icount)
981 qemu_notify_event();
985 int qemu_timer_pending(QEMUTimer *ts)
987 QEMUTimer *t;
988 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
989 if (t == ts)
990 return 1;
992 return 0;
995 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
997 if (!timer_head)
998 return 0;
999 return (timer_head->expire_time <= current_time);
1002 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1004 QEMUTimer *ts;
1006 for(;;) {
1007 ts = *ptimer_head;
1008 if (!ts || ts->expire_time > current_time)
1009 break;
1010 /* remove timer from the list before calling the callback */
1011 *ptimer_head = ts->next;
1012 ts->next = NULL;
1014 /* run the callback (the timer list can be modified) */
1015 ts->cb(ts->opaque);
1019 int64_t qemu_get_clock(QEMUClock *clock)
1021 switch(clock->type) {
1022 case QEMU_TIMER_REALTIME:
1023 return get_clock() / 1000000;
1024 default:
1025 case QEMU_TIMER_VIRTUAL:
1026 if (use_icount) {
1027 return cpu_get_icount();
1028 } else {
1029 return cpu_get_clock();
1034 static void init_timers(void)
1036 init_get_clock();
1037 ticks_per_sec = QEMU_TIMER_BASE;
1038 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1039 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1042 /* save a timer */
1043 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1045 uint64_t expire_time;
1047 if (qemu_timer_pending(ts)) {
1048 expire_time = ts->expire_time;
1049 } else {
1050 expire_time = -1;
1052 qemu_put_be64(f, expire_time);
1055 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1057 uint64_t expire_time;
1059 expire_time = qemu_get_be64(f);
1060 if (expire_time != -1) {
1061 qemu_mod_timer(ts, expire_time);
1062 } else {
1063 qemu_del_timer(ts);
1067 static void timer_save(QEMUFile *f, void *opaque)
1069 if (cpu_ticks_enabled) {
1070 hw_error("cannot save state if virtual timers are running");
1072 qemu_put_be64(f, cpu_ticks_offset);
1073 qemu_put_be64(f, ticks_per_sec);
1074 qemu_put_be64(f, cpu_clock_offset);
1077 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1079 if (version_id != 1 && version_id != 2)
1080 return -EINVAL;
1081 if (cpu_ticks_enabled) {
1082 return -EINVAL;
1084 cpu_ticks_offset=qemu_get_be64(f);
1085 ticks_per_sec=qemu_get_be64(f);
1086 if (version_id == 2) {
1087 cpu_clock_offset=qemu_get_be64(f);
1089 return 0;
1092 static void qemu_event_increment(void);
1094 #ifdef _WIN32
1095 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1096 DWORD_PTR dwUser, DWORD_PTR dw1,
1097 DWORD_PTR dw2)
1098 #else
1099 static void host_alarm_handler(int host_signum)
1100 #endif
1102 #if 0
1103 #define DISP_FREQ 1000
1105 static int64_t delta_min = INT64_MAX;
1106 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1107 static int count;
1108 ti = qemu_get_clock(vm_clock);
1109 if (last_clock != 0) {
1110 delta = ti - last_clock;
1111 if (delta < delta_min)
1112 delta_min = delta;
1113 if (delta > delta_max)
1114 delta_max = delta;
1115 delta_cum += delta;
1116 if (++count == DISP_FREQ) {
1117 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1118 muldiv64(delta_min, 1000000, ticks_per_sec),
1119 muldiv64(delta_max, 1000000, ticks_per_sec),
1120 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1121 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1122 count = 0;
1123 delta_min = INT64_MAX;
1124 delta_max = 0;
1125 delta_cum = 0;
1128 last_clock = ti;
1130 #endif
1131 if (alarm_has_dynticks(alarm_timer) ||
1132 (!use_icount &&
1133 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1134 qemu_get_clock(vm_clock))) ||
1135 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1136 qemu_get_clock(rt_clock))) {
1137 qemu_event_increment();
1138 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1140 #ifndef CONFIG_IOTHREAD
1141 if (next_cpu) {
1142 /* stop the currently executing cpu because a timer occured */
1143 cpu_exit(next_cpu);
1145 #endif
1146 timer_alarm_pending = 1;
1147 qemu_notify_event();
1151 static int64_t qemu_next_deadline(void)
1153 int64_t delta;
1155 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1156 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1157 qemu_get_clock(vm_clock);
1158 } else {
1159 /* To avoid problems with overflow limit this to 2^32. */
1160 delta = INT32_MAX;
1163 if (delta < 0)
1164 delta = 0;
1166 return delta;
1169 #if defined(__linux__) || defined(_WIN32)
1170 static uint64_t qemu_next_deadline_dyntick(void)
1172 int64_t delta;
1173 int64_t rtdelta;
1175 if (use_icount)
1176 delta = INT32_MAX;
1177 else
1178 delta = (qemu_next_deadline() + 999) / 1000;
1180 if (active_timers[QEMU_TIMER_REALTIME]) {
1181 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1182 qemu_get_clock(rt_clock))*1000;
1183 if (rtdelta < delta)
1184 delta = rtdelta;
1187 if (delta < MIN_TIMER_REARM_US)
1188 delta = MIN_TIMER_REARM_US;
1190 return delta;
1192 #endif
1194 #ifndef _WIN32
1196 /* Sets a specific flag */
1197 static int fcntl_setfl(int fd, int flag)
1199 int flags;
1201 flags = fcntl(fd, F_GETFL);
1202 if (flags == -1)
1203 return -errno;
1205 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1206 return -errno;
1208 return 0;
1211 #if defined(__linux__)
1213 #define RTC_FREQ 1024
1215 static void enable_sigio_timer(int fd)
1217 struct sigaction act;
1219 /* timer signal */
1220 sigfillset(&act.sa_mask);
1221 act.sa_flags = 0;
1222 act.sa_handler = host_alarm_handler;
1224 sigaction(SIGIO, &act, NULL);
1225 fcntl_setfl(fd, O_ASYNC);
1226 fcntl(fd, F_SETOWN, getpid());
1229 static int hpet_start_timer(struct qemu_alarm_timer *t)
1231 struct hpet_info info;
1232 int r, fd;
1234 fd = open("/dev/hpet", O_RDONLY);
1235 if (fd < 0)
1236 return -1;
1238 /* Set frequency */
1239 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1240 if (r < 0) {
1241 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1242 "error, but for better emulation accuracy type:\n"
1243 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1244 goto fail;
1247 /* Check capabilities */
1248 r = ioctl(fd, HPET_INFO, &info);
1249 if (r < 0)
1250 goto fail;
1252 /* Enable periodic mode */
1253 r = ioctl(fd, HPET_EPI, 0);
1254 if (info.hi_flags && (r < 0))
1255 goto fail;
1257 /* Enable interrupt */
1258 r = ioctl(fd, HPET_IE_ON, 0);
1259 if (r < 0)
1260 goto fail;
1262 enable_sigio_timer(fd);
1263 t->priv = (void *)(long)fd;
1265 return 0;
1266 fail:
1267 close(fd);
1268 return -1;
1271 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1273 int fd = (long)t->priv;
1275 close(fd);
1278 static int rtc_start_timer(struct qemu_alarm_timer *t)
1280 int rtc_fd;
1281 unsigned long current_rtc_freq = 0;
1283 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1284 if (rtc_fd < 0)
1285 return -1;
1286 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1287 if (current_rtc_freq != RTC_FREQ &&
1288 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1289 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1290 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1291 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1292 goto fail;
1294 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1295 fail:
1296 close(rtc_fd);
1297 return -1;
1300 enable_sigio_timer(rtc_fd);
1302 t->priv = (void *)(long)rtc_fd;
1304 return 0;
1307 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1309 int rtc_fd = (long)t->priv;
1311 close(rtc_fd);
1314 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1316 struct sigevent ev;
1317 timer_t host_timer;
1318 struct sigaction act;
1320 sigfillset(&act.sa_mask);
1321 act.sa_flags = 0;
1322 act.sa_handler = host_alarm_handler;
1324 sigaction(SIGALRM, &act, NULL);
1327 * Initialize ev struct to 0 to avoid valgrind complaining
1328 * about uninitialized data in timer_create call
1330 memset(&ev, 0, sizeof(ev));
1331 ev.sigev_value.sival_int = 0;
1332 ev.sigev_notify = SIGEV_SIGNAL;
1333 ev.sigev_signo = SIGALRM;
1335 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1336 perror("timer_create");
1338 /* disable dynticks */
1339 fprintf(stderr, "Dynamic Ticks disabled\n");
1341 return -1;
1344 t->priv = (void *)(long)host_timer;
1346 return 0;
1349 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1351 timer_t host_timer = (timer_t)(long)t->priv;
1353 timer_delete(host_timer);
1356 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1358 timer_t host_timer = (timer_t)(long)t->priv;
1359 struct itimerspec timeout;
1360 int64_t nearest_delta_us = INT64_MAX;
1361 int64_t current_us;
1363 if (!active_timers[QEMU_TIMER_REALTIME] &&
1364 !active_timers[QEMU_TIMER_VIRTUAL])
1365 return;
1367 nearest_delta_us = qemu_next_deadline_dyntick();
1369 /* check whether a timer is already running */
1370 if (timer_gettime(host_timer, &timeout)) {
1371 perror("gettime");
1372 fprintf(stderr, "Internal timer error: aborting\n");
1373 exit(1);
1375 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1376 if (current_us && current_us <= nearest_delta_us)
1377 return;
1379 timeout.it_interval.tv_sec = 0;
1380 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1381 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1382 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1383 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1384 perror("settime");
1385 fprintf(stderr, "Internal timer error: aborting\n");
1386 exit(1);
1390 #endif /* defined(__linux__) */
1392 static int unix_start_timer(struct qemu_alarm_timer *t)
1394 struct sigaction act;
1395 struct itimerval itv;
1396 int err;
1398 /* timer signal */
1399 sigfillset(&act.sa_mask);
1400 act.sa_flags = 0;
1401 act.sa_handler = host_alarm_handler;
1403 sigaction(SIGALRM, &act, NULL);
1405 itv.it_interval.tv_sec = 0;
1406 /* for i386 kernel 2.6 to get 1 ms */
1407 itv.it_interval.tv_usec = 999;
1408 itv.it_value.tv_sec = 0;
1409 itv.it_value.tv_usec = 10 * 1000;
1411 err = setitimer(ITIMER_REAL, &itv, NULL);
1412 if (err)
1413 return -1;
1415 return 0;
1418 static void unix_stop_timer(struct qemu_alarm_timer *t)
1420 struct itimerval itv;
1422 memset(&itv, 0, sizeof(itv));
1423 setitimer(ITIMER_REAL, &itv, NULL);
1426 #endif /* !defined(_WIN32) */
1429 #ifdef _WIN32
1431 static int win32_start_timer(struct qemu_alarm_timer *t)
1433 TIMECAPS tc;
1434 struct qemu_alarm_win32 *data = t->priv;
1435 UINT flags;
1437 memset(&tc, 0, sizeof(tc));
1438 timeGetDevCaps(&tc, sizeof(tc));
1440 if (data->period < tc.wPeriodMin)
1441 data->period = tc.wPeriodMin;
1443 timeBeginPeriod(data->period);
1445 flags = TIME_CALLBACK_FUNCTION;
1446 if (alarm_has_dynticks(t))
1447 flags |= TIME_ONESHOT;
1448 else
1449 flags |= TIME_PERIODIC;
1451 data->timerId = timeSetEvent(1, // interval (ms)
1452 data->period, // resolution
1453 host_alarm_handler, // function
1454 (DWORD)t, // parameter
1455 flags);
1457 if (!data->timerId) {
1458 perror("Failed to initialize win32 alarm timer");
1459 timeEndPeriod(data->period);
1460 return -1;
1463 return 0;
1466 static void win32_stop_timer(struct qemu_alarm_timer *t)
1468 struct qemu_alarm_win32 *data = t->priv;
1470 timeKillEvent(data->timerId);
1471 timeEndPeriod(data->period);
1474 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1476 struct qemu_alarm_win32 *data = t->priv;
1477 uint64_t nearest_delta_us;
1479 if (!active_timers[QEMU_TIMER_REALTIME] &&
1480 !active_timers[QEMU_TIMER_VIRTUAL])
1481 return;
1483 nearest_delta_us = qemu_next_deadline_dyntick();
1484 nearest_delta_us /= 1000;
1486 timeKillEvent(data->timerId);
1488 data->timerId = timeSetEvent(1,
1489 data->period,
1490 host_alarm_handler,
1491 (DWORD)t,
1492 TIME_ONESHOT | TIME_PERIODIC);
1494 if (!data->timerId) {
1495 perror("Failed to re-arm win32 alarm timer");
1497 timeEndPeriod(data->period);
1498 exit(1);
1502 #endif /* _WIN32 */
1504 static int init_timer_alarm(void)
1506 struct qemu_alarm_timer *t = NULL;
1507 int i, err = -1;
1509 for (i = 0; alarm_timers[i].name; i++) {
1510 t = &alarm_timers[i];
1512 err = t->start(t);
1513 if (!err)
1514 break;
1517 if (err) {
1518 err = -ENOENT;
1519 goto fail;
1522 alarm_timer = t;
1524 return 0;
1526 fail:
1527 return err;
1530 static void quit_timers(void)
1532 alarm_timer->stop(alarm_timer);
1533 alarm_timer = NULL;
1536 /***********************************************************/
1537 /* host time/date access */
1538 void qemu_get_timedate(struct tm *tm, int offset)
1540 time_t ti;
1541 struct tm *ret;
1543 time(&ti);
1544 ti += offset;
1545 if (rtc_date_offset == -1) {
1546 if (rtc_utc)
1547 ret = gmtime(&ti);
1548 else
1549 ret = localtime(&ti);
1550 } else {
1551 ti -= rtc_date_offset;
1552 ret = gmtime(&ti);
1555 memcpy(tm, ret, sizeof(struct tm));
1558 int qemu_timedate_diff(struct tm *tm)
1560 time_t seconds;
1562 if (rtc_date_offset == -1)
1563 if (rtc_utc)
1564 seconds = mktimegm(tm);
1565 else
1566 seconds = mktime(tm);
1567 else
1568 seconds = mktimegm(tm) + rtc_date_offset;
1570 return seconds - time(NULL);
1573 #ifdef _WIN32
1574 static void socket_cleanup(void)
1576 WSACleanup();
1579 static int socket_init(void)
1581 WSADATA Data;
1582 int ret, err;
1584 ret = WSAStartup(MAKEWORD(2,2), &Data);
1585 if (ret != 0) {
1586 err = WSAGetLastError();
1587 fprintf(stderr, "WSAStartup: %d\n", err);
1588 return -1;
1590 atexit(socket_cleanup);
1591 return 0;
1593 #endif
1595 /***********************************************************/
1596 /* Bluetooth support */
1597 static int nb_hcis;
1598 static int cur_hci;
1599 static struct HCIInfo *hci_table[MAX_NICS];
1601 static struct bt_vlan_s {
1602 struct bt_scatternet_s net;
1603 int id;
1604 struct bt_vlan_s *next;
1605 } *first_bt_vlan;
1607 /* find or alloc a new bluetooth "VLAN" */
1608 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1610 struct bt_vlan_s **pvlan, *vlan;
1611 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1612 if (vlan->id == id)
1613 return &vlan->net;
1615 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1616 vlan->id = id;
1617 pvlan = &first_bt_vlan;
1618 while (*pvlan != NULL)
1619 pvlan = &(*pvlan)->next;
1620 *pvlan = vlan;
1621 return &vlan->net;
1624 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1628 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1630 return -ENOTSUP;
1633 static struct HCIInfo null_hci = {
1634 .cmd_send = null_hci_send,
1635 .sco_send = null_hci_send,
1636 .acl_send = null_hci_send,
1637 .bdaddr_set = null_hci_addr_set,
1640 struct HCIInfo *qemu_next_hci(void)
1642 if (cur_hci == nb_hcis)
1643 return &null_hci;
1645 return hci_table[cur_hci++];
1648 static struct HCIInfo *hci_init(const char *str)
1650 char *endp;
1651 struct bt_scatternet_s *vlan = 0;
1653 if (!strcmp(str, "null"))
1654 /* null */
1655 return &null_hci;
1656 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1657 /* host[:hciN] */
1658 return bt_host_hci(str[4] ? str + 5 : "hci0");
1659 else if (!strncmp(str, "hci", 3)) {
1660 /* hci[,vlan=n] */
1661 if (str[3]) {
1662 if (!strncmp(str + 3, ",vlan=", 6)) {
1663 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1664 if (*endp)
1665 vlan = 0;
1667 } else
1668 vlan = qemu_find_bt_vlan(0);
1669 if (vlan)
1670 return bt_new_hci(vlan);
1673 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1675 return 0;
1678 static int bt_hci_parse(const char *str)
1680 struct HCIInfo *hci;
1681 bdaddr_t bdaddr;
1683 if (nb_hcis >= MAX_NICS) {
1684 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1685 return -1;
1688 hci = hci_init(str);
1689 if (!hci)
1690 return -1;
1692 bdaddr.b[0] = 0x52;
1693 bdaddr.b[1] = 0x54;
1694 bdaddr.b[2] = 0x00;
1695 bdaddr.b[3] = 0x12;
1696 bdaddr.b[4] = 0x34;
1697 bdaddr.b[5] = 0x56 + nb_hcis;
1698 hci->bdaddr_set(hci, bdaddr.b);
1700 hci_table[nb_hcis++] = hci;
1702 return 0;
1705 static void bt_vhci_add(int vlan_id)
1707 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1709 if (!vlan->slave)
1710 fprintf(stderr, "qemu: warning: adding a VHCI to "
1711 "an empty scatternet %i\n", vlan_id);
1713 bt_vhci_init(bt_new_hci(vlan));
1716 static struct bt_device_s *bt_device_add(const char *opt)
1718 struct bt_scatternet_s *vlan;
1719 int vlan_id = 0;
1720 char *endp = strstr(opt, ",vlan=");
1721 int len = (endp ? endp - opt : strlen(opt)) + 1;
1722 char devname[10];
1724 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1726 if (endp) {
1727 vlan_id = strtol(endp + 6, &endp, 0);
1728 if (*endp) {
1729 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1730 return 0;
1734 vlan = qemu_find_bt_vlan(vlan_id);
1736 if (!vlan->slave)
1737 fprintf(stderr, "qemu: warning: adding a slave device to "
1738 "an empty scatternet %i\n", vlan_id);
1740 if (!strcmp(devname, "keyboard"))
1741 return bt_keyboard_init(vlan);
1743 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1744 return 0;
1747 static int bt_parse(const char *opt)
1749 const char *endp, *p;
1750 int vlan;
1752 if (strstart(opt, "hci", &endp)) {
1753 if (!*endp || *endp == ',') {
1754 if (*endp)
1755 if (!strstart(endp, ",vlan=", 0))
1756 opt = endp + 1;
1758 return bt_hci_parse(opt);
1760 } else if (strstart(opt, "vhci", &endp)) {
1761 if (!*endp || *endp == ',') {
1762 if (*endp) {
1763 if (strstart(endp, ",vlan=", &p)) {
1764 vlan = strtol(p, (char **) &endp, 0);
1765 if (*endp) {
1766 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1767 return 1;
1769 } else {
1770 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1771 return 1;
1773 } else
1774 vlan = 0;
1776 bt_vhci_add(vlan);
1777 return 0;
1779 } else if (strstart(opt, "device:", &endp))
1780 return !bt_device_add(endp);
1782 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1783 return 1;
1786 /***********************************************************/
1787 /* QEMU Block devices */
1789 #define HD_ALIAS "index=%d,media=disk"
1790 #define CDROM_ALIAS "index=2,media=cdrom"
1791 #define FD_ALIAS "index=%d,if=floppy"
1792 #define PFLASH_ALIAS "if=pflash"
1793 #define MTD_ALIAS "if=mtd"
1794 #define SD_ALIAS "index=0,if=sd"
1796 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1798 va_list ap;
1799 char optstr[1024];
1800 QemuOpts *opts;
1802 va_start(ap, fmt);
1803 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1804 va_end(ap);
1806 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1807 if (!opts) {
1808 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1809 __FUNCTION__, optstr);
1810 return NULL;
1812 if (file)
1813 qemu_opt_set(opts, "file", file);
1814 return opts;
1817 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1819 DriveInfo *dinfo;
1821 /* seek interface, bus and unit */
1823 TAILQ_FOREACH(dinfo, &drives, next) {
1824 if (dinfo->type == type &&
1825 dinfo->bus == bus &&
1826 dinfo->unit == unit)
1827 return dinfo;
1830 return NULL;
1833 DriveInfo *drive_get_by_id(const char *id)
1835 DriveInfo *dinfo;
1837 TAILQ_FOREACH(dinfo, &drives, next) {
1838 if (strcmp(id, dinfo->id))
1839 continue;
1840 return dinfo;
1842 return NULL;
1845 int drive_get_max_bus(BlockInterfaceType type)
1847 int max_bus;
1848 DriveInfo *dinfo;
1850 max_bus = -1;
1851 TAILQ_FOREACH(dinfo, &drives, next) {
1852 if(dinfo->type == type &&
1853 dinfo->bus > max_bus)
1854 max_bus = dinfo->bus;
1856 return max_bus;
1859 const char *drive_get_serial(BlockDriverState *bdrv)
1861 DriveInfo *dinfo;
1863 TAILQ_FOREACH(dinfo, &drives, next) {
1864 if (dinfo->bdrv == bdrv)
1865 return dinfo->serial;
1868 return "\0";
1871 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1873 DriveInfo *dinfo;
1875 TAILQ_FOREACH(dinfo, &drives, next) {
1876 if (dinfo->bdrv == bdrv)
1877 return dinfo->onerror;
1880 return BLOCK_ERR_STOP_ENOSPC;
1883 static void bdrv_format_print(void *opaque, const char *name)
1885 fprintf(stderr, " %s", name);
1888 void drive_uninit(BlockDriverState *bdrv)
1890 DriveInfo *dinfo;
1892 TAILQ_FOREACH(dinfo, &drives, next) {
1893 if (dinfo->bdrv != bdrv)
1894 continue;
1895 qemu_opts_del(dinfo->opts);
1896 TAILQ_REMOVE(&drives, dinfo, next);
1897 qemu_free(dinfo);
1898 break;
1902 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1903 int *fatal_error)
1905 const char *buf;
1906 const char *file = NULL;
1907 char devname[128];
1908 const char *serial;
1909 const char *mediastr = "";
1910 BlockInterfaceType type;
1911 enum { MEDIA_DISK, MEDIA_CDROM } media;
1912 int bus_id, unit_id;
1913 int cyls, heads, secs, translation;
1914 BlockDriver *drv = NULL;
1915 QEMUMachine *machine = opaque;
1916 int max_devs;
1917 int index;
1918 int cache;
1919 int aio = 0;
1920 int bdrv_flags, onerror;
1921 const char *devaddr;
1922 DriveInfo *dinfo;
1923 int snapshot = 0;
1925 *fatal_error = 1;
1927 translation = BIOS_ATA_TRANSLATION_AUTO;
1928 cache = 1;
1930 if (machine->use_scsi) {
1931 type = IF_SCSI;
1932 max_devs = MAX_SCSI_DEVS;
1933 pstrcpy(devname, sizeof(devname), "scsi");
1934 } else {
1935 type = IF_IDE;
1936 max_devs = MAX_IDE_DEVS;
1937 pstrcpy(devname, sizeof(devname), "ide");
1939 media = MEDIA_DISK;
1941 /* extract parameters */
1942 bus_id = qemu_opt_get_number(opts, "bus", 0);
1943 unit_id = qemu_opt_get_number(opts, "unit", -1);
1944 index = qemu_opt_get_number(opts, "index", -1);
1946 cyls = qemu_opt_get_number(opts, "cyls", 0);
1947 heads = qemu_opt_get_number(opts, "heads", 0);
1948 secs = qemu_opt_get_number(opts, "secs", 0);
1950 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1952 file = qemu_opt_get(opts, "file");
1953 serial = qemu_opt_get(opts, "serial");
1955 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1956 pstrcpy(devname, sizeof(devname), buf);
1957 if (!strcmp(buf, "ide")) {
1958 type = IF_IDE;
1959 max_devs = MAX_IDE_DEVS;
1960 } else if (!strcmp(buf, "scsi")) {
1961 type = IF_SCSI;
1962 max_devs = MAX_SCSI_DEVS;
1963 } else if (!strcmp(buf, "floppy")) {
1964 type = IF_FLOPPY;
1965 max_devs = 0;
1966 } else if (!strcmp(buf, "pflash")) {
1967 type = IF_PFLASH;
1968 max_devs = 0;
1969 } else if (!strcmp(buf, "mtd")) {
1970 type = IF_MTD;
1971 max_devs = 0;
1972 } else if (!strcmp(buf, "sd")) {
1973 type = IF_SD;
1974 max_devs = 0;
1975 } else if (!strcmp(buf, "virtio")) {
1976 type = IF_VIRTIO;
1977 max_devs = 0;
1978 } else if (!strcmp(buf, "xen")) {
1979 type = IF_XEN;
1980 max_devs = 0;
1981 } else if (!strcmp(buf, "none")) {
1982 type = IF_NONE;
1983 max_devs = 0;
1984 } else {
1985 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
1986 return NULL;
1990 if (cyls || heads || secs) {
1991 if (cyls < 1 || cyls > 16383) {
1992 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
1993 return NULL;
1995 if (heads < 1 || heads > 16) {
1996 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
1997 return NULL;
1999 if (secs < 1 || secs > 63) {
2000 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2001 return NULL;
2005 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2006 if (!cyls) {
2007 fprintf(stderr,
2008 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2009 buf);
2010 return NULL;
2012 if (!strcmp(buf, "none"))
2013 translation = BIOS_ATA_TRANSLATION_NONE;
2014 else if (!strcmp(buf, "lba"))
2015 translation = BIOS_ATA_TRANSLATION_LBA;
2016 else if (!strcmp(buf, "auto"))
2017 translation = BIOS_ATA_TRANSLATION_AUTO;
2018 else {
2019 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2020 return NULL;
2024 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2025 if (!strcmp(buf, "disk")) {
2026 media = MEDIA_DISK;
2027 } else if (!strcmp(buf, "cdrom")) {
2028 if (cyls || secs || heads) {
2029 fprintf(stderr,
2030 "qemu: '%s' invalid physical CHS format\n", buf);
2031 return NULL;
2033 media = MEDIA_CDROM;
2034 } else {
2035 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2036 return NULL;
2040 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2041 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2042 cache = 0;
2043 else if (!strcmp(buf, "writethrough"))
2044 cache = 1;
2045 else if (!strcmp(buf, "writeback"))
2046 cache = 2;
2047 else {
2048 fprintf(stderr, "qemu: invalid cache option\n");
2049 return NULL;
2053 #ifdef CONFIG_LINUX_AIO
2054 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2055 if (!strcmp(buf, "threads"))
2056 aio = 0;
2057 else if (!strcmp(buf, "native"))
2058 aio = 1;
2059 else {
2060 fprintf(stderr, "qemu: invalid aio option\n");
2061 return NULL;
2064 #endif
2066 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2067 if (strcmp(buf, "?") == 0) {
2068 fprintf(stderr, "qemu: Supported formats:");
2069 bdrv_iterate_format(bdrv_format_print, NULL);
2070 fprintf(stderr, "\n");
2071 return NULL;
2073 drv = bdrv_find_format(buf);
2074 if (!drv) {
2075 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2076 return NULL;
2080 onerror = BLOCK_ERR_STOP_ENOSPC;
2081 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2082 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2083 fprintf(stderr, "werror is no supported by this format\n");
2084 return NULL;
2086 if (!strcmp(buf, "ignore"))
2087 onerror = BLOCK_ERR_IGNORE;
2088 else if (!strcmp(buf, "enospc"))
2089 onerror = BLOCK_ERR_STOP_ENOSPC;
2090 else if (!strcmp(buf, "stop"))
2091 onerror = BLOCK_ERR_STOP_ANY;
2092 else if (!strcmp(buf, "report"))
2093 onerror = BLOCK_ERR_REPORT;
2094 else {
2095 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2096 return NULL;
2100 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2101 if (type != IF_VIRTIO) {
2102 fprintf(stderr, "addr is not supported\n");
2103 return NULL;
2107 /* compute bus and unit according index */
2109 if (index != -1) {
2110 if (bus_id != 0 || unit_id != -1) {
2111 fprintf(stderr,
2112 "qemu: index cannot be used with bus and unit\n");
2113 return NULL;
2115 if (max_devs == 0)
2117 unit_id = index;
2118 bus_id = 0;
2119 } else {
2120 unit_id = index % max_devs;
2121 bus_id = index / max_devs;
2125 /* if user doesn't specify a unit_id,
2126 * try to find the first free
2129 if (unit_id == -1) {
2130 unit_id = 0;
2131 while (drive_get(type, bus_id, unit_id) != NULL) {
2132 unit_id++;
2133 if (max_devs && unit_id >= max_devs) {
2134 unit_id -= max_devs;
2135 bus_id++;
2140 /* check unit id */
2142 if (max_devs && unit_id >= max_devs) {
2143 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2144 unit_id, max_devs - 1);
2145 return NULL;
2149 * ignore multiple definitions
2152 if (drive_get(type, bus_id, unit_id) != NULL) {
2153 *fatal_error = 0;
2154 return NULL;
2157 /* init */
2159 dinfo = qemu_mallocz(sizeof(*dinfo));
2160 if ((buf = qemu_opts_id(opts)) != NULL) {
2161 dinfo->id = qemu_strdup(buf);
2162 } else {
2163 /* no id supplied -> create one */
2164 dinfo->id = qemu_mallocz(32);
2165 if (type == IF_IDE || type == IF_SCSI)
2166 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2167 if (max_devs)
2168 snprintf(dinfo->id, 32, "%s%i%s%i",
2169 devname, bus_id, mediastr, unit_id);
2170 else
2171 snprintf(dinfo->id, 32, "%s%s%i",
2172 devname, mediastr, unit_id);
2174 dinfo->bdrv = bdrv_new(dinfo->id);
2175 dinfo->devaddr = devaddr;
2176 dinfo->type = type;
2177 dinfo->bus = bus_id;
2178 dinfo->unit = unit_id;
2179 dinfo->onerror = onerror;
2180 dinfo->opts = opts;
2181 if (serial)
2182 strncpy(dinfo->serial, serial, sizeof(serial));
2183 TAILQ_INSERT_TAIL(&drives, dinfo, next);
2185 switch(type) {
2186 case IF_IDE:
2187 case IF_SCSI:
2188 case IF_XEN:
2189 switch(media) {
2190 case MEDIA_DISK:
2191 if (cyls != 0) {
2192 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2193 bdrv_set_translation_hint(dinfo->bdrv, translation);
2195 break;
2196 case MEDIA_CDROM:
2197 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2198 break;
2200 break;
2201 case IF_SD:
2202 /* FIXME: This isn't really a floppy, but it's a reasonable
2203 approximation. */
2204 case IF_FLOPPY:
2205 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2206 break;
2207 case IF_PFLASH:
2208 case IF_MTD:
2209 case IF_NONE:
2210 break;
2211 case IF_VIRTIO:
2212 /* add virtio block device */
2213 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2214 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2215 qemu_opt_set(opts, "drive", dinfo->id);
2216 if (devaddr)
2217 qemu_opt_set(opts, "addr", devaddr);
2218 break;
2219 case IF_COUNT:
2220 abort();
2222 if (!file) {
2223 *fatal_error = 0;
2224 return NULL;
2226 bdrv_flags = 0;
2227 if (snapshot) {
2228 bdrv_flags |= BDRV_O_SNAPSHOT;
2229 cache = 2; /* always use write-back with snapshot */
2231 if (cache == 0) /* no caching */
2232 bdrv_flags |= BDRV_O_NOCACHE;
2233 else if (cache == 2) /* write-back */
2234 bdrv_flags |= BDRV_O_CACHE_WB;
2236 if (aio == 1) {
2237 bdrv_flags |= BDRV_O_NATIVE_AIO;
2238 } else {
2239 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2242 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2243 fprintf(stderr, "qemu: could not open disk image %s\n",
2244 file);
2245 return NULL;
2248 if (bdrv_key_required(dinfo->bdrv))
2249 autostart = 0;
2250 *fatal_error = 0;
2251 return dinfo;
2254 static int drive_init_func(QemuOpts *opts, void *opaque)
2256 QEMUMachine *machine = opaque;
2257 int fatal_error = 0;
2259 if (drive_init(opts, machine, &fatal_error) == NULL) {
2260 if (fatal_error)
2261 return 1;
2263 return 0;
2266 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2268 if (NULL == qemu_opt_get(opts, "snapshot")) {
2269 qemu_opt_set(opts, "snapshot", "on");
2271 return 0;
2274 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2276 boot_set_handler = func;
2277 boot_set_opaque = opaque;
2280 int qemu_boot_set(const char *boot_devices)
2282 if (!boot_set_handler) {
2283 return -EINVAL;
2285 return boot_set_handler(boot_set_opaque, boot_devices);
2288 static int parse_bootdevices(char *devices)
2290 /* We just do some generic consistency checks */
2291 const char *p;
2292 int bitmap = 0;
2294 for (p = devices; *p != '\0'; p++) {
2295 /* Allowed boot devices are:
2296 * a-b: floppy disk drives
2297 * c-f: IDE disk drives
2298 * g-m: machine implementation dependant drives
2299 * n-p: network devices
2300 * It's up to each machine implementation to check if the given boot
2301 * devices match the actual hardware implementation and firmware
2302 * features.
2304 if (*p < 'a' || *p > 'p') {
2305 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2306 exit(1);
2308 if (bitmap & (1 << (*p - 'a'))) {
2309 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2310 exit(1);
2312 bitmap |= 1 << (*p - 'a');
2314 return bitmap;
2317 static void restore_boot_devices(void *opaque)
2319 char *standard_boot_devices = opaque;
2321 qemu_boot_set(standard_boot_devices);
2323 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2324 qemu_free(standard_boot_devices);
2327 static void numa_add(const char *optarg)
2329 char option[128];
2330 char *endptr;
2331 unsigned long long value, endvalue;
2332 int nodenr;
2334 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2335 if (!strcmp(option, "node")) {
2336 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2337 nodenr = nb_numa_nodes;
2338 } else {
2339 nodenr = strtoull(option, NULL, 10);
2342 if (get_param_value(option, 128, "mem", optarg) == 0) {
2343 node_mem[nodenr] = 0;
2344 } else {
2345 value = strtoull(option, &endptr, 0);
2346 switch (*endptr) {
2347 case 0: case 'M': case 'm':
2348 value <<= 20;
2349 break;
2350 case 'G': case 'g':
2351 value <<= 30;
2352 break;
2354 node_mem[nodenr] = value;
2356 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2357 node_cpumask[nodenr] = 0;
2358 } else {
2359 value = strtoull(option, &endptr, 10);
2360 if (value >= 64) {
2361 value = 63;
2362 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2363 } else {
2364 if (*endptr == '-') {
2365 endvalue = strtoull(endptr+1, &endptr, 10);
2366 if (endvalue >= 63) {
2367 endvalue = 62;
2368 fprintf(stderr,
2369 "only 63 CPUs in NUMA mode supported.\n");
2371 value = (1 << (endvalue + 1)) - (1 << value);
2372 } else {
2373 value = 1 << value;
2376 node_cpumask[nodenr] = value;
2378 nb_numa_nodes++;
2380 return;
2383 static void smp_parse(const char *optarg)
2385 int smp, sockets = 0, threads = 0, cores = 0;
2386 char *endptr;
2387 char option[128];
2389 smp = strtoul(optarg, &endptr, 10);
2390 if (endptr != optarg) {
2391 if (*endptr == ',') {
2392 endptr++;
2395 if (get_param_value(option, 128, "sockets", endptr) != 0)
2396 sockets = strtoull(option, NULL, 10);
2397 if (get_param_value(option, 128, "cores", endptr) != 0)
2398 cores = strtoull(option, NULL, 10);
2399 if (get_param_value(option, 128, "threads", endptr) != 0)
2400 threads = strtoull(option, NULL, 10);
2401 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2402 max_cpus = strtoull(option, NULL, 10);
2404 /* compute missing values, prefer sockets over cores over threads */
2405 if (smp == 0 || sockets == 0) {
2406 sockets = sockets > 0 ? sockets : 1;
2407 cores = cores > 0 ? cores : 1;
2408 threads = threads > 0 ? threads : 1;
2409 if (smp == 0) {
2410 smp = cores * threads * sockets;
2411 } else {
2412 sockets = smp / (cores * threads);
2414 } else {
2415 if (cores == 0) {
2416 threads = threads > 0 ? threads : 1;
2417 cores = smp / (sockets * threads);
2418 } else {
2419 if (sockets == 0) {
2420 sockets = smp / (cores * threads);
2421 } else {
2422 threads = smp / (cores * sockets);
2426 smp_cpus = smp;
2427 smp_cores = cores > 0 ? cores : 1;
2428 smp_threads = threads > 0 ? threads : 1;
2429 if (max_cpus == 0)
2430 max_cpus = smp_cpus;
2433 /***********************************************************/
2434 /* USB devices */
2436 static USBPort *used_usb_ports;
2437 static USBPort *free_usb_ports;
2439 /* ??? Maybe change this to register a hub to keep track of the topology. */
2440 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2441 usb_attachfn attach)
2443 port->opaque = opaque;
2444 port->index = index;
2445 port->attach = attach;
2446 port->next = free_usb_ports;
2447 free_usb_ports = port;
2450 int usb_device_add_dev(USBDevice *dev)
2452 USBPort *port;
2454 /* Find a USB port to add the device to. */
2455 port = free_usb_ports;
2456 if (!port->next) {
2457 USBDevice *hub;
2459 /* Create a new hub and chain it on. */
2460 free_usb_ports = NULL;
2461 port->next = used_usb_ports;
2462 used_usb_ports = port;
2464 hub = usb_hub_init(VM_USB_HUB_SIZE);
2465 usb_attach(port, hub);
2466 port = free_usb_ports;
2469 free_usb_ports = port->next;
2470 port->next = used_usb_ports;
2471 used_usb_ports = port;
2472 usb_attach(port, dev);
2473 return 0;
2476 static void usb_msd_password_cb(void *opaque, int err)
2478 USBDevice *dev = opaque;
2480 if (!err)
2481 usb_device_add_dev(dev);
2482 else
2483 dev->handle_destroy(dev);
2486 static int usb_device_add(const char *devname, int is_hotplug)
2488 const char *p;
2489 USBDevice *dev;
2491 if (!free_usb_ports)
2492 return -1;
2494 if (strstart(devname, "host:", &p)) {
2495 dev = usb_host_device_open(p);
2496 } else if (!strcmp(devname, "mouse")) {
2497 dev = usb_mouse_init();
2498 } else if (!strcmp(devname, "tablet")) {
2499 dev = usb_tablet_init();
2500 } else if (!strcmp(devname, "keyboard")) {
2501 dev = usb_keyboard_init();
2502 } else if (strstart(devname, "disk:", &p)) {
2503 BlockDriverState *bs;
2505 dev = usb_msd_init(p);
2506 if (!dev)
2507 return -1;
2508 bs = usb_msd_get_bdrv(dev);
2509 if (bdrv_key_required(bs)) {
2510 autostart = 0;
2511 if (is_hotplug) {
2512 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2513 dev);
2514 return 0;
2517 } else if (!strcmp(devname, "wacom-tablet")) {
2518 dev = usb_wacom_init();
2519 } else if (strstart(devname, "serial:", &p)) {
2520 dev = usb_serial_init(p);
2521 #ifdef CONFIG_BRLAPI
2522 } else if (!strcmp(devname, "braille")) {
2523 dev = usb_baum_init();
2524 #endif
2525 } else if (strstart(devname, "net:", &p)) {
2526 int nic = nb_nics;
2528 if (net_client_init(NULL, "nic", p) < 0)
2529 return -1;
2530 nd_table[nic].model = "usb";
2531 dev = usb_net_init(&nd_table[nic]);
2532 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2533 dev = usb_bt_init(devname[2] ? hci_init(p) :
2534 bt_new_hci(qemu_find_bt_vlan(0)));
2535 } else {
2536 return -1;
2538 if (!dev)
2539 return -1;
2541 return usb_device_add_dev(dev);
2544 int usb_device_del_addr(int bus_num, int addr)
2546 USBPort *port;
2547 USBPort **lastp;
2548 USBDevice *dev;
2550 if (!used_usb_ports)
2551 return -1;
2553 if (bus_num != 0)
2554 return -1;
2556 lastp = &used_usb_ports;
2557 port = used_usb_ports;
2558 while (port && port->dev->addr != addr) {
2559 lastp = &port->next;
2560 port = port->next;
2563 if (!port)
2564 return -1;
2566 dev = port->dev;
2567 *lastp = port->next;
2568 usb_attach(port, NULL);
2569 dev->handle_destroy(dev);
2570 port->next = free_usb_ports;
2571 free_usb_ports = port;
2572 return 0;
2575 static int usb_device_del(const char *devname)
2577 int bus_num, addr;
2578 const char *p;
2580 if (strstart(devname, "host:", &p))
2581 return usb_host_device_close(p);
2583 if (!used_usb_ports)
2584 return -1;
2586 p = strchr(devname, '.');
2587 if (!p)
2588 return -1;
2589 bus_num = strtoul(devname, NULL, 0);
2590 addr = strtoul(p + 1, NULL, 0);
2592 return usb_device_del_addr(bus_num, addr);
2595 static int usb_parse(const char *cmdline)
2597 return usb_device_add(cmdline, 0);
2600 void do_usb_add(Monitor *mon, const char *devname)
2602 usb_device_add(devname, 1);
2605 void do_usb_del(Monitor *mon, const char *devname)
2607 usb_device_del(devname);
2610 void usb_info(Monitor *mon)
2612 USBDevice *dev;
2613 USBPort *port;
2614 const char *speed_str;
2616 if (!usb_enabled) {
2617 monitor_printf(mon, "USB support not enabled\n");
2618 return;
2621 for (port = used_usb_ports; port; port = port->next) {
2622 dev = port->dev;
2623 if (!dev)
2624 continue;
2625 switch(dev->speed) {
2626 case USB_SPEED_LOW:
2627 speed_str = "1.5";
2628 break;
2629 case USB_SPEED_FULL:
2630 speed_str = "12";
2631 break;
2632 case USB_SPEED_HIGH:
2633 speed_str = "480";
2634 break;
2635 default:
2636 speed_str = "?";
2637 break;
2639 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2640 0, dev->addr, speed_str, dev->devname);
2644 /***********************************************************/
2645 /* PCMCIA/Cardbus */
2647 static struct pcmcia_socket_entry_s {
2648 PCMCIASocket *socket;
2649 struct pcmcia_socket_entry_s *next;
2650 } *pcmcia_sockets = 0;
2652 void pcmcia_socket_register(PCMCIASocket *socket)
2654 struct pcmcia_socket_entry_s *entry;
2656 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2657 entry->socket = socket;
2658 entry->next = pcmcia_sockets;
2659 pcmcia_sockets = entry;
2662 void pcmcia_socket_unregister(PCMCIASocket *socket)
2664 struct pcmcia_socket_entry_s *entry, **ptr;
2666 ptr = &pcmcia_sockets;
2667 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2668 if (entry->socket == socket) {
2669 *ptr = entry->next;
2670 qemu_free(entry);
2674 void pcmcia_info(Monitor *mon)
2676 struct pcmcia_socket_entry_s *iter;
2678 if (!pcmcia_sockets)
2679 monitor_printf(mon, "No PCMCIA sockets\n");
2681 for (iter = pcmcia_sockets; iter; iter = iter->next)
2682 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2683 iter->socket->attached ? iter->socket->card_string :
2684 "Empty");
2687 /***********************************************************/
2688 /* register display */
2690 struct DisplayAllocator default_allocator = {
2691 defaultallocator_create_displaysurface,
2692 defaultallocator_resize_displaysurface,
2693 defaultallocator_free_displaysurface
2696 void register_displaystate(DisplayState *ds)
2698 DisplayState **s;
2699 s = &display_state;
2700 while (*s != NULL)
2701 s = &(*s)->next;
2702 ds->next = NULL;
2703 *s = ds;
2706 DisplayState *get_displaystate(void)
2708 return display_state;
2711 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2713 if(ds->allocator == &default_allocator) ds->allocator = da;
2714 return ds->allocator;
2717 /* dumb display */
2719 static void dumb_display_init(void)
2721 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2722 ds->allocator = &default_allocator;
2723 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2724 register_displaystate(ds);
2727 /***********************************************************/
2728 /* I/O handling */
2730 typedef struct IOHandlerRecord {
2731 int fd;
2732 IOCanRWHandler *fd_read_poll;
2733 IOHandler *fd_read;
2734 IOHandler *fd_write;
2735 int deleted;
2736 void *opaque;
2737 /* temporary data */
2738 struct pollfd *ufd;
2739 struct IOHandlerRecord *next;
2740 } IOHandlerRecord;
2742 static IOHandlerRecord *first_io_handler;
2744 /* XXX: fd_read_poll should be suppressed, but an API change is
2745 necessary in the character devices to suppress fd_can_read(). */
2746 int qemu_set_fd_handler2(int fd,
2747 IOCanRWHandler *fd_read_poll,
2748 IOHandler *fd_read,
2749 IOHandler *fd_write,
2750 void *opaque)
2752 IOHandlerRecord **pioh, *ioh;
2754 if (!fd_read && !fd_write) {
2755 pioh = &first_io_handler;
2756 for(;;) {
2757 ioh = *pioh;
2758 if (ioh == NULL)
2759 break;
2760 if (ioh->fd == fd) {
2761 ioh->deleted = 1;
2762 break;
2764 pioh = &ioh->next;
2766 } else {
2767 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2768 if (ioh->fd == fd)
2769 goto found;
2771 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2772 ioh->next = first_io_handler;
2773 first_io_handler = ioh;
2774 found:
2775 ioh->fd = fd;
2776 ioh->fd_read_poll = fd_read_poll;
2777 ioh->fd_read = fd_read;
2778 ioh->fd_write = fd_write;
2779 ioh->opaque = opaque;
2780 ioh->deleted = 0;
2782 return 0;
2785 int qemu_set_fd_handler(int fd,
2786 IOHandler *fd_read,
2787 IOHandler *fd_write,
2788 void *opaque)
2790 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2793 #ifdef _WIN32
2794 /***********************************************************/
2795 /* Polling handling */
2797 typedef struct PollingEntry {
2798 PollingFunc *func;
2799 void *opaque;
2800 struct PollingEntry *next;
2801 } PollingEntry;
2803 static PollingEntry *first_polling_entry;
2805 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2807 PollingEntry **ppe, *pe;
2808 pe = qemu_mallocz(sizeof(PollingEntry));
2809 pe->func = func;
2810 pe->opaque = opaque;
2811 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2812 *ppe = pe;
2813 return 0;
2816 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2818 PollingEntry **ppe, *pe;
2819 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2820 pe = *ppe;
2821 if (pe->func == func && pe->opaque == opaque) {
2822 *ppe = pe->next;
2823 qemu_free(pe);
2824 break;
2829 /***********************************************************/
2830 /* Wait objects support */
2831 typedef struct WaitObjects {
2832 int num;
2833 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2834 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2835 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2836 } WaitObjects;
2838 static WaitObjects wait_objects = {0};
2840 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2842 WaitObjects *w = &wait_objects;
2844 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2845 return -1;
2846 w->events[w->num] = handle;
2847 w->func[w->num] = func;
2848 w->opaque[w->num] = opaque;
2849 w->num++;
2850 return 0;
2853 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2855 int i, found;
2856 WaitObjects *w = &wait_objects;
2858 found = 0;
2859 for (i = 0; i < w->num; i++) {
2860 if (w->events[i] == handle)
2861 found = 1;
2862 if (found) {
2863 w->events[i] = w->events[i + 1];
2864 w->func[i] = w->func[i + 1];
2865 w->opaque[i] = w->opaque[i + 1];
2868 if (found)
2869 w->num--;
2871 #endif
2873 /***********************************************************/
2874 /* ram save/restore */
2876 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2878 int v;
2880 v = qemu_get_byte(f);
2881 switch(v) {
2882 case 0:
2883 if (qemu_get_buffer(f, buf, len) != len)
2884 return -EIO;
2885 break;
2886 case 1:
2887 v = qemu_get_byte(f);
2888 memset(buf, v, len);
2889 break;
2890 default:
2891 return -EINVAL;
2894 if (qemu_file_has_error(f))
2895 return -EIO;
2897 return 0;
2900 static int ram_load_v1(QEMUFile *f, void *opaque)
2902 int ret;
2903 ram_addr_t i;
2905 if (qemu_get_be32(f) != last_ram_offset)
2906 return -EINVAL;
2907 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2908 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2909 if (ret)
2910 return ret;
2912 return 0;
2915 #define BDRV_HASH_BLOCK_SIZE 1024
2916 #define IOBUF_SIZE 4096
2917 #define RAM_CBLOCK_MAGIC 0xfabe
2919 typedef struct RamDecompressState {
2920 z_stream zstream;
2921 QEMUFile *f;
2922 uint8_t buf[IOBUF_SIZE];
2923 } RamDecompressState;
2925 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2927 int ret;
2928 memset(s, 0, sizeof(*s));
2929 s->f = f;
2930 ret = inflateInit(&s->zstream);
2931 if (ret != Z_OK)
2932 return -1;
2933 return 0;
2936 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2938 int ret, clen;
2940 s->zstream.avail_out = len;
2941 s->zstream.next_out = buf;
2942 while (s->zstream.avail_out > 0) {
2943 if (s->zstream.avail_in == 0) {
2944 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
2945 return -1;
2946 clen = qemu_get_be16(s->f);
2947 if (clen > IOBUF_SIZE)
2948 return -1;
2949 qemu_get_buffer(s->f, s->buf, clen);
2950 s->zstream.avail_in = clen;
2951 s->zstream.next_in = s->buf;
2953 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
2954 if (ret != Z_OK && ret != Z_STREAM_END) {
2955 return -1;
2958 return 0;
2961 static void ram_decompress_close(RamDecompressState *s)
2963 inflateEnd(&s->zstream);
2966 #define RAM_SAVE_FLAG_FULL 0x01
2967 #define RAM_SAVE_FLAG_COMPRESS 0x02
2968 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2969 #define RAM_SAVE_FLAG_PAGE 0x08
2970 #define RAM_SAVE_FLAG_EOS 0x10
2972 static int is_dup_page(uint8_t *page, uint8_t ch)
2974 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2975 uint32_t *array = (uint32_t *)page;
2976 int i;
2978 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2979 if (array[i] != val)
2980 return 0;
2983 return 1;
2986 static int ram_save_block(QEMUFile *f)
2988 static ram_addr_t current_addr = 0;
2989 ram_addr_t saved_addr = current_addr;
2990 ram_addr_t addr = 0;
2991 int found = 0;
2993 while (addr < last_ram_offset) {
2994 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2995 uint8_t *p;
2997 cpu_physical_memory_reset_dirty(current_addr,
2998 current_addr + TARGET_PAGE_SIZE,
2999 MIGRATION_DIRTY_FLAG);
3001 p = qemu_get_ram_ptr(current_addr);
3003 if (is_dup_page(p, *p)) {
3004 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3005 qemu_put_byte(f, *p);
3006 } else {
3007 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3008 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3011 found = 1;
3012 break;
3014 addr += TARGET_PAGE_SIZE;
3015 current_addr = (saved_addr + addr) % last_ram_offset;
3018 return found;
3021 static uint64_t bytes_transferred = 0;
3023 static ram_addr_t ram_save_remaining(void)
3025 ram_addr_t addr;
3026 ram_addr_t count = 0;
3028 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3029 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3030 count++;
3033 return count;
3036 uint64_t ram_bytes_remaining(void)
3038 return ram_save_remaining() * TARGET_PAGE_SIZE;
3041 uint64_t ram_bytes_transferred(void)
3043 return bytes_transferred;
3046 uint64_t ram_bytes_total(void)
3048 return last_ram_offset;
3051 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3053 ram_addr_t addr;
3054 uint64_t bytes_transferred_last;
3055 double bwidth = 0;
3056 uint64_t expected_time = 0;
3058 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3059 qemu_file_set_error(f);
3060 return 0;
3063 if (stage == 1) {
3064 /* Make sure all dirty bits are set */
3065 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3066 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3067 cpu_physical_memory_set_dirty(addr);
3070 /* Enable dirty memory tracking */
3071 cpu_physical_memory_set_dirty_tracking(1);
3073 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3076 bytes_transferred_last = bytes_transferred;
3077 bwidth = get_clock();
3079 while (!qemu_file_rate_limit(f)) {
3080 int ret;
3082 ret = ram_save_block(f);
3083 bytes_transferred += ret * TARGET_PAGE_SIZE;
3084 if (ret == 0) /* no more blocks */
3085 break;
3088 bwidth = get_clock() - bwidth;
3089 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3091 /* if we haven't transferred anything this round, force expected_time to a
3092 * a very high value, but without crashing */
3093 if (bwidth == 0)
3094 bwidth = 0.000001;
3096 /* try transferring iterative blocks of memory */
3098 if (stage == 3) {
3100 /* flush all remaining blocks regardless of rate limiting */
3101 while (ram_save_block(f) != 0) {
3102 bytes_transferred += TARGET_PAGE_SIZE;
3104 cpu_physical_memory_set_dirty_tracking(0);
3107 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3109 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3111 return (stage == 2) && (expected_time <= migrate_max_downtime());
3114 static int ram_load_dead(QEMUFile *f, void *opaque)
3116 RamDecompressState s1, *s = &s1;
3117 uint8_t buf[10];
3118 ram_addr_t i;
3120 if (ram_decompress_open(s, f) < 0)
3121 return -EINVAL;
3122 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3123 if (ram_decompress_buf(s, buf, 1) < 0) {
3124 fprintf(stderr, "Error while reading ram block header\n");
3125 goto error;
3127 if (buf[0] == 0) {
3128 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3129 BDRV_HASH_BLOCK_SIZE) < 0) {
3130 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3131 goto error;
3133 } else {
3134 error:
3135 printf("Error block header\n");
3136 return -EINVAL;
3139 ram_decompress_close(s);
3141 return 0;
3144 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3146 ram_addr_t addr;
3147 int flags;
3149 if (version_id == 1)
3150 return ram_load_v1(f, opaque);
3152 if (version_id == 2) {
3153 if (qemu_get_be32(f) != last_ram_offset)
3154 return -EINVAL;
3155 return ram_load_dead(f, opaque);
3158 if (version_id != 3)
3159 return -EINVAL;
3161 do {
3162 addr = qemu_get_be64(f);
3164 flags = addr & ~TARGET_PAGE_MASK;
3165 addr &= TARGET_PAGE_MASK;
3167 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3168 if (addr != last_ram_offset)
3169 return -EINVAL;
3172 if (flags & RAM_SAVE_FLAG_FULL) {
3173 if (ram_load_dead(f, opaque) < 0)
3174 return -EINVAL;
3177 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3178 uint8_t ch = qemu_get_byte(f);
3179 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3180 #ifndef _WIN32
3181 if (ch == 0 &&
3182 (!kvm_enabled() || kvm_has_sync_mmu())) {
3183 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3185 #endif
3186 } else if (flags & RAM_SAVE_FLAG_PAGE)
3187 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3188 } while (!(flags & RAM_SAVE_FLAG_EOS));
3190 return 0;
3193 void qemu_service_io(void)
3195 qemu_notify_event();
3198 /***********************************************************/
3199 /* bottom halves (can be seen as timers which expire ASAP) */
3201 struct QEMUBH {
3202 QEMUBHFunc *cb;
3203 void *opaque;
3204 int scheduled;
3205 int idle;
3206 int deleted;
3207 QEMUBH *next;
3210 static QEMUBH *first_bh = NULL;
3212 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3214 QEMUBH *bh;
3215 bh = qemu_mallocz(sizeof(QEMUBH));
3216 bh->cb = cb;
3217 bh->opaque = opaque;
3218 bh->next = first_bh;
3219 first_bh = bh;
3220 return bh;
3223 int qemu_bh_poll(void)
3225 QEMUBH *bh, **bhp;
3226 int ret;
3228 ret = 0;
3229 for (bh = first_bh; bh; bh = bh->next) {
3230 if (!bh->deleted && bh->scheduled) {
3231 bh->scheduled = 0;
3232 if (!bh->idle)
3233 ret = 1;
3234 bh->idle = 0;
3235 bh->cb(bh->opaque);
3239 /* remove deleted bhs */
3240 bhp = &first_bh;
3241 while (*bhp) {
3242 bh = *bhp;
3243 if (bh->deleted) {
3244 *bhp = bh->next;
3245 qemu_free(bh);
3246 } else
3247 bhp = &bh->next;
3250 return ret;
3253 void qemu_bh_schedule_idle(QEMUBH *bh)
3255 if (bh->scheduled)
3256 return;
3257 bh->scheduled = 1;
3258 bh->idle = 1;
3261 void qemu_bh_schedule(QEMUBH *bh)
3263 if (bh->scheduled)
3264 return;
3265 bh->scheduled = 1;
3266 bh->idle = 0;
3267 /* stop the currently executing CPU to execute the BH ASAP */
3268 qemu_notify_event();
3271 void qemu_bh_cancel(QEMUBH *bh)
3273 bh->scheduled = 0;
3276 void qemu_bh_delete(QEMUBH *bh)
3278 bh->scheduled = 0;
3279 bh->deleted = 1;
3282 static void qemu_bh_update_timeout(int *timeout)
3284 QEMUBH *bh;
3286 for (bh = first_bh; bh; bh = bh->next) {
3287 if (!bh->deleted && bh->scheduled) {
3288 if (bh->idle) {
3289 /* idle bottom halves will be polled at least
3290 * every 10ms */
3291 *timeout = MIN(10, *timeout);
3292 } else {
3293 /* non-idle bottom halves will be executed
3294 * immediately */
3295 *timeout = 0;
3296 break;
3302 /***********************************************************/
3303 /* machine registration */
3305 static QEMUMachine *first_machine = NULL;
3306 QEMUMachine *current_machine = NULL;
3308 int qemu_register_machine(QEMUMachine *m)
3310 QEMUMachine **pm;
3311 pm = &first_machine;
3312 while (*pm != NULL)
3313 pm = &(*pm)->next;
3314 m->next = NULL;
3315 *pm = m;
3316 return 0;
3319 static QEMUMachine *find_machine(const char *name)
3321 QEMUMachine *m;
3323 for(m = first_machine; m != NULL; m = m->next) {
3324 if (!strcmp(m->name, name))
3325 return m;
3326 if (m->alias && !strcmp(m->alias, name))
3327 return m;
3329 return NULL;
3332 static QEMUMachine *find_default_machine(void)
3334 QEMUMachine *m;
3336 for(m = first_machine; m != NULL; m = m->next) {
3337 if (m->is_default) {
3338 return m;
3341 return NULL;
3344 /***********************************************************/
3345 /* main execution loop */
3347 static void gui_update(void *opaque)
3349 uint64_t interval = GUI_REFRESH_INTERVAL;
3350 DisplayState *ds = opaque;
3351 DisplayChangeListener *dcl = ds->listeners;
3353 dpy_refresh(ds);
3355 while (dcl != NULL) {
3356 if (dcl->gui_timer_interval &&
3357 dcl->gui_timer_interval < interval)
3358 interval = dcl->gui_timer_interval;
3359 dcl = dcl->next;
3361 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3364 static void nographic_update(void *opaque)
3366 uint64_t interval = GUI_REFRESH_INTERVAL;
3368 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3371 struct vm_change_state_entry {
3372 VMChangeStateHandler *cb;
3373 void *opaque;
3374 LIST_ENTRY (vm_change_state_entry) entries;
3377 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3379 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3380 void *opaque)
3382 VMChangeStateEntry *e;
3384 e = qemu_mallocz(sizeof (*e));
3386 e->cb = cb;
3387 e->opaque = opaque;
3388 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3389 return e;
3392 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3394 LIST_REMOVE (e, entries);
3395 qemu_free (e);
3398 static void vm_state_notify(int running, int reason)
3400 VMChangeStateEntry *e;
3402 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3403 e->cb(e->opaque, running, reason);
3407 static void resume_all_vcpus(void);
3408 static void pause_all_vcpus(void);
3410 void vm_start(void)
3412 if (!vm_running) {
3413 cpu_enable_ticks();
3414 vm_running = 1;
3415 vm_state_notify(1, 0);
3416 qemu_rearm_alarm_timer(alarm_timer);
3417 resume_all_vcpus();
3421 /* reset/shutdown handler */
3423 typedef struct QEMUResetEntry {
3424 TAILQ_ENTRY(QEMUResetEntry) entry;
3425 QEMUResetHandler *func;
3426 void *opaque;
3427 } QEMUResetEntry;
3429 static TAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3430 TAILQ_HEAD_INITIALIZER(reset_handlers);
3431 static int reset_requested;
3432 static int shutdown_requested;
3433 static int powerdown_requested;
3434 static int debug_requested;
3435 static int vmstop_requested;
3437 int qemu_shutdown_requested(void)
3439 int r = shutdown_requested;
3440 shutdown_requested = 0;
3441 return r;
3444 int qemu_reset_requested(void)
3446 int r = reset_requested;
3447 reset_requested = 0;
3448 return r;
3451 int qemu_powerdown_requested(void)
3453 int r = powerdown_requested;
3454 powerdown_requested = 0;
3455 return r;
3458 static int qemu_debug_requested(void)
3460 int r = debug_requested;
3461 debug_requested = 0;
3462 return r;
3465 static int qemu_vmstop_requested(void)
3467 int r = vmstop_requested;
3468 vmstop_requested = 0;
3469 return r;
3472 static void do_vm_stop(int reason)
3474 if (vm_running) {
3475 cpu_disable_ticks();
3476 vm_running = 0;
3477 pause_all_vcpus();
3478 vm_state_notify(0, reason);
3482 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3484 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3486 re->func = func;
3487 re->opaque = opaque;
3488 TAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3491 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3493 QEMUResetEntry *re;
3495 TAILQ_FOREACH(re, &reset_handlers, entry) {
3496 if (re->func == func && re->opaque == opaque) {
3497 TAILQ_REMOVE(&reset_handlers, re, entry);
3498 qemu_free(re);
3499 return;
3504 void qemu_system_reset(void)
3506 QEMUResetEntry *re, *nre;
3508 /* reset all devices */
3509 TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3510 re->func(re->opaque);
3514 void qemu_system_reset_request(void)
3516 if (no_reboot) {
3517 shutdown_requested = 1;
3518 } else {
3519 reset_requested = 1;
3521 qemu_notify_event();
3524 void qemu_system_shutdown_request(void)
3526 shutdown_requested = 1;
3527 qemu_notify_event();
3530 void qemu_system_powerdown_request(void)
3532 powerdown_requested = 1;
3533 qemu_notify_event();
3536 #ifdef CONFIG_IOTHREAD
3537 static void qemu_system_vmstop_request(int reason)
3539 vmstop_requested = reason;
3540 qemu_notify_event();
3542 #endif
3544 #ifndef _WIN32
3545 static int io_thread_fd = -1;
3547 static void qemu_event_increment(void)
3549 static const char byte = 0;
3551 if (io_thread_fd == -1)
3552 return;
3554 write(io_thread_fd, &byte, sizeof(byte));
3557 static void qemu_event_read(void *opaque)
3559 int fd = (unsigned long)opaque;
3560 ssize_t len;
3562 /* Drain the notify pipe */
3563 do {
3564 char buffer[512];
3565 len = read(fd, buffer, sizeof(buffer));
3566 } while ((len == -1 && errno == EINTR) || len > 0);
3569 static int qemu_event_init(void)
3571 int err;
3572 int fds[2];
3574 err = pipe(fds);
3575 if (err == -1)
3576 return -errno;
3578 err = fcntl_setfl(fds[0], O_NONBLOCK);
3579 if (err < 0)
3580 goto fail;
3582 err = fcntl_setfl(fds[1], O_NONBLOCK);
3583 if (err < 0)
3584 goto fail;
3586 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3587 (void *)(unsigned long)fds[0]);
3589 io_thread_fd = fds[1];
3590 return 0;
3592 fail:
3593 close(fds[0]);
3594 close(fds[1]);
3595 return err;
3597 #else
3598 HANDLE qemu_event_handle;
3600 static void dummy_event_handler(void *opaque)
3604 static int qemu_event_init(void)
3606 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3607 if (!qemu_event_handle) {
3608 perror("Failed CreateEvent");
3609 return -1;
3611 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3612 return 0;
3615 static void qemu_event_increment(void)
3617 SetEvent(qemu_event_handle);
3619 #endif
3621 static int cpu_can_run(CPUState *env)
3623 if (env->stop)
3624 return 0;
3625 if (env->stopped)
3626 return 0;
3627 return 1;
3630 #ifndef CONFIG_IOTHREAD
3631 static int qemu_init_main_loop(void)
3633 return qemu_event_init();
3636 void qemu_init_vcpu(void *_env)
3638 CPUState *env = _env;
3640 if (kvm_enabled())
3641 kvm_init_vcpu(env);
3642 env->nr_cores = smp_cores;
3643 env->nr_threads = smp_threads;
3644 return;
3647 int qemu_cpu_self(void *env)
3649 return 1;
3652 static void resume_all_vcpus(void)
3656 static void pause_all_vcpus(void)
3660 void qemu_cpu_kick(void *env)
3662 return;
3665 void qemu_notify_event(void)
3667 CPUState *env = cpu_single_env;
3669 if (env) {
3670 cpu_exit(env);
3674 #define qemu_mutex_lock_iothread() do { } while (0)
3675 #define qemu_mutex_unlock_iothread() do { } while (0)
3677 void vm_stop(int reason)
3679 do_vm_stop(reason);
3682 #else /* CONFIG_IOTHREAD */
3684 #include "qemu-thread.h"
3686 QemuMutex qemu_global_mutex;
3687 static QemuMutex qemu_fair_mutex;
3689 static QemuThread io_thread;
3691 static QemuThread *tcg_cpu_thread;
3692 static QemuCond *tcg_halt_cond;
3694 static int qemu_system_ready;
3695 /* cpu creation */
3696 static QemuCond qemu_cpu_cond;
3697 /* system init */
3698 static QemuCond qemu_system_cond;
3699 static QemuCond qemu_pause_cond;
3701 static void block_io_signals(void);
3702 static void unblock_io_signals(void);
3703 static int tcg_has_work(void);
3705 static int qemu_init_main_loop(void)
3707 int ret;
3709 ret = qemu_event_init();
3710 if (ret)
3711 return ret;
3713 qemu_cond_init(&qemu_pause_cond);
3714 qemu_mutex_init(&qemu_fair_mutex);
3715 qemu_mutex_init(&qemu_global_mutex);
3716 qemu_mutex_lock(&qemu_global_mutex);
3718 unblock_io_signals();
3719 qemu_thread_self(&io_thread);
3721 return 0;
3724 static void qemu_wait_io_event(CPUState *env)
3726 while (!tcg_has_work())
3727 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3729 qemu_mutex_unlock(&qemu_global_mutex);
3732 * Users of qemu_global_mutex can be starved, having no chance
3733 * to acquire it since this path will get to it first.
3734 * So use another lock to provide fairness.
3736 qemu_mutex_lock(&qemu_fair_mutex);
3737 qemu_mutex_unlock(&qemu_fair_mutex);
3739 qemu_mutex_lock(&qemu_global_mutex);
3740 if (env->stop) {
3741 env->stop = 0;
3742 env->stopped = 1;
3743 qemu_cond_signal(&qemu_pause_cond);
3747 static int qemu_cpu_exec(CPUState *env);
3749 static void *kvm_cpu_thread_fn(void *arg)
3751 CPUState *env = arg;
3753 block_io_signals();
3754 qemu_thread_self(env->thread);
3756 /* signal CPU creation */
3757 qemu_mutex_lock(&qemu_global_mutex);
3758 env->created = 1;
3759 qemu_cond_signal(&qemu_cpu_cond);
3761 /* and wait for machine initialization */
3762 while (!qemu_system_ready)
3763 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3765 while (1) {
3766 if (cpu_can_run(env))
3767 qemu_cpu_exec(env);
3768 qemu_wait_io_event(env);
3771 return NULL;
3774 static void tcg_cpu_exec(void);
3776 static void *tcg_cpu_thread_fn(void *arg)
3778 CPUState *env = arg;
3780 block_io_signals();
3781 qemu_thread_self(env->thread);
3783 /* signal CPU creation */
3784 qemu_mutex_lock(&qemu_global_mutex);
3785 for (env = first_cpu; env != NULL; env = env->next_cpu)
3786 env->created = 1;
3787 qemu_cond_signal(&qemu_cpu_cond);
3789 /* and wait for machine initialization */
3790 while (!qemu_system_ready)
3791 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3793 while (1) {
3794 tcg_cpu_exec();
3795 qemu_wait_io_event(cur_cpu);
3798 return NULL;
3801 void qemu_cpu_kick(void *_env)
3803 CPUState *env = _env;
3804 qemu_cond_broadcast(env->halt_cond);
3805 if (kvm_enabled())
3806 qemu_thread_signal(env->thread, SIGUSR1);
3809 int qemu_cpu_self(void *env)
3811 return (cpu_single_env != NULL);
3814 static void cpu_signal(int sig)
3816 if (cpu_single_env)
3817 cpu_exit(cpu_single_env);
3820 static void block_io_signals(void)
3822 sigset_t set;
3823 struct sigaction sigact;
3825 sigemptyset(&set);
3826 sigaddset(&set, SIGUSR2);
3827 sigaddset(&set, SIGIO);
3828 sigaddset(&set, SIGALRM);
3829 pthread_sigmask(SIG_BLOCK, &set, NULL);
3831 sigemptyset(&set);
3832 sigaddset(&set, SIGUSR1);
3833 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3835 memset(&sigact, 0, sizeof(sigact));
3836 sigact.sa_handler = cpu_signal;
3837 sigaction(SIGUSR1, &sigact, NULL);
3840 static void unblock_io_signals(void)
3842 sigset_t set;
3844 sigemptyset(&set);
3845 sigaddset(&set, SIGUSR2);
3846 sigaddset(&set, SIGIO);
3847 sigaddset(&set, SIGALRM);
3848 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3850 sigemptyset(&set);
3851 sigaddset(&set, SIGUSR1);
3852 pthread_sigmask(SIG_BLOCK, &set, NULL);
3855 static void qemu_signal_lock(unsigned int msecs)
3857 qemu_mutex_lock(&qemu_fair_mutex);
3859 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3860 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3861 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3862 break;
3864 qemu_mutex_unlock(&qemu_fair_mutex);
3867 static void qemu_mutex_lock_iothread(void)
3869 if (kvm_enabled()) {
3870 qemu_mutex_lock(&qemu_fair_mutex);
3871 qemu_mutex_lock(&qemu_global_mutex);
3872 qemu_mutex_unlock(&qemu_fair_mutex);
3873 } else
3874 qemu_signal_lock(100);
3877 static void qemu_mutex_unlock_iothread(void)
3879 qemu_mutex_unlock(&qemu_global_mutex);
3882 static int all_vcpus_paused(void)
3884 CPUState *penv = first_cpu;
3886 while (penv) {
3887 if (!penv->stopped)
3888 return 0;
3889 penv = (CPUState *)penv->next_cpu;
3892 return 1;
3895 static void pause_all_vcpus(void)
3897 CPUState *penv = first_cpu;
3899 while (penv) {
3900 penv->stop = 1;
3901 qemu_thread_signal(penv->thread, SIGUSR1);
3902 qemu_cpu_kick(penv);
3903 penv = (CPUState *)penv->next_cpu;
3906 while (!all_vcpus_paused()) {
3907 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3908 penv = first_cpu;
3909 while (penv) {
3910 qemu_thread_signal(penv->thread, SIGUSR1);
3911 penv = (CPUState *)penv->next_cpu;
3916 static void resume_all_vcpus(void)
3918 CPUState *penv = first_cpu;
3920 while (penv) {
3921 penv->stop = 0;
3922 penv->stopped = 0;
3923 qemu_thread_signal(penv->thread, SIGUSR1);
3924 qemu_cpu_kick(penv);
3925 penv = (CPUState *)penv->next_cpu;
3929 static void tcg_init_vcpu(void *_env)
3931 CPUState *env = _env;
3932 /* share a single thread for all cpus with TCG */
3933 if (!tcg_cpu_thread) {
3934 env->thread = qemu_mallocz(sizeof(QemuThread));
3935 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3936 qemu_cond_init(env->halt_cond);
3937 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3938 while (env->created == 0)
3939 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3940 tcg_cpu_thread = env->thread;
3941 tcg_halt_cond = env->halt_cond;
3942 } else {
3943 env->thread = tcg_cpu_thread;
3944 env->halt_cond = tcg_halt_cond;
3948 static void kvm_start_vcpu(CPUState *env)
3950 kvm_init_vcpu(env);
3951 env->thread = qemu_mallocz(sizeof(QemuThread));
3952 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3953 qemu_cond_init(env->halt_cond);
3954 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3955 while (env->created == 0)
3956 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3959 void qemu_init_vcpu(void *_env)
3961 CPUState *env = _env;
3963 if (kvm_enabled())
3964 kvm_start_vcpu(env);
3965 else
3966 tcg_init_vcpu(env);
3967 env->nr_cores = smp_cores;
3968 env->nr_threads = smp_threads;
3971 void qemu_notify_event(void)
3973 qemu_event_increment();
3976 void vm_stop(int reason)
3978 QemuThread me;
3979 qemu_thread_self(&me);
3981 if (!qemu_thread_equal(&me, &io_thread)) {
3982 qemu_system_vmstop_request(reason);
3984 * FIXME: should not return to device code in case
3985 * vm_stop() has been requested.
3987 if (cpu_single_env) {
3988 cpu_exit(cpu_single_env);
3989 cpu_single_env->stop = 1;
3991 return;
3993 do_vm_stop(reason);
3996 #endif
3999 #ifdef _WIN32
4000 static void host_main_loop_wait(int *timeout)
4002 int ret, ret2, i;
4003 PollingEntry *pe;
4006 /* XXX: need to suppress polling by better using win32 events */
4007 ret = 0;
4008 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4009 ret |= pe->func(pe->opaque);
4011 if (ret == 0) {
4012 int err;
4013 WaitObjects *w = &wait_objects;
4015 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4016 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4017 if (w->func[ret - WAIT_OBJECT_0])
4018 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4020 /* Check for additional signaled events */
4021 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4023 /* Check if event is signaled */
4024 ret2 = WaitForSingleObject(w->events[i], 0);
4025 if(ret2 == WAIT_OBJECT_0) {
4026 if (w->func[i])
4027 w->func[i](w->opaque[i]);
4028 } else if (ret2 == WAIT_TIMEOUT) {
4029 } else {
4030 err = GetLastError();
4031 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4034 } else if (ret == WAIT_TIMEOUT) {
4035 } else {
4036 err = GetLastError();
4037 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4041 *timeout = 0;
4043 #else
4044 static void host_main_loop_wait(int *timeout)
4047 #endif
4049 void main_loop_wait(int timeout)
4051 IOHandlerRecord *ioh;
4052 fd_set rfds, wfds, xfds;
4053 int ret, nfds;
4054 struct timeval tv;
4056 qemu_bh_update_timeout(&timeout);
4058 host_main_loop_wait(&timeout);
4060 /* poll any events */
4061 /* XXX: separate device handlers from system ones */
4062 nfds = -1;
4063 FD_ZERO(&rfds);
4064 FD_ZERO(&wfds);
4065 FD_ZERO(&xfds);
4066 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4067 if (ioh->deleted)
4068 continue;
4069 if (ioh->fd_read &&
4070 (!ioh->fd_read_poll ||
4071 ioh->fd_read_poll(ioh->opaque) != 0)) {
4072 FD_SET(ioh->fd, &rfds);
4073 if (ioh->fd > nfds)
4074 nfds = ioh->fd;
4076 if (ioh->fd_write) {
4077 FD_SET(ioh->fd, &wfds);
4078 if (ioh->fd > nfds)
4079 nfds = ioh->fd;
4083 tv.tv_sec = timeout / 1000;
4084 tv.tv_usec = (timeout % 1000) * 1000;
4086 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4088 qemu_mutex_unlock_iothread();
4089 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4090 qemu_mutex_lock_iothread();
4091 if (ret > 0) {
4092 IOHandlerRecord **pioh;
4094 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4095 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4096 ioh->fd_read(ioh->opaque);
4098 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4099 ioh->fd_write(ioh->opaque);
4103 /* remove deleted IO handlers */
4104 pioh = &first_io_handler;
4105 while (*pioh) {
4106 ioh = *pioh;
4107 if (ioh->deleted) {
4108 *pioh = ioh->next;
4109 qemu_free(ioh);
4110 } else
4111 pioh = &ioh->next;
4115 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4117 /* rearm timer, if not periodic */
4118 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4119 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4120 qemu_rearm_alarm_timer(alarm_timer);
4123 /* vm time timers */
4124 if (vm_running) {
4125 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4126 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4127 qemu_get_clock(vm_clock));
4130 /* real time timers */
4131 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4132 qemu_get_clock(rt_clock));
4134 /* Check bottom-halves last in case any of the earlier events triggered
4135 them. */
4136 qemu_bh_poll();
4140 static int qemu_cpu_exec(CPUState *env)
4142 int ret;
4143 #ifdef CONFIG_PROFILER
4144 int64_t ti;
4145 #endif
4147 #ifdef CONFIG_PROFILER
4148 ti = profile_getclock();
4149 #endif
4150 if (use_icount) {
4151 int64_t count;
4152 int decr;
4153 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4154 env->icount_decr.u16.low = 0;
4155 env->icount_extra = 0;
4156 count = qemu_next_deadline();
4157 count = (count + (1 << icount_time_shift) - 1)
4158 >> icount_time_shift;
4159 qemu_icount += count;
4160 decr = (count > 0xffff) ? 0xffff : count;
4161 count -= decr;
4162 env->icount_decr.u16.low = decr;
4163 env->icount_extra = count;
4165 ret = cpu_exec(env);
4166 #ifdef CONFIG_PROFILER
4167 qemu_time += profile_getclock() - ti;
4168 #endif
4169 if (use_icount) {
4170 /* Fold pending instructions back into the
4171 instruction counter, and clear the interrupt flag. */
4172 qemu_icount -= (env->icount_decr.u16.low
4173 + env->icount_extra);
4174 env->icount_decr.u32 = 0;
4175 env->icount_extra = 0;
4177 return ret;
4180 static void tcg_cpu_exec(void)
4182 int ret = 0;
4184 if (next_cpu == NULL)
4185 next_cpu = first_cpu;
4186 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4187 CPUState *env = cur_cpu = next_cpu;
4189 if (!vm_running)
4190 break;
4191 if (timer_alarm_pending) {
4192 timer_alarm_pending = 0;
4193 break;
4195 if (cpu_can_run(env))
4196 ret = qemu_cpu_exec(env);
4197 if (ret == EXCP_DEBUG) {
4198 gdb_set_stop_cpu(env);
4199 debug_requested = 1;
4200 break;
4205 static int cpu_has_work(CPUState *env)
4207 if (env->stop)
4208 return 1;
4209 if (env->stopped)
4210 return 0;
4211 if (!env->halted)
4212 return 1;
4213 if (qemu_cpu_has_work(env))
4214 return 1;
4215 return 0;
4218 static int tcg_has_work(void)
4220 CPUState *env;
4222 for (env = first_cpu; env != NULL; env = env->next_cpu)
4223 if (cpu_has_work(env))
4224 return 1;
4225 return 0;
4228 static int qemu_calculate_timeout(void)
4230 #ifndef CONFIG_IOTHREAD
4231 int timeout;
4233 if (!vm_running)
4234 timeout = 5000;
4235 else if (tcg_has_work())
4236 timeout = 0;
4237 else if (!use_icount)
4238 timeout = 5000;
4239 else {
4240 /* XXX: use timeout computed from timers */
4241 int64_t add;
4242 int64_t delta;
4243 /* Advance virtual time to the next event. */
4244 if (use_icount == 1) {
4245 /* When not using an adaptive execution frequency
4246 we tend to get badly out of sync with real time,
4247 so just delay for a reasonable amount of time. */
4248 delta = 0;
4249 } else {
4250 delta = cpu_get_icount() - cpu_get_clock();
4252 if (delta > 0) {
4253 /* If virtual time is ahead of real time then just
4254 wait for IO. */
4255 timeout = (delta / 1000000) + 1;
4256 } else {
4257 /* Wait for either IO to occur or the next
4258 timer event. */
4259 add = qemu_next_deadline();
4260 /* We advance the timer before checking for IO.
4261 Limit the amount we advance so that early IO
4262 activity won't get the guest too far ahead. */
4263 if (add > 10000000)
4264 add = 10000000;
4265 delta += add;
4266 add = (add + (1 << icount_time_shift) - 1)
4267 >> icount_time_shift;
4268 qemu_icount += add;
4269 timeout = delta / 1000000;
4270 if (timeout < 0)
4271 timeout = 0;
4275 return timeout;
4276 #else /* CONFIG_IOTHREAD */
4277 return 1000;
4278 #endif
4281 static int vm_can_run(void)
4283 if (powerdown_requested)
4284 return 0;
4285 if (reset_requested)
4286 return 0;
4287 if (shutdown_requested)
4288 return 0;
4289 if (debug_requested)
4290 return 0;
4291 return 1;
4294 qemu_irq qemu_system_powerdown;
4296 static void main_loop(void)
4298 int r;
4300 #ifdef CONFIG_IOTHREAD
4301 qemu_system_ready = 1;
4302 qemu_cond_broadcast(&qemu_system_cond);
4303 #endif
4305 for (;;) {
4306 do {
4307 #ifdef CONFIG_PROFILER
4308 int64_t ti;
4309 #endif
4310 #ifndef CONFIG_IOTHREAD
4311 tcg_cpu_exec();
4312 #endif
4313 #ifdef CONFIG_PROFILER
4314 ti = profile_getclock();
4315 #endif
4316 main_loop_wait(qemu_calculate_timeout());
4317 #ifdef CONFIG_PROFILER
4318 dev_time += profile_getclock() - ti;
4319 #endif
4320 } while (vm_can_run());
4322 if (qemu_debug_requested())
4323 vm_stop(EXCP_DEBUG);
4324 if (qemu_shutdown_requested()) {
4325 if (no_shutdown) {
4326 vm_stop(0);
4327 no_shutdown = 0;
4328 } else
4329 break;
4331 if (qemu_reset_requested()) {
4332 pause_all_vcpus();
4333 qemu_system_reset();
4334 resume_all_vcpus();
4336 if (qemu_powerdown_requested()) {
4337 qemu_irq_raise(qemu_system_powerdown);
4339 if ((r = qemu_vmstop_requested()))
4340 vm_stop(r);
4342 pause_all_vcpus();
4345 static void version(void)
4347 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4350 static void help(int exitcode)
4352 version();
4353 printf("usage: %s [options] [disk_image]\n"
4354 "\n"
4355 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4356 "\n"
4357 #define DEF(option, opt_arg, opt_enum, opt_help) \
4358 opt_help
4359 #define DEFHEADING(text) stringify(text) "\n"
4360 #include "qemu-options.h"
4361 #undef DEF
4362 #undef DEFHEADING
4363 #undef GEN_DOCS
4364 "\n"
4365 "During emulation, the following keys are useful:\n"
4366 "ctrl-alt-f toggle full screen\n"
4367 "ctrl-alt-n switch to virtual console 'n'\n"
4368 "ctrl-alt toggle mouse and keyboard grab\n"
4369 "\n"
4370 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4372 "qemu",
4373 DEFAULT_RAM_SIZE,
4374 #ifndef _WIN32
4375 DEFAULT_NETWORK_SCRIPT,
4376 DEFAULT_NETWORK_DOWN_SCRIPT,
4377 #endif
4378 DEFAULT_GDBSTUB_PORT,
4379 "/tmp/qemu.log");
4380 exit(exitcode);
4383 #define HAS_ARG 0x0001
4385 enum {
4386 #define DEF(option, opt_arg, opt_enum, opt_help) \
4387 opt_enum,
4388 #define DEFHEADING(text)
4389 #include "qemu-options.h"
4390 #undef DEF
4391 #undef DEFHEADING
4392 #undef GEN_DOCS
4395 typedef struct QEMUOption {
4396 const char *name;
4397 int flags;
4398 int index;
4399 } QEMUOption;
4401 static const QEMUOption qemu_options[] = {
4402 { "h", 0, QEMU_OPTION_h },
4403 #define DEF(option, opt_arg, opt_enum, opt_help) \
4404 { option, opt_arg, opt_enum },
4405 #define DEFHEADING(text)
4406 #include "qemu-options.h"
4407 #undef DEF
4408 #undef DEFHEADING
4409 #undef GEN_DOCS
4410 { NULL },
4413 #ifdef HAS_AUDIO
4414 struct soundhw soundhw[] = {
4415 #ifdef HAS_AUDIO_CHOICE
4416 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4418 "pcspk",
4419 "PC speaker",
4422 { .init_isa = pcspk_audio_init }
4424 #endif
4426 #ifdef CONFIG_SB16
4428 "sb16",
4429 "Creative Sound Blaster 16",
4432 { .init_isa = SB16_init }
4434 #endif
4436 #ifdef CONFIG_CS4231A
4438 "cs4231a",
4439 "CS4231A",
4442 { .init_isa = cs4231a_init }
4444 #endif
4446 #ifdef CONFIG_ADLIB
4448 "adlib",
4449 #ifdef HAS_YMF262
4450 "Yamaha YMF262 (OPL3)",
4451 #else
4452 "Yamaha YM3812 (OPL2)",
4453 #endif
4456 { .init_isa = Adlib_init }
4458 #endif
4460 #ifdef CONFIG_GUS
4462 "gus",
4463 "Gravis Ultrasound GF1",
4466 { .init_isa = GUS_init }
4468 #endif
4470 #ifdef CONFIG_AC97
4472 "ac97",
4473 "Intel 82801AA AC97 Audio",
4476 { .init_pci = ac97_init }
4478 #endif
4480 #ifdef CONFIG_ES1370
4482 "es1370",
4483 "ENSONIQ AudioPCI ES1370",
4486 { .init_pci = es1370_init }
4488 #endif
4490 #endif /* HAS_AUDIO_CHOICE */
4492 { NULL, NULL, 0, 0, { NULL } }
4495 static void select_soundhw (const char *optarg)
4497 struct soundhw *c;
4499 if (*optarg == '?') {
4500 show_valid_cards:
4502 printf ("Valid sound card names (comma separated):\n");
4503 for (c = soundhw; c->name; ++c) {
4504 printf ("%-11s %s\n", c->name, c->descr);
4506 printf ("\n-soundhw all will enable all of the above\n");
4507 exit (*optarg != '?');
4509 else {
4510 size_t l;
4511 const char *p;
4512 char *e;
4513 int bad_card = 0;
4515 if (!strcmp (optarg, "all")) {
4516 for (c = soundhw; c->name; ++c) {
4517 c->enabled = 1;
4519 return;
4522 p = optarg;
4523 while (*p) {
4524 e = strchr (p, ',');
4525 l = !e ? strlen (p) : (size_t) (e - p);
4527 for (c = soundhw; c->name; ++c) {
4528 if (!strncmp (c->name, p, l)) {
4529 c->enabled = 1;
4530 break;
4534 if (!c->name) {
4535 if (l > 80) {
4536 fprintf (stderr,
4537 "Unknown sound card name (too big to show)\n");
4539 else {
4540 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4541 (int) l, p);
4543 bad_card = 1;
4545 p += l + (e != NULL);
4548 if (bad_card)
4549 goto show_valid_cards;
4552 #endif
4554 static void select_vgahw (const char *p)
4556 const char *opts;
4558 vga_interface_type = VGA_NONE;
4559 if (strstart(p, "std", &opts)) {
4560 vga_interface_type = VGA_STD;
4561 } else if (strstart(p, "cirrus", &opts)) {
4562 vga_interface_type = VGA_CIRRUS;
4563 } else if (strstart(p, "vmware", &opts)) {
4564 vga_interface_type = VGA_VMWARE;
4565 } else if (strstart(p, "xenfb", &opts)) {
4566 vga_interface_type = VGA_XENFB;
4567 } else if (!strstart(p, "none", &opts)) {
4568 invalid_vga:
4569 fprintf(stderr, "Unknown vga type: %s\n", p);
4570 exit(1);
4572 while (*opts) {
4573 const char *nextopt;
4575 if (strstart(opts, ",retrace=", &nextopt)) {
4576 opts = nextopt;
4577 if (strstart(opts, "dumb", &nextopt))
4578 vga_retrace_method = VGA_RETRACE_DUMB;
4579 else if (strstart(opts, "precise", &nextopt))
4580 vga_retrace_method = VGA_RETRACE_PRECISE;
4581 else goto invalid_vga;
4582 } else goto invalid_vga;
4583 opts = nextopt;
4587 #ifdef TARGET_I386
4588 static int balloon_parse(const char *arg)
4590 char buf[128];
4591 const char *p;
4593 if (!strcmp(arg, "none")) {
4594 virtio_balloon = 0;
4595 } else if (!strncmp(arg, "virtio", 6)) {
4596 virtio_balloon = 1;
4597 if (arg[6] == ',') {
4598 p = arg + 7;
4599 if (get_param_value(buf, sizeof(buf), "addr", p)) {
4600 virtio_balloon_devaddr = strdup(buf);
4603 } else {
4604 return -1;
4606 return 0;
4608 #endif
4610 #ifdef _WIN32
4611 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4613 exit(STATUS_CONTROL_C_EXIT);
4614 return TRUE;
4616 #endif
4618 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4620 int ret;
4622 if(strlen(str) != 36)
4623 return -1;
4625 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4626 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4627 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4629 if(ret != 16)
4630 return -1;
4632 #ifdef TARGET_I386
4633 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4634 #endif
4636 return 0;
4639 #define MAX_NET_CLIENTS 32
4641 #ifndef _WIN32
4643 static void termsig_handler(int signal)
4645 qemu_system_shutdown_request();
4648 static void sigchld_handler(int signal)
4650 waitpid(-1, NULL, WNOHANG);
4653 static void sighandler_setup(void)
4655 struct sigaction act;
4657 memset(&act, 0, sizeof(act));
4658 act.sa_handler = termsig_handler;
4659 sigaction(SIGINT, &act, NULL);
4660 sigaction(SIGHUP, &act, NULL);
4661 sigaction(SIGTERM, &act, NULL);
4663 act.sa_handler = sigchld_handler;
4664 act.sa_flags = SA_NOCLDSTOP;
4665 sigaction(SIGCHLD, &act, NULL);
4668 #endif
4670 #ifdef _WIN32
4671 /* Look for support files in the same directory as the executable. */
4672 static char *find_datadir(const char *argv0)
4674 char *p;
4675 char buf[MAX_PATH];
4676 DWORD len;
4678 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4679 if (len == 0) {
4680 return NULL;
4683 buf[len] = 0;
4684 p = buf + len - 1;
4685 while (p != buf && *p != '\\')
4686 p--;
4687 *p = 0;
4688 if (access(buf, R_OK) == 0) {
4689 return qemu_strdup(buf);
4691 return NULL;
4693 #else /* !_WIN32 */
4695 /* Find a likely location for support files using the location of the binary.
4696 For installed binaries this will be "$bindir/../share/qemu". When
4697 running from the build tree this will be "$bindir/../pc-bios". */
4698 #define SHARE_SUFFIX "/share/qemu"
4699 #define BUILD_SUFFIX "/pc-bios"
4700 static char *find_datadir(const char *argv0)
4702 char *dir;
4703 char *p = NULL;
4704 char *res;
4705 #ifdef PATH_MAX
4706 char buf[PATH_MAX];
4707 #endif
4708 size_t max_len;
4710 #if defined(__linux__)
4712 int len;
4713 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4714 if (len > 0) {
4715 buf[len] = 0;
4716 p = buf;
4719 #elif defined(__FreeBSD__)
4721 int len;
4722 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4723 if (len > 0) {
4724 buf[len] = 0;
4725 p = buf;
4728 #endif
4729 /* If we don't have any way of figuring out the actual executable
4730 location then try argv[0]. */
4731 if (!p) {
4732 #ifdef PATH_MAX
4733 p = buf;
4734 #endif
4735 p = realpath(argv0, p);
4736 if (!p) {
4737 return NULL;
4740 dir = dirname(p);
4741 dir = dirname(dir);
4743 max_len = strlen(dir) +
4744 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4745 res = qemu_mallocz(max_len);
4746 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4747 if (access(res, R_OK)) {
4748 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4749 if (access(res, R_OK)) {
4750 qemu_free(res);
4751 res = NULL;
4754 #ifndef PATH_MAX
4755 free(p);
4756 #endif
4757 return res;
4759 #undef SHARE_SUFFIX
4760 #undef BUILD_SUFFIX
4761 #endif
4763 char *qemu_find_file(int type, const char *name)
4765 int len;
4766 const char *subdir;
4767 char *buf;
4769 /* If name contains path separators then try it as a straight path. */
4770 if ((strchr(name, '/') || strchr(name, '\\'))
4771 && access(name, R_OK) == 0) {
4772 return strdup(name);
4774 switch (type) {
4775 case QEMU_FILE_TYPE_BIOS:
4776 subdir = "";
4777 break;
4778 case QEMU_FILE_TYPE_KEYMAP:
4779 subdir = "keymaps/";
4780 break;
4781 default:
4782 abort();
4784 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4785 buf = qemu_mallocz(len);
4786 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4787 if (access(buf, R_OK)) {
4788 qemu_free(buf);
4789 return NULL;
4791 return buf;
4794 static int device_init_func(QemuOpts *opts, void *opaque)
4796 DeviceState *dev;
4798 dev = qdev_device_add(opts);
4799 if (!dev)
4800 return -1;
4801 return 0;
4804 struct device_config {
4805 enum {
4806 DEV_USB, /* -usbdevice */
4807 DEV_BT, /* -bt */
4808 } type;
4809 const char *cmdline;
4810 TAILQ_ENTRY(device_config) next;
4812 TAILQ_HEAD(, device_config) device_configs = TAILQ_HEAD_INITIALIZER(device_configs);
4814 static void add_device_config(int type, const char *cmdline)
4816 struct device_config *conf;
4818 conf = qemu_mallocz(sizeof(*conf));
4819 conf->type = type;
4820 conf->cmdline = cmdline;
4821 TAILQ_INSERT_TAIL(&device_configs, conf, next);
4824 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4826 struct device_config *conf;
4827 int rc;
4829 TAILQ_FOREACH(conf, &device_configs, next) {
4830 if (conf->type != type)
4831 continue;
4832 rc = func(conf->cmdline);
4833 if (0 != rc)
4834 return rc;
4836 return 0;
4839 int main(int argc, char **argv, char **envp)
4841 const char *gdbstub_dev = NULL;
4842 uint32_t boot_devices_bitmap = 0;
4843 int i;
4844 int snapshot, linux_boot, net_boot;
4845 const char *initrd_filename;
4846 const char *kernel_filename, *kernel_cmdline;
4847 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4848 DisplayState *ds;
4849 DisplayChangeListener *dcl;
4850 int cyls, heads, secs, translation;
4851 const char *net_clients[MAX_NET_CLIENTS];
4852 int nb_net_clients;
4853 QemuOpts *hda_opts = NULL, *opts;
4854 int optind;
4855 const char *r, *optarg;
4856 CharDriverState *monitor_hd = NULL;
4857 const char *monitor_device;
4858 const char *serial_devices[MAX_SERIAL_PORTS];
4859 int serial_device_index;
4860 const char *parallel_devices[MAX_PARALLEL_PORTS];
4861 int parallel_device_index;
4862 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4863 int virtio_console_index;
4864 const char *loadvm = NULL;
4865 QEMUMachine *machine;
4866 const char *cpu_model;
4867 #ifndef _WIN32
4868 int fds[2];
4869 #endif
4870 int tb_size;
4871 const char *pid_file = NULL;
4872 const char *incoming = NULL;
4873 #ifndef _WIN32
4874 int fd = 0;
4875 struct passwd *pwd = NULL;
4876 const char *chroot_dir = NULL;
4877 const char *run_as = NULL;
4878 #endif
4879 CPUState *env;
4880 int show_vnc_port = 0;
4882 qemu_cache_utils_init(envp);
4884 LIST_INIT (&vm_change_state_head);
4885 #ifndef _WIN32
4887 struct sigaction act;
4888 sigfillset(&act.sa_mask);
4889 act.sa_flags = 0;
4890 act.sa_handler = SIG_IGN;
4891 sigaction(SIGPIPE, &act, NULL);
4893 #else
4894 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4895 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4896 QEMU to run on a single CPU */
4898 HANDLE h;
4899 DWORD mask, smask;
4900 int i;
4901 h = GetCurrentProcess();
4902 if (GetProcessAffinityMask(h, &mask, &smask)) {
4903 for(i = 0; i < 32; i++) {
4904 if (mask & (1 << i))
4905 break;
4907 if (i != 32) {
4908 mask = 1 << i;
4909 SetProcessAffinityMask(h, mask);
4913 #endif
4915 module_call_init(MODULE_INIT_MACHINE);
4916 machine = find_default_machine();
4917 cpu_model = NULL;
4918 initrd_filename = NULL;
4919 ram_size = 0;
4920 snapshot = 0;
4921 kernel_filename = NULL;
4922 kernel_cmdline = "";
4923 cyls = heads = secs = 0;
4924 translation = BIOS_ATA_TRANSLATION_AUTO;
4925 monitor_device = "vc:80Cx24C";
4927 serial_devices[0] = "vc:80Cx24C";
4928 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4929 serial_devices[i] = NULL;
4930 serial_device_index = 0;
4932 parallel_devices[0] = "vc:80Cx24C";
4933 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4934 parallel_devices[i] = NULL;
4935 parallel_device_index = 0;
4937 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4938 virtio_consoles[i] = NULL;
4939 virtio_console_index = 0;
4941 for (i = 0; i < MAX_NODES; i++) {
4942 node_mem[i] = 0;
4943 node_cpumask[i] = 0;
4946 nb_net_clients = 0;
4947 nb_numa_nodes = 0;
4948 nb_nics = 0;
4950 tb_size = 0;
4951 autostart= 1;
4953 register_watchdogs();
4955 optind = 1;
4956 for(;;) {
4957 if (optind >= argc)
4958 break;
4959 r = argv[optind];
4960 if (r[0] != '-') {
4961 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4962 } else {
4963 const QEMUOption *popt;
4965 optind++;
4966 /* Treat --foo the same as -foo. */
4967 if (r[1] == '-')
4968 r++;
4969 popt = qemu_options;
4970 for(;;) {
4971 if (!popt->name) {
4972 fprintf(stderr, "%s: invalid option -- '%s'\n",
4973 argv[0], r);
4974 exit(1);
4976 if (!strcmp(popt->name, r + 1))
4977 break;
4978 popt++;
4980 if (popt->flags & HAS_ARG) {
4981 if (optind >= argc) {
4982 fprintf(stderr, "%s: option '%s' requires an argument\n",
4983 argv[0], r);
4984 exit(1);
4986 optarg = argv[optind++];
4987 } else {
4988 optarg = NULL;
4991 switch(popt->index) {
4992 case QEMU_OPTION_M:
4993 machine = find_machine(optarg);
4994 if (!machine) {
4995 QEMUMachine *m;
4996 printf("Supported machines are:\n");
4997 for(m = first_machine; m != NULL; m = m->next) {
4998 if (m->alias)
4999 printf("%-10s %s (alias of %s)\n",
5000 m->alias, m->desc, m->name);
5001 printf("%-10s %s%s\n",
5002 m->name, m->desc,
5003 m->is_default ? " (default)" : "");
5005 exit(*optarg != '?');
5007 break;
5008 case QEMU_OPTION_cpu:
5009 /* hw initialization will check this */
5010 if (*optarg == '?') {
5011 /* XXX: implement xxx_cpu_list for targets that still miss it */
5012 #if defined(cpu_list)
5013 cpu_list(stdout, &fprintf);
5014 #endif
5015 exit(0);
5016 } else {
5017 cpu_model = optarg;
5019 break;
5020 case QEMU_OPTION_initrd:
5021 initrd_filename = optarg;
5022 break;
5023 case QEMU_OPTION_hda:
5024 if (cyls == 0)
5025 hda_opts = drive_add(optarg, HD_ALIAS, 0);
5026 else
5027 hda_opts = drive_add(optarg, HD_ALIAS
5028 ",cyls=%d,heads=%d,secs=%d%s",
5029 0, cyls, heads, secs,
5030 translation == BIOS_ATA_TRANSLATION_LBA ?
5031 ",trans=lba" :
5032 translation == BIOS_ATA_TRANSLATION_NONE ?
5033 ",trans=none" : "");
5034 break;
5035 case QEMU_OPTION_hdb:
5036 case QEMU_OPTION_hdc:
5037 case QEMU_OPTION_hdd:
5038 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5039 break;
5040 case QEMU_OPTION_drive:
5041 drive_add(NULL, "%s", optarg);
5042 break;
5043 case QEMU_OPTION_set:
5044 if (qemu_set_option(optarg) != 0)
5045 exit(1);
5046 break;
5047 case QEMU_OPTION_mtdblock:
5048 drive_add(optarg, MTD_ALIAS);
5049 break;
5050 case QEMU_OPTION_sd:
5051 drive_add(optarg, SD_ALIAS);
5052 break;
5053 case QEMU_OPTION_pflash:
5054 drive_add(optarg, PFLASH_ALIAS);
5055 break;
5056 case QEMU_OPTION_snapshot:
5057 snapshot = 1;
5058 break;
5059 case QEMU_OPTION_hdachs:
5061 const char *p;
5062 p = optarg;
5063 cyls = strtol(p, (char **)&p, 0);
5064 if (cyls < 1 || cyls > 16383)
5065 goto chs_fail;
5066 if (*p != ',')
5067 goto chs_fail;
5068 p++;
5069 heads = strtol(p, (char **)&p, 0);
5070 if (heads < 1 || heads > 16)
5071 goto chs_fail;
5072 if (*p != ',')
5073 goto chs_fail;
5074 p++;
5075 secs = strtol(p, (char **)&p, 0);
5076 if (secs < 1 || secs > 63)
5077 goto chs_fail;
5078 if (*p == ',') {
5079 p++;
5080 if (!strcmp(p, "none"))
5081 translation = BIOS_ATA_TRANSLATION_NONE;
5082 else if (!strcmp(p, "lba"))
5083 translation = BIOS_ATA_TRANSLATION_LBA;
5084 else if (!strcmp(p, "auto"))
5085 translation = BIOS_ATA_TRANSLATION_AUTO;
5086 else
5087 goto chs_fail;
5088 } else if (*p != '\0') {
5089 chs_fail:
5090 fprintf(stderr, "qemu: invalid physical CHS format\n");
5091 exit(1);
5093 if (hda_opts != NULL) {
5094 char num[16];
5095 snprintf(num, sizeof(num), "%d", cyls);
5096 qemu_opt_set(hda_opts, "cyls", num);
5097 snprintf(num, sizeof(num), "%d", heads);
5098 qemu_opt_set(hda_opts, "heads", num);
5099 snprintf(num, sizeof(num), "%d", secs);
5100 qemu_opt_set(hda_opts, "secs", num);
5101 if (translation == BIOS_ATA_TRANSLATION_LBA)
5102 qemu_opt_set(hda_opts, "trans", "lba");
5103 if (translation == BIOS_ATA_TRANSLATION_NONE)
5104 qemu_opt_set(hda_opts, "trans", "none");
5107 break;
5108 case QEMU_OPTION_numa:
5109 if (nb_numa_nodes >= MAX_NODES) {
5110 fprintf(stderr, "qemu: too many NUMA nodes\n");
5111 exit(1);
5113 numa_add(optarg);
5114 break;
5115 case QEMU_OPTION_nographic:
5116 display_type = DT_NOGRAPHIC;
5117 break;
5118 #ifdef CONFIG_CURSES
5119 case QEMU_OPTION_curses:
5120 display_type = DT_CURSES;
5121 break;
5122 #endif
5123 case QEMU_OPTION_portrait:
5124 graphic_rotate = 1;
5125 break;
5126 case QEMU_OPTION_kernel:
5127 kernel_filename = optarg;
5128 break;
5129 case QEMU_OPTION_append:
5130 kernel_cmdline = optarg;
5131 break;
5132 case QEMU_OPTION_cdrom:
5133 drive_add(optarg, CDROM_ALIAS);
5134 break;
5135 case QEMU_OPTION_boot:
5137 static const char * const params[] = {
5138 "order", "once", "menu", NULL
5140 char buf[sizeof(boot_devices)];
5141 char *standard_boot_devices;
5142 int legacy = 0;
5144 if (!strchr(optarg, '=')) {
5145 legacy = 1;
5146 pstrcpy(buf, sizeof(buf), optarg);
5147 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5148 fprintf(stderr,
5149 "qemu: unknown boot parameter '%s' in '%s'\n",
5150 buf, optarg);
5151 exit(1);
5154 if (legacy ||
5155 get_param_value(buf, sizeof(buf), "order", optarg)) {
5156 boot_devices_bitmap = parse_bootdevices(buf);
5157 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5159 if (!legacy) {
5160 if (get_param_value(buf, sizeof(buf),
5161 "once", optarg)) {
5162 boot_devices_bitmap |= parse_bootdevices(buf);
5163 standard_boot_devices = qemu_strdup(boot_devices);
5164 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5165 qemu_register_reset(restore_boot_devices,
5166 standard_boot_devices);
5168 if (get_param_value(buf, sizeof(buf),
5169 "menu", optarg)) {
5170 if (!strcmp(buf, "on")) {
5171 boot_menu = 1;
5172 } else if (!strcmp(buf, "off")) {
5173 boot_menu = 0;
5174 } else {
5175 fprintf(stderr,
5176 "qemu: invalid option value '%s'\n",
5177 buf);
5178 exit(1);
5183 break;
5184 case QEMU_OPTION_fda:
5185 case QEMU_OPTION_fdb:
5186 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5187 break;
5188 #ifdef TARGET_I386
5189 case QEMU_OPTION_no_fd_bootchk:
5190 fd_bootchk = 0;
5191 break;
5192 #endif
5193 case QEMU_OPTION_net:
5194 if (nb_net_clients >= MAX_NET_CLIENTS) {
5195 fprintf(stderr, "qemu: too many network clients\n");
5196 exit(1);
5198 net_clients[nb_net_clients] = optarg;
5199 nb_net_clients++;
5200 break;
5201 #ifdef CONFIG_SLIRP
5202 case QEMU_OPTION_tftp:
5203 legacy_tftp_prefix = optarg;
5204 break;
5205 case QEMU_OPTION_bootp:
5206 legacy_bootp_filename = optarg;
5207 break;
5208 #ifndef _WIN32
5209 case QEMU_OPTION_smb:
5210 net_slirp_smb(optarg);
5211 break;
5212 #endif
5213 case QEMU_OPTION_redir:
5214 net_slirp_redir(optarg);
5215 break;
5216 #endif
5217 case QEMU_OPTION_bt:
5218 add_device_config(DEV_BT, optarg);
5219 break;
5220 #ifdef HAS_AUDIO
5221 case QEMU_OPTION_audio_help:
5222 AUD_help ();
5223 exit (0);
5224 break;
5225 case QEMU_OPTION_soundhw:
5226 select_soundhw (optarg);
5227 break;
5228 #endif
5229 case QEMU_OPTION_h:
5230 help(0);
5231 break;
5232 case QEMU_OPTION_version:
5233 version();
5234 exit(0);
5235 break;
5236 case QEMU_OPTION_m: {
5237 uint64_t value;
5238 char *ptr;
5240 value = strtoul(optarg, &ptr, 10);
5241 switch (*ptr) {
5242 case 0: case 'M': case 'm':
5243 value <<= 20;
5244 break;
5245 case 'G': case 'g':
5246 value <<= 30;
5247 break;
5248 default:
5249 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5250 exit(1);
5253 /* On 32-bit hosts, QEMU is limited by virtual address space */
5254 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5255 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5256 exit(1);
5258 if (value != (uint64_t)(ram_addr_t)value) {
5259 fprintf(stderr, "qemu: ram size too large\n");
5260 exit(1);
5262 ram_size = value;
5263 break;
5265 case QEMU_OPTION_d:
5267 int mask;
5268 const CPULogItem *item;
5270 mask = cpu_str_to_log_mask(optarg);
5271 if (!mask) {
5272 printf("Log items (comma separated):\n");
5273 for(item = cpu_log_items; item->mask != 0; item++) {
5274 printf("%-10s %s\n", item->name, item->help);
5276 exit(1);
5278 cpu_set_log(mask);
5280 break;
5281 case QEMU_OPTION_s:
5282 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5283 break;
5284 case QEMU_OPTION_gdb:
5285 gdbstub_dev = optarg;
5286 break;
5287 case QEMU_OPTION_L:
5288 data_dir = optarg;
5289 break;
5290 case QEMU_OPTION_bios:
5291 bios_name = optarg;
5292 break;
5293 case QEMU_OPTION_singlestep:
5294 singlestep = 1;
5295 break;
5296 case QEMU_OPTION_S:
5297 autostart = 0;
5298 break;
5299 #ifndef _WIN32
5300 case QEMU_OPTION_k:
5301 keyboard_layout = optarg;
5302 break;
5303 #endif
5304 case QEMU_OPTION_localtime:
5305 rtc_utc = 0;
5306 break;
5307 case QEMU_OPTION_vga:
5308 select_vgahw (optarg);
5309 break;
5310 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5311 case QEMU_OPTION_g:
5313 const char *p;
5314 int w, h, depth;
5315 p = optarg;
5316 w = strtol(p, (char **)&p, 10);
5317 if (w <= 0) {
5318 graphic_error:
5319 fprintf(stderr, "qemu: invalid resolution or depth\n");
5320 exit(1);
5322 if (*p != 'x')
5323 goto graphic_error;
5324 p++;
5325 h = strtol(p, (char **)&p, 10);
5326 if (h <= 0)
5327 goto graphic_error;
5328 if (*p == 'x') {
5329 p++;
5330 depth = strtol(p, (char **)&p, 10);
5331 if (depth != 8 && depth != 15 && depth != 16 &&
5332 depth != 24 && depth != 32)
5333 goto graphic_error;
5334 } else if (*p == '\0') {
5335 depth = graphic_depth;
5336 } else {
5337 goto graphic_error;
5340 graphic_width = w;
5341 graphic_height = h;
5342 graphic_depth = depth;
5344 break;
5345 #endif
5346 case QEMU_OPTION_echr:
5348 char *r;
5349 term_escape_char = strtol(optarg, &r, 0);
5350 if (r == optarg)
5351 printf("Bad argument to echr\n");
5352 break;
5354 case QEMU_OPTION_monitor:
5355 monitor_device = optarg;
5356 break;
5357 case QEMU_OPTION_serial:
5358 if (serial_device_index >= MAX_SERIAL_PORTS) {
5359 fprintf(stderr, "qemu: too many serial ports\n");
5360 exit(1);
5362 serial_devices[serial_device_index] = optarg;
5363 serial_device_index++;
5364 break;
5365 case QEMU_OPTION_watchdog:
5366 i = select_watchdog(optarg);
5367 if (i > 0)
5368 exit (i == 1 ? 1 : 0);
5369 break;
5370 case QEMU_OPTION_watchdog_action:
5371 if (select_watchdog_action(optarg) == -1) {
5372 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5373 exit(1);
5375 break;
5376 case QEMU_OPTION_virtiocon:
5377 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5378 fprintf(stderr, "qemu: too many virtio consoles\n");
5379 exit(1);
5381 virtio_consoles[virtio_console_index] = optarg;
5382 virtio_console_index++;
5383 break;
5384 case QEMU_OPTION_parallel:
5385 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5386 fprintf(stderr, "qemu: too many parallel ports\n");
5387 exit(1);
5389 parallel_devices[parallel_device_index] = optarg;
5390 parallel_device_index++;
5391 break;
5392 case QEMU_OPTION_loadvm:
5393 loadvm = optarg;
5394 break;
5395 case QEMU_OPTION_full_screen:
5396 full_screen = 1;
5397 break;
5398 #ifdef CONFIG_SDL
5399 case QEMU_OPTION_no_frame:
5400 no_frame = 1;
5401 break;
5402 case QEMU_OPTION_alt_grab:
5403 alt_grab = 1;
5404 break;
5405 case QEMU_OPTION_no_quit:
5406 no_quit = 1;
5407 break;
5408 case QEMU_OPTION_sdl:
5409 display_type = DT_SDL;
5410 break;
5411 #endif
5412 case QEMU_OPTION_pidfile:
5413 pid_file = optarg;
5414 break;
5415 #ifdef TARGET_I386
5416 case QEMU_OPTION_win2k_hack:
5417 win2k_install_hack = 1;
5418 break;
5419 case QEMU_OPTION_rtc_td_hack:
5420 rtc_td_hack = 1;
5421 break;
5422 case QEMU_OPTION_acpitable:
5423 if(acpi_table_add(optarg) < 0) {
5424 fprintf(stderr, "Wrong acpi table provided\n");
5425 exit(1);
5427 break;
5428 case QEMU_OPTION_smbios:
5429 if(smbios_entry_add(optarg) < 0) {
5430 fprintf(stderr, "Wrong smbios provided\n");
5431 exit(1);
5433 break;
5434 #endif
5435 #ifdef CONFIG_KVM
5436 case QEMU_OPTION_enable_kvm:
5437 kvm_allowed = 1;
5438 break;
5439 #endif
5440 case QEMU_OPTION_usb:
5441 usb_enabled = 1;
5442 break;
5443 case QEMU_OPTION_usbdevice:
5444 usb_enabled = 1;
5445 add_device_config(DEV_USB, optarg);
5446 break;
5447 case QEMU_OPTION_device:
5448 opts = qemu_opts_parse(&qemu_device_opts, optarg, "driver");
5449 if (!opts) {
5450 fprintf(stderr, "parse error: %s\n", optarg);
5451 exit(1);
5453 break;
5454 case QEMU_OPTION_smp:
5455 smp_parse(optarg);
5456 if (smp_cpus < 1) {
5457 fprintf(stderr, "Invalid number of CPUs\n");
5458 exit(1);
5460 if (max_cpus < smp_cpus) {
5461 fprintf(stderr, "maxcpus must be equal to or greater than "
5462 "smp\n");
5463 exit(1);
5465 if (max_cpus > 255) {
5466 fprintf(stderr, "Unsupported number of maxcpus\n");
5467 exit(1);
5469 break;
5470 case QEMU_OPTION_vnc:
5471 display_type = DT_VNC;
5472 vnc_display = optarg;
5473 break;
5474 #ifdef TARGET_I386
5475 case QEMU_OPTION_no_acpi:
5476 acpi_enabled = 0;
5477 break;
5478 case QEMU_OPTION_no_hpet:
5479 no_hpet = 1;
5480 break;
5481 case QEMU_OPTION_balloon:
5482 if (balloon_parse(optarg) < 0) {
5483 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5484 exit(1);
5486 break;
5487 #endif
5488 case QEMU_OPTION_no_reboot:
5489 no_reboot = 1;
5490 break;
5491 case QEMU_OPTION_no_shutdown:
5492 no_shutdown = 1;
5493 break;
5494 case QEMU_OPTION_show_cursor:
5495 cursor_hide = 0;
5496 break;
5497 case QEMU_OPTION_uuid:
5498 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5499 fprintf(stderr, "Fail to parse UUID string."
5500 " Wrong format.\n");
5501 exit(1);
5503 break;
5504 #ifndef _WIN32
5505 case QEMU_OPTION_daemonize:
5506 daemonize = 1;
5507 break;
5508 #endif
5509 case QEMU_OPTION_option_rom:
5510 if (nb_option_roms >= MAX_OPTION_ROMS) {
5511 fprintf(stderr, "Too many option ROMs\n");
5512 exit(1);
5514 option_rom[nb_option_roms] = optarg;
5515 nb_option_roms++;
5516 break;
5517 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5518 case QEMU_OPTION_semihosting:
5519 semihosting_enabled = 1;
5520 break;
5521 #endif
5522 case QEMU_OPTION_name:
5523 qemu_name = qemu_strdup(optarg);
5525 char *p = strchr(qemu_name, ',');
5526 if (p != NULL) {
5527 *p++ = 0;
5528 if (strncmp(p, "process=", 8)) {
5529 fprintf(stderr, "Unknown subargument %s to -name", p);
5530 exit(1);
5532 p += 8;
5533 set_proc_name(p);
5536 break;
5537 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5538 case QEMU_OPTION_prom_env:
5539 if (nb_prom_envs >= MAX_PROM_ENVS) {
5540 fprintf(stderr, "Too many prom variables\n");
5541 exit(1);
5543 prom_envs[nb_prom_envs] = optarg;
5544 nb_prom_envs++;
5545 break;
5546 #endif
5547 #ifdef TARGET_ARM
5548 case QEMU_OPTION_old_param:
5549 old_param = 1;
5550 break;
5551 #endif
5552 case QEMU_OPTION_clock:
5553 configure_alarms(optarg);
5554 break;
5555 case QEMU_OPTION_startdate:
5557 struct tm tm;
5558 time_t rtc_start_date;
5559 if (!strcmp(optarg, "now")) {
5560 rtc_date_offset = -1;
5561 } else {
5562 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5563 &tm.tm_year,
5564 &tm.tm_mon,
5565 &tm.tm_mday,
5566 &tm.tm_hour,
5567 &tm.tm_min,
5568 &tm.tm_sec) == 6) {
5569 /* OK */
5570 } else if (sscanf(optarg, "%d-%d-%d",
5571 &tm.tm_year,
5572 &tm.tm_mon,
5573 &tm.tm_mday) == 3) {
5574 tm.tm_hour = 0;
5575 tm.tm_min = 0;
5576 tm.tm_sec = 0;
5577 } else {
5578 goto date_fail;
5580 tm.tm_year -= 1900;
5581 tm.tm_mon--;
5582 rtc_start_date = mktimegm(&tm);
5583 if (rtc_start_date == -1) {
5584 date_fail:
5585 fprintf(stderr, "Invalid date format. Valid format are:\n"
5586 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5587 exit(1);
5589 rtc_date_offset = time(NULL) - rtc_start_date;
5592 break;
5593 case QEMU_OPTION_tb_size:
5594 tb_size = strtol(optarg, NULL, 0);
5595 if (tb_size < 0)
5596 tb_size = 0;
5597 break;
5598 case QEMU_OPTION_icount:
5599 use_icount = 1;
5600 if (strcmp(optarg, "auto") == 0) {
5601 icount_time_shift = -1;
5602 } else {
5603 icount_time_shift = strtol(optarg, NULL, 0);
5605 break;
5606 case QEMU_OPTION_incoming:
5607 incoming = optarg;
5608 break;
5609 #ifndef _WIN32
5610 case QEMU_OPTION_chroot:
5611 chroot_dir = optarg;
5612 break;
5613 case QEMU_OPTION_runas:
5614 run_as = optarg;
5615 break;
5616 #endif
5617 #ifdef CONFIG_XEN
5618 case QEMU_OPTION_xen_domid:
5619 xen_domid = atoi(optarg);
5620 break;
5621 case QEMU_OPTION_xen_create:
5622 xen_mode = XEN_CREATE;
5623 break;
5624 case QEMU_OPTION_xen_attach:
5625 xen_mode = XEN_ATTACH;
5626 break;
5627 #endif
5632 /* If no data_dir is specified then try to find it relative to the
5633 executable path. */
5634 if (!data_dir) {
5635 data_dir = find_datadir(argv[0]);
5637 /* If all else fails use the install patch specified when building. */
5638 if (!data_dir) {
5639 data_dir = CONFIG_QEMU_SHAREDIR;
5643 * Default to max_cpus = smp_cpus, in case the user doesn't
5644 * specify a max_cpus value.
5646 if (!max_cpus)
5647 max_cpus = smp_cpus;
5649 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5650 if (smp_cpus > machine->max_cpus) {
5651 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5652 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5653 machine->max_cpus);
5654 exit(1);
5657 if (display_type == DT_NOGRAPHIC) {
5658 if (serial_device_index == 0)
5659 serial_devices[0] = "stdio";
5660 if (parallel_device_index == 0)
5661 parallel_devices[0] = "null";
5662 if (strncmp(monitor_device, "vc", 2) == 0)
5663 monitor_device = "stdio";
5666 #ifndef _WIN32
5667 if (daemonize) {
5668 pid_t pid;
5670 if (pipe(fds) == -1)
5671 exit(1);
5673 pid = fork();
5674 if (pid > 0) {
5675 uint8_t status;
5676 ssize_t len;
5678 close(fds[1]);
5680 again:
5681 len = read(fds[0], &status, 1);
5682 if (len == -1 && (errno == EINTR))
5683 goto again;
5685 if (len != 1)
5686 exit(1);
5687 else if (status == 1) {
5688 fprintf(stderr, "Could not acquire pidfile\n");
5689 exit(1);
5690 } else
5691 exit(0);
5692 } else if (pid < 0)
5693 exit(1);
5695 setsid();
5697 pid = fork();
5698 if (pid > 0)
5699 exit(0);
5700 else if (pid < 0)
5701 exit(1);
5703 umask(027);
5705 signal(SIGTSTP, SIG_IGN);
5706 signal(SIGTTOU, SIG_IGN);
5707 signal(SIGTTIN, SIG_IGN);
5710 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5711 if (daemonize) {
5712 uint8_t status = 1;
5713 write(fds[1], &status, 1);
5714 } else
5715 fprintf(stderr, "Could not acquire pid file\n");
5716 exit(1);
5718 #endif
5720 if (qemu_init_main_loop()) {
5721 fprintf(stderr, "qemu_init_main_loop failed\n");
5722 exit(1);
5724 linux_boot = (kernel_filename != NULL);
5726 if (!linux_boot && *kernel_cmdline != '\0') {
5727 fprintf(stderr, "-append only allowed with -kernel option\n");
5728 exit(1);
5731 if (!linux_boot && initrd_filename != NULL) {
5732 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5733 exit(1);
5736 #ifndef _WIN32
5737 /* Win32 doesn't support line-buffering and requires size >= 2 */
5738 setvbuf(stdout, NULL, _IOLBF, 0);
5739 #endif
5741 init_timers();
5742 if (init_timer_alarm() < 0) {
5743 fprintf(stderr, "could not initialize alarm timer\n");
5744 exit(1);
5746 if (use_icount && icount_time_shift < 0) {
5747 use_icount = 2;
5748 /* 125MIPS seems a reasonable initial guess at the guest speed.
5749 It will be corrected fairly quickly anyway. */
5750 icount_time_shift = 3;
5751 init_icount_adjust();
5754 #ifdef _WIN32
5755 socket_init();
5756 #endif
5758 /* init network clients */
5759 if (nb_net_clients == 0) {
5760 /* if no clients, we use a default config */
5761 net_clients[nb_net_clients++] = "nic";
5762 #ifdef CONFIG_SLIRP
5763 net_clients[nb_net_clients++] = "user";
5764 #endif
5767 for(i = 0;i < nb_net_clients; i++) {
5768 if (net_client_parse(net_clients[i]) < 0)
5769 exit(1);
5772 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5773 net_set_boot_mask(net_boot);
5775 net_client_check();
5777 /* init the bluetooth world */
5778 if (foreach_device_config(DEV_BT, bt_parse))
5779 exit(1);
5781 /* init the memory */
5782 if (ram_size == 0)
5783 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5785 /* init the dynamic translator */
5786 cpu_exec_init_all(tb_size * 1024 * 1024);
5788 bdrv_init();
5790 /* we always create the cdrom drive, even if no disk is there */
5791 drive_add(NULL, CDROM_ALIAS);
5793 /* we always create at least one floppy */
5794 drive_add(NULL, FD_ALIAS, 0);
5796 /* we always create one sd slot, even if no card is in it */
5797 drive_add(NULL, SD_ALIAS);
5799 /* open the virtual block devices */
5800 if (snapshot)
5801 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5802 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5803 exit(1);
5805 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5806 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5808 #ifndef _WIN32
5809 /* must be after terminal init, SDL library changes signal handlers */
5810 sighandler_setup();
5811 #endif
5813 /* Maintain compatibility with multiple stdio monitors */
5814 if (!strcmp(monitor_device,"stdio")) {
5815 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5816 const char *devname = serial_devices[i];
5817 if (devname && !strcmp(devname,"mon:stdio")) {
5818 monitor_device = NULL;
5819 break;
5820 } else if (devname && !strcmp(devname,"stdio")) {
5821 monitor_device = NULL;
5822 serial_devices[i] = "mon:stdio";
5823 break;
5828 if (nb_numa_nodes > 0) {
5829 int i;
5831 if (nb_numa_nodes > smp_cpus) {
5832 nb_numa_nodes = smp_cpus;
5835 /* If no memory size if given for any node, assume the default case
5836 * and distribute the available memory equally across all nodes
5838 for (i = 0; i < nb_numa_nodes; i++) {
5839 if (node_mem[i] != 0)
5840 break;
5842 if (i == nb_numa_nodes) {
5843 uint64_t usedmem = 0;
5845 /* On Linux, the each node's border has to be 8MB aligned,
5846 * the final node gets the rest.
5848 for (i = 0; i < nb_numa_nodes - 1; i++) {
5849 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5850 usedmem += node_mem[i];
5852 node_mem[i] = ram_size - usedmem;
5855 for (i = 0; i < nb_numa_nodes; i++) {
5856 if (node_cpumask[i] != 0)
5857 break;
5859 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5860 * must cope with this anyway, because there are BIOSes out there in
5861 * real machines which also use this scheme.
5863 if (i == nb_numa_nodes) {
5864 for (i = 0; i < smp_cpus; i++) {
5865 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5870 if (kvm_enabled()) {
5871 int ret;
5873 ret = kvm_init(smp_cpus);
5874 if (ret < 0) {
5875 fprintf(stderr, "failed to initialize KVM\n");
5876 exit(1);
5880 if (monitor_device) {
5881 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5882 if (!monitor_hd) {
5883 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5884 exit(1);
5888 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5889 const char *devname = serial_devices[i];
5890 if (devname && strcmp(devname, "none")) {
5891 char label[32];
5892 snprintf(label, sizeof(label), "serial%d", i);
5893 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5894 if (!serial_hds[i]) {
5895 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5896 devname);
5897 exit(1);
5902 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5903 const char *devname = parallel_devices[i];
5904 if (devname && strcmp(devname, "none")) {
5905 char label[32];
5906 snprintf(label, sizeof(label), "parallel%d", i);
5907 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5908 if (!parallel_hds[i]) {
5909 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5910 devname);
5911 exit(1);
5916 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5917 const char *devname = virtio_consoles[i];
5918 if (devname && strcmp(devname, "none")) {
5919 char label[32];
5920 snprintf(label, sizeof(label), "virtcon%d", i);
5921 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5922 if (!virtcon_hds[i]) {
5923 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5924 devname);
5925 exit(1);
5930 module_call_init(MODULE_INIT_DEVICE);
5932 if (machine->compat_props) {
5933 qdev_prop_register_compat(machine->compat_props);
5935 machine->init(ram_size, boot_devices,
5936 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5939 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5940 for (i = 0; i < nb_numa_nodes; i++) {
5941 if (node_cpumask[i] & (1 << env->cpu_index)) {
5942 env->numa_node = i;
5947 current_machine = machine;
5949 /* init USB devices */
5950 if (usb_enabled) {
5951 foreach_device_config(DEV_USB, usb_parse);
5954 /* init generic devices */
5955 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5956 exit(1);
5958 if (!display_state)
5959 dumb_display_init();
5960 /* just use the first displaystate for the moment */
5961 ds = display_state;
5963 if (display_type == DT_DEFAULT) {
5964 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5965 display_type = DT_SDL;
5966 #else
5967 display_type = DT_VNC;
5968 vnc_display = "localhost:0,to=99";
5969 show_vnc_port = 1;
5970 #endif
5974 switch (display_type) {
5975 case DT_NOGRAPHIC:
5976 break;
5977 #if defined(CONFIG_CURSES)
5978 case DT_CURSES:
5979 curses_display_init(ds, full_screen);
5980 break;
5981 #endif
5982 #if defined(CONFIG_SDL)
5983 case DT_SDL:
5984 sdl_display_init(ds, full_screen, no_frame);
5985 break;
5986 #elif defined(CONFIG_COCOA)
5987 case DT_SDL:
5988 cocoa_display_init(ds, full_screen);
5989 break;
5990 #endif
5991 case DT_VNC:
5992 vnc_display_init(ds);
5993 if (vnc_display_open(ds, vnc_display) < 0)
5994 exit(1);
5996 if (show_vnc_port) {
5997 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5999 break;
6000 default:
6001 break;
6003 dpy_resize(ds);
6005 dcl = ds->listeners;
6006 while (dcl != NULL) {
6007 if (dcl->dpy_refresh != NULL) {
6008 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6009 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6011 dcl = dcl->next;
6014 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6015 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6016 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6019 text_consoles_set_display(display_state);
6020 qemu_chr_initial_reset();
6022 if (monitor_device && monitor_hd)
6023 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6025 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6026 const char *devname = serial_devices[i];
6027 if (devname && strcmp(devname, "none")) {
6028 if (strstart(devname, "vc", 0))
6029 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6033 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6034 const char *devname = parallel_devices[i];
6035 if (devname && strcmp(devname, "none")) {
6036 if (strstart(devname, "vc", 0))
6037 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6041 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6042 const char *devname = virtio_consoles[i];
6043 if (virtcon_hds[i] && devname) {
6044 if (strstart(devname, "vc", 0))
6045 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6049 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6050 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6051 gdbstub_dev);
6052 exit(1);
6055 if (loadvm) {
6056 if (load_vmstate(cur_mon, loadvm) < 0) {
6057 autostart = 0;
6061 if (incoming) {
6062 qemu_start_incoming_migration(incoming);
6063 } else if (autostart) {
6064 vm_start();
6067 #ifndef _WIN32
6068 if (daemonize) {
6069 uint8_t status = 0;
6070 ssize_t len;
6072 again1:
6073 len = write(fds[1], &status, 1);
6074 if (len == -1 && (errno == EINTR))
6075 goto again1;
6077 if (len != 1)
6078 exit(1);
6080 chdir("/");
6081 TFR(fd = open("/dev/null", O_RDWR));
6082 if (fd == -1)
6083 exit(1);
6086 if (run_as) {
6087 pwd = getpwnam(run_as);
6088 if (!pwd) {
6089 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6090 exit(1);
6094 if (chroot_dir) {
6095 if (chroot(chroot_dir) < 0) {
6096 fprintf(stderr, "chroot failed\n");
6097 exit(1);
6099 chdir("/");
6102 if (run_as) {
6103 if (setgid(pwd->pw_gid) < 0) {
6104 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6105 exit(1);
6107 if (setuid(pwd->pw_uid) < 0) {
6108 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6109 exit(1);
6111 if (setuid(0) != -1) {
6112 fprintf(stderr, "Dropping privileges failed\n");
6113 exit(1);
6117 if (daemonize) {
6118 dup2(fd, 0);
6119 dup2(fd, 1);
6120 dup2(fd, 2);
6122 close(fd);
6124 #endif
6126 main_loop();
6127 quit_timers();
6128 net_cleanup();
6130 return 0;