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"
38 #include "qemu-timer.h"
39 #include "qemu-char.h"
40 #include "cache-utils.h"
42 #include "audio/audio.h"
43 #include "migration.h"
57 #include <sys/times.h>
61 #include <sys/ioctl.h>
62 #include <sys/resource.h>
63 #include <sys/socket.h>
64 #include <netinet/in.h>
66 #if defined(__NetBSD__)
67 #include <net/if_tap.h>
70 #include <linux/if_tun.h>
72 #include <arpa/inet.h>
75 #include <sys/select.h>
83 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
84 #include <freebsd/stdlib.h>
89 #include <linux/rtc.h>
91 /* For the benefit of older linux systems which don't supply it,
92 we use a local copy of hpet.h. */
93 /* #include <linux/hpet.h> */
96 #include <linux/ppdev.h>
97 #include <linux/parport.h>
100 #include <sys/stat.h>
101 #include <sys/ethernet.h>
102 #include <sys/sockio.h>
103 #include <netinet/arp.h>
104 #include <netinet/in.h>
105 #include <netinet/in_systm.h>
106 #include <netinet/ip.h>
107 #include <netinet/ip_icmp.h> // must come after ip.h
108 #include <netinet/udp.h>
109 #include <netinet/tcp.h>
117 #include "qemu_socket.h"
119 #if defined(CONFIG_SLIRP)
120 #include "libslirp.h"
123 #if defined(__OpenBSD__)
127 #if defined(CONFIG_VDE)
128 #include <libvdeplug.h>
133 #include <sys/timeb.h>
134 #include <mmsystem.h>
135 #define getopt_long_only getopt_long
136 #define memalign(align, size) malloc(size)
142 int qemu_main(int argc, char **argv, char **envp);
143 int main(int argc, char **argv)
145 qemu_main(argc, argv, NULL);
148 #define main qemu_main
150 #endif /* CONFIG_SDL */
154 #define main qemu_main
155 #endif /* CONFIG_COCOA */
159 #include "exec-all.h"
161 //#define DEBUG_UNUSED_IOPORT
162 //#define DEBUG_IOPORT
164 //#define DEBUG_SLIRP
168 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
170 # define LOG_IOPORT(...) do { } while (0)
173 #define DEFAULT_RAM_SIZE 128
175 /* Max number of USB devices that can be specified on the commandline. */
176 #define MAX_USB_CMDLINE 8
178 /* Max number of bluetooth switches on the commandline. */
179 #define MAX_BT_CMDLINE 10
181 /* XXX: use a two level table to limit memory usage */
182 #define MAX_IOPORTS 65536
184 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
185 const char *bios_name = NULL;
186 static void *ioport_opaque[MAX_IOPORTS];
187 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
188 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
189 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
190 to store the VM snapshots */
191 DriveInfo drives_table[MAX_DRIVES+1];
193 static int vga_ram_size;
194 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
195 static DisplayState *display_state;
199 const char* keyboard_layout = NULL;
200 int64_t ticks_per_sec;
203 NICInfo nd_table[MAX_NICS];
205 static int autostart;
206 static int rtc_utc = 1;
207 static int rtc_date_offset = -1; /* -1 means no change */
208 int cirrus_vga_enabled = 1;
209 int std_vga_enabled = 0;
210 int vmsvga_enabled = 0;
212 int graphic_width = 1024;
213 int graphic_height = 768;
214 int graphic_depth = 8;
216 int graphic_width = 800;
217 int graphic_height = 600;
218 int graphic_depth = 15;
220 static int full_screen = 0;
222 static int no_frame = 0;
225 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
226 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
227 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
229 int win2k_install_hack = 0;
234 const char *vnc_display;
235 int acpi_enabled = 1;
241 int graphic_rotate = 0;
243 const char *option_rom[MAX_OPTION_ROMS];
245 int semihosting_enabled = 0;
249 const char *qemu_name;
251 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
252 unsigned int nb_prom_envs = 0;
253 const char *prom_envs[MAX_PROM_ENVS];
256 struct drive_opt drives_opt[MAX_DRIVES];
258 static CPUState *cur_cpu;
259 static CPUState *next_cpu;
260 static int event_pending = 1;
261 /* Conversion factor from emulated instructions to virtual clock ticks. */
262 static int icount_time_shift;
263 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
264 #define MAX_ICOUNT_SHIFT 10
265 /* Compensate for varying guest execution speed. */
266 static int64_t qemu_icount_bias;
267 static QEMUTimer *icount_rt_timer;
268 static QEMUTimer *icount_vm_timer;
269 static QEMUTimer *nographic_timer;
271 uint8_t qemu_uuid[16];
273 /***********************************************************/
274 /* x86 ISA bus support */
276 target_phys_addr_t isa_mem_base = 0;
279 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
280 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
282 static uint32_t ioport_read(int index, uint32_t address)
284 static IOPortReadFunc *default_func[3] = {
285 default_ioport_readb,
286 default_ioport_readw,
289 IOPortReadFunc *func = ioport_read_table[index][address];
291 func = default_func[index];
292 return func(ioport_opaque[address], address);
295 static void ioport_write(int index, uint32_t address, uint32_t data)
297 static IOPortWriteFunc *default_func[3] = {
298 default_ioport_writeb,
299 default_ioport_writew,
300 default_ioport_writel
302 IOPortWriteFunc *func = ioport_write_table[index][address];
304 func = default_func[index];
305 func(ioport_opaque[address], address, data);
308 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
310 #ifdef DEBUG_UNUSED_IOPORT
311 fprintf(stderr, "unused inb: port=0x%04x\n", address);
316 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
318 #ifdef DEBUG_UNUSED_IOPORT
319 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
323 /* default is to make two byte accesses */
324 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
327 data = ioport_read(0, address);
328 address = (address + 1) & (MAX_IOPORTS - 1);
329 data |= ioport_read(0, address) << 8;
333 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
335 ioport_write(0, address, data & 0xff);
336 address = (address + 1) & (MAX_IOPORTS - 1);
337 ioport_write(0, address, (data >> 8) & 0xff);
340 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
342 #ifdef DEBUG_UNUSED_IOPORT
343 fprintf(stderr, "unused inl: port=0x%04x\n", address);
348 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
350 #ifdef DEBUG_UNUSED_IOPORT
351 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
355 /* size is the word size in byte */
356 int register_ioport_read(int start, int length, int size,
357 IOPortReadFunc *func, void *opaque)
363 } else if (size == 2) {
365 } else if (size == 4) {
368 hw_error("register_ioport_read: invalid size");
371 for(i = start; i < start + length; i += size) {
372 ioport_read_table[bsize][i] = func;
373 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
374 hw_error("register_ioport_read: invalid opaque");
375 ioport_opaque[i] = opaque;
380 /* size is the word size in byte */
381 int register_ioport_write(int start, int length, int size,
382 IOPortWriteFunc *func, void *opaque)
388 } else if (size == 2) {
390 } else if (size == 4) {
393 hw_error("register_ioport_write: invalid size");
396 for(i = start; i < start + length; i += size) {
397 ioport_write_table[bsize][i] = func;
398 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
399 hw_error("register_ioport_write: invalid opaque");
400 ioport_opaque[i] = opaque;
405 void isa_unassign_ioport(int start, int length)
409 for(i = start; i < start + length; i++) {
410 ioport_read_table[0][i] = default_ioport_readb;
411 ioport_read_table[1][i] = default_ioport_readw;
412 ioport_read_table[2][i] = default_ioport_readl;
414 ioport_write_table[0][i] = default_ioport_writeb;
415 ioport_write_table[1][i] = default_ioport_writew;
416 ioport_write_table[2][i] = default_ioport_writel;
418 ioport_opaque[i] = NULL;
422 /***********************************************************/
424 void cpu_outb(CPUState *env, int addr, int val)
426 LOG_IOPORT("outb: %04x %02x\n", addr, val);
427 ioport_write(0, addr, val);
430 env->last_io_time = cpu_get_time_fast();
434 void cpu_outw(CPUState *env, int addr, int val)
436 LOG_IOPORT("outw: %04x %04x\n", addr, val);
437 ioport_write(1, addr, val);
440 env->last_io_time = cpu_get_time_fast();
444 void cpu_outl(CPUState *env, int addr, int val)
446 LOG_IOPORT("outl: %04x %08x\n", addr, val);
447 ioport_write(2, addr, val);
450 env->last_io_time = cpu_get_time_fast();
454 int cpu_inb(CPUState *env, int addr)
457 val = ioport_read(0, addr);
458 LOG_IOPORT("inb : %04x %02x\n", addr, val);
461 env->last_io_time = cpu_get_time_fast();
466 int cpu_inw(CPUState *env, int addr)
469 val = ioport_read(1, addr);
470 LOG_IOPORT("inw : %04x %04x\n", addr, val);
473 env->last_io_time = cpu_get_time_fast();
478 int cpu_inl(CPUState *env, int addr)
481 val = ioport_read(2, addr);
482 LOG_IOPORT("inl : %04x %08x\n", addr, val);
485 env->last_io_time = cpu_get_time_fast();
490 /***********************************************************/
491 void hw_error(const char *fmt, ...)
497 fprintf(stderr, "qemu: hardware error: ");
498 vfprintf(stderr, fmt, ap);
499 fprintf(stderr, "\n");
500 for(env = first_cpu; env != NULL; env = env->next_cpu) {
501 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
503 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
505 cpu_dump_state(env, stderr, fprintf, 0);
515 static QEMUBalloonEvent *qemu_balloon_event;
516 void *qemu_balloon_event_opaque;
518 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
520 qemu_balloon_event = func;
521 qemu_balloon_event_opaque = opaque;
524 void qemu_balloon(ram_addr_t target)
526 if (qemu_balloon_event)
527 qemu_balloon_event(qemu_balloon_event_opaque, target);
530 ram_addr_t qemu_balloon_status(void)
532 if (qemu_balloon_event)
533 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
537 /***********************************************************/
540 static QEMUPutKBDEvent *qemu_put_kbd_event;
541 static void *qemu_put_kbd_event_opaque;
542 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
543 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
545 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
547 qemu_put_kbd_event_opaque = opaque;
548 qemu_put_kbd_event = func;
551 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
552 void *opaque, int absolute,
555 QEMUPutMouseEntry *s, *cursor;
557 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
559 s->qemu_put_mouse_event = func;
560 s->qemu_put_mouse_event_opaque = opaque;
561 s->qemu_put_mouse_event_absolute = absolute;
562 s->qemu_put_mouse_event_name = qemu_strdup(name);
565 if (!qemu_put_mouse_event_head) {
566 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
570 cursor = qemu_put_mouse_event_head;
571 while (cursor->next != NULL)
572 cursor = cursor->next;
575 qemu_put_mouse_event_current = s;
580 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
582 QEMUPutMouseEntry *prev = NULL, *cursor;
584 if (!qemu_put_mouse_event_head || entry == NULL)
587 cursor = qemu_put_mouse_event_head;
588 while (cursor != NULL && cursor != entry) {
590 cursor = cursor->next;
593 if (cursor == NULL) // does not exist or list empty
595 else if (prev == NULL) { // entry is head
596 qemu_put_mouse_event_head = cursor->next;
597 if (qemu_put_mouse_event_current == entry)
598 qemu_put_mouse_event_current = cursor->next;
599 qemu_free(entry->qemu_put_mouse_event_name);
604 prev->next = entry->next;
606 if (qemu_put_mouse_event_current == entry)
607 qemu_put_mouse_event_current = prev;
609 qemu_free(entry->qemu_put_mouse_event_name);
613 void kbd_put_keycode(int keycode)
615 if (qemu_put_kbd_event) {
616 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
620 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
622 QEMUPutMouseEvent *mouse_event;
623 void *mouse_event_opaque;
626 if (!qemu_put_mouse_event_current) {
631 qemu_put_mouse_event_current->qemu_put_mouse_event;
633 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
636 if (graphic_rotate) {
637 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
640 width = graphic_width - 1;
641 mouse_event(mouse_event_opaque,
642 width - dy, dx, dz, buttons_state);
644 mouse_event(mouse_event_opaque,
645 dx, dy, dz, buttons_state);
649 int kbd_mouse_is_absolute(void)
651 if (!qemu_put_mouse_event_current)
654 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
657 void do_info_mice(Monitor *mon)
659 QEMUPutMouseEntry *cursor;
662 if (!qemu_put_mouse_event_head) {
663 monitor_printf(mon, "No mouse devices connected\n");
667 monitor_printf(mon, "Mouse devices available:\n");
668 cursor = qemu_put_mouse_event_head;
669 while (cursor != NULL) {
670 monitor_printf(mon, "%c Mouse #%d: %s\n",
671 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
672 index, cursor->qemu_put_mouse_event_name);
674 cursor = cursor->next;
678 void do_mouse_set(Monitor *mon, int index)
680 QEMUPutMouseEntry *cursor;
683 if (!qemu_put_mouse_event_head) {
684 monitor_printf(mon, "No mouse devices connected\n");
688 cursor = qemu_put_mouse_event_head;
689 while (cursor != NULL && index != i) {
691 cursor = cursor->next;
695 qemu_put_mouse_event_current = cursor;
697 monitor_printf(mon, "Mouse at given index not found\n");
700 /* compute with 96 bit intermediate result: (a*b)/c */
701 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
706 #ifdef WORDS_BIGENDIAN
716 rl = (uint64_t)u.l.low * (uint64_t)b;
717 rh = (uint64_t)u.l.high * (uint64_t)b;
720 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
724 /***********************************************************/
725 /* real time host monotonic timer */
727 #define QEMU_TIMER_BASE 1000000000LL
731 static int64_t clock_freq;
733 static void init_get_clock(void)
737 ret = QueryPerformanceFrequency(&freq);
739 fprintf(stderr, "Could not calibrate ticks\n");
742 clock_freq = freq.QuadPart;
745 static int64_t get_clock(void)
748 QueryPerformanceCounter(&ti);
749 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
754 static int use_rt_clock;
756 static void init_get_clock(void)
759 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
762 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
769 static int64_t get_clock(void)
771 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
774 clock_gettime(CLOCK_MONOTONIC, &ts);
775 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
779 /* XXX: using gettimeofday leads to problems if the date
780 changes, so it should be avoided. */
782 gettimeofday(&tv, NULL);
783 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
788 /* Return the virtual CPU time, based on the instruction counter. */
789 static int64_t cpu_get_icount(void)
792 CPUState *env = cpu_single_env;;
793 icount = qemu_icount;
796 fprintf(stderr, "Bad clock read\n");
797 icount -= (env->icount_decr.u16.low + env->icount_extra);
799 return qemu_icount_bias + (icount << icount_time_shift);
802 /***********************************************************/
803 /* guest cycle counter */
805 static int64_t cpu_ticks_prev;
806 static int64_t cpu_ticks_offset;
807 static int64_t cpu_clock_offset;
808 static int cpu_ticks_enabled;
810 /* return the host CPU cycle counter and handle stop/restart */
811 int64_t cpu_get_ticks(void)
814 return cpu_get_icount();
816 if (!cpu_ticks_enabled) {
817 return cpu_ticks_offset;
820 ticks = cpu_get_real_ticks();
821 if (cpu_ticks_prev > ticks) {
822 /* Note: non increasing ticks may happen if the host uses
824 cpu_ticks_offset += cpu_ticks_prev - ticks;
826 cpu_ticks_prev = ticks;
827 return ticks + cpu_ticks_offset;
831 /* return the host CPU monotonic timer and handle stop/restart */
832 static int64_t cpu_get_clock(void)
835 if (!cpu_ticks_enabled) {
836 return cpu_clock_offset;
839 return ti + cpu_clock_offset;
843 /* enable cpu_get_ticks() */
844 void cpu_enable_ticks(void)
846 if (!cpu_ticks_enabled) {
847 cpu_ticks_offset -= cpu_get_real_ticks();
848 cpu_clock_offset -= get_clock();
849 cpu_ticks_enabled = 1;
853 /* disable cpu_get_ticks() : the clock is stopped. You must not call
854 cpu_get_ticks() after that. */
855 void cpu_disable_ticks(void)
857 if (cpu_ticks_enabled) {
858 cpu_ticks_offset = cpu_get_ticks();
859 cpu_clock_offset = cpu_get_clock();
860 cpu_ticks_enabled = 0;
864 /***********************************************************/
867 #define QEMU_TIMER_REALTIME 0
868 #define QEMU_TIMER_VIRTUAL 1
872 /* XXX: add frequency */
880 struct QEMUTimer *next;
883 struct qemu_alarm_timer {
887 int (*start)(struct qemu_alarm_timer *t);
888 void (*stop)(struct qemu_alarm_timer *t);
889 void (*rearm)(struct qemu_alarm_timer *t);
893 #define ALARM_FLAG_DYNTICKS 0x1
894 #define ALARM_FLAG_EXPIRED 0x2
896 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
898 return t->flags & ALARM_FLAG_DYNTICKS;
901 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
903 if (!alarm_has_dynticks(t))
909 /* TODO: MIN_TIMER_REARM_US should be optimized */
910 #define MIN_TIMER_REARM_US 250
912 static struct qemu_alarm_timer *alarm_timer;
914 static int alarm_timer_rfd, alarm_timer_wfd;
919 struct qemu_alarm_win32 {
923 } alarm_win32_data = {0, NULL, -1};
925 static int win32_start_timer(struct qemu_alarm_timer *t);
926 static void win32_stop_timer(struct qemu_alarm_timer *t);
927 static void win32_rearm_timer(struct qemu_alarm_timer *t);
931 static int unix_start_timer(struct qemu_alarm_timer *t);
932 static void unix_stop_timer(struct qemu_alarm_timer *t);
936 static int dynticks_start_timer(struct qemu_alarm_timer *t);
937 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
938 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
940 static int hpet_start_timer(struct qemu_alarm_timer *t);
941 static void hpet_stop_timer(struct qemu_alarm_timer *t);
943 static int rtc_start_timer(struct qemu_alarm_timer *t);
944 static void rtc_stop_timer(struct qemu_alarm_timer *t);
946 #endif /* __linux__ */
950 /* Correlation between real and virtual time is always going to be
951 fairly approximate, so ignore small variation.
952 When the guest is idle real and virtual time will be aligned in
954 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
956 static void icount_adjust(void)
961 static int64_t last_delta;
962 /* If the VM is not running, then do nothing. */
966 cur_time = cpu_get_clock();
967 cur_icount = qemu_get_clock(vm_clock);
968 delta = cur_icount - cur_time;
969 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
971 && last_delta + ICOUNT_WOBBLE < delta * 2
972 && icount_time_shift > 0) {
973 /* The guest is getting too far ahead. Slow time down. */
977 && last_delta - ICOUNT_WOBBLE > delta * 2
978 && icount_time_shift < MAX_ICOUNT_SHIFT) {
979 /* The guest is getting too far behind. Speed time up. */
983 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
986 static void icount_adjust_rt(void * opaque)
988 qemu_mod_timer(icount_rt_timer,
989 qemu_get_clock(rt_clock) + 1000);
993 static void icount_adjust_vm(void * opaque)
995 qemu_mod_timer(icount_vm_timer,
996 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1000 static void init_icount_adjust(void)
1002 /* Have both realtime and virtual time triggers for speed adjustment.
1003 The realtime trigger catches emulated time passing too slowly,
1004 the virtual time trigger catches emulated time passing too fast.
1005 Realtime triggers occur even when idle, so use them less frequently
1006 than VM triggers. */
1007 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1008 qemu_mod_timer(icount_rt_timer,
1009 qemu_get_clock(rt_clock) + 1000);
1010 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1011 qemu_mod_timer(icount_vm_timer,
1012 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1015 static struct qemu_alarm_timer alarm_timers[] = {
1018 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1019 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1020 /* HPET - if available - is preferred */
1021 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1022 /* ...otherwise try RTC */
1023 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1025 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1027 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1028 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1029 {"win32", 0, win32_start_timer,
1030 win32_stop_timer, NULL, &alarm_win32_data},
1035 static void show_available_alarms(void)
1039 printf("Available alarm timers, in order of precedence:\n");
1040 for (i = 0; alarm_timers[i].name; i++)
1041 printf("%s\n", alarm_timers[i].name);
1044 static void configure_alarms(char const *opt)
1048 int count = ARRAY_SIZE(alarm_timers) - 1;
1051 struct qemu_alarm_timer tmp;
1053 if (!strcmp(opt, "?")) {
1054 show_available_alarms();
1060 /* Reorder the array */
1061 name = strtok(arg, ",");
1063 for (i = 0; i < count && alarm_timers[i].name; i++) {
1064 if (!strcmp(alarm_timers[i].name, name))
1069 fprintf(stderr, "Unknown clock %s\n", name);
1078 tmp = alarm_timers[i];
1079 alarm_timers[i] = alarm_timers[cur];
1080 alarm_timers[cur] = tmp;
1084 name = strtok(NULL, ",");
1090 /* Disable remaining timers */
1091 for (i = cur; i < count; i++)
1092 alarm_timers[i].name = NULL;
1094 show_available_alarms();
1099 QEMUClock *rt_clock;
1100 QEMUClock *vm_clock;
1102 static QEMUTimer *active_timers[2];
1104 static QEMUClock *qemu_new_clock(int type)
1107 clock = qemu_mallocz(sizeof(QEMUClock));
1112 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1116 ts = qemu_mallocz(sizeof(QEMUTimer));
1119 ts->opaque = opaque;
1123 void qemu_free_timer(QEMUTimer *ts)
1128 /* stop a timer, but do not dealloc it */
1129 void qemu_del_timer(QEMUTimer *ts)
1133 /* NOTE: this code must be signal safe because
1134 qemu_timer_expired() can be called from a signal. */
1135 pt = &active_timers[ts->clock->type];
1148 /* modify the current timer so that it will be fired when current_time
1149 >= expire_time. The corresponding callback will be called. */
1150 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1156 /* add the timer in the sorted list */
1157 /* NOTE: this code must be signal safe because
1158 qemu_timer_expired() can be called from a signal. */
1159 pt = &active_timers[ts->clock->type];
1164 if (t->expire_time > expire_time)
1168 ts->expire_time = expire_time;
1172 /* Rearm if necessary */
1173 if (pt == &active_timers[ts->clock->type]) {
1174 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1175 qemu_rearm_alarm_timer(alarm_timer);
1177 /* Interrupt execution to force deadline recalculation. */
1178 if (use_icount && cpu_single_env) {
1179 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1184 int qemu_timer_pending(QEMUTimer *ts)
1187 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1194 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1198 return (timer_head->expire_time <= current_time);
1201 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1207 if (!ts || ts->expire_time > current_time)
1209 /* remove timer from the list before calling the callback */
1210 *ptimer_head = ts->next;
1213 /* run the callback (the timer list can be modified) */
1218 int64_t qemu_get_clock(QEMUClock *clock)
1220 switch(clock->type) {
1221 case QEMU_TIMER_REALTIME:
1222 return get_clock() / 1000000;
1224 case QEMU_TIMER_VIRTUAL:
1226 return cpu_get_icount();
1228 return cpu_get_clock();
1233 static void init_timers(void)
1236 ticks_per_sec = QEMU_TIMER_BASE;
1237 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1238 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1242 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1244 uint64_t expire_time;
1246 if (qemu_timer_pending(ts)) {
1247 expire_time = ts->expire_time;
1251 qemu_put_be64(f, expire_time);
1254 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1256 uint64_t expire_time;
1258 expire_time = qemu_get_be64(f);
1259 if (expire_time != -1) {
1260 qemu_mod_timer(ts, expire_time);
1266 static void timer_save(QEMUFile *f, void *opaque)
1268 if (cpu_ticks_enabled) {
1269 hw_error("cannot save state if virtual timers are running");
1271 qemu_put_be64(f, cpu_ticks_offset);
1272 qemu_put_be64(f, ticks_per_sec);
1273 qemu_put_be64(f, cpu_clock_offset);
1276 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1278 if (version_id != 1 && version_id != 2)
1280 if (cpu_ticks_enabled) {
1283 cpu_ticks_offset=qemu_get_be64(f);
1284 ticks_per_sec=qemu_get_be64(f);
1285 if (version_id == 2) {
1286 cpu_clock_offset=qemu_get_be64(f);
1292 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1293 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1295 static void host_alarm_handler(int host_signum)
1299 #define DISP_FREQ 1000
1301 static int64_t delta_min = INT64_MAX;
1302 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1304 ti = qemu_get_clock(vm_clock);
1305 if (last_clock != 0) {
1306 delta = ti - last_clock;
1307 if (delta < delta_min)
1309 if (delta > delta_max)
1312 if (++count == DISP_FREQ) {
1313 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1314 muldiv64(delta_min, 1000000, ticks_per_sec),
1315 muldiv64(delta_max, 1000000, ticks_per_sec),
1316 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1317 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1319 delta_min = INT64_MAX;
1327 if (alarm_has_dynticks(alarm_timer) ||
1329 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1330 qemu_get_clock(vm_clock))) ||
1331 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1332 qemu_get_clock(rt_clock))) {
1333 CPUState *env = next_cpu;
1336 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1337 SetEvent(data->host_alarm);
1339 static const char byte = 0;
1340 write(alarm_timer_wfd, &byte, sizeof(byte));
1342 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1345 /* stop the currently executing cpu because a timer occured */
1346 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1348 if (env->kqemu_enabled) {
1349 kqemu_cpu_interrupt(env);
1357 static int64_t qemu_next_deadline(void)
1361 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1362 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1363 qemu_get_clock(vm_clock);
1365 /* To avoid problems with overflow limit this to 2^32. */
1375 #if defined(__linux__) || defined(_WIN32)
1376 static uint64_t qemu_next_deadline_dyntick(void)
1384 delta = (qemu_next_deadline() + 999) / 1000;
1386 if (active_timers[QEMU_TIMER_REALTIME]) {
1387 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1388 qemu_get_clock(rt_clock))*1000;
1389 if (rtdelta < delta)
1393 if (delta < MIN_TIMER_REARM_US)
1394 delta = MIN_TIMER_REARM_US;
1402 /* Sets a specific flag */
1403 static int fcntl_setfl(int fd, int flag)
1407 flags = fcntl(fd, F_GETFL);
1411 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1417 #if defined(__linux__)
1419 #define RTC_FREQ 1024
1421 static void enable_sigio_timer(int fd)
1423 struct sigaction act;
1426 sigfillset(&act.sa_mask);
1428 act.sa_handler = host_alarm_handler;
1430 sigaction(SIGIO, &act, NULL);
1431 fcntl_setfl(fd, O_ASYNC);
1432 fcntl(fd, F_SETOWN, getpid());
1435 static int hpet_start_timer(struct qemu_alarm_timer *t)
1437 struct hpet_info info;
1440 fd = open("/dev/hpet", O_RDONLY);
1445 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1447 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1448 "error, but for better emulation accuracy type:\n"
1449 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1453 /* Check capabilities */
1454 r = ioctl(fd, HPET_INFO, &info);
1458 /* Enable periodic mode */
1459 r = ioctl(fd, HPET_EPI, 0);
1460 if (info.hi_flags && (r < 0))
1463 /* Enable interrupt */
1464 r = ioctl(fd, HPET_IE_ON, 0);
1468 enable_sigio_timer(fd);
1469 t->priv = (void *)(long)fd;
1477 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1479 int fd = (long)t->priv;
1484 static int rtc_start_timer(struct qemu_alarm_timer *t)
1487 unsigned long current_rtc_freq = 0;
1489 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1492 ioctl(rtc_fd, RTC_IRQP_READ, ¤t_rtc_freq);
1493 if (current_rtc_freq != RTC_FREQ &&
1494 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1495 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1496 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1497 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1500 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1506 enable_sigio_timer(rtc_fd);
1508 t->priv = (void *)(long)rtc_fd;
1513 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1515 int rtc_fd = (long)t->priv;
1520 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1524 struct sigaction act;
1526 sigfillset(&act.sa_mask);
1528 act.sa_handler = host_alarm_handler;
1530 sigaction(SIGALRM, &act, NULL);
1532 ev.sigev_value.sival_int = 0;
1533 ev.sigev_notify = SIGEV_SIGNAL;
1534 ev.sigev_signo = SIGALRM;
1536 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1537 perror("timer_create");
1539 /* disable dynticks */
1540 fprintf(stderr, "Dynamic Ticks disabled\n");
1545 t->priv = (void *)(long)host_timer;
1550 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1552 timer_t host_timer = (timer_t)(long)t->priv;
1554 timer_delete(host_timer);
1557 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1559 timer_t host_timer = (timer_t)(long)t->priv;
1560 struct itimerspec timeout;
1561 int64_t nearest_delta_us = INT64_MAX;
1564 if (!active_timers[QEMU_TIMER_REALTIME] &&
1565 !active_timers[QEMU_TIMER_VIRTUAL])
1568 nearest_delta_us = qemu_next_deadline_dyntick();
1570 /* check whether a timer is already running */
1571 if (timer_gettime(host_timer, &timeout)) {
1573 fprintf(stderr, "Internal timer error: aborting\n");
1576 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1577 if (current_us && current_us <= nearest_delta_us)
1580 timeout.it_interval.tv_sec = 0;
1581 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1582 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1583 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1584 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1586 fprintf(stderr, "Internal timer error: aborting\n");
1591 #endif /* defined(__linux__) */
1593 static int unix_start_timer(struct qemu_alarm_timer *t)
1595 struct sigaction act;
1596 struct itimerval itv;
1600 sigfillset(&act.sa_mask);
1602 act.sa_handler = host_alarm_handler;
1604 sigaction(SIGALRM, &act, NULL);
1606 itv.it_interval.tv_sec = 0;
1607 /* for i386 kernel 2.6 to get 1 ms */
1608 itv.it_interval.tv_usec = 999;
1609 itv.it_value.tv_sec = 0;
1610 itv.it_value.tv_usec = 10 * 1000;
1612 err = setitimer(ITIMER_REAL, &itv, NULL);
1619 static void unix_stop_timer(struct qemu_alarm_timer *t)
1621 struct itimerval itv;
1623 memset(&itv, 0, sizeof(itv));
1624 setitimer(ITIMER_REAL, &itv, NULL);
1627 #endif /* !defined(_WIN32) */
1629 static void try_to_rearm_timer(void *opaque)
1631 struct qemu_alarm_timer *t = opaque;
1635 /* Drain the notify pipe */
1638 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1639 } while ((len == -1 && errno == EINTR) || len > 0);
1642 if (t->flags & ALARM_FLAG_EXPIRED) {
1643 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1644 qemu_rearm_alarm_timer(alarm_timer);
1650 static int win32_start_timer(struct qemu_alarm_timer *t)
1653 struct qemu_alarm_win32 *data = t->priv;
1656 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1657 if (!data->host_alarm) {
1658 perror("Failed CreateEvent");
1662 memset(&tc, 0, sizeof(tc));
1663 timeGetDevCaps(&tc, sizeof(tc));
1665 if (data->period < tc.wPeriodMin)
1666 data->period = tc.wPeriodMin;
1668 timeBeginPeriod(data->period);
1670 flags = TIME_CALLBACK_FUNCTION;
1671 if (alarm_has_dynticks(t))
1672 flags |= TIME_ONESHOT;
1674 flags |= TIME_PERIODIC;
1676 data->timerId = timeSetEvent(1, // interval (ms)
1677 data->period, // resolution
1678 host_alarm_handler, // function
1679 (DWORD)t, // parameter
1682 if (!data->timerId) {
1683 perror("Failed to initialize win32 alarm timer");
1685 timeEndPeriod(data->period);
1686 CloseHandle(data->host_alarm);
1690 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1695 static void win32_stop_timer(struct qemu_alarm_timer *t)
1697 struct qemu_alarm_win32 *data = t->priv;
1699 timeKillEvent(data->timerId);
1700 timeEndPeriod(data->period);
1702 CloseHandle(data->host_alarm);
1705 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1707 struct qemu_alarm_win32 *data = t->priv;
1708 uint64_t nearest_delta_us;
1710 if (!active_timers[QEMU_TIMER_REALTIME] &&
1711 !active_timers[QEMU_TIMER_VIRTUAL])
1714 nearest_delta_us = qemu_next_deadline_dyntick();
1715 nearest_delta_us /= 1000;
1717 timeKillEvent(data->timerId);
1719 data->timerId = timeSetEvent(1,
1723 TIME_ONESHOT | TIME_PERIODIC);
1725 if (!data->timerId) {
1726 perror("Failed to re-arm win32 alarm timer");
1728 timeEndPeriod(data->period);
1729 CloseHandle(data->host_alarm);
1736 static int init_timer_alarm(void)
1738 struct qemu_alarm_timer *t = NULL;
1748 err = fcntl_setfl(fds[0], O_NONBLOCK);
1752 err = fcntl_setfl(fds[1], O_NONBLOCK);
1756 alarm_timer_rfd = fds[0];
1757 alarm_timer_wfd = fds[1];
1760 for (i = 0; alarm_timers[i].name; i++) {
1761 t = &alarm_timers[i];
1774 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1775 try_to_rearm_timer, NULL, t);
1790 static void quit_timers(void)
1792 alarm_timer->stop(alarm_timer);
1796 /***********************************************************/
1797 /* host time/date access */
1798 void qemu_get_timedate(struct tm *tm, int offset)
1805 if (rtc_date_offset == -1) {
1809 ret = localtime(&ti);
1811 ti -= rtc_date_offset;
1815 memcpy(tm, ret, sizeof(struct tm));
1818 int qemu_timedate_diff(struct tm *tm)
1822 if (rtc_date_offset == -1)
1824 seconds = mktimegm(tm);
1826 seconds = mktime(tm);
1828 seconds = mktimegm(tm) + rtc_date_offset;
1830 return seconds - time(NULL);
1834 static void socket_cleanup(void)
1839 static int socket_init(void)
1844 ret = WSAStartup(MAKEWORD(2,2), &Data);
1846 err = WSAGetLastError();
1847 fprintf(stderr, "WSAStartup: %d\n", err);
1850 atexit(socket_cleanup);
1855 const char *get_opt_name(char *buf, int buf_size, const char *p)
1860 while (*p != '\0' && *p != '=') {
1861 if (q && (q - buf) < buf_size - 1)
1871 const char *get_opt_value(char *buf, int buf_size, const char *p)
1876 while (*p != '\0') {
1878 if (*(p + 1) != ',')
1882 if (q && (q - buf) < buf_size - 1)
1892 int get_param_value(char *buf, int buf_size,
1893 const char *tag, const char *str)
1900 p = get_opt_name(option, sizeof(option), p);
1904 if (!strcmp(tag, option)) {
1905 (void)get_opt_value(buf, buf_size, p);
1908 p = get_opt_value(NULL, 0, p);
1917 int check_params(char *buf, int buf_size,
1918 const char * const *params, const char *str)
1925 p = get_opt_name(buf, buf_size, p);
1929 for(i = 0; params[i] != NULL; i++)
1930 if (!strcmp(params[i], buf))
1932 if (params[i] == NULL)
1934 p = get_opt_value(NULL, 0, p);
1942 /***********************************************************/
1943 /* Bluetooth support */
1946 static struct HCIInfo *hci_table[MAX_NICS];
1948 static struct bt_vlan_s {
1949 struct bt_scatternet_s net;
1951 struct bt_vlan_s *next;
1954 /* find or alloc a new bluetooth "VLAN" */
1955 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1957 struct bt_vlan_s **pvlan, *vlan;
1958 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1962 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1964 pvlan = &first_bt_vlan;
1965 while (*pvlan != NULL)
1966 pvlan = &(*pvlan)->next;
1971 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1975 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1980 static struct HCIInfo null_hci = {
1981 .cmd_send = null_hci_send,
1982 .sco_send = null_hci_send,
1983 .acl_send = null_hci_send,
1984 .bdaddr_set = null_hci_addr_set,
1987 struct HCIInfo *qemu_next_hci(void)
1989 if (cur_hci == nb_hcis)
1992 return hci_table[cur_hci++];
1995 static struct HCIInfo *hci_init(const char *str)
1998 struct bt_scatternet_s *vlan = 0;
2000 if (!strcmp(str, "null"))
2003 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2005 return bt_host_hci(str[4] ? str + 5 : "hci0");
2006 else if (!strncmp(str, "hci", 3)) {
2009 if (!strncmp(str + 3, ",vlan=", 6)) {
2010 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2015 vlan = qemu_find_bt_vlan(0);
2017 return bt_new_hci(vlan);
2020 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2025 static int bt_hci_parse(const char *str)
2027 struct HCIInfo *hci;
2030 if (nb_hcis >= MAX_NICS) {
2031 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2035 hci = hci_init(str);
2044 bdaddr.b[5] = 0x56 + nb_hcis;
2045 hci->bdaddr_set(hci, bdaddr.b);
2047 hci_table[nb_hcis++] = hci;
2052 static void bt_vhci_add(int vlan_id)
2054 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2057 fprintf(stderr, "qemu: warning: adding a VHCI to "
2058 "an empty scatternet %i\n", vlan_id);
2060 bt_vhci_init(bt_new_hci(vlan));
2063 static struct bt_device_s *bt_device_add(const char *opt)
2065 struct bt_scatternet_s *vlan;
2067 char *endp = strstr(opt, ",vlan=");
2068 int len = (endp ? endp - opt : strlen(opt)) + 1;
2071 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2074 vlan_id = strtol(endp + 6, &endp, 0);
2076 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2081 vlan = qemu_find_bt_vlan(vlan_id);
2084 fprintf(stderr, "qemu: warning: adding a slave device to "
2085 "an empty scatternet %i\n", vlan_id);
2087 if (!strcmp(devname, "keyboard"))
2088 return bt_keyboard_init(vlan);
2090 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2094 static int bt_parse(const char *opt)
2096 const char *endp, *p;
2099 if (strstart(opt, "hci", &endp)) {
2100 if (!*endp || *endp == ',') {
2102 if (!strstart(endp, ",vlan=", 0))
2105 return bt_hci_parse(opt);
2107 } else if (strstart(opt, "vhci", &endp)) {
2108 if (!*endp || *endp == ',') {
2110 if (strstart(endp, ",vlan=", &p)) {
2111 vlan = strtol(p, (char **) &endp, 0);
2113 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2117 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2126 } else if (strstart(opt, "device:", &endp))
2127 return !bt_device_add(endp);
2129 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2133 /***********************************************************/
2134 /* QEMU Block devices */
2136 #define HD_ALIAS "index=%d,media=disk"
2138 #define CDROM_ALIAS "index=1,media=cdrom"
2140 #define CDROM_ALIAS "index=2,media=cdrom"
2142 #define FD_ALIAS "index=%d,if=floppy"
2143 #define PFLASH_ALIAS "if=pflash"
2144 #define MTD_ALIAS "if=mtd"
2145 #define SD_ALIAS "index=0,if=sd"
2147 static int drive_opt_get_free_idx(void)
2151 for (index = 0; index < MAX_DRIVES; index++)
2152 if (!drives_opt[index].used) {
2153 drives_opt[index].used = 1;
2160 static int drive_get_free_idx(void)
2164 for (index = 0; index < MAX_DRIVES; index++)
2165 if (!drives_table[index].used) {
2166 drives_table[index].used = 1;
2173 int drive_add(const char *file, const char *fmt, ...)
2176 int index = drive_opt_get_free_idx();
2178 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2179 fprintf(stderr, "qemu: too many drives\n");
2183 drives_opt[index].file = file;
2185 vsnprintf(drives_opt[index].opt,
2186 sizeof(drives_opt[0].opt), fmt, ap);
2193 void drive_remove(int index)
2195 drives_opt[index].used = 0;
2199 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2203 /* seek interface, bus and unit */
2205 for (index = 0; index < MAX_DRIVES; index++)
2206 if (drives_table[index].type == type &&
2207 drives_table[index].bus == bus &&
2208 drives_table[index].unit == unit &&
2209 drives_table[index].used)
2215 int drive_get_max_bus(BlockInterfaceType type)
2221 for (index = 0; index < nb_drives; index++) {
2222 if(drives_table[index].type == type &&
2223 drives_table[index].bus > max_bus)
2224 max_bus = drives_table[index].bus;
2229 const char *drive_get_serial(BlockDriverState *bdrv)
2233 for (index = 0; index < nb_drives; index++)
2234 if (drives_table[index].bdrv == bdrv)
2235 return drives_table[index].serial;
2240 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2244 for (index = 0; index < nb_drives; index++)
2245 if (drives_table[index].bdrv == bdrv)
2246 return drives_table[index].onerror;
2248 return BLOCK_ERR_STOP_ENOSPC;
2251 static void bdrv_format_print(void *opaque, const char *name)
2253 fprintf(stderr, " %s", name);
2256 void drive_uninit(BlockDriverState *bdrv)
2260 for (i = 0; i < MAX_DRIVES; i++)
2261 if (drives_table[i].bdrv == bdrv) {
2262 drives_table[i].bdrv = NULL;
2263 drives_table[i].used = 0;
2264 drive_remove(drives_table[i].drive_opt_idx);
2270 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2276 const char *mediastr = "";
2277 BlockInterfaceType type;
2278 enum { MEDIA_DISK, MEDIA_CDROM } media;
2279 int bus_id, unit_id;
2280 int cyls, heads, secs, translation;
2281 BlockDriverState *bdrv;
2282 BlockDriver *drv = NULL;
2283 QEMUMachine *machine = opaque;
2287 int bdrv_flags, onerror;
2288 int drives_table_idx;
2289 char *str = arg->opt;
2290 static const char * const params[] = { "bus", "unit", "if", "index",
2291 "cyls", "heads", "secs", "trans",
2292 "media", "snapshot", "file",
2293 "cache", "format", "serial", "werror",
2296 if (check_params(buf, sizeof(buf), params, str) < 0) {
2297 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2303 cyls = heads = secs = 0;
2306 translation = BIOS_ATA_TRANSLATION_AUTO;
2310 if (machine->use_scsi) {
2312 max_devs = MAX_SCSI_DEVS;
2313 pstrcpy(devname, sizeof(devname), "scsi");
2316 max_devs = MAX_IDE_DEVS;
2317 pstrcpy(devname, sizeof(devname), "ide");
2321 /* extract parameters */
2323 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2324 bus_id = strtol(buf, NULL, 0);
2326 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2331 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2332 unit_id = strtol(buf, NULL, 0);
2334 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2339 if (get_param_value(buf, sizeof(buf), "if", str)) {
2340 pstrcpy(devname, sizeof(devname), buf);
2341 if (!strcmp(buf, "ide")) {
2343 max_devs = MAX_IDE_DEVS;
2344 } else if (!strcmp(buf, "scsi")) {
2346 max_devs = MAX_SCSI_DEVS;
2347 } else if (!strcmp(buf, "floppy")) {
2350 } else if (!strcmp(buf, "pflash")) {
2353 } else if (!strcmp(buf, "mtd")) {
2356 } else if (!strcmp(buf, "sd")) {
2359 } else if (!strcmp(buf, "virtio")) {
2363 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2368 if (get_param_value(buf, sizeof(buf), "index", str)) {
2369 index = strtol(buf, NULL, 0);
2371 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2376 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2377 cyls = strtol(buf, NULL, 0);
2380 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2381 heads = strtol(buf, NULL, 0);
2384 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2385 secs = strtol(buf, NULL, 0);
2388 if (cyls || heads || secs) {
2389 if (cyls < 1 || cyls > 16383) {
2390 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2393 if (heads < 1 || heads > 16) {
2394 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2397 if (secs < 1 || secs > 63) {
2398 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2403 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2406 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2410 if (!strcmp(buf, "none"))
2411 translation = BIOS_ATA_TRANSLATION_NONE;
2412 else if (!strcmp(buf, "lba"))
2413 translation = BIOS_ATA_TRANSLATION_LBA;
2414 else if (!strcmp(buf, "auto"))
2415 translation = BIOS_ATA_TRANSLATION_AUTO;
2417 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2422 if (get_param_value(buf, sizeof(buf), "media", str)) {
2423 if (!strcmp(buf, "disk")) {
2425 } else if (!strcmp(buf, "cdrom")) {
2426 if (cyls || secs || heads) {
2428 "qemu: '%s' invalid physical CHS format\n", str);
2431 media = MEDIA_CDROM;
2433 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2438 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2439 if (!strcmp(buf, "on"))
2441 else if (!strcmp(buf, "off"))
2444 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2449 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2450 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2452 else if (!strcmp(buf, "writethrough"))
2454 else if (!strcmp(buf, "writeback"))
2457 fprintf(stderr, "qemu: invalid cache option\n");
2462 if (get_param_value(buf, sizeof(buf), "format", str)) {
2463 if (strcmp(buf, "?") == 0) {
2464 fprintf(stderr, "qemu: Supported formats:");
2465 bdrv_iterate_format(bdrv_format_print, NULL);
2466 fprintf(stderr, "\n");
2469 drv = bdrv_find_format(buf);
2471 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2476 if (arg->file == NULL)
2477 get_param_value(file, sizeof(file), "file", str);
2479 pstrcpy(file, sizeof(file), arg->file);
2481 if (!get_param_value(serial, sizeof(serial), "serial", str))
2482 memset(serial, 0, sizeof(serial));
2484 onerror = BLOCK_ERR_STOP_ENOSPC;
2485 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2486 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2487 fprintf(stderr, "werror is no supported by this format\n");
2490 if (!strcmp(buf, "ignore"))
2491 onerror = BLOCK_ERR_IGNORE;
2492 else if (!strcmp(buf, "enospc"))
2493 onerror = BLOCK_ERR_STOP_ENOSPC;
2494 else if (!strcmp(buf, "stop"))
2495 onerror = BLOCK_ERR_STOP_ANY;
2496 else if (!strcmp(buf, "report"))
2497 onerror = BLOCK_ERR_REPORT;
2499 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2504 /* compute bus and unit according index */
2507 if (bus_id != 0 || unit_id != -1) {
2509 "qemu: '%s' index cannot be used with bus and unit\n", str);
2517 unit_id = index % max_devs;
2518 bus_id = index / max_devs;
2522 /* if user doesn't specify a unit_id,
2523 * try to find the first free
2526 if (unit_id == -1) {
2528 while (drive_get_index(type, bus_id, unit_id) != -1) {
2530 if (max_devs && unit_id >= max_devs) {
2531 unit_id -= max_devs;
2539 if (max_devs && unit_id >= max_devs) {
2540 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2541 str, unit_id, max_devs - 1);
2546 * ignore multiple definitions
2549 if (drive_get_index(type, bus_id, unit_id) != -1)
2554 if (type == IF_IDE || type == IF_SCSI)
2555 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2557 snprintf(buf, sizeof(buf), "%s%i%s%i",
2558 devname, bus_id, mediastr, unit_id);
2560 snprintf(buf, sizeof(buf), "%s%s%i",
2561 devname, mediastr, unit_id);
2562 bdrv = bdrv_new(buf);
2563 drives_table_idx = drive_get_free_idx();
2564 drives_table[drives_table_idx].bdrv = bdrv;
2565 drives_table[drives_table_idx].type = type;
2566 drives_table[drives_table_idx].bus = bus_id;
2567 drives_table[drives_table_idx].unit = unit_id;
2568 drives_table[drives_table_idx].onerror = onerror;
2569 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2570 strncpy(drives_table[nb_drives].serial, serial, sizeof(serial));
2579 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2580 bdrv_set_translation_hint(bdrv, translation);
2584 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2589 /* FIXME: This isn't really a floppy, but it's a reasonable
2592 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2603 bdrv_flags |= BDRV_O_SNAPSHOT;
2604 cache = 2; /* always use write-back with snapshot */
2606 if (cache == 0) /* no caching */
2607 bdrv_flags |= BDRV_O_NOCACHE;
2608 else if (cache == 2) /* write-back */
2609 bdrv_flags |= BDRV_O_CACHE_WB;
2610 else if (cache == 3) /* not specified */
2611 bdrv_flags |= BDRV_O_CACHE_DEF;
2612 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2613 fprintf(stderr, "qemu: could not open disk image %s\n",
2617 if (bdrv_key_required(bdrv))
2619 return drives_table_idx;
2622 /***********************************************************/
2625 static USBPort *used_usb_ports;
2626 static USBPort *free_usb_ports;
2628 /* ??? Maybe change this to register a hub to keep track of the topology. */
2629 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2630 usb_attachfn attach)
2632 port->opaque = opaque;
2633 port->index = index;
2634 port->attach = attach;
2635 port->next = free_usb_ports;
2636 free_usb_ports = port;
2639 int usb_device_add_dev(USBDevice *dev)
2643 /* Find a USB port to add the device to. */
2644 port = free_usb_ports;
2648 /* Create a new hub and chain it on. */
2649 free_usb_ports = NULL;
2650 port->next = used_usb_ports;
2651 used_usb_ports = port;
2653 hub = usb_hub_init(VM_USB_HUB_SIZE);
2654 usb_attach(port, hub);
2655 port = free_usb_ports;
2658 free_usb_ports = port->next;
2659 port->next = used_usb_ports;
2660 used_usb_ports = port;
2661 usb_attach(port, dev);
2665 static void usb_msd_password_cb(void *opaque, int err)
2667 USBDevice *dev = opaque;
2670 usb_device_add_dev(dev);
2672 dev->handle_destroy(dev);
2675 static int usb_device_add(const char *devname, int is_hotplug)
2680 if (!free_usb_ports)
2683 if (strstart(devname, "host:", &p)) {
2684 dev = usb_host_device_open(p);
2685 } else if (!strcmp(devname, "mouse")) {
2686 dev = usb_mouse_init();
2687 } else if (!strcmp(devname, "tablet")) {
2688 dev = usb_tablet_init();
2689 } else if (!strcmp(devname, "keyboard")) {
2690 dev = usb_keyboard_init();
2691 } else if (strstart(devname, "disk:", &p)) {
2692 BlockDriverState *bs;
2694 dev = usb_msd_init(p);
2697 bs = usb_msd_get_bdrv(dev);
2698 if (bdrv_key_required(bs)) {
2701 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2706 } else if (!strcmp(devname, "wacom-tablet")) {
2707 dev = usb_wacom_init();
2708 } else if (strstart(devname, "serial:", &p)) {
2709 dev = usb_serial_init(p);
2710 #ifdef CONFIG_BRLAPI
2711 } else if (!strcmp(devname, "braille")) {
2712 dev = usb_baum_init();
2714 } else if (strstart(devname, "net:", &p)) {
2717 if (net_client_init("nic", p) < 0)
2719 nd_table[nic].model = "usb";
2720 dev = usb_net_init(&nd_table[nic]);
2721 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2722 dev = usb_bt_init(devname[2] ? hci_init(p) :
2723 bt_new_hci(qemu_find_bt_vlan(0)));
2730 return usb_device_add_dev(dev);
2733 int usb_device_del_addr(int bus_num, int addr)
2739 if (!used_usb_ports)
2745 lastp = &used_usb_ports;
2746 port = used_usb_ports;
2747 while (port && port->dev->addr != addr) {
2748 lastp = &port->next;
2756 *lastp = port->next;
2757 usb_attach(port, NULL);
2758 dev->handle_destroy(dev);
2759 port->next = free_usb_ports;
2760 free_usb_ports = port;
2764 static int usb_device_del(const char *devname)
2769 if (strstart(devname, "host:", &p))
2770 return usb_host_device_close(p);
2772 if (!used_usb_ports)
2775 p = strchr(devname, '.');
2778 bus_num = strtoul(devname, NULL, 0);
2779 addr = strtoul(p + 1, NULL, 0);
2781 return usb_device_del_addr(bus_num, addr);
2784 void do_usb_add(Monitor *mon, const char *devname)
2786 usb_device_add(devname, 1);
2789 void do_usb_del(Monitor *mon, const char *devname)
2791 usb_device_del(devname);
2794 void usb_info(Monitor *mon)
2798 const char *speed_str;
2801 monitor_printf(mon, "USB support not enabled\n");
2805 for (port = used_usb_ports; port; port = port->next) {
2809 switch(dev->speed) {
2813 case USB_SPEED_FULL:
2816 case USB_SPEED_HIGH:
2823 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2824 0, dev->addr, speed_str, dev->devname);
2828 /***********************************************************/
2829 /* PCMCIA/Cardbus */
2831 static struct pcmcia_socket_entry_s {
2832 struct pcmcia_socket_s *socket;
2833 struct pcmcia_socket_entry_s *next;
2834 } *pcmcia_sockets = 0;
2836 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2838 struct pcmcia_socket_entry_s *entry;
2840 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2841 entry->socket = socket;
2842 entry->next = pcmcia_sockets;
2843 pcmcia_sockets = entry;
2846 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2848 struct pcmcia_socket_entry_s *entry, **ptr;
2850 ptr = &pcmcia_sockets;
2851 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2852 if (entry->socket == socket) {
2858 void pcmcia_info(Monitor *mon)
2860 struct pcmcia_socket_entry_s *iter;
2862 if (!pcmcia_sockets)
2863 monitor_printf(mon, "No PCMCIA sockets\n");
2865 for (iter = pcmcia_sockets; iter; iter = iter->next)
2866 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2867 iter->socket->attached ? iter->socket->card_string :
2871 /***********************************************************/
2872 /* register display */
2874 void register_displaystate(DisplayState *ds)
2884 DisplayState *get_displaystate(void)
2886 return display_state;
2891 static void dumb_display_init(void)
2893 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2894 ds->surface = qemu_create_displaysurface(640, 480, 32, 640 * 4);
2895 register_displaystate(ds);
2898 /***********************************************************/
2901 #define MAX_IO_HANDLERS 64
2903 typedef struct IOHandlerRecord {
2905 IOCanRWHandler *fd_read_poll;
2907 IOHandler *fd_write;
2910 /* temporary data */
2912 struct IOHandlerRecord *next;
2915 static IOHandlerRecord *first_io_handler;
2917 /* XXX: fd_read_poll should be suppressed, but an API change is
2918 necessary in the character devices to suppress fd_can_read(). */
2919 int qemu_set_fd_handler2(int fd,
2920 IOCanRWHandler *fd_read_poll,
2922 IOHandler *fd_write,
2925 IOHandlerRecord **pioh, *ioh;
2927 if (!fd_read && !fd_write) {
2928 pioh = &first_io_handler;
2933 if (ioh->fd == fd) {
2940 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2944 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2945 ioh->next = first_io_handler;
2946 first_io_handler = ioh;
2949 ioh->fd_read_poll = fd_read_poll;
2950 ioh->fd_read = fd_read;
2951 ioh->fd_write = fd_write;
2952 ioh->opaque = opaque;
2958 int qemu_set_fd_handler(int fd,
2960 IOHandler *fd_write,
2963 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2967 /***********************************************************/
2968 /* Polling handling */
2970 typedef struct PollingEntry {
2973 struct PollingEntry *next;
2976 static PollingEntry *first_polling_entry;
2978 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2980 PollingEntry **ppe, *pe;
2981 pe = qemu_mallocz(sizeof(PollingEntry));
2983 pe->opaque = opaque;
2984 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2989 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2991 PollingEntry **ppe, *pe;
2992 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2994 if (pe->func == func && pe->opaque == opaque) {
3002 /***********************************************************/
3003 /* Wait objects support */
3004 typedef struct WaitObjects {
3006 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3007 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3008 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3011 static WaitObjects wait_objects = {0};
3013 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3015 WaitObjects *w = &wait_objects;
3017 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3019 w->events[w->num] = handle;
3020 w->func[w->num] = func;
3021 w->opaque[w->num] = opaque;
3026 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3029 WaitObjects *w = &wait_objects;
3032 for (i = 0; i < w->num; i++) {
3033 if (w->events[i] == handle)
3036 w->events[i] = w->events[i + 1];
3037 w->func[i] = w->func[i + 1];
3038 w->opaque[i] = w->opaque[i + 1];
3046 /***********************************************************/
3047 /* ram save/restore */
3049 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3053 v = qemu_get_byte(f);
3056 if (qemu_get_buffer(f, buf, len) != len)
3060 v = qemu_get_byte(f);
3061 memset(buf, v, len);
3067 if (qemu_file_has_error(f))
3073 static int ram_load_v1(QEMUFile *f, void *opaque)
3078 if (qemu_get_be32(f) != phys_ram_size)
3080 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3081 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3088 #define BDRV_HASH_BLOCK_SIZE 1024
3089 #define IOBUF_SIZE 4096
3090 #define RAM_CBLOCK_MAGIC 0xfabe
3092 typedef struct RamDecompressState {
3095 uint8_t buf[IOBUF_SIZE];
3096 } RamDecompressState;
3098 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3101 memset(s, 0, sizeof(*s));
3103 ret = inflateInit(&s->zstream);
3109 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3113 s->zstream.avail_out = len;
3114 s->zstream.next_out = buf;
3115 while (s->zstream.avail_out > 0) {
3116 if (s->zstream.avail_in == 0) {
3117 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3119 clen = qemu_get_be16(s->f);
3120 if (clen > IOBUF_SIZE)
3122 qemu_get_buffer(s->f, s->buf, clen);
3123 s->zstream.avail_in = clen;
3124 s->zstream.next_in = s->buf;
3126 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3127 if (ret != Z_OK && ret != Z_STREAM_END) {
3134 static void ram_decompress_close(RamDecompressState *s)
3136 inflateEnd(&s->zstream);
3139 #define RAM_SAVE_FLAG_FULL 0x01
3140 #define RAM_SAVE_FLAG_COMPRESS 0x02
3141 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3142 #define RAM_SAVE_FLAG_PAGE 0x08
3143 #define RAM_SAVE_FLAG_EOS 0x10
3145 static int is_dup_page(uint8_t *page, uint8_t ch)
3147 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3148 uint32_t *array = (uint32_t *)page;
3151 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3152 if (array[i] != val)
3159 static int ram_save_block(QEMUFile *f)
3161 static ram_addr_t current_addr = 0;
3162 ram_addr_t saved_addr = current_addr;
3163 ram_addr_t addr = 0;
3166 while (addr < phys_ram_size) {
3167 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3170 cpu_physical_memory_reset_dirty(current_addr,
3171 current_addr + TARGET_PAGE_SIZE,
3172 MIGRATION_DIRTY_FLAG);
3174 ch = *(phys_ram_base + current_addr);
3176 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3177 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3178 qemu_put_byte(f, ch);
3180 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3181 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3187 addr += TARGET_PAGE_SIZE;
3188 current_addr = (saved_addr + addr) % phys_ram_size;
3194 static ram_addr_t ram_save_threshold = 10;
3196 static ram_addr_t ram_save_remaining(void)
3199 ram_addr_t count = 0;
3201 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3202 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3209 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3214 /* Make sure all dirty bits are set */
3215 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3216 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3217 cpu_physical_memory_set_dirty(addr);
3220 /* Enable dirty memory tracking */
3221 cpu_physical_memory_set_dirty_tracking(1);
3223 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3226 while (!qemu_file_rate_limit(f)) {
3229 ret = ram_save_block(f);
3230 if (ret == 0) /* no more blocks */
3234 /* try transferring iterative blocks of memory */
3237 cpu_physical_memory_set_dirty_tracking(0);
3239 /* flush all remaining blocks regardless of rate limiting */
3240 while (ram_save_block(f) != 0);
3243 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3245 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3248 static int ram_load_dead(QEMUFile *f, void *opaque)
3250 RamDecompressState s1, *s = &s1;
3254 if (ram_decompress_open(s, f) < 0)
3256 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3257 if (ram_decompress_buf(s, buf, 1) < 0) {
3258 fprintf(stderr, "Error while reading ram block header\n");
3262 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3263 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3268 printf("Error block header\n");
3272 ram_decompress_close(s);
3277 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3282 if (version_id == 1)
3283 return ram_load_v1(f, opaque);
3285 if (version_id == 2) {
3286 if (qemu_get_be32(f) != phys_ram_size)
3288 return ram_load_dead(f, opaque);
3291 if (version_id != 3)
3295 addr = qemu_get_be64(f);
3297 flags = addr & ~TARGET_PAGE_MASK;
3298 addr &= TARGET_PAGE_MASK;
3300 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3301 if (addr != phys_ram_size)
3305 if (flags & RAM_SAVE_FLAG_FULL) {
3306 if (ram_load_dead(f, opaque) < 0)
3310 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3311 uint8_t ch = qemu_get_byte(f);
3312 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3313 } else if (flags & RAM_SAVE_FLAG_PAGE)
3314 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3315 } while (!(flags & RAM_SAVE_FLAG_EOS));
3320 void qemu_service_io(void)
3322 CPUState *env = cpu_single_env;
3324 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3326 if (env->kqemu_enabled) {
3327 kqemu_cpu_interrupt(env);
3333 /***********************************************************/
3334 /* bottom halves (can be seen as timers which expire ASAP) */
3345 static QEMUBH *first_bh = NULL;
3347 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3350 bh = qemu_mallocz(sizeof(QEMUBH));
3352 bh->opaque = opaque;
3353 bh->next = first_bh;
3358 int qemu_bh_poll(void)
3364 for (bh = first_bh; bh; bh = bh->next) {
3365 if (!bh->deleted && bh->scheduled) {
3374 /* remove deleted bhs */
3388 void qemu_bh_schedule_idle(QEMUBH *bh)
3396 void qemu_bh_schedule(QEMUBH *bh)
3398 CPUState *env = cpu_single_env;
3403 /* stop the currently executing CPU to execute the BH ASAP */
3405 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3409 void qemu_bh_cancel(QEMUBH *bh)
3414 void qemu_bh_delete(QEMUBH *bh)
3420 static void qemu_bh_update_timeout(int *timeout)
3424 for (bh = first_bh; bh; bh = bh->next) {
3425 if (!bh->deleted && bh->scheduled) {
3427 /* idle bottom halves will be polled at least
3429 *timeout = MIN(10, *timeout);
3431 /* non-idle bottom halves will be executed
3440 /***********************************************************/
3441 /* machine registration */
3443 static QEMUMachine *first_machine = NULL;
3444 QEMUMachine *current_machine = NULL;
3446 int qemu_register_machine(QEMUMachine *m)
3449 pm = &first_machine;
3457 static QEMUMachine *find_machine(const char *name)
3461 for(m = first_machine; m != NULL; m = m->next) {
3462 if (!strcmp(m->name, name))
3468 /***********************************************************/
3469 /* main execution loop */
3471 static void gui_update(void *opaque)
3473 uint64_t interval = GUI_REFRESH_INTERVAL;
3474 DisplayState *ds = opaque;
3475 DisplayChangeListener *dcl = ds->listeners;
3479 while (dcl != NULL) {
3480 if (dcl->gui_timer_interval &&
3481 dcl->gui_timer_interval < interval)
3482 interval = dcl->gui_timer_interval;
3485 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3488 static void nographic_update(void *opaque)
3490 uint64_t interval = GUI_REFRESH_INTERVAL;
3492 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3495 struct vm_change_state_entry {
3496 VMChangeStateHandler *cb;
3498 LIST_ENTRY (vm_change_state_entry) entries;
3501 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3503 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3506 VMChangeStateEntry *e;
3508 e = qemu_mallocz(sizeof (*e));
3512 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3516 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3518 LIST_REMOVE (e, entries);
3522 static void vm_state_notify(int running, int reason)
3524 VMChangeStateEntry *e;
3526 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3527 e->cb(e->opaque, running, reason);
3536 vm_state_notify(1, 0);
3537 qemu_rearm_alarm_timer(alarm_timer);
3541 void vm_stop(int reason)
3544 cpu_disable_ticks();
3546 vm_state_notify(0, reason);
3550 /* reset/shutdown handler */
3552 typedef struct QEMUResetEntry {
3553 QEMUResetHandler *func;
3555 struct QEMUResetEntry *next;
3558 static QEMUResetEntry *first_reset_entry;
3559 static int reset_requested;
3560 static int shutdown_requested;
3561 static int powerdown_requested;
3563 int qemu_shutdown_requested(void)
3565 int r = shutdown_requested;
3566 shutdown_requested = 0;
3570 int qemu_reset_requested(void)
3572 int r = reset_requested;
3573 reset_requested = 0;
3577 int qemu_powerdown_requested(void)
3579 int r = powerdown_requested;
3580 powerdown_requested = 0;
3584 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3586 QEMUResetEntry **pre, *re;
3588 pre = &first_reset_entry;
3589 while (*pre != NULL)
3590 pre = &(*pre)->next;
3591 re = qemu_mallocz(sizeof(QEMUResetEntry));
3593 re->opaque = opaque;
3598 void qemu_system_reset(void)
3602 /* reset all devices */
3603 for(re = first_reset_entry; re != NULL; re = re->next) {
3604 re->func(re->opaque);
3608 void qemu_system_reset_request(void)
3611 shutdown_requested = 1;
3613 reset_requested = 1;
3616 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3619 void qemu_system_shutdown_request(void)
3621 shutdown_requested = 1;
3623 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3626 void qemu_system_powerdown_request(void)
3628 powerdown_requested = 1;
3630 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3634 static void host_main_loop_wait(int *timeout)
3640 /* XXX: need to suppress polling by better using win32 events */
3642 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3643 ret |= pe->func(pe->opaque);
3647 WaitObjects *w = &wait_objects;
3649 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3650 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3651 if (w->func[ret - WAIT_OBJECT_0])
3652 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3654 /* Check for additional signaled events */
3655 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3657 /* Check if event is signaled */
3658 ret2 = WaitForSingleObject(w->events[i], 0);
3659 if(ret2 == WAIT_OBJECT_0) {
3661 w->func[i](w->opaque[i]);
3662 } else if (ret2 == WAIT_TIMEOUT) {
3664 err = GetLastError();
3665 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3668 } else if (ret == WAIT_TIMEOUT) {
3670 err = GetLastError();
3671 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3678 static void host_main_loop_wait(int *timeout)
3683 void main_loop_wait(int timeout)
3685 IOHandlerRecord *ioh;
3686 fd_set rfds, wfds, xfds;
3690 qemu_bh_update_timeout(&timeout);
3692 host_main_loop_wait(&timeout);
3694 /* poll any events */
3695 /* XXX: separate device handlers from system ones */
3700 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3704 (!ioh->fd_read_poll ||
3705 ioh->fd_read_poll(ioh->opaque) != 0)) {
3706 FD_SET(ioh->fd, &rfds);
3710 if (ioh->fd_write) {
3711 FD_SET(ioh->fd, &wfds);
3717 tv.tv_sec = timeout / 1000;
3718 tv.tv_usec = (timeout % 1000) * 1000;
3720 #if defined(CONFIG_SLIRP)
3721 if (slirp_is_inited()) {
3722 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3725 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3727 IOHandlerRecord **pioh;
3729 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3730 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3731 ioh->fd_read(ioh->opaque);
3733 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3734 ioh->fd_write(ioh->opaque);
3738 /* remove deleted IO handlers */
3739 pioh = &first_io_handler;
3749 #if defined(CONFIG_SLIRP)
3750 if (slirp_is_inited()) {
3756 slirp_select_poll(&rfds, &wfds, &xfds);
3760 /* vm time timers */
3761 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3762 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3763 qemu_get_clock(vm_clock));
3765 /* real time timers */
3766 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3767 qemu_get_clock(rt_clock));
3769 /* Check bottom-halves last in case any of the earlier events triggered
3775 static int main_loop(void)
3778 #ifdef CONFIG_PROFILER
3783 cur_cpu = first_cpu;
3784 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3791 #ifdef CONFIG_PROFILER
3792 ti = profile_getclock();
3797 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3798 env->icount_decr.u16.low = 0;
3799 env->icount_extra = 0;
3800 count = qemu_next_deadline();
3801 count = (count + (1 << icount_time_shift) - 1)
3802 >> icount_time_shift;
3803 qemu_icount += count;
3804 decr = (count > 0xffff) ? 0xffff : count;
3806 env->icount_decr.u16.low = decr;
3807 env->icount_extra = count;
3809 ret = cpu_exec(env);
3810 #ifdef CONFIG_PROFILER
3811 qemu_time += profile_getclock() - ti;
3814 /* Fold pending instructions back into the
3815 instruction counter, and clear the interrupt flag. */
3816 qemu_icount -= (env->icount_decr.u16.low
3817 + env->icount_extra);
3818 env->icount_decr.u32 = 0;
3819 env->icount_extra = 0;
3821 next_cpu = env->next_cpu ?: first_cpu;
3822 if (event_pending && likely(ret != EXCP_DEBUG)) {
3823 ret = EXCP_INTERRUPT;
3827 if (ret == EXCP_HLT) {
3828 /* Give the next CPU a chance to run. */
3832 if (ret != EXCP_HALTED)
3834 /* all CPUs are halted ? */
3840 if (shutdown_requested) {
3841 ret = EXCP_INTERRUPT;
3849 if (reset_requested) {
3850 reset_requested = 0;
3851 qemu_system_reset();
3852 ret = EXCP_INTERRUPT;
3854 if (powerdown_requested) {
3855 powerdown_requested = 0;
3856 qemu_system_powerdown();
3857 ret = EXCP_INTERRUPT;
3859 if (unlikely(ret == EXCP_DEBUG)) {
3860 gdb_set_stop_cpu(cur_cpu);
3861 vm_stop(EXCP_DEBUG);
3863 /* If all cpus are halted then wait until the next IRQ */
3864 /* XXX: use timeout computed from timers */
3865 if (ret == EXCP_HALTED) {
3869 /* Advance virtual time to the next event. */
3870 if (use_icount == 1) {
3871 /* When not using an adaptive execution frequency
3872 we tend to get badly out of sync with real time,
3873 so just delay for a reasonable amount of time. */
3876 delta = cpu_get_icount() - cpu_get_clock();
3879 /* If virtual time is ahead of real time then just
3881 timeout = (delta / 1000000) + 1;
3883 /* Wait for either IO to occur or the next
3885 add = qemu_next_deadline();
3886 /* We advance the timer before checking for IO.
3887 Limit the amount we advance so that early IO
3888 activity won't get the guest too far ahead. */
3892 add = (add + (1 << icount_time_shift) - 1)
3893 >> icount_time_shift;
3895 timeout = delta / 1000000;
3906 if (shutdown_requested) {
3907 ret = EXCP_INTERRUPT;
3912 #ifdef CONFIG_PROFILER
3913 ti = profile_getclock();
3915 main_loop_wait(timeout);
3916 #ifdef CONFIG_PROFILER
3917 dev_time += profile_getclock() - ti;
3920 cpu_disable_ticks();
3924 static void help(int exitcode)
3926 /* Please keep in synch with QEMU_OPTION_ enums, qemu_options[]
3927 and qemu-doc.texi */
3928 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3929 "usage: %s [options] [disk_image]\n"
3931 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3933 "Standard options:\n"
3934 "-h or -help display this help and exit\n"
3935 "-M machine select emulated machine (-M ? for list)\n"
3936 "-cpu cpu select CPU (-cpu ? for list)\n"
3937 "-smp n set the number of CPUs to 'n' [default=1]\n"
3938 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3939 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3940 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3941 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3942 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3943 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3944 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
3945 " use 'file' as a drive image\n"
3946 "-mtdblock file use 'file' as on-board Flash memory image\n"
3947 "-sd file use 'file' as SecureDigital card image\n"
3948 "-pflash file use 'file' as a parallel flash image\n"
3949 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3950 "-snapshot write to temporary files instead of disk image files\n"
3951 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3953 "-k language use keyboard layout (for example \"fr\" for French)\n"
3956 "-audio-help print list of audio drivers and their options\n"
3957 "-soundhw c1,... enable audio support\n"
3958 " and only specified sound cards (comma separated list)\n"
3959 " use -soundhw ? to get the list of supported cards\n"
3960 " use -soundhw all to enable all of them\n"
3962 "-usb enable the USB driver (will be the default soon)\n"
3963 "-usbdevice name add the host or guest USB device 'name'\n"
3964 "-name string set the name of the guest\n"
3965 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x\n"
3966 " specify machine UUID\n"
3968 "Display options:\n"
3969 "-nographic disable graphical output and redirect serial I/Os to console\n"
3970 #ifdef CONFIG_CURSES
3971 "-curses use a curses/ncurses interface instead of SDL\n"
3974 "-no-frame open SDL window without a frame and window decorations\n"
3975 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3976 "-no-quit disable SDL window close capability\n"
3979 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3980 "-vga [std|cirrus|vmware|none]\n"
3981 " select video card type\n"
3982 "-full-screen start in full screen\n"
3983 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3984 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3986 "-vnc display start a VNC server on display\n"
3988 "Network options:\n"
3989 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
3990 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3992 "-net user[,vlan=n][,name=str][,hostname=host]\n"
3993 " connect the user mode network stack to VLAN 'n' and send\n"
3994 " hostname 'host' to DHCP clients\n"
3997 "-net tap[,vlan=n][,name=str],ifname=name\n"
3998 " connect the host TAP network interface to VLAN 'n'\n"
4000 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4001 " connect the host TAP network interface to VLAN 'n' and use the\n"
4002 " network scripts 'file' (default=%s)\n"
4003 " and 'dfile' (default=%s);\n"
4004 " use '[down]script=no' to disable script execution;\n"
4005 " use 'fd=h' to connect to an already opened TAP interface\n"
4007 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4008 " connect the vlan 'n' to another VLAN using a socket connection\n"
4009 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
4010 " connect the vlan 'n' to multicast maddr and port\n"
4012 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4013 " connect the vlan 'n' to port 'n' of a vde switch running\n"
4014 " on host and listening for incoming connections on 'socketpath'.\n"
4015 " Use group 'groupname' and mode 'octalmode' to change default\n"
4016 " ownership and permissions for communication port.\n"
4018 "-net none use it alone to have zero network devices; if no -net option\n"
4019 " is provided, the default is '-net nic -net user'\n"
4021 "-tftp dir allow tftp access to files in dir [-net user]\n"
4022 "-bootp file advertise file in BOOTP replies\n"
4024 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4026 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4027 " redirect TCP or UDP connections from host to guest [-net user]\n"
4030 "-bt hci,null dumb bluetooth HCI - doesn't respond to commands\n"
4031 "-bt hci,host[:id]\n"
4032 " use host's HCI with the given name\n"
4033 "-bt hci[,vlan=n]\n"
4034 " emulate a standard HCI in virtual scatternet 'n'\n"
4035 "-bt vhci[,vlan=n]\n"
4036 " add host computer to virtual scatternet 'n' using VHCI\n"
4037 "-bt device:dev[,vlan=n]\n"
4038 " emulate a bluetooth device 'dev' in scatternet 'n'\n"
4042 "i386 target only:\n"
4043 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4044 "-rtc-td-hack use it to fix time drift in Windows ACPI HAL\n"
4045 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4046 "-no-acpi disable ACPI\n"
4047 "-no-hpet disable HPET\n"
4048 "-acpitable [sig=str][,rev=n][,oem_id=str][,oem_table_id=str][,oem_rev=n][,asl_compiler_id=str][,asl_compiler_rev=n][,data=file1[:file2]...]\n"
4049 " ACPI table description\n"
4051 "Linux boot specific:\n"
4052 "-kernel bzImage use 'bzImage' as kernel image\n"
4053 "-append cmdline use 'cmdline' as kernel command line\n"
4054 "-initrd file use 'file' as initial ram disk\n"
4056 "Debug/Expert options:\n"
4057 "-serial dev redirect the serial port to char device 'dev'\n"
4058 "-parallel dev redirect the parallel port to char device 'dev'\n"
4059 "-monitor dev redirect the monitor to char device 'dev'\n"
4060 "-pidfile file write PID to 'file'\n"
4061 "-S freeze CPU at startup (use 'c' to start execution)\n"
4062 "-s wait gdb connection to port\n"
4063 "-p port set gdb connection port [default=%s]\n"
4064 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4065 "-hdachs c,h,s[,t]\n"
4066 " force hard disk 0 physical geometry and the optional BIOS\n"
4067 " translation (t=none or lba) (usually qemu can guess them)\n"
4068 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4069 "-bios file set the filename for the BIOS\n"
4071 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4072 "-no-kqemu disable KQEMU kernel module usage\n"
4075 "-enable-kvm enable KVM full virtualization support\n"
4077 "-no-reboot exit instead of rebooting\n"
4078 "-no-shutdown stop before shutdown\n"
4079 "-loadvm [tag|id]\n"
4080 " start right away with a saved state (loadvm in monitor)\n"
4082 "-daemonize daemonize QEMU after initializing\n"
4084 "-option-rom rom load a file, rom, into the option ROM space\n"
4085 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4086 "-prom-env variable=value\n"
4087 " set OpenBIOS nvram variables\n"
4089 "-clock force the use of the given methods for timer alarm.\n"
4090 " To see what timers are available use -clock ?\n"
4091 "-localtime set the real time clock to local time [default=utc]\n"
4092 "-startdate select initial date of the clock\n"
4093 "-icount [N|auto]\n"
4094 " enable virtual instruction counter with 2^N clock ticks per instruction\n"
4095 "-echr chr set terminal escape character instead of ctrl-a\n"
4096 "-virtioconsole c\n"
4097 " set virtio console\n"
4098 "-show-cursor show cursor\n"
4099 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4100 "-semihosting semihosting mode\n"
4102 #if defined(TARGET_ARM)
4103 "-old-param old param mode\n"
4105 "-tb-size n set TB size\n"
4106 "-incoming p prepare for incoming migration, listen on port p\n"
4108 "-chroot dir Chroot to dir just before starting the VM.\n"
4109 "-runas user Change to user id user just before starting the VM.\n"
4112 "During emulation, the following keys are useful:\n"
4113 "ctrl-alt-f toggle full screen\n"
4114 "ctrl-alt-n switch to virtual console 'n'\n"
4115 "ctrl-alt toggle mouse and keyboard grab\n"
4117 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4122 DEFAULT_NETWORK_SCRIPT,
4123 DEFAULT_NETWORK_DOWN_SCRIPT,
4125 DEFAULT_GDBSTUB_PORT,
4130 #define HAS_ARG 0x0001
4133 /* Please keep in synch with help, qemu_options[] and
4135 /* Standard options: */
4148 QEMU_OPTION_mtdblock,
4152 QEMU_OPTION_snapshot,
4155 QEMU_OPTION_audio_help,
4156 QEMU_OPTION_soundhw,
4158 QEMU_OPTION_usbdevice,
4162 /* Display options: */
4163 QEMU_OPTION_nographic,
4165 QEMU_OPTION_no_frame,
4166 QEMU_OPTION_alt_grab,
4167 QEMU_OPTION_no_quit,
4169 QEMU_OPTION_portrait,
4171 QEMU_OPTION_full_screen,
4175 /* Network options: */
4183 /* i386 target only: */
4184 QEMU_OPTION_win2k_hack,
4185 QEMU_OPTION_rtc_td_hack,
4186 QEMU_OPTION_no_fd_bootchk,
4187 QEMU_OPTION_no_acpi,
4188 QEMU_OPTION_no_hpet,
4189 QEMU_OPTION_acpitable,
4191 /* Linux boot specific: */
4196 /* Debug/Expert options: */
4198 QEMU_OPTION_parallel,
4199 QEMU_OPTION_monitor,
4200 QEMU_OPTION_pidfile,
4208 QEMU_OPTION_kernel_kqemu,
4209 QEMU_OPTION_no_kqemu,
4210 QEMU_OPTION_enable_kvm,
4211 QEMU_OPTION_no_reboot,
4212 QEMU_OPTION_no_shutdown,
4214 QEMU_OPTION_daemonize,
4215 QEMU_OPTION_option_rom,
4216 QEMU_OPTION_prom_env,
4218 QEMU_OPTION_localtime,
4219 QEMU_OPTION_startdate,
4222 QEMU_OPTION_virtiocon,
4223 QEMU_OPTION_show_cursor,
4224 QEMU_OPTION_semihosting,
4225 QEMU_OPTION_old_param,
4226 QEMU_OPTION_tb_size,
4227 QEMU_OPTION_incoming,
4232 typedef struct QEMUOption {
4238 static const QEMUOption qemu_options[] = {
4239 /* Please keep in synch with help, QEMU_OPTION_ enums, and
4241 /* Standard options: */
4242 { "h", 0, QEMU_OPTION_h },
4243 { "help", 0, QEMU_OPTION_h },
4244 { "M", HAS_ARG, QEMU_OPTION_M },
4245 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4246 { "smp", HAS_ARG, QEMU_OPTION_smp },
4247 { "fda", HAS_ARG, QEMU_OPTION_fda },
4248 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4249 { "hda", HAS_ARG, QEMU_OPTION_hda },
4250 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4251 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4252 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4253 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4254 { "drive", HAS_ARG, QEMU_OPTION_drive },
4255 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4256 { "sd", HAS_ARG, QEMU_OPTION_sd },
4257 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4258 { "boot", HAS_ARG, QEMU_OPTION_boot },
4259 { "snapshot", 0, QEMU_OPTION_snapshot },
4260 { "m", HAS_ARG, QEMU_OPTION_m },
4262 { "k", HAS_ARG, QEMU_OPTION_k },
4265 { "audio-help", 0, QEMU_OPTION_audio_help },
4266 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4268 { "usb", 0, QEMU_OPTION_usb },
4269 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4270 { "name", HAS_ARG, QEMU_OPTION_name },
4271 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4273 /* Display options: */
4274 { "nographic", 0, QEMU_OPTION_nographic },
4275 #ifdef CONFIG_CURSES
4276 { "curses", 0, QEMU_OPTION_curses },
4279 { "no-frame", 0, QEMU_OPTION_no_frame },
4280 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4281 { "no-quit", 0, QEMU_OPTION_no_quit },
4282 { "sdl", 0, QEMU_OPTION_sdl },
4284 { "portrait", 0, QEMU_OPTION_portrait },
4285 { "vga", HAS_ARG, QEMU_OPTION_vga },
4286 { "full-screen", 0, QEMU_OPTION_full_screen },
4287 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4288 { "g", 1, QEMU_OPTION_g },
4290 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4292 /* Network options: */
4293 { "net", HAS_ARG, QEMU_OPTION_net},
4295 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4296 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4298 { "smb", HAS_ARG, QEMU_OPTION_smb },
4300 { "redir", HAS_ARG, QEMU_OPTION_redir },
4302 { "bt", HAS_ARG, QEMU_OPTION_bt },
4304 /* i386 target only: */
4305 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4306 { "rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack },
4307 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4308 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4309 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4310 { "acpitable", HAS_ARG, QEMU_OPTION_acpitable },
4313 /* Linux boot specific: */
4314 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4315 { "append", HAS_ARG, QEMU_OPTION_append },
4316 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4318 /* Debug/Expert options: */
4319 { "serial", HAS_ARG, QEMU_OPTION_serial },
4320 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4321 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4322 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4323 { "S", 0, QEMU_OPTION_S },
4324 { "s", 0, QEMU_OPTION_s },
4325 { "p", HAS_ARG, QEMU_OPTION_p },
4326 { "d", HAS_ARG, QEMU_OPTION_d },
4327 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4328 { "L", HAS_ARG, QEMU_OPTION_L },
4329 { "bios", HAS_ARG, QEMU_OPTION_bios },
4331 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4332 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4335 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4337 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4338 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4339 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4340 { "daemonize", 0, QEMU_OPTION_daemonize },
4341 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4342 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4343 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4345 { "clock", HAS_ARG, QEMU_OPTION_clock },
4346 { "localtime", 0, QEMU_OPTION_localtime },
4347 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4348 { "icount", HAS_ARG, QEMU_OPTION_icount },
4349 { "echr", HAS_ARG, QEMU_OPTION_echr },
4350 { "virtioconsole", HAS_ARG, QEMU_OPTION_virtiocon },
4351 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4352 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4353 { "semihosting", 0, QEMU_OPTION_semihosting },
4355 #if defined(TARGET_ARM)
4356 { "old-param", 0, QEMU_OPTION_old_param },
4358 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4359 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4360 { "chroot", HAS_ARG, QEMU_OPTION_chroot },
4361 { "runas", HAS_ARG, QEMU_OPTION_runas },
4366 struct soundhw soundhw[] = {
4367 #ifdef HAS_AUDIO_CHOICE
4368 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4374 { .init_isa = pcspk_audio_init }
4381 "Creative Sound Blaster 16",
4384 { .init_isa = SB16_init }
4388 #ifdef CONFIG_CS4231A
4394 { .init_isa = cs4231a_init }
4402 "Yamaha YMF262 (OPL3)",
4404 "Yamaha YM3812 (OPL2)",
4408 { .init_isa = Adlib_init }
4415 "Gravis Ultrasound GF1",
4418 { .init_isa = GUS_init }
4425 "Intel 82801AA AC97 Audio",
4428 { .init_pci = ac97_init }
4432 #ifdef CONFIG_ES1370
4435 "ENSONIQ AudioPCI ES1370",
4438 { .init_pci = es1370_init }
4442 #endif /* HAS_AUDIO_CHOICE */
4444 { NULL, NULL, 0, 0, { NULL } }
4447 static void select_soundhw (const char *optarg)
4451 if (*optarg == '?') {
4454 printf ("Valid sound card names (comma separated):\n");
4455 for (c = soundhw; c->name; ++c) {
4456 printf ("%-11s %s\n", c->name, c->descr);
4458 printf ("\n-soundhw all will enable all of the above\n");
4459 exit (*optarg != '?');
4467 if (!strcmp (optarg, "all")) {
4468 for (c = soundhw; c->name; ++c) {
4476 e = strchr (p, ',');
4477 l = !e ? strlen (p) : (size_t) (e - p);
4479 for (c = soundhw; c->name; ++c) {
4480 if (!strncmp (c->name, p, l)) {
4489 "Unknown sound card name (too big to show)\n");
4492 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4497 p += l + (e != NULL);
4501 goto show_valid_cards;
4506 static void select_vgahw (const char *p)
4510 if (strstart(p, "std", &opts)) {
4511 std_vga_enabled = 1;
4512 cirrus_vga_enabled = 0;
4514 } else if (strstart(p, "cirrus", &opts)) {
4515 cirrus_vga_enabled = 1;
4516 std_vga_enabled = 0;
4518 } else if (strstart(p, "vmware", &opts)) {
4519 cirrus_vga_enabled = 0;
4520 std_vga_enabled = 0;
4522 } else if (strstart(p, "none", &opts)) {
4523 cirrus_vga_enabled = 0;
4524 std_vga_enabled = 0;
4528 fprintf(stderr, "Unknown vga type: %s\n", p);
4532 const char *nextopt;
4534 if (strstart(opts, ",retrace=", &nextopt)) {
4536 if (strstart(opts, "dumb", &nextopt))
4537 vga_retrace_method = VGA_RETRACE_DUMB;
4538 else if (strstart(opts, "precise", &nextopt))
4539 vga_retrace_method = VGA_RETRACE_PRECISE;
4540 else goto invalid_vga;
4541 } else goto invalid_vga;
4547 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4549 exit(STATUS_CONTROL_C_EXIT);
4554 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4558 if(strlen(str) != 36)
4561 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4562 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4563 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4571 #define MAX_NET_CLIENTS 32
4575 static void termsig_handler(int signal)
4577 qemu_system_shutdown_request();
4580 static void termsig_setup(void)
4582 struct sigaction act;
4584 memset(&act, 0, sizeof(act));
4585 act.sa_handler = termsig_handler;
4586 sigaction(SIGINT, &act, NULL);
4587 sigaction(SIGHUP, &act, NULL);
4588 sigaction(SIGTERM, &act, NULL);
4593 int main(int argc, char **argv, char **envp)
4595 #ifdef CONFIG_GDBSTUB
4597 const char *gdbstub_port;
4599 uint32_t boot_devices_bitmap = 0;
4601 int snapshot, linux_boot, net_boot;
4602 const char *initrd_filename;
4603 const char *kernel_filename, *kernel_cmdline;
4604 const char *boot_devices = "";
4606 DisplayChangeListener *dcl;
4607 int cyls, heads, secs, translation;
4608 const char *net_clients[MAX_NET_CLIENTS];
4610 const char *bt_opts[MAX_BT_CMDLINE];
4614 const char *r, *optarg;
4615 CharDriverState *monitor_hd = NULL;
4616 const char *monitor_device;
4617 const char *serial_devices[MAX_SERIAL_PORTS];
4618 int serial_device_index;
4619 const char *parallel_devices[MAX_PARALLEL_PORTS];
4620 int parallel_device_index;
4621 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4622 int virtio_console_index;
4623 const char *loadvm = NULL;
4624 QEMUMachine *machine;
4625 const char *cpu_model;
4626 const char *usb_devices[MAX_USB_CMDLINE];
4627 int usb_devices_index;
4630 const char *pid_file = NULL;
4631 const char *incoming = NULL;
4633 struct passwd *pwd = NULL;
4634 const char *chroot_dir = NULL;
4635 const char *run_as = NULL;
4637 qemu_cache_utils_init(envp);
4639 LIST_INIT (&vm_change_state_head);
4642 struct sigaction act;
4643 sigfillset(&act.sa_mask);
4645 act.sa_handler = SIG_IGN;
4646 sigaction(SIGPIPE, &act, NULL);
4649 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4650 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4651 QEMU to run on a single CPU */
4656 h = GetCurrentProcess();
4657 if (GetProcessAffinityMask(h, &mask, &smask)) {
4658 for(i = 0; i < 32; i++) {
4659 if (mask & (1 << i))
4664 SetProcessAffinityMask(h, mask);
4670 register_machines();
4671 machine = first_machine;
4673 initrd_filename = NULL;
4675 vga_ram_size = VGA_RAM_SIZE;
4676 #ifdef CONFIG_GDBSTUB
4678 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4683 kernel_filename = NULL;
4684 kernel_cmdline = "";
4685 cyls = heads = secs = 0;
4686 translation = BIOS_ATA_TRANSLATION_AUTO;
4687 monitor_device = "vc:80Cx24C";
4689 serial_devices[0] = "vc:80Cx24C";
4690 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4691 serial_devices[i] = NULL;
4692 serial_device_index = 0;
4694 parallel_devices[0] = "vc:80Cx24C";
4695 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4696 parallel_devices[i] = NULL;
4697 parallel_device_index = 0;
4699 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4700 virtio_consoles[i] = NULL;
4701 virtio_console_index = 0;
4703 usb_devices_index = 0;
4722 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4724 const QEMUOption *popt;
4727 /* Treat --foo the same as -foo. */
4730 popt = qemu_options;
4733 fprintf(stderr, "%s: invalid option -- '%s'\n",
4737 if (!strcmp(popt->name, r + 1))
4741 if (popt->flags & HAS_ARG) {
4742 if (optind >= argc) {
4743 fprintf(stderr, "%s: option '%s' requires an argument\n",
4747 optarg = argv[optind++];
4752 switch(popt->index) {
4754 machine = find_machine(optarg);
4757 printf("Supported machines are:\n");
4758 for(m = first_machine; m != NULL; m = m->next) {
4759 printf("%-10s %s%s\n",
4761 m == first_machine ? " (default)" : "");
4763 exit(*optarg != '?');
4766 case QEMU_OPTION_cpu:
4767 /* hw initialization will check this */
4768 if (*optarg == '?') {
4769 /* XXX: implement xxx_cpu_list for targets that still miss it */
4770 #if defined(cpu_list)
4771 cpu_list(stdout, &fprintf);
4778 case QEMU_OPTION_initrd:
4779 initrd_filename = optarg;
4781 case QEMU_OPTION_hda:
4783 hda_index = drive_add(optarg, HD_ALIAS, 0);
4785 hda_index = drive_add(optarg, HD_ALIAS
4786 ",cyls=%d,heads=%d,secs=%d%s",
4787 0, cyls, heads, secs,
4788 translation == BIOS_ATA_TRANSLATION_LBA ?
4790 translation == BIOS_ATA_TRANSLATION_NONE ?
4791 ",trans=none" : "");
4793 case QEMU_OPTION_hdb:
4794 case QEMU_OPTION_hdc:
4795 case QEMU_OPTION_hdd:
4796 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4798 case QEMU_OPTION_drive:
4799 drive_add(NULL, "%s", optarg);
4801 case QEMU_OPTION_mtdblock:
4802 drive_add(optarg, MTD_ALIAS);
4804 case QEMU_OPTION_sd:
4805 drive_add(optarg, SD_ALIAS);
4807 case QEMU_OPTION_pflash:
4808 drive_add(optarg, PFLASH_ALIAS);
4810 case QEMU_OPTION_snapshot:
4813 case QEMU_OPTION_hdachs:
4817 cyls = strtol(p, (char **)&p, 0);
4818 if (cyls < 1 || cyls > 16383)
4823 heads = strtol(p, (char **)&p, 0);
4824 if (heads < 1 || heads > 16)
4829 secs = strtol(p, (char **)&p, 0);
4830 if (secs < 1 || secs > 63)
4834 if (!strcmp(p, "none"))
4835 translation = BIOS_ATA_TRANSLATION_NONE;
4836 else if (!strcmp(p, "lba"))
4837 translation = BIOS_ATA_TRANSLATION_LBA;
4838 else if (!strcmp(p, "auto"))
4839 translation = BIOS_ATA_TRANSLATION_AUTO;
4842 } else if (*p != '\0') {
4844 fprintf(stderr, "qemu: invalid physical CHS format\n");
4847 if (hda_index != -1)
4848 snprintf(drives_opt[hda_index].opt,
4849 sizeof(drives_opt[hda_index].opt),
4850 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4851 0, cyls, heads, secs,
4852 translation == BIOS_ATA_TRANSLATION_LBA ?
4854 translation == BIOS_ATA_TRANSLATION_NONE ?
4855 ",trans=none" : "");
4858 case QEMU_OPTION_nographic:
4861 #ifdef CONFIG_CURSES
4862 case QEMU_OPTION_curses:
4866 case QEMU_OPTION_portrait:
4869 case QEMU_OPTION_kernel:
4870 kernel_filename = optarg;
4872 case QEMU_OPTION_append:
4873 kernel_cmdline = optarg;
4875 case QEMU_OPTION_cdrom:
4876 drive_add(optarg, CDROM_ALIAS);
4878 case QEMU_OPTION_boot:
4879 boot_devices = optarg;
4880 /* We just do some generic consistency checks */
4882 /* Could easily be extended to 64 devices if needed */
4885 boot_devices_bitmap = 0;
4886 for (p = boot_devices; *p != '\0'; p++) {
4887 /* Allowed boot devices are:
4888 * a b : floppy disk drives
4889 * c ... f : IDE disk drives
4890 * g ... m : machine implementation dependant drives
4891 * n ... p : network devices
4892 * It's up to each machine implementation to check
4893 * if the given boot devices match the actual hardware
4894 * implementation and firmware features.
4896 if (*p < 'a' || *p > 'q') {
4897 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4900 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4902 "Boot device '%c' was given twice\n",*p);
4905 boot_devices_bitmap |= 1 << (*p - 'a');
4909 case QEMU_OPTION_fda:
4910 case QEMU_OPTION_fdb:
4911 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4914 case QEMU_OPTION_no_fd_bootchk:
4918 case QEMU_OPTION_net:
4919 if (nb_net_clients >= MAX_NET_CLIENTS) {
4920 fprintf(stderr, "qemu: too many network clients\n");
4923 net_clients[nb_net_clients] = optarg;
4927 case QEMU_OPTION_tftp:
4928 tftp_prefix = optarg;
4930 case QEMU_OPTION_bootp:
4931 bootp_filename = optarg;
4934 case QEMU_OPTION_smb:
4935 net_slirp_smb(optarg);
4938 case QEMU_OPTION_redir:
4939 net_slirp_redir(optarg);
4942 case QEMU_OPTION_bt:
4943 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4944 fprintf(stderr, "qemu: too many bluetooth options\n");
4947 bt_opts[nb_bt_opts++] = optarg;
4950 case QEMU_OPTION_audio_help:
4954 case QEMU_OPTION_soundhw:
4955 select_soundhw (optarg);
4961 case QEMU_OPTION_m: {
4965 value = strtoul(optarg, &ptr, 10);
4967 case 0: case 'M': case 'm':
4974 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4978 /* On 32-bit hosts, QEMU is limited by virtual address space */
4979 if (value > (2047 << 20)
4981 && HOST_LONG_BITS == 32
4984 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4987 if (value != (uint64_t)(ram_addr_t)value) {
4988 fprintf(stderr, "qemu: ram size too large\n");
4997 const CPULogItem *item;
4999 mask = cpu_str_to_log_mask(optarg);
5001 printf("Log items (comma separated):\n");
5002 for(item = cpu_log_items; item->mask != 0; item++) {
5003 printf("%-10s %s\n", item->name, item->help);
5010 #ifdef CONFIG_GDBSTUB
5015 gdbstub_port = optarg;
5021 case QEMU_OPTION_bios:
5028 keyboard_layout = optarg;
5030 case QEMU_OPTION_localtime:
5033 case QEMU_OPTION_vga:
5034 select_vgahw (optarg);
5041 w = strtol(p, (char **)&p, 10);
5044 fprintf(stderr, "qemu: invalid resolution or depth\n");
5050 h = strtol(p, (char **)&p, 10);
5055 depth = strtol(p, (char **)&p, 10);
5056 if (depth != 8 && depth != 15 && depth != 16 &&
5057 depth != 24 && depth != 32)
5059 } else if (*p == '\0') {
5060 depth = graphic_depth;
5067 graphic_depth = depth;
5070 case QEMU_OPTION_echr:
5073 term_escape_char = strtol(optarg, &r, 0);
5075 printf("Bad argument to echr\n");
5078 case QEMU_OPTION_monitor:
5079 monitor_device = optarg;
5081 case QEMU_OPTION_serial:
5082 if (serial_device_index >= MAX_SERIAL_PORTS) {
5083 fprintf(stderr, "qemu: too many serial ports\n");
5086 serial_devices[serial_device_index] = optarg;
5087 serial_device_index++;
5089 case QEMU_OPTION_virtiocon:
5090 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5091 fprintf(stderr, "qemu: too many virtio consoles\n");
5094 virtio_consoles[virtio_console_index] = optarg;
5095 virtio_console_index++;
5097 case QEMU_OPTION_parallel:
5098 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5099 fprintf(stderr, "qemu: too many parallel ports\n");
5102 parallel_devices[parallel_device_index] = optarg;
5103 parallel_device_index++;
5105 case QEMU_OPTION_loadvm:
5108 case QEMU_OPTION_full_screen:
5112 case QEMU_OPTION_no_frame:
5115 case QEMU_OPTION_alt_grab:
5118 case QEMU_OPTION_no_quit:
5121 case QEMU_OPTION_sdl:
5125 case QEMU_OPTION_pidfile:
5129 case QEMU_OPTION_win2k_hack:
5130 win2k_install_hack = 1;
5132 case QEMU_OPTION_rtc_td_hack:
5135 case QEMU_OPTION_acpitable:
5136 if(acpi_table_add(optarg) < 0) {
5137 fprintf(stderr, "Wrong acpi table provided\n");
5143 case QEMU_OPTION_no_kqemu:
5146 case QEMU_OPTION_kernel_kqemu:
5151 case QEMU_OPTION_enable_kvm:
5158 case QEMU_OPTION_usb:
5161 case QEMU_OPTION_usbdevice:
5163 if (usb_devices_index >= MAX_USB_CMDLINE) {
5164 fprintf(stderr, "Too many USB devices\n");
5167 usb_devices[usb_devices_index] = optarg;
5168 usb_devices_index++;
5170 case QEMU_OPTION_smp:
5171 smp_cpus = atoi(optarg);
5173 fprintf(stderr, "Invalid number of CPUs\n");
5177 case QEMU_OPTION_vnc:
5178 vnc_display = optarg;
5180 case QEMU_OPTION_no_acpi:
5183 case QEMU_OPTION_no_hpet:
5186 case QEMU_OPTION_no_reboot:
5189 case QEMU_OPTION_no_shutdown:
5192 case QEMU_OPTION_show_cursor:
5195 case QEMU_OPTION_uuid:
5196 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5197 fprintf(stderr, "Fail to parse UUID string."
5198 " Wrong format.\n");
5202 case QEMU_OPTION_daemonize:
5205 case QEMU_OPTION_option_rom:
5206 if (nb_option_roms >= MAX_OPTION_ROMS) {
5207 fprintf(stderr, "Too many option ROMs\n");
5210 option_rom[nb_option_roms] = optarg;
5213 case QEMU_OPTION_semihosting:
5214 semihosting_enabled = 1;
5216 case QEMU_OPTION_name:
5219 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5220 case QEMU_OPTION_prom_env:
5221 if (nb_prom_envs >= MAX_PROM_ENVS) {
5222 fprintf(stderr, "Too many prom variables\n");
5225 prom_envs[nb_prom_envs] = optarg;
5230 case QEMU_OPTION_old_param:
5234 case QEMU_OPTION_clock:
5235 configure_alarms(optarg);
5237 case QEMU_OPTION_startdate:
5240 time_t rtc_start_date;
5241 if (!strcmp(optarg, "now")) {
5242 rtc_date_offset = -1;
5244 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5252 } else if (sscanf(optarg, "%d-%d-%d",
5255 &tm.tm_mday) == 3) {
5264 rtc_start_date = mktimegm(&tm);
5265 if (rtc_start_date == -1) {
5267 fprintf(stderr, "Invalid date format. Valid format are:\n"
5268 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5271 rtc_date_offset = time(NULL) - rtc_start_date;
5275 case QEMU_OPTION_tb_size:
5276 tb_size = strtol(optarg, NULL, 0);
5280 case QEMU_OPTION_icount:
5282 if (strcmp(optarg, "auto") == 0) {
5283 icount_time_shift = -1;
5285 icount_time_shift = strtol(optarg, NULL, 0);
5288 case QEMU_OPTION_incoming:
5291 case QEMU_OPTION_chroot:
5292 chroot_dir = optarg;
5294 case QEMU_OPTION_runas:
5301 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5302 if (kvm_allowed && kqemu_allowed) {
5304 "You can not enable both KVM and kqemu at the same time\n");
5309 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5310 if (smp_cpus > machine->max_cpus) {
5311 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5312 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5318 if (serial_device_index == 0)
5319 serial_devices[0] = "stdio";
5320 if (parallel_device_index == 0)
5321 parallel_devices[0] = "null";
5322 if (strncmp(monitor_device, "vc", 2) == 0)
5323 monitor_device = "stdio";
5330 if (pipe(fds) == -1)
5341 len = read(fds[0], &status, 1);
5342 if (len == -1 && (errno == EINTR))
5347 else if (status == 1) {
5348 fprintf(stderr, "Could not acquire pidfile\n");
5365 signal(SIGTSTP, SIG_IGN);
5366 signal(SIGTTOU, SIG_IGN);
5367 signal(SIGTTIN, SIG_IGN);
5371 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5374 write(fds[1], &status, 1);
5376 fprintf(stderr, "Could not acquire pid file\n");
5384 linux_boot = (kernel_filename != NULL);
5385 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5387 if (!linux_boot && net_boot == 0 &&
5388 !machine->nodisk_ok && nb_drives_opt == 0)
5391 if (!linux_boot && *kernel_cmdline != '\0') {
5392 fprintf(stderr, "-append only allowed with -kernel option\n");
5396 if (!linux_boot && initrd_filename != NULL) {
5397 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5401 /* boot to floppy or the default cd if no hard disk defined yet */
5402 if (!boot_devices[0]) {
5403 boot_devices = "cad";
5405 setvbuf(stdout, NULL, _IOLBF, 0);
5408 if (init_timer_alarm() < 0) {
5409 fprintf(stderr, "could not initialize alarm timer\n");
5412 if (use_icount && icount_time_shift < 0) {
5414 /* 125MIPS seems a reasonable initial guess at the guest speed.
5415 It will be corrected fairly quickly anyway. */
5416 icount_time_shift = 3;
5417 init_icount_adjust();
5424 /* init network clients */
5425 if (nb_net_clients == 0) {
5426 /* if no clients, we use a default config */
5427 net_clients[nb_net_clients++] = "nic";
5429 net_clients[nb_net_clients++] = "user";
5433 for(i = 0;i < nb_net_clients; i++) {
5434 if (net_client_parse(net_clients[i]) < 0)
5440 /* XXX: this should be moved in the PC machine instantiation code */
5441 if (net_boot != 0) {
5443 for (i = 0; i < nb_nics && i < 4; i++) {
5444 const char *model = nd_table[i].model;
5446 if (net_boot & (1 << i)) {
5449 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5450 if (get_image_size(buf) > 0) {
5451 if (nb_option_roms >= MAX_OPTION_ROMS) {
5452 fprintf(stderr, "Too many option ROMs\n");
5455 option_rom[nb_option_roms] = strdup(buf);
5462 fprintf(stderr, "No valid PXE rom found for network device\n");
5468 /* init the bluetooth world */
5469 for (i = 0; i < nb_bt_opts; i++)
5470 if (bt_parse(bt_opts[i]))
5473 /* init the memory */
5474 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5476 if (machine->ram_require & RAMSIZE_FIXED) {
5478 if (ram_size < phys_ram_size) {
5479 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5480 machine->name, (unsigned long long) phys_ram_size);
5484 phys_ram_size = ram_size;
5486 ram_size = phys_ram_size;
5489 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5491 phys_ram_size += ram_size;
5494 phys_ram_base = qemu_vmalloc(phys_ram_size);
5495 if (!phys_ram_base) {
5496 fprintf(stderr, "Could not allocate physical memory\n");
5500 /* init the dynamic translator */
5501 cpu_exec_init_all(tb_size * 1024 * 1024);
5505 /* we always create the cdrom drive, even if no disk is there */
5507 if (nb_drives_opt < MAX_DRIVES)
5508 drive_add(NULL, CDROM_ALIAS);
5510 /* we always create at least one floppy */
5512 if (nb_drives_opt < MAX_DRIVES)
5513 drive_add(NULL, FD_ALIAS, 0);
5515 /* we always create one sd slot, even if no card is in it */
5517 if (nb_drives_opt < MAX_DRIVES)
5518 drive_add(NULL, SD_ALIAS);
5520 /* open the virtual block devices */
5522 for(i = 0; i < nb_drives_opt; i++)
5523 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5526 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5527 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5530 /* must be after terminal init, SDL library changes signal handlers */
5534 /* Maintain compatibility with multiple stdio monitors */
5535 if (!strcmp(monitor_device,"stdio")) {
5536 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5537 const char *devname = serial_devices[i];
5538 if (devname && !strcmp(devname,"mon:stdio")) {
5539 monitor_device = NULL;
5541 } else if (devname && !strcmp(devname,"stdio")) {
5542 monitor_device = NULL;
5543 serial_devices[i] = "mon:stdio";
5549 if (kvm_enabled()) {
5552 ret = kvm_init(smp_cpus);
5554 fprintf(stderr, "failed to initialize KVM\n");
5559 if (monitor_device) {
5560 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5562 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5567 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5568 const char *devname = serial_devices[i];
5569 if (devname && strcmp(devname, "none")) {
5571 snprintf(label, sizeof(label), "serial%d", i);
5572 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5573 if (!serial_hds[i]) {
5574 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5581 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5582 const char *devname = parallel_devices[i];
5583 if (devname && strcmp(devname, "none")) {
5585 snprintf(label, sizeof(label), "parallel%d", i);
5586 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5587 if (!parallel_hds[i]) {
5588 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5595 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5596 const char *devname = virtio_consoles[i];
5597 if (devname && strcmp(devname, "none")) {
5599 snprintf(label, sizeof(label), "virtcon%d", i);
5600 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5601 if (!virtcon_hds[i]) {
5602 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5609 machine->init(ram_size, vga_ram_size, boot_devices,
5610 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5612 current_machine = machine;
5614 /* Set KVM's vcpu state to qemu's initial CPUState. */
5615 if (kvm_enabled()) {
5618 ret = kvm_sync_vcpus();
5620 fprintf(stderr, "failed to initialize vcpus\n");
5625 /* init USB devices */
5627 for(i = 0; i < usb_devices_index; i++) {
5628 if (usb_device_add(usb_devices[i], 0) < 0) {
5629 fprintf(stderr, "Warning: could not add USB device %s\n",
5636 dumb_display_init();
5637 /* just use the first displaystate for the moment */
5642 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5646 #if defined(CONFIG_CURSES)
5648 /* At the moment curses cannot be used with other displays */
5649 curses_display_init(ds, full_screen);
5653 if (vnc_display != NULL) {
5654 vnc_display_init(ds);
5655 if (vnc_display_open(ds, vnc_display) < 0)
5658 #if defined(CONFIG_SDL)
5659 if (sdl || !vnc_display)
5660 sdl_display_init(ds, full_screen, no_frame);
5661 #elif defined(CONFIG_COCOA)
5662 if (sdl || !vnc_display)
5663 cocoa_display_init(ds, full_screen);
5669 dcl = ds->listeners;
5670 while (dcl != NULL) {
5671 if (dcl->dpy_refresh != NULL) {
5672 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5673 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5678 if (nographic || (vnc_display && !sdl)) {
5679 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5680 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5683 text_consoles_set_display(display_state);
5684 qemu_chr_initial_reset();
5686 if (monitor_device && monitor_hd)
5687 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
5689 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5690 const char *devname = serial_devices[i];
5691 if (devname && strcmp(devname, "none")) {
5693 snprintf(label, sizeof(label), "serial%d", i);
5694 if (strstart(devname, "vc", 0))
5695 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5699 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5700 const char *devname = parallel_devices[i];
5701 if (devname && strcmp(devname, "none")) {
5703 snprintf(label, sizeof(label), "parallel%d", i);
5704 if (strstart(devname, "vc", 0))
5705 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5709 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5710 const char *devname = virtio_consoles[i];
5711 if (virtcon_hds[i] && devname) {
5713 snprintf(label, sizeof(label), "virtcon%d", i);
5714 if (strstart(devname, "vc", 0))
5715 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5719 #ifdef CONFIG_GDBSTUB
5721 /* XXX: use standard host:port notation and modify options
5723 if (gdbserver_start(gdbstub_port) < 0) {
5724 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5732 do_loadvm(cur_mon, loadvm);
5735 autostart = 0; /* fixme how to deal with -daemonize */
5736 qemu_start_incoming_migration(incoming);
5747 len = write(fds[1], &status, 1);
5748 if (len == -1 && (errno == EINTR))
5755 TFR(fd = open("/dev/null", O_RDWR));
5762 pwd = getpwnam(run_as);
5764 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5770 if (chroot(chroot_dir) < 0) {
5771 fprintf(stderr, "chroot failed\n");
5778 if (setgid(pwd->pw_gid) < 0) {
5779 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5782 if (setuid(pwd->pw_uid) < 0) {
5783 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5786 if (setuid(0) != -1) {
5787 fprintf(stderr, "Dropping privileges failed\n");