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
32 /* Needed early for HOST_BSD etc. */
33 #include "config-host.h"
37 #include <sys/times.h>
41 #include <sys/ioctl.h>
42 #include <sys/resource.h>
43 #include <sys/socket.h>
44 #include <netinet/in.h>
46 #if defined(__NetBSD__)
47 #include <net/if_tap.h>
50 #include <linux/if_tun.h>
52 #include <arpa/inet.h>
55 #include <sys/select.h>
58 #if defined(__FreeBSD__) || defined(__DragonFly__)
63 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
64 #include <freebsd/stdlib.h>
69 #include <linux/rtc.h>
71 /* For the benefit of older linux systems which don't supply it,
72 we use a local copy of hpet.h. */
73 /* #include <linux/hpet.h> */
76 #include <linux/ppdev.h>
77 #include <linux/parport.h>
81 #include <sys/ethernet.h>
82 #include <sys/sockio.h>
83 #include <netinet/arp.h>
84 #include <netinet/in.h>
85 #include <netinet/in_systm.h>
86 #include <netinet/ip.h>
87 #include <netinet/ip_icmp.h> // must come after ip.h
88 #include <netinet/udp.h>
89 #include <netinet/tcp.h>
97 #if defined(__OpenBSD__)
101 #if defined(CONFIG_VDE)
102 #include <libvdeplug.h>
108 #include <sys/timeb.h>
109 #include <mmsystem.h>
110 #define getopt_long_only getopt_long
111 #define memalign(align, size) malloc(size)
117 int qemu_main(int argc, char **argv, char **envp);
118 int main(int argc, char **argv)
120 qemu_main(argc, argv, NULL);
123 #define main qemu_main
125 #endif /* CONFIG_SDL */
129 #define main qemu_main
130 #endif /* CONFIG_COCOA */
133 #include "hw/boards.h"
135 #include "hw/pcmcia.h"
137 #include "hw/audiodev.h"
141 #include "hw/smbios.h"
149 #include "qemu-timer.h"
150 #include "qemu-char.h"
151 #include "cache-utils.h"
154 #include "audio/audio.h"
155 #include "migration.h"
161 #include "exec-all.h"
163 #include "qemu_socket.h"
165 #if defined(CONFIG_SLIRP)
166 #include "libslirp.h"
169 //#define DEBUG_UNUSED_IOPORT
170 //#define DEBUG_IOPORT
172 //#define DEBUG_SLIRP
176 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
178 # define LOG_IOPORT(...) do { } while (0)
181 #define DEFAULT_RAM_SIZE 128
183 /* Max number of USB devices that can be specified on the commandline. */
184 #define MAX_USB_CMDLINE 8
186 /* Max number of bluetooth switches on the commandline. */
187 #define MAX_BT_CMDLINE 10
189 /* XXX: use a two level table to limit memory usage */
190 #define MAX_IOPORTS 65536
192 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
193 const char *bios_name = NULL;
194 static void *ioport_opaque[MAX_IOPORTS];
195 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
196 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
197 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
198 to store the VM snapshots */
199 DriveInfo drives_table[MAX_DRIVES+1];
201 static int vga_ram_size;
202 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
203 static DisplayState *display_state;
207 const char* keyboard_layout = NULL;
208 int64_t ticks_per_sec;
211 NICInfo nd_table[MAX_NICS];
213 static int autostart;
214 static int rtc_utc = 1;
215 static int rtc_date_offset = -1; /* -1 means no change */
216 int cirrus_vga_enabled = 1;
217 int std_vga_enabled = 0;
218 int vmsvga_enabled = 0;
220 int graphic_width = 1024;
221 int graphic_height = 768;
222 int graphic_depth = 8;
224 int graphic_width = 800;
225 int graphic_height = 600;
226 int graphic_depth = 15;
228 static int full_screen = 0;
230 static int no_frame = 0;
233 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
234 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
235 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
237 int win2k_install_hack = 0;
243 const char *vnc_display;
244 int acpi_enabled = 1;
250 int graphic_rotate = 0;
254 const char *option_rom[MAX_OPTION_ROMS];
256 int semihosting_enabled = 0;
260 const char *qemu_name;
262 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
263 unsigned int nb_prom_envs = 0;
264 const char *prom_envs[MAX_PROM_ENVS];
267 struct drive_opt drives_opt[MAX_DRIVES];
270 uint64_t node_mem[MAX_NODES];
271 uint64_t node_cpumask[MAX_NODES];
273 static CPUState *cur_cpu;
274 static CPUState *next_cpu;
275 static int event_pending = 1;
276 /* Conversion factor from emulated instructions to virtual clock ticks. */
277 static int icount_time_shift;
278 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
279 #define MAX_ICOUNT_SHIFT 10
280 /* Compensate for varying guest execution speed. */
281 static int64_t qemu_icount_bias;
282 static QEMUTimer *icount_rt_timer;
283 static QEMUTimer *icount_vm_timer;
284 static QEMUTimer *nographic_timer;
286 uint8_t qemu_uuid[16];
288 /***********************************************************/
289 /* x86 ISA bus support */
291 target_phys_addr_t isa_mem_base = 0;
294 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
295 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
297 static uint32_t ioport_read(int index, uint32_t address)
299 static IOPortReadFunc *default_func[3] = {
300 default_ioport_readb,
301 default_ioport_readw,
304 IOPortReadFunc *func = ioport_read_table[index][address];
306 func = default_func[index];
307 return func(ioport_opaque[address], address);
310 static void ioport_write(int index, uint32_t address, uint32_t data)
312 static IOPortWriteFunc *default_func[3] = {
313 default_ioport_writeb,
314 default_ioport_writew,
315 default_ioport_writel
317 IOPortWriteFunc *func = ioport_write_table[index][address];
319 func = default_func[index];
320 func(ioport_opaque[address], address, data);
323 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
325 #ifdef DEBUG_UNUSED_IOPORT
326 fprintf(stderr, "unused inb: port=0x%04x\n", address);
331 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
333 #ifdef DEBUG_UNUSED_IOPORT
334 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
338 /* default is to make two byte accesses */
339 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
342 data = ioport_read(0, address);
343 address = (address + 1) & (MAX_IOPORTS - 1);
344 data |= ioport_read(0, address) << 8;
348 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
350 ioport_write(0, address, data & 0xff);
351 address = (address + 1) & (MAX_IOPORTS - 1);
352 ioport_write(0, address, (data >> 8) & 0xff);
355 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
357 #ifdef DEBUG_UNUSED_IOPORT
358 fprintf(stderr, "unused inl: port=0x%04x\n", address);
363 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
365 #ifdef DEBUG_UNUSED_IOPORT
366 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
370 /* size is the word size in byte */
371 int register_ioport_read(int start, int length, int size,
372 IOPortReadFunc *func, void *opaque)
378 } else if (size == 2) {
380 } else if (size == 4) {
383 hw_error("register_ioport_read: invalid size");
386 for(i = start; i < start + length; i += size) {
387 ioport_read_table[bsize][i] = func;
388 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
389 hw_error("register_ioport_read: invalid opaque");
390 ioport_opaque[i] = opaque;
395 /* size is the word size in byte */
396 int register_ioport_write(int start, int length, int size,
397 IOPortWriteFunc *func, void *opaque)
403 } else if (size == 2) {
405 } else if (size == 4) {
408 hw_error("register_ioport_write: invalid size");
411 for(i = start; i < start + length; i += size) {
412 ioport_write_table[bsize][i] = func;
413 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
414 hw_error("register_ioport_write: invalid opaque");
415 ioport_opaque[i] = opaque;
420 void isa_unassign_ioport(int start, int length)
424 for(i = start; i < start + length; i++) {
425 ioport_read_table[0][i] = default_ioport_readb;
426 ioport_read_table[1][i] = default_ioport_readw;
427 ioport_read_table[2][i] = default_ioport_readl;
429 ioport_write_table[0][i] = default_ioport_writeb;
430 ioport_write_table[1][i] = default_ioport_writew;
431 ioport_write_table[2][i] = default_ioport_writel;
433 ioport_opaque[i] = NULL;
437 /***********************************************************/
439 void cpu_outb(CPUState *env, int addr, int val)
441 LOG_IOPORT("outb: %04x %02x\n", addr, val);
442 ioport_write(0, addr, val);
445 env->last_io_time = cpu_get_time_fast();
449 void cpu_outw(CPUState *env, int addr, int val)
451 LOG_IOPORT("outw: %04x %04x\n", addr, val);
452 ioport_write(1, addr, val);
455 env->last_io_time = cpu_get_time_fast();
459 void cpu_outl(CPUState *env, int addr, int val)
461 LOG_IOPORT("outl: %04x %08x\n", addr, val);
462 ioport_write(2, addr, val);
465 env->last_io_time = cpu_get_time_fast();
469 int cpu_inb(CPUState *env, int addr)
472 val = ioport_read(0, addr);
473 LOG_IOPORT("inb : %04x %02x\n", addr, val);
476 env->last_io_time = cpu_get_time_fast();
481 int cpu_inw(CPUState *env, int addr)
484 val = ioport_read(1, addr);
485 LOG_IOPORT("inw : %04x %04x\n", addr, val);
488 env->last_io_time = cpu_get_time_fast();
493 int cpu_inl(CPUState *env, int addr)
496 val = ioport_read(2, addr);
497 LOG_IOPORT("inl : %04x %08x\n", addr, val);
500 env->last_io_time = cpu_get_time_fast();
505 /***********************************************************/
506 void hw_error(const char *fmt, ...)
512 fprintf(stderr, "qemu: hardware error: ");
513 vfprintf(stderr, fmt, ap);
514 fprintf(stderr, "\n");
515 for(env = first_cpu; env != NULL; env = env->next_cpu) {
516 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
518 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
520 cpu_dump_state(env, stderr, fprintf, 0);
530 static QEMUBalloonEvent *qemu_balloon_event;
531 void *qemu_balloon_event_opaque;
533 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
535 qemu_balloon_event = func;
536 qemu_balloon_event_opaque = opaque;
539 void qemu_balloon(ram_addr_t target)
541 if (qemu_balloon_event)
542 qemu_balloon_event(qemu_balloon_event_opaque, target);
545 ram_addr_t qemu_balloon_status(void)
547 if (qemu_balloon_event)
548 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
552 /***********************************************************/
555 static QEMUPutKBDEvent *qemu_put_kbd_event;
556 static void *qemu_put_kbd_event_opaque;
557 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
558 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
560 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
562 qemu_put_kbd_event_opaque = opaque;
563 qemu_put_kbd_event = func;
566 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
567 void *opaque, int absolute,
570 QEMUPutMouseEntry *s, *cursor;
572 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
574 s->qemu_put_mouse_event = func;
575 s->qemu_put_mouse_event_opaque = opaque;
576 s->qemu_put_mouse_event_absolute = absolute;
577 s->qemu_put_mouse_event_name = qemu_strdup(name);
580 if (!qemu_put_mouse_event_head) {
581 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
585 cursor = qemu_put_mouse_event_head;
586 while (cursor->next != NULL)
587 cursor = cursor->next;
590 qemu_put_mouse_event_current = s;
595 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
597 QEMUPutMouseEntry *prev = NULL, *cursor;
599 if (!qemu_put_mouse_event_head || entry == NULL)
602 cursor = qemu_put_mouse_event_head;
603 while (cursor != NULL && cursor != entry) {
605 cursor = cursor->next;
608 if (cursor == NULL) // does not exist or list empty
610 else if (prev == NULL) { // entry is head
611 qemu_put_mouse_event_head = cursor->next;
612 if (qemu_put_mouse_event_current == entry)
613 qemu_put_mouse_event_current = cursor->next;
614 qemu_free(entry->qemu_put_mouse_event_name);
619 prev->next = entry->next;
621 if (qemu_put_mouse_event_current == entry)
622 qemu_put_mouse_event_current = prev;
624 qemu_free(entry->qemu_put_mouse_event_name);
628 void kbd_put_keycode(int keycode)
630 if (qemu_put_kbd_event) {
631 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
635 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
637 QEMUPutMouseEvent *mouse_event;
638 void *mouse_event_opaque;
641 if (!qemu_put_mouse_event_current) {
646 qemu_put_mouse_event_current->qemu_put_mouse_event;
648 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
651 if (graphic_rotate) {
652 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
655 width = graphic_width - 1;
656 mouse_event(mouse_event_opaque,
657 width - dy, dx, dz, buttons_state);
659 mouse_event(mouse_event_opaque,
660 dx, dy, dz, buttons_state);
664 int kbd_mouse_is_absolute(void)
666 if (!qemu_put_mouse_event_current)
669 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
672 void do_info_mice(Monitor *mon)
674 QEMUPutMouseEntry *cursor;
677 if (!qemu_put_mouse_event_head) {
678 monitor_printf(mon, "No mouse devices connected\n");
682 monitor_printf(mon, "Mouse devices available:\n");
683 cursor = qemu_put_mouse_event_head;
684 while (cursor != NULL) {
685 monitor_printf(mon, "%c Mouse #%d: %s\n",
686 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
687 index, cursor->qemu_put_mouse_event_name);
689 cursor = cursor->next;
693 void do_mouse_set(Monitor *mon, int index)
695 QEMUPutMouseEntry *cursor;
698 if (!qemu_put_mouse_event_head) {
699 monitor_printf(mon, "No mouse devices connected\n");
703 cursor = qemu_put_mouse_event_head;
704 while (cursor != NULL && index != i) {
706 cursor = cursor->next;
710 qemu_put_mouse_event_current = cursor;
712 monitor_printf(mon, "Mouse at given index not found\n");
715 /* compute with 96 bit intermediate result: (a*b)/c */
716 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
721 #ifdef WORDS_BIGENDIAN
731 rl = (uint64_t)u.l.low * (uint64_t)b;
732 rh = (uint64_t)u.l.high * (uint64_t)b;
735 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
739 /***********************************************************/
740 /* real time host monotonic timer */
742 #define QEMU_TIMER_BASE 1000000000LL
746 static int64_t clock_freq;
748 static void init_get_clock(void)
752 ret = QueryPerformanceFrequency(&freq);
754 fprintf(stderr, "Could not calibrate ticks\n");
757 clock_freq = freq.QuadPart;
760 static int64_t get_clock(void)
763 QueryPerformanceCounter(&ti);
764 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
769 static int use_rt_clock;
771 static void init_get_clock(void)
774 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
775 || defined(__DragonFly__)
778 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
785 static int64_t get_clock(void)
787 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
788 || defined(__DragonFly__)
791 clock_gettime(CLOCK_MONOTONIC, &ts);
792 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
796 /* XXX: using gettimeofday leads to problems if the date
797 changes, so it should be avoided. */
799 gettimeofday(&tv, NULL);
800 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
805 /* Return the virtual CPU time, based on the instruction counter. */
806 static int64_t cpu_get_icount(void)
809 CPUState *env = cpu_single_env;;
810 icount = qemu_icount;
813 fprintf(stderr, "Bad clock read\n");
814 icount -= (env->icount_decr.u16.low + env->icount_extra);
816 return qemu_icount_bias + (icount << icount_time_shift);
819 /***********************************************************/
820 /* guest cycle counter */
822 static int64_t cpu_ticks_prev;
823 static int64_t cpu_ticks_offset;
824 static int64_t cpu_clock_offset;
825 static int cpu_ticks_enabled;
827 /* return the host CPU cycle counter and handle stop/restart */
828 int64_t cpu_get_ticks(void)
831 return cpu_get_icount();
833 if (!cpu_ticks_enabled) {
834 return cpu_ticks_offset;
837 ticks = cpu_get_real_ticks();
838 if (cpu_ticks_prev > ticks) {
839 /* Note: non increasing ticks may happen if the host uses
841 cpu_ticks_offset += cpu_ticks_prev - ticks;
843 cpu_ticks_prev = ticks;
844 return ticks + cpu_ticks_offset;
848 /* return the host CPU monotonic timer and handle stop/restart */
849 static int64_t cpu_get_clock(void)
852 if (!cpu_ticks_enabled) {
853 return cpu_clock_offset;
856 return ti + cpu_clock_offset;
860 /* enable cpu_get_ticks() */
861 void cpu_enable_ticks(void)
863 if (!cpu_ticks_enabled) {
864 cpu_ticks_offset -= cpu_get_real_ticks();
865 cpu_clock_offset -= get_clock();
866 cpu_ticks_enabled = 1;
870 /* disable cpu_get_ticks() : the clock is stopped. You must not call
871 cpu_get_ticks() after that. */
872 void cpu_disable_ticks(void)
874 if (cpu_ticks_enabled) {
875 cpu_ticks_offset = cpu_get_ticks();
876 cpu_clock_offset = cpu_get_clock();
877 cpu_ticks_enabled = 0;
881 /***********************************************************/
884 #define QEMU_TIMER_REALTIME 0
885 #define QEMU_TIMER_VIRTUAL 1
889 /* XXX: add frequency */
897 struct QEMUTimer *next;
900 struct qemu_alarm_timer {
904 int (*start)(struct qemu_alarm_timer *t);
905 void (*stop)(struct qemu_alarm_timer *t);
906 void (*rearm)(struct qemu_alarm_timer *t);
910 #define ALARM_FLAG_DYNTICKS 0x1
911 #define ALARM_FLAG_EXPIRED 0x2
913 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
915 return t->flags & ALARM_FLAG_DYNTICKS;
918 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
920 if (!alarm_has_dynticks(t))
926 /* TODO: MIN_TIMER_REARM_US should be optimized */
927 #define MIN_TIMER_REARM_US 250
929 static struct qemu_alarm_timer *alarm_timer;
931 static int alarm_timer_rfd, alarm_timer_wfd;
936 struct qemu_alarm_win32 {
940 } alarm_win32_data = {0, NULL, -1};
942 static int win32_start_timer(struct qemu_alarm_timer *t);
943 static void win32_stop_timer(struct qemu_alarm_timer *t);
944 static void win32_rearm_timer(struct qemu_alarm_timer *t);
948 static int unix_start_timer(struct qemu_alarm_timer *t);
949 static void unix_stop_timer(struct qemu_alarm_timer *t);
953 static int dynticks_start_timer(struct qemu_alarm_timer *t);
954 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
955 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
957 static int hpet_start_timer(struct qemu_alarm_timer *t);
958 static void hpet_stop_timer(struct qemu_alarm_timer *t);
960 static int rtc_start_timer(struct qemu_alarm_timer *t);
961 static void rtc_stop_timer(struct qemu_alarm_timer *t);
963 #endif /* __linux__ */
967 /* Correlation between real and virtual time is always going to be
968 fairly approximate, so ignore small variation.
969 When the guest is idle real and virtual time will be aligned in
971 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
973 static void icount_adjust(void)
978 static int64_t last_delta;
979 /* If the VM is not running, then do nothing. */
983 cur_time = cpu_get_clock();
984 cur_icount = qemu_get_clock(vm_clock);
985 delta = cur_icount - cur_time;
986 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
988 && last_delta + ICOUNT_WOBBLE < delta * 2
989 && icount_time_shift > 0) {
990 /* The guest is getting too far ahead. Slow time down. */
994 && last_delta - ICOUNT_WOBBLE > delta * 2
995 && icount_time_shift < MAX_ICOUNT_SHIFT) {
996 /* The guest is getting too far behind. Speed time up. */
1000 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1003 static void icount_adjust_rt(void * opaque)
1005 qemu_mod_timer(icount_rt_timer,
1006 qemu_get_clock(rt_clock) + 1000);
1010 static void icount_adjust_vm(void * opaque)
1012 qemu_mod_timer(icount_vm_timer,
1013 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1017 static void init_icount_adjust(void)
1019 /* Have both realtime and virtual time triggers for speed adjustment.
1020 The realtime trigger catches emulated time passing too slowly,
1021 the virtual time trigger catches emulated time passing too fast.
1022 Realtime triggers occur even when idle, so use them less frequently
1023 than VM triggers. */
1024 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1025 qemu_mod_timer(icount_rt_timer,
1026 qemu_get_clock(rt_clock) + 1000);
1027 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1028 qemu_mod_timer(icount_vm_timer,
1029 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1032 static struct qemu_alarm_timer alarm_timers[] = {
1035 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1036 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1037 /* HPET - if available - is preferred */
1038 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1039 /* ...otherwise try RTC */
1040 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1042 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1044 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1045 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1046 {"win32", 0, win32_start_timer,
1047 win32_stop_timer, NULL, &alarm_win32_data},
1052 static void show_available_alarms(void)
1056 printf("Available alarm timers, in order of precedence:\n");
1057 for (i = 0; alarm_timers[i].name; i++)
1058 printf("%s\n", alarm_timers[i].name);
1061 static void configure_alarms(char const *opt)
1065 int count = ARRAY_SIZE(alarm_timers) - 1;
1068 struct qemu_alarm_timer tmp;
1070 if (!strcmp(opt, "?")) {
1071 show_available_alarms();
1077 /* Reorder the array */
1078 name = strtok(arg, ",");
1080 for (i = 0; i < count && alarm_timers[i].name; i++) {
1081 if (!strcmp(alarm_timers[i].name, name))
1086 fprintf(stderr, "Unknown clock %s\n", name);
1095 tmp = alarm_timers[i];
1096 alarm_timers[i] = alarm_timers[cur];
1097 alarm_timers[cur] = tmp;
1101 name = strtok(NULL, ",");
1107 /* Disable remaining timers */
1108 for (i = cur; i < count; i++)
1109 alarm_timers[i].name = NULL;
1111 show_available_alarms();
1116 QEMUClock *rt_clock;
1117 QEMUClock *vm_clock;
1119 static QEMUTimer *active_timers[2];
1121 static QEMUClock *qemu_new_clock(int type)
1124 clock = qemu_mallocz(sizeof(QEMUClock));
1129 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1133 ts = qemu_mallocz(sizeof(QEMUTimer));
1136 ts->opaque = opaque;
1140 void qemu_free_timer(QEMUTimer *ts)
1145 /* stop a timer, but do not dealloc it */
1146 void qemu_del_timer(QEMUTimer *ts)
1150 /* NOTE: this code must be signal safe because
1151 qemu_timer_expired() can be called from a signal. */
1152 pt = &active_timers[ts->clock->type];
1165 /* modify the current timer so that it will be fired when current_time
1166 >= expire_time. The corresponding callback will be called. */
1167 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1173 /* add the timer in the sorted list */
1174 /* NOTE: this code must be signal safe because
1175 qemu_timer_expired() can be called from a signal. */
1176 pt = &active_timers[ts->clock->type];
1181 if (t->expire_time > expire_time)
1185 ts->expire_time = expire_time;
1189 /* Rearm if necessary */
1190 if (pt == &active_timers[ts->clock->type]) {
1191 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1192 qemu_rearm_alarm_timer(alarm_timer);
1194 /* Interrupt execution to force deadline recalculation. */
1195 if (use_icount && cpu_single_env) {
1196 cpu_exit(cpu_single_env);
1201 int qemu_timer_pending(QEMUTimer *ts)
1204 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1211 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1215 return (timer_head->expire_time <= current_time);
1218 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1224 if (!ts || ts->expire_time > current_time)
1226 /* remove timer from the list before calling the callback */
1227 *ptimer_head = ts->next;
1230 /* run the callback (the timer list can be modified) */
1235 int64_t qemu_get_clock(QEMUClock *clock)
1237 switch(clock->type) {
1238 case QEMU_TIMER_REALTIME:
1239 return get_clock() / 1000000;
1241 case QEMU_TIMER_VIRTUAL:
1243 return cpu_get_icount();
1245 return cpu_get_clock();
1250 static void init_timers(void)
1253 ticks_per_sec = QEMU_TIMER_BASE;
1254 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1255 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1259 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1261 uint64_t expire_time;
1263 if (qemu_timer_pending(ts)) {
1264 expire_time = ts->expire_time;
1268 qemu_put_be64(f, expire_time);
1271 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1273 uint64_t expire_time;
1275 expire_time = qemu_get_be64(f);
1276 if (expire_time != -1) {
1277 qemu_mod_timer(ts, expire_time);
1283 static void timer_save(QEMUFile *f, void *opaque)
1285 if (cpu_ticks_enabled) {
1286 hw_error("cannot save state if virtual timers are running");
1288 qemu_put_be64(f, cpu_ticks_offset);
1289 qemu_put_be64(f, ticks_per_sec);
1290 qemu_put_be64(f, cpu_clock_offset);
1293 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1295 if (version_id != 1 && version_id != 2)
1297 if (cpu_ticks_enabled) {
1300 cpu_ticks_offset=qemu_get_be64(f);
1301 ticks_per_sec=qemu_get_be64(f);
1302 if (version_id == 2) {
1303 cpu_clock_offset=qemu_get_be64(f);
1309 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1310 DWORD_PTR dwUser, DWORD_PTR dw1,
1313 static void host_alarm_handler(int host_signum)
1317 #define DISP_FREQ 1000
1319 static int64_t delta_min = INT64_MAX;
1320 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1322 ti = qemu_get_clock(vm_clock);
1323 if (last_clock != 0) {
1324 delta = ti - last_clock;
1325 if (delta < delta_min)
1327 if (delta > delta_max)
1330 if (++count == DISP_FREQ) {
1331 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1332 muldiv64(delta_min, 1000000, ticks_per_sec),
1333 muldiv64(delta_max, 1000000, ticks_per_sec),
1334 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1335 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1337 delta_min = INT64_MAX;
1345 if (alarm_has_dynticks(alarm_timer) ||
1347 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1348 qemu_get_clock(vm_clock))) ||
1349 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1350 qemu_get_clock(rt_clock))) {
1351 CPUState *env = next_cpu;
1354 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1355 SetEvent(data->host_alarm);
1357 static const char byte = 0;
1358 write(alarm_timer_wfd, &byte, sizeof(byte));
1360 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1363 /* stop the currently executing cpu because a timer occured */
1366 if (env->kqemu_enabled) {
1367 kqemu_cpu_interrupt(env);
1375 static int64_t qemu_next_deadline(void)
1379 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1380 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1381 qemu_get_clock(vm_clock);
1383 /* To avoid problems with overflow limit this to 2^32. */
1393 #if defined(__linux__) || defined(_WIN32)
1394 static uint64_t qemu_next_deadline_dyntick(void)
1402 delta = (qemu_next_deadline() + 999) / 1000;
1404 if (active_timers[QEMU_TIMER_REALTIME]) {
1405 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1406 qemu_get_clock(rt_clock))*1000;
1407 if (rtdelta < delta)
1411 if (delta < MIN_TIMER_REARM_US)
1412 delta = MIN_TIMER_REARM_US;
1420 /* Sets a specific flag */
1421 static int fcntl_setfl(int fd, int flag)
1425 flags = fcntl(fd, F_GETFL);
1429 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1435 #if defined(__linux__)
1437 #define RTC_FREQ 1024
1439 static void enable_sigio_timer(int fd)
1441 struct sigaction act;
1444 sigfillset(&act.sa_mask);
1446 act.sa_handler = host_alarm_handler;
1448 sigaction(SIGIO, &act, NULL);
1449 fcntl_setfl(fd, O_ASYNC);
1450 fcntl(fd, F_SETOWN, getpid());
1453 static int hpet_start_timer(struct qemu_alarm_timer *t)
1455 struct hpet_info info;
1458 fd = open("/dev/hpet", O_RDONLY);
1463 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1465 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1466 "error, but for better emulation accuracy type:\n"
1467 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1471 /* Check capabilities */
1472 r = ioctl(fd, HPET_INFO, &info);
1476 /* Enable periodic mode */
1477 r = ioctl(fd, HPET_EPI, 0);
1478 if (info.hi_flags && (r < 0))
1481 /* Enable interrupt */
1482 r = ioctl(fd, HPET_IE_ON, 0);
1486 enable_sigio_timer(fd);
1487 t->priv = (void *)(long)fd;
1495 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1497 int fd = (long)t->priv;
1502 static int rtc_start_timer(struct qemu_alarm_timer *t)
1505 unsigned long current_rtc_freq = 0;
1507 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1510 ioctl(rtc_fd, RTC_IRQP_READ, ¤t_rtc_freq);
1511 if (current_rtc_freq != RTC_FREQ &&
1512 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1513 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1514 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1515 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1518 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1524 enable_sigio_timer(rtc_fd);
1526 t->priv = (void *)(long)rtc_fd;
1531 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1533 int rtc_fd = (long)t->priv;
1538 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1542 struct sigaction act;
1544 sigfillset(&act.sa_mask);
1546 act.sa_handler = host_alarm_handler;
1548 sigaction(SIGALRM, &act, NULL);
1550 ev.sigev_value.sival_int = 0;
1551 ev.sigev_notify = SIGEV_SIGNAL;
1552 ev.sigev_signo = SIGALRM;
1554 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1555 perror("timer_create");
1557 /* disable dynticks */
1558 fprintf(stderr, "Dynamic Ticks disabled\n");
1563 t->priv = (void *)(long)host_timer;
1568 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1570 timer_t host_timer = (timer_t)(long)t->priv;
1572 timer_delete(host_timer);
1575 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1577 timer_t host_timer = (timer_t)(long)t->priv;
1578 struct itimerspec timeout;
1579 int64_t nearest_delta_us = INT64_MAX;
1582 if (!active_timers[QEMU_TIMER_REALTIME] &&
1583 !active_timers[QEMU_TIMER_VIRTUAL])
1586 nearest_delta_us = qemu_next_deadline_dyntick();
1588 /* check whether a timer is already running */
1589 if (timer_gettime(host_timer, &timeout)) {
1591 fprintf(stderr, "Internal timer error: aborting\n");
1594 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1595 if (current_us && current_us <= nearest_delta_us)
1598 timeout.it_interval.tv_sec = 0;
1599 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1600 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1601 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1602 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1604 fprintf(stderr, "Internal timer error: aborting\n");
1609 #endif /* defined(__linux__) */
1611 static int unix_start_timer(struct qemu_alarm_timer *t)
1613 struct sigaction act;
1614 struct itimerval itv;
1618 sigfillset(&act.sa_mask);
1620 act.sa_handler = host_alarm_handler;
1622 sigaction(SIGALRM, &act, NULL);
1624 itv.it_interval.tv_sec = 0;
1625 /* for i386 kernel 2.6 to get 1 ms */
1626 itv.it_interval.tv_usec = 999;
1627 itv.it_value.tv_sec = 0;
1628 itv.it_value.tv_usec = 10 * 1000;
1630 err = setitimer(ITIMER_REAL, &itv, NULL);
1637 static void unix_stop_timer(struct qemu_alarm_timer *t)
1639 struct itimerval itv;
1641 memset(&itv, 0, sizeof(itv));
1642 setitimer(ITIMER_REAL, &itv, NULL);
1645 #endif /* !defined(_WIN32) */
1647 static void try_to_rearm_timer(void *opaque)
1649 struct qemu_alarm_timer *t = opaque;
1653 /* Drain the notify pipe */
1656 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1657 } while ((len == -1 && errno == EINTR) || len > 0);
1660 if (t->flags & ALARM_FLAG_EXPIRED) {
1661 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1662 qemu_rearm_alarm_timer(alarm_timer);
1668 static int win32_start_timer(struct qemu_alarm_timer *t)
1671 struct qemu_alarm_win32 *data = t->priv;
1674 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1675 if (!data->host_alarm) {
1676 perror("Failed CreateEvent");
1680 memset(&tc, 0, sizeof(tc));
1681 timeGetDevCaps(&tc, sizeof(tc));
1683 if (data->period < tc.wPeriodMin)
1684 data->period = tc.wPeriodMin;
1686 timeBeginPeriod(data->period);
1688 flags = TIME_CALLBACK_FUNCTION;
1689 if (alarm_has_dynticks(t))
1690 flags |= TIME_ONESHOT;
1692 flags |= TIME_PERIODIC;
1694 data->timerId = timeSetEvent(1, // interval (ms)
1695 data->period, // resolution
1696 host_alarm_handler, // function
1697 (DWORD)t, // parameter
1700 if (!data->timerId) {
1701 perror("Failed to initialize win32 alarm timer");
1703 timeEndPeriod(data->period);
1704 CloseHandle(data->host_alarm);
1708 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1713 static void win32_stop_timer(struct qemu_alarm_timer *t)
1715 struct qemu_alarm_win32 *data = t->priv;
1717 timeKillEvent(data->timerId);
1718 timeEndPeriod(data->period);
1720 CloseHandle(data->host_alarm);
1723 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1725 struct qemu_alarm_win32 *data = t->priv;
1726 uint64_t nearest_delta_us;
1728 if (!active_timers[QEMU_TIMER_REALTIME] &&
1729 !active_timers[QEMU_TIMER_VIRTUAL])
1732 nearest_delta_us = qemu_next_deadline_dyntick();
1733 nearest_delta_us /= 1000;
1735 timeKillEvent(data->timerId);
1737 data->timerId = timeSetEvent(1,
1741 TIME_ONESHOT | TIME_PERIODIC);
1743 if (!data->timerId) {
1744 perror("Failed to re-arm win32 alarm timer");
1746 timeEndPeriod(data->period);
1747 CloseHandle(data->host_alarm);
1754 static int init_timer_alarm(void)
1756 struct qemu_alarm_timer *t = NULL;
1766 err = fcntl_setfl(fds[0], O_NONBLOCK);
1770 err = fcntl_setfl(fds[1], O_NONBLOCK);
1774 alarm_timer_rfd = fds[0];
1775 alarm_timer_wfd = fds[1];
1778 for (i = 0; alarm_timers[i].name; i++) {
1779 t = &alarm_timers[i];
1792 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1793 try_to_rearm_timer, NULL, t);
1808 static void quit_timers(void)
1810 alarm_timer->stop(alarm_timer);
1814 /***********************************************************/
1815 /* host time/date access */
1816 void qemu_get_timedate(struct tm *tm, int offset)
1823 if (rtc_date_offset == -1) {
1827 ret = localtime(&ti);
1829 ti -= rtc_date_offset;
1833 memcpy(tm, ret, sizeof(struct tm));
1836 int qemu_timedate_diff(struct tm *tm)
1840 if (rtc_date_offset == -1)
1842 seconds = mktimegm(tm);
1844 seconds = mktime(tm);
1846 seconds = mktimegm(tm) + rtc_date_offset;
1848 return seconds - time(NULL);
1852 static void socket_cleanup(void)
1857 static int socket_init(void)
1862 ret = WSAStartup(MAKEWORD(2,2), &Data);
1864 err = WSAGetLastError();
1865 fprintf(stderr, "WSAStartup: %d\n", err);
1868 atexit(socket_cleanup);
1873 const char *get_opt_name(char *buf, int buf_size, const char *p, char delim)
1878 while (*p != '\0' && *p != delim) {
1879 if (q && (q - buf) < buf_size - 1)
1889 const char *get_opt_value(char *buf, int buf_size, const char *p)
1894 while (*p != '\0') {
1896 if (*(p + 1) != ',')
1900 if (q && (q - buf) < buf_size - 1)
1910 int get_param_value(char *buf, int buf_size,
1911 const char *tag, const char *str)
1918 p = get_opt_name(option, sizeof(option), p, '=');
1922 if (!strcmp(tag, option)) {
1923 (void)get_opt_value(buf, buf_size, p);
1926 p = get_opt_value(NULL, 0, p);
1935 int check_params(char *buf, int buf_size,
1936 const char * const *params, const char *str)
1942 while (*p != '\0') {
1943 p = get_opt_name(buf, buf_size, p, '=');
1947 for(i = 0; params[i] != NULL; i++)
1948 if (!strcmp(params[i], buf))
1950 if (params[i] == NULL)
1952 p = get_opt_value(NULL, 0, p);
1960 /***********************************************************/
1961 /* Bluetooth support */
1964 static struct HCIInfo *hci_table[MAX_NICS];
1966 static struct bt_vlan_s {
1967 struct bt_scatternet_s net;
1969 struct bt_vlan_s *next;
1972 /* find or alloc a new bluetooth "VLAN" */
1973 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1975 struct bt_vlan_s **pvlan, *vlan;
1976 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1980 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1982 pvlan = &first_bt_vlan;
1983 while (*pvlan != NULL)
1984 pvlan = &(*pvlan)->next;
1989 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1993 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1998 static struct HCIInfo null_hci = {
1999 .cmd_send = null_hci_send,
2000 .sco_send = null_hci_send,
2001 .acl_send = null_hci_send,
2002 .bdaddr_set = null_hci_addr_set,
2005 struct HCIInfo *qemu_next_hci(void)
2007 if (cur_hci == nb_hcis)
2010 return hci_table[cur_hci++];
2013 static struct HCIInfo *hci_init(const char *str)
2016 struct bt_scatternet_s *vlan = 0;
2018 if (!strcmp(str, "null"))
2021 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2023 return bt_host_hci(str[4] ? str + 5 : "hci0");
2024 else if (!strncmp(str, "hci", 3)) {
2027 if (!strncmp(str + 3, ",vlan=", 6)) {
2028 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2033 vlan = qemu_find_bt_vlan(0);
2035 return bt_new_hci(vlan);
2038 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2043 static int bt_hci_parse(const char *str)
2045 struct HCIInfo *hci;
2048 if (nb_hcis >= MAX_NICS) {
2049 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2053 hci = hci_init(str);
2062 bdaddr.b[5] = 0x56 + nb_hcis;
2063 hci->bdaddr_set(hci, bdaddr.b);
2065 hci_table[nb_hcis++] = hci;
2070 static void bt_vhci_add(int vlan_id)
2072 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2075 fprintf(stderr, "qemu: warning: adding a VHCI to "
2076 "an empty scatternet %i\n", vlan_id);
2078 bt_vhci_init(bt_new_hci(vlan));
2081 static struct bt_device_s *bt_device_add(const char *opt)
2083 struct bt_scatternet_s *vlan;
2085 char *endp = strstr(opt, ",vlan=");
2086 int len = (endp ? endp - opt : strlen(opt)) + 1;
2089 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2092 vlan_id = strtol(endp + 6, &endp, 0);
2094 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2099 vlan = qemu_find_bt_vlan(vlan_id);
2102 fprintf(stderr, "qemu: warning: adding a slave device to "
2103 "an empty scatternet %i\n", vlan_id);
2105 if (!strcmp(devname, "keyboard"))
2106 return bt_keyboard_init(vlan);
2108 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2112 static int bt_parse(const char *opt)
2114 const char *endp, *p;
2117 if (strstart(opt, "hci", &endp)) {
2118 if (!*endp || *endp == ',') {
2120 if (!strstart(endp, ",vlan=", 0))
2123 return bt_hci_parse(opt);
2125 } else if (strstart(opt, "vhci", &endp)) {
2126 if (!*endp || *endp == ',') {
2128 if (strstart(endp, ",vlan=", &p)) {
2129 vlan = strtol(p, (char **) &endp, 0);
2131 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2135 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2144 } else if (strstart(opt, "device:", &endp))
2145 return !bt_device_add(endp);
2147 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2151 /***********************************************************/
2152 /* QEMU Block devices */
2154 #define HD_ALIAS "index=%d,media=disk"
2155 #define CDROM_ALIAS "index=2,media=cdrom"
2156 #define FD_ALIAS "index=%d,if=floppy"
2157 #define PFLASH_ALIAS "if=pflash"
2158 #define MTD_ALIAS "if=mtd"
2159 #define SD_ALIAS "index=0,if=sd"
2161 static int drive_opt_get_free_idx(void)
2165 for (index = 0; index < MAX_DRIVES; index++)
2166 if (!drives_opt[index].used) {
2167 drives_opt[index].used = 1;
2174 static int drive_get_free_idx(void)
2178 for (index = 0; index < MAX_DRIVES; index++)
2179 if (!drives_table[index].used) {
2180 drives_table[index].used = 1;
2187 int drive_add(const char *file, const char *fmt, ...)
2190 int index = drive_opt_get_free_idx();
2192 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2193 fprintf(stderr, "qemu: too many drives\n");
2197 drives_opt[index].file = file;
2199 vsnprintf(drives_opt[index].opt,
2200 sizeof(drives_opt[0].opt), fmt, ap);
2207 void drive_remove(int index)
2209 drives_opt[index].used = 0;
2213 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2217 /* seek interface, bus and unit */
2219 for (index = 0; index < MAX_DRIVES; index++)
2220 if (drives_table[index].type == type &&
2221 drives_table[index].bus == bus &&
2222 drives_table[index].unit == unit &&
2223 drives_table[index].used)
2229 int drive_get_max_bus(BlockInterfaceType type)
2235 for (index = 0; index < nb_drives; index++) {
2236 if(drives_table[index].type == type &&
2237 drives_table[index].bus > max_bus)
2238 max_bus = drives_table[index].bus;
2243 const char *drive_get_serial(BlockDriverState *bdrv)
2247 for (index = 0; index < nb_drives; index++)
2248 if (drives_table[index].bdrv == bdrv)
2249 return drives_table[index].serial;
2254 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2258 for (index = 0; index < nb_drives; index++)
2259 if (drives_table[index].bdrv == bdrv)
2260 return drives_table[index].onerror;
2262 return BLOCK_ERR_STOP_ENOSPC;
2265 static void bdrv_format_print(void *opaque, const char *name)
2267 fprintf(stderr, " %s", name);
2270 void drive_uninit(BlockDriverState *bdrv)
2274 for (i = 0; i < MAX_DRIVES; i++)
2275 if (drives_table[i].bdrv == bdrv) {
2276 drives_table[i].bdrv = NULL;
2277 drives_table[i].used = 0;
2278 drive_remove(drives_table[i].drive_opt_idx);
2284 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2290 const char *mediastr = "";
2291 BlockInterfaceType type;
2292 enum { MEDIA_DISK, MEDIA_CDROM } media;
2293 int bus_id, unit_id;
2294 int cyls, heads, secs, translation;
2295 BlockDriverState *bdrv;
2296 BlockDriver *drv = NULL;
2297 QEMUMachine *machine = opaque;
2301 int bdrv_flags, onerror;
2302 int drives_table_idx;
2303 char *str = arg->opt;
2304 static const char * const params[] = { "bus", "unit", "if", "index",
2305 "cyls", "heads", "secs", "trans",
2306 "media", "snapshot", "file",
2307 "cache", "format", "serial", "werror",
2310 if (check_params(buf, sizeof(buf), params, str) < 0) {
2311 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2317 cyls = heads = secs = 0;
2320 translation = BIOS_ATA_TRANSLATION_AUTO;
2324 if (machine->use_scsi) {
2326 max_devs = MAX_SCSI_DEVS;
2327 pstrcpy(devname, sizeof(devname), "scsi");
2330 max_devs = MAX_IDE_DEVS;
2331 pstrcpy(devname, sizeof(devname), "ide");
2335 /* extract parameters */
2337 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2338 bus_id = strtol(buf, NULL, 0);
2340 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2345 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2346 unit_id = strtol(buf, NULL, 0);
2348 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2353 if (get_param_value(buf, sizeof(buf), "if", str)) {
2354 pstrcpy(devname, sizeof(devname), buf);
2355 if (!strcmp(buf, "ide")) {
2357 max_devs = MAX_IDE_DEVS;
2358 } else if (!strcmp(buf, "scsi")) {
2360 max_devs = MAX_SCSI_DEVS;
2361 } else if (!strcmp(buf, "floppy")) {
2364 } else if (!strcmp(buf, "pflash")) {
2367 } else if (!strcmp(buf, "mtd")) {
2370 } else if (!strcmp(buf, "sd")) {
2373 } else if (!strcmp(buf, "virtio")) {
2376 } else if (!strcmp(buf, "xen")) {
2380 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2385 if (get_param_value(buf, sizeof(buf), "index", str)) {
2386 index = strtol(buf, NULL, 0);
2388 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2393 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2394 cyls = strtol(buf, NULL, 0);
2397 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2398 heads = strtol(buf, NULL, 0);
2401 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2402 secs = strtol(buf, NULL, 0);
2405 if (cyls || heads || secs) {
2406 if (cyls < 1 || cyls > 16383) {
2407 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2410 if (heads < 1 || heads > 16) {
2411 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2414 if (secs < 1 || secs > 63) {
2415 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2420 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2423 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2427 if (!strcmp(buf, "none"))
2428 translation = BIOS_ATA_TRANSLATION_NONE;
2429 else if (!strcmp(buf, "lba"))
2430 translation = BIOS_ATA_TRANSLATION_LBA;
2431 else if (!strcmp(buf, "auto"))
2432 translation = BIOS_ATA_TRANSLATION_AUTO;
2434 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2439 if (get_param_value(buf, sizeof(buf), "media", str)) {
2440 if (!strcmp(buf, "disk")) {
2442 } else if (!strcmp(buf, "cdrom")) {
2443 if (cyls || secs || heads) {
2445 "qemu: '%s' invalid physical CHS format\n", str);
2448 media = MEDIA_CDROM;
2450 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2455 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2456 if (!strcmp(buf, "on"))
2458 else if (!strcmp(buf, "off"))
2461 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2466 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2467 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2469 else if (!strcmp(buf, "writethrough"))
2471 else if (!strcmp(buf, "writeback"))
2474 fprintf(stderr, "qemu: invalid cache option\n");
2479 if (get_param_value(buf, sizeof(buf), "format", str)) {
2480 if (strcmp(buf, "?") == 0) {
2481 fprintf(stderr, "qemu: Supported formats:");
2482 bdrv_iterate_format(bdrv_format_print, NULL);
2483 fprintf(stderr, "\n");
2486 drv = bdrv_find_format(buf);
2488 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2493 if (arg->file == NULL)
2494 get_param_value(file, sizeof(file), "file", str);
2496 pstrcpy(file, sizeof(file), arg->file);
2498 if (!get_param_value(serial, sizeof(serial), "serial", str))
2499 memset(serial, 0, sizeof(serial));
2501 onerror = BLOCK_ERR_STOP_ENOSPC;
2502 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2503 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2504 fprintf(stderr, "werror is no supported by this format\n");
2507 if (!strcmp(buf, "ignore"))
2508 onerror = BLOCK_ERR_IGNORE;
2509 else if (!strcmp(buf, "enospc"))
2510 onerror = BLOCK_ERR_STOP_ENOSPC;
2511 else if (!strcmp(buf, "stop"))
2512 onerror = BLOCK_ERR_STOP_ANY;
2513 else if (!strcmp(buf, "report"))
2514 onerror = BLOCK_ERR_REPORT;
2516 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2521 /* compute bus and unit according index */
2524 if (bus_id != 0 || unit_id != -1) {
2526 "qemu: '%s' index cannot be used with bus and unit\n", str);
2534 unit_id = index % max_devs;
2535 bus_id = index / max_devs;
2539 /* if user doesn't specify a unit_id,
2540 * try to find the first free
2543 if (unit_id == -1) {
2545 while (drive_get_index(type, bus_id, unit_id) != -1) {
2547 if (max_devs && unit_id >= max_devs) {
2548 unit_id -= max_devs;
2556 if (max_devs && unit_id >= max_devs) {
2557 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2558 str, unit_id, max_devs - 1);
2563 * ignore multiple definitions
2566 if (drive_get_index(type, bus_id, unit_id) != -1)
2571 if (type == IF_IDE || type == IF_SCSI)
2572 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2574 snprintf(buf, sizeof(buf), "%s%i%s%i",
2575 devname, bus_id, mediastr, unit_id);
2577 snprintf(buf, sizeof(buf), "%s%s%i",
2578 devname, mediastr, unit_id);
2579 bdrv = bdrv_new(buf);
2580 drives_table_idx = drive_get_free_idx();
2581 drives_table[drives_table_idx].bdrv = bdrv;
2582 drives_table[drives_table_idx].type = type;
2583 drives_table[drives_table_idx].bus = bus_id;
2584 drives_table[drives_table_idx].unit = unit_id;
2585 drives_table[drives_table_idx].onerror = onerror;
2586 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2587 strncpy(drives_table[nb_drives].serial, serial, sizeof(serial));
2597 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2598 bdrv_set_translation_hint(bdrv, translation);
2602 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2607 /* FIXME: This isn't really a floppy, but it's a reasonable
2610 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2621 bdrv_flags |= BDRV_O_SNAPSHOT;
2622 cache = 2; /* always use write-back with snapshot */
2624 if (cache == 0) /* no caching */
2625 bdrv_flags |= BDRV_O_NOCACHE;
2626 else if (cache == 2) /* write-back */
2627 bdrv_flags |= BDRV_O_CACHE_WB;
2628 else if (cache == 3) /* not specified */
2629 bdrv_flags |= BDRV_O_CACHE_DEF;
2630 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2631 fprintf(stderr, "qemu: could not open disk image %s\n",
2635 if (bdrv_key_required(bdrv))
2637 return drives_table_idx;
2640 static void numa_add(const char *optarg)
2644 unsigned long long value, endvalue;
2647 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2648 if (!strcmp(option, "node")) {
2649 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2650 nodenr = nb_numa_nodes;
2652 nodenr = strtoull(option, NULL, 10);
2655 if (get_param_value(option, 128, "mem", optarg) == 0) {
2656 node_mem[nodenr] = 0;
2658 value = strtoull(option, &endptr, 0);
2660 case 0: case 'M': case 'm':
2667 node_mem[nodenr] = value;
2669 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2670 node_cpumask[nodenr] = 0;
2672 value = strtoull(option, &endptr, 10);
2675 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2677 if (*endptr == '-') {
2678 endvalue = strtoull(endptr+1, &endptr, 10);
2679 if (endvalue >= 63) {
2682 "only 63 CPUs in NUMA mode supported.\n");
2684 value = (1 << (endvalue + 1)) - (1 << value);
2689 node_cpumask[nodenr] = value;
2696 /***********************************************************/
2699 static USBPort *used_usb_ports;
2700 static USBPort *free_usb_ports;
2702 /* ??? Maybe change this to register a hub to keep track of the topology. */
2703 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2704 usb_attachfn attach)
2706 port->opaque = opaque;
2707 port->index = index;
2708 port->attach = attach;
2709 port->next = free_usb_ports;
2710 free_usb_ports = port;
2713 int usb_device_add_dev(USBDevice *dev)
2717 /* Find a USB port to add the device to. */
2718 port = free_usb_ports;
2722 /* Create a new hub and chain it on. */
2723 free_usb_ports = NULL;
2724 port->next = used_usb_ports;
2725 used_usb_ports = port;
2727 hub = usb_hub_init(VM_USB_HUB_SIZE);
2728 usb_attach(port, hub);
2729 port = free_usb_ports;
2732 free_usb_ports = port->next;
2733 port->next = used_usb_ports;
2734 used_usb_ports = port;
2735 usb_attach(port, dev);
2739 static void usb_msd_password_cb(void *opaque, int err)
2741 USBDevice *dev = opaque;
2744 usb_device_add_dev(dev);
2746 dev->handle_destroy(dev);
2749 static int usb_device_add(const char *devname, int is_hotplug)
2754 if (!free_usb_ports)
2757 if (strstart(devname, "host:", &p)) {
2758 dev = usb_host_device_open(p);
2759 } else if (!strcmp(devname, "mouse")) {
2760 dev = usb_mouse_init();
2761 } else if (!strcmp(devname, "tablet")) {
2762 dev = usb_tablet_init();
2763 } else if (!strcmp(devname, "keyboard")) {
2764 dev = usb_keyboard_init();
2765 } else if (strstart(devname, "disk:", &p)) {
2766 BlockDriverState *bs;
2768 dev = usb_msd_init(p);
2771 bs = usb_msd_get_bdrv(dev);
2772 if (bdrv_key_required(bs)) {
2775 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2780 } else if (!strcmp(devname, "wacom-tablet")) {
2781 dev = usb_wacom_init();
2782 } else if (strstart(devname, "serial:", &p)) {
2783 dev = usb_serial_init(p);
2784 #ifdef CONFIG_BRLAPI
2785 } else if (!strcmp(devname, "braille")) {
2786 dev = usb_baum_init();
2788 } else if (strstart(devname, "net:", &p)) {
2791 if (net_client_init("nic", p) < 0)
2793 nd_table[nic].model = "usb";
2794 dev = usb_net_init(&nd_table[nic]);
2795 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2796 dev = usb_bt_init(devname[2] ? hci_init(p) :
2797 bt_new_hci(qemu_find_bt_vlan(0)));
2804 return usb_device_add_dev(dev);
2807 int usb_device_del_addr(int bus_num, int addr)
2813 if (!used_usb_ports)
2819 lastp = &used_usb_ports;
2820 port = used_usb_ports;
2821 while (port && port->dev->addr != addr) {
2822 lastp = &port->next;
2830 *lastp = port->next;
2831 usb_attach(port, NULL);
2832 dev->handle_destroy(dev);
2833 port->next = free_usb_ports;
2834 free_usb_ports = port;
2838 static int usb_device_del(const char *devname)
2843 if (strstart(devname, "host:", &p))
2844 return usb_host_device_close(p);
2846 if (!used_usb_ports)
2849 p = strchr(devname, '.');
2852 bus_num = strtoul(devname, NULL, 0);
2853 addr = strtoul(p + 1, NULL, 0);
2855 return usb_device_del_addr(bus_num, addr);
2858 void do_usb_add(Monitor *mon, const char *devname)
2860 usb_device_add(devname, 1);
2863 void do_usb_del(Monitor *mon, const char *devname)
2865 usb_device_del(devname);
2868 void usb_info(Monitor *mon)
2872 const char *speed_str;
2875 monitor_printf(mon, "USB support not enabled\n");
2879 for (port = used_usb_ports; port; port = port->next) {
2883 switch(dev->speed) {
2887 case USB_SPEED_FULL:
2890 case USB_SPEED_HIGH:
2897 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2898 0, dev->addr, speed_str, dev->devname);
2902 /***********************************************************/
2903 /* PCMCIA/Cardbus */
2905 static struct pcmcia_socket_entry_s {
2906 struct pcmcia_socket_s *socket;
2907 struct pcmcia_socket_entry_s *next;
2908 } *pcmcia_sockets = 0;
2910 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2912 struct pcmcia_socket_entry_s *entry;
2914 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2915 entry->socket = socket;
2916 entry->next = pcmcia_sockets;
2917 pcmcia_sockets = entry;
2920 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2922 struct pcmcia_socket_entry_s *entry, **ptr;
2924 ptr = &pcmcia_sockets;
2925 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2926 if (entry->socket == socket) {
2932 void pcmcia_info(Monitor *mon)
2934 struct pcmcia_socket_entry_s *iter;
2936 if (!pcmcia_sockets)
2937 monitor_printf(mon, "No PCMCIA sockets\n");
2939 for (iter = pcmcia_sockets; iter; iter = iter->next)
2940 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2941 iter->socket->attached ? iter->socket->card_string :
2945 /***********************************************************/
2946 /* register display */
2948 struct DisplayAllocator default_allocator = {
2949 defaultallocator_create_displaysurface,
2950 defaultallocator_resize_displaysurface,
2951 defaultallocator_free_displaysurface
2954 void register_displaystate(DisplayState *ds)
2964 DisplayState *get_displaystate(void)
2966 return display_state;
2969 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2971 if(ds->allocator == &default_allocator) ds->allocator = da;
2972 return ds->allocator;
2977 static void dumb_display_init(void)
2979 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2980 ds->allocator = &default_allocator;
2981 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2982 register_displaystate(ds);
2985 /***********************************************************/
2988 typedef struct IOHandlerRecord {
2990 IOCanRWHandler *fd_read_poll;
2992 IOHandler *fd_write;
2995 /* temporary data */
2997 struct IOHandlerRecord *next;
3000 static IOHandlerRecord *first_io_handler;
3002 /* XXX: fd_read_poll should be suppressed, but an API change is
3003 necessary in the character devices to suppress fd_can_read(). */
3004 int qemu_set_fd_handler2(int fd,
3005 IOCanRWHandler *fd_read_poll,
3007 IOHandler *fd_write,
3010 IOHandlerRecord **pioh, *ioh;
3012 if (!fd_read && !fd_write) {
3013 pioh = &first_io_handler;
3018 if (ioh->fd == fd) {
3025 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3029 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3030 ioh->next = first_io_handler;
3031 first_io_handler = ioh;
3034 ioh->fd_read_poll = fd_read_poll;
3035 ioh->fd_read = fd_read;
3036 ioh->fd_write = fd_write;
3037 ioh->opaque = opaque;
3043 int qemu_set_fd_handler(int fd,
3045 IOHandler *fd_write,
3048 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3052 /***********************************************************/
3053 /* Polling handling */
3055 typedef struct PollingEntry {
3058 struct PollingEntry *next;
3061 static PollingEntry *first_polling_entry;
3063 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3065 PollingEntry **ppe, *pe;
3066 pe = qemu_mallocz(sizeof(PollingEntry));
3068 pe->opaque = opaque;
3069 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3074 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3076 PollingEntry **ppe, *pe;
3077 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3079 if (pe->func == func && pe->opaque == opaque) {
3087 /***********************************************************/
3088 /* Wait objects support */
3089 typedef struct WaitObjects {
3091 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3092 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3093 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3096 static WaitObjects wait_objects = {0};
3098 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3100 WaitObjects *w = &wait_objects;
3102 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3104 w->events[w->num] = handle;
3105 w->func[w->num] = func;
3106 w->opaque[w->num] = opaque;
3111 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3114 WaitObjects *w = &wait_objects;
3117 for (i = 0; i < w->num; i++) {
3118 if (w->events[i] == handle)
3121 w->events[i] = w->events[i + 1];
3122 w->func[i] = w->func[i + 1];
3123 w->opaque[i] = w->opaque[i + 1];
3131 /***********************************************************/
3132 /* ram save/restore */
3134 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3138 v = qemu_get_byte(f);
3141 if (qemu_get_buffer(f, buf, len) != len)
3145 v = qemu_get_byte(f);
3146 memset(buf, v, len);
3152 if (qemu_file_has_error(f))
3158 static int ram_load_v1(QEMUFile *f, void *opaque)
3163 if (qemu_get_be32(f) != last_ram_offset)
3165 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
3166 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
3173 #define BDRV_HASH_BLOCK_SIZE 1024
3174 #define IOBUF_SIZE 4096
3175 #define RAM_CBLOCK_MAGIC 0xfabe
3177 typedef struct RamDecompressState {
3180 uint8_t buf[IOBUF_SIZE];
3181 } RamDecompressState;
3183 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3186 memset(s, 0, sizeof(*s));
3188 ret = inflateInit(&s->zstream);
3194 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3198 s->zstream.avail_out = len;
3199 s->zstream.next_out = buf;
3200 while (s->zstream.avail_out > 0) {
3201 if (s->zstream.avail_in == 0) {
3202 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3204 clen = qemu_get_be16(s->f);
3205 if (clen > IOBUF_SIZE)
3207 qemu_get_buffer(s->f, s->buf, clen);
3208 s->zstream.avail_in = clen;
3209 s->zstream.next_in = s->buf;
3211 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3212 if (ret != Z_OK && ret != Z_STREAM_END) {
3219 static void ram_decompress_close(RamDecompressState *s)
3221 inflateEnd(&s->zstream);
3224 #define RAM_SAVE_FLAG_FULL 0x01
3225 #define RAM_SAVE_FLAG_COMPRESS 0x02
3226 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3227 #define RAM_SAVE_FLAG_PAGE 0x08
3228 #define RAM_SAVE_FLAG_EOS 0x10
3230 static int is_dup_page(uint8_t *page, uint8_t ch)
3232 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3233 uint32_t *array = (uint32_t *)page;
3236 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3237 if (array[i] != val)
3244 static int ram_save_block(QEMUFile *f)
3246 static ram_addr_t current_addr = 0;
3247 ram_addr_t saved_addr = current_addr;
3248 ram_addr_t addr = 0;
3251 while (addr < last_ram_offset) {
3252 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3255 cpu_physical_memory_reset_dirty(current_addr,
3256 current_addr + TARGET_PAGE_SIZE,
3257 MIGRATION_DIRTY_FLAG);
3259 p = qemu_get_ram_ptr(current_addr);
3261 if (is_dup_page(p, *p)) {
3262 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3263 qemu_put_byte(f, *p);
3265 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3266 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3272 addr += TARGET_PAGE_SIZE;
3273 current_addr = (saved_addr + addr) % last_ram_offset;
3279 static ram_addr_t ram_save_threshold = 10;
3281 static ram_addr_t ram_save_remaining(void)
3284 ram_addr_t count = 0;
3286 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3287 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3294 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3299 /* Make sure all dirty bits are set */
3300 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3301 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3302 cpu_physical_memory_set_dirty(addr);
3305 /* Enable dirty memory tracking */
3306 cpu_physical_memory_set_dirty_tracking(1);
3308 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3311 while (!qemu_file_rate_limit(f)) {
3314 ret = ram_save_block(f);
3315 if (ret == 0) /* no more blocks */
3319 /* try transferring iterative blocks of memory */
3323 /* flush all remaining blocks regardless of rate limiting */
3324 while (ram_save_block(f) != 0);
3325 cpu_physical_memory_set_dirty_tracking(0);
3328 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3330 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3333 static int ram_load_dead(QEMUFile *f, void *opaque)
3335 RamDecompressState s1, *s = &s1;
3339 if (ram_decompress_open(s, f) < 0)
3341 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3342 if (ram_decompress_buf(s, buf, 1) < 0) {
3343 fprintf(stderr, "Error while reading ram block header\n");
3347 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3348 BDRV_HASH_BLOCK_SIZE) < 0) {
3349 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3354 printf("Error block header\n");
3358 ram_decompress_close(s);
3363 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3368 if (version_id == 1)
3369 return ram_load_v1(f, opaque);
3371 if (version_id == 2) {
3372 if (qemu_get_be32(f) != last_ram_offset)
3374 return ram_load_dead(f, opaque);
3377 if (version_id != 3)
3381 addr = qemu_get_be64(f);
3383 flags = addr & ~TARGET_PAGE_MASK;
3384 addr &= TARGET_PAGE_MASK;
3386 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3387 if (addr != last_ram_offset)
3391 if (flags & RAM_SAVE_FLAG_FULL) {
3392 if (ram_load_dead(f, opaque) < 0)
3396 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3397 uint8_t ch = qemu_get_byte(f);
3398 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3399 } else if (flags & RAM_SAVE_FLAG_PAGE)
3400 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3401 } while (!(flags & RAM_SAVE_FLAG_EOS));
3406 void qemu_service_io(void)
3408 CPUState *env = cpu_single_env;
3412 if (env->kqemu_enabled) {
3413 kqemu_cpu_interrupt(env);
3419 /***********************************************************/
3420 /* bottom halves (can be seen as timers which expire ASAP) */
3431 static QEMUBH *first_bh = NULL;
3433 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3436 bh = qemu_mallocz(sizeof(QEMUBH));
3438 bh->opaque = opaque;
3439 bh->next = first_bh;
3444 int qemu_bh_poll(void)
3450 for (bh = first_bh; bh; bh = bh->next) {
3451 if (!bh->deleted && bh->scheduled) {
3460 /* remove deleted bhs */
3474 void qemu_bh_schedule_idle(QEMUBH *bh)
3482 void qemu_bh_schedule(QEMUBH *bh)
3484 CPUState *env = cpu_single_env;
3489 /* stop the currently executing CPU to execute the BH ASAP */
3495 void qemu_bh_cancel(QEMUBH *bh)
3500 void qemu_bh_delete(QEMUBH *bh)
3506 static void qemu_bh_update_timeout(int *timeout)
3510 for (bh = first_bh; bh; bh = bh->next) {
3511 if (!bh->deleted && bh->scheduled) {
3513 /* idle bottom halves will be polled at least
3515 *timeout = MIN(10, *timeout);
3517 /* non-idle bottom halves will be executed
3526 /***********************************************************/
3527 /* machine registration */
3529 static QEMUMachine *first_machine = NULL;
3530 QEMUMachine *current_machine = NULL;
3532 int qemu_register_machine(QEMUMachine *m)
3535 pm = &first_machine;
3543 static QEMUMachine *find_machine(const char *name)
3547 for(m = first_machine; m != NULL; m = m->next) {
3548 if (!strcmp(m->name, name))
3554 /***********************************************************/
3555 /* main execution loop */
3557 static void gui_update(void *opaque)
3559 uint64_t interval = GUI_REFRESH_INTERVAL;
3560 DisplayState *ds = opaque;
3561 DisplayChangeListener *dcl = ds->listeners;
3565 while (dcl != NULL) {
3566 if (dcl->gui_timer_interval &&
3567 dcl->gui_timer_interval < interval)
3568 interval = dcl->gui_timer_interval;
3571 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3574 static void nographic_update(void *opaque)
3576 uint64_t interval = GUI_REFRESH_INTERVAL;
3578 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3581 struct vm_change_state_entry {
3582 VMChangeStateHandler *cb;
3584 LIST_ENTRY (vm_change_state_entry) entries;
3587 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3589 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3592 VMChangeStateEntry *e;
3594 e = qemu_mallocz(sizeof (*e));
3598 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3602 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3604 LIST_REMOVE (e, entries);
3608 static void vm_state_notify(int running, int reason)
3610 VMChangeStateEntry *e;
3612 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3613 e->cb(e->opaque, running, reason);
3622 vm_state_notify(1, 0);
3623 qemu_rearm_alarm_timer(alarm_timer);
3627 void vm_stop(int reason)
3630 cpu_disable_ticks();
3632 vm_state_notify(0, reason);
3636 /* reset/shutdown handler */
3638 typedef struct QEMUResetEntry {
3639 QEMUResetHandler *func;
3641 struct QEMUResetEntry *next;
3644 static QEMUResetEntry *first_reset_entry;
3645 static int reset_requested;
3646 static int shutdown_requested;
3647 static int powerdown_requested;
3649 int qemu_shutdown_requested(void)
3651 int r = shutdown_requested;
3652 shutdown_requested = 0;
3656 int qemu_reset_requested(void)
3658 int r = reset_requested;
3659 reset_requested = 0;
3663 int qemu_powerdown_requested(void)
3665 int r = powerdown_requested;
3666 powerdown_requested = 0;
3670 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3672 QEMUResetEntry **pre, *re;
3674 pre = &first_reset_entry;
3675 while (*pre != NULL)
3676 pre = &(*pre)->next;
3677 re = qemu_mallocz(sizeof(QEMUResetEntry));
3679 re->opaque = opaque;
3684 void qemu_system_reset(void)
3688 /* reset all devices */
3689 for(re = first_reset_entry; re != NULL; re = re->next) {
3690 re->func(re->opaque);
3696 void qemu_system_reset_request(void)
3699 shutdown_requested = 1;
3701 reset_requested = 1;
3704 cpu_exit(cpu_single_env);
3707 void qemu_system_shutdown_request(void)
3709 shutdown_requested = 1;
3711 cpu_exit(cpu_single_env);
3714 void qemu_system_powerdown_request(void)
3716 powerdown_requested = 1;
3718 cpu_exit(cpu_single_env);
3722 static void host_main_loop_wait(int *timeout)
3728 /* XXX: need to suppress polling by better using win32 events */
3730 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3731 ret |= pe->func(pe->opaque);
3735 WaitObjects *w = &wait_objects;
3737 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3738 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3739 if (w->func[ret - WAIT_OBJECT_0])
3740 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3742 /* Check for additional signaled events */
3743 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3745 /* Check if event is signaled */
3746 ret2 = WaitForSingleObject(w->events[i], 0);
3747 if(ret2 == WAIT_OBJECT_0) {
3749 w->func[i](w->opaque[i]);
3750 } else if (ret2 == WAIT_TIMEOUT) {
3752 err = GetLastError();
3753 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3756 } else if (ret == WAIT_TIMEOUT) {
3758 err = GetLastError();
3759 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3766 static void host_main_loop_wait(int *timeout)
3771 void main_loop_wait(int timeout)
3773 IOHandlerRecord *ioh;
3774 fd_set rfds, wfds, xfds;
3778 qemu_bh_update_timeout(&timeout);
3780 host_main_loop_wait(&timeout);
3782 /* poll any events */
3783 /* XXX: separate device handlers from system ones */
3788 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3792 (!ioh->fd_read_poll ||
3793 ioh->fd_read_poll(ioh->opaque) != 0)) {
3794 FD_SET(ioh->fd, &rfds);
3798 if (ioh->fd_write) {
3799 FD_SET(ioh->fd, &wfds);
3805 tv.tv_sec = timeout / 1000;
3806 tv.tv_usec = (timeout % 1000) * 1000;
3808 #if defined(CONFIG_SLIRP)
3809 if (slirp_is_inited()) {
3810 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3813 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3815 IOHandlerRecord **pioh;
3817 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3818 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3819 ioh->fd_read(ioh->opaque);
3821 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3822 ioh->fd_write(ioh->opaque);
3826 /* remove deleted IO handlers */
3827 pioh = &first_io_handler;
3837 #if defined(CONFIG_SLIRP)
3838 if (slirp_is_inited()) {
3844 slirp_select_poll(&rfds, &wfds, &xfds);
3848 /* vm time timers */
3849 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3850 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3851 qemu_get_clock(vm_clock));
3853 /* real time timers */
3854 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3855 qemu_get_clock(rt_clock));
3857 /* Check bottom-halves last in case any of the earlier events triggered
3863 static int main_loop(void)
3866 #ifdef CONFIG_PROFILER
3871 cur_cpu = first_cpu;
3872 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3879 #ifdef CONFIG_PROFILER
3880 ti = profile_getclock();
3885 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3886 env->icount_decr.u16.low = 0;
3887 env->icount_extra = 0;
3888 count = qemu_next_deadline();
3889 count = (count + (1 << icount_time_shift) - 1)
3890 >> icount_time_shift;
3891 qemu_icount += count;
3892 decr = (count > 0xffff) ? 0xffff : count;
3894 env->icount_decr.u16.low = decr;
3895 env->icount_extra = count;
3897 ret = cpu_exec(env);
3898 #ifdef CONFIG_PROFILER
3899 qemu_time += profile_getclock() - ti;
3902 /* Fold pending instructions back into the
3903 instruction counter, and clear the interrupt flag. */
3904 qemu_icount -= (env->icount_decr.u16.low
3905 + env->icount_extra);
3906 env->icount_decr.u32 = 0;
3907 env->icount_extra = 0;
3909 next_cpu = env->next_cpu ?: first_cpu;
3910 if (event_pending && likely(ret != EXCP_DEBUG)) {
3911 ret = EXCP_INTERRUPT;
3915 if (ret == EXCP_HLT) {
3916 /* Give the next CPU a chance to run. */
3920 if (ret != EXCP_HALTED)
3922 /* all CPUs are halted ? */
3928 if (shutdown_requested) {
3929 ret = EXCP_INTERRUPT;
3937 if (reset_requested) {
3938 reset_requested = 0;
3939 qemu_system_reset();
3940 ret = EXCP_INTERRUPT;
3942 if (powerdown_requested) {
3943 powerdown_requested = 0;
3944 qemu_system_powerdown();
3945 ret = EXCP_INTERRUPT;
3947 if (unlikely(ret == EXCP_DEBUG)) {
3948 gdb_set_stop_cpu(cur_cpu);
3949 vm_stop(EXCP_DEBUG);
3951 /* If all cpus are halted then wait until the next IRQ */
3952 /* XXX: use timeout computed from timers */
3953 if (ret == EXCP_HALTED) {
3957 /* Advance virtual time to the next event. */
3958 if (use_icount == 1) {
3959 /* When not using an adaptive execution frequency
3960 we tend to get badly out of sync with real time,
3961 so just delay for a reasonable amount of time. */
3964 delta = cpu_get_icount() - cpu_get_clock();
3967 /* If virtual time is ahead of real time then just
3969 timeout = (delta / 1000000) + 1;
3971 /* Wait for either IO to occur or the next
3973 add = qemu_next_deadline();
3974 /* We advance the timer before checking for IO.
3975 Limit the amount we advance so that early IO
3976 activity won't get the guest too far ahead. */
3980 add = (add + (1 << icount_time_shift) - 1)
3981 >> icount_time_shift;
3983 timeout = delta / 1000000;
3994 if (shutdown_requested) {
3995 ret = EXCP_INTERRUPT;
4000 #ifdef CONFIG_PROFILER
4001 ti = profile_getclock();
4003 main_loop_wait(timeout);
4004 #ifdef CONFIG_PROFILER
4005 dev_time += profile_getclock() - ti;
4008 cpu_disable_ticks();
4012 static void version(void)
4014 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4017 static void help(int exitcode)
4020 printf("usage: %s [options] [disk_image]\n"
4022 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4024 #define DEF(option, opt_arg, opt_enum, opt_help) \
4026 #define DEFHEADING(text) stringify(text) "\n"
4027 #include "qemu-options.h"
4032 "During emulation, the following keys are useful:\n"
4033 "ctrl-alt-f toggle full screen\n"
4034 "ctrl-alt-n switch to virtual console 'n'\n"
4035 "ctrl-alt toggle mouse and keyboard grab\n"
4037 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4042 DEFAULT_NETWORK_SCRIPT,
4043 DEFAULT_NETWORK_DOWN_SCRIPT,
4045 DEFAULT_GDBSTUB_PORT,
4050 #define HAS_ARG 0x0001
4053 #define DEF(option, opt_arg, opt_enum, opt_help) \
4055 #define DEFHEADING(text)
4056 #include "qemu-options.h"
4062 typedef struct QEMUOption {
4068 static const QEMUOption qemu_options[] = {
4069 { "h", 0, QEMU_OPTION_h },
4070 #define DEF(option, opt_arg, opt_enum, opt_help) \
4071 { option, opt_arg, opt_enum },
4072 #define DEFHEADING(text)
4073 #include "qemu-options.h"
4081 struct soundhw soundhw[] = {
4082 #ifdef HAS_AUDIO_CHOICE
4083 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4089 { .init_isa = pcspk_audio_init }
4096 "Creative Sound Blaster 16",
4099 { .init_isa = SB16_init }
4103 #ifdef CONFIG_CS4231A
4109 { .init_isa = cs4231a_init }
4117 "Yamaha YMF262 (OPL3)",
4119 "Yamaha YM3812 (OPL2)",
4123 { .init_isa = Adlib_init }
4130 "Gravis Ultrasound GF1",
4133 { .init_isa = GUS_init }
4140 "Intel 82801AA AC97 Audio",
4143 { .init_pci = ac97_init }
4147 #ifdef CONFIG_ES1370
4150 "ENSONIQ AudioPCI ES1370",
4153 { .init_pci = es1370_init }
4157 #endif /* HAS_AUDIO_CHOICE */
4159 { NULL, NULL, 0, 0, { NULL } }
4162 static void select_soundhw (const char *optarg)
4166 if (*optarg == '?') {
4169 printf ("Valid sound card names (comma separated):\n");
4170 for (c = soundhw; c->name; ++c) {
4171 printf ("%-11s %s\n", c->name, c->descr);
4173 printf ("\n-soundhw all will enable all of the above\n");
4174 exit (*optarg != '?');
4182 if (!strcmp (optarg, "all")) {
4183 for (c = soundhw; c->name; ++c) {
4191 e = strchr (p, ',');
4192 l = !e ? strlen (p) : (size_t) (e - p);
4194 for (c = soundhw; c->name; ++c) {
4195 if (!strncmp (c->name, p, l)) {
4204 "Unknown sound card name (too big to show)\n");
4207 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4212 p += l + (e != NULL);
4216 goto show_valid_cards;
4221 static void select_vgahw (const char *p)
4225 cirrus_vga_enabled = 0;
4226 std_vga_enabled = 0;
4228 if (strstart(p, "std", &opts)) {
4229 std_vga_enabled = 1;
4230 } else if (strstart(p, "cirrus", &opts)) {
4231 cirrus_vga_enabled = 1;
4232 } else if (strstart(p, "vmware", &opts)) {
4234 } else if (!strstart(p, "none", &opts)) {
4236 fprintf(stderr, "Unknown vga type: %s\n", p);
4240 const char *nextopt;
4242 if (strstart(opts, ",retrace=", &nextopt)) {
4244 if (strstart(opts, "dumb", &nextopt))
4245 vga_retrace_method = VGA_RETRACE_DUMB;
4246 else if (strstart(opts, "precise", &nextopt))
4247 vga_retrace_method = VGA_RETRACE_PRECISE;
4248 else goto invalid_vga;
4249 } else goto invalid_vga;
4255 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4257 exit(STATUS_CONTROL_C_EXIT);
4262 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4266 if(strlen(str) != 36)
4269 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4270 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4271 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4277 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4283 #define MAX_NET_CLIENTS 32
4287 static void termsig_handler(int signal)
4289 qemu_system_shutdown_request();
4292 static void termsig_setup(void)
4294 struct sigaction act;
4296 memset(&act, 0, sizeof(act));
4297 act.sa_handler = termsig_handler;
4298 sigaction(SIGINT, &act, NULL);
4299 sigaction(SIGHUP, &act, NULL);
4300 sigaction(SIGTERM, &act, NULL);
4305 int main(int argc, char **argv, char **envp)
4307 #ifdef CONFIG_GDBSTUB
4308 const char *gdbstub_dev = NULL;
4310 uint32_t boot_devices_bitmap = 0;
4312 int snapshot, linux_boot, net_boot;
4313 const char *initrd_filename;
4314 const char *kernel_filename, *kernel_cmdline;
4315 const char *boot_devices = "";
4317 DisplayChangeListener *dcl;
4318 int cyls, heads, secs, translation;
4319 const char *net_clients[MAX_NET_CLIENTS];
4321 const char *bt_opts[MAX_BT_CMDLINE];
4325 const char *r, *optarg;
4326 CharDriverState *monitor_hd = NULL;
4327 const char *monitor_device;
4328 const char *serial_devices[MAX_SERIAL_PORTS];
4329 int serial_device_index;
4330 const char *parallel_devices[MAX_PARALLEL_PORTS];
4331 int parallel_device_index;
4332 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4333 int virtio_console_index;
4334 const char *loadvm = NULL;
4335 QEMUMachine *machine;
4336 const char *cpu_model;
4337 const char *usb_devices[MAX_USB_CMDLINE];
4338 int usb_devices_index;
4343 const char *pid_file = NULL;
4344 const char *incoming = NULL;
4347 struct passwd *pwd = NULL;
4348 const char *chroot_dir = NULL;
4349 const char *run_as = NULL;
4353 qemu_cache_utils_init(envp);
4355 LIST_INIT (&vm_change_state_head);
4358 struct sigaction act;
4359 sigfillset(&act.sa_mask);
4361 act.sa_handler = SIG_IGN;
4362 sigaction(SIGPIPE, &act, NULL);
4365 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4366 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4367 QEMU to run on a single CPU */
4372 h = GetCurrentProcess();
4373 if (GetProcessAffinityMask(h, &mask, &smask)) {
4374 for(i = 0; i < 32; i++) {
4375 if (mask & (1 << i))
4380 SetProcessAffinityMask(h, mask);
4386 register_machines();
4387 machine = first_machine;
4389 initrd_filename = NULL;
4391 vga_ram_size = VGA_RAM_SIZE;
4395 kernel_filename = NULL;
4396 kernel_cmdline = "";
4397 cyls = heads = secs = 0;
4398 translation = BIOS_ATA_TRANSLATION_AUTO;
4399 monitor_device = "vc:80Cx24C";
4401 serial_devices[0] = "vc:80Cx24C";
4402 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4403 serial_devices[i] = NULL;
4404 serial_device_index = 0;
4406 parallel_devices[0] = "vc:80Cx24C";
4407 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4408 parallel_devices[i] = NULL;
4409 parallel_device_index = 0;
4411 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4412 virtio_consoles[i] = NULL;
4413 virtio_console_index = 0;
4415 for (i = 0; i < MAX_NODES; i++) {
4417 node_cpumask[i] = 0;
4420 usb_devices_index = 0;
4440 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4442 const QEMUOption *popt;
4445 /* Treat --foo the same as -foo. */
4448 popt = qemu_options;
4451 fprintf(stderr, "%s: invalid option -- '%s'\n",
4455 if (!strcmp(popt->name, r + 1))
4459 if (popt->flags & HAS_ARG) {
4460 if (optind >= argc) {
4461 fprintf(stderr, "%s: option '%s' requires an argument\n",
4465 optarg = argv[optind++];
4470 switch(popt->index) {
4472 machine = find_machine(optarg);
4475 printf("Supported machines are:\n");
4476 for(m = first_machine; m != NULL; m = m->next) {
4477 printf("%-10s %s%s\n",
4479 m == first_machine ? " (default)" : "");
4481 exit(*optarg != '?');
4484 case QEMU_OPTION_cpu:
4485 /* hw initialization will check this */
4486 if (*optarg == '?') {
4487 /* XXX: implement xxx_cpu_list for targets that still miss it */
4488 #if defined(cpu_list)
4489 cpu_list(stdout, &fprintf);
4496 case QEMU_OPTION_initrd:
4497 initrd_filename = optarg;
4499 case QEMU_OPTION_hda:
4501 hda_index = drive_add(optarg, HD_ALIAS, 0);
4503 hda_index = drive_add(optarg, HD_ALIAS
4504 ",cyls=%d,heads=%d,secs=%d%s",
4505 0, cyls, heads, secs,
4506 translation == BIOS_ATA_TRANSLATION_LBA ?
4508 translation == BIOS_ATA_TRANSLATION_NONE ?
4509 ",trans=none" : "");
4511 case QEMU_OPTION_hdb:
4512 case QEMU_OPTION_hdc:
4513 case QEMU_OPTION_hdd:
4514 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4516 case QEMU_OPTION_drive:
4517 drive_add(NULL, "%s", optarg);
4519 case QEMU_OPTION_mtdblock:
4520 drive_add(optarg, MTD_ALIAS);
4522 case QEMU_OPTION_sd:
4523 drive_add(optarg, SD_ALIAS);
4525 case QEMU_OPTION_pflash:
4526 drive_add(optarg, PFLASH_ALIAS);
4528 case QEMU_OPTION_snapshot:
4531 case QEMU_OPTION_hdachs:
4535 cyls = strtol(p, (char **)&p, 0);
4536 if (cyls < 1 || cyls > 16383)
4541 heads = strtol(p, (char **)&p, 0);
4542 if (heads < 1 || heads > 16)
4547 secs = strtol(p, (char **)&p, 0);
4548 if (secs < 1 || secs > 63)
4552 if (!strcmp(p, "none"))
4553 translation = BIOS_ATA_TRANSLATION_NONE;
4554 else if (!strcmp(p, "lba"))
4555 translation = BIOS_ATA_TRANSLATION_LBA;
4556 else if (!strcmp(p, "auto"))
4557 translation = BIOS_ATA_TRANSLATION_AUTO;
4560 } else if (*p != '\0') {
4562 fprintf(stderr, "qemu: invalid physical CHS format\n");
4565 if (hda_index != -1)
4566 snprintf(drives_opt[hda_index].opt,
4567 sizeof(drives_opt[hda_index].opt),
4568 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4569 0, cyls, heads, secs,
4570 translation == BIOS_ATA_TRANSLATION_LBA ?
4572 translation == BIOS_ATA_TRANSLATION_NONE ?
4573 ",trans=none" : "");
4576 case QEMU_OPTION_numa:
4577 if (nb_numa_nodes >= MAX_NODES) {
4578 fprintf(stderr, "qemu: too many NUMA nodes\n");
4583 case QEMU_OPTION_nographic:
4586 #ifdef CONFIG_CURSES
4587 case QEMU_OPTION_curses:
4591 case QEMU_OPTION_portrait:
4594 case QEMU_OPTION_kernel:
4595 kernel_filename = optarg;
4597 case QEMU_OPTION_append:
4598 kernel_cmdline = optarg;
4600 case QEMU_OPTION_cdrom:
4601 drive_add(optarg, CDROM_ALIAS);
4603 case QEMU_OPTION_boot:
4604 boot_devices = optarg;
4605 /* We just do some generic consistency checks */
4607 /* Could easily be extended to 64 devices if needed */
4610 boot_devices_bitmap = 0;
4611 for (p = boot_devices; *p != '\0'; p++) {
4612 /* Allowed boot devices are:
4613 * a b : floppy disk drives
4614 * c ... f : IDE disk drives
4615 * g ... m : machine implementation dependant drives
4616 * n ... p : network devices
4617 * It's up to each machine implementation to check
4618 * if the given boot devices match the actual hardware
4619 * implementation and firmware features.
4621 if (*p < 'a' || *p > 'q') {
4622 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4625 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4627 "Boot device '%c' was given twice\n",*p);
4630 boot_devices_bitmap |= 1 << (*p - 'a');
4634 case QEMU_OPTION_fda:
4635 case QEMU_OPTION_fdb:
4636 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4639 case QEMU_OPTION_no_fd_bootchk:
4643 case QEMU_OPTION_net:
4644 if (nb_net_clients >= MAX_NET_CLIENTS) {
4645 fprintf(stderr, "qemu: too many network clients\n");
4648 net_clients[nb_net_clients] = optarg;
4652 case QEMU_OPTION_tftp:
4653 tftp_prefix = optarg;
4655 case QEMU_OPTION_bootp:
4656 bootp_filename = optarg;
4659 case QEMU_OPTION_smb:
4660 net_slirp_smb(optarg);
4663 case QEMU_OPTION_redir:
4664 net_slirp_redir(NULL, optarg);
4667 case QEMU_OPTION_bt:
4668 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4669 fprintf(stderr, "qemu: too many bluetooth options\n");
4672 bt_opts[nb_bt_opts++] = optarg;
4675 case QEMU_OPTION_audio_help:
4679 case QEMU_OPTION_soundhw:
4680 select_soundhw (optarg);
4686 case QEMU_OPTION_version:
4690 case QEMU_OPTION_m: {
4694 value = strtoul(optarg, &ptr, 10);
4696 case 0: case 'M': case 'm':
4703 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4707 /* On 32-bit hosts, QEMU is limited by virtual address space */
4708 if (value > (2047 << 20)
4709 #ifndef CONFIG_KQEMU
4710 && HOST_LONG_BITS == 32
4713 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4716 if (value != (uint64_t)(ram_addr_t)value) {
4717 fprintf(stderr, "qemu: ram size too large\n");
4726 const CPULogItem *item;
4728 mask = cpu_str_to_log_mask(optarg);
4730 printf("Log items (comma separated):\n");
4731 for(item = cpu_log_items; item->mask != 0; item++) {
4732 printf("%-10s %s\n", item->name, item->help);
4739 #ifdef CONFIG_GDBSTUB
4741 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
4743 case QEMU_OPTION_gdb:
4744 gdbstub_dev = optarg;
4750 case QEMU_OPTION_bios:
4753 case QEMU_OPTION_singlestep:
4761 keyboard_layout = optarg;
4764 case QEMU_OPTION_localtime:
4767 case QEMU_OPTION_vga:
4768 select_vgahw (optarg);
4770 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4776 w = strtol(p, (char **)&p, 10);
4779 fprintf(stderr, "qemu: invalid resolution or depth\n");
4785 h = strtol(p, (char **)&p, 10);
4790 depth = strtol(p, (char **)&p, 10);
4791 if (depth != 8 && depth != 15 && depth != 16 &&
4792 depth != 24 && depth != 32)
4794 } else if (*p == '\0') {
4795 depth = graphic_depth;
4802 graphic_depth = depth;
4806 case QEMU_OPTION_echr:
4809 term_escape_char = strtol(optarg, &r, 0);
4811 printf("Bad argument to echr\n");
4814 case QEMU_OPTION_monitor:
4815 monitor_device = optarg;
4817 case QEMU_OPTION_serial:
4818 if (serial_device_index >= MAX_SERIAL_PORTS) {
4819 fprintf(stderr, "qemu: too many serial ports\n");
4822 serial_devices[serial_device_index] = optarg;
4823 serial_device_index++;
4825 case QEMU_OPTION_virtiocon:
4826 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
4827 fprintf(stderr, "qemu: too many virtio consoles\n");
4830 virtio_consoles[virtio_console_index] = optarg;
4831 virtio_console_index++;
4833 case QEMU_OPTION_parallel:
4834 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4835 fprintf(stderr, "qemu: too many parallel ports\n");
4838 parallel_devices[parallel_device_index] = optarg;
4839 parallel_device_index++;
4841 case QEMU_OPTION_loadvm:
4844 case QEMU_OPTION_full_screen:
4848 case QEMU_OPTION_no_frame:
4851 case QEMU_OPTION_alt_grab:
4854 case QEMU_OPTION_no_quit:
4857 case QEMU_OPTION_sdl:
4861 case QEMU_OPTION_pidfile:
4865 case QEMU_OPTION_win2k_hack:
4866 win2k_install_hack = 1;
4868 case QEMU_OPTION_rtc_td_hack:
4871 case QEMU_OPTION_acpitable:
4872 if(acpi_table_add(optarg) < 0) {
4873 fprintf(stderr, "Wrong acpi table provided\n");
4877 case QEMU_OPTION_smbios:
4878 if(smbios_entry_add(optarg) < 0) {
4879 fprintf(stderr, "Wrong smbios provided\n");
4885 case QEMU_OPTION_no_kqemu:
4888 case QEMU_OPTION_kernel_kqemu:
4893 case QEMU_OPTION_enable_kvm:
4900 case QEMU_OPTION_usb:
4903 case QEMU_OPTION_usbdevice:
4905 if (usb_devices_index >= MAX_USB_CMDLINE) {
4906 fprintf(stderr, "Too many USB devices\n");
4909 usb_devices[usb_devices_index] = optarg;
4910 usb_devices_index++;
4912 case QEMU_OPTION_smp:
4913 smp_cpus = atoi(optarg);
4915 fprintf(stderr, "Invalid number of CPUs\n");
4919 case QEMU_OPTION_vnc:
4920 vnc_display = optarg;
4923 case QEMU_OPTION_no_acpi:
4926 case QEMU_OPTION_no_hpet:
4930 case QEMU_OPTION_no_reboot:
4933 case QEMU_OPTION_no_shutdown:
4936 case QEMU_OPTION_show_cursor:
4939 case QEMU_OPTION_uuid:
4940 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
4941 fprintf(stderr, "Fail to parse UUID string."
4942 " Wrong format.\n");
4947 case QEMU_OPTION_daemonize:
4951 case QEMU_OPTION_option_rom:
4952 if (nb_option_roms >= MAX_OPTION_ROMS) {
4953 fprintf(stderr, "Too many option ROMs\n");
4956 option_rom[nb_option_roms] = optarg;
4959 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4960 case QEMU_OPTION_semihosting:
4961 semihosting_enabled = 1;
4964 case QEMU_OPTION_name:
4967 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4968 case QEMU_OPTION_prom_env:
4969 if (nb_prom_envs >= MAX_PROM_ENVS) {
4970 fprintf(stderr, "Too many prom variables\n");
4973 prom_envs[nb_prom_envs] = optarg;
4978 case QEMU_OPTION_old_param:
4982 case QEMU_OPTION_clock:
4983 configure_alarms(optarg);
4985 case QEMU_OPTION_startdate:
4988 time_t rtc_start_date;
4989 if (!strcmp(optarg, "now")) {
4990 rtc_date_offset = -1;
4992 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5000 } else if (sscanf(optarg, "%d-%d-%d",
5003 &tm.tm_mday) == 3) {
5012 rtc_start_date = mktimegm(&tm);
5013 if (rtc_start_date == -1) {
5015 fprintf(stderr, "Invalid date format. Valid format are:\n"
5016 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5019 rtc_date_offset = time(NULL) - rtc_start_date;
5023 case QEMU_OPTION_tb_size:
5024 tb_size = strtol(optarg, NULL, 0);
5028 case QEMU_OPTION_icount:
5030 if (strcmp(optarg, "auto") == 0) {
5031 icount_time_shift = -1;
5033 icount_time_shift = strtol(optarg, NULL, 0);
5036 case QEMU_OPTION_incoming:
5040 case QEMU_OPTION_chroot:
5041 chroot_dir = optarg;
5043 case QEMU_OPTION_runas:
5048 case QEMU_OPTION_xen_domid:
5049 xen_domid = atoi(optarg);
5051 case QEMU_OPTION_xen_create:
5052 xen_mode = XEN_CREATE;
5054 case QEMU_OPTION_xen_attach:
5055 xen_mode = XEN_ATTACH;
5062 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5063 if (kvm_allowed && kqemu_allowed) {
5065 "You can not enable both KVM and kqemu at the same time\n");
5070 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5071 if (smp_cpus > machine->max_cpus) {
5072 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5073 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5079 if (serial_device_index == 0)
5080 serial_devices[0] = "stdio";
5081 if (parallel_device_index == 0)
5082 parallel_devices[0] = "null";
5083 if (strncmp(monitor_device, "vc", 2) == 0)
5084 monitor_device = "stdio";
5091 if (pipe(fds) == -1)
5102 len = read(fds[0], &status, 1);
5103 if (len == -1 && (errno == EINTR))
5108 else if (status == 1) {
5109 fprintf(stderr, "Could not acquire pidfile\n");
5126 signal(SIGTSTP, SIG_IGN);
5127 signal(SIGTTOU, SIG_IGN);
5128 signal(SIGTTIN, SIG_IGN);
5131 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5134 write(fds[1], &status, 1);
5136 fprintf(stderr, "Could not acquire pid file\n");
5145 linux_boot = (kernel_filename != NULL);
5146 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5148 if (!linux_boot && *kernel_cmdline != '\0') {
5149 fprintf(stderr, "-append only allowed with -kernel option\n");
5153 if (!linux_boot && initrd_filename != NULL) {
5154 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5158 /* boot to floppy or the default cd if no hard disk defined yet */
5159 if (!boot_devices[0]) {
5160 boot_devices = "cad";
5162 setvbuf(stdout, NULL, _IOLBF, 0);
5165 if (init_timer_alarm() < 0) {
5166 fprintf(stderr, "could not initialize alarm timer\n");
5169 if (use_icount && icount_time_shift < 0) {
5171 /* 125MIPS seems a reasonable initial guess at the guest speed.
5172 It will be corrected fairly quickly anyway. */
5173 icount_time_shift = 3;
5174 init_icount_adjust();
5181 /* init network clients */
5182 if (nb_net_clients == 0) {
5183 /* if no clients, we use a default config */
5184 net_clients[nb_net_clients++] = "nic";
5186 net_clients[nb_net_clients++] = "user";
5190 for(i = 0;i < nb_net_clients; i++) {
5191 if (net_client_parse(net_clients[i]) < 0)
5197 /* XXX: this should be moved in the PC machine instantiation code */
5198 if (net_boot != 0) {
5200 for (i = 0; i < nb_nics && i < 4; i++) {
5201 const char *model = nd_table[i].model;
5203 if (net_boot & (1 << i)) {
5206 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5207 if (get_image_size(buf) > 0) {
5208 if (nb_option_roms >= MAX_OPTION_ROMS) {
5209 fprintf(stderr, "Too many option ROMs\n");
5212 option_rom[nb_option_roms] = strdup(buf);
5219 fprintf(stderr, "No valid PXE rom found for network device\n");
5225 /* init the bluetooth world */
5226 for (i = 0; i < nb_bt_opts; i++)
5227 if (bt_parse(bt_opts[i]))
5230 /* init the memory */
5232 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5235 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5236 guest ram allocation. It needs to go away. */
5237 if (kqemu_allowed) {
5238 kqemu_phys_ram_size = ram_size + VGA_RAM_SIZE + 4 * 1024 * 1024;
5239 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5240 if (!kqemu_phys_ram_base) {
5241 fprintf(stderr, "Could not allocate physical memory\n");
5247 /* init the dynamic translator */
5248 cpu_exec_init_all(tb_size * 1024 * 1024);
5253 /* we always create the cdrom drive, even if no disk is there */
5255 if (nb_drives_opt < MAX_DRIVES)
5256 drive_add(NULL, CDROM_ALIAS);
5258 /* we always create at least one floppy */
5260 if (nb_drives_opt < MAX_DRIVES)
5261 drive_add(NULL, FD_ALIAS, 0);
5263 /* we always create one sd slot, even if no card is in it */
5265 if (nb_drives_opt < MAX_DRIVES)
5266 drive_add(NULL, SD_ALIAS);
5268 /* open the virtual block devices */
5270 for(i = 0; i < nb_drives_opt; i++)
5271 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5274 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5275 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5278 /* must be after terminal init, SDL library changes signal handlers */
5282 /* Maintain compatibility with multiple stdio monitors */
5283 if (!strcmp(monitor_device,"stdio")) {
5284 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5285 const char *devname = serial_devices[i];
5286 if (devname && !strcmp(devname,"mon:stdio")) {
5287 monitor_device = NULL;
5289 } else if (devname && !strcmp(devname,"stdio")) {
5290 monitor_device = NULL;
5291 serial_devices[i] = "mon:stdio";
5297 if (nb_numa_nodes > 0) {
5300 if (nb_numa_nodes > smp_cpus) {
5301 nb_numa_nodes = smp_cpus;
5304 /* If no memory size if given for any node, assume the default case
5305 * and distribute the available memory equally across all nodes
5307 for (i = 0; i < nb_numa_nodes; i++) {
5308 if (node_mem[i] != 0)
5311 if (i == nb_numa_nodes) {
5312 uint64_t usedmem = 0;
5314 /* On Linux, the each node's border has to be 8MB aligned,
5315 * the final node gets the rest.
5317 for (i = 0; i < nb_numa_nodes - 1; i++) {
5318 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5319 usedmem += node_mem[i];
5321 node_mem[i] = ram_size - usedmem;
5324 for (i = 0; i < nb_numa_nodes; i++) {
5325 if (node_cpumask[i] != 0)
5328 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5329 * must cope with this anyway, because there are BIOSes out there in
5330 * real machines which also use this scheme.
5332 if (i == nb_numa_nodes) {
5333 for (i = 0; i < smp_cpus; i++) {
5334 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5339 if (kvm_enabled()) {
5342 ret = kvm_init(smp_cpus);
5344 fprintf(stderr, "failed to initialize KVM\n");
5349 if (monitor_device) {
5350 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5352 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5357 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5358 const char *devname = serial_devices[i];
5359 if (devname && strcmp(devname, "none")) {
5361 snprintf(label, sizeof(label), "serial%d", i);
5362 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5363 if (!serial_hds[i]) {
5364 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5371 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5372 const char *devname = parallel_devices[i];
5373 if (devname && strcmp(devname, "none")) {
5375 snprintf(label, sizeof(label), "parallel%d", i);
5376 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5377 if (!parallel_hds[i]) {
5378 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5385 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5386 const char *devname = virtio_consoles[i];
5387 if (devname && strcmp(devname, "none")) {
5389 snprintf(label, sizeof(label), "virtcon%d", i);
5390 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5391 if (!virtcon_hds[i]) {
5392 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5399 machine->init(ram_size, vga_ram_size, boot_devices,
5400 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5403 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5404 for (i = 0; i < nb_numa_nodes; i++) {
5405 if (node_cpumask[i] & (1 << env->cpu_index)) {
5411 current_machine = machine;
5413 /* Set KVM's vcpu state to qemu's initial CPUState. */
5414 if (kvm_enabled()) {
5417 ret = kvm_sync_vcpus();
5419 fprintf(stderr, "failed to initialize vcpus\n");
5424 /* init USB devices */
5426 for(i = 0; i < usb_devices_index; i++) {
5427 if (usb_device_add(usb_devices[i], 0) < 0) {
5428 fprintf(stderr, "Warning: could not add USB device %s\n",
5435 dumb_display_init();
5436 /* just use the first displaystate for the moment */
5441 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5445 #if defined(CONFIG_CURSES)
5447 /* At the moment curses cannot be used with other displays */
5448 curses_display_init(ds, full_screen);
5452 if (vnc_display != NULL) {
5453 vnc_display_init(ds);
5454 if (vnc_display_open(ds, vnc_display) < 0)
5457 #if defined(CONFIG_SDL)
5458 if (sdl || !vnc_display)
5459 sdl_display_init(ds, full_screen, no_frame);
5460 #elif defined(CONFIG_COCOA)
5461 if (sdl || !vnc_display)
5462 cocoa_display_init(ds, full_screen);
5468 dcl = ds->listeners;
5469 while (dcl != NULL) {
5470 if (dcl->dpy_refresh != NULL) {
5471 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5472 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5477 if (nographic || (vnc_display && !sdl)) {
5478 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5479 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5482 text_consoles_set_display(display_state);
5483 qemu_chr_initial_reset();
5485 if (monitor_device && monitor_hd)
5486 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
5488 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5489 const char *devname = serial_devices[i];
5490 if (devname && strcmp(devname, "none")) {
5492 snprintf(label, sizeof(label), "serial%d", i);
5493 if (strstart(devname, "vc", 0))
5494 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5498 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5499 const char *devname = parallel_devices[i];
5500 if (devname && strcmp(devname, "none")) {
5502 snprintf(label, sizeof(label), "parallel%d", i);
5503 if (strstart(devname, "vc", 0))
5504 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5508 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5509 const char *devname = virtio_consoles[i];
5510 if (virtcon_hds[i] && devname) {
5512 snprintf(label, sizeof(label), "virtcon%d", i);
5513 if (strstart(devname, "vc", 0))
5514 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5518 #ifdef CONFIG_GDBSTUB
5519 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5520 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5527 do_loadvm(cur_mon, loadvm);
5530 autostart = 0; /* fixme how to deal with -daemonize */
5531 qemu_start_incoming_migration(incoming);
5543 len = write(fds[1], &status, 1);
5544 if (len == -1 && (errno == EINTR))
5551 TFR(fd = open("/dev/null", O_RDWR));
5557 pwd = getpwnam(run_as);
5559 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5565 if (chroot(chroot_dir) < 0) {
5566 fprintf(stderr, "chroot failed\n");
5573 if (setgid(pwd->pw_gid) < 0) {
5574 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5577 if (setuid(pwd->pw_uid) < 0) {
5578 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5581 if (setuid(0) != -1) {
5582 fprintf(stderr, "Dropping privileges failed\n");