4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "hw/boards.h"
27 #include "hw/pcmcia.h"
29 #include "hw/audiodev.h"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
39 #include "cache-utils.h"
41 #include "audio/audio.h"
42 #include "migration.h"
55 #include <sys/times.h>
59 #include <sys/ioctl.h>
60 #include <sys/resource.h>
61 #include <sys/socket.h>
62 #include <netinet/in.h>
64 #if defined(__NetBSD__)
65 #include <net/if_tap.h>
68 #include <linux/if_tun.h>
70 #include <arpa/inet.h>
73 #include <sys/select.h>
81 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
82 #include <freebsd/stdlib.h>
87 #include <linux/rtc.h>
89 /* For the benefit of older linux systems which don't supply it,
90 we use a local copy of hpet.h. */
91 /* #include <linux/hpet.h> */
94 #include <linux/ppdev.h>
95 #include <linux/parport.h>
99 #include <sys/ethernet.h>
100 #include <sys/sockio.h>
101 #include <netinet/arp.h>
102 #include <netinet/in.h>
103 #include <netinet/in_systm.h>
104 #include <netinet/ip.h>
105 #include <netinet/ip_icmp.h> // must come after ip.h
106 #include <netinet/udp.h>
107 #include <netinet/tcp.h>
115 #include "qemu_socket.h"
117 #if defined(CONFIG_SLIRP)
118 #include "libslirp.h"
121 #if defined(__OpenBSD__)
125 #if defined(CONFIG_VDE)
126 #include <libvdeplug.h>
131 #include <sys/timeb.h>
132 #include <mmsystem.h>
133 #define getopt_long_only getopt_long
134 #define memalign(align, size) malloc(size)
140 int qemu_main(int argc, char **argv, char **envp);
141 int main(int argc, char **argv)
143 qemu_main(argc, argv, NULL);
146 #define main qemu_main
148 #endif /* CONFIG_SDL */
152 #define main qemu_main
153 #endif /* CONFIG_COCOA */
157 #include "exec-all.h"
159 //#define DEBUG_UNUSED_IOPORT
160 //#define DEBUG_IOPORT
162 //#define DEBUG_SLIRP
166 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
168 # define LOG_IOPORT(...) do { } while (0)
171 #define DEFAULT_RAM_SIZE 128
173 /* Max number of USB devices that can be specified on the commandline. */
174 #define MAX_USB_CMDLINE 8
176 /* Max number of bluetooth switches on the commandline. */
177 #define MAX_BT_CMDLINE 10
179 /* XXX: use a two level table to limit memory usage */
180 #define MAX_IOPORTS 65536
182 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
183 const char *bios_name = NULL;
184 static void *ioport_opaque[MAX_IOPORTS];
185 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
186 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
187 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
188 to store the VM snapshots */
189 DriveInfo drives_table[MAX_DRIVES+1];
191 static int vga_ram_size;
192 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
193 static DisplayState *display_state;
197 const char* keyboard_layout = NULL;
198 int64_t ticks_per_sec;
201 NICInfo nd_table[MAX_NICS];
203 static int rtc_utc = 1;
204 static int rtc_date_offset = -1; /* -1 means no change */
205 int cirrus_vga_enabled = 1;
206 int std_vga_enabled = 0;
207 int vmsvga_enabled = 0;
209 int graphic_width = 1024;
210 int graphic_height = 768;
211 int graphic_depth = 8;
213 int graphic_width = 800;
214 int graphic_height = 600;
215 int graphic_depth = 15;
217 static int full_screen = 0;
219 static int no_frame = 0;
222 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
223 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
224 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
226 int win2k_install_hack = 0;
231 const char *vnc_display;
232 int acpi_enabled = 1;
238 int graphic_rotate = 0;
240 const char *option_rom[MAX_OPTION_ROMS];
242 int semihosting_enabled = 0;
246 const char *qemu_name;
248 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
249 unsigned int nb_prom_envs = 0;
250 const char *prom_envs[MAX_PROM_ENVS];
253 struct drive_opt drives_opt[MAX_DRIVES];
255 static CPUState *cur_cpu;
256 static CPUState *next_cpu;
257 static int event_pending = 1;
258 /* Conversion factor from emulated instructions to virtual clock ticks. */
259 static int icount_time_shift;
260 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
261 #define MAX_ICOUNT_SHIFT 10
262 /* Compensate for varying guest execution speed. */
263 static int64_t qemu_icount_bias;
264 static QEMUTimer *icount_rt_timer;
265 static QEMUTimer *icount_vm_timer;
266 static QEMUTimer *nographic_timer;
268 uint8_t qemu_uuid[16];
270 /***********************************************************/
271 /* x86 ISA bus support */
273 target_phys_addr_t isa_mem_base = 0;
276 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
277 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
279 static uint32_t ioport_read(int index, uint32_t address)
281 static IOPortReadFunc *default_func[3] = {
282 default_ioport_readb,
283 default_ioport_readw,
286 IOPortReadFunc *func = ioport_read_table[index][address];
288 func = default_func[index];
289 return func(ioport_opaque[address], address);
292 static void ioport_write(int index, uint32_t address, uint32_t data)
294 static IOPortWriteFunc *default_func[3] = {
295 default_ioport_writeb,
296 default_ioport_writew,
297 default_ioport_writel
299 IOPortWriteFunc *func = ioport_write_table[index][address];
301 func = default_func[index];
302 func(ioport_opaque[address], address, data);
305 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
307 #ifdef DEBUG_UNUSED_IOPORT
308 fprintf(stderr, "unused inb: port=0x%04x\n", address);
313 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
315 #ifdef DEBUG_UNUSED_IOPORT
316 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
320 /* default is to make two byte accesses */
321 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
324 data = ioport_read(0, address);
325 address = (address + 1) & (MAX_IOPORTS - 1);
326 data |= ioport_read(0, address) << 8;
330 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
332 ioport_write(0, address, data & 0xff);
333 address = (address + 1) & (MAX_IOPORTS - 1);
334 ioport_write(0, address, (data >> 8) & 0xff);
337 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
339 #ifdef DEBUG_UNUSED_IOPORT
340 fprintf(stderr, "unused inl: port=0x%04x\n", address);
345 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
347 #ifdef DEBUG_UNUSED_IOPORT
348 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
352 /* size is the word size in byte */
353 int register_ioport_read(int start, int length, int size,
354 IOPortReadFunc *func, void *opaque)
360 } else if (size == 2) {
362 } else if (size == 4) {
365 hw_error("register_ioport_read: invalid size");
368 for(i = start; i < start + length; i += size) {
369 ioport_read_table[bsize][i] = func;
370 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
371 hw_error("register_ioport_read: invalid opaque");
372 ioport_opaque[i] = opaque;
377 /* size is the word size in byte */
378 int register_ioport_write(int start, int length, int size,
379 IOPortWriteFunc *func, void *opaque)
385 } else if (size == 2) {
387 } else if (size == 4) {
390 hw_error("register_ioport_write: invalid size");
393 for(i = start; i < start + length; i += size) {
394 ioport_write_table[bsize][i] = func;
395 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
396 hw_error("register_ioport_write: invalid opaque");
397 ioport_opaque[i] = opaque;
402 void isa_unassign_ioport(int start, int length)
406 for(i = start; i < start + length; i++) {
407 ioport_read_table[0][i] = default_ioport_readb;
408 ioport_read_table[1][i] = default_ioport_readw;
409 ioport_read_table[2][i] = default_ioport_readl;
411 ioport_write_table[0][i] = default_ioport_writeb;
412 ioport_write_table[1][i] = default_ioport_writew;
413 ioport_write_table[2][i] = default_ioport_writel;
415 ioport_opaque[i] = NULL;
419 /***********************************************************/
421 void cpu_outb(CPUState *env, int addr, int val)
423 LOG_IOPORT("outb: %04x %02x\n", addr, val);
424 ioport_write(0, addr, val);
427 env->last_io_time = cpu_get_time_fast();
431 void cpu_outw(CPUState *env, int addr, int val)
433 LOG_IOPORT("outw: %04x %04x\n", addr, val);
434 ioport_write(1, addr, val);
437 env->last_io_time = cpu_get_time_fast();
441 void cpu_outl(CPUState *env, int addr, int val)
443 LOG_IOPORT("outl: %04x %08x\n", addr, val);
444 ioport_write(2, addr, val);
447 env->last_io_time = cpu_get_time_fast();
451 int cpu_inb(CPUState *env, int addr)
454 val = ioport_read(0, addr);
455 LOG_IOPORT("inb : %04x %02x\n", addr, val);
458 env->last_io_time = cpu_get_time_fast();
463 int cpu_inw(CPUState *env, int addr)
466 val = ioport_read(1, addr);
467 LOG_IOPORT("inw : %04x %04x\n", addr, val);
470 env->last_io_time = cpu_get_time_fast();
475 int cpu_inl(CPUState *env, int addr)
478 val = ioport_read(2, addr);
479 LOG_IOPORT("inl : %04x %08x\n", addr, val);
482 env->last_io_time = cpu_get_time_fast();
487 /***********************************************************/
488 void hw_error(const char *fmt, ...)
494 fprintf(stderr, "qemu: hardware error: ");
495 vfprintf(stderr, fmt, ap);
496 fprintf(stderr, "\n");
497 for(env = first_cpu; env != NULL; env = env->next_cpu) {
498 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
500 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
502 cpu_dump_state(env, stderr, fprintf, 0);
512 static QEMUBalloonEvent *qemu_balloon_event;
513 void *qemu_balloon_event_opaque;
515 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
517 qemu_balloon_event = func;
518 qemu_balloon_event_opaque = opaque;
521 void qemu_balloon(ram_addr_t target)
523 if (qemu_balloon_event)
524 qemu_balloon_event(qemu_balloon_event_opaque, target);
527 ram_addr_t qemu_balloon_status(void)
529 if (qemu_balloon_event)
530 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
534 /***********************************************************/
537 static QEMUPutKBDEvent *qemu_put_kbd_event;
538 static void *qemu_put_kbd_event_opaque;
539 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
540 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
542 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
544 qemu_put_kbd_event_opaque = opaque;
545 qemu_put_kbd_event = func;
548 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
549 void *opaque, int absolute,
552 QEMUPutMouseEntry *s, *cursor;
554 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
556 s->qemu_put_mouse_event = func;
557 s->qemu_put_mouse_event_opaque = opaque;
558 s->qemu_put_mouse_event_absolute = absolute;
559 s->qemu_put_mouse_event_name = qemu_strdup(name);
562 if (!qemu_put_mouse_event_head) {
563 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
567 cursor = qemu_put_mouse_event_head;
568 while (cursor->next != NULL)
569 cursor = cursor->next;
572 qemu_put_mouse_event_current = s;
577 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
579 QEMUPutMouseEntry *prev = NULL, *cursor;
581 if (!qemu_put_mouse_event_head || entry == NULL)
584 cursor = qemu_put_mouse_event_head;
585 while (cursor != NULL && cursor != entry) {
587 cursor = cursor->next;
590 if (cursor == NULL) // does not exist or list empty
592 else if (prev == NULL) { // entry is head
593 qemu_put_mouse_event_head = cursor->next;
594 if (qemu_put_mouse_event_current == entry)
595 qemu_put_mouse_event_current = cursor->next;
596 qemu_free(entry->qemu_put_mouse_event_name);
601 prev->next = entry->next;
603 if (qemu_put_mouse_event_current == entry)
604 qemu_put_mouse_event_current = prev;
606 qemu_free(entry->qemu_put_mouse_event_name);
610 void kbd_put_keycode(int keycode)
612 if (qemu_put_kbd_event) {
613 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
617 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
619 QEMUPutMouseEvent *mouse_event;
620 void *mouse_event_opaque;
623 if (!qemu_put_mouse_event_current) {
628 qemu_put_mouse_event_current->qemu_put_mouse_event;
630 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
633 if (graphic_rotate) {
634 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
637 width = graphic_width - 1;
638 mouse_event(mouse_event_opaque,
639 width - dy, dx, dz, buttons_state);
641 mouse_event(mouse_event_opaque,
642 dx, dy, dz, buttons_state);
646 int kbd_mouse_is_absolute(void)
648 if (!qemu_put_mouse_event_current)
651 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
654 void do_info_mice(void)
656 QEMUPutMouseEntry *cursor;
659 if (!qemu_put_mouse_event_head) {
660 term_printf("No mouse devices connected\n");
664 term_printf("Mouse devices available:\n");
665 cursor = qemu_put_mouse_event_head;
666 while (cursor != NULL) {
667 term_printf("%c Mouse #%d: %s\n",
668 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
669 index, cursor->qemu_put_mouse_event_name);
671 cursor = cursor->next;
675 void do_mouse_set(int index)
677 QEMUPutMouseEntry *cursor;
680 if (!qemu_put_mouse_event_head) {
681 term_printf("No mouse devices connected\n");
685 cursor = qemu_put_mouse_event_head;
686 while (cursor != NULL && index != i) {
688 cursor = cursor->next;
692 qemu_put_mouse_event_current = cursor;
694 term_printf("Mouse at given index not found\n");
697 /* compute with 96 bit intermediate result: (a*b)/c */
698 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
703 #ifdef WORDS_BIGENDIAN
713 rl = (uint64_t)u.l.low * (uint64_t)b;
714 rh = (uint64_t)u.l.high * (uint64_t)b;
717 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
721 /***********************************************************/
722 /* real time host monotonic timer */
724 #define QEMU_TIMER_BASE 1000000000LL
728 static int64_t clock_freq;
730 static void init_get_clock(void)
734 ret = QueryPerformanceFrequency(&freq);
736 fprintf(stderr, "Could not calibrate ticks\n");
739 clock_freq = freq.QuadPart;
742 static int64_t get_clock(void)
745 QueryPerformanceCounter(&ti);
746 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
751 static int use_rt_clock;
753 static void init_get_clock(void)
756 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
759 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
766 static int64_t get_clock(void)
768 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
771 clock_gettime(CLOCK_MONOTONIC, &ts);
772 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
776 /* XXX: using gettimeofday leads to problems if the date
777 changes, so it should be avoided. */
779 gettimeofday(&tv, NULL);
780 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
785 /* Return the virtual CPU time, based on the instruction counter. */
786 static int64_t cpu_get_icount(void)
789 CPUState *env = cpu_single_env;;
790 icount = qemu_icount;
793 fprintf(stderr, "Bad clock read\n");
794 icount -= (env->icount_decr.u16.low + env->icount_extra);
796 return qemu_icount_bias + (icount << icount_time_shift);
799 /***********************************************************/
800 /* guest cycle counter */
802 static int64_t cpu_ticks_prev;
803 static int64_t cpu_ticks_offset;
804 static int64_t cpu_clock_offset;
805 static int cpu_ticks_enabled;
807 /* return the host CPU cycle counter and handle stop/restart */
808 int64_t cpu_get_ticks(void)
811 return cpu_get_icount();
813 if (!cpu_ticks_enabled) {
814 return cpu_ticks_offset;
817 ticks = cpu_get_real_ticks();
818 if (cpu_ticks_prev > ticks) {
819 /* Note: non increasing ticks may happen if the host uses
821 cpu_ticks_offset += cpu_ticks_prev - ticks;
823 cpu_ticks_prev = ticks;
824 return ticks + cpu_ticks_offset;
828 /* return the host CPU monotonic timer and handle stop/restart */
829 static int64_t cpu_get_clock(void)
832 if (!cpu_ticks_enabled) {
833 return cpu_clock_offset;
836 return ti + cpu_clock_offset;
840 /* enable cpu_get_ticks() */
841 void cpu_enable_ticks(void)
843 if (!cpu_ticks_enabled) {
844 cpu_ticks_offset -= cpu_get_real_ticks();
845 cpu_clock_offset -= get_clock();
846 cpu_ticks_enabled = 1;
850 /* disable cpu_get_ticks() : the clock is stopped. You must not call
851 cpu_get_ticks() after that. */
852 void cpu_disable_ticks(void)
854 if (cpu_ticks_enabled) {
855 cpu_ticks_offset = cpu_get_ticks();
856 cpu_clock_offset = cpu_get_clock();
857 cpu_ticks_enabled = 0;
861 /***********************************************************/
864 #define QEMU_TIMER_REALTIME 0
865 #define QEMU_TIMER_VIRTUAL 1
869 /* XXX: add frequency */
877 struct QEMUTimer *next;
880 struct qemu_alarm_timer {
884 int (*start)(struct qemu_alarm_timer *t);
885 void (*stop)(struct qemu_alarm_timer *t);
886 void (*rearm)(struct qemu_alarm_timer *t);
890 #define ALARM_FLAG_DYNTICKS 0x1
891 #define ALARM_FLAG_EXPIRED 0x2
893 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
895 return t->flags & ALARM_FLAG_DYNTICKS;
898 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
900 if (!alarm_has_dynticks(t))
906 /* TODO: MIN_TIMER_REARM_US should be optimized */
907 #define MIN_TIMER_REARM_US 250
909 static struct qemu_alarm_timer *alarm_timer;
911 static int alarm_timer_rfd, alarm_timer_wfd;
916 struct qemu_alarm_win32 {
920 } alarm_win32_data = {0, NULL, -1};
922 static int win32_start_timer(struct qemu_alarm_timer *t);
923 static void win32_stop_timer(struct qemu_alarm_timer *t);
924 static void win32_rearm_timer(struct qemu_alarm_timer *t);
928 static int unix_start_timer(struct qemu_alarm_timer *t);
929 static void unix_stop_timer(struct qemu_alarm_timer *t);
933 static int dynticks_start_timer(struct qemu_alarm_timer *t);
934 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
935 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
937 static int hpet_start_timer(struct qemu_alarm_timer *t);
938 static void hpet_stop_timer(struct qemu_alarm_timer *t);
940 static int rtc_start_timer(struct qemu_alarm_timer *t);
941 static void rtc_stop_timer(struct qemu_alarm_timer *t);
943 #endif /* __linux__ */
947 /* Correlation between real and virtual time is always going to be
948 fairly approximate, so ignore small variation.
949 When the guest is idle real and virtual time will be aligned in
951 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
953 static void icount_adjust(void)
958 static int64_t last_delta;
959 /* If the VM is not running, then do nothing. */
963 cur_time = cpu_get_clock();
964 cur_icount = qemu_get_clock(vm_clock);
965 delta = cur_icount - cur_time;
966 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
968 && last_delta + ICOUNT_WOBBLE < delta * 2
969 && icount_time_shift > 0) {
970 /* The guest is getting too far ahead. Slow time down. */
974 && last_delta - ICOUNT_WOBBLE > delta * 2
975 && icount_time_shift < MAX_ICOUNT_SHIFT) {
976 /* The guest is getting too far behind. Speed time up. */
980 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
983 static void icount_adjust_rt(void * opaque)
985 qemu_mod_timer(icount_rt_timer,
986 qemu_get_clock(rt_clock) + 1000);
990 static void icount_adjust_vm(void * opaque)
992 qemu_mod_timer(icount_vm_timer,
993 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
997 static void init_icount_adjust(void)
999 /* Have both realtime and virtual time triggers for speed adjustment.
1000 The realtime trigger catches emulated time passing too slowly,
1001 the virtual time trigger catches emulated time passing too fast.
1002 Realtime triggers occur even when idle, so use them less frequently
1003 than VM triggers. */
1004 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1005 qemu_mod_timer(icount_rt_timer,
1006 qemu_get_clock(rt_clock) + 1000);
1007 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1008 qemu_mod_timer(icount_vm_timer,
1009 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1012 static struct qemu_alarm_timer alarm_timers[] = {
1015 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1016 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1017 /* HPET - if available - is preferred */
1018 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1019 /* ...otherwise try RTC */
1020 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1022 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1024 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1025 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1026 {"win32", 0, win32_start_timer,
1027 win32_stop_timer, NULL, &alarm_win32_data},
1032 static void show_available_alarms(void)
1036 printf("Available alarm timers, in order of precedence:\n");
1037 for (i = 0; alarm_timers[i].name; i++)
1038 printf("%s\n", alarm_timers[i].name);
1041 static void configure_alarms(char const *opt)
1045 int count = ARRAY_SIZE(alarm_timers) - 1;
1048 struct qemu_alarm_timer tmp;
1050 if (!strcmp(opt, "?")) {
1051 show_available_alarms();
1057 /* Reorder the array */
1058 name = strtok(arg, ",");
1060 for (i = 0; i < count && alarm_timers[i].name; i++) {
1061 if (!strcmp(alarm_timers[i].name, name))
1066 fprintf(stderr, "Unknown clock %s\n", name);
1075 tmp = alarm_timers[i];
1076 alarm_timers[i] = alarm_timers[cur];
1077 alarm_timers[cur] = tmp;
1081 name = strtok(NULL, ",");
1087 /* Disable remaining timers */
1088 for (i = cur; i < count; i++)
1089 alarm_timers[i].name = NULL;
1091 show_available_alarms();
1096 QEMUClock *rt_clock;
1097 QEMUClock *vm_clock;
1099 static QEMUTimer *active_timers[2];
1101 static QEMUClock *qemu_new_clock(int type)
1104 clock = qemu_mallocz(sizeof(QEMUClock));
1109 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1113 ts = qemu_mallocz(sizeof(QEMUTimer));
1116 ts->opaque = opaque;
1120 void qemu_free_timer(QEMUTimer *ts)
1125 /* stop a timer, but do not dealloc it */
1126 void qemu_del_timer(QEMUTimer *ts)
1130 /* NOTE: this code must be signal safe because
1131 qemu_timer_expired() can be called from a signal. */
1132 pt = &active_timers[ts->clock->type];
1145 /* modify the current timer so that it will be fired when current_time
1146 >= expire_time. The corresponding callback will be called. */
1147 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1153 /* add the timer in the sorted list */
1154 /* NOTE: this code must be signal safe because
1155 qemu_timer_expired() can be called from a signal. */
1156 pt = &active_timers[ts->clock->type];
1161 if (t->expire_time > expire_time)
1165 ts->expire_time = expire_time;
1169 /* Rearm if necessary */
1170 if (pt == &active_timers[ts->clock->type]) {
1171 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1172 qemu_rearm_alarm_timer(alarm_timer);
1174 /* Interrupt execution to force deadline recalculation. */
1175 if (use_icount && cpu_single_env) {
1176 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1181 int qemu_timer_pending(QEMUTimer *ts)
1184 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1191 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1195 return (timer_head->expire_time <= current_time);
1198 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1204 if (!ts || ts->expire_time > current_time)
1206 /* remove timer from the list before calling the callback */
1207 *ptimer_head = ts->next;
1210 /* run the callback (the timer list can be modified) */
1215 int64_t qemu_get_clock(QEMUClock *clock)
1217 switch(clock->type) {
1218 case QEMU_TIMER_REALTIME:
1219 return get_clock() / 1000000;
1221 case QEMU_TIMER_VIRTUAL:
1223 return cpu_get_icount();
1225 return cpu_get_clock();
1230 static void init_timers(void)
1233 ticks_per_sec = QEMU_TIMER_BASE;
1234 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1235 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1239 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1241 uint64_t expire_time;
1243 if (qemu_timer_pending(ts)) {
1244 expire_time = ts->expire_time;
1248 qemu_put_be64(f, expire_time);
1251 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1253 uint64_t expire_time;
1255 expire_time = qemu_get_be64(f);
1256 if (expire_time != -1) {
1257 qemu_mod_timer(ts, expire_time);
1263 static void timer_save(QEMUFile *f, void *opaque)
1265 if (cpu_ticks_enabled) {
1266 hw_error("cannot save state if virtual timers are running");
1268 qemu_put_be64(f, cpu_ticks_offset);
1269 qemu_put_be64(f, ticks_per_sec);
1270 qemu_put_be64(f, cpu_clock_offset);
1273 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1275 if (version_id != 1 && version_id != 2)
1277 if (cpu_ticks_enabled) {
1280 cpu_ticks_offset=qemu_get_be64(f);
1281 ticks_per_sec=qemu_get_be64(f);
1282 if (version_id == 2) {
1283 cpu_clock_offset=qemu_get_be64(f);
1289 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1290 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1292 static void host_alarm_handler(int host_signum)
1296 #define DISP_FREQ 1000
1298 static int64_t delta_min = INT64_MAX;
1299 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1301 ti = qemu_get_clock(vm_clock);
1302 if (last_clock != 0) {
1303 delta = ti - last_clock;
1304 if (delta < delta_min)
1306 if (delta > delta_max)
1309 if (++count == DISP_FREQ) {
1310 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1311 muldiv64(delta_min, 1000000, ticks_per_sec),
1312 muldiv64(delta_max, 1000000, ticks_per_sec),
1313 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1314 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1316 delta_min = INT64_MAX;
1324 if (alarm_has_dynticks(alarm_timer) ||
1326 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1327 qemu_get_clock(vm_clock))) ||
1328 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1329 qemu_get_clock(rt_clock))) {
1330 CPUState *env = next_cpu;
1333 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1334 SetEvent(data->host_alarm);
1336 static const char byte = 0;
1337 write(alarm_timer_wfd, &byte, sizeof(byte));
1339 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1342 /* stop the currently executing cpu because a timer occured */
1343 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1345 if (env->kqemu_enabled) {
1346 kqemu_cpu_interrupt(env);
1354 static int64_t qemu_next_deadline(void)
1358 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1359 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1360 qemu_get_clock(vm_clock);
1362 /* To avoid problems with overflow limit this to 2^32. */
1372 #if defined(__linux__) || defined(_WIN32)
1373 static uint64_t qemu_next_deadline_dyntick(void)
1381 delta = (qemu_next_deadline() + 999) / 1000;
1383 if (active_timers[QEMU_TIMER_REALTIME]) {
1384 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1385 qemu_get_clock(rt_clock))*1000;
1386 if (rtdelta < delta)
1390 if (delta < MIN_TIMER_REARM_US)
1391 delta = MIN_TIMER_REARM_US;
1399 /* Sets a specific flag */
1400 static int fcntl_setfl(int fd, int flag)
1404 flags = fcntl(fd, F_GETFL);
1408 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1414 #if defined(__linux__)
1416 #define RTC_FREQ 1024
1418 static void enable_sigio_timer(int fd)
1420 struct sigaction act;
1423 sigfillset(&act.sa_mask);
1425 act.sa_handler = host_alarm_handler;
1427 sigaction(SIGIO, &act, NULL);
1428 fcntl_setfl(fd, O_ASYNC);
1429 fcntl(fd, F_SETOWN, getpid());
1432 static int hpet_start_timer(struct qemu_alarm_timer *t)
1434 struct hpet_info info;
1437 fd = open("/dev/hpet", O_RDONLY);
1442 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1444 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1445 "error, but for better emulation accuracy type:\n"
1446 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1450 /* Check capabilities */
1451 r = ioctl(fd, HPET_INFO, &info);
1455 /* Enable periodic mode */
1456 r = ioctl(fd, HPET_EPI, 0);
1457 if (info.hi_flags && (r < 0))
1460 /* Enable interrupt */
1461 r = ioctl(fd, HPET_IE_ON, 0);
1465 enable_sigio_timer(fd);
1466 t->priv = (void *)(long)fd;
1474 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1476 int fd = (long)t->priv;
1481 static int rtc_start_timer(struct qemu_alarm_timer *t)
1484 unsigned long current_rtc_freq = 0;
1486 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1489 ioctl(rtc_fd, RTC_IRQP_READ, ¤t_rtc_freq);
1490 if (current_rtc_freq != RTC_FREQ &&
1491 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1492 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1493 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1494 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1497 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1503 enable_sigio_timer(rtc_fd);
1505 t->priv = (void *)(long)rtc_fd;
1510 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1512 int rtc_fd = (long)t->priv;
1517 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1521 struct sigaction act;
1523 sigfillset(&act.sa_mask);
1525 act.sa_handler = host_alarm_handler;
1527 sigaction(SIGALRM, &act, NULL);
1529 ev.sigev_value.sival_int = 0;
1530 ev.sigev_notify = SIGEV_SIGNAL;
1531 ev.sigev_signo = SIGALRM;
1533 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1534 perror("timer_create");
1536 /* disable dynticks */
1537 fprintf(stderr, "Dynamic Ticks disabled\n");
1542 t->priv = (void *)(long)host_timer;
1547 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1549 timer_t host_timer = (timer_t)(long)t->priv;
1551 timer_delete(host_timer);
1554 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1556 timer_t host_timer = (timer_t)(long)t->priv;
1557 struct itimerspec timeout;
1558 int64_t nearest_delta_us = INT64_MAX;
1561 if (!active_timers[QEMU_TIMER_REALTIME] &&
1562 !active_timers[QEMU_TIMER_VIRTUAL])
1565 nearest_delta_us = qemu_next_deadline_dyntick();
1567 /* check whether a timer is already running */
1568 if (timer_gettime(host_timer, &timeout)) {
1570 fprintf(stderr, "Internal timer error: aborting\n");
1573 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1574 if (current_us && current_us <= nearest_delta_us)
1577 timeout.it_interval.tv_sec = 0;
1578 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1579 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1580 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1581 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1583 fprintf(stderr, "Internal timer error: aborting\n");
1588 #endif /* defined(__linux__) */
1590 static int unix_start_timer(struct qemu_alarm_timer *t)
1592 struct sigaction act;
1593 struct itimerval itv;
1597 sigfillset(&act.sa_mask);
1599 act.sa_handler = host_alarm_handler;
1601 sigaction(SIGALRM, &act, NULL);
1603 itv.it_interval.tv_sec = 0;
1604 /* for i386 kernel 2.6 to get 1 ms */
1605 itv.it_interval.tv_usec = 999;
1606 itv.it_value.tv_sec = 0;
1607 itv.it_value.tv_usec = 10 * 1000;
1609 err = setitimer(ITIMER_REAL, &itv, NULL);
1616 static void unix_stop_timer(struct qemu_alarm_timer *t)
1618 struct itimerval itv;
1620 memset(&itv, 0, sizeof(itv));
1621 setitimer(ITIMER_REAL, &itv, NULL);
1624 #endif /* !defined(_WIN32) */
1626 static void try_to_rearm_timer(void *opaque)
1628 struct qemu_alarm_timer *t = opaque;
1632 /* Drain the notify pipe */
1635 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1636 } while ((len == -1 && errno == EINTR) || len > 0);
1639 if (t->flags & ALARM_FLAG_EXPIRED) {
1640 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1641 qemu_rearm_alarm_timer(alarm_timer);
1647 static int win32_start_timer(struct qemu_alarm_timer *t)
1650 struct qemu_alarm_win32 *data = t->priv;
1653 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1654 if (!data->host_alarm) {
1655 perror("Failed CreateEvent");
1659 memset(&tc, 0, sizeof(tc));
1660 timeGetDevCaps(&tc, sizeof(tc));
1662 if (data->period < tc.wPeriodMin)
1663 data->period = tc.wPeriodMin;
1665 timeBeginPeriod(data->period);
1667 flags = TIME_CALLBACK_FUNCTION;
1668 if (alarm_has_dynticks(t))
1669 flags |= TIME_ONESHOT;
1671 flags |= TIME_PERIODIC;
1673 data->timerId = timeSetEvent(1, // interval (ms)
1674 data->period, // resolution
1675 host_alarm_handler, // function
1676 (DWORD)t, // parameter
1679 if (!data->timerId) {
1680 perror("Failed to initialize win32 alarm timer");
1682 timeEndPeriod(data->period);
1683 CloseHandle(data->host_alarm);
1687 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1692 static void win32_stop_timer(struct qemu_alarm_timer *t)
1694 struct qemu_alarm_win32 *data = t->priv;
1696 timeKillEvent(data->timerId);
1697 timeEndPeriod(data->period);
1699 CloseHandle(data->host_alarm);
1702 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1704 struct qemu_alarm_win32 *data = t->priv;
1705 uint64_t nearest_delta_us;
1707 if (!active_timers[QEMU_TIMER_REALTIME] &&
1708 !active_timers[QEMU_TIMER_VIRTUAL])
1711 nearest_delta_us = qemu_next_deadline_dyntick();
1712 nearest_delta_us /= 1000;
1714 timeKillEvent(data->timerId);
1716 data->timerId = timeSetEvent(1,
1720 TIME_ONESHOT | TIME_PERIODIC);
1722 if (!data->timerId) {
1723 perror("Failed to re-arm win32 alarm timer");
1725 timeEndPeriod(data->period);
1726 CloseHandle(data->host_alarm);
1733 static int init_timer_alarm(void)
1735 struct qemu_alarm_timer *t = NULL;
1745 err = fcntl_setfl(fds[0], O_NONBLOCK);
1749 err = fcntl_setfl(fds[1], O_NONBLOCK);
1753 alarm_timer_rfd = fds[0];
1754 alarm_timer_wfd = fds[1];
1757 for (i = 0; alarm_timers[i].name; i++) {
1758 t = &alarm_timers[i];
1771 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1772 try_to_rearm_timer, NULL, t);
1787 static void quit_timers(void)
1789 alarm_timer->stop(alarm_timer);
1793 /***********************************************************/
1794 /* host time/date access */
1795 void qemu_get_timedate(struct tm *tm, int offset)
1802 if (rtc_date_offset == -1) {
1806 ret = localtime(&ti);
1808 ti -= rtc_date_offset;
1812 memcpy(tm, ret, sizeof(struct tm));
1815 int qemu_timedate_diff(struct tm *tm)
1819 if (rtc_date_offset == -1)
1821 seconds = mktimegm(tm);
1823 seconds = mktime(tm);
1825 seconds = mktimegm(tm) + rtc_date_offset;
1827 return seconds - time(NULL);
1831 static void socket_cleanup(void)
1836 static int socket_init(void)
1841 ret = WSAStartup(MAKEWORD(2,2), &Data);
1843 err = WSAGetLastError();
1844 fprintf(stderr, "WSAStartup: %d\n", err);
1847 atexit(socket_cleanup);
1852 const char *get_opt_name(char *buf, int buf_size, const char *p)
1857 while (*p != '\0' && *p != '=') {
1858 if (q && (q - buf) < buf_size - 1)
1868 const char *get_opt_value(char *buf, int buf_size, const char *p)
1873 while (*p != '\0') {
1875 if (*(p + 1) != ',')
1879 if (q && (q - buf) < buf_size - 1)
1889 int get_param_value(char *buf, int buf_size,
1890 const char *tag, const char *str)
1897 p = get_opt_name(option, sizeof(option), p);
1901 if (!strcmp(tag, option)) {
1902 (void)get_opt_value(buf, buf_size, p);
1905 p = get_opt_value(NULL, 0, p);
1914 int check_params(char *buf, int buf_size,
1915 const char * const *params, const char *str)
1922 p = get_opt_name(buf, buf_size, p);
1926 for(i = 0; params[i] != NULL; i++)
1927 if (!strcmp(params[i], buf))
1929 if (params[i] == NULL)
1931 p = get_opt_value(NULL, 0, p);
1939 /***********************************************************/
1940 /* Bluetooth support */
1943 static struct HCIInfo *hci_table[MAX_NICS];
1945 static struct bt_vlan_s {
1946 struct bt_scatternet_s net;
1948 struct bt_vlan_s *next;
1951 /* find or alloc a new bluetooth "VLAN" */
1952 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1954 struct bt_vlan_s **pvlan, *vlan;
1955 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1959 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1961 pvlan = &first_bt_vlan;
1962 while (*pvlan != NULL)
1963 pvlan = &(*pvlan)->next;
1968 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1972 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1977 static struct HCIInfo null_hci = {
1978 .cmd_send = null_hci_send,
1979 .sco_send = null_hci_send,
1980 .acl_send = null_hci_send,
1981 .bdaddr_set = null_hci_addr_set,
1984 struct HCIInfo *qemu_next_hci(void)
1986 if (cur_hci == nb_hcis)
1989 return hci_table[cur_hci++];
1992 static struct HCIInfo *hci_init(const char *str)
1995 struct bt_scatternet_s *vlan = 0;
1997 if (!strcmp(str, "null"))
2000 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2002 return bt_host_hci(str[4] ? str + 5 : "hci0");
2003 else if (!strncmp(str, "hci", 3)) {
2006 if (!strncmp(str + 3, ",vlan=", 6)) {
2007 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2012 vlan = qemu_find_bt_vlan(0);
2014 return bt_new_hci(vlan);
2017 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2022 static int bt_hci_parse(const char *str)
2024 struct HCIInfo *hci;
2027 if (nb_hcis >= MAX_NICS) {
2028 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2032 hci = hci_init(str);
2041 bdaddr.b[5] = 0x56 + nb_hcis;
2042 hci->bdaddr_set(hci, bdaddr.b);
2044 hci_table[nb_hcis++] = hci;
2049 static void bt_vhci_add(int vlan_id)
2051 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2054 fprintf(stderr, "qemu: warning: adding a VHCI to "
2055 "an empty scatternet %i\n", vlan_id);
2057 bt_vhci_init(bt_new_hci(vlan));
2060 static struct bt_device_s *bt_device_add(const char *opt)
2062 struct bt_scatternet_s *vlan;
2064 char *endp = strstr(opt, ",vlan=");
2065 int len = (endp ? endp - opt : strlen(opt)) + 1;
2068 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2071 vlan_id = strtol(endp + 6, &endp, 0);
2073 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2078 vlan = qemu_find_bt_vlan(vlan_id);
2081 fprintf(stderr, "qemu: warning: adding a slave device to "
2082 "an empty scatternet %i\n", vlan_id);
2084 if (!strcmp(devname, "keyboard"))
2085 return bt_keyboard_init(vlan);
2087 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2091 static int bt_parse(const char *opt)
2093 const char *endp, *p;
2096 if (strstart(opt, "hci", &endp)) {
2097 if (!*endp || *endp == ',') {
2099 if (!strstart(endp, ",vlan=", 0))
2102 return bt_hci_parse(opt);
2104 } else if (strstart(opt, "vhci", &endp)) {
2105 if (!*endp || *endp == ',') {
2107 if (strstart(endp, ",vlan=", &p)) {
2108 vlan = strtol(p, (char **) &endp, 0);
2110 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2114 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2123 } else if (strstart(opt, "device:", &endp))
2124 return !bt_device_add(endp);
2126 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2130 /***********************************************************/
2131 /* QEMU Block devices */
2133 #define HD_ALIAS "index=%d,media=disk"
2135 #define CDROM_ALIAS "index=1,media=cdrom"
2137 #define CDROM_ALIAS "index=2,media=cdrom"
2139 #define FD_ALIAS "index=%d,if=floppy"
2140 #define PFLASH_ALIAS "if=pflash"
2141 #define MTD_ALIAS "if=mtd"
2142 #define SD_ALIAS "index=0,if=sd"
2144 static int drive_opt_get_free_idx(void)
2148 for (index = 0; index < MAX_DRIVES; index++)
2149 if (!drives_opt[index].used) {
2150 drives_opt[index].used = 1;
2157 static int drive_get_free_idx(void)
2161 for (index = 0; index < MAX_DRIVES; index++)
2162 if (!drives_table[index].used) {
2163 drives_table[index].used = 1;
2170 int drive_add(const char *file, const char *fmt, ...)
2173 int index = drive_opt_get_free_idx();
2175 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2176 fprintf(stderr, "qemu: too many drives\n");
2180 drives_opt[index].file = file;
2182 vsnprintf(drives_opt[index].opt,
2183 sizeof(drives_opt[0].opt), fmt, ap);
2190 void drive_remove(int index)
2192 drives_opt[index].used = 0;
2196 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2200 /* seek interface, bus and unit */
2202 for (index = 0; index < MAX_DRIVES; index++)
2203 if (drives_table[index].type == type &&
2204 drives_table[index].bus == bus &&
2205 drives_table[index].unit == unit &&
2206 drives_table[index].used)
2212 int drive_get_max_bus(BlockInterfaceType type)
2218 for (index = 0; index < nb_drives; index++) {
2219 if(drives_table[index].type == type &&
2220 drives_table[index].bus > max_bus)
2221 max_bus = drives_table[index].bus;
2226 const char *drive_get_serial(BlockDriverState *bdrv)
2230 for (index = 0; index < nb_drives; index++)
2231 if (drives_table[index].bdrv == bdrv)
2232 return drives_table[index].serial;
2237 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2241 for (index = 0; index < nb_drives; index++)
2242 if (drives_table[index].bdrv == bdrv)
2243 return drives_table[index].onerror;
2245 return BLOCK_ERR_REPORT;
2248 static void bdrv_format_print(void *opaque, const char *name)
2250 fprintf(stderr, " %s", name);
2253 void drive_uninit(BlockDriverState *bdrv)
2257 for (i = 0; i < MAX_DRIVES; i++)
2258 if (drives_table[i].bdrv == bdrv) {
2259 drives_table[i].bdrv = NULL;
2260 drives_table[i].used = 0;
2261 drive_remove(drives_table[i].drive_opt_idx);
2267 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2273 const char *mediastr = "";
2274 BlockInterfaceType type;
2275 enum { MEDIA_DISK, MEDIA_CDROM } media;
2276 int bus_id, unit_id;
2277 int cyls, heads, secs, translation;
2278 BlockDriverState *bdrv;
2279 BlockDriver *drv = NULL;
2280 QEMUMachine *machine = opaque;
2284 int bdrv_flags, onerror;
2285 int drives_table_idx;
2286 char *str = arg->opt;
2287 static const char * const params[] = { "bus", "unit", "if", "index",
2288 "cyls", "heads", "secs", "trans",
2289 "media", "snapshot", "file",
2290 "cache", "format", "serial", "werror",
2293 if (check_params(buf, sizeof(buf), params, str) < 0) {
2294 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2300 cyls = heads = secs = 0;
2303 translation = BIOS_ATA_TRANSLATION_AUTO;
2307 if (machine->use_scsi) {
2309 max_devs = MAX_SCSI_DEVS;
2310 pstrcpy(devname, sizeof(devname), "scsi");
2313 max_devs = MAX_IDE_DEVS;
2314 pstrcpy(devname, sizeof(devname), "ide");
2318 /* extract parameters */
2320 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2321 bus_id = strtol(buf, NULL, 0);
2323 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2328 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2329 unit_id = strtol(buf, NULL, 0);
2331 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2336 if (get_param_value(buf, sizeof(buf), "if", str)) {
2337 pstrcpy(devname, sizeof(devname), buf);
2338 if (!strcmp(buf, "ide")) {
2340 max_devs = MAX_IDE_DEVS;
2341 } else if (!strcmp(buf, "scsi")) {
2343 max_devs = MAX_SCSI_DEVS;
2344 } else if (!strcmp(buf, "floppy")) {
2347 } else if (!strcmp(buf, "pflash")) {
2350 } else if (!strcmp(buf, "mtd")) {
2353 } else if (!strcmp(buf, "sd")) {
2356 } else if (!strcmp(buf, "virtio")) {
2360 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2365 if (get_param_value(buf, sizeof(buf), "index", str)) {
2366 index = strtol(buf, NULL, 0);
2368 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2373 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2374 cyls = strtol(buf, NULL, 0);
2377 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2378 heads = strtol(buf, NULL, 0);
2381 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2382 secs = strtol(buf, NULL, 0);
2385 if (cyls || heads || secs) {
2386 if (cyls < 1 || cyls > 16383) {
2387 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2390 if (heads < 1 || heads > 16) {
2391 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2394 if (secs < 1 || secs > 63) {
2395 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2400 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2403 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2407 if (!strcmp(buf, "none"))
2408 translation = BIOS_ATA_TRANSLATION_NONE;
2409 else if (!strcmp(buf, "lba"))
2410 translation = BIOS_ATA_TRANSLATION_LBA;
2411 else if (!strcmp(buf, "auto"))
2412 translation = BIOS_ATA_TRANSLATION_AUTO;
2414 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2419 if (get_param_value(buf, sizeof(buf), "media", str)) {
2420 if (!strcmp(buf, "disk")) {
2422 } else if (!strcmp(buf, "cdrom")) {
2423 if (cyls || secs || heads) {
2425 "qemu: '%s' invalid physical CHS format\n", str);
2428 media = MEDIA_CDROM;
2430 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2435 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2436 if (!strcmp(buf, "on"))
2438 else if (!strcmp(buf, "off"))
2441 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2446 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2447 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2449 else if (!strcmp(buf, "writethrough"))
2451 else if (!strcmp(buf, "writeback"))
2454 fprintf(stderr, "qemu: invalid cache option\n");
2459 if (get_param_value(buf, sizeof(buf), "format", str)) {
2460 if (strcmp(buf, "?") == 0) {
2461 fprintf(stderr, "qemu: Supported formats:");
2462 bdrv_iterate_format(bdrv_format_print, NULL);
2463 fprintf(stderr, "\n");
2466 drv = bdrv_find_format(buf);
2468 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2473 if (arg->file == NULL)
2474 get_param_value(file, sizeof(file), "file", str);
2476 pstrcpy(file, sizeof(file), arg->file);
2478 if (!get_param_value(serial, sizeof(serial), "serial", str))
2479 memset(serial, 0, sizeof(serial));
2481 onerror = BLOCK_ERR_REPORT;
2482 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2483 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2484 fprintf(stderr, "werror is no supported by this format\n");
2487 if (!strcmp(buf, "ignore"))
2488 onerror = BLOCK_ERR_IGNORE;
2489 else if (!strcmp(buf, "enospc"))
2490 onerror = BLOCK_ERR_STOP_ENOSPC;
2491 else if (!strcmp(buf, "stop"))
2492 onerror = BLOCK_ERR_STOP_ANY;
2493 else if (!strcmp(buf, "report"))
2494 onerror = BLOCK_ERR_REPORT;
2496 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2501 /* compute bus and unit according index */
2504 if (bus_id != 0 || unit_id != -1) {
2506 "qemu: '%s' index cannot be used with bus and unit\n", str);
2514 unit_id = index % max_devs;
2515 bus_id = index / max_devs;
2519 /* if user doesn't specify a unit_id,
2520 * try to find the first free
2523 if (unit_id == -1) {
2525 while (drive_get_index(type, bus_id, unit_id) != -1) {
2527 if (max_devs && unit_id >= max_devs) {
2528 unit_id -= max_devs;
2536 if (max_devs && unit_id >= max_devs) {
2537 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2538 str, unit_id, max_devs - 1);
2543 * ignore multiple definitions
2546 if (drive_get_index(type, bus_id, unit_id) != -1)
2551 if (type == IF_IDE || type == IF_SCSI)
2552 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2554 snprintf(buf, sizeof(buf), "%s%i%s%i",
2555 devname, bus_id, mediastr, unit_id);
2557 snprintf(buf, sizeof(buf), "%s%s%i",
2558 devname, mediastr, unit_id);
2559 bdrv = bdrv_new(buf);
2560 drives_table_idx = drive_get_free_idx();
2561 drives_table[drives_table_idx].bdrv = bdrv;
2562 drives_table[drives_table_idx].type = type;
2563 drives_table[drives_table_idx].bus = bus_id;
2564 drives_table[drives_table_idx].unit = unit_id;
2565 drives_table[drives_table_idx].onerror = onerror;
2566 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2567 strncpy(drives_table[nb_drives].serial, serial, sizeof(serial));
2576 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2577 bdrv_set_translation_hint(bdrv, translation);
2581 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2586 /* FIXME: This isn't really a floppy, but it's a reasonable
2589 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2600 bdrv_flags |= BDRV_O_SNAPSHOT;
2601 cache = 2; /* always use write-back with snapshot */
2603 if (cache == 0) /* no caching */
2604 bdrv_flags |= BDRV_O_NOCACHE;
2605 else if (cache == 2) /* write-back */
2606 bdrv_flags |= BDRV_O_CACHE_WB;
2607 else if (cache == 3) /* not specified */
2608 bdrv_flags |= BDRV_O_CACHE_DEF;
2609 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2610 fprintf(stderr, "qemu: could not open disk image %s\n",
2614 return drives_table_idx;
2617 /***********************************************************/
2620 static USBPort *used_usb_ports;
2621 static USBPort *free_usb_ports;
2623 /* ??? Maybe change this to register a hub to keep track of the topology. */
2624 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2625 usb_attachfn attach)
2627 port->opaque = opaque;
2628 port->index = index;
2629 port->attach = attach;
2630 port->next = free_usb_ports;
2631 free_usb_ports = port;
2634 int usb_device_add_dev(USBDevice *dev)
2638 /* Find a USB port to add the device to. */
2639 port = free_usb_ports;
2643 /* Create a new hub and chain it on. */
2644 free_usb_ports = NULL;
2645 port->next = used_usb_ports;
2646 used_usb_ports = port;
2648 hub = usb_hub_init(VM_USB_HUB_SIZE);
2649 usb_attach(port, hub);
2650 port = free_usb_ports;
2653 free_usb_ports = port->next;
2654 port->next = used_usb_ports;
2655 used_usb_ports = port;
2656 usb_attach(port, dev);
2660 static int usb_device_add(const char *devname)
2665 if (!free_usb_ports)
2668 if (strstart(devname, "host:", &p)) {
2669 dev = usb_host_device_open(p);
2670 } else if (!strcmp(devname, "mouse")) {
2671 dev = usb_mouse_init();
2672 } else if (!strcmp(devname, "tablet")) {
2673 dev = usb_tablet_init();
2674 } else if (!strcmp(devname, "keyboard")) {
2675 dev = usb_keyboard_init();
2676 } else if (strstart(devname, "disk:", &p)) {
2677 dev = usb_msd_init(p);
2678 } else if (!strcmp(devname, "wacom-tablet")) {
2679 dev = usb_wacom_init();
2680 } else if (strstart(devname, "serial:", &p)) {
2681 dev = usb_serial_init(p);
2682 #ifdef CONFIG_BRLAPI
2683 } else if (!strcmp(devname, "braille")) {
2684 dev = usb_baum_init();
2686 } else if (strstart(devname, "net:", &p)) {
2689 if (net_client_init("nic", p) < 0)
2691 nd_table[nic].model = "usb";
2692 dev = usb_net_init(&nd_table[nic]);
2693 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2694 dev = usb_bt_init(devname[2] ? hci_init(p) :
2695 bt_new_hci(qemu_find_bt_vlan(0)));
2702 return usb_device_add_dev(dev);
2705 int usb_device_del_addr(int bus_num, int addr)
2711 if (!used_usb_ports)
2717 lastp = &used_usb_ports;
2718 port = used_usb_ports;
2719 while (port && port->dev->addr != addr) {
2720 lastp = &port->next;
2728 *lastp = port->next;
2729 usb_attach(port, NULL);
2730 dev->handle_destroy(dev);
2731 port->next = free_usb_ports;
2732 free_usb_ports = port;
2736 static int usb_device_del(const char *devname)
2741 if (strstart(devname, "host:", &p))
2742 return usb_host_device_close(p);
2744 if (!used_usb_ports)
2747 p = strchr(devname, '.');
2750 bus_num = strtoul(devname, NULL, 0);
2751 addr = strtoul(p + 1, NULL, 0);
2753 return usb_device_del_addr(bus_num, addr);
2756 void do_usb_add(const char *devname)
2758 usb_device_add(devname);
2761 void do_usb_del(const char *devname)
2763 usb_device_del(devname);
2770 const char *speed_str;
2773 term_printf("USB support not enabled\n");
2777 for (port = used_usb_ports; port; port = port->next) {
2781 switch(dev->speed) {
2785 case USB_SPEED_FULL:
2788 case USB_SPEED_HIGH:
2795 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2796 0, dev->addr, speed_str, dev->devname);
2800 /***********************************************************/
2801 /* PCMCIA/Cardbus */
2803 static struct pcmcia_socket_entry_s {
2804 struct pcmcia_socket_s *socket;
2805 struct pcmcia_socket_entry_s *next;
2806 } *pcmcia_sockets = 0;
2808 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2810 struct pcmcia_socket_entry_s *entry;
2812 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2813 entry->socket = socket;
2814 entry->next = pcmcia_sockets;
2815 pcmcia_sockets = entry;
2818 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2820 struct pcmcia_socket_entry_s *entry, **ptr;
2822 ptr = &pcmcia_sockets;
2823 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2824 if (entry->socket == socket) {
2830 void pcmcia_info(void)
2832 struct pcmcia_socket_entry_s *iter;
2833 if (!pcmcia_sockets)
2834 term_printf("No PCMCIA sockets\n");
2836 for (iter = pcmcia_sockets; iter; iter = iter->next)
2837 term_printf("%s: %s\n", iter->socket->slot_string,
2838 iter->socket->attached ? iter->socket->card_string :
2842 /***********************************************************/
2843 /* register display */
2845 void register_displaystate(DisplayState *ds)
2855 DisplayState *get_displaystate(void)
2857 return display_state;
2862 static void dumb_display_init(void)
2864 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2865 ds->surface = qemu_create_displaysurface(640, 480, 32, 640 * 4);
2866 register_displaystate(ds);
2869 /***********************************************************/
2872 #define MAX_IO_HANDLERS 64
2874 typedef struct IOHandlerRecord {
2876 IOCanRWHandler *fd_read_poll;
2878 IOHandler *fd_write;
2881 /* temporary data */
2883 struct IOHandlerRecord *next;
2886 static IOHandlerRecord *first_io_handler;
2888 /* XXX: fd_read_poll should be suppressed, but an API change is
2889 necessary in the character devices to suppress fd_can_read(). */
2890 int qemu_set_fd_handler2(int fd,
2891 IOCanRWHandler *fd_read_poll,
2893 IOHandler *fd_write,
2896 IOHandlerRecord **pioh, *ioh;
2898 if (!fd_read && !fd_write) {
2899 pioh = &first_io_handler;
2904 if (ioh->fd == fd) {
2911 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2915 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2916 ioh->next = first_io_handler;
2917 first_io_handler = ioh;
2920 ioh->fd_read_poll = fd_read_poll;
2921 ioh->fd_read = fd_read;
2922 ioh->fd_write = fd_write;
2923 ioh->opaque = opaque;
2929 int qemu_set_fd_handler(int fd,
2931 IOHandler *fd_write,
2934 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2938 /***********************************************************/
2939 /* Polling handling */
2941 typedef struct PollingEntry {
2944 struct PollingEntry *next;
2947 static PollingEntry *first_polling_entry;
2949 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2951 PollingEntry **ppe, *pe;
2952 pe = qemu_mallocz(sizeof(PollingEntry));
2954 pe->opaque = opaque;
2955 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2960 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2962 PollingEntry **ppe, *pe;
2963 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2965 if (pe->func == func && pe->opaque == opaque) {
2973 /***********************************************************/
2974 /* Wait objects support */
2975 typedef struct WaitObjects {
2977 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2978 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2979 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2982 static WaitObjects wait_objects = {0};
2984 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2986 WaitObjects *w = &wait_objects;
2988 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2990 w->events[w->num] = handle;
2991 w->func[w->num] = func;
2992 w->opaque[w->num] = opaque;
2997 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3000 WaitObjects *w = &wait_objects;
3003 for (i = 0; i < w->num; i++) {
3004 if (w->events[i] == handle)
3007 w->events[i] = w->events[i + 1];
3008 w->func[i] = w->func[i + 1];
3009 w->opaque[i] = w->opaque[i + 1];
3017 /***********************************************************/
3018 /* ram save/restore */
3020 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3024 v = qemu_get_byte(f);
3027 if (qemu_get_buffer(f, buf, len) != len)
3031 v = qemu_get_byte(f);
3032 memset(buf, v, len);
3038 if (qemu_file_has_error(f))
3044 static int ram_load_v1(QEMUFile *f, void *opaque)
3049 if (qemu_get_be32(f) != phys_ram_size)
3051 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3052 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3059 #define BDRV_HASH_BLOCK_SIZE 1024
3060 #define IOBUF_SIZE 4096
3061 #define RAM_CBLOCK_MAGIC 0xfabe
3063 typedef struct RamDecompressState {
3066 uint8_t buf[IOBUF_SIZE];
3067 } RamDecompressState;
3069 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3072 memset(s, 0, sizeof(*s));
3074 ret = inflateInit(&s->zstream);
3080 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3084 s->zstream.avail_out = len;
3085 s->zstream.next_out = buf;
3086 while (s->zstream.avail_out > 0) {
3087 if (s->zstream.avail_in == 0) {
3088 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3090 clen = qemu_get_be16(s->f);
3091 if (clen > IOBUF_SIZE)
3093 qemu_get_buffer(s->f, s->buf, clen);
3094 s->zstream.avail_in = clen;
3095 s->zstream.next_in = s->buf;
3097 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3098 if (ret != Z_OK && ret != Z_STREAM_END) {
3105 static void ram_decompress_close(RamDecompressState *s)
3107 inflateEnd(&s->zstream);
3110 #define RAM_SAVE_FLAG_FULL 0x01
3111 #define RAM_SAVE_FLAG_COMPRESS 0x02
3112 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3113 #define RAM_SAVE_FLAG_PAGE 0x08
3114 #define RAM_SAVE_FLAG_EOS 0x10
3116 static int is_dup_page(uint8_t *page, uint8_t ch)
3118 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3119 uint32_t *array = (uint32_t *)page;
3122 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3123 if (array[i] != val)
3130 static int ram_save_block(QEMUFile *f)
3132 static ram_addr_t current_addr = 0;
3133 ram_addr_t saved_addr = current_addr;
3134 ram_addr_t addr = 0;
3137 while (addr < phys_ram_size) {
3138 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3141 cpu_physical_memory_reset_dirty(current_addr,
3142 current_addr + TARGET_PAGE_SIZE,
3143 MIGRATION_DIRTY_FLAG);
3145 ch = *(phys_ram_base + current_addr);
3147 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3148 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3149 qemu_put_byte(f, ch);
3151 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3152 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3158 addr += TARGET_PAGE_SIZE;
3159 current_addr = (saved_addr + addr) % phys_ram_size;
3165 static ram_addr_t ram_save_threshold = 10;
3167 static ram_addr_t ram_save_remaining(void)
3170 ram_addr_t count = 0;
3172 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3173 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3180 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3185 /* Make sure all dirty bits are set */
3186 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3187 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3188 cpu_physical_memory_set_dirty(addr);
3191 /* Enable dirty memory tracking */
3192 cpu_physical_memory_set_dirty_tracking(1);
3194 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3197 while (!qemu_file_rate_limit(f)) {
3200 ret = ram_save_block(f);
3201 if (ret == 0) /* no more blocks */
3205 /* try transferring iterative blocks of memory */
3208 cpu_physical_memory_set_dirty_tracking(0);
3210 /* flush all remaining blocks regardless of rate limiting */
3211 while (ram_save_block(f) != 0);
3214 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3216 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3219 static int ram_load_dead(QEMUFile *f, void *opaque)
3221 RamDecompressState s1, *s = &s1;
3225 if (ram_decompress_open(s, f) < 0)
3227 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3228 if (ram_decompress_buf(s, buf, 1) < 0) {
3229 fprintf(stderr, "Error while reading ram block header\n");
3233 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3234 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3239 printf("Error block header\n");
3243 ram_decompress_close(s);
3248 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3253 if (version_id == 1)
3254 return ram_load_v1(f, opaque);
3256 if (version_id == 2) {
3257 if (qemu_get_be32(f) != phys_ram_size)
3259 return ram_load_dead(f, opaque);
3262 if (version_id != 3)
3266 addr = qemu_get_be64(f);
3268 flags = addr & ~TARGET_PAGE_MASK;
3269 addr &= TARGET_PAGE_MASK;
3271 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3272 if (addr != phys_ram_size)
3276 if (flags & RAM_SAVE_FLAG_FULL) {
3277 if (ram_load_dead(f, opaque) < 0)
3281 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3282 uint8_t ch = qemu_get_byte(f);
3283 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3284 } else if (flags & RAM_SAVE_FLAG_PAGE)
3285 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3286 } while (!(flags & RAM_SAVE_FLAG_EOS));
3291 void qemu_service_io(void)
3293 CPUState *env = cpu_single_env;
3295 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3297 if (env->kqemu_enabled) {
3298 kqemu_cpu_interrupt(env);
3304 /***********************************************************/
3305 /* bottom halves (can be seen as timers which expire ASAP) */
3316 static QEMUBH *first_bh = NULL;
3318 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3321 bh = qemu_mallocz(sizeof(QEMUBH));
3323 bh->opaque = opaque;
3324 bh->next = first_bh;
3329 int qemu_bh_poll(void)
3335 for (bh = first_bh; bh; bh = bh->next) {
3336 if (!bh->deleted && bh->scheduled) {
3345 /* remove deleted bhs */
3359 void qemu_bh_schedule_idle(QEMUBH *bh)
3367 void qemu_bh_schedule(QEMUBH *bh)
3369 CPUState *env = cpu_single_env;
3374 /* stop the currently executing CPU to execute the BH ASAP */
3376 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3380 void qemu_bh_cancel(QEMUBH *bh)
3385 void qemu_bh_delete(QEMUBH *bh)
3391 static void qemu_bh_update_timeout(int *timeout)
3395 for (bh = first_bh; bh; bh = bh->next) {
3396 if (!bh->deleted && bh->scheduled) {
3398 /* idle bottom halves will be polled at least
3400 *timeout = MIN(10, *timeout);
3402 /* non-idle bottom halves will be executed
3411 /***********************************************************/
3412 /* machine registration */
3414 static QEMUMachine *first_machine = NULL;
3415 QEMUMachine *current_machine = NULL;
3417 int qemu_register_machine(QEMUMachine *m)
3420 pm = &first_machine;
3428 static QEMUMachine *find_machine(const char *name)
3432 for(m = first_machine; m != NULL; m = m->next) {
3433 if (!strcmp(m->name, name))
3439 /***********************************************************/
3440 /* main execution loop */
3442 static void gui_update(void *opaque)
3444 uint64_t interval = GUI_REFRESH_INTERVAL;
3445 DisplayState *ds = opaque;
3446 DisplayChangeListener *dcl = ds->listeners;
3450 while (dcl != NULL) {
3451 if (dcl->gui_timer_interval &&
3452 dcl->gui_timer_interval < interval)
3453 interval = dcl->gui_timer_interval;
3456 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3459 static void nographic_update(void *opaque)
3461 uint64_t interval = GUI_REFRESH_INTERVAL;
3463 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3466 struct vm_change_state_entry {
3467 VMChangeStateHandler *cb;
3469 LIST_ENTRY (vm_change_state_entry) entries;
3472 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3474 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3477 VMChangeStateEntry *e;
3479 e = qemu_mallocz(sizeof (*e));
3483 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3487 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3489 LIST_REMOVE (e, entries);
3493 static void vm_state_notify(int running, int reason)
3495 VMChangeStateEntry *e;
3497 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3498 e->cb(e->opaque, running, reason);
3507 vm_state_notify(1, 0);
3508 qemu_rearm_alarm_timer(alarm_timer);
3512 void vm_stop(int reason)
3515 cpu_disable_ticks();
3517 vm_state_notify(0, reason);
3521 /* reset/shutdown handler */
3523 typedef struct QEMUResetEntry {
3524 QEMUResetHandler *func;
3526 struct QEMUResetEntry *next;
3529 static QEMUResetEntry *first_reset_entry;
3530 static int reset_requested;
3531 static int shutdown_requested;
3532 static int powerdown_requested;
3534 int qemu_shutdown_requested(void)
3536 int r = shutdown_requested;
3537 shutdown_requested = 0;
3541 int qemu_reset_requested(void)
3543 int r = reset_requested;
3544 reset_requested = 0;
3548 int qemu_powerdown_requested(void)
3550 int r = powerdown_requested;
3551 powerdown_requested = 0;
3555 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3557 QEMUResetEntry **pre, *re;
3559 pre = &first_reset_entry;
3560 while (*pre != NULL)
3561 pre = &(*pre)->next;
3562 re = qemu_mallocz(sizeof(QEMUResetEntry));
3564 re->opaque = opaque;
3569 void qemu_system_reset(void)
3573 /* reset all devices */
3574 for(re = first_reset_entry; re != NULL; re = re->next) {
3575 re->func(re->opaque);
3579 void qemu_system_reset_request(void)
3582 shutdown_requested = 1;
3584 reset_requested = 1;
3587 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3590 void qemu_system_shutdown_request(void)
3592 shutdown_requested = 1;
3594 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3597 void qemu_system_powerdown_request(void)
3599 powerdown_requested = 1;
3601 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3605 static void host_main_loop_wait(int *timeout)
3611 /* XXX: need to suppress polling by better using win32 events */
3613 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3614 ret |= pe->func(pe->opaque);
3618 WaitObjects *w = &wait_objects;
3620 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3621 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3622 if (w->func[ret - WAIT_OBJECT_0])
3623 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3625 /* Check for additional signaled events */
3626 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3628 /* Check if event is signaled */
3629 ret2 = WaitForSingleObject(w->events[i], 0);
3630 if(ret2 == WAIT_OBJECT_0) {
3632 w->func[i](w->opaque[i]);
3633 } else if (ret2 == WAIT_TIMEOUT) {
3635 err = GetLastError();
3636 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3639 } else if (ret == WAIT_TIMEOUT) {
3641 err = GetLastError();
3642 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3649 static void host_main_loop_wait(int *timeout)
3654 void main_loop_wait(int timeout)
3656 IOHandlerRecord *ioh;
3657 fd_set rfds, wfds, xfds;
3661 qemu_bh_update_timeout(&timeout);
3663 host_main_loop_wait(&timeout);
3665 /* poll any events */
3666 /* XXX: separate device handlers from system ones */
3671 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3675 (!ioh->fd_read_poll ||
3676 ioh->fd_read_poll(ioh->opaque) != 0)) {
3677 FD_SET(ioh->fd, &rfds);
3681 if (ioh->fd_write) {
3682 FD_SET(ioh->fd, &wfds);
3688 tv.tv_sec = timeout / 1000;
3689 tv.tv_usec = (timeout % 1000) * 1000;
3691 #if defined(CONFIG_SLIRP)
3692 if (slirp_is_inited()) {
3693 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3696 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3698 IOHandlerRecord **pioh;
3700 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3701 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3702 ioh->fd_read(ioh->opaque);
3704 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3705 ioh->fd_write(ioh->opaque);
3709 /* remove deleted IO handlers */
3710 pioh = &first_io_handler;
3720 #if defined(CONFIG_SLIRP)
3721 if (slirp_is_inited()) {
3727 slirp_select_poll(&rfds, &wfds, &xfds);
3731 /* vm time timers */
3732 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3733 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3734 qemu_get_clock(vm_clock));
3736 /* real time timers */
3737 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3738 qemu_get_clock(rt_clock));
3740 /* Check bottom-halves last in case any of the earlier events triggered
3746 static int main_loop(void)
3749 #ifdef CONFIG_PROFILER
3754 cur_cpu = first_cpu;
3755 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3762 #ifdef CONFIG_PROFILER
3763 ti = profile_getclock();
3768 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3769 env->icount_decr.u16.low = 0;
3770 env->icount_extra = 0;
3771 count = qemu_next_deadline();
3772 count = (count + (1 << icount_time_shift) - 1)
3773 >> icount_time_shift;
3774 qemu_icount += count;
3775 decr = (count > 0xffff) ? 0xffff : count;
3777 env->icount_decr.u16.low = decr;
3778 env->icount_extra = count;
3780 ret = cpu_exec(env);
3781 #ifdef CONFIG_PROFILER
3782 qemu_time += profile_getclock() - ti;
3785 /* Fold pending instructions back into the
3786 instruction counter, and clear the interrupt flag. */
3787 qemu_icount -= (env->icount_decr.u16.low
3788 + env->icount_extra);
3789 env->icount_decr.u32 = 0;
3790 env->icount_extra = 0;
3792 next_cpu = env->next_cpu ?: first_cpu;
3793 if (event_pending && likely(ret != EXCP_DEBUG)) {
3794 ret = EXCP_INTERRUPT;
3798 if (ret == EXCP_HLT) {
3799 /* Give the next CPU a chance to run. */
3803 if (ret != EXCP_HALTED)
3805 /* all CPUs are halted ? */
3811 if (shutdown_requested) {
3812 ret = EXCP_INTERRUPT;
3820 if (reset_requested) {
3821 reset_requested = 0;
3822 qemu_system_reset();
3823 ret = EXCP_INTERRUPT;
3825 if (powerdown_requested) {
3826 powerdown_requested = 0;
3827 qemu_system_powerdown();
3828 ret = EXCP_INTERRUPT;
3830 if (unlikely(ret == EXCP_DEBUG)) {
3831 gdb_set_stop_cpu(cur_cpu);
3832 vm_stop(EXCP_DEBUG);
3834 /* If all cpus are halted then wait until the next IRQ */
3835 /* XXX: use timeout computed from timers */
3836 if (ret == EXCP_HALTED) {
3840 /* Advance virtual time to the next event. */
3841 if (use_icount == 1) {
3842 /* When not using an adaptive execution frequency
3843 we tend to get badly out of sync with real time,
3844 so just delay for a reasonable amount of time. */
3847 delta = cpu_get_icount() - cpu_get_clock();
3850 /* If virtual time is ahead of real time then just
3852 timeout = (delta / 1000000) + 1;
3854 /* Wait for either IO to occur or the next
3856 add = qemu_next_deadline();
3857 /* We advance the timer before checking for IO.
3858 Limit the amount we advance so that early IO
3859 activity won't get the guest too far ahead. */
3863 add = (add + (1 << icount_time_shift) - 1)
3864 >> icount_time_shift;
3866 timeout = delta / 1000000;
3877 if (shutdown_requested) {
3878 ret = EXCP_INTERRUPT;
3883 #ifdef CONFIG_PROFILER
3884 ti = profile_getclock();
3886 main_loop_wait(timeout);
3887 #ifdef CONFIG_PROFILER
3888 dev_time += profile_getclock() - ti;
3891 cpu_disable_ticks();
3895 static void help(int exitcode)
3897 /* Please keep in synch with QEMU_OPTION_ enums, qemu_options[]
3898 and qemu-doc.texi */
3899 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3900 "usage: %s [options] [disk_image]\n"
3902 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3904 "Standard options:\n"
3905 "-h or -help display this help and exit\n"
3906 "-M machine select emulated machine (-M ? for list)\n"
3907 "-cpu cpu select CPU (-cpu ? for list)\n"
3908 "-smp n set the number of CPUs to 'n' [default=1]\n"
3909 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3910 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3911 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3912 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3913 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3914 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3915 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
3916 " use 'file' as a drive image\n"
3917 "-mtdblock file use 'file' as on-board Flash memory image\n"
3918 "-sd file use 'file' as SecureDigital card image\n"
3919 "-pflash file use 'file' as a parallel flash image\n"
3920 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3921 "-snapshot write to temporary files instead of disk image files\n"
3922 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3924 "-k language use keyboard layout (for example \"fr\" for French)\n"
3927 "-audio-help print list of audio drivers and their options\n"
3928 "-soundhw c1,... enable audio support\n"
3929 " and only specified sound cards (comma separated list)\n"
3930 " use -soundhw ? to get the list of supported cards\n"
3931 " use -soundhw all to enable all of them\n"
3933 "-usb enable the USB driver (will be the default soon)\n"
3934 "-usbdevice name add the host or guest USB device 'name'\n"
3935 "-name string set the name of the guest\n"
3936 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x\n"
3937 " specify machine UUID\n"
3939 "Display options:\n"
3940 "-nographic disable graphical output and redirect serial I/Os to console\n"
3941 #ifdef CONFIG_CURSES
3942 "-curses use a curses/ncurses interface instead of SDL\n"
3945 "-no-frame open SDL window without a frame and window decorations\n"
3946 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3947 "-no-quit disable SDL window close capability\n"
3950 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3951 "-vga [std|cirrus|vmware|none]\n"
3952 " select video card type\n"
3953 "-full-screen start in full screen\n"
3954 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3955 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3957 "-vnc display start a VNC server on display\n"
3959 "Network options:\n"
3960 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
3961 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3963 "-net user[,vlan=n][,name=str][,hostname=host]\n"
3964 " connect the user mode network stack to VLAN 'n' and send\n"
3965 " hostname 'host' to DHCP clients\n"
3968 "-net tap[,vlan=n][,name=str],ifname=name\n"
3969 " connect the host TAP network interface to VLAN 'n'\n"
3971 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
3972 " connect the host TAP network interface to VLAN 'n' and use the\n"
3973 " network scripts 'file' (default=%s)\n"
3974 " and 'dfile' (default=%s);\n"
3975 " use '[down]script=no' to disable script execution;\n"
3976 " use 'fd=h' to connect to an already opened TAP interface\n"
3978 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
3979 " connect the vlan 'n' to another VLAN using a socket connection\n"
3980 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
3981 " connect the vlan 'n' to multicast maddr and port\n"
3983 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
3984 " connect the vlan 'n' to port 'n' of a vde switch running\n"
3985 " on host and listening for incoming connections on 'socketpath'.\n"
3986 " Use group 'groupname' and mode 'octalmode' to change default\n"
3987 " ownership and permissions for communication port.\n"
3989 "-net none use it alone to have zero network devices; if no -net option\n"
3990 " is provided, the default is '-net nic -net user'\n"
3992 "-tftp dir allow tftp access to files in dir [-net user]\n"
3993 "-bootp file advertise file in BOOTP replies\n"
3995 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
3997 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
3998 " redirect TCP or UDP connections from host to guest [-net user]\n"
4001 "-bt hci,null dumb bluetooth HCI - doesn't respond to commands\n"
4002 "-bt hci,host[:id]\n"
4003 " use host's HCI with the given name\n"
4004 "-bt hci[,vlan=n]\n"
4005 " emulate a standard HCI in virtual scatternet 'n'\n"
4006 "-bt vhci[,vlan=n]\n"
4007 " add host computer to virtual scatternet 'n' using VHCI\n"
4008 "-bt device:dev[,vlan=n]\n"
4009 " emulate a bluetooth device 'dev' in scatternet 'n'\n"
4013 "i386 target only:\n"
4014 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4015 "-rtc-td-hack use it to fix time drift in Windows ACPI HAL\n"
4016 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4017 "-no-acpi disable ACPI\n"
4018 "-no-hpet disable HPET\n"
4019 "-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"
4020 " ACPI table description\n"
4022 "Linux boot specific:\n"
4023 "-kernel bzImage use 'bzImage' as kernel image\n"
4024 "-append cmdline use 'cmdline' as kernel command line\n"
4025 "-initrd file use 'file' as initial ram disk\n"
4027 "Debug/Expert options:\n"
4028 "-serial dev redirect the serial port to char device 'dev'\n"
4029 "-parallel dev redirect the parallel port to char device 'dev'\n"
4030 "-monitor dev redirect the monitor to char device 'dev'\n"
4031 "-pidfile file write PID to 'file'\n"
4032 "-S freeze CPU at startup (use 'c' to start execution)\n"
4033 "-s wait gdb connection to port\n"
4034 "-p port set gdb connection port [default=%s]\n"
4035 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4036 "-hdachs c,h,s[,t]\n"
4037 " force hard disk 0 physical geometry and the optional BIOS\n"
4038 " translation (t=none or lba) (usually qemu can guess them)\n"
4039 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4040 "-bios file set the filename for the BIOS\n"
4042 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4043 "-no-kqemu disable KQEMU kernel module usage\n"
4046 "-enable-kvm enable KVM full virtualization support\n"
4048 "-no-reboot exit instead of rebooting\n"
4049 "-no-shutdown stop before shutdown\n"
4050 "-loadvm [tag|id]\n"
4051 " start right away with a saved state (loadvm in monitor)\n"
4053 "-daemonize daemonize QEMU after initializing\n"
4055 "-option-rom rom load a file, rom, into the option ROM space\n"
4056 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4057 "-prom-env variable=value\n"
4058 " set OpenBIOS nvram variables\n"
4060 "-clock force the use of the given methods for timer alarm.\n"
4061 " To see what timers are available use -clock ?\n"
4062 "-localtime set the real time clock to local time [default=utc]\n"
4063 "-startdate select initial date of the clock\n"
4064 "-icount [N|auto]\n"
4065 " enable virtual instruction counter with 2^N clock ticks per instruction\n"
4066 "-echr chr set terminal escape character instead of ctrl-a\n"
4067 "-virtioconsole c\n"
4068 " set virtio console\n"
4069 "-show-cursor show cursor\n"
4070 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4071 "-semihosting semihosting mode\n"
4073 #if defined(TARGET_ARM)
4074 "-old-param old param mode\n"
4076 "-tb-size n set TB size\n"
4077 "-incoming p prepare for incoming migration, listen on port p\n"
4079 "During emulation, the following keys are useful:\n"
4080 "ctrl-alt-f toggle full screen\n"
4081 "ctrl-alt-n switch to virtual console 'n'\n"
4082 "ctrl-alt toggle mouse and keyboard grab\n"
4084 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4089 DEFAULT_NETWORK_SCRIPT,
4090 DEFAULT_NETWORK_DOWN_SCRIPT,
4092 DEFAULT_GDBSTUB_PORT,
4097 #define HAS_ARG 0x0001
4100 /* Please keep in synch with help, qemu_options[] and
4102 /* Standard options: */
4115 QEMU_OPTION_mtdblock,
4119 QEMU_OPTION_snapshot,
4122 QEMU_OPTION_audio_help,
4123 QEMU_OPTION_soundhw,
4125 QEMU_OPTION_usbdevice,
4129 /* Display options: */
4130 QEMU_OPTION_nographic,
4132 QEMU_OPTION_no_frame,
4133 QEMU_OPTION_alt_grab,
4134 QEMU_OPTION_no_quit,
4136 QEMU_OPTION_portrait,
4138 QEMU_OPTION_full_screen,
4142 /* Network options: */
4150 /* i386 target only: */
4151 QEMU_OPTION_win2k_hack,
4152 QEMU_OPTION_rtc_td_hack,
4153 QEMU_OPTION_no_fd_bootchk,
4154 QEMU_OPTION_no_acpi,
4155 QEMU_OPTION_no_hpet,
4156 QEMU_OPTION_acpitable,
4158 /* Linux boot specific: */
4163 /* Debug/Expert options: */
4165 QEMU_OPTION_parallel,
4166 QEMU_OPTION_monitor,
4167 QEMU_OPTION_pidfile,
4175 QEMU_OPTION_kernel_kqemu,
4176 QEMU_OPTION_no_kqemu,
4177 QEMU_OPTION_enable_kvm,
4178 QEMU_OPTION_no_reboot,
4179 QEMU_OPTION_no_shutdown,
4181 QEMU_OPTION_daemonize,
4182 QEMU_OPTION_option_rom,
4183 QEMU_OPTION_prom_env,
4185 QEMU_OPTION_localtime,
4186 QEMU_OPTION_startdate,
4189 QEMU_OPTION_virtiocon,
4190 QEMU_OPTION_show_cursor,
4191 QEMU_OPTION_semihosting,
4192 QEMU_OPTION_old_param,
4193 QEMU_OPTION_tb_size,
4194 QEMU_OPTION_incoming,
4197 typedef struct QEMUOption {
4203 static const QEMUOption qemu_options[] = {
4204 /* Please keep in synch with help, QEMU_OPTION_ enums, and
4206 /* Standard options: */
4207 { "h", 0, QEMU_OPTION_h },
4208 { "help", 0, QEMU_OPTION_h },
4209 { "M", HAS_ARG, QEMU_OPTION_M },
4210 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4211 { "smp", HAS_ARG, QEMU_OPTION_smp },
4212 { "fda", HAS_ARG, QEMU_OPTION_fda },
4213 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4214 { "hda", HAS_ARG, QEMU_OPTION_hda },
4215 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4216 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4217 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4218 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4219 { "drive", HAS_ARG, QEMU_OPTION_drive },
4220 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4221 { "sd", HAS_ARG, QEMU_OPTION_sd },
4222 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4223 { "boot", HAS_ARG, QEMU_OPTION_boot },
4224 { "snapshot", 0, QEMU_OPTION_snapshot },
4225 { "m", HAS_ARG, QEMU_OPTION_m },
4227 { "k", HAS_ARG, QEMU_OPTION_k },
4230 { "audio-help", 0, QEMU_OPTION_audio_help },
4231 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4233 { "usb", 0, QEMU_OPTION_usb },
4234 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4235 { "name", HAS_ARG, QEMU_OPTION_name },
4236 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4238 /* Display options: */
4239 { "nographic", 0, QEMU_OPTION_nographic },
4240 #ifdef CONFIG_CURSES
4241 { "curses", 0, QEMU_OPTION_curses },
4244 { "no-frame", 0, QEMU_OPTION_no_frame },
4245 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4246 { "no-quit", 0, QEMU_OPTION_no_quit },
4247 { "sdl", 0, QEMU_OPTION_sdl },
4249 { "portrait", 0, QEMU_OPTION_portrait },
4250 { "vga", HAS_ARG, QEMU_OPTION_vga },
4251 { "full-screen", 0, QEMU_OPTION_full_screen },
4252 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4253 { "g", 1, QEMU_OPTION_g },
4255 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4257 /* Network options: */
4258 { "net", HAS_ARG, QEMU_OPTION_net},
4260 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4261 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4263 { "smb", HAS_ARG, QEMU_OPTION_smb },
4265 { "redir", HAS_ARG, QEMU_OPTION_redir },
4267 { "bt", HAS_ARG, QEMU_OPTION_bt },
4269 /* i386 target only: */
4270 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4271 { "rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack },
4272 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4273 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4274 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4275 { "acpitable", HAS_ARG, QEMU_OPTION_acpitable },
4278 /* Linux boot specific: */
4279 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4280 { "append", HAS_ARG, QEMU_OPTION_append },
4281 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4283 /* Debug/Expert options: */
4284 { "serial", HAS_ARG, QEMU_OPTION_serial },
4285 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4286 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4287 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4288 { "S", 0, QEMU_OPTION_S },
4289 { "s", 0, QEMU_OPTION_s },
4290 { "p", HAS_ARG, QEMU_OPTION_p },
4291 { "d", HAS_ARG, QEMU_OPTION_d },
4292 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4293 { "L", HAS_ARG, QEMU_OPTION_L },
4294 { "bios", HAS_ARG, QEMU_OPTION_bios },
4296 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4297 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4300 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4302 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4303 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4304 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4305 { "daemonize", 0, QEMU_OPTION_daemonize },
4306 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4307 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4308 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4310 { "clock", HAS_ARG, QEMU_OPTION_clock },
4311 { "localtime", 0, QEMU_OPTION_localtime },
4312 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4313 { "icount", HAS_ARG, QEMU_OPTION_icount },
4314 { "echr", HAS_ARG, QEMU_OPTION_echr },
4315 { "virtioconsole", HAS_ARG, QEMU_OPTION_virtiocon },
4316 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4317 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4318 { "semihosting", 0, QEMU_OPTION_semihosting },
4320 #if defined(TARGET_ARM)
4321 { "old-param", 0, QEMU_OPTION_old_param },
4323 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4324 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4328 /* password input */
4330 int qemu_key_check(BlockDriverState *bs, const char *name)
4335 if (!bdrv_is_encrypted(bs))
4338 term_printf("%s is encrypted.\n", name);
4339 for(i = 0; i < 3; i++) {
4340 monitor_readline("Password: ", 1, password, sizeof(password));
4341 if (bdrv_set_key(bs, password) == 0)
4343 term_printf("invalid password\n");
4348 static BlockDriverState *get_bdrv(int index)
4350 if (index > nb_drives)
4352 return drives_table[index].bdrv;
4355 static void read_passwords(void)
4357 BlockDriverState *bs;
4360 for(i = 0; i < 6; i++) {
4363 qemu_key_check(bs, bdrv_get_device_name(bs));
4368 struct soundhw soundhw[] = {
4369 #ifdef HAS_AUDIO_CHOICE
4370 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4376 { .init_isa = pcspk_audio_init }
4383 "Creative Sound Blaster 16",
4386 { .init_isa = SB16_init }
4390 #ifdef CONFIG_CS4231A
4396 { .init_isa = cs4231a_init }
4404 "Yamaha YMF262 (OPL3)",
4406 "Yamaha YM3812 (OPL2)",
4410 { .init_isa = Adlib_init }
4417 "Gravis Ultrasound GF1",
4420 { .init_isa = GUS_init }
4427 "Intel 82801AA AC97 Audio",
4430 { .init_pci = ac97_init }
4434 #ifdef CONFIG_ES1370
4437 "ENSONIQ AudioPCI ES1370",
4440 { .init_pci = es1370_init }
4444 #endif /* HAS_AUDIO_CHOICE */
4446 { NULL, NULL, 0, 0, { NULL } }
4449 static void select_soundhw (const char *optarg)
4453 if (*optarg == '?') {
4456 printf ("Valid sound card names (comma separated):\n");
4457 for (c = soundhw; c->name; ++c) {
4458 printf ("%-11s %s\n", c->name, c->descr);
4460 printf ("\n-soundhw all will enable all of the above\n");
4461 exit (*optarg != '?');
4469 if (!strcmp (optarg, "all")) {
4470 for (c = soundhw; c->name; ++c) {
4478 e = strchr (p, ',');
4479 l = !e ? strlen (p) : (size_t) (e - p);
4481 for (c = soundhw; c->name; ++c) {
4482 if (!strncmp (c->name, p, l)) {
4491 "Unknown sound card name (too big to show)\n");
4494 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4499 p += l + (e != NULL);
4503 goto show_valid_cards;
4508 static void select_vgahw (const char *p)
4512 if (strstart(p, "std", &opts)) {
4513 std_vga_enabled = 1;
4514 cirrus_vga_enabled = 0;
4516 } else if (strstart(p, "cirrus", &opts)) {
4517 cirrus_vga_enabled = 1;
4518 std_vga_enabled = 0;
4520 } else if (strstart(p, "vmware", &opts)) {
4521 cirrus_vga_enabled = 0;
4522 std_vga_enabled = 0;
4524 } else if (strstart(p, "none", &opts)) {
4525 cirrus_vga_enabled = 0;
4526 std_vga_enabled = 0;
4530 fprintf(stderr, "Unknown vga type: %s\n", p);
4534 const char *nextopt;
4536 if (strstart(opts, ",retrace=", &nextopt)) {
4538 if (strstart(opts, "dumb", &nextopt))
4539 vga_retrace_method = VGA_RETRACE_DUMB;
4540 else if (strstart(opts, "precise", &nextopt))
4541 vga_retrace_method = VGA_RETRACE_PRECISE;
4542 else goto invalid_vga;
4543 } else goto invalid_vga;
4549 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4551 exit(STATUS_CONTROL_C_EXIT);
4556 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4560 if(strlen(str) != 36)
4563 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4564 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4565 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4573 #define MAX_NET_CLIENTS 32
4577 static void termsig_handler(int signal)
4579 qemu_system_shutdown_request();
4582 static void termsig_setup(void)
4584 struct sigaction act;
4586 memset(&act, 0, sizeof(act));
4587 act.sa_handler = termsig_handler;
4588 sigaction(SIGINT, &act, NULL);
4589 sigaction(SIGHUP, &act, NULL);
4590 sigaction(SIGTERM, &act, NULL);
4595 int main(int argc, char **argv, char **envp)
4597 #ifdef CONFIG_GDBSTUB
4599 const char *gdbstub_port;
4601 uint32_t boot_devices_bitmap = 0;
4603 int snapshot, linux_boot, net_boot;
4604 const char *initrd_filename;
4605 const char *kernel_filename, *kernel_cmdline;
4606 const char *boot_devices = "";
4608 DisplayChangeListener *dcl;
4609 int cyls, heads, secs, translation;
4610 const char *net_clients[MAX_NET_CLIENTS];
4612 const char *bt_opts[MAX_BT_CMDLINE];
4616 const char *r, *optarg;
4617 CharDriverState *monitor_hd = NULL;
4618 const char *monitor_device;
4619 const char *serial_devices[MAX_SERIAL_PORTS];
4620 int serial_device_index;
4621 const char *parallel_devices[MAX_PARALLEL_PORTS];
4622 int parallel_device_index;
4623 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4624 int virtio_console_index;
4625 const char *loadvm = NULL;
4626 QEMUMachine *machine;
4627 const char *cpu_model;
4628 const char *usb_devices[MAX_USB_CMDLINE];
4629 int usb_devices_index;
4632 const char *pid_file = NULL;
4634 const char *incoming = NULL;
4636 qemu_cache_utils_init(envp);
4638 LIST_INIT (&vm_change_state_head);
4641 struct sigaction act;
4642 sigfillset(&act.sa_mask);
4644 act.sa_handler = SIG_IGN;
4645 sigaction(SIGPIPE, &act, NULL);
4648 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4649 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4650 QEMU to run on a single CPU */
4655 h = GetCurrentProcess();
4656 if (GetProcessAffinityMask(h, &mask, &smask)) {
4657 for(i = 0; i < 32; i++) {
4658 if (mask & (1 << i))
4663 SetProcessAffinityMask(h, mask);
4669 register_machines();
4670 machine = first_machine;
4672 initrd_filename = NULL;
4674 vga_ram_size = VGA_RAM_SIZE;
4675 #ifdef CONFIG_GDBSTUB
4677 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4682 kernel_filename = NULL;
4683 kernel_cmdline = "";
4684 cyls = heads = secs = 0;
4685 translation = BIOS_ATA_TRANSLATION_AUTO;
4686 monitor_device = "vc";
4688 serial_devices[0] = "vc:80Cx24C";
4689 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4690 serial_devices[i] = NULL;
4691 serial_device_index = 0;
4693 parallel_devices[0] = "vc:640x480";
4694 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4695 parallel_devices[i] = NULL;
4696 parallel_device_index = 0;
4698 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4699 virtio_consoles[i] = NULL;
4700 virtio_console_index = 0;
4702 usb_devices_index = 0;
4721 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4723 const QEMUOption *popt;
4726 /* Treat --foo the same as -foo. */
4729 popt = qemu_options;
4732 fprintf(stderr, "%s: invalid option -- '%s'\n",
4736 if (!strcmp(popt->name, r + 1))
4740 if (popt->flags & HAS_ARG) {
4741 if (optind >= argc) {
4742 fprintf(stderr, "%s: option '%s' requires an argument\n",
4746 optarg = argv[optind++];
4751 switch(popt->index) {
4753 machine = find_machine(optarg);
4756 printf("Supported machines are:\n");
4757 for(m = first_machine; m != NULL; m = m->next) {
4758 printf("%-10s %s%s\n",
4760 m == first_machine ? " (default)" : "");
4762 exit(*optarg != '?');
4765 case QEMU_OPTION_cpu:
4766 /* hw initialization will check this */
4767 if (*optarg == '?') {
4768 /* XXX: implement xxx_cpu_list for targets that still miss it */
4769 #if defined(cpu_list)
4770 cpu_list(stdout, &fprintf);
4777 case QEMU_OPTION_initrd:
4778 initrd_filename = optarg;
4780 case QEMU_OPTION_hda:
4782 hda_index = drive_add(optarg, HD_ALIAS, 0);
4784 hda_index = drive_add(optarg, HD_ALIAS
4785 ",cyls=%d,heads=%d,secs=%d%s",
4786 0, cyls, heads, secs,
4787 translation == BIOS_ATA_TRANSLATION_LBA ?
4789 translation == BIOS_ATA_TRANSLATION_NONE ?
4790 ",trans=none" : "");
4792 case QEMU_OPTION_hdb:
4793 case QEMU_OPTION_hdc:
4794 case QEMU_OPTION_hdd:
4795 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4797 case QEMU_OPTION_drive:
4798 drive_add(NULL, "%s", optarg);
4800 case QEMU_OPTION_mtdblock:
4801 drive_add(optarg, MTD_ALIAS);
4803 case QEMU_OPTION_sd:
4804 drive_add(optarg, SD_ALIAS);
4806 case QEMU_OPTION_pflash:
4807 drive_add(optarg, PFLASH_ALIAS);
4809 case QEMU_OPTION_snapshot:
4812 case QEMU_OPTION_hdachs:
4816 cyls = strtol(p, (char **)&p, 0);
4817 if (cyls < 1 || cyls > 16383)
4822 heads = strtol(p, (char **)&p, 0);
4823 if (heads < 1 || heads > 16)
4828 secs = strtol(p, (char **)&p, 0);
4829 if (secs < 1 || secs > 63)
4833 if (!strcmp(p, "none"))
4834 translation = BIOS_ATA_TRANSLATION_NONE;
4835 else if (!strcmp(p, "lba"))
4836 translation = BIOS_ATA_TRANSLATION_LBA;
4837 else if (!strcmp(p, "auto"))
4838 translation = BIOS_ATA_TRANSLATION_AUTO;
4841 } else if (*p != '\0') {
4843 fprintf(stderr, "qemu: invalid physical CHS format\n");
4846 if (hda_index != -1)
4847 snprintf(drives_opt[hda_index].opt,
4848 sizeof(drives_opt[hda_index].opt),
4849 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4850 0, cyls, heads, secs,
4851 translation == BIOS_ATA_TRANSLATION_LBA ?
4853 translation == BIOS_ATA_TRANSLATION_NONE ?
4854 ",trans=none" : "");
4857 case QEMU_OPTION_nographic:
4860 #ifdef CONFIG_CURSES
4861 case QEMU_OPTION_curses:
4865 case QEMU_OPTION_portrait:
4868 case QEMU_OPTION_kernel:
4869 kernel_filename = optarg;
4871 case QEMU_OPTION_append:
4872 kernel_cmdline = optarg;
4874 case QEMU_OPTION_cdrom:
4875 drive_add(optarg, CDROM_ALIAS);
4877 case QEMU_OPTION_boot:
4878 boot_devices = optarg;
4879 /* We just do some generic consistency checks */
4881 /* Could easily be extended to 64 devices if needed */
4884 boot_devices_bitmap = 0;
4885 for (p = boot_devices; *p != '\0'; p++) {
4886 /* Allowed boot devices are:
4887 * a b : floppy disk drives
4888 * c ... f : IDE disk drives
4889 * g ... m : machine implementation dependant drives
4890 * n ... p : network devices
4891 * It's up to each machine implementation to check
4892 * if the given boot devices match the actual hardware
4893 * implementation and firmware features.
4895 if (*p < 'a' || *p > 'q') {
4896 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4899 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4901 "Boot device '%c' was given twice\n",*p);
4904 boot_devices_bitmap |= 1 << (*p - 'a');
4908 case QEMU_OPTION_fda:
4909 case QEMU_OPTION_fdb:
4910 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4913 case QEMU_OPTION_no_fd_bootchk:
4917 case QEMU_OPTION_net:
4918 if (nb_net_clients >= MAX_NET_CLIENTS) {
4919 fprintf(stderr, "qemu: too many network clients\n");
4922 net_clients[nb_net_clients] = optarg;
4926 case QEMU_OPTION_tftp:
4927 tftp_prefix = optarg;
4929 case QEMU_OPTION_bootp:
4930 bootp_filename = optarg;
4933 case QEMU_OPTION_smb:
4934 net_slirp_smb(optarg);
4937 case QEMU_OPTION_redir:
4938 net_slirp_redir(optarg);
4941 case QEMU_OPTION_bt:
4942 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4943 fprintf(stderr, "qemu: too many bluetooth options\n");
4946 bt_opts[nb_bt_opts++] = optarg;
4949 case QEMU_OPTION_audio_help:
4953 case QEMU_OPTION_soundhw:
4954 select_soundhw (optarg);
4960 case QEMU_OPTION_m: {
4964 value = strtoul(optarg, &ptr, 10);
4966 case 0: case 'M': case 'm':
4973 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4977 /* On 32-bit hosts, QEMU is limited by virtual address space */
4978 if (value > (2047 << 20)
4980 && HOST_LONG_BITS == 32
4983 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4986 if (value != (uint64_t)(ram_addr_t)value) {
4987 fprintf(stderr, "qemu: ram size too large\n");
4996 const CPULogItem *item;
4998 mask = cpu_str_to_log_mask(optarg);
5000 printf("Log items (comma separated):\n");
5001 for(item = cpu_log_items; item->mask != 0; item++) {
5002 printf("%-10s %s\n", item->name, item->help);
5009 #ifdef CONFIG_GDBSTUB
5014 gdbstub_port = optarg;
5020 case QEMU_OPTION_bios:
5027 keyboard_layout = optarg;
5029 case QEMU_OPTION_localtime:
5032 case QEMU_OPTION_vga:
5033 select_vgahw (optarg);
5040 w = strtol(p, (char **)&p, 10);
5043 fprintf(stderr, "qemu: invalid resolution or depth\n");
5049 h = strtol(p, (char **)&p, 10);
5054 depth = strtol(p, (char **)&p, 10);
5055 if (depth != 8 && depth != 15 && depth != 16 &&
5056 depth != 24 && depth != 32)
5058 } else if (*p == '\0') {
5059 depth = graphic_depth;
5066 graphic_depth = depth;
5069 case QEMU_OPTION_echr:
5072 term_escape_char = strtol(optarg, &r, 0);
5074 printf("Bad argument to echr\n");
5077 case QEMU_OPTION_monitor:
5078 monitor_device = optarg;
5080 case QEMU_OPTION_serial:
5081 if (serial_device_index >= MAX_SERIAL_PORTS) {
5082 fprintf(stderr, "qemu: too many serial ports\n");
5085 serial_devices[serial_device_index] = optarg;
5086 serial_device_index++;
5088 case QEMU_OPTION_virtiocon:
5089 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5090 fprintf(stderr, "qemu: too many virtio consoles\n");
5093 virtio_consoles[virtio_console_index] = optarg;
5094 virtio_console_index++;
5096 case QEMU_OPTION_parallel:
5097 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5098 fprintf(stderr, "qemu: too many parallel ports\n");
5101 parallel_devices[parallel_device_index] = optarg;
5102 parallel_device_index++;
5104 case QEMU_OPTION_loadvm:
5107 case QEMU_OPTION_full_screen:
5111 case QEMU_OPTION_no_frame:
5114 case QEMU_OPTION_alt_grab:
5117 case QEMU_OPTION_no_quit:
5120 case QEMU_OPTION_sdl:
5124 case QEMU_OPTION_pidfile:
5128 case QEMU_OPTION_win2k_hack:
5129 win2k_install_hack = 1;
5131 case QEMU_OPTION_rtc_td_hack:
5134 case QEMU_OPTION_acpitable:
5135 if(acpi_table_add(optarg) < 0) {
5136 fprintf(stderr, "Wrong acpi table provided\n");
5142 case QEMU_OPTION_no_kqemu:
5145 case QEMU_OPTION_kernel_kqemu:
5150 case QEMU_OPTION_enable_kvm:
5157 case QEMU_OPTION_usb:
5160 case QEMU_OPTION_usbdevice:
5162 if (usb_devices_index >= MAX_USB_CMDLINE) {
5163 fprintf(stderr, "Too many USB devices\n");
5166 usb_devices[usb_devices_index] = optarg;
5167 usb_devices_index++;
5169 case QEMU_OPTION_smp:
5170 smp_cpus = atoi(optarg);
5172 fprintf(stderr, "Invalid number of CPUs\n");
5176 case QEMU_OPTION_vnc:
5177 vnc_display = optarg;
5179 case QEMU_OPTION_no_acpi:
5182 case QEMU_OPTION_no_hpet:
5185 case QEMU_OPTION_no_reboot:
5188 case QEMU_OPTION_no_shutdown:
5191 case QEMU_OPTION_show_cursor:
5194 case QEMU_OPTION_uuid:
5195 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5196 fprintf(stderr, "Fail to parse UUID string."
5197 " Wrong format.\n");
5201 case QEMU_OPTION_daemonize:
5204 case QEMU_OPTION_option_rom:
5205 if (nb_option_roms >= MAX_OPTION_ROMS) {
5206 fprintf(stderr, "Too many option ROMs\n");
5209 option_rom[nb_option_roms] = optarg;
5212 case QEMU_OPTION_semihosting:
5213 semihosting_enabled = 1;
5215 case QEMU_OPTION_name:
5218 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5219 case QEMU_OPTION_prom_env:
5220 if (nb_prom_envs >= MAX_PROM_ENVS) {
5221 fprintf(stderr, "Too many prom variables\n");
5224 prom_envs[nb_prom_envs] = optarg;
5229 case QEMU_OPTION_old_param:
5233 case QEMU_OPTION_clock:
5234 configure_alarms(optarg);
5236 case QEMU_OPTION_startdate:
5239 time_t rtc_start_date;
5240 if (!strcmp(optarg, "now")) {
5241 rtc_date_offset = -1;
5243 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5251 } else if (sscanf(optarg, "%d-%d-%d",
5254 &tm.tm_mday) == 3) {
5263 rtc_start_date = mktimegm(&tm);
5264 if (rtc_start_date == -1) {
5266 fprintf(stderr, "Invalid date format. Valid format are:\n"
5267 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5270 rtc_date_offset = time(NULL) - rtc_start_date;
5274 case QEMU_OPTION_tb_size:
5275 tb_size = strtol(optarg, NULL, 0);
5279 case QEMU_OPTION_icount:
5281 if (strcmp(optarg, "auto") == 0) {
5282 icount_time_shift = -1;
5284 icount_time_shift = strtol(optarg, NULL, 0);
5287 case QEMU_OPTION_incoming:
5294 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5295 if (kvm_allowed && kqemu_allowed) {
5297 "You can not enable both KVM and kqemu at the same time\n");
5302 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5303 if (smp_cpus > machine->max_cpus) {
5304 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5305 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5311 if (serial_device_index == 0)
5312 serial_devices[0] = "stdio";
5313 if (parallel_device_index == 0)
5314 parallel_devices[0] = "null";
5315 if (strncmp(monitor_device, "vc", 2) == 0)
5316 monitor_device = "stdio";
5323 if (pipe(fds) == -1)
5334 len = read(fds[0], &status, 1);
5335 if (len == -1 && (errno == EINTR))
5340 else if (status == 1) {
5341 fprintf(stderr, "Could not acquire pidfile\n");
5358 signal(SIGTSTP, SIG_IGN);
5359 signal(SIGTTOU, SIG_IGN);
5360 signal(SIGTTIN, SIG_IGN);
5364 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5367 write(fds[1], &status, 1);
5369 fprintf(stderr, "Could not acquire pid file\n");
5377 linux_boot = (kernel_filename != NULL);
5378 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5380 if (!linux_boot && net_boot == 0 &&
5381 !machine->nodisk_ok && nb_drives_opt == 0)
5384 if (!linux_boot && *kernel_cmdline != '\0') {
5385 fprintf(stderr, "-append only allowed with -kernel option\n");
5389 if (!linux_boot && initrd_filename != NULL) {
5390 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5394 /* boot to floppy or the default cd if no hard disk defined yet */
5395 if (!boot_devices[0]) {
5396 boot_devices = "cad";
5398 setvbuf(stdout, NULL, _IOLBF, 0);
5401 if (init_timer_alarm() < 0) {
5402 fprintf(stderr, "could not initialize alarm timer\n");
5405 if (use_icount && icount_time_shift < 0) {
5407 /* 125MIPS seems a reasonable initial guess at the guest speed.
5408 It will be corrected fairly quickly anyway. */
5409 icount_time_shift = 3;
5410 init_icount_adjust();
5417 /* init network clients */
5418 if (nb_net_clients == 0) {
5419 /* if no clients, we use a default config */
5420 net_clients[nb_net_clients++] = "nic";
5422 net_clients[nb_net_clients++] = "user";
5426 for(i = 0;i < nb_net_clients; i++) {
5427 if (net_client_parse(net_clients[i]) < 0)
5433 /* XXX: this should be moved in the PC machine instantiation code */
5434 if (net_boot != 0) {
5436 for (i = 0; i < nb_nics && i < 4; i++) {
5437 const char *model = nd_table[i].model;
5439 if (net_boot & (1 << i)) {
5442 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5443 if (get_image_size(buf) > 0) {
5444 if (nb_option_roms >= MAX_OPTION_ROMS) {
5445 fprintf(stderr, "Too many option ROMs\n");
5448 option_rom[nb_option_roms] = strdup(buf);
5455 fprintf(stderr, "No valid PXE rom found for network device\n");
5461 /* init the bluetooth world */
5462 for (i = 0; i < nb_bt_opts; i++)
5463 if (bt_parse(bt_opts[i]))
5466 /* init the memory */
5467 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5469 if (machine->ram_require & RAMSIZE_FIXED) {
5471 if (ram_size < phys_ram_size) {
5472 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5473 machine->name, (unsigned long long) phys_ram_size);
5477 phys_ram_size = ram_size;
5479 ram_size = phys_ram_size;
5482 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5484 phys_ram_size += ram_size;
5487 phys_ram_base = qemu_vmalloc(phys_ram_size);
5488 if (!phys_ram_base) {
5489 fprintf(stderr, "Could not allocate physical memory\n");
5493 /* init the dynamic translator */
5494 cpu_exec_init_all(tb_size * 1024 * 1024);
5498 /* we always create the cdrom drive, even if no disk is there */
5500 if (nb_drives_opt < MAX_DRIVES)
5501 drive_add(NULL, CDROM_ALIAS);
5503 /* we always create at least one floppy */
5505 if (nb_drives_opt < MAX_DRIVES)
5506 drive_add(NULL, FD_ALIAS, 0);
5508 /* we always create one sd slot, even if no card is in it */
5510 if (nb_drives_opt < MAX_DRIVES)
5511 drive_add(NULL, SD_ALIAS);
5513 /* open the virtual block devices */
5515 for(i = 0; i < nb_drives_opt; i++)
5516 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5519 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5520 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5523 /* must be after terminal init, SDL library changes signal handlers */
5527 /* Maintain compatibility with multiple stdio monitors */
5528 if (!strcmp(monitor_device,"stdio")) {
5529 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5530 const char *devname = serial_devices[i];
5531 if (devname && !strcmp(devname,"mon:stdio")) {
5532 monitor_device = NULL;
5534 } else if (devname && !strcmp(devname,"stdio")) {
5535 monitor_device = NULL;
5536 serial_devices[i] = "mon:stdio";
5542 if (kvm_enabled()) {
5545 ret = kvm_init(smp_cpus);
5547 fprintf(stderr, "failed to initialize KVM\n");
5552 if (monitor_device) {
5553 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5555 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5560 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5561 const char *devname = serial_devices[i];
5562 if (devname && strcmp(devname, "none")) {
5564 snprintf(label, sizeof(label), "serial%d", i);
5565 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5566 if (!serial_hds[i]) {
5567 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5574 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5575 const char *devname = parallel_devices[i];
5576 if (devname && strcmp(devname, "none")) {
5578 snprintf(label, sizeof(label), "parallel%d", i);
5579 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5580 if (!parallel_hds[i]) {
5581 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5588 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5589 const char *devname = virtio_consoles[i];
5590 if (devname && strcmp(devname, "none")) {
5592 snprintf(label, sizeof(label), "virtcon%d", i);
5593 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5594 if (!virtcon_hds[i]) {
5595 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5602 machine->init(ram_size, vga_ram_size, boot_devices,
5603 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5605 current_machine = machine;
5607 /* Set KVM's vcpu state to qemu's initial CPUState. */
5608 if (kvm_enabled()) {
5611 ret = kvm_sync_vcpus();
5613 fprintf(stderr, "failed to initialize vcpus\n");
5618 /* init USB devices */
5620 for(i = 0; i < usb_devices_index; i++) {
5621 if (usb_device_add(usb_devices[i]) < 0) {
5622 fprintf(stderr, "Warning: could not add USB device %s\n",
5629 dumb_display_init();
5630 /* just use the first displaystate for the moment */
5635 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5639 #if defined(CONFIG_CURSES)
5641 /* At the moment curses cannot be used with other displays */
5642 curses_display_init(ds, full_screen);
5646 if (vnc_display != NULL) {
5647 vnc_display_init(ds);
5648 if (vnc_display_open(ds, vnc_display) < 0)
5651 #if defined(CONFIG_SDL)
5652 if (sdl || !vnc_display)
5653 sdl_display_init(ds, full_screen, no_frame);
5654 #elif defined(CONFIG_COCOA)
5655 if (sdl || !vnc_display)
5656 cocoa_display_init(ds, full_screen);
5662 dcl = ds->listeners;
5663 while (dcl != NULL) {
5664 if (dcl->dpy_refresh != NULL) {
5665 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5666 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5671 if (nographic || (vnc_display && !sdl)) {
5672 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5673 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5676 text_consoles_set_display(display_state);
5678 if (monitor_device && monitor_hd)
5679 monitor_init(monitor_hd, !nographic);
5681 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5682 const char *devname = serial_devices[i];
5683 if (devname && strcmp(devname, "none")) {
5685 snprintf(label, sizeof(label), "serial%d", i);
5686 if (strstart(devname, "vc", 0))
5687 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5691 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5692 const char *devname = parallel_devices[i];
5693 if (devname && strcmp(devname, "none")) {
5695 snprintf(label, sizeof(label), "parallel%d", i);
5696 if (strstart(devname, "vc", 0))
5697 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5701 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5702 const char *devname = virtio_consoles[i];
5703 if (virtcon_hds[i] && devname) {
5705 snprintf(label, sizeof(label), "virtcon%d", i);
5706 if (strstart(devname, "vc", 0))
5707 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5711 #ifdef CONFIG_GDBSTUB
5713 /* XXX: use standard host:port notation and modify options
5715 if (gdbserver_start(gdbstub_port) < 0) {
5716 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5727 autostart = 0; /* fixme how to deal with -daemonize */
5728 qemu_start_incoming_migration(incoming);
5732 /* XXX: simplify init */
5745 len = write(fds[1], &status, 1);
5746 if (len == -1 && (errno == EINTR))
5753 TFR(fd = open("/dev/null", O_RDWR));