QemuOpts: switch over -device.
[qemu.git] / vl.c
blob6c4a5099894257939222c441f8f46584c247e64a
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 cirrus_vga_enabled = 1;
195 int std_vga_enabled = 0;
196 int vmsvga_enabled = 0;
197 int xenfb_enabled = 0;
198 #ifdef TARGET_SPARC
199 int graphic_width = 1024;
200 int graphic_height = 768;
201 int graphic_depth = 8;
202 #else
203 int graphic_width = 800;
204 int graphic_height = 600;
205 int graphic_depth = 15;
206 #endif
207 static int full_screen = 0;
208 #ifdef CONFIG_SDL
209 static int no_frame = 0;
210 #endif
211 int no_quit = 0;
212 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
213 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
214 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
215 #ifdef TARGET_I386
216 int win2k_install_hack = 0;
217 int rtc_td_hack = 0;
218 #endif
219 int usb_enabled = 0;
220 int singlestep = 0;
221 int smp_cpus = 1;
222 int max_cpus = 0;
223 const char *vnc_display;
224 int acpi_enabled = 1;
225 int no_hpet = 0;
226 int virtio_balloon = 1;
227 const char *virtio_balloon_devaddr;
228 int fd_bootchk = 1;
229 int no_reboot = 0;
230 int no_shutdown = 0;
231 int cursor_hide = 1;
232 int graphic_rotate = 0;
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 #ifdef __linux__
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 static inline 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);
1144 #ifdef CONFIG_KQEMU
1145 if (next_cpu->kqemu_enabled) {
1146 kqemu_cpu_interrupt(next_cpu);
1148 #endif
1150 #endif
1151 timer_alarm_pending = 1;
1152 qemu_notify_event();
1156 static int64_t qemu_next_deadline(void)
1158 int64_t delta;
1160 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1161 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1162 qemu_get_clock(vm_clock);
1163 } else {
1164 /* To avoid problems with overflow limit this to 2^32. */
1165 delta = INT32_MAX;
1168 if (delta < 0)
1169 delta = 0;
1171 return delta;
1174 #if defined(__linux__) || defined(_WIN32)
1175 static uint64_t qemu_next_deadline_dyntick(void)
1177 int64_t delta;
1178 int64_t rtdelta;
1180 if (use_icount)
1181 delta = INT32_MAX;
1182 else
1183 delta = (qemu_next_deadline() + 999) / 1000;
1185 if (active_timers[QEMU_TIMER_REALTIME]) {
1186 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1187 qemu_get_clock(rt_clock))*1000;
1188 if (rtdelta < delta)
1189 delta = rtdelta;
1192 if (delta < MIN_TIMER_REARM_US)
1193 delta = MIN_TIMER_REARM_US;
1195 return delta;
1197 #endif
1199 #ifndef _WIN32
1201 /* Sets a specific flag */
1202 static int fcntl_setfl(int fd, int flag)
1204 int flags;
1206 flags = fcntl(fd, F_GETFL);
1207 if (flags == -1)
1208 return -errno;
1210 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1211 return -errno;
1213 return 0;
1216 #if defined(__linux__)
1218 #define RTC_FREQ 1024
1220 static void enable_sigio_timer(int fd)
1222 struct sigaction act;
1224 /* timer signal */
1225 sigfillset(&act.sa_mask);
1226 act.sa_flags = 0;
1227 act.sa_handler = host_alarm_handler;
1229 sigaction(SIGIO, &act, NULL);
1230 fcntl_setfl(fd, O_ASYNC);
1231 fcntl(fd, F_SETOWN, getpid());
1234 static int hpet_start_timer(struct qemu_alarm_timer *t)
1236 struct hpet_info info;
1237 int r, fd;
1239 fd = open("/dev/hpet", O_RDONLY);
1240 if (fd < 0)
1241 return -1;
1243 /* Set frequency */
1244 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1245 if (r < 0) {
1246 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1247 "error, but for better emulation accuracy type:\n"
1248 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1249 goto fail;
1252 /* Check capabilities */
1253 r = ioctl(fd, HPET_INFO, &info);
1254 if (r < 0)
1255 goto fail;
1257 /* Enable periodic mode */
1258 r = ioctl(fd, HPET_EPI, 0);
1259 if (info.hi_flags && (r < 0))
1260 goto fail;
1262 /* Enable interrupt */
1263 r = ioctl(fd, HPET_IE_ON, 0);
1264 if (r < 0)
1265 goto fail;
1267 enable_sigio_timer(fd);
1268 t->priv = (void *)(long)fd;
1270 return 0;
1271 fail:
1272 close(fd);
1273 return -1;
1276 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1278 int fd = (long)t->priv;
1280 close(fd);
1283 static int rtc_start_timer(struct qemu_alarm_timer *t)
1285 int rtc_fd;
1286 unsigned long current_rtc_freq = 0;
1288 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1289 if (rtc_fd < 0)
1290 return -1;
1291 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1292 if (current_rtc_freq != RTC_FREQ &&
1293 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1294 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1295 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1296 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1297 goto fail;
1299 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1300 fail:
1301 close(rtc_fd);
1302 return -1;
1305 enable_sigio_timer(rtc_fd);
1307 t->priv = (void *)(long)rtc_fd;
1309 return 0;
1312 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1314 int rtc_fd = (long)t->priv;
1316 close(rtc_fd);
1319 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1321 struct sigevent ev;
1322 timer_t host_timer;
1323 struct sigaction act;
1325 sigfillset(&act.sa_mask);
1326 act.sa_flags = 0;
1327 act.sa_handler = host_alarm_handler;
1329 sigaction(SIGALRM, &act, NULL);
1332 * Initialize ev struct to 0 to avoid valgrind complaining
1333 * about uninitialized data in timer_create call
1335 memset(&ev, 0, sizeof(ev));
1336 ev.sigev_value.sival_int = 0;
1337 ev.sigev_notify = SIGEV_SIGNAL;
1338 ev.sigev_signo = SIGALRM;
1340 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1341 perror("timer_create");
1343 /* disable dynticks */
1344 fprintf(stderr, "Dynamic Ticks disabled\n");
1346 return -1;
1349 t->priv = (void *)(long)host_timer;
1351 return 0;
1354 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1356 timer_t host_timer = (timer_t)(long)t->priv;
1358 timer_delete(host_timer);
1361 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1363 timer_t host_timer = (timer_t)(long)t->priv;
1364 struct itimerspec timeout;
1365 int64_t nearest_delta_us = INT64_MAX;
1366 int64_t current_us;
1368 if (!active_timers[QEMU_TIMER_REALTIME] &&
1369 !active_timers[QEMU_TIMER_VIRTUAL])
1370 return;
1372 nearest_delta_us = qemu_next_deadline_dyntick();
1374 /* check whether a timer is already running */
1375 if (timer_gettime(host_timer, &timeout)) {
1376 perror("gettime");
1377 fprintf(stderr, "Internal timer error: aborting\n");
1378 exit(1);
1380 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1381 if (current_us && current_us <= nearest_delta_us)
1382 return;
1384 timeout.it_interval.tv_sec = 0;
1385 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1386 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1387 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1388 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1389 perror("settime");
1390 fprintf(stderr, "Internal timer error: aborting\n");
1391 exit(1);
1395 #endif /* defined(__linux__) */
1397 static int unix_start_timer(struct qemu_alarm_timer *t)
1399 struct sigaction act;
1400 struct itimerval itv;
1401 int err;
1403 /* timer signal */
1404 sigfillset(&act.sa_mask);
1405 act.sa_flags = 0;
1406 act.sa_handler = host_alarm_handler;
1408 sigaction(SIGALRM, &act, NULL);
1410 itv.it_interval.tv_sec = 0;
1411 /* for i386 kernel 2.6 to get 1 ms */
1412 itv.it_interval.tv_usec = 999;
1413 itv.it_value.tv_sec = 0;
1414 itv.it_value.tv_usec = 10 * 1000;
1416 err = setitimer(ITIMER_REAL, &itv, NULL);
1417 if (err)
1418 return -1;
1420 return 0;
1423 static void unix_stop_timer(struct qemu_alarm_timer *t)
1425 struct itimerval itv;
1427 memset(&itv, 0, sizeof(itv));
1428 setitimer(ITIMER_REAL, &itv, NULL);
1431 #endif /* !defined(_WIN32) */
1434 #ifdef _WIN32
1436 static int win32_start_timer(struct qemu_alarm_timer *t)
1438 TIMECAPS tc;
1439 struct qemu_alarm_win32 *data = t->priv;
1440 UINT flags;
1442 memset(&tc, 0, sizeof(tc));
1443 timeGetDevCaps(&tc, sizeof(tc));
1445 if (data->period < tc.wPeriodMin)
1446 data->period = tc.wPeriodMin;
1448 timeBeginPeriod(data->period);
1450 flags = TIME_CALLBACK_FUNCTION;
1451 if (alarm_has_dynticks(t))
1452 flags |= TIME_ONESHOT;
1453 else
1454 flags |= TIME_PERIODIC;
1456 data->timerId = timeSetEvent(1, // interval (ms)
1457 data->period, // resolution
1458 host_alarm_handler, // function
1459 (DWORD)t, // parameter
1460 flags);
1462 if (!data->timerId) {
1463 perror("Failed to initialize win32 alarm timer");
1464 timeEndPeriod(data->period);
1465 return -1;
1468 return 0;
1471 static void win32_stop_timer(struct qemu_alarm_timer *t)
1473 struct qemu_alarm_win32 *data = t->priv;
1475 timeKillEvent(data->timerId);
1476 timeEndPeriod(data->period);
1479 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1481 struct qemu_alarm_win32 *data = t->priv;
1482 uint64_t nearest_delta_us;
1484 if (!active_timers[QEMU_TIMER_REALTIME] &&
1485 !active_timers[QEMU_TIMER_VIRTUAL])
1486 return;
1488 nearest_delta_us = qemu_next_deadline_dyntick();
1489 nearest_delta_us /= 1000;
1491 timeKillEvent(data->timerId);
1493 data->timerId = timeSetEvent(1,
1494 data->period,
1495 host_alarm_handler,
1496 (DWORD)t,
1497 TIME_ONESHOT | TIME_PERIODIC);
1499 if (!data->timerId) {
1500 perror("Failed to re-arm win32 alarm timer");
1502 timeEndPeriod(data->period);
1503 exit(1);
1507 #endif /* _WIN32 */
1509 static int init_timer_alarm(void)
1511 struct qemu_alarm_timer *t = NULL;
1512 int i, err = -1;
1514 for (i = 0; alarm_timers[i].name; i++) {
1515 t = &alarm_timers[i];
1517 err = t->start(t);
1518 if (!err)
1519 break;
1522 if (err) {
1523 err = -ENOENT;
1524 goto fail;
1527 alarm_timer = t;
1529 return 0;
1531 fail:
1532 return err;
1535 static void quit_timers(void)
1537 alarm_timer->stop(alarm_timer);
1538 alarm_timer = NULL;
1541 /***********************************************************/
1542 /* host time/date access */
1543 void qemu_get_timedate(struct tm *tm, int offset)
1545 time_t ti;
1546 struct tm *ret;
1548 time(&ti);
1549 ti += offset;
1550 if (rtc_date_offset == -1) {
1551 if (rtc_utc)
1552 ret = gmtime(&ti);
1553 else
1554 ret = localtime(&ti);
1555 } else {
1556 ti -= rtc_date_offset;
1557 ret = gmtime(&ti);
1560 memcpy(tm, ret, sizeof(struct tm));
1563 int qemu_timedate_diff(struct tm *tm)
1565 time_t seconds;
1567 if (rtc_date_offset == -1)
1568 if (rtc_utc)
1569 seconds = mktimegm(tm);
1570 else
1571 seconds = mktime(tm);
1572 else
1573 seconds = mktimegm(tm) + rtc_date_offset;
1575 return seconds - time(NULL);
1578 #ifdef _WIN32
1579 static void socket_cleanup(void)
1581 WSACleanup();
1584 static int socket_init(void)
1586 WSADATA Data;
1587 int ret, err;
1589 ret = WSAStartup(MAKEWORD(2,2), &Data);
1590 if (ret != 0) {
1591 err = WSAGetLastError();
1592 fprintf(stderr, "WSAStartup: %d\n", err);
1593 return -1;
1595 atexit(socket_cleanup);
1596 return 0;
1598 #endif
1600 /***********************************************************/
1601 /* Bluetooth support */
1602 static int nb_hcis;
1603 static int cur_hci;
1604 static struct HCIInfo *hci_table[MAX_NICS];
1606 static struct bt_vlan_s {
1607 struct bt_scatternet_s net;
1608 int id;
1609 struct bt_vlan_s *next;
1610 } *first_bt_vlan;
1612 /* find or alloc a new bluetooth "VLAN" */
1613 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1615 struct bt_vlan_s **pvlan, *vlan;
1616 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1617 if (vlan->id == id)
1618 return &vlan->net;
1620 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1621 vlan->id = id;
1622 pvlan = &first_bt_vlan;
1623 while (*pvlan != NULL)
1624 pvlan = &(*pvlan)->next;
1625 *pvlan = vlan;
1626 return &vlan->net;
1629 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1633 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1635 return -ENOTSUP;
1638 static struct HCIInfo null_hci = {
1639 .cmd_send = null_hci_send,
1640 .sco_send = null_hci_send,
1641 .acl_send = null_hci_send,
1642 .bdaddr_set = null_hci_addr_set,
1645 struct HCIInfo *qemu_next_hci(void)
1647 if (cur_hci == nb_hcis)
1648 return &null_hci;
1650 return hci_table[cur_hci++];
1653 static struct HCIInfo *hci_init(const char *str)
1655 char *endp;
1656 struct bt_scatternet_s *vlan = 0;
1658 if (!strcmp(str, "null"))
1659 /* null */
1660 return &null_hci;
1661 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1662 /* host[:hciN] */
1663 return bt_host_hci(str[4] ? str + 5 : "hci0");
1664 else if (!strncmp(str, "hci", 3)) {
1665 /* hci[,vlan=n] */
1666 if (str[3]) {
1667 if (!strncmp(str + 3, ",vlan=", 6)) {
1668 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1669 if (*endp)
1670 vlan = 0;
1672 } else
1673 vlan = qemu_find_bt_vlan(0);
1674 if (vlan)
1675 return bt_new_hci(vlan);
1678 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1680 return 0;
1683 static int bt_hci_parse(const char *str)
1685 struct HCIInfo *hci;
1686 bdaddr_t bdaddr;
1688 if (nb_hcis >= MAX_NICS) {
1689 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1690 return -1;
1693 hci = hci_init(str);
1694 if (!hci)
1695 return -1;
1697 bdaddr.b[0] = 0x52;
1698 bdaddr.b[1] = 0x54;
1699 bdaddr.b[2] = 0x00;
1700 bdaddr.b[3] = 0x12;
1701 bdaddr.b[4] = 0x34;
1702 bdaddr.b[5] = 0x56 + nb_hcis;
1703 hci->bdaddr_set(hci, bdaddr.b);
1705 hci_table[nb_hcis++] = hci;
1707 return 0;
1710 static void bt_vhci_add(int vlan_id)
1712 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1714 if (!vlan->slave)
1715 fprintf(stderr, "qemu: warning: adding a VHCI to "
1716 "an empty scatternet %i\n", vlan_id);
1718 bt_vhci_init(bt_new_hci(vlan));
1721 static struct bt_device_s *bt_device_add(const char *opt)
1723 struct bt_scatternet_s *vlan;
1724 int vlan_id = 0;
1725 char *endp = strstr(opt, ",vlan=");
1726 int len = (endp ? endp - opt : strlen(opt)) + 1;
1727 char devname[10];
1729 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1731 if (endp) {
1732 vlan_id = strtol(endp + 6, &endp, 0);
1733 if (*endp) {
1734 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1735 return 0;
1739 vlan = qemu_find_bt_vlan(vlan_id);
1741 if (!vlan->slave)
1742 fprintf(stderr, "qemu: warning: adding a slave device to "
1743 "an empty scatternet %i\n", vlan_id);
1745 if (!strcmp(devname, "keyboard"))
1746 return bt_keyboard_init(vlan);
1748 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1749 return 0;
1752 static int bt_parse(const char *opt)
1754 const char *endp, *p;
1755 int vlan;
1757 if (strstart(opt, "hci", &endp)) {
1758 if (!*endp || *endp == ',') {
1759 if (*endp)
1760 if (!strstart(endp, ",vlan=", 0))
1761 opt = endp + 1;
1763 return bt_hci_parse(opt);
1765 } else if (strstart(opt, "vhci", &endp)) {
1766 if (!*endp || *endp == ',') {
1767 if (*endp) {
1768 if (strstart(endp, ",vlan=", &p)) {
1769 vlan = strtol(p, (char **) &endp, 0);
1770 if (*endp) {
1771 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1772 return 1;
1774 } else {
1775 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1776 return 1;
1778 } else
1779 vlan = 0;
1781 bt_vhci_add(vlan);
1782 return 0;
1784 } else if (strstart(opt, "device:", &endp))
1785 return !bt_device_add(endp);
1787 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1788 return 1;
1791 /***********************************************************/
1792 /* QEMU Block devices */
1794 #define HD_ALIAS "index=%d,media=disk"
1795 #define CDROM_ALIAS "index=2,media=cdrom"
1796 #define FD_ALIAS "index=%d,if=floppy"
1797 #define PFLASH_ALIAS "if=pflash"
1798 #define MTD_ALIAS "if=mtd"
1799 #define SD_ALIAS "index=0,if=sd"
1801 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1803 va_list ap;
1804 char optstr[1024];
1805 QemuOpts *opts;
1807 va_start(ap, fmt);
1808 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1809 va_end(ap);
1811 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1812 if (!opts) {
1813 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1814 __FUNCTION__, optstr);
1815 return NULL;
1817 if (file)
1818 qemu_opt_set(opts, "file", file);
1819 return opts;
1822 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1824 DriveInfo *dinfo;
1826 /* seek interface, bus and unit */
1828 TAILQ_FOREACH(dinfo, &drives, next) {
1829 if (dinfo->type == type &&
1830 dinfo->bus == bus &&
1831 dinfo->unit == unit)
1832 return dinfo;
1835 return NULL;
1838 DriveInfo *drive_get_by_id(char *id)
1840 DriveInfo *dinfo;
1842 TAILQ_FOREACH(dinfo, &drives, next) {
1843 if (strcmp(id, dinfo->id))
1844 continue;
1845 return dinfo;
1847 return NULL;
1850 int drive_get_max_bus(BlockInterfaceType type)
1852 int max_bus;
1853 DriveInfo *dinfo;
1855 max_bus = -1;
1856 TAILQ_FOREACH(dinfo, &drives, next) {
1857 if(dinfo->type == type &&
1858 dinfo->bus > max_bus)
1859 max_bus = dinfo->bus;
1861 return max_bus;
1864 const char *drive_get_serial(BlockDriverState *bdrv)
1866 DriveInfo *dinfo;
1868 TAILQ_FOREACH(dinfo, &drives, next) {
1869 if (dinfo->bdrv == bdrv)
1870 return dinfo->serial;
1873 return "\0";
1876 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1878 DriveInfo *dinfo;
1880 TAILQ_FOREACH(dinfo, &drives, next) {
1881 if (dinfo->bdrv == bdrv)
1882 return dinfo->onerror;
1885 return BLOCK_ERR_STOP_ENOSPC;
1888 static void bdrv_format_print(void *opaque, const char *name)
1890 fprintf(stderr, " %s", name);
1893 void drive_uninit(BlockDriverState *bdrv)
1895 DriveInfo *dinfo;
1897 TAILQ_FOREACH(dinfo, &drives, next) {
1898 if (dinfo->bdrv != bdrv)
1899 continue;
1900 qemu_opts_del(dinfo->opts);
1901 TAILQ_REMOVE(&drives, dinfo, next);
1902 qemu_free(dinfo);
1903 break;
1907 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1908 int *fatal_error)
1910 const char *buf;
1911 const char *file = NULL;
1912 char devname[128];
1913 const char *serial;
1914 const char *mediastr = "";
1915 BlockInterfaceType type;
1916 enum { MEDIA_DISK, MEDIA_CDROM } media;
1917 int bus_id, unit_id;
1918 int cyls, heads, secs, translation;
1919 BlockDriver *drv = NULL;
1920 QEMUMachine *machine = opaque;
1921 int max_devs;
1922 int index;
1923 int cache;
1924 int bdrv_flags, onerror;
1925 const char *devaddr;
1926 DriveInfo *dinfo;
1927 int snapshot = 0;
1929 *fatal_error = 1;
1931 translation = BIOS_ATA_TRANSLATION_AUTO;
1932 cache = 1;
1934 if (machine->use_scsi) {
1935 type = IF_SCSI;
1936 max_devs = MAX_SCSI_DEVS;
1937 pstrcpy(devname, sizeof(devname), "scsi");
1938 } else {
1939 type = IF_IDE;
1940 max_devs = MAX_IDE_DEVS;
1941 pstrcpy(devname, sizeof(devname), "ide");
1943 media = MEDIA_DISK;
1945 /* extract parameters */
1946 bus_id = qemu_opt_get_number(opts, "bus", 0);
1947 unit_id = qemu_opt_get_number(opts, "unit", -1);
1948 index = qemu_opt_get_number(opts, "index", -1);
1950 cyls = qemu_opt_get_number(opts, "cyls", 0);
1951 heads = qemu_opt_get_number(opts, "heads", 0);
1952 secs = qemu_opt_get_number(opts, "secs", 0);
1954 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1956 file = qemu_opt_get(opts, "file");
1957 serial = qemu_opt_get(opts, "serial");
1959 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1960 pstrcpy(devname, sizeof(devname), buf);
1961 if (!strcmp(buf, "ide")) {
1962 type = IF_IDE;
1963 max_devs = MAX_IDE_DEVS;
1964 } else if (!strcmp(buf, "scsi")) {
1965 type = IF_SCSI;
1966 max_devs = MAX_SCSI_DEVS;
1967 } else if (!strcmp(buf, "floppy")) {
1968 type = IF_FLOPPY;
1969 max_devs = 0;
1970 } else if (!strcmp(buf, "pflash")) {
1971 type = IF_PFLASH;
1972 max_devs = 0;
1973 } else if (!strcmp(buf, "mtd")) {
1974 type = IF_MTD;
1975 max_devs = 0;
1976 } else if (!strcmp(buf, "sd")) {
1977 type = IF_SD;
1978 max_devs = 0;
1979 } else if (!strcmp(buf, "virtio")) {
1980 type = IF_VIRTIO;
1981 max_devs = 0;
1982 } else if (!strcmp(buf, "xen")) {
1983 type = IF_XEN;
1984 max_devs = 0;
1985 } else {
1986 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
1987 return NULL;
1991 if (cyls || heads || secs) {
1992 if (cyls < 1 || cyls > 16383) {
1993 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
1994 return NULL;
1996 if (heads < 1 || heads > 16) {
1997 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
1998 return NULL;
2000 if (secs < 1 || secs > 63) {
2001 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2002 return NULL;
2006 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2007 if (!cyls) {
2008 fprintf(stderr,
2009 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2010 buf);
2011 return NULL;
2013 if (!strcmp(buf, "none"))
2014 translation = BIOS_ATA_TRANSLATION_NONE;
2015 else if (!strcmp(buf, "lba"))
2016 translation = BIOS_ATA_TRANSLATION_LBA;
2017 else if (!strcmp(buf, "auto"))
2018 translation = BIOS_ATA_TRANSLATION_AUTO;
2019 else {
2020 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2021 return NULL;
2025 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2026 if (!strcmp(buf, "disk")) {
2027 media = MEDIA_DISK;
2028 } else if (!strcmp(buf, "cdrom")) {
2029 if (cyls || secs || heads) {
2030 fprintf(stderr,
2031 "qemu: '%s' invalid physical CHS format\n", buf);
2032 return NULL;
2034 media = MEDIA_CDROM;
2035 } else {
2036 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2037 return NULL;
2041 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2042 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2043 cache = 0;
2044 else if (!strcmp(buf, "writethrough"))
2045 cache = 1;
2046 else if (!strcmp(buf, "writeback"))
2047 cache = 2;
2048 else {
2049 fprintf(stderr, "qemu: invalid cache option\n");
2050 return NULL;
2054 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2055 if (strcmp(buf, "?") == 0) {
2056 fprintf(stderr, "qemu: Supported formats:");
2057 bdrv_iterate_format(bdrv_format_print, NULL);
2058 fprintf(stderr, "\n");
2059 return NULL;
2061 drv = bdrv_find_format(buf);
2062 if (!drv) {
2063 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2064 return NULL;
2068 onerror = BLOCK_ERR_STOP_ENOSPC;
2069 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2070 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2071 fprintf(stderr, "werror is no supported by this format\n");
2072 return NULL;
2074 if (!strcmp(buf, "ignore"))
2075 onerror = BLOCK_ERR_IGNORE;
2076 else if (!strcmp(buf, "enospc"))
2077 onerror = BLOCK_ERR_STOP_ENOSPC;
2078 else if (!strcmp(buf, "stop"))
2079 onerror = BLOCK_ERR_STOP_ANY;
2080 else if (!strcmp(buf, "report"))
2081 onerror = BLOCK_ERR_REPORT;
2082 else {
2083 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2084 return NULL;
2088 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2089 if (type != IF_VIRTIO) {
2090 fprintf(stderr, "addr is not supported\n");
2091 return NULL;
2095 /* compute bus and unit according index */
2097 if (index != -1) {
2098 if (bus_id != 0 || unit_id != -1) {
2099 fprintf(stderr,
2100 "qemu: index cannot be used with bus and unit\n");
2101 return NULL;
2103 if (max_devs == 0)
2105 unit_id = index;
2106 bus_id = 0;
2107 } else {
2108 unit_id = index % max_devs;
2109 bus_id = index / max_devs;
2113 /* if user doesn't specify a unit_id,
2114 * try to find the first free
2117 if (unit_id == -1) {
2118 unit_id = 0;
2119 while (drive_get(type, bus_id, unit_id) != NULL) {
2120 unit_id++;
2121 if (max_devs && unit_id >= max_devs) {
2122 unit_id -= max_devs;
2123 bus_id++;
2128 /* check unit id */
2130 if (max_devs && unit_id >= max_devs) {
2131 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2132 unit_id, max_devs - 1);
2133 return NULL;
2137 * ignore multiple definitions
2140 if (drive_get(type, bus_id, unit_id) != NULL) {
2141 *fatal_error = 0;
2142 return NULL;
2145 /* init */
2147 dinfo = qemu_mallocz(sizeof(*dinfo));
2148 if ((buf = qemu_opts_id(opts)) != NULL) {
2149 dinfo->id = qemu_strdup(buf);
2150 } else {
2151 /* no id supplied -> create one */
2152 dinfo->id = qemu_mallocz(32);
2153 if (type == IF_IDE || type == IF_SCSI)
2154 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2155 if (max_devs)
2156 snprintf(dinfo->id, 32, "%s%i%s%i",
2157 devname, bus_id, mediastr, unit_id);
2158 else
2159 snprintf(dinfo->id, 32, "%s%s%i",
2160 devname, mediastr, unit_id);
2162 dinfo->bdrv = bdrv_new(dinfo->id);
2163 dinfo->devaddr = devaddr;
2164 dinfo->type = type;
2165 dinfo->bus = bus_id;
2166 dinfo->unit = unit_id;
2167 dinfo->onerror = onerror;
2168 dinfo->opts = opts;
2169 if (serial)
2170 strncpy(dinfo->serial, serial, sizeof(serial));
2171 TAILQ_INSERT_TAIL(&drives, dinfo, next);
2173 switch(type) {
2174 case IF_IDE:
2175 case IF_SCSI:
2176 case IF_XEN:
2177 switch(media) {
2178 case MEDIA_DISK:
2179 if (cyls != 0) {
2180 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2181 bdrv_set_translation_hint(dinfo->bdrv, translation);
2183 break;
2184 case MEDIA_CDROM:
2185 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2186 break;
2188 break;
2189 case IF_SD:
2190 /* FIXME: This isn't really a floppy, but it's a reasonable
2191 approximation. */
2192 case IF_FLOPPY:
2193 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2194 break;
2195 case IF_PFLASH:
2196 case IF_MTD:
2197 case IF_VIRTIO:
2198 break;
2199 case IF_COUNT:
2200 abort();
2202 if (!file) {
2203 *fatal_error = 0;
2204 return NULL;
2206 bdrv_flags = 0;
2207 if (snapshot) {
2208 bdrv_flags |= BDRV_O_SNAPSHOT;
2209 cache = 2; /* always use write-back with snapshot */
2211 if (cache == 0) /* no caching */
2212 bdrv_flags |= BDRV_O_NOCACHE;
2213 else if (cache == 2) /* write-back */
2214 bdrv_flags |= BDRV_O_CACHE_WB;
2215 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2216 fprintf(stderr, "qemu: could not open disk image %s\n",
2217 file);
2218 return NULL;
2220 if (bdrv_key_required(dinfo->bdrv))
2221 autostart = 0;
2222 *fatal_error = 0;
2223 return dinfo;
2226 static int drive_init_func(QemuOpts *opts, void *opaque)
2228 QEMUMachine *machine = opaque;
2229 int fatal_error = 0;
2231 if (drive_init(opts, machine, &fatal_error) == NULL) {
2232 if (fatal_error)
2233 return 1;
2235 return 0;
2238 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2240 if (NULL == qemu_opt_get(opts, "snapshot")) {
2241 qemu_opt_set(opts, "snapshot", "on");
2243 return 0;
2246 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2248 boot_set_handler = func;
2249 boot_set_opaque = opaque;
2252 int qemu_boot_set(const char *boot_devices)
2254 if (!boot_set_handler) {
2255 return -EINVAL;
2257 return boot_set_handler(boot_set_opaque, boot_devices);
2260 static int parse_bootdevices(char *devices)
2262 /* We just do some generic consistency checks */
2263 const char *p;
2264 int bitmap = 0;
2266 for (p = devices; *p != '\0'; p++) {
2267 /* Allowed boot devices are:
2268 * a-b: floppy disk drives
2269 * c-f: IDE disk drives
2270 * g-m: machine implementation dependant drives
2271 * n-p: network devices
2272 * It's up to each machine implementation to check if the given boot
2273 * devices match the actual hardware implementation and firmware
2274 * features.
2276 if (*p < 'a' || *p > 'p') {
2277 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2278 exit(1);
2280 if (bitmap & (1 << (*p - 'a'))) {
2281 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2282 exit(1);
2284 bitmap |= 1 << (*p - 'a');
2286 return bitmap;
2289 static void restore_boot_devices(void *opaque)
2291 char *standard_boot_devices = opaque;
2293 qemu_boot_set(standard_boot_devices);
2295 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2296 qemu_free(standard_boot_devices);
2299 static void numa_add(const char *optarg)
2301 char option[128];
2302 char *endptr;
2303 unsigned long long value, endvalue;
2304 int nodenr;
2306 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2307 if (!strcmp(option, "node")) {
2308 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2309 nodenr = nb_numa_nodes;
2310 } else {
2311 nodenr = strtoull(option, NULL, 10);
2314 if (get_param_value(option, 128, "mem", optarg) == 0) {
2315 node_mem[nodenr] = 0;
2316 } else {
2317 value = strtoull(option, &endptr, 0);
2318 switch (*endptr) {
2319 case 0: case 'M': case 'm':
2320 value <<= 20;
2321 break;
2322 case 'G': case 'g':
2323 value <<= 30;
2324 break;
2326 node_mem[nodenr] = value;
2328 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2329 node_cpumask[nodenr] = 0;
2330 } else {
2331 value = strtoull(option, &endptr, 10);
2332 if (value >= 64) {
2333 value = 63;
2334 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2335 } else {
2336 if (*endptr == '-') {
2337 endvalue = strtoull(endptr+1, &endptr, 10);
2338 if (endvalue >= 63) {
2339 endvalue = 62;
2340 fprintf(stderr,
2341 "only 63 CPUs in NUMA mode supported.\n");
2343 value = (1 << (endvalue + 1)) - (1 << value);
2344 } else {
2345 value = 1 << value;
2348 node_cpumask[nodenr] = value;
2350 nb_numa_nodes++;
2352 return;
2355 /***********************************************************/
2356 /* USB devices */
2358 static USBPort *used_usb_ports;
2359 static USBPort *free_usb_ports;
2361 /* ??? Maybe change this to register a hub to keep track of the topology. */
2362 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2363 usb_attachfn attach)
2365 port->opaque = opaque;
2366 port->index = index;
2367 port->attach = attach;
2368 port->next = free_usb_ports;
2369 free_usb_ports = port;
2372 int usb_device_add_dev(USBDevice *dev)
2374 USBPort *port;
2376 /* Find a USB port to add the device to. */
2377 port = free_usb_ports;
2378 if (!port->next) {
2379 USBDevice *hub;
2381 /* Create a new hub and chain it on. */
2382 free_usb_ports = NULL;
2383 port->next = used_usb_ports;
2384 used_usb_ports = port;
2386 hub = usb_hub_init(VM_USB_HUB_SIZE);
2387 usb_attach(port, hub);
2388 port = free_usb_ports;
2391 free_usb_ports = port->next;
2392 port->next = used_usb_ports;
2393 used_usb_ports = port;
2394 usb_attach(port, dev);
2395 return 0;
2398 static void usb_msd_password_cb(void *opaque, int err)
2400 USBDevice *dev = opaque;
2402 if (!err)
2403 usb_device_add_dev(dev);
2404 else
2405 dev->handle_destroy(dev);
2408 static int usb_device_add(const char *devname, int is_hotplug)
2410 const char *p;
2411 USBDevice *dev;
2413 if (!free_usb_ports)
2414 return -1;
2416 if (strstart(devname, "host:", &p)) {
2417 dev = usb_host_device_open(p);
2418 } else if (!strcmp(devname, "mouse")) {
2419 dev = usb_mouse_init();
2420 } else if (!strcmp(devname, "tablet")) {
2421 dev = usb_tablet_init();
2422 } else if (!strcmp(devname, "keyboard")) {
2423 dev = usb_keyboard_init();
2424 } else if (strstart(devname, "disk:", &p)) {
2425 BlockDriverState *bs;
2427 dev = usb_msd_init(p);
2428 if (!dev)
2429 return -1;
2430 bs = usb_msd_get_bdrv(dev);
2431 if (bdrv_key_required(bs)) {
2432 autostart = 0;
2433 if (is_hotplug) {
2434 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2435 dev);
2436 return 0;
2439 } else if (!strcmp(devname, "wacom-tablet")) {
2440 dev = usb_wacom_init();
2441 } else if (strstart(devname, "serial:", &p)) {
2442 dev = usb_serial_init(p);
2443 #ifdef CONFIG_BRLAPI
2444 } else if (!strcmp(devname, "braille")) {
2445 dev = usb_baum_init();
2446 #endif
2447 } else if (strstart(devname, "net:", &p)) {
2448 int nic = nb_nics;
2450 if (net_client_init(NULL, "nic", p) < 0)
2451 return -1;
2452 nd_table[nic].model = "usb";
2453 dev = usb_net_init(&nd_table[nic]);
2454 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2455 dev = usb_bt_init(devname[2] ? hci_init(p) :
2456 bt_new_hci(qemu_find_bt_vlan(0)));
2457 } else {
2458 return -1;
2460 if (!dev)
2461 return -1;
2463 return usb_device_add_dev(dev);
2466 int usb_device_del_addr(int bus_num, int addr)
2468 USBPort *port;
2469 USBPort **lastp;
2470 USBDevice *dev;
2472 if (!used_usb_ports)
2473 return -1;
2475 if (bus_num != 0)
2476 return -1;
2478 lastp = &used_usb_ports;
2479 port = used_usb_ports;
2480 while (port && port->dev->addr != addr) {
2481 lastp = &port->next;
2482 port = port->next;
2485 if (!port)
2486 return -1;
2488 dev = port->dev;
2489 *lastp = port->next;
2490 usb_attach(port, NULL);
2491 dev->handle_destroy(dev);
2492 port->next = free_usb_ports;
2493 free_usb_ports = port;
2494 return 0;
2497 static int usb_device_del(const char *devname)
2499 int bus_num, addr;
2500 const char *p;
2502 if (strstart(devname, "host:", &p))
2503 return usb_host_device_close(p);
2505 if (!used_usb_ports)
2506 return -1;
2508 p = strchr(devname, '.');
2509 if (!p)
2510 return -1;
2511 bus_num = strtoul(devname, NULL, 0);
2512 addr = strtoul(p + 1, NULL, 0);
2514 return usb_device_del_addr(bus_num, addr);
2517 static int usb_parse(const char *cmdline)
2519 return usb_device_add(cmdline, 0);
2522 void do_usb_add(Monitor *mon, const char *devname)
2524 usb_device_add(devname, 1);
2527 void do_usb_del(Monitor *mon, const char *devname)
2529 usb_device_del(devname);
2532 void usb_info(Monitor *mon)
2534 USBDevice *dev;
2535 USBPort *port;
2536 const char *speed_str;
2538 if (!usb_enabled) {
2539 monitor_printf(mon, "USB support not enabled\n");
2540 return;
2543 for (port = used_usb_ports; port; port = port->next) {
2544 dev = port->dev;
2545 if (!dev)
2546 continue;
2547 switch(dev->speed) {
2548 case USB_SPEED_LOW:
2549 speed_str = "1.5";
2550 break;
2551 case USB_SPEED_FULL:
2552 speed_str = "12";
2553 break;
2554 case USB_SPEED_HIGH:
2555 speed_str = "480";
2556 break;
2557 default:
2558 speed_str = "?";
2559 break;
2561 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2562 0, dev->addr, speed_str, dev->devname);
2566 /***********************************************************/
2567 /* PCMCIA/Cardbus */
2569 static struct pcmcia_socket_entry_s {
2570 PCMCIASocket *socket;
2571 struct pcmcia_socket_entry_s *next;
2572 } *pcmcia_sockets = 0;
2574 void pcmcia_socket_register(PCMCIASocket *socket)
2576 struct pcmcia_socket_entry_s *entry;
2578 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2579 entry->socket = socket;
2580 entry->next = pcmcia_sockets;
2581 pcmcia_sockets = entry;
2584 void pcmcia_socket_unregister(PCMCIASocket *socket)
2586 struct pcmcia_socket_entry_s *entry, **ptr;
2588 ptr = &pcmcia_sockets;
2589 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2590 if (entry->socket == socket) {
2591 *ptr = entry->next;
2592 qemu_free(entry);
2596 void pcmcia_info(Monitor *mon)
2598 struct pcmcia_socket_entry_s *iter;
2600 if (!pcmcia_sockets)
2601 monitor_printf(mon, "No PCMCIA sockets\n");
2603 for (iter = pcmcia_sockets; iter; iter = iter->next)
2604 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2605 iter->socket->attached ? iter->socket->card_string :
2606 "Empty");
2609 /***********************************************************/
2610 /* register display */
2612 struct DisplayAllocator default_allocator = {
2613 defaultallocator_create_displaysurface,
2614 defaultallocator_resize_displaysurface,
2615 defaultallocator_free_displaysurface
2618 void register_displaystate(DisplayState *ds)
2620 DisplayState **s;
2621 s = &display_state;
2622 while (*s != NULL)
2623 s = &(*s)->next;
2624 ds->next = NULL;
2625 *s = ds;
2628 DisplayState *get_displaystate(void)
2630 return display_state;
2633 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2635 if(ds->allocator == &default_allocator) ds->allocator = da;
2636 return ds->allocator;
2639 /* dumb display */
2641 static void dumb_display_init(void)
2643 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2644 ds->allocator = &default_allocator;
2645 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2646 register_displaystate(ds);
2649 /***********************************************************/
2650 /* I/O handling */
2652 typedef struct IOHandlerRecord {
2653 int fd;
2654 IOCanRWHandler *fd_read_poll;
2655 IOHandler *fd_read;
2656 IOHandler *fd_write;
2657 int deleted;
2658 void *opaque;
2659 /* temporary data */
2660 struct pollfd *ufd;
2661 struct IOHandlerRecord *next;
2662 } IOHandlerRecord;
2664 static IOHandlerRecord *first_io_handler;
2666 /* XXX: fd_read_poll should be suppressed, but an API change is
2667 necessary in the character devices to suppress fd_can_read(). */
2668 int qemu_set_fd_handler2(int fd,
2669 IOCanRWHandler *fd_read_poll,
2670 IOHandler *fd_read,
2671 IOHandler *fd_write,
2672 void *opaque)
2674 IOHandlerRecord **pioh, *ioh;
2676 if (!fd_read && !fd_write) {
2677 pioh = &first_io_handler;
2678 for(;;) {
2679 ioh = *pioh;
2680 if (ioh == NULL)
2681 break;
2682 if (ioh->fd == fd) {
2683 ioh->deleted = 1;
2684 break;
2686 pioh = &ioh->next;
2688 } else {
2689 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2690 if (ioh->fd == fd)
2691 goto found;
2693 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2694 ioh->next = first_io_handler;
2695 first_io_handler = ioh;
2696 found:
2697 ioh->fd = fd;
2698 ioh->fd_read_poll = fd_read_poll;
2699 ioh->fd_read = fd_read;
2700 ioh->fd_write = fd_write;
2701 ioh->opaque = opaque;
2702 ioh->deleted = 0;
2704 return 0;
2707 int qemu_set_fd_handler(int fd,
2708 IOHandler *fd_read,
2709 IOHandler *fd_write,
2710 void *opaque)
2712 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2715 #ifdef _WIN32
2716 /***********************************************************/
2717 /* Polling handling */
2719 typedef struct PollingEntry {
2720 PollingFunc *func;
2721 void *opaque;
2722 struct PollingEntry *next;
2723 } PollingEntry;
2725 static PollingEntry *first_polling_entry;
2727 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2729 PollingEntry **ppe, *pe;
2730 pe = qemu_mallocz(sizeof(PollingEntry));
2731 pe->func = func;
2732 pe->opaque = opaque;
2733 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2734 *ppe = pe;
2735 return 0;
2738 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2740 PollingEntry **ppe, *pe;
2741 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2742 pe = *ppe;
2743 if (pe->func == func && pe->opaque == opaque) {
2744 *ppe = pe->next;
2745 qemu_free(pe);
2746 break;
2751 /***********************************************************/
2752 /* Wait objects support */
2753 typedef struct WaitObjects {
2754 int num;
2755 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2756 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2757 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2758 } WaitObjects;
2760 static WaitObjects wait_objects = {0};
2762 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2764 WaitObjects *w = &wait_objects;
2766 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2767 return -1;
2768 w->events[w->num] = handle;
2769 w->func[w->num] = func;
2770 w->opaque[w->num] = opaque;
2771 w->num++;
2772 return 0;
2775 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2777 int i, found;
2778 WaitObjects *w = &wait_objects;
2780 found = 0;
2781 for (i = 0; i < w->num; i++) {
2782 if (w->events[i] == handle)
2783 found = 1;
2784 if (found) {
2785 w->events[i] = w->events[i + 1];
2786 w->func[i] = w->func[i + 1];
2787 w->opaque[i] = w->opaque[i + 1];
2790 if (found)
2791 w->num--;
2793 #endif
2795 /***********************************************************/
2796 /* ram save/restore */
2798 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2800 int v;
2802 v = qemu_get_byte(f);
2803 switch(v) {
2804 case 0:
2805 if (qemu_get_buffer(f, buf, len) != len)
2806 return -EIO;
2807 break;
2808 case 1:
2809 v = qemu_get_byte(f);
2810 memset(buf, v, len);
2811 break;
2812 default:
2813 return -EINVAL;
2816 if (qemu_file_has_error(f))
2817 return -EIO;
2819 return 0;
2822 static int ram_load_v1(QEMUFile *f, void *opaque)
2824 int ret;
2825 ram_addr_t i;
2827 if (qemu_get_be32(f) != last_ram_offset)
2828 return -EINVAL;
2829 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2830 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2831 if (ret)
2832 return ret;
2834 return 0;
2837 #define BDRV_HASH_BLOCK_SIZE 1024
2838 #define IOBUF_SIZE 4096
2839 #define RAM_CBLOCK_MAGIC 0xfabe
2841 typedef struct RamDecompressState {
2842 z_stream zstream;
2843 QEMUFile *f;
2844 uint8_t buf[IOBUF_SIZE];
2845 } RamDecompressState;
2847 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2849 int ret;
2850 memset(s, 0, sizeof(*s));
2851 s->f = f;
2852 ret = inflateInit(&s->zstream);
2853 if (ret != Z_OK)
2854 return -1;
2855 return 0;
2858 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2860 int ret, clen;
2862 s->zstream.avail_out = len;
2863 s->zstream.next_out = buf;
2864 while (s->zstream.avail_out > 0) {
2865 if (s->zstream.avail_in == 0) {
2866 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
2867 return -1;
2868 clen = qemu_get_be16(s->f);
2869 if (clen > IOBUF_SIZE)
2870 return -1;
2871 qemu_get_buffer(s->f, s->buf, clen);
2872 s->zstream.avail_in = clen;
2873 s->zstream.next_in = s->buf;
2875 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
2876 if (ret != Z_OK && ret != Z_STREAM_END) {
2877 return -1;
2880 return 0;
2883 static void ram_decompress_close(RamDecompressState *s)
2885 inflateEnd(&s->zstream);
2888 #define RAM_SAVE_FLAG_FULL 0x01
2889 #define RAM_SAVE_FLAG_COMPRESS 0x02
2890 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2891 #define RAM_SAVE_FLAG_PAGE 0x08
2892 #define RAM_SAVE_FLAG_EOS 0x10
2894 static int is_dup_page(uint8_t *page, uint8_t ch)
2896 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2897 uint32_t *array = (uint32_t *)page;
2898 int i;
2900 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2901 if (array[i] != val)
2902 return 0;
2905 return 1;
2908 static int ram_save_block(QEMUFile *f)
2910 static ram_addr_t current_addr = 0;
2911 ram_addr_t saved_addr = current_addr;
2912 ram_addr_t addr = 0;
2913 int found = 0;
2915 while (addr < last_ram_offset) {
2916 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2917 uint8_t *p;
2919 cpu_physical_memory_reset_dirty(current_addr,
2920 current_addr + TARGET_PAGE_SIZE,
2921 MIGRATION_DIRTY_FLAG);
2923 p = qemu_get_ram_ptr(current_addr);
2925 if (is_dup_page(p, *p)) {
2926 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2927 qemu_put_byte(f, *p);
2928 } else {
2929 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2930 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2933 found = 1;
2934 break;
2936 addr += TARGET_PAGE_SIZE;
2937 current_addr = (saved_addr + addr) % last_ram_offset;
2940 return found;
2943 static uint64_t bytes_transferred = 0;
2945 static ram_addr_t ram_save_remaining(void)
2947 ram_addr_t addr;
2948 ram_addr_t count = 0;
2950 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2951 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2952 count++;
2955 return count;
2958 uint64_t ram_bytes_remaining(void)
2960 return ram_save_remaining() * TARGET_PAGE_SIZE;
2963 uint64_t ram_bytes_transferred(void)
2965 return bytes_transferred;
2968 uint64_t ram_bytes_total(void)
2970 return last_ram_offset;
2973 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
2975 ram_addr_t addr;
2976 uint64_t bytes_transferred_last;
2977 double bwidth = 0;
2978 uint64_t expected_time = 0;
2980 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2981 qemu_file_set_error(f);
2982 return 0;
2985 if (stage == 1) {
2986 /* Make sure all dirty bits are set */
2987 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2988 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2989 cpu_physical_memory_set_dirty(addr);
2992 /* Enable dirty memory tracking */
2993 cpu_physical_memory_set_dirty_tracking(1);
2995 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2998 bytes_transferred_last = bytes_transferred;
2999 bwidth = get_clock();
3001 while (!qemu_file_rate_limit(f)) {
3002 int ret;
3004 ret = ram_save_block(f);
3005 bytes_transferred += ret * TARGET_PAGE_SIZE;
3006 if (ret == 0) /* no more blocks */
3007 break;
3010 bwidth = get_clock() - bwidth;
3011 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3013 /* if we haven't transferred anything this round, force expected_time to a
3014 * a very high value, but without crashing */
3015 if (bwidth == 0)
3016 bwidth = 0.000001;
3018 /* try transferring iterative blocks of memory */
3020 if (stage == 3) {
3022 /* flush all remaining blocks regardless of rate limiting */
3023 while (ram_save_block(f) != 0) {
3024 bytes_transferred += TARGET_PAGE_SIZE;
3026 cpu_physical_memory_set_dirty_tracking(0);
3029 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3031 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3033 return (stage == 2) && (expected_time <= migrate_max_downtime());
3036 static int ram_load_dead(QEMUFile *f, void *opaque)
3038 RamDecompressState s1, *s = &s1;
3039 uint8_t buf[10];
3040 ram_addr_t i;
3042 if (ram_decompress_open(s, f) < 0)
3043 return -EINVAL;
3044 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3045 if (ram_decompress_buf(s, buf, 1) < 0) {
3046 fprintf(stderr, "Error while reading ram block header\n");
3047 goto error;
3049 if (buf[0] == 0) {
3050 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3051 BDRV_HASH_BLOCK_SIZE) < 0) {
3052 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3053 goto error;
3055 } else {
3056 error:
3057 printf("Error block header\n");
3058 return -EINVAL;
3061 ram_decompress_close(s);
3063 return 0;
3066 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3068 ram_addr_t addr;
3069 int flags;
3071 if (version_id == 1)
3072 return ram_load_v1(f, opaque);
3074 if (version_id == 2) {
3075 if (qemu_get_be32(f) != last_ram_offset)
3076 return -EINVAL;
3077 return ram_load_dead(f, opaque);
3080 if (version_id != 3)
3081 return -EINVAL;
3083 do {
3084 addr = qemu_get_be64(f);
3086 flags = addr & ~TARGET_PAGE_MASK;
3087 addr &= TARGET_PAGE_MASK;
3089 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3090 if (addr != last_ram_offset)
3091 return -EINVAL;
3094 if (flags & RAM_SAVE_FLAG_FULL) {
3095 if (ram_load_dead(f, opaque) < 0)
3096 return -EINVAL;
3099 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3100 uint8_t ch = qemu_get_byte(f);
3101 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3102 #ifndef _WIN32
3103 if (ch == 0 &&
3104 (!kvm_enabled() || kvm_has_sync_mmu())) {
3105 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3107 #endif
3108 } else if (flags & RAM_SAVE_FLAG_PAGE)
3109 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3110 } while (!(flags & RAM_SAVE_FLAG_EOS));
3112 return 0;
3115 void qemu_service_io(void)
3117 qemu_notify_event();
3120 /***********************************************************/
3121 /* bottom halves (can be seen as timers which expire ASAP) */
3123 struct QEMUBH {
3124 QEMUBHFunc *cb;
3125 void *opaque;
3126 int scheduled;
3127 int idle;
3128 int deleted;
3129 QEMUBH *next;
3132 static QEMUBH *first_bh = NULL;
3134 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3136 QEMUBH *bh;
3137 bh = qemu_mallocz(sizeof(QEMUBH));
3138 bh->cb = cb;
3139 bh->opaque = opaque;
3140 bh->next = first_bh;
3141 first_bh = bh;
3142 return bh;
3145 int qemu_bh_poll(void)
3147 QEMUBH *bh, **bhp;
3148 int ret;
3150 ret = 0;
3151 for (bh = first_bh; bh; bh = bh->next) {
3152 if (!bh->deleted && bh->scheduled) {
3153 bh->scheduled = 0;
3154 if (!bh->idle)
3155 ret = 1;
3156 bh->idle = 0;
3157 bh->cb(bh->opaque);
3161 /* remove deleted bhs */
3162 bhp = &first_bh;
3163 while (*bhp) {
3164 bh = *bhp;
3165 if (bh->deleted) {
3166 *bhp = bh->next;
3167 qemu_free(bh);
3168 } else
3169 bhp = &bh->next;
3172 return ret;
3175 void qemu_bh_schedule_idle(QEMUBH *bh)
3177 if (bh->scheduled)
3178 return;
3179 bh->scheduled = 1;
3180 bh->idle = 1;
3183 void qemu_bh_schedule(QEMUBH *bh)
3185 if (bh->scheduled)
3186 return;
3187 bh->scheduled = 1;
3188 bh->idle = 0;
3189 /* stop the currently executing CPU to execute the BH ASAP */
3190 qemu_notify_event();
3193 void qemu_bh_cancel(QEMUBH *bh)
3195 bh->scheduled = 0;
3198 void qemu_bh_delete(QEMUBH *bh)
3200 bh->scheduled = 0;
3201 bh->deleted = 1;
3204 static void qemu_bh_update_timeout(int *timeout)
3206 QEMUBH *bh;
3208 for (bh = first_bh; bh; bh = bh->next) {
3209 if (!bh->deleted && bh->scheduled) {
3210 if (bh->idle) {
3211 /* idle bottom halves will be polled at least
3212 * every 10ms */
3213 *timeout = MIN(10, *timeout);
3214 } else {
3215 /* non-idle bottom halves will be executed
3216 * immediately */
3217 *timeout = 0;
3218 break;
3224 /***********************************************************/
3225 /* machine registration */
3227 static QEMUMachine *first_machine = NULL;
3228 QEMUMachine *current_machine = NULL;
3230 int qemu_register_machine(QEMUMachine *m)
3232 QEMUMachine **pm;
3233 pm = &first_machine;
3234 while (*pm != NULL)
3235 pm = &(*pm)->next;
3236 m->next = NULL;
3237 *pm = m;
3238 return 0;
3241 static QEMUMachine *find_machine(const char *name)
3243 QEMUMachine *m;
3245 for(m = first_machine; m != NULL; m = m->next) {
3246 if (!strcmp(m->name, name))
3247 return m;
3248 if (m->alias && !strcmp(m->alias, name))
3249 return m;
3251 return NULL;
3254 static QEMUMachine *find_default_machine(void)
3256 QEMUMachine *m;
3258 for(m = first_machine; m != NULL; m = m->next) {
3259 if (m->is_default) {
3260 return m;
3263 return NULL;
3266 /***********************************************************/
3267 /* main execution loop */
3269 static void gui_update(void *opaque)
3271 uint64_t interval = GUI_REFRESH_INTERVAL;
3272 DisplayState *ds = opaque;
3273 DisplayChangeListener *dcl = ds->listeners;
3275 dpy_refresh(ds);
3277 while (dcl != NULL) {
3278 if (dcl->gui_timer_interval &&
3279 dcl->gui_timer_interval < interval)
3280 interval = dcl->gui_timer_interval;
3281 dcl = dcl->next;
3283 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3286 static void nographic_update(void *opaque)
3288 uint64_t interval = GUI_REFRESH_INTERVAL;
3290 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3293 struct vm_change_state_entry {
3294 VMChangeStateHandler *cb;
3295 void *opaque;
3296 LIST_ENTRY (vm_change_state_entry) entries;
3299 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3301 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3302 void *opaque)
3304 VMChangeStateEntry *e;
3306 e = qemu_mallocz(sizeof (*e));
3308 e->cb = cb;
3309 e->opaque = opaque;
3310 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3311 return e;
3314 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3316 LIST_REMOVE (e, entries);
3317 qemu_free (e);
3320 static void vm_state_notify(int running, int reason)
3322 VMChangeStateEntry *e;
3324 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3325 e->cb(e->opaque, running, reason);
3329 static void resume_all_vcpus(void);
3330 static void pause_all_vcpus(void);
3332 void vm_start(void)
3334 if (!vm_running) {
3335 cpu_enable_ticks();
3336 vm_running = 1;
3337 vm_state_notify(1, 0);
3338 qemu_rearm_alarm_timer(alarm_timer);
3339 resume_all_vcpus();
3343 /* reset/shutdown handler */
3345 typedef struct QEMUResetEntry {
3346 TAILQ_ENTRY(QEMUResetEntry) entry;
3347 QEMUResetHandler *func;
3348 void *opaque;
3349 } QEMUResetEntry;
3351 static TAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3352 TAILQ_HEAD_INITIALIZER(reset_handlers);
3353 static int reset_requested;
3354 static int shutdown_requested;
3355 static int powerdown_requested;
3356 static int debug_requested;
3357 static int vmstop_requested;
3359 int qemu_shutdown_requested(void)
3361 int r = shutdown_requested;
3362 shutdown_requested = 0;
3363 return r;
3366 int qemu_reset_requested(void)
3368 int r = reset_requested;
3369 reset_requested = 0;
3370 return r;
3373 int qemu_powerdown_requested(void)
3375 int r = powerdown_requested;
3376 powerdown_requested = 0;
3377 return r;
3380 static int qemu_debug_requested(void)
3382 int r = debug_requested;
3383 debug_requested = 0;
3384 return r;
3387 static int qemu_vmstop_requested(void)
3389 int r = vmstop_requested;
3390 vmstop_requested = 0;
3391 return r;
3394 static void do_vm_stop(int reason)
3396 if (vm_running) {
3397 cpu_disable_ticks();
3398 vm_running = 0;
3399 pause_all_vcpus();
3400 vm_state_notify(0, reason);
3404 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3406 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3408 re->func = func;
3409 re->opaque = opaque;
3410 TAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3413 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3415 QEMUResetEntry *re;
3417 TAILQ_FOREACH(re, &reset_handlers, entry) {
3418 if (re->func == func && re->opaque == opaque) {
3419 TAILQ_REMOVE(&reset_handlers, re, entry);
3420 qemu_free(re);
3421 return;
3426 void qemu_system_reset(void)
3428 QEMUResetEntry *re, *nre;
3430 /* reset all devices */
3431 TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3432 re->func(re->opaque);
3436 void qemu_system_reset_request(void)
3438 if (no_reboot) {
3439 shutdown_requested = 1;
3440 } else {
3441 reset_requested = 1;
3443 qemu_notify_event();
3446 void qemu_system_shutdown_request(void)
3448 shutdown_requested = 1;
3449 qemu_notify_event();
3452 void qemu_system_powerdown_request(void)
3454 powerdown_requested = 1;
3455 qemu_notify_event();
3458 #ifdef CONFIG_IOTHREAD
3459 static void qemu_system_vmstop_request(int reason)
3461 vmstop_requested = reason;
3462 qemu_notify_event();
3464 #endif
3466 #ifndef _WIN32
3467 static int io_thread_fd = -1;
3469 static void qemu_event_increment(void)
3471 static const char byte = 0;
3473 if (io_thread_fd == -1)
3474 return;
3476 write(io_thread_fd, &byte, sizeof(byte));
3479 static void qemu_event_read(void *opaque)
3481 int fd = (unsigned long)opaque;
3482 ssize_t len;
3484 /* Drain the notify pipe */
3485 do {
3486 char buffer[512];
3487 len = read(fd, buffer, sizeof(buffer));
3488 } while ((len == -1 && errno == EINTR) || len > 0);
3491 static int qemu_event_init(void)
3493 int err;
3494 int fds[2];
3496 err = pipe(fds);
3497 if (err == -1)
3498 return -errno;
3500 err = fcntl_setfl(fds[0], O_NONBLOCK);
3501 if (err < 0)
3502 goto fail;
3504 err = fcntl_setfl(fds[1], O_NONBLOCK);
3505 if (err < 0)
3506 goto fail;
3508 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3509 (void *)(unsigned long)fds[0]);
3511 io_thread_fd = fds[1];
3512 return 0;
3514 fail:
3515 close(fds[0]);
3516 close(fds[1]);
3517 return err;
3519 #else
3520 HANDLE qemu_event_handle;
3522 static void dummy_event_handler(void *opaque)
3526 static int qemu_event_init(void)
3528 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3529 if (!qemu_event_handle) {
3530 perror("Failed CreateEvent");
3531 return -1;
3533 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3534 return 0;
3537 static void qemu_event_increment(void)
3539 SetEvent(qemu_event_handle);
3541 #endif
3543 static int cpu_can_run(CPUState *env)
3545 if (env->stop)
3546 return 0;
3547 if (env->stopped)
3548 return 0;
3549 return 1;
3552 #ifndef CONFIG_IOTHREAD
3553 static int qemu_init_main_loop(void)
3555 return qemu_event_init();
3558 void qemu_init_vcpu(void *_env)
3560 CPUState *env = _env;
3562 if (kvm_enabled())
3563 kvm_init_vcpu(env);
3564 return;
3567 int qemu_cpu_self(void *env)
3569 return 1;
3572 static void resume_all_vcpus(void)
3576 static void pause_all_vcpus(void)
3580 void qemu_cpu_kick(void *env)
3582 return;
3585 void qemu_notify_event(void)
3587 CPUState *env = cpu_single_env;
3589 if (env) {
3590 cpu_exit(env);
3591 #ifdef USE_KQEMU
3592 if (env->kqemu_enabled)
3593 kqemu_cpu_interrupt(env);
3594 #endif
3598 #define qemu_mutex_lock_iothread() do { } while (0)
3599 #define qemu_mutex_unlock_iothread() do { } while (0)
3601 void vm_stop(int reason)
3603 do_vm_stop(reason);
3606 #else /* CONFIG_IOTHREAD */
3608 #include "qemu-thread.h"
3610 QemuMutex qemu_global_mutex;
3611 static QemuMutex qemu_fair_mutex;
3613 static QemuThread io_thread;
3615 static QemuThread *tcg_cpu_thread;
3616 static QemuCond *tcg_halt_cond;
3618 static int qemu_system_ready;
3619 /* cpu creation */
3620 static QemuCond qemu_cpu_cond;
3621 /* system init */
3622 static QemuCond qemu_system_cond;
3623 static QemuCond qemu_pause_cond;
3625 static void block_io_signals(void);
3626 static void unblock_io_signals(void);
3627 static int tcg_has_work(void);
3629 static int qemu_init_main_loop(void)
3631 int ret;
3633 ret = qemu_event_init();
3634 if (ret)
3635 return ret;
3637 qemu_cond_init(&qemu_pause_cond);
3638 qemu_mutex_init(&qemu_fair_mutex);
3639 qemu_mutex_init(&qemu_global_mutex);
3640 qemu_mutex_lock(&qemu_global_mutex);
3642 unblock_io_signals();
3643 qemu_thread_self(&io_thread);
3645 return 0;
3648 static void qemu_wait_io_event(CPUState *env)
3650 while (!tcg_has_work())
3651 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3653 qemu_mutex_unlock(&qemu_global_mutex);
3656 * Users of qemu_global_mutex can be starved, having no chance
3657 * to acquire it since this path will get to it first.
3658 * So use another lock to provide fairness.
3660 qemu_mutex_lock(&qemu_fair_mutex);
3661 qemu_mutex_unlock(&qemu_fair_mutex);
3663 qemu_mutex_lock(&qemu_global_mutex);
3664 if (env->stop) {
3665 env->stop = 0;
3666 env->stopped = 1;
3667 qemu_cond_signal(&qemu_pause_cond);
3671 static int qemu_cpu_exec(CPUState *env);
3673 static void *kvm_cpu_thread_fn(void *arg)
3675 CPUState *env = arg;
3677 block_io_signals();
3678 qemu_thread_self(env->thread);
3680 /* signal CPU creation */
3681 qemu_mutex_lock(&qemu_global_mutex);
3682 env->created = 1;
3683 qemu_cond_signal(&qemu_cpu_cond);
3685 /* and wait for machine initialization */
3686 while (!qemu_system_ready)
3687 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3689 while (1) {
3690 if (cpu_can_run(env))
3691 qemu_cpu_exec(env);
3692 qemu_wait_io_event(env);
3695 return NULL;
3698 static void tcg_cpu_exec(void);
3700 static void *tcg_cpu_thread_fn(void *arg)
3702 CPUState *env = arg;
3704 block_io_signals();
3705 qemu_thread_self(env->thread);
3707 /* signal CPU creation */
3708 qemu_mutex_lock(&qemu_global_mutex);
3709 for (env = first_cpu; env != NULL; env = env->next_cpu)
3710 env->created = 1;
3711 qemu_cond_signal(&qemu_cpu_cond);
3713 /* and wait for machine initialization */
3714 while (!qemu_system_ready)
3715 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3717 while (1) {
3718 tcg_cpu_exec();
3719 qemu_wait_io_event(cur_cpu);
3722 return NULL;
3725 void qemu_cpu_kick(void *_env)
3727 CPUState *env = _env;
3728 qemu_cond_broadcast(env->halt_cond);
3729 if (kvm_enabled())
3730 qemu_thread_signal(env->thread, SIGUSR1);
3733 int qemu_cpu_self(void *env)
3735 return (cpu_single_env != NULL);
3738 static void cpu_signal(int sig)
3740 if (cpu_single_env)
3741 cpu_exit(cpu_single_env);
3744 static void block_io_signals(void)
3746 sigset_t set;
3747 struct sigaction sigact;
3749 sigemptyset(&set);
3750 sigaddset(&set, SIGUSR2);
3751 sigaddset(&set, SIGIO);
3752 sigaddset(&set, SIGALRM);
3753 pthread_sigmask(SIG_BLOCK, &set, NULL);
3755 sigemptyset(&set);
3756 sigaddset(&set, SIGUSR1);
3757 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3759 memset(&sigact, 0, sizeof(sigact));
3760 sigact.sa_handler = cpu_signal;
3761 sigaction(SIGUSR1, &sigact, NULL);
3764 static void unblock_io_signals(void)
3766 sigset_t set;
3768 sigemptyset(&set);
3769 sigaddset(&set, SIGUSR2);
3770 sigaddset(&set, SIGIO);
3771 sigaddset(&set, SIGALRM);
3772 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3774 sigemptyset(&set);
3775 sigaddset(&set, SIGUSR1);
3776 pthread_sigmask(SIG_BLOCK, &set, NULL);
3779 static void qemu_signal_lock(unsigned int msecs)
3781 qemu_mutex_lock(&qemu_fair_mutex);
3783 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3784 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3785 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3786 break;
3788 qemu_mutex_unlock(&qemu_fair_mutex);
3791 static void qemu_mutex_lock_iothread(void)
3793 if (kvm_enabled()) {
3794 qemu_mutex_lock(&qemu_fair_mutex);
3795 qemu_mutex_lock(&qemu_global_mutex);
3796 qemu_mutex_unlock(&qemu_fair_mutex);
3797 } else
3798 qemu_signal_lock(100);
3801 static void qemu_mutex_unlock_iothread(void)
3803 qemu_mutex_unlock(&qemu_global_mutex);
3806 static int all_vcpus_paused(void)
3808 CPUState *penv = first_cpu;
3810 while (penv) {
3811 if (!penv->stopped)
3812 return 0;
3813 penv = (CPUState *)penv->next_cpu;
3816 return 1;
3819 static void pause_all_vcpus(void)
3821 CPUState *penv = first_cpu;
3823 while (penv) {
3824 penv->stop = 1;
3825 qemu_thread_signal(penv->thread, SIGUSR1);
3826 qemu_cpu_kick(penv);
3827 penv = (CPUState *)penv->next_cpu;
3830 while (!all_vcpus_paused()) {
3831 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3832 penv = first_cpu;
3833 while (penv) {
3834 qemu_thread_signal(penv->thread, SIGUSR1);
3835 penv = (CPUState *)penv->next_cpu;
3840 static void resume_all_vcpus(void)
3842 CPUState *penv = first_cpu;
3844 while (penv) {
3845 penv->stop = 0;
3846 penv->stopped = 0;
3847 qemu_thread_signal(penv->thread, SIGUSR1);
3848 qemu_cpu_kick(penv);
3849 penv = (CPUState *)penv->next_cpu;
3853 static void tcg_init_vcpu(void *_env)
3855 CPUState *env = _env;
3856 /* share a single thread for all cpus with TCG */
3857 if (!tcg_cpu_thread) {
3858 env->thread = qemu_mallocz(sizeof(QemuThread));
3859 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3860 qemu_cond_init(env->halt_cond);
3861 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3862 while (env->created == 0)
3863 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3864 tcg_cpu_thread = env->thread;
3865 tcg_halt_cond = env->halt_cond;
3866 } else {
3867 env->thread = tcg_cpu_thread;
3868 env->halt_cond = tcg_halt_cond;
3872 static void kvm_start_vcpu(CPUState *env)
3874 kvm_init_vcpu(env);
3875 env->thread = qemu_mallocz(sizeof(QemuThread));
3876 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3877 qemu_cond_init(env->halt_cond);
3878 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3879 while (env->created == 0)
3880 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3883 void qemu_init_vcpu(void *_env)
3885 CPUState *env = _env;
3887 if (kvm_enabled())
3888 kvm_start_vcpu(env);
3889 else
3890 tcg_init_vcpu(env);
3893 void qemu_notify_event(void)
3895 qemu_event_increment();
3898 void vm_stop(int reason)
3900 QemuThread me;
3901 qemu_thread_self(&me);
3903 if (!qemu_thread_equal(&me, &io_thread)) {
3904 qemu_system_vmstop_request(reason);
3906 * FIXME: should not return to device code in case
3907 * vm_stop() has been requested.
3909 if (cpu_single_env) {
3910 cpu_exit(cpu_single_env);
3911 cpu_single_env->stop = 1;
3913 return;
3915 do_vm_stop(reason);
3918 #endif
3921 #ifdef _WIN32
3922 static void host_main_loop_wait(int *timeout)
3924 int ret, ret2, i;
3925 PollingEntry *pe;
3928 /* XXX: need to suppress polling by better using win32 events */
3929 ret = 0;
3930 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3931 ret |= pe->func(pe->opaque);
3933 if (ret == 0) {
3934 int err;
3935 WaitObjects *w = &wait_objects;
3937 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3938 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3939 if (w->func[ret - WAIT_OBJECT_0])
3940 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3942 /* Check for additional signaled events */
3943 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3945 /* Check if event is signaled */
3946 ret2 = WaitForSingleObject(w->events[i], 0);
3947 if(ret2 == WAIT_OBJECT_0) {
3948 if (w->func[i])
3949 w->func[i](w->opaque[i]);
3950 } else if (ret2 == WAIT_TIMEOUT) {
3951 } else {
3952 err = GetLastError();
3953 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3956 } else if (ret == WAIT_TIMEOUT) {
3957 } else {
3958 err = GetLastError();
3959 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3963 *timeout = 0;
3965 #else
3966 static void host_main_loop_wait(int *timeout)
3969 #endif
3971 void main_loop_wait(int timeout)
3973 IOHandlerRecord *ioh;
3974 fd_set rfds, wfds, xfds;
3975 int ret, nfds;
3976 struct timeval tv;
3978 qemu_bh_update_timeout(&timeout);
3980 host_main_loop_wait(&timeout);
3982 /* poll any events */
3983 /* XXX: separate device handlers from system ones */
3984 nfds = -1;
3985 FD_ZERO(&rfds);
3986 FD_ZERO(&wfds);
3987 FD_ZERO(&xfds);
3988 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3989 if (ioh->deleted)
3990 continue;
3991 if (ioh->fd_read &&
3992 (!ioh->fd_read_poll ||
3993 ioh->fd_read_poll(ioh->opaque) != 0)) {
3994 FD_SET(ioh->fd, &rfds);
3995 if (ioh->fd > nfds)
3996 nfds = ioh->fd;
3998 if (ioh->fd_write) {
3999 FD_SET(ioh->fd, &wfds);
4000 if (ioh->fd > nfds)
4001 nfds = ioh->fd;
4005 tv.tv_sec = timeout / 1000;
4006 tv.tv_usec = (timeout % 1000) * 1000;
4008 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4010 qemu_mutex_unlock_iothread();
4011 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4012 qemu_mutex_lock_iothread();
4013 if (ret > 0) {
4014 IOHandlerRecord **pioh;
4016 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4017 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4018 ioh->fd_read(ioh->opaque);
4020 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4021 ioh->fd_write(ioh->opaque);
4025 /* remove deleted IO handlers */
4026 pioh = &first_io_handler;
4027 while (*pioh) {
4028 ioh = *pioh;
4029 if (ioh->deleted) {
4030 *pioh = ioh->next;
4031 qemu_free(ioh);
4032 } else
4033 pioh = &ioh->next;
4037 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4039 /* rearm timer, if not periodic */
4040 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4041 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4042 qemu_rearm_alarm_timer(alarm_timer);
4045 /* vm time timers */
4046 if (vm_running) {
4047 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4048 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4049 qemu_get_clock(vm_clock));
4052 /* real time timers */
4053 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4054 qemu_get_clock(rt_clock));
4056 /* Check bottom-halves last in case any of the earlier events triggered
4057 them. */
4058 qemu_bh_poll();
4062 static int qemu_cpu_exec(CPUState *env)
4064 int ret;
4065 #ifdef CONFIG_PROFILER
4066 int64_t ti;
4067 #endif
4069 #ifdef CONFIG_PROFILER
4070 ti = profile_getclock();
4071 #endif
4072 if (use_icount) {
4073 int64_t count;
4074 int decr;
4075 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4076 env->icount_decr.u16.low = 0;
4077 env->icount_extra = 0;
4078 count = qemu_next_deadline();
4079 count = (count + (1 << icount_time_shift) - 1)
4080 >> icount_time_shift;
4081 qemu_icount += count;
4082 decr = (count > 0xffff) ? 0xffff : count;
4083 count -= decr;
4084 env->icount_decr.u16.low = decr;
4085 env->icount_extra = count;
4087 ret = cpu_exec(env);
4088 #ifdef CONFIG_PROFILER
4089 qemu_time += profile_getclock() - ti;
4090 #endif
4091 if (use_icount) {
4092 /* Fold pending instructions back into the
4093 instruction counter, and clear the interrupt flag. */
4094 qemu_icount -= (env->icount_decr.u16.low
4095 + env->icount_extra);
4096 env->icount_decr.u32 = 0;
4097 env->icount_extra = 0;
4099 return ret;
4102 static void tcg_cpu_exec(void)
4104 int ret = 0;
4106 if (next_cpu == NULL)
4107 next_cpu = first_cpu;
4108 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4109 CPUState *env = cur_cpu = next_cpu;
4111 if (!vm_running)
4112 break;
4113 if (timer_alarm_pending) {
4114 timer_alarm_pending = 0;
4115 break;
4117 if (cpu_can_run(env))
4118 ret = qemu_cpu_exec(env);
4119 if (ret == EXCP_DEBUG) {
4120 gdb_set_stop_cpu(env);
4121 debug_requested = 1;
4122 break;
4127 static int cpu_has_work(CPUState *env)
4129 if (env->stop)
4130 return 1;
4131 if (env->stopped)
4132 return 0;
4133 if (!env->halted)
4134 return 1;
4135 if (qemu_cpu_has_work(env))
4136 return 1;
4137 return 0;
4140 static int tcg_has_work(void)
4142 CPUState *env;
4144 for (env = first_cpu; env != NULL; env = env->next_cpu)
4145 if (cpu_has_work(env))
4146 return 1;
4147 return 0;
4150 static int qemu_calculate_timeout(void)
4152 #ifndef CONFIG_IOTHREAD
4153 int timeout;
4155 if (!vm_running)
4156 timeout = 5000;
4157 else if (tcg_has_work())
4158 timeout = 0;
4159 else if (!use_icount)
4160 timeout = 5000;
4161 else {
4162 /* XXX: use timeout computed from timers */
4163 int64_t add;
4164 int64_t delta;
4165 /* Advance virtual time to the next event. */
4166 if (use_icount == 1) {
4167 /* When not using an adaptive execution frequency
4168 we tend to get badly out of sync with real time,
4169 so just delay for a reasonable amount of time. */
4170 delta = 0;
4171 } else {
4172 delta = cpu_get_icount() - cpu_get_clock();
4174 if (delta > 0) {
4175 /* If virtual time is ahead of real time then just
4176 wait for IO. */
4177 timeout = (delta / 1000000) + 1;
4178 } else {
4179 /* Wait for either IO to occur or the next
4180 timer event. */
4181 add = qemu_next_deadline();
4182 /* We advance the timer before checking for IO.
4183 Limit the amount we advance so that early IO
4184 activity won't get the guest too far ahead. */
4185 if (add > 10000000)
4186 add = 10000000;
4187 delta += add;
4188 add = (add + (1 << icount_time_shift) - 1)
4189 >> icount_time_shift;
4190 qemu_icount += add;
4191 timeout = delta / 1000000;
4192 if (timeout < 0)
4193 timeout = 0;
4197 return timeout;
4198 #else /* CONFIG_IOTHREAD */
4199 return 1000;
4200 #endif
4203 static int vm_can_run(void)
4205 if (powerdown_requested)
4206 return 0;
4207 if (reset_requested)
4208 return 0;
4209 if (shutdown_requested)
4210 return 0;
4211 if (debug_requested)
4212 return 0;
4213 return 1;
4216 qemu_irq qemu_system_powerdown;
4218 static void main_loop(void)
4220 int r;
4222 #ifdef CONFIG_IOTHREAD
4223 qemu_system_ready = 1;
4224 qemu_cond_broadcast(&qemu_system_cond);
4225 #endif
4227 for (;;) {
4228 do {
4229 #ifdef CONFIG_PROFILER
4230 int64_t ti;
4231 #endif
4232 #ifndef CONFIG_IOTHREAD
4233 tcg_cpu_exec();
4234 #endif
4235 #ifdef CONFIG_PROFILER
4236 ti = profile_getclock();
4237 #endif
4238 main_loop_wait(qemu_calculate_timeout());
4239 #ifdef CONFIG_PROFILER
4240 dev_time += profile_getclock() - ti;
4241 #endif
4242 } while (vm_can_run());
4244 if (qemu_debug_requested())
4245 vm_stop(EXCP_DEBUG);
4246 if (qemu_shutdown_requested()) {
4247 if (no_shutdown) {
4248 vm_stop(0);
4249 no_shutdown = 0;
4250 } else
4251 break;
4253 if (qemu_reset_requested()) {
4254 pause_all_vcpus();
4255 qemu_system_reset();
4256 resume_all_vcpus();
4258 if (qemu_powerdown_requested()) {
4259 qemu_irq_raise(qemu_system_powerdown);
4261 if ((r = qemu_vmstop_requested()))
4262 vm_stop(r);
4264 pause_all_vcpus();
4267 static void version(void)
4269 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4272 static void help(int exitcode)
4274 version();
4275 printf("usage: %s [options] [disk_image]\n"
4276 "\n"
4277 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4278 "\n"
4279 #define DEF(option, opt_arg, opt_enum, opt_help) \
4280 opt_help
4281 #define DEFHEADING(text) stringify(text) "\n"
4282 #include "qemu-options.h"
4283 #undef DEF
4284 #undef DEFHEADING
4285 #undef GEN_DOCS
4286 "\n"
4287 "During emulation, the following keys are useful:\n"
4288 "ctrl-alt-f toggle full screen\n"
4289 "ctrl-alt-n switch to virtual console 'n'\n"
4290 "ctrl-alt toggle mouse and keyboard grab\n"
4291 "\n"
4292 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4294 "qemu",
4295 DEFAULT_RAM_SIZE,
4296 #ifndef _WIN32
4297 DEFAULT_NETWORK_SCRIPT,
4298 DEFAULT_NETWORK_DOWN_SCRIPT,
4299 #endif
4300 DEFAULT_GDBSTUB_PORT,
4301 "/tmp/qemu.log");
4302 exit(exitcode);
4305 #define HAS_ARG 0x0001
4307 enum {
4308 #define DEF(option, opt_arg, opt_enum, opt_help) \
4309 opt_enum,
4310 #define DEFHEADING(text)
4311 #include "qemu-options.h"
4312 #undef DEF
4313 #undef DEFHEADING
4314 #undef GEN_DOCS
4317 typedef struct QEMUOption {
4318 const char *name;
4319 int flags;
4320 int index;
4321 } QEMUOption;
4323 static const QEMUOption qemu_options[] = {
4324 { "h", 0, QEMU_OPTION_h },
4325 #define DEF(option, opt_arg, opt_enum, opt_help) \
4326 { option, opt_arg, opt_enum },
4327 #define DEFHEADING(text)
4328 #include "qemu-options.h"
4329 #undef DEF
4330 #undef DEFHEADING
4331 #undef GEN_DOCS
4332 { NULL },
4335 #ifdef HAS_AUDIO
4336 struct soundhw soundhw[] = {
4337 #ifdef HAS_AUDIO_CHOICE
4338 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4340 "pcspk",
4341 "PC speaker",
4344 { .init_isa = pcspk_audio_init }
4346 #endif
4348 #ifdef CONFIG_SB16
4350 "sb16",
4351 "Creative Sound Blaster 16",
4354 { .init_isa = SB16_init }
4356 #endif
4358 #ifdef CONFIG_CS4231A
4360 "cs4231a",
4361 "CS4231A",
4364 { .init_isa = cs4231a_init }
4366 #endif
4368 #ifdef CONFIG_ADLIB
4370 "adlib",
4371 #ifdef HAS_YMF262
4372 "Yamaha YMF262 (OPL3)",
4373 #else
4374 "Yamaha YM3812 (OPL2)",
4375 #endif
4378 { .init_isa = Adlib_init }
4380 #endif
4382 #ifdef CONFIG_GUS
4384 "gus",
4385 "Gravis Ultrasound GF1",
4388 { .init_isa = GUS_init }
4390 #endif
4392 #ifdef CONFIG_AC97
4394 "ac97",
4395 "Intel 82801AA AC97 Audio",
4398 { .init_pci = ac97_init }
4400 #endif
4402 #ifdef CONFIG_ES1370
4404 "es1370",
4405 "ENSONIQ AudioPCI ES1370",
4408 { .init_pci = es1370_init }
4410 #endif
4412 #endif /* HAS_AUDIO_CHOICE */
4414 { NULL, NULL, 0, 0, { NULL } }
4417 static void select_soundhw (const char *optarg)
4419 struct soundhw *c;
4421 if (*optarg == '?') {
4422 show_valid_cards:
4424 printf ("Valid sound card names (comma separated):\n");
4425 for (c = soundhw; c->name; ++c) {
4426 printf ("%-11s %s\n", c->name, c->descr);
4428 printf ("\n-soundhw all will enable all of the above\n");
4429 exit (*optarg != '?');
4431 else {
4432 size_t l;
4433 const char *p;
4434 char *e;
4435 int bad_card = 0;
4437 if (!strcmp (optarg, "all")) {
4438 for (c = soundhw; c->name; ++c) {
4439 c->enabled = 1;
4441 return;
4444 p = optarg;
4445 while (*p) {
4446 e = strchr (p, ',');
4447 l = !e ? strlen (p) : (size_t) (e - p);
4449 for (c = soundhw; c->name; ++c) {
4450 if (!strncmp (c->name, p, l)) {
4451 c->enabled = 1;
4452 break;
4456 if (!c->name) {
4457 if (l > 80) {
4458 fprintf (stderr,
4459 "Unknown sound card name (too big to show)\n");
4461 else {
4462 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4463 (int) l, p);
4465 bad_card = 1;
4467 p += l + (e != NULL);
4470 if (bad_card)
4471 goto show_valid_cards;
4474 #endif
4476 static void select_vgahw (const char *p)
4478 const char *opts;
4480 cirrus_vga_enabled = 0;
4481 std_vga_enabled = 0;
4482 vmsvga_enabled = 0;
4483 xenfb_enabled = 0;
4484 if (strstart(p, "std", &opts)) {
4485 std_vga_enabled = 1;
4486 } else if (strstart(p, "cirrus", &opts)) {
4487 cirrus_vga_enabled = 1;
4488 } else if (strstart(p, "vmware", &opts)) {
4489 vmsvga_enabled = 1;
4490 } else if (strstart(p, "xenfb", &opts)) {
4491 xenfb_enabled = 1;
4492 } else if (!strstart(p, "none", &opts)) {
4493 invalid_vga:
4494 fprintf(stderr, "Unknown vga type: %s\n", p);
4495 exit(1);
4497 while (*opts) {
4498 const char *nextopt;
4500 if (strstart(opts, ",retrace=", &nextopt)) {
4501 opts = nextopt;
4502 if (strstart(opts, "dumb", &nextopt))
4503 vga_retrace_method = VGA_RETRACE_DUMB;
4504 else if (strstart(opts, "precise", &nextopt))
4505 vga_retrace_method = VGA_RETRACE_PRECISE;
4506 else goto invalid_vga;
4507 } else goto invalid_vga;
4508 opts = nextopt;
4512 #ifdef TARGET_I386
4513 static int balloon_parse(const char *arg)
4515 char buf[128];
4516 const char *p;
4518 if (!strcmp(arg, "none")) {
4519 virtio_balloon = 0;
4520 } else if (!strncmp(arg, "virtio", 6)) {
4521 virtio_balloon = 1;
4522 if (arg[6] == ',') {
4523 p = arg + 7;
4524 if (get_param_value(buf, sizeof(buf), "addr", p)) {
4525 virtio_balloon_devaddr = strdup(buf);
4528 } else {
4529 return -1;
4531 return 0;
4533 #endif
4535 #ifdef _WIN32
4536 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4538 exit(STATUS_CONTROL_C_EXIT);
4539 return TRUE;
4541 #endif
4543 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4545 int ret;
4547 if(strlen(str) != 36)
4548 return -1;
4550 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4551 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4552 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4554 if(ret != 16)
4555 return -1;
4557 #ifdef TARGET_I386
4558 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4559 #endif
4561 return 0;
4564 #define MAX_NET_CLIENTS 32
4566 #ifndef _WIN32
4568 static void termsig_handler(int signal)
4570 qemu_system_shutdown_request();
4573 static void sigchld_handler(int signal)
4575 waitpid(-1, NULL, WNOHANG);
4578 static void sighandler_setup(void)
4580 struct sigaction act;
4582 memset(&act, 0, sizeof(act));
4583 act.sa_handler = termsig_handler;
4584 sigaction(SIGINT, &act, NULL);
4585 sigaction(SIGHUP, &act, NULL);
4586 sigaction(SIGTERM, &act, NULL);
4588 act.sa_handler = sigchld_handler;
4589 act.sa_flags = SA_NOCLDSTOP;
4590 sigaction(SIGCHLD, &act, NULL);
4593 #endif
4595 #ifdef _WIN32
4596 /* Look for support files in the same directory as the executable. */
4597 static char *find_datadir(const char *argv0)
4599 char *p;
4600 char buf[MAX_PATH];
4601 DWORD len;
4603 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4604 if (len == 0) {
4605 return NULL;
4608 buf[len] = 0;
4609 p = buf + len - 1;
4610 while (p != buf && *p != '\\')
4611 p--;
4612 *p = 0;
4613 if (access(buf, R_OK) == 0) {
4614 return qemu_strdup(buf);
4616 return NULL;
4618 #else /* !_WIN32 */
4620 /* Find a likely location for support files using the location of the binary.
4621 For installed binaries this will be "$bindir/../share/qemu". When
4622 running from the build tree this will be "$bindir/../pc-bios". */
4623 #define SHARE_SUFFIX "/share/qemu"
4624 #define BUILD_SUFFIX "/pc-bios"
4625 static char *find_datadir(const char *argv0)
4627 char *dir;
4628 char *p = NULL;
4629 char *res;
4630 #ifdef PATH_MAX
4631 char buf[PATH_MAX];
4632 #endif
4633 size_t max_len;
4635 #if defined(__linux__)
4637 int len;
4638 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4639 if (len > 0) {
4640 buf[len] = 0;
4641 p = buf;
4644 #elif defined(__FreeBSD__)
4646 int len;
4647 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4648 if (len > 0) {
4649 buf[len] = 0;
4650 p = buf;
4653 #endif
4654 /* If we don't have any way of figuring out the actual executable
4655 location then try argv[0]. */
4656 if (!p) {
4657 #ifdef PATH_MAX
4658 p = buf;
4659 #endif
4660 p = realpath(argv0, p);
4661 if (!p) {
4662 return NULL;
4665 dir = dirname(p);
4666 dir = dirname(dir);
4668 max_len = strlen(dir) +
4669 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4670 res = qemu_mallocz(max_len);
4671 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4672 if (access(res, R_OK)) {
4673 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4674 if (access(res, R_OK)) {
4675 qemu_free(res);
4676 res = NULL;
4679 #ifndef PATH_MAX
4680 free(p);
4681 #endif
4682 return res;
4684 #undef SHARE_SUFFIX
4685 #undef BUILD_SUFFIX
4686 #endif
4688 char *qemu_find_file(int type, const char *name)
4690 int len;
4691 const char *subdir;
4692 char *buf;
4694 /* If name contains path separators then try it as a straight path. */
4695 if ((strchr(name, '/') || strchr(name, '\\'))
4696 && access(name, R_OK) == 0) {
4697 return strdup(name);
4699 switch (type) {
4700 case QEMU_FILE_TYPE_BIOS:
4701 subdir = "";
4702 break;
4703 case QEMU_FILE_TYPE_KEYMAP:
4704 subdir = "keymaps/";
4705 break;
4706 default:
4707 abort();
4709 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4710 buf = qemu_mallocz(len);
4711 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4712 if (access(buf, R_OK)) {
4713 qemu_free(buf);
4714 return NULL;
4716 return buf;
4719 static int device_init_func(QemuOpts *opts, void *opaque)
4721 DeviceState *dev;
4723 dev = qdev_device_add(opts);
4724 if (!dev)
4725 return -1;
4726 return 0;
4729 struct device_config {
4730 enum {
4731 DEV_USB, /* -usbdevice */
4732 DEV_BT, /* -bt */
4733 } type;
4734 const char *cmdline;
4735 TAILQ_ENTRY(device_config) next;
4737 TAILQ_HEAD(, device_config) device_configs = TAILQ_HEAD_INITIALIZER(device_configs);
4739 static void add_device_config(int type, const char *cmdline)
4741 struct device_config *conf;
4743 conf = qemu_mallocz(sizeof(*conf));
4744 conf->type = type;
4745 conf->cmdline = cmdline;
4746 TAILQ_INSERT_TAIL(&device_configs, conf, next);
4749 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4751 struct device_config *conf;
4752 int rc;
4754 TAILQ_FOREACH(conf, &device_configs, next) {
4755 if (conf->type != type)
4756 continue;
4757 rc = func(conf->cmdline);
4758 if (0 != rc)
4759 return rc;
4761 return 0;
4764 int main(int argc, char **argv, char **envp)
4766 const char *gdbstub_dev = NULL;
4767 uint32_t boot_devices_bitmap = 0;
4768 int i;
4769 int snapshot, linux_boot, net_boot;
4770 const char *initrd_filename;
4771 const char *kernel_filename, *kernel_cmdline;
4772 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4773 DisplayState *ds;
4774 DisplayChangeListener *dcl;
4775 int cyls, heads, secs, translation;
4776 const char *net_clients[MAX_NET_CLIENTS];
4777 int nb_net_clients;
4778 QemuOpts *hda_opts = NULL, *opts;
4779 int optind;
4780 const char *r, *optarg;
4781 CharDriverState *monitor_hd = NULL;
4782 const char *monitor_device;
4783 const char *serial_devices[MAX_SERIAL_PORTS];
4784 int serial_device_index;
4785 const char *parallel_devices[MAX_PARALLEL_PORTS];
4786 int parallel_device_index;
4787 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4788 int virtio_console_index;
4789 const char *loadvm = NULL;
4790 QEMUMachine *machine;
4791 const char *cpu_model;
4792 #ifndef _WIN32
4793 int fds[2];
4794 #endif
4795 int tb_size;
4796 const char *pid_file = NULL;
4797 const char *incoming = NULL;
4798 #ifndef _WIN32
4799 int fd = 0;
4800 struct passwd *pwd = NULL;
4801 const char *chroot_dir = NULL;
4802 const char *run_as = NULL;
4803 #endif
4804 CPUState *env;
4805 int show_vnc_port = 0;
4807 qemu_cache_utils_init(envp);
4809 LIST_INIT (&vm_change_state_head);
4810 #ifndef _WIN32
4812 struct sigaction act;
4813 sigfillset(&act.sa_mask);
4814 act.sa_flags = 0;
4815 act.sa_handler = SIG_IGN;
4816 sigaction(SIGPIPE, &act, NULL);
4818 #else
4819 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4820 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4821 QEMU to run on a single CPU */
4823 HANDLE h;
4824 DWORD mask, smask;
4825 int i;
4826 h = GetCurrentProcess();
4827 if (GetProcessAffinityMask(h, &mask, &smask)) {
4828 for(i = 0; i < 32; i++) {
4829 if (mask & (1 << i))
4830 break;
4832 if (i != 32) {
4833 mask = 1 << i;
4834 SetProcessAffinityMask(h, mask);
4838 #endif
4840 module_call_init(MODULE_INIT_MACHINE);
4841 machine = find_default_machine();
4842 cpu_model = NULL;
4843 initrd_filename = NULL;
4844 ram_size = 0;
4845 snapshot = 0;
4846 kernel_filename = NULL;
4847 kernel_cmdline = "";
4848 cyls = heads = secs = 0;
4849 translation = BIOS_ATA_TRANSLATION_AUTO;
4850 monitor_device = "vc:80Cx24C";
4852 serial_devices[0] = "vc:80Cx24C";
4853 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4854 serial_devices[i] = NULL;
4855 serial_device_index = 0;
4857 parallel_devices[0] = "vc:80Cx24C";
4858 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4859 parallel_devices[i] = NULL;
4860 parallel_device_index = 0;
4862 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4863 virtio_consoles[i] = NULL;
4864 virtio_console_index = 0;
4866 for (i = 0; i < MAX_NODES; i++) {
4867 node_mem[i] = 0;
4868 node_cpumask[i] = 0;
4871 nb_net_clients = 0;
4872 nb_numa_nodes = 0;
4873 nb_nics = 0;
4875 tb_size = 0;
4876 autostart= 1;
4878 register_watchdogs();
4880 optind = 1;
4881 for(;;) {
4882 if (optind >= argc)
4883 break;
4884 r = argv[optind];
4885 if (r[0] != '-') {
4886 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4887 } else {
4888 const QEMUOption *popt;
4890 optind++;
4891 /* Treat --foo the same as -foo. */
4892 if (r[1] == '-')
4893 r++;
4894 popt = qemu_options;
4895 for(;;) {
4896 if (!popt->name) {
4897 fprintf(stderr, "%s: invalid option -- '%s'\n",
4898 argv[0], r);
4899 exit(1);
4901 if (!strcmp(popt->name, r + 1))
4902 break;
4903 popt++;
4905 if (popt->flags & HAS_ARG) {
4906 if (optind >= argc) {
4907 fprintf(stderr, "%s: option '%s' requires an argument\n",
4908 argv[0], r);
4909 exit(1);
4911 optarg = argv[optind++];
4912 } else {
4913 optarg = NULL;
4916 switch(popt->index) {
4917 case QEMU_OPTION_M:
4918 machine = find_machine(optarg);
4919 if (!machine) {
4920 QEMUMachine *m;
4921 printf("Supported machines are:\n");
4922 for(m = first_machine; m != NULL; m = m->next) {
4923 if (m->alias)
4924 printf("%-10s %s (alias of %s)\n",
4925 m->alias, m->desc, m->name);
4926 printf("%-10s %s%s\n",
4927 m->name, m->desc,
4928 m->is_default ? " (default)" : "");
4930 exit(*optarg != '?');
4932 break;
4933 case QEMU_OPTION_cpu:
4934 /* hw initialization will check this */
4935 if (*optarg == '?') {
4936 /* XXX: implement xxx_cpu_list for targets that still miss it */
4937 #if defined(cpu_list)
4938 cpu_list(stdout, &fprintf);
4939 #endif
4940 exit(0);
4941 } else {
4942 cpu_model = optarg;
4944 break;
4945 case QEMU_OPTION_initrd:
4946 initrd_filename = optarg;
4947 break;
4948 case QEMU_OPTION_hda:
4949 if (cyls == 0)
4950 hda_opts = drive_add(optarg, HD_ALIAS, 0);
4951 else
4952 hda_opts = drive_add(optarg, HD_ALIAS
4953 ",cyls=%d,heads=%d,secs=%d%s",
4954 0, cyls, heads, secs,
4955 translation == BIOS_ATA_TRANSLATION_LBA ?
4956 ",trans=lba" :
4957 translation == BIOS_ATA_TRANSLATION_NONE ?
4958 ",trans=none" : "");
4959 break;
4960 case QEMU_OPTION_hdb:
4961 case QEMU_OPTION_hdc:
4962 case QEMU_OPTION_hdd:
4963 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4964 break;
4965 case QEMU_OPTION_drive:
4966 drive_add(NULL, "%s", optarg);
4967 break;
4968 case QEMU_OPTION_set:
4969 if (qemu_set_option(optarg) != 0)
4970 exit(1);
4971 break;
4972 case QEMU_OPTION_mtdblock:
4973 drive_add(optarg, MTD_ALIAS);
4974 break;
4975 case QEMU_OPTION_sd:
4976 drive_add(optarg, SD_ALIAS);
4977 break;
4978 case QEMU_OPTION_pflash:
4979 drive_add(optarg, PFLASH_ALIAS);
4980 break;
4981 case QEMU_OPTION_snapshot:
4982 snapshot = 1;
4983 break;
4984 case QEMU_OPTION_hdachs:
4986 const char *p;
4987 p = optarg;
4988 cyls = strtol(p, (char **)&p, 0);
4989 if (cyls < 1 || cyls > 16383)
4990 goto chs_fail;
4991 if (*p != ',')
4992 goto chs_fail;
4993 p++;
4994 heads = strtol(p, (char **)&p, 0);
4995 if (heads < 1 || heads > 16)
4996 goto chs_fail;
4997 if (*p != ',')
4998 goto chs_fail;
4999 p++;
5000 secs = strtol(p, (char **)&p, 0);
5001 if (secs < 1 || secs > 63)
5002 goto chs_fail;
5003 if (*p == ',') {
5004 p++;
5005 if (!strcmp(p, "none"))
5006 translation = BIOS_ATA_TRANSLATION_NONE;
5007 else if (!strcmp(p, "lba"))
5008 translation = BIOS_ATA_TRANSLATION_LBA;
5009 else if (!strcmp(p, "auto"))
5010 translation = BIOS_ATA_TRANSLATION_AUTO;
5011 else
5012 goto chs_fail;
5013 } else if (*p != '\0') {
5014 chs_fail:
5015 fprintf(stderr, "qemu: invalid physical CHS format\n");
5016 exit(1);
5018 if (hda_opts != NULL) {
5019 char num[16];
5020 snprintf(num, sizeof(num), "%d", cyls);
5021 qemu_opt_set(hda_opts, "cyls", num);
5022 snprintf(num, sizeof(num), "%d", heads);
5023 qemu_opt_set(hda_opts, "heads", num);
5024 snprintf(num, sizeof(num), "%d", secs);
5025 qemu_opt_set(hda_opts, "secs", num);
5026 if (translation == BIOS_ATA_TRANSLATION_LBA)
5027 qemu_opt_set(hda_opts, "trans", "lba");
5028 if (translation == BIOS_ATA_TRANSLATION_NONE)
5029 qemu_opt_set(hda_opts, "trans", "none");
5032 break;
5033 case QEMU_OPTION_numa:
5034 if (nb_numa_nodes >= MAX_NODES) {
5035 fprintf(stderr, "qemu: too many NUMA nodes\n");
5036 exit(1);
5038 numa_add(optarg);
5039 break;
5040 case QEMU_OPTION_nographic:
5041 display_type = DT_NOGRAPHIC;
5042 break;
5043 #ifdef CONFIG_CURSES
5044 case QEMU_OPTION_curses:
5045 display_type = DT_CURSES;
5046 break;
5047 #endif
5048 case QEMU_OPTION_portrait:
5049 graphic_rotate = 1;
5050 break;
5051 case QEMU_OPTION_kernel:
5052 kernel_filename = optarg;
5053 break;
5054 case QEMU_OPTION_append:
5055 kernel_cmdline = optarg;
5056 break;
5057 case QEMU_OPTION_cdrom:
5058 drive_add(optarg, CDROM_ALIAS);
5059 break;
5060 case QEMU_OPTION_boot:
5062 static const char * const params[] = {
5063 "order", "once", "menu", NULL
5065 char buf[sizeof(boot_devices)];
5066 char *standard_boot_devices;
5067 int legacy = 0;
5069 if (!strchr(optarg, '=')) {
5070 legacy = 1;
5071 pstrcpy(buf, sizeof(buf), optarg);
5072 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5073 fprintf(stderr,
5074 "qemu: unknown boot parameter '%s' in '%s'\n",
5075 buf, optarg);
5076 exit(1);
5079 if (legacy ||
5080 get_param_value(buf, sizeof(buf), "order", optarg)) {
5081 boot_devices_bitmap = parse_bootdevices(buf);
5082 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5084 if (!legacy) {
5085 if (get_param_value(buf, sizeof(buf),
5086 "once", optarg)) {
5087 boot_devices_bitmap |= parse_bootdevices(buf);
5088 standard_boot_devices = qemu_strdup(boot_devices);
5089 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5090 qemu_register_reset(restore_boot_devices,
5091 standard_boot_devices);
5093 if (get_param_value(buf, sizeof(buf),
5094 "menu", optarg)) {
5095 if (!strcmp(buf, "on")) {
5096 boot_menu = 1;
5097 } else if (!strcmp(buf, "off")) {
5098 boot_menu = 0;
5099 } else {
5100 fprintf(stderr,
5101 "qemu: invalid option value '%s'\n",
5102 buf);
5103 exit(1);
5108 break;
5109 case QEMU_OPTION_fda:
5110 case QEMU_OPTION_fdb:
5111 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5112 break;
5113 #ifdef TARGET_I386
5114 case QEMU_OPTION_no_fd_bootchk:
5115 fd_bootchk = 0;
5116 break;
5117 #endif
5118 case QEMU_OPTION_net:
5119 if (nb_net_clients >= MAX_NET_CLIENTS) {
5120 fprintf(stderr, "qemu: too many network clients\n");
5121 exit(1);
5123 net_clients[nb_net_clients] = optarg;
5124 nb_net_clients++;
5125 break;
5126 #ifdef CONFIG_SLIRP
5127 case QEMU_OPTION_tftp:
5128 legacy_tftp_prefix = optarg;
5129 break;
5130 case QEMU_OPTION_bootp:
5131 legacy_bootp_filename = optarg;
5132 break;
5133 #ifndef _WIN32
5134 case QEMU_OPTION_smb:
5135 net_slirp_smb(optarg);
5136 break;
5137 #endif
5138 case QEMU_OPTION_redir:
5139 net_slirp_redir(optarg);
5140 break;
5141 #endif
5142 case QEMU_OPTION_bt:
5143 add_device_config(DEV_BT, optarg);
5144 break;
5145 #ifdef HAS_AUDIO
5146 case QEMU_OPTION_audio_help:
5147 AUD_help ();
5148 exit (0);
5149 break;
5150 case QEMU_OPTION_soundhw:
5151 select_soundhw (optarg);
5152 break;
5153 #endif
5154 case QEMU_OPTION_h:
5155 help(0);
5156 break;
5157 case QEMU_OPTION_version:
5158 version();
5159 exit(0);
5160 break;
5161 case QEMU_OPTION_m: {
5162 uint64_t value;
5163 char *ptr;
5165 value = strtoul(optarg, &ptr, 10);
5166 switch (*ptr) {
5167 case 0: case 'M': case 'm':
5168 value <<= 20;
5169 break;
5170 case 'G': case 'g':
5171 value <<= 30;
5172 break;
5173 default:
5174 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5175 exit(1);
5178 /* On 32-bit hosts, QEMU is limited by virtual address space */
5179 if (value > (2047 << 20)
5180 #ifndef CONFIG_KQEMU
5181 && HOST_LONG_BITS == 32
5182 #endif
5184 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5185 exit(1);
5187 if (value != (uint64_t)(ram_addr_t)value) {
5188 fprintf(stderr, "qemu: ram size too large\n");
5189 exit(1);
5191 ram_size = value;
5192 break;
5194 case QEMU_OPTION_d:
5196 int mask;
5197 const CPULogItem *item;
5199 mask = cpu_str_to_log_mask(optarg);
5200 if (!mask) {
5201 printf("Log items (comma separated):\n");
5202 for(item = cpu_log_items; item->mask != 0; item++) {
5203 printf("%-10s %s\n", item->name, item->help);
5205 exit(1);
5207 cpu_set_log(mask);
5209 break;
5210 case QEMU_OPTION_s:
5211 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5212 break;
5213 case QEMU_OPTION_gdb:
5214 gdbstub_dev = optarg;
5215 break;
5216 case QEMU_OPTION_L:
5217 data_dir = optarg;
5218 break;
5219 case QEMU_OPTION_bios:
5220 bios_name = optarg;
5221 break;
5222 case QEMU_OPTION_singlestep:
5223 singlestep = 1;
5224 break;
5225 case QEMU_OPTION_S:
5226 autostart = 0;
5227 break;
5228 #ifndef _WIN32
5229 case QEMU_OPTION_k:
5230 keyboard_layout = optarg;
5231 break;
5232 #endif
5233 case QEMU_OPTION_localtime:
5234 rtc_utc = 0;
5235 break;
5236 case QEMU_OPTION_vga:
5237 select_vgahw (optarg);
5238 break;
5239 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5240 case QEMU_OPTION_g:
5242 const char *p;
5243 int w, h, depth;
5244 p = optarg;
5245 w = strtol(p, (char **)&p, 10);
5246 if (w <= 0) {
5247 graphic_error:
5248 fprintf(stderr, "qemu: invalid resolution or depth\n");
5249 exit(1);
5251 if (*p != 'x')
5252 goto graphic_error;
5253 p++;
5254 h = strtol(p, (char **)&p, 10);
5255 if (h <= 0)
5256 goto graphic_error;
5257 if (*p == 'x') {
5258 p++;
5259 depth = strtol(p, (char **)&p, 10);
5260 if (depth != 8 && depth != 15 && depth != 16 &&
5261 depth != 24 && depth != 32)
5262 goto graphic_error;
5263 } else if (*p == '\0') {
5264 depth = graphic_depth;
5265 } else {
5266 goto graphic_error;
5269 graphic_width = w;
5270 graphic_height = h;
5271 graphic_depth = depth;
5273 break;
5274 #endif
5275 case QEMU_OPTION_echr:
5277 char *r;
5278 term_escape_char = strtol(optarg, &r, 0);
5279 if (r == optarg)
5280 printf("Bad argument to echr\n");
5281 break;
5283 case QEMU_OPTION_monitor:
5284 monitor_device = optarg;
5285 break;
5286 case QEMU_OPTION_serial:
5287 if (serial_device_index >= MAX_SERIAL_PORTS) {
5288 fprintf(stderr, "qemu: too many serial ports\n");
5289 exit(1);
5291 serial_devices[serial_device_index] = optarg;
5292 serial_device_index++;
5293 break;
5294 case QEMU_OPTION_watchdog:
5295 i = select_watchdog(optarg);
5296 if (i > 0)
5297 exit (i == 1 ? 1 : 0);
5298 break;
5299 case QEMU_OPTION_watchdog_action:
5300 if (select_watchdog_action(optarg) == -1) {
5301 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5302 exit(1);
5304 break;
5305 case QEMU_OPTION_virtiocon:
5306 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5307 fprintf(stderr, "qemu: too many virtio consoles\n");
5308 exit(1);
5310 virtio_consoles[virtio_console_index] = optarg;
5311 virtio_console_index++;
5312 break;
5313 case QEMU_OPTION_parallel:
5314 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5315 fprintf(stderr, "qemu: too many parallel ports\n");
5316 exit(1);
5318 parallel_devices[parallel_device_index] = optarg;
5319 parallel_device_index++;
5320 break;
5321 case QEMU_OPTION_loadvm:
5322 loadvm = optarg;
5323 break;
5324 case QEMU_OPTION_full_screen:
5325 full_screen = 1;
5326 break;
5327 #ifdef CONFIG_SDL
5328 case QEMU_OPTION_no_frame:
5329 no_frame = 1;
5330 break;
5331 case QEMU_OPTION_alt_grab:
5332 alt_grab = 1;
5333 break;
5334 case QEMU_OPTION_no_quit:
5335 no_quit = 1;
5336 break;
5337 case QEMU_OPTION_sdl:
5338 display_type = DT_SDL;
5339 break;
5340 #endif
5341 case QEMU_OPTION_pidfile:
5342 pid_file = optarg;
5343 break;
5344 #ifdef TARGET_I386
5345 case QEMU_OPTION_win2k_hack:
5346 win2k_install_hack = 1;
5347 break;
5348 case QEMU_OPTION_rtc_td_hack:
5349 rtc_td_hack = 1;
5350 break;
5351 case QEMU_OPTION_acpitable:
5352 if(acpi_table_add(optarg) < 0) {
5353 fprintf(stderr, "Wrong acpi table provided\n");
5354 exit(1);
5356 break;
5357 case QEMU_OPTION_smbios:
5358 if(smbios_entry_add(optarg) < 0) {
5359 fprintf(stderr, "Wrong smbios provided\n");
5360 exit(1);
5362 break;
5363 #endif
5364 #ifdef CONFIG_KQEMU
5365 case QEMU_OPTION_enable_kqemu:
5366 kqemu_allowed = 1;
5367 break;
5368 case QEMU_OPTION_kernel_kqemu:
5369 kqemu_allowed = 2;
5370 break;
5371 #endif
5372 #ifdef CONFIG_KVM
5373 case QEMU_OPTION_enable_kvm:
5374 kvm_allowed = 1;
5375 #ifdef CONFIG_KQEMU
5376 kqemu_allowed = 0;
5377 #endif
5378 break;
5379 #endif
5380 case QEMU_OPTION_usb:
5381 usb_enabled = 1;
5382 break;
5383 case QEMU_OPTION_usbdevice:
5384 usb_enabled = 1;
5385 add_device_config(DEV_USB, optarg);
5386 break;
5387 case QEMU_OPTION_device:
5388 opts = qemu_opts_parse(&qemu_device_opts, optarg, "driver");
5389 if (!opts) {
5390 fprintf(stderr, "parse error: %s\n", optarg);
5391 exit(1);
5393 break;
5394 case QEMU_OPTION_smp:
5396 char *p;
5397 char option[128];
5398 smp_cpus = strtol(optarg, &p, 10);
5399 if (smp_cpus < 1) {
5400 fprintf(stderr, "Invalid number of CPUs\n");
5401 exit(1);
5403 if (*p++ != ',')
5404 break;
5405 if (get_param_value(option, 128, "maxcpus", p))
5406 max_cpus = strtol(option, NULL, 0);
5407 if (max_cpus < smp_cpus) {
5408 fprintf(stderr, "maxcpus must be equal to or greater than "
5409 "smp\n");
5410 exit(1);
5412 if (max_cpus > 255) {
5413 fprintf(stderr, "Unsupported number of maxcpus\n");
5414 exit(1);
5416 break;
5418 case QEMU_OPTION_vnc:
5419 display_type = DT_VNC;
5420 vnc_display = optarg;
5421 break;
5422 #ifdef TARGET_I386
5423 case QEMU_OPTION_no_acpi:
5424 acpi_enabled = 0;
5425 break;
5426 case QEMU_OPTION_no_hpet:
5427 no_hpet = 1;
5428 break;
5429 case QEMU_OPTION_balloon:
5430 if (balloon_parse(optarg) < 0) {
5431 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5432 exit(1);
5434 break;
5435 #endif
5436 case QEMU_OPTION_no_reboot:
5437 no_reboot = 1;
5438 break;
5439 case QEMU_OPTION_no_shutdown:
5440 no_shutdown = 1;
5441 break;
5442 case QEMU_OPTION_show_cursor:
5443 cursor_hide = 0;
5444 break;
5445 case QEMU_OPTION_uuid:
5446 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5447 fprintf(stderr, "Fail to parse UUID string."
5448 " Wrong format.\n");
5449 exit(1);
5451 break;
5452 #ifndef _WIN32
5453 case QEMU_OPTION_daemonize:
5454 daemonize = 1;
5455 break;
5456 #endif
5457 case QEMU_OPTION_option_rom:
5458 if (nb_option_roms >= MAX_OPTION_ROMS) {
5459 fprintf(stderr, "Too many option ROMs\n");
5460 exit(1);
5462 option_rom[nb_option_roms] = optarg;
5463 nb_option_roms++;
5464 break;
5465 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5466 case QEMU_OPTION_semihosting:
5467 semihosting_enabled = 1;
5468 break;
5469 #endif
5470 case QEMU_OPTION_name:
5471 qemu_name = qemu_strdup(optarg);
5473 char *p = strchr(qemu_name, ',');
5474 if (p != NULL) {
5475 *p++ = 0;
5476 if (strncmp(p, "process=", 8)) {
5477 fprintf(stderr, "Unknown subargument %s to -name", p);
5478 exit(1);
5480 p += 8;
5481 set_proc_name(p);
5484 break;
5485 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5486 case QEMU_OPTION_prom_env:
5487 if (nb_prom_envs >= MAX_PROM_ENVS) {
5488 fprintf(stderr, "Too many prom variables\n");
5489 exit(1);
5491 prom_envs[nb_prom_envs] = optarg;
5492 nb_prom_envs++;
5493 break;
5494 #endif
5495 #ifdef TARGET_ARM
5496 case QEMU_OPTION_old_param:
5497 old_param = 1;
5498 break;
5499 #endif
5500 case QEMU_OPTION_clock:
5501 configure_alarms(optarg);
5502 break;
5503 case QEMU_OPTION_startdate:
5505 struct tm tm;
5506 time_t rtc_start_date;
5507 if (!strcmp(optarg, "now")) {
5508 rtc_date_offset = -1;
5509 } else {
5510 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5511 &tm.tm_year,
5512 &tm.tm_mon,
5513 &tm.tm_mday,
5514 &tm.tm_hour,
5515 &tm.tm_min,
5516 &tm.tm_sec) == 6) {
5517 /* OK */
5518 } else if (sscanf(optarg, "%d-%d-%d",
5519 &tm.tm_year,
5520 &tm.tm_mon,
5521 &tm.tm_mday) == 3) {
5522 tm.tm_hour = 0;
5523 tm.tm_min = 0;
5524 tm.tm_sec = 0;
5525 } else {
5526 goto date_fail;
5528 tm.tm_year -= 1900;
5529 tm.tm_mon--;
5530 rtc_start_date = mktimegm(&tm);
5531 if (rtc_start_date == -1) {
5532 date_fail:
5533 fprintf(stderr, "Invalid date format. Valid format are:\n"
5534 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5535 exit(1);
5537 rtc_date_offset = time(NULL) - rtc_start_date;
5540 break;
5541 case QEMU_OPTION_tb_size:
5542 tb_size = strtol(optarg, NULL, 0);
5543 if (tb_size < 0)
5544 tb_size = 0;
5545 break;
5546 case QEMU_OPTION_icount:
5547 use_icount = 1;
5548 if (strcmp(optarg, "auto") == 0) {
5549 icount_time_shift = -1;
5550 } else {
5551 icount_time_shift = strtol(optarg, NULL, 0);
5553 break;
5554 case QEMU_OPTION_incoming:
5555 incoming = optarg;
5556 break;
5557 #ifndef _WIN32
5558 case QEMU_OPTION_chroot:
5559 chroot_dir = optarg;
5560 break;
5561 case QEMU_OPTION_runas:
5562 run_as = optarg;
5563 break;
5564 #endif
5565 #ifdef CONFIG_XEN
5566 case QEMU_OPTION_xen_domid:
5567 xen_domid = atoi(optarg);
5568 break;
5569 case QEMU_OPTION_xen_create:
5570 xen_mode = XEN_CREATE;
5571 break;
5572 case QEMU_OPTION_xen_attach:
5573 xen_mode = XEN_ATTACH;
5574 break;
5575 #endif
5580 /* If no data_dir is specified then try to find it relative to the
5581 executable path. */
5582 if (!data_dir) {
5583 data_dir = find_datadir(argv[0]);
5585 /* If all else fails use the install patch specified when building. */
5586 if (!data_dir) {
5587 data_dir = CONFIG_QEMU_SHAREDIR;
5590 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5591 if (kvm_allowed && kqemu_allowed) {
5592 fprintf(stderr,
5593 "You can not enable both KVM and kqemu at the same time\n");
5594 exit(1);
5596 #endif
5599 * Default to max_cpus = smp_cpus, in case the user doesn't
5600 * specify a max_cpus value.
5602 if (!max_cpus)
5603 max_cpus = smp_cpus;
5605 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5606 if (smp_cpus > machine->max_cpus) {
5607 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5608 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5609 machine->max_cpus);
5610 exit(1);
5613 if (display_type == DT_NOGRAPHIC) {
5614 if (serial_device_index == 0)
5615 serial_devices[0] = "stdio";
5616 if (parallel_device_index == 0)
5617 parallel_devices[0] = "null";
5618 if (strncmp(monitor_device, "vc", 2) == 0)
5619 monitor_device = "stdio";
5622 #ifndef _WIN32
5623 if (daemonize) {
5624 pid_t pid;
5626 if (pipe(fds) == -1)
5627 exit(1);
5629 pid = fork();
5630 if (pid > 0) {
5631 uint8_t status;
5632 ssize_t len;
5634 close(fds[1]);
5636 again:
5637 len = read(fds[0], &status, 1);
5638 if (len == -1 && (errno == EINTR))
5639 goto again;
5641 if (len != 1)
5642 exit(1);
5643 else if (status == 1) {
5644 fprintf(stderr, "Could not acquire pidfile\n");
5645 exit(1);
5646 } else
5647 exit(0);
5648 } else if (pid < 0)
5649 exit(1);
5651 setsid();
5653 pid = fork();
5654 if (pid > 0)
5655 exit(0);
5656 else if (pid < 0)
5657 exit(1);
5659 umask(027);
5661 signal(SIGTSTP, SIG_IGN);
5662 signal(SIGTTOU, SIG_IGN);
5663 signal(SIGTTIN, SIG_IGN);
5666 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5667 if (daemonize) {
5668 uint8_t status = 1;
5669 write(fds[1], &status, 1);
5670 } else
5671 fprintf(stderr, "Could not acquire pid file\n");
5672 exit(1);
5674 #endif
5676 #ifdef CONFIG_KQEMU
5677 if (smp_cpus > 1)
5678 kqemu_allowed = 0;
5679 #endif
5680 if (qemu_init_main_loop()) {
5681 fprintf(stderr, "qemu_init_main_loop failed\n");
5682 exit(1);
5684 linux_boot = (kernel_filename != NULL);
5686 if (!linux_boot && *kernel_cmdline != '\0') {
5687 fprintf(stderr, "-append only allowed with -kernel option\n");
5688 exit(1);
5691 if (!linux_boot && initrd_filename != NULL) {
5692 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5693 exit(1);
5696 #ifndef _WIN32
5697 /* Win32 doesn't support line-buffering and requires size >= 2 */
5698 setvbuf(stdout, NULL, _IOLBF, 0);
5699 #endif
5701 init_timers();
5702 if (init_timer_alarm() < 0) {
5703 fprintf(stderr, "could not initialize alarm timer\n");
5704 exit(1);
5706 if (use_icount && icount_time_shift < 0) {
5707 use_icount = 2;
5708 /* 125MIPS seems a reasonable initial guess at the guest speed.
5709 It will be corrected fairly quickly anyway. */
5710 icount_time_shift = 3;
5711 init_icount_adjust();
5714 #ifdef _WIN32
5715 socket_init();
5716 #endif
5718 /* init network clients */
5719 if (nb_net_clients == 0) {
5720 /* if no clients, we use a default config */
5721 net_clients[nb_net_clients++] = "nic";
5722 #ifdef CONFIG_SLIRP
5723 net_clients[nb_net_clients++] = "user";
5724 #endif
5727 for(i = 0;i < nb_net_clients; i++) {
5728 if (net_client_parse(net_clients[i]) < 0)
5729 exit(1);
5732 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5733 net_set_boot_mask(net_boot);
5735 net_client_check();
5737 /* init the bluetooth world */
5738 if (foreach_device_config(DEV_BT, bt_parse))
5739 exit(1);
5741 /* init the memory */
5742 if (ram_size == 0)
5743 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5745 #ifdef CONFIG_KQEMU
5746 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5747 guest ram allocation. It needs to go away. */
5748 if (kqemu_allowed) {
5749 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
5750 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5751 if (!kqemu_phys_ram_base) {
5752 fprintf(stderr, "Could not allocate physical memory\n");
5753 exit(1);
5756 #endif
5758 /* init the dynamic translator */
5759 cpu_exec_init_all(tb_size * 1024 * 1024);
5761 bdrv_init();
5763 /* we always create the cdrom drive, even if no disk is there */
5764 drive_add(NULL, CDROM_ALIAS);
5766 /* we always create at least one floppy */
5767 drive_add(NULL, FD_ALIAS, 0);
5769 /* we always create one sd slot, even if no card is in it */
5770 drive_add(NULL, SD_ALIAS);
5772 /* open the virtual block devices */
5773 if (snapshot)
5774 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5775 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5776 exit(1);
5778 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5779 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5781 #ifndef _WIN32
5782 /* must be after terminal init, SDL library changes signal handlers */
5783 sighandler_setup();
5784 #endif
5786 /* Maintain compatibility with multiple stdio monitors */
5787 if (!strcmp(monitor_device,"stdio")) {
5788 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5789 const char *devname = serial_devices[i];
5790 if (devname && !strcmp(devname,"mon:stdio")) {
5791 monitor_device = NULL;
5792 break;
5793 } else if (devname && !strcmp(devname,"stdio")) {
5794 monitor_device = NULL;
5795 serial_devices[i] = "mon:stdio";
5796 break;
5801 if (nb_numa_nodes > 0) {
5802 int i;
5804 if (nb_numa_nodes > smp_cpus) {
5805 nb_numa_nodes = smp_cpus;
5808 /* If no memory size if given for any node, assume the default case
5809 * and distribute the available memory equally across all nodes
5811 for (i = 0; i < nb_numa_nodes; i++) {
5812 if (node_mem[i] != 0)
5813 break;
5815 if (i == nb_numa_nodes) {
5816 uint64_t usedmem = 0;
5818 /* On Linux, the each node's border has to be 8MB aligned,
5819 * the final node gets the rest.
5821 for (i = 0; i < nb_numa_nodes - 1; i++) {
5822 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5823 usedmem += node_mem[i];
5825 node_mem[i] = ram_size - usedmem;
5828 for (i = 0; i < nb_numa_nodes; i++) {
5829 if (node_cpumask[i] != 0)
5830 break;
5832 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5833 * must cope with this anyway, because there are BIOSes out there in
5834 * real machines which also use this scheme.
5836 if (i == nb_numa_nodes) {
5837 for (i = 0; i < smp_cpus; i++) {
5838 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5843 if (kvm_enabled()) {
5844 int ret;
5846 ret = kvm_init(smp_cpus);
5847 if (ret < 0) {
5848 fprintf(stderr, "failed to initialize KVM\n");
5849 exit(1);
5853 if (monitor_device) {
5854 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5855 if (!monitor_hd) {
5856 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5857 exit(1);
5861 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5862 const char *devname = serial_devices[i];
5863 if (devname && strcmp(devname, "none")) {
5864 char label[32];
5865 snprintf(label, sizeof(label), "serial%d", i);
5866 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5867 if (!serial_hds[i]) {
5868 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5869 devname);
5870 exit(1);
5875 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5876 const char *devname = parallel_devices[i];
5877 if (devname && strcmp(devname, "none")) {
5878 char label[32];
5879 snprintf(label, sizeof(label), "parallel%d", i);
5880 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5881 if (!parallel_hds[i]) {
5882 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5883 devname);
5884 exit(1);
5889 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5890 const char *devname = virtio_consoles[i];
5891 if (devname && strcmp(devname, "none")) {
5892 char label[32];
5893 snprintf(label, sizeof(label), "virtcon%d", i);
5894 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5895 if (!virtcon_hds[i]) {
5896 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5897 devname);
5898 exit(1);
5903 module_call_init(MODULE_INIT_DEVICE);
5905 if (machine->compat_props) {
5906 qdev_prop_register_compat(machine->compat_props);
5908 machine->init(ram_size, boot_devices,
5909 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5912 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5913 for (i = 0; i < nb_numa_nodes; i++) {
5914 if (node_cpumask[i] & (1 << env->cpu_index)) {
5915 env->numa_node = i;
5920 current_machine = machine;
5922 /* init USB devices */
5923 if (usb_enabled) {
5924 foreach_device_config(DEV_USB, usb_parse);
5927 /* init generic devices */
5928 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5929 exit(1);
5931 if (!display_state)
5932 dumb_display_init();
5933 /* just use the first displaystate for the moment */
5934 ds = display_state;
5936 if (display_type == DT_DEFAULT) {
5937 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5938 display_type = DT_SDL;
5939 #else
5940 display_type = DT_VNC;
5941 vnc_display = "localhost:0,to=99";
5942 show_vnc_port = 1;
5943 #endif
5947 switch (display_type) {
5948 case DT_NOGRAPHIC:
5949 break;
5950 #if defined(CONFIG_CURSES)
5951 case DT_CURSES:
5952 curses_display_init(ds, full_screen);
5953 break;
5954 #endif
5955 #if defined(CONFIG_SDL)
5956 case DT_SDL:
5957 sdl_display_init(ds, full_screen, no_frame);
5958 break;
5959 #elif defined(CONFIG_COCOA)
5960 case DT_SDL:
5961 cocoa_display_init(ds, full_screen);
5962 break;
5963 #endif
5964 case DT_VNC:
5965 vnc_display_init(ds);
5966 if (vnc_display_open(ds, vnc_display) < 0)
5967 exit(1);
5969 if (show_vnc_port) {
5970 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5972 break;
5973 default:
5974 break;
5976 dpy_resize(ds);
5978 dcl = ds->listeners;
5979 while (dcl != NULL) {
5980 if (dcl->dpy_refresh != NULL) {
5981 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5982 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5984 dcl = dcl->next;
5987 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5988 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5989 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5992 text_consoles_set_display(display_state);
5993 qemu_chr_initial_reset();
5995 if (monitor_device && monitor_hd)
5996 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
5998 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5999 const char *devname = serial_devices[i];
6000 if (devname && strcmp(devname, "none")) {
6001 if (strstart(devname, "vc", 0))
6002 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6006 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6007 const char *devname = parallel_devices[i];
6008 if (devname && strcmp(devname, "none")) {
6009 if (strstart(devname, "vc", 0))
6010 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6014 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6015 const char *devname = virtio_consoles[i];
6016 if (virtcon_hds[i] && devname) {
6017 if (strstart(devname, "vc", 0))
6018 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6022 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6023 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6024 gdbstub_dev);
6025 exit(1);
6028 if (loadvm)
6029 do_loadvm(cur_mon, loadvm);
6031 if (incoming) {
6032 autostart = 0;
6033 qemu_start_incoming_migration(incoming);
6036 else if (autostart)
6037 vm_start();
6039 #ifndef _WIN32
6040 if (daemonize) {
6041 uint8_t status = 0;
6042 ssize_t len;
6044 again1:
6045 len = write(fds[1], &status, 1);
6046 if (len == -1 && (errno == EINTR))
6047 goto again1;
6049 if (len != 1)
6050 exit(1);
6052 chdir("/");
6053 TFR(fd = open("/dev/null", O_RDWR));
6054 if (fd == -1)
6055 exit(1);
6058 if (run_as) {
6059 pwd = getpwnam(run_as);
6060 if (!pwd) {
6061 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6062 exit(1);
6066 if (chroot_dir) {
6067 if (chroot(chroot_dir) < 0) {
6068 fprintf(stderr, "chroot failed\n");
6069 exit(1);
6071 chdir("/");
6074 if (run_as) {
6075 if (setgid(pwd->pw_gid) < 0) {
6076 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6077 exit(1);
6079 if (setuid(pwd->pw_uid) < 0) {
6080 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6081 exit(1);
6083 if (setuid(0) != -1) {
6084 fprintf(stderr, "Dropping privileges failed\n");
6085 exit(1);
6089 if (daemonize) {
6090 dup2(fd, 0);
6091 dup2(fd, 1);
6092 dup2(fd, 2);
6094 close(fd);
6096 #endif
6098 main_loop();
6099 quit_timers();
6100 net_cleanup();
6102 return 0;