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"
39 #include "cache-utils.h"
41 #include "audio/audio.h"
42 #include "migration.h"
55 #include <sys/times.h>
59 #include <sys/ioctl.h>
60 #include <sys/resource.h>
61 #include <sys/socket.h>
62 #include <netinet/in.h>
64 #if defined(__NetBSD__)
65 #include <net/if_tap.h>
68 #include <linux/if_tun.h>
70 #include <arpa/inet.h>
73 #include <sys/select.h>
81 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
82 #include <freebsd/stdlib.h>
87 #include <linux/rtc.h>
89 /* For the benefit of older linux systems which don't supply it,
90 we use a local copy of hpet.h. */
91 /* #include <linux/hpet.h> */
94 #include <linux/ppdev.h>
95 #include <linux/parport.h>
99 #include <sys/ethernet.h>
100 #include <sys/sockio.h>
101 #include <netinet/arp.h>
102 #include <netinet/in.h>
103 #include <netinet/in_systm.h>
104 #include <netinet/ip.h>
105 #include <netinet/ip_icmp.h> // must come after ip.h
106 #include <netinet/udp.h>
107 #include <netinet/tcp.h>
115 #include "qemu_socket.h"
117 #if defined(CONFIG_SLIRP)
118 #include "libslirp.h"
121 #if defined(__OpenBSD__)
125 #if defined(CONFIG_VDE)
126 #include <libvdeplug.h>
131 #include <sys/timeb.h>
132 #include <mmsystem.h>
133 #define getopt_long_only getopt_long
134 #define memalign(align, size) malloc(size)
141 #endif /* CONFIG_SDL */
145 #define main qemu_main
146 #endif /* CONFIG_COCOA */
150 #include "exec-all.h"
152 //#define DEBUG_UNUSED_IOPORT
153 //#define DEBUG_IOPORT
155 //#define DEBUG_SLIRP
159 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
161 # define LOG_IOPORT(...) do { } while (0)
164 #define DEFAULT_RAM_SIZE 128
166 /* Max number of USB devices that can be specified on the commandline. */
167 #define MAX_USB_CMDLINE 8
169 /* Max number of bluetooth switches on the commandline. */
170 #define MAX_BT_CMDLINE 10
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 static int vga_ram_size;
185 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
186 static DisplayState *display_state;
190 const char* keyboard_layout = NULL;
191 int64_t ticks_per_sec;
194 NICInfo nd_table[MAX_NICS];
196 static int rtc_utc = 1;
197 static int rtc_date_offset = -1; /* -1 means no change */
198 int cirrus_vga_enabled = 1;
199 int std_vga_enabled = 0;
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;
212 static int no_frame = 0;
215 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
216 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
217 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
219 int win2k_install_hack = 0;
224 const char *vnc_display;
225 int acpi_enabled = 1;
231 int graphic_rotate = 0;
233 const char *option_rom[MAX_OPTION_ROMS];
235 int semihosting_enabled = 0;
239 const char *qemu_name;
241 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
242 unsigned int nb_prom_envs = 0;
243 const char *prom_envs[MAX_PROM_ENVS];
245 static int nb_drives_opt;
246 static struct drive_opt {
250 } drives_opt[MAX_DRIVES];
252 static CPUState *cur_cpu;
253 static CPUState *next_cpu;
254 static int event_pending = 1;
255 /* Conversion factor from emulated instructions to virtual clock ticks. */
256 static int icount_time_shift;
257 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
258 #define MAX_ICOUNT_SHIFT 10
259 /* Compensate for varying guest execution speed. */
260 static int64_t qemu_icount_bias;
261 static QEMUTimer *icount_rt_timer;
262 static QEMUTimer *icount_vm_timer;
263 static QEMUTimer *nographic_timer;
265 uint8_t qemu_uuid[16];
267 /***********************************************************/
268 /* x86 ISA bus support */
270 target_phys_addr_t isa_mem_base = 0;
273 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
274 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
276 static uint32_t ioport_read(int index, uint32_t address)
278 static IOPortReadFunc *default_func[3] = {
279 default_ioport_readb,
280 default_ioport_readw,
283 IOPortReadFunc *func = ioport_read_table[index][address];
285 func = default_func[index];
286 return func(ioport_opaque[address], address);
289 static void ioport_write(int index, uint32_t address, uint32_t data)
291 static IOPortWriteFunc *default_func[3] = {
292 default_ioport_writeb,
293 default_ioport_writew,
294 default_ioport_writel
296 IOPortWriteFunc *func = ioport_write_table[index][address];
298 func = default_func[index];
299 func(ioport_opaque[address], address, data);
302 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
304 #ifdef DEBUG_UNUSED_IOPORT
305 fprintf(stderr, "unused inb: port=0x%04x\n", address);
310 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
312 #ifdef DEBUG_UNUSED_IOPORT
313 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
317 /* default is to make two byte accesses */
318 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
321 data = ioport_read(0, address);
322 address = (address + 1) & (MAX_IOPORTS - 1);
323 data |= ioport_read(0, address) << 8;
327 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
329 ioport_write(0, address, data & 0xff);
330 address = (address + 1) & (MAX_IOPORTS - 1);
331 ioport_write(0, address, (data >> 8) & 0xff);
334 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
336 #ifdef DEBUG_UNUSED_IOPORT
337 fprintf(stderr, "unused inl: port=0x%04x\n", address);
342 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
344 #ifdef DEBUG_UNUSED_IOPORT
345 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
349 /* size is the word size in byte */
350 int register_ioport_read(int start, int length, int size,
351 IOPortReadFunc *func, void *opaque)
357 } else if (size == 2) {
359 } else if (size == 4) {
362 hw_error("register_ioport_read: invalid size");
365 for(i = start; i < start + length; i += size) {
366 ioport_read_table[bsize][i] = func;
367 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
368 hw_error("register_ioport_read: invalid opaque");
369 ioport_opaque[i] = opaque;
374 /* size is the word size in byte */
375 int register_ioport_write(int start, int length, int size,
376 IOPortWriteFunc *func, void *opaque)
382 } else if (size == 2) {
384 } else if (size == 4) {
387 hw_error("register_ioport_write: invalid size");
390 for(i = start; i < start + length; i += size) {
391 ioport_write_table[bsize][i] = func;
392 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
393 hw_error("register_ioport_write: invalid opaque");
394 ioport_opaque[i] = opaque;
399 void isa_unassign_ioport(int start, int length)
403 for(i = start; i < start + length; i++) {
404 ioport_read_table[0][i] = default_ioport_readb;
405 ioport_read_table[1][i] = default_ioport_readw;
406 ioport_read_table[2][i] = default_ioport_readl;
408 ioport_write_table[0][i] = default_ioport_writeb;
409 ioport_write_table[1][i] = default_ioport_writew;
410 ioport_write_table[2][i] = default_ioport_writel;
414 /***********************************************************/
416 void cpu_outb(CPUState *env, int addr, int val)
418 LOG_IOPORT("outb: %04x %02x\n", addr, val);
419 ioport_write(0, addr, val);
422 env->last_io_time = cpu_get_time_fast();
426 void cpu_outw(CPUState *env, int addr, int val)
428 LOG_IOPORT("outw: %04x %04x\n", addr, val);
429 ioport_write(1, addr, val);
432 env->last_io_time = cpu_get_time_fast();
436 void cpu_outl(CPUState *env, int addr, int val)
438 LOG_IOPORT("outl: %04x %08x\n", addr, val);
439 ioport_write(2, addr, val);
442 env->last_io_time = cpu_get_time_fast();
446 int cpu_inb(CPUState *env, int addr)
449 val = ioport_read(0, addr);
450 LOG_IOPORT("inb : %04x %02x\n", addr, val);
453 env->last_io_time = cpu_get_time_fast();
458 int cpu_inw(CPUState *env, int addr)
461 val = ioport_read(1, addr);
462 LOG_IOPORT("inw : %04x %04x\n", addr, val);
465 env->last_io_time = cpu_get_time_fast();
470 int cpu_inl(CPUState *env, int addr)
473 val = ioport_read(2, addr);
474 LOG_IOPORT("inl : %04x %08x\n", addr, val);
477 env->last_io_time = cpu_get_time_fast();
482 /***********************************************************/
483 void hw_error(const char *fmt, ...)
489 fprintf(stderr, "qemu: hardware error: ");
490 vfprintf(stderr, fmt, ap);
491 fprintf(stderr, "\n");
492 for(env = first_cpu; env != NULL; env = env->next_cpu) {
493 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
495 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
497 cpu_dump_state(env, stderr, fprintf, 0);
507 static QEMUBalloonEvent *qemu_balloon_event;
508 void *qemu_balloon_event_opaque;
510 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
512 qemu_balloon_event = func;
513 qemu_balloon_event_opaque = opaque;
516 void qemu_balloon(ram_addr_t target)
518 if (qemu_balloon_event)
519 qemu_balloon_event(qemu_balloon_event_opaque, target);
522 ram_addr_t qemu_balloon_status(void)
524 if (qemu_balloon_event)
525 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
529 /***********************************************************/
532 static QEMUPutKBDEvent *qemu_put_kbd_event;
533 static void *qemu_put_kbd_event_opaque;
534 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
535 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
537 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
539 qemu_put_kbd_event_opaque = opaque;
540 qemu_put_kbd_event = func;
543 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
544 void *opaque, int absolute,
547 QEMUPutMouseEntry *s, *cursor;
549 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
551 s->qemu_put_mouse_event = func;
552 s->qemu_put_mouse_event_opaque = opaque;
553 s->qemu_put_mouse_event_absolute = absolute;
554 s->qemu_put_mouse_event_name = qemu_strdup(name);
557 if (!qemu_put_mouse_event_head) {
558 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
562 cursor = qemu_put_mouse_event_head;
563 while (cursor->next != NULL)
564 cursor = cursor->next;
567 qemu_put_mouse_event_current = s;
572 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
574 QEMUPutMouseEntry *prev = NULL, *cursor;
576 if (!qemu_put_mouse_event_head || entry == NULL)
579 cursor = qemu_put_mouse_event_head;
580 while (cursor != NULL && cursor != entry) {
582 cursor = cursor->next;
585 if (cursor == NULL) // does not exist or list empty
587 else if (prev == NULL) { // entry is head
588 qemu_put_mouse_event_head = cursor->next;
589 if (qemu_put_mouse_event_current == entry)
590 qemu_put_mouse_event_current = cursor->next;
591 qemu_free(entry->qemu_put_mouse_event_name);
596 prev->next = entry->next;
598 if (qemu_put_mouse_event_current == entry)
599 qemu_put_mouse_event_current = prev;
601 qemu_free(entry->qemu_put_mouse_event_name);
605 void kbd_put_keycode(int keycode)
607 if (qemu_put_kbd_event) {
608 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
612 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
614 QEMUPutMouseEvent *mouse_event;
615 void *mouse_event_opaque;
618 if (!qemu_put_mouse_event_current) {
623 qemu_put_mouse_event_current->qemu_put_mouse_event;
625 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
628 if (graphic_rotate) {
629 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
632 width = graphic_width - 1;
633 mouse_event(mouse_event_opaque,
634 width - dy, dx, dz, buttons_state);
636 mouse_event(mouse_event_opaque,
637 dx, dy, dz, buttons_state);
641 int kbd_mouse_is_absolute(void)
643 if (!qemu_put_mouse_event_current)
646 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
649 void do_info_mice(void)
651 QEMUPutMouseEntry *cursor;
654 if (!qemu_put_mouse_event_head) {
655 term_printf("No mouse devices connected\n");
659 term_printf("Mouse devices available:\n");
660 cursor = qemu_put_mouse_event_head;
661 while (cursor != NULL) {
662 term_printf("%c Mouse #%d: %s\n",
663 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
664 index, cursor->qemu_put_mouse_event_name);
666 cursor = cursor->next;
670 void do_mouse_set(int index)
672 QEMUPutMouseEntry *cursor;
675 if (!qemu_put_mouse_event_head) {
676 term_printf("No mouse devices connected\n");
680 cursor = qemu_put_mouse_event_head;
681 while (cursor != NULL && index != i) {
683 cursor = cursor->next;
687 qemu_put_mouse_event_current = cursor;
689 term_printf("Mouse at given index not found\n");
692 /* compute with 96 bit intermediate result: (a*b)/c */
693 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
698 #ifdef WORDS_BIGENDIAN
708 rl = (uint64_t)u.l.low * (uint64_t)b;
709 rh = (uint64_t)u.l.high * (uint64_t)b;
712 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
716 /***********************************************************/
717 /* real time host monotonic timer */
719 #define QEMU_TIMER_BASE 1000000000LL
723 static int64_t clock_freq;
725 static void init_get_clock(void)
729 ret = QueryPerformanceFrequency(&freq);
731 fprintf(stderr, "Could not calibrate ticks\n");
734 clock_freq = freq.QuadPart;
737 static int64_t get_clock(void)
740 QueryPerformanceCounter(&ti);
741 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
746 static int use_rt_clock;
748 static void init_get_clock(void)
751 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
754 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
761 static int64_t get_clock(void)
763 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
766 clock_gettime(CLOCK_MONOTONIC, &ts);
767 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
771 /* XXX: using gettimeofday leads to problems if the date
772 changes, so it should be avoided. */
774 gettimeofday(&tv, NULL);
775 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
780 /* Return the virtual CPU time, based on the instruction counter. */
781 static int64_t cpu_get_icount(void)
784 CPUState *env = cpu_single_env;;
785 icount = qemu_icount;
788 fprintf(stderr, "Bad clock read\n");
789 icount -= (env->icount_decr.u16.low + env->icount_extra);
791 return qemu_icount_bias + (icount << icount_time_shift);
794 /***********************************************************/
795 /* guest cycle counter */
797 static int64_t cpu_ticks_prev;
798 static int64_t cpu_ticks_offset;
799 static int64_t cpu_clock_offset;
800 static int cpu_ticks_enabled;
802 /* return the host CPU cycle counter and handle stop/restart */
803 int64_t cpu_get_ticks(void)
806 return cpu_get_icount();
808 if (!cpu_ticks_enabled) {
809 return cpu_ticks_offset;
812 ticks = cpu_get_real_ticks();
813 if (cpu_ticks_prev > ticks) {
814 /* Note: non increasing ticks may happen if the host uses
816 cpu_ticks_offset += cpu_ticks_prev - ticks;
818 cpu_ticks_prev = ticks;
819 return ticks + cpu_ticks_offset;
823 /* return the host CPU monotonic timer and handle stop/restart */
824 static int64_t cpu_get_clock(void)
827 if (!cpu_ticks_enabled) {
828 return cpu_clock_offset;
831 return ti + cpu_clock_offset;
835 /* enable cpu_get_ticks() */
836 void cpu_enable_ticks(void)
838 if (!cpu_ticks_enabled) {
839 cpu_ticks_offset -= cpu_get_real_ticks();
840 cpu_clock_offset -= get_clock();
841 cpu_ticks_enabled = 1;
845 /* disable cpu_get_ticks() : the clock is stopped. You must not call
846 cpu_get_ticks() after that. */
847 void cpu_disable_ticks(void)
849 if (cpu_ticks_enabled) {
850 cpu_ticks_offset = cpu_get_ticks();
851 cpu_clock_offset = cpu_get_clock();
852 cpu_ticks_enabled = 0;
856 /***********************************************************/
859 #define QEMU_TIMER_REALTIME 0
860 #define QEMU_TIMER_VIRTUAL 1
864 /* XXX: add frequency */
872 struct QEMUTimer *next;
875 struct qemu_alarm_timer {
879 int (*start)(struct qemu_alarm_timer *t);
880 void (*stop)(struct qemu_alarm_timer *t);
881 void (*rearm)(struct qemu_alarm_timer *t);
885 #define ALARM_FLAG_DYNTICKS 0x1
886 #define ALARM_FLAG_EXPIRED 0x2
888 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
890 return t->flags & ALARM_FLAG_DYNTICKS;
893 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
895 if (!alarm_has_dynticks(t))
901 /* TODO: MIN_TIMER_REARM_US should be optimized */
902 #define MIN_TIMER_REARM_US 250
904 static struct qemu_alarm_timer *alarm_timer;
906 static int alarm_timer_rfd, alarm_timer_wfd;
911 struct qemu_alarm_win32 {
915 } alarm_win32_data = {0, NULL, -1};
917 static int win32_start_timer(struct qemu_alarm_timer *t);
918 static void win32_stop_timer(struct qemu_alarm_timer *t);
919 static void win32_rearm_timer(struct qemu_alarm_timer *t);
923 static int unix_start_timer(struct qemu_alarm_timer *t);
924 static void unix_stop_timer(struct qemu_alarm_timer *t);
928 static int dynticks_start_timer(struct qemu_alarm_timer *t);
929 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
930 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
932 static int hpet_start_timer(struct qemu_alarm_timer *t);
933 static void hpet_stop_timer(struct qemu_alarm_timer *t);
935 static int rtc_start_timer(struct qemu_alarm_timer *t);
936 static void rtc_stop_timer(struct qemu_alarm_timer *t);
938 #endif /* __linux__ */
942 /* Correlation between real and virtual time is always going to be
943 fairly approximate, so ignore small variation.
944 When the guest is idle real and virtual time will be aligned in
946 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
948 static void icount_adjust(void)
953 static int64_t last_delta;
954 /* If the VM is not running, then do nothing. */
958 cur_time = cpu_get_clock();
959 cur_icount = qemu_get_clock(vm_clock);
960 delta = cur_icount - cur_time;
961 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
963 && last_delta + ICOUNT_WOBBLE < delta * 2
964 && icount_time_shift > 0) {
965 /* The guest is getting too far ahead. Slow time down. */
969 && last_delta - ICOUNT_WOBBLE > delta * 2
970 && icount_time_shift < MAX_ICOUNT_SHIFT) {
971 /* The guest is getting too far behind. Speed time up. */
975 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
978 static void icount_adjust_rt(void * opaque)
980 qemu_mod_timer(icount_rt_timer,
981 qemu_get_clock(rt_clock) + 1000);
985 static void icount_adjust_vm(void * opaque)
987 qemu_mod_timer(icount_vm_timer,
988 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
992 static void init_icount_adjust(void)
994 /* Have both realtime and virtual time triggers for speed adjustment.
995 The realtime trigger catches emulated time passing too slowly,
996 the virtual time trigger catches emulated time passing too fast.
997 Realtime triggers occur even when idle, so use them less frequently
999 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1000 qemu_mod_timer(icount_rt_timer,
1001 qemu_get_clock(rt_clock) + 1000);
1002 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1003 qemu_mod_timer(icount_vm_timer,
1004 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1007 static struct qemu_alarm_timer alarm_timers[] = {
1010 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1011 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1012 /* HPET - if available - is preferred */
1013 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1014 /* ...otherwise try RTC */
1015 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1017 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1019 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1020 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1021 {"win32", 0, win32_start_timer,
1022 win32_stop_timer, NULL, &alarm_win32_data},
1027 static void show_available_alarms(void)
1031 printf("Available alarm timers, in order of precedence:\n");
1032 for (i = 0; alarm_timers[i].name; i++)
1033 printf("%s\n", alarm_timers[i].name);
1036 static void configure_alarms(char const *opt)
1040 int count = ARRAY_SIZE(alarm_timers) - 1;
1043 struct qemu_alarm_timer tmp;
1045 if (!strcmp(opt, "?")) {
1046 show_available_alarms();
1052 /* Reorder the array */
1053 name = strtok(arg, ",");
1055 for (i = 0; i < count && alarm_timers[i].name; i++) {
1056 if (!strcmp(alarm_timers[i].name, name))
1061 fprintf(stderr, "Unknown clock %s\n", name);
1070 tmp = alarm_timers[i];
1071 alarm_timers[i] = alarm_timers[cur];
1072 alarm_timers[cur] = tmp;
1076 name = strtok(NULL, ",");
1082 /* Disable remaining timers */
1083 for (i = cur; i < count; i++)
1084 alarm_timers[i].name = NULL;
1086 show_available_alarms();
1091 QEMUClock *rt_clock;
1092 QEMUClock *vm_clock;
1094 static QEMUTimer *active_timers[2];
1096 static QEMUClock *qemu_new_clock(int type)
1099 clock = qemu_mallocz(sizeof(QEMUClock));
1104 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1108 ts = qemu_mallocz(sizeof(QEMUTimer));
1111 ts->opaque = opaque;
1115 void qemu_free_timer(QEMUTimer *ts)
1120 /* stop a timer, but do not dealloc it */
1121 void qemu_del_timer(QEMUTimer *ts)
1125 /* NOTE: this code must be signal safe because
1126 qemu_timer_expired() can be called from a signal. */
1127 pt = &active_timers[ts->clock->type];
1140 /* modify the current timer so that it will be fired when current_time
1141 >= expire_time. The corresponding callback will be called. */
1142 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1148 /* add the timer in the sorted list */
1149 /* NOTE: this code must be signal safe because
1150 qemu_timer_expired() can be called from a signal. */
1151 pt = &active_timers[ts->clock->type];
1156 if (t->expire_time > expire_time)
1160 ts->expire_time = expire_time;
1164 /* Rearm if necessary */
1165 if (pt == &active_timers[ts->clock->type]) {
1166 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1167 qemu_rearm_alarm_timer(alarm_timer);
1169 /* Interrupt execution to force deadline recalculation. */
1170 if (use_icount && cpu_single_env) {
1171 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1176 int qemu_timer_pending(QEMUTimer *ts)
1179 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1186 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1190 return (timer_head->expire_time <= current_time);
1193 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1199 if (!ts || ts->expire_time > current_time)
1201 /* remove timer from the list before calling the callback */
1202 *ptimer_head = ts->next;
1205 /* run the callback (the timer list can be modified) */
1210 int64_t qemu_get_clock(QEMUClock *clock)
1212 switch(clock->type) {
1213 case QEMU_TIMER_REALTIME:
1214 return get_clock() / 1000000;
1216 case QEMU_TIMER_VIRTUAL:
1218 return cpu_get_icount();
1220 return cpu_get_clock();
1225 static void init_timers(void)
1228 ticks_per_sec = QEMU_TIMER_BASE;
1229 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1230 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1234 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1236 uint64_t expire_time;
1238 if (qemu_timer_pending(ts)) {
1239 expire_time = ts->expire_time;
1243 qemu_put_be64(f, expire_time);
1246 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1248 uint64_t expire_time;
1250 expire_time = qemu_get_be64(f);
1251 if (expire_time != -1) {
1252 qemu_mod_timer(ts, expire_time);
1258 static void timer_save(QEMUFile *f, void *opaque)
1260 if (cpu_ticks_enabled) {
1261 hw_error("cannot save state if virtual timers are running");
1263 qemu_put_be64(f, cpu_ticks_offset);
1264 qemu_put_be64(f, ticks_per_sec);
1265 qemu_put_be64(f, cpu_clock_offset);
1268 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1270 if (version_id != 1 && version_id != 2)
1272 if (cpu_ticks_enabled) {
1275 cpu_ticks_offset=qemu_get_be64(f);
1276 ticks_per_sec=qemu_get_be64(f);
1277 if (version_id == 2) {
1278 cpu_clock_offset=qemu_get_be64(f);
1284 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1285 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1287 static void host_alarm_handler(int host_signum)
1291 #define DISP_FREQ 1000
1293 static int64_t delta_min = INT64_MAX;
1294 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1296 ti = qemu_get_clock(vm_clock);
1297 if (last_clock != 0) {
1298 delta = ti - last_clock;
1299 if (delta < delta_min)
1301 if (delta > delta_max)
1304 if (++count == DISP_FREQ) {
1305 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1306 muldiv64(delta_min, 1000000, ticks_per_sec),
1307 muldiv64(delta_max, 1000000, ticks_per_sec),
1308 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1309 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1311 delta_min = INT64_MAX;
1319 if (alarm_has_dynticks(alarm_timer) ||
1321 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1322 qemu_get_clock(vm_clock))) ||
1323 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1324 qemu_get_clock(rt_clock))) {
1325 CPUState *env = next_cpu;
1328 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1329 SetEvent(data->host_alarm);
1331 static const char byte = 0;
1332 write(alarm_timer_wfd, &byte, sizeof(byte));
1334 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1337 /* stop the currently executing cpu because a timer occured */
1338 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1340 if (env->kqemu_enabled) {
1341 kqemu_cpu_interrupt(env);
1349 static int64_t qemu_next_deadline(void)
1353 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1354 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1355 qemu_get_clock(vm_clock);
1357 /* To avoid problems with overflow limit this to 2^32. */
1367 #if defined(__linux__) || defined(_WIN32)
1368 static uint64_t qemu_next_deadline_dyntick(void)
1376 delta = (qemu_next_deadline() + 999) / 1000;
1378 if (active_timers[QEMU_TIMER_REALTIME]) {
1379 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1380 qemu_get_clock(rt_clock))*1000;
1381 if (rtdelta < delta)
1385 if (delta < MIN_TIMER_REARM_US)
1386 delta = MIN_TIMER_REARM_US;
1394 /* Sets a specific flag */
1395 static int fcntl_setfl(int fd, int flag)
1399 flags = fcntl(fd, F_GETFL);
1403 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1409 #if defined(__linux__)
1411 #define RTC_FREQ 1024
1413 static void enable_sigio_timer(int fd)
1415 struct sigaction act;
1418 sigfillset(&act.sa_mask);
1420 act.sa_handler = host_alarm_handler;
1422 sigaction(SIGIO, &act, NULL);
1423 fcntl_setfl(fd, O_ASYNC);
1424 fcntl(fd, F_SETOWN, getpid());
1427 static int hpet_start_timer(struct qemu_alarm_timer *t)
1429 struct hpet_info info;
1432 fd = open("/dev/hpet", O_RDONLY);
1437 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1439 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1440 "error, but for better emulation accuracy type:\n"
1441 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1445 /* Check capabilities */
1446 r = ioctl(fd, HPET_INFO, &info);
1450 /* Enable periodic mode */
1451 r = ioctl(fd, HPET_EPI, 0);
1452 if (info.hi_flags && (r < 0))
1455 /* Enable interrupt */
1456 r = ioctl(fd, HPET_IE_ON, 0);
1460 enable_sigio_timer(fd);
1461 t->priv = (void *)(long)fd;
1469 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1471 int fd = (long)t->priv;
1476 static int rtc_start_timer(struct qemu_alarm_timer *t)
1479 unsigned long current_rtc_freq = 0;
1481 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1484 ioctl(rtc_fd, RTC_IRQP_READ, ¤t_rtc_freq);
1485 if (current_rtc_freq != RTC_FREQ &&
1486 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1487 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1488 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1489 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1492 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1498 enable_sigio_timer(rtc_fd);
1500 t->priv = (void *)(long)rtc_fd;
1505 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1507 int rtc_fd = (long)t->priv;
1512 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1516 struct sigaction act;
1518 sigfillset(&act.sa_mask);
1520 act.sa_handler = host_alarm_handler;
1522 sigaction(SIGALRM, &act, NULL);
1524 ev.sigev_value.sival_int = 0;
1525 ev.sigev_notify = SIGEV_SIGNAL;
1526 ev.sigev_signo = SIGALRM;
1528 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1529 perror("timer_create");
1531 /* disable dynticks */
1532 fprintf(stderr, "Dynamic Ticks disabled\n");
1537 t->priv = (void *)(long)host_timer;
1542 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1544 timer_t host_timer = (timer_t)(long)t->priv;
1546 timer_delete(host_timer);
1549 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1551 timer_t host_timer = (timer_t)(long)t->priv;
1552 struct itimerspec timeout;
1553 int64_t nearest_delta_us = INT64_MAX;
1556 if (!active_timers[QEMU_TIMER_REALTIME] &&
1557 !active_timers[QEMU_TIMER_VIRTUAL])
1560 nearest_delta_us = qemu_next_deadline_dyntick();
1562 /* check whether a timer is already running */
1563 if (timer_gettime(host_timer, &timeout)) {
1565 fprintf(stderr, "Internal timer error: aborting\n");
1568 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1569 if (current_us && current_us <= nearest_delta_us)
1572 timeout.it_interval.tv_sec = 0;
1573 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1574 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1575 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1576 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1578 fprintf(stderr, "Internal timer error: aborting\n");
1583 #endif /* defined(__linux__) */
1585 static int unix_start_timer(struct qemu_alarm_timer *t)
1587 struct sigaction act;
1588 struct itimerval itv;
1592 sigfillset(&act.sa_mask);
1594 act.sa_handler = host_alarm_handler;
1596 sigaction(SIGALRM, &act, NULL);
1598 itv.it_interval.tv_sec = 0;
1599 /* for i386 kernel 2.6 to get 1 ms */
1600 itv.it_interval.tv_usec = 999;
1601 itv.it_value.tv_sec = 0;
1602 itv.it_value.tv_usec = 10 * 1000;
1604 err = setitimer(ITIMER_REAL, &itv, NULL);
1611 static void unix_stop_timer(struct qemu_alarm_timer *t)
1613 struct itimerval itv;
1615 memset(&itv, 0, sizeof(itv));
1616 setitimer(ITIMER_REAL, &itv, NULL);
1619 #endif /* !defined(_WIN32) */
1621 static void try_to_rearm_timer(void *opaque)
1623 struct qemu_alarm_timer *t = opaque;
1627 /* Drain the notify pipe */
1630 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1631 } while ((len == -1 && errno == EINTR) || len > 0);
1634 if (t->flags & ALARM_FLAG_EXPIRED) {
1635 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1636 qemu_rearm_alarm_timer(alarm_timer);
1642 static int win32_start_timer(struct qemu_alarm_timer *t)
1645 struct qemu_alarm_win32 *data = t->priv;
1648 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1649 if (!data->host_alarm) {
1650 perror("Failed CreateEvent");
1654 memset(&tc, 0, sizeof(tc));
1655 timeGetDevCaps(&tc, sizeof(tc));
1657 if (data->period < tc.wPeriodMin)
1658 data->period = tc.wPeriodMin;
1660 timeBeginPeriod(data->period);
1662 flags = TIME_CALLBACK_FUNCTION;
1663 if (alarm_has_dynticks(t))
1664 flags |= TIME_ONESHOT;
1666 flags |= TIME_PERIODIC;
1668 data->timerId = timeSetEvent(1, // interval (ms)
1669 data->period, // resolution
1670 host_alarm_handler, // function
1671 (DWORD)t, // parameter
1674 if (!data->timerId) {
1675 perror("Failed to initialize win32 alarm timer");
1677 timeEndPeriod(data->period);
1678 CloseHandle(data->host_alarm);
1682 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1687 static void win32_stop_timer(struct qemu_alarm_timer *t)
1689 struct qemu_alarm_win32 *data = t->priv;
1691 timeKillEvent(data->timerId);
1692 timeEndPeriod(data->period);
1694 CloseHandle(data->host_alarm);
1697 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1699 struct qemu_alarm_win32 *data = t->priv;
1700 uint64_t nearest_delta_us;
1702 if (!active_timers[QEMU_TIMER_REALTIME] &&
1703 !active_timers[QEMU_TIMER_VIRTUAL])
1706 nearest_delta_us = qemu_next_deadline_dyntick();
1707 nearest_delta_us /= 1000;
1709 timeKillEvent(data->timerId);
1711 data->timerId = timeSetEvent(1,
1715 TIME_ONESHOT | TIME_PERIODIC);
1717 if (!data->timerId) {
1718 perror("Failed to re-arm win32 alarm timer");
1720 timeEndPeriod(data->period);
1721 CloseHandle(data->host_alarm);
1728 static int init_timer_alarm(void)
1730 struct qemu_alarm_timer *t = NULL;
1740 err = fcntl_setfl(fds[0], O_NONBLOCK);
1744 err = fcntl_setfl(fds[1], O_NONBLOCK);
1748 alarm_timer_rfd = fds[0];
1749 alarm_timer_wfd = fds[1];
1752 for (i = 0; alarm_timers[i].name; i++) {
1753 t = &alarm_timers[i];
1766 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1767 try_to_rearm_timer, NULL, t);
1782 static void quit_timers(void)
1784 alarm_timer->stop(alarm_timer);
1788 /***********************************************************/
1789 /* host time/date access */
1790 void qemu_get_timedate(struct tm *tm, int offset)
1797 if (rtc_date_offset == -1) {
1801 ret = localtime(&ti);
1803 ti -= rtc_date_offset;
1807 memcpy(tm, ret, sizeof(struct tm));
1810 int qemu_timedate_diff(struct tm *tm)
1814 if (rtc_date_offset == -1)
1816 seconds = mktimegm(tm);
1818 seconds = mktime(tm);
1820 seconds = mktimegm(tm) + rtc_date_offset;
1822 return seconds - time(NULL);
1826 static void socket_cleanup(void)
1831 static int socket_init(void)
1836 ret = WSAStartup(MAKEWORD(2,2), &Data);
1838 err = WSAGetLastError();
1839 fprintf(stderr, "WSAStartup: %d\n", err);
1842 atexit(socket_cleanup);
1847 const char *get_opt_name(char *buf, int buf_size, const char *p)
1852 while (*p != '\0' && *p != '=') {
1853 if (q && (q - buf) < buf_size - 1)
1863 const char *get_opt_value(char *buf, int buf_size, const char *p)
1868 while (*p != '\0') {
1870 if (*(p + 1) != ',')
1874 if (q && (q - buf) < buf_size - 1)
1884 int get_param_value(char *buf, int buf_size,
1885 const char *tag, const char *str)
1892 p = get_opt_name(option, sizeof(option), p);
1896 if (!strcmp(tag, option)) {
1897 (void)get_opt_value(buf, buf_size, p);
1900 p = get_opt_value(NULL, 0, p);
1909 int check_params(char *buf, int buf_size,
1910 const char * const *params, const char *str)
1917 p = get_opt_name(buf, buf_size, p);
1921 for(i = 0; params[i] != NULL; i++)
1922 if (!strcmp(params[i], buf))
1924 if (params[i] == NULL)
1926 p = get_opt_value(NULL, 0, p);
1934 /***********************************************************/
1935 /* Bluetooth support */
1938 static struct HCIInfo *hci_table[MAX_NICS];
1940 static struct bt_vlan_s {
1941 struct bt_scatternet_s net;
1943 struct bt_vlan_s *next;
1946 /* find or alloc a new bluetooth "VLAN" */
1947 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1949 struct bt_vlan_s **pvlan, *vlan;
1950 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1954 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1956 pvlan = &first_bt_vlan;
1957 while (*pvlan != NULL)
1958 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 static struct HCIInfo *hci_init(const char *str)
1990 struct bt_scatternet_s *vlan = 0;
1992 if (!strcmp(str, "null"))
1995 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1997 return bt_host_hci(str[4] ? str + 5 : "hci0");
1998 else if (!strncmp(str, "hci", 3)) {
2001 if (!strncmp(str + 3, ",vlan=", 6)) {
2002 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2007 vlan = qemu_find_bt_vlan(0);
2009 return bt_new_hci(vlan);
2012 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2017 static int bt_hci_parse(const char *str)
2019 struct HCIInfo *hci;
2022 if (nb_hcis >= MAX_NICS) {
2023 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2027 hci = hci_init(str);
2036 bdaddr.b[5] = 0x56 + nb_hcis;
2037 hci->bdaddr_set(hci, bdaddr.b);
2039 hci_table[nb_hcis++] = hci;
2044 static void bt_vhci_add(int vlan_id)
2046 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2049 fprintf(stderr, "qemu: warning: adding a VHCI to "
2050 "an empty scatternet %i\n", vlan_id);
2052 bt_vhci_init(bt_new_hci(vlan));
2055 static struct bt_device_s *bt_device_add(const char *opt)
2057 struct bt_scatternet_s *vlan;
2059 char *endp = strstr(opt, ",vlan=");
2060 int len = (endp ? endp - opt : strlen(opt)) + 1;
2063 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2066 vlan_id = strtol(endp + 6, &endp, 0);
2068 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2073 vlan = qemu_find_bt_vlan(vlan_id);
2076 fprintf(stderr, "qemu: warning: adding a slave device to "
2077 "an empty scatternet %i\n", vlan_id);
2079 if (!strcmp(devname, "keyboard"))
2080 return bt_keyboard_init(vlan);
2082 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2086 static int bt_parse(const char *opt)
2088 const char *endp, *p;
2091 if (strstart(opt, "hci", &endp)) {
2092 if (!*endp || *endp == ',') {
2094 if (!strstart(endp, ",vlan=", 0))
2097 return bt_hci_parse(opt);
2099 } else if (strstart(opt, "vhci", &endp)) {
2100 if (!*endp || *endp == ',') {
2102 if (strstart(endp, ",vlan=", &p)) {
2103 vlan = strtol(p, (char **) &endp, 0);
2105 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2109 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2118 } else if (strstart(opt, "device:", &endp))
2119 return !bt_device_add(endp);
2121 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2125 /***********************************************************/
2126 /* QEMU Block devices */
2128 #define HD_ALIAS "index=%d,media=disk"
2130 #define CDROM_ALIAS "index=1,media=cdrom"
2132 #define CDROM_ALIAS "index=2,media=cdrom"
2134 #define FD_ALIAS "index=%d,if=floppy"
2135 #define PFLASH_ALIAS "if=pflash"
2136 #define MTD_ALIAS "if=mtd"
2137 #define SD_ALIAS "index=0,if=sd"
2139 static int drive_opt_get_free_idx(void)
2143 for (index = 0; index < MAX_DRIVES; index++)
2144 if (!drives_opt[index].used) {
2145 drives_opt[index].used = 1;
2152 static int drive_get_free_idx(void)
2156 for (index = 0; index < MAX_DRIVES; index++)
2157 if (!drives_table[index].used) {
2158 drives_table[index].used = 1;
2165 static int drive_add(const char *file, const char *fmt, ...)
2168 int index = drive_opt_get_free_idx();
2170 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2171 fprintf(stderr, "qemu: too many drives\n");
2175 drives_opt[index].file = file;
2177 vsnprintf(drives_opt[index].opt,
2178 sizeof(drives_opt[0].opt), fmt, ap);
2185 void drive_remove(int index)
2187 drives_opt[index].used = 0;
2191 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2195 /* seek interface, bus and unit */
2197 for (index = 0; index < MAX_DRIVES; index++)
2198 if (drives_table[index].type == type &&
2199 drives_table[index].bus == bus &&
2200 drives_table[index].unit == unit &&
2201 drives_table[index].used)
2207 int drive_get_max_bus(BlockInterfaceType type)
2213 for (index = 0; index < nb_drives; index++) {
2214 if(drives_table[index].type == type &&
2215 drives_table[index].bus > max_bus)
2216 max_bus = drives_table[index].bus;
2221 const char *drive_get_serial(BlockDriverState *bdrv)
2225 for (index = 0; index < nb_drives; index++)
2226 if (drives_table[index].bdrv == bdrv)
2227 return drives_table[index].serial;
2232 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2236 for (index = 0; index < nb_drives; index++)
2237 if (drives_table[index].bdrv == bdrv)
2238 return drives_table[index].onerror;
2240 return BLOCK_ERR_REPORT;
2243 static void bdrv_format_print(void *opaque, const char *name)
2245 fprintf(stderr, " %s", name);
2248 void drive_uninit(BlockDriverState *bdrv)
2252 for (i = 0; i < MAX_DRIVES; i++)
2253 if (drives_table[i].bdrv == bdrv) {
2254 drives_table[i].bdrv = NULL;
2255 drives_table[i].used = 0;
2256 drive_remove(drives_table[i].drive_opt_idx);
2262 static int drive_init(struct drive_opt *arg, int snapshot,
2263 QEMUMachine *machine)
2269 const char *mediastr = "";
2270 BlockInterfaceType type;
2271 enum { MEDIA_DISK, MEDIA_CDROM } media;
2272 int bus_id, unit_id;
2273 int cyls, heads, secs, translation;
2274 BlockDriverState *bdrv;
2275 BlockDriver *drv = NULL;
2279 int bdrv_flags, onerror;
2280 int drives_table_idx;
2281 char *str = arg->opt;
2282 static const char * const params[] = { "bus", "unit", "if", "index",
2283 "cyls", "heads", "secs", "trans",
2284 "media", "snapshot", "file",
2285 "cache", "format", "serial", "werror",
2288 if (check_params(buf, sizeof(buf), params, str) < 0) {
2289 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2295 cyls = heads = secs = 0;
2298 translation = BIOS_ATA_TRANSLATION_AUTO;
2302 if (machine->use_scsi) {
2304 max_devs = MAX_SCSI_DEVS;
2305 pstrcpy(devname, sizeof(devname), "scsi");
2308 max_devs = MAX_IDE_DEVS;
2309 pstrcpy(devname, sizeof(devname), "ide");
2313 /* extract parameters */
2315 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2316 bus_id = strtol(buf, NULL, 0);
2318 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2323 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2324 unit_id = strtol(buf, NULL, 0);
2326 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2331 if (get_param_value(buf, sizeof(buf), "if", str)) {
2332 pstrcpy(devname, sizeof(devname), buf);
2333 if (!strcmp(buf, "ide")) {
2335 max_devs = MAX_IDE_DEVS;
2336 } else if (!strcmp(buf, "scsi")) {
2338 max_devs = MAX_SCSI_DEVS;
2339 } else if (!strcmp(buf, "floppy")) {
2342 } else if (!strcmp(buf, "pflash")) {
2345 } else if (!strcmp(buf, "mtd")) {
2348 } else if (!strcmp(buf, "sd")) {
2351 } else if (!strcmp(buf, "virtio")) {
2355 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2360 if (get_param_value(buf, sizeof(buf), "index", str)) {
2361 index = strtol(buf, NULL, 0);
2363 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2368 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2369 cyls = strtol(buf, NULL, 0);
2372 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2373 heads = strtol(buf, NULL, 0);
2376 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2377 secs = strtol(buf, NULL, 0);
2380 if (cyls || heads || secs) {
2381 if (cyls < 1 || cyls > 16383) {
2382 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2385 if (heads < 1 || heads > 16) {
2386 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2389 if (secs < 1 || secs > 63) {
2390 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2395 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2398 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2402 if (!strcmp(buf, "none"))
2403 translation = BIOS_ATA_TRANSLATION_NONE;
2404 else if (!strcmp(buf, "lba"))
2405 translation = BIOS_ATA_TRANSLATION_LBA;
2406 else if (!strcmp(buf, "auto"))
2407 translation = BIOS_ATA_TRANSLATION_AUTO;
2409 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2414 if (get_param_value(buf, sizeof(buf), "media", str)) {
2415 if (!strcmp(buf, "disk")) {
2417 } else if (!strcmp(buf, "cdrom")) {
2418 if (cyls || secs || heads) {
2420 "qemu: '%s' invalid physical CHS format\n", str);
2423 media = MEDIA_CDROM;
2425 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2430 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2431 if (!strcmp(buf, "on"))
2433 else if (!strcmp(buf, "off"))
2436 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2441 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2442 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2444 else if (!strcmp(buf, "writethrough"))
2446 else if (!strcmp(buf, "writeback"))
2449 fprintf(stderr, "qemu: invalid cache option\n");
2454 if (get_param_value(buf, sizeof(buf), "format", str)) {
2455 if (strcmp(buf, "?") == 0) {
2456 fprintf(stderr, "qemu: Supported formats:");
2457 bdrv_iterate_format(bdrv_format_print, NULL);
2458 fprintf(stderr, "\n");
2461 drv = bdrv_find_format(buf);
2463 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2468 if (arg->file == NULL)
2469 get_param_value(file, sizeof(file), "file", str);
2471 pstrcpy(file, sizeof(file), arg->file);
2473 if (!get_param_value(serial, sizeof(serial), "serial", str))
2474 memset(serial, 0, sizeof(serial));
2476 onerror = BLOCK_ERR_REPORT;
2477 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2478 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2479 fprintf(stderr, "werror is no supported by this format\n");
2482 if (!strcmp(buf, "ignore"))
2483 onerror = BLOCK_ERR_IGNORE;
2484 else if (!strcmp(buf, "enospc"))
2485 onerror = BLOCK_ERR_STOP_ENOSPC;
2486 else if (!strcmp(buf, "stop"))
2487 onerror = BLOCK_ERR_STOP_ANY;
2488 else if (!strcmp(buf, "report"))
2489 onerror = BLOCK_ERR_REPORT;
2491 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2496 /* compute bus and unit according index */
2499 if (bus_id != 0 || unit_id != -1) {
2501 "qemu: '%s' index cannot be used with bus and unit\n", str);
2509 unit_id = index % max_devs;
2510 bus_id = index / max_devs;
2514 /* if user doesn't specify a unit_id,
2515 * try to find the first free
2518 if (unit_id == -1) {
2520 while (drive_get_index(type, bus_id, unit_id) != -1) {
2522 if (max_devs && unit_id >= max_devs) {
2523 unit_id -= max_devs;
2531 if (max_devs && unit_id >= max_devs) {
2532 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2533 str, unit_id, max_devs - 1);
2538 * ignore multiple definitions
2541 if (drive_get_index(type, bus_id, unit_id) != -1)
2546 if (type == IF_IDE || type == IF_SCSI)
2547 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2549 snprintf(buf, sizeof(buf), "%s%i%s%i",
2550 devname, bus_id, mediastr, unit_id);
2552 snprintf(buf, sizeof(buf), "%s%s%i",
2553 devname, mediastr, unit_id);
2554 bdrv = bdrv_new(buf);
2555 drives_table_idx = drive_get_free_idx();
2556 drives_table[drives_table_idx].bdrv = bdrv;
2557 drives_table[drives_table_idx].type = type;
2558 drives_table[drives_table_idx].bus = bus_id;
2559 drives_table[drives_table_idx].unit = unit_id;
2560 drives_table[drives_table_idx].onerror = onerror;
2561 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2562 strncpy(drives_table[nb_drives].serial, serial, sizeof(serial));
2571 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2572 bdrv_set_translation_hint(bdrv, translation);
2576 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2581 /* FIXME: This isn't really a floppy, but it's a reasonable
2584 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2595 bdrv_flags |= BDRV_O_SNAPSHOT;
2596 cache = 2; /* always use write-back with snapshot */
2598 if (cache == 0) /* no caching */
2599 bdrv_flags |= BDRV_O_NOCACHE;
2600 else if (cache == 2) /* write-back */
2601 bdrv_flags |= BDRV_O_CACHE_WB;
2602 else if (cache == 3) /* not specified */
2603 bdrv_flags |= BDRV_O_CACHE_DEF;
2604 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2605 fprintf(stderr, "qemu: could not open disk image %s\n",
2612 /***********************************************************/
2615 static USBPort *used_usb_ports;
2616 static USBPort *free_usb_ports;
2618 /* ??? Maybe change this to register a hub to keep track of the topology. */
2619 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2620 usb_attachfn attach)
2622 port->opaque = opaque;
2623 port->index = index;
2624 port->attach = attach;
2625 port->next = free_usb_ports;
2626 free_usb_ports = port;
2629 int usb_device_add_dev(USBDevice *dev)
2633 /* Find a USB port to add the device to. */
2634 port = free_usb_ports;
2638 /* Create a new hub and chain it on. */
2639 free_usb_ports = NULL;
2640 port->next = used_usb_ports;
2641 used_usb_ports = port;
2643 hub = usb_hub_init(VM_USB_HUB_SIZE);
2644 usb_attach(port, hub);
2645 port = free_usb_ports;
2648 free_usb_ports = port->next;
2649 port->next = used_usb_ports;
2650 used_usb_ports = port;
2651 usb_attach(port, dev);
2655 static int usb_device_add(const char *devname)
2660 if (!free_usb_ports)
2663 if (strstart(devname, "host:", &p)) {
2664 dev = usb_host_device_open(p);
2665 } else if (!strcmp(devname, "mouse")) {
2666 dev = usb_mouse_init();
2667 } else if (!strcmp(devname, "tablet")) {
2668 dev = usb_tablet_init();
2669 } else if (!strcmp(devname, "keyboard")) {
2670 dev = usb_keyboard_init();
2671 } else if (strstart(devname, "disk:", &p)) {
2672 dev = usb_msd_init(p);
2673 } else if (!strcmp(devname, "wacom-tablet")) {
2674 dev = usb_wacom_init();
2675 } else if (strstart(devname, "serial:", &p)) {
2676 dev = usb_serial_init(p);
2677 #ifdef CONFIG_BRLAPI
2678 } else if (!strcmp(devname, "braille")) {
2679 dev = usb_baum_init();
2681 } else if (strstart(devname, "net:", &p)) {
2684 if (net_client_init("nic", p) < 0)
2686 nd_table[nic].model = "usb";
2687 dev = usb_net_init(&nd_table[nic]);
2688 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2689 dev = usb_bt_init(devname[2] ? hci_init(p) :
2690 bt_new_hci(qemu_find_bt_vlan(0)));
2697 return usb_device_add_dev(dev);
2700 int usb_device_del_addr(int bus_num, int addr)
2706 if (!used_usb_ports)
2712 lastp = &used_usb_ports;
2713 port = used_usb_ports;
2714 while (port && port->dev->addr != addr) {
2715 lastp = &port->next;
2723 *lastp = port->next;
2724 usb_attach(port, NULL);
2725 dev->handle_destroy(dev);
2726 port->next = free_usb_ports;
2727 free_usb_ports = port;
2731 static int usb_device_del(const char *devname)
2736 if (strstart(devname, "host:", &p))
2737 return usb_host_device_close(p);
2739 if (!used_usb_ports)
2742 p = strchr(devname, '.');
2745 bus_num = strtoul(devname, NULL, 0);
2746 addr = strtoul(p + 1, NULL, 0);
2748 return usb_device_del_addr(bus_num, addr);
2751 void do_usb_add(const char *devname)
2753 usb_device_add(devname);
2756 void do_usb_del(const char *devname)
2758 usb_device_del(devname);
2765 const char *speed_str;
2768 term_printf("USB support not enabled\n");
2772 for (port = used_usb_ports; port; port = port->next) {
2776 switch(dev->speed) {
2780 case USB_SPEED_FULL:
2783 case USB_SPEED_HIGH:
2790 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2791 0, dev->addr, speed_str, dev->devname);
2795 /***********************************************************/
2796 /* PCMCIA/Cardbus */
2798 static struct pcmcia_socket_entry_s {
2799 struct pcmcia_socket_s *socket;
2800 struct pcmcia_socket_entry_s *next;
2801 } *pcmcia_sockets = 0;
2803 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2805 struct pcmcia_socket_entry_s *entry;
2807 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2808 entry->socket = socket;
2809 entry->next = pcmcia_sockets;
2810 pcmcia_sockets = entry;
2813 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2815 struct pcmcia_socket_entry_s *entry, **ptr;
2817 ptr = &pcmcia_sockets;
2818 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2819 if (entry->socket == socket) {
2825 void pcmcia_info(void)
2827 struct pcmcia_socket_entry_s *iter;
2828 if (!pcmcia_sockets)
2829 term_printf("No PCMCIA sockets\n");
2831 for (iter = pcmcia_sockets; iter; iter = iter->next)
2832 term_printf("%s: %s\n", iter->socket->slot_string,
2833 iter->socket->attached ? iter->socket->card_string :
2837 /***********************************************************/
2838 /* register display */
2840 void register_displaystate(DisplayState *ds)
2850 DisplayState *get_displaystate(void)
2852 return display_state;
2857 static void dumb_display_init(void)
2859 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2860 ds->surface = qemu_create_displaysurface(640, 480, 32, 640 * 4);
2861 register_displaystate(ds);
2864 /***********************************************************/
2867 #define MAX_IO_HANDLERS 64
2869 typedef struct IOHandlerRecord {
2871 IOCanRWHandler *fd_read_poll;
2873 IOHandler *fd_write;
2876 /* temporary data */
2878 struct IOHandlerRecord *next;
2881 static IOHandlerRecord *first_io_handler;
2883 /* XXX: fd_read_poll should be suppressed, but an API change is
2884 necessary in the character devices to suppress fd_can_read(). */
2885 int qemu_set_fd_handler2(int fd,
2886 IOCanRWHandler *fd_read_poll,
2888 IOHandler *fd_write,
2891 IOHandlerRecord **pioh, *ioh;
2893 if (!fd_read && !fd_write) {
2894 pioh = &first_io_handler;
2899 if (ioh->fd == fd) {
2906 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2910 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2911 ioh->next = first_io_handler;
2912 first_io_handler = ioh;
2915 ioh->fd_read_poll = fd_read_poll;
2916 ioh->fd_read = fd_read;
2917 ioh->fd_write = fd_write;
2918 ioh->opaque = opaque;
2924 int qemu_set_fd_handler(int fd,
2926 IOHandler *fd_write,
2929 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2933 /***********************************************************/
2934 /* Polling handling */
2936 typedef struct PollingEntry {
2939 struct PollingEntry *next;
2942 static PollingEntry *first_polling_entry;
2944 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2946 PollingEntry **ppe, *pe;
2947 pe = qemu_mallocz(sizeof(PollingEntry));
2949 pe->opaque = opaque;
2950 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2955 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2957 PollingEntry **ppe, *pe;
2958 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2960 if (pe->func == func && pe->opaque == opaque) {
2968 /***********************************************************/
2969 /* Wait objects support */
2970 typedef struct WaitObjects {
2972 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2973 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2974 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2977 static WaitObjects wait_objects = {0};
2979 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2981 WaitObjects *w = &wait_objects;
2983 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2985 w->events[w->num] = handle;
2986 w->func[w->num] = func;
2987 w->opaque[w->num] = opaque;
2992 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2995 WaitObjects *w = &wait_objects;
2998 for (i = 0; i < w->num; i++) {
2999 if (w->events[i] == handle)
3002 w->events[i] = w->events[i + 1];
3003 w->func[i] = w->func[i + 1];
3004 w->opaque[i] = w->opaque[i + 1];
3012 /***********************************************************/
3013 /* ram save/restore */
3015 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3019 v = qemu_get_byte(f);
3022 if (qemu_get_buffer(f, buf, len) != len)
3026 v = qemu_get_byte(f);
3027 memset(buf, v, len);
3033 if (qemu_file_has_error(f))
3039 static int ram_load_v1(QEMUFile *f, void *opaque)
3044 if (qemu_get_be32(f) != phys_ram_size)
3046 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3047 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3054 #define BDRV_HASH_BLOCK_SIZE 1024
3055 #define IOBUF_SIZE 4096
3056 #define RAM_CBLOCK_MAGIC 0xfabe
3058 typedef struct RamDecompressState {
3061 uint8_t buf[IOBUF_SIZE];
3062 } RamDecompressState;
3064 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3067 memset(s, 0, sizeof(*s));
3069 ret = inflateInit(&s->zstream);
3075 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3079 s->zstream.avail_out = len;
3080 s->zstream.next_out = buf;
3081 while (s->zstream.avail_out > 0) {
3082 if (s->zstream.avail_in == 0) {
3083 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3085 clen = qemu_get_be16(s->f);
3086 if (clen > IOBUF_SIZE)
3088 qemu_get_buffer(s->f, s->buf, clen);
3089 s->zstream.avail_in = clen;
3090 s->zstream.next_in = s->buf;
3092 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3093 if (ret != Z_OK && ret != Z_STREAM_END) {
3100 static void ram_decompress_close(RamDecompressState *s)
3102 inflateEnd(&s->zstream);
3105 #define RAM_SAVE_FLAG_FULL 0x01
3106 #define RAM_SAVE_FLAG_COMPRESS 0x02
3107 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3108 #define RAM_SAVE_FLAG_PAGE 0x08
3109 #define RAM_SAVE_FLAG_EOS 0x10
3111 static int is_dup_page(uint8_t *page, uint8_t ch)
3113 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3114 uint32_t *array = (uint32_t *)page;
3117 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3118 if (array[i] != val)
3125 static int ram_save_block(QEMUFile *f)
3127 static ram_addr_t current_addr = 0;
3128 ram_addr_t saved_addr = current_addr;
3129 ram_addr_t addr = 0;
3132 while (addr < phys_ram_size) {
3133 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3136 cpu_physical_memory_reset_dirty(current_addr,
3137 current_addr + TARGET_PAGE_SIZE,
3138 MIGRATION_DIRTY_FLAG);
3140 ch = *(phys_ram_base + current_addr);
3142 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3143 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3144 qemu_put_byte(f, ch);
3146 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3147 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3153 addr += TARGET_PAGE_SIZE;
3154 current_addr = (saved_addr + addr) % phys_ram_size;
3160 static ram_addr_t ram_save_threshold = 10;
3162 static ram_addr_t ram_save_remaining(void)
3165 ram_addr_t count = 0;
3167 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3168 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3175 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3180 /* Make sure all dirty bits are set */
3181 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3182 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3183 cpu_physical_memory_set_dirty(addr);
3186 /* Enable dirty memory tracking */
3187 cpu_physical_memory_set_dirty_tracking(1);
3189 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3192 while (!qemu_file_rate_limit(f)) {
3195 ret = ram_save_block(f);
3196 if (ret == 0) /* no more blocks */
3200 /* try transferring iterative blocks of memory */
3203 cpu_physical_memory_set_dirty_tracking(0);
3205 /* flush all remaining blocks regardless of rate limiting */
3206 while (ram_save_block(f) != 0);
3209 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3211 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3214 static int ram_load_dead(QEMUFile *f, void *opaque)
3216 RamDecompressState s1, *s = &s1;
3220 if (ram_decompress_open(s, f) < 0)
3222 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3223 if (ram_decompress_buf(s, buf, 1) < 0) {
3224 fprintf(stderr, "Error while reading ram block header\n");
3228 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3229 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3234 printf("Error block header\n");
3238 ram_decompress_close(s);
3243 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3248 if (version_id == 1)
3249 return ram_load_v1(f, opaque);
3251 if (version_id == 2) {
3252 if (qemu_get_be32(f) != phys_ram_size)
3254 return ram_load_dead(f, opaque);
3257 if (version_id != 3)
3261 addr = qemu_get_be64(f);
3263 flags = addr & ~TARGET_PAGE_MASK;
3264 addr &= TARGET_PAGE_MASK;
3266 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3267 if (addr != phys_ram_size)
3271 if (flags & RAM_SAVE_FLAG_FULL) {
3272 if (ram_load_dead(f, opaque) < 0)
3276 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3277 uint8_t ch = qemu_get_byte(f);
3278 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3279 } else if (flags & RAM_SAVE_FLAG_PAGE)
3280 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3281 } while (!(flags & RAM_SAVE_FLAG_EOS));
3286 void qemu_service_io(void)
3288 CPUState *env = cpu_single_env;
3290 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3292 if (env->kqemu_enabled) {
3293 kqemu_cpu_interrupt(env);
3299 /***********************************************************/
3300 /* bottom halves (can be seen as timers which expire ASAP) */
3311 static QEMUBH *first_bh = NULL;
3313 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3316 bh = qemu_mallocz(sizeof(QEMUBH));
3318 bh->opaque = opaque;
3319 bh->next = first_bh;
3324 int qemu_bh_poll(void)
3330 for (bh = first_bh; bh; bh = bh->next) {
3331 if (!bh->deleted && bh->scheduled) {
3340 /* remove deleted bhs */
3354 void qemu_bh_schedule_idle(QEMUBH *bh)
3362 void qemu_bh_schedule(QEMUBH *bh)
3364 CPUState *env = cpu_single_env;
3369 /* stop the currently executing CPU to execute the BH ASAP */
3371 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3375 void qemu_bh_cancel(QEMUBH *bh)
3380 void qemu_bh_delete(QEMUBH *bh)
3386 static void qemu_bh_update_timeout(int *timeout)
3390 for (bh = first_bh; bh; bh = bh->next) {
3391 if (!bh->deleted && bh->scheduled) {
3393 /* idle bottom halves will be polled at least
3395 *timeout = MIN(10, *timeout);
3397 /* non-idle bottom halves will be executed
3406 /***********************************************************/
3407 /* machine registration */
3409 static QEMUMachine *first_machine = NULL;
3411 int qemu_register_machine(QEMUMachine *m)
3414 pm = &first_machine;
3422 static QEMUMachine *find_machine(const char *name)
3426 for(m = first_machine; m != NULL; m = m->next) {
3427 if (!strcmp(m->name, name))
3433 /***********************************************************/
3434 /* main execution loop */
3436 static void gui_update(void *opaque)
3438 uint64_t interval = GUI_REFRESH_INTERVAL;
3439 DisplayState *ds = opaque;
3440 DisplayChangeListener *dcl = ds->listeners;
3444 while (dcl != NULL) {
3445 if (dcl->gui_timer_interval &&
3446 dcl->gui_timer_interval < interval)
3447 interval = dcl->gui_timer_interval;
3450 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3453 static void nographic_update(void *opaque)
3455 uint64_t interval = GUI_REFRESH_INTERVAL;
3457 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3460 struct vm_change_state_entry {
3461 VMChangeStateHandler *cb;
3463 LIST_ENTRY (vm_change_state_entry) entries;
3466 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3468 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3471 VMChangeStateEntry *e;
3473 e = qemu_mallocz(sizeof (*e));
3477 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3481 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3483 LIST_REMOVE (e, entries);
3487 static void vm_state_notify(int running, int reason)
3489 VMChangeStateEntry *e;
3491 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3492 e->cb(e->opaque, running, reason);
3501 vm_state_notify(1, 0);
3502 qemu_rearm_alarm_timer(alarm_timer);
3506 void vm_stop(int reason)
3509 cpu_disable_ticks();
3511 vm_state_notify(0, reason);
3515 /* reset/shutdown handler */
3517 typedef struct QEMUResetEntry {
3518 QEMUResetHandler *func;
3520 struct QEMUResetEntry *next;
3523 static QEMUResetEntry *first_reset_entry;
3524 static int reset_requested;
3525 static int shutdown_requested;
3526 static int powerdown_requested;
3528 int qemu_shutdown_requested(void)
3530 int r = shutdown_requested;
3531 shutdown_requested = 0;
3535 int qemu_reset_requested(void)
3537 int r = reset_requested;
3538 reset_requested = 0;
3542 int qemu_powerdown_requested(void)
3544 int r = powerdown_requested;
3545 powerdown_requested = 0;
3549 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3551 QEMUResetEntry **pre, *re;
3553 pre = &first_reset_entry;
3554 while (*pre != NULL)
3555 pre = &(*pre)->next;
3556 re = qemu_mallocz(sizeof(QEMUResetEntry));
3558 re->opaque = opaque;
3563 void qemu_system_reset(void)
3567 /* reset all devices */
3568 for(re = first_reset_entry; re != NULL; re = re->next) {
3569 re->func(re->opaque);
3573 void qemu_system_reset_request(void)
3576 shutdown_requested = 1;
3578 reset_requested = 1;
3581 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3584 void qemu_system_shutdown_request(void)
3586 shutdown_requested = 1;
3588 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3591 void qemu_system_powerdown_request(void)
3593 powerdown_requested = 1;
3595 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3599 static void host_main_loop_wait(int *timeout)
3605 /* XXX: need to suppress polling by better using win32 events */
3607 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3608 ret |= pe->func(pe->opaque);
3612 WaitObjects *w = &wait_objects;
3614 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3615 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3616 if (w->func[ret - WAIT_OBJECT_0])
3617 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3619 /* Check for additional signaled events */
3620 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3622 /* Check if event is signaled */
3623 ret2 = WaitForSingleObject(w->events[i], 0);
3624 if(ret2 == WAIT_OBJECT_0) {
3626 w->func[i](w->opaque[i]);
3627 } else if (ret2 == WAIT_TIMEOUT) {
3629 err = GetLastError();
3630 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3633 } else if (ret == WAIT_TIMEOUT) {
3635 err = GetLastError();
3636 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3643 static void host_main_loop_wait(int *timeout)
3648 void main_loop_wait(int timeout)
3650 IOHandlerRecord *ioh;
3651 fd_set rfds, wfds, xfds;
3655 qemu_bh_update_timeout(&timeout);
3657 host_main_loop_wait(&timeout);
3659 /* poll any events */
3660 /* XXX: separate device handlers from system ones */
3665 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3669 (!ioh->fd_read_poll ||
3670 ioh->fd_read_poll(ioh->opaque) != 0)) {
3671 FD_SET(ioh->fd, &rfds);
3675 if (ioh->fd_write) {
3676 FD_SET(ioh->fd, &wfds);
3682 tv.tv_sec = timeout / 1000;
3683 tv.tv_usec = (timeout % 1000) * 1000;
3685 #if defined(CONFIG_SLIRP)
3686 if (slirp_is_inited()) {
3687 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3690 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3692 IOHandlerRecord **pioh;
3694 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3695 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3696 ioh->fd_read(ioh->opaque);
3698 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3699 ioh->fd_write(ioh->opaque);
3703 /* remove deleted IO handlers */
3704 pioh = &first_io_handler;
3714 #if defined(CONFIG_SLIRP)
3715 if (slirp_is_inited()) {
3721 slirp_select_poll(&rfds, &wfds, &xfds);
3725 /* vm time timers */
3726 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3727 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3728 qemu_get_clock(vm_clock));
3730 /* real time timers */
3731 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3732 qemu_get_clock(rt_clock));
3734 /* Check bottom-halves last in case any of the earlier events triggered
3740 static int main_loop(void)
3743 #ifdef CONFIG_PROFILER
3748 cur_cpu = first_cpu;
3749 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3756 #ifdef CONFIG_PROFILER
3757 ti = profile_getclock();
3762 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3763 env->icount_decr.u16.low = 0;
3764 env->icount_extra = 0;
3765 count = qemu_next_deadline();
3766 count = (count + (1 << icount_time_shift) - 1)
3767 >> icount_time_shift;
3768 qemu_icount += count;
3769 decr = (count > 0xffff) ? 0xffff : count;
3771 env->icount_decr.u16.low = decr;
3772 env->icount_extra = count;
3774 ret = cpu_exec(env);
3775 #ifdef CONFIG_PROFILER
3776 qemu_time += profile_getclock() - ti;
3779 /* Fold pending instructions back into the
3780 instruction counter, and clear the interrupt flag. */
3781 qemu_icount -= (env->icount_decr.u16.low
3782 + env->icount_extra);
3783 env->icount_decr.u32 = 0;
3784 env->icount_extra = 0;
3786 next_cpu = env->next_cpu ?: first_cpu;
3787 if (event_pending && likely(ret != EXCP_DEBUG)) {
3788 ret = EXCP_INTERRUPT;
3792 if (ret == EXCP_HLT) {
3793 /* Give the next CPU a chance to run. */
3797 if (ret != EXCP_HALTED)
3799 /* all CPUs are halted ? */
3805 if (shutdown_requested) {
3806 ret = EXCP_INTERRUPT;
3814 if (reset_requested) {
3815 reset_requested = 0;
3816 qemu_system_reset();
3817 ret = EXCP_INTERRUPT;
3819 if (powerdown_requested) {
3820 powerdown_requested = 0;
3821 qemu_system_powerdown();
3822 ret = EXCP_INTERRUPT;
3824 if (unlikely(ret == EXCP_DEBUG)) {
3825 gdb_set_stop_cpu(cur_cpu);
3826 vm_stop(EXCP_DEBUG);
3828 /* If all cpus are halted then wait until the next IRQ */
3829 /* XXX: use timeout computed from timers */
3830 if (ret == EXCP_HALTED) {
3834 /* Advance virtual time to the next event. */
3835 if (use_icount == 1) {
3836 /* When not using an adaptive execution frequency
3837 we tend to get badly out of sync with real time,
3838 so just delay for a reasonable amount of time. */
3841 delta = cpu_get_icount() - cpu_get_clock();
3844 /* If virtual time is ahead of real time then just
3846 timeout = (delta / 1000000) + 1;
3848 /* Wait for either IO to occur or the next
3850 add = qemu_next_deadline();
3851 /* We advance the timer before checking for IO.
3852 Limit the amount we advance so that early IO
3853 activity won't get the guest too far ahead. */
3857 add = (add + (1 << icount_time_shift) - 1)
3858 >> icount_time_shift;
3860 timeout = delta / 1000000;
3871 if (shutdown_requested) {
3872 ret = EXCP_INTERRUPT;
3877 #ifdef CONFIG_PROFILER
3878 ti = profile_getclock();
3880 main_loop_wait(timeout);
3881 #ifdef CONFIG_PROFILER
3882 dev_time += profile_getclock() - ti;
3885 cpu_disable_ticks();
3889 static void help(int exitcode)
3891 /* Please keep in synch with QEMU_OPTION_ enums, qemu_options[]
3892 and qemu-doc.texi */
3893 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3894 "usage: %s [options] [disk_image]\n"
3896 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3898 "Standard options:\n"
3899 "-h or -help display this help and exit\n"
3900 "-M machine select emulated machine (-M ? for list)\n"
3901 "-cpu cpu select CPU (-cpu ? for list)\n"
3902 "-smp n set the number of CPUs to 'n' [default=1]\n"
3903 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3904 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3905 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3906 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3907 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3908 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3909 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
3910 " use 'file' as a drive image\n"
3911 "-mtdblock file use 'file' as on-board Flash memory image\n"
3912 "-sd file use 'file' as SecureDigital card image\n"
3913 "-pflash file use 'file' as a parallel flash image\n"
3914 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3915 "-snapshot write to temporary files instead of disk image files\n"
3916 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3918 "-k language use keyboard layout (for example \"fr\" for French)\n"
3921 "-audio-help print list of audio drivers and their options\n"
3922 "-soundhw c1,... enable audio support\n"
3923 " and only specified sound cards (comma separated list)\n"
3924 " use -soundhw ? to get the list of supported cards\n"
3925 " use -soundhw all to enable all of them\n"
3927 "-usb enable the USB driver (will be the default soon)\n"
3928 "-usbdevice name add the host or guest USB device 'name'\n"
3929 "-name string set the name of the guest\n"
3930 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x\n"
3931 " specify machine UUID\n"
3933 "Display options:\n"
3934 "-nographic disable graphical output and redirect serial I/Os to console\n"
3935 #ifdef CONFIG_CURSES
3936 "-curses use a curses/ncurses interface instead of SDL\n"
3939 "-no-frame open SDL window without a frame and window decorations\n"
3940 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3941 "-no-quit disable SDL window close capability\n"
3944 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3945 "-vga [std|cirrus|vmware|none]\n"
3946 " select video card type\n"
3947 "-full-screen start in full screen\n"
3948 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3949 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3951 "-vnc display start a VNC server on display\n"
3953 "Network options:\n"
3954 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
3955 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3957 "-net user[,vlan=n][,name=str][,hostname=host]\n"
3958 " connect the user mode network stack to VLAN 'n' and send\n"
3959 " hostname 'host' to DHCP clients\n"
3962 "-net tap[,vlan=n][,name=str],ifname=name\n"
3963 " connect the host TAP network interface to VLAN 'n'\n"
3965 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
3966 " connect the host TAP network interface to VLAN 'n' and use the\n"
3967 " network scripts 'file' (default=%s)\n"
3968 " and 'dfile' (default=%s);\n"
3969 " use '[down]script=no' to disable script execution;\n"
3970 " use 'fd=h' to connect to an already opened TAP interface\n"
3972 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
3973 " connect the vlan 'n' to another VLAN using a socket connection\n"
3974 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
3975 " connect the vlan 'n' to multicast maddr and port\n"
3977 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
3978 " connect the vlan 'n' to port 'n' of a vde switch running\n"
3979 " on host and listening for incoming connections on 'socketpath'.\n"
3980 " Use group 'groupname' and mode 'octalmode' to change default\n"
3981 " ownership and permissions for communication port.\n"
3983 "-net none use it alone to have zero network devices; if no -net option\n"
3984 " is provided, the default is '-net nic -net user'\n"
3986 "-tftp dir allow tftp access to files in dir [-net user]\n"
3987 "-bootp file advertise file in BOOTP replies\n"
3989 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
3991 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
3992 " redirect TCP or UDP connections from host to guest [-net user]\n"
3995 "-bt hci,null dumb bluetooth HCI - doesn't respond to commands\n"
3996 "-bt hci,host[:id]\n"
3997 " use host's HCI with the given name\n"
3998 "-bt hci[,vlan=n]\n"
3999 " emulate a standard HCI in virtual scatternet 'n'\n"
4000 "-bt vhci[,vlan=n]\n"
4001 " add host computer to virtual scatternet 'n' using VHCI\n"
4002 "-bt device:dev[,vlan=n]\n"
4003 " emulate a bluetooth device 'dev' in scatternet 'n'\n"
4007 "i386 target only:\n"
4008 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4009 "-rtc-td-hack use it to fix time drift in Windows ACPI HAL\n"
4010 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4011 "-no-acpi disable ACPI\n"
4012 "-no-hpet disable HPET\n"
4014 "Linux boot specific:\n"
4015 "-kernel bzImage use 'bzImage' as kernel image\n"
4016 "-append cmdline use 'cmdline' as kernel command line\n"
4017 "-initrd file use 'file' as initial ram disk\n"
4019 "Debug/Expert options:\n"
4020 "-serial dev redirect the serial port to char device 'dev'\n"
4021 "-parallel dev redirect the parallel port to char device 'dev'\n"
4022 "-monitor dev redirect the monitor to char device 'dev'\n"
4023 "-pidfile file write PID to 'file'\n"
4024 "-S freeze CPU at startup (use 'c' to start execution)\n"
4025 "-s wait gdb connection to port\n"
4026 "-p port set gdb connection port [default=%s]\n"
4027 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4028 "-hdachs c,h,s[,t]\n"
4029 " force hard disk 0 physical geometry and the optional BIOS\n"
4030 " translation (t=none or lba) (usually qemu can guess them)\n"
4031 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4032 "-bios file set the filename for the BIOS\n"
4034 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4035 "-no-kqemu disable KQEMU kernel module usage\n"
4038 "-enable-kvm enable KVM full virtualization support\n"
4040 "-no-reboot exit instead of rebooting\n"
4041 "-no-shutdown stop before shutdown\n"
4042 "-loadvm [tag|id]\n"
4043 " start right away with a saved state (loadvm in monitor)\n"
4045 "-daemonize daemonize QEMU after initializing\n"
4047 "-option-rom rom load a file, rom, into the option ROM space\n"
4048 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4049 "-prom-env variable=value\n"
4050 " set OpenBIOS nvram variables\n"
4052 "-clock force the use of the given methods for timer alarm.\n"
4053 " To see what timers are available use -clock ?\n"
4054 "-localtime set the real time clock to local time [default=utc]\n"
4055 "-startdate select initial date of the clock\n"
4056 "-icount [N|auto]\n"
4057 " enable virtual instruction counter with 2^N clock ticks per instruction\n"
4058 "-echr chr set terminal escape character instead of ctrl-a\n"
4059 "-virtioconsole c\n"
4060 " set virtio console\n"
4061 "-show-cursor show cursor\n"
4062 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4063 "-semihosting semihosting mode\n"
4065 #if defined(TARGET_ARM)
4066 "-old-param old param mode\n"
4068 "-tb-size n set TB size\n"
4069 "-incoming p prepare for incoming migration, listen on port p\n"
4071 "During emulation, the following keys are useful:\n"
4072 "ctrl-alt-f toggle full screen\n"
4073 "ctrl-alt-n switch to virtual console 'n'\n"
4074 "ctrl-alt toggle mouse and keyboard grab\n"
4076 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4081 DEFAULT_NETWORK_SCRIPT,
4082 DEFAULT_NETWORK_DOWN_SCRIPT,
4084 DEFAULT_GDBSTUB_PORT,
4089 #define HAS_ARG 0x0001
4092 /* Please keep in synch with help, qemu_options[] and
4094 /* Standard options: */
4107 QEMU_OPTION_mtdblock,
4111 QEMU_OPTION_snapshot,
4114 QEMU_OPTION_audio_help,
4115 QEMU_OPTION_soundhw,
4117 QEMU_OPTION_usbdevice,
4121 /* Display options: */
4122 QEMU_OPTION_nographic,
4124 QEMU_OPTION_no_frame,
4125 QEMU_OPTION_alt_grab,
4126 QEMU_OPTION_no_quit,
4128 QEMU_OPTION_portrait,
4130 QEMU_OPTION_full_screen,
4134 /* Network options: */
4142 /* i386 target only: */
4143 QEMU_OPTION_win2k_hack,
4144 QEMU_OPTION_rtc_td_hack,
4145 QEMU_OPTION_no_fd_bootchk,
4146 QEMU_OPTION_no_acpi,
4147 QEMU_OPTION_no_hpet,
4149 /* Linux boot specific: */
4154 /* Debug/Expert options: */
4156 QEMU_OPTION_parallel,
4157 QEMU_OPTION_monitor,
4158 QEMU_OPTION_pidfile,
4166 QEMU_OPTION_kernel_kqemu,
4167 QEMU_OPTION_no_kqemu,
4168 QEMU_OPTION_enable_kvm,
4169 QEMU_OPTION_no_reboot,
4170 QEMU_OPTION_no_shutdown,
4172 QEMU_OPTION_daemonize,
4173 QEMU_OPTION_option_rom,
4174 QEMU_OPTION_prom_env,
4176 QEMU_OPTION_localtime,
4177 QEMU_OPTION_startdate,
4180 QEMU_OPTION_virtiocon,
4181 QEMU_OPTION_show_cursor,
4182 QEMU_OPTION_semihosting,
4183 QEMU_OPTION_old_param,
4184 QEMU_OPTION_tb_size,
4185 QEMU_OPTION_incoming,
4188 typedef struct QEMUOption {
4194 static const QEMUOption qemu_options[] = {
4195 /* Please keep in synch with help, QEMU_OPTION_ enums, and
4197 /* Standard options: */
4198 { "h", 0, QEMU_OPTION_h },
4199 { "help", 0, QEMU_OPTION_h },
4200 { "M", HAS_ARG, QEMU_OPTION_M },
4201 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4202 { "smp", HAS_ARG, QEMU_OPTION_smp },
4203 { "fda", HAS_ARG, QEMU_OPTION_fda },
4204 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4205 { "hda", HAS_ARG, QEMU_OPTION_hda },
4206 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4207 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4208 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4209 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4210 { "drive", HAS_ARG, QEMU_OPTION_drive },
4211 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4212 { "sd", HAS_ARG, QEMU_OPTION_sd },
4213 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4214 { "boot", HAS_ARG, QEMU_OPTION_boot },
4215 { "snapshot", 0, QEMU_OPTION_snapshot },
4216 { "m", HAS_ARG, QEMU_OPTION_m },
4218 { "k", HAS_ARG, QEMU_OPTION_k },
4221 { "audio-help", 0, QEMU_OPTION_audio_help },
4222 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4224 { "usb", 0, QEMU_OPTION_usb },
4225 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4226 { "name", HAS_ARG, QEMU_OPTION_name },
4227 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4229 /* Display options: */
4230 { "nographic", 0, QEMU_OPTION_nographic },
4231 #ifdef CONFIG_CURSES
4232 { "curses", 0, QEMU_OPTION_curses },
4235 { "no-frame", 0, QEMU_OPTION_no_frame },
4236 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4237 { "no-quit", 0, QEMU_OPTION_no_quit },
4238 { "sdl", 0, QEMU_OPTION_sdl },
4240 { "portrait", 0, QEMU_OPTION_portrait },
4241 { "vga", HAS_ARG, QEMU_OPTION_vga },
4242 { "full-screen", 0, QEMU_OPTION_full_screen },
4243 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4244 { "g", 1, QEMU_OPTION_g },
4246 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4248 /* Network options: */
4249 { "net", HAS_ARG, QEMU_OPTION_net},
4251 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4252 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4254 { "smb", HAS_ARG, QEMU_OPTION_smb },
4256 { "redir", HAS_ARG, QEMU_OPTION_redir },
4258 { "bt", HAS_ARG, QEMU_OPTION_bt },
4260 /* i386 target only: */
4261 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4262 { "rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack },
4263 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4264 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4265 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4268 /* Linux boot specific: */
4269 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4270 { "append", HAS_ARG, QEMU_OPTION_append },
4271 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4273 /* Debug/Expert options: */
4274 { "serial", HAS_ARG, QEMU_OPTION_serial },
4275 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4276 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4277 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4278 { "S", 0, QEMU_OPTION_S },
4279 { "s", 0, QEMU_OPTION_s },
4280 { "p", HAS_ARG, QEMU_OPTION_p },
4281 { "d", HAS_ARG, QEMU_OPTION_d },
4282 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4283 { "L", HAS_ARG, QEMU_OPTION_L },
4284 { "bios", HAS_ARG, QEMU_OPTION_bios },
4286 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4287 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4290 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4292 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4293 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4294 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4295 { "daemonize", 0, QEMU_OPTION_daemonize },
4296 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4297 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4298 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4300 { "clock", HAS_ARG, QEMU_OPTION_clock },
4301 { "localtime", 0, QEMU_OPTION_localtime },
4302 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4303 { "icount", HAS_ARG, QEMU_OPTION_icount },
4304 { "echr", HAS_ARG, QEMU_OPTION_echr },
4305 { "virtioconsole", HAS_ARG, QEMU_OPTION_virtiocon },
4306 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4307 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4308 { "semihosting", 0, QEMU_OPTION_semihosting },
4310 #if defined(TARGET_ARM)
4311 { "old-param", 0, QEMU_OPTION_old_param },
4313 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4314 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4318 /* password input */
4320 int qemu_key_check(BlockDriverState *bs, const char *name)
4325 if (!bdrv_is_encrypted(bs))
4328 term_printf("%s is encrypted.\n", name);
4329 for(i = 0; i < 3; i++) {
4330 monitor_readline("Password: ", 1, password, sizeof(password));
4331 if (bdrv_set_key(bs, password) == 0)
4333 term_printf("invalid password\n");
4338 static BlockDriverState *get_bdrv(int index)
4340 if (index > nb_drives)
4342 return drives_table[index].bdrv;
4345 static void read_passwords(void)
4347 BlockDriverState *bs;
4350 for(i = 0; i < 6; i++) {
4353 qemu_key_check(bs, bdrv_get_device_name(bs));
4358 struct soundhw soundhw[] = {
4359 #ifdef HAS_AUDIO_CHOICE
4360 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4366 { .init_isa = pcspk_audio_init }
4373 "Creative Sound Blaster 16",
4376 { .init_isa = SB16_init }
4380 #ifdef CONFIG_CS4231A
4386 { .init_isa = cs4231a_init }
4394 "Yamaha YMF262 (OPL3)",
4396 "Yamaha YM3812 (OPL2)",
4400 { .init_isa = Adlib_init }
4407 "Gravis Ultrasound GF1",
4410 { .init_isa = GUS_init }
4417 "Intel 82801AA AC97 Audio",
4420 { .init_pci = ac97_init }
4424 #ifdef CONFIG_ES1370
4427 "ENSONIQ AudioPCI ES1370",
4430 { .init_pci = es1370_init }
4434 #endif /* HAS_AUDIO_CHOICE */
4436 { NULL, NULL, 0, 0, { NULL } }
4439 static void select_soundhw (const char *optarg)
4443 if (*optarg == '?') {
4446 printf ("Valid sound card names (comma separated):\n");
4447 for (c = soundhw; c->name; ++c) {
4448 printf ("%-11s %s\n", c->name, c->descr);
4450 printf ("\n-soundhw all will enable all of the above\n");
4451 exit (*optarg != '?');
4459 if (!strcmp (optarg, "all")) {
4460 for (c = soundhw; c->name; ++c) {
4468 e = strchr (p, ',');
4469 l = !e ? strlen (p) : (size_t) (e - p);
4471 for (c = soundhw; c->name; ++c) {
4472 if (!strncmp (c->name, p, l)) {
4481 "Unknown sound card name (too big to show)\n");
4484 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4489 p += l + (e != NULL);
4493 goto show_valid_cards;
4498 static void select_vgahw (const char *p)
4502 if (strstart(p, "std", &opts)) {
4503 std_vga_enabled = 1;
4504 cirrus_vga_enabled = 0;
4506 } else if (strstart(p, "cirrus", &opts)) {
4507 cirrus_vga_enabled = 1;
4508 std_vga_enabled = 0;
4510 } else if (strstart(p, "vmware", &opts)) {
4511 cirrus_vga_enabled = 0;
4512 std_vga_enabled = 0;
4514 } else if (strstart(p, "none", &opts)) {
4515 cirrus_vga_enabled = 0;
4516 std_vga_enabled = 0;
4520 fprintf(stderr, "Unknown vga type: %s\n", p);
4524 const char *nextopt;
4526 if (strstart(opts, ",retrace=", &nextopt)) {
4528 if (strstart(opts, "dumb", &nextopt))
4529 vga_retrace_method = VGA_RETRACE_DUMB;
4530 else if (strstart(opts, "precise", &nextopt))
4531 vga_retrace_method = VGA_RETRACE_PRECISE;
4532 else goto invalid_vga;
4533 } else goto invalid_vga;
4539 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4541 exit(STATUS_CONTROL_C_EXIT);
4546 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4550 if(strlen(str) != 36)
4553 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4554 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4555 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4563 #define MAX_NET_CLIENTS 32
4567 static void termsig_handler(int signal)
4569 qemu_system_shutdown_request();
4572 static void termsig_setup(void)
4574 struct sigaction act;
4576 memset(&act, 0, sizeof(act));
4577 act.sa_handler = termsig_handler;
4578 sigaction(SIGINT, &act, NULL);
4579 sigaction(SIGHUP, &act, NULL);
4580 sigaction(SIGTERM, &act, NULL);
4585 int main(int argc, char **argv, char **envp)
4587 #ifdef CONFIG_GDBSTUB
4589 const char *gdbstub_port;
4591 uint32_t boot_devices_bitmap = 0;
4593 int snapshot, linux_boot, net_boot;
4594 const char *initrd_filename;
4595 const char *kernel_filename, *kernel_cmdline;
4596 const char *boot_devices = "";
4598 DisplayChangeListener *dcl;
4599 int cyls, heads, secs, translation;
4600 const char *net_clients[MAX_NET_CLIENTS];
4602 const char *bt_opts[MAX_BT_CMDLINE];
4606 const char *r, *optarg;
4607 CharDriverState *monitor_hd = NULL;
4608 const char *monitor_device;
4609 const char *serial_devices[MAX_SERIAL_PORTS];
4610 int serial_device_index;
4611 const char *parallel_devices[MAX_PARALLEL_PORTS];
4612 int parallel_device_index;
4613 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4614 int virtio_console_index;
4615 const char *loadvm = NULL;
4616 QEMUMachine *machine;
4617 const char *cpu_model;
4618 const char *usb_devices[MAX_USB_CMDLINE];
4619 int usb_devices_index;
4622 const char *pid_file = NULL;
4624 const char *incoming = NULL;
4626 qemu_cache_utils_init(envp);
4628 LIST_INIT (&vm_change_state_head);
4631 struct sigaction act;
4632 sigfillset(&act.sa_mask);
4634 act.sa_handler = SIG_IGN;
4635 sigaction(SIGPIPE, &act, NULL);
4638 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4639 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4640 QEMU to run on a single CPU */
4645 h = GetCurrentProcess();
4646 if (GetProcessAffinityMask(h, &mask, &smask)) {
4647 for(i = 0; i < 32; i++) {
4648 if (mask & (1 << i))
4653 SetProcessAffinityMask(h, mask);
4659 register_machines();
4660 machine = first_machine;
4662 initrd_filename = NULL;
4664 vga_ram_size = VGA_RAM_SIZE;
4665 #ifdef CONFIG_GDBSTUB
4667 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4672 kernel_filename = NULL;
4673 kernel_cmdline = "";
4674 cyls = heads = secs = 0;
4675 translation = BIOS_ATA_TRANSLATION_AUTO;
4676 monitor_device = "vc";
4678 serial_devices[0] = "vc:80Cx24C";
4679 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4680 serial_devices[i] = NULL;
4681 serial_device_index = 0;
4683 parallel_devices[0] = "vc:640x480";
4684 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4685 parallel_devices[i] = NULL;
4686 parallel_device_index = 0;
4688 virtio_consoles[0] = "vc:80Cx24C";
4689 for(i = 1; i < MAX_VIRTIO_CONSOLES; i++)
4690 virtio_consoles[i] = NULL;
4691 virtio_console_index = 0;
4693 usb_devices_index = 0;
4712 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4714 const QEMUOption *popt;
4717 /* Treat --foo the same as -foo. */
4720 popt = qemu_options;
4723 fprintf(stderr, "%s: invalid option -- '%s'\n",
4727 if (!strcmp(popt->name, r + 1))
4731 if (popt->flags & HAS_ARG) {
4732 if (optind >= argc) {
4733 fprintf(stderr, "%s: option '%s' requires an argument\n",
4737 optarg = argv[optind++];
4742 switch(popt->index) {
4744 machine = find_machine(optarg);
4747 printf("Supported machines are:\n");
4748 for(m = first_machine; m != NULL; m = m->next) {
4749 printf("%-10s %s%s\n",
4751 m == first_machine ? " (default)" : "");
4753 exit(*optarg != '?');
4756 case QEMU_OPTION_cpu:
4757 /* hw initialization will check this */
4758 if (*optarg == '?') {
4759 /* XXX: implement xxx_cpu_list for targets that still miss it */
4760 #if defined(cpu_list)
4761 cpu_list(stdout, &fprintf);
4768 case QEMU_OPTION_initrd:
4769 initrd_filename = optarg;
4771 case QEMU_OPTION_hda:
4773 hda_index = drive_add(optarg, HD_ALIAS, 0);
4775 hda_index = drive_add(optarg, HD_ALIAS
4776 ",cyls=%d,heads=%d,secs=%d%s",
4777 0, cyls, heads, secs,
4778 translation == BIOS_ATA_TRANSLATION_LBA ?
4780 translation == BIOS_ATA_TRANSLATION_NONE ?
4781 ",trans=none" : "");
4783 case QEMU_OPTION_hdb:
4784 case QEMU_OPTION_hdc:
4785 case QEMU_OPTION_hdd:
4786 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4788 case QEMU_OPTION_drive:
4789 drive_add(NULL, "%s", optarg);
4791 case QEMU_OPTION_mtdblock:
4792 drive_add(optarg, MTD_ALIAS);
4794 case QEMU_OPTION_sd:
4795 drive_add(optarg, SD_ALIAS);
4797 case QEMU_OPTION_pflash:
4798 drive_add(optarg, PFLASH_ALIAS);
4800 case QEMU_OPTION_snapshot:
4803 case QEMU_OPTION_hdachs:
4807 cyls = strtol(p, (char **)&p, 0);
4808 if (cyls < 1 || cyls > 16383)
4813 heads = strtol(p, (char **)&p, 0);
4814 if (heads < 1 || heads > 16)
4819 secs = strtol(p, (char **)&p, 0);
4820 if (secs < 1 || secs > 63)
4824 if (!strcmp(p, "none"))
4825 translation = BIOS_ATA_TRANSLATION_NONE;
4826 else if (!strcmp(p, "lba"))
4827 translation = BIOS_ATA_TRANSLATION_LBA;
4828 else if (!strcmp(p, "auto"))
4829 translation = BIOS_ATA_TRANSLATION_AUTO;
4832 } else if (*p != '\0') {
4834 fprintf(stderr, "qemu: invalid physical CHS format\n");
4837 if (hda_index != -1)
4838 snprintf(drives_opt[hda_index].opt,
4839 sizeof(drives_opt[hda_index].opt),
4840 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4841 0, cyls, heads, secs,
4842 translation == BIOS_ATA_TRANSLATION_LBA ?
4844 translation == BIOS_ATA_TRANSLATION_NONE ?
4845 ",trans=none" : "");
4848 case QEMU_OPTION_nographic:
4851 #ifdef CONFIG_CURSES
4852 case QEMU_OPTION_curses:
4856 case QEMU_OPTION_portrait:
4859 case QEMU_OPTION_kernel:
4860 kernel_filename = optarg;
4862 case QEMU_OPTION_append:
4863 kernel_cmdline = optarg;
4865 case QEMU_OPTION_cdrom:
4866 drive_add(optarg, CDROM_ALIAS);
4868 case QEMU_OPTION_boot:
4869 boot_devices = optarg;
4870 /* We just do some generic consistency checks */
4872 /* Could easily be extended to 64 devices if needed */
4875 boot_devices_bitmap = 0;
4876 for (p = boot_devices; *p != '\0'; p++) {
4877 /* Allowed boot devices are:
4878 * a b : floppy disk drives
4879 * c ... f : IDE disk drives
4880 * g ... m : machine implementation dependant drives
4881 * n ... p : network devices
4882 * It's up to each machine implementation to check
4883 * if the given boot devices match the actual hardware
4884 * implementation and firmware features.
4886 if (*p < 'a' || *p > 'q') {
4887 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4890 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4892 "Boot device '%c' was given twice\n",*p);
4895 boot_devices_bitmap |= 1 << (*p - 'a');
4899 case QEMU_OPTION_fda:
4900 case QEMU_OPTION_fdb:
4901 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4904 case QEMU_OPTION_no_fd_bootchk:
4908 case QEMU_OPTION_net:
4909 if (nb_net_clients >= MAX_NET_CLIENTS) {
4910 fprintf(stderr, "qemu: too many network clients\n");
4913 net_clients[nb_net_clients] = optarg;
4917 case QEMU_OPTION_tftp:
4918 tftp_prefix = optarg;
4920 case QEMU_OPTION_bootp:
4921 bootp_filename = optarg;
4924 case QEMU_OPTION_smb:
4925 net_slirp_smb(optarg);
4928 case QEMU_OPTION_redir:
4929 net_slirp_redir(optarg);
4932 case QEMU_OPTION_bt:
4933 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4934 fprintf(stderr, "qemu: too many bluetooth options\n");
4937 bt_opts[nb_bt_opts++] = optarg;
4940 case QEMU_OPTION_audio_help:
4944 case QEMU_OPTION_soundhw:
4945 select_soundhw (optarg);
4951 case QEMU_OPTION_m: {
4955 value = strtoul(optarg, &ptr, 10);
4957 case 0: case 'M': case 'm':
4964 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4968 /* On 32-bit hosts, QEMU is limited by virtual address space */
4969 if (value > (2047 << 20)
4971 && HOST_LONG_BITS == 32
4974 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4977 if (value != (uint64_t)(ram_addr_t)value) {
4978 fprintf(stderr, "qemu: ram size too large\n");
4987 const CPULogItem *item;
4989 mask = cpu_str_to_log_mask(optarg);
4991 printf("Log items (comma separated):\n");
4992 for(item = cpu_log_items; item->mask != 0; item++) {
4993 printf("%-10s %s\n", item->name, item->help);
5000 #ifdef CONFIG_GDBSTUB
5005 gdbstub_port = optarg;
5011 case QEMU_OPTION_bios:
5018 keyboard_layout = optarg;
5020 case QEMU_OPTION_localtime:
5023 case QEMU_OPTION_vga:
5024 select_vgahw (optarg);
5031 w = strtol(p, (char **)&p, 10);
5034 fprintf(stderr, "qemu: invalid resolution or depth\n");
5040 h = strtol(p, (char **)&p, 10);
5045 depth = strtol(p, (char **)&p, 10);
5046 if (depth != 8 && depth != 15 && depth != 16 &&
5047 depth != 24 && depth != 32)
5049 } else if (*p == '\0') {
5050 depth = graphic_depth;
5057 graphic_depth = depth;
5060 case QEMU_OPTION_echr:
5063 term_escape_char = strtol(optarg, &r, 0);
5065 printf("Bad argument to echr\n");
5068 case QEMU_OPTION_monitor:
5069 monitor_device = optarg;
5071 case QEMU_OPTION_serial:
5072 if (serial_device_index >= MAX_SERIAL_PORTS) {
5073 fprintf(stderr, "qemu: too many serial ports\n");
5076 serial_devices[serial_device_index] = optarg;
5077 serial_device_index++;
5079 case QEMU_OPTION_virtiocon:
5080 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5081 fprintf(stderr, "qemu: too many virtio consoles\n");
5084 virtio_consoles[virtio_console_index] = optarg;
5085 virtio_console_index++;
5087 case QEMU_OPTION_parallel:
5088 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5089 fprintf(stderr, "qemu: too many parallel ports\n");
5092 parallel_devices[parallel_device_index] = optarg;
5093 parallel_device_index++;
5095 case QEMU_OPTION_loadvm:
5098 case QEMU_OPTION_full_screen:
5102 case QEMU_OPTION_no_frame:
5105 case QEMU_OPTION_alt_grab:
5108 case QEMU_OPTION_no_quit:
5111 case QEMU_OPTION_sdl:
5115 case QEMU_OPTION_pidfile:
5119 case QEMU_OPTION_win2k_hack:
5120 win2k_install_hack = 1;
5122 case QEMU_OPTION_rtc_td_hack:
5127 case QEMU_OPTION_no_kqemu:
5130 case QEMU_OPTION_kernel_kqemu:
5135 case QEMU_OPTION_enable_kvm:
5142 case QEMU_OPTION_usb:
5145 case QEMU_OPTION_usbdevice:
5147 if (usb_devices_index >= MAX_USB_CMDLINE) {
5148 fprintf(stderr, "Too many USB devices\n");
5151 usb_devices[usb_devices_index] = optarg;
5152 usb_devices_index++;
5154 case QEMU_OPTION_smp:
5155 smp_cpus = atoi(optarg);
5157 fprintf(stderr, "Invalid number of CPUs\n");
5161 case QEMU_OPTION_vnc:
5162 vnc_display = optarg;
5164 case QEMU_OPTION_no_acpi:
5167 case QEMU_OPTION_no_hpet:
5170 case QEMU_OPTION_no_reboot:
5173 case QEMU_OPTION_no_shutdown:
5176 case QEMU_OPTION_show_cursor:
5179 case QEMU_OPTION_uuid:
5180 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5181 fprintf(stderr, "Fail to parse UUID string."
5182 " Wrong format.\n");
5186 case QEMU_OPTION_daemonize:
5189 case QEMU_OPTION_option_rom:
5190 if (nb_option_roms >= MAX_OPTION_ROMS) {
5191 fprintf(stderr, "Too many option ROMs\n");
5194 option_rom[nb_option_roms] = optarg;
5197 case QEMU_OPTION_semihosting:
5198 semihosting_enabled = 1;
5200 case QEMU_OPTION_name:
5203 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5204 case QEMU_OPTION_prom_env:
5205 if (nb_prom_envs >= MAX_PROM_ENVS) {
5206 fprintf(stderr, "Too many prom variables\n");
5209 prom_envs[nb_prom_envs] = optarg;
5214 case QEMU_OPTION_old_param:
5218 case QEMU_OPTION_clock:
5219 configure_alarms(optarg);
5221 case QEMU_OPTION_startdate:
5224 time_t rtc_start_date;
5225 if (!strcmp(optarg, "now")) {
5226 rtc_date_offset = -1;
5228 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5236 } else if (sscanf(optarg, "%d-%d-%d",
5239 &tm.tm_mday) == 3) {
5248 rtc_start_date = mktimegm(&tm);
5249 if (rtc_start_date == -1) {
5251 fprintf(stderr, "Invalid date format. Valid format are:\n"
5252 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5255 rtc_date_offset = time(NULL) - rtc_start_date;
5259 case QEMU_OPTION_tb_size:
5260 tb_size = strtol(optarg, NULL, 0);
5264 case QEMU_OPTION_icount:
5266 if (strcmp(optarg, "auto") == 0) {
5267 icount_time_shift = -1;
5269 icount_time_shift = strtol(optarg, NULL, 0);
5272 case QEMU_OPTION_incoming:
5279 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5280 if (kvm_allowed && kqemu_allowed) {
5282 "You can not enable both KVM and kqemu at the same time\n");
5287 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5288 if (smp_cpus > machine->max_cpus) {
5289 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5290 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5296 if (serial_device_index == 0)
5297 serial_devices[0] = "stdio";
5298 if (parallel_device_index == 0)
5299 parallel_devices[0] = "null";
5300 if (strncmp(monitor_device, "vc", 2) == 0)
5301 monitor_device = "stdio";
5302 if (virtio_console_index == 0)
5303 virtio_consoles[0] = "null";
5310 if (pipe(fds) == -1)
5321 len = read(fds[0], &status, 1);
5322 if (len == -1 && (errno == EINTR))
5327 else if (status == 1) {
5328 fprintf(stderr, "Could not acquire pidfile\n");
5345 signal(SIGTSTP, SIG_IGN);
5346 signal(SIGTTOU, SIG_IGN);
5347 signal(SIGTTIN, SIG_IGN);
5351 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5354 write(fds[1], &status, 1);
5356 fprintf(stderr, "Could not acquire pid file\n");
5364 linux_boot = (kernel_filename != NULL);
5365 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5367 if (!linux_boot && net_boot == 0 &&
5368 !machine->nodisk_ok && nb_drives_opt == 0)
5371 if (!linux_boot && *kernel_cmdline != '\0') {
5372 fprintf(stderr, "-append only allowed with -kernel option\n");
5376 if (!linux_boot && initrd_filename != NULL) {
5377 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5381 /* boot to floppy or the default cd if no hard disk defined yet */
5382 if (!boot_devices[0]) {
5383 boot_devices = "cad";
5385 setvbuf(stdout, NULL, _IOLBF, 0);
5388 if (init_timer_alarm() < 0) {
5389 fprintf(stderr, "could not initialize alarm timer\n");
5392 if (use_icount && icount_time_shift < 0) {
5394 /* 125MIPS seems a reasonable initial guess at the guest speed.
5395 It will be corrected fairly quickly anyway. */
5396 icount_time_shift = 3;
5397 init_icount_adjust();
5404 /* init network clients */
5405 if (nb_net_clients == 0) {
5406 /* if no clients, we use a default config */
5407 net_clients[nb_net_clients++] = "nic";
5409 net_clients[nb_net_clients++] = "user";
5413 for(i = 0;i < nb_net_clients; i++) {
5414 if (net_client_parse(net_clients[i]) < 0)
5420 /* XXX: this should be moved in the PC machine instantiation code */
5421 if (net_boot != 0) {
5423 for (i = 0; i < nb_nics && i < 4; i++) {
5424 const char *model = nd_table[i].model;
5426 if (net_boot & (1 << i)) {
5429 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5430 if (get_image_size(buf) > 0) {
5431 if (nb_option_roms >= MAX_OPTION_ROMS) {
5432 fprintf(stderr, "Too many option ROMs\n");
5435 option_rom[nb_option_roms] = strdup(buf);
5442 fprintf(stderr, "No valid PXE rom found for network device\n");
5448 /* init the bluetooth world */
5449 for (i = 0; i < nb_bt_opts; i++)
5450 if (bt_parse(bt_opts[i]))
5453 /* init the memory */
5454 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5456 if (machine->ram_require & RAMSIZE_FIXED) {
5458 if (ram_size < phys_ram_size) {
5459 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5460 machine->name, (unsigned long long) phys_ram_size);
5464 phys_ram_size = ram_size;
5466 ram_size = phys_ram_size;
5469 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5471 phys_ram_size += ram_size;
5474 phys_ram_base = qemu_vmalloc(phys_ram_size);
5475 if (!phys_ram_base) {
5476 fprintf(stderr, "Could not allocate physical memory\n");
5480 /* init the dynamic translator */
5481 cpu_exec_init_all(tb_size * 1024 * 1024);
5485 /* we always create the cdrom drive, even if no disk is there */
5487 if (nb_drives_opt < MAX_DRIVES)
5488 drive_add(NULL, CDROM_ALIAS);
5490 /* we always create at least one floppy */
5492 if (nb_drives_opt < MAX_DRIVES)
5493 drive_add(NULL, FD_ALIAS, 0);
5495 /* we always create one sd slot, even if no card is in it */
5497 if (nb_drives_opt < MAX_DRIVES)
5498 drive_add(NULL, SD_ALIAS);
5500 /* open the virtual block devices */
5502 for(i = 0; i < nb_drives_opt; i++)
5503 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5506 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5507 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5510 /* must be after terminal init, SDL library changes signal handlers */
5514 /* Maintain compatibility with multiple stdio monitors */
5515 if (!strcmp(monitor_device,"stdio")) {
5516 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5517 const char *devname = serial_devices[i];
5518 if (devname && !strcmp(devname,"mon:stdio")) {
5519 monitor_device = NULL;
5521 } else if (devname && !strcmp(devname,"stdio")) {
5522 monitor_device = NULL;
5523 serial_devices[i] = "mon:stdio";
5529 if (kvm_enabled()) {
5532 ret = kvm_init(smp_cpus);
5534 fprintf(stderr, "failed to initialize KVM\n");
5539 if (monitor_device) {
5540 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5542 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5547 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5548 const char *devname = serial_devices[i];
5549 if (devname && strcmp(devname, "none")) {
5551 snprintf(label, sizeof(label), "serial%d", i);
5552 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5553 if (!serial_hds[i]) {
5554 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5561 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5562 const char *devname = parallel_devices[i];
5563 if (devname && strcmp(devname, "none")) {
5565 snprintf(label, sizeof(label), "parallel%d", i);
5566 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5567 if (!parallel_hds[i]) {
5568 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5575 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5576 const char *devname = virtio_consoles[i];
5577 if (devname && strcmp(devname, "none")) {
5579 snprintf(label, sizeof(label), "virtcon%d", i);
5580 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5581 if (!virtcon_hds[i]) {
5582 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5589 machine->init(ram_size, vga_ram_size, boot_devices,
5590 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5592 /* Set KVM's vcpu state to qemu's initial CPUState. */
5593 if (kvm_enabled()) {
5596 ret = kvm_sync_vcpus();
5598 fprintf(stderr, "failed to initialize vcpus\n");
5603 /* init USB devices */
5605 for(i = 0; i < usb_devices_index; i++) {
5606 if (usb_device_add(usb_devices[i]) < 0) {
5607 fprintf(stderr, "Warning: could not add USB device %s\n",
5614 dumb_display_init();
5615 /* just use the first displaystate for the moment */
5620 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5624 #if defined(CONFIG_CURSES)
5626 /* At the moment curses cannot be used with other displays */
5627 curses_display_init(ds, full_screen);
5631 if (vnc_display != NULL) {
5632 vnc_display_init(ds);
5633 if (vnc_display_open(ds, vnc_display) < 0)
5636 #if defined(CONFIG_SDL)
5637 if (sdl || !vnc_display)
5638 sdl_display_init(ds, full_screen, no_frame);
5639 #elif defined(CONFIG_COCOA)
5640 if (sdl || !vnc_display)
5641 cocoa_display_init(ds, full_screen);
5647 dcl = ds->listeners;
5648 while (dcl != NULL) {
5649 if (dcl->dpy_refresh != NULL) {
5650 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5651 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5656 if (nographic || (vnc_display && !sdl)) {
5657 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5658 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5661 text_consoles_set_display(display_state);
5663 if (monitor_device && monitor_hd)
5664 monitor_init(monitor_hd, !nographic);
5666 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5667 const char *devname = serial_devices[i];
5668 if (devname && strcmp(devname, "none")) {
5670 snprintf(label, sizeof(label), "serial%d", i);
5671 if (strstart(devname, "vc", 0))
5672 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5676 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5677 const char *devname = parallel_devices[i];
5678 if (devname && strcmp(devname, "none")) {
5680 snprintf(label, sizeof(label), "parallel%d", i);
5681 if (strstart(devname, "vc", 0))
5682 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5686 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5687 const char *devname = virtio_consoles[i];
5688 if (virtcon_hds[i] && devname) {
5690 snprintf(label, sizeof(label), "virtcon%d", i);
5691 if (strstart(devname, "vc", 0))
5692 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5696 #ifdef CONFIG_GDBSTUB
5698 /* XXX: use standard host:port notation and modify options
5700 if (gdbserver_start(gdbstub_port) < 0) {
5701 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5712 autostart = 0; /* fixme how to deal with -daemonize */
5713 qemu_start_incoming_migration(incoming);
5717 /* XXX: simplify init */
5730 len = write(fds[1], &status, 1);
5731 if (len == -1 && (errno == EINTR))
5738 TFR(fd = open("/dev/null", O_RDWR));