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
25 #include "hw/boards.h"
27 #include "hw/pcmcia.h"
29 #include "hw/audiodev.h"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
40 #include "audio/audio.h"
41 #include "migration.h"
53 #include <sys/times.h>
57 #include <sys/ioctl.h>
58 #include <sys/resource.h>
59 #include <sys/socket.h>
60 #include <netinet/in.h>
62 #if defined(__NetBSD__)
63 #include <net/if_tap.h>
66 #include <linux/if_tun.h>
68 #include <arpa/inet.h>
71 #include <sys/select.h>
79 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
80 #include <freebsd/stdlib.h>
85 #include <linux/rtc.h>
87 /* For the benefit of older linux systems which don't supply it,
88 we use a local copy of hpet.h. */
89 /* #include <linux/hpet.h> */
92 #include <linux/ppdev.h>
93 #include <linux/parport.h>
97 #include <sys/ethernet.h>
98 #include <sys/sockio.h>
99 #include <netinet/arp.h>
100 #include <netinet/in.h>
101 #include <netinet/in_systm.h>
102 #include <netinet/ip.h>
103 #include <netinet/ip_icmp.h> // must come after ip.h
104 #include <netinet/udp.h>
105 #include <netinet/tcp.h>
113 #include "qemu_socket.h"
115 #if defined(CONFIG_SLIRP)
116 #include "libslirp.h"
119 #if defined(__OpenBSD__)
123 #if defined(CONFIG_VDE)
124 #include <libvdeplug.h>
129 #include <sys/timeb.h>
130 #include <mmsystem.h>
131 #define getopt_long_only getopt_long
132 #define memalign(align, size) malloc(size)
139 #endif /* CONFIG_SDL */
143 #define main qemu_main
144 #endif /* CONFIG_COCOA */
148 #include "exec-all.h"
150 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
151 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
153 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
155 #define SMBD_COMMAND "/usr/sbin/smbd"
158 //#define DEBUG_UNUSED_IOPORT
159 //#define DEBUG_IOPORT
161 //#define DEBUG_SLIRP
164 #define DEFAULT_RAM_SIZE 144
166 #define DEFAULT_RAM_SIZE 128
169 /* Max number of USB devices that can be specified on the commandline. */
170 #define MAX_USB_CMDLINE 8
172 /* XXX: use a two level table to limit memory usage */
173 #define MAX_IOPORTS 65536
175 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
176 const char *bios_name = NULL;
177 static void *ioport_opaque[MAX_IOPORTS];
178 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
179 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
180 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
181 to store the VM snapshots */
182 DriveInfo drives_table[MAX_DRIVES+1];
184 /* point to the block driver where the snapshots are managed */
185 static BlockDriverState *bs_snapshots;
186 static int vga_ram_size;
187 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
188 DisplayState display_state;
191 const char* keyboard_layout = NULL;
192 int64_t ticks_per_sec;
195 NICInfo nd_table[MAX_NICS];
197 static int rtc_utc = 1;
198 static int rtc_date_offset = -1; /* -1 means no change */
199 int cirrus_vga_enabled = 1;
200 int vmsvga_enabled = 0;
202 int graphic_width = 1024;
203 int graphic_height = 768;
204 int graphic_depth = 8;
206 int graphic_width = 800;
207 int graphic_height = 600;
208 int graphic_depth = 15;
210 static int full_screen = 0;
211 static int no_frame = 0;
213 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
214 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
216 int win2k_install_hack = 0;
220 const char *vnc_display;
221 int acpi_enabled = 1;
226 int graphic_rotate = 0;
228 const char *option_rom[MAX_OPTION_ROMS];
230 int semihosting_enabled = 0;
234 const char *qemu_name;
237 unsigned int nb_prom_envs = 0;
238 const char *prom_envs[MAX_PROM_ENVS];
240 static int nb_drives_opt;
241 static struct drive_opt {
244 } drives_opt[MAX_DRIVES];
246 static CPUState *cur_cpu;
247 static CPUState *next_cpu;
248 static int event_pending = 1;
249 /* Conversion factor from emulated instructions to virtual clock ticks. */
250 static int icount_time_shift;
251 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
252 #define MAX_ICOUNT_SHIFT 10
253 /* Compensate for varying guest execution speed. */
254 static int64_t qemu_icount_bias;
255 static QEMUTimer *icount_rt_timer;
256 static QEMUTimer *icount_vm_timer;
258 uint8_t qemu_uuid[16];
260 /***********************************************************/
261 /* x86 ISA bus support */
263 target_phys_addr_t isa_mem_base = 0;
266 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
267 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
269 static uint32_t ioport_read(int index, uint32_t address)
271 static IOPortReadFunc *default_func[3] = {
272 default_ioport_readb,
273 default_ioport_readw,
276 IOPortReadFunc *func = ioport_read_table[index][address];
278 func = default_func[index];
279 return func(ioport_opaque[address], address);
282 static void ioport_write(int index, uint32_t address, uint32_t data)
284 static IOPortWriteFunc *default_func[3] = {
285 default_ioport_writeb,
286 default_ioport_writew,
287 default_ioport_writel
289 IOPortWriteFunc *func = ioport_write_table[index][address];
291 func = default_func[index];
292 func(ioport_opaque[address], address, data);
295 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
297 #ifdef DEBUG_UNUSED_IOPORT
298 fprintf(stderr, "unused inb: port=0x%04x\n", address);
303 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
305 #ifdef DEBUG_UNUSED_IOPORT
306 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
310 /* default is to make two byte accesses */
311 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
314 data = ioport_read(0, address);
315 address = (address + 1) & (MAX_IOPORTS - 1);
316 data |= ioport_read(0, address) << 8;
320 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
322 ioport_write(0, address, data & 0xff);
323 address = (address + 1) & (MAX_IOPORTS - 1);
324 ioport_write(0, address, (data >> 8) & 0xff);
327 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
329 #ifdef DEBUG_UNUSED_IOPORT
330 fprintf(stderr, "unused inl: port=0x%04x\n", address);
335 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
337 #ifdef DEBUG_UNUSED_IOPORT
338 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
342 /* size is the word size in byte */
343 int register_ioport_read(int start, int length, int size,
344 IOPortReadFunc *func, void *opaque)
350 } else if (size == 2) {
352 } else if (size == 4) {
355 hw_error("register_ioport_read: invalid size");
358 for(i = start; i < start + length; i += size) {
359 ioport_read_table[bsize][i] = func;
360 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
361 hw_error("register_ioport_read: invalid opaque");
362 ioport_opaque[i] = opaque;
367 /* size is the word size in byte */
368 int register_ioport_write(int start, int length, int size,
369 IOPortWriteFunc *func, void *opaque)
375 } else if (size == 2) {
377 } else if (size == 4) {
380 hw_error("register_ioport_write: invalid size");
383 for(i = start; i < start + length; i += size) {
384 ioport_write_table[bsize][i] = func;
385 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
386 hw_error("register_ioport_write: invalid opaque");
387 ioport_opaque[i] = opaque;
392 void isa_unassign_ioport(int start, int length)
396 for(i = start; i < start + length; i++) {
397 ioport_read_table[0][i] = default_ioport_readb;
398 ioport_read_table[1][i] = default_ioport_readw;
399 ioport_read_table[2][i] = default_ioport_readl;
401 ioport_write_table[0][i] = default_ioport_writeb;
402 ioport_write_table[1][i] = default_ioport_writew;
403 ioport_write_table[2][i] = default_ioport_writel;
407 /***********************************************************/
409 void cpu_outb(CPUState *env, int addr, int val)
412 if (loglevel & CPU_LOG_IOPORT)
413 fprintf(logfile, "outb: %04x %02x\n", addr, val);
415 ioport_write(0, addr, val);
418 env->last_io_time = cpu_get_time_fast();
422 void cpu_outw(CPUState *env, int addr, int val)
425 if (loglevel & CPU_LOG_IOPORT)
426 fprintf(logfile, "outw: %04x %04x\n", addr, val);
428 ioport_write(1, addr, val);
431 env->last_io_time = cpu_get_time_fast();
435 void cpu_outl(CPUState *env, int addr, int val)
438 if (loglevel & CPU_LOG_IOPORT)
439 fprintf(logfile, "outl: %04x %08x\n", addr, val);
441 ioport_write(2, addr, val);
444 env->last_io_time = cpu_get_time_fast();
448 int cpu_inb(CPUState *env, int addr)
451 val = ioport_read(0, addr);
453 if (loglevel & CPU_LOG_IOPORT)
454 fprintf(logfile, "inb : %04x %02x\n", addr, val);
458 env->last_io_time = cpu_get_time_fast();
463 int cpu_inw(CPUState *env, int addr)
466 val = ioport_read(1, addr);
468 if (loglevel & CPU_LOG_IOPORT)
469 fprintf(logfile, "inw : %04x %04x\n", addr, val);
473 env->last_io_time = cpu_get_time_fast();
478 int cpu_inl(CPUState *env, int addr)
481 val = ioport_read(2, addr);
483 if (loglevel & CPU_LOG_IOPORT)
484 fprintf(logfile, "inl : %04x %08x\n", addr, val);
488 env->last_io_time = cpu_get_time_fast();
493 /***********************************************************/
494 void hw_error(const char *fmt, ...)
500 fprintf(stderr, "qemu: hardware error: ");
501 vfprintf(stderr, fmt, ap);
502 fprintf(stderr, "\n");
503 for(env = first_cpu; env != NULL; env = env->next_cpu) {
504 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
506 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
508 cpu_dump_state(env, stderr, fprintf, 0);
515 /***********************************************************/
518 static QEMUPutKBDEvent *qemu_put_kbd_event;
519 static void *qemu_put_kbd_event_opaque;
520 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
521 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
523 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
525 qemu_put_kbd_event_opaque = opaque;
526 qemu_put_kbd_event = func;
529 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
530 void *opaque, int absolute,
533 QEMUPutMouseEntry *s, *cursor;
535 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
539 s->qemu_put_mouse_event = func;
540 s->qemu_put_mouse_event_opaque = opaque;
541 s->qemu_put_mouse_event_absolute = absolute;
542 s->qemu_put_mouse_event_name = qemu_strdup(name);
545 if (!qemu_put_mouse_event_head) {
546 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
550 cursor = qemu_put_mouse_event_head;
551 while (cursor->next != NULL)
552 cursor = cursor->next;
555 qemu_put_mouse_event_current = s;
560 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
562 QEMUPutMouseEntry *prev = NULL, *cursor;
564 if (!qemu_put_mouse_event_head || entry == NULL)
567 cursor = qemu_put_mouse_event_head;
568 while (cursor != NULL && cursor != entry) {
570 cursor = cursor->next;
573 if (cursor == NULL) // does not exist or list empty
575 else if (prev == NULL) { // entry is head
576 qemu_put_mouse_event_head = cursor->next;
577 if (qemu_put_mouse_event_current == entry)
578 qemu_put_mouse_event_current = cursor->next;
579 qemu_free(entry->qemu_put_mouse_event_name);
584 prev->next = entry->next;
586 if (qemu_put_mouse_event_current == entry)
587 qemu_put_mouse_event_current = prev;
589 qemu_free(entry->qemu_put_mouse_event_name);
593 void kbd_put_keycode(int keycode)
595 if (qemu_put_kbd_event) {
596 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
600 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
602 QEMUPutMouseEvent *mouse_event;
603 void *mouse_event_opaque;
606 if (!qemu_put_mouse_event_current) {
611 qemu_put_mouse_event_current->qemu_put_mouse_event;
613 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
616 if (graphic_rotate) {
617 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
620 width = graphic_width - 1;
621 mouse_event(mouse_event_opaque,
622 width - dy, dx, dz, buttons_state);
624 mouse_event(mouse_event_opaque,
625 dx, dy, dz, buttons_state);
629 int kbd_mouse_is_absolute(void)
631 if (!qemu_put_mouse_event_current)
634 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
637 void do_info_mice(void)
639 QEMUPutMouseEntry *cursor;
642 if (!qemu_put_mouse_event_head) {
643 term_printf("No mouse devices connected\n");
647 term_printf("Mouse devices available:\n");
648 cursor = qemu_put_mouse_event_head;
649 while (cursor != NULL) {
650 term_printf("%c Mouse #%d: %s\n",
651 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
652 index, cursor->qemu_put_mouse_event_name);
654 cursor = cursor->next;
658 void do_mouse_set(int index)
660 QEMUPutMouseEntry *cursor;
663 if (!qemu_put_mouse_event_head) {
664 term_printf("No mouse devices connected\n");
668 cursor = qemu_put_mouse_event_head;
669 while (cursor != NULL && index != i) {
671 cursor = cursor->next;
675 qemu_put_mouse_event_current = cursor;
677 term_printf("Mouse at given index not found\n");
680 /* compute with 96 bit intermediate result: (a*b)/c */
681 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
686 #ifdef WORDS_BIGENDIAN
696 rl = (uint64_t)u.l.low * (uint64_t)b;
697 rh = (uint64_t)u.l.high * (uint64_t)b;
700 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
704 /***********************************************************/
705 /* real time host monotonic timer */
707 #define QEMU_TIMER_BASE 1000000000LL
711 static int64_t clock_freq;
713 static void init_get_clock(void)
717 ret = QueryPerformanceFrequency(&freq);
719 fprintf(stderr, "Could not calibrate ticks\n");
722 clock_freq = freq.QuadPart;
725 static int64_t get_clock(void)
728 QueryPerformanceCounter(&ti);
729 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
734 static int use_rt_clock;
736 static void init_get_clock(void)
739 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
742 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
749 static int64_t get_clock(void)
751 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
754 clock_gettime(CLOCK_MONOTONIC, &ts);
755 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
759 /* XXX: using gettimeofday leads to problems if the date
760 changes, so it should be avoided. */
762 gettimeofday(&tv, NULL);
763 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
768 /* Return the virtual CPU time, based on the instruction counter. */
769 static int64_t cpu_get_icount(void)
772 CPUState *env = cpu_single_env;;
773 icount = qemu_icount;
776 fprintf(stderr, "Bad clock read\n");
777 icount -= (env->icount_decr.u16.low + env->icount_extra);
779 return qemu_icount_bias + (icount << icount_time_shift);
782 /***********************************************************/
783 /* guest cycle counter */
785 static int64_t cpu_ticks_prev;
786 static int64_t cpu_ticks_offset;
787 static int64_t cpu_clock_offset;
788 static int cpu_ticks_enabled;
790 /* return the host CPU cycle counter and handle stop/restart */
791 int64_t cpu_get_ticks(void)
794 return cpu_get_icount();
796 if (!cpu_ticks_enabled) {
797 return cpu_ticks_offset;
800 ticks = cpu_get_real_ticks();
801 if (cpu_ticks_prev > ticks) {
802 /* Note: non increasing ticks may happen if the host uses
804 cpu_ticks_offset += cpu_ticks_prev - ticks;
806 cpu_ticks_prev = ticks;
807 return ticks + cpu_ticks_offset;
811 /* return the host CPU monotonic timer and handle stop/restart */
812 static int64_t cpu_get_clock(void)
815 if (!cpu_ticks_enabled) {
816 return cpu_clock_offset;
819 return ti + cpu_clock_offset;
823 /* enable cpu_get_ticks() */
824 void cpu_enable_ticks(void)
826 if (!cpu_ticks_enabled) {
827 cpu_ticks_offset -= cpu_get_real_ticks();
828 cpu_clock_offset -= get_clock();
829 cpu_ticks_enabled = 1;
833 /* disable cpu_get_ticks() : the clock is stopped. You must not call
834 cpu_get_ticks() after that. */
835 void cpu_disable_ticks(void)
837 if (cpu_ticks_enabled) {
838 cpu_ticks_offset = cpu_get_ticks();
839 cpu_clock_offset = cpu_get_clock();
840 cpu_ticks_enabled = 0;
844 /***********************************************************/
847 #define QEMU_TIMER_REALTIME 0
848 #define QEMU_TIMER_VIRTUAL 1
852 /* XXX: add frequency */
860 struct QEMUTimer *next;
863 struct qemu_alarm_timer {
867 int (*start)(struct qemu_alarm_timer *t);
868 void (*stop)(struct qemu_alarm_timer *t);
869 void (*rearm)(struct qemu_alarm_timer *t);
873 #define ALARM_FLAG_DYNTICKS 0x1
874 #define ALARM_FLAG_EXPIRED 0x2
876 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
878 return t->flags & ALARM_FLAG_DYNTICKS;
881 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
883 if (!alarm_has_dynticks(t))
889 /* TODO: MIN_TIMER_REARM_US should be optimized */
890 #define MIN_TIMER_REARM_US 250
892 static struct qemu_alarm_timer *alarm_timer;
894 static int alarm_timer_rfd, alarm_timer_wfd;
899 struct qemu_alarm_win32 {
903 } alarm_win32_data = {0, NULL, -1};
905 static int win32_start_timer(struct qemu_alarm_timer *t);
906 static void win32_stop_timer(struct qemu_alarm_timer *t);
907 static void win32_rearm_timer(struct qemu_alarm_timer *t);
911 static int unix_start_timer(struct qemu_alarm_timer *t);
912 static void unix_stop_timer(struct qemu_alarm_timer *t);
916 static int dynticks_start_timer(struct qemu_alarm_timer *t);
917 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
918 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
920 static int hpet_start_timer(struct qemu_alarm_timer *t);
921 static void hpet_stop_timer(struct qemu_alarm_timer *t);
923 static int rtc_start_timer(struct qemu_alarm_timer *t);
924 static void rtc_stop_timer(struct qemu_alarm_timer *t);
926 #endif /* __linux__ */
930 /* Correlation between real and virtual time is always going to be
931 fairly approximate, so ignore small variation.
932 When the guest is idle real and virtual time will be aligned in
934 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
936 static void icount_adjust(void)
941 static int64_t last_delta;
942 /* If the VM is not running, then do nothing. */
946 cur_time = cpu_get_clock();
947 cur_icount = qemu_get_clock(vm_clock);
948 delta = cur_icount - cur_time;
949 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
951 && last_delta + ICOUNT_WOBBLE < delta * 2
952 && icount_time_shift > 0) {
953 /* The guest is getting too far ahead. Slow time down. */
957 && last_delta - ICOUNT_WOBBLE > delta * 2
958 && icount_time_shift < MAX_ICOUNT_SHIFT) {
959 /* The guest is getting too far behind. Speed time up. */
963 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
966 static void icount_adjust_rt(void * opaque)
968 qemu_mod_timer(icount_rt_timer,
969 qemu_get_clock(rt_clock) + 1000);
973 static void icount_adjust_vm(void * opaque)
975 qemu_mod_timer(icount_vm_timer,
976 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
980 static void init_icount_adjust(void)
982 /* Have both realtime and virtual time triggers for speed adjustment.
983 The realtime trigger catches emulated time passing too slowly,
984 the virtual time trigger catches emulated time passing too fast.
985 Realtime triggers occur even when idle, so use them less frequently
987 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
988 qemu_mod_timer(icount_rt_timer,
989 qemu_get_clock(rt_clock) + 1000);
990 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
991 qemu_mod_timer(icount_vm_timer,
992 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
995 static struct qemu_alarm_timer alarm_timers[] = {
998 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
999 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1000 /* HPET - if available - is preferred */
1001 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1002 /* ...otherwise try RTC */
1003 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1005 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1007 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1008 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1009 {"win32", 0, win32_start_timer,
1010 win32_stop_timer, NULL, &alarm_win32_data},
1015 static void show_available_alarms(void)
1019 printf("Available alarm timers, in order of precedence:\n");
1020 for (i = 0; alarm_timers[i].name; i++)
1021 printf("%s\n", alarm_timers[i].name);
1024 static void configure_alarms(char const *opt)
1028 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1031 struct qemu_alarm_timer tmp;
1033 if (!strcmp(opt, "?")) {
1034 show_available_alarms();
1040 /* Reorder the array */
1041 name = strtok(arg, ",");
1043 for (i = 0; i < count && alarm_timers[i].name; i++) {
1044 if (!strcmp(alarm_timers[i].name, name))
1049 fprintf(stderr, "Unknown clock %s\n", name);
1058 tmp = alarm_timers[i];
1059 alarm_timers[i] = alarm_timers[cur];
1060 alarm_timers[cur] = tmp;
1064 name = strtok(NULL, ",");
1070 /* Disable remaining timers */
1071 for (i = cur; i < count; i++)
1072 alarm_timers[i].name = NULL;
1074 show_available_alarms();
1079 QEMUClock *rt_clock;
1080 QEMUClock *vm_clock;
1082 static QEMUTimer *active_timers[2];
1084 static QEMUClock *qemu_new_clock(int type)
1087 clock = qemu_mallocz(sizeof(QEMUClock));
1094 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1098 ts = qemu_mallocz(sizeof(QEMUTimer));
1101 ts->opaque = opaque;
1105 void qemu_free_timer(QEMUTimer *ts)
1110 /* stop a timer, but do not dealloc it */
1111 void qemu_del_timer(QEMUTimer *ts)
1115 /* NOTE: this code must be signal safe because
1116 qemu_timer_expired() can be called from a signal. */
1117 pt = &active_timers[ts->clock->type];
1130 /* modify the current timer so that it will be fired when current_time
1131 >= expire_time. The corresponding callback will be called. */
1132 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1138 /* add the timer in the sorted list */
1139 /* NOTE: this code must be signal safe because
1140 qemu_timer_expired() can be called from a signal. */
1141 pt = &active_timers[ts->clock->type];
1146 if (t->expire_time > expire_time)
1150 ts->expire_time = expire_time;
1154 /* Rearm if necessary */
1155 if (pt == &active_timers[ts->clock->type]) {
1156 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1157 qemu_rearm_alarm_timer(alarm_timer);
1159 /* Interrupt execution to force deadline recalculation. */
1160 if (use_icount && cpu_single_env) {
1161 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1166 int qemu_timer_pending(QEMUTimer *ts)
1169 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1176 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1180 return (timer_head->expire_time <= current_time);
1183 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1189 if (!ts || ts->expire_time > current_time)
1191 /* remove timer from the list before calling the callback */
1192 *ptimer_head = ts->next;
1195 /* run the callback (the timer list can be modified) */
1200 int64_t qemu_get_clock(QEMUClock *clock)
1202 switch(clock->type) {
1203 case QEMU_TIMER_REALTIME:
1204 return get_clock() / 1000000;
1206 case QEMU_TIMER_VIRTUAL:
1208 return cpu_get_icount();
1210 return cpu_get_clock();
1215 static void init_timers(void)
1218 ticks_per_sec = QEMU_TIMER_BASE;
1219 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1220 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1224 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1226 uint64_t expire_time;
1228 if (qemu_timer_pending(ts)) {
1229 expire_time = ts->expire_time;
1233 qemu_put_be64(f, expire_time);
1236 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1238 uint64_t expire_time;
1240 expire_time = qemu_get_be64(f);
1241 if (expire_time != -1) {
1242 qemu_mod_timer(ts, expire_time);
1248 static void timer_save(QEMUFile *f, void *opaque)
1250 if (cpu_ticks_enabled) {
1251 hw_error("cannot save state if virtual timers are running");
1253 qemu_put_be64(f, cpu_ticks_offset);
1254 qemu_put_be64(f, ticks_per_sec);
1255 qemu_put_be64(f, cpu_clock_offset);
1258 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1260 if (version_id != 1 && version_id != 2)
1262 if (cpu_ticks_enabled) {
1265 cpu_ticks_offset=qemu_get_be64(f);
1266 ticks_per_sec=qemu_get_be64(f);
1267 if (version_id == 2) {
1268 cpu_clock_offset=qemu_get_be64(f);
1274 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1275 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1277 static void host_alarm_handler(int host_signum)
1281 #define DISP_FREQ 1000
1283 static int64_t delta_min = INT64_MAX;
1284 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1286 ti = qemu_get_clock(vm_clock);
1287 if (last_clock != 0) {
1288 delta = ti - last_clock;
1289 if (delta < delta_min)
1291 if (delta > delta_max)
1294 if (++count == DISP_FREQ) {
1295 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1296 muldiv64(delta_min, 1000000, ticks_per_sec),
1297 muldiv64(delta_max, 1000000, ticks_per_sec),
1298 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1299 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1301 delta_min = INT64_MAX;
1309 if (alarm_has_dynticks(alarm_timer) ||
1311 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1312 qemu_get_clock(vm_clock))) ||
1313 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1314 qemu_get_clock(rt_clock))) {
1315 CPUState *env = next_cpu;
1318 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1319 SetEvent(data->host_alarm);
1321 static const char byte = 0;
1322 write(alarm_timer_wfd, &byte, sizeof(byte));
1324 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1327 /* stop the currently executing cpu because a timer occured */
1328 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1330 if (env->kqemu_enabled) {
1331 kqemu_cpu_interrupt(env);
1339 static int64_t qemu_next_deadline(void)
1343 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1344 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1345 qemu_get_clock(vm_clock);
1347 /* To avoid problems with overflow limit this to 2^32. */
1357 #if defined(__linux__) || defined(_WIN32)
1358 static uint64_t qemu_next_deadline_dyntick(void)
1366 delta = (qemu_next_deadline() + 999) / 1000;
1368 if (active_timers[QEMU_TIMER_REALTIME]) {
1369 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1370 qemu_get_clock(rt_clock))*1000;
1371 if (rtdelta < delta)
1375 if (delta < MIN_TIMER_REARM_US)
1376 delta = MIN_TIMER_REARM_US;
1384 /* Sets a specific flag */
1385 static int fcntl_setfl(int fd, int flag)
1389 flags = fcntl(fd, F_GETFL);
1393 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1399 #if defined(__linux__)
1401 #define RTC_FREQ 1024
1403 static void enable_sigio_timer(int fd)
1405 struct sigaction act;
1408 sigfillset(&act.sa_mask);
1410 act.sa_handler = host_alarm_handler;
1412 sigaction(SIGIO, &act, NULL);
1413 fcntl_setfl(fd, O_ASYNC);
1414 fcntl(fd, F_SETOWN, getpid());
1417 static int hpet_start_timer(struct qemu_alarm_timer *t)
1419 struct hpet_info info;
1422 fd = open("/dev/hpet", O_RDONLY);
1427 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1429 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1430 "error, but for better emulation accuracy type:\n"
1431 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1435 /* Check capabilities */
1436 r = ioctl(fd, HPET_INFO, &info);
1440 /* Enable periodic mode */
1441 r = ioctl(fd, HPET_EPI, 0);
1442 if (info.hi_flags && (r < 0))
1445 /* Enable interrupt */
1446 r = ioctl(fd, HPET_IE_ON, 0);
1450 enable_sigio_timer(fd);
1451 t->priv = (void *)(long)fd;
1459 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1461 int fd = (long)t->priv;
1466 static int rtc_start_timer(struct qemu_alarm_timer *t)
1469 unsigned long current_rtc_freq = 0;
1471 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1474 ioctl(rtc_fd, RTC_IRQP_READ, ¤t_rtc_freq);
1475 if (current_rtc_freq != RTC_FREQ &&
1476 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1477 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1478 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1479 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1482 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1488 enable_sigio_timer(rtc_fd);
1490 t->priv = (void *)(long)rtc_fd;
1495 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1497 int rtc_fd = (long)t->priv;
1502 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1506 struct sigaction act;
1508 sigfillset(&act.sa_mask);
1510 act.sa_handler = host_alarm_handler;
1512 sigaction(SIGALRM, &act, NULL);
1514 ev.sigev_value.sival_int = 0;
1515 ev.sigev_notify = SIGEV_SIGNAL;
1516 ev.sigev_signo = SIGALRM;
1518 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1519 perror("timer_create");
1521 /* disable dynticks */
1522 fprintf(stderr, "Dynamic Ticks disabled\n");
1527 t->priv = (void *)host_timer;
1532 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1534 timer_t host_timer = (timer_t)t->priv;
1536 timer_delete(host_timer);
1539 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1541 timer_t host_timer = (timer_t)t->priv;
1542 struct itimerspec timeout;
1543 int64_t nearest_delta_us = INT64_MAX;
1546 if (!active_timers[QEMU_TIMER_REALTIME] &&
1547 !active_timers[QEMU_TIMER_VIRTUAL])
1550 nearest_delta_us = qemu_next_deadline_dyntick();
1552 /* check whether a timer is already running */
1553 if (timer_gettime(host_timer, &timeout)) {
1555 fprintf(stderr, "Internal timer error: aborting\n");
1558 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1559 if (current_us && current_us <= nearest_delta_us)
1562 timeout.it_interval.tv_sec = 0;
1563 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1564 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1565 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1566 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1568 fprintf(stderr, "Internal timer error: aborting\n");
1573 #endif /* defined(__linux__) */
1575 static int unix_start_timer(struct qemu_alarm_timer *t)
1577 struct sigaction act;
1578 struct itimerval itv;
1582 sigfillset(&act.sa_mask);
1584 act.sa_handler = host_alarm_handler;
1586 sigaction(SIGALRM, &act, NULL);
1588 itv.it_interval.tv_sec = 0;
1589 /* for i386 kernel 2.6 to get 1 ms */
1590 itv.it_interval.tv_usec = 999;
1591 itv.it_value.tv_sec = 0;
1592 itv.it_value.tv_usec = 10 * 1000;
1594 err = setitimer(ITIMER_REAL, &itv, NULL);
1601 static void unix_stop_timer(struct qemu_alarm_timer *t)
1603 struct itimerval itv;
1605 memset(&itv, 0, sizeof(itv));
1606 setitimer(ITIMER_REAL, &itv, NULL);
1609 #endif /* !defined(_WIN32) */
1611 static void try_to_rearm_timer(void *opaque)
1613 struct qemu_alarm_timer *t = opaque;
1617 /* Drain the notify pipe */
1620 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1621 } while ((len == -1 && errno == EINTR) || len > 0);
1624 /* vm time timers */
1625 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
1626 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
1627 qemu_get_clock(vm_clock));
1629 /* real time timers */
1630 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
1631 qemu_get_clock(rt_clock));
1633 if (t->flags & ALARM_FLAG_EXPIRED) {
1634 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1635 qemu_rearm_alarm_timer(alarm_timer);
1641 static int win32_start_timer(struct qemu_alarm_timer *t)
1644 struct qemu_alarm_win32 *data = t->priv;
1647 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1648 if (!data->host_alarm) {
1649 perror("Failed CreateEvent");
1653 memset(&tc, 0, sizeof(tc));
1654 timeGetDevCaps(&tc, sizeof(tc));
1656 if (data->period < tc.wPeriodMin)
1657 data->period = tc.wPeriodMin;
1659 timeBeginPeriod(data->period);
1661 flags = TIME_CALLBACK_FUNCTION;
1662 if (alarm_has_dynticks(t))
1663 flags |= TIME_ONESHOT;
1665 flags |= TIME_PERIODIC;
1667 data->timerId = timeSetEvent(1, // interval (ms)
1668 data->period, // resolution
1669 host_alarm_handler, // function
1670 (DWORD)t, // parameter
1673 if (!data->timerId) {
1674 perror("Failed to initialize win32 alarm timer");
1676 timeEndPeriod(data->period);
1677 CloseHandle(data->host_alarm);
1681 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1686 static void win32_stop_timer(struct qemu_alarm_timer *t)
1688 struct qemu_alarm_win32 *data = t->priv;
1690 timeKillEvent(data->timerId);
1691 timeEndPeriod(data->period);
1693 CloseHandle(data->host_alarm);
1696 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1698 struct qemu_alarm_win32 *data = t->priv;
1699 uint64_t nearest_delta_us;
1701 if (!active_timers[QEMU_TIMER_REALTIME] &&
1702 !active_timers[QEMU_TIMER_VIRTUAL])
1705 nearest_delta_us = qemu_next_deadline_dyntick();
1706 nearest_delta_us /= 1000;
1708 timeKillEvent(data->timerId);
1710 data->timerId = timeSetEvent(1,
1714 TIME_ONESHOT | TIME_PERIODIC);
1716 if (!data->timerId) {
1717 perror("Failed to re-arm win32 alarm timer");
1719 timeEndPeriod(data->period);
1720 CloseHandle(data->host_alarm);
1727 static int init_timer_alarm(void)
1729 struct qemu_alarm_timer *t = NULL;
1739 err = fcntl_setfl(fds[0], O_NONBLOCK);
1743 err = fcntl_setfl(fds[1], O_NONBLOCK);
1747 alarm_timer_rfd = fds[0];
1748 alarm_timer_wfd = fds[1];
1751 for (i = 0; alarm_timers[i].name; i++) {
1752 t = &alarm_timers[i];
1765 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1766 try_to_rearm_timer, NULL, t);
1781 static void quit_timers(void)
1783 alarm_timer->stop(alarm_timer);
1787 /***********************************************************/
1788 /* host time/date access */
1789 void qemu_get_timedate(struct tm *tm, int offset)
1796 if (rtc_date_offset == -1) {
1800 ret = localtime(&ti);
1802 ti -= rtc_date_offset;
1806 memcpy(tm, ret, sizeof(struct tm));
1809 int qemu_timedate_diff(struct tm *tm)
1813 if (rtc_date_offset == -1)
1815 seconds = mktimegm(tm);
1817 seconds = mktime(tm);
1819 seconds = mktimegm(tm) + rtc_date_offset;
1821 return seconds - time(NULL);
1825 static void socket_cleanup(void)
1830 static int socket_init(void)
1835 ret = WSAStartup(MAKEWORD(2,2), &Data);
1837 err = WSAGetLastError();
1838 fprintf(stderr, "WSAStartup: %d\n", err);
1841 atexit(socket_cleanup);
1846 const char *get_opt_name(char *buf, int buf_size, const char *p)
1851 while (*p != '\0' && *p != '=') {
1852 if (q && (q - buf) < buf_size - 1)
1862 const char *get_opt_value(char *buf, int buf_size, const char *p)
1867 while (*p != '\0') {
1869 if (*(p + 1) != ',')
1873 if (q && (q - buf) < buf_size - 1)
1883 int get_param_value(char *buf, int buf_size,
1884 const char *tag, const char *str)
1891 p = get_opt_name(option, sizeof(option), p);
1895 if (!strcmp(tag, option)) {
1896 (void)get_opt_value(buf, buf_size, p);
1899 p = get_opt_value(NULL, 0, p);
1908 int check_params(char *buf, int buf_size,
1909 const char * const *params, const char *str)
1916 p = get_opt_name(buf, buf_size, p);
1920 for(i = 0; params[i] != NULL; i++)
1921 if (!strcmp(params[i], buf))
1923 if (params[i] == NULL)
1925 p = get_opt_value(NULL, 0, p);
1933 /***********************************************************/
1934 /* Bluetooth support */
1937 static struct HCIInfo *hci_table[MAX_NICS];
1939 static struct bt_vlan_s {
1940 struct bt_scatternet_s net;
1942 struct bt_vlan_s *next;
1945 /* find or alloc a new bluetooth "VLAN" */
1946 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1948 struct bt_vlan_s **pvlan, *vlan;
1949 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1953 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1955 pvlan = &first_bt_vlan;
1956 while (*pvlan != NULL)
1957 pvlan = &(*pvlan)->next;
1963 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1967 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1972 static struct HCIInfo null_hci = {
1973 .cmd_send = null_hci_send,
1974 .sco_send = null_hci_send,
1975 .acl_send = null_hci_send,
1976 .bdaddr_set = null_hci_addr_set,
1979 struct HCIInfo *qemu_next_hci(void)
1981 if (cur_hci == nb_hcis)
1984 return hci_table[cur_hci++];
1987 /***********************************************************/
1988 /* QEMU Block devices */
1990 #define HD_ALIAS "index=%d,media=disk"
1992 #define CDROM_ALIAS "index=1,media=cdrom"
1994 #define CDROM_ALIAS "index=2,media=cdrom"
1996 #define FD_ALIAS "index=%d,if=floppy"
1997 #define PFLASH_ALIAS "if=pflash"
1998 #define MTD_ALIAS "if=mtd"
1999 #define SD_ALIAS "index=0,if=sd"
2001 static int drive_add(const char *file, const char *fmt, ...)
2005 if (nb_drives_opt >= MAX_DRIVES) {
2006 fprintf(stderr, "qemu: too many drives\n");
2010 drives_opt[nb_drives_opt].file = file;
2012 vsnprintf(drives_opt[nb_drives_opt].opt,
2013 sizeof(drives_opt[0].opt), fmt, ap);
2016 return nb_drives_opt++;
2019 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2023 /* seek interface, bus and unit */
2025 for (index = 0; index < nb_drives; index++)
2026 if (drives_table[index].type == type &&
2027 drives_table[index].bus == bus &&
2028 drives_table[index].unit == unit)
2034 int drive_get_max_bus(BlockInterfaceType type)
2040 for (index = 0; index < nb_drives; index++) {
2041 if(drives_table[index].type == type &&
2042 drives_table[index].bus > max_bus)
2043 max_bus = drives_table[index].bus;
2048 static void bdrv_format_print(void *opaque, const char *name)
2050 fprintf(stderr, " %s", name);
2053 static int drive_init(struct drive_opt *arg, int snapshot,
2054 QEMUMachine *machine)
2059 const char *mediastr = "";
2060 BlockInterfaceType type;
2061 enum { MEDIA_DISK, MEDIA_CDROM } media;
2062 int bus_id, unit_id;
2063 int cyls, heads, secs, translation;
2064 BlockDriverState *bdrv;
2065 BlockDriver *drv = NULL;
2070 char *str = arg->opt;
2071 static const char * const params[] = { "bus", "unit", "if", "index",
2072 "cyls", "heads", "secs", "trans",
2073 "media", "snapshot", "file",
2074 "cache", "format", NULL };
2076 if (check_params(buf, sizeof(buf), params, str) < 0) {
2077 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2083 cyls = heads = secs = 0;
2086 translation = BIOS_ATA_TRANSLATION_AUTO;
2090 if (machine->use_scsi) {
2092 max_devs = MAX_SCSI_DEVS;
2093 pstrcpy(devname, sizeof(devname), "scsi");
2096 max_devs = MAX_IDE_DEVS;
2097 pstrcpy(devname, sizeof(devname), "ide");
2101 /* extract parameters */
2103 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2104 bus_id = strtol(buf, NULL, 0);
2106 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2111 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2112 unit_id = strtol(buf, NULL, 0);
2114 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2119 if (get_param_value(buf, sizeof(buf), "if", str)) {
2120 pstrcpy(devname, sizeof(devname), buf);
2121 if (!strcmp(buf, "ide")) {
2123 max_devs = MAX_IDE_DEVS;
2124 } else if (!strcmp(buf, "scsi")) {
2126 max_devs = MAX_SCSI_DEVS;
2127 } else if (!strcmp(buf, "floppy")) {
2130 } else if (!strcmp(buf, "pflash")) {
2133 } else if (!strcmp(buf, "mtd")) {
2136 } else if (!strcmp(buf, "sd")) {
2140 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2145 if (get_param_value(buf, sizeof(buf), "index", str)) {
2146 index = strtol(buf, NULL, 0);
2148 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2153 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2154 cyls = strtol(buf, NULL, 0);
2157 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2158 heads = strtol(buf, NULL, 0);
2161 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2162 secs = strtol(buf, NULL, 0);
2165 if (cyls || heads || secs) {
2166 if (cyls < 1 || cyls > 16383) {
2167 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2170 if (heads < 1 || heads > 16) {
2171 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2174 if (secs < 1 || secs > 63) {
2175 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2180 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2183 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2187 if (!strcmp(buf, "none"))
2188 translation = BIOS_ATA_TRANSLATION_NONE;
2189 else if (!strcmp(buf, "lba"))
2190 translation = BIOS_ATA_TRANSLATION_LBA;
2191 else if (!strcmp(buf, "auto"))
2192 translation = BIOS_ATA_TRANSLATION_AUTO;
2194 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2199 if (get_param_value(buf, sizeof(buf), "media", str)) {
2200 if (!strcmp(buf, "disk")) {
2202 } else if (!strcmp(buf, "cdrom")) {
2203 if (cyls || secs || heads) {
2205 "qemu: '%s' invalid physical CHS format\n", str);
2208 media = MEDIA_CDROM;
2210 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2215 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2216 if (!strcmp(buf, "on"))
2218 else if (!strcmp(buf, "off"))
2221 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2226 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2227 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2229 else if (!strcmp(buf, "writethrough"))
2231 else if (!strcmp(buf, "writeback"))
2234 fprintf(stderr, "qemu: invalid cache option\n");
2239 if (get_param_value(buf, sizeof(buf), "format", str)) {
2240 if (strcmp(buf, "?") == 0) {
2241 fprintf(stderr, "qemu: Supported formats:");
2242 bdrv_iterate_format(bdrv_format_print, NULL);
2243 fprintf(stderr, "\n");
2246 drv = bdrv_find_format(buf);
2248 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2253 if (arg->file == NULL)
2254 get_param_value(file, sizeof(file), "file", str);
2256 pstrcpy(file, sizeof(file), arg->file);
2258 /* compute bus and unit according index */
2261 if (bus_id != 0 || unit_id != -1) {
2263 "qemu: '%s' index cannot be used with bus and unit\n", str);
2271 unit_id = index % max_devs;
2272 bus_id = index / max_devs;
2276 /* if user doesn't specify a unit_id,
2277 * try to find the first free
2280 if (unit_id == -1) {
2282 while (drive_get_index(type, bus_id, unit_id) != -1) {
2284 if (max_devs && unit_id >= max_devs) {
2285 unit_id -= max_devs;
2293 if (max_devs && unit_id >= max_devs) {
2294 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2295 str, unit_id, max_devs - 1);
2300 * ignore multiple definitions
2303 if (drive_get_index(type, bus_id, unit_id) != -1)
2308 if (type == IF_IDE || type == IF_SCSI)
2309 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2311 snprintf(buf, sizeof(buf), "%s%i%s%i",
2312 devname, bus_id, mediastr, unit_id);
2314 snprintf(buf, sizeof(buf), "%s%s%i",
2315 devname, mediastr, unit_id);
2316 bdrv = bdrv_new(buf);
2317 drives_table[nb_drives].bdrv = bdrv;
2318 drives_table[nb_drives].type = type;
2319 drives_table[nb_drives].bus = bus_id;
2320 drives_table[nb_drives].unit = unit_id;
2329 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2330 bdrv_set_translation_hint(bdrv, translation);
2334 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2339 /* FIXME: This isn't really a floppy, but it's a reasonable
2342 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2352 bdrv_flags |= BDRV_O_SNAPSHOT;
2353 cache = 2; /* always use write-back with snapshot */
2355 if (cache == 0) /* no caching */
2356 bdrv_flags |= BDRV_O_NOCACHE;
2357 else if (cache == 2) /* write-back */
2358 bdrv_flags |= BDRV_O_CACHE_WB;
2359 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2360 fprintf(stderr, "qemu: could not open disk image %s\n",
2367 /***********************************************************/
2370 static USBPort *used_usb_ports;
2371 static USBPort *free_usb_ports;
2373 /* ??? Maybe change this to register a hub to keep track of the topology. */
2374 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2375 usb_attachfn attach)
2377 port->opaque = opaque;
2378 port->index = index;
2379 port->attach = attach;
2380 port->next = free_usb_ports;
2381 free_usb_ports = port;
2384 int usb_device_add_dev(USBDevice *dev)
2388 /* Find a USB port to add the device to. */
2389 port = free_usb_ports;
2393 /* Create a new hub and chain it on. */
2394 free_usb_ports = NULL;
2395 port->next = used_usb_ports;
2396 used_usb_ports = port;
2398 hub = usb_hub_init(VM_USB_HUB_SIZE);
2399 usb_attach(port, hub);
2400 port = free_usb_ports;
2403 free_usb_ports = port->next;
2404 port->next = used_usb_ports;
2405 used_usb_ports = port;
2406 usb_attach(port, dev);
2410 static int usb_device_add(const char *devname)
2415 if (!free_usb_ports)
2418 if (strstart(devname, "host:", &p)) {
2419 dev = usb_host_device_open(p);
2420 } else if (!strcmp(devname, "mouse")) {
2421 dev = usb_mouse_init();
2422 } else if (!strcmp(devname, "tablet")) {
2423 dev = usb_tablet_init();
2424 } else if (!strcmp(devname, "keyboard")) {
2425 dev = usb_keyboard_init();
2426 } else if (strstart(devname, "disk:", &p)) {
2427 dev = usb_msd_init(p);
2428 } else if (!strcmp(devname, "wacom-tablet")) {
2429 dev = usb_wacom_init();
2430 } else if (strstart(devname, "serial:", &p)) {
2431 dev = usb_serial_init(p);
2432 #ifdef CONFIG_BRLAPI
2433 } else if (!strcmp(devname, "braille")) {
2434 dev = usb_baum_init();
2436 } else if (strstart(devname, "net:", &p)) {
2439 if (net_client_init("nic", p) < 0)
2441 nd_table[nic].model = "usb";
2442 dev = usb_net_init(&nd_table[nic]);
2449 return usb_device_add_dev(dev);
2452 int usb_device_del_addr(int bus_num, int addr)
2458 if (!used_usb_ports)
2464 lastp = &used_usb_ports;
2465 port = used_usb_ports;
2466 while (port && port->dev->addr != addr) {
2467 lastp = &port->next;
2475 *lastp = port->next;
2476 usb_attach(port, NULL);
2477 dev->handle_destroy(dev);
2478 port->next = free_usb_ports;
2479 free_usb_ports = port;
2483 static int usb_device_del(const char *devname)
2488 if (strstart(devname, "host:", &p))
2489 return usb_host_device_close(p);
2491 if (!used_usb_ports)
2494 p = strchr(devname, '.');
2497 bus_num = strtoul(devname, NULL, 0);
2498 addr = strtoul(p + 1, NULL, 0);
2500 return usb_device_del_addr(bus_num, addr);
2503 void do_usb_add(const char *devname)
2505 usb_device_add(devname);
2508 void do_usb_del(const char *devname)
2510 usb_device_del(devname);
2517 const char *speed_str;
2520 term_printf("USB support not enabled\n");
2524 for (port = used_usb_ports; port; port = port->next) {
2528 switch(dev->speed) {
2532 case USB_SPEED_FULL:
2535 case USB_SPEED_HIGH:
2542 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2543 0, dev->addr, speed_str, dev->devname);
2547 /***********************************************************/
2548 /* PCMCIA/Cardbus */
2550 static struct pcmcia_socket_entry_s {
2551 struct pcmcia_socket_s *socket;
2552 struct pcmcia_socket_entry_s *next;
2553 } *pcmcia_sockets = 0;
2555 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2557 struct pcmcia_socket_entry_s *entry;
2559 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2560 entry->socket = socket;
2561 entry->next = pcmcia_sockets;
2562 pcmcia_sockets = entry;
2565 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2567 struct pcmcia_socket_entry_s *entry, **ptr;
2569 ptr = &pcmcia_sockets;
2570 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2571 if (entry->socket == socket) {
2577 void pcmcia_info(void)
2579 struct pcmcia_socket_entry_s *iter;
2580 if (!pcmcia_sockets)
2581 term_printf("No PCMCIA sockets\n");
2583 for (iter = pcmcia_sockets; iter; iter = iter->next)
2584 term_printf("%s: %s\n", iter->socket->slot_string,
2585 iter->socket->attached ? iter->socket->card_string :
2589 /***********************************************************/
2592 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2596 static void dumb_resize(DisplayState *ds, int w, int h)
2600 static void dumb_display_init(DisplayState *ds)
2605 ds->dpy_update = dumb_update;
2606 ds->dpy_resize = dumb_resize;
2607 ds->dpy_refresh = NULL;
2608 ds->gui_timer_interval = 0;
2612 /***********************************************************/
2615 #define MAX_IO_HANDLERS 64
2617 typedef struct IOHandlerRecord {
2619 IOCanRWHandler *fd_read_poll;
2621 IOHandler *fd_write;
2624 /* temporary data */
2626 struct IOHandlerRecord *next;
2629 static IOHandlerRecord *first_io_handler;
2631 /* XXX: fd_read_poll should be suppressed, but an API change is
2632 necessary in the character devices to suppress fd_can_read(). */
2633 int qemu_set_fd_handler2(int fd,
2634 IOCanRWHandler *fd_read_poll,
2636 IOHandler *fd_write,
2639 IOHandlerRecord **pioh, *ioh;
2641 if (!fd_read && !fd_write) {
2642 pioh = &first_io_handler;
2647 if (ioh->fd == fd) {
2654 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2658 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2661 ioh->next = first_io_handler;
2662 first_io_handler = ioh;
2665 ioh->fd_read_poll = fd_read_poll;
2666 ioh->fd_read = fd_read;
2667 ioh->fd_write = fd_write;
2668 ioh->opaque = opaque;
2674 int qemu_set_fd_handler(int fd,
2676 IOHandler *fd_write,
2679 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2683 /***********************************************************/
2684 /* Polling handling */
2686 typedef struct PollingEntry {
2689 struct PollingEntry *next;
2692 static PollingEntry *first_polling_entry;
2694 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2696 PollingEntry **ppe, *pe;
2697 pe = qemu_mallocz(sizeof(PollingEntry));
2701 pe->opaque = opaque;
2702 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2707 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2709 PollingEntry **ppe, *pe;
2710 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2712 if (pe->func == func && pe->opaque == opaque) {
2720 /***********************************************************/
2721 /* Wait objects support */
2722 typedef struct WaitObjects {
2724 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2725 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2726 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2729 static WaitObjects wait_objects = {0};
2731 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2733 WaitObjects *w = &wait_objects;
2735 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2737 w->events[w->num] = handle;
2738 w->func[w->num] = func;
2739 w->opaque[w->num] = opaque;
2744 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2747 WaitObjects *w = &wait_objects;
2750 for (i = 0; i < w->num; i++) {
2751 if (w->events[i] == handle)
2754 w->events[i] = w->events[i + 1];
2755 w->func[i] = w->func[i + 1];
2756 w->opaque[i] = w->opaque[i + 1];
2764 #define SELF_ANNOUNCE_ROUNDS 5
2765 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
2766 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
2767 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
2769 static int announce_self_create(uint8_t *buf,
2772 uint32_t magic = EXPERIMENTAL_MAGIC;
2773 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
2775 /* FIXME: should we send a different packet (arp/rarp/ping)? */
2777 memset(buf, 0xff, 6); /* h_dst */
2778 memcpy(buf + 6, mac_addr, 6); /* h_src */
2779 memcpy(buf + 12, &proto, 2); /* h_proto */
2780 memcpy(buf + 14, &magic, 4); /* magic */
2782 return 18; /* len */
2785 void qemu_announce_self(void)
2789 VLANClientState *vc;
2792 for (i = 0; i < nb_nics; i++) {
2793 len = announce_self_create(buf, nd_table[i].macaddr);
2794 vlan = nd_table[i].vlan;
2795 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2796 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
2797 vc->fd_read(vc->opaque, buf, len);
2802 /***********************************************************/
2803 /* savevm/loadvm support */
2805 #define IO_BUF_SIZE 32768
2808 QEMUFilePutBufferFunc *put_buffer;
2809 QEMUFileGetBufferFunc *get_buffer;
2810 QEMUFileCloseFunc *close;
2811 QEMUFileRateLimit *rate_limit;
2815 int64_t buf_offset; /* start of buffer when writing, end of buffer
2818 int buf_size; /* 0 when writing */
2819 uint8_t buf[IO_BUF_SIZE];
2824 typedef struct QEMUFileSocket
2830 static int socket_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
2832 QEMUFileSocket *s = opaque;
2836 len = recv(s->fd, buf, size, 0);
2837 } while (len == -1 && socket_error() == EINTR);
2840 len = -socket_error();
2845 static int socket_close(void *opaque)
2847 QEMUFileSocket *s = opaque;
2852 QEMUFile *qemu_fopen_socket(int fd)
2854 QEMUFileSocket *s = qemu_mallocz(sizeof(QEMUFileSocket));
2860 s->file = qemu_fopen_ops(s, NULL, socket_get_buffer, socket_close, NULL);
2864 typedef struct QEMUFileStdio
2869 static int file_put_buffer(void *opaque, const uint8_t *buf,
2870 int64_t pos, int size)
2872 QEMUFileStdio *s = opaque;
2873 fseek(s->outfile, pos, SEEK_SET);
2874 fwrite(buf, 1, size, s->outfile);
2878 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
2880 QEMUFileStdio *s = opaque;
2881 fseek(s->outfile, pos, SEEK_SET);
2882 return fread(buf, 1, size, s->outfile);
2885 static int file_close(void *opaque)
2887 QEMUFileStdio *s = opaque;
2893 QEMUFile *qemu_fopen(const char *filename, const char *mode)
2897 s = qemu_mallocz(sizeof(QEMUFileStdio));
2901 s->outfile = fopen(filename, mode);
2905 if (!strcmp(mode, "wb"))
2906 return qemu_fopen_ops(s, file_put_buffer, NULL, file_close, NULL);
2907 else if (!strcmp(mode, "rb"))
2908 return qemu_fopen_ops(s, NULL, file_get_buffer, file_close, NULL);
2917 typedef struct QEMUFileBdrv
2919 BlockDriverState *bs;
2920 int64_t base_offset;
2923 static int bdrv_put_buffer(void *opaque, const uint8_t *buf,
2924 int64_t pos, int size)
2926 QEMUFileBdrv *s = opaque;
2927 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
2931 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
2933 QEMUFileBdrv *s = opaque;
2934 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
2937 static int bdrv_fclose(void *opaque)
2939 QEMUFileBdrv *s = opaque;
2944 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
2948 s = qemu_mallocz(sizeof(QEMUFileBdrv));
2953 s->base_offset = offset;
2956 return qemu_fopen_ops(s, bdrv_put_buffer, NULL, bdrv_fclose, NULL);
2958 return qemu_fopen_ops(s, NULL, bdrv_get_buffer, bdrv_fclose, NULL);
2961 QEMUFile *qemu_fopen_ops(void *opaque, QEMUFilePutBufferFunc *put_buffer,
2962 QEMUFileGetBufferFunc *get_buffer,
2963 QEMUFileCloseFunc *close,
2964 QEMUFileRateLimit *rate_limit)
2968 f = qemu_mallocz(sizeof(QEMUFile));
2973 f->put_buffer = put_buffer;
2974 f->get_buffer = get_buffer;
2976 f->rate_limit = rate_limit;
2982 int qemu_file_has_error(QEMUFile *f)
2984 return f->has_error;
2987 void qemu_fflush(QEMUFile *f)
2992 if (f->is_write && f->buf_index > 0) {
2995 len = f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
2997 f->buf_offset += f->buf_index;
3004 static void qemu_fill_buffer(QEMUFile *f)
3014 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
3018 f->buf_offset += len;
3019 } else if (len != -EAGAIN)
3023 int qemu_fclose(QEMUFile *f)
3028 ret = f->close(f->opaque);
3033 void qemu_file_put_notify(QEMUFile *f)
3035 f->put_buffer(f->opaque, NULL, 0, 0);
3038 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3042 if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
3044 "Attempted to write to buffer while read buffer is not empty\n");
3048 while (!f->has_error && size > 0) {
3049 l = IO_BUF_SIZE - f->buf_index;
3052 memcpy(f->buf + f->buf_index, buf, l);
3057 if (f->buf_index >= IO_BUF_SIZE)
3062 void qemu_put_byte(QEMUFile *f, int v)
3064 if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
3066 "Attempted to write to buffer while read buffer is not empty\n");
3070 f->buf[f->buf_index++] = v;
3072 if (f->buf_index >= IO_BUF_SIZE)
3076 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
3085 l = f->buf_size - f->buf_index;
3087 qemu_fill_buffer(f);
3088 l = f->buf_size - f->buf_index;
3094 memcpy(buf, f->buf + f->buf_index, l);
3099 return size1 - size;
3102 int qemu_get_byte(QEMUFile *f)
3107 if (f->buf_index >= f->buf_size) {
3108 qemu_fill_buffer(f);
3109 if (f->buf_index >= f->buf_size)
3112 return f->buf[f->buf_index++];
3115 int64_t qemu_ftell(QEMUFile *f)
3117 return f->buf_offset - f->buf_size + f->buf_index;
3120 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3122 if (whence == SEEK_SET) {
3124 } else if (whence == SEEK_CUR) {
3125 pos += qemu_ftell(f);
3127 /* SEEK_END not supported */
3130 if (f->put_buffer) {
3132 f->buf_offset = pos;
3134 f->buf_offset = pos;
3141 int qemu_file_rate_limit(QEMUFile *f)
3144 return f->rate_limit(f->opaque);
3149 void qemu_put_be16(QEMUFile *f, unsigned int v)
3151 qemu_put_byte(f, v >> 8);
3152 qemu_put_byte(f, v);
3155 void qemu_put_be32(QEMUFile *f, unsigned int v)
3157 qemu_put_byte(f, v >> 24);
3158 qemu_put_byte(f, v >> 16);
3159 qemu_put_byte(f, v >> 8);
3160 qemu_put_byte(f, v);
3163 void qemu_put_be64(QEMUFile *f, uint64_t v)
3165 qemu_put_be32(f, v >> 32);
3166 qemu_put_be32(f, v);
3169 unsigned int qemu_get_be16(QEMUFile *f)
3172 v = qemu_get_byte(f) << 8;
3173 v |= qemu_get_byte(f);
3177 unsigned int qemu_get_be32(QEMUFile *f)
3180 v = qemu_get_byte(f) << 24;
3181 v |= qemu_get_byte(f) << 16;
3182 v |= qemu_get_byte(f) << 8;
3183 v |= qemu_get_byte(f);
3187 uint64_t qemu_get_be64(QEMUFile *f)
3190 v = (uint64_t)qemu_get_be32(f) << 32;
3191 v |= qemu_get_be32(f);
3195 typedef struct SaveStateEntry {
3200 SaveLiveStateHandler *save_live_state;
3201 SaveStateHandler *save_state;
3202 LoadStateHandler *load_state;
3204 struct SaveStateEntry *next;
3207 static SaveStateEntry *first_se;
3209 /* TODO: Individual devices generally have very little idea about the rest
3210 of the system, so instance_id should be removed/replaced.
3211 Meanwhile pass -1 as instance_id if you do not already have a clearly
3212 distinguishing id for all instances of your device class. */
3213 int register_savevm_live(const char *idstr,
3216 SaveLiveStateHandler *save_live_state,
3217 SaveStateHandler *save_state,
3218 LoadStateHandler *load_state,
3221 SaveStateEntry *se, **pse;
3222 static int global_section_id;
3224 se = qemu_malloc(sizeof(SaveStateEntry));
3227 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3228 se->instance_id = (instance_id == -1) ? 0 : instance_id;
3229 se->version_id = version_id;
3230 se->section_id = global_section_id++;
3231 se->save_live_state = save_live_state;
3232 se->save_state = save_state;
3233 se->load_state = load_state;
3234 se->opaque = opaque;
3237 /* add at the end of list */
3239 while (*pse != NULL) {
3240 if (instance_id == -1
3241 && strcmp(se->idstr, (*pse)->idstr) == 0
3242 && se->instance_id <= (*pse)->instance_id)
3243 se->instance_id = (*pse)->instance_id + 1;
3244 pse = &(*pse)->next;
3250 int register_savevm(const char *idstr,
3253 SaveStateHandler *save_state,
3254 LoadStateHandler *load_state,
3257 return register_savevm_live(idstr, instance_id, version_id,
3258 NULL, save_state, load_state, opaque);
3261 #define QEMU_VM_FILE_MAGIC 0x5145564d
3262 #define QEMU_VM_FILE_VERSION_COMPAT 0x00000002
3263 #define QEMU_VM_FILE_VERSION 0x00000003
3265 #define QEMU_VM_EOF 0x00
3266 #define QEMU_VM_SECTION_START 0x01
3267 #define QEMU_VM_SECTION_PART 0x02
3268 #define QEMU_VM_SECTION_END 0x03
3269 #define QEMU_VM_SECTION_FULL 0x04
3271 int qemu_savevm_state_begin(QEMUFile *f)
3275 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3276 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3278 for (se = first_se; se != NULL; se = se->next) {
3281 if (se->save_live_state == NULL)
3285 qemu_put_byte(f, QEMU_VM_SECTION_START);
3286 qemu_put_be32(f, se->section_id);
3289 len = strlen(se->idstr);
3290 qemu_put_byte(f, len);
3291 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
3293 qemu_put_be32(f, se->instance_id);
3294 qemu_put_be32(f, se->version_id);
3296 se->save_live_state(f, QEMU_VM_SECTION_START, se->opaque);
3299 if (qemu_file_has_error(f))
3305 int qemu_savevm_state_iterate(QEMUFile *f)
3310 for (se = first_se; se != NULL; se = se->next) {
3311 if (se->save_live_state == NULL)
3315 qemu_put_byte(f, QEMU_VM_SECTION_PART);
3316 qemu_put_be32(f, se->section_id);
3318 ret &= !!se->save_live_state(f, QEMU_VM_SECTION_PART, se->opaque);
3324 if (qemu_file_has_error(f))
3330 int qemu_savevm_state_complete(QEMUFile *f)
3334 for (se = first_se; se != NULL; se = se->next) {
3335 if (se->save_live_state == NULL)
3339 qemu_put_byte(f, QEMU_VM_SECTION_END);
3340 qemu_put_be32(f, se->section_id);
3342 se->save_live_state(f, QEMU_VM_SECTION_END, se->opaque);
3345 for(se = first_se; se != NULL; se = se->next) {
3348 if (se->save_state == NULL)
3352 qemu_put_byte(f, QEMU_VM_SECTION_FULL);
3353 qemu_put_be32(f, se->section_id);
3356 len = strlen(se->idstr);
3357 qemu_put_byte(f, len);
3358 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
3360 qemu_put_be32(f, se->instance_id);
3361 qemu_put_be32(f, se->version_id);
3363 se->save_state(f, se->opaque);
3366 qemu_put_byte(f, QEMU_VM_EOF);
3368 if (qemu_file_has_error(f))
3374 int qemu_savevm_state(QEMUFile *f)
3376 int saved_vm_running;
3379 saved_vm_running = vm_running;
3384 ret = qemu_savevm_state_begin(f);
3389 ret = qemu_savevm_state_iterate(f);
3394 ret = qemu_savevm_state_complete(f);
3397 if (qemu_file_has_error(f))
3400 if (!ret && saved_vm_running)
3406 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3410 for(se = first_se; se != NULL; se = se->next) {
3411 if (!strcmp(se->idstr, idstr) &&
3412 instance_id == se->instance_id)
3418 typedef struct LoadStateEntry {
3422 struct LoadStateEntry *next;
3425 static int qemu_loadvm_state_v2(QEMUFile *f)
3428 int len, ret, instance_id, record_len, version_id;
3429 int64_t total_len, end_pos, cur_pos;
3432 total_len = qemu_get_be64(f);
3433 end_pos = total_len + qemu_ftell(f);
3435 if (qemu_ftell(f) >= end_pos)
3437 len = qemu_get_byte(f);
3438 qemu_get_buffer(f, (uint8_t *)idstr, len);
3440 instance_id = qemu_get_be32(f);
3441 version_id = qemu_get_be32(f);
3442 record_len = qemu_get_be32(f);
3443 cur_pos = qemu_ftell(f);
3444 se = find_se(idstr, instance_id);
3446 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3447 instance_id, idstr);
3449 ret = se->load_state(f, se->opaque, version_id);
3451 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3452 instance_id, idstr);
3455 /* always seek to exact end of record */
3456 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3459 if (qemu_file_has_error(f))
3465 int qemu_loadvm_state(QEMUFile *f)
3467 LoadStateEntry *first_le = NULL;
3468 uint8_t section_type;
3472 v = qemu_get_be32(f);
3473 if (v != QEMU_VM_FILE_MAGIC)
3476 v = qemu_get_be32(f);
3477 if (v == QEMU_VM_FILE_VERSION_COMPAT)
3478 return qemu_loadvm_state_v2(f);
3479 if (v != QEMU_VM_FILE_VERSION)
3482 while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
3483 uint32_t instance_id, version_id, section_id;
3489 switch (section_type) {
3490 case QEMU_VM_SECTION_START:
3491 case QEMU_VM_SECTION_FULL:
3492 /* Read section start */
3493 section_id = qemu_get_be32(f);
3494 len = qemu_get_byte(f);
3495 qemu_get_buffer(f, (uint8_t *)idstr, len);
3497 instance_id = qemu_get_be32(f);
3498 version_id = qemu_get_be32(f);
3500 /* Find savevm section */
3501 se = find_se(idstr, instance_id);
3503 fprintf(stderr, "Unknown savevm section or instance '%s' %d\n", idstr, instance_id);
3508 /* Validate version */
3509 if (version_id > se->version_id) {
3510 fprintf(stderr, "savevm: unsupported version %d for '%s' v%d\n",
3511 version_id, idstr, se->version_id);
3517 le = qemu_mallocz(sizeof(*le));
3524 le->section_id = section_id;
3525 le->version_id = version_id;
3526 le->next = first_le;
3529 le->se->load_state(f, le->se->opaque, le->version_id);
3531 case QEMU_VM_SECTION_PART:
3532 case QEMU_VM_SECTION_END:
3533 section_id = qemu_get_be32(f);
3535 for (le = first_le; le && le->section_id != section_id; le = le->next);
3537 fprintf(stderr, "Unknown savevm section %d\n", section_id);
3542 le->se->load_state(f, le->se->opaque, le->version_id);
3545 fprintf(stderr, "Unknown savevm section type %d\n", section_type);
3555 LoadStateEntry *le = first_le;
3556 first_le = first_le->next;
3560 if (qemu_file_has_error(f))
3566 /* device can contain snapshots */
3567 static int bdrv_can_snapshot(BlockDriverState *bs)
3570 !bdrv_is_removable(bs) &&
3571 !bdrv_is_read_only(bs));
3574 /* device must be snapshots in order to have a reliable snapshot */
3575 static int bdrv_has_snapshot(BlockDriverState *bs)
3578 !bdrv_is_removable(bs) &&
3579 !bdrv_is_read_only(bs));
3582 static BlockDriverState *get_bs_snapshots(void)
3584 BlockDriverState *bs;
3588 return bs_snapshots;
3589 for(i = 0; i <= nb_drives; i++) {
3590 bs = drives_table[i].bdrv;
3591 if (bdrv_can_snapshot(bs))
3600 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
3603 QEMUSnapshotInfo *sn_tab, *sn;
3607 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
3610 for(i = 0; i < nb_sns; i++) {
3612 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
3622 void do_savevm(const char *name)
3624 BlockDriverState *bs, *bs1;
3625 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
3626 int must_delete, ret, i;
3627 BlockDriverInfo bdi1, *bdi = &bdi1;
3629 int saved_vm_running;
3636 bs = get_bs_snapshots();
3638 term_printf("No block device can accept snapshots\n");
3642 /* ??? Should this occur after vm_stop? */
3645 saved_vm_running = vm_running;
3650 ret = bdrv_snapshot_find(bs, old_sn, name);
3655 memset(sn, 0, sizeof(*sn));
3657 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
3658 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
3661 pstrcpy(sn->name, sizeof(sn->name), name);
3664 /* fill auxiliary fields */
3667 sn->date_sec = tb.time;
3668 sn->date_nsec = tb.millitm * 1000000;
3670 gettimeofday(&tv, NULL);
3671 sn->date_sec = tv.tv_sec;
3672 sn->date_nsec = tv.tv_usec * 1000;
3674 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
3676 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
3677 term_printf("Device %s does not support VM state snapshots\n",
3678 bdrv_get_device_name(bs));
3682 /* save the VM state */
3683 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
3685 term_printf("Could not open VM state file\n");
3688 ret = qemu_savevm_state(f);
3689 sn->vm_state_size = qemu_ftell(f);
3692 term_printf("Error %d while writing VM\n", ret);
3696 /* create the snapshots */
3698 for(i = 0; i < nb_drives; i++) {
3699 bs1 = drives_table[i].bdrv;
3700 if (bdrv_has_snapshot(bs1)) {
3702 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
3704 term_printf("Error while deleting snapshot on '%s'\n",
3705 bdrv_get_device_name(bs1));
3708 ret = bdrv_snapshot_create(bs1, sn);
3710 term_printf("Error while creating snapshot on '%s'\n",
3711 bdrv_get_device_name(bs1));
3717 if (saved_vm_running)
3721 void do_loadvm(const char *name)
3723 BlockDriverState *bs, *bs1;
3724 BlockDriverInfo bdi1, *bdi = &bdi1;
3727 int saved_vm_running;
3729 bs = get_bs_snapshots();
3731 term_printf("No block device supports snapshots\n");
3735 /* Flush all IO requests so they don't interfere with the new state. */
3738 saved_vm_running = vm_running;
3741 for(i = 0; i <= nb_drives; i++) {
3742 bs1 = drives_table[i].bdrv;
3743 if (bdrv_has_snapshot(bs1)) {
3744 ret = bdrv_snapshot_goto(bs1, name);
3747 term_printf("Warning: ");
3750 term_printf("Snapshots not supported on device '%s'\n",
3751 bdrv_get_device_name(bs1));
3754 term_printf("Could not find snapshot '%s' on device '%s'\n",
3755 name, bdrv_get_device_name(bs1));
3758 term_printf("Error %d while activating snapshot on '%s'\n",
3759 ret, bdrv_get_device_name(bs1));
3762 /* fatal on snapshot block device */
3769 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
3770 term_printf("Device %s does not support VM state snapshots\n",
3771 bdrv_get_device_name(bs));
3775 /* restore the VM state */
3776 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
3778 term_printf("Could not open VM state file\n");
3781 ret = qemu_loadvm_state(f);
3784 term_printf("Error %d while loading VM state\n", ret);
3787 if (saved_vm_running)
3791 void do_delvm(const char *name)
3793 BlockDriverState *bs, *bs1;
3796 bs = get_bs_snapshots();
3798 term_printf("No block device supports snapshots\n");
3802 for(i = 0; i <= nb_drives; i++) {
3803 bs1 = drives_table[i].bdrv;
3804 if (bdrv_has_snapshot(bs1)) {
3805 ret = bdrv_snapshot_delete(bs1, name);
3807 if (ret == -ENOTSUP)
3808 term_printf("Snapshots not supported on device '%s'\n",
3809 bdrv_get_device_name(bs1));
3811 term_printf("Error %d while deleting snapshot on '%s'\n",
3812 ret, bdrv_get_device_name(bs1));
3818 void do_info_snapshots(void)
3820 BlockDriverState *bs, *bs1;
3821 QEMUSnapshotInfo *sn_tab, *sn;
3825 bs = get_bs_snapshots();
3827 term_printf("No available block device supports snapshots\n");
3830 term_printf("Snapshot devices:");
3831 for(i = 0; i <= nb_drives; i++) {
3832 bs1 = drives_table[i].bdrv;
3833 if (bdrv_has_snapshot(bs1)) {
3835 term_printf(" %s", bdrv_get_device_name(bs1));
3840 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
3842 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
3845 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
3846 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
3847 for(i = 0; i < nb_sns; i++) {
3849 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
3854 /***********************************************************/
3855 /* ram save/restore */
3857 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3861 v = qemu_get_byte(f);
3864 if (qemu_get_buffer(f, buf, len) != len)
3868 v = qemu_get_byte(f);
3869 memset(buf, v, len);
3875 if (qemu_file_has_error(f))
3881 static int ram_load_v1(QEMUFile *f, void *opaque)
3886 if (qemu_get_be32(f) != phys_ram_size)
3888 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3889 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3896 #define BDRV_HASH_BLOCK_SIZE 1024
3897 #define IOBUF_SIZE 4096
3898 #define RAM_CBLOCK_MAGIC 0xfabe
3900 typedef struct RamDecompressState {
3903 uint8_t buf[IOBUF_SIZE];
3904 } RamDecompressState;
3906 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3909 memset(s, 0, sizeof(*s));
3911 ret = inflateInit(&s->zstream);
3917 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3921 s->zstream.avail_out = len;
3922 s->zstream.next_out = buf;
3923 while (s->zstream.avail_out > 0) {
3924 if (s->zstream.avail_in == 0) {
3925 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3927 clen = qemu_get_be16(s->f);
3928 if (clen > IOBUF_SIZE)
3930 qemu_get_buffer(s->f, s->buf, clen);
3931 s->zstream.avail_in = clen;
3932 s->zstream.next_in = s->buf;
3934 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3935 if (ret != Z_OK && ret != Z_STREAM_END) {
3942 static void ram_decompress_close(RamDecompressState *s)
3944 inflateEnd(&s->zstream);
3947 #define RAM_SAVE_FLAG_FULL 0x01
3948 #define RAM_SAVE_FLAG_COMPRESS 0x02
3949 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3950 #define RAM_SAVE_FLAG_PAGE 0x08
3951 #define RAM_SAVE_FLAG_EOS 0x10
3953 static int is_dup_page(uint8_t *page, uint8_t ch)
3955 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3956 uint32_t *array = (uint32_t *)page;
3959 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3960 if (array[i] != val)
3967 static int ram_save_block(QEMUFile *f)
3969 static ram_addr_t current_addr = 0;
3970 ram_addr_t saved_addr = current_addr;
3971 ram_addr_t addr = 0;
3974 while (addr < phys_ram_size) {
3975 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3978 cpu_physical_memory_reset_dirty(current_addr,
3979 current_addr + TARGET_PAGE_SIZE,
3980 MIGRATION_DIRTY_FLAG);
3982 ch = *(phys_ram_base + current_addr);
3984 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3985 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3986 qemu_put_byte(f, ch);
3988 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3989 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3995 addr += TARGET_PAGE_SIZE;
3996 current_addr = (saved_addr + addr) % phys_ram_size;
4002 static ram_addr_t ram_save_threshold = 10;
4004 static ram_addr_t ram_save_remaining(void)
4007 ram_addr_t count = 0;
4009 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
4010 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
4017 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
4022 /* Make sure all dirty bits are set */
4023 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
4024 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
4025 cpu_physical_memory_set_dirty(addr);
4028 /* Enable dirty memory tracking */
4029 cpu_physical_memory_set_dirty_tracking(1);
4031 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
4034 while (!qemu_file_rate_limit(f)) {
4037 ret = ram_save_block(f);
4038 if (ret == 0) /* no more blocks */
4042 /* try transferring iterative blocks of memory */
4045 cpu_physical_memory_set_dirty_tracking(0);
4047 /* flush all remaining blocks regardless of rate limiting */
4048 while (ram_save_block(f) != 0);
4051 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
4053 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
4056 static int ram_load_dead(QEMUFile *f, void *opaque)
4058 RamDecompressState s1, *s = &s1;
4062 if (ram_decompress_open(s, f) < 0)
4064 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
4065 if (ram_decompress_buf(s, buf, 1) < 0) {
4066 fprintf(stderr, "Error while reading ram block header\n");
4070 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
4071 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
4076 printf("Error block header\n");
4080 ram_decompress_close(s);
4085 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4090 if (version_id == 1)
4091 return ram_load_v1(f, opaque);
4093 if (version_id == 2) {
4094 if (qemu_get_be32(f) != phys_ram_size)
4096 return ram_load_dead(f, opaque);
4099 if (version_id != 3)
4103 addr = qemu_get_be64(f);
4105 flags = addr & ~TARGET_PAGE_MASK;
4106 addr &= TARGET_PAGE_MASK;
4108 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
4109 if (addr != phys_ram_size)
4113 if (flags & RAM_SAVE_FLAG_FULL) {
4114 if (ram_load_dead(f, opaque) < 0)
4118 if (flags & RAM_SAVE_FLAG_COMPRESS) {
4119 uint8_t ch = qemu_get_byte(f);
4120 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
4121 } else if (flags & RAM_SAVE_FLAG_PAGE)
4122 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
4123 } while (!(flags & RAM_SAVE_FLAG_EOS));
4128 void qemu_service_io(void)
4130 CPUState *env = cpu_single_env;
4132 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
4134 if (env->kqemu_enabled) {
4135 kqemu_cpu_interrupt(env);
4141 /***********************************************************/
4142 /* bottom halves (can be seen as timers which expire ASAP) */
4153 static QEMUBH *first_bh = NULL;
4155 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
4158 bh = qemu_mallocz(sizeof(QEMUBH));
4162 bh->opaque = opaque;
4163 bh->next = first_bh;
4168 int qemu_bh_poll(void)
4174 for (bh = first_bh; bh; bh = bh->next) {
4175 if (!bh->deleted && bh->scheduled) {
4184 /* remove deleted bhs */
4198 void qemu_bh_schedule_idle(QEMUBH *bh)
4206 void qemu_bh_schedule(QEMUBH *bh)
4208 CPUState *env = cpu_single_env;
4213 /* stop the currently executing CPU to execute the BH ASAP */
4215 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
4219 void qemu_bh_cancel(QEMUBH *bh)
4224 void qemu_bh_delete(QEMUBH *bh)
4230 static void qemu_bh_update_timeout(int *timeout)
4234 for (bh = first_bh; bh; bh = bh->next) {
4235 if (!bh->deleted && bh->scheduled) {
4237 /* idle bottom halves will be polled at least
4239 *timeout = MIN(10, *timeout);
4241 /* non-idle bottom halves will be executed
4250 /***********************************************************/
4251 /* machine registration */
4253 static QEMUMachine *first_machine = NULL;
4255 int qemu_register_machine(QEMUMachine *m)
4258 pm = &first_machine;
4266 static QEMUMachine *find_machine(const char *name)
4270 for(m = first_machine; m != NULL; m = m->next) {
4271 if (!strcmp(m->name, name))
4277 /***********************************************************/
4278 /* main execution loop */
4280 static void gui_update(void *opaque)
4282 DisplayState *ds = opaque;
4283 ds->dpy_refresh(ds);
4284 qemu_mod_timer(ds->gui_timer,
4285 (ds->gui_timer_interval ?
4286 ds->gui_timer_interval :
4287 GUI_REFRESH_INTERVAL)
4288 + qemu_get_clock(rt_clock));
4291 struct vm_change_state_entry {
4292 VMChangeStateHandler *cb;
4294 LIST_ENTRY (vm_change_state_entry) entries;
4297 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4299 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4302 VMChangeStateEntry *e;
4304 e = qemu_mallocz(sizeof (*e));
4310 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4314 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4316 LIST_REMOVE (e, entries);
4320 static void vm_state_notify(int running)
4322 VMChangeStateEntry *e;
4324 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4325 e->cb(e->opaque, running);
4329 /* XXX: support several handlers */
4330 static VMStopHandler *vm_stop_cb;
4331 static void *vm_stop_opaque;
4333 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4336 vm_stop_opaque = opaque;
4340 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4351 qemu_rearm_alarm_timer(alarm_timer);
4355 void vm_stop(int reason)
4358 cpu_disable_ticks();
4362 vm_stop_cb(vm_stop_opaque, reason);
4369 /* reset/shutdown handler */
4371 typedef struct QEMUResetEntry {
4372 QEMUResetHandler *func;
4374 struct QEMUResetEntry *next;
4377 static QEMUResetEntry *first_reset_entry;
4378 static int reset_requested;
4379 static int shutdown_requested;
4380 static int powerdown_requested;
4382 int qemu_shutdown_requested(void)
4384 int r = shutdown_requested;
4385 shutdown_requested = 0;
4389 int qemu_reset_requested(void)
4391 int r = reset_requested;
4392 reset_requested = 0;
4396 int qemu_powerdown_requested(void)
4398 int r = powerdown_requested;
4399 powerdown_requested = 0;
4403 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4405 QEMUResetEntry **pre, *re;
4407 pre = &first_reset_entry;
4408 while (*pre != NULL)
4409 pre = &(*pre)->next;
4410 re = qemu_mallocz(sizeof(QEMUResetEntry));
4412 re->opaque = opaque;
4417 void qemu_system_reset(void)
4421 /* reset all devices */
4422 for(re = first_reset_entry; re != NULL; re = re->next) {
4423 re->func(re->opaque);
4427 void qemu_system_reset_request(void)
4430 shutdown_requested = 1;
4432 reset_requested = 1;
4435 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4438 void qemu_system_shutdown_request(void)
4440 shutdown_requested = 1;
4442 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4445 void qemu_system_powerdown_request(void)
4447 powerdown_requested = 1;
4449 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4453 void host_main_loop_wait(int *timeout)
4459 /* XXX: need to suppress polling by better using win32 events */
4461 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4462 ret |= pe->func(pe->opaque);
4466 WaitObjects *w = &wait_objects;
4468 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4469 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4470 if (w->func[ret - WAIT_OBJECT_0])
4471 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4473 /* Check for additional signaled events */
4474 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4476 /* Check if event is signaled */
4477 ret2 = WaitForSingleObject(w->events[i], 0);
4478 if(ret2 == WAIT_OBJECT_0) {
4480 w->func[i](w->opaque[i]);
4481 } else if (ret2 == WAIT_TIMEOUT) {
4483 err = GetLastError();
4484 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4487 } else if (ret == WAIT_TIMEOUT) {
4489 err = GetLastError();
4490 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4497 void host_main_loop_wait(int *timeout)
4502 void main_loop_wait(int timeout)
4504 IOHandlerRecord *ioh;
4505 fd_set rfds, wfds, xfds;
4509 qemu_bh_update_timeout(&timeout);
4511 host_main_loop_wait(&timeout);
4513 /* poll any events */
4514 /* XXX: separate device handlers from system ones */
4519 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4523 (!ioh->fd_read_poll ||
4524 ioh->fd_read_poll(ioh->opaque) != 0)) {
4525 FD_SET(ioh->fd, &rfds);
4529 if (ioh->fd_write) {
4530 FD_SET(ioh->fd, &wfds);
4536 tv.tv_sec = timeout / 1000;
4537 tv.tv_usec = (timeout % 1000) * 1000;
4539 #if defined(CONFIG_SLIRP)
4540 if (slirp_is_inited()) {
4541 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4544 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4546 IOHandlerRecord **pioh;
4548 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4549 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4550 ioh->fd_read(ioh->opaque);
4552 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4553 ioh->fd_write(ioh->opaque);
4557 /* remove deleted IO handlers */
4558 pioh = &first_io_handler;
4568 #if defined(CONFIG_SLIRP)
4569 if (slirp_is_inited()) {
4575 slirp_select_poll(&rfds, &wfds, &xfds);
4579 /* Check bottom-halves last in case any of the earlier events triggered
4585 static int main_loop(void)
4588 #ifdef CONFIG_PROFILER
4593 cur_cpu = first_cpu;
4594 next_cpu = cur_cpu->next_cpu ?: first_cpu;
4601 #ifdef CONFIG_PROFILER
4602 ti = profile_getclock();
4607 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4608 env->icount_decr.u16.low = 0;
4609 env->icount_extra = 0;
4610 count = qemu_next_deadline();
4611 count = (count + (1 << icount_time_shift) - 1)
4612 >> icount_time_shift;
4613 qemu_icount += count;
4614 decr = (count > 0xffff) ? 0xffff : count;
4616 env->icount_decr.u16.low = decr;
4617 env->icount_extra = count;
4619 ret = cpu_exec(env);
4620 #ifdef CONFIG_PROFILER
4621 qemu_time += profile_getclock() - ti;
4624 /* Fold pending instructions back into the
4625 instruction counter, and clear the interrupt flag. */
4626 qemu_icount -= (env->icount_decr.u16.low
4627 + env->icount_extra);
4628 env->icount_decr.u32 = 0;
4629 env->icount_extra = 0;
4631 next_cpu = env->next_cpu ?: first_cpu;
4632 if (event_pending && likely(ret != EXCP_DEBUG)) {
4633 ret = EXCP_INTERRUPT;
4637 if (ret == EXCP_HLT) {
4638 /* Give the next CPU a chance to run. */
4642 if (ret != EXCP_HALTED)
4644 /* all CPUs are halted ? */
4650 if (shutdown_requested) {
4651 ret = EXCP_INTERRUPT;
4659 if (reset_requested) {
4660 reset_requested = 0;
4661 qemu_system_reset();
4662 ret = EXCP_INTERRUPT;
4664 if (powerdown_requested) {
4665 powerdown_requested = 0;
4666 qemu_system_powerdown();
4667 ret = EXCP_INTERRUPT;
4669 if (unlikely(ret == EXCP_DEBUG)) {
4670 vm_stop(EXCP_DEBUG);
4672 /* If all cpus are halted then wait until the next IRQ */
4673 /* XXX: use timeout computed from timers */
4674 if (ret == EXCP_HALTED) {
4678 /* Advance virtual time to the next event. */
4679 if (use_icount == 1) {
4680 /* When not using an adaptive execution frequency
4681 we tend to get badly out of sync with real time,
4682 so just delay for a reasonable amount of time. */
4685 delta = cpu_get_icount() - cpu_get_clock();
4688 /* If virtual time is ahead of real time then just
4690 timeout = (delta / 1000000) + 1;
4692 /* Wait for either IO to occur or the next
4694 add = qemu_next_deadline();
4695 /* We advance the timer before checking for IO.
4696 Limit the amount we advance so that early IO
4697 activity won't get the guest too far ahead. */
4701 add = (add + (1 << icount_time_shift) - 1)
4702 >> icount_time_shift;
4704 timeout = delta / 1000000;
4715 if (shutdown_requested) {
4716 ret = EXCP_INTERRUPT;
4721 #ifdef CONFIG_PROFILER
4722 ti = profile_getclock();
4724 main_loop_wait(timeout);
4725 #ifdef CONFIG_PROFILER
4726 dev_time += profile_getclock() - ti;
4729 cpu_disable_ticks();
4733 static void help(int exitcode)
4735 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
4736 "usage: %s [options] [disk_image]\n"
4738 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4740 "Standard options:\n"
4741 "-M machine select emulated machine (-M ? for list)\n"
4742 "-cpu cpu select CPU (-cpu ? for list)\n"
4743 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
4744 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
4745 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
4746 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4747 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
4748 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
4749 " [,cache=writethrough|writeback|none][,format=f]\n"
4750 " use 'file' as a drive image\n"
4751 "-mtdblock file use 'file' as on-board Flash memory image\n"
4752 "-sd file use 'file' as SecureDigital card image\n"
4753 "-pflash file use 'file' as a parallel flash image\n"
4754 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
4755 "-snapshot write to temporary files instead of disk image files\n"
4757 "-no-frame open SDL window without a frame and window decorations\n"
4758 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
4759 "-no-quit disable SDL window close capability\n"
4762 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4764 "-m megs set virtual RAM size to megs MB [default=%d]\n"
4765 "-smp n set the number of CPUs to 'n' [default=1]\n"
4766 "-nographic disable graphical output and redirect serial I/Os to console\n"
4767 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
4769 "-k language use keyboard layout (for example \"fr\" for French)\n"
4772 "-audio-help print list of audio drivers and their options\n"
4773 "-soundhw c1,... enable audio support\n"
4774 " and only specified sound cards (comma separated list)\n"
4775 " use -soundhw ? to get the list of supported cards\n"
4776 " use -soundhw all to enable all of them\n"
4778 "-vga [std|cirrus|vmware]\n"
4779 " select video card type\n"
4780 "-localtime set the real time clock to local time [default=utc]\n"
4781 "-full-screen start in full screen\n"
4783 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4785 "-usb enable the USB driver (will be the default soon)\n"
4786 "-usbdevice name add the host or guest USB device 'name'\n"
4787 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4788 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4790 "-name string set the name of the guest\n"
4791 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
4793 "Network options:\n"
4794 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4795 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4797 "-net user[,vlan=n][,hostname=host]\n"
4798 " connect the user mode network stack to VLAN 'n' and send\n"
4799 " hostname 'host' to DHCP clients\n"
4802 "-net tap[,vlan=n],ifname=name\n"
4803 " connect the host TAP network interface to VLAN 'n'\n"
4805 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4806 " connect the host TAP network interface to VLAN 'n' and use the\n"
4807 " network scripts 'file' (default=%s)\n"
4808 " and 'dfile' (default=%s);\n"
4809 " use '[down]script=no' to disable script execution;\n"
4810 " use 'fd=h' to connect to an already opened TAP interface\n"
4812 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4813 " connect the vlan 'n' to another VLAN using a socket connection\n"
4814 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4815 " connect the vlan 'n' to multicast maddr and port\n"
4817 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4818 " connect the vlan 'n' to port 'n' of a vde switch running\n"
4819 " on host and listening for incoming connections on 'socketpath'.\n"
4820 " Use group 'groupname' and mode 'octalmode' to change default\n"
4821 " ownership and permissions for communication port.\n"
4823 "-net none use it alone to have zero network devices; if no -net option\n"
4824 " is provided, the default is '-net nic -net user'\n"
4827 "-tftp dir allow tftp access to files in dir [-net user]\n"
4828 "-bootp file advertise file in BOOTP replies\n"
4830 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4832 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4833 " redirect TCP or UDP connections from host to guest [-net user]\n"
4836 "Linux boot specific:\n"
4837 "-kernel bzImage use 'bzImage' as kernel image\n"
4838 "-append cmdline use 'cmdline' as kernel command line\n"
4839 "-initrd file use 'file' as initial ram disk\n"
4841 "Debug/Expert options:\n"
4842 "-monitor dev redirect the monitor to char device 'dev'\n"
4843 "-serial dev redirect the serial port to char device 'dev'\n"
4844 "-parallel dev redirect the parallel port to char device 'dev'\n"
4845 "-pidfile file Write PID to 'file'\n"
4846 "-S freeze CPU at startup (use 'c' to start execution)\n"
4847 "-s wait gdb connection to port\n"
4848 "-p port set gdb connection port [default=%s]\n"
4849 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4850 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4851 " translation (t=none or lba) (usually qemu can guess them)\n"
4852 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4854 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4855 "-no-kqemu disable KQEMU kernel module usage\n"
4858 "-enable-kvm enable KVM full virtualization support\n"
4861 "-no-acpi disable ACPI\n"
4863 #ifdef CONFIG_CURSES
4864 "-curses use a curses/ncurses interface instead of SDL\n"
4866 "-no-reboot exit instead of rebooting\n"
4867 "-no-shutdown stop before shutdown\n"
4868 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
4869 "-vnc display start a VNC server on display\n"
4871 "-daemonize daemonize QEMU after initializing\n"
4873 "-option-rom rom load a file, rom, into the option ROM space\n"
4875 "-prom-env variable=value set OpenBIOS nvram variables\n"
4877 "-clock force the use of the given methods for timer alarm.\n"
4878 " To see what timers are available use -clock ?\n"
4879 "-startdate select initial date of the clock\n"
4880 "-icount [N|auto]\n"
4881 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
4883 "During emulation, the following keys are useful:\n"
4884 "ctrl-alt-f toggle full screen\n"
4885 "ctrl-alt-n switch to virtual console 'n'\n"
4886 "ctrl-alt toggle mouse and keyboard grab\n"
4888 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4893 DEFAULT_NETWORK_SCRIPT,
4894 DEFAULT_NETWORK_DOWN_SCRIPT,
4896 DEFAULT_GDBSTUB_PORT,
4901 #define HAS_ARG 0x0001
4916 QEMU_OPTION_mtdblock,
4920 QEMU_OPTION_snapshot,
4922 QEMU_OPTION_no_fd_bootchk,
4925 QEMU_OPTION_nographic,
4926 QEMU_OPTION_portrait,
4928 QEMU_OPTION_audio_help,
4929 QEMU_OPTION_soundhw,
4950 QEMU_OPTION_localtime,
4954 QEMU_OPTION_monitor,
4956 QEMU_OPTION_parallel,
4958 QEMU_OPTION_full_screen,
4959 QEMU_OPTION_no_frame,
4960 QEMU_OPTION_alt_grab,
4961 QEMU_OPTION_no_quit,
4962 QEMU_OPTION_pidfile,
4963 QEMU_OPTION_no_kqemu,
4964 QEMU_OPTION_kernel_kqemu,
4965 QEMU_OPTION_enable_kvm,
4966 QEMU_OPTION_win2k_hack,
4968 QEMU_OPTION_usbdevice,
4971 QEMU_OPTION_no_acpi,
4973 QEMU_OPTION_no_reboot,
4974 QEMU_OPTION_no_shutdown,
4975 QEMU_OPTION_show_cursor,
4976 QEMU_OPTION_daemonize,
4977 QEMU_OPTION_option_rom,
4978 QEMU_OPTION_semihosting,
4980 QEMU_OPTION_prom_env,
4981 QEMU_OPTION_old_param,
4983 QEMU_OPTION_startdate,
4984 QEMU_OPTION_tb_size,
4987 QEMU_OPTION_incoming,
4990 typedef struct QEMUOption {
4996 static const QEMUOption qemu_options[] = {
4997 { "h", 0, QEMU_OPTION_h },
4998 { "help", 0, QEMU_OPTION_h },
5000 { "M", HAS_ARG, QEMU_OPTION_M },
5001 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
5002 { "fda", HAS_ARG, QEMU_OPTION_fda },
5003 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
5004 { "hda", HAS_ARG, QEMU_OPTION_hda },
5005 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
5006 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
5007 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
5008 { "drive", HAS_ARG, QEMU_OPTION_drive },
5009 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
5010 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
5011 { "sd", HAS_ARG, QEMU_OPTION_sd },
5012 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
5013 { "boot", HAS_ARG, QEMU_OPTION_boot },
5014 { "snapshot", 0, QEMU_OPTION_snapshot },
5016 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
5018 { "m", HAS_ARG, QEMU_OPTION_m },
5019 { "nographic", 0, QEMU_OPTION_nographic },
5020 { "portrait", 0, QEMU_OPTION_portrait },
5021 { "k", HAS_ARG, QEMU_OPTION_k },
5023 { "audio-help", 0, QEMU_OPTION_audio_help },
5024 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
5027 { "net", HAS_ARG, QEMU_OPTION_net},
5029 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
5030 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
5032 { "smb", HAS_ARG, QEMU_OPTION_smb },
5034 { "redir", HAS_ARG, QEMU_OPTION_redir },
5037 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
5038 { "append", HAS_ARG, QEMU_OPTION_append },
5039 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
5041 { "S", 0, QEMU_OPTION_S },
5042 { "s", 0, QEMU_OPTION_s },
5043 { "p", HAS_ARG, QEMU_OPTION_p },
5044 { "d", HAS_ARG, QEMU_OPTION_d },
5045 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
5046 { "L", HAS_ARG, QEMU_OPTION_L },
5047 { "bios", HAS_ARG, QEMU_OPTION_bios },
5049 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
5050 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
5053 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
5055 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5056 { "g", 1, QEMU_OPTION_g },
5058 { "localtime", 0, QEMU_OPTION_localtime },
5059 { "vga", HAS_ARG, QEMU_OPTION_vga },
5060 { "echr", HAS_ARG, QEMU_OPTION_echr },
5061 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
5062 { "serial", HAS_ARG, QEMU_OPTION_serial },
5063 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
5064 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
5065 { "full-screen", 0, QEMU_OPTION_full_screen },
5067 { "no-frame", 0, QEMU_OPTION_no_frame },
5068 { "alt-grab", 0, QEMU_OPTION_alt_grab },
5069 { "no-quit", 0, QEMU_OPTION_no_quit },
5071 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
5072 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
5073 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
5074 { "smp", HAS_ARG, QEMU_OPTION_smp },
5075 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
5076 #ifdef CONFIG_CURSES
5077 { "curses", 0, QEMU_OPTION_curses },
5079 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
5081 /* temporary options */
5082 { "usb", 0, QEMU_OPTION_usb },
5083 { "no-acpi", 0, QEMU_OPTION_no_acpi },
5084 { "no-reboot", 0, QEMU_OPTION_no_reboot },
5085 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
5086 { "show-cursor", 0, QEMU_OPTION_show_cursor },
5087 { "daemonize", 0, QEMU_OPTION_daemonize },
5088 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
5089 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5090 { "semihosting", 0, QEMU_OPTION_semihosting },
5092 { "name", HAS_ARG, QEMU_OPTION_name },
5093 #if defined(TARGET_SPARC)
5094 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
5096 #if defined(TARGET_ARM)
5097 { "old-param", 0, QEMU_OPTION_old_param },
5099 { "clock", HAS_ARG, QEMU_OPTION_clock },
5100 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
5101 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
5102 { "icount", HAS_ARG, QEMU_OPTION_icount },
5103 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
5107 /* password input */
5109 int qemu_key_check(BlockDriverState *bs, const char *name)
5114 if (!bdrv_is_encrypted(bs))
5117 term_printf("%s is encrypted.\n", name);
5118 for(i = 0; i < 3; i++) {
5119 monitor_readline("Password: ", 1, password, sizeof(password));
5120 if (bdrv_set_key(bs, password) == 0)
5122 term_printf("invalid password\n");
5127 static BlockDriverState *get_bdrv(int index)
5129 if (index > nb_drives)
5131 return drives_table[index].bdrv;
5134 static void read_passwords(void)
5136 BlockDriverState *bs;
5139 for(i = 0; i < 6; i++) {
5142 qemu_key_check(bs, bdrv_get_device_name(bs));
5147 struct soundhw soundhw[] = {
5148 #ifdef HAS_AUDIO_CHOICE
5149 #if defined(TARGET_I386) || defined(TARGET_MIPS)
5155 { .init_isa = pcspk_audio_init }
5160 "Creative Sound Blaster 16",
5163 { .init_isa = SB16_init }
5166 #ifdef CONFIG_CS4231A
5172 { .init_isa = cs4231a_init }
5180 "Yamaha YMF262 (OPL3)",
5182 "Yamaha YM3812 (OPL2)",
5186 { .init_isa = Adlib_init }
5193 "Gravis Ultrasound GF1",
5196 { .init_isa = GUS_init }
5203 "Intel 82801AA AC97 Audio",
5206 { .init_pci = ac97_init }
5212 "ENSONIQ AudioPCI ES1370",
5215 { .init_pci = es1370_init }
5219 { NULL, NULL, 0, 0, { NULL } }
5222 static void select_soundhw (const char *optarg)
5226 if (*optarg == '?') {
5229 printf ("Valid sound card names (comma separated):\n");
5230 for (c = soundhw; c->name; ++c) {
5231 printf ("%-11s %s\n", c->name, c->descr);
5233 printf ("\n-soundhw all will enable all of the above\n");
5234 exit (*optarg != '?');
5242 if (!strcmp (optarg, "all")) {
5243 for (c = soundhw; c->name; ++c) {
5251 e = strchr (p, ',');
5252 l = !e ? strlen (p) : (size_t) (e - p);
5254 for (c = soundhw; c->name; ++c) {
5255 if (!strncmp (c->name, p, l)) {
5264 "Unknown sound card name (too big to show)\n");
5267 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5272 p += l + (e != NULL);
5276 goto show_valid_cards;
5281 static void select_vgahw (const char *p)
5285 if (strstart(p, "std", &opts)) {
5286 cirrus_vga_enabled = 0;
5288 } else if (strstart(p, "cirrus", &opts)) {
5289 cirrus_vga_enabled = 1;
5291 } else if (strstart(p, "vmware", &opts)) {
5292 cirrus_vga_enabled = 0;
5296 fprintf(stderr, "Unknown vga type: %s\n", p);
5300 const char *nextopt;
5302 if (strstart(opts, ",retrace=", &nextopt)) {
5304 if (strstart(opts, "dumb", &nextopt))
5305 vga_retrace_method = VGA_RETRACE_DUMB;
5306 else if (strstart(opts, "precise", &nextopt))
5307 vga_retrace_method = VGA_RETRACE_PRECISE;
5308 else goto invalid_vga;
5309 } else goto invalid_vga;
5315 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
5317 exit(STATUS_CONTROL_C_EXIT);
5322 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
5326 if(strlen(str) != 36)
5329 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
5330 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
5331 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
5339 #define MAX_NET_CLIENTS 32
5343 static void termsig_handler(int signal)
5345 qemu_system_shutdown_request();
5348 static void termsig_setup(void)
5350 struct sigaction act;
5352 memset(&act, 0, sizeof(act));
5353 act.sa_handler = termsig_handler;
5354 sigaction(SIGINT, &act, NULL);
5355 sigaction(SIGHUP, &act, NULL);
5356 sigaction(SIGTERM, &act, NULL);
5361 int main(int argc, char **argv)
5363 #ifdef CONFIG_GDBSTUB
5365 const char *gdbstub_port;
5367 uint32_t boot_devices_bitmap = 0;
5369 int snapshot, linux_boot, net_boot;
5370 const char *initrd_filename;
5371 const char *kernel_filename, *kernel_cmdline;
5372 const char *boot_devices = "";
5373 DisplayState *ds = &display_state;
5374 int cyls, heads, secs, translation;
5375 const char *net_clients[MAX_NET_CLIENTS];
5379 const char *r, *optarg;
5380 CharDriverState *monitor_hd;
5381 const char *monitor_device;
5382 const char *serial_devices[MAX_SERIAL_PORTS];
5383 int serial_device_index;
5384 const char *parallel_devices[MAX_PARALLEL_PORTS];
5385 int parallel_device_index;
5386 const char *loadvm = NULL;
5387 QEMUMachine *machine;
5388 const char *cpu_model;
5389 const char *usb_devices[MAX_USB_CMDLINE];
5390 int usb_devices_index;
5393 const char *pid_file = NULL;
5395 const char *incoming = NULL;
5397 LIST_INIT (&vm_change_state_head);
5400 struct sigaction act;
5401 sigfillset(&act.sa_mask);
5403 act.sa_handler = SIG_IGN;
5404 sigaction(SIGPIPE, &act, NULL);
5407 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5408 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5409 QEMU to run on a single CPU */
5414 h = GetCurrentProcess();
5415 if (GetProcessAffinityMask(h, &mask, &smask)) {
5416 for(i = 0; i < 32; i++) {
5417 if (mask & (1 << i))
5422 SetProcessAffinityMask(h, mask);
5428 register_machines();
5429 machine = first_machine;
5431 initrd_filename = NULL;
5433 vga_ram_size = VGA_RAM_SIZE;
5434 #ifdef CONFIG_GDBSTUB
5436 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5441 kernel_filename = NULL;
5442 kernel_cmdline = "";
5443 cyls = heads = secs = 0;
5444 translation = BIOS_ATA_TRANSLATION_AUTO;
5445 monitor_device = "vc";
5447 serial_devices[0] = "vc:80Cx24C";
5448 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5449 serial_devices[i] = NULL;
5450 serial_device_index = 0;
5452 parallel_devices[0] = "vc:640x480";
5453 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5454 parallel_devices[i] = NULL;
5455 parallel_device_index = 0;
5457 usb_devices_index = 0;
5475 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5477 const QEMUOption *popt;
5480 /* Treat --foo the same as -foo. */
5483 popt = qemu_options;
5486 fprintf(stderr, "%s: invalid option -- '%s'\n",
5490 if (!strcmp(popt->name, r + 1))
5494 if (popt->flags & HAS_ARG) {
5495 if (optind >= argc) {
5496 fprintf(stderr, "%s: option '%s' requires an argument\n",
5500 optarg = argv[optind++];
5505 switch(popt->index) {
5507 machine = find_machine(optarg);
5510 printf("Supported machines are:\n");
5511 for(m = first_machine; m != NULL; m = m->next) {
5512 printf("%-10s %s%s\n",
5514 m == first_machine ? " (default)" : "");
5516 exit(*optarg != '?');
5519 case QEMU_OPTION_cpu:
5520 /* hw initialization will check this */
5521 if (*optarg == '?') {
5522 /* XXX: implement xxx_cpu_list for targets that still miss it */
5523 #if defined(cpu_list)
5524 cpu_list(stdout, &fprintf);
5531 case QEMU_OPTION_initrd:
5532 initrd_filename = optarg;
5534 case QEMU_OPTION_hda:
5536 hda_index = drive_add(optarg, HD_ALIAS, 0);
5538 hda_index = drive_add(optarg, HD_ALIAS
5539 ",cyls=%d,heads=%d,secs=%d%s",
5540 0, cyls, heads, secs,
5541 translation == BIOS_ATA_TRANSLATION_LBA ?
5543 translation == BIOS_ATA_TRANSLATION_NONE ?
5544 ",trans=none" : "");
5546 case QEMU_OPTION_hdb:
5547 case QEMU_OPTION_hdc:
5548 case QEMU_OPTION_hdd:
5549 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5551 case QEMU_OPTION_drive:
5552 drive_add(NULL, "%s", optarg);
5554 case QEMU_OPTION_mtdblock:
5555 drive_add(optarg, MTD_ALIAS);
5557 case QEMU_OPTION_sd:
5558 drive_add(optarg, SD_ALIAS);
5560 case QEMU_OPTION_pflash:
5561 drive_add(optarg, PFLASH_ALIAS);
5563 case QEMU_OPTION_snapshot:
5566 case QEMU_OPTION_hdachs:
5570 cyls = strtol(p, (char **)&p, 0);
5571 if (cyls < 1 || cyls > 16383)
5576 heads = strtol(p, (char **)&p, 0);
5577 if (heads < 1 || heads > 16)
5582 secs = strtol(p, (char **)&p, 0);
5583 if (secs < 1 || secs > 63)
5587 if (!strcmp(p, "none"))
5588 translation = BIOS_ATA_TRANSLATION_NONE;
5589 else if (!strcmp(p, "lba"))
5590 translation = BIOS_ATA_TRANSLATION_LBA;
5591 else if (!strcmp(p, "auto"))
5592 translation = BIOS_ATA_TRANSLATION_AUTO;
5595 } else if (*p != '\0') {
5597 fprintf(stderr, "qemu: invalid physical CHS format\n");
5600 if (hda_index != -1)
5601 snprintf(drives_opt[hda_index].opt,
5602 sizeof(drives_opt[hda_index].opt),
5603 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5604 0, cyls, heads, secs,
5605 translation == BIOS_ATA_TRANSLATION_LBA ?
5607 translation == BIOS_ATA_TRANSLATION_NONE ?
5608 ",trans=none" : "");
5611 case QEMU_OPTION_nographic:
5614 #ifdef CONFIG_CURSES
5615 case QEMU_OPTION_curses:
5619 case QEMU_OPTION_portrait:
5622 case QEMU_OPTION_kernel:
5623 kernel_filename = optarg;
5625 case QEMU_OPTION_append:
5626 kernel_cmdline = optarg;
5628 case QEMU_OPTION_cdrom:
5629 drive_add(optarg, CDROM_ALIAS);
5631 case QEMU_OPTION_boot:
5632 boot_devices = optarg;
5633 /* We just do some generic consistency checks */
5635 /* Could easily be extended to 64 devices if needed */
5638 boot_devices_bitmap = 0;
5639 for (p = boot_devices; *p != '\0'; p++) {
5640 /* Allowed boot devices are:
5641 * a b : floppy disk drives
5642 * c ... f : IDE disk drives
5643 * g ... m : machine implementation dependant drives
5644 * n ... p : network devices
5645 * It's up to each machine implementation to check
5646 * if the given boot devices match the actual hardware
5647 * implementation and firmware features.
5649 if (*p < 'a' || *p > 'q') {
5650 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5653 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5655 "Boot device '%c' was given twice\n",*p);
5658 boot_devices_bitmap |= 1 << (*p - 'a');
5662 case QEMU_OPTION_fda:
5663 case QEMU_OPTION_fdb:
5664 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5667 case QEMU_OPTION_no_fd_bootchk:
5671 case QEMU_OPTION_net:
5672 if (nb_net_clients >= MAX_NET_CLIENTS) {
5673 fprintf(stderr, "qemu: too many network clients\n");
5676 net_clients[nb_net_clients] = optarg;
5680 case QEMU_OPTION_tftp:
5681 tftp_prefix = optarg;
5683 case QEMU_OPTION_bootp:
5684 bootp_filename = optarg;
5687 case QEMU_OPTION_smb:
5688 net_slirp_smb(optarg);
5691 case QEMU_OPTION_redir:
5692 net_slirp_redir(optarg);
5696 case QEMU_OPTION_audio_help:
5700 case QEMU_OPTION_soundhw:
5701 select_soundhw (optarg);
5707 case QEMU_OPTION_m: {
5711 value = strtoul(optarg, &ptr, 10);
5713 case 0: case 'M': case 'm':
5720 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5724 /* On 32-bit hosts, QEMU is limited by virtual address space */
5725 if (value > (2047 << 20)
5727 && HOST_LONG_BITS == 32
5730 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5733 if (value != (uint64_t)(ram_addr_t)value) {
5734 fprintf(stderr, "qemu: ram size too large\n");
5743 const CPULogItem *item;
5745 mask = cpu_str_to_log_mask(optarg);
5747 printf("Log items (comma separated):\n");
5748 for(item = cpu_log_items; item->mask != 0; item++) {
5749 printf("%-10s %s\n", item->name, item->help);
5756 #ifdef CONFIG_GDBSTUB
5761 gdbstub_port = optarg;
5767 case QEMU_OPTION_bios:
5774 keyboard_layout = optarg;
5776 case QEMU_OPTION_localtime:
5779 case QEMU_OPTION_vga:
5780 select_vgahw (optarg);
5787 w = strtol(p, (char **)&p, 10);
5790 fprintf(stderr, "qemu: invalid resolution or depth\n");
5796 h = strtol(p, (char **)&p, 10);
5801 depth = strtol(p, (char **)&p, 10);
5802 if (depth != 8 && depth != 15 && depth != 16 &&
5803 depth != 24 && depth != 32)
5805 } else if (*p == '\0') {
5806 depth = graphic_depth;
5813 graphic_depth = depth;
5816 case QEMU_OPTION_echr:
5819 term_escape_char = strtol(optarg, &r, 0);
5821 printf("Bad argument to echr\n");
5824 case QEMU_OPTION_monitor:
5825 monitor_device = optarg;
5827 case QEMU_OPTION_serial:
5828 if (serial_device_index >= MAX_SERIAL_PORTS) {
5829 fprintf(stderr, "qemu: too many serial ports\n");
5832 serial_devices[serial_device_index] = optarg;
5833 serial_device_index++;
5835 case QEMU_OPTION_parallel:
5836 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5837 fprintf(stderr, "qemu: too many parallel ports\n");
5840 parallel_devices[parallel_device_index] = optarg;
5841 parallel_device_index++;
5843 case QEMU_OPTION_loadvm:
5846 case QEMU_OPTION_full_screen:
5850 case QEMU_OPTION_no_frame:
5853 case QEMU_OPTION_alt_grab:
5856 case QEMU_OPTION_no_quit:
5860 case QEMU_OPTION_pidfile:
5864 case QEMU_OPTION_win2k_hack:
5865 win2k_install_hack = 1;
5869 case QEMU_OPTION_no_kqemu:
5872 case QEMU_OPTION_kernel_kqemu:
5877 case QEMU_OPTION_enable_kvm:
5884 case QEMU_OPTION_usb:
5887 case QEMU_OPTION_usbdevice:
5889 if (usb_devices_index >= MAX_USB_CMDLINE) {
5890 fprintf(stderr, "Too many USB devices\n");
5893 usb_devices[usb_devices_index] = optarg;
5894 usb_devices_index++;
5896 case QEMU_OPTION_smp:
5897 smp_cpus = atoi(optarg);
5899 fprintf(stderr, "Invalid number of CPUs\n");
5903 case QEMU_OPTION_vnc:
5904 vnc_display = optarg;
5906 case QEMU_OPTION_no_acpi:
5909 case QEMU_OPTION_no_reboot:
5912 case QEMU_OPTION_no_shutdown:
5915 case QEMU_OPTION_show_cursor:
5918 case QEMU_OPTION_uuid:
5919 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5920 fprintf(stderr, "Fail to parse UUID string."
5921 " Wrong format.\n");
5925 case QEMU_OPTION_daemonize:
5928 case QEMU_OPTION_option_rom:
5929 if (nb_option_roms >= MAX_OPTION_ROMS) {
5930 fprintf(stderr, "Too many option ROMs\n");
5933 option_rom[nb_option_roms] = optarg;
5936 case QEMU_OPTION_semihosting:
5937 semihosting_enabled = 1;
5939 case QEMU_OPTION_name:
5943 case QEMU_OPTION_prom_env:
5944 if (nb_prom_envs >= MAX_PROM_ENVS) {
5945 fprintf(stderr, "Too many prom variables\n");
5948 prom_envs[nb_prom_envs] = optarg;
5953 case QEMU_OPTION_old_param:
5957 case QEMU_OPTION_clock:
5958 configure_alarms(optarg);
5960 case QEMU_OPTION_startdate:
5963 time_t rtc_start_date;
5964 if (!strcmp(optarg, "now")) {
5965 rtc_date_offset = -1;
5967 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5975 } else if (sscanf(optarg, "%d-%d-%d",
5978 &tm.tm_mday) == 3) {
5987 rtc_start_date = mktimegm(&tm);
5988 if (rtc_start_date == -1) {
5990 fprintf(stderr, "Invalid date format. Valid format are:\n"
5991 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5994 rtc_date_offset = time(NULL) - rtc_start_date;
5998 case QEMU_OPTION_tb_size:
5999 tb_size = strtol(optarg, NULL, 0);
6003 case QEMU_OPTION_icount:
6005 if (strcmp(optarg, "auto") == 0) {
6006 icount_time_shift = -1;
6008 icount_time_shift = strtol(optarg, NULL, 0);
6011 case QEMU_OPTION_incoming:
6018 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
6019 if (kvm_allowed && kqemu_allowed) {
6021 "You can not enable both KVM and kqemu at the same time\n");
6026 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
6027 if (smp_cpus > machine->max_cpus) {
6028 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
6029 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
6035 if (serial_device_index == 0)
6036 serial_devices[0] = "stdio";
6037 if (parallel_device_index == 0)
6038 parallel_devices[0] = "null";
6039 if (strncmp(monitor_device, "vc", 2) == 0)
6040 monitor_device = "stdio";
6047 if (pipe(fds) == -1)
6058 len = read(fds[0], &status, 1);
6059 if (len == -1 && (errno == EINTR))
6064 else if (status == 1) {
6065 fprintf(stderr, "Could not acquire pidfile\n");
6082 signal(SIGTSTP, SIG_IGN);
6083 signal(SIGTTOU, SIG_IGN);
6084 signal(SIGTTIN, SIG_IGN);
6088 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
6091 write(fds[1], &status, 1);
6093 fprintf(stderr, "Could not acquire pid file\n");
6101 linux_boot = (kernel_filename != NULL);
6102 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
6104 if (!linux_boot && net_boot == 0 &&
6105 !machine->nodisk_ok && nb_drives_opt == 0)
6108 if (!linux_boot && *kernel_cmdline != '\0') {
6109 fprintf(stderr, "-append only allowed with -kernel option\n");
6113 if (!linux_boot && initrd_filename != NULL) {
6114 fprintf(stderr, "-initrd only allowed with -kernel option\n");
6118 /* boot to floppy or the default cd if no hard disk defined yet */
6119 if (!boot_devices[0]) {
6120 boot_devices = "cad";
6122 setvbuf(stdout, NULL, _IOLBF, 0);
6125 if (init_timer_alarm() < 0) {
6126 fprintf(stderr, "could not initialize alarm timer\n");
6129 if (use_icount && icount_time_shift < 0) {
6131 /* 125MIPS seems a reasonable initial guess at the guest speed.
6132 It will be corrected fairly quickly anyway. */
6133 icount_time_shift = 3;
6134 init_icount_adjust();
6141 /* init network clients */
6142 if (nb_net_clients == 0) {
6143 /* if no clients, we use a default config */
6144 net_clients[nb_net_clients++] = "nic";
6146 net_clients[nb_net_clients++] = "user";
6150 for(i = 0;i < nb_net_clients; i++) {
6151 if (net_client_parse(net_clients[i]) < 0)
6157 /* XXX: this should be moved in the PC machine instantiation code */
6158 if (net_boot != 0) {
6160 for (i = 0; i < nb_nics && i < 4; i++) {
6161 const char *model = nd_table[i].model;
6163 if (net_boot & (1 << i)) {
6166 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
6167 if (get_image_size(buf) > 0) {
6168 if (nb_option_roms >= MAX_OPTION_ROMS) {
6169 fprintf(stderr, "Too many option ROMs\n");
6172 option_rom[nb_option_roms] = strdup(buf);
6179 fprintf(stderr, "No valid PXE rom found for network device\n");
6185 /* init the memory */
6186 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
6188 if (machine->ram_require & RAMSIZE_FIXED) {
6190 if (ram_size < phys_ram_size) {
6191 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
6192 machine->name, (unsigned long long) phys_ram_size);
6196 phys_ram_size = ram_size;
6198 ram_size = phys_ram_size;
6201 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6203 phys_ram_size += ram_size;
6206 phys_ram_base = qemu_vmalloc(phys_ram_size);
6207 if (!phys_ram_base) {
6208 fprintf(stderr, "Could not allocate physical memory\n");
6212 /* init the dynamic translator */
6213 cpu_exec_init_all(tb_size * 1024 * 1024);
6217 /* we always create the cdrom drive, even if no disk is there */
6219 if (nb_drives_opt < MAX_DRIVES)
6220 drive_add(NULL, CDROM_ALIAS);
6222 /* we always create at least one floppy */
6224 if (nb_drives_opt < MAX_DRIVES)
6225 drive_add(NULL, FD_ALIAS, 0);
6227 /* we always create one sd slot, even if no card is in it */
6229 if (nb_drives_opt < MAX_DRIVES)
6230 drive_add(NULL, SD_ALIAS);
6232 /* open the virtual block devices */
6234 for(i = 0; i < nb_drives_opt; i++)
6235 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
6238 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6239 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
6242 memset(&display_state, 0, sizeof(display_state));
6245 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
6248 /* nearly nothing to do */
6249 dumb_display_init(ds);
6250 } else if (vnc_display != NULL) {
6251 vnc_display_init(ds);
6252 if (vnc_display_open(ds, vnc_display) < 0)
6255 #if defined(CONFIG_CURSES)
6257 curses_display_init(ds, full_screen);
6261 #if defined(CONFIG_SDL)
6262 sdl_display_init(ds, full_screen, no_frame);
6263 #elif defined(CONFIG_COCOA)
6264 cocoa_display_init(ds, full_screen);
6266 dumb_display_init(ds);
6271 /* must be after terminal init, SDL library changes signal handlers */
6275 /* Maintain compatibility with multiple stdio monitors */
6276 if (!strcmp(monitor_device,"stdio")) {
6277 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
6278 const char *devname = serial_devices[i];
6279 if (devname && !strcmp(devname,"mon:stdio")) {
6280 monitor_device = NULL;
6282 } else if (devname && !strcmp(devname,"stdio")) {
6283 monitor_device = NULL;
6284 serial_devices[i] = "mon:stdio";
6289 if (monitor_device) {
6290 monitor_hd = qemu_chr_open("monitor", monitor_device);
6292 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6295 monitor_init(monitor_hd, !nographic);
6298 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6299 const char *devname = serial_devices[i];
6300 if (devname && strcmp(devname, "none")) {
6302 snprintf(label, sizeof(label), "serial%d", i);
6303 serial_hds[i] = qemu_chr_open(label, devname);
6304 if (!serial_hds[i]) {
6305 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6309 if (strstart(devname, "vc", 0))
6310 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6314 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6315 const char *devname = parallel_devices[i];
6316 if (devname && strcmp(devname, "none")) {
6318 snprintf(label, sizeof(label), "parallel%d", i);
6319 parallel_hds[i] = qemu_chr_open(label, devname);
6320 if (!parallel_hds[i]) {
6321 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6325 if (strstart(devname, "vc", 0))
6326 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6330 if (kvm_enabled()) {
6333 ret = kvm_init(smp_cpus);
6335 fprintf(stderr, "failed to initialize KVM\n");
6340 machine->init(ram_size, vga_ram_size, boot_devices, ds,
6341 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6343 /* init USB devices */
6345 for(i = 0; i < usb_devices_index; i++) {
6346 if (usb_device_add(usb_devices[i]) < 0) {
6347 fprintf(stderr, "Warning: could not add USB device %s\n",
6353 if (display_state.dpy_refresh) {
6354 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
6355 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
6358 #ifdef CONFIG_GDBSTUB
6360 /* XXX: use standard host:port notation and modify options
6362 if (gdbserver_start(gdbstub_port) < 0) {
6363 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
6374 autostart = 0; /* fixme how to deal with -daemonize */
6375 qemu_start_incoming_migration(incoming);
6379 /* XXX: simplify init */
6392 len = write(fds[1], &status, 1);
6393 if (len == -1 && (errno == EINTR))
6400 TFR(fd = open("/dev/null", O_RDWR));