push CPUID level to 4 to allow Intel multicore decoding
[qemu.git] / vl.c
blob3a247aeabb52f47b50e47c135d1540d42c606bae
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
34 /* Needed early to override system queue definitions on BSD */
35 #include "sys-queue.h"
37 #ifndef _WIN32
38 #include <libgen.h>
39 #include <pwd.h>
40 #include <sys/times.h>
41 #include <sys/wait.h>
42 #include <termios.h>
43 #include <sys/mman.h>
44 #include <sys/ioctl.h>
45 #include <sys/resource.h>
46 #include <sys/socket.h>
47 #include <netinet/in.h>
48 #include <net/if.h>
49 #if defined(__NetBSD__)
50 #include <net/if_tap.h>
51 #endif
52 #ifdef __linux__
53 #include <linux/if_tun.h>
54 #endif
55 #include <arpa/inet.h>
56 #include <dirent.h>
57 #include <netdb.h>
58 #include <sys/select.h>
59 #ifdef CONFIG_BSD
60 #include <sys/stat.h>
61 #if defined(__FreeBSD__) || defined(__DragonFly__)
62 #include <libutil.h>
63 #else
64 #include <util.h>
65 #endif
66 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
67 #include <freebsd/stdlib.h>
68 #else
69 #ifdef __linux__
70 #include <pty.h>
71 #include <malloc.h>
72 #include <linux/rtc.h>
73 #include <sys/prctl.h>
75 /* For the benefit of older linux systems which don't supply it,
76 we use a local copy of hpet.h. */
77 /* #include <linux/hpet.h> */
78 #include "hpet.h"
80 #include <linux/ppdev.h>
81 #include <linux/parport.h>
82 #endif
83 #ifdef __sun__
84 #include <sys/stat.h>
85 #include <sys/ethernet.h>
86 #include <sys/sockio.h>
87 #include <netinet/arp.h>
88 #include <netinet/in.h>
89 #include <netinet/in_systm.h>
90 #include <netinet/ip.h>
91 #include <netinet/ip_icmp.h> // must come after ip.h
92 #include <netinet/udp.h>
93 #include <netinet/tcp.h>
94 #include <net/if.h>
95 #include <syslog.h>
96 #include <stropts.h>
97 #endif
98 #endif
99 #endif
101 #if defined(__OpenBSD__)
102 #include <util.h>
103 #endif
105 #if defined(CONFIG_VDE)
106 #include <libvdeplug.h>
107 #endif
109 #ifdef _WIN32
110 #include <windows.h>
111 #include <mmsystem.h>
112 #endif
114 #ifdef CONFIG_SDL
115 #if defined(__APPLE__) || defined(main)
116 #include <SDL.h>
117 int qemu_main(int argc, char **argv, char **envp);
118 int main(int argc, char **argv)
120 return qemu_main(argc, argv, NULL);
122 #undef main
123 #define main qemu_main
124 #endif
125 #endif /* CONFIG_SDL */
127 #ifdef CONFIG_COCOA
128 #undef main
129 #define main qemu_main
130 #endif /* CONFIG_COCOA */
132 #include "hw/hw.h"
133 #include "hw/boards.h"
134 #include "hw/usb.h"
135 #include "hw/pcmcia.h"
136 #include "hw/pc.h"
137 #include "hw/audiodev.h"
138 #include "hw/isa.h"
139 #include "hw/baum.h"
140 #include "hw/bt.h"
141 #include "hw/watchdog.h"
142 #include "hw/smbios.h"
143 #include "hw/xen.h"
144 #include "hw/qdev.h"
145 #include "bt-host.h"
146 #include "net.h"
147 #include "monitor.h"
148 #include "console.h"
149 #include "sysemu.h"
150 #include "gdbstub.h"
151 #include "qemu-timer.h"
152 #include "qemu-char.h"
153 #include "cache-utils.h"
154 #include "block.h"
155 #include "dma.h"
156 #include "audio/audio.h"
157 #include "migration.h"
158 #include "kvm.h"
159 #include "balloon.h"
160 #include "qemu-option.h"
161 #include "qemu-config.h"
163 #include "disas.h"
165 #include "exec-all.h"
167 #include "qemu_socket.h"
169 #include "slirp/libslirp.h"
171 //#define DEBUG_NET
172 //#define DEBUG_SLIRP
174 #define DEFAULT_RAM_SIZE 128
176 static const char *data_dir;
177 const char *bios_name = NULL;
178 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
179 to store the VM snapshots */
180 struct drivelist drives = TAILQ_HEAD_INITIALIZER(drives);
181 struct driveoptlist driveopts = TAILQ_HEAD_INITIALIZER(driveopts);
182 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
183 static DisplayState *display_state;
184 DisplayType display_type = DT_DEFAULT;
185 const char* keyboard_layout = NULL;
186 int64_t ticks_per_sec;
187 ram_addr_t ram_size;
188 int nb_nics;
189 NICInfo nd_table[MAX_NICS];
190 int vm_running;
191 int autostart;
192 static int rtc_utc = 1;
193 static int rtc_date_offset = -1; /* -1 means no change */
194 int vga_interface_type = VGA_CIRRUS;
195 #ifdef TARGET_SPARC
196 int graphic_width = 1024;
197 int graphic_height = 768;
198 int graphic_depth = 8;
199 #else
200 int graphic_width = 800;
201 int graphic_height = 600;
202 int graphic_depth = 15;
203 #endif
204 static int full_screen = 0;
205 #ifdef CONFIG_SDL
206 static int no_frame = 0;
207 #endif
208 int no_quit = 0;
209 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
210 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
211 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
212 #ifdef TARGET_I386
213 int win2k_install_hack = 0;
214 int rtc_td_hack = 0;
215 #endif
216 int usb_enabled = 0;
217 int singlestep = 0;
218 int smp_cpus = 1;
219 int max_cpus = 0;
220 int smp_cores = 1;
221 int smp_threads = 1;
222 const char *vnc_display;
223 int acpi_enabled = 1;
224 int no_hpet = 0;
225 int virtio_balloon = 1;
226 const char *virtio_balloon_devaddr;
227 int fd_bootchk = 1;
228 int no_reboot = 0;
229 int no_shutdown = 0;
230 int cursor_hide = 1;
231 int graphic_rotate = 0;
232 uint8_t irq0override = 1;
233 #ifndef _WIN32
234 int daemonize = 0;
235 #endif
236 WatchdogTimerModel *watchdog = NULL;
237 int watchdog_action = WDT_RESET;
238 const char *option_rom[MAX_OPTION_ROMS];
239 int nb_option_roms;
240 int semihosting_enabled = 0;
241 #ifdef TARGET_ARM
242 int old_param = 0;
243 #endif
244 const char *qemu_name;
245 int alt_grab = 0;
246 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
247 unsigned int nb_prom_envs = 0;
248 const char *prom_envs[MAX_PROM_ENVS];
249 #endif
250 int boot_menu;
252 int nb_numa_nodes;
253 uint64_t node_mem[MAX_NODES];
254 uint64_t node_cpumask[MAX_NODES];
256 static CPUState *cur_cpu;
257 static CPUState *next_cpu;
258 static int timer_alarm_pending = 1;
259 /* Conversion factor from emulated instructions to virtual clock ticks. */
260 static int icount_time_shift;
261 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
262 #define MAX_ICOUNT_SHIFT 10
263 /* Compensate for varying guest execution speed. */
264 static int64_t qemu_icount_bias;
265 static QEMUTimer *icount_rt_timer;
266 static QEMUTimer *icount_vm_timer;
267 static QEMUTimer *nographic_timer;
269 uint8_t qemu_uuid[16];
271 static QEMUBootSetHandler *boot_set_handler;
272 static void *boot_set_opaque;
274 /***********************************************************/
275 /* x86 ISA bus support */
277 target_phys_addr_t isa_mem_base = 0;
278 PicState2 *isa_pic;
280 /***********************************************************/
281 void hw_error(const char *fmt, ...)
283 va_list ap;
284 CPUState *env;
286 va_start(ap, fmt);
287 fprintf(stderr, "qemu: hardware error: ");
288 vfprintf(stderr, fmt, ap);
289 fprintf(stderr, "\n");
290 for(env = first_cpu; env != NULL; env = env->next_cpu) {
291 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
292 #ifdef TARGET_I386
293 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
294 #else
295 cpu_dump_state(env, stderr, fprintf, 0);
296 #endif
298 va_end(ap);
299 abort();
302 static void set_proc_name(const char *s)
304 #if defined(__linux__) && defined(PR_SET_NAME)
305 char name[16];
306 if (!s)
307 return;
308 name[sizeof(name) - 1] = 0;
309 strncpy(name, s, sizeof(name));
310 /* Could rewrite argv[0] too, but that's a bit more complicated.
311 This simple way is enough for `top'. */
312 prctl(PR_SET_NAME, name);
313 #endif
316 /***************/
317 /* ballooning */
319 static QEMUBalloonEvent *qemu_balloon_event;
320 void *qemu_balloon_event_opaque;
322 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
324 qemu_balloon_event = func;
325 qemu_balloon_event_opaque = opaque;
328 void qemu_balloon(ram_addr_t target)
330 if (qemu_balloon_event)
331 qemu_balloon_event(qemu_balloon_event_opaque, target);
334 ram_addr_t qemu_balloon_status(void)
336 if (qemu_balloon_event)
337 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
338 return 0;
341 /***********************************************************/
342 /* keyboard/mouse */
344 static QEMUPutKBDEvent *qemu_put_kbd_event;
345 static void *qemu_put_kbd_event_opaque;
346 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
347 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
349 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
351 qemu_put_kbd_event_opaque = opaque;
352 qemu_put_kbd_event = func;
355 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
356 void *opaque, int absolute,
357 const char *name)
359 QEMUPutMouseEntry *s, *cursor;
361 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
363 s->qemu_put_mouse_event = func;
364 s->qemu_put_mouse_event_opaque = opaque;
365 s->qemu_put_mouse_event_absolute = absolute;
366 s->qemu_put_mouse_event_name = qemu_strdup(name);
367 s->next = NULL;
369 if (!qemu_put_mouse_event_head) {
370 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
371 return s;
374 cursor = qemu_put_mouse_event_head;
375 while (cursor->next != NULL)
376 cursor = cursor->next;
378 cursor->next = s;
379 qemu_put_mouse_event_current = s;
381 return s;
384 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
386 QEMUPutMouseEntry *prev = NULL, *cursor;
388 if (!qemu_put_mouse_event_head || entry == NULL)
389 return;
391 cursor = qemu_put_mouse_event_head;
392 while (cursor != NULL && cursor != entry) {
393 prev = cursor;
394 cursor = cursor->next;
397 if (cursor == NULL) // does not exist or list empty
398 return;
399 else if (prev == NULL) { // entry is head
400 qemu_put_mouse_event_head = cursor->next;
401 if (qemu_put_mouse_event_current == entry)
402 qemu_put_mouse_event_current = cursor->next;
403 qemu_free(entry->qemu_put_mouse_event_name);
404 qemu_free(entry);
405 return;
408 prev->next = entry->next;
410 if (qemu_put_mouse_event_current == entry)
411 qemu_put_mouse_event_current = prev;
413 qemu_free(entry->qemu_put_mouse_event_name);
414 qemu_free(entry);
417 void kbd_put_keycode(int keycode)
419 if (qemu_put_kbd_event) {
420 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
424 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
426 QEMUPutMouseEvent *mouse_event;
427 void *mouse_event_opaque;
428 int width;
430 if (!qemu_put_mouse_event_current) {
431 return;
434 mouse_event =
435 qemu_put_mouse_event_current->qemu_put_mouse_event;
436 mouse_event_opaque =
437 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
439 if (mouse_event) {
440 if (graphic_rotate) {
441 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
442 width = 0x7fff;
443 else
444 width = graphic_width - 1;
445 mouse_event(mouse_event_opaque,
446 width - dy, dx, dz, buttons_state);
447 } else
448 mouse_event(mouse_event_opaque,
449 dx, dy, dz, buttons_state);
453 int kbd_mouse_is_absolute(void)
455 if (!qemu_put_mouse_event_current)
456 return 0;
458 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
461 void do_info_mice(Monitor *mon)
463 QEMUPutMouseEntry *cursor;
464 int index = 0;
466 if (!qemu_put_mouse_event_head) {
467 monitor_printf(mon, "No mouse devices connected\n");
468 return;
471 monitor_printf(mon, "Mouse devices available:\n");
472 cursor = qemu_put_mouse_event_head;
473 while (cursor != NULL) {
474 monitor_printf(mon, "%c Mouse #%d: %s\n",
475 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
476 index, cursor->qemu_put_mouse_event_name);
477 index++;
478 cursor = cursor->next;
482 void do_mouse_set(Monitor *mon, int index)
484 QEMUPutMouseEntry *cursor;
485 int i = 0;
487 if (!qemu_put_mouse_event_head) {
488 monitor_printf(mon, "No mouse devices connected\n");
489 return;
492 cursor = qemu_put_mouse_event_head;
493 while (cursor != NULL && index != i) {
494 i++;
495 cursor = cursor->next;
498 if (cursor != NULL)
499 qemu_put_mouse_event_current = cursor;
500 else
501 monitor_printf(mon, "Mouse at given index not found\n");
504 /* compute with 96 bit intermediate result: (a*b)/c */
505 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
507 union {
508 uint64_t ll;
509 struct {
510 #ifdef HOST_WORDS_BIGENDIAN
511 uint32_t high, low;
512 #else
513 uint32_t low, high;
514 #endif
515 } l;
516 } u, res;
517 uint64_t rl, rh;
519 u.ll = a;
520 rl = (uint64_t)u.l.low * (uint64_t)b;
521 rh = (uint64_t)u.l.high * (uint64_t)b;
522 rh += (rl >> 32);
523 res.l.high = rh / c;
524 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
525 return res.ll;
528 /***********************************************************/
529 /* real time host monotonic timer */
531 #define QEMU_TIMER_BASE 1000000000LL
533 #ifdef WIN32
535 static int64_t clock_freq;
537 static void init_get_clock(void)
539 LARGE_INTEGER freq;
540 int ret;
541 ret = QueryPerformanceFrequency(&freq);
542 if (ret == 0) {
543 fprintf(stderr, "Could not calibrate ticks\n");
544 exit(1);
546 clock_freq = freq.QuadPart;
549 static int64_t get_clock(void)
551 LARGE_INTEGER ti;
552 QueryPerformanceCounter(&ti);
553 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
556 #else
558 static int use_rt_clock;
560 static void init_get_clock(void)
562 use_rt_clock = 0;
563 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
564 || defined(__DragonFly__)
566 struct timespec ts;
567 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
568 use_rt_clock = 1;
571 #endif
574 static int64_t get_clock(void)
576 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
577 || defined(__DragonFly__)
578 if (use_rt_clock) {
579 struct timespec ts;
580 clock_gettime(CLOCK_MONOTONIC, &ts);
581 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
582 } else
583 #endif
585 /* XXX: using gettimeofday leads to problems if the date
586 changes, so it should be avoided. */
587 struct timeval tv;
588 gettimeofday(&tv, NULL);
589 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
592 #endif
594 /* Return the virtual CPU time, based on the instruction counter. */
595 static int64_t cpu_get_icount(void)
597 int64_t icount;
598 CPUState *env = cpu_single_env;;
599 icount = qemu_icount;
600 if (env) {
601 if (!can_do_io(env))
602 fprintf(stderr, "Bad clock read\n");
603 icount -= (env->icount_decr.u16.low + env->icount_extra);
605 return qemu_icount_bias + (icount << icount_time_shift);
608 /***********************************************************/
609 /* guest cycle counter */
611 static int64_t cpu_ticks_prev;
612 static int64_t cpu_ticks_offset;
613 static int64_t cpu_clock_offset;
614 static int cpu_ticks_enabled;
616 /* return the host CPU cycle counter and handle stop/restart */
617 int64_t cpu_get_ticks(void)
619 if (use_icount) {
620 return cpu_get_icount();
622 if (!cpu_ticks_enabled) {
623 return cpu_ticks_offset;
624 } else {
625 int64_t ticks;
626 ticks = cpu_get_real_ticks();
627 if (cpu_ticks_prev > ticks) {
628 /* Note: non increasing ticks may happen if the host uses
629 software suspend */
630 cpu_ticks_offset += cpu_ticks_prev - ticks;
632 cpu_ticks_prev = ticks;
633 return ticks + cpu_ticks_offset;
637 /* return the host CPU monotonic timer and handle stop/restart */
638 static int64_t cpu_get_clock(void)
640 int64_t ti;
641 if (!cpu_ticks_enabled) {
642 return cpu_clock_offset;
643 } else {
644 ti = get_clock();
645 return ti + cpu_clock_offset;
649 /* enable cpu_get_ticks() */
650 void cpu_enable_ticks(void)
652 if (!cpu_ticks_enabled) {
653 cpu_ticks_offset -= cpu_get_real_ticks();
654 cpu_clock_offset -= get_clock();
655 cpu_ticks_enabled = 1;
659 /* disable cpu_get_ticks() : the clock is stopped. You must not call
660 cpu_get_ticks() after that. */
661 void cpu_disable_ticks(void)
663 if (cpu_ticks_enabled) {
664 cpu_ticks_offset = cpu_get_ticks();
665 cpu_clock_offset = cpu_get_clock();
666 cpu_ticks_enabled = 0;
670 /***********************************************************/
671 /* timers */
673 #define QEMU_TIMER_REALTIME 0
674 #define QEMU_TIMER_VIRTUAL 1
676 struct QEMUClock {
677 int type;
678 /* XXX: add frequency */
681 struct QEMUTimer {
682 QEMUClock *clock;
683 int64_t expire_time;
684 QEMUTimerCB *cb;
685 void *opaque;
686 struct QEMUTimer *next;
689 struct qemu_alarm_timer {
690 char const *name;
691 unsigned int flags;
693 int (*start)(struct qemu_alarm_timer *t);
694 void (*stop)(struct qemu_alarm_timer *t);
695 void (*rearm)(struct qemu_alarm_timer *t);
696 void *priv;
699 #define ALARM_FLAG_DYNTICKS 0x1
700 #define ALARM_FLAG_EXPIRED 0x2
702 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
704 return t && (t->flags & ALARM_FLAG_DYNTICKS);
707 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
709 if (!alarm_has_dynticks(t))
710 return;
712 t->rearm(t);
715 /* TODO: MIN_TIMER_REARM_US should be optimized */
716 #define MIN_TIMER_REARM_US 250
718 static struct qemu_alarm_timer *alarm_timer;
720 #ifdef _WIN32
722 struct qemu_alarm_win32 {
723 MMRESULT timerId;
724 unsigned int period;
725 } alarm_win32_data = {0, -1};
727 static int win32_start_timer(struct qemu_alarm_timer *t);
728 static void win32_stop_timer(struct qemu_alarm_timer *t);
729 static void win32_rearm_timer(struct qemu_alarm_timer *t);
731 #else
733 static int unix_start_timer(struct qemu_alarm_timer *t);
734 static void unix_stop_timer(struct qemu_alarm_timer *t);
736 #ifdef __linux__
738 static int dynticks_start_timer(struct qemu_alarm_timer *t);
739 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
740 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
742 static int hpet_start_timer(struct qemu_alarm_timer *t);
743 static void hpet_stop_timer(struct qemu_alarm_timer *t);
745 static int rtc_start_timer(struct qemu_alarm_timer *t);
746 static void rtc_stop_timer(struct qemu_alarm_timer *t);
748 #endif /* __linux__ */
750 #endif /* _WIN32 */
752 /* Correlation between real and virtual time is always going to be
753 fairly approximate, so ignore small variation.
754 When the guest is idle real and virtual time will be aligned in
755 the IO wait loop. */
756 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
758 static void icount_adjust(void)
760 int64_t cur_time;
761 int64_t cur_icount;
762 int64_t delta;
763 static int64_t last_delta;
764 /* If the VM is not running, then do nothing. */
765 if (!vm_running)
766 return;
768 cur_time = cpu_get_clock();
769 cur_icount = qemu_get_clock(vm_clock);
770 delta = cur_icount - cur_time;
771 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
772 if (delta > 0
773 && last_delta + ICOUNT_WOBBLE < delta * 2
774 && icount_time_shift > 0) {
775 /* The guest is getting too far ahead. Slow time down. */
776 icount_time_shift--;
778 if (delta < 0
779 && last_delta - ICOUNT_WOBBLE > delta * 2
780 && icount_time_shift < MAX_ICOUNT_SHIFT) {
781 /* The guest is getting too far behind. Speed time up. */
782 icount_time_shift++;
784 last_delta = delta;
785 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
788 static void icount_adjust_rt(void * opaque)
790 qemu_mod_timer(icount_rt_timer,
791 qemu_get_clock(rt_clock) + 1000);
792 icount_adjust();
795 static void icount_adjust_vm(void * opaque)
797 qemu_mod_timer(icount_vm_timer,
798 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
799 icount_adjust();
802 static void init_icount_adjust(void)
804 /* Have both realtime and virtual time triggers for speed adjustment.
805 The realtime trigger catches emulated time passing too slowly,
806 the virtual time trigger catches emulated time passing too fast.
807 Realtime triggers occur even when idle, so use them less frequently
808 than VM triggers. */
809 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
810 qemu_mod_timer(icount_rt_timer,
811 qemu_get_clock(rt_clock) + 1000);
812 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
813 qemu_mod_timer(icount_vm_timer,
814 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
817 static struct qemu_alarm_timer alarm_timers[] = {
818 #ifndef _WIN32
819 #ifdef __linux__
820 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
821 dynticks_stop_timer, dynticks_rearm_timer, NULL},
822 /* HPET - if available - is preferred */
823 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
824 /* ...otherwise try RTC */
825 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
826 #endif
827 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
828 #else
829 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
830 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
831 {"win32", 0, win32_start_timer,
832 win32_stop_timer, NULL, &alarm_win32_data},
833 #endif
834 {NULL, }
837 static void show_available_alarms(void)
839 int i;
841 printf("Available alarm timers, in order of precedence:\n");
842 for (i = 0; alarm_timers[i].name; i++)
843 printf("%s\n", alarm_timers[i].name);
846 static void configure_alarms(char const *opt)
848 int i;
849 int cur = 0;
850 int count = ARRAY_SIZE(alarm_timers) - 1;
851 char *arg;
852 char *name;
853 struct qemu_alarm_timer tmp;
855 if (!strcmp(opt, "?")) {
856 show_available_alarms();
857 exit(0);
860 arg = strdup(opt);
862 /* Reorder the array */
863 name = strtok(arg, ",");
864 while (name) {
865 for (i = 0; i < count && alarm_timers[i].name; i++) {
866 if (!strcmp(alarm_timers[i].name, name))
867 break;
870 if (i == count) {
871 fprintf(stderr, "Unknown clock %s\n", name);
872 goto next;
875 if (i < cur)
876 /* Ignore */
877 goto next;
879 /* Swap */
880 tmp = alarm_timers[i];
881 alarm_timers[i] = alarm_timers[cur];
882 alarm_timers[cur] = tmp;
884 cur++;
885 next:
886 name = strtok(NULL, ",");
889 free(arg);
891 if (cur) {
892 /* Disable remaining timers */
893 for (i = cur; i < count; i++)
894 alarm_timers[i].name = NULL;
895 } else {
896 show_available_alarms();
897 exit(1);
901 QEMUClock *rt_clock;
902 QEMUClock *vm_clock;
904 static QEMUTimer *active_timers[2];
906 static QEMUClock *qemu_new_clock(int type)
908 QEMUClock *clock;
909 clock = qemu_mallocz(sizeof(QEMUClock));
910 clock->type = type;
911 return clock;
914 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
916 QEMUTimer *ts;
918 ts = qemu_mallocz(sizeof(QEMUTimer));
919 ts->clock = clock;
920 ts->cb = cb;
921 ts->opaque = opaque;
922 return ts;
925 void qemu_free_timer(QEMUTimer *ts)
927 qemu_free(ts);
930 /* stop a timer, but do not dealloc it */
931 void qemu_del_timer(QEMUTimer *ts)
933 QEMUTimer **pt, *t;
935 /* NOTE: this code must be signal safe because
936 qemu_timer_expired() can be called from a signal. */
937 pt = &active_timers[ts->clock->type];
938 for(;;) {
939 t = *pt;
940 if (!t)
941 break;
942 if (t == ts) {
943 *pt = t->next;
944 break;
946 pt = &t->next;
950 /* modify the current timer so that it will be fired when current_time
951 >= expire_time. The corresponding callback will be called. */
952 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
954 QEMUTimer **pt, *t;
956 qemu_del_timer(ts);
958 /* add the timer in the sorted list */
959 /* NOTE: this code must be signal safe because
960 qemu_timer_expired() can be called from a signal. */
961 pt = &active_timers[ts->clock->type];
962 for(;;) {
963 t = *pt;
964 if (!t)
965 break;
966 if (t->expire_time > expire_time)
967 break;
968 pt = &t->next;
970 ts->expire_time = expire_time;
971 ts->next = *pt;
972 *pt = ts;
974 /* Rearm if necessary */
975 if (pt == &active_timers[ts->clock->type]) {
976 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
977 qemu_rearm_alarm_timer(alarm_timer);
979 /* Interrupt execution to force deadline recalculation. */
980 if (use_icount)
981 qemu_notify_event();
985 int qemu_timer_pending(QEMUTimer *ts)
987 QEMUTimer *t;
988 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
989 if (t == ts)
990 return 1;
992 return 0;
995 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
997 if (!timer_head)
998 return 0;
999 return (timer_head->expire_time <= current_time);
1002 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1004 QEMUTimer *ts;
1006 for(;;) {
1007 ts = *ptimer_head;
1008 if (!ts || ts->expire_time > current_time)
1009 break;
1010 /* remove timer from the list before calling the callback */
1011 *ptimer_head = ts->next;
1012 ts->next = NULL;
1014 /* run the callback (the timer list can be modified) */
1015 ts->cb(ts->opaque);
1019 int64_t qemu_get_clock(QEMUClock *clock)
1021 switch(clock->type) {
1022 case QEMU_TIMER_REALTIME:
1023 return get_clock() / 1000000;
1024 default:
1025 case QEMU_TIMER_VIRTUAL:
1026 if (use_icount) {
1027 return cpu_get_icount();
1028 } else {
1029 return cpu_get_clock();
1034 static void init_timers(void)
1036 init_get_clock();
1037 ticks_per_sec = QEMU_TIMER_BASE;
1038 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1039 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1042 /* save a timer */
1043 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1045 uint64_t expire_time;
1047 if (qemu_timer_pending(ts)) {
1048 expire_time = ts->expire_time;
1049 } else {
1050 expire_time = -1;
1052 qemu_put_be64(f, expire_time);
1055 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1057 uint64_t expire_time;
1059 expire_time = qemu_get_be64(f);
1060 if (expire_time != -1) {
1061 qemu_mod_timer(ts, expire_time);
1062 } else {
1063 qemu_del_timer(ts);
1067 static void timer_save(QEMUFile *f, void *opaque)
1069 if (cpu_ticks_enabled) {
1070 hw_error("cannot save state if virtual timers are running");
1072 qemu_put_be64(f, cpu_ticks_offset);
1073 qemu_put_be64(f, ticks_per_sec);
1074 qemu_put_be64(f, cpu_clock_offset);
1077 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1079 if (version_id != 1 && version_id != 2)
1080 return -EINVAL;
1081 if (cpu_ticks_enabled) {
1082 return -EINVAL;
1084 cpu_ticks_offset=qemu_get_be64(f);
1085 ticks_per_sec=qemu_get_be64(f);
1086 if (version_id == 2) {
1087 cpu_clock_offset=qemu_get_be64(f);
1089 return 0;
1092 static void qemu_event_increment(void);
1094 #ifdef _WIN32
1095 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1096 DWORD_PTR dwUser, DWORD_PTR dw1,
1097 DWORD_PTR dw2)
1098 #else
1099 static void host_alarm_handler(int host_signum)
1100 #endif
1102 #if 0
1103 #define DISP_FREQ 1000
1105 static int64_t delta_min = INT64_MAX;
1106 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1107 static int count;
1108 ti = qemu_get_clock(vm_clock);
1109 if (last_clock != 0) {
1110 delta = ti - last_clock;
1111 if (delta < delta_min)
1112 delta_min = delta;
1113 if (delta > delta_max)
1114 delta_max = delta;
1115 delta_cum += delta;
1116 if (++count == DISP_FREQ) {
1117 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1118 muldiv64(delta_min, 1000000, ticks_per_sec),
1119 muldiv64(delta_max, 1000000, ticks_per_sec),
1120 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1121 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1122 count = 0;
1123 delta_min = INT64_MAX;
1124 delta_max = 0;
1125 delta_cum = 0;
1128 last_clock = ti;
1130 #endif
1131 if (alarm_has_dynticks(alarm_timer) ||
1132 (!use_icount &&
1133 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1134 qemu_get_clock(vm_clock))) ||
1135 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1136 qemu_get_clock(rt_clock))) {
1137 qemu_event_increment();
1138 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1140 #ifndef CONFIG_IOTHREAD
1141 if (next_cpu) {
1142 /* stop the currently executing cpu because a timer occured */
1143 cpu_exit(next_cpu);
1145 #endif
1146 timer_alarm_pending = 1;
1147 qemu_notify_event();
1151 static int64_t qemu_next_deadline(void)
1153 int64_t delta;
1155 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1156 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1157 qemu_get_clock(vm_clock);
1158 } else {
1159 /* To avoid problems with overflow limit this to 2^32. */
1160 delta = INT32_MAX;
1163 if (delta < 0)
1164 delta = 0;
1166 return delta;
1169 #if defined(__linux__) || defined(_WIN32)
1170 static uint64_t qemu_next_deadline_dyntick(void)
1172 int64_t delta;
1173 int64_t rtdelta;
1175 if (use_icount)
1176 delta = INT32_MAX;
1177 else
1178 delta = (qemu_next_deadline() + 999) / 1000;
1180 if (active_timers[QEMU_TIMER_REALTIME]) {
1181 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1182 qemu_get_clock(rt_clock))*1000;
1183 if (rtdelta < delta)
1184 delta = rtdelta;
1187 if (delta < MIN_TIMER_REARM_US)
1188 delta = MIN_TIMER_REARM_US;
1190 return delta;
1192 #endif
1194 #ifndef _WIN32
1196 /* Sets a specific flag */
1197 static int fcntl_setfl(int fd, int flag)
1199 int flags;
1201 flags = fcntl(fd, F_GETFL);
1202 if (flags == -1)
1203 return -errno;
1205 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1206 return -errno;
1208 return 0;
1211 #if defined(__linux__)
1213 #define RTC_FREQ 1024
1215 static void enable_sigio_timer(int fd)
1217 struct sigaction act;
1219 /* timer signal */
1220 sigfillset(&act.sa_mask);
1221 act.sa_flags = 0;
1222 act.sa_handler = host_alarm_handler;
1224 sigaction(SIGIO, &act, NULL);
1225 fcntl_setfl(fd, O_ASYNC);
1226 fcntl(fd, F_SETOWN, getpid());
1229 static int hpet_start_timer(struct qemu_alarm_timer *t)
1231 struct hpet_info info;
1232 int r, fd;
1234 fd = open("/dev/hpet", O_RDONLY);
1235 if (fd < 0)
1236 return -1;
1238 /* Set frequency */
1239 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1240 if (r < 0) {
1241 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1242 "error, but for better emulation accuracy type:\n"
1243 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1244 goto fail;
1247 /* Check capabilities */
1248 r = ioctl(fd, HPET_INFO, &info);
1249 if (r < 0)
1250 goto fail;
1252 /* Enable periodic mode */
1253 r = ioctl(fd, HPET_EPI, 0);
1254 if (info.hi_flags && (r < 0))
1255 goto fail;
1257 /* Enable interrupt */
1258 r = ioctl(fd, HPET_IE_ON, 0);
1259 if (r < 0)
1260 goto fail;
1262 enable_sigio_timer(fd);
1263 t->priv = (void *)(long)fd;
1265 return 0;
1266 fail:
1267 close(fd);
1268 return -1;
1271 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1273 int fd = (long)t->priv;
1275 close(fd);
1278 static int rtc_start_timer(struct qemu_alarm_timer *t)
1280 int rtc_fd;
1281 unsigned long current_rtc_freq = 0;
1283 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1284 if (rtc_fd < 0)
1285 return -1;
1286 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1287 if (current_rtc_freq != RTC_FREQ &&
1288 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1289 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1290 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1291 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1292 goto fail;
1294 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1295 fail:
1296 close(rtc_fd);
1297 return -1;
1300 enable_sigio_timer(rtc_fd);
1302 t->priv = (void *)(long)rtc_fd;
1304 return 0;
1307 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1309 int rtc_fd = (long)t->priv;
1311 close(rtc_fd);
1314 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1316 struct sigevent ev;
1317 timer_t host_timer;
1318 struct sigaction act;
1320 sigfillset(&act.sa_mask);
1321 act.sa_flags = 0;
1322 act.sa_handler = host_alarm_handler;
1324 sigaction(SIGALRM, &act, NULL);
1327 * Initialize ev struct to 0 to avoid valgrind complaining
1328 * about uninitialized data in timer_create call
1330 memset(&ev, 0, sizeof(ev));
1331 ev.sigev_value.sival_int = 0;
1332 ev.sigev_notify = SIGEV_SIGNAL;
1333 ev.sigev_signo = SIGALRM;
1335 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1336 perror("timer_create");
1338 /* disable dynticks */
1339 fprintf(stderr, "Dynamic Ticks disabled\n");
1341 return -1;
1344 t->priv = (void *)(long)host_timer;
1346 return 0;
1349 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1351 timer_t host_timer = (timer_t)(long)t->priv;
1353 timer_delete(host_timer);
1356 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1358 timer_t host_timer = (timer_t)(long)t->priv;
1359 struct itimerspec timeout;
1360 int64_t nearest_delta_us = INT64_MAX;
1361 int64_t current_us;
1363 if (!active_timers[QEMU_TIMER_REALTIME] &&
1364 !active_timers[QEMU_TIMER_VIRTUAL])
1365 return;
1367 nearest_delta_us = qemu_next_deadline_dyntick();
1369 /* check whether a timer is already running */
1370 if (timer_gettime(host_timer, &timeout)) {
1371 perror("gettime");
1372 fprintf(stderr, "Internal timer error: aborting\n");
1373 exit(1);
1375 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1376 if (current_us && current_us <= nearest_delta_us)
1377 return;
1379 timeout.it_interval.tv_sec = 0;
1380 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1381 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1382 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1383 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1384 perror("settime");
1385 fprintf(stderr, "Internal timer error: aborting\n");
1386 exit(1);
1390 #endif /* defined(__linux__) */
1392 static int unix_start_timer(struct qemu_alarm_timer *t)
1394 struct sigaction act;
1395 struct itimerval itv;
1396 int err;
1398 /* timer signal */
1399 sigfillset(&act.sa_mask);
1400 act.sa_flags = 0;
1401 act.sa_handler = host_alarm_handler;
1403 sigaction(SIGALRM, &act, NULL);
1405 itv.it_interval.tv_sec = 0;
1406 /* for i386 kernel 2.6 to get 1 ms */
1407 itv.it_interval.tv_usec = 999;
1408 itv.it_value.tv_sec = 0;
1409 itv.it_value.tv_usec = 10 * 1000;
1411 err = setitimer(ITIMER_REAL, &itv, NULL);
1412 if (err)
1413 return -1;
1415 return 0;
1418 static void unix_stop_timer(struct qemu_alarm_timer *t)
1420 struct itimerval itv;
1422 memset(&itv, 0, sizeof(itv));
1423 setitimer(ITIMER_REAL, &itv, NULL);
1426 #endif /* !defined(_WIN32) */
1429 #ifdef _WIN32
1431 static int win32_start_timer(struct qemu_alarm_timer *t)
1433 TIMECAPS tc;
1434 struct qemu_alarm_win32 *data = t->priv;
1435 UINT flags;
1437 memset(&tc, 0, sizeof(tc));
1438 timeGetDevCaps(&tc, sizeof(tc));
1440 if (data->period < tc.wPeriodMin)
1441 data->period = tc.wPeriodMin;
1443 timeBeginPeriod(data->period);
1445 flags = TIME_CALLBACK_FUNCTION;
1446 if (alarm_has_dynticks(t))
1447 flags |= TIME_ONESHOT;
1448 else
1449 flags |= TIME_PERIODIC;
1451 data->timerId = timeSetEvent(1, // interval (ms)
1452 data->period, // resolution
1453 host_alarm_handler, // function
1454 (DWORD)t, // parameter
1455 flags);
1457 if (!data->timerId) {
1458 perror("Failed to initialize win32 alarm timer");
1459 timeEndPeriod(data->period);
1460 return -1;
1463 return 0;
1466 static void win32_stop_timer(struct qemu_alarm_timer *t)
1468 struct qemu_alarm_win32 *data = t->priv;
1470 timeKillEvent(data->timerId);
1471 timeEndPeriod(data->period);
1474 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1476 struct qemu_alarm_win32 *data = t->priv;
1477 uint64_t nearest_delta_us;
1479 if (!active_timers[QEMU_TIMER_REALTIME] &&
1480 !active_timers[QEMU_TIMER_VIRTUAL])
1481 return;
1483 nearest_delta_us = qemu_next_deadline_dyntick();
1484 nearest_delta_us /= 1000;
1486 timeKillEvent(data->timerId);
1488 data->timerId = timeSetEvent(1,
1489 data->period,
1490 host_alarm_handler,
1491 (DWORD)t,
1492 TIME_ONESHOT | TIME_PERIODIC);
1494 if (!data->timerId) {
1495 perror("Failed to re-arm win32 alarm timer");
1497 timeEndPeriod(data->period);
1498 exit(1);
1502 #endif /* _WIN32 */
1504 static int init_timer_alarm(void)
1506 struct qemu_alarm_timer *t = NULL;
1507 int i, err = -1;
1509 for (i = 0; alarm_timers[i].name; i++) {
1510 t = &alarm_timers[i];
1512 err = t->start(t);
1513 if (!err)
1514 break;
1517 if (err) {
1518 err = -ENOENT;
1519 goto fail;
1522 alarm_timer = t;
1524 return 0;
1526 fail:
1527 return err;
1530 static void quit_timers(void)
1532 alarm_timer->stop(alarm_timer);
1533 alarm_timer = NULL;
1536 /***********************************************************/
1537 /* host time/date access */
1538 void qemu_get_timedate(struct tm *tm, int offset)
1540 time_t ti;
1541 struct tm *ret;
1543 time(&ti);
1544 ti += offset;
1545 if (rtc_date_offset == -1) {
1546 if (rtc_utc)
1547 ret = gmtime(&ti);
1548 else
1549 ret = localtime(&ti);
1550 } else {
1551 ti -= rtc_date_offset;
1552 ret = gmtime(&ti);
1555 memcpy(tm, ret, sizeof(struct tm));
1558 int qemu_timedate_diff(struct tm *tm)
1560 time_t seconds;
1562 if (rtc_date_offset == -1)
1563 if (rtc_utc)
1564 seconds = mktimegm(tm);
1565 else
1566 seconds = mktime(tm);
1567 else
1568 seconds = mktimegm(tm) + rtc_date_offset;
1570 return seconds - time(NULL);
1573 #ifdef _WIN32
1574 static void socket_cleanup(void)
1576 WSACleanup();
1579 static int socket_init(void)
1581 WSADATA Data;
1582 int ret, err;
1584 ret = WSAStartup(MAKEWORD(2,2), &Data);
1585 if (ret != 0) {
1586 err = WSAGetLastError();
1587 fprintf(stderr, "WSAStartup: %d\n", err);
1588 return -1;
1590 atexit(socket_cleanup);
1591 return 0;
1593 #endif
1595 /***********************************************************/
1596 /* Bluetooth support */
1597 static int nb_hcis;
1598 static int cur_hci;
1599 static struct HCIInfo *hci_table[MAX_NICS];
1601 static struct bt_vlan_s {
1602 struct bt_scatternet_s net;
1603 int id;
1604 struct bt_vlan_s *next;
1605 } *first_bt_vlan;
1607 /* find or alloc a new bluetooth "VLAN" */
1608 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1610 struct bt_vlan_s **pvlan, *vlan;
1611 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1612 if (vlan->id == id)
1613 return &vlan->net;
1615 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1616 vlan->id = id;
1617 pvlan = &first_bt_vlan;
1618 while (*pvlan != NULL)
1619 pvlan = &(*pvlan)->next;
1620 *pvlan = vlan;
1621 return &vlan->net;
1624 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1628 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1630 return -ENOTSUP;
1633 static struct HCIInfo null_hci = {
1634 .cmd_send = null_hci_send,
1635 .sco_send = null_hci_send,
1636 .acl_send = null_hci_send,
1637 .bdaddr_set = null_hci_addr_set,
1640 struct HCIInfo *qemu_next_hci(void)
1642 if (cur_hci == nb_hcis)
1643 return &null_hci;
1645 return hci_table[cur_hci++];
1648 static struct HCIInfo *hci_init(const char *str)
1650 char *endp;
1651 struct bt_scatternet_s *vlan = 0;
1653 if (!strcmp(str, "null"))
1654 /* null */
1655 return &null_hci;
1656 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1657 /* host[:hciN] */
1658 return bt_host_hci(str[4] ? str + 5 : "hci0");
1659 else if (!strncmp(str, "hci", 3)) {
1660 /* hci[,vlan=n] */
1661 if (str[3]) {
1662 if (!strncmp(str + 3, ",vlan=", 6)) {
1663 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1664 if (*endp)
1665 vlan = 0;
1667 } else
1668 vlan = qemu_find_bt_vlan(0);
1669 if (vlan)
1670 return bt_new_hci(vlan);
1673 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1675 return 0;
1678 static int bt_hci_parse(const char *str)
1680 struct HCIInfo *hci;
1681 bdaddr_t bdaddr;
1683 if (nb_hcis >= MAX_NICS) {
1684 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1685 return -1;
1688 hci = hci_init(str);
1689 if (!hci)
1690 return -1;
1692 bdaddr.b[0] = 0x52;
1693 bdaddr.b[1] = 0x54;
1694 bdaddr.b[2] = 0x00;
1695 bdaddr.b[3] = 0x12;
1696 bdaddr.b[4] = 0x34;
1697 bdaddr.b[5] = 0x56 + nb_hcis;
1698 hci->bdaddr_set(hci, bdaddr.b);
1700 hci_table[nb_hcis++] = hci;
1702 return 0;
1705 static void bt_vhci_add(int vlan_id)
1707 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1709 if (!vlan->slave)
1710 fprintf(stderr, "qemu: warning: adding a VHCI to "
1711 "an empty scatternet %i\n", vlan_id);
1713 bt_vhci_init(bt_new_hci(vlan));
1716 static struct bt_device_s *bt_device_add(const char *opt)
1718 struct bt_scatternet_s *vlan;
1719 int vlan_id = 0;
1720 char *endp = strstr(opt, ",vlan=");
1721 int len = (endp ? endp - opt : strlen(opt)) + 1;
1722 char devname[10];
1724 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1726 if (endp) {
1727 vlan_id = strtol(endp + 6, &endp, 0);
1728 if (*endp) {
1729 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1730 return 0;
1734 vlan = qemu_find_bt_vlan(vlan_id);
1736 if (!vlan->slave)
1737 fprintf(stderr, "qemu: warning: adding a slave device to "
1738 "an empty scatternet %i\n", vlan_id);
1740 if (!strcmp(devname, "keyboard"))
1741 return bt_keyboard_init(vlan);
1743 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1744 return 0;
1747 static int bt_parse(const char *opt)
1749 const char *endp, *p;
1750 int vlan;
1752 if (strstart(opt, "hci", &endp)) {
1753 if (!*endp || *endp == ',') {
1754 if (*endp)
1755 if (!strstart(endp, ",vlan=", 0))
1756 opt = endp + 1;
1758 return bt_hci_parse(opt);
1760 } else if (strstart(opt, "vhci", &endp)) {
1761 if (!*endp || *endp == ',') {
1762 if (*endp) {
1763 if (strstart(endp, ",vlan=", &p)) {
1764 vlan = strtol(p, (char **) &endp, 0);
1765 if (*endp) {
1766 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1767 return 1;
1769 } else {
1770 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1771 return 1;
1773 } else
1774 vlan = 0;
1776 bt_vhci_add(vlan);
1777 return 0;
1779 } else if (strstart(opt, "device:", &endp))
1780 return !bt_device_add(endp);
1782 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1783 return 1;
1786 /***********************************************************/
1787 /* QEMU Block devices */
1789 #define HD_ALIAS "index=%d,media=disk"
1790 #define CDROM_ALIAS "index=2,media=cdrom"
1791 #define FD_ALIAS "index=%d,if=floppy"
1792 #define PFLASH_ALIAS "if=pflash"
1793 #define MTD_ALIAS "if=mtd"
1794 #define SD_ALIAS "index=0,if=sd"
1796 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1798 va_list ap;
1799 char optstr[1024];
1800 QemuOpts *opts;
1802 va_start(ap, fmt);
1803 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1804 va_end(ap);
1806 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1807 if (!opts) {
1808 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1809 __FUNCTION__, optstr);
1810 return NULL;
1812 if (file)
1813 qemu_opt_set(opts, "file", file);
1814 return opts;
1817 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1819 DriveInfo *dinfo;
1821 /* seek interface, bus and unit */
1823 TAILQ_FOREACH(dinfo, &drives, next) {
1824 if (dinfo->type == type &&
1825 dinfo->bus == bus &&
1826 dinfo->unit == unit)
1827 return dinfo;
1830 return NULL;
1833 DriveInfo *drive_get_by_id(const char *id)
1835 DriveInfo *dinfo;
1837 TAILQ_FOREACH(dinfo, &drives, next) {
1838 if (strcmp(id, dinfo->id))
1839 continue;
1840 return dinfo;
1842 return NULL;
1845 int drive_get_max_bus(BlockInterfaceType type)
1847 int max_bus;
1848 DriveInfo *dinfo;
1850 max_bus = -1;
1851 TAILQ_FOREACH(dinfo, &drives, next) {
1852 if(dinfo->type == type &&
1853 dinfo->bus > max_bus)
1854 max_bus = dinfo->bus;
1856 return max_bus;
1859 const char *drive_get_serial(BlockDriverState *bdrv)
1861 DriveInfo *dinfo;
1863 TAILQ_FOREACH(dinfo, &drives, next) {
1864 if (dinfo->bdrv == bdrv)
1865 return dinfo->serial;
1868 return "\0";
1871 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1873 DriveInfo *dinfo;
1875 TAILQ_FOREACH(dinfo, &drives, next) {
1876 if (dinfo->bdrv == bdrv)
1877 return dinfo->onerror;
1880 return BLOCK_ERR_STOP_ENOSPC;
1883 static void bdrv_format_print(void *opaque, const char *name)
1885 fprintf(stderr, " %s", name);
1888 void drive_uninit(BlockDriverState *bdrv)
1890 DriveInfo *dinfo;
1892 TAILQ_FOREACH(dinfo, &drives, next) {
1893 if (dinfo->bdrv != bdrv)
1894 continue;
1895 qemu_opts_del(dinfo->opts);
1896 TAILQ_REMOVE(&drives, dinfo, next);
1897 qemu_free(dinfo);
1898 break;
1902 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1903 int *fatal_error)
1905 const char *buf;
1906 const char *file = NULL;
1907 char devname[128];
1908 const char *serial;
1909 const char *mediastr = "";
1910 BlockInterfaceType type;
1911 enum { MEDIA_DISK, MEDIA_CDROM } media;
1912 int bus_id, unit_id;
1913 int cyls, heads, secs, translation;
1914 BlockDriver *drv = NULL;
1915 QEMUMachine *machine = opaque;
1916 int max_devs;
1917 int index;
1918 int cache;
1919 int bdrv_flags, onerror;
1920 const char *devaddr;
1921 DriveInfo *dinfo;
1922 int snapshot = 0;
1924 *fatal_error = 1;
1926 translation = BIOS_ATA_TRANSLATION_AUTO;
1927 cache = 1;
1929 if (machine->use_scsi) {
1930 type = IF_SCSI;
1931 max_devs = MAX_SCSI_DEVS;
1932 pstrcpy(devname, sizeof(devname), "scsi");
1933 } else {
1934 type = IF_IDE;
1935 max_devs = MAX_IDE_DEVS;
1936 pstrcpy(devname, sizeof(devname), "ide");
1938 media = MEDIA_DISK;
1940 /* extract parameters */
1941 bus_id = qemu_opt_get_number(opts, "bus", 0);
1942 unit_id = qemu_opt_get_number(opts, "unit", -1);
1943 index = qemu_opt_get_number(opts, "index", -1);
1945 cyls = qemu_opt_get_number(opts, "cyls", 0);
1946 heads = qemu_opt_get_number(opts, "heads", 0);
1947 secs = qemu_opt_get_number(opts, "secs", 0);
1949 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1951 file = qemu_opt_get(opts, "file");
1952 serial = qemu_opt_get(opts, "serial");
1954 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1955 pstrcpy(devname, sizeof(devname), buf);
1956 if (!strcmp(buf, "ide")) {
1957 type = IF_IDE;
1958 max_devs = MAX_IDE_DEVS;
1959 } else if (!strcmp(buf, "scsi")) {
1960 type = IF_SCSI;
1961 max_devs = MAX_SCSI_DEVS;
1962 } else if (!strcmp(buf, "floppy")) {
1963 type = IF_FLOPPY;
1964 max_devs = 0;
1965 } else if (!strcmp(buf, "pflash")) {
1966 type = IF_PFLASH;
1967 max_devs = 0;
1968 } else if (!strcmp(buf, "mtd")) {
1969 type = IF_MTD;
1970 max_devs = 0;
1971 } else if (!strcmp(buf, "sd")) {
1972 type = IF_SD;
1973 max_devs = 0;
1974 } else if (!strcmp(buf, "virtio")) {
1975 type = IF_VIRTIO;
1976 max_devs = 0;
1977 } else if (!strcmp(buf, "xen")) {
1978 type = IF_XEN;
1979 max_devs = 0;
1980 } else if (!strcmp(buf, "none")) {
1981 type = IF_NONE;
1982 max_devs = 0;
1983 } else {
1984 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
1985 return NULL;
1989 if (cyls || heads || secs) {
1990 if (cyls < 1 || cyls > 16383) {
1991 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
1992 return NULL;
1994 if (heads < 1 || heads > 16) {
1995 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
1996 return NULL;
1998 if (secs < 1 || secs > 63) {
1999 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2000 return NULL;
2004 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2005 if (!cyls) {
2006 fprintf(stderr,
2007 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2008 buf);
2009 return NULL;
2011 if (!strcmp(buf, "none"))
2012 translation = BIOS_ATA_TRANSLATION_NONE;
2013 else if (!strcmp(buf, "lba"))
2014 translation = BIOS_ATA_TRANSLATION_LBA;
2015 else if (!strcmp(buf, "auto"))
2016 translation = BIOS_ATA_TRANSLATION_AUTO;
2017 else {
2018 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2019 return NULL;
2023 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2024 if (!strcmp(buf, "disk")) {
2025 media = MEDIA_DISK;
2026 } else if (!strcmp(buf, "cdrom")) {
2027 if (cyls || secs || heads) {
2028 fprintf(stderr,
2029 "qemu: '%s' invalid physical CHS format\n", buf);
2030 return NULL;
2032 media = MEDIA_CDROM;
2033 } else {
2034 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2035 return NULL;
2039 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2040 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2041 cache = 0;
2042 else if (!strcmp(buf, "writethrough"))
2043 cache = 1;
2044 else if (!strcmp(buf, "writeback"))
2045 cache = 2;
2046 else {
2047 fprintf(stderr, "qemu: invalid cache option\n");
2048 return NULL;
2052 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2053 if (strcmp(buf, "?") == 0) {
2054 fprintf(stderr, "qemu: Supported formats:");
2055 bdrv_iterate_format(bdrv_format_print, NULL);
2056 fprintf(stderr, "\n");
2057 return NULL;
2059 drv = bdrv_find_format(buf);
2060 if (!drv) {
2061 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2062 return NULL;
2066 onerror = BLOCK_ERR_STOP_ENOSPC;
2067 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2068 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2069 fprintf(stderr, "werror is no supported by this format\n");
2070 return NULL;
2072 if (!strcmp(buf, "ignore"))
2073 onerror = BLOCK_ERR_IGNORE;
2074 else if (!strcmp(buf, "enospc"))
2075 onerror = BLOCK_ERR_STOP_ENOSPC;
2076 else if (!strcmp(buf, "stop"))
2077 onerror = BLOCK_ERR_STOP_ANY;
2078 else if (!strcmp(buf, "report"))
2079 onerror = BLOCK_ERR_REPORT;
2080 else {
2081 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2082 return NULL;
2086 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2087 if (type != IF_VIRTIO) {
2088 fprintf(stderr, "addr is not supported\n");
2089 return NULL;
2093 /* compute bus and unit according index */
2095 if (index != -1) {
2096 if (bus_id != 0 || unit_id != -1) {
2097 fprintf(stderr,
2098 "qemu: index cannot be used with bus and unit\n");
2099 return NULL;
2101 if (max_devs == 0)
2103 unit_id = index;
2104 bus_id = 0;
2105 } else {
2106 unit_id = index % max_devs;
2107 bus_id = index / max_devs;
2111 /* if user doesn't specify a unit_id,
2112 * try to find the first free
2115 if (unit_id == -1) {
2116 unit_id = 0;
2117 while (drive_get(type, bus_id, unit_id) != NULL) {
2118 unit_id++;
2119 if (max_devs && unit_id >= max_devs) {
2120 unit_id -= max_devs;
2121 bus_id++;
2126 /* check unit id */
2128 if (max_devs && unit_id >= max_devs) {
2129 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2130 unit_id, max_devs - 1);
2131 return NULL;
2135 * ignore multiple definitions
2138 if (drive_get(type, bus_id, unit_id) != NULL) {
2139 *fatal_error = 0;
2140 return NULL;
2143 /* init */
2145 dinfo = qemu_mallocz(sizeof(*dinfo));
2146 if ((buf = qemu_opts_id(opts)) != NULL) {
2147 dinfo->id = qemu_strdup(buf);
2148 } else {
2149 /* no id supplied -> create one */
2150 dinfo->id = qemu_mallocz(32);
2151 if (type == IF_IDE || type == IF_SCSI)
2152 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2153 if (max_devs)
2154 snprintf(dinfo->id, 32, "%s%i%s%i",
2155 devname, bus_id, mediastr, unit_id);
2156 else
2157 snprintf(dinfo->id, 32, "%s%s%i",
2158 devname, mediastr, unit_id);
2160 dinfo->bdrv = bdrv_new(dinfo->id);
2161 dinfo->devaddr = devaddr;
2162 dinfo->type = type;
2163 dinfo->bus = bus_id;
2164 dinfo->unit = unit_id;
2165 dinfo->onerror = onerror;
2166 dinfo->opts = opts;
2167 if (serial)
2168 strncpy(dinfo->serial, serial, sizeof(serial));
2169 TAILQ_INSERT_TAIL(&drives, dinfo, next);
2171 switch(type) {
2172 case IF_IDE:
2173 case IF_SCSI:
2174 case IF_XEN:
2175 switch(media) {
2176 case MEDIA_DISK:
2177 if (cyls != 0) {
2178 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2179 bdrv_set_translation_hint(dinfo->bdrv, translation);
2181 break;
2182 case MEDIA_CDROM:
2183 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2184 break;
2186 break;
2187 case IF_SD:
2188 /* FIXME: This isn't really a floppy, but it's a reasonable
2189 approximation. */
2190 case IF_FLOPPY:
2191 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2192 break;
2193 case IF_PFLASH:
2194 case IF_MTD:
2195 case IF_NONE:
2196 break;
2197 case IF_VIRTIO:
2198 /* add virtio block device */
2199 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2200 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2201 qemu_opt_set(opts, "drive", dinfo->id);
2202 if (devaddr)
2203 qemu_opt_set(opts, "addr", devaddr);
2204 break;
2205 case IF_COUNT:
2206 abort();
2208 if (!file) {
2209 *fatal_error = 0;
2210 return NULL;
2212 bdrv_flags = 0;
2213 if (snapshot) {
2214 bdrv_flags |= BDRV_O_SNAPSHOT;
2215 cache = 2; /* always use write-back with snapshot */
2217 if (cache == 0) /* no caching */
2218 bdrv_flags |= BDRV_O_NOCACHE;
2219 else if (cache == 2) /* write-back */
2220 bdrv_flags |= BDRV_O_CACHE_WB;
2221 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2222 fprintf(stderr, "qemu: could not open disk image %s\n",
2223 file);
2224 return NULL;
2226 if (bdrv_key_required(dinfo->bdrv))
2227 autostart = 0;
2228 *fatal_error = 0;
2229 return dinfo;
2232 static int drive_init_func(QemuOpts *opts, void *opaque)
2234 QEMUMachine *machine = opaque;
2235 int fatal_error = 0;
2237 if (drive_init(opts, machine, &fatal_error) == NULL) {
2238 if (fatal_error)
2239 return 1;
2241 return 0;
2244 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2246 if (NULL == qemu_opt_get(opts, "snapshot")) {
2247 qemu_opt_set(opts, "snapshot", "on");
2249 return 0;
2252 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2254 boot_set_handler = func;
2255 boot_set_opaque = opaque;
2258 int qemu_boot_set(const char *boot_devices)
2260 if (!boot_set_handler) {
2261 return -EINVAL;
2263 return boot_set_handler(boot_set_opaque, boot_devices);
2266 static int parse_bootdevices(char *devices)
2268 /* We just do some generic consistency checks */
2269 const char *p;
2270 int bitmap = 0;
2272 for (p = devices; *p != '\0'; p++) {
2273 /* Allowed boot devices are:
2274 * a-b: floppy disk drives
2275 * c-f: IDE disk drives
2276 * g-m: machine implementation dependant drives
2277 * n-p: network devices
2278 * It's up to each machine implementation to check if the given boot
2279 * devices match the actual hardware implementation and firmware
2280 * features.
2282 if (*p < 'a' || *p > 'p') {
2283 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2284 exit(1);
2286 if (bitmap & (1 << (*p - 'a'))) {
2287 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2288 exit(1);
2290 bitmap |= 1 << (*p - 'a');
2292 return bitmap;
2295 static void restore_boot_devices(void *opaque)
2297 char *standard_boot_devices = opaque;
2299 qemu_boot_set(standard_boot_devices);
2301 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2302 qemu_free(standard_boot_devices);
2305 static void numa_add(const char *optarg)
2307 char option[128];
2308 char *endptr;
2309 unsigned long long value, endvalue;
2310 int nodenr;
2312 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2313 if (!strcmp(option, "node")) {
2314 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2315 nodenr = nb_numa_nodes;
2316 } else {
2317 nodenr = strtoull(option, NULL, 10);
2320 if (get_param_value(option, 128, "mem", optarg) == 0) {
2321 node_mem[nodenr] = 0;
2322 } else {
2323 value = strtoull(option, &endptr, 0);
2324 switch (*endptr) {
2325 case 0: case 'M': case 'm':
2326 value <<= 20;
2327 break;
2328 case 'G': case 'g':
2329 value <<= 30;
2330 break;
2332 node_mem[nodenr] = value;
2334 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2335 node_cpumask[nodenr] = 0;
2336 } else {
2337 value = strtoull(option, &endptr, 10);
2338 if (value >= 64) {
2339 value = 63;
2340 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2341 } else {
2342 if (*endptr == '-') {
2343 endvalue = strtoull(endptr+1, &endptr, 10);
2344 if (endvalue >= 63) {
2345 endvalue = 62;
2346 fprintf(stderr,
2347 "only 63 CPUs in NUMA mode supported.\n");
2349 value = (1 << (endvalue + 1)) - (1 << value);
2350 } else {
2351 value = 1 << value;
2354 node_cpumask[nodenr] = value;
2356 nb_numa_nodes++;
2358 return;
2361 static void smp_parse(const char *optarg)
2363 int smp, sockets = 0, threads = 0, cores = 0;
2364 char *endptr;
2365 char option[128];
2367 smp = strtoul(optarg, &endptr, 10);
2368 if (endptr != optarg) {
2369 if (*endptr == ',') {
2370 endptr++;
2373 if (get_param_value(option, 128, "sockets", endptr) != 0)
2374 sockets = strtoull(option, NULL, 10);
2375 if (get_param_value(option, 128, "cores", endptr) != 0)
2376 cores = strtoull(option, NULL, 10);
2377 if (get_param_value(option, 128, "threads", endptr) != 0)
2378 threads = strtoull(option, NULL, 10);
2379 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2380 max_cpus = strtoull(option, NULL, 10);
2382 /* compute missing values, prefer sockets over cores over threads */
2383 if (smp == 0 || sockets == 0) {
2384 sockets = sockets > 0 ? sockets : 1;
2385 cores = cores > 0 ? cores : 1;
2386 threads = threads > 0 ? threads : 1;
2387 if (smp == 0) {
2388 smp = cores * threads * sockets;
2389 } else {
2390 sockets = smp / (cores * threads);
2392 } else {
2393 if (cores == 0) {
2394 threads = threads > 0 ? threads : 1;
2395 cores = smp / (sockets * threads);
2396 } else {
2397 if (sockets == 0) {
2398 sockets = smp / (cores * threads);
2399 } else {
2400 threads = smp / (cores * sockets);
2404 smp_cpus = smp;
2405 smp_cores = cores > 0 ? cores : 1;
2406 smp_threads = threads > 0 ? threads : 1;
2407 if (max_cpus == 0)
2408 max_cpus = smp_cpus;
2411 /***********************************************************/
2412 /* USB devices */
2414 static USBPort *used_usb_ports;
2415 static USBPort *free_usb_ports;
2417 /* ??? Maybe change this to register a hub to keep track of the topology. */
2418 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2419 usb_attachfn attach)
2421 port->opaque = opaque;
2422 port->index = index;
2423 port->attach = attach;
2424 port->next = free_usb_ports;
2425 free_usb_ports = port;
2428 int usb_device_add_dev(USBDevice *dev)
2430 USBPort *port;
2432 /* Find a USB port to add the device to. */
2433 port = free_usb_ports;
2434 if (!port->next) {
2435 USBDevice *hub;
2437 /* Create a new hub and chain it on. */
2438 free_usb_ports = NULL;
2439 port->next = used_usb_ports;
2440 used_usb_ports = port;
2442 hub = usb_hub_init(VM_USB_HUB_SIZE);
2443 usb_attach(port, hub);
2444 port = free_usb_ports;
2447 free_usb_ports = port->next;
2448 port->next = used_usb_ports;
2449 used_usb_ports = port;
2450 usb_attach(port, dev);
2451 return 0;
2454 static void usb_msd_password_cb(void *opaque, int err)
2456 USBDevice *dev = opaque;
2458 if (!err)
2459 usb_device_add_dev(dev);
2460 else
2461 dev->handle_destroy(dev);
2464 static int usb_device_add(const char *devname, int is_hotplug)
2466 const char *p;
2467 USBDevice *dev;
2469 if (!free_usb_ports)
2470 return -1;
2472 if (strstart(devname, "host:", &p)) {
2473 dev = usb_host_device_open(p);
2474 } else if (!strcmp(devname, "mouse")) {
2475 dev = usb_mouse_init();
2476 } else if (!strcmp(devname, "tablet")) {
2477 dev = usb_tablet_init();
2478 } else if (!strcmp(devname, "keyboard")) {
2479 dev = usb_keyboard_init();
2480 } else if (strstart(devname, "disk:", &p)) {
2481 BlockDriverState *bs;
2483 dev = usb_msd_init(p);
2484 if (!dev)
2485 return -1;
2486 bs = usb_msd_get_bdrv(dev);
2487 if (bdrv_key_required(bs)) {
2488 autostart = 0;
2489 if (is_hotplug) {
2490 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2491 dev);
2492 return 0;
2495 } else if (!strcmp(devname, "wacom-tablet")) {
2496 dev = usb_wacom_init();
2497 } else if (strstart(devname, "serial:", &p)) {
2498 dev = usb_serial_init(p);
2499 #ifdef CONFIG_BRLAPI
2500 } else if (!strcmp(devname, "braille")) {
2501 dev = usb_baum_init();
2502 #endif
2503 } else if (strstart(devname, "net:", &p)) {
2504 int nic = nb_nics;
2506 if (net_client_init(NULL, "nic", p) < 0)
2507 return -1;
2508 nd_table[nic].model = "usb";
2509 dev = usb_net_init(&nd_table[nic]);
2510 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2511 dev = usb_bt_init(devname[2] ? hci_init(p) :
2512 bt_new_hci(qemu_find_bt_vlan(0)));
2513 } else {
2514 return -1;
2516 if (!dev)
2517 return -1;
2519 return usb_device_add_dev(dev);
2522 int usb_device_del_addr(int bus_num, int addr)
2524 USBPort *port;
2525 USBPort **lastp;
2526 USBDevice *dev;
2528 if (!used_usb_ports)
2529 return -1;
2531 if (bus_num != 0)
2532 return -1;
2534 lastp = &used_usb_ports;
2535 port = used_usb_ports;
2536 while (port && port->dev->addr != addr) {
2537 lastp = &port->next;
2538 port = port->next;
2541 if (!port)
2542 return -1;
2544 dev = port->dev;
2545 *lastp = port->next;
2546 usb_attach(port, NULL);
2547 dev->handle_destroy(dev);
2548 port->next = free_usb_ports;
2549 free_usb_ports = port;
2550 return 0;
2553 static int usb_device_del(const char *devname)
2555 int bus_num, addr;
2556 const char *p;
2558 if (strstart(devname, "host:", &p))
2559 return usb_host_device_close(p);
2561 if (!used_usb_ports)
2562 return -1;
2564 p = strchr(devname, '.');
2565 if (!p)
2566 return -1;
2567 bus_num = strtoul(devname, NULL, 0);
2568 addr = strtoul(p + 1, NULL, 0);
2570 return usb_device_del_addr(bus_num, addr);
2573 static int usb_parse(const char *cmdline)
2575 return usb_device_add(cmdline, 0);
2578 void do_usb_add(Monitor *mon, const char *devname)
2580 usb_device_add(devname, 1);
2583 void do_usb_del(Monitor *mon, const char *devname)
2585 usb_device_del(devname);
2588 void usb_info(Monitor *mon)
2590 USBDevice *dev;
2591 USBPort *port;
2592 const char *speed_str;
2594 if (!usb_enabled) {
2595 monitor_printf(mon, "USB support not enabled\n");
2596 return;
2599 for (port = used_usb_ports; port; port = port->next) {
2600 dev = port->dev;
2601 if (!dev)
2602 continue;
2603 switch(dev->speed) {
2604 case USB_SPEED_LOW:
2605 speed_str = "1.5";
2606 break;
2607 case USB_SPEED_FULL:
2608 speed_str = "12";
2609 break;
2610 case USB_SPEED_HIGH:
2611 speed_str = "480";
2612 break;
2613 default:
2614 speed_str = "?";
2615 break;
2617 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2618 0, dev->addr, speed_str, dev->devname);
2622 /***********************************************************/
2623 /* PCMCIA/Cardbus */
2625 static struct pcmcia_socket_entry_s {
2626 PCMCIASocket *socket;
2627 struct pcmcia_socket_entry_s *next;
2628 } *pcmcia_sockets = 0;
2630 void pcmcia_socket_register(PCMCIASocket *socket)
2632 struct pcmcia_socket_entry_s *entry;
2634 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2635 entry->socket = socket;
2636 entry->next = pcmcia_sockets;
2637 pcmcia_sockets = entry;
2640 void pcmcia_socket_unregister(PCMCIASocket *socket)
2642 struct pcmcia_socket_entry_s *entry, **ptr;
2644 ptr = &pcmcia_sockets;
2645 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2646 if (entry->socket == socket) {
2647 *ptr = entry->next;
2648 qemu_free(entry);
2652 void pcmcia_info(Monitor *mon)
2654 struct pcmcia_socket_entry_s *iter;
2656 if (!pcmcia_sockets)
2657 monitor_printf(mon, "No PCMCIA sockets\n");
2659 for (iter = pcmcia_sockets; iter; iter = iter->next)
2660 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2661 iter->socket->attached ? iter->socket->card_string :
2662 "Empty");
2665 /***********************************************************/
2666 /* register display */
2668 struct DisplayAllocator default_allocator = {
2669 defaultallocator_create_displaysurface,
2670 defaultallocator_resize_displaysurface,
2671 defaultallocator_free_displaysurface
2674 void register_displaystate(DisplayState *ds)
2676 DisplayState **s;
2677 s = &display_state;
2678 while (*s != NULL)
2679 s = &(*s)->next;
2680 ds->next = NULL;
2681 *s = ds;
2684 DisplayState *get_displaystate(void)
2686 return display_state;
2689 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2691 if(ds->allocator == &default_allocator) ds->allocator = da;
2692 return ds->allocator;
2695 /* dumb display */
2697 static void dumb_display_init(void)
2699 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2700 ds->allocator = &default_allocator;
2701 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2702 register_displaystate(ds);
2705 /***********************************************************/
2706 /* I/O handling */
2708 typedef struct IOHandlerRecord {
2709 int fd;
2710 IOCanRWHandler *fd_read_poll;
2711 IOHandler *fd_read;
2712 IOHandler *fd_write;
2713 int deleted;
2714 void *opaque;
2715 /* temporary data */
2716 struct pollfd *ufd;
2717 struct IOHandlerRecord *next;
2718 } IOHandlerRecord;
2720 static IOHandlerRecord *first_io_handler;
2722 /* XXX: fd_read_poll should be suppressed, but an API change is
2723 necessary in the character devices to suppress fd_can_read(). */
2724 int qemu_set_fd_handler2(int fd,
2725 IOCanRWHandler *fd_read_poll,
2726 IOHandler *fd_read,
2727 IOHandler *fd_write,
2728 void *opaque)
2730 IOHandlerRecord **pioh, *ioh;
2732 if (!fd_read && !fd_write) {
2733 pioh = &first_io_handler;
2734 for(;;) {
2735 ioh = *pioh;
2736 if (ioh == NULL)
2737 break;
2738 if (ioh->fd == fd) {
2739 ioh->deleted = 1;
2740 break;
2742 pioh = &ioh->next;
2744 } else {
2745 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2746 if (ioh->fd == fd)
2747 goto found;
2749 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2750 ioh->next = first_io_handler;
2751 first_io_handler = ioh;
2752 found:
2753 ioh->fd = fd;
2754 ioh->fd_read_poll = fd_read_poll;
2755 ioh->fd_read = fd_read;
2756 ioh->fd_write = fd_write;
2757 ioh->opaque = opaque;
2758 ioh->deleted = 0;
2760 return 0;
2763 int qemu_set_fd_handler(int fd,
2764 IOHandler *fd_read,
2765 IOHandler *fd_write,
2766 void *opaque)
2768 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2771 #ifdef _WIN32
2772 /***********************************************************/
2773 /* Polling handling */
2775 typedef struct PollingEntry {
2776 PollingFunc *func;
2777 void *opaque;
2778 struct PollingEntry *next;
2779 } PollingEntry;
2781 static PollingEntry *first_polling_entry;
2783 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2785 PollingEntry **ppe, *pe;
2786 pe = qemu_mallocz(sizeof(PollingEntry));
2787 pe->func = func;
2788 pe->opaque = opaque;
2789 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2790 *ppe = pe;
2791 return 0;
2794 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2796 PollingEntry **ppe, *pe;
2797 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2798 pe = *ppe;
2799 if (pe->func == func && pe->opaque == opaque) {
2800 *ppe = pe->next;
2801 qemu_free(pe);
2802 break;
2807 /***********************************************************/
2808 /* Wait objects support */
2809 typedef struct WaitObjects {
2810 int num;
2811 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2812 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2813 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2814 } WaitObjects;
2816 static WaitObjects wait_objects = {0};
2818 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2820 WaitObjects *w = &wait_objects;
2822 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2823 return -1;
2824 w->events[w->num] = handle;
2825 w->func[w->num] = func;
2826 w->opaque[w->num] = opaque;
2827 w->num++;
2828 return 0;
2831 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2833 int i, found;
2834 WaitObjects *w = &wait_objects;
2836 found = 0;
2837 for (i = 0; i < w->num; i++) {
2838 if (w->events[i] == handle)
2839 found = 1;
2840 if (found) {
2841 w->events[i] = w->events[i + 1];
2842 w->func[i] = w->func[i + 1];
2843 w->opaque[i] = w->opaque[i + 1];
2846 if (found)
2847 w->num--;
2849 #endif
2851 /***********************************************************/
2852 /* ram save/restore */
2854 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2856 int v;
2858 v = qemu_get_byte(f);
2859 switch(v) {
2860 case 0:
2861 if (qemu_get_buffer(f, buf, len) != len)
2862 return -EIO;
2863 break;
2864 case 1:
2865 v = qemu_get_byte(f);
2866 memset(buf, v, len);
2867 break;
2868 default:
2869 return -EINVAL;
2872 if (qemu_file_has_error(f))
2873 return -EIO;
2875 return 0;
2878 static int ram_load_v1(QEMUFile *f, void *opaque)
2880 int ret;
2881 ram_addr_t i;
2883 if (qemu_get_be32(f) != last_ram_offset)
2884 return -EINVAL;
2885 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2886 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2887 if (ret)
2888 return ret;
2890 return 0;
2893 #define BDRV_HASH_BLOCK_SIZE 1024
2894 #define IOBUF_SIZE 4096
2895 #define RAM_CBLOCK_MAGIC 0xfabe
2897 typedef struct RamDecompressState {
2898 z_stream zstream;
2899 QEMUFile *f;
2900 uint8_t buf[IOBUF_SIZE];
2901 } RamDecompressState;
2903 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2905 int ret;
2906 memset(s, 0, sizeof(*s));
2907 s->f = f;
2908 ret = inflateInit(&s->zstream);
2909 if (ret != Z_OK)
2910 return -1;
2911 return 0;
2914 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2916 int ret, clen;
2918 s->zstream.avail_out = len;
2919 s->zstream.next_out = buf;
2920 while (s->zstream.avail_out > 0) {
2921 if (s->zstream.avail_in == 0) {
2922 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
2923 return -1;
2924 clen = qemu_get_be16(s->f);
2925 if (clen > IOBUF_SIZE)
2926 return -1;
2927 qemu_get_buffer(s->f, s->buf, clen);
2928 s->zstream.avail_in = clen;
2929 s->zstream.next_in = s->buf;
2931 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
2932 if (ret != Z_OK && ret != Z_STREAM_END) {
2933 return -1;
2936 return 0;
2939 static void ram_decompress_close(RamDecompressState *s)
2941 inflateEnd(&s->zstream);
2944 #define RAM_SAVE_FLAG_FULL 0x01
2945 #define RAM_SAVE_FLAG_COMPRESS 0x02
2946 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2947 #define RAM_SAVE_FLAG_PAGE 0x08
2948 #define RAM_SAVE_FLAG_EOS 0x10
2950 static int is_dup_page(uint8_t *page, uint8_t ch)
2952 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2953 uint32_t *array = (uint32_t *)page;
2954 int i;
2956 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2957 if (array[i] != val)
2958 return 0;
2961 return 1;
2964 static int ram_save_block(QEMUFile *f)
2966 static ram_addr_t current_addr = 0;
2967 ram_addr_t saved_addr = current_addr;
2968 ram_addr_t addr = 0;
2969 int found = 0;
2971 while (addr < last_ram_offset) {
2972 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2973 uint8_t *p;
2975 cpu_physical_memory_reset_dirty(current_addr,
2976 current_addr + TARGET_PAGE_SIZE,
2977 MIGRATION_DIRTY_FLAG);
2979 p = qemu_get_ram_ptr(current_addr);
2981 if (is_dup_page(p, *p)) {
2982 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2983 qemu_put_byte(f, *p);
2984 } else {
2985 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2986 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2989 found = 1;
2990 break;
2992 addr += TARGET_PAGE_SIZE;
2993 current_addr = (saved_addr + addr) % last_ram_offset;
2996 return found;
2999 static uint64_t bytes_transferred = 0;
3001 static ram_addr_t ram_save_remaining(void)
3003 ram_addr_t addr;
3004 ram_addr_t count = 0;
3006 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3007 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3008 count++;
3011 return count;
3014 uint64_t ram_bytes_remaining(void)
3016 return ram_save_remaining() * TARGET_PAGE_SIZE;
3019 uint64_t ram_bytes_transferred(void)
3021 return bytes_transferred;
3024 uint64_t ram_bytes_total(void)
3026 return last_ram_offset;
3029 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3031 ram_addr_t addr;
3032 uint64_t bytes_transferred_last;
3033 double bwidth = 0;
3034 uint64_t expected_time = 0;
3036 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3037 qemu_file_set_error(f);
3038 return 0;
3041 if (stage == 1) {
3042 /* Make sure all dirty bits are set */
3043 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3044 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3045 cpu_physical_memory_set_dirty(addr);
3048 /* Enable dirty memory tracking */
3049 cpu_physical_memory_set_dirty_tracking(1);
3051 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3054 bytes_transferred_last = bytes_transferred;
3055 bwidth = get_clock();
3057 while (!qemu_file_rate_limit(f)) {
3058 int ret;
3060 ret = ram_save_block(f);
3061 bytes_transferred += ret * TARGET_PAGE_SIZE;
3062 if (ret == 0) /* no more blocks */
3063 break;
3066 bwidth = get_clock() - bwidth;
3067 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3069 /* if we haven't transferred anything this round, force expected_time to a
3070 * a very high value, but without crashing */
3071 if (bwidth == 0)
3072 bwidth = 0.000001;
3074 /* try transferring iterative blocks of memory */
3076 if (stage == 3) {
3078 /* flush all remaining blocks regardless of rate limiting */
3079 while (ram_save_block(f) != 0) {
3080 bytes_transferred += TARGET_PAGE_SIZE;
3082 cpu_physical_memory_set_dirty_tracking(0);
3085 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3087 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3089 return (stage == 2) && (expected_time <= migrate_max_downtime());
3092 static int ram_load_dead(QEMUFile *f, void *opaque)
3094 RamDecompressState s1, *s = &s1;
3095 uint8_t buf[10];
3096 ram_addr_t i;
3098 if (ram_decompress_open(s, f) < 0)
3099 return -EINVAL;
3100 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3101 if (ram_decompress_buf(s, buf, 1) < 0) {
3102 fprintf(stderr, "Error while reading ram block header\n");
3103 goto error;
3105 if (buf[0] == 0) {
3106 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3107 BDRV_HASH_BLOCK_SIZE) < 0) {
3108 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3109 goto error;
3111 } else {
3112 error:
3113 printf("Error block header\n");
3114 return -EINVAL;
3117 ram_decompress_close(s);
3119 return 0;
3122 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3124 ram_addr_t addr;
3125 int flags;
3127 if (version_id == 1)
3128 return ram_load_v1(f, opaque);
3130 if (version_id == 2) {
3131 if (qemu_get_be32(f) != last_ram_offset)
3132 return -EINVAL;
3133 return ram_load_dead(f, opaque);
3136 if (version_id != 3)
3137 return -EINVAL;
3139 do {
3140 addr = qemu_get_be64(f);
3142 flags = addr & ~TARGET_PAGE_MASK;
3143 addr &= TARGET_PAGE_MASK;
3145 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3146 if (addr != last_ram_offset)
3147 return -EINVAL;
3150 if (flags & RAM_SAVE_FLAG_FULL) {
3151 if (ram_load_dead(f, opaque) < 0)
3152 return -EINVAL;
3155 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3156 uint8_t ch = qemu_get_byte(f);
3157 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3158 #ifndef _WIN32
3159 if (ch == 0 &&
3160 (!kvm_enabled() || kvm_has_sync_mmu())) {
3161 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3163 #endif
3164 } else if (flags & RAM_SAVE_FLAG_PAGE)
3165 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3166 } while (!(flags & RAM_SAVE_FLAG_EOS));
3168 return 0;
3171 void qemu_service_io(void)
3173 qemu_notify_event();
3176 /***********************************************************/
3177 /* bottom halves (can be seen as timers which expire ASAP) */
3179 struct QEMUBH {
3180 QEMUBHFunc *cb;
3181 void *opaque;
3182 int scheduled;
3183 int idle;
3184 int deleted;
3185 QEMUBH *next;
3188 static QEMUBH *first_bh = NULL;
3190 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3192 QEMUBH *bh;
3193 bh = qemu_mallocz(sizeof(QEMUBH));
3194 bh->cb = cb;
3195 bh->opaque = opaque;
3196 bh->next = first_bh;
3197 first_bh = bh;
3198 return bh;
3201 int qemu_bh_poll(void)
3203 QEMUBH *bh, **bhp;
3204 int ret;
3206 ret = 0;
3207 for (bh = first_bh; bh; bh = bh->next) {
3208 if (!bh->deleted && bh->scheduled) {
3209 bh->scheduled = 0;
3210 if (!bh->idle)
3211 ret = 1;
3212 bh->idle = 0;
3213 bh->cb(bh->opaque);
3217 /* remove deleted bhs */
3218 bhp = &first_bh;
3219 while (*bhp) {
3220 bh = *bhp;
3221 if (bh->deleted) {
3222 *bhp = bh->next;
3223 qemu_free(bh);
3224 } else
3225 bhp = &bh->next;
3228 return ret;
3231 void qemu_bh_schedule_idle(QEMUBH *bh)
3233 if (bh->scheduled)
3234 return;
3235 bh->scheduled = 1;
3236 bh->idle = 1;
3239 void qemu_bh_schedule(QEMUBH *bh)
3241 if (bh->scheduled)
3242 return;
3243 bh->scheduled = 1;
3244 bh->idle = 0;
3245 /* stop the currently executing CPU to execute the BH ASAP */
3246 qemu_notify_event();
3249 void qemu_bh_cancel(QEMUBH *bh)
3251 bh->scheduled = 0;
3254 void qemu_bh_delete(QEMUBH *bh)
3256 bh->scheduled = 0;
3257 bh->deleted = 1;
3260 static void qemu_bh_update_timeout(int *timeout)
3262 QEMUBH *bh;
3264 for (bh = first_bh; bh; bh = bh->next) {
3265 if (!bh->deleted && bh->scheduled) {
3266 if (bh->idle) {
3267 /* idle bottom halves will be polled at least
3268 * every 10ms */
3269 *timeout = MIN(10, *timeout);
3270 } else {
3271 /* non-idle bottom halves will be executed
3272 * immediately */
3273 *timeout = 0;
3274 break;
3280 /***********************************************************/
3281 /* machine registration */
3283 static QEMUMachine *first_machine = NULL;
3284 QEMUMachine *current_machine = NULL;
3286 int qemu_register_machine(QEMUMachine *m)
3288 QEMUMachine **pm;
3289 pm = &first_machine;
3290 while (*pm != NULL)
3291 pm = &(*pm)->next;
3292 m->next = NULL;
3293 *pm = m;
3294 return 0;
3297 static QEMUMachine *find_machine(const char *name)
3299 QEMUMachine *m;
3301 for(m = first_machine; m != NULL; m = m->next) {
3302 if (!strcmp(m->name, name))
3303 return m;
3304 if (m->alias && !strcmp(m->alias, name))
3305 return m;
3307 return NULL;
3310 static QEMUMachine *find_default_machine(void)
3312 QEMUMachine *m;
3314 for(m = first_machine; m != NULL; m = m->next) {
3315 if (m->is_default) {
3316 return m;
3319 return NULL;
3322 /***********************************************************/
3323 /* main execution loop */
3325 static void gui_update(void *opaque)
3327 uint64_t interval = GUI_REFRESH_INTERVAL;
3328 DisplayState *ds = opaque;
3329 DisplayChangeListener *dcl = ds->listeners;
3331 dpy_refresh(ds);
3333 while (dcl != NULL) {
3334 if (dcl->gui_timer_interval &&
3335 dcl->gui_timer_interval < interval)
3336 interval = dcl->gui_timer_interval;
3337 dcl = dcl->next;
3339 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3342 static void nographic_update(void *opaque)
3344 uint64_t interval = GUI_REFRESH_INTERVAL;
3346 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3349 struct vm_change_state_entry {
3350 VMChangeStateHandler *cb;
3351 void *opaque;
3352 LIST_ENTRY (vm_change_state_entry) entries;
3355 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3357 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3358 void *opaque)
3360 VMChangeStateEntry *e;
3362 e = qemu_mallocz(sizeof (*e));
3364 e->cb = cb;
3365 e->opaque = opaque;
3366 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3367 return e;
3370 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3372 LIST_REMOVE (e, entries);
3373 qemu_free (e);
3376 static void vm_state_notify(int running, int reason)
3378 VMChangeStateEntry *e;
3380 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3381 e->cb(e->opaque, running, reason);
3385 static void resume_all_vcpus(void);
3386 static void pause_all_vcpus(void);
3388 void vm_start(void)
3390 if (!vm_running) {
3391 cpu_enable_ticks();
3392 vm_running = 1;
3393 vm_state_notify(1, 0);
3394 qemu_rearm_alarm_timer(alarm_timer);
3395 resume_all_vcpus();
3399 /* reset/shutdown handler */
3401 typedef struct QEMUResetEntry {
3402 TAILQ_ENTRY(QEMUResetEntry) entry;
3403 QEMUResetHandler *func;
3404 void *opaque;
3405 } QEMUResetEntry;
3407 static TAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3408 TAILQ_HEAD_INITIALIZER(reset_handlers);
3409 static int reset_requested;
3410 static int shutdown_requested;
3411 static int powerdown_requested;
3412 static int debug_requested;
3413 static int vmstop_requested;
3415 int qemu_shutdown_requested(void)
3417 int r = shutdown_requested;
3418 shutdown_requested = 0;
3419 return r;
3422 int qemu_reset_requested(void)
3424 int r = reset_requested;
3425 reset_requested = 0;
3426 return r;
3429 int qemu_powerdown_requested(void)
3431 int r = powerdown_requested;
3432 powerdown_requested = 0;
3433 return r;
3436 static int qemu_debug_requested(void)
3438 int r = debug_requested;
3439 debug_requested = 0;
3440 return r;
3443 static int qemu_vmstop_requested(void)
3445 int r = vmstop_requested;
3446 vmstop_requested = 0;
3447 return r;
3450 static void do_vm_stop(int reason)
3452 if (vm_running) {
3453 cpu_disable_ticks();
3454 vm_running = 0;
3455 pause_all_vcpus();
3456 vm_state_notify(0, reason);
3460 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3462 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3464 re->func = func;
3465 re->opaque = opaque;
3466 TAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3469 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3471 QEMUResetEntry *re;
3473 TAILQ_FOREACH(re, &reset_handlers, entry) {
3474 if (re->func == func && re->opaque == opaque) {
3475 TAILQ_REMOVE(&reset_handlers, re, entry);
3476 qemu_free(re);
3477 return;
3482 void qemu_system_reset(void)
3484 QEMUResetEntry *re, *nre;
3486 /* reset all devices */
3487 TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3488 re->func(re->opaque);
3492 void qemu_system_reset_request(void)
3494 if (no_reboot) {
3495 shutdown_requested = 1;
3496 } else {
3497 reset_requested = 1;
3499 qemu_notify_event();
3502 void qemu_system_shutdown_request(void)
3504 shutdown_requested = 1;
3505 qemu_notify_event();
3508 void qemu_system_powerdown_request(void)
3510 powerdown_requested = 1;
3511 qemu_notify_event();
3514 #ifdef CONFIG_IOTHREAD
3515 static void qemu_system_vmstop_request(int reason)
3517 vmstop_requested = reason;
3518 qemu_notify_event();
3520 #endif
3522 #ifndef _WIN32
3523 static int io_thread_fd = -1;
3525 static void qemu_event_increment(void)
3527 static const char byte = 0;
3529 if (io_thread_fd == -1)
3530 return;
3532 write(io_thread_fd, &byte, sizeof(byte));
3535 static void qemu_event_read(void *opaque)
3537 int fd = (unsigned long)opaque;
3538 ssize_t len;
3540 /* Drain the notify pipe */
3541 do {
3542 char buffer[512];
3543 len = read(fd, buffer, sizeof(buffer));
3544 } while ((len == -1 && errno == EINTR) || len > 0);
3547 static int qemu_event_init(void)
3549 int err;
3550 int fds[2];
3552 err = pipe(fds);
3553 if (err == -1)
3554 return -errno;
3556 err = fcntl_setfl(fds[0], O_NONBLOCK);
3557 if (err < 0)
3558 goto fail;
3560 err = fcntl_setfl(fds[1], O_NONBLOCK);
3561 if (err < 0)
3562 goto fail;
3564 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3565 (void *)(unsigned long)fds[0]);
3567 io_thread_fd = fds[1];
3568 return 0;
3570 fail:
3571 close(fds[0]);
3572 close(fds[1]);
3573 return err;
3575 #else
3576 HANDLE qemu_event_handle;
3578 static void dummy_event_handler(void *opaque)
3582 static int qemu_event_init(void)
3584 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3585 if (!qemu_event_handle) {
3586 perror("Failed CreateEvent");
3587 return -1;
3589 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3590 return 0;
3593 static void qemu_event_increment(void)
3595 SetEvent(qemu_event_handle);
3597 #endif
3599 static int cpu_can_run(CPUState *env)
3601 if (env->stop)
3602 return 0;
3603 if (env->stopped)
3604 return 0;
3605 return 1;
3608 #ifndef CONFIG_IOTHREAD
3609 static int qemu_init_main_loop(void)
3611 return qemu_event_init();
3614 void qemu_init_vcpu(void *_env)
3616 CPUState *env = _env;
3618 if (kvm_enabled())
3619 kvm_init_vcpu(env);
3620 env->nr_cores = smp_cores;
3621 env->nr_threads = smp_threads;
3622 return;
3625 int qemu_cpu_self(void *env)
3627 return 1;
3630 static void resume_all_vcpus(void)
3634 static void pause_all_vcpus(void)
3638 void qemu_cpu_kick(void *env)
3640 return;
3643 void qemu_notify_event(void)
3645 CPUState *env = cpu_single_env;
3647 if (env) {
3648 cpu_exit(env);
3652 #define qemu_mutex_lock_iothread() do { } while (0)
3653 #define qemu_mutex_unlock_iothread() do { } while (0)
3655 void vm_stop(int reason)
3657 do_vm_stop(reason);
3660 #else /* CONFIG_IOTHREAD */
3662 #include "qemu-thread.h"
3664 QemuMutex qemu_global_mutex;
3665 static QemuMutex qemu_fair_mutex;
3667 static QemuThread io_thread;
3669 static QemuThread *tcg_cpu_thread;
3670 static QemuCond *tcg_halt_cond;
3672 static int qemu_system_ready;
3673 /* cpu creation */
3674 static QemuCond qemu_cpu_cond;
3675 /* system init */
3676 static QemuCond qemu_system_cond;
3677 static QemuCond qemu_pause_cond;
3679 static void block_io_signals(void);
3680 static void unblock_io_signals(void);
3681 static int tcg_has_work(void);
3683 static int qemu_init_main_loop(void)
3685 int ret;
3687 ret = qemu_event_init();
3688 if (ret)
3689 return ret;
3691 qemu_cond_init(&qemu_pause_cond);
3692 qemu_mutex_init(&qemu_fair_mutex);
3693 qemu_mutex_init(&qemu_global_mutex);
3694 qemu_mutex_lock(&qemu_global_mutex);
3696 unblock_io_signals();
3697 qemu_thread_self(&io_thread);
3699 return 0;
3702 static void qemu_wait_io_event(CPUState *env)
3704 while (!tcg_has_work())
3705 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3707 qemu_mutex_unlock(&qemu_global_mutex);
3710 * Users of qemu_global_mutex can be starved, having no chance
3711 * to acquire it since this path will get to it first.
3712 * So use another lock to provide fairness.
3714 qemu_mutex_lock(&qemu_fair_mutex);
3715 qemu_mutex_unlock(&qemu_fair_mutex);
3717 qemu_mutex_lock(&qemu_global_mutex);
3718 if (env->stop) {
3719 env->stop = 0;
3720 env->stopped = 1;
3721 qemu_cond_signal(&qemu_pause_cond);
3725 static int qemu_cpu_exec(CPUState *env);
3727 static void *kvm_cpu_thread_fn(void *arg)
3729 CPUState *env = arg;
3731 block_io_signals();
3732 qemu_thread_self(env->thread);
3734 /* signal CPU creation */
3735 qemu_mutex_lock(&qemu_global_mutex);
3736 env->created = 1;
3737 qemu_cond_signal(&qemu_cpu_cond);
3739 /* and wait for machine initialization */
3740 while (!qemu_system_ready)
3741 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3743 while (1) {
3744 if (cpu_can_run(env))
3745 qemu_cpu_exec(env);
3746 qemu_wait_io_event(env);
3749 return NULL;
3752 static void tcg_cpu_exec(void);
3754 static void *tcg_cpu_thread_fn(void *arg)
3756 CPUState *env = arg;
3758 block_io_signals();
3759 qemu_thread_self(env->thread);
3761 /* signal CPU creation */
3762 qemu_mutex_lock(&qemu_global_mutex);
3763 for (env = first_cpu; env != NULL; env = env->next_cpu)
3764 env->created = 1;
3765 qemu_cond_signal(&qemu_cpu_cond);
3767 /* and wait for machine initialization */
3768 while (!qemu_system_ready)
3769 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3771 while (1) {
3772 tcg_cpu_exec();
3773 qemu_wait_io_event(cur_cpu);
3776 return NULL;
3779 void qemu_cpu_kick(void *_env)
3781 CPUState *env = _env;
3782 qemu_cond_broadcast(env->halt_cond);
3783 if (kvm_enabled())
3784 qemu_thread_signal(env->thread, SIGUSR1);
3787 int qemu_cpu_self(void *env)
3789 return (cpu_single_env != NULL);
3792 static void cpu_signal(int sig)
3794 if (cpu_single_env)
3795 cpu_exit(cpu_single_env);
3798 static void block_io_signals(void)
3800 sigset_t set;
3801 struct sigaction sigact;
3803 sigemptyset(&set);
3804 sigaddset(&set, SIGUSR2);
3805 sigaddset(&set, SIGIO);
3806 sigaddset(&set, SIGALRM);
3807 pthread_sigmask(SIG_BLOCK, &set, NULL);
3809 sigemptyset(&set);
3810 sigaddset(&set, SIGUSR1);
3811 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3813 memset(&sigact, 0, sizeof(sigact));
3814 sigact.sa_handler = cpu_signal;
3815 sigaction(SIGUSR1, &sigact, NULL);
3818 static void unblock_io_signals(void)
3820 sigset_t set;
3822 sigemptyset(&set);
3823 sigaddset(&set, SIGUSR2);
3824 sigaddset(&set, SIGIO);
3825 sigaddset(&set, SIGALRM);
3826 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3828 sigemptyset(&set);
3829 sigaddset(&set, SIGUSR1);
3830 pthread_sigmask(SIG_BLOCK, &set, NULL);
3833 static void qemu_signal_lock(unsigned int msecs)
3835 qemu_mutex_lock(&qemu_fair_mutex);
3837 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3838 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3839 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3840 break;
3842 qemu_mutex_unlock(&qemu_fair_mutex);
3845 static void qemu_mutex_lock_iothread(void)
3847 if (kvm_enabled()) {
3848 qemu_mutex_lock(&qemu_fair_mutex);
3849 qemu_mutex_lock(&qemu_global_mutex);
3850 qemu_mutex_unlock(&qemu_fair_mutex);
3851 } else
3852 qemu_signal_lock(100);
3855 static void qemu_mutex_unlock_iothread(void)
3857 qemu_mutex_unlock(&qemu_global_mutex);
3860 static int all_vcpus_paused(void)
3862 CPUState *penv = first_cpu;
3864 while (penv) {
3865 if (!penv->stopped)
3866 return 0;
3867 penv = (CPUState *)penv->next_cpu;
3870 return 1;
3873 static void pause_all_vcpus(void)
3875 CPUState *penv = first_cpu;
3877 while (penv) {
3878 penv->stop = 1;
3879 qemu_thread_signal(penv->thread, SIGUSR1);
3880 qemu_cpu_kick(penv);
3881 penv = (CPUState *)penv->next_cpu;
3884 while (!all_vcpus_paused()) {
3885 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3886 penv = first_cpu;
3887 while (penv) {
3888 qemu_thread_signal(penv->thread, SIGUSR1);
3889 penv = (CPUState *)penv->next_cpu;
3894 static void resume_all_vcpus(void)
3896 CPUState *penv = first_cpu;
3898 while (penv) {
3899 penv->stop = 0;
3900 penv->stopped = 0;
3901 qemu_thread_signal(penv->thread, SIGUSR1);
3902 qemu_cpu_kick(penv);
3903 penv = (CPUState *)penv->next_cpu;
3907 static void tcg_init_vcpu(void *_env)
3909 CPUState *env = _env;
3910 /* share a single thread for all cpus with TCG */
3911 if (!tcg_cpu_thread) {
3912 env->thread = qemu_mallocz(sizeof(QemuThread));
3913 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3914 qemu_cond_init(env->halt_cond);
3915 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3916 while (env->created == 0)
3917 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3918 tcg_cpu_thread = env->thread;
3919 tcg_halt_cond = env->halt_cond;
3920 } else {
3921 env->thread = tcg_cpu_thread;
3922 env->halt_cond = tcg_halt_cond;
3926 static void kvm_start_vcpu(CPUState *env)
3928 kvm_init_vcpu(env);
3929 env->thread = qemu_mallocz(sizeof(QemuThread));
3930 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3931 qemu_cond_init(env->halt_cond);
3932 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3933 while (env->created == 0)
3934 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3937 void qemu_init_vcpu(void *_env)
3939 CPUState *env = _env;
3941 if (kvm_enabled())
3942 kvm_start_vcpu(env);
3943 else
3944 tcg_init_vcpu(env);
3945 env->nr_cores = smp_cores;
3946 env->nr_threads = smp_threads;
3949 void qemu_notify_event(void)
3951 qemu_event_increment();
3954 void vm_stop(int reason)
3956 QemuThread me;
3957 qemu_thread_self(&me);
3959 if (!qemu_thread_equal(&me, &io_thread)) {
3960 qemu_system_vmstop_request(reason);
3962 * FIXME: should not return to device code in case
3963 * vm_stop() has been requested.
3965 if (cpu_single_env) {
3966 cpu_exit(cpu_single_env);
3967 cpu_single_env->stop = 1;
3969 return;
3971 do_vm_stop(reason);
3974 #endif
3977 #ifdef _WIN32
3978 static void host_main_loop_wait(int *timeout)
3980 int ret, ret2, i;
3981 PollingEntry *pe;
3984 /* XXX: need to suppress polling by better using win32 events */
3985 ret = 0;
3986 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3987 ret |= pe->func(pe->opaque);
3989 if (ret == 0) {
3990 int err;
3991 WaitObjects *w = &wait_objects;
3993 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3994 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3995 if (w->func[ret - WAIT_OBJECT_0])
3996 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3998 /* Check for additional signaled events */
3999 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4001 /* Check if event is signaled */
4002 ret2 = WaitForSingleObject(w->events[i], 0);
4003 if(ret2 == WAIT_OBJECT_0) {
4004 if (w->func[i])
4005 w->func[i](w->opaque[i]);
4006 } else if (ret2 == WAIT_TIMEOUT) {
4007 } else {
4008 err = GetLastError();
4009 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4012 } else if (ret == WAIT_TIMEOUT) {
4013 } else {
4014 err = GetLastError();
4015 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4019 *timeout = 0;
4021 #else
4022 static void host_main_loop_wait(int *timeout)
4025 #endif
4027 void main_loop_wait(int timeout)
4029 IOHandlerRecord *ioh;
4030 fd_set rfds, wfds, xfds;
4031 int ret, nfds;
4032 struct timeval tv;
4034 qemu_bh_update_timeout(&timeout);
4036 host_main_loop_wait(&timeout);
4038 /* poll any events */
4039 /* XXX: separate device handlers from system ones */
4040 nfds = -1;
4041 FD_ZERO(&rfds);
4042 FD_ZERO(&wfds);
4043 FD_ZERO(&xfds);
4044 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4045 if (ioh->deleted)
4046 continue;
4047 if (ioh->fd_read &&
4048 (!ioh->fd_read_poll ||
4049 ioh->fd_read_poll(ioh->opaque) != 0)) {
4050 FD_SET(ioh->fd, &rfds);
4051 if (ioh->fd > nfds)
4052 nfds = ioh->fd;
4054 if (ioh->fd_write) {
4055 FD_SET(ioh->fd, &wfds);
4056 if (ioh->fd > nfds)
4057 nfds = ioh->fd;
4061 tv.tv_sec = timeout / 1000;
4062 tv.tv_usec = (timeout % 1000) * 1000;
4064 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4066 qemu_mutex_unlock_iothread();
4067 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4068 qemu_mutex_lock_iothread();
4069 if (ret > 0) {
4070 IOHandlerRecord **pioh;
4072 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4073 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4074 ioh->fd_read(ioh->opaque);
4076 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4077 ioh->fd_write(ioh->opaque);
4081 /* remove deleted IO handlers */
4082 pioh = &first_io_handler;
4083 while (*pioh) {
4084 ioh = *pioh;
4085 if (ioh->deleted) {
4086 *pioh = ioh->next;
4087 qemu_free(ioh);
4088 } else
4089 pioh = &ioh->next;
4093 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4095 /* rearm timer, if not periodic */
4096 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4097 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4098 qemu_rearm_alarm_timer(alarm_timer);
4101 /* vm time timers */
4102 if (vm_running) {
4103 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4104 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4105 qemu_get_clock(vm_clock));
4108 /* real time timers */
4109 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4110 qemu_get_clock(rt_clock));
4112 /* Check bottom-halves last in case any of the earlier events triggered
4113 them. */
4114 qemu_bh_poll();
4118 static int qemu_cpu_exec(CPUState *env)
4120 int ret;
4121 #ifdef CONFIG_PROFILER
4122 int64_t ti;
4123 #endif
4125 #ifdef CONFIG_PROFILER
4126 ti = profile_getclock();
4127 #endif
4128 if (use_icount) {
4129 int64_t count;
4130 int decr;
4131 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4132 env->icount_decr.u16.low = 0;
4133 env->icount_extra = 0;
4134 count = qemu_next_deadline();
4135 count = (count + (1 << icount_time_shift) - 1)
4136 >> icount_time_shift;
4137 qemu_icount += count;
4138 decr = (count > 0xffff) ? 0xffff : count;
4139 count -= decr;
4140 env->icount_decr.u16.low = decr;
4141 env->icount_extra = count;
4143 ret = cpu_exec(env);
4144 #ifdef CONFIG_PROFILER
4145 qemu_time += profile_getclock() - ti;
4146 #endif
4147 if (use_icount) {
4148 /* Fold pending instructions back into the
4149 instruction counter, and clear the interrupt flag. */
4150 qemu_icount -= (env->icount_decr.u16.low
4151 + env->icount_extra);
4152 env->icount_decr.u32 = 0;
4153 env->icount_extra = 0;
4155 return ret;
4158 static void tcg_cpu_exec(void)
4160 int ret = 0;
4162 if (next_cpu == NULL)
4163 next_cpu = first_cpu;
4164 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4165 CPUState *env = cur_cpu = next_cpu;
4167 if (!vm_running)
4168 break;
4169 if (timer_alarm_pending) {
4170 timer_alarm_pending = 0;
4171 break;
4173 if (cpu_can_run(env))
4174 ret = qemu_cpu_exec(env);
4175 if (ret == EXCP_DEBUG) {
4176 gdb_set_stop_cpu(env);
4177 debug_requested = 1;
4178 break;
4183 static int cpu_has_work(CPUState *env)
4185 if (env->stop)
4186 return 1;
4187 if (env->stopped)
4188 return 0;
4189 if (!env->halted)
4190 return 1;
4191 if (qemu_cpu_has_work(env))
4192 return 1;
4193 return 0;
4196 static int tcg_has_work(void)
4198 CPUState *env;
4200 for (env = first_cpu; env != NULL; env = env->next_cpu)
4201 if (cpu_has_work(env))
4202 return 1;
4203 return 0;
4206 static int qemu_calculate_timeout(void)
4208 #ifndef CONFIG_IOTHREAD
4209 int timeout;
4211 if (!vm_running)
4212 timeout = 5000;
4213 else if (tcg_has_work())
4214 timeout = 0;
4215 else if (!use_icount)
4216 timeout = 5000;
4217 else {
4218 /* XXX: use timeout computed from timers */
4219 int64_t add;
4220 int64_t delta;
4221 /* Advance virtual time to the next event. */
4222 if (use_icount == 1) {
4223 /* When not using an adaptive execution frequency
4224 we tend to get badly out of sync with real time,
4225 so just delay for a reasonable amount of time. */
4226 delta = 0;
4227 } else {
4228 delta = cpu_get_icount() - cpu_get_clock();
4230 if (delta > 0) {
4231 /* If virtual time is ahead of real time then just
4232 wait for IO. */
4233 timeout = (delta / 1000000) + 1;
4234 } else {
4235 /* Wait for either IO to occur or the next
4236 timer event. */
4237 add = qemu_next_deadline();
4238 /* We advance the timer before checking for IO.
4239 Limit the amount we advance so that early IO
4240 activity won't get the guest too far ahead. */
4241 if (add > 10000000)
4242 add = 10000000;
4243 delta += add;
4244 add = (add + (1 << icount_time_shift) - 1)
4245 >> icount_time_shift;
4246 qemu_icount += add;
4247 timeout = delta / 1000000;
4248 if (timeout < 0)
4249 timeout = 0;
4253 return timeout;
4254 #else /* CONFIG_IOTHREAD */
4255 return 1000;
4256 #endif
4259 static int vm_can_run(void)
4261 if (powerdown_requested)
4262 return 0;
4263 if (reset_requested)
4264 return 0;
4265 if (shutdown_requested)
4266 return 0;
4267 if (debug_requested)
4268 return 0;
4269 return 1;
4272 qemu_irq qemu_system_powerdown;
4274 static void main_loop(void)
4276 int r;
4278 #ifdef CONFIG_IOTHREAD
4279 qemu_system_ready = 1;
4280 qemu_cond_broadcast(&qemu_system_cond);
4281 #endif
4283 for (;;) {
4284 do {
4285 #ifdef CONFIG_PROFILER
4286 int64_t ti;
4287 #endif
4288 #ifndef CONFIG_IOTHREAD
4289 tcg_cpu_exec();
4290 #endif
4291 #ifdef CONFIG_PROFILER
4292 ti = profile_getclock();
4293 #endif
4294 main_loop_wait(qemu_calculate_timeout());
4295 #ifdef CONFIG_PROFILER
4296 dev_time += profile_getclock() - ti;
4297 #endif
4298 } while (vm_can_run());
4300 if (qemu_debug_requested())
4301 vm_stop(EXCP_DEBUG);
4302 if (qemu_shutdown_requested()) {
4303 if (no_shutdown) {
4304 vm_stop(0);
4305 no_shutdown = 0;
4306 } else
4307 break;
4309 if (qemu_reset_requested()) {
4310 pause_all_vcpus();
4311 qemu_system_reset();
4312 resume_all_vcpus();
4314 if (qemu_powerdown_requested()) {
4315 qemu_irq_raise(qemu_system_powerdown);
4317 if ((r = qemu_vmstop_requested()))
4318 vm_stop(r);
4320 pause_all_vcpus();
4323 static void version(void)
4325 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4328 static void help(int exitcode)
4330 version();
4331 printf("usage: %s [options] [disk_image]\n"
4332 "\n"
4333 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4334 "\n"
4335 #define DEF(option, opt_arg, opt_enum, opt_help) \
4336 opt_help
4337 #define DEFHEADING(text) stringify(text) "\n"
4338 #include "qemu-options.h"
4339 #undef DEF
4340 #undef DEFHEADING
4341 #undef GEN_DOCS
4342 "\n"
4343 "During emulation, the following keys are useful:\n"
4344 "ctrl-alt-f toggle full screen\n"
4345 "ctrl-alt-n switch to virtual console 'n'\n"
4346 "ctrl-alt toggle mouse and keyboard grab\n"
4347 "\n"
4348 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4350 "qemu",
4351 DEFAULT_RAM_SIZE,
4352 #ifndef _WIN32
4353 DEFAULT_NETWORK_SCRIPT,
4354 DEFAULT_NETWORK_DOWN_SCRIPT,
4355 #endif
4356 DEFAULT_GDBSTUB_PORT,
4357 "/tmp/qemu.log");
4358 exit(exitcode);
4361 #define HAS_ARG 0x0001
4363 enum {
4364 #define DEF(option, opt_arg, opt_enum, opt_help) \
4365 opt_enum,
4366 #define DEFHEADING(text)
4367 #include "qemu-options.h"
4368 #undef DEF
4369 #undef DEFHEADING
4370 #undef GEN_DOCS
4373 typedef struct QEMUOption {
4374 const char *name;
4375 int flags;
4376 int index;
4377 } QEMUOption;
4379 static const QEMUOption qemu_options[] = {
4380 { "h", 0, QEMU_OPTION_h },
4381 #define DEF(option, opt_arg, opt_enum, opt_help) \
4382 { option, opt_arg, opt_enum },
4383 #define DEFHEADING(text)
4384 #include "qemu-options.h"
4385 #undef DEF
4386 #undef DEFHEADING
4387 #undef GEN_DOCS
4388 { NULL },
4391 #ifdef HAS_AUDIO
4392 struct soundhw soundhw[] = {
4393 #ifdef HAS_AUDIO_CHOICE
4394 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4396 "pcspk",
4397 "PC speaker",
4400 { .init_isa = pcspk_audio_init }
4402 #endif
4404 #ifdef CONFIG_SB16
4406 "sb16",
4407 "Creative Sound Blaster 16",
4410 { .init_isa = SB16_init }
4412 #endif
4414 #ifdef CONFIG_CS4231A
4416 "cs4231a",
4417 "CS4231A",
4420 { .init_isa = cs4231a_init }
4422 #endif
4424 #ifdef CONFIG_ADLIB
4426 "adlib",
4427 #ifdef HAS_YMF262
4428 "Yamaha YMF262 (OPL3)",
4429 #else
4430 "Yamaha YM3812 (OPL2)",
4431 #endif
4434 { .init_isa = Adlib_init }
4436 #endif
4438 #ifdef CONFIG_GUS
4440 "gus",
4441 "Gravis Ultrasound GF1",
4444 { .init_isa = GUS_init }
4446 #endif
4448 #ifdef CONFIG_AC97
4450 "ac97",
4451 "Intel 82801AA AC97 Audio",
4454 { .init_pci = ac97_init }
4456 #endif
4458 #ifdef CONFIG_ES1370
4460 "es1370",
4461 "ENSONIQ AudioPCI ES1370",
4464 { .init_pci = es1370_init }
4466 #endif
4468 #endif /* HAS_AUDIO_CHOICE */
4470 { NULL, NULL, 0, 0, { NULL } }
4473 static void select_soundhw (const char *optarg)
4475 struct soundhw *c;
4477 if (*optarg == '?') {
4478 show_valid_cards:
4480 printf ("Valid sound card names (comma separated):\n");
4481 for (c = soundhw; c->name; ++c) {
4482 printf ("%-11s %s\n", c->name, c->descr);
4484 printf ("\n-soundhw all will enable all of the above\n");
4485 exit (*optarg != '?');
4487 else {
4488 size_t l;
4489 const char *p;
4490 char *e;
4491 int bad_card = 0;
4493 if (!strcmp (optarg, "all")) {
4494 for (c = soundhw; c->name; ++c) {
4495 c->enabled = 1;
4497 return;
4500 p = optarg;
4501 while (*p) {
4502 e = strchr (p, ',');
4503 l = !e ? strlen (p) : (size_t) (e - p);
4505 for (c = soundhw; c->name; ++c) {
4506 if (!strncmp (c->name, p, l)) {
4507 c->enabled = 1;
4508 break;
4512 if (!c->name) {
4513 if (l > 80) {
4514 fprintf (stderr,
4515 "Unknown sound card name (too big to show)\n");
4517 else {
4518 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4519 (int) l, p);
4521 bad_card = 1;
4523 p += l + (e != NULL);
4526 if (bad_card)
4527 goto show_valid_cards;
4530 #endif
4532 static void select_vgahw (const char *p)
4534 const char *opts;
4536 vga_interface_type = VGA_NONE;
4537 if (strstart(p, "std", &opts)) {
4538 vga_interface_type = VGA_STD;
4539 } else if (strstart(p, "cirrus", &opts)) {
4540 vga_interface_type = VGA_CIRRUS;
4541 } else if (strstart(p, "vmware", &opts)) {
4542 vga_interface_type = VGA_VMWARE;
4543 } else if (strstart(p, "xenfb", &opts)) {
4544 vga_interface_type = VGA_XENFB;
4545 } else if (!strstart(p, "none", &opts)) {
4546 invalid_vga:
4547 fprintf(stderr, "Unknown vga type: %s\n", p);
4548 exit(1);
4550 while (*opts) {
4551 const char *nextopt;
4553 if (strstart(opts, ",retrace=", &nextopt)) {
4554 opts = nextopt;
4555 if (strstart(opts, "dumb", &nextopt))
4556 vga_retrace_method = VGA_RETRACE_DUMB;
4557 else if (strstart(opts, "precise", &nextopt))
4558 vga_retrace_method = VGA_RETRACE_PRECISE;
4559 else goto invalid_vga;
4560 } else goto invalid_vga;
4561 opts = nextopt;
4565 #ifdef TARGET_I386
4566 static int balloon_parse(const char *arg)
4568 char buf[128];
4569 const char *p;
4571 if (!strcmp(arg, "none")) {
4572 virtio_balloon = 0;
4573 } else if (!strncmp(arg, "virtio", 6)) {
4574 virtio_balloon = 1;
4575 if (arg[6] == ',') {
4576 p = arg + 7;
4577 if (get_param_value(buf, sizeof(buf), "addr", p)) {
4578 virtio_balloon_devaddr = strdup(buf);
4581 } else {
4582 return -1;
4584 return 0;
4586 #endif
4588 #ifdef _WIN32
4589 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4591 exit(STATUS_CONTROL_C_EXIT);
4592 return TRUE;
4594 #endif
4596 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4598 int ret;
4600 if(strlen(str) != 36)
4601 return -1;
4603 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4604 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4605 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4607 if(ret != 16)
4608 return -1;
4610 #ifdef TARGET_I386
4611 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4612 #endif
4614 return 0;
4617 #define MAX_NET_CLIENTS 32
4619 #ifndef _WIN32
4621 static void termsig_handler(int signal)
4623 qemu_system_shutdown_request();
4626 static void sigchld_handler(int signal)
4628 waitpid(-1, NULL, WNOHANG);
4631 static void sighandler_setup(void)
4633 struct sigaction act;
4635 memset(&act, 0, sizeof(act));
4636 act.sa_handler = termsig_handler;
4637 sigaction(SIGINT, &act, NULL);
4638 sigaction(SIGHUP, &act, NULL);
4639 sigaction(SIGTERM, &act, NULL);
4641 act.sa_handler = sigchld_handler;
4642 act.sa_flags = SA_NOCLDSTOP;
4643 sigaction(SIGCHLD, &act, NULL);
4646 #endif
4648 #ifdef _WIN32
4649 /* Look for support files in the same directory as the executable. */
4650 static char *find_datadir(const char *argv0)
4652 char *p;
4653 char buf[MAX_PATH];
4654 DWORD len;
4656 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4657 if (len == 0) {
4658 return NULL;
4661 buf[len] = 0;
4662 p = buf + len - 1;
4663 while (p != buf && *p != '\\')
4664 p--;
4665 *p = 0;
4666 if (access(buf, R_OK) == 0) {
4667 return qemu_strdup(buf);
4669 return NULL;
4671 #else /* !_WIN32 */
4673 /* Find a likely location for support files using the location of the binary.
4674 For installed binaries this will be "$bindir/../share/qemu". When
4675 running from the build tree this will be "$bindir/../pc-bios". */
4676 #define SHARE_SUFFIX "/share/qemu"
4677 #define BUILD_SUFFIX "/pc-bios"
4678 static char *find_datadir(const char *argv0)
4680 char *dir;
4681 char *p = NULL;
4682 char *res;
4683 #ifdef PATH_MAX
4684 char buf[PATH_MAX];
4685 #endif
4686 size_t max_len;
4688 #if defined(__linux__)
4690 int len;
4691 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4692 if (len > 0) {
4693 buf[len] = 0;
4694 p = buf;
4697 #elif defined(__FreeBSD__)
4699 int len;
4700 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4701 if (len > 0) {
4702 buf[len] = 0;
4703 p = buf;
4706 #endif
4707 /* If we don't have any way of figuring out the actual executable
4708 location then try argv[0]. */
4709 if (!p) {
4710 #ifdef PATH_MAX
4711 p = buf;
4712 #endif
4713 p = realpath(argv0, p);
4714 if (!p) {
4715 return NULL;
4718 dir = dirname(p);
4719 dir = dirname(dir);
4721 max_len = strlen(dir) +
4722 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4723 res = qemu_mallocz(max_len);
4724 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4725 if (access(res, R_OK)) {
4726 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4727 if (access(res, R_OK)) {
4728 qemu_free(res);
4729 res = NULL;
4732 #ifndef PATH_MAX
4733 free(p);
4734 #endif
4735 return res;
4737 #undef SHARE_SUFFIX
4738 #undef BUILD_SUFFIX
4739 #endif
4741 char *qemu_find_file(int type, const char *name)
4743 int len;
4744 const char *subdir;
4745 char *buf;
4747 /* If name contains path separators then try it as a straight path. */
4748 if ((strchr(name, '/') || strchr(name, '\\'))
4749 && access(name, R_OK) == 0) {
4750 return strdup(name);
4752 switch (type) {
4753 case QEMU_FILE_TYPE_BIOS:
4754 subdir = "";
4755 break;
4756 case QEMU_FILE_TYPE_KEYMAP:
4757 subdir = "keymaps/";
4758 break;
4759 default:
4760 abort();
4762 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4763 buf = qemu_mallocz(len);
4764 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4765 if (access(buf, R_OK)) {
4766 qemu_free(buf);
4767 return NULL;
4769 return buf;
4772 static int device_init_func(QemuOpts *opts, void *opaque)
4774 DeviceState *dev;
4776 dev = qdev_device_add(opts);
4777 if (!dev)
4778 return -1;
4779 return 0;
4782 struct device_config {
4783 enum {
4784 DEV_USB, /* -usbdevice */
4785 DEV_BT, /* -bt */
4786 } type;
4787 const char *cmdline;
4788 TAILQ_ENTRY(device_config) next;
4790 TAILQ_HEAD(, device_config) device_configs = TAILQ_HEAD_INITIALIZER(device_configs);
4792 static void add_device_config(int type, const char *cmdline)
4794 struct device_config *conf;
4796 conf = qemu_mallocz(sizeof(*conf));
4797 conf->type = type;
4798 conf->cmdline = cmdline;
4799 TAILQ_INSERT_TAIL(&device_configs, conf, next);
4802 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4804 struct device_config *conf;
4805 int rc;
4807 TAILQ_FOREACH(conf, &device_configs, next) {
4808 if (conf->type != type)
4809 continue;
4810 rc = func(conf->cmdline);
4811 if (0 != rc)
4812 return rc;
4814 return 0;
4817 int main(int argc, char **argv, char **envp)
4819 const char *gdbstub_dev = NULL;
4820 uint32_t boot_devices_bitmap = 0;
4821 int i;
4822 int snapshot, linux_boot, net_boot;
4823 const char *initrd_filename;
4824 const char *kernel_filename, *kernel_cmdline;
4825 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4826 DisplayState *ds;
4827 DisplayChangeListener *dcl;
4828 int cyls, heads, secs, translation;
4829 const char *net_clients[MAX_NET_CLIENTS];
4830 int nb_net_clients;
4831 QemuOpts *hda_opts = NULL, *opts;
4832 int optind;
4833 const char *r, *optarg;
4834 CharDriverState *monitor_hd = NULL;
4835 const char *monitor_device;
4836 const char *serial_devices[MAX_SERIAL_PORTS];
4837 int serial_device_index;
4838 const char *parallel_devices[MAX_PARALLEL_PORTS];
4839 int parallel_device_index;
4840 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4841 int virtio_console_index;
4842 const char *loadvm = NULL;
4843 QEMUMachine *machine;
4844 const char *cpu_model;
4845 #ifndef _WIN32
4846 int fds[2];
4847 #endif
4848 int tb_size;
4849 const char *pid_file = NULL;
4850 const char *incoming = NULL;
4851 #ifndef _WIN32
4852 int fd = 0;
4853 struct passwd *pwd = NULL;
4854 const char *chroot_dir = NULL;
4855 const char *run_as = NULL;
4856 #endif
4857 CPUState *env;
4858 int show_vnc_port = 0;
4860 qemu_cache_utils_init(envp);
4862 LIST_INIT (&vm_change_state_head);
4863 #ifndef _WIN32
4865 struct sigaction act;
4866 sigfillset(&act.sa_mask);
4867 act.sa_flags = 0;
4868 act.sa_handler = SIG_IGN;
4869 sigaction(SIGPIPE, &act, NULL);
4871 #else
4872 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4873 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4874 QEMU to run on a single CPU */
4876 HANDLE h;
4877 DWORD mask, smask;
4878 int i;
4879 h = GetCurrentProcess();
4880 if (GetProcessAffinityMask(h, &mask, &smask)) {
4881 for(i = 0; i < 32; i++) {
4882 if (mask & (1 << i))
4883 break;
4885 if (i != 32) {
4886 mask = 1 << i;
4887 SetProcessAffinityMask(h, mask);
4891 #endif
4893 module_call_init(MODULE_INIT_MACHINE);
4894 machine = find_default_machine();
4895 cpu_model = NULL;
4896 initrd_filename = NULL;
4897 ram_size = 0;
4898 snapshot = 0;
4899 kernel_filename = NULL;
4900 kernel_cmdline = "";
4901 cyls = heads = secs = 0;
4902 translation = BIOS_ATA_TRANSLATION_AUTO;
4903 monitor_device = "vc:80Cx24C";
4905 serial_devices[0] = "vc:80Cx24C";
4906 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4907 serial_devices[i] = NULL;
4908 serial_device_index = 0;
4910 parallel_devices[0] = "vc:80Cx24C";
4911 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4912 parallel_devices[i] = NULL;
4913 parallel_device_index = 0;
4915 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4916 virtio_consoles[i] = NULL;
4917 virtio_console_index = 0;
4919 for (i = 0; i < MAX_NODES; i++) {
4920 node_mem[i] = 0;
4921 node_cpumask[i] = 0;
4924 nb_net_clients = 0;
4925 nb_numa_nodes = 0;
4926 nb_nics = 0;
4928 tb_size = 0;
4929 autostart= 1;
4931 register_watchdogs();
4933 optind = 1;
4934 for(;;) {
4935 if (optind >= argc)
4936 break;
4937 r = argv[optind];
4938 if (r[0] != '-') {
4939 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4940 } else {
4941 const QEMUOption *popt;
4943 optind++;
4944 /* Treat --foo the same as -foo. */
4945 if (r[1] == '-')
4946 r++;
4947 popt = qemu_options;
4948 for(;;) {
4949 if (!popt->name) {
4950 fprintf(stderr, "%s: invalid option -- '%s'\n",
4951 argv[0], r);
4952 exit(1);
4954 if (!strcmp(popt->name, r + 1))
4955 break;
4956 popt++;
4958 if (popt->flags & HAS_ARG) {
4959 if (optind >= argc) {
4960 fprintf(stderr, "%s: option '%s' requires an argument\n",
4961 argv[0], r);
4962 exit(1);
4964 optarg = argv[optind++];
4965 } else {
4966 optarg = NULL;
4969 switch(popt->index) {
4970 case QEMU_OPTION_M:
4971 machine = find_machine(optarg);
4972 if (!machine) {
4973 QEMUMachine *m;
4974 printf("Supported machines are:\n");
4975 for(m = first_machine; m != NULL; m = m->next) {
4976 if (m->alias)
4977 printf("%-10s %s (alias of %s)\n",
4978 m->alias, m->desc, m->name);
4979 printf("%-10s %s%s\n",
4980 m->name, m->desc,
4981 m->is_default ? " (default)" : "");
4983 exit(*optarg != '?');
4985 break;
4986 case QEMU_OPTION_cpu:
4987 /* hw initialization will check this */
4988 if (*optarg == '?') {
4989 /* XXX: implement xxx_cpu_list for targets that still miss it */
4990 #if defined(cpu_list)
4991 cpu_list(stdout, &fprintf);
4992 #endif
4993 exit(0);
4994 } else {
4995 cpu_model = optarg;
4997 break;
4998 case QEMU_OPTION_initrd:
4999 initrd_filename = optarg;
5000 break;
5001 case QEMU_OPTION_hda:
5002 if (cyls == 0)
5003 hda_opts = drive_add(optarg, HD_ALIAS, 0);
5004 else
5005 hda_opts = drive_add(optarg, HD_ALIAS
5006 ",cyls=%d,heads=%d,secs=%d%s",
5007 0, cyls, heads, secs,
5008 translation == BIOS_ATA_TRANSLATION_LBA ?
5009 ",trans=lba" :
5010 translation == BIOS_ATA_TRANSLATION_NONE ?
5011 ",trans=none" : "");
5012 break;
5013 case QEMU_OPTION_hdb:
5014 case QEMU_OPTION_hdc:
5015 case QEMU_OPTION_hdd:
5016 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5017 break;
5018 case QEMU_OPTION_drive:
5019 drive_add(NULL, "%s", optarg);
5020 break;
5021 case QEMU_OPTION_set:
5022 if (qemu_set_option(optarg) != 0)
5023 exit(1);
5024 break;
5025 case QEMU_OPTION_mtdblock:
5026 drive_add(optarg, MTD_ALIAS);
5027 break;
5028 case QEMU_OPTION_sd:
5029 drive_add(optarg, SD_ALIAS);
5030 break;
5031 case QEMU_OPTION_pflash:
5032 drive_add(optarg, PFLASH_ALIAS);
5033 break;
5034 case QEMU_OPTION_snapshot:
5035 snapshot = 1;
5036 break;
5037 case QEMU_OPTION_hdachs:
5039 const char *p;
5040 p = optarg;
5041 cyls = strtol(p, (char **)&p, 0);
5042 if (cyls < 1 || cyls > 16383)
5043 goto chs_fail;
5044 if (*p != ',')
5045 goto chs_fail;
5046 p++;
5047 heads = strtol(p, (char **)&p, 0);
5048 if (heads < 1 || heads > 16)
5049 goto chs_fail;
5050 if (*p != ',')
5051 goto chs_fail;
5052 p++;
5053 secs = strtol(p, (char **)&p, 0);
5054 if (secs < 1 || secs > 63)
5055 goto chs_fail;
5056 if (*p == ',') {
5057 p++;
5058 if (!strcmp(p, "none"))
5059 translation = BIOS_ATA_TRANSLATION_NONE;
5060 else if (!strcmp(p, "lba"))
5061 translation = BIOS_ATA_TRANSLATION_LBA;
5062 else if (!strcmp(p, "auto"))
5063 translation = BIOS_ATA_TRANSLATION_AUTO;
5064 else
5065 goto chs_fail;
5066 } else if (*p != '\0') {
5067 chs_fail:
5068 fprintf(stderr, "qemu: invalid physical CHS format\n");
5069 exit(1);
5071 if (hda_opts != NULL) {
5072 char num[16];
5073 snprintf(num, sizeof(num), "%d", cyls);
5074 qemu_opt_set(hda_opts, "cyls", num);
5075 snprintf(num, sizeof(num), "%d", heads);
5076 qemu_opt_set(hda_opts, "heads", num);
5077 snprintf(num, sizeof(num), "%d", secs);
5078 qemu_opt_set(hda_opts, "secs", num);
5079 if (translation == BIOS_ATA_TRANSLATION_LBA)
5080 qemu_opt_set(hda_opts, "trans", "lba");
5081 if (translation == BIOS_ATA_TRANSLATION_NONE)
5082 qemu_opt_set(hda_opts, "trans", "none");
5085 break;
5086 case QEMU_OPTION_numa:
5087 if (nb_numa_nodes >= MAX_NODES) {
5088 fprintf(stderr, "qemu: too many NUMA nodes\n");
5089 exit(1);
5091 numa_add(optarg);
5092 break;
5093 case QEMU_OPTION_nographic:
5094 display_type = DT_NOGRAPHIC;
5095 break;
5096 #ifdef CONFIG_CURSES
5097 case QEMU_OPTION_curses:
5098 display_type = DT_CURSES;
5099 break;
5100 #endif
5101 case QEMU_OPTION_portrait:
5102 graphic_rotate = 1;
5103 break;
5104 case QEMU_OPTION_kernel:
5105 kernel_filename = optarg;
5106 break;
5107 case QEMU_OPTION_append:
5108 kernel_cmdline = optarg;
5109 break;
5110 case QEMU_OPTION_cdrom:
5111 drive_add(optarg, CDROM_ALIAS);
5112 break;
5113 case QEMU_OPTION_boot:
5115 static const char * const params[] = {
5116 "order", "once", "menu", NULL
5118 char buf[sizeof(boot_devices)];
5119 char *standard_boot_devices;
5120 int legacy = 0;
5122 if (!strchr(optarg, '=')) {
5123 legacy = 1;
5124 pstrcpy(buf, sizeof(buf), optarg);
5125 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5126 fprintf(stderr,
5127 "qemu: unknown boot parameter '%s' in '%s'\n",
5128 buf, optarg);
5129 exit(1);
5132 if (legacy ||
5133 get_param_value(buf, sizeof(buf), "order", optarg)) {
5134 boot_devices_bitmap = parse_bootdevices(buf);
5135 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5137 if (!legacy) {
5138 if (get_param_value(buf, sizeof(buf),
5139 "once", optarg)) {
5140 boot_devices_bitmap |= parse_bootdevices(buf);
5141 standard_boot_devices = qemu_strdup(boot_devices);
5142 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5143 qemu_register_reset(restore_boot_devices,
5144 standard_boot_devices);
5146 if (get_param_value(buf, sizeof(buf),
5147 "menu", optarg)) {
5148 if (!strcmp(buf, "on")) {
5149 boot_menu = 1;
5150 } else if (!strcmp(buf, "off")) {
5151 boot_menu = 0;
5152 } else {
5153 fprintf(stderr,
5154 "qemu: invalid option value '%s'\n",
5155 buf);
5156 exit(1);
5161 break;
5162 case QEMU_OPTION_fda:
5163 case QEMU_OPTION_fdb:
5164 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5165 break;
5166 #ifdef TARGET_I386
5167 case QEMU_OPTION_no_fd_bootchk:
5168 fd_bootchk = 0;
5169 break;
5170 #endif
5171 case QEMU_OPTION_net:
5172 if (nb_net_clients >= MAX_NET_CLIENTS) {
5173 fprintf(stderr, "qemu: too many network clients\n");
5174 exit(1);
5176 net_clients[nb_net_clients] = optarg;
5177 nb_net_clients++;
5178 break;
5179 #ifdef CONFIG_SLIRP
5180 case QEMU_OPTION_tftp:
5181 legacy_tftp_prefix = optarg;
5182 break;
5183 case QEMU_OPTION_bootp:
5184 legacy_bootp_filename = optarg;
5185 break;
5186 #ifndef _WIN32
5187 case QEMU_OPTION_smb:
5188 net_slirp_smb(optarg);
5189 break;
5190 #endif
5191 case QEMU_OPTION_redir:
5192 net_slirp_redir(optarg);
5193 break;
5194 #endif
5195 case QEMU_OPTION_bt:
5196 add_device_config(DEV_BT, optarg);
5197 break;
5198 #ifdef HAS_AUDIO
5199 case QEMU_OPTION_audio_help:
5200 AUD_help ();
5201 exit (0);
5202 break;
5203 case QEMU_OPTION_soundhw:
5204 select_soundhw (optarg);
5205 break;
5206 #endif
5207 case QEMU_OPTION_h:
5208 help(0);
5209 break;
5210 case QEMU_OPTION_version:
5211 version();
5212 exit(0);
5213 break;
5214 case QEMU_OPTION_m: {
5215 uint64_t value;
5216 char *ptr;
5218 value = strtoul(optarg, &ptr, 10);
5219 switch (*ptr) {
5220 case 0: case 'M': case 'm':
5221 value <<= 20;
5222 break;
5223 case 'G': case 'g':
5224 value <<= 30;
5225 break;
5226 default:
5227 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5228 exit(1);
5231 /* On 32-bit hosts, QEMU is limited by virtual address space */
5232 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5233 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5234 exit(1);
5236 if (value != (uint64_t)(ram_addr_t)value) {
5237 fprintf(stderr, "qemu: ram size too large\n");
5238 exit(1);
5240 ram_size = value;
5241 break;
5243 case QEMU_OPTION_d:
5245 int mask;
5246 const CPULogItem *item;
5248 mask = cpu_str_to_log_mask(optarg);
5249 if (!mask) {
5250 printf("Log items (comma separated):\n");
5251 for(item = cpu_log_items; item->mask != 0; item++) {
5252 printf("%-10s %s\n", item->name, item->help);
5254 exit(1);
5256 cpu_set_log(mask);
5258 break;
5259 case QEMU_OPTION_s:
5260 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5261 break;
5262 case QEMU_OPTION_gdb:
5263 gdbstub_dev = optarg;
5264 break;
5265 case QEMU_OPTION_L:
5266 data_dir = optarg;
5267 break;
5268 case QEMU_OPTION_bios:
5269 bios_name = optarg;
5270 break;
5271 case QEMU_OPTION_singlestep:
5272 singlestep = 1;
5273 break;
5274 case QEMU_OPTION_S:
5275 autostart = 0;
5276 break;
5277 #ifndef _WIN32
5278 case QEMU_OPTION_k:
5279 keyboard_layout = optarg;
5280 break;
5281 #endif
5282 case QEMU_OPTION_localtime:
5283 rtc_utc = 0;
5284 break;
5285 case QEMU_OPTION_vga:
5286 select_vgahw (optarg);
5287 break;
5288 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5289 case QEMU_OPTION_g:
5291 const char *p;
5292 int w, h, depth;
5293 p = optarg;
5294 w = strtol(p, (char **)&p, 10);
5295 if (w <= 0) {
5296 graphic_error:
5297 fprintf(stderr, "qemu: invalid resolution or depth\n");
5298 exit(1);
5300 if (*p != 'x')
5301 goto graphic_error;
5302 p++;
5303 h = strtol(p, (char **)&p, 10);
5304 if (h <= 0)
5305 goto graphic_error;
5306 if (*p == 'x') {
5307 p++;
5308 depth = strtol(p, (char **)&p, 10);
5309 if (depth != 8 && depth != 15 && depth != 16 &&
5310 depth != 24 && depth != 32)
5311 goto graphic_error;
5312 } else if (*p == '\0') {
5313 depth = graphic_depth;
5314 } else {
5315 goto graphic_error;
5318 graphic_width = w;
5319 graphic_height = h;
5320 graphic_depth = depth;
5322 break;
5323 #endif
5324 case QEMU_OPTION_echr:
5326 char *r;
5327 term_escape_char = strtol(optarg, &r, 0);
5328 if (r == optarg)
5329 printf("Bad argument to echr\n");
5330 break;
5332 case QEMU_OPTION_monitor:
5333 monitor_device = optarg;
5334 break;
5335 case QEMU_OPTION_serial:
5336 if (serial_device_index >= MAX_SERIAL_PORTS) {
5337 fprintf(stderr, "qemu: too many serial ports\n");
5338 exit(1);
5340 serial_devices[serial_device_index] = optarg;
5341 serial_device_index++;
5342 break;
5343 case QEMU_OPTION_watchdog:
5344 i = select_watchdog(optarg);
5345 if (i > 0)
5346 exit (i == 1 ? 1 : 0);
5347 break;
5348 case QEMU_OPTION_watchdog_action:
5349 if (select_watchdog_action(optarg) == -1) {
5350 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5351 exit(1);
5353 break;
5354 case QEMU_OPTION_virtiocon:
5355 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5356 fprintf(stderr, "qemu: too many virtio consoles\n");
5357 exit(1);
5359 virtio_consoles[virtio_console_index] = optarg;
5360 virtio_console_index++;
5361 break;
5362 case QEMU_OPTION_parallel:
5363 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5364 fprintf(stderr, "qemu: too many parallel ports\n");
5365 exit(1);
5367 parallel_devices[parallel_device_index] = optarg;
5368 parallel_device_index++;
5369 break;
5370 case QEMU_OPTION_loadvm:
5371 loadvm = optarg;
5372 break;
5373 case QEMU_OPTION_full_screen:
5374 full_screen = 1;
5375 break;
5376 #ifdef CONFIG_SDL
5377 case QEMU_OPTION_no_frame:
5378 no_frame = 1;
5379 break;
5380 case QEMU_OPTION_alt_grab:
5381 alt_grab = 1;
5382 break;
5383 case QEMU_OPTION_no_quit:
5384 no_quit = 1;
5385 break;
5386 case QEMU_OPTION_sdl:
5387 display_type = DT_SDL;
5388 break;
5389 #endif
5390 case QEMU_OPTION_pidfile:
5391 pid_file = optarg;
5392 break;
5393 #ifdef TARGET_I386
5394 case QEMU_OPTION_win2k_hack:
5395 win2k_install_hack = 1;
5396 break;
5397 case QEMU_OPTION_rtc_td_hack:
5398 rtc_td_hack = 1;
5399 break;
5400 case QEMU_OPTION_acpitable:
5401 if(acpi_table_add(optarg) < 0) {
5402 fprintf(stderr, "Wrong acpi table provided\n");
5403 exit(1);
5405 break;
5406 case QEMU_OPTION_smbios:
5407 if(smbios_entry_add(optarg) < 0) {
5408 fprintf(stderr, "Wrong smbios provided\n");
5409 exit(1);
5411 break;
5412 #endif
5413 #ifdef CONFIG_KVM
5414 case QEMU_OPTION_enable_kvm:
5415 kvm_allowed = 1;
5416 break;
5417 #endif
5418 case QEMU_OPTION_usb:
5419 usb_enabled = 1;
5420 break;
5421 case QEMU_OPTION_usbdevice:
5422 usb_enabled = 1;
5423 add_device_config(DEV_USB, optarg);
5424 break;
5425 case QEMU_OPTION_device:
5426 opts = qemu_opts_parse(&qemu_device_opts, optarg, "driver");
5427 if (!opts) {
5428 fprintf(stderr, "parse error: %s\n", optarg);
5429 exit(1);
5431 break;
5432 case QEMU_OPTION_smp:
5433 smp_parse(optarg);
5434 if (smp_cpus < 1) {
5435 fprintf(stderr, "Invalid number of CPUs\n");
5436 exit(1);
5438 if (max_cpus < smp_cpus) {
5439 fprintf(stderr, "maxcpus must be equal to or greater than "
5440 "smp\n");
5441 exit(1);
5443 if (max_cpus > 255) {
5444 fprintf(stderr, "Unsupported number of maxcpus\n");
5445 exit(1);
5447 break;
5448 case QEMU_OPTION_vnc:
5449 display_type = DT_VNC;
5450 vnc_display = optarg;
5451 break;
5452 #ifdef TARGET_I386
5453 case QEMU_OPTION_no_acpi:
5454 acpi_enabled = 0;
5455 break;
5456 case QEMU_OPTION_no_hpet:
5457 no_hpet = 1;
5458 break;
5459 case QEMU_OPTION_balloon:
5460 if (balloon_parse(optarg) < 0) {
5461 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5462 exit(1);
5464 break;
5465 #endif
5466 case QEMU_OPTION_no_reboot:
5467 no_reboot = 1;
5468 break;
5469 case QEMU_OPTION_no_shutdown:
5470 no_shutdown = 1;
5471 break;
5472 case QEMU_OPTION_show_cursor:
5473 cursor_hide = 0;
5474 break;
5475 case QEMU_OPTION_uuid:
5476 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5477 fprintf(stderr, "Fail to parse UUID string."
5478 " Wrong format.\n");
5479 exit(1);
5481 break;
5482 #ifndef _WIN32
5483 case QEMU_OPTION_daemonize:
5484 daemonize = 1;
5485 break;
5486 #endif
5487 case QEMU_OPTION_option_rom:
5488 if (nb_option_roms >= MAX_OPTION_ROMS) {
5489 fprintf(stderr, "Too many option ROMs\n");
5490 exit(1);
5492 option_rom[nb_option_roms] = optarg;
5493 nb_option_roms++;
5494 break;
5495 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5496 case QEMU_OPTION_semihosting:
5497 semihosting_enabled = 1;
5498 break;
5499 #endif
5500 case QEMU_OPTION_name:
5501 qemu_name = qemu_strdup(optarg);
5503 char *p = strchr(qemu_name, ',');
5504 if (p != NULL) {
5505 *p++ = 0;
5506 if (strncmp(p, "process=", 8)) {
5507 fprintf(stderr, "Unknown subargument %s to -name", p);
5508 exit(1);
5510 p += 8;
5511 set_proc_name(p);
5514 break;
5515 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5516 case QEMU_OPTION_prom_env:
5517 if (nb_prom_envs >= MAX_PROM_ENVS) {
5518 fprintf(stderr, "Too many prom variables\n");
5519 exit(1);
5521 prom_envs[nb_prom_envs] = optarg;
5522 nb_prom_envs++;
5523 break;
5524 #endif
5525 #ifdef TARGET_ARM
5526 case QEMU_OPTION_old_param:
5527 old_param = 1;
5528 break;
5529 #endif
5530 case QEMU_OPTION_clock:
5531 configure_alarms(optarg);
5532 break;
5533 case QEMU_OPTION_startdate:
5535 struct tm tm;
5536 time_t rtc_start_date;
5537 if (!strcmp(optarg, "now")) {
5538 rtc_date_offset = -1;
5539 } else {
5540 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5541 &tm.tm_year,
5542 &tm.tm_mon,
5543 &tm.tm_mday,
5544 &tm.tm_hour,
5545 &tm.tm_min,
5546 &tm.tm_sec) == 6) {
5547 /* OK */
5548 } else if (sscanf(optarg, "%d-%d-%d",
5549 &tm.tm_year,
5550 &tm.tm_mon,
5551 &tm.tm_mday) == 3) {
5552 tm.tm_hour = 0;
5553 tm.tm_min = 0;
5554 tm.tm_sec = 0;
5555 } else {
5556 goto date_fail;
5558 tm.tm_year -= 1900;
5559 tm.tm_mon--;
5560 rtc_start_date = mktimegm(&tm);
5561 if (rtc_start_date == -1) {
5562 date_fail:
5563 fprintf(stderr, "Invalid date format. Valid format are:\n"
5564 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5565 exit(1);
5567 rtc_date_offset = time(NULL) - rtc_start_date;
5570 break;
5571 case QEMU_OPTION_tb_size:
5572 tb_size = strtol(optarg, NULL, 0);
5573 if (tb_size < 0)
5574 tb_size = 0;
5575 break;
5576 case QEMU_OPTION_icount:
5577 use_icount = 1;
5578 if (strcmp(optarg, "auto") == 0) {
5579 icount_time_shift = -1;
5580 } else {
5581 icount_time_shift = strtol(optarg, NULL, 0);
5583 break;
5584 case QEMU_OPTION_incoming:
5585 incoming = optarg;
5586 break;
5587 #ifndef _WIN32
5588 case QEMU_OPTION_chroot:
5589 chroot_dir = optarg;
5590 break;
5591 case QEMU_OPTION_runas:
5592 run_as = optarg;
5593 break;
5594 #endif
5595 #ifdef CONFIG_XEN
5596 case QEMU_OPTION_xen_domid:
5597 xen_domid = atoi(optarg);
5598 break;
5599 case QEMU_OPTION_xen_create:
5600 xen_mode = XEN_CREATE;
5601 break;
5602 case QEMU_OPTION_xen_attach:
5603 xen_mode = XEN_ATTACH;
5604 break;
5605 #endif
5610 /* If no data_dir is specified then try to find it relative to the
5611 executable path. */
5612 if (!data_dir) {
5613 data_dir = find_datadir(argv[0]);
5615 /* If all else fails use the install patch specified when building. */
5616 if (!data_dir) {
5617 data_dir = CONFIG_QEMU_SHAREDIR;
5621 * Default to max_cpus = smp_cpus, in case the user doesn't
5622 * specify a max_cpus value.
5624 if (!max_cpus)
5625 max_cpus = smp_cpus;
5627 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5628 if (smp_cpus > machine->max_cpus) {
5629 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5630 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5631 machine->max_cpus);
5632 exit(1);
5635 if (display_type == DT_NOGRAPHIC) {
5636 if (serial_device_index == 0)
5637 serial_devices[0] = "stdio";
5638 if (parallel_device_index == 0)
5639 parallel_devices[0] = "null";
5640 if (strncmp(monitor_device, "vc", 2) == 0)
5641 monitor_device = "stdio";
5644 #ifndef _WIN32
5645 if (daemonize) {
5646 pid_t pid;
5648 if (pipe(fds) == -1)
5649 exit(1);
5651 pid = fork();
5652 if (pid > 0) {
5653 uint8_t status;
5654 ssize_t len;
5656 close(fds[1]);
5658 again:
5659 len = read(fds[0], &status, 1);
5660 if (len == -1 && (errno == EINTR))
5661 goto again;
5663 if (len != 1)
5664 exit(1);
5665 else if (status == 1) {
5666 fprintf(stderr, "Could not acquire pidfile\n");
5667 exit(1);
5668 } else
5669 exit(0);
5670 } else if (pid < 0)
5671 exit(1);
5673 setsid();
5675 pid = fork();
5676 if (pid > 0)
5677 exit(0);
5678 else if (pid < 0)
5679 exit(1);
5681 umask(027);
5683 signal(SIGTSTP, SIG_IGN);
5684 signal(SIGTTOU, SIG_IGN);
5685 signal(SIGTTIN, SIG_IGN);
5688 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5689 if (daemonize) {
5690 uint8_t status = 1;
5691 write(fds[1], &status, 1);
5692 } else
5693 fprintf(stderr, "Could not acquire pid file\n");
5694 exit(1);
5696 #endif
5698 if (qemu_init_main_loop()) {
5699 fprintf(stderr, "qemu_init_main_loop failed\n");
5700 exit(1);
5702 linux_boot = (kernel_filename != NULL);
5704 if (!linux_boot && *kernel_cmdline != '\0') {
5705 fprintf(stderr, "-append only allowed with -kernel option\n");
5706 exit(1);
5709 if (!linux_boot && initrd_filename != NULL) {
5710 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5711 exit(1);
5714 #ifndef _WIN32
5715 /* Win32 doesn't support line-buffering and requires size >= 2 */
5716 setvbuf(stdout, NULL, _IOLBF, 0);
5717 #endif
5719 init_timers();
5720 if (init_timer_alarm() < 0) {
5721 fprintf(stderr, "could not initialize alarm timer\n");
5722 exit(1);
5724 if (use_icount && icount_time_shift < 0) {
5725 use_icount = 2;
5726 /* 125MIPS seems a reasonable initial guess at the guest speed.
5727 It will be corrected fairly quickly anyway. */
5728 icount_time_shift = 3;
5729 init_icount_adjust();
5732 #ifdef _WIN32
5733 socket_init();
5734 #endif
5736 /* init network clients */
5737 if (nb_net_clients == 0) {
5738 /* if no clients, we use a default config */
5739 net_clients[nb_net_clients++] = "nic";
5740 #ifdef CONFIG_SLIRP
5741 net_clients[nb_net_clients++] = "user";
5742 #endif
5745 for(i = 0;i < nb_net_clients; i++) {
5746 if (net_client_parse(net_clients[i]) < 0)
5747 exit(1);
5750 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5751 net_set_boot_mask(net_boot);
5753 net_client_check();
5755 /* init the bluetooth world */
5756 if (foreach_device_config(DEV_BT, bt_parse))
5757 exit(1);
5759 /* init the memory */
5760 if (ram_size == 0)
5761 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5763 /* init the dynamic translator */
5764 cpu_exec_init_all(tb_size * 1024 * 1024);
5766 bdrv_init();
5768 /* we always create the cdrom drive, even if no disk is there */
5769 drive_add(NULL, CDROM_ALIAS);
5771 /* we always create at least one floppy */
5772 drive_add(NULL, FD_ALIAS, 0);
5774 /* we always create one sd slot, even if no card is in it */
5775 drive_add(NULL, SD_ALIAS);
5777 /* open the virtual block devices */
5778 if (snapshot)
5779 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5780 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5781 exit(1);
5783 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5784 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5786 #ifndef _WIN32
5787 /* must be after terminal init, SDL library changes signal handlers */
5788 sighandler_setup();
5789 #endif
5791 /* Maintain compatibility with multiple stdio monitors */
5792 if (!strcmp(monitor_device,"stdio")) {
5793 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5794 const char *devname = serial_devices[i];
5795 if (devname && !strcmp(devname,"mon:stdio")) {
5796 monitor_device = NULL;
5797 break;
5798 } else if (devname && !strcmp(devname,"stdio")) {
5799 monitor_device = NULL;
5800 serial_devices[i] = "mon:stdio";
5801 break;
5806 if (nb_numa_nodes > 0) {
5807 int i;
5809 if (nb_numa_nodes > smp_cpus) {
5810 nb_numa_nodes = smp_cpus;
5813 /* If no memory size if given for any node, assume the default case
5814 * and distribute the available memory equally across all nodes
5816 for (i = 0; i < nb_numa_nodes; i++) {
5817 if (node_mem[i] != 0)
5818 break;
5820 if (i == nb_numa_nodes) {
5821 uint64_t usedmem = 0;
5823 /* On Linux, the each node's border has to be 8MB aligned,
5824 * the final node gets the rest.
5826 for (i = 0; i < nb_numa_nodes - 1; i++) {
5827 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5828 usedmem += node_mem[i];
5830 node_mem[i] = ram_size - usedmem;
5833 for (i = 0; i < nb_numa_nodes; i++) {
5834 if (node_cpumask[i] != 0)
5835 break;
5837 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5838 * must cope with this anyway, because there are BIOSes out there in
5839 * real machines which also use this scheme.
5841 if (i == nb_numa_nodes) {
5842 for (i = 0; i < smp_cpus; i++) {
5843 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5848 if (kvm_enabled()) {
5849 int ret;
5851 ret = kvm_init(smp_cpus);
5852 if (ret < 0) {
5853 fprintf(stderr, "failed to initialize KVM\n");
5854 exit(1);
5858 if (monitor_device) {
5859 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5860 if (!monitor_hd) {
5861 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5862 exit(1);
5866 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5867 const char *devname = serial_devices[i];
5868 if (devname && strcmp(devname, "none")) {
5869 char label[32];
5870 snprintf(label, sizeof(label), "serial%d", i);
5871 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5872 if (!serial_hds[i]) {
5873 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5874 devname);
5875 exit(1);
5880 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5881 const char *devname = parallel_devices[i];
5882 if (devname && strcmp(devname, "none")) {
5883 char label[32];
5884 snprintf(label, sizeof(label), "parallel%d", i);
5885 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5886 if (!parallel_hds[i]) {
5887 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5888 devname);
5889 exit(1);
5894 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5895 const char *devname = virtio_consoles[i];
5896 if (devname && strcmp(devname, "none")) {
5897 char label[32];
5898 snprintf(label, sizeof(label), "virtcon%d", i);
5899 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5900 if (!virtcon_hds[i]) {
5901 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5902 devname);
5903 exit(1);
5908 module_call_init(MODULE_INIT_DEVICE);
5910 if (machine->compat_props) {
5911 qdev_prop_register_compat(machine->compat_props);
5913 machine->init(ram_size, boot_devices,
5914 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5917 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5918 for (i = 0; i < nb_numa_nodes; i++) {
5919 if (node_cpumask[i] & (1 << env->cpu_index)) {
5920 env->numa_node = i;
5925 current_machine = machine;
5927 /* init USB devices */
5928 if (usb_enabled) {
5929 foreach_device_config(DEV_USB, usb_parse);
5932 /* init generic devices */
5933 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5934 exit(1);
5936 if (!display_state)
5937 dumb_display_init();
5938 /* just use the first displaystate for the moment */
5939 ds = display_state;
5941 if (display_type == DT_DEFAULT) {
5942 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5943 display_type = DT_SDL;
5944 #else
5945 display_type = DT_VNC;
5946 vnc_display = "localhost:0,to=99";
5947 show_vnc_port = 1;
5948 #endif
5952 switch (display_type) {
5953 case DT_NOGRAPHIC:
5954 break;
5955 #if defined(CONFIG_CURSES)
5956 case DT_CURSES:
5957 curses_display_init(ds, full_screen);
5958 break;
5959 #endif
5960 #if defined(CONFIG_SDL)
5961 case DT_SDL:
5962 sdl_display_init(ds, full_screen, no_frame);
5963 break;
5964 #elif defined(CONFIG_COCOA)
5965 case DT_SDL:
5966 cocoa_display_init(ds, full_screen);
5967 break;
5968 #endif
5969 case DT_VNC:
5970 vnc_display_init(ds);
5971 if (vnc_display_open(ds, vnc_display) < 0)
5972 exit(1);
5974 if (show_vnc_port) {
5975 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5977 break;
5978 default:
5979 break;
5981 dpy_resize(ds);
5983 dcl = ds->listeners;
5984 while (dcl != NULL) {
5985 if (dcl->dpy_refresh != NULL) {
5986 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5987 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5989 dcl = dcl->next;
5992 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5993 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5994 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5997 text_consoles_set_display(display_state);
5998 qemu_chr_initial_reset();
6000 if (monitor_device && monitor_hd)
6001 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6003 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6004 const char *devname = serial_devices[i];
6005 if (devname && strcmp(devname, "none")) {
6006 if (strstart(devname, "vc", 0))
6007 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6011 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6012 const char *devname = parallel_devices[i];
6013 if (devname && strcmp(devname, "none")) {
6014 if (strstart(devname, "vc", 0))
6015 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6019 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6020 const char *devname = virtio_consoles[i];
6021 if (virtcon_hds[i] && devname) {
6022 if (strstart(devname, "vc", 0))
6023 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6027 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6028 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6029 gdbstub_dev);
6030 exit(1);
6033 if (loadvm)
6034 do_loadvm(cur_mon, loadvm);
6036 if (incoming) {
6037 qemu_start_incoming_migration(incoming);
6038 } else if (autostart) {
6039 vm_start();
6042 #ifndef _WIN32
6043 if (daemonize) {
6044 uint8_t status = 0;
6045 ssize_t len;
6047 again1:
6048 len = write(fds[1], &status, 1);
6049 if (len == -1 && (errno == EINTR))
6050 goto again1;
6052 if (len != 1)
6053 exit(1);
6055 chdir("/");
6056 TFR(fd = open("/dev/null", O_RDWR));
6057 if (fd == -1)
6058 exit(1);
6061 if (run_as) {
6062 pwd = getpwnam(run_as);
6063 if (!pwd) {
6064 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6065 exit(1);
6069 if (chroot_dir) {
6070 if (chroot(chroot_dir) < 0) {
6071 fprintf(stderr, "chroot failed\n");
6072 exit(1);
6074 chdir("/");
6077 if (run_as) {
6078 if (setgid(pwd->pw_gid) < 0) {
6079 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6080 exit(1);
6082 if (setuid(pwd->pw_uid) < 0) {
6083 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6084 exit(1);
6086 if (setuid(0) != -1) {
6087 fprintf(stderr, "Dropping privileges failed\n");
6088 exit(1);
6092 if (daemonize) {
6093 dup2(fd, 0);
6094 dup2(fd, 1);
6095 dup2(fd, 2);
6097 close(fd);
6099 #endif
6101 main_loop();
6102 quit_timers();
6103 net_cleanup();
6105 return 0;